diff --git a/.gitattributes b/.gitattributes index 2dca999e49015c1b1062c88a35e179f92c7931d7..668f65eb46dc7841fa0f90260e74cff03d02edfe 100644 --- a/.gitattributes +++ b/.gitattributes @@ -702,3 +702,4 @@ deepseek/lib/python3.10/site-packages/numpy/lib/tests/__pycache__/test_function_ deepseek/lib/python3.10/site-packages/numpy/core/tests/__pycache__/test_numeric.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text deepseek/lib/python3.10/site-packages/numpy/core/__pycache__/_add_newdocs.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text deepseekvl2/lib/python3.10/site-packages/torch/_inductor/__pycache__/ir.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text +infer_4_33_0/lib/python3.10/site-packages/aiohttp/_websocket/reader_c.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text diff --git a/deepseekvl2/lib/python3.10/site-packages/numpy/distutils/checks/extra_vsx4_mma.c b/deepseekvl2/lib/python3.10/site-packages/numpy/distutils/checks/extra_vsx4_mma.c new file mode 100644 index 0000000000000000000000000000000000000000..a70b2a9f6f95408eb7cfe59c056f114cc363869b --- /dev/null +++ b/deepseekvl2/lib/python3.10/site-packages/numpy/distutils/checks/extra_vsx4_mma.c @@ -0,0 +1,21 @@ +#ifndef __VSX__ + #error "VSX is not supported" +#endif +#include + +typedef __vector float fv4sf_t; +typedef __vector unsigned char vec_t; + +int main(void) +{ + __vector_quad acc0; + float a[4] = {0,1,2,3}; + float b[4] = {0,1,2,3}; + vec_t *va = (vec_t *) a; + vec_t *vb = (vec_t *) b; + __builtin_mma_xvf32ger(&acc0, va[0], vb[0]); + fv4sf_t result[4]; + __builtin_mma_disassemble_acc((void *)result, &acc0); + fv4sf_t c0 = result[0]; + return (int)((float*)&c0)[0]; +} diff --git a/deepseekvl2/lib/python3.10/site-packages/numpy/distutils/fcompiler/__pycache__/__init__.cpython-310.pyc b/deepseekvl2/lib/python3.10/site-packages/numpy/distutils/fcompiler/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..921675dbf11f6523e3b30aaff90e0685337b611f Binary files /dev/null and b/deepseekvl2/lib/python3.10/site-packages/numpy/distutils/fcompiler/__pycache__/__init__.cpython-310.pyc differ diff --git a/deepseekvl2/lib/python3.10/site-packages/numpy/distutils/fcompiler/__pycache__/absoft.cpython-310.pyc b/deepseekvl2/lib/python3.10/site-packages/numpy/distutils/fcompiler/__pycache__/absoft.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bfd244538f5d2ae381f2e75e402c41512faa7f62 Binary files /dev/null and b/deepseekvl2/lib/python3.10/site-packages/numpy/distutils/fcompiler/__pycache__/absoft.cpython-310.pyc differ diff --git a/deepseekvl2/lib/python3.10/site-packages/numpy/distutils/fcompiler/__pycache__/arm.cpython-310.pyc b/deepseekvl2/lib/python3.10/site-packages/numpy/distutils/fcompiler/__pycache__/arm.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7df929f61d0b8ec8489161ef1a335403481afd65 Binary files /dev/null and b/deepseekvl2/lib/python3.10/site-packages/numpy/distutils/fcompiler/__pycache__/arm.cpython-310.pyc differ diff --git a/deepseekvl2/lib/python3.10/site-packages/numpy/distutils/fcompiler/__pycache__/compaq.cpython-310.pyc b/deepseekvl2/lib/python3.10/site-packages/numpy/distutils/fcompiler/__pycache__/compaq.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2edc11a78e28b8f967662111363d78c21035b2b2 Binary files /dev/null and b/deepseekvl2/lib/python3.10/site-packages/numpy/distutils/fcompiler/__pycache__/compaq.cpython-310.pyc differ diff --git a/deepseekvl2/lib/python3.10/site-packages/numpy/distutils/fcompiler/__pycache__/environment.cpython-310.pyc b/deepseekvl2/lib/python3.10/site-packages/numpy/distutils/fcompiler/__pycache__/environment.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1cb0eb81203ce280e62993af5fe240b6701b3fc0 Binary files /dev/null and b/deepseekvl2/lib/python3.10/site-packages/numpy/distutils/fcompiler/__pycache__/environment.cpython-310.pyc differ diff --git a/deepseekvl2/lib/python3.10/site-packages/numpy/distutils/fcompiler/__pycache__/g95.cpython-310.pyc b/deepseekvl2/lib/python3.10/site-packages/numpy/distutils/fcompiler/__pycache__/g95.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d7d9a52823f9dad8a0f59fdbc972211a579ea5fc Binary files /dev/null and b/deepseekvl2/lib/python3.10/site-packages/numpy/distutils/fcompiler/__pycache__/g95.cpython-310.pyc differ diff --git a/deepseekvl2/lib/python3.10/site-packages/numpy/distutils/fcompiler/__pycache__/gnu.cpython-310.pyc b/deepseekvl2/lib/python3.10/site-packages/numpy/distutils/fcompiler/__pycache__/gnu.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a838761c885274b07900e611dc74b9d2f37e6d2f Binary files /dev/null and b/deepseekvl2/lib/python3.10/site-packages/numpy/distutils/fcompiler/__pycache__/gnu.cpython-310.pyc differ diff --git a/deepseekvl2/lib/python3.10/site-packages/numpy/distutils/fcompiler/__pycache__/hpux.cpython-310.pyc b/deepseekvl2/lib/python3.10/site-packages/numpy/distutils/fcompiler/__pycache__/hpux.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3d00afb7cb85a6dfc456f9a1e31b85dd9b8ae97e Binary files /dev/null and b/deepseekvl2/lib/python3.10/site-packages/numpy/distutils/fcompiler/__pycache__/hpux.cpython-310.pyc differ diff --git a/deepseekvl2/lib/python3.10/site-packages/numpy/distutils/fcompiler/__pycache__/ibm.cpython-310.pyc b/deepseekvl2/lib/python3.10/site-packages/numpy/distutils/fcompiler/__pycache__/ibm.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8a4c17ad2a5497191e42451ebfd87c69c4ab93d4 Binary files /dev/null and b/deepseekvl2/lib/python3.10/site-packages/numpy/distutils/fcompiler/__pycache__/ibm.cpython-310.pyc differ diff --git a/deepseekvl2/lib/python3.10/site-packages/numpy/distutils/fcompiler/__pycache__/intel.cpython-310.pyc b/deepseekvl2/lib/python3.10/site-packages/numpy/distutils/fcompiler/__pycache__/intel.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bdb0fff1a9fb8adbab1da34d491d59e28fe7a779 Binary files /dev/null and b/deepseekvl2/lib/python3.10/site-packages/numpy/distutils/fcompiler/__pycache__/intel.cpython-310.pyc differ diff --git a/deepseekvl2/lib/python3.10/site-packages/numpy/distutils/fcompiler/__pycache__/lahey.cpython-310.pyc b/deepseekvl2/lib/python3.10/site-packages/numpy/distutils/fcompiler/__pycache__/lahey.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..90087c9b22c36217a78105393d2f0f01efe95937 Binary files /dev/null and b/deepseekvl2/lib/python3.10/site-packages/numpy/distutils/fcompiler/__pycache__/lahey.cpython-310.pyc differ diff --git a/deepseekvl2/lib/python3.10/site-packages/numpy/distutils/fcompiler/__pycache__/mips.cpython-310.pyc b/deepseekvl2/lib/python3.10/site-packages/numpy/distutils/fcompiler/__pycache__/mips.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..42589aa38b7cc4767ff508bd051b70e1af5ecb3f Binary files /dev/null and b/deepseekvl2/lib/python3.10/site-packages/numpy/distutils/fcompiler/__pycache__/mips.cpython-310.pyc differ diff --git a/deepseekvl2/lib/python3.10/site-packages/numpy/distutils/fcompiler/__pycache__/nag.cpython-310.pyc b/deepseekvl2/lib/python3.10/site-packages/numpy/distutils/fcompiler/__pycache__/nag.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..febb89a43a8a048175bfb928367db4ab3588e112 Binary files /dev/null and b/deepseekvl2/lib/python3.10/site-packages/numpy/distutils/fcompiler/__pycache__/nag.cpython-310.pyc differ diff --git a/deepseekvl2/lib/python3.10/site-packages/numpy/distutils/fcompiler/__pycache__/none.cpython-310.pyc b/deepseekvl2/lib/python3.10/site-packages/numpy/distutils/fcompiler/__pycache__/none.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bc2d12912d9dc1a1f286814c84e7d9d6a7b62b45 Binary files /dev/null and b/deepseekvl2/lib/python3.10/site-packages/numpy/distutils/fcompiler/__pycache__/none.cpython-310.pyc differ diff --git a/deepseekvl2/lib/python3.10/site-packages/numpy/distutils/fcompiler/__pycache__/nv.cpython-310.pyc b/deepseekvl2/lib/python3.10/site-packages/numpy/distutils/fcompiler/__pycache__/nv.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3284191281f3391e6a342ede3d17a7421042029a Binary files /dev/null and b/deepseekvl2/lib/python3.10/site-packages/numpy/distutils/fcompiler/__pycache__/nv.cpython-310.pyc differ diff --git a/deepseekvl2/lib/python3.10/site-packages/numpy/distutils/fcompiler/__pycache__/pathf95.cpython-310.pyc b/deepseekvl2/lib/python3.10/site-packages/numpy/distutils/fcompiler/__pycache__/pathf95.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e2c336ec74fc3938471d1afb655dd574f2693d9b Binary files /dev/null and b/deepseekvl2/lib/python3.10/site-packages/numpy/distutils/fcompiler/__pycache__/pathf95.cpython-310.pyc differ diff --git a/deepseekvl2/lib/python3.10/site-packages/numpy/distutils/fcompiler/__pycache__/pg.cpython-310.pyc b/deepseekvl2/lib/python3.10/site-packages/numpy/distutils/fcompiler/__pycache__/pg.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..43c212e56b6d3a297a91865ec6dec493df608b21 Binary files /dev/null and b/deepseekvl2/lib/python3.10/site-packages/numpy/distutils/fcompiler/__pycache__/pg.cpython-310.pyc differ diff --git a/deepseekvl2/lib/python3.10/site-packages/numpy/distutils/fcompiler/__pycache__/sun.cpython-310.pyc b/deepseekvl2/lib/python3.10/site-packages/numpy/distutils/fcompiler/__pycache__/sun.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7fbb89ea94d348598815784bed49b9ffc7556fde Binary files /dev/null and b/deepseekvl2/lib/python3.10/site-packages/numpy/distutils/fcompiler/__pycache__/sun.cpython-310.pyc differ diff --git a/deepseekvl2/lib/python3.10/site-packages/numpy/distutils/fcompiler/__pycache__/vast.cpython-310.pyc b/deepseekvl2/lib/python3.10/site-packages/numpy/distutils/fcompiler/__pycache__/vast.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..801442677312dd0127ca92ad67693fd63201d6c2 Binary files /dev/null and b/deepseekvl2/lib/python3.10/site-packages/numpy/distutils/fcompiler/__pycache__/vast.cpython-310.pyc differ diff --git a/deepseekvl2/lib/python3.10/site-packages/psutil/__pycache__/__init__.cpython-310.pyc b/deepseekvl2/lib/python3.10/site-packages/psutil/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..018c96287ef4beae12cf737d0144aa58d3867317 Binary files /dev/null and b/deepseekvl2/lib/python3.10/site-packages/psutil/__pycache__/__init__.cpython-310.pyc differ diff --git a/deepseekvl2/lib/python3.10/site-packages/psutil/__pycache__/_pssunos.cpython-310.pyc b/deepseekvl2/lib/python3.10/site-packages/psutil/__pycache__/_pssunos.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9777286a33710fabbe9b3c3dc3e5ad8ddbfee2cf Binary files /dev/null and b/deepseekvl2/lib/python3.10/site-packages/psutil/__pycache__/_pssunos.cpython-310.pyc differ diff --git a/deepseekvl2/lib/python3.10/site-packages/psutil/__pycache__/_pswindows.cpython-310.pyc b/deepseekvl2/lib/python3.10/site-packages/psutil/__pycache__/_pswindows.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..202decc0d0d27960c56d92ac1116dfd26938cb0d Binary files /dev/null and b/deepseekvl2/lib/python3.10/site-packages/psutil/__pycache__/_pswindows.cpython-310.pyc differ diff --git a/deepseekvl2/lib/python3.10/site-packages/torchvision-0.15.2+cu118.dist-info/INSTALLER b/deepseekvl2/lib/python3.10/site-packages/torchvision-0.15.2+cu118.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/deepseekvl2/lib/python3.10/site-packages/torchvision-0.15.2+cu118.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/deepseekvl2/lib/python3.10/site-packages/torchvision-0.15.2+cu118.dist-info/LICENSE b/deepseekvl2/lib/python3.10/site-packages/torchvision-0.15.2+cu118.dist-info/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..1edcf92c3317b90fedd187e2eaad101bd1c1efc5 --- /dev/null +++ b/deepseekvl2/lib/python3.10/site-packages/torchvision-0.15.2+cu118.dist-info/LICENSE @@ -0,0 +1,29 @@ +BSD 3-Clause License + +Copyright (c) Soumith Chintala 2016, +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +* Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/deepseekvl2/lib/python3.10/site-packages/torchvision-0.15.2+cu118.dist-info/METADATA b/deepseekvl2/lib/python3.10/site-packages/torchvision-0.15.2+cu118.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..38a3b7f2a5a8d67c7f2bc59f265d3d338f758566 --- /dev/null +++ b/deepseekvl2/lib/python3.10/site-packages/torchvision-0.15.2+cu118.dist-info/METADATA @@ -0,0 +1,233 @@ +Metadata-Version: 2.1 +Name: torchvision +Version: 0.15.2+cu118 +Summary: image and video datasets and models for torch deep learning +Home-page: https://github.com/pytorch/vision +Author: PyTorch Core Team +Author-email: soumith@pytorch.org +License: BSD +Requires-Python: >=3.8 +License-File: LICENSE +Requires-Dist: numpy +Requires-Dist: requests +Requires-Dist: torch (==2.0.1) +Requires-Dist: pillow (!=8.3.*,>=5.3.0) +Provides-Extra: scipy +Requires-Dist: scipy ; extra == 'scipy' + +torchvision +=========== + +.. image:: https://pepy.tech/badge/torchvision + :target: https://pepy.tech/project/torchvision + +.. image:: https://img.shields.io/badge/dynamic/json.svg?label=docs&url=https%3A%2F%2Fpypi.org%2Fpypi%2Ftorchvision%2Fjson&query=%24.info.version&colorB=brightgreen&prefix=v + :target: https://pytorch.org/vision/stable/index.html + + +The torchvision package consists of popular datasets, model architectures, and common image transformations for computer vision. + + +Installation +============ + +We recommend Anaconda as Python package management system. Please refer to `pytorch.org `_ +for the detail of PyTorch (``torch``) installation. The following is the corresponding ``torchvision`` versions and +supported Python versions. + ++--------------------------+--------------------------+---------------------------------+ +| ``torch`` | ``torchvision`` | ``python`` | ++==========================+==========================+=================================+ +| ``main`` / ``nightly`` | ``main`` / ``nightly`` | ``>=3.8``, ``<=3.10`` | ++--------------------------+--------------------------+---------------------------------+ +| ``1.13.0`` | ``0.14.0`` | ``>=3.7.2``, ``<=3.10`` | ++--------------------------+--------------------------+---------------------------------+ +| ``1.12.0`` | ``0.13.0`` | ``>=3.7``, ``<=3.10`` | ++--------------------------+--------------------------+---------------------------------+ +| ``1.11.0`` | ``0.12.0`` | ``>=3.7``, ``<=3.10`` | ++--------------------------+--------------------------+---------------------------------+ +| ``1.10.2`` | ``0.11.3`` | ``>=3.6``, ``<=3.9`` | ++--------------------------+--------------------------+---------------------------------+ +| ``1.10.1`` | ``0.11.2`` | ``>=3.6``, ``<=3.9`` | ++--------------------------+--------------------------+---------------------------------+ +| ``1.10.0`` | ``0.11.1`` | ``>=3.6``, ``<=3.9`` | ++--------------------------+--------------------------+---------------------------------+ +| ``1.9.1`` | ``0.10.1`` | ``>=3.6``, ``<=3.9`` | ++--------------------------+--------------------------+---------------------------------+ +| ``1.9.0`` | ``0.10.0`` | ``>=3.6``, ``<=3.9`` | ++--------------------------+--------------------------+---------------------------------+ +| ``1.8.2`` | ``0.9.2`` | ``>=3.6``, ``<=3.9`` | ++--------------------------+--------------------------+---------------------------------+ +| ``1.8.1`` | ``0.9.1`` | ``>=3.6``, ``<=3.9`` | ++--------------------------+--------------------------+---------------------------------+ +| ``1.8.0`` | ``0.9.0`` | ``>=3.6``, ``<=3.9`` | ++--------------------------+--------------------------+---------------------------------+ +| ``1.7.1`` | ``0.8.2`` | ``>=3.6``, ``<=3.9`` | ++--------------------------+--------------------------+---------------------------------+ +| ``1.7.0`` | ``0.8.1`` | ``>=3.6``, ``<=3.8`` | ++--------------------------+--------------------------+---------------------------------+ +| ``1.7.0`` | ``0.8.0`` | ``>=3.6``, ``<=3.8`` | ++--------------------------+--------------------------+---------------------------------+ +| ``1.6.0`` | ``0.7.0`` | ``>=3.6``, ``<=3.8`` | ++--------------------------+--------------------------+---------------------------------+ +| ``1.5.1`` | ``0.6.1`` | ``>=3.5``, ``<=3.8`` | ++--------------------------+--------------------------+---------------------------------+ +| ``1.5.0`` | ``0.6.0`` | ``>=3.5``, ``<=3.8`` | ++--------------------------+--------------------------+---------------------------------+ +| ``1.4.0`` | ``0.5.0`` | ``==2.7``, ``>=3.5``, ``<=3.8`` | ++--------------------------+--------------------------+---------------------------------+ +| ``1.3.1`` | ``0.4.2`` | ``==2.7``, ``>=3.5``, ``<=3.7`` | ++--------------------------+--------------------------+---------------------------------+ +| ``1.3.0`` | ``0.4.1`` | ``==2.7``, ``>=3.5``, ``<=3.7`` | ++--------------------------+--------------------------+---------------------------------+ +| ``1.2.0`` | ``0.4.0`` | ``==2.7``, ``>=3.5``, ``<=3.7`` | ++--------------------------+--------------------------+---------------------------------+ +| ``1.1.0`` | ``0.3.0`` | ``==2.7``, ``>=3.5``, ``<=3.7`` | ++--------------------------+--------------------------+---------------------------------+ +| ``<=1.0.1`` | ``0.2.2`` | ``==2.7``, ``>=3.5``, ``<=3.7`` | ++--------------------------+--------------------------+---------------------------------+ + +Anaconda: + +.. code:: bash + + conda install torchvision -c pytorch + +pip: + +.. code:: bash + + pip install torchvision + +From source: + +.. code:: bash + + python setup.py install + # or, for OSX + # MACOSX_DEPLOYMENT_TARGET=10.9 CC=clang CXX=clang++ python setup.py install + + +We don't officially support building from source using ``pip``, but *if* you do, +you'll need to use the ``--no-build-isolation`` flag. +In case building TorchVision from source fails, install the nightly version of PyTorch following +the linked guide on the `contributing page `_ and retry the install. + +By default, GPU support is built if CUDA is found and ``torch.cuda.is_available()`` is true. +It's possible to force building GPU support by setting ``FORCE_CUDA=1`` environment variable, +which is useful when building a docker image. + +Image Backend +============= +Torchvision currently supports the following image backends: + +* `Pillow`_ (default) + +* `Pillow-SIMD`_ - a **much faster** drop-in replacement for Pillow with SIMD. If installed will be used as the default. + +* `accimage`_ - if installed can be activated by calling :code:`torchvision.set_image_backend('accimage')` + +* `libpng`_ - can be installed via conda :code:`conda install libpng` or any of the package managers for debian-based and RHEL-based Linux distributions. + +* `libjpeg`_ - can be installed via conda :code:`conda install jpeg` or any of the package managers for debian-based and RHEL-based Linux distributions. `libjpeg-turbo`_ can be used as well. + +**Notes:** ``libpng`` and ``libjpeg`` must be available at compilation time in order to be available. Make sure that it is available on the standard library locations, +otherwise, add the include and library paths in the environment variables ``TORCHVISION_INCLUDE`` and ``TORCHVISION_LIBRARY``, respectively. + +.. _libpng : http://www.libpng.org/pub/png/libpng.html +.. _Pillow : https://python-pillow.org/ +.. _Pillow-SIMD : https://github.com/uploadcare/pillow-simd +.. _accimage: https://github.com/pytorch/accimage +.. _libjpeg: http://ijg.org/ +.. _libjpeg-turbo: https://libjpeg-turbo.org/ + +Video Backend +============= +Torchvision currently supports the following video backends: + +* `pyav`_ (default) - Pythonic binding for ffmpeg libraries. + +.. _pyav : https://github.com/PyAV-Org/PyAV + +* video_reader - This needs ffmpeg to be installed and torchvision to be built from source. There shouldn't be any conflicting version of ffmpeg installed. Currently, this is only supported on Linux. + +.. code:: bash + + conda install -c conda-forge ffmpeg + python setup.py install + + +Using the models on C++ +======================= +TorchVision provides an example project for how to use the models on C++ using JIT Script. + +Installation From source: + +.. code:: bash + + mkdir build + cd build + # Add -DWITH_CUDA=on support for the CUDA if needed + cmake .. + make + make install + +Once installed, the library can be accessed in cmake (after properly configuring ``CMAKE_PREFIX_PATH``) via the :code:`TorchVision::TorchVision` target: + +.. code:: rest + + find_package(TorchVision REQUIRED) + target_link_libraries(my-target PUBLIC TorchVision::TorchVision) + +The ``TorchVision`` package will also automatically look for the ``Torch`` package and add it as a dependency to ``my-target``, +so make sure that it is also available to cmake via the ``CMAKE_PREFIX_PATH``. + +For an example setup, take a look at ``examples/cpp/hello_world``. + +Python linking is disabled by default when compiling TorchVision with CMake, this allows you to run models without any Python +dependency. In some special cases where TorchVision's operators are used from Python code, you may need to link to Python. This +can be done by passing ``-DUSE_PYTHON=on`` to CMake. + +TorchVision Operators +--------------------- +In order to get the torchvision operators registered with torch (eg. for the JIT), all you need to do is to ensure that you +:code:`#include ` in your project. + +Documentation +============= +You can find the API documentation on the pytorch website: https://pytorch.org/vision/stable/index.html + +Contributing +============ + +See the `CONTRIBUTING `_ file for how to help out. + +Disclaimer on Datasets +====================== + +This is a utility library that downloads and prepares public datasets. We do not host or distribute these datasets, vouch for their quality or fairness, or claim that you have license to use the dataset. It is your responsibility to determine whether you have permission to use the dataset under the dataset's license. + +If you're a dataset owner and wish to update any part of it (description, citation, etc.), or do not want your dataset to be included in this library, please get in touch through a GitHub issue. Thanks for your contribution to the ML community! + +Pre-trained Model License +========================= + +The pre-trained models provided in this library may have their own licenses or terms and conditions derived from the dataset used for training. It is your responsibility to determine whether you have permission to use the models for your use case. + +More specifically, SWAG models are released under the CC-BY-NC 4.0 license. See `SWAG LICENSE `_ for additional details. + +Citing TorchVision +================== + +If you find TorchVision useful in your work, please consider citing the following BibTeX entry: + +.. code:: bibtex + + @software{torchvision2016, + title = {TorchVision: PyTorch's Computer Vision library}, + author = {TorchVision maintainers and contributors}, + year = 2016, + journal = {GitHub repository}, + publisher = {GitHub}, + howpublished = {\url{https://github.com/pytorch/vision}} + } diff --git a/deepseekvl2/lib/python3.10/site-packages/torchvision-0.15.2+cu118.dist-info/WHEEL b/deepseekvl2/lib/python3.10/site-packages/torchvision-0.15.2+cu118.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..3f78a79a0f2d50333e0936e383d5fd80de48c119 --- /dev/null +++ b/deepseekvl2/lib/python3.10/site-packages/torchvision-0.15.2+cu118.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: bdist_wheel (0.37.1) +Root-Is-Purelib: false +Tag: cp310-cp310-linux_x86_64 + diff --git a/infer_4_33_0/lib/python3.10/site-packages/aiohttp/__pycache__/http_websocket.cpython-310.pyc b/infer_4_33_0/lib/python3.10/site-packages/aiohttp/__pycache__/http_websocket.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6fe3209fea0724d386418e9e4221c8fa0d5fa903 Binary files /dev/null and b/infer_4_33_0/lib/python3.10/site-packages/aiohttp/__pycache__/http_websocket.cpython-310.pyc differ diff --git a/infer_4_33_0/lib/python3.10/site-packages/aiohttp/_websocket/.hash/mask.pxd.hash b/infer_4_33_0/lib/python3.10/site-packages/aiohttp/_websocket/.hash/mask.pxd.hash new file mode 100644 index 0000000000000000000000000000000000000000..eadfed3d48b4781b271296d8864672a9b46b73c8 --- /dev/null +++ b/infer_4_33_0/lib/python3.10/site-packages/aiohttp/_websocket/.hash/mask.pxd.hash @@ -0,0 +1 @@ +b01999d409b29bd916e067bc963d5f2d9ee63cfc9ae0bccb769910131417bf93 /home/runner/work/aiohttp/aiohttp/aiohttp/_websocket/mask.pxd diff --git a/infer_4_33_0/lib/python3.10/site-packages/aiohttp/_websocket/__init__.py b/infer_4_33_0/lib/python3.10/site-packages/aiohttp/_websocket/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..836257cc47aba3e74863c7de0e098d0835bcee1f --- /dev/null +++ b/infer_4_33_0/lib/python3.10/site-packages/aiohttp/_websocket/__init__.py @@ -0,0 +1 @@ +"""WebSocket protocol versions 13 and 8.""" diff --git a/infer_4_33_0/lib/python3.10/site-packages/aiohttp/_websocket/helpers.py b/infer_4_33_0/lib/python3.10/site-packages/aiohttp/_websocket/helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..0bb58df9228603fc1eb79a7a2cac8301217a36a1 --- /dev/null +++ b/infer_4_33_0/lib/python3.10/site-packages/aiohttp/_websocket/helpers.py @@ -0,0 +1,147 @@ +"""Helpers for WebSocket protocol versions 13 and 8.""" + +import functools +import re +from struct import Struct +from typing import TYPE_CHECKING, Final, List, Optional, Pattern, Tuple + +from ..helpers import NO_EXTENSIONS +from .models import WSHandshakeError + +UNPACK_LEN3 = Struct("!Q").unpack_from +UNPACK_CLOSE_CODE = Struct("!H").unpack +PACK_LEN1 = Struct("!BB").pack +PACK_LEN2 = Struct("!BBH").pack +PACK_LEN3 = Struct("!BBQ").pack +PACK_CLOSE_CODE = Struct("!H").pack +PACK_RANDBITS = Struct("!L").pack +MSG_SIZE: Final[int] = 2**14 +MASK_LEN: Final[int] = 4 + +WS_KEY: Final[bytes] = b"258EAFA5-E914-47DA-95CA-C5AB0DC85B11" + + +# Used by _websocket_mask_python +@functools.lru_cache +def _xor_table() -> List[bytes]: + return [bytes(a ^ b for a in range(256)) for b in range(256)] + + +def _websocket_mask_python(mask: bytes, data: bytearray) -> None: + """Websocket masking function. + + `mask` is a `bytes` object of length 4; `data` is a `bytearray` + object of any length. The contents of `data` are masked with `mask`, + as specified in section 5.3 of RFC 6455. + + Note that this function mutates the `data` argument. + + This pure-python implementation may be replaced by an optimized + version when available. + + """ + assert isinstance(data, bytearray), data + assert len(mask) == 4, mask + + if data: + _XOR_TABLE = _xor_table() + a, b, c, d = (_XOR_TABLE[n] for n in mask) + data[::4] = data[::4].translate(a) + data[1::4] = data[1::4].translate(b) + data[2::4] = data[2::4].translate(c) + data[3::4] = data[3::4].translate(d) + + +if TYPE_CHECKING or NO_EXTENSIONS: # pragma: no cover + websocket_mask = _websocket_mask_python +else: + try: + from .mask import _websocket_mask_cython # type: ignore[import-not-found] + + websocket_mask = _websocket_mask_cython + except ImportError: # pragma: no cover + websocket_mask = _websocket_mask_python + + +_WS_EXT_RE: Final[Pattern[str]] = re.compile( + r"^(?:;\s*(?:" + r"(server_no_context_takeover)|" + r"(client_no_context_takeover)|" + r"(server_max_window_bits(?:=(\d+))?)|" + r"(client_max_window_bits(?:=(\d+))?)))*$" +) + +_WS_EXT_RE_SPLIT: Final[Pattern[str]] = re.compile(r"permessage-deflate([^,]+)?") + + +def ws_ext_parse(extstr: Optional[str], isserver: bool = False) -> Tuple[int, bool]: + if not extstr: + return 0, False + + compress = 0 + notakeover = False + for ext in _WS_EXT_RE_SPLIT.finditer(extstr): + defext = ext.group(1) + # Return compress = 15 when get `permessage-deflate` + if not defext: + compress = 15 + break + match = _WS_EXT_RE.match(defext) + if match: + compress = 15 + if isserver: + # Server never fail to detect compress handshake. + # Server does not need to send max wbit to client + if match.group(4): + compress = int(match.group(4)) + # Group3 must match if group4 matches + # Compress wbit 8 does not support in zlib + # If compress level not support, + # CONTINUE to next extension + if compress > 15 or compress < 9: + compress = 0 + continue + if match.group(1): + notakeover = True + # Ignore regex group 5 & 6 for client_max_window_bits + break + else: + if match.group(6): + compress = int(match.group(6)) + # Group5 must match if group6 matches + # Compress wbit 8 does not support in zlib + # If compress level not support, + # FAIL the parse progress + if compress > 15 or compress < 9: + raise WSHandshakeError("Invalid window size") + if match.group(2): + notakeover = True + # Ignore regex group 5 & 6 for client_max_window_bits + break + # Return Fail if client side and not match + elif not isserver: + raise WSHandshakeError("Extension for deflate not supported" + ext.group(1)) + + return compress, notakeover + + +def ws_ext_gen( + compress: int = 15, isserver: bool = False, server_notakeover: bool = False +) -> str: + # client_notakeover=False not used for server + # compress wbit 8 does not support in zlib + if compress < 9 or compress > 15: + raise ValueError( + "Compress wbits must between 9 and 15, zlib does not support wbits=8" + ) + enabledext = ["permessage-deflate"] + if not isserver: + enabledext.append("client_max_window_bits") + + if compress < 15: + enabledext.append("server_max_window_bits=" + str(compress)) + if server_notakeover: + enabledext.append("server_no_context_takeover") + # if client_notakeover: + # enabledext.append('client_no_context_takeover') + return "; ".join(enabledext) diff --git a/infer_4_33_0/lib/python3.10/site-packages/aiohttp/_websocket/mask.pyx b/infer_4_33_0/lib/python3.10/site-packages/aiohttp/_websocket/mask.pyx new file mode 100644 index 0000000000000000000000000000000000000000..2d956c8899644d4c6bce042b928be1f23e51293a --- /dev/null +++ b/infer_4_33_0/lib/python3.10/site-packages/aiohttp/_websocket/mask.pyx @@ -0,0 +1,48 @@ +from cpython cimport PyBytes_AsString + + +#from cpython cimport PyByteArray_AsString # cython still not exports that +cdef extern from "Python.h": + char* PyByteArray_AsString(bytearray ba) except NULL + +from libc.stdint cimport uint32_t, uint64_t, uintmax_t + + +cpdef void _websocket_mask_cython(bytes mask, bytearray data): + """Note, this function mutates its `data` argument + """ + cdef: + Py_ssize_t data_len, i + # bit operations on signed integers are implementation-specific + unsigned char * in_buf + const unsigned char * mask_buf + uint32_t uint32_msk + uint64_t uint64_msk + + assert len(mask) == 4 + + data_len = len(data) + in_buf = PyByteArray_AsString(data) + mask_buf = PyBytes_AsString(mask) + uint32_msk = (mask_buf)[0] + + # TODO: align in_data ptr to achieve even faster speeds + # does it need in python ?! malloc() always aligns to sizeof(long) bytes + + if sizeof(size_t) >= 8: + uint64_msk = uint32_msk + uint64_msk = (uint64_msk << 32) | uint32_msk + + while data_len >= 8: + (in_buf)[0] ^= uint64_msk + in_buf += 8 + data_len -= 8 + + + while data_len >= 4: + (in_buf)[0] ^= uint32_msk + in_buf += 4 + data_len -= 4 + + for i in range(0, data_len): + in_buf[i] ^= mask_buf[i] diff --git a/infer_4_33_0/lib/python3.10/site-packages/aiohttp/_websocket/models.py b/infer_4_33_0/lib/python3.10/site-packages/aiohttp/_websocket/models.py new file mode 100644 index 0000000000000000000000000000000000000000..7e89b9652957e8f4e73916e18048368e8d75911e --- /dev/null +++ b/infer_4_33_0/lib/python3.10/site-packages/aiohttp/_websocket/models.py @@ -0,0 +1,84 @@ +"""Models for WebSocket protocol versions 13 and 8.""" + +import json +from enum import IntEnum +from typing import Any, Callable, Final, NamedTuple, Optional, cast + +WS_DEFLATE_TRAILING: Final[bytes] = bytes([0x00, 0x00, 0xFF, 0xFF]) + + +class WSCloseCode(IntEnum): + OK = 1000 + GOING_AWAY = 1001 + PROTOCOL_ERROR = 1002 + UNSUPPORTED_DATA = 1003 + ABNORMAL_CLOSURE = 1006 + INVALID_TEXT = 1007 + POLICY_VIOLATION = 1008 + MESSAGE_TOO_BIG = 1009 + MANDATORY_EXTENSION = 1010 + INTERNAL_ERROR = 1011 + SERVICE_RESTART = 1012 + TRY_AGAIN_LATER = 1013 + BAD_GATEWAY = 1014 + + +class WSMsgType(IntEnum): + # websocket spec types + CONTINUATION = 0x0 + TEXT = 0x1 + BINARY = 0x2 + PING = 0x9 + PONG = 0xA + CLOSE = 0x8 + + # aiohttp specific types + CLOSING = 0x100 + CLOSED = 0x101 + ERROR = 0x102 + + text = TEXT + binary = BINARY + ping = PING + pong = PONG + close = CLOSE + closing = CLOSING + closed = CLOSED + error = ERROR + + +class WSMessage(NamedTuple): + type: WSMsgType + # To type correctly, this would need some kind of tagged union for each type. + data: Any + extra: Optional[str] + + def json(self, *, loads: Callable[[Any], Any] = json.loads) -> Any: + """Return parsed JSON data. + + .. versionadded:: 0.22 + """ + return loads(self.data) + + +# Constructing the tuple directly to avoid the overhead of +# the lambda and arg processing since NamedTuples are constructed +# with a run time built lambda +# https://github.com/python/cpython/blob/d83fcf8371f2f33c7797bc8f5423a8bca8c46e5c/Lib/collections/__init__.py#L441 +WS_CLOSED_MESSAGE = tuple.__new__(WSMessage, (WSMsgType.CLOSED, None, None)) +WS_CLOSING_MESSAGE = tuple.__new__(WSMessage, (WSMsgType.CLOSING, None, None)) + + +class WebSocketError(Exception): + """WebSocket protocol parser error.""" + + def __init__(self, code: int, message: str) -> None: + self.code = code + super().__init__(code, message) + + def __str__(self) -> str: + return cast(str, self.args[1]) + + +class WSHandshakeError(Exception): + """WebSocket protocol handshake error.""" diff --git a/infer_4_33_0/lib/python3.10/site-packages/aiohttp/_websocket/reader.py b/infer_4_33_0/lib/python3.10/site-packages/aiohttp/_websocket/reader.py new file mode 100644 index 0000000000000000000000000000000000000000..23f32265cfccbdc8c8fe2f1600accbfb6f816efa --- /dev/null +++ b/infer_4_33_0/lib/python3.10/site-packages/aiohttp/_websocket/reader.py @@ -0,0 +1,31 @@ +"""Reader for WebSocket protocol versions 13 and 8.""" + +from typing import TYPE_CHECKING + +from ..helpers import NO_EXTENSIONS + +if TYPE_CHECKING or NO_EXTENSIONS: # pragma: no cover + from .reader_py import ( + WebSocketDataQueue as WebSocketDataQueuePython, + WebSocketReader as WebSocketReaderPython, + ) + + WebSocketReader = WebSocketReaderPython + WebSocketDataQueue = WebSocketDataQueuePython +else: + try: + from .reader_c import ( # type: ignore[import-not-found] + WebSocketDataQueue as WebSocketDataQueueCython, + WebSocketReader as WebSocketReaderCython, + ) + + WebSocketReader = WebSocketReaderCython + WebSocketDataQueue = WebSocketDataQueueCython + except ImportError: # pragma: no cover + from .reader_py import ( + WebSocketDataQueue as WebSocketDataQueuePython, + WebSocketReader as WebSocketReaderPython, + ) + + WebSocketReader = WebSocketReaderPython + WebSocketDataQueue = WebSocketDataQueuePython diff --git a/infer_4_33_0/lib/python3.10/site-packages/aiohttp/_websocket/reader_c.cpython-310-x86_64-linux-gnu.so b/infer_4_33_0/lib/python3.10/site-packages/aiohttp/_websocket/reader_c.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..e5c9ec5f09731719836cd493ceb33f918fbcbd99 --- /dev/null +++ b/infer_4_33_0/lib/python3.10/site-packages/aiohttp/_websocket/reader_c.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1c5ee8930e058192e5010d0bf82618fce110b123c08a7ca5db16bbb7fe1af988 +size 1666456 diff --git a/infer_4_33_0/lib/python3.10/site-packages/aiohttp/_websocket/reader_c.pxd b/infer_4_33_0/lib/python3.10/site-packages/aiohttp/_websocket/reader_c.pxd new file mode 100644 index 0000000000000000000000000000000000000000..461e658e116f66fec6124936e7d45d7a1aa986ae --- /dev/null +++ b/infer_4_33_0/lib/python3.10/site-packages/aiohttp/_websocket/reader_c.pxd @@ -0,0 +1,102 @@ +import cython + +from .mask cimport _websocket_mask_cython as websocket_mask + + +cdef unsigned int READ_HEADER +cdef unsigned int READ_PAYLOAD_LENGTH +cdef unsigned int READ_PAYLOAD_MASK +cdef unsigned int READ_PAYLOAD + +cdef unsigned int OP_CODE_CONTINUATION +cdef unsigned int OP_CODE_TEXT +cdef unsigned int OP_CODE_BINARY +cdef unsigned int OP_CODE_CLOSE +cdef unsigned int OP_CODE_PING +cdef unsigned int OP_CODE_PONG + +cdef object UNPACK_LEN3 +cdef object UNPACK_CLOSE_CODE +cdef object TUPLE_NEW + +cdef object WSMsgType +cdef object WSMessage + +cdef object WS_MSG_TYPE_TEXT +cdef object WS_MSG_TYPE_BINARY + +cdef set ALLOWED_CLOSE_CODES +cdef set MESSAGE_TYPES_WITH_CONTENT + +cdef tuple EMPTY_FRAME +cdef tuple EMPTY_FRAME_ERROR + +cdef class WebSocketDataQueue: + + cdef unsigned int _size + cdef public object _protocol + cdef unsigned int _limit + cdef object _loop + cdef bint _eof + cdef object _waiter + cdef object _exception + cdef public object _buffer + cdef object _get_buffer + cdef object _put_buffer + + cdef void _release_waiter(self) + + cpdef void feed_data(self, object data, unsigned int size) + + @cython.locals(size="unsigned int") + cdef _read_from_buffer(self) + +cdef class WebSocketReader: + + cdef WebSocketDataQueue queue + cdef unsigned int _max_msg_size + + cdef Exception _exc + cdef bytearray _partial + cdef unsigned int _state + + cdef object _opcode + cdef object _frame_fin + cdef object _frame_opcode + cdef object _frame_payload + cdef unsigned long long _frame_payload_len + + cdef bytes _tail + cdef bint _has_mask + cdef bytes _frame_mask + cdef unsigned long long _payload_length + cdef unsigned int _payload_length_flag + cdef object _compressed + cdef object _decompressobj + cdef bint _compress + + cpdef tuple feed_data(self, object data) + + @cython.locals( + is_continuation=bint, + fin=bint, + has_partial=bint, + payload_merged=bytes, + opcode="unsigned int", + ) + cpdef void _feed_data(self, bytes data) + + @cython.locals( + start_pos="unsigned int", + buf_len="unsigned int", + length="unsigned int", + chunk_size="unsigned int", + chunk_len="unsigned int", + buf_length="unsigned int", + first_byte="unsigned char", + second_byte="unsigned char", + end_pos="unsigned int", + has_mask=bint, + fin=bint, + ) + cpdef list parse_frame(self, bytes buf) diff --git a/infer_4_33_0/lib/python3.10/site-packages/aiohttp/_websocket/reader_c.py b/infer_4_33_0/lib/python3.10/site-packages/aiohttp/_websocket/reader_c.py new file mode 100644 index 0000000000000000000000000000000000000000..94d20010890e4ddaf33603f9616102693af61039 --- /dev/null +++ b/infer_4_33_0/lib/python3.10/site-packages/aiohttp/_websocket/reader_c.py @@ -0,0 +1,468 @@ +"""Reader for WebSocket protocol versions 13 and 8.""" + +import asyncio +import builtins +from collections import deque +from typing import Deque, Final, List, Optional, Set, Tuple, Union + +from ..base_protocol import BaseProtocol +from ..compression_utils import ZLibDecompressor +from ..helpers import _EXC_SENTINEL, set_exception +from ..streams import EofStream +from .helpers import UNPACK_CLOSE_CODE, UNPACK_LEN3, websocket_mask +from .models import ( + WS_DEFLATE_TRAILING, + WebSocketError, + WSCloseCode, + WSMessage, + WSMsgType, +) + +ALLOWED_CLOSE_CODES: Final[Set[int]] = {int(i) for i in WSCloseCode} + +# States for the reader, used to parse the WebSocket frame +# integer values are used so they can be cythonized +READ_HEADER = 1 +READ_PAYLOAD_LENGTH = 2 +READ_PAYLOAD_MASK = 3 +READ_PAYLOAD = 4 + +WS_MSG_TYPE_BINARY = WSMsgType.BINARY +WS_MSG_TYPE_TEXT = WSMsgType.TEXT + +# WSMsgType values unpacked so they can by cythonized to ints +OP_CODE_CONTINUATION = WSMsgType.CONTINUATION.value +OP_CODE_TEXT = WSMsgType.TEXT.value +OP_CODE_BINARY = WSMsgType.BINARY.value +OP_CODE_CLOSE = WSMsgType.CLOSE.value +OP_CODE_PING = WSMsgType.PING.value +OP_CODE_PONG = WSMsgType.PONG.value + +EMPTY_FRAME_ERROR = (True, b"") +EMPTY_FRAME = (False, b"") + +TUPLE_NEW = tuple.__new__ + +int_ = int # Prevent Cython from converting to PyInt + + +class WebSocketDataQueue: + """WebSocketDataQueue resumes and pauses an underlying stream. + + It is a destination for WebSocket data. + """ + + def __init__( + self, protocol: BaseProtocol, limit: int, *, loop: asyncio.AbstractEventLoop + ) -> None: + self._size = 0 + self._protocol = protocol + self._limit = limit * 2 + self._loop = loop + self._eof = False + self._waiter: Optional[asyncio.Future[None]] = None + self._exception: Union[BaseException, None] = None + self._buffer: Deque[Tuple[WSMessage, int]] = deque() + self._get_buffer = self._buffer.popleft + self._put_buffer = self._buffer.append + + def is_eof(self) -> bool: + return self._eof + + def exception(self) -> Optional[BaseException]: + return self._exception + + def set_exception( + self, + exc: "BaseException", + exc_cause: builtins.BaseException = _EXC_SENTINEL, + ) -> None: + self._eof = True + self._exception = exc + if (waiter := self._waiter) is not None: + self._waiter = None + set_exception(waiter, exc, exc_cause) + + def _release_waiter(self) -> None: + if (waiter := self._waiter) is None: + return + self._waiter = None + if not waiter.done(): + waiter.set_result(None) + + def feed_eof(self) -> None: + self._eof = True + self._release_waiter() + + def feed_data(self, data: "WSMessage", size: "int_") -> None: + self._size += size + self._put_buffer((data, size)) + self._release_waiter() + if self._size > self._limit and not self._protocol._reading_paused: + self._protocol.pause_reading() + + async def read(self) -> WSMessage: + if not self._buffer and not self._eof: + assert not self._waiter + self._waiter = self._loop.create_future() + try: + await self._waiter + except (asyncio.CancelledError, asyncio.TimeoutError): + self._waiter = None + raise + return self._read_from_buffer() + + def _read_from_buffer(self) -> WSMessage: + if self._buffer: + data, size = self._get_buffer() + self._size -= size + if self._size < self._limit and self._protocol._reading_paused: + self._protocol.resume_reading() + return data + if self._exception is not None: + raise self._exception + raise EofStream + + +class WebSocketReader: + def __init__( + self, queue: WebSocketDataQueue, max_msg_size: int, compress: bool = True + ) -> None: + self.queue = queue + self._max_msg_size = max_msg_size + + self._exc: Optional[Exception] = None + self._partial = bytearray() + self._state = READ_HEADER + + self._opcode: Optional[int] = None + self._frame_fin = False + self._frame_opcode: Optional[int] = None + self._frame_payload: Union[bytes, bytearray] = b"" + self._frame_payload_len = 0 + + self._tail: bytes = b"" + self._has_mask = False + self._frame_mask: Optional[bytes] = None + self._payload_length = 0 + self._payload_length_flag = 0 + self._compressed: Optional[bool] = None + self._decompressobj: Optional[ZLibDecompressor] = None + self._compress = compress + + def feed_eof(self) -> None: + self.queue.feed_eof() + + # data can be bytearray on Windows because proactor event loop uses bytearray + # and asyncio types this to Union[bytes, bytearray, memoryview] so we need + # coerce data to bytes if it is not + def feed_data( + self, data: Union[bytes, bytearray, memoryview] + ) -> Tuple[bool, bytes]: + if type(data) is not bytes: + data = bytes(data) + + if self._exc is not None: + return True, data + + try: + self._feed_data(data) + except Exception as exc: + self._exc = exc + set_exception(self.queue, exc) + return EMPTY_FRAME_ERROR + + return EMPTY_FRAME + + def _feed_data(self, data: bytes) -> None: + msg: WSMessage + for frame in self.parse_frame(data): + fin = frame[0] + opcode = frame[1] + payload = frame[2] + compressed = frame[3] + + is_continuation = opcode == OP_CODE_CONTINUATION + if opcode == OP_CODE_TEXT or opcode == OP_CODE_BINARY or is_continuation: + # load text/binary + if not fin: + # got partial frame payload + if not is_continuation: + self._opcode = opcode + self._partial += payload + if self._max_msg_size and len(self._partial) >= self._max_msg_size: + raise WebSocketError( + WSCloseCode.MESSAGE_TOO_BIG, + "Message size {} exceeds limit {}".format( + len(self._partial), self._max_msg_size + ), + ) + continue + + has_partial = bool(self._partial) + if is_continuation: + if self._opcode is None: + raise WebSocketError( + WSCloseCode.PROTOCOL_ERROR, + "Continuation frame for non started message", + ) + opcode = self._opcode + self._opcode = None + # previous frame was non finished + # we should get continuation opcode + elif has_partial: + raise WebSocketError( + WSCloseCode.PROTOCOL_ERROR, + "The opcode in non-fin frame is expected " + "to be zero, got {!r}".format(opcode), + ) + + assembled_payload: Union[bytes, bytearray] + if has_partial: + assembled_payload = self._partial + payload + self._partial.clear() + else: + assembled_payload = payload + + if self._max_msg_size and len(assembled_payload) >= self._max_msg_size: + raise WebSocketError( + WSCloseCode.MESSAGE_TOO_BIG, + "Message size {} exceeds limit {}".format( + len(assembled_payload), self._max_msg_size + ), + ) + + # Decompress process must to be done after all packets + # received. + if compressed: + if not self._decompressobj: + self._decompressobj = ZLibDecompressor( + suppress_deflate_header=True + ) + payload_merged = self._decompressobj.decompress_sync( + assembled_payload + WS_DEFLATE_TRAILING, self._max_msg_size + ) + if self._decompressobj.unconsumed_tail: + left = len(self._decompressobj.unconsumed_tail) + raise WebSocketError( + WSCloseCode.MESSAGE_TOO_BIG, + "Decompressed message size {} exceeds limit {}".format( + self._max_msg_size + left, self._max_msg_size + ), + ) + elif type(assembled_payload) is bytes: + payload_merged = assembled_payload + else: + payload_merged = bytes(assembled_payload) + + if opcode == OP_CODE_TEXT: + try: + text = payload_merged.decode("utf-8") + except UnicodeDecodeError as exc: + raise WebSocketError( + WSCloseCode.INVALID_TEXT, "Invalid UTF-8 text message" + ) from exc + + # XXX: The Text and Binary messages here can be a performance + # bottleneck, so we use tuple.__new__ to improve performance. + # This is not type safe, but many tests should fail in + # test_client_ws_functional.py if this is wrong. + self.queue.feed_data( + TUPLE_NEW(WSMessage, (WS_MSG_TYPE_TEXT, text, "")), + len(payload_merged), + ) + else: + self.queue.feed_data( + TUPLE_NEW(WSMessage, (WS_MSG_TYPE_BINARY, payload_merged, "")), + len(payload_merged), + ) + elif opcode == OP_CODE_CLOSE: + if len(payload) >= 2: + close_code = UNPACK_CLOSE_CODE(payload[:2])[0] + if close_code < 3000 and close_code not in ALLOWED_CLOSE_CODES: + raise WebSocketError( + WSCloseCode.PROTOCOL_ERROR, + f"Invalid close code: {close_code}", + ) + try: + close_message = payload[2:].decode("utf-8") + except UnicodeDecodeError as exc: + raise WebSocketError( + WSCloseCode.INVALID_TEXT, "Invalid UTF-8 text message" + ) from exc + msg = TUPLE_NEW( + WSMessage, (WSMsgType.CLOSE, close_code, close_message) + ) + elif payload: + raise WebSocketError( + WSCloseCode.PROTOCOL_ERROR, + f"Invalid close frame: {fin} {opcode} {payload!r}", + ) + else: + msg = TUPLE_NEW(WSMessage, (WSMsgType.CLOSE, 0, "")) + + self.queue.feed_data(msg, 0) + elif opcode == OP_CODE_PING: + msg = TUPLE_NEW(WSMessage, (WSMsgType.PING, payload, "")) + self.queue.feed_data(msg, len(payload)) + + elif opcode == OP_CODE_PONG: + msg = TUPLE_NEW(WSMessage, (WSMsgType.PONG, payload, "")) + self.queue.feed_data(msg, len(payload)) + + else: + raise WebSocketError( + WSCloseCode.PROTOCOL_ERROR, f"Unexpected opcode={opcode!r}" + ) + + def parse_frame( + self, buf: bytes + ) -> List[Tuple[bool, Optional[int], Union[bytes, bytearray], Optional[bool]]]: + """Return the next frame from the socket.""" + frames: List[ + Tuple[bool, Optional[int], Union[bytes, bytearray], Optional[bool]] + ] = [] + if self._tail: + buf, self._tail = self._tail + buf, b"" + + start_pos: int = 0 + buf_length = len(buf) + + while True: + # read header + if self._state == READ_HEADER: + if buf_length - start_pos < 2: + break + first_byte = buf[start_pos] + second_byte = buf[start_pos + 1] + start_pos += 2 + + fin = (first_byte >> 7) & 1 + rsv1 = (first_byte >> 6) & 1 + rsv2 = (first_byte >> 5) & 1 + rsv3 = (first_byte >> 4) & 1 + opcode = first_byte & 0xF + + # frame-fin = %x0 ; more frames of this message follow + # / %x1 ; final frame of this message + # frame-rsv1 = %x0 ; + # 1 bit, MUST be 0 unless negotiated otherwise + # frame-rsv2 = %x0 ; + # 1 bit, MUST be 0 unless negotiated otherwise + # frame-rsv3 = %x0 ; + # 1 bit, MUST be 0 unless negotiated otherwise + # + # Remove rsv1 from this test for deflate development + if rsv2 or rsv3 or (rsv1 and not self._compress): + raise WebSocketError( + WSCloseCode.PROTOCOL_ERROR, + "Received frame with non-zero reserved bits", + ) + + if opcode > 0x7 and fin == 0: + raise WebSocketError( + WSCloseCode.PROTOCOL_ERROR, + "Received fragmented control frame", + ) + + has_mask = (second_byte >> 7) & 1 + length = second_byte & 0x7F + + # Control frames MUST have a payload + # length of 125 bytes or less + if opcode > 0x7 and length > 125: + raise WebSocketError( + WSCloseCode.PROTOCOL_ERROR, + "Control frame payload cannot be larger than 125 bytes", + ) + + # Set compress status if last package is FIN + # OR set compress status if this is first fragment + # Raise error if not first fragment with rsv1 = 0x1 + if self._frame_fin or self._compressed is None: + self._compressed = True if rsv1 else False + elif rsv1: + raise WebSocketError( + WSCloseCode.PROTOCOL_ERROR, + "Received frame with non-zero reserved bits", + ) + + self._frame_fin = bool(fin) + self._frame_opcode = opcode + self._has_mask = bool(has_mask) + self._payload_length_flag = length + self._state = READ_PAYLOAD_LENGTH + + # read payload length + if self._state == READ_PAYLOAD_LENGTH: + length_flag = self._payload_length_flag + if length_flag == 126: + if buf_length - start_pos < 2: + break + first_byte = buf[start_pos] + second_byte = buf[start_pos + 1] + start_pos += 2 + self._payload_length = first_byte << 8 | second_byte + elif length_flag > 126: + if buf_length - start_pos < 8: + break + data = buf[start_pos : start_pos + 8] + start_pos += 8 + self._payload_length = UNPACK_LEN3(data)[0] + else: + self._payload_length = length_flag + + self._state = READ_PAYLOAD_MASK if self._has_mask else READ_PAYLOAD + + # read payload mask + if self._state == READ_PAYLOAD_MASK: + if buf_length - start_pos < 4: + break + self._frame_mask = buf[start_pos : start_pos + 4] + start_pos += 4 + self._state = READ_PAYLOAD + + if self._state == READ_PAYLOAD: + chunk_len = buf_length - start_pos + if self._payload_length >= chunk_len: + end_pos = buf_length + self._payload_length -= chunk_len + else: + end_pos = start_pos + self._payload_length + self._payload_length = 0 + + if self._frame_payload_len: + if type(self._frame_payload) is not bytearray: + self._frame_payload = bytearray(self._frame_payload) + self._frame_payload += buf[start_pos:end_pos] + else: + # Fast path for the first frame + self._frame_payload = buf[start_pos:end_pos] + + self._frame_payload_len += end_pos - start_pos + start_pos = end_pos + + if self._payload_length != 0: + break + + if self._has_mask: + assert self._frame_mask is not None + if type(self._frame_payload) is not bytearray: + self._frame_payload = bytearray(self._frame_payload) + websocket_mask(self._frame_mask, self._frame_payload) + + frames.append( + ( + self._frame_fin, + self._frame_opcode, + self._frame_payload, + self._compressed, + ) + ) + self._frame_payload = b"" + self._frame_payload_len = 0 + self._state = READ_HEADER + + self._tail = buf[start_pos:] if start_pos < buf_length else b"" + + return frames diff --git a/infer_4_33_0/lib/python3.10/site-packages/aiohttp/_websocket/writer.py b/infer_4_33_0/lib/python3.10/site-packages/aiohttp/_websocket/writer.py new file mode 100644 index 0000000000000000000000000000000000000000..fc2cf32b93490677b9fb9a5d5f20c07c18734b8b --- /dev/null +++ b/infer_4_33_0/lib/python3.10/site-packages/aiohttp/_websocket/writer.py @@ -0,0 +1,177 @@ +"""WebSocket protocol versions 13 and 8.""" + +import asyncio +import random +import zlib +from functools import partial +from typing import Any, Final, Optional, Union + +from ..base_protocol import BaseProtocol +from ..client_exceptions import ClientConnectionResetError +from ..compression_utils import ZLibCompressor +from .helpers import ( + MASK_LEN, + MSG_SIZE, + PACK_CLOSE_CODE, + PACK_LEN1, + PACK_LEN2, + PACK_LEN3, + PACK_RANDBITS, + websocket_mask, +) +from .models import WS_DEFLATE_TRAILING, WSMsgType + +DEFAULT_LIMIT: Final[int] = 2**16 + +# For websockets, keeping latency low is extremely important as implementations +# generally expect to be able to send and receive messages quickly. We use a +# larger chunk size than the default to reduce the number of executor calls +# since the executor is a significant source of latency and overhead when +# the chunks are small. A size of 5KiB was chosen because it is also the +# same value python-zlib-ng choose to use as the threshold to release the GIL. + +WEBSOCKET_MAX_SYNC_CHUNK_SIZE = 5 * 1024 + + +class WebSocketWriter: + """WebSocket writer. + + The writer is responsible for sending messages to the client. It is + created by the protocol when a connection is established. The writer + should avoid implementing any application logic and should only be + concerned with the low-level details of the WebSocket protocol. + """ + + def __init__( + self, + protocol: BaseProtocol, + transport: asyncio.Transport, + *, + use_mask: bool = False, + limit: int = DEFAULT_LIMIT, + random: random.Random = random.Random(), + compress: int = 0, + notakeover: bool = False, + ) -> None: + """Initialize a WebSocket writer.""" + self.protocol = protocol + self.transport = transport + self.use_mask = use_mask + self.get_random_bits = partial(random.getrandbits, 32) + self.compress = compress + self.notakeover = notakeover + self._closing = False + self._limit = limit + self._output_size = 0 + self._compressobj: Any = None # actually compressobj + + async def send_frame( + self, message: bytes, opcode: int, compress: Optional[int] = None + ) -> None: + """Send a frame over the websocket with message as its payload.""" + if self._closing and not (opcode & WSMsgType.CLOSE): + raise ClientConnectionResetError("Cannot write to closing transport") + + # RSV are the reserved bits in the frame header. They are used to + # indicate that the frame is using an extension. + # https://datatracker.ietf.org/doc/html/rfc6455#section-5.2 + rsv = 0 + # Only compress larger packets (disabled) + # Does small packet needs to be compressed? + # if self.compress and opcode < 8 and len(message) > 124: + if (compress or self.compress) and opcode < 8: + # RSV1 (rsv = 0x40) is set for compressed frames + # https://datatracker.ietf.org/doc/html/rfc7692#section-7.2.3.1 + rsv = 0x40 + + if compress: + # Do not set self._compress if compressing is for this frame + compressobj = self._make_compress_obj(compress) + else: # self.compress + if not self._compressobj: + self._compressobj = self._make_compress_obj(self.compress) + compressobj = self._compressobj + + message = ( + await compressobj.compress(message) + + compressobj.flush( + zlib.Z_FULL_FLUSH if self.notakeover else zlib.Z_SYNC_FLUSH + ) + ).removesuffix(WS_DEFLATE_TRAILING) + # Its critical that we do not return control to the event + # loop until we have finished sending all the compressed + # data. Otherwise we could end up mixing compressed frames + # if there are multiple coroutines compressing data. + + msg_length = len(message) + + use_mask = self.use_mask + mask_bit = 0x80 if use_mask else 0 + + # Depending on the message length, the header is assembled differently. + # The first byte is reserved for the opcode and the RSV bits. + first_byte = 0x80 | rsv | opcode + if msg_length < 126: + header = PACK_LEN1(first_byte, msg_length | mask_bit) + header_len = 2 + elif msg_length < 65536: + header = PACK_LEN2(first_byte, 126 | mask_bit, msg_length) + header_len = 4 + else: + header = PACK_LEN3(first_byte, 127 | mask_bit, msg_length) + header_len = 10 + + if self.transport.is_closing(): + raise ClientConnectionResetError("Cannot write to closing transport") + + # https://datatracker.ietf.org/doc/html/rfc6455#section-5.3 + # If we are using a mask, we need to generate it randomly + # and apply it to the message before sending it. A mask is + # a 32-bit value that is applied to the message using a + # bitwise XOR operation. It is used to prevent certain types + # of attacks on the websocket protocol. The mask is only used + # when aiohttp is acting as a client. Servers do not use a mask. + if use_mask: + mask = PACK_RANDBITS(self.get_random_bits()) + message = bytearray(message) + websocket_mask(mask, message) + self.transport.write(header + mask + message) + self._output_size += MASK_LEN + elif msg_length > MSG_SIZE: + self.transport.write(header) + self.transport.write(message) + else: + self.transport.write(header + message) + + self._output_size += header_len + msg_length + + # It is safe to return control to the event loop when using compression + # after this point as we have already sent or buffered all the data. + + # Once we have written output_size up to the limit, we call the + # drain helper which waits for the transport to be ready to accept + # more data. This is a flow control mechanism to prevent the buffer + # from growing too large. The drain helper will return right away + # if the writer is not paused. + if self._output_size > self._limit: + self._output_size = 0 + if self.protocol._paused: + await self.protocol._drain_helper() + + def _make_compress_obj(self, compress: int) -> ZLibCompressor: + return ZLibCompressor( + level=zlib.Z_BEST_SPEED, + wbits=-compress, + max_sync_chunk_size=WEBSOCKET_MAX_SYNC_CHUNK_SIZE, + ) + + async def close(self, code: int = 1000, message: Union[bytes, str] = b"") -> None: + """Close the websocket, sending the specified code and message.""" + if isinstance(message, str): + message = message.encode("utf-8") + try: + await self.send_frame( + PACK_CLOSE_CODE(code) + message, opcode=WSMsgType.CLOSE + ) + finally: + self._closing = True diff --git a/infer_4_33_0/lib/python3.10/site-packages/h5py/tests/data_files/vlen_string_dset.h5 b/infer_4_33_0/lib/python3.10/site-packages/h5py/tests/data_files/vlen_string_dset.h5 new file mode 100644 index 0000000000000000000000000000000000000000..dbf021d4c80f66b6343fead92e5d7a6ea8ab647e --- /dev/null +++ b/infer_4_33_0/lib/python3.10/site-packages/h5py/tests/data_files/vlen_string_dset.h5 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:900f8baf19d3d8c4d1193ac1ac6019ee7774005e85c030af44e6757b38d29793 +size 6304 diff --git a/infer_4_33_0/lib/python3.10/site-packages/h5py/tests/data_files/vlen_string_s390x.h5 b/infer_4_33_0/lib/python3.10/site-packages/h5py/tests/data_files/vlen_string_s390x.h5 new file mode 100644 index 0000000000000000000000000000000000000000..bca4b91ad9029e3d0f0118aff12c28094edc95af --- /dev/null +++ b/infer_4_33_0/lib/python3.10/site-packages/h5py/tests/data_files/vlen_string_s390x.h5 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ea990c68e0371bafab4966f752fa1355b3b9f64360066f6d9daff8f1b7e74ca5 +size 9008 diff --git a/infer_4_33_0/lib/python3.10/site-packages/mdit_py_plugins/myst_blocks/__init__.py b/infer_4_33_0/lib/python3.10/site-packages/mdit_py_plugins/myst_blocks/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..434cad6ccbe2dbdcbf2304ab88ba5950e82792bc --- /dev/null +++ b/infer_4_33_0/lib/python3.10/site-packages/mdit_py_plugins/myst_blocks/__init__.py @@ -0,0 +1 @@ +from .index import myst_block_plugin # noqa: F401 diff --git a/infer_4_33_0/lib/python3.10/site-packages/mdit_py_plugins/myst_blocks/__pycache__/__init__.cpython-310.pyc b/infer_4_33_0/lib/python3.10/site-packages/mdit_py_plugins/myst_blocks/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e1ab14de3181e19188ee3580733bd47637acc128 Binary files /dev/null and b/infer_4_33_0/lib/python3.10/site-packages/mdit_py_plugins/myst_blocks/__pycache__/__init__.cpython-310.pyc differ diff --git a/infer_4_33_0/lib/python3.10/site-packages/mdit_py_plugins/myst_blocks/__pycache__/index.cpython-310.pyc b/infer_4_33_0/lib/python3.10/site-packages/mdit_py_plugins/myst_blocks/__pycache__/index.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5499e529b760e56ca5a28ba92476329d83a6a00c Binary files /dev/null and b/infer_4_33_0/lib/python3.10/site-packages/mdit_py_plugins/myst_blocks/__pycache__/index.cpython-310.pyc differ diff --git a/infer_4_33_0/lib/python3.10/site-packages/mdit_py_plugins/myst_blocks/index.py b/infer_4_33_0/lib/python3.10/site-packages/mdit_py_plugins/myst_blocks/index.py new file mode 100644 index 0000000000000000000000000000000000000000..d0e4cf6aac70e952472169ae366681ed84dd0f52 --- /dev/null +++ b/infer_4_33_0/lib/python3.10/site-packages/mdit_py_plugins/myst_blocks/index.py @@ -0,0 +1,153 @@ +import itertools + +from markdown_it import MarkdownIt +from markdown_it.common.utils import escapeHtml, isSpace +from markdown_it.rules_block import StateBlock + + +def myst_block_plugin(md: MarkdownIt): + """Parse MyST targets (``(name)=``), blockquotes (``% comment``) and block breaks (``+++``).""" + md.block.ruler.before( + "blockquote", + "myst_line_comment", + line_comment, + {"alt": ["paragraph", "reference", "blockquote", "list", "footnote_def"]}, + ) + md.block.ruler.before( + "hr", + "myst_block_break", + block_break, + {"alt": ["paragraph", "reference", "blockquote", "list", "footnote_def"]}, + ) + md.block.ruler.before( + "hr", + "myst_target", + target, + {"alt": ["paragraph", "reference", "blockquote", "list", "footnote_def"]}, + ) + md.add_render_rule("myst_target", render_myst_target) + md.add_render_rule("myst_line_comment", render_myst_line_comment) + + +def line_comment(state: StateBlock, startLine: int, endLine: int, silent: bool): + + pos = state.bMarks[startLine] + state.tShift[startLine] + maximum = state.eMarks[startLine] + + # if it's indented more than 3 spaces, it should be a code block + if state.sCount[startLine] - state.blkIndent >= 4: + return False + + if state.src[pos] != "%": + return False + + if silent: + return True + + token = state.push("myst_line_comment", "", 0) + token.attrSet("class", "myst-line-comment") + token.content = state.src[pos + 1 : maximum].rstrip() + token.markup = "%" + + # search end of block while appending lines to `token.content` + for nextLine in itertools.count(startLine + 1): + if nextLine >= endLine: + break + pos = state.bMarks[nextLine] + state.tShift[nextLine] + maximum = state.eMarks[nextLine] + + if state.src[pos] != "%": + break + token.content += "\n" + state.src[pos + 1 : maximum].rstrip() + + state.line = nextLine + token.map = [startLine, nextLine] + + return True + + +def block_break(state: StateBlock, startLine: int, endLine: int, silent: bool): + + pos = state.bMarks[startLine] + state.tShift[startLine] + maximum = state.eMarks[startLine] + + # if it's indented more than 3 spaces, it should be a code block + if state.sCount[startLine] - state.blkIndent >= 4: + return False + + marker = state.srcCharCode[pos] + pos += 1 + + # Check block marker /* + */ + if marker != 0x2B: + return False + + # markers can be mixed with spaces, but there should be at least 3 of them + + cnt = 1 + while pos < maximum: + ch = state.srcCharCode[pos] + if ch != marker and not isSpace(ch): + break + if ch == marker: + cnt += 1 + pos += 1 + + if cnt < 3: + return False + + if silent: + return True + + state.line = startLine + 1 + + token = state.push("myst_block_break", "hr", 0) + token.attrSet("class", "myst-block") + token.content = state.src[pos:maximum].strip() + token.map = [startLine, state.line] + token.markup = chr(marker) * cnt + + return True + + +def target(state: StateBlock, startLine: int, endLine: int, silent: bool): + + pos = state.bMarks[startLine] + state.tShift[startLine] + maximum = state.eMarks[startLine] + + # if it's indented more than 3 spaces, it should be a code block + if state.sCount[startLine] - state.blkIndent >= 4: + return False + + text = state.src[pos:maximum].strip() + if not text.startswith("("): + return False + if not text.endswith(")="): + return False + if not text[1:-2]: + return False + + if silent: + return True + + state.line = startLine + 1 + + token = state.push("myst_target", "", 0) + token.attrSet("class", "myst-target") + token.content = text[1:-2] + token.map = [startLine, state.line] + + return True + + +def render_myst_target(self, tokens, idx, options, env): + label = tokens[idx].content + class_name = "myst-target" + target = f'({label})=' + return f'
{target}
' + + +def render_myst_line_comment(self, tokens, idx, options, env): + # Strip leading whitespace from all lines + content = "\n".join(line.lstrip() for line in tokens[idx].content.split("\n")) + return f"" diff --git a/infer_4_33_0/lib/python3.10/site-packages/mdit_py_plugins/myst_role/__init__.py b/infer_4_33_0/lib/python3.10/site-packages/mdit_py_plugins/myst_role/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..67b87f82b65f221b867c9c5685873caed0b3088f --- /dev/null +++ b/infer_4_33_0/lib/python3.10/site-packages/mdit_py_plugins/myst_role/__init__.py @@ -0,0 +1 @@ +from .index import myst_role_plugin # noqa: F401 diff --git a/infer_4_33_0/lib/python3.10/site-packages/mdit_py_plugins/tasklists/__pycache__/__init__.cpython-310.pyc b/infer_4_33_0/lib/python3.10/site-packages/mdit_py_plugins/tasklists/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9a7ac956d117e9c226f8b796c75bb099bc839ca7 Binary files /dev/null and b/infer_4_33_0/lib/python3.10/site-packages/mdit_py_plugins/tasklists/__pycache__/__init__.cpython-310.pyc differ diff --git a/infer_4_33_0/lib/python3.10/site-packages/mdit_py_plugins/texmath/LICENSE b/infer_4_33_0/lib/python3.10/site-packages/mdit_py_plugins/texmath/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..b88387c65e878791588425fe9504247c708db535 --- /dev/null +++ b/infer_4_33_0/lib/python3.10/site-packages/mdit_py_plugins/texmath/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2013-17 Stefan Goessner + +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/infer_4_33_0/lib/python3.10/site-packages/mdit_py_plugins/texmath/__init__.py b/infer_4_33_0/lib/python3.10/site-packages/mdit_py_plugins/texmath/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f0c258875f102750ef36836e8802098f65916b00 --- /dev/null +++ b/infer_4_33_0/lib/python3.10/site-packages/mdit_py_plugins/texmath/__init__.py @@ -0,0 +1 @@ +from .index import texmath_plugin # noqa F401 diff --git a/infer_4_33_0/lib/python3.10/site-packages/mdit_py_plugins/texmath/index.py b/infer_4_33_0/lib/python3.10/site-packages/mdit_py_plugins/texmath/index.py new file mode 100644 index 0000000000000000000000000000000000000000..ecf178c0cf3a48dd1135e06271c965e384df957b --- /dev/null +++ b/infer_4_33_0/lib/python3.10/site-packages/mdit_py_plugins/texmath/index.py @@ -0,0 +1,307 @@ +import re +from typing import Optional + +from markdown_it import MarkdownIt +from markdown_it.common.utils import charCodeAt + + +def texmath_plugin(md: MarkdownIt, delimiters="dollars", macros: Optional[dict] = None): + """Plugin ported from + `markdown-it-texmath `__. + + It parses TeX math equations set inside opening and closing delimiters: + + .. code-block:: md + + $\\alpha = \\frac{1}{2}$ + + :param delimiters: one of: brackets, dollars, gitlab, julia, kramdown + + """ + macros = macros or {} + + if delimiters in rules: + for rule_inline in rules[delimiters]["inline"]: + md.inline.ruler.before( + "escape", rule_inline["name"], make_inline_func(rule_inline) + ) + + def render_math_inline(self, tokens, idx, options, env): + return rule_inline["tmpl"].format( + render(tokens[idx].content, False, macros) + ) + + md.add_render_rule(rule_inline["name"], render_math_inline) + + for rule_block in rules[delimiters]["block"]: + md.block.ruler.before( + "fence", rule_block["name"], make_block_func(rule_block) + ) + + def render_math_block(self, tokens, idx, options, env): + return rule_block["tmpl"].format( + render(tokens[idx].content, True, macros), tokens[idx].info + ) + + md.add_render_rule(rule_block["name"], render_math_block) + + +def applyRule(rule, string: str, begin, inBlockquote): + + if not ( + string.startswith(rule["tag"], begin) + and (rule["pre"](string, begin) if "pre" in rule else True) + ): + return False + + match = rule["rex"].match(string[begin:]) # type: re.Match + + if not match or match.start() != 0: + return False + + lastIndex = match.end() + begin - 1 + if "post" in rule: + if not ( + rule["post"](string, lastIndex) # valid post-condition + # remove evil blockquote bug (https:#github.com/goessner/mdmath/issues/50) + and (not inBlockquote or "\n" not in match.group(1)) + ): + return False + return match + + +def make_inline_func(rule): + def _func(state, silent): + res = applyRule(rule, state.src, state.pos, False) + if res: + if not silent: + token = state.push(rule["name"], "math", 0) + token.content = res[1] # group 1 from regex .. + token.markup = rule["tag"] + + state.pos += res.end() + + return bool(res) + + return _func + + +def make_block_func(rule): + def _func(state, begLine, endLine, silent): + begin = state.bMarks[begLine] + state.tShift[begLine] + res = applyRule(rule, state.src, begin, state.parentType == "blockquote") + if res: + if not silent: + token = state.push(rule["name"], "math", 0) + token.block = True + token.content = res[1] + token.info = res[len(res.groups())] + token.markup = rule["tag"] + + line = begLine + endpos = begin + res.end() - 1 + + while line < endLine: + if endpos >= state.bMarks[line] and endpos <= state.eMarks[line]: + # line for end of block math found ... + state.line = line + 1 + break + line += 1 + + state.pos = begin + res.end() + + return bool(res) + + return _func + + +def dollar_pre(str, beg): + prv = charCodeAt(str[beg - 1], 0) if beg > 0 else False + return ( + (not prv) or prv != 0x5C and (prv < 0x30 or prv > 0x39) # no backslash, + ) # no decimal digit .. before opening '$' + + +def dollar_post(string, end): + try: + nxt = string[end + 1] and charCodeAt(string[end + 1], 0) + except IndexError: + return True + return ( + (not nxt) or (nxt < 0x30) or (nxt > 0x39) + ) # no decimal digit .. after closing '$' + + +def render(tex, displayMode, macros): + return tex + # TODO better HTML renderer port for math + # try: + # res = katex.renderToString(tex,{throwOnError:False,displayMode,macros}) + # except: + # res = tex+": "+err.message.replace("<","<") + # return res + + +# def use(katex): # math renderer used ... +# texmath.katex = katex; # ... katex solely at current ... +# return texmath; +# } + + +# All regexes areg global (g) and sticky (y), see: +# https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/sticky + +rules: dict = { + "brackets": { + "inline": [ + { + "name": "math_inline", + "rex": re.compile(r"^\\\((.+?)\\\)", re.DOTALL), + "tmpl": "{0}", + "tag": "\\(", + } + ], + "block": [ + { + "name": "math_block_eqno", + "rex": re.compile( + r"^\\\[(((?!\\\]|\\\[)[\s\S])+?)\\\]\s*?\(([^)$\r\n]+?)\)", re.M + ), + "tmpl": '
{0}({1})
', + "tag": "\\[", + }, + { + "name": "math_block", + "rex": re.compile(r"^\\\[([\s\S]+?)\\\]", re.M), + "tmpl": "
\n{0}\n
\n", + "tag": "\\[", + }, + ], + }, + "gitlab": { + "inline": [ + { + "name": "math_inline", + "rex": re.compile(r"^\$`(.+?)`\$"), + "tmpl": "{0}", + "tag": "$`", + } + ], + "block": [ + { + "name": "math_block_eqno", + "rex": re.compile( + r"^`{3}math\s+?([^`]+?)\s+?`{3}\s*?\(([^)$\r\n]+?)\)", re.M + ), + "tmpl": '
\n{0}({1})\n
\n', # noqa: E501 + "tag": "```math", + }, + { + "name": "math_block", + "rex": re.compile(r"^`{3}math\s+?([^`]+?)\s+?`{3}", re.M), + "tmpl": "
\n{0}\n
\n", + "tag": "```math", + }, + ], + }, + "julia": { + "inline": [ + { + "name": "math_inline", + "rex": re.compile(r"^`{2}([^`]+?)`{2}"), + "tmpl": "{0}", + "tag": "``", + }, + { + "name": "math_inline", + "rex": re.compile(r"^\$(\S[^$\r\n]*?[^\s\\]{1}?)\$"), + "tmpl": "{0}", + "tag": "$", + "pre": dollar_pre, + "post": dollar_post, + }, + { + "name": "math_single", + "rex": re.compile(r"^\$([^$\s\\]{1}?)\$"), + "tmpl": "{0}", + "tag": "$", + "pre": dollar_pre, + "post": dollar_post, + }, + ], + "block": [ + { + "name": "math_block_eqno", + "rex": re.compile( + r"^`{3}math\s+?([^`]+?)\s+?`{3}\s*?\(([^)$\r\n]+?)\)", re.M + ), + "tmpl": '
{0}({1})
', + "tag": "```math", + }, + { + "name": "math_block", + "rex": re.compile(r"^`{3}math\s+?([^`]+?)\s+?`{3}", re.M), + "tmpl": "
{0}
", + "tag": "```math", + }, + ], + }, + "kramdown": { + "inline": [ + { + "name": "math_inline", + "rex": re.compile(r"^\${2}([^$\r\n]*?)\${2}"), + "tmpl": "{0}", + "tag": "$$", + } + ], + "block": [ + { + "name": "math_block_eqno", + "rex": re.compile(r"^\${2}([^$]*?)\${2}\s*?\(([^)$\r\n]+?)\)", re.M), + "tmpl": '
{0}({1})
', + "tag": "$$", + }, + { + "name": "math_block", + "rex": re.compile(r"^\${2}([^$]*?)\${2}", re.M), + "tmpl": "
{0}
", + "tag": "$$", + }, + ], + }, + "dollars": { + "inline": [ + { + "name": "math_inline", + "rex": re.compile(r"^\$(\S[^$]*?[^\s\\]{1}?)\$"), + "tmpl": "{0}", + "tag": "$", + "pre": dollar_pre, + "post": dollar_post, + }, + { + "name": "math_single", + "rex": re.compile(r"^\$([^$\s\\]{1}?)\$"), + "tmpl": "{0}", + "tag": "$", + "pre": dollar_pre, + "post": dollar_post, + }, + ], + "block": [ + { + "name": "math_block_eqno", + "rex": re.compile(r"^\${2}([^$]*?)\${2}\s*?\(([^)$\r\n]+?)\)", re.M), + "tmpl": '
\n{0}({1})\n
\n', # noqa: E501 + "tag": "$$", + }, + { + "name": "math_block", + "rex": re.compile(r"^\${2}([^$]*?)\${2}", re.M), + "tmpl": "
\n{0}\n
\n", + "tag": "$$", + }, + ], + }, +} diff --git a/infer_4_33_0/lib/python3.10/site-packages/mdit_py_plugins/texmath/port.yaml b/infer_4_33_0/lib/python3.10/site-packages/mdit_py_plugins/texmath/port.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ba47ac83a460f1e3f07f2e45536e756c4bb5512a --- /dev/null +++ b/infer_4_33_0/lib/python3.10/site-packages/mdit_py_plugins/texmath/port.yaml @@ -0,0 +1,7 @@ +- package: markdown-it-texmath + commit: 78c548829ce2ef85c73dc71e680d01e5ae41ffbf + date: Oct 4, 2019 + version: 0.6 + changes: | + both dollars/math_inline and brackets/math_inline regexes have been changed, + to allow (single) line breaks diff --git a/infer_4_33_0/lib/python3.10/site-packages/opt_einsum/__pycache__/blas.cpython-310.pyc b/infer_4_33_0/lib/python3.10/site-packages/opt_einsum/__pycache__/blas.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..29855f90fda5ba2f378471e36873a452c7d4443e Binary files /dev/null and b/infer_4_33_0/lib/python3.10/site-packages/opt_einsum/__pycache__/blas.cpython-310.pyc differ diff --git a/infer_4_33_0/lib/python3.10/site-packages/opt_einsum/__pycache__/helpers.cpython-310.pyc b/infer_4_33_0/lib/python3.10/site-packages/opt_einsum/__pycache__/helpers.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cbd312a265e0fae851a202234081a4bb49765432 Binary files /dev/null and b/infer_4_33_0/lib/python3.10/site-packages/opt_einsum/__pycache__/helpers.cpython-310.pyc differ diff --git a/infer_4_33_0/lib/python3.10/site-packages/opt_einsum/__pycache__/paths.cpython-310.pyc b/infer_4_33_0/lib/python3.10/site-packages/opt_einsum/__pycache__/paths.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..53074fecf62fca28f9207841785b2b41bc928f7a Binary files /dev/null and b/infer_4_33_0/lib/python3.10/site-packages/opt_einsum/__pycache__/paths.cpython-310.pyc differ diff --git a/infer_4_33_0/lib/python3.10/site-packages/opt_einsum/backends/__pycache__/__init__.cpython-310.pyc b/infer_4_33_0/lib/python3.10/site-packages/opt_einsum/backends/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e5618100cc8c22c71ca0bec04008ee7e4c5f8c44 Binary files /dev/null and b/infer_4_33_0/lib/python3.10/site-packages/opt_einsum/backends/__pycache__/__init__.cpython-310.pyc differ diff --git a/infer_4_33_0/lib/python3.10/site-packages/opt_einsum/backends/__pycache__/cupy.cpython-310.pyc b/infer_4_33_0/lib/python3.10/site-packages/opt_einsum/backends/__pycache__/cupy.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..897bbdec518ec16d79965ae2c95ac6de5975989f Binary files /dev/null and b/infer_4_33_0/lib/python3.10/site-packages/opt_einsum/backends/__pycache__/cupy.cpython-310.pyc differ diff --git a/infer_4_33_0/lib/python3.10/site-packages/opt_einsum/backends/__pycache__/dispatch.cpython-310.pyc b/infer_4_33_0/lib/python3.10/site-packages/opt_einsum/backends/__pycache__/dispatch.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..05a27dbf0150c097069bd2aff1ba24cf5398d309 Binary files /dev/null and b/infer_4_33_0/lib/python3.10/site-packages/opt_einsum/backends/__pycache__/dispatch.cpython-310.pyc differ diff --git a/infer_4_33_0/lib/python3.10/site-packages/opt_einsum/backends/__pycache__/object_arrays.cpython-310.pyc b/infer_4_33_0/lib/python3.10/site-packages/opt_einsum/backends/__pycache__/object_arrays.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..87764e9738e760e7c582d7891127167fe17bf5bc Binary files /dev/null and b/infer_4_33_0/lib/python3.10/site-packages/opt_einsum/backends/__pycache__/object_arrays.cpython-310.pyc differ diff --git a/infer_4_33_0/lib/python3.10/site-packages/opt_einsum/backends/__pycache__/tensorflow.cpython-310.pyc b/infer_4_33_0/lib/python3.10/site-packages/opt_einsum/backends/__pycache__/tensorflow.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6155079f45682e4df2f2034edc44bbe90dc7dfee Binary files /dev/null and b/infer_4_33_0/lib/python3.10/site-packages/opt_einsum/backends/__pycache__/tensorflow.cpython-310.pyc differ diff --git a/infer_4_33_0/lib/python3.10/site-packages/opt_einsum/backends/__pycache__/theano.cpython-310.pyc b/infer_4_33_0/lib/python3.10/site-packages/opt_einsum/backends/__pycache__/theano.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..420854ade72d2d37218244ecfe986ff233f915f0 Binary files /dev/null and b/infer_4_33_0/lib/python3.10/site-packages/opt_einsum/backends/__pycache__/theano.cpython-310.pyc differ diff --git a/infer_4_33_0/lib/python3.10/site-packages/opt_einsum/backends/__pycache__/torch.cpython-310.pyc b/infer_4_33_0/lib/python3.10/site-packages/opt_einsum/backends/__pycache__/torch.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..55c7435d45e2140d1eb394a71c80a8fa32a7d0b5 Binary files /dev/null and b/infer_4_33_0/lib/python3.10/site-packages/opt_einsum/backends/__pycache__/torch.cpython-310.pyc differ diff --git a/infer_4_33_0/lib/python3.10/site-packages/opt_einsum/backends/cupy.py b/infer_4_33_0/lib/python3.10/site-packages/opt_einsum/backends/cupy.py new file mode 100644 index 0000000000000000000000000000000000000000..34e47639d265636a24d67c2a0ac1b0f442bcc029 --- /dev/null +++ b/infer_4_33_0/lib/python3.10/site-packages/opt_einsum/backends/cupy.py @@ -0,0 +1,32 @@ +"""Required functions for optimized contractions of numpy arrays using cupy.""" + +from opt_einsum.helpers import has_array_interface +from opt_einsum.sharing import to_backend_cache_wrap + +__all__ = ["to_cupy", "build_expression", "evaluate_constants"] + + +@to_backend_cache_wrap +def to_cupy(array): # pragma: no cover + import cupy + + if has_array_interface(array): + return cupy.asarray(array) + + return array + + +def build_expression(_, expr): # pragma: no cover + """Build a cupy function based on ``arrays`` and ``expr``.""" + + def cupy_contract(*arrays): + return expr._contract([to_cupy(x) for x in arrays], backend="cupy").get() + + return cupy_contract + + +def evaluate_constants(const_arrays, expr): # pragma: no cover + """Convert constant arguments to cupy arrays, and perform any possible + constant contractions. + """ + return expr(*[to_cupy(x) for x in const_arrays], backend="cupy", evaluate_constants=True) diff --git a/infer_4_33_0/lib/python3.10/site-packages/opt_einsum/tests/__init__.py b/infer_4_33_0/lib/python3.10/site-packages/opt_einsum/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/infer_4_33_0/lib/python3.10/site-packages/opt_einsum/tests/__pycache__/__init__.cpython-310.pyc b/infer_4_33_0/lib/python3.10/site-packages/opt_einsum/tests/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cedebbb2ef8b73580be818830515d3aed26cd22a Binary files /dev/null and b/infer_4_33_0/lib/python3.10/site-packages/opt_einsum/tests/__pycache__/__init__.cpython-310.pyc differ diff --git a/infer_4_33_0/lib/python3.10/site-packages/opt_einsum/tests/__pycache__/test_backends.cpython-310.pyc b/infer_4_33_0/lib/python3.10/site-packages/opt_einsum/tests/__pycache__/test_backends.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ffd3bd8b6a39a573e32b5599e214425554c9e00c Binary files /dev/null and b/infer_4_33_0/lib/python3.10/site-packages/opt_einsum/tests/__pycache__/test_backends.cpython-310.pyc differ diff --git a/infer_4_33_0/lib/python3.10/site-packages/opt_einsum/tests/__pycache__/test_blas.cpython-310.pyc b/infer_4_33_0/lib/python3.10/site-packages/opt_einsum/tests/__pycache__/test_blas.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4d421d3aefdf6e217bb18646762aaee98714b011 Binary files /dev/null and b/infer_4_33_0/lib/python3.10/site-packages/opt_einsum/tests/__pycache__/test_blas.cpython-310.pyc differ diff --git a/infer_4_33_0/lib/python3.10/site-packages/opt_einsum/tests/__pycache__/test_contract.cpython-310.pyc b/infer_4_33_0/lib/python3.10/site-packages/opt_einsum/tests/__pycache__/test_contract.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..49b2f1f8b8ad1304e4d587975934a72967cb85ff Binary files /dev/null and b/infer_4_33_0/lib/python3.10/site-packages/opt_einsum/tests/__pycache__/test_contract.cpython-310.pyc differ diff --git a/infer_4_33_0/lib/python3.10/site-packages/opt_einsum/tests/__pycache__/test_edge_cases.cpython-310.pyc b/infer_4_33_0/lib/python3.10/site-packages/opt_einsum/tests/__pycache__/test_edge_cases.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7eb69a7884cc61b7e669ed775bea7db1748534ea Binary files /dev/null and b/infer_4_33_0/lib/python3.10/site-packages/opt_einsum/tests/__pycache__/test_edge_cases.cpython-310.pyc differ diff --git a/infer_4_33_0/lib/python3.10/site-packages/opt_einsum/tests/__pycache__/test_input.cpython-310.pyc b/infer_4_33_0/lib/python3.10/site-packages/opt_einsum/tests/__pycache__/test_input.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4d51fb52a3133768e0451d89d033ac884da2d26e Binary files /dev/null and b/infer_4_33_0/lib/python3.10/site-packages/opt_einsum/tests/__pycache__/test_input.cpython-310.pyc differ diff --git a/infer_4_33_0/lib/python3.10/site-packages/opt_einsum/tests/__pycache__/test_parser.cpython-310.pyc b/infer_4_33_0/lib/python3.10/site-packages/opt_einsum/tests/__pycache__/test_parser.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..09c87f63bdc8c9d3b5c13cfa6caab1c31ed444e0 Binary files /dev/null and b/infer_4_33_0/lib/python3.10/site-packages/opt_einsum/tests/__pycache__/test_parser.cpython-310.pyc differ diff --git a/infer_4_33_0/lib/python3.10/site-packages/opt_einsum/tests/__pycache__/test_sharing.cpython-310.pyc b/infer_4_33_0/lib/python3.10/site-packages/opt_einsum/tests/__pycache__/test_sharing.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..49bbb7c4a8484a392645ba678d670542a0697b76 Binary files /dev/null and b/infer_4_33_0/lib/python3.10/site-packages/opt_einsum/tests/__pycache__/test_sharing.cpython-310.pyc differ diff --git a/infer_4_33_0/lib/python3.10/site-packages/opt_einsum/tests/test_backends.py b/infer_4_33_0/lib/python3.10/site-packages/opt_einsum/tests/test_backends.py new file mode 100644 index 0000000000000000000000000000000000000000..8145fb16c1a612d4cc4856cc0370cfeb89512c83 --- /dev/null +++ b/infer_4_33_0/lib/python3.10/site-packages/opt_einsum/tests/test_backends.py @@ -0,0 +1,462 @@ +from typing import Set + +import pytest + +from opt_einsum import backends, contract, contract_expression, sharing +from opt_einsum.contract import ArrayShaped, infer_backend, parse_backend +from opt_einsum.testing import build_views + +try: + # needed so tensorflow doesn't allocate all gpu mem + try: + from tensorflow import ConfigProto # type: ignore + from tensorflow import Session as TFSession + except ImportError: + from tensorflow.compat.v1 import ConfigProto # type: ignore + from tensorflow.compat.v1 import Session as TFSession + _TF_CONFIG = ConfigProto() + _TF_CONFIG.gpu_options.allow_growth = True +except ImportError: + pass + + +tests = [ + "ab,bc->ca", + "abc,bcd,dea", + "abc,def->fedcba", + "abc,bcd,df->fa", + # test 'prefer einsum' ops + "ijk,ikj", + "i,j->ij", + "ijk,k->ij", + "AB,BC->CA", +] + + +@pytest.mark.parametrize("string", tests) +def test_tensorflow(string: str) -> None: + np = pytest.importorskip("numpy") + pytest.importorskip("tensorflow") + + views = build_views(string) + ein = contract(string, *views, optimize=False, use_blas=False) + opt = np.empty_like(ein) + + shps = [v.shape for v in views] + expr = contract_expression(string, *shps, optimize=True) + + sess = TFSession(config=_TF_CONFIG) + with sess.as_default(): + expr(*views, backend="tensorflow", out=opt) + sess.close() + + assert np.allclose(ein, opt) + + # test non-conversion mode + tensorflow_views = [backends.to_tensorflow(view) for view in views] + expr(*tensorflow_views) + + +@pytest.mark.parametrize("constants", [{0, 1}, {0, 2}, {1, 2}]) +def test_tensorflow_with_constants(constants: Set[int]) -> None: + np = pytest.importorskip("numpy") + tf = pytest.importorskip("tensorflow") + + eq = "ij,jk,kl->li" + shapes = (2, 3), (3, 4), (4, 5) + (non_const,) = {0, 1, 2} - constants + ops = [np.random.rand(*shp) if i in constants else shp for i, shp in enumerate(shapes)] + var = np.random.rand(*shapes[non_const]) + res_exp = contract(eq, *(ops[i] if i in constants else var for i in range(3))) + + expr = contract_expression(eq, *ops, constants=constants) + + # check tensorflow + with TFSession(config=_TF_CONFIG).as_default(): + res_got = expr(var, backend="tensorflow") + assert all( + array is None or infer_backend(array) == "tensorflow" for array in expr._evaluated_constants["tensorflow"] + ) + assert np.allclose(res_exp, res_got) + + # check can call with numpy still + res_got2 = expr(var, backend="numpy") + assert np.allclose(res_exp, res_got2) + + # check tensorflow call returns tensorflow still + res_got3 = expr(backends.to_tensorflow(var)) + assert isinstance(res_got3, tf.Tensor) + + +@pytest.mark.parametrize("string", tests) +def test_tensorflow_with_sharing(string: str) -> None: + np = pytest.importorskip("numpy") + tf = pytest.importorskip("tensorflow") + + views = build_views(string) + ein = contract(string, *views, optimize=False, use_blas=False) + + shps = [v.shape for v in views] + expr = contract_expression(string, *shps, optimize=True) + + sess = TFSession(config=_TF_CONFIG) + + with sess.as_default(), sharing.shared_intermediates() as cache: + tfl1 = expr(*views, backend="tensorflow") + assert sharing.get_sharing_cache() is cache + cache_sz = len(cache) + assert cache_sz > 0 + tfl2 = expr(*views, backend="tensorflow") + assert len(cache) == cache_sz + + assert all(isinstance(t, tf.Tensor) for t in cache.values()) + + assert np.allclose(ein, tfl1) + assert np.allclose(ein, tfl2) + + +@pytest.mark.parametrize("string", tests) +def test_theano(string: str) -> None: + np = pytest.importorskip("numpy") + theano = pytest.importorskip("theano") + + views = build_views(string) + ein = contract(string, *views, optimize=False, use_blas=False) + shps = [v.shape for v in views] + + expr = contract_expression(string, *shps, optimize=True) + + opt = expr(*views, backend="theano") + assert np.allclose(ein, opt) + + # test non-conversion mode + theano_views = [backends.to_theano(view) for view in views] + theano_opt = expr(*theano_views) + assert isinstance(theano_opt, theano.tensor.TensorVariable) + + +@pytest.mark.parametrize("constants", [{0, 1}, {0, 2}, {1, 2}]) +def test_theano_with_constants(constants: Set[int]) -> None: + np = pytest.importorskip("numpy") + theano = pytest.importorskip("theano") + + eq = "ij,jk,kl->li" + shapes = (2, 3), (3, 4), (4, 5) + (non_const,) = {0, 1, 2} - constants + ops = [np.random.rand(*shp) if i in constants else shp for i, shp in enumerate(shapes)] + var = np.random.rand(*shapes[non_const]) + res_exp = contract(eq, *(ops[i] if i in constants else var for i in range(3))) + + expr = contract_expression(eq, *ops, constants=constants) + + # check theano + res_got = expr(var, backend="theano") + assert all(array is None or infer_backend(array) == "theano" for array in expr._evaluated_constants["theano"]) + assert np.allclose(res_exp, res_got) + + # check can call with numpy still + res_got2 = expr(var, backend="numpy") + assert np.allclose(res_exp, res_got2) + + # check theano call returns theano still + res_got3 = expr(backends.to_theano(var)) + assert isinstance(res_got3, theano.tensor.TensorVariable) + + +@pytest.mark.parametrize("string", tests) +def test_theano_with_sharing(string: str) -> None: + np = pytest.importorskip("numpy") + theano = pytest.importorskip("theano") + + views = build_views(string) + ein = contract(string, *views, optimize=False, use_blas=False) + + shps = [v.shape for v in views] + expr = contract_expression(string, *shps, optimize=True) + + with sharing.shared_intermediates() as cache: + thn1 = expr(*views, backend="theano") + assert sharing.get_sharing_cache() is cache + cache_sz = len(cache) + assert cache_sz > 0 + thn2 = expr(*views, backend="theano") + assert len(cache) == cache_sz + + assert all(isinstance(t, theano.tensor.TensorVariable) for t in cache.values()) + + assert np.allclose(ein, thn1) + assert np.allclose(ein, thn2) + + +@pytest.mark.parametrize("string", tests) +def test_cupy(string: str) -> None: + np = pytest.importorskip("numpy") # pragma: no cover + cupy = pytest.importorskip("cupy") + + views = build_views(string) + ein = contract(string, *views, optimize=False, use_blas=False) + shps = [v.shape for v in views] + + expr = contract_expression(string, *shps, optimize=True) + + opt = expr(*views, backend="cupy") + assert np.allclose(ein, opt) + + # test non-conversion mode + cupy_views = [backends.to_cupy(view) for view in views] + cupy_opt = expr(*cupy_views) + assert isinstance(cupy_opt, cupy.ndarray) + assert np.allclose(ein, cupy.asnumpy(cupy_opt)) + + +@pytest.mark.parametrize("constants", [{0, 1}, {0, 2}, {1, 2}]) +def test_cupy_with_constants(constants: Set[int]) -> None: + np = pytest.importorskip("numpy") # pragma: no cover + cupy = pytest.importorskip("cupy") + + eq = "ij,jk,kl->li" + shapes = (2, 3), (3, 4), (4, 5) + (non_const,) = {0, 1, 2} - constants + ops = [np.random.rand(*shp) if i in constants else shp for i, shp in enumerate(shapes)] + var = np.random.rand(*shapes[non_const]) + res_exp = contract(eq, *(ops[i] if i in constants else var for i in range(3))) + + expr = contract_expression(eq, *ops, constants=constants) + + # check cupy + res_got = expr(var, backend="cupy") + # check cupy versions of constants exist + assert all(array is None or infer_backend(array) == "cupy" for array in expr._evaluated_constants["cupy"]) + assert np.allclose(res_exp, res_got) + + # check can call with numpy still + res_got2 = expr(var, backend="numpy") + assert np.allclose(res_exp, res_got2) + + # check cupy call returns cupy still + res_got3 = expr(cupy.asarray(var)) + assert isinstance(res_got3, cupy.ndarray) + assert np.allclose(res_exp, res_got3.get()) + + +@pytest.mark.parametrize("string", tests) +def test_jax(string: str) -> None: + np = pytest.importorskip("numpy") # pragma: no cover + pytest.importorskip("jax") + + views = build_views(string) + ein = contract(string, *views, optimize=False, use_blas=False) + shps = [v.shape for v in views] + + expr = contract_expression(string, *shps, optimize=True) + + opt = expr(*views, backend="jax") + assert np.allclose(ein, opt) + assert isinstance(opt, np.ndarray) + + +@pytest.mark.parametrize("constants", [{0, 1}, {0, 2}, {1, 2}]) +def test_jax_with_constants(constants: Set[int]) -> None: + jax = pytest.importorskip("jax") + key = jax.random.PRNGKey(42) + + eq = "ij,jk,kl->li" + shapes = (2, 3), (3, 4), (4, 5) + (non_const,) = {0, 1, 2} - constants + ops = [jax.random.uniform(key, shp) if i in constants else shp for i, shp in enumerate(shapes)] + var = jax.random.uniform(key, shapes[non_const]) + res_exp = contract(eq, *(ops[i] if i in constants else var for i in range(3))) + + expr = contract_expression(eq, *ops, constants=constants) + + # check jax + res_got = expr(var, backend="jax") + # check jax versions of constants exist + assert all(array is None or infer_backend(array).startswith("jax") for array in expr._evaluated_constants["jax"]) + assert jax.numpy.sum(jax.numpy.abs(res_exp - res_got)) < 1e-8 + + +def test_jax_jit_gradient() -> None: + jax = pytest.importorskip("jax") + key = jax.random.PRNGKey(42) + + eq = "ij,jk,kl->" + shapes = (2, 3), (3, 4), (4, 2) + views = [jax.random.uniform(key, s) for s in shapes] + expr = contract_expression(eq, *shapes) + x0 = expr(*views) + + jit_expr = jax.jit(expr) + x1 = jit_expr(*views).item() + assert x1 == pytest.approx(x0, rel=1e-5) + + # jax only takes gradient w.r.t first argument + grad_expr = jax.jit(jax.grad(lambda views: expr(*views))) + view_grads = grad_expr(views) + assert all(v1.shape == v2.shape for v1, v2 in zip(views, view_grads)) + + # taking a step along the gradient should reduce our 'loss' + new_views = [v - 0.001 * dv for v, dv in zip(views, view_grads)] + x2 = jit_expr(*new_views).item() + assert x2 < x1 + + +def test_autograd_gradient() -> None: + np = pytest.importorskip("numpy") + autograd = pytest.importorskip("autograd") + + eq = "ij,jk,kl->" + shapes = (2, 3), (3, 4), (4, 2) + views = [np.random.randn(*s) for s in shapes] + expr = contract_expression(eq, *shapes) + x0 = expr(*views) + + # autograd only takes gradient w.r.t first argument + grad_expr = autograd.grad(lambda views: expr(*views)) + view_grads = grad_expr(views) + assert all(v1.shape == v2.shape for v1, v2 in zip(views, view_grads)) + + # taking a step along the gradient should reduce our 'loss' + new_views = [v - 0.001 * dv for v, dv in zip(views, view_grads)] + x1 = expr(*new_views) + assert x1 < x0 + + +@pytest.mark.parametrize("string", tests) +def test_dask(string: str) -> None: + np = pytest.importorskip("numpy") + da = pytest.importorskip("dask.array") + + views = build_views(string) + ein = contract(string, *views, optimize=False, use_blas=False) + shps = [v.shape for v in views] + expr = contract_expression(string, *shps, optimize=True) + + # test non-conversion mode + da_views = [da.from_array(x, chunks=(2)) for x in views] + da_opt = expr(*da_views) + + # check type is maintained when not using numpy arrays + assert isinstance(da_opt, da.Array) + + assert np.allclose(ein, np.array(da_opt)) + + # try raw contract + da_opt = contract(string, *da_views) + assert isinstance(da_opt, da.Array) + assert np.allclose(ein, np.array(da_opt)) + + +@pytest.mark.parametrize("string", tests) +def test_sparse(string: str) -> None: + np = pytest.importorskip("numpy") + sparse = pytest.importorskip("sparse") + + views = build_views(string) + + # sparsify views so they don't become dense during contraction + for view in views: + np.random.seed(42) + mask = np.random.choice([False, True], view.shape, True, [0.05, 0.95]) + view[mask] = 0 + + ein = contract(string, *views, optimize=False, use_blas=False) + shps = [v.shape for v in views] + expr = contract_expression(string, *shps, optimize=True) + + # test non-conversion mode + sparse_views = [sparse.COO.from_numpy(x) for x in views] + sparse_opt = expr(*sparse_views) + + # If the expression returns a float, stop here + if not ein.shape: + assert pytest.approx(ein) == 0.0 + return + + # check type is maintained when not using numpy arrays + assert isinstance(sparse_opt, sparse.COO) + assert np.allclose(ein, sparse_opt.todense()) + + # try raw contract + sparse_opt = contract(string, *sparse_views) + assert isinstance(sparse_opt, sparse.COO) + assert np.allclose(ein, sparse_opt.todense()) + + +@pytest.mark.parametrize("string", tests) +def test_torch(string: str) -> None: + torch = pytest.importorskip("torch") + + views = build_views(string, array_function=torch.rand) + ein = torch.einsum(string, *views) + + shps = [v.shape for v in views] + expr = contract_expression(string, *shps, optimize=True) + + opt = expr(*views, backend="torch") + torch.testing.assert_close(ein, opt) + + # test non-conversion mode + torch_views = [backends.to_torch(view) for view in views] + torch_opt = expr(*torch_views) + assert isinstance(torch_opt, torch.Tensor) + torch.testing.assert_close(ein, torch_opt) + + +@pytest.mark.parametrize("constants", [{0, 1}, {0, 2}, {1, 2}]) +def test_torch_with_constants(constants: Set[int]) -> None: + torch = pytest.importorskip("torch") + + eq = "ij,jk,kl->li" + shapes = (2, 3), (3, 4), (4, 5) + (non_const,) = {0, 1, 2} - constants + ops = [torch.rand(*shp) if i in constants else shp for i, shp in enumerate(shapes)] + var = torch.rand(*shapes[non_const]) + res_exp = contract(eq, *(ops[i] if i in constants else var for i in range(3)), backend="torch") + + expr = contract_expression(eq, *ops, constants=constants) + + # check torch + res_got = expr(var, backend="torch") + assert all(array is None or infer_backend(array) == "torch" for array in expr._evaluated_constants["torch"]) + torch.testing.assert_close(res_exp, res_got) + + # check can call with numpy still + res_got2 = expr(var, backend="torch") + torch.testing.assert_close(res_exp, res_got2) + + # check torch call returns torch still + res_got3 = expr(backends.to_torch(var)) + assert isinstance(res_got3, torch.Tensor) + torch.testing.assert_close(res_exp, res_got3) + + +def test_auto_backend_custom_array_no_tensordot() -> None: + x = ArrayShaped((1, 2, 3)) + # Shaped is an array-like object defined by opt_einsum - which has no TDOT + assert infer_backend(x) == "opt_einsum" + assert parse_backend([x], "auto") == "numpy" + assert parse_backend([x], None) == "numpy" + + +@pytest.mark.parametrize("string", tests) +def test_object_arrays_backend(string: str) -> None: + np = pytest.importorskip("numpy") + views = build_views(string) + ein = contract(string, *views, optimize=False, use_blas=False) + assert ein.dtype != object + + shps = [v.shape for v in views] + expr = contract_expression(string, *shps, optimize=True) + + obj_views = [view.astype(object) for view in views] + + # try raw contract + obj_opt = contract(string, *obj_views, backend="object") + assert obj_opt.dtype == object + assert np.allclose(ein, obj_opt.astype(float)) + + # test expression + obj_opt = expr(*obj_views, backend="object") + assert obj_opt.dtype == object + assert np.allclose(ein, obj_opt.astype(float)) diff --git a/infer_4_33_0/lib/python3.10/site-packages/opt_einsum/tests/test_blas.py b/infer_4_33_0/lib/python3.10/site-packages/opt_einsum/tests/test_blas.py new file mode 100644 index 0000000000000000000000000000000000000000..28b723a5b435a9a6a24105495e99093721dcbc14 --- /dev/null +++ b/infer_4_33_0/lib/python3.10/site-packages/opt_einsum/tests/test_blas.py @@ -0,0 +1,81 @@ +""" +Tests the BLAS capability for the opt_einsum module. +""" + +from typing import Any + +import pytest + +from opt_einsum import blas, contract + +blas_tests = [ + # DOT + ((["k", "k"], "", set("k")), "DOT"), # DDOT + ((["ijk", "ijk"], "", set("ijk")), "DOT"), # DDOT + # GEMV? + # GEMM + ((["ij", "jk"], "ik", set("j")), "GEMM"), # GEMM N N + ((["ijl", "jlk"], "ik", set("jl")), "GEMM"), # GEMM N N Tensor + ((["ij", "kj"], "ik", set("j")), "GEMM"), # GEMM N T + ((["ijl", "kjl"], "ik", set("jl")), "GEMM"), # GEMM N T Tensor + ((["ji", "jk"], "ik", set("j")), "GEMM"), # GEMM T N + ((["jli", "jlk"], "ik", set("jl")), "GEMM"), # GEMM T N Tensor + ((["ji", "kj"], "ik", set("j")), "GEMM"), # GEMM T T + ((["jli", "kjl"], "ik", set("jl")), "GEMM"), # GEMM T T Tensor + # GEMM with final transpose + ((["ij", "jk"], "ki", set("j")), "GEMM"), # GEMM N N + ((["ijl", "jlk"], "ki", set("jl")), "GEMM"), # GEMM N N Tensor + ((["ij", "kj"], "ki", set("j")), "GEMM"), # GEMM N T + ((["ijl", "kjl"], "ki", set("jl")), "GEMM"), # GEMM N T Tensor + ((["ji", "jk"], "ki", set("j")), "GEMM"), # GEMM T N + ((["jli", "jlk"], "ki", set("jl")), "GEMM"), # GEMM T N Tensor + ((["ji", "kj"], "ki", set("j")), "GEMM"), # GEMM T T + ((["jli", "kjl"], "ki", set("jl")), "GEMM"), # GEMM T T Tensor + # Tensor Dot (requires copy), lets not deal with this for now + ((["ilj", "jlk"], "ik", set("jl")), "TDOT"), # FT GEMM N N Tensor + ((["ijl", "ljk"], "ik", set("jl")), "TDOT"), # ST GEMM N N Tensor + ((["ilj", "kjl"], "ik", set("jl")), "TDOT"), # FT GEMM N T Tensor + ((["ijl", "klj"], "ik", set("jl")), "TDOT"), # ST GEMM N T Tensor + ((["lji", "jlk"], "ik", set("jl")), "TDOT"), # FT GEMM T N Tensor + ((["jli", "ljk"], "ik", set("jl")), "TDOT"), # ST GEMM T N Tensor + ((["lji", "jlk"], "ik", set("jl")), "TDOT"), # FT GEMM T N Tensor + ((["jli", "ljk"], "ik", set("jl")), "TDOT"), # ST GEMM T N Tensor + # Tensor Dot (requires copy), lets not deal with this for now with transpose + ((["ilj", "jlk"], "ik", set("lj")), "TDOT"), # FT GEMM N N Tensor + ((["ijl", "ljk"], "ik", set("lj")), "TDOT"), # ST GEMM N N Tensor + ((["ilj", "kjl"], "ik", set("lj")), "TDOT"), # FT GEMM N T Tensor + ((["ijl", "klj"], "ik", set("lj")), "TDOT"), # ST GEMM N T Tensor + ((["lji", "jlk"], "ik", set("lj")), "TDOT"), # FT GEMM T N Tensor + ((["jli", "ljk"], "ik", set("lj")), "TDOT"), # ST GEMM T N Tensor + ((["lji", "jlk"], "ik", set("lj")), "TDOT"), # FT GEMM T N Tensor + ((["jli", "ljk"], "ik", set("lj")), "TDOT"), # ST GEMM T N Tensor + # Other + ((["ijk", "ikj"], "", set("ijk")), "DOT/EINSUM"), # Transpose DOT + ((["i", "j"], "ij", set()), "OUTER/EINSUM"), # Outer + ((["ijk", "ik"], "j", set("ik")), "GEMV/EINSUM"), # Matrix-vector + ((["ijj", "jk"], "ik", set("j")), False), # Double index + ((["ijk", "j"], "ij", set()), False), # Index sum 1 + ((["ij", "ij"], "ij", set()), False), # Index sum 2 +] + + +@pytest.mark.parametrize("inp,benchmark", blas_tests) +def test_can_blas(inp: Any, benchmark: bool) -> None: + result = blas.can_blas(*inp) + assert result == benchmark + + +def test_blas_out() -> None: + np = pytest.importorskip("numpy") + + a = np.random.rand(4, 4) + b = np.random.rand(4, 4) + c = np.random.rand(4, 4) + d = np.empty((4, 4)) + + contract("ij,jk->ik", a, b, out=d) + np.testing.assert_allclose(d, np.dot(a, b)) + assert np.allclose(d, np.dot(a, b)) + + contract("ij,jk,kl->il", a, b, c, out=d) + np.testing.assert_allclose(d, np.dot(a, b).dot(c)) diff --git a/infer_4_33_0/lib/python3.10/site-packages/opt_einsum/tests/test_contract.py b/infer_4_33_0/lib/python3.10/site-packages/opt_einsum/tests/test_contract.py new file mode 100644 index 0000000000000000000000000000000000000000..72d90f7e2fd78d3ffccbecd94a647a945bbb9a13 --- /dev/null +++ b/infer_4_33_0/lib/python3.10/site-packages/opt_einsum/tests/test_contract.py @@ -0,0 +1,279 @@ +""" +Tets a series of opt_einsum contraction paths to ensure the results are the same for different paths +""" + +from typing import Any, List + +import pytest + +from opt_einsum import contract, contract_expression, contract_path +from opt_einsum.paths import _PATH_OPTIONS, linear_to_ssa, ssa_to_linear +from opt_einsum.testing import build_views, rand_equation +from opt_einsum.typing import OptimizeKind + +# NumPy is required for the majority of this file +np = pytest.importorskip("numpy") + + +tests = [ + # Test scalar-like operations + "a,->a", + "ab,->ab", + ",ab,->ab", + ",,->", + # Test hadamard-like products + "a,ab,abc->abc", + "a,b,ab->ab", + # Test index-transformations + "ea,fb,gc,hd,abcd->efgh", + "ea,fb,abcd,gc,hd->efgh", + "abcd,ea,fb,gc,hd->efgh", + # Test complex contractions + "acdf,jbje,gihb,hfac,gfac,gifabc,hfac", + "acdf,jbje,gihb,hfac,gfac,gifabc,hfac", + "cd,bdhe,aidb,hgca,gc,hgibcd,hgac", + "abhe,hidj,jgba,hiab,gab", + "bde,cdh,agdb,hica,ibd,hgicd,hiac", + "chd,bde,agbc,hiad,hgc,hgi,hiad", + "chd,bde,agbc,hiad,bdi,cgh,agdb", + "bdhe,acad,hiab,agac,hibd", + # Test collapse + "ab,ab,c->", + "ab,ab,c->c", + "ab,ab,cd,cd->", + "ab,ab,cd,cd->ac", + "ab,ab,cd,cd->cd", + "ab,ab,cd,cd,ef,ef->", + # Test outer prodcuts + "ab,cd,ef->abcdef", + "ab,cd,ef->acdf", + "ab,cd,de->abcde", + "ab,cd,de->be", + "ab,bcd,cd->abcd", + "ab,bcd,cd->abd", + # Random test cases that have previously failed + "eb,cb,fb->cef", + "dd,fb,be,cdb->cef", + "bca,cdb,dbf,afc->", + "dcc,fce,ea,dbf->ab", + "fdf,cdd,ccd,afe->ae", + "abcd,ad", + "ed,fcd,ff,bcf->be", + "baa,dcf,af,cde->be", + "bd,db,eac->ace", + "fff,fae,bef,def->abd", + "efc,dbc,acf,fd->abe", + # Inner products + "ab,ab", + "ab,ba", + "abc,abc", + "abc,bac", + "abc,cba", + # GEMM test cases + "ab,bc", + "ab,cb", + "ba,bc", + "ba,cb", + "abcd,cd", + "abcd,ab", + "abcd,cdef", + "abcd,cdef->feba", + "abcd,efdc", + # Inner than dot + "aab,bc->ac", + "ab,bcc->ac", + "aab,bcc->ac", + "baa,bcc->ac", + "aab,ccb->ac", + # Randomly build test caes + "aab,fa,df,ecc->bde", + "ecb,fef,bad,ed->ac", + "bcf,bbb,fbf,fc->", + "bb,ff,be->e", + "bcb,bb,fc,fff->", + "fbb,dfd,fc,fc->", + "afd,ba,cc,dc->bf", + "adb,bc,fa,cfc->d", + "bbd,bda,fc,db->acf", + "dba,ead,cad->bce", + "aef,fbc,dca->bde", +] + + +@pytest.mark.parametrize("optimize", (True, False, None)) +def test_contract_plain_types(optimize: OptimizeKind) -> None: + expr = "ij,jk,kl->il" + ops = [np.random.rand(2, 2), np.random.rand(2, 2), np.random.rand(2, 2)] + + path = contract_path(expr, *ops, optimize=optimize) + assert len(path) == 2 + + result = contract(expr, *ops, optimize=optimize) + assert result.shape == (2, 2) + + +@pytest.mark.parametrize("string", tests) +@pytest.mark.parametrize("optimize", _PATH_OPTIONS) +def test_compare(optimize: OptimizeKind, string: str) -> None: + views = build_views(string) + + ein = contract(string, *views, optimize=False, use_blas=False) + opt = contract(string, *views, optimize=optimize, use_blas=False) + assert np.allclose(ein, opt) + + +@pytest.mark.parametrize("string", tests) +def test_drop_in_replacement(string: str) -> None: + views = build_views(string) + opt = contract(string, *views) + assert np.allclose(opt, np.einsum(string, *views)) + + +@pytest.mark.parametrize("string", tests) +@pytest.mark.parametrize("optimize", _PATH_OPTIONS) +def test_compare_greek(optimize: OptimizeKind, string: str) -> None: + views = build_views(string) + + ein = contract(string, *views, optimize=False, use_blas=False) + + # convert to greek + string = "".join(chr(ord(c) + 848) if c not in ",->." else c for c in string) + + opt = contract(string, *views, optimize=optimize, use_blas=False) + assert np.allclose(ein, opt) + + +@pytest.mark.parametrize("string", tests) +@pytest.mark.parametrize("optimize", _PATH_OPTIONS) +def test_compare_blas(optimize: OptimizeKind, string: str) -> None: + views = build_views(string) + + ein = contract(string, *views, optimize=False) + opt = contract(string, *views, optimize=optimize) + assert np.allclose(ein, opt) + + +@pytest.mark.parametrize("string", tests) +@pytest.mark.parametrize("optimize", _PATH_OPTIONS) +def test_compare_blas_greek(optimize: OptimizeKind, string: str) -> None: + views = build_views(string) + + ein = contract(string, *views, optimize=False) + + # convert to greek + string = "".join(chr(ord(c) + 848) if c not in ",->." else c for c in string) + + opt = contract(string, *views, optimize=optimize) + assert np.allclose(ein, opt) + + +def test_some_non_alphabet_maintains_order() -> None: + # 'c beta a' should automatically go to -> 'a c beta' + string = "c" + chr(ord("b") + 848) + "a" + # but beta will be temporarily replaced with 'b' for which 'cba->abc' + # so check manual output kicks in: + x = np.random.rand(2, 3, 4) + assert np.allclose(contract(string, x), contract("cxa", x)) + + +def test_printing(): + string = "bbd,bda,fc,db->acf" + views = build_views(string) + + ein = contract_path(string, *views) + assert len(str(ein[1])) == 728 + + +@pytest.mark.parametrize("string", tests) +@pytest.mark.parametrize("optimize", _PATH_OPTIONS) +@pytest.mark.parametrize("use_blas", [False, True]) +@pytest.mark.parametrize("out_spec", [False, True]) +def test_contract_expressions(string: str, optimize: OptimizeKind, use_blas: bool, out_spec: bool) -> None: + views = build_views(string) + shapes = [view.shape if hasattr(view, "shape") else () for view in views] + expected = contract(string, *views, optimize=False, use_blas=False) + + expr = contract_expression(string, *shapes, optimize=optimize, use_blas=use_blas) + + if out_spec and ("->" in string) and (string[-2:] != "->"): + (out,) = build_views(string.split("->")[1]) + expr(*views, out=out) + else: + out = expr(*views) + + assert np.allclose(out, expected) + + # check representations + assert string in expr.__repr__() + assert string in expr.__str__() + + +def test_contract_expression_interleaved_input() -> None: + x, y, z = (np.random.randn(2, 2) for _ in "xyz") + expected = np.einsum(x, [0, 1], y, [1, 2], z, [2, 3], [3, 0]) + xshp, yshp, zshp = ((2, 2) for _ in "xyz") + expr = contract_expression(xshp, [0, 1], yshp, [1, 2], zshp, [2, 3], [3, 0]) + out = expr(x, y, z) + assert np.allclose(out, expected) + + +@pytest.mark.parametrize( + "string,constants", + [ + ("hbc,bdef,cdkj,ji,ikeh,lfo", [1, 2, 3, 4]), + ("bdef,cdkj,ji,ikeh,hbc,lfo", [0, 1, 2, 3]), + ("hbc,bdef,cdkj,ji,ikeh,lfo", [1, 2, 3, 4]), + ("hbc,bdef,cdkj,ji,ikeh,lfo", [1, 2, 3, 4]), + ("ijab,acd,bce,df,ef->ji", [1, 2, 3, 4]), + ("ab,cd,ad,cb", [1, 3]), + ("ab,bc,cd", [0, 1]), + ], +) +def test_contract_expression_with_constants(string: str, constants: List[int]) -> None: + views = build_views(string) + expected = contract(string, *views, optimize=False, use_blas=False) + + shapes = [view.shape if hasattr(view, "shape") else () for view in views] + + expr_args: List[Any] = [] + ctrc_args = [] + for i, (shape, view) in enumerate(zip(shapes, views)): + if i in constants: + expr_args.append(view) + else: + expr_args.append(shape) + ctrc_args.append(view) + + expr = contract_expression(string, *expr_args, constants=constants) + out = expr(*ctrc_args) + assert np.allclose(expected, out) + + +@pytest.mark.parametrize("optimize", ["greedy", "optimal"]) +@pytest.mark.parametrize("n", [4, 5]) +@pytest.mark.parametrize("reg", [2, 3]) +@pytest.mark.parametrize("n_out", [0, 2, 4]) +@pytest.mark.parametrize("global_dim", [False, True]) +def test_rand_equation(optimize: OptimizeKind, n: int, reg: int, n_out: int, global_dim: bool) -> None: + eq, _, size_dict = rand_equation(n, reg, n_out, d_min=2, d_max=5, seed=42, return_size_dict=True) + views = build_views(eq, size_dict) + + expected = contract(eq, *views, optimize=False) + actual = contract(eq, *views, optimize=optimize) + + assert np.allclose(expected, actual) + + +@pytest.mark.parametrize("equation", tests) +def test_linear_vs_ssa(equation: str) -> None: + views = build_views(equation) + linear_path, _ = contract_path(equation, *views) + ssa_path = linear_to_ssa(linear_path) + linear_path2 = ssa_to_linear(ssa_path) + assert linear_path2 == linear_path + + +def test_contract_path_supply_shapes() -> None: + eq = "ab,bc,cd" + shps = [(2, 3), (3, 4), (4, 5)] + contract_path(eq, *shps, shapes=True) diff --git a/infer_4_33_0/lib/python3.10/site-packages/opt_einsum/tests/test_edge_cases.py b/infer_4_33_0/lib/python3.10/site-packages/opt_einsum/tests/test_edge_cases.py new file mode 100644 index 0000000000000000000000000000000000000000..483553173e21f9e57a839bdb906d8be2b309f883 --- /dev/null +++ b/infer_4_33_0/lib/python3.10/site-packages/opt_einsum/tests/test_edge_cases.py @@ -0,0 +1,152 @@ +""" +Tets a series of opt_einsum contraction paths to ensure the results are the same for different paths +""" + +from typing import Any, Tuple + +import pytest + +from opt_einsum import contract, contract_expression, contract_path +from opt_einsum.typing import PathType + +# NumPy is required for the majority of this file +np = pytest.importorskip("numpy") + + +def test_contract_expression_checks() -> None: + # check optimize needed + with pytest.raises(ValueError): + contract_expression("ab,bc->ac", (2, 3), (3, 4), optimize=False) + + # check sizes are still checked + with pytest.raises(ValueError): + contract_expression("ab,bc->ac", (2, 3), (3, 4), (42, 42)) + + # check if out given + out = np.empty((2, 4)) + with pytest.raises(ValueError): + contract_expression("ab,bc->ac", (2, 3), (3, 4), out=out) + + # check still get errors when wrong ranks supplied to expression + expr = contract_expression("ab,bc->ac", (2, 3), (3, 4)) + + # too few arguments + with pytest.raises(ValueError) as err: + expr(np.random.rand(2, 3)) + assert "`ContractExpression` takes exactly 2" in str(err.value) + + # too many arguments + with pytest.raises(ValueError) as err: + expr(np.random.rand(2, 3), np.random.rand(2, 3), np.random.rand(2, 3)) + assert "`ContractExpression` takes exactly 2" in str(err.value) + + # wrong shapes + with pytest.raises(ValueError) as err: + expr(np.random.rand(2, 3, 4), np.random.rand(3, 4)) + assert "Internal error while evaluating `ContractExpression`" in str(err.value) + with pytest.raises(ValueError) as err: + expr(np.random.rand(2, 4), np.random.rand(3, 4, 5)) + assert "Internal error while evaluating `ContractExpression`" in str(err.value) + with pytest.raises(ValueError) as err: + expr(np.random.rand(2, 3), np.random.rand(3, 4), out=np.random.rand(2, 4, 6)) + assert "Internal error while evaluating `ContractExpression`" in str(err.value) + + # should only be able to specify out + with pytest.raises(TypeError) as err_type: + expr(np.random.rand(2, 3), np.random.rand(3, 4), order="F") # type: ignore + assert "got an unexpected keyword" in str(err_type.value) + + +def test_broadcasting_contraction() -> None: + a = np.random.rand(1, 5, 4) + b = np.random.rand(4, 6) + c = np.random.rand(5, 6) + d = np.random.rand(10) + + ein_scalar = contract("ijk,kl,jl", a, b, c, optimize=False) + opt_scalar = contract("ijk,kl,jl", a, b, c, optimize=True) + assert np.allclose(ein_scalar, opt_scalar) + + result = ein_scalar * d + + ein = contract("ijk,kl,jl,i->i", a, b, c, d, optimize=False) + opt = contract("ijk,kl,jl,i->i", a, b, c, d, optimize=True) + + assert np.allclose(ein, result) + assert np.allclose(opt, result) + + +def test_broadcasting_contraction2() -> None: + a = np.random.rand(1, 1, 5, 4) + b = np.random.rand(4, 6) + c = np.random.rand(5, 6) + d = np.random.rand(7, 7) + + ein_scalar = contract("abjk,kl,jl", a, b, c, optimize=False) + opt_scalar = contract("abjk,kl,jl", a, b, c, optimize=True) + assert np.allclose(ein_scalar, opt_scalar) + + result = ein_scalar * d + + ein = contract("abjk,kl,jl,ab->ab", a, b, c, d, optimize=False) + opt = contract("abjk,kl,jl,ab->ab", a, b, c, d, optimize=True) + + assert np.allclose(ein, result) + assert np.allclose(opt, result) + + +def test_broadcasting_contraction3() -> None: + a = np.random.rand(1, 5, 4) + b = np.random.rand(4, 1, 6) + c = np.random.rand(5, 6) + d = np.random.rand(7, 7) + + ein = contract("ajk,kbl,jl,ab->ab", a, b, c, d, optimize=False) + opt = contract("ajk,kbl,jl,ab->ab", a, b, c, d, optimize=True) + + assert np.allclose(ein, opt) + + +def test_broadcasting_contraction4() -> None: + a = np.arange(64).reshape(2, 4, 8) + ein = contract("obk,ijk->ioj", a, a, optimize=False) + opt = contract("obk,ijk->ioj", a, a, optimize=True) + + assert np.allclose(ein, opt) + + +def test_can_blas_on_healed_broadcast_dimensions() -> None: + expr = contract_expression("ab,bc,bd->acd", (5, 4), (1, 5), (4, 20)) + # first contraction involves broadcasting + assert expr.contraction_list[0][2] == "bc,ab->bca" + assert expr.contraction_list[0][-1] is False + # but then is healed GEMM is usable + assert expr.contraction_list[1][2] == "bca,bd->acd" + assert expr.contraction_list[1][-1] == "GEMM" + + +def test_pathinfo_for_empty_contraction() -> None: + eq = "->" + arrays = (1.0,) + path: PathType = [] + _, info = contract_path(eq, *arrays, optimize=path) + # some info is built lazily, so check repr + assert repr(info) + assert info.largest_intermediate == 1 + + +@pytest.mark.parametrize( + "expression, operands", + [ + [",,->", (5, 5.0, 2.0j)], + ["ab,->", ([[5, 5], [2.0, 1]], 2.0j)], + ["ab,bc->ac", ([[5, 5], [2.0, 1]], [[2.0, 1], [3.0, 4]])], + ["ab,->", ([[5, 5], [2.0, 1]], True)], + ], +) +def test_contract_with_assumed_shapes(expression: str, operands: Tuple[Any]) -> None: + """Test that we can contract with assumed shapes, and that the output is correct. This is required as we need to infer intermediate shape sizes.""" + + benchmark = np.einsum(expression, *operands) + result = contract(expression, *operands, optimize=True) + assert np.allclose(benchmark, result) diff --git a/infer_4_33_0/lib/python3.10/site-packages/opt_einsum/tests/test_input.py b/infer_4_33_0/lib/python3.10/site-packages/opt_einsum/tests/test_input.py new file mode 100644 index 0000000000000000000000000000000000000000..24b1ead3fb342204c7161759b5fdefb1a261a840 --- /dev/null +++ b/infer_4_33_0/lib/python3.10/site-packages/opt_einsum/tests/test_input.py @@ -0,0 +1,279 @@ +""" +Tests the input parsing for opt_einsum. Duplicates the np.einsum input tests. +""" + +from typing import Any, List + +import pytest + +from opt_einsum import contract, contract_path +from opt_einsum.typing import ArrayType + +np = pytest.importorskip("numpy") + + +def build_views(string: str) -> List[ArrayType]: + """Builds random numpy arrays for testing by using a fixed size dictionary and an input string.""" + + chars = "abcdefghij" + sizes_array = np.array([2, 3, 4, 5, 4, 3, 2, 6, 5, 4]) + sizes = dict(zip(chars, sizes_array)) + + views = [] + + string = string.replace("...", "ij") + + terms = string.split("->")[0].split(",") + for term in terms: + dims = [sizes[x] for x in term] + views.append(np.random.rand(*dims)) + return views + + +def test_type_errors() -> None: + # subscripts must be a string + with pytest.raises(TypeError): + contract(0, 0) + + # out parameter must be an array + with pytest.raises(TypeError): + contract("", 0, out="test") + + # order parameter must be a valid order + # changed in Numpy 1.19, see https://github.com/numpy/numpy/commit/35b0a051c19265f5643f6011ee11e31d30c8bc4c + with pytest.raises((TypeError, ValueError)): + contract("", 0, order="W") # type: ignore + + # casting parameter must be a valid casting + with pytest.raises(ValueError): + contract("", 0, casting="blah") # type: ignore + + # dtype parameter must be a valid dtype + with pytest.raises(TypeError): + contract("", 0, dtype="bad_data_type") + + # other keyword arguments are rejected + with pytest.raises(TypeError): + contract("", 0, bad_arg=0) + + # issue 4528 revealed a segfault with this call + with pytest.raises(TypeError): + contract(*(None,) * 63) + + # Cannot have two -> + with pytest.raises(ValueError): + contract("->,->", 0, 5) + + # Undefined symbol lhs + with pytest.raises(ValueError): + contract("&,a->", 0, 5) + + # Undefined symbol rhs + with pytest.raises(ValueError): + contract("a,a->&", 0, 5) + + with pytest.raises(ValueError): + contract("a,a->&", 0, 5) + + # Catch ellipsis errors + string = "...a->...a" + views = build_views(string) + + # Subscript list must contain Ellipsis or (hashable && comparable) object + with pytest.raises(TypeError): + contract(views[0], [Ellipsis, 0], [Ellipsis, ["a"]]) + + with pytest.raises(TypeError): + contract(views[0], [Ellipsis, {}], [Ellipsis, "a"]) + + +@pytest.mark.parametrize("contract_fn", [contract, contract_path]) +def test_value_errors(contract_fn: Any) -> None: + with pytest.raises(ValueError): + contract_fn("") + + # subscripts must be a string + with pytest.raises(TypeError): + contract_fn(0, 0) + + # invalid subscript character + with pytest.raises(ValueError): + contract_fn("i%...", [0, 0]) + with pytest.raises(ValueError): + contract_fn("...j$", [0, 0]) + with pytest.raises(ValueError): + contract_fn("i->&", [0, 0]) + + with pytest.raises(ValueError): + contract_fn("") + # number of operands must match count in subscripts string + with pytest.raises(ValueError): + contract_fn("", 0, 0) + with pytest.raises(ValueError): + contract_fn(",", 0, [0], [0]) + with pytest.raises(ValueError): + contract_fn(",", [0]) + + # can't have more subscripts than dimensions in the operand + with pytest.raises(ValueError): + contract_fn("i", 0) + with pytest.raises(ValueError): + contract_fn("ij", [0, 0]) + with pytest.raises(ValueError): + contract_fn("...i", 0) + with pytest.raises(ValueError): + contract_fn("i...j", [0, 0]) + with pytest.raises(ValueError): + contract_fn("i...", 0) + with pytest.raises(ValueError): + contract_fn("ij...", [0, 0]) + + # invalid ellipsis + with pytest.raises(ValueError): + contract_fn("i..", [0, 0]) + with pytest.raises(ValueError): + contract_fn(".i...", [0, 0]) + with pytest.raises(ValueError): + contract_fn("j->..j", [0, 0]) + with pytest.raises(ValueError): + contract_fn("j->.j...", [0, 0]) + + # invalid subscript character + with pytest.raises(ValueError): + contract_fn("i%...", [0, 0]) + with pytest.raises(ValueError): + contract_fn("...j$", [0, 0]) + with pytest.raises(ValueError): + contract_fn("i->&", [0, 0]) + + # output subscripts must appear in input + with pytest.raises(ValueError): + contract_fn("i->ij", [0, 0]) + + # output subscripts may only be specified once + with pytest.raises(ValueError): + contract_fn("ij->jij", [[0, 0], [0, 0]]) + + # dimensions much match when being collapsed + with pytest.raises(ValueError): + contract_fn("ii", np.arange(6).reshape(2, 3)) + with pytest.raises(ValueError): + contract_fn("ii->i", np.arange(6).reshape(2, 3)) + + # broadcasting to new dimensions must be enabled explicitly + with pytest.raises(ValueError): + contract_fn("i", np.arange(6).reshape(2, 3)) + + with pytest.raises(TypeError): + contract_fn("ij->ij", [[0, 1], [0, 1]], bad_kwarg=True) + + +@pytest.mark.parametrize( + "string", + [ + # Ellipse + "...a->...", + "a...->...", + "a...a->...a", + "...,...", + "a,b", + "...a,...b", + ], +) +def test_compare(string: str) -> None: + views = build_views(string) + + ein = contract(string, *views, optimize=False) + opt = contract(string, *views) + assert np.allclose(ein, opt) + + opt = contract(string, *views, optimize="optimal") + assert np.allclose(ein, opt) + + +def test_ellipse_input1() -> None: + string = "...a->..." + views = build_views(string) + + ein = contract(string, *views, optimize=False) + opt = contract(views[0], [Ellipsis, 0], [Ellipsis]) + assert np.allclose(ein, opt) + + +def test_ellipse_input2() -> None: + string = "...a" + views = build_views(string) + + ein = contract(string, *views, optimize=False) + opt = contract(views[0], [Ellipsis, 0]) + assert np.allclose(ein, opt) + + +def test_ellipse_input3() -> None: + string = "...a->...a" + views = build_views(string) + + ein = contract(string, *views, optimize=False) + opt = contract(views[0], [Ellipsis, 0], [Ellipsis, 0]) + assert np.allclose(ein, opt) + + +def test_ellipse_input4() -> None: + string = "...b,...a->..." + views = build_views(string) + + ein = contract(string, *views, optimize=False) + opt = contract(views[0], [Ellipsis, 1], views[1], [Ellipsis, 0], [Ellipsis]) + assert np.allclose(ein, opt) + + +def test_singleton_dimension_broadcast() -> None: + # singleton dimensions broadcast (gh-10343) + p = np.ones((10, 2)) + q = np.ones((1, 2)) + + ein = contract("ij,ij->j", p, q, optimize=False) + opt = contract("ij,ij->j", p, q, optimize=True) + assert np.allclose(ein, opt) + assert np.allclose(opt, [10.0, 10.0]) + + p = np.ones((1, 5)) + q = np.ones((5, 5)) + + for optimize in (True, False): + res1 = (contract("...ij,...jk->...ik", p, p, optimize=optimize),) + res2 = contract("...ij,...jk->...ik", p, q, optimize=optimize) + assert np.allclose(res1, res2) + assert np.allclose(res2, np.full((1, 5), 5)) + + +def test_large_int_input_format() -> None: + string = "ab,bc,cd" + x, y, z = build_views(string) + string_output = contract(string, x, y, z) + int_output = contract(x, (1000, 1001), y, (1001, 1002), z, (1002, 1003)) + assert np.allclose(string_output, int_output) + for i in range(10): + transpose_output = contract(x, (i + 1, i)) + assert np.allclose(transpose_output, x.T) + + +def test_hashable_object_input_format() -> None: + string = "ab,bc,cd" + x, y, z = build_views(string) + string_output = contract(string, x, y, z) + hash_output1 = contract(x, ("left", "bond1"), y, ("bond1", "bond2"), z, ("bond2", "right")) + hash_output2 = contract( + x, + ("left", "bond1"), + y, + ("bond1", "bond2"), + z, + ("bond2", "right"), + ("left", "right"), + ) + assert np.allclose(string_output, hash_output1) + assert np.allclose(hash_output1, hash_output2) + for i in range(1, 10): + transpose_output = contract(x, ("b" * i, "a" * i)) + assert np.allclose(transpose_output, x.T) diff --git a/infer_4_33_0/lib/python3.10/site-packages/opt_einsum/tests/test_parser.py b/infer_4_33_0/lib/python3.10/site-packages/opt_einsum/tests/test_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..b39bf8b4bdbb2b790641e51d96cd44bb5ef88762 --- /dev/null +++ b/infer_4_33_0/lib/python3.10/site-packages/opt_einsum/tests/test_parser.py @@ -0,0 +1,74 @@ +""" +Directly tests various parser utility functions. +""" + +from typing import Any, Tuple + +import pytest + +from opt_einsum.parser import get_shape, get_symbol, parse_einsum_input +from opt_einsum.testing import build_arrays_from_tuples + + +def test_get_symbol() -> None: + assert get_symbol(2) == "c" + assert get_symbol(200000) == "\U00031540" + # Ensure we skip surrogates '[\uD800-\uDFFF]' + assert get_symbol(55295) == "\ud88b" + assert get_symbol(55296) == "\ue000" + assert get_symbol(57343) == "\ue7ff" + + +def test_parse_einsum_input() -> None: + eq = "ab,bc,cd" + ops = build_arrays_from_tuples([(2, 3), (3, 4), (4, 5)]) + input_subscripts, output_subscript, operands = parse_einsum_input([eq, *ops]) + assert input_subscripts == eq + assert output_subscript == "ad" + assert operands == ops + + +def test_parse_einsum_input_shapes_error() -> None: + eq = "ab,bc,cd" + ops = build_arrays_from_tuples([(2, 3), (3, 4), (4, 5)]) + + with pytest.raises(ValueError): + _ = parse_einsum_input([eq, *ops], shapes=True) + + +def test_parse_einsum_input_shapes() -> None: + eq = "ab,bc,cd" + shapes = [(2, 3), (3, 4), (4, 5)] + input_subscripts, output_subscript, operands = parse_einsum_input([eq, *shapes], shapes=True) + assert input_subscripts == eq + assert output_subscript == "ad" + assert shapes == operands + + +def test_parse_with_ellisis() -> None: + eq = "...a,ab" + shapes = [(2, 3), (3, 4)] + input_subscripts, output_subscript, operands = parse_einsum_input([eq, *shapes], shapes=True) + assert input_subscripts == "da,ab" + assert output_subscript == "db" + assert shapes == operands + + +@pytest.mark.parametrize( + "array, shape", + [ + [[5], (1,)], + [[5, 5], (2,)], + [(5, 5), (2,)], + [[[[[[5, 2]]]]], (1, 1, 1, 1, 2)], + [[[[[["abcdef", "b"]]]]], (1, 1, 1, 1, 2)], + ["A", ()], + [b"A", ()], + [True, ()], + [5, ()], + [5.0, ()], + [5.0 + 0j, ()], + ], +) +def test_get_shapes(array: Any, shape: Tuple[int]) -> None: + assert get_shape(array) == shape diff --git a/infer_4_33_0/lib/python3.10/site-packages/opt_einsum/tests/test_paths.py b/infer_4_33_0/lib/python3.10/site-packages/opt_einsum/tests/test_paths.py new file mode 100644 index 0000000000000000000000000000000000000000..22ed1429e6bc98a9c9c3bdcff0871fae57ff647a --- /dev/null +++ b/infer_4_33_0/lib/python3.10/site-packages/opt_einsum/tests/test_paths.py @@ -0,0 +1,534 @@ +""" +Tests the accuracy of the opt_einsum paths in addition to unit tests for +the various path helper functions. +""" + +import itertools +from concurrent.futures import ProcessPoolExecutor +from typing import Any, Dict, List, Optional + +import pytest + +import opt_einsum as oe +from opt_einsum.testing import build_shapes, rand_equation +from opt_einsum.typing import ArrayIndexType, OptimizeKind, PathType, TensorShapeType + +explicit_path_tests = { + "GEMM1": ( + [set("abd"), set("ac"), set("bdc")], + set(""), + {"a": 1, "b": 2, "c": 3, "d": 4}, + ), + "Inner1": ( + [set("abcd"), set("abc"), set("bc")], + set(""), + {"a": 5, "b": 2, "c": 3, "d": 4}, + ), +} + +# note that these tests have no unique solution due to the chosen dimensions +path_edge_tests = [ + ["greedy", "eb,cb,fb->cef", ((0, 2), (0, 1))], + ["branch-all", "eb,cb,fb->cef", ((0, 2), (0, 1))], + ["branch-2", "eb,cb,fb->cef", ((0, 2), (0, 1))], + ["optimal", "eb,cb,fb->cef", ((0, 2), (0, 1))], + ["dp", "eb,cb,fb->cef", ((1, 2), (0, 1))], + ["greedy", "dd,fb,be,cdb->cef", ((0, 3), (0, 1), (0, 1))], + ["branch-all", "dd,fb,be,cdb->cef", ((0, 3), (0, 1), (0, 1))], + ["branch-2", "dd,fb,be,cdb->cef", ((0, 3), (0, 1), (0, 1))], + ["optimal", "dd,fb,be,cdb->cef", ((0, 3), (0, 1), (0, 1))], + ["optimal", "dd,fb,be,cdb->cef", ((0, 3), (0, 1), (0, 1))], + ["dp", "dd,fb,be,cdb->cef", ((0, 3), (0, 2), (0, 1))], + ["greedy", "bca,cdb,dbf,afc->", ((1, 2), (0, 2), (0, 1))], + ["branch-all", "bca,cdb,dbf,afc->", ((1, 2), (0, 2), (0, 1))], + ["branch-2", "bca,cdb,dbf,afc->", ((1, 2), (0, 2), (0, 1))], + ["optimal", "bca,cdb,dbf,afc->", ((1, 2), (0, 2), (0, 1))], + ["dp", "bca,cdb,dbf,afc->", ((1, 2), (1, 2), (0, 1))], + ["greedy", "dcc,fce,ea,dbf->ab", ((1, 2), (0, 1), (0, 1))], + ["branch-all", "dcc,fce,ea,dbf->ab", ((1, 2), (0, 2), (0, 1))], + ["branch-2", "dcc,fce,ea,dbf->ab", ((1, 2), (0, 2), (0, 1))], + ["optimal", "dcc,fce,ea,dbf->ab", ((1, 2), (0, 2), (0, 1))], + ["dp", "dcc,fce,ea,dbf->ab", ((1, 2), (0, 2), (0, 1))], +] + +# note that these tests have no unique solution due to the chosen dimensions +path_scalar_tests = [ + [ + "a,->a", + 1, + ], + ["ab,->ab", 1], + [",a,->a", 2], + [",,a,->a", 3], + [",,->", 2], +] + + +def check_path(test_output: PathType, benchmark: PathType, bypass: bool = False) -> bool: + if not isinstance(test_output, list): + return False + + if len(test_output) != len(benchmark): + return False + + ret = True + for pos in range(len(test_output)): + ret &= isinstance(test_output[pos], tuple) + ret &= test_output[pos] == list(benchmark)[pos] + return ret + + +def assert_contract_order(func: Any, test_data: Any, max_size: int, benchmark: PathType) -> None: + test_output = func(test_data[0], test_data[1], test_data[2], max_size) + assert check_path(test_output, benchmark) + + +def test_size_by_dict() -> None: + sizes_dict = {} + for ind, val in zip("abcdez", [2, 5, 9, 11, 13, 0]): + sizes_dict[ind] = val + + path_func = oe.helpers.compute_size_by_dict + + assert 1 == path_func("", sizes_dict) + assert 2 == path_func("a", sizes_dict) + assert 5 == path_func("b", sizes_dict) + + assert 0 == path_func("z", sizes_dict) + assert 0 == path_func("az", sizes_dict) + assert 0 == path_func("zbc", sizes_dict) + + assert 104 == path_func("aaae", sizes_dict) + assert 12870 == path_func("abcde", sizes_dict) + + +def test_flop_cost() -> None: + size_dict = {v: 10 for v in "abcdef"} + + # Loop over an array + assert 10 == oe.helpers.flop_count("a", False, 1, size_dict) + + # Hadamard product (*) + assert 10 == oe.helpers.flop_count("a", False, 2, size_dict) + assert 100 == oe.helpers.flop_count("ab", False, 2, size_dict) + + # Inner product (+, *) + assert 20 == oe.helpers.flop_count("a", True, 2, size_dict) + assert 200 == oe.helpers.flop_count("ab", True, 2, size_dict) + + # Inner product x3 (+, *, *) + assert 30 == oe.helpers.flop_count("a", True, 3, size_dict) + + # GEMM + assert 2000 == oe.helpers.flop_count("abc", True, 2, size_dict) + + +def test_bad_path_option() -> None: + with pytest.raises(KeyError): + oe.contract("a,b,c", [1], [2], [3], optimize="optimall", shapes=True) # type: ignore + + +def test_explicit_path() -> None: + pytest.importorskip("numpy") + x = oe.contract("a,b,c", [1], [2], [3], optimize=[(1, 2), (0, 1)]) + assert x.item() == 6 + + +def test_path_optimal() -> None: + test_func = oe.paths.optimal + + test_data = explicit_path_tests["GEMM1"] + assert_contract_order(test_func, test_data, 5000, [(0, 2), (0, 1)]) + assert_contract_order(test_func, test_data, 0, [(0, 1, 2)]) + + +def test_path_greedy() -> None: + test_func = oe.paths.greedy + + test_data = explicit_path_tests["GEMM1"] + assert_contract_order(test_func, test_data, 5000, [(0, 2), (0, 1)]) + assert_contract_order(test_func, test_data, 0, [(0, 1, 2)]) + + +def test_memory_paths() -> None: + expression = "abc,bdef,fghj,cem,mhk,ljk->adgl" + + views = build_shapes(expression) + + # Test tiny memory limit + path_ret = oe.contract_path(expression, *views, optimize="optimal", memory_limit=5, shapes=True) + assert check_path(path_ret[0], [(0, 1, 2, 3, 4, 5)]) + + path_ret = oe.contract_path(expression, *views, optimize="greedy", memory_limit=5, shapes=True) + assert check_path(path_ret[0], [(0, 1, 2, 3, 4, 5)]) + + # Check the possibilities, greedy is capped + path_ret = oe.contract_path(expression, *views, optimize="optimal", memory_limit=-1, shapes=True) + assert check_path(path_ret[0], [(0, 3), (0, 4), (0, 2), (0, 2), (0, 1)]) + + path_ret = oe.contract_path(expression, *views, optimize="greedy", memory_limit=-1, shapes=True) + assert check_path(path_ret[0], [(0, 3), (0, 4), (0, 2), (0, 2), (0, 1)]) + + +@pytest.mark.parametrize("alg,expression,order", path_edge_tests) +def test_path_edge_cases(alg: OptimizeKind, expression: str, order: PathType) -> None: + views = build_shapes(expression) + + # Test tiny memory limit + path_ret = oe.contract_path(expression, *views, optimize=alg, shapes=True) + assert check_path(path_ret[0], order) + + +@pytest.mark.parametrize("expression,order", path_scalar_tests) +@pytest.mark.parametrize("alg", oe.paths._PATH_OPTIONS) +def test_path_scalar_cases(alg: OptimizeKind, expression: str, order: PathType) -> None: + views = build_shapes(expression) + + # Test tiny memory limit + path_ret = oe.contract_path(expression, *views, optimize=alg, shapes=True) + # print(path_ret[0]) + assert len(path_ret[0]) == order + + +def test_optimal_edge_cases() -> None: + # Edge test5 + expression = "a,ac,ab,ad,cd,bd,bc->" + edge_test4 = build_shapes(expression, dimension_dict={"a": 20, "b": 20, "c": 20, "d": 20}) + path, _ = oe.contract_path(expression, *edge_test4, optimize="greedy", memory_limit="max_input", shapes=True) + assert check_path(path, [(0, 1), (0, 1, 2, 3, 4, 5)]) + + path, _ = oe.contract_path(expression, *edge_test4, optimize="optimal", memory_limit="max_input", shapes=True) + assert check_path(path, [(0, 1), (0, 1, 2, 3, 4, 5)]) + + +def test_greedy_edge_cases() -> None: + expression = "abc,cfd,dbe,efa" + dim_dict = {k: 20 for k in expression.replace(",", "")} + tensors = build_shapes(expression, dimension_dict=dim_dict) + + path, _ = oe.contract_path(expression, *tensors, optimize="greedy", memory_limit="max_input", shapes=True) + assert check_path(path, [(0, 1, 2, 3)]) + + path, _ = oe.contract_path(expression, *tensors, optimize="greedy", memory_limit=-1, shapes=True) + assert check_path(path, [(0, 1), (0, 2), (0, 1)]) + + +def test_dp_edge_cases_dimension_1() -> None: + eq = "nlp,nlq,pl->n" + shapes = [(1, 1, 1), (1, 1, 1), (1, 1)] + info = oe.contract_path(eq, *shapes, shapes=True, optimize="dp")[1] + assert max(info.scale_list) == 3 + + +def test_dp_edge_cases_all_singlet_indices() -> None: + eq = "a,bcd,efg->" + shapes = [(2,), (2, 2, 2), (2, 2, 2)] + info = oe.contract_path(eq, *shapes, shapes=True, optimize="dp")[1] + assert max(info.scale_list) == 3 + + +def test_custom_dp_can_optimize_for_outer_products() -> None: + eq = "a,b,abc->c" + + da, db, dc = 2, 2, 3 + shapes = [(da,), (db,), (da, db, dc)] + + opt1 = oe.DynamicProgramming(search_outer=False) + opt2 = oe.DynamicProgramming(search_outer=True) + + info1 = oe.contract_path(eq, *shapes, shapes=True, optimize=opt1)[1] + info2 = oe.contract_path(eq, *shapes, shapes=True, optimize=opt2)[1] + + assert info2.opt_cost < info1.opt_cost + + +def test_custom_dp_can_optimize_for_size() -> None: + eq, shapes = rand_equation(10, 4, seed=43) + + opt1 = oe.DynamicProgramming(minimize="flops") + opt2 = oe.DynamicProgramming(minimize="size") + + info1 = oe.contract_path(eq, *shapes, shapes=True, optimize=opt1)[1] + info2 = oe.contract_path(eq, *shapes, shapes=True, optimize=opt2)[1] + + assert info1.opt_cost < info2.opt_cost + assert info1.largest_intermediate > info2.largest_intermediate + + +def test_custom_dp_can_set_cost_cap() -> None: + eq, shapes = rand_equation(5, 3, seed=42) + opt1 = oe.DynamicProgramming(cost_cap=True) + opt2 = oe.DynamicProgramming(cost_cap=False) + opt3 = oe.DynamicProgramming(cost_cap=100) + info1 = oe.contract_path(eq, *shapes, shapes=True, optimize=opt1)[1] + info2 = oe.contract_path(eq, *shapes, shapes=True, optimize=opt2)[1] + info3 = oe.contract_path(eq, *shapes, shapes=True, optimize=opt3)[1] + assert info1.opt_cost == info2.opt_cost == info3.opt_cost + + +@pytest.mark.parametrize( + "minimize,cost,width,path", + [ + ("flops", 663054, 18900, [(4, 5), (2, 5), (2, 7), (5, 6), (1, 5), (1, 4), (0, 3), (0, 2), (0, 1)]), + ("size", 1114440, 2016, [(2, 7), (3, 8), (3, 7), (2, 6), (1, 5), (1, 4), (1, 3), (1, 2), (0, 1)]), + ("write", 983790, 2016, [(0, 8), (3, 4), (1, 4), (5, 6), (1, 5), (0, 4), (0, 3), (1, 2), (0, 1)]), + ("combo", 973518, 2016, [(4, 5), (2, 5), (6, 7), (2, 6), (1, 5), (1, 4), (0, 3), (0, 2), (0, 1)]), + ("limit", 983832, 2016, [(2, 7), (3, 4), (0, 4), (3, 6), (2, 5), (0, 4), (0, 3), (1, 2), (0, 1)]), + ("combo-256", 983790, 2016, [(0, 8), (3, 4), (1, 4), (5, 6), (1, 5), (0, 4), (0, 3), (1, 2), (0, 1)]), + ("limit-256", 983832, 2016, [(2, 7), (3, 4), (0, 4), (3, 6), (2, 5), (0, 4), (0, 3), (1, 2), (0, 1)]), + ], +) +def test_custom_dp_can_set_minimize(minimize: str, cost: int, width: int, path: PathType) -> None: + eq, shapes = rand_equation(10, 4, seed=43) + opt = oe.DynamicProgramming(minimize=minimize) + info = oe.contract_path(eq, *shapes, shapes=True, optimize=opt)[1] + assert info.path == path + assert info.opt_cost == cost + assert info.largest_intermediate == width + + +def test_dp_errors_when_no_contractions_found() -> None: + eq, shapes = rand_equation(10, 3, seed=42) + + # first get the actual minimum cost + opt = oe.DynamicProgramming(minimize="size") + _, info = oe.contract_path(eq, *shapes, shapes=True, optimize=opt) + mincost = info.largest_intermediate + + # check we can still find it without minimizing size explicitly + oe.contract_path(eq, *shapes, shapes=True, memory_limit=mincost, optimize="dp") + + # but check just below this threshold raises + with pytest.raises(RuntimeError): + oe.contract_path(eq, *shapes, shapes=True, memory_limit=mincost - 1, optimize="dp") + + +@pytest.mark.parametrize("optimize", ["greedy", "branch-2", "branch-all", "optimal", "dp"]) +def test_can_optimize_outer_products(optimize: OptimizeKind) -> None: + a, b, c = ((10, 10) for _ in range(3)) + d = (10, 2) + + assert oe.contract_path("ab,cd,ef,fg", a, b, c, d, optimize=optimize, shapes=True)[0] == [ + (2, 3), + (0, 2), + (0, 1), + ] + + +@pytest.mark.parametrize("num_symbols", [2, 3, 26, 26 + 26, 256 - 140, 300]) +def test_large_path(num_symbols: int) -> None: + symbols = "".join(oe.get_symbol(i) for i in range(num_symbols)) + dimension_dict = dict(zip(symbols, itertools.cycle([2, 3, 4]))) + expression = ",".join(symbols[t : t + 2] for t in range(num_symbols - 1)) + tensors = build_shapes(expression, dimension_dict=dimension_dict) + + # Check that path construction does not crash + oe.contract_path(expression, *tensors, optimize="greedy", shapes=True) + + +def test_custom_random_greedy() -> None: + np = pytest.importorskip("numpy") + + eq, shapes = rand_equation(10, 4, seed=42) + views = list(map(np.ones, shapes)) + + with pytest.raises(ValueError): + oe.RandomGreedy(minimize="something") + + optimizer = oe.RandomGreedy(max_repeats=10, minimize="flops") + path, path_info = oe.contract_path(eq, *views, optimize=optimizer) + + assert len(optimizer.costs) == 10 + assert len(optimizer.sizes) == 10 + + assert path == optimizer.path + assert optimizer.best["flops"] == min(optimizer.costs) + assert path_info.largest_intermediate == optimizer.best["size"] + assert path_info.opt_cost == optimizer.best["flops"] + + # check can change settings and run again + optimizer.temperature = 0.0 + optimizer.max_repeats = 6 + path, path_info = oe.contract_path(eq, *views, optimize=optimizer) + + assert len(optimizer.costs) == 16 + assert len(optimizer.sizes) == 16 + + assert path == optimizer.path + assert optimizer.best["size"] == min(optimizer.sizes) + assert path_info.largest_intermediate == optimizer.best["size"] + assert path_info.opt_cost == optimizer.best["flops"] + + # check error if we try and reuse the optimizer on a different expression + eq, shapes = rand_equation(10, 4, seed=41) + views = list(map(np.ones, shapes)) + with pytest.raises(ValueError): + path, path_info = oe.contract_path(eq, *views, optimize=optimizer) + + +def test_custom_branchbound() -> None: + np = pytest.importorskip("numpy") + + eq, shapes = rand_equation(8, 4, seed=42) + views = list(map(np.ones, shapes)) + optimizer = oe.BranchBound(nbranch=2, cutoff_flops_factor=10, minimize="size") + + path, path_info = oe.contract_path(eq, *views, optimize=optimizer) + + assert path == optimizer.path + assert path_info.largest_intermediate == optimizer.best["size"] + assert path_info.opt_cost == optimizer.best["flops"] + + # tweak settings and run again + optimizer.nbranch = 3 + optimizer.cutoff_flops_factor = 4 + path, path_info = oe.contract_path(eq, *views, optimize=optimizer) + + assert path == optimizer.path + assert path_info.largest_intermediate == optimizer.best["size"] + assert path_info.opt_cost == optimizer.best["flops"] + + # check error if we try and reuse the optimizer on a different expression + eq, shapes = rand_equation(8, 4, seed=41) + views = list(map(np.ones, shapes)) + with pytest.raises(ValueError): + path, path_info = oe.contract_path(eq, *views, optimize=optimizer) + + +def test_branchbound_validation() -> None: + with pytest.raises(ValueError): + oe.BranchBound(nbranch=0) + + +def test_parallel_random_greedy() -> None: + np = pytest.importorskip("numpy") + + pool = ProcessPoolExecutor(2) + + eq, shapes = rand_equation(10, 4, seed=42) + views = list(map(np.ones, shapes)) + + optimizer = oe.RandomGreedy(max_repeats=10, parallel=pool) + path, path_info = oe.contract_path(eq, *views, optimize=optimizer) + + assert len(optimizer.costs) == 10 + assert len(optimizer.sizes) == 10 + + assert path == optimizer.path + assert optimizer.parallel is pool + assert optimizer._executor is pool + assert optimizer.best["flops"] == min(optimizer.costs) + assert path_info.largest_intermediate == optimizer.best["size"] + assert path_info.opt_cost == optimizer.best["flops"] + + # now switch to max time algorithm + optimizer.max_repeats = int(1e6) + optimizer.max_time = 0.2 + optimizer.parallel = 2 + + path, path_info = oe.contract_path(eq, *views, optimize=optimizer) + + assert len(optimizer.costs) > 10 + assert len(optimizer.sizes) > 10 + + assert path == optimizer.path + assert optimizer.best["flops"] == min(optimizer.costs) + assert path_info.largest_intermediate == optimizer.best["size"] + assert path_info.opt_cost == optimizer.best["flops"] + + optimizer.parallel = True + assert optimizer._executor is not None + assert optimizer._executor is not pool + + are_done = [f.running() or f.done() for f in optimizer._futures] + assert all(are_done) + + +def test_custom_path_optimizer() -> None: + np = pytest.importorskip("numpy") + + class NaiveOptimizer(oe.paths.PathOptimizer): + def __call__( + self, + inputs: List[ArrayIndexType], + output: ArrayIndexType, + size_dict: Dict[str, int], + memory_limit: Optional[int] = None, + ) -> PathType: + self.was_used = True + return [(0, 1)] * (len(inputs) - 1) + + eq, shapes = rand_equation(5, 3, seed=42, d_max=3) + views = list(map(np.ones, shapes)) + + exp = oe.contract(eq, *views, optimize=False) + + optimizer = NaiveOptimizer() + out = oe.contract(eq, *views, optimize=optimizer) + assert exp == out + assert optimizer.was_used + + +def test_custom_random_optimizer() -> None: + np = pytest.importorskip("numpy") + + class NaiveRandomOptimizer(oe.path_random.RandomOptimizer): + @staticmethod + def random_path( + r: int, n: int, inputs: List[ArrayIndexType], output: ArrayIndexType, size_dict: Dict[str, int] + ) -> Any: + """Picks a completely random contraction order.""" + np.random.seed(r) + ssa_path: List[TensorShapeType] = [] + remaining = set(range(n)) + while len(remaining) > 1: + i, j = np.random.choice(list(remaining), size=2, replace=False) + remaining.add(n + len(ssa_path)) + remaining.remove(i) + remaining.remove(j) + ssa_path.append((i, j)) + cost, size = oe.path_random.ssa_path_compute_cost(ssa_path, inputs, output, size_dict) + return ssa_path, cost, size + + def setup(self, inputs: Any, output: Any, size_dict: Any) -> Any: + self.was_used = True + n = len(inputs) + trial_fn = self.random_path + trial_args = (n, inputs, output, size_dict) + return trial_fn, trial_args + + eq, shapes = rand_equation(5, 3, seed=42, d_max=3) + views = list(map(np.ones, shapes)) + + exp = oe.contract(eq, *views, optimize=False) + + optimizer = NaiveRandomOptimizer(max_repeats=16) + out = oe.contract(eq, *views, optimize=optimizer) + assert exp == out + assert optimizer.was_used + + assert len(optimizer.costs) == 16 + + +def test_optimizer_registration() -> None: + def custom_optimizer( + inputs: List[ArrayIndexType], output: ArrayIndexType, size_dict: Dict[str, int], memory_limit: Optional[int] + ) -> PathType: + return [(0, 1)] * (len(inputs) - 1) + + with pytest.raises(KeyError): + oe.paths.register_path_fn("optimal", custom_optimizer) + + oe.paths.register_path_fn("custom", custom_optimizer) + assert "custom" in oe.paths._PATH_OPTIONS + + eq = "ab,bc,cd" + shapes = [(2, 3), (3, 4), (4, 5)] + path, _ = oe.contract_path(eq, *shapes, shapes=True, optimize="custom") # type: ignore + assert path == [(0, 1), (0, 1)] + del oe.paths._PATH_OPTIONS["custom"] + + +def test_path_with_assumed_shapes() -> None: + path, _ = oe.contract_path("ab,bc,cd", [[5, 3]], [[2], [4]], [[3, 2]]) + assert path == [(0, 1), (0, 1)] diff --git a/infer_4_33_0/lib/python3.10/site-packages/opt_einsum/tests/test_sharing.py b/infer_4_33_0/lib/python3.10/site-packages/opt_einsum/tests/test_sharing.py new file mode 100644 index 0000000000000000000000000000000000000000..8b0f1c08e521b14c2e0c74015b1b0b6b46cf982a --- /dev/null +++ b/infer_4_33_0/lib/python3.10/site-packages/opt_einsum/tests/test_sharing.py @@ -0,0 +1,390 @@ +import itertools +import weakref +from collections import Counter +from typing import Any + +import pytest + +from opt_einsum import contract, contract_expression, contract_path, get_symbol, shared_intermediates +from opt_einsum.backends import to_cupy, to_torch +from opt_einsum.contract import _einsum +from opt_einsum.parser import parse_einsum_input +from opt_einsum.sharing import count_cached_ops, currently_sharing, get_sharing_cache +from opt_einsum.testing import build_views +from opt_einsum.typing import BackendType + +pytest.importorskip("numpy") + +try: + import numpy as np # type: ignore + + numpy_if_found = "numpy" +except ImportError: + numpy_if_found = pytest.param("numpy", marks=[pytest.mark.skip(reason="NumPy not installed.")]) # type: ignore + +try: + import cupy # noqa + + cupy_if_found = "cupy" +except ImportError: + cupy_if_found = pytest.param("cupy", marks=[pytest.mark.skip(reason="CuPy not installed.")]) # type: ignore + +try: + import torch # type: ignore # noqa + + torch_if_found = "torch" +except ImportError: + torch_if_found = pytest.param("torch", marks=[pytest.mark.skip(reason="PyTorch not installed.")]) # type: ignore + +backends = [numpy_if_found, torch_if_found, cupy_if_found] +equations = [ + "ab,bc->ca", + "abc,bcd,dea", + "abc,def->fedcba", + "abc,bcd,df->fa", + # test 'prefer einsum' ops + "ijk,ikj", + "i,j->ij", + "ijk,k->ij", + "AB,BC->CA", +] +to_backend = { + "numpy": lambda x: x, + "torch": to_torch, + "cupy": to_cupy, +} + + +@pytest.mark.parametrize("eq", equations) +@pytest.mark.parametrize("backend", backends) +def test_sharing_value(eq: str, backend: BackendType) -> None: + views = build_views(eq) + shapes = [v.shape for v in views] + expr = contract_expression(eq, *shapes) + + expected = expr(*views, backend=backend) + with shared_intermediates(): + actual = expr(*views, backend=backend) + + assert (actual == expected).all() + + +@pytest.mark.parametrize("backend", backends) +def test_complete_sharing(backend: BackendType) -> None: + eq = "ab,bc,cd->" + views = build_views(eq) + expr = contract_expression(eq, *(v.shape for v in views)) + + print("-" * 40) + print("Without sharing:") + with shared_intermediates() as cache: + expr(*views, backend=backend) + expected = count_cached_ops(cache) + + print("-" * 40) + print("With sharing:") + with shared_intermediates() as cache: + expr(*views, backend=backend) + expr(*views, backend=backend) + actual = count_cached_ops(cache) + + print("-" * 40) + print(f"Without sharing: {expected} expressions") + print(f"With sharing: {actual} expressions") + assert actual == expected + + +@pytest.mark.parametrize("backend", backends) +def test_sharing_reused_cache(backend: BackendType) -> None: + eq = "ab,bc,cd->" + views = build_views(eq) + expr = contract_expression(eq, *(v.shape for v in views)) + + print("-" * 40) + print("Without sharing:") + with shared_intermediates() as cache: + expr(*views, backend=backend) + expected = count_cached_ops(cache) + + print("-" * 40) + print("With sharing:") + with shared_intermediates() as cache: + expr(*views, backend=backend) + with shared_intermediates(cache): + expr(*views, backend=backend) + actual = count_cached_ops(cache) + + print("-" * 40) + print(f"Without sharing: {expected} expressions") + print(f"With sharing: {actual} expressions") + assert actual == expected + + +@pytest.mark.parametrize("backend", backends) +def test_no_sharing_separate_cache(backend: BackendType) -> None: + eq = "ab,bc,cd->" + views = build_views(eq) + expr = contract_expression(eq, *(v.shape for v in views)) + + print("-" * 40) + print("Without sharing:") + with shared_intermediates() as cache: + expr(*views, backend=backend) + expected = count_cached_ops(cache) + expected.update(count_cached_ops(cache)) # we expect double + + print("-" * 40) + print("With sharing:") + with shared_intermediates() as cache1: + expr(*views, backend=backend) + actual = count_cached_ops(cache1) + with shared_intermediates() as cache2: + expr(*views, backend=backend) + actual.update(count_cached_ops(cache2)) + + print("-" * 40) + print(f"Without sharing: {expected} expressions") + print(f"With sharing: {actual} expressions") + assert actual == expected + + +@pytest.mark.parametrize("backend", backends) +def test_sharing_nesting(backend: BackendType) -> None: + eqs = ["ab,bc,cd->a", "ab,bc,cd->b", "ab,bc,cd->c", "ab,bc,cd->c"] + views = build_views(eqs[0]) + shapes = [v.shape for v in views] + refs: Any = weakref.WeakValueDictionary() + + def method1(views): + with shared_intermediates(): + w = contract_expression(eqs[0], *shapes)(*views, backend=backend) + x = contract_expression(eqs[2], *shapes)(*views, backend=backend) + result = contract_expression("a,b->", w.shape, x.shape)(w, x, backend=backend) + refs["w"] = w + refs["x"] = x + del w, x + assert "w" in refs + assert "x" in refs + assert "w" not in refs, "cache leakage" + assert "x" not in refs, "cache leakage" + return result + + def method2(views): + with shared_intermediates(): + y = contract_expression(eqs[2], *shapes)(*views, backend=backend) + z = contract_expression(eqs[3], *shapes)(*views, backend=backend) + refs["y"] = y + refs["z"] = z + result = contract_expression("c,d->", y.shape, z.shape)(y, z, backend=backend) + result = result + method1(views) # nest method1 in method2 + del y, z + assert "y" in refs + assert "z" in refs + assert "y" not in refs + assert "z" not in refs + + method1(views) + method2(views) + + +@pytest.mark.parametrize("eq", equations) +@pytest.mark.parametrize("backend", backends) +def test_sharing_modulo_commutativity(eq: str, backend: BackendType) -> None: + ops = tuple(to_backend[backend](x) for x in build_views(eq)) + inputs, output, _ = parse_einsum_input([eq] + list(ops)) + inputs_list = inputs.split(",") + + print("-" * 40) + print("Without sharing:") + with shared_intermediates() as cache: + _einsum(eq, *ops, backend=backend) + expected = count_cached_ops(cache) + + print("-" * 40) + print("With sharing:") + with shared_intermediates() as cache: + for permuted in itertools.permutations(zip(inputs_list, ops)): + permuted_inputs = [p[0] for p in permuted] + permuted_ops = [p[1] for p in permuted] + permuted_eq = "{}->{}".format(",".join(permuted_inputs), output) + _einsum(permuted_eq, *permuted_ops, backend=backend) + actual = count_cached_ops(cache) + + print("-" * 40) + print(f"Without sharing: {expected} expressions") + print(f"With sharing: {actual} expressions") + assert actual == expected + + +@pytest.mark.parametrize("backend", backends) +def test_partial_sharing(backend: BackendType) -> None: + eq = "ab,bc,de->" + x, y, z1 = build_views(eq) # type: ignore + z2 = 2.0 * z1 - 1.0 + expr = contract_expression(eq, x.shape, y.shape, z1.shape) + + print("-" * 40) + print("Without sharing:") + num_exprs_nosharing: Any = Counter() + with shared_intermediates() as cache: + expr(x, y, z1, backend=backend) + num_exprs_nosharing.update(count_cached_ops(cache)) + with shared_intermediates() as cache: + expr(x, y, z2, backend=backend) + num_exprs_nosharing.update(count_cached_ops(cache)) + + print("-" * 40) + print("With sharing:") + with shared_intermediates() as cache: + expr(x, y, z1, backend=backend) + expr(x, y, z2, backend=backend) + num_exprs_sharing = count_cached_ops(cache) + + print("-" * 40) + print(f"Without sharing: {num_exprs_nosharing} expressions") + print(f"With sharing: {num_exprs_sharing} expressions") + assert num_exprs_nosharing["einsum"] > num_exprs_sharing["einsum"] + + +@pytest.mark.parametrize("backend", backends) +def test_sharing_with_constants(backend: BackendType) -> None: + inputs = "ij,jk,kl" + outputs = "ijkl" + equations = [f"{inputs}->{output}" for output in outputs] + shapes = (2, 3), (3, 4), (4, 5) + constants = {0, 2} + ops = [np.random.rand(*shp) if i in constants else shp for i, shp in enumerate(shapes)] + var = np.random.rand(*shapes[1]) + + expected = [contract_expression(eq, *shapes)(ops[0], var, ops[2]) for eq in equations] + + with shared_intermediates(): + actual = [contract_expression(eq, *ops, constants=constants)(var) for eq in equations] + + for dim, expected_dim, actual_dim in zip(outputs, expected, actual): + assert np.allclose(expected_dim, actual_dim), f"error at {dim}" + + +@pytest.mark.parametrize("size", [3, 4, 5]) +@pytest.mark.parametrize("backend", backends) +def test_chain(size: int, backend: BackendType) -> None: + xs = [np.random.rand(2, 2) for _ in range(size)] + shapes = [x.shape for x in xs] + alphabet = "".join(get_symbol(i) for i in range(size + 1)) + names = [alphabet[i : i + 2] for i in range(size)] + inputs = ",".join(names) + + with shared_intermediates(): + print(inputs) + for i in range(size + 1): + target = alphabet[i] + eq = f"{inputs}->{target}" + path_info = contract_path(eq, *xs) + print(path_info[1]) + expr = contract_expression(eq, *shapes) + expr(*xs, backend=backend) + print("-" * 40) + + +@pytest.mark.parametrize("size", [3, 4, 5, 10]) +@pytest.mark.parametrize("backend", backends) +def test_chain_2(size: int, backend: BackendType) -> None: + xs = [np.random.rand(2, 2) for _ in range(size)] + shapes = [x.shape for x in xs] + alphabet = "".join(get_symbol(i) for i in range(size + 1)) + names = [alphabet[i : i + 2] for i in range(size)] + inputs = ",".join(names) + + with shared_intermediates(): + print(inputs) + for i in range(size): + target = alphabet[i : i + 2] + eq = f"{inputs}->{target}" + path_info = contract_path(eq, *xs) + print(path_info[1]) + expr = contract_expression(eq, *shapes) + expr(*xs, backend=backend) + print("-" * 40) + + +def _compute_cost(cache): + counts = count_cached_ops(cache) + return counts["einsum"] + counts["tensordot"] + + +@pytest.mark.parametrize("backend", backends) +def test_chain_2_growth(backend: BackendType) -> None: + sizes = list(range(1, 21)) + costs = [] + for size in sizes: + xs = [np.random.rand(2, 2) for _ in range(size)] + alphabet = "".join(get_symbol(i) for i in range(size + 1)) + names = [alphabet[i : i + 2] for i in range(size)] + inputs = ",".join(names) + + with shared_intermediates() as cache: + for i in range(size): + target = alphabet[i : i + 2] + eq = f"{inputs}->{target}" + expr = contract_expression(eq, *(x.shape for x in xs)) + expr(*xs, backend=backend) + costs.append(_compute_cost(cache)) + + print(f"sizes = {repr(sizes)}") + print(f"costs = {repr(costs)}") + for size, cost in zip(sizes, costs): + print(f"{size}\t{cost}") + + +@pytest.mark.parametrize("size", [3, 4, 5]) +@pytest.mark.parametrize("backend", backends) +def test_chain_sharing(size: int, backend: BackendType) -> None: + xs = [np.random.rand(2, 2) for _ in range(size)] + alphabet = "".join(get_symbol(i) for i in range(size + 1)) + names = [alphabet[i : i + 2] for i in range(size)] + inputs = ",".join(names) + + num_exprs_nosharing = 0 + for i in range(size + 1): + with shared_intermediates() as cache: + target = alphabet[i] + eq = f"{inputs}->{target}" + expr = contract_expression(eq, *tuple(x.shape for x in xs)) + expr(*xs, backend=backend) + num_exprs_nosharing += _compute_cost(cache) + + with shared_intermediates() as cache: + print(inputs) + for i in range(size + 1): + target = alphabet[i] + eq = f"{inputs}->{target}" + path_info = contract_path(eq, *xs) + print(path_info[1]) + expr = contract_expression(eq, *[x.shape for x in xs]) + expr(*xs, backend=backend) + num_exprs_sharing = _compute_cost(cache) + + print("-" * 40) + print(f"Without sharing: {num_exprs_nosharing} expressions") + print(f"With sharing: {num_exprs_sharing} expressions") + assert num_exprs_nosharing > num_exprs_sharing + + +def test_multithreaded_sharing() -> None: + from multiprocessing.pool import ThreadPool + + def fn(): + x, y, z = build_views("ab,bc,cd") + + with shared_intermediates(): + contract("ab,bc,cd->a", x, y, z) + contract("ab,bc,cd->b", x, y, z) + + return len(get_sharing_cache()) + + expected = fn() + pool = ThreadPool(8) + fs = [pool.apply_async(fn) for _ in range(16)] + assert not currently_sharing() + assert [f.get() for f in fs] == [expected] * 16 + pool.close()