diff --git a/.gitattributes b/.gitattributes
index 71166666601fbf6fd1fc99627f3d3107faa202c7..97bca66ccf5549b29436ce054badaf8bb687777a 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -3915,3 +3915,32 @@ tool_server/.venv/lib/python3.12/site-packages/click/__pycache__/core.cpython-31
tool_server/.venv/lib/python3.12/site-packages/anyio/_backends/__pycache__/_asyncio.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
tool_server/.venv/lib/python3.12/site-packages/pydantic/__pycache__/json_schema.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
tool_server/.venv/lib/python3.12/site-packages/pydantic/_internal/__pycache__/_generate_schema.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
+tool_server/.venv/lib/python3.12/site-packages/numba/core/runtime/_nrt_python.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
+tool_server/.venv/lib/python3.12/site-packages/numba/core/typeconv/_typeconv.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
+tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/byteflow.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
+tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/pythonapi.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
+tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/ir_utils.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
+tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/interpreter.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
+tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/randomimpl.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
+tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/unicode.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
+tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/__pycache__/driver.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
+tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_atomics.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
+tool_server/.venv/lib/python3.12/site-packages/numba/np/ufunc/_internal.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
+tool_server/.venv/lib/python3.12/site-packages/numba/np/ufunc/omppool.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
+tool_server/.venv/lib/python3.12/site-packages/numba/np/ufunc/tbbpool.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
+tool_server/.venv/lib/python3.12/site-packages/numba/np/ufunc/workqueue.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
+tool_server/.venv/lib/python3.12/site-packages/numba/np/__pycache__/arrayobj.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
+tool_server/.venv/lib/python3.12/site-packages/numba/np/__pycache__/linalg.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
+tool_server/.venv/lib/python3.12/site-packages/numba/np/__pycache__/new_arraymath.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
+tool_server/.venv/lib/python3.12/site-packages/numba/np/__pycache__/old_arraymath.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
+tool_server/.venv/lib/python3.12/site-packages/numba/parfors/__pycache__/array_analysis.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
+tool_server/.venv/lib/python3.12/site-packages/numba/parfors/__pycache__/parfor.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
+tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_array_methods.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
+tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_dictobject.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
+tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_dyn_array.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
+tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_extending.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
+tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_np_functions.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
+tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_jitclasses.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
+tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_linalg.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
+tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_lists.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
+tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_ufuncs.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..384ca0695da761425978c6d1e8f9602344741702
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/__pycache__/__main__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/__pycache__/__main__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4389984bb0d66ac62ef3710088bbc4c3dacb6b35
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/__pycache__/__main__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/__pycache__/_version.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/__pycache__/_version.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7edbfe71ea8684f25671bcbd358f3d53edb7c714
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/__pycache__/_version.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/__pycache__/extending.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/__pycache__/extending.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..31db485dbc67f0de5923b5d1b769c9937dbea52c
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/__pycache__/extending.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/__pycache__/runtests.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/__pycache__/runtests.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4c2585d3eedd108d96d184441dd90166fa46edec
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/__pycache__/runtests.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cext/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cext/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e66420f0327eeeca5e6779849f9519ab64b23718
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cext/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cloudpickle/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cloudpickle/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..43d298a11e3c7b77798c7f0d924e7699e0e55ff6
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cloudpickle/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cloudpickle/__pycache__/cloudpickle.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cloudpickle/__pycache__/cloudpickle.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..61ac0ed6a29bf0b0789828a216fbf983a5997d16
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cloudpickle/__pycache__/cloudpickle.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cloudpickle/__pycache__/cloudpickle_fast.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cloudpickle/__pycache__/cloudpickle_fast.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..49f2851b5689279907f538465b27e747afbb9dc3
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cloudpickle/__pycache__/cloudpickle_fast.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fe1beac8df4161690fb4cf0d10bb3ea68346eb27
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/analysis.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/analysis.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..37674e3ed55d0407633eef0ec178b04ed1875aa9
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/analysis.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/base.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/base.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..728a98988b158198586a9c802cf5fff80badad94
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/base.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/boxing.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/boxing.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8c557fd599e83f4ee9eed9eeb6dc4b13146c797f
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/boxing.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/bytecode.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/bytecode.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4f947e995a6acf9f667ba5e3b1efecdd470881d5
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/bytecode.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/byteflow.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/byteflow.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8f9bc83844dc8d09479a7a95921afa0427f328e1
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/byteflow.cpython-312.pyc
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:bacdc907688808d806b713816f9c72777f01db3ad7f92ec9ebd96d0ef67f0bf9
+size 101772
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/caching.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/caching.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..81fc362aceb5e4913872a269927b2085ddacf893
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/caching.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/callconv.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/callconv.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fd18222aadfb0d37399d644d621c0a888f13c85b
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/callconv.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/callwrapper.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/callwrapper.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5e5205fc17927af8b729fe0f3215e76ba9430b27
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/callwrapper.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/ccallback.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/ccallback.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2c07051ba52918533b52ebad12ab508fe7649c49
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/ccallback.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/cgutils.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/cgutils.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4edfb43a80fcd653a3fb380698fd3ebf5268007f
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/cgutils.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/codegen.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/codegen.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4e6262893fdac5e1f3c885150d09af27419953cc
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/codegen.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/compiler.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/compiler.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f35a0c87bcaf8f495eefa2362a2a2936fba3b4c5
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/compiler.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/compiler_lock.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/compiler_lock.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c3238e77aefa0e9ee94f98650733e025b2df0cf2
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/compiler_lock.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/compiler_machinery.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/compiler_machinery.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4397a87a12b8dc6e076d14640c45d3ae91b8d9f5
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/compiler_machinery.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/config.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/config.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e58140c8ca35b6905c7de4b2e7036889224a921c
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/config.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/consts.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/consts.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..75ffa28bea45ce2a46c6b916a8cb2724c4a073da
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/consts.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/controlflow.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/controlflow.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..75b3a8233c4f2f8433e55a115498065ee5084812
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/controlflow.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/cpu.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/cpu.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..74641bdf152e25f68e2403b79031c708eb1c6025
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/cpu.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/cpu_options.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/cpu_options.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8cac1263fcc530947662327178f49a24f23ba727
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/cpu_options.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/debuginfo.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/debuginfo.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d2a05d044688fefac4931eb6126747dff6a14cd8
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/debuginfo.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/decorators.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/decorators.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9a87e66d336265851bddbc4dba507327c092d64b
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/decorators.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/descriptors.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/descriptors.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..17a124ab36118ce3fe1f7eaa20ef71692fdf409d
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/descriptors.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/dispatcher.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/dispatcher.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..88894a01dbe6d77c4c234a0da68171cc3d5370fc
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/dispatcher.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/entrypoints.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/entrypoints.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c4b94d869a13f3480b712562f0ae7469ce98b9e7
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/entrypoints.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/environment.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/environment.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3683520a2f2317e7d4cf94e95079df4a0221beeb
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/environment.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/errors.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/errors.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..57a67a990305dc7cc0af53d0535235c62d0d025b
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/errors.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/event.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..943637e474d0c77b211183520d611a06e28f0858
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/event.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/extending.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/extending.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..147ffe0dd3c361cb0d758aacbcbf17295f092d47
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/extending.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/externals.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/externals.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1c280ca050ffaae9286e5dc7b89f50e57a9f3f49
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/externals.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/fastmathpass.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/fastmathpass.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d9966815915c909370c524220c7ea9ba44aa96f1
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/fastmathpass.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/funcdesc.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/funcdesc.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..aba0d3f8b5d0ef70dd412802722e6403f726288e
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/funcdesc.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/generators.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/generators.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5f318020f7a3eae35aa15ce5bbbbe3e55e71fe22
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/generators.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/imputils.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/imputils.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..69edf6f27f0a4ce90288784ac661a4956dd3373a
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/imputils.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/inline_closurecall.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/inline_closurecall.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4e8f6cc9ff4d2aa2cfa38231a126a07b61253891
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/inline_closurecall.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/interpreter.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/interpreter.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b138e0d5b23d7beda2784b3a67a949840ee44f76
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/interpreter.cpython-312.pyc
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:67f94e7385596285d483edb706440e1918d7714d7e6332b06848a19cf14b66e8
+size 157056
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/intrinsics.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/intrinsics.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..650bd3c49de890a97a1a1b3c6c48eff6c4181770
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/intrinsics.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/ir.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/ir.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..576406224578bd9d1bbba628e412667a9dba439a
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/ir.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/ir_utils.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/ir_utils.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..870db4f869a2913990af86b1e0569b115074cde8
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/ir_utils.cpython-312.pyc
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:8719f3e787799c2a3033e802b48498dd60017a52b8b95e569da054bd555051f4
+size 110712
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/itanium_mangler.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/itanium_mangler.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d071adf4caa188f3605fbdb6a6fe87851c534beb
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/itanium_mangler.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/llvm_bindings.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/llvm_bindings.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..52e9dce2f4ad38b535c24271530c58fdf019ffa0
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/llvm_bindings.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/lowering.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/lowering.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a4b8b68938028a6e54c136168d39a940500d5904
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/lowering.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/new_boxing.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/new_boxing.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6a7b2ca995c56818d575d38baad6990d7b26bf45
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/new_boxing.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/object_mode_passes.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/object_mode_passes.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..53729cc925ffeacabb5bfca11546e2e4a180c3a3
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/object_mode_passes.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/old_boxing.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/old_boxing.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0b8435a7818351d5a891430cac98965dd7f607d8
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/old_boxing.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/optional.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/optional.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e7380d745c683b488e6e3ad200e751f7536376fc
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/optional.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/options.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/options.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2ecdb4963ec07d520bcbe7fe25e95390d5414b7a
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/options.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/postproc.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/postproc.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ce8cbae382070196c20183e6f6b3d99f81e2e707
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/postproc.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/pylowering.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/pylowering.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f00810a1c75b5f67765d941c150cf0861c707abf
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/pylowering.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/pythonapi.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/pythonapi.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3bad16b65167c4fb69bdd6586ddaeb499bc0388a
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/pythonapi.cpython-312.pyc
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:68f411688402d7b7aef76fd161e14db6af187edde8bfc6c43086656884f1edba
+size 117602
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/registry.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/registry.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c849cdb54627c6dce3049116180975c3edeb4d52
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/registry.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/removerefctpass.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/removerefctpass.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..48bdb440f6f9998c60ba0bd1cb6c84c059b00423
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/removerefctpass.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/serialize.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/serialize.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..19dd1b7e409a33678803d995869415b4f1406423
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/serialize.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/sigutils.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/sigutils.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2e1b32477fe54f0d0947a6e42be103a5f6ee5d37
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/sigutils.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/ssa.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/ssa.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..143cc276211f563a43605b963cd915ed4fc4a01e
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/ssa.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/target_extension.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/target_extension.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d69be49a45a5d24364cb5c9f2b5226eabe360418
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/target_extension.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/targetconfig.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/targetconfig.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..997847c761ff3565e066be35d967cbc37191ce46
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/targetconfig.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/tracing.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/tracing.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f97ba6a77b10cc816ffe0c23db222c1e1db430be
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/tracing.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/transforms.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/transforms.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f3efc116e205a53b2abadf95969def6856feb36b
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/transforms.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/typed_passes.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/typed_passes.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8fbd007d2e67000e6570564ce838890409718867
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/typed_passes.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/typeinfer.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/typeinfer.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9b6a3b7560fc12239d3312288c13aee3d7893af0
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/typeinfer.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/untyped_passes.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/untyped_passes.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..38ca70b3c5c2e1280fce302e8b224cc01efe7702
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/untyped_passes.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/utils.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/utils.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2430be8c57102000ebb23272e9f2d73bca074803
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/utils.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/withcontexts.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/withcontexts.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5982e0882c5711867a683e794a481509319ccc47
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/__pycache__/withcontexts.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/annotations/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/numba/core/annotations/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/annotations/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/annotations/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..05fe7503f4d5c6db96a4a8f0180bae258af71397
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/annotations/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/annotations/__pycache__/pretty_annotate.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/annotations/__pycache__/pretty_annotate.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9e6d29b5e689f9c165b5908335085a02fdd8ccd2
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/annotations/__pycache__/pretty_annotate.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/annotations/__pycache__/type_annotations.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/annotations/__pycache__/type_annotations.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..886a67396aec8327d042edd0457b2d28c9b16427
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/annotations/__pycache__/type_annotations.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/annotations/pretty_annotate.py b/tool_server/.venv/lib/python3.12/site-packages/numba/core/annotations/pretty_annotate.py
new file mode 100644
index 0000000000000000000000000000000000000000..6e4f43b91189ee7bfd07dac3af2c40ef317eef2c
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/core/annotations/pretty_annotate.py
@@ -0,0 +1,283 @@
+"""
+This module implements code highlighting of numba function annotations.
+"""
+
+from warnings import warn
+
+warn("The pretty_annotate functionality is experimental and might change API",
+ FutureWarning)
+
+def hllines(code, style):
+ try:
+ from pygments import highlight
+ from pygments.lexers import PythonLexer
+ from pygments.formatters import HtmlFormatter
+ except ImportError:
+ raise ImportError("please install the 'pygments' package")
+ pylex = PythonLexer()
+ "Given a code string, return a list of html-highlighted lines"
+ hf = HtmlFormatter(noclasses=True, style=style, nowrap=True)
+ res = highlight(code, pylex, hf)
+ return res.splitlines()
+
+
+def htlines(code, style):
+ try:
+ from pygments import highlight
+ from pygments.lexers import PythonLexer
+ # TerminalFormatter does not support themes, Terminal256 should,
+ # but seem to not work.
+ from pygments.formatters import TerminalFormatter
+ except ImportError:
+ raise ImportError("please install the 'pygments' package")
+ pylex = PythonLexer()
+ "Given a code string, return a list of ANSI-highlighted lines"
+ hf = TerminalFormatter(style=style)
+ res = highlight(code, pylex, hf)
+ return res.splitlines()
+
+def get_ansi_template():
+ try:
+ from jinja2 import Template
+ except ImportError:
+ raise ImportError("please install the 'jinja2' package")
+ return Template("""
+ {%- for func_key in func_data.keys() -%}
+ Function name: \x1b[34m{{func_data[func_key]['funcname']}}\x1b[39;49;00m
+ {%- if func_data[func_key]['filename'] -%}
+ {{'\n'}}In file: \x1b[34m{{func_data[func_key]['filename'] -}}\x1b[39;49;00m
+ {%- endif -%}
+ {{'\n'}}With signature: \x1b[34m{{func_key[1]}}\x1b[39;49;00m
+ {{- "\n" -}}
+ {%- for num, line, hl, hc in func_data[func_key]['pygments_lines'] -%}
+ {{-'\n'}}{{ num}}: {{hc-}}
+ {%- if func_data[func_key]['ir_lines'][num] -%}
+ {%- for ir_line, ir_line_type in func_data[func_key]['ir_lines'][num] %}
+ {{-'\n'}}--{{- ' '*func_data[func_key]['python_indent'][num]}}
+ {{- ' '*(func_data[func_key]['ir_indent'][num][loop.index0]+4)
+ }}{{ir_line }}\x1b[41m{{ir_line_type-}}\x1b[39;49;00m
+ {%- endfor -%}
+ {%- endif -%}
+ {%- endfor -%}
+ {%- endfor -%}
+ """)
+ return ansi_template
+
+def get_html_template():
+ try:
+ from jinja2 import Template
+ except ImportError:
+ raise ImportError("please install the 'jinja2' package")
+ return Template("""
+
+
+
+
+
+
+ {% for func_key in func_data.keys() %}
+
+ Function name: {{func_data[func_key]['funcname']}}
+ {% if func_data[func_key]['filename'] %}
+ in file: {{func_data[func_key]['filename']|escape}}
+ {% endif %}
+ with signature: {{func_key[1]|e}}
+
+
+
+ {%- for num, line, hl, hc in func_data[func_key]['pygments_lines'] -%}
+ {%- if func_data[func_key]['ir_lines'][num] %}
+
+
+
+
+ {{num}}:
+ {{' '*func_data[func_key]['python_indent'][num]}}{{hl}}
+
+
+
+
+ {%- for ir_line, ir_line_type in func_data[func_key]['ir_lines'][num] %}
+
+
+
+ {{- ' '*func_data[func_key]['python_indent'][num]}}
+ {{ ' '*func_data[func_key]['ir_indent'][num][loop.index0]}}{{ir_line|e -}}
+ {{ir_line_type}}
+
+
+
+ {%- endfor -%}
+
+
+
+
+ {% else -%}
+
+
+ {{num}}:
+ {{' '*func_data[func_key]['python_indent'][num]}}{{hl}}
+
+
+ {%- endif -%}
+ {%- endfor -%}
+
+
+ {% endfor %}
+
+
+ """)
+
+
+def reform_code(annotation):
+ """
+ Extract the code from the Numba annotation datastructure.
+
+ Pygments can only highlight full multi-line strings, the Numba
+ annotation is list of single lines, with indentation removed.
+ """
+ ident_dict = annotation['python_indent']
+ s= ''
+ for n,l in annotation['python_lines']:
+ s = s+' '*ident_dict[n]+l+'\n'
+ return s
+
+
+class Annotate:
+ """
+ Construct syntax highlighted annotation for a given jitted function:
+
+ Example:
+
+ >>> import numba
+ >>> from numba.pretty_annotate import Annotate
+ >>> @numba.jit
+ ... def test(q):
+ ... res = 0
+ ... for i in range(q):
+ ... res += i
+ ... return res
+ ...
+ >>> test(10)
+ 45
+ >>> Annotate(test)
+
+ The last line will return an HTML and/or ANSI representation that will be
+ displayed accordingly in Jupyter/IPython.
+
+ Function annotations persist across compilation for newly encountered
+ type signatures and as a result annotations are shown for all signatures
+ by default.
+
+ Annotations for a specific signature can be shown by using the
+ ``signature`` parameter.
+
+ >>> @numba.jit
+ ... def add(x, y):
+ ... return x + y
+ ...
+ >>> add(1, 2)
+ 3
+ >>> add(1.3, 5.7)
+ 7.0
+ >>> add.signatures
+ [(int64, int64), (float64, float64)]
+ >>> Annotate(add, signature=add.signatures[1]) # annotation for (float64, float64)
+ """
+ def __init__(self, function, signature=None, **kwargs):
+
+ style = kwargs.get('style', 'default')
+ if not function.signatures:
+ raise ValueError('function need to be jitted for at least one signature')
+ ann = function.get_annotation_info(signature=signature)
+ self.ann = ann
+
+ for k,v in ann.items():
+ res = hllines(reform_code(v), style)
+ rest = htlines(reform_code(v), style)
+ v['pygments_lines'] = [(a,b,c, d) for (a,b),c, d in zip(v['python_lines'], res, rest)]
+
+ def _repr_html_(self):
+ return get_html_template().render(func_data=self.ann)
+
+ def __repr__(self):
+ return get_ansi_template().render(func_data=self.ann)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/annotations/template.html b/tool_server/.venv/lib/python3.12/site-packages/numba/core/annotations/template.html
new file mode 100644
index 0000000000000000000000000000000000000000..73e2f6f855d071bfd54770963dfb741eb700bcd9
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/core/annotations/template.html
@@ -0,0 +1,144 @@
+
+
+
+
+
+
+
+
+
+
+ {% for func_key in func_data.keys() %}
+
+ {% set loop1 = loop %}
+
+
+ Function name: {{func_data[func_key]['funcname']}}
+ in file: {{func_data[func_key]['filename']}}
+ with signature: {{func_key[1]|e}}
+
+
+
+
+
+ {%- for num, line in func_data[func_key]['python_lines'] -%}
+ {%- if func_data[func_key]['ir_lines'][num] %}
+
+
+
+
+ {{num}}:
+ {{func_data[func_key]['python_indent'][num]}}{{line|e}}
+
+
+
+
+ {%- for ir_line, ir_line_type in func_data[func_key]['ir_lines'][num] %}
+
+
+ {{- func_data[func_key]['python_indent'][num]}}
+ {{func_data[func_key]['ir_indent'][num][loop.index0]}}{{ir_line|e -}}
+ {{ir_line_type}}
+
+
+
+ {%- endfor -%}
+
+
+
+
+ {% else -%}
+
+
+ {{num}}:
+ {{func_data[func_key]['python_indent'][num]}}{{line|e}}
+
+
+ {%- endif -%}
+ {%- endfor -%}
+
+
+
+
+
+ {% endfor %}
+
+
+
+
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/annotations/type_annotations.py b/tool_server/.venv/lib/python3.12/site-packages/numba/core/annotations/type_annotations.py
new file mode 100644
index 0000000000000000000000000000000000000000..47bd0125011fb06550dfd39fc7b56bba9a824cd6
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/core/annotations/type_annotations.py
@@ -0,0 +1,283 @@
+from collections import defaultdict, OrderedDict
+from collections.abc import Mapping
+from contextlib import closing
+import copy
+import inspect
+import os
+import re
+import sys
+import textwrap
+from io import StringIO
+
+import numba.core.dispatcher
+from numba.core import ir
+
+
+class SourceLines(Mapping):
+ def __init__(self, func):
+
+ try:
+ lines, startno = inspect.getsourcelines(func)
+ except OSError:
+ self.lines = ()
+ self.startno = 0
+ else:
+ self.lines = textwrap.dedent(''.join(lines)).splitlines()
+ self.startno = startno
+
+ def __getitem__(self, lineno):
+ try:
+ return self.lines[lineno - self.startno].rstrip()
+ except IndexError:
+ return ''
+
+ def __iter__(self):
+ return iter((self.startno + i) for i in range(len(self.lines)))
+
+ def __len__(self):
+ return len(self.lines)
+
+ @property
+ def avail(self):
+ return bool(self.lines)
+
+
+class TypeAnnotation(object):
+
+ # func_data dict stores annotation data for all functions that are
+ # compiled. We store the data in the TypeAnnotation class since a new
+ # TypeAnnotation instance is created for each function that is compiled.
+ # For every function that is compiled, we add the type annotation data to
+ # this dict and write the html annotation file to disk (rewrite the html
+ # file for every function since we don't know if this is the last function
+ # to be compiled).
+ func_data = OrderedDict()
+
+ def __init__(self, func_ir, typemap, calltypes, lifted, lifted_from,
+ args, return_type, html_output=None):
+ self.func_id = func_ir.func_id
+ self.blocks = func_ir.blocks
+ self.typemap = typemap
+ self.calltypes = calltypes
+ self.filename = func_ir.loc.filename
+ self.linenum = str(func_ir.loc.line)
+ self.signature = str(args) + ' -> ' + str(return_type)
+
+ # lifted loop information
+ self.lifted = lifted
+ self.num_lifted_loops = len(lifted)
+
+ # If this is a lifted loop function that is being compiled, lifted_from
+ # points to annotation data from function that this loop lifted function
+ # was lifted from. This is used to stick lifted loop annotations back
+ # into original function.
+ self.lifted_from = lifted_from
+
+ def prepare_annotations(self):
+ # Prepare annotations
+ groupedinst = defaultdict(list)
+ found_lifted_loop = False
+ #for blkid, blk in self.blocks.items():
+ for blkid in sorted(self.blocks.keys()):
+ blk = self.blocks[blkid]
+ groupedinst[blk.loc.line].append("label %s" % blkid)
+ for inst in blk.body:
+ lineno = inst.loc.line
+
+ if isinstance(inst, ir.Assign):
+ if found_lifted_loop:
+ atype = 'XXX Lifted Loop XXX'
+ found_lifted_loop = False
+ elif (isinstance(inst.value, ir.Expr) and
+ inst.value.op == 'call'):
+ atype = self.calltypes[inst.value]
+ elif (isinstance(inst.value, ir.Const) and
+ isinstance(inst.value.value, numba.core.dispatcher.LiftedLoop)):
+ atype = 'XXX Lifted Loop XXX'
+ found_lifted_loop = True
+ else:
+ # TODO: fix parfor lowering so that typemap is valid.
+ atype = self.typemap.get(inst.target.name, "")
+
+ aline = "%s = %s :: %s" % (inst.target, inst.value, atype)
+ elif isinstance(inst, ir.SetItem):
+ atype = self.calltypes[inst]
+ aline = "%s :: %s" % (inst, atype)
+ else:
+ aline = "%s" % inst
+ groupedinst[lineno].append(" %s" % aline)
+ return groupedinst
+
+ def annotate(self):
+ source = SourceLines(self.func_id.func)
+ # if not source.avail:
+ # return "Source code unavailable"
+
+ groupedinst = self.prepare_annotations()
+
+ # Format annotations
+ io = StringIO()
+ with closing(io):
+ if source.avail:
+ print("# File: %s" % self.filename, file=io)
+ for num in source:
+ srcline = source[num]
+ ind = _getindent(srcline)
+ print("%s# --- LINE %d --- " % (ind, num), file=io)
+ for inst in groupedinst[num]:
+ print('%s# %s' % (ind, inst), file=io)
+ print(file=io)
+ print(srcline, file=io)
+ print(file=io)
+ if self.lifted:
+ print("# The function contains lifted loops", file=io)
+ for loop in self.lifted:
+ print("# Loop at line %d" % loop.get_source_location(),
+ file=io)
+ print("# Has %d overloads" % len(loop.overloads),
+ file=io)
+ for cres in loop.overloads.values():
+ print(cres.type_annotation, file=io)
+ else:
+ print("# Source code unavailable", file=io)
+ for num in groupedinst:
+ for inst in groupedinst[num]:
+ print('%s' % (inst,), file=io)
+ print(file=io)
+
+ return io.getvalue()
+
+ def html_annotate(self, outfile):
+ # ensure that annotation information is assembled
+ self.annotate_raw()
+ # make a deep copy ahead of the pending mutations
+ func_data = copy.deepcopy(self.func_data)
+
+ key = 'python_indent'
+ for this_func in func_data.values():
+ if key in this_func:
+ idents = {}
+ for line, amount in this_func[key].items():
+ idents[line] = ' ' * amount
+ this_func[key] = idents
+
+ key = 'ir_indent'
+ for this_func in func_data.values():
+ if key in this_func:
+ idents = {}
+ for line, ir_id in this_func[key].items():
+ idents[line] = [' ' * amount for amount in ir_id]
+ this_func[key] = idents
+
+
+
+ try:
+ from jinja2 import Template
+ except ImportError:
+ raise ImportError("please install the 'jinja2' package")
+
+ root = os.path.join(os.path.dirname(__file__))
+ template_filename = os.path.join(root, 'template.html')
+ with open(template_filename, 'r') as template:
+ html = template.read()
+
+ template = Template(html)
+ rendered = template.render(func_data=func_data)
+ outfile.write(rendered)
+
+ def annotate_raw(self):
+ """
+ This returns "raw" annotation information i.e. it has no output format
+ specific markup included.
+ """
+ python_source = SourceLines(self.func_id.func)
+ ir_lines = self.prepare_annotations()
+ line_nums = [num for num in python_source]
+ lifted_lines = [l.get_source_location() for l in self.lifted]
+
+ def add_ir_line(func_data, line):
+ line_str = line.strip()
+ line_type = ''
+ if line_str.endswith('pyobject'):
+ line_str = line_str.replace('pyobject', '')
+ line_type = 'pyobject'
+ func_data['ir_lines'][num].append((line_str, line_type))
+ indent_len = len(_getindent(line))
+ func_data['ir_indent'][num].append(indent_len)
+
+ func_key = (self.func_id.filename + ':' + str(self.func_id.firstlineno + 1),
+ self.signature)
+ if self.lifted_from is not None and self.lifted_from[1]['num_lifted_loops'] > 0:
+ # This is a lifted loop function that is being compiled. Get the
+ # numba ir for lines in loop function to use for annotating
+ # original python function that the loop was lifted from.
+ func_data = self.lifted_from[1]
+ for num in line_nums:
+ if num not in ir_lines.keys():
+ continue
+ func_data['ir_lines'][num] = []
+ func_data['ir_indent'][num] = []
+ for line in ir_lines[num]:
+ add_ir_line(func_data, line)
+ if line.strip().endswith('pyobject'):
+ func_data['python_tags'][num] = 'object_tag'
+ # If any pyobject line is found, make sure original python
+ # line that was marked as a lifted loop start line is tagged
+ # as an object line instead. Lifted loop start lines should
+ # only be marked as lifted loop lines if the lifted loop
+ # was successfully compiled in nopython mode.
+ func_data['python_tags'][self.lifted_from[0]] = 'object_tag'
+
+ # We're done with this lifted loop, so decrement lifted loop counter.
+ # When lifted loop counter hits zero, that means we're ready to write
+ # out annotations to html file.
+ self.lifted_from[1]['num_lifted_loops'] -= 1
+
+ elif func_key not in TypeAnnotation.func_data.keys():
+ TypeAnnotation.func_data[func_key] = {}
+ func_data = TypeAnnotation.func_data[func_key]
+
+ for i, loop in enumerate(self.lifted):
+ # Make sure that when we process each lifted loop function later,
+ # we'll know where it originally came from.
+ loop.lifted_from = (lifted_lines[i], func_data)
+ func_data['num_lifted_loops'] = self.num_lifted_loops
+
+ func_data['filename'] = self.filename
+ func_data['funcname'] = self.func_id.func_name
+ func_data['python_lines'] = []
+ func_data['python_indent'] = {}
+ func_data['python_tags'] = {}
+ func_data['ir_lines'] = {}
+ func_data['ir_indent'] = {}
+
+ for num in line_nums:
+ func_data['python_lines'].append((num, python_source[num].strip()))
+ indent_len = len(_getindent(python_source[num]))
+ func_data['python_indent'][num] = indent_len
+ func_data['python_tags'][num] = ''
+ func_data['ir_lines'][num] = []
+ func_data['ir_indent'][num] = []
+
+ for line in ir_lines[num]:
+ add_ir_line(func_data, line)
+ if num in lifted_lines:
+ func_data['python_tags'][num] = 'lifted_tag'
+ elif line.strip().endswith('pyobject'):
+ func_data['python_tags'][num] = 'object_tag'
+ return self.func_data
+
+
+ def __str__(self):
+ return self.annotate()
+
+
+re_longest_white_prefix = re.compile(r'^\s*')
+
+
+def _getindent(text):
+ m = re_longest_white_prefix.match(text)
+ if not m:
+ return ''
+ else:
+ return ' ' * len(m.group(0))
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/datamodel/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/numba/core/datamodel/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..2f4f1eebd86acc01412cc2bcf634bd231540aac9
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/core/datamodel/__init__.py
@@ -0,0 +1,4 @@
+from .manager import DataModelManager
+from .packer import ArgPacker, DataPacker
+from .registry import register_default, default_manager, register
+from .models import PrimitiveModel, CompositeModel, StructModel # type: ignore
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/datamodel/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/datamodel/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a2b9a0ac0a209ff9fb3b86c1b6de391f285489fe
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/datamodel/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/datamodel/__pycache__/manager.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/datamodel/__pycache__/manager.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..29550023dc9e1c3198f5f028f13e3db77d470d46
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/datamodel/__pycache__/manager.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/datamodel/__pycache__/models.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/datamodel/__pycache__/models.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..38458ac6e6c6e6e7f598725aa4b2c8d53a54f998
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/datamodel/__pycache__/models.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/datamodel/__pycache__/new_models.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/datamodel/__pycache__/new_models.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bcb5077b042a6472ee38637fbe150b788918d6b8
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/datamodel/__pycache__/new_models.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/datamodel/__pycache__/old_models.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/datamodel/__pycache__/old_models.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ece458af396e1aba40a0d71a95349b738cb49bfa
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/datamodel/__pycache__/old_models.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/datamodel/__pycache__/packer.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/datamodel/__pycache__/packer.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ac223e4ae7db0f8fb9895a5d0f57980187142f6b
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/datamodel/__pycache__/packer.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/datamodel/__pycache__/registry.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/datamodel/__pycache__/registry.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1abb81042a439df5ead4fff7a179d3c9e39d94e8
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/datamodel/__pycache__/registry.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/datamodel/__pycache__/testing.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/datamodel/__pycache__/testing.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6d849630092fe86316ed224c46972b13e9e86d65
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/datamodel/__pycache__/testing.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/datamodel/manager.py b/tool_server/.venv/lib/python3.12/site-packages/numba/core/datamodel/manager.py
new file mode 100644
index 0000000000000000000000000000000000000000..95ec9e328000e7a31b7ae102d373a15e35bc81b2
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/core/datamodel/manager.py
@@ -0,0 +1,68 @@
+import weakref
+from collections import ChainMap
+
+from numba.core import types
+
+
+class DataModelManager(object):
+ """Manages mapping of FE types to their corresponding data model
+ """
+
+ def __init__(self, handlers=None):
+ """
+ Parameters
+ -----------
+ handlers: Mapping[Type, DataModel] or None
+ Optionally provide the initial handlers mapping.
+ """
+ # { numba type class -> model factory }
+ self._handlers = handlers or {}
+ # { numba type instance -> model instance }
+ self._cache = weakref.WeakKeyDictionary()
+
+ def register(self, fetypecls, handler):
+ """Register the datamodel factory corresponding to a frontend-type class
+ """
+ assert issubclass(fetypecls, types.Type)
+ self._handlers[fetypecls] = handler
+
+ def lookup(self, fetype):
+ """Returns the corresponding datamodel given the frontend-type instance
+ """
+ try:
+ return self._cache[fetype]
+ except KeyError:
+ pass
+ handler = self._handlers[type(fetype)]
+ model = self._cache[fetype] = handler(self, fetype)
+ return model
+
+ def __getitem__(self, fetype):
+ """Shorthand for lookup()
+ """
+ return self.lookup(fetype)
+
+ def copy(self):
+ """
+ Make a copy of the manager.
+ Use this to inherit from the default data model and specialize it
+ for custom target.
+ """
+ return DataModelManager(self._handlers.copy())
+
+ def chain(self, other_manager):
+ """Create a new DataModelManager by chaining the handlers mapping of
+ `other_manager` with a fresh handlers mapping.
+
+ Any existing and new handlers inserted to `other_manager` will be
+ visible to the new manager. Any handlers inserted to the new manager
+ can override existing handlers in `other_manager` without actually
+ mutating `other_manager`.
+
+ Parameters
+ ----------
+ other_manager: DataModelManager
+ """
+ chained = ChainMap(self._handlers, other_manager._handlers)
+ return DataModelManager(chained)
+
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/datamodel/models.py b/tool_server/.venv/lib/python3.12/site-packages/numba/core/datamodel/models.py
new file mode 100644
index 0000000000000000000000000000000000000000..a2328d9639a22f0273a07822aa9fc5205a3cb72b
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/core/datamodel/models.py
@@ -0,0 +1,12 @@
+import sys
+from numba.core.utils import _RedirectSubpackage
+from numba.core import config
+
+if config.USE_LEGACY_TYPE_SYSTEM: # type: ignore
+ sys.modules[__name__] = _RedirectSubpackage(
+ locals(), "numba.core.datamodel.old_models"
+ )
+else:
+ sys.modules[__name__] = _RedirectSubpackage(
+ locals(), "numba.core.datamodel.new_models"
+ )
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/datamodel/new_models.py b/tool_server/.venv/lib/python3.12/site-packages/numba/core/datamodel/new_models.py
new file mode 100644
index 0000000000000000000000000000000000000000..c7c5c0f0792c65becf2e032b7d17dad37feb761f
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/core/datamodel/new_models.py
@@ -0,0 +1,1390 @@
+from functools import partial
+from collections import deque
+
+from llvmlite import ir
+
+from numba.core.datamodel.registry import register_default
+from numba.core import types, cgutils
+from numba.np import numpy_support
+
+
+class DataModel(object):
+ """
+ DataModel describe how a FE type is represented in the LLVM IR at
+ different contexts.
+
+ Contexts are:
+
+ - value: representation inside function body. Maybe stored in stack.
+ The representation here are flexible.
+
+ - data: representation used when storing into containers (e.g. arrays).
+
+ - argument: representation used for function argument. All composite
+ types are unflattened into multiple primitive types.
+
+ - return: representation used for return argument.
+
+ Throughput the compiler pipeline, a LLVM value is usually passed around
+ in the "value" representation. All "as_" prefix function converts from
+ "value" representation. All "from_" prefix function converts to the
+ "value" representation.
+
+ """
+ def __init__(self, dmm, fe_type):
+ self._dmm = dmm
+ self._fe_type = fe_type
+
+ @property
+ def fe_type(self):
+ return self._fe_type
+
+ def get_value_type(self):
+ raise NotImplementedError(self)
+
+ def get_data_type(self):
+ return self.get_value_type()
+
+ def get_argument_type(self):
+ """Return a LLVM type or nested tuple of LLVM type
+ """
+ return self.get_value_type()
+
+ def get_return_type(self):
+ return self.get_value_type()
+
+ def as_data(self, builder, value):
+ raise NotImplementedError(self)
+
+ def as_argument(self, builder, value):
+ """
+ Takes one LLVM value
+ Return a LLVM value or nested tuple of LLVM value
+ """
+ raise NotImplementedError(self)
+
+ def as_return(self, builder, value):
+ raise NotImplementedError(self)
+
+ def from_data(self, builder, value):
+ raise NotImplementedError(self)
+
+ def from_argument(self, builder, value):
+ """
+ Takes a LLVM value or nested tuple of LLVM value
+ Returns one LLVM value
+ """
+ raise NotImplementedError(self)
+
+ def from_return(self, builder, value):
+ raise NotImplementedError(self)
+
+ def load_from_data_pointer(self, builder, ptr, align=None):
+ """
+ Load value from a pointer to data.
+ This is the default implementation, sufficient for most purposes.
+ """
+ return self.from_data(builder, builder.load(ptr, align=align))
+
+ def traverse(self, builder):
+ """
+ Traverse contained members.
+ Returns a iterable of contained (types, getters).
+ Each getter is a one-argument function accepting a LLVM value.
+ """
+ return []
+
+ def traverse_models(self):
+ """
+ Recursively list all models involved in this model.
+ """
+ return [self._dmm[t] for t in self.traverse_types()]
+
+ def traverse_types(self):
+ """
+ Recursively list all frontend types involved in this model.
+ """
+ types = [self._fe_type]
+ queue = deque([self])
+ while len(queue) > 0:
+ dm = queue.popleft()
+
+ for i_dm in dm.inner_models():
+ if i_dm._fe_type not in types:
+ queue.append(i_dm)
+ types.append(i_dm._fe_type)
+
+ return types
+
+ def inner_models(self):
+ """
+ List all *inner* models.
+ """
+ return []
+
+ def get_nrt_meminfo(self, builder, value):
+ """
+ Returns the MemInfo object or None if it is not tracked.
+ It is only defined for types.meminfo_pointer
+ """
+ return None
+
+ def has_nrt_meminfo(self):
+ return False
+
+ def contains_nrt_meminfo(self):
+ """
+ Recursively check all contained types for need for NRT meminfo.
+ """
+ return any(model.has_nrt_meminfo() for model in self.traverse_models())
+
+ def _compared_fields(self):
+ return (type(self), self._fe_type)
+
+ def __hash__(self):
+ return hash(tuple(self._compared_fields()))
+
+ def __eq__(self, other):
+ if type(self) is type(other):
+ return self._compared_fields() == other._compared_fields()
+ else:
+ return False
+
+ def __ne__(self, other):
+ return not self.__eq__(other)
+
+
+@register_default(types.Omitted)
+class OmittedArgDataModel(DataModel):
+ """
+ A data model for omitted arguments. Only the "argument" representation
+ is defined, other representations raise a NotImplementedError.
+ """
+ # Omitted arguments are using a dummy value type
+ def get_value_type(self):
+ return ir.LiteralStructType([])
+
+ # Omitted arguments don't produce any LLVM function argument.
+ def get_argument_type(self):
+ return ()
+
+ def as_argument(self, builder, val):
+ return ()
+
+ def from_argument(self, builder, val):
+ assert val == (), val
+ return None
+
+class PrimitiveModel(DataModel):
+ """A primitive type can be represented natively in the target in all
+ usage contexts.
+ """
+
+ def __init__(self, dmm, fe_type, be_type):
+ super(PrimitiveModel, self).__init__(dmm, fe_type)
+ self.be_type = be_type
+
+ def get_value_type(self):
+ return self.be_type
+
+ def as_data(self, builder, value):
+ return value
+
+ def as_argument(self, builder, value):
+ return value
+
+ def as_return(self, builder, value):
+ return value
+
+ def from_data(self, builder, value):
+ return value
+
+ def from_argument(self, builder, value):
+ return value
+
+ def from_return(self, builder, value):
+ return value
+
+
+class ProxyModel(DataModel):
+ """
+ Helper class for models which delegate to another model.
+ """
+
+ def get_value_type(self):
+ return self._proxied_model.get_value_type()
+
+ def get_data_type(self):
+ return self._proxied_model.get_data_type()
+
+ def get_return_type(self):
+ return self._proxied_model.get_return_type()
+
+ def get_argument_type(self):
+ return self._proxied_model.get_argument_type()
+
+ def as_data(self, builder, value):
+ return self._proxied_model.as_data(builder, value)
+
+ def as_argument(self, builder, value):
+ return self._proxied_model.as_argument(builder, value)
+
+ def as_return(self, builder, value):
+ return self._proxied_model.as_return(builder, value)
+
+ def from_data(self, builder, value):
+ return self._proxied_model.from_data(builder, value)
+
+ def from_argument(self, builder, value):
+ return self._proxied_model.from_argument(builder, value)
+
+ def from_return(self, builder, value):
+ return self._proxied_model.from_return(builder, value)
+
+
+@register_default(types.EnumMember)
+@register_default(types.IntEnumMember)
+class EnumModel(ProxyModel):
+ """
+ Enum members are represented exactly like their values.
+ """
+ def __init__(self, dmm, fe_type):
+ super(EnumModel, self).__init__(dmm, fe_type)
+ self._proxied_model = dmm.lookup(fe_type.dtype)
+
+
+@register_default(types.Opaque)
+@register_default(types.PyObject)
+@register_default(types.RawPointer)
+@register_default(types.NoneType)
+@register_default(types.StringLiteral)
+@register_default(types.EllipsisType)
+@register_default(types.Function)
+@register_default(types.Type)
+@register_default(types.Object)
+@register_default(types.Module)
+@register_default(types.Phantom)
+@register_default(types.UndefVar)
+@register_default(types.ContextManager)
+@register_default(types.Dispatcher)
+@register_default(types.ObjModeDispatcher)
+@register_default(types.ExceptionClass)
+@register_default(types.Dummy)
+@register_default(types.ExceptionInstance)
+@register_default(types.ExternalFunction)
+@register_default(types.EnumClass)
+@register_default(types.IntEnumClass)
+@register_default(types.NumberClass)
+@register_default(types.TypeRef)
+@register_default(types.NamedTupleClass)
+@register_default(types.DType)
+@register_default(types.RecursiveCall)
+@register_default(types.MakeFunctionLiteral)
+@register_default(types.Poison)
+class OpaqueModel(PrimitiveModel):
+ """
+ Passed as opaque pointers
+ """
+ _ptr_type = ir.IntType(8).as_pointer()
+
+ def __init__(self, dmm, fe_type):
+ be_type = self._ptr_type
+ super(OpaqueModel, self).__init__(dmm, fe_type, be_type)
+
+
+@register_default(types.MemInfoPointer)
+class MemInfoModel(OpaqueModel):
+
+ def inner_models(self):
+ return [self._dmm.lookup(self._fe_type.dtype)]
+
+ def has_nrt_meminfo(self):
+ return True
+
+ def get_nrt_meminfo(self, builder, value):
+ return value
+
+
+@register_default(types.CPointer)
+class PointerModel(PrimitiveModel):
+ def __init__(self, dmm, fe_type):
+ self._pointee_model = dmm.lookup(fe_type.dtype)
+ self._pointee_be_type = self._pointee_model.get_data_type()
+ be_type = self._pointee_be_type.as_pointer()
+ super(PointerModel, self).__init__(dmm, fe_type, be_type)
+
+
+@register_default(types.EphemeralPointer)
+class EphemeralPointerModel(PointerModel):
+
+ def get_data_type(self):
+ return self._pointee_be_type
+
+ def as_data(self, builder, value):
+ value = builder.load(value)
+ return self._pointee_model.as_data(builder, value)
+
+ def from_data(self, builder, value):
+ raise NotImplementedError("use load_from_data_pointer() instead")
+
+ def load_from_data_pointer(self, builder, ptr, align=None):
+ return builder.bitcast(ptr, self.get_value_type())
+
+
+@register_default(types.EphemeralArray)
+class EphemeralArrayModel(PointerModel):
+
+ def __init__(self, dmm, fe_type):
+ super(EphemeralArrayModel, self).__init__(dmm, fe_type)
+ self._data_type = ir.ArrayType(self._pointee_be_type,
+ self._fe_type.count)
+
+ def get_data_type(self):
+ return self._data_type
+
+ def as_data(self, builder, value):
+ values = [builder.load(cgutils.gep_inbounds(builder, value, i))
+ for i in range(self._fe_type.count)]
+ return cgutils.pack_array(builder, values)
+
+ def from_data(self, builder, value):
+ raise NotImplementedError("use load_from_data_pointer() instead")
+
+ def load_from_data_pointer(self, builder, ptr, align=None):
+ return builder.bitcast(ptr, self.get_value_type())
+
+
+@register_default(types.ExternalFunctionPointer)
+class ExternalFuncPointerModel(PrimitiveModel):
+ def __init__(self, dmm, fe_type):
+ sig = fe_type.sig
+ # Since the function is non-Numba, there is no adaptation
+ # of arguments and return value, hence get_value_type().
+ retty = dmm.lookup(sig.return_type).get_value_type()
+ args = [dmm.lookup(t).get_value_type() for t in sig.args]
+ be_type = ir.PointerType(ir.FunctionType(retty, args))
+ super(ExternalFuncPointerModel, self).__init__(dmm, fe_type, be_type)
+
+
+@register_default(types.UniTuple)
+@register_default(types.NamedUniTuple)
+@register_default(types.StarArgUniTuple)
+class UniTupleModel(DataModel):
+ def __init__(self, dmm, fe_type):
+ super(UniTupleModel, self).__init__(dmm, fe_type)
+ self._elem_model = dmm.lookup(fe_type.dtype)
+ self._count = len(fe_type)
+ self._value_type = ir.ArrayType(self._elem_model.get_value_type(),
+ self._count)
+ self._data_type = ir.ArrayType(self._elem_model.get_data_type(),
+ self._count)
+
+ def get_value_type(self):
+ return self._value_type
+
+ def get_data_type(self):
+ return self._data_type
+
+ def get_return_type(self):
+ return self.get_value_type()
+
+ def get_argument_type(self):
+ return (self._elem_model.get_argument_type(),) * self._count
+
+ def as_argument(self, builder, value):
+ out = []
+ for i in range(self._count):
+ v = builder.extract_value(value, [i])
+ v = self._elem_model.as_argument(builder, v)
+ out.append(v)
+ return out
+
+ def from_argument(self, builder, value):
+ out = ir.Constant(self.get_value_type(), ir.Undefined)
+ for i, v in enumerate(value):
+ v = self._elem_model.from_argument(builder, v)
+ out = builder.insert_value(out, v, [i])
+ return out
+
+ def as_data(self, builder, value):
+ out = ir.Constant(self.get_data_type(), ir.Undefined)
+ for i in range(self._count):
+ val = builder.extract_value(value, [i])
+ dval = self._elem_model.as_data(builder, val)
+ out = builder.insert_value(out, dval, [i])
+ return out
+
+ def from_data(self, builder, value):
+ out = ir.Constant(self.get_value_type(), ir.Undefined)
+ for i in range(self._count):
+ val = builder.extract_value(value, [i])
+ dval = self._elem_model.from_data(builder, val)
+ out = builder.insert_value(out, dval, [i])
+ return out
+
+ def as_return(self, builder, value):
+ return value
+
+ def from_return(self, builder, value):
+ return value
+
+ def traverse(self, builder):
+ def getter(i, value):
+ return builder.extract_value(value, i)
+ return [(self._fe_type.dtype, partial(getter, i))
+ for i in range(self._count)]
+
+ def inner_models(self):
+ return [self._elem_model]
+
+
+class CompositeModel(DataModel):
+ """Any model that is composed of multiple other models should subclass from
+ this.
+ """
+ pass
+
+
+class StructModel(CompositeModel):
+ _value_type = None
+ _data_type = None
+
+ def __init__(self, dmm, fe_type, members):
+ super(StructModel, self).__init__(dmm, fe_type)
+ if members:
+ self._fields, self._members = zip(*members)
+ else:
+ self._fields = self._members = ()
+ self._models = tuple([self._dmm.lookup(t) for t in self._members])
+
+ def get_member_fe_type(self, name):
+ """
+ StructModel-specific: get the Numba type of the field named *name*.
+ """
+ pos = self.get_field_position(name)
+ return self._members[pos]
+
+ def get_value_type(self):
+ if self._value_type is None:
+ self._value_type = ir.LiteralStructType([t.get_value_type()
+ for t in self._models])
+ return self._value_type
+
+ def get_data_type(self):
+ if self._data_type is None:
+ self._data_type = ir.LiteralStructType([t.get_data_type()
+ for t in self._models])
+ return self._data_type
+
+ def get_argument_type(self):
+ return tuple([t.get_argument_type() for t in self._models])
+
+ def get_return_type(self):
+ return self.get_data_type()
+
+ def _as(self, methname, builder, value):
+ extracted = []
+ for i, dm in enumerate(self._models):
+ extracted.append(getattr(dm, methname)(builder,
+ self.get(builder, value, i)))
+ return tuple(extracted)
+
+ def _from(self, methname, builder, value):
+ struct = ir.Constant(self.get_value_type(), ir.Undefined)
+
+ for i, (dm, val) in enumerate(zip(self._models, value)):
+ v = getattr(dm, methname)(builder, val)
+ struct = self.set(builder, struct, v, i)
+
+ return struct
+
+ def as_data(self, builder, value):
+ """
+ Converts the LLVM struct in `value` into a representation suited for
+ storing into arrays.
+
+ Note
+ ----
+ Current implementation rarely changes how types are represented for
+ "value" and "data". This is usually a pointless rebuild of the
+ immutable LLVM struct value. Luckily, LLVM optimization removes all
+ redundancy.
+
+ Sample usecase: Structures nested with pointers to other structures
+ that can be serialized into a flat representation when storing into
+ array.
+ """
+ elems = self._as("as_data", builder, value)
+ struct = ir.Constant(self.get_data_type(), ir.Undefined)
+ for i, el in enumerate(elems):
+ struct = builder.insert_value(struct, el, [i])
+ return struct
+
+ def from_data(self, builder, value):
+ """
+ Convert from "data" representation back into "value" representation.
+ Usually invoked when loading from array.
+
+ See notes in `as_data()`
+ """
+ vals = [builder.extract_value(value, [i])
+ for i in range(len(self._members))]
+ return self._from("from_data", builder, vals)
+
+ def load_from_data_pointer(self, builder, ptr, align=None):
+ values = []
+ for i, model in enumerate(self._models):
+ elem_ptr = cgutils.gep_inbounds(builder, ptr, 0, i)
+ val = model.load_from_data_pointer(builder, elem_ptr, align)
+ values.append(val)
+
+ struct = ir.Constant(self.get_value_type(), ir.Undefined)
+ for i, val in enumerate(values):
+ struct = self.set(builder, struct, val, i)
+ return struct
+
+ def as_argument(self, builder, value):
+ return self._as("as_argument", builder, value)
+
+ def from_argument(self, builder, value):
+ return self._from("from_argument", builder, value)
+
+ def as_return(self, builder, value):
+ elems = self._as("as_data", builder, value)
+ struct = ir.Constant(self.get_data_type(), ir.Undefined)
+ for i, el in enumerate(elems):
+ struct = builder.insert_value(struct, el, [i])
+ return struct
+
+ def from_return(self, builder, value):
+ vals = [builder.extract_value(value, [i])
+ for i in range(len(self._members))]
+ return self._from("from_data", builder, vals)
+
+ def get(self, builder, val, pos):
+ """Get a field at the given position or the fieldname
+
+ Args
+ ----
+ builder:
+ LLVM IRBuilder
+ val:
+ value to be inserted
+ pos: int or str
+ field index or field name
+
+ Returns
+ -------
+ Extracted value
+ """
+ if isinstance(pos, str):
+ pos = self.get_field_position(pos)
+ return builder.extract_value(val, [pos],
+ name="extracted." + self._fields[pos])
+
+ def set(self, builder, stval, val, pos):
+ """Set a field at the given position or the fieldname
+
+ Args
+ ----
+ builder:
+ LLVM IRBuilder
+ stval:
+ LLVM struct value
+ val:
+ value to be inserted
+ pos: int or str
+ field index or field name
+
+ Returns
+ -------
+ A new LLVM struct with the value inserted
+ """
+ if isinstance(pos, str):
+ pos = self.get_field_position(pos)
+ return builder.insert_value(stval, val, [pos],
+ name="inserted." + self._fields[pos])
+
+ def get_field_position(self, field):
+ try:
+ return self._fields.index(field)
+ except ValueError:
+ raise KeyError("%s does not have a field named %r"
+ % (self.__class__.__name__, field))
+
+ @property
+ def field_count(self):
+ return len(self._fields)
+
+ def get_type(self, pos):
+ """Get the frontend type (numba type) of a field given the position
+ or the fieldname
+
+ Args
+ ----
+ pos: int or str
+ field index or field name
+ """
+ if isinstance(pos, str):
+ pos = self.get_field_position(pos)
+ return self._members[pos]
+
+ def get_model(self, pos):
+ """
+ Get the datamodel of a field given the position or the fieldname.
+
+ Args
+ ----
+ pos: int or str
+ field index or field name
+ """
+ return self._models[pos]
+
+ def traverse(self, builder):
+ def getter(k, value):
+ if value.type != self.get_value_type():
+ args = self.get_value_type(), value.type
+ raise TypeError("expecting {0} but got {1}".format(*args))
+ return self.get(builder, value, k)
+
+ return [(self.get_type(k), partial(getter, k)) for k in self._fields]
+
+ def inner_models(self):
+ return self._models
+
+
+@register_default(types.PythonBoolean)
+@register_default(types.PythonBooleanLiteral)
+@register_default(types.NumPyBoolean)
+@register_default(types.NumPyBooleanLiteral)
+@register_default(types.MachineBoolean)
+@register_default(types.MachineBooleanLiteral)
+class BooleanModel(DataModel):
+ _bit_type = ir.IntType(1)
+ _byte_type = ir.IntType(8)
+
+ def get_value_type(self):
+ return self._bit_type
+
+ def get_data_type(self):
+ return self._byte_type
+
+ def get_return_type(self):
+ return self.get_data_type()
+
+ def get_argument_type(self):
+ return self.get_data_type()
+
+ def as_data(self, builder, value):
+ return builder.zext(value, self.get_data_type())
+
+ def as_argument(self, builder, value):
+ return self.as_data(builder, value)
+
+ def as_return(self, builder, value):
+ return self.as_data(builder, value)
+
+ def from_data(self, builder, value):
+ ty = self.get_value_type()
+ resalloca = cgutils.alloca_once(builder, ty)
+ cond = builder.icmp_unsigned('==', value, value.type(0))
+ with builder.if_else(cond) as (then, otherwise):
+ with then:
+ builder.store(ty(0), resalloca)
+ with otherwise:
+ builder.store(ty(1), resalloca)
+ return builder.load(resalloca)
+
+ def from_argument(self, builder, value):
+ return self.from_data(builder, value)
+
+ def from_return(self, builder, value):
+ return self.from_data(builder, value)
+
+
+@register_default(types.PythonInteger)
+@register_default(types.PythonIntegerLiteral)
+@register_default(types.NumPyInteger)
+@register_default(types.NumPyIntegerLiteral)
+@register_default(types.MachineInteger)
+@register_default(types.MachineIntegerLiteral)
+class IntegerModel(PrimitiveModel):
+ def __init__(self, dmm, fe_type):
+ be_type = ir.IntType(fe_type.bitwidth)
+ super(IntegerModel, self).__init__(dmm, fe_type, be_type)
+
+
+@register_default(types.PythonFloat)
+@register_default(types.NumPyFloat)
+@register_default(types.MachineFloat)
+class FloatModel(PrimitiveModel):
+ def __init__(self, dmm, fe_type):
+ be_type = ir.DoubleType()
+ super(FloatModel, self).__init__(dmm, fe_type, be_type)
+
+
+@register_default(types.PythonComplex)
+@register_default(types.NumPyComplex)
+@register_default(types.MachineComplex)
+class ComplexModel(StructModel):
+ _element_type = NotImplemented
+
+ def __init__(self, dmm, fe_type):
+ members = [
+ ('real', fe_type.underlying_float),
+ ('imag', fe_type.underlying_float),
+ ]
+ super(ComplexModel, self).__init__(dmm, fe_type, members)
+
+
+@register_default(types.LiteralList)
+@register_default(types.LiteralStrKeyDict)
+@register_default(types.Tuple)
+@register_default(types.NamedTuple)
+@register_default(types.StarArgTuple)
+class TupleModel(StructModel):
+ def __init__(self, dmm, fe_type):
+ members = [('f' + str(i), t) for i, t in enumerate(fe_type)]
+ super(TupleModel, self).__init__(dmm, fe_type, members)
+
+
+@register_default(types.UnionType)
+class UnionModel(StructModel):
+ def __init__(self, dmm, fe_type):
+ members = [
+ ('tag', types.uintp),
+ # XXX: it should really be a MemInfoPointer(types.voidptr)
+ ('payload', types.Tuple.from_types(fe_type.types)),
+ ]
+ super(UnionModel, self).__init__(dmm, fe_type, members)
+
+
+@register_default(types.Pair)
+class PairModel(StructModel):
+ def __init__(self, dmm, fe_type):
+ members = [('first', fe_type.first_type),
+ ('second', fe_type.second_type)]
+ super(PairModel, self).__init__(dmm, fe_type, members)
+
+
+@register_default(types.ListPayload)
+class ListPayloadModel(StructModel):
+ def __init__(self, dmm, fe_type):
+ # The fields are mutable but the payload is always manipulated
+ # by reference. This scheme allows mutations of an array to
+ # be seen by its iterators.
+ members = [
+ ('size', types.intp),
+ ('allocated', types.intp),
+ # This member is only used only for reflected lists
+ ('dirty', types.boolean),
+ # Actually an inlined var-sized array
+ ('data', fe_type.container.dtype),
+ ]
+ super(ListPayloadModel, self).__init__(dmm, fe_type, members)
+
+
+@register_default(types.List)
+class ListModel(StructModel):
+ def __init__(self, dmm, fe_type):
+ payload_type = types.ListPayload(fe_type)
+ members = [
+ # The meminfo data points to a ListPayload
+ ('meminfo', types.MemInfoPointer(payload_type)),
+ # This member is only used only for reflected lists
+ ('parent', types.pyobject),
+ ]
+ super(ListModel, self).__init__(dmm, fe_type, members)
+
+
+@register_default(types.ListIter)
+class ListIterModel(StructModel):
+ def __init__(self, dmm, fe_type):
+ payload_type = types.ListPayload(fe_type.container)
+ members = [
+ # The meminfo data points to a ListPayload (shared with the
+ # original list object)
+ ('meminfo', types.MemInfoPointer(payload_type)),
+ ('index', types.EphemeralPointer(types.intp)),
+ ]
+ super(ListIterModel, self).__init__(dmm, fe_type, members)
+
+
+@register_default(types.SetEntry)
+class SetEntryModel(StructModel):
+ def __init__(self, dmm, fe_type):
+ dtype = fe_type.set_type.dtype
+ members = [
+ # -1 = empty, -2 = deleted
+ ('hash', types.intp),
+ ('key', dtype),
+ ]
+ super(SetEntryModel, self).__init__(dmm, fe_type, members)
+
+
+@register_default(types.SetPayload)
+class SetPayloadModel(StructModel):
+ def __init__(self, dmm, fe_type):
+ entry_type = types.SetEntry(fe_type.container)
+ members = [
+ # Number of active + deleted entries
+ ('fill', types.intp),
+ # Number of active entries
+ ('used', types.intp),
+ # Allocated size - 1 (size being a power of 2)
+ ('mask', types.intp),
+ # Search finger
+ ('finger', types.intp),
+ # This member is only used only for reflected sets
+ ('dirty', types.boolean),
+ # Actually an inlined var-sized array
+ ('entries', entry_type),
+ ]
+ super(SetPayloadModel, self).__init__(dmm, fe_type, members)
+
+@register_default(types.Set)
+class SetModel(StructModel):
+ def __init__(self, dmm, fe_type):
+ payload_type = types.SetPayload(fe_type)
+ members = [
+ # The meminfo data points to a SetPayload
+ ('meminfo', types.MemInfoPointer(payload_type)),
+ # This member is only used only for reflected sets
+ ('parent', types.pyobject),
+ ]
+ super(SetModel, self).__init__(dmm, fe_type, members)
+
+@register_default(types.SetIter)
+class SetIterModel(StructModel):
+ def __init__(self, dmm, fe_type):
+ payload_type = types.SetPayload(fe_type.container)
+ members = [
+ # The meminfo data points to a SetPayload (shared with the
+ # original set object)
+ ('meminfo', types.MemInfoPointer(payload_type)),
+ # The index into the entries table
+ ('index', types.EphemeralPointer(types.intp)),
+ ]
+ super(SetIterModel, self).__init__(dmm, fe_type, members)
+
+
+@register_default(types.Array)
+@register_default(types.Buffer)
+@register_default(types.ByteArray)
+@register_default(types.Bytes)
+@register_default(types.MemoryView)
+@register_default(types.PyArray)
+class ArrayModel(StructModel):
+ def __init__(self, dmm, fe_type):
+ ndim = fe_type.ndim
+ members = [
+ ('meminfo', types.MemInfoPointer(fe_type.dtype)),
+ ('parent', types.pyobject),
+ ('nitems', types.intp),
+ ('itemsize', types.intp),
+ ('data', types.CPointer(fe_type.dtype)),
+ ('shape', types.UniTuple(types.intp, ndim)),
+ ('strides', types.UniTuple(types.intp, ndim)),
+
+ ]
+ super(ArrayModel, self).__init__(dmm, fe_type, members)
+
+
+@register_default(types.ArrayFlags)
+class ArrayFlagsModel(StructModel):
+ def __init__(self, dmm, fe_type):
+ members = [
+ ('parent', fe_type.array_type),
+ ]
+ super(ArrayFlagsModel, self).__init__(dmm, fe_type, members)
+
+
+@register_default(types.NestedArray)
+class NestedArrayModel(ArrayModel):
+ def __init__(self, dmm, fe_type):
+ self._be_type = dmm.lookup(fe_type.dtype).get_data_type()
+ super(NestedArrayModel, self).__init__(dmm, fe_type)
+
+ def as_storage_type(self):
+ """Return the LLVM type representation for the storage of
+ the nestedarray.
+ """
+ ret = ir.ArrayType(self._be_type, self._fe_type.nitems)
+ return ret
+
+
+@register_default(types.Optional)
+class OptionalModel(StructModel):
+ def __init__(self, dmm, fe_type):
+ members = [
+ ('data', fe_type.type),
+ ('valid', types.boolean),
+ ]
+ self._value_model = dmm.lookup(fe_type.type)
+ super(OptionalModel, self).__init__(dmm, fe_type, members)
+
+ def get_return_type(self):
+ return self._value_model.get_return_type()
+
+ def as_return(self, builder, value):
+ raise NotImplementedError
+
+ def from_return(self, builder, value):
+ return self._value_model.from_return(builder, value)
+
+ def traverse(self, builder):
+ def get_data(value):
+ valid = get_valid(value)
+ data = self.get(builder, value, "data")
+ return builder.select(valid, data, ir.Constant(data.type, None))
+ def get_valid(value):
+ return self.get(builder, value, "valid")
+
+ return [(self.get_type("data"), get_data),
+ (self.get_type("valid"), get_valid)]
+
+
+@register_default(types.Record)
+class RecordModel(CompositeModel):
+ def __init__(self, dmm, fe_type):
+ super(RecordModel, self).__init__(dmm, fe_type)
+ self._models = [self._dmm.lookup(t) for _, t in fe_type.members]
+ self._be_type = ir.ArrayType(ir.IntType(8), fe_type.size)
+ self._be_ptr_type = self._be_type.as_pointer()
+
+ def get_value_type(self):
+ """Passed around as reference to underlying data
+ """
+ return self._be_ptr_type
+
+ def get_argument_type(self):
+ return self._be_ptr_type
+
+ def get_return_type(self):
+ return self._be_ptr_type
+
+ def get_data_type(self):
+ return self._be_type
+
+ def as_data(self, builder, value):
+ return builder.load(value)
+
+ def from_data(self, builder, value):
+ raise NotImplementedError("use load_from_data_pointer() instead")
+
+ def as_argument(self, builder, value):
+ return value
+
+ def from_argument(self, builder, value):
+ return value
+
+ def as_return(self, builder, value):
+ return value
+
+ def from_return(self, builder, value):
+ return value
+
+ def load_from_data_pointer(self, builder, ptr, align=None):
+ return builder.bitcast(ptr, self.get_value_type())
+
+
+@register_default(types.UnicodeCharSeq)
+class UnicodeCharSeq(DataModel):
+ def __init__(self, dmm, fe_type):
+ super(UnicodeCharSeq, self).__init__(dmm, fe_type)
+ charty = ir.IntType(numpy_support.sizeof_unicode_char * 8)
+ self._be_type = ir.ArrayType(charty, fe_type.count)
+
+ def get_value_type(self):
+ return self._be_type
+
+ def get_data_type(self):
+ return self._be_type
+
+ def as_data(self, builder, value):
+ return value
+
+ def from_data(self, builder, value):
+ return value
+
+ def as_return(self, builder, value):
+ return value
+
+ def from_return(self, builder, value):
+ return value
+
+ def as_argument(self, builder, value):
+ return value
+
+ def from_argument(self, builder, value):
+ return value
+
+
+@register_default(types.CharSeq)
+class CharSeq(DataModel):
+ def __init__(self, dmm, fe_type):
+ super(CharSeq, self).__init__(dmm, fe_type)
+ charty = ir.IntType(8)
+ self._be_type = ir.ArrayType(charty, fe_type.count)
+
+ def get_value_type(self):
+ return self._be_type
+
+ def get_data_type(self):
+ return self._be_type
+
+ def as_data(self, builder, value):
+ return value
+
+ def from_data(self, builder, value):
+ return value
+
+ def as_return(self, builder, value):
+ return value
+
+ def from_return(self, builder, value):
+ return value
+
+ def as_argument(self, builder, value):
+ return value
+
+ def from_argument(self, builder, value):
+ return value
+
+
+class CContiguousFlatIter(StructModel):
+ def __init__(self, dmm, fe_type, need_indices):
+ assert fe_type.array_type.layout == 'C'
+ array_type = fe_type.array_type
+ dtype = array_type.dtype
+ ndim = array_type.ndim
+ members = [('array', array_type),
+ ('stride', types.intp),
+ ('index', types.EphemeralPointer(types.intp)),
+ ]
+ if need_indices:
+ # For ndenumerate()
+ members.append(('indices', types.EphemeralArray(types.intp, ndim)))
+ super(CContiguousFlatIter, self).__init__(dmm, fe_type, members)
+
+
+class FlatIter(StructModel):
+ def __init__(self, dmm, fe_type):
+ array_type = fe_type.array_type
+ dtype = array_type.dtype
+ ndim = array_type.ndim
+ members = [('array', array_type),
+ ('pointers', types.EphemeralArray(types.CPointer(dtype), ndim)),
+ ('indices', types.EphemeralArray(types.intp, ndim)),
+ ('exhausted', types.EphemeralPointer(types.boolean)),
+ ]
+ super(FlatIter, self).__init__(dmm, fe_type, members)
+
+
+@register_default(types.UniTupleIter)
+class UniTupleIter(StructModel):
+ def __init__(self, dmm, fe_type):
+ members = [('index', types.EphemeralPointer(types.intp)),
+ ('tuple', fe_type.container,)]
+ super(UniTupleIter, self).__init__(dmm, fe_type, members)
+
+
+@register_default(types.misc.SliceLiteral)
+@register_default(types.SliceType)
+class SliceModel(StructModel):
+ def __init__(self, dmm, fe_type):
+ members = [('start', types.intp),
+ ('stop', types.intp),
+ ('step', types.intp),
+ ]
+ super(SliceModel, self).__init__(dmm, fe_type, members)
+
+
+@register_default(types.NPDatetime)
+@register_default(types.NPTimedelta)
+class NPDatetimeModel(PrimitiveModel):
+ def __init__(self, dmm, fe_type):
+ be_type = ir.IntType(64)
+ super(NPDatetimeModel, self).__init__(dmm, fe_type, be_type)
+
+
+@register_default(types.ArrayIterator)
+class ArrayIterator(StructModel):
+ def __init__(self, dmm, fe_type):
+ # We use an unsigned index to avoid the cost of negative index tests.
+ members = [('index', types.EphemeralPointer(types.uintp)),
+ ('array', fe_type.array_type)]
+ super(ArrayIterator, self).__init__(dmm, fe_type, members)
+
+
+@register_default(types.EnumerateType)
+class EnumerateType(StructModel):
+ def __init__(self, dmm, fe_type):
+ members = [('count', types.EphemeralPointer(types.intp)),
+ ('iter', fe_type.source_type)]
+
+ super(EnumerateType, self).__init__(dmm, fe_type, members)
+
+
+@register_default(types.ZipType)
+class ZipType(StructModel):
+ def __init__(self, dmm, fe_type):
+ members = [('iter%d' % i, source_type.iterator_type)
+ for i, source_type in enumerate(fe_type.source_types)]
+ super(ZipType, self).__init__(dmm, fe_type, members)
+
+
+@register_default(types.RangeIteratorType)
+class RangeIteratorType(StructModel):
+ def __init__(self, dmm, fe_type):
+ int_type = fe_type.yield_type
+ members = [('iter', types.EphemeralPointer(int_type)),
+ ('stop', int_type),
+ ('step', int_type),
+ ('count', types.EphemeralPointer(int_type))]
+ super(RangeIteratorType, self).__init__(dmm, fe_type, members)
+
+
+@register_default(types.Generator)
+class GeneratorModel(CompositeModel):
+ def __init__(self, dmm, fe_type):
+ super(GeneratorModel, self).__init__(dmm, fe_type)
+ # XXX Fold this in DataPacker?
+ self._arg_models = [self._dmm.lookup(t) for t in fe_type.arg_types
+ if not isinstance(t, types.Omitted)]
+ self._state_models = [self._dmm.lookup(t) for t in fe_type.state_types]
+
+ self._args_be_type = ir.LiteralStructType(
+ [t.get_data_type() for t in self._arg_models])
+ self._state_be_type = ir.LiteralStructType(
+ [t.get_data_type() for t in self._state_models])
+ # The whole generator closure
+ self._be_type = ir.LiteralStructType(
+ [self._dmm.lookup(types.int32).get_value_type(),
+ self._args_be_type, self._state_be_type])
+ self._be_ptr_type = self._be_type.as_pointer()
+
+ def get_value_type(self):
+ """
+ The generator closure is passed around as a reference.
+ """
+ return self._be_ptr_type
+
+ def get_argument_type(self):
+ return self._be_ptr_type
+
+ def get_return_type(self):
+ return self._be_type
+
+ def get_data_type(self):
+ return self._be_type
+
+ def as_argument(self, builder, value):
+ return value
+
+ def from_argument(self, builder, value):
+ return value
+
+ def as_return(self, builder, value):
+ return self.as_data(builder, value)
+
+ def from_return(self, builder, value):
+ return self.from_data(builder, value)
+
+ def as_data(self, builder, value):
+ return builder.load(value)
+
+ def from_data(self, builder, value):
+ stack = cgutils.alloca_once(builder, value.type)
+ builder.store(value, stack)
+ return stack
+
+
+@register_default(types.ArrayCTypes)
+class ArrayCTypesModel(StructModel):
+ def __init__(self, dmm, fe_type):
+ # ndim = fe_type.ndim
+ members = [('data', types.CPointer(fe_type.dtype)),
+ ('meminfo', types.MemInfoPointer(fe_type.dtype))]
+ super(ArrayCTypesModel, self).__init__(dmm, fe_type, members)
+
+
+@register_default(types.RangeType)
+class RangeModel(StructModel):
+ def __init__(self, dmm, fe_type):
+ int_type = fe_type.iterator_type.yield_type
+ members = [('start', int_type),
+ ('stop', int_type),
+ ('step', int_type)]
+ super(RangeModel, self).__init__(dmm, fe_type, members)
+
+
+# =============================================================================
+
+@register_default(types.NumpyNdIndexType)
+class NdIndexModel(StructModel):
+ def __init__(self, dmm, fe_type):
+ ndim = fe_type.ndim
+ members = [('shape', types.UniTuple(types.intp, ndim)),
+ ('indices', types.EphemeralArray(types.intp, ndim)),
+ ('exhausted', types.EphemeralPointer(types.boolean)),
+ ]
+ super(NdIndexModel, self).__init__(dmm, fe_type, members)
+
+
+@register_default(types.NumpyFlatType)
+def handle_numpy_flat_type(dmm, ty):
+ if ty.array_type.layout == 'C':
+ return CContiguousFlatIter(dmm, ty, need_indices=False)
+ else:
+ return FlatIter(dmm, ty)
+
+@register_default(types.NumpyNdEnumerateType)
+def handle_numpy_ndenumerate_type(dmm, ty):
+ if ty.array_type.layout == 'C':
+ return CContiguousFlatIter(dmm, ty, need_indices=True)
+ else:
+ return FlatIter(dmm, ty)
+
+@register_default(types.BoundFunction)
+def handle_bound_function(dmm, ty):
+ # The same as the underlying type
+ return dmm[ty.this]
+
+
+@register_default(types.NumpyNdIterType)
+class NdIter(StructModel):
+ def __init__(self, dmm, fe_type):
+ array_types = fe_type.arrays
+ ndim = fe_type.ndim
+ shape_len = ndim if fe_type.need_shaped_indexing else 1
+ members = [('exhausted', types.EphemeralPointer(types.boolean)),
+ ('arrays', types.Tuple(array_types)),
+ # The iterator's main shape and indices
+ ('shape', types.UniTuple(types.intp, shape_len)),
+ ('indices', types.EphemeralArray(types.intp, shape_len)),
+ ]
+ # Indexing state for the various sub-iterators
+ # XXX use a tuple instead?
+ for i, sub in enumerate(fe_type.indexers):
+ kind, start_dim, end_dim, _ = sub
+ member_name = 'index%d' % i
+ if kind == 'flat':
+ # A single index into the flattened array
+ members.append((member_name, types.EphemeralPointer(types.intp)))
+ elif kind in ('scalar', 'indexed', '0d'):
+ # Nothing required
+ pass
+ else:
+ assert 0
+ # Slots holding values of the scalar args
+ # XXX use a tuple instead?
+ for i, ty in enumerate(fe_type.arrays):
+ if not isinstance(ty, types.Array):
+ member_name = 'scalar%d' % i
+ members.append((member_name, types.EphemeralPointer(ty)))
+
+ super(NdIter, self).__init__(dmm, fe_type, members)
+
+
+@register_default(types.DeferredType)
+class DeferredStructModel(CompositeModel):
+ def __init__(self, dmm, fe_type):
+ super(DeferredStructModel, self).__init__(dmm, fe_type)
+ self.typename = "deferred.{0}".format(id(fe_type))
+ self.actual_fe_type = fe_type.get()
+
+ def get_value_type(self):
+ return ir.global_context.get_identified_type(self.typename + '.value')
+
+ def get_data_type(self):
+ return ir.global_context.get_identified_type(self.typename + '.data')
+
+ def get_argument_type(self):
+ return self._actual_model.get_argument_type()
+
+ def as_argument(self, builder, value):
+ inner = self.get(builder, value)
+ return self._actual_model.as_argument(builder, inner)
+
+ def from_argument(self, builder, value):
+ res = self._actual_model.from_argument(builder, value)
+ return self.set(builder, self.make_uninitialized(), res)
+
+ def from_data(self, builder, value):
+ self._define()
+ elem = self.get(builder, value)
+ value = self._actual_model.from_data(builder, elem)
+ out = self.make_uninitialized()
+ return self.set(builder, out, value)
+
+ def as_data(self, builder, value):
+ self._define()
+ elem = self.get(builder, value)
+ value = self._actual_model.as_data(builder, elem)
+ out = self.make_uninitialized(kind='data')
+ return self.set(builder, out, value)
+
+ def from_return(self, builder, value):
+ return value
+
+ def as_return(self, builder, value):
+ return value
+
+ def get(self, builder, value):
+ return builder.extract_value(value, [0])
+
+ def set(self, builder, value, content):
+ return builder.insert_value(value, content, [0])
+
+ def make_uninitialized(self, kind='value'):
+ self._define()
+ if kind == 'value':
+ ty = self.get_value_type()
+ else:
+ ty = self.get_data_type()
+ return ir.Constant(ty, ir.Undefined)
+
+ def _define(self):
+ valty = self.get_value_type()
+ self._define_value_type(valty)
+ datty = self.get_data_type()
+ self._define_data_type(datty)
+
+ def _define_value_type(self, value_type):
+ if value_type.is_opaque:
+ value_type.set_body(self._actual_model.get_value_type())
+
+ def _define_data_type(self, data_type):
+ if data_type.is_opaque:
+ data_type.set_body(self._actual_model.get_data_type())
+
+ @property
+ def _actual_model(self):
+ return self._dmm.lookup(self.actual_fe_type)
+
+ def traverse(self, builder):
+ return [(self.actual_fe_type,
+ lambda value: builder.extract_value(value, [0]))]
+
+
+@register_default(types.StructRefPayload)
+class StructPayloadModel(StructModel):
+ """Model for the payload of a mutable struct
+ """
+ def __init__(self, dmm, fe_typ):
+ members = tuple(fe_typ.field_dict.items())
+ super().__init__(dmm, fe_typ, members)
+
+
+class StructRefModel(StructModel):
+ """Model for a mutable struct.
+ A reference to the payload
+ """
+ def __init__(self, dmm, fe_typ):
+ dtype = fe_typ.get_data_type()
+ members = [
+ ("meminfo", types.MemInfoPointer(dtype)),
+ ]
+ super().__init__(dmm, fe_typ, members)
+
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/datamodel/old_models.py b/tool_server/.venv/lib/python3.12/site-packages/numba/core/datamodel/old_models.py
new file mode 100644
index 0000000000000000000000000000000000000000..0837888d8fab9a97410d8c56e253b131660a8f64
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/core/datamodel/old_models.py
@@ -0,0 +1,1385 @@
+from functools import partial
+from collections import deque
+
+from llvmlite import ir
+
+from numba.core.datamodel.registry import register_default
+from numba.core import types, cgutils
+from numba.np import numpy_support
+
+
+class DataModel(object):
+ """
+ DataModel describe how a FE type is represented in the LLVM IR at
+ different contexts.
+
+ Contexts are:
+
+ - value: representation inside function body. Maybe stored in stack.
+ The representation here are flexible.
+
+ - data: representation used when storing into containers (e.g. arrays).
+
+ - argument: representation used for function argument. All composite
+ types are unflattened into multiple primitive types.
+
+ - return: representation used for return argument.
+
+ Throughput the compiler pipeline, a LLVM value is usually passed around
+ in the "value" representation. All "as_" prefix function converts from
+ "value" representation. All "from_" prefix function converts to the
+ "value" representation.
+
+ """
+ def __init__(self, dmm, fe_type):
+ self._dmm = dmm
+ self._fe_type = fe_type
+
+ @property
+ def fe_type(self):
+ return self._fe_type
+
+ def get_value_type(self):
+ raise NotImplementedError(self)
+
+ def get_data_type(self):
+ return self.get_value_type()
+
+ def get_argument_type(self):
+ """Return a LLVM type or nested tuple of LLVM type
+ """
+ return self.get_value_type()
+
+ def get_return_type(self):
+ return self.get_value_type()
+
+ def as_data(self, builder, value):
+ raise NotImplementedError(self)
+
+ def as_argument(self, builder, value):
+ """
+ Takes one LLVM value
+ Return a LLVM value or nested tuple of LLVM value
+ """
+ raise NotImplementedError(self)
+
+ def as_return(self, builder, value):
+ raise NotImplementedError(self)
+
+ def from_data(self, builder, value):
+ raise NotImplementedError(self)
+
+ def from_argument(self, builder, value):
+ """
+ Takes a LLVM value or nested tuple of LLVM value
+ Returns one LLVM value
+ """
+ raise NotImplementedError(self)
+
+ def from_return(self, builder, value):
+ raise NotImplementedError(self)
+
+ def load_from_data_pointer(self, builder, ptr, align=None):
+ """
+ Load value from a pointer to data.
+ This is the default implementation, sufficient for most purposes.
+ """
+ return self.from_data(builder, builder.load(ptr, align=align))
+
+ def traverse(self, builder):
+ """
+ Traverse contained members.
+ Returns a iterable of contained (types, getters).
+ Each getter is a one-argument function accepting a LLVM value.
+ """
+ return []
+
+ def traverse_models(self):
+ """
+ Recursively list all models involved in this model.
+ """
+ return [self._dmm[t] for t in self.traverse_types()]
+
+ def traverse_types(self):
+ """
+ Recursively list all frontend types involved in this model.
+ """
+ types = [self._fe_type]
+ queue = deque([self])
+ while len(queue) > 0:
+ dm = queue.popleft()
+
+ for i_dm in dm.inner_models():
+ if i_dm._fe_type not in types:
+ queue.append(i_dm)
+ types.append(i_dm._fe_type)
+
+ return types
+
+ def inner_models(self):
+ """
+ List all *inner* models.
+ """
+ return []
+
+ def get_nrt_meminfo(self, builder, value):
+ """
+ Returns the MemInfo object or None if it is not tracked.
+ It is only defined for types.meminfo_pointer
+ """
+ return None
+
+ def has_nrt_meminfo(self):
+ return False
+
+ def contains_nrt_meminfo(self):
+ """
+ Recursively check all contained types for need for NRT meminfo.
+ """
+ return any(model.has_nrt_meminfo() for model in self.traverse_models())
+
+ def _compared_fields(self):
+ return (type(self), self._fe_type)
+
+ def __hash__(self):
+ return hash(tuple(self._compared_fields()))
+
+ def __eq__(self, other):
+ if type(self) is type(other):
+ return self._compared_fields() == other._compared_fields()
+ else:
+ return False
+
+ def __ne__(self, other):
+ return not self.__eq__(other)
+
+
+@register_default(types.Omitted)
+class OmittedArgDataModel(DataModel):
+ """
+ A data model for omitted arguments. Only the "argument" representation
+ is defined, other representations raise a NotImplementedError.
+ """
+ # Omitted arguments are using a dummy value type
+ def get_value_type(self):
+ return ir.LiteralStructType([])
+
+ # Omitted arguments don't produce any LLVM function argument.
+ def get_argument_type(self):
+ return ()
+
+ def as_argument(self, builder, val):
+ return ()
+
+ def from_argument(self, builder, val):
+ assert val == (), val
+ return None
+
+
+@register_default(types.Boolean)
+@register_default(types.BooleanLiteral)
+class BooleanModel(DataModel):
+ _bit_type = ir.IntType(1)
+ _byte_type = ir.IntType(8)
+
+ def get_value_type(self):
+ return self._bit_type
+
+ def get_data_type(self):
+ return self._byte_type
+
+ def get_return_type(self):
+ return self.get_data_type()
+
+ def get_argument_type(self):
+ return self.get_data_type()
+
+ def as_data(self, builder, value):
+ return builder.zext(value, self.get_data_type())
+
+ def as_argument(self, builder, value):
+ return self.as_data(builder, value)
+
+ def as_return(self, builder, value):
+ return self.as_data(builder, value)
+
+ def from_data(self, builder, value):
+ ty = self.get_value_type()
+ resalloca = cgutils.alloca_once(builder, ty)
+ cond = builder.icmp_unsigned('==', value, value.type(0))
+ with builder.if_else(cond) as (then, otherwise):
+ with then:
+ builder.store(ty(0), resalloca)
+ with otherwise:
+ builder.store(ty(1), resalloca)
+ return builder.load(resalloca)
+
+ def from_argument(self, builder, value):
+ return self.from_data(builder, value)
+
+ def from_return(self, builder, value):
+ return self.from_data(builder, value)
+
+
+class PrimitiveModel(DataModel):
+ """A primitive type can be represented natively in the target in all
+ usage contexts.
+ """
+
+ def __init__(self, dmm, fe_type, be_type):
+ super(PrimitiveModel, self).__init__(dmm, fe_type)
+ self.be_type = be_type
+
+ def get_value_type(self):
+ return self.be_type
+
+ def as_data(self, builder, value):
+ return value
+
+ def as_argument(self, builder, value):
+ return value
+
+ def as_return(self, builder, value):
+ return value
+
+ def from_data(self, builder, value):
+ return value
+
+ def from_argument(self, builder, value):
+ return value
+
+ def from_return(self, builder, value):
+ return value
+
+
+class ProxyModel(DataModel):
+ """
+ Helper class for models which delegate to another model.
+ """
+
+ def get_value_type(self):
+ return self._proxied_model.get_value_type()
+
+ def get_data_type(self):
+ return self._proxied_model.get_data_type()
+
+ def get_return_type(self):
+ return self._proxied_model.get_return_type()
+
+ def get_argument_type(self):
+ return self._proxied_model.get_argument_type()
+
+ def as_data(self, builder, value):
+ return self._proxied_model.as_data(builder, value)
+
+ def as_argument(self, builder, value):
+ return self._proxied_model.as_argument(builder, value)
+
+ def as_return(self, builder, value):
+ return self._proxied_model.as_return(builder, value)
+
+ def from_data(self, builder, value):
+ return self._proxied_model.from_data(builder, value)
+
+ def from_argument(self, builder, value):
+ return self._proxied_model.from_argument(builder, value)
+
+ def from_return(self, builder, value):
+ return self._proxied_model.from_return(builder, value)
+
+
+@register_default(types.EnumMember)
+@register_default(types.IntEnumMember)
+class EnumModel(ProxyModel):
+ """
+ Enum members are represented exactly like their values.
+ """
+ def __init__(self, dmm, fe_type):
+ super(EnumModel, self).__init__(dmm, fe_type)
+ self._proxied_model = dmm.lookup(fe_type.dtype)
+
+
+@register_default(types.Opaque)
+@register_default(types.PyObject)
+@register_default(types.RawPointer)
+@register_default(types.NoneType)
+@register_default(types.StringLiteral)
+@register_default(types.EllipsisType)
+@register_default(types.Function)
+@register_default(types.Type)
+@register_default(types.Object)
+@register_default(types.Module)
+@register_default(types.Phantom)
+@register_default(types.UndefVar)
+@register_default(types.ContextManager)
+@register_default(types.Dispatcher)
+@register_default(types.ObjModeDispatcher)
+@register_default(types.ExceptionClass)
+@register_default(types.Dummy)
+@register_default(types.ExceptionInstance)
+@register_default(types.ExternalFunction)
+@register_default(types.EnumClass)
+@register_default(types.IntEnumClass)
+@register_default(types.NumberClass)
+@register_default(types.TypeRef)
+@register_default(types.NamedTupleClass)
+@register_default(types.DType)
+@register_default(types.RecursiveCall)
+@register_default(types.MakeFunctionLiteral)
+@register_default(types.Poison)
+class OpaqueModel(PrimitiveModel):
+ """
+ Passed as opaque pointers
+ """
+ _ptr_type = ir.IntType(8).as_pointer()
+
+ def __init__(self, dmm, fe_type):
+ be_type = self._ptr_type
+ super(OpaqueModel, self).__init__(dmm, fe_type, be_type)
+
+
+@register_default(types.MemInfoPointer)
+class MemInfoModel(OpaqueModel):
+
+ def inner_models(self):
+ return [self._dmm.lookup(self._fe_type.dtype)]
+
+ def has_nrt_meminfo(self):
+ return True
+
+ def get_nrt_meminfo(self, builder, value):
+ return value
+
+
+@register_default(types.Integer)
+@register_default(types.IntegerLiteral)
+class IntegerModel(PrimitiveModel):
+ def __init__(self, dmm, fe_type):
+ be_type = ir.IntType(fe_type.bitwidth)
+ super(IntegerModel, self).__init__(dmm, fe_type, be_type)
+
+
+@register_default(types.Float)
+class FloatModel(PrimitiveModel):
+ def __init__(self, dmm, fe_type):
+ if fe_type == types.float32:
+ be_type = ir.FloatType()
+ elif fe_type == types.float64:
+ be_type = ir.DoubleType()
+ else:
+ raise NotImplementedError(fe_type)
+ super(FloatModel, self).__init__(dmm, fe_type, be_type)
+
+
+@register_default(types.CPointer)
+class PointerModel(PrimitiveModel):
+ def __init__(self, dmm, fe_type):
+ self._pointee_model = dmm.lookup(fe_type.dtype)
+ self._pointee_be_type = self._pointee_model.get_data_type()
+ be_type = self._pointee_be_type.as_pointer()
+ super(PointerModel, self).__init__(dmm, fe_type, be_type)
+
+
+@register_default(types.EphemeralPointer)
+class EphemeralPointerModel(PointerModel):
+
+ def get_data_type(self):
+ return self._pointee_be_type
+
+ def as_data(self, builder, value):
+ value = builder.load(value)
+ return self._pointee_model.as_data(builder, value)
+
+ def from_data(self, builder, value):
+ raise NotImplementedError("use load_from_data_pointer() instead")
+
+ def load_from_data_pointer(self, builder, ptr, align=None):
+ return builder.bitcast(ptr, self.get_value_type())
+
+
+@register_default(types.EphemeralArray)
+class EphemeralArrayModel(PointerModel):
+
+ def __init__(self, dmm, fe_type):
+ super(EphemeralArrayModel, self).__init__(dmm, fe_type)
+ self._data_type = ir.ArrayType(self._pointee_be_type,
+ self._fe_type.count)
+
+ def get_data_type(self):
+ return self._data_type
+
+ def as_data(self, builder, value):
+ values = [builder.load(cgutils.gep_inbounds(builder, value, i))
+ for i in range(self._fe_type.count)]
+ return cgutils.pack_array(builder, values)
+
+ def from_data(self, builder, value):
+ raise NotImplementedError("use load_from_data_pointer() instead")
+
+ def load_from_data_pointer(self, builder, ptr, align=None):
+ return builder.bitcast(ptr, self.get_value_type())
+
+
+@register_default(types.ExternalFunctionPointer)
+class ExternalFuncPointerModel(PrimitiveModel):
+ def __init__(self, dmm, fe_type):
+ sig = fe_type.sig
+ # Since the function is non-Numba, there is no adaptation
+ # of arguments and return value, hence get_value_type().
+ retty = dmm.lookup(sig.return_type).get_value_type()
+ args = [dmm.lookup(t).get_value_type() for t in sig.args]
+ be_type = ir.PointerType(ir.FunctionType(retty, args))
+ super(ExternalFuncPointerModel, self).__init__(dmm, fe_type, be_type)
+
+
+@register_default(types.UniTuple)
+@register_default(types.NamedUniTuple)
+@register_default(types.StarArgUniTuple)
+class UniTupleModel(DataModel):
+ def __init__(self, dmm, fe_type):
+ super(UniTupleModel, self).__init__(dmm, fe_type)
+ self._elem_model = dmm.lookup(fe_type.dtype)
+ self._count = len(fe_type)
+ self._value_type = ir.ArrayType(self._elem_model.get_value_type(),
+ self._count)
+ self._data_type = ir.ArrayType(self._elem_model.get_data_type(),
+ self._count)
+
+ def get_value_type(self):
+ return self._value_type
+
+ def get_data_type(self):
+ return self._data_type
+
+ def get_return_type(self):
+ return self.get_value_type()
+
+ def get_argument_type(self):
+ return (self._elem_model.get_argument_type(),) * self._count
+
+ def as_argument(self, builder, value):
+ out = []
+ for i in range(self._count):
+ v = builder.extract_value(value, [i])
+ v = self._elem_model.as_argument(builder, v)
+ out.append(v)
+ return out
+
+ def from_argument(self, builder, value):
+ out = ir.Constant(self.get_value_type(), ir.Undefined)
+ for i, v in enumerate(value):
+ v = self._elem_model.from_argument(builder, v)
+ out = builder.insert_value(out, v, [i])
+ return out
+
+ def as_data(self, builder, value):
+ out = ir.Constant(self.get_data_type(), ir.Undefined)
+ for i in range(self._count):
+ val = builder.extract_value(value, [i])
+ dval = self._elem_model.as_data(builder, val)
+ out = builder.insert_value(out, dval, [i])
+ return out
+
+ def from_data(self, builder, value):
+ out = ir.Constant(self.get_value_type(), ir.Undefined)
+ for i in range(self._count):
+ val = builder.extract_value(value, [i])
+ dval = self._elem_model.from_data(builder, val)
+ out = builder.insert_value(out, dval, [i])
+ return out
+
+ def as_return(self, builder, value):
+ return value
+
+ def from_return(self, builder, value):
+ return value
+
+ def traverse(self, builder):
+ def getter(i, value):
+ return builder.extract_value(value, i)
+ return [(self._fe_type.dtype, partial(getter, i))
+ for i in range(self._count)]
+
+ def inner_models(self):
+ return [self._elem_model]
+
+
+class CompositeModel(DataModel):
+ """Any model that is composed of multiple other models should subclass from
+ this.
+ """
+ pass
+
+
+class StructModel(CompositeModel):
+ _value_type = None
+ _data_type = None
+
+ def __init__(self, dmm, fe_type, members):
+ super(StructModel, self).__init__(dmm, fe_type)
+ if members:
+ self._fields, self._members = zip(*members)
+ else:
+ self._fields = self._members = ()
+ self._models = tuple([self._dmm.lookup(t) for t in self._members])
+
+ def get_member_fe_type(self, name):
+ """
+ StructModel-specific: get the Numba type of the field named *name*.
+ """
+ pos = self.get_field_position(name)
+ return self._members[pos]
+
+ def get_value_type(self):
+ if self._value_type is None:
+ self._value_type = ir.LiteralStructType([t.get_value_type()
+ for t in self._models])
+ return self._value_type
+
+ def get_data_type(self):
+ if self._data_type is None:
+ self._data_type = ir.LiteralStructType([t.get_data_type()
+ for t in self._models])
+ return self._data_type
+
+ def get_argument_type(self):
+ return tuple([t.get_argument_type() for t in self._models])
+
+ def get_return_type(self):
+ return self.get_data_type()
+
+ def _as(self, methname, builder, value):
+ extracted = []
+ for i, dm in enumerate(self._models):
+ extracted.append(getattr(dm, methname)(builder,
+ self.get(builder, value, i)))
+ return tuple(extracted)
+
+ def _from(self, methname, builder, value):
+ struct = ir.Constant(self.get_value_type(), ir.Undefined)
+
+ for i, (dm, val) in enumerate(zip(self._models, value)):
+ v = getattr(dm, methname)(builder, val)
+ struct = self.set(builder, struct, v, i)
+
+ return struct
+
+ def as_data(self, builder, value):
+ """
+ Converts the LLVM struct in `value` into a representation suited for
+ storing into arrays.
+
+ Note
+ ----
+ Current implementation rarely changes how types are represented for
+ "value" and "data". This is usually a pointless rebuild of the
+ immutable LLVM struct value. Luckily, LLVM optimization removes all
+ redundancy.
+
+ Sample usecase: Structures nested with pointers to other structures
+ that can be serialized into a flat representation when storing into
+ array.
+ """
+ elems = self._as("as_data", builder, value)
+ struct = ir.Constant(self.get_data_type(), ir.Undefined)
+ for i, el in enumerate(elems):
+ struct = builder.insert_value(struct, el, [i])
+ return struct
+
+ def from_data(self, builder, value):
+ """
+ Convert from "data" representation back into "value" representation.
+ Usually invoked when loading from array.
+
+ See notes in `as_data()`
+ """
+ vals = [builder.extract_value(value, [i])
+ for i in range(len(self._members))]
+ return self._from("from_data", builder, vals)
+
+ def load_from_data_pointer(self, builder, ptr, align=None):
+ values = []
+ for i, model in enumerate(self._models):
+ elem_ptr = cgutils.gep_inbounds(builder, ptr, 0, i)
+ val = model.load_from_data_pointer(builder, elem_ptr, align)
+ values.append(val)
+
+ struct = ir.Constant(self.get_value_type(), ir.Undefined)
+ for i, val in enumerate(values):
+ struct = self.set(builder, struct, val, i)
+ return struct
+
+ def as_argument(self, builder, value):
+ return self._as("as_argument", builder, value)
+
+ def from_argument(self, builder, value):
+ return self._from("from_argument", builder, value)
+
+ def as_return(self, builder, value):
+ elems = self._as("as_data", builder, value)
+ struct = ir.Constant(self.get_data_type(), ir.Undefined)
+ for i, el in enumerate(elems):
+ struct = builder.insert_value(struct, el, [i])
+ return struct
+
+ def from_return(self, builder, value):
+ vals = [builder.extract_value(value, [i])
+ for i in range(len(self._members))]
+ return self._from("from_data", builder, vals)
+
+ def get(self, builder, val, pos):
+ """Get a field at the given position or the fieldname
+
+ Args
+ ----
+ builder:
+ LLVM IRBuilder
+ val:
+ value to be inserted
+ pos: int or str
+ field index or field name
+
+ Returns
+ -------
+ Extracted value
+ """
+ if isinstance(pos, str):
+ pos = self.get_field_position(pos)
+ return builder.extract_value(val, [pos],
+ name="extracted." + self._fields[pos])
+
+ def set(self, builder, stval, val, pos):
+ """Set a field at the given position or the fieldname
+
+ Args
+ ----
+ builder:
+ LLVM IRBuilder
+ stval:
+ LLVM struct value
+ val:
+ value to be inserted
+ pos: int or str
+ field index or field name
+
+ Returns
+ -------
+ A new LLVM struct with the value inserted
+ """
+ if isinstance(pos, str):
+ pos = self.get_field_position(pos)
+ return builder.insert_value(stval, val, [pos],
+ name="inserted." + self._fields[pos])
+
+ def get_field_position(self, field):
+ try:
+ return self._fields.index(field)
+ except ValueError:
+ raise KeyError("%s does not have a field named %r"
+ % (self.__class__.__name__, field))
+
+ @property
+ def field_count(self):
+ return len(self._fields)
+
+ def get_type(self, pos):
+ """Get the frontend type (numba type) of a field given the position
+ or the fieldname
+
+ Args
+ ----
+ pos: int or str
+ field index or field name
+ """
+ if isinstance(pos, str):
+ pos = self.get_field_position(pos)
+ return self._members[pos]
+
+ def get_model(self, pos):
+ """
+ Get the datamodel of a field given the position or the fieldname.
+
+ Args
+ ----
+ pos: int or str
+ field index or field name
+ """
+ return self._models[pos]
+
+ def traverse(self, builder):
+ def getter(k, value):
+ if value.type != self.get_value_type():
+ args = self.get_value_type(), value.type
+ raise TypeError("expecting {0} but got {1}".format(*args))
+ return self.get(builder, value, k)
+
+ return [(self.get_type(k), partial(getter, k)) for k in self._fields]
+
+ def inner_models(self):
+ return self._models
+
+
+@register_default(types.Complex)
+class ComplexModel(StructModel):
+ _element_type = NotImplemented
+
+ def __init__(self, dmm, fe_type):
+ members = [
+ ('real', fe_type.underlying_float),
+ ('imag', fe_type.underlying_float),
+ ]
+ super(ComplexModel, self).__init__(dmm, fe_type, members)
+
+
+@register_default(types.LiteralList)
+@register_default(types.LiteralStrKeyDict)
+@register_default(types.Tuple)
+@register_default(types.NamedTuple)
+@register_default(types.StarArgTuple)
+class TupleModel(StructModel):
+ def __init__(self, dmm, fe_type):
+ members = [('f' + str(i), t) for i, t in enumerate(fe_type)]
+ super(TupleModel, self).__init__(dmm, fe_type, members)
+
+
+@register_default(types.UnionType)
+class UnionModel(StructModel):
+ def __init__(self, dmm, fe_type):
+ members = [
+ ('tag', types.uintp),
+ # XXX: it should really be a MemInfoPointer(types.voidptr)
+ ('payload', types.Tuple.from_types(fe_type.types)),
+ ]
+ super(UnionModel, self).__init__(dmm, fe_type, members)
+
+
+
+@register_default(types.Pair)
+class PairModel(StructModel):
+ def __init__(self, dmm, fe_type):
+ members = [('first', fe_type.first_type),
+ ('second', fe_type.second_type)]
+ super(PairModel, self).__init__(dmm, fe_type, members)
+
+
+@register_default(types.ListPayload)
+class ListPayloadModel(StructModel):
+ def __init__(self, dmm, fe_type):
+ # The fields are mutable but the payload is always manipulated
+ # by reference. This scheme allows mutations of an array to
+ # be seen by its iterators.
+ members = [
+ ('size', types.intp),
+ ('allocated', types.intp),
+ # This member is only used only for reflected lists
+ ('dirty', types.boolean),
+ # Actually an inlined var-sized array
+ ('data', fe_type.container.dtype),
+ ]
+ super(ListPayloadModel, self).__init__(dmm, fe_type, members)
+
+
+@register_default(types.List)
+class ListModel(StructModel):
+ def __init__(self, dmm, fe_type):
+ payload_type = types.ListPayload(fe_type)
+ members = [
+ # The meminfo data points to a ListPayload
+ ('meminfo', types.MemInfoPointer(payload_type)),
+ # This member is only used only for reflected lists
+ ('parent', types.pyobject),
+ ]
+ super(ListModel, self).__init__(dmm, fe_type, members)
+
+
+@register_default(types.ListIter)
+class ListIterModel(StructModel):
+ def __init__(self, dmm, fe_type):
+ payload_type = types.ListPayload(fe_type.container)
+ members = [
+ # The meminfo data points to a ListPayload (shared with the
+ # original list object)
+ ('meminfo', types.MemInfoPointer(payload_type)),
+ ('index', types.EphemeralPointer(types.intp)),
+ ]
+ super(ListIterModel, self).__init__(dmm, fe_type, members)
+
+
+@register_default(types.SetEntry)
+class SetEntryModel(StructModel):
+ def __init__(self, dmm, fe_type):
+ dtype = fe_type.set_type.dtype
+ members = [
+ # -1 = empty, -2 = deleted
+ ('hash', types.intp),
+ ('key', dtype),
+ ]
+ super(SetEntryModel, self).__init__(dmm, fe_type, members)
+
+
+@register_default(types.SetPayload)
+class SetPayloadModel(StructModel):
+ def __init__(self, dmm, fe_type):
+ entry_type = types.SetEntry(fe_type.container)
+ members = [
+ # Number of active + deleted entries
+ ('fill', types.intp),
+ # Number of active entries
+ ('used', types.intp),
+ # Allocated size - 1 (size being a power of 2)
+ ('mask', types.intp),
+ # Search finger
+ ('finger', types.intp),
+ # This member is only used only for reflected sets
+ ('dirty', types.boolean),
+ # Actually an inlined var-sized array
+ ('entries', entry_type),
+ ]
+ super(SetPayloadModel, self).__init__(dmm, fe_type, members)
+
+@register_default(types.Set)
+class SetModel(StructModel):
+ def __init__(self, dmm, fe_type):
+ payload_type = types.SetPayload(fe_type)
+ members = [
+ # The meminfo data points to a SetPayload
+ ('meminfo', types.MemInfoPointer(payload_type)),
+ # This member is only used only for reflected sets
+ ('parent', types.pyobject),
+ ]
+ super(SetModel, self).__init__(dmm, fe_type, members)
+
+@register_default(types.SetIter)
+class SetIterModel(StructModel):
+ def __init__(self, dmm, fe_type):
+ payload_type = types.SetPayload(fe_type.container)
+ members = [
+ # The meminfo data points to a SetPayload (shared with the
+ # original set object)
+ ('meminfo', types.MemInfoPointer(payload_type)),
+ # The index into the entries table
+ ('index', types.EphemeralPointer(types.intp)),
+ ]
+ super(SetIterModel, self).__init__(dmm, fe_type, members)
+
+
+@register_default(types.Array)
+@register_default(types.Buffer)
+@register_default(types.ByteArray)
+@register_default(types.Bytes)
+@register_default(types.MemoryView)
+@register_default(types.PyArray)
+class ArrayModel(StructModel):
+ def __init__(self, dmm, fe_type):
+ ndim = fe_type.ndim
+ members = [
+ ('meminfo', types.MemInfoPointer(fe_type.dtype)),
+ ('parent', types.pyobject),
+ ('nitems', types.intp),
+ ('itemsize', types.intp),
+ ('data', types.CPointer(fe_type.dtype)),
+ ('shape', types.UniTuple(types.intp, ndim)),
+ ('strides', types.UniTuple(types.intp, ndim)),
+
+ ]
+ super(ArrayModel, self).__init__(dmm, fe_type, members)
+
+
+@register_default(types.ArrayFlags)
+class ArrayFlagsModel(StructModel):
+ def __init__(self, dmm, fe_type):
+ members = [
+ ('parent', fe_type.array_type),
+ ]
+ super(ArrayFlagsModel, self).__init__(dmm, fe_type, members)
+
+
+@register_default(types.NestedArray)
+class NestedArrayModel(ArrayModel):
+ def __init__(self, dmm, fe_type):
+ self._be_type = dmm.lookup(fe_type.dtype).get_data_type()
+ super(NestedArrayModel, self).__init__(dmm, fe_type)
+
+ def as_storage_type(self):
+ """Return the LLVM type representation for the storage of
+ the nestedarray.
+ """
+ ret = ir.ArrayType(self._be_type, self._fe_type.nitems)
+ return ret
+
+
+@register_default(types.Optional)
+class OptionalModel(StructModel):
+ def __init__(self, dmm, fe_type):
+ members = [
+ ('data', fe_type.type),
+ ('valid', types.boolean),
+ ]
+ self._value_model = dmm.lookup(fe_type.type)
+ super(OptionalModel, self).__init__(dmm, fe_type, members)
+
+ def get_return_type(self):
+ return self._value_model.get_return_type()
+
+ def as_return(self, builder, value):
+ raise NotImplementedError
+
+ def from_return(self, builder, value):
+ return self._value_model.from_return(builder, value)
+
+ def traverse(self, builder):
+ def get_data(value):
+ valid = get_valid(value)
+ data = self.get(builder, value, "data")
+ return builder.select(valid, data, ir.Constant(data.type, None))
+ def get_valid(value):
+ return self.get(builder, value, "valid")
+
+ return [(self.get_type("data"), get_data),
+ (self.get_type("valid"), get_valid)]
+
+
+@register_default(types.Record)
+class RecordModel(CompositeModel):
+ def __init__(self, dmm, fe_type):
+ super(RecordModel, self).__init__(dmm, fe_type)
+ self._models = [self._dmm.lookup(t) for _, t in fe_type.members]
+ self._be_type = ir.ArrayType(ir.IntType(8), fe_type.size)
+ self._be_ptr_type = self._be_type.as_pointer()
+
+ def get_value_type(self):
+ """Passed around as reference to underlying data
+ """
+ return self._be_ptr_type
+
+ def get_argument_type(self):
+ return self._be_ptr_type
+
+ def get_return_type(self):
+ return self._be_ptr_type
+
+ def get_data_type(self):
+ return self._be_type
+
+ def as_data(self, builder, value):
+ return builder.load(value)
+
+ def from_data(self, builder, value):
+ raise NotImplementedError("use load_from_data_pointer() instead")
+
+ def as_argument(self, builder, value):
+ return value
+
+ def from_argument(self, builder, value):
+ return value
+
+ def as_return(self, builder, value):
+ return value
+
+ def from_return(self, builder, value):
+ return value
+
+ def load_from_data_pointer(self, builder, ptr, align=None):
+ return builder.bitcast(ptr, self.get_value_type())
+
+
+@register_default(types.UnicodeCharSeq)
+class UnicodeCharSeq(DataModel):
+ def __init__(self, dmm, fe_type):
+ super(UnicodeCharSeq, self).__init__(dmm, fe_type)
+ charty = ir.IntType(numpy_support.sizeof_unicode_char * 8)
+ self._be_type = ir.ArrayType(charty, fe_type.count)
+
+ def get_value_type(self):
+ return self._be_type
+
+ def get_data_type(self):
+ return self._be_type
+
+ def as_data(self, builder, value):
+ return value
+
+ def from_data(self, builder, value):
+ return value
+
+ def as_return(self, builder, value):
+ return value
+
+ def from_return(self, builder, value):
+ return value
+
+ def as_argument(self, builder, value):
+ return value
+
+ def from_argument(self, builder, value):
+ return value
+
+
+@register_default(types.CharSeq)
+class CharSeq(DataModel):
+ def __init__(self, dmm, fe_type):
+ super(CharSeq, self).__init__(dmm, fe_type)
+ charty = ir.IntType(8)
+ self._be_type = ir.ArrayType(charty, fe_type.count)
+
+ def get_value_type(self):
+ return self._be_type
+
+ def get_data_type(self):
+ return self._be_type
+
+ def as_data(self, builder, value):
+ return value
+
+ def from_data(self, builder, value):
+ return value
+
+ def as_return(self, builder, value):
+ return value
+
+ def from_return(self, builder, value):
+ return value
+
+ def as_argument(self, builder, value):
+ return value
+
+ def from_argument(self, builder, value):
+ return value
+
+
+class CContiguousFlatIter(StructModel):
+ def __init__(self, dmm, fe_type, need_indices):
+ assert fe_type.array_type.layout == 'C'
+ array_type = fe_type.array_type
+ dtype = array_type.dtype
+ ndim = array_type.ndim
+ members = [('array', array_type),
+ ('stride', types.intp),
+ ('index', types.EphemeralPointer(types.intp)),
+ ]
+ if need_indices:
+ # For ndenumerate()
+ members.append(('indices', types.EphemeralArray(types.intp, ndim)))
+ super(CContiguousFlatIter, self).__init__(dmm, fe_type, members)
+
+
+class FlatIter(StructModel):
+ def __init__(self, dmm, fe_type):
+ array_type = fe_type.array_type
+ dtype = array_type.dtype
+ ndim = array_type.ndim
+ members = [('array', array_type),
+ ('pointers', types.EphemeralArray(types.CPointer(dtype), ndim)),
+ ('indices', types.EphemeralArray(types.intp, ndim)),
+ ('exhausted', types.EphemeralPointer(types.boolean)),
+ ]
+ super(FlatIter, self).__init__(dmm, fe_type, members)
+
+
+@register_default(types.UniTupleIter)
+class UniTupleIter(StructModel):
+ def __init__(self, dmm, fe_type):
+ members = [('index', types.EphemeralPointer(types.intp)),
+ ('tuple', fe_type.container,)]
+ super(UniTupleIter, self).__init__(dmm, fe_type, members)
+
+
+@register_default(types.misc.SliceLiteral)
+@register_default(types.SliceType)
+class SliceModel(StructModel):
+ def __init__(self, dmm, fe_type):
+ members = [('start', types.intp),
+ ('stop', types.intp),
+ ('step', types.intp),
+ ]
+ super(SliceModel, self).__init__(dmm, fe_type, members)
+
+
+@register_default(types.NPDatetime)
+@register_default(types.NPTimedelta)
+class NPDatetimeModel(PrimitiveModel):
+ def __init__(self, dmm, fe_type):
+ be_type = ir.IntType(64)
+ super(NPDatetimeModel, self).__init__(dmm, fe_type, be_type)
+
+
+@register_default(types.ArrayIterator)
+class ArrayIterator(StructModel):
+ def __init__(self, dmm, fe_type):
+ # We use an unsigned index to avoid the cost of negative index tests.
+ members = [('index', types.EphemeralPointer(types.uintp)),
+ ('array', fe_type.array_type)]
+ super(ArrayIterator, self).__init__(dmm, fe_type, members)
+
+
+@register_default(types.EnumerateType)
+class EnumerateType(StructModel):
+ def __init__(self, dmm, fe_type):
+ members = [('count', types.EphemeralPointer(types.intp)),
+ ('iter', fe_type.source_type)]
+
+ super(EnumerateType, self).__init__(dmm, fe_type, members)
+
+
+@register_default(types.ZipType)
+class ZipType(StructModel):
+ def __init__(self, dmm, fe_type):
+ members = [('iter%d' % i, source_type.iterator_type)
+ for i, source_type in enumerate(fe_type.source_types)]
+ super(ZipType, self).__init__(dmm, fe_type, members)
+
+
+@register_default(types.RangeIteratorType)
+class RangeIteratorType(StructModel):
+ def __init__(self, dmm, fe_type):
+ int_type = fe_type.yield_type
+ members = [('iter', types.EphemeralPointer(int_type)),
+ ('stop', int_type),
+ ('step', int_type),
+ ('count', types.EphemeralPointer(int_type))]
+ super(RangeIteratorType, self).__init__(dmm, fe_type, members)
+
+
+@register_default(types.Generator)
+class GeneratorModel(CompositeModel):
+ def __init__(self, dmm, fe_type):
+ super(GeneratorModel, self).__init__(dmm, fe_type)
+ # XXX Fold this in DataPacker?
+ self._arg_models = [self._dmm.lookup(t) for t in fe_type.arg_types
+ if not isinstance(t, types.Omitted)]
+ self._state_models = [self._dmm.lookup(t) for t in fe_type.state_types]
+
+ self._args_be_type = ir.LiteralStructType(
+ [t.get_data_type() for t in self._arg_models])
+ self._state_be_type = ir.LiteralStructType(
+ [t.get_data_type() for t in self._state_models])
+ # The whole generator closure
+ self._be_type = ir.LiteralStructType(
+ [self._dmm.lookup(types.int32).get_value_type(),
+ self._args_be_type, self._state_be_type])
+ self._be_ptr_type = self._be_type.as_pointer()
+
+ def get_value_type(self):
+ """
+ The generator closure is passed around as a reference.
+ """
+ return self._be_ptr_type
+
+ def get_argument_type(self):
+ return self._be_ptr_type
+
+ def get_return_type(self):
+ return self._be_type
+
+ def get_data_type(self):
+ return self._be_type
+
+ def as_argument(self, builder, value):
+ return value
+
+ def from_argument(self, builder, value):
+ return value
+
+ def as_return(self, builder, value):
+ return self.as_data(builder, value)
+
+ def from_return(self, builder, value):
+ return self.from_data(builder, value)
+
+ def as_data(self, builder, value):
+ return builder.load(value)
+
+ def from_data(self, builder, value):
+ stack = cgutils.alloca_once(builder, value.type)
+ builder.store(value, stack)
+ return stack
+
+
+@register_default(types.ArrayCTypes)
+class ArrayCTypesModel(StructModel):
+ def __init__(self, dmm, fe_type):
+ # ndim = fe_type.ndim
+ members = [('data', types.CPointer(fe_type.dtype)),
+ ('meminfo', types.MemInfoPointer(fe_type.dtype))]
+ super(ArrayCTypesModel, self).__init__(dmm, fe_type, members)
+
+
+@register_default(types.RangeType)
+class RangeModel(StructModel):
+ def __init__(self, dmm, fe_type):
+ int_type = fe_type.iterator_type.yield_type
+ members = [('start', int_type),
+ ('stop', int_type),
+ ('step', int_type)]
+ super(RangeModel, self).__init__(dmm, fe_type, members)
+
+
+# =============================================================================
+
+@register_default(types.NumpyNdIndexType)
+class NdIndexModel(StructModel):
+ def __init__(self, dmm, fe_type):
+ ndim = fe_type.ndim
+ members = [('shape', types.UniTuple(types.intp, ndim)),
+ ('indices', types.EphemeralArray(types.intp, ndim)),
+ ('exhausted', types.EphemeralPointer(types.boolean)),
+ ]
+ super(NdIndexModel, self).__init__(dmm, fe_type, members)
+
+
+@register_default(types.NumpyFlatType)
+def handle_numpy_flat_type(dmm, ty):
+ if ty.array_type.layout == 'C':
+ return CContiguousFlatIter(dmm, ty, need_indices=False)
+ else:
+ return FlatIter(dmm, ty)
+
+@register_default(types.NumpyNdEnumerateType)
+def handle_numpy_ndenumerate_type(dmm, ty):
+ if ty.array_type.layout == 'C':
+ return CContiguousFlatIter(dmm, ty, need_indices=True)
+ else:
+ return FlatIter(dmm, ty)
+
+@register_default(types.BoundFunction)
+def handle_bound_function(dmm, ty):
+ # The same as the underlying type
+ return dmm[ty.this]
+
+
+@register_default(types.NumpyNdIterType)
+class NdIter(StructModel):
+ def __init__(self, dmm, fe_type):
+ array_types = fe_type.arrays
+ ndim = fe_type.ndim
+ shape_len = ndim if fe_type.need_shaped_indexing else 1
+ members = [('exhausted', types.EphemeralPointer(types.boolean)),
+ ('arrays', types.Tuple(array_types)),
+ # The iterator's main shape and indices
+ ('shape', types.UniTuple(types.intp, shape_len)),
+ ('indices', types.EphemeralArray(types.intp, shape_len)),
+ ]
+ # Indexing state for the various sub-iterators
+ # XXX use a tuple instead?
+ for i, sub in enumerate(fe_type.indexers):
+ kind, start_dim, end_dim, _ = sub
+ member_name = 'index%d' % i
+ if kind == 'flat':
+ # A single index into the flattened array
+ members.append((member_name, types.EphemeralPointer(types.intp)))
+ elif kind in ('scalar', 'indexed', '0d'):
+ # Nothing required
+ pass
+ else:
+ assert 0
+ # Slots holding values of the scalar args
+ # XXX use a tuple instead?
+ for i, ty in enumerate(fe_type.arrays):
+ if not isinstance(ty, types.Array):
+ member_name = 'scalar%d' % i
+ members.append((member_name, types.EphemeralPointer(ty)))
+
+ super(NdIter, self).__init__(dmm, fe_type, members)
+
+
+@register_default(types.DeferredType)
+class DeferredStructModel(CompositeModel):
+ def __init__(self, dmm, fe_type):
+ super(DeferredStructModel, self).__init__(dmm, fe_type)
+ self.typename = "deferred.{0}".format(id(fe_type))
+ self.actual_fe_type = fe_type.get()
+
+ def get_value_type(self):
+ return ir.global_context.get_identified_type(self.typename + '.value')
+
+ def get_data_type(self):
+ return ir.global_context.get_identified_type(self.typename + '.data')
+
+ def get_argument_type(self):
+ return self._actual_model.get_argument_type()
+
+ def as_argument(self, builder, value):
+ inner = self.get(builder, value)
+ return self._actual_model.as_argument(builder, inner)
+
+ def from_argument(self, builder, value):
+ res = self._actual_model.from_argument(builder, value)
+ return self.set(builder, self.make_uninitialized(), res)
+
+ def from_data(self, builder, value):
+ self._define()
+ elem = self.get(builder, value)
+ value = self._actual_model.from_data(builder, elem)
+ out = self.make_uninitialized()
+ return self.set(builder, out, value)
+
+ def as_data(self, builder, value):
+ self._define()
+ elem = self.get(builder, value)
+ value = self._actual_model.as_data(builder, elem)
+ out = self.make_uninitialized(kind='data')
+ return self.set(builder, out, value)
+
+ def from_return(self, builder, value):
+ return value
+
+ def as_return(self, builder, value):
+ return value
+
+ def get(self, builder, value):
+ return builder.extract_value(value, [0])
+
+ def set(self, builder, value, content):
+ return builder.insert_value(value, content, [0])
+
+ def make_uninitialized(self, kind='value'):
+ self._define()
+ if kind == 'value':
+ ty = self.get_value_type()
+ else:
+ ty = self.get_data_type()
+ return ir.Constant(ty, ir.Undefined)
+
+ def _define(self):
+ valty = self.get_value_type()
+ self._define_value_type(valty)
+ datty = self.get_data_type()
+ self._define_data_type(datty)
+
+ def _define_value_type(self, value_type):
+ if value_type.is_opaque:
+ value_type.set_body(self._actual_model.get_value_type())
+
+ def _define_data_type(self, data_type):
+ if data_type.is_opaque:
+ data_type.set_body(self._actual_model.get_data_type())
+
+ @property
+ def _actual_model(self):
+ return self._dmm.lookup(self.actual_fe_type)
+
+ def traverse(self, builder):
+ return [(self.actual_fe_type,
+ lambda value: builder.extract_value(value, [0]))]
+
+
+@register_default(types.StructRefPayload)
+class StructPayloadModel(StructModel):
+ """Model for the payload of a mutable struct
+ """
+ def __init__(self, dmm, fe_typ):
+ members = tuple(fe_typ.field_dict.items())
+ super().__init__(dmm, fe_typ, members)
+
+
+class StructRefModel(StructModel):
+ """Model for a mutable struct.
+ A reference to the payload
+ """
+ def __init__(self, dmm, fe_typ):
+ dtype = fe_typ.get_data_type()
+ members = [
+ ("meminfo", types.MemInfoPointer(dtype)),
+ ]
+ super().__init__(dmm, fe_typ, members)
+
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/datamodel/packer.py b/tool_server/.venv/lib/python3.12/site-packages/numba/core/datamodel/packer.py
new file mode 100644
index 0000000000000000000000000000000000000000..9efc51449bc3699b67e2cef8035bbdb93c3dabde
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/core/datamodel/packer.py
@@ -0,0 +1,213 @@
+from collections import deque
+
+from numba.core import types, cgutils
+
+
+
+class DataPacker(object):
+ """
+ A helper to pack a number of typed arguments into a data structure.
+ Omitted arguments (i.e. values with the type `Omitted`) are automatically
+ skipped.
+ """
+ # XXX should DataPacker be a model for a dedicated type?
+
+ def __init__(self, dmm, fe_types):
+ self._dmm = dmm
+ self._fe_types = fe_types
+ self._models = [dmm.lookup(ty) for ty in fe_types]
+
+ self._pack_map = []
+ self._be_types = []
+ for i, ty in enumerate(fe_types):
+ if not isinstance(ty, types.Omitted):
+ self._pack_map.append(i)
+ self._be_types.append(self._models[i].get_data_type())
+
+ def as_data(self, builder, values):
+ """
+ Return the given values packed as a data structure.
+ """
+ elems = [self._models[i].as_data(builder, values[i])
+ for i in self._pack_map]
+ return cgutils.make_anonymous_struct(builder, elems)
+
+ def _do_load(self, builder, ptr, formal_list=None):
+ res = []
+ for i, i_formal in enumerate(self._pack_map):
+ elem_ptr = cgutils.gep_inbounds(builder, ptr, 0, i)
+ val = self._models[i_formal].load_from_data_pointer(builder, elem_ptr)
+ if formal_list is None:
+ res.append((self._fe_types[i_formal], val))
+ else:
+ formal_list[i_formal] = val
+ return res
+
+ def load(self, builder, ptr):
+ """
+ Load the packed values and return a (type, value) tuples.
+ """
+ return self._do_load(builder, ptr)
+
+ def load_into(self, builder, ptr, formal_list):
+ """
+ Load the packed values into a sequence indexed by formal
+ argument number (skipping any Omitted position).
+ """
+ self._do_load(builder, ptr, formal_list)
+
+
+class ArgPacker(object):
+ """
+ Compute the position for each high-level typed argument.
+ It flattens every composite argument into primitive types.
+ It maintains a position map for unflattening the arguments.
+
+ Since struct (esp. nested struct) have specific ABI requirements (e.g.
+ alignment, pointer address-space, ...) in different architecture (e.g.
+ OpenCL, CUDA), flattening composite argument types simplifes the call
+ setup from the Python side. Functions are receiving simple primitive
+ types and there are only a handful of these.
+ """
+
+ def __init__(self, dmm, fe_args):
+ self._dmm = dmm
+ self._fe_args = fe_args
+ self._nargs = len(fe_args)
+
+ self._dm_args = []
+ argtys = []
+ for ty in fe_args:
+ dm = self._dmm.lookup(ty)
+ self._dm_args.append(dm)
+ argtys.append(dm.get_argument_type())
+ self._unflattener = _Unflattener(argtys)
+ self._be_args = list(_flatten(argtys))
+
+ def as_arguments(self, builder, values):
+ """Flatten all argument values
+ """
+ if len(values) != self._nargs:
+ raise TypeError("invalid number of args: expected %d, got %d"
+ % (self._nargs, len(values)))
+
+ if not values:
+ return ()
+
+ args = [dm.as_argument(builder, val)
+ for dm, val in zip(self._dm_args, values)
+ ]
+
+ args = tuple(_flatten(args))
+ return args
+
+ def from_arguments(self, builder, args):
+ """Unflatten all argument values
+ """
+
+ valtree = self._unflattener.unflatten(args)
+ values = [dm.from_argument(builder, val)
+ for dm, val in zip(self._dm_args, valtree)
+ ]
+
+ return values
+
+ def assign_names(self, args, names):
+ """Assign names for each flattened argument values.
+ """
+
+ valtree = self._unflattener.unflatten(args)
+ for aval, aname in zip(valtree, names):
+ self._assign_names(aval, aname)
+
+ def _assign_names(self, val_or_nested, name, depth=()):
+ if isinstance(val_or_nested, (tuple, list)):
+ for pos, aval in enumerate(val_or_nested):
+ self._assign_names(aval, name, depth=depth + (pos,))
+ else:
+ postfix = '.'.join(map(str, depth))
+ parts = [name, postfix]
+ val_or_nested.name = '.'.join(filter(bool, parts))
+
+ @property
+ def argument_types(self):
+ """Return a list of LLVM types that are results of flattening
+ composite types.
+ """
+ return tuple(ty for ty in self._be_args if ty != ())
+
+
+def _flatten(iterable):
+ """
+ Flatten nested iterable of (tuple, list).
+ """
+ def rec(iterable):
+ for i in iterable:
+ if isinstance(i, (tuple, list)):
+ for j in rec(i):
+ yield j
+ else:
+ yield i
+ return rec(iterable)
+
+
+_PUSH_LIST = 1
+_APPEND_NEXT_VALUE = 2
+_APPEND_EMPTY_TUPLE = 3
+_POP = 4
+
+class _Unflattener(object):
+ """
+ An object used to unflatten nested sequences after a given pattern
+ (an arbitrarily nested sequence).
+ The pattern shows the nested sequence shape desired when unflattening;
+ the values it contains are irrelevant.
+ """
+
+ def __init__(self, pattern):
+ self._code = self._build_unflatten_code(pattern)
+
+ def _build_unflatten_code(self, iterable):
+ """Build the unflatten opcode sequence for the given *iterable* structure
+ (an iterable of nested sequences).
+ """
+ code = []
+ def rec(iterable):
+ for i in iterable:
+ if isinstance(i, (tuple, list)):
+ if len(i) > 0:
+ code.append(_PUSH_LIST)
+ rec(i)
+ code.append(_POP)
+ else:
+ code.append(_APPEND_EMPTY_TUPLE)
+ else:
+ code.append(_APPEND_NEXT_VALUE)
+
+ rec(iterable)
+ return code
+
+ def unflatten(self, flatiter):
+ """Rebuild a nested tuple structure.
+ """
+ vals = deque(flatiter)
+
+ res = []
+ cur = res
+ stack = []
+ for op in self._code:
+ if op is _PUSH_LIST:
+ stack.append(cur)
+ cur.append([])
+ cur = cur[-1]
+ elif op is _APPEND_NEXT_VALUE:
+ cur.append(vals.popleft())
+ elif op is _APPEND_EMPTY_TUPLE:
+ cur.append(())
+ elif op is _POP:
+ cur = stack.pop()
+
+ assert not stack, stack
+ assert not vals, vals
+
+ return res
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/datamodel/registry.py b/tool_server/.venv/lib/python3.12/site-packages/numba/core/datamodel/registry.py
new file mode 100644
index 0000000000000000000000000000000000000000..18bdc475ef09727924b8159a0c9428f7c3abbee1
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/core/datamodel/registry.py
@@ -0,0 +1,18 @@
+import functools
+from .manager import DataModelManager
+
+
+def register(dmm, typecls):
+ """Used as decorator to simplify datamodel registration.
+ Returns the object being decorated so that chaining is possible.
+ """
+ def wraps(fn):
+ dmm.register(typecls, fn)
+ return fn
+
+ return wraps
+
+
+default_manager = DataModelManager()
+
+register_default = functools.partial(register, default_manager)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/datamodel/testing.py b/tool_server/.venv/lib/python3.12/site-packages/numba/core/datamodel/testing.py
new file mode 100644
index 0000000000000000000000000000000000000000..e2e8a2818b6111efc3979f28a7aa80eef4686a8e
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/core/datamodel/testing.py
@@ -0,0 +1,150 @@
+from llvmlite import ir
+from llvmlite import binding as ll
+
+from numba.core import datamodel
+import unittest
+
+
+class DataModelTester(unittest.TestCase):
+ """
+ Test the implementation of a DataModel for a frontend type.
+ """
+ fe_type = NotImplemented
+
+ def setUp(self):
+ self.module = ir.Module()
+ self.datamodel = datamodel.default_manager[self.fe_type]
+
+ def test_as_arg(self):
+ """
+ - Is as_arg() and from_arg() implemented?
+ - Are they the inverse of each other?
+ """
+ fnty = ir.FunctionType(ir.VoidType(), [])
+ function = ir.Function(self.module, fnty, name="test_as_arg")
+ builder = ir.IRBuilder()
+ builder.position_at_end(function.append_basic_block())
+
+ undef_value = ir.Constant(self.datamodel.get_value_type(), None)
+ args = self.datamodel.as_argument(builder, undef_value)
+ self.assertIsNot(args, NotImplemented, "as_argument returned "
+ "NotImplementedError")
+
+ if isinstance(args, (tuple, list)):
+ def recur_tuplize(args, func=None):
+ for arg in args:
+ if isinstance(arg, (tuple, list)):
+ yield tuple(recur_tuplize(arg, func=func))
+ else:
+ if func is None:
+ yield arg
+ else:
+ yield func(arg)
+
+ argtypes = tuple(recur_tuplize(args, func=lambda x: x.type))
+ exptypes = tuple(recur_tuplize(
+ self.datamodel.get_argument_type()))
+ self.assertEqual(exptypes, argtypes)
+ else:
+ self.assertEqual(args.type,
+ self.datamodel.get_argument_type())
+
+ rev_value = self.datamodel.from_argument(builder, args)
+ self.assertEqual(rev_value.type, self.datamodel.get_value_type())
+
+ builder.ret_void() # end function
+
+ # Ensure valid LLVM generation
+ materialized = ll.parse_assembly(str(self.module))
+ str(materialized)
+
+ def test_as_return(self):
+ """
+ - Is as_return() and from_return() implemented?
+ - Are they the inverse of each other?
+ """
+ fnty = ir.FunctionType(ir.VoidType(), [])
+ function = ir.Function(self.module, fnty, name="test_as_return")
+ builder = ir.IRBuilder()
+ builder.position_at_end(function.append_basic_block())
+
+ undef_value = ir.Constant(self.datamodel.get_value_type(), None)
+ ret = self.datamodel.as_return(builder, undef_value)
+ self.assertIsNot(ret, NotImplemented, "as_return returned "
+ "NotImplementedError")
+
+ self.assertEqual(ret.type, self.datamodel.get_return_type())
+
+ rev_value = self.datamodel.from_return(builder, ret)
+ self.assertEqual(rev_value.type, self.datamodel.get_value_type())
+
+ builder.ret_void() # end function
+
+ # Ensure valid LLVM generation
+ materialized = ll.parse_assembly(str(self.module))
+ str(materialized)
+
+
+class SupportAsDataMixin(object):
+ """Test as_data() and from_data()
+ """
+ # XXX test load_from_data_pointer() as well
+
+ def test_as_data(self):
+ fnty = ir.FunctionType(ir.VoidType(), [])
+ function = ir.Function(self.module, fnty, name="test_as_data")
+ builder = ir.IRBuilder()
+ builder.position_at_end(function.append_basic_block())
+
+ undef_value = ir.Constant(self.datamodel.get_value_type(), None)
+ data = self.datamodel.as_data(builder, undef_value)
+ self.assertIsNot(data, NotImplemented,
+ "as_data returned NotImplemented")
+
+ self.assertEqual(data.type, self.datamodel.get_data_type())
+
+ rev_value = self.datamodel.from_data(builder, data)
+ self.assertEqual(rev_value.type,
+ self.datamodel.get_value_type())
+
+ builder.ret_void() # end function
+
+ # Ensure valid LLVM generation
+ materialized = ll.parse_assembly(str(self.module))
+ str(materialized)
+
+
+class NotSupportAsDataMixin(object):
+ """Ensure as_data() and from_data() raise NotImplementedError.
+ """
+
+ def test_as_data_not_supported(self):
+ fnty = ir.FunctionType(ir.VoidType(), [])
+ function = ir.Function(self.module, fnty, name="test_as_data")
+ builder = ir.IRBuilder()
+ builder.position_at_end(function.append_basic_block())
+
+ undef_value = ir.Constant(self.datamodel.get_value_type(), None)
+ with self.assertRaises(NotImplementedError):
+ data = self.datamodel.as_data(builder, undef_value)
+ with self.assertRaises(NotImplementedError):
+ rev_data = self.datamodel.from_data(builder, undef_value)
+
+
+class DataModelTester_SupportAsDataMixin(DataModelTester,
+ SupportAsDataMixin):
+ pass
+
+
+class DataModelTester_NotSupportAsDataMixin(DataModelTester,
+ NotSupportAsDataMixin):
+ pass
+
+
+def test_factory(support_as_data=True):
+ """A helper for returning a unittest TestCase for testing
+ """
+ if support_as_data:
+ return DataModelTester_SupportAsDataMixin
+ else:
+ return DataModelTester_NotSupportAsDataMixin
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/rewrites/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/numba/core/rewrites/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..61f55a8ecde8df1f3f8fef4533a9fdff6762b45c
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/core/rewrites/__init__.py
@@ -0,0 +1,8 @@
+"""
+A subpackage hosting Numba IR rewrite passes.
+"""
+
+from .registry import register_rewrite, rewrite_registry, Rewrite
+# Register various built-in rewrite passes
+from numba.core.rewrites import (static_getitem, static_raise, static_binop,
+ ir_print)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/rewrites/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/rewrites/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..72b41384d1092a553b5135fedc8b5b064f54c841
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/rewrites/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/rewrites/__pycache__/ir_print.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/rewrites/__pycache__/ir_print.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3b034c76e14e8ff4cdc1c575fc07004f2b6d161d
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/rewrites/__pycache__/ir_print.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/rewrites/__pycache__/registry.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/rewrites/__pycache__/registry.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..dda9155aade27adcf348ea8ec1e4850f944c1a7d
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/rewrites/__pycache__/registry.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/rewrites/__pycache__/static_binop.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/rewrites/__pycache__/static_binop.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..644ce1390eb0b66773f10b7599f7107ad00a99bc
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/rewrites/__pycache__/static_binop.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/rewrites/__pycache__/static_getitem.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/rewrites/__pycache__/static_getitem.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..db20ffee5f96536b154df80a925cadb59a78def7
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/rewrites/__pycache__/static_getitem.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/rewrites/__pycache__/static_raise.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/rewrites/__pycache__/static_raise.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8c4a3320db00002ae4c61a67ac66924c89f06308
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/rewrites/__pycache__/static_raise.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/rewrites/ir_print.py b/tool_server/.venv/lib/python3.12/site-packages/numba/core/rewrites/ir_print.py
new file mode 100644
index 0000000000000000000000000000000000000000..6d678381bb18ab697d5c1fceb4c12e8cae18e342
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/core/rewrites/ir_print.py
@@ -0,0 +1,82 @@
+from numba.core import errors, ir
+from numba.core.rewrites import register_rewrite, Rewrite
+
+
+@register_rewrite('before-inference')
+class RewritePrintCalls(Rewrite):
+ """
+ Rewrite calls to the print() global function to dedicated IR print() nodes.
+ """
+
+ def match(self, func_ir, block, typemap, calltypes):
+ self.prints = prints = {}
+ self.block = block
+ # Find all assignments with a right-hand print() call
+ for inst in block.find_insts(ir.Assign):
+ if isinstance(inst.value, ir.Expr) and inst.value.op == 'call':
+ expr = inst.value
+ try:
+ callee = func_ir.infer_constant(expr.func)
+ except errors.ConstantInferenceError:
+ continue
+ if callee is print:
+ if expr.kws:
+ # Only positional args are supported
+ msg = ("Numba's print() function implementation does not "
+ "support keyword arguments.")
+ raise errors.UnsupportedError(msg, inst.loc)
+ prints[inst] = expr
+ return len(prints) > 0
+
+ def apply(self):
+ """
+ Rewrite `var = call (...)` as a sequence of
+ `print(...)` and `var = const(None)`.
+ """
+ new_block = self.block.copy()
+ new_block.clear()
+ for inst in self.block.body:
+ if inst in self.prints:
+ expr = self.prints[inst]
+ print_node = ir.Print(args=expr.args, vararg=expr.vararg,
+ loc=expr.loc)
+ new_block.append(print_node)
+ assign_node = ir.Assign(value=ir.Const(None, loc=expr.loc),
+ target=inst.target,
+ loc=inst.loc)
+ new_block.append(assign_node)
+ else:
+ new_block.append(inst)
+ return new_block
+
+
+@register_rewrite('before-inference')
+class DetectConstPrintArguments(Rewrite):
+ """
+ Detect and store constant arguments to print() nodes.
+ """
+
+ def match(self, func_ir, block, typemap, calltypes):
+ self.consts = consts = {}
+ self.block = block
+ for inst in block.find_insts(ir.Print):
+ if inst.consts:
+ # Already rewritten
+ continue
+ for idx, var in enumerate(inst.args):
+ try:
+ const = func_ir.infer_constant(var)
+ except errors.ConstantInferenceError:
+ continue
+ consts.setdefault(inst, {})[idx] = const
+
+ return len(consts) > 0
+
+ def apply(self):
+ """
+ Store detected constant arguments on their nodes.
+ """
+ for inst in self.block.body:
+ if inst in self.consts:
+ inst.consts = self.consts[inst]
+ return self.block
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/rewrites/registry.py b/tool_server/.venv/lib/python3.12/site-packages/numba/core/rewrites/registry.py
new file mode 100644
index 0000000000000000000000000000000000000000..ea22fc8e354940235089c208e091382ed6ec87de
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/core/rewrites/registry.py
@@ -0,0 +1,98 @@
+from collections import defaultdict
+
+from numba.core import config
+
+
+class Rewrite(object):
+ '''Defines the abstract base class for Numba rewrites.
+ '''
+
+ def __init__(self, state=None):
+ '''Constructor for the Rewrite class.
+ '''
+ pass
+
+ def match(self, func_ir, block, typemap, calltypes):
+ '''Overload this method to check an IR block for matching terms in the
+ rewrite.
+ '''
+ return False
+
+ def apply(self):
+ '''Overload this method to return a rewritten IR basic block when a
+ match has been found.
+ '''
+ raise NotImplementedError("Abstract Rewrite.apply() called!")
+
+
+class RewriteRegistry(object):
+ '''Defines a registry for Numba rewrites.
+ '''
+ _kinds = frozenset(['before-inference', 'after-inference'])
+
+ def __init__(self):
+ '''Constructor for the rewrite registry. Initializes the rewrites
+ member to an empty list.
+ '''
+ self.rewrites = defaultdict(list)
+
+ def register(self, kind):
+ """
+ Decorator adding a subclass of Rewrite to the registry for
+ the given *kind*.
+ """
+ if kind not in self._kinds:
+ raise KeyError("invalid kind %r" % (kind,))
+ def do_register(rewrite_cls):
+ if not issubclass(rewrite_cls, Rewrite):
+ raise TypeError('{0} is not a subclass of Rewrite'.format(
+ rewrite_cls))
+ self.rewrites[kind].append(rewrite_cls)
+ return rewrite_cls
+ return do_register
+
+ def apply(self, kind, state):
+ '''Given a pipeline and a dictionary of basic blocks, exhaustively
+ attempt to apply all registered rewrites to all basic blocks.
+ '''
+ assert kind in self._kinds
+ blocks = state.func_ir.blocks
+ old_blocks = blocks.copy()
+ for rewrite_cls in self.rewrites[kind]:
+ # Exhaustively apply a rewrite until it stops matching.
+ rewrite = rewrite_cls(state)
+ work_list = list(blocks.items())
+ while work_list:
+ key, block = work_list.pop()
+ matches = rewrite.match(state.func_ir, block, state.typemap,
+ state.calltypes)
+ if matches:
+ if config.DEBUG or config.DUMP_IR:
+ print("_" * 70)
+ print("REWRITING (%s):" % rewrite_cls.__name__)
+ block.dump()
+ print("_" * 60)
+ new_block = rewrite.apply()
+ blocks[key] = new_block
+ work_list.append((key, new_block))
+ if config.DEBUG or config.DUMP_IR:
+ new_block.dump()
+ print("_" * 70)
+ # If any blocks were changed, perform a sanity check.
+ for key, block in blocks.items():
+ if block != old_blocks[key]:
+ block.verify()
+
+ # Some passes, e.g. _inline_const_arraycall are known to occasionally
+ # do invalid things WRT ir.Del, others, e.g. RewriteArrayExprs do valid
+ # things with ir.Del, but the placement is not optimal. The lines below
+ # fix-up the IR so that ref counts are valid and optimally placed,
+ # see #4093 for context. This has to be run here opposed to in
+ # apply() as the CFG needs computing so full IR is needed.
+ from numba.core import postproc
+ post_proc = postproc.PostProcessor(state.func_ir)
+ post_proc.run()
+
+
+rewrite_registry = RewriteRegistry()
+register_rewrite = rewrite_registry.register
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/rewrites/static_binop.py b/tool_server/.venv/lib/python3.12/site-packages/numba/core/rewrites/static_binop.py
new file mode 100644
index 0000000000000000000000000000000000000000..33487a67549856c73d655cc1fc59a95eab941f6b
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/core/rewrites/static_binop.py
@@ -0,0 +1,35 @@
+from numba.core import errors, ir
+from numba.core.rewrites import register_rewrite, Rewrite
+
+
+@register_rewrite('before-inference')
+class DetectStaticBinops(Rewrite):
+ """
+ Detect constant arguments to select binops.
+ """
+
+ # Those operators can benefit from a constant-inferred argument
+ rhs_operators = {'**'}
+
+ def match(self, func_ir, block, typemap, calltypes):
+ self.static_lhs = {}
+ self.static_rhs = {}
+ self.block = block
+ # Find binop expressions with a constant lhs or rhs
+ for expr in block.find_exprs(op='binop'):
+ try:
+ if (expr.fn in self.rhs_operators
+ and expr.static_rhs is ir.UNDEFINED):
+ self.static_rhs[expr] = func_ir.infer_constant(expr.rhs)
+ except errors.ConstantInferenceError:
+ continue
+
+ return len(self.static_lhs) > 0 or len(self.static_rhs) > 0
+
+ def apply(self):
+ """
+ Store constant arguments that were detected in match().
+ """
+ for expr, rhs in self.static_rhs.items():
+ expr.static_rhs = rhs
+ return self.block
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/rewrites/static_getitem.py b/tool_server/.venv/lib/python3.12/site-packages/numba/core/rewrites/static_getitem.py
new file mode 100644
index 0000000000000000000000000000000000000000..56343d0eac93cef756834d22c76780e228398a7d
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/core/rewrites/static_getitem.py
@@ -0,0 +1,175 @@
+from numba.core import errors, ir, types
+from numba.core.rewrites import register_rewrite, Rewrite
+
+
+@register_rewrite('before-inference')
+class RewriteConstGetitems(Rewrite):
+ """
+ Rewrite IR expressions of the kind `getitem(value=arr, index=$constXX)`
+ where `$constXX` is a known constant as
+ `static_getitem(value=arr, index=)`.
+ """
+
+ def match(self, func_ir, block, typemap, calltypes):
+ self.getitems = getitems = {}
+ self.block = block
+ # Detect all getitem expressions and find which ones can be
+ # rewritten
+ for expr in block.find_exprs(op='getitem'):
+ if expr.op == 'getitem':
+ try:
+ const = func_ir.infer_constant(expr.index)
+ except errors.ConstantInferenceError:
+ continue
+ getitems[expr] = const
+
+ return len(getitems) > 0
+
+ def apply(self):
+ """
+ Rewrite all matching getitems as static_getitems.
+ """
+ new_block = self.block.copy()
+ new_block.clear()
+ for inst in self.block.body:
+ if isinstance(inst, ir.Assign):
+ expr = inst.value
+ if expr in self.getitems:
+ const = self.getitems[expr]
+ new_expr = ir.Expr.static_getitem(value=expr.value,
+ index=const,
+ index_var=expr.index,
+ loc=expr.loc)
+ inst = ir.Assign(value=new_expr, target=inst.target,
+ loc=inst.loc)
+ new_block.append(inst)
+ return new_block
+
+
+@register_rewrite('after-inference')
+class RewriteStringLiteralGetitems(Rewrite):
+ """
+ Rewrite IR expressions of the kind `getitem(value=arr, index=$XX)`
+ where `$XX` is a StringLiteral value as
+ `static_getitem(value=arr, index=)`.
+ """
+
+ def match(self, func_ir, block, typemap, calltypes):
+ """
+ Detect all getitem expressions and find which ones have
+ string literal indexes
+ """
+ self.getitems = getitems = {}
+ self.block = block
+ self.calltypes = calltypes
+ for expr in block.find_exprs(op='getitem'):
+ if expr.op == 'getitem':
+ index_ty = typemap[expr.index.name]
+ if isinstance(index_ty, types.StringLiteral):
+ getitems[expr] = (expr.index, index_ty.literal_value)
+
+ return len(getitems) > 0
+
+ def apply(self):
+ """
+ Rewrite all matching getitems as static_getitems where the index
+ is the literal value of the string.
+ """
+ new_block = ir.Block(self.block.scope, self.block.loc)
+ for inst in self.block.body:
+ if isinstance(inst, ir.Assign):
+ expr = inst.value
+ if expr in self.getitems:
+ const, lit_val = self.getitems[expr]
+ new_expr = ir.Expr.static_getitem(value=expr.value,
+ index=lit_val,
+ index_var=expr.index,
+ loc=expr.loc)
+ self.calltypes[new_expr] = self.calltypes[expr]
+ inst = ir.Assign(value=new_expr, target=inst.target,
+ loc=inst.loc)
+ new_block.append(inst)
+ return new_block
+
+
+@register_rewrite('after-inference')
+class RewriteStringLiteralSetitems(Rewrite):
+ """
+ Rewrite IR expressions of the kind `setitem(value=arr, index=$XX, value=)`
+ where `$XX` is a StringLiteral value as
+ `static_setitem(value=arr, index=, value=)`.
+ """
+
+ def match(self, func_ir, block, typemap, calltypes):
+ """
+ Detect all setitem expressions and find which ones have
+ string literal indexes
+ """
+ self.setitems = setitems = {}
+ self.block = block
+ self.calltypes = calltypes
+ for inst in block.find_insts(ir.SetItem):
+ index_ty = typemap[inst.index.name]
+ if isinstance(index_ty, types.StringLiteral):
+ setitems[inst] = (inst.index, index_ty.literal_value)
+
+ return len(setitems) > 0
+
+ def apply(self):
+ """
+ Rewrite all matching setitems as static_setitems where the index
+ is the literal value of the string.
+ """
+ new_block = ir.Block(self.block.scope, self.block.loc)
+ for inst in self.block.body:
+ if isinstance(inst, ir.SetItem):
+ if inst in self.setitems:
+ const, lit_val = self.setitems[inst]
+ new_inst = ir.StaticSetItem(target=inst.target,
+ index=lit_val,
+ index_var=inst.index,
+ value=inst.value,
+ loc=inst.loc)
+ self.calltypes[new_inst] = self.calltypes[inst]
+ inst = new_inst
+ new_block.append(inst)
+ return new_block
+
+
+@register_rewrite('before-inference')
+class RewriteConstSetitems(Rewrite):
+ """
+ Rewrite IR statements of the kind `setitem(target=arr, index=$constXX, ...)`
+ where `$constXX` is a known constant as
+ `static_setitem(target=arr, index=, ...)`.
+ """
+
+ def match(self, func_ir, block, typemap, calltypes):
+ self.setitems = setitems = {}
+ self.block = block
+ # Detect all setitem statements and find which ones can be
+ # rewritten
+ for inst in block.find_insts(ir.SetItem):
+ try:
+ const = func_ir.infer_constant(inst.index)
+ except errors.ConstantInferenceError:
+ continue
+ setitems[inst] = const
+
+ return len(setitems) > 0
+
+ def apply(self):
+ """
+ Rewrite all matching setitems as static_setitems.
+ """
+ new_block = self.block.copy()
+ new_block.clear()
+ for inst in self.block.body:
+ if inst in self.setitems:
+ const = self.setitems[inst]
+ new_inst = ir.StaticSetItem(inst.target, const,
+ inst.index, inst.value, inst.loc)
+ new_block.append(new_inst)
+ else:
+ new_block.append(inst)
+ return new_block
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/rewrites/static_raise.py b/tool_server/.venv/lib/python3.12/site-packages/numba/core/rewrites/static_raise.py
new file mode 100644
index 0000000000000000000000000000000000000000..7527e571f026fcf0eef9c53645caa46a94b37f73
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/core/rewrites/static_raise.py
@@ -0,0 +1,93 @@
+from numba.core import errors, ir, consts
+from numba.core.rewrites import register_rewrite, Rewrite
+
+
+@register_rewrite('before-inference')
+class RewriteConstRaises(Rewrite):
+ """
+ Rewrite IR statements of the kind `raise(value)`
+ where `value` is the result of instantiating an exception with
+ constant arguments
+ into `static_raise(exception_type, constant args)`.
+
+ This allows lowering in nopython mode, where one can't instantiate
+ exception instances from runtime data.
+ """
+
+ def _is_exception_type(self, const):
+ return isinstance(const, type) and issubclass(const, Exception)
+
+ def _break_constant(self, const, loc):
+ """
+ Break down constant exception.
+ """
+ if isinstance(const, tuple): # it's a tuple(exception class, args)
+ if not self._is_exception_type(const[0]):
+ msg = "Encountered unsupported exception constant %r"
+ raise errors.UnsupportedError(msg % (const[0],), loc)
+ return const[0], tuple(const[1])
+ elif self._is_exception_type(const):
+ return const, None
+ else:
+ if isinstance(const, str):
+ msg = ("Directly raising a string constant as an exception is "
+ "not supported.")
+ else:
+ msg = "Encountered unsupported constant type used for exception"
+ raise errors.UnsupportedError(msg, loc)
+
+ def _try_infer_constant(self, func_ir, inst):
+ try:
+ return func_ir.infer_constant(inst.exception)
+ except consts.ConstantInferenceError:
+ # not a static exception
+ return None
+
+ def match(self, func_ir, block, typemap, calltypes):
+ self.raises = raises = {}
+ self.tryraises = tryraises = {}
+ self.block = block
+ # Detect all raise statements and find which ones can be
+ # rewritten
+ for inst in block.find_insts((ir.Raise, ir.TryRaise)):
+ if inst.exception is None:
+ # re-reraise
+ exc_type, exc_args = None, None
+ else:
+ # raise => find the definition site for
+ const = self._try_infer_constant(func_ir, inst)
+
+ # failure to infer constant indicates this isn't a static
+ # exception
+ if const is None:
+ continue
+
+ loc = inst.exception.loc
+ exc_type, exc_args = self._break_constant(const, loc)
+
+ if isinstance(inst, ir.Raise):
+ raises[inst] = exc_type, exc_args
+ elif isinstance(inst, ir.TryRaise):
+ tryraises[inst] = exc_type, exc_args
+ else:
+ raise ValueError('unexpected: {}'.format(type(inst)))
+ return (len(raises) + len(tryraises)) > 0
+
+ def apply(self):
+ """
+ Rewrite all matching setitems as static_setitems.
+ """
+ new_block = self.block.copy()
+ new_block.clear()
+ for inst in self.block.body:
+ if inst in self.raises:
+ exc_type, exc_args = self.raises[inst]
+ new_inst = ir.StaticRaise(exc_type, exc_args, inst.loc)
+ new_block.append(new_inst)
+ elif inst in self.tryraises:
+ exc_type, exc_args = self.tryraises[inst]
+ new_inst = ir.StaticTryRaise(exc_type, exc_args, inst.loc)
+ new_block.append(new_inst)
+ else:
+ new_block.append(inst)
+ return new_block
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/runtime/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/numba/core/runtime/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..5904700316933083c9996ee5e132c620f25014e0
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/core/runtime/__init__.py
@@ -0,0 +1 @@
+from .nrt import rtsys
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/runtime/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/runtime/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..52b5bf5340ba0d8b1b893efdac42167889970086
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/runtime/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/runtime/__pycache__/context.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/runtime/__pycache__/context.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5157dbd6f0ac23c3f64c2ee104016f006789763f
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/runtime/__pycache__/context.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/runtime/__pycache__/nrt.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/runtime/__pycache__/nrt.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fa6561d9ca3449220dcf8fe58d4e433c5341ce20
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/runtime/__pycache__/nrt.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/runtime/__pycache__/nrtdynmod.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/runtime/__pycache__/nrtdynmod.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0ecfb2e2cf0787c6a4ead70aebc125fc2eb90d20
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/runtime/__pycache__/nrtdynmod.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/runtime/__pycache__/nrtopt.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/runtime/__pycache__/nrtopt.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8b49a8eef82a4845ad7722e4777350502f6fba0f
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/runtime/__pycache__/nrtopt.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/runtime/_nrt_python.c b/tool_server/.venv/lib/python3.12/site-packages/numba/core/runtime/_nrt_python.c
new file mode 100644
index 0000000000000000000000000000000000000000..84d5886f439cab02e8167dd970fadee74ef46e5b
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/core/runtime/_nrt_python.c
@@ -0,0 +1,486 @@
+/*
+ * Definition of NRT functions for marshalling from / to Python objects.
+ * This module is included by _nrt_pythonmod.c and by pycc-compiled modules.
+ */
+
+#include "../../_pymodule.h"
+
+#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
+#include
+#include
+
+#include "../../_arraystruct.h"
+#include "../../_numba_common.h"
+#include "nrt.h"
+
+
+/*
+ * Create a NRT MemInfo for data owned by a PyObject.
+ */
+
+static void
+pyobject_dtor(void *ptr, size_t size, void* info) {
+ PyGILState_STATE gstate;
+ PyObject *ownerobj = info;
+
+ gstate = PyGILState_Ensure(); /* ensure the GIL */
+ Py_DECREF(ownerobj); /* release the python object */
+ PyGILState_Release(gstate); /* release the GIL */
+}
+
+NUMBA_EXPORT_FUNC(NRT_MemInfo *)
+NRT_meminfo_new_from_pyobject(void *data, PyObject *ownerobj) {
+ size_t dummy_size = 0;
+ Py_INCREF(ownerobj);
+ return NRT_MemInfo_new(data, dummy_size, pyobject_dtor, ownerobj);
+}
+
+
+/*
+ * A Python object wrapping a NRT meminfo.
+ */
+
+typedef struct {
+ PyObject_HEAD
+ NRT_MemInfo *meminfo;
+} MemInfoObject;
+
+
+static
+int MemInfo_init(MemInfoObject *self, PyObject *args, PyObject *kwds) {
+ static char *keywords[] = {"ptr", NULL};
+ PyObject *raw_ptr_obj;
+ void *raw_ptr;
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "O", keywords, &raw_ptr_obj)) {
+ return -1;
+ }
+ raw_ptr = PyLong_AsVoidPtr(raw_ptr_obj);
+ NRT_Debug(nrt_debug_print("MemInfo_init self=%p raw_ptr=%p\n", self, raw_ptr));
+
+ if(PyErr_Occurred()) return -1;
+ self->meminfo = (NRT_MemInfo *)raw_ptr;
+ assert (NRT_MemInfo_refcount(self->meminfo) > 0 && "0 refcount");
+ return 0;
+}
+
+
+static int
+MemInfo_getbuffer(PyObject *exporter, Py_buffer *view, int flags) {
+ Py_ssize_t len;
+ void *buf;
+ int readonly = 0;
+
+ MemInfoObject *miobj = (MemInfoObject*)exporter;
+ NRT_MemInfo *mi = miobj->meminfo;
+
+ buf = NRT_MemInfo_data(mi);
+ len = NRT_MemInfo_size(mi);
+ return PyBuffer_FillInfo(view, exporter, buf, len, readonly, flags);
+}
+
+static PyBufferProcs MemInfo_bufferProcs = {MemInfo_getbuffer, NULL};
+
+static
+PyObject*
+MemInfo_acquire(MemInfoObject *self) {
+ NRT_MemInfo_acquire(self->meminfo);
+ Py_RETURN_NONE;
+}
+
+static
+PyObject*
+MemInfo_release(MemInfoObject *self) {
+ NRT_MemInfo_release(self->meminfo);
+ Py_RETURN_NONE;
+}
+
+static
+PyObject*
+MemInfo_get_data(MemInfoObject *self, void *closure) {
+ return PyLong_FromVoidPtr(NRT_MemInfo_data(self->meminfo));
+}
+
+static
+PyObject*
+MemInfo_get_refcount(MemInfoObject *self, void *closure) {
+ size_t refct = NRT_MemInfo_refcount(self->meminfo);
+ if ( refct == (size_t)-1 ) {
+ PyErr_SetString(PyExc_ValueError, "invalid MemInfo");
+ return NULL;
+ }
+ return PyLong_FromSize_t(refct);
+}
+
+static
+PyObject*
+MemInfo_get_external_allocator(MemInfoObject *self, void *closure) {
+ void *p = NRT_MemInfo_external_allocator(self->meminfo);
+ return PyLong_FromVoidPtr(p);
+}
+
+static
+PyObject*
+MemInfo_get_parent(MemInfoObject *self, void *closure) {
+ void *p = NRT_MemInfo_parent(self->meminfo);
+ if (p) {
+ Py_INCREF(p);
+ return (PyObject*)p;
+ } else {
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
+}
+
+static void
+MemInfo_dealloc(MemInfoObject *self)
+{
+ NRT_MemInfo_release(self->meminfo);
+ Py_TYPE(self)->tp_free((PyObject*)self);
+}
+
+static PyMethodDef MemInfo_methods[] = {
+ {"acquire", (PyCFunction)MemInfo_acquire, METH_NOARGS,
+ "Increment the reference count"
+ },
+ {"release", (PyCFunction)MemInfo_release, METH_NOARGS,
+ "Decrement the reference count"
+ },
+ {NULL} /* Sentinel */
+};
+
+
+static PyGetSetDef MemInfo_getsets[] = {
+ {"data",
+ (getter)MemInfo_get_data, NULL,
+ "Get the data pointer as an integer",
+ NULL},
+ {"refcount",
+ (getter)MemInfo_get_refcount, NULL,
+ "Get the refcount",
+ NULL},
+ {"external_allocator",
+ (getter)MemInfo_get_external_allocator, NULL,
+ "Get the external allocator",
+ NULL},
+ {"parent",
+ (getter)MemInfo_get_parent, NULL,
+ NULL},
+ {NULL} /* Sentinel */
+};
+
+
+static PyTypeObject MemInfoType = {
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "_nrt_python._MemInfo", /* tp_name */
+ sizeof(MemInfoObject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ (destructor)MemInfo_dealloc, /* tp_dealloc */
+ 0, /* tp_vectorcall_offset */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_as_async */
+ 0, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ 0, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ 0, /* tp_getattro */
+ 0, /* tp_setattro */
+ &MemInfo_bufferProcs, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
+ 0, /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ MemInfo_methods, /* tp_methods */
+ 0, /* tp_members */
+ MemInfo_getsets, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ (initproc)MemInfo_init, /* tp_init */
+ 0, /* tp_alloc */
+ 0, /* tp_new */
+ 0, /* tp_free */
+ 0, /* tp_is_gc */
+ 0, /* tp_bases */
+ 0, /* tp_mro */
+ 0, /* tp_cache */
+ 0, /* tp_subclasses */
+ 0, /* tp_weaklist */
+ 0, /* tp_del */
+ 0, /* tp_version_tag */
+ 0, /* tp_finalize */
+ 0, /* tp_vectorcall */
+#if (PY_MAJOR_VERSION == 3) && (PY_MINOR_VERSION == 12)
+/* This was introduced first in 3.12
+ * https://github.com/python/cpython/issues/91051
+ */
+ 0, /* tp_watched */
+#endif
+
+/* WARNING: Do not remove this, only modify it! It is a version guard to
+ * act as a reminder to update this struct on Python version update! */
+#if (PY_MAJOR_VERSION == 3)
+#if ! (NB_SUPPORTED_PYTHON_MINOR)
+#error "Python minor version is not supported."
+#endif
+#else
+#error "Python major version is not supported."
+#endif
+/* END WARNING*/
+};
+
+/*
+Return a MemInfo* as a MemInfoObject*
+The NRT reference to the MemInfo is borrowed.
+*/
+NUMBA_EXPORT_FUNC(MemInfoObject*)
+NRT_meminfo_as_pyobject(NRT_MemInfo *meminfo) {
+ MemInfoObject *mi;
+ PyObject *addr;
+
+ addr = PyLong_FromVoidPtr(meminfo);
+ if (!addr) return NULL;
+ mi = (MemInfoObject*)PyObject_CallFunctionObjArgs((PyObject *)&MemInfoType, addr, NULL);
+ Py_DECREF(addr);
+ if (!mi) return NULL;
+ return mi;
+}
+
+
+/*
+Return a MemInfo* from a MemInfoObject*
+A new reference is returned.
+*/
+NUMBA_EXPORT_FUNC(NRT_MemInfo*)
+NRT_meminfo_from_pyobject(MemInfoObject *miobj) {
+ NRT_MemInfo_acquire(miobj->meminfo);
+ return miobj->meminfo;
+}
+
+
+/*
+ * Array adaptor code
+ */
+
+NUMBA_EXPORT_FUNC(int)
+NRT_adapt_ndarray_from_python(PyObject *obj, arystruct_t* arystruct) {
+ PyArrayObject *ndary;
+ int i, ndim;
+ npy_intp *p;
+ void *data;
+
+ if (!PyArray_Check(obj)) {
+ return -1;
+ }
+
+ ndary = (PyArrayObject*)obj;
+ ndim = PyArray_NDIM(ndary);
+ data = PyArray_DATA(ndary);
+
+ arystruct->meminfo = NRT_meminfo_new_from_pyobject((void*)data, obj);
+ arystruct->data = data;
+ arystruct->nitems = PyArray_SIZE(ndary);
+ arystruct->itemsize = PyArray_ITEMSIZE(ndary);
+ arystruct->parent = obj;
+ p = arystruct->shape_and_strides;
+ for (i = 0; i < ndim; i++, p++) {
+ *p = PyArray_DIM(ndary, i);
+ }
+ for (i = 0; i < ndim; i++, p++) {
+ *p = PyArray_STRIDE(ndary, i);
+ }
+
+ NRT_Debug(nrt_debug_print("NRT_adapt_ndarray_from_python %p\n",
+ arystruct->meminfo));
+ return 0;
+}
+
+static
+PyObject* try_to_return_parent(arystruct_t *arystruct, int ndim,
+ PyArray_Descr *descr)
+{
+ int i;
+ PyArrayObject *array = (PyArrayObject *)arystruct->parent;
+
+ if (!PyArray_Check(arystruct->parent))
+ /* Parent is a generic buffer-providing object */
+ goto RETURN_ARRAY_COPY;
+
+ if (PyArray_DATA(array) != arystruct->data)
+ goto RETURN_ARRAY_COPY;
+
+ if (PyArray_NDIM(array) != ndim)
+ goto RETURN_ARRAY_COPY;
+
+ if (PyObject_RichCompareBool((PyObject *) PyArray_DESCR(array),
+ (PyObject *) descr, Py_EQ) <= 0)
+ goto RETURN_ARRAY_COPY;
+
+ for(i = 0; i < ndim; ++i) {
+ if (PyArray_DIMS(array)[i] != arystruct->shape_and_strides[i])
+ goto RETURN_ARRAY_COPY;
+ if (PyArray_STRIDES(array)[i] != arystruct->shape_and_strides[ndim + i])
+ goto RETURN_ARRAY_COPY;
+ }
+
+ /* Yes, it is the same array
+ Return new reference */
+ Py_INCREF((PyObject *)array);
+ return (PyObject *)array;
+
+RETURN_ARRAY_COPY:
+ return NULL;
+}
+
+/**
+ * This function is used during the boxing of ndarray type.
+ * `arystruct` is a structure containing essential information from the
+ * unboxed array.
+ * `retty` is the subtype of the NumPy PyArray_Type this function should return.
+ * This is related to `numba.core.types.Array.box_type`.
+ * `ndim` is the number of dimension of the array.
+ * `writeable` corresponds to the "writable" flag in NumPy ndarray.
+ * `descr` is the NumPy data type description.
+ *
+ * This function was renamed in 0.52.0 to specify that it acquires references.
+ * It used to steal the reference of the arystruct.
+ * Refer to https://github.com/numba/numba/pull/6446
+ */
+NUMBA_EXPORT_FUNC(PyObject *)
+NRT_adapt_ndarray_to_python_acqref(arystruct_t* arystruct, PyTypeObject *retty,
+ int ndim, int writeable, PyArray_Descr *descr)
+{
+ PyArrayObject *array;
+ MemInfoObject *miobj = NULL;
+ PyObject *args;
+ npy_intp *shape, *strides;
+ int flags = 0;
+
+ if (descr == NULL) {
+ PyErr_Format(PyExc_RuntimeError,
+ "In 'NRT_adapt_ndarray_to_python', 'descr' is NULL");
+ return NULL;
+ }
+
+ if (!NUMBA_PyArray_DescrCheck(descr)) {
+ PyErr_Format(PyExc_TypeError,
+ "expected dtype object, got '%.200s'",
+ Py_TYPE(descr)->tp_name);
+ return NULL;
+ }
+
+ if (arystruct->parent) {
+ PyObject *obj = try_to_return_parent(arystruct, ndim, descr);
+ if (obj) {
+ return obj;
+ }
+ }
+
+ if (arystruct->meminfo) {
+ /* wrap into MemInfoObject */
+ miobj = PyObject_New(MemInfoObject, &MemInfoType);
+ args = PyTuple_New(1);
+ /* SETITEM steals reference */
+ PyTuple_SET_ITEM(args, 0, PyLong_FromVoidPtr(arystruct->meminfo));
+ NRT_Debug(nrt_debug_print("NRT_adapt_ndarray_to_python arystruct->meminfo=%p\n", arystruct->meminfo));
+ /* Note: MemInfo_init() does not incref. This function steals the
+ * NRT reference, which we need to acquire.
+ */
+ NRT_Debug(nrt_debug_print("NRT_adapt_ndarray_to_python_acqref created MemInfo=%p\n", miobj));
+ NRT_MemInfo_acquire(arystruct->meminfo);
+ if (MemInfo_init(miobj, args, NULL)) {
+ NRT_Debug(nrt_debug_print("MemInfo_init failed.\n"));
+ return NULL;
+ }
+ Py_DECREF(args);
+ }
+
+ shape = arystruct->shape_and_strides;
+ strides = shape + ndim;
+ Py_INCREF((PyObject *) descr);
+ array = (PyArrayObject *) PyArray_NewFromDescr(retty, descr, ndim,
+ shape, strides, arystruct->data,
+ flags, (PyObject *) miobj);
+
+ if (array == NULL)
+ return NULL;
+
+ /* Set writable */
+#if NPY_API_VERSION >= 0x00000007
+ if (writeable) {
+ PyArray_ENABLEFLAGS(array, NPY_ARRAY_WRITEABLE);
+ }
+ else {
+ PyArray_CLEARFLAGS(array, NPY_ARRAY_WRITEABLE);
+ }
+#else
+ if (writeable) {
+ array->flags |= NPY_WRITEABLE;
+ }
+ else {
+ array->flags &= ~NPY_WRITEABLE;
+ }
+#endif
+
+ if (miobj) {
+ /* Set the MemInfoObject as the base object */
+#if NPY_API_VERSION >= 0x00000007
+ if (-1 == PyArray_SetBaseObject(array,
+ (PyObject *) miobj))
+ {
+ Py_DECREF(array);
+ Py_DECREF(miobj);
+ return NULL;
+ }
+#else
+ PyArray_BASE(array) = (PyObject *) miobj;
+#endif
+
+ }
+ return (PyObject *) array;
+}
+
+NUMBA_EXPORT_FUNC(void)
+NRT_adapt_buffer_from_python(Py_buffer *buf, arystruct_t *arystruct)
+{
+ int i;
+ npy_intp *p;
+
+ if (buf->obj) {
+ /* Allocate new MemInfo only if the buffer has a parent */
+ arystruct->meminfo = NRT_meminfo_new_from_pyobject((void*)buf->buf, buf->obj);
+ }
+ arystruct->data = buf->buf;
+ arystruct->itemsize = buf->itemsize;
+ arystruct->parent = buf->obj;
+ arystruct->nitems = 1;
+ p = arystruct->shape_and_strides;
+ for (i = 0; i < buf->ndim; i++, p++) {
+ *p = buf->shape[i];
+ arystruct->nitems *= buf->shape[i];
+ }
+ for (i = 0; i < buf->ndim; i++, p++) {
+ *p = buf->strides[i];
+ }
+}
+
+
+/* Initialization subroutines for modules including this source file */
+
+static int
+init_nrt_python_module(PyObject *module)
+{
+ MemInfoType.tp_new = PyType_GenericNew;
+ if (PyType_Ready(&MemInfoType))
+ return -1;
+ return 0;
+}
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/runtime/_nrt_python.cpython-312-x86_64-linux-gnu.so b/tool_server/.venv/lib/python3.12/site-packages/numba/core/runtime/_nrt_python.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..67e63e5d00ff98904c403dade87dd1a91ff3254e
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/core/runtime/_nrt_python.cpython-312-x86_64-linux-gnu.so
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:8737ea90a16ab30d3b7ce522b993c513f042ed9a98018119adc99adaf2675e95
+size 196232
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/runtime/_nrt_pythonmod.c b/tool_server/.venv/lib/python3.12/site-packages/numba/core/runtime/_nrt_pythonmod.c
new file mode 100644
index 0000000000000000000000000000000000000000..19eb120fac011064c2c2e73ba8cdb6affc2fbf53
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/core/runtime/_nrt_pythonmod.c
@@ -0,0 +1,217 @@
+#define NUMBA_EXPORT_FUNC(_rettype) static _rettype
+#define NUMBA_EXPORT_DATA(_vartype) static _vartype
+
+#include "_nrt_python.c"
+
+static PyObject *
+memsys_shutdown(PyObject *self, PyObject *args) {
+ NRT_MemSys_shutdown();
+ Py_RETURN_NONE;
+}
+
+static PyObject *
+memsys_use_cpython_allocator(PyObject *self, PyObject *args) {
+ NRT_MemSys_set_allocator(PyMem_RawMalloc,
+ PyMem_RawRealloc,
+ PyMem_RawFree);
+ Py_RETURN_NONE;
+}
+
+static PyObject *
+memsys_get_stats_alloc(PyObject *self, PyObject *args) {
+ if(!NRT_MemSys_stats_enabled()) {
+ PyErr_SetString(PyExc_RuntimeError, "NRT stats are disabled.");
+ return NULL;
+ }
+ return PyLong_FromSize_t(NRT_MemSys_get_stats_alloc());
+}
+
+static PyObject *
+memsys_get_stats_free(PyObject *self, PyObject *args) {
+ if(!NRT_MemSys_stats_enabled()) {
+ PyErr_SetString(PyExc_RuntimeError, "NRT stats are disabled.");
+ return NULL;
+ }
+ return PyLong_FromSize_t(NRT_MemSys_get_stats_free());
+}
+
+static PyObject *
+memsys_get_stats_mi_alloc(PyObject *self, PyObject *args) {
+ if(!NRT_MemSys_stats_enabled()) {
+ PyErr_SetString(PyExc_RuntimeError, "NRT stats are disabled.");
+ return NULL;
+ }
+ return PyLong_FromSize_t(NRT_MemSys_get_stats_mi_alloc());
+}
+
+static PyObject *
+memsys_get_stats_mi_free(PyObject *self, PyObject *args) {
+ if(!NRT_MemSys_stats_enabled()) {
+ PyErr_SetString(PyExc_RuntimeError, "NRT stats are disabled.");
+ return NULL;
+ }
+ return PyLong_FromSize_t(NRT_MemSys_get_stats_mi_free());
+}
+
+static PyObject *
+memsys_stats_enabled(PyObject *self, PyObject *args) {
+ if (NRT_MemSys_stats_enabled()) {
+ Py_RETURN_TRUE;
+ } else {
+ Py_RETURN_FALSE;
+ }
+}
+
+static PyObject *
+memsys_enable_stats(PyObject *self, PyObject *args) {
+ NRT_MemSys_enable_stats();
+ Py_RETURN_NONE;
+}
+
+static PyObject *
+memsys_disable_stats(PyObject *self, PyObject *args) {
+ NRT_MemSys_disable_stats();
+ Py_RETURN_NONE;
+}
+
+/*
+ * Create a new MemInfo with a owner PyObject
+ */
+static PyObject *
+meminfo_new(PyObject *self, PyObject *args) {
+ PyObject *addr_data_obj;
+ void *addr_data;
+ PyObject *ownerobj;
+ NRT_MemInfo *mi;
+ if (!PyArg_ParseTuple(args, "OO", &addr_data_obj, &ownerobj)) {
+ return NULL;
+ }
+ addr_data = PyLong_AsVoidPtr(addr_data_obj);
+ if (PyErr_Occurred())
+ return NULL;
+ mi = NRT_meminfo_new_from_pyobject(addr_data, ownerobj);
+ return PyLong_FromVoidPtr(mi);
+}
+
+/*
+ * Create a new MemInfo with a new NRT allocation
+ */
+static PyObject *
+meminfo_alloc(PyObject *self, PyObject *args) {
+ NRT_MemInfo *mi;
+ Py_ssize_t size;
+ if (!PyArg_ParseTuple(args, "n", &size)) {
+ return NULL;
+ }
+ mi = NRT_MemInfo_alloc(size);
+ return PyLong_FromVoidPtr(mi);
+}
+
+/*
+ * Like meminfo_alloc but set memory to zero after allocation and before
+ * deallocation.
+ */
+static PyObject *
+meminfo_alloc_safe(PyObject *self, PyObject *args) {
+ NRT_MemInfo *mi;
+ Py_ssize_t size;
+ if (!PyArg_ParseTuple(args, "n", &size)) {
+ return NULL;
+ }
+ mi = NRT_MemInfo_alloc_safe(size);
+ return PyLong_FromVoidPtr(mi);
+}
+
+static PyMethodDef ext_methods[] = {
+#define declmethod(func) { #func , ( PyCFunction )func , METH_VARARGS , NULL }
+#define declmethod_noargs(func) { #func , ( PyCFunction )func , METH_NOARGS, NULL }
+ declmethod_noargs(memsys_use_cpython_allocator),
+ declmethod_noargs(memsys_shutdown),
+ declmethod_noargs(memsys_get_stats_alloc),
+ declmethod_noargs(memsys_get_stats_free),
+ declmethod_noargs(memsys_get_stats_mi_alloc),
+ declmethod_noargs(memsys_get_stats_mi_free),
+ declmethod_noargs(memsys_stats_enabled),
+ declmethod_noargs(memsys_enable_stats),
+ declmethod_noargs(memsys_disable_stats),
+ declmethod(meminfo_new),
+ declmethod(meminfo_alloc),
+ declmethod(meminfo_alloc_safe),
+ { NULL },
+#undef declmethod
+};
+
+
+
+static PyObject *
+build_c_helpers_dict(void)
+{
+ PyObject *dct = PyDict_New();
+ if (dct == NULL)
+ goto error;
+
+#define _declpointer(name, value) do { \
+ PyObject *o = PyLong_FromVoidPtr(value); \
+ if (o == NULL) goto error; \
+ if (PyDict_SetItemString(dct, name, o)) { \
+ Py_DECREF(o); \
+ goto error; \
+ } \
+ Py_DECREF(o); \
+} while (0)
+
+#define declmethod(func) _declpointer(#func, &NRT_##func)
+#define declmethod_internal(func) _declpointer(#func, &func)
+
+declmethod(adapt_ndarray_from_python);
+declmethod(adapt_ndarray_to_python_acqref);
+declmethod(adapt_buffer_from_python);
+declmethod(meminfo_new_from_pyobject);
+declmethod(meminfo_as_pyobject);
+declmethod(meminfo_from_pyobject);
+declmethod(MemInfo_alloc);
+declmethod(MemInfo_alloc_safe);
+declmethod(MemInfo_alloc_aligned);
+declmethod(MemInfo_alloc_safe_aligned);
+declmethod(MemInfo_alloc_safe_aligned_external);
+declmethod_internal(_nrt_get_sample_external_allocator);
+declmethod(MemInfo_alloc_dtor);
+declmethod(MemInfo_alloc_dtor_safe);
+declmethod(MemInfo_call_dtor);
+declmethod(MemInfo_new_varsize);
+declmethod(MemInfo_new_varsize_dtor);
+declmethod(MemInfo_varsize_alloc);
+declmethod(MemInfo_data);
+declmethod(MemInfo_varsize_free);
+declmethod(MemInfo_varsize_realloc);
+declmethod(MemInfo_release);
+declmethod(Allocate);
+declmethod(Free);
+declmethod(get_api);
+
+
+#undef declmethod
+#undef declmethod_internal
+ return dct;
+error:
+ Py_XDECREF(dct);
+ return NULL;
+}
+
+MOD_INIT(_nrt_python) {
+ PyObject *m;
+ MOD_DEF(m, "_nrt_python", "No docs", ext_methods)
+ if (m == NULL)
+ return MOD_ERROR_VAL;
+ import_array();
+ NRT_MemSys_init();
+ if (init_nrt_python_module(m))
+ return MOD_ERROR_VAL;
+
+ Py_INCREF(&MemInfoType);
+ PyModule_AddObject(m, "_MemInfo", (PyObject *) (&MemInfoType));
+
+ PyModule_AddObject(m, "c_helpers", build_c_helpers_dict());
+
+ return MOD_SUCCESS_VAL(m);
+}
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/runtime/context.py b/tool_server/.venv/lib/python3.12/site-packages/numba/core/runtime/context.py
new file mode 100644
index 0000000000000000000000000000000000000000..8a8458d63027159914c19e658f65ba47bb9d8e08
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/core/runtime/context.py
@@ -0,0 +1,426 @@
+import functools
+from collections import namedtuple
+
+from llvmlite import ir
+from numba.core import types, cgutils, errors, config
+from numba.core.utils import PYVERSION
+
+
+_NRT_Meminfo_Functions = namedtuple("_NRT_Meminfo_Functions",
+ ("alloc",
+ "alloc_dtor",
+ "alloc_aligned"))
+
+
+_NRT_MEMINFO_SAFE_API = _NRT_Meminfo_Functions("NRT_MemInfo_alloc_safe",
+ "NRT_MemInfo_alloc_dtor_safe",
+ "NRT_MemInfo_alloc_safe_aligned")
+
+
+_NRT_MEMINFO_DEFAULT_API = _NRT_Meminfo_Functions("NRT_MemInfo_alloc",
+ "NRT_MemInfo_alloc_dtor",
+ "NRT_MemInfo_alloc_aligned")
+
+
+class NRTContext(object):
+ """
+ An object providing access to NRT APIs in the lowering pass.
+ """
+
+ def __init__(self, context, enabled):
+ self._context = context
+ self._enabled = enabled
+ # If DEBUG_NRT is set, use the safe function variants which use memset
+ # to inject a few known bytes into the start of allocated regions.
+ if config.DEBUG_NRT:
+ self._meminfo_api = _NRT_MEMINFO_SAFE_API
+ else:
+ self._meminfo_api = _NRT_MEMINFO_DEFAULT_API
+
+ def _require_nrt(self):
+ if not self._enabled:
+ raise errors.NumbaRuntimeError("NRT required but not enabled")
+
+ def _check_null_result(func):
+ @functools.wraps(func)
+ def wrap(self, builder, *args, **kwargs):
+ memptr = func(self, builder, *args, **kwargs)
+ msg = "Allocation failed (probably too large)."
+ cgutils.guard_memory_error(self._context, builder, memptr, msg=msg)
+ return memptr
+ return wrap
+
+ @_check_null_result
+ def allocate(self, builder, size):
+ """
+ Low-level allocate a new memory area of `size` bytes. The result of the
+ call is checked and if it is NULL, i.e. allocation failed, then a
+ MemoryError is raised.
+ """
+ return self.allocate_unchecked(builder, size)
+
+ def allocate_unchecked(self, builder, size):
+ """
+ Low-level allocate a new memory area of `size` bytes. Returns NULL to
+ indicate error/failure to allocate.
+ """
+ self._require_nrt()
+
+ mod = builder.module
+ fnty = ir.FunctionType(cgutils.voidptr_t, [cgutils.intp_t])
+ fn = cgutils.get_or_insert_function(mod, fnty, "NRT_Allocate")
+ fn.return_value.add_attribute("noalias")
+ return builder.call(fn, [size])
+
+ def free(self, builder, ptr):
+ """
+ Low-level free a memory area allocated with allocate().
+ """
+ self._require_nrt()
+
+ mod = builder.module
+ fnty = ir.FunctionType(ir.VoidType(), [cgutils.voidptr_t])
+ fn = cgutils.get_or_insert_function(mod, fnty, "NRT_Free")
+ return builder.call(fn, [ptr])
+
+ @_check_null_result
+ def meminfo_alloc(self, builder, size):
+ """
+ Allocate a new MemInfo with a data payload of `size` bytes.
+
+ A pointer to the MemInfo is returned.
+
+ The result of the call is checked and if it is NULL, i.e. allocation
+ failed, then a MemoryError is raised.
+ """
+ return self.meminfo_alloc_unchecked(builder, size)
+
+ def meminfo_alloc_unchecked(self, builder, size):
+ """
+ Allocate a new MemInfo with a data payload of `size` bytes.
+
+ A pointer to the MemInfo is returned.
+
+ Returns NULL to indicate error/failure to allocate.
+ """
+ self._require_nrt()
+
+ mod = builder.module
+ fnty = ir.FunctionType(cgutils.voidptr_t, [cgutils.intp_t])
+ fn = cgutils.get_or_insert_function(mod, fnty,
+ self._meminfo_api.alloc)
+ fn.return_value.add_attribute("noalias")
+ return builder.call(fn, [size])
+
+ @_check_null_result
+ def meminfo_alloc_dtor(self, builder, size, dtor):
+ """
+ Allocate a new MemInfo with a data payload of `size` bytes and a
+ destructor `dtor`.
+
+ A pointer to the MemInfo is returned.
+
+ The result of the call is checked and if it is NULL, i.e. allocation
+ failed, then a MemoryError is raised.
+ """
+ return self.meminfo_alloc_dtor_unchecked(builder, size, dtor)
+
+ def meminfo_alloc_dtor_unchecked(self, builder, size, dtor):
+ """
+ Allocate a new MemInfo with a data payload of `size` bytes and a
+ destructor `dtor`.
+
+ A pointer to the MemInfo is returned.
+
+ Returns NULL to indicate error/failure to allocate.
+ """
+ self._require_nrt()
+
+ mod = builder.module
+ fnty = ir.FunctionType(cgutils.voidptr_t,
+ [cgutils.intp_t, cgutils.voidptr_t])
+ fn = cgutils.get_or_insert_function(mod, fnty,
+ self._meminfo_api.alloc_dtor)
+ fn.return_value.add_attribute("noalias")
+ return builder.call(fn, [size,
+ builder.bitcast(dtor, cgutils.voidptr_t)])
+
+ @_check_null_result
+ def meminfo_alloc_aligned(self, builder, size, align):
+ """
+ Allocate a new MemInfo with an aligned data payload of `size` bytes.
+ The data pointer is aligned to `align` bytes. `align` can be either
+ a Python int or a LLVM uint32 value.
+
+ A pointer to the MemInfo is returned.
+
+ The result of the call is checked and if it is NULL, i.e. allocation
+ failed, then a MemoryError is raised.
+ """
+ return self.meminfo_alloc_aligned_unchecked(builder, size, align)
+
+ def meminfo_alloc_aligned_unchecked(self, builder, size, align):
+ """
+ Allocate a new MemInfo with an aligned data payload of `size` bytes.
+ The data pointer is aligned to `align` bytes. `align` can be either
+ a Python int or a LLVM uint32 value.
+
+ A pointer to the MemInfo is returned.
+
+ Returns NULL to indicate error/failure to allocate.
+ """
+ self._require_nrt()
+
+ mod = builder.module
+ u32 = ir.IntType(32)
+ fnty = ir.FunctionType(cgutils.voidptr_t, [cgutils.intp_t, u32])
+ fn = cgutils.get_or_insert_function(mod, fnty,
+ self._meminfo_api.alloc_aligned)
+ fn.return_value.add_attribute("noalias")
+ if isinstance(align, int):
+ align = self._context.get_constant(types.uint32, align)
+ else:
+ assert align.type == u32, "align must be a uint32"
+ return builder.call(fn, [size, align])
+
+ @_check_null_result
+ def meminfo_new_varsize(self, builder, size):
+ """
+ Allocate a MemInfo pointing to a variable-sized data area. The area
+ is separately allocated (i.e. two allocations are made) so that
+ re-allocating it doesn't change the MemInfo's address.
+
+ A pointer to the MemInfo is returned.
+
+ The result of the call is checked and if it is NULL, i.e. allocation
+ failed, then a MemoryError is raised.
+ """
+ return self.meminfo_new_varsize_unchecked(builder, size)
+
+ def meminfo_new_varsize_unchecked(self, builder, size):
+ """
+ Allocate a MemInfo pointing to a variable-sized data area. The area
+ is separately allocated (i.e. two allocations are made) so that
+ re-allocating it doesn't change the MemInfo's address.
+
+ A pointer to the MemInfo is returned.
+
+ Returns NULL to indicate error/failure to allocate.
+ """
+ self._require_nrt()
+
+ mod = builder.module
+ fnty = ir.FunctionType(cgutils.voidptr_t, [cgutils.intp_t])
+ fn = cgutils.get_or_insert_function(mod, fnty,
+ "NRT_MemInfo_new_varsize")
+ fn.return_value.add_attribute("noalias")
+ return builder.call(fn, [size])
+
+ @_check_null_result
+ def meminfo_new_varsize_dtor(self, builder, size, dtor):
+ """
+ Like meminfo_new_varsize() but also set the destructor for
+ cleaning up references to objects inside the allocation.
+
+ A pointer to the MemInfo is returned.
+
+ The result of the call is checked and if it is NULL, i.e. allocation
+ failed, then a MemoryError is raised.
+ """
+ return self.meminfo_new_varsize_dtor_unchecked(builder, size, dtor)
+
+ def meminfo_new_varsize_dtor_unchecked(self, builder, size, dtor):
+ """
+ Like meminfo_new_varsize() but also set the destructor for
+ cleaning up references to objects inside the allocation.
+
+ A pointer to the MemInfo is returned.
+
+ Returns NULL to indicate error/failure to allocate.
+ """
+ self._require_nrt()
+
+ mod = builder.module
+ fnty = ir.FunctionType(cgutils.voidptr_t,
+ [cgutils.intp_t, cgutils.voidptr_t])
+ fn = cgutils.get_or_insert_function(
+ mod, fnty, "NRT_MemInfo_new_varsize_dtor")
+ return builder.call(fn, [size, dtor])
+
+ @_check_null_result
+ def meminfo_varsize_alloc(self, builder, meminfo, size):
+ """
+ Allocate a new data area for a MemInfo created by meminfo_new_varsize().
+ The new data pointer is returned, for convenience.
+
+ Contrary to realloc(), this always allocates a new area and doesn't
+ copy the old data. This is useful if resizing a container needs
+ more than simply copying the data area (e.g. for hash tables).
+
+ The old pointer will have to be freed with meminfo_varsize_free().
+
+ The result of the call is checked and if it is NULL, i.e. allocation
+ failed, then a MemoryError is raised.
+ """
+ return self.meminfo_varsize_alloc_unchecked(builder, meminfo, size)
+
+ def meminfo_varsize_alloc_unchecked(self, builder, meminfo, size):
+ """
+ Allocate a new data area for a MemInfo created by meminfo_new_varsize().
+ The new data pointer is returned, for convenience.
+
+ Contrary to realloc(), this always allocates a new area and doesn't
+ copy the old data. This is useful if resizing a container needs
+ more than simply copying the data area (e.g. for hash tables).
+
+ The old pointer will have to be freed with meminfo_varsize_free().
+
+ Returns NULL to indicate error/failure to allocate.
+ """
+ return self._call_varsize_alloc(builder, meminfo, size,
+ "NRT_MemInfo_varsize_alloc")
+
+ @_check_null_result
+ def meminfo_varsize_realloc(self, builder, meminfo, size):
+ """
+ Reallocate a data area allocated by meminfo_new_varsize().
+ The new data pointer is returned, for convenience.
+
+ The result of the call is checked and if it is NULL, i.e. allocation
+ failed, then a MemoryError is raised.
+ """
+ return self.meminfo_varsize_realloc_unchecked(builder, meminfo, size)
+
+ def meminfo_varsize_realloc_unchecked(self, builder, meminfo, size):
+ """
+ Reallocate a data area allocated by meminfo_new_varsize().
+ The new data pointer is returned, for convenience.
+
+ Returns NULL to indicate error/failure to allocate.
+ """
+ return self._call_varsize_alloc(builder, meminfo, size,
+ "NRT_MemInfo_varsize_realloc")
+
+ def meminfo_varsize_free(self, builder, meminfo, ptr):
+ """
+ Free a memory area allocated for a NRT varsize object.
+ Note this does *not* free the NRT object itself!
+ """
+ self._require_nrt()
+
+ mod = builder.module
+ fnty = ir.FunctionType(ir.VoidType(),
+ [cgutils.voidptr_t, cgutils.voidptr_t])
+ fn = cgutils.get_or_insert_function(mod, fnty,
+ "NRT_MemInfo_varsize_free")
+ return builder.call(fn, (meminfo, ptr))
+
+ def _call_varsize_alloc(self, builder, meminfo, size, funcname):
+ self._require_nrt()
+
+ mod = builder.module
+ fnty = ir.FunctionType(cgutils.voidptr_t,
+ [cgutils.voidptr_t, cgutils.intp_t])
+ fn = cgutils.get_or_insert_function(mod, fnty, funcname)
+ fn.return_value.add_attribute("noalias")
+ return builder.call(fn, [meminfo, size])
+
+ def meminfo_data(self, builder, meminfo):
+ """
+ Given a MemInfo pointer, return a pointer to the allocated data
+ managed by it. This works for MemInfos allocated with all the
+ above methods.
+ """
+ self._require_nrt()
+
+ from numba.core.runtime.nrtdynmod import meminfo_data_ty
+
+ mod = builder.module
+ fn = cgutils.get_or_insert_function(mod, meminfo_data_ty,
+ "NRT_MemInfo_data_fast")
+ return builder.call(fn, [meminfo])
+
+ def get_meminfos(self, builder, ty, val):
+ """Return a list of *(type, meminfo)* inside the given value.
+ """
+ datamodel = self._context.data_model_manager[ty]
+ members = datamodel.traverse(builder)
+
+ meminfos = []
+ if datamodel.has_nrt_meminfo():
+ mi = datamodel.get_nrt_meminfo(builder, val)
+ meminfos.append((ty, mi))
+
+ for mtyp, getter in members:
+ field = getter(val)
+ inner_meminfos = self.get_meminfos(builder, mtyp, field)
+ meminfos.extend(inner_meminfos)
+ return meminfos
+
+ def _call_incref_decref(self, builder, typ, value, funcname):
+ """Call function of *funcname* on every meminfo found in *value*.
+ """
+ self._require_nrt()
+
+ from numba.core.runtime.nrtdynmod import incref_decref_ty
+
+ meminfos = self.get_meminfos(builder, typ, value)
+ for _, mi in meminfos:
+ mod = builder.module
+ fn = cgutils.get_or_insert_function(mod, incref_decref_ty,
+ funcname)
+ # XXX "nonnull" causes a crash in test_dyn_array: can this
+ # function be called with a NULL pointer?
+ fn.args[0].add_attribute("noalias")
+ fn.args[0].add_attribute("nocapture")
+ builder.call(fn, [mi])
+
+ def incref(self, builder, typ, value):
+ """
+ Recursively incref the given *value* and its members.
+ """
+ self._call_incref_decref(builder, typ, value, "NRT_incref")
+
+ def decref(self, builder, typ, value):
+ """
+ Recursively decref the given *value* and its members.
+ """
+ self._call_incref_decref(builder, typ, value, "NRT_decref")
+
+ def get_nrt_api(self, builder):
+ """Calls NRT_get_api(), which returns the NRT API function table.
+ """
+ self._require_nrt()
+
+ fnty = ir.FunctionType(cgutils.voidptr_t, ())
+ mod = builder.module
+ fn = cgutils.get_or_insert_function(mod, fnty, "NRT_get_api")
+ return builder.call(fn, ())
+
+ def eh_check(self, builder):
+ """Check if an exception is raised
+ """
+ ctx = self._context
+ cc = ctx.call_conv
+ # Inspect the excinfo argument on the function
+ trystatus = cc.check_try_status(builder)
+ excinfo = trystatus.excinfo
+ has_raised = builder.not_(cgutils.is_null(builder, excinfo))
+ if PYVERSION < (3, 11):
+ with builder.if_then(has_raised):
+ self.eh_end_try(builder)
+ return has_raised
+
+ def eh_try(self, builder):
+ """Begin a try-block.
+ """
+ ctx = self._context
+ cc = ctx.call_conv
+ cc.set_try_status(builder)
+
+ def eh_end_try(self, builder):
+ """End a try-block
+ """
+ ctx = self._context
+ cc = ctx.call_conv
+ cc.unset_try_status(builder)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/runtime/nrt.cpp b/tool_server/.venv/lib/python3.12/site-packages/numba/core/runtime/nrt.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..e5644faf45c0a2d16cd11247d6bacd98ece91952
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/core/runtime/nrt.cpp
@@ -0,0 +1,629 @@
+/* MSVC C99 doesn't have , else this could be written in easily
+ * in C */
+#include
+
+#ifdef _MSC_VER
+#include
+#endif
+
+#include
+#include /* for memset */
+#include "nrt.h"
+#include "assert.h"
+
+
+/* NOTE: if changing the layout, please update numba.core.runtime.atomicops */
+extern "C" {
+struct MemInfo {
+ std::atomic_size_t refct;
+ NRT_dtor_function dtor;
+ void *dtor_info;
+ void *data;
+ size_t size; /* only used for NRT allocated memory */
+ NRT_ExternalAllocator *external_allocator;
+};
+}
+
+
+/*
+ * Misc helpers.
+ */
+
+static void nrt_fatal_error(const char *msg)
+{
+ fprintf(stderr, "Fatal Numba error: %s\n", msg);
+ fflush(stderr); /* it helps in Windows debug build */
+
+#if defined(MS_WINDOWS) && defined(_DEBUG)
+ DebugBreak();
+#endif
+ abort();
+}
+
+/*
+ * Global resources.
+ */
+
+struct NRT_MemSys {
+ /* Shutdown flag */
+ int shutting;
+ /* Stats */
+ struct {
+ bool enabled;
+ std::atomic_size_t alloc;
+ std::atomic_size_t free;
+ std::atomic_size_t mi_alloc;
+ std::atomic_size_t mi_free;
+ } stats;
+ /* System allocation functions */
+ struct {
+ NRT_malloc_func malloc;
+ NRT_realloc_func realloc;
+ NRT_free_func free;
+ } allocator;
+};
+
+
+/* The Memory System object */
+static NRT_MemSys TheMSys;
+
+
+extern "C" void NRT_MemSys_init(void) {
+ TheMSys.shutting = 0;
+ // Stats are off by default, call NRT_MemSys_enable_stats to enable
+ TheMSys.stats.enabled = false;
+ TheMSys.stats.alloc = 0;
+ TheMSys.stats.free = 0;
+ TheMSys.stats.mi_alloc = 0;
+ TheMSys.stats.mi_free = 0;
+ /* Bind to libc allocator */
+ TheMSys.allocator.malloc = malloc;
+ TheMSys.allocator.realloc = realloc;
+ TheMSys.allocator.free = free;
+}
+
+extern "C" void NRT_MemSys_shutdown(void) {
+ TheMSys.shutting = 1;
+}
+
+extern "C" void NRT_MemSys_enable_stats(void) {
+ TheMSys.stats.enabled = true;
+}
+
+extern "C" void NRT_MemSys_disable_stats(void) {
+ TheMSys.stats.enabled = false;
+}
+
+extern "C" size_t NRT_MemSys_stats_enabled(void) {
+ return (size_t)TheMSys.stats.enabled;
+}
+
+extern "C" void NRT_MemSys_set_allocator(NRT_malloc_func malloc_func,
+ NRT_realloc_func realloc_func,
+ NRT_free_func free_func)
+{
+ bool stats_cond = false;
+ if (TheMSys.stats.enabled)
+ {
+ stats_cond = (TheMSys.stats.alloc != TheMSys.stats.free ||
+ TheMSys.stats.mi_alloc != TheMSys.stats.mi_free);
+ }
+ if ((malloc_func != TheMSys.allocator.malloc ||
+ realloc_func != TheMSys.allocator.realloc ||
+ free_func != TheMSys.allocator.free) &&
+ stats_cond) {
+ nrt_fatal_error("cannot change allocator while blocks are allocated");
+ }
+ TheMSys.allocator.malloc = malloc_func;
+ TheMSys.allocator.realloc = realloc_func;
+ TheMSys.allocator.free = free_func;
+}
+
+/* This value is used as a marker for "stats are disabled", it's ASCII "AAAA" */
+static size_t _DISABLED_STATS_VALUE = 0x41414141;
+
+extern "C" size_t NRT_MemSys_get_stats_alloc() {
+ if (TheMSys.stats.enabled)
+ {
+ return TheMSys.stats.alloc.load();
+ } else {
+ return _DISABLED_STATS_VALUE;
+ }
+}
+
+extern "C" size_t NRT_MemSys_get_stats_free() {
+ if (TheMSys.stats.enabled)
+ {
+ return TheMSys.stats.free.load();
+ } else {
+ return _DISABLED_STATS_VALUE;
+ }
+}
+
+extern "C" size_t NRT_MemSys_get_stats_mi_alloc() {
+ if (TheMSys.stats.enabled)
+ {
+ return TheMSys.stats.mi_alloc.load();
+ } else {
+ return _DISABLED_STATS_VALUE;
+ }
+}
+
+extern "C" size_t NRT_MemSys_get_stats_mi_free() {
+ if (TheMSys.stats.enabled)
+ {
+ return TheMSys.stats.mi_free.load();
+ } else {
+ return _DISABLED_STATS_VALUE;
+ }
+}
+
+/*
+ * The MemInfo structure.
+ */
+
+extern "C" void NRT_MemInfo_init(NRT_MemInfo *mi,void *data, size_t size,
+ NRT_dtor_function dtor, void *dtor_info,
+ NRT_ExternalAllocator *external_allocator)
+{
+ mi->refct = 1; /* starts with 1 refct */
+ mi->dtor = dtor;
+ mi->dtor_info = dtor_info;
+ mi->data = data;
+ mi->size = size;
+ mi->external_allocator = external_allocator;
+ NRT_Debug(nrt_debug_print("NRT_MemInfo_init mi=%p external_allocator=%p\n", mi, external_allocator));
+ /* Update stats */
+ if (TheMSys.stats.enabled)
+ {
+ TheMSys.stats.mi_alloc++;
+ }
+}
+
+NRT_MemInfo *NRT_MemInfo_new(void *data, size_t size,
+ NRT_dtor_function dtor, void *dtor_info)
+{
+ NRT_MemInfo *mi = (NRT_MemInfo *)NRT_Allocate(sizeof(NRT_MemInfo));
+ if (mi != NULL) {
+ NRT_Debug(nrt_debug_print("NRT_MemInfo_new mi=%p\n", mi));
+ NRT_MemInfo_init(mi, data, size, dtor, dtor_info, NULL);
+ }
+ return mi;
+}
+
+size_t NRT_MemInfo_refcount(NRT_MemInfo *mi) {
+ /* Should never returns 0 for a valid MemInfo */
+ if (mi && mi->data)
+ return mi->refct;
+ else{
+ return (size_t)-1;
+ }
+}
+
+static
+void nrt_internal_dtor_safe(void *ptr, size_t size, void *info) {
+ NRT_Debug(nrt_debug_print("nrt_internal_dtor_safe %p, %p\n", ptr, info));
+ /* See NRT_MemInfo_alloc_safe() */
+ /* Fill region with debug markers */
+ memset(ptr, 0xDE, size);
+}
+
+static
+void *nrt_allocate_meminfo_and_data(size_t size, NRT_MemInfo **mi_out, NRT_ExternalAllocator *allocator) {
+ NRT_MemInfo *mi = NULL;
+ NRT_Debug(nrt_debug_print("nrt_allocate_meminfo_and_data %p\n", allocator));
+ char *base = (char *)NRT_Allocate_External(sizeof(NRT_MemInfo) + size, allocator);
+ if (base == NULL) {
+ *mi_out = NULL; /* set meminfo to NULL as allocation failed */
+ return NULL; /* return early as allocation failed */
+ }
+ mi = (NRT_MemInfo *) base;
+ *mi_out = mi;
+ return (void*)((char *)base + sizeof(NRT_MemInfo));
+}
+
+
+static
+void nrt_internal_custom_dtor_safe(void *ptr, size_t size, void *info) {
+ NRT_dtor_function dtor = (NRT_dtor_function)info;
+ NRT_Debug(nrt_debug_print("nrt_internal_custom_dtor_safe %p, %p\n",
+ ptr, info));
+ if (dtor) {
+ dtor(ptr, size, NULL);
+ }
+
+ nrt_internal_dtor_safe(ptr, size, NULL);
+}
+
+static
+void nrt_internal_custom_dtor(void *ptr, size_t size, void *info) {
+ NRT_dtor_function dtor = (NRT_dtor_function)info;
+ NRT_Debug(nrt_debug_print("nrt_internal_custom_dtor %p, %p\n",
+ ptr, info));
+ if (dtor) {
+ dtor(ptr, size, NULL);
+ }
+}
+
+NRT_MemInfo *NRT_MemInfo_alloc(size_t size) {
+ NRT_MemInfo *mi = NULL;
+ void *data = nrt_allocate_meminfo_and_data(size, &mi, NULL);
+ if (data == NULL) {
+ return NULL; /* return early as allocation failed */
+ }
+ NRT_Debug(nrt_debug_print("NRT_MemInfo_alloc %p\n", data));
+ NRT_MemInfo_init(mi, data, size, NULL, NULL, NULL);
+ return mi;
+}
+
+extern "C" NRT_MemInfo *NRT_MemInfo_alloc_external(size_t size, NRT_ExternalAllocator *allocator) {
+ NRT_MemInfo *mi = NULL;
+ void *data = nrt_allocate_meminfo_and_data(size, &mi, allocator);
+ if (data == NULL) {
+ return NULL; /* return early as allocation failed */
+ }
+ NRT_Debug(nrt_debug_print("NRT_MemInfo_alloc %p\n", data));
+ NRT_MemInfo_init(mi, data, size, NULL, NULL, allocator);
+ return mi;
+}
+
+extern "C" NRT_MemInfo *NRT_MemInfo_alloc_safe(size_t size) {
+ return NRT_MemInfo_alloc_dtor_safe(size, NULL);
+}
+
+extern "C" NRT_MemInfo* NRT_MemInfo_alloc_dtor_safe(size_t size, NRT_dtor_function dtor) {
+ NRT_MemInfo *mi = NULL;
+ void *data = nrt_allocate_meminfo_and_data(size, &mi, NULL);
+ if (data == NULL) {
+ return NULL; /* return early as allocation failed */
+ }
+ /* Fill region with debug markers */
+ memset(data, 0xCB, size);
+ NRT_Debug(nrt_debug_print("NRT_MemInfo_alloc_dtor_safe %p %zu\n", data, size));
+ NRT_MemInfo_init(mi, data, size, nrt_internal_custom_dtor_safe, (void*)dtor, NULL);
+ return mi;
+}
+
+NRT_MemInfo* NRT_MemInfo_alloc_dtor(size_t size, NRT_dtor_function dtor) {
+ NRT_MemInfo *mi = NULL;
+ void *data = (void *)nrt_allocate_meminfo_and_data(size, &mi, NULL);
+ if (data == NULL) {
+ return NULL; /* return early as allocation failed */
+ }
+ NRT_Debug(nrt_debug_print("NRT_MemInfo_alloc_dtor %p %zu\n", data, size));
+ NRT_MemInfo_init(mi, data, size, nrt_internal_custom_dtor, (void *)dtor, NULL);
+ return mi;
+}
+
+static
+void *nrt_allocate_meminfo_and_data_align(size_t size, unsigned align,
+ NRT_MemInfo **mi, NRT_ExternalAllocator *allocator)
+{
+ size_t offset = 0, intptr = 0, remainder = 0;
+ NRT_Debug(nrt_debug_print("nrt_allocate_meminfo_and_data_align %p\n", allocator));
+ char *base = (char *)nrt_allocate_meminfo_and_data(size + 2 * align, mi, allocator);
+ if (base == NULL) {
+ return NULL; /* return early as allocation failed */
+ }
+ intptr = (size_t) base;
+ /*
+ * See if the allocation is aligned already...
+ * Check if align is a power of 2, if so the modulo can be avoided.
+ */
+ if((align & (align - 1)) == 0)
+ {
+ remainder = intptr & (align - 1);
+ }
+ else
+ {
+ remainder = intptr % align;
+ }
+ if (remainder == 0){ /* Yes */
+ offset = 0;
+ } else { /* No, move forward `offset` bytes */
+ offset = align - remainder;
+ }
+ return (void*)((char *)base + offset);
+}
+
+extern "C" NRT_MemInfo *NRT_MemInfo_alloc_aligned(size_t size, unsigned align) {
+ NRT_MemInfo *mi = NULL;
+ void *data = nrt_allocate_meminfo_and_data_align(size, align, &mi, NULL);
+ if (data == NULL) {
+ return NULL; /* return early as allocation failed */
+ }
+ NRT_Debug(nrt_debug_print("NRT_MemInfo_alloc_aligned %p\n", data));
+ NRT_MemInfo_init(mi, data, size, NULL, NULL, NULL);
+ return mi;
+}
+
+extern "C" NRT_MemInfo *NRT_MemInfo_alloc_safe_aligned(size_t size, unsigned align) {
+ NRT_MemInfo *mi = NULL;
+ void *data = nrt_allocate_meminfo_and_data_align(size, align, &mi, NULL);
+ if (data == NULL) {
+ return NULL; /* return early as allocation failed */
+ }
+ /* Fill region with debug markers */
+ memset(data, 0xCB, size);
+ NRT_Debug(nrt_debug_print("NRT_MemInfo_alloc_safe_aligned %p %zu\n",
+ data, size));
+ NRT_MemInfo_init(mi, data, size, nrt_internal_dtor_safe, (void*)size, NULL);
+ return mi;
+}
+
+extern "C" NRT_MemInfo *NRT_MemInfo_alloc_safe_aligned_external(size_t size, unsigned align, NRT_ExternalAllocator *allocator) {
+ NRT_MemInfo *mi = NULL;
+ NRT_Debug(nrt_debug_print("NRT_MemInfo_alloc_safe_aligned_external %p\n", allocator));
+ void *data = nrt_allocate_meminfo_and_data_align(size, align, &mi, allocator);
+ if (data == NULL) {
+ return NULL; /* return early as allocation failed */
+ }
+ /* Fill region with debug markers */
+ memset(data, 0xCB, size);
+ NRT_Debug(nrt_debug_print("NRT_MemInfo_alloc_safe_aligned %p %zu\n",
+ data, size));
+ NRT_MemInfo_init(mi, data, size, nrt_internal_dtor_safe, (void*)size, allocator);
+ return mi;
+}
+
+extern "C" void NRT_dealloc(NRT_MemInfo *mi) {
+ NRT_Debug(nrt_debug_print("NRT_dealloc meminfo: %p external_allocator: %p\n", mi, mi->external_allocator));
+ if (mi->external_allocator) {
+ mi->external_allocator->free(mi, mi->external_allocator->opaque_data);
+ if (TheMSys.stats.enabled)
+ {
+ TheMSys.stats.free++;
+ }
+ } else {
+ NRT_Free(mi);
+ }
+}
+
+extern "C" void NRT_MemInfo_destroy(NRT_MemInfo *mi) {
+ NRT_dealloc(mi);
+ if (TheMSys.stats.enabled)
+ {
+ TheMSys.stats.mi_free++;
+ }
+}
+
+extern "C" void NRT_MemInfo_acquire(NRT_MemInfo *mi) {
+ NRT_Debug(nrt_debug_print("NRT_MemInfo_acquire %p refct=%zu\n", mi,
+ mi->refct.load()));
+ assert(mi->refct > 0 && "RefCt cannot be zero");
+ mi->refct++;
+}
+
+extern "C" void NRT_MemInfo_call_dtor(NRT_MemInfo *mi) {
+ NRT_Debug(nrt_debug_print("NRT_MemInfo_call_dtor %p\n", mi));
+ if (mi->dtor && !TheMSys.shutting)
+ /* We have a destructor and the system is not shutting down */
+ mi->dtor(mi->data, mi->size, mi->dtor_info);
+ /* Clear and release MemInfo */
+ NRT_MemInfo_destroy(mi);
+}
+
+extern "C" void NRT_MemInfo_release(NRT_MemInfo *mi) {
+ NRT_Debug(nrt_debug_print("NRT_MemInfo_release %p refct=%zu\n", mi,
+ mi->refct.load()));
+ assert (mi->refct > 0 && "RefCt cannot be 0");
+ /* RefCt drop to zero */
+ if ((--(mi->refct)) == 0) {
+ NRT_MemInfo_call_dtor(mi);
+ }
+}
+
+extern "C" void* NRT_MemInfo_data(NRT_MemInfo* mi) {
+ return mi->data;
+}
+
+size_t NRT_MemInfo_size(NRT_MemInfo* mi) {
+ return mi->size;
+}
+
+extern "C" void * NRT_MemInfo_external_allocator(NRT_MemInfo *mi) {
+ NRT_Debug(nrt_debug_print("NRT_MemInfo_external_allocator meminfo: %p external_allocator: %p\n", mi, mi->external_allocator));
+ return mi->external_allocator;
+}
+
+extern "C" void *NRT_MemInfo_parent(NRT_MemInfo *mi) {
+ return mi->dtor_info;
+}
+
+extern "C" void NRT_MemInfo_dump(NRT_MemInfo *mi, FILE *out) {
+ fprintf(out, "MemInfo %p refcount %zu\n", mi, mi->refct.load());
+}
+
+/*
+ * Resizable buffer API.
+ */
+
+static void
+nrt_varsize_dtor(void *ptr, size_t size, void *info) {
+ NRT_Debug(nrt_debug_print("nrt_varsize_dtor %p\n", ptr));
+ if (info) {
+ /* call element dtor */
+ typedef void dtor_fn_t(void *ptr);
+ dtor_fn_t *dtor = (dtor_fn_t *)info;
+ dtor(ptr);
+ }
+ NRT_Free(ptr);
+}
+
+NRT_MemInfo *NRT_MemInfo_new_varsize(size_t size)
+{
+ NRT_MemInfo *mi = NULL;
+ void *data = NRT_Allocate(size);
+ if (data == NULL) {
+ return NULL; /* return early as allocation failed */
+ }
+
+ mi = NRT_MemInfo_new(data, size, nrt_varsize_dtor, NULL);
+ NRT_Debug(nrt_debug_print("NRT_MemInfo_new_varsize size=%zu "
+ "-> meminfo=%p, data=%p\n", size, mi, data));
+ return mi;
+}
+
+NRT_MemInfo *NRT_MemInfo_new_varsize_dtor(size_t size, NRT_dtor_function dtor) {
+ NRT_MemInfo *mi = NRT_MemInfo_new_varsize(size);
+ if (mi) {
+ mi->dtor_info = (void*)dtor;
+ }
+ return mi;
+}
+
+extern "C" void *NRT_MemInfo_varsize_alloc(NRT_MemInfo *mi, size_t size)
+{
+ if (mi->dtor != nrt_varsize_dtor) {
+ nrt_fatal_error("ERROR: NRT_MemInfo_varsize_alloc called "
+ "with a non varsize-allocated meminfo");
+ return NULL; /* unreachable */
+ }
+ mi->data = NRT_Allocate(size);
+ if (mi->data == NULL)
+ return NULL;
+ mi->size = size;
+ NRT_Debug(nrt_debug_print("NRT_MemInfo_varsize_alloc %p size=%zu "
+ "-> data=%p\n", mi, size, mi->data));
+ return mi->data;
+}
+
+extern "C" void *NRT_MemInfo_varsize_realloc(NRT_MemInfo *mi, size_t size)
+{
+ if (mi->dtor != nrt_varsize_dtor) {
+ nrt_fatal_error("ERROR: NRT_MemInfo_varsize_realloc called "
+ "with a non varsize-allocated meminfo");
+ return NULL; /* unreachable */
+ }
+ mi->data = NRT_Reallocate(mi->data, size);
+ if (mi->data == NULL)
+ return NULL;
+ mi->size = size;
+ NRT_Debug(nrt_debug_print("NRT_MemInfo_varsize_realloc %p size=%zu "
+ "-> data=%p\n", mi, size, mi->data));
+ return mi->data;
+}
+
+extern "C" void NRT_MemInfo_varsize_free(NRT_MemInfo *mi, void *ptr)
+{
+ NRT_Free(ptr);
+ if (ptr == mi->data)
+ mi->data = NULL;
+}
+
+/*
+ * Low-level allocation wrappers.
+ */
+
+extern "C" void* NRT_Allocate(size_t size) {
+ return NRT_Allocate_External(size, NULL);
+}
+
+extern "C" void* NRT_Allocate_External(size_t size, NRT_ExternalAllocator *allocator) {
+ void *ptr = NULL;
+ if (allocator) {
+ ptr = allocator->malloc(size, allocator->opaque_data);
+ NRT_Debug(nrt_debug_print("NRT_Allocate_External custom bytes=%zu ptr=%p\n", size, ptr));
+ } else {
+ ptr = TheMSys.allocator.malloc(size);
+ NRT_Debug(nrt_debug_print("NRT_Allocate_External bytes=%zu ptr=%p\n", size, ptr));
+ }
+ if (TheMSys.stats.enabled)
+ {
+ TheMSys.stats.alloc++;
+ }
+ return ptr;
+}
+
+extern "C" void *NRT_Reallocate(void *ptr, size_t size) {
+ void *new_ptr = TheMSys.allocator.realloc(ptr, size);
+ NRT_Debug(nrt_debug_print("NRT_Reallocate bytes=%zu ptr=%p -> %p\n",
+ size, ptr, new_ptr));
+ return new_ptr;
+}
+
+extern "C" void NRT_Free(void *ptr) {
+ NRT_Debug(nrt_debug_print("NRT_Free %p\n", ptr));
+ TheMSys.allocator.free(ptr);
+ if (TheMSys.stats.enabled)
+ {
+ TheMSys.stats.free++;
+ }
+}
+
+/*
+ * Sample external allocator implementation for internal testing.
+ */
+
+static int sample_external_opaque_data = 0xabacad;
+
+static
+void* sample_external_malloc(size_t size, void* opaque_data) {
+ if (opaque_data != &sample_external_opaque_data) return NULL;
+ return TheMSys.allocator.malloc(size);
+}
+
+static
+void* sample_external_realloc(void *ptr, size_t new_size, void *opaque_data) {
+ if (opaque_data != &sample_external_opaque_data) return NULL;
+ return TheMSys.allocator.realloc(ptr, new_size);
+}
+
+static
+void sample_external_free(void *ptr, void* opaque_data) {
+ TheMSys.allocator.free(ptr);
+}
+
+static NRT_ExternalAllocator sample_external_allocator = {
+ // malloc
+ sample_external_malloc,
+ // realloc
+ sample_external_realloc,
+ // free
+ sample_external_free,
+ // opaque_data
+ &sample_external_opaque_data
+};
+
+extern "C" NRT_ExternalAllocator* _nrt_get_sample_external_allocator() {
+ return &sample_external_allocator;
+}
+
+/*
+ * Debugging printf function used internally
+ */
+void nrt_debug_print(const char *fmt, ...) {
+ va_list args;
+
+ va_start(args, fmt);
+ vfprintf(stderr, fmt, args);
+ va_end(args);
+}
+
+
+static
+void nrt_manage_memory_dtor(void *data, size_t size, void *info) {
+ NRT_managed_dtor* dtor = (NRT_managed_dtor*)info;
+ dtor(data);
+}
+
+static
+NRT_MemInfo* nrt_manage_memory(void *data, NRT_managed_dtor dtor) {
+ return (NRT_MemInfo*)(NRT_MemInfo_new(data, 0, nrt_manage_memory_dtor, (void*)dtor));
+}
+
+
+static const
+NRT_api_functions nrt_functions_table = {
+ NRT_MemInfo_alloc,
+ NRT_MemInfo_alloc_external,
+ nrt_manage_memory,
+ NRT_MemInfo_acquire,
+ NRT_MemInfo_release,
+ NRT_MemInfo_data
+};
+
+
+extern "C" const NRT_api_functions* NRT_get_api(void) {
+ return &nrt_functions_table;
+}
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/runtime/nrt.h b/tool_server/.venv/lib/python3.12/site-packages/numba/core/runtime/nrt.h
new file mode 100644
index 0000000000000000000000000000000000000000..b8fe1f22aa16b622213ca03cdc9523299e6c9a90
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/core/runtime/nrt.h
@@ -0,0 +1,273 @@
+/*
+All functions described here are threadsafe.
+*/
+
+#ifndef NUMBA_NRT_H_
+#define NUMBA_NRT_H_
+
+
+#include
+#include
+#include "../../_numba_common.h"
+
+#include "nrt_external.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+/* Debugging facilities - enabled at compile-time */
+/* #undef NDEBUG */
+#if 0
+# define NRT_Debug(X) {X; fflush(stdout); }
+#else
+# define NRT_Debug(X) if (0) { X; }
+#endif
+
+/* TypeDefs */
+typedef void (*NRT_dtor_function)(void *ptr, size_t size, void *info);
+typedef void (*NRT_dealloc_func)(void *ptr, void *dealloc_info);
+
+typedef void *(*NRT_malloc_func)(size_t size);
+typedef void *(*NRT_realloc_func)(void *ptr, size_t new_size);
+typedef void (*NRT_free_func)(void *ptr);
+
+/* Memory System API */
+
+/* Initialize the memory system */
+VISIBILITY_HIDDEN
+void NRT_MemSys_init(void);
+
+/* Shutdown the memory system */
+VISIBILITY_HIDDEN
+void NRT_MemSys_shutdown(void);
+
+/*
+ * Register the system allocation functions
+ */
+VISIBILITY_HIDDEN
+void NRT_MemSys_set_allocator(NRT_malloc_func, NRT_realloc_func, NRT_free_func);
+
+/*
+ * Enable the internal statistics counters.
+ */
+VISIBILITY_HIDDEN
+void NRT_MemSys_enable_stats(void);
+
+/*
+ * Disable the internal statistics counters.
+ */
+VISIBILITY_HIDDEN
+void NRT_MemSys_disable_stats(void);
+
+/*
+ * Query whether the internal statistics counters are enabled.
+ * Returns 1 if they are, 0 if they are not.
+ */
+VISIBILITY_HIDDEN
+size_t NRT_MemSys_stats_enabled(void);
+
+/*
+ * The following functions get internal statistics of the memory subsystem.
+ */
+VISIBILITY_HIDDEN
+size_t NRT_MemSys_get_stats_alloc(void);
+VISIBILITY_HIDDEN
+size_t NRT_MemSys_get_stats_free(void);
+VISIBILITY_HIDDEN
+size_t NRT_MemSys_get_stats_mi_alloc(void);
+VISIBILITY_HIDDEN
+size_t NRT_MemSys_get_stats_mi_free(void);
+
+/* Memory Info API */
+
+/* Create a new MemInfo for external memory
+ *
+ * data: data pointer being tracked
+ * dtor: destructor to execute
+ * dtor_info: additional information to pass to the destructor
+ */
+VISIBILITY_HIDDEN
+NRT_MemInfo* NRT_MemInfo_new(void *data, size_t size,
+ NRT_dtor_function dtor, void *dtor_info);
+
+/*
+ * The `external_allocator` is for experimental API to customize the allocator.
+ * Set to NULL to use the default builtin allocator.
+ */
+VISIBILITY_HIDDEN
+void NRT_MemInfo_init(NRT_MemInfo *mi, void *data, size_t size,
+ NRT_dtor_function dtor, void *dtor_info,
+ NRT_ExternalAllocator *external_allocator);
+
+/*
+ * Returns the refcount of a MemInfo or (size_t)-1 if error.
+ */
+VISIBILITY_HIDDEN
+size_t NRT_MemInfo_refcount(NRT_MemInfo *mi);
+
+/*
+ * Allocate memory of `size` bytes and return a pointer to a MemInfo structure
+ * that describes the allocation
+ */
+VISIBILITY_HIDDEN
+NRT_MemInfo *NRT_MemInfo_alloc(size_t size);
+
+NRT_MemInfo *NRT_MemInfo_alloc_external(size_t size, NRT_ExternalAllocator *allocator);
+
+/*
+ * The "safe" NRT_MemInfo_alloc performs additional steps to help debug
+ * memory errors.
+ * It is guaranteed to:
+ * - zero-fill to the memory region after allocation and before deallocation.
+ * - may do more in the future
+ */
+VISIBILITY_HIDDEN
+NRT_MemInfo *NRT_MemInfo_alloc_safe(size_t size);
+
+/*
+ * Similar to NRT_MemInfo_alloc_safe but with a custom dtor.
+ */
+VISIBILITY_HIDDEN
+NRT_MemInfo* NRT_MemInfo_alloc_dtor_safe(size_t size, NRT_dtor_function dtor);
+
+/*
+ * Similar to NRT_MemInfo_alloc but with a custom dtor.
+ */
+VISIBILITY_HIDDEN
+NRT_MemInfo* NRT_MemInfo_alloc_dtor(size_t size, NRT_dtor_function dtor);
+
+/*
+ * Aligned versions of the NRT_MemInfo_alloc and NRT_MemInfo_alloc_safe.
+ * These take an additional argument `align` for number of bytes to align to.
+ */
+VISIBILITY_HIDDEN
+NRT_MemInfo *NRT_MemInfo_alloc_aligned(size_t size, unsigned align);
+VISIBILITY_HIDDEN
+NRT_MemInfo *NRT_MemInfo_alloc_safe_aligned(size_t size, unsigned align);
+
+/*
+ * Experimental.
+ * A variation to use an external allocator.
+ */
+NRT_MemInfo *NRT_MemInfo_alloc_safe_aligned_external(size_t size, unsigned align, NRT_ExternalAllocator *allocator);
+
+/*
+ * Internal API.
+ * Release a MemInfo. Calls NRT_MemSys_insert_meminfo.
+ */
+VISIBILITY_HIDDEN
+void NRT_MemInfo_destroy(NRT_MemInfo *mi);
+
+/*
+ * Acquire a reference to a MemInfo
+ */
+VISIBILITY_HIDDEN
+void NRT_MemInfo_acquire(NRT_MemInfo* mi);
+
+/*
+ * Release a reference to a MemInfo
+ */
+VISIBILITY_HIDDEN
+void NRT_MemInfo_release(NRT_MemInfo* mi);
+
+/*
+ * Internal/Compiler API.
+ * Invoke the registered destructor of a MemInfo.
+ */
+VISIBILITY_HIDDEN
+void NRT_MemInfo_call_dtor(NRT_MemInfo *mi);
+
+/*
+ * Returns the data pointer
+ */
+VISIBILITY_HIDDEN
+void* NRT_MemInfo_data(NRT_MemInfo* mi);
+
+/*
+ * Returns the allocated size
+ */
+VISIBILITY_HIDDEN
+size_t NRT_MemInfo_size(NRT_MemInfo* mi);
+
+
+/*
+ * Experimental.
+ * Returns the external allocator
+ */
+VISIBILITY_HIDDEN
+void* NRT_MemInfo_external_allocator(NRT_MemInfo* mi);
+
+/*
+ * Returns the parent MemInfo
+ */
+VISIBILITY_HIDDEN
+void* NRT_MemInfo_parent(NRT_MemInfo* mi);
+
+
+/*
+ * NRT API for resizable buffers.
+ */
+VISIBILITY_HIDDEN
+NRT_MemInfo *NRT_MemInfo_new_varsize(size_t size);
+VISIBILITY_HIDDEN
+NRT_MemInfo *NRT_MemInfo_new_varsize_dtor(size_t size, NRT_dtor_function dtor);
+VISIBILITY_HIDDEN
+void *NRT_MemInfo_varsize_alloc(NRT_MemInfo *mi, size_t size);
+VISIBILITY_HIDDEN
+void *NRT_MemInfo_varsize_realloc(NRT_MemInfo *mi, size_t size);
+VISIBILITY_HIDDEN
+void NRT_MemInfo_varsize_free(NRT_MemInfo *mi, void *ptr);
+
+/*
+ * Print debug info to FILE
+ */
+VISIBILITY_HIDDEN
+void NRT_MemInfo_dump(NRT_MemInfo *mi, FILE *out);
+
+
+/* Low-level allocation wrappers. */
+
+/*
+ * Allocate memory of `size` bytes.
+ */
+VISIBILITY_HIDDEN void* NRT_Allocate(size_t size);
+
+/*
+ * Experimental
+ *
+ * An alternative allocator that allows using an external allocator.
+ */
+VISIBILITY_HIDDEN void* NRT_Allocate_External(size_t size, NRT_ExternalAllocator *allocator);
+
+/*
+ * Deallocate memory pointed by `ptr`.
+ */
+VISIBILITY_HIDDEN void NRT_Free(void *ptr);
+
+/*
+ * Reallocate memory at `ptr`.
+ */
+VISIBILITY_HIDDEN void *NRT_Reallocate(void *ptr, size_t size);
+
+/*
+ * Debugging printf function used internally
+ */
+VISIBILITY_HIDDEN void nrt_debug_print(const char *fmt, ...);
+
+/*
+ * Get API function table.
+ */
+VISIBILITY_HIDDEN const NRT_api_functions* NRT_get_api(void);
+
+
+/*
+ * FOR INTERNAL USE ONLY.
+ * Get a sample external allocator for testing
+ */
+VISIBILITY_HIDDEN NRT_ExternalAllocator* _nrt_get_sample_external_allocator(void);
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* NUMBA_NRT_H_ */
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/runtime/nrt.py b/tool_server/.venv/lib/python3.12/site-packages/numba/core/runtime/nrt.py
new file mode 100644
index 0000000000000000000000000000000000000000..f8551002a5f6af232ffa2bf40e62235d9e314676
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/core/runtime/nrt.py
@@ -0,0 +1,131 @@
+from collections import namedtuple
+from weakref import finalize as _finalize
+
+from numba.core.runtime import nrtdynmod
+from llvmlite import binding as ll
+
+from numba.core.compiler_lock import global_compiler_lock
+from numba.core.typing.typeof import typeof_impl
+from numba.core import types, config
+from numba.core.runtime import _nrt_python as _nrt
+
+_nrt_mstats = namedtuple("nrt_mstats", ["alloc", "free", "mi_alloc", "mi_free"])
+
+
+class _Runtime(object):
+ def __init__(self):
+ self._init = False
+
+ @global_compiler_lock
+ def initialize(self, ctx):
+ """Initializes the NRT
+
+ Must be called before any actual call to the NRT API.
+ Safe to be called multiple times.
+ """
+ if self._init:
+ # Already initialized
+ return
+
+ # Switch stats on if the config requests them.
+ if config.NRT_STATS:
+ _nrt.memsys_enable_stats()
+
+ # Register globals into the system
+ for py_name in _nrt.c_helpers:
+ if py_name.startswith("_"):
+ # internal API
+ c_name = py_name
+ else:
+ c_name = "NRT_" + py_name
+ c_address = _nrt.c_helpers[py_name]
+ ll.add_symbol(c_name, c_address)
+
+ # Compile atomic operations
+ self._library = nrtdynmod.compile_nrt_functions(ctx)
+ self._init = True
+
+ def _init_guard(self):
+ if not self._init:
+ msg = "Runtime must be initialized before use."
+ raise RuntimeError(msg)
+
+ @staticmethod
+ def shutdown():
+ """
+ Shutdown the NRT
+ Safe to be called without calling Runtime.initialize first
+ """
+ _nrt.memsys_shutdown()
+
+ @property
+ def library(self):
+ """
+ Return the Library object containing the various NRT functions.
+ """
+ self._init_guard()
+ return self._library
+
+ def meminfo_new(self, data, pyobj):
+ """
+ Returns a MemInfo object that tracks memory at `data` owned by `pyobj`.
+ MemInfo will acquire a reference on `pyobj`.
+ The release of MemInfo will release a reference on `pyobj`.
+ """
+ self._init_guard()
+ mi = _nrt.meminfo_new(data, pyobj)
+ return MemInfo(mi)
+
+ def meminfo_alloc(self, size, safe=False):
+ """
+ Allocate a new memory of `size` bytes and returns a MemInfo object
+ that tracks the allocation. When there is no more reference to the
+ MemInfo object, the underlying memory will be deallocated.
+
+ If `safe` flag is True, the memory is allocated using the `safe` scheme.
+ This is used for debugging and testing purposes.
+ See `NRT_MemInfo_alloc_safe()` in "nrt.h" for details.
+ """
+ self._init_guard()
+ if size < 0:
+ msg = f"Cannot allocate a negative number of bytes: {size}."
+ raise ValueError(msg)
+ if safe:
+ mi = _nrt.meminfo_alloc_safe(size)
+ else:
+ mi = _nrt.meminfo_alloc(size)
+ if mi == 0: # alloc failed or size was 0 and alloc returned NULL.
+ msg = f"Requested allocation of {size} bytes failed."
+ raise MemoryError(msg)
+ return MemInfo(mi)
+
+ def get_allocation_stats(self):
+ """
+ Returns a namedtuple of (alloc, free, mi_alloc, mi_free) for count of
+ each memory operations.
+ """
+ # No init guard needed to access stats members
+ return _nrt_mstats(alloc=_nrt.memsys_get_stats_alloc(),
+ free=_nrt.memsys_get_stats_free(),
+ mi_alloc=_nrt.memsys_get_stats_mi_alloc(),
+ mi_free=_nrt.memsys_get_stats_mi_free())
+
+
+# Alias to _nrt_python._MemInfo
+MemInfo = _nrt._MemInfo
+
+
+@typeof_impl.register(MemInfo)
+def typeof_meminfo(val, c):
+ return types.MemInfoPointer(types.voidptr)
+
+
+# Create runtime
+_nrt.memsys_use_cpython_allocator()
+rtsys = _Runtime()
+
+# Install finalizer
+_finalize(rtsys, _Runtime.shutdown)
+
+# Avoid future use of the class
+del _Runtime
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/runtime/nrt_external.h b/tool_server/.venv/lib/python3.12/site-packages/numba/core/runtime/nrt_external.h
new file mode 100644
index 0000000000000000000000000000000000000000..8689550157b66bb8280db0056ece315d014b6209
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/core/runtime/nrt_external.h
@@ -0,0 +1,65 @@
+#ifndef NUMBA_NRT_EXTERNAL_H_
+#define NUMBA_NRT_EXTERNAL_H_
+
+#include
+
+typedef struct MemInfo NRT_MemInfo;
+
+typedef void NRT_managed_dtor(void *data);
+
+typedef void *(*NRT_external_malloc_func)(size_t size, void *opaque_data);
+typedef void *(*NRT_external_realloc_func)(void *ptr, size_t new_size, void *opaque_data);
+typedef void (*NRT_external_free_func)(void *ptr, void *opaque_data);
+
+struct ExternalMemAllocator {
+ NRT_external_malloc_func malloc;
+ NRT_external_realloc_func realloc;
+ NRT_external_free_func free;
+ void *opaque_data;
+};
+
+typedef struct ExternalMemAllocator NRT_ExternalAllocator;
+
+typedef struct {
+ /* Methods to create MemInfos.
+
+ MemInfos are like smart pointers for objects that are managed by the Numba.
+ */
+
+ /* Allocate memory
+
+ *nbytes* is the number of bytes to be allocated
+
+ Returning a new reference.
+ */
+ NRT_MemInfo* (*allocate)(size_t nbytes);
+ /* Allocates memory using an external allocator but still using Numba's MemInfo.
+ *
+ * NOTE: An externally provided allocator must behave the same way as C99
+ * stdlib.h's "malloc" function with respect to return value
+ * (including the behaviour that occurs when requesting an allocation
+ * of size 0 bytes).
+ */
+ NRT_MemInfo* (*allocate_external)(size_t nbytes, NRT_ExternalAllocator *allocator);
+
+ /* Convert externally allocated memory into a MemInfo.
+
+ *data* is the memory pointer
+ *dtor* is the deallocator of the memory
+ */
+ NRT_MemInfo* (*manage_memory)(void *data, NRT_managed_dtor dtor);
+
+ /* Acquire a reference */
+ void (*acquire)(NRT_MemInfo* mi);
+
+ /* Release a reference */
+ void (*release)(NRT_MemInfo* mi);
+
+ /* Get MemInfo data pointer */
+ void* (*get_data)(NRT_MemInfo* mi);
+
+} NRT_api_functions;
+
+
+
+#endif /* NUMBA_NRT_EXTERNAL_H_ */
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/runtime/nrtdynmod.py b/tool_server/.venv/lib/python3.12/site-packages/numba/core/runtime/nrtdynmod.py
new file mode 100644
index 0000000000000000000000000000000000000000..c8cc1973d3f791ab398dec1b1d474d0fd4e13cf9
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/core/runtime/nrtdynmod.py
@@ -0,0 +1,215 @@
+"""
+Dynamically generate the NRT module
+"""
+
+
+from numba.core import config
+from numba.core import types, cgutils
+from llvmlite import ir, binding
+
+
+_word_type = ir.IntType(config.MACHINE_BITS)
+_pointer_type = ir.PointerType(ir.IntType(8))
+
+_meminfo_struct_type = ir.LiteralStructType([
+ _word_type, # size_t refct
+ _pointer_type, # dtor_function dtor
+ _pointer_type, # void *dtor_info
+ _pointer_type, # void *data
+ _word_type, # size_t size
+ ])
+
+
+incref_decref_ty = ir.FunctionType(ir.VoidType(), [_pointer_type])
+meminfo_data_ty = ir.FunctionType(_pointer_type, [_pointer_type])
+
+
+def _define_nrt_meminfo_data(module):
+ """
+ Implement NRT_MemInfo_data_fast in the module. This allows LLVM
+ to inline lookup of the data pointer.
+ """
+ fn = cgutils.get_or_insert_function(module, meminfo_data_ty,
+ "NRT_MemInfo_data_fast")
+ builder = ir.IRBuilder(fn.append_basic_block())
+ [ptr] = fn.args
+ struct_ptr = builder.bitcast(ptr, _meminfo_struct_type.as_pointer())
+ data_ptr = builder.load(cgutils.gep(builder, struct_ptr, 0, 3))
+ builder.ret(data_ptr)
+
+
+def _define_nrt_incref(module, atomic_incr):
+ """
+ Implement NRT_incref in the module
+ """
+ fn_incref = cgutils.get_or_insert_function(module, incref_decref_ty,
+ "NRT_incref")
+ # Cannot inline this for refcount pruning to work
+ fn_incref.attributes.add('noinline')
+ builder = ir.IRBuilder(fn_incref.append_basic_block())
+ [ptr] = fn_incref.args
+ is_null = builder.icmp_unsigned("==", ptr, cgutils.get_null_value(ptr.type))
+ with cgutils.if_unlikely(builder, is_null):
+ builder.ret_void()
+
+ word_ptr = builder.bitcast(ptr, atomic_incr.args[0].type)
+ if config.DEBUG_NRT:
+ cgutils.printf(builder, "*** NRT_Incref %zu [%p]\n", builder.load(word_ptr),
+ ptr)
+ builder.call(atomic_incr, [word_ptr])
+ builder.ret_void()
+
+
+def _define_nrt_decref(module, atomic_decr):
+ """
+ Implement NRT_decref in the module
+ """
+ fn_decref = cgutils.get_or_insert_function(module, incref_decref_ty,
+ "NRT_decref")
+ # Cannot inline this for refcount pruning to work
+ fn_decref.attributes.add('noinline')
+ calldtor = ir.Function(module,
+ ir.FunctionType(ir.VoidType(), [_pointer_type]),
+ name="NRT_MemInfo_call_dtor")
+
+ builder = ir.IRBuilder(fn_decref.append_basic_block())
+ [ptr] = fn_decref.args
+ is_null = builder.icmp_unsigned("==", ptr, cgutils.get_null_value(ptr.type))
+ with cgutils.if_unlikely(builder, is_null):
+ builder.ret_void()
+
+
+ # For memory fence usage, see https://llvm.org/docs/Atomics.html
+
+ # A release fence is used before the relevant write operation.
+ # No-op on x86. On POWER, it lowers to lwsync.
+ builder.fence("release")
+
+ word_ptr = builder.bitcast(ptr, atomic_decr.args[0].type)
+
+ if config.DEBUG_NRT:
+ cgutils.printf(builder, "*** NRT_Decref %zu [%p]\n", builder.load(word_ptr),
+ ptr)
+ newrefct = builder.call(atomic_decr,
+ [word_ptr])
+
+ refct_eq_0 = builder.icmp_unsigned("==", newrefct,
+ ir.Constant(newrefct.type, 0))
+ with cgutils.if_unlikely(builder, refct_eq_0):
+ # An acquire fence is used after the relevant read operation.
+ # No-op on x86. On POWER, it lowers to lwsync.
+ builder.fence("acquire")
+ builder.call(calldtor, [ptr])
+ builder.ret_void()
+
+
+# Set this to True to measure the overhead of atomic refcounts compared
+# to non-atomic.
+_disable_atomicity = 0
+
+
+def _define_atomic_inc_dec(module, op, ordering):
+ """Define a llvm function for atomic increment/decrement to the given module
+ Argument ``op`` is the operation "add"/"sub". Argument ``ordering`` is
+ the memory ordering. The generated function returns the new value.
+ """
+ ftype = ir.FunctionType(_word_type, [_word_type.as_pointer()])
+ fn_atomic = ir.Function(module, ftype, name="nrt_atomic_{0}".format(op))
+
+ [ptr] = fn_atomic.args
+ bb = fn_atomic.append_basic_block()
+ builder = ir.IRBuilder(bb)
+ ONE = ir.Constant(_word_type, 1)
+ if not _disable_atomicity:
+ oldval = builder.atomic_rmw(op, ptr, ONE, ordering=ordering)
+ # Perform the operation on the old value so that we can pretend returning
+ # the "new" value.
+ res = getattr(builder, op)(oldval, ONE)
+ builder.ret(res)
+ else:
+ oldval = builder.load(ptr)
+ newval = getattr(builder, op)(oldval, ONE)
+ builder.store(newval, ptr)
+ builder.ret(oldval)
+
+ return fn_atomic
+
+
+def _define_atomic_cas(module, ordering):
+ """Define a llvm function for atomic compare-and-swap.
+ The generated function is a direct wrapper of the LLVM cmpxchg with the
+ difference that the a int indicate success (1) or failure (0) is returned
+ and the last argument is a output pointer for storing the old value.
+
+ Note
+ ----
+ On failure, the generated function behaves like an atomic load. The loaded
+ value is stored to the last argument.
+ """
+ ftype = ir.FunctionType(ir.IntType(32), [_word_type.as_pointer(),
+ _word_type, _word_type,
+ _word_type.as_pointer()])
+ fn_cas = ir.Function(module, ftype, name="nrt_atomic_cas")
+
+ [ptr, cmp, repl, oldptr] = fn_cas.args
+ bb = fn_cas.append_basic_block()
+ builder = ir.IRBuilder(bb)
+ outtup = builder.cmpxchg(ptr, cmp, repl, ordering=ordering)
+ old, ok = cgutils.unpack_tuple(builder, outtup, 2)
+ builder.store(old, oldptr)
+ builder.ret(builder.zext(ok, ftype.return_type))
+
+ return fn_cas
+
+
+def _define_nrt_unresolved_abort(ctx, module):
+ """
+ Defines an abort function due to unresolved symbol.
+
+ The function takes no args and will always raise an exception.
+ It should be safe to call this function with incorrect number of arguments.
+ """
+ fnty = ctx.call_conv.get_function_type(types.none, ())
+ fn = ir.Function(module, fnty, name="nrt_unresolved_abort")
+ bb = fn.append_basic_block()
+ builder = ir.IRBuilder(bb)
+ msg = "numba jitted function aborted due to unresolved symbol"
+ ctx.call_conv.return_user_exc(builder, RuntimeError, (msg,))
+ return fn
+
+
+def create_nrt_module(ctx):
+ """
+ Create an IR module defining the LLVM NRT functions.
+ A (IR module, library) tuple is returned.
+ """
+ codegen = ctx.codegen()
+ library = codegen.create_library("nrt")
+
+ # Implement LLVM module with atomic ops
+ ir_mod = library.create_ir_module("nrt_module")
+
+ atomic_inc = _define_atomic_inc_dec(ir_mod, "add", ordering='monotonic')
+ atomic_dec = _define_atomic_inc_dec(ir_mod, "sub", ordering='monotonic')
+ _define_atomic_cas(ir_mod, ordering='monotonic')
+
+ _define_nrt_meminfo_data(ir_mod)
+ _define_nrt_incref(ir_mod, atomic_inc)
+ _define_nrt_decref(ir_mod, atomic_dec)
+
+ _define_nrt_unresolved_abort(ctx, ir_mod)
+
+ return ir_mod, library
+
+
+def compile_nrt_functions(ctx):
+ """
+ Compile all LLVM NRT functions and return a library containing them.
+ The library is created using the given target context.
+ """
+ ir_mod, library = create_nrt_module(ctx)
+
+ library.add_ir_module(ir_mod)
+ library.finalize()
+
+ return library
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/runtime/nrtopt.py b/tool_server/.venv/lib/python3.12/site-packages/numba/core/runtime/nrtopt.py
new file mode 100644
index 0000000000000000000000000000000000000000..2a6f56b09108d06ed4522ff259a9ee49c279fcfd
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/core/runtime/nrtopt.py
@@ -0,0 +1,182 @@
+"""
+NRT specific optimizations
+"""
+import re
+from collections import defaultdict, deque
+from llvmlite import binding as ll
+from numba.core import cgutils
+
+_regex_incref = re.compile(r'\s*(?:tail)?\s*call void @NRT_incref\((.*)\)')
+_regex_decref = re.compile(r'\s*(?:tail)?\s*call void @NRT_decref\((.*)\)')
+_regex_bb = re.compile(
+ r'|'.join([
+ # unnamed BB is just a plain number
+ r'[0-9]+:',
+ # with a proper identifier (see llvm langref)
+ r'[\'"]?[-a-zA-Z$._0-9][-a-zA-Z$._0-9]*[\'"]?:',
+ # is a start of a function definition
+ r'^define',
+ # no name
+ r'^;\s*',
+ ])
+)
+
+
+def _remove_redundant_nrt_refct(llvmir):
+ # Note: As soon as we have better utility in analyzing materialized LLVM
+ # module in llvmlite, we can redo this without so much string
+ # processing.
+ def _extract_functions(module):
+ cur = []
+ for line in str(module).splitlines():
+ if line.startswith('define'):
+ # start of function
+ assert not cur
+ cur.append(line)
+ elif line.startswith('}'):
+ # end of function
+ assert cur
+ cur.append(line)
+ yield True, cur
+ cur = []
+ elif cur:
+ cur.append(line)
+ else:
+ yield False, [line]
+
+ def _process_function(func_lines):
+ out = []
+ for is_bb, bb_lines in _extract_basic_blocks(func_lines):
+ if is_bb and bb_lines:
+ bb_lines = _process_basic_block(bb_lines)
+ out += bb_lines
+ return out
+
+ def _extract_basic_blocks(func_lines):
+ assert func_lines[0].startswith('define')
+ assert func_lines[-1].startswith('}')
+ yield False, [func_lines[0]]
+
+ cur = []
+ for ln in func_lines[1:-1]:
+ m = _regex_bb.match(ln)
+ if m is not None:
+ # line is a basic block separator
+ yield True, cur
+ cur = []
+ yield False, [ln]
+ elif ln:
+ cur.append(ln)
+
+ yield True, cur
+ yield False, [func_lines[-1]]
+
+ def _process_basic_block(bb_lines):
+ bb_lines = _move_and_group_decref_after_all_increfs(bb_lines)
+ bb_lines = _prune_redundant_refct_ops(bb_lines)
+ return bb_lines
+
+ def _examine_refct_op(bb_lines):
+ for num, ln in enumerate(bb_lines):
+ m = _regex_incref.match(ln)
+ if m is not None:
+ yield num, m.group(1), None
+ continue
+
+ m = _regex_decref.match(ln)
+ if m is not None:
+ yield num, None, m.group(1)
+ continue
+
+ yield ln, None, None
+
+ def _prune_redundant_refct_ops(bb_lines):
+ incref_map = defaultdict(deque)
+ decref_map = defaultdict(deque)
+ to_remove = set()
+ for num, incref_var, decref_var in _examine_refct_op(bb_lines):
+ assert not (incref_var and decref_var)
+ if incref_var:
+ if incref_var == 'i8* null':
+ to_remove.add(num)
+ else:
+ incref_map[incref_var].append(num)
+ elif decref_var:
+ if decref_var == 'i8* null':
+ to_remove.add(num)
+ else:
+ decref_map[decref_var].append(num)
+
+ for var, decops in decref_map.items():
+ incops = incref_map[var]
+ ct = min(len(incops), len(decops))
+ for _ in range(ct):
+ to_remove.add(incops.pop())
+ to_remove.add(decops.popleft())
+
+ return [ln for num, ln in enumerate(bb_lines)
+ if num not in to_remove]
+
+ def _move_and_group_decref_after_all_increfs(bb_lines):
+ # find last incref
+ last_incref_pos = 0
+ for pos, ln in enumerate(bb_lines):
+ if _regex_incref.match(ln) is not None:
+ last_incref_pos = pos + 1
+
+ # find last decref
+ last_decref_pos = 0
+ for pos, ln in enumerate(bb_lines):
+ if _regex_decref.match(ln) is not None:
+ last_decref_pos = pos + 1
+
+ last_pos = max(last_incref_pos, last_decref_pos)
+
+ # find decrefs before last_pos
+ decrefs = []
+ head = []
+ for ln in bb_lines[:last_pos]:
+ if _regex_decref.match(ln) is not None:
+ decrefs.append(ln)
+ else:
+ head.append(ln)
+
+ # insert decrefs at last_pos
+ return head + decrefs + bb_lines[last_pos:]
+
+ # Driver
+ processed = []
+
+ for is_func, lines in _extract_functions(llvmir):
+ if is_func:
+ lines = _process_function(lines)
+
+ processed += lines
+
+ return '\n'.join(processed)
+
+
+def remove_redundant_nrt_refct(ll_module):
+ """
+ Remove redundant reference count operations from the
+ `llvmlite.binding.ModuleRef`. This parses the ll_module as a string and
+ line by line to remove the unnecessary nrt refct pairs within each block.
+ Decref calls are moved after the last incref call in the block to avoid
+ temporarily decref'ing to zero (which can happen due to hidden decref from
+ alias).
+
+ Note: non-threadsafe due to usage of global LLVMcontext
+ """
+ # Early escape if NRT_incref is not used
+ try:
+ ll_module.get_function('NRT_incref')
+ except NameError:
+ return ll_module
+
+ # the optimisation pass loses the name of module as it operates on
+ # strings, so back it up and reset it on completion
+ name = ll_module.name
+ newll = _remove_redundant_nrt_refct(str(ll_module))
+ new_mod = ll.parse_assembly(newll)
+ new_mod.name = cgutils.normalize_ir_text(name)
+ return new_mod
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/typeconv/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typeconv/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..4ae3acabfbf1f8e34238ad0ab2ee37a9407d29fe
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typeconv/__init__.py
@@ -0,0 +1 @@
+from .castgraph import Conversion
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/typeconv/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typeconv/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f683daa2c9c805f0e61e51118276eeab9d1006ec
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typeconv/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/typeconv/__pycache__/castgraph.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typeconv/__pycache__/castgraph.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3bac41b2417c73c759561ec795d52049461bd27a
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typeconv/__pycache__/castgraph.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/typeconv/__pycache__/rules.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typeconv/__pycache__/rules.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d96d01022d6ef82bf090b688a751a977e4fdeef0
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typeconv/__pycache__/rules.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/typeconv/__pycache__/typeconv.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typeconv/__pycache__/typeconv.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..de8c1c48def594309c0ed1511190dbd37a3f0b46
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typeconv/__pycache__/typeconv.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/typeconv/_typeconv.cpython-312-x86_64-linux-gnu.so b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typeconv/_typeconv.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..923fba7b1eb244f119e47c7d496da94654c4ae27
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typeconv/_typeconv.cpython-312-x86_64-linux-gnu.so
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:1c80775cdeb203965903e79bec022fbc5f4751e45215efeb09a40b9ee0f26c03
+size 139336
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/typeconv/castgraph.py b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typeconv/castgraph.py
new file mode 100644
index 0000000000000000000000000000000000000000..2591c0cc51e42d472b0f1e4d4d075dd6166dc592
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typeconv/castgraph.py
@@ -0,0 +1,133 @@
+from collections import defaultdict
+from functools import total_ordering
+import enum
+
+
+class Conversion(enum.IntEnum):
+ """
+ A conversion kind from one type to the other. The enum members
+ are ordered from stricter to looser.
+ """
+ # The two types are identical
+ exact = 1
+ # The two types are of the same kind, the destination type has more
+ # extension or precision than the source type (e.g. float32 -> float64,
+ # or int32 -> int64)
+ promote = 2
+ # The source type can be converted to the destination type without loss
+ # of information (e.g. int32 -> int64). Note that the conversion may
+ # still fail explicitly at runtime (e.g. Optional(int32) -> int32)
+ safe = 3
+ # The conversion may appear to succeed at runtime while losing information
+ # or precision (e.g. int32 -> uint32, float64 -> float32, int64 -> int32,
+ # etc.)
+ unsafe = 4
+
+ # This value is only used internally
+ nil = 99
+
+
+class CastSet(object):
+ """A set of casting rules.
+
+ There is at most one rule per target type.
+ """
+
+ def __init__(self):
+ self._rels = {}
+
+ def insert(self, to, rel):
+ old = self.get(to)
+ setrel = min(rel, old)
+ self._rels[to] = setrel
+ return old != setrel
+
+ def items(self):
+ return self._rels.items()
+
+ def get(self, item):
+ return self._rels.get(item, Conversion.nil)
+
+ def __len__(self):
+ return len(self._rels)
+
+ def __repr__(self):
+ body = ["{rel}({ty})".format(rel=rel, ty=ty)
+ for ty, rel in self._rels.items()]
+ return "{" + ', '.join(body) + "}"
+
+ def __contains__(self, item):
+ return item in self._rels
+
+ def __iter__(self):
+ return iter(self._rels.keys())
+
+ def __getitem__(self, item):
+ return self._rels[item]
+
+
+class TypeGraph(object):
+ """A graph that maintains the casting relationship of all types.
+
+ This simplifies the definition of casting rules by automatically
+ propagating the rules.
+ """
+
+ def __init__(self, callback=None):
+ """
+ Args
+ ----
+ - callback: callable or None
+ It is called for each new casting rule with
+ (from_type, to_type, castrel).
+ """
+ assert callback is None or callable(callback)
+ self._forwards = defaultdict(CastSet)
+ self._backwards = defaultdict(set)
+ self._callback = callback
+
+ def get(self, ty):
+ return self._forwards[ty]
+
+ def propagate(self, a, b, baserel):
+ backset = self._backwards[a]
+
+ # Forward propagate the relationship to all nodes that b leads to
+ for child in self._forwards[b]:
+ rel = max(baserel, self._forwards[b][child])
+ if a != child:
+ if self._forwards[a].insert(child, rel):
+ self._callback(a, child, rel)
+ self._backwards[child].add(a)
+
+ # Propagate the relationship from nodes that connects to a
+ for backnode in backset:
+ if backnode != child:
+ backrel = max(rel, self._forwards[backnode][a])
+ if self._forwards[backnode].insert(child, backrel):
+ self._callback(backnode, child, backrel)
+ self._backwards[child].add(backnode)
+
+ # Every node that leads to a connects to b
+ for child in self._backwards[a]:
+ rel = max(baserel, self._forwards[child][a])
+ if b != child:
+ if self._forwards[child].insert(b, rel):
+ self._callback(child, b, rel)
+ self._backwards[b].add(child)
+
+ def insert_rule(self, a, b, rel):
+ self._forwards[a].insert(b, rel)
+ self._callback(a, b, rel)
+ self._backwards[b].add(a)
+ self.propagate(a, b, rel)
+
+ def promote(self, a, b):
+ self.insert_rule(a, b, Conversion.promote)
+
+ def safe(self, a, b):
+ self.insert_rule(a, b, Conversion.safe)
+
+ def unsafe(self, a, b):
+ self.insert_rule(a, b, Conversion.unsafe)
+
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/typeconv/rules.py b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typeconv/rules.py
new file mode 100644
index 0000000000000000000000000000000000000000..fb2f61c2dc1c7d7174b289087f983e09a0394b12
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typeconv/rules.py
@@ -0,0 +1,69 @@
+import itertools
+from .typeconv import TypeManager, TypeCastingRules
+from numba.core import types, config
+
+
+default_type_manager = TypeManager()
+
+
+def dump_number_rules():
+ tm = default_type_manager
+ for a, b in itertools.product(types.number_domain, types.number_domain):
+ print(a, '->', b, tm.check_compatible(a, b))
+
+
+if config.USE_LEGACY_TYPE_SYSTEM: # Old type system
+ def _init_casting_rules(tm):
+ tcr = TypeCastingRules(tm)
+ tcr.safe_unsafe(types.boolean, types.int8)
+ tcr.safe_unsafe(types.boolean, types.uint8)
+
+ tcr.promote_unsafe(types.int8, types.int16)
+ tcr.promote_unsafe(types.uint8, types.uint16)
+
+ tcr.promote_unsafe(types.int16, types.int32)
+ tcr.promote_unsafe(types.uint16, types.uint32)
+
+ tcr.promote_unsafe(types.int32, types.int64)
+ tcr.promote_unsafe(types.uint32, types.uint64)
+
+ tcr.safe_unsafe(types.uint8, types.int16)
+ tcr.safe_unsafe(types.uint16, types.int32)
+ tcr.safe_unsafe(types.uint32, types.int64)
+
+ tcr.safe_unsafe(types.int8, types.float16)
+ tcr.safe_unsafe(types.int16, types.float32)
+ tcr.safe_unsafe(types.int32, types.float64)
+
+
+ tcr.unsafe_unsafe(types.int16, types.float16)
+ tcr.unsafe_unsafe(types.int32, types.float32)
+ # XXX this is inconsistent with the above; but we want to prefer
+ # float64 over int64 when typing a heterogeneous operation,
+ # e.g. `float64 + int64`. Perhaps we need more granularity in the
+ # conversion kinds.
+ tcr.safe_unsafe(types.int64, types.float64)
+ tcr.safe_unsafe(types.uint64, types.float64)
+
+ tcr.promote_unsafe(types.float16, types.float32)
+ tcr.promote_unsafe(types.float32, types.float64)
+
+ tcr.safe(types.float32, types.complex64)
+ tcr.safe(types.float64, types.complex128)
+
+ tcr.promote_unsafe(types.complex64, types.complex128)
+
+ # Allow integers to cast ot void*
+ tcr.unsafe_unsafe(types.uintp, types.voidptr)
+
+ return tcr
+else: # New type system
+ # Currently left as empty
+ # If no casting rules are required we may opt to remove
+ # this framework upon deprecation
+ def _init_casting_rules(tm):
+ tcr = TypeCastingRules(tm)
+ return tcr
+
+default_casting_rules = _init_casting_rules(default_type_manager)
+
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/typeconv/typeconv.py b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typeconv/typeconv.py
new file mode 100644
index 0000000000000000000000000000000000000000..1d380bc017924197b9b0122bcf98546c9cfc4660
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typeconv/typeconv.py
@@ -0,0 +1,128 @@
+try:
+ # This is usually the the first C extension import performed when importing
+ # Numba, if it fails to import, provide some feedback
+ from numba.core.typeconv import _typeconv
+except ImportError as e:
+ base_url = "https://numba.readthedocs.io/en/stable"
+ dev_url = f"{base_url}/developer/contributing.html"
+ user_url = f"{base_url}/user/faq.html#numba-could-not-be-imported"
+ dashes = '-' * 80
+ msg = (f"Numba could not be imported.\n{dashes}\nIf you are seeing this "
+ "message and are undertaking Numba development work, you may need "
+ "to rebuild Numba.\nPlease see the development set up guide:\n\n"
+ f"{dev_url}.\n\n{dashes}\nIf you are not working on Numba "
+ f"development, the original error was: '{str(e)}'.\nFor help, "
+ f"please visit:\n\n{user_url}\n")
+ raise ImportError(msg)
+
+from numba.core.typeconv import castgraph, Conversion
+from numba.core import types
+
+
+class TypeManager(object):
+
+ # The character codes used by the C/C++ API (_typeconv.cpp)
+ _conversion_codes = {Conversion.safe: ord("s"),
+ Conversion.unsafe: ord("u"),
+ Conversion.promote: ord("p"),}
+
+ def __init__(self):
+ self._ptr = _typeconv.new_type_manager()
+ self._types = set()
+
+ def select_overload(self, sig, overloads, allow_unsafe,
+ exact_match_required):
+ sig = [t._code for t in sig]
+ overloads = [[t._code for t in s] for s in overloads]
+ return _typeconv.select_overload(self._ptr, sig, overloads,
+ allow_unsafe, exact_match_required)
+
+ def check_compatible(self, fromty, toty):
+ if not isinstance(toty, types.Type):
+ raise ValueError("Specified type '%s' (%s) is not a Numba type" %
+ (toty, type(toty)))
+ name = _typeconv.check_compatible(self._ptr, fromty._code, toty._code)
+ conv = Conversion[name] if name is not None else None
+ assert conv is not Conversion.nil
+ return conv
+
+ def set_compatible(self, fromty, toty, by):
+ code = self._conversion_codes[by]
+ _typeconv.set_compatible(self._ptr, fromty._code, toty._code, code)
+ # Ensure the types don't die, otherwise they may be recreated with
+ # other type codes and pollute the hash table.
+ self._types.add(fromty)
+ self._types.add(toty)
+
+ def set_promote(self, fromty, toty):
+ self.set_compatible(fromty, toty, Conversion.promote)
+
+ def set_unsafe_convert(self, fromty, toty):
+ self.set_compatible(fromty, toty, Conversion.unsafe)
+
+ def set_safe_convert(self, fromty, toty):
+ self.set_compatible(fromty, toty, Conversion.safe)
+
+ def get_pointer(self):
+ return _typeconv.get_pointer(self._ptr)
+
+
+class TypeCastingRules(object):
+ """
+ A helper for establishing type casting rules.
+ """
+ def __init__(self, tm):
+ self._tm = tm
+ self._tg = castgraph.TypeGraph(self._cb_update)
+
+ def promote(self, a, b):
+ """
+ Set `a` can promote to `b`
+ """
+ self._tg.promote(a, b)
+
+ def unsafe(self, a, b):
+ """
+ Set `a` can unsafe convert to `b`
+ """
+ self._tg.unsafe(a, b)
+
+ def safe(self, a, b):
+ """
+ Set `a` can safe convert to `b`
+ """
+ self._tg.safe(a, b)
+
+ def promote_unsafe(self, a, b):
+ """
+ Set `a` can promote to `b` and `b` can unsafe convert to `a`
+ """
+ self.promote(a, b)
+ self.unsafe(b, a)
+
+ def safe_unsafe(self, a, b):
+ """
+ Set `a` can safe convert to `b` and `b` can unsafe convert to `a`
+ """
+ self._tg.safe(a, b)
+ self._tg.unsafe(b, a)
+
+ def unsafe_unsafe(self, a, b):
+ """
+ Set `a` can unsafe convert to `b` and `b` can unsafe convert to `a`
+ """
+ self._tg.unsafe(a, b)
+ self._tg.unsafe(b, a)
+
+ def _cb_update(self, a, b, rel):
+ """
+ Callback for updating.
+ """
+ if rel == Conversion.promote:
+ self._tm.set_promote(a, b)
+ elif rel == Conversion.safe:
+ self._tm.set_safe_convert(a, b)
+ elif rel == Conversion.unsafe:
+ self._tm.set_unsafe_convert(a, b)
+ else:
+ raise AssertionError(rel)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..26e4a0efdf52203937bf7c89248916239bea2e63
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/__init__.py
@@ -0,0 +1,386 @@
+import struct
+
+import numpy as np
+from numba.core import utils
+
+from .abstract import *
+from .containers import *
+from .functions import *
+from .iterators import *
+from .misc import *
+from .npytypes import *
+from .scalars import *
+from .function_type import *
+
+numpy_version = tuple(map(int, np.__version__.split('.')[:2]))
+
+# Short names
+
+pyobject = PyObject('pyobject')
+ffi_forced_object = Opaque('ffi_forced_object')
+ffi = Opaque('ffi')
+none = NoneType('none')
+ellipsis = EllipsisType('...')
+Any = Phantom('any')
+undefined = Undefined('undefined')
+py2_string_type = Opaque('str')
+unicode_type = UnicodeType('unicode_type')
+string = unicode_type
+unknown = Dummy('unknown')
+npy_rng = NumPyRandomGeneratorType('rng')
+npy_bitgen = NumPyRandomBitGeneratorType('bitgen')
+
+# _undef_var is used to represent undefined variables in the type system.
+_undef_var = UndefVar('_undef_var')
+
+code_type = Opaque('code')
+pyfunc_type = Opaque('pyfunc')
+
+# No operation is defined on voidptr
+# Can only pass it around
+voidptr = RawPointer('void*')
+
+# optional types
+optional = Optional
+deferred_type = DeferredType
+slice2_type = SliceType('slice', 2)
+slice3_type = SliceType('slice', 3)
+void = none
+
+# Need to ignore mypy errors because mypy cannot unify types for both
+# the type systems even if they're logically mutually exclusive.
+# mypy: ignore-errors
+
+if config.USE_LEGACY_TYPE_SYSTEM: # type: ignore
+ boolean = bool_ = Boolean('bool')
+ if numpy_version >= (2, 0):
+ bool = bool_
+
+ byte = uint8 = Integer('uint8')
+ uint16 = Integer('uint16')
+ uint32 = Integer('uint32')
+ uint64 = Integer('uint64')
+
+ int8 = Integer('int8')
+ int16 = Integer('int16')
+ int32 = Integer('int32')
+ int64 = Integer('int64')
+ intp = int32 if utils.MACHINE_BITS == 32 else int64
+ uintp = uint32 if utils.MACHINE_BITS == 32 else uint64
+ intc = int32 if struct.calcsize('i') == 4 else int64
+ uintc = uint32 if struct.calcsize('I') == 4 else uint64
+ ssize_t = int32 if struct.calcsize('n') == 4 else int64
+ size_t = uint32 if struct.calcsize('N') == 4 else uint64
+
+ float32 = Float('float32')
+ float64 = Float('float64')
+ float16 = Float('float16')
+
+ complex64 = Complex('complex64', float32)
+ complex128 = Complex('complex128', float64)
+
+ range_iter32_type = RangeIteratorType(int32)
+ range_iter64_type = RangeIteratorType(int64)
+ unsigned_range_iter64_type = RangeIteratorType(uint64)
+ range_state32_type = RangeType(int32)
+ range_state64_type = RangeType(int64)
+ unsigned_range_state64_type = RangeType(uint64)
+
+ signed_domain = frozenset([int8, int16, int32, int64])
+ unsigned_domain = frozenset([uint8, uint16, uint32, uint64])
+ integer_domain = signed_domain | unsigned_domain
+ real_domain = frozenset([float32, float64])
+ complex_domain = frozenset([complex64, complex128])
+ number_domain = real_domain | integer_domain | complex_domain
+
+ # Integer Aliases
+ c_bool = py_bool = np_bool_ = boolean
+
+ c_uint8 = np_uint8 = uint8
+ c_uint16 = np_uint16 = uint16
+ c_uint32 = np_uint32 = uint32
+ c_uint64 = np_uint64 = uint64
+ c_uintp = np_uintp = uintp
+
+ c_int8 = np_int8 = int8
+ c_int16 = np_int16 = int16
+ c_int32 = np_int32 = int32
+ c_int64 = np_int64 = int64
+ c_intp = py_int = np_intp = intp
+
+ c_float16 = np_float16 = float16
+ c_float32 = np_float32 = float32
+ c_float64 = py_float = np_float64 = float64
+
+ np_complex64 = complex64
+ py_complex = np_complex128 = complex128
+
+ # Domain Aliases
+ py_signed_domain = np_signed_domain = signed_domain
+ np_unsigned_domain = unsigned_domain
+ py_integer_domain = np_integer_domain = integer_domain
+ py_real_domain = np_real_domain = real_domain
+ py_complex_domain = np_complex_domain = complex_domain
+ py_number_domain = np_number_domain = number_domain
+
+ # Aliases to NumPy type names
+
+ b1 = bool_
+ i1 = int8
+ i2 = int16
+ i4 = int32
+ i8 = int64
+ u1 = uint8
+ u2 = uint16
+ u4 = uint32
+ u8 = uint64
+
+ f2 = float16
+ f4 = float32
+ f8 = float64
+
+ c8 = complex64
+ c16 = complex128
+
+ np_float_ = float32
+ np_double = double = float64
+ if numpy_version < (2, 0):
+ float_ = float32
+
+ _make_signed = lambda x: globals()["int%d" % (np.dtype(x).itemsize * 8)]
+ _make_unsigned = lambda x: globals()["uint%d" % (np.dtype(x).itemsize * 8)]
+
+ char = np_char = _make_signed(np.byte)
+ uchar = np_uchar = byte = _make_unsigned(np.byte)
+ short = np_short = _make_signed(np.short)
+ ushort = np_ushort = _make_unsigned(np.short)
+ int_ = np_int_ = _make_signed(np.int_)
+ uint = np_uint = _make_unsigned(np.int_)
+ intc = np_intc = _make_signed(np.intc) # C-compat int
+ uintc = np_uintc = _make_unsigned(np.uintc) # C-compat uint
+ long_ = np_long = _make_signed(np.int_) # C-compat long
+ ulong = np_ulong = _make_unsigned(np.int_) # C-compat ulong
+ longlong = np_longlong = _make_signed(np.longlong)
+ ulonglong = np_ulonglong = _make_unsigned(np.longlong)
+
+ all_str = '''
+ int8
+ int16
+ int32
+ int64
+ uint8
+ uint16
+ uint32
+ uint64
+ intp
+ uintp
+ intc
+ uintc
+ ssize_t
+ size_t
+ boolean
+ float32
+ float64
+ complex64
+ complex128
+ bool_
+ byte
+ char
+ uchar
+ short
+ ushort
+ int_
+ uint
+ long_
+ ulong
+ longlong
+ ulonglong
+ float_
+ double
+ void
+ none
+ b1
+ i1
+ i2
+ i4
+ i8
+ u1
+ u2
+ u4
+ u8
+ f4
+ f8
+ c8
+ c16
+ optional
+ ffi_forced_object
+ ffi
+ deferred_type
+ '''
+else:
+ from .new_scalars import *
+ ### Machine Datatypes ###
+ c_bool = MachineBoolean('c_bool')
+ c_byte = c_int8 = MachineInteger('c_int8')
+ c_int16 = MachineInteger('c_int16')
+ c_int32 = MachineInteger('c_int32')
+ c_int64 = MachineInteger('c_int64')
+ c_uint8 = MachineInteger('c_uint8')
+ c_uint16 = MachineInteger('c_uint16')
+ c_uint32 = MachineInteger('c_uint32')
+ c_uint64 = MachineInteger('c_uint64')
+
+ c_intp = c_int32 if utils.MACHINE_BITS == 32 else c_int64
+ c_uintp = c_uint32 if utils.MACHINE_BITS == 32 else c_uint64
+
+ # Machine Floats
+ c_float16 = MachineFloat('c_float16')
+ c_float32 = MachineFloat('c_float32')
+ c_float64 = MachineFloat('c_float64')
+
+ # Machine Complex
+ c_complex64 = MachineComplex('c_complex64', c_float32)
+ c_complex128 = MachineComplex('c_complex128', c_float64)
+
+ c_signed_domain = frozenset([c_int8, c_int16, c_int32, c_int64])
+ c_unsigned_domain = frozenset([c_uint8, c_uint16, c_uint32, c_uint64])
+ c_integer_domain = c_signed_domain | c_unsigned_domain
+ c_real_domain = frozenset([c_float32, c_float64])
+ c_complex_domain = frozenset([c_complex64, c_complex128])
+ c_number_domain = c_real_domain | c_integer_domain | c_complex_domain
+
+ ### Python Datatypes ###
+ # Python Integers
+ py_bool = PythonBoolean('py_bool')
+ py_int = PythonInteger('py_int')
+
+ # Python Float
+ py_float = PythonFloat('py_float')
+
+ # Python Complex
+ py_complex = PythonComplex('py_complex', py_float)
+
+ py_signed_domain = frozenset([py_int])
+ py_integer_domain = py_signed_domain
+ py_real_domain = frozenset([py_float])
+ py_complex_domain = frozenset([py_complex])
+ py_number_domain = py_real_domain | py_integer_domain | py_complex_domain
+
+ range_iter_type = RangeIteratorType(py_int)
+ range_state_type = RangeType(py_int)
+
+ ### NumPy Datatypes ###
+ # Numpy Integers
+ np_bool_ = np_bool = NumPyBoolean('np_bool_')
+ np_byte = np_int8 = NumPyInteger('np_int8')
+ np_int16 = NumPyInteger('np_int16')
+ np_int32 = NumPyInteger('np_int32')
+ np_int64 = NumPyInteger('np_int64')
+ np_uint8 = NumPyInteger('np_uint8')
+ np_uint16 = NumPyInteger('np_uint16')
+ np_uint32 = NumPyInteger('np_uint32')
+ np_uint64 = NumPyInteger('np_uint64')
+
+ np_intp = np_int32 if utils.MACHINE_BITS == 32 else np_int64
+ np_uintp = np_uint32 if utils.MACHINE_BITS == 32 else np_uint64
+
+ # NumPy Floats
+ np_float16 = NumPyFloat('np_float16')
+ np_float32 = NumPyFloat('np_float32')
+ np_float64 = NumPyFloat('np_float64')
+
+ # NumPy Complex
+ np_complex64 = NumPyComplex('np_complex64', np_float32)
+ np_complex128 = NumPyComplex('np_complex128', np_float64)
+
+ np_signed_domain = frozenset([np_int8, np_int16, np_int32, np_int64])
+ np_unsigned_domain = frozenset([np_uint8, np_uint16, np_uint32, np_uint64])
+ np_integer_domain = np_signed_domain | np_unsigned_domain
+ np_real_domain = frozenset([np_float32, np_float64])
+ np_complex_domain = frozenset([np_complex64, np_complex128])
+ np_number_domain = np_real_domain | np_integer_domain | np_complex_domain
+
+ # NumPy globals
+ np_double = np_float64
+ _make_signed = lambda x: globals()["np_int%d" % (np.dtype(x).itemsize * 8)]
+ _make_unsigned = lambda x: globals()["np_uint%d" % (np.dtype(x).itemsize * 8)]
+
+ np_char = _make_signed(np.byte)
+ np_uchar = byte = _make_unsigned(np.byte)
+ np_short = _make_signed(np.short)
+ np_ushort = _make_unsigned(np.short)
+ np_int_ = _make_signed(np.int_)
+ np_uint = _make_unsigned(np.int_)
+ np_intc = _make_signed(np.intc) # C-compat int
+ np_uintc = _make_unsigned(np.uintc) # C-compat uint
+ np_long_ = _make_signed(np.int_) # C-compat long
+ np_ulong = _make_unsigned(np.int_) # C-compat ulong
+ np_longlong = _make_signed(np.longlong)
+ np_ulonglong = _make_unsigned(np.longlong)
+
+ all_str = '''
+ c_bool
+ c_byte
+ c_int8
+ c_int16
+ c_int32
+ c_int64
+ c_uint8
+ c_uint16
+ c_uint32
+ c_uint64
+ c_intp
+ c_uintp
+ c_float16
+ c_float32
+ c_float64
+ c_complex64
+ c_complex128
+ py_bool
+ py_int
+ py_float
+ py_complex
+ np_bool_
+ np_bool
+ np_byte
+ np_int8
+ np_int16
+ np_int32
+ np_int64
+ np_uint8
+ np_uint16
+ np_uint32
+ np_uint64
+ np_intp
+ np_uintp
+ np_float16
+ np_float32
+ np_float64
+ np_complex64
+ np_complex128
+ np_double
+ np_char
+ np_uchar
+ np_short
+ np_ushort
+ np_int_
+ np_uint
+ np_intc
+ np_uintc
+ np_long_
+ np_ulong
+ np_longlong
+ np_ulonglong
+ ffi_forced_object
+ ffi
+ none
+ optional
+ deferred_type
+ void
+ '''
+
+
+__all__ = all_str.split()
+if numpy_version >= (2, 0) and config.USE_LEGACY_TYPE_SYSTEM:
+ __all__.remove('float_')
+ __all__.append('bool')
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/__init__.pyi b/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/__init__.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..0e460b36a05ee1a7e5f969a4c7a4f1c02f4966ae
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/__init__.pyi
@@ -0,0 +1,224 @@
+# This file is provided by @jorenham with minor modifications (e.g. typos).
+# See original content at: https://github.com/numba/numba/pull/9945#pullrequestreview-2668923222.
+#
+# This file has been tested under:
+# - mypy for the use-case in issue #9900
+# - mypy numba/core/types/__init__.pyi
+# Testing with mypy.stubtest does not work due to other mypy errors in the code
+# base.
+from .abstract import *
+from .common import Opaque
+from .containers import *
+from .function_type import *
+from .functions import *
+from .iterators import *
+from .misc import *
+from .new_scalars import *
+from .npytypes import *
+from .scalars import *
+
+__all__ = [
+ "b1",
+ "bool",
+ "bool_",
+ "boolean",
+ "byte",
+ "c8",
+ "c16",
+ "char",
+ "complex64",
+ "complex128",
+ "deferred_type",
+ "double",
+ "f4",
+ "f8",
+ "ffi",
+ "ffi_forced_object",
+ "float32",
+ "float64",
+ "i1",
+ "i2",
+ "i4",
+ "i8",
+ "int8",
+ "int16",
+ "int32",
+ "int64",
+ "int_",
+ "intc",
+ "intp",
+ "long_",
+ "longlong",
+ "none",
+ "optional",
+ "short",
+ "size_t",
+ "ssize_t",
+ "u1",
+ "u2",
+ "u4",
+ "u8",
+ "uchar",
+ "uint",
+ "uint8",
+ "uint16",
+ "uint32",
+ "uint64",
+ "uintc",
+ "uintp",
+ "ulong",
+ "ulonglong",
+ "ushort",
+ "void",
+]
+
+# TODO: Final
+
+pyobject: PyObject = ...
+ffi_forced_object: Opaque = ...
+ffi: Opaque = ...
+none: NoneType = ...
+ellipsis: EllipsisType = ...
+Any: Phantom = ...
+undefined: Undefined = ...
+py2_string_type: Opaque = ...
+unicode_type: UnicodeType = ...
+string: UnicodeType = ...
+unknown: Dummy = ...
+npy_rng: NumPyRandomGeneratorType = ...
+npy_bitgen: NumPyRandomBitGeneratorType = ...
+
+_undef_var: UndefVar = ...
+
+code_type: Opaque = ...
+pyfunc_type: Opaque = ...
+
+voidptr: RawPointer = ...
+
+optional = Optional
+deferred_type = DeferredType
+slice2_type: SliceType = ...
+slice3_type: SliceType = ...
+void: NoneType = ...
+
+boolean: Boolean = ...
+bool_: Boolean = ...
+bool: Boolean = ... # numpy>=2
+
+int8: Integer = ...
+int16: Integer = ...
+int32: Integer = ...
+int64: Integer = ...
+intp: Integer = ...
+intc: Integer = ...
+ssize_t: Integer = ...
+char: Integer = ...
+short: Integer = ...
+int_: Integer = ...
+long_: Integer = ...
+longlong: Integer = ...
+
+byte: Integer = ...
+uint8: Integer = ...
+uint16: Integer = ...
+uint32: Integer = ...
+uint64: Integer = ...
+uintp: Integer = ...
+uintc: Integer = ...
+size_t: Integer = ...
+uchar: Integer = ...
+ushort: Integer = ...
+uint: Integer = ...
+ulong: Integer = ...
+ulonglong: Integer = ...
+
+float16: Float = ...
+float32: Float = ...
+float_ = float32
+float64: Float = ...
+double = float64
+
+# TODO: make generic in the wrapped `Float` type
+complex64: Complex = ...
+complex128: Complex = ...
+
+range_iter32_type: RangeIteratorType = ...
+range_iter64_type: RangeIteratorType = ...
+unsigned_range_iter64_type: RangeIteratorType = ...
+range_state32_type: RangeType = ...
+range_state64_type: RangeType = ...
+unsigned_range_state64_type: RangeType = ...
+
+signed_domain: frozenset[Integer] = ...
+unsigned_domain: frozenset[Integer] = ...
+integer_domain: frozenset[Integer] = ...
+real_domain: frozenset[Float] = ...
+complex_domain: frozenset[Complex] = ...
+number_domain: frozenset[Integer | Float | Complex] = ...
+
+c_bool: MachineBoolean | Boolean = ...
+c_int8: MachineInteger | Integer = ...
+c_int16: MachineInteger | Integer = ...
+c_int32: MachineInteger | Integer = ...
+c_int64: MachineInteger | Integer = ...
+c_intp: MachineInteger | Integer = ...
+c_uint8: MachineInteger | Integer = ...
+c_uint16: MachineInteger | Integer = ...
+c_uint32: MachineInteger | Integer = ...
+c_uint64: MachineInteger | Integer = ...
+c_uintp: MachineInteger | Integer = ...
+c_float16: MachineFloat | Float = ...
+c_float32: MachineFloat | Float = ...
+c_float64: MachineFloat | Float = ...
+
+np_bool_: NumPyBoolean | Boolean = ...
+np_int8: NumPyInteger | Integer = ...
+np_int16: NumPyInteger | Integer = ...
+np_int32: NumPyInteger | Integer = ...
+np_int64: NumPyInteger | Integer = ...
+np_intp: NumPyInteger | Integer = ...
+np_uint8: NumPyInteger | Integer = ...
+np_uint16: NumPyInteger | Integer = ...
+np_uint32: NumPyInteger | Integer = ...
+np_uint64: NumPyInteger | Integer = ...
+np_uintp: NumPyInteger | Integer = ...
+np_float16: NumPyFloat | Float = ...
+np_float32: NumPyFloat | Float = ...
+np_float64: NumPyFloat | Float = ...
+np_float_ = float32
+np_double = np_float64
+np_complex64: NumPyComplex | Complex = ...
+np_complex128: NumPyComplex | Complex = ...
+
+py_bool: PythonBoolean | Boolean = ...
+py_int: PythonInteger | Integer = ...
+py_float: PythonFloat | Float = ...
+py_complex: PythonComplex | Complex = ...
+
+py_signed_domain: frozenset[PythonInteger] | frozenset[Integer] = ...
+py_integer_domain: frozenset[PythonInteger] | frozenset[Integer] = ...
+py_real_domain: frozenset[PythonFloat] | frozenset[Float] = ...
+py_complex_domain: frozenset[PythonComplex] | frozenset[Complex] = ...
+py_number_domain: frozenset[PythonInteger | PythonFloat | PythonComplex] | frozenset[Integer | Float | Complex] = ...
+
+np_signed_domain: frozenset[NumPyInteger] | frozenset[Integer] = ...
+np_unsigned_domain: frozenset[NumPyInteger] | frozenset[Integer] = ...
+np_integer_domain: frozenset[NumPyInteger] | frozenset[Integer] = ...
+np_real_domain: frozenset[NumPyFloat] | frozenset[Float] = ...
+np_complex_domain: frozenset[NumPyComplex] | frozenset[Complex] = ...
+np_number_domain: frozenset[NumPyInteger | NumPyFloat | NumPyComplex] | frozenset[Integer | Float | Complex] = ...
+
+b1 = bool_
+i1 = int8
+i2 = int16
+i4 = int32
+i8 = int64
+u1 = uint8
+u2 = uint16
+u4 = uint32
+u8 = uint64
+f2 = float16
+f4 = float32
+f8 = float64
+c8 = complex64
+c16 = complex128
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3a90812f718cbfed1e2099f388fe80a6493854f0
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/__pycache__/abstract.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/__pycache__/abstract.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..487961402befd3854b071c24ce05ee3176c658e6
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/__pycache__/abstract.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/__pycache__/common.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/__pycache__/common.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..16ecceab0259dc4b733b5ebcf42960295e3cc176
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/__pycache__/common.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/__pycache__/containers.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/__pycache__/containers.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8e3ab9fab5c6bbdfd03d1386bb35afdd52d6cc00
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/__pycache__/containers.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/__pycache__/function_type.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/__pycache__/function_type.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..79f8c00ca39c17e2afcf7162921fa9f6b0901393
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/__pycache__/function_type.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/__pycache__/functions.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/__pycache__/functions.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c1254de034354d7247bfb9eb1ade41d4b880045e
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/__pycache__/functions.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/__pycache__/iterators.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/__pycache__/iterators.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e30c8ac309bbbb7828e955a4ea8af8fc72ec8bfd
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/__pycache__/iterators.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/__pycache__/misc.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/__pycache__/misc.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0833591b47748eca93e10fe9dcb34dfc82d97e5d
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/__pycache__/misc.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/__pycache__/npytypes.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/__pycache__/npytypes.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8b4b0f4af87a19ecdd7d3a455173c7d8c761adb1
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/__pycache__/npytypes.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/__pycache__/old_scalars.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/__pycache__/old_scalars.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..eb2abd91b9402d92e70322c83cff4871d46a0a88
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/__pycache__/old_scalars.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/__pycache__/scalars.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/__pycache__/scalars.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a32fdd21c167de5071c2c7162fd58cc4e0c6eb54
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/__pycache__/scalars.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/abstract.py b/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/abstract.py
new file mode 100644
index 0000000000000000000000000000000000000000..054958833ae6d8175c237b736aaeb1f301d4ed4e
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/abstract.py
@@ -0,0 +1,512 @@
+from abc import ABCMeta, abstractmethod, abstractproperty
+from typing import Dict as ptDict, Type as ptType
+import itertools
+import weakref
+from functools import cached_property
+
+import numpy as np
+
+from numba.core.utils import get_hashable_key
+
+# Types are added to a global registry (_typecache) in order to assign
+# them unique integer codes for fast matching in _dispatcher.c.
+# However, we also want types to be disposable, therefore we ensure
+# each type is interned as a weak reference, so that it lives only as
+# long as necessary to keep a stable type code.
+# NOTE: some types can still be made immortal elsewhere (for example
+# in _dispatcher.c's internal caches).
+_typecodes = itertools.count()
+
+def _autoincr():
+ n = next(_typecodes)
+ # 4 billion types should be enough, right?
+ assert n < 2 ** 32, "Limited to 4 billion types"
+ return n
+
+_typecache: ptDict[weakref.ref, weakref.ref] = {}
+
+def _on_type_disposal(wr, _pop=_typecache.pop):
+ _pop(wr, None)
+
+
+class _TypeMetaclass(ABCMeta):
+ """
+ A metaclass that will intern instances after they are created.
+ This is done by first creating a new instance (including calling
+ __init__, which sets up the required attributes for equality
+ and hashing), then looking it up in the _typecache registry.
+ """
+
+ def __init__(cls, name, bases, orig_vars):
+ # __init__ is hooked to mark whether a Type class being defined is a
+ # Numba internal type (one which is defined somewhere under the `numba`
+ # module) or an external type (one which is defined elsewhere, for
+ # example a user defined type).
+ super(_TypeMetaclass, cls).__init__(name, bases, orig_vars)
+ root = (cls.__module__.split('.'))[0]
+ cls._is_internal = root == "numba"
+
+ def _intern(cls, inst):
+ # Try to intern the created instance
+ wr = weakref.ref(inst, _on_type_disposal)
+ orig = _typecache.get(wr)
+ orig = orig and orig()
+ if orig is not None:
+ return orig
+ else:
+ inst._code = _autoincr()
+ _typecache[wr] = wr
+ return inst
+
+ def __call__(cls, *args, **kwargs):
+ """
+ Instantiate *cls* (a Type subclass, presumably) and intern it.
+ If an interned instance already exists, it is returned, otherwise
+ the new instance is returned.
+ """
+ inst = type.__call__(cls, *args, **kwargs)
+ return cls._intern(inst)
+
+
+def _type_reconstructor(reconstructor, reconstructor_args, state):
+ """
+ Rebuild function for unpickling types.
+ """
+ obj = reconstructor(*reconstructor_args)
+ if state:
+ obj.__dict__.update(state)
+ return type(obj)._intern(obj)
+
+
+class Type(metaclass=_TypeMetaclass):
+ """
+ The base class for all Numba types.
+ It is essential that proper equality comparison is implemented. The
+ default implementation uses the "key" property (overridable in subclasses)
+ for both comparison and hashing, to ensure sane behaviour.
+ """
+
+ mutable = False
+ # Rather the type is reflected at the python<->nopython boundary
+ reflected = False
+
+ def __init__(self, name):
+ self.name = name
+
+ @property
+ def key(self):
+ """
+ A property used for __eq__, __ne__ and __hash__. Can be overridden
+ in subclasses.
+ """
+ return self.name
+
+ @property
+ def mangling_args(self):
+ """
+ Returns `(basename, args)` where `basename` is the name of the type
+ and `args` is a sequence of parameters of the type.
+
+ Subclass should override to specialize the behavior.
+ By default, this returns `(self.name, ())`.
+ """
+ return self.name, ()
+
+ def __repr__(self):
+ return self.name
+
+ def __str__(self):
+ return self.name
+
+ def __hash__(self):
+ return hash(self.key)
+
+ def __eq__(self, other):
+ return self.__class__ is other.__class__ and self.key == other.key
+
+ def __ne__(self, other):
+ return not (self == other)
+
+ def __reduce__(self):
+ reconstructor, args, state = super(Type, self).__reduce__()
+ return (_type_reconstructor, (reconstructor, args, state))
+
+ def unify(self, typingctx, other):
+ """
+ Try to unify this type with the *other*. A third type must
+ be returned, or None if unification is not possible.
+ Only override this if the coercion logic cannot be expressed
+ as simple casting rules.
+ """
+ return None
+
+ def can_convert_to(self, typingctx, other):
+ """
+ Check whether this type can be converted to the *other*.
+ If successful, must return a string describing the conversion, e.g.
+ "exact", "promote", "unsafe", "safe"; otherwise None is returned.
+ """
+ return None
+
+ def can_convert_from(self, typingctx, other):
+ """
+ Similar to *can_convert_to*, but in reverse. Only needed if
+ the type provides conversion from other types.
+ """
+ return None
+
+ def is_precise(self):
+ """
+ Whether this type is precise, i.e. can be part of a successful
+ type inference. Default implementation returns True.
+ """
+ return True
+
+ def augment(self, other):
+ """
+ Augment this type with the *other*. Return the augmented type,
+ or None if not supported.
+ """
+ return None
+
+ # User-facing helpers. These are not part of the core Type API but
+ # are provided so that users can write e.g. `numba.boolean(1.5)`
+ # (returns True) or `types.int32(types.int32[:])` (returns something
+ # usable as a function signature).
+
+ def __call__(self, *args):
+ from numba.core.typing import signature
+ if len(args) == 1 and not isinstance(args[0], Type):
+ return self.cast_python_value(args[0])
+ return signature(self, # return_type
+ *args)
+
+ def __getitem__(self, args):
+ """
+ Return an array of this type.
+ """
+ from numba.core.types import Array
+ ndim, layout = self._determine_array_spec(args)
+ return Array(dtype=self, ndim=ndim, layout=layout)
+
+ def _determine_array_spec(self, args):
+ # XXX non-contiguous by default, even for 1d arrays,
+ # doesn't sound very intuitive
+ def validate_slice(s):
+ return isinstance(s, slice) and s.start is None and s.stop is None
+
+ if isinstance(args, (tuple, list)) and all(map(validate_slice, args)):
+ ndim = len(args)
+ if args[0].step == 1:
+ layout = 'F'
+ elif args[-1].step == 1:
+ layout = 'C'
+ else:
+ layout = 'A'
+ elif validate_slice(args):
+ ndim = 1
+ if args.step == 1:
+ layout = 'C'
+ else:
+ layout = 'A'
+ else:
+ # Raise a KeyError to not be handled by collection constructors (e.g. list).
+ raise KeyError(f"Can only index numba types with slices with no start or stop, got {args}.")
+
+ return ndim, layout
+
+ def cast_python_value(self, args):
+ raise NotImplementedError
+
+
+ @property
+ def is_internal(self):
+ """ Returns True if this class is an internally defined Numba type by
+ virtue of the module in which it is instantiated, False else."""
+ return self._is_internal
+
+ def dump(self, tab=''):
+ print(f'{tab}DUMP {type(self).__name__}[code={self._code}, name={self.name}]')
+
+# XXX we should distinguish between Dummy (no meaningful
+# representation, e.g. None or a builtin function) and Opaque (has a
+# meaningful representation, e.g. ExternalFunctionPointer)
+
+class Dummy(Type):
+ """
+ Base class for types that do not really have a representation and are
+ compatible with a void*.
+ """
+
+
+class Hashable(Type):
+ """
+ Base class for hashable types.
+ """
+
+
+class Number(Hashable):
+ """
+ Base class for number types.
+ """
+
+ def unify(self, typingctx, other):
+ """
+ Unify the two number types using Numpy's rules.
+ """
+ from numba.np import numpy_support
+ if isinstance(other, Number):
+ # XXX: this can produce unsafe conversions,
+ # e.g. would unify {int64, uint64} to float64
+ a = numpy_support.as_dtype(self)
+ b = numpy_support.as_dtype(other)
+ sel = np.promote_types(a, b)
+ return numpy_support.from_dtype(sel)
+
+
+class Callable(Type):
+ """
+ Base class for callables.
+ """
+
+ @abstractmethod
+ def get_call_type(self, context, args, kws):
+ """
+ Using the typing *context*, resolve the callable's signature for
+ the given arguments. A signature object is returned, or None.
+ """
+
+ @abstractmethod
+ def get_call_signatures(self):
+ """
+ Returns a tuple of (list of signatures, parameterized)
+ """
+
+ @abstractmethod
+ def get_impl_key(self, sig):
+ """
+ Returns the impl key for the given signature
+ """
+
+
+class DTypeSpec(Type):
+ """
+ Base class for types usable as "dtype" arguments to various Numpy APIs
+ (e.g. np.empty()).
+ """
+
+ @abstractproperty
+ def dtype(self):
+ """
+ The actual dtype denoted by this dtype spec (a Type instance).
+ """
+
+
+class IterableType(Type):
+ """
+ Base class for iterable types.
+ """
+
+ @abstractproperty
+ def iterator_type(self):
+ """
+ The iterator type obtained when calling iter() (explicitly or implicitly).
+ """
+
+
+class Sized(Type):
+ """
+ Base class for objects that support len()
+ """
+
+
+class ConstSized(Sized):
+ """
+ For types that have a constant size
+ """
+ @abstractmethod
+ def __len__(self):
+ pass
+
+
+class IteratorType(IterableType):
+ """
+ Base class for all iterator types.
+ Derived classes should implement the *yield_type* attribute.
+ """
+
+ def __init__(self, name, **kwargs):
+ super(IteratorType, self).__init__(name, **kwargs)
+
+ @abstractproperty
+ def yield_type(self):
+ """
+ The type of values yielded by the iterator.
+ """
+
+ # This is a property to avoid recursivity (for pickling)
+
+ @property
+ def iterator_type(self):
+ return self
+
+
+class Container(Sized, IterableType):
+ """
+ Base class for container types.
+ """
+
+
+class Sequence(Container):
+ """
+ Base class for 1d sequence types. Instances should have the *dtype*
+ attribute.
+ """
+
+
+class MutableSequence(Sequence):
+ """
+ Base class for 1d mutable sequence types. Instances should have the
+ *dtype* attribute.
+ """
+
+ mutable = True
+
+class ArrayCompatible(Type):
+ """
+ Type class for Numpy array-compatible objects (typically, objects
+ exposing an __array__ method).
+ Derived classes should implement the *as_array* attribute.
+ """
+ # If overridden by a subclass, it should also implement typing
+ # for '__array_wrap__' with arguments (input, formal result).
+ array_priority = 0.0
+
+ @abstractproperty
+ def as_array(self):
+ """
+ The equivalent array type, for operations supporting array-compatible
+ objects (such as ufuncs).
+ """
+
+ # For compatibility with types.Array
+
+ @cached_property
+ def ndim(self):
+ return self.as_array.ndim
+
+ @cached_property
+ def layout(self):
+ return self.as_array.layout
+
+ @cached_property
+ def dtype(self):
+ return self.as_array.dtype
+
+
+class Literal(Type):
+ """Base class for Literal types.
+ Literal types contain the original Python value in the type.
+
+ A literal type should always be constructed from the `literal(val)`
+ function.
+ """
+
+ # *ctor_map* is a dictionary mapping Python types to Literal subclasses
+ # for constructing a numba type for a given Python type.
+ # It is used in `literal(val)` function.
+ # To add new Literal subclass, register a new mapping to this dict.
+ ctor_map: ptDict[type, ptType['Literal']] = {}
+
+ # *_literal_type_cache* is used to cache the numba type of the given value.
+ _literal_type_cache = None
+
+ def __init__(self, value):
+ if type(self) is Literal:
+ raise TypeError(
+ "Cannot be constructed directly. "
+ "Use `numba.types.literal(value)` instead",
+ )
+ self._literal_init(value)
+ fmt = "Literal[{}]({})"
+ super(Literal, self).__init__(fmt.format(type(value).__name__, value))
+
+ def _literal_init(self, value):
+ self._literal_value = value
+ # We want to support constants of non-hashable values, therefore
+ # fall back on the value's id() if necessary.
+ self._key = get_hashable_key(value)
+
+ @property
+ def literal_value(self):
+ return self._literal_value
+
+ @property
+ def literal_type(self):
+ if self._literal_type_cache is None:
+ from numba.core import typing
+ ctx = typing.Context()
+ try:
+ res = ctx.resolve_value_type(self.literal_value)
+ except ValueError as e:
+
+ if "Int value is too large" in str(e):
+ # If a string literal cannot create an IntegerLiteral
+ # because of overflow we generate this message.
+ msg = f"Cannot create literal type. {str(e)}"
+ raise TypeError(msg)
+ # Not all literal types have a literal_value that can be
+ # resolved to a type, for example, LiteralStrKeyDict has a
+ # literal_value that is a python dict for which there's no
+ # `typeof` support.
+ msg = "{} has no attribute 'literal_type'".format(self)
+ raise AttributeError(msg)
+ self._literal_type_cache = res
+
+ return self._literal_type_cache
+
+
+
+class TypeRef(Dummy):
+ """Reference to a type.
+
+ Used when a type is passed as a value.
+ """
+ def __init__(self, instance_type):
+ self.instance_type = instance_type
+ super(TypeRef, self).__init__('typeref[{}]'.format(self.instance_type))
+
+ @property
+ def key(self):
+ return self.instance_type
+
+
+class InitialValue(object):
+ """
+ Used as a mixin for a type will potentially have an initial value that will
+ be carried in the .initial_value attribute.
+ """
+ def __init__(self, initial_value):
+ self._initial_value = initial_value
+
+ @property
+ def initial_value(self):
+ return self._initial_value
+
+
+class Poison(Type):
+ """
+ This is the "bottom" type in the type system. It won't unify and it's
+ unliteral version is Poison of itself. It's advisable for debugging purposes
+ to call the constructor with the type that's being poisoned (for whatever
+ reason) but this isn't strictly required.
+ """
+ def __init__(self, ty):
+ self.ty = ty
+ super(Poison, self).__init__(name="Poison<%s>" % ty)
+
+ def __unliteral__(self):
+ return Poison(self)
+
+ def unify(self, typingctx, other):
+ return None
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/common.py b/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/common.py
new file mode 100644
index 0000000000000000000000000000000000000000..129f109dde011295cbe118f8e161928b3f2be598
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/common.py
@@ -0,0 +1,104 @@
+"""
+Helper classes / mixins for defining types.
+"""
+
+from .abstract import ArrayCompatible, Dummy, IterableType, IteratorType
+from numba.core.errors import NumbaTypeError, NumbaValueError
+
+
+class Opaque(Dummy):
+ """
+ A type that is a opaque pointer.
+ """
+
+
+class SimpleIterableType(IterableType):
+
+ def __init__(self, name, iterator_type):
+ self._iterator_type = iterator_type
+ super(SimpleIterableType, self).__init__(name)
+
+ @property
+ def iterator_type(self):
+ return self._iterator_type
+
+
+class SimpleIteratorType(IteratorType):
+
+ def __init__(self, name, yield_type):
+ self._yield_type = yield_type
+ super(SimpleIteratorType, self).__init__(name)
+
+ @property
+ def yield_type(self):
+ return self._yield_type
+
+
+class Buffer(IterableType, ArrayCompatible):
+ """
+ Type class for objects providing the buffer protocol.
+ Derived classes exist for more specific cases.
+ """
+ mutable = True
+ slice_is_copy = False
+ aligned = True
+
+ # CS and FS are not reserved for inner contig but strided
+ LAYOUTS = frozenset(['C', 'F', 'CS', 'FS', 'A'])
+
+ def __init__(self, dtype, ndim, layout, readonly=False, name=None):
+ from .misc import unliteral
+
+ if isinstance(dtype, Buffer):
+ msg = ("The dtype of a Buffer type cannot itself be a Buffer type, "
+ "this is unsupported behaviour."
+ "\nThe dtype requested for the unsupported Buffer was: {}.")
+ raise NumbaTypeError(msg.format(dtype))
+ if layout not in self.LAYOUTS:
+ raise NumbaValueError("Invalid layout '%s'" % layout)
+ self.dtype = unliteral(dtype)
+ self.ndim = ndim
+ self.layout = layout
+ if readonly:
+ self.mutable = False
+ if name is None:
+ type_name = self.__class__.__name__.lower()
+ if readonly:
+ type_name = "readonly %s" % type_name
+ name = "%s(%s, %sd, %s)" % (type_name, dtype, ndim, layout)
+ super(Buffer, self).__init__(name)
+
+ @property
+ def iterator_type(self):
+ from .iterators import ArrayIterator
+ return ArrayIterator(self)
+
+ @property
+ def as_array(self):
+ return self
+
+ def copy(self, dtype=None, ndim=None, layout=None):
+ if dtype is None:
+ dtype = self.dtype
+ if ndim is None:
+ ndim = self.ndim
+ if layout is None:
+ layout = self.layout
+ return self.__class__(dtype=dtype, ndim=ndim, layout=layout,
+ readonly=not self.mutable)
+
+ @property
+ def key(self):
+ return self.dtype, self.ndim, self.layout, self.mutable
+
+ @property
+ def is_c_contig(self):
+ return self.layout == 'C' or (self.ndim <= 1 and self.layout in 'CF')
+
+ @property
+ def is_f_contig(self):
+ return self.layout == 'F' or (self.ndim <= 1 and self.layout in 'CF')
+
+ @property
+ def is_contig(self):
+ return self.layout in 'CF'
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/containers.py b/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/containers.py
new file mode 100644
index 0000000000000000000000000000000000000000..d0a8a1f1ba6656b867ea85c63f9208cf1e03897b
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/containers.py
@@ -0,0 +1,974 @@
+from collections.abc import Iterable
+from collections.abc import Sequence as pySequence
+from types import MappingProxyType
+
+from .abstract import (
+ ConstSized,
+ Container,
+ Hashable,
+ MutableSequence,
+ Sequence,
+ Type,
+ TypeRef,
+ Literal,
+ InitialValue,
+ Poison,
+)
+from .common import (
+ Buffer,
+ IterableType,
+ SimpleIterableType,
+ SimpleIteratorType,
+)
+from .misc import Undefined, unliteral, Optional, NoneType
+from ..typeconv import Conversion
+from ..errors import TypingError
+from .. import utils
+
+
+class Pair(Type):
+ """
+ A heterogeneous pair.
+ """
+
+ def __init__(self, first_type, second_type):
+ self.first_type = first_type
+ self.second_type = second_type
+ name = "pair<%s, %s>" % (first_type, second_type)
+ super(Pair, self).__init__(name=name)
+
+ @property
+ def key(self):
+ return self.first_type, self.second_type
+
+ def unify(self, typingctx, other):
+ if isinstance(other, Pair):
+ first = typingctx.unify_pairs(self.first_type, other.first_type)
+ second = typingctx.unify_pairs(self.second_type, other.second_type)
+ if first is not None and second is not None:
+ return Pair(first, second)
+
+
+class BaseContainerIterator(SimpleIteratorType):
+ """
+ Convenience base class for some container iterators.
+
+ Derived classes must implement the *container_class* attribute.
+ """
+
+ def __init__(self, container):
+ assert isinstance(container, self.container_class), container
+ self.container = container
+ yield_type = container.dtype
+ name = "iter(%s)" % container
+ super(BaseContainerIterator, self).__init__(name, yield_type)
+
+ def unify(self, typingctx, other):
+ cls = type(self)
+ if isinstance(other, cls):
+ container = typingctx.unify_pairs(self.container, other.container)
+ if container is not None:
+ return cls(container)
+
+ @property
+ def key(self):
+ return self.container
+
+
+class BaseContainerPayload(Type):
+ """
+ Convenience base class for some container payloads.
+
+ Derived classes must implement the *container_class* attribute.
+ """
+
+ def __init__(self, container):
+ assert isinstance(container, self.container_class)
+ self.container = container
+ name = "payload(%s)" % container
+ super(BaseContainerPayload, self).__init__(name)
+
+ @property
+ def key(self):
+ return self.container
+
+
+class Bytes(Buffer):
+ """
+ Type class for Python 3.x bytes objects.
+ """
+
+ mutable = False
+ # Actually true but doesn't matter since bytes is immutable
+ slice_is_copy = False
+
+
+class ByteArray(Buffer):
+ """
+ Type class for bytearray objects.
+ """
+
+ slice_is_copy = True
+
+
+class PyArray(Buffer):
+ """
+ Type class for array.array objects.
+ """
+
+ slice_is_copy = True
+
+
+class MemoryView(Buffer):
+ """
+ Type class for memoryview objects.
+ """
+
+
+def is_homogeneous(*tys):
+ """Are the types homogeneous?
+ """
+ if tys:
+ first, tys = tys[0], tys[1:]
+ return not any(t != first for t in tys)
+ else:
+ # *tys* is empty.
+ return False
+
+
+class BaseTuple(ConstSized, Hashable):
+ """
+ The base class for all tuple types (with a known size).
+ """
+
+ @classmethod
+ def from_types(cls, tys, pyclass=None):
+ """
+ Instantiate the right tuple type for the given element types.
+ """
+ if pyclass is not None and pyclass is not tuple:
+ # A subclass => is it a namedtuple?
+ assert issubclass(pyclass, tuple)
+ if hasattr(pyclass, "_asdict"):
+ tys = tuple(map(unliteral, tys))
+ homogeneous = is_homogeneous(*tys)
+ if homogeneous:
+ return NamedUniTuple(tys[0], len(tys), pyclass)
+ else:
+ return NamedTuple(tys, pyclass)
+ else:
+ dtype = utils.unified_function_type(tys)
+ if dtype is not None:
+ return UniTuple(dtype, len(tys))
+ # non-named tuple
+ homogeneous = is_homogeneous(*tys)
+ if homogeneous:
+ return cls._make_homogeneous_tuple(tys[0], len(tys))
+ else:
+ return cls._make_heterogeneous_tuple(tys)
+
+ @classmethod
+ def _make_homogeneous_tuple(cls, dtype, count):
+ return UniTuple(dtype, count)
+
+ @classmethod
+ def _make_heterogeneous_tuple(cls, tys):
+ return Tuple(tys)
+
+
+class BaseAnonymousTuple(BaseTuple):
+ """
+ Mixin for non-named tuples.
+ """
+
+ def can_convert_to(self, typingctx, other):
+ """
+ Convert this tuple to another one. Note named tuples are rejected.
+ """
+ if not isinstance(other, BaseAnonymousTuple):
+ return
+ if len(self) != len(other):
+ return
+ if len(self) == 0:
+ return Conversion.safe
+ if isinstance(other, BaseTuple):
+ kinds = [
+ typingctx.can_convert(ta, tb) for ta, tb in zip(self, other)
+ ]
+ if any(kind is None for kind in kinds):
+ return
+ return max(kinds)
+
+ def __unliteral__(self):
+ return type(self).from_types([unliteral(t) for t in self])
+
+
+class _HomogeneousTuple(Sequence, BaseTuple):
+ @property
+ def iterator_type(self):
+ return UniTupleIter(self)
+
+ def __getitem__(self, i):
+ """
+ Return element at position i
+ """
+ return self.dtype
+
+ def __iter__(self):
+ return iter([self.dtype] * self.count)
+
+ def __len__(self):
+ return self.count
+
+ @property
+ def types(self):
+ return (self.dtype,) * self.count
+
+
+class UniTuple(BaseAnonymousTuple, _HomogeneousTuple, Sequence):
+ """
+ Type class for homogeneous tuples.
+ """
+
+ def __init__(self, dtype, count):
+ self.dtype = dtype
+ self.count = count
+ name = "%s(%s x %d)" % (self.__class__.__name__, dtype, count,)
+ super(UniTuple, self).__init__(name)
+
+ @property
+ def mangling_args(self):
+ return self.__class__.__name__, (self.dtype, self.count)
+
+ @property
+ def key(self):
+ return self.dtype, self.count
+
+ def unify(self, typingctx, other):
+ """
+ Unify UniTuples with their dtype
+ """
+ if isinstance(other, UniTuple) and len(self) == len(other):
+ dtype = typingctx.unify_pairs(self.dtype, other.dtype)
+ if dtype is not None:
+ return UniTuple(dtype=dtype, count=self.count)
+
+ def __unliteral__(self):
+ return type(self)(dtype=unliteral(self.dtype), count=self.count)
+
+ def __repr__(self):
+ return f"UniTuple({repr(self.dtype)}, {self.count})"
+
+
+class UniTupleIter(BaseContainerIterator):
+ """
+ Type class for homogeneous tuple iterators.
+ """
+
+ container_class = _HomogeneousTuple
+
+
+class _HeterogeneousTuple(BaseTuple):
+ def __getitem__(self, i):
+ """
+ Return element at position i
+ """
+ return self.types[i]
+
+ def __len__(self):
+ # Beware: this makes Tuple(()) false-ish
+ return len(self.types)
+
+ def __iter__(self):
+ return iter(self.types)
+
+ @staticmethod
+ def is_types_iterable(types):
+ # issue 4463 - check if argument 'types' is iterable
+ if not isinstance(types, Iterable):
+ raise TypingError("Argument 'types' is not iterable")
+
+
+class UnionType(Type):
+ def __init__(self, types):
+ self.types = tuple(sorted(set(types), key=lambda x: x.name))
+ name = "Union[{}]".format(",".join(map(str, self.types)))
+ super(UnionType, self).__init__(name=name)
+
+ def get_type_tag(self, typ):
+ return self.types.index(typ)
+
+
+class Tuple(BaseAnonymousTuple, _HeterogeneousTuple):
+ def __new__(cls, types):
+
+ t = utils.unified_function_type(types, require_precise=True)
+ if t is not None:
+ return UniTuple(dtype=t, count=len(types))
+
+ _HeterogeneousTuple.is_types_iterable(types)
+
+ if types and all(t == types[0] for t in types[1:]):
+ return UniTuple(dtype=types[0], count=len(types))
+ else:
+ return object.__new__(Tuple)
+
+ def __init__(self, types):
+ self.types = tuple(types)
+ self.count = len(self.types)
+ self.dtype = UnionType(types)
+ name = "%s(%s)" % (
+ self.__class__.__name__,
+ ", ".join(str(i) for i in self.types),
+ )
+ super(Tuple, self).__init__(name)
+
+ @property
+ def mangling_args(self):
+ return self.__class__.__name__, tuple(t for t in self.types)
+
+ @property
+ def key(self):
+ return self.types
+
+ def unify(self, typingctx, other):
+ """
+ Unify elements of Tuples/UniTuples
+ """
+ # Other is UniTuple or Tuple
+ if isinstance(other, BaseTuple) and len(self) == len(other):
+ unified = [
+ typingctx.unify_pairs(ta, tb) for ta, tb in zip(self, other)
+ ]
+
+ if all(t is not None for t in unified):
+ return Tuple(unified)
+
+ def __repr__(self):
+ return f"Tuple({tuple(ty for ty in self.types)})"
+
+
+class _StarArgTupleMixin:
+ @classmethod
+ def _make_homogeneous_tuple(cls, dtype, count):
+ return StarArgUniTuple(dtype, count)
+
+ @classmethod
+ def _make_heterogeneous_tuple(cls, tys):
+ return StarArgTuple(tys)
+
+
+class StarArgTuple(_StarArgTupleMixin, Tuple):
+ """To distinguish from Tuple() used as argument to a `*args`.
+ """
+
+ def __new__(cls, types):
+ _HeterogeneousTuple.is_types_iterable(types)
+
+ if types and all(t == types[0] for t in types[1:]):
+ return StarArgUniTuple(dtype=types[0], count=len(types))
+ else:
+ return object.__new__(StarArgTuple)
+
+
+class StarArgUniTuple(_StarArgTupleMixin, UniTuple):
+ """To distinguish from UniTuple() used as argument to a `*args`.
+ """
+
+
+class BaseNamedTuple(BaseTuple):
+ pass
+
+
+class NamedUniTuple(_HomogeneousTuple, BaseNamedTuple):
+ def __init__(self, dtype, count, cls):
+ self.dtype = dtype
+ self.count = count
+ self.fields = tuple(cls._fields)
+ self.instance_class = cls
+ name = "%s(%s x %d)" % (cls.__name__, dtype, count)
+ super(NamedUniTuple, self).__init__(name)
+
+ @property
+ def iterator_type(self):
+ return UniTupleIter(self)
+
+ @property
+ def key(self):
+ return self.instance_class, self.dtype, self.count
+
+
+class NamedTuple(_HeterogeneousTuple, BaseNamedTuple):
+ def __init__(self, types, cls):
+ _HeterogeneousTuple.is_types_iterable(types)
+
+ self.types = tuple(types)
+ self.count = len(self.types)
+ self.fields = tuple(cls._fields)
+ self.instance_class = cls
+ name = "%s(%s)" % (cls.__name__, ", ".join(str(i) for i in self.types))
+ super(NamedTuple, self).__init__(name)
+
+ @property
+ def key(self):
+ return self.instance_class, self.types
+
+
+class List(MutableSequence, InitialValue):
+ """
+ Type class for (arbitrary-sized) homogeneous lists.
+ """
+
+ def __init__(self, dtype, reflected=False, initial_value=None):
+ dtype = unliteral(dtype)
+ self.dtype = dtype
+ self.reflected = reflected
+ cls_name = "reflected list" if reflected else "list"
+ name = "%s(%s)" % (cls_name, self.dtype, initial_value)
+ super(List, self).__init__(name=name)
+ InitialValue.__init__(self, initial_value)
+
+ def copy(self, dtype=None, reflected=None):
+ if dtype is None:
+ dtype = self.dtype
+ if reflected is None:
+ reflected = self.reflected
+ return List(dtype, reflected, self.initial_value)
+
+ def unify(self, typingctx, other):
+ if isinstance(other, List):
+ dtype = typingctx.unify_pairs(self.dtype, other.dtype)
+ reflected = self.reflected or other.reflected
+ if dtype is not None:
+ siv = self.initial_value
+ oiv = other.initial_value
+ if siv is not None and oiv is not None:
+ use = siv
+ if siv is None:
+ use = oiv
+ return List(dtype, reflected, use)
+ else:
+ return List(dtype, reflected)
+
+ @property
+ def key(self):
+ return self.dtype, self.reflected, str(self.initial_value)
+
+ @property
+ def iterator_type(self):
+ return ListIter(self)
+
+ def is_precise(self):
+ return self.dtype.is_precise()
+
+ def __getitem__(self, args):
+ """
+ Overrides the default __getitem__ from Type.
+ """
+ return self.dtype
+
+ def __unliteral__(self):
+ return List(self.dtype, reflected=self.reflected,
+ initial_value=None)
+
+ def __repr__(self):
+ return f"List({self.dtype}, {self.reflected})"
+
+
+class LiteralList(Literal, ConstSized, Hashable):
+ """A heterogeneous immutable list (basically a tuple with list semantics).
+ """
+
+ mutable = False
+
+ def __init__(self, literal_value):
+ self.is_types_iterable(literal_value)
+ self._literal_init(list(literal_value))
+ self.types = tuple(literal_value)
+ self.count = len(self.types)
+ self.name = "LiteralList({})".format(literal_value)
+
+ def __getitem__(self, i):
+ """
+ Return element at position i
+ """
+ return self.types[i]
+
+ def __len__(self):
+ return len(self.types)
+
+ def __iter__(self):
+ return iter(self.types)
+
+ @classmethod
+ def from_types(cls, tys):
+ return LiteralList(tys)
+
+ @staticmethod
+ def is_types_iterable(types):
+ if not isinstance(types, Iterable):
+ raise TypingError("Argument 'types' is not iterable")
+
+ @property
+ def iterator_type(self):
+ return ListIter(self)
+
+ def __unliteral__(self):
+ return Poison(self)
+
+ def unify(self, typingctx, other):
+ """
+ Unify this with the *other* one.
+ """
+ if isinstance(other, LiteralList) and self.count == other.count:
+ tys = []
+ for i1, i2 in zip(self.types, other.types):
+ tys.append(typingctx.unify_pairs(i1, i2))
+ if all(tys):
+ return LiteralList(tys)
+
+
+class ListIter(BaseContainerIterator):
+ """
+ Type class for list iterators.
+ """
+
+ container_class = List
+
+
+class ListPayload(BaseContainerPayload):
+ """
+ Internal type class for the dynamically-allocated payload of a list.
+ """
+
+ container_class = List
+
+
+class Set(Container):
+ """
+ Type class for homogeneous sets.
+ """
+
+ mutable = True
+
+ def __init__(self, dtype, reflected=False):
+ assert isinstance(dtype, (Hashable, Undefined))
+ self.dtype = dtype
+ self.reflected = reflected
+ cls_name = "reflected set" if reflected else "set"
+ name = "%s(%s)" % (cls_name, self.dtype)
+ super(Set, self).__init__(name=name)
+
+ @property
+ def key(self):
+ return self.dtype, self.reflected
+
+ @property
+ def iterator_type(self):
+ return SetIter(self)
+
+ def is_precise(self):
+ return self.dtype.is_precise()
+
+ def copy(self, dtype=None, reflected=None):
+ if dtype is None:
+ dtype = self.dtype
+ if reflected is None:
+ reflected = self.reflected
+ return Set(dtype, reflected)
+
+ def unify(self, typingctx, other):
+ if isinstance(other, Set):
+ dtype = typingctx.unify_pairs(self.dtype, other.dtype)
+ reflected = self.reflected or other.reflected
+ if dtype is not None:
+ return Set(dtype, reflected)
+
+ def __repr__(self):
+ return f"Set({self.dtype}, {self.reflected})"
+
+
+class SetIter(BaseContainerIterator):
+ """
+ Type class for set iterators.
+ """
+
+ container_class = Set
+
+
+class SetPayload(BaseContainerPayload):
+ """
+ Internal type class for the dynamically-allocated payload of a set.
+ """
+
+ container_class = Set
+
+
+class SetEntry(Type):
+ """
+ Internal type class for the entries of a Set's hash table.
+ """
+
+ def __init__(self, set_type):
+ self.set_type = set_type
+ name = "entry(%s)" % set_type
+ super(SetEntry, self).__init__(name)
+
+ @property
+ def key(self):
+ return self.set_type
+
+
+class ListType(IterableType):
+ """List type
+ """
+
+ mutable = True
+
+ def __init__(self, itemty):
+ assert not isinstance(itemty, TypeRef)
+ itemty = unliteral(itemty)
+ if isinstance(itemty, Optional):
+ fmt = "List.item_type cannot be of type {}"
+ raise TypingError(fmt.format(itemty))
+ # FIXME: _sentry_forbidden_types(itemty)
+ self.item_type = itemty
+ self.dtype = itemty
+ name = "{}[{}]".format(self.__class__.__name__, itemty,)
+ super(ListType, self).__init__(name)
+
+ @property
+ def key(self):
+ return self.item_type
+
+ def is_precise(self):
+ return not isinstance(self.item_type, Undefined)
+
+ @property
+ def iterator_type(self):
+ return ListTypeIterableType(self).iterator_type
+
+ @classmethod
+ def refine(cls, itemty):
+ """Refine to a precise list type
+ """
+ res = cls(itemty)
+ assert res.is_precise()
+ return res
+
+ def unify(self, typingctx, other):
+ """
+ Unify this with the *other* list.
+ """
+ # If other is list
+ if isinstance(other, ListType):
+ if not other.is_precise():
+ return self
+
+ def __repr__(self):
+ return f"ListType({self.item_type})"
+
+
+class ListTypeIterableType(SimpleIterableType):
+ """List iterable type
+ """
+
+ def __init__(self, parent):
+ assert isinstance(parent, ListType)
+ self.parent = parent
+ self.yield_type = self.parent.item_type
+ name = "list[{}]".format(self.parent.name)
+ iterator_type = ListTypeIteratorType(self)
+ super(ListTypeIterableType, self).__init__(name, iterator_type)
+
+
+class ListTypeIteratorType(SimpleIteratorType):
+ def __init__(self, iterable):
+ self.parent = iterable.parent
+ self.iterable = iterable
+ yield_type = iterable.yield_type
+ name = "iter[{}->{}]".format(iterable.parent, yield_type)
+ super(ListTypeIteratorType, self).__init__(name, yield_type)
+
+
+def _sentry_forbidden_types(key, value):
+ # Forbids List and Set for now
+ if isinstance(key, (Set, List)):
+ raise TypingError("{} as key is forbidden".format(key))
+ if isinstance(value, (Set, List)):
+ raise TypingError("{} as value is forbidden".format(value))
+
+
+class DictType(IterableType, InitialValue):
+ """Dictionary type
+ """
+
+ def __init__(self, keyty, valty, initial_value=None):
+ assert not isinstance(keyty, TypeRef)
+ assert not isinstance(valty, TypeRef)
+ keyty = unliteral(keyty)
+ valty = unliteral(valty)
+ if isinstance(keyty, (Optional, NoneType)):
+ fmt = "Dict.key_type cannot be of type {}"
+ raise TypingError(fmt.format(keyty))
+ if isinstance(valty, (Optional, NoneType)):
+ fmt = "Dict.value_type cannot be of type {}"
+ raise TypingError(fmt.format(valty))
+ _sentry_forbidden_types(keyty, valty)
+ self.key_type = keyty
+ self.value_type = valty
+ self.keyvalue_type = Tuple([keyty, valty])
+ name = "{}[{},{}]".format(
+ self.__class__.__name__, keyty, valty, initial_value
+ )
+ super(DictType, self).__init__(name)
+ InitialValue.__init__(self, initial_value)
+
+ def is_precise(self):
+ return not any(
+ (
+ isinstance(self.key_type, Undefined),
+ isinstance(self.value_type, Undefined),
+ )
+ )
+
+ @property
+ def iterator_type(self):
+ return DictKeysIterableType(self).iterator_type
+
+ @classmethod
+ def refine(cls, keyty, valty):
+ """Refine to a precise dictionary type
+ """
+ res = cls(keyty, valty)
+ assert res.is_precise()
+ return res
+
+ def unify(self, typingctx, other):
+ """
+ Unify this with the *other* dictionary.
+ """
+ # If other is dict
+ if isinstance(other, DictType):
+ if not other.is_precise():
+ return self
+ else:
+ ukey_type = self.key_type == other.key_type
+ uvalue_type = self.value_type == other.value_type
+ if ukey_type and uvalue_type:
+ siv = self.initial_value
+ oiv = other.initial_value
+ siv_none = siv is None
+ oiv_none = oiv is None
+ if not siv_none and not oiv_none:
+ if siv == oiv:
+ return DictType(self.key_type, other.value_type,
+ siv)
+ return DictType(self.key_type, other.value_type)
+
+ @property
+ def key(self):
+ return self.key_type, self.value_type, str(self.initial_value)
+
+ def __unliteral__(self):
+ return DictType(self.key_type, self.value_type)
+
+ def __repr__(self):
+ return f"DictType({self.key_type}, {self.value_type})"
+
+
+class LiteralStrKeyDict(Literal, ConstSized, Hashable):
+ """A Dictionary of string keys to heterogeneous values (basically a
+ namedtuple with dict semantics).
+ """
+
+ class FakeNamedTuple(pySequence):
+ # This is namedtuple-like and is a workaround for #6518 and #7416.
+ # This has the couple of namedtuple properties that are used by Numba's
+ # internals but avoids use of an actual namedtuple as it cannot have
+ # numeric field names, i.e. `namedtuple('foo', '0 1')` is invalid.
+ def __init__(self, name, keys):
+ self.__name__ = name
+ self._fields = tuple(keys)
+ super(LiteralStrKeyDict.FakeNamedTuple, self).__init__()
+
+ def __len__(self):
+ return len(self._fields)
+
+ def __getitem__(self, key):
+ return self._fields[key]
+
+ mutable = False
+
+ def __init__(self, literal_value, value_index=None):
+ self._literal_init(literal_value)
+ self.value_index = value_index
+ strkeys = [x.literal_value for x in literal_value.keys()]
+ self.tuple_ty = self.FakeNamedTuple("_ntclazz", strkeys)
+ tys = [x for x in literal_value.values()]
+ self.types = tuple(tys)
+ self.count = len(self.types)
+ self.fields = tuple(self.tuple_ty._fields)
+ self.instance_class = self.tuple_ty
+ self.name = "LiteralStrKey[Dict]({})".format(literal_value)
+
+ def __unliteral__(self):
+ return Poison(self)
+
+ def unify(self, typingctx, other):
+ """
+ Unify this with the *other* one.
+ """
+ if isinstance(other, LiteralStrKeyDict):
+ tys = []
+ for (k1, v1), (k2, v2) in zip(
+ self.literal_value.items(), other.literal_value.items()
+ ):
+ if k1 != k2: # keys must be same
+ break
+ tys.append(typingctx.unify_pairs(v1, v2))
+ else:
+ if all(tys):
+ d = {k: v for k, v in zip(self.literal_value.keys(), tys)}
+ return LiteralStrKeyDict(d)
+
+ def __len__(self):
+ return len(self.types)
+
+ def __iter__(self):
+ return iter(self.types)
+
+ @property
+ def key(self):
+ # use the namedtuple fields not the namedtuple itself as it's created
+ # locally in the ctor and comparison would always be False.
+ return self.tuple_ty._fields, self.types, str(self.literal_value)
+
+
+class DictItemsIterableType(SimpleIterableType):
+ """Dictionary iterable type for .items()
+ """
+
+ def __init__(self, parent):
+ assert isinstance(parent, DictType)
+ self.parent = parent
+ self.yield_type = self.parent.keyvalue_type
+ name = "items[{}]".format(self.parent.name)
+ self.name = name
+ iterator_type = DictIteratorType(self)
+ super(DictItemsIterableType, self).__init__(name, iterator_type)
+
+
+class DictKeysIterableType(SimpleIterableType):
+ """Dictionary iterable type for .keys()
+ """
+
+ def __init__(self, parent):
+ assert isinstance(parent, DictType)
+ self.parent = parent
+ self.yield_type = self.parent.key_type
+ name = "keys[{}]".format(self.parent.name)
+ self.name = name
+ iterator_type = DictIteratorType(self)
+ super(DictKeysIterableType, self).__init__(name, iterator_type)
+
+
+class DictValuesIterableType(SimpleIterableType):
+ """Dictionary iterable type for .values()
+ """
+
+ def __init__(self, parent):
+ assert isinstance(parent, DictType)
+ self.parent = parent
+ self.yield_type = self.parent.value_type
+ name = "values[{}]".format(self.parent.name)
+ self.name = name
+ iterator_type = DictIteratorType(self)
+ super(DictValuesIterableType, self).__init__(name, iterator_type)
+
+
+class DictIteratorType(SimpleIteratorType):
+ def __init__(self, iterable):
+ self.parent = iterable.parent
+ self.iterable = iterable
+ yield_type = iterable.yield_type
+ name = "iter[{}->{}],{}".format(
+ iterable.parent, yield_type, iterable.name
+ )
+ super(DictIteratorType, self).__init__(name, yield_type)
+
+
+class StructRef(Type):
+ """A mutable struct.
+ """
+
+ def __init__(self, fields):
+ """
+ Parameters
+ ----------
+ fields : Sequence
+ A sequence of field descriptions, which is a 2-tuple-like object
+ containing `(name, type)`, where `name` is a `str` for the field
+ name, and `type` is a numba type for the field type.
+ """
+
+ def check_field_pair(fieldpair):
+ name, typ = fieldpair
+ if not isinstance(name, str):
+ msg = "expecting a str for field name"
+ raise ValueError(msg)
+ if not isinstance(typ, Type):
+ msg = "expecting a Numba Type for field type"
+ raise ValueError(msg)
+ return name, typ
+
+ fields = tuple(map(check_field_pair, fields))
+ self._fields = tuple(map(check_field_pair,
+ self.preprocess_fields(fields)))
+ self._typename = self.__class__.__qualname__
+ name = f"numba.{self._typename}{self._fields}"
+ super().__init__(name=name)
+
+ def preprocess_fields(self, fields):
+ """Subclasses can override this to do additional clean up on fields.
+
+ The default is an identity function.
+
+ Parameters:
+ -----------
+ fields : Sequence[Tuple[str, Type]]
+ """
+ return fields
+
+ @property
+ def field_dict(self):
+ """Return an immutable mapping for the field names and their
+ corresponding types.
+ """
+ return MappingProxyType(dict(self._fields))
+
+ def get_data_type(self):
+ """Get the payload type for the actual underlying structure referred
+ to by this struct reference.
+
+ See also: `ClassInstanceType.get_data_type`
+ """
+ return StructRefPayload(
+ typename=self.__class__.__name__, fields=self._fields,
+ )
+
+
+class StructRefPayload(Type):
+ """The type of the payload of a mutable struct.
+ """
+
+ mutable = True
+
+ def __init__(self, typename, fields):
+ self._typename = typename
+ self._fields = tuple(fields)
+ super().__init__(name=f"numba.{typename}{self._fields}.payload")
+
+ @property
+ def field_dict(self):
+ return MappingProxyType(dict(self._fields))
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/function_type.py b/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/function_type.py
new file mode 100644
index 0000000000000000000000000000000000000000..7dffd195b5621d4d3460b8d329061dfd6d624f5b
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/function_type.py
@@ -0,0 +1,211 @@
+
+__all__ = ['FunctionType', 'UndefinedFunctionType', 'FunctionPrototype',
+ 'WrapperAddressProtocol', 'CompileResultWAP']
+
+from abc import ABC, abstractmethod
+from .abstract import Type
+from .. import types, errors
+
+
+class FunctionType(Type):
+ """
+ First-class function type.
+ """
+
+ cconv = None
+
+ def __init__(self, signature):
+ sig = types.unliteral(signature)
+ self.nargs = len(sig.args)
+ self.signature = sig
+ self.ftype = FunctionPrototype(sig.return_type, sig.args)
+ self._key = self.ftype.key
+
+ @property
+ def key(self):
+ return self._key
+
+ @property
+ def name(self):
+ return f'{type(self).__name__}[{self.key}]'
+
+ def is_precise(self):
+ return self.signature.is_precise()
+
+ def get_precise(self):
+ return self
+
+ def dump(self, tab=''):
+ print(f'{tab}DUMP {type(self).__name__}[code={self._code}]')
+ self.signature.dump(tab=tab + ' ')
+ print(f'{tab}END DUMP {type(self).__name__}')
+
+ def get_call_type(self, context, args, kws):
+ from numba.core import typing
+
+ if kws:
+ # First-class functions carry only the type signature
+ # information and function address value. So, it is not
+ # possible to determine the positional arguments
+ # corresponding to the keyword arguments in the call
+ # expression. For instance, the definition of the
+ # first-class function may not use the same argument names
+ # that the caller assumes. [numba/issues/5540].
+ raise errors.UnsupportedError(
+ 'first-class function call cannot use keyword arguments')
+
+ if len(args) != self.nargs:
+ raise ValueError(
+ f'mismatch of arguments number: {len(args)} vs {self.nargs}')
+
+ sig = self.signature
+
+ # check that arguments types match with the signature types exactly
+ for atype, sig_atype in zip(args, sig.args):
+ atype = types.unliteral(atype)
+ if sig_atype.is_precise():
+ conv_score = context.context.can_convert(
+ fromty=atype, toty=sig_atype
+ )
+ if conv_score is None \
+ or conv_score > typing.context.Conversion.safe:
+ raise ValueError(
+ f'mismatch of argument types: {atype} vs {sig_atype}')
+
+ if not sig.is_precise():
+ for dispatcher in self.dispatchers:
+ template, pysig, args, kws \
+ = dispatcher.get_call_template(args, kws)
+ new_sig = template(context.context).apply(args, kws)
+ return types.unliteral(new_sig)
+
+ return sig
+
+ def check_signature(self, other_sig):
+ """Return True if signatures match (up to being precise).
+ """
+ sig = self.signature
+ return (self.nargs == len(other_sig.args)
+ and (sig == other_sig or not sig.is_precise()))
+
+ def unify(self, context, other):
+ if isinstance(other, types.UndefinedFunctionType) \
+ and self.nargs == other.nargs:
+ return self
+
+
+class UndefinedFunctionType(FunctionType):
+
+ _counter = 0
+
+ def __init__(self, nargs, dispatchers):
+ from numba.core.typing.templates import Signature
+ signature = Signature(types.undefined,
+ (types.undefined,) * nargs, recvr=None)
+
+ super(UndefinedFunctionType, self).__init__(signature)
+
+ self.dispatchers = dispatchers
+
+ # make the undefined function type instance unique
+ type(self)._counter += 1
+ self._key += str(type(self)._counter)
+
+ def get_precise(self):
+ """
+ Return precise function type if possible.
+ """
+ for dispatcher in self.dispatchers:
+ for cres in dispatcher.overloads.values():
+ sig = types.unliteral(cres.signature)
+ return FunctionType(sig)
+ return self
+
+
+class FunctionPrototype(Type):
+ """
+ Represents the prototype of a first-class function type.
+ Used internally.
+ """
+ cconv = None
+
+ def __init__(self, rtype, atypes):
+ self.rtype = rtype
+ self.atypes = tuple(atypes)
+
+ assert isinstance(rtype, Type), (rtype)
+ lst = []
+ for atype in self.atypes:
+ assert isinstance(atype, Type), (atype)
+ lst.append(atype.name)
+ name = '%s(%s)' % (rtype, ', '.join(lst))
+
+ super(FunctionPrototype, self).__init__(name)
+
+ @property
+ def key(self):
+ return self.name
+
+
+class WrapperAddressProtocol(ABC):
+ """Base class for Wrapper Address Protocol.
+
+ Objects that inherit from the WrapperAddressProtocol can be passed
+ as arguments to Numba jit compiled functions where it can be used
+ as first-class functions. As a minimum, the derived types must
+ implement two methods ``__wrapper_address__`` and ``signature``.
+ """
+
+ @abstractmethod
+ def __wrapper_address__(self):
+ """Return the address of a first-class function.
+
+ Returns
+ -------
+ addr : int
+ """
+
+ @abstractmethod
+ def signature(self):
+ """Return the signature of a first-class function.
+
+ Returns
+ -------
+ sig : Signature
+ The returned Signature instance represents the type of a
+ first-class function that the given WrapperAddressProtocol
+ instance represents.
+ """
+
+
+class CompileResultWAP(WrapperAddressProtocol):
+ """Wrapper of dispatcher instance compilation result to turn it a
+ first-class function.
+ """
+
+ def __init__(self, cres):
+ """
+ Parameters
+ ----------
+ cres : CompileResult
+ Specify compilation result of a Numba jit-decorated function
+ (that is a value of dispatcher instance ``overloads``
+ attribute)
+ """
+ self.cres = cres
+ name = getattr(cres.fndesc, 'llvm_cfunc_wrapper_name')
+ self.address = cres.library.get_pointer_to_function(name)
+
+ def dump(self, tab=''):
+ print(f'{tab}DUMP {type(self).__name__} [addr={self.address}]')
+ self.cres.signature.dump(tab=tab + ' ')
+ print(f'{tab}END DUMP {type(self).__name__}')
+
+ def __wrapper_address__(self):
+ return self.address
+
+ def signature(self):
+ return self.cres.signature
+
+ def __call__(self, *args, **kwargs): # used in object-mode
+ return self.cres.entry_point(*args, **kwargs)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/functions.py b/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/functions.py
new file mode 100644
index 0000000000000000000000000000000000000000..3d17bd9f7739d6aace270adfb9a03daaa0978426
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/functions.py
@@ -0,0 +1,743 @@
+import traceback
+from collections import namedtuple, defaultdict
+import itertools
+import logging
+import textwrap
+from shutil import get_terminal_size
+
+from .abstract import Callable, DTypeSpec, Dummy, Literal, Type, weakref
+from .common import Opaque
+from .misc import unliteral
+from numba.core import errors, utils, types, config
+from numba.core.typeconv import Conversion
+
+_logger = logging.getLogger(__name__)
+
+
+# terminal color markup
+_termcolor = errors.termcolor()
+
+_FAILURE = namedtuple('_FAILURE', 'template matched error literal')
+
+_termwidth = get_terminal_size().columns
+
+
+# pull out the lead line as unit tests often use this
+_header_lead = "No implementation of function"
+_header_template = (_header_lead + " {the_function} found for signature:\n \n "
+ ">>> {fname}({signature})\n \nThere are {ncandidates} "
+ "candidate implementations:")
+
+_reason_template = """
+" - Of which {nmatches} did not match due to:\n
+"""
+
+
+def _wrapper(tmp, indent=0):
+ return textwrap.indent(tmp, ' ' * indent, lambda line: True)
+
+
+_overload_template = ("- Of which {nduplicates} did not match due to:\n"
+ "{kind} {inof} function '{function}': File: {file}: "
+ "Line {line}.\n With argument(s): '({args})':")
+
+
+_err_reasons = {'specific_error': "Rejected as the implementation raised a "
+ "specific error:\n{}"}
+
+
+def _bt_as_lines(bt):
+ """
+ Converts a backtrace into a list of lines, squashes it a bit on the way.
+ """
+ return [y for y in itertools.chain(*[x.split('\n') for x in bt]) if y]
+
+
+def argsnkwargs_to_str(args, kwargs):
+ buf = [str(a) for a in tuple(args)]
+ buf.extend(["{}={}".format(k, v) for k, v in kwargs.items()])
+ return ', '.join(buf)
+
+
+class _ResolutionFailures(object):
+ """Collect and format function resolution failures.
+ """
+ def __init__(self, context, function_type, args, kwargs, depth=0):
+ self._context = context
+ self._function_type = function_type
+ self._args = args
+ self._kwargs = kwargs
+ self._failures = defaultdict(list)
+ self._depth = depth
+ self._max_depth = 5
+ self._scale = 2
+
+ def __len__(self):
+ return len(self._failures)
+
+ def add_error(self, calltemplate, matched, error, literal):
+ """
+ Args
+ ----
+ calltemplate : CallTemplate
+ error : Exception or str
+ Error message
+ """
+ isexc = isinstance(error, Exception)
+ errclazz = '%s: ' % type(error).__name__ if isexc else ''
+
+ key = "{}{}".format(errclazz, str(error))
+ self._failures[key].append(_FAILURE(calltemplate, matched, error,
+ literal))
+
+ def format(self):
+ """Return a formatted error message from all the gathered errors.
+ """
+ indent = ' ' * self._scale
+ argstr = argsnkwargs_to_str(self._args, self._kwargs)
+ ncandidates = sum([len(x) for x in self._failures.values()])
+
+ # sort out a display name for the function
+ tykey = self._function_type.typing_key
+ # most things have __name__
+ fname = getattr(tykey, '__name__', None)
+ is_external_fn_ptr = isinstance(self._function_type,
+ ExternalFunctionPointer)
+
+ if fname is None:
+ if is_external_fn_ptr:
+ fname = "ExternalFunctionPointer"
+ else:
+ fname = ""
+
+ msgbuf = [_header_template.format(the_function=self._function_type,
+ fname=fname,
+ signature=argstr,
+ ncandidates=ncandidates)]
+ nolitargs = tuple([unliteral(a) for a in self._args])
+ nolitkwargs = {k: unliteral(v) for k, v in self._kwargs.items()}
+ nolitargstr = argsnkwargs_to_str(nolitargs, nolitkwargs)
+
+ # depth could potentially get massive, so limit it.
+ ldepth = min(max(self._depth, 0), self._max_depth)
+
+ def template_info(tp):
+ src_info = tp.get_template_info()
+ unknown = "unknown"
+ source_name = src_info.get('name', unknown)
+ source_file = src_info.get('filename', unknown)
+ source_lines = src_info.get('lines', unknown)
+ source_kind = src_info.get('kind', 'Unknown template')
+ return source_name, source_file, source_lines, source_kind
+
+ for i, (k, err_list) in enumerate(self._failures.items()):
+ err = err_list[0]
+ nduplicates = len(err_list)
+ template, error = err.template, err.error
+ ifo = template_info(template)
+ source_name, source_file, source_lines, source_kind = ifo
+ largstr = argstr if err.literal else nolitargstr
+
+ if err.error == "No match.":
+ err_dict = defaultdict(set)
+ for errs in err_list:
+ err_dict[errs.template].add(errs.literal)
+ # if there's just one template, and it's erroring on
+ # literal/nonliteral be specific
+ if len(err_dict) == 1:
+ template = [_ for _ in err_dict.keys()][0]
+ source_name, source_file, source_lines, source_kind = \
+ template_info(template)
+ source_lines = source_lines[0]
+ else:
+ source_file = ""
+ source_lines = "N/A"
+
+ msgbuf.append(_termcolor.errmsg(
+ _wrapper(_overload_template.format(nduplicates=nduplicates,
+ kind=source_kind.title(),
+ function=fname,
+ inof='of',
+ file=source_file,
+ line=source_lines,
+ args=largstr),
+ ldepth + 1)))
+ msgbuf.append(_termcolor.highlight(_wrapper(err.error,
+ ldepth + 2)))
+ else:
+ # There was at least one match in this failure class, but it
+ # failed for a specific reason try and report this.
+ msgbuf.append(_termcolor.errmsg(
+ _wrapper(_overload_template.format(nduplicates=nduplicates,
+ kind=source_kind.title(),
+ function=source_name,
+ inof='in',
+ file=source_file,
+ line=source_lines[0],
+ args=largstr),
+ ldepth + 1)))
+
+ if isinstance(error, BaseException):
+ reason = indent + self.format_error(error)
+ errstr = _err_reasons['specific_error'].format(reason)
+ else:
+ errstr = error
+ # if you are a developer, show the back traces
+ if config.DEVELOPER_MODE:
+ if isinstance(error, BaseException):
+ # if the error is an actual exception instance, trace it
+ bt = traceback.format_exception(type(error), error,
+ error.__traceback__)
+ else:
+ bt = [""]
+ bt_as_lines = _bt_as_lines(bt)
+ nd2indent = '\n{}'.format(2 * indent)
+ errstr += _termcolor.reset(nd2indent +
+ nd2indent.join(bt_as_lines))
+ msgbuf.append(_termcolor.highlight(_wrapper(errstr,
+ ldepth + 2)))
+ loc = self.get_loc(template, error)
+ if loc:
+ msgbuf.append('{}raised from {}'.format(indent, loc))
+
+ # the commented bit rewraps each block, may not be helpful?!
+ return _wrapper('\n'.join(msgbuf) + '\n') # , self._scale * ldepth)
+
+ def format_error(self, error):
+ """Format error message or exception
+ """
+ if isinstance(error, Exception):
+ return '{}: {}'.format(type(error).__name__, error)
+ else:
+ return '{}'.format(error)
+
+ def get_loc(self, classtemplate, error):
+ """Get source location information from the error message.
+ """
+ if isinstance(error, Exception) and hasattr(error, '__traceback__'):
+ # traceback is unavailable in py2
+ frame = traceback.extract_tb(error.__traceback__)[-1]
+ return "{}:{}".format(frame[0], frame[1])
+
+ def raise_error(self):
+ for faillist in self._failures.values():
+ for fail in faillist:
+ if isinstance(fail.error, errors.ForceLiteralArg):
+ raise fail.error
+ raise errors.TypingError(self.format())
+
+
+def _unlit_non_poison(ty):
+ """Apply unliteral(ty) and raise a TypingError if type is Poison.
+ """
+ out = unliteral(ty)
+ if isinstance(out, types.Poison):
+ m = f"Poison type used in arguments; got {out}"
+ raise errors.TypingError(m)
+ return out
+
+
+class BaseFunction(Callable):
+ """
+ Base type class for some function types.
+ """
+
+ def __init__(self, template):
+
+ if isinstance(template, (list, tuple)):
+ self.templates = tuple(template)
+ keys = set(temp.key for temp in self.templates)
+ if len(keys) != 1:
+ raise ValueError("incompatible templates: keys = %s"
+ % (keys,))
+ self.typing_key, = keys
+ else:
+ self.templates = (template,)
+ self.typing_key = template.key
+ self._impl_keys = {}
+ name = "%s(%s)" % (self.__class__.__name__, self.typing_key)
+ self._depth = 0
+ super(BaseFunction, self).__init__(name)
+
+ @property
+ def key(self):
+ return self.typing_key, self.templates
+
+ def augment(self, other):
+ """
+ Augment this function type with the other function types' templates,
+ so as to support more input types.
+ """
+ if type(other) is type(self) and other.typing_key == self.typing_key:
+ return type(self)(self.templates + other.templates)
+
+ def get_impl_key(self, sig):
+ """
+ Get the implementation key (used by the target context) for the
+ given signature.
+ """
+ return self._impl_keys[sig.args]
+
+ def get_call_type(self, context, args, kws):
+
+ prefer_lit = [True, False] # old behavior preferring literal
+ prefer_not = [False, True] # new behavior preferring non-literal
+ failures = _ResolutionFailures(context, self, args, kws,
+ depth=self._depth)
+
+ # get the order in which to try templates
+ from numba.core.target_extension import get_local_target # circular
+ target_hw = get_local_target(context)
+ order = utils.order_by_target_specificity(target_hw, self.templates,
+ fnkey=self.key[0])
+
+ self._depth += 1
+
+ for temp_cls in order:
+ temp = temp_cls(context)
+ # The template can override the default and prefer literal args
+ choice = prefer_lit if temp.prefer_literal else prefer_not
+ for uselit in choice:
+ try:
+ if uselit:
+ sig = temp.apply(args, kws)
+ else:
+ nolitargs = tuple([_unlit_non_poison(a) for a in args])
+ nolitkws = {k: _unlit_non_poison(v)
+ for k, v in kws.items()}
+ sig = temp.apply(nolitargs, nolitkws)
+ except Exception as e:
+ if not isinstance(e, errors.NumbaError):
+ raise e
+ sig = None
+ failures.add_error(temp, False, e, uselit)
+ else:
+ if sig is not None:
+ self._impl_keys[sig.args] = temp.get_impl_key(sig)
+ self._depth -= 1
+ return sig
+ else:
+ registered_sigs = getattr(temp, 'cases', None)
+ if registered_sigs is not None:
+ msg = "No match for registered cases:\n%s"
+ msg = msg % '\n'.join(" * {}".format(x) for x in
+ registered_sigs)
+ else:
+ msg = 'No match.'
+ failures.add_error(temp, True, msg, uselit)
+
+ failures.raise_error()
+
+ def get_call_signatures(self):
+ sigs = []
+ is_param = False
+ for temp in self.templates:
+ sigs += getattr(temp, 'cases', [])
+ is_param = is_param or hasattr(temp, 'generic')
+ return sigs, is_param
+
+
+class Function(BaseFunction, Opaque):
+ """
+ Type class for builtin functions implemented by Numba.
+ """
+
+
+class BoundFunction(Callable, Opaque):
+ """
+ A function with an implicit first argument (denoted as *this* below).
+ """
+
+ def __init__(self, template, this):
+ # Create a derived template with an attribute *this*
+ newcls = type(template.__name__ + '.' + str(this), (template,),
+ dict(this=this))
+ self.template = newcls
+ self.typing_key = self.template.key
+ self.this = this
+ name = "%s(%s for %s)" % (self.__class__.__name__,
+ self.typing_key, self.this)
+ super(BoundFunction, self).__init__(name)
+
+ def unify(self, typingctx, other):
+ if (isinstance(other, BoundFunction) and
+ self.typing_key == other.typing_key):
+ this = typingctx.unify_pairs(self.this, other.this)
+ if this is not None:
+ # XXX is it right that both template instances are distinct?
+ return self.copy(this=this)
+
+ def copy(self, this):
+ return type(self)(self.template, this)
+
+ @property
+ def key(self):
+ # FIXME: With target-overload, the MethodTemplate can change depending
+ # on the target.
+ unique_impl = getattr(self.template, "_overload_func", None)
+ return self.typing_key, self.this, unique_impl
+
+ def get_impl_key(self, sig):
+ """
+ Get the implementation key (used by the target context) for the
+ given signature.
+ """
+ return self.typing_key
+
+ def get_call_type(self, context, args, kws):
+ template = self.template(context)
+ literal_e = None
+ nonliteral_e = None
+ out = None
+
+ choice = [True, False] if template.prefer_literal else [False, True]
+ for uselit in choice:
+ if uselit:
+ # Try with Literal
+ try:
+ out = template.apply(args, kws)
+ except Exception as exc:
+ if not isinstance(exc, errors.NumbaError):
+ raise exc
+ if isinstance(exc, errors.ForceLiteralArg):
+ raise exc
+ literal_e = exc
+ out = None
+ else:
+ break
+ else:
+ # if the unliteral_args and unliteral_kws are the same as the
+ # literal ones, set up to not bother retrying
+ unliteral_args = tuple([_unlit_non_poison(a) for a in args])
+ unliteral_kws = {k: _unlit_non_poison(v)
+ for k, v in kws.items()}
+ skip = unliteral_args == args and kws == unliteral_kws
+
+ # If the above template application failed and the non-literal
+ # args are different to the literal ones, try again with
+ # literals rewritten as non-literals
+ if not skip and out is None:
+ try:
+ out = template.apply(unliteral_args, unliteral_kws)
+ except Exception as exc:
+ if isinstance(exc, errors.ForceLiteralArg):
+ if template.prefer_literal:
+ # For template that prefers literal types,
+ # reaching here means that the literal types
+ # have failed typing as well.
+ raise exc
+ nonliteral_e = exc
+ else:
+ break
+
+ if out is None and (nonliteral_e is not None or literal_e is not None):
+ header = "- Resolution failure for {} arguments:\n{}\n"
+ tmplt = _termcolor.highlight(header)
+ if config.DEVELOPER_MODE:
+ indent = ' ' * 4
+
+ def add_bt(error):
+ if isinstance(error, BaseException):
+ # if the error is an actual exception instance, trace it
+ bt = traceback.format_exception(type(error), error,
+ error.__traceback__)
+ else:
+ bt = [""]
+ nd2indent = '\n{}'.format(2 * indent)
+ errstr = _termcolor.reset(nd2indent +
+ nd2indent.join(_bt_as_lines(bt)))
+ return _termcolor.reset(errstr)
+ else:
+ add_bt = lambda X: ''
+
+ def nested_msg(literalness, e):
+ estr = str(e)
+ estr = estr if estr else (str(repr(e)) + add_bt(e))
+ new_e = errors.TypingError(textwrap.dedent(estr))
+ return tmplt.format(literalness, str(new_e))
+
+ raise errors.TypingError(nested_msg('literal', literal_e) +
+ nested_msg('non-literal', nonliteral_e))
+ return out
+
+ def get_call_signatures(self):
+ sigs = getattr(self.template, 'cases', [])
+ is_param = hasattr(self.template, 'generic')
+ return sigs, is_param
+
+
+class MakeFunctionLiteral(Literal, Opaque):
+ pass
+
+
+class _PickleableWeakRef(weakref.ref):
+ """
+ Allow a weakref to be pickled.
+
+ Note that if the object referred to is not kept alive elsewhere in the
+ pickle, the weakref will immediately expire after being constructed.
+ """
+ def __getnewargs__(self):
+ obj = self()
+ if obj is None:
+ raise ReferenceError("underlying object has vanished")
+ return (obj,)
+
+
+class WeakType(Type):
+ """
+ Base class for types parametered by a mortal object, to which only
+ a weak reference is kept.
+ """
+
+ def _store_object(self, obj):
+ self._wr = _PickleableWeakRef(obj)
+
+ def _get_object(self):
+ obj = self._wr()
+ if obj is None:
+ raise ReferenceError("underlying object has vanished")
+ return obj
+
+ @property
+ def key(self):
+ return self._wr
+
+ def __eq__(self, other):
+ if type(self) is type(other):
+ obj = self._wr()
+ return obj is not None and obj is other._wr()
+ return NotImplemented
+
+ def __hash__(self):
+ return Type.__hash__(self)
+
+
+class Dispatcher(WeakType, Callable, Dummy):
+ """
+ Type class for @jit-compiled functions.
+ """
+
+ def __init__(self, dispatcher):
+ self._store_object(dispatcher)
+ super(Dispatcher, self).__init__("type(%s)" % dispatcher)
+
+ def dump(self, tab=''):
+ print((f'{tab}DUMP {type(self).__name__}[code={self._code}, '
+ f'name={self.name}]'))
+ self.dispatcher.dump(tab=tab + ' ')
+ print(f'{tab}END DUMP')
+
+ def get_call_type(self, context, args, kws):
+ """
+ Resolve a call to this dispatcher using the given argument types.
+ A signature returned and it is ensured that a compiled specialization
+ is available for it.
+ """
+ template, pysig, args, kws = \
+ self.dispatcher.get_call_template(args, kws)
+ sig = template(context).apply(args, kws)
+ if sig:
+ sig = sig.replace(pysig=pysig)
+ return sig
+
+ def get_call_signatures(self):
+ sigs = self.dispatcher.nopython_signatures
+ return sigs, True
+
+ @property
+ def dispatcher(self):
+ """
+ A strong reference to the underlying numba.dispatcher.Dispatcher
+ instance.
+ """
+ return self._get_object()
+
+ def get_overload(self, sig):
+ """
+ Get the compiled overload for the given signature.
+ """
+ return self.dispatcher.get_overload(sig.args)
+
+ def get_impl_key(self, sig):
+ """
+ Get the implementation key for the given signature.
+ """
+ return self.get_overload(sig)
+
+ def unify(self, context, other):
+ return utils.unified_function_type((self, other), require_precise=False)
+
+ def can_convert_to(self, typingctx, other):
+ if isinstance(other, types.FunctionType):
+ try:
+ self.dispatcher.get_compile_result(other.signature)
+ except errors.NumbaError:
+ return None
+ else:
+ return Conversion.safe
+
+
+class ObjModeDispatcher(Dispatcher):
+ """Dispatcher subclass that enters objectmode function.
+ """
+ pass
+
+
+class ExternalFunctionPointer(BaseFunction):
+ """
+ A pointer to a native function (e.g. exported via ctypes or cffi).
+ *get_pointer* is a Python function taking an object
+ and returning the raw pointer value as an int.
+ """
+ def __init__(self, sig, get_pointer, cconv=None):
+ from numba.core.typing.templates import (AbstractTemplate,
+ make_concrete_template,
+ signature)
+ from numba.core.types import ffi_forced_object
+ if sig.return_type == ffi_forced_object:
+ msg = "Cannot return a pyobject from an external function"
+ raise errors.TypingError(msg)
+ self.sig = sig
+ self.requires_gil = any(a == ffi_forced_object for a in self.sig.args)
+ self.get_pointer = get_pointer
+ self.cconv = cconv
+ if self.requires_gil:
+ class GilRequiringDefn(AbstractTemplate):
+ key = self.sig
+
+ def generic(self, args, kws):
+ if kws:
+ msg = "does not support keyword arguments"
+ raise errors.TypingError(msg)
+ # Make ffi_forced_object a bottom type to allow any type to
+ # be casted to it. This is the only place that support
+ # ffi_forced_object.
+ coerced = [actual if formal == ffi_forced_object else formal
+ for actual, formal
+ in zip(args, self.key.args)]
+ return signature(self.key.return_type, *coerced)
+ template = GilRequiringDefn
+ else:
+ template = make_concrete_template("CFuncPtr", sig, [sig])
+ super(ExternalFunctionPointer, self).__init__(template)
+
+ @property
+ def key(self):
+ return self.sig, self.cconv, self.get_pointer
+
+
+class ExternalFunction(Function):
+ """
+ A named native function (resolvable by LLVM) accepting an explicit
+ signature. For internal use only.
+ """
+
+ def __init__(self, symbol, sig):
+ from numba.core import typing
+ self.symbol = symbol
+ self.sig = sig
+ template = typing.make_concrete_template(symbol, symbol, [sig])
+ super(ExternalFunction, self).__init__(template)
+
+ @property
+ def key(self):
+ return self.symbol, self.sig
+
+
+class NamedTupleClass(Callable, Opaque):
+ """
+ Type class for namedtuple classes.
+ """
+
+ def __init__(self, instance_class):
+ self.instance_class = instance_class
+ name = "class(%s)" % (instance_class)
+ super(NamedTupleClass, self).__init__(name)
+
+ def get_call_type(self, context, args, kws):
+ # Overridden by the __call__ constructor resolution in
+ # typing.collections
+ return None
+
+ def get_call_signatures(self):
+ return (), True
+
+ def get_impl_key(self, sig):
+ return type(self)
+
+ @property
+ def key(self):
+ return self.instance_class
+
+
+class NumberClass(Callable, DTypeSpec, Opaque):
+ """
+ Type class for number classes (e.g. "np.float64").
+ """
+
+ def __init__(self, instance_type):
+ self.instance_type = instance_type
+ name = "class(%s)" % (instance_type,)
+ super(NumberClass, self).__init__(name)
+
+ def get_call_type(self, context, args, kws):
+ # Overridden by the __call__ constructor resolution in typing.builtins
+ return None
+
+ def get_call_signatures(self):
+ return (), True
+
+ def get_impl_key(self, sig):
+ return type(self)
+
+ @property
+ def key(self):
+ return self.instance_type
+
+ @property
+ def dtype(self):
+ return self.instance_type
+
+
+_RecursiveCallOverloads = namedtuple("_RecursiveCallOverloads", "qualname,uid")
+
+
+class RecursiveCall(Opaque):
+ """
+ Recursive call to a Dispatcher.
+ """
+ _overloads = None
+
+ def __init__(self, dispatcher_type):
+ assert isinstance(dispatcher_type, Dispatcher)
+ self.dispatcher_type = dispatcher_type
+ name = "recursive(%s)" % (dispatcher_type,)
+ super(RecursiveCall, self).__init__(name)
+ # Initializing for the first time
+ if self._overloads is None:
+ self._overloads = {}
+
+ def add_overloads(self, args, qualname, uid):
+ """Add an overload of the function.
+
+ Parameters
+ ----------
+ args :
+ argument types
+ qualname :
+ function qualifying name
+ uid :
+ unique id
+ """
+ self._overloads[args] = _RecursiveCallOverloads(qualname, uid)
+
+ def get_overloads(self, args):
+ """Get the qualifying name and unique id for the overload given the
+ argument types.
+ """
+ return self._overloads[args]
+
+ @property
+ def key(self):
+ return self.dispatcher_type
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/iterators.py b/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/iterators.py
new file mode 100644
index 0000000000000000000000000000000000000000..2baf1d42a0c29fd654e927c2fe316216ffcc3138
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/iterators.py
@@ -0,0 +1,108 @@
+from .common import SimpleIterableType, SimpleIteratorType
+from ..errors import TypingError
+
+
+class RangeType(SimpleIterableType):
+
+ def __init__(self, dtype):
+ self.dtype = dtype
+ name = "range_state_%s" % (dtype,)
+ super(SimpleIterableType, self).__init__(name)
+ self._iterator_type = RangeIteratorType(self.dtype)
+
+ def unify(self, typingctx, other):
+ if isinstance(other, RangeType):
+ dtype = typingctx.unify_pairs(self.dtype, other.dtype)
+ if dtype is not None:
+ return RangeType(dtype)
+
+
+class RangeIteratorType(SimpleIteratorType):
+
+ def __init__(self, dtype):
+ name = "range_iter_%s" % (dtype,)
+ super(SimpleIteratorType, self).__init__(name)
+ self._yield_type = dtype
+
+ def unify(self, typingctx, other):
+ if isinstance(other, RangeIteratorType):
+ dtype = typingctx.unify_pairs(self.yield_type, other.yield_type)
+ if dtype is not None:
+ return RangeIteratorType(dtype)
+
+
+class Generator(SimpleIteratorType):
+ """
+ Type class for Numba-compiled generator objects.
+ """
+
+ def __init__(self, gen_func, yield_type, arg_types, state_types,
+ has_finalizer):
+ self.gen_func = gen_func
+ self.arg_types = tuple(arg_types)
+ self.state_types = tuple(state_types)
+ self.has_finalizer = has_finalizer
+ name = "%s generator(func=%s, args=%s, has_finalizer=%s)" % (
+ yield_type, self.gen_func, self.arg_types,
+ self.has_finalizer)
+ super(Generator, self).__init__(name, yield_type)
+
+ @property
+ def key(self):
+ return (self.gen_func, self.arg_types, self.yield_type,
+ self.has_finalizer, self.state_types)
+
+
+class EnumerateType(SimpleIteratorType):
+ """
+ Type class for `enumerate` objects.
+ Type instances are parametered with the underlying source type.
+ """
+
+ def __init__(self, iterable_type):
+ from numba.core.types import Tuple, intp
+ self.source_type = iterable_type.iterator_type
+ yield_type = Tuple([intp, self.source_type.yield_type])
+ name = 'enumerate(%s)' % (self.source_type)
+ super(EnumerateType, self).__init__(name, yield_type)
+
+ @property
+ def key(self):
+ return self.source_type
+
+
+class ZipType(SimpleIteratorType):
+ """
+ Type class for `zip` objects.
+ Type instances are parametered with the underlying source types.
+ """
+
+ def __init__(self, iterable_types):
+ from numba.core.types import Tuple
+ self.source_types = tuple(tp.iterator_type for tp in iterable_types)
+ yield_type = Tuple([tp.yield_type for tp in self.source_types])
+ name = 'zip(%s)' % ', '.join(str(tp) for tp in self.source_types)
+ super(ZipType, self).__init__(name, yield_type)
+
+ @property
+ def key(self):
+ return self.source_types
+
+
+class ArrayIterator(SimpleIteratorType):
+ """
+ Type class for iterators of array and buffer objects.
+ """
+
+ def __init__(self, array_type):
+ self.array_type = array_type
+ name = "iter(%s)" % (self.array_type,)
+ nd = array_type.ndim
+ if nd == 0:
+ raise TypingError("iteration over a 0-d array")
+ elif nd == 1:
+ yield_type = array_type.dtype
+ else:
+ # iteration semantics leads to A order layout
+ yield_type = array_type.copy(ndim=array_type.ndim - 1, layout='A')
+ super(ArrayIterator, self).__init__(name, yield_type)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/misc.py b/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/misc.py
new file mode 100644
index 0000000000000000000000000000000000000000..666b122d18860f88eaaa800dd7a3866f5c520e03
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/misc.py
@@ -0,0 +1,556 @@
+from numba.core.types.abstract import Callable, Literal, Type, Hashable
+from numba.core.types.common import (Dummy, IterableType, Opaque,
+ SimpleIteratorType)
+from numba.core.typeconv import Conversion
+from numba.core.errors import TypingError, LiteralTypingError
+from numba.core.ir import UndefinedType
+from numba.core.utils import get_hashable_key
+
+
+class PyObject(Dummy):
+ """
+ A generic CPython object.
+ """
+
+ def is_precise(self):
+ return False
+
+
+class Phantom(Dummy):
+ """
+ A type that cannot be materialized. A Phantom cannot be used as
+ argument or return type.
+ """
+
+
+class Undefined(Dummy):
+ """
+ A type that is left imprecise. This is used as a temporaray placeholder
+ during type inference in the hope that the type can be later refined.
+ """
+
+ def is_precise(self):
+ return False
+
+
+class UndefVar(Dummy):
+ """
+ A type that is created by Expr.undef to represent an undefined variable.
+ This type can be promoted to any other type.
+ This is introduced to handle Python 3.12 LOAD_FAST_AND_CLEAR.
+ """
+
+ def can_convert_to(self, typingctx, other):
+ return Conversion.promote
+
+
+class RawPointer(Opaque):
+ """
+ A raw pointer without any specific meaning.
+ """
+
+
+class StringLiteral(Literal, Dummy):
+
+ def can_convert_to(self, typingctx, other):
+ if isinstance(other, UnicodeType):
+ return Conversion.safe
+
+
+Literal.ctor_map[str] = StringLiteral
+
+
+def unliteral(lit_type):
+ """
+ Get base type from Literal type.
+ """
+ if hasattr(lit_type, '__unliteral__'):
+ return lit_type.__unliteral__()
+ return getattr(lit_type, 'literal_type', lit_type)
+
+
+def literal(value):
+ """Returns a Literal instance or raise LiteralTypingError
+ """
+ ty = type(value)
+ if isinstance(value, Literal):
+ msg = "the function does not accept a Literal type; got {} ({})"
+ raise ValueError(msg.format(value, ty))
+ try:
+ ctor = Literal.ctor_map[ty]
+ except KeyError:
+ raise LiteralTypingError("{} cannot be used as a literal".format(ty))
+ else:
+ return ctor(value)
+
+
+def maybe_literal(value):
+ """Get a Literal type for the value or None.
+ """
+ try:
+ return literal(value)
+ except LiteralTypingError:
+ return
+
+
+class Omitted(Opaque):
+ """
+ An omitted function argument with a default value.
+ """
+
+ def __init__(self, value):
+ self._value = value
+ # Use helper function to support both hashable and non-hashable
+ # values. See discussion in gh #6957.
+ self._value_key = get_hashable_key(value)
+ super(Omitted, self).__init__("omitted(default=%r)" % (value,))
+
+ @property
+ def key(self):
+ return type(self._value), self._value_key
+
+ @property
+ def value(self):
+ return self._value
+
+
+class VarArg(Type):
+ """
+ Special type representing a variable number of arguments at the
+ end of a function's signature. Only used for signature matching,
+ not for actual values.
+ """
+
+ def __init__(self, dtype):
+ self.dtype = dtype
+ super(VarArg, self).__init__("*%s" % dtype)
+
+ @property
+ def key(self):
+ return self.dtype
+
+
+class Module(Dummy):
+ def __init__(self, pymod):
+ self.pymod = pymod
+ super(Module, self).__init__("Module(%s)" % pymod)
+
+ @property
+ def key(self):
+ return self.pymod
+
+
+class MemInfoPointer(Type):
+ """
+ Pointer to a Numba "meminfo" (i.e. the information for a managed
+ piece of memory).
+ """
+ mutable = True
+
+ def __init__(self, dtype):
+ self.dtype = dtype
+ name = "memory-managed *%s" % dtype
+ super(MemInfoPointer, self).__init__(name)
+
+ @property
+ def key(self):
+ return self.dtype
+
+
+class CPointer(Type):
+ """
+ Type class for pointers to other types.
+
+ Attributes
+ ----------
+ dtype : The pointee type
+ addrspace : int
+ The address space pointee belongs to.
+ """
+ mutable = True
+
+ def __init__(self, dtype, addrspace=None):
+ self.dtype = dtype
+ self.addrspace = addrspace
+ if addrspace is not None:
+ name = "%s_%s*" % (dtype, addrspace)
+ else:
+ name = "%s*" % dtype
+ super(CPointer, self).__init__(name)
+
+ @property
+ def key(self):
+ return self.dtype, self.addrspace
+
+
+class EphemeralPointer(CPointer):
+ """
+ Type class for pointers which aren't guaranteed to last long - e.g.
+ stack-allocated slots. The data model serializes such pointers
+ by copying the data pointed to.
+ """
+
+
+class EphemeralArray(Type):
+ """
+ Similar to EphemeralPointer, but pointing to an array of elements,
+ rather than a single one. The array size must be known at compile-time.
+ """
+
+ def __init__(self, dtype, count):
+ self.dtype = dtype
+ self.count = count
+ name = "*%s[%d]" % (dtype, count)
+ super(EphemeralArray, self).__init__(name)
+
+ @property
+ def key(self):
+ return self.dtype, self.count
+
+
+class Object(Type):
+ # XXX unused?
+ mutable = True
+
+ def __init__(self, clsobj):
+ self.cls = clsobj
+ name = "Object(%s)" % clsobj.__name__
+ super(Object, self).__init__(name)
+
+ @property
+ def key(self):
+ return self.cls
+
+
+class Optional(Type):
+ """
+ Type class for optional types, i.e. union { some type, None }
+ """
+
+ def __init__(self, typ):
+ assert not isinstance(typ, (Optional, NoneType))
+ typ = unliteral(typ)
+ self.type = typ
+ name = "OptionalType(%s)" % self.type
+ super(Optional, self).__init__(name)
+
+ @property
+ def key(self):
+ return self.type
+
+ def can_convert_to(self, typingctx, other):
+ if isinstance(other, Optional):
+ return typingctx.can_convert(self.type, other.type)
+ else:
+ conv = typingctx.can_convert(self.type, other)
+ if conv is not None:
+ return max(conv, Conversion.safe)
+
+ def can_convert_from(self, typingctx, other):
+ if isinstance(other, NoneType):
+ return Conversion.promote
+ elif isinstance(other, Optional):
+ return typingctx.can_convert(other.type, self.type)
+ else:
+ conv = typingctx.can_convert(other, self.type)
+ if conv is not None:
+ return max(conv, Conversion.promote)
+
+ def unify(self, typingctx, other):
+ if isinstance(other, Optional):
+ unified = typingctx.unify_pairs(self.type, other.type)
+ else:
+ unified = typingctx.unify_pairs(self.type, other)
+
+ if unified is not None:
+ if isinstance(unified, Optional):
+ return unified
+ else:
+ return Optional(unified)
+
+
+class NoneType(Opaque):
+ """
+ The type for None.
+ """
+
+ def unify(self, typingctx, other):
+ """
+ Turn anything to a Optional type;
+ """
+ if isinstance(other, (Optional, NoneType)):
+ return other
+ return Optional(other)
+
+
+class EllipsisType(Opaque):
+ """
+ The type for the Ellipsis singleton.
+ """
+
+
+class ExceptionClass(Callable, Phantom):
+ """
+ The type of exception classes (not instances).
+ """
+
+ def __init__(self, exc_class):
+ assert issubclass(exc_class, BaseException)
+ name = "%s" % (exc_class.__name__)
+ self.exc_class = exc_class
+ super(ExceptionClass, self).__init__(name)
+
+ def get_call_type(self, context, args, kws):
+ return self.get_call_signatures()[0][0]
+
+ def get_call_signatures(self):
+ from numba.core import typing
+ return_type = ExceptionInstance(self.exc_class)
+ return [typing.signature(return_type)], False
+
+ def get_impl_key(self, sig):
+ return type(self)
+
+ @property
+ def key(self):
+ return self.exc_class
+
+
+class ExceptionInstance(Phantom):
+ """
+ The type of exception instances. *exc_class* should be the
+ exception class.
+ """
+
+ def __init__(self, exc_class):
+ assert issubclass(exc_class, BaseException)
+ name = "%s(...)" % (exc_class.__name__,)
+ self.exc_class = exc_class
+ super(ExceptionInstance, self).__init__(name)
+
+ @property
+ def key(self):
+ return self.exc_class
+
+
+class SliceType(Type):
+
+ def __init__(self, name, members):
+ assert members in (2, 3)
+ self.members = members
+ self.has_step = members >= 3
+ super(SliceType, self).__init__(name)
+
+ @property
+ def key(self):
+ return self.members
+
+
+class SliceLiteral(Literal, SliceType):
+ def __init__(self, value):
+ self._literal_init(value)
+ name = 'Literal[slice]({})'.format(value)
+ members = 2 if value.step is None else 3
+ SliceType.__init__(self, name=name, members=members)
+
+ @property
+ def key(self):
+ sl = self.literal_value
+ return sl.start, sl.stop, sl.step
+
+
+Literal.ctor_map[slice] = SliceLiteral
+
+
+class ClassInstanceType(Type):
+ """
+ The type of a jitted class *instance*. It will be the return-type
+ of the constructor of the class.
+ """
+ mutable = True
+ name_prefix = "instance"
+
+ def __init__(self, class_type):
+ self.class_type = class_type
+ name = "{0}.{1}".format(self.name_prefix, self.class_type.name)
+ super(ClassInstanceType, self).__init__(name)
+
+ def get_data_type(self):
+ return ClassDataType(self)
+
+ def get_reference_type(self):
+ return self
+
+ @property
+ def key(self):
+ return self.class_type.key
+
+ @property
+ def classname(self):
+ return self.class_type.class_name
+
+ @property
+ def jit_props(self):
+ return self.class_type.jit_props
+
+ @property
+ def jit_static_methods(self):
+ return self.class_type.jit_static_methods
+
+ @property
+ def jit_methods(self):
+ return self.class_type.jit_methods
+
+ @property
+ def struct(self):
+ return self.class_type.struct
+
+ @property
+ def methods(self):
+ return self.class_type.methods
+
+ @property
+ def static_methods(self):
+ return self.class_type.static_methods
+
+
+class ClassType(Callable, Opaque):
+ """
+ The type of the jitted class (not instance). When the type of a class
+ is called, its constructor is invoked.
+ """
+ mutable = True
+ name_prefix = "jitclass"
+ instance_type_class = ClassInstanceType
+
+ def __init__(self, class_def, ctor_template_cls, struct, jit_methods,
+ jit_props, jit_static_methods):
+ self.class_name = class_def.__name__
+ self.class_doc = class_def.__doc__
+ self._ctor_template_class = ctor_template_cls
+ self.jit_methods = jit_methods
+ self.jit_props = jit_props
+ self.jit_static_methods = jit_static_methods
+ self.struct = struct
+ fielddesc = ','.join("{0}:{1}".format(k, v) for k, v in struct.items())
+ name = "{0}.{1}#{2:x}<{3}>".format(self.name_prefix, self.class_name,
+ id(self), fielddesc)
+ super(ClassType, self).__init__(name)
+
+ def get_call_type(self, context, args, kws):
+ return self.ctor_template(context).apply(args, kws)
+
+ def get_call_signatures(self):
+ return (), True
+
+ def get_impl_key(self, sig):
+ return type(self)
+
+ @property
+ def methods(self):
+ return {k: v.py_func for k, v in self.jit_methods.items()}
+
+ @property
+ def static_methods(self):
+ return {k: v.py_func for k, v in self.jit_static_methods.items()}
+
+ @property
+ def instance_type(self):
+ return ClassInstanceType(self)
+
+ @property
+ def ctor_template(self):
+ return self._specialize_template(self._ctor_template_class)
+
+ def _specialize_template(self, basecls):
+ return type(basecls.__name__, (basecls,), dict(key=self))
+
+
+class DeferredType(Type):
+ """
+ Represents a type that will be defined later. It must be defined
+ before it is materialized (used in the compiler). Once defined, it
+ behaves exactly as the type it is defining.
+ """
+
+ def __init__(self):
+ self._define = None
+ name = "{0}#{1}".format(type(self).__name__, id(self))
+ super(DeferredType, self).__init__(name)
+
+ def get(self):
+ if self._define is None:
+ raise RuntimeError("deferred type not defined")
+ return self._define
+
+ def define(self, typ):
+ if self._define is not None:
+ raise TypeError("deferred type already defined")
+ if not isinstance(typ, Type):
+ raise TypeError("arg is not a Type; got: {0}".format(type(typ)))
+ self._define = typ
+
+ def unify(self, typingctx, other):
+ return typingctx.unify_pairs(self.get(), other)
+
+
+class ClassDataType(Type):
+ """
+ Internal only.
+ Represents the data of the instance. The representation of
+ ClassInstanceType contains a pointer to a ClassDataType which represents
+ a C structure that contains all the data fields of the class instance.
+ """
+
+ def __init__(self, classtyp):
+ self.class_type = classtyp
+ name = "data.{0}".format(self.class_type.name)
+ super(ClassDataType, self).__init__(name)
+
+
+class ContextManager(Callable, Phantom):
+ """
+ An overly-simple ContextManager type that cannot be materialized.
+ """
+
+ def __init__(self, cm):
+ self.cm = cm
+ super(ContextManager, self).__init__("ContextManager({})".format(cm))
+
+ def get_call_signatures(self):
+ if not self.cm.is_callable:
+ msg = "contextmanager {} is not callable".format(self.cm)
+ raise TypingError(msg)
+
+ return (), False
+
+ def get_call_type(self, context, args, kws):
+ from numba.core import typing
+
+ if not self.cm.is_callable:
+ msg = "contextmanager {} is not callable".format(self.cm)
+ raise TypingError(msg)
+
+ posargs = list(args) + [v for k, v in sorted(kws.items())]
+ return typing.signature(self, *posargs)
+
+ def get_impl_key(self, sig):
+ return type(self)
+
+
+class UnicodeType(IterableType, Hashable):
+
+ def __init__(self, name):
+ super(UnicodeType, self).__init__(name)
+
+ @property
+ def iterator_type(self):
+ return UnicodeIteratorType(self)
+
+
+class UnicodeIteratorType(SimpleIteratorType):
+
+ def __init__(self, dtype):
+ name = "iter_unicode"
+ self.data = dtype
+ super(UnicodeIteratorType, self).__init__(name, dtype)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/new_scalars/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/new_scalars/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..94f0c899853e2f0a7b68c2d6cfa1847489450f35
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/new_scalars/__init__.py
@@ -0,0 +1,18 @@
+from numba.core.types.new_scalars.scalars import (
+ Integer, IntegerLiteral, Boolean, BooleanLiteral, Float, Complex,
+ parse_integer_bitwidth, parse_integer_signed,
+ _NPDatetimeBase, NPTimedelta, NPDatetime, EnumClass, IntEnumClass,
+ EnumMember, IntEnumMember
+)
+from numba.core.types.new_scalars.python_types import (
+ PythonBoolean, PythonInteger, PythonFloat, PythonComplex,
+ PythonBooleanLiteral, PythonIntegerLiteral
+)
+from numba.core.types.new_scalars.machine_types import (
+ MachineBoolean, MachineInteger, MachineFloat, MachineComplex,
+ MachineBooleanLiteral, MachineIntegerLiteral
+)
+from numba.core.types.new_scalars.numpy_types import (
+ NumPyBoolean, NumPyInteger, NumPyFloat, NumPyComplex,
+ NumPyBooleanLiteral, NumPyIntegerLiteral
+)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/new_scalars/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/new_scalars/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1cc410ad09dbc00d43e046a80b242ff20cbfbe8e
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/new_scalars/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/new_scalars/__pycache__/machine_types.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/new_scalars/__pycache__/machine_types.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cd1ada20561895b30d59cae208af71072ff592b5
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/new_scalars/__pycache__/machine_types.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/new_scalars/__pycache__/numpy_types.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/new_scalars/__pycache__/numpy_types.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5d4377641742877dd197eea616e3f41b70169cad
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/new_scalars/__pycache__/numpy_types.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/new_scalars/__pycache__/python_types.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/new_scalars/__pycache__/python_types.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8b5f812cdc69a622ceb6b5528e01bc056fa401c8
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/new_scalars/__pycache__/python_types.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/new_scalars/__pycache__/scalars.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/new_scalars/__pycache__/scalars.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f0314b735f10a8f0086ee1f00c1a18c8e909a0f7
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/new_scalars/__pycache__/scalars.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/new_scalars/machine_types.py b/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/new_scalars/machine_types.py
new file mode 100644
index 0000000000000000000000000000000000000000..ab7a8da7db70a229ff759fb055f032fb906a90ba
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/new_scalars/machine_types.py
@@ -0,0 +1,119 @@
+"""
+ Type definitions for machine types.
+"""
+
+from numba.core.types.new_scalars.scalars \
+ import (Integer, IntegerLiteral, Boolean,
+ BooleanLiteral, Float, Complex,
+ parse_integer_bitwidth, parse_integer_signed)
+from functools import total_ordering
+from numba.core.typeconv import Conversion
+
+
+@total_ordering
+class MachineInteger(Integer):
+ def __init__(self, name, bitwidth=None, signed=None):
+ super(MachineInteger, self).__init__(name)
+ if bitwidth is None:
+ bitwidth = parse_integer_bitwidth(name)
+ if signed is None:
+ signed = parse_integer_signed(name)
+ self.bitwidth = bitwidth
+ self.signed = signed
+
+ @classmethod
+ def from_bitwidth(cls, bitwidth, signed=True):
+ name = ('int%d' if signed else 'uint%d') % bitwidth
+ return cls(name)
+
+ def __lt__(self, other):
+ if self.__class__ is not other.__class__:
+ return NotImplemented
+ if self.signed != other.signed:
+ return NotImplemented
+ return self.bitwidth < other.bitwidth
+
+ @property
+ def maxval(self):
+ """
+ The maximum value representable by this type.
+ """
+ if self.signed:
+ return (1 << (self.bitwidth - 1)) - 1
+ else:
+ return (1 << self.bitwidth) - 1
+
+ @property
+ def minval(self):
+ """
+ The minimal value representable by this type.
+ """
+ if self.signed:
+ return -(1 << (self.bitwidth - 1))
+ else:
+ return 0
+
+
+class MachineIntegerLiteral(IntegerLiteral, MachineInteger):
+ def __init__(self, value):
+ self._literal_init(value)
+ name = 'Literal[machine_int]({})'.format(value)
+ basetype = self.literal_type
+ MachineInteger.__init__(self,
+ name=name,
+ bitwidth=basetype.bitwidth,
+ signed=basetype.signed,)
+
+ def can_convert_to(self, typingctx, other):
+ conv = typingctx.can_convert(self.literal_type, other)
+ if conv is not None:
+ return max(conv, Conversion.promote)
+
+
+class MachineBoolean(Boolean):
+ pass
+
+
+class MachineBooleanLiteral(BooleanLiteral, MachineBoolean):
+
+ def __init__(self, value):
+ self._literal_init(value)
+ name = 'Literal[machine_bool]({})'.format(value)
+ MachineBoolean.__init__(self,
+ name=name)
+
+ def can_convert_to(self, typingctx, other):
+ conv = typingctx.can_convert(self.literal_type, other)
+ if conv is not None:
+ return max(conv, Conversion.promote)
+
+
+@total_ordering
+class MachineFloat(Float):
+ def __init__(self, *args, **kws):
+ super(MachineFloat, self).__init__(*args, **kws)
+ # Determine bitwidth
+ assert self.name.startswith('c_float')
+ bitwidth = int(self.name[8:])
+ self.bitwidth = bitwidth
+
+ def __lt__(self, other):
+ if self.__class__ is not other.__class__:
+ return NotImplemented
+ return self.bitwidth < other.bitwidth
+
+
+@total_ordering
+class MachineComplex(Complex):
+ def __init__(self, name, underlying_float, **kwargs):
+ super(MachineComplex, self).__init__(name, **kwargs)
+ self.underlying_float = underlying_float
+ # Determine bitwidth
+ assert self.name.startswith('c_complex')
+ bitwidth = int(self.name[10:])
+ self.bitwidth = bitwidth
+
+ def __lt__(self, other):
+ if self.__class__ is not other.__class__:
+ return NotImplemented
+ return self.bitwidth < other.bitwidth
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/new_scalars/numpy_types.py b/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/new_scalars/numpy_types.py
new file mode 100644
index 0000000000000000000000000000000000000000..82a475c61aa33b53e7c7cf68b37a9ec2da8abbd1
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/new_scalars/numpy_types.py
@@ -0,0 +1,142 @@
+"""
+ Type definitions for NumPy types.
+"""
+
+import numpy as np
+
+from numba.core.types.abstract import Literal
+from numba.core.types.new_scalars.scalars \
+ import (Integer, IntegerLiteral, Boolean,
+ BooleanLiteral, Float, Complex,
+ parse_integer_bitwidth, parse_integer_signed)
+from functools import total_ordering
+from numba.core.typeconv import Conversion
+
+
+@total_ordering
+class NumPyInteger(Integer):
+ def __init__(self, name, bitwidth=None, signed=None):
+ super(NumPyInteger, self).__init__(name)
+ if bitwidth is None:
+ bitwidth = parse_integer_bitwidth(name)
+ if signed is None:
+ signed = parse_integer_signed(name)
+ self.bitwidth = bitwidth
+ self.signed = signed
+
+ @classmethod
+ def from_bitwidth(cls, bitwidth, signed=True):
+ name = ('np_int%d' if signed else 'np_uint%d') % bitwidth
+ return cls(name)
+
+ def cast_python_value(self, value):
+ sign_char = "" if self.signed else "u"
+ return getattr(
+ np,
+ sign_char + "int" + str(self.bitwidth)
+ )(value)
+
+ def __lt__(self, other):
+ if self.__class__ is not other.__class__:
+ return NotImplemented
+ if self.signed != other.signed:
+ return NotImplemented
+ return self.bitwidth < other.bitwidth
+
+ @property
+ def maxval(self):
+ """
+ The maximum value representable by this type.
+ """
+ if self.signed:
+ return (1 << (self.bitwidth - 1)) - 1
+ else:
+ return (1 << self.bitwidth) - 1
+
+ @property
+ def minval(self):
+ """
+ The minimal value representable by this type.
+ """
+ if self.signed:
+ return -(1 << (self.bitwidth - 1))
+ else:
+ return 0
+
+
+class NumPyIntegerLiteral(IntegerLiteral):
+ def __init__(self, value):
+ self._literal_init(value)
+ name = 'Literal[int]({})'.format(value)
+ basetype = self.literal_type
+ NumPyInteger.__init__(self,
+ name=name,
+ bitwidth=basetype.bitwidth,
+ signed=basetype.signed,)
+
+ def can_convert_to(self, typingctx, other):
+ conv = typingctx.can_convert(self.literal_type, other)
+ if conv is not None:
+ return max(conv, Conversion.promote)
+
+
+Literal.ctor_map[np.integer] = NumPyIntegerLiteral
+
+
+class NumPyBoolean(Boolean):
+ def cast_python_value(self, value):
+ return np.bool_(value)
+
+
+class NumPyBooleanLiteral(BooleanLiteral, NumPyBoolean):
+
+ def __init__(self, value):
+ self._literal_init(value)
+ name = 'Literal[np.bool_]({})'.format(value)
+ NumPyBoolean.__init__(self,
+ name=name)
+
+ def can_convert_to(self, typingctx, other):
+ conv = typingctx.can_convert(self.literal_type, other)
+ if conv is not None:
+ return max(conv, Conversion.promote)
+
+
+Literal.ctor_map[np.bool_] = NumPyBooleanLiteral
+
+
+@total_ordering
+class NumPyFloat(Float):
+ def __init__(self, *args, **kws):
+ super(NumPyFloat, self).__init__(*args, **kws)
+ # Determine bitwidth
+ assert self.name.startswith('np_float')
+ bitwidth = int(self.name[8:])
+ self.bitwidth = bitwidth
+
+ def cast_python_value(self, value):
+ return getattr(np, "float" + str(self.bitwidth))(value)
+
+ def __lt__(self, other):
+ if self.__class__ is not other.__class__:
+ return NotImplemented
+ return self.bitwidth < other.bitwidth
+
+
+@total_ordering
+class NumPyComplex(Complex):
+ def __init__(self, name, underlying_float, **kwargs):
+ super(NumPyComplex, self).__init__(name, **kwargs)
+ self.underlying_float = underlying_float
+ # Determine bitwidth
+ assert self.name.startswith('np_complex')
+ bitwidth = int(self.name[10:])
+ self.bitwidth = bitwidth
+
+ def cast_python_value(self, value):
+ return getattr(np, "complex" + str(self.bitwidth))(value)
+
+ def __lt__(self, other):
+ if self.__class__ is not other.__class__:
+ return NotImplemented
+ return self.bitwidth < other.bitwidth
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/new_scalars/python_types.py b/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/new_scalars/python_types.py
new file mode 100644
index 0000000000000000000000000000000000000000..2cc13f8d0d546567ca995bb699d2131d1daa154b
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/new_scalars/python_types.py
@@ -0,0 +1,130 @@
+"""
+ Type definitions for Python types.
+"""
+
+from numba.core.types.abstract import Literal
+from numba.core.types.new_scalars.scalars \
+ import (Integer, IntegerLiteral, Boolean,
+ BooleanLiteral, Float, Complex,
+ parse_integer_signed)
+from functools import total_ordering
+from numba.core.typeconv import Conversion
+
+
+@total_ordering
+class PythonInteger(Integer):
+ def __init__(self, name, bitwidth=None, signed=None):
+ super(PythonInteger, self).__init__(name)
+ if bitwidth is None:
+ bitwidth = 64
+ if signed is None:
+ signed = parse_integer_signed(name)
+ self.bitwidth = bitwidth
+ self.signed = signed
+
+ def cast_python_value(self, value):
+ return int(value)
+
+ def __lt__(self, other):
+ if self.__class__ is not other.__class__:
+ return NotImplemented
+ if self.signed != other.signed:
+ return NotImplemented
+ return self.bitwidth < other.bitwidth
+
+ @property
+ def maxval(self):
+ """
+ The maximum value representable by this type.
+ """
+ if self.signed:
+ return (1 << (self.bitwidth - 1)) - 1
+ else:
+ return (1 << self.bitwidth) - 1
+
+ @property
+ def minval(self):
+ """
+ The minimal value representable by this type.
+ """
+ if self.signed:
+ return -(1 << (self.bitwidth - 1))
+ else:
+ return 0
+
+
+class PythonIntegerLiteral(IntegerLiteral, PythonInteger):
+ def __init__(self, value):
+ self._literal_init(value)
+ name = 'Literal[int]({})'.format(value)
+ basetype = self.literal_type
+ PythonInteger.__init__(self,
+ name=name,
+ bitwidth=basetype.bitwidth,
+ signed=basetype.signed,)
+
+ def can_convert_to(self, typingctx, other):
+ conv = typingctx.can_convert(self.literal_type, other)
+ if conv is not None:
+ return max(conv, Conversion.promote)
+
+
+Literal.ctor_map[int] = PythonIntegerLiteral
+
+
+class PythonBoolean(Boolean):
+ def cast_python_value(self, value):
+ return bool(value)
+
+
+class PythonBooleanLiteral(BooleanLiteral, PythonBoolean):
+
+ def __init__(self, value):
+ self._literal_init(value)
+ name = 'Literal[bool]({})'.format(value)
+ PythonBoolean.__init__(self, name=name)
+
+ def can_convert_to(self, typingctx, other):
+ conv = typingctx.can_convert(self.literal_type, other)
+ if conv is not None:
+ return max(conv, Conversion.promote)
+
+
+Literal.ctor_map[bool] = PythonBooleanLiteral
+
+
+@total_ordering
+class PythonFloat(Float):
+ def __init__(self, *args, **kws):
+ super(PythonFloat, self).__init__(*args, **kws)
+ # Determine bitwidth
+ assert self.name.startswith('py_float')
+ bitwidth = 64
+ self.bitwidth = bitwidth
+
+ def cast_python_value(self, value):
+ return float(value)
+
+ def __lt__(self, other):
+ if self.__class__ is not other.__class__:
+ return NotImplemented
+ return self.bitwidth < other.bitwidth
+
+
+@total_ordering
+class PythonComplex(Complex):
+ def __init__(self, name, underlying_float, **kwargs):
+ super(PythonComplex, self).__init__(name, **kwargs)
+ self.underlying_float = underlying_float
+ # Determine bitwidth
+ assert self.name.startswith('py_complex')
+ bitwidth = 128
+ self.bitwidth = bitwidth
+
+ def cast_python_value(self, value):
+ return complex(value)
+
+ def __lt__(self, other):
+ if self.__class__ is not other.__class__:
+ return NotImplemented
+ return self.bitwidth < other.bitwidth
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/new_scalars/scalars.py b/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/new_scalars/scalars.py
new file mode 100644
index 0000000000000000000000000000000000000000..9f26c2160e21285fd92de0c71a522a0569ccda75
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/new_scalars/scalars.py
@@ -0,0 +1,161 @@
+import enum
+import re
+import numpy as np
+
+from numba.core.types.abstract import Dummy, Hashable, Literal, Number, Type
+from functools import total_ordering, cached_property
+from numba.core import utils
+from numba.core.typeconv import Conversion
+from numba.np import npdatetime_helpers
+
+
+class Boolean(Hashable):
+ pass
+
+def parse_integer_bitwidth(name):
+ bitwidth = int(re.findall(r'\d+', name)[-1])
+ return bitwidth
+
+
+def parse_integer_signed(name):
+ signed = name.startswith('int')
+ return signed
+
+
+class Integer(Number):
+ pass
+
+
+class IntegerLiteral(Literal, Integer):
+ pass
+
+
+class BooleanLiteral(Literal, Boolean):
+ pass
+
+
+class Float(Number):
+ pass
+
+
+class Complex(Number):
+ pass
+
+
+class _NPDatetimeBase(Type):
+ """
+ Common base class for np.datetime64 and np.timedelta64.
+ """
+
+ def __init__(self, unit, *args, **kws):
+ name = '%s[%s]' % (self.type_name, unit)
+ self.unit = unit
+ self.unit_code = npdatetime_helpers.DATETIME_UNITS[self.unit]
+ super(_NPDatetimeBase, self).__init__(name, *args, **kws)
+
+ def __lt__(self, other):
+ if self.__class__ is not other.__class__:
+ return NotImplemented
+ # A coarser-grained unit is "smaller", i.e. less precise values
+ # can be represented (but the magnitude of representable values is
+ # also greater...).
+ return self.unit_code < other.unit_code
+
+ def cast_python_value(self, value):
+ cls = getattr(np, self.type_name)
+ if self.unit:
+ return cls(value, self.unit)
+ else:
+ return cls(value)
+
+
+@total_ordering
+class NPTimedelta(_NPDatetimeBase):
+ type_name = 'timedelta64'
+
+@total_ordering
+class NPDatetime(_NPDatetimeBase):
+ type_name = 'datetime64'
+
+
+class EnumClass(Dummy):
+ """
+ Type class for Enum classes.
+ """
+ basename = "Enum class"
+
+ def __init__(self, cls, dtype):
+ assert isinstance(cls, type)
+ assert isinstance(dtype, Type)
+ self.instance_class = cls
+ self.dtype = dtype
+ name = "%s<%s>(%s)" % (self.basename, self.dtype, self.instance_class.__name__)
+ super(EnumClass, self).__init__(name)
+
+ @property
+ def key(self):
+ return self.instance_class, self.dtype
+
+ @cached_property
+ def member_type(self):
+ """
+ The type of this class' members.
+ """
+ return EnumMember(self.instance_class, self.dtype)
+
+
+class IntEnumClass(EnumClass):
+ """
+ Type class for IntEnum classes.
+ """
+ basename = "IntEnum class"
+
+ @cached_property
+ def member_type(self):
+ """
+ The type of this class' members.
+ """
+ return IntEnumMember(self.instance_class, self.dtype)
+
+
+class EnumMember(Type):
+ """
+ Type class for Enum members.
+ """
+ basename = "Enum"
+ class_type_class = EnumClass
+
+ def __init__(self, cls, dtype):
+ assert isinstance(cls, type)
+ assert isinstance(dtype, Type)
+ self.instance_class = cls
+ self.dtype = dtype
+ name = "%s<%s>(%s)" % (self.basename, self.dtype, self.instance_class.__name__)
+ super(EnumMember, self).__init__(name)
+
+ @property
+ def key(self):
+ return self.instance_class, self.dtype
+
+ @property
+ def class_type(self):
+ """
+ The type of this member's class.
+ """
+ return self.class_type_class(self.instance_class, self.dtype)
+
+
+class IntEnumMember(EnumMember):
+ """
+ Type class for IntEnum members.
+ """
+ basename = "IntEnum"
+ class_type_class = IntEnumClass
+
+ def can_convert_to(self, typingctx, other):
+ """
+ Convert IntEnum members to plain integers.
+ """
+ if issubclass(self.instance_class, enum.IntEnum):
+ conv = typingctx.can_convert(self.dtype, other)
+ return max(conv, Conversion.safe)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/npytypes.py b/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/npytypes.py
new file mode 100644
index 0000000000000000000000000000000000000000..264ff356c8d22f5f46abc35cce7bb54617cb6896
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/npytypes.py
@@ -0,0 +1,649 @@
+import collections
+import warnings
+from functools import cached_property
+
+from llvmlite import ir
+
+from .abstract import DTypeSpec, IteratorType, MutableSequence, Number, Type
+from .common import Buffer, Opaque, SimpleIteratorType
+from numba.core.typeconv import Conversion
+from numba.core import utils
+from .misc import UnicodeType
+from .containers import Bytes
+import numpy as np
+
+class CharSeq(Type):
+ """
+ A fixed-length 8-bit character sequence.
+ """
+ mutable = True
+
+ def __init__(self, count):
+ self.count = count
+ name = "[char x %d]" % count
+ super(CharSeq, self).__init__(name)
+
+ @property
+ def key(self):
+ return self.count
+
+ def can_convert_from(self, typingctx, other):
+ if isinstance(other, Bytes):
+ return Conversion.safe
+
+
+class UnicodeCharSeq(Type):
+ """
+ A fixed-length unicode character sequence.
+ """
+ mutable = True
+
+ def __init__(self, count):
+ self.count = count
+ name = "[unichr x %d]" % count
+ super(UnicodeCharSeq, self).__init__(name)
+
+ @property
+ def key(self):
+ return self.count
+
+ def can_convert_to(self, typingctx, other):
+ if isinstance(other, UnicodeCharSeq):
+ return Conversion.safe
+
+ def can_convert_from(self, typingctx, other):
+ if isinstance(other, UnicodeType):
+ # Assuming that unicode_type itemsize is not greater than
+ # numpy.dtype('U1').itemsize that UnicodeCharSeq is based
+ # on.
+ return Conversion.safe
+
+ def __repr__(self):
+ return f"UnicodeCharSeq({self.count})"
+
+
+_RecordField = collections.namedtuple(
+ '_RecordField',
+ 'type,offset,alignment,title',
+)
+
+
+class Record(Type):
+ """
+ A Record datatype can be mapped to a NumPy structured dtype.
+ A record is very flexible since it is laid out as a list of bytes.
+ Fields can be mapped to arbitrary points inside it, even if they overlap.
+
+ *fields* is a list of `(name:str, data:dict)`.
+ Where `data` is `{ type: Type, offset: int }`
+ *size* is an int; the record size
+ *aligned* is a boolean; whether the record is ABI aligned.
+ """
+ mutable = True
+
+ @classmethod
+ def make_c_struct(cls, name_types):
+ """Construct a Record type from a list of (name:str, type:Types).
+ The layout of the structure will follow C.
+
+ Note: only scalar types are supported currently.
+ """
+ from numba.core.registry import cpu_target
+
+ ctx = cpu_target.target_context
+ offset = 0
+ fields = []
+ lltypes = []
+ for k, ty in name_types:
+ if not isinstance(ty, (Number, NestedArray)):
+ msg = "Only Number and NestedArray types are supported, found: {}. "
+ raise TypeError(msg.format(ty))
+ if isinstance(ty, NestedArray):
+ datatype = ctx.data_model_manager[ty].as_storage_type()
+ else:
+ datatype = ctx.get_data_type(ty)
+ lltypes.append(datatype)
+ size = ctx.get_abi_sizeof(datatype)
+ align = ctx.get_abi_alignment(datatype)
+ # align
+ misaligned = offset % align
+ if misaligned:
+ offset += align - misaligned
+ fields.append((k, {
+ 'type': ty, 'offset': offset, 'alignment': align,
+ }))
+ offset += size
+ # Adjust sizeof structure
+ abi_size = ctx.get_abi_sizeof(ir.LiteralStructType(lltypes))
+ return Record(fields, size=abi_size, aligned=True)
+
+ def __init__(self, fields, size, aligned):
+ fields = self._normalize_fields(fields)
+ self.fields = dict(fields)
+ self.size = size
+ self.aligned = aligned
+
+ # Create description
+ descbuf = []
+ fmt = "{}[type={};offset={}{}]"
+ for k, infos in fields:
+ extra = ""
+ if infos.alignment is not None:
+ extra += ';alignment={}'.format(infos.alignment)
+ elif infos.title is not None:
+ extra += ';title={}'.format(infos.title)
+ descbuf.append(fmt.format(k, infos.type, infos.offset, extra))
+
+ desc = ','.join(descbuf)
+ name = 'Record({};{};{})'.format(desc, self.size, self.aligned)
+ super(Record, self).__init__(name)
+
+ self.bitwidth = self.dtype.itemsize * 8
+
+ @classmethod
+ def _normalize_fields(cls, fields):
+ """
+ fields:
+ [name: str,
+ value: {
+ type: Type,
+ offset: int,
+ [ alignment: int ],
+ [ title : str],
+ }]
+ """
+ res = []
+ for name, infos in sorted(fields, key=lambda x: (x[1]['offset'], x[0])):
+ fd = _RecordField(
+ type=infos['type'],
+ offset=infos['offset'],
+ alignment=infos.get('alignment'),
+ title=infos.get('title'),
+ )
+ res.append((name, fd))
+ return res
+
+ @property
+ def key(self):
+ # Numpy dtype equality doesn't always succeed, use the name instead
+ # (https://github.com/numpy/numpy/issues/5715)
+ return self.name
+
+ @property
+ def mangling_args(self):
+ return self.__class__.__name__, (self._code,)
+
+ def __len__(self):
+ """Returns the number of fields
+ """
+ return len(self.fields)
+
+ def offset(self, key):
+ """Get the byte offset of a field from the start of the structure.
+ """
+ return self.fields[key].offset
+
+ def typeof(self, key):
+ """Get the type of a field.
+ """
+ return self.fields[key].type
+
+ def alignof(self, key):
+ """Get the specified alignment of the field.
+
+ Since field alignment is optional, this may return None.
+ """
+ return self.fields[key].alignment
+
+ def has_titles(self):
+ """Returns True the record uses titles.
+ """
+ return any(fd.title is not None for fd in self.fields.values())
+
+ def is_title(self, key):
+ """Returns True if the field named *key* is a title.
+ """
+ return self.fields[key].title == key
+
+ @property
+ def members(self):
+ """An ordered list of (name, type) for the fields.
+ """
+ ordered = sorted(self.fields.items(), key=lambda x: x[1].offset)
+ return [(k, v.type) for k, v in ordered]
+
+ @property
+ def dtype(self):
+ from numba.np.numpy_support import as_struct_dtype
+
+ return as_struct_dtype(self)
+
+ def can_convert_to(self, typingctx, other):
+ """
+ Convert this Record to the *other*.
+
+ This method only implements width subtyping for records.
+ """
+ from numba.core.errors import NumbaExperimentalFeatureWarning
+
+ if isinstance(other, Record):
+ if len(other.fields) > len(self.fields):
+ return
+ for other_fd, self_fd in zip(other.fields.items(),
+ self.fields.items()):
+ if not other_fd == self_fd:
+ return
+ warnings.warn(f"{self} has been considered a subtype of {other} "
+ f" This is an experimental feature.",
+ category=NumbaExperimentalFeatureWarning)
+ return Conversion.safe
+
+ def __repr__(self):
+ fields = [f"('{f_name}', " +
+ f"{{'type': {repr(f_info.type)}, " +
+ f"'offset': {f_info.offset}, " +
+ f"'alignment': {f_info.alignment}, " +
+ f"'title': {f_info.title}, " +
+ f"}}" +
+ ")"
+ for f_name, f_info in self.fields.items()
+ ]
+ fields = "[" + ", ".join(fields) + "]"
+ return f"Record({fields}, {self.size}, {self.aligned})"
+
+class DType(DTypeSpec, Opaque):
+ """
+ Type class associated with the `np.dtype`.
+
+ i.e. :code:`assert type(np.dtype('int32')) == np.dtype`
+
+ np.dtype('int32')
+ """
+
+ def __init__(self, dtype):
+ assert isinstance(dtype, Type)
+ self._dtype = dtype
+ name = "dtype(%s)" % (dtype,)
+ super(DTypeSpec, self).__init__(name)
+
+ @property
+ def key(self):
+ return self.dtype
+
+ @property
+ def dtype(self):
+ return self._dtype
+
+ def __getitem__(self, arg):
+ res = super(DType, self).__getitem__(arg)
+ return res.copy(dtype=self.dtype)
+
+
+class NumpyFlatType(SimpleIteratorType, MutableSequence):
+ """
+ Type class for `ndarray.flat()` objects.
+ """
+
+ def __init__(self, arrty):
+ self.array_type = arrty
+ yield_type = arrty.dtype
+ self.dtype = yield_type
+ name = "array.flat({arrayty})".format(arrayty=arrty)
+ super(NumpyFlatType, self).__init__(name, yield_type)
+
+ @property
+ def key(self):
+ return self.array_type
+
+
+class NumpyNdEnumerateType(SimpleIteratorType):
+ """
+ Type class for `np.ndenumerate()` objects.
+ """
+
+ def __init__(self, arrty):
+ from . import Tuple, UniTuple, intp
+ self.array_type = arrty
+ yield_type = Tuple((UniTuple(intp, arrty.ndim), arrty.dtype))
+ name = "ndenumerate({arrayty})".format(arrayty=arrty)
+ super(NumpyNdEnumerateType, self).__init__(name, yield_type)
+
+ @property
+ def key(self):
+ return self.array_type
+
+
+class NumpyNdIterType(IteratorType):
+ """
+ Type class for `np.nditer()` objects.
+
+ The layout denotes in which order the logical shape is iterated on.
+ "C" means logical order (corresponding to in-memory order in C arrays),
+ "F" means reverse logical order (corresponding to in-memory order in
+ F arrays).
+ """
+
+ def __init__(self, arrays):
+ # Note inputs arrays can also be scalars, in which case they are
+ # broadcast.
+ self.arrays = tuple(arrays)
+ self.layout = self._compute_layout(self.arrays)
+ self.dtypes = tuple(getattr(a, 'dtype', a) for a in self.arrays)
+ self.ndim = max(getattr(a, 'ndim', 0) for a in self.arrays)
+ name = "nditer(ndim={ndim}, layout={layout}, inputs={arrays})".format(
+ ndim=self.ndim, layout=self.layout, arrays=self.arrays)
+ super(NumpyNdIterType, self).__init__(name)
+
+ @classmethod
+ def _compute_layout(cls, arrays):
+ c = collections.Counter()
+ for a in arrays:
+ if not isinstance(a, Array):
+ continue
+ if a.layout in 'CF' and a.ndim == 1:
+ c['C'] += 1
+ c['F'] += 1
+ elif a.ndim >= 1:
+ c[a.layout] += 1
+ return 'F' if c['F'] > c['C'] else 'C'
+
+ @property
+ def key(self):
+ return self.arrays
+
+ @property
+ def views(self):
+ """
+ The views yielded by the iterator.
+ """
+ return [Array(dtype, 0, 'C') for dtype in self.dtypes]
+
+ @property
+ def yield_type(self):
+ from . import BaseTuple
+ views = self.views
+ if len(views) > 1:
+ return BaseTuple.from_types(views)
+ else:
+ return views[0]
+
+ @cached_property
+ def indexers(self):
+ """
+ A list of (kind, start_dim, end_dim, indices) where:
+ - `kind` is either "flat", "indexed", "0d" or "scalar"
+ - `start_dim` and `end_dim` are the dimension numbers at which
+ this indexing takes place
+ - `indices` is the indices of the indexed arrays in self.arrays
+ """
+ d = collections.OrderedDict()
+ layout = self.layout
+ ndim = self.ndim
+ assert layout in 'CF'
+ for i, a in enumerate(self.arrays):
+ if not isinstance(a, Array):
+ indexer = ('scalar', 0, 0)
+ elif a.ndim == 0:
+ indexer = ('0d', 0, 0)
+ else:
+ if a.layout == layout or (a.ndim == 1 and a.layout in 'CF'):
+ kind = 'flat'
+ else:
+ kind = 'indexed'
+ if layout == 'C':
+ # If iterating in C order, broadcasting is done on the outer indices
+ indexer = (kind, ndim - a.ndim, ndim)
+ else:
+ indexer = (kind, 0, a.ndim)
+ d.setdefault(indexer, []).append(i)
+ return list(k + (v,) for k, v in d.items())
+
+ @cached_property
+ def need_shaped_indexing(self):
+ """
+ Whether iterating on this iterator requires keeping track of
+ individual indices inside the shape. If False, only a single index
+ over the equivalent flat shape is required, which can make the
+ iterator more efficient.
+ """
+ for kind, start_dim, end_dim, _ in self.indexers:
+ if kind in ('0d', 'scalar'):
+ pass
+ elif kind == 'flat':
+ if (start_dim, end_dim) != (0, self.ndim):
+ # Broadcast flat iteration needs shaped indexing
+ # to know when to restart iteration.
+ return True
+ else:
+ return True
+ return False
+
+
+class NumpyNdIndexType(SimpleIteratorType):
+ """
+ Type class for `np.ndindex()` objects.
+ """
+
+ def __init__(self, ndim):
+ from . import UniTuple, intp
+ self.ndim = ndim
+ yield_type = UniTuple(intp, self.ndim)
+ name = "ndindex(ndim={ndim})".format(ndim=ndim)
+ super(NumpyNdIndexType, self).__init__(name, yield_type)
+
+ @property
+ def key(self):
+ return self.ndim
+
+
+class Array(Buffer):
+ """
+ Type class for Numpy arrays.
+ """
+
+ def __init__(self, dtype, ndim, layout, readonly=False, name=None,
+ aligned=True):
+ if readonly:
+ self.mutable = False
+ if (not aligned or
+ (isinstance(dtype, Record) and not dtype.aligned)):
+ self.aligned = False
+ if isinstance(dtype, NestedArray):
+ ndim += dtype.ndim
+ dtype = dtype.dtype
+ if name is None:
+ type_name = "array"
+ if not self.mutable:
+ type_name = "readonly " + type_name
+ if not self.aligned:
+ type_name = "unaligned " + type_name
+ name = "%s(%s, %sd, %s)" % (type_name, dtype, ndim, layout)
+ super(Array, self).__init__(dtype, ndim, layout, name=name)
+
+ @property
+ def mangling_args(self):
+ args = [self.dtype, self.ndim, self.layout,
+ 'mutable' if self.mutable else 'readonly',
+ 'aligned' if self.aligned else 'unaligned']
+ return self.__class__.__name__, args
+
+ def copy(self, dtype=None, ndim=None, layout=None, readonly=None):
+ if dtype is None:
+ dtype = self.dtype
+ if ndim is None:
+ ndim = self.ndim
+ if layout is None:
+ layout = self.layout
+ if readonly is None:
+ readonly = not self.mutable
+ return Array(dtype=dtype, ndim=ndim, layout=layout, readonly=readonly,
+ aligned=self.aligned)
+
+ @property
+ def key(self):
+ return self.dtype, self.ndim, self.layout, self.mutable, self.aligned
+
+ def unify(self, typingctx, other):
+ """
+ Unify this with the *other* Array.
+ """
+ # If other is array and the ndim matches
+ if isinstance(other, Array) and other.ndim == self.ndim:
+ # If dtype matches or other.dtype is undefined (inferred)
+ if other.dtype == self.dtype or not other.dtype.is_precise():
+ if self.layout == other.layout:
+ layout = self.layout
+ else:
+ layout = 'A'
+ readonly = not (self.mutable and other.mutable)
+ aligned = self.aligned and other.aligned
+ return Array(dtype=self.dtype, ndim=self.ndim, layout=layout,
+ readonly=readonly, aligned=aligned)
+
+ def can_convert_to(self, typingctx, other):
+ """
+ Convert this Array to the *other*.
+ """
+ if (isinstance(other, Array) and other.ndim == self.ndim
+ and other.dtype == self.dtype):
+ if (other.layout in ('A', self.layout)
+ and (self.mutable or not other.mutable)
+ and (self.aligned or not other.aligned)):
+ return Conversion.safe
+
+ def is_precise(self):
+ return self.dtype.is_precise()
+
+ @property
+ def box_type(self):
+ """Returns the Python type to box to.
+ """
+ return np.ndarray
+
+ def __repr__(self):
+ return (
+ f"Array({repr(self.dtype)}, {self.ndim}, '{self.layout}', "
+ f"{not self.mutable}, aligned={self.aligned})"
+ )
+
+class ArrayCTypes(Type):
+ """
+ This is the type for `np.ndarray.ctypes`.
+ """
+ def __init__(self, arytype):
+ # This depends on the ndim for the shape and strides attributes,
+ # even though they are not implemented, yet.
+ self.dtype = arytype.dtype
+ self.ndim = arytype.ndim
+ name = "ArrayCTypes(dtype={0}, ndim={1})".format(self.dtype, self.ndim)
+ super(ArrayCTypes, self).__init__(name)
+
+ @property
+ def key(self):
+ return self.dtype, self.ndim
+
+ def can_convert_to(self, typingctx, other):
+ """
+ Convert this type to the corresponding pointer type.
+ This allows passing a array.ctypes object to a C function taking
+ a raw pointer.
+
+ Note that in pure Python, the array.ctypes object can only be
+ passed to a ctypes function accepting a c_void_p, not a typed
+ pointer.
+ """
+ from . import CPointer, voidptr
+ # XXX what about readonly
+ if isinstance(other, CPointer) and other.dtype == self.dtype:
+ return Conversion.safe
+ elif other == voidptr:
+ return Conversion.safe
+
+
+class ArrayFlags(Type):
+ """
+ This is the type for `np.ndarray.flags`.
+ """
+ def __init__(self, arytype):
+ self.array_type = arytype
+ name = "ArrayFlags({0})".format(self.array_type)
+ super(ArrayFlags, self).__init__(name)
+
+ @property
+ def key(self):
+ return self.array_type
+
+
+class NestedArray(Array):
+ """
+ A NestedArray is an array nested within a structured type (which are "void"
+ type in NumPy parlance). Unlike an Array, the shape, and not just the number
+ of dimensions is part of the type of a NestedArray.
+ """
+
+ def __init__(self, dtype, shape):
+ if isinstance(dtype, NestedArray):
+ tmp = Array(dtype.dtype, dtype.ndim, 'C')
+ shape += dtype.shape
+ dtype = tmp.dtype
+ assert dtype.bitwidth % 8 == 0, \
+ "Dtype bitwidth must be a multiple of bytes"
+ self._shape = shape
+ name = "nestedarray(%s, %s)" % (dtype, shape)
+ ndim = len(shape)
+ super(NestedArray, self).__init__(dtype, ndim, 'C', name=name)
+
+ @property
+ def shape(self):
+ return self._shape
+
+ @property
+ def nitems(self):
+ l = 1
+ for s in self.shape:
+ l = l * s
+ return l
+
+ @property
+ def size(self):
+ return self.dtype.bitwidth // 8
+
+ @property
+ def strides(self):
+ stride = self.size
+ strides = []
+ for i in reversed(self._shape):
+ strides.append(stride)
+ stride *= i
+ return tuple(reversed(strides))
+
+ @property
+ def key(self):
+ return self.dtype, self.shape
+
+ def __repr__(self):
+ return f"NestedArray({repr(self.dtype)}, {self.shape})"
+
+
+class NumPyRandomBitGeneratorType(Type):
+ def __init__(self, *args, **kwargs):
+ super(NumPyRandomBitGeneratorType, self).__init__(*args, **kwargs)
+ self.name = 'NumPyRandomBitGeneratorType'
+
+
+class NumPyRandomGeneratorType(Type):
+ def __init__(self, *args, **kwargs):
+ super(NumPyRandomGeneratorType, self).__init__(*args, **kwargs)
+ self.name = 'NumPyRandomGeneratorType'
+
+
+class PolynomialType(Type):
+ def __init__(self, coef, domain=None, window=None, n_args=1):
+ super(PolynomialType, self).__init__(name=f'PolynomialType({coef}, {domain}, {domain}, {n_args})')
+ self.coef = coef
+ self.domain = domain
+ self.window = window
+ # We use n_args to keep track of the number of arguments in the
+ # constructor, since the types of domain and window arguments depend on
+ # that and we need that information when boxing
+ self.n_args = n_args
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/old_scalars.py b/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/old_scalars.py
new file mode 100644
index 0000000000000000000000000000000000000000..ba6dd2e30b1bc068bb74f6a5a5d1ce2ae87d75cd
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/old_scalars.py
@@ -0,0 +1,270 @@
+import enum
+
+import numpy as np
+
+from .abstract import Dummy, Hashable, Literal, Number, Type
+from functools import total_ordering, cached_property
+from numba.core import utils
+from numba.core.typeconv import Conversion
+from numba.np import npdatetime_helpers
+
+
+class Boolean(Hashable):
+
+ def cast_python_value(self, value):
+ return bool(value)
+
+
+def parse_integer_bitwidth(name):
+ for prefix in ('int', 'uint'):
+ if name.startswith(prefix):
+ bitwidth = int(name[len(prefix):])
+ return bitwidth
+
+
+def parse_integer_signed(name):
+ signed = name.startswith('int')
+ return signed
+
+
+@total_ordering
+class Integer(Number):
+ def __init__(self, name, bitwidth=None, signed=None):
+ super(Integer, self).__init__(name)
+ if bitwidth is None:
+ bitwidth = parse_integer_bitwidth(name)
+ if signed is None:
+ signed = parse_integer_signed(name)
+ self.bitwidth = bitwidth
+ self.signed = signed
+
+ @classmethod
+ def from_bitwidth(cls, bitwidth, signed=True):
+ name = ('int%d' if signed else 'uint%d') % bitwidth
+ return cls(name)
+
+ def cast_python_value(self, value):
+ return getattr(np, self.name)(value)
+
+ def __lt__(self, other):
+ if self.__class__ is not other.__class__:
+ return NotImplemented
+ if self.signed != other.signed:
+ return NotImplemented
+ return self.bitwidth < other.bitwidth
+
+ @property
+ def maxval(self):
+ """
+ The maximum value representable by this type.
+ """
+ if self.signed:
+ return (1 << (self.bitwidth - 1)) - 1
+ else:
+ return (1 << self.bitwidth) - 1
+
+ @property
+ def minval(self):
+ """
+ The minimal value representable by this type.
+ """
+ if self.signed:
+ return -(1 << (self.bitwidth - 1))
+ else:
+ return 0
+
+
+class IntegerLiteral(Literal, Integer):
+ def __init__(self, value):
+ self._literal_init(value)
+ name = 'Literal[int]({})'.format(value)
+ basetype = self.literal_type
+ Integer.__init__(
+ self,
+ name=name,
+ bitwidth=basetype.bitwidth,
+ signed=basetype.signed,
+ )
+
+ def can_convert_to(self, typingctx, other):
+ conv = typingctx.can_convert(self.literal_type, other)
+ if conv is not None:
+ return max(conv, Conversion.promote)
+
+
+Literal.ctor_map[int] = IntegerLiteral
+
+
+class BooleanLiteral(Literal, Boolean):
+
+ def __init__(self, value):
+ self._literal_init(value)
+ name = 'Literal[bool]({})'.format(value)
+ Boolean.__init__(
+ self,
+ name=name
+ )
+
+ def can_convert_to(self, typingctx, other):
+ conv = typingctx.can_convert(self.literal_type, other)
+ if conv is not None:
+ return max(conv, Conversion.promote)
+
+
+Literal.ctor_map[bool] = BooleanLiteral
+
+
+@total_ordering
+class Float(Number):
+ def __init__(self, *args, **kws):
+ super(Float, self).__init__(*args, **kws)
+ # Determine bitwidth
+ assert self.name.startswith('float')
+ bitwidth = int(self.name[5:])
+ self.bitwidth = bitwidth
+
+ def cast_python_value(self, value):
+ return getattr(np, self.name)(value)
+
+ def __lt__(self, other):
+ if self.__class__ is not other.__class__:
+ return NotImplemented
+ return self.bitwidth < other.bitwidth
+
+
+@total_ordering
+class Complex(Number):
+ def __init__(self, name, underlying_float, **kwargs):
+ super(Complex, self).__init__(name, **kwargs)
+ self.underlying_float = underlying_float
+ # Determine bitwidth
+ assert self.name.startswith('complex')
+ bitwidth = int(self.name[7:])
+ self.bitwidth = bitwidth
+
+ def cast_python_value(self, value):
+ return getattr(np, self.name)(value)
+
+ def __lt__(self, other):
+ if self.__class__ is not other.__class__:
+ return NotImplemented
+ return self.bitwidth < other.bitwidth
+
+
+class _NPDatetimeBase(Type):
+ """
+ Common base class for np.datetime64 and np.timedelta64.
+ """
+
+ def __init__(self, unit, *args, **kws):
+ name = '%s[%s]' % (self.type_name, unit)
+ self.unit = unit
+ self.unit_code = npdatetime_helpers.DATETIME_UNITS[self.unit]
+ super(_NPDatetimeBase, self).__init__(name, *args, **kws)
+
+ def __lt__(self, other):
+ if self.__class__ is not other.__class__:
+ return NotImplemented
+ # A coarser-grained unit is "smaller", i.e. less precise values
+ # can be represented (but the magnitude of representable values is
+ # also greater...).
+ return self.unit_code < other.unit_code
+
+ def cast_python_value(self, value):
+ cls = getattr(np, self.type_name)
+ if self.unit:
+ return cls(value, self.unit)
+ else:
+ return cls(value)
+
+
+@total_ordering
+class NPTimedelta(_NPDatetimeBase):
+ type_name = 'timedelta64'
+
+@total_ordering
+class NPDatetime(_NPDatetimeBase):
+ type_name = 'datetime64'
+
+
+class EnumClass(Dummy):
+ """
+ Type class for Enum classes.
+ """
+ basename = "Enum class"
+
+ def __init__(self, cls, dtype):
+ assert isinstance(cls, type)
+ assert isinstance(dtype, Type)
+ self.instance_class = cls
+ self.dtype = dtype
+ name = "%s<%s>(%s)" % (self.basename, self.dtype, self.instance_class.__name__)
+ super(EnumClass, self).__init__(name)
+
+ @property
+ def key(self):
+ return self.instance_class, self.dtype
+
+ @cached_property
+ def member_type(self):
+ """
+ The type of this class' members.
+ """
+ return EnumMember(self.instance_class, self.dtype)
+
+
+class IntEnumClass(EnumClass):
+ """
+ Type class for IntEnum classes.
+ """
+ basename = "IntEnum class"
+
+ @cached_property
+ def member_type(self):
+ """
+ The type of this class' members.
+ """
+ return IntEnumMember(self.instance_class, self.dtype)
+
+
+class EnumMember(Type):
+ """
+ Type class for Enum members.
+ """
+ basename = "Enum"
+ class_type_class = EnumClass
+
+ def __init__(self, cls, dtype):
+ assert isinstance(cls, type)
+ assert isinstance(dtype, Type)
+ self.instance_class = cls
+ self.dtype = dtype
+ name = "%s<%s>(%s)" % (self.basename, self.dtype, self.instance_class.__name__)
+ super(EnumMember, self).__init__(name)
+
+ @property
+ def key(self):
+ return self.instance_class, self.dtype
+
+ @property
+ def class_type(self):
+ """
+ The type of this member's class.
+ """
+ return self.class_type_class(self.instance_class, self.dtype)
+
+
+class IntEnumMember(EnumMember):
+ """
+ Type class for IntEnum members.
+ """
+ basename = "IntEnum"
+ class_type_class = IntEnumClass
+
+ def can_convert_to(self, typingctx, other):
+ """
+ Convert IntEnum members to plain integers.
+ """
+ if issubclass(self.instance_class, enum.IntEnum):
+ conv = typingctx.can_convert(self.dtype, other)
+ return max(conv, Conversion.safe)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/scalars.py b/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/scalars.py
new file mode 100644
index 0000000000000000000000000000000000000000..38c49eb126db48c6cef625538467487310502f4c
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/core/types/scalars.py
@@ -0,0 +1,12 @@
+import sys
+from numba.core.utils import _RedirectSubpackage
+from numba.core import config
+
+if config.USE_LEGACY_TYPE_SYSTEM: # type: ignore
+ sys.modules[__name__] = _RedirectSubpackage(
+ locals(), "numba.core.types.old_scalars"
+ )
+else:
+ sys.modules[__name__] = _RedirectSubpackage(
+ locals(), "numba.core.types.new_scalars"
+ )
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..7a30bbd0c058ecb730c798f91174c12c110c88f0
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/__init__.py
@@ -0,0 +1,3 @@
+from .context import BaseContext, Context
+from .templates import (signature, make_concrete_template, Signature,
+ fold_arguments)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d1e9f2f02ec7891dbecc2640805516533472228f
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/__pycache__/arraydecl.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/__pycache__/arraydecl.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..89a270f5ed0b5e8a9a4a7318832df1dfee462a30
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/__pycache__/arraydecl.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/__pycache__/asnumbatype.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/__pycache__/asnumbatype.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..412f99085210b9c2ccdb5b1c60feaecb80bb7aa9
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/__pycache__/asnumbatype.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/__pycache__/bufproto.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/__pycache__/bufproto.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1707c157b86e67eac7ab3f6a5c7b6cef008b71cd
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/__pycache__/bufproto.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/__pycache__/builtins.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/__pycache__/builtins.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..97667c75a0e8f9981781517ce8906ac0be8d6f62
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/__pycache__/builtins.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/__pycache__/cffi_utils.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/__pycache__/cffi_utils.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0ebda3a8b9d8caffaa1bcb8e7785b3b24aab15ec
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/__pycache__/cffi_utils.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/__pycache__/cmathdecl.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/__pycache__/cmathdecl.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d5df0fe31bec42c51c707098281437800b8d3374
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/__pycache__/cmathdecl.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/__pycache__/collections.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/__pycache__/collections.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8adcd1284190d0b299685339e30d176c5a6f7f8d
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/__pycache__/collections.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/__pycache__/context.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/__pycache__/context.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..83217f0916bc24db1526f7e9201de031b7ba97eb
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/__pycache__/context.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/__pycache__/ctypes_utils.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/__pycache__/ctypes_utils.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ecb38878dd839b69f7bcaad62a115ab2c64ea9f7
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/__pycache__/ctypes_utils.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/__pycache__/dictdecl.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/__pycache__/dictdecl.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f20c725be5ae95f4e8ccca08d14c9a491bf48c78
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/__pycache__/dictdecl.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/__pycache__/enumdecl.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/__pycache__/enumdecl.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..81b997ae397781b3aebe5c95245fb1e7d26b024f
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/__pycache__/enumdecl.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/__pycache__/listdecl.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/__pycache__/listdecl.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..79cd33bdd17217c866c5451537da9672c2926962
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/__pycache__/listdecl.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/__pycache__/mathdecl.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/__pycache__/mathdecl.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..710f5bdec369f22f6d46880615ea77258058793d
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/__pycache__/mathdecl.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/__pycache__/new_builtins.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/__pycache__/new_builtins.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b5a9aff1981d80a3aecfd07d813551caa155d9e0
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/__pycache__/new_builtins.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/__pycache__/new_cmathdecl.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/__pycache__/new_cmathdecl.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c96b096177d3936befd8762051aefc4458ad25f0
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/__pycache__/new_cmathdecl.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/__pycache__/new_mathdecl.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/__pycache__/new_mathdecl.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..30fd61a7a5c06ae6a5785460857b5681d5c593f6
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/__pycache__/new_mathdecl.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/__pycache__/npdatetime.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/__pycache__/npdatetime.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..26bb961f31c00b27dd61781749e2b9381f4c7686
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/__pycache__/npdatetime.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/__pycache__/npydecl.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/__pycache__/npydecl.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..888312e2938d4db8e91ca4f092032a480fb35b5c
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/__pycache__/npydecl.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/__pycache__/old_builtins.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/__pycache__/old_builtins.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e4f77039eee602e94a053c068ee9ee9c7a01b396
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/__pycache__/old_builtins.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/__pycache__/old_cmathdecl.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/__pycache__/old_cmathdecl.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cfb489e5ee6a56ad3dc1107ddee03ce419004fd6
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/__pycache__/old_cmathdecl.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/__pycache__/old_mathdecl.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/__pycache__/old_mathdecl.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1db422dab110768040247b23f36588a50d876e02
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/__pycache__/old_mathdecl.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/__pycache__/setdecl.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/__pycache__/setdecl.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0593393e929a63ba2ae282494b1a5e2108a9c19f
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/__pycache__/setdecl.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/__pycache__/templates.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/__pycache__/templates.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b3b4c45e1b1b1debc7e59793ba75bae0ca15aa16
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/__pycache__/templates.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/__pycache__/typeof.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/__pycache__/typeof.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a01203f951a00c18d34090dcb262c20ab4fe97d7
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/__pycache__/typeof.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/arraydecl.py b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/arraydecl.py
new file mode 100644
index 0000000000000000000000000000000000000000..7ef5e493cfd718ae1376f82b4f04d1bc2a36063a
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/arraydecl.py
@@ -0,0 +1,880 @@
+import numpy as np
+import operator
+from collections import namedtuple
+
+from numba.core import types, utils
+from numba.core.typing.templates import (AttributeTemplate, AbstractTemplate,
+ infer, infer_global, infer_getattr,
+ signature, bound_function)
+# import time side effect: array operations requires typing support of sequence
+# defined in collections: e.g. array.shape[i]
+from numba.core.typing import collections
+from numba.core.errors import (TypingError, RequireLiteralValue, NumbaTypeError,
+ NumbaNotImplementedError, NumbaAssertionError,
+ NumbaKeyError, NumbaIndexError, NumbaValueError)
+from numba.core.cgutils import is_nonelike
+
+numpy_version = tuple(map(int, np.__version__.split('.')[:2]))
+
+
+Indexing = namedtuple("Indexing", ("index", "result", "advanced"))
+
+
+def get_array_index_type(ary, idx):
+ """
+ Returns None or a tuple-3 for the types of the input array, index, and
+ resulting type of ``array[index]``.
+
+ Note: This is shared logic for ndarray getitem and setitem.
+ """
+ if not isinstance(ary, types.Buffer):
+ return
+
+ ndim = ary.ndim
+
+ left_indices = []
+ right_indices = []
+ ellipsis_met = False
+ advanced = False
+ num_newaxis = 0
+
+ if not isinstance(idx, types.BaseTuple):
+ idx = [idx]
+
+ # Here, a subspace is considered as a contiguous group of advanced indices.
+ # num_subspaces keeps track of the number of such
+ # contiguous groups.
+ in_subspace = False
+ num_subspaces = 0
+ array_indices = 0
+
+ # Walk indices
+ for ty in idx:
+ if ty is types.ellipsis:
+ if ellipsis_met:
+ raise NumbaTypeError(
+ "Only one ellipsis allowed in array indices "
+ "(got %s)" % (idx,))
+ ellipsis_met = True
+ in_subspace = False
+ elif isinstance(ty, types.SliceType):
+ # If we encounter a non-advanced index while in a
+ # subspace then that subspace ends.
+ in_subspace = False
+ # In advanced indexing, any index broadcastable to an
+ # array is considered an advanced index. Hence all the
+ # branches below are considered as advanced indices.
+ elif isinstance(ty, types.Integer):
+ # Normalize integer index
+ ty = types.intp if ty.signed else types.uintp
+ # Integer indexing removes the given dimension
+ ndim -= 1
+ # If we're within a subspace/contiguous group of
+ # advanced indices then no action is necessary
+ # since we've already counted that subspace once.
+ if not in_subspace:
+ # If we're not within a subspace and we encounter
+ # this branch then we have a new subspace/group.
+ num_subspaces += 1
+ in_subspace = True
+ elif (isinstance(ty, types.Array) and ty.ndim == 0
+ and isinstance(ty.dtype, types.Integer)):
+ # 0-d array used as integer index
+ ndim -= 1
+ if not in_subspace:
+ num_subspaces += 1
+ in_subspace = True
+ elif (isinstance(ty, types.Array)
+ and isinstance(ty.dtype, (types.Integer, types.Boolean))):
+ if ty.ndim > 1:
+ # Advanced indexing limitation # 1
+ raise NumbaTypeError(
+ "Multi-dimensional indices are not supported.")
+ array_indices += 1
+ # The condition for activating advanced indexing is simply
+ # having at least one array with size > 1.
+ advanced = True
+ if not in_subspace:
+ num_subspaces += 1
+ in_subspace = True
+ elif (is_nonelike(ty)):
+ ndim += 1
+ num_newaxis += 1
+ else:
+ raise NumbaTypeError("Unsupported array index type %s in %s"
+ % (ty, idx))
+ (right_indices if ellipsis_met else left_indices).append(ty)
+
+ if advanced:
+ if array_indices > 1:
+ # Advanced indexing limitation # 2
+ msg = "Using more than one non-scalar array index is unsupported."
+ raise NumbaTypeError(msg)
+
+ if num_subspaces > 1:
+ # Advanced indexing limitation # 3
+ msg = ("Using more than one indexing subspace is unsupported."
+ " An indexing subspace is a group of one or more"
+ " consecutive indices comprising integer or array types.")
+ raise NumbaTypeError(msg)
+
+ # Only Numpy arrays support advanced indexing
+ if advanced and not isinstance(ary, types.Array):
+ return
+
+ # Check indices and result dimensionality
+ all_indices = left_indices + right_indices
+ if ellipsis_met:
+ assert right_indices[0] is types.ellipsis
+ del right_indices[0]
+
+ n_indices = len(all_indices) - ellipsis_met - num_newaxis
+ if n_indices > ary.ndim:
+ raise NumbaTypeError("cannot index %s with %d indices: %s"
+ % (ary, n_indices, idx))
+ if n_indices == ary.ndim and ndim == 0 and not ellipsis_met:
+ # Full integer indexing => scalar result
+ # (note if ellipsis is present, a 0-d view is returned instead)
+ res = ary.dtype
+
+ elif advanced:
+ # Result is a copy
+ res = ary.copy(ndim=ndim, layout='C', readonly=False)
+
+ else:
+ # Result is a view
+ if ary.slice_is_copy:
+ # Avoid view semantics when the original type creates a copy
+ # when slicing.
+ return
+
+ # Infer layout
+ layout = ary.layout
+
+ def keeps_contiguity(ty, is_innermost):
+ # A slice can only keep an array contiguous if it is the
+ # innermost index and it is not strided
+ return (ty is types.ellipsis or isinstance(ty, types.Integer)
+ or (is_innermost and isinstance(ty, types.SliceType)
+ and not ty.has_step))
+
+ def check_contiguity(outer_indices):
+ """
+ Whether indexing with the given indices (from outer to inner in
+ physical layout order) can keep an array contiguous.
+ """
+ for ty in outer_indices[:-1]:
+ if not keeps_contiguity(ty, False):
+ return False
+ if outer_indices and not keeps_contiguity(outer_indices[-1], True):
+ return False
+ return True
+
+ if layout == 'C':
+ # Integer indexing on the left keeps the array C-contiguous
+ if n_indices == ary.ndim:
+ # If all indices are there, ellipsis's place is indifferent
+ left_indices = left_indices + right_indices
+ right_indices = []
+ if right_indices:
+ layout = 'A'
+ elif not check_contiguity(left_indices):
+ layout = 'A'
+ elif layout == 'F':
+ # Integer indexing on the right keeps the array F-contiguous
+ if n_indices == ary.ndim:
+ # If all indices are there, ellipsis's place is indifferent
+ right_indices = left_indices + right_indices
+ left_indices = []
+ if left_indices:
+ layout = 'A'
+ elif not check_contiguity(right_indices[::-1]):
+ layout = 'A'
+
+ if ndim == 0:
+ # Implicitly convert to a scalar if the output ndim==0
+ res = ary.dtype
+ else:
+ res = ary.copy(ndim=ndim, layout=layout)
+
+ # Re-wrap indices
+ if isinstance(idx, types.BaseTuple):
+ idx = types.BaseTuple.from_types(all_indices)
+ else:
+ idx, = all_indices
+
+ return Indexing(idx, res, advanced)
+
+
+@infer_global(operator.getitem)
+class GetItemBuffer(AbstractTemplate):
+ def generic(self, args, kws):
+ assert not kws
+ [ary, idx] = args
+ out = get_array_index_type(ary, idx)
+ if out is not None:
+ return signature(out.result, ary, out.index)
+
+
+@infer_global(operator.setitem)
+class SetItemBuffer(AbstractTemplate):
+ def generic(self, args, kws):
+ assert not kws
+ ary, idx, val = args
+ if not isinstance(ary, types.Buffer):
+ return
+ if not ary.mutable:
+ msg = f"Cannot modify readonly array of type: {ary}"
+ raise NumbaTypeError(msg)
+ out = get_array_index_type(ary, idx)
+ if out is None:
+ return
+
+ idx = out.index
+ res = out.result # res is the result type of the access ary[idx]
+ if isinstance(res, types.Array):
+ # Indexing produces an array
+ if isinstance(val, types.Array):
+ if not self.context.can_convert(val.dtype, res.dtype):
+ # DType conversion not possible
+ return
+ else:
+ res = val
+ elif isinstance(val, types.Sequence):
+ if (res.ndim == 1 and
+ self.context.can_convert(val.dtype, res.dtype)):
+ # Allow assignment of sequence to 1d array
+ res = val
+ else:
+ # NOTE: sequence-to-array broadcasting is unsupported
+ return
+ else:
+ # Allow scalar broadcasting
+ if self.context.can_convert(val, res.dtype):
+ res = res.dtype
+ else:
+ # Incompatible scalar type
+ return
+ elif not isinstance(val, types.Array):
+ # Single item assignment
+ if not self.context.can_convert(val, res):
+ # if the array dtype is not yet defined
+ if not res.is_precise():
+ # set the array type to use the dtype of value (RHS)
+ newary = ary.copy(dtype=val)
+ return signature(types.none, newary, idx, res)
+ else:
+ return
+ res = val
+ elif (isinstance(val, types.Array) and val.ndim == 0
+ and self.context.can_convert(val.dtype, res)):
+ # val is an array(T, 0d, O), where T is the type of res, O is order
+ res = val
+ else:
+ return
+ return signature(types.none, ary, idx, res)
+
+
+def normalize_shape(shape):
+ if isinstance(shape, types.UniTuple):
+ if isinstance(shape.dtype, types.Integer):
+ dimtype = types.intp if shape.dtype.signed else types.uintp
+ return types.UniTuple(dimtype, len(shape))
+
+ elif isinstance(shape, types.Tuple) and shape.count == 0:
+ # Force (0 x intp) for consistency with other shapes
+ return types.UniTuple(types.intp, 0)
+
+
+@infer_getattr
+class ArrayAttribute(AttributeTemplate):
+ key = types.Array
+
+ def resolve_dtype(self, ary):
+ return types.DType(ary.dtype)
+
+ def resolve_nbytes(self, ary):
+ return types.intp
+
+ def resolve_itemsize(self, ary):
+ return types.intp
+
+ def resolve_shape(self, ary):
+ return types.UniTuple(types.intp, ary.ndim)
+
+ def resolve_strides(self, ary):
+ return types.UniTuple(types.intp, ary.ndim)
+
+ def resolve_ndim(self, ary):
+ return types.intp
+
+ def resolve_size(self, ary):
+ return types.intp
+
+ def resolve_flat(self, ary):
+ return types.NumpyFlatType(ary)
+
+ def resolve_ctypes(self, ary):
+ return types.ArrayCTypes(ary)
+
+ def resolve_flags(self, ary):
+ return types.ArrayFlags(ary)
+
+ def resolve_T(self, ary):
+ if ary.ndim <= 1:
+ retty = ary
+ else:
+ layout = {"C": "F", "F": "C"}.get(ary.layout, "A")
+ retty = ary.copy(layout=layout)
+ return retty
+
+ def resolve_real(self, ary):
+ return self._resolve_real_imag(ary, attr='real')
+
+ def resolve_imag(self, ary):
+ return self._resolve_real_imag(ary, attr='imag')
+
+ def _resolve_real_imag(self, ary, attr):
+ if ary.dtype in types.complex_domain:
+ return ary.copy(dtype=ary.dtype.underlying_float, layout='A')
+ elif ary.dtype in types.number_domain:
+ res = ary.copy(dtype=ary.dtype)
+ if attr == 'imag':
+ res = res.copy(readonly=True)
+ return res
+ else:
+ msg = "cannot access .{} of array of {}"
+ raise TypingError(msg.format(attr, ary.dtype))
+
+ @bound_function("array.transpose")
+ def resolve_transpose(self, ary, args, kws):
+ def sentry_shape_scalar(ty):
+ if ty in types.number_domain:
+ # Guard against non integer type
+ if not isinstance(ty, types.Integer):
+ msg = "transpose() arg cannot be {0}".format(ty)
+ raise TypingError(msg)
+ return True
+ else:
+ return False
+
+ assert not kws
+ if len(args) == 0:
+ return signature(self.resolve_T(ary))
+
+ if len(args) == 1:
+ shape, = args
+
+ if sentry_shape_scalar(shape):
+ assert ary.ndim == 1
+ return signature(ary, *args)
+
+ if isinstance(shape, types.NoneType):
+ return signature(self.resolve_T(ary))
+
+ shape = normalize_shape(shape)
+ if shape is None:
+ return
+
+ assert ary.ndim == shape.count
+ return signature(self.resolve_T(ary).copy(layout="A"), shape)
+
+ else:
+ if any(not sentry_shape_scalar(a) for a in args):
+ msg = "transpose({0}) is not supported".format(
+ ', '.join(args))
+ raise TypingError(msg)
+ assert ary.ndim == len(args)
+ return signature(self.resolve_T(ary).copy(layout="A"), *args)
+
+ @bound_function("array.copy")
+ def resolve_copy(self, ary, args, kws):
+ assert not args
+ assert not kws
+ retty = ary.copy(layout="C", readonly=False)
+ return signature(retty)
+
+ @bound_function("array.item")
+ def resolve_item(self, ary, args, kws):
+ assert not kws
+ # We don't support explicit arguments as that's exactly equivalent
+ # to regular indexing. The no-argument form is interesting to
+ # allow some degree of genericity when writing functions.
+ if not args:
+ return signature(ary.dtype)
+
+ if numpy_version < (2, 0):
+ @bound_function("array.itemset")
+ def resolve_itemset(self, ary, args, kws):
+ assert not kws
+ # We don't support explicit arguments as that's exactly equivalent
+ # to regular indexing. The no-argument form is interesting to
+ # allow some degree of genericity when writing functions.
+ if len(args) == 1:
+ return signature(types.none, ary.dtype)
+
+ @bound_function("array.nonzero")
+ def resolve_nonzero(self, ary, args, kws):
+ assert not args
+ assert not kws
+ if ary.ndim == 0 and numpy_version >= (2, 1):
+ raise NumbaValueError(
+ "Calling nonzero on 0d arrays is not allowed."
+ " Use np.atleast_1d(scalar).nonzero() instead."
+ )
+ # 0-dim arrays return one result array
+ ndim = max(ary.ndim, 1)
+ retty = types.UniTuple(types.Array(types.intp, 1, 'C'), ndim)
+ return signature(retty)
+
+ @bound_function("array.reshape")
+ def resolve_reshape(self, ary, args, kws):
+ def sentry_shape_scalar(ty):
+ if ty in types.number_domain:
+ # Guard against non integer type
+ if not isinstance(ty, types.Integer):
+ raise TypingError("reshape() arg cannot be {0}".format(ty))
+ return True
+ else:
+ return False
+
+ assert not kws
+ if ary.layout not in 'CF':
+ # only work for contiguous array
+ raise TypingError("reshape() supports contiguous array only")
+
+ if len(args) == 1:
+ # single arg
+ shape, = args
+
+ if sentry_shape_scalar(shape):
+ ndim = 1
+ else:
+ shape = normalize_shape(shape)
+ if shape is None:
+ return
+ ndim = shape.count
+ retty = ary.copy(ndim=ndim)
+ return signature(retty, shape)
+
+ elif len(args) == 0:
+ # no arg
+ raise TypingError("reshape() take at least one arg")
+
+ else:
+ # vararg case
+ if any(not sentry_shape_scalar(a) for a in args):
+ raise TypingError("reshape({0}) is not supported".format(
+ ', '.join(map(str, args))))
+
+ retty = ary.copy(ndim=len(args))
+ return signature(retty, *args)
+
+ @bound_function("array.sort")
+ def resolve_sort(self, ary, args, kws):
+ assert not args
+ assert not kws
+ return signature(types.none)
+
+ @bound_function("array.argsort")
+ def resolve_argsort(self, ary, args, kws):
+ assert not args
+ kwargs = dict(kws)
+ kind = kwargs.pop('kind', types.StringLiteral('quicksort'))
+ if not isinstance(kind, types.StringLiteral):
+ raise TypingError('"kind" must be a string literal')
+ if kwargs:
+ msg = "Unsupported keywords: {!r}"
+ raise TypingError(msg.format([k for k in kwargs.keys()]))
+ if ary.ndim == 1:
+ def argsort_stub(kind='quicksort'):
+ pass
+ pysig = utils.pysignature(argsort_stub)
+ sig = signature(types.Array(types.intp, 1, 'C'), kind).replace(pysig=pysig)
+ return sig
+
+ @bound_function("array.view")
+ def resolve_view(self, ary, args, kws):
+ from .npydecl import parse_dtype
+ assert not kws
+ dtype, = args
+ dtype = parse_dtype(dtype)
+ if dtype is None:
+ return
+ retty = ary.copy(dtype=dtype)
+ return signature(retty, *args)
+
+ @bound_function("array.astype")
+ def resolve_astype(self, ary, args, kws):
+ from .npydecl import parse_dtype
+ assert not kws
+ dtype, = args
+ if isinstance(dtype, types.UnicodeType):
+ raise RequireLiteralValue(("array.astype if dtype is a string it "
+ "must be constant"))
+ dtype = parse_dtype(dtype)
+ if dtype is None:
+ return
+ if not self.context.can_convert(ary.dtype, dtype):
+ raise TypingError("astype(%s) not supported on %s: "
+ "cannot convert from %s to %s"
+ % (dtype, ary, ary.dtype, dtype))
+ layout = ary.layout if ary.layout in 'CF' else 'C'
+ # reset the write bit irrespective of whether the cast type is the same
+ # as the current dtype, this replicates numpy
+ retty = ary.copy(dtype=dtype, layout=layout, readonly=False)
+ return signature(retty, *args)
+
+ @bound_function("array.ravel")
+ def resolve_ravel(self, ary, args, kws):
+ # Only support no argument version (default order='C')
+ assert not kws
+ assert not args
+ copy_will_be_made = ary.layout != 'C'
+ readonly = not (copy_will_be_made or ary.mutable)
+ return signature(ary.copy(ndim=1, layout='C', readonly=readonly))
+
+ @bound_function("array.flatten")
+ def resolve_flatten(self, ary, args, kws):
+ # Only support no argument version (default order='C')
+ assert not kws
+ assert not args
+ # To ensure that Numba behaves exactly like NumPy,
+ # we also clear the read-only flag when doing a "flatten"
+ # Why? Two reasons:
+ # Because flatten always returns a copy. (see NumPy docs for "flatten")
+ # And because a copy always returns a writeable array.
+ # ref: https://numpy.org/doc/stable/reference/generated/numpy.copy.html
+ return signature(ary.copy(ndim=1, layout='C', readonly=False))
+
+ def generic_resolve(self, ary, attr):
+ # Resolution of other attributes, for record arrays
+ if isinstance(ary.dtype, types.Record):
+ if attr in ary.dtype.fields:
+ attr_dtype = ary.dtype.typeof(attr)
+ if isinstance(attr_dtype, types.NestedArray):
+ return ary.copy(
+ dtype=attr_dtype.dtype,
+ ndim=ary.ndim + attr_dtype.ndim,
+ layout='A'
+ )
+ else:
+ return ary.copy(dtype=attr_dtype, layout='A')
+
+
+@infer_getattr
+class DTypeAttr(AttributeTemplate):
+ key = types.DType
+
+ def resolve_type(self, ary):
+ # Wrap the numeric type in NumberClass
+ return types.NumberClass(ary.dtype)
+
+ def resolve_kind(self, ary):
+ if isinstance(ary.key, types.scalars.Float):
+ val = 'f'
+ elif isinstance(ary.key, types.scalars.Integer):
+ val = 'i'
+ else:
+ return None # other types not supported yet
+ return types.StringLiteral(val)
+
+
+@infer
+class StaticGetItemArray(AbstractTemplate):
+ key = "static_getitem"
+
+ def generic(self, args, kws):
+ # Resolution of members for record and structured arrays
+ ary, idx = args
+ if (isinstance(ary, types.Array) and isinstance(idx, str) and
+ isinstance(ary.dtype, types.Record)):
+ if idx in ary.dtype.fields:
+ attr_dtype = ary.dtype.typeof(idx)
+ if isinstance(attr_dtype, types.NestedArray):
+ ret = ary.copy(
+ dtype=attr_dtype.dtype,
+ ndim=ary.ndim + attr_dtype.ndim,
+ layout='A'
+ )
+ return signature(ret, *args)
+ else:
+ ret = ary.copy(dtype=attr_dtype, layout='A')
+ return signature(ret, *args)
+
+
+@infer_getattr
+class RecordAttribute(AttributeTemplate):
+ key = types.Record
+
+ def generic_resolve(self, record, attr):
+ ret = record.typeof(attr)
+ assert ret
+ return ret
+
+
+@infer
+class StaticGetItemRecord(AbstractTemplate):
+ key = "static_getitem"
+
+ def generic(self, args, kws):
+ # Resolution of members for records
+ record, idx = args
+ if isinstance(record, types.Record) and isinstance(idx, str):
+ if idx not in record.fields:
+ raise NumbaKeyError(f"Field '{idx}' was not found in record "
+ "with fields "
+ f"{tuple(record.fields.keys())}")
+ ret = record.typeof(idx)
+ assert ret
+ return signature(ret, *args)
+
+
+@infer_global(operator.getitem)
+class StaticGetItemLiteralRecord(AbstractTemplate):
+ def generic(self, args, kws):
+ # Resolution of members for records
+ record, idx = args
+ if isinstance(record, types.Record):
+ if isinstance(idx, types.StringLiteral):
+ if idx.literal_value not in record.fields:
+ msg = (f"Field '{idx.literal_value}' was not found in "
+ f"record with fields {tuple(record.fields.keys())}")
+ raise NumbaKeyError(msg)
+ ret = record.typeof(idx.literal_value)
+ assert ret
+ return signature(ret, *args)
+ elif isinstance(idx, types.IntegerLiteral):
+ if idx.literal_value >= len(record.fields):
+ msg = f"Requested index {idx.literal_value} is out of range"
+ raise NumbaIndexError(msg)
+ field_names = list(record.fields)
+ ret = record.typeof(field_names[idx.literal_value])
+ assert ret
+ return signature(ret, *args)
+
+
+@infer
+class StaticSetItemRecord(AbstractTemplate):
+ key = "static_setitem"
+
+ def generic(self, args, kws):
+ # Resolution of members for record and structured arrays
+ record, idx, value = args
+ if isinstance(record, types.Record):
+ if isinstance(idx, str):
+ expectedty = record.typeof(idx)
+ if self.context.can_convert(value, expectedty) is not None:
+ return signature(types.void, record, types.literal(idx),
+ value)
+ elif isinstance(idx, int):
+ if idx >= len(record.fields):
+ msg = f"Requested index {idx} is out of range"
+ raise NumbaIndexError(msg)
+ str_field = list(record.fields)[idx]
+ expectedty = record.typeof(str_field)
+ if self.context.can_convert(value, expectedty) is not None:
+ return signature(types.void, record, types.literal(idx),
+ value)
+
+
+@infer_global(operator.setitem)
+class StaticSetItemLiteralRecord(AbstractTemplate):
+ def generic(self, args, kws):
+ # Resolution of members for records
+ target, idx, value = args
+ if isinstance(target, types.Record) and isinstance(idx, types.StringLiteral):
+ if idx.literal_value not in target.fields:
+ msg = (f"Field '{idx.literal_value}' was not found in record "
+ f"with fields {tuple(target.fields.keys())}")
+ raise NumbaKeyError(msg)
+ expectedty = target.typeof(idx.literal_value)
+ if self.context.can_convert(value, expectedty) is not None:
+ return signature(types.void, target, idx, value)
+
+
+@infer_getattr
+class ArrayCTypesAttribute(AttributeTemplate):
+ key = types.ArrayCTypes
+
+ def resolve_data(self, ctinfo):
+ return types.uintp
+
+
+@infer_getattr
+class ArrayFlagsAttribute(AttributeTemplate):
+ key = types.ArrayFlags
+
+ def resolve_contiguous(self, ctflags):
+ return types.boolean
+
+ def resolve_c_contiguous(self, ctflags):
+ return types.boolean
+
+ def resolve_f_contiguous(self, ctflags):
+ return types.boolean
+
+
+@infer_getattr
+class NestedArrayAttribute(ArrayAttribute):
+ key = types.NestedArray
+
+
+def _expand_integer(ty):
+ """
+ If *ty* is an integer, expand it to a machine int (like Numpy).
+ """
+ if isinstance(ty, types.Integer):
+ if ty.signed:
+ return max(types.intp, ty)
+ else:
+ return max(types.uintp, ty)
+ elif isinstance(ty, types.Boolean):
+ return types.intp
+ else:
+ return ty
+
+
+def generic_homog(self, args, kws):
+ if args:
+ raise NumbaAssertionError("args not supported")
+ if kws:
+ raise NumbaAssertionError("kws not supported")
+
+ return signature(self.this.dtype, recvr=self.this)
+
+
+def generic_expand(self, args, kws):
+ assert not args
+ assert not kws
+ return signature(_expand_integer(self.this.dtype), recvr=self.this)
+
+
+def sum_expand(self, args, kws):
+ """
+ sum can be called with or without an axis parameter, and with or without
+ a dtype parameter
+ """
+ pysig = None
+ if 'axis' in kws and 'dtype' not in kws:
+ def sum_stub(axis):
+ pass
+ pysig = utils.pysignature(sum_stub)
+ # rewrite args
+ args = list(args) + [kws['axis']]
+ elif 'dtype' in kws and 'axis' not in kws:
+ def sum_stub(dtype):
+ pass
+ pysig = utils.pysignature(sum_stub)
+ # rewrite args
+ args = list(args) + [kws['dtype']]
+ elif 'dtype' in kws and 'axis' in kws:
+ def sum_stub(axis, dtype):
+ pass
+ pysig = utils.pysignature(sum_stub)
+ # rewrite args
+ args = list(args) + [kws['axis'], kws['dtype']]
+
+ args_len = len(args)
+ assert args_len <= 2
+ if args_len == 0:
+ # No axis or dtype parameter so the return type of the summation is a scalar
+ # of the type of the array.
+ out = signature(_expand_integer(self.this.dtype), *args,
+ recvr=self.this)
+ elif args_len == 1 and 'dtype' not in kws:
+ # There is an axis parameter, either arg or kwarg
+ if self.this.ndim == 1:
+ # 1d reduces to a scalar
+ return_type = _expand_integer(self.this.dtype)
+ else:
+ # the return type of this summation is an array of dimension one
+ # less than the input array.
+ return_type = types.Array(dtype=_expand_integer(self.this.dtype),
+ ndim=self.this.ndim-1, layout='C')
+ out = signature(return_type, *args, recvr=self.this)
+
+ elif args_len == 1 and 'dtype' in kws:
+ # No axis parameter so the return type of the summation is a scalar
+ # of the dtype parameter.
+ from .npydecl import parse_dtype
+ dtype, = args
+ dtype = parse_dtype(dtype)
+ out = signature(dtype, *args, recvr=self.this)
+
+ elif args_len == 2:
+ # There is an axis and dtype parameter, either arg or kwarg
+ from .npydecl import parse_dtype
+ dtype = parse_dtype(args[1])
+ return_type = dtype
+ if self.this.ndim != 1:
+ # 1d reduces to a scalar, 2d and above reduce dim by 1
+ # the return type of this summation is an array of dimension one
+ # less than the input array.
+ return_type = types.Array(dtype=return_type,
+ ndim=self.this.ndim-1, layout='C')
+ out = signature(return_type, *args, recvr=self.this)
+ else:
+ pass
+ return out.replace(pysig=pysig)
+
+
+def generic_expand_cumulative(self, args, kws):
+ if args:
+ raise NumbaAssertionError("args unsupported")
+ if kws:
+ raise NumbaAssertionError("kwargs unsupported")
+ assert isinstance(self.this, types.Array)
+ return_type = types.Array(dtype=_expand_integer(self.this.dtype),
+ ndim=1, layout='C')
+ return signature(return_type, recvr=self.this)
+
+
+def generic_hetero_real(self, args, kws):
+ assert not args
+ assert not kws
+ if isinstance(self.this.dtype, (types.Integer, types.Boolean)):
+ return signature(types.float64, recvr=self.this)
+ return signature(self.this.dtype, recvr=self.this)
+
+
+def generic_hetero_always_real(self, args, kws):
+ assert not args
+ assert not kws
+ if isinstance(self.this.dtype, (types.Integer, types.Boolean)):
+ return signature(types.float64, recvr=self.this)
+ if isinstance(self.this.dtype, types.Complex):
+ return signature(self.this.dtype.underlying_float, recvr=self.this)
+ return signature(self.this.dtype, recvr=self.this)
+
+
+def generic_index(self, args, kws):
+ assert not args
+ assert not kws
+ return signature(types.intp, recvr=self.this)
+
+
+def install_array_method(name, generic, prefer_literal=True):
+ my_attr = {"key": "array." + name, "generic": generic,
+ "prefer_literal": prefer_literal}
+ temp_class = type("Array_" + name, (AbstractTemplate,), my_attr)
+
+ def array_attribute_attachment(self, ary):
+ return types.BoundFunction(temp_class, ary)
+
+ setattr(ArrayAttribute, "resolve_" + name, array_attribute_attachment)
+
+
+# Functions that return a machine-width type, to avoid overflows
+install_array_method("sum", sum_expand, prefer_literal=True)
+
+
+@infer_global(operator.eq)
+class CmpOpEqArray(AbstractTemplate):
+ #key = operator.eq
+
+ def generic(self, args, kws):
+ assert not kws
+ [va, vb] = args
+ if isinstance(va, types.Array) and va == vb:
+ return signature(va.copy(dtype=types.boolean), va, vb)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/asnumbatype.py b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/asnumbatype.py
new file mode 100644
index 0000000000000000000000000000000000000000..ec6b22847b056b286abab09f70140eee4981067f
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/asnumbatype.py
@@ -0,0 +1,124 @@
+import inspect
+import typing as py_typing
+
+from numba.core.typing.typeof import typeof
+from numba.core import errors, types
+
+
+class AsNumbaTypeRegistry:
+ """
+ A registry for python typing declarations. This registry stores a lookup
+ table for simple cases (e.g. int) and a list of functions for more
+ complicated cases (e.g. generics like List[int]).
+
+ The as_numba_type registry is meant to work statically on type annotations
+ at compile type, not dynamically on instances at runtime. To check the type
+ of an object at runtime, see numba.typeof.
+ """
+
+ def __init__(self):
+ self.lookup = {
+ type(example): typeof(example)
+ for example in [
+ 0,
+ 0.0,
+ complex(0),
+ "numba",
+ True,
+ None,
+ ]
+ }
+
+ self.functions = [self._builtin_infer, self._numba_type_infer]
+
+ def _numba_type_infer(self, py_type):
+ if isinstance(py_type, types.Type):
+ return py_type
+
+ def _builtin_infer(self, py_type):
+ if not isinstance(py_type, py_typing._GenericAlias):
+ return
+
+ if getattr(py_type, "__origin__", None) is py_typing.Union:
+ if len(py_type.__args__) != 2:
+ raise errors.TypingError(
+ "Cannot type Union of more than two types")
+
+ (arg_1_py, arg_2_py) = py_type.__args__
+
+ if arg_2_py is type(None): # noqa: E721
+ return types.Optional(self.infer(arg_1_py))
+ elif arg_1_py is type(None): # noqa: E721
+ return types.Optional(self.infer(arg_2_py))
+ else:
+ raise errors.TypingError(
+ "Cannot type Union that is not an Optional "
+ f"(neither type type {arg_2_py} is not NoneType")
+
+ if getattr(py_type, "__origin__", None) is list:
+ (element_py,) = py_type.__args__
+ return types.ListType(self.infer(element_py))
+
+ if getattr(py_type, "__origin__", None) is dict:
+ key_py, value_py = py_type.__args__
+ return types.DictType(self.infer(key_py), self.infer(value_py))
+
+ if getattr(py_type, "__origin__", None) is set:
+ (element_py,) = py_type.__args__
+ return types.Set(self.infer(element_py))
+
+ if getattr(py_type, "__origin__", None) is tuple:
+ tys = tuple(map(self.infer, py_type.__args__))
+ return types.BaseTuple.from_types(tys)
+
+ def register(self, func_or_py_type, numba_type=None):
+ """
+ Extend AsNumbaType to support new python types (e.g. a user defined
+ JitClass). For a simple pair of a python type and a numba type, can
+ use as a function register(py_type, numba_type). If more complex logic
+ is required (e.g. for generic types), register can also be used as a
+ decorator for a function that takes a python type as input and returns
+ a numba type or None.
+ """
+ if numba_type is not None:
+ # register used with a specific (py_type, numba_type) pair.
+ assert isinstance(numba_type, types.Type)
+ self.lookup[func_or_py_type] = numba_type
+ else:
+ # register used as a decorator.
+ assert inspect.isfunction(func_or_py_type)
+ self.functions.append(func_or_py_type)
+
+ def try_infer(self, py_type):
+ """
+ Try to determine the numba type of a given python type.
+ We first consider the lookup dictionary. If py_type is not there, we
+ iterate through the registered functions until one returns a numba type.
+ If type inference fails, return None.
+ """
+ result = self.lookup.get(py_type, None)
+
+ for func in self.functions:
+ if result is not None:
+ break
+ result = func(py_type)
+
+ if result is not None and not isinstance(result, types.Type):
+ raise errors.TypingError(
+ f"as_numba_type should return a numba type, got {result}"
+ )
+ return result
+
+ def infer(self, py_type):
+ result = self.try_infer(py_type)
+ if result is None:
+ raise errors.TypingError(
+ f"Cannot infer numba type of python type {py_type}"
+ )
+ return result
+
+ def __call__(self, py_type):
+ return self.infer(py_type)
+
+
+as_numba_type = AsNumbaTypeRegistry()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/bufproto.py b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/bufproto.py
new file mode 100644
index 0000000000000000000000000000000000000000..95bf2f7e06c1c1d5842528523747bf621fd70f2c
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/bufproto.py
@@ -0,0 +1,79 @@
+"""
+Typing support for the buffer protocol (PEP 3118).
+"""
+
+import array
+
+from numba.core import types, config
+from numba.core.errors import NumbaValueError
+
+
+_pep3118_int_types = set('bBhHiIlLqQnN')
+
+if config.USE_LEGACY_TYPE_SYSTEM: # Old type system
+ _pep3118_scalar_map = {
+ 'f': types.float32,
+ 'd': types.float64,
+ 'Zf': types.complex64,
+ 'Zd': types.complex128,
+ }
+else: # New type system
+ _pep3118_scalar_map = {
+ # TODO: FIXME We need to modify the following Map to use Python Types.
+ # However currently here's nothing in Python types that maps
+ # to a float32 or a complex64
+ # 'f': types.np_float32,
+ 'd': types.py_float, # 64-bit float
+ # 'Zf': types.np_complex64,
+ 'Zd': types.py_complex, # 128-bit complex
+ }
+
+_type_map = {
+ bytearray: types.ByteArray,
+ array.array: types.PyArray,
+ }
+
+_type_map[memoryview] = types.MemoryView
+_type_map[bytes] = types.Bytes
+
+
+def decode_pep3118_format(fmt, itemsize):
+ """
+ Return the Numba type for an item with format string *fmt* and size
+ *itemsize* (in bytes).
+ """
+ # XXX reuse _dtype_from_pep3118() from np.core._internal?
+ if fmt in _pep3118_int_types:
+ # Determine int width and signedness
+ name = 'int%d' % (itemsize * 8,)
+ if fmt.isupper():
+ name = 'u' + name
+ return types.Integer(name)
+ try:
+ # For the hard-coded types above, consider "=" the same as "@"
+ # (the default). This is because Numpy sometimes adds "="
+ # in front of the PEP 3118 format string.
+ return _pep3118_scalar_map[fmt.lstrip('=')]
+ except KeyError:
+ raise NumbaValueError("unsupported PEP 3118 format %r" % (fmt,))
+
+
+def get_type_class(typ):
+ """
+ Get the Numba type class for buffer-compatible Python *typ*.
+ """
+ try:
+ # Look up special case.
+ return _type_map[typ]
+ except KeyError:
+ # Fall back on generic one.
+ return types.Buffer
+
+
+def infer_layout(val):
+ """
+ Infer layout of the given memoryview *val*.
+ """
+ return ('C' if val.c_contiguous else
+ 'F' if val.f_contiguous else
+ 'A')
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/builtins.py b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/builtins.py
new file mode 100644
index 0000000000000000000000000000000000000000..31d54b6f58ab3b9885101f73dd8fa31000c02456
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/builtins.py
@@ -0,0 +1,14 @@
+import sys
+from numba.core.utils import _RedirectSubpackage
+from numba.core import config
+
+if config.USE_LEGACY_TYPE_SYSTEM:
+ sys.modules[__name__] = _RedirectSubpackage(
+ locals(),
+ "numba.core.typing.old_builtins"
+ )
+else:
+ sys.modules[__name__] = _RedirectSubpackage(
+ locals(),
+ "numba.core.typing.new_builtins"
+ )
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/cffi_utils.py b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/cffi_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..325272b9d9af575df916321308df46424e5de02e
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/cffi_utils.py
@@ -0,0 +1,229 @@
+# -*- coding: utf-8 -*-
+"""
+Support for CFFI. Allows checking whether objects are CFFI functions and
+obtaining the pointer and numba signature.
+"""
+
+from types import BuiltinFunctionType
+import ctypes
+from functools import partial
+import numpy as np
+
+from numba.core import types
+from numba.core.errors import TypingError
+from numba.core.typing import templates
+from numba.np import numpy_support
+
+try:
+ import cffi
+ ffi = cffi.FFI()
+except ImportError:
+ ffi = None
+
+SUPPORTED = ffi is not None
+_ool_func_types = {}
+_ool_func_ptr = {}
+_ffi_instances = set()
+
+
+def is_ffi_instance(obj):
+ # Compiled FFI modules have a member, ffi, which is an instance of
+ # CompiledFFI, which behaves similarly to an instance of cffi.FFI. In
+ # order to simplify handling a CompiledFFI object, we treat them as
+ # if they're cffi.FFI instances for typing and lowering purposes.
+ try:
+ return obj in _ffi_instances or isinstance(obj, cffi.FFI)
+ except TypeError: # Unhashable type possible
+ return False
+
+def is_cffi_func(obj):
+ """Check whether the obj is a CFFI function"""
+ try:
+ return ffi.typeof(obj).kind == 'function'
+ except TypeError:
+ try:
+ return obj in _ool_func_types
+ except:
+ return False
+
+def get_pointer(cffi_func):
+ """
+ Get a pointer to the underlying function for a CFFI function as an
+ integer.
+ """
+ if cffi_func in _ool_func_ptr:
+ return _ool_func_ptr[cffi_func]
+ return int(ffi.cast("uintptr_t", cffi_func))
+
+
+_cached_type_map = None
+
+def _type_map():
+ """
+ Lazily compute type map, as calling ffi.typeof() involves costly
+ parsing of C code...
+ """
+ global _cached_type_map
+ if _cached_type_map is None:
+ _cached_type_map = {
+ ffi.typeof('bool') : types.boolean,
+ ffi.typeof('char') : types.char,
+ ffi.typeof('short') : types.short,
+ ffi.typeof('int') : types.intc,
+ ffi.typeof('long') : types.long_,
+ ffi.typeof('long long') : types.longlong,
+ ffi.typeof('unsigned char') : types.uchar,
+ ffi.typeof('unsigned short') : types.ushort,
+ ffi.typeof('unsigned int') : types.uintc,
+ ffi.typeof('unsigned long') : types.ulong,
+ ffi.typeof('unsigned long long') : types.ulonglong,
+ ffi.typeof('int8_t') : types.char,
+ ffi.typeof('uint8_t') : types.uchar,
+ ffi.typeof('int16_t') : types.short,
+ ffi.typeof('uint16_t') : types.ushort,
+ ffi.typeof('int32_t') : types.intc,
+ ffi.typeof('uint32_t') : types.uintc,
+ ffi.typeof('int64_t') : types.longlong,
+ ffi.typeof('uint64_t') : types.ulonglong,
+ ffi.typeof('float') : types.float32,
+ ffi.typeof('double') : types.double,
+ ffi.typeof('ssize_t') : types.intp,
+ ffi.typeof('size_t') : types.uintp,
+ ffi.typeof('void') : types.void,
+ }
+ return _cached_type_map
+
+
+def map_type(cffi_type, use_record_dtype=False):
+ """
+ Map CFFI type to numba type.
+
+ Parameters
+ ----------
+ cffi_type:
+ The CFFI type to be converted.
+ use_record_dtype: bool (default: False)
+ When True, struct types are mapped to a NumPy Record dtype.
+
+ """
+ primed_map_type = partial(map_type, use_record_dtype=use_record_dtype)
+ kind = getattr(cffi_type, 'kind', '')
+ if kind == 'union':
+ raise TypeError("No support for CFFI union")
+ elif kind == 'function':
+ if cffi_type.ellipsis:
+ raise TypeError("vararg function is not supported")
+ restype = primed_map_type(cffi_type.result)
+ argtypes = [primed_map_type(arg) for arg in cffi_type.args]
+ return templates.signature(restype, *argtypes)
+ elif kind == 'pointer':
+ pointee = cffi_type.item
+ if pointee.kind == 'void':
+ return types.voidptr
+ else:
+ return types.CPointer(primed_map_type(pointee))
+ elif kind == 'array':
+ dtype = primed_map_type(cffi_type.item)
+ nelem = cffi_type.length
+ return types.NestedArray(dtype=dtype, shape=(nelem,))
+ elif kind == 'struct' and use_record_dtype:
+ return map_struct_to_record_dtype(cffi_type)
+ else:
+ result = _type_map().get(cffi_type)
+ if result is None:
+ raise TypeError(cffi_type)
+ return result
+
+
+def map_struct_to_record_dtype(cffi_type):
+ """Convert a cffi type into a NumPy Record dtype
+ """
+ fields = {
+ 'names': [],
+ 'formats': [],
+ 'offsets': [],
+ 'itemsize': ffi.sizeof(cffi_type),
+ }
+ is_aligned = True
+ for k, v in cffi_type.fields:
+ # guard unsupported values
+ if v.bitshift != -1:
+ msg = "field {!r} has bitshift, this is not supported"
+ raise ValueError(msg.format(k))
+ if v.flags != 0:
+ msg = "field {!r} has flags, this is not supported"
+ raise ValueError(msg.format(k))
+ if v.bitsize != -1:
+ msg = "field {!r} has bitsize, this is not supported"
+ raise ValueError(msg.format(k))
+ dtype = numpy_support.as_dtype(
+ map_type(v.type, use_record_dtype=True),
+ )
+ fields['names'].append(k)
+ fields['formats'].append(dtype)
+ fields['offsets'].append(v.offset)
+ # Check alignment
+ is_aligned &= (v.offset % dtype.alignment == 0)
+
+ return numpy_support.from_dtype(np.dtype(fields, align=is_aligned))
+
+
+def make_function_type(cffi_func, use_record_dtype=False):
+ """
+ Return a Numba type for the given CFFI function pointer.
+ """
+ cffi_type = _ool_func_types.get(cffi_func) or ffi.typeof(cffi_func)
+ if getattr(cffi_type, 'kind', '') == 'struct':
+ raise TypeError('No support for CFFI struct values')
+ sig = map_type(cffi_type, use_record_dtype=use_record_dtype)
+ return types.ExternalFunctionPointer(sig, get_pointer=get_pointer)
+
+
+registry = templates.Registry()
+
+@registry.register
+class FFI_from_buffer(templates.AbstractTemplate):
+ key = 'ffi.from_buffer'
+
+ def generic(self, args, kws):
+ if kws or len(args) != 1:
+ return
+ [ary] = args
+ if not isinstance(ary, types.Buffer):
+ raise TypingError("from_buffer() expected a buffer object, got %s"
+ % (ary,))
+ if ary.layout not in ('C', 'F'):
+ raise TypingError("from_buffer() unsupported on non-contiguous buffers (got %s)"
+ % (ary,))
+ if ary.layout != 'C' and ary.ndim > 1:
+ raise TypingError("from_buffer() only supports multidimensional arrays with C layout (got %s)"
+ % (ary,))
+ ptr = types.CPointer(ary.dtype)
+ return templates.signature(ptr, ary)
+
+@registry.register_attr
+class FFIAttribute(templates.AttributeTemplate):
+ key = types.ffi
+
+ def resolve_from_buffer(self, ffi):
+ return types.BoundFunction(FFI_from_buffer, types.ffi)
+
+
+def register_module(mod):
+ """
+ Add typing for all functions in an out-of-line CFFI module to the typemap
+ """
+ for f in dir(mod.lib):
+ f = getattr(mod.lib, f)
+ if isinstance(f, BuiltinFunctionType):
+ _ool_func_types[f] = mod.ffi.typeof(f)
+ addr = mod.ffi.addressof(mod.lib, f.__name__)
+ _ool_func_ptr[f] = int(mod.ffi.cast("uintptr_t", addr))
+ _ffi_instances.add(mod.ffi)
+
+def register_type(cffi_type, numba_type):
+ """
+ Add typing for a given CFFI type to the typemap
+ """
+ tm = _type_map()
+ tm[cffi_type] = numba_type
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/cmathdecl.py b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/cmathdecl.py
new file mode 100644
index 0000000000000000000000000000000000000000..1bde45629b50b83a863198e5fc66d97e14247c0f
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/cmathdecl.py
@@ -0,0 +1,14 @@
+import sys
+from numba.core.utils import _RedirectSubpackage
+from numba.core import config
+
+if config.USE_LEGACY_TYPE_SYSTEM:
+ sys.modules[__name__] = _RedirectSubpackage(
+ locals(),
+ "numba.core.typing.old_cmathdecl"
+ )
+else:
+ sys.modules[__name__] = _RedirectSubpackage(
+ locals(),
+ "numba.core.typing.new_cmathdecl"
+ )
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/collections.py b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/collections.py
new file mode 100644
index 0000000000000000000000000000000000000000..bb4639a3e794af96e894cd220541afb0f6c05b99
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/collections.py
@@ -0,0 +1,121 @@
+from .. import types, utils, errors
+import operator
+from .templates import (AttributeTemplate, ConcreteTemplate, AbstractTemplate,
+ infer_global, infer, infer_getattr,
+ signature, bound_function, make_callable_template)
+from .builtins import normalize_1d_index
+
+
+@infer_global(operator.contains)
+class InContainer(AbstractTemplate):
+ key = operator.contains
+
+ def generic(self, args, kws):
+ cont, item = args
+ if isinstance(cont, types.Container):
+ return signature(types.boolean, cont, cont.dtype)
+
+@infer_global(len)
+class ContainerLen(AbstractTemplate):
+
+ def generic(self, args, kws):
+ assert not kws
+ (val,) = args
+ if isinstance(val, (types.Container)):
+ return signature(types.intp, val)
+
+
+@infer_global(operator.truth)
+class SequenceBool(AbstractTemplate):
+ key = operator.truth
+
+ def generic(self, args, kws):
+ assert not kws
+ (val,) = args
+ if isinstance(val, (types.Sequence)):
+ return signature(types.boolean, val)
+
+
+@infer_global(operator.getitem)
+class GetItemSequence(AbstractTemplate):
+ key = operator.getitem
+
+ def generic(self, args, kws):
+ seq, idx = args
+ if isinstance(seq, types.Sequence):
+ idx = normalize_1d_index(idx)
+ if isinstance(idx, types.SliceType):
+ # Slicing a tuple only supported with static_getitem
+ if not isinstance(seq, types.BaseTuple):
+ return signature(seq, seq, idx)
+ elif isinstance(idx, types.Integer):
+ return signature(seq.dtype, seq, idx)
+
+@infer_global(operator.setitem)
+class SetItemSequence(AbstractTemplate):
+ def generic(self, args, kws):
+ seq, idx, value = args
+ if isinstance(seq, types.MutableSequence):
+ idx = normalize_1d_index(idx)
+ if isinstance(idx, types.SliceType):
+ return signature(types.none, seq, idx, seq)
+ elif isinstance(idx, types.Integer):
+ if not self.context.can_convert(value, seq.dtype):
+ msg = "invalid setitem with value of {} to element of {}"
+ raise errors.TypingError(msg.format(types.unliteral(value), seq.dtype))
+ return signature(types.none, seq, idx, seq.dtype)
+
+
+@infer_global(operator.delitem)
+class DelItemSequence(AbstractTemplate):
+ def generic(self, args, kws):
+ seq, idx = args
+ if isinstance(seq, types.MutableSequence):
+ idx = normalize_1d_index(idx)
+ return signature(types.none, seq, idx)
+
+
+# --------------------------------------------------------------------------
+# named tuples
+
+@infer_getattr
+class NamedTupleAttribute(AttributeTemplate):
+ key = types.BaseNamedTuple
+
+ def resolve___class__(self, tup):
+ return types.NamedTupleClass(tup.instance_class)
+
+ def generic_resolve(self, tup, attr):
+ # Resolution of other attributes
+ try:
+ index = tup.fields.index(attr)
+ except ValueError:
+ return
+ return tup[index]
+
+
+@infer_getattr
+class NamedTupleClassAttribute(AttributeTemplate):
+ key = types.NamedTupleClass
+
+ def resolve___call__(self, classty):
+ """
+ Resolve the named tuple constructor, aka the class's __call__ method.
+ """
+ instance_class = classty.instance_class
+ pysig = utils.pysignature(instance_class)
+
+ def typer(*args, **kws):
+ # Fold keyword args
+ try:
+ bound = pysig.bind(*args, **kws)
+ except TypeError as e:
+ msg = "In '%s': %s" % (instance_class, e)
+ e.args = (msg,)
+ raise
+ assert not bound.kwargs
+ return types.BaseTuple.from_types(bound.args, instance_class)
+
+ # Override the typer's pysig to match the namedtuple constructor's
+ typer.pysig = pysig
+ return types.Function(make_callable_template(self.key, typer))
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/context.py b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/context.py
new file mode 100644
index 0000000000000000000000000000000000000000..b479f7bd7b09f00e7e7853c374728c139ac95081
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/context.py
@@ -0,0 +1,741 @@
+from collections import defaultdict
+from collections.abc import Sequence
+import types as pytypes
+import weakref
+import threading
+import contextlib
+import operator
+
+from numba.core import types, errors
+from numba.core.typeconv import Conversion, rules
+from numba.core.typing import templates
+from numba.core.utils import order_by_target_specificity
+from .typeof import typeof, Purpose
+
+from numba.core import utils
+
+
+class Rating(object):
+ __slots__ = 'promote', 'safe_convert', "unsafe_convert"
+
+ def __init__(self):
+ self.promote = 0
+ self.safe_convert = 0
+ self.unsafe_convert = 0
+
+ def astuple(self):
+ """Returns a tuple suitable for comparing with the worse situation
+ start first.
+ """
+ return (self.unsafe_convert, self.safe_convert, self.promote)
+
+ def __add__(self, other):
+ if type(self) is not type(other):
+ return NotImplemented
+ rsum = Rating()
+ rsum.promote = self.promote + other.promote
+ rsum.safe_convert = self.safe_convert + other.safe_convert
+ rsum.unsafe_convert = self.unsafe_convert + other.unsafe_convert
+ return rsum
+
+
+class CallStack(Sequence):
+ """
+ A compile-time call stack
+ """
+
+ def __init__(self):
+ self._stack = []
+ self._lock = threading.RLock()
+
+ def __getitem__(self, index):
+ """
+ Returns item in the stack where index=0 is the top and index=1 is
+ the second item from the top.
+ """
+ return self._stack[len(self) - index - 1]
+
+ def __len__(self):
+ return len(self._stack)
+
+ @contextlib.contextmanager
+ def register(self, target, typeinfer, func_id, args):
+ # guard compiling the same function with the same signature
+ if self.match(func_id.func, args):
+ msg = "compiler re-entrant to the same function signature"
+ raise errors.NumbaRuntimeError(msg)
+ self._lock.acquire()
+ self._stack.append(CallFrame(target, typeinfer, func_id, args))
+ try:
+ yield
+ finally:
+ self._stack.pop()
+ self._lock.release()
+
+ def finditer(self, py_func):
+ """
+ Yields frame that matches the function object starting from the top
+ of stack.
+ """
+ for frame in self:
+ if frame.func_id.func is py_func:
+ yield frame
+
+ def findfirst(self, py_func):
+ """
+ Returns the first result from `.finditer(py_func)`; or None if no match.
+ """
+ try:
+ return next(self.finditer(py_func))
+ except StopIteration:
+ return
+
+ def match(self, py_func, args):
+ """
+ Returns first function that matches *py_func* and the arguments types in
+ *args*; or, None if no match.
+ """
+ for frame in self.finditer(py_func):
+ if frame.args == args:
+ return frame
+
+
+class CallFrame(object):
+ """
+ A compile-time call frame
+ """
+ def __init__(self, target, typeinfer, func_id, args):
+ self.typeinfer = typeinfer
+ self.func_id = func_id
+ self.args = args
+ self.target = target
+ self._inferred_retty = set()
+
+ def __repr__(self):
+ return "CallFrame({}, {})".format(self.func_id, self.args)
+
+ def add_return_type(self, return_type):
+ """Add *return_type* to the list of inferred return-types.
+ If there are too many, raise `TypingError`.
+ """
+ # The maximum limit is picked arbitrarily.
+ # Don't think that this needs to be user configurable.
+ RETTY_LIMIT = 16
+ self._inferred_retty.add(return_type)
+ if len(self._inferred_retty) >= RETTY_LIMIT:
+ m = "Return type of recursive function does not converge"
+ raise errors.TypingError(m)
+
+
+class BaseContext(object):
+ """A typing context for storing function typing constrain template.
+ """
+
+ def __init__(self):
+ # A list of installed registries
+ self._registries = {}
+ # Typing declarations extracted from the registries or other sources
+ self._functions = defaultdict(list)
+ self._attributes = defaultdict(list)
+ self._globals = utils.UniqueDict()
+ self.tm = rules.default_type_manager
+ self.callstack = CallStack()
+
+ # Initialize
+ self.init()
+
+ def init(self):
+ """
+ Initialize the typing context. Can be overridden by subclasses.
+ """
+
+ def refresh(self):
+ """
+ Refresh context with new declarations from known registries.
+ Useful for third-party extensions.
+ """
+ self.load_additional_registries()
+ # Some extensions may have augmented the builtin registry
+ self._load_builtins()
+
+ def explain_function_type(self, func):
+ """
+ Returns a string description of the type of a function
+ """
+ desc = []
+ defns = []
+ param = False
+ if isinstance(func, types.Callable):
+ sigs, param = func.get_call_signatures()
+ defns.extend(sigs)
+
+ elif func in self._functions:
+ for tpl in self._functions[func]:
+ param = param or hasattr(tpl, 'generic')
+ defns.extend(getattr(tpl, 'cases', []))
+
+ else:
+ msg = "No type info available for {func!r} as a callable."
+ desc.append(msg.format(func=func))
+
+ if defns:
+ desc = ['Known signatures:']
+ for sig in defns:
+ desc.append(' * {0}'.format(sig))
+
+ return '\n'.join(desc)
+
+ def resolve_function_type(self, func, args, kws):
+ """
+ Resolve function type *func* for argument types *args* and *kws*.
+ A signature is returned.
+ """
+ # Prefer user definition first
+ try:
+ res = self._resolve_user_function_type(func, args, kws)
+ except errors.TypingError as e:
+ # Capture any typing error
+ last_exception = e
+ res = None
+ else:
+ last_exception = None
+
+ # Return early we know there's a working user function
+ if res is not None:
+ return res
+
+ # Check builtin functions
+ res = self._resolve_builtin_function_type(func, args, kws)
+
+ # Re-raise last_exception if no function type has been found
+ if res is None and last_exception is not None:
+ raise last_exception
+
+ return res
+
+ def _resolve_builtin_function_type(self, func, args, kws):
+ # NOTE: we should reduce usage of this
+ if func in self._functions:
+ # Note: Duplicating code with types.Function.get_call_type().
+ # *defns* are CallTemplates.
+ defns = self._functions[func]
+ for defn in defns:
+ for support_literals in [True, False]:
+ if support_literals:
+ res = defn.apply(args, kws)
+ else:
+ fixedargs = [types.unliteral(a) for a in args]
+ res = defn.apply(fixedargs, kws)
+ if res is not None:
+ return res
+
+ def _resolve_user_function_type(self, func, args, kws, literals=None):
+ # It's not a known function type, perhaps it's a global?
+ functy = self._lookup_global(func)
+ if functy is not None:
+ func = functy
+
+ if isinstance(func, types.Type):
+ # If it's a type, it may support a __call__ method
+ func_type = self.resolve_getattr(func, "__call__")
+ if func_type is not None:
+ # The function has a __call__ method, type its call.
+ return self.resolve_function_type(func_type, args, kws)
+
+ if isinstance(func, types.Callable):
+ # XXX fold this into the __call__ attribute logic?
+ return func.get_call_type(self, args, kws)
+
+ def _get_attribute_templates(self, typ):
+ """
+ Get matching AttributeTemplates for the Numba type.
+ """
+ if typ in self._attributes:
+ for attrinfo in self._attributes[typ]:
+ yield attrinfo
+ else:
+ for cls in type(typ).__mro__:
+ if cls in self._attributes:
+ for attrinfo in self._attributes[cls]:
+ yield attrinfo
+
+ def resolve_getattr(self, typ, attr):
+ """
+ Resolve getting the attribute *attr* (a string) on the Numba type.
+ The attribute's type is returned, or None if resolution failed.
+ """
+ def core(typ):
+ out = self.find_matching_getattr_template(typ, attr)
+ if out:
+ return out['return_type']
+
+ out = core(typ)
+ if out is not None:
+ return out
+
+ # Try again without literals
+ out = core(types.unliteral(typ))
+ if out is not None:
+ return out
+
+ if isinstance(typ, types.Module):
+ attrty = self.resolve_module_constants(typ, attr)
+ if attrty is not None:
+ return attrty
+
+ def find_matching_getattr_template(self, typ, attr):
+
+ templates = list(self._get_attribute_templates(typ))
+
+ # get the order in which to try templates
+ from numba.core.target_extension import get_local_target # circular
+ target_hw = get_local_target(self)
+ order = order_by_target_specificity(target_hw, templates, fnkey=attr)
+
+ for template in order:
+ return_type = template.resolve(typ, attr)
+ if return_type is not None:
+ return {
+ 'template': template,
+ 'return_type': return_type,
+ }
+
+ def resolve_setattr(self, target, attr, value):
+ """
+ Resolve setting the attribute *attr* (a string) on the *target* type
+ to the given *value* type.
+ A function signature is returned, or None if resolution failed.
+ """
+ for attrinfo in self._get_attribute_templates(target):
+ expectedty = attrinfo.resolve(target, attr)
+ # NOTE: convertibility from *value* to *expectedty* is left to
+ # the caller.
+ if expectedty is not None:
+ return templates.signature(types.void, target, expectedty)
+
+ def resolve_static_getitem(self, value, index):
+ assert not isinstance(index, types.Type), index
+ args = value, index
+ kws = ()
+ return self.resolve_function_type("static_getitem", args, kws)
+
+ def resolve_static_setitem(self, target, index, value):
+ assert not isinstance(index, types.Type), index
+ args = target, index, value
+ kws = {}
+ return self.resolve_function_type("static_setitem", args, kws)
+
+ def resolve_setitem(self, target, index, value):
+ assert isinstance(index, types.Type), index
+ fnty = self.resolve_value_type(operator.setitem)
+ sig = fnty.get_call_type(self, (target, index, value), {})
+ return sig
+
+ def resolve_delitem(self, target, index):
+ args = target, index
+ kws = {}
+ fnty = self.resolve_value_type(operator.delitem)
+ sig = fnty.get_call_type(self, args, kws)
+ return sig
+
+ def resolve_module_constants(self, typ, attr):
+ """
+ Resolve module-level global constants.
+ Return None or the attribute type
+ """
+ assert isinstance(typ, types.Module)
+ attrval = getattr(typ.pymod, attr)
+ try:
+ return self.resolve_value_type(attrval)
+ except ValueError:
+ pass
+
+ def resolve_value_type(self, val):
+ """
+ Return the numba type of a Python value that is being used
+ as a runtime constant.
+ ValueError is raised for unsupported types.
+ """
+ try:
+ ty = typeof(val, Purpose.constant)
+ except ValueError as e:
+ # Make sure the exception doesn't hold a reference to the user
+ # value.
+ typeof_exc = utils.erase_traceback(e)
+ else:
+ return ty
+
+ if isinstance(val, types.ExternalFunction):
+ return val
+
+ # Try to look up target specific typing information
+ ty = self._get_global_type(val)
+ if ty is not None:
+ return ty
+
+ raise typeof_exc
+
+ def resolve_value_type_prefer_literal(self, value):
+ """Resolve value type and prefer Literal types whenever possible.
+ """
+ lit = types.maybe_literal(value)
+ if lit is None:
+ return self.resolve_value_type(value)
+ else:
+ return lit
+
+ def _get_global_type(self, gv):
+ ty = self._lookup_global(gv)
+ if ty is not None:
+ return ty
+ if isinstance(gv, pytypes.ModuleType):
+ return types.Module(gv)
+
+ def _load_builtins(self):
+ # Initialize declarations
+ from numba.core.typing import builtins, arraydecl, npdatetime # noqa: F401, E501
+ from numba.core.typing import ctypes_utils, bufproto # noqa: F401, E501
+ from numba.core.unsafe import eh # noqa: F401
+
+ self.install_registry(templates.builtin_registry)
+
+ def load_additional_registries(self):
+ """
+ Load target-specific registries. Can be overridden by subclasses.
+ """
+
+ def install_registry(self, registry):
+ """
+ Install a *registry* (a templates.Registry instance) of function,
+ attribute and global declarations.
+ """
+ try:
+ loader = self._registries[registry]
+ except KeyError:
+ loader = templates.RegistryLoader(registry)
+ self._registries[registry] = loader
+
+ from numba.core.target_extension import (get_local_target,
+ resolve_target_str)
+ current_target = get_local_target(self)
+
+ def is_for_this_target(ftcls):
+ metadata = getattr(ftcls, 'metadata', None)
+ if metadata is None:
+ return True
+
+ target_str = metadata.get('target')
+ if target_str is None:
+ return True
+
+ # There may be pending registrations for nonexistent targets.
+ # Ideally it would be impossible to leave a registration pending
+ # for an invalid target, but in practice this is exceedingly
+ # difficult to guard against - many things are registered at import
+ # time, and eagerly reporting an error when registering for invalid
+ # targets would require that all target registration code is
+ # executed prior to all typing registrations during the import
+ # process; attempting to enforce this would impose constraints on
+ # execution order during import that would be very difficult to
+ # resolve and maintain in the presence of typical code maintenance.
+ # Furthermore, these constraints would be imposed not only on
+ # Numba internals, but also on its dependents.
+ #
+ # Instead of that enforcement, we simply catch any occurrences of
+ # registrations for targets that don't exist, and report that
+ # they're not for this target. They will then not be encountered
+ # again during future typing context refreshes (because the
+ # loader's new registrations are a stream_list that doesn't yield
+ # previously-yielded items).
+ try:
+ ft_target = resolve_target_str(target_str)
+ except errors.NonexistentTargetError:
+ return False
+
+ return current_target.inherits_from(ft_target)
+
+ for ftcls in loader.new_registrations('functions'):
+ if not is_for_this_target(ftcls):
+ continue
+ self.insert_function(ftcls(self))
+ for ftcls in loader.new_registrations('attributes'):
+ if not is_for_this_target(ftcls):
+ continue
+ self.insert_attributes(ftcls(self))
+ for gv, gty in loader.new_registrations('globals'):
+ existing = self._lookup_global(gv)
+ if existing is None:
+ self.insert_global(gv, gty)
+ else:
+ # A type was already inserted, see if we can add to it
+ newty = existing.augment(gty)
+ if newty is None:
+ raise TypeError("cannot augment %s with %s"
+ % (existing, gty))
+ self._remove_global(gv)
+ self._insert_global(gv, newty)
+
+ def _lookup_global(self, gv):
+ """
+ Look up the registered type for global value *gv*.
+ """
+ try:
+ gv = weakref.ref(gv)
+ except TypeError:
+ pass
+ try:
+ return self._globals.get(gv, None)
+ except TypeError:
+ # Unhashable type
+ return None
+
+ def _insert_global(self, gv, gty):
+ """
+ Register type *gty* for value *gv*. Only a weak reference
+ to *gv* is kept, if possible.
+ """
+ def on_disposal(wr, pop=self._globals.pop):
+ # pop() is pre-looked up to avoid a crash late at shutdown on 3.5
+ # (https://bugs.python.org/issue25217)
+ pop(wr)
+ try:
+ gv = weakref.ref(gv, on_disposal)
+ except TypeError:
+ pass
+ self._globals[gv] = gty
+
+ def _remove_global(self, gv):
+ """
+ Remove the registered type for global value *gv*.
+ """
+ try:
+ gv = weakref.ref(gv)
+ except TypeError:
+ pass
+ del self._globals[gv]
+
+ def insert_global(self, gv, gty):
+ self._insert_global(gv, gty)
+
+ def insert_attributes(self, at):
+ key = at.key
+ self._attributes[key].append(at)
+
+ def insert_function(self, ft):
+ key = ft.key
+ self._functions[key].append(ft)
+
+ def insert_user_function(self, fn, ft):
+ """Insert a user function.
+
+ Args
+ ----
+ - fn:
+ object used as callee
+ - ft:
+ function template
+ """
+ self._insert_global(fn, types.Function(ft))
+
+ def can_convert(self, fromty, toty):
+ """
+ Check whether conversion is possible from *fromty* to *toty*.
+ If successful, return a numba.typeconv.Conversion instance;
+ otherwise None is returned.
+ """
+ if fromty == toty:
+ return Conversion.exact
+ else:
+ # First check with the type manager (some rules are registered
+ # at startup there, see numba.typeconv.rules)
+ conv = self.tm.check_compatible(fromty, toty)
+ if conv is not None:
+ return conv
+
+ # Fall back on type-specific rules
+ forward = fromty.can_convert_to(self, toty)
+ backward = toty.can_convert_from(self, fromty)
+ if backward is None:
+ return forward
+ elif forward is None:
+ return backward
+ else:
+ return min(forward, backward)
+
+ def _rate_arguments(self, actualargs, formalargs, unsafe_casting=True,
+ exact_match_required=False):
+ """
+ Rate the actual arguments for compatibility against the formal
+ arguments. A Rating instance is returned, or None if incompatible.
+ """
+ if len(actualargs) != len(formalargs):
+ return None
+ rate = Rating()
+ for actual, formal in zip(actualargs, formalargs):
+ conv = self.can_convert(actual, formal)
+ if conv is None:
+ return None
+ elif not unsafe_casting and conv >= Conversion.unsafe:
+ return None
+ elif exact_match_required and conv != Conversion.exact:
+ return None
+
+ if conv == Conversion.promote:
+ rate.promote += 1
+ elif conv == Conversion.safe:
+ rate.safe_convert += 1
+ elif conv == Conversion.unsafe:
+ rate.unsafe_convert += 1
+ elif conv == Conversion.exact:
+ pass
+ else:
+ raise AssertionError("unreachable", conv)
+
+ return rate
+
+ def install_possible_conversions(self, actualargs, formalargs):
+ """
+ Install possible conversions from the actual argument types to
+ the formal argument types in the C++ type manager.
+ Return True if all arguments can be converted.
+ """
+ if len(actualargs) != len(formalargs):
+ return False
+ for actual, formal in zip(actualargs, formalargs):
+ if self.tm.check_compatible(actual, formal) is not None:
+ # This conversion is already known
+ continue
+ conv = self.can_convert(actual, formal)
+ if conv is None:
+ return False
+ assert conv is not Conversion.exact
+ self.tm.set_compatible(actual, formal, conv)
+ return True
+
+ def resolve_overload(self, key, cases, args, kws,
+ allow_ambiguous=True, unsafe_casting=True,
+ exact_match_required=False):
+ """
+ Given actual *args* and *kws*, find the best matching
+ signature in *cases*, or None if none matches.
+ *key* is used for error reporting purposes.
+ If *allow_ambiguous* is False, a tie in the best matches
+ will raise an error.
+ If *unsafe_casting* is False, unsafe casting is forbidden.
+ """
+ assert not kws, "Keyword arguments are not supported, yet"
+ options = {
+ 'unsafe_casting': unsafe_casting,
+ 'exact_match_required': exact_match_required,
+ }
+ # Rate each case
+ candidates = []
+ for case in cases:
+ if len(args) == len(case.args):
+ rating = self._rate_arguments(args, case.args, **options)
+ if rating is not None:
+ candidates.append((rating.astuple(), case))
+
+ # Find the best case
+ candidates.sort(key=lambda i: i[0])
+ if candidates:
+ best_rate, best = candidates[0]
+ if not allow_ambiguous:
+ # Find whether there is a tie and if so, raise an error
+ tied = []
+ for rate, case in candidates:
+ if rate != best_rate:
+ break
+ tied.append(case)
+ if len(tied) > 1:
+ args = (key, args, '\n'.join(map(str, tied)))
+ msg = "Ambiguous overloading for %s %s:\n%s" % args
+ raise TypeError(msg)
+ # Simply return the best matching candidate in order.
+ # If there is a tie, since list.sort() is stable, the first case
+ # in the original order is returned.
+ # (this can happen if e.g. a function template exposes
+ # (int32, int32) -> int32 and (int64, int64) -> int64,
+ # and you call it with (int16, int16) arguments)
+ return best
+
+ def unify_types(self, *typelist):
+ # Sort the type list according to bit width before doing
+ # pairwise unification (with thanks to aterrel).
+ def keyfunc(obj):
+ """Uses bitwidth to order numeric-types.
+ Fallback to stable, deterministic sort.
+ """
+ return getattr(obj, 'bitwidth', 0)
+ typelist = sorted(typelist, key=keyfunc)
+ unified = typelist[0]
+ for tp in typelist[1:]:
+ unified = self.unify_pairs(unified, tp)
+ if unified is None:
+ break
+ return unified
+
+ def unify_pairs(self, first, second):
+ """
+ Try to unify the two given types. A third type is returned,
+ or None in case of failure.
+ """
+ if first == second:
+ return first
+
+ if first is types.undefined:
+ return second
+ elif second is types.undefined:
+ return first
+
+ # Types with special unification rules
+ unified = first.unify(self, second)
+ if unified is not None:
+ return unified
+
+ unified = second.unify(self, first)
+ if unified is not None:
+ return unified
+
+ # Other types with simple conversion rules
+ conv = self.can_convert(fromty=first, toty=second)
+ if conv is not None and conv <= Conversion.safe:
+ # Can convert from first to second
+ return second
+
+ conv = self.can_convert(fromty=second, toty=first)
+ if conv is not None and conv <= Conversion.safe:
+ # Can convert from second to first
+ return first
+
+ if isinstance(first, types.Literal) or \
+ isinstance(second, types.Literal):
+ first = types.unliteral(first)
+ second = types.unliteral(second)
+ return self.unify_pairs(first, second)
+
+ # Cannot unify
+ return None
+
+
+class Context(BaseContext):
+
+ def load_additional_registries(self):
+ from . import (
+ cffi_utils,
+ cmathdecl,
+ enumdecl,
+ listdecl,
+ mathdecl,
+ npydecl,
+ setdecl,
+ dictdecl,
+ )
+ self.install_registry(cffi_utils.registry)
+ self.install_registry(cmathdecl.registry)
+ self.install_registry(enumdecl.registry)
+ self.install_registry(listdecl.registry)
+ self.install_registry(mathdecl.registry)
+ self.install_registry(npydecl.registry)
+ self.install_registry(setdecl.registry)
+ self.install_registry(dictdecl.registry)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/ctypes_utils.py b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/ctypes_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..3df27f9a239bcc4f5d17e9751d394da54ec5ecdc
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/ctypes_utils.py
@@ -0,0 +1,149 @@
+"""
+Support for typing ctypes function pointers.
+"""
+
+
+import ctypes
+import sys
+
+from numba.core import types, config
+from numba.core.typing import templates
+from .typeof import typeof_impl
+
+
+if config.USE_LEGACY_TYPE_SYSTEM:
+ _FROM_CTYPES = {
+ ctypes.c_bool: types.boolean,
+
+ ctypes.c_int8: types.int8,
+ ctypes.c_int16: types.int16,
+ ctypes.c_int32: types.int32,
+ ctypes.c_int64: types.int64,
+
+ ctypes.c_uint8: types.uint8,
+ ctypes.c_uint16: types.uint16,
+ ctypes.c_uint32: types.uint32,
+ ctypes.c_uint64: types.uint64,
+
+ ctypes.c_float: types.float32,
+ ctypes.c_double: types.float64,
+
+ ctypes.c_void_p: types.voidptr,
+ ctypes.py_object: types.ffi_forced_object,
+ }
+else:
+ _FROM_CTYPES = {
+ ctypes.c_bool: types.c_bool,
+
+ ctypes.c_int8: types.c_int8,
+ ctypes.c_int16: types.c_int16,
+ ctypes.c_int32: types.c_int32,
+ ctypes.c_int64: types.c_int64,
+
+ ctypes.c_uint8: types.c_uint8,
+ ctypes.c_uint16: types.c_uint16,
+ ctypes.c_uint32: types.c_uint32,
+ ctypes.c_uint64: types.c_uint64,
+
+ ctypes.c_float: types.c_float32,
+ ctypes.c_double: types.c_float64,
+
+ ctypes.c_void_p: types.voidptr,
+ ctypes.py_object: types.ffi_forced_object,
+ }
+
+_TO_CTYPES = {v: k for (k, v) in _FROM_CTYPES.items()}
+
+
+def from_ctypes(ctypeobj):
+ """
+ Convert the given ctypes type to a Numba type.
+ """
+ if ctypeobj is None:
+ # Special case for the restype of void-returning functions
+ return types.none
+
+ assert isinstance(ctypeobj, type), ctypeobj
+
+ def _convert_internal(ctypeobj):
+ # Recursive helper
+ if issubclass(ctypeobj, ctypes._Pointer):
+ valuety = _convert_internal(ctypeobj._type_)
+ if valuety is not None:
+ return types.CPointer(valuety)
+ else:
+ return _FROM_CTYPES.get(ctypeobj)
+
+ ty = _convert_internal(ctypeobj)
+ if ty is None:
+ raise TypeError("Unsupported ctypes type: %s" % ctypeobj)
+ return ty
+
+
+def to_ctypes(ty):
+ """
+ Convert the given Numba type to a ctypes type.
+ """
+ assert isinstance(ty, types.Type), ty
+
+ if ty is types.none:
+ # Special case for the restype of void-returning functions
+ return None
+
+ def _convert_internal(ty):
+ if isinstance(ty, types.CPointer):
+ return ctypes.POINTER(_convert_internal(ty.dtype))
+ else:
+ return _TO_CTYPES.get(ty)
+
+ ctypeobj = _convert_internal(ty)
+ if ctypeobj is None:
+ raise TypeError("Cannot convert Numba type '%s' to ctypes type"
+ % (ty,))
+ return ctypeobj
+
+
+def is_ctypes_funcptr(obj):
+ try:
+ # Is it something of which we can get the address
+ ctypes.cast(obj, ctypes.c_void_p)
+ except ctypes.ArgumentError:
+ return False
+ else:
+ # Does it define argtypes and restype
+ return hasattr(obj, 'argtypes') and hasattr(obj, 'restype')
+
+
+def get_pointer(ctypes_func):
+ """
+ Get a pointer to the underlying function for a ctypes function as an
+ integer.
+ """
+ return ctypes.cast(ctypes_func, ctypes.c_void_p).value
+
+
+def make_function_type(cfnptr):
+ """
+ Return a Numba type for the given ctypes function pointer.
+ """
+ if cfnptr.argtypes is None:
+ raise TypeError("ctypes function %r doesn't define its argument types; "
+ "consider setting the `argtypes` attribute"
+ % (cfnptr.__name__,))
+ cargs = [from_ctypes(a)
+ for a in cfnptr.argtypes]
+ cret = from_ctypes(cfnptr.restype)
+ # void* return type is a int/long on 32 bit platforms and an int on 64 bit
+ # platforms, explicit conversion to a int64 should match.
+ if cret == types.voidptr:
+ cret = types.uintp
+ if sys.platform == 'win32' and not cfnptr._flags_ & ctypes._FUNCFLAG_CDECL:
+ # 'stdcall' calling convention under Windows
+ cconv = 'x86_stdcallcc'
+ else:
+ # Default C calling convention
+ cconv = None
+
+ sig = templates.signature(cret, *cargs)
+ return types.ExternalFunctionPointer(sig, cconv=cconv,
+ get_pointer=get_pointer)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/dictdecl.py b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/dictdecl.py
new file mode 100644
index 0000000000000000000000000000000000000000..914ff176b554571e3832b8a5e157953d805b4d67
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/dictdecl.py
@@ -0,0 +1,55 @@
+"""
+This implements the typing template for `dict()`.
+"""
+
+from .. import types, errors
+from .templates import (
+ AbstractTemplate,
+ Registry,
+ signature,
+)
+
+registry = Registry()
+infer = registry.register
+infer_global = registry.register_global
+infer_getattr = registry.register_attr
+
+
+_message_dict_support = """
+Unsupported use of `dict()` with positional or keyword argument(s). \
+The only supported uses are `dict()` or `dict(iterable)`.
+""".strip()
+
+
+@infer_global(dict)
+class DictBuiltin(AbstractTemplate):
+ def generic(self, args, kws):
+ if kws:
+ raise errors.TypingError(_message_dict_support)
+ if args:
+ iterable, = args
+ if isinstance(iterable, types.IterableType):
+ dtype = iterable.iterator_type.yield_type
+ if isinstance(dtype, types.UniTuple):
+ length = dtype.count
+ if length != 2:
+ msg = ("dictionary update sequence element has length "
+ f"{length}; 2 is required")
+ raise errors.TypingError(msg)
+ k = v = dtype.key[0]
+ elif isinstance(dtype, types.Tuple):
+ k, v = dtype.key
+ else:
+ raise errors.TypingError(_message_dict_support)
+
+ # dict key must be hashable
+ if not isinstance(k, types.Hashable):
+ msg = f"Unhashable type: {k}"
+ raise errors.TypingError(msg)
+
+ return signature(types.DictType(k, v), iterable)
+ else:
+ msg = ("Non-iterable args used in dict(iterable) "
+ f"constructor. Got 'dict({args[0]})'")
+ raise errors.TypingError(msg)
+ return signature(types.DictType(types.undefined, types.undefined))
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/enumdecl.py b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/enumdecl.py
new file mode 100644
index 0000000000000000000000000000000000000000..ce3c4d6c94b6124df762c5f29d61034f973a9071
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/enumdecl.py
@@ -0,0 +1,64 @@
+"""
+Typing for enums.
+"""
+import operator
+from numba.core import types
+from numba.core.typing.templates import (AbstractTemplate, AttributeTemplate,
+ signature, Registry)
+
+registry = Registry()
+infer = registry.register
+infer_global = registry.register_global
+infer_getattr = registry.register_attr
+
+
+@infer_getattr
+class EnumAttribute(AttributeTemplate):
+ key = types.EnumMember
+
+ def resolve_value(self, ty):
+ return ty.dtype
+
+
+@infer_getattr
+class EnumClassAttribute(AttributeTemplate):
+ key = types.EnumClass
+
+ def generic_resolve(self, ty, attr):
+ """
+ Resolve attributes of an enum class as enum members.
+ """
+ if attr in ty.instance_class.__members__:
+ return ty.member_type
+
+
+@infer
+class EnumClassStaticGetItem(AbstractTemplate):
+ key = "static_getitem"
+
+ def generic(self, args, kws):
+ enum, idx = args
+ if (isinstance(enum, types.EnumClass)
+ and idx in enum.instance_class.__members__):
+ return signature(enum.member_type, *args)
+
+
+class EnumCompare(AbstractTemplate):
+
+ def generic(self, args, kws):
+ [lhs, rhs] = args
+ if (isinstance(lhs, types.EnumMember)
+ and isinstance(rhs, types.EnumMember)
+ and lhs == rhs):
+ return signature(types.boolean, lhs, rhs)
+
+
+@infer_global(operator.eq)
+class EnumEq(EnumCompare):
+ pass
+
+
+
+@infer_global(operator.ne)
+class EnumNe(EnumCompare):
+ pass
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/listdecl.py b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/listdecl.py
new file mode 100644
index 0000000000000000000000000000000000000000..52e0e950a45290c1c8d1d768efceaa291b7c97c3
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/listdecl.py
@@ -0,0 +1,140 @@
+import operator
+from numba.core import types
+from .templates import (ConcreteTemplate, AbstractTemplate, AttributeTemplate,
+ CallableTemplate, Registry, signature, bound_function,
+ make_callable_template)
+# Ensure list is typed as a collection as well
+from numba.core.typing import collections
+
+
+registry = Registry()
+infer = registry.register
+infer_global = registry.register_global
+infer_getattr = registry.register_attr
+
+
+@infer_global(list)
+class ListBuiltin(AbstractTemplate):
+
+ def generic(self, args, kws):
+ assert not kws
+ if args:
+ iterable, = args
+ if isinstance(iterable, types.IterableType):
+ dtype = iterable.iterator_type.yield_type
+ return signature(types.List(dtype), iterable)
+ else:
+ return signature(types.List(types.undefined))
+
+
+@infer_getattr
+class ListAttribute(AttributeTemplate):
+ key = types.List
+
+ # NOTE: some of these should be Sequence / MutableSequence methods
+
+ @bound_function("list.append")
+ def resolve_append(self, list, args, kws):
+ item, = args
+ assert not kws
+ unified = self.context.unify_pairs(list.dtype, item)
+ if unified is not None:
+ sig = signature(types.none, unified)
+ sig = sig.replace(recvr=list.copy(dtype=unified))
+ return sig
+
+ @bound_function("list.clear")
+ def resolve_clear(self, list, args, kws):
+ assert not args
+ assert not kws
+ return signature(types.none)
+
+ @bound_function("list.extend")
+ def resolve_extend(self, list, args, kws):
+ iterable, = args
+ assert not kws
+ if not isinstance(iterable, types.IterableType):
+ return
+
+ dtype = iterable.iterator_type.yield_type
+ unified = self.context.unify_pairs(list.dtype, dtype)
+ if unified is not None:
+ sig = signature(types.none, iterable)
+ sig = sig.replace(recvr = list.copy(dtype=unified))
+ return sig
+
+ @bound_function("list.insert")
+ def resolve_insert(self, list, args, kws):
+ idx, item = args
+ assert not kws
+ if isinstance(idx, types.Integer):
+ unified = self.context.unify_pairs(list.dtype, item)
+ if unified is not None:
+ sig = signature(types.none, types.intp, unified)
+ sig = sig.replace(recvr = list.copy(dtype=unified))
+ return sig
+
+ @bound_function("list.pop")
+ def resolve_pop(self, list, args, kws):
+ assert not kws
+ if not args:
+ return signature(list.dtype)
+ else:
+ idx, = args
+ if isinstance(idx, types.Integer):
+ return signature(list.dtype, types.intp)
+
+@infer_global(operator.add)
+class AddList(AbstractTemplate):
+
+ def generic(self, args, kws):
+ if len(args) == 2:
+ a, b = args
+ if isinstance(a, types.List) and isinstance(b, types.List):
+ unified = self.context.unify_pairs(a, b)
+ if unified is not None:
+ return signature(unified, a, b)
+
+
+@infer_global(operator.iadd)
+class InplaceAddList(AbstractTemplate):
+
+ def generic(self, args, kws):
+ if len(args) == 2:
+ a, b = args
+ if isinstance(a, types.List) and isinstance(b, types.List):
+ if self.context.can_convert(b.dtype, a.dtype):
+ return signature(a, a, b)
+
+
+@infer_global(operator.mul)
+class MulList(AbstractTemplate):
+ #key = operator.mul
+
+ def generic(self, args, kws):
+ a, b = args
+ if isinstance(a, types.List) and isinstance(b, types.Integer):
+ return signature(a, a, types.intp)
+ elif isinstance(a, types.Integer) and isinstance(b, types.List):
+ return signature(b, types.intp, b)
+
+
+@infer_global(operator.imul)
+class InplaceMulList(MulList): pass
+ #key = operator.imul
+
+
+class ListCompare(AbstractTemplate):
+
+ def generic(self, args, kws):
+ [lhs, rhs] = args
+ if isinstance(lhs, types.List) and isinstance(rhs, types.List):
+ # Check element-wise comparability
+ res = self.context.resolve_function_type(self.key,
+ (lhs.dtype, rhs.dtype), {})
+ if res is not None:
+ return signature(types.boolean, lhs, rhs)
+
+@infer_global(operator.eq)
+class ListEq(ListCompare): pass
+ #key = operator.eq
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/mathdecl.py b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/mathdecl.py
new file mode 100644
index 0000000000000000000000000000000000000000..20f1385d33b2004736a271d769c4b7f26e256820
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/mathdecl.py
@@ -0,0 +1,14 @@
+import sys
+from numba.core.utils import _RedirectSubpackage
+from numba.core import config
+
+if config.USE_LEGACY_TYPE_SYSTEM:
+ sys.modules[__name__] = _RedirectSubpackage(
+ locals(),
+ "numba.core.typing.old_mathdecl"
+ )
+else:
+ sys.modules[__name__] = _RedirectSubpackage(
+ locals(),
+ "numba.core.typing.new_mathdecl"
+ )
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/new_builtins.py b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/new_builtins.py
new file mode 100644
index 0000000000000000000000000000000000000000..1a05e6ed4987685cf644b1c184b576bd39f760ba
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/new_builtins.py
@@ -0,0 +1,1163 @@
+import itertools
+
+import numpy as np
+import operator
+
+from numba.core import types, errors, config
+from numba import prange
+from numba.parfors.parfor import internal_prange
+
+from numba.core.typing.templates import (AttributeTemplate, ConcreteTemplate,
+ AbstractTemplate, infer_global, infer,
+ infer_getattr, signature,
+ bound_function, make_callable_template)
+
+
+from numba.core.extending import (
+ typeof_impl, type_callable, models, register_model, make_attribute_wrapper,
+ )
+
+
+@infer_global(print)
+class Print(AbstractTemplate):
+ def generic(self, args, kws):
+ for a in args:
+ sig = self.context.resolve_function_type("print_item", (a,), {})
+ if sig is None:
+ raise errors.TypingError("Type %s is not printable." % a)
+ assert sig.return_type is types.none
+ return signature(types.none, *args)
+
+@infer
+class PrintItem(AbstractTemplate):
+ key = "print_item"
+
+ def generic(self, args, kws):
+ arg, = args
+ return signature(types.none, *args)
+
+
+@infer_global(abs)
+class Abs(ConcreteTemplate):
+ int_cases = [signature(ty, ty) for ty in sorted(types.py_signed_domain)]
+ real_cases = [signature(ty, ty) for ty in sorted(types.py_real_domain)]
+ complex_cases = [signature(ty.underlying_float, ty)
+ for ty in sorted(types.py_complex_domain)]
+ cases = int_cases + real_cases + complex_cases
+
+
+@infer_global(slice)
+class Slice(ConcreteTemplate):
+ cases = [
+ signature(types.slice2_type, types.py_int),
+ signature(types.slice2_type, types.none),
+ signature(types.slice2_type, types.none, types.none),
+ signature(types.slice2_type, types.none, types.py_int),
+ signature(types.slice2_type, types.py_int, types.none),
+ signature(types.slice2_type, types.py_int, types.py_int),
+ signature(types.slice3_type, types.py_int, types.py_int, types.py_int),
+ signature(types.slice3_type, types.none, types.py_int, types.py_int),
+ signature(types.slice3_type, types.py_int, types.none, types.py_int),
+ signature(types.slice3_type, types.py_int, types.py_int, types.none),
+ signature(types.slice3_type, types.py_int, types.none, types.none),
+ signature(types.slice3_type, types.none, types.py_int, types.none),
+ signature(types.slice3_type, types.none, types.none, types.py_int),
+ signature(types.slice3_type, types.none, types.none, types.none),
+ ]
+
+
+@infer_global(range, typing_key=range)
+@infer_global(prange, typing_key=prange)
+@infer_global(internal_prange, typing_key=internal_prange)
+class Range(ConcreteTemplate):
+ cases = [
+ signature(types.range_state_type, types.py_int),
+ signature(types.range_state_type, types.py_int, types.py_int),
+ signature(types.range_state_type, types.py_int, types.py_int,
+ types.py_int),
+ ]
+
+
+@infer
+class GetIter(AbstractTemplate):
+ key = "getiter"
+
+ def generic(self, args, kws):
+ assert not kws
+ [obj] = args
+ if isinstance(obj, types.IterableType):
+ return signature(obj.iterator_type, obj)
+
+
+@infer
+class IterNext(AbstractTemplate):
+ key = "iternext"
+
+ def generic(self, args, kws):
+ assert not kws
+ [it] = args
+ if isinstance(it, types.IteratorType):
+ return signature(types.Pair(it.yield_type, types.py_bool), it)
+
+
+@infer
+class PairFirst(AbstractTemplate):
+ """
+ Given a heterogeneous pair, return the first element.
+ """
+ key = "pair_first"
+
+ def generic(self, args, kws):
+ assert not kws
+ [pair] = args
+ if isinstance(pair, types.Pair):
+ return signature(pair.first_type, pair)
+
+
+@infer
+class PairSecond(AbstractTemplate):
+ """
+ Given a heterogeneous pair, return the second element.
+ """
+ key = "pair_second"
+
+ def generic(self, args, kws):
+ assert not kws
+ [pair] = args
+ if isinstance(pair, types.Pair):
+ return signature(pair.second_type, pair)
+
+
+def choose_result_bitwidth(*inputs):
+ return max(tp.bitwidth for tp in inputs)
+
+def choose_result_int(*inputs):
+ """
+ Choose the integer result type for an operation on integer inputs,
+ according to the integer typing NBEP. In accordance with the new
+ type system.
+ """
+ bitwidth = choose_result_bitwidth(*inputs)
+ signed = any(tp.signed for tp in inputs)
+
+ # If any integer is a NumPy integer, promotion should be to the
+ # respective NumPy type.
+ if any('np' in tp.name for tp in inputs):
+ return types.NumPyInteger.from_bitwidth(bitwidth, signed)
+
+ return types.py_int
+
+all_ints = (
+ sorted(set((types.py_int, types.py_int))) +
+ sorted(set((types.np_int32, types.np_int64))) +
+ sorted(set((types.np_uint32, types.np_uint64)))
+ )
+integer_binop_cases = tuple(
+ signature(choose_result_int(op1, op2), op1, op2)
+ for op1, op2 in itertools.product(all_ints, all_ints)
+ )
+
+class BinOp(ConcreteTemplate):
+ cases = list(integer_binop_cases)
+
+ cases += [signature(op, op, op) for op in sorted(types.py_real_domain)]
+ cases += [signature(op, op, op) for op in sorted(types.py_complex_domain)]
+ cases += [signature(op, op, op) for op in sorted(types.np_real_domain)]
+ cases += [signature(op, op, op) for op in sorted(types.np_complex_domain)]
+
+
+@infer_global(operator.add)
+class BinOpAdd(BinOp):
+ pass
+
+
+@infer_global(operator.iadd)
+class BinOpAdd(BinOp):
+ pass
+
+
+@infer_global(operator.sub)
+class BinOpSub(BinOp):
+ pass
+
+
+@infer_global(operator.isub)
+class BinOpSub(BinOp):
+ pass
+
+
+@infer_global(operator.mul)
+class BinOpMul(BinOp):
+ pass
+
+
+@infer_global(operator.imul)
+class BinOpMul(BinOp):
+ pass
+
+
+@infer_global(operator.mod)
+class BinOpMod(ConcreteTemplate):
+ cases = list(integer_binop_cases)
+ cases += [signature(op, op, op) for op in sorted(types.np_real_domain)]
+
+
+@infer_global(operator.imod)
+class BinOpMod(ConcreteTemplate):
+ cases = list(integer_binop_cases)
+ cases += [signature(op, op, op) for op in sorted(types.np_real_domain)]
+
+
+@infer_global(operator.truediv)
+class BinOpTrueDiv(ConcreteTemplate):
+ cases = [signature(types.np_float64, op1, op2)
+ for op1, op2 in itertools.product(all_ints, all_ints)]
+ cases += [signature(op, op, op) for op in sorted(types.np_real_domain)]
+ cases += [signature(op, op, op) for op in sorted(types.np_complex_domain)]
+
+
+@infer_global(operator.itruediv)
+class BinOpTrueDiv(ConcreteTemplate):
+ cases = [signature(types.np_float64, op1, op2)
+ for op1, op2 in itertools.product(all_ints, all_ints)]
+ cases += [signature(op, op, op) for op in sorted(types.np_real_domain)]
+ cases += [signature(op, op, op) for op in sorted(types.np_complex_domain)]
+
+
+@infer_global(operator.floordiv)
+class BinOpFloorDiv(ConcreteTemplate):
+ cases = list(integer_binop_cases)
+ cases += [signature(op, op, op) for op in sorted(types.np_real_domain)]
+
+
+@infer_global(operator.ifloordiv)
+class BinOpFloorDiv(ConcreteTemplate):
+ cases = list(integer_binop_cases)
+ cases += [signature(op, op, op) for op in sorted(types.np_real_domain)]
+
+
+@infer_global(divmod)
+class DivMod(ConcreteTemplate):
+ _tys = all_ints + sorted(types.np_real_domain)
+ cases = [signature(types.UniTuple(ty, 2), ty, ty) for ty in _tys]
+
+
+@infer_global(operator.pow)
+class BinOpPower(ConcreteTemplate):
+ cases = list(integer_binop_cases)
+ # Ensure that float32 ** int doesn't go through DP computations
+ cases += [signature(types.np_float32, types.np_float32, op)
+ for op in (types.np_int32, types.np_int64, types.np_uint64)]
+ cases += [signature(types.np_float64, types.np_float64, op)
+ for op in (types.np_int32, types.np_int64, types.np_uint64)]
+ cases += [signature(op, op, op)
+ for op in sorted(types.np_real_domain)]
+ cases += [signature(op, op, op)
+ for op in sorted(types.np_complex_domain)]
+
+
+@infer_global(operator.ipow)
+class BinOpPower(ConcreteTemplate):
+ cases = list(integer_binop_cases)
+ # Ensure that float32 ** int doesn't go through DP computations
+ cases += [signature(types.np_float32, types.np_float32, op)
+ for op in (types.np_int32, types.np_int64, types.np_uint64)]
+ cases += [signature(types.np_float64, types.np_float64, op)
+ for op in (types.np_int32, types.np_int64, types.np_uint64)]
+ cases += [signature(op, op, op)
+ for op in sorted(types.np_real_domain)]
+ cases += [signature(op, op, op)
+ for op in sorted(types.np_complex_domain)]
+
+
+@infer_global(pow)
+class PowerBuiltin(BinOpPower):
+ # TODO add 3 operand version
+ pass
+
+
+class BitwiseShiftOperation(ConcreteTemplate):
+ # For bitshifts, only the first operand's signedness matters
+ # to choose the operation's signedness (the second operand
+ # should always be positive but will generally be considered
+ # signed anyway, since it's often a constant integer).
+ # (also, see issue #1995 for right-shifts)
+
+ # The RHS type is fixed to 64-bit signed/unsigned ints.
+ # The implementation will always cast the operands to the width of the
+ # result type, which is the widest between the LHS type and (u)intp.
+ cases = [signature(max(op, types.py_int), op, op2)
+ for op in types.py_signed_domain
+ for op2 in types.py_signed_domain]
+ unsafe_casting = False
+
+
+@infer_global(operator.lshift)
+class BitwiseLeftShift(BitwiseShiftOperation):
+ pass
+
+@infer_global(operator.ilshift)
+class BitwiseLeftShift(BitwiseShiftOperation):
+ pass
+
+
+@infer_global(operator.rshift)
+class BitwiseRightShift(BitwiseShiftOperation):
+ pass
+
+
+@infer_global(operator.irshift)
+class BitwiseRightShift(BitwiseShiftOperation):
+ pass
+
+
+class BitwiseLogicOperation(BinOp):
+ cases = [signature(types.py_bool, types.py_bool, types.py_bool)]
+ cases += [signature(types.np_bool_, types.np_bool_, types.np_bool_)]
+ cases += list(integer_binop_cases)
+ unsafe_casting = False
+
+
+@infer_global(operator.and_)
+class BitwiseAnd(BitwiseLogicOperation):
+ pass
+
+
+@infer_global(operator.iand)
+class BitwiseAnd(BitwiseLogicOperation):
+ pass
+
+
+@infer_global(operator.or_)
+class BitwiseOr(BitwiseLogicOperation):
+ pass
+
+
+@infer_global(operator.ior)
+class BitwiseOr(BitwiseLogicOperation):
+ pass
+
+
+@infer_global(operator.xor)
+class BitwiseXor(BitwiseLogicOperation):
+ pass
+
+
+@infer_global(operator.ixor)
+class BitwiseXor(BitwiseLogicOperation):
+ pass
+
+
+# Bitwise invert and negate are special: we must not upcast the operand
+# for unsigned numbers, as that would change the result.
+# (i.e. ~np.int8(0) == 255 but ~np.int32(0) == 4294967295).
+
+@infer_global(operator.invert)
+class BitwiseInvert(ConcreteTemplate):
+ # Note Numba follows the Numpy semantics of returning a bool,
+ # while Python returns an int. This makes it consistent with
+ # np.invert() and makes array expressions correct.
+ cases = [signature(types.py_bool, types.py_bool)]
+ cases = [signature(types.np_bool_, types.np_bool_)]
+
+ cases += [signature(choose_result_int(op), op) for op in sorted(types.np_unsigned_domain)]
+
+ cases += [signature(choose_result_int(op), op) for op in sorted(types.py_signed_domain)]
+ cases += [signature(choose_result_int(op), op) for op in sorted(types.np_signed_domain)]
+
+
+ unsafe_casting = False
+
+
+class UnaryOp(ConcreteTemplate):
+ cases = [signature(choose_result_int(op), op) for op in sorted(types.np_unsigned_domain)]
+ cases += [signature(choose_result_int(op), op) for op in sorted(types.py_signed_domain)]
+ cases += [signature(choose_result_int(op), op) for op in sorted(types.np_signed_domain)]
+
+ cases += [signature(op, op) for op in sorted(types.py_real_domain)]
+ cases += [signature(op, op) for op in sorted(types.np_real_domain)]
+
+ cases += [signature(op, op) for op in sorted(types.py_complex_domain)]
+ cases += [signature(op, op) for op in sorted(types.np_complex_domain)]
+
+ cases += [signature(types.py_int, types.py_bool)]
+ cases += [signature(types.np_intp, types.np_bool_)]
+
+
+@infer_global(operator.neg)
+class UnaryNegate(UnaryOp):
+ pass
+
+
+@infer_global(operator.pos)
+class UnaryPositive(UnaryOp):
+ pass
+
+
+@infer_global(operator.not_)
+class UnaryNot(ConcreteTemplate):
+ cases = [signature(types.np_bool_, types.np_bool_)]
+ cases += [signature(types.np_bool_, op) for op in sorted(types.np_signed_domain)]
+ cases += [signature(types.np_bool_, op) for op in sorted(types.np_unsigned_domain)]
+ cases += [signature(types.np_bool_, op) for op in sorted(types.np_real_domain)]
+ cases += [signature(types.np_bool_, op) for op in sorted(types.np_complex_domain)]
+
+
+class OrderedCmpOp(ConcreteTemplate):
+ cases = [signature(types.py_bool, types.py_bool, types.py_bool)]
+ cases += [signature(types.py_bool, op, op) for op in sorted(types.py_signed_domain)]
+ cases += [signature(types.py_bool, op, op) for op in sorted(types.py_real_domain)]
+ cases = [signature(types.np_bool_, types.np_bool_, types.np_bool_)]
+ cases += [signature(types.np_bool_, op, op) for op in sorted(types.np_signed_domain)]
+ cases += [signature(types.np_bool_, op, op) for op in sorted(types.np_unsigned_domain)]
+ cases += [signature(types.np_bool_, op, op) for op in sorted(types.np_real_domain)]
+
+
+class UnorderedCmpOp(ConcreteTemplate):
+ cases = OrderedCmpOp.cases + [
+ signature(types.py_bool, op, op) for op in sorted(types.py_complex_domain)] + [
+ signature(types.np_bool_, op, op) for op in sorted(types.np_complex_domain)]
+
+
+@infer_global(operator.lt)
+class CmpOpLt(OrderedCmpOp):
+ pass
+
+
+@infer_global(operator.le)
+class CmpOpLe(OrderedCmpOp):
+ pass
+
+
+@infer_global(operator.gt)
+class CmpOpGt(OrderedCmpOp):
+ pass
+
+
+@infer_global(operator.ge)
+class CmpOpGe(OrderedCmpOp):
+ pass
+
+
+# more specific overloads should be registered first
+@infer_global(operator.eq)
+class ConstOpEq(AbstractTemplate):
+ def generic(self, args, kws):
+ assert not kws
+ (arg1, arg2) = args
+ if isinstance(arg1, types.Literal) and isinstance(arg2, types.Literal):
+ return signature(types.np_bool_, arg1, arg2)
+
+
+@infer_global(operator.ne)
+class ConstOpNotEq(ConstOpEq):
+ pass
+
+
+@infer_global(operator.eq)
+class CmpOpEq(UnorderedCmpOp):
+ pass
+
+
+@infer_global(operator.ne)
+class CmpOpNe(UnorderedCmpOp):
+ pass
+
+
+class TupleCompare(AbstractTemplate):
+ def generic(self, args, kws):
+ [lhs, rhs] = args
+ if isinstance(lhs, types.BaseTuple) and isinstance(rhs, types.BaseTuple):
+ for u, v in zip(lhs, rhs):
+ # Check element-wise comparability
+ res = self.context.resolve_function_type(self.key, (u, v), {})
+ if res is None:
+ break
+ else:
+ return signature(types.py_bool, lhs, rhs)
+
+
+@infer_global(operator.eq)
+class TupleEq(TupleCompare):
+ pass
+
+
+@infer_global(operator.ne)
+class TupleNe(TupleCompare):
+ pass
+
+
+@infer_global(operator.ge)
+class TupleGe(TupleCompare):
+ pass
+
+
+@infer_global(operator.gt)
+class TupleGt(TupleCompare):
+ pass
+
+
+@infer_global(operator.le)
+class TupleLe(TupleCompare):
+ pass
+
+
+@infer_global(operator.lt)
+class TupleLt(TupleCompare):
+ pass
+
+
+@infer_global(operator.add)
+class TupleAdd(AbstractTemplate):
+ def generic(self, args, kws):
+ if len(args) == 2:
+ a, b = args
+ if (isinstance(a, types.BaseTuple) and isinstance(b, types.BaseTuple)
+ and not isinstance(a, types.BaseNamedTuple)
+ and not isinstance(b, types.BaseNamedTuple)):
+ res = types.BaseTuple.from_types(tuple(a) + tuple(b))
+ return signature(res, a, b)
+
+
+class CmpOpIdentity(AbstractTemplate):
+ def generic(self, args, kws):
+ [lhs, rhs] = args
+ return signature(types.py_bool, lhs, rhs)
+
+
+@infer_global(operator.is_)
+class CmpOpIs(CmpOpIdentity):
+ pass
+
+
+@infer_global(operator.is_not)
+class CmpOpIsNot(CmpOpIdentity):
+ pass
+
+
+def normalize_1d_index(index):
+ """
+ Normalize the *index* type (an integer or slice) for indexing a 1D
+ sequence.
+ """
+ if isinstance(index, types.SliceType):
+ return index
+
+ elif isinstance(index, types.Integer):
+ return types.np_intp if index.signed else types.uintp
+
+
+@infer_global(operator.getitem)
+class GetItemCPointer(AbstractTemplate):
+ def generic(self, args, kws):
+ assert not kws
+ ptr, idx = args
+ if isinstance(ptr, types.CPointer) and isinstance(idx, types.Integer):
+ return signature(ptr.dtype, ptr, normalize_1d_index(idx))
+
+
+@infer_global(operator.setitem)
+class SetItemCPointer(AbstractTemplate):
+ def generic(self, args, kws):
+ assert not kws
+ ptr, idx, val = args
+ if isinstance(ptr, types.CPointer) and isinstance(idx, types.Integer):
+ return signature(types.none, ptr, normalize_1d_index(idx), ptr.dtype)
+
+
+@infer_global(len)
+class Len(AbstractTemplate):
+ def generic(self, args, kws):
+ assert not kws
+ (val,) = args
+ if isinstance(val, (types.Buffer, types.BaseTuple)):
+ return signature(types.py_int, val)
+ elif isinstance(val, (types.RangeType)):
+ return signature(val.dtype, val)
+
+@infer_global(tuple)
+class TupleConstructor(AbstractTemplate):
+ def generic(self, args, kws):
+ assert not kws
+ # empty tuple case
+ if len(args) == 0:
+ return signature(types.Tuple(()))
+ (val,) = args
+ # tuple as input
+ if isinstance(val, types.BaseTuple):
+ return signature(val, val)
+
+
+@infer_global(operator.contains)
+class Contains(AbstractTemplate):
+ def generic(self, args, kws):
+ assert not kws
+ (seq, val) = args
+
+ if isinstance(seq, (types.Sequence)):
+ return signature(types.py_bool, seq, val)
+
+@infer_global(operator.truth)
+class TupleBool(AbstractTemplate):
+ def generic(self, args, kws):
+ assert not kws
+ (val,) = args
+ if isinstance(val, (types.BaseTuple)):
+ return signature(types.py_bool, val)
+
+
+@infer
+class StaticGetItemTuple(AbstractTemplate):
+ key = "static_getitem"
+
+ def generic(self, args, kws):
+ tup, idx = args
+ ret = None
+ if not isinstance(tup, types.BaseTuple):
+ return
+ if isinstance(idx, int):
+ try:
+ ret = tup.types[idx]
+ except IndexError:
+ raise errors.NumbaIndexError("tuple index out of range")
+ elif isinstance(idx, slice):
+ ret = types.BaseTuple.from_types(tup.types[idx])
+ if ret is not None:
+ sig = signature(ret, *args)
+ return sig
+
+
+@infer
+class StaticGetItemLiteralList(AbstractTemplate):
+ key = "static_getitem"
+
+ def generic(self, args, kws):
+ tup, idx = args
+ ret = None
+ if not isinstance(tup, types.LiteralList):
+ return
+ if isinstance(idx, int):
+ ret = tup.types[idx]
+ if ret is not None:
+ sig = signature(ret, *args)
+ return sig
+
+
+@infer
+class StaticGetItemLiteralStrKeyDict(AbstractTemplate):
+ key = "static_getitem"
+
+ def generic(self, args, kws):
+ tup, idx = args
+ ret = None
+ if not isinstance(tup, types.LiteralStrKeyDict):
+ return
+ if isinstance(idx, str):
+ if idx in tup.fields:
+ lookup = tup.fields.index(idx)
+ else:
+ raise errors.NumbaKeyError(f"Key '{idx}' is not in dict.")
+ ret = tup.types[lookup]
+ if ret is not None:
+ sig = signature(ret, *args)
+ return sig
+
+@infer
+class StaticGetItemClass(AbstractTemplate):
+ """This handles the "static_getitem" when a Numba type is subscripted e.g:
+ var = typed.List.empty_list(float64[::1, :])
+ It only allows this on simple numerical types. Compound types, like
+ records, are not supported.
+ """
+ key = "static_getitem"
+
+ def generic(self, args, kws):
+ clazz, idx = args
+ if not isinstance(clazz, types.NumberClass):
+ return
+ ret = clazz.dtype[idx]
+ sig = signature(ret, *args)
+ return sig
+
+
+# Generic implementation for "not in"
+
+@infer
+class GenericNotIn(AbstractTemplate):
+ key = "not in"
+
+ def generic(self, args, kws):
+ args = args[::-1]
+ sig = self.context.resolve_function_type(operator.contains, args, kws)
+ return signature(sig.return_type, *sig.args[::-1])
+
+
+#-------------------------------------------------------------------------------
+
+@infer_getattr
+class MemoryViewAttribute(AttributeTemplate):
+ key = types.MemoryView
+
+ def resolve_contiguous(self, buf):
+ return types.py_bool
+
+ def resolve_c_contiguous(self, buf):
+ return types.py_bool
+
+ def resolve_f_contiguous(self, buf):
+ return types.py_bool
+
+ def resolve_itemsize(self, buf):
+ return types.py_int
+
+ def resolve_nbytes(self, buf):
+ return types.py_int
+
+ def resolve_readonly(self, buf):
+ return types.py_bool
+
+ def resolve_shape(self, buf):
+ return types.UniTuple(types.py_int, buf.ndim)
+
+ def resolve_strides(self, buf):
+ return types.UniTuple(types.py_int, buf.ndim)
+
+ def resolve_ndim(self, buf):
+ return types.py_int
+
+
+#-------------------------------------------------------------------------------
+
+
+@infer_getattr
+class BooleanAttribute(AttributeTemplate):
+ key = types.Boolean
+
+ def resolve___class__(self, ty):
+ return types.NumberClass(ty)
+
+ @bound_function("number.item")
+ def resolve_item(self, ty, args, kws):
+ assert not kws
+ if not args:
+ return signature(ty)
+
+
+@infer_getattr
+class NumberAttribute(AttributeTemplate):
+ key = types.Number
+
+ def resolve___class__(self, ty):
+ return types.NumberClass(ty)
+
+ def resolve_real(self, ty):
+ return getattr(ty, "underlying_float", ty)
+
+ def resolve_imag(self, ty):
+ return getattr(ty, "underlying_float", ty)
+
+ @bound_function("complex.conjugate")
+ def resolve_conjugate(self, ty, args, kws):
+ assert not args
+ assert not kws
+ return signature(ty)
+
+ @bound_function("number.item")
+ def resolve_item(self, ty, args, kws):
+ assert not kws
+ if not args:
+ return signature(ty)
+
+
+@infer_getattr
+class NPTimedeltaAttribute(AttributeTemplate):
+ key = types.NPTimedelta
+
+ def resolve___class__(self, ty):
+ return types.NumberClass(ty)
+
+
+@infer_getattr
+class NPDatetimeAttribute(AttributeTemplate):
+ key = types.NPDatetime
+
+ def resolve___class__(self, ty):
+ return types.NumberClass(ty)
+
+
+@infer_getattr
+class SliceAttribute(AttributeTemplate):
+ key = types.SliceType
+
+ def resolve_start(self, ty):
+ return types.py_int
+
+ def resolve_stop(self, ty):
+ return types.py_int
+
+ def resolve_step(self, ty):
+ return types.py_int
+
+ @bound_function("slice.indices")
+ def resolve_indices(self, ty, args, kws):
+ assert not kws
+ if len(args) != 1:
+ raise errors.NumbaTypeError(
+ "indices() takes exactly one argument (%d given)" % len(args)
+ )
+ typ, = args
+ if not isinstance(typ, types.Integer):
+ raise errors.NumbaTypeError(
+ "'%s' object cannot be interpreted as an integer" % typ
+ )
+ return signature(types.UniTuple(types.py_int, 3), types.py_int)
+
+
+#-------------------------------------------------------------------------------
+
+
+@infer_getattr
+class NumberClassAttribute(AttributeTemplate):
+ key = types.NumberClass
+
+ def resolve___call__(self, classty):
+ """
+ Resolve a NumPy number class's constructor (e.g. calling numpy.int32(...))
+ """
+ ty = classty.instance_type
+
+ def typer(val):
+ if isinstance(val, (types.BaseTuple, types.Sequence)):
+ # Array constructor, e.g. np.int32([1, 2])
+ fnty = self.context.resolve_value_type(np.array)
+ sig = fnty.get_call_type(self.context, (val, types.DType(ty)),
+ {})
+ return sig.return_type
+ elif isinstance(val, (types.Number, types.Boolean, types.IntEnumMember)):
+ # Scalar constructor, e.g. np.int32(42)
+ return ty
+ elif isinstance(val, (types.NPDatetime, types.NPTimedelta)):
+ # Constructor cast from datetime-like, e.g.
+ # > np.int64(np.datetime64("2000-01-01"))
+ if ty.bitwidth == 64:
+ return ty
+ else:
+ msg = (f"Cannot cast {val} to {ty} as {ty} is not 64 bits "
+ "wide.")
+ raise errors.TypingError(msg)
+ else:
+ if (isinstance(val, types.Array) and val.ndim == 0 and
+ val.dtype == ty):
+ # This is 0d array -> scalar degrading
+ return ty
+ else:
+ # unsupported
+ msg = f"Casting {val} to {ty} directly is unsupported."
+ if isinstance(val, types.Array):
+ # array casts are supported a different way.
+ msg += f" Try doing '.astype(np.{ty})' instead"
+ raise errors.TypingError(msg)
+
+ return types.Function(make_callable_template(key=ty, typer=typer))
+
+
+@infer_getattr
+class TypeRefAttribute(AttributeTemplate):
+ key = types.TypeRef
+
+ def resolve___call__(self, classty):
+ """
+ Resolve a core number's constructor (e.g. calling int(...))
+
+ Note:
+
+ This is needed because of the limitation of the current type-system
+ implementation. Specifically, the lack of a higher-order type
+ (i.e. passing the ``DictType`` vs ``DictType(key_type, value_type)``)
+ """
+ ty = classty.instance_type
+
+ if isinstance(ty, type) and issubclass(ty, types.Type):
+ # Redirect the typing to a:
+ # @type_callable(ty)
+ # def typeddict_call(context):
+ # ...
+ # For example, see numba/typed/typeddict.py
+ # @type_callable(DictType)
+ # def typeddict_call(context):
+ class Redirect(object):
+
+ def __init__(self, context):
+ self.context = context
+
+ def __call__(self, *args, **kwargs):
+ result = self.context.resolve_function_type(ty, args, kwargs)
+ if hasattr(result, "pysig"):
+ self.pysig = result.pysig
+ return result
+
+ return types.Function(make_callable_template(key=ty,
+ typer=Redirect(self.context)))
+
+
+#------------------------------------------------------------------------------
+
+
+class MinMaxBase(AbstractTemplate):
+
+ def _unify_minmax(self, tys):
+ for ty in tys:
+ if not isinstance(ty, (types.Number, types.NPDatetime, types.NPTimedelta)):
+ return
+ return self.context.unify_types(*tys)
+
+ def generic(self, args, kws):
+ """
+ Resolve a min() or max() call.
+ """
+ assert not kws
+
+ if not args:
+ return
+ if len(args) == 1:
+ # max(arg) only supported if arg is an iterable
+ if isinstance(args[0], types.BaseTuple):
+ tys = list(args[0])
+ if not tys:
+ raise errors.TypingError("%s() argument is an empty tuple"
+ % (self.key.__name__,))
+ else:
+ return
+ else:
+ # max(*args)
+ tys = args
+ retty = self._unify_minmax(tys)
+ if retty is not None:
+ return signature(retty, *args)
+
+
+@infer_global(max)
+class Max(MinMaxBase):
+ pass
+
+
+@infer_global(min)
+class Min(MinMaxBase):
+ pass
+
+
+@infer_global(round)
+class Round(ConcreteTemplate):
+ cases = [
+ signature(types.py_int, types.py_float),
+ signature(types.py_float, types.py_float, types.py_int)
+ ]
+
+
+#------------------------------------------------------------------------------
+
+
+@infer_global(bool)
+class Bool(AbstractTemplate):
+
+ def generic(self, args, kws):
+ assert not kws
+ [arg] = args
+ if isinstance(arg, (types.Boolean, types.Number)):
+ return signature(types.py_bool, arg)
+ # XXX typing for bool cannot be polymorphic because of the
+ # types.Function thing, so we redirect to the operator.truth
+ # intrinsic.
+ return self.context.resolve_function_type(operator.truth, args, kws)
+
+
+@infer_global(int)
+class Int(AbstractTemplate):
+
+ def generic(self, args, kws):
+ if kws:
+ raise errors.NumbaAssertionError('kws not supported')
+
+ [arg] = args
+
+ if isinstance(arg, (types.Integer, types.Float,
+ types.Boolean, types.NPDatetime,
+ types.NPTimedelta)):
+ return signature(types.py_int, arg)
+
+
+@infer_global(float)
+class Float(AbstractTemplate):
+
+ def generic(self, args, kws):
+ assert not kws
+
+ [arg] = args
+
+ if arg not in types.py_number_domain or arg not in types.np_number_domain:
+ raise errors.NumbaTypeError("float() only support for numbers")
+
+ if arg in types.py_complex_domain or arg in types.np_complex_domain:
+ raise errors.NumbaTypeError("float() does not support complex")
+
+ return signature(types.py_float, arg)
+
+
+
+@infer_global(complex)
+class Complex(AbstractTemplate):
+
+ def generic(self, args, kws):
+ assert not kws
+ number_domain = types.py_number_domain | types.np_number_domain
+
+ if len(args) == 1:
+ [arg] = args
+ if arg not in number_domain:
+ raise errors.NumbaTypeError("complex() only support for numbers")
+
+ return signature(types.py_complex, arg)
+
+ elif len(args) == 2:
+ [real, imag] = args
+ if (real not in number_domain or
+ imag not in number_domain):
+ raise errors.NumbaTypeError("complex() only support for numbers")
+
+ return signature(types.py_complex, real, imag)
+
+
+#------------------------------------------------------------------------------
+
+@infer_global(enumerate)
+class Enumerate(AbstractTemplate):
+
+ def generic(self, args, kws):
+ assert not kws
+ it = args[0]
+ if len(args) > 1 and not isinstance(args[1], types.Integer):
+ raise errors.NumbaTypeError("Only integers supported as start "
+ "value in enumerate")
+ elif len(args) > 2:
+ #let python raise its own error
+ enumerate(*args)
+
+ if isinstance(it, types.IterableType):
+ enumerate_type = types.EnumerateType(it)
+ return signature(enumerate_type, *args)
+
+
+@infer_global(zip)
+class Zip(AbstractTemplate):
+
+ def generic(self, args, kws):
+ assert not kws
+ if all(isinstance(it, types.IterableType) for it in args):
+ zip_type = types.ZipType(args)
+ return signature(zip_type, *args)
+
+
+@infer_global(iter)
+class Iter(AbstractTemplate):
+
+ def generic(self, args, kws):
+ assert not kws
+ if len(args) == 1:
+ it = args[0]
+ if isinstance(it, types.IterableType):
+ return signature(it.iterator_type, *args)
+
+
+@infer_global(next)
+class Next(AbstractTemplate):
+
+ def generic(self, args, kws):
+ assert not kws
+ if len(args) == 1:
+ it = args[0]
+ if isinstance(it, types.IteratorType):
+ return signature(it.yield_type, *args)
+
+
+#------------------------------------------------------------------------------
+
+@infer_global(type)
+class TypeBuiltin(AbstractTemplate):
+
+ def generic(self, args, kws):
+ assert not kws
+ if len(args) == 1:
+ # One-argument type() -> return the __class__
+ # Avoid literal types
+ arg = types.unliteral(args[0])
+ classty = self.context.resolve_getattr(arg, "__class__")
+ if classty is not None:
+ return signature(classty, *args)
+
+
+#------------------------------------------------------------------------------
+
+@infer_getattr
+class OptionalAttribute(AttributeTemplate):
+ key = types.Optional
+
+ def generic_resolve(self, optional, attr):
+ return self.context.resolve_getattr(optional.type, attr)
+
+#------------------------------------------------------------------------------
+
+@infer_getattr
+class DeferredAttribute(AttributeTemplate):
+ key = types.DeferredType
+
+ def generic_resolve(self, deferred, attr):
+ return self.context.resolve_getattr(deferred.get(), attr)
+
+#------------------------------------------------------------------------------
+
+
+class IndexValue(object):
+ """
+ Index and value
+ """
+ def __init__(self, ind, val):
+ self.index = ind
+ self.value = val
+
+ def __repr__(self):
+ return 'IndexValue(%f, %f)' % (self.index, self.value)
+
+
+class IndexValueType(types.Type):
+ def __init__(self, val_typ):
+ self.val_typ = val_typ
+ super(IndexValueType, self).__init__(
+ name='IndexValueType({})'.format(val_typ))
+
+
+@typeof_impl.register(IndexValue)
+def typeof_index(val, c):
+ val_typ = typeof_impl(val.value, c)
+ return IndexValueType(val_typ)
+
+
+@type_callable(IndexValue)
+def type_index_value(context):
+ def typer(ind, mval):
+ if ind == types.np_intp or ind == types.uintp:
+ return IndexValueType(mval)
+ return typer
+
+
+@register_model(IndexValueType)
+class IndexValueModel(models.StructModel):
+ def __init__(self, dmm, fe_type):
+ members = [
+ ('index', types.np_intp),
+ ('value', fe_type.val_typ),
+ ]
+ models.StructModel.__init__(self, dmm, fe_type, members)
+
+
+make_attribute_wrapper(IndexValueType, 'index', 'index')
+make_attribute_wrapper(IndexValueType, 'value', 'value')
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/new_cmathdecl.py b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/new_cmathdecl.py
new file mode 100644
index 0000000000000000000000000000000000000000..33111f67301658ca36fde1f7743d8f5b83229eb9
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/new_cmathdecl.py
@@ -0,0 +1,50 @@
+import cmath
+
+from numba.core import types, utils
+from numba.core.typing.templates import (AbstractTemplate, ConcreteTemplate,
+ signature, Registry)
+
+registry = Registry()
+infer_global = registry.register_global
+
+# TODO: support non-complex arguments (floats and ints)
+
+# TODO: New Type System
+# These functions are part of the Python standard library
+# and (without checking) probably accept anything which
+# is "number"-like i.e. has a __float__, __int__, or
+# __index__
+# This needs fixing in the new type system
+
+
+@infer_global(cmath.acos)
+@infer_global(cmath.asin)
+@infer_global(cmath.asinh)
+@infer_global(cmath.atan)
+@infer_global(cmath.atanh)
+@infer_global(cmath.cos)
+@infer_global(cmath.exp)
+@infer_global(cmath.sin)
+@infer_global(cmath.sqrt)
+@infer_global(cmath.tan)
+class CMath_unary(ConcreteTemplate):
+ cases = []
+
+
+@infer_global(cmath.isinf)
+@infer_global(cmath.isnan)
+class CMath_predicate(ConcreteTemplate):
+ cases = []
+
+
+@infer_global(cmath.isfinite)
+class CMath_isfinite(CMath_predicate):
+ pass
+
+
+@infer_global(cmath.log)
+class Cmath_log(ConcreteTemplate):
+ # unary cmath.log()
+ cases = []
+ # binary cmath.log()
+ cases += []
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/new_mathdecl.py b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/new_mathdecl.py
new file mode 100644
index 0000000000000000000000000000000000000000..74ac47c95ce93d878f453207c781a3c20fd4bf62
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/new_mathdecl.py
@@ -0,0 +1,107 @@
+import math
+from numba.core import types, utils
+from numba.core.typing.templates import (AttributeTemplate, ConcreteTemplate,
+ signature, Registry)
+
+# TODO: New Type System
+# These functions are part of the Python standard library
+# and (without checking) probably accept anything which
+# is "number"-like i.e. has a __float__, __int__, or
+# __index__
+# This needs fixing in the new type system
+
+
+registry = Registry()
+infer_global = registry.register_global
+
+
+@infer_global(math.exp)
+@infer_global(math.expm1)
+@infer_global(math.fabs)
+@infer_global(math.sqrt)
+@infer_global(math.log)
+@infer_global(math.log1p)
+@infer_global(math.log10)
+@infer_global(math.log2)
+@infer_global(math.sin)
+@infer_global(math.cos)
+@infer_global(math.tan)
+@infer_global(math.sinh)
+@infer_global(math.cosh)
+@infer_global(math.tanh)
+@infer_global(math.asin)
+@infer_global(math.acos)
+@infer_global(math.atan)
+@infer_global(math.asinh)
+@infer_global(math.acosh)
+@infer_global(math.atanh)
+@infer_global(math.degrees)
+@infer_global(math.radians)
+@infer_global(math.erf)
+@infer_global(math.erfc)
+@infer_global(math.gamma)
+@infer_global(math.lgamma)
+class Math_unary(ConcreteTemplate):
+ cases = []
+
+
+@infer_global(math.atan2)
+class Math_atan2(ConcreteTemplate):
+ cases = []
+
+
+@infer_global(math.trunc)
+class Math_converter(ConcreteTemplate):
+ cases = []
+
+
+@infer_global(math.floor)
+@infer_global(math.ceil)
+class Math_floor_ceil(Math_converter):
+ pass
+
+
+@infer_global(math.copysign)
+class Math_copysign(ConcreteTemplate):
+ cases = []
+
+
+@infer_global(math.hypot)
+class Math_hypot(ConcreteTemplate):
+ cases = []
+
+
+@infer_global(math.nextafter)
+class Math_nextafter(ConcreteTemplate):
+ cases = []
+
+
+@infer_global(math.isinf)
+@infer_global(math.isnan)
+class Math_predicate(ConcreteTemplate):
+ cases = []
+
+
+@infer_global(math.isfinite)
+class Math_isfinite(Math_predicate):
+ pass
+
+
+@infer_global(math.pow)
+class Math_pow(ConcreteTemplate):
+ cases = []
+
+
+@infer_global(math.gcd)
+class Math_gcd(ConcreteTemplate):
+ cases = []
+
+
+@infer_global(math.frexp)
+class Math_frexp(ConcreteTemplate):
+ cases = []
+
+
+@infer_global(math.ldexp)
+class Math_ldexp(ConcreteTemplate):
+ cases = []
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/npdatetime.py b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/npdatetime.py
new file mode 100644
index 0000000000000000000000000000000000000000..c880f7f1dc06b24ff4293e27f06ebb84a3c08248
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/npdatetime.py
@@ -0,0 +1,294 @@
+"""
+Typing declarations for np.timedelta64.
+"""
+
+
+from itertools import product
+import operator
+
+from numba.core import types, errors
+from numba.core.typing.templates import (AttributeTemplate, ConcreteTemplate,
+ AbstractTemplate, infer_global, infer,
+ infer_getattr, signature)
+from numba.np import npdatetime_helpers
+from numba.np.numpy_support import numpy_version
+
+
+# timedelta64-only operations
+
+class TimedeltaUnaryOp(AbstractTemplate):
+
+ def generic(self, args, kws):
+ if len(args) == 2:
+ # Guard against binary + and -
+ return
+ op, = args
+ if not isinstance(op, types.NPTimedelta):
+ return
+ return signature(op, op)
+
+
+class TimedeltaBinOp(AbstractTemplate):
+
+ def generic(self, args, kws):
+ if len(args) == 1:
+ # Guard against unary + and -
+ return
+ left, right = args
+ if not all(isinstance(tp, types.NPTimedelta) for tp in args):
+ return
+ if npdatetime_helpers.can_cast_timedelta_units(left.unit, right.unit):
+ return signature(right, left, right)
+ elif npdatetime_helpers.can_cast_timedelta_units(right.unit, left.unit):
+ return signature(left, left, right)
+
+
+class TimedeltaCmpOp(AbstractTemplate):
+
+ def generic(self, args, kws):
+ # For equality comparisons, all units are inter-comparable
+ left, right = args
+ if not all(isinstance(tp, types.NPTimedelta) for tp in args):
+ return
+ return signature(types.boolean, left, right)
+
+
+class TimedeltaOrderedCmpOp(AbstractTemplate):
+
+ def generic(self, args, kws):
+ # For ordered comparisons, units must be compatible
+ left, right = args
+ if not all(isinstance(tp, types.NPTimedelta) for tp in args):
+ return
+ if (npdatetime_helpers.can_cast_timedelta_units(left.unit, right.unit) or
+ npdatetime_helpers.can_cast_timedelta_units(right.unit, left.unit)):
+ return signature(types.boolean, left, right)
+
+
+class TimedeltaMixOp(AbstractTemplate):
+
+ def generic(self, args, kws):
+ """
+ (timedelta64, {int, float}) -> timedelta64
+ ({int, float}, timedelta64) -> timedelta64
+ """
+ left, right = args
+ if isinstance(right, types.NPTimedelta):
+ td, other = right, left
+ sig_factory = lambda other: signature(td, other, td)
+ elif isinstance(left, types.NPTimedelta):
+ td, other = left, right
+ sig_factory = lambda other: signature(td, td, other)
+ else:
+ return
+ if not isinstance(other, (types.Float, types.Integer)):
+ return
+ # Force integer types to convert to signed because it matches
+ # timedelta64 semantics better.
+ if isinstance(other, types.Integer):
+ other = types.int64
+ return sig_factory(other)
+
+
+class TimedeltaDivOp(AbstractTemplate):
+
+ def generic(self, args, kws):
+ """
+ (timedelta64, {int, float}) -> timedelta64
+ (timedelta64, timedelta64) -> float
+ """
+ left, right = args
+ if not isinstance(left, types.NPTimedelta):
+ return
+ if isinstance(right, types.NPTimedelta):
+ if (npdatetime_helpers.can_cast_timedelta_units(left.unit, right.unit)
+ or npdatetime_helpers.can_cast_timedelta_units(right.unit, left.unit)):
+ return signature(types.float64, left, right)
+ elif isinstance(right, (types.Float)):
+ return signature(left, left, right)
+ elif isinstance(right, (types.Integer)):
+ # Force integer types to convert to signed because it matches
+ # timedelta64 semantics better.
+ return signature(left, left, types.int64)
+
+
+@infer_global(operator.pos)
+class TimedeltaUnaryPos(TimedeltaUnaryOp):
+ key = operator.pos
+
+@infer_global(operator.neg)
+class TimedeltaUnaryNeg(TimedeltaUnaryOp):
+ key = operator.neg
+
+@infer_global(operator.add)
+@infer_global(operator.iadd)
+class TimedeltaBinAdd(TimedeltaBinOp):
+ key = operator.add
+
+@infer_global(operator.sub)
+@infer_global(operator.isub)
+class TimedeltaBinSub(TimedeltaBinOp):
+ key = operator.sub
+
+@infer_global(operator.mul)
+@infer_global(operator.imul)
+class TimedeltaBinMult(TimedeltaMixOp):
+ key = operator.mul
+
+@infer_global(operator.truediv)
+@infer_global(operator.itruediv)
+class TimedeltaTrueDiv(TimedeltaDivOp):
+ key = operator.truediv
+
+@infer_global(operator.floordiv)
+@infer_global(operator.ifloordiv)
+class TimedeltaFloorDiv(TimedeltaDivOp):
+ key = operator.floordiv
+
+if numpy_version >= (1, 25):
+ @infer_global(operator.eq)
+ class TimedeltaCmpEq(TimedeltaOrderedCmpOp):
+ key = operator.eq
+
+ @infer_global(operator.ne)
+ class TimedeltaCmpNe(TimedeltaOrderedCmpOp):
+ key = operator.ne
+else:
+ @infer_global(operator.eq)
+ class TimedeltaCmpEq(TimedeltaCmpOp):
+ key = operator.eq
+
+ @infer_global(operator.ne)
+ class TimedeltaCmpNe(TimedeltaCmpOp):
+ key = operator.ne
+
+@infer_global(operator.lt)
+class TimedeltaCmpLt(TimedeltaOrderedCmpOp):
+ key = operator.lt
+
+@infer_global(operator.le)
+class TimedeltaCmpLE(TimedeltaOrderedCmpOp):
+ key = operator.le
+
+@infer_global(operator.gt)
+class TimedeltaCmpGt(TimedeltaOrderedCmpOp):
+ key = operator.gt
+
+@infer_global(operator.ge)
+class TimedeltaCmpGE(TimedeltaOrderedCmpOp):
+ key = operator.ge
+
+
+@infer_global(abs)
+class TimedeltaAbs(TimedeltaUnaryOp):
+ pass
+
+
+# datetime64 operations
+
+@infer_global(operator.add)
+@infer_global(operator.iadd)
+class DatetimePlusTimedelta(AbstractTemplate):
+ key = operator.add
+
+ def generic(self, args, kws):
+ if len(args) == 1:
+ # Guard against unary +
+ return
+ left, right = args
+ if isinstance(right, types.NPTimedelta):
+ dt = left
+ td = right
+ elif isinstance(left, types.NPTimedelta):
+ dt = right
+ td = left
+ else:
+ return
+ if isinstance(dt, types.NPDatetime):
+ unit = npdatetime_helpers.combine_datetime_timedelta_units(dt.unit,
+ td.unit)
+ if unit is not None:
+ return signature(types.NPDatetime(unit), left, right)
+
+@infer_global(operator.sub)
+@infer_global(operator.isub)
+class DatetimeMinusTimedelta(AbstractTemplate):
+ key = operator.sub
+
+ def generic(self, args, kws):
+ if len(args) == 1:
+ # Guard against unary -
+ return
+ dt, td = args
+ if isinstance(dt, types.NPDatetime) and isinstance(td,
+ types.NPTimedelta):
+ unit = npdatetime_helpers.combine_datetime_timedelta_units(dt.unit,
+ td.unit)
+ if unit is not None:
+ return signature(types.NPDatetime(unit), dt, td)
+
+@infer_global(operator.sub)
+class DatetimeMinusDatetime(AbstractTemplate):
+ key = operator.sub
+
+ def generic(self, args, kws):
+ if len(args) == 1:
+ # Guard against unary -
+ return
+ left, right = args
+ if isinstance(left, types.NPDatetime) and isinstance(right,
+ types.NPDatetime):
+ unit = npdatetime_helpers.get_best_unit(left.unit, right.unit)
+ return signature(types.NPTimedelta(unit), left, right)
+
+
+class DatetimeCmpOp(AbstractTemplate):
+
+ def generic(self, args, kws):
+ # For datetime64 comparisons, all units are inter-comparable
+ left, right = args
+ if not all(isinstance(tp, types.NPDatetime) for tp in args):
+ return
+ return signature(types.boolean, left, right)
+
+
+@infer_global(operator.eq)
+class DatetimeCmpEq(DatetimeCmpOp):
+ key = operator.eq
+
+@infer_global(operator.ne)
+class DatetimeCmpNe(DatetimeCmpOp):
+ key = operator.ne
+
+@infer_global(operator.lt)
+class DatetimeCmpLt(DatetimeCmpOp):
+ key = operator.lt
+
+@infer_global(operator.le)
+class DatetimeCmpLE(DatetimeCmpOp):
+ key = operator.le
+
+@infer_global(operator.gt)
+class DatetimeCmpGt(DatetimeCmpOp):
+ key = operator.gt
+
+@infer_global(operator.ge)
+class DatetimeCmpGE(DatetimeCmpOp):
+ key = operator.ge
+
+
+@infer_global(npdatetime_helpers.datetime_minimum)
+@infer_global(npdatetime_helpers.datetime_maximum)
+class DatetimeMinMax(AbstractTemplate):
+ def generic(self, args, kws):
+ assert not kws
+ assert len(args) == 2
+ error_msg = "DatetimeMinMax requires both arguments to be NPDatetime type or both arguments to be NPTimedelta types"
+ assert isinstance(args[0], (types.NPDatetime, types.NPTimedelta)), error_msg
+ if isinstance(args[0], types.NPDatetime):
+ if not isinstance(args[1], types.NPDatetime):
+ raise errors.TypingError(error_msg)
+ else:
+ if not isinstance(args[1], types.NPTimedelta):
+ raise errors.TypingError(error_msg)
+ return signature(args[0], *args)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/npydecl.py b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/npydecl.py
new file mode 100644
index 0000000000000000000000000000000000000000..85534dc81ec565dc0381baf4b12eae99871aa15a
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/npydecl.py
@@ -0,0 +1,690 @@
+import warnings
+
+import numpy as np
+import operator
+
+from numba.core import types, utils, config
+from numba.core.typing.templates import (AttributeTemplate, AbstractTemplate,
+ CallableTemplate, Registry, signature)
+
+from numba.np.numpy_support import (ufunc_find_matching_loop,
+ supported_ufunc_loop, as_dtype,
+ from_dtype, as_dtype, resolve_output_type,
+ carray, farray, _ufunc_loop_sig)
+from numba.core.errors import (TypingError, NumbaPerformanceWarning,
+ NumbaTypeError, NumbaAssertionError)
+from numba import pndindex
+
+registry = Registry()
+infer = registry.register
+infer_global = registry.register_global
+infer_getattr = registry.register_attr
+
+
+class Numpy_rules_ufunc(AbstractTemplate):
+ @classmethod
+ def _handle_inputs(cls, ufunc, args, kws):
+ """
+ Process argument types to a given *ufunc*.
+ Returns a (base types, explicit outputs, ndims, layout) tuple where:
+ - `base types` is a tuple of scalar types for each input
+ - `explicit outputs` is a tuple of explicit output types (arrays)
+ - `ndims` is the number of dimensions of the loop and also of
+ any outputs, explicit or implicit
+ - `layout` is the layout for any implicit output to be allocated
+ """
+ nin = ufunc.nin
+ nout = ufunc.nout
+ nargs = ufunc.nargs
+
+ # preconditions
+ assert nargs == nin + nout
+
+ if len(args) < nin:
+ msg = "ufunc '{0}': not enough arguments ({1} found, {2} required)"
+ raise TypingError(msg=msg.format(ufunc.__name__, len(args), nin))
+
+ if len(args) > nargs:
+ msg = "ufunc '{0}': too many arguments ({1} found, {2} maximum)"
+ raise TypingError(msg=msg.format(ufunc.__name__, len(args), nargs))
+
+ args = [a.as_array if isinstance(a, types.ArrayCompatible) else a
+ for a in args]
+ arg_ndims = [a.ndim if isinstance(a, types.ArrayCompatible) else 0
+ for a in args]
+ ndims = max(arg_ndims)
+
+ # explicit outputs must be arrays (no explicit scalar return values supported)
+ explicit_outputs = args[nin:]
+
+ if not all(isinstance(output, types.ArrayCompatible)
+ for output in explicit_outputs):
+ msg = "ufunc '{0}' called with an explicit output that is not an array"
+ raise TypingError(msg=msg.format(ufunc.__name__))
+
+ if not all(output.mutable for output in explicit_outputs):
+ msg = "ufunc '{0}' called with an explicit output that is read-only"
+ raise TypingError(msg=msg.format(ufunc.__name__))
+
+ # find the kernel to use, based only in the input types (as does NumPy)
+ base_types = [x.dtype if isinstance(x, types.ArrayCompatible) else x
+ for x in args]
+
+ # Figure out the output array layout, if needed.
+ layout = None
+ if ndims > 0 and (len(explicit_outputs) < ufunc.nout):
+ layout = 'C'
+ layouts = [x.layout if isinstance(x, types.ArrayCompatible) else ''
+ for x in args]
+
+ # Prefer C contig if any array is C contig.
+ # Next, prefer F contig.
+ # Defaults to C contig if not layouts are C/F.
+ if 'C' not in layouts and 'F' in layouts:
+ layout = 'F'
+
+ return base_types, explicit_outputs, ndims, layout
+
+ @property
+ def ufunc(self):
+ return self.key
+
+ def generic(self, args, kws):
+ # First, strip optional types, ufunc loops are typed on concrete types
+ args = [x.type if isinstance(x, types.Optional) else x for x in args]
+
+ ufunc = self.ufunc
+ base_types, explicit_outputs, ndims, layout = self._handle_inputs(
+ ufunc, args, kws)
+ ufunc_loop = ufunc_find_matching_loop(ufunc, base_types)
+ if ufunc_loop is None:
+ raise TypingError("can't resolve ufunc {0} for types {1}".format(ufunc.__name__, args))
+
+ # check if all the types involved in the ufunc loop are supported in this mode
+ if not supported_ufunc_loop(ufunc, ufunc_loop):
+ msg = "ufunc '{0}' using the loop '{1}' not supported in this mode"
+ raise TypingError(msg=msg.format(ufunc.__name__, ufunc_loop.ufunc_sig))
+
+ # if there is any explicit output type, check that it is valid
+ explicit_outputs_np = [as_dtype(tp.dtype) for tp in explicit_outputs]
+
+ # Numpy will happily use unsafe conversions (although it will actually warn)
+ if not all (np.can_cast(fromty, toty, 'unsafe') for (fromty, toty) in
+ zip(ufunc_loop.numpy_outputs, explicit_outputs_np)):
+ msg = "ufunc '{0}' can't cast result to explicit result type"
+ raise TypingError(msg=msg.format(ufunc.__name__))
+
+ # A valid loop was found that is compatible. The result of type inference should
+ # be based on the explicit output types, and when not available with the type given
+ # by the selected NumPy loop
+ out = list(explicit_outputs)
+ implicit_output_count = ufunc.nout - len(explicit_outputs)
+ if implicit_output_count > 0:
+ # XXX this is sometimes wrong for datetime64 and timedelta64,
+ # as ufunc_find_matching_loop() doesn't do any type inference
+ ret_tys = ufunc_loop.outputs[-implicit_output_count:]
+ if ndims > 0:
+ assert layout is not None
+ # If either of the types involved in the ufunc operation have a
+ # __array_ufunc__ method then invoke the first such one to
+ # determine the output type of the ufunc.
+ array_ufunc_type = None
+ for a in args:
+ if hasattr(a, "__array_ufunc__"):
+ array_ufunc_type = a
+ break
+ output_type = types.Array
+ if array_ufunc_type is not None:
+ output_type = array_ufunc_type.__array_ufunc__(ufunc, "__call__", *args, **kws)
+ if output_type is NotImplemented:
+ msg = (f"unsupported use of ufunc {ufunc} on "
+ f"{array_ufunc_type}")
+ # raise TypeError here because
+ # NumpyRulesArrayOperator.generic is capturing
+ # TypingError
+ raise NumbaTypeError(msg)
+ elif not issubclass(output_type, types.Array):
+ msg = (f"ufunc {ufunc} on {array_ufunc_type}"
+ f"cannot return non-array {output_type}")
+ # raise TypeError here because
+ # NumpyRulesArrayOperator.generic is capturing
+ # TypingError
+ raise NumbaTypeError(msg)
+
+ ret_tys = [output_type(dtype=ret_ty, ndim=ndims, layout=layout)
+ for ret_ty in ret_tys]
+ ret_tys = [resolve_output_type(self.context, args, ret_ty)
+ for ret_ty in ret_tys]
+ out.extend(ret_tys)
+
+ return _ufunc_loop_sig(out, args)
+
+
+class NumpyRulesArrayOperator(Numpy_rules_ufunc):
+ _op_map = {
+ operator.add: "add",
+ operator.sub: "subtract",
+ operator.mul: "multiply",
+ operator.truediv: "true_divide",
+ operator.floordiv: "floor_divide",
+ operator.mod: "remainder",
+ operator.pow: "power",
+ operator.lshift: "left_shift",
+ operator.rshift: "right_shift",
+ operator.and_: "bitwise_and",
+ operator.or_: "bitwise_or",
+ operator.xor: "bitwise_xor",
+ operator.eq: "equal",
+ operator.gt: "greater",
+ operator.ge: "greater_equal",
+ operator.lt: "less",
+ operator.le: "less_equal",
+ operator.ne: "not_equal",
+ }
+
+ @property
+ def ufunc(self):
+ return getattr(np, self._op_map[self.key])
+
+ @classmethod
+ def install_operations(cls):
+ for op, ufunc_name in cls._op_map.items():
+ infer_global(op)(
+ type("NumpyRulesArrayOperator_" + ufunc_name, (cls,), dict(key=op))
+ )
+
+ def generic(self, args, kws):
+ '''Overloads and calls base class generic() method, returning
+ None if a TypingError occurred.
+
+ Returning None for operators is important since operators are
+ heavily overloaded, and by suppressing type errors, we allow
+ type inference to check other possibilities before giving up
+ (particularly user-defined operators).
+ '''
+ try:
+ sig = super(NumpyRulesArrayOperator, self).generic(args, kws)
+ except TypingError:
+ return None
+ if sig is None:
+ return None
+ args = sig.args
+ # Only accept at least one array argument, otherwise the operator
+ # doesn't involve Numpy's ufunc machinery.
+ if not any(isinstance(arg, types.ArrayCompatible)
+ for arg in args):
+ return None
+ return sig
+
+
+_binop_map = NumpyRulesArrayOperator._op_map
+
+class NumpyRulesInplaceArrayOperator(NumpyRulesArrayOperator):
+ _op_map = {
+ operator.iadd: "add",
+ operator.isub: "subtract",
+ operator.imul: "multiply",
+ operator.itruediv: "true_divide",
+ operator.ifloordiv: "floor_divide",
+ operator.imod: "remainder",
+ operator.ipow: "power",
+ operator.ilshift: "left_shift",
+ operator.irshift: "right_shift",
+ operator.iand: "bitwise_and",
+ operator.ior: "bitwise_or",
+ operator.ixor: "bitwise_xor",
+ }
+
+ def generic(self, args, kws):
+ # Type the inplace operator as if an explicit output was passed,
+ # to handle type resolution correctly.
+ # (for example int8[:] += int16[:] should use an int8[:] output,
+ # not int16[:])
+ lhs, rhs = args
+ if not isinstance(lhs, types.ArrayCompatible):
+ return
+ args = args + (lhs,)
+ sig = super(NumpyRulesInplaceArrayOperator, self).generic(args, kws)
+ # Strip off the fake explicit output
+ assert len(sig.args) == 3
+ real_sig = signature(sig.return_type, *sig.args[:2])
+ return real_sig
+
+
+class NumpyRulesUnaryArrayOperator(NumpyRulesArrayOperator):
+ _op_map = {
+ operator.pos: "positive",
+ operator.neg: "negative",
+ operator.invert: "invert",
+ }
+
+ def generic(self, args, kws):
+ assert not kws
+ if len(args) == 1 and isinstance(args[0], types.ArrayCompatible):
+ return super(NumpyRulesUnaryArrayOperator, self).generic(args, kws)
+
+
+# list of unary ufuncs to register
+
+math_operations = [ "add", "subtract", "multiply",
+ "logaddexp", "logaddexp2", "true_divide",
+ "floor_divide", "negative", "positive", "power",
+ "float_power", "remainder", "fmod", "absolute",
+ "rint", "sign", "conjugate", "exp", "exp2",
+ "log", "log2", "log10", "expm1", "log1p",
+ "sqrt", "square", "cbrt", "reciprocal",
+ "divide", "mod", "divmod", "abs", "fabs" , "gcd", "lcm"]
+
+trigonometric_functions = [ "sin", "cos", "tan", "arcsin",
+ "arccos", "arctan", "arctan2",
+ "hypot", "sinh", "cosh", "tanh",
+ "arcsinh", "arccosh", "arctanh",
+ "deg2rad", "rad2deg", "degrees",
+ "radians" ]
+
+bit_twiddling_functions = ["bitwise_and", "bitwise_or",
+ "bitwise_xor", "invert",
+ "left_shift", "right_shift",
+ "bitwise_not" ]
+
+comparison_functions = [ "greater", "greater_equal", "less",
+ "less_equal", "not_equal", "equal",
+ "logical_and", "logical_or",
+ "logical_xor", "logical_not",
+ "maximum", "minimum", "fmax", "fmin" ]
+
+floating_functions = [ "isfinite", "isinf", "isnan", "signbit",
+ "copysign", "nextafter", "modf", "ldexp",
+ "frexp", "floor", "ceil", "trunc",
+ "spacing" ]
+
+logic_functions = [ "isnat" ]
+
+
+# This is a set of the ufuncs that are not yet supported by Lowering. In order
+# to trigger no-python mode we must not register them until their Lowering is
+# implemented.
+#
+# It also works as a nice TODO list for ufunc support :)
+_unsupported = set([ 'frexp',
+ 'modf',
+ ])
+
+
+def register_numpy_ufunc(name, register_global=infer_global):
+ func = getattr(np, name)
+ class typing_class(Numpy_rules_ufunc):
+ key = func
+
+ typing_class.__name__ = "resolve_{0}".format(name)
+
+ # A list of ufuncs that are in fact aliases of other ufuncs. They need to
+ # insert the resolve method, but not register the ufunc itself
+ aliases = ("abs", "bitwise_not", "divide", "abs")
+
+ if name not in aliases:
+ register_global(func, types.Function(typing_class))
+
+all_ufuncs = sum([math_operations, trigonometric_functions,
+ bit_twiddling_functions, comparison_functions,
+ floating_functions, logic_functions], [])
+
+supported_ufuncs = [x for x in all_ufuncs if x not in _unsupported]
+
+for func in supported_ufuncs:
+ register_numpy_ufunc(func)
+
+all_ufuncs = [getattr(np, name) for name in all_ufuncs]
+supported_ufuncs = [getattr(np, name) for name in supported_ufuncs]
+
+NumpyRulesUnaryArrayOperator.install_operations()
+NumpyRulesArrayOperator.install_operations()
+NumpyRulesInplaceArrayOperator.install_operations()
+
+supported_array_operators = set(
+ NumpyRulesUnaryArrayOperator._op_map.keys()
+).union(
+ NumpyRulesArrayOperator._op_map.keys()
+).union(
+ NumpyRulesInplaceArrayOperator._op_map.keys()
+)
+
+del _unsupported
+
+
+# -----------------------------------------------------------------------------
+# Install global helpers for array methods.
+
+class Numpy_method_redirection(AbstractTemplate):
+ """
+ A template redirecting a Numpy global function (e.g. np.sum) to an
+ array method of the same name (e.g. ndarray.sum).
+ """
+
+ # Arguments like *axis* can specialize on literals but also support
+ # non-literals
+ prefer_literal = True
+
+ def generic(self, args, kws):
+ pysig = None
+ if kws:
+ if self.method_name == 'sum':
+ if 'axis' in kws and 'dtype' not in kws:
+ def sum_stub(arr, axis):
+ pass
+ pysig = utils.pysignature(sum_stub)
+ elif 'dtype' in kws and 'axis' not in kws:
+ def sum_stub(arr, dtype):
+ pass
+ pysig = utils.pysignature(sum_stub)
+ elif 'dtype' in kws and 'axis' in kws:
+ def sum_stub(arr, axis, dtype):
+ pass
+ pysig = utils.pysignature(sum_stub)
+ elif self.method_name == 'argsort':
+ def argsort_stub(arr, kind='quicksort'):
+ pass
+ pysig = utils.pysignature(argsort_stub)
+ else:
+ fmt = "numba doesn't support kwarg for {}"
+ raise TypingError(fmt.format(self.method_name))
+
+ arr = args[0]
+ # This will return a BoundFunction
+ meth_ty = self.context.resolve_getattr(arr, self.method_name)
+ # Resolve arguments on the bound function
+ meth_sig = self.context.resolve_function_type(meth_ty, args[1:], kws)
+ if meth_sig is not None:
+ return meth_sig.as_function().replace(pysig=pysig)
+
+
+# Function to glue attributes onto the numpy-esque object
+def _numpy_redirect(fname):
+ numpy_function = getattr(np, fname)
+ cls = type("Numpy_redirect_{0}".format(fname), (Numpy_method_redirection,),
+ dict(key=numpy_function, method_name=fname))
+ infer_global(numpy_function, types.Function(cls))
+
+
+for func in ['sum', 'argsort', 'nonzero', 'ravel']:
+ _numpy_redirect(func)
+
+
+# -----------------------------------------------------------------------------
+# Numpy scalar constructors
+
+if config.USE_LEGACY_TYPE_SYSTEM:
+ # Register np.int8, etc. as converters to the equivalent Numba types
+ np_types = set(getattr(np, str(nb_type)) for nb_type in types.number_domain)
+ np_types.add(np.bool_)
+ # Those may or may not be aliases (depending on the Numpy build / version)
+ np_types.add(np.intc)
+ np_types.add(np.intp)
+ np_types.add(np.uintc)
+ np_types.add(np.uintp)
+
+
+ def register_number_classes(register_global):
+ for np_type in np_types:
+ nb_type = getattr(types, np_type.__name__)
+
+ register_global(np_type, types.NumberClass(nb_type))
+else:
+ # Register np.int8, etc. as converters to the equivalent Numba types
+ np_types = set(getattr(np, str(nb_type).split('np_')[-1]) for nb_type in types.np_number_domain)
+ np_types.add(np.bool_)
+ # Those may or may not be aliases (depending on the Numpy build / version)
+ np_types.add(np.intc)
+ np_types.add(np.intp)
+ np_types.add(np.uintc)
+ np_types.add(np.uintp)
+
+
+ def register_number_classes(register_global):
+ for np_type in np_types:
+ nb_type = getattr(types, f'np_{np_type.__name__}')
+
+ register_global(np_type, types.NumberClass(nb_type))
+
+
+register_number_classes(infer_global)
+
+
+# -----------------------------------------------------------------------------
+# Numpy array constructors
+
+def parse_shape(shape):
+ """
+ Given a shape, return the number of dimensions.
+ """
+ ndim = None
+ if isinstance(shape, types.Integer):
+ ndim = 1
+ elif isinstance(shape, (types.Tuple, types.UniTuple)):
+ int_tys = (types.Integer, types.IntEnumMember)
+ if all(isinstance(s, int_tys) for s in shape):
+ ndim = len(shape)
+ return ndim
+
+def parse_dtype(dtype):
+ """
+ Return the dtype of a type, if it is either a DtypeSpec (used for most
+ dtypes) or a TypeRef (used for record types).
+ """
+ if isinstance(dtype, types.DTypeSpec):
+ return dtype.dtype
+ elif isinstance(dtype, types.TypeRef):
+ return dtype.instance_type
+ elif isinstance(dtype, types.StringLiteral):
+ dtstr = dtype.literal_value
+ try:
+ dt = np.dtype(dtstr)
+ except TypeError:
+ msg = f"Invalid NumPy dtype specified: '{dtstr}'"
+ raise TypingError(msg)
+ return from_dtype(dt)
+
+def _parse_nested_sequence(context, typ):
+ """
+ Parse a (possibly 0d) nested sequence type.
+ A (ndim, dtype) tuple is returned. Note the sequence may still be
+ heterogeneous, as long as it converts to the given dtype.
+ """
+ if isinstance(typ, (types.Buffer,)):
+ raise TypingError("%s not allowed in a homogeneous sequence" % typ)
+ elif isinstance(typ, (types.Sequence,)):
+ n, dtype = _parse_nested_sequence(context, typ.dtype)
+ return n + 1, dtype
+ elif isinstance(typ, (types.BaseTuple,)):
+ if typ.count == 0:
+ # Mimic Numpy's behaviour
+ return 1, types.float64
+ n, dtype = _parse_nested_sequence(context, typ[0])
+ dtypes = [dtype]
+ for i in range(1, typ.count):
+ _n, dtype = _parse_nested_sequence(context, typ[i])
+ if _n != n:
+ raise TypingError("type %s does not have a regular shape"
+ % (typ,))
+ dtypes.append(dtype)
+ dtype = context.unify_types(*dtypes)
+ if dtype is None:
+ raise TypingError("cannot convert %s to a homogeneous type" % typ)
+ return n + 1, dtype
+ else:
+ # Scalar type => check it's valid as a Numpy array dtype
+ as_dtype(typ)
+ return 0, typ
+
+
+def _infer_dtype_from_inputs(inputs):
+ return dtype
+
+
+def _homogeneous_dims(context, func_name, arrays):
+ ndim = arrays[0].ndim
+ for a in arrays:
+ if a.ndim != ndim:
+ msg = (f"{func_name}(): all the input arrays must have same number "
+ "of dimensions")
+ raise NumbaTypeError(msg)
+ return ndim
+
+def _sequence_of_arrays(context, func_name, arrays,
+ dim_chooser=_homogeneous_dims):
+ if (not isinstance(arrays, types.BaseTuple)
+ or not len(arrays)
+ or not all(isinstance(a, types.Array) for a in arrays)):
+ raise TypingError("%s(): expecting a non-empty tuple of arrays, "
+ "got %s" % (func_name, arrays))
+
+ ndim = dim_chooser(context, func_name, arrays)
+
+ dtype = context.unify_types(*(a.dtype for a in arrays))
+ if dtype is None:
+ raise TypingError("%s(): input arrays must have "
+ "compatible dtypes" % func_name)
+
+ return dtype, ndim
+
+def _choose_concatenation_layout(arrays):
+ # Only create a F array if all input arrays have F layout.
+ # This is a simplified version of Numpy's behaviour,
+ # while Numpy's actually processes the input strides to
+ # decide on optimal output strides
+ # (see PyArray_CreateMultiSortedStridePerm()).
+ return 'F' if all(a.layout == 'F' for a in arrays) else 'C'
+
+
+# -----------------------------------------------------------------------------
+# Linear algebra
+
+
+class MatMulTyperMixin(object):
+
+ def matmul_typer(self, a, b, out=None):
+ """
+ Typer function for Numpy matrix multiplication.
+ """
+ if not isinstance(a, types.Array) or not isinstance(b, types.Array):
+ return
+ if not all(x.ndim in (1, 2) for x in (a, b)):
+ raise TypingError("%s only supported on 1-D and 2-D arrays"
+ % (self.func_name, ))
+ # Output dimensionality
+ ndims = set([a.ndim, b.ndim])
+ if ndims == set([2]):
+ # M * M
+ out_ndim = 2
+ elif ndims == set([1, 2]):
+ # M* V and V * M
+ out_ndim = 1
+ elif ndims == set([1]):
+ # V * V
+ out_ndim = 0
+
+ if out is not None:
+ if out_ndim == 0:
+ raise TypingError(
+ "explicit output unsupported for vector * vector")
+ elif out.ndim != out_ndim:
+ raise TypingError(
+ "explicit output has incorrect dimensionality")
+ if not isinstance(out, types.Array) or out.layout != 'C':
+ raise TypingError("output must be a C-contiguous array")
+ all_args = (a, b, out)
+ else:
+ all_args = (a, b)
+
+ if not (config.DISABLE_PERFORMANCE_WARNINGS or
+ all(x.layout in 'CF' for x in (a, b))):
+ msg = ("%s is faster on contiguous arrays, called on %s" %
+ (self.func_name, (a, b)))
+ warnings.warn(NumbaPerformanceWarning(msg))
+ if not all(x.dtype == a.dtype for x in all_args):
+ raise TypingError("%s arguments must all have "
+ "the same dtype" % (self.func_name,))
+ if not isinstance(a.dtype, (types.Float, types.Complex)):
+ raise TypingError("%s only supported on "
+ "float and complex arrays"
+ % (self.func_name,))
+ if out:
+ return out
+ elif out_ndim > 0:
+ return types.Array(a.dtype, out_ndim, 'C')
+ else:
+ return a.dtype
+
+
+def _check_linalg_matrix(a, func_name):
+ if not isinstance(a, types.Array):
+ return
+ if not a.ndim == 2:
+ raise TypingError("np.linalg.%s() only supported on 2-D arrays"
+ % func_name)
+ if not isinstance(a.dtype, (types.Float, types.Complex)):
+ raise TypingError("np.linalg.%s() only supported on "
+ "float and complex arrays" % func_name)
+
+# -----------------------------------------------------------------------------
+# Miscellaneous functions
+
+@infer_global(np.ndenumerate)
+class NdEnumerate(AbstractTemplate):
+
+ def generic(self, args, kws):
+ assert not kws
+ arr, = args
+
+ if isinstance(arr, types.Array):
+ enumerate_type = types.NumpyNdEnumerateType(arr)
+ return signature(enumerate_type, *args)
+
+
+@infer_global(np.nditer)
+class NdIter(AbstractTemplate):
+
+ def generic(self, args, kws):
+ assert not kws
+ if len(args) != 1:
+ return
+ arrays, = args
+
+ if isinstance(arrays, types.BaseTuple):
+ if not arrays:
+ return
+ arrays = list(arrays)
+ else:
+ arrays = [arrays]
+ nditerty = types.NumpyNdIterType(arrays)
+ return signature(nditerty, *args)
+
+
+@infer_global(pndindex)
+@infer_global(np.ndindex)
+class NdIndex(AbstractTemplate):
+
+ def generic(self, args, kws):
+ assert not kws
+
+ # Either ndindex(shape) or ndindex(*shape)
+ if len(args) == 1 and isinstance(args[0], types.BaseTuple):
+ tup = args[0]
+ if tup.count > 0 and not isinstance(tup, types.UniTuple):
+ # Heterogeneous tuple
+ return
+ shape = list(tup)
+ else:
+ shape = args
+
+ if all(isinstance(x, types.Integer) for x in shape):
+ iterator_type = types.NumpyNdIndexType(len(shape))
+ return signature(iterator_type, *args)
+
+
+@infer_global(operator.eq)
+class DtypeEq(AbstractTemplate):
+ def generic(self, args, kws):
+ [lhs, rhs] = args
+ if isinstance(lhs, types.DType) and isinstance(rhs, types.DType):
+ return signature(types.boolean, lhs, rhs)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/old_builtins.py b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/old_builtins.py
new file mode 100644
index 0000000000000000000000000000000000000000..0f727a4bd3810c02133fc420f8dc9a1d98a9a7e1
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/old_builtins.py
@@ -0,0 +1,1177 @@
+import itertools
+
+import numpy as np
+import operator
+
+from numba.core import types, errors
+from numba import prange
+from numba.parfors.parfor import internal_prange
+
+from numba.core.typing.templates import (AttributeTemplate, ConcreteTemplate,
+ AbstractTemplate, infer_global, infer,
+ infer_getattr, signature,
+ bound_function, make_callable_template)
+
+
+from numba.core.extending import (
+ typeof_impl, type_callable, models, register_model, make_attribute_wrapper,
+ )
+
+
+@infer_global(print)
+class Print(AbstractTemplate):
+ def generic(self, args, kws):
+ for a in args:
+ sig = self.context.resolve_function_type("print_item", (a,), {})
+ if sig is None:
+ raise errors.TypingError("Type %s is not printable." % a)
+ assert sig.return_type is types.none
+ return signature(types.none, *args)
+
+@infer
+class PrintItem(AbstractTemplate):
+ key = "print_item"
+
+ def generic(self, args, kws):
+ arg, = args
+ return signature(types.none, *args)
+
+
+@infer_global(abs)
+class Abs(ConcreteTemplate):
+ int_cases = [signature(ty, ty) for ty in sorted(types.signed_domain)]
+ uint_cases = [signature(ty, ty) for ty in sorted(types.unsigned_domain)]
+ real_cases = [signature(ty, ty) for ty in sorted(types.real_domain)]
+ complex_cases = [signature(ty.underlying_float, ty)
+ for ty in sorted(types.complex_domain)]
+ cases = int_cases + uint_cases + real_cases + complex_cases
+
+
+@infer_global(slice)
+class Slice(ConcreteTemplate):
+ cases = [
+ signature(types.slice2_type, types.intp),
+ signature(types.slice2_type, types.none),
+ signature(types.slice2_type, types.none, types.none),
+ signature(types.slice2_type, types.none, types.intp),
+ signature(types.slice2_type, types.intp, types.none),
+ signature(types.slice2_type, types.intp, types.intp),
+ signature(types.slice3_type, types.intp, types.intp, types.intp),
+ signature(types.slice3_type, types.none, types.intp, types.intp),
+ signature(types.slice3_type, types.intp, types.none, types.intp),
+ signature(types.slice3_type, types.intp, types.intp, types.none),
+ signature(types.slice3_type, types.intp, types.none, types.none),
+ signature(types.slice3_type, types.none, types.intp, types.none),
+ signature(types.slice3_type, types.none, types.none, types.intp),
+ signature(types.slice3_type, types.none, types.none, types.none),
+ ]
+
+
+@infer_global(range, typing_key=range)
+@infer_global(prange, typing_key=prange)
+@infer_global(internal_prange, typing_key=internal_prange)
+class Range(ConcreteTemplate):
+ cases = [
+ signature(types.range_state32_type, types.int32),
+ signature(types.range_state32_type, types.int32, types.int32),
+ signature(types.range_state32_type, types.int32, types.int32,
+ types.int32),
+ signature(types.range_state64_type, types.int64),
+ signature(types.range_state64_type, types.int64, types.int64),
+ signature(types.range_state64_type, types.int64, types.int64,
+ types.int64),
+ signature(types.unsigned_range_state64_type, types.uint64),
+ signature(types.unsigned_range_state64_type, types.uint64, types.uint64),
+ signature(types.unsigned_range_state64_type, types.uint64, types.uint64,
+ types.uint64),
+ ]
+
+
+@infer
+class GetIter(AbstractTemplate):
+ key = "getiter"
+
+ def generic(self, args, kws):
+ assert not kws
+ [obj] = args
+ if isinstance(obj, types.IterableType):
+ return signature(obj.iterator_type, obj)
+
+
+@infer
+class IterNext(AbstractTemplate):
+ key = "iternext"
+
+ def generic(self, args, kws):
+ assert not kws
+ [it] = args
+ if isinstance(it, types.IteratorType):
+ return signature(types.Pair(it.yield_type, types.boolean), it)
+
+
+@infer
+class PairFirst(AbstractTemplate):
+ """
+ Given a heterogeneous pair, return the first element.
+ """
+ key = "pair_first"
+
+ def generic(self, args, kws):
+ assert not kws
+ [pair] = args
+ if isinstance(pair, types.Pair):
+ return signature(pair.first_type, pair)
+
+
+@infer
+class PairSecond(AbstractTemplate):
+ """
+ Given a heterogeneous pair, return the second element.
+ """
+ key = "pair_second"
+
+ def generic(self, args, kws):
+ assert not kws
+ [pair] = args
+ if isinstance(pair, types.Pair):
+ return signature(pair.second_type, pair)
+
+
+def choose_result_bitwidth(*inputs):
+ return max(types.intp.bitwidth, *(tp.bitwidth for tp in inputs))
+
+def choose_result_int(*inputs):
+ """
+ Choose the integer result type for an operation on integer inputs,
+ according to the integer typing NBEP.
+ """
+ bitwidth = choose_result_bitwidth(*inputs)
+ signed = any(tp.signed for tp in inputs)
+ return types.Integer.from_bitwidth(bitwidth, signed)
+
+
+# The "machine" integer types to take into consideration for operator typing
+# (according to the integer typing NBEP)
+machine_ints = (
+ sorted(set((types.intp, types.int64))) +
+ sorted(set((types.uintp, types.uint64)))
+ )
+
+# Explicit integer rules for binary operators; smaller ints will be
+# automatically upcast.
+integer_binop_cases = tuple(
+ signature(choose_result_int(op1, op2), op1, op2)
+ for op1, op2 in itertools.product(machine_ints, machine_ints)
+ )
+
+
+class BinOp(ConcreteTemplate):
+ cases = list(integer_binop_cases)
+ cases += [signature(op, op, op) for op in sorted(types.real_domain)]
+ cases += [signature(op, op, op) for op in sorted(types.complex_domain)]
+
+
+@infer_global(operator.add)
+class BinOpAdd(BinOp):
+ pass
+
+
+@infer_global(operator.iadd)
+class BinOpAdd(BinOp):
+ pass
+
+
+@infer_global(operator.sub)
+class BinOpSub(BinOp):
+ pass
+
+
+@infer_global(operator.isub)
+class BinOpSub(BinOp):
+ pass
+
+
+@infer_global(operator.mul)
+class BinOpMul(BinOp):
+ pass
+
+
+@infer_global(operator.imul)
+class BinOpMul(BinOp):
+ pass
+
+
+@infer_global(operator.mod)
+class BinOpMod(ConcreteTemplate):
+ cases = list(integer_binop_cases)
+ cases += [signature(op, op, op) for op in sorted(types.real_domain)]
+
+
+@infer_global(operator.imod)
+class BinOpMod(ConcreteTemplate):
+ cases = list(integer_binop_cases)
+ cases += [signature(op, op, op) for op in sorted(types.real_domain)]
+
+
+@infer_global(operator.truediv)
+class BinOpTrueDiv(ConcreteTemplate):
+ cases = [signature(types.float64, op1, op2)
+ for op1, op2 in itertools.product(machine_ints, machine_ints)]
+ cases += [signature(op, op, op) for op in sorted(types.real_domain)]
+ cases += [signature(op, op, op) for op in sorted(types.complex_domain)]
+
+
+@infer_global(operator.itruediv)
+class BinOpTrueDiv(ConcreteTemplate):
+ cases = [signature(types.float64, op1, op2)
+ for op1, op2 in itertools.product(machine_ints, machine_ints)]
+ cases += [signature(op, op, op) for op in sorted(types.real_domain)]
+ cases += [signature(op, op, op) for op in sorted(types.complex_domain)]
+
+
+@infer_global(operator.floordiv)
+class BinOpFloorDiv(ConcreteTemplate):
+ cases = list(integer_binop_cases)
+ cases += [signature(op, op, op) for op in sorted(types.real_domain)]
+
+
+@infer_global(operator.ifloordiv)
+class BinOpFloorDiv(ConcreteTemplate):
+ cases = list(integer_binop_cases)
+ cases += [signature(op, op, op) for op in sorted(types.real_domain)]
+
+
+@infer_global(divmod)
+class DivMod(ConcreteTemplate):
+ _tys = machine_ints + sorted(types.real_domain)
+ cases = [signature(types.UniTuple(ty, 2), ty, ty) for ty in _tys]
+
+
+@infer_global(operator.pow)
+class BinOpPower(ConcreteTemplate):
+ cases = list(integer_binop_cases)
+ # Ensure that float32 ** int doesn't go through DP computations
+ cases += [signature(types.float32, types.float32, op)
+ for op in (types.int32, types.int64, types.uint64)]
+ cases += [signature(types.float64, types.float64, op)
+ for op in (types.int32, types.int64, types.uint64)]
+ cases += [signature(op, op, op)
+ for op in sorted(types.real_domain)]
+ cases += [signature(op, op, op)
+ for op in sorted(types.complex_domain)]
+
+
+@infer_global(operator.ipow)
+class BinOpPower(ConcreteTemplate):
+ cases = list(integer_binop_cases)
+ # Ensure that float32 ** int doesn't go through DP computations
+ cases += [signature(types.float32, types.float32, op)
+ for op in (types.int32, types.int64, types.uint64)]
+ cases += [signature(types.float64, types.float64, op)
+ for op in (types.int32, types.int64, types.uint64)]
+ cases += [signature(op, op, op)
+ for op in sorted(types.real_domain)]
+ cases += [signature(op, op, op)
+ for op in sorted(types.complex_domain)]
+
+
+@infer_global(pow)
+class PowerBuiltin(BinOpPower):
+ # TODO add 3 operand version
+ pass
+
+
+class BitwiseShiftOperation(ConcreteTemplate):
+ # For bitshifts, only the first operand's signedness matters
+ # to choose the operation's signedness (the second operand
+ # should always be positive but will generally be considered
+ # signed anyway, since it's often a constant integer).
+ # (also, see issue #1995 for right-shifts)
+
+ # The RHS type is fixed to 64-bit signed/unsigned ints.
+ # The implementation will always cast the operands to the width of the
+ # result type, which is the widest between the LHS type and (u)intp.
+ cases = [signature(max(op, types.intp), op, op2)
+ for op in sorted(types.signed_domain)
+ for op2 in [types.uint64, types.int64]]
+ cases += [signature(max(op, types.uintp), op, op2)
+ for op in sorted(types.unsigned_domain)
+ for op2 in [types.uint64, types.int64]]
+ unsafe_casting = False
+
+
+@infer_global(operator.lshift)
+class BitwiseLeftShift(BitwiseShiftOperation):
+ pass
+
+@infer_global(operator.ilshift)
+class BitwiseLeftShift(BitwiseShiftOperation):
+ pass
+
+
+@infer_global(operator.rshift)
+class BitwiseRightShift(BitwiseShiftOperation):
+ pass
+
+
+@infer_global(operator.irshift)
+class BitwiseRightShift(BitwiseShiftOperation):
+ pass
+
+
+class BitwiseLogicOperation(BinOp):
+ cases = [signature(types.boolean, types.boolean, types.boolean)]
+ cases += list(integer_binop_cases)
+ unsafe_casting = False
+
+
+@infer_global(operator.and_)
+class BitwiseAnd(BitwiseLogicOperation):
+ pass
+
+
+@infer_global(operator.iand)
+class BitwiseAnd(BitwiseLogicOperation):
+ pass
+
+
+@infer_global(operator.or_)
+class BitwiseOr(BitwiseLogicOperation):
+ pass
+
+
+@infer_global(operator.ior)
+class BitwiseOr(BitwiseLogicOperation):
+ pass
+
+
+@infer_global(operator.xor)
+class BitwiseXor(BitwiseLogicOperation):
+ pass
+
+
+@infer_global(operator.ixor)
+class BitwiseXor(BitwiseLogicOperation):
+ pass
+
+
+# Bitwise invert and negate are special: we must not upcast the operand
+# for unsigned numbers, as that would change the result.
+# (i.e. ~np.int8(0) == 255 but ~np.int32(0) == 4294967295).
+
+@infer_global(operator.invert)
+class BitwiseInvert(ConcreteTemplate):
+ # Note Numba follows the Numpy semantics of returning a bool,
+ # while Python returns an int. This makes it consistent with
+ # np.invert() and makes array expressions correct.
+ cases = [signature(types.boolean, types.boolean)]
+ cases += [signature(choose_result_int(op), op) for op in sorted(types.unsigned_domain)]
+ cases += [signature(choose_result_int(op), op) for op in sorted(types.signed_domain)]
+
+ unsafe_casting = False
+
+
+class UnaryOp(ConcreteTemplate):
+ cases = [signature(choose_result_int(op), op) for op in sorted(types.unsigned_domain)]
+ cases += [signature(choose_result_int(op), op) for op in sorted(types.signed_domain)]
+ cases += [signature(op, op) for op in sorted(types.real_domain)]
+ cases += [signature(op, op) for op in sorted(types.complex_domain)]
+ cases += [signature(types.intp, types.boolean)]
+
+
+@infer_global(operator.neg)
+class UnaryNegate(UnaryOp):
+ pass
+
+
+@infer_global(operator.pos)
+class UnaryPositive(UnaryOp):
+ pass
+
+
+@infer_global(operator.not_)
+class UnaryNot(ConcreteTemplate):
+ cases = [signature(types.boolean, types.boolean)]
+ cases += [signature(types.boolean, op) for op in sorted(types.signed_domain)]
+ cases += [signature(types.boolean, op) for op in sorted(types.unsigned_domain)]
+ cases += [signature(types.boolean, op) for op in sorted(types.real_domain)]
+ cases += [signature(types.boolean, op) for op in sorted(types.complex_domain)]
+
+
+class OrderedCmpOp(ConcreteTemplate):
+ cases = [signature(types.boolean, types.boolean, types.boolean)]
+ cases += [signature(types.boolean, op, op) for op in sorted(types.signed_domain)]
+ cases += [signature(types.boolean, op, op) for op in sorted(types.unsigned_domain)]
+ cases += [signature(types.boolean, op, op) for op in sorted(types.real_domain)]
+
+
+class UnorderedCmpOp(ConcreteTemplate):
+ cases = OrderedCmpOp.cases + [
+ signature(types.boolean, op, op) for op in sorted(types.complex_domain)]
+
+
+@infer_global(operator.lt)
+class CmpOpLt(OrderedCmpOp):
+ pass
+
+
+@infer_global(operator.le)
+class CmpOpLe(OrderedCmpOp):
+ pass
+
+
+@infer_global(operator.gt)
+class CmpOpGt(OrderedCmpOp):
+ pass
+
+
+@infer_global(operator.ge)
+class CmpOpGe(OrderedCmpOp):
+ pass
+
+
+# more specific overloads should be registered first
+@infer_global(operator.eq)
+class ConstOpEq(AbstractTemplate):
+ def generic(self, args, kws):
+ assert not kws
+ (arg1, arg2) = args
+ if isinstance(arg1, types.Literal) and isinstance(arg2, types.Literal):
+ return signature(types.boolean, arg1, arg2)
+
+
+@infer_global(operator.ne)
+class ConstOpNotEq(ConstOpEq):
+ pass
+
+
+@infer_global(operator.eq)
+class CmpOpEq(UnorderedCmpOp):
+ pass
+
+
+@infer_global(operator.ne)
+class CmpOpNe(UnorderedCmpOp):
+ pass
+
+
+class TupleCompare(AbstractTemplate):
+ def generic(self, args, kws):
+ [lhs, rhs] = args
+ if isinstance(lhs, types.BaseTuple) and isinstance(rhs, types.BaseTuple):
+ for u, v in zip(lhs, rhs):
+ # Check element-wise comparability
+ res = self.context.resolve_function_type(self.key, (u, v), {})
+ if res is None:
+ break
+ else:
+ return signature(types.boolean, lhs, rhs)
+
+
+@infer_global(operator.eq)
+class TupleEq(TupleCompare):
+ pass
+
+
+@infer_global(operator.ne)
+class TupleNe(TupleCompare):
+ pass
+
+
+@infer_global(operator.ge)
+class TupleGe(TupleCompare):
+ pass
+
+
+@infer_global(operator.gt)
+class TupleGt(TupleCompare):
+ pass
+
+
+@infer_global(operator.le)
+class TupleLe(TupleCompare):
+ pass
+
+
+@infer_global(operator.lt)
+class TupleLt(TupleCompare):
+ pass
+
+
+@infer_global(operator.add)
+class TupleAdd(AbstractTemplate):
+ def generic(self, args, kws):
+ if len(args) == 2:
+ a, b = args
+ if (isinstance(a, types.BaseTuple) and isinstance(b, types.BaseTuple)
+ and not isinstance(a, types.BaseNamedTuple)
+ and not isinstance(b, types.BaseNamedTuple)):
+ res = types.BaseTuple.from_types(tuple(a) + tuple(b))
+ return signature(res, a, b)
+
+
+class CmpOpIdentity(AbstractTemplate):
+ def generic(self, args, kws):
+ [lhs, rhs] = args
+ return signature(types.boolean, lhs, rhs)
+
+
+@infer_global(operator.is_)
+class CmpOpIs(CmpOpIdentity):
+ pass
+
+
+@infer_global(operator.is_not)
+class CmpOpIsNot(CmpOpIdentity):
+ pass
+
+
+def normalize_1d_index(index):
+ """
+ Normalize the *index* type (an integer or slice) for indexing a 1D
+ sequence.
+ """
+ if isinstance(index, types.SliceType):
+ return index
+
+ elif isinstance(index, types.Integer):
+ return types.intp if index.signed else types.uintp
+
+
+@infer_global(operator.getitem)
+class GetItemCPointer(AbstractTemplate):
+ def generic(self, args, kws):
+ assert not kws
+ ptr, idx = args
+ if isinstance(ptr, types.CPointer) and isinstance(idx, types.Integer):
+ return signature(ptr.dtype, ptr, normalize_1d_index(idx))
+
+
+@infer_global(operator.setitem)
+class SetItemCPointer(AbstractTemplate):
+ def generic(self, args, kws):
+ assert not kws
+ ptr, idx, val = args
+ if isinstance(ptr, types.CPointer) and isinstance(idx, types.Integer):
+ return signature(types.none, ptr, normalize_1d_index(idx), ptr.dtype)
+
+
+@infer_global(len)
+class Len(AbstractTemplate):
+ def generic(self, args, kws):
+ assert not kws
+ (val,) = args
+ if isinstance(val, (types.Buffer, types.BaseTuple)):
+ return signature(types.intp, val)
+ elif isinstance(val, (types.RangeType)):
+ return signature(val.dtype, val)
+
+@infer_global(tuple)
+class TupleConstructor(AbstractTemplate):
+ def generic(self, args, kws):
+ assert not kws
+ # empty tuple case
+ if len(args) == 0:
+ return signature(types.Tuple(()))
+ (val,) = args
+ # tuple as input
+ if isinstance(val, types.BaseTuple):
+ return signature(val, val)
+
+
+@infer_global(operator.contains)
+class Contains(AbstractTemplate):
+ def generic(self, args, kws):
+ assert not kws
+ (seq, val) = args
+
+ if isinstance(seq, (types.Sequence)):
+ return signature(types.boolean, seq, val)
+
+@infer_global(operator.truth)
+class TupleBool(AbstractTemplate):
+ def generic(self, args, kws):
+ assert not kws
+ (val,) = args
+ if isinstance(val, (types.BaseTuple)):
+ return signature(types.boolean, val)
+
+
+@infer
+class StaticGetItemTuple(AbstractTemplate):
+ key = "static_getitem"
+
+ def generic(self, args, kws):
+ tup, idx = args
+ ret = None
+ if not isinstance(tup, types.BaseTuple):
+ return
+ if isinstance(idx, int):
+ try:
+ ret = tup.types[idx]
+ except IndexError:
+ raise errors.NumbaIndexError("tuple index out of range")
+ elif isinstance(idx, slice):
+ ret = types.BaseTuple.from_types(tup.types[idx])
+ if ret is not None:
+ sig = signature(ret, *args)
+ return sig
+
+
+@infer
+class StaticGetItemLiteralList(AbstractTemplate):
+ key = "static_getitem"
+
+ def generic(self, args, kws):
+ tup, idx = args
+ ret = None
+ if not isinstance(tup, types.LiteralList):
+ return
+ if isinstance(idx, int):
+ ret = tup.types[idx]
+ if ret is not None:
+ sig = signature(ret, *args)
+ return sig
+
+
+@infer
+class StaticGetItemLiteralStrKeyDict(AbstractTemplate):
+ key = "static_getitem"
+
+ def generic(self, args, kws):
+ tup, idx = args
+ ret = None
+ if not isinstance(tup, types.LiteralStrKeyDict):
+ return
+ if isinstance(idx, str):
+ if idx in tup.fields:
+ lookup = tup.fields.index(idx)
+ else:
+ raise errors.NumbaKeyError(f"Key '{idx}' is not in dict.")
+ ret = tup.types[lookup]
+ if ret is not None:
+ sig = signature(ret, *args)
+ return sig
+
+@infer
+class StaticGetItemClass(AbstractTemplate):
+ """This handles the "static_getitem" when a Numba type is subscripted e.g:
+ var = typed.List.empty_list(float64[::1, :])
+ It only allows this on simple numerical types. Compound types, like
+ records, are not supported.
+ """
+ key = "static_getitem"
+
+ def generic(self, args, kws):
+ clazz, idx = args
+ if not isinstance(clazz, types.NumberClass):
+ return
+ ret = clazz.dtype[idx]
+ sig = signature(ret, *args)
+ return sig
+
+
+# Generic implementation for "not in"
+
+@infer
+class GenericNotIn(AbstractTemplate):
+ key = "not in"
+
+ def generic(self, args, kws):
+ args = args[::-1]
+ sig = self.context.resolve_function_type(operator.contains, args, kws)
+ return signature(sig.return_type, *sig.args[::-1])
+
+
+#-------------------------------------------------------------------------------
+
+@infer_getattr
+class MemoryViewAttribute(AttributeTemplate):
+ key = types.MemoryView
+
+ def resolve_contiguous(self, buf):
+ return types.boolean
+
+ def resolve_c_contiguous(self, buf):
+ return types.boolean
+
+ def resolve_f_contiguous(self, buf):
+ return types.boolean
+
+ def resolve_itemsize(self, buf):
+ return types.intp
+
+ def resolve_nbytes(self, buf):
+ return types.intp
+
+ def resolve_readonly(self, buf):
+ return types.boolean
+
+ def resolve_shape(self, buf):
+ return types.UniTuple(types.intp, buf.ndim)
+
+ def resolve_strides(self, buf):
+ return types.UniTuple(types.intp, buf.ndim)
+
+ def resolve_ndim(self, buf):
+ return types.intp
+
+
+#-------------------------------------------------------------------------------
+
+
+@infer_getattr
+class BooleanAttribute(AttributeTemplate):
+ key = types.Boolean
+
+ def resolve___class__(self, ty):
+ return types.NumberClass(ty)
+
+ @bound_function("number.item")
+ def resolve_item(self, ty, args, kws):
+ assert not kws
+ if not args:
+ return signature(ty)
+
+
+@infer_getattr
+class NumberAttribute(AttributeTemplate):
+ key = types.Number
+
+ def resolve___class__(self, ty):
+ return types.NumberClass(ty)
+
+ def resolve_real(self, ty):
+ return getattr(ty, "underlying_float", ty)
+
+ def resolve_imag(self, ty):
+ return getattr(ty, "underlying_float", ty)
+
+ @bound_function("complex.conjugate")
+ def resolve_conjugate(self, ty, args, kws):
+ assert not args
+ assert not kws
+ return signature(ty)
+
+ @bound_function("number.item")
+ def resolve_item(self, ty, args, kws):
+ assert not kws
+ if not args:
+ return signature(ty)
+
+
+@infer_getattr
+class NPTimedeltaAttribute(AttributeTemplate):
+ key = types.NPTimedelta
+
+ def resolve___class__(self, ty):
+ return types.NumberClass(ty)
+
+
+@infer_getattr
+class NPDatetimeAttribute(AttributeTemplate):
+ key = types.NPDatetime
+
+ def resolve___class__(self, ty):
+ return types.NumberClass(ty)
+
+
+@infer_getattr
+class SliceAttribute(AttributeTemplate):
+ key = types.SliceType
+
+ def resolve_start(self, ty):
+ return types.intp
+
+ def resolve_stop(self, ty):
+ return types.intp
+
+ def resolve_step(self, ty):
+ return types.intp
+
+ @bound_function("slice.indices")
+ def resolve_indices(self, ty, args, kws):
+ assert not kws
+ if len(args) != 1:
+ raise errors.NumbaTypeError(
+ "indices() takes exactly one argument (%d given)" % len(args)
+ )
+ typ, = args
+ if not isinstance(typ, types.Integer):
+ raise errors.NumbaTypeError(
+ "'%s' object cannot be interpreted as an integer" % typ
+ )
+ return signature(types.UniTuple(types.intp, 3), types.intp)
+
+
+#-------------------------------------------------------------------------------
+
+
+@infer_getattr
+class NumberClassAttribute(AttributeTemplate):
+ key = types.NumberClass
+
+ def resolve___call__(self, classty):
+ """
+ Resolve a NumPy number class's constructor (e.g. calling numpy.int32(...))
+ """
+ ty = classty.instance_type
+
+ def typer(val):
+ if isinstance(val, (types.BaseTuple, types.Sequence)):
+ # Array constructor, e.g. np.int32([1, 2])
+ fnty = self.context.resolve_value_type(np.array)
+ sig = fnty.get_call_type(self.context, (val, types.DType(ty)),
+ {})
+ return sig.return_type
+ elif isinstance(val, (types.Number, types.Boolean, types.IntEnumMember)):
+ # Scalar constructor, e.g. np.int32(42)
+ return ty
+ elif isinstance(val, (types.NPDatetime, types.NPTimedelta)):
+ # Constructor cast from datetime-like, e.g.
+ # > np.int64(np.datetime64("2000-01-01"))
+ if ty.bitwidth == 64:
+ return ty
+ else:
+ msg = (f"Cannot cast {val} to {ty} as {ty} is not 64 bits "
+ "wide.")
+ raise errors.TypingError(msg)
+ else:
+ if (isinstance(val, types.Array) and val.ndim == 0 and
+ val.dtype == ty):
+ # This is 0d array -> scalar degrading
+ return ty
+ else:
+ # unsupported
+ msg = f"Casting {val} to {ty} directly is unsupported."
+ if isinstance(val, types.Array):
+ # array casts are supported a different way.
+ msg += f" Try doing '.astype(np.{ty})' instead"
+ raise errors.TypingError(msg)
+
+ return types.Function(make_callable_template(key=ty, typer=typer))
+
+
+@infer_getattr
+class TypeRefAttribute(AttributeTemplate):
+ key = types.TypeRef
+
+ def resolve___call__(self, classty):
+ """
+ Resolve a core number's constructor (e.g. calling int(...))
+
+ Note:
+
+ This is needed because of the limitation of the current type-system
+ implementation. Specifically, the lack of a higher-order type
+ (i.e. passing the ``DictType`` vs ``DictType(key_type, value_type)``)
+ """
+ ty = classty.instance_type
+
+ if isinstance(ty, type) and issubclass(ty, types.Type):
+ # Redirect the typing to a:
+ # @type_callable(ty)
+ # def typeddict_call(context):
+ # ...
+ # For example, see numba/typed/typeddict.py
+ # @type_callable(DictType)
+ # def typeddict_call(context):
+ class Redirect(object):
+
+ def __init__(self, context):
+ self.context = context
+
+ def __call__(self, *args, **kwargs):
+ result = self.context.resolve_function_type(ty, args, kwargs)
+ if hasattr(result, "pysig"):
+ self.pysig = result.pysig
+ return result
+
+ return types.Function(make_callable_template(key=ty,
+ typer=Redirect(self.context)))
+
+
+#------------------------------------------------------------------------------
+
+
+class MinMaxBase(AbstractTemplate):
+
+ def _unify_minmax(self, tys):
+ for ty in tys:
+ if not isinstance(ty, (types.Number, types.NPDatetime, types.NPTimedelta)):
+ return
+ return self.context.unify_types(*tys)
+
+ def generic(self, args, kws):
+ """
+ Resolve a min() or max() call.
+ """
+ assert not kws
+
+ if not args:
+ return
+ if len(args) == 1:
+ # max(arg) only supported if arg is an iterable
+ if isinstance(args[0], types.BaseTuple):
+ tys = list(args[0])
+ if not tys:
+ raise errors.TypingError("%s() argument is an empty tuple"
+ % (self.key.__name__,))
+ else:
+ return
+ else:
+ # max(*args)
+ tys = args
+ retty = self._unify_minmax(tys)
+ if retty is not None:
+ return signature(retty, *args)
+
+
+@infer_global(max)
+class Max(MinMaxBase):
+ pass
+
+
+@infer_global(min)
+class Min(MinMaxBase):
+ pass
+
+
+@infer_global(round)
+class Round(ConcreteTemplate):
+ cases = [
+ signature(types.intp, types.float32),
+ signature(types.int64, types.float64),
+ signature(types.float32, types.float32, types.intp),
+ signature(types.float64, types.float64, types.intp),
+ ]
+
+
+#------------------------------------------------------------------------------
+
+
+@infer_global(bool)
+class Bool(AbstractTemplate):
+
+ def generic(self, args, kws):
+ assert not kws
+ [arg] = args
+ if isinstance(arg, (types.Boolean, types.Number)):
+ return signature(types.boolean, arg)
+ # XXX typing for bool cannot be polymorphic because of the
+ # types.Function thing, so we redirect to the operator.truth
+ # intrinsic.
+ return self.context.resolve_function_type(operator.truth, args, kws)
+
+
+@infer_global(int)
+class Int(AbstractTemplate):
+
+ def generic(self, args, kws):
+ if kws:
+ raise errors.NumbaAssertionError('kws not supported')
+
+ [arg] = args
+
+ if isinstance(arg, types.Integer):
+ return signature(arg, arg)
+ if isinstance(arg, (types.Float, types.Boolean)):
+ return signature(types.intp, arg)
+ if isinstance(arg, types.NPDatetime):
+ if arg.unit == 'ns':
+ return signature(types.int64, arg)
+ else:
+ raise errors.NumbaTypeError(f"Only datetime64[ns] can be converted, but got datetime64[{arg.unit}]")
+ if isinstance(arg, types.NPTimedelta):
+ return signature(types.int64, arg)
+
+
+@infer_global(float)
+class Float(AbstractTemplate):
+
+ def generic(self, args, kws):
+ assert not kws
+
+ [arg] = args
+
+ if isinstance(arg, types.UnicodeType):
+ msg = 'argument must be a string literal'
+ raise errors.RequireLiteralValue(msg)
+
+ if isinstance(arg, types.StringLiteral):
+ return signature(types.float64, arg)
+
+ if arg not in types.number_domain:
+ raise errors.NumbaTypeError("float() only support for numbers")
+
+ if arg in types.complex_domain:
+ raise errors.NumbaTypeError("float() does not support complex")
+
+ if arg in types.integer_domain:
+ return signature(types.float64, arg)
+
+ elif arg in types.real_domain:
+ return signature(arg, arg)
+
+
+@infer_global(complex)
+class Complex(AbstractTemplate):
+
+ def generic(self, args, kws):
+ assert not kws
+
+ if len(args) == 1:
+ [arg] = args
+ if arg not in types.number_domain:
+ raise errors.NumbaTypeError("complex() only support for numbers")
+ if arg == types.float32:
+ return signature(types.complex64, arg)
+ else:
+ return signature(types.complex128, arg)
+
+ elif len(args) == 2:
+ [real, imag] = args
+ if (real not in types.number_domain or
+ imag not in types.number_domain):
+ raise errors.NumbaTypeError("complex() only support for numbers")
+ if real == imag == types.float32:
+ return signature(types.complex64, real, imag)
+ else:
+ return signature(types.complex128, real, imag)
+
+
+#------------------------------------------------------------------------------
+
+@infer_global(enumerate)
+class Enumerate(AbstractTemplate):
+
+ def generic(self, args, kws):
+ assert not kws
+ it = args[0]
+ if len(args) > 1 and not isinstance(args[1], types.Integer):
+ raise errors.NumbaTypeError("Only integers supported as start "
+ "value in enumerate")
+ elif len(args) > 2:
+ #let python raise its own error
+ enumerate(*args)
+
+ if isinstance(it, types.IterableType):
+ enumerate_type = types.EnumerateType(it)
+ return signature(enumerate_type, *args)
+
+
+@infer_global(zip)
+class Zip(AbstractTemplate):
+
+ def generic(self, args, kws):
+ assert not kws
+ if all(isinstance(it, types.IterableType) for it in args):
+ zip_type = types.ZipType(args)
+ return signature(zip_type, *args)
+
+
+@infer_global(iter)
+class Iter(AbstractTemplate):
+
+ def generic(self, args, kws):
+ assert not kws
+ if len(args) == 1:
+ it = args[0]
+ if isinstance(it, types.IterableType):
+ return signature(it.iterator_type, *args)
+
+
+@infer_global(next)
+class Next(AbstractTemplate):
+
+ def generic(self, args, kws):
+ assert not kws
+ if len(args) == 1:
+ it = args[0]
+ if isinstance(it, types.IteratorType):
+ return signature(it.yield_type, *args)
+
+
+#------------------------------------------------------------------------------
+
+@infer_global(type)
+class TypeBuiltin(AbstractTemplate):
+
+ def generic(self, args, kws):
+ assert not kws
+ if len(args) == 1:
+ # One-argument type() -> return the __class__
+ # Avoid literal types
+ arg = types.unliteral(args[0])
+ classty = self.context.resolve_getattr(arg, "__class__")
+ if classty is not None:
+ return signature(classty, *args)
+
+
+#------------------------------------------------------------------------------
+
+@infer_getattr
+class OptionalAttribute(AttributeTemplate):
+ key = types.Optional
+
+ def generic_resolve(self, optional, attr):
+ return self.context.resolve_getattr(optional.type, attr)
+
+#------------------------------------------------------------------------------
+
+@infer_getattr
+class DeferredAttribute(AttributeTemplate):
+ key = types.DeferredType
+
+ def generic_resolve(self, deferred, attr):
+ return self.context.resolve_getattr(deferred.get(), attr)
+
+
+#------------------------------------------------------------------------------
+
+
+class IndexValue(object):
+ """
+ Index and value
+ """
+ def __init__(self, ind, val):
+ self.index = ind
+ self.value = val
+
+ def __repr__(self):
+ return 'IndexValue(%f, %f)' % (self.index, self.value)
+
+
+class IndexValueType(types.Type):
+ def __init__(self, val_typ):
+ self.val_typ = val_typ
+ super(IndexValueType, self).__init__(
+ name='IndexValueType({})'.format(val_typ))
+
+
+@typeof_impl.register(IndexValue)
+def typeof_index(val, c):
+ val_typ = typeof_impl(val.value, c)
+ return IndexValueType(val_typ)
+
+
+@type_callable(IndexValue)
+def type_index_value(context):
+ def typer(ind, mval):
+ if ind == types.intp or ind == types.uintp:
+ return IndexValueType(mval)
+ return typer
+
+
+@register_model(IndexValueType)
+class IndexValueModel(models.StructModel):
+ def __init__(self, dmm, fe_type):
+ members = [
+ ('index', types.intp),
+ ('value', fe_type.val_typ),
+ ]
+ models.StructModel.__init__(self, dmm, fe_type, members)
+
+
+make_attribute_wrapper(IndexValueType, 'index', 'index')
+make_attribute_wrapper(IndexValueType, 'value', 'value')
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/old_cmathdecl.py b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/old_cmathdecl.py
new file mode 100644
index 0000000000000000000000000000000000000000..829e962a807a6138a1f18d3eebd70f46c2d0756d
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/old_cmathdecl.py
@@ -0,0 +1,44 @@
+import cmath
+
+from numba.core import types, utils
+from numba.core.typing.templates import (AbstractTemplate, ConcreteTemplate,
+ signature, Registry)
+
+registry = Registry()
+infer_global = registry.register_global
+
+# TODO: support non-complex arguments (floats and ints)
+
+
+@infer_global(cmath.acos)
+@infer_global(cmath.asin)
+@infer_global(cmath.asinh)
+@infer_global(cmath.atan)
+@infer_global(cmath.atanh)
+@infer_global(cmath.cos)
+@infer_global(cmath.exp)
+@infer_global(cmath.sin)
+@infer_global(cmath.sqrt)
+@infer_global(cmath.tan)
+class CMath_unary(ConcreteTemplate):
+ cases = [signature(tp, tp) for tp in sorted(types.complex_domain)]
+
+
+@infer_global(cmath.isinf)
+@infer_global(cmath.isnan)
+class CMath_predicate(ConcreteTemplate):
+ cases = [signature(types.boolean, tp) for tp in
+ sorted(types.complex_domain)]
+
+
+@infer_global(cmath.isfinite)
+class CMath_isfinite(CMath_predicate):
+ pass
+
+
+@infer_global(cmath.log)
+class Cmath_log(ConcreteTemplate):
+ # unary cmath.log()
+ cases = [signature(tp, tp) for tp in sorted(types.complex_domain)]
+ # binary cmath.log()
+ cases += [signature(tp, tp, tp) for tp in sorted(types.complex_domain)]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/old_mathdecl.py b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/old_mathdecl.py
new file mode 100644
index 0000000000000000000000000000000000000000..2b46e4316e4a61a7fbfeb45da37cb6b243e5fb9b
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/old_mathdecl.py
@@ -0,0 +1,150 @@
+import math
+from numba.core import types, utils
+from numba.core.typing.templates import (AttributeTemplate, ConcreteTemplate,
+ signature, Registry)
+
+registry = Registry()
+infer_global = registry.register_global
+
+
+@infer_global(math.exp)
+@infer_global(math.expm1)
+@infer_global(math.fabs)
+@infer_global(math.sqrt)
+@infer_global(math.log)
+@infer_global(math.log1p)
+@infer_global(math.log10)
+@infer_global(math.log2)
+@infer_global(math.sin)
+@infer_global(math.cos)
+@infer_global(math.tan)
+@infer_global(math.sinh)
+@infer_global(math.cosh)
+@infer_global(math.tanh)
+@infer_global(math.asin)
+@infer_global(math.acos)
+@infer_global(math.atan)
+@infer_global(math.asinh)
+@infer_global(math.acosh)
+@infer_global(math.atanh)
+@infer_global(math.degrees)
+@infer_global(math.radians)
+@infer_global(math.erf)
+@infer_global(math.erfc)
+@infer_global(math.gamma)
+@infer_global(math.lgamma)
+class Math_unary(ConcreteTemplate):
+ cases = [
+ signature(types.float64, types.int64),
+ signature(types.float64, types.uint64),
+ signature(types.float32, types.float32),
+ signature(types.float64, types.float64),
+ ]
+
+
+@infer_global(math.atan2)
+class Math_atan2(ConcreteTemplate):
+ cases = [
+ signature(types.float64, types.int64, types.int64),
+ signature(types.float64, types.uint64, types.uint64),
+ signature(types.float32, types.float32, types.float32),
+ signature(types.float64, types.float64, types.float64),
+ ]
+
+
+@infer_global(math.trunc)
+class Math_converter(ConcreteTemplate):
+ cases = [
+ signature(types.intp, types.intp),
+ signature(types.int64, types.int64),
+ signature(types.uint64, types.uint64),
+ signature(types.int64, types.float32),
+ signature(types.int64, types.float64),
+ ]
+
+
+@infer_global(math.floor)
+@infer_global(math.ceil)
+class Math_floor_ceil(Math_converter):
+ pass
+
+
+@infer_global(math.copysign)
+class Math_copysign(ConcreteTemplate):
+ cases = [
+ signature(types.float32, types.float32, types.float32),
+ signature(types.float64, types.float64, types.float64),
+ ]
+
+
+@infer_global(math.hypot)
+class Math_hypot(ConcreteTemplate):
+ cases = [
+ signature(types.float64, types.int64, types.int64),
+ signature(types.float64, types.uint64, types.uint64),
+ signature(types.float32, types.float32, types.float32),
+ signature(types.float64, types.float64, types.float64),
+ ]
+
+
+@infer_global(math.nextafter)
+class Math_nextafter(ConcreteTemplate):
+ cases = [
+ signature(types.float64, types.float64, types.float64),
+ signature(types.float32, types.float32, types.float32),
+ ]
+
+
+@infer_global(math.isinf)
+@infer_global(math.isnan)
+class Math_predicate(ConcreteTemplate):
+ cases = [
+ signature(types.boolean, types.int64),
+ signature(types.boolean, types.uint64),
+ signature(types.boolean, types.float32),
+ signature(types.boolean, types.float64),
+ ]
+
+
+@infer_global(math.isfinite)
+class Math_isfinite(Math_predicate):
+ pass
+
+
+@infer_global(math.pow)
+class Math_pow(ConcreteTemplate):
+ cases = [
+ signature(types.float64, types.float64, types.int64),
+ signature(types.float64, types.float64, types.uint64),
+ signature(types.float32, types.float32, types.float32),
+ signature(types.float64, types.float64, types.float64),
+ ]
+
+
+@infer_global(math.gcd)
+class Math_gcd(ConcreteTemplate):
+ cases = [
+ signature(types.int64, types.int64, types.int64),
+ signature(types.int32, types.int32, types.int32),
+ signature(types.int16, types.int16, types.int16),
+ signature(types.int8, types.int8, types.int8),
+ signature(types.uint64, types.uint64, types.uint64),
+ signature(types.uint32, types.uint32, types.uint32),
+ signature(types.uint16, types.uint16, types.uint16),
+ signature(types.uint8, types.uint8, types.uint8),
+ ]
+
+
+@infer_global(math.frexp)
+class Math_frexp(ConcreteTemplate):
+ cases = [
+ signature(types.Tuple((types.float64, types.intc)), types.float64),
+ signature(types.Tuple((types.float32, types.intc)), types.float32),
+ ]
+
+@infer_global(math.ldexp)
+class Math_ldexp(ConcreteTemplate):
+ cases = [
+ signature(types.float64, types.float64, types.intc),
+ signature(types.float32, types.float32, types.intc),
+ ]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/setdecl.py b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/setdecl.py
new file mode 100644
index 0000000000000000000000000000000000000000..2ee3c402eb8a8bea95cbd3efb2ac9170117938fa
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/setdecl.py
@@ -0,0 +1,107 @@
+import operator
+
+from numba.core import types
+from .templates import (ConcreteTemplate, AbstractTemplate, AttributeTemplate,
+ CallableTemplate, Registry, signature, bound_function,
+ make_callable_template)
+# Ensure set is typed as a collection as well
+from numba.core.typing import collections
+
+
+registry = Registry()
+infer = registry.register
+infer_global = registry.register_global
+infer_getattr = registry.register_attr
+
+
+@infer_global(set)
+class SetBuiltin(AbstractTemplate):
+
+ def generic(self, args, kws):
+ assert not kws
+ if args:
+ # set(iterable)
+ iterable, = args
+ if isinstance(iterable, types.IterableType):
+ dtype = iterable.iterator_type.yield_type
+ if isinstance(dtype, types.Hashable):
+ return signature(types.Set(dtype), iterable)
+ else:
+ # set()
+ return signature(types.Set(types.undefined))
+
+
+@infer_getattr
+class SetAttribute(AttributeTemplate):
+ key = types.Set
+
+ @bound_function("set.add")
+ def resolve_add(self, set, args, kws):
+ item, = args
+ assert not kws
+ unified = self.context.unify_pairs(set.dtype, item)
+ if unified is not None:
+ sig = signature(types.none, unified)
+ sig = sig.replace(recvr=set.copy(dtype=unified))
+ return sig
+
+ @bound_function("set.update")
+ def resolve_update(self, set, args, kws):
+ iterable, = args
+ assert not kws
+ if not isinstance(iterable, types.IterableType):
+ return
+
+ dtype = iterable.iterator_type.yield_type
+ unified = self.context.unify_pairs(set.dtype, dtype)
+ if unified is not None:
+ sig = signature(types.none, iterable)
+ sig = sig.replace(recvr=set.copy(dtype=unified))
+ return sig
+
+ def _resolve_operator(self, set, args, kws):
+ assert not kws
+ iterable, = args
+ # Set arguments only supported for now
+ # (note we can mix non-reflected and reflected arguments)
+ if isinstance(iterable, types.Set) and iterable.dtype == set.dtype:
+ return signature(set, iterable)
+
+ def _resolve_comparator(self, set, args, kws):
+ assert not kws
+ arg, = args
+ if arg == set:
+ return signature(types.boolean, arg)
+
+
+class SetOperator(AbstractTemplate):
+
+ def generic(self, args, kws):
+ if len(args) != 2:
+ return
+ a, b = args
+ if (isinstance(a, types.Set) and isinstance(b, types.Set)
+ and a.dtype == b.dtype):
+ return signature(a, *args)
+
+
+class SetComparison(AbstractTemplate):
+
+ def generic(self, args, kws):
+ if len(args) != 2:
+ return
+ a, b = args
+ if isinstance(a, types.Set) and isinstance(b, types.Set) and a == b:
+ return signature(types.boolean, *args)
+
+
+for op_key in (operator.add, operator.invert):
+ @infer_global(op_key)
+ class ConcreteSetOperator(SetOperator):
+ key = op_key
+
+
+for op_key in (operator.iadd,):
+ @infer_global(op_key)
+ class ConcreteInplaceSetOperator(SetOperator):
+ key = op_key
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/templates.py b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/templates.py
new file mode 100644
index 0000000000000000000000000000000000000000..2bc465eeabcf5c60d8e0d15e8c516772ff469342
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/templates.py
@@ -0,0 +1,1337 @@
+"""
+Define typing templates
+"""
+
+from abc import ABC, abstractmethod
+import functools
+import sys
+import inspect
+import os.path
+from collections import namedtuple
+from collections.abc import Sequence
+from types import MethodType, FunctionType, MappingProxyType
+
+import numba
+from numba.core import types, utils, targetconfig
+from numba.core.errors import (
+ TypingError,
+ InternalError,
+)
+from numba.core.cpu_options import InlineOptions
+
+# info store for inliner callback functions e.g. cost model
+_inline_info = namedtuple('inline_info',
+ 'func_ir typemap calltypes signature')
+
+
+class Signature(object):
+ """
+ The signature of a function call or operation, i.e. its argument types
+ and return type.
+ """
+
+ # XXX Perhaps the signature should be a BoundArguments, instead
+ # of separate args and pysig...
+ __slots__ = '_return_type', '_args', '_recvr', '_pysig'
+
+ def __init__(self, return_type, args, recvr, pysig=None):
+ if isinstance(args, list):
+ args = tuple(args)
+ self._return_type = return_type
+ self._args = args
+ self._recvr = recvr
+ self._pysig = pysig
+
+ @property
+ def return_type(self):
+ return self._return_type
+
+ @property
+ def args(self):
+ return self._args
+
+ @property
+ def recvr(self):
+ return self._recvr
+
+ @property
+ def pysig(self):
+ return self._pysig
+
+ def replace(self, **kwargs):
+ """Copy and replace the given attributes provided as keyword arguments.
+ Returns an updated copy.
+ """
+ curstate = dict(return_type=self.return_type,
+ args=self.args,
+ recvr=self.recvr,
+ pysig=self.pysig)
+ curstate.update(kwargs)
+ return Signature(**curstate)
+
+ def __getstate__(self):
+ """
+ Needed because of __slots__.
+ """
+ return self._return_type, self._args, self._recvr, self._pysig
+
+ def __setstate__(self, state):
+ """
+ Needed because of __slots__.
+ """
+ self._return_type, self._args, self._recvr, self._pysig = state
+
+ def __hash__(self):
+ return hash((self.args, self.return_type))
+
+ def __eq__(self, other):
+ if isinstance(other, Signature):
+ return (self.args == other.args and
+ self.return_type == other.return_type and
+ self.recvr == other.recvr and
+ self.pysig == other.pysig)
+
+ def __ne__(self, other):
+ return not (self == other)
+
+ def __repr__(self):
+ return "%s -> %s" % (self.args, self.return_type)
+
+ @property
+ def is_method(self):
+ """
+ Whether this signature represents a bound method or a regular
+ function.
+ """
+ return self.recvr is not None
+
+ def as_method(self):
+ """
+ Convert this signature to a bound method signature.
+ """
+ if self.recvr is not None:
+ return self
+ sig = signature(self.return_type, *self.args[1:],
+ recvr=self.args[0])
+
+ # Adjust the python signature
+ params = list(self.pysig.parameters.values())[1:]
+ sig = sig.replace(
+ pysig=utils.pySignature(
+ parameters=params,
+ return_annotation=self.pysig.return_annotation,
+ ),
+ )
+ return sig
+
+ def as_function(self):
+ """
+ Convert this signature to a regular function signature.
+ """
+ if self.recvr is None:
+ return self
+ sig = signature(self.return_type, *((self.recvr,) + self.args))
+ return sig
+
+ def as_type(self):
+ """
+ Convert this signature to a first-class function type.
+ """
+ return types.FunctionType(self)
+
+ def __unliteral__(self):
+ return signature(types.unliteral(self.return_type),
+ *map(types.unliteral, self.args))
+
+ def dump(self, tab=''):
+ c = self.as_type()._code
+ print(f'{tab}DUMP {type(self).__name__} [type code: {c}]')
+ print(f'{tab} Argument types:')
+ for a in self.args:
+ a.dump(tab=tab + ' | ')
+ print(f'{tab} Return type:')
+ self.return_type.dump(tab=tab + ' | ')
+ print(f'{tab}END DUMP')
+
+ def is_precise(self):
+ for atype in self.args:
+ if not atype.is_precise():
+ return False
+ return self.return_type.is_precise()
+
+
+def make_concrete_template(name, key, signatures):
+ baseclasses = (ConcreteTemplate,)
+ gvars = dict(key=key, cases=list(signatures))
+ return type(name, baseclasses, gvars)
+
+
+def make_callable_template(key, typer, recvr=None):
+ """
+ Create a callable template with the given key and typer function.
+ """
+ def generic(self):
+ return typer
+
+ name = "%s_CallableTemplate" % (key,)
+ bases = (CallableTemplate,)
+ class_dict = dict(key=key, generic=generic, recvr=recvr)
+ return type(name, bases, class_dict)
+
+
+def signature(return_type, *args, **kws):
+ recvr = kws.pop('recvr', None)
+ assert not kws
+ return Signature(return_type, args, recvr=recvr)
+
+
+def fold_arguments(pysig, args, kws, normal_handler, default_handler,
+ stararg_handler):
+ """
+ Given the signature *pysig*, explicit *args* and *kws*, resolve
+ omitted arguments and keyword arguments. A tuple of positional
+ arguments is returned.
+ Various handlers allow to process arguments:
+ - normal_handler(index, param, value) is called for normal arguments
+ - default_handler(index, param, default) is called for omitted arguments
+ - stararg_handler(index, param, values) is called for a "*args" argument
+ """
+ if isinstance(kws, Sequence):
+ # Normalize dict kws
+ kws = dict(kws)
+
+ # deal with kwonly args
+ params = pysig.parameters
+ kwonly = []
+ for name, p in params.items():
+ if p.kind == p.KEYWORD_ONLY:
+ kwonly.append(name)
+
+ if kwonly:
+ bind_args = args[:-len(kwonly)]
+ else:
+ bind_args = args
+ bind_kws = kws.copy()
+ if kwonly:
+ for idx, n in enumerate(kwonly):
+ bind_kws[n] = args[len(kwonly) + idx]
+
+ # now bind
+ try:
+ ba = pysig.bind(*bind_args, **bind_kws)
+ except TypeError as e:
+ # The binding attempt can raise if the args don't match up, this needs
+ # to be converted to a TypingError so that e.g. partial type inference
+ # doesn't just halt.
+ msg = (f"Cannot bind 'args={bind_args} kws={bind_kws}' to "
+ f"signature '{pysig}' due to \"{type(e).__name__}: {e}\".")
+ raise TypingError(msg)
+ for i, param in enumerate(pysig.parameters.values()):
+ name = param.name
+ default = param.default
+ if param.kind == param.VAR_POSITIONAL:
+ # stararg may be omitted, in which case its "default" value
+ # is simply the empty tuple
+ if name in ba.arguments:
+ argval = ba.arguments[name]
+ # NOTE: avoid wrapping the tuple type for stararg in another
+ # tuple.
+ if (len(argval) == 1 and
+ isinstance(argval[0], (types.StarArgTuple,
+ types.StarArgUniTuple))):
+ argval = tuple(argval[0])
+ else:
+ argval = ()
+ out = stararg_handler(i, param, argval)
+
+ ba.arguments[name] = out
+ elif name in ba.arguments:
+ # Non-stararg, present
+ ba.arguments[name] = normal_handler(i, param, ba.arguments[name])
+ else:
+ # Non-stararg, omitted
+ assert default is not param.empty
+ ba.arguments[name] = default_handler(i, param, default)
+ # Collect args in the right order
+ args = tuple(ba.arguments[param.name]
+ for param in pysig.parameters.values())
+ return args
+
+
+class FunctionTemplate(ABC):
+ # Set to true to disable unsafe cast.
+ # subclass overide-able
+ unsafe_casting = True
+ # Set to true to require exact match without casting.
+ # subclass overide-able
+ exact_match_required = False
+ # Set to true to prefer literal arguments.
+ # Useful for definitions that specialize on literal but also support
+ # non-literals.
+ # subclass overide-able
+ prefer_literal = False
+ # metadata
+ metadata = {}
+
+ def __init__(self, context):
+ self.context = context
+
+ def _select(self, cases, args, kws):
+ options = {
+ 'unsafe_casting': self.unsafe_casting,
+ 'exact_match_required': self.exact_match_required,
+ }
+ selected = self.context.resolve_overload(self.key, cases, args, kws,
+ **options)
+ return selected
+
+ def get_impl_key(self, sig):
+ """
+ Return the key for looking up the implementation for the given
+ signature on the target context.
+ """
+ # Lookup the key on the class, to avoid binding it with `self`.
+ key = type(self).key
+ # On Python 2, we must also take care about unbound methods
+ if isinstance(key, MethodType):
+ assert key.im_self is None
+ key = key.im_func
+ return key
+
+ @classmethod
+ def get_source_code_info(cls, impl):
+ """
+ Gets the source information about function impl.
+ Returns:
+
+ code - str: source code as a string
+ firstlineno - int: the first line number of the function impl
+ path - str: the path to file containing impl
+
+ if any of the above are not available something generic is returned
+ """
+ try:
+ code, firstlineno = inspect.getsourcelines(impl)
+ except OSError: # missing source, probably a string
+ code = "None available (built from string?)"
+ firstlineno = 0
+ path = inspect.getsourcefile(impl)
+ if path is None:
+ path = " (built from string?)"
+ return code, firstlineno, path
+
+ @abstractmethod
+ def get_template_info(self):
+ """
+ Returns a dictionary with information specific to the template that will
+ govern how error messages are displayed to users. The dictionary must
+ be of the form:
+ info = {
+ 'kind': "unknown", # str: The kind of template, e.g. "Overload"
+ 'name': "unknown", # str: The name of the source function
+ 'sig': "unknown", # str: The signature(s) of the source function
+ 'filename': "unknown", # str: The filename of the source function
+ 'lines': ("start", "end"), # tuple(int, int): The start and
+ end line of the source function.
+ 'docstring': "unknown" # str: The docstring of the source function
+ }
+ """
+ pass
+
+ def __str__(self):
+ info = self.get_template_info()
+ srcinfo = f"{info['filename']}:{info['lines'][0]}"
+ return f"<{self.__class__.__name__} {srcinfo}>"
+
+ __repr__ = __str__
+
+
+class AbstractTemplate(FunctionTemplate):
+ """
+ Defines method ``generic(self, args, kws)`` which compute a possible
+ signature base on input types. The signature does not have to match the
+ input types. It is compared against the input types afterwards.
+ """
+
+ def apply(self, args, kws):
+ generic = getattr(self, "generic")
+ sig = generic(args, kws)
+ # Enforce that *generic()* must return None or Signature
+ if sig is not None:
+ if not isinstance(sig, Signature):
+ raise AssertionError(
+ "generic() must return a Signature or None. "
+ "{} returned {}".format(generic, type(sig)),
+ )
+
+ # Unpack optional type if no matching signature
+ if not sig and any(isinstance(x, types.Optional) for x in args):
+ def unpack_opt(x):
+ if isinstance(x, types.Optional):
+ return x.type
+ else:
+ return x
+
+ args = list(map(unpack_opt, args))
+ assert not kws # Not supported yet
+ sig = generic(args, kws)
+
+ return sig
+
+ def get_template_info(self):
+ impl = getattr(self, "generic")
+ basepath = os.path.dirname(os.path.dirname(numba.__file__))
+
+ code, firstlineno, path = self.get_source_code_info(impl)
+ sig = str(utils.pysignature(impl))
+ info = {
+ 'kind': "overload",
+ 'name': getattr(impl, '__qualname__', impl.__name__),
+ 'sig': sig,
+ 'filename': utils.safe_relpath(path, start=basepath),
+ 'lines': (firstlineno, firstlineno + len(code) - 1),
+ 'docstring': impl.__doc__
+ }
+ return info
+
+
+class CallableTemplate(FunctionTemplate):
+ """
+ Base class for a template defining a ``generic(self)`` method
+ returning a callable to be called with the actual ``*args`` and
+ ``**kwargs`` representing the call signature. The callable has
+ to return a return type, a full signature, or None. The signature
+ does not have to match the input types. It is compared against the
+ input types afterwards.
+ """
+ recvr = None
+
+ def apply(self, args, kws):
+ generic = getattr(self, "generic")
+ typer = generic()
+ match_sig = inspect.signature(typer)
+ try:
+ match_sig.bind(*args, **kws)
+ except TypeError as e:
+ # bind failed, raise, if there's a
+ # ValueError then there's likely unrecoverable
+ # problems
+ raise TypingError(str(e)) from e
+
+ sig = typer(*args, **kws)
+
+ # Unpack optional type if no matching signature
+ if sig is None:
+ if any(isinstance(x, types.Optional) for x in args):
+ def unpack_opt(x):
+ if isinstance(x, types.Optional):
+ return x.type
+ else:
+ return x
+
+ args = list(map(unpack_opt, args))
+ sig = typer(*args, **kws)
+ if sig is None:
+ return
+
+ # Get the pysig
+ try:
+ pysig = typer.pysig
+ except AttributeError:
+ pysig = utils.pysignature(typer)
+
+ # Fold any keyword arguments
+ bound = pysig.bind(*args, **kws)
+ if bound.kwargs:
+ raise TypingError("unsupported call signature")
+ if not isinstance(sig, Signature):
+ # If not a signature, `sig` is assumed to be the return type
+ if not isinstance(sig, types.Type):
+ raise TypeError("invalid return type for callable template: "
+ "got %r" % (sig,))
+ sig = signature(sig, *bound.args)
+ if self.recvr is not None:
+ sig = sig.replace(recvr=self.recvr)
+ # Hack any omitted parameters out of the typer's pysig,
+ # as lowering expects an exact match between formal signature
+ # and actual args.
+ if len(bound.args) < len(pysig.parameters):
+ parameters = list(pysig.parameters.values())[:len(bound.args)]
+ pysig = pysig.replace(parameters=parameters)
+ sig = sig.replace(pysig=pysig)
+ cases = [sig]
+ return self._select(cases, bound.args, bound.kwargs)
+
+ def get_template_info(self):
+ impl = getattr(self, "generic")
+ basepath = os.path.dirname(os.path.dirname(numba.__file__))
+ code, firstlineno, path = self.get_source_code_info(impl)
+ sig = str(utils.pysignature(impl))
+ info = {
+ 'kind': "overload",
+ 'name': getattr(self.key, '__name__',
+ getattr(impl, '__qualname__', impl.__name__),),
+ 'sig': sig,
+ 'filename': utils.safe_relpath(path, start=basepath),
+ 'lines': (firstlineno, firstlineno + len(code) - 1),
+ 'docstring': impl.__doc__
+ }
+ return info
+
+
+class ConcreteTemplate(FunctionTemplate):
+ """
+ Defines attributes "cases" as a list of signature to match against the
+ given input types.
+ """
+
+ def apply(self, args, kws):
+ cases = getattr(self, 'cases')
+ return self._select(cases, args, kws)
+
+ def get_template_info(self):
+ import operator
+ name = getattr(self.key, '__name__', "unknown")
+ op_func = getattr(operator, name, None)
+
+ kind = "Type restricted function"
+ if op_func is not None:
+ if self.key is op_func:
+ kind = "operator overload"
+ info = {
+ 'kind': kind,
+ 'name': name,
+ 'sig': "unknown",
+ 'filename': "unknown",
+ 'lines': ("unknown", "unknown"),
+ 'docstring': "unknown"
+ }
+ return info
+
+
+class _EmptyImplementationEntry(InternalError):
+ def __init__(self, reason):
+ super(_EmptyImplementationEntry, self).__init__(
+ "_EmptyImplementationEntry({!r})".format(reason),
+ )
+
+
+class _OverloadFunctionTemplate(AbstractTemplate):
+ """
+ A base class of templates for overload functions.
+ """
+
+ def _validate_sigs(self, typing_func, impl_func):
+ # check that the impl func and the typing func have the same signature!
+ typing_sig = utils.pysignature(typing_func)
+ impl_sig = utils.pysignature(impl_func)
+ # the typing signature is considered golden and must be adhered to by
+ # the implementation...
+ # Things that are valid:
+ # 1. args match exactly
+ # 2. kwargs match exactly in name and default value
+ # 3. Use of *args in the same location by the same name in both typing
+ # and implementation signature
+ # 4. Use of *args in the implementation signature to consume any number
+ # of arguments in the typing signature.
+ # Things that are invalid:
+ # 5. Use of *args in the typing signature that is not replicated
+ # in the implementing signature
+ # 6. Use of **kwargs
+
+ def get_args_kwargs(sig):
+ kws = []
+ args = []
+ pos_arg = None
+ for x in sig.parameters.values():
+ if x.default == utils.pyParameter.empty:
+ args.append(x)
+ if x.kind == utils.pyParameter.VAR_POSITIONAL:
+ pos_arg = x
+ elif x.kind == utils.pyParameter.VAR_KEYWORD:
+ msg = ("The use of VAR_KEYWORD (e.g. **kwargs) is "
+ "unsupported. (offending argument name is '%s')")
+ raise InternalError(msg % x)
+ else:
+ kws.append(x)
+ return args, kws, pos_arg
+
+ ty_args, ty_kws, ty_pos = get_args_kwargs(typing_sig)
+ im_args, im_kws, im_pos = get_args_kwargs(impl_sig)
+
+ sig_fmt = ("Typing signature: %s\n"
+ "Implementation signature: %s")
+ sig_str = sig_fmt % (typing_sig, impl_sig)
+
+ err_prefix = "Typing and implementation arguments differ in "
+
+ a = ty_args
+ b = im_args
+ if ty_pos:
+ if not im_pos:
+ # case 5. described above
+ msg = ("VAR_POSITIONAL (e.g. *args) argument kind (offending "
+ "argument name is '%s') found in the typing function "
+ "signature, but is not in the implementing function "
+ "signature.\n%s") % (ty_pos, sig_str)
+ raise InternalError(msg)
+ else:
+ if im_pos:
+ # no *args in typing but there's a *args in the implementation
+ # this is case 4. described above
+ b = im_args[:im_args.index(im_pos)]
+ try:
+ a = ty_args[:ty_args.index(b[-1]) + 1]
+ except ValueError:
+ # there's no b[-1] arg name in the ty_args, something is
+ # very wrong, we can't work out a diff (*args consumes
+ # unknown quantity of args) so just report first error
+ specialized = "argument names.\n%s\nFirst difference: '%s'"
+ msg = err_prefix + specialized % (sig_str, b[-1])
+ raise InternalError(msg)
+
+ def gen_diff(typing, implementing):
+ diff = set(typing) ^ set(implementing)
+ return "Difference: %s" % diff
+
+ if a != b:
+ specialized = "argument names.\n%s\n%s" % (sig_str, gen_diff(a, b))
+ raise InternalError(err_prefix + specialized)
+
+ # ensure kwargs are the same
+ ty = [x.name for x in ty_kws]
+ im = [x.name for x in im_kws]
+ if ty != im:
+ specialized = "keyword argument names.\n%s\n%s"
+ msg = err_prefix + specialized % (sig_str, gen_diff(ty_kws, im_kws))
+ raise InternalError(msg)
+ same = [x.default for x in ty_kws] == [x.default for x in im_kws]
+ if not same:
+ specialized = "keyword argument default values.\n%s\n%s"
+ msg = err_prefix + specialized % (sig_str, gen_diff(ty_kws, im_kws))
+ raise InternalError(msg)
+
+ def generic(self, args, kws):
+ """
+ Type the overloaded function by compiling the appropriate
+ implementation for the given args.
+ """
+ from numba.core.typed_passes import PreLowerStripPhis
+
+ disp, new_args = self._get_impl(args, kws)
+ if disp is None:
+ return
+ # Compile and type it for the given types
+ disp_type = types.Dispatcher(disp)
+ # Store the compiled overload for use in the lowering phase if there's
+ # no inlining required (else functions are being compiled which will
+ # never be used as they are inlined)
+ if not self._inline.is_never_inline:
+ # need to run the compiler front end up to type inference to compute
+ # a signature
+ from numba.core import typed_passes, compiler
+ from numba.core.inline_closurecall import InlineWorker
+ fcomp = disp._compiler
+ flags = compiler.Flags()
+
+ # Updating these causes problems?!
+ #fcomp.targetdescr.options.parse_as_flags(flags,
+ # fcomp.targetoptions)
+ #flags = fcomp._customize_flags(flags)
+
+ # spoof a compiler pipline like the one that will be in use
+ tyctx = fcomp.targetdescr.typing_context
+ tgctx = fcomp.targetdescr.target_context
+ compiler_inst = fcomp.pipeline_class(tyctx, tgctx, None, None, None,
+ flags, None, )
+ inline_worker = InlineWorker(tyctx, tgctx, fcomp.locals,
+ compiler_inst, flags, None,)
+
+ # If the inlinee contains something to trigger literal arg dispatch
+ # then the pipeline call will unconditionally fail due to a raised
+ # ForceLiteralArg exception. Therefore `resolve` is run first, as
+ # type resolution must occur at some point, this will hit any
+ # `literally` calls and because it's going via the dispatcher will
+ # handle them correctly i.e. ForceLiteralArg propagates. This having
+ # the desired effect of ensuring the pipeline call is only made in
+ # situations that will succeed. For context see #5887.
+ resolve = disp_type.dispatcher.get_call_template
+ template, pysig, folded_args, kws = resolve(new_args, kws)
+ ir = inline_worker.run_untyped_passes(
+ disp_type.dispatcher.py_func, enable_ssa=True
+ )
+
+ (
+ typemap,
+ return_type,
+ calltypes,
+ _
+ ) = typed_passes.type_inference_stage(
+ self.context, tgctx, ir, folded_args, None)
+ ir = PreLowerStripPhis()._strip_phi_nodes(ir)
+ ir._definitions = numba.core.ir_utils.build_definitions(ir.blocks)
+
+ sig = Signature(return_type, folded_args, None)
+ # this stores a load of info for the cost model function if supplied
+ # it by default is None
+ self._inline_overloads[sig.args] = {'folded_args': folded_args}
+ # this stores the compiled overloads, if there's no compiled
+ # overload available i.e. function is always inlined, the key still
+ # needs to exist for type resolution
+
+ # NOTE: If lowering is failing on a `_EmptyImplementationEntry`,
+ # the inliner has failed to inline this entry correctly.
+ impl_init = _EmptyImplementationEntry('always inlined')
+ self._compiled_overloads[sig.args] = impl_init
+ if not self._inline.is_always_inline:
+ # this branch is here because a user has supplied a function to
+ # determine whether to inline or not. As a result both compiled
+ # function and inliner info needed, delaying the computation of
+ # this leads to an internal state mess at present. TODO: Fix!
+ sig = disp_type.get_call_type(self.context, new_args, kws)
+ self._compiled_overloads[sig.args] = disp_type.get_overload(sig)
+ # store the inliner information, it's used later in the cost
+ # model function call
+ iinfo = _inline_info(ir, typemap, calltypes, sig)
+ self._inline_overloads[sig.args] = {'folded_args': folded_args,
+ 'iinfo': iinfo}
+ else:
+ sig = disp_type.get_call_type(self.context, new_args, kws)
+ if sig is None: # can't resolve for this target
+ return None
+ self._compiled_overloads[sig.args] = disp_type.get_overload(sig)
+ return sig
+
+ def _get_impl(self, args, kws):
+ """Get implementation given the argument types.
+
+ Returning a Dispatcher object. The Dispatcher object is cached
+ internally in `self._impl_cache`.
+ """
+ flags = targetconfig.ConfigStack.top_or_none()
+ cache_key = self.context, tuple(args), tuple(kws.items()), flags
+ try:
+ impl, args = self._impl_cache[cache_key]
+ return impl, args
+ except KeyError:
+ # pass and try outside the scope so as to not have KeyError with a
+ # nested addition error in the case the _build_impl fails
+ pass
+ impl, args = self._build_impl(cache_key, args, kws)
+ return impl, args
+
+ def _get_jit_decorator(self):
+ """Gets a jit decorator suitable for the current target"""
+
+ from numba.core.target_extension import (target_registry,
+ get_local_target,
+ jit_registry)
+
+ jitter_str = self.metadata.get('target', 'generic')
+ jitter = jit_registry.get(jitter_str, None)
+
+ if jitter is None:
+ # No JIT known for target string, see if something is
+ # registered for the string and report if not.
+ target_class = target_registry.get(jitter_str, None)
+ if target_class is None:
+ msg = ("Unknown target '{}', has it been ",
+ "registered?")
+ raise ValueError(msg.format(jitter_str))
+
+ target_hw = get_local_target(self.context)
+
+ # check that the requested target is in the hierarchy for the
+ # current frame's target.
+ if not issubclass(target_hw, target_class):
+ msg = "No overloads exist for the requested target: {}."
+
+ jitter = jit_registry[target_hw]
+
+ if jitter is None:
+ raise ValueError("Cannot find a suitable jit decorator")
+
+ return jitter
+
+ def _build_impl(self, cache_key, args, kws):
+ """Build and cache the implementation.
+
+ Given the positional (`args`) and keyword arguments (`kws`), obtains
+ the `overload` implementation and wrap it in a Dispatcher object.
+ The expected argument types are returned for use by type-inference.
+ The expected argument types are only different from the given argument
+ types if there is an imprecise type in the given argument types.
+
+ Parameters
+ ----------
+ cache_key : hashable
+ The key used for caching the implementation.
+ args : Tuple[Type]
+ Types of positional argument.
+ kws : Dict[Type]
+ Types of keyword argument.
+
+ Returns
+ -------
+ disp, args :
+ On success, returns `(Dispatcher, Tuple[Type])`.
+ On failure, returns `(None, None)`.
+
+ """
+ jitter = self._get_jit_decorator()
+
+ # Get the overload implementation for the given types
+ ov_sig = inspect.signature(self._overload_func)
+ try:
+ ov_sig.bind(*args, **kws)
+ except TypeError as e:
+ # bind failed, raise, if there's a
+ # ValueError then there's likely unrecoverable
+ # problems
+ raise TypingError(str(e)) from e
+ else:
+ ovf_result = self._overload_func(*args, **kws)
+
+ if ovf_result is None:
+ # No implementation => fail typing
+ self._impl_cache[cache_key] = None, None
+ return None, None
+ elif isinstance(ovf_result, tuple):
+ # The implementation returned a signature that the type-inferencer
+ # should be using.
+ sig, pyfunc = ovf_result
+ args = sig.args
+ kws = {}
+ cache_key = None # don't cache
+ else:
+ # Regular case
+ pyfunc = ovf_result
+
+ # Check type of pyfunc
+ if not isinstance(pyfunc, FunctionType):
+ msg = ("Implementation function returned by `@overload` "
+ "has an unexpected type. Got {}")
+ raise AssertionError(msg.format(pyfunc))
+
+ # check that the typing and impl sigs match up
+ if self._strict:
+ self._validate_sigs(self._overload_func, pyfunc)
+ # Make dispatcher
+ jitdecor = jitter(**self._jit_options)
+ disp = jitdecor(pyfunc)
+ # Make sure that the implementation can be fully compiled
+ disp_type = types.Dispatcher(disp)
+ disp_type.get_call_type(self.context, args, kws)
+ if cache_key is not None:
+ self._impl_cache[cache_key] = disp, args
+ return disp, args
+
+ def get_impl_key(self, sig):
+ """
+ Return the key for looking up the implementation for the given
+ signature on the target context.
+ """
+ return self._compiled_overloads[sig.args]
+
+ @classmethod
+ def get_source_info(cls):
+ """Return a dictionary with information about the source code of the
+ implementation.
+
+ Returns
+ -------
+ info : dict
+ - "kind" : str
+ The implementation kind.
+ - "name" : str
+ The name of the function that provided the definition.
+ - "sig" : str
+ The formatted signature of the function.
+ - "filename" : str
+ The name of the source file.
+ - "lines": tuple (int, int)
+ First and list line number.
+ - "docstring": str
+ The docstring of the definition.
+ """
+ basepath = os.path.dirname(os.path.dirname(numba.__file__))
+ impl = cls._overload_func
+ code, firstlineno, path = cls.get_source_code_info(impl)
+ sig = str(utils.pysignature(impl))
+ info = {
+ 'kind': "overload",
+ 'name': getattr(impl, '__qualname__', impl.__name__),
+ 'sig': sig,
+ 'filename': utils.safe_relpath(path, start=basepath),
+ 'lines': (firstlineno, firstlineno + len(code) - 1),
+ 'docstring': impl.__doc__
+ }
+ return info
+
+ def get_template_info(self):
+ basepath = os.path.dirname(os.path.dirname(numba.__file__))
+ impl = self._overload_func
+ code, firstlineno, path = self.get_source_code_info(impl)
+ sig = str(utils.pysignature(impl))
+ info = {
+ 'kind': "overload",
+ 'name': getattr(impl, '__qualname__', impl.__name__),
+ 'sig': sig,
+ 'filename': utils.safe_relpath(path, start=basepath),
+ 'lines': (firstlineno, firstlineno + len(code) - 1),
+ 'docstring': impl.__doc__
+ }
+ return info
+
+
+def make_overload_template(func, overload_func, jit_options, strict,
+ inline, prefer_literal=False, **kwargs):
+ """
+ Make a template class for function *func* overloaded by *overload_func*.
+ Compiler options are passed as a dictionary to *jit_options*.
+ """
+ func_name = getattr(func, '__name__', str(func))
+ name = "OverloadTemplate_%s" % (func_name,)
+ base = _OverloadFunctionTemplate
+ dct = dict(key=func, _overload_func=staticmethod(overload_func),
+ _impl_cache={}, _compiled_overloads={}, _jit_options=jit_options,
+ _strict=strict, _inline=staticmethod(InlineOptions(inline)),
+ _inline_overloads={}, prefer_literal=prefer_literal,
+ metadata=kwargs)
+ return type(base)(name, (base,), dct)
+
+
+class _TemplateTargetHelperMixin(object):
+ """Mixin for helper methods that assist with target/registry resolution"""
+
+ def _get_target_registry(self, reason):
+ """Returns the registry for the current target.
+
+ Parameters
+ ----------
+ reason: str
+ Reason for the resolution. Expects a noun.
+ Returns
+ -------
+ reg : a registry suitable for the current target.
+ """
+ from numba.core.target_extension import (_get_local_target_checked,
+ dispatcher_registry)
+ hwstr = self.metadata.get('target', 'generic')
+ target_hw = _get_local_target_checked(self.context, hwstr, reason)
+ # Get registry for the current hardware
+ disp = dispatcher_registry[target_hw]
+ tgtctx = disp.targetdescr.target_context
+ # This is all workarounds...
+ # The issue is that whilst targets shouldn't care about which registry
+ # in which to register lowering implementations, the CUDA target
+ # "borrows" implementations from the CPU from specific registries. This
+ # means that if some impl is defined via @intrinsic, e.g. numba.*unsafe
+ # modules, _AND_ CUDA also makes use of the same impl, then it's
+ # required that the registry in use is one that CUDA borrows from. This
+ # leads to the following expression where by the CPU builtin_registry is
+ # used if it is in the target context as a known registry (i.e. the
+ # target installed it) and if it is not then it is assumed that the
+ # registries for the target are unbound to any other target and so it's
+ # fine to use any of them as a place to put lowering impls.
+ #
+ # NOTE: This will need subsequently fixing again when targets use solely
+ # the extension APIs to describe their implementation. The issue will be
+ # that the builtin_registry should contain _just_ the stack allocated
+ # implementations and low level target invariant things and should not
+ # be modified further. It should be acceptable to remove the `then`
+ # branch and just keep the `else`.
+
+ # In case the target has swapped, e.g. cuda borrowing cpu, refresh to
+ # populate.
+ tgtctx.refresh()
+ if builtin_registry in tgtctx._registries:
+ reg = builtin_registry
+ else:
+ # Pick a registry in which to install intrinsics
+ registries = iter(tgtctx._registries)
+ reg = next(registries)
+ return reg
+
+
+class _IntrinsicTemplate(_TemplateTargetHelperMixin, AbstractTemplate):
+ """
+ A base class of templates for intrinsic definition
+ """
+
+ def generic(self, args, kws):
+ """
+ Type the intrinsic by the arguments.
+ """
+ lower_builtin = self._get_target_registry('intrinsic').lower
+ cache_key = self.context, args, tuple(kws.items())
+ try:
+ return self._impl_cache[cache_key]
+ except KeyError:
+ pass
+ result = self._definition_func(self.context, *args, **kws)
+ if result is None:
+ return
+ [sig, imp] = result
+ pysig = utils.pysignature(self._definition_func)
+ # omit context argument from user function
+ parameters = list(pysig.parameters.values())[1:]
+ sig = sig.replace(pysig=pysig.replace(parameters=parameters))
+ self._impl_cache[cache_key] = sig
+ self._overload_cache[sig.args] = imp
+ # register the lowering
+ lower_builtin(imp, *sig.args)(imp)
+ return sig
+
+ def get_impl_key(self, sig):
+ """
+ Return the key for looking up the implementation for the given
+ signature on the target context.
+ """
+ return self._overload_cache[sig.args]
+
+ def get_template_info(self):
+ basepath = os.path.dirname(os.path.dirname(numba.__file__))
+ impl = self._definition_func
+ code, firstlineno, path = self.get_source_code_info(impl)
+ sig = str(utils.pysignature(impl))
+ info = {
+ 'kind': "intrinsic",
+ 'name': getattr(impl, '__qualname__', impl.__name__),
+ 'sig': sig,
+ 'filename': utils.safe_relpath(path, start=basepath),
+ 'lines': (firstlineno, firstlineno + len(code) - 1),
+ 'docstring': impl.__doc__
+ }
+ return info
+
+
+def make_intrinsic_template(handle, defn, name, *, prefer_literal=False,
+ kwargs=None):
+ """
+ Make a template class for a intrinsic handle *handle* defined by the
+ function *defn*. The *name* is used for naming the new template class.
+ """
+ kwargs = MappingProxyType({} if kwargs is None else kwargs)
+ base = _IntrinsicTemplate
+ name = "_IntrinsicTemplate_%s" % (name)
+ dct = dict(key=handle, _definition_func=staticmethod(defn),
+ _impl_cache={}, _overload_cache={},
+ prefer_literal=prefer_literal, metadata=kwargs)
+ return type(base)(name, (base,), dct)
+
+
+class AttributeTemplate(object):
+ def __init__(self, context):
+ self.context = context
+
+ def resolve(self, value, attr):
+ return self._resolve(value, attr)
+
+ def _resolve(self, value, attr):
+ fn = getattr(self, "resolve_%s" % attr, None)
+ if fn is None:
+ fn = self.generic_resolve
+ if fn is NotImplemented:
+ if isinstance(value, types.Module):
+ return self.context.resolve_module_constants(value, attr)
+ else:
+ return None
+ else:
+ return fn(value, attr)
+ else:
+ return fn(value)
+
+ generic_resolve = NotImplemented
+
+
+class _OverloadAttributeTemplate(_TemplateTargetHelperMixin, AttributeTemplate):
+ """
+ A base class of templates for @overload_attribute functions.
+ """
+ is_method = False
+
+ def __init__(self, context):
+ super(_OverloadAttributeTemplate, self).__init__(context)
+ self.context = context
+ self._init_once()
+
+ def _init_once(self):
+ cls = type(self)
+ attr = cls._attr
+
+ lower_getattr = self._get_target_registry('attribute').lower_getattr
+
+ @lower_getattr(cls.key, attr)
+ def getattr_impl(context, builder, typ, value):
+ typingctx = context.typing_context
+ fnty = cls._get_function_type(typingctx, typ)
+ sig = cls._get_signature(typingctx, fnty, (typ,), {})
+ call = context.get_function(fnty, sig)
+ return call(builder, (value,))
+
+ def _resolve(self, typ, attr):
+ if self._attr != attr:
+ return None
+ fnty = self._get_function_type(self.context, typ)
+ sig = self._get_signature(self.context, fnty, (typ,), {})
+ # There should only be one template
+ for template in fnty.templates:
+ self._inline_overloads.update(template._inline_overloads)
+ return sig.return_type
+
+ @classmethod
+ def _get_signature(cls, typingctx, fnty, args, kws):
+ sig = fnty.get_call_type(typingctx, args, kws)
+ sig = sig.replace(pysig=utils.pysignature(cls._overload_func))
+ return sig
+
+ @classmethod
+ def _get_function_type(cls, typingctx, typ):
+ return typingctx.resolve_value_type(cls._overload_func)
+
+
+class _OverloadMethodTemplate(_OverloadAttributeTemplate):
+ """
+ A base class of templates for @overload_method functions.
+ """
+ is_method = True
+
+ def _init_once(self):
+ """
+ Overriding parent definition
+ """
+ attr = self._attr
+
+ registry = self._get_target_registry('method')
+
+ @registry.lower((self.key, attr), self.key, types.VarArg(types.Any))
+ def method_impl(context, builder, sig, args):
+ typ = sig.args[0]
+ typing_context = context.typing_context
+ fnty = self._get_function_type(typing_context, typ)
+ sig = self._get_signature(typing_context, fnty, sig.args, {})
+ call = context.get_function(fnty, sig)
+ # Link dependent library
+ context.add_linking_libs(getattr(call, 'libs', ()))
+ return call(builder, args)
+
+ def _resolve(self, typ, attr):
+ if self._attr != attr:
+ return None
+
+ if isinstance(typ, types.TypeRef):
+ assert typ == self.key
+ elif isinstance(typ, types.Callable):
+ assert typ == self.key
+ else:
+ assert isinstance(typ, self.key)
+
+ class MethodTemplate(AbstractTemplate):
+ key = (self.key, attr)
+ _inline = self._inline
+ _overload_func = staticmethod(self._overload_func)
+ _inline_overloads = self._inline_overloads
+ prefer_literal = self.prefer_literal
+
+ def generic(_, args, kws):
+ args = (typ,) + tuple(args)
+ fnty = self._get_function_type(self.context, typ)
+ sig = self._get_signature(self.context, fnty, args, kws)
+ sig = sig.replace(pysig=utils.pysignature(self._overload_func))
+ for template in fnty.templates:
+ self._inline_overloads.update(template._inline_overloads)
+ if sig is not None:
+ return sig.as_method()
+
+ def get_template_info(self):
+ basepath = os.path.dirname(os.path.dirname(numba.__file__))
+ impl = self._overload_func
+ code, firstlineno, path = self.get_source_code_info(impl)
+ sig = str(utils.pysignature(impl))
+ info = {
+ 'kind': "overload_method",
+ 'name': getattr(impl, '__qualname__', impl.__name__),
+ 'sig': sig,
+ 'filename': utils.safe_relpath(path, start=basepath),
+ 'lines': (firstlineno, firstlineno + len(code) - 1),
+ 'docstring': impl.__doc__
+ }
+
+ return info
+
+ return types.BoundFunction(MethodTemplate, typ)
+
+
+def make_overload_attribute_template(typ, attr, overload_func, inline='never',
+ prefer_literal=False,
+ base=_OverloadAttributeTemplate,
+ **kwargs):
+ """
+ Make a template class for attribute *attr* of *typ* overloaded by
+ *overload_func*.
+ """
+ assert isinstance(typ, types.Type) or issubclass(typ, types.Type)
+ name = "OverloadAttributeTemplate_%s_%s" % (typ, attr)
+ # Note the implementation cache is subclass-specific
+ dct = dict(key=typ, _attr=attr, _impl_cache={},
+ _inline=staticmethod(InlineOptions(inline)),
+ _inline_overloads={},
+ _overload_func=staticmethod(overload_func),
+ prefer_literal=prefer_literal,
+ metadata=kwargs,
+ )
+ obj = type(base)(name, (base,), dct)
+ return obj
+
+
+def make_overload_method_template(typ, attr, overload_func, inline,
+ prefer_literal=False, **kwargs):
+ """
+ Make a template class for method *attr* of *typ* overloaded by
+ *overload_func*.
+ """
+ return make_overload_attribute_template(
+ typ, attr, overload_func, inline=inline,
+ base=_OverloadMethodTemplate, prefer_literal=prefer_literal,
+ **kwargs,
+ )
+
+
+def bound_function(template_key):
+ """
+ Wrap an AttributeTemplate resolve_* method to allow it to
+ resolve an instance method's signature rather than a instance attribute.
+ The wrapped method must return the resolved method's signature
+ according to the given self type, args, and keywords.
+
+ It is used thusly:
+
+ class ComplexAttributes(AttributeTemplate):
+ @bound_function("complex.conjugate")
+ def resolve_conjugate(self, ty, args, kwds):
+ return ty
+
+ *template_key* (e.g. "complex.conjugate" above) will be used by the
+ target to look up the method's implementation, as a regular function.
+ """
+ def wrapper(method_resolver):
+ @functools.wraps(method_resolver)
+ def attribute_resolver(self, ty):
+ class MethodTemplate(AbstractTemplate):
+ key = template_key
+
+ def generic(_, args, kws):
+ sig = method_resolver(self, ty, args, kws)
+ if sig is not None and sig.recvr is None:
+ sig = sig.replace(recvr=ty)
+ return sig
+
+ return types.BoundFunction(MethodTemplate, ty)
+ return attribute_resolver
+ return wrapper
+
+
+# -----------------------------
+
+class Registry(object):
+ """
+ A registry of typing declarations. The registry stores such declarations
+ for functions, attributes and globals.
+ """
+
+ def __init__(self):
+ self.functions = []
+ self.attributes = []
+ self.globals = []
+
+ def register(self, item):
+ assert issubclass(item, FunctionTemplate)
+ self.functions.append(item)
+ return item
+
+ def register_attr(self, item):
+ assert issubclass(item, AttributeTemplate)
+ self.attributes.append(item)
+ return item
+
+ def register_global(self, val=None, typ=None, **kwargs):
+ """
+ Register the typing of a global value.
+ Functional usage with a Numba type::
+ register_global(value, typ)
+
+ Decorator usage with a template class::
+ @register_global(value, typing_key=None)
+ class Template:
+ ...
+ """
+ if typ is not None:
+ # register_global(val, typ)
+ assert val is not None
+ assert not kwargs
+ self.globals.append((val, typ))
+ else:
+ def decorate(cls, typing_key):
+ class Template(cls):
+ key = typing_key
+ if callable(val):
+ typ = types.Function(Template)
+ else:
+ raise TypeError("cannot infer type for global value %r")
+ self.globals.append((val, typ))
+ return cls
+
+ # register_global(val, typing_key=None)()
+ assert val is not None
+ typing_key = kwargs.pop('typing_key', val)
+ assert not kwargs
+ if typing_key is val:
+ # Check the value is globally reachable, as it is going
+ # to be used as the key.
+ mod = sys.modules[val.__module__]
+ if getattr(mod, val.__name__) is not val:
+ raise ValueError("%r is not globally reachable as '%s.%s'"
+ % (mod, val.__module__, val.__name__))
+
+ def decorator(cls):
+ return decorate(cls, typing_key)
+ return decorator
+
+
+class BaseRegistryLoader(object):
+ """
+ An incremental loader for a registry. Each new call to
+ new_registrations() will iterate over the not yet seen registrations.
+
+ The reason for this object is multiple:
+ - there can be several contexts
+ - each context wants to install all registrations
+ - registrations can be added after the first installation, so contexts
+ must be able to get the "new" installations
+
+ Therefore each context maintains its own loaders for each existing
+ registry, without duplicating the registries themselves.
+ """
+
+ def __init__(self, registry):
+ self._registrations = dict(
+ (name, utils.stream_list(getattr(registry, name)))
+ for name in self.registry_items)
+
+ def new_registrations(self, name):
+ for item in next(self._registrations[name]):
+ yield item
+
+
+class RegistryLoader(BaseRegistryLoader):
+ """
+ An incremental loader for a typing registry.
+ """
+ registry_items = ('functions', 'attributes', 'globals')
+
+
+builtin_registry = Registry()
+infer = builtin_registry.register
+infer_getattr = builtin_registry.register_attr
+infer_global = builtin_registry.register_global
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/typeof.py b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/typeof.py
new file mode 100644
index 0000000000000000000000000000000000000000..48e4fb1a9bdc67e6a0c44bd13fcb5b29d5e60a54
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/core/typing/typeof.py
@@ -0,0 +1,312 @@
+from collections import namedtuple
+from functools import singledispatch
+import ctypes
+import enum
+
+import numpy as np
+from numpy.random.bit_generator import BitGenerator
+
+from numba.core import types, utils, errors, config
+from numba.np import numpy_support
+
+
+# terminal color markup
+_termcolor = errors.termcolor()
+
+
+class Purpose(enum.Enum):
+ # Value being typed is used as an argument
+ argument = 1
+ # Value being typed is used as a constant
+ constant = 2
+
+
+_TypeofContext = namedtuple("_TypeofContext", ("purpose",))
+
+
+def typeof(val, purpose=Purpose.argument):
+ """
+ Get the Numba type of a Python value for the given purpose.
+ """
+ # Note the behaviour for Purpose.argument must match _typeof.c.
+ c = _TypeofContext(purpose)
+ ty = typeof_impl(val, c)
+ if ty is None:
+ msg = _termcolor.errmsg(
+ f"Cannot determine Numba type of {type(val)}")
+ raise ValueError(msg)
+ return ty
+
+
+@singledispatch
+def typeof_impl(val, c):
+ """
+ Generic typeof() implementation.
+ """
+ tp = _typeof_buffer(val, c)
+ if tp is not None:
+ return tp
+
+ tp = getattr(val, "_numba_type_", None)
+ if tp is not None:
+ return tp
+
+ # cffi is handled here as it does not expose a public base class
+ # for exported functions or CompiledFFI instances.
+ from numba.core.typing import cffi_utils
+ if cffi_utils.SUPPORTED:
+ if cffi_utils.is_cffi_func(val):
+ return cffi_utils.make_function_type(val)
+ if cffi_utils.is_ffi_instance(val):
+ return types.ffi
+
+ return None
+
+
+def _typeof_buffer(val, c):
+ from numba.core.typing import bufproto
+ try:
+ m = memoryview(val)
+ except TypeError:
+ return
+ # Object has the buffer protocol
+ try:
+ dtype = bufproto.decode_pep3118_format(m.format, m.itemsize)
+ except ValueError:
+ return
+ type_class = bufproto.get_type_class(type(val))
+ layout = bufproto.infer_layout(m)
+ return type_class(dtype, m.ndim, layout=layout,
+ readonly=m.readonly)
+
+
+@typeof_impl.register(ctypes._CFuncPtr)
+def _typeof_ctypes_function(val, c):
+ from .ctypes_utils import is_ctypes_funcptr, make_function_type
+ if is_ctypes_funcptr(val):
+ return make_function_type(val)
+
+
+@typeof_impl.register(type)
+def _typeof_type(val, c):
+ """
+ Type various specific Python types.
+ """
+ if issubclass(val, BaseException):
+ return types.ExceptionClass(val)
+ if issubclass(val, tuple) and hasattr(val, "_asdict"):
+ return types.NamedTupleClass(val)
+
+ if issubclass(val, np.generic):
+ return types.NumberClass(numpy_support.from_dtype(val))
+
+ if issubclass(val, types.Type):
+ return types.TypeRef(val)
+
+ from numba.typed import Dict
+ if issubclass(val, Dict):
+ return types.TypeRef(types.DictType)
+
+ from numba.typed import List
+ if issubclass(val, List):
+ return types.TypeRef(types.ListType)
+
+
+if config.USE_LEGACY_TYPE_SYSTEM:
+ @typeof_impl.register(bool)
+ def _typeof_bool(val, c):
+ return types.boolean
+
+ @typeof_impl.register(float)
+ def _typeof_float(val, c):
+ return types.float64
+
+ @typeof_impl.register(complex)
+ def _typeof_complex(val, c):
+ return types.complex128
+
+ @typeof_impl.register(int)
+ def _typeof_int(val, c):
+ # As in _typeof.c
+ nbits = utils.bit_length(val)
+ if nbits < 32:
+ typ = types.intp
+ elif nbits < 64:
+ typ = types.int64
+ elif nbits == 64 and val >= 0:
+ typ = types.uint64
+ else:
+ raise ValueError("Int value is too large: %s" % val)
+ return typ
+else:
+ @typeof_impl.register(bool)
+ def _typeof_bool(val, c):
+ return types.py_bool
+
+ @typeof_impl.register(float)
+ def _typeof_float(val, c):
+ return types.py_float
+
+ @typeof_impl.register(complex)
+ def _typeof_complex(val, c):
+ return types.py_complex
+
+ @typeof_impl.register(int)
+ def _typeof_int(val, c):
+ # As in _typeof.c
+ typ = types.py_int
+ return typ
+
+
+@typeof_impl.register(np.generic)
+def _typeof_numpy_scalar(val, c):
+ try:
+ return numpy_support.map_arrayscalar_type(val)
+ except errors.NumbaNotImplementedError:
+ pass
+ except NotImplementedError:
+ pass
+
+
+@typeof_impl.register(str)
+def _typeof_str(val, c):
+ return types.string
+
+
+@typeof_impl.register(type((lambda a: a).__code__))
+def _typeof_code(val, c):
+ return types.code_type
+
+
+@typeof_impl.register(type(None))
+def _typeof_none(val, c):
+ return types.none
+
+
+@typeof_impl.register(type(Ellipsis))
+def _typeof_ellipsis(val, c):
+ return types.ellipsis
+
+
+@typeof_impl.register(tuple)
+def _typeof_tuple(val, c):
+ tys = [typeof_impl(v, c) for v in val]
+ if any(ty is None for ty in tys):
+ return
+ return types.BaseTuple.from_types(tys, type(val))
+
+
+@typeof_impl.register(list)
+def _typeof_list(val, c):
+ if len(val) == 0:
+ raise ValueError("Cannot type empty list")
+ ty = typeof_impl(val[0], c)
+ if ty is None:
+ raise ValueError(
+ f"Cannot type list element type {type(val[0])}")
+ return types.List(ty, reflected=True)
+
+
+@typeof_impl.register(set)
+def _typeof_set(val, c):
+ if len(val) == 0:
+ raise ValueError("Cannot type empty set")
+ item = next(iter(val))
+ ty = typeof_impl(item, c)
+ if ty is None:
+ raise ValueError(
+ f"Cannot type set element type {type(item)}")
+ return types.Set(ty, reflected=True)
+
+
+@typeof_impl.register(slice)
+def _typeof_slice(val, c):
+ return types.slice2_type if val.step in (None, 1) else types.slice3_type
+
+
+@typeof_impl.register(enum.Enum)
+@typeof_impl.register(enum.IntEnum)
+def _typeof_enum(val, c):
+ clsty = typeof_impl(type(val), c)
+ return clsty.member_type
+
+
+@typeof_impl.register(enum.EnumMeta)
+def _typeof_enum_class(val, c):
+ cls = val
+ members = list(cls.__members__.values())
+ if len(members) == 0:
+ raise ValueError("Cannot type enum with no members")
+ dtypes = {typeof_impl(mem.value, c) for mem in members}
+ if len(dtypes) > 1:
+ raise ValueError("Cannot type heterogeneous enum: "
+ "got value types %s"
+ % ", ".join(sorted(str(ty) for ty in dtypes)))
+ if issubclass(val, enum.IntEnum):
+ typecls = types.IntEnumClass
+ else:
+ typecls = types.EnumClass
+ return typecls(cls, dtypes.pop())
+
+
+@typeof_impl.register(np.dtype)
+def _typeof_dtype(val, c):
+ tp = numpy_support.from_dtype(val)
+ return types.DType(tp)
+
+
+@typeof_impl.register(np.ndarray)
+def _typeof_ndarray(val, c):
+ if isinstance(val, np.ma.MaskedArray):
+ msg = "Unsupported array type: numpy.ma.MaskedArray."
+ raise errors.NumbaTypeError(msg)
+ try:
+ dtype = numpy_support.from_dtype(val.dtype)
+ except errors.NumbaNotImplementedError:
+ raise errors.NumbaValueError(f"Unsupported array dtype: {val.dtype}")
+ layout = numpy_support.map_layout(val)
+ readonly = not val.flags.writeable
+ return types.Array(dtype, val.ndim, layout, readonly=readonly)
+
+
+@typeof_impl.register(types.NumberClass)
+def _typeof_number_class(val, c):
+ return val
+
+
+@typeof_impl.register(types.Literal)
+def _typeof_literal(val, c):
+ return val
+
+
+@typeof_impl.register(types.TypeRef)
+def _typeof_typeref(val, c):
+ return val
+
+
+@typeof_impl.register(types.Type)
+def _typeof_nb_type(val, c):
+ if isinstance(val, types.BaseFunction):
+ return val
+ elif isinstance(val, (types.Number, types.Boolean)):
+ return types.NumberClass(val)
+ else:
+ return types.TypeRef(val)
+
+
+@typeof_impl.register(BitGenerator)
+def typeof_numpy_random_bitgen(val, c):
+ return types.NumPyRandomBitGeneratorType(val)
+
+
+@typeof_impl.register(np.random.Generator)
+def typeof_random_generator(val, c):
+ return types.NumPyRandomGeneratorType(val)
+
+
+@typeof_impl.register(np.polynomial.polynomial.Polynomial)
+def typeof_numpy_polynomial(val, c):
+ coef = typeof(val.coef)
+ domain = typeof(val.domain)
+ window = typeof(val.window)
+ return types.PolynomialType(coef, domain, window)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/unsafe/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/numba/core/unsafe/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/unsafe/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/unsafe/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..06da1d1659c7c8eb48af7024cc405a0b9d72f87f
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/unsafe/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/unsafe/__pycache__/bytes.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/unsafe/__pycache__/bytes.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..73145a445158d24081d40549e54872f5fd85d2ef
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/unsafe/__pycache__/bytes.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/unsafe/__pycache__/eh.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/unsafe/__pycache__/eh.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..db4fe1c14db57a676f62f9fb8743765799abe533
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/unsafe/__pycache__/eh.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/unsafe/__pycache__/nrt.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/unsafe/__pycache__/nrt.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7ef209cecb1e6de7b7cd80b09315e7e82f0f8e3a
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/unsafe/__pycache__/nrt.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/unsafe/__pycache__/refcount.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/core/unsafe/__pycache__/refcount.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fec4f15c0ce26f6b210fc0e1e2b75065d05e46ae
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/core/unsafe/__pycache__/refcount.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/unsafe/bytes.py b/tool_server/.venv/lib/python3.12/site-packages/numba/core/unsafe/bytes.py
new file mode 100644
index 0000000000000000000000000000000000000000..3c99be1bd553f3f73a72b54c839af1ef6ecacfb5
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/core/unsafe/bytes.py
@@ -0,0 +1,49 @@
+"""
+This file provides internal compiler utilities that support certain special
+operations with bytes and workarounds for limitations enforced in userland.
+"""
+
+from numba.core.extending import intrinsic
+from llvmlite import ir
+from numba.core import types, cgutils
+
+
+@intrinsic
+def grab_byte(typingctx, data, offset):
+ # returns a byte at a given offset in data
+ def impl(context, builder, signature, args):
+ data, idx = args
+ ptr = builder.bitcast(data, ir.IntType(8).as_pointer())
+ ch = builder.load(builder.gep(ptr, [idx]))
+ return ch
+
+ sig = types.uint8(types.voidptr, types.intp)
+ return sig, impl
+
+
+@intrinsic
+def grab_uint64_t(typingctx, data, offset):
+ # returns a uint64_t at a given offset in data
+ def impl(context, builder, signature, args):
+ data, idx = args
+ ptr = builder.bitcast(data, ir.IntType(64).as_pointer())
+ ch = builder.load(builder.gep(ptr, [idx]))
+ return ch
+ sig = types.uint64(types.voidptr, types.intp)
+ return sig, impl
+
+
+@intrinsic
+def memcpy_region(typingctx, dst, dst_offset, src, src_offset, nbytes, align):
+ '''Copy nbytes from *(src + src_offset) to *(dst + dst_offset)'''
+ def codegen(context, builder, signature, args):
+ [dst_val, dst_offset_val, src_val, src_offset_val, nbytes_val,
+ align_val] = args
+ src_ptr = builder.gep(src_val, [src_offset_val])
+ dst_ptr = builder.gep(dst_val, [dst_offset_val])
+ cgutils.raw_memcpy(builder, dst_ptr, src_ptr, nbytes_val, align_val)
+ return context.get_dummy_value()
+
+ sig = types.void(types.voidptr, types.intp, types.voidptr, types.intp,
+ types.intp, types.intp)
+ return sig, codegen
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/unsafe/eh.py b/tool_server/.venv/lib/python3.12/site-packages/numba/core/unsafe/eh.py
new file mode 100644
index 0000000000000000000000000000000000000000..56132d50f04c4c8c0fd290b2dd69c0a69ba00329
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/core/unsafe/eh.py
@@ -0,0 +1,62 @@
+"""
+Exception handling intrinsics.
+"""
+
+from numba.core import types, errors, cgutils
+from numba.core.extending import intrinsic
+
+
+@intrinsic
+def exception_check(typingctx):
+ """An intrinsic to check if an exception is raised
+ """
+ def codegen(context, builder, signature, args):
+ nrt = context.nrt
+ return nrt.eh_check(builder)
+
+ restype = types.boolean
+ return restype(), codegen
+
+
+@intrinsic
+def mark_try_block(typingctx):
+ """An intrinsic to mark the start of a *try* block.
+ """
+ def codegen(context, builder, signature, args):
+ nrt = context.nrt
+ nrt.eh_try(builder)
+ return context.get_dummy_value()
+
+ restype = types.none
+ return restype(), codegen
+
+
+@intrinsic
+def end_try_block(typingctx):
+ """An intrinsic to mark the end of a *try* block.
+ """
+ def codegen(context, builder, signature, args):
+ nrt = context.nrt
+ nrt.eh_end_try(builder)
+ return context.get_dummy_value()
+
+ restype = types.none
+ return restype(), codegen
+
+
+@intrinsic
+def exception_match(typingctx, exc_value, exc_class):
+ """Basically do ``isinstance(exc_value, exc_class)`` for exception objects.
+ Used in ``except Exception:`` syntax.
+ """
+ # Check for our limitation
+ if exc_class.exc_class is not Exception:
+ msg = "Exception matching is limited to {}"
+ raise errors.UnsupportedError(msg.format(Exception))
+
+ def codegen(context, builder, signature, args):
+ # Intentionally always True.
+ return cgutils.true_bit
+
+ restype = types.boolean
+ return restype(exc_value, exc_class), codegen
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/unsafe/nrt.py b/tool_server/.venv/lib/python3.12/site-packages/numba/core/unsafe/nrt.py
new file mode 100644
index 0000000000000000000000000000000000000000..673f0130faf69236f3e5fba636221d763811e3c6
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/core/unsafe/nrt.py
@@ -0,0 +1,20 @@
+"""
+Contains unsafe intrinsic that calls NRT C API
+"""
+
+from numba.core import types
+from numba.core.typing import signature
+from numba.core.extending import intrinsic
+
+
+@intrinsic
+def NRT_get_api(tyctx):
+ """NRT_get_api()
+
+ Calls NRT_get_api() from the NRT C API
+ Returns LLVM Type i8* (void pointer)
+ """
+ def codegen(cgctx, builder, sig, args):
+ return cgctx.nrt.get_nrt_api(builder)
+ sig = signature(types.voidptr)
+ return sig, codegen
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/core/unsafe/refcount.py b/tool_server/.venv/lib/python3.12/site-packages/numba/core/unsafe/refcount.py
new file mode 100644
index 0000000000000000000000000000000000000000..3e79314602ea2dea8bfab08940d58fb3d0156930
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/core/unsafe/refcount.py
@@ -0,0 +1,80 @@
+"""
+Helpers to see the refcount information of an object
+"""
+from llvmlite import ir
+
+from numba.core import types, cgutils
+from numba.core.extending import intrinsic
+
+from numba.core.runtime.nrtdynmod import _meminfo_struct_type
+
+
+@intrinsic
+def dump_refcount(typingctx, obj):
+ """Dump the refcount of an object to stdout.
+
+ Returns True if and only if object is reference-counted and NRT is enabled.
+ """
+ def codegen(context, builder, signature, args):
+ [obj] = args
+ [ty] = signature.args
+ # A sequence of (type, meminfo)
+ meminfos = []
+ if context.enable_nrt:
+ tmp_mis = context.nrt.get_meminfos(builder, ty, obj)
+ meminfos.extend(tmp_mis)
+
+ if meminfos:
+ pyapi = context.get_python_api(builder)
+ gil_state = pyapi.gil_ensure()
+ pyapi.print_string("dump refct of {}".format(ty))
+ for ty, mi in meminfos:
+ miptr = builder.bitcast(mi, _meminfo_struct_type.as_pointer())
+ refctptr = cgutils.gep_inbounds(builder, miptr, 0, 0)
+ refct = builder.load(refctptr)
+
+ pyapi.print_string(" | {} refct=".format(ty))
+ # "%zu" is not portable. just truncate refcount to 32-bit.
+ # that's good enough for a debugging util.
+ refct_32bit = builder.trunc(refct, ir.IntType(32))
+ printed = cgutils.snprintf_stackbuffer(
+ builder, 30, "%d [%p]", refct_32bit, miptr
+ )
+ pyapi.sys_write_stdout(printed)
+
+ pyapi.print_string(";\n")
+ pyapi.gil_release(gil_state)
+ return cgutils.true_bit
+ else:
+ return cgutils.false_bit
+
+ sig = types.bool_(obj)
+ return sig, codegen
+
+
+@intrinsic
+def get_refcount(typingctx, obj):
+ """Get the current refcount of an object.
+
+ FIXME: only handles the first object
+ """
+ def codegen(context, builder, signature, args):
+ [obj] = args
+ [ty] = signature.args
+ # A sequence of (type, meminfo)
+ meminfos = []
+ if context.enable_nrt:
+ tmp_mis = context.nrt.get_meminfos(builder, ty, obj)
+ meminfos.extend(tmp_mis)
+ refcounts = []
+ if meminfos:
+ for ty, mi in meminfos:
+ miptr = builder.bitcast(mi, _meminfo_struct_type.as_pointer())
+ refctptr = cgutils.gep_inbounds(builder, miptr, 0, 0)
+ refct = builder.load(refctptr)
+ refct_32bit = builder.trunc(refct, ir.IntType(32))
+ refcounts.append(refct_32bit)
+ return refcounts[0]
+
+ sig = types.int32(obj)
+ return sig, codegen
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..97b572f6d46a2c399e01e984face9b653ba6e944
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/builtins.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/builtins.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4af78292560d8dcfe0d16c91e3c876a89cf944ca
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/builtins.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/charseq.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/charseq.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f61974b09fe36beff511ee15d78c08b40253d5e8
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/charseq.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/cmathimpl.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/cmathimpl.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..decf0ef46e333ee5839ae801f3c0948b98af6ec8
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/cmathimpl.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/enumimpl.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/enumimpl.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a37d1f7fef842e80f49e6d5be458230ff9a108be
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/enumimpl.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/hashing.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/hashing.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c42f54f480dc38d758dea4843d041baa037eff95
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/hashing.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/heapq.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/heapq.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ed8db479a40172c3968946a4538682a1b6ec57c8
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/heapq.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/iterators.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/iterators.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3dc1e1425888fe35307be1bb2595034d64369ac7
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/iterators.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/listobj.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/listobj.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f3bdbe71293e6741241cf59c6d97b714943100bc
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/listobj.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/mathimpl.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/mathimpl.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8d2b753d011f840f99d51b015c55ea3bd7fe730f
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/mathimpl.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/new_builtins.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/new_builtins.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9733d2be435d5dea0e1df9295058d502735e8cd8
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/new_builtins.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/new_hashing.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/new_hashing.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f7c1d12e2f8b96fe9a54b5566bfbb2a402afdda8
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/new_hashing.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/new_mathimpl.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/new_mathimpl.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..702b3136d51e79ca14a53187a4c021780296e44b
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/new_mathimpl.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/new_numbers.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/new_numbers.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..33c0bd6ca6f1fadb8982aaef458ed4b4102579f0
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/new_numbers.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/new_tupleobj.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/new_tupleobj.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..99120d4f64a5ea3193ebde79eb616e880a5f5ff0
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/new_tupleobj.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/numbers.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/numbers.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..531e315ce5fd40ddd17b767809d98e0a8ff60c3c
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/numbers.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/old_builtins.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/old_builtins.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3db008f3279003f365340f0c58b667ca10b11b91
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/old_builtins.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/old_hashing.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/old_hashing.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ccc7372821e648d5e3a88a5dd74d641a63bfad76
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/old_hashing.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/old_mathimpl.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/old_mathimpl.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..da7bbac032e74d9043ef0832c6573d1b8262eb03
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/old_mathimpl.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/old_numbers.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/old_numbers.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..917cb60254959fdb9f390fe0d9ed973882d5fd88
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/old_numbers.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/old_tupleobj.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/old_tupleobj.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..971a0baae90894eba32830c23a4d567318b7ecb5
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/old_tupleobj.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/printimpl.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/printimpl.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0aa061593998cfc48c1951af454feef59db62db5
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/printimpl.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/randomimpl.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/randomimpl.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1a98b7abb25072ed6552357cd7e8885095ea0ee4
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/randomimpl.cpython-312.pyc
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:089ba7ab2886db560fc81baedc8a818c9efacbd2d74f1aa75c1ea529e77acd83
+size 140493
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/rangeobj.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/rangeobj.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ac939c7e2145bc84fd9e70bee30cec49ec2d4a6b
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/rangeobj.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/setobj.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/setobj.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..26ee0a4d0263f77efad0799f65f004a1a6682338
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/setobj.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/slicing.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/slicing.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..687652983cb405b2a15244684f4bdeecb3fbd692
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/slicing.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/tupleobj.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/tupleobj.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..aa3638e27a68251128901c0368ac940a3956a801
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/tupleobj.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/unicode.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/unicode.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..589b2de10ccfb1bc153d1de6952c8d6bee2e56b2
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/unicode.cpython-312.pyc
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:dcca33b82b243b876601d65f8c4bf145fb3fccd572b8b2bb26c2ba9e7fd99042
+size 102972
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/unicode_support.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/unicode_support.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cff5f5edbcb844e02353d133c33a69d0fda2f3ae
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/__pycache__/unicode_support.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/unsafe/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/unsafe/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/unsafe/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/unsafe/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0f5bfa6c61813039ad3997ee868c3264615653fc
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/unsafe/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/unsafe/__pycache__/numbers.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/unsafe/__pycache__/numbers.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9e7957c0c2facf8b775b0f23b40e76bd3d47fae9
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/unsafe/__pycache__/numbers.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/unsafe/__pycache__/tuple.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/unsafe/__pycache__/tuple.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0bf9f193e73b2005afca704252270a0d49ebd9bc
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/unsafe/__pycache__/tuple.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/unsafe/numbers.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/unsafe/numbers.py
new file mode 100644
index 0000000000000000000000000000000000000000..81a9e88c69e5479678364c92270aea00b39acabf
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/unsafe/numbers.py
@@ -0,0 +1,53 @@
+""" This module provides the unsafe things for targets/numbers.py
+"""
+from numba.core import types, errors
+from numba.core.extending import intrinsic
+
+from llvmlite import ir
+
+
+@intrinsic
+def viewer(tyctx, val, viewty):
+ """ Bitcast a scalar 'val' to the given type 'viewty'. """
+ bits = val.bitwidth
+ if isinstance(viewty.dtype, types.Integer):
+ bitcastty = ir.IntType(bits)
+ elif isinstance(viewty.dtype, types.Float):
+ bitcastty = ir.FloatType() if bits == 32 else ir.DoubleType()
+ else:
+ assert 0, "unreachable"
+
+ def codegen(cgctx, builder, typ, args):
+ flt = args[0]
+ return builder.bitcast(flt, bitcastty)
+ retty = viewty.dtype
+ sig = retty(val, viewty)
+ return sig, codegen
+
+
+@intrinsic
+def trailing_zeros(typeingctx, src):
+ """Counts trailing zeros in the binary representation of an integer."""
+ if not isinstance(src, types.Integer):
+ msg = ("trailing_zeros is only defined for integers, but value passed "
+ f"was '{src}'.")
+ raise errors.NumbaTypeError(msg)
+
+ def codegen(context, builder, signature, args):
+ [src] = args
+ return builder.cttz(src, ir.Constant(ir.IntType(1), 0))
+ return src(src), codegen
+
+
+@intrinsic
+def leading_zeros(typeingctx, src):
+ """Counts leading zeros in the binary representation of an integer."""
+ if not isinstance(src, types.Integer):
+ msg = ("leading_zeros is only defined for integers, but value passed "
+ f"was '{src}'.")
+ raise errors.NumbaTypeError(msg)
+
+ def codegen(context, builder, signature, args):
+ [src] = args
+ return builder.ctlz(src, ir.Constant(ir.IntType(1), 0))
+ return src(src), codegen
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/unsafe/tuple.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/unsafe/tuple.py
new file mode 100644
index 0000000000000000000000000000000000000000..ef243fec5c4e187861d38f99235737fb1b7a118d
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cpython/unsafe/tuple.py
@@ -0,0 +1,84 @@
+"""
+This file provides internal compiler utilities that support certain special
+operations with tuple and workarounds for limitations enforced in userland.
+"""
+
+from numba.core import types, typing, errors
+from numba.core.cgutils import alloca_once
+from numba.core.extending import intrinsic
+
+
+@intrinsic
+def tuple_setitem(typingctx, tup, idx, val):
+ """Return a copy of the tuple with item at *idx* replaced with *val*.
+
+ Operation: ``out = tup[:idx] + (val,) + tup[idx + 1:]
+
+ **Warning**
+
+ - No boundchecking.
+ - The dtype of the tuple cannot be changed.
+ *val* is always cast to the existing dtype of the tuple.
+ """
+ def codegen(context, builder, signature, args):
+ tup, idx, val = args
+ stack = alloca_once(builder, tup.type)
+ builder.store(tup, stack)
+ # Unsafe load on unchecked bounds. Poison value maybe returned.
+ offptr = builder.gep(stack, [idx.type(0), idx], inbounds=True)
+ builder.store(val, offptr)
+ return builder.load(stack)
+
+ sig = tup(tup, idx, tup.dtype)
+ return sig, codegen
+
+
+@intrinsic
+def build_full_slice_tuple(tyctx, sz):
+ """Creates a sz-tuple of full slices."""
+ if not isinstance(sz, types.IntegerLiteral):
+ raise errors.RequireLiteralValue(sz)
+
+ size = int(sz.literal_value)
+ tuple_type = types.UniTuple(dtype=types.slice2_type, count=size)
+ sig = tuple_type(sz)
+
+ def codegen(context, builder, signature, args):
+ def impl(length, empty_tuple):
+ out = empty_tuple
+ for i in range(length):
+ out = tuple_setitem(out, i, slice(None, None))
+ return out
+
+ inner_argtypes = [types.intp, tuple_type]
+ inner_sig = typing.signature(tuple_type, *inner_argtypes)
+ ll_idx_type = context.get_value_type(types.intp)
+ # Allocate an empty tuple
+ empty_tuple = context.get_constant_undef(tuple_type)
+ inner_args = [ll_idx_type(size), empty_tuple]
+
+ res = context.compile_internal(builder, impl, inner_sig, inner_args)
+ return res
+
+ return sig, codegen
+
+
+@intrinsic
+def unpack_single_tuple(tyctx, tup):
+ """This exists to handle the situation y = (*x,), the interpreter injects a
+ call to it in the case of a single value unpack. It's not possible at
+ interpreting time to differentiate between an unpack on a variable sized
+ container e.g. list and a fixed one, e.g. tuple. This function handles the
+ situation should it arise.
+ """
+ # See issue #6534
+ if not isinstance(tup, types.BaseTuple):
+ msg = (f"Only tuples are supported when unpacking a single item, "
+ f"got type: {tup}")
+ raise errors.UnsupportedError(msg)
+
+ sig = tup(tup)
+
+ def codegen(context, builder, signature, args):
+ return args[0] # there's only one tuple and it's a simple pass through
+ return sig, codegen
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c4e7ad255555c744daa4afeedc9cddbf358a2194
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/api.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/api.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..686c367f5e55ded603acc417c0e5c85aa3a3a3a7
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/api.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/api_util.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/api_util.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e88ce0e95bf723b0358619c99482895c75e43272
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/api_util.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/args.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/args.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6710451988ca389324b2da54d158002faf9c532b
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/args.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/cg.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/cg.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..efb52c34822139334579e04fb8fd4b0c75a03a90
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/cg.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/codegen.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/codegen.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f9fc052d9515185b62536d17dc2d8687cda58c77
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/codegen.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/compiler.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/compiler.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f80fae36b89d367f6f16bad8a7e6167fa51e7fc3
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/compiler.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/cuda_paths.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/cuda_paths.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f0369be4e7407b9fd8207ecea65b806ce04b7bb7
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/cuda_paths.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/cudadecl.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/cudadecl.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8d3bc058cb5dcbc4724ba81e0d764be3c69f8e45
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/cudadecl.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/cudaimpl.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/cudaimpl.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..76bbdc38a48787b420d3052d93b669458180c7d0
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/cudaimpl.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/cudamath.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/cudamath.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1fa094b7911cdfd798726cc9adc840d853b09dce
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/cudamath.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/decorators.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/decorators.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..77699c81eb32a011668077b69fa46634a067c495
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/decorators.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/descriptor.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/descriptor.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..caf6a8996c7ac679cc0dde56456e92e2651577ef
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/descriptor.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/device_init.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/device_init.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..13c6a2c0c53267365cdfea172c6c2edf30d0c551
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/device_init.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/deviceufunc.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/deviceufunc.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9388201b91b5586bcf0b19b92a4b86c0d04f7da2
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/deviceufunc.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/dispatcher.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/dispatcher.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..85ceb76d4a0912977acf1c07276db0f51621998a
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/dispatcher.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/errors.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/errors.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0f90ba47166ffc6ffcc00dbea364e2b55694e82c
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/errors.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/extending.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/extending.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5c5953185e0595acb4f707a3a70eb7cdadfe3cac
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/extending.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/initialize.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/initialize.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..212521df03c83983c42c9943b6ad2453cd3e287e
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/initialize.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/intrinsic_wrapper.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/intrinsic_wrapper.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..08e1d57df14d8f079d21da8085be060b50fc538d
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/intrinsic_wrapper.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/intrinsics.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/intrinsics.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5367e571575719d884a37f19572b394ca335e27b
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/intrinsics.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/libdevice.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/libdevice.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b6a3d48dbb213f93bd9844d2d3ccb696e9d85306
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/libdevice.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/libdevicedecl.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/libdevicedecl.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1386dab0655e8063f73e819f30cceb9000030265
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/libdevicedecl.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/libdevicefuncs.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/libdevicefuncs.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a87047818af84106749f93f1ece3f7a000af8ec7
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/libdevicefuncs.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/libdeviceimpl.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/libdeviceimpl.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..42f4d10577840ae059ed03d4d66a007ec6b6ba9c
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/libdeviceimpl.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/mathimpl.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/mathimpl.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8307cd71f1dac663f21356ea5196194b2937783a
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/mathimpl.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/models.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/models.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..07c68cd76602605c418661712a7c5a0b47f53315
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/models.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/nvvmutils.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/nvvmutils.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a871453db76f708a4f56321e7a5677071c258c1f
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/nvvmutils.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/printimpl.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/printimpl.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..16831e786a148a27cf54c0f6b26b5653c6bd6b7a
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/printimpl.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/random.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/random.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..74ab664ef3a64466d116812e47a722612af76ab4
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/random.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/simulator_init.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/simulator_init.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9c5fda505675501c69b43b419e2552cbea5cb05e
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/simulator_init.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/stubs.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/stubs.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d9c7f0305feaf27acc45a96458f55ced3d4ac10b
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/stubs.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/target.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/target.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3ccd6fdf65921854a991b5c2804f81a48780a238
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/target.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/testing.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/testing.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c9e6bc9e36fbe5d397cb320f02410ddedfe467d9
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/testing.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/types.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/types.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1d16d6dc0174e502073c72c24a2b23103788d162
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/types.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/ufuncs.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/ufuncs.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3687eb7c49624a02faac2c5ffac01eb9a3bf8331
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/ufuncs.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/vector_types.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/vector_types.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..aa1268db1da8c363180b4984dcb2e5485dfa7fe1
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/vector_types.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/vectorizers.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/vectorizers.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3974602563bc0bac597dfe70e400d8ae2ce66d9d
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/__pycache__/vectorizers.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..33bfca3456659148c7ff4ef81e96ddaa7470b93f
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/__init__.py
@@ -0,0 +1,9 @@
+"""CUDA Driver
+
+- Driver API binding
+- NVVM API binding
+- Device array implementation
+
+"""
+from numba.core import config
+assert not config.ENABLE_CUDASIM, 'Cannot use real driver API with simulator'
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7fe15b315b12f03ff00dc1e4851413e8fa3f2984
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/__pycache__/devicearray.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/__pycache__/devicearray.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9ac14b30d3c8ba91b94bc7e3793422da70a2012d
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/__pycache__/devicearray.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/__pycache__/devices.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/__pycache__/devices.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7f133c997c8c4ce1573e2bf261304cd1a5233aaf
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/__pycache__/devices.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/__pycache__/driver.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/__pycache__/driver.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..34668d4533bd2e2292109aaf4577ad88595db249
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/__pycache__/driver.cpython-312.pyc
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:22405c4d01a532bf92d0012014907cebf2e01ba21244a80761c2b163453f3808
+size 147973
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/__pycache__/drvapi.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/__pycache__/drvapi.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..183eb623818ec81ef670b51a91f053cc9d19dcc5
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/__pycache__/drvapi.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/__pycache__/dummyarray.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/__pycache__/dummyarray.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..285fa2ee46ecad9a73b57d4c6a35b13c85139e60
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/__pycache__/dummyarray.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/__pycache__/enums.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/__pycache__/enums.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3a28241420cde408ba069a522a98768387b7bc02
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/__pycache__/enums.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/__pycache__/error.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/__pycache__/error.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..53d073b3ca0b8b9dd93e06a53ee739f96c730e0f
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/__pycache__/error.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/__pycache__/libs.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/__pycache__/libs.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..28179b7138f31d3c249bd40391d532f5e26ee827
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/__pycache__/libs.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/__pycache__/ndarray.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/__pycache__/ndarray.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..240d6bc752ca863cb2cdf4b94ece5f06fead4d4b
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/__pycache__/ndarray.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/__pycache__/nvrtc.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/__pycache__/nvrtc.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fbc0c5d9d0f9822de00f1b1129fd880a270a0deb
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/__pycache__/nvrtc.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/__pycache__/nvvm.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/__pycache__/nvvm.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..086494621bda3c7d521e8200fe00c12b19676ab5
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/__pycache__/nvvm.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/__pycache__/rtapi.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/__pycache__/rtapi.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0fa67ff36eed424b40e5bf6c4e003281abfe1c83
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/__pycache__/rtapi.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/__pycache__/runtime.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/__pycache__/runtime.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..522af3e9b931cdc610adaf73e24ec45e2d4f3090
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/__pycache__/runtime.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/_extras.cpython-312-x86_64-linux-gnu.so b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/_extras.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..4f2b80b8636681656dca1e30a54d02bdcb6ca12f
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/_extras.cpython-312-x86_64-linux-gnu.so differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/devicearray.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/devicearray.py
new file mode 100644
index 0000000000000000000000000000000000000000..90f407023cf7a914da0140c44b1ca32aa6ed2efd
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/devicearray.py
@@ -0,0 +1,904 @@
+"""
+A CUDA ND Array is recognized by checking the __cuda_memory__ attribute
+on the object. If it exists and evaluate to True, it must define shape,
+strides, dtype and size attributes similar to a NumPy ndarray.
+"""
+
+import math
+import functools
+import operator
+import copy
+from ctypes import c_void_p
+
+import numpy as np
+
+import numba
+from numba import _devicearray
+from numba.cuda.cudadrv import devices, dummyarray
+from numba.cuda.cudadrv import driver as _driver
+from numba.core import types, config
+from numba.np.unsafe.ndarray import to_fixed_tuple
+from numba.np.numpy_support import numpy_version
+from numba.np import numpy_support
+from numba.cuda.api_util import prepare_shape_strides_dtype
+from numba.core.errors import NumbaPerformanceWarning
+from warnings import warn
+
+try:
+ lru_cache = getattr(functools, 'lru_cache')(None)
+except AttributeError:
+ # Python 3.1 or lower
+ def lru_cache(func):
+ return func
+
+
+def is_cuda_ndarray(obj):
+ "Check if an object is a CUDA ndarray"
+ return getattr(obj, '__cuda_ndarray__', False)
+
+
+def verify_cuda_ndarray_interface(obj):
+ "Verify the CUDA ndarray interface for an obj"
+ require_cuda_ndarray(obj)
+
+ def requires_attr(attr, typ):
+ if not hasattr(obj, attr):
+ raise AttributeError(attr)
+ if not isinstance(getattr(obj, attr), typ):
+ raise AttributeError('%s must be of type %s' % (attr, typ))
+
+ requires_attr('shape', tuple)
+ requires_attr('strides', tuple)
+ requires_attr('dtype', np.dtype)
+ requires_attr('size', int)
+
+
+def require_cuda_ndarray(obj):
+ "Raises ValueError is is_cuda_ndarray(obj) evaluates False"
+ if not is_cuda_ndarray(obj):
+ raise ValueError('require an cuda ndarray object')
+
+
+class DeviceNDArrayBase(_devicearray.DeviceArray):
+ """A on GPU NDArray representation
+ """
+ __cuda_memory__ = True
+ __cuda_ndarray__ = True # There must be gpu_data attribute
+
+ def __init__(self, shape, strides, dtype, stream=0, gpu_data=None):
+ """
+ Args
+ ----
+
+ shape
+ array shape.
+ strides
+ array strides.
+ dtype
+ data type as np.dtype coercible object.
+ stream
+ cuda stream.
+ gpu_data
+ user provided device memory for the ndarray data buffer
+ """
+ if isinstance(shape, int):
+ shape = (shape,)
+ if isinstance(strides, int):
+ strides = (strides,)
+ dtype = np.dtype(dtype)
+ self.ndim = len(shape)
+ if len(strides) != self.ndim:
+ raise ValueError('strides not match ndim')
+ self._dummy = dummyarray.Array.from_desc(0, shape, strides,
+ dtype.itemsize)
+ self.shape = tuple(shape)
+ self.strides = tuple(strides)
+ self.dtype = dtype
+ self.size = int(functools.reduce(operator.mul, self.shape, 1))
+ # prepare gpu memory
+ if self.size > 0:
+ if gpu_data is None:
+ self.alloc_size = _driver.memory_size_from_info(
+ self.shape, self.strides, self.dtype.itemsize)
+ gpu_data = devices.get_context().memalloc(self.alloc_size)
+ else:
+ self.alloc_size = _driver.device_memory_size(gpu_data)
+ else:
+ # Make NULL pointer for empty allocation
+ if _driver.USE_NV_BINDING:
+ null = _driver.binding.CUdeviceptr(0)
+ else:
+ null = c_void_p(0)
+ gpu_data = _driver.MemoryPointer(context=devices.get_context(),
+ pointer=null, size=0)
+ self.alloc_size = 0
+
+ self.gpu_data = gpu_data
+ self.stream = stream
+
+ @property
+ def __cuda_array_interface__(self):
+ if _driver.USE_NV_BINDING:
+ if self.device_ctypes_pointer is not None:
+ ptr = int(self.device_ctypes_pointer)
+ else:
+ ptr = 0
+ else:
+ if self.device_ctypes_pointer.value is not None:
+ ptr = self.device_ctypes_pointer.value
+ else:
+ ptr = 0
+
+ return {
+ 'shape': tuple(self.shape),
+ 'strides': None if is_contiguous(self) else tuple(self.strides),
+ 'data': (ptr, False),
+ 'typestr': self.dtype.str,
+ 'stream': int(self.stream) if self.stream != 0 else None,
+ 'version': 3,
+ }
+
+ def bind(self, stream=0):
+ """Bind a CUDA stream to this object so that all subsequent operation
+ on this array defaults to the given stream.
+ """
+ clone = copy.copy(self)
+ clone.stream = stream
+ return clone
+
+ @property
+ def T(self):
+ return self.transpose()
+
+ def transpose(self, axes=None):
+ if axes and tuple(axes) == tuple(range(self.ndim)):
+ return self
+ elif self.ndim != 2:
+ msg = "transposing a non-2D DeviceNDArray isn't supported"
+ raise NotImplementedError(msg)
+ elif axes is not None and set(axes) != set(range(self.ndim)):
+ raise ValueError("invalid axes list %r" % (axes,))
+ else:
+ from numba.cuda.kernels.transpose import transpose
+ return transpose(self)
+
+ def _default_stream(self, stream):
+ return self.stream if not stream else stream
+
+ @property
+ def _numba_type_(self):
+ """
+ Magic attribute expected by Numba to get the numba type that
+ represents this object.
+ """
+ # Typing considerations:
+ #
+ # 1. The preference is to use 'C' or 'F' layout since this enables
+ # hardcoding stride values into compiled kernels, which is more
+ # efficient than storing a passed-in value in a register.
+ #
+ # 2. If an array is both C- and F-contiguous, prefer 'C' layout as it's
+ # the more likely / common case.
+ #
+ # 3. If an array is broadcast then it must be typed as 'A' - using 'C'
+ # or 'F' does not apply for broadcast arrays, because the strides, some
+ # of which will be 0, will not match those hardcoded in for 'C' or 'F'
+ # layouts.
+
+ broadcast = 0 in self.strides
+ if self.flags['C_CONTIGUOUS'] and not broadcast:
+ layout = 'C'
+ elif self.flags['F_CONTIGUOUS'] and not broadcast:
+ layout = 'F'
+ else:
+ layout = 'A'
+
+ dtype = numpy_support.from_dtype(self.dtype)
+ return types.Array(dtype, self.ndim, layout)
+
+ @property
+ def device_ctypes_pointer(self):
+ """Returns the ctypes pointer to the GPU data buffer
+ """
+ if self.gpu_data is None:
+ if _driver.USE_NV_BINDING:
+ return _driver.binding.CUdeviceptr(0)
+ else:
+ return c_void_p(0)
+ else:
+ return self.gpu_data.device_ctypes_pointer
+
+ @devices.require_context
+ def copy_to_device(self, ary, stream=0):
+ """Copy `ary` to `self`.
+
+ If `ary` is a CUDA memory, perform a device-to-device transfer.
+ Otherwise, perform a a host-to-device transfer.
+ """
+ if ary.size == 0:
+ # Nothing to do
+ return
+
+ sentry_contiguous(self)
+ stream = self._default_stream(stream)
+
+ self_core, ary_core = array_core(self), array_core(ary)
+ if _driver.is_device_memory(ary):
+ sentry_contiguous(ary)
+ check_array_compatibility(self_core, ary_core)
+ _driver.device_to_device(self, ary, self.alloc_size, stream=stream)
+ else:
+ # Ensure same contiguity. Only makes a host-side copy if necessary
+ # (i.e., in order to materialize a writable strided view)
+ ary_core = np.array(
+ ary_core,
+ order='C' if self_core.flags['C_CONTIGUOUS'] else 'F',
+ subok=True,
+ copy=(not ary_core.flags['WRITEABLE'])
+ if numpy_version < (2, 0) else None)
+ check_array_compatibility(self_core, ary_core)
+ _driver.host_to_device(self, ary_core, self.alloc_size,
+ stream=stream)
+
+ @devices.require_context
+ def copy_to_host(self, ary=None, stream=0):
+ """Copy ``self`` to ``ary`` or create a new Numpy ndarray
+ if ``ary`` is ``None``.
+
+ If a CUDA ``stream`` is given, then the transfer will be made
+ asynchronously as part as the given stream. Otherwise, the transfer is
+ synchronous: the function returns after the copy is finished.
+
+ Always returns the host array.
+
+ Example::
+
+ import numpy as np
+ from numba import cuda
+
+ arr = np.arange(1000)
+ d_arr = cuda.to_device(arr)
+
+ my_kernel[100, 100](d_arr)
+
+ result_array = d_arr.copy_to_host()
+ """
+ if any(s < 0 for s in self.strides):
+ msg = 'D->H copy not implemented for negative strides: {}'
+ raise NotImplementedError(msg.format(self.strides))
+ assert self.alloc_size >= 0, "Negative memory size"
+ stream = self._default_stream(stream)
+ if ary is None:
+ hostary = np.empty(shape=self.alloc_size, dtype=np.byte)
+ else:
+ check_array_compatibility(self, ary)
+ hostary = ary
+
+ if self.alloc_size != 0:
+ _driver.device_to_host(hostary, self, self.alloc_size,
+ stream=stream)
+
+ if ary is None:
+ if self.size == 0:
+ hostary = np.ndarray(shape=self.shape, dtype=self.dtype,
+ buffer=hostary)
+ else:
+ hostary = np.ndarray(shape=self.shape, dtype=self.dtype,
+ strides=self.strides, buffer=hostary)
+ return hostary
+
+ def split(self, section, stream=0):
+ """Split the array into equal partition of the `section` size.
+ If the array cannot be equally divided, the last section will be
+ smaller.
+ """
+ stream = self._default_stream(stream)
+ if self.ndim != 1:
+ raise ValueError("only support 1d array")
+ if self.strides[0] != self.dtype.itemsize:
+ raise ValueError("only support unit stride")
+ nsect = int(math.ceil(float(self.size) / section))
+ strides = self.strides
+ itemsize = self.dtype.itemsize
+ for i in range(nsect):
+ begin = i * section
+ end = min(begin + section, self.size)
+ shape = (end - begin,)
+ gpu_data = self.gpu_data.view(begin * itemsize, end * itemsize)
+ yield DeviceNDArray(shape, strides, dtype=self.dtype, stream=stream,
+ gpu_data=gpu_data)
+
+ def as_cuda_arg(self):
+ """Returns a device memory object that is used as the argument.
+ """
+ return self.gpu_data
+
+ def get_ipc_handle(self):
+ """
+ Returns a *IpcArrayHandle* object that is safe to serialize and transfer
+ to another process to share the local allocation.
+
+ Note: this feature is only available on Linux.
+ """
+ ipch = devices.get_context().get_ipc_handle(self.gpu_data)
+ desc = dict(shape=self.shape, strides=self.strides, dtype=self.dtype)
+ return IpcArrayHandle(ipc_handle=ipch, array_desc=desc)
+
+ def squeeze(self, axis=None, stream=0):
+ """
+ Remove axes of size one from the array shape.
+
+ Parameters
+ ----------
+ axis : None or int or tuple of ints, optional
+ Subset of dimensions to remove. A `ValueError` is raised if an axis
+ with size greater than one is selected. If `None`, all axes with
+ size one are removed.
+ stream : cuda stream or 0, optional
+ Default stream for the returned view of the array.
+
+ Returns
+ -------
+ DeviceNDArray
+ Squeezed view into the array.
+
+ """
+ new_dummy, _ = self._dummy.squeeze(axis=axis)
+ return DeviceNDArray(
+ shape=new_dummy.shape,
+ strides=new_dummy.strides,
+ dtype=self.dtype,
+ stream=self._default_stream(stream),
+ gpu_data=self.gpu_data,
+ )
+
+ def view(self, dtype):
+ """Returns a new object by reinterpretting the dtype without making a
+ copy of the data.
+ """
+ dtype = np.dtype(dtype)
+ shape = list(self.shape)
+ strides = list(self.strides)
+
+ if self.dtype.itemsize != dtype.itemsize:
+ if not self.is_c_contiguous():
+ raise ValueError(
+ "To change to a dtype of a different size,"
+ " the array must be C-contiguous"
+ )
+
+ shape[-1], rem = divmod(
+ shape[-1] * self.dtype.itemsize,
+ dtype.itemsize
+ )
+
+ if rem != 0:
+ raise ValueError(
+ "When changing to a larger dtype,"
+ " its size must be a divisor of the total size in bytes"
+ " of the last axis of the array."
+ )
+
+ strides[-1] = dtype.itemsize
+
+ return DeviceNDArray(
+ shape=shape,
+ strides=strides,
+ dtype=dtype,
+ stream=self.stream,
+ gpu_data=self.gpu_data,
+ )
+
+ @property
+ def nbytes(self):
+ # Note: not using `alloc_size`. `alloc_size` reports memory
+ # consumption of the allocation, not the size of the array
+ # https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.nbytes.html
+ return self.dtype.itemsize * self.size
+
+
+class DeviceRecord(DeviceNDArrayBase):
+ '''
+ An on-GPU record type
+ '''
+ def __init__(self, dtype, stream=0, gpu_data=None):
+ shape = ()
+ strides = ()
+ super(DeviceRecord, self).__init__(shape, strides, dtype, stream,
+ gpu_data)
+
+ @property
+ def flags(self):
+ """
+ For `numpy.ndarray` compatibility. Ideally this would return a
+ `np.core.multiarray.flagsobj`, but that needs to be constructed
+ with an existing `numpy.ndarray` (as the C- and F- contiguous flags
+ aren't writeable).
+ """
+ return dict(self._dummy.flags) # defensive copy
+
+ @property
+ def _numba_type_(self):
+ """
+ Magic attribute expected by Numba to get the numba type that
+ represents this object.
+ """
+ return numpy_support.from_dtype(self.dtype)
+
+ @devices.require_context
+ def __getitem__(self, item):
+ return self._do_getitem(item)
+
+ @devices.require_context
+ def getitem(self, item, stream=0):
+ """Do `__getitem__(item)` with CUDA stream
+ """
+ return self._do_getitem(item, stream)
+
+ def _do_getitem(self, item, stream=0):
+ stream = self._default_stream(stream)
+ typ, offset = self.dtype.fields[item]
+ newdata = self.gpu_data.view(offset)
+
+ if typ.shape == ():
+ if typ.names is not None:
+ return DeviceRecord(dtype=typ, stream=stream,
+ gpu_data=newdata)
+ else:
+ hostary = np.empty(1, dtype=typ)
+ _driver.device_to_host(dst=hostary, src=newdata,
+ size=typ.itemsize,
+ stream=stream)
+ return hostary[0]
+ else:
+ shape, strides, dtype = \
+ prepare_shape_strides_dtype(typ.shape,
+ None,
+ typ.subdtype[0], 'C')
+ return DeviceNDArray(shape=shape, strides=strides,
+ dtype=dtype, gpu_data=newdata,
+ stream=stream)
+
+ @devices.require_context
+ def __setitem__(self, key, value):
+ return self._do_setitem(key, value)
+
+ @devices.require_context
+ def setitem(self, key, value, stream=0):
+ """Do `__setitem__(key, value)` with CUDA stream
+ """
+ return self._do_setitem(key, value, stream=stream)
+
+ def _do_setitem(self, key, value, stream=0):
+
+ stream = self._default_stream(stream)
+
+ # If the record didn't have a default stream, and the user didn't
+ # provide a stream, then we will use the default stream for the
+ # assignment kernel and synchronize on it.
+ synchronous = not stream
+ if synchronous:
+ ctx = devices.get_context()
+ stream = ctx.get_default_stream()
+
+ # (1) prepare LHS
+
+ typ, offset = self.dtype.fields[key]
+ newdata = self.gpu_data.view(offset)
+
+ lhs = type(self)(dtype=typ, stream=stream, gpu_data=newdata)
+
+ # (2) prepare RHS
+
+ rhs, _ = auto_device(lhs.dtype.type(value), stream=stream)
+
+ # (3) do the copy
+
+ _driver.device_to_device(lhs, rhs, rhs.dtype.itemsize, stream)
+
+ if synchronous:
+ stream.synchronize()
+
+
+@lru_cache
+def _assign_kernel(ndim):
+ """
+ A separate method so we don't need to compile code every assignment (!).
+
+ :param ndim: We need to have static array sizes for cuda.local.array, so
+ bake in the number of dimensions into the kernel
+ """
+ from numba import cuda # circular!
+
+ if ndim == 0:
+ # the (2, ndim) allocation below is not yet supported, so avoid it
+ @cuda.jit
+ def kernel(lhs, rhs):
+ lhs[()] = rhs[()]
+ return kernel
+
+ @cuda.jit
+ def kernel(lhs, rhs):
+ location = cuda.grid(1)
+
+ n_elements = 1
+ for i in range(lhs.ndim):
+ n_elements *= lhs.shape[i]
+ if location >= n_elements:
+ # bake n_elements into the kernel, better than passing it in
+ # as another argument.
+ return
+
+ # [0, :] is the to-index (into `lhs`)
+ # [1, :] is the from-index (into `rhs`)
+ idx = cuda.local.array(
+ shape=(2, ndim),
+ dtype=types.int64)
+
+ for i in range(ndim - 1, -1, -1):
+ idx[0, i] = location % lhs.shape[i]
+ idx[1, i] = (location % lhs.shape[i]) * (rhs.shape[i] > 1)
+ location //= lhs.shape[i]
+
+ lhs[to_fixed_tuple(idx[0], ndim)] = rhs[to_fixed_tuple(idx[1], ndim)]
+ return kernel
+
+
+class DeviceNDArray(DeviceNDArrayBase):
+ '''
+ An on-GPU array type
+ '''
+ def is_f_contiguous(self):
+ '''
+ Return true if the array is Fortran-contiguous.
+ '''
+ return self._dummy.is_f_contig
+
+ @property
+ def flags(self):
+ """
+ For `numpy.ndarray` compatibility. Ideally this would return a
+ `np.core.multiarray.flagsobj`, but that needs to be constructed
+ with an existing `numpy.ndarray` (as the C- and F- contiguous flags
+ aren't writeable).
+ """
+ return dict(self._dummy.flags) # defensive copy
+
+ def is_c_contiguous(self):
+ '''
+ Return true if the array is C-contiguous.
+ '''
+ return self._dummy.is_c_contig
+
+ def __array__(self, dtype=None):
+ """
+ :return: an `numpy.ndarray`, so copies to the host.
+ """
+ if dtype:
+ return self.copy_to_host().__array__(dtype)
+ else:
+ return self.copy_to_host().__array__()
+
+ def __len__(self):
+ return self.shape[0]
+
+ def reshape(self, *newshape, **kws):
+ """
+ Reshape the array without changing its contents, similarly to
+ :meth:`numpy.ndarray.reshape`. Example::
+
+ d_arr = d_arr.reshape(20, 50, order='F')
+ """
+ if len(newshape) == 1 and isinstance(newshape[0], (tuple, list)):
+ newshape = newshape[0]
+
+ cls = type(self)
+ if newshape == self.shape:
+ # nothing to do
+ return cls(shape=self.shape, strides=self.strides,
+ dtype=self.dtype, gpu_data=self.gpu_data)
+
+ newarr, extents = self._dummy.reshape(*newshape, **kws)
+
+ if extents == [self._dummy.extent]:
+ return cls(shape=newarr.shape, strides=newarr.strides,
+ dtype=self.dtype, gpu_data=self.gpu_data)
+ else:
+ raise NotImplementedError("operation requires copying")
+
+ def ravel(self, order='C', stream=0):
+ '''
+ Flattens a contiguous array without changing its contents, similar to
+ :meth:`numpy.ndarray.ravel`. If the array is not contiguous, raises an
+ exception.
+ '''
+ stream = self._default_stream(stream)
+ cls = type(self)
+ newarr, extents = self._dummy.ravel(order=order)
+
+ if extents == [self._dummy.extent]:
+ return cls(shape=newarr.shape, strides=newarr.strides,
+ dtype=self.dtype, gpu_data=self.gpu_data,
+ stream=stream)
+
+ else:
+ raise NotImplementedError("operation requires copying")
+
+ @devices.require_context
+ def __getitem__(self, item):
+ return self._do_getitem(item)
+
+ @devices.require_context
+ def getitem(self, item, stream=0):
+ """Do `__getitem__(item)` with CUDA stream
+ """
+ return self._do_getitem(item, stream)
+
+ def _do_getitem(self, item, stream=0):
+ stream = self._default_stream(stream)
+
+ arr = self._dummy.__getitem__(item)
+ extents = list(arr.iter_contiguous_extent())
+ cls = type(self)
+ if len(extents) == 1:
+ newdata = self.gpu_data.view(*extents[0])
+
+ if not arr.is_array:
+ # Check for structured array type (record)
+ if self.dtype.names is not None:
+ return DeviceRecord(dtype=self.dtype, stream=stream,
+ gpu_data=newdata)
+ else:
+ # Element indexing
+ hostary = np.empty(1, dtype=self.dtype)
+ _driver.device_to_host(dst=hostary, src=newdata,
+ size=self._dummy.itemsize,
+ stream=stream)
+ return hostary[0]
+ else:
+ return cls(shape=arr.shape, strides=arr.strides,
+ dtype=self.dtype, gpu_data=newdata, stream=stream)
+ else:
+ newdata = self.gpu_data.view(*arr.extent)
+ return cls(shape=arr.shape, strides=arr.strides,
+ dtype=self.dtype, gpu_data=newdata, stream=stream)
+
+ @devices.require_context
+ def __setitem__(self, key, value):
+ return self._do_setitem(key, value)
+
+ @devices.require_context
+ def setitem(self, key, value, stream=0):
+ """Do `__setitem__(key, value)` with CUDA stream
+ """
+ return self._do_setitem(key, value, stream=stream)
+
+ def _do_setitem(self, key, value, stream=0):
+
+ stream = self._default_stream(stream)
+
+ # If the array didn't have a default stream, and the user didn't provide
+ # a stream, then we will use the default stream for the assignment
+ # kernel and synchronize on it.
+ synchronous = not stream
+ if synchronous:
+ ctx = devices.get_context()
+ stream = ctx.get_default_stream()
+
+ # (1) prepare LHS
+
+ arr = self._dummy.__getitem__(key)
+ newdata = self.gpu_data.view(*arr.extent)
+
+ if isinstance(arr, dummyarray.Element):
+ # convert to a 0d array
+ shape = ()
+ strides = ()
+ else:
+ shape = arr.shape
+ strides = arr.strides
+
+ lhs = type(self)(
+ shape=shape,
+ strides=strides,
+ dtype=self.dtype,
+ gpu_data=newdata,
+ stream=stream)
+
+ # (2) prepare RHS
+
+ rhs, _ = auto_device(value, stream=stream, user_explicit=True)
+ if rhs.ndim > lhs.ndim:
+ raise ValueError("Can't assign %s-D array to %s-D self" % (
+ rhs.ndim,
+ lhs.ndim))
+ rhs_shape = np.ones(lhs.ndim, dtype=np.int64)
+ # negative indices would not work if rhs.ndim == 0
+ rhs_shape[lhs.ndim - rhs.ndim:] = rhs.shape
+ rhs = rhs.reshape(*rhs_shape)
+ for i, (l, r) in enumerate(zip(lhs.shape, rhs.shape)):
+ if r != 1 and l != r:
+ raise ValueError("Can't copy sequence with size %d to array "
+ "axis %d with dimension %d" % ( r, i, l))
+
+ # (3) do the copy
+
+ n_elements = functools.reduce(operator.mul, lhs.shape, 1)
+ _assign_kernel(lhs.ndim).forall(n_elements, stream=stream)(lhs, rhs)
+ if synchronous:
+ stream.synchronize()
+
+
+class IpcArrayHandle(object):
+ """
+ An IPC array handle that can be serialized and transfer to another process
+ in the same machine for share a GPU allocation.
+
+ On the destination process, use the *.open()* method to creates a new
+ *DeviceNDArray* object that shares the allocation from the original process.
+ To release the resources, call the *.close()* method. After that, the
+ destination can no longer use the shared array object. (Note: the
+ underlying weakref to the resource is now dead.)
+
+ This object implements the context-manager interface that calls the
+ *.open()* and *.close()* method automatically::
+
+ with the_ipc_array_handle as ipc_array:
+ # use ipc_array here as a normal gpu array object
+ some_code(ipc_array)
+ # ipc_array is dead at this point
+ """
+ def __init__(self, ipc_handle, array_desc):
+ self._array_desc = array_desc
+ self._ipc_handle = ipc_handle
+
+ def open(self):
+ """
+ Returns a new *DeviceNDArray* that shares the allocation from the
+ original process. Must not be used on the original process.
+ """
+ dptr = self._ipc_handle.open(devices.get_context())
+ return DeviceNDArray(gpu_data=dptr, **self._array_desc)
+
+ def close(self):
+ """
+ Closes the IPC handle to the array.
+ """
+ self._ipc_handle.close()
+
+ def __enter__(self):
+ return self.open()
+
+ def __exit__(self, type, value, traceback):
+ self.close()
+
+
+class MappedNDArray(DeviceNDArrayBase, np.ndarray):
+ """
+ A host array that uses CUDA mapped memory.
+ """
+
+ def device_setup(self, gpu_data, stream=0):
+ self.gpu_data = gpu_data
+ self.stream = stream
+
+
+class ManagedNDArray(DeviceNDArrayBase, np.ndarray):
+ """
+ A host array that uses CUDA managed memory.
+ """
+
+ def device_setup(self, gpu_data, stream=0):
+ self.gpu_data = gpu_data
+ self.stream = stream
+
+
+def from_array_like(ary, stream=0, gpu_data=None):
+ "Create a DeviceNDArray object that is like ary."
+ return DeviceNDArray(ary.shape, ary.strides, ary.dtype, stream=stream,
+ gpu_data=gpu_data)
+
+
+def from_record_like(rec, stream=0, gpu_data=None):
+ "Create a DeviceRecord object that is like rec."
+ return DeviceRecord(rec.dtype, stream=stream, gpu_data=gpu_data)
+
+
+def array_core(ary):
+ """
+ Extract the repeated core of a broadcast array.
+
+ Broadcast arrays are by definition non-contiguous due to repeated
+ dimensions, i.e., dimensions with stride 0. In order to ascertain memory
+ contiguity and copy the underlying data from such arrays, we must create
+ a view without the repeated dimensions.
+
+ """
+ if not ary.strides or not ary.size:
+ return ary
+ core_index = []
+ for stride in ary.strides:
+ core_index.append(0 if stride == 0 else slice(None))
+ return ary[tuple(core_index)]
+
+
+def is_contiguous(ary):
+ """
+ Returns True iff `ary` is C-style contiguous while ignoring
+ broadcasted and 1-sized dimensions.
+ As opposed to array_core(), it does not call require_context(),
+ which can be quite expensive.
+ """
+ size = ary.dtype.itemsize
+ for shape, stride in zip(reversed(ary.shape), reversed(ary.strides)):
+ if shape > 1 and stride != 0:
+ if size != stride:
+ return False
+ size *= shape
+ return True
+
+
+errmsg_contiguous_buffer = ("Array contains non-contiguous buffer and cannot "
+ "be transferred as a single memory region. Please "
+ "ensure contiguous buffer with numpy "
+ ".ascontiguousarray()")
+
+
+def sentry_contiguous(ary):
+ core = array_core(ary)
+ if not core.flags['C_CONTIGUOUS'] and not core.flags['F_CONTIGUOUS']:
+ raise ValueError(errmsg_contiguous_buffer)
+
+
+def auto_device(obj, stream=0, copy=True, user_explicit=False):
+ """
+ Create a DeviceRecord or DeviceArray like obj and optionally copy data from
+ host to device. If obj already represents device memory, it is returned and
+ no copy is made.
+ """
+ if _driver.is_device_memory(obj):
+ return obj, False
+ elif hasattr(obj, '__cuda_array_interface__'):
+ return numba.cuda.as_cuda_array(obj), False
+ else:
+ if isinstance(obj, np.void):
+ devobj = from_record_like(obj, stream=stream)
+ else:
+ # This allows you to pass non-array objects like constants and
+ # objects implementing the array interface
+ # https://docs.scipy.org/doc/numpy-1.13.0/reference/arrays.interface.html
+ # into this function (with no overhead -- copies -- for `obj`s
+ # that are already `ndarray`s.
+ obj = np.array(
+ obj,
+ copy=False if numpy_version < (2, 0) else None,
+ subok=True)
+ sentry_contiguous(obj)
+ devobj = from_array_like(obj, stream=stream)
+ if copy:
+ if config.CUDA_WARN_ON_IMPLICIT_COPY:
+ if (
+ not user_explicit and
+ (not isinstance(obj, DeviceNDArray)
+ and isinstance(obj, np.ndarray))
+ ):
+ msg = ("Host array used in CUDA kernel will incur "
+ "copy overhead to/from device.")
+ warn(NumbaPerformanceWarning(msg))
+ devobj.copy_to_device(obj, stream=stream)
+ return devobj, True
+
+
+def check_array_compatibility(ary1, ary2):
+ ary1sq, ary2sq = ary1.squeeze(), ary2.squeeze()
+ if ary1.dtype != ary2.dtype:
+ raise TypeError('incompatible dtype: %s vs. %s' %
+ (ary1.dtype, ary2.dtype))
+ if ary1sq.shape != ary2sq.shape:
+ raise ValueError('incompatible shape: %s vs. %s' %
+ (ary1.shape, ary2.shape))
+ # We check strides only if the size is nonzero, because strides are
+ # irrelevant (and can differ) for zero-length copies.
+ if ary1.size and ary1sq.strides != ary2sq.strides:
+ raise ValueError('incompatible strides: %s vs. %s' %
+ (ary1.strides, ary2.strides))
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/devices.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/devices.py
new file mode 100644
index 0000000000000000000000000000000000000000..6cc9e2e393fc07276f01c5c4c14952bd81f04b50
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/devices.py
@@ -0,0 +1,248 @@
+"""
+Expose each GPU devices directly.
+
+This module implements a API that is like the "CUDA runtime" context manager
+for managing CUDA context stack and clean up. It relies on thread-local globals
+to separate the context stack management of each thread. Contexts are also
+shareable among threads. Only the main thread can destroy Contexts.
+
+Note:
+- This module must be imported by the main-thread.
+
+"""
+import functools
+import threading
+from contextlib import contextmanager
+
+from .driver import driver, USE_NV_BINDING
+
+
+class _DeviceList(object):
+ def __getattr__(self, attr):
+ # First time looking at "lst" attribute.
+ if attr == "lst":
+ # Device list is not initialized.
+ # Query all CUDA devices.
+ numdev = driver.get_device_count()
+ gpus = [_DeviceContextManager(driver.get_device(devid))
+ for devid in range(numdev)]
+ # Define "lst" to avoid re-initialization
+ self.lst = gpus
+ return gpus
+
+ # Other attributes
+ return super(_DeviceList, self).__getattr__(attr)
+
+ def __getitem__(self, devnum):
+ '''
+ Returns the context manager for device *devnum*.
+ '''
+ return self.lst[devnum]
+
+ def __str__(self):
+ return ', '.join([str(d) for d in self.lst])
+
+ def __iter__(self):
+ return iter(self.lst)
+
+ def __len__(self):
+ return len(self.lst)
+
+ @property
+ def current(self):
+ """Returns the active device or None if there's no active device
+ """
+ with driver.get_active_context() as ac:
+ devnum = ac.devnum
+ if devnum is not None:
+ return self[devnum]
+
+
+class _DeviceContextManager(object):
+ """
+ Provides a context manager for executing in the context of the chosen
+ device. The normal use of instances of this type is from
+ ``numba.cuda.gpus``. For example, to execute on device 2::
+
+ with numba.cuda.gpus[2]:
+ d_a = numba.cuda.to_device(a)
+
+ to copy the array *a* onto device 2, referred to by *d_a*.
+ """
+
+ def __init__(self, device):
+ self._device = device
+
+ def __getattr__(self, item):
+ return getattr(self._device, item)
+
+ def __enter__(self):
+ _runtime.get_or_create_context(self._device.id)
+
+ def __exit__(self, exc_type, exc_val, exc_tb):
+ # this will verify that we are popping the right device context.
+ self._device.get_primary_context().pop()
+
+ def __str__(self):
+ return "".format(self=self)
+
+
+class _Runtime(object):
+ """Emulate the CUDA runtime context management.
+
+ It owns all Devices and Contexts.
+ Keeps at most one Context per Device
+ """
+
+ def __init__(self):
+ self.gpus = _DeviceList()
+
+ # For caching the attached CUDA Context
+ self._tls = threading.local()
+
+ # Remember the main thread
+ # Only the main thread can *actually* destroy
+ self._mainthread = threading.current_thread()
+
+ # Avoid mutation of runtime state in multithreaded programs
+ self._lock = threading.RLock()
+
+ @contextmanager
+ def ensure_context(self):
+ """Ensure a CUDA context is available inside the context.
+
+ On entrance, queries the CUDA driver for an active CUDA context and
+ attaches it in TLS for subsequent calls so they do not need to query
+ the CUDA driver again. On exit, detach the CUDA context from the TLS.
+
+ This will allow us to pickup thirdparty activated CUDA context in
+ any top-level Numba CUDA API.
+ """
+ with driver.get_active_context():
+ oldctx = self._get_attached_context()
+ newctx = self.get_or_create_context(None)
+ self._set_attached_context(newctx)
+ try:
+ yield
+ finally:
+ self._set_attached_context(oldctx)
+
+ def get_or_create_context(self, devnum):
+ """Returns the primary context and push+create it if needed
+ for *devnum*. If *devnum* is None, use the active CUDA context (must
+ be primary) or create a new one with ``devnum=0``.
+ """
+ if devnum is None:
+ attached_ctx = self._get_attached_context()
+ if attached_ctx is None:
+ return self._get_or_create_context_uncached(devnum)
+ else:
+ return attached_ctx
+ else:
+ if USE_NV_BINDING:
+ devnum = int(devnum)
+ return self._activate_context_for(devnum)
+
+ def _get_or_create_context_uncached(self, devnum):
+ """See also ``get_or_create_context(devnum)``.
+ This version does not read the cache.
+ """
+ with self._lock:
+ # Try to get the active context in the CUDA stack or
+ # activate GPU-0 with the primary context
+ with driver.get_active_context() as ac:
+ if not ac:
+ return self._activate_context_for(0)
+ else:
+ # Get primary context for the active device
+ ctx = self.gpus[ac.devnum].get_primary_context()
+ # Is active context the primary context?
+ if USE_NV_BINDING:
+ ctx_handle = int(ctx.handle)
+ ac_ctx_handle = int(ac.context_handle)
+ else:
+ ctx_handle = ctx.handle.value
+ ac_ctx_handle = ac.context_handle.value
+ if ctx_handle != ac_ctx_handle:
+ msg = ('Numba cannot operate on non-primary'
+ ' CUDA context {:x}')
+ raise RuntimeError(msg.format(ac_ctx_handle))
+ # Ensure the context is ready
+ ctx.prepare_for_use()
+ return ctx
+
+ def _activate_context_for(self, devnum):
+ with self._lock:
+ gpu = self.gpus[devnum]
+ newctx = gpu.get_primary_context()
+ # Detect unexpected context switch
+ cached_ctx = self._get_attached_context()
+ if cached_ctx is not None and cached_ctx is not newctx:
+ raise RuntimeError('Cannot switch CUDA-context.')
+ newctx.push()
+ return newctx
+
+ def _get_attached_context(self):
+ return getattr(self._tls, 'attached_context', None)
+
+ def _set_attached_context(self, ctx):
+ self._tls.attached_context = ctx
+
+ def reset(self):
+ """Clear all contexts in the thread. Destroy the context if and only
+ if we are in the main thread.
+ """
+ # Pop all active context.
+ while driver.pop_active_context() is not None:
+ pass
+
+ # If it is the main thread
+ if threading.current_thread() == self._mainthread:
+ self._destroy_all_contexts()
+
+ def _destroy_all_contexts(self):
+ # Reset all devices
+ for gpu in self.gpus:
+ gpu.reset()
+
+
+_runtime = _Runtime()
+
+# ================================ PUBLIC API ================================
+
+gpus = _runtime.gpus
+
+
+def get_context(devnum=None):
+ """Get the current device or use a device by device number, and
+ return the CUDA context.
+ """
+ return _runtime.get_or_create_context(devnum)
+
+
+def require_context(fn):
+ """
+ A decorator that ensures a CUDA context is available when *fn* is executed.
+
+ Note: The function *fn* cannot switch CUDA-context.
+ """
+ @functools.wraps(fn)
+ def _require_cuda_context(*args, **kws):
+ with _runtime.ensure_context():
+ return fn(*args, **kws)
+
+ return _require_cuda_context
+
+
+def reset():
+ """Reset the CUDA subsystem for the current thread.
+
+ In the main thread:
+ This removes all CUDA contexts. Only use this at shutdown or for
+ cleaning up between tests.
+
+ In non-main threads:
+ This clear the CUDA context stack only.
+
+ """
+ _runtime.reset()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/driver.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/driver.py
new file mode 100644
index 0000000000000000000000000000000000000000..875497e55d47292bb56a6f81990dbe7c5c64616b
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/driver.py
@@ -0,0 +1,3224 @@
+"""
+CUDA driver bridge implementation
+
+NOTE:
+The new driver implementation uses a *_PendingDeallocs* that help prevents a
+crashing the system (particularly OSX) when the CUDA context is corrupted at
+resource deallocation. The old approach ties resource management directly
+into the object destructor; thus, at corruption of the CUDA context,
+subsequent deallocation could further corrupt the CUDA context and causes the
+system to freeze in some cases.
+
+"""
+
+import sys
+import os
+import ctypes
+import weakref
+import functools
+import warnings
+import logging
+import threading
+import asyncio
+import pathlib
+from itertools import product
+from abc import ABCMeta, abstractmethod
+from ctypes import (c_int, byref, c_size_t, c_char, c_char_p, addressof,
+ c_void_p, c_float, c_uint)
+import contextlib
+import importlib
+import numpy as np
+from collections import namedtuple, deque
+
+from numba import mviewbuf
+from numba.core import utils, serialize, config
+from .error import CudaSupportError, CudaDriverError
+from .drvapi import API_PROTOTYPES
+from .drvapi import cu_occupancy_b2d_size, cu_stream_callback_pyobj, cu_uuid
+from numba.cuda.cudadrv import enums, drvapi, nvrtc, _extras
+
+USE_NV_BINDING = config.CUDA_USE_NVIDIA_BINDING
+
+if USE_NV_BINDING:
+ from cuda import cuda as binding
+ # There is no definition of the default stream in the Nvidia bindings (nor
+ # is there at the C/C++ level), so we define it here so we don't need to
+ # use a magic number 0 in places where we want the default stream.
+ CU_STREAM_DEFAULT = 0
+
+MIN_REQUIRED_CC = (3, 5)
+SUPPORTS_IPC = sys.platform.startswith('linux')
+
+
+_py_decref = ctypes.pythonapi.Py_DecRef
+_py_incref = ctypes.pythonapi.Py_IncRef
+_py_decref.argtypes = [ctypes.py_object]
+_py_incref.argtypes = [ctypes.py_object]
+
+
+def make_logger():
+ logger = logging.getLogger(__name__)
+ # is logging configured?
+ if not logger.hasHandlers():
+ # read user config
+ lvl = str(config.CUDA_LOG_LEVEL).upper()
+ lvl = getattr(logging, lvl, None)
+ if not isinstance(lvl, int):
+ # default to critical level
+ lvl = logging.CRITICAL
+ logger.setLevel(lvl)
+ # did user specify a level?
+ if config.CUDA_LOG_LEVEL:
+ # create a simple handler that prints to stderr
+ handler = logging.StreamHandler(sys.stderr)
+ fmt = '== CUDA [%(relativeCreated)d] %(levelname)5s -- %(message)s'
+ handler.setFormatter(logging.Formatter(fmt=fmt))
+ logger.addHandler(handler)
+ else:
+ # otherwise, put a null handler
+ logger.addHandler(logging.NullHandler())
+ return logger
+
+
+class DeadMemoryError(RuntimeError):
+ pass
+
+
+class LinkerError(RuntimeError):
+ pass
+
+
+class CudaAPIError(CudaDriverError):
+ def __init__(self, code, msg):
+ self.code = code
+ self.msg = msg
+ super(CudaAPIError, self).__init__(code, msg)
+
+ def __str__(self):
+ return "[%s] %s" % (self.code, self.msg)
+
+
+def locate_driver_and_loader():
+
+ envpath = config.CUDA_DRIVER
+
+ if envpath == '0':
+ # Force fail
+ _raise_driver_not_found()
+
+ # Determine DLL type
+ if sys.platform == 'win32':
+ dlloader = ctypes.WinDLL
+ dldir = ['\\windows\\system32']
+ dlnames = ['nvcuda.dll']
+ elif sys.platform == 'darwin':
+ dlloader = ctypes.CDLL
+ dldir = ['/usr/local/cuda/lib']
+ dlnames = ['libcuda.dylib']
+ else:
+ # Assume to be *nix like
+ dlloader = ctypes.CDLL
+ dldir = ['/usr/lib', '/usr/lib64']
+ dlnames = ['libcuda.so', 'libcuda.so.1']
+
+ if envpath:
+ try:
+ envpath = os.path.abspath(envpath)
+ except ValueError:
+ raise ValueError("NUMBA_CUDA_DRIVER %s is not a valid path" %
+ envpath)
+ if not os.path.isfile(envpath):
+ raise ValueError("NUMBA_CUDA_DRIVER %s is not a valid file "
+ "path. Note it must be a filepath of the .so/"
+ ".dll/.dylib or the driver" % envpath)
+ candidates = [envpath]
+ else:
+ # First search for the name in the default library path.
+ # If that is not found, try the specific path.
+ candidates = dlnames + [os.path.join(x, y)
+ for x, y in product(dldir, dlnames)]
+
+ return dlloader, candidates
+
+
+def load_driver(dlloader, candidates):
+
+ # Load the driver; Collect driver error information
+ path_not_exist = []
+ driver_load_error = []
+
+ for path in candidates:
+ try:
+ dll = dlloader(path)
+ except OSError as e:
+ # Problem opening the DLL
+ path_not_exist.append(not os.path.isfile(path))
+ driver_load_error.append(e)
+ else:
+ return dll, path
+
+ # Problem loading driver
+ if all(path_not_exist):
+ _raise_driver_not_found()
+ else:
+ errmsg = '\n'.join(str(e) for e in driver_load_error)
+ _raise_driver_error(errmsg)
+
+
+def find_driver():
+ dlloader, candidates = locate_driver_and_loader()
+ dll, path = load_driver(dlloader, candidates)
+ return dll
+
+
+DRIVER_NOT_FOUND_MSG = """
+CUDA driver library cannot be found.
+If you are sure that a CUDA driver is installed,
+try setting environment variable NUMBA_CUDA_DRIVER
+with the file path of the CUDA driver shared library.
+"""
+
+DRIVER_LOAD_ERROR_MSG = """
+Possible CUDA driver libraries are found but error occurred during load:
+%s
+"""
+
+
+def _raise_driver_not_found():
+ raise CudaSupportError(DRIVER_NOT_FOUND_MSG)
+
+
+def _raise_driver_error(e):
+ raise CudaSupportError(DRIVER_LOAD_ERROR_MSG % e)
+
+
+def _build_reverse_error_map():
+ prefix = 'CUDA_ERROR'
+ map = utils.UniqueDict()
+ for name in dir(enums):
+ if name.startswith(prefix):
+ code = getattr(enums, name)
+ map[code] = name
+ return map
+
+
+def _getpid():
+ return os.getpid()
+
+
+ERROR_MAP = _build_reverse_error_map()
+
+
+class Driver(object):
+ """
+ Driver API functions are lazily bound.
+ """
+ _singleton = None
+
+ def __new__(cls):
+ obj = cls._singleton
+ if obj is not None:
+ return obj
+ else:
+ obj = object.__new__(cls)
+ cls._singleton = obj
+ return obj
+
+ def __init__(self):
+ self.devices = utils.UniqueDict()
+ self.is_initialized = False
+ self.initialization_error = None
+ self.pid = None
+ try:
+ if config.DISABLE_CUDA:
+ msg = ("CUDA is disabled due to setting NUMBA_DISABLE_CUDA=1 "
+ "in the environment, or because CUDA is unsupported on "
+ "32-bit systems.")
+ raise CudaSupportError(msg)
+ self.lib = find_driver()
+ except CudaSupportError as e:
+ self.is_initialized = True
+ self.initialization_error = e.msg
+
+ def ensure_initialized(self):
+ if self.is_initialized:
+ return
+
+ # lazily initialize logger
+ global _logger
+ _logger = make_logger()
+
+ self.is_initialized = True
+ try:
+ _logger.info('init')
+ self.cuInit(0)
+ except CudaAPIError as e:
+ description = f"{e.msg} ({e.code})"
+ self.initialization_error = description
+ raise CudaSupportError(f"Error at driver init: {description}")
+ else:
+ self.pid = _getpid()
+
+ self._initialize_extras()
+
+ def _initialize_extras(self):
+ if USE_NV_BINDING:
+ # The extras are only needed when using Numba's ctypes bindings
+ return
+
+ # set pointer to original cuIpcOpenMemHandle
+ set_proto = ctypes.CFUNCTYPE(None, c_void_p)
+ set_cuIpcOpenMemHandle = set_proto(_extras.set_cuIpcOpenMemHandle)
+ set_cuIpcOpenMemHandle(self._find_api('cuIpcOpenMemHandle'))
+ # bind caller to cuIpcOpenMemHandle that fixes the ABI
+ call_proto = ctypes.CFUNCTYPE(c_int,
+ ctypes.POINTER(drvapi.cu_device_ptr),
+ ctypes.POINTER(drvapi.cu_ipc_mem_handle),
+ ctypes.c_uint)
+ call_cuIpcOpenMemHandle = call_proto(_extras.call_cuIpcOpenMemHandle)
+ call_cuIpcOpenMemHandle.__name__ = 'call_cuIpcOpenMemHandle'
+ safe_call = self._ctypes_wrap_fn('call_cuIpcOpenMemHandle',
+ call_cuIpcOpenMemHandle)
+ # override cuIpcOpenMemHandle
+ self.cuIpcOpenMemHandle = safe_call
+
+ @property
+ def is_available(self):
+ self.ensure_initialized()
+ return self.initialization_error is None
+
+ def __getattr__(self, fname):
+ # First request of a driver API function
+ self.ensure_initialized()
+
+ if self.initialization_error is not None:
+ raise CudaSupportError("Error at driver init: \n%s:" %
+ self.initialization_error)
+
+ if USE_NV_BINDING:
+ return self._cuda_python_wrap_fn(fname)
+ else:
+ return self._ctypes_wrap_fn(fname)
+
+ def _ctypes_wrap_fn(self, fname, libfn=None):
+ # Wrap a CUDA driver function by default
+ if libfn is None:
+ try:
+ proto = API_PROTOTYPES[fname]
+ except KeyError:
+ raise AttributeError(fname)
+ restype = proto[0]
+ argtypes = proto[1:]
+
+ # Find function in driver library
+ libfn = self._find_api(fname)
+ libfn.restype = restype
+ libfn.argtypes = argtypes
+
+ def verbose_cuda_api_call(*args):
+ argstr = ", ".join([str(arg) for arg in args])
+ _logger.debug('call driver api: %s(%s)', libfn.__name__, argstr)
+ retcode = libfn(*args)
+ self._check_ctypes_error(fname, retcode)
+
+ def safe_cuda_api_call(*args):
+ _logger.debug('call driver api: %s', libfn.__name__)
+ retcode = libfn(*args)
+ self._check_ctypes_error(fname, retcode)
+
+ if config.CUDA_LOG_API_ARGS:
+ wrapper = verbose_cuda_api_call
+ else:
+ wrapper = safe_cuda_api_call
+
+ safe_call = functools.wraps(libfn)(wrapper)
+ setattr(self, fname, safe_call)
+ return safe_call
+
+ def _cuda_python_wrap_fn(self, fname):
+ libfn = getattr(binding, fname)
+
+ def verbose_cuda_api_call(*args):
+ argstr = ", ".join([str(arg) for arg in args])
+ _logger.debug('call driver api: %s(%s)', libfn.__name__, argstr)
+ return self._check_cuda_python_error(fname, libfn(*args))
+
+ def safe_cuda_api_call(*args):
+ _logger.debug('call driver api: %s', libfn.__name__)
+ return self._check_cuda_python_error(fname, libfn(*args))
+
+ if config.CUDA_LOG_API_ARGS:
+ wrapper = verbose_cuda_api_call
+ else:
+ wrapper = safe_cuda_api_call
+
+ safe_call = functools.wraps(libfn)(wrapper)
+ setattr(self, fname, safe_call)
+ return safe_call
+
+ def _find_api(self, fname):
+ # We use alternatively-named functions for PTDS with the Numba ctypes
+ # binding. For the NVidia binding, it handles linking to the correct
+ # variant.
+ if config.CUDA_PER_THREAD_DEFAULT_STREAM and not USE_NV_BINDING:
+ variants = ('_v2_ptds', '_v2_ptsz', '_ptds', '_ptsz', '_v2', '')
+ else:
+ variants = ('_v2', '')
+
+ for variant in variants:
+ try:
+ return getattr(self.lib, f'{fname}{variant}')
+ except AttributeError:
+ pass
+
+ # Not found.
+ # Delay missing function error to use
+ def absent_function(*args, **kws):
+ raise CudaDriverError(f'Driver missing function: {fname}')
+
+ setattr(self, fname, absent_function)
+ return absent_function
+
+ def _detect_fork(self):
+ if self.pid is not None and _getpid() != self.pid:
+ msg = 'pid %s forked from pid %s after CUDA driver init'
+ _logger.critical(msg, _getpid(), self.pid)
+ raise CudaDriverError("CUDA initialized before forking")
+
+ def _check_ctypes_error(self, fname, retcode):
+ if retcode != enums.CUDA_SUCCESS:
+ errname = ERROR_MAP.get(retcode, "UNKNOWN_CUDA_ERROR")
+ msg = "Call to %s results in %s" % (fname, errname)
+ _logger.error(msg)
+ if retcode == enums.CUDA_ERROR_NOT_INITIALIZED:
+ self._detect_fork()
+ raise CudaAPIError(retcode, msg)
+
+ def _check_cuda_python_error(self, fname, returned):
+ retcode = returned[0]
+ retval = returned[1:]
+ if len(retval) == 1:
+ retval = retval[0]
+
+ if retcode != binding.CUresult.CUDA_SUCCESS:
+ msg = "Call to %s results in %s" % (fname, retcode.name)
+ _logger.error(msg)
+ if retcode == binding.CUresult.CUDA_ERROR_NOT_INITIALIZED:
+ self._detect_fork()
+ raise CudaAPIError(retcode, msg)
+
+ return retval
+
+ def get_device(self, devnum=0):
+ dev = self.devices.get(devnum)
+ if dev is None:
+ dev = Device(devnum)
+ self.devices[devnum] = dev
+ return weakref.proxy(dev)
+
+ def get_device_count(self):
+ if USE_NV_BINDING:
+ return self.cuDeviceGetCount()
+
+ count = c_int()
+ self.cuDeviceGetCount(byref(count))
+ return count.value
+
+ def list_devices(self):
+ """Returns a list of active devices
+ """
+ return list(self.devices.values())
+
+ def reset(self):
+ """Reset all devices
+ """
+ for dev in self.devices.values():
+ dev.reset()
+
+ def pop_active_context(self):
+ """Pop the active CUDA context and return the handle.
+ If no CUDA context is active, return None.
+ """
+ with self.get_active_context() as ac:
+ if ac.devnum is not None:
+ if USE_NV_BINDING:
+ return driver.cuCtxPopCurrent()
+ else:
+ popped = drvapi.cu_context()
+ driver.cuCtxPopCurrent(byref(popped))
+ return popped
+
+ def get_active_context(self):
+ """Returns an instance of ``_ActiveContext``.
+ """
+ return _ActiveContext()
+
+ def get_version(self):
+ """
+ Returns the CUDA Runtime version as a tuple (major, minor).
+ """
+ if USE_NV_BINDING:
+ version = driver.cuDriverGetVersion()
+ else:
+ dv = ctypes.c_int(0)
+ driver.cuDriverGetVersion(ctypes.byref(dv))
+ version = dv.value
+
+ # The version is encoded as (1000 * major) + (10 * minor)
+ major = version // 1000
+ minor = (version - (major * 1000)) // 10
+ return (major, minor)
+
+
+class _ActiveContext(object):
+ """An contextmanager object to cache active context to reduce dependency
+ on querying the CUDA driver API.
+
+ Once entering the context, it is assumed that the active CUDA context is
+ not changed until the context is exited.
+ """
+ _tls_cache = threading.local()
+
+ def __enter__(self):
+ is_top = False
+ # check TLS cache
+ if hasattr(self._tls_cache, 'ctx_devnum'):
+ hctx, devnum = self._tls_cache.ctx_devnum
+ # Not cached. Query the driver API.
+ else:
+ if USE_NV_BINDING:
+ hctx = driver.cuCtxGetCurrent()
+ if int(hctx) == 0:
+ hctx = None
+ else:
+ hctx = drvapi.cu_context(0)
+ driver.cuCtxGetCurrent(byref(hctx))
+ hctx = hctx if hctx.value else None
+
+ if hctx is None:
+ devnum = None
+ else:
+ if USE_NV_BINDING:
+ devnum = int(driver.cuCtxGetDevice())
+ else:
+ hdevice = drvapi.cu_device()
+ driver.cuCtxGetDevice(byref(hdevice))
+ devnum = hdevice.value
+
+ self._tls_cache.ctx_devnum = (hctx, devnum)
+ is_top = True
+
+ self._is_top = is_top
+ self.context_handle = hctx
+ self.devnum = devnum
+ return self
+
+ def __exit__(self, exc_type, exc_val, exc_tb):
+ if self._is_top:
+ delattr(self._tls_cache, 'ctx_devnum')
+
+ def __bool__(self):
+ """Returns True is there's a valid and active CUDA context.
+ """
+ return self.context_handle is not None
+
+ __nonzero__ = __bool__
+
+
+driver = Driver()
+
+
+def _build_reverse_device_attrs():
+ prefix = "CU_DEVICE_ATTRIBUTE_"
+ map = utils.UniqueDict()
+ for name in dir(enums):
+ if name.startswith(prefix):
+ map[name[len(prefix):]] = getattr(enums, name)
+ return map
+
+
+DEVICE_ATTRIBUTES = _build_reverse_device_attrs()
+
+
+class Device(object):
+ """
+ The device object owns the CUDA contexts. This is owned by the driver
+ object. User should not construct devices directly.
+ """
+ @classmethod
+ def from_identity(self, identity):
+ """Create Device object from device identity created by
+ ``Device.get_device_identity()``.
+ """
+ for devid in range(driver.get_device_count()):
+ d = driver.get_device(devid)
+ if d.get_device_identity() == identity:
+ return d
+ else:
+ errmsg = (
+ "No device of {} is found. "
+ "Target device may not be visible in this process."
+ ).format(identity)
+ raise RuntimeError(errmsg)
+
+ def __init__(self, devnum):
+ if USE_NV_BINDING:
+ result = driver.cuDeviceGet(devnum)
+ self.id = result
+ got_devnum = int(result)
+ else:
+ result = c_int()
+ driver.cuDeviceGet(byref(result), devnum)
+ got_devnum = result.value
+ self.id = got_devnum
+
+ msg = f"Driver returned device {got_devnum} instead of {devnum}"
+ if devnum != got_devnum:
+ raise RuntimeError(msg)
+
+ self.attributes = {}
+
+ # Read compute capability
+ self.compute_capability = (self.COMPUTE_CAPABILITY_MAJOR,
+ self.COMPUTE_CAPABILITY_MINOR)
+
+ # Read name
+ bufsz = 128
+
+ if USE_NV_BINDING:
+ buf = driver.cuDeviceGetName(bufsz, self.id)
+ name = buf.decode('utf-8').rstrip('\0')
+ else:
+ buf = (c_char * bufsz)()
+ driver.cuDeviceGetName(buf, bufsz, self.id)
+ name = buf.value
+
+ self.name = name
+
+ # Read UUID
+ if USE_NV_BINDING:
+ uuid = driver.cuDeviceGetUuid(self.id)
+ uuid_vals = tuple(uuid.bytes)
+ else:
+ uuid = cu_uuid()
+ driver.cuDeviceGetUuid(byref(uuid), self.id)
+ uuid_vals = tuple(bytes(uuid))
+
+ b = '%02x'
+ b2 = b * 2
+ b4 = b * 4
+ b6 = b * 6
+ fmt = f'GPU-{b4}-{b2}-{b2}-{b2}-{b6}'
+ self.uuid = fmt % uuid_vals
+
+ self.primary_context = None
+
+ def get_device_identity(self):
+ return {
+ 'pci_domain_id': self.PCI_DOMAIN_ID,
+ 'pci_bus_id': self.PCI_BUS_ID,
+ 'pci_device_id': self.PCI_DEVICE_ID,
+ }
+
+ def __repr__(self):
+ return "" % (self.id, self.name)
+
+ def __getattr__(self, attr):
+ """Read attributes lazily
+ """
+ if USE_NV_BINDING:
+ code = getattr(binding.CUdevice_attribute,
+ f'CU_DEVICE_ATTRIBUTE_{attr}')
+ value = driver.cuDeviceGetAttribute(code, self.id)
+ else:
+ try:
+ code = DEVICE_ATTRIBUTES[attr]
+ except KeyError:
+ raise AttributeError(attr)
+
+ result = c_int()
+ driver.cuDeviceGetAttribute(byref(result), code, self.id)
+ value = result.value
+
+ setattr(self, attr, value)
+ return value
+
+ def __hash__(self):
+ return hash(self.id)
+
+ def __eq__(self, other):
+ if isinstance(other, Device):
+ return self.id == other.id
+ return False
+
+ def __ne__(self, other):
+ return not (self == other)
+
+ def get_primary_context(self):
+ """
+ Returns the primary context for the device.
+ Note: it is not pushed to the CPU thread.
+ """
+ if self.primary_context is not None:
+ return self.primary_context
+
+ met_requirement_for_device(self)
+ # create primary context
+ if USE_NV_BINDING:
+ hctx = driver.cuDevicePrimaryCtxRetain(self.id)
+ else:
+ hctx = drvapi.cu_context()
+ driver.cuDevicePrimaryCtxRetain(byref(hctx), self.id)
+
+ ctx = Context(weakref.proxy(self), hctx)
+ self.primary_context = ctx
+ return ctx
+
+ def release_primary_context(self):
+ """
+ Release reference to primary context if it has been retained.
+ """
+ if self.primary_context:
+ driver.cuDevicePrimaryCtxRelease(self.id)
+ self.primary_context = None
+
+ def reset(self):
+ try:
+ if self.primary_context is not None:
+ self.primary_context.reset()
+ self.release_primary_context()
+ finally:
+ # reset at the driver level
+ driver.cuDevicePrimaryCtxReset(self.id)
+
+ @property
+ def supports_float16(self):
+ return self.compute_capability >= (5, 3)
+
+
+def met_requirement_for_device(device):
+ if device.compute_capability < MIN_REQUIRED_CC:
+ raise CudaSupportError("%s has compute capability < %s" %
+ (device, MIN_REQUIRED_CC))
+
+
+class BaseCUDAMemoryManager(object, metaclass=ABCMeta):
+ """Abstract base class for External Memory Management (EMM) Plugins."""
+
+ def __init__(self, *args, **kwargs):
+ if 'context' not in kwargs:
+ raise RuntimeError("Memory manager requires a context")
+ self.context = kwargs.pop('context')
+
+ @abstractmethod
+ def memalloc(self, size):
+ """
+ Allocate on-device memory in the current context.
+
+ :param size: Size of allocation in bytes
+ :type size: int
+ :return: A memory pointer instance that owns the allocated memory
+ :rtype: :class:`MemoryPointer`
+ """
+
+ @abstractmethod
+ def memhostalloc(self, size, mapped, portable, wc):
+ """
+ Allocate pinned host memory.
+
+ :param size: Size of the allocation in bytes
+ :type size: int
+ :param mapped: Whether the allocated memory should be mapped into the
+ CUDA address space.
+ :type mapped: bool
+ :param portable: Whether the memory will be considered pinned by all
+ contexts, and not just the calling context.
+ :type portable: bool
+ :param wc: Whether to allocate the memory as write-combined.
+ :type wc: bool
+ :return: A memory pointer instance that owns the allocated memory. The
+ return type depends on whether the region was mapped into
+ device memory.
+ :rtype: :class:`MappedMemory` or :class:`PinnedMemory`
+ """
+
+ @abstractmethod
+ def mempin(self, owner, pointer, size, mapped):
+ """
+ Pin a region of host memory that is already allocated.
+
+ :param owner: The object that owns the memory.
+ :param pointer: The pointer to the beginning of the region to pin.
+ :type pointer: int
+ :param size: The size of the region in bytes.
+ :type size: int
+ :param mapped: Whether the region should also be mapped into device
+ memory.
+ :type mapped: bool
+ :return: A memory pointer instance that refers to the allocated
+ memory.
+ :rtype: :class:`MappedMemory` or :class:`PinnedMemory`
+ """
+
+ @abstractmethod
+ def initialize(self):
+ """
+ Perform any initialization required for the EMM plugin instance to be
+ ready to use.
+
+ :return: None
+ """
+
+ @abstractmethod
+ def get_ipc_handle(self, memory):
+ """
+ Return an IPC handle from a GPU allocation.
+
+ :param memory: Memory for which the IPC handle should be created.
+ :type memory: :class:`MemoryPointer`
+ :return: IPC handle for the allocation
+ :rtype: :class:`IpcHandle`
+ """
+
+ @abstractmethod
+ def get_memory_info(self):
+ """
+ Returns ``(free, total)`` memory in bytes in the context. May raise
+ :class:`NotImplementedError`, if returning such information is not
+ practical (e.g. for a pool allocator).
+
+ :return: Memory info
+ :rtype: :class:`MemoryInfo`
+ """
+
+ @abstractmethod
+ def reset(self):
+ """
+ Clears up all memory allocated in this context.
+
+ :return: None
+ """
+
+ @abstractmethod
+ def defer_cleanup(self):
+ """
+ Returns a context manager that ensures the implementation of deferred
+ cleanup whilst it is active.
+
+ :return: Context manager
+ """
+
+ @property
+ @abstractmethod
+ def interface_version(self):
+ """
+ Returns an integer specifying the version of the EMM Plugin interface
+ supported by the plugin implementation. Should always return 1 for
+ implementations of this version of the specification.
+ """
+
+
+class HostOnlyCUDAMemoryManager(BaseCUDAMemoryManager):
+ """Base class for External Memory Management (EMM) Plugins that only
+ implement on-device allocation. A subclass need not implement the
+ ``memhostalloc`` and ``mempin`` methods.
+
+ This class also implements ``reset`` and ``defer_cleanup`` (see
+ :class:`numba.cuda.BaseCUDAMemoryManager`) for its own internal state
+ management. If an EMM Plugin based on this class also implements these
+ methods, then its implementations of these must also call the method from
+ ``super()`` to give ``HostOnlyCUDAMemoryManager`` an opportunity to do the
+ necessary work for the host allocations it is managing.
+
+ This class does not implement ``interface_version``, as it will always be
+ consistent with the version of Numba in which it is implemented. An EMM
+ Plugin subclassing this class should implement ``interface_version``
+ instead.
+ """
+
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ self.allocations = utils.UniqueDict()
+ self.deallocations = _PendingDeallocs()
+
+ def _attempt_allocation(self, allocator):
+ """
+ Attempt allocation by calling *allocator*. If an out-of-memory error
+ is raised, the pending deallocations are flushed and the allocation
+ is retried. If it fails in the second attempt, the error is reraised.
+ """
+ try:
+ return allocator()
+ except CudaAPIError as e:
+ # is out-of-memory?
+ if USE_NV_BINDING:
+ oom_code = binding.CUresult.CUDA_ERROR_OUT_OF_MEMORY
+ else:
+ oom_code = enums.CUDA_ERROR_OUT_OF_MEMORY
+
+ if e.code == oom_code:
+ # clear pending deallocations
+ self.deallocations.clear()
+ # try again
+ return allocator()
+ else:
+ raise
+
+ def memhostalloc(self, size, mapped=False, portable=False,
+ wc=False):
+ """Implements the allocation of pinned host memory.
+
+ It is recommended that this method is not overridden by EMM Plugin
+ implementations - instead, use the :class:`BaseCUDAMemoryManager`.
+ """
+ flags = 0
+ if mapped:
+ flags |= enums.CU_MEMHOSTALLOC_DEVICEMAP
+ if portable:
+ flags |= enums.CU_MEMHOSTALLOC_PORTABLE
+ if wc:
+ flags |= enums.CU_MEMHOSTALLOC_WRITECOMBINED
+
+ if USE_NV_BINDING:
+ def allocator():
+ return driver.cuMemHostAlloc(size, flags)
+
+ if mapped:
+ pointer = self._attempt_allocation(allocator)
+ else:
+ pointer = allocator()
+
+ alloc_key = pointer
+ else:
+ pointer = c_void_p()
+
+ def allocator():
+ driver.cuMemHostAlloc(byref(pointer), size, flags)
+
+ if mapped:
+ self._attempt_allocation(allocator)
+ else:
+ allocator()
+
+ alloc_key = pointer.value
+
+ finalizer = _hostalloc_finalizer(self, pointer, alloc_key, size, mapped)
+ ctx = weakref.proxy(self.context)
+
+ if mapped:
+ mem = MappedMemory(ctx, pointer, size, finalizer=finalizer)
+ self.allocations[alloc_key] = mem
+ return mem.own()
+ else:
+ return PinnedMemory(ctx, pointer, size, finalizer=finalizer)
+
+ def mempin(self, owner, pointer, size, mapped=False):
+ """Implements the pinning of host memory.
+
+ It is recommended that this method is not overridden by EMM Plugin
+ implementations - instead, use the :class:`BaseCUDAMemoryManager`.
+ """
+ if isinstance(pointer, int) and not USE_NV_BINDING:
+ pointer = c_void_p(pointer)
+
+ if USE_NV_BINDING:
+ alloc_key = pointer
+ else:
+ alloc_key = pointer.value
+
+ # possible flags are "portable" (between context)
+ # and "device-map" (map host memory to device thus no need
+ # for memory transfer).
+ flags = 0
+
+ if mapped:
+ flags |= enums.CU_MEMHOSTREGISTER_DEVICEMAP
+
+ def allocator():
+ driver.cuMemHostRegister(pointer, size, flags)
+
+ if mapped:
+ self._attempt_allocation(allocator)
+ else:
+ allocator()
+
+ finalizer = _pin_finalizer(self, pointer, alloc_key, mapped)
+ ctx = weakref.proxy(self.context)
+
+ if mapped:
+ mem = MappedMemory(ctx, pointer, size, owner=owner,
+ finalizer=finalizer)
+ self.allocations[alloc_key] = mem
+ return mem.own()
+ else:
+ return PinnedMemory(ctx, pointer, size, owner=owner,
+ finalizer=finalizer)
+
+ def memallocmanaged(self, size, attach_global):
+ if USE_NV_BINDING:
+ def allocator():
+ ma_flags = binding.CUmemAttach_flags
+
+ if attach_global:
+ flags = ma_flags.CU_MEM_ATTACH_GLOBAL.value
+ else:
+ flags = ma_flags.CU_MEM_ATTACH_HOST.value
+
+ return driver.cuMemAllocManaged(size, flags)
+
+ ptr = self._attempt_allocation(allocator)
+
+ alloc_key = ptr
+
+ else:
+ ptr = drvapi.cu_device_ptr()
+
+ def allocator():
+ flags = c_uint()
+ if attach_global:
+ flags = enums.CU_MEM_ATTACH_GLOBAL
+ else:
+ flags = enums.CU_MEM_ATTACH_HOST
+
+ driver.cuMemAllocManaged(byref(ptr), size, flags)
+
+ self._attempt_allocation(allocator)
+
+ alloc_key = ptr.value
+
+ finalizer = _alloc_finalizer(self, ptr, alloc_key, size)
+ ctx = weakref.proxy(self.context)
+ mem = ManagedMemory(ctx, ptr, size, finalizer=finalizer)
+ self.allocations[alloc_key] = mem
+ return mem.own()
+
+ def reset(self):
+ """Clears up all host memory (mapped and/or pinned) in the current
+ context.
+
+ EMM Plugins that override this method must call ``super().reset()`` to
+ ensure that host allocations are also cleaned up."""
+ self.allocations.clear()
+ self.deallocations.clear()
+
+ @contextlib.contextmanager
+ def defer_cleanup(self):
+ """Returns a context manager that disables cleanup of mapped or pinned
+ host memory in the current context whilst it is active.
+
+ EMM Plugins that override this method must obtain the context manager
+ from this method before yielding to ensure that cleanup of host
+ allocations is also deferred."""
+ with self.deallocations.disable():
+ yield
+
+
+class GetIpcHandleMixin:
+ """A class that provides a default implementation of ``get_ipc_handle()``.
+ """
+
+ def get_ipc_handle(self, memory):
+ """Open an IPC memory handle by using ``cuMemGetAddressRange`` to
+ determine the base pointer of the allocation. An IPC handle of type
+ ``cu_ipc_mem_handle`` is constructed and initialized with
+ ``cuIpcGetMemHandle``. A :class:`numba.cuda.IpcHandle` is returned,
+ populated with the underlying ``ipc_mem_handle``.
+ """
+ base, end = device_extents(memory)
+ if USE_NV_BINDING:
+ ipchandle = driver.cuIpcGetMemHandle(base)
+ offset = int(memory.handle) - int(base)
+ else:
+ ipchandle = drvapi.cu_ipc_mem_handle()
+ driver.cuIpcGetMemHandle(byref(ipchandle), base)
+ offset = memory.handle.value - base
+ source_info = self.context.device.get_device_identity()
+
+ return IpcHandle(memory, ipchandle, memory.size, source_info,
+ offset=offset)
+
+
+class NumbaCUDAMemoryManager(GetIpcHandleMixin, HostOnlyCUDAMemoryManager):
+ """Internal on-device memory management for Numba. This is implemented using
+ the EMM Plugin interface, but is not part of the public API."""
+
+ def initialize(self):
+ # Set the memory capacity of *deallocations* as the memory manager
+ # becomes active for the first time
+ if self.deallocations.memory_capacity == _SizeNotSet:
+ self.deallocations.memory_capacity = self.get_memory_info().total
+
+ def memalloc(self, size):
+ if USE_NV_BINDING:
+ def allocator():
+ return driver.cuMemAlloc(size)
+
+ ptr = self._attempt_allocation(allocator)
+ alloc_key = ptr
+ else:
+ ptr = drvapi.cu_device_ptr()
+
+ def allocator():
+ driver.cuMemAlloc(byref(ptr), size)
+
+ self._attempt_allocation(allocator)
+ alloc_key = ptr.value
+
+ finalizer = _alloc_finalizer(self, ptr, alloc_key, size)
+ ctx = weakref.proxy(self.context)
+ mem = AutoFreePointer(ctx, ptr, size, finalizer=finalizer)
+ self.allocations[alloc_key] = mem
+ return mem.own()
+
+ def get_memory_info(self):
+ if USE_NV_BINDING:
+ free, total = driver.cuMemGetInfo()
+ else:
+ free = c_size_t()
+ total = c_size_t()
+ driver.cuMemGetInfo(byref(free), byref(total))
+ free = free.value
+ total = total.value
+
+ return MemoryInfo(free=free, total=total)
+
+ @property
+ def interface_version(self):
+ return _SUPPORTED_EMM_INTERFACE_VERSION
+
+
+_SUPPORTED_EMM_INTERFACE_VERSION = 1
+
+_memory_manager = None
+
+
+def _ensure_memory_manager():
+ global _memory_manager
+
+ if _memory_manager:
+ return
+
+ if config.CUDA_MEMORY_MANAGER == 'default':
+ _memory_manager = NumbaCUDAMemoryManager
+ return
+
+ try:
+ mgr_module = importlib.import_module(config.CUDA_MEMORY_MANAGER)
+ set_memory_manager(mgr_module._numba_memory_manager)
+ except Exception:
+ raise RuntimeError("Failed to use memory manager from %s" %
+ config.CUDA_MEMORY_MANAGER)
+
+
+def set_memory_manager(mm_plugin):
+ """Configure Numba to use an External Memory Management (EMM) Plugin. If
+ the EMM Plugin version does not match one supported by this version of
+ Numba, a RuntimeError will be raised.
+
+ :param mm_plugin: The class implementing the EMM Plugin.
+ :type mm_plugin: BaseCUDAMemoryManager
+ :return: None
+ """
+ global _memory_manager
+
+ dummy = mm_plugin(context=None)
+ iv = dummy.interface_version
+ if iv != _SUPPORTED_EMM_INTERFACE_VERSION:
+ err = "EMM Plugin interface has version %d - version %d required" \
+ % (iv, _SUPPORTED_EMM_INTERFACE_VERSION)
+ raise RuntimeError(err)
+
+ _memory_manager = mm_plugin
+
+
+class _SizeNotSet(int):
+ """
+ Dummy object for _PendingDeallocs when *size* is not set.
+ """
+
+ def __new__(cls, *args, **kwargs):
+ return super().__new__(cls, 0)
+
+ def __str__(self):
+ return '?'
+
+
+_SizeNotSet = _SizeNotSet()
+
+
+class _PendingDeallocs(object):
+ """
+ Pending deallocations of a context (or device since we are using the primary
+ context). The capacity defaults to being unset (_SizeNotSet) but can be
+ modified later once the driver is initialized and the total memory capacity
+ known.
+ """
+ def __init__(self, capacity=_SizeNotSet):
+ self._cons = deque()
+ self._disable_count = 0
+ self._size = 0
+ self.memory_capacity = capacity
+
+ @property
+ def _max_pending_bytes(self):
+ return int(self.memory_capacity * config.CUDA_DEALLOCS_RATIO)
+
+ def add_item(self, dtor, handle, size=_SizeNotSet):
+ """
+ Add a pending deallocation.
+
+ The *dtor* arg is the destructor function that takes an argument,
+ *handle*. It is used as ``dtor(handle)``. The *size* arg is the
+ byte size of the resource added. It is an optional argument. Some
+ resources (e.g. CUModule) has an unknown memory footprint on the device.
+ """
+ _logger.info('add pending dealloc: %s %s bytes', dtor.__name__, size)
+ self._cons.append((dtor, handle, size))
+ self._size += int(size)
+ if (len(self._cons) > config.CUDA_DEALLOCS_COUNT or
+ self._size > self._max_pending_bytes):
+ self.clear()
+
+ def clear(self):
+ """
+ Flush any pending deallocations unless it is disabled.
+ Do nothing if disabled.
+ """
+ if not self.is_disabled:
+ while self._cons:
+ [dtor, handle, size] = self._cons.popleft()
+ _logger.info('dealloc: %s %s bytes', dtor.__name__, size)
+ dtor(handle)
+ self._size = 0
+
+ @contextlib.contextmanager
+ def disable(self):
+ """
+ Context manager to temporarily disable flushing pending deallocation.
+ This can be nested.
+ """
+ self._disable_count += 1
+ try:
+ yield
+ finally:
+ self._disable_count -= 1
+ assert self._disable_count >= 0
+
+ @property
+ def is_disabled(self):
+ return self._disable_count > 0
+
+ def __len__(self):
+ """
+ Returns number of pending deallocations.
+ """
+ return len(self._cons)
+
+
+MemoryInfo = namedtuple("MemoryInfo", "free,total")
+"""Free and total memory for a device.
+
+.. py:attribute:: free
+
+ Free device memory in bytes.
+
+.. py:attribute:: total
+
+ Total device memory in bytes.
+"""
+
+
+class Context(object):
+ """
+ This object wraps a CUDA Context resource.
+
+ Contexts should not be constructed directly by user code.
+ """
+
+ def __init__(self, device, handle):
+ self.device = device
+ self.handle = handle
+ self.allocations = utils.UniqueDict()
+ self.deallocations = _PendingDeallocs()
+ _ensure_memory_manager()
+ self.memory_manager = _memory_manager(context=self)
+ self.modules = utils.UniqueDict()
+ # For storing context specific data
+ self.extras = {}
+
+ def reset(self):
+ """
+ Clean up all owned resources in this context.
+ """
+ # Free owned resources
+ _logger.info('reset context of device %s', self.device.id)
+ self.memory_manager.reset()
+ self.modules.clear()
+ # Clear trash
+ self.deallocations.clear()
+
+ def get_memory_info(self):
+ """Returns (free, total) memory in bytes in the context.
+ """
+ return self.memory_manager.get_memory_info()
+
+ def get_active_blocks_per_multiprocessor(self, func, blocksize, memsize,
+ flags=None):
+ """Return occupancy of a function.
+ :param func: kernel for which occupancy is calculated
+ :param blocksize: block size the kernel is intended to be launched with
+ :param memsize: per-block dynamic shared memory usage intended, in bytes
+ """
+ args = (func, blocksize, memsize, flags)
+ if USE_NV_BINDING:
+ return self._cuda_python_active_blocks_per_multiprocessor(*args)
+ else:
+ return self._ctypes_active_blocks_per_multiprocessor(*args)
+
+ def _cuda_python_active_blocks_per_multiprocessor(self, func, blocksize,
+ memsize, flags):
+ ps = [func.handle, blocksize, memsize]
+
+ if not flags:
+ return driver.cuOccupancyMaxActiveBlocksPerMultiprocessor(*ps)
+
+ ps.append(flags)
+ return driver.cuOccupancyMaxActiveBlocksPerMultiprocessorWithFlags(*ps)
+
+ def _ctypes_active_blocks_per_multiprocessor(self, func, blocksize,
+ memsize, flags):
+ retval = c_int()
+ args = (byref(retval), func.handle, blocksize, memsize)
+
+ if not flags:
+ driver.cuOccupancyMaxActiveBlocksPerMultiprocessor(*args)
+ else:
+ driver.cuOccupancyMaxActiveBlocksPerMultiprocessorWithFlags(*args)
+
+ return retval.value
+
+ def get_max_potential_block_size(self, func, b2d_func, memsize,
+ blocksizelimit, flags=None):
+ """Suggest a launch configuration with reasonable occupancy.
+ :param func: kernel for which occupancy is calculated
+ :param b2d_func: function that calculates how much per-block dynamic
+ shared memory 'func' uses based on the block size.
+ Can also be the address of a C function.
+ Use `0` to pass `NULL` to the underlying CUDA API.
+ :param memsize: per-block dynamic shared memory usage intended, in bytes
+ :param blocksizelimit: maximum block size the kernel is designed to
+ handle
+ """
+ args = (func, b2d_func, memsize, blocksizelimit, flags)
+ if USE_NV_BINDING:
+ return self._cuda_python_max_potential_block_size(*args)
+ else:
+ return self._ctypes_max_potential_block_size(*args)
+
+ def _ctypes_max_potential_block_size(self, func, b2d_func, memsize,
+ blocksizelimit, flags):
+ gridsize = c_int()
+ blocksize = c_int()
+ b2d_cb = cu_occupancy_b2d_size(b2d_func)
+ args = [byref(gridsize), byref(blocksize), func.handle, b2d_cb,
+ memsize, blocksizelimit]
+
+ if not flags:
+ driver.cuOccupancyMaxPotentialBlockSize(*args)
+ else:
+ args.append(flags)
+ driver.cuOccupancyMaxPotentialBlockSizeWithFlags(*args)
+
+ return (gridsize.value, blocksize.value)
+
+ def _cuda_python_max_potential_block_size(self, func, b2d_func, memsize,
+ blocksizelimit, flags):
+ b2d_cb = ctypes.CFUNCTYPE(c_size_t, c_int)(b2d_func)
+ ptr = int.from_bytes(b2d_cb, byteorder='little')
+ driver_b2d_cb = binding.CUoccupancyB2DSize(ptr)
+ args = [func.handle, driver_b2d_cb, memsize, blocksizelimit]
+
+ if not flags:
+ return driver.cuOccupancyMaxPotentialBlockSize(*args)
+ else:
+ args.append(flags)
+ return driver.cuOccupancyMaxPotentialBlockSizeWithFlags(*args)
+
+ def prepare_for_use(self):
+ """Initialize the context for use.
+ It's safe to be called multiple times.
+ """
+ self.memory_manager.initialize()
+
+ def push(self):
+ """
+ Pushes this context on the current CPU Thread.
+ """
+ driver.cuCtxPushCurrent(self.handle)
+ self.prepare_for_use()
+
+ def pop(self):
+ """
+ Pops this context off the current CPU thread. Note that this context
+ must be at the top of the context stack, otherwise an error will occur.
+ """
+ popped = driver.pop_active_context()
+ if USE_NV_BINDING:
+ assert int(popped) == int(self.handle)
+ else:
+ assert popped.value == self.handle.value
+
+ def memalloc(self, bytesize):
+ return self.memory_manager.memalloc(bytesize)
+
+ def memallocmanaged(self, bytesize, attach_global=True):
+ return self.memory_manager.memallocmanaged(bytesize, attach_global)
+
+ def memhostalloc(self, bytesize, mapped=False, portable=False, wc=False):
+ return self.memory_manager.memhostalloc(bytesize, mapped, portable, wc)
+
+ def mempin(self, owner, pointer, size, mapped=False):
+ if mapped and not self.device.CAN_MAP_HOST_MEMORY:
+ raise CudaDriverError("%s cannot map host memory" % self.device)
+ return self.memory_manager.mempin(owner, pointer, size, mapped)
+
+ def get_ipc_handle(self, memory):
+ """
+ Returns an *IpcHandle* from a GPU allocation.
+ """
+ if not SUPPORTS_IPC:
+ raise OSError('OS does not support CUDA IPC')
+ return self.memory_manager.get_ipc_handle(memory)
+
+ def open_ipc_handle(self, handle, size):
+ # open the IPC handle to get the device pointer
+ flags = 1 # CU_IPC_MEM_LAZY_ENABLE_PEER_ACCESS
+ if USE_NV_BINDING:
+ dptr = driver.cuIpcOpenMemHandle(handle, flags)
+ else:
+ dptr = drvapi.cu_device_ptr()
+ driver.cuIpcOpenMemHandle(byref(dptr), handle, flags)
+
+ # wrap it
+ return MemoryPointer(context=weakref.proxy(self), pointer=dptr,
+ size=size)
+
+ def enable_peer_access(self, peer_context, flags=0):
+ """Enable peer access between the current context and the peer context
+ """
+ assert flags == 0, '*flags* is reserved and MUST be zero'
+ driver.cuCtxEnablePeerAccess(peer_context, flags)
+
+ def can_access_peer(self, peer_device):
+ """Returns a bool indicating whether the peer access between the
+ current and peer device is possible.
+ """
+ if USE_NV_BINDING:
+ peer_device = binding.CUdevice(peer_device)
+ can_access_peer = driver.cuDeviceCanAccessPeer(self.device.id,
+ peer_device)
+ else:
+ can_access_peer = c_int()
+ driver.cuDeviceCanAccessPeer(byref(can_access_peer),
+ self.device.id, peer_device,)
+
+ return bool(can_access_peer)
+
+ def create_module_ptx(self, ptx):
+ if isinstance(ptx, str):
+ ptx = ptx.encode('utf8')
+ if USE_NV_BINDING:
+ image = ptx
+ else:
+ image = c_char_p(ptx)
+ return self.create_module_image(image)
+
+ def create_module_image(self, image):
+ module = load_module_image(self, image)
+ if USE_NV_BINDING:
+ key = module.handle
+ else:
+ key = module.handle.value
+ self.modules[key] = module
+ return weakref.proxy(module)
+
+ def unload_module(self, module):
+ if USE_NV_BINDING:
+ key = module.handle
+ else:
+ key = module.handle.value
+ del self.modules[key]
+
+ def get_default_stream(self):
+ if USE_NV_BINDING:
+ handle = binding.CUstream(CU_STREAM_DEFAULT)
+ else:
+ handle = drvapi.cu_stream(drvapi.CU_STREAM_DEFAULT)
+ return Stream(weakref.proxy(self), handle, None)
+
+ def get_legacy_default_stream(self):
+ if USE_NV_BINDING:
+ handle = binding.CUstream(binding.CU_STREAM_LEGACY)
+ else:
+ handle = drvapi.cu_stream(drvapi.CU_STREAM_LEGACY)
+ return Stream(weakref.proxy(self), handle, None)
+
+ def get_per_thread_default_stream(self):
+ if USE_NV_BINDING:
+ handle = binding.CUstream(binding.CU_STREAM_PER_THREAD)
+ else:
+ handle = drvapi.cu_stream(drvapi.CU_STREAM_PER_THREAD)
+ return Stream(weakref.proxy(self), handle, None)
+
+ def create_stream(self):
+ if USE_NV_BINDING:
+ # The default stream creation flag, specifying that the created
+ # stream synchronizes with stream 0 (this is different from the
+ # default stream, which we define also as CU_STREAM_DEFAULT when
+ # the NV binding is in use).
+ flags = binding.CUstream_flags.CU_STREAM_DEFAULT.value
+ handle = driver.cuStreamCreate(flags)
+ else:
+ handle = drvapi.cu_stream()
+ driver.cuStreamCreate(byref(handle), 0)
+ return Stream(weakref.proxy(self), handle,
+ _stream_finalizer(self.deallocations, handle))
+
+ def create_external_stream(self, ptr):
+ if not isinstance(ptr, int):
+ raise TypeError("ptr for external stream must be an int")
+ if USE_NV_BINDING:
+ handle = binding.CUstream(ptr)
+ else:
+ handle = drvapi.cu_stream(ptr)
+ return Stream(weakref.proxy(self), handle, None,
+ external=True)
+
+ def create_event(self, timing=True):
+ flags = 0
+ if not timing:
+ flags |= enums.CU_EVENT_DISABLE_TIMING
+ if USE_NV_BINDING:
+ handle = driver.cuEventCreate(flags)
+ else:
+ handle = drvapi.cu_event()
+ driver.cuEventCreate(byref(handle), flags)
+ return Event(weakref.proxy(self), handle,
+ finalizer=_event_finalizer(self.deallocations, handle))
+
+ def synchronize(self):
+ driver.cuCtxSynchronize()
+
+ @contextlib.contextmanager
+ def defer_cleanup(self):
+ with self.memory_manager.defer_cleanup():
+ with self.deallocations.disable():
+ yield
+
+ def __repr__(self):
+ return "" % (self.handle, self.device.id)
+
+ def __eq__(self, other):
+ if isinstance(other, Context):
+ return self.handle == other.handle
+ else:
+ return NotImplemented
+
+ def __ne__(self, other):
+ return not self.__eq__(other)
+
+
+def load_module_image(context, image):
+ """
+ image must be a pointer
+ """
+ if USE_NV_BINDING:
+ return load_module_image_cuda_python(context, image)
+ else:
+ return load_module_image_ctypes(context, image)
+
+
+def load_module_image_ctypes(context, image):
+ logsz = config.CUDA_LOG_SIZE
+
+ jitinfo = (c_char * logsz)()
+ jiterrors = (c_char * logsz)()
+
+ options = {
+ enums.CU_JIT_INFO_LOG_BUFFER: addressof(jitinfo),
+ enums.CU_JIT_INFO_LOG_BUFFER_SIZE_BYTES: c_void_p(logsz),
+ enums.CU_JIT_ERROR_LOG_BUFFER: addressof(jiterrors),
+ enums.CU_JIT_ERROR_LOG_BUFFER_SIZE_BYTES: c_void_p(logsz),
+ enums.CU_JIT_LOG_VERBOSE: c_void_p(config.CUDA_VERBOSE_JIT_LOG),
+ }
+
+ option_keys = (drvapi.cu_jit_option * len(options))(*options.keys())
+ option_vals = (c_void_p * len(options))(*options.values())
+
+ handle = drvapi.cu_module()
+ try:
+ driver.cuModuleLoadDataEx(byref(handle), image, len(options),
+ option_keys, option_vals)
+ except CudaAPIError as e:
+ msg = "cuModuleLoadDataEx error:\n%s" % jiterrors.value.decode("utf8")
+ raise CudaAPIError(e.code, msg)
+
+ info_log = jitinfo.value
+
+ return CtypesModule(weakref.proxy(context), handle, info_log,
+ _module_finalizer(context, handle))
+
+
+def load_module_image_cuda_python(context, image):
+ """
+ image must be a pointer
+ """
+ logsz = config.CUDA_LOG_SIZE
+
+ jitinfo = bytearray(logsz)
+ jiterrors = bytearray(logsz)
+
+ jit_option = binding.CUjit_option
+ options = {
+ jit_option.CU_JIT_INFO_LOG_BUFFER: jitinfo,
+ jit_option.CU_JIT_INFO_LOG_BUFFER_SIZE_BYTES: logsz,
+ jit_option.CU_JIT_ERROR_LOG_BUFFER: jiterrors,
+ jit_option.CU_JIT_ERROR_LOG_BUFFER_SIZE_BYTES: logsz,
+ jit_option.CU_JIT_LOG_VERBOSE: config.CUDA_VERBOSE_JIT_LOG,
+ }
+
+ option_keys = [k for k in options.keys()]
+ option_vals = [v for v in options.values()]
+
+ try:
+ handle = driver.cuModuleLoadDataEx(image, len(options), option_keys,
+ option_vals)
+ except CudaAPIError as e:
+ err_string = jiterrors.decode('utf-8')
+ msg = "cuModuleLoadDataEx error:\n%s" % err_string
+ raise CudaAPIError(e.code, msg)
+
+ info_log = jitinfo.decode('utf-8')
+
+ return CudaPythonModule(weakref.proxy(context), handle, info_log,
+ _module_finalizer(context, handle))
+
+
+def _alloc_finalizer(memory_manager, ptr, alloc_key, size):
+ allocations = memory_manager.allocations
+ deallocations = memory_manager.deallocations
+
+ def core():
+ if allocations:
+ del allocations[alloc_key]
+ deallocations.add_item(driver.cuMemFree, ptr, size)
+
+ return core
+
+
+def _hostalloc_finalizer(memory_manager, ptr, alloc_key, size, mapped):
+ """
+ Finalize page-locked host memory allocated by `context.memhostalloc`.
+
+ This memory is managed by CUDA, and finalization entails deallocation. The
+ issues noted in `_pin_finalizer` are not relevant in this case, and the
+ finalization is placed in the `context.deallocations` queue along with
+ finalization of device objects.
+
+ """
+ allocations = memory_manager.allocations
+ deallocations = memory_manager.deallocations
+ if not mapped:
+ size = _SizeNotSet
+
+ def core():
+ if mapped and allocations:
+ del allocations[alloc_key]
+ deallocations.add_item(driver.cuMemFreeHost, ptr, size)
+
+ return core
+
+
+def _pin_finalizer(memory_manager, ptr, alloc_key, mapped):
+ """
+ Finalize temporary page-locking of host memory by `context.mempin`.
+
+ This applies to memory not otherwise managed by CUDA. Page-locking can
+ be requested multiple times on the same memory, and must therefore be
+ lifted as soon as finalization is requested, otherwise subsequent calls to
+ `mempin` may fail with `CUDA_ERROR_HOST_MEMORY_ALREADY_REGISTERED`, leading
+ to unexpected behavior for the context managers `cuda.{pinned,mapped}`.
+ This function therefore carries out finalization immediately, bypassing the
+ `context.deallocations` queue.
+
+ """
+ allocations = memory_manager.allocations
+
+ def core():
+ if mapped and allocations:
+ del allocations[alloc_key]
+ driver.cuMemHostUnregister(ptr)
+
+ return core
+
+
+def _event_finalizer(deallocs, handle):
+ def core():
+ deallocs.add_item(driver.cuEventDestroy, handle)
+
+ return core
+
+
+def _stream_finalizer(deallocs, handle):
+ def core():
+ deallocs.add_item(driver.cuStreamDestroy, handle)
+
+ return core
+
+
+def _module_finalizer(context, handle):
+ dealloc = context.deallocations
+ modules = context.modules
+
+ if USE_NV_BINDING:
+ key = handle
+ else:
+ key = handle.value
+
+ def core():
+ shutting_down = utils.shutting_down # early bind
+
+ def module_unload(handle):
+ # If we are not shutting down, we must be called due to
+ # Context.reset() of Context.unload_module(). Both must have
+ # cleared the module reference from the context.
+ assert shutting_down() or key not in modules
+ driver.cuModuleUnload(handle)
+
+ dealloc.add_item(module_unload, handle)
+
+ return core
+
+
+class _CudaIpcImpl(object):
+ """Implementation of GPU IPC using CUDA driver API.
+ This requires the devices to be peer accessible.
+ """
+ def __init__(self, parent):
+ self.base = parent.base
+ self.handle = parent.handle
+ self.size = parent.size
+ self.offset = parent.offset
+ # remember if the handle is already opened
+ self._opened_mem = None
+
+ def open(self, context):
+ """
+ Import the IPC memory and returns a raw CUDA memory pointer object
+ """
+ if self.base is not None:
+ raise ValueError('opening IpcHandle from original process')
+
+ if self._opened_mem is not None:
+ raise ValueError('IpcHandle is already opened')
+
+ mem = context.open_ipc_handle(self.handle, self.offset + self.size)
+ # this object owns the opened allocation
+ # note: it is required the memory be freed after the ipc handle is
+ # closed by the importing context.
+ self._opened_mem = mem
+ return mem.own().view(self.offset)
+
+ def close(self):
+ if self._opened_mem is None:
+ raise ValueError('IpcHandle not opened')
+ driver.cuIpcCloseMemHandle(self._opened_mem.handle)
+ self._opened_mem = None
+
+
+class _StagedIpcImpl(object):
+ """Implementation of GPU IPC using custom staging logic to workaround
+ CUDA IPC limitation on peer accessibility between devices.
+ """
+ def __init__(self, parent, source_info):
+ self.parent = parent
+ self.base = parent.base
+ self.handle = parent.handle
+ self.size = parent.size
+ self.source_info = source_info
+
+ def open(self, context):
+ from numba import cuda
+
+ srcdev = Device.from_identity(self.source_info)
+ if USE_NV_BINDING:
+ srcdev_id = int(srcdev.id)
+ else:
+ srcdev_id = srcdev.id
+
+ impl = _CudaIpcImpl(parent=self.parent)
+ # Open context on the source device.
+ with cuda.gpus[srcdev_id]:
+ source_ptr = impl.open(cuda.devices.get_context())
+
+ # Allocate GPU buffer.
+ newmem = context.memalloc(self.size)
+ # Do D->D from the source peer-context
+ # This performs automatic host staging
+ device_to_device(newmem, source_ptr, self.size)
+
+ # Cleanup source context
+ with cuda.gpus[srcdev_id]:
+ impl.close()
+
+ return newmem
+
+ def close(self):
+ # Nothing has to be done here
+ pass
+
+
+class IpcHandle(object):
+ """
+ CUDA IPC handle. Serialization of the CUDA IPC handle object is implemented
+ here.
+
+ :param base: A reference to the original allocation to keep it alive
+ :type base: MemoryPointer
+ :param handle: The CUDA IPC handle, as a ctypes array of bytes.
+ :param size: Size of the original allocation
+ :type size: int
+ :param source_info: The identity of the device on which the IPC handle was
+ opened.
+ :type source_info: dict
+ :param offset: The offset into the underlying allocation of the memory
+ referred to by this IPC handle.
+ :type offset: int
+ """
+ def __init__(self, base, handle, size, source_info=None, offset=0):
+ self.base = base
+ self.handle = handle
+ self.size = size
+ self.source_info = source_info
+ self._impl = None
+ self.offset = offset
+
+ def _sentry_source_info(self):
+ if self.source_info is None:
+ raise RuntimeError("IPC handle doesn't have source info")
+
+ def can_access_peer(self, context):
+ """Returns a bool indicating whether the active context can peer
+ access the IPC handle
+ """
+ self._sentry_source_info()
+ if self.source_info == context.device.get_device_identity():
+ return True
+ source_device = Device.from_identity(self.source_info)
+ return context.can_access_peer(source_device.id)
+
+ def open_staged(self, context):
+ """Open the IPC by allowing staging on the host memory first.
+ """
+ self._sentry_source_info()
+
+ if self._impl is not None:
+ raise ValueError('IpcHandle is already opened')
+
+ self._impl = _StagedIpcImpl(self, self.source_info)
+ return self._impl.open(context)
+
+ def open_direct(self, context):
+ """
+ Import the IPC memory and returns a raw CUDA memory pointer object
+ """
+ if self._impl is not None:
+ raise ValueError('IpcHandle is already opened')
+
+ self._impl = _CudaIpcImpl(self)
+ return self._impl.open(context)
+
+ def open(self, context):
+ """Open the IPC handle and import the memory for usage in the given
+ context. Returns a raw CUDA memory pointer object.
+
+ This is enhanced over CUDA IPC that it will work regardless of whether
+ the source device is peer-accessible by the destination device.
+ If the devices are peer-accessible, it uses .open_direct().
+ If the devices are not peer-accessible, it uses .open_staged().
+ """
+ if self.source_info is None or self.can_access_peer(context):
+ fn = self.open_direct
+ else:
+ fn = self.open_staged
+ return fn(context)
+
+ def open_array(self, context, shape, dtype, strides=None):
+ """
+ Similar to `.open()` but returns an device array.
+ """
+ from . import devicearray
+
+ # by default, set strides to itemsize
+ if strides is None:
+ strides = dtype.itemsize
+ dptr = self.open(context)
+ # read the device pointer as an array
+ return devicearray.DeviceNDArray(shape=shape, strides=strides,
+ dtype=dtype, gpu_data=dptr)
+
+ def close(self):
+ if self._impl is None:
+ raise ValueError('IpcHandle not opened')
+ self._impl.close()
+ self._impl = None
+
+ def __reduce__(self):
+ # Preprocess the IPC handle, which is defined as a byte array.
+ if USE_NV_BINDING:
+ preprocessed_handle = self.handle.reserved
+ else:
+ preprocessed_handle = tuple(self.handle)
+ args = (
+ self.__class__,
+ preprocessed_handle,
+ self.size,
+ self.source_info,
+ self.offset,
+ )
+ return (serialize._rebuild_reduction, args)
+
+ @classmethod
+ def _rebuild(cls, handle_ary, size, source_info, offset):
+ if USE_NV_BINDING:
+ handle = binding.CUipcMemHandle()
+ handle.reserved = handle_ary
+ else:
+ handle = drvapi.cu_ipc_mem_handle(*handle_ary)
+ return cls(base=None, handle=handle, size=size,
+ source_info=source_info, offset=offset)
+
+
+class MemoryPointer(object):
+ """A memory pointer that owns a buffer, with an optional finalizer. Memory
+ pointers provide reference counting, and instances are initialized with a
+ reference count of 1.
+
+ The base ``MemoryPointer`` class does not use the
+ reference count for managing the buffer lifetime. Instead, the buffer
+ lifetime is tied to the memory pointer instance's lifetime:
+
+ - When the instance is deleted, the finalizer will be called.
+ - When the reference count drops to 0, no action is taken.
+
+ Subclasses of ``MemoryPointer`` may modify these semantics, for example to
+ tie the buffer lifetime to the reference count, so that the buffer is freed
+ when there are no more references.
+
+ :param context: The context in which the pointer was allocated.
+ :type context: Context
+ :param pointer: The address of the buffer.
+ :type pointer: ctypes.c_void_p
+ :param size: The size of the allocation in bytes.
+ :type size: int
+ :param owner: The owner is sometimes set by the internals of this class, or
+ used for Numba's internal memory management. It should not be
+ provided by an external user of the ``MemoryPointer`` class
+ (e.g. from within an EMM Plugin); the default of `None`
+ should always suffice.
+ :type owner: NoneType
+ :param finalizer: A function that is called when the buffer is to be freed.
+ :type finalizer: function
+ """
+ __cuda_memory__ = True
+
+ def __init__(self, context, pointer, size, owner=None, finalizer=None):
+ self.context = context
+ self.device_pointer = pointer
+ self.size = size
+ self._cuda_memsize_ = size
+ self.is_managed = finalizer is not None
+ self.refct = 1
+ self.handle = self.device_pointer
+ self._owner = owner
+
+ if finalizer is not None:
+ self._finalizer = weakref.finalize(self, finalizer)
+
+ @property
+ def owner(self):
+ return self if self._owner is None else self._owner
+
+ def own(self):
+ return OwnedPointer(weakref.proxy(self))
+
+ def free(self):
+ """
+ Forces the device memory to the trash.
+ """
+ if self.is_managed:
+ if not self._finalizer.alive:
+ raise RuntimeError("Freeing dead memory")
+ self._finalizer()
+ assert not self._finalizer.alive
+
+ def memset(self, byte, count=None, stream=0):
+ count = self.size if count is None else count
+ if stream:
+ driver.cuMemsetD8Async(self.device_pointer, byte, count,
+ stream.handle)
+ else:
+ driver.cuMemsetD8(self.device_pointer, byte, count)
+
+ def view(self, start, stop=None):
+ if stop is None:
+ size = self.size - start
+ else:
+ size = stop - start
+
+ # Handle NULL/empty memory buffer
+ if not self.device_pointer_value:
+ if size != 0:
+ raise RuntimeError("non-empty slice into empty slice")
+ view = self # new view is just a reference to self
+ # Handle normal case
+ else:
+ base = self.device_pointer_value + start
+ if size < 0:
+ raise RuntimeError('size cannot be negative')
+ if USE_NV_BINDING:
+ pointer = binding.CUdeviceptr()
+ ctypes_ptr = drvapi.cu_device_ptr.from_address(pointer.getPtr())
+ ctypes_ptr.value = base
+ else:
+ pointer = drvapi.cu_device_ptr(base)
+ view = MemoryPointer(self.context, pointer, size, owner=self.owner)
+
+ if isinstance(self.owner, (MemoryPointer, OwnedPointer)):
+ # Owned by a numba-managed memory segment, take an owned reference
+ return OwnedPointer(weakref.proxy(self.owner), view)
+ else:
+ # Owned by external alloc, return view with same external owner
+ return view
+
+ @property
+ def device_ctypes_pointer(self):
+ return self.device_pointer
+
+ @property
+ def device_pointer_value(self):
+ if USE_NV_BINDING:
+ return int(self.device_pointer) or None
+ else:
+ return self.device_pointer.value
+
+
+class AutoFreePointer(MemoryPointer):
+ """Modifies the ownership semantic of the MemoryPointer so that the
+ instance lifetime is directly tied to the number of references.
+
+ When the reference count reaches zero, the finalizer is invoked.
+
+ Constructor arguments are the same as for :class:`MemoryPointer`.
+ """
+ def __init__(self, *args, **kwargs):
+ super(AutoFreePointer, self).__init__(*args, **kwargs)
+ # Releease the self reference to the buffer, so that the finalizer
+ # is invoked if all the derived pointers are gone.
+ self.refct -= 1
+
+
+class MappedMemory(AutoFreePointer):
+ """A memory pointer that refers to a buffer on the host that is mapped into
+ device memory.
+
+ :param context: The context in which the pointer was mapped.
+ :type context: Context
+ :param pointer: The address of the buffer.
+ :type pointer: ctypes.c_void_p
+ :param size: The size of the buffer in bytes.
+ :type size: int
+ :param owner: The owner is sometimes set by the internals of this class, or
+ used for Numba's internal memory management. It should not be
+ provided by an external user of the ``MappedMemory`` class
+ (e.g. from within an EMM Plugin); the default of `None`
+ should always suffice.
+ :type owner: NoneType
+ :param finalizer: A function that is called when the buffer is to be freed.
+ :type finalizer: function
+ """
+
+ __cuda_memory__ = True
+
+ def __init__(self, context, pointer, size, owner=None, finalizer=None):
+ self.owned = owner
+ self.host_pointer = pointer
+
+ if USE_NV_BINDING:
+ devptr = driver.cuMemHostGetDevicePointer(pointer, 0)
+ self._bufptr_ = self.host_pointer
+ else:
+ devptr = drvapi.cu_device_ptr()
+ driver.cuMemHostGetDevicePointer(byref(devptr), pointer, 0)
+ self._bufptr_ = self.host_pointer.value
+
+ self.device_pointer = devptr
+ super(MappedMemory, self).__init__(context, devptr, size,
+ finalizer=finalizer)
+ self.handle = self.host_pointer
+
+ # For buffer interface
+ self._buflen_ = self.size
+
+ def own(self):
+ return MappedOwnedPointer(weakref.proxy(self))
+
+
+class PinnedMemory(mviewbuf.MemAlloc):
+ """A pointer to a pinned buffer on the host.
+
+ :param context: The context in which the pointer was mapped.
+ :type context: Context
+ :param owner: The object owning the memory. For EMM plugin implementation,
+ this ca
+ :param pointer: The address of the buffer.
+ :type pointer: ctypes.c_void_p
+ :param size: The size of the buffer in bytes.
+ :type size: int
+ :param owner: An object owning the buffer that has been pinned. For EMM
+ plugin implementation, the default of ``None`` suffices for
+ memory allocated in ``memhostalloc`` - for ``mempin``, it
+ should be the owner passed in to the ``mempin`` method.
+ :param finalizer: A function that is called when the buffer is to be freed.
+ :type finalizer: function
+ """
+
+ def __init__(self, context, pointer, size, owner=None, finalizer=None):
+ self.context = context
+ self.owned = owner
+ self.size = size
+ self.host_pointer = pointer
+ self.is_managed = finalizer is not None
+ self.handle = self.host_pointer
+
+ # For buffer interface
+ self._buflen_ = self.size
+ if USE_NV_BINDING:
+ self._bufptr_ = self.host_pointer
+ else:
+ self._bufptr_ = self.host_pointer.value
+
+ if finalizer is not None:
+ weakref.finalize(self, finalizer)
+
+ def own(self):
+ return self
+
+
+class ManagedMemory(AutoFreePointer):
+ """A memory pointer that refers to a managed memory buffer (can be accessed
+ on both host and device).
+
+ :param context: The context in which the pointer was mapped.
+ :type context: Context
+ :param pointer: The address of the buffer.
+ :type pointer: ctypes.c_void_p
+ :param size: The size of the buffer in bytes.
+ :type size: int
+ :param owner: The owner is sometimes set by the internals of this class, or
+ used for Numba's internal memory management. It should not be
+ provided by an external user of the ``ManagedMemory`` class
+ (e.g. from within an EMM Plugin); the default of `None`
+ should always suffice.
+ :type owner: NoneType
+ :param finalizer: A function that is called when the buffer is to be freed.
+ :type finalizer: function
+ """
+
+ __cuda_memory__ = True
+
+ def __init__(self, context, pointer, size, owner=None, finalizer=None):
+ self.owned = owner
+ devptr = pointer
+ super().__init__(context, devptr, size, finalizer=finalizer)
+
+ # For buffer interface
+ self._buflen_ = self.size
+ if USE_NV_BINDING:
+ self._bufptr_ = self.device_pointer
+ else:
+ self._bufptr_ = self.device_pointer.value
+
+ def own(self):
+ return ManagedOwnedPointer(weakref.proxy(self))
+
+
+class OwnedPointer(object):
+ def __init__(self, memptr, view=None):
+ self._mem = memptr
+
+ if view is None:
+ self._view = self._mem
+ else:
+ assert not view.is_managed
+ self._view = view
+
+ mem = self._mem
+
+ def deref():
+ try:
+ mem.refct -= 1
+ assert mem.refct >= 0
+ if mem.refct == 0:
+ mem.free()
+ except ReferenceError:
+ # ignore reference error here
+ pass
+
+ self._mem.refct += 1
+ weakref.finalize(self, deref)
+
+ def __getattr__(self, fname):
+ """Proxy MemoryPointer methods
+ """
+ return getattr(self._view, fname)
+
+
+class MappedOwnedPointer(OwnedPointer, mviewbuf.MemAlloc):
+ pass
+
+
+class ManagedOwnedPointer(OwnedPointer, mviewbuf.MemAlloc):
+ pass
+
+
+class Stream(object):
+ def __init__(self, context, handle, finalizer, external=False):
+ self.context = context
+ self.handle = handle
+ self.external = external
+ if finalizer is not None:
+ weakref.finalize(self, finalizer)
+
+ def __int__(self):
+ if USE_NV_BINDING:
+ return int(self.handle)
+ else:
+ # The default stream's handle.value is 0, which gives `None`
+ return self.handle.value or drvapi.CU_STREAM_DEFAULT
+
+ def __repr__(self):
+ if USE_NV_BINDING:
+ default_streams = {
+ CU_STREAM_DEFAULT: "",
+ binding.CU_STREAM_LEGACY:
+ "",
+ binding.CU_STREAM_PER_THREAD:
+ "",
+ }
+ ptr = int(self.handle) or 0
+ else:
+ default_streams = {
+ drvapi.CU_STREAM_DEFAULT: "",
+ drvapi.CU_STREAM_LEGACY: "",
+ drvapi.CU_STREAM_PER_THREAD:
+ "",
+ }
+ ptr = self.handle.value or drvapi.CU_STREAM_DEFAULT
+
+ if ptr in default_streams:
+ return default_streams[ptr] % self.context
+ elif self.external:
+ return "" % (ptr, self.context)
+ else:
+ return "" % (ptr, self.context)
+
+ def synchronize(self):
+ '''
+ Wait for all commands in this stream to execute. This will commit any
+ pending memory transfers.
+ '''
+ driver.cuStreamSynchronize(self.handle)
+
+ @contextlib.contextmanager
+ def auto_synchronize(self):
+ '''
+ A context manager that waits for all commands in this stream to execute
+ and commits any pending memory transfers upon exiting the context.
+ '''
+ yield self
+ self.synchronize()
+
+ def add_callback(self, callback, arg=None):
+ """
+ Add a callback to a compute stream.
+ The user provided function is called from a driver thread once all
+ preceding stream operations are complete.
+
+ Callback functions are called from a CUDA driver thread, not from
+ the thread that invoked `add_callback`. No CUDA API functions may
+ be called from within the callback function.
+
+ The duration of a callback function should be kept short, as the
+ callback will block later work in the stream and may block other
+ callbacks from being executed.
+
+ Note: The driver function underlying this method is marked for
+ eventual deprecation and may be replaced in a future CUDA release.
+
+ :param callback: Callback function with arguments (stream, status, arg).
+ :param arg: Optional user data to be passed to the callback function.
+ """
+ data = (self, callback, arg)
+ _py_incref(data)
+ if USE_NV_BINDING:
+ ptr = int.from_bytes(self._stream_callback, byteorder='little')
+ stream_callback = binding.CUstreamCallback(ptr)
+ # The callback needs to receive a pointer to the data PyObject
+ data = id(data)
+ else:
+ stream_callback = self._stream_callback
+ driver.cuStreamAddCallback(self.handle, stream_callback, data, 0)
+
+ @staticmethod
+ @cu_stream_callback_pyobj
+ def _stream_callback(handle, status, data):
+ try:
+ stream, callback, arg = data
+ callback(stream, status, arg)
+ except Exception as e:
+ warnings.warn(f"Exception in stream callback: {e}")
+ finally:
+ _py_decref(data)
+
+ def async_done(self) -> asyncio.futures.Future:
+ """
+ Return an awaitable that resolves once all preceding stream operations
+ are complete. The result of the awaitable is the current stream.
+ """
+ loop = asyncio.get_running_loop()
+ future = loop.create_future()
+
+ def resolver(future, status):
+ if future.done():
+ return
+ elif status == 0:
+ future.set_result(self)
+ else:
+ future.set_exception(Exception(f"Stream error {status}"))
+
+ def callback(stream, status, future):
+ loop.call_soon_threadsafe(resolver, future, status)
+
+ self.add_callback(callback, future)
+ return future
+
+
+class Event(object):
+ def __init__(self, context, handle, finalizer=None):
+ self.context = context
+ self.handle = handle
+ if finalizer is not None:
+ weakref.finalize(self, finalizer)
+
+ def query(self):
+ """
+ Returns True if all work before the most recent record has completed;
+ otherwise, returns False.
+ """
+ try:
+ driver.cuEventQuery(self.handle)
+ except CudaAPIError as e:
+ if e.code == enums.CUDA_ERROR_NOT_READY:
+ return False
+ else:
+ raise
+ else:
+ return True
+
+ def record(self, stream=0):
+ """
+ Set the record point of the event to the current point in the given
+ stream.
+
+ The event will be considered to have occurred when all work that was
+ queued in the stream at the time of the call to ``record()`` has been
+ completed.
+ """
+ if USE_NV_BINDING:
+ hstream = stream.handle if stream else binding.CUstream(0)
+ else:
+ hstream = stream.handle if stream else 0
+ driver.cuEventRecord(self.handle, hstream)
+
+ def synchronize(self):
+ """
+ Synchronize the host thread for the completion of the event.
+ """
+ driver.cuEventSynchronize(self.handle)
+
+ def wait(self, stream=0):
+ """
+ All future works submitted to stream will wait util the event completes.
+ """
+ if USE_NV_BINDING:
+ hstream = stream.handle if stream else binding.CUstream(0)
+ else:
+ hstream = stream.handle if stream else 0
+ flags = 0
+ driver.cuStreamWaitEvent(hstream, self.handle, flags)
+
+ def elapsed_time(self, evtend):
+ return event_elapsed_time(self, evtend)
+
+
+def event_elapsed_time(evtstart, evtend):
+ '''
+ Compute the elapsed time between two events in milliseconds.
+ '''
+ if USE_NV_BINDING:
+ return driver.cuEventElapsedTime(evtstart.handle, evtend.handle)
+ else:
+ msec = c_float()
+ driver.cuEventElapsedTime(byref(msec), evtstart.handle, evtend.handle)
+ return msec.value
+
+
+class Module(metaclass=ABCMeta):
+ """Abstract base class for modules"""
+
+ def __init__(self, context, handle, info_log, finalizer=None):
+ self.context = context
+ self.handle = handle
+ self.info_log = info_log
+ if finalizer is not None:
+ self._finalizer = weakref.finalize(self, finalizer)
+
+ def unload(self):
+ """Unload this module from the context"""
+ self.context.unload_module(self)
+
+ @abstractmethod
+ def get_function(self, name):
+ """Returns a Function object encapsulating the named function"""
+
+ @abstractmethod
+ def get_global_symbol(self, name):
+ """Return a MemoryPointer referring to the named symbol"""
+
+
+class CtypesModule(Module):
+
+ def get_function(self, name):
+ handle = drvapi.cu_function()
+ driver.cuModuleGetFunction(byref(handle), self.handle,
+ name.encode('utf8'))
+ return CtypesFunction(weakref.proxy(self), handle, name)
+
+ def get_global_symbol(self, name):
+ ptr = drvapi.cu_device_ptr()
+ size = drvapi.c_size_t()
+ driver.cuModuleGetGlobal(byref(ptr), byref(size), self.handle,
+ name.encode('utf8'))
+ return MemoryPointer(self.context, ptr, size), size.value
+
+
+class CudaPythonModule(Module):
+
+ def get_function(self, name):
+ handle = driver.cuModuleGetFunction(self.handle, name.encode('utf8'))
+ return CudaPythonFunction(weakref.proxy(self), handle, name)
+
+ def get_global_symbol(self, name):
+ ptr, size = driver.cuModuleGetGlobal(self.handle, name.encode('utf8'))
+ return MemoryPointer(self.context, ptr, size), size
+
+
+FuncAttr = namedtuple("FuncAttr", ["regs", "shared", "local", "const",
+ "maxthreads"])
+
+
+class Function(metaclass=ABCMeta):
+ griddim = 1, 1, 1
+ blockdim = 1, 1, 1
+ stream = 0
+ sharedmem = 0
+
+ def __init__(self, module, handle, name):
+ self.module = module
+ self.handle = handle
+ self.name = name
+ self.attrs = self.read_func_attr_all()
+
+ def __repr__(self):
+ return "" % self.name
+
+ @property
+ def device(self):
+ return self.module.context.device
+
+ @abstractmethod
+ def cache_config(self, prefer_equal=False, prefer_cache=False,
+ prefer_shared=False):
+ """Set the cache configuration for this function."""
+
+ @abstractmethod
+ def read_func_attr(self, attrid):
+ """Return the value of the attribute with given ID."""
+
+ @abstractmethod
+ def read_func_attr_all(self):
+ """Return a FuncAttr object with the values of various function
+ attributes."""
+
+
+class CtypesFunction(Function):
+
+ def cache_config(self, prefer_equal=False, prefer_cache=False,
+ prefer_shared=False):
+ prefer_equal = prefer_equal or (prefer_cache and prefer_shared)
+ if prefer_equal:
+ flag = enums.CU_FUNC_CACHE_PREFER_EQUAL
+ elif prefer_cache:
+ flag = enums.CU_FUNC_CACHE_PREFER_L1
+ elif prefer_shared:
+ flag = enums.CU_FUNC_CACHE_PREFER_SHARED
+ else:
+ flag = enums.CU_FUNC_CACHE_PREFER_NONE
+ driver.cuFuncSetCacheConfig(self.handle, flag)
+
+ def read_func_attr(self, attrid):
+ retval = c_int()
+ driver.cuFuncGetAttribute(byref(retval), attrid, self.handle)
+ return retval.value
+
+ def read_func_attr_all(self):
+ nregs = self.read_func_attr(enums.CU_FUNC_ATTRIBUTE_NUM_REGS)
+ cmem = self.read_func_attr(enums.CU_FUNC_ATTRIBUTE_CONST_SIZE_BYTES)
+ lmem = self.read_func_attr(enums.CU_FUNC_ATTRIBUTE_LOCAL_SIZE_BYTES)
+ smem = self.read_func_attr(enums.CU_FUNC_ATTRIBUTE_SHARED_SIZE_BYTES)
+ maxtpb = self.read_func_attr(
+ enums.CU_FUNC_ATTRIBUTE_MAX_THREADS_PER_BLOCK)
+ return FuncAttr(regs=nregs, const=cmem, local=lmem, shared=smem,
+ maxthreads=maxtpb)
+
+
+class CudaPythonFunction(Function):
+
+ def cache_config(self, prefer_equal=False, prefer_cache=False,
+ prefer_shared=False):
+ prefer_equal = prefer_equal or (prefer_cache and prefer_shared)
+ attr = binding.CUfunction_attribute
+ if prefer_equal:
+ flag = attr.CU_FUNC_CACHE_PREFER_EQUAL
+ elif prefer_cache:
+ flag = attr.CU_FUNC_CACHE_PREFER_L1
+ elif prefer_shared:
+ flag = attr.CU_FUNC_CACHE_PREFER_SHARED
+ else:
+ flag = attr.CU_FUNC_CACHE_PREFER_NONE
+ driver.cuFuncSetCacheConfig(self.handle, flag)
+
+ def read_func_attr(self, attrid):
+ return driver.cuFuncGetAttribute(attrid, self.handle)
+
+ def read_func_attr_all(self):
+ attr = binding.CUfunction_attribute
+ nregs = self.read_func_attr(attr.CU_FUNC_ATTRIBUTE_NUM_REGS)
+ cmem = self.read_func_attr(attr.CU_FUNC_ATTRIBUTE_CONST_SIZE_BYTES)
+ lmem = self.read_func_attr(attr.CU_FUNC_ATTRIBUTE_LOCAL_SIZE_BYTES)
+ smem = self.read_func_attr(attr.CU_FUNC_ATTRIBUTE_SHARED_SIZE_BYTES)
+ maxtpb = self.read_func_attr(
+ attr.CU_FUNC_ATTRIBUTE_MAX_THREADS_PER_BLOCK)
+ return FuncAttr(regs=nregs, const=cmem, local=lmem, shared=smem,
+ maxthreads=maxtpb)
+
+
+def launch_kernel(cufunc_handle,
+ gx, gy, gz,
+ bx, by, bz,
+ sharedmem,
+ hstream,
+ args,
+ cooperative=False):
+
+ param_ptrs = [addressof(arg) for arg in args]
+ params = (c_void_p * len(param_ptrs))(*param_ptrs)
+
+ if USE_NV_BINDING:
+ params_for_launch = addressof(params)
+ extra = 0
+ else:
+ params_for_launch = params
+ extra = None
+
+ if cooperative:
+ driver.cuLaunchCooperativeKernel(cufunc_handle,
+ gx, gy, gz,
+ bx, by, bz,
+ sharedmem,
+ hstream,
+ params_for_launch)
+ else:
+ driver.cuLaunchKernel(cufunc_handle,
+ gx, gy, gz,
+ bx, by, bz,
+ sharedmem,
+ hstream,
+ params_for_launch,
+ extra)
+
+
+if USE_NV_BINDING:
+ jitty = binding.CUjitInputType
+ FILE_EXTENSION_MAP = {
+ 'o': jitty.CU_JIT_INPUT_OBJECT,
+ 'ptx': jitty.CU_JIT_INPUT_PTX,
+ 'a': jitty.CU_JIT_INPUT_LIBRARY,
+ 'lib': jitty.CU_JIT_INPUT_LIBRARY,
+ 'cubin': jitty.CU_JIT_INPUT_CUBIN,
+ 'fatbin': jitty.CU_JIT_INPUT_FATBINARY,
+ }
+else:
+ FILE_EXTENSION_MAP = {
+ 'o': enums.CU_JIT_INPUT_OBJECT,
+ 'ptx': enums.CU_JIT_INPUT_PTX,
+ 'a': enums.CU_JIT_INPUT_LIBRARY,
+ 'lib': enums.CU_JIT_INPUT_LIBRARY,
+ 'cubin': enums.CU_JIT_INPUT_CUBIN,
+ 'fatbin': enums.CU_JIT_INPUT_FATBINARY,
+ }
+
+
+class Linker(metaclass=ABCMeta):
+ """Abstract base class for linkers"""
+
+ @classmethod
+ def new(cls, max_registers=0, lineinfo=False, cc=None):
+ if config.CUDA_ENABLE_MINOR_VERSION_COMPATIBILITY:
+ return MVCLinker(max_registers, lineinfo, cc)
+ elif USE_NV_BINDING:
+ return CudaPythonLinker(max_registers, lineinfo, cc)
+ else:
+ return CtypesLinker(max_registers, lineinfo, cc)
+
+ @abstractmethod
+ def __init__(self, max_registers, lineinfo, cc):
+ # LTO unsupported in Numba at present, but the pynvjitlink linker
+ # (https://github.com/rapidsai/pynvjitlink) supports it,
+ self.lto = False
+
+ @property
+ @abstractmethod
+ def info_log(self):
+ """Return the info log from the linker invocation"""
+
+ @property
+ @abstractmethod
+ def error_log(self):
+ """Return the error log from the linker invocation"""
+
+ @abstractmethod
+ def add_ptx(self, ptx, name):
+ """Add PTX source in a string to the link"""
+
+ def add_cu(self, cu, name):
+ """Add CUDA source in a string to the link. The name of the source
+ file should be specified in `name`."""
+ with driver.get_active_context() as ac:
+ dev = driver.get_device(ac.devnum)
+ cc = dev.compute_capability
+
+ ptx, log = nvrtc.compile(cu, name, cc)
+
+ if config.DUMP_ASSEMBLY:
+ print(("ASSEMBLY %s" % name).center(80, '-'))
+ print(ptx)
+ print('=' * 80)
+
+ # Link the program's PTX using the normal linker mechanism
+ ptx_name = os.path.splitext(name)[0] + ".ptx"
+ self.add_ptx(ptx.encode(), ptx_name)
+
+ @abstractmethod
+ def add_file(self, path, kind):
+ """Add code from a file to the link"""
+
+ def add_cu_file(self, path):
+ with open(path, 'rb') as f:
+ cu = f.read()
+ self.add_cu(cu, os.path.basename(path))
+
+ def add_file_guess_ext(self, path):
+ """Add a file to the link, guessing its type from its extension."""
+ ext = os.path.splitext(path)[1][1:]
+ if ext == '':
+ raise RuntimeError("Don't know how to link file with no extension")
+ elif ext == 'cu':
+ self.add_cu_file(path)
+ else:
+ kind = FILE_EXTENSION_MAP.get(ext, None)
+ if kind is None:
+ raise RuntimeError("Don't know how to link file with extension "
+ f".{ext}")
+ self.add_file(path, kind)
+
+ @abstractmethod
+ def complete(self):
+ """Complete the link. Returns (cubin, size)
+
+ cubin is a pointer to a internal buffer of cubin owned by the linker;
+ thus, it should be loaded before the linker is destroyed.
+ """
+
+
+_MVC_ERROR_MESSAGE = (
+ "Minor version compatibility requires ptxcompiler and cubinlinker packages "
+ "to be available"
+)
+
+
+class MVCLinker(Linker):
+ """
+ Linker supporting Minor Version Compatibility, backed by the cubinlinker
+ package.
+ """
+ def __init__(self, max_registers=None, lineinfo=False, cc=None):
+ try:
+ from cubinlinker import CubinLinker
+ except ImportError as err:
+ raise ImportError(_MVC_ERROR_MESSAGE) from err
+
+ if cc is None:
+ raise RuntimeError("MVCLinker requires Compute Capability to be "
+ "specified, but cc is None")
+
+ super().__init__(max_registers, lineinfo, cc)
+
+ arch = f"sm_{cc[0] * 10 + cc[1]}"
+ ptx_compile_opts = ['--gpu-name', arch, '-c']
+ if max_registers:
+ arg = f"--maxrregcount={max_registers}"
+ ptx_compile_opts.append(arg)
+ if lineinfo:
+ ptx_compile_opts.append('--generate-line-info')
+ self.ptx_compile_options = tuple(ptx_compile_opts)
+
+ self._linker = CubinLinker(f"--arch={arch}")
+
+ @property
+ def info_log(self):
+ return self._linker.info_log
+
+ @property
+ def error_log(self):
+ return self._linker.error_log
+
+ def add_ptx(self, ptx, name=''):
+ try:
+ from ptxcompiler import compile_ptx
+ from cubinlinker import CubinLinkerError
+ except ImportError as err:
+ raise ImportError(_MVC_ERROR_MESSAGE) from err
+ compile_result = compile_ptx(ptx.decode(), self.ptx_compile_options)
+ try:
+ self._linker.add_cubin(compile_result.compiled_program, name)
+ except CubinLinkerError as e:
+ raise LinkerError from e
+
+ def add_file(self, path, kind):
+ try:
+ from cubinlinker import CubinLinkerError
+ except ImportError as err:
+ raise ImportError(_MVC_ERROR_MESSAGE) from err
+
+ try:
+ with open(path, 'rb') as f:
+ data = f.read()
+ except FileNotFoundError:
+ raise LinkerError(f'{path} not found')
+
+ name = pathlib.Path(path).name
+ if kind == FILE_EXTENSION_MAP['cubin']:
+ fn = self._linker.add_cubin
+ elif kind == FILE_EXTENSION_MAP['fatbin']:
+ fn = self._linker.add_fatbin
+ elif kind == FILE_EXTENSION_MAP['a']:
+ raise LinkerError(f"Don't know how to link {kind}")
+ elif kind == FILE_EXTENSION_MAP['ptx']:
+ return self.add_ptx(data, name)
+ else:
+ raise LinkerError(f"Don't know how to link {kind}")
+
+ try:
+ fn(data, name)
+ except CubinLinkerError as e:
+ raise LinkerError from e
+
+ def complete(self):
+ try:
+ from cubinlinker import CubinLinkerError
+ except ImportError as err:
+ raise ImportError(_MVC_ERROR_MESSAGE) from err
+
+ try:
+ return self._linker.complete()
+ except CubinLinkerError as e:
+ raise LinkerError from e
+
+
+class CtypesLinker(Linker):
+ """
+ Links for current device if no CC given
+ """
+ def __init__(self, max_registers=0, lineinfo=False, cc=None):
+ super().__init__(max_registers, lineinfo, cc)
+
+ logsz = config.CUDA_LOG_SIZE
+ linkerinfo = (c_char * logsz)()
+ linkererrors = (c_char * logsz)()
+
+ options = {
+ enums.CU_JIT_INFO_LOG_BUFFER: addressof(linkerinfo),
+ enums.CU_JIT_INFO_LOG_BUFFER_SIZE_BYTES: c_void_p(logsz),
+ enums.CU_JIT_ERROR_LOG_BUFFER: addressof(linkererrors),
+ enums.CU_JIT_ERROR_LOG_BUFFER_SIZE_BYTES: c_void_p(logsz),
+ enums.CU_JIT_LOG_VERBOSE: c_void_p(1),
+ }
+ if max_registers:
+ options[enums.CU_JIT_MAX_REGISTERS] = c_void_p(max_registers)
+ if lineinfo:
+ options[enums.CU_JIT_GENERATE_LINE_INFO] = c_void_p(1)
+
+ if cc is None:
+ # No option value is needed, but we need something as a placeholder
+ options[enums.CU_JIT_TARGET_FROM_CUCONTEXT] = 1
+ else:
+ cc_val = cc[0] * 10 + cc[1]
+ options[enums.CU_JIT_TARGET] = c_void_p(cc_val)
+
+ raw_keys = list(options.keys())
+ raw_values = list(options.values())
+
+ option_keys = (drvapi.cu_jit_option * len(raw_keys))(*raw_keys)
+ option_vals = (c_void_p * len(raw_values))(*raw_values)
+
+ self.handle = handle = drvapi.cu_link_state()
+ driver.cuLinkCreate(len(raw_keys), option_keys, option_vals,
+ byref(self.handle))
+
+ weakref.finalize(self, driver.cuLinkDestroy, handle)
+
+ self.linker_info_buf = linkerinfo
+ self.linker_errors_buf = linkererrors
+
+ self._keep_alive = [linkerinfo, linkererrors, option_keys, option_vals]
+
+ @property
+ def info_log(self):
+ return self.linker_info_buf.value.decode('utf8')
+
+ @property
+ def error_log(self):
+ return self.linker_errors_buf.value.decode('utf8')
+
+ def add_ptx(self, ptx, name=''):
+ ptxbuf = c_char_p(ptx)
+ namebuf = c_char_p(name.encode('utf8'))
+ self._keep_alive += [ptxbuf, namebuf]
+ try:
+ driver.cuLinkAddData(self.handle, enums.CU_JIT_INPUT_PTX,
+ ptxbuf, len(ptx), namebuf, 0, None, None)
+ except CudaAPIError as e:
+ raise LinkerError("%s\n%s" % (e, self.error_log))
+
+ def add_file(self, path, kind):
+ pathbuf = c_char_p(path.encode("utf8"))
+ self._keep_alive.append(pathbuf)
+
+ try:
+ driver.cuLinkAddFile(self.handle, kind, pathbuf, 0, None, None)
+ except CudaAPIError as e:
+ if e.code == enums.CUDA_ERROR_FILE_NOT_FOUND:
+ msg = f'{path} not found'
+ else:
+ msg = "%s\n%s" % (e, self.error_log)
+ raise LinkerError(msg)
+
+ def complete(self):
+ cubin_buf = c_void_p(0)
+ size = c_size_t(0)
+
+ try:
+ driver.cuLinkComplete(self.handle, byref(cubin_buf), byref(size))
+ except CudaAPIError as e:
+ raise LinkerError("%s\n%s" % (e, self.error_log))
+
+ size = size.value
+ assert size > 0, 'linker returned a zero sized cubin'
+ del self._keep_alive[:]
+
+ # We return a copy of the cubin because it's owned by the linker
+ cubin_ptr = ctypes.cast(cubin_buf, ctypes.POINTER(ctypes.c_char))
+ return bytes(np.ctypeslib.as_array(cubin_ptr, shape=(size,)))
+
+
+class CudaPythonLinker(Linker):
+ """
+ Links for current device if no CC given
+ """
+ def __init__(self, max_registers=0, lineinfo=False, cc=None):
+ super().__init__(max_registers, lineinfo, cc)
+
+ logsz = config.CUDA_LOG_SIZE
+ linkerinfo = bytearray(logsz)
+ linkererrors = bytearray(logsz)
+
+ jit_option = binding.CUjit_option
+
+ options = {
+ jit_option.CU_JIT_INFO_LOG_BUFFER: linkerinfo,
+ jit_option.CU_JIT_INFO_LOG_BUFFER_SIZE_BYTES: logsz,
+ jit_option.CU_JIT_ERROR_LOG_BUFFER: linkererrors,
+ jit_option.CU_JIT_ERROR_LOG_BUFFER_SIZE_BYTES: logsz,
+ jit_option.CU_JIT_LOG_VERBOSE: 1,
+ }
+ if max_registers:
+ options[jit_option.CU_JIT_MAX_REGISTERS] = max_registers
+ if lineinfo:
+ options[jit_option.CU_JIT_GENERATE_LINE_INFO] = 1
+
+ if cc is None:
+ # No option value is needed, but we need something as a placeholder
+ options[jit_option.CU_JIT_TARGET_FROM_CUCONTEXT] = 1
+ else:
+ cc_val = cc[0] * 10 + cc[1]
+ cc_enum = getattr(binding.CUjit_target,
+ f'CU_TARGET_COMPUTE_{cc_val}')
+ options[jit_option.CU_JIT_TARGET] = cc_enum
+
+ raw_keys = list(options.keys())
+ raw_values = list(options.values())
+
+ self.handle = driver.cuLinkCreate(len(raw_keys), raw_keys, raw_values)
+
+ weakref.finalize(self, driver.cuLinkDestroy, self.handle)
+
+ self.linker_info_buf = linkerinfo
+ self.linker_errors_buf = linkererrors
+
+ self._keep_alive = [linkerinfo, linkererrors, raw_keys, raw_values]
+
+ @property
+ def info_log(self):
+ return self.linker_info_buf.decode('utf8')
+
+ @property
+ def error_log(self):
+ return self.linker_errors_buf.decode('utf8')
+
+ def add_ptx(self, ptx, name=''):
+ namebuf = name.encode('utf8')
+ self._keep_alive += [ptx, namebuf]
+ try:
+ input_ptx = binding.CUjitInputType.CU_JIT_INPUT_PTX
+ driver.cuLinkAddData(self.handle, input_ptx, ptx, len(ptx),
+ namebuf, 0, [], [])
+ except CudaAPIError as e:
+ raise LinkerError("%s\n%s" % (e, self.error_log))
+
+ def add_file(self, path, kind):
+ pathbuf = path.encode("utf8")
+ self._keep_alive.append(pathbuf)
+
+ try:
+ driver.cuLinkAddFile(self.handle, kind, pathbuf, 0, [], [])
+ except CudaAPIError as e:
+ if e.code == binding.CUresult.CUDA_ERROR_FILE_NOT_FOUND:
+ msg = f'{path} not found'
+ else:
+ msg = "%s\n%s" % (e, self.error_log)
+ raise LinkerError(msg)
+
+ def complete(self):
+ try:
+ cubin_buf, size = driver.cuLinkComplete(self.handle)
+ except CudaAPIError as e:
+ raise LinkerError("%s\n%s" % (e, self.error_log))
+
+ assert size > 0, 'linker returned a zero sized cubin'
+ del self._keep_alive[:]
+ # We return a copy of the cubin because it's owned by the linker
+ cubin_ptr = ctypes.cast(cubin_buf, ctypes.POINTER(ctypes.c_char))
+ return bytes(np.ctypeslib.as_array(cubin_ptr, shape=(size,)))
+
+
+# -----------------------------------------------------------------------------
+
+
+def get_devptr_for_active_ctx(ptr):
+ """Query the device pointer usable in the current context from an arbitrary
+ pointer.
+ """
+ if ptr != 0:
+ if USE_NV_BINDING:
+ ptr_attrs = binding.CUpointer_attribute
+ attr = ptr_attrs.CU_POINTER_ATTRIBUTE_DEVICE_POINTER
+ ptrobj = binding.CUdeviceptr(ptr)
+ return driver.cuPointerGetAttribute(attr, ptrobj)
+ else:
+ devptr = drvapi.cu_device_ptr()
+ attr = enums.CU_POINTER_ATTRIBUTE_DEVICE_POINTER
+ driver.cuPointerGetAttribute(byref(devptr), attr, ptr)
+ return devptr
+ else:
+ if USE_NV_BINDING:
+ return binding.CUdeviceptr()
+ else:
+ return drvapi.cu_device_ptr()
+
+
+def device_extents(devmem):
+ """Find the extents (half open begin and end pointer) of the underlying
+ device memory allocation.
+
+ NOTE: it always returns the extents of the allocation but the extents
+ of the device memory view that can be a subsection of the entire allocation.
+ """
+ devptr = device_ctypes_pointer(devmem)
+ if USE_NV_BINDING:
+ s, n = driver.cuMemGetAddressRange(devptr)
+ return s, binding.CUdeviceptr(int(s) + n)
+ else:
+ s = drvapi.cu_device_ptr()
+ n = c_size_t()
+ driver.cuMemGetAddressRange(byref(s), byref(n), devptr)
+ s, n = s.value, n.value
+ return s, s + n
+
+
+def device_memory_size(devmem):
+ """Check the memory size of the device memory.
+ The result is cached in the device memory object.
+ It may query the driver for the memory size of the device memory allocation.
+ """
+ sz = getattr(devmem, '_cuda_memsize_', None)
+ if sz is None:
+ s, e = device_extents(devmem)
+ if USE_NV_BINDING:
+ sz = int(e) - int(s)
+ else:
+ sz = e - s
+ devmem._cuda_memsize_ = sz
+ assert sz >= 0, "{} length array".format(sz)
+ return sz
+
+
+def _is_datetime_dtype(obj):
+ """Returns True if the obj.dtype is datetime64 or timedelta64
+ """
+ dtype = getattr(obj, 'dtype', None)
+ return dtype is not None and dtype.char in 'Mm'
+
+
+def _workaround_for_datetime(obj):
+ """Workaround for numpy#4983: buffer protocol doesn't support
+ datetime64 or timedelta64.
+ """
+ if _is_datetime_dtype(obj):
+ obj = obj.view(np.int64)
+ return obj
+
+
+def host_pointer(obj, readonly=False):
+ """Get host pointer from an obj.
+
+ If `readonly` is False, the buffer must be writable.
+
+ NOTE: The underlying data pointer from the host data buffer is used and
+ it should not be changed until the operation which can be asynchronous
+ completes.
+ """
+ if isinstance(obj, int):
+ return obj
+
+ forcewritable = False
+ if not readonly:
+ forcewritable = isinstance(obj, np.void) or _is_datetime_dtype(obj)
+
+ obj = _workaround_for_datetime(obj)
+ return mviewbuf.memoryview_get_buffer(obj, forcewritable, readonly)
+
+
+def host_memory_extents(obj):
+ "Returns (start, end) the start and end pointer of the array (half open)."
+ obj = _workaround_for_datetime(obj)
+ return mviewbuf.memoryview_get_extents(obj)
+
+
+def memory_size_from_info(shape, strides, itemsize):
+ """Get the byte size of a contiguous memory buffer given the shape, strides
+ and itemsize.
+ """
+ assert len(shape) == len(strides), "# dim mismatch"
+ ndim = len(shape)
+ s, e = mviewbuf.memoryview_get_extents_info(shape, strides, ndim, itemsize)
+ return e - s
+
+
+def host_memory_size(obj):
+ "Get the size of the memory"
+ s, e = host_memory_extents(obj)
+ assert e >= s, "memory extend of negative size"
+ return e - s
+
+
+def device_pointer(obj):
+ "Get the device pointer as an integer"
+ if USE_NV_BINDING:
+ return obj.device_ctypes_pointer
+ else:
+ return device_ctypes_pointer(obj).value
+
+
+def device_ctypes_pointer(obj):
+ "Get the ctypes object for the device pointer"
+ if obj is None:
+ return c_void_p(0)
+ require_device_memory(obj)
+ return obj.device_ctypes_pointer
+
+
+def is_device_memory(obj):
+ """All CUDA memory object is recognized as an instance with the attribute
+ "__cuda_memory__" defined and its value evaluated to True.
+
+ All CUDA memory object should also define an attribute named
+ "device_pointer" which value is an int object carrying the pointer
+ value of the device memory address. This is not tested in this method.
+ """
+ return getattr(obj, '__cuda_memory__', False)
+
+
+def require_device_memory(obj):
+ """A sentry for methods that accept CUDA memory object.
+ """
+ if not is_device_memory(obj):
+ raise Exception("Not a CUDA memory object.")
+
+
+def device_memory_depends(devmem, *objs):
+ """Add dependencies to the device memory.
+
+ Mainly used for creating structures that points to other device memory,
+ so that the referees are not GC and released.
+ """
+ depset = getattr(devmem, "_depends_", [])
+ depset.extend(objs)
+
+
+def host_to_device(dst, src, size, stream=0):
+ """
+ NOTE: The underlying data pointer from the host data buffer is used and
+ it should not be changed until the operation which can be asynchronous
+ completes.
+ """
+ varargs = []
+
+ if stream:
+ assert isinstance(stream, Stream)
+ fn = driver.cuMemcpyHtoDAsync
+ varargs.append(stream.handle)
+ else:
+ fn = driver.cuMemcpyHtoD
+
+ fn(device_pointer(dst), host_pointer(src, readonly=True), size, *varargs)
+
+
+def device_to_host(dst, src, size, stream=0):
+ """
+ NOTE: The underlying data pointer from the host data buffer is used and
+ it should not be changed until the operation which can be asynchronous
+ completes.
+ """
+ varargs = []
+
+ if stream:
+ assert isinstance(stream, Stream)
+ fn = driver.cuMemcpyDtoHAsync
+ varargs.append(stream.handle)
+ else:
+ fn = driver.cuMemcpyDtoH
+
+ fn(host_pointer(dst), device_pointer(src), size, *varargs)
+
+
+def device_to_device(dst, src, size, stream=0):
+ """
+ NOTE: The underlying data pointer from the host data buffer is used and
+ it should not be changed until the operation which can be asynchronous
+ completes.
+ """
+ varargs = []
+
+ if stream:
+ assert isinstance(stream, Stream)
+ fn = driver.cuMemcpyDtoDAsync
+ varargs.append(stream.handle)
+ else:
+ fn = driver.cuMemcpyDtoD
+
+ fn(device_pointer(dst), device_pointer(src), size, *varargs)
+
+
+def device_memset(dst, val, size, stream=0):
+ """Memset on the device.
+ If stream is not zero, asynchronous mode is used.
+
+ dst: device memory
+ val: byte value to be written
+ size: number of byte to be written
+ stream: a CUDA stream
+ """
+ varargs = []
+
+ if stream:
+ assert isinstance(stream, Stream)
+ fn = driver.cuMemsetD8Async
+ varargs.append(stream.handle)
+ else:
+ fn = driver.cuMemsetD8
+
+ fn(device_pointer(dst), val, size, *varargs)
+
+
+def profile_start():
+ '''
+ Enable profile collection in the current context.
+ '''
+ driver.cuProfilerStart()
+
+
+def profile_stop():
+ '''
+ Disable profile collection in the current context.
+ '''
+ driver.cuProfilerStop()
+
+
+@contextlib.contextmanager
+def profiling():
+ """
+ Context manager that enables profiling on entry and disables profiling on
+ exit.
+ """
+ profile_start()
+ yield
+ profile_stop()
+
+
+def get_version():
+ """
+ Return the driver version as a tuple of (major, minor)
+ """
+ return driver.get_version()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/drvapi.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/drvapi.py
new file mode 100644
index 0000000000000000000000000000000000000000..cbbd792d3122bb0b76ba6bf7efb45ab2c06ed19d
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/drvapi.py
@@ -0,0 +1,394 @@
+from ctypes import (c_byte, c_char_p, c_float, c_int, c_size_t, c_uint,
+ c_uint8, c_void_p, py_object, CFUNCTYPE, POINTER)
+
+from numba.cuda.cudadrv import _extras
+
+cu_device = c_int
+cu_device_attribute = c_int # enum
+cu_context = c_void_p # an opaque handle
+cu_module = c_void_p # an opaque handle
+cu_jit_option = c_int # enum
+cu_jit_input_type = c_int # enum
+cu_function = c_void_p # an opaque handle
+cu_device_ptr = c_size_t # defined as unsigned long long
+cu_stream = c_void_p # an opaque handle
+cu_event = c_void_p
+cu_link_state = c_void_p
+cu_function_attribute = c_int
+cu_ipc_mem_handle = (c_byte * _extras.CUDA_IPC_HANDLE_SIZE) # 64 bytes wide
+cu_uuid = (c_byte * 16) # Device UUID
+
+cu_stream_callback_pyobj = CFUNCTYPE(None, cu_stream, c_int, py_object)
+
+cu_occupancy_b2d_size = CFUNCTYPE(c_size_t, c_int)
+
+# See https://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__TYPES.html
+CU_STREAM_DEFAULT = 0
+CU_STREAM_LEGACY = 1
+CU_STREAM_PER_THREAD = 2
+
+API_PROTOTYPES = {
+ # CUresult cuInit(unsigned int Flags);
+ 'cuInit' : (c_int, c_uint),
+
+ # CUresult cuDriverGetVersion (int* driverVersion )
+ 'cuDriverGetVersion': (c_int, POINTER(c_int)),
+
+ # CUresult cuDeviceGetCount(int *count);
+ 'cuDeviceGetCount': (c_int, POINTER(c_int)),
+
+ # CUresult cuDeviceGet(CUdevice *device, int ordinal);
+ 'cuDeviceGet': (c_int, POINTER(cu_device), c_int),
+
+ # CUresult cuDeviceGetName ( char* name, int len, CUdevice dev )
+ 'cuDeviceGetName': (c_int, c_char_p, c_int, cu_device),
+
+ # CUresult cuDeviceGetAttribute(int *pi, CUdevice_attribute attrib,
+ # CUdevice dev);
+ 'cuDeviceGetAttribute': (c_int, POINTER(c_int), cu_device_attribute,
+ cu_device),
+
+ # CUresult cuDeviceComputeCapability(int *major, int *minor,
+ # CUdevice dev);
+ 'cuDeviceComputeCapability': (c_int, POINTER(c_int), POINTER(c_int),
+ cu_device),
+
+ # CUresult cuDevicePrimaryCtxGetState(
+ # CUdevice dev,
+ # unsigned int* flags,
+ # int* active)
+ 'cuDevicePrimaryCtxGetState': (c_int,
+ cu_device, POINTER(c_uint), POINTER(c_int)),
+
+ # CUresult cuDevicePrimaryCtxRelease ( CUdevice dev )
+ 'cuDevicePrimaryCtxRelease': (c_int, cu_device),
+
+ # CUresult cuDevicePrimaryCtxReset ( CUdevice dev )
+ 'cuDevicePrimaryCtxReset': (c_int, cu_device),
+
+ # CUresult cuDevicePrimaryCtxRetain ( CUcontext* pctx, CUdevice dev )
+ 'cuDevicePrimaryCtxRetain': (c_int, POINTER(cu_context), cu_device),
+
+ # CUresult cuDevicePrimaryCtxSetFlags ( CUdevice dev, unsigned int flags )
+ 'cuDevicePrimaryCtxSetFlags': (c_int, cu_device, c_uint),
+
+ # CUresult cuCtxCreate(CUcontext *pctx, unsigned int flags,
+ # CUdevice dev);
+ 'cuCtxCreate': (c_int, POINTER(cu_context), c_uint, cu_device),
+
+ # CUresult cuCtxGetDevice ( CUdevice * device )
+ 'cuCtxGetDevice': (c_int, POINTER(cu_device)),
+
+ # CUresult cuCtxGetCurrent (CUcontext *pctx);
+ 'cuCtxGetCurrent': (c_int, POINTER(cu_context)),
+
+ # CUresult cuCtxPushCurrent (CUcontext pctx);
+ 'cuCtxPushCurrent': (c_int, cu_context),
+
+ # CUresult cuCtxPopCurrent (CUcontext *pctx);
+ 'cuCtxPopCurrent': (c_int, POINTER(cu_context)),
+
+ # CUresult cuCtxDestroy(CUcontext pctx);
+ 'cuCtxDestroy': (c_int, cu_context),
+
+ # CUresult cuModuleLoadDataEx(CUmodule *module, const void *image,
+ # unsigned int numOptions,
+ # CUjit_option *options,
+ # void **optionValues);
+ 'cuModuleLoadDataEx': (c_int, cu_module, c_void_p, c_uint,
+ POINTER(cu_jit_option), POINTER(c_void_p)),
+
+ # CUresult cuModuleUnload(CUmodule hmod);
+ 'cuModuleUnload': (c_int, cu_module),
+
+ # CUresult cuModuleGetFunction(CUfunction *hfunc, CUmodule hmod,
+ # const char *name);
+ 'cuModuleGetFunction': (c_int, cu_function, cu_module, c_char_p),
+
+ # CUresult cuModuleGetGlobal ( CUdeviceptr* dptr, size_t* bytes, CUmodule
+ # hmod, const char* name )
+ 'cuModuleGetGlobal': (c_int, POINTER(cu_device_ptr), POINTER(c_size_t),
+ cu_module, c_char_p),
+
+ # CUresult CUDAAPI cuFuncSetCacheConfig(CUfunction hfunc,
+ # CUfunc_cache config);
+ 'cuFuncSetCacheConfig': (c_int, cu_function, c_uint),
+
+ # CUresult cuMemAlloc(CUdeviceptr *dptr, size_t bytesize);
+ 'cuMemAlloc': (c_int, POINTER(cu_device_ptr), c_size_t),
+
+ # CUresult cuMemAllocManaged(CUdeviceptr *dptr, size_t bytesize,
+ # unsigned int flags);
+ 'cuMemAllocManaged': (c_int, c_void_p, c_size_t, c_uint),
+
+ # CUresult cuMemsetD8(CUdeviceptr dstDevice, unsigned char uc, size_t N)
+ 'cuMemsetD8': (c_int, cu_device_ptr, c_uint8, c_size_t),
+
+ # CUresult cuMemsetD8Async(CUdeviceptr dstDevice, unsigned char uc,
+ # size_t N, CUstream hStream);
+ 'cuMemsetD8Async': (c_int,
+ cu_device_ptr, c_uint8, c_size_t, cu_stream),
+
+ # CUresult cuMemcpyHtoD(CUdeviceptr dstDevice, const void *srcHost,
+ # size_t ByteCount);
+ 'cuMemcpyHtoD': (c_int, cu_device_ptr, c_void_p, c_size_t),
+
+ # CUresult cuMemcpyHtoDAsync(CUdeviceptr dstDevice, const void *srcHost,
+ # size_t ByteCount, CUstream hStream);
+ 'cuMemcpyHtoDAsync': (c_int, cu_device_ptr, c_void_p, c_size_t,
+ cu_stream),
+
+ # CUresult cuMemcpyDtoD(CUdeviceptr dstDevice, const void *srcDevice,
+ # size_t ByteCount);
+ 'cuMemcpyDtoD': (c_int, cu_device_ptr, cu_device_ptr, c_size_t),
+
+ # CUresult cuMemcpyDtoDAsync(CUdeviceptr dstDevice, const void *srcDevice,
+ # size_t ByteCount, CUstream hStream);
+ 'cuMemcpyDtoDAsync': (c_int, cu_device_ptr, cu_device_ptr, c_size_t,
+ cu_stream),
+
+
+ # CUresult cuMemcpyDtoH(void *dstHost, CUdeviceptr srcDevice,
+ # size_t ByteCount);
+ 'cuMemcpyDtoH': (c_int, c_void_p, cu_device_ptr, c_size_t),
+
+ # CUresult cuMemcpyDtoHAsync(void *dstHost, CUdeviceptr srcDevice,
+ # size_t ByteCount, CUstream hStream);
+ 'cuMemcpyDtoHAsync': (c_int, c_void_p, cu_device_ptr, c_size_t,
+ cu_stream),
+
+ # CUresult cuMemFree(CUdeviceptr dptr);
+ 'cuMemFree': (c_int, cu_device_ptr),
+
+ # CUresult cuStreamCreate(CUstream *phStream, unsigned int Flags);
+ 'cuStreamCreate': (c_int, POINTER(cu_stream), c_uint),
+
+ # CUresult cuStreamDestroy(CUstream hStream);
+ 'cuStreamDestroy': (c_int, cu_stream),
+
+ # CUresult cuStreamSynchronize(CUstream hStream);
+ 'cuStreamSynchronize': (c_int, cu_stream),
+
+ # CUresult cuStreamAddCallback(
+ # CUstream hStream,
+ # CUstreamCallback callback,
+ # void* userData,
+ # unsigned int flags)
+ 'cuStreamAddCallback': (c_int, cu_stream, cu_stream_callback_pyobj,
+ py_object, c_uint),
+
+ # CUresult cuLaunchKernel(CUfunction f, unsigned int gridDimX,
+ # unsigned int gridDimY,
+ # unsigned int gridDimZ,
+ # unsigned int blockDimX,
+ # unsigned int blockDimY,
+ # unsigned int blockDimZ,
+ # unsigned int sharedMemBytes,
+ # CUstream hStream, void **kernelParams,
+ # void ** extra)
+ 'cuLaunchKernel': (c_int, cu_function, c_uint, c_uint, c_uint,
+ c_uint, c_uint, c_uint, c_uint, cu_stream,
+ POINTER(c_void_p), POINTER(c_void_p)),
+
+ # CUresult cuLaunchCooperativeKernel(CUfunction f, unsigned int gridDimX,
+ # unsigned int gridDimY,
+ # unsigned int gridDimZ,
+ # unsigned int blockDimX,
+ # unsigned int blockDimY,
+ # unsigned int blockDimZ,
+ # unsigned int sharedMemBytes,
+ # CUstream hStream, void **kernelParams)
+ 'cuLaunchCooperativeKernel': (c_int, cu_function, c_uint, c_uint, c_uint,
+ c_uint, c_uint, c_uint, c_uint, cu_stream,
+ POINTER(c_void_p)),
+
+ # CUresult cuMemHostAlloc ( void ** pp,
+ # size_t bytesize,
+ # unsigned int Flags
+ # )
+ 'cuMemHostAlloc': (c_int, c_void_p, c_size_t, c_uint),
+
+ # CUresult cuMemFreeHost ( void * p )
+ 'cuMemFreeHost': (c_int, c_void_p),
+
+ # CUresult cuMemHostRegister(void * p,
+ # size_t bytesize,
+ # unsigned int Flags)
+ 'cuMemHostRegister': (c_int, c_void_p, c_size_t, c_uint),
+
+ # CUresult cuMemHostUnregister(void * p)
+ 'cuMemHostUnregister': (c_int, c_void_p),
+
+ # CUresult cuMemHostGetDevicePointer(CUdeviceptr * pdptr,
+ # void * p,
+ # unsigned int Flags)
+ 'cuMemHostGetDevicePointer': (c_int, POINTER(cu_device_ptr),
+ c_void_p, c_uint),
+
+ # CUresult cuMemGetInfo(size_t * free, size_t * total)
+ 'cuMemGetInfo' : (c_int, POINTER(c_size_t), POINTER(c_size_t)),
+
+ # CUresult cuEventCreate ( CUevent * phEvent,
+ # unsigned int Flags )
+ 'cuEventCreate': (c_int, POINTER(cu_event), c_uint),
+
+ # CUresult cuEventDestroy ( CUevent hEvent )
+ 'cuEventDestroy': (c_int, cu_event),
+
+ # CUresult cuEventElapsedTime ( float * pMilliseconds,
+ # CUevent hStart,
+ # CUevent hEnd )
+ 'cuEventElapsedTime': (c_int, POINTER(c_float), cu_event, cu_event),
+
+ # CUresult cuEventQuery ( CUevent hEvent )
+ 'cuEventQuery': (c_int, cu_event),
+
+ # CUresult cuEventRecord ( CUevent hEvent,
+ # CUstream hStream )
+ 'cuEventRecord': (c_int, cu_event, cu_stream),
+
+ # CUresult cuEventSynchronize ( CUevent hEvent )
+ 'cuEventSynchronize': (c_int, cu_event),
+
+
+ # CUresult cuStreamWaitEvent ( CUstream hStream,
+ # CUevent hEvent,
+ # unsigned int Flags )
+ 'cuStreamWaitEvent': (c_int, cu_stream, cu_event, c_uint),
+
+ # CUresult cuPointerGetAttribute (
+ # void *data,
+ # CUpointer_attribute attribute,
+ # CUdeviceptr ptr)
+ 'cuPointerGetAttribute': (c_int, c_void_p, c_uint, cu_device_ptr),
+
+ # CUresult cuMemGetAddressRange ( CUdeviceptr * pbase,
+ # size_t * psize,
+ # CUdeviceptr dptr
+ # )
+ 'cuMemGetAddressRange': (c_int,
+ POINTER(cu_device_ptr),
+ POINTER(c_size_t),
+ cu_device_ptr),
+
+ # CUresult cuMemHostGetFlags ( unsigned int * pFlags,
+ # void * p )
+ 'cuMemHostGetFlags': (c_int,
+ POINTER(c_uint),
+ c_void_p),
+
+ # CUresult cuCtxSynchronize ( void )
+ 'cuCtxSynchronize' : (c_int,),
+
+ # CUresult
+ # cuLinkCreate(unsigned int numOptions, CUjit_option *options,
+ # void **optionValues, CUlinkState *stateOut);
+ 'cuLinkCreate': (c_int,
+ c_uint, POINTER(cu_jit_option),
+ POINTER(c_void_p), POINTER(cu_link_state)),
+
+ # CUresult
+ # cuLinkAddData(CUlinkState state, CUjitInputType type, void *data,
+ # size_t size, const char *name, unsigned
+ # int numOptions, CUjit_option *options,
+ # void **optionValues);
+ 'cuLinkAddData': (c_int,
+ cu_link_state, cu_jit_input_type, c_void_p,
+ c_size_t, c_char_p, c_uint, POINTER(cu_jit_option),
+ POINTER(c_void_p)),
+
+ # CUresult
+ # cuLinkAddFile(CUlinkState state, CUjitInputType type,
+ # const char *path, unsigned int numOptions,
+ # CUjit_option *options, void **optionValues);
+
+ 'cuLinkAddFile': (c_int,
+ cu_link_state, cu_jit_input_type, c_char_p, c_uint,
+ POINTER(cu_jit_option), POINTER(c_void_p)),
+
+ # CUresult CUDAAPI
+ # cuLinkComplete(CUlinkState state, void **cubinOut, size_t *sizeOut)
+ 'cuLinkComplete': (c_int,
+ cu_link_state, POINTER(c_void_p), POINTER(c_size_t)),
+
+ # CUresult CUDAAPI
+ # cuLinkDestroy(CUlinkState state)
+ 'cuLinkDestroy': (c_int, cu_link_state),
+
+ # cuProfilerStart ( void )
+ 'cuProfilerStart': (c_int,),
+
+ # cuProfilerStop ( void )
+ 'cuProfilerStop': (c_int,),
+
+ # CUresult cuFuncGetAttribute ( int* pi, CUfunction_attribute attrib,
+ # CUfunction hfunc )
+ 'cuFuncGetAttribute': (c_int,
+ POINTER(c_int), cu_function_attribute, cu_function),
+
+ # CUresult CUDAAPI cuOccupancyMaxActiveBlocksPerMultiprocessor(
+ # int *numBlocks,
+ # CUfunction func,
+ # int blockSize,
+ # size_t dynamicSMemSize);
+ 'cuOccupancyMaxActiveBlocksPerMultiprocessor': (c_int, POINTER(c_int),
+ cu_function, c_size_t,
+ c_uint),
+
+ # CUresult CUDAAPI cuOccupancyMaxActiveBlocksPerMultiprocessorWithFlags(
+ # int *numBlocks,
+ # CUfunction func,
+ # int blockSize,
+ # size_t dynamicSMemSize,
+ # unsigned int flags);
+ 'cuOccupancyMaxActiveBlocksPerMultiprocessorWithFlags': (c_int,
+ POINTER(c_int),
+ cu_function,
+ c_size_t, c_uint),
+
+ # CUresult CUDAAPI cuOccupancyMaxPotentialBlockSize(
+ # int *minGridSize, int *blockSize,
+ # CUfunction func,
+ # CUoccupancyB2DSize blockSizeToDynamicSMemSize,
+ # size_t dynamicSMemSize, int blockSizeLimit);
+ 'cuOccupancyMaxPotentialBlockSize': (c_int, POINTER(c_int), POINTER(c_int),
+ cu_function, cu_occupancy_b2d_size,
+ c_size_t, c_int),
+
+ # CUresult CUDAAPI cuOccupancyMaxPotentialBlockSizeWithFlags(
+ # int *minGridSize, int *blockSize,
+ # CUfunction func,
+ # CUoccupancyB2DSize blockSizeToDynamicSMemSize,
+ # size_t dynamicSMemSize, int blockSizeLimit,
+ # unsigned int flags);
+ 'cuOccupancyMaxPotentialBlockSizeWithFlags': (c_int, POINTER(c_int),
+ POINTER(c_int), cu_function,
+ cu_occupancy_b2d_size,
+ c_size_t, c_int, c_uint),
+
+ # CUresult cuIpcGetMemHandle ( CUipcMemHandle* pHandle, CUdeviceptr dptr )
+ 'cuIpcGetMemHandle': (c_int,
+ POINTER(cu_ipc_mem_handle), cu_device_ptr),
+
+ # CUresult cuIpcOpenMemHandle(
+ # CUdeviceptr* pdptr,
+ # CUipcMemHandle handle,
+ # unsigned int Flags)
+ 'cuIpcOpenMemHandle': (c_int, POINTER(cu_device_ptr), cu_ipc_mem_handle,
+ c_uint),
+
+ # CUresult cuIpcCloseMemHandle ( CUdeviceptr dptr )
+
+ 'cuIpcCloseMemHandle': (c_int, cu_device_ptr),
+
+ # CUresult cuCtxEnablePeerAccess (CUcontext peerContext, unsigned int Flags)
+ 'cuCtxEnablePeerAccess': (c_int, cu_context, c_int),
+
+ # CUresult cuDeviceCanAccessPeer ( int* canAccessPeer,
+ # CUdevice dev, CUdevice peerDev )
+ 'cuDeviceCanAccessPeer': (c_int,
+ POINTER(c_int), cu_device, cu_device),
+
+ # CUresult cuDeviceGetUuid ( CUuuid* uuid, CUdevice dev )
+ 'cuDeviceGetUuid': (c_int, POINTER(cu_uuid), cu_device),
+}
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/dummyarray.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/dummyarray.py
new file mode 100644
index 0000000000000000000000000000000000000000..38e1b890e660dbe9f79ffce1b1a31766be60068b
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/dummyarray.py
@@ -0,0 +1,452 @@
+from collections import namedtuple
+import itertools
+import functools
+import operator
+import ctypes
+
+import numpy as np
+
+from numba import _helperlib
+
+Extent = namedtuple("Extent", ["begin", "end"])
+
+attempt_nocopy_reshape = ctypes.CFUNCTYPE(
+ ctypes.c_int,
+ ctypes.c_long, # nd
+ np.ctypeslib.ndpointer(np.ctypeslib.c_intp, ndim=1), # dims
+ np.ctypeslib.ndpointer(np.ctypeslib.c_intp, ndim=1), # strides
+ ctypes.c_long, # newnd
+ np.ctypeslib.ndpointer(np.ctypeslib.c_intp, ndim=1), # newdims
+ np.ctypeslib.ndpointer(np.ctypeslib.c_intp, ndim=1), # newstrides
+ ctypes.c_long, # itemsize
+ ctypes.c_int, # is_f_order
+)(_helperlib.c_helpers['attempt_nocopy_reshape'])
+
+
+class Dim(object):
+ """A single dimension of the array
+
+ Attributes
+ ----------
+ start:
+ start offset
+ stop:
+ stop offset
+ size:
+ number of items
+ stride:
+ item stride
+ """
+ __slots__ = 'start', 'stop', 'size', 'stride', 'single'
+
+ def __init__(self, start, stop, size, stride, single):
+ self.start = start
+ self.stop = stop
+ self.size = size
+ self.stride = stride
+ self.single = single
+ assert not single or size == 1
+
+ def __getitem__(self, item):
+ if isinstance(item, slice):
+ start, stop, step = item.indices(self.size)
+ stride = step * self.stride
+ start = self.start + start * abs(self.stride)
+ stop = self.start + stop * abs(self.stride)
+ if stride == 0:
+ size = 1
+ else:
+ size = _compute_size(start, stop, stride)
+ ret = Dim(
+ start=start,
+ stop=stop,
+ size=size,
+ stride=stride,
+ single=False
+ )
+ return ret
+ else:
+ sliced = self[item:item + 1] if item != -1 else self[-1:]
+ if sliced.size != 1:
+ raise IndexError
+ return Dim(
+ start=sliced.start,
+ stop=sliced.stop,
+ size=sliced.size,
+ stride=sliced.stride,
+ single=True,
+ )
+
+ def get_offset(self, idx):
+ return self.start + idx * self.stride
+
+ def __repr__(self):
+ strfmt = "Dim(start=%s, stop=%s, size=%s, stride=%s)"
+ return strfmt % (self.start, self.stop, self.size, self.stride)
+
+ def normalize(self, base):
+ return Dim(start=self.start - base, stop=self.stop - base,
+ size=self.size, stride=self.stride, single=self.single)
+
+ def copy(self, start=None, stop=None, size=None, stride=None, single=None):
+ if start is None:
+ start = self.start
+ if stop is None:
+ stop = self.stop
+ if size is None:
+ size = self.size
+ if stride is None:
+ stride = self.stride
+ if single is None:
+ single = self.single
+ return Dim(start, stop, size, stride, single)
+
+ def is_contiguous(self, itemsize):
+ return self.stride == itemsize
+
+
+def compute_index(indices, dims):
+ return sum(d.get_offset(i) for i, d in zip(indices, dims))
+
+
+class Element(object):
+ is_array = False
+
+ def __init__(self, extent):
+ self.extent = extent
+
+ def iter_contiguous_extent(self):
+ yield self.extent
+
+
+class Array(object):
+ """A dummy numpy array-like object. Consider it an array without the
+ actual data, but offset from the base data pointer.
+
+ Attributes
+ ----------
+ dims: tuple of Dim
+ describing each dimension of the array
+
+ ndim: int
+ number of dimension
+
+ shape: tuple of int
+ size of each dimension
+
+ strides: tuple of int
+ stride of each dimension
+
+ itemsize: int
+ itemsize
+
+ extent: (start, end)
+ start and end offset containing the memory region
+ """
+ is_array = True
+
+ @classmethod
+ def from_desc(cls, offset, shape, strides, itemsize):
+ dims = []
+ for ashape, astride in zip(shape, strides):
+ dim = Dim(offset, offset + ashape * astride, ashape, astride,
+ single=False)
+ dims.append(dim)
+ offset = 0 # offset only applies to first dimension
+ return cls(dims, itemsize)
+
+ def __init__(self, dims, itemsize):
+ self.dims = tuple(dims)
+ self.ndim = len(self.dims)
+ self.shape = tuple(dim.size for dim in self.dims)
+ self.strides = tuple(dim.stride for dim in self.dims)
+ self.itemsize = itemsize
+ self.size = functools.reduce(operator.mul, self.shape, 1)
+ self.extent = self._compute_extent()
+ self.flags = self._compute_layout()
+
+ def _compute_layout(self):
+ # The logic here is based on that in _UpdateContiguousFlags from
+ # numpy/core/src/multiarray/flagsobject.c in NumPy v1.19.1 (commit
+ # 13661ac70).
+ # https://github.com/numpy/numpy/blob/maintenance/1.19.x/numpy/core/src/multiarray/flagsobject.c#L123-L191
+
+ # Records have no dims, and we can treat them as contiguous
+ if not self.dims:
+ return {'C_CONTIGUOUS': True, 'F_CONTIGUOUS': True}
+
+ # If this is a broadcast array then it is not contiguous
+ if any([dim.stride == 0 for dim in self.dims]):
+ return {'C_CONTIGUOUS': False, 'F_CONTIGUOUS': False}
+
+ flags = {'C_CONTIGUOUS': True, 'F_CONTIGUOUS': True}
+
+ # Check C contiguity
+ sd = self.itemsize
+ for dim in reversed(self.dims):
+ if dim.size == 0:
+ # Contiguous by definition
+ return {'C_CONTIGUOUS': True, 'F_CONTIGUOUS': True}
+ if dim.size != 1:
+ if dim.stride != sd:
+ flags['C_CONTIGUOUS'] = False
+ sd *= dim.size
+
+ # Check F contiguity
+ sd = self.itemsize
+ for dim in self.dims:
+ if dim.size != 1:
+ if dim.stride != sd:
+ flags['F_CONTIGUOUS'] = False
+ return flags
+ sd *= dim.size
+
+ return flags
+
+ def _compute_extent(self):
+ firstidx = [0] * self.ndim
+ lastidx = [s - 1 for s in self.shape]
+ start = compute_index(firstidx, self.dims)
+ stop = compute_index(lastidx, self.dims) + self.itemsize
+ stop = max(stop, start) # ensure positive extent
+ return Extent(start, stop)
+
+ def __repr__(self):
+ return '' % (self.dims, self.itemsize)
+
+ def __getitem__(self, item):
+ if not isinstance(item, tuple):
+ item = [item]
+ else:
+ item = list(item)
+
+ nitem = len(item)
+ ndim = len(self.dims)
+ if nitem > ndim:
+ raise IndexError("%d extra indices given" % (nitem - ndim,))
+
+ # Add empty slices for missing indices
+ while len(item) < ndim:
+ item.append(slice(None, None))
+
+ dims = [dim.__getitem__(it) for dim, it in zip(self.dims, item)]
+ newshape = [d.size for d in dims if not d.single]
+
+ arr = Array(dims, self.itemsize)
+ if newshape:
+ return arr.reshape(*newshape)[0]
+ else:
+ return Element(arr.extent)
+
+ @property
+ def is_c_contig(self):
+ return self.flags['C_CONTIGUOUS']
+
+ @property
+ def is_f_contig(self):
+ return self.flags['F_CONTIGUOUS']
+
+ def iter_contiguous_extent(self):
+ """ Generates extents
+ """
+ if self.is_c_contig or self.is_f_contig:
+ yield self.extent
+ else:
+ if self.dims[0].stride < self.dims[-1].stride:
+ innerdim = self.dims[0]
+ outerdims = self.dims[1:]
+ outershape = self.shape[1:]
+ else:
+ innerdim = self.dims[-1]
+ outerdims = self.dims[:-1]
+ outershape = self.shape[:-1]
+
+ if innerdim.is_contiguous(self.itemsize):
+ oslen = [range(s) for s in outershape]
+ for indices in itertools.product(*oslen):
+ base = compute_index(indices, outerdims)
+ yield base + innerdim.start, base + innerdim.stop
+ else:
+ oslen = [range(s) for s in self.shape]
+ for indices in itertools.product(*oslen):
+ offset = compute_index(indices, self.dims)
+ yield offset, offset + self.itemsize
+
+ def reshape(self, *newdims, **kws):
+ oldnd = self.ndim
+ newnd = len(newdims)
+
+ if newdims == self.shape:
+ return self, None
+
+ order = kws.pop('order', 'C')
+ if kws:
+ raise TypeError('unknown keyword arguments %s' % kws.keys())
+ if order not in 'CFA':
+ raise ValueError('order not C|F|A')
+
+ # check for exactly one instance of -1 in newdims
+ # https://github.com/numpy/numpy/blob/623bc1fae1d47df24e7f1e29321d0c0ba2771ce0/numpy/core/src/multiarray/shape.c#L470-L515 # noqa: E501
+ unknownidx = -1
+ knownsize = 1
+ for i, dim in enumerate(newdims):
+ if dim < 0:
+ if unknownidx == -1:
+ unknownidx = i
+ else:
+ raise ValueError("can only specify one unknown dimension")
+ else:
+ knownsize *= dim
+
+ # compute the missing dimension
+ if unknownidx >= 0:
+ if knownsize == 0 or self.size % knownsize != 0:
+ raise ValueError("cannot infer valid shape "
+ "for unknown dimension")
+ else:
+ newdims = newdims[0:unknownidx] \
+ + (self.size // knownsize,) \
+ + newdims[unknownidx + 1:]
+
+ newsize = functools.reduce(operator.mul, newdims, 1)
+
+ if order == 'A':
+ order = 'F' if self.is_f_contig else 'C'
+
+ if newsize != self.size:
+ raise ValueError("reshape changes the size of the array")
+
+ if self.is_c_contig or self.is_f_contig:
+ if order == 'C':
+ newstrides = list(iter_strides_c_contig(self, newdims))
+ elif order == 'F':
+ newstrides = list(iter_strides_f_contig(self, newdims))
+ else:
+ raise AssertionError("unreachable")
+ else:
+ newstrides = np.empty(newnd, np.ctypeslib.c_intp)
+
+ # need to keep these around in variables, not temporaries, so they
+ # don't get GC'ed before we call into the C code
+ olddims = np.array(self.shape, dtype=np.ctypeslib.c_intp)
+ oldstrides = np.array(self.strides, dtype=np.ctypeslib.c_intp)
+ newdims = np.array(newdims, dtype=np.ctypeslib.c_intp)
+
+ if not attempt_nocopy_reshape(
+ oldnd,
+ olddims,
+ oldstrides,
+ newnd,
+ newdims,
+ newstrides,
+ self.itemsize,
+ order == 'F',
+ ):
+ raise NotImplementedError('reshape would require copy')
+
+ ret = self.from_desc(self.extent.begin, shape=newdims,
+ strides=newstrides, itemsize=self.itemsize)
+
+ return ret, list(self.iter_contiguous_extent())
+
+ def squeeze(self, axis=None):
+ newshape, newstrides = [], []
+ if axis is None:
+ for length, stride in zip(self.shape, self.strides):
+ if length != 1:
+ newshape.append(length)
+ newstrides.append(stride)
+ else:
+ if not isinstance(axis, tuple):
+ axis = (axis,)
+ for ax in axis:
+ if self.shape[ax] != 1:
+ raise ValueError(
+ "cannot select an axis to squeeze out which has size "
+ "not equal to one"
+ )
+ for i, (length, stride) in enumerate(zip(self.shape, self.strides)):
+ if i not in axis:
+ newshape.append(length)
+ newstrides.append(stride)
+ newarr = self.from_desc(
+ self.extent.begin,
+ shape=newshape,
+ strides=newstrides,
+ itemsize=self.itemsize,
+ )
+ return newarr, list(self.iter_contiguous_extent())
+
+ def ravel(self, order='C'):
+ if order not in 'CFA':
+ raise ValueError('order not C|F|A')
+
+ if (order in 'CA' and self.is_c_contig
+ or order in 'FA' and self.is_f_contig):
+ newshape = (self.size,)
+ newstrides = (self.itemsize,)
+ arr = self.from_desc(self.extent.begin, newshape, newstrides,
+ self.itemsize)
+ return arr, list(self.iter_contiguous_extent())
+
+ else:
+ raise NotImplementedError("ravel on non-contiguous array")
+
+
+def iter_strides_f_contig(arr, shape=None):
+ """yields the f-contiguous strides
+ """
+ shape = arr.shape if shape is None else shape
+ itemsize = arr.itemsize
+ yield itemsize
+ sum = 1
+ for s in shape[:-1]:
+ sum *= s
+ yield sum * itemsize
+
+
+def iter_strides_c_contig(arr, shape=None):
+ """yields the c-contiguous strides
+ """
+ shape = arr.shape if shape is None else shape
+ itemsize = arr.itemsize
+
+ def gen():
+ yield itemsize
+ sum = 1
+ for s in reversed(shape[1:]):
+ sum *= s
+ yield sum * itemsize
+
+ for i in reversed(list(gen())):
+ yield i
+
+
+def is_element_indexing(item, ndim):
+ if isinstance(item, slice):
+ return False
+
+ elif isinstance(item, tuple):
+ if len(item) == ndim:
+ if not any(isinstance(it, slice) for it in item):
+ return True
+
+ else:
+ return True
+
+ return False
+
+
+def _compute_size(start, stop, step):
+ """Algorithm adapted from cpython rangeobject.c
+ """
+ if step > 0:
+ lo = start
+ hi = stop
+ else:
+ lo = stop
+ hi = start
+ step = -step
+ if lo >= hi:
+ return 0
+ return (hi - lo - 1) // step + 1
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/enums.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/enums.py
new file mode 100644
index 0000000000000000000000000000000000000000..3431cf72c99bf4576bff892f9f4ad80388d9fc39
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/enums.py
@@ -0,0 +1,607 @@
+"""
+Enum values for CUDA driver. Information about the values
+can be found on the official NVIDIA documentation website.
+ref: https://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__TYPES.html
+anchor: #group__CUDA__TYPES
+"""
+
+
+# Error codes
+
+CUDA_SUCCESS = 0
+CUDA_ERROR_INVALID_VALUE = 1
+CUDA_ERROR_OUT_OF_MEMORY = 2
+CUDA_ERROR_NOT_INITIALIZED = 3
+CUDA_ERROR_DEINITIALIZED = 4
+CUDA_ERROR_PROFILER_DISABLED = 5
+CUDA_ERROR_PROFILER_NOT_INITIALIZED = 6
+CUDA_ERROR_PROFILER_ALREADY_STARTED = 7
+CUDA_ERROR_PROFILER_ALREADY_STOPPED = 8
+CUDA_ERROR_STUB_LIBRARY = 34
+CUDA_ERROR_DEVICE_UNAVAILABLE = 46
+CUDA_ERROR_NO_DEVICE = 100
+CUDA_ERROR_INVALID_DEVICE = 101
+CUDA_ERROR_DEVICE_NOT_LICENSED = 102
+CUDA_ERROR_INVALID_IMAGE = 200
+CUDA_ERROR_INVALID_CONTEXT = 201
+CUDA_ERROR_CONTEXT_ALREADY_CURRENT = 202
+CUDA_ERROR_MAP_FAILED = 205
+CUDA_ERROR_UNMAP_FAILED = 206
+CUDA_ERROR_ARRAY_IS_MAPPED = 207
+CUDA_ERROR_ALREADY_MAPPED = 208
+CUDA_ERROR_NO_BINARY_FOR_GPU = 209
+CUDA_ERROR_ALREADY_ACQUIRED = 210
+CUDA_ERROR_NOT_MAPPED = 211
+CUDA_ERROR_NOT_MAPPED_AS_ARRAY = 212
+CUDA_ERROR_NOT_MAPPED_AS_POINTER = 213
+CUDA_ERROR_ECC_UNCORRECTABLE = 214
+CUDA_ERROR_UNSUPPORTED_LIMIT = 215
+CUDA_ERROR_CONTEXT_ALREADY_IN_USE = 216
+CUDA_ERROR_PEER_ACCESS_UNSUPPORTED = 217
+CUDA_ERROR_INVALID_PTX = 218
+CUDA_ERROR_INVALID_GRAPHICS_CONTEXT = 219
+CUDA_ERROR_NVLINK_UNCORRECTABLE = 220
+CUDA_ERROR_JIT_COMPILER_NOT_FOUND = 221
+CUDA_ERROR_UNSUPPORTED_PTX_VERSION = 222
+CUDA_ERROR_JIT_COMPILATION_DISABLED = 223
+CUDA_ERROR_UNSUPPORTED_EXEC_AFFINITY = 224
+CUDA_ERROR_UNSUPPORTED_DEVSIDE_SYNC = 225
+CUDA_ERROR_INVALID_SOURCE = 300
+CUDA_ERROR_FILE_NOT_FOUND = 301
+CUDA_ERROR_SHARED_OBJECT_SYMBOL_NOT_FOUND = 302
+CUDA_ERROR_SHARED_OBJECT_INIT_FAILED = 303
+CUDA_ERROR_OPERATING_SYSTEM = 304
+CUDA_ERROR_INVALID_HANDLE = 400
+CUDA_ERROR_ILLEGAL_STATE = 401
+CUDA_ERROR_NOT_FOUND = 500
+CUDA_ERROR_NOT_READY = 600
+CUDA_ERROR_LAUNCH_FAILED = 700
+CUDA_ERROR_LAUNCH_OUT_OF_RESOURCES = 701
+CUDA_ERROR_LAUNCH_TIMEOUT = 702
+CUDA_ERROR_LAUNCH_INCOMPATIBLE_TEXTURING = 703
+CUDA_ERROR_PEER_ACCESS_ALREADY_ENABLED = 704
+CUDA_ERROR_PEER_ACCESS_NOT_ENABLED = 705
+CUDA_ERROR_PRIMARY_CONTEXT_ACTIVE = 708
+CUDA_ERROR_CONTEXT_IS_DESTROYED = 709
+CUDA_ERROR_ASSERT = 710
+CUDA_ERROR_TOO_MANY_PEERS = 711
+CUDA_ERROR_HOST_MEMORY_ALREADY_REGISTERED = 712
+CUDA_ERROR_HOST_MEMORY_NOT_REGISTERED = 713
+CUDA_ERROR_HARDWARE_STACK_ERROR = 714
+CUDA_ERROR_ILLEGAL_INSTRUCTION = 715
+CUDA_ERROR_MISALIGNED_ADDRESS = 716
+CUDA_ERROR_INVALID_ADDRESS_SPACE = 717
+CUDA_ERROR_INVALID_PC = 718
+CUDA_ERROR_LAUNCH_FAILED = 719
+CUDA_ERROR_COOPERATIVE_LAUNCH_TOO_LARGE = 720
+CUDA_ERROR_NOT_PERMITTED = 800
+CUDA_ERROR_NOT_SUPPORTED = 801
+CUDA_ERROR_SYSTEM_NOT_READY = 802
+CUDA_ERROR_SYSTEM_DRIVER_MISMATCH = 803
+CUDA_ERROR_COMPAT_NOT_SUPPORTED_ON_DEVICE = 804
+CUDA_ERROR_MPS_CONNECTION_FAILED = 805
+CUDA_ERROR_MPS_RPC_FAILURE = 806
+CUDA_ERROR_MPS_SERVER_NOT_READY = 807
+CUDA_ERROR_MPS_MAX_CLIENTS_REACHED = 808
+CUDA_ERROR_MPS_MAX_CONNECTIONS_REACHED = 809
+CUDA_ERROR_MPS_CLIENT_TERMINATED = 810
+CUDA_ERROR_CDP_NOT_SUPPORTED = 811
+CUDA_ERROR_CDP_VERSION_MISMATCH = 812
+CUDA_ERROR_STREAM_CAPTURE_UNSUPPORTED = 900
+CUDA_ERROR_STREAM_CAPTURE_INVALIDATED = 901
+CUDA_ERROR_STREAM_CAPTURE_MERGE = 902
+CUDA_ERROR_STREAM_CAPTURE_UNMATCHED = 903
+CUDA_ERROR_STREAM_CAPTURE_UNJOINED = 904
+CUDA_ERROR_STREAM_CAPTURE_ISOLATION = 905
+CUDA_ERROR_STREAM_CAPTURE_IMPLICIT = 906
+CUDA_ERROR_CAPTURED_EVENT = 907
+CUDA_ERROR_STREAM_CAPTURE_WRONG_THREAD = 908
+CUDA_ERROR_TIMEOUT = 909
+CUDA_ERROR_GRAPH_EXEC_UPDATE_FAILURE = 910
+CUDA_ERROR_EXTERNAL_DEVICE = 911
+CUDA_ERROR_INVALID_CLUSTER_SIZE = 912
+CUDA_ERROR_UNKNOWN = 999
+
+
+# Function cache configurations
+
+# no preference for shared memory or L1 (default)
+CU_FUNC_CACHE_PREFER_NONE = 0x00
+# prefer larger shared memory and smaller L1 cache
+CU_FUNC_CACHE_PREFER_SHARED = 0x01
+# prefer larger L1 cache and smaller shared memory
+CU_FUNC_CACHE_PREFER_L1 = 0x02
+# prefer equal sized L1 cache and shared memory
+CU_FUNC_CACHE_PREFER_EQUAL = 0x03
+
+
+# Context creation flags
+
+# Automatic scheduling
+CU_CTX_SCHED_AUTO = 0x00
+# Set spin as default scheduling
+CU_CTX_SCHED_SPIN = 0x01
+# Set yield as default scheduling
+CU_CTX_SCHED_YIELD = 0x02
+# Set blocking synchronization as default scheduling
+CU_CTX_SCHED_BLOCKING_SYNC = 0x04
+
+CU_CTX_SCHED_MASK = 0x07
+# Support mapped pinned allocations
+# This flag was deprecated as of CUDA 11.0 and it no longer has effect.
+# All contexts as of CUDA 3.2 behave as though the flag is enabled.
+CU_CTX_MAP_HOST = 0x08
+# Keep local memory allocation after launch
+CU_CTX_LMEM_RESIZE_TO_MAX = 0x10
+# Trigger coredumps from exceptions in this context
+CU_CTX_COREDUMP_ENABLE = 0x20
+# Enable user pipe to trigger coredumps in this context
+CU_CTX_USER_COREDUMP_ENABLE = 0x40
+# Force synchronous blocking on cudaMemcpy/cudaMemset
+CU_CTX_SYNC_MEMOPS = 0x80
+
+CU_CTX_FLAGS_MASK = 0xff
+
+
+# DEFINES
+
+# If set, host memory is portable between CUDA contexts.
+# Flag for cuMemHostAlloc()
+CU_MEMHOSTALLOC_PORTABLE = 0x01
+
+# If set, host memory is mapped into CUDA address space and
+# cuMemHostGetDevicePointer() may be called on the host pointer.
+# Flag for cuMemHostAlloc()
+CU_MEMHOSTALLOC_DEVICEMAP = 0x02
+
+# If set, host memory is allocated as write-combined - fast to write,
+# faster to DMA, slow to read except via SSE4 streaming load instruction
+# (MOVNTDQA).
+# Flag for cuMemHostAlloc()
+CU_MEMHOSTALLOC_WRITECOMBINED = 0x04
+
+
+# If set, host memory is portable between CUDA contexts.
+# Flag for cuMemHostRegister()
+CU_MEMHOSTREGISTER_PORTABLE = 0x01
+
+# If set, host memory is mapped into CUDA address space and
+# cuMemHostGetDevicePointer() may be called on the host pointer.
+# Flag for cuMemHostRegister()
+CU_MEMHOSTREGISTER_DEVICEMAP = 0x02
+
+# If set, the passed memory pointer is treated as pointing to some
+# memory-mapped I/O space, e.g. belonging to a third-party PCIe device.
+# On Windows the flag is a no-op. On Linux that memory is marked
+# as non cache-coherent for the GPU and is expected
+# to be physically contiguous. It may return CUDA_ERROR_NOT_PERMITTED
+# if run as an unprivileged user, CUDA_ERROR_NOT_SUPPORTED on older
+# Linux kernel versions. On all other platforms, it is not supported
+# and CUDA_ERROR_NOT_SUPPORTED is returned.
+# Flag for cuMemHostRegister()
+CU_MEMHOSTREGISTER_IOMEMORY = 0x04
+
+# If set, the passed memory pointer is treated as pointing to memory
+# that is considered read-only by the device. On platforms without
+# CU_DEVICE_ATTRIBUTE_PAGEABLE_MEMORY_ACCESS_USES_HOST_PAGE_TABLES,
+# this flag is required in order to register memory mapped
+# to the CPU as read-only. Support for the use of this flag can be
+# queried from the device attribute
+# CU_DEVICE_ATTRIBUTE_READ_ONLY_HOST_REGISTER_SUPPORTED.
+# Using this flag with a current context associated with a device
+# that does not have this attribute set will cause cuMemHostRegister
+# to error with CUDA_ERROR_NOT_SUPPORTED.
+CU_MEMHOSTREGISTER_READ_ONLY = 0x08
+
+
+# CUDA Mem Attach Flags
+
+# If set, managed memory is accessible from all streams on all devices.
+CU_MEM_ATTACH_GLOBAL = 0x01
+
+# If set on a platform where the device attribute
+# cudaDevAttrConcurrentManagedAccess is zero, then managed memory is
+# only accessible on the host (unless explicitly attached to a stream
+# with cudaStreamAttachMemAsync, in which case it can be used in kernels
+# launched on that stream).
+CU_MEM_ATTACH_HOST = 0x02
+
+# If set on a platform where the device attribute
+# cudaDevAttrConcurrentManagedAccess is zero, then managed memory accesses
+# on the associated device must only be from a single stream.
+CU_MEM_ATTACH_SINGLE = 0x04
+
+
+# Event creation flags
+
+# Default event flag
+CU_EVENT_DEFAULT = 0x0
+# Event uses blocking synchronization
+CU_EVENT_BLOCKING_SYNC = 0x1
+# Event will not record timing data
+CU_EVENT_DISABLE_TIMING = 0x2
+# Event is suitable for interprocess use. CU_EVENT_DISABLE_TIMING must be set
+CU_EVENT_INTERPROCESS = 0x4
+
+
+# Pointer information
+
+# The CUcontext on which a pointer was allocated or registered
+CU_POINTER_ATTRIBUTE_CONTEXT = 1
+# The CUmemorytype describing the physical location of a pointer
+CU_POINTER_ATTRIBUTE_MEMORY_TYPE = 2
+# The address at which a pointer's memory may be accessed on the device
+CU_POINTER_ATTRIBUTE_DEVICE_POINTER = 3
+# The address at which a pointer's memory may be accessed on the host
+CU_POINTER_ATTRIBUTE_HOST_POINTER = 4
+# A pair of tokens for use with the nv-p2p.h Linux kernel interface
+CU_POINTER_ATTRIBUTE_P2P_TOKENS = 5
+# Synchronize every synchronous memory operation initiated on this region
+CU_POINTER_ATTRIBUTE_SYNC_MEMOPS = 6
+# A process-wide unique ID for an allocated memory region
+CU_POINTER_ATTRIBUTE_BUFFER_ID = 7
+# Indicates if the pointer points to managed memory
+CU_POINTER_ATTRIBUTE_IS_MANAGED = 8
+# A device ordinal of a device on which a pointer was allocated or registered
+CU_POINTER_ATTRIBUTE_DEVICE_ORDINAL = 9
+# 1 if this pointer maps to an allocation
+# that is suitable for cudaIpcGetMemHandle, 0 otherwise
+CU_POINTER_ATTRIBUTE_IS_LEGACY_CUDA_IPC_CAPABLE = 10
+# Starting address for this requested pointer
+CU_POINTER_ATTRIBUTE_RANGE_START_ADDR = 11
+# Size of the address range for this requested pointer
+CU_POINTER_ATTRIBUTE_RANGE_SIZE = 12
+# 1 if this pointer is in a valid address range
+# that is mapped to a backing allocation, 0 otherwise
+CU_POINTER_ATTRIBUTE_MAPPED = 13
+# Bitmask of allowed CUmemAllocationHandleType for this allocation
+CU_POINTER_ATTRIBUTE_ALLOWED_HANDLE_TYPES = 14
+# 1 if the memory this pointer is referencing
+# can be used with the GPUDirect RDMA API
+CU_POINTER_ATTRIBUTE_IS_GPU_DIRECT_RDMA_CAPABLE = 15
+# Returns the access flags the device associated
+# with the current context has on the corresponding
+# memory referenced by the pointer given
+CU_POINTER_ATTRIBUTE_ACCESS_FLAGS = 16
+# Returns the mempool handle for the allocation
+# if it was allocated from a mempool. Otherwise returns NULL
+CU_POINTER_ATTRIBUTE_MEMPOOL_HANDLE = 17
+# Size of the actual underlying mapping that the pointer belongs to
+CU_POINTER_ATTRIBUTE_MAPPING_SIZE = 18
+# The start address of the mapping that the pointer belongs to
+CU_POINTER_ATTRIBUTE_MAPPING_BASE_ADDR = 19
+# A process-wide unique id corresponding to the
+# physical allocation the pointer belongs to
+CU_POINTER_ATTRIBUTE_MEMORY_BLOCK_ID = 20
+
+
+# Memory types
+
+# Host memory
+CU_MEMORYTYPE_HOST = 0x01
+# Device memory
+CU_MEMORYTYPE_DEVICE = 0x02
+# Array memory
+CU_MEMORYTYPE_ARRAY = 0x03
+# Unified device or host memory
+CU_MEMORYTYPE_UNIFIED = 0x04
+
+
+# Device code formats
+
+# Compiled device-class-specific device code
+# Applicable options: none
+CU_JIT_INPUT_CUBIN = 0
+
+# PTX source code
+# Applicable options: PTX compiler options
+CU_JIT_INPUT_PTX = 1
+
+# Bundle of multiple cubins and/or PTX of some device code
+# Applicable options: PTX compiler options, ::CU_JIT_FALLBACK_STRATEGY
+CU_JIT_INPUT_FATBINARY = 2
+
+# Host object with embedded device code
+# Applicable options: PTX compiler options, ::CU_JIT_FALLBACK_STRATEGY
+CU_JIT_INPUT_OBJECT = 3
+
+# Archive of host objects with embedded device code
+# Applicable options: PTX compiler options, ::CU_JIT_FALLBACK_STRATEGY
+CU_JIT_INPUT_LIBRARY = 4
+
+CU_JIT_NUM_INPUT_TYPES = 6
+
+
+# Online compiler and linker options
+
+# Max number of registers that a thread may use.
+# Option type: unsigned int
+# Applies to: compiler only
+CU_JIT_MAX_REGISTERS = 0
+
+# IN: Specifies minimum number of threads per block to target compilation
+# for
+# OUT: Returns the number of threads the compiler actually targeted.
+# This restricts the resource utilization fo the compiler (e.g. max
+# registers) such that a block with the given number of threads should be
+# able to launch based on register limitations. Note, this option does not
+# currently take into account any other resource limitations, such as
+# shared memory utilization.
+# Cannot be combined with ::CU_JIT_TARGET.
+# Option type: unsigned int
+# Applies to: compiler only
+CU_JIT_THREADS_PER_BLOCK = 1
+
+# Overwrites the option value with the total wall clock time, in
+# milliseconds, spent in the compiler and linker
+# Option type: float
+# Applies to: compiler and linker
+CU_JIT_WALL_TIME = 2
+
+# Pointer to a buffer in which to print any log messages
+# that are informational in nature (the buffer size is specified via
+# option ::CU_JIT_INFO_LOG_BUFFER_SIZE_BYTES)
+# Option type: char *
+# Applies to: compiler and linker
+CU_JIT_INFO_LOG_BUFFER = 3
+
+# IN: Log buffer size in bytes. Log messages will be capped at this size
+# (including null terminator)
+# OUT: Amount of log buffer filled with messages
+# Option type: unsigned int
+# Applies to: compiler and linker
+CU_JIT_INFO_LOG_BUFFER_SIZE_BYTES = 4
+
+# Pointer to a buffer in which to print any log messages that
+# reflect errors (the buffer size is specified via option
+# ::CU_JIT_ERROR_LOG_BUFFER_SIZE_BYTES)
+# Option type: char *
+# Applies to: compiler and linker
+CU_JIT_ERROR_LOG_BUFFER = 5
+
+# IN: Log buffer size in bytes. Log messages will be capped at this size
+# (including null terminator)
+# OUT: Amount of log buffer filled with messages
+# Option type: unsigned int
+# Applies to: compiler and linker
+CU_JIT_ERROR_LOG_BUFFER_SIZE_BYTES = 6
+
+# Level of optimizations to apply to generated code (0 - 4), with 4
+# being the default and highest level of optimizations.
+# Option type: unsigned int
+# Applies to: compiler only
+CU_JIT_OPTIMIZATION_LEVEL = 7
+
+# No option value required. Determines the target based on the current
+# attached context (default)
+# Option type: No option value needed
+# Applies to: compiler and linker
+CU_JIT_TARGET_FROM_CUCONTEXT = 8
+
+# Target is chosen based on supplied ::CUjit_target. Cannot be
+# combined with ::CU_JIT_THREADS_PER_BLOCK.
+# Option type: unsigned int for enumerated type ::CUjit_target
+# Applies to: compiler and linker
+CU_JIT_TARGET = 9
+
+# Specifies choice of fallback strategy if matching cubin is not found.
+# Choice is based on supplied ::CUjit_fallback.
+# Option type: unsigned int for enumerated type ::CUjit_fallback
+# Applies to: compiler only
+CU_JIT_FALLBACK_STRATEGY = 10
+
+# Specifies whether to create debug information in output (-g)
+# (0: false, default)
+# Option type: int
+# Applies to: compiler and linker
+CU_JIT_GENERATE_DEBUG_INFO = 11
+
+# Generate verbose log messages (0: false, default)
+# Option type: int
+# Applies to: compiler and linker
+CU_JIT_LOG_VERBOSE = 12
+
+# Generate line number information (-lineinfo) (0: false, default)
+# Option type: int
+# Applies to: compiler only
+CU_JIT_GENERATE_LINE_INFO = 13
+
+# Specifies whether to enable caching explicitly (-dlcm)
+# Choice is based on supplied ::CUjit_cacheMode_enum.
+# Option type: unsigned int for enumerated type ::CUjit_cacheMode_enum
+# Applies to: compiler only
+CU_JIT_CACHE_MODE = 14
+
+
+# CUfunction_attribute
+
+# The maximum number of threads per block, beyond which a launch of the
+# function would fail. This number depends on both the function and the
+# device on which the function is currently loaded.
+CU_FUNC_ATTRIBUTE_MAX_THREADS_PER_BLOCK = 0
+
+# The size in bytes of statically-allocated shared memory required by
+# this function. This does not include dynamically-allocated shared
+# memory requested by the user at runtime.
+CU_FUNC_ATTRIBUTE_SHARED_SIZE_BYTES = 1
+
+# The size in bytes of user-allocated constant memory required by this
+# function.
+CU_FUNC_ATTRIBUTE_CONST_SIZE_BYTES = 2
+
+# The size in bytes of local memory used by each thread of this function.
+CU_FUNC_ATTRIBUTE_LOCAL_SIZE_BYTES = 3
+
+# The number of registers used by each thread of this function.
+CU_FUNC_ATTRIBUTE_NUM_REGS = 4
+
+# The PTX virtual architecture version for which the function was
+# compiled. This value is the major PTX version * 10 + the minor PTX
+# version, so a PTX version 1.3 function would return the value 13.
+# Note that this may return the undefined value of 0 for cubins
+# compiled prior to CUDA 3.0.
+CU_FUNC_ATTRIBUTE_PTX_VERSION = 5
+
+# The binary architecture version for which the function was compiled.
+# This value is the major binary version * 10 + the minor binary version,
+# so a binary version 1.3 function would return the value 13. Note that
+# this will return a value of 10 for legacy cubins that do not have a
+# properly-encoded binary architecture version.
+CU_FUNC_ATTRIBUTE_BINARY_VERSION = 6
+
+# The attribute to indicate whether the function has been compiled
+# with user specified option "-Xptxas --dlcm=ca" set
+CU_FUNC_ATTRIBUTE_CACHE_MODE_CA = 7
+
+# The maximum size in bytes of dynamically-allocated shared memory
+# that can be used by this function. If the user-specified
+# dynamic shared memory size is larger than this value,
+# the launch will fail. See cuFuncSetAttribute, cuKernelSetAttribute
+CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES = 8
+
+# On devices where the L1 cache and shared memory use the same
+# hardware resources, this sets the shared memory carveout preference,
+# in percent of the total shared memory. Refer to
+# CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_MULTIPROCESSOR.
+# This is only a hint, and the driver can choose a different ratio
+# if required to execute the function.
+# See cuFuncSetAttribute, cuKernelSetAttribute
+CU_FUNC_ATTRIBUTE_PREFERRED_SHARED_MEMORY_CARVEOUT = 9
+
+# If this attribute is set, the kernel must launch with a valid cluster
+# size specified. See cuFuncSetAttribute, cuKernelSetAttribute
+CU_FUNC_ATTRIBUTE_CLUSTER_SIZE_MUST_BE_SET = 10
+
+# The required cluster width in blocks. The values must either all be 0
+# or all be positive. The validity of the cluster dimensions
+# is otherwise checked at launch time. If the value is set during
+# compile time, it cannot be set at runtime.
+# Setting it at runtime will return CUDA_ERROR_NOT_PERMITTED.
+# See cuFuncSetAttribute, cuKernelSetAttribute
+CU_FUNC_ATTRIBUTE_REQUIRED_CLUSTER_WIDTH = 11
+
+# The required cluster height in blocks. The values must either all be 0
+# or all be positive. The validity of the cluster dimensions
+# is otherwise checked at launch time.If the value is set during
+# compile time, it cannot be set at runtime.
+# Setting it at runtime should return CUDA_ERROR_NOT_PERMITTED.
+# See cuFuncSetAttribute, cuKernelSetAttribute
+CU_FUNC_ATTRIBUTE_REQUIRED_CLUSTER_HEIGHT = 12
+
+# The required cluster depth in blocks. The values must either all be 0
+# or all be positive. The validity of the cluster dimensions
+# is otherwise checked at launch time.If the value is set during
+# compile time, it cannot be set at runtime.
+# Setting it at runtime should return CUDA_ERROR_NOT_PERMITTED.
+# See cuFuncSetAttribute, cuKernelSetAttribute
+CU_FUNC_ATTRIBUTE_REQUIRED_CLUSTER_DEPTH = 13
+
+# Whether the function can be launched with non-portable cluster size.
+# 1 is allowed, 0 is disallowed. A non-portable cluster size may only
+# function on the specific SKUs the program is tested on.
+# The launch might fail if the program is run on a different hardware platform.
+# For more details refer to link :
+# https://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__TYPES.html#group__CUDA__TYPES
+CU_FUNC_ATTRIBUTE_NON_PORTABLE_CLUSTER_SIZE_ALLOWED = 14
+
+# The block scheduling policy of a function.
+# The value type is CUclusterSchedulingPolicy / cudaClusterSchedulingPolicy.
+# See cuFuncSetAttribute, cuKernelSetAttribute
+CU_FUNC_ATTRIBUTE_CLUSTER_SCHEDULING_POLICY_PREFERENCE = 15
+
+
+# Device attributes
+
+CU_DEVICE_ATTRIBUTE_MAX_THREADS_PER_BLOCK = 1
+CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_X = 2
+CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_Y = 3
+CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_Z = 4
+CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_X = 5
+CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_Y = 6
+CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_Z = 7
+CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_BLOCK = 8
+CU_DEVICE_ATTRIBUTE_TOTAL_CONSTANT_MEMORY = 9
+CU_DEVICE_ATTRIBUTE_WARP_SIZE = 10
+CU_DEVICE_ATTRIBUTE_MAX_PITCH = 11
+CU_DEVICE_ATTRIBUTE_MAX_REGISTERS_PER_BLOCK = 12
+CU_DEVICE_ATTRIBUTE_CLOCK_RATE = 13
+CU_DEVICE_ATTRIBUTE_TEXTURE_ALIGNMENT = 14
+CU_DEVICE_ATTRIBUTE_GPU_OVERLAP = 15
+CU_DEVICE_ATTRIBUTE_MULTIPROCESSOR_COUNT = 16
+CU_DEVICE_ATTRIBUTE_KERNEL_EXEC_TIMEOUT = 17
+CU_DEVICE_ATTRIBUTE_INTEGRATED = 18
+CU_DEVICE_ATTRIBUTE_CAN_MAP_HOST_MEMORY = 19
+CU_DEVICE_ATTRIBUTE_COMPUTE_MODE = 20
+CU_DEVICE_ATTRIBUTE_MAX_TEXTURE_1D_WIDTH = 21
+CU_DEVICE_ATTRIBUTE_MAX_TEXTURE_2D_WIDTH = 22
+CU_DEVICE_ATTRIBUTE_MAX_TEXTURE_2D_HEIGHT = 23
+CU_DEVICE_ATTRIBUTE_MAX_TEXTURE_3D_WIDTH = 24
+CU_DEVICE_ATTRIBUTE_MAX_TEXTURE_3D_HEIGHT = 25
+CU_DEVICE_ATTRIBUTE_MAX_TEXTURE_3D_DEPTH = 26
+CU_DEVICE_ATTRIBUTE_MAX_TEXTURE_2D_LAYERED_WIDTH = 27
+CU_DEVICE_ATTRIBUTE_MAX_TEXTURE_2D_LAYERED_HEIGHT = 28
+CU_DEVICE_ATTRIBUTE_MAX_TEXTURE_2D_LAYERED_LAYERS = 29
+CU_DEVICE_ATTRIBUTE_SURFACE_ALIGNMENT = 30
+CU_DEVICE_ATTRIBUTE_CONCURRENT_KERNELS = 31
+CU_DEVICE_ATTRIBUTE_ECC_ENABLED = 32
+CU_DEVICE_ATTRIBUTE_PCI_BUS_ID = 33
+CU_DEVICE_ATTRIBUTE_PCI_DEVICE_ID = 34
+CU_DEVICE_ATTRIBUTE_TCC_DRIVER = 35
+CU_DEVICE_ATTRIBUTE_MEMORY_CLOCK_RATE = 36
+CU_DEVICE_ATTRIBUTE_GLOBAL_MEMORY_BUS_WIDTH = 37
+CU_DEVICE_ATTRIBUTE_L2_CACHE_SIZE = 38
+CU_DEVICE_ATTRIBUTE_MAX_THREADS_PER_MULTI_PROCESSOR = 39
+CU_DEVICE_ATTRIBUTE_ASYNC_ENGINE_COUNT = 40
+CU_DEVICE_ATTRIBUTE_UNIFIED_ADDRESSING = 41
+CU_DEVICE_ATTRIBUTE_MAX_TEXTURE_1D_LAYERED_WIDTH = 42
+CU_DEVICE_ATTRIBUTE_MAX_TEXTURE_1D_LAYERED_LAYERS = 43
+CU_DEVICE_ATTRIBUTE_MAX_TEXTURE_2D_GATHER_WIDTH = 45
+CU_DEVICE_ATTRIBUTE_MAX_TEXTURE_2D_GATHER_HEIGHT = 46
+CU_DEVICE_ATTRIBUTE_MAX_TEXTURE_3D_WIDTH_ALT = 47
+CU_DEVICE_ATTRIBUTE_MAX_TEXTURE_3D_HEIGHT_ALT = 48
+CU_DEVICE_ATTRIBUTE_MAX_TEXTURE_3D_DEPTH_ALT = 49
+CU_DEVICE_ATTRIBUTE_PCI_DOMAIN_ID = 50
+CU_DEVICE_ATTRIBUTE_TEXTURE_PITCH_ALIGNMENT = 51
+CU_DEVICE_ATTRIBUTE_MAX_TEXTURE_CUBEMAP_WIDTH = 52
+CU_DEVICE_ATTRIBUTE_MAX_TEXTURE_CUBEMAP_LAYERED_WIDTH = 53
+CU_DEVICE_ATTRIBUTE_MAX_TEXTURE_CUBEMAP_LAYERED_LAYERS = 54
+CU_DEVICE_ATTRIBUTE_MAX_SURFACE_1D_WIDTH = 55
+CU_DEVICE_ATTRIBUTE_MAX_SURFACE_2D_WIDTH = 56
+CU_DEVICE_ATTRIBUTE_MAX_SURFACE_2D_HEIGHT = 57
+CU_DEVICE_ATTRIBUTE_MAX_SURFACE_3D_WIDTH = 58
+CU_DEVICE_ATTRIBUTE_MAX_SURFACE_3D_HEIGHT = 59
+CU_DEVICE_ATTRIBUTE_MAX_SURFACE_3D_DEPTH = 60
+CU_DEVICE_ATTRIBUTE_MAX_SURFACE_1D_LAYERED_WIDTH = 61
+CU_DEVICE_ATTRIBUTE_MAX_SURFACE_1D_LAYERED_LAYERS = 62
+CU_DEVICE_ATTRIBUTE_MAX_SURFACE_2D_LAYERED_WIDTH = 63
+CU_DEVICE_ATTRIBUTE_MAX_SURFACE_2D_LAYERED_HEIGHT = 64
+CU_DEVICE_ATTRIBUTE_MAX_SURFACE_2D_LAYERED_LAYERS = 65
+CU_DEVICE_ATTRIBUTE_MAX_SURFACE_CUBEMAP_WIDTH = 66
+CU_DEVICE_ATTRIBUTE_MAX_SURFACE_CUBEMAP_LAYERED_WIDTH = 67
+CU_DEVICE_ATTRIBUTE_MAX_SURFACE_CUBEMAP_LAYERED_LAYERS = 68
+CU_DEVICE_ATTRIBUTE_MAX_TEXTURE_1D_LINEAR_WIDTH = 69
+CU_DEVICE_ATTRIBUTE_MAX_TEXTURE_2D_LINEAR_WIDTH = 70
+CU_DEVICE_ATTRIBUTE_MAX_TEXTURE_2D_LINEAR_HEIGHT = 71
+CU_DEVICE_ATTRIBUTE_MAX_TEXTURE_2D_LINEAR_PITCH = 72
+CU_DEVICE_ATTRIBUTE_MAX_TEXTURE_2D_MIPMAPPED_WIDTH = 73
+CU_DEVICE_ATTRIBUTE_MAX_MAX_TEXTURE_2D_MIPMAPPED_HEIGHT = 74
+CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MAJOR = 75
+CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MINOR = 76
+CU_DEVICE_ATTRIBUTE_MAX_TEXTURE_1D_MIPMAPPED_WIDTH = 77
+CU_DEVICE_ATTRIBUTE_STREAM_PRIORITIES_SUPPORTED = 78
+CU_DEVICE_ATTRIBUTE_GLOBAL_L1_CACHE_SUPPORTED = 79
+CU_DEVICE_ATTRIBUTE_LOCAL_L1_CACHE_SUPPORTED = 80
+CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_MULTIPROCESSOR = 81
+CU_DEVICE_ATTRIBUTE_MAX_REGISTERS_PER_MULTIPROCESSOR = 82
+CU_DEVICE_ATTRIBUTE_MANAGED_MEMORY = 83
+CU_DEVICE_ATTRIBUTE_IS_MULTI_GPU_BOARD = 84
+CU_DEVICE_ATTRIBUTE_MULTI_GPU_BOARD_GROUP_ID = 85
+CU_DEVICE_ATTRIBUTE_HOST_NATIVE_ATOMIC_SUPPORTED = 86
+CU_DEVICE_ATTRIBUTE_SINGLE_TO_DOUBLE_PRECISION_PERF_RATIO = 87
+CU_DEVICE_ATTRIBUTE_PAGEABLE_MEMORY_ACCESS = 88
+CU_DEVICE_ATTRIBUTE_CONCURRENT_MANAGED_ACCESS = 89
+CU_DEVICE_ATTRIBUTE_COMPUTE_PREEMPTION_SUPPORTED = 90
+CU_DEVICE_ATTRIBUTE_CAN_USE_HOST_POINTER_FOR_REGISTERED_MEM = 91
+CU_DEVICE_ATTRIBUTE_COOPERATIVE_LAUNCH = 95
+CU_DEVICE_ATTRIBUTE_COOPERATIVE_MULTI_DEVICE_LAUNCH = 96
+CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_BLOCK_OPTIN = 97
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/error.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/error.py
new file mode 100644
index 0000000000000000000000000000000000000000..ec3420586b4d6b14efd4f095ac2d983a042c4861
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/error.py
@@ -0,0 +1,36 @@
+class CudaDriverError(Exception):
+ pass
+
+
+class CudaRuntimeError(Exception):
+ pass
+
+
+class CudaSupportError(ImportError):
+ pass
+
+
+class NvvmError(Exception):
+ def __str__(self):
+ return '\n'.join(map(str, self.args))
+
+
+class NvvmSupportError(ImportError):
+ pass
+
+
+class NvvmWarning(Warning):
+ pass
+
+
+class NvrtcError(Exception):
+ def __str__(self):
+ return '\n'.join(map(str, self.args))
+
+
+class NvrtcCompilationError(NvrtcError):
+ pass
+
+
+class NvrtcSupportError(ImportError):
+ pass
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/libs.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/libs.py
new file mode 100644
index 0000000000000000000000000000000000000000..ce3ed9c96e4057b9742f1a12021657fc40ea2580
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/libs.py
@@ -0,0 +1,176 @@
+"""CUDA Toolkit libraries lookup utilities.
+
+CUDA Toolkit libraries can be available via either:
+
+- the `cuda-nvcc` and `cuda-nvrtc` conda packages for CUDA 12,
+- the `cudatoolkit` conda package for CUDA 11,
+- a user supplied location from CUDA_HOME,
+- a system wide location,
+- package-specific locations (e.g. the Debian NVIDIA packages),
+- or can be discovered by the system loader.
+"""
+
+import os
+import sys
+import ctypes
+
+from numba.misc.findlib import find_lib
+from numba.cuda.cuda_paths import get_cuda_paths
+from numba.cuda.cudadrv.driver import locate_driver_and_loader, load_driver
+from numba.cuda.cudadrv.error import CudaSupportError
+
+
+if sys.platform == 'win32':
+ _dllnamepattern = '%s.dll'
+ _staticnamepattern = '%s.lib'
+elif sys.platform == 'darwin':
+ _dllnamepattern = 'lib%s.dylib'
+ _staticnamepattern = 'lib%s.a'
+else:
+ _dllnamepattern = 'lib%s.so'
+ _staticnamepattern = 'lib%s.a'
+
+
+def get_libdevice():
+ d = get_cuda_paths()
+ paths = d['libdevice'].info
+ return paths
+
+
+def open_libdevice():
+ with open(get_libdevice(), 'rb') as bcfile:
+ return bcfile.read()
+
+
+def get_cudalib(lib, static=False):
+ """
+ Find the path of a CUDA library based on a search of known locations. If
+ the search fails, return a generic filename for the library (e.g.
+ 'libnvvm.so' for 'nvvm') so that we may attempt to load it using the system
+ loader's search mechanism.
+ """
+ if lib == 'nvvm':
+ return get_cuda_paths()['nvvm'].info or _dllnamepattern % 'nvvm'
+ else:
+ dir_type = 'static_cudalib_dir' if static else 'cudalib_dir'
+ libdir = get_cuda_paths()[dir_type].info
+
+ candidates = find_lib(lib, libdir, static=static)
+ namepattern = _staticnamepattern if static else _dllnamepattern
+ return max(candidates) if candidates else namepattern % lib
+
+
+def open_cudalib(lib):
+ path = get_cudalib(lib)
+ return ctypes.CDLL(path)
+
+
+def check_static_lib(path):
+ if not os.path.isfile(path):
+ raise FileNotFoundError(f'{path} not found')
+
+
+def _get_source_variable(lib, static=False):
+ if lib == 'nvvm':
+ return get_cuda_paths()['nvvm'].by
+ elif lib == 'libdevice':
+ return get_cuda_paths()['libdevice'].by
+ else:
+ dir_type = 'static_cudalib_dir' if static else 'cudalib_dir'
+ return get_cuda_paths()[dir_type].by
+
+
+def test():
+ """Test library lookup. Path info is printed to stdout.
+ """
+ failed = False
+
+ # Check for the driver
+ try:
+ dlloader, candidates = locate_driver_and_loader()
+ print('Finding driver from candidates:')
+ for location in candidates:
+ print(f'\t{location}')
+ print(f'Using loader {dlloader}')
+ print('\tTrying to load driver', end='...')
+ dll, path = load_driver(dlloader, candidates)
+ print('\tok')
+ print(f'\t\tLoaded from {path}')
+ except CudaSupportError as e:
+ print(f'\tERROR: failed to open driver: {e}')
+ failed = True
+
+ # Find the absolute location of the driver on Linux. Various driver-related
+ # issues have been reported by WSL2 users, and it is almost always due to a
+ # Linux (i.e. not- WSL2) driver being installed in a WSL2 system.
+ # Providing the absolute location of the driver indicates its version
+ # number in the soname (e.g. "libcuda.so.530.30.02"), which can be used to
+ # look up whether the driver was intended for "native" Linux.
+ if sys.platform == 'linux' and not failed:
+ pid = os.getpid()
+ mapsfile = os.path.join(os.path.sep, 'proc', f'{pid}', 'maps')
+ try:
+ with open(mapsfile) as f:
+ maps = f.read()
+ # It's difficult to predict all that might go wrong reading the maps
+ # file - in case various error conditions ensue (the file is not found,
+ # not readable, etc.) we use OSError to hopefully catch any of them.
+ except OSError:
+ # It's helpful to report that this went wrong to the user, but we
+ # don't set failed to True because this doesn't have any connection
+ # to actual CUDA functionality.
+ print(f'\tERROR: Could not open {mapsfile} to determine absolute '
+ 'path to libcuda.so')
+ else:
+ # In this case we could read the maps, so we can report the
+ # relevant ones to the user
+ locations = set(s for s in maps.split() if 'libcuda.so' in s)
+ print('\tMapped libcuda.so paths:')
+ for location in locations:
+ print(f'\t\t{location}')
+
+ # Checks for dynamic libraries
+ libs = 'nvvm nvrtc cudart'.split()
+ for lib in libs:
+ path = get_cudalib(lib)
+ print('Finding {} from {}'.format(lib, _get_source_variable(lib)))
+ print('\tLocated at', path)
+
+ try:
+ print('\tTrying to open library', end='...')
+ open_cudalib(lib)
+ print('\tok')
+ except OSError as e:
+ print('\tERROR: failed to open %s:\n%s' % (lib, e))
+ failed = True
+
+ # Check for cudadevrt (the only static library)
+ lib = 'cudadevrt'
+ path = get_cudalib(lib, static=True)
+ print('Finding {} from {}'.format(lib, _get_source_variable(lib,
+ static=True)))
+ print('\tLocated at', path)
+
+ try:
+ print('\tChecking library', end='...')
+ check_static_lib(path)
+ print('\tok')
+ except FileNotFoundError as e:
+ print('\tERROR: failed to find %s:\n%s' % (lib, e))
+ failed = True
+
+ # Check for libdevice
+ where = _get_source_variable('libdevice')
+ print(f'Finding libdevice from {where}')
+ path = get_libdevice()
+ print('\tLocated at', path)
+
+ try:
+ print('\tChecking library', end='...')
+ check_static_lib(path)
+ print('\tok')
+ except FileNotFoundError as e:
+ print('\tERROR: failed to find %s:\n%s' % (lib, e))
+ failed = True
+
+ return not failed
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/ndarray.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/ndarray.py
new file mode 100644
index 0000000000000000000000000000000000000000..bca40dfd977dc3c657835d93fd45142d16fe46f7
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/ndarray.py
@@ -0,0 +1,20 @@
+from numba.cuda.cudadrv import devices, driver
+from numba.core.registry import cpu_target
+
+
+def _calc_array_sizeof(ndim):
+ """
+ Use the ABI size in the CPU target
+ """
+ ctx = cpu_target.target_context
+ return ctx.calc_array_sizeof(ndim)
+
+
+def ndarray_device_allocate_data(ary):
+ """
+ Allocate gpu data buffer
+ """
+ datasize = driver.host_memory_size(ary)
+ # allocate
+ gpu_data = devices.get_context().memalloc(datasize)
+ return gpu_data
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/nvrtc.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/nvrtc.py
new file mode 100644
index 0000000000000000000000000000000000000000..d10fd90b9cdafd187d2cc278c1536921f857f935
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/nvrtc.py
@@ -0,0 +1,260 @@
+from ctypes import byref, c_char, c_char_p, c_int, c_size_t, c_void_p, POINTER
+from enum import IntEnum
+from numba.core import config
+from numba.cuda.cudadrv.error import (NvrtcError, NvrtcCompilationError,
+ NvrtcSupportError)
+
+import functools
+import os
+import threading
+import warnings
+
+# Opaque handle for compilation unit
+nvrtc_program = c_void_p
+
+# Result code
+nvrtc_result = c_int
+
+
+class NvrtcResult(IntEnum):
+ NVRTC_SUCCESS = 0
+ NVRTC_ERROR_OUT_OF_MEMORY = 1
+ NVRTC_ERROR_PROGRAM_CREATION_FAILURE = 2
+ NVRTC_ERROR_INVALID_INPUT = 3
+ NVRTC_ERROR_INVALID_PROGRAM = 4
+ NVRTC_ERROR_INVALID_OPTION = 5
+ NVRTC_ERROR_COMPILATION = 6
+ NVRTC_ERROR_BUILTIN_OPERATION_FAILURE = 7
+ NVRTC_ERROR_NO_NAME_EXPRESSIONS_AFTER_COMPILATION = 8
+ NVRTC_ERROR_NO_LOWERED_NAMES_BEFORE_COMPILATION = 9
+ NVRTC_ERROR_NAME_EXPRESSION_NOT_VALID = 10
+ NVRTC_ERROR_INTERNAL_ERROR = 11
+
+
+_nvrtc_lock = threading.Lock()
+
+
+class NvrtcProgram:
+ """
+ A class for managing the lifetime of nvrtcProgram instances. Instances of
+ the class own an nvrtcProgram; when an instance is deleted, the underlying
+ nvrtcProgram is destroyed using the appropriate NVRTC API.
+ """
+ def __init__(self, nvrtc, handle):
+ self._nvrtc = nvrtc
+ self._handle = handle
+
+ @property
+ def handle(self):
+ return self._handle
+
+ def __del__(self):
+ if self._handle:
+ self._nvrtc.destroy_program(self)
+
+
+class NVRTC:
+ """
+ Provides a Pythonic interface to the NVRTC APIs, abstracting away the C API
+ calls.
+
+ The sole instance of this class is a process-wide singleton, similar to the
+ NVVM interface. Initialization is protected by a lock and uses the standard
+ (for Numba) open_cudalib function to load the NVRTC library.
+ """
+ _PROTOTYPES = {
+ # nvrtcResult nvrtcVersion(int *major, int *minor)
+ 'nvrtcVersion': (nvrtc_result, POINTER(c_int), POINTER(c_int)),
+ # nvrtcResult nvrtcCreateProgram(nvrtcProgram *prog,
+ # const char *src,
+ # const char *name,
+ # int numHeaders,
+ # const char * const *headers,
+ # const char * const *includeNames)
+ 'nvrtcCreateProgram': (nvrtc_result, nvrtc_program, c_char_p, c_char_p,
+ c_int, POINTER(c_char_p), POINTER(c_char_p)),
+ # nvrtcResult nvrtcDestroyProgram(nvrtcProgram *prog);
+ 'nvrtcDestroyProgram': (nvrtc_result, POINTER(nvrtc_program)),
+ # nvrtcResult nvrtcCompileProgram(nvrtcProgram prog,
+ # int numOptions,
+ # const char * const *options)
+ 'nvrtcCompileProgram': (nvrtc_result, nvrtc_program, c_int,
+ POINTER(c_char_p)),
+ # nvrtcResult nvrtcGetPTXSize(nvrtcProgram prog, size_t *ptxSizeRet);
+ 'nvrtcGetPTXSize': (nvrtc_result, nvrtc_program, POINTER(c_size_t)),
+ # nvrtcResult nvrtcGetPTX(nvrtcProgram prog, char *ptx);
+ 'nvrtcGetPTX': (nvrtc_result, nvrtc_program, c_char_p),
+ # nvrtcResult nvrtcGetCUBINSize(nvrtcProgram prog,
+ # size_t *cubinSizeRet);
+ 'nvrtcGetCUBINSize': (nvrtc_result, nvrtc_program, POINTER(c_size_t)),
+ # nvrtcResult nvrtcGetCUBIN(nvrtcProgram prog, char *cubin);
+ 'nvrtcGetCUBIN': (nvrtc_result, nvrtc_program, c_char_p),
+ # nvrtcResult nvrtcGetProgramLogSize(nvrtcProgram prog,
+ # size_t *logSizeRet);
+ 'nvrtcGetProgramLogSize': (nvrtc_result, nvrtc_program,
+ POINTER(c_size_t)),
+ # nvrtcResult nvrtcGetProgramLog(nvrtcProgram prog, char *log);
+ 'nvrtcGetProgramLog': (nvrtc_result, nvrtc_program, c_char_p),
+ }
+
+ # Singleton reference
+ __INSTANCE = None
+
+ def __new__(cls):
+ with _nvrtc_lock:
+ if cls.__INSTANCE is None:
+ from numba.cuda.cudadrv.libs import open_cudalib
+ cls.__INSTANCE = inst = object.__new__(cls)
+ try:
+ lib = open_cudalib('nvrtc')
+ except OSError as e:
+ cls.__INSTANCE = None
+ raise NvrtcSupportError("NVRTC cannot be loaded") from e
+
+ # Find & populate functions
+ for name, proto in inst._PROTOTYPES.items():
+ func = getattr(lib, name)
+ func.restype = proto[0]
+ func.argtypes = proto[1:]
+
+ @functools.wraps(func)
+ def checked_call(*args, func=func, name=name):
+ error = func(*args)
+ if error == NvrtcResult.NVRTC_ERROR_COMPILATION:
+ raise NvrtcCompilationError()
+ elif error != NvrtcResult.NVRTC_SUCCESS:
+ try:
+ error_name = NvrtcResult(error).name
+ except ValueError:
+ error_name = ('Unknown nvrtc_result '
+ f'(error code: {error})')
+ msg = f'Failed to call {name}: {error_name}'
+ raise NvrtcError(msg)
+
+ setattr(inst, name, checked_call)
+
+ return cls.__INSTANCE
+
+ def get_version(self):
+ """
+ Get the NVRTC version as a tuple (major, minor).
+ """
+ major = c_int()
+ minor = c_int()
+ self.nvrtcVersion(byref(major), byref(minor))
+ return major.value, minor.value
+
+ def create_program(self, src, name):
+ """
+ Create an NVRTC program with managed lifetime.
+ """
+ if isinstance(src, str):
+ src = src.encode()
+ if isinstance(name, str):
+ name = name.encode()
+
+ handle = nvrtc_program()
+
+ # The final three arguments are for passing the contents of headers -
+ # this is not supported, so there are 0 headers and the header names
+ # and contents are null.
+ self.nvrtcCreateProgram(byref(handle), src, name, 0, None, None)
+ return NvrtcProgram(self, handle)
+
+ def compile_program(self, program, options):
+ """
+ Compile an NVRTC program. Compilation may fail due to a user error in
+ the source; this function returns ``True`` if there is a compilation
+ error and ``False`` on success.
+ """
+ # We hold a list of encoded options to ensure they can't be collected
+ # prior to the call to nvrtcCompileProgram
+ encoded_options = [opt.encode() for opt in options]
+ option_pointers = [c_char_p(opt) for opt in encoded_options]
+ c_options_type = (c_char_p * len(options))
+ c_options = c_options_type(*option_pointers)
+ try:
+ self.nvrtcCompileProgram(program.handle, len(options), c_options)
+ return False
+ except NvrtcCompilationError:
+ return True
+
+ def destroy_program(self, program):
+ """
+ Destroy an NVRTC program.
+ """
+ self.nvrtcDestroyProgram(byref(program.handle))
+
+ def get_compile_log(self, program):
+ """
+ Get the compile log as a Python string.
+ """
+ log_size = c_size_t()
+ self.nvrtcGetProgramLogSize(program.handle, byref(log_size))
+
+ log = (c_char * log_size.value)()
+ self.nvrtcGetProgramLog(program.handle, log)
+
+ return log.value.decode()
+
+ def get_ptx(self, program):
+ """
+ Get the compiled PTX as a Python string.
+ """
+ ptx_size = c_size_t()
+ self.nvrtcGetPTXSize(program.handle, byref(ptx_size))
+
+ ptx = (c_char * ptx_size.value)()
+ self.nvrtcGetPTX(program.handle, ptx)
+
+ return ptx.value.decode()
+
+
+def compile(src, name, cc):
+ """
+ Compile a CUDA C/C++ source to PTX for a given compute capability.
+
+ :param src: The source code to compile
+ :type src: str
+ :param name: The filename of the source (for information only)
+ :type name: str
+ :param cc: A tuple ``(major, minor)`` of the compute capability
+ :type cc: tuple
+ :return: The compiled PTX and compilation log
+ :rtype: tuple
+ """
+ nvrtc = NVRTC()
+ program = nvrtc.create_program(src, name)
+
+ # Compilation options:
+ # - Compile for the current device's compute capability.
+ # - The CUDA include path is added.
+ # - Relocatable Device Code (rdc) is needed to prevent device functions
+ # being optimized away.
+ major, minor = cc
+ arch = f'--gpu-architecture=compute_{major}{minor}'
+ include = f'-I{config.CUDA_INCLUDE_PATH}'
+
+ cudadrv_path = os.path.dirname(os.path.abspath(__file__))
+ numba_cuda_path = os.path.dirname(cudadrv_path)
+ numba_include = f'-I{numba_cuda_path}'
+ options = [arch, include, numba_include, '-rdc', 'true']
+
+ # Compile the program
+ compile_error = nvrtc.compile_program(program, options)
+
+ # Get log from compilation
+ log = nvrtc.get_compile_log(program)
+
+ # If the compile failed, provide the log in an exception
+ if compile_error:
+ msg = (f'NVRTC Compilation failure whilst compiling {name}:\n\n{log}')
+ raise NvrtcError(msg)
+
+ # Otherwise, if there's any content in the log, present it as a warning
+ if log:
+ msg = (f"NVRTC log messages whilst compiling {name}:\n\n{log}")
+ warnings.warn(msg)
+
+ ptx = nvrtc.get_ptx(program)
+ return ptx, log
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/nvvm.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/nvvm.py
new file mode 100644
index 0000000000000000000000000000000000000000..1da13a325cae089f7bb60aaadffd0d48217e17fe
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/nvvm.py
@@ -0,0 +1,707 @@
+"""
+This is a direct translation of nvvm.h
+"""
+import logging
+import re
+import sys
+import warnings
+from ctypes import (c_void_p, c_int, POINTER, c_char_p, c_size_t, byref,
+ c_char)
+
+import threading
+
+from llvmlite import ir
+
+from .error import NvvmError, NvvmSupportError, NvvmWarning
+from .libs import get_libdevice, open_libdevice, open_cudalib
+from numba.core import cgutils, config
+
+
+logger = logging.getLogger(__name__)
+
+ADDRSPACE_GENERIC = 0
+ADDRSPACE_GLOBAL = 1
+ADDRSPACE_SHARED = 3
+ADDRSPACE_CONSTANT = 4
+ADDRSPACE_LOCAL = 5
+
+# Opaque handle for compilation unit
+nvvm_program = c_void_p
+
+# Result code
+nvvm_result = c_int
+
+RESULT_CODE_NAMES = '''
+NVVM_SUCCESS
+NVVM_ERROR_OUT_OF_MEMORY
+NVVM_ERROR_PROGRAM_CREATION_FAILURE
+NVVM_ERROR_IR_VERSION_MISMATCH
+NVVM_ERROR_INVALID_INPUT
+NVVM_ERROR_INVALID_PROGRAM
+NVVM_ERROR_INVALID_IR
+NVVM_ERROR_INVALID_OPTION
+NVVM_ERROR_NO_MODULE_IN_PROGRAM
+NVVM_ERROR_COMPILATION
+'''.split()
+
+for i, k in enumerate(RESULT_CODE_NAMES):
+ setattr(sys.modules[__name__], k, i)
+
+# Data layouts. NVVM IR 1.8 (CUDA 11.6) introduced 128-bit integer support.
+
+_datalayout_original = ('e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-'
+ 'i64:64:64-f32:32:32-f64:64:64-v16:16:16-v32:32:32-'
+ 'v64:64:64-v128:128:128-n16:32:64')
+_datalayout_i128 = ('e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-'
+ 'i128:128:128-f32:32:32-f64:64:64-v16:16:16-v32:32:32-'
+ 'v64:64:64-v128:128:128-n16:32:64')
+
+
+def is_available():
+ """
+ Return if libNVVM is available
+ """
+ try:
+ NVVM()
+ except NvvmSupportError:
+ return False
+ else:
+ return True
+
+
+_nvvm_lock = threading.Lock()
+
+
+class NVVM(object):
+ '''Process-wide singleton.
+ '''
+ _PROTOTYPES = {
+
+ # nvvmResult nvvmVersion(int *major, int *minor)
+ 'nvvmVersion': (nvvm_result, POINTER(c_int), POINTER(c_int)),
+
+ # nvvmResult nvvmCreateProgram(nvvmProgram *cu)
+ 'nvvmCreateProgram': (nvvm_result, POINTER(nvvm_program)),
+
+ # nvvmResult nvvmDestroyProgram(nvvmProgram *cu)
+ 'nvvmDestroyProgram': (nvvm_result, POINTER(nvvm_program)),
+
+ # nvvmResult nvvmAddModuleToProgram(nvvmProgram cu, const char *buffer,
+ # size_t size, const char *name)
+ 'nvvmAddModuleToProgram': (
+ nvvm_result, nvvm_program, c_char_p, c_size_t, c_char_p),
+
+ # nvvmResult nvvmLazyAddModuleToProgram(nvvmProgram cu,
+ # const char* buffer,
+ # size_t size,
+ # const char *name)
+ 'nvvmLazyAddModuleToProgram': (
+ nvvm_result, nvvm_program, c_char_p, c_size_t, c_char_p),
+
+ # nvvmResult nvvmCompileProgram(nvvmProgram cu, int numOptions,
+ # const char **options)
+ 'nvvmCompileProgram': (
+ nvvm_result, nvvm_program, c_int, POINTER(c_char_p)),
+
+ # nvvmResult nvvmGetCompiledResultSize(nvvmProgram cu,
+ # size_t *bufferSizeRet)
+ 'nvvmGetCompiledResultSize': (
+ nvvm_result, nvvm_program, POINTER(c_size_t)),
+
+ # nvvmResult nvvmGetCompiledResult(nvvmProgram cu, char *buffer)
+ 'nvvmGetCompiledResult': (nvvm_result, nvvm_program, c_char_p),
+
+ # nvvmResult nvvmGetProgramLogSize(nvvmProgram cu,
+ # size_t *bufferSizeRet)
+ 'nvvmGetProgramLogSize': (nvvm_result, nvvm_program, POINTER(c_size_t)),
+
+ # nvvmResult nvvmGetProgramLog(nvvmProgram cu, char *buffer)
+ 'nvvmGetProgramLog': (nvvm_result, nvvm_program, c_char_p),
+
+ # nvvmResult nvvmIRVersion (int* majorIR, int* minorIR, int* majorDbg,
+ # int* minorDbg )
+ 'nvvmIRVersion': (nvvm_result, POINTER(c_int), POINTER(c_int),
+ POINTER(c_int), POINTER(c_int)),
+ # nvvmResult nvvmVerifyProgram (nvvmProgram prog, int numOptions,
+ # const char** options)
+ 'nvvmVerifyProgram': (nvvm_result, nvvm_program, c_int,
+ POINTER(c_char_p))
+ }
+
+ # Singleton reference
+ __INSTANCE = None
+
+ def __new__(cls):
+ with _nvvm_lock:
+ if cls.__INSTANCE is None:
+ cls.__INSTANCE = inst = object.__new__(cls)
+ try:
+ inst.driver = open_cudalib('nvvm')
+ except OSError as e:
+ cls.__INSTANCE = None
+ errmsg = ("libNVVM cannot be found. Do `conda install "
+ "cudatoolkit`:\n%s")
+ raise NvvmSupportError(errmsg % e)
+
+ # Find & populate functions
+ for name, proto in inst._PROTOTYPES.items():
+ func = getattr(inst.driver, name)
+ func.restype = proto[0]
+ func.argtypes = proto[1:]
+ setattr(inst, name, func)
+
+ return cls.__INSTANCE
+
+ def __init__(self):
+ ir_versions = self.get_ir_version()
+ self._majorIR = ir_versions[0]
+ self._minorIR = ir_versions[1]
+ self._majorDbg = ir_versions[2]
+ self._minorDbg = ir_versions[3]
+ self._supported_ccs = get_supported_ccs()
+
+ @property
+ def data_layout(self):
+ if (self._majorIR, self._minorIR) < (1, 8):
+ return _datalayout_original
+ else:
+ return _datalayout_i128
+
+ @property
+ def supported_ccs(self):
+ return self._supported_ccs
+
+ def get_version(self):
+ major = c_int()
+ minor = c_int()
+ err = self.nvvmVersion(byref(major), byref(minor))
+ self.check_error(err, 'Failed to get version.')
+ return major.value, minor.value
+
+ def get_ir_version(self):
+ majorIR = c_int()
+ minorIR = c_int()
+ majorDbg = c_int()
+ minorDbg = c_int()
+ err = self.nvvmIRVersion(byref(majorIR), byref(minorIR),
+ byref(majorDbg), byref(minorDbg))
+ self.check_error(err, 'Failed to get IR version.')
+ return majorIR.value, minorIR.value, majorDbg.value, minorDbg.value
+
+ def check_error(self, error, msg, exit=False):
+ if error:
+ exc = NvvmError(msg, RESULT_CODE_NAMES[error])
+ if exit:
+ print(exc)
+ sys.exit(1)
+ else:
+ raise exc
+
+
+class CompilationUnit(object):
+ def __init__(self):
+ self.driver = NVVM()
+ self._handle = nvvm_program()
+ err = self.driver.nvvmCreateProgram(byref(self._handle))
+ self.driver.check_error(err, 'Failed to create CU')
+
+ def __del__(self):
+ driver = NVVM()
+ err = driver.nvvmDestroyProgram(byref(self._handle))
+ driver.check_error(err, 'Failed to destroy CU', exit=True)
+
+ def add_module(self, buffer):
+ """
+ Add a module level NVVM IR to a compilation unit.
+ - The buffer should contain an NVVM module IR either in the bitcode
+ representation (LLVM3.0) or in the text representation.
+ """
+ err = self.driver.nvvmAddModuleToProgram(self._handle, buffer,
+ len(buffer), None)
+ self.driver.check_error(err, 'Failed to add module')
+
+ def lazy_add_module(self, buffer):
+ """
+ Lazily add an NVVM IR module to a compilation unit.
+ The buffer should contain NVVM module IR either in the bitcode
+ representation or in the text representation.
+ """
+ err = self.driver.nvvmLazyAddModuleToProgram(self._handle, buffer,
+ len(buffer), None)
+ self.driver.check_error(err, 'Failed to add module')
+
+ def compile(self, **options):
+ """Perform Compilation.
+
+ Compilation options are accepted as keyword arguments, with the
+ following considerations:
+
+ - Underscores (`_`) in option names are converted to dashes (`-`), to
+ match NVVM's option name format.
+ - Options that take a value will be emitted in the form
+ "-=".
+ - Booleans passed as option values will be converted to integers.
+ - Options which take no value (such as `-gen-lto`) should have a value
+ of `None` passed in and will be emitted in the form "-".
+
+ For documentation on NVVM compilation options, see the CUDA Toolkit
+ Documentation:
+
+ https://docs.nvidia.com/cuda/libnvvm-api/index.html#_CPPv418nvvmCompileProgram11nvvmProgramiPPKc
+ """
+
+ def stringify_option(k, v):
+ k = k.replace('_', '-')
+
+ if v is None:
+ return f'-{k}'
+
+ if isinstance(v, bool):
+ v = int(v)
+
+ return f'-{k}={v}'
+
+ options = [stringify_option(k, v) for k, v in options.items()]
+
+ c_opts = (c_char_p * len(options))(*[c_char_p(x.encode('utf8'))
+ for x in options])
+ # verify
+ err = self.driver.nvvmVerifyProgram(self._handle, len(options), c_opts)
+ self._try_error(err, 'Failed to verify\n')
+
+ # compile
+ err = self.driver.nvvmCompileProgram(self._handle, len(options), c_opts)
+ self._try_error(err, 'Failed to compile\n')
+
+ # get result
+ reslen = c_size_t()
+ err = self.driver.nvvmGetCompiledResultSize(self._handle, byref(reslen))
+
+ self._try_error(err, 'Failed to get size of compiled result.')
+
+ output_buffer = (c_char * reslen.value)()
+ err = self.driver.nvvmGetCompiledResult(self._handle, output_buffer)
+ self._try_error(err, 'Failed to get compiled result.')
+
+ # get log
+ self.log = self.get_log()
+ if self.log:
+ warnings.warn(self.log, category=NvvmWarning)
+
+ return output_buffer[:]
+
+ def _try_error(self, err, msg):
+ self.driver.check_error(err, "%s\n%s" % (msg, self.get_log()))
+
+ def get_log(self):
+ reslen = c_size_t()
+ err = self.driver.nvvmGetProgramLogSize(self._handle, byref(reslen))
+ self.driver.check_error(err, 'Failed to get compilation log size.')
+
+ if reslen.value > 1:
+ logbuf = (c_char * reslen.value)()
+ err = self.driver.nvvmGetProgramLog(self._handle, logbuf)
+ self.driver.check_error(err, 'Failed to get compilation log.')
+
+ return logbuf.value.decode('utf8') # populate log attribute
+
+ return ''
+
+
+COMPUTE_CAPABILITIES = (
+ (3, 5), (3, 7),
+ (5, 0), (5, 2), (5, 3),
+ (6, 0), (6, 1), (6, 2),
+ (7, 0), (7, 2), (7, 5),
+ (8, 0), (8, 6), (8, 7), (8, 9),
+ (9, 0)
+)
+
+# Maps CTK version -> (min supported cc, max supported cc) inclusive
+CTK_SUPPORTED = {
+ (11, 2): ((3, 5), (8, 6)),
+ (11, 3): ((3, 5), (8, 6)),
+ (11, 4): ((3, 5), (8, 7)),
+ (11, 5): ((3, 5), (8, 7)),
+ (11, 6): ((3, 5), (8, 7)),
+ (11, 7): ((3, 5), (8, 7)),
+ (11, 8): ((3, 5), (9, 0)),
+ (12, 0): ((5, 0), (9, 0)),
+ (12, 1): ((5, 0), (9, 0)),
+ (12, 2): ((5, 0), (9, 0)),
+ (12, 3): ((5, 0), (9, 0)),
+ (12, 4): ((5, 0), (9, 0)),
+}
+
+
+def ccs_supported_by_ctk(ctk_version):
+ try:
+ # For supported versions, we look up the range of supported CCs
+ min_cc, max_cc = CTK_SUPPORTED[ctk_version]
+ return tuple([cc for cc in COMPUTE_CAPABILITIES
+ if min_cc <= cc <= max_cc])
+ except KeyError:
+ # For unsupported CUDA toolkit versions, all we can do is assume all
+ # non-deprecated versions we are aware of are supported.
+ return tuple([cc for cc in COMPUTE_CAPABILITIES
+ if cc >= config.CUDA_DEFAULT_PTX_CC])
+
+
+def get_supported_ccs():
+ try:
+ from numba.cuda.cudadrv.runtime import runtime
+ cudart_version = runtime.get_version()
+ except: # noqa: E722
+ # We can't support anything if there's an error getting the runtime
+ # version (e.g. if it's not present or there's another issue)
+ _supported_cc = ()
+ return _supported_cc
+
+ # Ensure the minimum CTK version requirement is met
+ min_cudart = min(CTK_SUPPORTED)
+ if cudart_version < min_cudart:
+ _supported_cc = ()
+ ctk_ver = f"{cudart_version[0]}.{cudart_version[1]}"
+ unsupported_ver = (f"CUDA Toolkit {ctk_ver} is unsupported by Numba - "
+ f"{min_cudart[0]}.{min_cudart[1]} is the minimum "
+ "required version.")
+ warnings.warn(unsupported_ver)
+ return _supported_cc
+
+ _supported_cc = ccs_supported_by_ctk(cudart_version)
+ return _supported_cc
+
+
+def find_closest_arch(mycc):
+ """
+ Given a compute capability, return the closest compute capability supported
+ by the CUDA toolkit.
+
+ :param mycc: Compute capability as a tuple ``(MAJOR, MINOR)``
+ :return: Closest supported CC as a tuple ``(MAJOR, MINOR)``
+ """
+ supported_ccs = NVVM().supported_ccs
+
+ if not supported_ccs:
+ msg = "No supported GPU compute capabilities found. " \
+ "Please check your cudatoolkit version matches your CUDA version."
+ raise NvvmSupportError(msg)
+
+ for i, cc in enumerate(supported_ccs):
+ if cc == mycc:
+ # Matches
+ return cc
+ elif cc > mycc:
+ # Exceeded
+ if i == 0:
+ # CC lower than supported
+ msg = "GPU compute capability %d.%d is not supported" \
+ "(requires >=%d.%d)" % (mycc + cc)
+ raise NvvmSupportError(msg)
+ else:
+ # return the previous CC
+ return supported_ccs[i - 1]
+
+ # CC higher than supported
+ return supported_ccs[-1] # Choose the highest
+
+
+def get_arch_option(major, minor):
+ """Matches with the closest architecture option
+ """
+ if config.FORCE_CUDA_CC:
+ arch = config.FORCE_CUDA_CC
+ else:
+ arch = find_closest_arch((major, minor))
+ return 'compute_%d%d' % arch
+
+
+MISSING_LIBDEVICE_FILE_MSG = '''Missing libdevice file.
+Please ensure you have a CUDA Toolkit 11.2 or higher.
+For CUDA 12, ``cuda-nvcc`` and ``cuda-nvrtc`` are required:
+
+ $ conda install -c conda-forge cuda-nvcc cuda-nvrtc "cuda-version>=12.0"
+
+For CUDA 11, ``cudatoolkit`` is required:
+
+ $ conda install -c conda-forge cudatoolkit "cuda-version>=11.2,<12.0"
+'''
+
+
+class LibDevice(object):
+ _cache_ = None
+
+ def __init__(self):
+ if self._cache_ is None:
+ if get_libdevice() is None:
+ raise RuntimeError(MISSING_LIBDEVICE_FILE_MSG)
+ self._cache_ = open_libdevice()
+
+ self.bc = self._cache_
+
+ def get(self):
+ return self.bc
+
+
+cas_nvvm = """
+ %cas_success = cmpxchg volatile {Ti}* %iptr, {Ti} %old, {Ti} %new monotonic monotonic
+ %cas = extractvalue {{ {Ti}, i1 }} %cas_success, 0
+""" # noqa: E501
+
+
+# Translation of code from CUDA Programming Guide v6.5, section B.12
+ir_numba_atomic_binary_template = """
+define internal {T} @___numba_atomic_{T}_{FUNC}({T}* %ptr, {T} %val) alwaysinline {{
+entry:
+ %iptr = bitcast {T}* %ptr to {Ti}*
+ %old2 = load volatile {Ti}, {Ti}* %iptr
+ br label %attempt
+
+attempt:
+ %old = phi {Ti} [ %old2, %entry ], [ %cas, %attempt ]
+ %dold = bitcast {Ti} %old to {T}
+ %dnew = {OP} {T} %dold, %val
+ %new = bitcast {T} %dnew to {Ti}
+ {CAS}
+ %repeat = icmp ne {Ti} %cas, %old
+ br i1 %repeat, label %attempt, label %done
+
+done:
+ %result = bitcast {Ti} %old to {T}
+ ret {T} %result
+}}
+""" # noqa: E501
+
+ir_numba_atomic_inc_template = """
+define internal {T} @___numba_atomic_{Tu}_inc({T}* %iptr, {T} %val) alwaysinline {{
+entry:
+ %old2 = load volatile {T}, {T}* %iptr
+ br label %attempt
+
+attempt:
+ %old = phi {T} [ %old2, %entry ], [ %cas, %attempt ]
+ %bndchk = icmp ult {T} %old, %val
+ %inc = add {T} %old, 1
+ %new = select i1 %bndchk, {T} %inc, {T} 0
+ {CAS}
+ %repeat = icmp ne {T} %cas, %old
+ br i1 %repeat, label %attempt, label %done
+
+done:
+ ret {T} %old
+}}
+""" # noqa: E501
+
+ir_numba_atomic_dec_template = """
+define internal {T} @___numba_atomic_{Tu}_dec({T}* %iptr, {T} %val) alwaysinline {{
+entry:
+ %old2 = load volatile {T}, {T}* %iptr
+ br label %attempt
+
+attempt:
+ %old = phi {T} [ %old2, %entry ], [ %cas, %attempt ]
+ %dec = add {T} %old, -1
+ %bndchk = icmp ult {T} %dec, %val
+ %new = select i1 %bndchk, {T} %dec, {T} %val
+ {CAS}
+ %repeat = icmp ne {T} %cas, %old
+ br i1 %repeat, label %attempt, label %done
+
+done:
+ ret {T} %old
+}}
+""" # noqa: E501
+
+ir_numba_atomic_minmax_template = """
+define internal {T} @___numba_atomic_{T}_{NAN}{FUNC}({T}* %ptr, {T} %val) alwaysinline {{
+entry:
+ %ptrval = load volatile {T}, {T}* %ptr
+ ; Return early when:
+ ; - For nanmin / nanmax when val is a NaN
+ ; - For min / max when val or ptr is a NaN
+ %early_return = fcmp uno {T} %val, %{PTR_OR_VAL}val
+ br i1 %early_return, label %done, label %lt_check
+
+lt_check:
+ %dold = phi {T} [ %ptrval, %entry ], [ %dcas, %attempt ]
+ ; Continue attempts if dold less or greater than val (depending on whether min or max)
+ ; or if dold is NaN (for nanmin / nanmax)
+ %cmp = fcmp {OP} {T} %dold, %val
+ br i1 %cmp, label %attempt, label %done
+
+attempt:
+ ; Attempt to swap in the value
+ %old = bitcast {T} %dold to {Ti}
+ %iptr = bitcast {T}* %ptr to {Ti}*
+ %new = bitcast {T} %val to {Ti}
+ {CAS}
+ %dcas = bitcast {Ti} %cas to {T}
+ br label %lt_check
+
+done:
+ ret {T} %ptrval
+}}
+""" # noqa: E501
+
+
+def ir_cas(Ti):
+ return cas_nvvm.format(Ti=Ti)
+
+
+def ir_numba_atomic_binary(T, Ti, OP, FUNC):
+ params = dict(T=T, Ti=Ti, OP=OP, FUNC=FUNC, CAS=ir_cas(Ti))
+ return ir_numba_atomic_binary_template.format(**params)
+
+
+def ir_numba_atomic_minmax(T, Ti, NAN, OP, PTR_OR_VAL, FUNC):
+ params = dict(T=T, Ti=Ti, NAN=NAN, OP=OP, PTR_OR_VAL=PTR_OR_VAL,
+ FUNC=FUNC, CAS=ir_cas(Ti))
+
+ return ir_numba_atomic_minmax_template.format(**params)
+
+
+def ir_numba_atomic_inc(T, Tu):
+ return ir_numba_atomic_inc_template.format(T=T, Tu=Tu, CAS=ir_cas(T))
+
+
+def ir_numba_atomic_dec(T, Tu):
+ return ir_numba_atomic_dec_template.format(T=T, Tu=Tu, CAS=ir_cas(T))
+
+
+def llvm_replace(llvmir):
+ replacements = [
+ ('declare double @"___numba_atomic_double_add"(double* %".1", double %".2")', # noqa: E501
+ ir_numba_atomic_binary(T='double', Ti='i64', OP='fadd', FUNC='add')),
+ ('declare float @"___numba_atomic_float_sub"(float* %".1", float %".2")', # noqa: E501
+ ir_numba_atomic_binary(T='float', Ti='i32', OP='fsub', FUNC='sub')),
+ ('declare double @"___numba_atomic_double_sub"(double* %".1", double %".2")', # noqa: E501
+ ir_numba_atomic_binary(T='double', Ti='i64', OP='fsub', FUNC='sub')),
+ ('declare i64 @"___numba_atomic_u64_inc"(i64* %".1", i64 %".2")',
+ ir_numba_atomic_inc(T='i64', Tu='u64')),
+ ('declare i64 @"___numba_atomic_u64_dec"(i64* %".1", i64 %".2")',
+ ir_numba_atomic_dec(T='i64', Tu='u64')),
+ ('declare float @"___numba_atomic_float_max"(float* %".1", float %".2")', # noqa: E501
+ ir_numba_atomic_minmax(T='float', Ti='i32', NAN='', OP='nnan olt',
+ PTR_OR_VAL='ptr', FUNC='max')),
+ ('declare double @"___numba_atomic_double_max"(double* %".1", double %".2")', # noqa: E501
+ ir_numba_atomic_minmax(T='double', Ti='i64', NAN='', OP='nnan olt',
+ PTR_OR_VAL='ptr', FUNC='max')),
+ ('declare float @"___numba_atomic_float_min"(float* %".1", float %".2")', # noqa: E501
+ ir_numba_atomic_minmax(T='float', Ti='i32', NAN='', OP='nnan ogt',
+ PTR_OR_VAL='ptr', FUNC='min')),
+ ('declare double @"___numba_atomic_double_min"(double* %".1", double %".2")', # noqa: E501
+ ir_numba_atomic_minmax(T='double', Ti='i64', NAN='', OP='nnan ogt',
+ PTR_OR_VAL='ptr', FUNC='min')),
+ ('declare float @"___numba_atomic_float_nanmax"(float* %".1", float %".2")', # noqa: E501
+ ir_numba_atomic_minmax(T='float', Ti='i32', NAN='nan', OP='ult',
+ PTR_OR_VAL='', FUNC='max')),
+ ('declare double @"___numba_atomic_double_nanmax"(double* %".1", double %".2")', # noqa: E501
+ ir_numba_atomic_minmax(T='double', Ti='i64', NAN='nan', OP='ult',
+ PTR_OR_VAL='', FUNC='max')),
+ ('declare float @"___numba_atomic_float_nanmin"(float* %".1", float %".2")', # noqa: E501
+ ir_numba_atomic_minmax(T='float', Ti='i32', NAN='nan', OP='ugt',
+ PTR_OR_VAL='', FUNC='min')),
+ ('declare double @"___numba_atomic_double_nanmin"(double* %".1", double %".2")', # noqa: E501
+ ir_numba_atomic_minmax(T='double', Ti='i64', NAN='nan', OP='ugt',
+ PTR_OR_VAL='', FUNC='min')),
+ ('immarg', '')
+ ]
+
+ for decl, fn in replacements:
+ llvmir = llvmir.replace(decl, fn)
+
+ llvmir = llvm140_to_70_ir(llvmir)
+
+ return llvmir
+
+
+def compile_ir(llvmir, **opts):
+ if isinstance(llvmir, str):
+ llvmir = [llvmir]
+
+ if opts.pop('fastmath', False):
+ opts.update({
+ 'ftz': True,
+ 'fma': True,
+ 'prec_div': False,
+ 'prec_sqrt': False,
+ })
+
+ cu = CompilationUnit()
+ libdevice = LibDevice()
+
+ for mod in llvmir:
+ mod = llvm_replace(mod)
+ cu.add_module(mod.encode('utf8'))
+ cu.lazy_add_module(libdevice.get())
+
+ return cu.compile(**opts)
+
+
+re_attributes_def = re.compile(r"^attributes #\d+ = \{ ([\w\s]+)\ }")
+
+
+def llvm140_to_70_ir(ir):
+ """
+ Convert LLVM 14.0 IR for LLVM 7.0.
+ """
+ buf = []
+ for line in ir.splitlines():
+ if line.startswith('attributes #'):
+ # Remove function attributes unsupported by LLVM 7.0
+ m = re_attributes_def.match(line)
+ attrs = m.group(1).split()
+ attrs = ' '.join(a for a in attrs if a != 'willreturn')
+ line = line.replace(m.group(1), attrs)
+
+ buf.append(line)
+
+ return '\n'.join(buf)
+
+
+def set_cuda_kernel(function):
+ """
+ Mark a function as a CUDA kernel. Kernels have the following requirements:
+
+ - Metadata that marks them as a kernel.
+ - Addition to the @llvm.used list, so that they will not be discarded.
+ - The noinline attribute is not permitted, because this causes NVVM to emit
+ a warning, which counts as failing IR verification.
+
+ Presently it is assumed that there is one kernel per module, which holds
+ for Numba-jitted functions. If this changes in future or this function is
+ to be used externally, this function may need modification to add to the
+ @llvm.used list rather than creating it.
+ """
+ module = function.module
+
+ # Add kernel metadata
+ mdstr = ir.MetaDataString(module, "kernel")
+ mdvalue = ir.Constant(ir.IntType(32), 1)
+ md = module.add_metadata((function, mdstr, mdvalue))
+
+ nmd = cgutils.get_or_insert_named_metadata(module, 'nvvm.annotations')
+ nmd.add(md)
+
+ # Create the used list
+ ptrty = ir.IntType(8).as_pointer()
+ usedty = ir.ArrayType(ptrty, 1)
+
+ fnptr = function.bitcast(ptrty)
+
+ llvm_used = ir.GlobalVariable(module, usedty, 'llvm.used')
+ llvm_used.linkage = 'appending'
+ llvm_used.section = 'llvm.metadata'
+ llvm_used.initializer = ir.Constant(usedty, [fnptr])
+
+ # Remove 'noinline' if it is present.
+ function.attributes.discard('noinline')
+
+
+def add_ir_version(mod):
+ """Add NVVM IR version to module"""
+ # We specify the IR version to match the current NVVM's IR version
+ i32 = ir.IntType(32)
+ ir_versions = [i32(v) for v in NVVM().get_ir_version()]
+ md_ver = mod.add_metadata(ir_versions)
+ mod.add_named_metadata('nvvmir.version', md_ver)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/rtapi.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/rtapi.py
new file mode 100644
index 0000000000000000000000000000000000000000..4a88457f9cb5a1e0cb134eb4dcb59267d1cf3f54
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/rtapi.py
@@ -0,0 +1,10 @@
+"""
+Declarations of the Runtime API functions.
+"""
+
+from ctypes import c_int, POINTER
+
+API_PROTOTYPES = {
+ # cudaError_t cudaRuntimeGetVersion ( int* runtimeVersion )
+ 'cudaRuntimeGetVersion': (c_int, POINTER(c_int)),
+}
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/runtime.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/runtime.py
new file mode 100644
index 0000000000000000000000000000000000000000..20634d8f4b7de3e87c99ecd76a427f8879b3fd9e
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/cudadrv/runtime.py
@@ -0,0 +1,142 @@
+"""
+CUDA Runtime wrapper.
+
+This provides a very minimal set of bindings, since the Runtime API is not
+really used in Numba except for querying the Runtime version.
+"""
+
+import ctypes
+import functools
+import sys
+
+from numba.core import config
+from numba.cuda.cudadrv.driver import ERROR_MAP, make_logger
+from numba.cuda.cudadrv.error import CudaSupportError, CudaRuntimeError
+from numba.cuda.cudadrv.libs import open_cudalib
+from numba.cuda.cudadrv.rtapi import API_PROTOTYPES
+from numba.cuda.cudadrv import enums
+
+
+class CudaRuntimeAPIError(CudaRuntimeError):
+ """
+ Raised when there is an error accessing a C API from the CUDA Runtime.
+ """
+ def __init__(self, code, msg):
+ self.code = code
+ self.msg = msg
+ super().__init__(code, msg)
+
+ def __str__(self):
+ return "[%s] %s" % (self.code, self.msg)
+
+
+class Runtime:
+ """
+ Runtime object that lazily binds runtime API functions.
+ """
+
+ def __init__(self):
+ self.is_initialized = False
+
+ def _initialize(self):
+ # lazily initialize logger
+ global _logger
+ _logger = make_logger()
+
+ if config.DISABLE_CUDA:
+ msg = ("CUDA is disabled due to setting NUMBA_DISABLE_CUDA=1 "
+ "in the environment, or because CUDA is unsupported on "
+ "32-bit systems.")
+ raise CudaSupportError(msg)
+ self.lib = open_cudalib('cudart')
+
+ self.is_initialized = True
+
+ def __getattr__(self, fname):
+ # First request of a runtime API function
+ try:
+ proto = API_PROTOTYPES[fname]
+ except KeyError:
+ raise AttributeError(fname)
+ restype = proto[0]
+ argtypes = proto[1:]
+
+ if not self.is_initialized:
+ self._initialize()
+
+ # Find function in runtime library
+ libfn = self._find_api(fname)
+ libfn.restype = restype
+ libfn.argtypes = argtypes
+
+ safe_call = self._wrap_api_call(fname, libfn)
+ setattr(self, fname, safe_call)
+ return safe_call
+
+ def _wrap_api_call(self, fname, libfn):
+ @functools.wraps(libfn)
+ def safe_cuda_api_call(*args):
+ _logger.debug('call runtime api: %s', libfn.__name__)
+ retcode = libfn(*args)
+ self._check_error(fname, retcode)
+ return safe_cuda_api_call
+
+ def _check_error(self, fname, retcode):
+ if retcode != enums.CUDA_SUCCESS:
+ errname = ERROR_MAP.get(retcode, "cudaErrorUnknown")
+ msg = "Call to %s results in %s" % (fname, errname)
+ _logger.error(msg)
+ raise CudaRuntimeAPIError(retcode, msg)
+
+ def _find_api(self, fname):
+ try:
+ return getattr(self.lib, fname)
+ except AttributeError:
+ pass
+
+ # Not found.
+ # Delay missing function error to use
+ def absent_function(*args, **kws):
+ msg = "runtime missing function: %s."
+ raise CudaRuntimeError(msg % fname)
+
+ setattr(self, fname, absent_function)
+ return absent_function
+
+ def get_version(self):
+ """
+ Returns the CUDA Runtime version as a tuple (major, minor).
+ """
+ rtver = ctypes.c_int()
+ self.cudaRuntimeGetVersion(ctypes.byref(rtver))
+ # The version is encoded as (1000 * major) + (10 * minor)
+ major = rtver.value // 1000
+ minor = (rtver.value - (major * 1000)) // 10
+ return (major, minor)
+
+ def is_supported_version(self):
+ """
+ Returns True if the CUDA Runtime is a supported version.
+ """
+
+ return self.get_version() in self.supported_versions
+
+ @property
+ def supported_versions(self):
+ """A tuple of all supported CUDA toolkit versions. Versions are given in
+ the form ``(major_version, minor_version)``."""
+ if sys.platform not in ('linux', 'win32') or config.MACHINE_BITS != 64:
+ # Only 64-bit Linux and Windows are supported
+ return ()
+ return ((11, 0), (11, 1), (11, 2), (11, 3), (11, 4), (11, 5), (11, 6),
+ (11, 7))
+
+
+runtime = Runtime()
+
+
+def get_version():
+ """
+ Return the runtime version as a tuple of (major, minor)
+ """
+ return runtime.get_version()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/kernels/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/kernels/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/kernels/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/kernels/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ab6a79392f79f01eb2d77b7d08f2eebf4343d304
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/kernels/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/kernels/__pycache__/reduction.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/kernels/__pycache__/reduction.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6c3103d028df8a44c2dea494909a5495853acc8d
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/kernels/__pycache__/reduction.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/kernels/__pycache__/transpose.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/kernels/__pycache__/transpose.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..da43b4635319878ef9f1f218b7cf92945e48bb6a
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/kernels/__pycache__/transpose.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/kernels/reduction.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/kernels/reduction.py
new file mode 100644
index 0000000000000000000000000000000000000000..f733935b6223c301bbf13251c4a9f50ffb38b622
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/kernels/reduction.py
@@ -0,0 +1,262 @@
+"""
+A library written in CUDA Python for generating reduction kernels
+"""
+
+from numba.np.numpy_support import from_dtype
+
+
+_WARPSIZE = 32
+_NUMWARPS = 4
+
+
+def _gpu_reduce_factory(fn, nbtype):
+ from numba import cuda
+
+ reduce_op = cuda.jit(device=True)(fn)
+ inner_sm_size = _WARPSIZE + 1 # plus one to avoid SM collision
+ max_blocksize = _NUMWARPS * _WARPSIZE
+
+ @cuda.jit(device=True)
+ def inner_warp_reduction(sm_partials, init):
+ """
+ Compute reduction within a single warp
+ """
+ tid = cuda.threadIdx.x
+ warpid = tid // _WARPSIZE
+ laneid = tid % _WARPSIZE
+
+ sm_this = sm_partials[warpid, :]
+ sm_this[laneid] = init
+ cuda.syncwarp()
+
+ width = _WARPSIZE // 2
+ while width:
+ if laneid < width:
+ old = sm_this[laneid]
+ sm_this[laneid] = reduce_op(old, sm_this[laneid + width])
+ cuda.syncwarp()
+ width //= 2
+
+ @cuda.jit(device=True)
+ def device_reduce_full_block(arr, partials, sm_partials):
+ """
+ Partially reduce `arr` into `partials` using `sm_partials` as working
+ space. The algorithm goes like:
+
+ array chunks of 128: | 0 | 128 | 256 | 384 | 512 |
+ block-0: | x | | | x | |
+ block-1: | | x | | | x |
+ block-2: | | | x | | |
+
+ The array is divided into chunks of 128 (size of a threadblock).
+ The threadblocks consumes the chunks in roundrobin scheduling.
+ First, a threadblock loads a chunk into temp memory. Then, all
+ subsequent chunks are combined into the temp memory.
+
+ Once all chunks are processed. Inner-block reduction is performed
+ on the temp memory. So that, there will just be one scalar result
+ per block. The result from each block is stored to `partials` at
+ the dedicated slot.
+ """
+ tid = cuda.threadIdx.x
+ blkid = cuda.blockIdx.x
+ blksz = cuda.blockDim.x
+ gridsz = cuda.gridDim.x
+
+ # block strided loop to compute the reduction
+ start = tid + blksz * blkid
+ stop = arr.size
+ step = blksz * gridsz
+
+ # load first value
+ tmp = arr[start]
+ # loop over all values in block-stride
+ for i in range(start + step, stop, step):
+ tmp = reduce_op(tmp, arr[i])
+
+ cuda.syncthreads()
+ # inner-warp reduction
+ inner_warp_reduction(sm_partials, tmp)
+
+ cuda.syncthreads()
+ # at this point, only the first slot for each warp in tsm_partials
+ # is valid.
+
+ # finish up block reduction
+ # warning: this is assuming 4 warps.
+ # assert numwarps == 4
+ if tid < 2:
+ sm_partials[tid, 0] = reduce_op(sm_partials[tid, 0],
+ sm_partials[tid + 2, 0])
+ cuda.syncwarp()
+ if tid == 0:
+ partials[blkid] = reduce_op(sm_partials[0, 0], sm_partials[1, 0])
+
+ @cuda.jit(device=True)
+ def device_reduce_partial_block(arr, partials, sm_partials):
+ """
+ This computes reduction on `arr`.
+ This device function must be used by 1 threadblock only.
+ The blocksize must match `arr.size` and must not be greater than 128.
+ """
+ tid = cuda.threadIdx.x
+ blkid = cuda.blockIdx.x
+ blksz = cuda.blockDim.x
+ warpid = tid // _WARPSIZE
+ laneid = tid % _WARPSIZE
+
+ size = arr.size
+ # load first value
+ tid = cuda.threadIdx.x
+ value = arr[tid]
+ sm_partials[warpid, laneid] = value
+
+ cuda.syncthreads()
+
+ if (warpid + 1) * _WARPSIZE < size:
+ # fully populated warps
+ inner_warp_reduction(sm_partials, value)
+ else:
+ # partially populated warps
+ # NOTE: this uses a very inefficient sequential algorithm
+ if laneid == 0:
+ sm_this = sm_partials[warpid, :]
+ base = warpid * _WARPSIZE
+ for i in range(1, size - base):
+ sm_this[0] = reduce_op(sm_this[0], sm_this[i])
+
+ cuda.syncthreads()
+ # finish up
+ if tid == 0:
+ num_active_warps = (blksz + _WARPSIZE - 1) // _WARPSIZE
+
+ result = sm_partials[0, 0]
+ for i in range(1, num_active_warps):
+ result = reduce_op(result, sm_partials[i, 0])
+
+ partials[blkid] = result
+
+ def gpu_reduce_block_strided(arr, partials, init, use_init):
+ """
+ Perform reductions on *arr* and writing out partial reduction result
+ into *partials*. The length of *partials* is determined by the
+ number of threadblocks. The initial value is set with *init*.
+
+ Launch config:
+
+ Blocksize must be multiple of warpsize and it is limited to 4 warps.
+ """
+ tid = cuda.threadIdx.x
+
+ sm_partials = cuda.shared.array((_NUMWARPS, inner_sm_size),
+ dtype=nbtype)
+ if cuda.blockDim.x == max_blocksize:
+ device_reduce_full_block(arr, partials, sm_partials)
+ else:
+ device_reduce_partial_block(arr, partials, sm_partials)
+ # deal with the initializer
+ if use_init and tid == 0 and cuda.blockIdx.x == 0:
+ partials[0] = reduce_op(partials[0], init)
+
+ return cuda.jit(gpu_reduce_block_strided)
+
+
+class Reduce(object):
+ """Create a reduction object that reduces values using a given binary
+ function. The binary function is compiled once and cached inside this
+ object. Keeping this object alive will prevent re-compilation.
+ """
+
+ _cache = {}
+
+ def __init__(self, functor):
+ """
+ :param functor: A function implementing a binary operation for
+ reduction. It will be compiled as a CUDA device
+ function using ``cuda.jit(device=True)``.
+ """
+ self._functor = functor
+
+ def _compile(self, dtype):
+ key = self._functor, dtype
+ if key in self._cache:
+ kernel = self._cache[key]
+ else:
+ kernel = _gpu_reduce_factory(self._functor, from_dtype(dtype))
+ self._cache[key] = kernel
+ return kernel
+
+ def __call__(self, arr, size=None, res=None, init=0, stream=0):
+ """Performs a full reduction.
+
+ :param arr: A host or device array.
+ :param size: Optional integer specifying the number of elements in
+ ``arr`` to reduce. If this parameter is not specified, the
+ entire array is reduced.
+ :param res: Optional device array into which to write the reduction
+ result to. The result is written into the first element of
+ this array. If this parameter is specified, then no
+ communication of the reduction output takes place from the
+ device to the host.
+ :param init: Optional initial value for the reduction, the type of which
+ must match ``arr.dtype``.
+ :param stream: Optional CUDA stream in which to perform the reduction.
+ If no stream is specified, the default stream of 0 is
+ used.
+ :return: If ``res`` is specified, ``None`` is returned. Otherwise, the
+ result of the reduction is returned.
+ """
+ from numba import cuda
+
+ # ensure 1d array
+ if arr.ndim != 1:
+ raise TypeError("only support 1D array")
+
+ # adjust array size
+ if size is not None:
+ arr = arr[:size]
+
+ init = arr.dtype.type(init) # ensure the right type
+
+ # return `init` if `arr` is empty
+ if arr.size < 1:
+ return init
+
+ kernel = self._compile(arr.dtype)
+
+ # Perform the reduction on the GPU
+ blocksize = _NUMWARPS * _WARPSIZE
+ size_full = (arr.size // blocksize) * blocksize
+ size_partial = arr.size - size_full
+ full_blockct = min(size_full // blocksize, _WARPSIZE * 2)
+
+ # allocate size of partials array
+ partials_size = full_blockct
+ if size_partial:
+ partials_size += 1
+ partials = cuda.device_array(shape=partials_size, dtype=arr.dtype)
+
+ if size_full:
+ # kernel for the fully populated threadblocks
+ kernel[full_blockct, blocksize, stream](arr[:size_full],
+ partials[:full_blockct],
+ init,
+ True)
+
+ if size_partial:
+ # kernel for partially populated threadblocks
+ kernel[1, size_partial, stream](arr[size_full:],
+ partials[full_blockct:],
+ init,
+ not full_blockct)
+
+ if partials.size > 1:
+ # finish up
+ kernel[1, partials_size, stream](partials, partials, init, False)
+
+ # handle return value
+ if res is not None:
+ res[:1].copy_to_device(partials[:1], stream=stream)
+ return
+ else:
+ return partials[0]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/kernels/transpose.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/kernels/transpose.py
new file mode 100644
index 0000000000000000000000000000000000000000..b1df36e048891119b08fa67b452df637c85db9df
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/kernels/transpose.py
@@ -0,0 +1,65 @@
+from numba import cuda
+from numba.cuda.cudadrv.driver import driver
+import math
+from numba.np import numpy_support as nps
+
+
+def transpose(a, b=None):
+ """Compute the transpose of 'a' and store it into 'b', if given,
+ and return it. If 'b' is not given, allocate a new array
+ and return that.
+
+ This implements the algorithm documented in
+ http://devblogs.nvidia.com/parallelforall/efficient-matrix-transpose-cuda-cc/
+
+ :param a: an `np.ndarray` or a `DeviceNDArrayBase` subclass. If already on
+ the device its stream will be used to perform the transpose (and to copy
+ `b` to the device if necessary).
+ """
+
+ # prefer `a`'s stream if
+ stream = getattr(a, 'stream', 0)
+
+ if not b:
+ cols, rows = a.shape
+ strides = a.dtype.itemsize * cols, a.dtype.itemsize
+ b = cuda.cudadrv.devicearray.DeviceNDArray(
+ (rows, cols),
+ strides,
+ dtype=a.dtype,
+ stream=stream)
+
+ dt = nps.from_dtype(a.dtype)
+
+ tpb = driver.get_device().MAX_THREADS_PER_BLOCK
+ # we need to factor available threads into x and y axis
+ tile_width = int(math.pow(2, math.log(tpb, 2) / 2))
+ tile_height = int(tpb / tile_width)
+
+ tile_shape = (tile_height, tile_width + 1)
+
+ @cuda.jit
+ def kernel(input, output):
+
+ tile = cuda.shared.array(shape=tile_shape, dtype=dt)
+
+ tx = cuda.threadIdx.x
+ ty = cuda.threadIdx.y
+ bx = cuda.blockIdx.x * cuda.blockDim.x
+ by = cuda.blockIdx.y * cuda.blockDim.y
+ x = by + tx
+ y = bx + ty
+
+ if by + ty < input.shape[0] and bx + tx < input.shape[1]:
+ tile[ty, tx] = input[by + ty, bx + tx]
+ cuda.syncthreads()
+ if y < output.shape[0] and x < output.shape[1]:
+ output[y, x] = tile[tx, ty]
+
+ # one block per tile, plus one for remainders
+ blocks = int(b.shape[0] / tile_height + 1), int(b.shape[1] / tile_width + 1)
+ # one thread per tile element
+ threads = tile_height, tile_width
+ kernel[blocks, threads, stream](a, b)
+
+ return b
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..d24aa6e7df0f941e2bf781c681122530ceb93e68
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/__init__.py
@@ -0,0 +1,38 @@
+import sys
+
+from .api import *
+from .vector_types import vector_types
+from .reduction import Reduce
+from .cudadrv.devicearray import (device_array, device_array_like, pinned,
+ pinned_array, pinned_array_like,
+ mapped_array, to_device, auto_device)
+from .cudadrv import devicearray
+from .cudadrv.devices import require_context, gpus
+from .cudadrv.devices import get_context as current_context
+from .cudadrv.runtime import runtime
+from numba.core import config
+reduce = Reduce
+
+# Register simulated vector types as module level variables
+for name, svty in vector_types.items():
+ setattr(sys.modules[__name__], name, svty)
+ for alias in svty.aliases:
+ setattr(sys.modules[__name__], alias, svty)
+del vector_types, name, svty, alias
+
+# Ensure that any user code attempting to import cudadrv etc. gets the
+# simulator's version and not the real version if the simulator is enabled.
+if config.ENABLE_CUDASIM:
+ import sys
+ from numba.cuda.simulator import cudadrv
+ sys.modules['numba.cuda.cudadrv'] = cudadrv
+ sys.modules['numba.cuda.cudadrv.devicearray'] = cudadrv.devicearray
+ sys.modules['numba.cuda.cudadrv.devices'] = cudadrv.devices
+ sys.modules['numba.cuda.cudadrv.driver'] = cudadrv.driver
+ sys.modules['numba.cuda.cudadrv.runtime'] = cudadrv.runtime
+ sys.modules['numba.cuda.cudadrv.drvapi'] = cudadrv.drvapi
+ sys.modules['numba.cuda.cudadrv.error'] = cudadrv.error
+ sys.modules['numba.cuda.cudadrv.nvvm'] = cudadrv.nvvm
+
+ from . import compiler
+ sys.modules['numba.cuda.compiler'] = compiler
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6c15a92d2b883cdbadaf43982a2841727f421ff5
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/__pycache__/api.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/__pycache__/api.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1f076cf031e2dc992c67954db598ce73d13079c4
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/__pycache__/api.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/__pycache__/compiler.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/__pycache__/compiler.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..672f97b3035c562c8688f65528709ae210ced85c
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/__pycache__/compiler.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/__pycache__/kernel.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/__pycache__/kernel.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e175c76a4ed855b5d861e1c35034f44e1cbe8248
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/__pycache__/kernel.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/__pycache__/kernelapi.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/__pycache__/kernelapi.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..51ba166fdc467f7428e8e5b57dd2aa9e788ac22c
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/__pycache__/kernelapi.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/__pycache__/reduction.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/__pycache__/reduction.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f7bea36f8cc93002cb20f72fd58d98a3e342e257
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/__pycache__/reduction.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/__pycache__/vector_types.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/__pycache__/vector_types.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3e7a11635b3f34f5af761eec471c545209f80c3f
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/__pycache__/vector_types.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/api.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/api.py
new file mode 100644
index 0000000000000000000000000000000000000000..0b3c5bfb5331794b1881132b1f47eb7417e6382b
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/api.py
@@ -0,0 +1,110 @@
+'''
+Contains CUDA API functions
+'''
+
+# Imports here bring together parts of the API from other modules, so some of
+# them appear unused.
+from contextlib import contextmanager
+
+from .cudadrv.devices import require_context, reset, gpus # noqa: F401
+from .kernel import FakeCUDAKernel
+from numba.core.sigutils import is_signature
+from warnings import warn
+from ..args import In, Out, InOut # noqa: F401
+
+
+def select_device(dev=0):
+ assert dev == 0, 'Only a single device supported by the simulator'
+
+
+def is_float16_supported():
+ return True
+
+
+class stream(object):
+ '''
+ The stream API is supported in the simulator - however, all execution
+ occurs synchronously, so synchronization requires no operation.
+ '''
+ @contextmanager
+ def auto_synchronize(self):
+ yield
+
+ def synchronize(self):
+ pass
+
+
+def synchronize():
+ pass
+
+
+def close():
+ gpus.closed = True
+
+
+def declare_device(*args, **kwargs):
+ pass
+
+
+def detect():
+ print('Found 1 CUDA devices')
+ print('id %d %20s %40s' % (0, 'SIMULATOR', '[SUPPORTED]'))
+ print('%40s: 5.0' % 'compute capability')
+
+
+def list_devices():
+ return gpus
+
+
+# Events
+
+class Event(object):
+ '''
+ The simulator supports the event API, but they do not record timing info,
+ and all simulation is synchronous. Execution time is not recorded.
+ '''
+ def record(self, stream=0):
+ pass
+
+ def wait(self, stream=0):
+ pass
+
+ def synchronize(self):
+ pass
+
+ def elapsed_time(self, event):
+ warn('Simulator timings are bogus')
+ return 0.0
+
+
+event = Event
+
+
+def jit(func_or_sig=None, device=False, debug=False, argtypes=None,
+ inline=False, restype=None, fastmath=False, link=None,
+ boundscheck=None, opt=True, cache=None
+ ):
+ # Here for API compatibility
+ if boundscheck:
+ raise NotImplementedError("bounds checking is not supported for CUDA")
+
+ if link is not None:
+ raise NotImplementedError('Cannot link PTX in the simulator')
+
+ # Check for first argument specifying types - in that case the
+ # decorator is not being passed a function
+ if (func_or_sig is None or is_signature(func_or_sig)
+ or isinstance(func_or_sig, list)):
+ def jitwrapper(fn):
+ return FakeCUDAKernel(fn,
+ device=device,
+ fastmath=fastmath,
+ debug=debug)
+ return jitwrapper
+ return FakeCUDAKernel(func_or_sig, device=device, debug=debug)
+
+
+@contextmanager
+def defer_cleanup():
+ # No effect for simulator
+ yield
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/compiler.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/compiler.py
new file mode 100644
index 0000000000000000000000000000000000000000..7db28d41ac65a8669f9ae2f6ed231304091df940
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/compiler.py
@@ -0,0 +1,9 @@
+'''
+The compiler is not implemented in the simulator. This module provides a stub
+to allow tests to import successfully.
+'''
+
+compile = None
+compile_for_current_device = None
+compile_ptx = None
+compile_ptx_for_current_device = None
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/cudadrv/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/cudadrv/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..dde9362d44669831843a33ed2d944c3c64ed91fa
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/cudadrv/__init__.py
@@ -0,0 +1,2 @@
+from numba.cuda.simulator.cudadrv import (devicearray, devices, driver, drvapi,
+ error, nvvm)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/cudadrv/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/cudadrv/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..90989b35807cd03471a033485a8f1cdc4bc36e02
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/cudadrv/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/cudadrv/__pycache__/devicearray.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/cudadrv/__pycache__/devicearray.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..dfce5d59c0f84022298664e0ade9a14cfe856967
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/cudadrv/__pycache__/devicearray.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/cudadrv/__pycache__/devices.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/cudadrv/__pycache__/devices.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a7f001eecbae30e60f39d6b906769244cdcf050e
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/cudadrv/__pycache__/devices.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/cudadrv/__pycache__/driver.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/cudadrv/__pycache__/driver.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c70efe948ac3387c98029107839c7f2e28880262
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/cudadrv/__pycache__/driver.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/cudadrv/__pycache__/drvapi.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/cudadrv/__pycache__/drvapi.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..eaf0f40663b215d4b6c88defc439b7fa69ca1aa6
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/cudadrv/__pycache__/drvapi.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/cudadrv/__pycache__/dummyarray.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/cudadrv/__pycache__/dummyarray.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..04c6b411b195a0f9aa0a0505c780be51b5d04819
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/cudadrv/__pycache__/dummyarray.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/cudadrv/__pycache__/error.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/cudadrv/__pycache__/error.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fab0a067d5f67ceeff4a82e4bd5607549897e625
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/cudadrv/__pycache__/error.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/cudadrv/__pycache__/libs.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/cudadrv/__pycache__/libs.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c5106991506a3dc51936a832e72bf3d564ce72d0
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/cudadrv/__pycache__/libs.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/cudadrv/__pycache__/nvvm.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/cudadrv/__pycache__/nvvm.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0bcfc96258545ae2f36116fea1f937c77578f143
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/cudadrv/__pycache__/nvvm.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/cudadrv/__pycache__/runtime.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/cudadrv/__pycache__/runtime.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3630359468255f6d7dc64afaf0d0c7cdfc0ca0af
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/cudadrv/__pycache__/runtime.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/cudadrv/devicearray.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/cudadrv/devicearray.py
new file mode 100644
index 0000000000000000000000000000000000000000..785f7cdc1748e496f894c0ad1f84c1b48abeba90
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/cudadrv/devicearray.py
@@ -0,0 +1,436 @@
+'''
+The Device Array API is not implemented in the simulator. This module provides
+stubs to allow tests to import correctly.
+'''
+from contextlib import contextmanager
+from numba.np.numpy_support import numpy_version
+
+import numpy as np
+
+
+DeviceRecord = None
+from_record_like = None
+
+
+errmsg_contiguous_buffer = ("Array contains non-contiguous buffer and cannot "
+ "be transferred as a single memory region. Please "
+ "ensure contiguous buffer with numpy "
+ ".ascontiguousarray()")
+
+
+class FakeShape(tuple):
+ '''
+ The FakeShape class is used to provide a shape which does not allow negative
+ indexing, similar to the shape in CUDA Python. (Numpy shape arrays allow
+ negative indexing)
+ '''
+
+ def __getitem__(self, k):
+ if isinstance(k, int) and k < 0:
+ raise IndexError('tuple index out of range')
+ return super(FakeShape, self).__getitem__(k)
+
+
+class FakeWithinKernelCUDAArray(object):
+ '''
+ Created to emulate the behavior of arrays within kernels, where either
+ array.item or array['item'] is valid (that is, give all structured
+ arrays `numpy.recarray`-like semantics). This behaviour does not follow
+ the semantics of Python and NumPy with non-jitted code, and will be
+ deprecated and removed.
+ '''
+
+ def __init__(self, item):
+ assert isinstance(item, FakeCUDAArray)
+ self.__dict__['_item'] = item
+
+ def __wrap_if_fake(self, item):
+ if isinstance(item, FakeCUDAArray):
+ return FakeWithinKernelCUDAArray(item)
+ else:
+ return item
+
+ def __getattr__(self, attrname):
+ try:
+ if attrname in dir(self._item._ary): # For e.g. array size.
+ return self.__wrap_if_fake(getattr(self._item._ary, attrname))
+ else:
+ return self.__wrap_if_fake(self._item.__getitem__(attrname))
+ except Exception as e:
+ if not isinstance(e, AttributeError):
+ raise AttributeError(attrname) from e
+
+ def __setattr__(self, nm, val):
+ self._item.__setitem__(nm, val)
+
+ def __getitem__(self, idx):
+ return self.__wrap_if_fake(self._item.__getitem__(idx))
+
+ def __setitem__(self, idx, val):
+ self._item.__setitem__(idx, val)
+
+ def __len__(self):
+ return len(self._item)
+
+ def __array_ufunc__(self, ufunc, method, *args, **kwargs):
+ # ufuncs can only be called directly on instances of numpy.ndarray (not
+ # things that implement its interfaces, like the FakeCUDAArray or
+ # FakeWithinKernelCUDAArray). For other objects, __array_ufunc__ is
+ # called when they are arguments to ufuncs, to provide an opportunity
+ # to somehow implement the ufunc. Since the FakeWithinKernelCUDAArray
+ # is just a thin wrapper over an ndarray, we can implement all ufuncs
+ # by passing the underlying ndarrays to a call to the intended ufunc.
+ call = getattr(ufunc, method)
+
+ def convert_fakes(obj):
+ if isinstance(obj, FakeWithinKernelCUDAArray):
+ obj = obj._item._ary
+
+ return obj
+
+ out = kwargs.get('out')
+ if out:
+ kwargs['out'] = tuple(convert_fakes(o) for o in out)
+ args = tuple(convert_fakes(a) for a in args)
+ return call(*args, **kwargs)
+
+
+class FakeCUDAArray(object):
+ '''
+ Implements the interface of a DeviceArray/DeviceRecord, but mostly just
+ wraps a NumPy array.
+ '''
+
+ __cuda_ndarray__ = True # There must be gpu_data attribute
+
+ def __init__(self, ary, stream=0):
+ self._ary = ary
+ self.stream = stream
+
+ @property
+ def alloc_size(self):
+ return self._ary.nbytes
+
+ @property
+ def nbytes(self):
+ # return nbytes -- FakeCUDAArray is a wrapper around NumPy
+ return self._ary.nbytes
+
+ def __getattr__(self, attrname):
+ try:
+ attr = getattr(self._ary, attrname)
+ return attr
+ except AttributeError as e:
+ msg = "Wrapped array has no attribute '%s'" % attrname
+ raise AttributeError(msg) from e
+
+ def bind(self, stream=0):
+ return FakeCUDAArray(self._ary, stream)
+
+ @property
+ def T(self):
+ return self.transpose()
+
+ def transpose(self, axes=None):
+ return FakeCUDAArray(np.transpose(self._ary, axes=axes))
+
+ def __getitem__(self, idx):
+ ret = self._ary.__getitem__(idx)
+ if type(ret) not in [np.ndarray, np.void]:
+ return ret
+ else:
+ return FakeCUDAArray(ret, stream=self.stream)
+
+ def __setitem__(self, idx, val):
+ return self._ary.__setitem__(idx, val)
+
+ def copy_to_host(self, ary=None, stream=0):
+ if ary is None:
+ ary = np.empty_like(self._ary)
+ else:
+ check_array_compatibility(self, ary)
+ np.copyto(ary, self._ary)
+ return ary
+
+ def copy_to_device(self, ary, stream=0):
+ '''
+ Copy from the provided array into this array.
+
+ This may be less forgiving than the CUDA Python implementation, which
+ will copy data up to the length of the smallest of the two arrays,
+ whereas this expects the size of the arrays to be equal.
+ '''
+ sentry_contiguous(self)
+ self_core, ary_core = array_core(self), array_core(ary)
+ if isinstance(ary, FakeCUDAArray):
+ sentry_contiguous(ary)
+ check_array_compatibility(self_core, ary_core)
+ else:
+ ary_core = np.array(
+ ary_core,
+ order='C' if self_core.flags['C_CONTIGUOUS'] else 'F',
+ subok=True,
+ copy=False if numpy_version < (2, 0) else None)
+ check_array_compatibility(self_core, ary_core)
+ np.copyto(self_core._ary, ary_core)
+
+ @property
+ def shape(self):
+ return FakeShape(self._ary.shape)
+
+ def ravel(self, *args, **kwargs):
+ return FakeCUDAArray(self._ary.ravel(*args, **kwargs))
+
+ def reshape(self, *args, **kwargs):
+ return FakeCUDAArray(self._ary.reshape(*args, **kwargs))
+
+ def view(self, *args, **kwargs):
+ return FakeCUDAArray(self._ary.view(*args, **kwargs))
+
+ def is_c_contiguous(self):
+ return self._ary.flags.c_contiguous
+
+ def is_f_contiguous(self):
+ return self._ary.flags.f_contiguous
+
+ def __str__(self):
+ return str(self._ary)
+
+ def __repr__(self):
+ return repr(self._ary)
+
+ def __len__(self):
+ return len(self._ary)
+
+ # TODO: Add inplace, bitwise, unary magic methods
+ # (or maybe inherit this class from numpy)?
+ def __eq__(self, other):
+ return FakeCUDAArray(self._ary == other)
+
+ def __ne__(self, other):
+ return FakeCUDAArray(self._ary != other)
+
+ def __lt__(self, other):
+ return FakeCUDAArray(self._ary < other)
+
+ def __le__(self, other):
+ return FakeCUDAArray(self._ary <= other)
+
+ def __gt__(self, other):
+ return FakeCUDAArray(self._ary > other)
+
+ def __ge__(self, other):
+ return FakeCUDAArray(self._ary >= other)
+
+ def __add__(self, other):
+ return FakeCUDAArray(self._ary + other)
+
+ def __sub__(self, other):
+ return FakeCUDAArray(self._ary - other)
+
+ def __mul__(self, other):
+ return FakeCUDAArray(self._ary * other)
+
+ def __floordiv__(self, other):
+ return FakeCUDAArray(self._ary // other)
+
+ def __truediv__(self, other):
+ return FakeCUDAArray(self._ary / other)
+
+ def __mod__(self, other):
+ return FakeCUDAArray(self._ary % other)
+
+ def __pow__(self, other):
+ return FakeCUDAArray(self._ary ** other)
+
+ def split(self, section, stream=0):
+ return [
+ FakeCUDAArray(a)
+ for a in np.split(self._ary, range(section, len(self), section))
+ ]
+
+
+def array_core(ary):
+ """
+ Extract the repeated core of a broadcast array.
+
+ Broadcast arrays are by definition non-contiguous due to repeated
+ dimensions, i.e., dimensions with stride 0. In order to ascertain memory
+ contiguity and copy the underlying data from such arrays, we must create
+ a view without the repeated dimensions.
+
+ """
+ if not ary.strides or not ary.size:
+ return ary
+ core_index = []
+ for stride in ary.strides:
+ core_index.append(0 if stride == 0 else slice(None))
+ return ary[tuple(core_index)]
+
+
+def is_contiguous(ary):
+ """
+ Returns True iff `ary` is C-style contiguous while ignoring
+ broadcasted and 1-sized dimensions.
+ As opposed to array_core(), it does not call require_context(),
+ which can be quite expensive.
+ """
+ size = ary.dtype.itemsize
+ for shape, stride in zip(reversed(ary.shape), reversed(ary.strides)):
+ if shape > 1 and stride != 0:
+ if size != stride:
+ return False
+ size *= shape
+ return True
+
+
+def sentry_contiguous(ary):
+ core = array_core(ary)
+ if not core.flags['C_CONTIGUOUS'] and not core.flags['F_CONTIGUOUS']:
+ raise ValueError(errmsg_contiguous_buffer)
+
+
+def check_array_compatibility(ary1, ary2):
+ ary1sq, ary2sq = ary1.squeeze(), ary2.squeeze()
+ if ary1.dtype != ary2.dtype:
+ raise TypeError('incompatible dtype: %s vs. %s' %
+ (ary1.dtype, ary2.dtype))
+ if ary1sq.shape != ary2sq.shape:
+ raise ValueError('incompatible shape: %s vs. %s' %
+ (ary1.shape, ary2.shape))
+ if ary1sq.strides != ary2sq.strides:
+ raise ValueError('incompatible strides: %s vs. %s' %
+ (ary1.strides, ary2.strides))
+
+
+def to_device(ary, stream=0, copy=True, to=None):
+ ary = np.array(ary,
+ copy=False if numpy_version < (2, 0) else None,
+ subok=True)
+ sentry_contiguous(ary)
+ if to is None:
+ buffer_dtype = np.int64 if ary.dtype.char in 'Mm' else ary.dtype
+ return FakeCUDAArray(
+ np.ndarray(
+ buffer=np.copy(array_core(ary)).view(buffer_dtype),
+ dtype=ary.dtype,
+ shape=ary.shape,
+ strides=ary.strides,
+ ).view(type=type(ary)),
+ )
+ else:
+ to.copy_to_device(ary, stream=stream)
+
+
+@contextmanager
+def pinned(arg):
+ yield
+
+
+def mapped_array(*args, **kwargs):
+ for unused_arg in ('portable', 'wc'):
+ if unused_arg in kwargs:
+ kwargs.pop(unused_arg)
+ return device_array(*args, **kwargs)
+
+
+def pinned_array(shape, dtype=np.float64, strides=None, order='C'):
+ return np.ndarray(shape=shape, strides=strides, dtype=dtype, order=order)
+
+
+def managed_array(shape, dtype=np.float64, strides=None, order='C'):
+ return np.ndarray(shape=shape, strides=strides, dtype=dtype, order=order)
+
+
+def device_array(*args, **kwargs):
+ stream = kwargs.pop('stream') if 'stream' in kwargs else 0
+ return FakeCUDAArray(np.ndarray(*args, **kwargs), stream=stream)
+
+
+def _contiguous_strides_like_array(ary):
+ """
+ Given an array, compute strides for a new contiguous array of the same
+ shape.
+ """
+ # Don't recompute strides if the default strides will be sufficient to
+ # create a contiguous array.
+ if ary.flags['C_CONTIGUOUS'] or ary.flags['F_CONTIGUOUS'] or ary.ndim <= 1:
+ return None
+
+ # Otherwise, we need to compute new strides using an algorithm adapted from
+ # NumPy v1.17.4's PyArray_NewLikeArrayWithShape in
+ # core/src/multiarray/ctors.c. We permute the strides in ascending order
+ # then compute the stride for the dimensions with the same permutation.
+
+ # Stride permutation. E.g. a stride array (4, -2, 12) becomes
+ # [(1, -2), (0, 4), (2, 12)]
+ strideperm = [ x for x in enumerate(ary.strides) ]
+ strideperm.sort(key=lambda x: x[1])
+
+ # Compute new strides using permutation
+ strides = [0] * len(ary.strides)
+ stride = ary.dtype.itemsize
+ for i_perm, _ in strideperm:
+ strides[i_perm] = stride
+ stride *= ary.shape[i_perm]
+ return tuple(strides)
+
+
+def _order_like_array(ary):
+ if ary.flags['F_CONTIGUOUS'] and not ary.flags['C_CONTIGUOUS']:
+ return 'F'
+ else:
+ return 'C'
+
+
+def device_array_like(ary, stream=0):
+ strides = _contiguous_strides_like_array(ary)
+ order = _order_like_array(ary)
+ return device_array(shape=ary.shape, dtype=ary.dtype, strides=strides,
+ order=order)
+
+
+def pinned_array_like(ary):
+ strides = _contiguous_strides_like_array(ary)
+ order = _order_like_array(ary)
+ return pinned_array(shape=ary.shape, dtype=ary.dtype, strides=strides,
+ order=order)
+
+
+def auto_device(ary, stream=0, copy=True):
+ if isinstance(ary, FakeCUDAArray):
+ return ary, False
+
+ if not isinstance(ary, np.void):
+ ary = np.array(
+ ary,
+ copy=False if numpy_version < (2, 0) else None,
+ subok=True)
+ return to_device(ary, stream, copy), True
+
+
+def is_cuda_ndarray(obj):
+ "Check if an object is a CUDA ndarray"
+ return getattr(obj, '__cuda_ndarray__', False)
+
+
+def verify_cuda_ndarray_interface(obj):
+ "Verify the CUDA ndarray interface for an obj"
+ require_cuda_ndarray(obj)
+
+ def requires_attr(attr, typ):
+ if not hasattr(obj, attr):
+ raise AttributeError(attr)
+ if not isinstance(getattr(obj, attr), typ):
+ raise AttributeError('%s must be of type %s' % (attr, typ))
+
+ requires_attr('shape', tuple)
+ requires_attr('strides', tuple)
+ requires_attr('dtype', np.dtype)
+ requires_attr('size', int)
+
+
+def require_cuda_ndarray(obj):
+ "Raises ValueError is is_cuda_ndarray(obj) evaluates False"
+ if not is_cuda_ndarray(obj):
+ raise ValueError('require an cuda ndarray object')
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/cudadrv/devices.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/cudadrv/devices.py
new file mode 100644
index 0000000000000000000000000000000000000000..3237fb2c6adea223bf079665319d3ef7b3c8489e
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/cudadrv/devices.py
@@ -0,0 +1,117 @@
+import numpy as np
+from collections import namedtuple
+
+_MemoryInfo = namedtuple("_MemoryInfo", "free,total")
+
+_SIMULATOR_CC = (5, 2)
+
+
+class FakeCUDADevice:
+ def __init__(self):
+ self.uuid = 'GPU-00000000-0000-0000-0000-000000000000'
+
+ @property
+ def compute_capability(self):
+ return _SIMULATOR_CC
+
+
+class FakeCUDAContext:
+ '''
+ This stub implements functionality only for simulating a single GPU
+ at the moment.
+ '''
+ def __init__(self, device_id):
+ self._device_id = device_id
+ self._device = FakeCUDADevice()
+
+ def __enter__(self):
+ pass
+
+ def __exit__(self, exc_type, exc_val, exc_tb):
+ pass
+
+ def __str__(self):
+ return "".format(self=self)
+
+ @property
+ def id(self):
+ return self._device_id
+
+ @property
+ def device(self):
+ return self._device
+
+ @property
+ def compute_capability(self):
+ return _SIMULATOR_CC
+
+ def reset(self):
+ pass
+
+ def get_memory_info(self):
+ """
+ Cross-platform free / total host memory is hard without external
+ dependencies, e.g. `psutil` - so return infinite memory to maintain API
+ type compatibility
+ """
+ return _MemoryInfo(float('inf'), float('inf'))
+
+ def memalloc(self, sz):
+ """
+ Allocates memory on the simulated device
+ At present, there is no division between simulated
+ host memory and simulated device memory.
+ """
+ return np.ndarray(sz, dtype='u1')
+
+ def memhostalloc(self, sz, mapped=False, portable=False, wc=False):
+ '''Allocates memory on the host'''
+ return self.memalloc(sz)
+
+
+class FakeDeviceList:
+ '''
+ This stub implements a device list containing a single GPU. It also
+ keeps track of the GPU status, i.e. whether the context is closed or not,
+ which may have been set by the user calling reset()
+ '''
+ def __init__(self):
+ self.lst = (FakeCUDAContext(0),)
+ self.closed = False
+
+ def __getitem__(self, devnum):
+ self.closed = False
+ return self.lst[devnum]
+
+ def __str__(self):
+ return ', '.join([str(d) for d in self.lst])
+
+ def __iter__(self):
+ return iter(self.lst)
+
+ def __len__(self):
+ return len(self.lst)
+
+ @property
+ def current(self):
+ if self.closed:
+ return None
+ return self.lst[0]
+
+
+gpus = FakeDeviceList()
+
+
+def reset():
+ gpus[0].closed = True
+
+
+def get_context(devnum=0):
+ return FakeCUDAContext(devnum)
+
+
+def require_context(func):
+ '''
+ In the simulator, a context is always "available", so this is a no-op.
+ '''
+ return func
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/cudadrv/driver.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/cudadrv/driver.py
new file mode 100644
index 0000000000000000000000000000000000000000..09de5b729af1da79db35f9c73bed08dfabffff48
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/cudadrv/driver.py
@@ -0,0 +1,62 @@
+'''
+Most of the driver API is unsupported in the simulator, but some stubs are
+provided to allow tests to import correctly.
+'''
+
+
+def device_memset(dst, val, size, stream=0):
+ dst.view('u1')[:size].fill(bytes([val])[0])
+
+
+def host_to_device(dst, src, size, stream=0):
+ dst.view('u1')[:size] = src.view('u1')[:size]
+
+
+def device_to_host(dst, src, size, stream=0):
+ host_to_device(dst, src, size)
+
+
+def device_memory_size(obj):
+ return obj.itemsize * obj.size
+
+
+def device_to_device(dst, src, size, stream=0):
+ host_to_device(dst, src, size)
+
+
+class FakeDriver(object):
+ def get_device_count(self):
+ return 1
+
+
+driver = FakeDriver()
+
+
+class Linker:
+ @classmethod
+ def new(cls, max_registers=0, lineinfo=False, cc=None):
+ return Linker()
+
+ @property
+ def lto(self):
+ return False
+
+
+class LinkerError(RuntimeError):
+ pass
+
+
+class NvrtcError(RuntimeError):
+ pass
+
+
+class CudaAPIError(RuntimeError):
+ pass
+
+
+def launch_kernel(*args, **kwargs):
+ msg = 'Launching kernels directly is not supported in the simulator'
+ raise RuntimeError(msg)
+
+
+USE_NV_BINDING = False
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/cudadrv/drvapi.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/cudadrv/drvapi.py
new file mode 100644
index 0000000000000000000000000000000000000000..44c697f37debb3a6a80d7516063f4524cbc3a152
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/cudadrv/drvapi.py
@@ -0,0 +1,4 @@
+'''
+drvapi is not implemented in the simulator, but this module exists to allow
+tests to import correctly.
+'''
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/cudadrv/dummyarray.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/cudadrv/dummyarray.py
new file mode 100644
index 0000000000000000000000000000000000000000..adabaa7828c24856a0a52d45c29f27bbdd544831
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/cudadrv/dummyarray.py
@@ -0,0 +1,4 @@
+# Dummy arrays are not implemented in the simulator. This file allows the dummy
+# array tests to be imported, but they are skipped on the simulator.
+
+Array = None
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/cudadrv/error.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/cudadrv/error.py
new file mode 100644
index 0000000000000000000000000000000000000000..eaaa2884a0d2380015b6a4f11177e2fcaaa7f51d
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/cudadrv/error.py
@@ -0,0 +1,6 @@
+class CudaSupportError(RuntimeError):
+ pass
+
+
+class NvrtcError(Exception):
+ pass
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/cudadrv/libs.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/cudadrv/libs.py
new file mode 100644
index 0000000000000000000000000000000000000000..347b936c5d9ae465b3d8644dc63529d363add4ed
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/cudadrv/libs.py
@@ -0,0 +1,2 @@
+def check_static_lib(lib):
+ raise FileNotFoundError('Linking libraries not supported by cudasim')
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/cudadrv/nvvm.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/cudadrv/nvvm.py
new file mode 100644
index 0000000000000000000000000000000000000000..2a011a77a4002e655085d2da67a7f06f4b1f0519
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/cudadrv/nvvm.py
@@ -0,0 +1,29 @@
+'''
+NVVM is not supported in the simulator, but stubs are provided to allow tests
+to import correctly.
+'''
+
+
+class NvvmSupportError(ImportError):
+ pass
+
+
+class NVVM(object):
+ def __init__(self):
+ raise NvvmSupportError('NVVM not supported in the simulator')
+
+
+CompilationUnit = None
+compile_ir = None
+set_cuda_kernel = None
+get_arch_option = None
+LibDevice = None
+NvvmError = None
+
+
+def is_available():
+ return False
+
+
+def get_supported_ccs():
+ return ()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/cudadrv/runtime.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/cudadrv/runtime.py
new file mode 100644
index 0000000000000000000000000000000000000000..308d19e7683b27754c68dca334f22805e50821d2
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/cudadrv/runtime.py
@@ -0,0 +1,19 @@
+'''
+The runtime API is unsupported in the simulator, but some stubs are
+provided to allow tests to import correctly.
+'''
+
+
+class FakeRuntime(object):
+ def get_version(self):
+ return (-1, -1)
+
+ def is_supported_version(self):
+ return True
+
+ @property
+ def supported_versions(self):
+ return (-1, -1),
+
+
+runtime = FakeRuntime()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/kernel.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/kernel.py
new file mode 100644
index 0000000000000000000000000000000000000000..b3ca2259938b99f0beefffe10b199715dd5e6707
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/kernel.py
@@ -0,0 +1,308 @@
+from contextlib import contextmanager
+import functools
+import sys
+import threading
+
+import numpy as np
+
+from .cudadrv.devicearray import FakeCUDAArray, FakeWithinKernelCUDAArray
+from .kernelapi import Dim3, FakeCUDAModule, swapped_cuda_module
+from ..errors import normalize_kernel_dimensions
+from ..args import wrap_arg, ArgHint
+
+
+"""
+Global variable to keep track of the current "kernel context", i.e the
+FakeCUDAModule. We only support one kernel launch at a time.
+No support for concurrent kernel launch.
+"""
+_kernel_context = None
+
+
+@contextmanager
+def _push_kernel_context(mod):
+ """
+ Push the current kernel context.
+ """
+ global _kernel_context
+ assert _kernel_context is None, "concurrent simulated kernel not supported"
+ _kernel_context = mod
+ try:
+ yield
+ finally:
+ _kernel_context = None
+
+
+def _get_kernel_context():
+ """
+ Get the current kernel context. This is usually done by a device function.
+ """
+ return _kernel_context
+
+
+class FakeOverload:
+ '''
+ Used only to provide the max_cooperative_grid_blocks method
+ '''
+ def max_cooperative_grid_blocks(self, blockdim):
+ # We can only run one block in a cooperative grid because we have no
+ # mechanism for synchronization between different blocks
+ return 1
+
+
+class FakeOverloadDict(dict):
+ def __getitem__(self, key):
+ # Always return a fake overload for any signature, as we don't keep
+ # track of overloads in the simulator.
+ return FakeOverload()
+
+
+class FakeCUDAKernel(object):
+ '''
+ Wraps a @cuda.jit-ed function.
+ '''
+
+ def __init__(self, fn, device, fastmath=False, extensions=[], debug=False):
+ self.fn = fn
+ self._device = device
+ self._fastmath = fastmath
+ self._debug = debug
+ self.extensions = list(extensions) # defensive copy
+ # Initial configuration: grid unconfigured, stream 0, no dynamic shared
+ # memory.
+ self.grid_dim = None
+ self.block_dim = None
+ self.stream = 0
+ self.dynshared_size = 0
+ functools.update_wrapper(self, fn)
+
+ def __call__(self, *args):
+ if self._device:
+ with swapped_cuda_module(self.fn, _get_kernel_context()):
+ return self.fn(*args)
+
+ # Ensure we've been given a valid grid configuration
+ grid_dim, block_dim = normalize_kernel_dimensions(self.grid_dim,
+ self.block_dim)
+
+ fake_cuda_module = FakeCUDAModule(grid_dim, block_dim,
+ self.dynshared_size)
+ with _push_kernel_context(fake_cuda_module):
+ # fake_args substitutes all numpy arrays for FakeCUDAArrays
+ # because they implement some semantics differently
+ retr = []
+
+ def fake_arg(arg):
+ # map the arguments using any extension you've registered
+ _, arg = functools.reduce(
+ lambda ty_val, extension: extension.prepare_args(
+ *ty_val,
+ stream=0,
+ retr=retr),
+ self.extensions,
+ (None, arg)
+ )
+
+ if isinstance(arg, np.ndarray) and arg.ndim > 0:
+ ret = wrap_arg(arg).to_device(retr)
+ elif isinstance(arg, ArgHint):
+ ret = arg.to_device(retr)
+ elif isinstance(arg, np.void):
+ ret = FakeCUDAArray(arg) # In case a np record comes in.
+ else:
+ ret = arg
+ if isinstance(ret, FakeCUDAArray):
+ return FakeWithinKernelCUDAArray(ret)
+ return ret
+
+ fake_args = [fake_arg(arg) for arg in args]
+ with swapped_cuda_module(self.fn, fake_cuda_module):
+ # Execute one block at a time
+ for grid_point in np.ndindex(*grid_dim):
+ bm = BlockManager(self.fn, grid_dim, block_dim, self._debug)
+ bm.run(grid_point, *fake_args)
+
+ for wb in retr:
+ wb()
+
+ def __getitem__(self, configuration):
+ self.grid_dim, self.block_dim = \
+ normalize_kernel_dimensions(*configuration[:2])
+
+ if len(configuration) == 4:
+ self.dynshared_size = configuration[3]
+
+ return self
+
+ def bind(self):
+ pass
+
+ def specialize(self, *args):
+ return self
+
+ def forall(self, ntasks, tpb=0, stream=0, sharedmem=0):
+ if ntasks < 0:
+ raise ValueError("Can't create ForAll with negative task count: %s"
+ % ntasks)
+ return self[ntasks, 1, stream, sharedmem]
+
+ @property
+ def overloads(self):
+ return FakeOverloadDict()
+
+ @property
+ def py_func(self):
+ return self.fn
+
+
+# Thread emulation
+
+class BlockThread(threading.Thread):
+ '''
+ Manages the execution of a function for a single CUDA thread.
+ '''
+ def __init__(self, f, manager, blockIdx, threadIdx, debug):
+ if debug:
+ def debug_wrapper(*args, **kwargs):
+ np.seterr(divide='raise')
+ f(*args, **kwargs)
+ target = debug_wrapper
+ else:
+ target = f
+
+ super(BlockThread, self).__init__(target=target)
+ self.syncthreads_event = threading.Event()
+ self.syncthreads_blocked = False
+ self._manager = manager
+ self.blockIdx = Dim3(*blockIdx)
+ self.threadIdx = Dim3(*threadIdx)
+ self.exception = None
+ self.daemon = True
+ self.abort = False
+ self.debug = debug
+ blockDim = Dim3(*self._manager._block_dim)
+ self.thread_id = self.threadIdx.x + (blockDim.x * (self.threadIdx.y +
+ blockDim.y *
+ self.threadIdx.z))
+
+ def run(self):
+ try:
+ super(BlockThread, self).run()
+ except Exception as e:
+ tid = 'tid=%s' % list(self.threadIdx)
+ ctaid = 'ctaid=%s' % list(self.blockIdx)
+ if str(e) == '':
+ msg = '%s %s' % (tid, ctaid)
+ else:
+ msg = '%s %s: %s' % (tid, ctaid, e)
+ tb = sys.exc_info()[2]
+ # Using `with_traceback` here would cause it to be mutated by
+ # future raise statements, which may or may not matter.
+ self.exception = (type(e)(msg), tb)
+
+ def syncthreads(self):
+
+ if self.abort:
+ raise RuntimeError("abort flag set on syncthreads call")
+
+ self.syncthreads_blocked = True
+ self.syncthreads_event.wait()
+ self.syncthreads_event.clear()
+
+ if self.abort:
+ raise RuntimeError("abort flag set on syncthreads clear")
+
+ def syncthreads_count(self, value):
+ idx = self.threadIdx.x, self.threadIdx.y, self.threadIdx.z
+ self._manager.block_state[idx] = value
+ self.syncthreads()
+ count = np.count_nonzero(self._manager.block_state)
+ self.syncthreads()
+ return count
+
+ def syncthreads_and(self, value):
+ idx = self.threadIdx.x, self.threadIdx.y, self.threadIdx.z
+ self._manager.block_state[idx] = value
+ self.syncthreads()
+ test = np.all(self._manager.block_state)
+ self.syncthreads()
+ return 1 if test else 0
+
+ def syncthreads_or(self, value):
+ idx = self.threadIdx.x, self.threadIdx.y, self.threadIdx.z
+ self._manager.block_state[idx] = value
+ self.syncthreads()
+ test = np.any(self._manager.block_state)
+ self.syncthreads()
+ return 1 if test else 0
+
+ def __str__(self):
+ return 'Thread <<<%s, %s>>>' % (self.blockIdx, self.threadIdx)
+
+
+class BlockManager(object):
+ '''
+ Manages the execution of a thread block.
+
+ When run() is called, all threads are started. Each thread executes until it
+ hits syncthreads(), at which point it sets its own syncthreads_blocked to
+ True so that the BlockManager knows it is blocked. It then waits on its
+ syncthreads_event.
+
+ The BlockManager polls threads to determine if they are blocked in
+ syncthreads(). If it finds a blocked thread, it adds it to the set of
+ blocked threads. When all threads are blocked, it unblocks all the threads.
+ The thread are unblocked by setting their syncthreads_blocked back to False
+ and setting their syncthreads_event.
+
+ The polling continues until no threads are alive, when execution is
+ complete.
+ '''
+ def __init__(self, f, grid_dim, block_dim, debug):
+ self._grid_dim = grid_dim
+ self._block_dim = block_dim
+ self._f = f
+ self._debug = debug
+ self.block_state = np.zeros(block_dim, dtype=np.bool_)
+
+ def run(self, grid_point, *args):
+ # Create all threads
+ threads = set()
+ livethreads = set()
+ blockedthreads = set()
+ for block_point in np.ndindex(*self._block_dim):
+ def target():
+ self._f(*args)
+ t = BlockThread(target, self, grid_point, block_point, self._debug)
+ t.start()
+ threads.add(t)
+ livethreads.add(t)
+
+ # Potential optimisations:
+ # 1. Continue the while loop immediately after finding a blocked thread
+ # 2. Don't poll already-blocked threads
+ while livethreads:
+ for t in livethreads:
+ if t.syncthreads_blocked:
+ blockedthreads.add(t)
+ elif t.exception:
+
+ # Abort all other simulator threads on exception,
+ # do *not* join immediately to facilitate debugging.
+ for t_other in threads:
+ t_other.abort = True
+ t_other.syncthreads_blocked = False
+ t_other.syncthreads_event.set()
+
+ raise t.exception[0].with_traceback(t.exception[1])
+ if livethreads == blockedthreads:
+ for t in blockedthreads:
+ t.syncthreads_blocked = False
+ t.syncthreads_event.set()
+ blockedthreads = set()
+ livethreads = set([ t for t in livethreads if t.is_alive() ])
+ # Final check for exceptions in case any were set prior to thread
+ # finishing, before we could check it
+ for t in threads:
+ if t.exception:
+ raise t.exception[0].with_traceback(t.exception[1])
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/kernelapi.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/kernelapi.py
new file mode 100644
index 0000000000000000000000000000000000000000..64793df054cc2e2baeb00d059338fa570e53718a
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/kernelapi.py
@@ -0,0 +1,495 @@
+'''
+Implements the cuda module as called from within an executing kernel
+(@cuda.jit-decorated function).
+'''
+
+from contextlib import contextmanager
+import sys
+import threading
+import traceback
+from numba.core import types
+import numpy as np
+
+from numba.np import numpy_support
+
+from .vector_types import vector_types
+
+
+class Dim3(object):
+ '''
+ Used to implement thread/block indices/dimensions
+ '''
+ def __init__(self, x, y, z):
+ self.x = x
+ self.y = y
+ self.z = z
+
+ def __str__(self):
+ return '(%s, %s, %s)' % (self.x, self.y, self.z)
+
+ def __repr__(self):
+ return 'Dim3(%s, %s, %s)' % (self.x, self.y, self.z)
+
+ def __iter__(self):
+ yield self.x
+ yield self.y
+ yield self.z
+
+
+class GridGroup:
+ '''
+ Used to implement the grid group.
+ '''
+
+ def sync(self):
+ # Synchronization of the grid group is equivalent to synchronization of
+ # the thread block, because we only support cooperative grids with one
+ # block.
+ threading.current_thread().syncthreads()
+
+
+class FakeCUDACg:
+ '''
+ CUDA Cooperative Groups
+ '''
+ def this_grid(self):
+ return GridGroup()
+
+
+class FakeCUDALocal(object):
+ '''
+ CUDA Local arrays
+ '''
+ def array(self, shape, dtype):
+ if isinstance(dtype, types.Type):
+ dtype = numpy_support.as_dtype(dtype)
+ return np.empty(shape, dtype)
+
+
+class FakeCUDAConst(object):
+ '''
+ CUDA Const arrays
+ '''
+ def array_like(self, ary):
+ return ary
+
+
+class FakeCUDAShared(object):
+ '''
+ CUDA Shared arrays.
+
+ Limitations: assumes that only one call to cuda.shared.array is on a line,
+ and that that line is only executed once per thread. i.e.::
+
+ a = cuda.shared.array(...); b = cuda.shared.array(...)
+
+ will erroneously alias a and b, and::
+
+ for i in range(10):
+ sharedarrs[i] = cuda.shared.array(...)
+
+ will alias all arrays created at that point (though it is not certain that
+ this would be supported by Numba anyway).
+ '''
+
+ def __init__(self, dynshared_size):
+ self._allocations = {}
+ self._dynshared_size = dynshared_size
+ self._dynshared = np.zeros(dynshared_size, dtype=np.byte)
+
+ def array(self, shape, dtype):
+ if isinstance(dtype, types.Type):
+ dtype = numpy_support.as_dtype(dtype)
+ # Dynamic shared memory is requested with size 0 - this all shares the
+ # same underlying memory
+ if shape == 0:
+ # Count must be the maximum number of whole elements that fit in the
+ # buffer (Numpy complains if the buffer is not a multiple of the
+ # element size)
+ count = self._dynshared_size // dtype.itemsize
+ return np.frombuffer(self._dynshared.data, dtype=dtype, count=count)
+
+ # Otherwise, identify allocations by source file and line number
+ # We pass the reference frame explicitly to work around
+ # http://bugs.python.org/issue25108
+ stack = traceback.extract_stack(sys._getframe())
+ caller = stack[-2][0:2]
+ res = self._allocations.get(caller)
+ if res is None:
+ res = np.empty(shape, dtype)
+ self._allocations[caller] = res
+ return res
+
+
+addlock = threading.Lock()
+sublock = threading.Lock()
+andlock = threading.Lock()
+orlock = threading.Lock()
+xorlock = threading.Lock()
+maxlock = threading.Lock()
+minlock = threading.Lock()
+compare_and_swaplock = threading.Lock()
+caslock = threading.Lock()
+inclock = threading.Lock()
+declock = threading.Lock()
+exchlock = threading.Lock()
+
+
+class FakeCUDAAtomic(object):
+ def add(self, array, index, val):
+ with addlock:
+ old = array[index]
+ array[index] += val
+ return old
+
+ def sub(self, array, index, val):
+ with sublock:
+ old = array[index]
+ array[index] -= val
+ return old
+
+ def and_(self, array, index, val):
+ with andlock:
+ old = array[index]
+ array[index] &= val
+ return old
+
+ def or_(self, array, index, val):
+ with orlock:
+ old = array[index]
+ array[index] |= val
+ return old
+
+ def xor(self, array, index, val):
+ with xorlock:
+ old = array[index]
+ array[index] ^= val
+ return old
+
+ def inc(self, array, index, val):
+ with inclock:
+ old = array[index]
+ if old >= val:
+ array[index] = 0
+ else:
+ array[index] += 1
+ return old
+
+ def dec(self, array, index, val):
+ with declock:
+ old = array[index]
+ if (old == 0) or (old > val):
+ array[index] = val
+ else:
+ array[index] -= 1
+ return old
+
+ def exch(self, array, index, val):
+ with exchlock:
+ old = array[index]
+ array[index] = val
+ return old
+
+ def max(self, array, index, val):
+ with maxlock:
+ old = array[index]
+ array[index] = max(old, val)
+ return old
+
+ def min(self, array, index, val):
+ with minlock:
+ old = array[index]
+ array[index] = min(old, val)
+ return old
+
+ def nanmax(self, array, index, val):
+ with maxlock:
+ old = array[index]
+ array[index] = np.nanmax([array[index], val])
+ return old
+
+ def nanmin(self, array, index, val):
+ with minlock:
+ old = array[index]
+ array[index] = np.nanmin([array[index], val])
+ return old
+
+ def compare_and_swap(self, array, old, val):
+ with compare_and_swaplock:
+ index = (0,) * array.ndim
+ loaded = array[index]
+ if loaded == old:
+ array[index] = val
+ return loaded
+
+ def cas(self, array, index, old, val):
+ with caslock:
+ loaded = array[index]
+ if loaded == old:
+ array[index] = val
+ return loaded
+
+
+class FakeCUDAFp16(object):
+ def hadd(self, a, b):
+ return a + b
+
+ def hsub(self, a, b):
+ return a - b
+
+ def hmul(self, a, b):
+ return a * b
+
+ def hdiv(self, a, b):
+ return a / b
+
+ def hfma(self, a, b, c):
+ return a * b + c
+
+ def hneg(self, a):
+ return -a
+
+ def habs(self, a):
+ return abs(a)
+
+ def hsin(self, x):
+ return np.sin(x, dtype=np.float16)
+
+ def hcos(self, x):
+ return np.cos(x, dtype=np.float16)
+
+ def hlog(self, x):
+ return np.log(x, dtype=np.float16)
+
+ def hlog2(self, x):
+ return np.log2(x, dtype=np.float16)
+
+ def hlog10(self, x):
+ return np.log10(x, dtype=np.float16)
+
+ def hexp(self, x):
+ return np.exp(x, dtype=np.float16)
+
+ def hexp2(self, x):
+ return np.exp2(x, dtype=np.float16)
+
+ def hexp10(self, x):
+ return np.float16(10 ** x)
+
+ def hsqrt(self, x):
+ return np.sqrt(x, dtype=np.float16)
+
+ def hrsqrt(self, x):
+ return np.float16(x ** -0.5)
+
+ def hceil(self, x):
+ return np.ceil(x, dtype=np.float16)
+
+ def hfloor(self, x):
+ return np.ceil(x, dtype=np.float16)
+
+ def hrcp(self, x):
+ return np.reciprocal(x, dtype=np.float16)
+
+ def htrunc(self, x):
+ return np.trunc(x, dtype=np.float16)
+
+ def hrint(self, x):
+ return np.rint(x, dtype=np.float16)
+
+ def heq(self, a, b):
+ return a == b
+
+ def hne(self, a, b):
+ return a != b
+
+ def hge(self, a, b):
+ return a >= b
+
+ def hgt(self, a, b):
+ return a > b
+
+ def hle(self, a, b):
+ return a <= b
+
+ def hlt(self, a, b):
+ return a < b
+
+ def hmax(self, a, b):
+ return max(a, b)
+
+ def hmin(self, a, b):
+ return min(a, b)
+
+
+class FakeCUDAModule(object):
+ '''
+ An instance of this class will be injected into the __globals__ for an
+ executing function in order to implement calls to cuda.*. This will fail to
+ work correctly if the user code does::
+
+ from numba import cuda as something_else
+
+ In other words, the CUDA module must be called cuda.
+ '''
+
+ def __init__(self, grid_dim, block_dim, dynshared_size):
+ self.gridDim = Dim3(*grid_dim)
+ self.blockDim = Dim3(*block_dim)
+ self._cg = FakeCUDACg()
+ self._local = FakeCUDALocal()
+ self._shared = FakeCUDAShared(dynshared_size)
+ self._const = FakeCUDAConst()
+ self._atomic = FakeCUDAAtomic()
+ self._fp16 = FakeCUDAFp16()
+ # Insert the vector types into the kernel context
+ # Note that we need to do this in addition to exposing them as module
+ # variables in `simulator.__init__.py`, because the test cases need
+ # to access the actual cuda module as well as the fake cuda module
+ # for vector types.
+ for name, svty in vector_types.items():
+ setattr(self, name, svty)
+ for alias in svty.aliases:
+ setattr(self, alias, svty)
+
+ @property
+ def cg(self):
+ return self._cg
+
+ @property
+ def local(self):
+ return self._local
+
+ @property
+ def shared(self):
+ return self._shared
+
+ @property
+ def const(self):
+ return self._const
+
+ @property
+ def atomic(self):
+ return self._atomic
+
+ @property
+ def fp16(self):
+ return self._fp16
+
+ @property
+ def threadIdx(self):
+ return threading.current_thread().threadIdx
+
+ @property
+ def blockIdx(self):
+ return threading.current_thread().blockIdx
+
+ @property
+ def warpsize(self):
+ return 32
+
+ @property
+ def laneid(self):
+ return threading.current_thread().thread_id % 32
+
+ def syncthreads(self):
+ threading.current_thread().syncthreads()
+
+ def threadfence(self):
+ # No-op
+ pass
+
+ def threadfence_block(self):
+ # No-op
+ pass
+
+ def threadfence_system(self):
+ # No-op
+ pass
+
+ def syncthreads_count(self, val):
+ return threading.current_thread().syncthreads_count(val)
+
+ def syncthreads_and(self, val):
+ return threading.current_thread().syncthreads_and(val)
+
+ def syncthreads_or(self, val):
+ return threading.current_thread().syncthreads_or(val)
+
+ def popc(self, val):
+ return bin(val).count("1")
+
+ def fma(self, a, b, c):
+ return a * b + c
+
+ def cbrt(self, a):
+ return a ** (1 / 3)
+
+ def brev(self, val):
+ return int('{:032b}'.format(val)[::-1], 2)
+
+ def clz(self, val):
+ s = '{:032b}'.format(val)
+ return len(s) - len(s.lstrip('0'))
+
+ def ffs(self, val):
+ # The algorithm is:
+ # 1. Count the number of trailing zeros.
+ # 2. Add 1, because the LSB is numbered 1 rather than 0, and so on.
+ # 3. If we've counted 32 zeros (resulting in 33), there were no bits
+ # set so we need to return zero.
+ s = '{:032b}'.format(val)
+ r = (len(s) - len(s.rstrip('0')) + 1) % 33
+ return r
+
+ def selp(self, a, b, c):
+ return b if a else c
+
+ def grid(self, n):
+ bdim = self.blockDim
+ bid = self.blockIdx
+ tid = self.threadIdx
+ x = bid.x * bdim.x + tid.x
+ if n == 1:
+ return x
+ y = bid.y * bdim.y + tid.y
+ if n == 2:
+ return (x, y)
+ z = bid.z * bdim.z + tid.z
+ if n == 3:
+ return (x, y, z)
+
+ raise RuntimeError("Global ID has 1-3 dimensions. %d requested" % n)
+
+ def gridsize(self, n):
+ bdim = self.blockDim
+ gdim = self.gridDim
+ x = bdim.x * gdim.x
+ if n == 1:
+ return x
+ y = bdim.y * gdim.y
+ if n == 2:
+ return (x, y)
+ z = bdim.z * gdim.z
+ if n == 3:
+ return (x, y, z)
+
+ raise RuntimeError("Global grid has 1-3 dimensions. %d requested" % n)
+
+
+@contextmanager
+def swapped_cuda_module(fn, fake_cuda_module):
+ from numba import cuda
+
+ fn_globs = fn.__globals__
+ # get all globals that is the "cuda" module
+ orig = dict((k, v) for k, v in fn_globs.items() if v is cuda)
+ # build replacement dict
+ repl = dict((k, fake_cuda_module) for k, v in orig.items())
+ # replace
+ fn_globs.update(repl)
+ try:
+ yield
+ finally:
+ # revert
+ fn_globs.update(orig)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/reduction.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/reduction.py
new file mode 100644
index 0000000000000000000000000000000000000000..1b819c043549c936fc9a73271fe846f02eb05001
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/reduction.py
@@ -0,0 +1,15 @@
+from functools import reduce as pyreduce
+
+
+def Reduce(func):
+ def reduce_wrapper(seq, res=None, init=0):
+ r = pyreduce(func, seq, init)
+ if res is not None:
+ res[0] = r
+ return None
+ else:
+ return r
+ return reduce_wrapper
+
+
+reduce = Reduce
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/vector_types.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/vector_types.py
new file mode 100644
index 0000000000000000000000000000000000000000..de82ab35e1085b816e934f09f87c457b9c6e2f45
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/simulator/vector_types.py
@@ -0,0 +1,63 @@
+from numba import types, config
+from numba.cuda.stubs import _vector_type_stubs
+
+
+class SimulatedVectorType:
+ attributes = ['x', 'y', 'z', 'w']
+
+ def __init__(self, *args):
+ args_flattened = []
+ for arg in args:
+ if isinstance(arg, SimulatedVectorType):
+ args_flattened += arg.as_list()
+ else:
+ args_flattened.append(arg)
+ self._attrs = self.attributes[:len(args_flattened)]
+ if not self.num_elements == len(args_flattened):
+ raise TypeError(
+ f"{self.name} expects {self.num_elements}"
+ f" elements, got {len(args_flattened)}"
+ )
+
+ for arg, attr in zip(args_flattened, self._attrs):
+ setattr(self, attr, arg)
+
+ @property
+ def name(self):
+ raise NotImplementedError()
+
+ @property
+ def num_elements(self):
+ raise NotImplementedError()
+
+ def as_list(self):
+ return [getattr(self, attr) for attr in self._attrs]
+
+
+def make_simulated_vector_type(num_elements, name):
+ if config.USE_LEGACY_TYPE_SYSTEM:
+ base_type = types.float32
+ else:
+ base_type = types.np_float32
+
+ obj = type(name, (SimulatedVectorType,), {
+ "num_elements": num_elements,
+ "base_type": base_type,
+ "name": name
+ })
+ obj.user_facing_object = obj
+ return obj
+
+
+def _initialize():
+ _simulated_vector_types = {}
+ for stub in _vector_type_stubs:
+ num_elements = int(stub.__name__[-1])
+ _simulated_vector_types[stub.__name__] = (
+ make_simulated_vector_type(num_elements, stub.__name__)
+ )
+ _simulated_vector_types[stub.__name__].aliases = stub.aliases
+ return _simulated_vector_types
+
+
+vector_types = _initialize()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..d6171b01f83cd2d9569baf0cdd33686c1d17d687
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/__init__.py
@@ -0,0 +1,24 @@
+from numba.cuda.testing import ensure_supported_ccs_initialized
+from numba.testing import unittest
+from numba.testing import load_testsuite
+from numba import cuda
+from os.path import dirname, join
+
+
+def load_tests(loader, tests, pattern):
+ suite = unittest.TestSuite()
+ this_dir = dirname(__file__)
+ ensure_supported_ccs_initialized()
+ suite.addTests(load_testsuite(loader, join(this_dir, 'nocuda')))
+ if cuda.is_available():
+ suite.addTests(load_testsuite(loader, join(this_dir, 'cudasim')))
+ gpus = cuda.list_devices()
+ if gpus and gpus[0].compute_capability >= (2, 0):
+ suite.addTests(load_testsuite(loader, join(this_dir, 'cudadrv')))
+ suite.addTests(load_testsuite(loader, join(this_dir, 'cudapy')))
+ suite.addTests(load_testsuite(loader, join(this_dir, 'doc_examples')))
+ else:
+ print("skipped CUDA tests because GPU CC < 2.0")
+ else:
+ print("skipped CUDA tests")
+ return suite
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3f7fc0957162c203c30dc862a1364156cbc9d996
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..d9e7d31af3b99e121a9ae04bc855a6c80cc4594d
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__init__.py
@@ -0,0 +1,8 @@
+from numba.cuda.testing import ensure_supported_ccs_initialized
+from numba.testing import load_testsuite
+import os
+
+
+def load_tests(loader, tests, pattern):
+ ensure_supported_ccs_initialized()
+ return load_testsuite(loader, os.path.dirname(__file__))
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9d69f5719178322744687fb8764a80f8222a1e69
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/test_array_attr.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/test_array_attr.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7b45b227226d841a4e6a978dec42bc9bd01c3503
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/test_array_attr.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/test_context_stack.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/test_context_stack.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..67c1da6d5ed8067dd39a83b2920055802b61e308
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/test_context_stack.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/test_cuda_array_slicing.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/test_cuda_array_slicing.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9c52fcbfab7ddf9686d202267175dbabce54af33
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/test_cuda_array_slicing.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/test_cuda_auto_context.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/test_cuda_auto_context.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..acb4928f820fee8f6865780876ea3bd5fabd63e4
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/test_cuda_auto_context.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/test_cuda_devicerecord.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/test_cuda_devicerecord.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..27ef65bb4554d7c17e542d2abeae5d9ae92856fa
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/test_cuda_devicerecord.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/test_cuda_driver.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/test_cuda_driver.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ac30a4568ea823acadd88e4ecf0936d563338a49
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/test_cuda_driver.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/test_cuda_libraries.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/test_cuda_libraries.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a63dfa9d44cc79c1a9603f41828cf27d785e086f
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/test_cuda_libraries.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/test_cuda_memory.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/test_cuda_memory.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..487807485f6977e17f24a740449dc5106fb288d2
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/test_cuda_memory.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/test_cuda_ndarray.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/test_cuda_ndarray.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7046653aa219991f5ba547aff68a0bef98e45387
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/test_cuda_ndarray.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/test_deallocations.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/test_deallocations.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2881f61312e93bb788f5e688358a28ccfa82beb2
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/test_deallocations.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/test_detect.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/test_detect.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bd57293498773131e466c6dad0e83e3b712a3abd
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/test_detect.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/test_emm_plugins.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/test_emm_plugins.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c76ea66f53cf795b5961484e876910d78745b340
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/test_emm_plugins.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/test_events.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/test_events.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..971bae98102960e8a878d472936131c43ebff83a
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/test_events.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/test_host_alloc.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/test_host_alloc.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..16be0ea9bc87f86139432beee9da9b4e83a85f2a
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/test_host_alloc.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/test_init.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/test_init.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..dc9df3a7f916444f33f445a84fbf7d2cd5b37779
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/test_init.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/test_inline_ptx.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/test_inline_ptx.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..991f4de26dfaaeb7c8de444ba6b9de8adc5d2ac4
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/test_inline_ptx.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/test_is_fp16.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/test_is_fp16.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..acf6ed3aafc598d6da1cf22664d7636a3ab47c2f
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/test_is_fp16.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/test_linker.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/test_linker.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cfc92e0b1a4d2ee6ac93cab82b6cc493075c9f5d
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/test_linker.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/test_managed_alloc.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/test_managed_alloc.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c55df8626f6a94abb0a296ab77990ab7d7afa9f3
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/test_managed_alloc.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/test_mvc.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/test_mvc.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bb1a67bc2ba350ae2b0f70a19a87c96e6380523f
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/test_mvc.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/test_nvvm_driver.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/test_nvvm_driver.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ad12faf914b4088f24c6981246945c89a132ce71
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/test_nvvm_driver.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/test_pinned.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/test_pinned.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b63b613975374c1af22ff2fe97b704facf6d9f01
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/test_pinned.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/test_profiler.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/test_profiler.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5e374e1e18f74337a7ccc0380cb299125bdb703a
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/test_profiler.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/test_ptds.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/test_ptds.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0755af01249f81181d56857c4e0aa5ef762ba03d
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/test_ptds.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/test_reset_device.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/test_reset_device.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d265162d960b17f441d4ee70c746cdb1ed77849d
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/test_reset_device.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/test_runtime.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/test_runtime.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4ff96ff5cdcb6f64646519e037f5e030ccb9f17f
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/test_runtime.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/test_select_device.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/test_select_device.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3f99f5b1838cf31ed9b4b567a7a373bfdd61d5e1
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/test_select_device.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/test_streams.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/test_streams.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0ce48560407972e950b9507e2793138352dfadd0
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/__pycache__/test_streams.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/test_array_attr.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/test_array_attr.py
new file mode 100644
index 0000000000000000000000000000000000000000..32f75c855cc5657ad81a15e805503e6ace650c45
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/test_array_attr.py
@@ -0,0 +1,145 @@
+import numpy as np
+from numba import cuda
+from numba.cuda.testing import unittest, CUDATestCase, skip_on_cudasim
+
+
+class TestArrayAttr(CUDATestCase):
+
+ def test_contigous_2d(self):
+ ary = np.arange(10)
+ cary = ary.reshape(2, 5)
+ fary = np.asfortranarray(cary)
+
+ dcary = cuda.to_device(cary)
+ dfary = cuda.to_device(fary)
+ self.assertTrue(dcary.is_c_contiguous())
+ self.assertTrue(not dfary.is_c_contiguous())
+ self.assertTrue(not dcary.is_f_contiguous())
+ self.assertTrue(dfary.is_f_contiguous())
+
+ def test_contigous_3d(self):
+ ary = np.arange(20)
+ cary = ary.reshape(2, 5, 2)
+ fary = np.asfortranarray(cary)
+
+ dcary = cuda.to_device(cary)
+ dfary = cuda.to_device(fary)
+ self.assertTrue(dcary.is_c_contiguous())
+ self.assertTrue(not dfary.is_c_contiguous())
+ self.assertTrue(not dcary.is_f_contiguous())
+ self.assertTrue(dfary.is_f_contiguous())
+
+ def test_contigous_4d(self):
+ ary = np.arange(60)
+ cary = ary.reshape(2, 5, 2, 3)
+ fary = np.asfortranarray(cary)
+
+ dcary = cuda.to_device(cary)
+ dfary = cuda.to_device(fary)
+ self.assertTrue(dcary.is_c_contiguous())
+ self.assertTrue(not dfary.is_c_contiguous())
+ self.assertTrue(not dcary.is_f_contiguous())
+ self.assertTrue(dfary.is_f_contiguous())
+
+ def test_ravel_1d(self):
+ ary = np.arange(60)
+ dary = cuda.to_device(ary)
+ for order in 'CFA':
+ expect = ary.ravel(order=order)
+ dflat = dary.ravel(order=order)
+ flat = dflat.copy_to_host()
+ self.assertTrue(dary is not dflat) # ravel returns new array
+ self.assertEqual(flat.ndim, 1)
+ self.assertPreciseEqual(expect, flat)
+
+ @skip_on_cudasim('CUDA Array Interface is not supported in the simulator')
+ def test_ravel_stride_1d(self):
+ ary = np.arange(60)
+ dary = cuda.to_device(ary)
+ # No-copy stride device array
+ darystride = dary[::2]
+ dary_data = dary.__cuda_array_interface__['data'][0]
+ ddarystride_data = darystride.__cuda_array_interface__['data'][0]
+ self.assertEqual(dary_data, ddarystride_data)
+ # Fail on ravel on non-contiguous array
+ with self.assertRaises(NotImplementedError):
+ darystride.ravel()
+
+ def test_ravel_c(self):
+ ary = np.arange(60)
+ reshaped = ary.reshape(2, 5, 2, 3)
+
+ expect = reshaped.ravel(order='C')
+ dary = cuda.to_device(reshaped)
+ dflat = dary.ravel()
+ flat = dflat.copy_to_host()
+ self.assertTrue(dary is not dflat)
+ self.assertEqual(flat.ndim, 1)
+ self.assertPreciseEqual(expect, flat)
+
+ # explicit order kwarg
+ for order in 'CA':
+ expect = reshaped.ravel(order=order)
+ dary = cuda.to_device(reshaped)
+ dflat = dary.ravel(order=order)
+ flat = dflat.copy_to_host()
+ self.assertTrue(dary is not dflat)
+ self.assertEqual(flat.ndim, 1)
+ self.assertPreciseEqual(expect, flat)
+
+ @skip_on_cudasim('CUDA Array Interface is not supported in the simulator')
+ def test_ravel_stride_c(self):
+ ary = np.arange(60)
+ reshaped = ary.reshape(2, 5, 2, 3)
+
+ dary = cuda.to_device(reshaped)
+ darystride = dary[::2, ::2, ::2, ::2]
+ dary_data = dary.__cuda_array_interface__['data'][0]
+ ddarystride_data = darystride.__cuda_array_interface__['data'][0]
+ self.assertEqual(dary_data, ddarystride_data)
+ with self.assertRaises(NotImplementedError):
+ darystride.ravel()
+
+ def test_ravel_f(self):
+ ary = np.arange(60)
+ reshaped = np.asfortranarray(ary.reshape(2, 5, 2, 3))
+ for order in 'FA':
+ expect = reshaped.ravel(order=order)
+ dary = cuda.to_device(reshaped)
+ dflat = dary.ravel(order=order)
+ flat = dflat.copy_to_host()
+ self.assertTrue(dary is not dflat)
+ self.assertEqual(flat.ndim, 1)
+ self.assertPreciseEqual(expect, flat)
+
+ @skip_on_cudasim('CUDA Array Interface is not supported in the simulator')
+ def test_ravel_stride_f(self):
+ ary = np.arange(60)
+ reshaped = np.asfortranarray(ary.reshape(2, 5, 2, 3))
+ dary = cuda.to_device(reshaped)
+ darystride = dary[::2, ::2, ::2, ::2]
+ dary_data = dary.__cuda_array_interface__['data'][0]
+ ddarystride_data = darystride.__cuda_array_interface__['data'][0]
+ self.assertEqual(dary_data, ddarystride_data)
+ with self.assertRaises(NotImplementedError):
+ darystride.ravel()
+
+ def test_reshape_c(self):
+ ary = np.arange(10)
+ expect = ary.reshape(2, 5)
+ dary = cuda.to_device(ary)
+ dary_reshaped = dary.reshape(2, 5)
+ got = dary_reshaped.copy_to_host()
+ self.assertPreciseEqual(expect, got)
+
+ def test_reshape_f(self):
+ ary = np.arange(10)
+ expect = ary.reshape(2, 5, order='F')
+ dary = cuda.to_device(ary)
+ dary_reshaped = dary.reshape(2, 5, order='F')
+ got = dary_reshaped.copy_to_host()
+ self.assertPreciseEqual(expect, got)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/test_context_stack.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/test_context_stack.py
new file mode 100644
index 0000000000000000000000000000000000000000..030052507358b4c2e0f1d0c48599cd1db3fc6b4b
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/test_context_stack.py
@@ -0,0 +1,145 @@
+import numbers
+from ctypes import byref
+import weakref
+
+from numba import cuda
+from numba.cuda.testing import unittest, CUDATestCase, skip_on_cudasim
+from numba.cuda.cudadrv import driver
+
+
+class TestContextStack(CUDATestCase):
+ def setUp(self):
+ super().setUp()
+ # Reset before testing
+ cuda.close()
+
+ def test_gpus_current(self):
+ self.assertIs(cuda.gpus.current, None)
+ with cuda.gpus[0]:
+ self.assertEqual(int(cuda.gpus.current.id), 0)
+
+ def test_gpus_len(self):
+ self.assertGreater(len(cuda.gpus), 0)
+
+ def test_gpus_iter(self):
+ gpulist = list(cuda.gpus)
+ self.assertGreater(len(gpulist), 0)
+
+
+class TestContextAPI(CUDATestCase):
+
+ def tearDown(self):
+ super().tearDown()
+ cuda.close()
+
+ def test_context_memory(self):
+ try:
+ mem = cuda.current_context().get_memory_info()
+ except NotImplementedError:
+ self.skipTest('EMM Plugin does not implement get_memory_info()')
+
+ self.assertIsInstance(mem.free, numbers.Number)
+ self.assertEqual(mem.free, mem[0])
+
+ self.assertIsInstance(mem.total, numbers.Number)
+ self.assertEqual(mem.total, mem[1])
+
+ self.assertLessEqual(mem.free, mem.total)
+
+ @unittest.skipIf(len(cuda.gpus) < 2, "need more than 1 gpus")
+ @skip_on_cudasim('CUDA HW required')
+ def test_forbidden_context_switch(self):
+ # Cannot switch context inside a `cuda.require_context`
+ @cuda.require_context
+ def switch_gpu():
+ with cuda.gpus[1]:
+ pass
+
+ with cuda.gpus[0]:
+ with self.assertRaises(RuntimeError) as raises:
+ switch_gpu()
+
+ self.assertIn("Cannot switch CUDA-context.", str(raises.exception))
+
+ @unittest.skipIf(len(cuda.gpus) < 2, "need more than 1 gpus")
+ def test_accepted_context_switch(self):
+ def switch_gpu():
+ with cuda.gpus[1]:
+ return cuda.current_context().device.id
+
+ with cuda.gpus[0]:
+ devid = switch_gpu()
+ self.assertEqual(int(devid), 1)
+
+
+@skip_on_cudasim('CUDA HW required')
+class Test3rdPartyContext(CUDATestCase):
+ def tearDown(self):
+ super().tearDown()
+ cuda.close()
+
+ def test_attached_primary(self, extra_work=lambda: None):
+ # Emulate primary context creation by 3rd party
+ the_driver = driver.driver
+ if driver.USE_NV_BINDING:
+ dev = driver.binding.CUdevice(0)
+ hctx = the_driver.cuDevicePrimaryCtxRetain(dev)
+ else:
+ dev = 0
+ hctx = driver.drvapi.cu_context()
+ the_driver.cuDevicePrimaryCtxRetain(byref(hctx), dev)
+ try:
+ ctx = driver.Context(weakref.proxy(self), hctx)
+ ctx.push()
+ # Check that the context from numba matches the created primary
+ # context.
+ my_ctx = cuda.current_context()
+ if driver.USE_NV_BINDING:
+ self.assertEqual(int(my_ctx.handle), int(ctx.handle))
+ else:
+ self.assertEqual(my_ctx.handle.value, ctx.handle.value)
+
+ extra_work()
+ finally:
+ ctx.pop()
+ the_driver.cuDevicePrimaryCtxRelease(dev)
+
+ def test_attached_non_primary(self):
+ # Emulate non-primary context creation by 3rd party
+ the_driver = driver.driver
+ if driver.USE_NV_BINDING:
+ flags = 0
+ dev = driver.binding.CUdevice(0)
+ hctx = the_driver.cuCtxCreate(flags, dev)
+ else:
+ hctx = driver.drvapi.cu_context()
+ the_driver.cuCtxCreate(byref(hctx), 0, 0)
+ try:
+ cuda.current_context()
+ except RuntimeError as e:
+ # Expecting an error about non-primary CUDA context
+ self.assertIn("Numba cannot operate on non-primary CUDA context ",
+ str(e))
+ else:
+ self.fail("No RuntimeError raised")
+ finally:
+ the_driver.cuCtxDestroy(hctx)
+
+ def test_cudajit_in_attached_primary_context(self):
+ def do():
+ from numba import cuda
+
+ @cuda.jit
+ def foo(a):
+ for i in range(a.size):
+ a[i] = i
+
+ a = cuda.device_array(10)
+ foo[1, 1](a)
+ self.assertEqual(list(a.copy_to_host()), list(range(10)))
+
+ self.test_attached_primary(do)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/test_cuda_array_slicing.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/test_cuda_array_slicing.py
new file mode 100644
index 0000000000000000000000000000000000000000..aad67d14ce6c7406617d965cf29cc42e036e5ae0
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/test_cuda_array_slicing.py
@@ -0,0 +1,376 @@
+from itertools import product
+
+import numpy as np
+
+from numba import cuda
+from numba.cuda.testing import unittest, CUDATestCase, skip_on_cudasim
+from unittest.mock import patch
+
+
+class CudaArrayIndexing(CUDATestCase):
+ def test_index_1d(self):
+ arr = np.arange(10)
+ darr = cuda.to_device(arr)
+ x, = arr.shape
+ for i in range(-x, x):
+ self.assertEqual(arr[i], darr[i])
+ with self.assertRaises(IndexError):
+ darr[-x - 1]
+ with self.assertRaises(IndexError):
+ darr[x]
+
+ def test_index_2d(self):
+ arr = np.arange(3 * 4).reshape(3, 4)
+ darr = cuda.to_device(arr)
+ x, y = arr.shape
+ for i in range(-x, x):
+ for j in range(-y, y):
+ self.assertEqual(arr[i, j], darr[i, j])
+ with self.assertRaises(IndexError):
+ darr[-x - 1, 0]
+ with self.assertRaises(IndexError):
+ darr[x, 0]
+ with self.assertRaises(IndexError):
+ darr[0, -y - 1]
+ with self.assertRaises(IndexError):
+ darr[0, y]
+
+ def test_index_3d(self):
+ arr = np.arange(3 * 4 * 5).reshape(3, 4, 5)
+ darr = cuda.to_device(arr)
+ x, y, z = arr.shape
+ for i in range(-x, x):
+ for j in range(-y, y):
+ for k in range(-z, z):
+ self.assertEqual(arr[i, j, k], darr[i, j, k])
+ with self.assertRaises(IndexError):
+ darr[-x - 1, 0, 0]
+ with self.assertRaises(IndexError):
+ darr[x, 0, 0]
+ with self.assertRaises(IndexError):
+ darr[0, -y - 1, 0]
+ with self.assertRaises(IndexError):
+ darr[0, y, 0]
+ with self.assertRaises(IndexError):
+ darr[0, 0, -z - 1]
+ with self.assertRaises(IndexError):
+ darr[0, 0, z]
+
+
+class CudaArrayStridedSlice(CUDATestCase):
+
+ def test_strided_index_1d(self):
+ arr = np.arange(10)
+ darr = cuda.to_device(arr)
+ for i in range(arr.size):
+ np.testing.assert_equal(arr[i::2], darr[i::2].copy_to_host())
+
+ def test_strided_index_2d(self):
+ arr = np.arange(6 * 7).reshape(6, 7)
+ darr = cuda.to_device(arr)
+
+ for i in range(arr.shape[0]):
+ for j in range(arr.shape[1]):
+ np.testing.assert_equal(arr[i::2, j::2],
+ darr[i::2, j::2].copy_to_host())
+
+ def test_strided_index_3d(self):
+ arr = np.arange(6 * 7 * 8).reshape(6, 7, 8)
+ darr = cuda.to_device(arr)
+
+ for i in range(arr.shape[0]):
+ for j in range(arr.shape[1]):
+ for k in range(arr.shape[2]):
+ np.testing.assert_equal(
+ arr[i::2, j::2, k::2],
+ darr[i::2, j::2, k::2].copy_to_host())
+
+
+class CudaArraySlicing(CUDATestCase):
+ def test_prefix_1d(self):
+ arr = np.arange(5)
+ darr = cuda.to_device(arr)
+ for i in range(arr.size):
+ expect = arr[i:]
+ got = darr[i:].copy_to_host()
+ self.assertTrue(np.all(expect == got))
+
+ def test_prefix_2d(self):
+ arr = np.arange(3 ** 2).reshape(3, 3)
+ darr = cuda.to_device(arr)
+ for i in range(arr.shape[0]):
+ for j in range(arr.shape[1]):
+ expect = arr[i:, j:]
+ sliced = darr[i:, j:]
+ self.assertEqual(expect.shape, sliced.shape)
+ self.assertEqual(expect.strides, sliced.strides)
+ got = sliced.copy_to_host()
+ self.assertTrue(np.all(expect == got))
+
+ def test_select_3d_first_two_dim(self):
+ arr = np.arange(3 * 4 * 5).reshape(3, 4, 5)
+ darr = cuda.to_device(arr)
+ # Select first dimension
+ for i in range(arr.shape[0]):
+ expect = arr[i]
+ sliced = darr[i]
+ self.assertEqual(expect.shape, sliced.shape)
+ self.assertEqual(expect.strides, sliced.strides)
+ got = sliced.copy_to_host()
+ self.assertTrue(np.all(expect == got))
+ # Select second dimension
+ for i in range(arr.shape[0]):
+ for j in range(arr.shape[1]):
+ expect = arr[i, j]
+ sliced = darr[i, j]
+ self.assertEqual(expect.shape, sliced.shape)
+ self.assertEqual(expect.strides, sliced.strides)
+ got = sliced.copy_to_host()
+ self.assertTrue(np.all(expect == got))
+
+ def test_select_f(self):
+ a = np.arange(5 * 6 * 7).reshape(5, 6, 7, order='F')
+ da = cuda.to_device(a)
+
+ for i in range(a.shape[0]):
+ for j in range(a.shape[1]):
+ self.assertTrue(np.array_equal(da[i, j, :].copy_to_host(),
+ a[i, j, :]))
+ for j in range(a.shape[2]):
+ self.assertTrue(np.array_equal(da[i, :, j].copy_to_host(),
+ a[i, :, j]))
+ for i in range(a.shape[1]):
+ for j in range(a.shape[2]):
+ self.assertTrue(np.array_equal(da[:, i, j].copy_to_host(),
+ a[:, i, j]))
+
+ def test_select_c(self):
+ a = np.arange(5 * 6 * 7).reshape(5, 6, 7, order='C')
+ da = cuda.to_device(a)
+
+ for i in range(a.shape[0]):
+ for j in range(a.shape[1]):
+ self.assertTrue(np.array_equal(da[i, j, :].copy_to_host(),
+ a[i, j, :]))
+ for j in range(a.shape[2]):
+ self.assertTrue(np.array_equal(da[i, :, j].copy_to_host(),
+ a[i, :, j]))
+ for i in range(a.shape[1]):
+ for j in range(a.shape[2]):
+ self.assertTrue(np.array_equal(da[:, i, j].copy_to_host(),
+ a[:, i, j]))
+
+ def test_prefix_select(self):
+ arr = np.arange(5 * 7).reshape(5, 7, order='F')
+
+ darr = cuda.to_device(arr)
+ self.assertTrue(np.all(darr[:1, 1].copy_to_host() == arr[:1, 1]))
+
+ def test_negative_slicing_1d(self):
+ arr = np.arange(10)
+ darr = cuda.to_device(arr)
+ for i, j in product(range(-10, 10), repeat=2):
+ np.testing.assert_array_equal(arr[i:j],
+ darr[i:j].copy_to_host())
+
+ def test_negative_slicing_2d(self):
+ arr = np.arange(12).reshape(3, 4)
+ darr = cuda.to_device(arr)
+ for x, y, w, s in product(range(-4, 4), repeat=4):
+ np.testing.assert_array_equal(arr[x:y, w:s],
+ darr[x:y, w:s].copy_to_host())
+
+ def test_empty_slice_1d(self):
+ arr = np.arange(5)
+ darr = cuda.to_device(arr)
+ for i in range(darr.shape[0]):
+ np.testing.assert_array_equal(darr[i:i].copy_to_host(), arr[i:i])
+ # empty slice of empty slice
+ np.testing.assert_array_equal(darr[:0][:0].copy_to_host(), np.empty(0))
+ # out-of-bound slice just produces empty slices
+ np.testing.assert_array_equal(darr[:0][:1].copy_to_host(),
+ arr[:0][:1])
+ np.testing.assert_array_equal(darr[:0][-1:].copy_to_host(),
+ arr[:0][-1:])
+
+ def test_empty_slice_2d(self):
+ arr = np.arange(5 * 7).reshape(5, 7)
+ darr = cuda.to_device(arr)
+ np.testing.assert_array_equal(darr[:0].copy_to_host(), arr[:0])
+ np.testing.assert_array_equal(darr[3, :0].copy_to_host(), arr[3, :0])
+ # empty slice of empty slice
+ np.testing.assert_array_equal(darr[:0][:0].copy_to_host(),
+ np.empty((0, 7)))
+ # out-of-bound slice just produces empty slices
+ np.testing.assert_array_equal(darr[:0][:1].copy_to_host(), arr[:0][:1])
+ np.testing.assert_array_equal(darr[:0][-1:].copy_to_host(),
+ arr[:0][-1:])
+
+
+class CudaArraySetting(CUDATestCase):
+ """
+ Most of the slicing logic is tested in the cases above, so these
+ tests focus on the setting logic.
+ """
+
+ def test_scalar(self):
+ arr = np.arange(5 * 7).reshape(5, 7)
+ darr = cuda.to_device(arr)
+ arr[2, 2] = 500
+ darr[2, 2] = 500
+ np.testing.assert_array_equal(darr.copy_to_host(), arr)
+
+ def test_rank(self):
+ arr = np.arange(5 * 7).reshape(5, 7)
+ darr = cuda.to_device(arr)
+ arr[2] = 500
+ darr[2] = 500
+ np.testing.assert_array_equal(darr.copy_to_host(), arr)
+
+ def test_broadcast(self):
+ arr = np.arange(5 * 7).reshape(5, 7)
+ darr = cuda.to_device(arr)
+ arr[:, 2] = 500
+ darr[:, 2] = 500
+ np.testing.assert_array_equal(darr.copy_to_host(), arr)
+
+ def test_array_assign_column(self):
+ arr = np.arange(5 * 7).reshape(5, 7)
+ darr = cuda.to_device(arr)
+ _400 = np.full(shape=7, fill_value=400)
+ arr[2] = _400
+ darr[2] = _400
+ np.testing.assert_array_equal(darr.copy_to_host(), arr)
+
+ def test_array_assign_row(self):
+ arr = np.arange(5 * 7).reshape(5, 7)
+ darr = cuda.to_device(arr)
+ _400 = np.full(shape=5, fill_value=400)
+ arr[:, 2] = _400
+ darr[:, 2] = _400
+ np.testing.assert_array_equal(darr.copy_to_host(), arr)
+
+ def test_array_assign_subarray(self):
+ arr = np.arange(5 * 6 * 7).reshape(5, 6, 7)
+ darr = cuda.to_device(arr)
+ _400 = np.full(shape=(6, 7), fill_value=400)
+ arr[2] = _400
+ darr[2] = _400
+ np.testing.assert_array_equal(darr.copy_to_host(), arr)
+
+ def test_array_assign_deep_subarray(self):
+ arr = np.arange(5 * 6 * 7 * 8).reshape(5, 6, 7, 8)
+ darr = cuda.to_device(arr)
+ _400 = np.full(shape=(5, 6, 8), fill_value=400)
+ arr[:, :, 2] = _400
+ darr[:, :, 2] = _400
+ np.testing.assert_array_equal(darr.copy_to_host(), arr)
+
+ def test_array_assign_all(self):
+ arr = np.arange(5 * 7).reshape(5, 7)
+ darr = cuda.to_device(arr)
+ _400 = np.full(shape=(5, 7), fill_value=400)
+ arr[:] = _400
+ darr[:] = _400
+ np.testing.assert_array_equal(darr.copy_to_host(), arr)
+
+ def test_strides(self):
+ arr = np.ones(20)
+ darr = cuda.to_device(arr)
+ arr[::2] = 500
+ darr[::2] = 500
+ np.testing.assert_array_equal(darr.copy_to_host(), arr)
+
+ def test_incompatible_highdim(self):
+ darr = cuda.to_device(np.arange(5 * 7))
+
+ with self.assertRaises(ValueError) as e:
+ darr[:] = np.ones(shape=(1, 2, 3))
+
+ self.assertIn(
+ member=str(e.exception),
+ container=[
+ "Can't assign 3-D array to 1-D self", # device
+ "could not broadcast input array from shape (2,3) "
+ "into shape (35,)", # simulator, NP >= 1.20
+ ])
+
+ def test_incompatible_shape(self):
+ darr = cuda.to_device(np.arange(5))
+
+ with self.assertRaises(ValueError) as e:
+ darr[:] = [1, 3]
+
+ self.assertIn(
+ member=str(e.exception),
+ container=[
+ "Can't copy sequence with size 2 to array axis 0 with "
+ "dimension 5", # device
+ "could not broadcast input array from shape (2,) into "
+ "shape (5,)", # simulator, NP >= 1.20
+ ])
+
+ @skip_on_cudasim('cudasim does not use streams and operates synchronously')
+ def test_sync(self):
+ # There should be a synchronization when no stream is supplied
+ darr = cuda.to_device(np.arange(5))
+
+ with patch.object(cuda.cudadrv.driver.Stream, 'synchronize',
+ return_value=None) as mock_sync:
+ darr[0] = 10
+
+ mock_sync.assert_called_once()
+
+ @skip_on_cudasim('cudasim does not use streams and operates synchronously')
+ def test_no_sync_default_stream(self):
+ # There should not be a synchronization when the array has a default
+ # stream, whether it is the default stream, the legacy default stream,
+ # the per-thread default stream, or another stream.
+ streams = (cuda.stream(), cuda.default_stream(),
+ cuda.legacy_default_stream(),
+ cuda.per_thread_default_stream())
+
+ for stream in streams:
+ darr = cuda.to_device(np.arange(5), stream=stream)
+
+ with patch.object(cuda.cudadrv.driver.Stream, 'synchronize',
+ return_value=None) as mock_sync:
+ darr[0] = 10
+
+ mock_sync.assert_not_called()
+
+ @skip_on_cudasim('cudasim does not use streams and operates synchronously')
+ def test_no_sync_supplied_stream(self):
+ # There should not be a synchronization when a stream is supplied for
+ # the setitem call, whether it is the default stream, the legacy default
+ # stream, the per-thread default stream, or another stream.
+ streams = (cuda.stream(), cuda.default_stream(),
+ cuda.legacy_default_stream(),
+ cuda.per_thread_default_stream())
+
+ for stream in streams:
+ darr = cuda.to_device(np.arange(5))
+
+ with patch.object(cuda.cudadrv.driver.Stream, 'synchronize',
+ return_value=None) as mock_sync:
+ darr.setitem(0, 10, stream=stream)
+
+ mock_sync.assert_not_called()
+
+ @unittest.skip('Requires PR #6367')
+ def test_issue_6505(self):
+ # On Windows, the writes to ary_v would not be visible prior to the
+ # assertion, due to the assignment being done with a kernel launch that
+ # returns asynchronously - there should now be a sync after the kernel
+ # launch to ensure that the writes are always visible.
+ ary = cuda.mapped_array(2, dtype=np.int32)
+ ary[:] = 0
+
+ ary_v = ary.view('u1')
+ ary_v[1] = 1
+ ary_v[5] = 1
+ self.assertEqual(sum(ary), 512)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/test_cuda_auto_context.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/test_cuda_auto_context.py
new file mode 100644
index 0000000000000000000000000000000000000000..4a4d59310dd34b36a1d8bd473a8f5e5d7eda5d93
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/test_cuda_auto_context.py
@@ -0,0 +1,21 @@
+import numpy as np
+from numba import cuda
+from numba.cuda.testing import unittest, CUDATestCase
+
+
+class TestCudaAutoContext(CUDATestCase):
+ def test_auto_context(self):
+ """A problem was revealed by a customer that the use cuda.to_device
+ does not create a CUDA context.
+ This tests the problem
+ """
+ A = np.arange(10, dtype=np.float32)
+ newA = np.empty_like(A)
+ dA = cuda.to_device(A)
+
+ dA.copy_to_host(newA)
+ self.assertTrue(np.allclose(A, newA))
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/test_cuda_devicerecord.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/test_cuda_devicerecord.py
new file mode 100644
index 0000000000000000000000000000000000000000..e2acd34d7eca1dcc1efe48b38089c50bbeade0e7
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/test_cuda_devicerecord.py
@@ -0,0 +1,179 @@
+import numpy as np
+import ctypes
+from numba.cuda.cudadrv.devicearray import (DeviceRecord, from_record_like,
+ auto_device)
+from numba.cuda.testing import unittest, CUDATestCase
+from numba.cuda.testing import skip_on_cudasim
+from numba.np import numpy_support
+from numba import cuda
+
+N_CHARS = 5
+
+recordtype = np.dtype(
+ [
+ ('a', np.float64),
+ ('b', np.int32),
+ ('c', np.complex64),
+ ('d', (np.str_, N_CHARS))
+ ],
+ align=True
+)
+
+recordwitharray = np.dtype(
+ [
+ ('g', np.int32),
+ ('h', np.float32, 2)
+ ],
+ align=True
+)
+
+recwithmat = np.dtype([('i', np.int32),
+ ('j', np.float32, (3, 3))])
+
+recwithrecwithmat = np.dtype([('x', np.int32), ('y', recwithmat)])
+
+
+@skip_on_cudasim('Device Record API unsupported in the simulator')
+class TestCudaDeviceRecord(CUDATestCase):
+ """
+ Tests the DeviceRecord class with np.void host types.
+ """
+ def setUp(self):
+ super().setUp()
+ self._create_data(np.zeros)
+
+ def _create_data(self, array_ctor):
+ self.dtype = np.dtype([('a', np.int32), ('b', np.float32)], align=True)
+ self.hostz = array_ctor(1, self.dtype)[0]
+ self.hostnz = array_ctor(1, self.dtype)[0]
+ self.hostnz['a'] = 10
+ self.hostnz['b'] = 11.0
+
+ def _check_device_record(self, reference, rec):
+ self.assertEqual(rec.shape, tuple())
+ self.assertEqual(rec.strides, tuple())
+ self.assertEqual(rec.dtype, reference.dtype)
+ self.assertEqual(rec.alloc_size, reference.dtype.itemsize)
+ self.assertIsNotNone(rec.gpu_data)
+ self.assertNotEqual(rec.device_ctypes_pointer, ctypes.c_void_p(0))
+
+ numba_type = numpy_support.from_dtype(reference.dtype)
+ self.assertEqual(rec._numba_type_, numba_type)
+
+ def test_device_record_interface(self):
+ hostrec = self.hostz.copy()
+ devrec = DeviceRecord(self.dtype)
+ self._check_device_record(hostrec, devrec)
+
+ def test_device_record_copy(self):
+ hostrec = self.hostz.copy()
+ devrec = DeviceRecord(self.dtype)
+ devrec.copy_to_device(hostrec)
+
+ # Copy back and check values are all zeros
+ hostrec2 = self.hostnz.copy()
+ devrec.copy_to_host(hostrec2)
+ np.testing.assert_equal(self.hostz, hostrec2)
+
+ # Copy non-zero values to GPU and back and check values
+ hostrec3 = self.hostnz.copy()
+ devrec.copy_to_device(hostrec3)
+
+ hostrec4 = self.hostz.copy()
+ devrec.copy_to_host(hostrec4)
+ np.testing.assert_equal(hostrec4, self.hostnz)
+
+ def test_from_record_like(self):
+ # Create record from host record
+ hostrec = self.hostz.copy()
+ devrec = from_record_like(hostrec)
+ self._check_device_record(hostrec, devrec)
+
+ # Create record from device record and check for distinct data
+ devrec2 = from_record_like(devrec)
+ self._check_device_record(devrec, devrec2)
+ self.assertNotEqual(devrec.gpu_data, devrec2.gpu_data)
+
+ def test_auto_device(self):
+ # Create record from host record
+ hostrec = self.hostnz.copy()
+ devrec, new_gpu_obj = auto_device(hostrec)
+ self._check_device_record(hostrec, devrec)
+ self.assertTrue(new_gpu_obj)
+
+ # Copy data back and check it is equal to auto_device arg
+ hostrec2 = self.hostz.copy()
+ devrec.copy_to_host(hostrec2)
+ np.testing.assert_equal(hostrec2, hostrec)
+
+
+class TestCudaDeviceRecordWithRecord(TestCudaDeviceRecord):
+ """
+ Tests the DeviceRecord class with np.record host types
+ """
+ def setUp(self):
+ CUDATestCase.setUp(self)
+ self._create_data(np.recarray)
+
+
+@skip_on_cudasim('Structured array attr access not supported in simulator')
+class TestRecordDtypeWithStructArrays(CUDATestCase):
+ '''
+ Test operation of device arrays on structured arrays.
+ '''
+
+ def _createSampleArrays(self):
+ self.sample1d = cuda.device_array(3, dtype=recordtype)
+ self.samplerec1darr = cuda.device_array(1, dtype=recordwitharray)[0]
+ self.samplerecmat = cuda.device_array(1,dtype=recwithmat)[0]
+
+ def setUp(self):
+ super().setUp()
+ self._createSampleArrays()
+
+ ary = self.sample1d
+ for i in range(ary.size):
+ x = i + 1
+ ary[i]['a'] = x / 2
+ ary[i]['b'] = x
+ ary[i]['c'] = x * 1j
+ ary[i]['d'] = str(x) * N_CHARS
+
+ def test_structured_array1(self):
+ ary = self.sample1d
+ for i in range(self.sample1d.size):
+ x = i + 1
+ self.assertEqual(ary[i]['a'], x / 2)
+ self.assertEqual(ary[i]['b'], x)
+ self.assertEqual(ary[i]['c'], x * 1j)
+ self.assertEqual(ary[i]['d'], str(x) * N_CHARS)
+
+ def test_structured_array2(self):
+ ary = self.samplerec1darr
+ ary['g'] = 2
+ ary['h'][0] = 3.0
+ ary['h'][1] = 4.0
+ self.assertEqual(ary['g'], 2)
+ self.assertEqual(ary['h'][0], 3.0)
+ self.assertEqual(ary['h'][1], 4.0)
+
+ def test_structured_array3(self):
+ ary = self.samplerecmat
+ mat = np.array([[5.0, 10.0, 15.0],
+ [20.0, 25.0, 30.0],
+ [35.0, 40.0, 45.0]],
+ dtype=np.float32).reshape(3,3)
+ ary['j'][:] = mat
+ np.testing.assert_equal(ary['j'], mat)
+
+ def test_structured_array4(self):
+ arr = np.zeros(1, dtype=recwithrecwithmat)
+ d_arr = cuda.to_device(arr)
+ d_arr[0]['y']['i'] = 1
+ self.assertEqual(d_arr[0]['y']['i'], 1)
+ d_arr[0]['y']['j'][0, 0] = 2.0
+ self.assertEqual(d_arr[0]['y']['j'][0, 0], 2.0)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/test_cuda_driver.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/test_cuda_driver.py
new file mode 100644
index 0000000000000000000000000000000000000000..ea9d72fa89cefa739be556061f19e26f680cbba7
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/test_cuda_driver.py
@@ -0,0 +1,235 @@
+from ctypes import byref, c_int, c_void_p, sizeof
+
+from numba.cuda.cudadrv.driver import (host_to_device, device_to_host, driver,
+ launch_kernel)
+from numba.cuda.cudadrv import devices, drvapi, driver as _driver
+from numba.cuda.testing import unittest, CUDATestCase
+from numba.cuda.testing import skip_on_cudasim
+
+
+ptx1 = '''
+ .version 1.4
+ .target sm_10, map_f64_to_f32
+
+ .entry _Z10helloworldPi (
+ .param .u64 __cudaparm__Z10helloworldPi_A)
+ {
+ .reg .u32 %r<3>;
+ .reg .u64 %rd<6>;
+ .loc 14 4 0
+$LDWbegin__Z10helloworldPi:
+ .loc 14 6 0
+ cvt.s32.u16 %r1, %tid.x;
+ ld.param.u64 %rd1, [__cudaparm__Z10helloworldPi_A];
+ cvt.u64.u16 %rd2, %tid.x;
+ mul.lo.u64 %rd3, %rd2, 4;
+ add.u64 %rd4, %rd1, %rd3;
+ st.global.s32 [%rd4+0], %r1;
+ .loc 14 7 0
+ exit;
+$LDWend__Z10helloworldPi:
+ } // _Z10helloworldPi
+'''
+
+ptx2 = '''
+.version 3.0
+.target sm_20
+.address_size 64
+
+ .file 1 "/tmp/tmpxft_000012c7_00000000-9_testcuda.cpp3.i"
+ .file 2 "testcuda.cu"
+
+.entry _Z10helloworldPi(
+ .param .u64 _Z10helloworldPi_param_0
+)
+{
+ .reg .s32 %r<3>;
+ .reg .s64 %rl<5>;
+
+
+ ld.param.u64 %rl1, [_Z10helloworldPi_param_0];
+ cvta.to.global.u64 %rl2, %rl1;
+ .loc 2 6 1
+ mov.u32 %r1, %tid.x;
+ mul.wide.u32 %rl3, %r1, 4;
+ add.s64 %rl4, %rl2, %rl3;
+ st.global.u32 [%rl4], %r1;
+ .loc 2 7 2
+ ret;
+}
+'''
+
+
+@skip_on_cudasim('CUDA Driver API unsupported in the simulator')
+class TestCudaDriver(CUDATestCase):
+ def setUp(self):
+ super().setUp()
+ self.assertTrue(len(devices.gpus) > 0)
+ self.context = devices.get_context()
+ device = self.context.device
+ ccmajor, _ = device.compute_capability
+ if ccmajor >= 2:
+ self.ptx = ptx2
+ else:
+ self.ptx = ptx1
+
+ def tearDown(self):
+ super().tearDown()
+ del self.context
+
+ def test_cuda_driver_basic(self):
+ module = self.context.create_module_ptx(self.ptx)
+ function = module.get_function('_Z10helloworldPi')
+
+ array = (c_int * 100)()
+
+ memory = self.context.memalloc(sizeof(array))
+ host_to_device(memory, array, sizeof(array))
+
+ ptr = memory.device_ctypes_pointer
+ stream = 0
+
+ if _driver.USE_NV_BINDING:
+ ptr = c_void_p(int(ptr))
+ stream = _driver.binding.CUstream(stream)
+
+ launch_kernel(function.handle, # Kernel
+ 1, 1, 1, # gx, gy, gz
+ 100, 1, 1, # bx, by, bz
+ 0, # dynamic shared mem
+ stream, # stream
+ [ptr]) # arguments
+
+ device_to_host(array, memory, sizeof(array))
+ for i, v in enumerate(array):
+ self.assertEqual(i, v)
+
+ module.unload()
+
+ def test_cuda_driver_stream_operations(self):
+ module = self.context.create_module_ptx(self.ptx)
+ function = module.get_function('_Z10helloworldPi')
+
+ array = (c_int * 100)()
+
+ stream = self.context.create_stream()
+
+ with stream.auto_synchronize():
+ memory = self.context.memalloc(sizeof(array))
+ host_to_device(memory, array, sizeof(array), stream=stream)
+
+ ptr = memory.device_ctypes_pointer
+ if _driver.USE_NV_BINDING:
+ ptr = c_void_p(int(ptr))
+
+ launch_kernel(function.handle, # Kernel
+ 1, 1, 1, # gx, gy, gz
+ 100, 1, 1, # bx, by, bz
+ 0, # dynamic shared mem
+ stream.handle, # stream
+ [ptr]) # arguments
+
+ device_to_host(array, memory, sizeof(array), stream=stream)
+
+ for i, v in enumerate(array):
+ self.assertEqual(i, v)
+
+ def test_cuda_driver_default_stream(self):
+ # Test properties of the default stream
+ ds = self.context.get_default_stream()
+ self.assertIn("Default CUDA stream", repr(ds))
+ self.assertEqual(0, int(ds))
+ # bool(stream) is the check that is done in memcpy to decide if async
+ # version should be used. So the default (0) stream should be true-ish
+ # even though 0 is usually false-ish in Python.
+ self.assertTrue(ds)
+ self.assertFalse(ds.external)
+
+ def test_cuda_driver_legacy_default_stream(self):
+ # Test properties of the legacy default stream
+ ds = self.context.get_legacy_default_stream()
+ self.assertIn("Legacy default CUDA stream", repr(ds))
+ self.assertEqual(1, int(ds))
+ self.assertTrue(ds)
+ self.assertFalse(ds.external)
+
+ def test_cuda_driver_per_thread_default_stream(self):
+ # Test properties of the per-thread default stream
+ ds = self.context.get_per_thread_default_stream()
+ self.assertIn("Per-thread default CUDA stream", repr(ds))
+ self.assertEqual(2, int(ds))
+ self.assertTrue(ds)
+ self.assertFalse(ds.external)
+
+ def test_cuda_driver_stream(self):
+ # Test properties of non-default streams
+ s = self.context.create_stream()
+ self.assertIn("CUDA stream", repr(s))
+ self.assertNotIn("Default", repr(s))
+ self.assertNotIn("External", repr(s))
+ self.assertNotEqual(0, int(s))
+ self.assertTrue(s)
+ self.assertFalse(s.external)
+
+ def test_cuda_driver_external_stream(self):
+ # Test properties of a stream created from an external stream object.
+ # We use the driver API directly to create a stream, to emulate an
+ # external library creating a stream
+ if _driver.USE_NV_BINDING:
+ handle = driver.cuStreamCreate(0)
+ ptr = int(handle)
+ else:
+ handle = drvapi.cu_stream()
+ driver.cuStreamCreate(byref(handle), 0)
+ ptr = handle.value
+ s = self.context.create_external_stream(ptr)
+
+ self.assertIn("External CUDA stream", repr(s))
+ # Ensure neither "Default" nor "default"
+ self.assertNotIn("efault", repr(s))
+ self.assertEqual(ptr, int(s))
+ self.assertTrue(s)
+ self.assertTrue(s.external)
+
+ def test_cuda_driver_occupancy(self):
+ module = self.context.create_module_ptx(self.ptx)
+ function = module.get_function('_Z10helloworldPi')
+
+ value = self.context.get_active_blocks_per_multiprocessor(function,
+ 128, 128)
+ self.assertTrue(value > 0)
+
+ def b2d(bs):
+ return bs
+
+ grid, block = self.context.get_max_potential_block_size(function, b2d,
+ 128, 128)
+ self.assertTrue(grid > 0)
+ self.assertTrue(block > 0)
+
+
+class TestDevice(CUDATestCase):
+ def test_device_get_uuid(self):
+ # A device UUID looks like:
+ #
+ # GPU-e6489c45-5b68-3b03-bab7-0e7c8e809643
+ #
+ # To test, we construct an RE that matches this form and verify that
+ # the returned UUID matches.
+ #
+ # Device UUIDs may not conform to parts of the UUID specification (RFC
+ # 4122) pertaining to versions and variants, so we do not extract and
+ # validate the values of these bits.
+
+ h = '[0-9a-f]{%d}'
+ h4 = h % 4
+ h8 = h % 8
+ h12 = h % 12
+ uuid_format = f'^GPU-{h8}-{h4}-{h4}-{h4}-{h12}$'
+
+ dev = devices.get_context().device
+ self.assertRegex(dev.uuid, uuid_format)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/test_cuda_libraries.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/test_cuda_libraries.py
new file mode 100644
index 0000000000000000000000000000000000000000..890bf68293565a24d0f36a56a613ea7a126d202e
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/test_cuda_libraries.py
@@ -0,0 +1,22 @@
+from numba.cuda.testing import unittest
+from numba.cuda.testing import skip_on_cudasim, skip_unless_conda_cudatoolkit
+from numba.misc.findlib import find_lib
+
+
+@skip_on_cudasim('Library detection unsupported in the simulator')
+@skip_unless_conda_cudatoolkit
+class TestLibraryDetection(unittest.TestCase):
+ def test_detect(self):
+ """
+ This test is solely present to ensure that shipped cudatoolkits have
+ additional core libraries in locations that Numba scans by default.
+ PyCulib (and potentially others) rely on Numba's library finding
+ capacity to find and subsequently load these libraries.
+ """
+ core_libs = ['nvvm']
+ for l in core_libs:
+ self.assertNotEqual(find_lib(l), [])
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/test_cuda_memory.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/test_cuda_memory.py
new file mode 100644
index 0000000000000000000000000000000000000000..6402f77730cc841f3d622974caf2db9f7db61a7e
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/test_cuda_memory.py
@@ -0,0 +1,193 @@
+import ctypes
+
+import numpy as np
+
+from numba.cuda.cudadrv import driver, drvapi, devices
+from numba.cuda.testing import unittest, ContextResettingTestCase
+from numba.cuda.testing import skip_on_cudasim
+
+
+@skip_on_cudasim('CUDA Memory API unsupported in the simulator')
+class TestCudaMemory(ContextResettingTestCase):
+ def setUp(self):
+ super().setUp()
+ self.context = devices.get_context()
+
+ def tearDown(self):
+ del self.context
+ super(TestCudaMemory, self).tearDown()
+
+ def _template(self, obj):
+ self.assertTrue(driver.is_device_memory(obj))
+ driver.require_device_memory(obj)
+ if driver.USE_NV_BINDING:
+ expected_class = driver.binding.CUdeviceptr
+ else:
+ expected_class = drvapi.cu_device_ptr
+ self.assertTrue(isinstance(obj.device_ctypes_pointer,
+ expected_class))
+
+ def test_device_memory(self):
+ devmem = self.context.memalloc(1024)
+ self._template(devmem)
+
+ def test_device_view(self):
+ devmem = self.context.memalloc(1024)
+ self._template(devmem.view(10))
+
+ def test_host_alloc(self):
+ devmem = self.context.memhostalloc(1024, mapped=True)
+ self._template(devmem)
+
+ def test_pinned_memory(self):
+ ary = np.arange(10)
+ devmem = self.context.mempin(ary, ary.ctypes.data,
+ ary.size * ary.dtype.itemsize,
+ mapped=True)
+ self._template(devmem)
+
+ def test_managed_memory(self):
+ devmem = self.context.memallocmanaged(1024)
+ self._template(devmem)
+
+ def test_derived_pointer(self):
+ # Use MemoryPointer.view to create derived pointer
+
+ def handle_val(mem):
+ if driver.USE_NV_BINDING:
+ return int(mem.handle)
+ else:
+ return mem.handle.value
+
+ def check(m, offset):
+ # create view
+ v1 = m.view(offset)
+ self.assertEqual(handle_val(v1.owner), handle_val(m))
+ self.assertEqual(m.refct, 2)
+ self.assertEqual(handle_val(v1) - offset, handle_val(v1.owner))
+ # create a view
+ v2 = v1.view(offset)
+ self.assertEqual(handle_val(v2.owner), handle_val(m))
+ self.assertEqual(handle_val(v2.owner), handle_val(m))
+ self.assertEqual(handle_val(v2) - offset * 2,
+ handle_val(v2.owner))
+ self.assertEqual(m.refct, 3)
+ del v2
+ self.assertEqual(m.refct, 2)
+ del v1
+ self.assertEqual(m.refct, 1)
+
+ m = self.context.memalloc(1024)
+ check(m=m, offset=0)
+ check(m=m, offset=1)
+
+ def test_user_extension(self):
+ # User can use MemoryPointer to wrap externally defined pointers.
+ # This test checks if the finalizer is invokded at correct time
+ fake_ptr = ctypes.c_void_p(0xdeadbeef)
+ dtor_invoked = [0]
+
+ def dtor():
+ dtor_invoked[0] += 1
+
+ # Ensure finalizer is called when pointer is deleted
+ ptr = driver.MemoryPointer(context=self.context, pointer=fake_ptr,
+ size=40, finalizer=dtor)
+ self.assertEqual(dtor_invoked[0], 0)
+ del ptr
+ self.assertEqual(dtor_invoked[0], 1)
+
+ # Ensure removing derived pointer doesn't call finalizer
+ ptr = driver.MemoryPointer(context=self.context, pointer=fake_ptr,
+ size=40, finalizer=dtor)
+ owned = ptr.own()
+ del owned
+ self.assertEqual(dtor_invoked[0], 1)
+ del ptr
+ self.assertEqual(dtor_invoked[0], 2)
+
+
+class TestCudaMemoryFunctions(ContextResettingTestCase):
+ def setUp(self):
+ super().setUp()
+ self.context = devices.get_context()
+
+ def tearDown(self):
+ del self.context
+ super(TestCudaMemoryFunctions, self).tearDown()
+
+ def test_memcpy(self):
+ hstary = np.arange(100, dtype=np.uint32)
+ hstary2 = np.arange(100, dtype=np.uint32)
+ sz = hstary.size * hstary.dtype.itemsize
+ devary = self.context.memalloc(sz)
+
+ driver.host_to_device(devary, hstary, sz)
+ driver.device_to_host(hstary2, devary, sz)
+
+ self.assertTrue(np.all(hstary == hstary2))
+
+ def test_memset(self):
+ dtype = np.dtype('uint32')
+ n = 10
+ sz = dtype.itemsize * 10
+ devary = self.context.memalloc(sz)
+ driver.device_memset(devary, 0xab, sz)
+
+ hstary = np.empty(n, dtype=dtype)
+ driver.device_to_host(hstary, devary, sz)
+
+ hstary2 = np.array([0xabababab] * n, dtype=np.dtype('uint32'))
+ self.assertTrue(np.all(hstary == hstary2))
+
+ def test_d2d(self):
+ hst = np.arange(100, dtype=np.uint32)
+ hst2 = np.empty_like(hst)
+ sz = hst.size * hst.dtype.itemsize
+ dev1 = self.context.memalloc(sz)
+ dev2 = self.context.memalloc(sz)
+ driver.host_to_device(dev1, hst, sz)
+ driver.device_to_device(dev2, dev1, sz)
+ driver.device_to_host(hst2, dev2, sz)
+ self.assertTrue(np.all(hst == hst2))
+
+
+@skip_on_cudasim('CUDA Memory API unsupported in the simulator')
+class TestMVExtent(ContextResettingTestCase):
+ def test_c_contiguous_array(self):
+ ary = np.arange(100)
+ arysz = ary.dtype.itemsize * ary.size
+ s, e = driver.host_memory_extents(ary)
+ self.assertTrue(ary.ctypes.data == s)
+ self.assertTrue(arysz == driver.host_memory_size(ary))
+
+ def test_f_contiguous_array(self):
+ ary = np.asfortranarray(np.arange(100).reshape(2, 50))
+ arysz = ary.dtype.itemsize * np.prod(ary.shape)
+ s, e = driver.host_memory_extents(ary)
+ self.assertTrue(ary.ctypes.data == s)
+ self.assertTrue(arysz == driver.host_memory_size(ary))
+
+ def test_single_element_array(self):
+ ary = np.asarray(np.uint32(1234))
+ arysz = ary.dtype.itemsize
+ s, e = driver.host_memory_extents(ary)
+ self.assertTrue(ary.ctypes.data == s)
+ self.assertTrue(arysz == driver.host_memory_size(ary))
+
+ def test_ctypes_struct(self):
+ class mystruct(ctypes.Structure):
+ _fields_ = [('x', ctypes.c_int), ('y', ctypes.c_int)]
+
+ data = mystruct(x=123, y=432)
+ sz = driver.host_memory_size(data)
+ self.assertTrue(ctypes.sizeof(data) == sz)
+
+ def test_ctypes_double(self):
+ data = ctypes.c_double(1.234)
+ sz = driver.host_memory_size(data)
+ self.assertTrue(ctypes.sizeof(data) == sz)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/test_cuda_ndarray.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/test_cuda_ndarray.py
new file mode 100644
index 0000000000000000000000000000000000000000..1c9c9195eb4b63eaa6b6764657f2f127be8b9b88
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/test_cuda_ndarray.py
@@ -0,0 +1,547 @@
+import itertools
+import numpy as np
+from numba.cuda.cudadrv import devicearray
+from numba import cuda
+from numba.cuda.testing import unittest, CUDATestCase
+from numba.cuda.testing import skip_on_cudasim
+
+
+class TestCudaNDArray(CUDATestCase):
+ def test_device_array_interface(self):
+ dary = cuda.device_array(shape=100)
+ devicearray.verify_cuda_ndarray_interface(dary)
+
+ ary = np.empty(100)
+ dary = cuda.to_device(ary)
+ devicearray.verify_cuda_ndarray_interface(dary)
+
+ ary = np.asarray(1.234)
+ dary = cuda.to_device(ary)
+ self.assertEqual(dary.ndim, 0)
+ devicearray.verify_cuda_ndarray_interface(dary)
+
+ def test_device_array_from_readonly(self):
+ ary = np.arange(100, dtype=np.float32)
+ # Make the array readonly
+ ary.flags.writeable = False
+ self.assertFalse(ary.flags.writeable)
+ # Ensure that we can copy the readonly array
+ dary = cuda.to_device(ary)
+ retr = dary.copy_to_host()
+ np.testing.assert_array_equal(retr, ary)
+
+ def test_devicearray_dtype(self):
+ dary = cuda.device_array(shape=(100,), dtype="f4")
+ self.assertEqual(dary.dtype, np.dtype("f4"))
+
+ def test_devicearray_no_copy(self):
+ array = np.arange(100, dtype=np.float32)
+ cuda.to_device(array, copy=False)
+
+ def test_devicearray_shape(self):
+ ary = np.arange(2 * 3 * 4).reshape(2, 3, 4)
+ dary = cuda.to_device(ary)
+ self.assertEqual(ary.shape, dary.shape)
+ self.assertEqual(ary.shape[1:], dary.shape[1:])
+
+ def test_devicearray(self):
+ array = np.arange(100, dtype=np.int32)
+ original = array.copy()
+ gpumem = cuda.to_device(array)
+ array[:] = 0
+ gpumem.copy_to_host(array)
+
+ np.testing.assert_array_equal(array, original)
+
+ def test_stream_bind(self):
+ stream = cuda.stream()
+ with stream.auto_synchronize():
+ arr = cuda.device_array(
+ (3, 3),
+ dtype=np.float64,
+ stream=stream)
+ self.assertEqual(arr.bind(stream).stream, stream)
+ self.assertEqual(arr.stream, stream)
+
+ def test_len_1d(self):
+ ary = np.empty((3,))
+ dary = cuda.device_array(3)
+ self.assertEqual(len(ary), len(dary))
+
+ def test_len_2d(self):
+ ary = np.empty((3, 5))
+ dary = cuda.device_array((3, 5))
+ self.assertEqual(len(ary), len(dary))
+
+ def test_len_3d(self):
+ ary = np.empty((3, 5, 7))
+ dary = cuda.device_array((3, 5, 7))
+ self.assertEqual(len(ary), len(dary))
+
+ def test_devicearray_partition(self):
+ N = 100
+ array = np.arange(N, dtype=np.int32)
+ original = array.copy()
+ gpumem = cuda.to_device(array)
+ left, right = gpumem.split(N // 2)
+
+ array[:] = 0
+
+ self.assertTrue(np.all(array == 0))
+
+ right.copy_to_host(array[N // 2:])
+ left.copy_to_host(array[:N // 2])
+
+ self.assertTrue(np.all(array == original))
+
+ def test_devicearray_replace(self):
+ N = 100
+ array = np.arange(N, dtype=np.int32)
+ original = array.copy()
+ gpumem = cuda.to_device(array)
+ cuda.to_device(array * 2, to=gpumem)
+ gpumem.copy_to_host(array)
+ np.testing.assert_array_equal(array, original * 2)
+
+ @skip_on_cudasim('This works in the simulator')
+ def test_devicearray_transpose_wrongdim(self):
+ gpumem = cuda.to_device(np.array(np.arange(12)).reshape(3, 4, 1))
+
+ with self.assertRaises(NotImplementedError) as e:
+ np.transpose(gpumem)
+
+ self.assertEqual(
+ "transposing a non-2D DeviceNDArray isn't supported",
+ str(e.exception))
+
+ def test_devicearray_transpose_identity(self):
+ # any-shape identities should work
+ original = np.array(np.arange(24)).reshape(3, 4, 2)
+ array = np.transpose(cuda.to_device(original),
+ axes=(0, 1, 2)).copy_to_host()
+ self.assertTrue(np.all(array == original))
+
+ def test_devicearray_transpose_duplicatedaxis(self):
+ gpumem = cuda.to_device(np.array(np.arange(12)).reshape(3, 4))
+
+ with self.assertRaises(ValueError) as e:
+ np.transpose(gpumem, axes=(0, 0))
+
+ self.assertIn(
+ str(e.exception),
+ container=[
+ 'invalid axes list (0, 0)', # GPU
+ 'repeated axis in transpose', # sim
+ ])
+
+ def test_devicearray_transpose_wrongaxis(self):
+ gpumem = cuda.to_device(np.array(np.arange(12)).reshape(3, 4))
+
+ with self.assertRaises(ValueError) as e:
+ np.transpose(gpumem, axes=(0, 2))
+
+ self.assertIn(
+ str(e.exception),
+ container=[
+ 'invalid axes list (0, 2)', # GPU
+ 'invalid axis for this array',
+ 'axis 2 is out of bounds for array of dimension 2', # sim
+ ])
+
+ def test_devicearray_view_ok(self):
+ original = np.array(np.arange(12), dtype="i2").reshape(3, 4)
+ array = cuda.to_device(original)
+ for dtype in ("i4", "u4", "i8", "f8"):
+ with self.subTest(dtype=dtype):
+ np.testing.assert_array_equal(
+ array.view(dtype).copy_to_host(),
+ original.view(dtype)
+ )
+
+ def test_devicearray_view_ok_not_c_contig(self):
+ original = np.array(np.arange(32), dtype="i2").reshape(4, 8)
+ array = cuda.to_device(original)[:, ::2]
+ original = original[:, ::2]
+ np.testing.assert_array_equal(
+ array.view("u2").copy_to_host(),
+ original.view("u2")
+ )
+
+ def test_devicearray_view_bad_not_c_contig(self):
+ original = np.array(np.arange(32), dtype="i2").reshape(4, 8)
+ array = cuda.to_device(original)[:, ::2]
+ with self.assertRaises(ValueError) as e:
+ array.view("i4")
+
+ msg = str(e.exception)
+ self.assertIn('To change to a dtype of a different size,', msg)
+
+ contiguous_pre_np123 = 'the array must be C-contiguous' in msg
+ contiguous_post_np123 = 'the last axis must be contiguous' in msg
+ self.assertTrue(contiguous_pre_np123 or contiguous_post_np123,
+ 'Expected message to mention contiguity')
+
+ def test_devicearray_view_bad_itemsize(self):
+ original = np.array(np.arange(12), dtype="i2").reshape(4, 3)
+ array = cuda.to_device(original)
+ with self.assertRaises(ValueError) as e:
+ array.view("i4")
+ self.assertEqual(
+ "When changing to a larger dtype,"
+ " its size must be a divisor of the total size in bytes"
+ " of the last axis of the array.",
+ str(e.exception))
+
+ def test_devicearray_transpose_ok(self):
+ original = np.array(np.arange(12)).reshape(3, 4)
+ array = np.transpose(cuda.to_device(original)).copy_to_host()
+ self.assertTrue(np.all(array == original.T))
+
+ def test_devicearray_transpose_T(self):
+ original = np.array(np.arange(12)).reshape(3, 4)
+ array = cuda.to_device(original).T.copy_to_host()
+ self.assertTrue(np.all(array == original.T))
+
+ def test_devicearray_contiguous_slice(self):
+ # memcpys are dumb ranges of bytes, so trying to
+ # copy to a non-contiguous range shouldn't work!
+ a = np.arange(25).reshape(5, 5, order='F')
+ s = np.full(fill_value=5, shape=(5,))
+
+ d = cuda.to_device(a)
+ a[2] = s
+
+ # d is in F-order (not C-order), so d[2] is not contiguous
+ # (40-byte strides). This means we can't memcpy to it!
+ with self.assertRaises(ValueError) as e:
+ d[2].copy_to_device(s)
+ self.assertEqual(
+ devicearray.errmsg_contiguous_buffer,
+ str(e.exception))
+
+ # if d[2].copy_to_device(s), then this would pass:
+ # self.assertTrue((a == d.copy_to_host()).all())
+
+ def _test_devicearray_contiguous_host_copy(self, a_c, a_f):
+ """
+ Checks host->device memcpys
+ """
+ self.assertTrue(a_c.flags.c_contiguous)
+ self.assertTrue(a_f.flags.f_contiguous)
+
+ for original, copy in [
+ (a_f, a_f),
+ (a_f, a_c),
+ (a_c, a_f),
+ (a_c, a_c),
+ ]:
+ msg = '%s => %s' % (
+ 'C' if original.flags.c_contiguous else 'F',
+ 'C' if copy.flags.c_contiguous else 'F',
+ )
+
+ d = cuda.to_device(original)
+ d.copy_to_device(copy)
+ self.assertTrue(np.all(d.copy_to_host() == a_c), msg=msg)
+ self.assertTrue(np.all(d.copy_to_host() == a_f), msg=msg)
+
+ def test_devicearray_contiguous_copy_host_3d(self):
+ a_c = np.arange(5 * 5 * 5).reshape(5, 5, 5)
+ a_f = np.array(a_c, order='F')
+ self._test_devicearray_contiguous_host_copy(a_c, a_f)
+
+ def test_devicearray_contiguous_copy_host_1d(self):
+ a_c = np.arange(5)
+ a_f = np.array(a_c, order='F')
+ self._test_devicearray_contiguous_host_copy(a_c, a_f)
+
+ def test_devicearray_contiguous_copy_device(self):
+ a_c = np.arange(5 * 5 * 5).reshape(5, 5, 5)
+ a_f = np.array(a_c, order='F')
+ self.assertTrue(a_c.flags.c_contiguous)
+ self.assertTrue(a_f.flags.f_contiguous)
+
+ d = cuda.to_device(a_c)
+
+ with self.assertRaises(ValueError) as e:
+ d.copy_to_device(cuda.to_device(a_f))
+ self.assertEqual(
+ "incompatible strides: {} vs. {}".format(a_c.strides, a_f.strides),
+ str(e.exception))
+
+ d.copy_to_device(cuda.to_device(a_c))
+ self.assertTrue(np.all(d.copy_to_host() == a_c))
+
+ d = cuda.to_device(a_f)
+
+ with self.assertRaises(ValueError) as e:
+ d.copy_to_device(cuda.to_device(a_c))
+ self.assertEqual(
+ "incompatible strides: {} vs. {}".format(a_f.strides, a_c.strides),
+ str(e.exception))
+
+ d.copy_to_device(cuda.to_device(a_f))
+ self.assertTrue(np.all(d.copy_to_host() == a_f))
+
+ def test_devicearray_broadcast_host_copy(self):
+ broadsize = 4
+ coreshape = (2, 3)
+ coresize = np.prod(coreshape)
+ core_c = np.arange(coresize).reshape(coreshape, order='C')
+ core_f = np.arange(coresize).reshape(coreshape, order='F')
+ for dim in range(len(coreshape)):
+ newindex = (slice(None),) * dim + (np.newaxis,)
+ broadshape = coreshape[:dim] + (broadsize,) + coreshape[dim:]
+ broad_c = np.broadcast_to(core_c[newindex], broadshape)
+ broad_f = np.broadcast_to(core_f[newindex], broadshape)
+ dbroad_c = cuda.to_device(broad_c)
+ dbroad_f = cuda.to_device(broad_f)
+ np.testing.assert_array_equal(dbroad_c.copy_to_host(), broad_c)
+ np.testing.assert_array_equal(dbroad_f.copy_to_host(), broad_f)
+ # Also test copying across different core orderings
+ dbroad_c.copy_to_device(broad_f)
+ dbroad_f.copy_to_device(broad_c)
+ np.testing.assert_array_equal(dbroad_c.copy_to_host(), broad_f)
+ np.testing.assert_array_equal(dbroad_f.copy_to_host(), broad_c)
+
+ def test_devicearray_contiguous_host_strided(self):
+ a_c = np.arange(10)
+ d = cuda.to_device(a_c)
+ arr = np.arange(20)[::2]
+ d.copy_to_device(arr)
+ np.testing.assert_array_equal(d.copy_to_host(), arr)
+
+ def test_devicearray_contiguous_device_strided(self):
+ d = cuda.to_device(np.arange(20))
+ arr = np.arange(20)
+
+ with self.assertRaises(ValueError) as e:
+ d.copy_to_device(cuda.to_device(arr)[::2])
+ self.assertEqual(
+ devicearray.errmsg_contiguous_buffer,
+ str(e.exception))
+
+ @skip_on_cudasim('DeviceNDArray class not present in simulator')
+ def test_devicearray_relaxed_strides(self):
+ # From the reproducer in Issue #6824.
+
+ # Construct a device array that is contiguous even though
+ # the strides for the first axis (800) are not equal to
+ # the strides * size (10 * 8 = 80) for the previous axis,
+ # because the first axis size is 1.
+ arr = devicearray.DeviceNDArray((1, 10), (800, 8), np.float64)
+
+ # Ensure we still believe the array to be contiguous because
+ # strides checking is relaxed.
+ self.assertTrue(arr.flags['C_CONTIGUOUS'])
+ self.assertTrue(arr.flags['F_CONTIGUOUS'])
+
+ def test_c_f_contiguity_matches_numpy(self):
+ # From the reproducer in Issue #4943.
+
+ shapes = ((1, 4), (4, 1))
+ orders = ('C', 'F')
+
+ for shape, order in itertools.product(shapes, orders):
+ arr = np.ndarray(shape, order=order)
+ d_arr = cuda.to_device(arr)
+ self.assertEqual(arr.flags['C_CONTIGUOUS'],
+ d_arr.flags['C_CONTIGUOUS'])
+ self.assertEqual(arr.flags['F_CONTIGUOUS'],
+ d_arr.flags['F_CONTIGUOUS'])
+
+ @skip_on_cudasim('Typing not done in the simulator')
+ def test_devicearray_typing_order_simple_c(self):
+ # C-order 1D array
+ a = np.zeros(10, order='C')
+ d = cuda.to_device(a)
+ self.assertEqual(d._numba_type_.layout, 'C')
+
+ @skip_on_cudasim('Typing not done in the simulator')
+ def test_devicearray_typing_order_simple_f(self):
+ # F-order array that is also C layout.
+ a = np.zeros(10, order='F')
+ d = cuda.to_device(a)
+ self.assertEqual(d._numba_type_.layout, 'C')
+
+ @skip_on_cudasim('Typing not done in the simulator')
+ def test_devicearray_typing_order_2d_c(self):
+ # C-order 2D array
+ a = np.zeros((2, 10), order='C')
+ d = cuda.to_device(a)
+ self.assertEqual(d._numba_type_.layout, 'C')
+
+ @skip_on_cudasim('Typing not done in the simulator')
+ def test_devicearray_typing_order_2d_f(self):
+ # F-order array that can only be F layout
+ a = np.zeros((2, 10), order='F')
+ d = cuda.to_device(a)
+ self.assertEqual(d._numba_type_.layout, 'F')
+
+ @skip_on_cudasim('Typing not done in the simulator')
+ def test_devicearray_typing_order_noncontig_slice_c(self):
+ # Non-contiguous slice of C-order array
+ a = np.zeros((5, 5), order='C')
+ d = cuda.to_device(a)[:,2]
+ self.assertEqual(d._numba_type_.layout, 'A')
+
+ @skip_on_cudasim('Typing not done in the simulator')
+ def test_devicearray_typing_order_noncontig_slice_f(self):
+ # Non-contiguous slice of F-order array
+ a = np.zeros((5, 5), order='F')
+ d = cuda.to_device(a)[2,:]
+ self.assertEqual(d._numba_type_.layout, 'A')
+
+ @skip_on_cudasim('Typing not done in the simulator')
+ def test_devicearray_typing_order_contig_slice_c(self):
+ # Contiguous slice of C-order array
+ a = np.zeros((5, 5), order='C')
+ d = cuda.to_device(a)[2,:]
+ self.assertEqual(d._numba_type_.layout, 'C')
+
+ @skip_on_cudasim('Typing not done in the simulator')
+ def test_devicearray_typing_order_contig_slice_f(self):
+ # Contiguous slice of F-order array - is both C- and F-contiguous, so
+ # types as 'C' layout
+ a = np.zeros((5, 5), order='F')
+ d = cuda.to_device(a)[:,2]
+ self.assertEqual(d._numba_type_.layout, 'C')
+
+ @skip_on_cudasim('Typing not done in the simulator')
+ def test_devicearray_typing_order_broadcasted(self):
+ # Broadcasted array, similar to that used for passing scalars to ufuncs
+ a = np.broadcast_to(np.array([1]), (10,))
+ d = cuda.to_device(a)
+ self.assertEqual(d._numba_type_.layout, 'A')
+
+ def test_bug6697(self):
+ ary = np.arange(10, dtype=np.int16)
+ dary = cuda.to_device(ary)
+ got = np.asarray(dary)
+ self.assertEqual(got.dtype, dary.dtype)
+
+ @skip_on_cudasim('DeviceNDArray class not present in simulator')
+ def test_issue_8477(self):
+ # Ensure that we can copy a zero-length device array to a zero-length
+ # host array when the strides of the device and host arrays differ -
+ # this should be possible because the strides are irrelevant when the
+ # length is zero. For more info see
+ # https://github.com/numba/numba/issues/8477.
+
+ # Create a device array with shape (0,) and strides (8,)
+ dev_array = devicearray.DeviceNDArray(shape=(0,), strides=(8,),
+ dtype=np.int8)
+
+ # Create a host array with shape (0,) and strides (0,)
+ host_array = np.ndarray(shape=(0,), strides=(0,), dtype=np.int8)
+
+ # Sanity check for this test - ensure our destination has the strides
+ # we expect, because strides can be ignored in some cases by the
+ # ndarray constructor - checking here ensures that we haven't failed to
+ # account for unexpected behaviour across different versions of NumPy
+ self.assertEqual(host_array.strides, (0,))
+
+ # Ensure that the copy succeeds in both directions
+ dev_array.copy_to_host(host_array)
+ dev_array.copy_to_device(host_array)
+
+ # Ensure that a device-to-device copy also succeeds when the strides
+ # differ - one way of doing this is to copy the host array across and
+ # use that for copies in both directions.
+ dev_array_from_host = cuda.to_device(host_array)
+ self.assertEqual(dev_array_from_host.shape, (0,))
+ self.assertEqual(dev_array_from_host.strides, (0,))
+
+ dev_array.copy_to_device(dev_array_from_host)
+ dev_array_from_host.copy_to_device(dev_array)
+
+
+class TestRecarray(CUDATestCase):
+ def test_recarray(self):
+ # From issue #4111
+ a = np.recarray((16,), dtype=[
+ ("value1", np.int64),
+ ("value2", np.float64),
+ ])
+ a.value1 = np.arange(a.size, dtype=np.int64)
+ a.value2 = np.arange(a.size, dtype=np.float64) / 100
+
+ expect1 = a.value1
+ expect2 = a.value2
+
+ def test(x, out1, out2):
+ i = cuda.grid(1)
+ if i < x.size:
+ out1[i] = x.value1[i]
+ out2[i] = x.value2[i]
+
+ got1 = np.zeros_like(expect1)
+ got2 = np.zeros_like(expect2)
+ cuda.jit(test)[1, a.size](a, got1, got2)
+
+ np.testing.assert_array_equal(expect1, got1)
+ np.testing.assert_array_equal(expect2, got2)
+
+
+class TestCoreContiguous(CUDATestCase):
+ def _test_against_array_core(self, view):
+ self.assertEqual(
+ devicearray.is_contiguous(view),
+ devicearray.array_core(view).flags['C_CONTIGUOUS']
+ )
+
+ def test_device_array_like_1d(self):
+ d_a = cuda.device_array(10, order='C')
+ self._test_against_array_core(d_a)
+
+ def test_device_array_like_2d(self):
+ d_a = cuda.device_array((10, 12), order='C')
+ self._test_against_array_core(d_a)
+
+ def test_device_array_like_2d_transpose(self):
+ d_a = cuda.device_array((10, 12), order='C')
+ self._test_against_array_core(d_a.T)
+
+ def test_device_array_like_3d(self):
+ d_a = cuda.device_array((10, 12, 14), order='C')
+ self._test_against_array_core(d_a)
+
+ def test_device_array_like_1d_f(self):
+ d_a = cuda.device_array(10, order='F')
+ self._test_against_array_core(d_a)
+
+ def test_device_array_like_2d_f(self):
+ d_a = cuda.device_array((10, 12), order='F')
+ self._test_against_array_core(d_a)
+
+ def test_device_array_like_2d_f_transpose(self):
+ d_a = cuda.device_array((10, 12), order='F')
+ self._test_against_array_core(d_a.T)
+
+ def test_device_array_like_3d_f(self):
+ d_a = cuda.device_array((10, 12, 14), order='F')
+ self._test_against_array_core(d_a)
+
+ def test_1d_view(self):
+ shape = 10
+ view = np.zeros(shape)[::2]
+ self._test_against_array_core(view)
+
+ def test_1d_view_f(self):
+ shape = 10
+ view = np.zeros(shape, order='F')[::2]
+ self._test_against_array_core(view)
+
+ def test_2d_view(self):
+ shape = (10, 12)
+ view = np.zeros(shape)[::2, ::2]
+ self._test_against_array_core(view)
+
+ def test_2d_view_f(self):
+ shape = (10, 12)
+ view = np.zeros(shape, order='F')[::2, ::2]
+ self._test_against_array_core(view)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/test_deallocations.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/test_deallocations.py
new file mode 100644
index 0000000000000000000000000000000000000000..66fbbc372e9a1347dded4cff3e699175b5d9c80d
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/test_deallocations.py
@@ -0,0 +1,249 @@
+from contextlib import contextmanager
+
+import numpy as np
+
+from numba import cuda
+from numba.cuda.testing import (unittest, skip_on_cudasim,
+ skip_if_external_memmgr, CUDATestCase)
+from numba.tests.support import captured_stderr
+from numba.core import config
+
+
+@skip_on_cudasim('not supported on CUDASIM')
+@skip_if_external_memmgr('Deallocation specific to Numba memory management')
+class TestDeallocation(CUDATestCase):
+ def test_max_pending_count(self):
+ # get deallocation manager and flush it
+ deallocs = cuda.current_context().memory_manager.deallocations
+ deallocs.clear()
+ self.assertEqual(len(deallocs), 0)
+ # deallocate to maximum count
+ for i in range(config.CUDA_DEALLOCS_COUNT):
+ cuda.to_device(np.arange(1))
+ self.assertEqual(len(deallocs), i + 1)
+ # one more to trigger .clear()
+ cuda.to_device(np.arange(1))
+ self.assertEqual(len(deallocs), 0)
+
+ def test_max_pending_bytes(self):
+ # get deallocation manager and flush it
+ ctx = cuda.current_context()
+ deallocs = ctx.memory_manager.deallocations
+ deallocs.clear()
+ self.assertEqual(len(deallocs), 0)
+
+ mi = ctx.get_memory_info()
+
+ max_pending = 10**6 # 1MB
+ old_ratio = config.CUDA_DEALLOCS_RATIO
+ try:
+ # change to a smaller ratio
+ config.CUDA_DEALLOCS_RATIO = max_pending / mi.total
+ # due to round off error (floor is used in calculating
+ # _max_pending_bytes) it can be off by 1.
+ self.assertAlmostEqual(deallocs._max_pending_bytes, max_pending,
+ delta=1)
+
+ # allocate half the max size
+ # this will not trigger deallocation
+ cuda.to_device(np.ones(max_pending // 2, dtype=np.int8))
+ self.assertEqual(len(deallocs), 1)
+
+ # allocate another remaining
+ # this will not trigger deallocation
+ cuda.to_device(np.ones(deallocs._max_pending_bytes -
+ deallocs._size, dtype=np.int8))
+ self.assertEqual(len(deallocs), 2)
+
+ # another byte to trigger .clear()
+ cuda.to_device(np.ones(1, dtype=np.int8))
+ self.assertEqual(len(deallocs), 0)
+ finally:
+ # restore old ratio
+ config.CUDA_DEALLOCS_RATIO = old_ratio
+
+
+@skip_on_cudasim("defer_cleanup has no effect in CUDASIM")
+@skip_if_external_memmgr('Deallocation specific to Numba memory management')
+class TestDeferCleanup(CUDATestCase):
+ def test_basic(self):
+ harr = np.arange(5)
+ darr1 = cuda.to_device(harr)
+ deallocs = cuda.current_context().memory_manager.deallocations
+ deallocs.clear()
+ self.assertEqual(len(deallocs), 0)
+ with cuda.defer_cleanup():
+ darr2 = cuda.to_device(harr)
+ del darr1
+ self.assertEqual(len(deallocs), 1)
+ del darr2
+ self.assertEqual(len(deallocs), 2)
+ deallocs.clear()
+ self.assertEqual(len(deallocs), 2)
+
+ deallocs.clear()
+ self.assertEqual(len(deallocs), 0)
+
+ def test_nested(self):
+ harr = np.arange(5)
+ darr1 = cuda.to_device(harr)
+ deallocs = cuda.current_context().memory_manager.deallocations
+ deallocs.clear()
+ self.assertEqual(len(deallocs), 0)
+ with cuda.defer_cleanup():
+ with cuda.defer_cleanup():
+ darr2 = cuda.to_device(harr)
+ del darr1
+ self.assertEqual(len(deallocs), 1)
+ del darr2
+ self.assertEqual(len(deallocs), 2)
+ deallocs.clear()
+ self.assertEqual(len(deallocs), 2)
+ deallocs.clear()
+ self.assertEqual(len(deallocs), 2)
+
+ deallocs.clear()
+ self.assertEqual(len(deallocs), 0)
+
+ def test_exception(self):
+ harr = np.arange(5)
+ darr1 = cuda.to_device(harr)
+ deallocs = cuda.current_context().memory_manager.deallocations
+ deallocs.clear()
+ self.assertEqual(len(deallocs), 0)
+
+ class CustomError(Exception):
+ pass
+
+ with self.assertRaises(CustomError):
+ with cuda.defer_cleanup():
+ darr2 = cuda.to_device(harr)
+ del darr2
+ self.assertEqual(len(deallocs), 1)
+ deallocs.clear()
+ self.assertEqual(len(deallocs), 1)
+ raise CustomError
+ deallocs.clear()
+ self.assertEqual(len(deallocs), 0)
+ del darr1
+ self.assertEqual(len(deallocs), 1)
+ deallocs.clear()
+ self.assertEqual(len(deallocs), 0)
+
+
+class TestDeferCleanupAvail(CUDATestCase):
+ def test_context_manager(self):
+ # just make sure the API is available
+ with cuda.defer_cleanup():
+ pass
+
+
+@skip_on_cudasim('not supported on CUDASIM')
+class TestDel(CUDATestCase):
+ """
+ Ensure resources are deleted properly without ignored exception.
+ """
+ @contextmanager
+ def check_ignored_exception(self, ctx):
+ with captured_stderr() as cap:
+ yield
+ ctx.deallocations.clear()
+ self.assertFalse(cap.getvalue())
+
+ def test_stream(self):
+ ctx = cuda.current_context()
+ stream = ctx.create_stream()
+ with self.check_ignored_exception(ctx):
+ del stream
+
+ def test_event(self):
+ ctx = cuda.current_context()
+ event = ctx.create_event()
+ with self.check_ignored_exception(ctx):
+ del event
+
+ def test_pinned_memory(self):
+ ctx = cuda.current_context()
+ mem = ctx.memhostalloc(32)
+ with self.check_ignored_exception(ctx):
+ del mem
+
+ def test_mapped_memory(self):
+ ctx = cuda.current_context()
+ mem = ctx.memhostalloc(32, mapped=True)
+ with self.check_ignored_exception(ctx):
+ del mem
+
+ def test_device_memory(self):
+ ctx = cuda.current_context()
+ mem = ctx.memalloc(32)
+ with self.check_ignored_exception(ctx):
+ del mem
+
+ def test_managed_memory(self):
+ ctx = cuda.current_context()
+ mem = ctx.memallocmanaged(32)
+ with self.check_ignored_exception(ctx):
+ del mem
+
+ def test_pinned_contextmanager(self):
+ # Check that temporarily pinned memory is unregistered immediately,
+ # such that it can be re-pinned at any time
+ class PinnedException(Exception):
+ pass
+
+ arr = np.zeros(1)
+ ctx = cuda.current_context()
+ ctx.deallocations.clear()
+ with self.check_ignored_exception(ctx):
+ with cuda.pinned(arr):
+ pass
+ with cuda.pinned(arr):
+ pass
+ # Should also work inside a `defer_cleanup` block
+ with cuda.defer_cleanup():
+ with cuda.pinned(arr):
+ pass
+ with cuda.pinned(arr):
+ pass
+ # Should also work when breaking out of the block due to an
+ # exception
+ try:
+ with cuda.pinned(arr):
+ raise PinnedException
+ except PinnedException:
+ with cuda.pinned(arr):
+ pass
+
+ def test_mapped_contextmanager(self):
+ # Check that temporarily mapped memory is unregistered immediately,
+ # such that it can be re-mapped at any time
+ class MappedException(Exception):
+ pass
+
+ arr = np.zeros(1)
+ ctx = cuda.current_context()
+ ctx.deallocations.clear()
+ with self.check_ignored_exception(ctx):
+ with cuda.mapped(arr):
+ pass
+ with cuda.mapped(arr):
+ pass
+ # Should also work inside a `defer_cleanup` block
+ with cuda.defer_cleanup():
+ with cuda.mapped(arr):
+ pass
+ with cuda.mapped(arr):
+ pass
+ # Should also work when breaking out of the block due to an
+ # exception
+ try:
+ with cuda.mapped(arr):
+ raise MappedException
+ except MappedException:
+ with cuda.mapped(arr):
+ pass
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/test_detect.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/test_detect.py
new file mode 100644
index 0000000000000000000000000000000000000000..528e11bf848893026a9b7885c2a959190d455222
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/test_detect.py
@@ -0,0 +1,81 @@
+import os
+import sys
+import subprocess
+import threading
+from numba import cuda
+from numba.cuda.testing import (unittest, CUDATestCase, skip_on_cudasim,
+ skip_under_cuda_memcheck)
+from numba.tests.support import captured_stdout
+
+
+class TestCudaDetect(CUDATestCase):
+ def test_cuda_detect(self):
+ # exercise the code path
+ with captured_stdout() as out:
+ cuda.detect()
+ output = out.getvalue()
+ self.assertIn('Found', output)
+ self.assertIn('CUDA devices', output)
+
+
+@skip_under_cuda_memcheck('Hangs cuda-memcheck')
+class TestCUDAFindLibs(CUDATestCase):
+
+ def run_cmd(self, cmdline, env):
+ popen = subprocess.Popen(cmdline,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ env=env)
+
+ # finish in 5 minutes or kill it
+ timeout = threading.Timer(5 * 60., popen.kill)
+ try:
+ timeout.start()
+ out, err = popen.communicate()
+ # the process should exit with an error
+ return out.decode(), err.decode()
+ finally:
+ timeout.cancel()
+ return None, None
+
+ def run_test_in_separate_process(self, envvar, envvar_value):
+ env_copy = os.environ.copy()
+ env_copy[envvar] = str(envvar_value)
+ code = """if 1:
+ from numba import cuda
+ @cuda.jit('(int64,)')
+ def kernel(x):
+ pass
+ kernel(1,)
+ """
+ cmdline = [sys.executable, "-c", code]
+ return self.run_cmd(cmdline, env_copy)
+
+ @skip_on_cudasim('Simulator does not hit device library search code path')
+ @unittest.skipIf(not sys.platform.startswith('linux'), "linux only")
+ def test_cuda_find_lib_errors(self):
+ """
+ This tests that the find_libs works as expected in the case of an
+ environment variable being used to set the path.
+ """
+ # one of these is likely to exist on linux, it's also unlikely that
+ # someone has extracted the contents of libdevice into here!
+ locs = ['lib', 'lib64']
+
+ looking_for = None
+ for l in locs:
+ looking_for = os.path.join(os.path.sep, l)
+ if os.path.exists(looking_for):
+ break
+
+ # This is the testing part, the test will only run if there's a valid
+ # path in which to look
+ if looking_for is not None:
+ out, err = self.run_test_in_separate_process("NUMBA_CUDA_DRIVER",
+ looking_for)
+ self.assertTrue(out is not None)
+ self.assertTrue(err is not None)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/test_emm_plugins.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/test_emm_plugins.py
new file mode 100644
index 0000000000000000000000000000000000000000..209355ed69935920c4dbbe1fdc7ad84b3f9c1a11
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/test_emm_plugins.py
@@ -0,0 +1,192 @@
+import ctypes
+import numpy as np
+import weakref
+
+from numba import cuda
+from numba.core import config
+from numba.cuda.testing import unittest, CUDATestCase, skip_on_cudasim
+from numba.tests.support import linux_only
+
+if not config.ENABLE_CUDASIM:
+ class DeviceOnlyEMMPlugin(cuda.HostOnlyCUDAMemoryManager):
+ """
+ Dummy EMM Plugin implementation for testing. It memorises which plugin
+ API methods have been called so that the tests can check that Numba
+ called into the plugin as expected.
+ """
+
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+
+ # For tracking our dummy allocations
+ self.allocations = {}
+ self.count = 0
+
+ # For tracking which methods have been called
+ self.initialized = False
+ self.memalloc_called = False
+ self.reset_called = False
+ self.get_memory_info_called = False
+ self.get_ipc_handle_called = False
+
+ def memalloc(self, size):
+ # We maintain a list of allocations and keep track of them, so that
+ # we can test that the finalizers of objects returned by memalloc
+ # get called.
+
+ # Numba should have initialized the memory manager when preparing
+ # the context for use, prior to any memalloc call.
+ if not self.initialized:
+ raise RuntimeError("memalloc called before initialize")
+ self.memalloc_called = True
+
+ # Create an allocation and record it
+ self.count += 1
+ alloc_count = self.count
+ self.allocations[alloc_count] = size
+
+ # The finalizer deletes the record from our internal dict of
+ # allocations.
+ finalizer_allocs = self.allocations
+
+ def finalizer():
+ del finalizer_allocs[alloc_count]
+
+ # We use an AutoFreePointer so that the finalizer will be run when
+ # the reference count drops to zero.
+ ctx = weakref.proxy(self.context)
+ ptr = ctypes.c_void_p(alloc_count)
+ return cuda.cudadrv.driver.AutoFreePointer(ctx, ptr, size,
+ finalizer=finalizer)
+
+ def initialize(self):
+ # No special initialization needed.
+ self.initialized = True
+
+ def reset(self):
+ # We remove all allocations on reset, just as a real EMM Plugin
+ # would do. Note that our finalizers in memalloc don't check
+ # whether the allocations are still alive, so running them after
+ # reset will detect any allocations that are floating around at
+ # exit time; however, the atexit finalizer for weakref will only
+ # print a traceback, not terminate the interpreter abnormally.
+ self.reset_called = True
+
+ def get_memory_info(self):
+ # Return some dummy memory information
+ self.get_memory_info_called = True
+ return cuda.MemoryInfo(free=32, total=64)
+
+ def get_ipc_handle(self, memory):
+ # The dummy IPC handle is only a string, so it is important that
+ # the tests don't try to do too much with it (e.g. open / close
+ # it).
+ self.get_ipc_handle_called = True
+ return "Dummy IPC handle for alloc %s" % memory.device_pointer.value
+
+ @property
+ def interface_version(self):
+ # The expected version for an EMM Plugin.
+ return 1
+
+ class BadVersionEMMPlugin(DeviceOnlyEMMPlugin):
+ """A plugin that claims to implement a different interface version"""
+
+ @property
+ def interface_version(self):
+ return 2
+
+
+@skip_on_cudasim('EMM Plugins not supported on CUDA simulator')
+class TestDeviceOnlyEMMPlugin(CUDATestCase):
+ """
+ Tests that the API of an EMM Plugin that implements device allocations
+ only is used correctly by Numba.
+ """
+
+ def setUp(self):
+ super().setUp()
+ # Always start afresh with a new context and memory manager
+ cuda.close()
+ cuda.set_memory_manager(DeviceOnlyEMMPlugin)
+
+ def tearDown(self):
+ super().tearDown()
+ # Unset the memory manager for subsequent tests
+ cuda.close()
+ cuda.cudadrv.driver._memory_manager = None
+
+ def test_memalloc(self):
+ mgr = cuda.current_context().memory_manager
+
+ # Allocate an array and check that memalloc was called with the correct
+ # size.
+ arr_1 = np.arange(10)
+ d_arr_1 = cuda.device_array_like(arr_1)
+ self.assertTrue(mgr.memalloc_called)
+ self.assertEqual(mgr.count, 1)
+ self.assertEqual(mgr.allocations[1], arr_1.nbytes)
+
+ # Allocate again, with a different size, and check that it is also
+ # correct.
+ arr_2 = np.arange(5)
+ d_arr_2 = cuda.device_array_like(arr_2)
+ self.assertEqual(mgr.count, 2)
+ self.assertEqual(mgr.allocations[2], arr_2.nbytes)
+
+ # Remove the first array, and check that our finalizer was called for
+ # the first array only.
+ del d_arr_1
+ self.assertNotIn(1, mgr.allocations)
+ self.assertIn(2, mgr.allocations)
+
+ # Remove the second array and check that its finalizer was also
+ # called.
+ del d_arr_2
+ self.assertNotIn(2, mgr.allocations)
+
+ def test_initialized_in_context(self):
+ # If we have a CUDA context, it should already have initialized its
+ # memory manager.
+ self.assertTrue(cuda.current_context().memory_manager.initialized)
+
+ def test_reset(self):
+ ctx = cuda.current_context()
+ ctx.reset()
+ self.assertTrue(ctx.memory_manager.reset_called)
+
+ def test_get_memory_info(self):
+ ctx = cuda.current_context()
+ meminfo = ctx.get_memory_info()
+ self.assertTrue(ctx.memory_manager.get_memory_info_called)
+ self.assertEqual(meminfo.free, 32)
+ self.assertEqual(meminfo.total, 64)
+
+ @linux_only
+ def test_get_ipc_handle(self):
+ # We don't attempt to close the IPC handle in this test because Numba
+ # will be expecting a real IpcHandle object to have been returned from
+ # get_ipc_handle, and it would cause problems to do so.
+ arr = np.arange(2)
+ d_arr = cuda.device_array_like(arr)
+ ipch = d_arr.get_ipc_handle()
+ ctx = cuda.current_context()
+ self.assertTrue(ctx.memory_manager.get_ipc_handle_called)
+ self.assertIn("Dummy IPC handle for alloc 1", ipch._ipc_handle)
+
+
+@skip_on_cudasim('EMM Plugins not supported on CUDA simulator')
+class TestBadEMMPluginVersion(CUDATestCase):
+ """
+ Ensure that Numba rejects EMM Plugins with incompatible version
+ numbers.
+ """
+
+ def test_bad_plugin_version(self):
+ with self.assertRaises(RuntimeError) as raises:
+ cuda.set_memory_manager(BadVersionEMMPlugin)
+ self.assertIn('version 1 required', str(raises.exception))
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/test_events.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/test_events.py
new file mode 100644
index 0000000000000000000000000000000000000000..b611a4a75fddfec427cd61f5d4db515066690548
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/test_events.py
@@ -0,0 +1,38 @@
+import numpy as np
+from numba import cuda
+from numba.cuda.testing import unittest, CUDATestCase
+
+
+class TestCudaEvent(CUDATestCase):
+ def test_event_elapsed(self):
+ N = 32
+ dary = cuda.device_array(N, dtype=np.double)
+ evtstart = cuda.event()
+ evtend = cuda.event()
+
+ evtstart.record()
+ cuda.to_device(np.arange(N, dtype=np.double), to=dary)
+ evtend.record()
+ evtend.wait()
+ evtend.synchronize()
+ # Exercise the code path
+ evtstart.elapsed_time(evtend)
+
+ def test_event_elapsed_stream(self):
+ N = 32
+ stream = cuda.stream()
+ dary = cuda.device_array(N, dtype=np.double)
+ evtstart = cuda.event()
+ evtend = cuda.event()
+
+ evtstart.record(stream=stream)
+ cuda.to_device(np.arange(N, dtype=np.double), to=dary, stream=stream)
+ evtend.record(stream=stream)
+ evtend.wait(stream=stream)
+ evtend.synchronize()
+ # Exercise the code path
+ evtstart.elapsed_time(evtend)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/test_host_alloc.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/test_host_alloc.py
new file mode 100644
index 0000000000000000000000000000000000000000..62c4ecafe6c04a85ff52c022f1417bfe5fef9c68
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/test_host_alloc.py
@@ -0,0 +1,65 @@
+import numpy as np
+from numba.cuda.cudadrv import driver
+from numba import cuda
+from numba.cuda.testing import unittest, ContextResettingTestCase
+
+
+class TestHostAlloc(ContextResettingTestCase):
+ def test_host_alloc_driver(self):
+ n = 32
+ mem = cuda.current_context().memhostalloc(n, mapped=True)
+
+ dtype = np.dtype(np.uint8)
+ ary = np.ndarray(shape=n // dtype.itemsize, dtype=dtype,
+ buffer=mem)
+
+ magic = 0xab
+ driver.device_memset(mem, magic, n)
+
+ self.assertTrue(np.all(ary == magic))
+
+ ary.fill(n)
+
+ recv = np.empty_like(ary)
+
+ driver.device_to_host(recv, mem, ary.size)
+
+ self.assertTrue(np.all(ary == recv))
+ self.assertTrue(np.all(recv == n))
+
+ def test_host_alloc_pinned(self):
+ ary = cuda.pinned_array(10, dtype=np.uint32)
+ ary.fill(123)
+ self.assertTrue(all(ary == 123))
+ devary = cuda.to_device(ary)
+ driver.device_memset(devary, 0, driver.device_memory_size(devary))
+ self.assertTrue(all(ary == 123))
+ devary.copy_to_host(ary)
+ self.assertTrue(all(ary == 0))
+
+ def test_host_alloc_mapped(self):
+ ary = cuda.mapped_array(10, dtype=np.uint32)
+ ary.fill(123)
+ self.assertTrue(all(ary == 123))
+ driver.device_memset(ary, 0, driver.device_memory_size(ary))
+ self.assertTrue(all(ary == 0))
+ self.assertTrue(sum(ary != 0) == 0)
+
+ def test_host_operators(self):
+ for ary in [cuda.mapped_array(10, dtype=np.uint32),
+ cuda.pinned_array(10, dtype=np.uint32)]:
+ ary[:] = range(10)
+ self.assertTrue(sum(ary + 1) == 55)
+ self.assertTrue(sum((ary + 1) * 2 - 1) == 100)
+ self.assertTrue(sum(ary < 5) == 5)
+ self.assertTrue(sum(ary <= 5) == 6)
+ self.assertTrue(sum(ary > 6) == 3)
+ self.assertTrue(sum(ary >= 6) == 4)
+ self.assertTrue(sum(ary ** 2) == 285)
+ self.assertTrue(sum(ary // 2) == 20)
+ self.assertTrue(sum(ary / 2.0) == 22.5)
+ self.assertTrue(sum(ary % 2) == 5)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/test_init.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/test_init.py
new file mode 100644
index 0000000000000000000000000000000000000000..600687fd52aa515b5adca075f1510726d914d9b4
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/test_init.py
@@ -0,0 +1,139 @@
+import multiprocessing as mp
+import os
+
+from numba import cuda
+from numba.cuda.cudadrv.driver import CudaAPIError, driver
+from numba.cuda.cudadrv.error import CudaSupportError
+from numba.cuda.testing import skip_on_cudasim, unittest, CUDATestCase
+
+
+# A mock of cuInit that always raises a CudaAPIError
+def cuInit_raising(arg):
+ raise CudaAPIError(999, 'CUDA_ERROR_UNKNOWN')
+
+
+# Test code to run in a child that patches driver.cuInit to a variant that
+# always raises. We can't use mock.patch.object here because driver.cuInit is
+# not assigned until we attempt to initialize - mock.patch.object cannot locate
+# the non-existent original method, and so fails. Instead we patch
+# driver.cuInit with our raising version prior to any attempt to initialize.
+def cuInit_raising_test(result_queue):
+ driver.cuInit = cuInit_raising
+
+ success = False
+ msg = None
+
+ try:
+ # A CUDA operation that forces initialization of the device
+ cuda.device_array(1)
+ except CudaSupportError as e:
+ success = True
+ msg = e.msg
+
+ result_queue.put((success, msg))
+
+
+# Similar to cuInit_raising_test above, but for testing that the string
+# returned by cuda_error() is as expected.
+def initialization_error_test(result_queue):
+ driver.cuInit = cuInit_raising
+
+ success = False
+ msg = None
+
+ try:
+ # A CUDA operation that forces initialization of the device
+ cuda.device_array(1)
+ except CudaSupportError:
+ success = True
+
+ msg = cuda.cuda_error()
+ result_queue.put((success, msg))
+
+
+# For testing the path where Driver.__init__() catches a CudaSupportError
+def cuda_disabled_test(result_queue):
+ success = False
+ msg = None
+
+ try:
+ # A CUDA operation that forces initialization of the device
+ cuda.device_array(1)
+ except CudaSupportError as e:
+ success = True
+ msg = e.msg
+
+ result_queue.put((success, msg))
+
+
+# Similar to cuda_disabled_test, but checks cuda.cuda_error() instead of the
+# exception raised on initialization
+def cuda_disabled_error_test(result_queue):
+ success = False
+ msg = None
+
+ try:
+ # A CUDA operation that forces initialization of the device
+ cuda.device_array(1)
+ except CudaSupportError:
+ success = True
+
+ msg = cuda.cuda_error()
+ result_queue.put((success, msg))
+
+
+@skip_on_cudasim('CUDA Simulator does not initialize driver')
+class TestInit(CUDATestCase):
+ def _test_init_failure(self, target, expected):
+ # Run the initialization failure test in a separate subprocess
+ ctx = mp.get_context('spawn')
+ result_queue = ctx.Queue()
+ proc = ctx.Process(target=target, args=(result_queue,))
+ proc.start()
+ proc.join(30) # should complete within 30s
+ success, msg = result_queue.get()
+
+ # Ensure the child process raised an exception during initialization
+ # before checking the message
+ if not success:
+ self.fail('CudaSupportError not raised')
+
+ self.assertIn(expected, msg)
+
+ def test_init_failure_raising(self):
+ expected = 'Error at driver init: CUDA_ERROR_UNKNOWN (999)'
+ self._test_init_failure(cuInit_raising_test, expected)
+
+ def test_init_failure_error(self):
+ expected = 'CUDA_ERROR_UNKNOWN (999)'
+ self._test_init_failure(initialization_error_test, expected)
+
+ def _test_cuda_disabled(self, target):
+ # Uses _test_init_failure to launch the test in a separate subprocess
+ # with CUDA disabled.
+ cuda_disabled = os.environ.get('NUMBA_DISABLE_CUDA')
+ os.environ['NUMBA_DISABLE_CUDA'] = "1"
+ try:
+ expected = 'CUDA is disabled due to setting NUMBA_DISABLE_CUDA=1'
+ self._test_init_failure(cuda_disabled_test, expected)
+ finally:
+ if cuda_disabled is not None:
+ os.environ['NUMBA_DISABLE_CUDA'] = cuda_disabled
+ else:
+ os.environ.pop('NUMBA_DISABLE_CUDA')
+
+ def test_cuda_disabled_raising(self):
+ self._test_cuda_disabled(cuda_disabled_test)
+
+ def test_cuda_disabled_error(self):
+ self._test_cuda_disabled(cuda_disabled_error_test)
+
+ def test_init_success(self):
+ # Here we assume that initialization is successful (because many bad
+ # things will happen with the test suite if it is not) and check that
+ # there is no error recorded.
+ self.assertIsNone(cuda.cuda_error())
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/test_inline_ptx.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/test_inline_ptx.py
new file mode 100644
index 0000000000000000000000000000000000000000..40a6fa599e2bc7f7813a9d2c3f2ce6d89397bb39
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/test_inline_ptx.py
@@ -0,0 +1,37 @@
+from llvmlite import ir
+
+from numba.cuda.cudadrv import nvvm
+from numba.cuda.testing import unittest, ContextResettingTestCase
+from numba.cuda.testing import skip_on_cudasim
+
+
+@skip_on_cudasim('Inline PTX cannot be used in the simulator')
+class TestCudaInlineAsm(ContextResettingTestCase):
+ def test_inline_rsqrt(self):
+ mod = ir.Module(__name__)
+ mod.triple = 'nvptx64-nvidia-cuda'
+ nvvm.add_ir_version(mod)
+ fnty = ir.FunctionType(ir.VoidType(), [ir.PointerType(ir.FloatType())])
+ fn = ir.Function(mod, fnty, 'cu_rsqrt')
+ bldr = ir.IRBuilder(fn.append_basic_block('entry'))
+
+ rsqrt_approx_fnty = ir.FunctionType(ir.FloatType(), [ir.FloatType()])
+ inlineasm = ir.InlineAsm(rsqrt_approx_fnty,
+ 'rsqrt.approx.f32 $0, $1;',
+ '=f,f', side_effect=True)
+ val = bldr.load(fn.args[0])
+ res = bldr.call(inlineasm, [val])
+
+ bldr.store(res, fn.args[0])
+ bldr.ret_void()
+
+ # generate ptx
+ mod.data_layout = nvvm.NVVM().data_layout
+ nvvm.set_cuda_kernel(fn)
+ nvvmir = str(mod)
+ ptx = nvvm.compile_ir(nvvmir)
+ self.assertTrue('rsqrt.approx.f32' in str(ptx))
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/test_is_fp16.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/test_is_fp16.py
new file mode 100644
index 0000000000000000000000000000000000000000..dcc73fa155f2ee73dd39ab363df56782656f8798
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/test_is_fp16.py
@@ -0,0 +1,12 @@
+from numba import cuda
+from numba.cuda.testing import CUDATestCase, skip_on_cudasim, skip_unless_cc_53
+
+
+class TestIsFP16Supported(CUDATestCase):
+ def test_is_fp16_supported(self):
+ self.assertTrue(cuda.is_float16_supported())
+
+ @skip_on_cudasim
+ @skip_unless_cc_53
+ def test_device_supports_float16(self):
+ self.assertTrue(cuda.get_current_device().supports_float16)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/test_linker.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/test_linker.py
new file mode 100644
index 0000000000000000000000000000000000000000..22e2ee8375c8c742e0636b8aa4760674e3c8f01b
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/test_linker.py
@@ -0,0 +1,317 @@
+import numpy as np
+import warnings
+from numba.cuda.testing import unittest
+from numba.cuda.testing import (skip_on_cudasim, skip_if_cuda_includes_missing)
+from numba.cuda.testing import CUDATestCase, test_data_dir
+from numba.cuda.cudadrv.driver import (CudaAPIError, Linker,
+ LinkerError)
+from numba.cuda.cudadrv.error import NvrtcError
+from numba.cuda import require_context
+from numba.tests.support import ignore_internal_warnings
+from numba import cuda, void, float64, int64, int32, typeof, float32
+
+
+CONST1D = np.arange(10, dtype=np.float64)
+
+
+def simple_const_mem(A):
+ C = cuda.const.array_like(CONST1D)
+ i = cuda.grid(1)
+
+ A[i] = C[i] + 1.0
+
+
+def func_with_lots_of_registers(x, a, b, c, d, e, f):
+ a1 = 1.0
+ a2 = 1.0
+ a3 = 1.0
+ a4 = 1.0
+ a5 = 1.0
+ b1 = 1.0
+ b2 = 1.0
+ b3 = 1.0
+ b4 = 1.0
+ b5 = 1.0
+ c1 = 1.0
+ c2 = 1.0
+ c3 = 1.0
+ c4 = 1.0
+ c5 = 1.0
+ d1 = 10
+ d2 = 10
+ d3 = 10
+ d4 = 10
+ d5 = 10
+ for i in range(a):
+ a1 += b
+ a2 += c
+ a3 += d
+ a4 += e
+ a5 += f
+ b1 *= b
+ b2 *= c
+ b3 *= d
+ b4 *= e
+ b5 *= f
+ c1 /= b
+ c2 /= c
+ c3 /= d
+ c4 /= e
+ c5 /= f
+ d1 <<= b
+ d2 <<= c
+ d3 <<= d
+ d4 <<= e
+ d5 <<= f
+ x[cuda.grid(1)] = a1 + a2 + a3 + a4 + a5
+ x[cuda.grid(1)] += b1 + b2 + b3 + b4 + b5
+ x[cuda.grid(1)] += c1 + c2 + c3 + c4 + c5
+ x[cuda.grid(1)] += d1 + d2 + d3 + d4 + d5
+
+
+def simple_smem(ary, dty):
+ sm = cuda.shared.array(100, dty)
+ i = cuda.grid(1)
+ if i == 0:
+ for j in range(100):
+ sm[j] = j
+ cuda.syncthreads()
+ ary[i] = sm[i]
+
+
+def coop_smem2d(ary):
+ i, j = cuda.grid(2)
+ sm = cuda.shared.array((10, 20), float32)
+ sm[i, j] = (i + 1) / (j + 1)
+ cuda.syncthreads()
+ ary[i, j] = sm[i, j]
+
+
+def simple_maxthreads(ary):
+ i = cuda.grid(1)
+ ary[i] = i
+
+
+LMEM_SIZE = 1000
+
+
+def simple_lmem(A, B, dty):
+ C = cuda.local.array(LMEM_SIZE, dty)
+ for i in range(C.shape[0]):
+ C[i] = A[i]
+ for i in range(C.shape[0]):
+ B[i] = C[i]
+
+
+@skip_on_cudasim('Linking unsupported in the simulator')
+class TestLinker(CUDATestCase):
+ _NUMBA_NVIDIA_BINDING_0_ENV = {'NUMBA_CUDA_USE_NVIDIA_BINDING': '0'}
+
+ @require_context
+ def test_linker_basic(self):
+ '''Simply go through the constructor and destructor
+ '''
+ linker = Linker.new(cc=(5, 3))
+ del linker
+
+ def _test_linking(self, eager):
+ global bar # must be a global; other it is recognized as a freevar
+ bar = cuda.declare_device('bar', 'int32(int32)')
+
+ link = str(test_data_dir / 'jitlink.ptx')
+
+ if eager:
+ args = ['void(int32[:], int32[:])']
+ else:
+ args = []
+
+ @cuda.jit(*args, link=[link])
+ def foo(x, y):
+ i = cuda.grid(1)
+ x[i] += bar(y[i])
+
+ A = np.array([123], dtype=np.int32)
+ B = np.array([321], dtype=np.int32)
+
+ foo[1, 1](A, B)
+
+ self.assertTrue(A[0] == 123 + 2 * 321)
+
+ def test_linking_lazy_compile(self):
+ self._test_linking(eager=False)
+
+ def test_linking_eager_compile(self):
+ self._test_linking(eager=True)
+
+ def test_linking_cu(self):
+ bar = cuda.declare_device('bar', 'int32(int32)')
+
+ link = str(test_data_dir / 'jitlink.cu')
+
+ @cuda.jit(link=[link])
+ def kernel(r, x):
+ i = cuda.grid(1)
+
+ if i < len(r):
+ r[i] = bar(x[i])
+
+ x = np.arange(10, dtype=np.int32)
+ r = np.zeros_like(x)
+
+ kernel[1, 32](r, x)
+
+ # Matches the operation of bar() in jitlink.cu
+ expected = x * 2
+ np.testing.assert_array_equal(r, expected)
+
+ def test_linking_cu_log_warning(self):
+ bar = cuda.declare_device('bar', 'int32(int32)')
+
+ link = str(test_data_dir / 'warn.cu')
+
+ with warnings.catch_warnings(record=True) as w:
+ ignore_internal_warnings()
+
+ @cuda.jit('void(int32)', link=[link])
+ def kernel(x):
+ bar(x)
+
+ self.assertEqual(len(w), 1, 'Expected warnings from NVRTC')
+ # Check the warning refers to the log messages
+ self.assertIn('NVRTC log messages', str(w[0].message))
+ # Check the message pertaining to the unused variable is provided
+ self.assertIn('declared but never referenced', str(w[0].message))
+
+ def test_linking_cu_error(self):
+ bar = cuda.declare_device('bar', 'int32(int32)')
+
+ link = str(test_data_dir / 'error.cu')
+
+ with self.assertRaises(NvrtcError) as e:
+ @cuda.jit('void(int32)', link=[link])
+ def kernel(x):
+ bar(x)
+
+ msg = e.exception.args[0]
+ # Check the error message refers to the NVRTC compile
+ self.assertIn('NVRTC Compilation failure', msg)
+ # Check the expected error in the CUDA source is reported
+ self.assertIn('identifier "SYNTAX" is undefined', msg)
+ # Check the filename is reported correctly
+ self.assertIn('in the compilation of "error.cu"', msg)
+
+ def test_linking_unknown_filetype_error(self):
+ expected_err = "Don't know how to link file with extension .cuh"
+ with self.assertRaisesRegex(RuntimeError, expected_err):
+ @cuda.jit('void()', link=['header.cuh'])
+ def kernel():
+ pass
+
+ def test_linking_file_with_no_extension_error(self):
+ expected_err = "Don't know how to link file with no extension"
+ with self.assertRaisesRegex(RuntimeError, expected_err):
+ @cuda.jit('void()', link=['data'])
+ def kernel():
+ pass
+
+ @skip_if_cuda_includes_missing
+ def test_linking_cu_cuda_include(self):
+ link = str(test_data_dir / 'cuda_include.cu')
+
+ # An exception will be raised when linking this kernel due to the
+ # compile failure if CUDA includes cannot be found by Nvrtc.
+ @cuda.jit('void()', link=[link])
+ def kernel():
+ pass
+
+ def test_try_to_link_nonexistent(self):
+ with self.assertRaises(LinkerError) as e:
+ @cuda.jit('void(int32[::1])', link=['nonexistent.a'])
+ def f(x):
+ x[0] = 0
+ self.assertIn('nonexistent.a not found', e.exception.args)
+
+ def test_set_registers_no_max(self):
+ """Ensure that the jitted kernel used in the test_set_registers_* tests
+ uses more than 57 registers - this ensures that test_set_registers_*
+ are really checking that they reduced the number of registers used from
+ something greater than the maximum."""
+ compiled = cuda.jit(func_with_lots_of_registers)
+ compiled = compiled.specialize(np.empty(32), *range(6))
+ self.assertGreater(compiled.get_regs_per_thread(), 57)
+
+ def test_set_registers_57(self):
+ compiled = cuda.jit(max_registers=57)(func_with_lots_of_registers)
+ compiled = compiled.specialize(np.empty(32), *range(6))
+ self.assertLessEqual(compiled.get_regs_per_thread(), 57)
+
+ def test_set_registers_38(self):
+ compiled = cuda.jit(max_registers=38)(func_with_lots_of_registers)
+ compiled = compiled.specialize(np.empty(32), *range(6))
+ self.assertLessEqual(compiled.get_regs_per_thread(), 38)
+
+ def test_set_registers_eager(self):
+ sig = void(float64[::1], int64, int64, int64, int64, int64, int64)
+ compiled = cuda.jit(sig, max_registers=38)(func_with_lots_of_registers)
+ self.assertLessEqual(compiled.get_regs_per_thread(), 38)
+
+ def test_get_const_mem_size(self):
+ sig = void(float64[::1])
+ compiled = cuda.jit(sig)(simple_const_mem)
+ const_mem_size = compiled.get_const_mem_size()
+ self.assertGreaterEqual(const_mem_size, CONST1D.nbytes)
+
+ def test_get_no_shared_memory(self):
+ compiled = cuda.jit(func_with_lots_of_registers)
+ compiled = compiled.specialize(np.empty(32), *range(6))
+ shared_mem_size = compiled.get_shared_mem_per_block()
+ self.assertEqual(shared_mem_size, 0)
+
+ def test_get_shared_mem_per_block(self):
+ sig = void(int32[::1], typeof(np.int32))
+ compiled = cuda.jit(sig)(simple_smem)
+ shared_mem_size = compiled.get_shared_mem_per_block()
+ self.assertEqual(shared_mem_size, 400)
+
+ def test_get_shared_mem_per_specialized(self):
+ compiled = cuda.jit(simple_smem)
+ compiled_specialized = compiled.specialize(
+ np.zeros(100, dtype=np.int32), np.float64)
+ shared_mem_size = compiled_specialized.get_shared_mem_per_block()
+ self.assertEqual(shared_mem_size, 800)
+
+ def test_get_max_threads_per_block(self):
+ compiled = cuda.jit("void(float32[:,::1])")(coop_smem2d)
+ max_threads = compiled.get_max_threads_per_block()
+ self.assertGreater(max_threads, 0)
+
+ def test_max_threads_exceeded(self):
+ compiled = cuda.jit("void(int32[::1])")(simple_maxthreads)
+ max_threads = compiled.get_max_threads_per_block()
+ nelem = max_threads + 1
+ ary = np.empty(nelem, dtype=np.int32)
+ try:
+ compiled[1, nelem](ary)
+ except CudaAPIError as e:
+ self.assertIn("cuLaunchKernel", e.msg)
+
+ def test_get_local_mem_per_thread(self):
+ sig = void(int32[::1], int32[::1], typeof(np.int32))
+ compiled = cuda.jit(sig)(simple_lmem)
+ local_mem_size = compiled.get_local_mem_per_thread()
+ calc_size = np.dtype(np.int32).itemsize * LMEM_SIZE
+ self.assertGreaterEqual(local_mem_size, calc_size)
+
+ def test_get_local_mem_per_specialized(self):
+ compiled = cuda.jit(simple_lmem)
+ compiled_specialized = compiled.specialize(
+ np.zeros(LMEM_SIZE, dtype=np.int32),
+ np.zeros(LMEM_SIZE, dtype=np.int32),
+ np.float64)
+ local_mem_size = compiled_specialized.get_local_mem_per_thread()
+ calc_size = np.dtype(np.float64).itemsize * LMEM_SIZE
+ self.assertGreaterEqual(local_mem_size, calc_size)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/test_managed_alloc.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/test_managed_alloc.py
new file mode 100644
index 0000000000000000000000000000000000000000..e9cc37ca84ad31274b226fc8841cca2093703194
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/test_managed_alloc.py
@@ -0,0 +1,127 @@
+import numpy as np
+from ctypes import byref, c_size_t
+from numba.cuda.cudadrv.driver import device_memset, driver, USE_NV_BINDING
+from numba import cuda
+from numba.cuda.testing import unittest, ContextResettingTestCase
+from numba.cuda.testing import skip_on_cudasim, skip_on_arm
+from numba.tests.support import linux_only
+
+
+@skip_on_cudasim('CUDA Driver API unsupported in the simulator')
+@linux_only
+@skip_on_arm('Managed Alloc support is experimental/untested on ARM')
+class TestManagedAlloc(ContextResettingTestCase):
+
+ def get_total_gpu_memory(self):
+ # We use a driver function to directly get the total GPU memory because
+ # an EMM plugin may report something different (or not implement
+ # get_memory_info at all).
+ if USE_NV_BINDING:
+ free, total = driver.cuMemGetInfo()
+ return total
+ else:
+ free = c_size_t()
+ total = c_size_t()
+ driver.cuMemGetInfo(byref(free), byref(total))
+ return total.value
+
+ def skip_if_cc_major_lt(self, min_required, reason):
+ """
+ Skip the current test if the compute capability of the device is
+ less than `min_required`.
+ """
+ ctx = cuda.current_context()
+ cc_major = ctx.device.compute_capability[0]
+ if cc_major < min_required:
+ self.skipTest(reason)
+
+ # CUDA Unified Memory comes in two flavors. For GPUs in the Kepler and
+ # Maxwell generations, managed memory allocations work as opaque,
+ # contiguous segments that can either be on the device or the host. For
+ # GPUs in the Pascal or later generations, managed memory operates on a
+ # per-page basis, so we can have arrays larger than GPU memory, where only
+ # part of them is resident on the device at one time. To ensure that this
+ # test works correctly on all supported GPUs, we'll select the size of our
+ # memory such that we only oversubscribe the GPU memory if we're on a
+ # Pascal or newer GPU (compute capability at least 6.0).
+
+ def test_managed_alloc_driver_undersubscribe(self):
+ msg = "Managed memory unsupported prior to CC 3.0"
+ self.skip_if_cc_major_lt(3, msg)
+ self._test_managed_alloc_driver(0.5)
+
+ # This test is skipped by default because it is easy to hang the machine
+ # for a very long time or get OOM killed if the GPU memory size is >50% of
+ # the system memory size. Even if the system does have more than 2x the RAM
+ # of the GPU, this test runs for a very long time (in comparison to the
+ # rest of the tests in the suite).
+ #
+ # However, it is left in here for manual testing as required.
+
+ @unittest.skip
+ def test_managed_alloc_driver_oversubscribe(self):
+ msg = "Oversubscription of managed memory unsupported prior to CC 6.0"
+ self.skip_if_cc_major_lt(6, msg)
+ self._test_managed_alloc_driver(2.0)
+
+ def test_managed_alloc_driver_host_attach(self):
+ msg = "Host attached managed memory is not accessible prior to CC 6.0"
+ self.skip_if_cc_major_lt(6, msg)
+ # Only test with a small array (0.01 * memory size) to keep the test
+ # quick.
+ self._test_managed_alloc_driver(0.01, attach_global=False)
+
+ def _test_managed_alloc_driver(self, memory_factor, attach_global=True):
+ # Verify that we can allocate and operate on managed
+ # memory through the CUDA driver interface.
+
+ total_mem_size = self.get_total_gpu_memory()
+ n_bytes = int(memory_factor * total_mem_size)
+
+ ctx = cuda.current_context()
+ mem = ctx.memallocmanaged(n_bytes, attach_global=attach_global)
+
+ dtype = np.dtype(np.uint8)
+ n_elems = n_bytes // dtype.itemsize
+ ary = np.ndarray(shape=n_elems, dtype=dtype, buffer=mem)
+
+ magic = 0xab
+ device_memset(mem, magic, n_bytes)
+ ctx.synchronize()
+
+ # Note that this assertion operates on the CPU, so this
+ # test effectively drives both the CPU and the GPU on
+ # managed memory.
+
+ self.assertTrue(np.all(ary == magic))
+
+ def _test_managed_array(self, attach_global=True):
+ # Check the managed_array interface on both host and device.
+
+ ary = cuda.managed_array(100, dtype=np.double)
+ ary.fill(123.456)
+ self.assertTrue(all(ary == 123.456))
+
+ @cuda.jit('void(double[:])')
+ def kernel(x):
+ i = cuda.grid(1)
+ if i < x.shape[0]:
+ x[i] = 1.0
+
+ kernel[10, 10](ary)
+ cuda.current_context().synchronize()
+
+ self.assertTrue(all(ary == 1.0))
+
+ def test_managed_array_attach_global(self):
+ self._test_managed_array()
+
+ def test_managed_array_attach_host(self):
+ self._test_managed_array()
+ msg = "Host attached managed memory is not accessible prior to CC 6.0"
+ self.skip_if_cc_major_lt(6, msg)
+ self._test_managed_array(attach_global=False)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/test_mvc.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/test_mvc.py
new file mode 100644
index 0000000000000000000000000000000000000000..c25bc5ae2d1f46b3f873e921e92c7e53ede33fa6
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/test_mvc.py
@@ -0,0 +1,54 @@
+import multiprocessing as mp
+import traceback
+from numba.cuda.testing import unittest, CUDATestCase
+from numba.cuda.testing import (skip_on_cudasim, skip_under_cuda_memcheck,
+ skip_if_mvc_libraries_unavailable)
+from numba.tests.support import linux_only
+
+
+def child_test():
+ from numba import config, cuda
+
+ # Change the MVC config after importing numba.cuda
+ config.CUDA_ENABLE_MINOR_VERSION_COMPATIBILITY = 1
+
+ @cuda.jit
+ def f():
+ pass
+
+ f[1, 1]()
+
+
+def child_test_wrapper(result_queue):
+ try:
+ output = child_test()
+ success = True
+ # Catch anything raised so it can be propagated
+ except: # noqa: E722
+ output = traceback.format_exc()
+ success = False
+
+ result_queue.put((success, output))
+
+
+@linux_only
+@skip_under_cuda_memcheck('May hang CUDA memcheck')
+@skip_on_cudasim('Simulator does not require or implement MVC')
+@skip_if_mvc_libraries_unavailable
+class TestMinorVersionCompatibility(CUDATestCase):
+ def test_mvc(self):
+ # Run test with Minor Version Compatibility enabled in a child process
+ ctx = mp.get_context('spawn')
+ result_queue = ctx.Queue()
+ proc = ctx.Process(target=child_test_wrapper, args=(result_queue,))
+ proc.start()
+ proc.join()
+ success, output = result_queue.get()
+
+ # Ensure the child process ran to completion before checking its output
+ if not success:
+ self.fail(output)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/test_nvvm_driver.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/test_nvvm_driver.py
new file mode 100644
index 0000000000000000000000000000000000000000..6e560764c50566579f83c84c6f23d9043b1bab37
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/test_nvvm_driver.py
@@ -0,0 +1,199 @@
+import warnings
+
+from llvmlite import ir
+from numba.cuda.cudadrv import nvvm, runtime
+from numba.cuda.testing import unittest
+from numba.cuda.cudadrv.nvvm import LibDevice, NvvmError, NVVM
+from numba.cuda.testing import skip_on_cudasim
+
+
+@skip_on_cudasim('NVVM Driver unsupported in the simulator')
+class TestNvvmDriver(unittest.TestCase):
+ def get_nvvmir(self):
+ versions = NVVM().get_ir_version()
+ data_layout = NVVM().data_layout
+ return nvvmir_generic.format(data_layout=data_layout, v=versions)
+
+ def test_nvvm_compile_simple(self):
+ nvvmir = self.get_nvvmir()
+ ptx = nvvm.compile_ir(nvvmir).decode('utf8')
+ self.assertTrue('simple' in ptx)
+ self.assertTrue('ave' in ptx)
+
+ def test_nvvm_compile_nullary_option(self):
+ # Tests compilation with an option that doesn't take an argument
+ # ("-gen-lto") - all other NVVM options are of the form
+ # "-="
+
+ # -gen-lto is not available prior to CUDA 11.5
+ if runtime.get_version() < (11, 5):
+ self.skipTest("-gen-lto unavailable in this toolkit version")
+
+ nvvmir = self.get_nvvmir()
+ ltoir = nvvm.compile_ir(nvvmir, opt=3, gen_lto=None, arch="compute_52")
+
+ # Verify we correctly passed the option by checking if we got LTOIR
+ # from NVVM (by looking for the expected magic number for LTOIR)
+ self.assertEqual(ltoir[:4], b'\xed\x43\x4e\x7f')
+
+ def test_nvvm_bad_option(self):
+ # Ensure that unsupported / non-existent options are reported as such
+ # to the user / caller
+ msg = "-made-up-option=2 is an unsupported option"
+ with self.assertRaisesRegex(NvvmError, msg):
+ nvvm.compile_ir("", made_up_option=2)
+
+ def test_nvvm_from_llvm(self):
+ m = ir.Module("test_nvvm_from_llvm")
+ m.triple = 'nvptx64-nvidia-cuda'
+ nvvm.add_ir_version(m)
+ fty = ir.FunctionType(ir.VoidType(), [ir.IntType(32)])
+ kernel = ir.Function(m, fty, name='mycudakernel')
+ bldr = ir.IRBuilder(kernel.append_basic_block('entry'))
+ bldr.ret_void()
+ nvvm.set_cuda_kernel(kernel)
+
+ m.data_layout = NVVM().data_layout
+ ptx = nvvm.compile_ir(str(m)).decode('utf8')
+ self.assertTrue('mycudakernel' in ptx)
+ self.assertTrue('.address_size 64' in ptx)
+
+ def test_used_list(self):
+ # Construct a module
+ m = ir.Module("test_used_list")
+ m.triple = 'nvptx64-nvidia-cuda'
+ m.data_layout = NVVM().data_layout
+ nvvm.add_ir_version(m)
+
+ # Add a function and mark it as a kernel
+ fty = ir.FunctionType(ir.VoidType(), [ir.IntType(32)])
+ kernel = ir.Function(m, fty, name='mycudakernel')
+ bldr = ir.IRBuilder(kernel.append_basic_block('entry'))
+ bldr.ret_void()
+ nvvm.set_cuda_kernel(kernel)
+
+ # Verify that the used list was correctly constructed
+ used_lines = [line for line in str(m).splitlines()
+ if 'llvm.used' in line]
+ msg = 'Expected exactly one @"llvm.used" array'
+ self.assertEqual(len(used_lines), 1, msg)
+
+ used_line = used_lines[0]
+ # Kernel should be referenced in the used list
+ self.assertIn("mycudakernel", used_line)
+ # Check linkage of the used list
+ self.assertIn("appending global", used_line)
+ # Ensure used list is in the metadata section
+ self.assertIn('section "llvm.metadata"', used_line)
+
+ def test_nvvm_ir_verify_fail(self):
+ m = ir.Module("test_bad_ir")
+ m.triple = "unknown-unknown-unknown"
+ m.data_layout = NVVM().data_layout
+ nvvm.add_ir_version(m)
+ with self.assertRaisesRegex(NvvmError, 'Invalid target triple'):
+ nvvm.compile_ir(str(m))
+
+ def _test_nvvm_support(self, arch):
+ compute_xx = 'compute_{0}{1}'.format(*arch)
+ nvvmir = self.get_nvvmir()
+ ptx = nvvm.compile_ir(nvvmir, arch=compute_xx, ftz=1, prec_sqrt=0,
+ prec_div=0).decode('utf8')
+ self.assertIn(".target sm_{0}{1}".format(*arch), ptx)
+ self.assertIn('simple', ptx)
+ self.assertIn('ave', ptx)
+
+ def test_nvvm_support(self):
+ """Test supported CC by NVVM
+ """
+ for arch in nvvm.get_supported_ccs():
+ self._test_nvvm_support(arch=arch)
+
+ def test_nvvm_warning(self):
+ m = ir.Module("test_nvvm_warning")
+ m.triple = 'nvptx64-nvidia-cuda'
+ m.data_layout = NVVM().data_layout
+ nvvm.add_ir_version(m)
+
+ fty = ir.FunctionType(ir.VoidType(), [])
+ kernel = ir.Function(m, fty, name='inlinekernel')
+ builder = ir.IRBuilder(kernel.append_basic_block('entry'))
+ builder.ret_void()
+ nvvm.set_cuda_kernel(kernel)
+
+ # Add the noinline attribute to trigger NVVM to generate a warning
+ kernel.attributes.add('noinline')
+
+ with warnings.catch_warnings(record=True) as w:
+ nvvm.compile_ir(str(m))
+
+ self.assertEqual(len(w), 1)
+ self.assertIn('overriding noinline attribute', str(w[0]))
+
+
+@skip_on_cudasim('NVVM Driver unsupported in the simulator')
+class TestArchOption(unittest.TestCase):
+ def test_get_arch_option(self):
+ # Test returning the nearest lowest arch.
+ self.assertEqual(nvvm.get_arch_option(5, 3), 'compute_53')
+ self.assertEqual(nvvm.get_arch_option(7, 5), 'compute_75')
+ self.assertEqual(nvvm.get_arch_option(7, 7), 'compute_75')
+ # Test known arch.
+ supported_cc = nvvm.get_supported_ccs()
+ for arch in supported_cc:
+ self.assertEqual(nvvm.get_arch_option(*arch), 'compute_%d%d' % arch)
+ self.assertEqual(nvvm.get_arch_option(1000, 0),
+ 'compute_%d%d' % supported_cc[-1])
+
+
+@skip_on_cudasim('NVVM Driver unsupported in the simulator')
+class TestLibDevice(unittest.TestCase):
+ def test_libdevice_load(self):
+ # Test that constructing LibDevice gives a bitcode file
+ libdevice = LibDevice()
+ self.assertEqual(libdevice.bc[:4], b'BC\xc0\xde')
+
+
+nvvmir_generic = '''\
+target triple="nvptx64-nvidia-cuda"
+target datalayout = "{data_layout}"
+
+define i32 @ave(i32 %a, i32 %b) {{
+entry:
+%add = add nsw i32 %a, %b
+%div = sdiv i32 %add, 2
+ret i32 %div
+}}
+
+define void @simple(i32* %data) {{
+entry:
+%0 = call i32 @llvm.nvvm.read.ptx.sreg.ctaid.x()
+%1 = call i32 @llvm.nvvm.read.ptx.sreg.ntid.x()
+%mul = mul i32 %0, %1
+%2 = call i32 @llvm.nvvm.read.ptx.sreg.tid.x()
+%add = add i32 %mul, %2
+%call = call i32 @ave(i32 %add, i32 %add)
+%idxprom = sext i32 %add to i64
+%arrayidx = getelementptr inbounds i32, i32* %data, i64 %idxprom
+store i32 %call, i32* %arrayidx, align 4
+ret void
+}}
+
+declare i32 @llvm.nvvm.read.ptx.sreg.ctaid.x() nounwind readnone
+
+declare i32 @llvm.nvvm.read.ptx.sreg.ntid.x() nounwind readnone
+
+declare i32 @llvm.nvvm.read.ptx.sreg.tid.x() nounwind readnone
+
+!nvvmir.version = !{{!1}}
+!1 = !{{i32 {v[0]}, i32 {v[1]}, i32 {v[2]}, i32 {v[3]}}}
+
+!nvvm.annotations = !{{!2}}
+!2 = !{{void (i32*)* @simple, !"kernel", i32 1}}
+
+@"llvm.used" = appending global [1 x i8*] [i8* bitcast (void (i32*)* @simple to i8*)], section "llvm.metadata"
+''' # noqa: E501
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/test_pinned.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/test_pinned.py
new file mode 100644
index 0000000000000000000000000000000000000000..ef727c5a89cbcd84ef813a7227b0654ab3070f68
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/test_pinned.py
@@ -0,0 +1,37 @@
+import numpy as np
+import platform
+
+from numba import cuda
+from numba.cuda.testing import unittest, ContextResettingTestCase
+
+
+class TestPinned(ContextResettingTestCase):
+
+ def _run_copies(self, A):
+ A0 = np.copy(A)
+
+ stream = cuda.stream()
+ ptr = cuda.to_device(A, copy=False, stream=stream)
+ ptr.copy_to_device(A, stream=stream)
+ ptr.copy_to_host(A, stream=stream)
+ stream.synchronize()
+
+ self.assertTrue(np.allclose(A, A0))
+
+ def test_pinned(self):
+ machine = platform.machine()
+ if machine.startswith('arm') or machine.startswith('aarch64'):
+ count = 262144 # 2MB
+ else:
+ count = 2097152 # 16MB
+ A = np.arange(count)
+ with cuda.pinned(A):
+ self._run_copies(A)
+
+ def test_unpinned(self):
+ A = np.arange(2 * 1024 * 1024) # 16 MB
+ self._run_copies(A)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/test_profiler.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/test_profiler.py
new file mode 100644
index 0000000000000000000000000000000000000000..1660d4d42fc1de142d4762a0ed7859278f99f2fb
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/test_profiler.py
@@ -0,0 +1,20 @@
+import unittest
+from numba.cuda.testing import ContextResettingTestCase
+from numba import cuda
+from numba.cuda.testing import skip_on_cudasim
+
+
+@skip_on_cudasim('CUDA Profiler unsupported in the simulator')
+class TestProfiler(ContextResettingTestCase):
+ def test_profiling(self):
+ with cuda.profiling():
+ a = cuda.device_array(10)
+ del a
+
+ with cuda.profiling():
+ a = cuda.device_array(100)
+ del a
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/test_ptds.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/test_ptds.py
new file mode 100644
index 0000000000000000000000000000000000000000..b03fd3647aeac35c0375c5947b072aaefa56bf1c
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/test_ptds.py
@@ -0,0 +1,149 @@
+import multiprocessing as mp
+import logging
+import traceback
+from numba.cuda.testing import unittest, CUDATestCase
+from numba.cuda.testing import (skip_on_cudasim, skip_with_cuda_python,
+ skip_under_cuda_memcheck)
+from numba.tests.support import linux_only
+
+
+def child_test():
+ from numba import cuda, int32, void
+ from numba.core import config
+ import io
+ import numpy as np
+ import threading
+
+ # Enable PTDS before we make any CUDA driver calls. Enabling it first
+ # ensures that PTDS APIs are used because the CUDA driver looks up API
+ # functions on first use and memoizes them.
+ config.CUDA_PER_THREAD_DEFAULT_STREAM = 1
+
+ # Set up log capture for the Driver API so we can see what API calls were
+ # used.
+ logbuf = io.StringIO()
+ handler = logging.StreamHandler(logbuf)
+ cudadrv_logger = logging.getLogger('numba.cuda.cudadrv.driver')
+ cudadrv_logger.addHandler(handler)
+ cudadrv_logger.setLevel(logging.DEBUG)
+
+ # Set up data for our test, and copy over to the device
+ N = 2 ** 16
+ N_THREADS = 10
+ N_ADDITIONS = 4096
+
+ # Seed the RNG for repeatability
+ np.random.seed(1)
+ x = np.random.randint(low=0, high=1000, size=N, dtype=np.int32)
+ r = np.zeros_like(x)
+
+ # One input and output array for each thread
+ xs = [cuda.to_device(x) for _ in range(N_THREADS)]
+ rs = [cuda.to_device(r) for _ in range(N_THREADS)]
+
+ # Compute the grid size and get the [per-thread] default stream
+ n_threads = 256
+ n_blocks = N // n_threads
+ stream = cuda.default_stream()
+
+ # A simple multiplication-by-addition kernel. What it does exactly is not
+ # too important; only that we have a kernel that does something.
+ @cuda.jit(void(int32[::1], int32[::1]))
+ def f(r, x):
+ i = cuda.grid(1)
+
+ if i > len(r):
+ return
+
+ # Accumulate x into r
+ for j in range(N_ADDITIONS):
+ r[i] += x[i]
+
+ # This function will be used to launch the kernel from each thread on its
+ # own unique data.
+ def kernel_thread(n):
+ f[n_blocks, n_threads, stream](rs[n], xs[n])
+
+ # Create threads
+ threads = [threading.Thread(target=kernel_thread, args=(i,))
+ for i in range(N_THREADS)]
+
+ # Start all threads
+ for thread in threads:
+ thread.start()
+
+ # Wait for all threads to finish, to ensure that we don't synchronize with
+ # the device until all kernels are scheduled.
+ for thread in threads:
+ thread.join()
+
+ # Synchronize with the device
+ cuda.synchronize()
+
+ # Check output is as expected
+ expected = x * N_ADDITIONS
+ for i in range(N_THREADS):
+ np.testing.assert_equal(rs[i].copy_to_host(), expected)
+
+ # Return the driver log output to the calling process for checking
+ handler.flush()
+ return logbuf.getvalue()
+
+
+def child_test_wrapper(result_queue):
+ try:
+ output = child_test()
+ success = True
+ # Catch anything raised so it can be propagated
+ except: # noqa: E722
+ output = traceback.format_exc()
+ success = False
+
+ result_queue.put((success, output))
+
+
+# Run on Linux only until the reason for test hangs on Windows (Issue #8635,
+# https://github.com/numba/numba/issues/8635) is diagnosed
+@linux_only
+@skip_under_cuda_memcheck('Hangs cuda-memcheck')
+@skip_on_cudasim('Streams not supported on the simulator')
+class TestPTDS(CUDATestCase):
+ @skip_with_cuda_python('Function names unchanged for PTDS with NV Binding')
+ def test_ptds(self):
+ # Run a test with PTDS enabled in a child process
+ ctx = mp.get_context('spawn')
+ result_queue = ctx.Queue()
+ proc = ctx.Process(target=child_test_wrapper, args=(result_queue,))
+ proc.start()
+ proc.join()
+ success, output = result_queue.get()
+
+ # Ensure the child process ran to completion before checking its output
+ if not success:
+ self.fail(output)
+
+ # Functions with a per-thread default stream variant that we expect to
+ # see in the output
+ ptds_functions = ('cuMemcpyHtoD_v2_ptds', 'cuLaunchKernel_ptsz',
+ 'cuMemcpyDtoH_v2_ptds')
+
+ for fn in ptds_functions:
+ with self.subTest(fn=fn, expected=True):
+ self.assertIn(fn, output)
+
+ # Non-PTDS versions of the functions that we should not see in the
+ # output:
+ legacy_functions = ('cuMemcpyHtoD_v2', 'cuLaunchKernel',
+ 'cuMemcpyDtoH_v2')
+
+ for fn in legacy_functions:
+ with self.subTest(fn=fn, expected=False):
+ # Ensure we only spot these function names appearing without a
+ # _ptds or _ptsz suffix by checking including the end of the
+ # line in the log
+ fn_at_end = f'{fn}\n'
+ self.assertNotIn(fn_at_end, output)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/test_reset_device.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/test_reset_device.py
new file mode 100644
index 0000000000000000000000000000000000000000..f2e0b6d108dda4cdf58ec340ede7a429b556cefc
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/test_reset_device.py
@@ -0,0 +1,36 @@
+import threading
+from numba import cuda
+from numba.cuda.cudadrv.driver import driver
+from numba.cuda.testing import unittest, ContextResettingTestCase
+from queue import Queue
+
+
+class TestResetDevice(ContextResettingTestCase):
+ def test_reset_device(self):
+
+ def newthread(exception_queue):
+ try:
+ devices = range(driver.get_device_count())
+ for _ in range(2):
+ for d in devices:
+ cuda.select_device(d)
+ cuda.close()
+ except Exception as e:
+ exception_queue.put(e)
+
+ # Do test on a separate thread so that we don't affect
+ # the current context in the main thread.
+
+ exception_queue = Queue()
+ t = threading.Thread(target=newthread, args=(exception_queue,))
+ t.start()
+ t.join()
+
+ exceptions = []
+ while not exception_queue.empty():
+ exceptions.append(exception_queue.get())
+ self.assertEqual(exceptions, [])
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/test_runtime.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/test_runtime.py
new file mode 100644
index 0000000000000000000000000000000000000000..51e0722eca4eb2f3868ebdff47e1b85ac224efcc
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/test_runtime.py
@@ -0,0 +1,85 @@
+import multiprocessing
+import os
+from numba.core import config
+from numba.cuda.cudadrv.runtime import runtime
+from numba.cuda.testing import unittest, SerialMixin, skip_on_cudasim
+from unittest.mock import patch
+
+
+def set_visible_devices_and_check(q):
+ try:
+ from numba import cuda
+ import os
+
+ os.environ['CUDA_VISIBLE_DEVICES'] = '0'
+ q.put(len(cuda.gpus.lst))
+ except: # noqa: E722
+ # Sentinel value for error executing test code
+ q.put(-1)
+
+
+if config.ENABLE_CUDASIM:
+ SUPPORTED_VERSIONS = (-1, -1),
+else:
+ SUPPORTED_VERSIONS = ((11, 0), (11, 1), (11, 2), (11, 3), (11, 4), (11, 5),
+ (11, 6), (11, 7))
+
+
+class TestRuntime(unittest.TestCase):
+ def test_is_supported_version_true(self):
+ for v in SUPPORTED_VERSIONS:
+ with patch.object(runtime, 'get_version', return_value=v):
+ self.assertTrue(runtime.is_supported_version())
+
+ @skip_on_cudasim('The simulator always simulates a supported runtime')
+ def test_is_supported_version_false(self):
+ # Check with an old unsupported version and some potential future
+ # versions
+ for v in ((10, 2), (11, 8), (12, 0)):
+ with patch.object(runtime, 'get_version', return_value=v):
+ self.assertFalse(runtime.is_supported_version())
+
+ def test_supported_versions(self):
+ self.assertEqual(SUPPORTED_VERSIONS, runtime.supported_versions)
+
+
+class TestVisibleDevices(unittest.TestCase, SerialMixin):
+ def test_visible_devices_set_after_import(self):
+ # See Issue #6149. This test checks that we can set
+ # CUDA_VISIBLE_DEVICES after importing Numba and have the value
+ # reflected in the available list of GPUs. Prior to the fix for this
+ # issue, Numba made a call to runtime.get_version() on import that
+ # initialized the driver and froze the list of available devices before
+ # CUDA_VISIBLE_DEVICES could be set by the user.
+
+ # Avoid importing cuda at the top level so that
+ # set_visible_devices_and_check gets to import it first in its process
+ from numba import cuda
+
+ if len(cuda.gpus.lst) in (0, 1):
+ self.skipTest('This test requires multiple GPUs')
+
+ if os.environ.get('CUDA_VISIBLE_DEVICES'):
+ msg = 'Cannot test when CUDA_VISIBLE_DEVICES already set'
+ self.skipTest(msg)
+
+ ctx = multiprocessing.get_context('spawn')
+ q = ctx.Queue()
+ p = ctx.Process(target=set_visible_devices_and_check, args=(q,))
+ p.start()
+ try:
+ visible_gpu_count = q.get()
+ finally:
+ p.join()
+
+ # Make an obvious distinction between an error running the test code
+ # and an incorrect number of GPUs in the list
+ msg = 'Error running set_visible_devices_and_check'
+ self.assertNotEqual(visible_gpu_count, -1, msg=msg)
+
+ # The actual check that we see only one GPU
+ self.assertEqual(visible_gpu_count, 1)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/test_select_device.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/test_select_device.py
new file mode 100644
index 0000000000000000000000000000000000000000..aca78d94bff59d41966b24ceca026284692c8a51
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/test_select_device.py
@@ -0,0 +1,41 @@
+#
+# Test does not work on some cards.
+#
+import threading
+from queue import Queue
+
+import numpy as np
+from numba import cuda
+from numba.cuda.testing import unittest, ContextResettingTestCase
+
+
+def newthread(exception_queue):
+ try:
+ cuda.select_device(0)
+ stream = cuda.stream()
+ A = np.arange(100)
+ dA = cuda.to_device(A, stream=stream)
+ stream.synchronize()
+ del dA
+ del stream
+ cuda.close()
+ except Exception as e:
+ exception_queue.put(e)
+
+
+class TestSelectDevice(ContextResettingTestCase):
+ def test_select_device(self):
+ exception_queue = Queue()
+ for i in range(10):
+ t = threading.Thread(target=newthread, args=(exception_queue,))
+ t.start()
+ t.join()
+
+ exceptions = []
+ while not exception_queue.empty():
+ exceptions.append(exception_queue.get())
+ self.assertEqual(exceptions, [])
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/test_streams.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/test_streams.py
new file mode 100644
index 0000000000000000000000000000000000000000..c4fbec19f7a7c64bd09b820a854af07f180ca1b3
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudadrv/test_streams.py
@@ -0,0 +1,122 @@
+import asyncio
+import functools
+import threading
+import numpy as np
+from numba import cuda
+from numba.cuda.testing import unittest, CUDATestCase, skip_on_cudasim
+
+
+def with_asyncio_loop(f):
+ @functools.wraps(f)
+ def runner(*args, **kwds):
+ loop = asyncio.new_event_loop()
+ loop.set_debug(True)
+ try:
+ return loop.run_until_complete(f(*args, **kwds))
+ finally:
+ loop.close()
+ return runner
+
+
+@skip_on_cudasim('CUDA Driver API unsupported in the simulator')
+class TestCudaStream(CUDATestCase):
+ def test_add_callback(self):
+ def callback(stream, status, event):
+ event.set()
+
+ stream = cuda.stream()
+ callback_event = threading.Event()
+ stream.add_callback(callback, callback_event)
+ self.assertTrue(callback_event.wait(1.0))
+
+ def test_add_callback_with_default_arg(self):
+ callback_event = threading.Event()
+
+ def callback(stream, status, arg):
+ self.assertIsNone(arg)
+ callback_event.set()
+
+ stream = cuda.stream()
+ stream.add_callback(callback)
+ self.assertTrue(callback_event.wait(1.0))
+
+ @with_asyncio_loop
+ async def test_async_done(self):
+ stream = cuda.stream()
+ await stream.async_done()
+
+ @with_asyncio_loop
+ async def test_parallel_tasks(self):
+ async def async_cuda_fn(value_in: float) -> float:
+ stream = cuda.stream()
+ h_src, h_dst = cuda.pinned_array(8), cuda.pinned_array(8)
+ h_src[:] = value_in
+ d_ary = cuda.to_device(h_src, stream=stream)
+ d_ary.copy_to_host(h_dst, stream=stream)
+ done_result = await stream.async_done()
+ self.assertEqual(done_result, stream)
+ return h_dst.mean()
+
+ values_in = [1, 2, 3, 4]
+ tasks = [asyncio.create_task(async_cuda_fn(v)) for v in values_in]
+ values_out = await asyncio.gather(*tasks)
+ self.assertTrue(np.allclose(values_in, values_out))
+
+ @with_asyncio_loop
+ async def test_multiple_async_done(self):
+ stream = cuda.stream()
+ done_aws = [stream.async_done() for _ in range(4)]
+ done = await asyncio.gather(*done_aws)
+ for d in done:
+ self.assertEqual(d, stream)
+
+ @with_asyncio_loop
+ async def test_multiple_async_done_multiple_streams(self):
+ streams = [cuda.stream() for _ in range(4)]
+ done_aws = [stream.async_done() for stream in streams]
+ done = await asyncio.gather(*done_aws)
+
+ # Ensure we got the four original streams in done
+ self.assertSetEqual(set(done), set(streams))
+
+ @with_asyncio_loop
+ async def test_cancelled_future(self):
+ stream = cuda.stream()
+ done1, done2 = stream.async_done(), stream.async_done()
+ done1.cancel()
+ await done2
+ self.assertTrue(done1.cancelled())
+ self.assertTrue(done2.done())
+
+
+@skip_on_cudasim('CUDA Driver API unsupported in the simulator')
+class TestFailingStream(CUDATestCase):
+ # This test can only be run in isolation because it corrupts the CUDA
+ # context, which cannot be recovered from within the same process. It is
+ # left here so that it can be run manually for debugging / testing purposes
+ # - or may be re-enabled if in future there is infrastructure added for
+ # running tests in a separate process (a subprocess cannot be used because
+ # CUDA will have been initialized before the fork, so it cannot be used in
+ # the child process).
+ @unittest.skip
+ @with_asyncio_loop
+ async def test_failed_stream(self):
+ ctx = cuda.current_context()
+ module = ctx.create_module_ptx("""
+ .version 6.5
+ .target sm_30
+ .address_size 64
+ .visible .entry failing_kernel() { trap; }
+ """)
+ failing_kernel = module.get_function("failing_kernel")
+
+ stream = cuda.stream()
+ failing_kernel.configure((1,), (1,), stream=stream).__call__()
+ done = stream.async_done()
+ with self.assertRaises(Exception):
+ await done
+ self.assertIsNotNone(done.exception())
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..d9e7d31af3b99e121a9ae04bc855a6c80cc4594d
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__init__.py
@@ -0,0 +1,8 @@
+from numba.cuda.testing import ensure_supported_ccs_initialized
+from numba.testing import load_testsuite
+import os
+
+
+def load_tests(loader, tests, pattern):
+ ensure_supported_ccs_initialized()
+ return load_testsuite(loader, os.path.dirname(__file__))
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3ef420002fddd434a3332e06920b6aa22ea99237
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/cache_usecases.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/cache_usecases.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9e322283e4c0f97a2977ec5724472d0bab3835ae
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/cache_usecases.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/cache_with_cpu_usecases.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/cache_with_cpu_usecases.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0c6bfd2cab6da13360575f8eec27d14bd9528a49
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/cache_with_cpu_usecases.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/extensions_usecases.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/extensions_usecases.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2078d906f494ca2ef5670b8d21c1221f13fe076a
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/extensions_usecases.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/recursion_usecases.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/recursion_usecases.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9cd7f570ff618363ab0acb756c467cf7223f9499
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/recursion_usecases.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_alignment.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_alignment.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3ae95cf5f2f43c2eac82c1604a8dc04f869f6360
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_alignment.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_array.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_array.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..91494619ac69829ac7c79d38b6cf428817d54af5
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_array.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_array_args.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_array_args.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0983dc64b948e29a0e33efa459c3795876389b89
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_array_args.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_array_methods.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_array_methods.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0054d38ccd75eaca5645d79f690c4d5d98cbb460
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_array_methods.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_atomics.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_atomics.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..64d882344ba6297cf7ea85eddf7284ea630b6691
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_atomics.cpython-312.pyc
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:0284ba5ec506dc700ed0caef54f993f5e066dba6a4ca397023add98286946a56
+size 108999
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_blackscholes.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_blackscholes.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..605ac4492827666fcc4bb6441caa5f39bfe67c8d
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_blackscholes.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_boolean.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_boolean.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..678ce6b5b4539afbb9efa27850a4976a3717dc9d
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_boolean.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_caching.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_caching.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..87573e959c1e31fe1d5129bf0b96ade18a24bd3f
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_caching.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_casting.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_casting.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..370cd938ea5146b1b00a1baa2dfba44265930226
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_casting.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_cffi.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_cffi.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7f98ca628af797e8a504301415f6a50c689dd50b
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_cffi.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_compiler.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_compiler.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6c03356b55e92f0a401ade72f48b4acc740e74b8
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_compiler.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_complex.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_complex.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ba8d9591c0b7bafb1bb1a6c60cbf36deddf20ab4
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_complex.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_complex_kernel.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_complex_kernel.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..32d943796ef5c264b01edb35edb9c8e3c720a11f
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_complex_kernel.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_const_string.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_const_string.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f2a3d7bbbe9c114a5f59d6453e3539e72644f58a
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_const_string.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_constmem.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_constmem.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e1f853e2513cad04d7e462563215850595df111d
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_constmem.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_cooperative_groups.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_cooperative_groups.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1625797ac72bae26007ead8dbd697dc3c74bd603
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_cooperative_groups.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_cuda_array_interface.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_cuda_array_interface.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a4aa5e616873e4bf9df8b2017f9f375e899d6d7b
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_cuda_array_interface.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_cuda_jit_no_types.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_cuda_jit_no_types.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a50de51bac9af3176022845734cb4372ed9aed0e
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_cuda_jit_no_types.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_datetime.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_datetime.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..385b15e36abe3a1c86ea0cc07f685ad80b128cb3
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_datetime.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_debug.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_debug.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a84182ce64b39ebb3eb7777d213267c641217fa8
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_debug.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_debuginfo.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_debuginfo.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7d272af426e48ec10ec2eed41d8a8e1f6bc55ef9
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_debuginfo.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_device_func.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_device_func.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4b7a44708b90900d4d4402799f797e0df451bd19
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_device_func.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_dispatcher.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_dispatcher.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5c27897b2770ca24f4ae70da7d029b1da9857ebb
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_dispatcher.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_enums.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_enums.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..72c8de0c313c4de1676b95ac263fd9ba9cf5726d
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_enums.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_errors.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_errors.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4af09aa04ca16462c4effcca67f86968db16aa61
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_errors.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_exception.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_exception.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..25c0b8ba6d64e34f2ae8901f508aee43f813909c
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_exception.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_extending.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_extending.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b18ed5f42609d983abf0696523c345473a271a91
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_extending.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_fastmath.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_fastmath.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6624f6d476899ffd1f8eb8400e04bcba8b40cb17
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_fastmath.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_forall.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_forall.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4f7e770c8de4267eec552cb72a57c1f97fbfa84a
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_forall.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_freevar.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_freevar.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6c6e86f0b1c6ef97c3bb3ded7f3f71ab5ec2b7a5
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_freevar.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_frexp_ldexp.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_frexp_ldexp.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e6778b7ec194d5dfdbad3fcf13a97e2b10a40b83
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_frexp_ldexp.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_globals.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_globals.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bc7409b24c17ab92d881341497c247c3ffae1f0c
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_globals.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_gufunc.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_gufunc.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..22e87322e68c082e5211e04fd52b3a86ef031d19
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_gufunc.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_gufunc_scalar.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_gufunc_scalar.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a2358560ed03bfcb6a3f27bc55d01b0a72d13dc2
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_gufunc_scalar.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_gufunc_scheduling.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_gufunc_scheduling.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f6903446ae3a302b2579b13d966971c0502bb7be
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_gufunc_scheduling.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_idiv.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_idiv.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2b11a1e4bda4b064944f933e1b56fb5896978b9a
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_idiv.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_inspect.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_inspect.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..20fcfb29dfa5aaec2d58c51d56f1cda02f0889dc
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_inspect.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_intrinsics.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_intrinsics.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fbfcc65adda3a895be1785b5d0683d7923723af6
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_intrinsics.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_ipc.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_ipc.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a17da969c5223b812f3cf578422697b9baee5ce6
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_ipc.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_iterators.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_iterators.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..13bffe1d29a551c9edd661743f4b8f49145dc19f
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_iterators.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_lang.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_lang.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..257c86050b7122217b3b969368ab33c932c7c667
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_lang.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_laplace.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_laplace.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fbaa706dae773fe4915fdc927c3ce38c9bb40d98
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_laplace.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_libdevice.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_libdevice.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c4e2825c2f5056785598fa63598cb7f3b81d53e7
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_libdevice.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_lineinfo.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_lineinfo.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9ab2ca49451ba7ea1720040dfeb490bec81914c4
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_lineinfo.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_localmem.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_localmem.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b57a80b01887ccfbb14c801a336d95a9808e534c
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_localmem.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_mandel.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_mandel.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9880f477588d5eccfdb2320661d460c2d0736c8e
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_mandel.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_math.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_math.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cf90e1dc36f3a1f1708e8349de427a9513b5b133
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_math.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_matmul.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_matmul.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0a3471028d0cd89aca1561edaf5f9ffe65f3081c
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_matmul.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_minmax.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_minmax.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7924daf6dd7139fa3239a1d835de0164bddcf327
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_minmax.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_montecarlo.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_montecarlo.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0c616c0a2e54fd5b9a55060980889c57c3506e56
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_montecarlo.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_multigpu.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_multigpu.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7daa87e49474b30ef0419b396f65ac61e6a97cbc
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_multigpu.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_multiprocessing.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_multiprocessing.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..eecaaa3e22f34fc5296dca57807596b8d12b639b
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_multiprocessing.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_multithreads.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_multithreads.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c4ac9d57cead26811c2f6b5bcf7eb79e43048785
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_multithreads.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_nondet.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_nondet.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8d73736802ace966893f733f213ccb838ecd9d1d
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_nondet.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_operator.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_operator.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ea71433c8a6b120554b96f3282fa3e3f03d3b207
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_operator.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_optimization.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_optimization.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..55dc9ff82303a6a81a3874c2d3ddd7aa84842e0c
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_optimization.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_overload.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_overload.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b610a7945bc220168850964dcb5d98fc404af511
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_overload.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_powi.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_powi.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..224ce98cece36f06839a1746f06db862e2d3e575
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_powi.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_print.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_print.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d55a84a67e17f6bc6bd3b798f67f9a52d5f16497
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_print.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_py2_div_issue.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_py2_div_issue.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4cb4809a3fa8e79c5da708d9a5e205b262035bfb
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_py2_div_issue.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_random.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_random.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7765f6f141bf1ee59054de57faba3dea59ceae1d
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_random.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_record_dtype.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_record_dtype.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..234289f77b477122e598fa00427335f4f5a78797
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_record_dtype.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_recursion.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_recursion.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f9d3ffeabdc77bb96ab22e731e9dee4b99b0c9d5
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_recursion.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_reduction.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_reduction.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b79ede9b354c7b2b499b127752069be41d6db131
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_reduction.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_retrieve_autoconverted_arrays.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_retrieve_autoconverted_arrays.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..373795f9f2b29079ff5d6a7a285ea3c374ab6024
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_retrieve_autoconverted_arrays.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_serialize.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_serialize.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5f8fceef3aee623abfddb186b5deb45d1bcb84dd
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_serialize.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_slicing.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_slicing.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..03bb70fadfc285e5fea16f372560478d419b0575
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_slicing.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_sm.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_sm.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a1e0da524cd2959c5d18dc982044098235139c1d
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_sm.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_sm_creation.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_sm_creation.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..217e7a5ee9f014fc312793b7ca5aa8ef031e34dd
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_sm_creation.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_sync.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_sync.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9121f36bf210e3c194d150099cb0f5fea6c90c87
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_sync.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_transpose.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_transpose.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..29f5dbfd95e35bd42b7aa07abea6ea7b02ce1fb8
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_transpose.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_ufuncs.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_ufuncs.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..998563f7e85f0e8ec9e359c21718b2b6526af8d3
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_ufuncs.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_userexc.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_userexc.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..eae27c2020e657fe381b46bb4f15bfcc63532589
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_userexc.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_vector_type.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_vector_type.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8f30156076d2cddf46323b67530965afc844540b
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_vector_type.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_vectorize.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_vectorize.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..85d56d2663231e0699264b5dea835e98f50cace9
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_vectorize.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_vectorize_complex.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_vectorize_complex.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9bfc3af24a0327ffaebc6c887719e181d933f1de
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_vectorize_complex.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_vectorize_decor.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_vectorize_decor.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..dd8b260527db5e2354a4b3a207cd9a6c719fc970
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_vectorize_decor.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_vectorize_device.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_vectorize_device.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bc8ecb2dec33805dd01b5404637c2f5f4d526326
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_vectorize_device.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_vectorize_scalar_arg.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_vectorize_scalar_arg.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d21d025645e935087f6bff79db4cc996183b56d9
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_vectorize_scalar_arg.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_warning.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_warning.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..00d6117f4d1d37e8c08d0875958d0e316d255e51
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_warning.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_warp_ops.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_warp_ops.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9e92ca4ef82acd7e014f3c57644e731edfde3006
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/__pycache__/test_warp_ops.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/cache_usecases.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/cache_usecases.py
new file mode 100644
index 0000000000000000000000000000000000000000..ad6d9ad57f022e98d9074799a1bbb61ad98b53c9
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/cache_usecases.py
@@ -0,0 +1,234 @@
+from numba import cuda
+from numba.cuda.testing import CUDATestCase
+import numpy as np
+import sys
+
+
+class UseCase:
+ """
+ Provide a way to call a kernel as if it were a function.
+
+ This allows the CUDA cache tests to closely match the CPU cache tests, and
+ also to support calling cache use cases as njitted functions. The class
+ wraps a function that takes an array for the return value and arguments,
+ and provides an interface that accepts arguments, launches the kernel
+ appropriately, and returns the stored return value.
+
+ The return type is inferred from the type of the first argument, unless it
+ is explicitly overridden by the ``retty`` kwarg.
+ """
+ def __init__(self, func, retty=None):
+ self._func = func
+ self._retty = retty
+
+ def __call__(self, *args):
+ array_args = [np.asarray(arg) for arg in args]
+ if self._retty:
+ array_return = np.ndarray((), dtype=self._retty)
+ else:
+ array_return = np.zeros_like(array_args[0])
+
+ self._call(array_return, *array_args)
+ return array_return[()]
+
+ @property
+ def func(self):
+ return self._func
+
+
+class CUDAUseCase(UseCase):
+ def _call(self, ret, *args):
+ self._func[1, 1](ret, *args)
+
+
+@cuda.jit(cache=True)
+def add_usecase_kernel(r, x, y):
+ r[()] = x[()] + y[()] + Z
+
+
+@cuda.jit(cache=False)
+def add_nocache_usecase_kernel(r, x, y):
+ r[()] = x[()] + y[()] + Z
+
+
+add_usecase = CUDAUseCase(add_usecase_kernel)
+add_nocache_usecase = CUDAUseCase(add_nocache_usecase_kernel)
+
+Z = 1
+
+
+# Inner / outer cached / uncached cases
+
+@cuda.jit(cache=True)
+def inner(x, y):
+ return x + y + Z
+
+
+@cuda.jit(cache=True)
+def outer_kernel(r, x, y):
+ r[()] = inner(-y[()], x[()])
+
+
+@cuda.jit(cache=False)
+def outer_uncached_kernel(r, x, y):
+ r[()] = inner(-y[()], x[()])
+
+
+outer = CUDAUseCase(outer_kernel)
+outer_uncached = CUDAUseCase(outer_uncached_kernel)
+
+
+# Exercise returning a record instance. This used to hardcode the dtype
+# pointer's value in the bitcode.
+
+packed_record_type = np.dtype([('a', np.int8), ('b', np.float64)])
+aligned_record_type = np.dtype([('a', np.int8), ('b', np.float64)], align=True)
+
+packed_arr = np.empty(2, dtype=packed_record_type)
+for i in range(packed_arr.size):
+ packed_arr[i]['a'] = i + 1
+ packed_arr[i]['b'] = i + 42.5
+
+aligned_arr = np.array(packed_arr, dtype=aligned_record_type)
+
+
+@cuda.jit(cache=True)
+def record_return(r, ary, i):
+ r[()] = ary[i]
+
+
+record_return_packed = CUDAUseCase(record_return, retty=packed_record_type)
+record_return_aligned = CUDAUseCase(record_return, retty=aligned_record_type)
+
+
+# Closure test cases
+
+def make_closure(x):
+ @cuda.jit(cache=True)
+ def closure(r, y):
+ r[()] = x + y[()]
+
+ return CUDAUseCase(closure)
+
+
+closure1 = make_closure(3)
+closure2 = make_closure(5)
+closure3 = make_closure(7)
+closure4 = make_closure(9)
+
+
+# Ambiguous / renamed functions
+
+@cuda.jit(cache=True)
+def ambiguous_function(r, x):
+ r[()] = x[()] + 2
+
+
+renamed_function1 = CUDAUseCase(ambiguous_function)
+
+
+@cuda.jit(cache=True)
+def ambiguous_function(r, x):
+ r[()] = x[()] + 6
+
+
+renamed_function2 = CUDAUseCase(ambiguous_function)
+
+
+@cuda.jit(cache=True)
+def many_locals():
+ aa = cuda.local.array((1, 1), np.float64)
+ ab = cuda.local.array((1, 1), np.float64)
+ ac = cuda.local.array((1, 1), np.float64)
+ ad = cuda.local.array((1, 1), np.float64)
+ ae = cuda.local.array((1, 1), np.float64)
+ af = cuda.local.array((1, 1), np.float64)
+ ag = cuda.local.array((1, 1), np.float64)
+ ah = cuda.local.array((1, 1), np.float64)
+ ai = cuda.local.array((1, 1), np.float64)
+ aj = cuda.local.array((1, 1), np.float64)
+ ak = cuda.local.array((1, 1), np.float64)
+ al = cuda.local.array((1, 1), np.float64)
+ am = cuda.local.array((1, 1), np.float64)
+ an = cuda.local.array((1, 1), np.float64)
+ ao = cuda.local.array((1, 1), np.float64)
+ ap = cuda.local.array((1, 1), np.float64)
+ ar = cuda.local.array((1, 1), np.float64)
+ at = cuda.local.array((1, 1), np.float64)
+ au = cuda.local.array((1, 1), np.float64)
+ av = cuda.local.array((1, 1), np.float64)
+ aw = cuda.local.array((1, 1), np.float64)
+ ax = cuda.local.array((1, 1), np.float64)
+ ay = cuda.local.array((1, 1), np.float64)
+ az = cuda.local.array((1, 1), np.float64)
+
+ aa[:] = 0
+ ab[:] = 0
+ ac[:] = 0
+ ad[:] = 0
+ ae[:] = 0
+ af[:] = 0
+ ag[:] = 0
+ ah[:] = 0
+ ai[:] = 0
+ aj[:] = 0
+ ak[:] = 0
+ al[:] = 0
+ am[:] = 0
+ an[:] = 0
+ ao[:] = 0
+ ap[:] = 0
+ ar[:] = 0
+ at[:] = 0
+ au[:] = 0
+ av[:] = 0
+ aw[:] = 0
+ ax[:] = 0
+ ay[:] = 0
+ az[:] = 0
+
+
+# Simple use case for multiprocessing test
+
+@cuda.jit(cache=True)
+def simple_usecase_kernel(r, x):
+ r[()] = x[()]
+
+
+simple_usecase_caller = CUDAUseCase(simple_usecase_kernel)
+
+
+# Usecase with cooperative groups
+
+@cuda.jit(cache=True)
+def cg_usecase_kernel(r, x):
+ grid = cuda.cg.this_grid()
+ grid.sync()
+
+
+cg_usecase = CUDAUseCase(cg_usecase_kernel)
+
+
+class _TestModule(CUDATestCase):
+ """
+ Tests for functionality of this module's functions.
+ Note this does not define any "test_*" method, instead check_module()
+ should be called by hand.
+ """
+
+ def check_module(self, mod):
+ self.assertPreciseEqual(mod.add_usecase(2, 3), 6)
+ self.assertPreciseEqual(mod.outer_uncached(3, 2), 2)
+ self.assertPreciseEqual(mod.outer(3, 2), 2)
+
+ packed_rec = mod.record_return_packed(mod.packed_arr, 1)
+ self.assertPreciseEqual(tuple(packed_rec), (2, 43.5))
+ aligned_rec = mod.record_return_aligned(mod.aligned_arr, 1)
+ self.assertPreciseEqual(tuple(aligned_rec), (2, 43.5))
+
+ mod.simple_usecase_caller(2)
+
+
+def self_test():
+ mod = sys.modules[__name__]
+ _TestModule().check_module(mod)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/cache_with_cpu_usecases.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/cache_with_cpu_usecases.py
new file mode 100644
index 0000000000000000000000000000000000000000..07b42d75550a2f4c4e833758cd56d9094dbbd374
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/cache_with_cpu_usecases.py
@@ -0,0 +1,41 @@
+import sys
+
+from numba import cuda, njit
+from numba.cuda.testing import CUDATestCase
+from numba.cuda.tests.cudapy.cache_usecases import CUDAUseCase, UseCase
+
+
+class CPUUseCase(UseCase):
+ def _call(self, ret, *args):
+ self._func(ret, *args)
+
+
+# Using the same function as a cached CPU and CUDA-jitted function
+
+def target_shared_assign(r, x):
+ r[()] = x[()]
+
+
+assign_cuda_kernel = cuda.jit(cache=True)(target_shared_assign)
+assign_cuda = CUDAUseCase(assign_cuda_kernel)
+assign_cpu_jitted = njit(cache=True)(target_shared_assign)
+assign_cpu = CPUUseCase(assign_cpu_jitted)
+
+
+class _TestModule(CUDATestCase):
+ """
+ Tests for functionality of this module's functions.
+ Note this does not define any "test_*" method, instead check_module()
+ should be called by hand.
+ """
+
+ def check_module(self, mod):
+ self.assertPreciseEqual(mod.assign_cpu(5), 5)
+ self.assertPreciseEqual(mod.assign_cpu(5.5), 5.5)
+ self.assertPreciseEqual(mod.assign_cuda(5), 5)
+ self.assertPreciseEqual(mod.assign_cuda(5.5), 5.5)
+
+
+def self_test():
+ mod = sys.modules[__name__]
+ _TestModule().check_module(mod)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/extensions_usecases.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/extensions_usecases.py
new file mode 100644
index 0000000000000000000000000000000000000000..1e639d379b3e3bdd266b98c9cbc9e99b4e021849
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/extensions_usecases.py
@@ -0,0 +1,58 @@
+from numba import types
+from numba.core import config
+
+
+class TestStruct:
+ def __init__(self, x, y):
+ self.x = x
+ self.y = y
+
+
+class TestStructModelType(types.Type):
+ def __init__(self):
+ super().__init__(name="TestStructModelType")
+
+
+test_struct_model_type = TestStructModelType()
+
+
+if not config.ENABLE_CUDASIM:
+ from numba import int32
+ from numba.core.extending import (
+ models,
+ register_model,
+ make_attribute_wrapper,
+ typeof_impl,
+ type_callable
+ )
+ from numba.cuda.cudaimpl import lower
+ from numba.core import cgutils
+
+ @typeof_impl.register(TestStruct)
+ def typeof_teststruct(val, c):
+ return test_struct_model_type
+
+ @register_model(TestStructModelType)
+ class TestStructModel(models.StructModel):
+ def __init__(self, dmm, fe_type):
+ members = [("x", int32), ("y", int32)]
+ super().__init__(dmm, fe_type, members)
+
+ make_attribute_wrapper(TestStructModelType, 'x', 'x')
+ make_attribute_wrapper(TestStructModelType, 'y', 'y')
+
+ @type_callable(TestStruct)
+ def type_test_struct(context):
+ def typer(x, y):
+ if isinstance(x, types.Integer) and isinstance(y, types.Integer):
+ return test_struct_model_type
+ return typer
+
+ @lower(TestStruct, types.Integer, types.Integer)
+ def lower_test_type_ctor(context, builder, sig, args):
+ obj = cgutils.create_struct_proxy(
+ test_struct_model_type
+ )(context, builder)
+ obj.x = args[0]
+ obj.y = args[1]
+ return obj._getvalue()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/recursion_usecases.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/recursion_usecases.py
new file mode 100644
index 0000000000000000000000000000000000000000..b182359b11a25b60218ff4b0962d0158cae05e33
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/recursion_usecases.py
@@ -0,0 +1,100 @@
+"""
+Usecases of recursive functions in the CUDA target, many derived from
+numba/tests/recursion_usecases.py.
+
+Some functions are compiled at import time, hence a separate module.
+"""
+
+from numba import cuda
+
+
+@cuda.jit("i8(i8)", device=True)
+def fib1(n):
+ if n < 2:
+ return n
+ # Note the second call does not use a named argument, unlike the CPU target
+ # usecase
+ return fib1(n - 1) + fib1(n - 2)
+
+
+def make_fib2():
+ @cuda.jit("i8(i8)", device=True)
+ def fib2(n):
+ if n < 2:
+ return n
+ return fib2(n - 1) + fib2(n - 2)
+
+ return fib2
+
+
+fib2 = make_fib2()
+
+
+@cuda.jit
+def type_change_self(x, y):
+ if x > 1 and y > 0:
+ return x + type_change_self(x - y, y)
+ else:
+ return y
+
+
+# Implicit signature
+@cuda.jit(device=True)
+def fib3(n):
+ if n < 2:
+ return n
+
+ return fib3(n - 1) + fib3(n - 2)
+
+
+# Run-away self recursion
+@cuda.jit(device=True)
+def runaway_self(x):
+ return runaway_self(x)
+
+
+@cuda.jit(device=True)
+def raise_self(x):
+ if x == 1:
+ raise ValueError("raise_self")
+ elif x > 0:
+ return raise_self(x - 1)
+ else:
+ return 1
+
+
+@cuda.jit(debug=True, opt=False)
+def raise_self_kernel(x):
+ raise_self(x)
+
+
+def make_optional_return_case(jit=lambda x: x):
+ @jit
+ def foo(x):
+ if x > 5:
+ return x - 1
+ else:
+ return
+
+ @jit
+ def bar(x):
+ out = foo(x)
+ if out is None:
+ return out
+ elif out < 8:
+ return out
+ else:
+ return x * bar(out)
+
+ return bar
+
+
+def make_growing_tuple_case(jit=lambda x: x):
+ # From issue #4387
+ @jit
+ def make_list(n):
+ if n <= 0:
+ return None
+
+ return (n, make_list(n - 1))
+ return make_list
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_alignment.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_alignment.py
new file mode 100644
index 0000000000000000000000000000000000000000..7c7dff8cafd94f257a6cc061b7c1b3c8d8d3a10d
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_alignment.py
@@ -0,0 +1,42 @@
+import numpy as np
+from numba import from_dtype, cuda
+from numba.cuda.testing import skip_on_cudasim, CUDATestCase
+import unittest
+
+
+class TestAlignment(CUDATestCase):
+ def test_record_alignment(self):
+ rec_dtype = np.dtype([('a', 'int32'), ('b', 'float64')], align=True)
+ rec = from_dtype(rec_dtype)
+
+ @cuda.jit((rec[:],))
+ def foo(a):
+ i = cuda.grid(1)
+ a[i].a = a[i].b
+
+ a_recarray = np.recarray(3, dtype=rec_dtype)
+ for i in range(a_recarray.size):
+ a_rec = a_recarray[i]
+ a_rec.a = 0
+ a_rec.b = (i + 1) * 123
+
+ foo[1, 3](a_recarray)
+
+ self.assertTrue(np.all(a_recarray.a == a_recarray.b))
+
+ @skip_on_cudasim('Simulator does not check alignment')
+ def test_record_alignment_error(self):
+ rec_dtype = np.dtype([('a', 'int32'), ('b', 'float64')])
+ rec = from_dtype(rec_dtype)
+
+ with self.assertRaises(Exception) as raises:
+ @cuda.jit((rec[:],))
+ def foo(a):
+ i = cuda.grid(1)
+ a[i].a = a[i].b
+
+ self.assertTrue('type float64 is not aligned' in str(raises.exception))
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_array.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_array.py
new file mode 100644
index 0000000000000000000000000000000000000000..79899daf10f038d6737e38d21bc147831ca5ee6c
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_array.py
@@ -0,0 +1,260 @@
+import numpy as np
+
+from numba.cuda.testing import unittest, CUDATestCase
+from numba.cuda.testing import skip_on_cudasim, skip_unless_cudasim
+from numba import config, cuda
+
+
+if config.ENABLE_CUDASIM:
+ ARRAY_LIKE_FUNCTIONS = (cuda.device_array_like, cuda.pinned_array_like)
+else:
+ ARRAY_LIKE_FUNCTIONS = (cuda.device_array_like, cuda.mapped_array_like,
+ cuda.pinned_array_like)
+
+
+class TestCudaArray(CUDATestCase):
+ def test_gpu_array_zero_length(self):
+ x = np.arange(0)
+ dx = cuda.to_device(x)
+ hx = dx.copy_to_host()
+ self.assertEqual(x.shape, dx.shape)
+ self.assertEqual(x.size, dx.size)
+ self.assertEqual(x.shape, hx.shape)
+ self.assertEqual(x.size, hx.size)
+
+ def test_null_shape(self):
+ null_shape = ()
+ shape1 = cuda.device_array(()).shape
+ shape2 = cuda.device_array_like(np.ndarray(())).shape
+ self.assertEqual(shape1, null_shape)
+ self.assertEqual(shape2, null_shape)
+
+ def test_gpu_array_strided(self):
+
+ @cuda.jit('void(double[:])')
+ def kernel(x):
+ i = cuda.grid(1)
+ if i < x.shape[0]:
+ x[i] = i
+
+ x = np.arange(10, dtype=np.double)
+ y = np.ndarray(shape=10 * 8, buffer=x, dtype=np.byte)
+ z = np.ndarray(9, buffer=y[4:-4], dtype=np.double)
+ kernel[10, 10](z)
+ self.assertTrue(np.allclose(z, list(range(9))))
+
+ def test_gpu_array_interleaved(self):
+
+ @cuda.jit('void(double[:], double[:])')
+ def copykernel(x, y):
+ i = cuda.grid(1)
+ if i < x.shape[0]:
+ x[i] = i
+ y[i] = i
+
+ x = np.arange(10, dtype=np.double)
+ y = x[:-1:2]
+ # z = x[1::2]
+ # n = y.size
+ try:
+ cuda.devicearray.auto_device(y)
+ except ValueError:
+ pass
+ else:
+ raise AssertionError("Should raise exception complaining the "
+ "contiguous-ness of the array.")
+ # Should we handle this use case?
+ # assert z.size == y.size
+ # copykernel[1, n](y, x)
+ # print(y, z)
+ # assert np.all(y == z)
+ # assert np.all(y == list(range(n)))
+
+ def test_auto_device_const(self):
+ d, _ = cuda.devicearray.auto_device(2)
+ self.assertTrue(np.all(d.copy_to_host() == np.array(2)))
+
+ def _test_array_like_same(self, like_func, array):
+ """
+ Tests of *_array_like where shape, strides, dtype, and flags should
+ all be equal.
+ """
+ array_like = like_func(array)
+ self.assertEqual(array.shape, array_like.shape)
+ self.assertEqual(array.strides, array_like.strides)
+ self.assertEqual(array.dtype, array_like.dtype)
+ self.assertEqual(array.flags['C_CONTIGUOUS'],
+ array_like.flags['C_CONTIGUOUS'])
+ self.assertEqual(array.flags['F_CONTIGUOUS'],
+ array_like.flags['F_CONTIGUOUS'])
+
+ def test_array_like_1d(self):
+ d_a = cuda.device_array(10, order='C')
+ for like_func in ARRAY_LIKE_FUNCTIONS:
+ with self.subTest(like_func=like_func):
+ self._test_array_like_same(like_func, d_a)
+
+ def test_array_like_2d(self):
+ d_a = cuda.device_array((10, 12), order='C')
+ for like_func in ARRAY_LIKE_FUNCTIONS:
+ with self.subTest(like_func=like_func):
+ self._test_array_like_same(like_func, d_a)
+
+ def test_array_like_2d_transpose(self):
+ d_a = cuda.device_array((10, 12), order='C')
+ for like_func in ARRAY_LIKE_FUNCTIONS:
+ with self.subTest(like_func=like_func):
+ self._test_array_like_same(like_func, d_a)
+
+ def test_array_like_3d(self):
+ d_a = cuda.device_array((10, 12, 14), order='C')
+ for like_func in ARRAY_LIKE_FUNCTIONS:
+ with self.subTest(like_func=like_func):
+ self._test_array_like_same(like_func, d_a)
+
+ def test_array_like_1d_f(self):
+ d_a = cuda.device_array(10, order='F')
+ for like_func in ARRAY_LIKE_FUNCTIONS:
+ with self.subTest(like_func=like_func):
+ self._test_array_like_same(like_func, d_a)
+
+ def test_array_like_2d_f(self):
+ d_a = cuda.device_array((10, 12), order='F')
+ for like_func in ARRAY_LIKE_FUNCTIONS:
+ with self.subTest(like_func=like_func):
+ self._test_array_like_same(like_func, d_a)
+
+ def test_array_like_2d_f_transpose(self):
+ d_a = cuda.device_array((10, 12), order='F')
+ for like_func in ARRAY_LIKE_FUNCTIONS:
+ with self.subTest(like_func=like_func):
+ self._test_array_like_same(like_func, d_a)
+
+ def test_array_like_3d_f(self):
+ d_a = cuda.device_array((10, 12, 14), order='F')
+ for like_func in ARRAY_LIKE_FUNCTIONS:
+ with self.subTest(like_func=like_func):
+ self._test_array_like_same(like_func, d_a)
+
+ def _test_array_like_view(self, like_func, view, d_view):
+ """
+ Tests of device_array_like where the original array is a view - the
+ strides should not be equal because a contiguous array is expected.
+ """
+ nb_like = like_func(d_view)
+ self.assertEqual(d_view.shape, nb_like.shape)
+ self.assertEqual(d_view.dtype, nb_like.dtype)
+
+ # Use NumPy as a reference for the expected strides
+ np_like = np.zeros_like(view)
+ self.assertEqual(nb_like.strides, np_like.strides)
+ self.assertEqual(nb_like.flags['C_CONTIGUOUS'],
+ np_like.flags['C_CONTIGUOUS'])
+ self.assertEqual(nb_like.flags['F_CONTIGUOUS'],
+ np_like.flags['F_CONTIGUOUS'])
+
+ def test_array_like_1d_view(self):
+ shape = 10
+ view = np.zeros(shape)[::2]
+ d_view = cuda.device_array(shape)[::2]
+ for like_func in ARRAY_LIKE_FUNCTIONS:
+ with self.subTest(like_func=like_func):
+ self._test_array_like_view(like_func, view, d_view)
+
+ def test_array_like_1d_view_f(self):
+ shape = 10
+ view = np.zeros(shape, order='F')[::2]
+ d_view = cuda.device_array(shape, order='F')[::2]
+ for like_func in ARRAY_LIKE_FUNCTIONS:
+ with self.subTest(like_func=like_func):
+ self._test_array_like_view(like_func, view, d_view)
+
+ def test_array_like_2d_view(self):
+ shape = (10, 12)
+ view = np.zeros(shape)[::2, ::2]
+ d_view = cuda.device_array(shape)[::2, ::2]
+ for like_func in ARRAY_LIKE_FUNCTIONS:
+ with self.subTest(like_func=like_func):
+ self._test_array_like_view(like_func, view, d_view)
+
+ def test_array_like_2d_view_f(self):
+ shape = (10, 12)
+ view = np.zeros(shape, order='F')[::2, ::2]
+ d_view = cuda.device_array(shape, order='F')[::2, ::2]
+ for like_func in ARRAY_LIKE_FUNCTIONS:
+ with self.subTest(like_func=like_func):
+ self._test_array_like_view(like_func, view, d_view)
+
+ @skip_on_cudasim('Numba and NumPy stride semantics differ for transpose')
+ def test_array_like_2d_view_transpose_device(self):
+ shape = (10, 12)
+ d_view = cuda.device_array(shape)[::2, ::2].T
+ for like_func in ARRAY_LIKE_FUNCTIONS:
+ with self.subTest(like_func=like_func):
+ # This is a special case (see issue #4974) because creating the
+ # transpose creates a new contiguous allocation with different
+ # strides. In this case, rather than comparing against NumPy,
+ # we can only compare against expected values.
+ like = like_func(d_view)
+ self.assertEqual(d_view.shape, like.shape)
+ self.assertEqual(d_view.dtype, like.dtype)
+ self.assertEqual((40, 8), like.strides)
+ self.assertTrue(like.flags['C_CONTIGUOUS'])
+ self.assertFalse(like.flags['F_CONTIGUOUS'])
+
+ @skip_unless_cudasim('Numba and NumPy stride semantics differ for '
+ 'transpose')
+ def test_array_like_2d_view_transpose_simulator(self):
+ shape = (10, 12)
+ view = np.zeros(shape)[::2, ::2].T
+ d_view = cuda.device_array(shape)[::2, ::2].T
+ for like_func in ARRAY_LIKE_FUNCTIONS:
+ with self.subTest(like_func=like_func):
+ # On the simulator, the transpose has different strides to on a
+ # CUDA device (See issue #4974). Here we can compare strides
+ # against NumPy as a reference.
+ np_like = np.zeros_like(view)
+ nb_like = like_func(d_view)
+ self.assertEqual(d_view.shape, nb_like.shape)
+ self.assertEqual(d_view.dtype, nb_like.dtype)
+ self.assertEqual(np_like.strides, nb_like.strides)
+ self.assertEqual(np_like.flags['C_CONTIGUOUS'],
+ nb_like.flags['C_CONTIGUOUS'])
+ self.assertEqual(np_like.flags['F_CONTIGUOUS'],
+ nb_like.flags['F_CONTIGUOUS'])
+
+ def test_array_like_2d_view_f_transpose(self):
+ shape = (10, 12)
+ view = np.zeros(shape, order='F')[::2, ::2].T
+ d_view = cuda.device_array(shape, order='F')[::2, ::2].T
+ for like_func in ARRAY_LIKE_FUNCTIONS:
+ with self.subTest(like_func=like_func):
+ self._test_array_like_view(like_func, view, d_view)
+
+ @skip_on_cudasim('Kernel overloads not created in the simulator')
+ def test_issue_4628(self):
+ # CUDA Device arrays were reported as always being typed with 'A' order
+ # so launching the kernel with a host array and then a device array
+ # resulted in two overloads being compiled - one for 'C' order from
+ # the host array, and one for 'A' order from the device array. With the
+ # resolution of this issue, the order of the device array is also 'C',
+ # so after the kernel launches there should only be one overload of
+ # the function.
+ @cuda.jit
+ def func(A, out):
+ i = cuda.grid(1)
+ out[i] = A[i] * 2
+
+ n = 128
+ a = np.ones((n,))
+ d_a = cuda.to_device(a)
+ result = np.zeros((n,))
+
+ func[1, 128](a, result)
+ func[1, 128](d_a, result)
+
+ self.assertEqual(1, len(func.overloads))
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_array_args.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_array_args.py
new file mode 100644
index 0000000000000000000000000000000000000000..87db4a6c7bc36771c80888d7653d122e4c16f44c
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_array_args.py
@@ -0,0 +1,201 @@
+import numpy as np
+from collections import namedtuple
+
+from numba import cuda
+from numba.cuda.testing import unittest, CUDATestCase
+
+
+class TestCudaArrayArg(CUDATestCase):
+ def test_array_ary(self):
+
+ @cuda.jit('double(double[:],int64)', device=True, inline=True)
+ def device_function(a, c):
+ return a[c]
+
+ @cuda.jit('void(double[:],double[:])')
+ def kernel(x, y):
+ i = cuda.grid(1)
+ y[i] = device_function(x, i)
+
+ x = np.arange(10, dtype=np.double)
+ y = np.zeros_like(x)
+ kernel[10, 1](x, y)
+ self.assertTrue(np.all(x == y))
+
+ def test_unituple(self):
+ @cuda.jit
+ def f(r, x):
+ r[0] = x[0]
+ r[1] = x[1]
+ r[2] = x[2]
+
+ x = (1, 2, 3)
+ r = np.zeros(len(x), dtype=np.int64)
+ f[1, 1](r, x)
+
+ for i in range(len(x)):
+ self.assertEqual(r[i], x[i])
+
+ def test_tuple(self):
+ @cuda.jit
+ def f(r1, r2, x):
+ r1[0] = x[0]
+ r1[1] = x[1]
+ r1[2] = x[2]
+ r2[0] = x[3]
+ r2[1] = x[4]
+ r2[2] = x[5]
+
+ x = (1, 2, 3, 4.5, 5.5, 6.5)
+ r1 = np.zeros(len(x) // 2, dtype=np.int64)
+ r2 = np.zeros(len(x) // 2, dtype=np.float64)
+ f[1, 1](r1, r2, x)
+
+ for i in range(len(r1)):
+ self.assertEqual(r1[i], x[i])
+
+ for i in range(len(r2)):
+ self.assertEqual(r2[i], x[i + len(r1)])
+
+ def test_namedunituple(self):
+ @cuda.jit
+ def f(r, x):
+ r[0] = x.x
+ r[1] = x.y
+
+ Point = namedtuple('Point', ('x', 'y'))
+ x = Point(1, 2)
+ r = np.zeros(len(x), dtype=np.int64)
+ f[1, 1](r, x)
+
+ self.assertEqual(r[0], x.x)
+ self.assertEqual(r[1], x.y)
+
+ def test_namedtuple(self):
+ @cuda.jit
+ def f(r1, r2, x):
+ r1[0] = x.x
+ r1[1] = x.y
+ r2[0] = x.r
+
+ Point = namedtuple('Point', ('x', 'y', 'r'))
+ x = Point(1, 2, 2.236)
+ r1 = np.zeros(2, dtype=np.int64)
+ r2 = np.zeros(1, dtype=np.float64)
+ f[1, 1](r1, r2, x)
+
+ self.assertEqual(r1[0], x.x)
+ self.assertEqual(r1[1], x.y)
+ self.assertEqual(r2[0], x.r)
+
+ def test_empty_tuple(self):
+ @cuda.jit
+ def f(r, x):
+ r[0] = len(x)
+
+ x = tuple()
+ r = np.ones(1, dtype=np.int64)
+ f[1, 1](r, x)
+
+ self.assertEqual(r[0], 0)
+
+ def test_tuple_of_empty_tuples(self):
+ @cuda.jit
+ def f(r, x):
+ r[0] = len(x)
+ r[1] = len(x[0])
+
+ x = ((), (), ())
+ r = np.ones(2, dtype=np.int64)
+ f[1, 1](r, x)
+
+ self.assertEqual(r[0], 3)
+ self.assertEqual(r[1], 0)
+
+ def test_tuple_of_tuples(self):
+ @cuda.jit
+ def f(r, x):
+ r[0] = len(x)
+ r[1] = len(x[0])
+ r[2] = len(x[1])
+ r[3] = len(x[2])
+ r[4] = x[1][0]
+ r[5] = x[1][1]
+ r[6] = x[2][0]
+ r[7] = x[2][1]
+ r[8] = x[2][2]
+
+ x = ((), (5, 6), (8, 9, 10))
+ r = np.ones(9, dtype=np.int64)
+ f[1, 1](r, x)
+
+ self.assertEqual(r[0], 3)
+ self.assertEqual(r[1], 0)
+ self.assertEqual(r[2], 2)
+ self.assertEqual(r[3], 3)
+ self.assertEqual(r[4], 5)
+ self.assertEqual(r[5], 6)
+ self.assertEqual(r[6], 8)
+ self.assertEqual(r[7], 9)
+ self.assertEqual(r[8], 10)
+
+ def test_tuple_of_tuples_and_scalars(self):
+ @cuda.jit
+ def f(r, x):
+ r[0] = len(x)
+ r[1] = len(x[0])
+ r[2] = x[0][0]
+ r[3] = x[0][1]
+ r[4] = x[0][2]
+ r[5] = x[1]
+
+ x = ((6, 5, 4), 7)
+ r = np.ones(9, dtype=np.int64)
+ f[1, 1](r, x)
+
+ self.assertEqual(r[0], 2)
+ self.assertEqual(r[1], 3)
+ self.assertEqual(r[2], 6)
+ self.assertEqual(r[3], 5)
+ self.assertEqual(r[4], 4)
+ self.assertEqual(r[5], 7)
+
+ def test_tuple_of_arrays(self):
+ @cuda.jit
+ def f(x):
+ i = cuda.grid(1)
+ if i < len(x[0]):
+ x[0][i] = x[1][i] + x[2][i]
+
+ N = 10
+ x0 = np.zeros(N)
+ x1 = np.ones_like(x0)
+ x2 = x1 * 3
+ x = (x0, x1, x2)
+ f[1, N](x)
+
+ np.testing.assert_equal(x0, x1 + x2)
+
+ def test_tuple_of_array_scalar_tuple(self):
+ @cuda.jit
+ def f(r, x):
+ r[0] = x[0][0]
+ r[1] = x[0][1]
+ r[2] = x[1]
+ r[3] = x[2][0]
+ r[4] = x[2][1]
+
+ z = np.arange(2, dtype=np.int64)
+ x = (2 * z, 10, (4, 3))
+ r = np.zeros(5, dtype=np.int64)
+ f[1, 1](r, x)
+
+ self.assertEqual(r[0], 0)
+ self.assertEqual(r[1], 2)
+ self.assertEqual(r[2], 10)
+ self.assertEqual(r[3], 4)
+ self.assertEqual(r[4], 3)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_array_methods.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_array_methods.py
new file mode 100644
index 0000000000000000000000000000000000000000..7f129b5df03121032c8f7252926eace3eab5c5d8
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_array_methods.py
@@ -0,0 +1,35 @@
+import numpy as np
+from numba import cuda
+from numba.cuda.testing import CUDATestCase
+import unittest
+
+
+def reinterpret_array_type(byte_arr, start, stop, output):
+ # Tested with just one thread
+ val = byte_arr[start:stop].view(np.int32)[0]
+ output[0] = val
+
+
+class TestCudaArrayMethods(CUDATestCase):
+ def test_reinterpret_array_type(self):
+ """
+ Reinterpret byte array as int32 in the GPU.
+ """
+ pyfunc = reinterpret_array_type
+ kernel = cuda.jit(pyfunc)
+
+ byte_arr = np.arange(256, dtype=np.uint8)
+ itemsize = np.dtype(np.int32).itemsize
+ for start in range(0, 256, itemsize):
+ stop = start + itemsize
+ expect = byte_arr[start:stop].view(np.int32)[0]
+
+ output = np.zeros(1, dtype=np.int32)
+ kernel[1, 1](byte_arr, start, stop, output)
+
+ got = output[0]
+ self.assertEqual(expect, got)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_atomics.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_atomics.py
new file mode 100644
index 0000000000000000000000000000000000000000..dd3da96b2dc1e167a9f896a9e80e358874599767
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_atomics.py
@@ -0,0 +1,1620 @@
+import numpy as np
+from textwrap import dedent
+
+from numba import cuda, uint32, uint64, float32, float64
+from numba.cuda.testing import unittest, CUDATestCase, cc_X_or_above
+from numba.core import config
+
+
+@cuda.jit(device=True)
+def atomic_cast_to_uint64(num):
+ return uint64(num)
+
+
+@cuda.jit(device=True)
+def atomic_cast_to_int(num):
+ return int(num)
+
+
+@cuda.jit(device=True)
+def atomic_cast_none(num):
+ return num
+
+
+@cuda.jit(device=True)
+def atomic_binary_1dim_shared(ary, idx, op2, ary_dtype, ary_nelements,
+ binop_func, cast_func, initializer,
+ neg_idx):
+ tid = cuda.threadIdx.x
+ sm = cuda.shared.array(ary_nelements, ary_dtype)
+ sm[tid] = initializer
+ cuda.syncthreads()
+ bin = cast_func(idx[tid] % ary_nelements)
+ if neg_idx:
+ bin = bin % ary_nelements
+ binop_func(sm, bin, op2)
+ cuda.syncthreads()
+ ary[tid] = sm[tid]
+
+
+@cuda.jit(device=True)
+def atomic_binary_1dim_shared2(ary, idx, op2, ary_dtype, ary_nelements,
+ binop_func, cast_func):
+ tid = cuda.threadIdx.x
+ sm = cuda.shared.array(ary_nelements, ary_dtype)
+ sm[tid] = ary[tid]
+ cuda.syncthreads()
+ bin = cast_func(idx[tid] % ary_nelements)
+ binop_func(sm, bin, op2)
+ cuda.syncthreads()
+ ary[tid] = sm[tid]
+
+
+@cuda.jit(device=True)
+def atomic_binary_2dim_shared(ary, op2, ary_dtype, ary_shape,
+ binop_func, y_cast_func, neg_idx):
+ tx = cuda.threadIdx.x
+ ty = cuda.threadIdx.y
+ sm = cuda.shared.array(ary_shape, ary_dtype)
+ sm[tx, ty] = ary[tx, ty]
+ cuda.syncthreads()
+ bin = (tx, y_cast_func(ty))
+ if neg_idx:
+ bin = (bin[0] % ary_shape[0], bin[1] % ary_shape[1])
+ binop_func(sm, bin, op2)
+ cuda.syncthreads()
+ ary[tx, ty] = sm[tx, ty]
+
+
+@cuda.jit(device=True)
+def atomic_binary_2dim_global(ary, op2, binop_func, y_cast_func, neg_idx):
+ tx = cuda.threadIdx.x
+ ty = cuda.threadIdx.y
+ bin = (tx, y_cast_func(ty))
+ if neg_idx:
+ bin = (bin[0] % ary.shape[0], bin[1] % ary.shape[1])
+ binop_func(ary, bin, op2)
+
+
+@cuda.jit(device=True)
+def atomic_binary_1dim_global(ary, idx, ary_nelements, op2,
+ binop_func, neg_idx):
+ tid = cuda.threadIdx.x
+ bin = int(idx[tid] % ary_nelements)
+ if neg_idx:
+ bin = bin % ary_nelements
+ binop_func(ary, bin, op2)
+
+
+def atomic_add(ary):
+ atomic_binary_1dim_shared(ary, ary, 1, uint32, 32,
+ cuda.atomic.add, atomic_cast_none, 0, False)
+
+
+def atomic_add_wrap(ary):
+ atomic_binary_1dim_shared(ary, ary, 1, uint32, 32,
+ cuda.atomic.add, atomic_cast_none, 0, True)
+
+
+def atomic_add2(ary):
+ atomic_binary_2dim_shared(ary, 1, uint32, (4, 8),
+ cuda.atomic.add, atomic_cast_none, False)
+
+
+def atomic_add2_wrap(ary):
+ atomic_binary_2dim_shared(ary, 1, uint32, (4, 8),
+ cuda.atomic.add, atomic_cast_none, True)
+
+
+def atomic_add3(ary):
+ atomic_binary_2dim_shared(ary, 1, uint32, (4, 8),
+ cuda.atomic.add, atomic_cast_to_uint64, False)
+
+
+def atomic_add_float(ary):
+ atomic_binary_1dim_shared(ary, ary, 1.0, float32, 32,
+ cuda.atomic.add, atomic_cast_to_int, 0.0, False)
+
+
+def atomic_add_float_wrap(ary):
+ atomic_binary_1dim_shared(ary, ary, 1.0, float32, 32,
+ cuda.atomic.add, atomic_cast_to_int, 0.0, True)
+
+
+def atomic_add_float_2(ary):
+ atomic_binary_2dim_shared(ary, 1.0, float32, (4, 8),
+ cuda.atomic.add, atomic_cast_none, False)
+
+
+def atomic_add_float_2_wrap(ary):
+ atomic_binary_2dim_shared(ary, 1.0, float32, (4, 8),
+ cuda.atomic.add, atomic_cast_none, True)
+
+
+def atomic_add_float_3(ary):
+ atomic_binary_2dim_shared(ary, 1.0, float32, (4, 8),
+ cuda.atomic.add, atomic_cast_to_uint64, False)
+
+
+def atomic_add_double_global(idx, ary):
+ atomic_binary_1dim_global(ary, idx, 32, 1.0, cuda.atomic.add, False)
+
+
+def atomic_add_double_global_wrap(idx, ary):
+ atomic_binary_1dim_global(ary, idx, 32, 1.0, cuda.atomic.add, True)
+
+
+def atomic_add_double_global_2(ary):
+ atomic_binary_2dim_global(ary, 1, cuda.atomic.add, atomic_cast_none, False)
+
+
+def atomic_add_double_global_2_wrap(ary):
+ atomic_binary_2dim_global(ary, 1, cuda.atomic.add, atomic_cast_none, True)
+
+
+def atomic_add_double_global_3(ary):
+ atomic_binary_2dim_global(ary, 1, cuda.atomic.add, atomic_cast_to_uint64,
+ False)
+
+
+def atomic_add_double(idx, ary):
+ atomic_binary_1dim_shared(ary, idx, 1.0, float64, 32,
+ cuda.atomic.add, atomic_cast_none, 0.0, False)
+
+
+def atomic_add_double_wrap(idx, ary):
+ atomic_binary_1dim_shared(ary, idx, 1.0, float64, 32,
+ cuda.atomic.add, atomic_cast_none, 0.0, True)
+
+
+def atomic_add_double_2(ary):
+ atomic_binary_2dim_shared(ary, 1.0, float64, (4, 8),
+ cuda.atomic.add, atomic_cast_none, False)
+
+
+def atomic_add_double_2_wrap(ary):
+ atomic_binary_2dim_shared(ary, 1.0, float64, (4, 8),
+ cuda.atomic.add, atomic_cast_none, True)
+
+
+def atomic_add_double_3(ary):
+ atomic_binary_2dim_shared(ary, 1.0, float64, (4, 8),
+ cuda.atomic.add, atomic_cast_to_uint64, False)
+
+
+def atomic_sub(ary):
+ atomic_binary_1dim_shared(ary, ary, 1, uint32, 32,
+ cuda.atomic.sub, atomic_cast_none, 0, False)
+
+
+def atomic_sub2(ary):
+ atomic_binary_2dim_shared(ary, 1, uint32, (4, 8),
+ cuda.atomic.sub, atomic_cast_none, False)
+
+
+def atomic_sub3(ary):
+ atomic_binary_2dim_shared(ary, 1, uint32, (4, 8),
+ cuda.atomic.sub, atomic_cast_to_uint64, False)
+
+
+def atomic_sub_float(ary):
+ atomic_binary_1dim_shared(ary, ary, 1.0, float32, 32,
+ cuda.atomic.sub, atomic_cast_to_int, 0.0, False)
+
+
+def atomic_sub_float_2(ary):
+ atomic_binary_2dim_shared(ary, 1.0, float32, (4, 8),
+ cuda.atomic.sub, atomic_cast_none, False)
+
+
+def atomic_sub_float_3(ary):
+ atomic_binary_2dim_shared(ary, 1.0, float32, (4, 8),
+ cuda.atomic.sub, atomic_cast_to_uint64, False)
+
+
+def atomic_sub_double(idx, ary):
+ atomic_binary_1dim_shared(ary, idx, 1.0, float64, 32,
+ cuda.atomic.sub, atomic_cast_none, 0.0, False)
+
+
+def atomic_sub_double_2(ary):
+ atomic_binary_2dim_shared(ary, 1.0, float64, (4, 8),
+ cuda.atomic.sub, atomic_cast_none, False)
+
+
+def atomic_sub_double_3(ary):
+ atomic_binary_2dim_shared(ary, 1.0, float64, (4, 8),
+ cuda.atomic.sub, atomic_cast_to_uint64, False)
+
+
+def atomic_sub_double_global(idx, ary):
+ atomic_binary_1dim_global(ary, idx, 32, 1.0, cuda.atomic.sub, False)
+
+
+def atomic_sub_double_global_2(ary):
+ atomic_binary_2dim_global(ary, 1.0, cuda.atomic.sub, atomic_cast_none,
+ False)
+
+
+def atomic_sub_double_global_3(ary):
+ atomic_binary_2dim_shared(ary, 1.0, float64, (4, 8),
+ cuda.atomic.sub, atomic_cast_to_uint64, False)
+
+
+def atomic_and(ary, op2):
+ atomic_binary_1dim_shared(ary, ary, op2, uint32, 32,
+ cuda.atomic.and_, atomic_cast_none, 1, False)
+
+
+def atomic_and2(ary, op2):
+ atomic_binary_2dim_shared(ary, op2, uint32, (4, 8),
+ cuda.atomic.and_, atomic_cast_none, False)
+
+
+def atomic_and3(ary, op2):
+ atomic_binary_2dim_shared(ary, op2, uint32, (4, 8),
+ cuda.atomic.and_, atomic_cast_to_uint64, False)
+
+
+def atomic_and_global(idx, ary, op2):
+ atomic_binary_1dim_global(ary, idx, 32, op2, cuda.atomic.and_, False)
+
+
+def atomic_and_global_2(ary, op2):
+ atomic_binary_2dim_global(ary, op2, cuda.atomic.and_,
+ atomic_cast_none, False)
+
+
+def atomic_or(ary, op2):
+ atomic_binary_1dim_shared(ary, ary, op2, uint32, 32,
+ cuda.atomic.or_, atomic_cast_none, 0, False)
+
+
+def atomic_or2(ary, op2):
+ atomic_binary_2dim_shared(ary, op2, uint32, (4, 8),
+ cuda.atomic.or_, atomic_cast_none, False)
+
+
+def atomic_or3(ary, op2):
+ atomic_binary_2dim_shared(ary, op2, uint32, (4, 8),
+ cuda.atomic.or_, atomic_cast_to_uint64, False)
+
+
+def atomic_or_global(idx, ary, op2):
+ atomic_binary_1dim_global(ary, idx, 32, op2, cuda.atomic.or_, False)
+
+
+def atomic_or_global_2(ary, op2):
+ atomic_binary_2dim_global(ary, op2, cuda.atomic.or_,
+ atomic_cast_none, False)
+
+
+def atomic_xor(ary, op2):
+ atomic_binary_1dim_shared(ary, ary, op2, uint32, 32,
+ cuda.atomic.xor, atomic_cast_none, 0, False)
+
+
+def atomic_xor2(ary, op2):
+ atomic_binary_2dim_shared(ary, op2, uint32, (4, 8),
+ cuda.atomic.xor, atomic_cast_none, False)
+
+
+def atomic_xor3(ary, op2):
+ atomic_binary_2dim_shared(ary, op2, uint32, (4, 8),
+ cuda.atomic.xor, atomic_cast_to_uint64, False)
+
+
+def atomic_xor_global(idx, ary, op2):
+ atomic_binary_1dim_global(ary, idx, 32, op2, cuda.atomic.xor, False)
+
+
+def atomic_xor_global_2(ary, op2):
+ atomic_binary_2dim_global(ary, op2, cuda.atomic.xor,
+ atomic_cast_none, False)
+
+
+def atomic_inc32(ary, idx, op2):
+ atomic_binary_1dim_shared2(ary, idx, op2, uint32, 32,
+ cuda.atomic.inc, atomic_cast_none)
+
+
+def atomic_inc64(ary, idx, op2):
+ atomic_binary_1dim_shared2(ary, idx, op2, uint64, 32,
+ cuda.atomic.inc, atomic_cast_to_int)
+
+
+def atomic_inc2_32(ary, op2):
+ atomic_binary_2dim_shared(ary, op2, uint32, (4, 8),
+ cuda.atomic.inc, atomic_cast_none, False)
+
+
+def atomic_inc2_64(ary, op2):
+ atomic_binary_2dim_shared(ary, op2, uint64, (4, 8),
+ cuda.atomic.inc, atomic_cast_none, False)
+
+
+def atomic_inc3(ary, op2):
+ atomic_binary_2dim_shared(ary, op2, uint32, (4, 8),
+ cuda.atomic.inc, atomic_cast_to_uint64, False)
+
+
+def atomic_inc_global(idx, ary, op2):
+ atomic_binary_1dim_global(ary, idx, 32, op2, cuda.atomic.inc, False)
+
+
+def atomic_inc_global_2(ary, op2):
+ atomic_binary_2dim_global(ary, op2, cuda.atomic.inc,
+ atomic_cast_none, False)
+
+
+def atomic_dec32(ary, idx, op2):
+ atomic_binary_1dim_shared2(ary, idx, op2, uint32, 32,
+ cuda.atomic.dec, atomic_cast_none)
+
+
+def atomic_dec64(ary, idx, op2):
+ atomic_binary_1dim_shared2(ary, idx, op2, uint64, 32,
+ cuda.atomic.dec, atomic_cast_to_int)
+
+
+def atomic_dec2_32(ary, op2):
+ atomic_binary_2dim_shared(ary, op2, uint32, (4, 8),
+ cuda.atomic.dec, atomic_cast_none, False)
+
+
+def atomic_dec2_64(ary, op2):
+ atomic_binary_2dim_shared(ary, op2, uint64, (4, 8),
+ cuda.atomic.dec, atomic_cast_none, False)
+
+
+def atomic_dec3(ary, op2):
+ atomic_binary_2dim_shared(ary, op2, uint32, (4, 8),
+ cuda.atomic.dec, atomic_cast_to_uint64, False)
+
+
+def atomic_dec_global(idx, ary, op2):
+ atomic_binary_1dim_global(ary, idx, 32, op2, cuda.atomic.dec, False)
+
+
+def atomic_dec_global_2(ary, op2):
+ atomic_binary_2dim_global(ary, op2, cuda.atomic.dec,
+ atomic_cast_none, False)
+
+
+def atomic_exch(ary, idx, op2):
+ atomic_binary_1dim_shared2(ary, idx, op2, uint32, 32,
+ cuda.atomic.exch, atomic_cast_none)
+
+
+def atomic_exch2(ary, op2):
+ atomic_binary_2dim_shared(ary, op2, uint32, (4, 8),
+ cuda.atomic.exch, atomic_cast_none, False)
+
+
+def atomic_exch3(ary, op2):
+ atomic_binary_2dim_shared(ary, op2, uint64, (4, 8),
+ cuda.atomic.exch, atomic_cast_none, False)
+
+
+def atomic_exch_global(idx, ary, op2):
+ atomic_binary_1dim_global(ary, idx, 32, op2, cuda.atomic.exch, False)
+
+
+def gen_atomic_extreme_funcs(func):
+
+ fns = dedent("""
+ def atomic(res, ary):
+ tx = cuda.threadIdx.x
+ bx = cuda.blockIdx.x
+ {func}(res, 0, ary[tx, bx])
+
+ def atomic_double_normalizedindex(res, ary):
+ tx = cuda.threadIdx.x
+ bx = cuda.blockIdx.x
+ {func}(res, 0, ary[tx, uint64(bx)])
+
+ def atomic_double_oneindex(res, ary):
+ tx = cuda.threadIdx.x
+ {func}(res, 0, ary[tx])
+
+ def atomic_double_shared(res, ary):
+ tid = cuda.threadIdx.x
+ smary = cuda.shared.array(32, float64)
+ smary[tid] = ary[tid]
+ smres = cuda.shared.array(1, float64)
+ if tid == 0:
+ smres[0] = res[0]
+ cuda.syncthreads()
+ {func}(smres, 0, smary[tid])
+ cuda.syncthreads()
+ if tid == 0:
+ res[0] = smres[0]
+ """).format(func=func)
+ ld = {}
+ exec(fns, {'cuda': cuda, 'float64': float64, 'uint64': uint64}, ld)
+ return (ld['atomic'], ld['atomic_double_normalizedindex'],
+ ld['atomic_double_oneindex'], ld['atomic_double_shared'])
+
+
+(atomic_max, atomic_max_double_normalizedindex, atomic_max_double_oneindex,
+ atomic_max_double_shared) = gen_atomic_extreme_funcs('cuda.atomic.max')
+(atomic_min, atomic_min_double_normalizedindex, atomic_min_double_oneindex,
+ atomic_min_double_shared) = gen_atomic_extreme_funcs('cuda.atomic.min')
+(atomic_nanmax, atomic_nanmax_double_normalizedindex,
+ atomic_nanmax_double_oneindex, atomic_nanmax_double_shared) = \
+ gen_atomic_extreme_funcs('cuda.atomic.nanmax')
+(atomic_nanmin, atomic_nanmin_double_normalizedindex,
+ atomic_nanmin_double_oneindex, atomic_nanmin_double_shared) = \
+ gen_atomic_extreme_funcs('cuda.atomic.nanmin')
+
+
+def atomic_compare_and_swap(res, old, ary, fill_val):
+ gid = cuda.grid(1)
+ if gid < res.size:
+ old[gid] = cuda.atomic.compare_and_swap(res[gid:], fill_val, ary[gid])
+
+
+def atomic_cas_1dim(res, old, ary, fill_val):
+ gid = cuda.grid(1)
+ if gid < res.size:
+ old[gid] = cuda.atomic.cas(res, gid, fill_val, ary[gid])
+
+
+def atomic_cas_2dim(res, old, ary, fill_val):
+ gid = cuda.grid(2)
+ if gid[0] < res.shape[0] and gid[1] < res.shape[1]:
+ old[gid] = cuda.atomic.cas(res, gid, fill_val, ary[gid])
+
+
+class TestCudaAtomics(CUDATestCase):
+ def setUp(self):
+ super().setUp()
+ np.random.seed(0)
+
+ def test_atomic_add(self):
+ ary = np.random.randint(0, 32, size=32).astype(np.uint32)
+ ary_wrap = ary.copy()
+ orig = ary.copy()
+
+ cuda_atomic_add = cuda.jit('void(uint32[:])')(atomic_add)
+ cuda_atomic_add[1, 32](ary)
+
+ cuda_atomic_add_wrap = cuda.jit('void(uint32[:])')(atomic_add_wrap)
+ cuda_atomic_add_wrap[1, 32](ary_wrap)
+
+ gold = np.zeros(32, dtype=np.uint32)
+ for i in range(orig.size):
+ gold[orig[i]] += 1
+
+ self.assertTrue(np.all(ary == gold))
+ self.assertTrue(np.all(ary_wrap == gold))
+
+ def test_atomic_add2(self):
+ ary = np.random.randint(0, 32, size=32).astype(np.uint32).reshape(4, 8)
+ ary_wrap = ary.copy()
+ orig = ary.copy()
+
+ cuda_atomic_add2 = cuda.jit('void(uint32[:,:])')(atomic_add2)
+ cuda_atomic_add2[1, (4, 8)](ary)
+
+ cuda_atomic_add2_wrap = cuda.jit('void(uint32[:,:])')(atomic_add2_wrap)
+ cuda_atomic_add2_wrap[1, (4, 8)](ary_wrap)
+
+ self.assertTrue(np.all(ary == orig + 1))
+ self.assertTrue(np.all(ary_wrap == orig + 1))
+
+ def test_atomic_add3(self):
+ ary = np.random.randint(0, 32, size=32).astype(np.uint32).reshape(4, 8)
+ orig = ary.copy()
+ cuda_atomic_add3 = cuda.jit('void(uint32[:,:])')(atomic_add3)
+ cuda_atomic_add3[1, (4, 8)](ary)
+
+ self.assertTrue(np.all(ary == orig + 1))
+
+ def test_atomic_add_float(self):
+ ary = np.random.randint(0, 32, size=32).astype(np.float32)
+ ary_wrap = ary.copy()
+ orig = ary.copy().astype(np.intp)
+
+ cuda_atomic_add_float = cuda.jit('void(float32[:])')(atomic_add_float)
+ cuda_atomic_add_float[1, 32](ary)
+
+ add_float_wrap = cuda.jit('void(float32[:])')(atomic_add_float_wrap)
+ add_float_wrap[1, 32](ary_wrap)
+
+ gold = np.zeros(32, dtype=np.uint32)
+ for i in range(orig.size):
+ gold[orig[i]] += 1.0
+
+ self.assertTrue(np.all(ary == gold))
+ self.assertTrue(np.all(ary_wrap == gold))
+
+ def test_atomic_add_float_2(self):
+ ary = np.random.randint(0, 32, size=32).astype(np.float32).reshape(4, 8)
+ ary_wrap = ary.copy()
+ orig = ary.copy()
+
+ cuda_atomic_add2 = cuda.jit('void(float32[:,:])')(atomic_add_float_2)
+ cuda_atomic_add2[1, (4, 8)](ary)
+
+ cuda_func_wrap = cuda.jit('void(float32[:,:])')(atomic_add_float_2_wrap)
+ cuda_func_wrap[1, (4, 8)](ary_wrap)
+
+ self.assertTrue(np.all(ary == orig + 1))
+ self.assertTrue(np.all(ary_wrap == orig + 1))
+
+ def test_atomic_add_float_3(self):
+ ary = np.random.randint(0, 32, size=32).astype(np.float32).reshape(4, 8)
+ orig = ary.copy()
+ cuda_atomic_add3 = cuda.jit('void(float32[:,:])')(atomic_add_float_3)
+ cuda_atomic_add3[1, (4, 8)](ary)
+
+ self.assertTrue(np.all(ary == orig + 1))
+
+ def assertCorrectFloat64Atomics(self, kernel, shared=True):
+ if config.ENABLE_CUDASIM:
+ return
+
+ # Use the first (and only) definition
+ asm = next(iter(kernel.inspect_asm().values()))
+ if cc_X_or_above(6, 0):
+ if cuda.runtime.get_version() > (12, 1):
+ # CUDA 12.2 and above generate a more optimized reduction
+ # instruction, because the result does not need to be
+ # placed in a register.
+ inst = 'red'
+ else:
+ inst = 'atom'
+
+ if shared:
+ inst = f'{inst}.shared'
+
+ self.assertIn(f'{inst}.add.f64', asm)
+ else:
+ if shared:
+ self.assertIn('atom.shared.cas.b64', asm)
+ else:
+ self.assertIn('atom.cas.b64', asm)
+
+ def test_atomic_add_double(self):
+ idx = np.random.randint(0, 32, size=32, dtype=np.int64)
+ ary = np.zeros(32, np.float64)
+ ary_wrap = ary.copy()
+
+ cuda_fn = cuda.jit('void(int64[:], float64[:])')(atomic_add_double)
+ cuda_fn[1, 32](idx, ary)
+
+ wrap_fn = cuda.jit('void(int64[:], float64[:])')(atomic_add_double_wrap)
+ wrap_fn[1, 32](idx, ary_wrap)
+
+ gold = np.zeros(32, dtype=np.uint32)
+ for i in range(idx.size):
+ gold[idx[i]] += 1.0
+
+ np.testing.assert_equal(ary, gold)
+ np.testing.assert_equal(ary_wrap, gold)
+ self.assertCorrectFloat64Atomics(cuda_fn)
+ self.assertCorrectFloat64Atomics(wrap_fn)
+
+ def test_atomic_add_double_2(self):
+ ary = np.random.randint(0, 32, size=32).astype(np.float64).reshape(4, 8)
+ ary_wrap = ary.copy()
+ orig = ary.copy()
+
+ cuda_fn = cuda.jit('void(float64[:,:])')(atomic_add_double_2)
+ cuda_fn[1, (4, 8)](ary)
+
+ cuda_fn_wrap = cuda.jit('void(float64[:,:])')(atomic_add_double_2_wrap)
+ cuda_fn_wrap[1, (4, 8)](ary_wrap)
+
+ np.testing.assert_equal(ary, orig + 1)
+ np.testing.assert_equal(ary_wrap, orig + 1)
+ self.assertCorrectFloat64Atomics(cuda_fn)
+ self.assertCorrectFloat64Atomics(cuda_fn_wrap)
+
+ def test_atomic_add_double_3(self):
+ ary = np.random.randint(0, 32, size=32).astype(np.float64).reshape(4, 8)
+ orig = ary.copy()
+ cuda_func = cuda.jit('void(float64[:,:])')(atomic_add_double_3)
+ cuda_func[1, (4, 8)](ary)
+
+ np.testing.assert_equal(ary, orig + 1)
+ self.assertCorrectFloat64Atomics(cuda_func)
+
+ def test_atomic_add_double_global(self):
+ idx = np.random.randint(0, 32, size=32, dtype=np.int64)
+ ary = np.zeros(32, np.float64)
+ ary_wrap = ary.copy()
+
+ sig = 'void(int64[:], float64[:])'
+ cuda_func = cuda.jit(sig)(atomic_add_double_global)
+ wrap_cuda_func = cuda.jit(sig)(atomic_add_double_global_wrap)
+
+ cuda_func[1, 32](idx, ary)
+ wrap_cuda_func[1, 32](idx, ary_wrap)
+
+ gold = np.zeros(32, dtype=np.uint32)
+ for i in range(idx.size):
+ gold[idx[i]] += 1.0
+
+ np.testing.assert_equal(ary, gold)
+ np.testing.assert_equal(ary_wrap, gold)
+ self.assertCorrectFloat64Atomics(cuda_func, shared=False)
+ self.assertCorrectFloat64Atomics(wrap_cuda_func, shared=False)
+
+ def test_atomic_add_double_global_2(self):
+ ary = np.random.randint(0, 32, size=32).astype(np.float64).reshape(4, 8)
+ ary_wrap = ary.copy()
+ orig = ary.copy()
+
+ sig = 'void(float64[:,:])'
+ cuda_func = cuda.jit(sig)(atomic_add_double_global_2)
+ wrap_cuda_func = cuda.jit(sig)(atomic_add_double_global_2_wrap)
+
+ cuda_func[1, (4, 8)](ary)
+ wrap_cuda_func[1, (4, 8)](ary_wrap)
+
+ np.testing.assert_equal(ary, orig + 1)
+ np.testing.assert_equal(ary_wrap, orig + 1)
+ self.assertCorrectFloat64Atomics(cuda_func, shared=False)
+ self.assertCorrectFloat64Atomics(wrap_cuda_func, shared=False)
+
+ def test_atomic_add_double_global_3(self):
+ ary = np.random.randint(0, 32, size=32).astype(np.float64).reshape(4, 8)
+ orig = ary.copy()
+ cuda_func = cuda.jit('void(float64[:,:])')(atomic_add_double_global_3)
+ cuda_func[1, (4, 8)](ary)
+
+ np.testing.assert_equal(ary, orig + 1)
+ self.assertCorrectFloat64Atomics(cuda_func, shared=False)
+
+ def test_atomic_sub(self):
+ ary = np.random.randint(0, 32, size=32).astype(np.uint32)
+ orig = ary.copy()
+ cuda_atomic_sub = cuda.jit('void(uint32[:])')(atomic_sub)
+ cuda_atomic_sub[1, 32](ary)
+
+ gold = np.zeros(32, dtype=np.uint32)
+ for i in range(orig.size):
+ gold[orig[i]] -= 1
+
+ self.assertTrue(np.all(ary == gold))
+
+ def test_atomic_sub2(self):
+ ary = np.random.randint(0, 32, size=32).astype(np.uint32).reshape(4, 8)
+ orig = ary.copy()
+ cuda_atomic_sub2 = cuda.jit('void(uint32[:,:])')(atomic_sub2)
+ cuda_atomic_sub2[1, (4, 8)](ary)
+ self.assertTrue(np.all(ary == orig - 1))
+
+ def test_atomic_sub3(self):
+ ary = np.random.randint(0, 32, size=32).astype(np.uint32).reshape(4, 8)
+ orig = ary.copy()
+ cuda_atomic_sub3 = cuda.jit('void(uint32[:,:])')(atomic_sub3)
+ cuda_atomic_sub3[1, (4, 8)](ary)
+ self.assertTrue(np.all(ary == orig - 1))
+
+ def test_atomic_sub_float(self):
+ ary = np.random.randint(0, 32, size=32).astype(np.float32)
+ orig = ary.copy().astype(np.intp)
+ cuda_atomic_sub_float = cuda.jit('void(float32[:])')(atomic_sub_float)
+ cuda_atomic_sub_float[1, 32](ary)
+
+ gold = np.zeros(32, dtype=np.float32)
+ for i in range(orig.size):
+ gold[orig[i]] -= 1.0
+
+ self.assertTrue(np.all(ary == gold))
+
+ def test_atomic_sub_float_2(self):
+ ary = np.random.randint(0, 32, size=32).astype(np.float32).reshape(4, 8)
+ orig = ary.copy()
+ cuda_atomic_sub2 = cuda.jit('void(float32[:,:])')(atomic_sub_float_2)
+ cuda_atomic_sub2[1, (4, 8)](ary)
+ self.assertTrue(np.all(ary == orig - 1))
+
+ def test_atomic_sub_float_3(self):
+ ary = np.random.randint(0, 32, size=32).astype(np.float32).reshape(4, 8)
+ orig = ary.copy()
+ cuda_atomic_sub3 = cuda.jit('void(float32[:,:])')(atomic_sub_float_3)
+ cuda_atomic_sub3[1, (4, 8)](ary)
+ self.assertTrue(np.all(ary == orig - 1))
+
+ def test_atomic_sub_double(self):
+ idx = np.random.randint(0, 32, size=32, dtype=np.int64)
+ ary = np.zeros(32, np.float64)
+ cuda_func = cuda.jit('void(int64[:], float64[:])')(atomic_sub_double)
+ cuda_func[1, 32](idx, ary)
+
+ gold = np.zeros(32, dtype=np.float64)
+ for i in range(idx.size):
+ gold[idx[i]] -= 1.0
+
+ np.testing.assert_equal(ary, gold)
+
+ def test_atomic_sub_double_2(self):
+ ary = np.random.randint(0, 32, size=32).astype(np.float64).reshape(4, 8)
+ orig = ary.copy()
+ cuda_func = cuda.jit('void(float64[:,:])')(atomic_sub_double_2)
+ cuda_func[1, (4, 8)](ary)
+ np.testing.assert_equal(ary, orig - 1)
+
+ def test_atomic_sub_double_3(self):
+ ary = np.random.randint(0, 32, size=32).astype(np.float64).reshape(4, 8)
+ orig = ary.copy()
+ cuda_func = cuda.jit('void(float64[:,:])')(atomic_sub_double_3)
+ cuda_func[1, (4, 8)](ary)
+ np.testing.assert_equal(ary, orig - 1)
+
+ def test_atomic_sub_double_global(self):
+ idx = np.random.randint(0, 32, size=32, dtype=np.int64)
+ ary = np.zeros(32, np.float64)
+ sig = 'void(int64[:], float64[:])'
+ cuda_func = cuda.jit(sig)(atomic_sub_double_global)
+ cuda_func[1, 32](idx, ary)
+
+ gold = np.zeros(32, dtype=np.float64)
+ for i in range(idx.size):
+ gold[idx[i]] -= 1.0
+
+ np.testing.assert_equal(ary, gold)
+
+ def test_atomic_sub_double_global_2(self):
+ ary = np.random.randint(0, 32, size=32).astype(np.float64).reshape(4, 8)
+ orig = ary.copy()
+ cuda_func = cuda.jit('void(float64[:,:])')(atomic_sub_double_global_2)
+ cuda_func[1, (4, 8)](ary)
+ np.testing.assert_equal(ary, orig - 1)
+
+ def test_atomic_sub_double_global_3(self):
+ ary = np.random.randint(0, 32, size=32).astype(np.float64).reshape(4, 8)
+ orig = ary.copy()
+ cuda_func = cuda.jit('void(float64[:,:])')(atomic_sub_double_global_3)
+ cuda_func[1, (4, 8)](ary)
+ np.testing.assert_equal(ary, orig - 1)
+
+ def test_atomic_and(self):
+ rand_const = np.random.randint(500)
+ ary = np.random.randint(0, 32, size=32).astype(np.uint32)
+ orig = ary.copy()
+ cuda_func = cuda.jit('void(uint32[:], uint32)')(atomic_and)
+ cuda_func[1, 32](ary, rand_const)
+
+ gold = ary.copy()
+ for i in range(orig.size):
+ gold[orig[i]] &= rand_const
+
+ self.assertTrue(np.all(ary == gold))
+
+ def test_atomic_and2(self):
+ rand_const = np.random.randint(500)
+ ary = np.random.randint(0, 32, size=32).astype(np.uint32).reshape(4, 8)
+ orig = ary.copy()
+ cuda_atomic_and2 = cuda.jit('void(uint32[:,:], uint32)')(atomic_and2)
+ cuda_atomic_and2[1, (4, 8)](ary, rand_const)
+ self.assertTrue(np.all(ary == orig & rand_const))
+
+ def test_atomic_and3(self):
+ rand_const = np.random.randint(500)
+ ary = np.random.randint(0, 32, size=32).astype(np.uint32).reshape(4, 8)
+ orig = ary.copy()
+ cuda_atomic_and3 = cuda.jit('void(uint32[:,:], uint32)')(atomic_and3)
+ cuda_atomic_and3[1, (4, 8)](ary, rand_const)
+ self.assertTrue(np.all(ary == orig & rand_const))
+
+ def test_atomic_and_global(self):
+ rand_const = np.random.randint(500)
+ idx = np.random.randint(0, 32, size=32, dtype=np.int32)
+ ary = np.random.randint(0, 32, size=32, dtype=np.int32)
+ sig = 'void(int32[:], int32[:], int32)'
+ cuda_func = cuda.jit(sig)(atomic_and_global)
+ cuda_func[1, 32](idx, ary, rand_const)
+
+ gold = ary.copy()
+ for i in range(idx.size):
+ gold[idx[i]] &= rand_const
+
+ np.testing.assert_equal(ary, gold)
+
+ def test_atomic_and_global_2(self):
+ rand_const = np.random.randint(500)
+ ary = np.random.randint(0, 32, size=32).astype(np.uint32).reshape(4, 8)
+ orig = ary.copy()
+ cuda_func = cuda.jit('void(uint32[:,:], uint32)')(atomic_and_global_2)
+ cuda_func[1, (4, 8)](ary, rand_const)
+ np.testing.assert_equal(ary, orig & rand_const)
+
+ def test_atomic_or(self):
+ rand_const = np.random.randint(500)
+ ary = np.random.randint(0, 32, size=32).astype(np.uint32)
+ orig = ary.copy()
+ cuda_func = cuda.jit('void(uint32[:], uint32)')(atomic_or)
+ cuda_func[1, 32](ary, rand_const)
+
+ gold = np.zeros(32, dtype=np.uint32)
+ for i in range(orig.size):
+ gold[orig[i]] |= rand_const
+
+ self.assertTrue(np.all(ary == gold))
+
+ def test_atomic_or2(self):
+ rand_const = np.random.randint(500)
+ ary = np.random.randint(0, 32, size=32).astype(np.uint32).reshape(4, 8)
+ orig = ary.copy()
+ cuda_atomic_and2 = cuda.jit('void(uint32[:,:], uint32)')(atomic_or2)
+ cuda_atomic_and2[1, (4, 8)](ary, rand_const)
+ self.assertTrue(np.all(ary == orig | rand_const))
+
+ def test_atomic_or3(self):
+ rand_const = np.random.randint(500)
+ ary = np.random.randint(0, 32, size=32).astype(np.uint32).reshape(4, 8)
+ orig = ary.copy()
+ cuda_atomic_and3 = cuda.jit('void(uint32[:,:], uint32)')(atomic_or3)
+ cuda_atomic_and3[1, (4, 8)](ary, rand_const)
+ self.assertTrue(np.all(ary == orig | rand_const))
+
+ def test_atomic_or_global(self):
+ rand_const = np.random.randint(500)
+ idx = np.random.randint(0, 32, size=32, dtype=np.int32)
+ ary = np.random.randint(0, 32, size=32, dtype=np.int32)
+ sig = 'void(int32[:], int32[:], int32)'
+ cuda_func = cuda.jit(sig)(atomic_or_global)
+ cuda_func[1, 32](idx, ary, rand_const)
+
+ gold = ary.copy()
+ for i in range(idx.size):
+ gold[idx[i]] |= rand_const
+
+ np.testing.assert_equal(ary, gold)
+
+ def test_atomic_or_global_2(self):
+ rand_const = np.random.randint(500)
+ ary = np.random.randint(0, 32, size=32).astype(np.uint32).reshape(4, 8)
+ orig = ary.copy()
+ cuda_func = cuda.jit('void(uint32[:,:], uint32)')(atomic_or_global_2)
+ cuda_func[1, (4, 8)](ary, rand_const)
+ np.testing.assert_equal(ary, orig | rand_const)
+
+ def test_atomic_xor(self):
+ rand_const = np.random.randint(500)
+ ary = np.random.randint(0, 32, size=32).astype(np.uint32)
+ orig = ary.copy()
+ cuda_func = cuda.jit('void(uint32[:], uint32)')(atomic_xor)
+ cuda_func[1, 32](ary, rand_const)
+
+ gold = np.zeros(32, dtype=np.uint32)
+ for i in range(orig.size):
+ gold[orig[i]] ^= rand_const
+
+ self.assertTrue(np.all(ary == gold))
+
+ def test_atomic_xor2(self):
+ rand_const = np.random.randint(500)
+ ary = np.random.randint(0, 32, size=32).astype(np.uint32).reshape(4, 8)
+ orig = ary.copy()
+ cuda_atomic_xor2 = cuda.jit('void(uint32[:,:], uint32)')(atomic_xor2)
+ cuda_atomic_xor2[1, (4, 8)](ary, rand_const)
+ self.assertTrue(np.all(ary == orig ^ rand_const))
+
+ def test_atomic_xor3(self):
+ rand_const = np.random.randint(500)
+ ary = np.random.randint(0, 32, size=32).astype(np.uint32).reshape(4, 8)
+ orig = ary.copy()
+ cuda_atomic_xor3 = cuda.jit('void(uint32[:,:], uint32)')(atomic_xor3)
+ cuda_atomic_xor3[1, (4, 8)](ary, rand_const)
+ self.assertTrue(np.all(ary == orig ^ rand_const))
+
+ def test_atomic_xor_global(self):
+ rand_const = np.random.randint(500)
+ idx = np.random.randint(0, 32, size=32, dtype=np.int32)
+ ary = np.random.randint(0, 32, size=32, dtype=np.int32)
+ gold = ary.copy()
+ sig = 'void(int32[:], int32[:], int32)'
+ cuda_func = cuda.jit(sig)(atomic_xor_global)
+ cuda_func[1, 32](idx, ary, rand_const)
+
+ for i in range(idx.size):
+ gold[idx[i]] ^= rand_const
+
+ np.testing.assert_equal(ary, gold)
+
+ def test_atomic_xor_global_2(self):
+ rand_const = np.random.randint(500)
+ ary = np.random.randint(0, 32, size=32).astype(np.uint32).reshape(4, 8)
+ orig = ary.copy()
+ cuda_func = cuda.jit('void(uint32[:,:], uint32)')(atomic_xor_global_2)
+ cuda_func[1, (4, 8)](ary, rand_const)
+ np.testing.assert_equal(ary, orig ^ rand_const)
+
+ def inc_dec_1dim_setup(self, dtype):
+ rconst = np.random.randint(32, dtype=dtype)
+ rary = np.random.randint(0, 32, size=32).astype(dtype)
+ ary_idx = np.arange(32, dtype=dtype)
+ return rconst, rary, ary_idx
+
+ def inc_dec_2dim_setup(self, dtype):
+ rconst = np.random.randint(32, dtype=dtype)
+ rary = np.random.randint(0, 32, size=32).astype(dtype).reshape(4, 8)
+ return rconst, rary
+
+ def check_inc_index(self, ary, idx, rconst, sig, nblocks, blksize, func):
+ orig = ary.copy()
+ cuda_func = cuda.jit(sig)(func)
+ cuda_func[nblocks, blksize](ary, idx, rconst)
+ np.testing.assert_equal(ary, np.where(orig >= rconst, 0, orig + 1))
+
+ def check_inc_index2(self, ary, idx, rconst, sig, nblocks, blksize, func):
+ orig = ary.copy()
+ cuda_func = cuda.jit(sig)(func)
+ cuda_func[nblocks, blksize](idx, ary, rconst)
+ np.testing.assert_equal(ary, np.where(orig >= rconst, 0, orig + 1))
+
+ def check_inc(self, ary, rconst, sig, nblocks, blksize, func):
+ orig = ary.copy()
+ cuda_func = cuda.jit(sig)(func)
+ cuda_func[nblocks, blksize](ary, rconst)
+ np.testing.assert_equal(ary, np.where(orig >= rconst, 0, orig + 1))
+
+ def test_atomic_inc_32(self):
+ rand_const, ary, idx = self.inc_dec_1dim_setup(dtype=np.uint32)
+ sig = 'void(uint32[:], uint32[:], uint32)'
+ self.check_inc_index(ary, idx, rand_const, sig, 1, 32, atomic_inc32)
+
+ def test_atomic_inc_64(self):
+ rand_const, ary, idx = self.inc_dec_1dim_setup(dtype=np.uint64)
+ sig = 'void(uint64[:], uint64[:], uint64)'
+ self.check_inc_index(ary, idx, rand_const, sig, 1, 32, atomic_inc64)
+
+ def test_atomic_inc2_32(self):
+ rand_const, ary = self.inc_dec_2dim_setup(np.uint32)
+ sig = 'void(uint32[:,:], uint32)'
+ self.check_inc(ary, rand_const, sig, 1, (4,8), atomic_inc2_32)
+
+ def test_atomic_inc2_64(self):
+ rand_const, ary = self.inc_dec_2dim_setup(np.uint64)
+ sig = 'void(uint64[:,:], uint64)'
+ self.check_inc(ary, rand_const, sig, 1, (4,8), atomic_inc2_64)
+
+ def test_atomic_inc3(self):
+ rand_const, ary = self.inc_dec_2dim_setup(np.uint32)
+ sig = 'void(uint32[:,:], uint32)'
+ self.check_inc(ary, rand_const, sig, 1, (4,8), atomic_inc3)
+
+ def test_atomic_inc_global_32(self):
+ rand_const, ary, idx = self.inc_dec_1dim_setup(dtype=np.uint32)
+ sig = 'void(uint32[:], uint32[:], uint32)'
+ self.check_inc_index2(ary, idx, rand_const, sig, 1, 32,
+ atomic_inc_global)
+
+ def test_atomic_inc_global_64(self):
+ rand_const, ary, idx = self.inc_dec_1dim_setup(dtype=np.uint64)
+ sig = 'void(uint64[:], uint64[:], uint64)'
+ self.check_inc_index2(ary, idx, rand_const, sig, 1, 32,
+ atomic_inc_global)
+
+ def test_atomic_inc_global_2_32(self):
+ rand_const, ary = self.inc_dec_2dim_setup(np.uint32)
+ sig = 'void(uint32[:,:], uint32)'
+ self.check_inc(ary, rand_const, sig, 1, (4,8), atomic_inc_global_2)
+
+ def test_atomic_inc_global_2_64(self):
+ rand_const, ary = self.inc_dec_2dim_setup(np.uint64)
+ sig = 'void(uint64[:,:], uint64)'
+ self.check_inc(ary, rand_const, sig, 1, (4,8), atomic_inc_global_2)
+
+ def check_dec_index(self, ary, idx, rconst, sig, nblocks, blksize, func):
+ orig = ary.copy()
+ cuda_func = cuda.jit(sig)(func)
+ cuda_func[nblocks, blksize](ary, idx, rconst)
+ np.testing.assert_equal(ary, np.where(orig == 0, rconst,
+ np.where(orig > rconst,
+ rconst,
+ orig - 1)))
+
+ def check_dec_index2(self, ary, idx, rconst, sig, nblocks, blksize, func):
+ orig = ary.copy()
+ cuda_func = cuda.jit(sig)(func)
+ cuda_func[nblocks, blksize](idx, ary, rconst)
+ np.testing.assert_equal(ary, np.where(orig == 0, rconst,
+ np.where(orig > rconst,
+ rconst,
+ orig - 1)))
+
+ def check_dec(self, ary, rconst, sig, nblocks, blksize, func):
+ orig = ary.copy()
+ cuda_func = cuda.jit(sig)(func)
+ cuda_func[nblocks, blksize](ary, rconst)
+ np.testing.assert_equal(ary, np.where(orig == 0, rconst,
+ np.where(orig > rconst,
+ rconst,
+ orig - 1)))
+
+ def test_atomic_dec_32(self):
+ rand_const, ary, idx = self.inc_dec_1dim_setup(dtype=np.uint32)
+ sig = 'void(uint32[:], uint32[:], uint32)'
+ self.check_dec_index(ary, idx, rand_const, sig, 1, 32, atomic_dec32)
+
+ def test_atomic_dec_64(self):
+ rand_const, ary, idx = self.inc_dec_1dim_setup(dtype=np.uint64)
+ sig = 'void(uint64[:], uint64[:], uint64)'
+ self.check_dec_index(ary, idx, rand_const, sig, 1, 32, atomic_dec64)
+
+ def test_atomic_dec2_32(self):
+ rand_const, ary = self.inc_dec_2dim_setup(np.uint32)
+ sig = 'void(uint32[:,:], uint32)'
+ self.check_dec(ary, rand_const, sig, 1, (4,8), atomic_dec2_32)
+
+ def test_atomic_dec2_64(self):
+ rand_const, ary = self.inc_dec_2dim_setup(np.uint64)
+ sig = 'void(uint64[:,:], uint64)'
+ self.check_dec(ary, rand_const, sig, 1, (4,8), atomic_dec2_64)
+
+ def test_atomic_dec3_new(self):
+ rand_const, ary = self.inc_dec_2dim_setup(np.uint32)
+ sig = 'void(uint32[:,:], uint32)'
+ self.check_dec(ary, rand_const, sig, 1, (4,8), atomic_dec3)
+
+ def test_atomic_dec_global_32(self):
+ rand_const, ary, idx = self.inc_dec_1dim_setup(dtype=np.uint32)
+ sig = 'void(uint32[:], uint32[:], uint32)'
+ self.check_dec_index2(ary, idx, rand_const, sig, 1, 32,
+ atomic_dec_global)
+
+ def test_atomic_dec_global_64(self):
+ rand_const, ary, idx = self.inc_dec_1dim_setup(dtype=np.uint64)
+ sig = 'void(uint64[:], uint64[:], uint64)'
+ self.check_dec_index2(ary, idx, rand_const, sig, 1, 32,
+ atomic_dec_global)
+
+ def test_atomic_dec_global2_32(self):
+ rand_const, ary = self.inc_dec_2dim_setup(np.uint32)
+ sig = 'void(uint32[:,:], uint32)'
+ self.check_dec(ary, rand_const, sig, 1, (4,8), atomic_dec_global_2)
+
+ def test_atomic_dec_global2_64(self):
+ rand_const, ary = self.inc_dec_2dim_setup(np.uint64)
+ sig = 'void(uint64[:,:], uint64)'
+ self.check_dec(ary, rand_const, sig, 1, (4,8), atomic_dec_global_2)
+
+ def test_atomic_exch(self):
+ rand_const = np.random.randint(50, 100, dtype=np.uint32)
+ ary = np.random.randint(0, 32, size=32).astype(np.uint32)
+ idx = np.arange(32, dtype=np.uint32)
+
+ cuda_func = cuda.jit('void(uint32[:], uint32[:], uint32)')(atomic_exch)
+ cuda_func[1, 32](ary, idx, rand_const)
+
+ np.testing.assert_equal(ary, rand_const)
+
+ def test_atomic_exch2(self):
+ rand_const = np.random.randint(50, 100, dtype=np.uint32)
+ ary = np.random.randint(0, 32, size=32).astype(np.uint32).reshape(4, 8)
+
+ cuda_func = cuda.jit('void(uint32[:,:], uint32)')(atomic_exch2)
+ cuda_func[1, (4, 8)](ary, rand_const)
+ np.testing.assert_equal(ary, rand_const)
+
+ def test_atomic_exch3(self):
+ rand_const = np.random.randint(50, 100, dtype=np.uint64)
+ ary = np.random.randint(0, 32, size=32).astype(np.uint64).reshape(4, 8)
+
+ cuda_func = cuda.jit('void(uint64[:,:], uint64)')(atomic_exch3)
+ cuda_func[1, (4, 8)](ary, rand_const)
+ np.testing.assert_equal(ary, rand_const)
+
+ def test_atomic_exch_global(self):
+ rand_const = np.random.randint(50, 100, dtype=np.uint32)
+ idx = np.arange(32, dtype=np.uint32)
+ ary = np.random.randint(0, 32, size=32, dtype=np.uint32)
+
+ sig = 'void(uint32[:], uint32[:], uint32)'
+ cuda_func = cuda.jit(sig)(atomic_exch_global)
+ cuda_func[1, 32](idx, ary, rand_const)
+ np.testing.assert_equal(ary, rand_const)
+
+ def check_atomic_max(self, dtype, lo, hi):
+ vals = np.random.randint(lo, hi, size=(32, 32)).astype(dtype)
+ res = np.zeros(1, dtype=vals.dtype)
+ cuda_func = cuda.jit(atomic_max)
+ cuda_func[32, 32](res, vals)
+ gold = np.max(vals)
+ np.testing.assert_equal(res, gold)
+
+ def test_atomic_max_int32(self):
+ self.check_atomic_max(dtype=np.int32, lo=-65535, hi=65535)
+
+ def test_atomic_max_uint32(self):
+ self.check_atomic_max(dtype=np.uint32, lo=0, hi=65535)
+
+ def test_atomic_max_int64(self):
+ self.check_atomic_max(dtype=np.int64, lo=-65535, hi=65535)
+
+ def test_atomic_max_uint64(self):
+ self.check_atomic_max(dtype=np.uint64, lo=0, hi=65535)
+
+ def test_atomic_max_float32(self):
+ self.check_atomic_max(dtype=np.float32, lo=-65535, hi=65535)
+
+ def test_atomic_max_double(self):
+ self.check_atomic_max(dtype=np.float64, lo=-65535, hi=65535)
+
+ def test_atomic_max_double_normalizedindex(self):
+ vals = np.random.randint(0, 65535, size=(32, 32)).astype(np.float64)
+ res = np.zeros(1, np.float64)
+ cuda_func = cuda.jit('void(float64[:], float64[:,:])')(
+ atomic_max_double_normalizedindex)
+ cuda_func[32, 32](res, vals)
+
+ gold = np.max(vals)
+ np.testing.assert_equal(res, gold)
+
+ def test_atomic_max_double_oneindex(self):
+ vals = np.random.randint(0, 128, size=32).astype(np.float64)
+ res = np.zeros(1, np.float64)
+ cuda_func = cuda.jit('void(float64[:], float64[:])')(
+ atomic_max_double_oneindex)
+ cuda_func[1, 32](res, vals)
+
+ gold = np.max(vals)
+ np.testing.assert_equal(res, gold)
+
+ def check_atomic_min(self, dtype, lo, hi):
+ vals = np.random.randint(lo, hi, size=(32, 32)).astype(dtype)
+ res = np.array([65535], dtype=vals.dtype)
+ cuda_func = cuda.jit(atomic_min)
+ cuda_func[32, 32](res, vals)
+
+ gold = np.min(vals)
+ np.testing.assert_equal(res, gold)
+
+ def test_atomic_min_int32(self):
+ self.check_atomic_min(dtype=np.int32, lo=-65535, hi=65535)
+
+ def test_atomic_min_uint32(self):
+ self.check_atomic_min(dtype=np.uint32, lo=0, hi=65535)
+
+ def test_atomic_min_int64(self):
+ self.check_atomic_min(dtype=np.int64, lo=-65535, hi=65535)
+
+ def test_atomic_min_uint64(self):
+ self.check_atomic_min(dtype=np.uint64, lo=0, hi=65535)
+
+ def test_atomic_min_float(self):
+ self.check_atomic_min(dtype=np.float32, lo=-65535, hi=65535)
+
+ def test_atomic_min_double(self):
+ self.check_atomic_min(dtype=np.float64, lo=-65535, hi=65535)
+
+ def test_atomic_min_double_normalizedindex(self):
+ vals = np.random.randint(0, 65535, size=(32, 32)).astype(np.float64)
+ res = np.ones(1, np.float64) * 65535
+ cuda_func = cuda.jit('void(float64[:], float64[:,:])')(
+ atomic_min_double_normalizedindex)
+ cuda_func[32, 32](res, vals)
+
+ gold = np.min(vals)
+ np.testing.assert_equal(res, gold)
+
+ def test_atomic_min_double_oneindex(self):
+ vals = np.random.randint(0, 128, size=32).astype(np.float64)
+ res = np.ones(1, np.float64) * 128
+ cuda_func = cuda.jit('void(float64[:], float64[:])')(
+ atomic_min_double_oneindex)
+ cuda_func[1, 32](res, vals)
+
+ gold = np.min(vals)
+ np.testing.assert_equal(res, gold)
+
+ # Taken together, _test_atomic_minmax_nan_location and
+ # _test_atomic_minmax_nan_val check that NaNs are treated similarly to the
+ # way they are in Python / NumPy - that is, {min,max}(a, b) == a if either
+ # a or b is a NaN. For the atomics, this means that the max is taken as the
+ # value stored in the memory location rather than the value supplied - i.e.
+ # for:
+ #
+ # cuda.atomic.{min,max}(ary, idx, val)
+ #
+ # the result will be ary[idx] for either of ary[idx] or val being NaN.
+
+ def _test_atomic_minmax_nan_location(self, func):
+
+ cuda_func = cuda.jit('void(float64[:], float64[:,:])')(func)
+
+ vals = np.random.randint(0, 128, size=(1,1)).astype(np.float64)
+ res = np.zeros(1, np.float64) + np.nan
+ cuda_func[1, 1](res, vals)
+ np.testing.assert_equal(res, [np.nan])
+
+ def _test_atomic_minmax_nan_val(self, func):
+ cuda_func = cuda.jit('void(float64[:], float64[:,:])')(func)
+
+ res = np.random.randint(0, 128, size=1).astype(np.float64)
+ gold = res.copy()
+ vals = np.zeros((1, 1), np.float64) + np.nan
+ cuda_func[1, 1](res, vals)
+
+ np.testing.assert_equal(res, gold)
+
+ def test_atomic_min_nan_location(self):
+ self._test_atomic_minmax_nan_location(atomic_min)
+
+ def test_atomic_max_nan_location(self):
+ self._test_atomic_minmax_nan_location(atomic_max)
+
+ def test_atomic_min_nan_val(self):
+ self._test_atomic_minmax_nan_val(atomic_min)
+
+ def test_atomic_max_nan_val(self):
+ self._test_atomic_minmax_nan_val(atomic_max)
+
+ def test_atomic_max_double_shared(self):
+ vals = np.random.randint(0, 32, size=32).astype(np.float64)
+ res = np.zeros(1, np.float64)
+ sig = 'void(float64[:], float64[:])'
+ cuda_func = cuda.jit(sig)(atomic_max_double_shared)
+ cuda_func[1, 32](res, vals)
+
+ gold = np.max(vals)
+ np.testing.assert_equal(res, gold)
+
+ def test_atomic_min_double_shared(self):
+ vals = np.random.randint(0, 32, size=32).astype(np.float64)
+ res = np.ones(1, np.float64) * 32
+ sig = 'void(float64[:], float64[:])'
+ cuda_func = cuda.jit(sig)(atomic_min_double_shared)
+ cuda_func[1, 32](res, vals)
+
+ gold = np.min(vals)
+ np.testing.assert_equal(res, gold)
+
+ def check_cas(self, n, fill, unfill, dtype, cas_func, ndim=1):
+ res = [fill] * (n // 2) + [unfill] * (n // 2)
+ np.random.shuffle(res)
+ res = np.asarray(res, dtype=dtype)
+ if ndim == 2:
+ res.shape = (10, -1)
+ out = np.zeros_like(res)
+ ary = np.random.randint(1, 10, size=res.shape).astype(res.dtype)
+
+ fill_mask = res == fill
+ unfill_mask = res == unfill
+
+ expect_res = np.zeros_like(res)
+ expect_res[fill_mask] = ary[fill_mask]
+ expect_res[unfill_mask] = unfill
+
+ expect_out = res.copy()
+
+ cuda_func = cuda.jit(cas_func)
+ if ndim == 1:
+ cuda_func[10, 10](res, out, ary, fill)
+ else:
+ cuda_func[(10, 10), (10, 10)](res, out, ary, fill)
+
+ np.testing.assert_array_equal(expect_res, res)
+ np.testing.assert_array_equal(expect_out, out)
+
+ def test_atomic_compare_and_swap(self):
+ self.check_cas(n=100, fill=-99, unfill=-1, dtype=np.int32,
+ cas_func=atomic_compare_and_swap)
+
+ def test_atomic_compare_and_swap2(self):
+ self.check_cas(n=100, fill=-45, unfill=-1, dtype=np.int64,
+ cas_func=atomic_compare_and_swap)
+
+ def test_atomic_compare_and_swap3(self):
+ rfill = np.random.randint(50, 500, dtype=np.uint32)
+ runfill = np.random.randint(1, 25, dtype=np.uint32)
+ self.check_cas(n=100, fill=rfill, unfill=runfill, dtype=np.uint32,
+ cas_func=atomic_compare_and_swap)
+
+ def test_atomic_compare_and_swap4(self):
+ rfill = np.random.randint(50, 500, dtype=np.uint64)
+ runfill = np.random.randint(1, 25, dtype=np.uint64)
+ self.check_cas(n=100, fill=rfill, unfill=runfill, dtype=np.uint64,
+ cas_func=atomic_compare_and_swap)
+
+ def test_atomic_cas_1dim(self):
+ self.check_cas(n=100, fill=-99, unfill=-1, dtype=np.int32,
+ cas_func=atomic_cas_1dim)
+
+ def test_atomic_cas_2dim(self):
+ self.check_cas(n=100, fill=-99, unfill=-1, dtype=np.int32,
+ cas_func=atomic_cas_2dim, ndim=2)
+
+ def test_atomic_cas2_1dim(self):
+ self.check_cas(n=100, fill=-45, unfill=-1, dtype=np.int64,
+ cas_func=atomic_cas_1dim)
+
+ def test_atomic_cas2_2dim(self):
+ self.check_cas(n=100, fill=-45, unfill=-1, dtype=np.int64,
+ cas_func=atomic_cas_2dim, ndim=2)
+
+ def test_atomic_cas3_1dim(self):
+ rfill = np.random.randint(50, 500, dtype=np.uint32)
+ runfill = np.random.randint(1, 25, dtype=np.uint32)
+ self.check_cas(n=100, fill=rfill, unfill=runfill, dtype=np.uint32,
+ cas_func=atomic_cas_1dim)
+
+ def test_atomic_cas3_2dim(self):
+ rfill = np.random.randint(50, 500, dtype=np.uint32)
+ runfill = np.random.randint(1, 25, dtype=np.uint32)
+ self.check_cas(n=100, fill=rfill, unfill=runfill, dtype=np.uint32,
+ cas_func=atomic_cas_2dim, ndim=2)
+
+ def test_atomic_cas4_1dim(self):
+ rfill = np.random.randint(50, 500, dtype=np.uint64)
+ runfill = np.random.randint(1, 25, dtype=np.uint64)
+ self.check_cas(n=100, fill=rfill, unfill=runfill, dtype=np.uint64,
+ cas_func=atomic_cas_1dim)
+
+ def test_atomic_cas4_2dim(self):
+ rfill = np.random.randint(50, 500, dtype=np.uint64)
+ runfill = np.random.randint(1, 25, dtype=np.uint64)
+ self.check_cas(n=100, fill=rfill, unfill=runfill, dtype=np.uint64,
+ cas_func=atomic_cas_2dim, ndim=2)
+
+ # Tests that the atomic add, min, and max operations return the old value -
+ # in the simulator, they did not (see Issue #5458). The max and min have
+ # special handling for NaN values, so we explicitly test with a NaN in the
+ # array being modified and the value provided.
+
+ def _test_atomic_returns_old(self, kernel, initial):
+ x = np.zeros(2, dtype=np.float32)
+ x[0] = initial
+ kernel[1, 1](x)
+ if np.isnan(initial):
+ self.assertTrue(np.isnan(x[1]))
+ else:
+ self.assertEqual(x[1], initial)
+
+ def test_atomic_add_returns_old(self):
+ @cuda.jit
+ def kernel(x):
+ x[1] = cuda.atomic.add(x, 0, 1)
+
+ self._test_atomic_returns_old(kernel, 10)
+
+ def test_atomic_max_returns_no_replace(self):
+ @cuda.jit
+ def kernel(x):
+ x[1] = cuda.atomic.max(x, 0, 1)
+
+ self._test_atomic_returns_old(kernel, 10)
+
+ def test_atomic_max_returns_old_replace(self):
+ @cuda.jit
+ def kernel(x):
+ x[1] = cuda.atomic.max(x, 0, 10)
+
+ self._test_atomic_returns_old(kernel, 1)
+
+ def test_atomic_max_returns_old_nan_in_array(self):
+ @cuda.jit
+ def kernel(x):
+ x[1] = cuda.atomic.max(x, 0, 1)
+
+ self._test_atomic_returns_old(kernel, np.nan)
+
+ def test_atomic_max_returns_old_nan_val(self):
+ @cuda.jit
+ def kernel(x):
+ x[1] = cuda.atomic.max(x, 0, np.nan)
+
+ self._test_atomic_returns_old(kernel, 10)
+
+ def test_atomic_min_returns_old_no_replace(self):
+ @cuda.jit
+ def kernel(x):
+ x[1] = cuda.atomic.min(x, 0, 11)
+
+ self._test_atomic_returns_old(kernel, 10)
+
+ def test_atomic_min_returns_old_replace(self):
+ @cuda.jit
+ def kernel(x):
+ x[1] = cuda.atomic.min(x, 0, 10)
+
+ self._test_atomic_returns_old(kernel, 11)
+
+ def test_atomic_min_returns_old_nan_in_array(self):
+ @cuda.jit
+ def kernel(x):
+ x[1] = cuda.atomic.min(x, 0, 11)
+
+ self._test_atomic_returns_old(kernel, np.nan)
+
+ def test_atomic_min_returns_old_nan_val(self):
+ @cuda.jit
+ def kernel(x):
+ x[1] = cuda.atomic.min(x, 0, np.nan)
+
+ self._test_atomic_returns_old(kernel, 11)
+
+ # Tests for atomic nanmin/nanmax
+
+ # nanmax tests
+ def check_atomic_nanmax(self, dtype, lo, hi, init_val):
+ vals = np.random.randint(lo, hi, size=(32, 32)).astype(dtype)
+ vals[1::2] = init_val
+ res = np.zeros(1, dtype=vals.dtype)
+ cuda_func = cuda.jit(atomic_nanmax)
+ cuda_func[32, 32](res, vals)
+ gold = np.nanmax(vals)
+ np.testing.assert_equal(res, gold)
+
+ def test_atomic_nanmax_int32(self):
+ self.check_atomic_nanmax(dtype=np.int32, lo=-65535, hi=65535,
+ init_val=0)
+
+ def test_atomic_nanmax_uint32(self):
+ self.check_atomic_nanmax(dtype=np.uint32, lo=0, hi=65535,
+ init_val=0)
+
+ def test_atomic_nanmax_int64(self):
+ self.check_atomic_nanmax(dtype=np.int64, lo=-65535, hi=65535,
+ init_val=0)
+
+ def test_atomic_nanmax_uint64(self):
+ self.check_atomic_nanmax(dtype=np.uint64, lo=0, hi=65535,
+ init_val=0)
+
+ def test_atomic_nanmax_float32(self):
+ self.check_atomic_nanmax(dtype=np.float32, lo=-65535, hi=65535,
+ init_val=np.nan)
+
+ def test_atomic_nanmax_double(self):
+ self.check_atomic_nanmax(dtype=np.float64, lo=-65535, hi=65535,
+ init_val=np.nan)
+
+ def test_atomic_nanmax_double_shared(self):
+ vals = np.random.randint(0, 32, size=32).astype(np.float64)
+ vals[1::2] = np.nan
+ res = np.array([0], dtype=vals.dtype)
+ sig = 'void(float64[:], float64[:])'
+ cuda_func = cuda.jit(sig)(atomic_nanmax_double_shared)
+ cuda_func[1, 32](res, vals)
+
+ gold = np.nanmax(vals)
+ np.testing.assert_equal(res, gold)
+
+ def test_atomic_nanmax_double_oneindex(self):
+ vals = np.random.randint(0, 128, size=32).astype(np.float64)
+ vals[1::2] = np.nan
+ res = np.zeros(1, np.float64)
+ cuda_func = cuda.jit('void(float64[:], float64[:])')(
+ atomic_max_double_oneindex)
+ cuda_func[1, 32](res, vals)
+
+ gold = np.nanmax(vals)
+ np.testing.assert_equal(res, gold)
+
+ # nanmin tests
+ def check_atomic_nanmin(self, dtype, lo, hi, init_val):
+ vals = np.random.randint(lo, hi, size=(32, 32)).astype(dtype)
+ vals[1::2] = init_val
+ res = np.array([65535], dtype=vals.dtype)
+ cuda_func = cuda.jit(atomic_nanmin)
+ cuda_func[32, 32](res, vals)
+
+ gold = np.nanmin(vals)
+ np.testing.assert_equal(res, gold)
+
+ def test_atomic_nanmin_int32(self):
+ self.check_atomic_nanmin(dtype=np.int32, lo=-65535, hi=65535,
+ init_val=0)
+
+ def test_atomic_nanmin_uint32(self):
+ self.check_atomic_nanmin(dtype=np.uint32, lo=0, hi=65535,
+ init_val=0)
+
+ def test_atomic_nanmin_int64(self):
+ self.check_atomic_nanmin(dtype=np.int64, lo=-65535, hi=65535,
+ init_val=0)
+
+ def test_atomic_nanmin_uint64(self):
+ self.check_atomic_nanmin(dtype=np.uint64, lo=0, hi=65535,
+ init_val=0)
+
+ def test_atomic_nanmin_float(self):
+ self.check_atomic_nanmin(dtype=np.float32, lo=-65535, hi=65535,
+ init_val=np.nan)
+
+ def test_atomic_nanmin_double(self):
+ self.check_atomic_nanmin(dtype=np.float64, lo=-65535, hi=65535,
+ init_val=np.nan)
+
+ def test_atomic_nanmin_double_shared(self):
+ vals = np.random.randint(0, 32, size=32).astype(np.float64)
+ vals[1::2] = np.nan
+ res = np.array([32], dtype=vals.dtype)
+ sig = 'void(float64[:], float64[:])'
+ cuda_func = cuda.jit(sig)(atomic_nanmin_double_shared)
+ cuda_func[1, 32](res, vals)
+
+ gold = np.nanmin(vals)
+ np.testing.assert_equal(res, gold)
+
+ def test_atomic_nanmin_double_oneindex(self):
+ vals = np.random.randint(0, 128, size=32).astype(np.float64)
+ vals[1::2] = np.nan
+ res = np.array([128], np.float64)
+ cuda_func = cuda.jit('void(float64[:], float64[:])')(
+ atomic_min_double_oneindex)
+ cuda_func[1, 32](res, vals)
+
+ gold = np.nanmin(vals)
+ np.testing.assert_equal(res, gold)
+
+ # Returning old value tests
+
+ def _test_atomic_nan_returns_old(self, kernel, initial):
+ x = np.zeros(2, dtype=np.float32)
+ x[0] = initial
+ x[1] = np.nan
+ kernel[1, 1](x)
+ if np.isnan(initial):
+ self.assertFalse(np.isnan(x[0]))
+ self.assertTrue(np.isnan(x[1]))
+ else:
+ self.assertEqual(x[1], initial)
+
+ def test_atomic_nanmax_returns_old_no_replace(self):
+ @cuda.jit
+ def kernel(x):
+ x[1] = cuda.atomic.nanmax(x, 0, 1)
+
+ self._test_atomic_nan_returns_old(kernel, 10)
+
+ def test_atomic_nanmax_returns_old_replace(self):
+ @cuda.jit
+ def kernel(x):
+ x[1] = cuda.atomic.nanmax(x, 0, 10)
+
+ self._test_atomic_nan_returns_old(kernel, 1)
+
+ def test_atomic_nanmax_returns_old_nan_in_array(self):
+ @cuda.jit
+ def kernel(x):
+ x[1] = cuda.atomic.nanmax(x, 0, 1)
+
+ self._test_atomic_nan_returns_old(kernel, np.nan)
+
+ def test_atomic_nanmax_returns_old_nan_val(self):
+ @cuda.jit
+ def kernel(x):
+ x[1] = cuda.atomic.nanmax(x, 0, np.nan)
+
+ self._test_atomic_nan_returns_old(kernel, 10)
+
+ def test_atomic_nanmin_returns_old_no_replace(self):
+ @cuda.jit
+ def kernel(x):
+ x[1] = cuda.atomic.nanmin(x, 0, 11)
+
+ self._test_atomic_nan_returns_old(kernel, 10)
+
+ def test_atomic_nanmin_returns_old_replace(self):
+ @cuda.jit
+ def kernel(x):
+ x[1] = cuda.atomic.nanmin(x, 0, 10)
+
+ self._test_atomic_nan_returns_old(kernel, 11)
+
+ def test_atomic_nanmin_returns_old_nan_in_array(self):
+ @cuda.jit
+ def kernel(x):
+ x[1] = cuda.atomic.nanmin(x, 0, 11)
+
+ self._test_atomic_nan_returns_old(kernel, np.nan)
+
+ def test_atomic_nanmin_returns_old_nan_val(self):
+ @cuda.jit
+ def kernel(x):
+ x[1] = cuda.atomic.nanmin(x, 0, np.nan)
+
+ self._test_atomic_nan_returns_old(kernel, 11)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_blackscholes.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_blackscholes.py
new file mode 100644
index 0000000000000000000000000000000000000000..1375162d9e1015009ea2a1c7ce098340231074f3
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_blackscholes.py
@@ -0,0 +1,120 @@
+import numpy as np
+import math
+from numba import cuda, double, void
+from numba.cuda.testing import unittest, CUDATestCase
+
+
+RISKFREE = 0.02
+VOLATILITY = 0.30
+
+A1 = 0.31938153
+A2 = -0.356563782
+A3 = 1.781477937
+A4 = -1.821255978
+A5 = 1.330274429
+RSQRT2PI = 0.39894228040143267793994605993438
+
+
+def cnd(d):
+ K = 1.0 / (1.0 + 0.2316419 * np.abs(d))
+ ret_val = (RSQRT2PI * np.exp(-0.5 * d * d) *
+ (K * (A1 + K * (A2 + K * (A3 + K * (A4 + K * A5))))))
+ return np.where(d > 0, 1.0 - ret_val, ret_val)
+
+
+def black_scholes(callResult, putResult, stockPrice, optionStrike, optionYears,
+ Riskfree, Volatility):
+ S = stockPrice
+ X = optionStrike
+ T = optionYears
+ R = Riskfree
+ V = Volatility
+ sqrtT = np.sqrt(T)
+ d1 = (np.log(S / X) + (R + 0.5 * V * V) * T) / (V * sqrtT)
+ d2 = d1 - V * sqrtT
+ cndd1 = cnd(d1)
+ cndd2 = cnd(d2)
+
+ expRT = np.exp(- R * T)
+ callResult[:] = (S * cndd1 - X * expRT * cndd2)
+ putResult[:] = (X * expRT * (1.0 - cndd2) - S * (1.0 - cndd1))
+
+
+def randfloat(rand_var, low, high):
+ return (1.0 - rand_var) * low + rand_var * high
+
+
+class TestBlackScholes(CUDATestCase):
+ def test_blackscholes(self):
+ OPT_N = 400
+ iterations = 2
+
+ stockPrice = randfloat(np.random.random(OPT_N), 5.0, 30.0)
+ optionStrike = randfloat(np.random.random(OPT_N), 1.0, 100.0)
+ optionYears = randfloat(np.random.random(OPT_N), 0.25, 10.0)
+
+ callResultNumpy = np.zeros(OPT_N)
+ putResultNumpy = -np.ones(OPT_N)
+
+ callResultNumba = np.zeros(OPT_N)
+ putResultNumba = -np.ones(OPT_N)
+
+ # numpy
+ for i in range(iterations):
+ black_scholes(callResultNumpy, putResultNumpy, stockPrice,
+ optionStrike, optionYears, RISKFREE, VOLATILITY)
+
+ @cuda.jit(double(double), device=True, inline=True)
+ def cnd_cuda(d):
+ K = 1.0 / (1.0 + 0.2316419 * math.fabs(d))
+ ret_val = (RSQRT2PI * math.exp(-0.5 * d * d) *
+ (K * (A1 + K * (A2 + K * (A3 + K * (A4 + K * A5))))))
+ if d > 0:
+ ret_val = 1.0 - ret_val
+ return ret_val
+
+ @cuda.jit(void(double[:], double[:], double[:], double[:], double[:],
+ double, double))
+ def black_scholes_cuda(callResult, putResult, S, X, T, R, V):
+ i = cuda.threadIdx.x + cuda.blockIdx.x * cuda.blockDim.x
+ if i >= S.shape[0]:
+ return
+ sqrtT = math.sqrt(T[i])
+ d1 = ((math.log(S[i] / X[i]) + (R + 0.5 * V * V) * T[i])
+ / (V * sqrtT))
+ d2 = d1 - V * sqrtT
+ cndd1 = cnd_cuda(d1)
+ cndd2 = cnd_cuda(d2)
+
+ expRT = math.exp((-1. * R) * T[i])
+ callResult[i] = (S[i] * cndd1 - X[i] * expRT * cndd2)
+ putResult[i] = (X[i] * expRT * (1.0 - cndd2) - S[i] * (1.0 - cndd1))
+
+ # numba
+ blockdim = 512, 1
+ griddim = int(math.ceil(float(OPT_N) / blockdim[0])), 1
+ stream = cuda.stream()
+ d_callResult = cuda.to_device(callResultNumba, stream)
+ d_putResult = cuda.to_device(putResultNumba, stream)
+ d_stockPrice = cuda.to_device(stockPrice, stream)
+ d_optionStrike = cuda.to_device(optionStrike, stream)
+ d_optionYears = cuda.to_device(optionYears, stream)
+
+ for i in range(iterations):
+ black_scholes_cuda[griddim, blockdim, stream](
+ d_callResult, d_putResult, d_stockPrice, d_optionStrike,
+ d_optionYears, RISKFREE, VOLATILITY)
+ d_callResult.copy_to_host(callResultNumba, stream)
+ d_putResult.copy_to_host(putResultNumba, stream)
+ stream.synchronize()
+
+ delta = np.abs(callResultNumpy - callResultNumba)
+ L1norm = delta.sum() / np.abs(callResultNumpy).sum()
+
+ max_abs_err = delta.max()
+ self.assertTrue(L1norm < 1e-13)
+ self.assertTrue(max_abs_err < 1e-13)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_boolean.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_boolean.py
new file mode 100644
index 0000000000000000000000000000000000000000..fc0568233a806961f86a5b6c1cb64441e5916b2e
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_boolean.py
@@ -0,0 +1,24 @@
+import numpy as np
+from numba.cuda.testing import unittest, CUDATestCase
+from numba import cuda
+
+
+def boolean_func(A, vertial):
+ if vertial:
+ A[0] = 123
+ else:
+ A[0] = 321
+
+
+class TestCudaBoolean(CUDATestCase):
+ def test_boolean(self):
+ func = cuda.jit('void(float64[:], bool_)')(boolean_func)
+ A = np.array([0], dtype='float64')
+ func[1, 1](A, True)
+ self.assertTrue(A[0] == 123)
+ func[1, 1](A, False)
+ self.assertTrue(A[0] == 321)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_caching.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_caching.py
new file mode 100644
index 0000000000000000000000000000000000000000..22e2f4a6e3e70514d3c92c5b8cc7ba3b83944d87
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_caching.py
@@ -0,0 +1,545 @@
+import multiprocessing
+import os
+import shutil
+import subprocess
+import sys
+import unittest
+import warnings
+
+from numba import cuda
+from numba.core.errors import NumbaWarning
+from numba.cuda.testing import (CUDATestCase, skip_on_cudasim,
+ skip_unless_cc_60, skip_if_cudadevrt_missing,
+ skip_if_mvc_enabled, test_data_dir)
+from numba.tests.support import SerialMixin
+from numba.tests.test_caching import (DispatcherCacheUsecasesTest,
+ skip_bad_access)
+
+
+@skip_on_cudasim('Simulator does not implement caching')
+class CUDACachingTest(SerialMixin, DispatcherCacheUsecasesTest):
+ here = os.path.dirname(__file__)
+ usecases_file = os.path.join(here, "cache_usecases.py")
+ modname = "cuda_caching_test_fodder"
+
+ def setUp(self):
+ DispatcherCacheUsecasesTest.setUp(self)
+ CUDATestCase.setUp(self)
+
+ def tearDown(self):
+ CUDATestCase.tearDown(self)
+ DispatcherCacheUsecasesTest.tearDown(self)
+
+ def test_caching(self):
+ self.check_pycache(0)
+ mod = self.import_module()
+ self.check_pycache(0)
+
+ f = mod.add_usecase
+ self.assertPreciseEqual(f(2, 3), 6)
+ self.check_pycache(2) # 1 index, 1 data
+ self.assertPreciseEqual(f(2.5, 3), 6.5)
+ self.check_pycache(3) # 1 index, 2 data
+ self.check_hits(f.func, 0, 2)
+
+ f = mod.record_return_aligned
+ rec = f(mod.aligned_arr, 1)
+ self.assertPreciseEqual(tuple(rec), (2, 43.5))
+
+ f = mod.record_return_packed
+ rec = f(mod.packed_arr, 1)
+ self.assertPreciseEqual(tuple(rec), (2, 43.5))
+ self.check_pycache(6) # 2 index, 4 data
+ self.check_hits(f.func, 0, 2)
+
+ # Check the code runs ok from another process
+ self.run_in_separate_process()
+
+ def test_no_caching(self):
+ mod = self.import_module()
+
+ f = mod.add_nocache_usecase
+ self.assertPreciseEqual(f(2, 3), 6)
+ self.check_pycache(0)
+
+ def test_many_locals(self):
+ # Declaring many local arrays creates a very large LLVM IR, which
+ # cannot be pickled due to the level of recursion it requires to
+ # pickle. This test ensures that kernels with many locals (and
+ # therefore large IR) can be cached. See Issue #8373:
+ # https://github.com/numba/numba/issues/8373
+ self.check_pycache(0)
+ mod = self.import_module()
+ f = mod.many_locals
+ f[1, 1]()
+ self.check_pycache(2) # 1 index, 1 data
+
+ def test_closure(self):
+ mod = self.import_module()
+
+ with warnings.catch_warnings():
+ warnings.simplefilter('error', NumbaWarning)
+
+ f = mod.closure1
+ self.assertPreciseEqual(f(3), 6) # 3 + 3 = 6
+ f = mod.closure2
+ self.assertPreciseEqual(f(3), 8) # 3 + 5 = 8
+ f = mod.closure3
+ self.assertPreciseEqual(f(3), 10) # 3 + 7 = 10
+ f = mod.closure4
+ self.assertPreciseEqual(f(3), 12) # 3 + 9 = 12
+ self.check_pycache(5) # 1 nbi, 4 nbc
+
+ def test_cache_reuse(self):
+ mod = self.import_module()
+ mod.add_usecase(2, 3)
+ mod.add_usecase(2.5, 3.5)
+ mod.outer_uncached(2, 3)
+ mod.outer(2, 3)
+ mod.record_return_packed(mod.packed_arr, 0)
+ mod.record_return_aligned(mod.aligned_arr, 1)
+ mod.simple_usecase_caller(2)
+ mtimes = self.get_cache_mtimes()
+ # Two signatures compiled
+ self.check_hits(mod.add_usecase.func, 0, 2)
+
+ mod2 = self.import_module()
+ self.assertIsNot(mod, mod2)
+ f = mod2.add_usecase
+ f(2, 3)
+ self.check_hits(f.func, 1, 0)
+ f(2.5, 3.5)
+ self.check_hits(f.func, 2, 0)
+
+ # The files haven't changed
+ self.assertEqual(self.get_cache_mtimes(), mtimes)
+
+ self.run_in_separate_process()
+ self.assertEqual(self.get_cache_mtimes(), mtimes)
+
+ def test_cache_invalidate(self):
+ mod = self.import_module()
+ f = mod.add_usecase
+ self.assertPreciseEqual(f(2, 3), 6)
+
+ # This should change the functions' results
+ with open(self.modfile, "a") as f:
+ f.write("\nZ = 10\n")
+
+ mod = self.import_module()
+ f = mod.add_usecase
+ self.assertPreciseEqual(f(2, 3), 15)
+
+ def test_recompile(self):
+ # Explicit call to recompile() should overwrite the cache
+ mod = self.import_module()
+ f = mod.add_usecase
+ self.assertPreciseEqual(f(2, 3), 6)
+
+ mod = self.import_module()
+ f = mod.add_usecase
+ mod.Z = 10
+ self.assertPreciseEqual(f(2, 3), 6)
+ f.func.recompile()
+ self.assertPreciseEqual(f(2, 3), 15)
+
+ # Freshly recompiled version is re-used from other imports
+ mod = self.import_module()
+ f = mod.add_usecase
+ self.assertPreciseEqual(f(2, 3), 15)
+
+ def test_same_names(self):
+ # Function with the same names should still disambiguate
+ mod = self.import_module()
+ f = mod.renamed_function1
+ self.assertPreciseEqual(f(2), 4)
+ f = mod.renamed_function2
+ self.assertPreciseEqual(f(2), 8)
+
+ @skip_unless_cc_60
+ @skip_if_cudadevrt_missing
+ @skip_if_mvc_enabled('CG not supported with MVC')
+ def test_cache_cg(self):
+ # Functions using cooperative groups should be cacheable. See Issue
+ # #8888: https://github.com/numba/numba/issues/8888
+ self.check_pycache(0)
+ mod = self.import_module()
+ self.check_pycache(0)
+
+ mod.cg_usecase(0)
+ self.check_pycache(2) # 1 index, 1 data
+
+ # Check the code runs ok from another process
+ self.run_in_separate_process()
+
+ @skip_unless_cc_60
+ @skip_if_cudadevrt_missing
+ @skip_if_mvc_enabled('CG not supported with MVC')
+ def test_cache_cg_clean_run(self):
+ # See Issue #9432: https://github.com/numba/numba/issues/9432
+ # If a cached function using CG sync was the first thing to compile,
+ # the compile would fail.
+ self.check_pycache(0)
+
+ # This logic is modelled on run_in_separate_process(), but executes the
+ # CG usecase directly in the subprocess.
+ code = """if 1:
+ import sys
+
+ sys.path.insert(0, %(tempdir)r)
+ mod = __import__(%(modname)r)
+ mod.cg_usecase(0)
+ """ % dict(tempdir=self.tempdir, modname=self.modname)
+
+ popen = subprocess.Popen([sys.executable, "-c", code],
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE)
+ out, err = popen.communicate(timeout=60)
+ if popen.returncode != 0:
+ raise AssertionError(
+ "process failed with code %s: \n"
+ "stdout follows\n%s\n"
+ "stderr follows\n%s\n"
+ % (popen.returncode, out.decode(), err.decode()),
+ )
+
+ def _test_pycache_fallback(self):
+ """
+ With a disabled __pycache__, test there is a working fallback
+ (e.g. on the user-wide cache dir)
+ """
+ mod = self.import_module()
+ f = mod.add_usecase
+ # Remove this function's cache files at the end, to avoid accumulation
+ # across test calls.
+ self.addCleanup(shutil.rmtree, f.func.stats.cache_path,
+ ignore_errors=True)
+
+ self.assertPreciseEqual(f(2, 3), 6)
+ # It's a cache miss since the file was copied to a new temp location
+ self.check_hits(f.func, 0, 1)
+
+ # Test re-use
+ mod2 = self.import_module()
+ f = mod2.add_usecase
+ self.assertPreciseEqual(f(2, 3), 6)
+ self.check_hits(f.func, 1, 0)
+
+ # The __pycache__ is empty (otherwise the test's preconditions
+ # wouldn't be met)
+ self.check_pycache(0)
+
+ @skip_bad_access
+ @unittest.skipIf(os.name == "nt",
+ "cannot easily make a directory read-only on Windows")
+ def test_non_creatable_pycache(self):
+ # Make it impossible to create the __pycache__ directory
+ old_perms = os.stat(self.tempdir).st_mode
+ os.chmod(self.tempdir, 0o500)
+ self.addCleanup(os.chmod, self.tempdir, old_perms)
+
+ self._test_pycache_fallback()
+
+ @skip_bad_access
+ @unittest.skipIf(os.name == "nt",
+ "cannot easily make a directory read-only on Windows")
+ def test_non_writable_pycache(self):
+ # Make it impossible to write to the __pycache__ directory
+ pycache = os.path.join(self.tempdir, '__pycache__')
+ os.mkdir(pycache)
+ old_perms = os.stat(pycache).st_mode
+ os.chmod(pycache, 0o500)
+ self.addCleanup(os.chmod, pycache, old_perms)
+
+ self._test_pycache_fallback()
+
+ def test_cannot_cache_linking_libraries(self):
+ link = str(test_data_dir / 'jitlink.ptx')
+ msg = 'Cannot pickle CUDACodeLibrary with linking files'
+ with self.assertRaisesRegex(RuntimeError, msg):
+ @cuda.jit('void()', cache=True, link=[link])
+ def f():
+ pass
+
+
+@skip_on_cudasim('Simulator does not implement caching')
+class CUDAAndCPUCachingTest(SerialMixin, DispatcherCacheUsecasesTest):
+ here = os.path.dirname(__file__)
+ usecases_file = os.path.join(here, "cache_with_cpu_usecases.py")
+ modname = "cuda_and_cpu_caching_test_fodder"
+
+ def setUp(self):
+ DispatcherCacheUsecasesTest.setUp(self)
+ CUDATestCase.setUp(self)
+
+ def tearDown(self):
+ CUDATestCase.tearDown(self)
+ DispatcherCacheUsecasesTest.tearDown(self)
+
+ def test_cpu_and_cuda_targets(self):
+ # The same function jitted for CPU and CUDA targets should maintain
+ # separate caches for each target.
+ self.check_pycache(0)
+ mod = self.import_module()
+ self.check_pycache(0)
+
+ f_cpu = mod.assign_cpu
+ f_cuda = mod.assign_cuda
+ self.assertPreciseEqual(f_cpu(5), 5)
+ self.check_pycache(2) # 1 index, 1 data
+ self.assertPreciseEqual(f_cuda(5), 5)
+ self.check_pycache(3) # 1 index, 2 data
+
+ self.check_hits(f_cpu.func, 0, 1)
+ self.check_hits(f_cuda.func, 0, 1)
+
+ self.assertPreciseEqual(f_cpu(5.5), 5.5)
+ self.check_pycache(4) # 1 index, 3 data
+ self.assertPreciseEqual(f_cuda(5.5), 5.5)
+ self.check_pycache(5) # 1 index, 4 data
+
+ self.check_hits(f_cpu.func, 0, 2)
+ self.check_hits(f_cuda.func, 0, 2)
+
+ def test_cpu_and_cuda_reuse(self):
+ # Existing cache files for the CPU and CUDA targets are reused.
+ mod = self.import_module()
+ mod.assign_cpu(5)
+ mod.assign_cpu(5.5)
+ mod.assign_cuda(5)
+ mod.assign_cuda(5.5)
+
+ mtimes = self.get_cache_mtimes()
+
+ # Two signatures compiled
+ self.check_hits(mod.assign_cpu.func, 0, 2)
+ self.check_hits(mod.assign_cuda.func, 0, 2)
+
+ mod2 = self.import_module()
+ self.assertIsNot(mod, mod2)
+ f_cpu = mod2.assign_cpu
+ f_cuda = mod2.assign_cuda
+
+ f_cpu(2)
+ self.check_hits(f_cpu.func, 1, 0)
+ f_cpu(2.5)
+ self.check_hits(f_cpu.func, 2, 0)
+ f_cuda(2)
+ self.check_hits(f_cuda.func, 1, 0)
+ f_cuda(2.5)
+ self.check_hits(f_cuda.func, 2, 0)
+
+ # The files haven't changed
+ self.assertEqual(self.get_cache_mtimes(), mtimes)
+
+ self.run_in_separate_process()
+ self.assertEqual(self.get_cache_mtimes(), mtimes)
+
+
+def get_different_cc_gpus():
+ # Find two GPUs with different Compute Capabilities and return them as a
+ # tuple. If two GPUs with distinct Compute Capabilities cannot be found,
+ # then None is returned.
+ first_gpu = cuda.gpus[0]
+ with first_gpu:
+ first_cc = cuda.current_context().device.compute_capability
+
+ for gpu in cuda.gpus[1:]:
+ with gpu:
+ cc = cuda.current_context().device.compute_capability
+ if cc != first_cc:
+ return (first_gpu, gpu)
+
+ return None
+
+
+@skip_on_cudasim('Simulator does not implement caching')
+class TestMultiCCCaching(SerialMixin, DispatcherCacheUsecasesTest):
+ here = os.path.dirname(__file__)
+ usecases_file = os.path.join(here, "cache_usecases.py")
+ modname = "cuda_multi_cc_caching_test_fodder"
+
+ def setUp(self):
+ DispatcherCacheUsecasesTest.setUp(self)
+ CUDATestCase.setUp(self)
+
+ def tearDown(self):
+ CUDATestCase.tearDown(self)
+ DispatcherCacheUsecasesTest.tearDown(self)
+
+ def test_cache(self):
+ gpus = get_different_cc_gpus()
+ if not gpus:
+ self.skipTest('Need two different CCs for multi-CC cache test')
+
+ self.check_pycache(0)
+ mod = self.import_module()
+ self.check_pycache(0)
+
+ # Step 1. Populate the cache with the first GPU
+ with gpus[0]:
+ f = mod.add_usecase
+ self.assertPreciseEqual(f(2, 3), 6)
+ self.check_pycache(2) # 1 index, 1 data
+ self.assertPreciseEqual(f(2.5, 3), 6.5)
+ self.check_pycache(3) # 1 index, 2 data
+ self.check_hits(f.func, 0, 2)
+
+ f = mod.record_return_aligned
+ rec = f(mod.aligned_arr, 1)
+ self.assertPreciseEqual(tuple(rec), (2, 43.5))
+
+ f = mod.record_return_packed
+ rec = f(mod.packed_arr, 1)
+ self.assertPreciseEqual(tuple(rec), (2, 43.5))
+ self.check_pycache(6) # 2 index, 4 data
+ self.check_hits(f.func, 0, 2)
+
+ # Step 2. Run with the second GPU - under present behaviour this
+ # doesn't further populate the cache.
+ with gpus[1]:
+ f = mod.add_usecase
+ self.assertPreciseEqual(f(2, 3), 6)
+ self.check_pycache(6) # cache unchanged
+ self.assertPreciseEqual(f(2.5, 3), 6.5)
+ self.check_pycache(6) # cache unchanged
+ self.check_hits(f.func, 0, 2)
+
+ f = mod.record_return_aligned
+ rec = f(mod.aligned_arr, 1)
+ self.assertPreciseEqual(tuple(rec), (2, 43.5))
+
+ f = mod.record_return_packed
+ rec = f(mod.packed_arr, 1)
+ self.assertPreciseEqual(tuple(rec), (2, 43.5))
+ self.check_pycache(6) # cache unchanged
+ self.check_hits(f.func, 0, 2)
+
+ # Step 3. Run in a separate module with the second GPU - this populates
+ # the cache for the second CC.
+ mod2 = self.import_module()
+ self.assertIsNot(mod, mod2)
+
+ with gpus[1]:
+ f = mod2.add_usecase
+ self.assertPreciseEqual(f(2, 3), 6)
+ self.check_pycache(7) # 2 index, 5 data
+ self.assertPreciseEqual(f(2.5, 3), 6.5)
+ self.check_pycache(8) # 2 index, 6 data
+ self.check_hits(f.func, 0, 2)
+
+ f = mod2.record_return_aligned
+ rec = f(mod.aligned_arr, 1)
+ self.assertPreciseEqual(tuple(rec), (2, 43.5))
+
+ f = mod2.record_return_packed
+ rec = f(mod.packed_arr, 1)
+ self.assertPreciseEqual(tuple(rec), (2, 43.5))
+ self.check_pycache(10) # 2 index, 8 data
+ self.check_hits(f.func, 0, 2)
+
+ # The following steps check that we can use the NVVM IR loaded from the
+ # cache to generate PTX for a different compute capability to the
+ # cached cubin's CC. To check this, we create another module that loads
+ # the cached version containing a cubin for GPU 1. There will be no
+ # cubin for GPU 0, so when we try to use it the PTX must be generated.
+
+ mod3 = self.import_module()
+ self.assertIsNot(mod, mod3)
+
+ # Step 4. Run with GPU 1 and get a cache hit, loading the cache created
+ # during Step 3.
+ with gpus[1]:
+ f = mod3.add_usecase
+ self.assertPreciseEqual(f(2, 3), 6)
+ self.assertPreciseEqual(f(2.5, 3), 6.5)
+
+ f = mod3.record_return_aligned
+ rec = f(mod.aligned_arr, 1)
+ self.assertPreciseEqual(tuple(rec), (2, 43.5))
+
+ f = mod3.record_return_packed
+ rec = f(mod.packed_arr, 1)
+ self.assertPreciseEqual(tuple(rec), (2, 43.5))
+
+ # Step 5. Run with GPU 0 using the module from Step 4, to force PTX
+ # generation from cached NVVM IR.
+ with gpus[0]:
+ f = mod3.add_usecase
+ self.assertPreciseEqual(f(2, 3), 6)
+ self.assertPreciseEqual(f(2.5, 3), 6.5)
+
+ f = mod3.record_return_aligned
+ rec = f(mod.aligned_arr, 1)
+ self.assertPreciseEqual(tuple(rec), (2, 43.5))
+
+ f = mod3.record_return_packed
+ rec = f(mod.packed_arr, 1)
+ self.assertPreciseEqual(tuple(rec), (2, 43.5))
+
+
+def child_initializer():
+ # Disable occupancy and implicit copy warnings in processes in a
+ # multiprocessing pool.
+ from numba.core import config
+ config.CUDA_LOW_OCCUPANCY_WARNINGS = 0
+ config.CUDA_WARN_ON_IMPLICIT_COPY = 0
+
+
+@skip_on_cudasim('Simulator does not implement caching')
+class TestMultiprocessCache(SerialMixin, DispatcherCacheUsecasesTest):
+
+ # Nested multiprocessing.Pool raises AssertionError:
+ # "daemonic processes are not allowed to have children"
+ _numba_parallel_test_ = False
+
+ here = os.path.dirname(__file__)
+ usecases_file = os.path.join(here, "cache_usecases.py")
+ modname = "cuda_mp_caching_test_fodder"
+
+ def setUp(self):
+ DispatcherCacheUsecasesTest.setUp(self)
+ CUDATestCase.setUp(self)
+
+ def tearDown(self):
+ CUDATestCase.tearDown(self)
+ DispatcherCacheUsecasesTest.tearDown(self)
+
+ def test_multiprocessing(self):
+ # Check caching works from multiple processes at once (#2028)
+ mod = self.import_module()
+ # Calling a pure Python caller of the JIT-compiled function is
+ # necessary to reproduce the issue.
+ f = mod.simple_usecase_caller
+ n = 3
+ try:
+ ctx = multiprocessing.get_context('spawn')
+ except AttributeError:
+ ctx = multiprocessing
+
+ pool = ctx.Pool(n, child_initializer)
+
+ try:
+ res = sum(pool.imap(f, range(n)))
+ finally:
+ pool.close()
+ self.assertEqual(res, n * (n - 1) // 2)
+
+
+@skip_on_cudasim('Simulator does not implement the CUDACodeLibrary')
+class TestCUDACodeLibrary(CUDATestCase):
+ # For tests of miscellaneous CUDACodeLibrary behaviour that we wish to
+ # explicitly check
+
+ def test_cannot_serialize_unfinalized(self):
+ # The CUDA codegen failes to import under the simulator, so we cannot
+ # import it at the top level
+ from numba.cuda.codegen import CUDACodeLibrary
+
+ # Usually a CodeLibrary requires a real CodeGen, but since we don't
+ # interact with it, anything will do
+ codegen = object()
+ name = 'library'
+ cl = CUDACodeLibrary(codegen, name)
+ with self.assertRaisesRegex(RuntimeError, 'Cannot pickle unfinalized'):
+ cl._reduce_states()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_casting.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_casting.py
new file mode 100644
index 0000000000000000000000000000000000000000..2ce77e05b35532eb2e157dfb2fc104698f823dd7
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_casting.py
@@ -0,0 +1,257 @@
+import numpy as np
+
+from numba.cuda import compile_ptx
+from numba.core.types import f2, i1, i2, i4, i8, u1, u2, u4, u8
+from numba import cuda
+from numba.core import types
+from numba.cuda.testing import (CUDATestCase, skip_on_cudasim,
+ skip_unless_cc_53)
+from numba.types import float16, float32
+import itertools
+import unittest
+
+
+def native_cast(x):
+ return float(x)
+
+
+def to_int8(x):
+ return np.int8(x)
+
+
+def to_int16(x):
+ return np.int16(x)
+
+
+def to_int32(x):
+ return np.int32(x)
+
+
+def to_int64(x):
+ return np.int64(x)
+
+
+def to_uint8(x):
+ return np.uint8(x)
+
+
+def to_uint16(x):
+ return np.uint16(x)
+
+
+def to_uint32(x):
+ return types.uint32(x)
+
+
+def to_uint64(x):
+ return types.uint64(x)
+
+
+def to_float16(x):
+ # When division and operators on float16 types are supported, this should
+ # be changed to match the implementation in to_float32.
+ return (np.float16(x) * np.float16(0.5))
+
+
+def to_float32(x):
+ return np.float32(x) / np.float32(2)
+
+
+def to_float64(x):
+ return np.float64(x) / np.float64(2)
+
+
+def to_complex64(x):
+ return np.complex64(x)
+
+
+def to_complex128(x):
+ return np.complex128(x)
+
+
+# Since multiplication of float16 is not supported via the operator * on
+# float16s yet, and the host does not implement cuda.fp16.*, we need two
+# versions of the following functions:
+#
+# - The device version uses cuda.fp16.hmul
+# - The host version uses the * operator
+
+def cuda_int_literal_to_float16(x):
+ # Note that we need to use `2` and not `np.float16(2)` to ensure that this
+ # types as a literal int and not a const float16.
+ return cuda.fp16.hmul(np.float16(x), 2)
+
+
+def reference_int_literal_to_float16(x):
+ return np.float16(x) * np.float16(2)
+
+
+def cuda_float_literal_to_float16(x):
+ # Note that `2.5` types as a const float64 and not a literal float, but
+ # this case is provided in case that changes in future.
+ return cuda.fp16.hmul(np.float16(x), 2.5)
+
+
+def reference_float_literal_to_float16(x):
+ return np.float16(x) * np.float16(2.5)
+
+
+class TestCasting(CUDATestCase):
+ def _create_wrapped(self, pyfunc, intype, outtype):
+ wrapped_func = cuda.jit(device=True)(pyfunc)
+
+ @cuda.jit
+ def cuda_wrapper_fn(arg, res):
+ res[0] = wrapped_func(arg[0])
+
+ def wrapper_fn(arg):
+ argarray = np.zeros(1, dtype=intype)
+ argarray[0] = arg
+ resarray = np.zeros(1, dtype=outtype)
+ cuda_wrapper_fn[1, 1](argarray, resarray)
+ return resarray[0]
+
+ return wrapper_fn
+
+ @skip_unless_cc_53
+ def test_float_to_int(self):
+ pyfuncs = (to_int8, to_int16, to_int32, to_int64)
+ totys = (np.int8, np.int16, np.int32, np.int64)
+ fromtys = (np.float16, np.float32, np.float64)
+
+ for pyfunc, toty in zip(pyfuncs, totys):
+ for fromty in fromtys:
+ with self.subTest(fromty=fromty, toty=toty):
+ cfunc = self._create_wrapped(pyfunc, fromty, toty)
+ self.assertEqual(cfunc(12.3), pyfunc(12.3))
+ self.assertEqual(cfunc(12.3), int(12.3))
+ self.assertEqual(cfunc(-12.3), pyfunc(-12.3))
+ self.assertEqual(cfunc(-12.3), int(-12.3))
+
+ @skip_on_cudasim('Compilation unsupported in the simulator')
+ def test_float16_to_int_ptx(self):
+ pyfuncs = (to_int8, to_int16, to_int32, to_int64)
+ sizes = (8, 16, 32, 64)
+
+ for pyfunc, size in zip(pyfuncs, sizes):
+ ptx, _ = compile_ptx(pyfunc, (f2,), device=True)
+ self.assertIn(f"cvt.rni.s{size}.f16", ptx)
+
+ @skip_unless_cc_53
+ def test_float_to_uint(self):
+ pyfuncs = (to_int8, to_int16, to_int32, to_int64)
+ totys = (np.uint8, np.uint16, np.uint32, np.uint64)
+ fromtys = (np.float16, np.float32, np.float64)
+
+ for pyfunc, toty in zip(pyfuncs, totys):
+ for fromty in fromtys:
+ with self.subTest(fromty=fromty, toty=toty):
+ cfunc = self._create_wrapped(pyfunc, fromty, toty)
+ self.assertEqual(cfunc(12.3), pyfunc(12.3))
+ self.assertEqual(cfunc(12.3), int(12.3))
+
+ @skip_on_cudasim('Compilation unsupported in the simulator')
+ def test_float16_to_uint_ptx(self):
+ pyfuncs = (to_uint8, to_uint16, to_uint32, to_uint64)
+ sizes = (8, 16, 32, 64)
+
+ for pyfunc, size in zip(pyfuncs, sizes):
+ ptx, _ = compile_ptx(pyfunc, (f2,), device=True)
+ self.assertIn(f"cvt.rni.u{size}.f16", ptx)
+
+ @skip_unless_cc_53
+ def test_int_to_float(self):
+ pyfuncs = (to_float16, to_float32, to_float64)
+ totys = (np.float16, np.float32, np.float64)
+
+ for pyfunc, toty in zip(pyfuncs, totys):
+ with self.subTest(toty=toty):
+ cfunc = self._create_wrapped(pyfunc, np.int64, toty)
+ self.assertEqual(cfunc(321), pyfunc(321))
+
+ @skip_unless_cc_53
+ def test_literal_to_float16(self):
+ cudafuncs = (cuda_int_literal_to_float16,
+ cuda_float_literal_to_float16)
+ hostfuncs = (reference_int_literal_to_float16,
+ reference_float_literal_to_float16)
+
+ for cudafunc, hostfunc in zip(cudafuncs, hostfuncs):
+ with self.subTest(func=cudafunc):
+ cfunc = self._create_wrapped(cudafunc, np.float16, np.float16)
+ self.assertEqual(cfunc(321), hostfunc(321))
+
+ @skip_on_cudasim('Compilation unsupported in the simulator')
+ def test_int_to_float16_ptx(self):
+ fromtys = (i1, i2, i4, i8)
+ sizes = (8, 16, 32, 64)
+
+ for ty, size in zip(fromtys, sizes):
+ ptx, _ = compile_ptx(to_float16, (ty,), device=True)
+ self.assertIn(f"cvt.rn.f16.s{size}", ptx)
+
+ @skip_on_cudasim('Compilation unsupported in the simulator')
+ def test_uint_to_float16_ptx(self):
+ fromtys = (u1, u2, u4, u8)
+ sizes = (8, 16, 32, 64)
+
+ for ty, size in zip(fromtys, sizes):
+ ptx, _ = compile_ptx(to_float16, (ty,), device=True)
+ self.assertIn(f"cvt.rn.f16.u{size}", ptx)
+
+ @skip_unless_cc_53
+ def test_float_to_float(self):
+ pyfuncs = (to_float16, to_float32, to_float64)
+ tys = (np.float16, np.float32, np.float64)
+
+ for (pyfunc, fromty), toty in itertools.product(zip(pyfuncs, tys), tys):
+ with self.subTest(fromty=fromty, toty=toty):
+ cfunc = self._create_wrapped(pyfunc, fromty, toty)
+ # For this test we cannot use the pyfunc for comparison because
+ # the CUDA target doesn't yet implement division (or operators)
+ # for float16 values, so we test by comparing with the computed
+ # expression instead.
+ np.testing.assert_allclose(cfunc(12.3),
+ toty(12.3) / toty(2), rtol=0.0003)
+ np.testing.assert_allclose(cfunc(-12.3),
+ toty(-12.3) / toty(2), rtol=0.0003)
+
+ @skip_on_cudasim('Compilation unsupported in the simulator')
+ def test_float16_to_float_ptx(self):
+ pyfuncs = (to_float32, to_float64)
+ postfixes = ("f32", "f64")
+
+ for pyfunc, postfix in zip(pyfuncs, postfixes):
+ ptx, _ = compile_ptx(pyfunc, (f2,), device=True)
+ self.assertIn(f"cvt.{postfix}.f16", ptx)
+
+ @skip_unless_cc_53
+ def test_float_to_complex(self):
+ pyfuncs = (to_complex64, to_complex128)
+ totys = (np.complex64, np.complex128)
+ fromtys = (np.float16, np.float32, np.float64)
+
+ for pyfunc, toty in zip(pyfuncs, totys):
+ for fromty in fromtys:
+ with self.subTest(fromty=fromty, toty=toty):
+ cfunc = self._create_wrapped(pyfunc, fromty, toty)
+ # Here we need to explicitly cast the input to the pyfunc
+ # to match the casting that is automatically applied when
+ # passing the input to the cfunc as part of wrapping it in
+ # an array of type fromtype.
+ np.testing.assert_allclose(cfunc(3.21),
+ pyfunc(fromty(3.21)))
+ np.testing.assert_allclose(cfunc(-3.21),
+ pyfunc(fromty(-3.21)) + 0j)
+
+ @skip_on_cudasim('Compilation unsupported in the simulator')
+ def test_native_cast(self):
+ float32_ptx, _ = cuda.compile_ptx(native_cast, (float32,), device=True)
+ self.assertIn("st.f32", float32_ptx)
+
+ float16_ptx, _ = cuda.compile_ptx(native_cast, (float16,), device=True)
+ self.assertIn("st.u16", float16_ptx)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_cffi.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_cffi.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee09fcc3129bdd8629b286f54772c593e94a3cb6
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_cffi.py
@@ -0,0 +1,33 @@
+import numpy as np
+
+from numba import cuda, types
+from numba.cuda.testing import (skip_on_cudasim, test_data_dir, unittest,
+ CUDATestCase)
+from numba.tests.support import skip_unless_cffi
+
+
+@skip_unless_cffi
+@skip_on_cudasim('Simulator does not support linking')
+class TestCFFI(CUDATestCase):
+ def test_from_buffer(self):
+ import cffi
+ ffi = cffi.FFI()
+
+ link = str(test_data_dir / 'jitlink.ptx')
+ sig = types.void(types.CPointer(types.int32))
+ array_mutator = cuda.declare_device('array_mutator', sig)
+
+ @cuda.jit(link=[link])
+ def mutate_array(x):
+ x_ptr = ffi.from_buffer(x)
+ array_mutator(x_ptr)
+
+ x = np.arange(2).astype(np.int32)
+ mutate_array[1, 1](x)
+
+ # The foreign function should have copied element 1 to element 0
+ self.assertEqual(x[0], x[1])
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_compiler.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_compiler.py
new file mode 100644
index 0000000000000000000000000000000000000000..4732db4ef4741b239fb7dd83fd58dbab230f0bed
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_compiler.py
@@ -0,0 +1,276 @@
+from math import sqrt
+from numba import cuda, float32, int16, int32, int64, uint32, void
+from numba.cuda import (compile, compile_for_current_device, compile_ptx,
+ compile_ptx_for_current_device)
+from numba.cuda.cudadrv import runtime
+from numba.cuda.testing import skip_on_cudasim, unittest, CUDATestCase
+
+
+# A test function at the module scope to ensure we get the name right for the C
+# ABI whether a function is at module or local scope.
+def f_module(x, y):
+ return x + y
+
+
+@skip_on_cudasim('Compilation unsupported in the simulator')
+class TestCompile(unittest.TestCase):
+ def test_global_kernel(self):
+ def f(r, x, y):
+ i = cuda.grid(1)
+ if i < len(r):
+ r[i] = x[i] + y[i]
+
+ args = (float32[:], float32[:], float32[:])
+ ptx, resty = compile_ptx(f, args)
+
+ # Kernels should not have a func_retval parameter
+ self.assertNotIn('func_retval', ptx)
+ # .visible .func is used to denote a device function
+ self.assertNotIn('.visible .func', ptx)
+ # .visible .entry would denote the presence of a global function
+ self.assertIn('.visible .entry', ptx)
+ # Return type for kernels should always be void
+ self.assertEqual(resty, void)
+
+ def test_device_function(self):
+ def add(x, y):
+ return x + y
+
+ args = (float32, float32)
+ ptx, resty = compile_ptx(add, args, device=True)
+
+ # Device functions take a func_retval parameter for storing the
+ # returned value in by reference
+ self.assertIn('func_retval', ptx)
+ # .visible .func is used to denote a device function
+ self.assertIn('.visible .func', ptx)
+ # .visible .entry would denote the presence of a global function
+ self.assertNotIn('.visible .entry', ptx)
+ # Inferred return type as expected?
+ self.assertEqual(resty, float32)
+
+ # Check that function's output matches signature
+ sig_int32 = int32(int32, int32)
+ ptx, resty = compile_ptx(add, sig_int32, device=True)
+ self.assertEqual(resty, int32)
+
+ sig_int16 = int16(int16, int16)
+ ptx, resty = compile_ptx(add, sig_int16, device=True)
+ self.assertEqual(resty, int16)
+ # Using string as signature
+ sig_string = "uint32(uint32, uint32)"
+ ptx, resty = compile_ptx(add, sig_string, device=True)
+ self.assertEqual(resty, uint32)
+
+ def test_fastmath(self):
+ def f(x, y, z, d):
+ return sqrt((x * y + z) / d)
+
+ args = (float32, float32, float32, float32)
+ ptx, resty = compile_ptx(f, args, device=True)
+
+ # Without fastmath, fma contraction is enabled by default, but ftz and
+ # approximate div / sqrt is not.
+ self.assertIn('fma.rn.f32', ptx)
+ self.assertIn('div.rn.f32', ptx)
+ self.assertIn('sqrt.rn.f32', ptx)
+
+ ptx, resty = compile_ptx(f, args, device=True, fastmath=True)
+
+ # With fastmath, ftz and approximate div / sqrt are enabled
+ self.assertIn('fma.rn.ftz.f32', ptx)
+ self.assertIn('div.approx.ftz.f32', ptx)
+ self.assertIn('sqrt.approx.ftz.f32', ptx)
+
+ def check_debug_info(self, ptx):
+ # A debug_info section should exist in the PTX. Whitespace varies
+ # between CUDA toolkit versions.
+ self.assertRegex(ptx, '\\.section\\s+\\.debug_info')
+ # A .file directive should be produced and include the name of the
+ # source. The path and whitespace may vary, so we accept anything
+ # ending in the filename of this module.
+ self.assertRegex(ptx, '\\.file.*test_compiler.py"')
+
+ def test_device_function_with_debug(self):
+ # See Issue #6719 - this ensures that compilation with debug succeeds
+ # with CUDA 11.2 / NVVM 7.0 onwards. Previously it failed because NVVM
+ # IR version metadata was not added when compiling device functions,
+ # and NVVM assumed DBG version 1.0 if not specified, which is
+ # incompatible with the 3.0 IR we use. This was specified only for
+ # kernels.
+ def f():
+ pass
+
+ ptx, resty = compile_ptx(f, (), device=True, debug=True)
+ self.check_debug_info(ptx)
+
+ def test_kernel_with_debug(self):
+ # Inspired by (but not originally affected by) Issue #6719
+ def f():
+ pass
+
+ ptx, resty = compile_ptx(f, (), debug=True)
+ self.check_debug_info(ptx)
+
+ def check_line_info(self, ptx):
+ # A .file directive should be produced and include the name of the
+ # source. The path and whitespace may vary, so we accept anything
+ # ending in the filename of this module.
+ self.assertRegex(ptx, '\\.file.*test_compiler.py"')
+
+ def test_device_function_with_line_info(self):
+ def f():
+ pass
+
+ ptx, resty = compile_ptx(f, (), device=True, lineinfo=True)
+ self.check_line_info(ptx)
+
+ def test_kernel_with_line_info(self):
+ def f():
+ pass
+
+ ptx, resty = compile_ptx(f, (), lineinfo=True)
+ self.check_line_info(ptx)
+
+ def test_non_void_return_type(self):
+ def f(x, y):
+ return x[0] + y[0]
+
+ with self.assertRaisesRegex(TypeError, 'must have void return type'):
+ compile_ptx(f, (uint32[::1], uint32[::1]))
+
+ def test_c_abi_disallowed_for_kernel(self):
+ def f(x, y):
+ return x + y
+
+ with self.assertRaisesRegex(NotImplementedError,
+ "The C ABI is not supported for kernels"):
+ compile_ptx(f, (int32, int32), abi="c")
+
+ def test_unsupported_abi(self):
+ def f(x, y):
+ return x + y
+
+ with self.assertRaisesRegex(NotImplementedError,
+ "Unsupported ABI: fastcall"):
+ compile_ptx(f, (int32, int32), abi="fastcall")
+
+ def test_c_abi_device_function(self):
+ def f(x, y):
+ return x + y
+
+ ptx, resty = compile_ptx(f, int32(int32, int32), device=True, abi="c")
+ # There should be no more than two parameters
+ self.assertNotIn(ptx, "param_2")
+
+ # The function name should match the Python function name (not the
+ # qualname, which includes additional info), and its return value
+ # should be 32 bits
+ self.assertRegex(ptx, r"\.visible\s+\.func\s+\(\.param\s+\.b32\s+"
+ r"func_retval0\)\s+f\(")
+
+ # If we compile for 64-bit integers, the return type should be 64 bits
+ # wide
+ ptx, resty = compile_ptx(f, int64(int64, int64), device=True, abi="c")
+ self.assertRegex(ptx, r"\.visible\s+\.func\s+\(\.param\s+\.b64")
+
+ def test_c_abi_device_function_module_scope(self):
+ ptx, resty = compile_ptx(f_module, int32(int32, int32), device=True,
+ abi="c")
+
+ # The function name should match the Python function name, and its
+ # return value should be 32 bits
+ self.assertRegex(ptx, r"\.visible\s+\.func\s+\(\.param\s+\.b32\s+"
+ r"func_retval0\)\s+f_module\(")
+
+ def test_c_abi_with_abi_name(self):
+ abi_info = {'abi_name': '_Z4funcii'}
+ ptx, resty = compile_ptx(f_module, int32(int32, int32), device=True,
+ abi="c", abi_info=abi_info)
+
+ # The function name should match the one given in the ABI info, and its
+ # return value should be 32 bits
+ self.assertRegex(ptx, r"\.visible\s+\.func\s+\(\.param\s+\.b32\s+"
+ r"func_retval0\)\s+_Z4funcii\(")
+
+ def test_compile_defaults_to_c_abi(self):
+ ptx, resty = compile(f_module, int32(int32, int32), device=True)
+
+ # The function name should match the Python function name, and its
+ # return value should be 32 bits
+ self.assertRegex(ptx, r"\.visible\s+\.func\s+\(\.param\s+\.b32\s+"
+ r"func_retval0\)\s+f_module\(")
+
+ def test_compile_to_ltoir(self):
+ if runtime.get_version() < (11, 5):
+ self.skipTest("-gen-lto unavailable in this toolkit version")
+
+ ltoir, resty = compile(f_module, int32(int32, int32), device=True,
+ output="ltoir")
+
+ # There are no tools to interpret the LTOIR output, but we can check
+ # that we appear to have obtained an LTOIR file. This magic number is
+ # not documented, but is expected to remain consistent.
+ LTOIR_MAGIC = 0x7F4E43ED
+ header = int.from_bytes(ltoir[:4], byteorder='little')
+ self.assertEqual(header, LTOIR_MAGIC)
+ self.assertEqual(resty, int32)
+
+ def test_compile_to_invalid_error(self):
+ illegal_output = "illegal"
+ msg = f"Unsupported output type: {illegal_output}"
+ with self.assertRaisesRegex(NotImplementedError, msg):
+ compile(f_module, int32(int32, int32), device=True,
+ output=illegal_output)
+
+
+@skip_on_cudasim('Compilation unsupported in the simulator')
+class TestCompileForCurrentDevice(CUDATestCase):
+ def _check_ptx_for_current_device(self, compile_function):
+ def add(x, y):
+ return x + y
+
+ args = (float32, float32)
+ ptx, resty = compile_function(add, args, device=True)
+
+ # Check we target the current device's compute capability, or the
+ # closest compute capability supported by the current toolkit.
+ device_cc = cuda.get_current_device().compute_capability
+ cc = cuda.cudadrv.nvvm.find_closest_arch(device_cc)
+ target = f'.target sm_{cc[0]}{cc[1]}'
+ self.assertIn(target, ptx)
+
+ def test_compile_ptx_for_current_device(self):
+ self._check_ptx_for_current_device(compile_ptx_for_current_device)
+
+ def test_compile_for_current_device(self):
+ self._check_ptx_for_current_device(compile_for_current_device)
+
+
+@skip_on_cudasim('Compilation unsupported in the simulator')
+class TestCompileOnlyTests(unittest.TestCase):
+ '''For tests where we can only check correctness by examining the compiler
+ output rather than observing the effects of execution.'''
+
+ def test_nanosleep(self):
+ def use_nanosleep(x):
+ # Sleep for a constant time
+ cuda.nanosleep(32)
+ # Sleep for a variable time
+ cuda.nanosleep(x)
+
+ ptx, resty = compile_ptx(use_nanosleep, (uint32,), cc=(7, 0))
+
+ nanosleep_count = 0
+ for line in ptx.split('\n'):
+ if 'nanosleep.u32' in line:
+ nanosleep_count += 1
+
+ expected = 2
+ self.assertEqual(expected, nanosleep_count,
+ (f'Got {nanosleep_count} nanosleep instructions, '
+ f'expected {expected}'))
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_complex.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_complex.py
new file mode 100644
index 0000000000000000000000000000000000000000..9583931629ccd421c3a1a8d5aa39232766510e26
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_complex.py
@@ -0,0 +1,296 @@
+import math
+import itertools
+
+import numpy as np
+
+from numba.cuda.testing import unittest, CUDATestCase
+from numba.core import types
+from numba import cuda
+from numba.tests.complex_usecases import (real_usecase, imag_usecase,
+ conjugate_usecase, phase_usecase,
+ polar_as_complex_usecase,
+ rect_usecase, isnan_usecase,
+ isinf_usecase, isfinite_usecase,
+ exp_usecase, log_usecase,
+ log_base_usecase, log10_usecase,
+ sqrt_usecase, asin_usecase,
+ acos_usecase, atan_usecase,
+ cos_usecase, sin_usecase,
+ tan_usecase, acosh_usecase,
+ asinh_usecase, atanh_usecase,
+ cosh_usecase, sinh_usecase,
+ tanh_usecase)
+from numba.np import numpy_support
+
+
+def compile_scalar_func(pyfunc, argtypes, restype):
+ # First compile a scalar device function
+ assert not any(isinstance(tp, types.Array) for tp in argtypes)
+ assert not isinstance(restype, types.Array)
+ device_func = cuda.jit(restype(*argtypes), device=True)(pyfunc)
+
+ kernel_types = [types.Array(tp, 1, "C")
+ for tp in [restype] + list(argtypes)]
+
+ if len(argtypes) == 1:
+ def kernel_func(out, a):
+ i = cuda.grid(1)
+ if i < out.shape[0]:
+ out[i] = device_func(a[i])
+ elif len(argtypes) == 2:
+ def kernel_func(out, a, b):
+ i = cuda.grid(1)
+ if i < out.shape[0]:
+ out[i] = device_func(a[i], b[i])
+ else:
+ assert 0
+
+ kernel = cuda.jit(tuple(kernel_types))(kernel_func)
+
+ def kernel_wrapper(values):
+ n = len(values)
+ inputs = [np.empty(n, dtype=numpy_support.as_dtype(tp))
+ for tp in argtypes]
+ output = np.empty(n, dtype=numpy_support.as_dtype(restype))
+ for i, vs in enumerate(values):
+ for v, inp in zip(vs, inputs):
+ inp[i] = v
+ args = [output] + inputs
+ kernel[int(math.ceil(n / 256)), 256](*args)
+ return list(output)
+ return kernel_wrapper
+
+
+class BaseComplexTest(CUDATestCase):
+
+ def basic_values(self):
+ reals = [-0.0, +0.0, 1, -1, +1.5, -3.5,
+ float('-inf'), float('+inf'), float('nan')]
+ return [complex(x, y) for x, y in itertools.product(reals, reals)]
+
+ def more_values(self):
+ reals = [0.0, +0.0, 1, -1, -math.pi, +math.pi,
+ float('-inf'), float('+inf'), float('nan')]
+ return [complex(x, y) for x, y in itertools.product(reals, reals)]
+
+ def non_nan_values(self):
+ reals = [-0.0, +0.0, 1, -1, -math.pi, +math.pi,
+ float('inf'), float('-inf')]
+ return [complex(x, y) for x, y in itertools.product(reals, reals)]
+
+ def run_func(self, pyfunc, sigs, values, ulps=1, ignore_sign_on_zero=False):
+ for sig in sigs:
+ if isinstance(sig, types.Type):
+ sig = sig,
+ if isinstance(sig, tuple):
+ # Assume return type is the type of first argument
+ sig = sig[0](*sig)
+ prec = ('single'
+ if sig.args[0] in (types.float32, types.complex64)
+ else 'double')
+ cudafunc = compile_scalar_func(pyfunc, sig.args, sig.return_type)
+ ok_values = []
+ expected_list = []
+ for args in values:
+ if not isinstance(args, (list, tuple)):
+ args = args,
+ try:
+ expected_list.append(pyfunc(*args))
+ ok_values.append(args)
+ except ValueError as e:
+ self.assertIn("math domain error", str(e))
+ continue
+ got_list = cudafunc(ok_values)
+ for got, expected, args in zip(got_list, expected_list, ok_values):
+ msg = 'for input %r with prec %r' % (args, prec)
+ self.assertPreciseEqual(got, expected, prec=prec,
+ ulps=ulps,
+ ignore_sign_on_zero=ignore_sign_on_zero,
+ msg=msg)
+
+ run_unary = run_func
+ run_binary = run_func
+
+
+class TestComplex(BaseComplexTest):
+
+ def check_real_image(self, pyfunc):
+ values = self.basic_values()
+ self.run_unary(pyfunc,
+ [tp.underlying_float(tp)
+ for tp in (types.complex64, types.complex128)],
+ values)
+
+ def test_real(self):
+ self.check_real_image(real_usecase)
+
+ def test_imag(self):
+ self.check_real_image(imag_usecase)
+
+ def test_conjugate(self):
+ pyfunc = conjugate_usecase
+ values = self.basic_values()
+ self.run_unary(pyfunc,
+ [types.complex64, types.complex128],
+ values)
+
+
+class TestCMath(BaseComplexTest):
+ """
+ Tests for cmath module support.
+ """
+
+ def check_predicate_func(self, pyfunc):
+ self.run_unary(pyfunc,
+ [types.boolean(tp)
+ for tp in (types.complex128, types.complex64)],
+ self.basic_values())
+
+ def check_unary_func(self, pyfunc, ulps=1, values=None,
+ returns_float=False, ignore_sign_on_zero=False):
+ if returns_float:
+ def sig(tp):
+ return tp.underlying_float(tp)
+ else:
+ def sig(tp):
+ return tp(tp)
+ self.run_unary(pyfunc, [sig(types.complex128)],
+ values or self.more_values(), ulps=ulps,
+ ignore_sign_on_zero=ignore_sign_on_zero)
+ # Avoid discontinuities around pi when in single precision.
+ self.run_unary(pyfunc, [sig(types.complex64)],
+ values or self.basic_values(), ulps=ulps,
+ ignore_sign_on_zero=ignore_sign_on_zero)
+
+ # Conversions
+
+ def test_phase(self):
+ self.check_unary_func(phase_usecase, returns_float=True)
+
+ def test_polar(self):
+ self.check_unary_func(polar_as_complex_usecase)
+
+ def test_rect(self):
+ def do_test(tp, seed_values):
+ values = [(z.real, z.imag) for z in seed_values
+ if not math.isinf(z.imag) or z.real == 0]
+ float_type = tp.underlying_float
+ self.run_binary(rect_usecase, [tp(float_type, float_type)],
+ values)
+ do_test(types.complex128, self.more_values())
+ # Avoid discontinuities around pi when in single precision.
+ do_test(types.complex64, self.basic_values())
+
+ # Classification
+
+ def test_isnan(self):
+ self.check_predicate_func(isnan_usecase)
+
+ def test_isinf(self):
+ self.check_predicate_func(isinf_usecase)
+
+ def test_isfinite(self):
+ self.check_predicate_func(isfinite_usecase)
+
+ # Power and logarithms
+
+ def test_exp(self):
+ self.check_unary_func(exp_usecase, ulps=2)
+
+ def test_log(self):
+ self.check_unary_func(log_usecase)
+
+ def test_log_base(self):
+ values = list(itertools.product(self.more_values(), self.more_values()))
+ value_types = [(types.complex128, types.complex128),
+ (types.complex64, types.complex64)]
+ self.run_binary(log_base_usecase, value_types, values,
+ ulps=3)
+
+ def test_log10(self):
+ self.check_unary_func(log10_usecase)
+
+ def test_sqrt(self):
+ self.check_unary_func(sqrt_usecase)
+
+ # Trigonometric functions
+
+ def test_acos(self):
+ self.check_unary_func(acos_usecase, ulps=2)
+
+ def test_asin(self):
+ self.check_unary_func(asin_usecase, ulps=2)
+
+ def test_atan(self):
+ self.check_unary_func(atan_usecase, ulps=2,
+ values=self.non_nan_values())
+
+ def test_cos(self):
+ self.check_unary_func(cos_usecase, ulps=2)
+
+ def test_sin(self):
+ # See test_sinh.
+ self.check_unary_func(sin_usecase, ulps=2)
+
+ def test_tan(self):
+ self.check_unary_func(tan_usecase, ulps=2,
+ ignore_sign_on_zero=True)
+
+ # Hyperbolic functions
+
+ def test_acosh(self):
+ self.check_unary_func(acosh_usecase)
+
+ def test_asinh(self):
+ self.check_unary_func(asinh_usecase, ulps=2)
+
+ def test_atanh(self):
+ self.check_unary_func(atanh_usecase, ulps=2,
+ ignore_sign_on_zero=True)
+
+ def test_cosh(self):
+ self.check_unary_func(cosh_usecase, ulps=2)
+
+ def test_sinh(self):
+ self.check_unary_func(sinh_usecase, ulps=2)
+
+ def test_tanh(self):
+ self.check_unary_func(tanh_usecase, ulps=2,
+ ignore_sign_on_zero=True)
+
+
+class TestAtomicOnComplexComponents(CUDATestCase):
+ # Based on the reproducer from Issue #8309. array.real and array.imag could
+ # not be used because they required returning an array from a generated
+ # function, and even if this was permitted, they could not be resolved from
+ # the atomic lowering when they were overloads.
+ #
+ # See https://github.com/numba/numba/issues/8309
+
+ def test_atomic_on_real(self):
+ @cuda.jit
+ def atomic_add_one(values):
+ i = cuda.grid(1)
+ cuda.atomic.add(values.real, i, 1)
+
+ N = 32
+ arr1 = np.arange(N) + np.arange(N) * 1j
+ arr2 = arr1.copy()
+ atomic_add_one[1, N](arr2)
+ np.testing.assert_equal(arr1 + 1, arr2)
+
+ def test_atomic_on_imag(self):
+ @cuda.jit
+ def atomic_add_one_j(values):
+ i = cuda.grid(1)
+ cuda.atomic.add(values.imag, i, 1)
+
+ N = 32
+ arr1 = np.arange(N) + np.arange(N) * 1j
+ arr2 = arr1.copy()
+ atomic_add_one_j[1, N](arr2)
+ np.testing.assert_equal(arr1 + 1j, arr2)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_complex_kernel.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_complex_kernel.py
new file mode 100644
index 0000000000000000000000000000000000000000..e72a6df006a41eafa3312fd8ff9eb11a869936d1
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_complex_kernel.py
@@ -0,0 +1,20 @@
+import numpy as np
+from numba import cuda
+from numba.cuda.testing import unittest, CUDATestCase
+
+
+class TestCudaComplex(CUDATestCase):
+ def test_cuda_complex_arg(self):
+ @cuda.jit('void(complex128[:], complex128)')
+ def foo(a, b):
+ i = cuda.grid(1)
+ a[i] += b
+
+ a = np.arange(5, dtype=np.complex128)
+ a0 = a.copy()
+ foo[1, a.shape](a, 2j)
+ self.assertTrue(np.allclose(a, a0 + 2j))
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_const_string.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_const_string.py
new file mode 100644
index 0000000000000000000000000000000000000000..173319cb223c11bd0cb1866926d50b63dee9a36e
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_const_string.py
@@ -0,0 +1,129 @@
+import re
+import numpy as np
+from numba import cuda
+from numba.cuda.testing import unittest, skip_on_cudasim, CUDATestCase
+from llvmlite import ir
+
+
+@skip_on_cudasim("This is testing CUDA backend code generation")
+class TestConstStringCodegen(unittest.TestCase):
+ def test_const_string(self):
+ # These imports are incompatible with CUDASIM
+ from numba.cuda.descriptor import cuda_target
+ from numba.cuda.cudadrv.nvvm import compile_ir
+
+ targetctx = cuda_target.target_context
+ mod = targetctx.create_module("")
+ textstring = 'A Little Brown Fox'
+ gv0 = targetctx.insert_const_string(mod, textstring)
+ # Insert the same const string a second time - the first should be
+ # reused.
+ targetctx.insert_const_string(mod, textstring)
+
+ res = re.findall(r"@\"__conststring__.*internal.*constant.*\["
+ r"19\s+x\s+i8\]", str(mod))
+ # Ensure that the const string was only inserted once
+ self.assertEqual(len(res), 1)
+
+ fnty = ir.FunctionType(ir.IntType(8).as_pointer(), [])
+
+ # Using insert_const_string
+ fn = ir.Function(mod, fnty, "test_insert_const_string")
+ builder = ir.IRBuilder(fn.append_basic_block())
+ res = builder.addrspacecast(gv0, ir.PointerType(ir.IntType(8)),
+ 'generic')
+ builder.ret(res)
+
+ matches = re.findall(r"@\"__conststring__.*internal.*constant.*\["
+ r"19\s+x\s+i8\]", str(mod))
+ self.assertEqual(len(matches), 1)
+
+ # Using insert_string_const_addrspace
+ fn = ir.Function(mod, fnty, "test_insert_string_const_addrspace")
+ builder = ir.IRBuilder(fn.append_basic_block())
+ res = targetctx.insert_string_const_addrspace(builder, textstring)
+ builder.ret(res)
+
+ matches = re.findall(r"@\"__conststring__.*internal.*constant.*\["
+ r"19\s+x\s+i8\]", str(mod))
+ self.assertEqual(len(matches), 1)
+
+ ptx = compile_ir(str(mod)).decode('ascii')
+ matches = list(re.findall(r"\.const.*__conststring__", ptx))
+
+ self.assertEqual(len(matches), 1)
+
+
+# Inspired by the reproducer from Issue #7041.
+class TestConstString(CUDATestCase):
+ def test_assign_const_unicode_string(self):
+ @cuda.jit
+ def str_assign(arr):
+ i = cuda.grid(1)
+ if i < len(arr):
+ arr[i] = "XYZ"
+
+ n_strings = 8
+ arr = np.zeros(n_strings + 1, dtype=" mb:
+ unittest.skip("GPU cannot support enough cooperative grid blocks")
+
+ c_sequential_rows[griddim, blockdim](A)
+
+ reference = np.tile(np.arange(shape[0]), (shape[1], 1)).T
+ np.testing.assert_equal(A, reference)
+
+ @skip_unless_cc_60
+ def test_max_cooperative_grid_blocks(self):
+ # The maximum number of blocks will vary based on the device so we
+ # can't test for an expected value, but we can check that the function
+ # doesn't error, and that varying the number of dimensions of the block
+ # whilst keeping the total number of threads constant doesn't change
+ # the maximum to validate some of the logic.
+ sig = (int32[:,::1],)
+ c_sequential_rows = cuda.jit(sig)(sequential_rows)
+ overload = c_sequential_rows.overloads[sig]
+ blocks1d = overload.max_cooperative_grid_blocks(256)
+ blocks2d = overload.max_cooperative_grid_blocks((16, 16))
+ blocks3d = overload.max_cooperative_grid_blocks((16, 4, 4))
+ self.assertEqual(blocks1d, blocks2d)
+ self.assertEqual(blocks1d, blocks3d)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_cuda_array_interface.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_cuda_array_interface.py
new file mode 100644
index 0000000000000000000000000000000000000000..6448f450a58a16bc841b6b457330afd3fd933e49
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_cuda_array_interface.py
@@ -0,0 +1,435 @@
+import numpy as np
+
+from numba import vectorize, guvectorize
+from numba import cuda
+from numba.cuda.cudadrv import driver
+from numba.cuda.testing import unittest, ContextResettingTestCase, ForeignArray
+from numba.cuda.testing import skip_on_cudasim, skip_if_external_memmgr
+from numba.tests.support import linux_only, override_config
+from unittest.mock import call, patch
+
+
+@skip_on_cudasim('CUDA Array Interface is not supported in the simulator')
+class TestCudaArrayInterface(ContextResettingTestCase):
+ def assertPointersEqual(self, a, b):
+ if driver.USE_NV_BINDING:
+ self.assertEqual(int(a.device_ctypes_pointer),
+ int(b.device_ctypes_pointer))
+
+ def test_as_cuda_array(self):
+ h_arr = np.arange(10)
+ self.assertFalse(cuda.is_cuda_array(h_arr))
+ d_arr = cuda.to_device(h_arr)
+ self.assertTrue(cuda.is_cuda_array(d_arr))
+ my_arr = ForeignArray(d_arr)
+ self.assertTrue(cuda.is_cuda_array(my_arr))
+ wrapped = cuda.as_cuda_array(my_arr)
+ self.assertTrue(cuda.is_cuda_array(wrapped))
+ # Their values must equal the original array
+ np.testing.assert_array_equal(wrapped.copy_to_host(), h_arr)
+ np.testing.assert_array_equal(d_arr.copy_to_host(), h_arr)
+ # d_arr and wrapped must be the same buffer
+ self.assertPointersEqual(wrapped, d_arr)
+
+ def get_stream_value(self, stream):
+ if driver.USE_NV_BINDING:
+ return int(stream.handle)
+ else:
+ return stream.handle.value
+
+ @skip_if_external_memmgr('Ownership not relevant with external memmgr')
+ def test_ownership(self):
+ # Get the deallocation queue
+ ctx = cuda.current_context()
+ deallocs = ctx.memory_manager.deallocations
+ # Flush all deallocations
+ deallocs.clear()
+ self.assertEqual(len(deallocs), 0)
+ # Make new device array
+ d_arr = cuda.to_device(np.arange(100))
+ # Convert it
+ cvted = cuda.as_cuda_array(d_arr)
+ # Drop reference to the original object such that
+ # only `cvted` has a reference to it.
+ del d_arr
+ # There shouldn't be any new deallocations
+ self.assertEqual(len(deallocs), 0)
+ # Try to access the memory and verify its content
+ np.testing.assert_equal(cvted.copy_to_host(), np.arange(100))
+ # Drop last reference to the memory
+ del cvted
+ self.assertEqual(len(deallocs), 1)
+ # Flush
+ deallocs.clear()
+
+ def test_kernel_arg(self):
+ h_arr = np.arange(10)
+ d_arr = cuda.to_device(h_arr)
+ my_arr = ForeignArray(d_arr)
+ wrapped = cuda.as_cuda_array(my_arr)
+
+ @cuda.jit
+ def mutate(arr, val):
+ i = cuda.grid(1)
+ if i >= len(arr):
+ return
+ arr[i] += val
+
+ val = 7
+ mutate.forall(wrapped.size)(wrapped, val)
+
+ np.testing.assert_array_equal(wrapped.copy_to_host(), h_arr + val)
+ np.testing.assert_array_equal(d_arr.copy_to_host(), h_arr + val)
+
+ def test_ufunc_arg(self):
+ @vectorize(['f8(f8, f8)'], target='cuda')
+ def vadd(a, b):
+ return a + b
+
+ # Case 1: use custom array as argument
+ h_arr = np.random.random(10)
+ arr = ForeignArray(cuda.to_device(h_arr))
+ val = 6
+ out = vadd(arr, val)
+ np.testing.assert_array_equal(out.copy_to_host(), h_arr + val)
+
+ # Case 2: use custom array as return
+ out = ForeignArray(cuda.device_array(h_arr.shape))
+ returned = vadd(h_arr, val, out=out)
+ np.testing.assert_array_equal(returned.copy_to_host(), h_arr + val)
+
+ def test_gufunc_arg(self):
+ @guvectorize(['(f8, f8, f8[:])'], '(),()->()', target='cuda')
+ def vadd(inp, val, out):
+ out[0] = inp + val
+
+ # Case 1: use custom array as argument
+ h_arr = np.random.random(10)
+ arr = ForeignArray(cuda.to_device(h_arr))
+ val = np.float64(7)
+ out = vadd(arr, val)
+ np.testing.assert_array_equal(out.copy_to_host(), h_arr + val)
+
+ # Case 2: use custom array as return
+ out = ForeignArray(cuda.device_array(h_arr.shape))
+ returned = vadd(h_arr, val, out=out)
+ np.testing.assert_array_equal(returned.copy_to_host(), h_arr + val)
+ self.assertPointersEqual(returned, out._arr)
+
+ def test_array_views(self):
+ """Views created via array interface support:
+ - Strided slices
+ - Strided slices
+ """
+ h_arr = np.random.random(10)
+ c_arr = cuda.to_device(h_arr)
+
+ arr = cuda.as_cuda_array(c_arr)
+
+ # __getitem__ interface accesses expected data
+
+ # Direct views
+ np.testing.assert_array_equal(arr.copy_to_host(), h_arr)
+ np.testing.assert_array_equal(arr[:].copy_to_host(), h_arr)
+
+ # Slicing
+ np.testing.assert_array_equal(arr[:5].copy_to_host(), h_arr[:5])
+
+ # Strided view
+ np.testing.assert_array_equal(arr[::2].copy_to_host(), h_arr[::2])
+
+ # View of strided array
+ arr_strided = cuda.as_cuda_array(c_arr[::2])
+ np.testing.assert_array_equal(arr_strided.copy_to_host(), h_arr[::2])
+
+ # A strided-view-of-array and view-of-strided-array have the same
+ # shape, strides, itemsize, and alloc_size
+ self.assertEqual(arr[::2].shape, arr_strided.shape)
+ self.assertEqual(arr[::2].strides, arr_strided.strides)
+ self.assertEqual(arr[::2].dtype.itemsize, arr_strided.dtype.itemsize)
+ self.assertEqual(arr[::2].alloc_size, arr_strided.alloc_size)
+ self.assertEqual(arr[::2].nbytes,
+ arr_strided.size * arr_strided.dtype.itemsize)
+
+ # __setitem__ interface propagates into external array
+
+ # Writes to a slice
+ arr[:5] = np.pi
+ np.testing.assert_array_equal(
+ c_arr.copy_to_host(),
+ np.concatenate((np.full(5, np.pi), h_arr[5:]))
+ )
+
+ # Writes to a slice from a view
+ arr[:5] = arr[5:]
+ np.testing.assert_array_equal(
+ c_arr.copy_to_host(),
+ np.concatenate((h_arr[5:], h_arr[5:]))
+ )
+
+ # Writes through a view
+ arr[:] = cuda.to_device(h_arr)
+ np.testing.assert_array_equal(c_arr.copy_to_host(), h_arr)
+
+ # Writes to a strided slice
+ arr[::2] = np.pi
+ np.testing.assert_array_equal(
+ c_arr.copy_to_host()[::2],
+ np.full(5, np.pi),
+ )
+ np.testing.assert_array_equal(
+ c_arr.copy_to_host()[1::2],
+ h_arr[1::2]
+ )
+
+ def test_negative_strided_issue(self):
+ # issue #3705
+ h_arr = np.random.random(10)
+ c_arr = cuda.to_device(h_arr)
+
+ def base_offset(orig, sliced):
+ return sliced['data'][0] - orig['data'][0]
+
+ h_ai = h_arr.__array_interface__
+ c_ai = c_arr.__cuda_array_interface__
+
+ h_ai_sliced = h_arr[::-1].__array_interface__
+ c_ai_sliced = c_arr[::-1].__cuda_array_interface__
+
+ # Check data offset is correct
+ self.assertEqual(
+ base_offset(h_ai, h_ai_sliced),
+ base_offset(c_ai, c_ai_sliced),
+ )
+ # Check shape and strides are correct
+ self.assertEqual(h_ai_sliced['shape'], c_ai_sliced['shape'])
+ self.assertEqual(h_ai_sliced['strides'], c_ai_sliced['strides'])
+
+ def test_negative_strided_copy_to_host(self):
+ # issue #3705
+ h_arr = np.random.random(10)
+ c_arr = cuda.to_device(h_arr)
+ sliced = c_arr[::-1]
+ with self.assertRaises(NotImplementedError) as raises:
+ sliced.copy_to_host()
+ expected_msg = 'D->H copy not implemented for negative strides'
+ self.assertIn(expected_msg, str(raises.exception))
+
+ def test_masked_array(self):
+ h_arr = np.random.random(10)
+ h_mask = np.random.randint(2, size=10, dtype='bool')
+ c_arr = cuda.to_device(h_arr)
+ c_mask = cuda.to_device(h_mask)
+
+ # Manually create a masked CUDA Array Interface dictionary
+ masked_cuda_array_interface = c_arr.__cuda_array_interface__.copy()
+ masked_cuda_array_interface['mask'] = c_mask
+
+ with self.assertRaises(NotImplementedError) as raises:
+ cuda.from_cuda_array_interface(masked_cuda_array_interface)
+ expected_msg = 'Masked arrays are not supported'
+ self.assertIn(expected_msg, str(raises.exception))
+
+ def test_zero_size_array(self):
+ # for #4175
+ c_arr = cuda.device_array(0)
+ self.assertEqual(c_arr.__cuda_array_interface__['data'][0], 0)
+
+ @cuda.jit
+ def add_one(arr):
+ x = cuda.grid(1)
+ N = arr.shape[0]
+ if x < N:
+ arr[x] += 1
+
+ d_arr = ForeignArray(c_arr)
+ add_one[1, 10](d_arr) # this should pass
+
+ def test_strides(self):
+ # for #4175
+ # First, test C-contiguous array
+ c_arr = cuda.device_array((2, 3, 4))
+ self.assertEqual(c_arr.__cuda_array_interface__['strides'], None)
+
+ # Second, test non C-contiguous array
+ c_arr = c_arr[:, 1, :]
+ self.assertNotEqual(c_arr.__cuda_array_interface__['strides'], None)
+
+ def test_consuming_strides(self):
+ hostarray = np.arange(10).reshape(2, 5)
+ devarray = cuda.to_device(hostarray)
+ face = devarray.__cuda_array_interface__
+ self.assertIsNone(face['strides'])
+ got = cuda.from_cuda_array_interface(face).copy_to_host()
+ np.testing.assert_array_equal(got, hostarray)
+ self.assertTrue(got.flags['C_CONTIGUOUS'])
+ # Try non-NULL strides
+ face['strides'] = hostarray.strides
+ self.assertIsNotNone(face['strides'])
+ got = cuda.from_cuda_array_interface(face).copy_to_host()
+ np.testing.assert_array_equal(got, hostarray)
+ self.assertTrue(got.flags['C_CONTIGUOUS'])
+
+ def test_produce_no_stream(self):
+ c_arr = cuda.device_array(10)
+ self.assertIsNone(c_arr.__cuda_array_interface__['stream'])
+
+ mapped_arr = cuda.mapped_array(10)
+ self.assertIsNone(mapped_arr.__cuda_array_interface__['stream'])
+
+ @linux_only
+ def test_produce_managed_no_stream(self):
+ managed_arr = cuda.managed_array(10)
+ self.assertIsNone(managed_arr.__cuda_array_interface__['stream'])
+
+ def test_produce_stream(self):
+ s = cuda.stream()
+ c_arr = cuda.device_array(10, stream=s)
+ cai_stream = c_arr.__cuda_array_interface__['stream']
+ stream_value = self.get_stream_value(s)
+ self.assertEqual(stream_value, cai_stream)
+
+ s = cuda.stream()
+ mapped_arr = cuda.mapped_array(10, stream=s)
+ cai_stream = mapped_arr.__cuda_array_interface__['stream']
+ stream_value = self.get_stream_value(s)
+ self.assertEqual(stream_value, cai_stream)
+
+ @linux_only
+ def test_produce_managed_stream(self):
+ s = cuda.stream()
+ managed_arr = cuda.managed_array(10, stream=s)
+ cai_stream = managed_arr.__cuda_array_interface__['stream']
+ stream_value = self.get_stream_value(s)
+ self.assertEqual(stream_value, cai_stream)
+
+ def test_consume_no_stream(self):
+ # Create a foreign array with no stream
+ f_arr = ForeignArray(cuda.device_array(10))
+
+ # Ensure that the imported array has no default stream
+ c_arr = cuda.as_cuda_array(f_arr)
+ self.assertEqual(c_arr.stream, 0)
+
+ def test_consume_stream(self):
+ # Create a foreign array with a stream
+ s = cuda.stream()
+ f_arr = ForeignArray(cuda.device_array(10, stream=s))
+
+ # Ensure that an imported array has the stream as its default stream
+ c_arr = cuda.as_cuda_array(f_arr)
+ self.assertTrue(c_arr.stream.external)
+ stream_value = self.get_stream_value(s)
+ imported_stream_value = self.get_stream_value(c_arr.stream)
+ self.assertEqual(stream_value, imported_stream_value)
+
+ def test_consume_no_sync(self):
+ # Create a foreign array with no stream
+ f_arr = ForeignArray(cuda.device_array(10))
+
+ with patch.object(cuda.cudadrv.driver.Stream, 'synchronize',
+ return_value=None) as mock_sync:
+ cuda.as_cuda_array(f_arr)
+
+ # Ensure the synchronize method of a stream was not called
+ mock_sync.assert_not_called()
+
+ def test_consume_sync(self):
+ # Create a foreign array with a stream
+ s = cuda.stream()
+ f_arr = ForeignArray(cuda.device_array(10, stream=s))
+
+ with patch.object(cuda.cudadrv.driver.Stream, 'synchronize',
+ return_value=None) as mock_sync:
+ cuda.as_cuda_array(f_arr)
+
+ # Ensure the synchronize method of a stream was called
+ mock_sync.assert_called_once_with()
+
+ def test_consume_sync_disabled(self):
+ # Create a foreign array with a stream
+ s = cuda.stream()
+ f_arr = ForeignArray(cuda.device_array(10, stream=s))
+
+ # Set sync to false before testing. The test suite should generally be
+ # run with sync enabled, but stash the old value just in case it is
+ # not.
+ with override_config('CUDA_ARRAY_INTERFACE_SYNC', False):
+ with patch.object(cuda.cudadrv.driver.Stream, 'synchronize',
+ return_value=None) as mock_sync:
+ cuda.as_cuda_array(f_arr)
+
+ # Ensure the synchronize method of a stream was not called
+ mock_sync.assert_not_called()
+
+ def test_launch_no_sync(self):
+ # Create a foreign array with no stream
+ f_arr = ForeignArray(cuda.device_array(10))
+
+ @cuda.jit
+ def f(x):
+ pass
+
+ with patch.object(cuda.cudadrv.driver.Stream, 'synchronize',
+ return_value=None) as mock_sync:
+ f[1, 1](f_arr)
+
+ # Ensure the synchronize method of a stream was not called
+ mock_sync.assert_not_called()
+
+ def test_launch_sync(self):
+ # Create a foreign array with a stream
+ s = cuda.stream()
+ f_arr = ForeignArray(cuda.device_array(10, stream=s))
+
+ @cuda.jit
+ def f(x):
+ pass
+
+ with patch.object(cuda.cudadrv.driver.Stream, 'synchronize',
+ return_value=None) as mock_sync:
+ f[1, 1](f_arr)
+
+ # Ensure the synchronize method of a stream was called
+ mock_sync.assert_called_once_with()
+
+ def test_launch_sync_two_streams(self):
+ # Create two foreign arrays with streams
+ s1 = cuda.stream()
+ s2 = cuda.stream()
+ f_arr1 = ForeignArray(cuda.device_array(10, stream=s1))
+ f_arr2 = ForeignArray(cuda.device_array(10, stream=s2))
+
+ @cuda.jit
+ def f(x, y):
+ pass
+
+ with patch.object(cuda.cudadrv.driver.Stream, 'synchronize',
+ return_value=None) as mock_sync:
+ f[1, 1](f_arr1, f_arr2)
+
+ # Ensure that synchronize was called twice
+ mock_sync.assert_has_calls([call(), call()])
+
+ def test_launch_sync_disabled(self):
+ # Create two foreign arrays with streams
+ s1 = cuda.stream()
+ s2 = cuda.stream()
+ f_arr1 = ForeignArray(cuda.device_array(10, stream=s1))
+ f_arr2 = ForeignArray(cuda.device_array(10, stream=s2))
+
+ with override_config('CUDA_ARRAY_INTERFACE_SYNC', False):
+ @cuda.jit
+ def f(x, y):
+ pass
+
+ with patch.object(cuda.cudadrv.driver.Stream, 'synchronize',
+ return_value=None) as mock_sync:
+ f[1, 1](f_arr1, f_arr2)
+
+ # Ensure that synchronize was not called
+ mock_sync.assert_not_called()
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_cuda_jit_no_types.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_cuda_jit_no_types.py
new file mode 100644
index 0000000000000000000000000000000000000000..b57e7649c172b38c8b8a117bcad2a2df5e251a97
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_cuda_jit_no_types.py
@@ -0,0 +1,90 @@
+from numba import cuda
+import numpy as np
+from numba.cuda.testing import CUDATestCase
+from numba.tests.support import override_config
+import unittest
+
+
+class TestCudaJitNoTypes(CUDATestCase):
+ """
+ Tests the jit decorator with no types provided.
+ """
+
+ def test_device_array(self):
+ @cuda.jit
+ def foo(x, y):
+ i = cuda.grid(1)
+ y[i] = x[i]
+
+ x = np.arange(10)
+ y = np.empty_like(x)
+
+ dx = cuda.to_device(x)
+ dy = cuda.to_device(y)
+
+ foo[10, 1](dx, dy)
+
+ dy.copy_to_host(y)
+
+ self.assertTrue(np.all(x == y))
+
+ def test_device_jit(self):
+ @cuda.jit(device=True)
+ def mapper(args):
+ a, b, c = args
+ return a + b + c
+
+ @cuda.jit(device=True)
+ def reducer(a, b):
+ return a + b
+
+ @cuda.jit
+ def driver(A, B):
+ i = cuda.grid(1)
+ if i < B.size:
+ args = A[i], A[i] + B[i], B[i]
+ B[i] = reducer(mapper(args), 1)
+
+ A = np.arange(100, dtype=np.float32)
+ B = np.arange(100, dtype=np.float32)
+
+ Acopy = A.copy()
+ Bcopy = B.copy()
+
+ driver[1, 100](A, B)
+
+ np.testing.assert_allclose(Acopy + Acopy + Bcopy + Bcopy + 1, B)
+
+ def test_device_jit_2(self):
+ @cuda.jit(device=True)
+ def inner(arg):
+ return arg + 1
+
+ @cuda.jit
+ def outer(argin, argout):
+ argout[0] = inner(argin[0]) + inner(2)
+
+ a = np.zeros(1)
+ b = np.zeros(1)
+
+ stream = cuda.stream()
+ d_a = cuda.to_device(a, stream)
+ d_b = cuda.to_device(b, stream)
+
+ outer[1, 1, stream](d_a, d_b)
+
+ d_b.copy_to_host(b, stream)
+
+ self.assertEqual(b[0], (a[0] + 1) + (2 + 1))
+
+ def test_jit_debug_simulator(self):
+ # Ensure that the jit decorator accepts the debug kwarg when the
+ # simulator is in use - see Issue #6615.
+ with override_config('ENABLE_CUDASIM', 1):
+ @cuda.jit(debug=True)
+ def f(x):
+ pass
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_datetime.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_datetime.py
new file mode 100644
index 0000000000000000000000000000000000000000..7921f9e9b8bce3fb325266e8888d3e1626c31809
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_datetime.py
@@ -0,0 +1,94 @@
+import numpy as np
+
+from numba import cuda, vectorize, guvectorize
+from numba.np.numpy_support import from_dtype
+from numba.cuda.testing import CUDATestCase, skip_on_cudasim
+import unittest
+
+
+class TestCudaDateTime(CUDATestCase):
+ def test_basic_datetime_kernel(self):
+ @cuda.jit
+ def foo(start, end, delta):
+ for i in range(cuda.grid(1), delta.size, cuda.gridsize(1)):
+ delta[i] = end[i] - start[i]
+
+ arr1 = np.arange('2005-02', '2006-02', dtype='datetime64[D]')
+ arr2 = arr1 + np.random.randint(0, 10000, arr1.size)
+ delta = np.zeros_like(arr1, dtype='timedelta64[D]')
+
+ foo[1, 32](arr1, arr2, delta)
+
+ self.assertPreciseEqual(delta, arr2 - arr1)
+
+ def test_scalar_datetime_kernel(self):
+ @cuda.jit
+ def foo(dates, target, delta, matches, outdelta):
+ for i in range(cuda.grid(1), matches.size, cuda.gridsize(1)):
+ matches[i] = dates[i] == target
+ outdelta[i] = dates[i] - delta
+ arr1 = np.arange('2005-02', '2006-02', dtype='datetime64[D]')
+ target = arr1[5] # datetime
+ delta = arr1[6] - arr1[5] # timedelta
+ matches = np.zeros_like(arr1, dtype=np.bool_)
+ outdelta = np.zeros_like(arr1, dtype='datetime64[D]')
+
+ foo[1, 32](arr1, target, delta, matches, outdelta)
+ where = matches.nonzero()
+
+ self.assertEqual(list(where), [5])
+ self.assertPreciseEqual(outdelta, arr1 - delta)
+
+ @skip_on_cudasim('ufunc API unsupported in the simulator')
+ def test_ufunc(self):
+ datetime_t = from_dtype(np.dtype('datetime64[D]'))
+
+ @vectorize([(datetime_t, datetime_t)], target='cuda')
+ def timediff(start, end):
+ return end - start
+
+ arr1 = np.arange('2005-02', '2006-02', dtype='datetime64[D]')
+ arr2 = arr1 + np.random.randint(0, 10000, arr1.size)
+
+ delta = timediff(arr1, arr2)
+
+ self.assertPreciseEqual(delta, arr2 - arr1)
+
+ @skip_on_cudasim('ufunc API unsupported in the simulator')
+ def test_gufunc(self):
+ datetime_t = from_dtype(np.dtype('datetime64[D]'))
+ timedelta_t = from_dtype(np.dtype('timedelta64[D]'))
+
+ @guvectorize([(datetime_t, datetime_t, timedelta_t[:])], '(),()->()',
+ target='cuda')
+ def timediff(start, end, out):
+ out[0] = end - start
+
+ arr1 = np.arange('2005-02', '2006-02', dtype='datetime64[D]')
+ arr2 = arr1 + np.random.randint(0, 10000, arr1.size)
+
+ delta = timediff(arr1, arr2)
+
+ self.assertPreciseEqual(delta, arr2 - arr1)
+
+ @skip_on_cudasim('no .copy_to_host() in the simulator')
+ def test_datetime_view_as_int64(self):
+ arr = np.arange('2005-02', '2006-02', dtype='datetime64[D]')
+ darr = cuda.to_device(arr)
+ viewed = darr.view(np.int64)
+ self.assertPreciseEqual(arr.view(np.int64), viewed.copy_to_host())
+ self.assertEqual(viewed.gpu_data, darr.gpu_data)
+
+ @skip_on_cudasim('no .copy_to_host() in the simulator')
+ def test_timedelta_view_as_int64(self):
+ arr = np.arange('2005-02', '2006-02', dtype='datetime64[D]')
+ arr = arr - (arr - 1)
+ self.assertEqual(arr.dtype, np.dtype('timedelta64[D]'))
+ darr = cuda.to_device(arr)
+ viewed = darr.view(np.int64)
+ self.assertPreciseEqual(arr.view(np.int64), viewed.copy_to_host())
+ self.assertEqual(viewed.gpu_data, darr.gpu_data)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_debug.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_debug.py
new file mode 100644
index 0000000000000000000000000000000000000000..e507aa91aa042a30680ad812df1f92547eb42c18
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_debug.py
@@ -0,0 +1,101 @@
+import numpy as np
+
+from numba.core.utils import PYVERSION
+from numba.cuda.testing import skip_on_cudasim, CUDATestCase
+from numba.tests.support import (override_config, captured_stderr,
+ captured_stdout)
+from numba import cuda, float64
+import unittest
+
+
+def simple_cuda(A, B):
+ i = cuda.grid(1)
+ B[i] = A[i] + 1.5
+
+
+@skip_on_cudasim('Simulator does not produce debug dumps')
+class TestDebugOutput(CUDATestCase):
+
+ def compile_simple_cuda(self):
+ with captured_stderr() as err:
+ with captured_stdout() as out:
+ cfunc = cuda.jit((float64[:], float64[:]))(simple_cuda)
+ # Call compiled function (to ensure PTX is generated)
+ # and sanity-check results.
+ A = np.linspace(0, 1, 10).astype(np.float64)
+ B = np.zeros_like(A)
+ cfunc[1, 10](A, B)
+ self.assertTrue(np.allclose(A + 1.5, B))
+ # stderr shouldn't be affected by debug output
+ self.assertFalse(err.getvalue())
+ return out.getvalue()
+
+ def assert_fails(self, *args, **kwargs):
+ self.assertRaises(AssertionError, *args, **kwargs)
+
+ def check_debug_output(self, out, enabled_dumps):
+ all_dumps = dict.fromkeys(['bytecode', 'cfg', 'ir', 'llvm',
+ 'assembly'],
+ False)
+ for name in enabled_dumps:
+ assert name in all_dumps
+ all_dumps[name] = True
+ for name, enabled in sorted(all_dumps.items()):
+ check_meth = getattr(self, '_check_dump_%s' % name)
+ if enabled:
+ check_meth(out)
+ else:
+ self.assertRaises(AssertionError, check_meth, out)
+
+ def _check_dump_bytecode(self, out):
+ if PYVERSION in ((3, 11), (3, 12), (3, 13)):
+ # binop with arg=0 is binary add, see CPython dis.py and opcode.py
+ self.assertIn('BINARY_OP(arg=0', out)
+ elif PYVERSION in ((3, 10),):
+ self.assertIn('BINARY_ADD', out)
+ else:
+ raise NotImplementedError(PYVERSION)
+
+ def _check_dump_cfg(self, out):
+ self.assertIn('CFG dominators', out)
+
+ def _check_dump_ir(self, out):
+ self.assertIn('--IR DUMP: simple_cuda--', out)
+ self.assertIn('const(float, 1.5)', out)
+
+ def _check_dump_llvm(self, out):
+ self.assertIn('--LLVM DUMP', out)
+ self.assertIn('!"kernel", i32 1', out)
+
+ def _check_dump_assembly(self, out):
+ self.assertIn('--ASSEMBLY simple_cuda', out)
+ self.assertIn('Generated by NVIDIA NVVM Compiler', out)
+
+ def test_dump_bytecode(self):
+ with override_config('DUMP_BYTECODE', True):
+ out = self.compile_simple_cuda()
+ self.check_debug_output(out, ['bytecode'])
+
+ def test_dump_ir(self):
+ with override_config('DUMP_IR', True):
+ out = self.compile_simple_cuda()
+ self.check_debug_output(out, ['ir'])
+
+ def test_dump_cfg(self):
+ with override_config('DUMP_CFG', True):
+ out = self.compile_simple_cuda()
+ self.check_debug_output(out, ['cfg'])
+
+ def test_dump_llvm(self):
+ with override_config('DUMP_LLVM', True):
+ out = self.compile_simple_cuda()
+ self.check_debug_output(out, ['llvm'])
+
+ def test_dump_assembly(self):
+ with override_config('DUMP_ASSEMBLY', True):
+ out = self.compile_simple_cuda()
+ self.check_debug_output(out, ['assembly'])
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_debuginfo.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_debuginfo.py
new file mode 100644
index 0000000000000000000000000000000000000000..efe42b50ce31f2a5e18c64f77e8198eb2f8ad2f8
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_debuginfo.py
@@ -0,0 +1,221 @@
+from numba.tests.support import override_config
+from numba.cuda.testing import skip_on_cudasim
+from numba import cuda
+from numba.core import types
+from numba.cuda.testing import CUDATestCase
+import itertools
+import re
+import unittest
+
+
+@skip_on_cudasim('Simulator does not produce debug dumps')
+class TestCudaDebugInfo(CUDATestCase):
+ """
+ These tests only checks the compiled PTX for debuginfo section
+ """
+
+ def setUp(self):
+ super().setUp()
+ # If we're using LTO then we can't check the PTX in these tests,
+ # because we produce LTO-IR, which is opaque to the user.
+ # Additionally, LTO optimizes away the exception status due to an
+ # oversight in the way we generate it (it is not added to the used
+ # list).
+ self.skip_if_lto("Exceptions not supported with LTO")
+
+ def _getasm(self, fn, sig):
+ fn.compile(sig)
+ return fn.inspect_asm(sig)
+
+ def _check(self, fn, sig, expect):
+ asm = self._getasm(fn, sig=sig)
+ re_section_dbginfo = re.compile(r"\.section\s+\.debug_info\s+{")
+ match = re_section_dbginfo.search(asm)
+ assertfn = self.assertIsNotNone if expect else self.assertIsNone
+ assertfn(match, msg=asm)
+
+ def test_no_debuginfo_in_asm(self):
+ @cuda.jit(debug=False)
+ def foo(x):
+ x[0] = 1
+
+ self._check(foo, sig=(types.int32[:],), expect=False)
+
+ def test_debuginfo_in_asm(self):
+ @cuda.jit(debug=True, opt=False)
+ def foo(x):
+ x[0] = 1
+
+ self._check(foo, sig=(types.int32[:],), expect=True)
+
+ def test_environment_override(self):
+ with override_config('CUDA_DEBUGINFO_DEFAULT', 1):
+ # Using default value
+ @cuda.jit(opt=False)
+ def foo(x):
+ x[0] = 1
+
+ self._check(foo, sig=(types.int32[:],), expect=True)
+
+ # User override default value
+ @cuda.jit(debug=False)
+ def bar(x):
+ x[0] = 1
+
+ self._check(bar, sig=(types.int32[:],), expect=False)
+
+ def test_issue_5835(self):
+ # Invalid debug metadata would segfault NVVM when any function was
+ # compiled with debug turned on and optimization off. This eager
+ # compilation should not crash anything.
+ @cuda.jit((types.int32[::1],), debug=True, opt=False)
+ def f(x):
+ x[0] = 0
+
+ def test_wrapper_has_debuginfo(self):
+ sig = (types.int32[::1],)
+
+ @cuda.jit(sig, debug=True, opt=0)
+ def f(x):
+ x[0] = 1
+
+ llvm_ir = f.inspect_llvm(sig)
+
+ defines = [line for line in llvm_ir.splitlines()
+ if 'define void @"_ZN6cudapy' in line]
+
+ # Make sure we only found one definition
+ self.assertEqual(len(defines), 1)
+
+ wrapper_define = defines[0]
+ self.assertIn('!dbg', wrapper_define)
+
+ def test_debug_function_calls_internal_impl(self):
+ # Calling a function in a module generated from an implementation
+ # internal to Numba requires multiple modules to be compiled with NVVM -
+ # the internal implementation, and the caller. This example uses two
+ # modules because the `in (2, 3)` is implemented with:
+ #
+ # numba::cpython::listobj::in_seq::$3clocals$3e::seq_contains_impl$242(
+ # UniTuple,
+ # int
+ # )
+ #
+ # This is condensed from this reproducer in Issue 5311:
+ # https://github.com/numba/numba/issues/5311#issuecomment-674206587
+
+ @cuda.jit((types.int32[:], types.int32[:]), debug=True, opt=False)
+ def f(inp, outp):
+ outp[0] = 1 if inp[0] in (2, 3) else 3
+
+ def test_debug_function_calls_device_function(self):
+ # Calling a device function requires compilation of multiple modules
+ # with NVVM - one for the caller and one for the callee. This checks
+ # that we don't cause an NVVM error in this case.
+
+ @cuda.jit(device=True, debug=True, opt=0)
+ def threadid():
+ return cuda.blockDim.x * cuda.blockIdx.x + cuda.threadIdx.x
+
+ @cuda.jit((types.int32[:],), debug=True, opt=0)
+ def kernel(arr):
+ i = cuda.grid(1)
+ if i < len(arr):
+ arr[i] = threadid()
+
+ def _test_chained_device_function(self, kernel_debug, f1_debug, f2_debug):
+ @cuda.jit(device=True, debug=f2_debug, opt=False)
+ def f2(x):
+ return x + 1
+
+ @cuda.jit(device=True, debug=f1_debug, opt=False)
+ def f1(x, y):
+ return x - f2(y)
+
+ @cuda.jit((types.int32, types.int32), debug=kernel_debug, opt=False)
+ def kernel(x, y):
+ f1(x, y)
+
+ kernel[1, 1](1, 2)
+
+ def test_chained_device_function(self):
+ # Calling a device function that calls another device function from a
+ # kernel with should succeed regardless of which jit decorators have
+ # debug=True. See Issue #7159.
+
+ debug_opts = itertools.product(*[(True, False)] * 3)
+
+ for kernel_debug, f1_debug, f2_debug in debug_opts:
+ with self.subTest(kernel_debug=kernel_debug,
+ f1_debug=f1_debug,
+ f2_debug=f2_debug):
+ self._test_chained_device_function(kernel_debug,
+ f1_debug,
+ f2_debug)
+
+ def _test_chained_device_function_two_calls(self, kernel_debug, f1_debug,
+ f2_debug):
+
+ @cuda.jit(device=True, debug=f2_debug, opt=False)
+ def f2(x):
+ return x + 1
+
+ @cuda.jit(device=True, debug=f1_debug, opt=False)
+ def f1(x, y):
+ return x - f2(y)
+
+ @cuda.jit(debug=kernel_debug, opt=False)
+ def kernel(x, y):
+ f1(x, y)
+ f2(x)
+
+ kernel[1, 1](1, 2)
+
+ def test_chained_device_function_two_calls(self):
+ # Calling a device function that calls a leaf device function from a
+ # kernel, and calling the leaf device function from the kernel should
+ # succeed, regardless of which jit decorators have debug=True. See
+ # Issue #7159.
+
+ debug_opts = itertools.product(*[(True, False)] * 3)
+
+ for kernel_debug, f1_debug, f2_debug in debug_opts:
+ with self.subTest(kernel_debug=kernel_debug,
+ f1_debug=f1_debug,
+ f2_debug=f2_debug):
+ self._test_chained_device_function_two_calls(kernel_debug,
+ f1_debug,
+ f2_debug)
+
+ def test_chained_device_three_functions(self):
+ # Like test_chained_device_function, but with enough functions (three)
+ # to ensure that the recursion visits all the way down the call tree
+ # when fixing linkage of functions for debug.
+ def three_device_fns(kernel_debug, leaf_debug):
+ @cuda.jit(device=True, debug=leaf_debug, opt=False)
+ def f3(x):
+ return x * x
+
+ @cuda.jit(device=True)
+ def f2(x):
+ return f3(x) + 1
+
+ @cuda.jit(device=True)
+ def f1(x, y):
+ return x - f2(y)
+
+ @cuda.jit(debug=kernel_debug, opt=False)
+ def kernel(x, y):
+ f1(x, y)
+
+ kernel[1, 1](1, 2)
+
+ # Check when debug on the kernel, on the leaf, and not on any function.
+ three_device_fns(kernel_debug=True, leaf_debug=True)
+ three_device_fns(kernel_debug=True, leaf_debug=False)
+ three_device_fns(kernel_debug=False, leaf_debug=True)
+ three_device_fns(kernel_debug=False, leaf_debug=False)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_device_func.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_device_func.py
new file mode 100644
index 0000000000000000000000000000000000000000..5583aa5e253f5a5d60e5e5bfe15d10f20429cd7c
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_device_func.py
@@ -0,0 +1,222 @@
+import re
+import types
+
+import numpy as np
+
+from numba.cuda.testing import unittest, skip_on_cudasim, CUDATestCase
+from numba import cuda, jit, float32, int32
+from numba.core.errors import TypingError
+
+
+class TestDeviceFunc(CUDATestCase):
+
+ def test_use_add2f(self):
+
+ @cuda.jit("float32(float32, float32)", device=True)
+ def add2f(a, b):
+ return a + b
+
+ def use_add2f(ary):
+ i = cuda.grid(1)
+ ary[i] = add2f(ary[i], ary[i])
+
+ compiled = cuda.jit("void(float32[:])")(use_add2f)
+
+ nelem = 10
+ ary = np.arange(nelem, dtype=np.float32)
+ exp = ary + ary
+ compiled[1, nelem](ary)
+
+ self.assertTrue(np.all(ary == exp), (ary, exp))
+
+ def test_indirect_add2f(self):
+
+ @cuda.jit("float32(float32, float32)", device=True)
+ def add2f(a, b):
+ return a + b
+
+ @cuda.jit("float32(float32, float32)", device=True)
+ def indirect(a, b):
+ return add2f(a, b)
+
+ def indirect_add2f(ary):
+ i = cuda.grid(1)
+ ary[i] = indirect(ary[i], ary[i])
+
+ compiled = cuda.jit("void(float32[:])")(indirect_add2f)
+
+ nelem = 10
+ ary = np.arange(nelem, dtype=np.float32)
+ exp = ary + ary
+ compiled[1, nelem](ary)
+
+ self.assertTrue(np.all(ary == exp), (ary, exp))
+
+ def _check_cpu_dispatcher(self, add):
+ @cuda.jit
+ def add_kernel(ary):
+ i = cuda.grid(1)
+ ary[i] = add(ary[i], 1)
+
+ ary = np.arange(10)
+ expect = ary + 1
+ add_kernel[1, ary.size](ary)
+ np.testing.assert_equal(expect, ary)
+
+ def test_cpu_dispatcher(self):
+ # Test correct usage
+ @jit
+ def add(a, b):
+ return a + b
+
+ self._check_cpu_dispatcher(add)
+
+ @skip_on_cudasim('not supported in cudasim')
+ def test_cpu_dispatcher_invalid(self):
+ # Test invalid usage
+ # Explicit signature disables compilation, which also disable
+ # compiling on CUDA.
+ @jit('(i4, i4)')
+ def add(a, b):
+ return a + b
+
+ # Check that the right error message is provided.
+ with self.assertRaises(TypingError) as raises:
+ self._check_cpu_dispatcher(add)
+ msg = "Untyped global name 'add':.*using cpu function on device"
+ expected = re.compile(msg)
+ self.assertTrue(expected.search(str(raises.exception)) is not None)
+
+ def test_cpu_dispatcher_other_module(self):
+ @jit
+ def add(a, b):
+ return a + b
+
+ mymod = types.ModuleType(name='mymod')
+ mymod.add = add
+ del add
+
+ @cuda.jit
+ def add_kernel(ary):
+ i = cuda.grid(1)
+ ary[i] = mymod.add(ary[i], 1)
+
+ ary = np.arange(10)
+ expect = ary + 1
+ add_kernel[1, ary.size](ary)
+ np.testing.assert_equal(expect, ary)
+
+ @skip_on_cudasim('not supported in cudasim')
+ def test_inspect_llvm(self):
+ @cuda.jit(device=True)
+ def foo(x, y):
+ return x + y
+
+ args = (int32, int32)
+ cres = foo.compile_device(args)
+
+ fname = cres.fndesc.mangled_name
+ # Verify that the function name has "foo" in it as in the python name
+ self.assertIn('foo', fname)
+
+ llvm = foo.inspect_llvm(args)
+ # Check that the compiled function name is in the LLVM.
+ self.assertIn(fname, llvm)
+
+ @skip_on_cudasim('not supported in cudasim')
+ def test_inspect_asm(self):
+ @cuda.jit(device=True)
+ def foo(x, y):
+ return x + y
+
+ args = (int32, int32)
+ cres = foo.compile_device(args)
+
+ fname = cres.fndesc.mangled_name
+ # Verify that the function name has "foo" in it as in the python name
+ self.assertIn('foo', fname)
+
+ ptx = foo.inspect_asm(args)
+ # Check that the compiled function name is in the PTX
+ self.assertIn(fname, ptx)
+
+ @skip_on_cudasim('not supported in cudasim')
+ def test_inspect_sass_disallowed(self):
+ @cuda.jit(device=True)
+ def foo(x, y):
+ return x + y
+
+ with self.assertRaises(RuntimeError) as raises:
+ foo.inspect_sass((int32, int32))
+
+ self.assertIn('Cannot inspect SASS of a device function',
+ str(raises.exception))
+
+ @skip_on_cudasim('cudasim will allow calling any function')
+ def test_device_func_as_kernel_disallowed(self):
+ @cuda.jit(device=True)
+ def f():
+ pass
+
+ with self.assertRaises(RuntimeError) as raises:
+ f[1, 1]()
+
+ self.assertIn('Cannot compile a device function as a kernel',
+ str(raises.exception))
+
+ @skip_on_cudasim('cudasim ignores casting by jit decorator signature')
+ def test_device_casting(self):
+ # Ensure that casts to the correct type are forced when calling a
+ # device function with a signature. This test ensures that:
+ #
+ # - We don't compile a new specialization of rgba for float32 when we
+ # shouldn't
+ # - We insert a cast when calling rgba, as opposed to failing to type.
+
+ @cuda.jit('int32(int32, int32, int32, int32)', device=True)
+ def rgba(r, g, b, a):
+ return (((r & 0xFF) << 16) |
+ ((g & 0xFF) << 8) |
+ ((b & 0xFF) << 0) |
+ ((a & 0xFF) << 24))
+
+ @cuda.jit
+ def rgba_caller(x, channels):
+ x[0] = rgba(channels[0], channels[1], channels[2], channels[3])
+
+ x = cuda.device_array(1, dtype=np.int32)
+ channels = cuda.to_device(np.asarray([1.0, 2.0, 3.0, 4.0],
+ dtype=np.float32))
+
+ rgba_caller[1, 1](x, channels)
+
+ self.assertEqual(0x04010203, x[0])
+
+ def _test_declare_device(self, decl):
+ self.assertEqual(decl.name, 'f1')
+ self.assertEqual(decl.sig.args, (float32[:],))
+ self.assertEqual(decl.sig.return_type, int32)
+
+ @skip_on_cudasim('cudasim does not check signatures')
+ def test_declare_device_signature(self):
+ f1 = cuda.declare_device('f1', int32(float32[:]))
+ self._test_declare_device(f1)
+
+ @skip_on_cudasim('cudasim does not check signatures')
+ def test_declare_device_string(self):
+ f1 = cuda.declare_device('f1', 'int32(float32[:])')
+ self._test_declare_device(f1)
+
+ @skip_on_cudasim('cudasim does not check signatures')
+ def test_bad_declare_device_tuple(self):
+ with self.assertRaisesRegex(TypeError, 'Return type'):
+ cuda.declare_device('f1', (float32[:],))
+
+ @skip_on_cudasim('cudasim does not check signatures')
+ def test_bad_declare_device_string(self):
+ with self.assertRaisesRegex(TypeError, 'Return type'):
+ cuda.declare_device('f1', '(float32[:],)')
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_dispatcher.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_dispatcher.py
new file mode 100644
index 0000000000000000000000000000000000000000..da5257699a2088d2ade94ae70fd11cfd2c550f09
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_dispatcher.py
@@ -0,0 +1,700 @@
+import numpy as np
+import threading
+
+from numba import boolean, config, cuda, float32, float64, int32, int64, void
+from numba.core.errors import TypingError
+from numba.cuda.testing import skip_on_cudasim, unittest, CUDATestCase
+import math
+
+
+def add(x, y):
+ return x + y
+
+
+def add_kernel(r, x, y):
+ r[0] = x + y
+
+
+@skip_on_cudasim('Specialization not implemented in the simulator')
+class TestDispatcherSpecialization(CUDATestCase):
+ def _test_no_double_specialize(self, dispatcher, ty):
+
+ with self.assertRaises(RuntimeError) as e:
+ dispatcher.specialize(ty)
+
+ self.assertIn('Dispatcher already specialized', str(e.exception))
+
+ def test_no_double_specialize_sig_same_types(self):
+ # Attempting to specialize a kernel jitted with a signature is illegal,
+ # even for the same types the kernel is already specialized for.
+ @cuda.jit('void(float32[::1])')
+ def f(x):
+ pass
+
+ self._test_no_double_specialize(f, float32[::1])
+
+ def test_no_double_specialize_no_sig_same_types(self):
+ # Attempting to specialize an already-specialized kernel is illegal,
+ # even for the same types the kernel is already specialized for.
+ @cuda.jit
+ def f(x):
+ pass
+
+ f_specialized = f.specialize(float32[::1])
+ self._test_no_double_specialize(f_specialized, float32[::1])
+
+ def test_no_double_specialize_sig_diff_types(self):
+ # Attempting to specialize a kernel jitted with a signature is illegal.
+ @cuda.jit('void(int32[::1])')
+ def f(x):
+ pass
+
+ self._test_no_double_specialize(f, float32[::1])
+
+ def test_no_double_specialize_no_sig_diff_types(self):
+ # Attempting to specialize an already-specialized kernel is illegal.
+ @cuda.jit
+ def f(x):
+ pass
+
+ f_specialized = f.specialize(int32[::1])
+ self._test_no_double_specialize(f_specialized, float32[::1])
+
+ def test_specialize_cache_same(self):
+ # Ensure that the same dispatcher is returned for the same argument
+ # types, and that different dispatchers are returned for different
+ # argument types.
+ @cuda.jit
+ def f(x):
+ pass
+
+ self.assertEqual(len(f.specializations), 0)
+
+ f_float32 = f.specialize(float32[::1])
+ self.assertEqual(len(f.specializations), 1)
+
+ f_float32_2 = f.specialize(float32[::1])
+ self.assertEqual(len(f.specializations), 1)
+ self.assertIs(f_float32, f_float32_2)
+
+ f_int32 = f.specialize(int32[::1])
+ self.assertEqual(len(f.specializations), 2)
+ self.assertIsNot(f_int32, f_float32)
+
+ def test_specialize_cache_same_with_ordering(self):
+ # Ensure that the same dispatcher is returned for the same argument
+ # types, and that different dispatchers are returned for different
+ # argument types, taking into account array ordering and multiple
+ # arguments.
+ @cuda.jit
+ def f(x, y):
+ pass
+
+ self.assertEqual(len(f.specializations), 0)
+
+ # 'A' order specialization
+ f_f32a_f32a = f.specialize(float32[:], float32[:])
+ self.assertEqual(len(f.specializations), 1)
+
+ # 'C' order specialization
+ f_f32c_f32c = f.specialize(float32[::1], float32[::1])
+ self.assertEqual(len(f.specializations), 2)
+ self.assertIsNot(f_f32a_f32a, f_f32c_f32c)
+
+ # Reuse 'C' order specialization
+ f_f32c_f32c_2 = f.specialize(float32[::1], float32[::1])
+ self.assertEqual(len(f.specializations), 2)
+ self.assertIs(f_f32c_f32c, f_f32c_f32c_2)
+
+
+class TestDispatcher(CUDATestCase):
+ """Most tests based on those in numba.tests.test_dispatcher."""
+
+ def test_coerce_input_types(self):
+ # Do not allow unsafe conversions if we can still compile other
+ # specializations.
+ c_add = cuda.jit(add_kernel)
+
+ # Using a complex128 allows us to represent any result produced by the
+ # test
+ r = np.zeros(1, dtype=np.complex128)
+
+ c_add[1, 1](r, 123, 456)
+ self.assertEqual(r[0], add(123, 456))
+
+ c_add[1, 1](r, 12.3, 45.6)
+ self.assertEqual(r[0], add(12.3, 45.6))
+
+ c_add[1, 1](r, 12.3, 45.6j)
+ self.assertEqual(r[0], add(12.3, 45.6j))
+
+ c_add[1, 1](r, 12300000000, 456)
+ self.assertEqual(r[0], add(12300000000, 456))
+
+ # Now force compilation of only a single specialization
+ c_add = cuda.jit('(i4[::1], i4, i4)')(add_kernel)
+ r = np.zeros(1, dtype=np.int32)
+
+ c_add[1, 1](r, 123, 456)
+ self.assertPreciseEqual(r[0], add(123, 456))
+
+ @skip_on_cudasim('Simulator ignores signature')
+ @unittest.expectedFailure
+ def test_coerce_input_types_unsafe(self):
+ # Implicit (unsafe) conversion of float to int, originally from
+ # test_coerce_input_types. This test presently fails with the CUDA
+ # Dispatcher because argument preparation is done by
+ # _Kernel._prepare_args, which is currently inflexible with respect to
+ # the types it can accept when preparing.
+ #
+ # This test is marked as xfail until future changes enable this
+ # behavior.
+ c_add = cuda.jit('(i4[::1], i4, i4)')(add_kernel)
+ r = np.zeros(1, dtype=np.int32)
+
+ c_add[1, 1](r, 12.3, 45.6)
+ self.assertPreciseEqual(r[0], add(12, 45))
+
+ @skip_on_cudasim('Simulator ignores signature')
+ def test_coerce_input_types_unsafe_complex(self):
+ # Implicit conversion of complex to int disallowed
+ c_add = cuda.jit('(i4[::1], i4, i4)')(add_kernel)
+ r = np.zeros(1, dtype=np.int32)
+
+ with self.assertRaises(TypeError):
+ c_add[1, 1](r, 12.3, 45.6j)
+
+ @skip_on_cudasim('Simulator does not track overloads')
+ def test_ambiguous_new_version(self):
+ """Test compiling new version in an ambiguous case
+ """
+ c_add = cuda.jit(add_kernel)
+
+ r = np.zeros(1, dtype=np.float64)
+ INT = 1
+ FLT = 1.5
+
+ c_add[1, 1](r, INT, FLT)
+ self.assertAlmostEqual(r[0], INT + FLT)
+ self.assertEqual(len(c_add.overloads), 1)
+
+ c_add[1, 1](r, FLT, INT)
+ self.assertAlmostEqual(r[0], FLT + INT)
+ self.assertEqual(len(c_add.overloads), 2)
+
+ c_add[1, 1](r, FLT, FLT)
+ self.assertAlmostEqual(r[0], FLT + FLT)
+ self.assertEqual(len(c_add.overloads), 3)
+
+ # The following call is ambiguous because (int, int) can resolve
+ # to (float, int) or (int, float) with equal weight.
+ c_add[1, 1](r, 1, 1)
+ self.assertAlmostEqual(r[0], INT + INT)
+ self.assertEqual(len(c_add.overloads), 4, "didn't compile a new "
+ "version")
+
+ @skip_on_cudasim("Simulator doesn't support concurrent kernels")
+ def test_lock(self):
+ """
+ Test that (lazy) compiling from several threads at once doesn't
+ produce errors (see issue #908).
+ """
+ errors = []
+
+ @cuda.jit
+ def foo(r, x):
+ r[0] = x + 1
+
+ def wrapper():
+ try:
+ r = np.zeros(1, dtype=np.int64)
+ foo[1, 1](r, 1)
+ self.assertEqual(r[0], 2)
+ except Exception as e:
+ errors.append(e)
+
+ threads = [threading.Thread(target=wrapper) for i in range(16)]
+ for t in threads:
+ t.start()
+ for t in threads:
+ t.join()
+ self.assertFalse(errors)
+
+ def _test_explicit_signatures(self, sigs):
+ f = cuda.jit(sigs)(add_kernel)
+
+ # Exact signature matches
+ r = np.zeros(1, dtype=np.int64)
+ f[1, 1](r, 1, 2)
+ self.assertPreciseEqual(r[0], 3)
+
+ r = np.zeros(1, dtype=np.float64)
+ f[1, 1](r, 1.5, 2.5)
+ self.assertPreciseEqual(r[0], 4.0)
+
+ if config.ENABLE_CUDASIM:
+ # Pass - we can't check for no conversion on the simulator.
+ return
+
+ # No conversion
+ with self.assertRaises(TypeError) as cm:
+ r = np.zeros(1, dtype=np.complex128)
+ f[1, 1](r, 1j, 1j)
+ self.assertIn("No matching definition", str(cm.exception))
+ self.assertEqual(len(f.overloads), 2, f.overloads)
+
+ def test_explicit_signatures_strings(self):
+ # Check with a list of strings for signatures
+ sigs = ["(int64[::1], int64, int64)",
+ "(float64[::1], float64, float64)"]
+ self._test_explicit_signatures(sigs)
+
+ def test_explicit_signatures_tuples(self):
+ # Check with a list of tuples of argument types for signatures
+ sigs = [(int64[::1], int64, int64), (float64[::1], float64, float64)]
+ self._test_explicit_signatures(sigs)
+
+ def test_explicit_signatures_signatures(self):
+ # Check with a list of Signature objects for signatures
+ sigs = [void(int64[::1], int64, int64),
+ void(float64[::1], float64, float64)]
+ self._test_explicit_signatures(sigs)
+
+ def test_explicit_signatures_mixed(self):
+ # Check when we mix types of signature objects in a list of signatures
+
+ # Tuple and string
+ sigs = [(int64[::1], int64, int64),
+ "(float64[::1], float64, float64)"]
+ self._test_explicit_signatures(sigs)
+
+ # Tuple and Signature object
+ sigs = [(int64[::1], int64, int64),
+ void(float64[::1], float64, float64)]
+ self._test_explicit_signatures(sigs)
+
+ # Signature object and string
+ sigs = [void(int64[::1], int64, int64),
+ "(float64[::1], float64, float64)"]
+ self._test_explicit_signatures(sigs)
+
+ def test_explicit_signatures_same_type_class(self):
+ # A more interesting one...
+ # (Note that the type of r is deliberately float64 in both cases so
+ # that dispatch is differentiated on the types of x and y only, to
+ # closely preserve the intent of the original test from
+ # numba.tests.test_dispatcher)
+ sigs = ["(float64[::1], float32, float32)",
+ "(float64[::1], float64, float64)"]
+ f = cuda.jit(sigs)(add_kernel)
+
+ r = np.zeros(1, dtype=np.float64)
+ f[1, 1](r, np.float32(1), np.float32(2**-25))
+ self.assertPreciseEqual(r[0], 1.0)
+
+ r = np.zeros(1, dtype=np.float64)
+ f[1, 1](r, 1, 2**-25)
+ self.assertPreciseEqual(r[0], 1.0000000298023224)
+
+ @skip_on_cudasim('No overload resolution in the simulator')
+ def test_explicit_signatures_ambiguous_resolution(self):
+ # Fail to resolve ambiguity between the two best overloads
+ # (Also deliberate float64[::1] for the first argument in all cases)
+ f = cuda.jit(["(float64[::1], float32, float64)",
+ "(float64[::1], float64, float32)",
+ "(float64[::1], int64, int64)"])(add_kernel)
+ with self.assertRaises(TypeError) as cm:
+ r = np.zeros(1, dtype=np.float64)
+ f[1, 1](r, 1.0, 2.0)
+
+ # The two best matches are output in the error message, as well
+ # as the actual argument types.
+ self.assertRegex(
+ str(cm.exception),
+ r"Ambiguous overloading for ]*> "
+ r"\(Array\(float64, 1, 'C', False, aligned=True\), float64,"
+ r" float64\):\n"
+ r"\(Array\(float64, 1, 'C', False, aligned=True\), float32,"
+ r" float64\) -> none\n"
+ r"\(Array\(float64, 1, 'C', False, aligned=True\), float64,"
+ r" float32\) -> none"
+ )
+ # The integer signature is not part of the best matches
+ self.assertNotIn("int64", str(cm.exception))
+
+ @skip_on_cudasim('Simulator does not use _prepare_args')
+ @unittest.expectedFailure
+ def test_explicit_signatures_unsafe(self):
+ # These tests are from test_explicit_signatures, but have to be xfail
+ # at present because _prepare_args in the CUDA target cannot handle
+ # unsafe conversions of arguments.
+ f = cuda.jit("(int64[::1], int64, int64)")(add_kernel)
+ r = np.zeros(1, dtype=np.int64)
+
+ # Approximate match (unsafe conversion)
+ f[1, 1](r, 1.5, 2.5)
+ self.assertPreciseEqual(r[0], 3)
+ self.assertEqual(len(f.overloads), 1, f.overloads)
+
+ sigs = ["(int64[::1], int64, int64)",
+ "(float64[::1], float64, float64)"]
+ f = cuda.jit(sigs)(add_kernel)
+ r = np.zeros(1, dtype=np.float64)
+ # Approximate match (int32 -> float64 is a safe conversion)
+ f[1, 1](r, np.int32(1), 2.5)
+ self.assertPreciseEqual(r[0], 3.5)
+
+ def add_device_usecase(self, sigs):
+ # Generate a kernel that calls the add device function compiled with a
+ # given set of signatures
+ add_device = cuda.jit(sigs, device=True)(add)
+
+ @cuda.jit
+ def f(r, x, y):
+ r[0] = add_device(x, y)
+
+ return f
+
+ def test_explicit_signatures_device(self):
+ # Tests similar to test_explicit_signatures, but on a device function
+ # instead of a kernel
+ sigs = ["(int64, int64)", "(float64, float64)"]
+ f = self.add_device_usecase(sigs)
+
+ # Exact signature matches
+ r = np.zeros(1, dtype=np.int64)
+ f[1, 1](r, 1, 2)
+ self.assertPreciseEqual(r[0], 3)
+
+ r = np.zeros(1, dtype=np.float64)
+ f[1, 1](r, 1.5, 2.5)
+ self.assertPreciseEqual(r[0], 4.0)
+
+ if config.ENABLE_CUDASIM:
+ # Pass - we can't check for no conversion on the simulator.
+ return
+
+ # No conversion
+ with self.assertRaises(TypingError) as cm:
+ r = np.zeros(1, dtype=np.complex128)
+ f[1, 1](r, 1j, 1j)
+
+ msg = str(cm.exception)
+ self.assertIn("Invalid use of type", msg)
+ self.assertIn("with parameters (complex128, complex128)", msg)
+ self.assertEqual(len(f.overloads), 2, f.overloads)
+
+ def test_explicit_signatures_device_same_type_class(self):
+ # A more interesting one...
+ # (Note that the type of r is deliberately float64 in both cases so
+ # that dispatch is differentiated on the types of x and y only, to
+ # closely preserve the intent of the original test from
+ # numba.tests.test_dispatcher)
+ sigs = ["(float32, float32)", "(float64, float64)"]
+ f = self.add_device_usecase(sigs)
+
+ r = np.zeros(1, dtype=np.float64)
+ f[1, 1](r, np.float32(1), np.float32(2**-25))
+ self.assertPreciseEqual(r[0], 1.0)
+
+ r = np.zeros(1, dtype=np.float64)
+ f[1, 1](r, 1, 2**-25)
+ self.assertPreciseEqual(r[0], 1.0000000298023224)
+
+ def test_explicit_signatures_device_ambiguous(self):
+ # Ambiguity between the two best overloads resolves. This is somewhat
+ # surprising given that ambiguity is not permitted for dispatching
+ # overloads when launching a kernel, but seems to be the general
+ # behaviour of Numba (See Issue #8307:
+ # https://github.com/numba/numba/issues/8307).
+ sigs = ["(float32, float64)", "(float64, float32)", "(int64, int64)"]
+ f = self.add_device_usecase(sigs)
+
+ r = np.zeros(1, dtype=np.float64)
+ f[1, 1](r, 1.5, 2.5)
+ self.assertPreciseEqual(r[0], 4.0)
+
+ @skip_on_cudasim('CUDA Simulator does not force casting')
+ def test_explicit_signatures_device_unsafe(self):
+ # These tests are from test_explicit_signatures. The device function
+ # variant of these tests can succeed on CUDA because the compilation
+ # can handle unsafe casting (c.f. test_explicit_signatures_unsafe which
+ # has to xfail due to _prepare_args not supporting unsafe casting).
+ sigs = ["(int64, int64)"]
+ f = self.add_device_usecase(sigs)
+
+ # Approximate match (unsafe conversion)
+ r = np.zeros(1, dtype=np.int64)
+ f[1, 1](r, 1.5, 2.5)
+ self.assertPreciseEqual(r[0], 3)
+ self.assertEqual(len(f.overloads), 1, f.overloads)
+
+ sigs = ["(int64, int64)", "(float64, float64)"]
+ f = self.add_device_usecase(sigs)
+
+ # Approximate match (int32 -> float64 is a safe conversion)
+ r = np.zeros(1, dtype=np.float64)
+ f[1, 1](r, np.int32(1), 2.5)
+ self.assertPreciseEqual(r[0], 3.5)
+
+ def test_dispatcher_docstring(self):
+ # Ensure that CUDA-jitting a function preserves its docstring. See
+ # Issue #5902: https://github.com/numba/numba/issues/5902
+
+ @cuda.jit
+ def add_kernel(a, b):
+ """Add two integers, kernel version"""
+
+ @cuda.jit(device=True)
+ def add_device(a, b):
+ """Add two integers, device version"""
+
+ self.assertEqual("Add two integers, kernel version", add_kernel.__doc__)
+ self.assertEqual("Add two integers, device version", add_device.__doc__)
+
+
+@skip_on_cudasim("CUDA simulator doesn't implement kernel properties")
+class TestDispatcherKernelProperties(CUDATestCase):
+ def test_get_regs_per_thread_unspecialized(self):
+ # A kernel where the register usage per thread is likely to differ
+ # between different specializations
+ @cuda.jit
+ def pi_sin_array(x, n):
+ i = cuda.grid(1)
+ if i < n:
+ x[i] = 3.14 * math.sin(x[i])
+
+ # Call the kernel with different arguments to create two different
+ # definitions within the Dispatcher object
+ N = 10
+ arr_f32 = np.zeros(N, dtype=np.float32)
+ arr_f64 = np.zeros(N, dtype=np.float64)
+
+ pi_sin_array[1, N](arr_f32, N)
+ pi_sin_array[1, N](arr_f64, N)
+
+ # Check we get a positive integer for the two different variations
+ sig_f32 = void(float32[::1], int64)
+ sig_f64 = void(float64[::1], int64)
+ regs_per_thread_f32 = pi_sin_array.get_regs_per_thread(sig_f32)
+ regs_per_thread_f64 = pi_sin_array.get_regs_per_thread(sig_f64)
+
+ self.assertIsInstance(regs_per_thread_f32, int)
+ self.assertIsInstance(regs_per_thread_f64, int)
+
+ self.assertGreater(regs_per_thread_f32, 0)
+ self.assertGreater(regs_per_thread_f64, 0)
+
+ # Check that getting the registers per thread for all signatures
+ # provides the same values as getting the registers per thread for
+ # individual signatures.
+ regs_per_thread_all = pi_sin_array.get_regs_per_thread()
+ self.assertEqual(regs_per_thread_all[sig_f32.args],
+ regs_per_thread_f32)
+ self.assertEqual(regs_per_thread_all[sig_f64.args],
+ regs_per_thread_f64)
+
+ if regs_per_thread_f32 == regs_per_thread_f64:
+ # If the register usage is the same for both variants, there may be
+ # a bug, but this may also be an artifact of the compiler / driver
+ # / device combination, so produce an informational message only.
+ print('f32 and f64 variant thread usages are equal.')
+ print('This may warrant some investigation. Devices:')
+ cuda.detect()
+
+ def test_get_regs_per_thread_specialized(self):
+ @cuda.jit(void(float32[::1], int64))
+ def pi_sin_array(x, n):
+ i = cuda.grid(1)
+ if i < n:
+ x[i] = 3.14 * math.sin(x[i])
+
+ # Check we get a positive integer for the specialized variation
+ regs_per_thread = pi_sin_array.get_regs_per_thread()
+ self.assertIsInstance(regs_per_thread, int)
+ self.assertGreater(regs_per_thread, 0)
+
+ def test_get_const_mem_unspecialized(self):
+ @cuda.jit
+ def const_fmt_string(val, to_print):
+ # We guard the print with a conditional to prevent noise from the
+ # test suite
+ if to_print:
+ print(val)
+
+ # Call the kernel with different arguments to create two different
+ # definitions within the Dispatcher object
+ const_fmt_string[1, 1](1, False)
+ const_fmt_string[1, 1](1.0, False)
+
+ # Check we get a positive integer for the two different variations
+ sig_i64 = void(int64, boolean)
+ sig_f64 = void(float64, boolean)
+ const_mem_size_i64 = const_fmt_string.get_const_mem_size(sig_i64)
+ const_mem_size_f64 = const_fmt_string.get_const_mem_size(sig_f64)
+
+ self.assertIsInstance(const_mem_size_i64, int)
+ self.assertIsInstance(const_mem_size_f64, int)
+
+ # 6 bytes for the equivalent of b'%lld\n\0'
+ self.assertGreaterEqual(const_mem_size_i64, 6)
+ # 4 bytes for the equivalent of b'%f\n\0'
+ self.assertGreaterEqual(const_mem_size_f64, 4)
+
+ # Check that getting the const memory size for all signatures
+ # provides the same values as getting the const memory size for
+ # individual signatures.
+
+ const_mem_size_all = const_fmt_string.get_const_mem_size()
+ self.assertEqual(const_mem_size_all[sig_i64.args], const_mem_size_i64)
+ self.assertEqual(const_mem_size_all[sig_f64.args], const_mem_size_f64)
+
+ def test_get_const_mem_specialized(self):
+ arr = np.arange(32, dtype=np.int64)
+ sig = void(int64[::1])
+
+ @cuda.jit(sig)
+ def const_array_use(x):
+ C = cuda.const.array_like(arr)
+ i = cuda.grid(1)
+ x[i] = C[i]
+
+ const_mem_size = const_array_use.get_const_mem_size(sig)
+ self.assertIsInstance(const_mem_size, int)
+ self.assertGreaterEqual(const_mem_size, arr.nbytes)
+
+ def test_get_shared_mem_per_block_unspecialized(self):
+ N = 10
+
+ # A kernel where the shared memory per block is likely to differ
+ # between different specializations
+ @cuda.jit
+ def simple_smem(ary):
+ sm = cuda.shared.array(N, dtype=ary.dtype)
+ for j in range(N):
+ sm[j] = j
+ for j in range(N):
+ ary[j] = sm[j]
+
+ # Call the kernel with different arguments to create two different
+ # definitions within the Dispatcher object
+ arr_f32 = np.zeros(N, dtype=np.float32)
+ arr_f64 = np.zeros(N, dtype=np.float64)
+
+ simple_smem[1, 1](arr_f32)
+ simple_smem[1, 1](arr_f64)
+
+ sig_f32 = void(float32[::1])
+ sig_f64 = void(float64[::1])
+
+ sh_mem_f32 = simple_smem.get_shared_mem_per_block(sig_f32)
+ sh_mem_f64 = simple_smem.get_shared_mem_per_block(sig_f64)
+
+ self.assertIsInstance(sh_mem_f32, int)
+ self.assertIsInstance(sh_mem_f64, int)
+
+ self.assertEqual(sh_mem_f32, N * 4)
+ self.assertEqual(sh_mem_f64, N * 8)
+
+ # Check that getting the shared memory per block for all signatures
+ # provides the same values as getting the shared mem per block for
+ # individual signatures.
+ sh_mem_f32_all = simple_smem.get_shared_mem_per_block()
+ sh_mem_f64_all = simple_smem.get_shared_mem_per_block()
+ self.assertEqual(sh_mem_f32_all[sig_f32.args], sh_mem_f32)
+ self.assertEqual(sh_mem_f64_all[sig_f64.args], sh_mem_f64)
+
+ def test_get_shared_mem_per_block_specialized(self):
+ @cuda.jit(void(float32[::1]))
+ def simple_smem(ary):
+ sm = cuda.shared.array(100, dtype=float32)
+ i = cuda.grid(1)
+ if i == 0:
+ for j in range(100):
+ sm[j] = j
+ cuda.syncthreads()
+ ary[i] = sm[i]
+
+ shared_mem_per_block = simple_smem.get_shared_mem_per_block()
+ self.assertIsInstance(shared_mem_per_block, int)
+ self.assertEqual(shared_mem_per_block, 400)
+
+ def test_get_max_threads_per_block_unspecialized(self):
+ N = 10
+
+ @cuda.jit
+ def simple_maxthreads(ary):
+ i = cuda.grid(1)
+ ary[i] = i
+
+ arr_f32 = np.zeros(N, dtype=np.float32)
+ simple_maxthreads[1, 1](arr_f32)
+ sig_f32 = void(float32[::1])
+ max_threads_f32 = simple_maxthreads.get_max_threads_per_block(sig_f32)
+
+ self.assertIsInstance(max_threads_f32, int)
+ self.assertGreater(max_threads_f32, 0)
+
+ max_threads_f32_all = simple_maxthreads.get_max_threads_per_block()
+ self.assertEqual(max_threads_f32_all[sig_f32.args], max_threads_f32)
+
+ def test_get_local_mem_per_thread_unspecialized(self):
+ # NOTE: A large amount of local memory must be allocated
+ # otherwise the compiler will optimize out the call to
+ # cuda.local.array and use local registers instead
+ N = 1000
+
+ @cuda.jit
+ def simple_lmem(ary):
+ lm = cuda.local.array(N, dtype=ary.dtype)
+ for j in range(N):
+ lm[j] = j
+ for j in range(N):
+ ary[j] = lm[j]
+
+ # Call the kernel with different arguments to create two different
+ # definitions within the Dispatcher object
+ arr_f32 = np.zeros(N, dtype=np.float32)
+ arr_f64 = np.zeros(N, dtype=np.float64)
+
+ simple_lmem[1, 1](arr_f32)
+ simple_lmem[1, 1](arr_f64)
+
+ sig_f32 = void(float32[::1])
+ sig_f64 = void(float64[::1])
+ local_mem_f32 = simple_lmem.get_local_mem_per_thread(sig_f32)
+ local_mem_f64 = simple_lmem.get_local_mem_per_thread(sig_f64)
+ self.assertIsInstance(local_mem_f32, int)
+ self.assertIsInstance(local_mem_f64, int)
+
+ self.assertGreaterEqual(local_mem_f32, N * 4)
+ self.assertGreaterEqual(local_mem_f64, N * 8)
+
+ # Check that getting the local memory per thread for all signatures
+ # provides the same values as getting the shared mem per block for
+ # individual signatures.
+ local_mem_all = simple_lmem.get_local_mem_per_thread()
+ self.assertEqual(local_mem_all[sig_f32.args], local_mem_f32)
+ self.assertEqual(local_mem_all[sig_f64.args], local_mem_f64)
+
+ def test_get_local_mem_per_thread_specialized(self):
+ # NOTE: A large amount of local memory must be allocated
+ # otherwise the compiler will optimize out the call to
+ # cuda.local.array and use local registers instead
+ N = 1000
+
+ @cuda.jit(void(float32[::1]))
+ def simple_lmem(ary):
+ lm = cuda.local.array(N, dtype=ary.dtype)
+ for j in range(N):
+ lm[j] = j
+ for j in range(N):
+ ary[j] = lm[j]
+
+ local_mem_per_thread = simple_lmem.get_local_mem_per_thread()
+ self.assertIsInstance(local_mem_per_thread, int)
+ self.assertGreaterEqual(local_mem_per_thread, N * 4)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_enums.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_enums.py
new file mode 100644
index 0000000000000000000000000000000000000000..da60b75651312d8566a652eadecfdea5b5e85cbe
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_enums.py
@@ -0,0 +1,121 @@
+"""
+Test cases adapted from numba/tests/test_enums.py
+"""
+
+import numpy as np
+
+from numba import int16, int32
+from numba import cuda, vectorize, njit
+from numba.cuda.testing import unittest, CUDATestCase, skip_on_cudasim
+from numba.tests.enum_usecases import (
+ Color,
+ Shape,
+ Planet,
+ RequestError,
+ IntEnumWithNegatives
+)
+
+
+class EnumTest(CUDATestCase):
+
+ pairs = [
+ (Color.red, Color.red),
+ (Color.red, Color.green),
+ (Planet.EARTH, Planet.EARTH),
+ (Planet.VENUS, Planet.MARS),
+ (Shape.circle, IntEnumWithNegatives.two) # IntEnum, same value
+ ]
+
+ def test_compare(self):
+ def f(a, b, out):
+ out[0] = a == b
+ out[1] = a != b
+ out[2] = a is b
+ out[3] = a is not b
+
+ cuda_f = cuda.jit(f)
+ for a, b in self.pairs:
+ got = np.zeros((4,), dtype=np.bool_)
+ expected = got.copy()
+ cuda_f[1, 1](a, b, got)
+ f(a, b, expected)
+ self.assertPreciseEqual(expected, got)
+
+ def test_getattr_getitem(self):
+ def f(out):
+ # Lookup of an enum member on its class
+ out[0] = Color.red == Color.green
+ out[1] = Color['red'] == Color['green']
+
+ cuda_f = cuda.jit(f)
+ got = np.zeros((2,), dtype=np.bool_)
+ expected = got.copy()
+ cuda_f[1, 1](got)
+ f(expected)
+ self.assertPreciseEqual(expected, got)
+
+ def test_return_from_device_func(self):
+ @njit
+ def inner(pred):
+ return Color.red if pred else Color.green
+
+ def f(pred, out):
+ out[0] = inner(pred) == Color.red
+ out[1] = inner(not pred) == Color.green
+
+ cuda_f = cuda.jit(f)
+ got = np.zeros((2,), dtype=np.bool_)
+ expected = got.copy()
+ f(True, expected)
+ cuda_f[1, 1](True, got)
+ self.assertPreciseEqual(expected, got)
+
+ def test_int_coerce(self):
+ def f(x, out):
+ # Implicit coercion of intenums to ints
+ if x > RequestError.internal_error:
+ out[0] = x - RequestError.not_found
+ else:
+ out[0] = x + Shape.circle
+
+ cuda_f = cuda.jit(f)
+ for x in [300, 450, 550]:
+ got = np.zeros((1,), dtype=np.int32)
+ expected = got.copy()
+ cuda_f[1, 1](x, got)
+ f(x, expected)
+ self.assertPreciseEqual(expected, got)
+
+ def test_int_cast(self):
+ def f(x, out):
+ # Explicit coercion of intenums to ints
+ if x > int16(RequestError.internal_error):
+ out[0] = x - int32(RequestError.not_found)
+ else:
+ out[0] = x + int16(Shape.circle)
+
+ cuda_f = cuda.jit(f)
+ for x in [300, 450, 550]:
+ got = np.zeros((1,), dtype=np.int32)
+ expected = got.copy()
+ cuda_f[1, 1](x, got)
+ f(x, expected)
+ self.assertEqual(expected, got)
+
+ @skip_on_cudasim("ufuncs are unsupported on simulator.")
+ def test_vectorize(self):
+ def f(x):
+ if x != RequestError.not_found:
+ return RequestError['internal_error']
+ else:
+ return RequestError.dummy
+
+ cuda_func = vectorize("int64(int64)", target='cuda')(f)
+ arr = np.array([2, 404, 500, 404], dtype=np.int64)
+ expected = np.array([f(x) for x in arr], dtype=np.int64)
+ got = cuda_func(arr)
+ self.assertPreciseEqual(expected, got)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_errors.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_errors.py
new file mode 100644
index 0000000000000000000000000000000000000000..c20fb8dccdf844ead9e4b46a3651b54a40b9efde
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_errors.py
@@ -0,0 +1,79 @@
+from numba import cuda
+from numba.core.errors import TypingError
+from numba.cuda.testing import unittest, CUDATestCase, skip_on_cudasim
+
+
+def noop(x):
+ pass
+
+
+class TestJitErrors(CUDATestCase):
+ """
+ Test compile-time errors with @jit.
+ """
+
+ def test_too_many_dims(self):
+ kernfunc = cuda.jit(noop)
+
+ with self.assertRaises(ValueError) as raises:
+ kernfunc[(1, 2, 3, 4), (5, 6)]
+ self.assertIn("griddim must be a sequence of 1, 2 or 3 integers, "
+ "got [1, 2, 3, 4]",
+ str(raises.exception))
+
+ with self.assertRaises(ValueError) as raises:
+ kernfunc[(1, 2,), (3, 4, 5, 6)]
+ self.assertIn("blockdim must be a sequence of 1, 2 or 3 integers, "
+ "got [3, 4, 5, 6]",
+ str(raises.exception))
+
+ def test_non_integral_dims(self):
+ kernfunc = cuda.jit(noop)
+
+ with self.assertRaises(TypeError) as raises:
+ kernfunc[2.0, 3]
+ self.assertIn("griddim must be a sequence of integers, got [2.0]",
+ str(raises.exception))
+
+ with self.assertRaises(TypeError) as raises:
+ kernfunc[2, 3.0]
+ self.assertIn("blockdim must be a sequence of integers, got [3.0]",
+ str(raises.exception))
+
+ def _test_unconfigured(self, kernfunc):
+ with self.assertRaises(ValueError) as raises:
+ kernfunc(0)
+ self.assertIn("launch configuration was not specified",
+ str(raises.exception))
+
+ def test_unconfigured_typed_cudakernel(self):
+ kernfunc = cuda.jit("void(int32)")(noop)
+ self._test_unconfigured(kernfunc)
+
+ def test_unconfigured_untyped_cudakernel(self):
+ kernfunc = cuda.jit(noop)
+ self._test_unconfigured(kernfunc)
+
+ @skip_on_cudasim('TypingError does not occur on simulator')
+ def test_typing_error(self):
+ # see #5860, this is present to catch changes to error reporting
+ # accidentally breaking the CUDA target
+
+ @cuda.jit(device=True)
+ def dev_func(x):
+ # floor is deliberately not imported for the purpose of this test.
+ return floor(x) # noqa: F821
+
+ @cuda.jit
+ def kernel_func():
+ dev_func(1.5)
+
+ with self.assertRaises(TypingError) as raises:
+ kernel_func[1, 1]()
+ excstr = str(raises.exception)
+ self.assertIn("resolving callee type: type(CUDADispatcher", excstr)
+ self.assertIn("NameError: name 'floor' is not defined", excstr)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_exception.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_exception.py
new file mode 100644
index 0000000000000000000000000000000000000000..8891010410c9db97439eb460142b4ae4e7724fbe
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_exception.py
@@ -0,0 +1,174 @@
+import numpy as np
+
+from numba import cuda
+from numba.cuda.testing import unittest, xfail_unless_cudasim, CUDATestCase
+from numba.core import config
+
+
+class TestException(CUDATestCase):
+ def setUp(self):
+ super().setUp()
+ # LTO optimizes away the exception status due to an oversight
+ # in the way we generate it (it is not added to the used list).
+ self.skip_if_lto("Exceptions not supported with LTO")
+
+ def test_exception(self):
+ def foo(ary):
+ x = cuda.threadIdx.x
+ if x == 2:
+ # NOTE: indexing with a out-of-bounds constant can fail at
+ # compile-time instead (because the getitem is rewritten as a
+ # static_getitem)
+ ary.shape[-x]
+
+ unsafe_foo = cuda.jit(foo)
+ safe_foo = cuda.jit(debug=True, opt=False)(foo)
+
+ if not config.ENABLE_CUDASIM:
+ # Simulator throws exceptions regardless of debug
+ # setting
+ unsafe_foo[1, 3](np.array([0, 1]))
+
+ with self.assertRaises(IndexError) as cm:
+ safe_foo[1, 3](np.array([0, 1]))
+ self.assertIn("tuple index out of range", str(cm.exception))
+
+ def test_user_raise(self):
+ @cuda.jit(debug=True, opt=False)
+ def foo(do_raise):
+ if do_raise:
+ raise ValueError
+
+ foo[1, 1](False)
+ with self.assertRaises(ValueError):
+ foo[1, 1](True)
+
+ def case_raise_causing_warp_diverge(self, with_debug_mode):
+ """Testing issue #2655.
+
+ Exception raising code can cause the compiler to miss location
+ of unifying branch target and resulting in unexpected warp
+ divergence.
+ """
+ with_opt_mode = not with_debug_mode
+
+ @cuda.jit(debug=with_debug_mode, opt=with_opt_mode)
+ def problematic(x, y):
+ tid = cuda.threadIdx.x
+ ntid = cuda.blockDim.x
+
+ if tid > 12:
+ for i in range(ntid):
+ y[i] += x[i] // y[i]
+
+ cuda.syncthreads()
+ if tid < 17:
+ for i in range(ntid):
+ x[i] += x[i] // y[i]
+
+ @cuda.jit
+ def oracle(x, y):
+ tid = cuda.threadIdx.x
+ ntid = cuda.blockDim.x
+
+ if tid > 12:
+ for i in range(ntid):
+ if y[i] != 0:
+ y[i] += x[i] // y[i]
+
+ cuda.syncthreads()
+ if tid < 17:
+ for i in range(ntid):
+ if y[i] != 0:
+ x[i] += x[i] // y[i]
+
+ n = 32
+ got_x = 1. / (np.arange(n) + 0.01)
+ got_y = 1. / (np.arange(n) + 0.01)
+ problematic[1, n](got_x, got_y)
+
+ expect_x = 1. / (np.arange(n) + 0.01)
+ expect_y = 1. / (np.arange(n) + 0.01)
+ oracle[1, n](expect_x, expect_y)
+
+ np.testing.assert_almost_equal(expect_x, got_x)
+ np.testing.assert_almost_equal(expect_y, got_y)
+
+ def test_raise_causing_warp_diverge(self):
+ """Test case for issue #2655.
+ """
+ self.case_raise_causing_warp_diverge(with_debug_mode=False)
+
+ # The following two cases relate to Issue #7806: Division by zero stops the
+ # kernel. https://github.com/numba/numba/issues/7806.
+
+ def test_no_zero_division_error(self):
+ # When debug is False:
+ # - Division by zero raises no exception
+ # - Execution proceeds after a divide by zero
+ @cuda.jit
+ def f(r, x, y):
+ r[0] = y[0] / x[0]
+ r[1] = y[0]
+
+ r = np.zeros(2)
+ x = np.zeros(1)
+ y = np.ones(1)
+
+ f[1, 1](r, x, y)
+
+ self.assertTrue(np.isinf(r[0]), 'Expected inf from div by zero')
+ self.assertEqual(r[1], y[0], 'Expected execution to continue')
+
+ def test_zero_division_error_in_debug(self):
+ # When debug is True:
+ # - Zero by division raises an exception
+ # - Execution halts at the point of division by zero
+ @cuda.jit(debug=True, opt=False)
+ def f(r, x, y):
+ r[0] = y[0] / x[0]
+ r[1] = y[0]
+
+ r = np.zeros(2)
+ x = np.zeros(1)
+ y = np.ones(1)
+
+ # Simulator and device behaviour differs slightly in the exception
+ # raised - in debug mode, the CUDA target uses the Python error model,
+ # which gives a ZeroDivision error. The simulator uses NumPy with the
+ # error mode for division by zero set to raise, which results in a
+ # FloatingPointError instead.
+ if config.ENABLE_CUDASIM:
+ exc = FloatingPointError
+ else:
+ exc = ZeroDivisionError
+
+ with self.assertRaises(exc):
+ f[1, 1](r, x, y)
+
+ self.assertEqual(r[0], 0, 'Expected result to be left unset')
+ self.assertEqual(r[1], 0, 'Expected execution to stop')
+
+ @xfail_unless_cudasim
+ def test_raise_in_device_function(self):
+ # This is an expected failure because reporting of exceptions raised in
+ # device functions does not work correctly - see Issue #8036:
+ # https://github.com/numba/numba/issues/8036
+ msg = 'Device Function Error'
+
+ @cuda.jit(device=True)
+ def f():
+ raise ValueError(msg)
+
+ @cuda.jit(debug=True)
+ def kernel():
+ f()
+
+ with self.assertRaises(ValueError) as raises:
+ kernel[1, 1]()
+
+ self.assertIn(msg, str(raises.exception))
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_extending.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_extending.py
new file mode 100644
index 0000000000000000000000000000000000000000..142d917c0cec9bf224c653aafffc60fc3653e0a6
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_extending.py
@@ -0,0 +1,155 @@
+from numba.cuda.testing import skip_on_cudasim, unittest, CUDATestCase
+
+import numpy as np
+from numba import config, cuda, njit, types
+
+
+class Interval:
+ """
+ A half-open interval on the real number line.
+ """
+ def __init__(self, lo, hi):
+ self.lo = lo
+ self.hi = hi
+
+ def __repr__(self):
+ return 'Interval(%f, %f)' % (self.lo, self.hi)
+
+ @property
+ def width(self):
+ return self.hi - self.lo
+
+
+@njit
+def interval_width(interval):
+ return interval.width
+
+
+@njit
+def sum_intervals(i, j):
+ return Interval(i.lo + j.lo, i.hi + j.hi)
+
+
+if not config.ENABLE_CUDASIM:
+ from numba.core import cgutils
+ from numba.core.extending import (lower_builtin, make_attribute_wrapper,
+ models, register_model, type_callable,
+ typeof_impl)
+ from numba.core.typing.templates import AttributeTemplate
+ from numba.cuda.cudadecl import registry as cuda_registry
+ from numba.cuda.cudaimpl import lower_attr as cuda_lower_attr
+
+ class IntervalType(types.Type):
+ def __init__(self):
+ super().__init__(name='Interval')
+
+ interval_type = IntervalType()
+
+ @typeof_impl.register(Interval)
+ def typeof_interval(val, c):
+ return interval_type
+
+ @type_callable(Interval)
+ def type_interval(context):
+ def typer(lo, hi):
+ if isinstance(lo, types.Float) and isinstance(hi, types.Float):
+ return interval_type
+ return typer
+
+ @register_model(IntervalType)
+ class IntervalModel(models.StructModel):
+ def __init__(self, dmm, fe_type):
+ members = [
+ ('lo', types.float64),
+ ('hi', types.float64),
+ ]
+ models.StructModel.__init__(self, dmm, fe_type, members)
+
+ make_attribute_wrapper(IntervalType, 'lo', 'lo')
+ make_attribute_wrapper(IntervalType, 'hi', 'hi')
+
+ @lower_builtin(Interval, types.Float, types.Float)
+ def impl_interval(context, builder, sig, args):
+ typ = sig.return_type
+ lo, hi = args
+ interval = cgutils.create_struct_proxy(typ)(context, builder)
+ interval.lo = lo
+ interval.hi = hi
+ return interval._getvalue()
+
+ @cuda_registry.register_attr
+ class Interval_attrs(AttributeTemplate):
+ key = IntervalType
+
+ def resolve_width(self, mod):
+ return types.float64
+
+ @cuda_lower_attr(IntervalType, 'width')
+ def cuda_Interval_width(context, builder, sig, arg):
+ lo = builder.extract_value(arg, 0)
+ hi = builder.extract_value(arg, 1)
+ return builder.fsub(hi, lo)
+
+
+@skip_on_cudasim('Extensions not supported in the simulator')
+class TestExtending(CUDATestCase):
+ def test_attributes(self):
+ @cuda.jit
+ def f(r, x):
+ iv = Interval(x[0], x[1])
+ r[0] = iv.lo
+ r[1] = iv.hi
+
+ x = np.asarray((1.5, 2.5))
+ r = np.zeros_like(x)
+
+ f[1, 1](r, x)
+
+ np.testing.assert_equal(r, x)
+
+ def test_property(self):
+ @cuda.jit
+ def f(r, x):
+ iv = Interval(x[0], x[1])
+ r[0] = iv.width
+
+ x = np.asarray((1.5, 2.5))
+ r = np.zeros(1)
+
+ f[1, 1](r, x)
+
+ np.testing.assert_allclose(r[0], x[1] - x[0])
+
+ def test_extension_type_as_arg(self):
+ @cuda.jit
+ def f(r, x):
+ iv = Interval(x[0], x[1])
+ r[0] = interval_width(iv)
+
+ x = np.asarray((1.5, 2.5))
+ r = np.zeros(1)
+
+ f[1, 1](r, x)
+
+ np.testing.assert_allclose(r[0], x[1] - x[0])
+
+ def test_extension_type_as_retvalue(self):
+ @cuda.jit
+ def f(r, x):
+ iv1 = Interval(x[0], x[1])
+ iv2 = Interval(x[2], x[3])
+ iv_sum = sum_intervals(iv1, iv2)
+ r[0] = iv_sum.lo
+ r[1] = iv_sum.hi
+
+ x = np.asarray((1.5, 2.5, 3.0, 4.0))
+ r = np.zeros(2)
+
+ f[1, 1](r, x)
+
+ expected = np.asarray((x[0] + x[2], x[1] + x[3]))
+ np.testing.assert_allclose(r, expected)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_fastmath.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_fastmath.py
new file mode 100644
index 0000000000000000000000000000000000000000..75d24eb88ea6bf8dacb95f9f4036f769eddc84a1
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_fastmath.py
@@ -0,0 +1,244 @@
+from typing import List
+from dataclasses import dataclass, field
+from numba import cuda, float32
+from numba.cuda.compiler import compile_ptx_for_current_device, compile_ptx
+from math import cos, sin, tan, exp, log, log10, log2, pow, tanh
+from operator import truediv
+import numpy as np
+from numba.cuda.testing import (CUDATestCase, skip_on_cudasim,
+ skip_unless_cc_75)
+import unittest
+
+
+@dataclass
+class FastMathCriterion:
+ fast_expected: List[str] = field(default_factory=list)
+ fast_unexpected: List[str] = field(default_factory=list)
+ prec_expected: List[str] = field(default_factory=list)
+ prec_unexpected: List[str] = field(default_factory=list)
+
+ def check(self, test: CUDATestCase, fast: str, prec: str):
+ test.assertTrue(all(i in fast for i in self.fast_expected))
+ test.assertTrue(all(i not in fast for i in self.fast_unexpected))
+ test.assertTrue(all(i in prec for i in self.prec_expected))
+ test.assertTrue(all(i not in prec for i in self.prec_unexpected))
+
+
+@skip_on_cudasim('Fastmath and PTX inspection not available on cudasim')
+class TestFastMathOption(CUDATestCase):
+ def _test_fast_math_common(self, pyfunc, sig, device, criterion):
+
+ # Test jit code path
+ fastver = cuda.jit(sig, device=device, fastmath=True)(pyfunc)
+ precver = cuda.jit(sig, device=device)(pyfunc)
+
+ criterion.check(
+ self, fastver.inspect_asm(sig), precver.inspect_asm(sig)
+ )
+
+ # Test compile_ptx code path
+ fastptx, _ = compile_ptx_for_current_device(
+ pyfunc, sig, device=device, fastmath=True
+ )
+ precptx, _ = compile_ptx_for_current_device(
+ pyfunc, sig, device=device
+ )
+
+ criterion.check(self, fastptx, precptx)
+
+ def _test_fast_math_unary(self, op, criterion: FastMathCriterion):
+ def kernel(r, x):
+ r[0] = op(x)
+
+ def device_function(x):
+ return op(x)
+
+ self._test_fast_math_common(
+ kernel, (float32[::1], float32), device=False, criterion=criterion
+ )
+ self._test_fast_math_common(
+ device_function, (float32,), device=True, criterion=criterion
+ )
+
+ def _test_fast_math_binary(self, op, criterion: FastMathCriterion):
+ def kernel(r, x, y):
+ r[0] = op(x, y)
+
+ def device(x, y):
+ return op(x, y)
+
+ self._test_fast_math_common(
+ kernel,
+ (float32[::1], float32, float32), device=False, criterion=criterion
+ )
+ self._test_fast_math_common(
+ device, (float32, float32), device=True, criterion=criterion
+ )
+
+ def test_cosf(self):
+ self._test_fast_math_unary(
+ cos,
+ FastMathCriterion(
+ fast_expected=['cos.approx.ftz.f32 '],
+ prec_unexpected=['cos.approx.ftz.f32 ']
+ )
+ )
+
+ def test_sinf(self):
+ self._test_fast_math_unary(
+ sin,
+ FastMathCriterion(
+ fast_expected=['sin.approx.ftz.f32 '],
+ prec_unexpected=['sin.approx.ftz.f32 ']
+ )
+ )
+
+ def test_tanf(self):
+ self._test_fast_math_unary(
+ tan,
+ FastMathCriterion(fast_expected=[
+ 'sin.approx.ftz.f32 ',
+ 'cos.approx.ftz.f32 ',
+ 'div.approx.ftz.f32 '
+ ], prec_unexpected=['sin.approx.ftz.f32 '])
+ )
+
+ @skip_unless_cc_75
+ def test_tanhf(self):
+
+ self._test_fast_math_unary(
+ tanh,
+ FastMathCriterion(
+ fast_expected=['tanh.approx.f32 '],
+ prec_unexpected=['tanh.approx.f32 ']
+ )
+ )
+
+ def test_tanhf_compile_ptx(self):
+ def tanh_kernel(r, x):
+ r[0] = tanh(x)
+
+ def tanh_common_test(cc, criterion):
+ fastptx, _ = compile_ptx(tanh_kernel, (float32[::1], float32),
+ fastmath=True, cc=cc)
+ precptx, _ = compile_ptx(tanh_kernel, (float32[::1], float32),
+ cc=cc)
+ criterion.check(self, fastptx, precptx)
+
+ tanh_common_test(cc=(7, 5), criterion=FastMathCriterion(
+ fast_expected=['tanh.approx.f32 '],
+ prec_unexpected=['tanh.approx.f32 ']
+ ))
+
+ tanh_common_test(cc=(7, 0),
+ criterion=FastMathCriterion(
+ fast_expected=['ex2.approx.ftz.f32 ',
+ 'rcp.approx.ftz.f32 '],
+ prec_unexpected=['tanh.approx.f32 ']))
+
+ def test_expf(self):
+ self._test_fast_math_unary(
+ exp,
+ FastMathCriterion(
+ fast_unexpected=['fma.rn.f32 '],
+ prec_expected=['fma.rn.f32 ']
+ )
+ )
+
+ def test_logf(self):
+ # Look for constant used to convert from log base 2 to log base e
+ self._test_fast_math_unary(
+ log, FastMathCriterion(
+ fast_expected=['lg2.approx.ftz.f32 ', '0f3F317218'],
+ prec_unexpected=['lg2.approx.ftz.f32 '],
+ )
+ )
+
+ def test_log10f(self):
+ # Look for constant used to convert from log base 2 to log base 10
+ self._test_fast_math_unary(
+ log10, FastMathCriterion(
+ fast_expected=['lg2.approx.ftz.f32 ', '0f3E9A209B'],
+ prec_unexpected=['lg2.approx.ftz.f32 ']
+ )
+ )
+
+ def test_log2f(self):
+ self._test_fast_math_unary(
+ log2, FastMathCriterion(
+ fast_expected=['lg2.approx.ftz.f32 '],
+ prec_unexpected=['lg2.approx.ftz.f32 ']
+ )
+ )
+
+ def test_powf(self):
+ self._test_fast_math_binary(
+ pow, FastMathCriterion(
+ fast_expected=['lg2.approx.ftz.f32 '],
+ prec_unexpected=['lg2.approx.ftz.f32 '],
+ )
+ )
+
+ def test_divf(self):
+ self._test_fast_math_binary(
+ truediv, FastMathCriterion(
+ fast_expected=['div.approx.ftz.f32 '],
+ fast_unexpected=['div.rn.f32'],
+ prec_expected=['div.rn.f32'],
+ prec_unexpected=['div.approx.ftz.f32 '],
+ )
+ )
+
+ def test_divf_exception(self):
+ # LTO optimizes away the exception status due to an oversight
+ # in the way we generate it (it is not added to the used list).
+ self.skip_if_lto("Exceptions not supported with LTO")
+
+ def f10(r, x, y):
+ r[0] = x / y
+
+ sig = (float32[::1], float32, float32)
+ fastver = cuda.jit(sig, fastmath=True, debug=True)(f10)
+ precver = cuda.jit(sig, debug=True)(f10)
+ nelem = 10
+ ary = np.empty(nelem, dtype=np.float32)
+ with self.assertRaises(ZeroDivisionError):
+ precver[1, nelem](ary, 10.0, 0.0)
+
+ try:
+ fastver[1, nelem](ary, 10.0, 0.0)
+ except ZeroDivisionError:
+ self.fail("Divide in fastmath should not throw ZeroDivisionError")
+
+ @unittest.expectedFailure
+ def test_device_fastmath_propagation(self):
+ # The fastmath option doesn't presently propagate to device functions
+ # from their callees - arguably it should do, so this test is presently
+ # an xfail.
+ @cuda.jit("float32(float32, float32)", device=True)
+ def foo(a, b):
+ return a / b
+
+ def bar(arr, val):
+ i = cuda.grid(1)
+ if i < arr.size:
+ arr[i] = foo(i, val)
+
+ sig = (float32[::1], float32)
+ fastver = cuda.jit(sig, fastmath=True)(bar)
+ precver = cuda.jit(sig)(bar)
+
+ # Variants of the div instruction are further documented at:
+ # https://docs.nvidia.com/cuda/parallel-thread-execution/index.html#floating-point-instructions-div
+
+ # The fast version should use the "fast, approximate divide" variant
+ self.assertIn('div.approx.f32', fastver.inspect_asm(sig))
+ # The precise version should use the "IEEE 754 compliant rounding"
+ # variant, and neither of the "approximate divide" variants.
+ self.assertIn('div.rn.f32', precver.inspect_asm(sig))
+ self.assertNotIn('div.approx.f32', precver.inspect_asm(sig))
+ self.assertNotIn('div.full.f32', precver.inspect_asm(sig))
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_forall.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_forall.py
new file mode 100644
index 0000000000000000000000000000000000000000..23286c22cc82be6813f96536f810c0d03bdafad5
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_forall.py
@@ -0,0 +1,52 @@
+import numpy as np
+
+from numba import cuda
+import unittest
+from numba.cuda.testing import CUDATestCase
+
+
+@cuda.jit
+def foo(x):
+ i = cuda.grid(1)
+ if i < x.size:
+ x[i] += 1
+
+
+class TestForAll(CUDATestCase):
+ def test_forall_1(self):
+ arr = np.arange(11)
+ orig = arr.copy()
+ foo.forall(arr.size)(arr)
+ np.testing.assert_array_almost_equal(arr, orig + 1)
+
+ def test_forall_2(self):
+ @cuda.jit("void(float32, float32[:], float32[:])")
+ def bar(a, x, y):
+ i = cuda.grid(1)
+ if i < x.size:
+ y[i] = a * x[i] + y[i]
+
+ x = np.arange(13, dtype=np.float32)
+ y = np.arange(13, dtype=np.float32)
+ oldy = y.copy()
+ a = 1.234
+ bar.forall(y.size)(a, x, y)
+ np.testing.assert_array_almost_equal(y, a * x + oldy, decimal=3)
+
+ def test_forall_no_work(self):
+ # Ensure that forall doesn't launch a kernel with no blocks when called
+ # with 0 elements. See Issue #5017.
+ arr = np.arange(11)
+ foo.forall(0)(arr)
+
+ def test_forall_negative_work(self):
+ # Ensure that forall doesn't allow the creation of a forall with a
+ # negative element count.
+ with self.assertRaises(ValueError) as raises:
+ foo.forall(-1)
+ self.assertIn("Can't create ForAll with negative task count",
+ str(raises.exception))
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_freevar.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_freevar.py
new file mode 100644
index 0000000000000000000000000000000000000000..6b7b2d2abcc6a55558a2c7142809fa7571a9fde6
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_freevar.py
@@ -0,0 +1,29 @@
+import numpy as np
+
+from numba import cuda
+from numba.cuda.testing import unittest, CUDATestCase
+
+
+class TestFreeVar(CUDATestCase):
+ def test_freevar(self):
+ """Make sure we can compile the following kernel with freevar reference
+ in arguments to shared.array
+ """
+ from numba import float32
+
+ size = 1024
+ nbtype = float32
+
+ @cuda.jit("(float32[::1], intp)")
+ def foo(A, i):
+ "Dummy function"
+ sdata = cuda.shared.array(size, # size is freevar
+ dtype=nbtype) # nbtype is freevar
+ A[i] = sdata[i]
+
+ A = np.arange(2, dtype="float32")
+ foo[1, 1](A, 0)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_frexp_ldexp.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_frexp_ldexp.py
new file mode 100644
index 0000000000000000000000000000000000000000..71169801ee98e0f54135210271458a7ffd477a6d
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_frexp_ldexp.py
@@ -0,0 +1,66 @@
+import numpy as np
+import math
+from numba import cuda
+from numba.types import float32, float64, int32, void
+from numba.cuda.testing import unittest, CUDATestCase
+
+
+def simple_frexp(aryx, aryexp, arg):
+ aryx[0], aryexp[0] = math.frexp(arg)
+
+
+def simple_ldexp(aryx, arg, exp):
+ aryx[0] = math.ldexp(arg, exp)
+
+
+class TestCudaFrexpLdexp(CUDATestCase):
+ def template_test_frexp(self, nptype, nbtype):
+ compiled = cuda.jit(void(nbtype[:], int32[:], nbtype))(simple_frexp)
+ arg = 3.1415
+ aryx = np.zeros(1, dtype=nptype)
+ aryexp = np.zeros(1, dtype=np.int32)
+ compiled[1, 1](aryx, aryexp, arg)
+ np.testing.assert_array_equal(aryx, nptype(0.785375))
+ self.assertEqual(aryexp, 2)
+
+ arg = np.inf
+ compiled[1, 1](aryx, aryexp, arg)
+ np.testing.assert_array_equal(aryx, nptype(np.inf))
+ self.assertEqual(aryexp, 0) # np.frexp gives -1
+
+ arg = np.nan
+ compiled[1, 1](aryx, aryexp, arg)
+ np.testing.assert_array_equal(aryx, nptype(np.nan))
+ self.assertEqual(aryexp, 0) # np.frexp gives -1
+
+ def template_test_ldexp(self, nptype, nbtype):
+ compiled = cuda.jit(void(nbtype[:], nbtype, int32))(simple_ldexp)
+ arg = 0.785375
+ exp = 2
+ aryx = np.zeros(1, dtype=nptype)
+ compiled[1, 1](aryx, arg, exp)
+ np.testing.assert_array_equal(aryx, nptype(3.1415))
+
+ arg = np.inf
+ compiled[1, 1](aryx, arg, exp)
+ np.testing.assert_array_equal(aryx, nptype(np.inf))
+
+ arg = np.nan
+ compiled[1, 1](aryx, arg, exp)
+ np.testing.assert_array_equal(aryx, nptype(np.nan))
+
+ def test_frexp_f4(self):
+ self.template_test_frexp(np.float32, float32)
+
+ def test_ldexp_f4(self):
+ self.template_test_ldexp(np.float32, float32)
+
+ def test_frexp_f8(self):
+ self.template_test_frexp(np.float64, float64)
+
+ def test_ldexp_f8(self):
+ self.template_test_ldexp(np.float64, float64)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_globals.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_globals.py
new file mode 100644
index 0000000000000000000000000000000000000000..a2406e6652710b6c5c62513a77c95d197c1e3ff2
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_globals.py
@@ -0,0 +1,60 @@
+import numpy as np
+from numba import cuda, int32, float32
+from numba.cuda.testing import unittest, CUDATestCase
+
+N = 100
+
+
+def simple_smem(ary):
+ sm = cuda.shared.array(N, int32)
+ i = cuda.grid(1)
+ if i == 0:
+ for j in range(N):
+ sm[j] = j
+ cuda.syncthreads()
+ ary[i] = sm[i]
+
+
+S0 = 10
+S1 = 20
+
+
+def coop_smem2d(ary):
+ i, j = cuda.grid(2)
+ sm = cuda.shared.array((S0, S1), float32)
+ sm[i, j] = (i + 1) / (j + 1)
+ cuda.syncthreads()
+ ary[i, j] = sm[i, j]
+
+
+class TestCudaTestGlobal(CUDATestCase):
+ def test_global_int_const(self):
+ """Test simple_smem
+ """
+ compiled = cuda.jit("void(int32[:])")(simple_smem)
+
+ nelem = 100
+ ary = np.empty(nelem, dtype=np.int32)
+ compiled[1, nelem](ary)
+
+ self.assertTrue(np.all(ary == np.arange(nelem, dtype=np.int32)))
+
+ @unittest.SkipTest
+ def test_global_tuple_const(self):
+ """Test coop_smem2d
+ """
+ compiled = cuda.jit("void(float32[:,:])")(coop_smem2d)
+
+ shape = 10, 20
+ ary = np.empty(shape, dtype=np.float32)
+ compiled[1, shape](ary)
+
+ exp = np.empty_like(ary)
+ for i in range(ary.shape[0]):
+ for j in range(ary.shape[1]):
+ exp[i, j] = float(i + 1) / (j + 1)
+ self.assertTrue(np.allclose(ary, exp))
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_gufunc.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_gufunc.py
new file mode 100644
index 0000000000000000000000000000000000000000..098318e3aa1127b389b7b63e3696c2005bfc7a46
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_gufunc.py
@@ -0,0 +1,456 @@
+import numpy as np
+
+from collections import namedtuple
+from numba import void, int32, float32, float64
+from numba import guvectorize
+from numba import cuda
+from numba.cuda.testing import skip_on_cudasim, CUDATestCase
+import unittest
+import warnings
+from numba.core.errors import NumbaPerformanceWarning, TypingError
+from numba.tests.support import override_config
+
+
+def _get_matmulcore_gufunc(dtype=float32):
+ @guvectorize([void(dtype[:, :], dtype[:, :], dtype[:, :])],
+ '(m,n),(n,p)->(m,p)',
+ target='cuda')
+ def matmulcore(A, B, C):
+ m, n = A.shape
+ n, p = B.shape
+ for i in range(m):
+ for j in range(p):
+ C[i, j] = 0
+ for k in range(n):
+ C[i, j] += A[i, k] * B[k, j]
+
+ return matmulcore
+
+
+@skip_on_cudasim('ufunc API unsupported in the simulator')
+class TestCUDAGufunc(CUDATestCase):
+
+ def test_gufunc_small(self):
+
+ gufunc = _get_matmulcore_gufunc()
+
+ matrix_ct = 2
+ A = np.arange(matrix_ct * 2 * 4, dtype=np.float32).reshape(matrix_ct, 2,
+ 4)
+ B = np.arange(matrix_ct * 4 * 5, dtype=np.float32).reshape(matrix_ct, 4,
+ 5)
+
+ C = gufunc(A, B)
+ Gold = np.matmul(A, B)
+ self.assertTrue(np.allclose(C, Gold))
+
+ def test_gufunc_auto_transfer(self):
+
+ gufunc = _get_matmulcore_gufunc()
+
+ matrix_ct = 2
+ A = np.arange(matrix_ct * 2 * 4, dtype=np.float32).reshape(matrix_ct, 2,
+ 4)
+ B = np.arange(matrix_ct * 4 * 5, dtype=np.float32).reshape(matrix_ct, 4,
+ 5)
+
+ dB = cuda.to_device(B)
+
+ C = gufunc(A, dB).copy_to_host()
+ Gold = np.matmul(A, B)
+ self.assertTrue(np.allclose(C, Gold))
+
+ def test_gufunc(self):
+
+ gufunc = _get_matmulcore_gufunc()
+
+ matrix_ct = 1001 # an odd number to test thread/block division in CUDA
+ A = np.arange(matrix_ct * 2 * 4, dtype=np.float32).reshape(matrix_ct, 2,
+ 4)
+ B = np.arange(matrix_ct * 4 * 5, dtype=np.float32).reshape(matrix_ct, 4,
+ 5)
+
+ C = gufunc(A, B)
+ Gold = np.matmul(A, B)
+ self.assertTrue(np.allclose(C, Gold))
+
+ def test_gufunc_hidim(self):
+
+ gufunc = _get_matmulcore_gufunc()
+
+ matrix_ct = 100 # an odd number to test thread/block division in CUDA
+ A = np.arange(matrix_ct * 2 * 4, dtype=np.float32).reshape(4, 25, 2, 4)
+ B = np.arange(matrix_ct * 4 * 5, dtype=np.float32).reshape(4, 25, 4, 5)
+
+ C = gufunc(A, B)
+ Gold = np.matmul(A, B)
+ self.assertTrue(np.allclose(C, Gold))
+
+ def test_gufunc_new_axis(self):
+
+ gufunc = _get_matmulcore_gufunc(dtype=float64)
+
+ X = np.random.randn(10, 3, 3)
+ Y = np.random.randn(3, 3)
+
+ gold = np.matmul(X, Y)
+
+ res1 = gufunc(X, Y)
+ np.testing.assert_allclose(gold, res1)
+
+ res2 = gufunc(X, np.tile(Y, (10, 1, 1)))
+ np.testing.assert_allclose(gold, res2)
+
+ def test_gufunc_stream(self):
+
+ gufunc = _get_matmulcore_gufunc()
+
+ #cuda.driver.flush_pending_free()
+ matrix_ct = 1001 # an odd number to test thread/block division in CUDA
+ A = np.arange(matrix_ct * 2 * 4, dtype=np.float32).reshape(matrix_ct, 2,
+ 4)
+ B = np.arange(matrix_ct * 4 * 5, dtype=np.float32).reshape(matrix_ct, 4,
+ 5)
+
+ stream = cuda.stream()
+ dA = cuda.to_device(A, stream)
+ dB = cuda.to_device(B, stream)
+
+ dC = cuda.device_array(shape=(1001, 2, 5), dtype=A.dtype, stream=stream)
+ dC = gufunc(dA, dB, out=dC, stream=stream)
+ C = dC.copy_to_host(stream=stream)
+ stream.synchronize()
+
+ Gold = np.matmul(A, B)
+
+ self.assertTrue(np.allclose(C, Gold))
+
+ def test_copy(self):
+
+ @guvectorize([void(float32[:], float32[:])],
+ '(x)->(x)',
+ target='cuda')
+ def copy(A, B):
+ for i in range(B.size):
+ B[i] = A[i]
+
+ A = np.arange(10, dtype=np.float32) + 1
+ B = np.zeros_like(A)
+ copy(A, out=B)
+ np.testing.assert_allclose(A, B)
+
+ def test_copy_unspecified_return(self):
+ # Ensure that behaviour is correct when the return type is not
+ # specified in the signature.
+ @guvectorize([(float32[:], float32[:])],
+ '(x)->(x)',
+ target='cuda')
+ def copy(A, B):
+ for i in range(B.size):
+ B[i] = A[i]
+
+ A = np.arange(10, dtype=np.float32) + 1
+ B = np.zeros_like(A)
+ copy(A, out=B)
+ self.assertTrue(np.allclose(A, B))
+
+ def test_copy_odd(self):
+
+ @guvectorize([void(float32[:], float32[:])],
+ '(x)->(x)',
+ target='cuda')
+ def copy(A, B):
+ for i in range(B.size):
+ B[i] = A[i]
+
+ A = np.arange(11, dtype=np.float32) + 1
+ B = np.zeros_like(A)
+ copy(A, out=B)
+ self.assertTrue(np.allclose(A, B))
+
+ def test_copy2d(self):
+
+ @guvectorize([void(float32[:, :], float32[:, :])],
+ '(x, y)->(x, y)',
+ target='cuda')
+ def copy2d(A, B):
+ for x in range(B.shape[0]):
+ for y in range(B.shape[1]):
+ B[x, y] = A[x, y]
+
+ A = np.arange(30, dtype=np.float32).reshape(5, 6) + 1
+ B = np.zeros_like(A)
+ copy2d(A, out=B)
+ self.assertTrue(np.allclose(A, B))
+
+ def test_not_supported_call_from_jit(self):
+ # not supported
+ @guvectorize([void(int32[:], int32[:])],
+ '(n)->(n)', target='cuda')
+ def gufunc_copy(A, b):
+ for i in range(A.shape[0]):
+ b[i] = A[i]
+
+ @cuda.jit
+ def cuda_jit(A, b):
+ return gufunc_copy(A, b)
+
+ A = np.arange(1024 * 32).astype('int32')
+ b = np.zeros_like(A)
+ msg = "Untyped global name 'gufunc_copy'.*"
+ with self.assertRaisesRegex(TypingError, msg):
+ cuda_jit[1, 1](A, b)
+
+ # Test inefficient use of the GPU where the inputs are all mapped onto a
+ # single thread in a single block.
+ def test_inefficient_launch_configuration(self):
+ @guvectorize(['void(float32[:], float32[:], float32[:])'],
+ '(n),(n)->(n)', target='cuda')
+ def numba_dist_cuda(a, b, dist):
+ len = a.shape[0]
+ for i in range(len):
+ dist[i] = a[i] * b[i]
+
+ a = np.random.rand(1024 * 32).astype('float32')
+ b = np.random.rand(1024 * 32).astype('float32')
+ dist = np.zeros(a.shape[0]).astype('float32')
+
+ with override_config('CUDA_LOW_OCCUPANCY_WARNINGS', 1):
+ with warnings.catch_warnings(record=True) as w:
+ numba_dist_cuda(a, b, dist)
+ self.assertEqual(w[0].category, NumbaPerformanceWarning)
+ self.assertIn('Grid size', str(w[0].message))
+ self.assertIn('low occupancy', str(w[0].message))
+
+ def test_efficient_launch_configuration(self):
+ @guvectorize(['void(float32[:], float32[:], float32[:])'],
+ '(n),(n)->(n)', nopython=True, target='cuda')
+ def numba_dist_cuda2(a, b, dist):
+ len = a.shape[0]
+ for i in range(len):
+ dist[i] = a[i] * b[i]
+
+ a = np.random.rand(524288 * 2).astype('float32').\
+ reshape((524288, 2))
+ b = np.random.rand(524288 * 2).astype('float32').\
+ reshape((524288, 2))
+ dist = np.zeros_like(a)
+
+ with override_config('CUDA_LOW_OCCUPANCY_WARNINGS', 1):
+ with warnings.catch_warnings(record=True) as w:
+ numba_dist_cuda2(a, b, dist)
+ self.assertEqual(len(w), 0)
+
+ def test_nopython_flag(self):
+
+ def foo(A, B):
+ pass
+
+ # nopython = True is fine
+ guvectorize([void(float32[:], float32[:])], '(x)->(x)', target='cuda',
+ nopython=True)(foo)
+
+ # nopython = False is bad
+ with self.assertRaises(TypeError) as raises:
+ guvectorize([void(float32[:], float32[:])], '(x)->(x)',
+ target='cuda', nopython=False)(foo)
+ self.assertEqual("nopython flag must be True", str(raises.exception))
+
+ def test_invalid_flags(self):
+ # Check invalid flags
+ def foo(A, B):
+ pass
+
+ with self.assertRaises(TypeError) as raises:
+ guvectorize([void(float32[:], float32[:])], '(x)->(x)',
+ target='cuda', what1=True, ever2=False)(foo)
+ head = "The following target options are not supported:"
+ msg = str(raises.exception)
+ self.assertEqual(msg[:len(head)], head)
+ items = msg[len(head):].strip().split(',')
+ items = [i.strip("'\" ") for i in items]
+ self.assertEqual(set(['what1', 'ever2']), set(items))
+
+ def test_duplicated_output(self):
+ @guvectorize([void(float32[:], float32[:])], '(x)->(x)', target='cuda')
+ def foo(inp, out):
+ pass # intentionally empty; never executed
+
+ inp = out = np.zeros(10, dtype=np.float32)
+ with self.assertRaises(ValueError) as raises:
+ foo(inp, out, out=out)
+
+ msg = "cannot specify argument 'out' as both positional and keyword"
+ self.assertEqual(str(raises.exception), msg)
+
+ def check_tuple_arg(self, a, b):
+ @guvectorize([(float64[:], float64[:], float64[:])], '(n),(n)->()',
+ target='cuda')
+ def gu_reduce(x, y, r):
+ s = 0
+ for i in range(len(x)):
+ s += x[i] * y[i]
+ r[0] = s
+
+ r = gu_reduce(a, b)
+ expected = np.sum(np.asarray(a) * np.asarray(b), axis=1)
+ np.testing.assert_equal(expected, r)
+
+ def test_tuple_of_tuple_arg(self):
+ a = ((1.0, 2.0, 3.0),
+ (4.0, 5.0, 6.0))
+ b = ((1.5, 2.5, 3.5),
+ (4.5, 5.5, 6.5))
+ self.check_tuple_arg(a, b)
+
+ def test_tuple_of_namedtuple_arg(self):
+ Point = namedtuple('Point', ('x', 'y', 'z'))
+ a = (Point(x=1.0, y=2.0, z=3.0),
+ Point(x=4.0, y=5.0, z=6.0))
+ b = (Point(x=1.5, y=2.5, z=3.5),
+ Point(x=4.5, y=5.5, z=6.5))
+ self.check_tuple_arg(a, b)
+
+ def test_tuple_of_array_arg(self):
+ a = (np.asarray((1.0, 2.0, 3.0)),
+ np.asarray((4.0, 5.0, 6.0)))
+ b = (np.asarray((1.5, 2.5, 3.5)),
+ np.asarray((4.5, 5.5, 6.5)))
+ self.check_tuple_arg(a, b)
+
+ def test_gufunc_name(self):
+ gufunc = _get_matmulcore_gufunc()
+ self.assertEqual(gufunc.__name__, 'matmulcore')
+
+ def test_bad_return_type(self):
+ with self.assertRaises(TypeError) as te:
+ @guvectorize([int32(int32[:], int32[:])], '(m)->(m)', target='cuda')
+ def f(x, y):
+ pass
+
+ msg = str(te.exception)
+ self.assertIn('guvectorized functions cannot return values', msg)
+ self.assertIn('specifies int32 return type', msg)
+
+ def test_incorrect_number_of_pos_args(self):
+ @guvectorize([(int32[:], int32[:], int32[:])],
+ '(m),(m)->(m)', target='cuda')
+ def f(x, y, z):
+ pass
+
+ arr = np.arange(5)
+
+ # Inputs only, too few
+ with self.assertRaises(TypeError) as te:
+ f(arr)
+
+ msg = str(te.exception)
+ self.assertIn('gufunc accepts 2 positional arguments', msg)
+ self.assertIn('or 3 positional arguments', msg)
+ self.assertIn('Got 1 positional argument.', msg)
+
+ # Inputs and outputs, too many
+ with self.assertRaises(TypeError) as te:
+ f(arr, arr, arr, arr)
+
+ msg = str(te.exception)
+ self.assertIn('gufunc accepts 2 positional arguments', msg)
+ self.assertIn('or 3 positional arguments', msg)
+ self.assertIn('Got 4 positional arguments.', msg)
+
+
+@skip_on_cudasim('ufunc API unsupported in the simulator')
+class TestMultipleOutputs(CUDATestCase):
+ def test_multiple_outputs_same_type_passed_in(self):
+ @guvectorize([void(float32[:], float32[:], float32[:])],
+ '(x)->(x),(x)',
+ target='cuda')
+ def copy(A, B, C):
+ for i in range(B.size):
+ B[i] = A[i]
+ C[i] = A[i]
+
+ A = np.arange(10, dtype=np.float32) + 1
+ B = np.zeros_like(A)
+ C = np.zeros_like(A)
+ copy(A, B, C)
+ np.testing.assert_allclose(A, B)
+ np.testing.assert_allclose(A, C)
+
+ def test_multiple_outputs_distinct_values(self):
+
+ @guvectorize([void(float32[:], float32[:], float32[:])],
+ '(x)->(x),(x)',
+ target='cuda')
+ def copy_and_double(A, B, C):
+ for i in range(B.size):
+ B[i] = A[i]
+ C[i] = A[i] * 2
+
+ A = np.arange(10, dtype=np.float32) + 1
+ B = np.zeros_like(A)
+ C = np.zeros_like(A)
+ copy_and_double(A, B, C)
+ np.testing.assert_allclose(A, B)
+ np.testing.assert_allclose(A * 2, C)
+
+ def test_multiple_output_allocation(self):
+ @guvectorize([void(float32[:], float32[:], float32[:])],
+ '(x)->(x),(x)',
+ target='cuda')
+ def copy_and_double(A, B, C):
+ for i in range(B.size):
+ B[i] = A[i]
+ C[i] = A[i] * 2
+
+ A = np.arange(10, dtype=np.float32) + 1
+ B, C = copy_and_double(A)
+ np.testing.assert_allclose(A, B)
+ np.testing.assert_allclose(A * 2, C)
+
+ def test_multiple_output_dtypes(self):
+
+ @guvectorize([void(int32[:], int32[:], float64[:])],
+ '(x)->(x),(x)',
+ target='cuda')
+ def copy_and_multiply(A, B, C):
+ for i in range(B.size):
+ B[i] = A[i]
+ C[i] = A[i] * 1.5
+
+ A = np.arange(10, dtype=np.int32) + 1
+ B = np.zeros_like(A)
+ C = np.zeros_like(A, dtype=np.float64)
+ copy_and_multiply(A, B, C)
+ np.testing.assert_allclose(A, B)
+ np.testing.assert_allclose(A * np.float64(1.5), C)
+
+ def test_incorrect_number_of_pos_args(self):
+ @guvectorize([(int32[:], int32[:], int32[:], int32[:])],
+ '(m),(m)->(m),(m)', target='cuda')
+ def f(x, y, z, w):
+ pass
+
+ arr = np.arange(5)
+
+ # Inputs only, too few
+ with self.assertRaises(TypeError) as te:
+ f(arr)
+
+ msg = str(te.exception)
+ self.assertIn('gufunc accepts 2 positional arguments', msg)
+ self.assertIn('or 4 positional arguments', msg)
+ self.assertIn('Got 1 positional argument.', msg)
+
+ # Inputs and outputs, too many
+ with self.assertRaises(TypeError) as te:
+ f(arr, arr, arr, arr, arr)
+
+ msg = str(te.exception)
+ self.assertIn('gufunc accepts 2 positional arguments', msg)
+ self.assertIn('or 4 positional arguments', msg)
+ self.assertIn('Got 5 positional arguments.', msg)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_gufunc_scalar.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_gufunc_scalar.py
new file mode 100644
index 0000000000000000000000000000000000000000..493a9ceec5ec27a0ed94b428ab5b914e253d75af
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_gufunc_scalar.py
@@ -0,0 +1,159 @@
+"""Example: sum each row using guvectorize
+
+See Numpy documentation for detail about gufunc:
+ http://docs.scipy.org/doc/numpy/reference/c-api.generalized-ufuncs.html
+"""
+import numpy as np
+from numba import guvectorize, cuda
+from numba.cuda.testing import skip_on_cudasim, CUDATestCase
+import unittest
+
+
+@skip_on_cudasim('ufunc API unsupported in the simulator')
+class TestGUFuncScalar(CUDATestCase):
+ def test_gufunc_scalar_output(self):
+ # function type:
+ # - has no void return type
+ # - array argument is one dimension fewer than the source array
+ # - scalar output is passed as a 1-element array.
+ #
+ # signature: (n)->()
+ # - the function takes an array of n-element and output a scalar.
+
+ @guvectorize(['void(int32[:], int32[:])'], '(n)->()', target='cuda')
+ def sum_row(inp, out):
+ tmp = 0.
+ for i in range(inp.shape[0]):
+ tmp += inp[i]
+ out[0] = tmp
+
+ # inp is (10000, 3)
+ # out is (10000)
+ # The outer (leftmost) dimension must match or numpy broadcasting
+ # is performed. But, broadcasting on CUDA arrays is not supported.
+
+ inp = np.arange(300, dtype=np.int32).reshape(100, 3)
+
+ # invoke on CUDA with manually managed memory
+ out1 = np.empty(100, dtype=inp.dtype)
+ out2 = np.empty(100, dtype=inp.dtype)
+
+ dev_inp = cuda.to_device(
+ inp) # alloc and copy input data
+ dev_out1 = cuda.to_device(out1, copy=False) # alloc only
+
+ sum_row(dev_inp, out=dev_out1) # invoke the gufunc
+ dev_out2 = sum_row(dev_inp) # invoke the gufunc
+
+ dev_out1.copy_to_host(out1) # retrieve the result
+ dev_out2.copy_to_host(out2) # retrieve the result
+
+ # verify result
+ for i in range(inp.shape[0]):
+ self.assertTrue(out1[i] == inp[i].sum())
+ self.assertTrue(out2[i] == inp[i].sum())
+
+ def test_gufunc_scalar_output_bug(self):
+ # Issue 2812: Error due to using input argument types as output argument
+ @guvectorize(['void(int32, int32[:])'], '()->()', target='cuda')
+ def twice(inp, out):
+ out[0] = inp * 2
+
+ self.assertEqual(twice(10), 20)
+ arg = np.arange(10).astype(np.int32)
+ self.assertPreciseEqual(twice(arg), arg * 2)
+
+ def test_gufunc_scalar_input_saxpy(self):
+ @guvectorize(['void(float32, float32[:], float32[:], float32[:])'],
+ '(),(t),(t)->(t)', target='cuda')
+ def saxpy(a, x, y, out):
+ for i in range(out.shape[0]):
+ out[i] = a * x[i] + y[i]
+
+ A = np.float32(2)
+ X = np.arange(10, dtype=np.float32).reshape(5, 2)
+ Y = np.arange(10, dtype=np.float32).reshape(5, 2)
+ out = saxpy(A, X, Y)
+
+ for j in range(5):
+ for i in range(2):
+ exp = A * X[j, i] + Y[j, i]
+ self.assertTrue(exp == out[j, i])
+
+ X = np.arange(10, dtype=np.float32)
+ Y = np.arange(10, dtype=np.float32)
+ out = saxpy(A, X, Y)
+
+ for j in range(10):
+ exp = A * X[j] + Y[j]
+ self.assertTrue(exp == out[j], (exp, out[j]))
+
+ A = np.arange(5, dtype=np.float32)
+ X = np.arange(10, dtype=np.float32).reshape(5, 2)
+ Y = np.arange(10, dtype=np.float32).reshape(5, 2)
+ out = saxpy(A, X, Y)
+
+ for j in range(5):
+ for i in range(2):
+ exp = A[j] * X[j, i] + Y[j, i]
+ self.assertTrue(exp == out[j, i], (exp, out[j, i]))
+
+ def test_gufunc_scalar_cast(self):
+ @guvectorize(['void(int32, int32[:], int32[:])'], '(),(t)->(t)',
+ target='cuda')
+ def foo(a, b, out):
+ for i in range(b.size):
+ out[i] = a * b[i]
+
+ a = np.int64(2) # type does not match signature (int32)
+ b = np.arange(10).astype(np.int32)
+ out = foo(a, b)
+ np.testing.assert_equal(out, a * b)
+
+ # test error
+ a = np.array(a)
+ da = cuda.to_device(a)
+ self.assertEqual(da.dtype, np.int64)
+ with self.assertRaises(TypeError) as raises:
+ foo(da, b)
+
+ self.assertIn("does not support .astype()", str(raises.exception))
+
+ def test_gufunc_old_style_scalar_as_array(self):
+ # Example from issue #2579
+ @guvectorize(['void(int32[:],int32[:],int32[:])'], '(n),()->(n)',
+ target='cuda')
+ def gufunc(x, y, res):
+ for i in range(x.shape[0]):
+ res[i] = x[i] + y[0]
+
+ # Case 1
+ a = np.array([1, 2, 3, 4], dtype=np.int32)
+ b = np.array([2], dtype=np.int32)
+
+ res = np.zeros(4, dtype=np.int32)
+
+ expected = res.copy()
+ expected = a + b
+
+ gufunc(a, b, out=res)
+
+ np.testing.assert_almost_equal(expected, res)
+
+ # Case 2
+ a = np.array([1, 2, 3, 4] * 2, dtype=np.int32).reshape(2, 4)
+ b = np.array([2, 10], dtype=np.int32)
+
+ res = np.zeros((2, 4), dtype=np.int32)
+
+ expected = res.copy()
+ expected[0] = a[0] + b[0]
+ expected[1] = a[1] + b[1]
+
+ gufunc(a, b, res)
+
+ np.testing.assert_almost_equal(expected, res)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_gufunc_scheduling.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_gufunc_scheduling.py
new file mode 100644
index 0000000000000000000000000000000000000000..fb8de3285f75b6372945667cd33b4f48b404cec3
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_gufunc_scheduling.py
@@ -0,0 +1,95 @@
+from numba.cuda.deviceufunc import GUFuncEngine
+import unittest
+
+
+def template(signature, shapes, expects):
+ gufb = GUFuncEngine.from_signature(signature)
+ sch = gufb.schedule(shapes)
+ for k, v in expects.items():
+ got = getattr(sch, k)
+ if got != v:
+ fmt = 'error for %s: got=%s but expect=%s'
+ raise AssertionError(fmt % (k, got, v))
+
+
+class TestGUFuncScheduling(unittest.TestCase):
+ def test_signature_1(self):
+ signature = '(m, n), (n, p) -> (m, p)'
+ shapes = (100, 4, 5), (1, 5, 7)
+ expects = dict(
+ ishapes=[(4, 5), (5, 7)],
+ oshapes=[(4, 7)],
+ loopdims=(100,),
+ pinned=[False, True]
+ )
+ template(signature, shapes, expects)
+
+ def test_signature_2(self):
+ signature = '(m, n), (n, p) -> (m, p)'
+ shapes = (100, 4, 5), (100, 5, 7)
+ expects = dict(
+ ishapes=[(4, 5), (5, 7)],
+ oshapes=[(4, 7)],
+ loopdims=(100,),
+ pinned=[False, False]
+ )
+ template(signature, shapes, expects)
+
+ def test_signature_3(self):
+ signature = '(m, n), (n, p) -> (m, p)'
+ shapes = (12, 34, 4, 5), (12, 34, 5, 7)
+ expects = dict(
+ ishapes=[(4, 5), (5, 7)],
+ oshapes=[(4, 7)],
+ loopdims=(12, 34),
+ pinned=[False, False]
+ )
+ template(signature, shapes, expects)
+
+ def test_signature_4(self):
+ signature = '(m, n), (n, p) -> (m, p)'
+ shapes = (4, 5), (5, 7)
+ expects = dict(
+ ishapes=[(4, 5), (5, 7)],
+ oshapes=[(4, 7)],
+ loopdims=(),
+ pinned=[False, False]
+ )
+ template(signature, shapes, expects)
+
+ def test_signature_5(self):
+ signature = '(a), (a) -> (a)'
+ shapes = (5,), (5,)
+ expects = dict(
+ ishapes=[(5,), (5,)],
+ oshapes=[(5,)],
+ loopdims=(),
+ pinned=[False, False]
+ )
+ template(signature, shapes, expects)
+
+ def test_signature_6(self):
+ signature = '(), () -> ()'
+ shapes = (5,), (5,)
+ expects = dict(
+ ishapes=[(), ()],
+ oshapes=[()],
+ loopdims=(5,),
+ pinned=[False, False]
+ )
+ template(signature, shapes, expects)
+
+ def test_signature_7(self):
+ signature = '(), () -> ()'
+ shapes = (5,), ()
+ expects = dict(
+ ishapes=[(), ()],
+ oshapes=[()],
+ loopdims=(5,),
+ pinned=[False, True]
+ )
+ template(signature, shapes, expects)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_idiv.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_idiv.py
new file mode 100644
index 0000000000000000000000000000000000000000..44b770f422deb7adefa7192982be9925e1ed291a
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_idiv.py
@@ -0,0 +1,37 @@
+import numpy as np
+from numba import cuda, float32, float64, int32, void
+from numba.cuda.testing import unittest, CUDATestCase
+
+
+class TestCudaIDiv(CUDATestCase):
+ def test_inplace_div(self):
+
+ @cuda.jit(void(float32[:, :], int32, int32))
+ def div(grid, l_x, l_y):
+ for x in range(l_x):
+ for y in range(l_y):
+ grid[x, y] /= 2.0
+
+ x = np.ones((2, 2), dtype=np.float32)
+ grid = cuda.to_device(x)
+ div[1, 1](grid, 2, 2)
+ y = grid.copy_to_host()
+ self.assertTrue(np.all(y == 0.5))
+
+ def test_inplace_div_double(self):
+
+ @cuda.jit(void(float64[:, :], int32, int32))
+ def div_double(grid, l_x, l_y):
+ for x in range(l_x):
+ for y in range(l_y):
+ grid[x, y] /= 2.0
+
+ x = np.ones((2, 2), dtype=np.float64)
+ grid = cuda.to_device(x)
+ div_double[1, 1](grid, 2, 2)
+ y = grid.copy_to_host()
+ self.assertTrue(np.all(y == 0.5))
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_inspect.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_inspect.py
new file mode 100644
index 0000000000000000000000000000000000000000..20d6792c1d5dd96f86ce2b89b48e9ad38f8bafdc
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_inspect.py
@@ -0,0 +1,165 @@
+import numpy as np
+
+from io import StringIO
+from numba import cuda, float32, float64, int32, intp
+from numba.cuda.testing import unittest, CUDATestCase
+from numba.cuda.testing import (skip_on_cudasim, skip_with_nvdisasm,
+ skip_without_nvdisasm)
+
+
+@skip_on_cudasim('Simulator does not generate code to be inspected')
+class TestInspect(CUDATestCase):
+ @property
+ def cc(self):
+ return cuda.current_context().device.compute_capability
+
+ def test_monotyped(self):
+ sig = (float32, int32)
+
+ @cuda.jit(sig)
+ def foo(x, y):
+ pass
+
+ file = StringIO()
+ foo.inspect_types(file=file)
+ typeanno = file.getvalue()
+ # Function name in annotation
+ self.assertIn("foo", typeanno)
+ # Signature in annotation
+ self.assertIn("(float32, int32)", typeanno)
+ file.close()
+ # Function name in LLVM
+ llvm = foo.inspect_llvm(sig)
+ self.assertIn("foo", llvm)
+
+ # Kernel in LLVM
+ self.assertIn('cuda.kernel.wrapper', llvm)
+
+ # Wrapped device function body in LLVM
+ self.assertIn("define linkonce_odr i32", llvm)
+
+ asm = foo.inspect_asm(sig)
+
+ # Function name in PTX
+ self.assertIn("foo", asm)
+ # NVVM inserted comments in PTX
+ self.assertIn("Generated by NVIDIA NVVM Compiler", asm)
+
+ def test_polytyped(self):
+ @cuda.jit
+ def foo(x, y):
+ pass
+
+ foo[1, 1](1, 1)
+ foo[1, 1](1.2, 2.4)
+
+ file = StringIO()
+ foo.inspect_types(file=file)
+ typeanno = file.getvalue()
+ file.close()
+ # Signature in annotation
+ self.assertIn("({0}, {0})".format(intp), typeanno)
+ self.assertIn("(float64, float64)", typeanno)
+
+ # Signature in LLVM dict
+ llvmirs = foo.inspect_llvm()
+ self.assertEqual(2, len(llvmirs), )
+ self.assertIn((intp, intp), llvmirs)
+ self.assertIn((float64, float64), llvmirs)
+
+ # Function name in LLVM
+ self.assertIn("foo", llvmirs[intp, intp])
+ self.assertIn("foo", llvmirs[float64, float64])
+
+ # Kernels in LLVM
+ self.assertIn('cuda.kernel.wrapper', llvmirs[intp, intp])
+ self.assertIn('cuda.kernel.wrapper', llvmirs[float64, float64])
+
+ # Wrapped device function bodies in LLVM
+ self.assertIn("define linkonce_odr i32", llvmirs[intp, intp])
+ self.assertIn("define linkonce_odr i32", llvmirs[float64, float64])
+
+ asmdict = foo.inspect_asm()
+
+ # Signature in assembly dict
+ self.assertEqual(2, len(asmdict), )
+ self.assertIn((intp, intp), asmdict)
+ self.assertIn((float64, float64), asmdict)
+
+ # NVVM inserted in PTX
+ self.assertIn("foo", asmdict[intp, intp])
+ self.assertIn("foo", asmdict[float64, float64])
+
+ def _test_inspect_sass(self, kernel, name, sass):
+ # Ensure function appears in output
+ seen_function = False
+ for line in sass.split():
+ if '.text' in line and name in line:
+ seen_function = True
+ self.assertTrue(seen_function)
+
+ self.assertRegex(sass, r'//## File ".*/test_inspect.py", line [0-9]')
+
+ # Some instructions common to all supported architectures that should
+ # appear in the output
+ self.assertIn('S2R', sass) # Special register to register
+ self.assertIn('BRA', sass) # Branch
+ self.assertIn('EXIT', sass) # Exit program
+
+ @skip_without_nvdisasm('nvdisasm needed for inspect_sass()')
+ def test_inspect_sass_eager(self):
+ sig = (float32[::1], int32[::1])
+
+ @cuda.jit(sig, lineinfo=True)
+ def add(x, y):
+ i = cuda.grid(1)
+ if i < len(x):
+ x[i] += y[i]
+
+ self._test_inspect_sass(add, 'add', add.inspect_sass(sig))
+
+ @skip_without_nvdisasm('nvdisasm needed for inspect_sass()')
+ def test_inspect_sass_lazy(self):
+ @cuda.jit(lineinfo=True)
+ def add(x, y):
+ i = cuda.grid(1)
+ if i < len(x):
+ x[i] += y[i]
+
+ x = np.arange(10).astype(np.int32)
+ y = np.arange(10).astype(np.float32)
+ add[1, 10](x, y)
+
+ signature = (int32[::1], float32[::1])
+ self._test_inspect_sass(add, 'add', add.inspect_sass(signature))
+
+ @skip_with_nvdisasm('Missing nvdisasm exception only generated when it is '
+ 'not present')
+ def test_inspect_sass_nvdisasm_missing(self):
+ @cuda.jit((float32[::1],))
+ def f(x):
+ x[0] = 0
+
+ with self.assertRaises(RuntimeError) as raises:
+ f.inspect_sass()
+
+ self.assertIn('nvdisasm has not been found', str(raises.exception))
+
+ @skip_without_nvdisasm('nvdisasm needed for inspect_sass_cfg()')
+ def test_inspect_sass_cfg(self):
+ sig = (float32[::1], int32[::1])
+
+ @cuda.jit(sig)
+ def add(x, y):
+ i = cuda.grid(1)
+ if i < len(x):
+ x[i] += y[i]
+
+ self.assertRegex(
+ add.inspect_sass_cfg(signature=sig),
+ r'digraph\s*\w\s*{(.|\n)*\n}'
+ )
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_intrinsics.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_intrinsics.py
new file mode 100644
index 0000000000000000000000000000000000000000..d1eebb484c5e69360b54651408ff16e448a4f93a
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_intrinsics.py
@@ -0,0 +1,1106 @@
+import itertools
+import numpy as np
+import operator
+import re
+from numba import cuda, int64
+from numba.cuda import compile_ptx
+from numba.core.errors import TypingError
+from numba.core.types import f2
+from numba.cuda.testing import (unittest, CUDATestCase, skip_on_cudasim,
+ skip_unless_cc_53)
+
+
+def simple_threadidx(ary):
+ i = cuda.threadIdx.x
+ ary[0] = i
+
+
+def fill_threadidx(ary):
+ i = cuda.threadIdx.x
+ ary[i] = i
+
+
+def fill3d_threadidx(ary):
+ i = cuda.threadIdx.x
+ j = cuda.threadIdx.y
+ k = cuda.threadIdx.z
+
+ ary[i, j, k] = (i + 1) * (j + 1) * (k + 1)
+
+
+def simple_grid1d(ary):
+ i = cuda.grid(1)
+ ary[i] = i
+
+
+def simple_grid2d(ary):
+ i, j = cuda.grid(2)
+ ary[i, j] = i + j
+
+
+def simple_gridsize1d(ary):
+ i = cuda.grid(1)
+ x = cuda.gridsize(1)
+ if i == 0:
+ ary[0] = x
+
+
+def simple_gridsize2d(ary):
+ i, j = cuda.grid(2)
+ x, y = cuda.gridsize(2)
+ if i == 0 and j == 0:
+ ary[0] = x
+ ary[1] = y
+
+
+def intrinsic_forloop_step(c):
+ startX, startY = cuda.grid(2)
+ gridX = cuda.gridDim.x * cuda.blockDim.x
+ gridY = cuda.gridDim.y * cuda.blockDim.y
+ height, width = c.shape
+
+ for x in range(startX, width, gridX):
+ for y in range(startY, height, gridY):
+ c[y, x] = x + y
+
+
+def simple_popc(ary, c):
+ ary[0] = cuda.popc(c)
+
+
+def simple_fma(ary, a, b, c):
+ ary[0] = cuda.fma(a, b, c)
+
+
+def simple_hadd(ary, a, b):
+ ary[0] = cuda.fp16.hadd(a[0], b[0])
+
+
+def simple_hadd_scalar(ary, a, b):
+ ary[0] = cuda.fp16.hadd(a, b)
+
+
+def simple_hfma(ary, a, b, c):
+ ary[0] = cuda.fp16.hfma(a[0], b[0], c[0])
+
+
+def simple_hfma_scalar(ary, a, b, c):
+ ary[0] = cuda.fp16.hfma(a, b, c)
+
+
+def simple_hsub(ary, a, b):
+ ary[0] = cuda.fp16.hsub(a[0], b[0])
+
+
+def simple_hsub_scalar(ary, a, b):
+ ary[0] = cuda.fp16.hsub(a, b)
+
+
+def simple_hmul(ary, a, b):
+ ary[0] = cuda.fp16.hmul(a[0], b[0])
+
+
+def simple_hmul_scalar(ary, a, b):
+ ary[0] = cuda.fp16.hmul(a, b)
+
+
+def simple_hdiv_scalar(ary, a, b):
+ ary[0] = cuda.fp16.hdiv(a, b)
+
+
+def simple_hdiv_kernel(ary, array_a, array_b):
+ i = cuda.grid(1)
+ if i < ary.size:
+ a = array_a[i]
+ b = array_b[i]
+ ary[i] = cuda.fp16.hdiv(a, b)
+
+
+def simple_hneg(ary, a):
+ ary[0] = cuda.fp16.hneg(a[0])
+
+
+def simple_hneg_scalar(ary, a):
+ ary[0] = cuda.fp16.hneg(a)
+
+
+def simple_habs(ary, a):
+ ary[0] = cuda.fp16.habs(a[0])
+
+
+def simple_habs_scalar(ary, a):
+ ary[0] = cuda.fp16.habs(a)
+
+
+def simple_heq_scalar(ary, a, b):
+ ary[0] = cuda.fp16.heq(a, b)
+
+
+def simple_hne_scalar(ary, a, b):
+ ary[0] = cuda.fp16.hne(a, b)
+
+
+def simple_hge_scalar(ary, a, b):
+ ary[0] = cuda.fp16.hge(a, b)
+
+
+def simple_hgt_scalar(ary, a, b):
+ ary[0] = cuda.fp16.hgt(a, b)
+
+
+def simple_hle_scalar(ary, a, b):
+ ary[0] = cuda.fp16.hle(a, b)
+
+
+def simple_hlt_scalar(ary, a, b):
+ ary[0] = cuda.fp16.hlt(a, b)
+
+
+@cuda.jit(device=True)
+def hlt_func_1(x, y):
+ return cuda.fp16.hlt(x, y)
+
+
+@cuda.jit(device=True)
+def hlt_func_2(x, y):
+ return cuda.fp16.hlt(x, y)
+
+
+def test_multiple_hcmp_1(r, a, b, c):
+ # float16 predicates used in two separate functions
+ r[0] = hlt_func_1(a, b) and hlt_func_2(b, c)
+
+
+def test_multiple_hcmp_2(r, a, b, c):
+ # The same float16 predicate used in the caller and callee
+ r[0] = hlt_func_1(a, b) and cuda.fp16.hlt(b, c)
+
+
+def test_multiple_hcmp_3(r, a, b, c):
+ # Different float16 predicates used in the caller and callee
+ r[0] = hlt_func_1(a, b) and cuda.fp16.hge(c, b)
+
+
+def test_multiple_hcmp_4(r, a, b, c):
+ # The same float16 predicates used twice in a function
+ r[0] = cuda.fp16.hlt(a, b) and cuda.fp16.hlt(b, c)
+
+
+def test_multiple_hcmp_5(r, a, b, c):
+ # Different float16 predicates used in a function
+ r[0] = cuda.fp16.hlt(a, b) and cuda.fp16.hge(c, b)
+
+
+def simple_hmax_scalar(ary, a, b):
+ ary[0] = cuda.fp16.hmax(a, b)
+
+
+def simple_hmin_scalar(ary, a, b):
+ ary[0] = cuda.fp16.hmin(a, b)
+
+
+def simple_hsin(r, x):
+ i = cuda.grid(1)
+
+ if i < len(r):
+ r[i] = cuda.fp16.hsin(x[i])
+
+
+def simple_hcos(r, x):
+ i = cuda.grid(1)
+
+ if i < len(r):
+ r[i] = cuda.fp16.hcos(x[i])
+
+
+def simple_hlog(r, x):
+ i = cuda.grid(1)
+
+ if i < len(r):
+ r[i] = cuda.fp16.hlog(x[i])
+
+
+def simple_hlog2(r, x):
+ i = cuda.grid(1)
+
+ if i < len(r):
+ r[i] = cuda.fp16.hlog2(x[i])
+
+
+def simple_hlog10(r, x):
+ i = cuda.grid(1)
+
+ if i < len(r):
+ r[i] = cuda.fp16.hlog10(x[i])
+
+
+def simple_hexp(r, x):
+ i = cuda.grid(1)
+
+ if i < len(r):
+ r[i] = cuda.fp16.hexp(x[i])
+
+
+def simple_hexp2(r, x):
+ i = cuda.grid(1)
+
+ if i < len(r):
+ r[i] = cuda.fp16.hexp2(x[i])
+
+
+def simple_hsqrt(r, x):
+ i = cuda.grid(1)
+
+ if i < len(r):
+ r[i] = cuda.fp16.hsqrt(x[i])
+
+
+def simple_hrsqrt(r, x):
+
+ i = cuda.grid(1)
+
+ if i < len(r):
+ r[i] = cuda.fp16.hrsqrt(x[i])
+
+
+def numpy_hrsqrt(x, dtype):
+ return x ** -0.5
+
+
+def simple_hceil(r, x):
+ i = cuda.grid(1)
+
+ if i < len(r):
+ r[i] = cuda.fp16.hceil(x[i])
+
+
+def simple_hfloor(r, x):
+ i = cuda.grid(1)
+
+ if i < len(r):
+ r[i] = cuda.fp16.hfloor(x[i])
+
+
+def simple_hrcp(r, x):
+ i = cuda.grid(1)
+
+ if i < len(r):
+ r[i] = cuda.fp16.hrcp(x[i])
+
+
+def simple_htrunc(r, x):
+ i = cuda.grid(1)
+
+ if i < len(r):
+ r[i] = cuda.fp16.htrunc(x[i])
+
+
+def simple_hrint(r, x):
+ i = cuda.grid(1)
+
+ if i < len(r):
+ r[i] = cuda.fp16.hrint(x[i])
+
+
+def simple_cbrt(ary, a):
+ ary[0] = cuda.cbrt(a)
+
+
+def simple_brev(ary, c):
+ ary[0] = cuda.brev(c)
+
+
+def simple_clz(ary, c):
+ ary[0] = cuda.clz(c)
+
+
+def simple_ffs(ary, c):
+ ary[0] = cuda.ffs(c)
+
+
+def simple_round(ary, c):
+ ary[0] = round(c)
+
+
+def simple_round_to(ary, c, ndigits):
+ ary[0] = round(c, ndigits)
+
+
+def branching_with_ifs(a, b, c):
+ i = cuda.grid(1)
+
+ if a[i] > 4:
+ if b % 2 == 0:
+ a[i] = c[i]
+ else:
+ a[i] = 13
+ else:
+ a[i] = 3
+
+
+def branching_with_selps(a, b, c):
+ i = cuda.grid(1)
+
+ inner = cuda.selp(b % 2 == 0, c[i], 13)
+ a[i] = cuda.selp(a[i] > 4, inner, 3)
+
+
+def simple_laneid(ary):
+ i = cuda.grid(1)
+ ary[i] = cuda.laneid
+
+
+def simple_warpsize(ary):
+ ary[0] = cuda.warpsize
+
+
+def nonliteral_grid(x):
+ cuda.grid(x)
+
+
+def nonliteral_gridsize(x):
+ cuda.gridsize(x)
+
+
+class TestCudaIntrinsic(CUDATestCase):
+ def setUp(self):
+ super().setUp()
+ np.random.seed(0)
+
+ def test_simple_threadidx(self):
+ compiled = cuda.jit("void(int32[:])")(simple_threadidx)
+ ary = np.ones(1, dtype=np.int32)
+ compiled[1, 1](ary)
+ self.assertTrue(ary[0] == 0)
+
+ def test_fill_threadidx(self):
+ compiled = cuda.jit("void(int32[:])")(fill_threadidx)
+ N = 10
+ ary = np.ones(N, dtype=np.int32)
+ exp = np.arange(N, dtype=np.int32)
+ compiled[1, N](ary)
+ self.assertTrue(np.all(ary == exp))
+
+ def test_fill3d_threadidx(self):
+ X, Y, Z = 4, 5, 6
+
+ def c_contigous():
+ compiled = cuda.jit("void(int32[:,:,::1])")(fill3d_threadidx)
+ ary = np.zeros((X, Y, Z), dtype=np.int32)
+ compiled[1, (X, Y, Z)](ary)
+ return ary
+
+ def f_contigous():
+ compiled = cuda.jit("void(int32[::1,:,:])")(fill3d_threadidx)
+ ary = np.asfortranarray(np.zeros((X, Y, Z), dtype=np.int32))
+ compiled[1, (X, Y, Z)](ary)
+ return ary
+
+ c_res = c_contigous()
+ f_res = f_contigous()
+ self.assertTrue(np.all(c_res == f_res))
+
+ @skip_on_cudasim('Cudasim does not check types')
+ def test_nonliteral_grid_error(self):
+ with self.assertRaisesRegex(TypingError, 'RequireLiteralValue'):
+ cuda.jit('void(int32)')(nonliteral_grid)
+
+ @skip_on_cudasim('Cudasim does not check types')
+ def test_nonliteral_gridsize_error(self):
+ with self.assertRaisesRegex(TypingError, 'RequireLiteralValue'):
+ cuda.jit('void(int32)')(nonliteral_gridsize)
+
+ def test_simple_grid1d(self):
+ compiled = cuda.jit("void(int32[::1])")(simple_grid1d)
+ ntid, nctaid = 3, 7
+ nelem = ntid * nctaid
+ ary = np.empty(nelem, dtype=np.int32)
+ compiled[nctaid, ntid](ary)
+ self.assertTrue(np.all(ary == np.arange(nelem)))
+
+ def test_simple_grid2d(self):
+ compiled = cuda.jit("void(int32[:,::1])")(simple_grid2d)
+ ntid = (4, 3)
+ nctaid = (5, 6)
+ shape = (ntid[0] * nctaid[0], ntid[1] * nctaid[1])
+ ary = np.empty(shape, dtype=np.int32)
+ exp = ary.copy()
+ compiled[nctaid, ntid](ary)
+
+ for i in range(ary.shape[0]):
+ for j in range(ary.shape[1]):
+ exp[i, j] = i + j
+
+ self.assertTrue(np.all(ary == exp))
+
+ def test_simple_gridsize1d(self):
+ compiled = cuda.jit("void(int32[::1])")(simple_gridsize1d)
+ ntid, nctaid = 3, 7
+ ary = np.zeros(1, dtype=np.int32)
+ compiled[nctaid, ntid](ary)
+ self.assertEqual(ary[0], nctaid * ntid)
+
+ @skip_on_cudasim('Requires too many threads')
+ def test_issue_9229(self):
+ # Ensure that grid and grid size are correct - #9229 showed that they
+ # overflowed an int32.
+ @cuda.jit
+ def f(grid_error, gridsize_error):
+ i1 = cuda.grid(1)
+ i2 = cuda.blockIdx.x * cuda.blockDim.x + cuda.threadIdx.x
+ gs1 = cuda.gridsize(1)
+ gs2 = cuda.blockDim.x * cuda.gridDim.x
+ if i1 != i2:
+ grid_error[0] = 1
+ if gs1 != gs2:
+ gridsize_error[0] = 1
+
+ grid_error = np.zeros(1, dtype=np.uint64)
+ gridsize_error = np.zeros(1, dtype=np.uint64)
+
+ # A large enough grid for thread IDs to overflow an int32
+ # (22121216 * 256 = 5663031296, which is greater than 2 ** 32)
+ f[22121216, 256](grid_error, gridsize_error)
+
+ self.assertEqual(grid_error[0], 0)
+ self.assertEqual(gridsize_error[0], 0)
+
+ @skip_on_cudasim('Tests PTX emission')
+ def test_selp(self):
+ sig = (int64[:], int64, int64[:])
+ cu_branching_with_ifs = cuda.jit(sig)(branching_with_ifs)
+ cu_branching_with_selps = cuda.jit(sig)(branching_with_selps)
+
+ n = 32
+ b = 6
+ c = np.full(shape=32, fill_value=17, dtype=np.int64)
+
+ expected = c.copy()
+ expected[:5] = 3
+
+ a = np.arange(n, dtype=np.int64)
+ cu_branching_with_ifs[n, 1](a, b, c)
+ ptx = cu_branching_with_ifs.inspect_asm(sig)
+ self.assertEqual(2, len(re.findall(r'\s+bra\s+', ptx)))
+ np.testing.assert_array_equal(a, expected, err_msg='branching')
+
+ a = np.arange(n, dtype=np.int64)
+ cu_branching_with_selps[n, 1](a, b, c)
+ ptx = cu_branching_with_selps.inspect_asm(sig)
+ self.assertEqual(0, len(re.findall(r'\s+bra\s+', ptx)))
+ np.testing.assert_array_equal(a, expected, err_msg='selp')
+
+ def test_simple_gridsize2d(self):
+ compiled = cuda.jit("void(int32[::1])")(simple_gridsize2d)
+ ntid = (4, 3)
+ nctaid = (5, 6)
+ ary = np.zeros(2, dtype=np.int32)
+ compiled[nctaid, ntid](ary)
+
+ self.assertEqual(ary[0], nctaid[0] * ntid[0])
+ self.assertEqual(ary[1], nctaid[1] * ntid[1])
+
+ def test_intrinsic_forloop_step(self):
+ compiled = cuda.jit("void(int32[:,::1])")(intrinsic_forloop_step)
+ ntid = (4, 3)
+ nctaid = (5, 6)
+ shape = (ntid[0] * nctaid[0], ntid[1] * nctaid[1])
+ ary = np.empty(shape, dtype=np.int32)
+
+ compiled[nctaid, ntid](ary)
+
+ gridX, gridY = shape
+ height, width = ary.shape
+ for i, j in zip(range(ntid[0]), range(ntid[1])):
+ startX, startY = gridX + i, gridY + j
+ for x in range(startX, width, gridX):
+ for y in range(startY, height, gridY):
+ self.assertTrue(ary[y, x] == x + y, (ary[y, x], x + y))
+
+ def test_3dgrid(self):
+ @cuda.jit
+ def foo(out):
+ x, y, z = cuda.grid(3)
+ a, b, c = cuda.gridsize(3)
+ out[x, y, z] = a * b * c
+
+ arr = np.zeros(9 ** 3, dtype=np.int32).reshape(9, 9, 9)
+ foo[(3, 3, 3), (3, 3, 3)](arr)
+
+ np.testing.assert_equal(arr, 9 ** 3)
+
+ def test_3dgrid_2(self):
+ @cuda.jit
+ def foo(out):
+ x, y, z = cuda.grid(3)
+ a, b, c = cuda.gridsize(3)
+ grid_is_right = (
+ x == cuda.threadIdx.x + cuda.blockIdx.x * cuda.blockDim.x and
+ y == cuda.threadIdx.y + cuda.blockIdx.y * cuda.blockDim.y and
+ z == cuda.threadIdx.z + cuda.blockIdx.z * cuda.blockDim.z
+ )
+ gridsize_is_right = (a == cuda.blockDim.x * cuda.gridDim.x and
+ b == cuda.blockDim.y * cuda.gridDim.y and
+ c == cuda.blockDim.z * cuda.gridDim.z)
+ out[x, y, z] = grid_is_right and gridsize_is_right
+
+ x, y, z = (4 * 3, 3 * 2, 2 * 4)
+ arr = np.zeros((x * y * z), dtype=np.bool_).reshape(x, y, z)
+ foo[(4, 3, 2), (3, 2, 4)](arr)
+
+ self.assertTrue(np.all(arr))
+
+ def test_popc_u4(self):
+ compiled = cuda.jit("void(int32[:], uint32)")(simple_popc)
+ ary = np.zeros(1, dtype=np.int32)
+ compiled[1, 1](ary, 0xF0)
+ self.assertEqual(ary[0], 4)
+
+ def test_popc_u8(self):
+ compiled = cuda.jit("void(int32[:], uint64)")(simple_popc)
+ ary = np.zeros(1, dtype=np.int32)
+ compiled[1, 1](ary, 0xF00000000000)
+ self.assertEqual(ary[0], 4)
+
+ def test_fma_f4(self):
+ compiled = cuda.jit("void(f4[:], f4, f4, f4)")(simple_fma)
+ ary = np.zeros(1, dtype=np.float32)
+ compiled[1, 1](ary, 2., 3., 4.)
+ np.testing.assert_allclose(ary[0], 2 * 3 + 4)
+
+ def test_fma_f8(self):
+ compiled = cuda.jit("void(f8[:], f8, f8, f8)")(simple_fma)
+ ary = np.zeros(1, dtype=np.float64)
+ compiled[1, 1](ary, 2., 3., 4.)
+ np.testing.assert_allclose(ary[0], 2 * 3 + 4)
+
+ @skip_unless_cc_53
+ def test_hadd(self):
+ compiled = cuda.jit("void(f2[:], f2[:], f2[:])")(simple_hadd)
+ ary = np.zeros(1, dtype=np.float16)
+ arg1 = np.array([3.], dtype=np.float16)
+ arg2 = np.array([4.], dtype=np.float16)
+ compiled[1, 1](ary, arg1, arg2)
+ np.testing.assert_allclose(ary[0], arg1 + arg2)
+
+ @skip_unless_cc_53
+ def test_hadd_scalar(self):
+ compiled = cuda.jit("void(f2[:], f2, f2)")(simple_hadd_scalar)
+ ary = np.zeros(1, dtype=np.float16)
+ arg1 = np.float16(3.1415926)
+ arg2 = np.float16(3.)
+ compiled[1, 1](ary, arg1, arg2)
+ ref = arg1 + arg2
+ np.testing.assert_allclose(ary[0], ref)
+
+ @skip_on_cudasim('Compilation unsupported in the simulator')
+ def test_hadd_ptx(self):
+ args = (f2[:], f2, f2)
+ ptx, _ = compile_ptx(simple_hadd_scalar, args, cc=(5, 3))
+ self.assertIn('add.f16', ptx)
+
+ @skip_unless_cc_53
+ def test_hfma(self):
+ compiled = cuda.jit("void(f2[:], f2[:], f2[:], f2[:])")(simple_hfma)
+ ary = np.zeros(1, dtype=np.float16)
+ arg1 = np.array([2.], dtype=np.float16)
+ arg2 = np.array([3.], dtype=np.float16)
+ arg3 = np.array([4.], dtype=np.float16)
+ compiled[1, 1](ary, arg1, arg2, arg3)
+ np.testing.assert_allclose(ary[0], arg1 * arg2 + arg3)
+
+ @skip_unless_cc_53
+ def test_hfma_scalar(self):
+ compiled = cuda.jit("void(f2[:], f2, f2, f2)")(simple_hfma_scalar)
+ ary = np.zeros(1, dtype=np.float16)
+ arg1 = np.float16(2.)
+ arg2 = np.float16(3.)
+ arg3 = np.float16(4.)
+ compiled[1, 1](ary, arg1, arg2, arg3)
+ ref = arg1 * arg2 + arg3
+ np.testing.assert_allclose(ary[0], ref)
+
+ @skip_on_cudasim('Compilation unsupported in the simulator')
+ def test_hfma_ptx(self):
+ args = (f2[:], f2, f2, f2)
+ ptx, _ = compile_ptx(simple_hfma_scalar, args, cc=(5, 3))
+ self.assertIn('fma.rn.f16', ptx)
+
+ @skip_unless_cc_53
+ def test_hsub(self):
+ compiled = cuda.jit("void(f2[:], f2[:], f2[:])")(simple_hsub)
+ ary = np.zeros(1, dtype=np.float16)
+ arg1 = np.array([3.], dtype=np.float16)
+ arg2 = np.array([4.], dtype=np.float16)
+ compiled[1, 1](ary, arg1, arg2)
+ np.testing.assert_allclose(ary[0], arg1 - arg2)
+
+ @skip_unless_cc_53
+ def test_hsub_scalar(self):
+ compiled = cuda.jit("void(f2[:], f2, f2)")(simple_hsub_scalar)
+ ary = np.zeros(1, dtype=np.float16)
+ arg1 = np.float16(3.1415926)
+ arg2 = np.float16(1.57)
+ compiled[1, 1](ary, arg1, arg2)
+ ref = arg1 - arg2
+ np.testing.assert_allclose(ary[0], ref)
+
+ @skip_on_cudasim('Compilation unsupported in the simulator')
+ def test_hsub_ptx(self):
+ args = (f2[:], f2, f2)
+ ptx, _ = compile_ptx(simple_hsub_scalar, args, cc=(5, 3))
+ self.assertIn('sub.f16', ptx)
+
+ @skip_unless_cc_53
+ def test_hmul(self):
+ compiled = cuda.jit()(simple_hmul)
+ ary = np.zeros(1, dtype=np.float16)
+ arg1 = np.array([3.], dtype=np.float16)
+ arg2 = np.array([4.], dtype=np.float16)
+ compiled[1, 1](ary, arg1, arg2)
+ np.testing.assert_allclose(ary[0], arg1 * arg2)
+
+ @skip_unless_cc_53
+ def test_hmul_scalar(self):
+ compiled = cuda.jit("void(f2[:], f2, f2)")(simple_hmul_scalar)
+ ary = np.zeros(1, dtype=np.float16)
+ arg1 = np.float16(3.1415926)
+ arg2 = np.float16(1.57)
+ compiled[1, 1](ary, arg1, arg2)
+ ref = arg1 * arg2
+ np.testing.assert_allclose(ary[0], ref)
+
+ @skip_on_cudasim('Compilation unsupported in the simulator')
+ def test_hmul_ptx(self):
+ args = (f2[:], f2, f2)
+ ptx, _ = compile_ptx(simple_hmul_scalar, args, cc=(5, 3))
+ self.assertIn('mul.f16', ptx)
+
+ @skip_unless_cc_53
+ def test_hdiv_scalar(self):
+ compiled = cuda.jit("void(f2[:], f2, f2)")(simple_hdiv_scalar)
+ ary = np.zeros(1, dtype=np.float16)
+ arg1 = np.float16(3.1415926)
+ arg2 = np.float16(1.57)
+
+ compiled[1, 1](ary, arg1, arg2)
+ ref = arg1 / arg2
+ np.testing.assert_allclose(ary[0], ref)
+
+ @skip_unless_cc_53
+ def test_hdiv(self):
+ compiled = cuda.jit("void(f2[:], f2[:], f2[:])")(simple_hdiv_kernel)
+ arry1 = np.random.randint(-65504, 65505, size=500).astype(np.float16)
+ arry2 = np.random.randint(-65504, 65505, size=500).astype(np.float16)
+ ary = np.zeros_like(arry1, dtype=np.float16)
+
+ compiled.forall(ary.size)(ary, arry1, arry2)
+ ref = arry1 / arry2
+ np.testing.assert_allclose(ary, ref)
+
+ @skip_unless_cc_53
+ def test_hneg(self):
+ compiled = cuda.jit("void(f2[:], f2[:])")(simple_hneg)
+ ary = np.zeros(1, dtype=np.float16)
+ arg1 = np.array([3.], dtype=np.float16)
+ compiled[1, 1](ary, arg1)
+ np.testing.assert_allclose(ary[0], -arg1)
+
+ @skip_unless_cc_53
+ def test_hneg_scalar(self):
+ compiled = cuda.jit("void(f2[:], f2)")(simple_hneg_scalar)
+ ary = np.zeros(1, dtype=np.float16)
+ arg1 = np.float16(3.1415926)
+ compiled[1, 1](ary, arg1)
+ ref = -arg1
+ np.testing.assert_allclose(ary[0], ref)
+
+ @skip_on_cudasim('Compilation unsupported in the simulator')
+ def test_hneg_ptx(self):
+ args = (f2[:], f2)
+ ptx, _ = compile_ptx(simple_hneg_scalar, args, cc=(5, 3))
+ self.assertIn('neg.f16', ptx)
+
+ @skip_unless_cc_53
+ def test_habs(self):
+ compiled = cuda.jit()(simple_habs)
+ ary = np.zeros(1, dtype=np.float16)
+ arg1 = np.array([-3.], dtype=np.float16)
+ compiled[1, 1](ary, arg1)
+ np.testing.assert_allclose(ary[0], abs(arg1))
+
+ @skip_unless_cc_53
+ def test_habs_scalar(self):
+ compiled = cuda.jit("void(f2[:], f2)")(simple_habs_scalar)
+ ary = np.zeros(1, dtype=np.float16)
+ arg1 = np.float16(-3.1415926)
+ compiled[1, 1](ary, arg1)
+ ref = abs(arg1)
+ np.testing.assert_allclose(ary[0], ref)
+
+ @skip_on_cudasim('Compilation unsupported in the simulator')
+ def test_habs_ptx(self):
+ args = (f2[:], f2)
+ ptx, _ = compile_ptx(simple_habs_scalar, args, cc=(5, 3))
+ self.assertIn('abs.f16', ptx)
+
+ @skip_unless_cc_53
+ def test_fp16_intrinsics_common(self):
+ kernels = (simple_hsin, simple_hcos,
+ simple_hlog, simple_hlog2, simple_hlog10,
+ simple_hsqrt, simple_hceil, simple_hfloor,
+ simple_hrcp, simple_htrunc, simple_hrint,
+ simple_hrsqrt)
+ exp_kernels = (simple_hexp, simple_hexp2)
+ expected_functions = (np.sin, np.cos,
+ np.log, np.log2, np.log10,
+ np.sqrt, np.ceil, np.floor,
+ np.reciprocal, np.trunc, np.rint,
+ numpy_hrsqrt)
+ expected_exp_functions = (np.exp, np.exp2)
+
+ # Generate random data
+ N = 32
+ np.random.seed(1)
+ x = np.random.randint(1, 65505, size=N).astype(np.float16)
+ r = np.zeros_like(x)
+ for kernel, fn in zip(kernels, expected_functions):
+ with self.subTest(fn=fn):
+ kernel = cuda.jit("void(f2[:], f2[:])")(kernel)
+ kernel[1,N](r, x)
+ expected = fn(x, dtype=np.float16)
+ np.testing.assert_allclose(r, expected)
+
+ x2 = np.random.randint(1, 10, size=N).astype(np.float16)
+ for kernel, fn in zip(exp_kernels, expected_exp_functions):
+ with self.subTest(fn=fn):
+ kernel = cuda.jit("void(f2[:], f2[:])")(kernel)
+ kernel[1,N](r, x2)
+ expected = fn(x2, dtype=np.float16)
+ np.testing.assert_allclose(r, expected)
+
+ @skip_unless_cc_53
+ def test_hexp10(self):
+ @cuda.jit()
+ def hexp10_vectors(r, x):
+ i = cuda.grid(1)
+
+ if i < len(r):
+ r[i] = cuda.fp16.hexp10(x[i])
+
+ # Generate random data
+ N = 32
+ np.random.seed(1)
+ x = np.random.rand(N).astype(np.float16)
+ r = np.zeros_like(x)
+
+ # Run the kernel
+ hexp10_vectors[1, N](r, x)
+ np.testing.assert_allclose(r, 10 ** x)
+
+ @skip_unless_cc_53
+ def test_fp16_comparison(self):
+ fns = (simple_heq_scalar, simple_hne_scalar, simple_hge_scalar,
+ simple_hgt_scalar, simple_hle_scalar, simple_hlt_scalar)
+ ops = (operator.eq, operator.ne, operator.ge,
+ operator.gt, operator.le, operator.lt)
+
+ for fn, op in zip(fns, ops):
+ with self.subTest(op=op):
+ kernel = cuda.jit("void(b1[:], f2, f2)")(fn)
+
+ expected = np.zeros(1, dtype=np.bool_)
+ got = np.zeros(1, dtype=np.bool_)
+ arg2 = np.float16(2)
+ arg3 = np.float16(3)
+ arg4 = np.float16(4)
+
+ # Check with equal arguments
+ kernel[1, 1](got, arg3, arg3)
+ expected = op(arg3, arg3)
+ self.assertEqual(expected, got[0])
+
+ # Check with LHS < RHS
+ kernel[1, 1](got, arg3, arg4)
+ expected = op(arg3, arg4)
+ self.assertEqual(expected, got[0])
+
+ # Check with LHS > RHS
+ kernel[1, 1](got, arg3, arg2)
+ expected = op(arg3, arg2)
+ self.assertEqual(expected, got[0])
+
+ @skip_unless_cc_53
+ def test_multiple_float16_comparisons(self):
+ functions = (test_multiple_hcmp_1,
+ test_multiple_hcmp_2,
+ test_multiple_hcmp_3,
+ test_multiple_hcmp_4,
+ test_multiple_hcmp_5)
+ for fn in functions:
+ with self.subTest(fn=fn):
+ compiled = cuda.jit("void(b1[:], f2, f2, f2)")(fn)
+ ary = np.zeros(1, dtype=np.bool_)
+ arg1 = np.float16(2.)
+ arg2 = np.float16(3.)
+ arg3 = np.float16(4.)
+ compiled[1, 1](ary, arg1, arg2, arg3)
+ self.assertTrue(ary[0])
+
+ @skip_unless_cc_53
+ def test_hmax(self):
+ compiled = cuda.jit("void(f2[:], f2, f2)")(simple_hmax_scalar)
+ ary = np.zeros(1, dtype=np.float16)
+ arg1 = np.float16(3.)
+ arg2 = np.float16(4.)
+ compiled[1, 1](ary, arg1, arg2)
+ np.testing.assert_allclose(ary[0], arg2)
+ arg1 = np.float16(5.)
+ compiled[1, 1](ary, arg1, arg2)
+ np.testing.assert_allclose(ary[0], arg1)
+
+ @skip_unless_cc_53
+ def test_hmin(self):
+ compiled = cuda.jit("void(f2[:], f2, f2)")(simple_hmin_scalar)
+ ary = np.zeros(1, dtype=np.float16)
+ arg1 = np.float16(3.)
+ arg2 = np.float16(4.)
+ compiled[1, 1](ary, arg1, arg2)
+ np.testing.assert_allclose(ary[0], arg1)
+ arg1 = np.float16(5.)
+ compiled[1, 1](ary, arg1, arg2)
+ np.testing.assert_allclose(ary[0], arg2)
+
+ def test_cbrt_f32(self):
+ compiled = cuda.jit("void(float32[:], float32)")(simple_cbrt)
+ ary = np.zeros(1, dtype=np.float32)
+ cbrt_arg = 2.
+ compiled[1, 1](ary, cbrt_arg)
+ np.testing.assert_allclose(ary[0], cbrt_arg ** (1 / 3))
+
+ def test_cbrt_f64(self):
+ compiled = cuda.jit("void(float64[:], float64)")(simple_cbrt)
+ ary = np.zeros(1, dtype=np.float64)
+ cbrt_arg = 6.
+ compiled[1, 1](ary, cbrt_arg)
+ np.testing.assert_allclose(ary[0], cbrt_arg ** (1 / 3))
+
+ def test_brev_u4(self):
+ compiled = cuda.jit("void(uint32[:], uint32)")(simple_brev)
+ ary = np.zeros(1, dtype=np.uint32)
+ compiled[1, 1](ary, 0x000030F0)
+ self.assertEqual(ary[0], 0x0F0C0000)
+
+ @skip_on_cudasim('only get given a Python "int", assumes 32 bits')
+ def test_brev_u8(self):
+ compiled = cuda.jit("void(uint64[:], uint64)")(simple_brev)
+ ary = np.zeros(1, dtype=np.uint64)
+ compiled[1, 1](ary, 0x000030F0000030F0)
+ self.assertEqual(ary[0], 0x0F0C00000F0C0000)
+
+ def test_clz_i4(self):
+ compiled = cuda.jit("void(int32[:], int32)")(simple_clz)
+ ary = np.zeros(1, dtype=np.int32)
+ compiled[1, 1](ary, 0x00100000)
+ self.assertEqual(ary[0], 11)
+
+ def test_clz_u4(self):
+ """
+ Although the CUDA Math API
+ (http://docs.nvidia.com/cuda/cuda-math-api/group__CUDA__MATH__INTRINSIC__INT.html)
+ only says int32 & int64 arguments are supported in C code, the LLVM
+ IR input supports i8, i16, i32 & i64 (LLVM doesn't have a concept of
+ unsigned integers, just unsigned operations on integers).
+ http://docs.nvidia.com/cuda/nvvm-ir-spec/index.html#bit-manipulations-intrinics
+ """
+ compiled = cuda.jit("void(int32[:], uint32)")(simple_clz)
+ ary = np.zeros(1, dtype=np.int32)
+ compiled[1, 1](ary, 0x00100000)
+ self.assertEqual(ary[0], 11)
+
+ def test_clz_i4_1s(self):
+ compiled = cuda.jit("void(int32[:], int32)")(simple_clz)
+ ary = np.zeros(1, dtype=np.int32)
+ compiled[1, 1](ary, 0xFFFFFFFF)
+ self.assertEqual(ary[0], 0)
+
+ def test_clz_i4_0s(self):
+ compiled = cuda.jit("void(int32[:], int32)")(simple_clz)
+ ary = np.zeros(1, dtype=np.int32)
+ compiled[1, 1](ary, 0x0)
+ self.assertEqual(ary[0], 32, "CUDA semantics")
+
+ @skip_on_cudasim('only get given a Python "int", assumes 32 bits')
+ def test_clz_i8(self):
+ compiled = cuda.jit("void(int32[:], int64)")(simple_clz)
+ ary = np.zeros(1, dtype=np.int32)
+ compiled[1, 1](ary, 0x000000000010000)
+ self.assertEqual(ary[0], 47)
+
+ def test_ffs_i4(self):
+ compiled = cuda.jit("void(int32[:], int32)")(simple_ffs)
+ ary = np.zeros(1, dtype=np.int32)
+ compiled[1, 1](ary, 0x00100000)
+ self.assertEqual(ary[0], 21)
+ compiled[1, 1](ary, 0x80000000)
+ self.assertEqual(ary[0], 32)
+
+ def test_ffs_u4(self):
+ compiled = cuda.jit("void(int32[:], uint32)")(simple_ffs)
+ ary = np.zeros(1, dtype=np.int32)
+ compiled[1, 1](ary, 0x00100000)
+ self.assertEqual(ary[0], 21)
+ compiled[1, 1](ary, 0x80000000)
+ self.assertEqual(ary[0], 32)
+
+ def test_ffs_i4_1s(self):
+ compiled = cuda.jit("void(int32[:], int32)")(simple_ffs)
+ ary = np.zeros(1, dtype=np.int32)
+ compiled[1, 1](ary, 0xFFFFFFFF)
+ self.assertEqual(ary[0], 1)
+
+ def test_ffs_i4_0s(self):
+ compiled = cuda.jit("void(int32[:], int32)")(simple_ffs)
+ ary = np.zeros(1, dtype=np.int32)
+ compiled[1, 1](ary, 0x0)
+ self.assertEqual(ary[0], 0)
+
+ @skip_on_cudasim('only get given a Python "int", assumes 32 bits')
+ def test_ffs_i8(self):
+ compiled = cuda.jit("void(int32[:], int64)")(simple_ffs)
+ ary = np.zeros(1, dtype=np.int32)
+ compiled[1, 1](ary, 0x000000000010000)
+ self.assertEqual(ary[0], 17)
+ compiled[1, 1](ary, 0x100000000)
+ self.assertEqual(ary[0], 33)
+
+ def test_simple_laneid(self):
+ compiled = cuda.jit("void(int32[:])")(simple_laneid)
+ count = 2
+ ary = np.zeros(count * 32, dtype=np.int32)
+ exp = np.tile(np.arange(32, dtype=np.int32), count)
+ compiled[1, count * 32](ary)
+ self.assertTrue(np.all(ary == exp))
+
+ def test_simple_warpsize(self):
+ compiled = cuda.jit("void(int32[:])")(simple_warpsize)
+ ary = np.zeros(1, dtype=np.int32)
+ compiled[1, 1](ary)
+ self.assertEqual(ary[0], 32, "CUDA semantics")
+
+ def test_round_f4(self):
+ compiled = cuda.jit("void(int64[:], float32)")(simple_round)
+ ary = np.zeros(1, dtype=np.int64)
+
+ for i in [-3.0, -2.5, -2.25, -1.5, 1.5, 2.25, 2.5, 2.75]:
+ compiled[1, 1](ary, i)
+ self.assertEqual(ary[0], round(i))
+
+ def test_round_f8(self):
+ compiled = cuda.jit("void(int64[:], float64)")(simple_round)
+ ary = np.zeros(1, dtype=np.int64)
+
+ for i in [-3.0, -2.5, -2.25, -1.5, 1.5, 2.25, 2.5, 2.75]:
+ compiled[1, 1](ary, i)
+ self.assertEqual(ary[0], round(i))
+
+ def test_round_to_f4(self):
+ compiled = cuda.jit("void(float32[:], float32, int32)")(simple_round_to)
+ ary = np.zeros(1, dtype=np.float32)
+ np.random.seed(123)
+ vals = np.random.random(32).astype(np.float32)
+ np.concatenate((vals, np.array([np.inf, -np.inf, np.nan])))
+ digits = (
+ # Common case branch of round_to_impl
+ -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5,
+ # The algorithm currently implemented can only round to 13 digits
+ # with single precision. Note that this doesn't trigger the
+ # "overflow safe" branch of the implementation, which can only be
+ # hit when using double precision.
+ 13
+ )
+ for val, ndigits in itertools.product(vals, digits):
+ with self.subTest(val=val, ndigits=ndigits):
+ compiled[1, 1](ary, val, ndigits)
+ self.assertPreciseEqual(ary[0], round(val, ndigits),
+ prec='single')
+
+ # CPython on most platforms uses rounding based on dtoa.c, whereas the CUDA
+ # round-to implementation uses CPython's fallback implementation, which has
+ # slightly different behavior at the edges of the domain. Since the CUDA
+ # simulator executes using CPython, we need to skip this test when the
+ # simulator is active.
+ @skip_on_cudasim('Overflow behavior differs on CPython')
+ def test_round_to_f4_overflow(self):
+ # Test that the input value is returned when y in round_ndigits
+ # overflows.
+ compiled = cuda.jit("void(float32[:], float32, int32)")(simple_round_to)
+ ary = np.zeros(1, dtype=np.float32)
+ val = np.finfo(np.float32).max
+ # An unusually large number of digits is required to hit the "y
+ # overflows" branch of the implementation because the typing results in
+ # the computation of y as float64.
+ ndigits = 300
+ compiled[1, 1](ary, val, ndigits)
+ self.assertEqual(ary[0], val)
+
+ def test_round_to_f4_halfway(self):
+ compiled = cuda.jit("void(float32[:], float32, int32)")(simple_round_to)
+ ary = np.zeros(1, dtype=np.float32)
+ # Value chosen to trigger the "round to even" branch of the
+ # implementation
+ val = 0.3425
+ ndigits = 3
+ compiled[1, 1](ary, val, ndigits)
+ self.assertPreciseEqual(ary[0], round(val, ndigits), prec='single')
+
+ def test_round_to_f8(self):
+ compiled = cuda.jit("void(float64[:], float64, int32)")(simple_round_to)
+ ary = np.zeros(1, dtype=np.float64)
+ np.random.seed(123)
+ vals = np.random.random(32)
+ np.concatenate((vals, np.array([np.inf, -np.inf, np.nan])))
+ digits = (-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5)
+
+ for val, ndigits in itertools.product(vals, digits):
+ with self.subTest(val=val, ndigits=ndigits):
+ compiled[1, 1](ary, val, ndigits)
+ self.assertPreciseEqual(ary[0], round(val, ndigits),
+ prec='exact')
+
+ # Trigger the "overflow safe" branch of the implementation
+ val = 0.12345678987654321 * 10e-15
+ ndigits = 23
+ with self.subTest(val=val, ndigits=ndigits):
+ compiled[1, 1](ary, val, ndigits)
+ self.assertPreciseEqual(ary[0], round(val, ndigits),
+ prec='double')
+
+ # Skipped on cudasim for the same reasons as test_round_to_f4 above.
+ @skip_on_cudasim('Overflow behavior differs on CPython')
+ def test_round_to_f8_overflow(self):
+ # Test that the input value is returned when y in round_ndigits
+ # overflows.
+ compiled = cuda.jit("void(float64[:], float64, int32)")(simple_round_to)
+ ary = np.zeros(1, dtype=np.float64)
+ val = np.finfo(np.float64).max
+ # Unlike test_round_to_f4_overflow, a reasonable number of digits can
+ # be used for this test to overflow y in round_ndigits.
+ ndigits = 12
+ compiled[1, 1](ary, val, ndigits)
+ self.assertEqual(ary[0], val)
+
+ def test_round_to_f8_halfway(self):
+ compiled = cuda.jit("void(float64[:], float64, int32)")(simple_round_to)
+ ary = np.zeros(1, dtype=np.float64)
+ # Value chosen to trigger the "round to even" branch of the
+ # implementation, with a value that is not exactly representable with a
+ # float32, but only a float64.
+ val = 0.5425
+ ndigits = 3
+ compiled[1, 1](ary, val, ndigits)
+ self.assertPreciseEqual(ary[0], round(val, ndigits), prec='double')
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_ipc.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_ipc.py
new file mode 100644
index 0000000000000000000000000000000000000000..e88bbc9a09807007d9f6d5f740315750c3b52dff
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_ipc.py
@@ -0,0 +1,314 @@
+import multiprocessing as mp
+import itertools
+import traceback
+import pickle
+
+import numpy as np
+
+from numba import cuda
+from numba.cuda.cudadrv import driver
+from numba.cuda.testing import (skip_on_arm, skip_on_cudasim,
+ skip_under_cuda_memcheck,
+ ContextResettingTestCase, ForeignArray)
+from numba.tests.support import linux_only, windows_only
+import unittest
+
+
+def core_ipc_handle_test(the_work, result_queue):
+ try:
+ arr = the_work()
+ # Catch anything going wrong in the worker function
+ except: # noqa: E722
+ # FAILED. propagate the exception as a string
+ succ = False
+ out = traceback.format_exc()
+ else:
+ # OK. send the ndarray back
+ succ = True
+ out = arr
+ result_queue.put((succ, out))
+
+
+def base_ipc_handle_test(handle, size, result_queue):
+ def the_work():
+ dtype = np.dtype(np.intp)
+ with cuda.open_ipc_array(handle, shape=size // dtype.itemsize,
+ dtype=dtype) as darr:
+ # copy the data to host
+ return darr.copy_to_host()
+
+ core_ipc_handle_test(the_work, result_queue)
+
+
+def serialize_ipc_handle_test(handle, result_queue):
+ def the_work():
+ dtype = np.dtype(np.intp)
+ darr = handle.open_array(cuda.current_context(),
+ shape=handle.size // dtype.itemsize,
+ dtype=dtype)
+ # copy the data to host
+ arr = darr.copy_to_host()
+ handle.close()
+ return arr
+
+ core_ipc_handle_test(the_work, result_queue)
+
+
+def ipc_array_test(ipcarr, result_queue):
+ try:
+ with ipcarr as darr:
+ arr = darr.copy_to_host()
+ try:
+ # should fail to reopen
+ with ipcarr:
+ pass
+ except ValueError as e:
+ if str(e) != 'IpcHandle is already opened':
+ raise AssertionError('invalid exception message')
+ else:
+ raise AssertionError('did not raise on reopen')
+ # Catch any exception so we can propagate it
+ except: # noqa: E722
+ # FAILED. propagate the exception as a string
+ succ = False
+ out = traceback.format_exc()
+ else:
+ # OK. send the ndarray back
+ succ = True
+ out = arr
+ result_queue.put((succ, out))
+
+
+@linux_only
+@skip_under_cuda_memcheck('Hangs cuda-memcheck')
+@skip_on_cudasim('Ipc not available in CUDASIM')
+@skip_on_arm('CUDA IPC not supported on ARM in Numba')
+class TestIpcMemory(ContextResettingTestCase):
+
+ def test_ipc_handle(self):
+ # prepare data for IPC
+ arr = np.arange(10, dtype=np.intp)
+ devarr = cuda.to_device(arr)
+
+ # create IPC handle
+ ctx = cuda.current_context()
+ ipch = ctx.get_ipc_handle(devarr.gpu_data)
+
+ # manually prepare for serialization as bytes
+ if driver.USE_NV_BINDING:
+ handle_bytes = ipch.handle.reserved
+ else:
+ handle_bytes = bytes(ipch.handle)
+ size = ipch.size
+
+ # spawn new process for testing
+ ctx = mp.get_context('spawn')
+ result_queue = ctx.Queue()
+ args = (handle_bytes, size, result_queue)
+ proc = ctx.Process(target=base_ipc_handle_test, args=args)
+ proc.start()
+ succ, out = result_queue.get()
+ if not succ:
+ self.fail(out)
+ else:
+ np.testing.assert_equal(arr, out)
+ proc.join(3)
+
+ def variants(self):
+ # Test with no slicing and various different slices
+ indices = (None, slice(3, None), slice(3, 8), slice(None, 8))
+ # Test with a Numba DeviceNDArray, or an array from elsewhere through
+ # the CUDA Array Interface
+ foreigns = (False, True)
+ return itertools.product(indices, foreigns)
+
+ def check_ipc_handle_serialization(self, index_arg=None, foreign=False):
+ # prepare data for IPC
+ arr = np.arange(10, dtype=np.intp)
+ devarr = cuda.to_device(arr)
+ if index_arg is not None:
+ devarr = devarr[index_arg]
+ if foreign:
+ devarr = cuda.as_cuda_array(ForeignArray(devarr))
+ expect = devarr.copy_to_host()
+
+ # create IPC handle
+ ctx = cuda.current_context()
+ ipch = ctx.get_ipc_handle(devarr.gpu_data)
+
+ # pickle
+ buf = pickle.dumps(ipch)
+ ipch_recon = pickle.loads(buf)
+ self.assertIs(ipch_recon.base, None)
+ self.assertEqual(ipch_recon.size, ipch.size)
+
+ if driver.USE_NV_BINDING:
+ self.assertEqual(ipch_recon.handle.reserved, ipch.handle.reserved)
+ else:
+ self.assertEqual(tuple(ipch_recon.handle), tuple(ipch.handle))
+
+ # spawn new process for testing
+ ctx = mp.get_context('spawn')
+ result_queue = ctx.Queue()
+ args = (ipch, result_queue)
+ proc = ctx.Process(target=serialize_ipc_handle_test, args=args)
+ proc.start()
+ succ, out = result_queue.get()
+ if not succ:
+ self.fail(out)
+ else:
+ np.testing.assert_equal(expect, out)
+ proc.join(3)
+
+ def test_ipc_handle_serialization(self):
+ for index, foreign, in self.variants():
+ with self.subTest(index=index, foreign=foreign):
+ self.check_ipc_handle_serialization(index, foreign)
+
+ def check_ipc_array(self, index_arg=None, foreign=False):
+ # prepare data for IPC
+ arr = np.arange(10, dtype=np.intp)
+ devarr = cuda.to_device(arr)
+ # Slice
+ if index_arg is not None:
+ devarr = devarr[index_arg]
+ if foreign:
+ devarr = cuda.as_cuda_array(ForeignArray(devarr))
+ expect = devarr.copy_to_host()
+ ipch = devarr.get_ipc_handle()
+
+ # spawn new process for testing
+ ctx = mp.get_context('spawn')
+ result_queue = ctx.Queue()
+ args = (ipch, result_queue)
+ proc = ctx.Process(target=ipc_array_test, args=args)
+ proc.start()
+ succ, out = result_queue.get()
+ if not succ:
+ self.fail(out)
+ else:
+ np.testing.assert_equal(expect, out)
+ proc.join(3)
+
+ def test_ipc_array(self):
+ for index, foreign, in self.variants():
+ with self.subTest(index=index, foreign=foreign):
+ self.check_ipc_array(index, foreign)
+
+
+def staged_ipc_handle_test(handle, device_num, result_queue):
+ def the_work():
+ with cuda.gpus[device_num]:
+ this_ctx = cuda.devices.get_context()
+ deviceptr = handle.open_staged(this_ctx)
+ arrsize = handle.size // np.dtype(np.intp).itemsize
+ hostarray = np.zeros(arrsize, dtype=np.intp)
+ cuda.driver.device_to_host(
+ hostarray, deviceptr, size=handle.size,
+ )
+ handle.close()
+ return hostarray
+
+ core_ipc_handle_test(the_work, result_queue)
+
+
+def staged_ipc_array_test(ipcarr, device_num, result_queue):
+ try:
+ with cuda.gpus[device_num]:
+ with ipcarr as darr:
+ arr = darr.copy_to_host()
+ try:
+ # should fail to reopen
+ with ipcarr:
+ pass
+ except ValueError as e:
+ if str(e) != 'IpcHandle is already opened':
+ raise AssertionError('invalid exception message')
+ else:
+ raise AssertionError('did not raise on reopen')
+ # Catch any exception so we can propagate it
+ except: # noqa: E722
+ # FAILED. propagate the exception as a string
+ succ = False
+ out = traceback.format_exc()
+ else:
+ # OK. send the ndarray back
+ succ = True
+ out = arr
+ result_queue.put((succ, out))
+
+
+@linux_only
+@skip_under_cuda_memcheck('Hangs cuda-memcheck')
+@skip_on_cudasim('Ipc not available in CUDASIM')
+@skip_on_arm('CUDA IPC not supported on ARM in Numba')
+class TestIpcStaged(ContextResettingTestCase):
+ def test_staged(self):
+ # prepare data for IPC
+ arr = np.arange(10, dtype=np.intp)
+ devarr = cuda.to_device(arr)
+
+ # spawn new process for testing
+ mpctx = mp.get_context('spawn')
+ result_queue = mpctx.Queue()
+
+ # create IPC handle
+ ctx = cuda.current_context()
+ ipch = ctx.get_ipc_handle(devarr.gpu_data)
+ # pickle
+ buf = pickle.dumps(ipch)
+ ipch_recon = pickle.loads(buf)
+ self.assertIs(ipch_recon.base, None)
+ if driver.USE_NV_BINDING:
+ self.assertEqual(ipch_recon.handle.reserved, ipch.handle.reserved)
+ else:
+ self.assertEqual(tuple(ipch_recon.handle), tuple(ipch.handle))
+ self.assertEqual(ipch_recon.size, ipch.size)
+
+ # Test on every CUDA devices
+ for device_num in range(len(cuda.gpus)):
+ args = (ipch, device_num, result_queue)
+ proc = mpctx.Process(target=staged_ipc_handle_test, args=args)
+ proc.start()
+ succ, out = result_queue.get()
+ proc.join(3)
+ if not succ:
+ self.fail(out)
+ else:
+ np.testing.assert_equal(arr, out)
+
+ def test_ipc_array(self):
+ for device_num in range(len(cuda.gpus)):
+ # prepare data for IPC
+ arr = np.random.random(10)
+ devarr = cuda.to_device(arr)
+ ipch = devarr.get_ipc_handle()
+
+ # spawn new process for testing
+ ctx = mp.get_context('spawn')
+ result_queue = ctx.Queue()
+ args = (ipch, device_num, result_queue)
+ proc = ctx.Process(target=staged_ipc_array_test, args=args)
+ proc.start()
+ succ, out = result_queue.get()
+ proc.join(3)
+ if not succ:
+ self.fail(out)
+ else:
+ np.testing.assert_equal(arr, out)
+
+
+@windows_only
+@skip_on_cudasim('Ipc not available in CUDASIM')
+class TestIpcNotSupported(ContextResettingTestCase):
+ def test_unsupported(self):
+ arr = np.arange(10, dtype=np.intp)
+ devarr = cuda.to_device(arr)
+ with self.assertRaises(OSError) as raises:
+ devarr.get_ipc_handle()
+ errmsg = str(raises.exception)
+ self.assertIn('OS does not support CUDA IPC', errmsg)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_iterators.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_iterators.py
new file mode 100644
index 0000000000000000000000000000000000000000..47366f3803e1a76bc1ab27f5390db250071baf31
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_iterators.py
@@ -0,0 +1,99 @@
+from numba import cuda
+from numba.cuda.testing import unittest, CUDATestCase
+
+import numpy as np
+
+
+class TestIterators(CUDATestCase):
+
+ def test_enumerate(self):
+ @cuda.jit
+ def enumerator(x, error):
+ count = 0
+
+ for i, v in enumerate(x):
+ if count != i:
+ error[0] = 1
+ if v != x[i]:
+ error[0] = 2
+
+ count += 1
+
+ if count != len(x):
+ error[0] = 3
+
+ x = np.asarray((10, 9, 8, 7, 6))
+ error = np.zeros(1, dtype=np.int32)
+
+ enumerator[1, 1](x, error)
+ self.assertEqual(error[0], 0)
+
+ def _test_twoarg_function(self, f):
+ x = np.asarray((10, 9, 8, 7, 6))
+ y = np.asarray((1, 2, 3, 4, 5))
+ error = np.zeros(1, dtype=np.int32)
+
+ f[1, 1](x, y, error)
+ self.assertEqual(error[0], 0)
+
+ def test_zip(self):
+ @cuda.jit
+ def zipper(x, y, error):
+ i = 0
+
+ for xv, yv in zip(x, y):
+ if xv != x[i]:
+ error[0] = 1
+ if yv != y[i]:
+ error[0] = 2
+
+ i += 1
+
+ if i != len(x):
+ error[0] = 3
+
+ self._test_twoarg_function(zipper)
+
+ def test_enumerate_zip(self):
+ @cuda.jit
+ def enumerator_zipper(x, y, error):
+ count = 0
+
+ for i, (xv, yv) in enumerate(zip(x, y)):
+ if i != count:
+ error[0] = 1
+ if xv != x[i]:
+ error[0] = 2
+ if yv != y[i]:
+ error[0] = 3
+
+ count += 1
+
+ if count != len(x):
+ error[0] = 4
+
+ self._test_twoarg_function(enumerator_zipper)
+
+ def test_zip_enumerate(self):
+ @cuda.jit
+ def zipper_enumerator(x, y, error):
+ count = 0
+
+ for (i, xv), yv in zip(enumerate(x), y):
+ if i != count:
+ error[0] = 1
+ if xv != x[i]:
+ error[0] = 2
+ if yv != y[i]:
+ error[0] = 3
+
+ count += 1
+
+ if count != len(x):
+ error[0] = 4
+
+ self._test_twoarg_function(zipper_enumerator)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_lang.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_lang.py
new file mode 100644
index 0000000000000000000000000000000000000000..0241c1e408ce2715dffebbf27d06d7a3083da136
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_lang.py
@@ -0,0 +1,64 @@
+"""
+Test basic language features
+
+"""
+
+import numpy as np
+from numba import cuda, float64
+from numba.cuda.testing import unittest, CUDATestCase
+
+
+class TestLang(CUDATestCase):
+ def test_enumerate(self):
+ tup = (1., 2.5, 3.)
+
+ @cuda.jit("void(float64[:])")
+ def foo(a):
+ for i, v in enumerate(tup):
+ a[i] = v
+
+ a = np.zeros(len(tup))
+ foo[1, 1](a)
+ self.assertTrue(np.all(a == tup))
+
+ def test_zip(self):
+ t1 = (1, 2, 3)
+ t2 = (4.5, 5.6, 6.7)
+
+ @cuda.jit("void(float64[:])")
+ def foo(a):
+ c = 0
+ for i, j in zip(t1, t2):
+ c += i + j
+ a[0] = c
+
+ a = np.zeros(1)
+ foo[1, 1](a)
+ b = np.array(t1)
+ c = np.array(t2)
+ self.assertTrue(np.all(a == (b + c).sum()))
+
+ def test_issue_872(self):
+ '''
+ Ensure that typing and lowering of CUDA kernel API primitives works in
+ more than one block. Was originally to ensure that macro expansion works
+ for more than one block (issue #872), but macro expansion has been
+ replaced by a "proper" implementation of all kernel API functions.
+ '''
+
+ @cuda.jit("void(float64[:,:])")
+ def cuda_kernel_api_in_multiple_blocks(ary):
+ for i in range(2):
+ tx = cuda.threadIdx.x
+ for j in range(3):
+ ty = cuda.threadIdx.y
+ sm = cuda.shared.array((2, 3), float64)
+ sm[tx, ty] = 1.0
+ ary[tx, ty] = sm[tx, ty]
+
+ a = np.zeros((2, 3))
+ cuda_kernel_api_in_multiple_blocks[1, (2, 3)](a)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_laplace.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_laplace.py
new file mode 100644
index 0000000000000000000000000000000000000000..d868b02970c5cefc7d8ef8f893d015cade584579
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_laplace.py
@@ -0,0 +1,119 @@
+import numpy as np
+from numba import cuda, float64, void
+from numba.cuda.testing import unittest, CUDATestCase
+from numba.core import config
+
+# NOTE: CUDA kernel does not return any value
+
+if config.ENABLE_CUDASIM:
+ tpb = 4
+else:
+ tpb = 16
+SM_SIZE = tpb, tpb
+
+
+class TestCudaLaplace(CUDATestCase):
+ def test_laplace_small(self):
+
+ @cuda.jit(float64(float64, float64), device=True, inline=True)
+ def get_max(a, b):
+ if a > b:
+ return a
+ else:
+ return b
+
+ @cuda.jit(void(float64[:, :], float64[:, :], float64[:, :]))
+ def jocabi_relax_core(A, Anew, error):
+ err_sm = cuda.shared.array(SM_SIZE, dtype=float64)
+
+ ty = cuda.threadIdx.x
+ tx = cuda.threadIdx.y
+ bx = cuda.blockIdx.x
+ by = cuda.blockIdx.y
+
+ n = A.shape[0]
+ m = A.shape[1]
+
+ i, j = cuda.grid(2)
+
+ err_sm[ty, tx] = 0
+ if j >= 1 and j < n - 1 and i >= 1 and i < m - 1:
+ Anew[j, i] = 0.25 * ( A[j, i + 1] + A[j, i - 1]
+ + A[j - 1, i] + A[j + 1, i])
+ err_sm[ty, tx] = Anew[j, i] - A[j, i]
+
+ cuda.syncthreads()
+
+ # max-reduce err_sm vertically
+ t = tpb // 2
+ while t > 0:
+ if ty < t:
+ err_sm[ty, tx] = get_max(err_sm[ty, tx], err_sm[ty + t, tx])
+ t //= 2
+ cuda.syncthreads()
+
+ # max-reduce err_sm horizontally
+ t = tpb // 2
+ while t > 0:
+ if tx < t and ty == 0:
+ err_sm[ty, tx] = get_max(err_sm[ty, tx], err_sm[ty, tx + t])
+ t //= 2
+ cuda.syncthreads()
+
+ if tx == 0 and ty == 0:
+ error[by, bx] = err_sm[0, 0]
+
+ if config.ENABLE_CUDASIM:
+ NN, NM = 4, 4
+ iter_max = 20
+ else:
+ NN, NM = 256, 256
+ iter_max = 1000
+
+ A = np.zeros((NN, NM), dtype=np.float64)
+ Anew = np.zeros((NN, NM), dtype=np.float64)
+
+ n = NN
+
+ tol = 1.0e-6
+ error = 1.0
+
+ for j in range(n):
+ A[j, 0] = 1.0
+ Anew[j, 0] = 1.0
+
+ iter = 0
+
+ blockdim = (tpb, tpb)
+ griddim = (NN // blockdim[0], NM // blockdim[1])
+
+ error_grid = np.zeros(griddim)
+
+ stream = cuda.stream()
+
+ dA = cuda.to_device(A, stream) # to device and don't come back
+ dAnew = cuda.to_device(Anew, stream) # to device and don't come back
+ derror_grid = cuda.to_device(error_grid, stream)
+
+ while error > tol and iter < iter_max:
+ self.assertTrue(error_grid.dtype == np.float64)
+
+ jocabi_relax_core[griddim, blockdim, stream](dA, dAnew, derror_grid)
+
+ derror_grid.copy_to_host(error_grid, stream=stream)
+
+ # error_grid is available on host
+ stream.synchronize()
+
+ error = np.abs(error_grid).max()
+
+ # swap dA and dAnew
+ tmp = dA
+ dA = dAnew
+ dAnew = tmp
+
+ iter += 1
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_libdevice.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_libdevice.py
new file mode 100644
index 0000000000000000000000000000000000000000..9572a8882c368c3ab7395953ec4fe666f5f8bc5a
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_libdevice.py
@@ -0,0 +1,187 @@
+import numpy as np
+from numba.core import types
+from numba.cuda.testing import skip_on_cudasim, unittest, CUDATestCase
+from numba import cuda
+from numba.cuda import libdevice, compile_ptx
+from numba.cuda.libdevicefuncs import functions, create_signature
+
+
+def use_sincos(s, c, x):
+ i = cuda.grid(1)
+
+ if i < len(x):
+ sr, cr = libdevice.sincos(x[i])
+ s[i] = sr
+ c[i] = cr
+
+
+def use_frexp(frac, exp, x):
+ i = cuda.grid(1)
+
+ if i < len(x):
+ fracr, expr = libdevice.frexp(x[i])
+ frac[i] = fracr
+ exp[i] = expr
+
+
+def use_sad(r, x, y, z):
+ i = cuda.grid(1)
+
+ if i < len(x):
+ r[i] = libdevice.sad(x[i], y[i], z[i])
+
+
+@skip_on_cudasim('Libdevice functions are not supported on cudasim')
+class TestLibdevice(CUDATestCase):
+ """
+ Some tests of libdevice function wrappers that check the returned values.
+
+ These are mainly to check that the generation of the implementations
+ results in correct typing and lowering for each type of function return
+ (e.g. scalar return, UniTuple return, Tuple return, etc.).
+ """
+
+ def test_sincos(self):
+ # Tests return of a UniTuple from a libdevice function
+ arr = np.arange(100, dtype=np.float64)
+ sres = np.zeros_like(arr)
+ cres = np.zeros_like(arr)
+
+ cufunc = cuda.jit(use_sincos)
+ cufunc[4, 32](sres, cres, arr)
+
+ np.testing.assert_allclose(np.cos(arr), cres)
+ np.testing.assert_allclose(np.sin(arr), sres)
+
+ def test_frexp(self):
+ # Test return of a Tuple from a libdevice function
+ arr = np.linspace(start=1.0, stop=10.0, num=100, dtype=np.float64)
+ fracres = np.zeros_like(arr)
+ expres = np.zeros(shape=arr.shape, dtype=np.int32)
+
+ cufunc = cuda.jit(use_frexp)
+ cufunc[4, 32](fracres, expres, arr)
+
+ frac_expect, exp_expect = np.frexp(arr)
+
+ np.testing.assert_array_equal(frac_expect, fracres)
+ np.testing.assert_array_equal(exp_expect, expres)
+
+ def test_sad(self):
+ # Test return of a scalar from a libdevice function
+ x = np.arange(0, 200, 2)
+ y = np.arange(50, 150)
+ z = np.arange(15, 115)
+ r = np.zeros_like(x)
+
+ cufunc = cuda.jit(use_sad)
+ cufunc[4, 32](r, x, y, z)
+
+ np.testing.assert_array_equal(np.abs(x - y) + z, r)
+
+
+# A template for generating tests of compiling calls to libdevice functions.
+# The purpose of the call and assignment of the return variables is to ensure
+# the actual function implementations are not thrown away resulting in a PTX
+# implementation that only contains the ret instruction - this may hide certain
+# errors.
+function_template = """\
+from numba.cuda import libdevice
+
+def pyfunc(%(pyargs)s):
+ ret = libdevice.%(func)s(%(funcargs)s)
+ %(retvars)s = ret
+"""
+
+
+def make_test_call(libname):
+ """
+ Generates a test function for each libdevice function.
+ """
+
+ def _test_call_functions(self):
+ # Strip off '__nv_' from libdevice name to get Python name
+ apiname = libname[5:]
+ apifunc = getattr(libdevice, apiname)
+ retty, args = functions[libname]
+ sig = create_signature(retty, args)
+
+ # Construct arguments to the libdevice function. These are all
+ # non-pointer arguments to the underlying bitcode function.
+ funcargs = ", ".join(['a%d' % i for i, arg in enumerate(args) if not
+ arg.is_ptr])
+
+ # Arguments to the Python function (`pyfunc` in the template above) are
+ # the arguments to the libdevice function, plus as many extra arguments
+ # as there are in the return type of the libdevice function - one for
+ # scalar-valued returns, or the length of the tuple for tuple-valued
+ # returns.
+ if isinstance(sig.return_type, (types.Tuple, types.UniTuple)):
+ # Start with the parameters for the return values
+ pyargs = ", ".join(['r%d' % i for i in
+ range(len(sig.return_type))])
+ # Add the parameters for the argument values
+ pyargs += ", " + funcargs
+ # Generate the unpacking of the return value from the libdevice
+ # function into the Python function return values (`r0`, `r1`,
+ # etc.).
+ retvars = ", ".join(['r%d[0]' % i for i in
+ range(len(sig.return_type))])
+ else:
+ # Scalar return is a more straightforward case
+ pyargs = "r0, " + funcargs
+ retvars = "r0[0]"
+
+ # Create the string containing the function to compile
+ d = { 'func': apiname,
+ 'pyargs': pyargs,
+ 'funcargs': funcargs,
+ 'retvars': retvars }
+ code = function_template % d
+
+ # Convert the string to a Python function
+ locals = {}
+ exec(code, globals(), locals)
+ pyfunc = locals['pyfunc']
+
+ # Compute the signature for compilation. This mirrors the creation of
+ # arguments to the Python function above.
+ pyargs = [ arg.ty for arg in args if not arg.is_ptr ]
+ if isinstance(sig.return_type, (types.Tuple, types.UniTuple)):
+ pyreturns = [ret[::1] for ret in sig.return_type]
+ pyargs = pyreturns + pyargs
+ else:
+ pyargs.insert(0, sig.return_type[::1])
+
+ pyargs = tuple(pyargs)
+ ptx, resty = compile_ptx(pyfunc, pyargs)
+
+ # If the function body was discarded by optimization (therefore making
+ # the test a bit weak), there won't be any loading of parameters -
+ # ensure that a load from parameters occurs somewhere in the PTX
+ self.assertIn('ld.param', ptx)
+
+ # Returning the result (through a passed-in array) should also require
+ # a store to global memory, so check for at least one of those too.
+ self.assertIn('st.global', ptx)
+
+ return _test_call_functions
+
+
+@skip_on_cudasim('Compilation to PTX is not supported on cudasim')
+class TestLibdeviceCompilation(unittest.TestCase):
+ """
+ Class for holding all tests of compiling calls to libdevice functions. We
+ generate the actual tests in this class (as opposed to using subTest and
+ one test within this class) because there are a lot of tests, and it makes
+ the test suite appear frozen to test them all as subTests in one test.
+ """
+
+
+for libname in functions:
+ setattr(TestLibdeviceCompilation, 'test_%s' % libname,
+ make_test_call(libname))
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_lineinfo.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_lineinfo.py
new file mode 100644
index 0000000000000000000000000000000000000000..b5093877fc28aceda8fcf2fce43624ba1dc72096
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_lineinfo.py
@@ -0,0 +1,199 @@
+from numba import cuda, float32, int32
+from numba.core.errors import NumbaInvalidConfigWarning
+from numba.cuda.testing import CUDATestCase, skip_on_cudasim
+from numba.tests.support import ignore_internal_warnings
+import re
+import unittest
+import warnings
+
+
+@skip_on_cudasim('Simulator does not produce lineinfo')
+class TestCudaLineInfo(CUDATestCase):
+ def _loc_directive_regex(self):
+ # This is used in several tests
+
+ pat = (
+ r'\.loc' # .loc directive beginning
+ r'\s+[0-9]+' # whitespace then file index
+ r'\s+[0-9]+' # whitespace then line number
+ r'\s+[0-9]+' # whitespace then column position
+ )
+ return re.compile(pat)
+
+ def _check(self, fn, sig, expect):
+ fn.compile(sig)
+ llvm = fn.inspect_llvm(sig)
+ ptx = fn.inspect_asm(sig)
+ assertfn = self.assertIsNotNone if expect else self.assertIsNone
+
+ # DICompileUnit debug info metadata should all be of the
+ # DebugDirectivesOnly kind, and not the FullDebug kind
+ pat = (
+ r'!DICompileUnit\(.*' # Opening of DICompileUnit metadata. Since
+ # the order of attributes is not
+ # guaranteed, we need to match arbitrarily
+ # afterwards.
+ r'emissionKind:\s+' # The emissionKind attribute followed by
+ # whitespace.
+ r'DebugDirectivesOnly' # The correct emissionKind.
+ )
+ match = re.compile(pat).search(llvm)
+ assertfn(match, msg=ptx)
+
+ pat = (
+ r'!DICompileUnit\(.*' # Same as the pattern above, but for the
+ r'emissionKind:\s+' # incorrect FullDebug emissionKind.
+ r'FullDebug' #
+ )
+ match = re.compile(pat).search(llvm)
+ self.assertIsNone(match, msg=ptx)
+
+ # The name of this file should be present in the line mapping
+ # if lineinfo was propagated through correctly.
+ pat = (
+ r'\.file' # .file directive beginning
+ r'\s+[0-9]+\s+' # file number surrounded by whitespace
+ r'".*test_lineinfo.py"' # filename in quotes, ignoring full path
+ )
+ match = re.compile(pat).search(ptx)
+ assertfn(match, msg=ptx)
+
+ # .loc directives should be present in the ptx
+ self._loc_directive_regex().search(ptx)
+ assertfn(match, msg=ptx)
+
+ # Debug info sections should not be present when only lineinfo is
+ # generated
+ pat = (
+ r'\.section\s+' # .section directive beginning
+ r'\.debug_info' # Section named ".debug_info"
+ )
+ match = re.compile(pat).search(ptx)
+ self.assertIsNone(match, msg=ptx)
+
+ def test_no_lineinfo_in_asm(self):
+ @cuda.jit(lineinfo=False)
+ def foo(x):
+ x[0] = 1
+
+ self._check(foo, sig=(int32[:],), expect=False)
+
+ def test_lineinfo_in_asm(self):
+ @cuda.jit(lineinfo=True)
+ def foo(x):
+ x[0] = 1
+
+ self._check(foo, sig=(int32[:],), expect=True)
+
+ def test_lineinfo_maintains_error_model(self):
+ sig = (float32[::1], float32[::1])
+
+ @cuda.jit(sig, lineinfo=True)
+ def divide_kernel(x, y):
+ x[0] /= y[0]
+
+ llvm = divide_kernel.inspect_llvm(sig)
+
+ # When the error model is Python, the device function returns 1 to
+ # signal an exception (e.g. divide by zero) has occurred. When the
+ # error model is the default NumPy one (as it should be when only
+ # lineinfo is enabled) the device function always returns 0.
+ self.assertNotIn('ret i32 1', llvm)
+
+ def test_no_lineinfo_in_device_function(self):
+ # Ensure that no lineinfo is generated in device functions by default.
+ @cuda.jit
+ def callee(x):
+ x[0] += 1
+
+ @cuda.jit
+ def caller(x):
+ x[0] = 1
+ callee(x)
+
+ sig = (int32[:],)
+ self._check(caller, sig=sig, expect=False)
+
+ def test_lineinfo_in_device_function(self):
+ # First we define a device function / kernel pair and run the usual
+ # checks on the generated LLVM and PTX.
+
+ @cuda.jit(lineinfo=True)
+ def callee(x):
+ x[0] += 1
+
+ @cuda.jit(lineinfo=True)
+ def caller(x):
+ x[0] = 1
+ callee(x)
+
+ sig = (int32[:],)
+ self._check(caller, sig=sig, expect=True)
+
+ # Now we can check the PTX of the device function specifically.
+
+ ptx = caller.inspect_asm(sig)
+ ptxlines = ptx.splitlines()
+
+ # Check that there is no device function in the PTX
+
+ # A line beginning with ".weak .func" that identifies a device function
+ devfn_start = re.compile(r'^\.weak\s+\.func')
+
+ for line in ptxlines:
+ if devfn_start.match(line) is not None:
+ self.fail(f"Found device function in PTX:\n\n{ptx}")
+
+ # Scan for .loc directives that refer to an inlined device function
+
+ loc_directive = self._loc_directive_regex()
+ found = False
+
+ for line in ptxlines:
+ if loc_directive.search(line) is not None:
+ if 'inlined_at' in line:
+ found = True
+ break
+
+ if not found:
+ self.fail(f'No .loc directive with inlined_at info found'
+ f'in:\n\n{ptx}')
+
+ # We also inspect the LLVM to ensure that there's debug info for each
+ # subprogram (function). A lightweight way to check this is to ensure
+ # that we have as many DISubprograms as we expect.
+
+ llvm = caller.inspect_llvm(sig)
+ subprograms = 0
+ for line in llvm.splitlines():
+ if 'distinct !DISubprogram' in line:
+ subprograms += 1
+
+ # One DISubprogram for each of:
+ # - The kernel wrapper
+ # - The caller
+ # - The callee
+ expected_subprograms = 3
+
+ self.assertEqual(subprograms, expected_subprograms,
+ f'"Expected {expected_subprograms} DISubprograms; '
+ f'got {subprograms}')
+
+ def test_debug_and_lineinfo_warning(self):
+ with warnings.catch_warnings(record=True) as w:
+ ignore_internal_warnings()
+
+ # We pass opt=False to prevent the warning about opt and debug
+ # occurring as well
+ @cuda.jit(debug=True, lineinfo=True, opt=False)
+ def f():
+ pass
+
+ self.assertEqual(len(w), 1)
+ self.assertEqual(w[0].category, NumbaInvalidConfigWarning)
+ self.assertIn('debug and lineinfo are mutually exclusive',
+ str(w[0].message))
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_localmem.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_localmem.py
new file mode 100644
index 0000000000000000000000000000000000000000..26b3469a77cf63e87459685e800584209daafd61
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_localmem.py
@@ -0,0 +1,164 @@
+import numpy as np
+
+from numba import cuda, int32, complex128, void
+from numba.core import types
+from numba.core.errors import TypingError
+from numba.cuda.testing import unittest, CUDATestCase, skip_on_cudasim
+from .extensions_usecases import test_struct_model_type, TestStruct
+
+
+def culocal(A, B):
+ C = cuda.local.array(1000, dtype=int32)
+ for i in range(C.shape[0]):
+ C[i] = A[i]
+ for i in range(C.shape[0]):
+ B[i] = C[i]
+
+
+def culocalcomplex(A, B):
+ C = cuda.local.array(100, dtype=complex128)
+ for i in range(C.shape[0]):
+ C[i] = A[i]
+ for i in range(C.shape[0]):
+ B[i] = C[i]
+
+
+def culocal1tuple(A, B):
+ C = cuda.local.array((5,), dtype=int32)
+ for i in range(C.shape[0]):
+ C[i] = A[i]
+ for i in range(C.shape[0]):
+ B[i] = C[i]
+
+
+@skip_on_cudasim('PTX inspection not available in cudasim')
+class TestCudaLocalMem(CUDATestCase):
+ def test_local_array(self):
+ sig = (int32[:], int32[:])
+ jculocal = cuda.jit(sig)(culocal)
+ self.assertTrue('.local' in jculocal.inspect_asm(sig))
+ A = np.arange(1000, dtype='int32')
+ B = np.zeros_like(A)
+ jculocal[1, 1](A, B)
+ self.assertTrue(np.all(A == B))
+
+ def test_local_array_1_tuple(self):
+ """Ensure that local arrays can be constructed with 1-tuple shape
+ """
+ jculocal = cuda.jit('void(int32[:], int32[:])')(culocal1tuple)
+ # Don't check if .local is in the ptx because the optimizer
+ # may reduce it to registers.
+ A = np.arange(5, dtype='int32')
+ B = np.zeros_like(A)
+ jculocal[1, 1](A, B)
+ self.assertTrue(np.all(A == B))
+
+ def test_local_array_complex(self):
+ sig = 'void(complex128[:], complex128[:])'
+ jculocalcomplex = cuda.jit(sig)(culocalcomplex)
+ A = (np.arange(100, dtype='complex128') - 1) / 2j
+ B = np.zeros_like(A)
+ jculocalcomplex[1, 1](A, B)
+ self.assertTrue(np.all(A == B))
+
+ def check_dtype(self, f, dtype):
+ # Find the typing of the dtype argument to cuda.local.array
+ annotation = next(iter(f.overloads.values()))._type_annotation
+ l_dtype = annotation.typemap['l'].dtype
+ # Ensure that the typing is correct
+ self.assertEqual(l_dtype, dtype)
+
+ @skip_on_cudasim("Can't check typing in simulator")
+ def test_numba_dtype(self):
+ # Check that Numba types can be used as the dtype of a local array
+ @cuda.jit(void(int32[::1]))
+ def f(x):
+ l = cuda.local.array(10, dtype=int32)
+ l[0] = x[0]
+ x[0] = l[0]
+
+ self.check_dtype(f, int32)
+
+ @skip_on_cudasim("Can't check typing in simulator")
+ def test_numpy_dtype(self):
+ # Check that NumPy types can be used as the dtype of a local array
+ @cuda.jit(void(int32[::1]))
+ def f(x):
+ l = cuda.local.array(10, dtype=np.int32)
+ l[0] = x[0]
+ x[0] = l[0]
+
+ self.check_dtype(f, int32)
+
+ @skip_on_cudasim("Can't check typing in simulator")
+ def test_string_dtype(self):
+ # Check that strings can be used to specify the dtype of a local array
+ @cuda.jit(void(int32[::1]))
+ def f(x):
+ l = cuda.local.array(10, dtype='int32')
+ l[0] = x[0]
+ x[0] = l[0]
+
+ self.check_dtype(f, int32)
+
+ @skip_on_cudasim("Can't check typing in simulator")
+ def test_invalid_string_dtype(self):
+ # Check that strings of invalid dtypes cause a typing error
+ re = ".*Invalid NumPy dtype specified: 'int33'.*"
+ with self.assertRaisesRegex(TypingError, re):
+ @cuda.jit(void(int32[::1]))
+ def f(x):
+ l = cuda.local.array(10, dtype='int33')
+ l[0] = x[0]
+ x[0] = l[0]
+
+ def test_type_with_struct_data_model(self):
+ @cuda.jit(void(test_struct_model_type[::1]))
+ def f(x):
+ l = cuda.local.array(10, dtype=test_struct_model_type)
+ l[0] = x[0]
+ x[0] = l[0]
+
+ self.check_dtype(f, test_struct_model_type)
+
+ def test_struct_model_type_arr(self):
+ @cuda.jit(void(int32[::1], int32[::1]))
+ def f(outx, outy):
+ # Test creation
+ arr = cuda.local.array(10, dtype=test_struct_model_type)
+ # Test set to arr
+ for i in range(len(arr)):
+ obj = TestStruct(int32(i), int32(i * 2))
+ arr[i] = obj
+ # Test get from arr
+ for i in range(len(arr)):
+ outx[i] = arr[i].x
+ outy[i] = arr[i].y
+
+ arrx = np.array((10,), dtype="int32")
+ arry = np.array((10,), dtype="int32")
+
+ f[1, 1](arrx, arry)
+
+ for i, x in enumerate(arrx):
+ self.assertEqual(x, i)
+ for i, y in enumerate(arry):
+ self.assertEqual(y, i * 2)
+
+ def _check_local_array_size_fp16(self, shape, expected, ty):
+ @cuda.jit
+ def s(a):
+ arr = cuda.local.array(shape, dtype=ty)
+ a[0] = arr.size
+
+ result = np.zeros(1, dtype=np.float16)
+ s[1, 1](result)
+ self.assertEqual(result[0], expected)
+
+ def test_issue_fp16_support(self):
+ self._check_local_array_size_fp16(2, 2, types.float16)
+ self._check_local_array_size_fp16(2, 2, np.float16)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_mandel.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_mandel.py
new file mode 100644
index 0000000000000000000000000000000000000000..2b7290ad48ea432aee7e9f8dc4a890ba5ff6cf6d
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_mandel.py
@@ -0,0 +1,37 @@
+from numba import float64, uint32
+from numba.cuda.compiler import compile_ptx
+from numba.cuda.testing import skip_on_cudasim, unittest
+
+
+@skip_on_cudasim('Compilation unsupported in the simulator')
+class TestCudaMandel(unittest.TestCase):
+ def test_mandel(self):
+ """Just make sure we can compile this
+ """
+
+ def mandel(tid, min_x, max_x, min_y, max_y, width, height, iters):
+ pixel_size_x = (max_x - min_x) / width
+ pixel_size_y = (max_y - min_y) / height
+
+ x = tid % width
+ y = tid / width
+
+ real = min_x + x * pixel_size_x
+ imag = min_y + y * pixel_size_y
+
+ c = complex(real, imag)
+ z = 0.0j
+
+ for i in range(iters):
+ z = z * z + c
+ if (z.real * z.real + z.imag * z.imag) >= 4:
+ return i
+ return iters
+
+ args = (uint32, float64, float64, float64, float64,
+ uint32, uint32, uint32)
+ compile_ptx(mandel, args, device=True)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_math.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_math.py
new file mode 100644
index 0000000000000000000000000000000000000000..028a402ff05ea36698c6eea654655e3e8f727b51
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_math.py
@@ -0,0 +1,786 @@
+import numpy as np
+from numba.cuda.testing import (skip_unless_cc_53,
+ unittest,
+ CUDATestCase,
+ skip_on_cudasim)
+from numba.np import numpy_support
+from numba import cuda, float32, float64, int32, vectorize, void, int64
+import math
+
+
+def math_acos(A, B):
+ i = cuda.grid(1)
+ B[i] = math.acos(A[i])
+
+
+def math_asin(A, B):
+ i = cuda.grid(1)
+ B[i] = math.asin(A[i])
+
+
+def math_atan(A, B):
+ i = cuda.grid(1)
+ B[i] = math.atan(A[i])
+
+
+def math_acosh(A, B):
+ i = cuda.grid(1)
+ B[i] = math.acosh(A[i])
+
+
+def math_asinh(A, B):
+ i = cuda.grid(1)
+ B[i] = math.asinh(A[i])
+
+
+def math_atanh(A, B):
+ i = cuda.grid(1)
+ B[i] = math.atanh(A[i])
+
+
+def math_cos(A, B):
+ i = cuda.grid(1)
+ B[i] = math.cos(A[i])
+
+
+def math_sin(A, B):
+ i = cuda.grid(1)
+ B[i] = math.sin(A[i])
+
+
+def math_tan(A, B):
+ i = cuda.grid(1)
+ B[i] = math.tan(A[i])
+
+
+def math_cosh(A, B):
+ i = cuda.grid(1)
+ B[i] = math.cosh(A[i])
+
+
+def math_sinh(A, B):
+ i = cuda.grid(1)
+ B[i] = math.sinh(A[i])
+
+
+def math_tanh(A, B):
+ i = cuda.grid(1)
+ B[i] = math.tanh(A[i])
+
+
+def math_atan2(A, B, C):
+ i = cuda.grid(1)
+ C[i] = math.atan2(A[i], B[i])
+
+
+def math_exp(A, B):
+ i = cuda.grid(1)
+ B[i] = math.exp(A[i])
+
+
+def math_erf(A, B):
+ i = cuda.grid(1)
+ B[i] = math.erf(A[i])
+
+
+def math_erfc(A, B):
+ i = cuda.grid(1)
+ B[i] = math.erfc(A[i])
+
+
+def math_expm1(A, B):
+ i = cuda.grid(1)
+ B[i] = math.expm1(A[i])
+
+
+def math_fabs(A, B):
+ i = cuda.grid(1)
+ B[i] = math.fabs(A[i])
+
+
+def math_gamma(A, B):
+ i = cuda.grid(1)
+ B[i] = math.gamma(A[i])
+
+
+def math_lgamma(A, B):
+ i = cuda.grid(1)
+ B[i] = math.lgamma(A[i])
+
+
+def math_log(A, B):
+ i = cuda.grid(1)
+ B[i] = math.log(A[i])
+
+
+def math_log2(A, B):
+ i = cuda.grid(1)
+ B[i] = math.log2(A[i])
+
+
+def math_log10(A, B):
+ i = cuda.grid(1)
+ B[i] = math.log10(A[i])
+
+
+def math_log1p(A, B):
+ i = cuda.grid(1)
+ B[i] = math.log1p(A[i])
+
+
+def math_remainder(A, B, C):
+ i = cuda.grid(1)
+ C[i] = math.remainder(A[i], B[i])
+
+
+def math_sqrt(A, B):
+ i = cuda.grid(1)
+ B[i] = math.sqrt(A[i])
+
+
+def math_hypot(A, B, C):
+ i = cuda.grid(1)
+ C[i] = math.hypot(A[i], B[i])
+
+
+def math_pow(A, B, C):
+ i = cuda.grid(1)
+ C[i] = math.pow(A[i], B[i])
+
+
+def math_ceil(A, B):
+ i = cuda.grid(1)
+ B[i] = math.ceil(A[i])
+
+
+def math_floor(A, B):
+ i = cuda.grid(1)
+ B[i] = math.floor(A[i])
+
+
+def math_copysign(A, B, C):
+ i = cuda.grid(1)
+ C[i] = math.copysign(A[i], B[i])
+
+
+def math_fmod(A, B, C):
+ i = cuda.grid(1)
+ C[i] = math.fmod(A[i], B[i])
+
+
+def math_modf(A, B, C):
+ i = cuda.grid(1)
+ B[i], C[i] = math.modf(A[i])
+
+
+def math_isnan(A, B):
+ i = cuda.grid(1)
+ B[i] = math.isnan(A[i])
+
+
+def math_isinf(A, B):
+ i = cuda.grid(1)
+ B[i] = math.isinf(A[i])
+
+
+def math_isfinite(A, B):
+ i = cuda.grid(1)
+ B[i] = math.isfinite(A[i])
+
+
+def math_degrees(A, B):
+ i = cuda.grid(1)
+ B[i] = math.degrees(A[i])
+
+
+def math_radians(A, B):
+ i = cuda.grid(1)
+ B[i] = math.radians(A[i])
+
+
+def math_trunc(A, B):
+ i = cuda.grid(1)
+ B[i] = math.trunc(A[i])
+
+
+def math_pow_binop(A, B, C):
+ i = cuda.grid(1)
+ C[i] = A[i] ** B[i]
+
+
+def math_mod_binop(A, B, C):
+ i = cuda.grid(1)
+ C[i] = A[i] % B[i]
+
+
+class TestCudaMath(CUDATestCase):
+ def unary_template_float16(self, func, npfunc, start=0, stop=1):
+ self.unary_template(func, npfunc, np.float16, np.float16, start, stop)
+
+ def unary_template_float32(self, func, npfunc, start=0, stop=1):
+ self.unary_template(func, npfunc, np.float32, np.float32, start, stop)
+
+ def unary_template_float64(self, func, npfunc, start=0, stop=1):
+ self.unary_template(func, npfunc, np.float64, np.float64, start, stop)
+
+ def unary_template_int64(self, func, npfunc, start=0, stop=50):
+ self.unary_template(func, npfunc, np.int64, np.float64, start, stop)
+
+ def unary_template_uint64(self, func, npfunc, start=0, stop=50):
+ self.unary_template(func, npfunc, np.uint64, np.float64, start, stop)
+
+ def unary_template(self, func, npfunc, npdtype, nprestype, start, stop):
+ nelem = 50
+ A = np.linspace(start, stop, nelem).astype(npdtype)
+ B = np.empty_like(A).astype(nprestype)
+ arytype = numpy_support.from_dtype(npdtype)[::1]
+ restype = numpy_support.from_dtype(nprestype)[::1]
+ cfunc = cuda.jit((arytype, restype))(func)
+ cfunc[1, nelem](A, B)
+
+ # When this test was originally written it used
+ # assertTrue(np.allclose(...), which has different default tolerance
+ # values to assert_allclose. The tolerance values here are chosen as
+ # the tightest under which the tests will pass.
+ if npdtype == np.float64:
+ rtol = 1e-13
+ elif npdtype == np.float32:
+ rtol = 1e-6
+ else:
+ rtol = 1e-3
+ np.testing.assert_allclose(npfunc(A), B, rtol=rtol)
+
+ def unary_bool_special_values(self, func, npfunc, npdtype, npmtype):
+ fi = np.finfo(npdtype)
+ denorm = fi.tiny / 4
+ A = np.array([0., denorm, fi.tiny, 0.5, 1., fi.max, np.inf, np.nan],
+ dtype=npdtype)
+ B = np.empty_like(A, dtype=np.int32)
+ cfunc = cuda.jit((npmtype[::1], int32[::1]))(func)
+
+ cfunc[1, A.size](A, B)
+ np.testing.assert_array_equal(B, npfunc(A))
+
+ cfunc[1, A.size](-A, B)
+ np.testing.assert_array_equal(B, npfunc(-A))
+
+ def unary_bool_special_values_float32(self, func, npfunc):
+ self.unary_bool_special_values(func, npfunc, np.float32, float32)
+
+ def unary_bool_special_values_float64(self, func, npfunc):
+ self.unary_bool_special_values(func, npfunc, np.float64, float64)
+
+ def unary_bool_template_float32(self, func, npfunc, start=0, stop=1):
+ self.unary_template(func, npfunc, np.float32, np.float32, start, stop)
+
+ def unary_bool_template_float64(self, func, npfunc, start=0, stop=1):
+ self.unary_template(func, npfunc, np.float64, np.float64, start, stop)
+
+ def unary_bool_template_int32(self, func, npfunc, start=0, stop=49):
+ self.unary_template(func, npfunc, np.int32, np.int32, start, stop)
+
+ def unary_bool_template_int64(self, func, npfunc, start=0, stop=49):
+ self.unary_template(func, npfunc, np.int64, np.int64, start, stop)
+
+ def unary_bool_template(self, func, npfunc, npdtype, npmtype, start, stop):
+ nelem = 50
+ A = np.linspace(start, stop, nelem).astype(npdtype)
+ B = np.empty(A.shape, dtype=np.int32)
+ iarytype = npmtype[::1]
+ oarytype = int32[::1]
+ cfunc = cuda.jit((iarytype, oarytype))(func)
+ cfunc[1, nelem](A, B)
+ np.testing.assert_allclose(npfunc(A), B)
+
+ def binary_template_float32(self, func, npfunc, start=0, stop=1):
+ self.binary_template(func, npfunc, np.float32, np.float32, start, stop)
+
+ def binary_template_float64(self, func, npfunc, start=0, stop=1):
+ self.binary_template(func, npfunc, np.float64, np.float64, start, stop)
+
+ def binary_template_int64(self, func, npfunc, start=0, stop=50):
+ self.binary_template(func, npfunc, np.int64, np.float64, start, stop)
+
+ def binary_template_uint64(self, func, npfunc, start=0, stop=50):
+ self.binary_template(func, npfunc, np.uint64, np.float64, start, stop)
+
+ def binary_template(self, func, npfunc, npdtype, nprestype, start, stop):
+ nelem = 50
+ A = np.linspace(start, stop, nelem).astype(npdtype)
+ B = np.empty_like(A).astype(nprestype)
+ arytype = numpy_support.from_dtype(npdtype)[::1]
+ restype = numpy_support.from_dtype(nprestype)[::1]
+ cfunc = cuda.jit((arytype, arytype, restype))(func)
+ cfunc[1, nelem](A, A, B)
+ np.testing.assert_allclose(npfunc(A, A), B)
+
+ #---------------------------------------------------------------------------
+ # test_math_acos
+
+ def test_math_acos(self):
+ self.unary_template_float32(math_acos, np.arccos)
+ self.unary_template_float64(math_acos, np.arccos)
+ # For integers we can only test with zero, since <=-1 and >=1 result in
+ # invalid values.
+ self.unary_template_int64(math_acos, np.arccos, start=0, stop=0)
+ self.unary_template_uint64(math_acos, np.arccos, start=0, stop=0)
+
+ #---------------------------------------------------------------------------
+ # test_math_asin
+
+ def test_math_asin(self):
+ self.unary_template_float32(math_asin, np.arcsin)
+ self.unary_template_float64(math_asin, np.arcsin)
+ # For integers we can only test with zero, since <=-1 and >=1 result in
+ # invalid values.
+ self.unary_template_int64(math_asin, np.arcsin, start=0, stop=0)
+ self.unary_template_uint64(math_asin, np.arcsin, start=0, stop=0)
+
+ #---------------------------------------------------------------------------
+ # test_math_atan
+
+ def test_math_atan(self):
+ self.unary_template_float32(math_atan, np.arctan)
+ self.unary_template_float64(math_atan, np.arctan)
+ self.unary_template_int64(math_atan, np.arctan)
+ self.unary_template_uint64(math_atan, np.arctan)
+
+ #---------------------------------------------------------------------------
+ # test_math_acosh
+
+ def test_math_acosh(self):
+ self.unary_template_float32(math_acosh, np.arccosh, start=1, stop=2)
+ self.unary_template_float64(math_acosh, np.arccosh, start=1, stop=2)
+ self.unary_template_int64(math_acosh, np.arccosh, start=1, stop=2)
+ self.unary_template_uint64(math_acosh, np.arccosh, start=1, stop=2)
+
+ #---------------------------------------------------------------------------
+ # test_math_asinh
+
+ def test_math_asinh(self):
+ self.unary_template_float32(math_asinh, np.arcsinh)
+ self.unary_template_float64(math_asinh, np.arcsinh)
+ self.unary_template_int64(math_asinh, np.arcsinh)
+ self.unary_template_uint64(math_asinh, np.arcsinh)
+
+ #---------------------------------------------------------------------------
+ # test_math_atanh
+
+ def test_math_atanh(self):
+ self.unary_template_float32(math_atanh, np.arctanh, start=0, stop=.9)
+ self.unary_template_float64(math_atanh, np.arctanh, start=0, stop=.9)
+ self.unary_template_int64(math_atanh, np.arctanh, start=0, stop=.9)
+ self.unary_template_uint64(math_atanh, np.arctanh, start=0, stop=.9)
+
+ #---------------------------------------------------------------------------
+ # test_math_cos
+
+ def test_math_cos(self):
+ self.unary_template_float32(math_cos, np.cos)
+ self.unary_template_float64(math_cos, np.cos)
+ self.unary_template_int64(math_cos, np.cos)
+ self.unary_template_uint64(math_cos, np.cos)
+
+ @skip_unless_cc_53
+ def test_math_fp16(self):
+ self.unary_template_float16(math_sin, np.sin)
+ self.unary_template_float16(math_cos, np.cos)
+ self.unary_template_float16(math_exp, np.exp)
+ self.unary_template_float16(math_log, np.log, start=1)
+ self.unary_template_float16(math_log2, np.log2, start=1)
+ self.unary_template_float16(math_log10, np.log10, start=1)
+ self.unary_template_float16(math_fabs, np.fabs, start=-1)
+ self.unary_template_float16(math_sqrt, np.sqrt)
+ self.unary_template_float16(math_ceil, np.ceil)
+ self.unary_template_float16(math_floor, np.floor)
+
+ @skip_on_cudasim("numpy does not support trunc for float16")
+ @skip_unless_cc_53
+ def test_math_fp16_trunc(self):
+ self.unary_template_float16(math_trunc, np.trunc)
+
+ #---------------------------------------------------------------------------
+ # test_math_sin
+
+ def test_math_sin(self):
+ self.unary_template_float32(math_sin, np.sin)
+ self.unary_template_float64(math_sin, np.sin)
+ self.unary_template_int64(math_sin, np.sin)
+ self.unary_template_uint64(math_sin, np.sin)
+
+ #---------------------------------------------------------------------------
+ # test_math_tan
+
+ def test_math_tan(self):
+ self.unary_template_float32(math_tan, np.tan)
+ self.unary_template_float64(math_tan, np.tan)
+ self.unary_template_int64(math_tan, np.tan)
+ self.unary_template_uint64(math_tan, np.tan)
+
+ #---------------------------------------------------------------------------
+ # test_math_cosh
+
+ def test_math_cosh(self):
+ self.unary_template_float32(math_cosh, np.cosh)
+ self.unary_template_float64(math_cosh, np.cosh)
+ self.unary_template_int64(math_cosh, np.cosh)
+ self.unary_template_uint64(math_cosh, np.cosh)
+
+ #---------------------------------------------------------------------------
+ # test_math_sinh
+
+ def test_math_sinh(self):
+ self.unary_template_float32(math_sinh, np.sinh)
+ self.unary_template_float64(math_sinh, np.sinh)
+ self.unary_template_int64(math_sinh, np.sinh)
+ self.unary_template_uint64(math_sinh, np.sinh)
+
+ #---------------------------------------------------------------------------
+ # test_math_tanh
+
+ def test_math_tanh(self):
+ self.unary_template_float32(math_tanh, np.tanh)
+ self.unary_template_float64(math_tanh, np.tanh)
+ self.unary_template_int64(math_tanh, np.tanh)
+ self.unary_template_uint64(math_tanh, np.tanh)
+
+ #---------------------------------------------------------------------------
+ # test_math_atan2
+
+ def test_math_atan2(self):
+ self.binary_template_float32(math_atan2, np.arctan2)
+ self.binary_template_float64(math_atan2, np.arctan2)
+ self.binary_template_int64(math_atan2, np.arctan2)
+ self.binary_template_uint64(math_atan2, np.arctan2)
+
+ #---------------------------------------------------------------------------
+ # test_math_erf
+
+ def test_math_erf(self):
+ @vectorize
+ def ufunc(x):
+ return math.erf(x)
+ self.unary_template_float32(math_erf, ufunc)
+ self.unary_template_float64(math_erf, ufunc)
+ self.unary_template_int64(math_erf, ufunc)
+ self.unary_template_uint64(math_erf, ufunc)
+
+ #---------------------------------------------------------------------------
+ # test_math_erfc
+
+ def test_math_erfc(self):
+ @vectorize
+ def ufunc(x):
+ return math.erfc(x)
+ self.unary_template_float32(math_erfc, ufunc)
+ self.unary_template_float64(math_erfc, ufunc)
+ self.unary_template_int64(math_erfc, ufunc)
+ self.unary_template_uint64(math_erfc, ufunc)
+
+ #---------------------------------------------------------------------------
+ # test_math_exp
+
+ def test_math_exp(self):
+ self.unary_template_float32(math_exp, np.exp)
+ self.unary_template_float64(math_exp, np.exp)
+ self.unary_template_int64(math_exp, np.exp)
+ self.unary_template_uint64(math_exp, np.exp)
+
+ #---------------------------------------------------------------------------
+ # test_math_expm1
+
+ def test_math_expm1(self):
+ self.unary_template_float32(math_expm1, np.expm1)
+ self.unary_template_float64(math_expm1, np.expm1)
+ self.unary_template_int64(math_expm1, np.expm1)
+ self.unary_template_uint64(math_expm1, np.expm1)
+
+ #---------------------------------------------------------------------------
+ # test_math_fabs
+
+ def test_math_fabs(self):
+ self.unary_template_float32(math_fabs, np.fabs, start=-1)
+ self.unary_template_float64(math_fabs, np.fabs, start=-1)
+ self.unary_template_int64(math_fabs, np.fabs, start=-1)
+ self.unary_template_uint64(math_fabs, np.fabs, start=-1)
+
+ #---------------------------------------------------------------------------
+ # test_math_gamma
+
+ def test_math_gamma(self):
+ @vectorize
+ def ufunc(x):
+ return math.gamma(x)
+ self.unary_template_float32(math_gamma, ufunc, start=0.1)
+ self.unary_template_float64(math_gamma, ufunc, start=0.1)
+ self.unary_template_int64(math_gamma, ufunc, start=1)
+ self.unary_template_uint64(math_gamma, ufunc, start=1)
+
+ #---------------------------------------------------------------------------
+ # test_math_lgamma
+
+ def test_math_lgamma(self):
+ @vectorize
+ def ufunc(x):
+ return math.lgamma(x)
+ self.unary_template_float32(math_lgamma, ufunc, start=0.1)
+ self.unary_template_float64(math_lgamma, ufunc, start=0.1)
+ self.unary_template_int64(math_lgamma, ufunc, start=1)
+ self.unary_template_uint64(math_lgamma, ufunc, start=1)
+
+ #---------------------------------------------------------------------------
+ # test_math_log
+
+ def test_math_log(self):
+ self.unary_template_float32(math_log, np.log, start=1)
+ self.unary_template_float64(math_log, np.log, start=1)
+ self.unary_template_int64(math_log, np.log, start=1)
+ self.unary_template_uint64(math_log, np.log, start=1)
+
+ #---------------------------------------------------------------------------
+ # test_math_log2
+
+ def test_math_log2(self):
+ self.unary_template_float32(math_log2, np.log2, start=1)
+ self.unary_template_float64(math_log2, np.log2, start=1)
+ self.unary_template_int64(math_log2, np.log2, start=1)
+ self.unary_template_uint64(math_log2, np.log2, start=1)
+
+ #---------------------------------------------------------------------------
+ # test_math_log10
+
+ def test_math_log10(self):
+ self.unary_template_float32(math_log10, np.log10, start=1)
+ self.unary_template_float64(math_log10, np.log10, start=1)
+ self.unary_template_int64(math_log10, np.log10, start=1)
+ self.unary_template_uint64(math_log10, np.log10, start=1)
+
+ #---------------------------------------------------------------------------
+ # test_math_log1p
+
+ def test_math_log1p(self):
+ self.unary_template_float32(math_log1p, np.log1p)
+ self.unary_template_float64(math_log1p, np.log1p)
+ self.unary_template_int64(math_log1p, np.log1p)
+ self.unary_template_uint64(math_log1p, np.log1p)
+
+ #---------------------------------------------------------------------------
+ # test_math_remainder
+
+ def test_math_remainder(self):
+ self.binary_template_float32(math_remainder, np.remainder, start=1e-11)
+ self.binary_template_float64(math_remainder, np.remainder, start=1e-11)
+ self.binary_template_int64(math_remainder, np.remainder, start=1)
+ self.binary_template_uint64(math_remainder, np.remainder, start=1)
+
+ @skip_on_cudasim('math.remainder(0, 0) raises a ValueError on CUDASim')
+ def test_math_remainder_0_0(self):
+ @cuda.jit(void(float64[::1], int64, int64))
+ def test_0_0(r, x, y):
+ r[0] = math.remainder(x, y)
+ r = np.zeros(1, np.float64)
+ test_0_0[1, 1](r, 0, 0)
+ self.assertTrue(np.isnan(r[0]))
+
+ #---------------------------------------------------------------------------
+ # test_math_sqrt
+
+ def test_math_sqrt(self):
+ self.unary_template_float32(math_sqrt, np.sqrt)
+ self.unary_template_float64(math_sqrt, np.sqrt)
+ self.unary_template_int64(math_sqrt, np.sqrt)
+ self.unary_template_uint64(math_sqrt, np.sqrt)
+
+ #---------------------------------------------------------------------------
+ # test_math_hypot
+
+ def test_math_hypot(self):
+ self.binary_template_float32(math_hypot, np.hypot)
+ self.binary_template_float64(math_hypot, np.hypot)
+ self.binary_template_int64(math_hypot, np.hypot)
+ self.binary_template_uint64(math_hypot, np.hypot)
+
+ #---------------------------------------------------------------------------
+ # test_math_pow
+
+ def pow_template_int32(self, npdtype):
+ nelem = 50
+ A = np.linspace(0, 25, nelem).astype(npdtype)
+ B = np.arange(nelem, dtype=np.int32)
+ C = np.empty_like(A)
+ arytype = numpy_support.from_dtype(npdtype)[::1]
+ cfunc = cuda.jit((arytype, int32[::1], arytype))(math_pow)
+ cfunc[1, nelem](A, B, C)
+
+ # NumPy casting rules result in a float64 output always, which doesn't
+ # match the overflow to inf of math.pow and libdevice.powi for large
+ # values of float32, so we compute the reference result with math.pow.
+ Cref = np.empty_like(A)
+ for i in range(len(A)):
+ Cref[i] = math.pow(A[i], B[i])
+ np.testing.assert_allclose(np.power(A, B).astype(npdtype), C, rtol=1e-6)
+
+ def test_math_pow(self):
+ self.binary_template_float32(math_pow, np.power)
+ self.binary_template_float64(math_pow, np.power)
+ self.pow_template_int32(np.float32)
+ self.pow_template_int32(np.float64)
+
+ #---------------------------------------------------------------------------
+ # test_math_pow_binop
+
+ def test_math_pow_binop(self):
+ self.binary_template_float32(math_pow_binop, np.power)
+ self.binary_template_float64(math_pow_binop, np.power)
+
+ #---------------------------------------------------------------------------
+ # test_math_ceil
+
+ def test_math_ceil(self):
+ self.unary_template_float32(math_ceil, np.ceil)
+ self.unary_template_float64(math_ceil, np.ceil)
+ self.unary_template_int64(math_ceil, np.ceil)
+ self.unary_template_uint64(math_ceil, np.ceil)
+
+ #---------------------------------------------------------------------------
+ # test_math_floor
+
+ def test_math_floor(self):
+ self.unary_template_float32(math_floor, np.floor)
+ self.unary_template_float64(math_floor, np.floor)
+ self.unary_template_int64(math_floor, np.floor)
+ self.unary_template_uint64(math_floor, np.floor)
+
+ #---------------------------------------------------------------------------
+ # test_math_trunc
+ #
+ # Note that math.trunc() is only supported on NumPy float64s, and not
+ # other float types or int types. See NumPy Issue #13375:
+ #
+ # - https://github.com/numpy/numpy/issues/13375 - "Add methods from the
+ # builtin float types to the numpy floating point types"
+
+ def test_math_trunc(self):
+ self.unary_template_float64(math_trunc, np.trunc)
+
+ @skip_on_cudasim('trunc only supported on NumPy float64')
+ def test_math_trunc_non_float64(self):
+ self.unary_template_float32(math_trunc, np.trunc)
+ self.unary_template_int64(math_trunc, np.trunc)
+ self.unary_template_uint64(math_trunc, np.trunc)
+
+ #---------------------------------------------------------------------------
+ # test_math_copysign
+
+ def test_math_copysign(self):
+ self.binary_template_float32(math_copysign, np.copysign, start=-1)
+ self.binary_template_float64(math_copysign, np.copysign, start=-1)
+
+ #---------------------------------------------------------------------------
+ # test_math_modf
+
+ def test_math_modf(self):
+ def modf_template_nan(dtype, arytype):
+ A = np.array([np.nan], dtype=dtype)
+ B = np.zeros_like(A)
+ C = np.zeros_like(A)
+ cfunc = cuda.jit((arytype, arytype, arytype))(math_modf)
+ cfunc[1, len(A)](A, B, C)
+ self.assertTrue(np.isnan(B))
+ self.assertTrue(np.isnan(C))
+
+ def modf_template_compare(A, dtype, arytype):
+ A = A.astype(dtype)
+ B = np.zeros_like(A)
+ C = np.zeros_like(A)
+ cfunc = cuda.jit((arytype, arytype, arytype))(math_modf)
+ cfunc[1, len(A)](A, B, C)
+ D, E = np.modf(A)
+ self.assertTrue(np.array_equal(B,D))
+ self.assertTrue(np.array_equal(C,E))
+
+ nelem = 50
+ #32 bit float
+ with self.subTest("float32 modf on simple float"):
+ modf_template_compare(np.linspace(0, 10, nelem), dtype=np.float32,
+ arytype=float32[:])
+ with self.subTest("float32 modf on +- infinity"):
+ modf_template_compare(np.array([np.inf, -np.inf]), dtype=np.float32,
+ arytype=float32[:])
+ with self.subTest("float32 modf on nan"):
+ modf_template_nan(dtype=np.float32, arytype=float32[:])
+
+ #64 bit float
+ with self.subTest("float64 modf on simple float"):
+ modf_template_compare(np.linspace(0, 10, nelem), dtype=np.float64,
+ arytype=float64[:])
+ with self.subTest("float64 modf on +- infinity"):
+ modf_template_compare(np.array([np.inf, -np.inf]), dtype=np.float64,
+ arytype=float64[:])
+ with self.subTest("float64 modf on nan"):
+ modf_template_nan(dtype=np.float64, arytype=float64[:])
+
+ #---------------------------------------------------------------------------
+ # test_math_fmod
+
+ def test_math_fmod(self):
+ self.binary_template_float32(math_fmod, np.fmod, start=1)
+ self.binary_template_float64(math_fmod, np.fmod, start=1)
+
+ #---------------------------------------------------------------------------
+ # test_math_mod_binop
+
+ def test_math_mod_binop(self):
+ self.binary_template_float32(math_mod_binop, np.fmod, start=1)
+ self.binary_template_float64(math_mod_binop, np.fmod, start=1)
+
+ #---------------------------------------------------------------------------
+ # test_math_isnan
+
+ def test_math_isnan(self):
+ self.unary_bool_template_float32(math_isnan, np.isnan)
+ self.unary_bool_template_float64(math_isnan, np.isnan)
+ self.unary_bool_template_int32(math_isnan, np.isnan)
+ self.unary_bool_template_int64(math_isnan, np.isnan)
+ self.unary_bool_special_values_float32(math_isnan, np.isnan)
+ self.unary_bool_special_values_float64(math_isnan, np.isnan)
+
+ #---------------------------------------------------------------------------
+ # test_math_isinf
+
+ def test_math_isinf(self):
+ self.unary_bool_template_float32(math_isinf, np.isinf)
+ self.unary_bool_template_float64(math_isinf, np.isinf)
+ self.unary_bool_template_int32(math_isinf, np.isinf)
+ self.unary_bool_template_int64(math_isinf, np.isinf)
+ self.unary_bool_special_values_float32(math_isinf, np.isinf)
+ self.unary_bool_special_values_float64(math_isinf, np.isinf)
+
+ #---------------------------------------------------------------------------
+ # test_math_isfinite
+
+ def test_math_isfinite(self):
+ self.unary_bool_template_float32(math_isfinite, np.isfinite)
+ self.unary_bool_template_float64(math_isfinite, np.isfinite)
+ self.unary_bool_template_int32(math_isfinite, np.isfinite)
+ self.unary_bool_template_int64(math_isfinite, np.isfinite)
+ self.unary_bool_special_values_float32(math_isfinite, np.isfinite)
+ self.unary_bool_special_values_float64(math_isfinite, np.isfinite)
+
+ #---------------------------------------------------------------------------
+ # test_math_degrees
+
+ def test_math_degrees(self):
+ self.unary_bool_template_float32(math_degrees, np.degrees)
+ self.unary_bool_template_float64(math_degrees, np.degrees)
+
+ #---------------------------------------------------------------------------
+ # test_math_radians
+
+ def test_math_radians(self):
+ self.unary_bool_template_float32(math_radians, np.radians)
+ self.unary_bool_template_float64(math_radians, np.radians)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_matmul.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_matmul.py
new file mode 100644
index 0000000000000000000000000000000000000000..51f1181a3a8ad46c38708eb215dfa26570354ab1
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_matmul.py
@@ -0,0 +1,74 @@
+import numpy as np
+
+from numba import cuda, float32, void
+from numba.cuda.testing import unittest, CUDATestCase
+from numba.core import config
+
+# Ensure the test takes a reasonable amount of time in the simulator
+if config.ENABLE_CUDASIM:
+ bpg, tpb = 2, 8
+else:
+ bpg, tpb = 50, 32
+
+n = bpg * tpb
+SM_SIZE = (tpb, tpb)
+
+
+class TestCudaMatMul(CUDATestCase):
+
+ def test_func(self):
+
+ @cuda.jit(void(float32[:, ::1], float32[:, ::1], float32[:, ::1]))
+ def cu_square_matrix_mul(A, B, C):
+ sA = cuda.shared.array(shape=SM_SIZE, dtype=float32)
+ sB = cuda.shared.array(shape=(tpb, tpb), dtype=float32)
+
+ tx = cuda.threadIdx.x
+ ty = cuda.threadIdx.y
+ bx = cuda.blockIdx.x
+ by = cuda.blockIdx.y
+ bw = cuda.blockDim.x
+ bh = cuda.blockDim.y
+
+ x = tx + bx * bw
+ y = ty + by * bh
+
+ acc = float32(0) # forces all the math to be f32
+ for i in range(bpg):
+ if x < n and y < n:
+ sA[ty, tx] = A[y, tx + i * tpb]
+ sB[ty, tx] = B[ty + i * tpb, x]
+
+ cuda.syncthreads()
+
+ if x < n and y < n:
+ for j in range(tpb):
+ acc += sA[ty, j] * sB[j, tx]
+
+ cuda.syncthreads()
+
+ if x < n and y < n:
+ C[y, x] = acc
+
+ np.random.seed(42)
+ A = np.array(np.random.random((n, n)), dtype=np.float32)
+ B = np.array(np.random.random((n, n)), dtype=np.float32)
+ C = np.empty_like(A)
+
+ stream = cuda.stream()
+ with stream.auto_synchronize():
+ dA = cuda.to_device(A, stream)
+ dB = cuda.to_device(B, stream)
+ dC = cuda.to_device(C, stream)
+ cu_square_matrix_mul[(bpg, bpg), (tpb, tpb), stream](dA, dB, dC)
+ dC.copy_to_host(C, stream)
+
+ # Host compute
+ Cans = np.dot(A, B)
+
+ # Check result
+ np.testing.assert_allclose(C, Cans, rtol=1e-5)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_minmax.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_minmax.py
new file mode 100644
index 0000000000000000000000000000000000000000..aee97fd63e0c7a2dfb7b4bf2280d86ea39d6e260
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_minmax.py
@@ -0,0 +1,113 @@
+import numpy as np
+
+from numba import cuda, float64
+from numba.cuda.testing import unittest, CUDATestCase, skip_on_cudasim
+
+
+def builtin_max(A, B, C):
+ i = cuda.grid(1)
+
+ if i >= len(C):
+ return
+
+ C[i] = float64(max(A[i], B[i]))
+
+
+def builtin_min(A, B, C):
+ i = cuda.grid(1)
+
+ if i >= len(C):
+ return
+
+ C[i] = float64(min(A[i], B[i]))
+
+
+@skip_on_cudasim('Tests PTX emission')
+class TestCudaMinMax(CUDATestCase):
+ def _run(
+ self,
+ kernel,
+ numpy_equivalent,
+ ptx_instruction,
+ dtype_left,
+ dtype_right,
+ n=5):
+ kernel = cuda.jit(kernel)
+
+ c = np.zeros(n, dtype=np.float64)
+ a = np.arange(n, dtype=dtype_left) + .5
+ b = np.full(n, fill_value=2, dtype=dtype_right)
+
+ kernel[1, c.shape](a, b, c)
+ np.testing.assert_allclose(c, numpy_equivalent(a, b))
+
+ ptx = next(p for p in kernel.inspect_asm().values())
+ self.assertIn(ptx_instruction, ptx)
+
+ def test_max_f8f8(self):
+ self._run(
+ builtin_max,
+ np.maximum,
+ 'max.f64',
+ np.float64,
+ np.float64)
+
+ def test_max_f4f8(self):
+ self._run(
+ builtin_max,
+ np.maximum,
+ 'max.f64',
+ np.float32,
+ np.float64)
+
+ def test_max_f8f4(self):
+ self._run(
+ builtin_max,
+ np.maximum,
+ 'max.f64',
+ np.float64,
+ np.float32)
+
+ def test_max_f4f4(self):
+ self._run(
+ builtin_max,
+ np.maximum,
+ 'max.f32',
+ np.float32,
+ np.float32)
+
+ def test_min_f8f8(self):
+ self._run(
+ builtin_min,
+ np.minimum,
+ 'min.f64',
+ np.float64,
+ np.float64)
+
+ def test_min_f4f8(self):
+ self._run(
+ builtin_min,
+ np.minimum,
+ 'min.f64',
+ np.float32,
+ np.float64)
+
+ def test_min_f8f4(self):
+ self._run(
+ builtin_min,
+ np.minimum,
+ 'min.f64',
+ np.float64,
+ np.float32)
+
+ def test_min_f4f4(self):
+ self._run(
+ builtin_min,
+ np.minimum,
+ 'min.f32',
+ np.float32,
+ np.float32)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_montecarlo.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_montecarlo.py
new file mode 100644
index 0000000000000000000000000000000000000000..181a80a69dd05bcd0f77c518ddd683539c67fc74
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_montecarlo.py
@@ -0,0 +1,22 @@
+import math
+from numba import cuda
+from numba.cuda.testing import unittest, CUDATestCase
+
+
+class TestCudaMonteCarlo(CUDATestCase):
+ def test_montecarlo(self):
+ """Just make sure we can compile this
+ """
+
+ @cuda.jit(
+ 'void(double[:], double[:], double, double, double, double[:])')
+ def step(last, paths, dt, c0, c1, normdist):
+ i = cuda.grid(1)
+ if i >= paths.shape[0]:
+ return
+ noise = normdist[i]
+ paths[i] = last[i] * math.exp(c0 * dt + c1 * noise)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_multigpu.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_multigpu.py
new file mode 100644
index 0000000000000000000000000000000000000000..01b8a63ea3678badaf4a2661f6381111454544c6
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_multigpu.py
@@ -0,0 +1,140 @@
+from numba import cuda
+import numpy as np
+from numba.cuda.testing import skip_on_cudasim, CUDATestCase
+import threading
+import unittest
+
+
+class TestMultiGPUContext(CUDATestCase):
+ @unittest.skipIf(len(cuda.gpus) < 2, "need more than 1 gpus")
+ def test_multigpu_context(self):
+ @cuda.jit("void(float64[:], float64[:])")
+ def copy_plus_1(inp, out):
+ i = cuda.grid(1)
+ if i < out.size:
+ out[i] = inp[i] + 1
+
+ def check(inp, out):
+ np.testing.assert_equal(inp + 1, out)
+
+ N = 32
+ A = np.arange(N, dtype=np.float64)
+ B = np.arange(N, dtype=np.float64)
+
+ with cuda.gpus[0]:
+ copy_plus_1[1, N](A, B)
+
+ check(A, B)
+
+ copy_plus_1[1, N](A, B)
+ check(A, B)
+
+ with cuda.gpus[0]:
+ A0 = np.arange(N, dtype=np.float64)
+ B0 = np.arange(N, dtype=np.float64)
+ copy_plus_1[1, N](A0, B0)
+
+ with cuda.gpus[1]:
+ A1 = np.arange(N, dtype=np.float64)
+ B1 = np.arange(N, dtype=np.float64)
+ copy_plus_1[1, N](A1, B1)
+
+ check(A0, B0)
+ check(A1, B1)
+
+ A = np.arange(N, dtype=np.float64)
+ B = np.arange(N, dtype=np.float64)
+ copy_plus_1[1, N](A, B)
+ check(A, B)
+
+ @skip_on_cudasim('Simulator does not support multiple threads')
+ def test_multithreaded(self):
+ def work(gpu, dA, results, ridx):
+ try:
+ with gpu:
+ arr = dA.copy_to_host()
+
+ except Exception as e:
+ results[ridx] = e
+
+ else:
+ results[ridx] = np.all(arr == np.arange(10))
+
+ dA = cuda.to_device(np.arange(10))
+
+ nthreads = 10
+ results = [None] * nthreads
+ threads = [threading.Thread(target=work, args=(cuda.gpus.current,
+ dA, results, i))
+ for i in range(nthreads)]
+ for th in threads:
+ th.start()
+
+ for th in threads:
+ th.join()
+
+ for r in results:
+ if isinstance(r, BaseException):
+ raise r
+ else:
+ self.assertTrue(r)
+
+ @unittest.skipIf(len(cuda.gpus) < 2, "need more than 1 gpus")
+ def test_with_context(self):
+
+ @cuda.jit
+ def vector_add_scalar(arr, val):
+ i = cuda.grid(1)
+ if i < arr.size:
+ arr[i] += val
+
+ hostarr = np.arange(10, dtype=np.float32)
+ with cuda.gpus[0]:
+ arr1 = cuda.to_device(hostarr)
+
+ with cuda.gpus[1]:
+ arr2 = cuda.to_device(hostarr)
+
+ with cuda.gpus[0]:
+ vector_add_scalar[1, 10](arr1, 1)
+
+ with cuda.gpus[1]:
+ vector_add_scalar[1, 10](arr2, 2)
+
+ with cuda.gpus[0]:
+ np.testing.assert_equal(arr1.copy_to_host(), (hostarr + 1))
+
+ with cuda.gpus[1]:
+ np.testing.assert_equal(arr2.copy_to_host(), (hostarr + 2))
+
+ @unittest.skipIf(len(cuda.gpus) < 2, "need more than 1 gpus")
+ def test_with_context_peer_copy(self):
+ # Peer access is not always possible - for example, with one GPU in TCC
+ # mode and one in WDDM - if that is the case, this test would fail so
+ # we need to skip it.
+ with cuda.gpus[0]:
+ ctx = cuda.current_context()
+ if not ctx.can_access_peer(1):
+ self.skipTest('Peer access between GPUs disabled')
+
+ # 1. Create a range in an array
+ hostarr = np.arange(10, dtype=np.float32)
+
+ # 2. Copy range array from host -> GPU 0
+ with cuda.gpus[0]:
+ arr1 = cuda.to_device(hostarr)
+
+ # 3. Initialize a zero-filled array on GPU 1
+ with cuda.gpus[1]:
+ arr2 = cuda.to_device(np.zeros_like(hostarr))
+
+ with cuda.gpus[0]:
+ # 4. Copy range from GPU 0 -> GPU 1
+ arr2.copy_to_device(arr1)
+
+ # 5. Copy range from GPU 1 -> host and check contents
+ np.testing.assert_equal(arr2.copy_to_host(), hostarr)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_multiprocessing.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_multiprocessing.py
new file mode 100644
index 0000000000000000000000000000000000000000..04a1234b471309574d7e94a8776be9d68a8d97a1
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_multiprocessing.py
@@ -0,0 +1,46 @@
+import os
+import multiprocessing as mp
+
+import numpy as np
+
+from numba import cuda
+from numba.cuda.testing import skip_on_cudasim, CUDATestCase
+import unittest
+
+has_mp_get_context = hasattr(mp, 'get_context')
+is_unix = os.name == 'posix'
+
+
+def fork_test(q):
+ from numba.cuda.cudadrv.error import CudaDriverError
+ try:
+ cuda.to_device(np.arange(1))
+ except CudaDriverError as e:
+ q.put(e)
+ else:
+ q.put(None)
+
+
+@skip_on_cudasim('disabled for cudasim')
+class TestMultiprocessing(CUDATestCase):
+ @unittest.skipUnless(has_mp_get_context, 'requires mp.get_context')
+ @unittest.skipUnless(is_unix, 'requires Unix')
+ def test_fork(self):
+ """
+ Test fork detection.
+ """
+ cuda.current_context() # force cuda initialize
+ # fork in process that also uses CUDA
+ ctx = mp.get_context('fork')
+ q = ctx.Queue()
+ proc = ctx.Process(target=fork_test, args=[q])
+ proc.start()
+ exc = q.get()
+ proc.join()
+ # there should be an exception raised in the child process
+ self.assertIsNotNone(exc)
+ self.assertIn('CUDA initialized before forking', str(exc))
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_multithreads.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_multithreads.py
new file mode 100644
index 0000000000000000000000000000000000000000..30afd3eb0cb4d68d82078200a5612feffcf65b0f
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_multithreads.py
@@ -0,0 +1,101 @@
+import traceback
+import threading
+import multiprocessing
+import numpy as np
+from numba import cuda
+from numba.cuda.testing import (skip_on_cudasim, skip_under_cuda_memcheck,
+ CUDATestCase)
+import unittest
+
+try:
+ from concurrent.futures import ThreadPoolExecutor
+except ImportError:
+ has_concurrent_futures = False
+else:
+ has_concurrent_futures = True
+
+
+has_mp_get_context = hasattr(multiprocessing, 'get_context')
+
+
+def check_concurrent_compiling():
+ @cuda.jit
+ def foo(x):
+ x[0] += 1
+
+ def use_foo(x):
+ foo[1, 1](x)
+ return x
+
+ arrays = [cuda.to_device(np.arange(10)) for i in range(10)]
+ expected = np.arange(10)
+ expected[0] += 1
+ with ThreadPoolExecutor(max_workers=4) as e:
+ for ary in e.map(use_foo, arrays):
+ np.testing.assert_equal(ary, expected)
+
+
+def spawn_process_entry(q):
+ try:
+ check_concurrent_compiling()
+ # Catch anything that goes wrong in the threads
+ except: # noqa: E722
+ msg = traceback.format_exc()
+ q.put('\n'.join(['', '=' * 80, msg]))
+ else:
+ q.put(None)
+
+
+@skip_under_cuda_memcheck('Hangs cuda-memcheck')
+@skip_on_cudasim('disabled for cudasim')
+class TestMultiThreadCompiling(CUDATestCase):
+
+ @unittest.skipIf(not has_concurrent_futures, "no concurrent.futures")
+ def test_concurrent_compiling(self):
+ check_concurrent_compiling()
+
+ @unittest.skipIf(not has_mp_get_context, "no multiprocessing.get_context")
+ def test_spawn_concurrent_compilation(self):
+ # force CUDA context init
+ cuda.get_current_device()
+ # use "spawn" to avoid inheriting the CUDA context
+ ctx = multiprocessing.get_context('spawn')
+
+ q = ctx.Queue()
+ p = ctx.Process(target=spawn_process_entry, args=(q,))
+ p.start()
+ try:
+ err = q.get()
+ finally:
+ p.join()
+ if err is not None:
+ raise AssertionError(err)
+ self.assertEqual(p.exitcode, 0, 'test failed in child process')
+
+ def test_invalid_context_error_with_d2h(self):
+ def d2h(arr, out):
+ out[:] = arr.copy_to_host()
+
+ arr = np.arange(1, 4)
+ out = np.zeros_like(arr)
+ darr = cuda.to_device(arr)
+ th = threading.Thread(target=d2h, args=[darr, out])
+ th.start()
+ th.join()
+ np.testing.assert_equal(arr, out)
+
+ def test_invalid_context_error_with_d2d(self):
+ def d2d(dst, src):
+ dst.copy_to_device(src)
+
+ arr = np.arange(100)
+ common = cuda.to_device(arr)
+ darr = cuda.to_device(np.zeros(common.shape, dtype=common.dtype))
+ th = threading.Thread(target=d2d, args=[darr, common])
+ th.start()
+ th.join()
+ np.testing.assert_equal(darr.copy_to_host(), arr)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_nondet.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_nondet.py
new file mode 100644
index 0000000000000000000000000000000000000000..eaf141052aebd71e8b85926d0f9b7463169bdc94
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_nondet.py
@@ -0,0 +1,49 @@
+import numpy as np
+from numba import cuda, float32, void
+from numba.cuda.testing import unittest, CUDATestCase
+
+
+def generate_input(n):
+ A = np.array(np.arange(n * n).reshape(n, n), dtype=np.float32)
+ B = np.array(np.arange(n) + 0, dtype=A.dtype)
+ return A, B
+
+
+class TestCudaNonDet(CUDATestCase):
+ def test_for_pre(self):
+ """Test issue with loop not running due to bad sign-extension at the for
+ loop precondition.
+ """
+
+ @cuda.jit(void(float32[:, :], float32[:, :], float32[:]))
+ def diagproduct(c, a, b):
+ startX, startY = cuda.grid(2)
+ gridX = cuda.gridDim.x * cuda.blockDim.x
+ gridY = cuda.gridDim.y * cuda.blockDim.y
+ height = c.shape[0]
+ width = c.shape[1]
+
+ for x in range(startX, width, (gridX)):
+ for y in range(startY, height, (gridY)):
+ c[y, x] = a[y, x] * b[x]
+
+ N = 8
+
+ A, B = generate_input(N)
+
+ F = np.empty(A.shape, dtype=A.dtype)
+
+ blockdim = (32, 8)
+ griddim = (1, 1)
+
+ dA = cuda.to_device(A)
+ dB = cuda.to_device(B)
+ dF = cuda.to_device(F, copy=False)
+ diagproduct[griddim, blockdim](dF, dA, dB)
+
+ E = np.dot(A, np.diag(B))
+ np.testing.assert_array_almost_equal(dF.copy_to_host(), E)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_operator.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_operator.py
new file mode 100644
index 0000000000000000000000000000000000000000..0547d55fe7bb434f94d02707eab64db010891794
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_operator.py
@@ -0,0 +1,401 @@
+import numpy as np
+from numba.cuda.testing import (unittest, CUDATestCase, skip_unless_cc_53,
+ skip_on_cudasim)
+from numba import cuda
+from numba.core.types import f2, b1
+from numba.cuda import compile_ptx
+import operator
+import itertools
+from numba.np.numpy_support import from_dtype
+
+
+def simple_fp16_div_scalar(ary, a, b):
+ ary[0] = a / b
+
+
+def simple_fp16add(ary, a, b):
+ ary[0] = a + b
+
+
+def simple_fp16_iadd(ary, a):
+ ary[0] += a
+
+
+def simple_fp16_isub(ary, a):
+ ary[0] -= a
+
+
+def simple_fp16_imul(ary, a):
+ ary[0] *= a
+
+
+def simple_fp16_idiv(ary, a):
+ ary[0] /= a
+
+
+def simple_fp16sub(ary, a, b):
+ ary[0] = a - b
+
+
+def simple_fp16mul(ary, a, b):
+ ary[0] = a * b
+
+
+def simple_fp16neg(ary, a):
+ ary[0] = -a
+
+
+def simple_fp16abs(ary, a):
+ ary[0] = abs(a)
+
+
+def simple_fp16_gt(ary, a, b):
+ ary[0] = a > b
+
+
+def simple_fp16_ge(ary, a, b):
+ ary[0] = a >= b
+
+
+def simple_fp16_lt(ary, a, b):
+ ary[0] = a < b
+
+
+def simple_fp16_le(ary, a, b):
+ ary[0] = a <= b
+
+
+def simple_fp16_eq(ary, a, b):
+ ary[0] = a == b
+
+
+def simple_fp16_ne(ary, a, b):
+ ary[0] = a != b
+
+
+@cuda.jit('b1(f2, f2)', device=True)
+def hlt_func_1(x, y):
+ return x < y
+
+
+@cuda.jit('b1(f2, f2)', device=True)
+def hlt_func_2(x, y):
+ return x < y
+
+
+def test_multiple_hcmp_1(r, a, b, c):
+ # float16 predicates used in two separate functions
+ r[0] = hlt_func_1(a, b) and hlt_func_2(b, c)
+
+
+def test_multiple_hcmp_2(r, a, b, c):
+ # The same float16 predicate used in the caller and callee
+ r[0] = hlt_func_1(a, b) and b < c
+
+
+def test_multiple_hcmp_3(r, a, b, c):
+ # Different float16 predicates used in the caller and callee
+ r[0] = hlt_func_1(a, b) and c >= b
+
+
+def test_multiple_hcmp_4(r, a, b, c):
+ # The same float16 predicates used twice in a function
+ r[0] = a < b and b < c
+
+
+def test_multiple_hcmp_5(r, a, b, c):
+ # Different float16 predicates used in a function
+ r[0] = a < b and c >= b
+
+
+class TestOperatorModule(CUDATestCase):
+ def setUp(self):
+ super().setUp()
+ np.random.seed(0)
+
+ """
+ Test if operator module is supported by the CUDA target.
+ """
+ def operator_template(self, op):
+ @cuda.jit
+ def foo(a, b):
+ i = 0
+ a[i] = op(a[i], b[i])
+
+ a = np.ones(1)
+ b = np.ones(1)
+ res = a.copy()
+ foo[1, 1](res, b)
+
+ np.testing.assert_equal(res, op(a, b))
+
+ def test_add(self):
+ self.operator_template(operator.add)
+
+ def test_sub(self):
+ self.operator_template(operator.sub)
+
+ def test_mul(self):
+ self.operator_template(operator.mul)
+
+ def test_truediv(self):
+ self.operator_template(operator.truediv)
+
+ def test_floordiv(self):
+ self.operator_template(operator.floordiv)
+
+ @skip_unless_cc_53
+ def test_fp16_binary(self):
+ functions = (simple_fp16add, simple_fp16sub, simple_fp16mul,
+ simple_fp16_div_scalar)
+ ops = (operator.add, operator.sub, operator.mul, operator.truediv)
+
+ for fn, op in zip(functions, ops):
+ with self.subTest(op=op):
+ kernel = cuda.jit("void(f2[:], f2, f2)")(fn)
+
+ got = np.zeros(1, dtype=np.float16)
+ arg1 = np.random.random(1).astype(np.float16)
+ arg2 = np.random.random(1).astype(np.float16)
+
+ kernel[1, 1](got, arg1[0], arg2[0])
+ expected = op(arg1, arg2)
+ np.testing.assert_allclose(got, expected)
+
+ @skip_on_cudasim('Compilation unsupported in the simulator')
+ def test_fp16_binary_ptx(self):
+ functions = (simple_fp16add, simple_fp16sub, simple_fp16mul)
+ instrs = ('add.f16', 'sub.f16', 'mul.f16')
+ args = (f2[:], f2, f2)
+ for fn, instr in zip(functions, instrs):
+ with self.subTest(instr=instr):
+ ptx, _ = compile_ptx(fn, args, cc=(5, 3))
+ self.assertIn(instr, ptx)
+
+ @skip_unless_cc_53
+ def test_mixed_fp16_binary_arithmetic(self):
+ functions = (simple_fp16add, simple_fp16sub, simple_fp16mul,
+ simple_fp16_div_scalar)
+ ops = (operator.add, operator.sub, operator.mul, operator.truediv)
+ types = (np.int8, np.int16, np.int32, np.int64,
+ np.float32, np.float64)
+ for (fn, op), ty in itertools.product(zip(functions, ops), types):
+ with self.subTest(op=op, ty=ty):
+ kernel = cuda.jit(fn)
+
+ arg1 = np.random.random(1).astype(np.float16)
+ arg2 = (np.random.random(1) * 100).astype(ty)
+ res_ty = np.result_type(np.float16, ty)
+
+ got = np.zeros(1, dtype=res_ty)
+ kernel[1, 1](got, arg1[0], arg2[0])
+ expected = op(arg1, arg2)
+ np.testing.assert_allclose(got, expected)
+
+ @skip_on_cudasim('Compilation unsupported in the simulator')
+ def test_fp16_inplace_binary_ptx(self):
+ functions = (simple_fp16_iadd, simple_fp16_isub, simple_fp16_imul)
+ instrs = ('add.f16', 'sub.f16', 'mul.f16')
+ args = (f2[:], f2)
+
+ for fn, instr in zip(functions, instrs):
+ with self.subTest(instr=instr):
+ ptx, _ = compile_ptx(fn, args, cc=(5, 3))
+ self.assertIn(instr, ptx)
+
+ @skip_unless_cc_53
+ def test_fp16_inplace_binary(self):
+ functions = (simple_fp16_iadd, simple_fp16_isub, simple_fp16_imul,
+ simple_fp16_idiv)
+ ops = (operator.iadd, operator.isub, operator.imul, operator.itruediv)
+
+ for fn, op in zip(functions, ops):
+ with self.subTest(op=op):
+ kernel = cuda.jit("void(f2[:], f2)")(fn)
+
+ got = np.random.random(1).astype(np.float16)
+ expected = got.copy()
+ arg = np.random.random(1).astype(np.float16)[0]
+ kernel[1, 1](got, arg)
+ op(expected, arg)
+ np.testing.assert_allclose(got, expected)
+
+ @skip_unless_cc_53
+ def test_fp16_unary(self):
+ functions = (simple_fp16neg, simple_fp16abs)
+ ops = (operator.neg, operator.abs)
+
+ for fn, op in zip(functions, ops):
+ with self.subTest(op=op):
+ kernel = cuda.jit("void(f2[:], f2)")(fn)
+
+ got = np.zeros(1, dtype=np.float16)
+ arg1 = np.random.random(1).astype(np.float16)
+
+ kernel[1, 1](got, arg1[0])
+ expected = op(arg1)
+ np.testing.assert_allclose(got, expected)
+
+ @skip_on_cudasim('Compilation unsupported in the simulator')
+ def test_fp16_neg_ptx(self):
+ args = (f2[:], f2)
+ ptx, _ = compile_ptx(simple_fp16neg, args, cc=(5, 3))
+ self.assertIn('neg.f16', ptx)
+
+ @skip_on_cudasim('Compilation unsupported in the simulator')
+ def test_fp16_abs_ptx(self):
+ args = (f2[:], f2)
+ ptx, _ = compile_ptx(simple_fp16abs, args, cc=(5, 3))
+
+ self.assertIn('abs.f16', ptx)
+
+ @skip_unless_cc_53
+ def test_fp16_comparison(self):
+ functions = (simple_fp16_gt, simple_fp16_ge,
+ simple_fp16_lt, simple_fp16_le,
+ simple_fp16_eq, simple_fp16_ne)
+ ops = (operator.gt, operator.ge, operator.lt, operator.le,
+ operator.eq, operator.ne)
+
+ for fn, op in zip(functions, ops):
+ with self.subTest(op=op):
+ kernel = cuda.jit("void(b1[:], f2, f2)")(fn)
+
+ got = np.zeros(1, dtype=np.bool_)
+ arg1 = np.random.random(1).astype(np.float16)
+ arg2 = np.random.random(1).astype(np.float16)
+
+ kernel[1, 1](got, arg1[0], arg2[0])
+ expected = op(arg1, arg2)
+ self.assertEqual(got[0], expected)
+
+ @skip_unless_cc_53
+ def test_mixed_fp16_comparison(self):
+ functions = (simple_fp16_gt, simple_fp16_ge,
+ simple_fp16_lt, simple_fp16_le,
+ simple_fp16_eq, simple_fp16_ne)
+ ops = (operator.gt, operator.ge, operator.lt, operator.le,
+ operator.eq, operator.ne)
+ types = (np.int8, np.int16, np.int32, np.int64,
+ np.float32, np.float64)
+
+ for (fn, op), ty in itertools.product(zip(functions, ops),
+ types):
+ with self.subTest(op=op, ty=ty):
+ kernel = cuda.jit(fn)
+
+ got = np.zeros(1, dtype=np.bool_)
+ arg1 = np.random.random(1).astype(np.float16)
+ arg2 = (np.random.random(1) * 100).astype(ty)
+
+ kernel[1, 1](got, arg1[0], arg2[0])
+ expected = op(arg1, arg2)
+ self.assertEqual(got[0], expected)
+
+ @skip_unless_cc_53
+ def test_multiple_float16_comparisons(self):
+ functions = (test_multiple_hcmp_1,
+ test_multiple_hcmp_2,
+ test_multiple_hcmp_3,
+ test_multiple_hcmp_4,
+ test_multiple_hcmp_5)
+ for fn in functions:
+ with self.subTest(fn=fn):
+ compiled = cuda.jit("void(b1[:], f2, f2, f2)")(fn)
+ ary = np.zeros(1, dtype=np.bool_)
+ arg1 = np.float16(2.)
+ arg2 = np.float16(3.)
+ arg3 = np.float16(4.)
+ compiled[1, 1](ary, arg1, arg2, arg3)
+ self.assertTrue(ary[0])
+
+ @skip_unless_cc_53
+ def test_multiple_float16_comparisons_false(self):
+ functions = (test_multiple_hcmp_1,
+ test_multiple_hcmp_2,
+ test_multiple_hcmp_3,
+ test_multiple_hcmp_4,
+ test_multiple_hcmp_5)
+ for fn in functions:
+ with self.subTest(fn=fn):
+ compiled = cuda.jit("void(b1[:], f2, f2, f2)")(fn)
+ ary = np.zeros(1, dtype=np.bool_)
+ arg1 = np.float16(2.)
+ arg2 = np.float16(3.)
+ arg3 = np.float16(1.)
+ compiled[1, 1](ary, arg1, arg2, arg3)
+ self.assertFalse(ary[0])
+
+ @skip_on_cudasim('Compilation unsupported in the simulator')
+ def test_fp16_comparison_ptx(self):
+ functions = (simple_fp16_gt, simple_fp16_ge,
+ simple_fp16_lt, simple_fp16_le,
+ simple_fp16_eq, simple_fp16_ne)
+ ops = (operator.gt, operator.ge, operator.lt, operator.le,
+ operator.eq, operator.ne)
+ opstring = ('setp.gt.f16', 'setp.ge.f16',
+ 'setp.lt.f16', 'setp.le.f16',
+ 'setp.eq.f16', 'setp.ne.f16')
+ args = (b1[:], f2, f2)
+
+ for fn, op, s in zip(functions, ops, opstring):
+ with self.subTest(op=op):
+ ptx, _ = compile_ptx(fn, args, cc=(5, 3))
+ self.assertIn(s, ptx)
+
+ @skip_on_cudasim('Compilation unsupported in the simulator')
+ def test_fp16_int8_comparison_ptx(self):
+ # Test that int8 can be safely converted to fp16
+ # in a comparison
+ functions = (simple_fp16_gt, simple_fp16_ge,
+ simple_fp16_lt, simple_fp16_le,
+ simple_fp16_eq, simple_fp16_ne)
+ ops = (operator.gt, operator.ge, operator.lt, operator.le,
+ operator.eq, operator.ne)
+
+ opstring = {operator.gt:'setp.gt.f16',
+ operator.ge:'setp.ge.f16',
+ operator.lt:'setp.lt.f16',
+ operator.le:'setp.le.f16',
+ operator.eq:'setp.eq.f16',
+ operator.ne:'setp.ne.f16'}
+ for fn, op in zip(functions, ops):
+ with self.subTest(op=op):
+ args = (b1[:], f2, from_dtype(np.int8))
+ ptx, _ = compile_ptx(fn, args, cc=(5, 3))
+ self.assertIn(opstring[op], ptx)
+
+ @skip_on_cudasim('Compilation unsupported in the simulator')
+ def test_mixed_fp16_comparison_promotion_ptx(self):
+ functions = (simple_fp16_gt, simple_fp16_ge,
+ simple_fp16_lt, simple_fp16_le,
+ simple_fp16_eq, simple_fp16_ne)
+ ops = (operator.gt, operator.ge, operator.lt, operator.le,
+ operator.eq, operator.ne)
+
+ types_promote = (np.int16, np.int32, np.int64,
+ np.float32, np.float64)
+ opstring = {operator.gt:'setp.gt.',
+ operator.ge:'setp.ge.',
+ operator.lt:'setp.lt.',
+ operator.le:'setp.le.',
+ operator.eq:'setp.eq.',
+ operator.ne:'setp.neu.'}
+ opsuffix = {np.dtype('int32'): 'f64',
+ np.dtype('int64'): 'f64',
+ np.dtype('float32'): 'f32',
+ np.dtype('float64'): 'f64'}
+
+ for (fn, op), ty in itertools.product(zip(functions, ops),
+ types_promote):
+ with self.subTest(op=op, ty=ty):
+ arg2_ty = np.result_type(np.float16, ty)
+ args = (b1[:], f2, from_dtype(arg2_ty))
+ ptx, _ = compile_ptx(fn, args, cc=(5, 3))
+
+ ops = opstring[op] + opsuffix[arg2_ty]
+ self.assertIn(ops, ptx)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_optimization.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_optimization.py
new file mode 100644
index 0000000000000000000000000000000000000000..812b1cfa35e658d4f730a5b22b1caa3cc4bab9b9
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_optimization.py
@@ -0,0 +1,86 @@
+import numpy as np
+
+from numba.cuda.testing import skip_on_cudasim, CUDATestCase
+from numba import cuda, float64
+import unittest
+
+
+def kernel_func(x):
+ x[0] = 1
+
+
+def device_func(x, y, z):
+ return x * y + z
+
+
+# Fragments of code that are removed from kernel_func's PTX when optimization
+# is on
+removed_by_opt = ( '__local_depot0', 'call.uni', 'st.param.b64')
+
+
+@skip_on_cudasim('Simulator does not optimize code')
+class TestOptimization(CUDATestCase):
+ def test_eager_opt(self):
+ # Optimization should occur by default
+ sig = (float64[::1],)
+ kernel = cuda.jit(sig)(kernel_func)
+ ptx = kernel.inspect_asm()
+
+ for fragment in removed_by_opt:
+ with self.subTest(fragment=fragment):
+ self.assertNotIn(fragment, ptx[sig])
+
+ def test_eager_noopt(self):
+ # Optimization disabled
+ sig = (float64[::1],)
+ kernel = cuda.jit(sig, opt=False)(kernel_func)
+ ptx = kernel.inspect_asm()
+
+ for fragment in removed_by_opt:
+ with self.subTest(fragment=fragment):
+ self.assertIn(fragment, ptx[sig])
+
+ def test_lazy_opt(self):
+ # Optimization should occur by default
+ kernel = cuda.jit(kernel_func)
+ x = np.zeros(1, dtype=np.float64)
+ kernel[1, 1](x)
+
+ # Grab the PTX for the one definition that has just been jitted
+ ptx = next(iter(kernel.inspect_asm().items()))[1]
+
+ for fragment in removed_by_opt:
+ with self.subTest(fragment=fragment):
+ self.assertNotIn(fragment, ptx)
+
+ def test_lazy_noopt(self):
+ # Optimization disabled
+ kernel = cuda.jit(opt=False)(kernel_func)
+ x = np.zeros(1, dtype=np.float64)
+ kernel[1, 1](x)
+
+ # Grab the PTX for the one definition that has just been jitted
+ ptx = next(iter(kernel.inspect_asm().items()))[1]
+
+ for fragment in removed_by_opt:
+ with self.subTest(fragment=fragment):
+ self.assertIn(fragment, ptx)
+
+ def test_device_opt(self):
+ # Optimization should occur by default
+ sig = (float64, float64, float64)
+ device = cuda.jit(sig, device=True)(device_func)
+ ptx = device.inspect_asm(sig)
+ self.assertIn('fma.rn.f64', ptx)
+
+ def test_device_noopt(self):
+ # Optimization disabled
+ sig = (float64, float64, float64)
+ device = cuda.jit(sig, device=True, opt=False)(device_func)
+ ptx = device.inspect_asm(sig)
+ # Fused-multiply adds should be disabled when not optimizing
+ self.assertNotIn('fma.rn.f64', ptx)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_overload.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_overload.py
new file mode 100644
index 0000000000000000000000000000000000000000..412fe2434ca9f1358c3a0d23e395d786ccd64d5f
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_overload.py
@@ -0,0 +1,327 @@
+from numba import cuda, njit, types
+from numba.core.errors import TypingError
+from numba.core.extending import overload, overload_attribute
+from numba.core.typing.typeof import typeof
+from numba.cuda.testing import CUDATestCase, skip_on_cudasim, unittest
+import numpy as np
+
+
+# Dummy function definitions to overload
+
+def generic_func_1():
+ pass
+
+
+def cuda_func_1():
+ pass
+
+
+def generic_func_2():
+ pass
+
+
+def cuda_func_2():
+ pass
+
+
+def generic_calls_generic():
+ pass
+
+
+def generic_calls_cuda():
+ pass
+
+
+def cuda_calls_generic():
+ pass
+
+
+def cuda_calls_cuda():
+ pass
+
+
+def target_overloaded():
+ pass
+
+
+def generic_calls_target_overloaded():
+ pass
+
+
+def cuda_calls_target_overloaded():
+ pass
+
+
+def target_overloaded_calls_target_overloaded():
+ pass
+
+
+# To recognise which functions are resolved for a call, we identify each with a
+# prime number. Each function called multiplies a value by its prime (starting
+# with the value 1), and we can check that the result is as expected based on
+# the final value after all multiplications.
+
+GENERIC_FUNCTION_1 = 2
+CUDA_FUNCTION_1 = 3
+GENERIC_FUNCTION_2 = 5
+CUDA_FUNCTION_2 = 7
+GENERIC_CALLS_GENERIC = 11
+GENERIC_CALLS_CUDA = 13
+CUDA_CALLS_GENERIC = 17
+CUDA_CALLS_CUDA = 19
+GENERIC_TARGET_OL = 23
+CUDA_TARGET_OL = 29
+GENERIC_CALLS_TARGET_OL = 31
+CUDA_CALLS_TARGET_OL = 37
+GENERIC_TARGET_OL_CALLS_TARGET_OL = 41
+CUDA_TARGET_OL_CALLS_TARGET_OL = 43
+
+
+# Overload implementations
+
+@overload(generic_func_1, target='generic')
+def ol_generic_func_1(x):
+ def impl(x):
+ x[0] *= GENERIC_FUNCTION_1
+ return impl
+
+
+@overload(cuda_func_1, target='cuda')
+def ol_cuda_func_1(x):
+ def impl(x):
+ x[0] *= CUDA_FUNCTION_1
+ return impl
+
+
+@overload(generic_func_2, target='generic')
+def ol_generic_func_2(x):
+ def impl(x):
+ x[0] *= GENERIC_FUNCTION_2
+ return impl
+
+
+@overload(cuda_func_2, target='cuda')
+def ol_cuda_func(x):
+ def impl(x):
+ x[0] *= CUDA_FUNCTION_2
+ return impl
+
+
+@overload(generic_calls_generic, target='generic')
+def ol_generic_calls_generic(x):
+ def impl(x):
+ x[0] *= GENERIC_CALLS_GENERIC
+ generic_func_1(x)
+ return impl
+
+
+@overload(generic_calls_cuda, target='generic')
+def ol_generic_calls_cuda(x):
+ def impl(x):
+ x[0] *= GENERIC_CALLS_CUDA
+ cuda_func_1(x)
+ return impl
+
+
+@overload(cuda_calls_generic, target='cuda')
+def ol_cuda_calls_generic(x):
+ def impl(x):
+ x[0] *= CUDA_CALLS_GENERIC
+ generic_func_1(x)
+ return impl
+
+
+@overload(cuda_calls_cuda, target='cuda')
+def ol_cuda_calls_cuda(x):
+ def impl(x):
+ x[0] *= CUDA_CALLS_CUDA
+ cuda_func_1(x)
+ return impl
+
+
+@overload(target_overloaded, target='generic')
+def ol_target_overloaded_generic(x):
+ def impl(x):
+ x[0] *= GENERIC_TARGET_OL
+ return impl
+
+
+@overload(target_overloaded, target='cuda')
+def ol_target_overloaded_cuda(x):
+ def impl(x):
+ x[0] *= CUDA_TARGET_OL
+ return impl
+
+
+@overload(generic_calls_target_overloaded, target='generic')
+def ol_generic_calls_target_overloaded(x):
+ def impl(x):
+ x[0] *= GENERIC_CALLS_TARGET_OL
+ target_overloaded(x)
+ return impl
+
+
+@overload(cuda_calls_target_overloaded, target='cuda')
+def ol_cuda_calls_target_overloaded(x):
+ def impl(x):
+ x[0] *= CUDA_CALLS_TARGET_OL
+ target_overloaded(x)
+ return impl
+
+
+@overload(target_overloaded_calls_target_overloaded, target='generic')
+def ol_generic_calls_target_overloaded_generic(x):
+ def impl(x):
+ x[0] *= GENERIC_TARGET_OL_CALLS_TARGET_OL
+ target_overloaded(x)
+ return impl
+
+
+@overload(target_overloaded_calls_target_overloaded, target='cuda')
+def ol_generic_calls_target_overloaded_cuda(x):
+ def impl(x):
+ x[0] *= CUDA_TARGET_OL_CALLS_TARGET_OL
+ target_overloaded(x)
+ return impl
+
+
+@skip_on_cudasim('Overloading not supported in cudasim')
+class TestOverload(CUDATestCase):
+ def check_overload(self, kernel, expected):
+ x = np.ones(1, dtype=np.int32)
+ cuda.jit(kernel)[1, 1](x)
+ self.assertEqual(x[0], expected)
+
+ def check_overload_cpu(self, kernel, expected):
+ x = np.ones(1, dtype=np.int32)
+ njit(kernel)(x)
+ self.assertEqual(x[0], expected)
+
+ def test_generic(self):
+ def kernel(x):
+ generic_func_1(x)
+
+ expected = GENERIC_FUNCTION_1
+ self.check_overload(kernel, expected)
+
+ def test_cuda(self):
+ def kernel(x):
+ cuda_func_1(x)
+
+ expected = CUDA_FUNCTION_1
+ self.check_overload(kernel, expected)
+
+ def test_generic_and_cuda(self):
+ def kernel(x):
+ generic_func_1(x)
+ cuda_func_1(x)
+
+ expected = GENERIC_FUNCTION_1 * CUDA_FUNCTION_1
+ self.check_overload(kernel, expected)
+
+ def test_call_two_generic_calls(self):
+ def kernel(x):
+ generic_func_1(x)
+ generic_func_2(x)
+
+ expected = GENERIC_FUNCTION_1 * GENERIC_FUNCTION_2
+ self.check_overload(kernel, expected)
+
+ def test_call_two_cuda_calls(self):
+ def kernel(x):
+ cuda_func_1(x)
+ cuda_func_2(x)
+
+ expected = CUDA_FUNCTION_1 * CUDA_FUNCTION_2
+ self.check_overload(kernel, expected)
+
+ def test_generic_calls_generic(self):
+ def kernel(x):
+ generic_calls_generic(x)
+
+ expected = GENERIC_CALLS_GENERIC * GENERIC_FUNCTION_1
+ self.check_overload(kernel, expected)
+
+ def test_generic_calls_cuda(self):
+ def kernel(x):
+ generic_calls_cuda(x)
+
+ expected = GENERIC_CALLS_CUDA * CUDA_FUNCTION_1
+ self.check_overload(kernel, expected)
+
+ def test_cuda_calls_generic(self):
+ def kernel(x):
+ cuda_calls_generic(x)
+
+ expected = CUDA_CALLS_GENERIC * GENERIC_FUNCTION_1
+ self.check_overload(kernel, expected)
+
+ def test_cuda_calls_cuda(self):
+ def kernel(x):
+ cuda_calls_cuda(x)
+
+ expected = CUDA_CALLS_CUDA * CUDA_FUNCTION_1
+ self.check_overload(kernel, expected)
+
+ def test_call_target_overloaded(self):
+ def kernel(x):
+ target_overloaded(x)
+
+ expected = CUDA_TARGET_OL
+ self.check_overload(kernel, expected)
+
+ def test_generic_calls_target_overloaded(self):
+ def kernel(x):
+ generic_calls_target_overloaded(x)
+
+ expected = GENERIC_CALLS_TARGET_OL * CUDA_TARGET_OL
+ self.check_overload(kernel, expected)
+
+ def test_cuda_calls_target_overloaded(self):
+ def kernel(x):
+ cuda_calls_target_overloaded(x)
+
+ expected = CUDA_CALLS_TARGET_OL * CUDA_TARGET_OL
+ self.check_overload(kernel, expected)
+
+ def test_target_overloaded_calls_target_overloaded(self):
+ def kernel(x):
+ target_overloaded_calls_target_overloaded(x)
+
+ # Check the CUDA overloads are used on CUDA
+ expected = CUDA_TARGET_OL_CALLS_TARGET_OL * CUDA_TARGET_OL
+ self.check_overload(kernel, expected)
+
+ # Also check that the CPU overloads are used on the CPU
+ expected = GENERIC_TARGET_OL_CALLS_TARGET_OL * GENERIC_TARGET_OL
+ self.check_overload_cpu(kernel, expected)
+
+ def test_overload_attribute_target(self):
+ MyDummy, MyDummyType = self.make_dummy_type()
+ mydummy_type = typeof(MyDummy())
+
+ @overload_attribute(MyDummyType, 'cuda_only', target='cuda')
+ def ov_dummy_cuda_attr(obj):
+ def imp(obj):
+ return 42
+
+ return imp
+
+ # Ensure that we cannot use the CUDA target-specific attribute on the
+ # CPU, and that an appropriate typing error is raised
+ with self.assertRaisesRegex(TypingError,
+ "Unknown attribute 'cuda_only'"):
+ @njit(types.int64(mydummy_type))
+ def illegal_target_attr_use(x):
+ return x.cuda_only
+
+ # Ensure that the CUDA target-specific attribute is usable and works
+ # correctly when the target is CUDA - note eager compilation via
+ # signature
+ @cuda.jit(types.void(types.int64[::1], mydummy_type))
+ def cuda_target_attr_use(res, dummy):
+ res[0] = dummy.cuda_only
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_powi.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_powi.py
new file mode 100644
index 0000000000000000000000000000000000000000..1932b31655516208a313d73ad55a7ca01eac9a5b
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_powi.py
@@ -0,0 +1,124 @@
+import math
+import numpy as np
+from numba import cuda, float64, int8, int32, void
+from numba.cuda.testing import unittest, CUDATestCase
+
+
+def cu_mat_power(A, power, power_A):
+ y, x = cuda.grid(2)
+
+ m, n = power_A.shape
+ if x >= n or y >= m:
+ return
+
+ power_A[y, x] = math.pow(A[y, x], int32(power))
+
+
+def cu_mat_power_binop(A, power, power_A):
+ y, x = cuda.grid(2)
+
+ m, n = power_A.shape
+ if x >= n or y >= m:
+ return
+
+ power_A[y, x] = A[y, x] ** power
+
+
+def vec_pow(r, x, y):
+ i = cuda.grid(1)
+
+ if i < len(r):
+ r[i] = pow(x[i], y[i])
+
+
+def vec_pow_binop(r, x, y):
+ i = cuda.grid(1)
+
+ if i < len(r):
+ r[i] = x[i] ** y[i]
+
+
+def vec_pow_inplace_binop(r, x):
+ i = cuda.grid(1)
+
+ if i < len(r):
+ r[i] **= x[i]
+
+
+def random_complex(N):
+ np.random.seed(123)
+ return (np.random.random(1) + np.random.random(1) * 1j)
+
+
+class TestCudaPowi(CUDATestCase):
+ def test_powi(self):
+ dec = cuda.jit(void(float64[:, :], int8, float64[:, :]))
+ kernel = dec(cu_mat_power)
+
+ power = 2
+ A = np.arange(10, dtype=np.float64).reshape(2, 5)
+ Aout = np.empty_like(A)
+ kernel[1, A.shape](A, power, Aout)
+ self.assertTrue(np.allclose(Aout, A ** power))
+
+ def test_powi_binop(self):
+ dec = cuda.jit(void(float64[:, :], int8, float64[:, :]))
+ kernel = dec(cu_mat_power_binop)
+
+ power = 2
+ A = np.arange(10, dtype=np.float64).reshape(2, 5)
+ Aout = np.empty_like(A)
+ kernel[1, A.shape](A, power, Aout)
+ self.assertTrue(np.allclose(Aout, A ** power))
+
+ # Relative tolerance kwarg is provided because 1.0e-7 (the default for
+ # assert_allclose) is a bit tight for single precision.
+ def _test_cpow(self, dtype, func, rtol=1.0e-7):
+ N = 32
+ x = random_complex(N).astype(dtype)
+ y = random_complex(N).astype(dtype)
+ r = np.zeros_like(x)
+
+ cfunc = cuda.jit(func)
+ cfunc[1, N](r, x, y)
+ np.testing.assert_allclose(r, x ** y, rtol=rtol)
+
+ # Checks special cases
+ x = np.asarray([0.0j, 1.0j], dtype=dtype)
+ y = np.asarray([0.0j, 1.0], dtype=dtype)
+ r = np.zeros_like(x)
+
+ cfunc[1, 2](r, x, y)
+ np.testing.assert_allclose(r, x ** y, rtol=rtol)
+
+ def test_cpow_complex64_pow(self):
+ self._test_cpow(np.complex64, vec_pow, rtol=3.0e-7)
+
+ def test_cpow_complex64_binop(self):
+ self._test_cpow(np.complex64, vec_pow_binop, rtol=3.0e-7)
+
+ def test_cpow_complex128_pow(self):
+ self._test_cpow(np.complex128, vec_pow)
+
+ def test_cpow_complex128_binop(self):
+ self._test_cpow(np.complex128, vec_pow_binop)
+
+ def _test_cpow_inplace_binop(self, dtype, rtol=1.0e-7):
+ N = 32
+ x = random_complex(N).astype(dtype)
+ y = random_complex(N).astype(dtype)
+ r = x ** y
+
+ cfunc = cuda.jit(vec_pow_inplace_binop)
+ cfunc[1, N](x, y)
+ np.testing.assert_allclose(x, r, rtol=rtol)
+
+ def test_cpow_complex64_inplace_binop(self):
+ self._test_cpow_inplace_binop(np.complex64, rtol=3.0e-7)
+
+ def test_cpow_complex128_inplace_binop(self):
+ self._test_cpow_inplace_binop(np.complex128, rtol=3.0e-7)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_print.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_print.py
new file mode 100644
index 0000000000000000000000000000000000000000..d8dca831a1ea455f9c29dd50d29f27dfd7720690
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_print.py
@@ -0,0 +1,128 @@
+from numba.cuda.testing import CUDATestCase, skip_on_cudasim
+import subprocess
+import sys
+import unittest
+
+
+cuhello_usecase = """\
+from numba import cuda
+
+@cuda.jit
+def cuhello():
+ i = cuda.grid(1)
+ print(i, 999)
+ print(-42)
+
+cuhello[2, 3]()
+cuda.synchronize()
+"""
+
+
+printfloat_usecase = """\
+from numba import cuda
+
+@cuda.jit
+def printfloat():
+ i = cuda.grid(1)
+ print(i, 23, 34.75, 321)
+
+printfloat[1, 1]()
+cuda.synchronize()
+"""
+
+
+printstring_usecase = """\
+from numba import cuda
+
+@cuda.jit
+def printstring():
+ i = cuda.grid(1)
+ print(i, "hop!", 999)
+
+printstring[1, 3]()
+cuda.synchronize()
+"""
+
+printempty_usecase = """\
+from numba import cuda
+
+@cuda.jit
+def printempty():
+ print()
+
+printempty[1, 1]()
+cuda.synchronize()
+"""
+
+
+print_too_many_usecase = """\
+from numba import cuda
+import numpy as np
+
+@cuda.jit
+def print_too_many(r):
+ print(r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9], r[10],
+ r[11], r[12], r[13], r[14], r[15], r[16], r[17], r[18], r[19], r[20],
+ r[21], r[22], r[23], r[24], r[25], r[26], r[27], r[28], r[29], r[30],
+ r[31], r[32])
+
+print_too_many[1, 1](np.arange(33))
+cuda.synchronize()
+"""
+
+
+class TestPrint(CUDATestCase):
+ # Note that in these tests we generally strip the output to avoid dealing
+ # with platform-specific line ending issues, e.g. '\r\n' vs '\n' etc.
+
+ def run_code(self, code):
+ """Runs code in a subprocess and returns the captured output"""
+ cmd = [sys.executable, "-c", code]
+ cp = subprocess.run(cmd, timeout=60, capture_output=True, check=True)
+ return cp.stdout.decode(), cp.stderr.decode()
+
+ def test_cuhello(self):
+ output, _ = self.run_code(cuhello_usecase)
+ actual = [line.strip() for line in output.splitlines()]
+ expected = ['-42'] * 6 + ['%d 999' % i for i in range(6)]
+ # The output of GPU threads is intermingled, but each print()
+ # call is still atomic
+ self.assertEqual(sorted(actual), expected)
+
+ def test_printfloat(self):
+ output, _ = self.run_code(printfloat_usecase)
+ # CUDA and the simulator use different formats for float formatting
+ expected_cases = ["0 23 34.750000 321", "0 23 34.75 321"]
+ self.assertIn(output.strip(), expected_cases)
+
+ def test_printempty(self):
+ output, _ = self.run_code(printempty_usecase)
+ self.assertEqual(output.strip(), "")
+
+ def test_string(self):
+ output, _ = self.run_code(printstring_usecase)
+ lines = [line.strip() for line in output.splitlines(True)]
+ expected = ['%d hop! 999' % i for i in range(3)]
+ self.assertEqual(sorted(lines), expected)
+
+ @skip_on_cudasim('cudasim can print unlimited output')
+ def test_too_many_args(self):
+ # Tests that we emit the format string and warn when there are more
+ # than 32 arguments, in common with CUDA C/C++ printf - this is due to
+ # a limitation in CUDA vprintf, see:
+ # https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#limitations
+
+ output, errors = self.run_code(print_too_many_usecase)
+
+ # Check that the format string was printed instead of formatted garbage
+ expected_fmt_string = ' '.join(['%lld' for _ in range(33)])
+ self.assertIn(expected_fmt_string, output)
+
+ # Check for the expected warning about formatting more than 32 items
+ warn_msg = ('CUDA print() cannot print more than 32 items. The raw '
+ 'format string will be emitted by the kernel instead.')
+ self.assertIn(warn_msg, errors)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_py2_div_issue.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_py2_div_issue.py
new file mode 100644
index 0000000000000000000000000000000000000000..298a5b74700afa53e8f989280da8d2c29a5d4de4
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_py2_div_issue.py
@@ -0,0 +1,33 @@
+import numpy as np
+from numba import cuda, float32, int32, void
+from numba.cuda.testing import unittest, CUDATestCase
+
+
+class TestCudaPy2Div(CUDATestCase):
+ def test_py2_div_issue(self):
+ @cuda.jit(void(float32[:], float32[:], float32[:], int32))
+ def preCalc(y, yA, yB, numDataPoints):
+ i = cuda.grid(1)
+ # k is unused, but may be part of the trigger for the bug this
+ # tests for.
+ k = i % numDataPoints # noqa: F841
+
+ ans = float32(1.001 * float32(i))
+
+ y[i] = ans
+ yA[i] = ans * 1.0
+ yB[i] = ans / 1.0
+
+ numDataPoints = 15
+
+ y = np.zeros(numDataPoints, dtype=np.float32)
+ yA = np.zeros(numDataPoints, dtype=np.float32)
+ yB = np.zeros(numDataPoints, dtype=np.float32)
+ preCalc[1, 15](y, yA, yB, numDataPoints)
+
+ self.assertTrue(np.all(y == yA))
+ self.assertTrue(np.all(y == yB))
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_random.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_random.py
new file mode 100644
index 0000000000000000000000000000000000000000..11bbf95aa4303283ab1616dc1d814ef71a027e04
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_random.py
@@ -0,0 +1,104 @@
+import math
+
+import numpy as np
+
+from numba import cuda
+from numba.cuda.testing import unittest
+from numba.cuda.testing import skip_on_cudasim, CUDATestCase
+
+from numba.cuda.random import \
+ xoroshiro128p_uniform_float32, xoroshiro128p_normal_float32, \
+ xoroshiro128p_uniform_float64, xoroshiro128p_normal_float64
+
+
+# Distributions
+UNIFORM = 1
+NORMAL = 2
+
+
+@cuda.jit
+def rng_kernel_float32(states, out, count, distribution):
+ thread_id = cuda.grid(1)
+
+ for i in range(count):
+ idx = thread_id * count + i
+
+ if distribution == UNIFORM:
+ out[idx] = xoroshiro128p_uniform_float32(states, thread_id)
+ elif distribution == NORMAL:
+ out[idx] = xoroshiro128p_normal_float32(states, thread_id)
+
+
+@cuda.jit
+def rng_kernel_float64(states, out, count, distribution):
+ thread_id = cuda.grid(1)
+
+ for i in range(count):
+ idx = thread_id * count + i
+
+ if distribution == UNIFORM:
+ out[idx] = xoroshiro128p_uniform_float64(states, thread_id)
+ elif distribution == NORMAL:
+ out[idx] = xoroshiro128p_normal_float64(states, thread_id)
+
+
+class TestCudaRandomXoroshiro128p(CUDATestCase):
+ def test_create(self):
+ states = cuda.random.create_xoroshiro128p_states(10, seed=1)
+ s = states.copy_to_host()
+ self.assertEqual(len(np.unique(s)), 10)
+
+ def test_create_subsequence_start(self):
+ states = cuda.random.create_xoroshiro128p_states(10, seed=1)
+ s1 = states.copy_to_host()
+
+ states = cuda.random.create_xoroshiro128p_states(10, seed=1,
+ subsequence_start=3)
+ s2 = states.copy_to_host()
+
+ # Starting seeds should match up with offset of 3
+ np.testing.assert_array_equal(s1[3:], s2[:-3])
+
+ def test_create_stream(self):
+ stream = cuda.stream()
+ states = cuda.random.create_xoroshiro128p_states(10, seed=1,
+ stream=stream)
+ s = states.copy_to_host()
+ self.assertEqual(len(np.unique(s)), 10)
+
+ def check_uniform(self, kernel_func, dtype):
+ states = cuda.random.create_xoroshiro128p_states(32 * 2, seed=1)
+ out = np.zeros(2 * 32 * 32, dtype=np.float32)
+
+ kernel_func[2, 32](states, out, 32, UNIFORM)
+ self.assertAlmostEqual(out.min(), 0.0, delta=1e-3)
+ self.assertAlmostEqual(out.max(), 1.0, delta=1e-3)
+ self.assertAlmostEqual(out.mean(), 0.5, delta=1.5e-2)
+ self.assertAlmostEqual(out.std(), 1.0 / (2 * math.sqrt(3)), delta=6e-3)
+
+ def test_uniform_float32(self):
+ self.check_uniform(rng_kernel_float32, np.float32)
+
+ @skip_on_cudasim('skip test for speed under cudasim')
+ def test_uniform_float64(self):
+ self.check_uniform(rng_kernel_float64, np.float64)
+
+ def check_normal(self, kernel_func, dtype):
+ states = cuda.random.create_xoroshiro128p_states(32 * 2, seed=1)
+ out = np.zeros(2 * 32 * 32, dtype=dtype)
+
+ kernel_func[2, 32](states, out, 32, NORMAL)
+
+ self.assertAlmostEqual(out.mean(), 0.0, delta=4e-3)
+ self.assertAlmostEqual(out.std(), 1.0, delta=2e-3)
+
+ def test_normal_float32(self):
+ self.check_normal(rng_kernel_float32, np.float32)
+
+ @skip_on_cudasim('skip test for speed under cudasim')
+ def test_normal_float64(self):
+ self.check_normal(rng_kernel_float64, np.float64)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_record_dtype.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_record_dtype.py
new file mode 100644
index 0000000000000000000000000000000000000000..75651488e1b0d253bb999eea304591ecc4c42c49
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_record_dtype.py
@@ -0,0 +1,610 @@
+import numpy as np
+from numba import cuda
+from numba.core import types
+from numba.cuda.testing import skip_on_cudasim, CUDATestCase
+import unittest
+from numba.np import numpy_support
+
+
+def set_a(ary, i, v):
+ ary[i].a = v
+
+
+def set_b(ary, i, v):
+ ary[i].b = v
+
+
+def set_c(ary, i, v):
+ ary[i].c = v
+
+
+def set_record(ary, i, j):
+ ary[i] = ary[j]
+
+
+def record_set_a(r, v):
+ r.a = v
+
+
+def record_set_b(r, v):
+ r.b = v
+
+
+def record_set_c(r, v):
+ r.c = v
+
+
+def record_read_a(r, arr):
+ arr[0] = r.a
+
+
+def record_read_b(r, arr):
+ arr[0] = r.b
+
+
+def record_read_c(r, arr):
+ arr[0] = r.c
+
+
+def record_write_array(r):
+ r.g = 2
+ r.h[0] = 3.0
+ r.h[1] = 4.0
+
+
+def record_write_2d_array(r):
+ r.i = 3
+ r.j[0, 0] = 5.0
+ r.j[0, 1] = 6.0
+ r.j[1, 0] = 7.0
+ r.j[1, 1] = 8.0
+ r.j[2, 0] = 9.0
+ r.j[2, 1] = 10.0
+
+
+def record_read_array(r, a):
+ a[0] = r.h[0]
+ a[1] = r.h[1]
+
+
+def record_read_2d_array(r, a):
+ a[0, 0] = r.j[0, 0]
+ a[0, 1] = r.j[0, 1]
+ a[1, 0] = r.j[1, 0]
+ a[1, 1] = r.j[1, 1]
+ a[2, 0] = r.j[2, 0]
+ a[2, 1] = r.j[2, 1]
+
+
+recordtype = np.dtype(
+ [
+ ('a', np.float64),
+ ('b', np.int32),
+ ('c', np.complex64),
+ ('d', (np.uint8, 5))
+ ],
+ align=True
+)
+
+recordwitharray = np.dtype(
+ [
+ ('g', np.int32),
+ ('h', np.float32, 2)
+ ],
+ align=True
+)
+
+recordwith2darray = np.dtype([('i', np.int32),
+ ('j', np.float32, (3, 2))])
+
+nested_array1_dtype = np.dtype([("array1", np.int16, (3,))], align=True)
+
+nested_array2_dtype = np.dtype([("array2", np.int16, (3, 2))], align=True)
+
+
+# Functions used for "full array" tests
+
+def record_write_full_array(rec):
+ rec.j[:, :] = np.ones((3, 2))
+
+
+def record_write_full_array_alt(rec):
+ rec['j'][:, :] = np.ones((3, 2))
+
+
+def recarray_set_record(ary, rec):
+ ary[0] = rec
+
+
+def recarray_write_array_of_nestedarray_broadcast(ary):
+ ary.j[:, :, :] = 1
+ return ary
+
+
+def record_setitem_array(rec_source, rec_dest):
+ rec_dest['j'] = rec_source['j']
+
+
+def recarray_write_array_of_nestedarray(ary):
+ ary.j[:, :, :] = np.ones((2, 3, 2))
+ return ary
+
+
+def recarray_getitem_return(ary):
+ return ary[0]
+
+
+def recarray_getitem_field_return(ary):
+ return ary['h']
+
+
+def recarray_getitem_field_return2(ary):
+ return ary.h
+
+
+def recarray_getitem_field_return2_2d(ary):
+ return ary.j
+
+
+def record_read_array0(ary):
+ return ary.h[0]
+
+
+def record_read_array1(ary):
+ return ary.h[1]
+
+
+def record_read_whole_array(ary):
+ return ary.h
+
+
+def record_read_2d_array00(ary):
+ return ary.j[0, 0]
+
+
+def record_read_2d_array10(ary):
+ return ary.j[1, 0]
+
+
+def record_read_2d_array01(ary):
+ return ary.j[0, 1]
+
+
+def assign_array_to_nested(dest, src):
+ dest['array1'] = src
+
+
+def assign_array_to_nested_2d(dest, src):
+ dest['array2'] = src
+
+
+class TestRecordDtype(CUDATestCase):
+
+ def _createSampleArrays(self):
+ self.sample1d = np.recarray(3, dtype=recordtype)
+ self.samplerec1darr = np.recarray(1, dtype=recordwitharray)[0]
+ self.samplerec2darr = np.recarray(1, dtype=recordwith2darray)[0]
+
+ def setUp(self):
+ super().setUp()
+ self._createSampleArrays()
+
+ ary = self.sample1d
+ for i in range(ary.size):
+ x = i + 1
+ ary[i]['a'] = x / 2
+ ary[i]['b'] = x
+ ary[i]['c'] = x * 1j
+ ary[i]['d'] = "%d" % x
+
+ def get_cfunc(self, pyfunc, argspec):
+ return cuda.jit()(pyfunc)
+
+ def _test_set_equal(self, pyfunc, value, valuetype):
+ rec = numpy_support.from_dtype(recordtype)
+ cfunc = self.get_cfunc(pyfunc, (rec[:], types.intp, valuetype))
+
+ for i in range(self.sample1d.size):
+ got = self.sample1d.copy()
+
+ # Force the argument to the pure Python function to be
+ # a recarray, as attribute access isn't supported on
+ # structured arrays.
+ expect = got.copy().view(np.recarray)
+
+ cfunc[1, 1](got, i, value)
+ pyfunc(expect, i, value)
+
+ # Match the entire array to ensure no memory corruption
+ self.assertTrue(np.all(expect == got))
+
+ def test_set_a(self):
+ self._test_set_equal(set_a, 3.1415, types.float64)
+ # Test again to check if coercion works
+ self._test_set_equal(set_a, 3., types.float32)
+
+ def test_set_b(self):
+ self._test_set_equal(set_b, 123, types.int32)
+ # Test again to check if coercion works
+ self._test_set_equal(set_b, 123, types.float64)
+
+ def test_set_c(self):
+ self._test_set_equal(set_c, 43j, types.complex64)
+ # Test again to check if coercion works
+ self._test_set_equal(set_c, 43j, types.complex128)
+
+ def test_set_record(self):
+ pyfunc = set_record
+ rec = numpy_support.from_dtype(recordtype)
+ cfunc = self.get_cfunc(pyfunc, (rec[:], types.intp, types.intp))
+
+ test_indices = [(0, 1), (1, 2), (0, 2)]
+ for i, j in test_indices:
+ expect = self.sample1d.copy()
+ pyfunc(expect, i, j)
+
+ got = self.sample1d.copy()
+ cfunc[1, 1](got, i, j)
+
+ # Match the entire array to ensure no memory corruption
+ self.assertEqual(expect[i], expect[j])
+ self.assertEqual(got[i], got[j])
+ self.assertTrue(np.all(expect == got))
+
+ def _test_rec_set(self, v, pyfunc, f):
+ rec = self.sample1d.copy()[0]
+ nbrecord = numpy_support.from_dtype(recordtype)
+ cfunc = self.get_cfunc(pyfunc, (nbrecord,))
+ cfunc[1, 1](rec, v)
+ np.testing.assert_equal(rec[f], v)
+
+ def test_rec_set_a(self):
+ self._test_rec_set(np.float64(1.5), record_set_a, 'a')
+
+ def test_rec_set_b(self):
+ self._test_rec_set(np.int32(2), record_set_b, 'b')
+
+ def test_rec_set_c(self):
+ self._test_rec_set(np.complex64(4.0 + 5.0j), record_set_c, 'c')
+
+ def _test_rec_read(self, v, pyfunc, f):
+ rec = self.sample1d.copy()[0]
+ rec[f] = v
+ arr = np.zeros(1, v.dtype)
+ nbrecord = numpy_support.from_dtype(recordtype)
+ cfunc = self.get_cfunc(pyfunc, (nbrecord,))
+ cfunc[1, 1](rec, arr)
+ np.testing.assert_equal(arr[0], v)
+
+ def test_rec_read_a(self):
+ self._test_rec_read(np.float64(1.5), record_read_a, 'a')
+
+ def test_rec_read_b(self):
+ self._test_rec_read(np.int32(2), record_read_b, 'b')
+
+ def test_rec_read_c(self):
+ self._test_rec_read(np.complex64(4.0 + 5.0j), record_read_c, 'c')
+
+ def test_record_write_1d_array(self):
+ '''
+ Test writing to a 1D array within a structured type
+ '''
+ rec = self.samplerec1darr.copy()
+ nbrecord = numpy_support.from_dtype(recordwitharray)
+ cfunc = self.get_cfunc(record_write_array, (nbrecord,))
+
+ cfunc[1, 1](rec)
+ expected = self.samplerec1darr.copy()
+ expected['g'] = 2
+ expected['h'][0] = 3.0
+ expected['h'][1] = 4.0
+
+ np.testing.assert_equal(expected, rec)
+
+ def test_record_write_2d_array(self):
+ '''
+ Test writing to a 2D array within a structured type
+ '''
+ rec = self.samplerec2darr.copy()
+ nbrecord = numpy_support.from_dtype(recordwith2darray)
+ cfunc = self.get_cfunc(record_write_2d_array, (nbrecord,))
+ cfunc[1, 1](rec)
+
+ expected = self.samplerec2darr.copy()
+ expected['i'] = 3
+ expected['j'][:] = np.asarray([5.0, 6.0, 7.0, 8.0, 9.0, 10.0],
+ np.float32).reshape(3, 2)
+ np.testing.assert_equal(expected, rec)
+
+ def test_record_read_1d_array(self):
+ '''
+ Test reading from a 1D array within a structured type
+ '''
+ rec = self.samplerec1darr.copy()
+ rec['h'][0] = 4.0
+ rec['h'][1] = 5.0
+
+ nbrecord = numpy_support.from_dtype(recordwitharray)
+ cfunc = self.get_cfunc(record_read_array, (nbrecord,))
+ arr = np.zeros(2, dtype=rec['h'].dtype)
+ cfunc[1, 1](rec, arr)
+
+ np.testing.assert_equal(rec['h'], arr)
+
+ def test_record_read_2d_array(self):
+ '''
+ Test reading from a 2D array within a structured type
+ '''
+ rec = self.samplerec2darr.copy()
+ rec['j'][:] = np.asarray([5.0, 6.0, 7.0, 8.0, 9.0, 10.0],
+ np.float32).reshape(3, 2)
+
+ nbrecord = numpy_support.from_dtype(recordwith2darray)
+ cfunc = self.get_cfunc(record_read_2d_array, (nbrecord,))
+ arr = np.zeros((3,2), dtype=rec['j'].dtype)
+ cfunc[1, 1](rec, arr)
+
+ np.testing.assert_equal(rec['j'], arr)
+
+
+@skip_on_cudasim('Structured array attr access not supported in simulator')
+class TestRecordDtypeWithStructArrays(TestRecordDtype):
+ '''
+ Same as TestRecordDtype, but using structured arrays instead of recarrays.
+ '''
+
+ def _createSampleArrays(self):
+ self.sample1d = np.zeros(3, dtype=recordtype)
+ self.samplerec1darr = np.zeros(1, dtype=recordwitharray)[0]
+ self.samplerec2darr = np.zeros(1, dtype=recordwith2darray)[0]
+
+
+class TestNestedArrays(CUDATestCase):
+
+ # These tests mirror those from
+ # numba.tests.test_record_dtype.TestNestedArrays added in PR
+ # #7359: https://github.com/numba/numba/pull/7359
+
+ # The code cannot be shared between the two classes without modification,
+ # as the CUDA test implementations need to be launched (and in some cases
+ # wrapped in an outer function to handle the return value). Otherwise, the
+ # code here is kept as similar to that in the equivalent CPU tests as
+ # possible.
+
+ # Reading records / recarrays
+
+ def get_cfunc(self, pyfunc, retty):
+ # Create a host-callable function for testing CUDA device functions
+ # that get a value from a record array
+ inner = cuda.jit(device=True)(pyfunc)
+
+ @cuda.jit
+ def outer(arg0, res):
+ res[0] = inner(arg0)
+
+ def host(arg0):
+ res = np.zeros(1, dtype=retty)
+ outer[1, 1](arg0, res)
+ return res[0]
+
+ return host
+
+ def test_record_read_array(self):
+ # Test reading from a 1D array within a structured type
+ nbval = np.recarray(1, dtype=recordwitharray)
+ nbval[0].h[0] = 15.0
+ nbval[0].h[1] = 25.0
+ cfunc = self.get_cfunc(record_read_array0, np.float32)
+ res = cfunc(nbval[0])
+ np.testing.assert_equal(res, nbval[0].h[0])
+
+ cfunc = self.get_cfunc(record_read_array1, np.float32)
+ res = cfunc(nbval[0])
+ np.testing.assert_equal(res, nbval[0].h[1])
+
+ def test_record_read_2d_array(self):
+ # Test reading from a 2D array within a structured type
+ nbval = np.recarray(1, dtype=recordwith2darray)
+ nbval[0].j = np.asarray([1.5, 2.5, 3.5, 4.5, 5.5, 6.5],
+ np.float32).reshape(3, 2)
+ cfunc = self.get_cfunc(record_read_2d_array00, np.float32)
+ res = cfunc(nbval[0])
+ np.testing.assert_equal(res, nbval[0].j[0, 0])
+
+ cfunc = self.get_cfunc(record_read_2d_array01, np.float32)
+ res = cfunc(nbval[0])
+ np.testing.assert_equal(res, nbval[0].j[0, 1])
+
+ cfunc = self.get_cfunc(record_read_2d_array10, np.float32)
+ res = cfunc(nbval[0])
+ np.testing.assert_equal(res, nbval[0].j[1, 0])
+
+ def test_setitem(self):
+ def gen():
+ nbarr1 = np.recarray(1, dtype=recordwith2darray)
+ nbarr1[0] = np.array([(1, ((1, 2), (4, 5), (2, 3)))],
+ dtype=recordwith2darray)[0]
+ nbarr2 = np.recarray(1, dtype=recordwith2darray)
+ nbarr2[0] = np.array([(10, ((10, 20), (40, 50), (20, 30)))],
+ dtype=recordwith2darray)[0]
+ return nbarr1[0], nbarr2[0]
+ pyfunc = record_setitem_array
+ pyargs = gen()
+ pyfunc(*pyargs)
+
+ cfunc = cuda.jit(pyfunc)
+ cuargs = gen()
+ cfunc[1, 1](*cuargs)
+ np.testing.assert_equal(pyargs, cuargs)
+
+ def test_getitem_idx(self):
+ # Test __getitem__ with numerical index
+
+ # This tests returning a record when passing an array and
+ # returning the first item when passing a record
+ nbarr = np.recarray(2, dtype=recordwitharray)
+ nbarr[0] = np.array([(1, (2, 3))], dtype=recordwitharray)[0]
+ for arg, retty in [(nbarr, recordwitharray), (nbarr[0], np.int32)]:
+ pyfunc = recarray_getitem_return
+ arr_expected = pyfunc(arg)
+ cfunc = self.get_cfunc(pyfunc, retty)
+ arr_res = cfunc(arg)
+ np.testing.assert_equal(arr_res, arr_expected)
+
+ # Writing to records / recarrays
+
+ @skip_on_cudasim('Structured array attr access not supported in simulator')
+ def test_set_record(self):
+ # Test setting an entire record
+ rec = np.ones(2, dtype=recordwith2darray).view(np.recarray)[0]
+ nbarr = np.zeros(2, dtype=recordwith2darray).view(np.recarray)
+ arr = np.zeros(2, dtype=recordwith2darray).view(np.recarray)
+ pyfunc = recarray_set_record
+ pyfunc(arr, rec)
+ kernel = cuda.jit(pyfunc)
+ kernel[1, 1](nbarr, rec)
+ np.testing.assert_equal(nbarr, arr)
+
+ def test_assign_array_to_nested(self):
+ src = (np.arange(3) + 1).astype(np.int16)
+ got = np.zeros(2, dtype=nested_array1_dtype)
+ expected = np.zeros(2, dtype=nested_array1_dtype)
+
+ pyfunc = assign_array_to_nested
+ kernel = cuda.jit(pyfunc)
+
+ kernel[1, 1](got[0], src)
+ pyfunc(expected[0], src)
+
+ np.testing.assert_array_equal(expected, got)
+
+ def test_assign_array_to_nested_2d(self):
+ src = (np.arange(6) + 1).astype(np.int16).reshape((3, 2))
+ got = np.zeros(2, dtype=nested_array2_dtype)
+ expected = np.zeros(2, dtype=nested_array2_dtype)
+
+ pyfunc = assign_array_to_nested_2d
+ kernel = cuda.jit(pyfunc)
+
+ kernel[1, 1](got[0], src)
+ pyfunc(expected[0], src)
+
+ np.testing.assert_array_equal(expected, got)
+
+ def test_issue_7693(self):
+ src_dtype = np.dtype([
+ ("user", np.float64),
+ ("array", np.int16, (3,))],
+ align=True)
+
+ dest_dtype = np.dtype([
+ ("user1", np.float64),
+ ("array1", np.int16, (3,))],
+ align=True)
+
+ @cuda.jit
+ def copy(index, src, dest):
+ dest['user1'] = src[index]['user']
+ dest['array1'] = src[index]['array']
+
+ source = np.zeros(2, dtype=src_dtype)
+ got = np.zeros(2, dtype=dest_dtype)
+ expected = np.zeros(2, dtype=dest_dtype)
+
+ source[0] = (1.2, [1, 2, 3])
+ copy[1, 1](0, source, got[0])
+ copy.py_func(0, source, expected[0])
+
+ np.testing.assert_array_equal(expected, got)
+
+ # Reading and returning arrays from recarrays - the following functions are
+ # all xfailed because CUDA cannot handle returning arrays from device
+ # functions (or creating arrays in general).
+
+ @unittest.expectedFailure
+ def test_getitem_idx_2darray(self):
+ # Test __getitem__ with numerical index
+ #
+ # This test returning a record when passing an array and
+ # return the first item when passing a record
+ nbarr = np.recarray(2, dtype=recordwith2darray)
+ nbarr[0] = np.array([(1, ((1,2),(4,5),(2,3)))],
+ dtype=recordwith2darray)[0]
+ for arg, retty in [(nbarr, recordwith2darray),
+ (nbarr[0], (np.float32, (3, 2)))]:
+ pyfunc = recarray_getitem_field_return2_2d
+ arr_expected = pyfunc(arg)
+ cfunc = self.get_cfunc(pyfunc, retty)
+ arr_res = cfunc(arg)
+ np.testing.assert_equal(arr_res, arr_expected)
+
+ @unittest.expectedFailure
+ def test_return_getattr_getitem_fieldname(self):
+ # Test __getitem__ with field name and getattr .field_name
+ #
+ # This tests returning a array of nestedarrays when passing an array and
+ # returning a nestedarray when passing a record
+ nbarr = np.recarray(2, dtype=recordwitharray)
+ nbarr[0] = np.array([(1, (2,3))], dtype=recordwitharray)[0]
+ for arg, retty in [(nbarr, recordwitharray), (nbarr[0], np.float32)]:
+ for pyfunc in [recarray_getitem_field_return,
+ recarray_getitem_field_return2]:
+ arr_expected = pyfunc(arg)
+ cfunc = self.get_cfunc(pyfunc, retty)
+ arr_res = cfunc(arg)
+ np.testing.assert_equal(arr_res, arr_expected)
+
+ @unittest.expectedFailure
+ def test_record_read_arrays(self):
+ # Test reading from a 1D array within a structured type
+ nbval = np.recarray(2, dtype=recordwitharray)
+ nbval[0].h[0] = 15.0
+ nbval[0].h[1] = 25.0
+ nbval[1].h[0] = 35.0
+ nbval[1].h[1] = 45.4
+ cfunc = self.get_cfunc(record_read_whole_array, np.float32)
+ res = cfunc(nbval)
+ np.testing.assert_equal(res, nbval.h)
+
+ @unittest.expectedFailure
+ def test_return_array(self):
+ # Test getitem record AND array within record and returning it
+ nbval = np.recarray(2, dtype=recordwitharray)
+ nbval[0] = np.array([(1, (2,3))], dtype=recordwitharray)[0]
+ pyfunc = record_read_array0
+ arr_expected = pyfunc(nbval)
+ cfunc = self.get_cfunc(pyfunc, np.float32)
+ arr_res = cfunc(nbval)
+ np.testing.assert_equal(arr_expected, arr_res)
+
+ @skip_on_cudasim('Will unexpectedly pass on cudasim')
+ @unittest.expectedFailure
+ def test_set_array(self):
+ #Test setting an entire array within one record
+ arr = np.zeros(2, dtype=recordwith2darray).view(np.recarray)
+ rec = arr[0]
+ nbarr = np.zeros(2, dtype=recordwith2darray).view(np.recarray)
+ nbrec = nbarr[0]
+ for pyfunc in (record_write_full_array, record_write_full_array_alt):
+ pyfunc(rec)
+ kernel = cuda.jit(pyfunc)
+ kernel[1, 1](nbrec)
+ np.testing.assert_equal(nbarr, arr)
+
+ @unittest.expectedFailure
+ def test_set_arrays(self):
+ # Test setting an entire array of arrays (multiple records)
+ arr = np.zeros(2, dtype=recordwith2darray).view(np.recarray)
+ nbarr = np.zeros(2, dtype=recordwith2darray).view(np.recarray)
+ for pyfunc in (
+ recarray_write_array_of_nestedarray_broadcast,
+ recarray_write_array_of_nestedarray,
+ ):
+ arr_expected = pyfunc(arr)
+ cfunc = self.get_cfunc(pyfunc, nbarr.dtype)
+ arr_res = cfunc(nbarr)
+ np.testing.assert_equal(arr_res, arr_expected)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_recursion.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_recursion.py
new file mode 100644
index 0000000000000000000000000000000000000000..579275330aad24a2a980b6190f63e2109e302d99
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_recursion.py
@@ -0,0 +1,125 @@
+from numba import cuda
+from numba.core.errors import TypingError
+from numba.cuda.testing import CUDATestCase, skip_on_cudasim
+import numpy as np
+import unittest
+
+
+class TestSelfRecursion(CUDATestCase):
+
+ def setUp(self):
+ # Avoid importing this module at the top level, as it triggers
+ # compilation and can therefore fail
+ from numba.cuda.tests.cudapy import recursion_usecases
+ self.mod = recursion_usecases
+ super().setUp()
+
+ def check_fib(self, cfunc):
+ @cuda.jit
+ def kernel(r, x):
+ r[0] = cfunc(x[0])
+
+ x = np.asarray([10], dtype=np.int64)
+ r = np.zeros_like(x)
+ kernel[1, 1](r, x)
+
+ actual = r[0]
+ expected = 55
+ self.assertPreciseEqual(actual, expected)
+
+ def test_global_explicit_sig(self):
+ self.check_fib(self.mod.fib1)
+
+ def test_inner_explicit_sig(self):
+ self.check_fib(self.mod.fib2)
+
+ def test_global_implicit_sig(self):
+ self.check_fib(self.mod.fib3)
+
+ @skip_on_cudasim('Simulator does not compile')
+ def test_runaway(self):
+ with self.assertRaises(TypingError) as raises:
+ cfunc = self.mod.runaway_self
+
+ @cuda.jit('void()')
+ def kernel():
+ cfunc(1)
+
+ self.assertIn("cannot type infer runaway recursion",
+ str(raises.exception))
+
+ @unittest.skip('Needs insert_unresolved_ref support in target')
+ def test_type_change(self):
+ pfunc = self.mod.type_change_self.py_func
+ cfunc = self.mod.type_change_self
+
+ @cuda.jit
+ def kernel(r, x, y):
+ r[0] = cfunc(x[0], y[0])
+
+ args = 13, 0.125
+ x = np.asarray([args[0]], dtype=np.int64)
+ y = np.asarray([args[1]], dtype=np.float64)
+ r = np.zeros_like(x)
+
+ kernel[1, 1](r, x, y)
+
+ expected = pfunc(*args)
+ actual = r[0]
+
+ self.assertPreciseEqual(actual, expected)
+
+ @unittest.expectedFailure
+ def test_raise(self):
+ # This is an expected failure because reporting of exceptions raised in
+ # device functions does not work correctly - see Issue #8036:
+ # https://github.com/numba/numba/issues/8036
+ with self.assertRaises(ValueError) as raises:
+ self.mod.raise_self_kernel[1, 1](3)
+
+ self.assertEqual(str(raises.exception), "raise_self")
+
+ @unittest.skip('Needs insert_unresolved_ref support in target')
+ def test_optional_return(self):
+ pfunc = self.mod.make_optional_return_case()
+ cfunc = self.mod.make_optional_return_case(cuda.jit)
+
+ @cuda.jit
+ def kernel(r, x):
+ res = cfunc(x[0])
+ if res is None:
+ res = 999
+ r[0] = res
+
+ def cpu_kernel(x):
+ res = pfunc(x)
+ if res is None:
+ res = 999
+ return res
+
+ for arg in (0, 5, 10, 15):
+ expected = cpu_kernel(arg)
+ x = np.asarray([arg], dtype=np.int64)
+ r = np.zeros_like(x)
+ kernel[1, 1](r, x)
+ actual = r[0]
+
+ self.assertEqual(expected, actual)
+
+ @skip_on_cudasim('Recursion handled because simulator does not compile')
+ def test_growing_return_tuple(self):
+ cfunc = self.mod.make_growing_tuple_case(cuda.jit)
+
+ with self.assertRaises(TypingError) as raises:
+ @cuda.jit('void()')
+ def kernel():
+ cfunc(100)
+
+ self.assertIn(
+ "Return type of recursive function does not converge",
+ str(raises.exception),
+ )
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_reduction.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_reduction.py
new file mode 100644
index 0000000000000000000000000000000000000000..420fc751641f7690a25d57dfc9803376af594126
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_reduction.py
@@ -0,0 +1,76 @@
+import numpy as np
+from numba import cuda
+from numba.core.config import ENABLE_CUDASIM
+from numba.cuda.testing import CUDATestCase
+import unittest
+
+# Avoid recompilation of the sum_reduce function by keeping it at global scope
+sum_reduce = cuda.Reduce(lambda a, b: a + b)
+
+
+class TestReduction(CUDATestCase):
+ def _sum_reduce(self, n):
+ A = (np.arange(n, dtype=np.float64) + 1)
+ expect = A.sum()
+ got = sum_reduce(A)
+ self.assertEqual(expect, got)
+
+ def test_sum_reduce(self):
+ if ENABLE_CUDASIM:
+ # Minimal test set for the simulator (which only wraps
+ # functools.reduce)
+ test_sizes = [ 1, 16 ]
+ else:
+ # Tests around the points where blocksize changes, and around larger
+ # powers of two, sums of powers of two, and some "random" sizes
+ test_sizes = [ 1, 15, 16, 17, 127, 128, 129, 1023, 1024,
+ 1025, 1536, 1048576, 1049600, 1049728, 34567 ]
+ # Avoid recompilation by keeping sum_reduce here
+ for n in test_sizes:
+ self._sum_reduce(n)
+
+ def test_empty_array_host(self):
+ A = (np.arange(0, dtype=np.float64) + 1)
+ expect = A.sum()
+ got = sum_reduce(A)
+ self.assertEqual(expect, got)
+
+ def test_empty_array_device(self):
+ A = (np.arange(0, dtype=np.float64) + 1)
+ dA = cuda.to_device(A)
+ expect = A.sum()
+ got = sum_reduce(dA)
+ self.assertEqual(expect, got)
+
+ def test_prod_reduce(self):
+ prod_reduce = cuda.reduce(lambda a, b: a * b)
+ A = (np.arange(64, dtype=np.float64) + 1)
+ expect = A.prod()
+ got = prod_reduce(A, init=1)
+ np.testing.assert_allclose(expect, got)
+
+ def test_max_reduce(self):
+ max_reduce = cuda.Reduce(lambda a, b: max(a, b))
+ A = (np.arange(3717, dtype=np.float64) + 1)
+ expect = A.max()
+ got = max_reduce(A, init=0)
+ self.assertEqual(expect, got)
+
+ def test_non_identity_init(self):
+ init = 3
+ A = (np.arange(10, dtype=np.float64) + 1)
+ expect = A.sum() + init
+ got = sum_reduce(A, init=init)
+ self.assertEqual(expect, got)
+
+ def test_result_on_device(self):
+ A = (np.arange(10, dtype=np.float64) + 1)
+ got = cuda.to_device(np.zeros(1, dtype=np.float64))
+ expect = A.sum()
+ res = sum_reduce(A, res=got)
+ self.assertIsNone(res)
+ self.assertEqual(expect, got[0])
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_retrieve_autoconverted_arrays.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_retrieve_autoconverted_arrays.py
new file mode 100644
index 0000000000000000000000000000000000000000..640efcac3de4c0803789797d1e4b33211b1aa790
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_retrieve_autoconverted_arrays.py
@@ -0,0 +1,83 @@
+import numpy as np
+
+from numba import cuda
+from numba.cuda.args import wrap_arg
+from numba.cuda.testing import CUDATestCase
+import unittest
+
+
+class DefaultIn(object):
+ def prepare_args(self, ty, val, **kwargs):
+ return ty, wrap_arg(val, default=cuda.In)
+
+
+def nocopy(kernel):
+ kernel.extensions.append(DefaultIn())
+ return kernel
+
+
+def set_array_to_three(arr):
+ arr[0] = 3
+
+
+def set_record_to_three(rec):
+ rec[0]['b'] = 3
+
+
+recordtype = np.dtype(
+ [('b', np.int32)],
+ align=True
+)
+
+
+class TestRetrieveAutoconvertedArrays(CUDATestCase):
+ def setUp(self):
+ super().setUp()
+ self.set_array_to_three = cuda.jit(set_array_to_three)
+ self.set_array_to_three_nocopy = nocopy(cuda.jit(set_array_to_three))
+ self.set_record_to_three = cuda.jit(set_record_to_three)
+ self.set_record_to_three_nocopy = nocopy(cuda.jit(set_record_to_three))
+
+ def test_array_inout(self):
+ host_arr = np.zeros(1, dtype=np.int64)
+ self.set_array_to_three[1, 1](cuda.InOut(host_arr))
+ self.assertEqual(3, host_arr[0])
+
+ def test_array_in(self):
+ host_arr = np.zeros(1, dtype=np.int64)
+ self.set_array_to_three[1, 1](cuda.In(host_arr))
+ self.assertEqual(0, host_arr[0])
+
+ def test_array_in_from_config(self):
+ host_arr = np.zeros(1, dtype=np.int64)
+ self.set_array_to_three_nocopy[1, 1](host_arr)
+ self.assertEqual(0, host_arr[0])
+
+ def test_array_default(self):
+ host_arr = np.zeros(1, dtype=np.int64)
+ self.set_array_to_three[1, 1](host_arr)
+ self.assertEqual(3, host_arr[0])
+
+ def test_record_in(self):
+ host_rec = np.zeros(1, dtype=recordtype)
+ self.set_record_to_three[1, 1](cuda.In(host_rec))
+ self.assertEqual(0, host_rec[0]['b'])
+
+ def test_record_inout(self):
+ host_rec = np.zeros(1, dtype=recordtype)
+ self.set_record_to_three[1, 1](cuda.InOut(host_rec))
+ self.assertEqual(3, host_rec[0]['b'])
+
+ def test_record_default(self):
+ host_rec = np.zeros(1, dtype=recordtype)
+ self.set_record_to_three[1, 1](host_rec)
+ self.assertEqual(3, host_rec[0]['b'])
+
+ def test_record_in_from_config(self):
+ host_rec = np.zeros(1, dtype=recordtype)
+ self.set_record_to_three_nocopy[1, 1](host_rec)
+ self.assertEqual(0, host_rec[0]['b'])
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_serialize.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_serialize.py
new file mode 100644
index 0000000000000000000000000000000000000000..b98aa85a0a1b4e8e9de3d0ca859e0864c21c291d
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_serialize.py
@@ -0,0 +1,85 @@
+import pickle
+import numpy as np
+from numba import cuda, vectorize
+from numba.core import types
+from numba.cuda.testing import skip_on_cudasim, CUDATestCase
+import unittest
+from numba.np import numpy_support
+
+
+@skip_on_cudasim('pickling not supported in CUDASIM')
+class TestPickle(CUDATestCase):
+
+ def check_call(self, callee):
+ arr = np.array([100])
+ expected = callee[1, 1](arr)
+
+ # serialize and rebuild
+ foo1 = pickle.loads(pickle.dumps(callee))
+ del callee
+ # call rebuild function
+ got1 = foo1[1, 1](arr)
+ np.testing.assert_equal(got1, expected)
+ del got1
+
+ # test serialization of previously serialized object
+ foo2 = pickle.loads(pickle.dumps(foo1))
+ del foo1
+ # call rebuild function
+ got2 = foo2[1, 1](arr)
+ np.testing.assert_equal(got2, expected)
+ del got2
+
+ # test propagation of thread, block config
+ foo3 = pickle.loads(pickle.dumps(foo2[5, 8]))
+ del foo2
+ self.assertEqual(foo3.griddim, (5, 1, 1))
+ self.assertEqual(foo3.blockdim, (8, 1, 1))
+
+ def test_pickling_jit_typing(self):
+ @cuda.jit(device=True)
+ def inner(a):
+ return a + 1
+
+ @cuda.jit('void(intp[:])')
+ def foo(arr):
+ arr[0] = inner(arr[0])
+
+ self.check_call(foo)
+
+ def test_pickling_jit(self):
+
+ @cuda.jit(device=True)
+ def inner(a):
+ return a + 1
+
+ @cuda.jit
+ def foo(arr):
+ arr[0] = inner(arr[0])
+
+ self.check_call(foo)
+
+ def test_pickling_vectorize(self):
+ @vectorize(['intp(intp)', 'float64(float64)'], target='cuda')
+ def cuda_vect(x):
+ return x * 2
+
+ # accommodate int representations in np.arange
+ npty = numpy_support.as_dtype(types.intp)
+ # get expected result
+ ary = np.arange(10, dtype=npty)
+ expected = cuda_vect(ary)
+ # first pickle
+ foo1 = pickle.loads(pickle.dumps(cuda_vect))
+ del cuda_vect
+ got1 = foo1(ary)
+ np.testing.assert_equal(expected, got1)
+ # second pickle
+ foo2 = pickle.loads(pickle.dumps(foo1))
+ del foo1
+ got2 = foo2(ary)
+ np.testing.assert_equal(expected, got2)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_slicing.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_slicing.py
new file mode 100644
index 0000000000000000000000000000000000000000..3c97775bf3ed9e39d4d7f0048215e2773ed90b1d
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_slicing.py
@@ -0,0 +1,77 @@
+import numpy as np
+from numba import cuda, errors
+from numba.cuda.testing import unittest, CUDATestCase, skip_on_cudasim
+
+
+def foo(inp, out):
+ for i in range(out.shape[0]):
+ out[i] = inp[i]
+
+
+def copy(inp, out):
+ i = cuda.grid(1)
+ cufoo(inp[i, :], out[i, :])
+
+
+class TestCudaSlicing(CUDATestCase):
+ def test_slice_as_arg(self):
+ global cufoo
+ cufoo = cuda.jit("void(int32[:], int32[:])", device=True)(foo)
+ cucopy = cuda.jit("void(int32[:,:], int32[:,:])")(copy)
+
+ inp = np.arange(100, dtype=np.int32).reshape(10, 10)
+ out = np.zeros_like(inp)
+
+ cucopy[1, 10](inp, out)
+
+ def test_assign_empty_slice(self):
+ # Issue #5017. Assigning to an empty slice should not result in a
+ # CudaAPIError.
+ N = 0
+ a = range(N)
+ arr = cuda.device_array(len(a))
+ arr[:] = cuda.to_device(a)
+
+ # NOTE: The following applies to:
+ # - test_array_slice_assignment_from_sequence_error_handling_codegen
+ # - test_array_slice_assignment_from_array_error_handling_codegen
+ #
+ # This checks that the error handling code for invalid slice assignment
+ # will compile for the CUDA target. There is nothing to check at run time
+ # because the CUDA target cannot propagate the raised exception across
+ # the (generated) function call boundary, in essence it fails silently.
+ # Further the built-in CUDA implementation does not support a "dynamic"
+ # sequence type (i.e. list or set) as it has no NRT available. As a
+ # result it's not possible at run time to take the execution path for
+ # raising the exception coming from the "sequence" side of the
+ # "mismatched" set-slice operation code generation. This is because it
+ # is preempted by an exception raised from the tuple being "seen" as the
+ # wrong size earlier in the execution. Also, due to lack of the NRT, the
+ # path for setting an array slice to a buffer value will not compile for
+ # CUDA and testing is best-effort (it checks compilation was ok up to
+ # the point it cannot get past without the NRT).
+ # See #9906 for context.
+
+ def test_array_slice_assignment_from_sequence_error_handling_codegen(self):
+ # Compile the "assign slice from sequence" path, this should compile
+ # without error, but will not execute correctly without exception
+ # propagation.
+ @cuda.jit("void(f4[:, :, :], i4, i4)")
+ def check_sequence_setslice(tmp, a, b):
+ tmp[a, b] = 1, 1, 1
+
+ @skip_on_cudasim("No NRT codegen in the CUDA simulator")
+ def test_array_slice_assignment_from_array_error_handling_codegen(self):
+ # Compile the "assign slice from array" path, it will fail, but only
+ # when it tries to do code generation for a potential array copy.
+ with self.assertRaises(errors.NumbaRuntimeError) as raises:
+ @cuda.jit("void(f4[:, :, :], f4[:], i4, i4)")
+ def check_array_setslice(tmp, value, a, b):
+ tmp[a, b] = value
+
+ msg = "NRT required but not enabled"
+ self.assertIn(msg, str(raises.exception))
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_sm.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_sm.py
new file mode 100644
index 0000000000000000000000000000000000000000..b61784a735a0970acea11499a49a22d776c76f5d
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_sm.py
@@ -0,0 +1,444 @@
+from numba import cuda, int32, float64, void
+from numba.core.errors import TypingError
+from numba.core import types
+from numba.cuda.testing import unittest, CUDATestCase, skip_on_cudasim
+
+import numpy as np
+from numba.np import numpy_support as nps
+
+from .extensions_usecases import test_struct_model_type, TestStruct
+
+recordwith2darray = np.dtype([('i', np.int32),
+ ('j', np.float32, (3, 2))])
+
+
+class TestSharedMemoryIssue(CUDATestCase):
+ def test_issue_953_sm_linkage_conflict(self):
+ @cuda.jit(device=True)
+ def inner():
+ inner_arr = cuda.shared.array(1, dtype=int32) # noqa: F841
+
+ @cuda.jit
+ def outer():
+ outer_arr = cuda.shared.array(1, dtype=int32) # noqa: F841
+ inner()
+
+ outer[1, 1]()
+
+ def _check_shared_array_size(self, shape, expected):
+ @cuda.jit
+ def s(a):
+ arr = cuda.shared.array(shape, dtype=int32)
+ a[0] = arr.size
+
+ result = np.zeros(1, dtype=np.int32)
+ s[1, 1](result)
+ self.assertEqual(result[0], expected)
+
+ def test_issue_1051_shared_size_broken_1d(self):
+ self._check_shared_array_size(2, 2)
+
+ def test_issue_1051_shared_size_broken_2d(self):
+ self._check_shared_array_size((2, 3), 6)
+
+ def test_issue_1051_shared_size_broken_3d(self):
+
+ self._check_shared_array_size((2, 3, 4), 24)
+
+ def _check_shared_array_size_fp16(self, shape, expected, ty):
+ @cuda.jit
+ def s(a):
+ arr = cuda.shared.array(shape, dtype=ty)
+ a[0] = arr.size
+
+ result = np.zeros(1, dtype=np.float16)
+ s[1, 1](result)
+ self.assertEqual(result[0], expected)
+
+ def test_issue_fp16_support(self):
+ self._check_shared_array_size_fp16(2, 2, types.float16)
+ self._check_shared_array_size_fp16(2, 2, np.float16)
+
+ def test_issue_2393(self):
+ """
+ Test issue of warp misalign address due to nvvm not knowing the
+ alignment(? but it should have taken the natural alignment of the type)
+ """
+ num_weights = 2
+ num_blocks = 48
+ examples_per_block = 4
+ threads_per_block = 1
+
+ @cuda.jit
+ def costs_func(d_block_costs):
+ s_features = cuda.shared.array((examples_per_block, num_weights),
+ float64)
+ s_initialcost = cuda.shared.array(7, float64) # Bug
+
+ threadIdx = cuda.threadIdx.x
+
+ prediction = 0
+ for j in range(num_weights):
+ prediction += s_features[threadIdx, j]
+
+ d_block_costs[0] = s_initialcost[0] + prediction
+
+ block_costs = np.zeros(num_blocks, dtype=np.float64)
+ d_block_costs = cuda.to_device(block_costs)
+
+ costs_func[num_blocks, threads_per_block](d_block_costs)
+
+ cuda.synchronize()
+
+
+class TestSharedMemory(CUDATestCase):
+ def _test_shared(self, arr):
+ # Use a kernel that copies via shared memory to check loading and
+ # storing different dtypes with shared memory. All threads in a block
+ # collaborate to load in values, then the output values are written
+ # only by the first thread in the block after synchronization.
+
+ nelem = len(arr)
+ nthreads = 16
+ nblocks = int(nelem / nthreads)
+ dt = nps.from_dtype(arr.dtype)
+
+ @cuda.jit
+ def use_sm_chunk_copy(x, y):
+ sm = cuda.shared.array(nthreads, dtype=dt)
+
+ tx = cuda.threadIdx.x
+ bx = cuda.blockIdx.x
+ bd = cuda.blockDim.x
+
+ # Load this block's chunk into shared
+ i = bx * bd + tx
+ if i < len(x):
+ sm[tx] = x[i]
+
+ cuda.syncthreads()
+
+ # One thread per block writes this block's chunk
+ if tx == 0:
+ for j in range(nthreads):
+ y[bd * bx + j] = sm[j]
+
+ d_result = cuda.device_array_like(arr)
+ use_sm_chunk_copy[nblocks, nthreads](arr, d_result)
+ host_result = d_result.copy_to_host()
+ np.testing.assert_array_equal(arr, host_result)
+
+ def test_shared_recarray(self):
+ arr = np.recarray(128, dtype=recordwith2darray)
+ for x in range(len(arr)):
+ arr[x].i = x
+ j = np.arange(3 * 2, dtype=np.float32)
+ arr[x].j = j.reshape(3, 2) * x
+
+ self._test_shared(arr)
+
+ def test_shared_bool(self):
+ arr = np.random.randint(2, size=(1024,), dtype=np.bool_)
+ self._test_shared(arr)
+
+ def _test_dynshared_slice(self, func, arr, expected):
+ # Check that slices of shared memory are correct
+ # (See Bug #5073 - prior to the addition of these tests and
+ # corresponding fix, slices of dynamic shared arrays all aliased each
+ # other)
+ nshared = arr.size * arr.dtype.itemsize
+ func[1, 1, 0, nshared](arr)
+ np.testing.assert_array_equal(expected, arr)
+
+ def test_dynshared_slice_write(self):
+ # Test writing values into disjoint slices of dynamic shared memory
+ @cuda.jit
+ def slice_write(x):
+ dynsmem = cuda.shared.array(0, dtype=int32)
+ sm1 = dynsmem[0:1]
+ sm2 = dynsmem[1:2]
+
+ sm1[0] = 1
+ sm2[0] = 2
+ x[0] = dynsmem[0]
+ x[1] = dynsmem[1]
+
+ arr = np.zeros(2, dtype=np.int32)
+ expected = np.array([1, 2], dtype=np.int32)
+ self._test_dynshared_slice(slice_write, arr, expected)
+
+ def test_dynshared_slice_read(self):
+ # Test reading values from disjoint slices of dynamic shared memory
+ @cuda.jit
+ def slice_read(x):
+ dynsmem = cuda.shared.array(0, dtype=int32)
+ sm1 = dynsmem[0:1]
+ sm2 = dynsmem[1:2]
+
+ dynsmem[0] = 1
+ dynsmem[1] = 2
+ x[0] = sm1[0]
+ x[1] = sm2[0]
+
+ arr = np.zeros(2, dtype=np.int32)
+ expected = np.array([1, 2], dtype=np.int32)
+ self._test_dynshared_slice(slice_read, arr, expected)
+
+ def test_dynshared_slice_diff_sizes(self):
+ # Test reading values from disjoint slices of dynamic shared memory
+ # with different sizes
+ @cuda.jit
+ def slice_diff_sizes(x):
+ dynsmem = cuda.shared.array(0, dtype=int32)
+ sm1 = dynsmem[0:1]
+ sm2 = dynsmem[1:3]
+
+ dynsmem[0] = 1
+ dynsmem[1] = 2
+ dynsmem[2] = 3
+ x[0] = sm1[0]
+ x[1] = sm2[0]
+ x[2] = sm2[1]
+
+ arr = np.zeros(3, dtype=np.int32)
+ expected = np.array([1, 2, 3], dtype=np.int32)
+ self._test_dynshared_slice(slice_diff_sizes, arr, expected)
+
+ def test_dynshared_slice_overlap(self):
+ # Test reading values from overlapping slices of dynamic shared memory
+ @cuda.jit
+ def slice_overlap(x):
+ dynsmem = cuda.shared.array(0, dtype=int32)
+ sm1 = dynsmem[0:2]
+ sm2 = dynsmem[1:4]
+
+ dynsmem[0] = 1
+ dynsmem[1] = 2
+ dynsmem[2] = 3
+ dynsmem[3] = 4
+ x[0] = sm1[0]
+ x[1] = sm1[1]
+ x[2] = sm2[0]
+ x[3] = sm2[1]
+ x[4] = sm2[2]
+
+ arr = np.zeros(5, dtype=np.int32)
+ expected = np.array([1, 2, 2, 3, 4], dtype=np.int32)
+ self._test_dynshared_slice(slice_overlap, arr, expected)
+
+ def test_dynshared_slice_gaps(self):
+ # Test writing values to slices of dynamic shared memory doesn't write
+ # outside the slice
+ @cuda.jit
+ def slice_gaps(x):
+ dynsmem = cuda.shared.array(0, dtype=int32)
+ sm1 = dynsmem[1:3]
+ sm2 = dynsmem[4:6]
+
+ # Initial values for dynamic shared memory, some to be overwritten
+ dynsmem[0] = 99
+ dynsmem[1] = 99
+ dynsmem[2] = 99
+ dynsmem[3] = 99
+ dynsmem[4] = 99
+ dynsmem[5] = 99
+ dynsmem[6] = 99
+
+ sm1[0] = 1
+ sm1[1] = 2
+ sm2[0] = 3
+ sm2[1] = 4
+
+ x[0] = dynsmem[0]
+ x[1] = dynsmem[1]
+ x[2] = dynsmem[2]
+ x[3] = dynsmem[3]
+ x[4] = dynsmem[4]
+ x[5] = dynsmem[5]
+ x[6] = dynsmem[6]
+
+ arr = np.zeros(7, dtype=np.int32)
+ expected = np.array([99, 1, 2, 99, 3, 4, 99], dtype=np.int32)
+ self._test_dynshared_slice(slice_gaps, arr, expected)
+
+ def test_dynshared_slice_write_backwards(self):
+ # Test writing values into disjoint slices of dynamic shared memory
+ # with negative steps
+ @cuda.jit
+ def slice_write_backwards(x):
+ dynsmem = cuda.shared.array(0, dtype=int32)
+ sm1 = dynsmem[1::-1]
+ sm2 = dynsmem[3:1:-1]
+
+ sm1[0] = 1
+ sm1[1] = 2
+ sm2[0] = 3
+ sm2[1] = 4
+ x[0] = dynsmem[0]
+ x[1] = dynsmem[1]
+ x[2] = dynsmem[2]
+ x[3] = dynsmem[3]
+
+ arr = np.zeros(4, dtype=np.int32)
+ expected = np.array([2, 1, 4, 3], dtype=np.int32)
+ self._test_dynshared_slice(slice_write_backwards, arr, expected)
+
+ def test_dynshared_slice_nonunit_stride(self):
+ # Test writing values into slice of dynamic shared memory with
+ # non-unit stride
+ @cuda.jit
+ def slice_nonunit_stride(x):
+ dynsmem = cuda.shared.array(0, dtype=int32)
+ sm1 = dynsmem[::2]
+
+ # Initial values for dynamic shared memory, some to be overwritten
+ dynsmem[0] = 99
+ dynsmem[1] = 99
+ dynsmem[2] = 99
+ dynsmem[3] = 99
+ dynsmem[4] = 99
+ dynsmem[5] = 99
+
+ sm1[0] = 1
+ sm1[1] = 2
+ sm1[2] = 3
+
+ x[0] = dynsmem[0]
+ x[1] = dynsmem[1]
+ x[2] = dynsmem[2]
+ x[3] = dynsmem[3]
+ x[4] = dynsmem[4]
+ x[5] = dynsmem[5]
+
+ arr = np.zeros(6, dtype=np.int32)
+ expected = np.array([1, 99, 2, 99, 3, 99], dtype=np.int32)
+ self._test_dynshared_slice(slice_nonunit_stride, arr, expected)
+
+ def test_dynshared_slice_nonunit_reverse_stride(self):
+ # Test writing values into slice of dynamic shared memory with
+ # reverse non-unit stride
+ @cuda.jit
+ def slice_nonunit_reverse_stride(x):
+ dynsmem = cuda.shared.array(0, dtype=int32)
+ sm1 = dynsmem[-1::-2]
+
+ # Initial values for dynamic shared memory, some to be overwritten
+ dynsmem[0] = 99
+ dynsmem[1] = 99
+ dynsmem[2] = 99
+ dynsmem[3] = 99
+ dynsmem[4] = 99
+ dynsmem[5] = 99
+
+ sm1[0] = 1
+ sm1[1] = 2
+ sm1[2] = 3
+
+ x[0] = dynsmem[0]
+ x[1] = dynsmem[1]
+ x[2] = dynsmem[2]
+ x[3] = dynsmem[3]
+ x[4] = dynsmem[4]
+ x[5] = dynsmem[5]
+
+ arr = np.zeros(6, dtype=np.int32)
+ expected = np.array([99, 3, 99, 2, 99, 1], dtype=np.int32)
+ self._test_dynshared_slice(slice_nonunit_reverse_stride, arr, expected)
+
+ def test_issue_5073(self):
+ # An example with which Bug #5073 (slices of dynamic shared memory all
+ # alias) was discovered. The kernel uses all threads in the block to
+ # load values into slices of dynamic shared memory. One thread per
+ # block then writes the loaded values back to a global array after
+ # syncthreads().
+
+ arr = np.arange(1024)
+ nelem = len(arr)
+ nthreads = 16
+ nblocks = int(nelem / nthreads)
+ dt = nps.from_dtype(arr.dtype)
+ nshared = nthreads * arr.dtype.itemsize
+ chunksize = int(nthreads / 2)
+
+ @cuda.jit
+ def sm_slice_copy(x, y, chunksize):
+ dynsmem = cuda.shared.array(0, dtype=dt)
+ sm1 = dynsmem[0:chunksize]
+ sm2 = dynsmem[chunksize:chunksize * 2]
+
+ tx = cuda.threadIdx.x
+ bx = cuda.blockIdx.x
+ bd = cuda.blockDim.x
+
+ # load this block's chunk into shared
+ i = bx * bd + tx
+ if i < len(x):
+ if tx < chunksize:
+ sm1[tx] = x[i]
+ else:
+ sm2[tx - chunksize] = x[i]
+
+ cuda.syncthreads()
+
+ # one thread per block writes this block's chunk
+ if tx == 0:
+ for j in range(chunksize):
+ y[bd * bx + j] = sm1[j]
+ y[bd * bx + j + chunksize] = sm2[j]
+
+ d_result = cuda.device_array_like(arr)
+ sm_slice_copy[nblocks, nthreads, 0, nshared](arr, d_result, chunksize)
+ host_result = d_result.copy_to_host()
+ np.testing.assert_array_equal(arr, host_result)
+
+ @skip_on_cudasim("Can't check typing in simulator")
+ def test_invalid_array_type(self):
+ rgx = ".*Cannot infer the type of variable 'arr'.*"
+
+ def unsupported_type():
+ arr = cuda.shared.array(10, dtype=np.dtype('O')) # noqa: F841
+ with self.assertRaisesRegex(TypingError, rgx):
+ cuda.jit(void())(unsupported_type)
+
+ rgx = ".*Invalid NumPy dtype specified: 'int33'.*"
+
+ def invalid_string_type():
+ arr = cuda.shared.array(10, dtype='int33') # noqa: F841
+ with self.assertRaisesRegex(TypingError, rgx):
+ cuda.jit(void())(invalid_string_type)
+
+ @skip_on_cudasim("Struct model array unsupported in simulator")
+ def test_struct_model_type_static(self):
+ nthreads = 64
+
+ @cuda.jit(void(int32[::1], int32[::1]))
+ def write_then_reverse_read_static(outx, outy):
+ # Test creation
+ arr = cuda.shared.array(nthreads, dtype=test_struct_model_type)
+
+ i = cuda.grid(1)
+ ri = nthreads - i - 1
+
+ if i < len(outx) and i < len(outy):
+ # Test set to arr
+ obj = TestStruct(int32(i), int32(i * 2))
+ arr[i] = obj
+
+ cuda.syncthreads()
+ # Test get from arr
+ outx[i] = arr[ri].x
+ outy[i] = arr[ri].y
+
+ arrx = np.zeros((nthreads,), dtype="int32")
+ arry = np.zeros((nthreads,), dtype="int32")
+
+ write_then_reverse_read_static[1, nthreads](arrx, arry)
+
+ for i, x in enumerate(arrx):
+ self.assertEqual(x, nthreads - i - 1)
+ for i, y in enumerate(arry):
+ self.assertEqual(y, (nthreads - i - 1) * 2)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_sm_creation.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_sm_creation.py
new file mode 100644
index 0000000000000000000000000000000000000000..bff48e64288a2c28b2da0e5d06dfa09d226460fc
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_sm_creation.py
@@ -0,0 +1,205 @@
+import numpy as np
+from numba import cuda, float32, int32, void
+from numba.core.errors import TypingError
+from numba.cuda.testing import unittest, CUDATestCase
+from numba.cuda.testing import skip_on_cudasim
+from .extensions_usecases import test_struct_model_type
+
+GLOBAL_CONSTANT = 5
+GLOBAL_CONSTANT_2 = 6
+GLOBAL_CONSTANT_TUPLE = 5, 6
+
+
+def udt_global_constants(A):
+ sa = cuda.shared.array(shape=GLOBAL_CONSTANT, dtype=float32)
+ i = cuda.grid(1)
+ A[i] = sa[i]
+
+
+def udt_global_build_tuple(A):
+ sa = cuda.shared.array(shape=(GLOBAL_CONSTANT, GLOBAL_CONSTANT_2),
+ dtype=float32)
+ i, j = cuda.grid(2)
+ A[i, j] = sa[i, j]
+
+
+def udt_global_build_list(A):
+ sa = cuda.shared.array(shape=[GLOBAL_CONSTANT, GLOBAL_CONSTANT_2],
+ dtype=float32)
+ i, j = cuda.grid(2)
+ A[i, j] = sa[i, j]
+
+
+def udt_global_constant_tuple(A):
+ sa = cuda.shared.array(shape=GLOBAL_CONSTANT_TUPLE, dtype=float32)
+ i, j = cuda.grid(2)
+ A[i, j] = sa[i, j]
+
+
+def udt_invalid_1(A):
+ sa = cuda.shared.array(shape=A[0], dtype=float32)
+ i = cuda.grid(1)
+ A[i] = sa[i]
+
+
+def udt_invalid_2(A):
+ sa = cuda.shared.array(shape=(1, A[0]), dtype=float32)
+ i, j = cuda.grid(2)
+ A[i, j] = sa[i, j]
+
+
+def udt_invalid_3(A):
+ sa = cuda.shared.array(shape=(1, A[0]), dtype=float32)
+ i = cuda.grid(1)
+ A[i] = sa[i, 0]
+
+
+class TestSharedMemoryCreation(CUDATestCase):
+ def getarg(self):
+ return np.array(100, dtype=np.float32, ndmin=1)
+
+ def getarg2(self):
+ return self.getarg().reshape(1,1)
+
+ def test_global_constants(self):
+ udt = cuda.jit((float32[:],))(udt_global_constants)
+ udt[1, 1](self.getarg())
+
+ def test_global_build_tuple(self):
+ udt = cuda.jit((float32[:, :],))(udt_global_build_tuple)
+ udt[1, 1](self.getarg2())
+
+ @skip_on_cudasim('Simulator does not prohibit lists for shared array shape')
+ def test_global_build_list(self):
+ with self.assertRaises(TypingError) as raises:
+ cuda.jit((float32[:, :],))(udt_global_build_list)
+
+ self.assertIn("No implementation of function "
+ "Function(>> array(shape=list(int64), "
+ "dtype=class(float32)",
+ str(raises.exception))
+
+ def test_global_constant_tuple(self):
+ udt = cuda.jit((float32[:, :],))(udt_global_constant_tuple)
+ udt[1, 1](self.getarg2())
+
+ @skip_on_cudasim("Can't check for constants in simulator")
+ def test_invalid_1(self):
+ # Scalar shape cannot be a floating point value
+ with self.assertRaises(TypingError) as raises:
+ cuda.jit((float32[:],))(udt_invalid_1)
+
+ self.assertIn("No implementation of function "
+ "Function(>> array(shape=float32, dtype=class(float32))",
+ str(raises.exception))
+
+ @skip_on_cudasim("Can't check for constants in simulator")
+ def test_invalid_2(self):
+ # Tuple shape cannot contain a floating point value
+ with self.assertRaises(TypingError) as raises:
+ cuda.jit((float32[:, :],))(udt_invalid_2)
+
+ self.assertIn("No implementation of function "
+ "Function(>> array(shape=Tuple(Literal[int](1), "
+ "array(float32, 1d, A)), dtype=class(float32))",
+ str(raises.exception))
+
+ @skip_on_cudasim("Can't check for constants in simulator")
+ def test_invalid_3(self):
+ # Scalar shape must be literal
+ with self.assertRaises(TypingError) as raises:
+ cuda.jit((int32[:],))(udt_invalid_1)
+
+ self.assertIn("No implementation of function "
+ "Function(>> array(shape=int32, dtype=class(float32))",
+ str(raises.exception))
+
+ @skip_on_cudasim("Can't check for constants in simulator")
+ def test_invalid_4(self):
+ # Tuple shape must contain only literals
+ with self.assertRaises(TypingError) as raises:
+ cuda.jit((int32[:],))(udt_invalid_3)
+
+ self.assertIn("No implementation of function "
+ "Function(>> array(shape=Tuple(Literal[int](1), int32), "
+ "dtype=class(float32))",
+ str(raises.exception))
+
+ def check_dtype(self, f, dtype):
+ # Find the typing of the dtype argument to cuda.shared.array
+ annotation = next(iter(f.overloads.values()))._type_annotation
+ l_dtype = annotation.typemap['s'].dtype
+ # Ensure that the typing is correct
+ self.assertEqual(l_dtype, dtype)
+
+ @skip_on_cudasim("Can't check typing in simulator")
+ def test_numba_dtype(self):
+ # Check that Numba types can be used as the dtype of a shared array
+ @cuda.jit(void(int32[::1]))
+ def f(x):
+ s = cuda.shared.array(10, dtype=int32)
+ s[0] = x[0]
+ x[0] = s[0]
+
+ self.check_dtype(f, int32)
+
+ @skip_on_cudasim("Can't check typing in simulator")
+ def test_numpy_dtype(self):
+ # Check that NumPy types can be used as the dtype of a shared array
+ @cuda.jit(void(int32[::1]))
+ def f(x):
+ s = cuda.shared.array(10, dtype=np.int32)
+ s[0] = x[0]
+ x[0] = s[0]
+
+ self.check_dtype(f, int32)
+
+ @skip_on_cudasim("Can't check typing in simulator")
+ def test_string_dtype(self):
+ # Check that strings can be used to specify the dtype of a shared array
+ @cuda.jit(void(int32[::1]))
+ def f(x):
+ s = cuda.shared.array(10, dtype='int32')
+ s[0] = x[0]
+ x[0] = s[0]
+
+ self.check_dtype(f, int32)
+
+ @skip_on_cudasim("Can't check typing in simulator")
+ def test_invalid_string_dtype(self):
+ # Check that strings of invalid dtypes cause a typing error
+ re = ".*Invalid NumPy dtype specified: 'int33'.*"
+ with self.assertRaisesRegex(TypingError, re):
+ @cuda.jit(void(int32[::1]))
+ def f(x):
+ s = cuda.shared.array(10, dtype='int33')
+ s[0] = x[0]
+ x[0] = s[0]
+
+ @skip_on_cudasim("Can't check typing in simulator")
+ def test_type_with_struct_data_model(self):
+ @cuda.jit(void(test_struct_model_type[::1]))
+ def f(x):
+ s = cuda.shared.array(10, dtype=test_struct_model_type)
+ s[0] = x[0]
+ x[0] = s[0]
+ self.check_dtype(f, test_struct_model_type)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_sync.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_sync.py
new file mode 100644
index 0000000000000000000000000000000000000000..d4d9326f0357e1c299d4bd9c5781e5e2a22b7002
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_sync.py
@@ -0,0 +1,271 @@
+import numpy as np
+from numba import cuda, int32, float32
+from numba.cuda.testing import skip_on_cudasim, unittest, CUDATestCase
+from numba.core.config import ENABLE_CUDASIM
+
+
+def useless_syncthreads(ary):
+ i = cuda.grid(1)
+ cuda.syncthreads()
+ ary[i] = i
+
+
+def useless_syncwarp(ary):
+ i = cuda.grid(1)
+ cuda.syncwarp()
+ ary[i] = i
+
+
+def useless_syncwarp_with_mask(ary):
+ i = cuda.grid(1)
+ cuda.syncwarp(0xFFFF)
+ ary[i] = i
+
+
+def coop_syncwarp(res):
+ sm = cuda.shared.array(32, int32)
+ i = cuda.grid(1)
+
+ sm[i] = i
+ cuda.syncwarp()
+
+ if i < 16:
+ sm[i] = sm[i] + sm[i + 16]
+ cuda.syncwarp(0xFFFF)
+
+ if i < 8:
+ sm[i] = sm[i] + sm[i + 8]
+ cuda.syncwarp(0xFF)
+
+ if i < 4:
+ sm[i] = sm[i] + sm[i + 4]
+ cuda.syncwarp(0xF)
+
+ if i < 2:
+ sm[i] = sm[i] + sm[i + 2]
+ cuda.syncwarp(0x3)
+
+ if i == 0:
+ res[0] = sm[0] + sm[1]
+
+
+def simple_smem(ary):
+ N = 100
+ sm = cuda.shared.array(N, int32)
+ i = cuda.grid(1)
+ if i == 0:
+ for j in range(N):
+ sm[j] = j
+ cuda.syncthreads()
+ ary[i] = sm[i]
+
+
+def coop_smem2d(ary):
+ i, j = cuda.grid(2)
+ sm = cuda.shared.array((10, 20), float32)
+ sm[i, j] = (i + 1) / (j + 1)
+ cuda.syncthreads()
+ ary[i, j] = sm[i, j]
+
+
+def dyn_shared_memory(ary):
+ i = cuda.grid(1)
+ sm = cuda.shared.array(0, float32)
+ sm[i] = i * 2
+ cuda.syncthreads()
+ ary[i] = sm[i]
+
+
+def use_threadfence(ary):
+ ary[0] += 123
+ cuda.threadfence()
+ ary[0] += 321
+
+
+def use_threadfence_block(ary):
+ ary[0] += 123
+ cuda.threadfence_block()
+ ary[0] += 321
+
+
+def use_threadfence_system(ary):
+ ary[0] += 123
+ cuda.threadfence_system()
+ ary[0] += 321
+
+
+def use_syncthreads_count(ary_in, ary_out):
+ i = cuda.grid(1)
+ ary_out[i] = cuda.syncthreads_count(ary_in[i])
+
+
+def use_syncthreads_and(ary_in, ary_out):
+ i = cuda.grid(1)
+ ary_out[i] = cuda.syncthreads_and(ary_in[i])
+
+
+def use_syncthreads_or(ary_in, ary_out):
+ i = cuda.grid(1)
+ ary_out[i] = cuda.syncthreads_or(ary_in[i])
+
+
+def _safe_cc_check(cc):
+ if ENABLE_CUDASIM:
+ return True
+ else:
+ return cuda.get_current_device().compute_capability >= cc
+
+
+class TestCudaSync(CUDATestCase):
+ def _test_useless(self, kernel):
+ compiled = cuda.jit("void(int32[::1])")(kernel)
+ nelem = 10
+ ary = np.empty(nelem, dtype=np.int32)
+ exp = np.arange(nelem, dtype=np.int32)
+ compiled[1, nelem](ary)
+ np.testing.assert_equal(ary, exp)
+
+ def test_useless_syncthreads(self):
+ self._test_useless(useless_syncthreads)
+
+ @skip_on_cudasim("syncwarp not implemented on cudasim")
+ def test_useless_syncwarp(self):
+ self._test_useless(useless_syncwarp)
+
+ @skip_on_cudasim("syncwarp not implemented on cudasim")
+ @unittest.skipUnless(_safe_cc_check((7, 0)),
+ "Partial masks require CC 7.0 or greater")
+ def test_useless_syncwarp_with_mask(self):
+ self._test_useless(useless_syncwarp_with_mask)
+
+ @skip_on_cudasim("syncwarp not implemented on cudasim")
+ @unittest.skipUnless(_safe_cc_check((7, 0)),
+ "Partial masks require CC 7.0 or greater")
+ def test_coop_syncwarp(self):
+ # coop_syncwarp computes the sum of all integers from 0 to 31 (496)
+ # using a single warp
+ expected = 496
+ nthreads = 32
+ nblocks = 1
+
+ compiled = cuda.jit("void(int32[::1])")(coop_syncwarp)
+ res = np.zeros(1, dtype=np.int32)
+ compiled[nblocks, nthreads](res)
+ np.testing.assert_equal(expected, res[0])
+
+ def test_simple_smem(self):
+ compiled = cuda.jit("void(int32[::1])")(simple_smem)
+ nelem = 100
+ ary = np.empty(nelem, dtype=np.int32)
+ compiled[1, nelem](ary)
+ self.assertTrue(np.all(ary == np.arange(nelem, dtype=np.int32)))
+
+ def test_coop_smem2d(self):
+ compiled = cuda.jit("void(float32[:,::1])")(coop_smem2d)
+ shape = 10, 20
+ ary = np.empty(shape, dtype=np.float32)
+ compiled[1, shape](ary)
+ exp = np.empty_like(ary)
+ for i in range(ary.shape[0]):
+ for j in range(ary.shape[1]):
+ exp[i, j] = (i + 1) / (j + 1)
+ self.assertTrue(np.allclose(ary, exp))
+
+ def test_dyn_shared_memory(self):
+ compiled = cuda.jit("void(float32[::1])")(dyn_shared_memory)
+ shape = 50
+ ary = np.empty(shape, dtype=np.float32)
+ compiled[1, shape, 0, ary.size * 4](ary)
+ self.assertTrue(np.all(ary == 2 * np.arange(ary.size, dtype=np.int32)))
+
+ def test_threadfence_codegen(self):
+ # Does not test runtime behavior, just the code generation.
+ sig = (int32[:],)
+ compiled = cuda.jit(sig)(use_threadfence)
+ ary = np.zeros(10, dtype=np.int32)
+ compiled[1, 1](ary)
+ self.assertEqual(123 + 321, ary[0])
+ if not ENABLE_CUDASIM:
+ self.assertIn("membar.gl;", compiled.inspect_asm(sig))
+
+ def test_threadfence_block_codegen(self):
+ # Does not test runtime behavior, just the code generation.
+ sig = (int32[:],)
+ compiled = cuda.jit(sig)(use_threadfence_block)
+ ary = np.zeros(10, dtype=np.int32)
+ compiled[1, 1](ary)
+ self.assertEqual(123 + 321, ary[0])
+ if not ENABLE_CUDASIM:
+ self.assertIn("membar.cta;", compiled.inspect_asm(sig))
+
+ def test_threadfence_system_codegen(self):
+ # Does not test runtime behavior, just the code generation.
+ sig = (int32[:],)
+ compiled = cuda.jit(sig)(use_threadfence_system)
+ ary = np.zeros(10, dtype=np.int32)
+ compiled[1, 1](ary)
+ self.assertEqual(123 + 321, ary[0])
+ if not ENABLE_CUDASIM:
+ self.assertIn("membar.sys;", compiled.inspect_asm(sig))
+
+ def _test_syncthreads_count(self, in_dtype):
+ compiled = cuda.jit(use_syncthreads_count)
+ ary_in = np.ones(72, dtype=in_dtype)
+ ary_out = np.zeros(72, dtype=np.int32)
+ ary_in[31] = 0
+ ary_in[42] = 0
+ compiled[1, 72](ary_in, ary_out)
+ self.assertTrue(np.all(ary_out == 70))
+
+ def test_syncthreads_count(self):
+ self._test_syncthreads_count(np.int32)
+
+ def test_syncthreads_count_upcast(self):
+ self._test_syncthreads_count(np.int16)
+
+ def test_syncthreads_count_downcast(self):
+ self._test_syncthreads_count(np.int64)
+
+ def _test_syncthreads_and(self, in_dtype):
+ compiled = cuda.jit(use_syncthreads_and)
+ nelem = 100
+ ary_in = np.ones(nelem, dtype=in_dtype)
+ ary_out = np.zeros(nelem, dtype=np.int32)
+ compiled[1, nelem](ary_in, ary_out)
+ self.assertTrue(np.all(ary_out == 1))
+ ary_in[31] = 0
+ compiled[1, nelem](ary_in, ary_out)
+ self.assertTrue(np.all(ary_out == 0))
+
+ def test_syncthreads_and(self):
+ self._test_syncthreads_and(np.int32)
+
+ def test_syncthreads_and_upcast(self):
+ self._test_syncthreads_and(np.int16)
+
+ def test_syncthreads_and_downcast(self):
+ self._test_syncthreads_and(np.int64)
+
+ def _test_syncthreads_or(self, in_dtype):
+ compiled = cuda.jit(use_syncthreads_or)
+ nelem = 100
+ ary_in = np.zeros(nelem, dtype=in_dtype)
+ ary_out = np.zeros(nelem, dtype=np.int32)
+ compiled[1, nelem](ary_in, ary_out)
+ self.assertTrue(np.all(ary_out == 0))
+ ary_in[31] = 1
+ compiled[1, nelem](ary_in, ary_out)
+ self.assertTrue(np.all(ary_out == 1))
+
+ def test_syncthreads_or(self):
+ self._test_syncthreads_or(np.int32)
+
+ def test_syncthreads_or_upcast(self):
+ self._test_syncthreads_or(np.int16)
+
+ def test_syncthreads_or_downcast(self):
+ self._test_syncthreads_or(np.int64)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_transpose.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_transpose.py
new file mode 100644
index 0000000000000000000000000000000000000000..9c13db5341c15c69e0d04dcb9bc2aa40a17bdda1
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_transpose.py
@@ -0,0 +1,80 @@
+import numpy as np
+from numba import cuda
+from numba.cuda.kernels.transpose import transpose
+from numba.cuda.testing import unittest
+from numba.cuda.testing import skip_on_cudasim, CUDATestCase
+
+
+recordwith2darray = np.dtype([('i', np.int32),
+ ('j', np.float32, (3, 2))])
+
+
+@skip_on_cudasim('Device Array API unsupported in the simulator')
+class TestTranspose(CUDATestCase):
+
+ def test_transpose(self):
+ variants = ((5, 6, np.float64),
+ (128, 128, np.complex128),
+ (1025, 512, np.float64))
+
+ for rows, cols, dtype in variants:
+ with self.subTest(rows=rows, cols=cols, dtype=dtype):
+ x = np.arange(rows * cols, dtype=dtype).reshape(cols, rows)
+ y = np.zeros(rows * cols, dtype=dtype).reshape(rows, cols)
+ dx = cuda.to_device(x)
+ dy = cuda.cudadrv.devicearray.from_array_like(y)
+ transpose(dx, dy)
+ dy.copy_to_host(y)
+ np.testing.assert_array_equal(x.transpose(), y)
+
+ small_variants = ((2, 3), (16, 16), (16, 17), (17, 16), (14, 15), (15, 14),
+ (14, 14))
+
+ def test_transpose_record(self):
+ for rows, cols in self.small_variants:
+ with self.subTest(rows=rows, cols=cols):
+ arr = np.recarray((rows, cols), dtype=recordwith2darray)
+ for x in range(rows):
+ for y in range(cols):
+ arr[x, y].i = x ** 2 + y
+ j = np.arange(3 * 2, dtype=np.float32)
+ arr[x, y].j = j.reshape(3, 2) * x + y
+
+ transposed = arr.T
+ d_arr = cuda.to_device(arr)
+ d_transposed = cuda.device_array_like(transposed)
+ transpose(d_arr, d_transposed)
+ host_transposed = d_transposed.copy_to_host()
+ np.testing.assert_array_equal(transposed, host_transposed)
+
+ def test_transpose_bool(self):
+ for rows, cols in self.small_variants:
+ with self.subTest(rows=rows, cols=cols):
+ arr = np.random.randint(2, size=(rows, cols), dtype=np.bool_)
+ transposed = arr.T
+
+ d_arr = cuda.to_device(arr)
+ d_transposed = cuda.device_array_like(transposed)
+ transpose(d_arr, d_transposed)
+
+ host_transposed = d_transposed.copy_to_host()
+ np.testing.assert_array_equal(transposed, host_transposed)
+
+ def test_transpose_view(self):
+ # Because the strides of transposes of views differ to those in NumPy
+ # (see issue #4974), we test the shape and strides of a transpose.
+ a = np.arange(120, dtype=np.int64).reshape((10, 12))
+ a_view_t = a[::2, ::2].T
+
+ d_a = cuda.to_device(a)
+ d_a_view_t = d_a[::2, ::2].T
+
+ self.assertEqual(d_a_view_t.shape, (6, 5))
+ self.assertEqual(d_a_view_t.strides, (40, 8))
+
+ h_a_view_t = d_a_view_t.copy_to_host()
+ np.testing.assert_array_equal(a_view_t, h_a_view_t)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_ufuncs.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_ufuncs.py
new file mode 100644
index 0000000000000000000000000000000000000000..7a98abde74fe68c1788d6ee9876777dc12b06330
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_ufuncs.py
@@ -0,0 +1,277 @@
+import functools
+import numpy as np
+import unittest
+
+from numba import config, cuda, types
+from numba.tests.support import TestCase
+from numba.tests.test_ufuncs import BasicUFuncTest
+
+
+def _make_ufunc_usecase(ufunc):
+ ldict = {}
+ arg_str = ','.join(['a{0}'.format(i) for i in range(ufunc.nargs)])
+ func_str = f'def fn({arg_str}):\n np.{ufunc.__name__}({arg_str})'
+ exec(func_str, globals(), ldict)
+ fn = ldict['fn']
+ fn.__name__ = '{0}_usecase'.format(ufunc.__name__)
+ return fn
+
+
+# This test would also be a CUDATestCase, but to avoid a confusing and
+# potentially dangerous inheritance diamond with setUp methods that modify
+# global state, we implement the necessary parts of CUDATestCase within this
+# class instead. These are:
+#
+# - Disable parallel testing with _numba_parallel_test_.
+# - Disabling CUDA performance warnings for the duration of tests.
+class TestUFuncs(BasicUFuncTest, TestCase):
+ _numba_parallel_test_ = False
+
+ def setUp(self):
+ BasicUFuncTest.setUp(self)
+
+ # The basic ufunc test does not set up complex inputs, so we'll add
+ # some here for testing with CUDA.
+ self.inputs.extend([
+ (np.complex64(-0.5 - 0.5j), types.complex64),
+ (np.complex64(0.0), types.complex64),
+ (np.complex64(0.5 + 0.5j), types.complex64),
+
+ (np.complex128(-0.5 - 0.5j), types.complex128),
+ (np.complex128(0.0), types.complex128),
+ (np.complex128(0.5 + 0.5j), types.complex128),
+
+ (np.array([-0.5 - 0.5j, 0.0, 0.5 + 0.5j], dtype='c8'),
+ types.Array(types.complex64, 1, 'C')),
+ (np.array([-0.5 - 0.5j, 0.0, 0.5 + 0.5j], dtype='c16'),
+ types.Array(types.complex128, 1, 'C')),
+ ])
+
+ # Test with multiple dimensions
+ self.inputs.extend([
+ # Basic 2D and 3D arrays
+ (np.linspace(0, 1).reshape((5, -1)),
+ types.Array(types.float64, 2, 'C')),
+ (np.linspace(0, 1).reshape((2, 5, -1)),
+ types.Array(types.float64, 3, 'C')),
+ # Complex data (i.e. interleaved)
+ (np.linspace(0, 1 + 1j).reshape(5, -1),
+ types.Array(types.complex128, 2, 'C')),
+ # F-ordered
+ (np.asfortranarray(np.linspace(0, 1).reshape((5, -1))),
+ types.Array(types.float64, 2, 'F')),
+ ])
+
+ # Add tests for other integer types
+ self.inputs.extend([
+ (np.uint8(0), types.uint8),
+ (np.uint8(1), types.uint8),
+ (np.int8(-1), types.int8),
+ (np.int8(0), types.int8),
+
+ (np.uint16(0), types.uint16),
+ (np.uint16(1), types.uint16),
+ (np.int16(-1), types.int16),
+ (np.int16(0), types.int16),
+
+ (np.ulonglong(0), types.ulonglong),
+ (np.ulonglong(1), types.ulonglong),
+ (np.longlong(-1), types.longlong),
+ (np.longlong(0), types.longlong),
+
+ (np.array([0,1], dtype=np.ulonglong),
+ types.Array(types.ulonglong, 1, 'C')),
+ (np.array([0,1], dtype=np.longlong),
+ types.Array(types.longlong, 1, 'C')),
+ ])
+
+ self._low_occupancy_warnings = config.CUDA_LOW_OCCUPANCY_WARNINGS
+ self._warn_on_implicit_copy = config.CUDA_WARN_ON_IMPLICIT_COPY
+
+ # Disable warnings about low gpu utilization in the test suite
+ config.CUDA_LOW_OCCUPANCY_WARNINGS = 0
+ # Disable warnings about host arrays in the test suite
+ config.CUDA_WARN_ON_IMPLICIT_COPY = 0
+
+ def tearDown(self):
+ # Restore original warning settings
+ config.CUDA_LOW_OCCUPANCY_WARNINGS = self._low_occupancy_warnings
+ config.CUDA_WARN_ON_IMPLICIT_COPY = self._warn_on_implicit_copy
+
+ def _make_ufunc_usecase(self, ufunc):
+ return _make_ufunc_usecase(ufunc)
+
+ @functools.lru_cache(maxsize=None)
+ def _compile(self, pyfunc, args):
+ # We return an already-configured kernel so that basic_ufunc_test can
+ # call it just like it does for a CPU function
+ return cuda.jit(args)(pyfunc)[1, 1]
+
+ def basic_int_ufunc_test(self, name=None):
+ skip_inputs = [
+ types.float32,
+ types.float64,
+ types.Array(types.float32, 1, 'C'),
+ types.Array(types.float32, 2, 'C'),
+ types.Array(types.float64, 1, 'C'),
+ types.Array(types.float64, 2, 'C'),
+ types.Array(types.float64, 3, 'C'),
+ types.Array(types.float64, 2, 'F'),
+ types.complex64,
+ types.complex128,
+ types.Array(types.complex64, 1, 'C'),
+ types.Array(types.complex64, 2, 'C'),
+ types.Array(types.complex128, 1, 'C'),
+ types.Array(types.complex128, 2, 'C'),
+ ]
+ self.basic_ufunc_test(name, skip_inputs=skip_inputs)
+
+ ############################################################################
+ # Trigonometric Functions
+
+ def test_sin_ufunc(self):
+ self.basic_ufunc_test(np.sin, kinds='cf')
+
+ def test_cos_ufunc(self):
+ self.basic_ufunc_test(np.cos, kinds='cf')
+
+ def test_tan_ufunc(self):
+ self.basic_ufunc_test(np.tan, kinds='cf')
+
+ def test_arcsin_ufunc(self):
+ self.basic_ufunc_test(np.arcsin, kinds='cf')
+
+ def test_arccos_ufunc(self):
+ self.basic_ufunc_test(np.arccos, kinds='cf')
+
+ def test_arctan_ufunc(self):
+ self.basic_ufunc_test(np.arctan, kinds='cf')
+
+ def test_arctan2_ufunc(self):
+ self.basic_ufunc_test(np.arctan2, kinds='f')
+
+ def test_hypot_ufunc(self):
+ self.basic_ufunc_test(np.hypot, kinds='f')
+
+ def test_sinh_ufunc(self):
+ self.basic_ufunc_test(np.sinh, kinds='cf')
+
+ def test_cosh_ufunc(self):
+ self.basic_ufunc_test(np.cosh, kinds='cf')
+
+ def test_tanh_ufunc(self):
+ self.basic_ufunc_test(np.tanh, kinds='cf')
+
+ def test_arcsinh_ufunc(self):
+ self.basic_ufunc_test(np.arcsinh, kinds='cf')
+
+ def test_arccosh_ufunc(self):
+ self.basic_ufunc_test(np.arccosh, kinds='cf')
+
+ def test_arctanh_ufunc(self):
+ # arctanh is only valid is only finite in the range ]-1, 1[
+ # This means that for any of the integer types it will produce
+ # conversion from infinity/-infinity to integer. That's undefined
+ # behavior in C, so the results may vary from implementation to
+ # implementation. This means that the result from the compiler
+ # used to compile NumPy may differ from the result generated by
+ # llvm. Skipping the integer types in this test avoids failed
+ # tests because of this.
+ to_skip = [types.Array(types.uint32, 1, 'C'), types.uint32,
+ types.Array(types.int32, 1, 'C'), types.int32,
+ types.Array(types.uint64, 1, 'C'), types.uint64,
+ types.Array(types.int64, 1, 'C'), types.int64]
+
+ self.basic_ufunc_test(np.arctanh, skip_inputs=to_skip, kinds='cf')
+
+ def test_deg2rad_ufunc(self):
+ self.basic_ufunc_test(np.deg2rad, kinds='f')
+
+ def test_rad2deg_ufunc(self):
+ self.basic_ufunc_test(np.rad2deg, kinds='f')
+
+ def test_degrees_ufunc(self):
+ self.basic_ufunc_test(np.degrees, kinds='f')
+
+ def test_radians_ufunc(self):
+ self.basic_ufunc_test(np.radians, kinds='f')
+
+ ############################################################################
+ # Comparison functions
+ def test_greater_ufunc(self):
+ self.signed_unsigned_cmp_test(np.greater)
+
+ def test_greater_equal_ufunc(self):
+ self.signed_unsigned_cmp_test(np.greater_equal)
+
+ def test_less_ufunc(self):
+ self.signed_unsigned_cmp_test(np.less)
+
+ def test_less_equal_ufunc(self):
+ self.signed_unsigned_cmp_test(np.less_equal)
+
+ def test_not_equal_ufunc(self):
+ self.signed_unsigned_cmp_test(np.not_equal)
+
+ def test_equal_ufunc(self):
+ self.signed_unsigned_cmp_test(np.equal)
+
+ def test_logical_and_ufunc(self):
+ self.basic_ufunc_test(np.logical_and)
+
+ def test_logical_or_ufunc(self):
+ self.basic_ufunc_test(np.logical_or)
+
+ def test_logical_xor_ufunc(self):
+ self.basic_ufunc_test(np.logical_xor)
+
+ def test_logical_not_ufunc(self):
+ self.basic_ufunc_test(np.logical_not)
+
+ def test_maximum_ufunc(self):
+ self.basic_ufunc_test(np.maximum)
+
+ def test_minimum_ufunc(self):
+ self.basic_ufunc_test(np.minimum)
+
+ def test_fmax_ufunc(self):
+ self.basic_ufunc_test(np.fmax)
+
+ def test_fmin_ufunc(self):
+ self.basic_ufunc_test(np.fmin)
+
+ def test_bitwise_and_ufunc(self):
+ self.basic_int_ufunc_test(np.bitwise_and)
+
+ def test_bitwise_or_ufunc(self):
+ self.basic_int_ufunc_test(np.bitwise_or)
+
+ def test_bitwise_xor_ufunc(self):
+ self.basic_int_ufunc_test(np.bitwise_xor)
+
+ def test_invert_ufunc(self):
+ self.basic_int_ufunc_test(np.invert)
+
+ def test_bitwise_not_ufunc(self):
+ self.basic_int_ufunc_test(np.bitwise_not)
+
+ # Note: there is no entry for np.left_shift and np.right_shift
+ # because their implementations in NumPy have undefined behavior
+ # when the second argument is a negative. See the comment in
+ # numba/tests/test_ufuncs.py for more details.
+
+ ############################################################################
+ # Mathematical Functions
+
+ def test_log_ufunc(self):
+ self.basic_ufunc_test(np.log, kinds='cf')
+
+ def test_log2_ufunc(self):
+ self.basic_ufunc_test(np.log2, kinds='cf')
+
+ def test_log10_ufunc(self):
+ self.basic_ufunc_test(np.log10, kinds='cf')
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_userexc.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_userexc.py
new file mode 100644
index 0000000000000000000000000000000000000000..2dca9c9f778d68168485b3a6457ce60e4f173c19
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_userexc.py
@@ -0,0 +1,47 @@
+from numba.cuda.testing import unittest, CUDATestCase
+from numba import cuda
+from numba.core import config
+
+
+class MyError(Exception):
+ pass
+
+
+regex_pattern = (
+ r'In function [\'"]test_exc[\'"], file [\:\.\/\\\-a-zA-Z_0-9]+, line \d+'
+)
+
+
+class TestUserExc(CUDATestCase):
+
+ def setUp(self):
+ super().setUp()
+ # LTO optimizes away the exception status due to an oversight
+ # in the way we generate it (it is not added to the used list).
+ # See https://github.com/numba/numba/issues/9526.
+ self.skip_if_lto("Exceptions not supported with LTO")
+
+ def test_user_exception(self):
+ @cuda.jit("void(int32)", debug=True)
+ def test_exc(x):
+ if x == 1:
+ raise MyError
+ elif x == 2:
+ raise MyError("foo")
+
+ test_exc[1, 1](0) # no raise
+ with self.assertRaises(MyError) as cm:
+ test_exc[1, 1](1)
+ if not config.ENABLE_CUDASIM:
+ self.assertRegex(str(cm.exception), regex_pattern)
+ self.assertIn("tid=[0, 0, 0] ctaid=[0, 0, 0]", str(cm.exception))
+ with self.assertRaises(MyError) as cm:
+ test_exc[1, 1](2)
+ if not config.ENABLE_CUDASIM:
+ self.assertRegex(str(cm.exception), regex_pattern)
+ self.assertRegex(str(cm.exception), regex_pattern)
+ self.assertIn("tid=[0, 0, 0] ctaid=[0, 0, 0]: foo", str(cm.exception))
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_vector_type.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_vector_type.py
new file mode 100644
index 0000000000000000000000000000000000000000..1ee72f2d390ba07cc65b73008f898405243f0016
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_vector_type.py
@@ -0,0 +1,307 @@
+"""
+CUDA vector type tests. Note that this test file imports
+`cuda.vector_type` module to programmatically test all the
+vector types. However, `vector_type` module is internal
+and should not be imported by user, user should only import the
+corresponding vector type from `cuda` module in kernel to use them.
+"""
+
+import numpy as np
+
+from numba.core import config
+from numba.cuda.testing import CUDATestCase
+
+from numba import cuda
+
+if config.ENABLE_CUDASIM:
+ from numba.cuda.simulator.vector_types import vector_types
+else:
+ from numba.cuda.vector_types import vector_types
+
+
+def make_kernel(vtype):
+ """
+ Returns a jit compiled kernel that constructs a vector types of
+ the given type, using the exact number of primitive types to
+ construct the vector type.
+ """
+ vobj = vtype.user_facing_object
+ base_type = vtype.base_type
+
+ def kernel_1elem(res):
+ v = vobj(base_type(0))
+ res[0] = v.x
+
+ def kernel_2elem(res):
+ v = vobj(base_type(0), base_type(1))
+ res[0] = v.x
+ res[1] = v.y
+
+ def kernel_3elem(res):
+ v = vobj(base_type(0), base_type(1), base_type(2))
+ res[0] = v.x
+ res[1] = v.y
+ res[2] = v.z
+
+ def kernel_4elem(res):
+ v = vobj(
+ base_type(0),
+ base_type(1),
+ base_type(2),
+ base_type(3)
+ )
+ res[0] = v.x
+ res[1] = v.y
+ res[2] = v.z
+ res[3] = v.w
+
+ host_function = {
+ 1: kernel_1elem,
+ 2: kernel_2elem,
+ 3: kernel_3elem,
+ 4: kernel_4elem
+ }[vtype.num_elements]
+ return cuda.jit(host_function)
+
+
+def make_fancy_creation_kernel(vtype):
+ """
+ Returns a jit compiled kernel that constructs a vector type using the
+ "fancy" construction, that is, with arbitrary combinations of primitive
+ types and vector types, as long as the total element of the construction
+ is the same as the number of elements of the vector type.
+ """
+ base_type = vtype.base_type
+ v1 = getattr(cuda, f"{vtype.name[:-1]}1")
+ v2 = getattr(cuda, f"{vtype.name[:-1]}2")
+ v3 = getattr(cuda, f"{vtype.name[:-1]}3")
+ v4 = getattr(cuda, f"{vtype.name[:-1]}4")
+
+ def kernel(res):
+ one = base_type(1.0)
+ two = base_type(2.0)
+ three = base_type(3.0)
+ four = base_type(4.0)
+
+ j = 0 # index of the result array
+
+ # Construct a 1-component vector type, possible combination includes:
+ # 2C1 = 2 combinations.
+
+ f1_1 = v1(one) # 1
+ f1_2 = v1(f1_1) # 1
+
+ res[0] = f1_1.x
+ res[1] = f1_2.x
+ j += 2
+
+ # Construct a 2-component vector type, possible combination includes:
+ # 1 + 2C1 * 2 = 5 combinations
+
+ f2_1 = v2(two, three) # 2 3
+ f2_2 = v2(f1_1, three) # 1 3
+ f2_3 = v2(two, f1_1) # 2 1
+ f2_4 = v2(f1_1, f1_1) # 1 1
+ f2_5 = v2(f2_1) # 2 3
+
+ for v in (f2_1, f2_2, f2_3, f2_4, f2_5):
+ res[j] = v.x
+ res[j + 1] = v.y
+ j += 2
+
+ # Construct a 3-component vector type, possible combination includes:
+ # 1 + 2C1 * 2 + 2^3 = 13 combinations
+
+ f3_1 = v3(f2_1, one) # 2 3 1
+ f3_2 = v3(f2_1, f1_1) # 2 3 1
+ f3_3 = v3(one, f2_1) # 1 2 3
+ f3_4 = v3(f1_1, f2_1) # 1 2 3
+
+ f3_5 = v3(one, two, three) # 1 2 3
+ f3_6 = v3(f1_1, two, three) # 1 2 3
+ f3_7 = v3(one, f1_1, three) # 1 1 3
+ f3_8 = v3(one, two, f1_1) # 1 2 1
+ f3_9 = v3(f1_1, f1_1, three) # 1 1 3
+ f3_10 = v3(one, f1_1, f1_1) # 1 1 1
+ f3_11 = v3(f1_1, two, f1_1) # 1 2 1
+ f3_12 = v3(f1_1, f1_1, f1_1) # 1 1 1
+
+ f3_13 = v3(f3_1) # 2 3 1
+
+ for v in (f3_1, f3_2, f3_3, f3_4, f3_5, f3_6, f3_7, f3_8, f3_9,
+ f3_10, f3_11, f3_12, f3_13):
+ res[j] = v.x
+ res[j + 1] = v.y
+ res[j + 2] = v.z
+ j += 3
+
+ # Construct a 4-component vector type, possible combination includes:
+ # 1 + (2C1 * 2 + 1) + 3C1 * 2^2 + 2^4 = 34 combinations
+
+ f4_1 = v4(one, two, three, four) # 1 2 3 4
+ f4_2 = v4(f1_1, two, three, four) # 1 2 3 4
+ f4_3 = v4(one, f1_1, three, four) # 1 1 3 4
+ f4_4 = v4(one, two, f1_1, four) # 1 2 1 4
+ f4_5 = v4(one, two, three, f1_1) # 1 2 3 1
+ f4_6 = v4(f1_1, f1_1, three, four) # 1 1 3 4
+ f4_7 = v4(f1_1, two, f1_1, four) # 1 2 1 4
+ f4_8 = v4(f1_1, two, three, f1_1) # 1 2 3 1
+ f4_9 = v4(one, f1_1, f1_1, four) # 1 1 1 4
+ f4_10 = v4(one, f1_1, three, f1_1) # 1 1 3 1
+ f4_11 = v4(one, two, f1_1, f1_1) # 1 2 1 1
+ f4_12 = v4(f1_1, f1_1, f1_1, four) # 1 1 1 4
+ f4_13 = v4(f1_1, f1_1, three, f1_1) # 1 1 3 1
+ f4_14 = v4(f1_1, two, f1_1, f1_1) # 1 2 1 1
+ f4_15 = v4(one, f1_1, f1_1, f1_1) # 1 1 1 1
+ f4_16 = v4(f1_1, f1_1, f1_1, f1_1) # 1 1 1 1
+
+ f4_17 = v4(f2_1, two, three) # 2 3 2 3
+ f4_18 = v4(f2_1, f1_1, three) # 2 3 1 3
+ f4_19 = v4(f2_1, two, f1_1) # 2 3 2 1
+ f4_20 = v4(f2_1, f1_1, f1_1) # 2 3 1 1
+ f4_21 = v4(one, f2_1, three) # 1 2 3 3
+ f4_22 = v4(f1_1, f2_1, three) # 1 2 3 3
+ f4_23 = v4(one, f2_1, f1_1) # 1 2 3 1
+ f4_24 = v4(f1_1, f2_1, f1_1) # 1 2 3 1
+ f4_25 = v4(one, four, f2_1) # 1 4 2 3
+ f4_26 = v4(f1_1, four, f2_1) # 1 4 2 3
+ f4_27 = v4(one, f1_1, f2_1) # 1 1 2 3
+ f4_28 = v4(f1_1, f1_1, f2_1) # 1 1 2 3
+
+ f4_29 = v4(f2_1, f2_1) # 2 3 2 3
+ f4_30 = v4(f3_1, four) # 2 3 1 4
+ f4_31 = v4(f3_1, f1_1) # 2 3 1 1
+ f4_32 = v4(four, f3_1) # 4 2 3 1
+ f4_33 = v4(f1_1, f3_1) # 1 2 3 1
+
+ f4_34 = v4(f4_1) # 1 2 3 4
+
+ for v in (f4_1, f4_2, f4_3, f4_4, f4_5, f4_6, f4_7, f4_8, f4_9, f4_10,
+ f4_11, f4_12, f4_13, f4_14, f4_15, f4_16, f4_17, f4_18, f4_19,
+ f4_20, f4_21, f4_22, f4_23, f4_24, f4_25, f4_26, f4_27, f4_28,
+ f4_29, f4_30, f4_31, f4_32, f4_33, f4_34):
+ res[j] = v.x
+ res[j + 1] = v.y
+ res[j + 2] = v.z
+ res[j + 3] = v.w
+ j += 4
+
+ return cuda.jit(kernel)
+
+
+class TestCudaVectorType(CUDATestCase):
+
+ def test_basic(self):
+ """Basic test that makes sure that vector type and aliases
+ are available within the cuda module from both device and
+ simulator mode. This is an important sanity check, since other
+ tests below tests the vector type objects programmatically.
+ """
+ @cuda.jit("void(float64[:])")
+ def kernel(arr):
+ v1 = cuda.float64x4(1.0, 3.0, 5.0, 7.0)
+ v2 = cuda.short2(10, 11)
+ arr[0] = v1.x
+ arr[1] = v1.y
+ arr[2] = v1.z
+ arr[3] = v1.w
+ arr[4] = v2.x
+ arr[5] = v2.y
+
+ res = np.zeros(6, dtype=np.float64)
+ kernel[1, 1](res)
+ self.assertTrue(np.allclose(res, [1.0, 3.0, 5.0, 7.0, 10, 11]))
+
+ def test_creation_readout(self):
+ for vty in vector_types.values():
+ with self.subTest(vty=vty):
+ arr = np.zeros((vty.num_elements,))
+ kernel = make_kernel(vty)
+ kernel[1, 1](arr)
+ np.testing.assert_almost_equal(
+ arr, np.array(range(vty.num_elements))
+ )
+
+ def test_fancy_creation_readout(self):
+ for vty in vector_types.values():
+ with self.subTest(vty=vty):
+ kernel = make_fancy_creation_kernel(vty)
+
+ expected = np.array([
+ # 1-component vectors
+ 1,
+ 1,
+ # 2-component vectors
+ 2, 3,
+ 1, 3,
+ 2, 1,
+ 1, 1,
+ 2, 3,
+ # 3-component vectors
+ 2, 3, 1,
+ 2, 3, 1,
+ 1, 2, 3,
+ 1, 2, 3,
+ 1, 2, 3,
+ 1, 2, 3,
+ 1, 1, 3,
+ 1, 2, 1,
+ 1, 1, 3,
+ 1, 1, 1,
+ 1, 2, 1,
+ 1, 1, 1,
+ 2, 3, 1,
+ # 4-component vectors
+ 1, 2, 3, 4,
+ 1, 2, 3, 4,
+ 1, 1, 3, 4,
+ 1, 2, 1, 4,
+ 1, 2, 3, 1,
+ 1, 1, 3, 4,
+ 1, 2, 1, 4,
+ 1, 2, 3, 1,
+ 1, 1, 1, 4,
+ 1, 1, 3, 1,
+ 1, 2, 1, 1,
+ 1, 1, 1, 4,
+ 1, 1, 3, 1,
+ 1, 2, 1, 1,
+ 1, 1, 1, 1,
+ 1, 1, 1, 1,
+ 2, 3, 2, 3,
+ 2, 3, 1, 3,
+ 2, 3, 2, 1,
+ 2, 3, 1, 1,
+ 1, 2, 3, 3,
+ 1, 2, 3, 3,
+ 1, 2, 3, 1,
+ 1, 2, 3, 1,
+ 1, 4, 2, 3,
+ 1, 4, 2, 3,
+ 1, 1, 2, 3,
+ 1, 1, 2, 3,
+ 2, 3, 2, 3,
+ 2, 3, 1, 4,
+ 2, 3, 1, 1,
+ 4, 2, 3, 1,
+ 1, 2, 3, 1,
+ 1, 2, 3, 4
+ ])
+ arr = np.zeros(expected.shape)
+ kernel[1, 1](arr)
+ np.testing.assert_almost_equal(arr, expected)
+
+ def test_vector_type_alias(self):
+ """Tests that `cuda.` are importable and
+ that is the same as `cuda.`.
+
+ `test_fancy_creation_readout` only test vector types imported
+ with its name. This test makes sure that construction with
+ objects imported with alias should work the same.
+ """
+ for vty in vector_types.values():
+ for alias in vty.user_facing_object.aliases:
+ with self.subTest(vty=vty.name, alias=alias):
+ self.assertEqual(
+ id(getattr(cuda, vty.name)), id(getattr(cuda, alias))
+ )
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_vectorize.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_vectorize.py
new file mode 100644
index 0000000000000000000000000000000000000000..c88e1792b53fe34981d075addaca4d09ffd31c5b
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_vectorize.py
@@ -0,0 +1,283 @@
+import numpy as np
+
+from collections import namedtuple
+from itertools import product
+from numba import vectorize
+from numba import cuda, int32, float32, float64
+from numba.cuda.cudadrv.driver import CudaAPIError, driver
+from numba.cuda.testing import skip_on_cudasim
+from numba.cuda.testing import CUDATestCase
+import unittest
+
+
+# Signatures to test with - these are all homogeneous in dtype, so the output
+# dtype should match the input dtype - the output should not have been cast
+# upwards, as reported in #8400: https://github.com/numba/numba/issues/8400
+signatures = [int32(int32, int32),
+ float32(float32, float32),
+ float64(float64, float64)]
+
+# The order here is chosen such that each subsequent dtype might have been
+# casted to a previously-used dtype. This is unlikely to be an issue for CUDA,
+# but there might be future circumstances in which it becomes relevant, perhaps
+# if it supported Dynamic UFuncs, and we want to ensure that an implementation
+# for a the given dtype is used rather than casting the input upwards.
+dtypes = (np.float64, np.float32, np.int32)
+
+# NumPy ndarray orders
+orders = ('C', 'F')
+
+# Input sizes corresponding to operations:
+# - Less than one warp,
+# - Less than one block,
+# - Greater than one block (i.e. many blocks)
+input_sizes = (8, 100, 2 ** 10 + 1)
+
+
+@skip_on_cudasim('ufunc API unsupported in the simulator')
+class TestCUDAVectorize(CUDATestCase):
+ # Presumably chosen as an odd number unlikely to coincide with the total
+ # thread count, and large enough to ensure a significant number of blocks
+ # are used.
+ N = 1000001
+
+ def test_scalar(self):
+
+ @vectorize(signatures, target='cuda')
+ def vector_add(a, b):
+ return a + b
+
+ a = 1.2
+ b = 2.3
+ c = vector_add(a, b)
+ self.assertEqual(c, a + b)
+
+ def test_1d(self):
+
+ @vectorize(signatures, target='cuda')
+ def vector_add(a, b):
+ return a + b
+
+ for ty in dtypes:
+ data = np.array(np.random.random(self.N), dtype=ty)
+ expected = np.add(data, data)
+ actual = vector_add(data, data)
+ np.testing.assert_allclose(expected, actual)
+ self.assertEqual(actual.dtype, ty)
+
+ def test_1d_async(self):
+
+ @vectorize(signatures, target='cuda')
+ def vector_add(a, b):
+ return a + b
+
+ stream = cuda.stream()
+
+ for ty in dtypes:
+ data = np.array(np.random.random(self.N), dtype=ty)
+ device_data = cuda.to_device(data, stream)
+
+ dresult = vector_add(device_data, device_data, stream=stream)
+ actual = dresult.copy_to_host()
+
+ expected = np.add(data, data)
+
+ np.testing.assert_allclose(expected, actual)
+ self.assertEqual(actual.dtype, ty)
+
+ def test_nd(self):
+
+ @vectorize(signatures, target='cuda')
+ def vector_add(a, b):
+ return a + b
+
+ for nd, dtype, order in product(range(1, 8), dtypes, orders):
+ shape = (4,) * nd
+ data = np.random.random(shape).astype(dtype)
+ data2 = np.array(data.T, order=order)
+
+ expected = data + data2
+ actual = vector_add(data, data2)
+ np.testing.assert_allclose(expected, actual)
+ self.assertEqual(actual.dtype, dtype)
+
+ def test_output_arg(self):
+ @vectorize(signatures, target='cuda')
+ def vector_add(a, b):
+ return a + b
+
+ A = np.arange(10, dtype=np.float32)
+ B = np.arange(10, dtype=np.float32)
+
+ expected = A + B
+ actual = np.empty_like(A)
+ vector_add(A, B, out=actual)
+
+ np.testing.assert_allclose(expected, actual)
+ self.assertEqual(expected.dtype, actual.dtype)
+
+ def test_reduce(self):
+ @vectorize(signatures, target='cuda')
+ def vector_add(a, b):
+ return a + b
+
+ dtype = np.int32
+
+ for n in input_sizes:
+ x = np.arange(n, dtype=dtype)
+ expected = np.add.reduce(x)
+ actual = vector_add.reduce(x)
+ np.testing.assert_allclose(expected, actual)
+ # np.add.reduce is special-cased to return an int64 for any int
+ # arguments, so we can't compare against its returned dtype when
+ # we're checking the general reduce machinery (which just happens
+ # to be using addition). Instead, compare against the input dtype.
+ self.assertEqual(dtype, actual.dtype)
+
+ def test_reduce_async(self):
+
+ @vectorize(signatures, target='cuda')
+ def vector_add(a, b):
+ return a + b
+
+ stream = cuda.stream()
+ dtype = np.int32
+
+ for n in input_sizes:
+ x = np.arange(n, dtype=dtype)
+ expected = np.add.reduce(x)
+ dx = cuda.to_device(x, stream)
+ actual = vector_add.reduce(dx, stream=stream)
+ np.testing.assert_allclose(expected, actual)
+ # Compare against the input dtype as in test_reduce().
+ self.assertEqual(dtype, actual.dtype)
+
+ def test_manual_transfer(self):
+ @vectorize(signatures, target='cuda')
+ def vector_add(a, b):
+ return a + b
+
+ n = 10
+ x = np.arange(n, dtype=np.int32)
+ dx = cuda.to_device(x)
+ expected = x + x
+ actual = vector_add(x, dx).copy_to_host()
+ np.testing.assert_equal(expected, actual)
+ self.assertEqual(expected.dtype, actual.dtype)
+
+ def test_ufunc_output_2d(self):
+ @vectorize(signatures, target='cuda')
+ def vector_add(a, b):
+ return a + b
+
+ n = 10
+ x = np.arange(n, dtype=np.int32).reshape(2, 5)
+ dx = cuda.to_device(x)
+ vector_add(dx, dx, out=dx)
+
+ expected = x + x
+ actual = dx.copy_to_host()
+ np.testing.assert_equal(expected, actual)
+ self.assertEqual(expected.dtype, actual.dtype)
+
+ def check_tuple_arg(self, a, b):
+ @vectorize(signatures, target='cuda')
+ def vector_add(a, b):
+ return a + b
+
+ r = vector_add(a, b)
+ np.testing.assert_equal(np.asarray(a) + np.asarray(b), r)
+
+ def test_tuple_arg(self):
+ a = (1.0, 2.0, 3.0)
+ b = (4.0, 5.0, 6.0)
+ self.check_tuple_arg(a, b)
+
+ def test_namedtuple_arg(self):
+ Point = namedtuple('Point', ('x', 'y', 'z'))
+ a = Point(x=1.0, y=2.0, z=3.0)
+ b = Point(x=4.0, y=5.0, z=6.0)
+ self.check_tuple_arg(a, b)
+
+ def test_tuple_of_array_arg(self):
+ arr = np.arange(10, dtype=np.int32)
+ a = (arr, arr + 1)
+ b = (arr + 2, arr + 2)
+ self.check_tuple_arg(a, b)
+
+ def test_tuple_of_namedtuple_arg(self):
+ Point = namedtuple('Point', ('x', 'y', 'z'))
+ a = (Point(x=1.0, y=2.0, z=3.0), Point(x=1.5, y=2.5, z=3.5))
+ b = (Point(x=4.0, y=5.0, z=6.0), Point(x=4.5, y=5.5, z=6.5))
+ self.check_tuple_arg(a, b)
+
+ def test_namedtuple_of_array_arg(self):
+ xs1 = np.arange(10, dtype=np.int32)
+ ys1 = xs1 + 2
+ xs2 = np.arange(10, dtype=np.int32) * 2
+ ys2 = xs2 + 1
+ Points = namedtuple('Points', ('xs', 'ys'))
+ a = Points(xs=xs1, ys=ys1)
+ b = Points(xs=xs2, ys=ys2)
+ self.check_tuple_arg(a, b)
+
+ def test_name_attribute(self):
+ @vectorize('f8(f8)', target='cuda')
+ def bar(x):
+ return x ** 2
+
+ self.assertEqual(bar.__name__, 'bar')
+
+ def test_no_transfer_for_device_data(self):
+ # Initialize test data on the device prior to banning host <-> device
+ # transfer
+
+ noise = np.random.randn(1, 3, 64, 64).astype(np.float32)
+ noise = cuda.to_device(noise)
+
+ # A mock of a CUDA function that always raises a CudaAPIError
+
+ def raising_transfer(*args, **kwargs):
+ raise CudaAPIError(999, 'Transfer not allowed')
+
+ # Use the mock for transfers between the host and device
+
+ old_HtoD = getattr(driver, 'cuMemcpyHtoD', None)
+ old_DtoH = getattr(driver, 'cuMemcpyDtoH', None)
+
+ setattr(driver, 'cuMemcpyHtoD', raising_transfer)
+ setattr(driver, 'cuMemcpyDtoH', raising_transfer)
+
+ # Ensure that the mock functions are working as expected
+
+ with self.assertRaisesRegex(CudaAPIError, "Transfer not allowed"):
+ noise.copy_to_host()
+
+ with self.assertRaisesRegex(CudaAPIError, "Transfer not allowed"):
+ cuda.to_device([1])
+
+ try:
+ # Check that defining and calling a ufunc with data on the device
+ # induces no transfers
+
+ @vectorize(['float32(float32)'], target='cuda')
+ def func(noise):
+ return noise + 1.0
+
+ func(noise)
+ finally:
+ # Replace our mocks with the original implementations. If there was
+ # no original implementation, simply remove ours.
+
+ if old_HtoD is not None:
+ setattr(driver, 'cuMemcpyHtoD', old_HtoD)
+ else:
+ del driver.cuMemcpyHtoD
+ if old_DtoH is not None:
+ setattr(driver, 'cuMemcpyDtoH', old_DtoH)
+ else:
+ del driver.cuMemcpyDtoH
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_vectorize_complex.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_vectorize_complex.py
new file mode 100644
index 0000000000000000000000000000000000000000..82c7ca8f88c8cb88428ccf75776596fbbbc0fa3f
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_vectorize_complex.py
@@ -0,0 +1,20 @@
+import numpy as np
+from numba import vectorize
+from numba.cuda.testing import skip_on_cudasim, CUDATestCase
+import unittest
+
+
+@skip_on_cudasim('ufunc API unsupported in the simulator')
+class TestVectorizeComplex(CUDATestCase):
+ def test_vectorize_complex(self):
+ @vectorize(['complex128(complex128)'], target='cuda')
+ def vcomp(a):
+ return a * a + 1.
+
+ A = np.arange(5, dtype=np.complex128)
+ B = vcomp(A)
+ self.assertTrue(np.allclose(A * A + 1., B))
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_vectorize_decor.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_vectorize_decor.py
new file mode 100644
index 0000000000000000000000000000000000000000..12b8fa03cf88569ab148b525d4568407c8450d39
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_vectorize_decor.py
@@ -0,0 +1,69 @@
+import numpy as np
+
+from numba import vectorize, cuda
+from numba.tests.npyufunc.test_vectorize_decor import BaseVectorizeDecor, \
+ BaseVectorizeNopythonArg, BaseVectorizeUnrecognizedArg
+from numba.cuda.testing import skip_on_cudasim, CUDATestCase
+import unittest
+
+
+@skip_on_cudasim('ufunc API unsupported in the simulator')
+class TestVectorizeDecor(CUDATestCase, BaseVectorizeDecor):
+ """
+ Runs the tests from BaseVectorizeDecor with the CUDA target.
+ """
+ target = 'cuda'
+
+
+@skip_on_cudasim('ufunc API unsupported in the simulator')
+class TestGPUVectorizeBroadcast(CUDATestCase):
+ def test_broadcast(self):
+ a = np.random.randn(100, 3, 1)
+ b = a.transpose(2, 1, 0)
+
+ def fn(a, b):
+ return a - b
+
+ @vectorize(['float64(float64,float64)'], target='cuda')
+ def fngpu(a, b):
+ return a - b
+
+ expect = fn(a, b)
+ got = fngpu(a, b)
+ np.testing.assert_almost_equal(expect, got)
+
+ def test_device_broadcast(self):
+ """
+ Same test as .test_broadcast() but with device array as inputs
+ """
+
+ a = np.random.randn(100, 3, 1)
+ b = a.transpose(2, 1, 0)
+
+ def fn(a, b):
+ return a - b
+
+ @vectorize(['float64(float64,float64)'], target='cuda')
+ def fngpu(a, b):
+ return a - b
+
+ expect = fn(a, b)
+ got = fngpu(cuda.to_device(a), cuda.to_device(b))
+ np.testing.assert_almost_equal(expect, got.copy_to_host())
+
+
+@skip_on_cudasim('ufunc API unsupported in the simulator')
+class TestVectorizeNopythonArg(BaseVectorizeNopythonArg, CUDATestCase):
+ def test_target_cuda_nopython(self):
+ warnings = ["nopython kwarg for cuda target is redundant"]
+ self._test_target_nopython('cuda', warnings)
+
+
+@skip_on_cudasim('ufunc API unsupported in the simulator')
+class TestVectorizeUnrecognizedArg(BaseVectorizeUnrecognizedArg, CUDATestCase):
+ def test_target_cuda_unrecognized_arg(self):
+ self._test_target_unrecognized_arg('cuda')
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_vectorize_device.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_vectorize_device.py
new file mode 100644
index 0000000000000000000000000000000000000000..e33598d8b7bccc3ced0ef7f9eb27fe93a6a84dce
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_vectorize_device.py
@@ -0,0 +1,36 @@
+from numba import vectorize
+from numba import cuda, float32
+import numpy as np
+from numba.cuda.testing import skip_on_cudasim, CUDATestCase
+import unittest
+
+
+@skip_on_cudasim('ufunc API unsupported in the simulator')
+class TestCudaVectorizeDeviceCall(CUDATestCase):
+ def test_cuda_vectorize_device_call(self):
+
+ @cuda.jit(float32(float32, float32, float32), device=True)
+ def cu_device_fn(x, y, z):
+ return x ** y / z
+
+ def cu_ufunc(x, y, z):
+ return cu_device_fn(x, y, z)
+
+ ufunc = vectorize([float32(float32, float32, float32)], target='cuda')(
+ cu_ufunc)
+
+ N = 100
+
+ X = np.array(np.random.sample(N), dtype=np.float32)
+ Y = np.array(np.random.sample(N), dtype=np.float32)
+ Z = np.array(np.random.sample(N), dtype=np.float32) + 0.1
+
+ out = ufunc(X, Y, Z)
+
+ gold = (X ** Y) / Z
+
+ self.assertTrue(np.allclose(out, gold))
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_vectorize_scalar_arg.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_vectorize_scalar_arg.py
new file mode 100644
index 0000000000000000000000000000000000000000..1c65a41d726105a2a9088ec2aeb92b728d12fa56
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_vectorize_scalar_arg.py
@@ -0,0 +1,37 @@
+import numpy as np
+from numba import vectorize
+from numba import cuda, float64
+from numba.cuda.testing import skip_on_cudasim, CUDATestCase
+import unittest
+
+sig = [float64(float64, float64)]
+
+
+@skip_on_cudasim('ufunc API unsupported in the simulator')
+class TestCUDAVectorizeScalarArg(CUDATestCase):
+
+ def test_vectorize_scalar_arg(self):
+ @vectorize(sig, target='cuda')
+ def vector_add(a, b):
+ return a + b
+
+ A = np.arange(10, dtype=np.float64)
+ dA = cuda.to_device(A)
+ v = vector_add(1.0, dA)
+
+ np.testing.assert_array_almost_equal(
+ v.copy_to_host(),
+ np.arange(1, 11, dtype=np.float64))
+
+ def test_vectorize_all_scalars(self):
+ @vectorize(sig, target='cuda')
+ def vector_add(a, b):
+ return a + b
+
+ v = vector_add(1.0, 1.0)
+
+ np.testing.assert_almost_equal(2.0, v)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_warning.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_warning.py
new file mode 100644
index 0000000000000000000000000000000000000000..e1b32dbb0a709174c89726d304c0629d2ef1651f
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_warning.py
@@ -0,0 +1,139 @@
+import numpy as np
+from numba import cuda
+from numba.cuda.testing import unittest, CUDATestCase, skip_on_cudasim
+from numba.tests.support import linux_only, override_config
+from numba.core.errors import NumbaPerformanceWarning
+import warnings
+
+
+@skip_on_cudasim('cudasim does not raise performance warnings')
+class TestWarnings(CUDATestCase):
+ def test_inefficient_launch_configuration(self):
+ @cuda.jit
+ def kernel():
+ pass
+
+ with override_config('CUDA_LOW_OCCUPANCY_WARNINGS', 1):
+ with warnings.catch_warnings(record=True) as w:
+ kernel[1, 1]()
+
+ self.assertEqual(w[0].category, NumbaPerformanceWarning)
+ self.assertIn('Grid size', str(w[0].message))
+ self.assertIn('low occupancy', str(w[0].message))
+
+ def test_efficient_launch_configuration(self):
+ @cuda.jit
+ def kernel():
+ pass
+
+ with override_config('CUDA_LOW_OCCUPANCY_WARNINGS', 1):
+ with warnings.catch_warnings(record=True) as w:
+ kernel[256, 256]()
+
+ self.assertEqual(len(w), 0)
+
+ def test_warn_on_host_array(self):
+ @cuda.jit
+ def foo(r, x):
+ r[0] = x + 1
+
+ N = 10
+ arr_f32 = np.zeros(N, dtype=np.float32)
+ with override_config('CUDA_WARN_ON_IMPLICIT_COPY', 1):
+ with warnings.catch_warnings(record=True) as w:
+ foo[1, N](arr_f32, N)
+
+ self.assertEqual(w[0].category, NumbaPerformanceWarning)
+ self.assertIn('Host array used in CUDA kernel will incur',
+ str(w[0].message))
+ self.assertIn('copy overhead', str(w[0].message))
+
+ def test_pinned_warn_on_host_array(self):
+ @cuda.jit
+ def foo(r, x):
+ r[0] = x + 1
+
+ N = 10
+ ary = cuda.pinned_array(N, dtype=np.float32)
+
+ with override_config('CUDA_WARN_ON_IMPLICIT_COPY', 1):
+ with warnings.catch_warnings(record=True) as w:
+ foo[1, N](ary, N)
+
+ self.assertEqual(w[0].category, NumbaPerformanceWarning)
+ self.assertIn('Host array used in CUDA kernel will incur',
+ str(w[0].message))
+ self.assertIn('copy overhead', str(w[0].message))
+
+ def test_nowarn_on_mapped_array(self):
+ @cuda.jit
+ def foo(r, x):
+ r[0] = x + 1
+
+ N = 10
+ ary = cuda.mapped_array(N, dtype=np.float32)
+
+ with override_config('CUDA_WARN_ON_IMPLICIT_COPY', 1):
+ with warnings.catch_warnings(record=True) as w:
+ foo[1, N](ary, N)
+
+ self.assertEqual(len(w), 0)
+
+ @linux_only
+ def test_nowarn_on_managed_array(self):
+ @cuda.jit
+ def foo(r, x):
+ r[0] = x + 1
+
+ N = 10
+ ary = cuda.managed_array(N, dtype=np.float32)
+
+ with override_config('CUDA_WARN_ON_IMPLICIT_COPY', 1):
+ with warnings.catch_warnings(record=True) as w:
+ foo[1, N](ary, N)
+
+ self.assertEqual(len(w), 0)
+
+ def test_nowarn_on_device_array(self):
+ @cuda.jit
+ def foo(r, x):
+ r[0] = x + 1
+
+ N = 10
+ ary = cuda.device_array(N, dtype=np.float32)
+
+ with override_config('CUDA_WARN_ON_IMPLICIT_COPY', 1):
+ with warnings.catch_warnings(record=True) as w:
+ foo[1, N](ary, N)
+
+ self.assertEqual(len(w), 0)
+
+ def test_warn_on_debug_and_opt(self):
+ with warnings.catch_warnings(record=True) as w:
+ cuda.jit(debug=True, opt=True)
+
+ self.assertEqual(len(w), 1)
+ self.assertIn('not supported by CUDA', str(w[0].message))
+
+ def test_warn_on_debug_and_opt_default(self):
+ with warnings.catch_warnings(record=True) as w:
+ cuda.jit(debug=True)
+
+ self.assertEqual(len(w), 1)
+ self.assertIn('not supported by CUDA', str(w[0].message))
+
+ def test_no_warn_on_debug_and_no_opt(self):
+ with warnings.catch_warnings(record=True) as w:
+ cuda.jit(debug=True, opt=False)
+
+ self.assertEqual(len(w), 0)
+
+ def test_no_warn_with_no_debug_and_opt_kwargs(self):
+ with warnings.catch_warnings(record=True) as w:
+ cuda.jit()
+
+ self.assertEqual(len(w), 0)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_warp_ops.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_warp_ops.py
new file mode 100644
index 0000000000000000000000000000000000000000..2fc157d07a3e07f3b5831a9031adf5a31315337e
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudapy/test_warp_ops.py
@@ -0,0 +1,276 @@
+import numpy as np
+from numba import cuda, int32, int64, float32, float64
+from numba.cuda.testing import unittest, CUDATestCase, skip_on_cudasim
+from numba.core import config
+
+
+def useful_syncwarp(ary):
+ i = cuda.grid(1)
+ if i == 0:
+ ary[0] = 42
+ cuda.syncwarp(0xffffffff)
+ ary[i] = ary[0]
+
+
+def use_shfl_sync_idx(ary, idx):
+ i = cuda.grid(1)
+ val = cuda.shfl_sync(0xffffffff, i, idx)
+ ary[i] = val
+
+
+def use_shfl_sync_up(ary, delta):
+ i = cuda.grid(1)
+ val = cuda.shfl_up_sync(0xffffffff, i, delta)
+ ary[i] = val
+
+
+def use_shfl_sync_down(ary, delta):
+ i = cuda.grid(1)
+ val = cuda.shfl_down_sync(0xffffffff, i, delta)
+ ary[i] = val
+
+
+def use_shfl_sync_xor(ary, xor):
+ i = cuda.grid(1)
+ val = cuda.shfl_xor_sync(0xffffffff, i, xor)
+ ary[i] = val
+
+
+def use_shfl_sync_with_val(ary, into):
+ i = cuda.grid(1)
+ val = cuda.shfl_sync(0xffffffff, into, 0)
+ ary[i] = val
+
+
+def use_vote_sync_all(ary_in, ary_out):
+ i = cuda.grid(1)
+ pred = cuda.all_sync(0xffffffff, ary_in[i])
+ ary_out[i] = pred
+
+
+def use_vote_sync_any(ary_in, ary_out):
+ i = cuda.grid(1)
+ pred = cuda.any_sync(0xffffffff, ary_in[i])
+ ary_out[i] = pred
+
+
+def use_vote_sync_eq(ary_in, ary_out):
+ i = cuda.grid(1)
+ pred = cuda.eq_sync(0xffffffff, ary_in[i])
+ ary_out[i] = pred
+
+
+def use_vote_sync_ballot(ary):
+ i = cuda.threadIdx.x
+ ballot = cuda.ballot_sync(0xffffffff, True)
+ ary[i] = ballot
+
+
+def use_match_any_sync(ary_in, ary_out):
+ i = cuda.grid(1)
+ ballot = cuda.match_any_sync(0xffffffff, ary_in[i])
+ ary_out[i] = ballot
+
+
+def use_match_all_sync(ary_in, ary_out):
+ i = cuda.grid(1)
+ ballot, pred = cuda.match_all_sync(0xffffffff, ary_in[i])
+ ary_out[i] = ballot if pred else 0
+
+
+def use_independent_scheduling(arr):
+ i = cuda.threadIdx.x
+ if i % 4 == 0:
+ ballot = cuda.ballot_sync(0x11111111, True)
+ elif i % 4 == 1:
+ ballot = cuda.ballot_sync(0x22222222, True)
+ elif i % 4 == 2:
+ ballot = cuda.ballot_sync(0x44444444, True)
+ elif i % 4 == 3:
+ ballot = cuda.ballot_sync(0x88888888, True)
+ arr[i] = ballot
+
+
+def _safe_cc_check(cc):
+ if config.ENABLE_CUDASIM:
+ return True
+ else:
+ return cuda.get_current_device().compute_capability >= cc
+
+
+@skip_on_cudasim("Warp Operations are not yet implemented on cudasim")
+class TestCudaWarpOperations(CUDATestCase):
+ def test_useful_syncwarp(self):
+ compiled = cuda.jit("void(int32[:])")(useful_syncwarp)
+ nelem = 32
+ ary = np.empty(nelem, dtype=np.int32)
+ compiled[1, nelem](ary)
+ self.assertTrue(np.all(ary == 42))
+
+ def test_shfl_sync_idx(self):
+ compiled = cuda.jit("void(int32[:], int32)")(use_shfl_sync_idx)
+ nelem = 32
+ idx = 4
+ ary = np.empty(nelem, dtype=np.int32)
+ compiled[1, nelem](ary, idx)
+ self.assertTrue(np.all(ary == idx))
+
+ def test_shfl_sync_up(self):
+ compiled = cuda.jit("void(int32[:], int32)")(use_shfl_sync_up)
+ nelem = 32
+ delta = 4
+ ary = np.empty(nelem, dtype=np.int32)
+ exp = np.arange(nelem, dtype=np.int32)
+ exp[delta:] -= delta
+ compiled[1, nelem](ary, delta)
+ self.assertTrue(np.all(ary == exp))
+
+ def test_shfl_sync_down(self):
+ compiled = cuda.jit("void(int32[:], int32)")(use_shfl_sync_down)
+ nelem = 32
+ delta = 4
+ ary = np.empty(nelem, dtype=np.int32)
+ exp = np.arange(nelem, dtype=np.int32)
+ exp[:-delta] += delta
+ compiled[1, nelem](ary, delta)
+ self.assertTrue(np.all(ary == exp))
+
+ def test_shfl_sync_xor(self):
+ compiled = cuda.jit("void(int32[:], int32)")(use_shfl_sync_xor)
+ nelem = 32
+ xor = 16
+ ary = np.empty(nelem, dtype=np.int32)
+ exp = np.arange(nelem, dtype=np.int32) ^ xor
+ compiled[1, nelem](ary, xor)
+ self.assertTrue(np.all(ary == exp))
+
+ def test_shfl_sync_types(self):
+ types = int32, int64, float32, float64
+ values = (np.int32(-1), np.int64(1 << 42),
+ np.float32(np.pi), np.float64(np.pi))
+ for typ, val in zip(types, values):
+ compiled = cuda.jit((typ[:], typ))(use_shfl_sync_with_val)
+ nelem = 32
+ ary = np.empty(nelem, dtype=val.dtype)
+ compiled[1, nelem](ary, val)
+ self.assertTrue(np.all(ary == val))
+
+ def test_vote_sync_all(self):
+ compiled = cuda.jit("void(int32[:], int32[:])")(use_vote_sync_all)
+ nelem = 32
+ ary_in = np.ones(nelem, dtype=np.int32)
+ ary_out = np.empty(nelem, dtype=np.int32)
+ compiled[1, nelem](ary_in, ary_out)
+ self.assertTrue(np.all(ary_out == 1))
+ ary_in[-1] = 0
+ compiled[1, nelem](ary_in, ary_out)
+ self.assertTrue(np.all(ary_out == 0))
+
+ def test_vote_sync_any(self):
+ compiled = cuda.jit("void(int32[:], int32[:])")(use_vote_sync_any)
+ nelem = 32
+ ary_in = np.zeros(nelem, dtype=np.int32)
+ ary_out = np.empty(nelem, dtype=np.int32)
+ compiled[1, nelem](ary_in, ary_out)
+ self.assertTrue(np.all(ary_out == 0))
+ ary_in[2] = 1
+ ary_in[5] = 1
+ compiled[1, nelem](ary_in, ary_out)
+ self.assertTrue(np.all(ary_out == 1))
+
+ def test_vote_sync_eq(self):
+ compiled = cuda.jit("void(int32[:], int32[:])")(use_vote_sync_eq)
+ nelem = 32
+ ary_in = np.zeros(nelem, dtype=np.int32)
+ ary_out = np.empty(nelem, dtype=np.int32)
+ compiled[1, nelem](ary_in, ary_out)
+ self.assertTrue(np.all(ary_out == 1))
+ ary_in[1] = 1
+ compiled[1, nelem](ary_in, ary_out)
+ self.assertTrue(np.all(ary_out == 0))
+ ary_in[:] = 1
+ compiled[1, nelem](ary_in, ary_out)
+ self.assertTrue(np.all(ary_out == 1))
+
+ def test_vote_sync_ballot(self):
+ compiled = cuda.jit("void(uint32[:])")(use_vote_sync_ballot)
+ nelem = 32
+ ary = np.empty(nelem, dtype=np.uint32)
+ compiled[1, nelem](ary)
+ self.assertTrue(np.all(ary == np.uint32(0xffffffff)))
+
+ @unittest.skipUnless(_safe_cc_check((7, 0)),
+ "Matching requires at least Volta Architecture")
+ def test_match_any_sync(self):
+ compiled = cuda.jit("void(int32[:], int32[:])")(use_match_any_sync)
+ nelem = 10
+ ary_in = np.arange(nelem, dtype=np.int32) % 2
+ ary_out = np.empty(nelem, dtype=np.int32)
+ exp = np.tile((0b0101010101, 0b1010101010), 5)
+ compiled[1, nelem](ary_in, ary_out)
+ self.assertTrue(np.all(ary_out == exp))
+
+ @unittest.skipUnless(_safe_cc_check((7, 0)),
+ "Matching requires at least Volta Architecture")
+ def test_match_all_sync(self):
+ compiled = cuda.jit("void(int32[:], int32[:])")(use_match_all_sync)
+ nelem = 10
+ ary_in = np.zeros(nelem, dtype=np.int32)
+ ary_out = np.empty(nelem, dtype=np.int32)
+ compiled[1, nelem](ary_in, ary_out)
+ self.assertTrue(np.all(ary_out == 0b1111111111))
+ ary_in[1] = 4
+ compiled[1, nelem](ary_in, ary_out)
+ self.assertTrue(np.all(ary_out == 0))
+
+ @unittest.skipUnless(_safe_cc_check((7, 0)),
+ "Independent scheduling requires at least Volta "
+ "Architecture")
+ def test_independent_scheduling(self):
+ compiled = cuda.jit("void(uint32[:])")(use_independent_scheduling)
+ arr = np.empty(32, dtype=np.uint32)
+ exp = np.tile((0x11111111, 0x22222222, 0x44444444, 0x88888888), 8)
+ compiled[1, 32](arr)
+ self.assertTrue(np.all(arr == exp))
+
+ def test_activemask(self):
+ @cuda.jit
+ def use_activemask(x):
+ i = cuda.grid(1)
+ if (i % 2) == 0:
+ # Even numbered threads fill in even numbered array entries
+ # with binary "...01010101"
+ x[i] = cuda.activemask()
+ else:
+ # Odd numbered threads fill in odd numbered array entries
+ # with binary "...10101010"
+ x[i] = cuda.activemask()
+
+ out = np.zeros(32, dtype=np.uint32)
+ use_activemask[1, 32](out)
+
+ # 0x5 = 0101: The pattern from even-numbered threads
+ # 0xA = 1010: The pattern from odd-numbered threads
+ expected = np.tile((0x55555555, 0xAAAAAAAA), 16)
+ np.testing.assert_equal(expected, out)
+
+ def test_lanemask_lt(self):
+ @cuda.jit
+ def use_lanemask_lt(x):
+ i = cuda.grid(1)
+ x[i] = cuda.lanemask_lt()
+
+ out = np.zeros(32, dtype=np.uint32)
+ use_lanemask_lt[1, 32](out)
+
+ # A string of 1s that grows from the LSB for each entry:
+ # 0, 1, 3, 7, F, 1F, 3F, 7F, FF, 1FF, etc.
+ # or in binary:
+ # ...0001, ....0011, ...0111, etc.
+ expected = np.asarray([(2 ** i) - 1 for i in range(32)],
+ dtype=np.uint32)
+ np.testing.assert_equal(expected, out)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudasim/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudasim/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..0465337eb70062fc004a0973c45d0be07803812a
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudasim/__init__.py
@@ -0,0 +1,6 @@
+from numba.testing import load_testsuite
+import os
+
+
+def load_tests(loader, tests, pattern):
+ return load_testsuite(loader, os.path.dirname(__file__))
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudasim/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudasim/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..97c51d7b8293e5d062e301004b879358347ed103
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudasim/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudasim/__pycache__/support.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudasim/__pycache__/support.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c677f72daf3dcc9e3734d13f1f002a31ccb741c7
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudasim/__pycache__/support.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudasim/__pycache__/test_cudasim_issues.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudasim/__pycache__/test_cudasim_issues.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2bffbbef048433631384a0902beefb010ec359cd
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudasim/__pycache__/test_cudasim_issues.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudasim/support.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudasim/support.py
new file mode 100644
index 0000000000000000000000000000000000000000..4fca39cadd70bb9201ebef9716f52ca8aa22e7fd
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudasim/support.py
@@ -0,0 +1,6 @@
+from numba import cuda
+
+
+@cuda.jit(device=True)
+def cuda_module_in_device_function():
+ return cuda.threadIdx.x
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudasim/test_cudasim_issues.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudasim/test_cudasim_issues.py
new file mode 100644
index 0000000000000000000000000000000000000000..0f544821ab8066351a04a82b1c5c84bba5389c59
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/cudasim/test_cudasim_issues.py
@@ -0,0 +1,102 @@
+import threading
+
+import numpy as np
+
+from numba import cuda
+from numba.cuda.testing import CUDATestCase, skip_unless_cudasim
+import numba.cuda.simulator as simulator
+import unittest
+
+
+class TestCudaSimIssues(CUDATestCase):
+ def test_record_access(self):
+ backyard_type = [('statue', np.float64),
+ ('newspaper', np.float64, (6,))]
+
+ goose_type = [('garden', np.float64, (12,)),
+ ('town', np.float64, (42,)),
+ ('backyard', backyard_type)]
+
+ goose_np_type = np.dtype(goose_type, align=True)
+
+ @cuda.jit
+ def simple_kernel(f):
+ f.garden[0] = 45.0
+ f.backyard.newspaper[3] = 2.0
+ f.backyard.newspaper[3] = f.backyard.newspaper[3] + 3.0
+
+ item = np.recarray(1, dtype=goose_np_type)
+ simple_kernel[1, 1](item[0])
+ np.testing.assert_equal(item[0]['garden'][0], 45)
+ np.testing.assert_equal(item[0]['backyard']['newspaper'][3], 5)
+
+ def test_recarray_setting(self):
+ recordwith2darray = np.dtype([('i', np.int32),
+ ('j', np.float32, (3, 2))])
+ rec = np.recarray(2, dtype=recordwith2darray)
+ rec[0]['i'] = 45
+
+ @cuda.jit
+ def simple_kernel(f):
+ f[1] = f[0]
+ simple_kernel[1, 1](rec)
+ np.testing.assert_equal(rec[0]['i'], rec[1]['i'])
+
+ def test_cuda_module_in_device_function(self):
+ """
+ Discovered in https://github.com/numba/numba/issues/1837.
+ When the `cuda` module is referenced in a device function,
+ it does not have the kernel API (e.g. cuda.threadIdx, cuda.shared)
+ """
+ from numba.cuda.tests.cudasim import support
+
+ inner = support.cuda_module_in_device_function
+
+ @cuda.jit
+ def outer(out):
+ tid = inner()
+ if tid < out.size:
+ out[tid] = tid
+
+ arr = np.zeros(10, dtype=np.int32)
+ outer[1, 11](arr)
+ expected = np.arange(arr.size, dtype=np.int32)
+ np.testing.assert_equal(expected, arr)
+
+ @skip_unless_cudasim('Only works on CUDASIM')
+ def test_deadlock_on_exception(self):
+ def assert_no_blockthreads():
+ blockthreads = []
+ for t in threading.enumerate():
+ if not isinstance(t, simulator.kernel.BlockThread):
+ continue
+
+ # join blockthreads with a short timeout to allow aborted
+ # threads to exit
+ t.join(1)
+ if t.is_alive():
+ self.fail("Blocked kernel thread: %s" % t)
+
+ self.assertListEqual(blockthreads, [])
+
+ @simulator.jit
+ def assign_with_sync(x, y):
+ i = cuda.grid(1)
+ y[i] = x[i]
+
+ cuda.syncthreads()
+ cuda.syncthreads()
+
+ x = np.arange(3)
+ y = np.empty(3)
+ assign_with_sync[1, 3](x, y)
+ np.testing.assert_array_equal(x, y)
+ assert_no_blockthreads()
+
+ with self.assertRaises(IndexError):
+ assign_with_sync[1, 6](x, y)
+ assert_no_blockthreads()
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/data/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/data/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/data/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/data/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..337ab877937d359c9822bc0c1d1aef3ef5fe9225
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/data/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/data/cuda_include.cu b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/data/cuda_include.cu
new file mode 100644
index 0000000000000000000000000000000000000000..69a0efd9a1f53037770384faa1ad049dcac5ab09
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/data/cuda_include.cu
@@ -0,0 +1,5 @@
+// Not all CUDA includes are safe to include in device code compiled by NVRTC,
+// because it does not have paths to all system include directories. Headers
+// such as cuda_device_runtime_api.h are safe to use in NVRTC without adding
+// additional includes.
+#include
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/data/error.cu b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/data/error.cu
new file mode 100644
index 0000000000000000000000000000000000000000..402f3138dce7a5c70c3677912d0e1c033150e3c8
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/data/error.cu
@@ -0,0 +1,7 @@
+extern "C" __device__
+int bar(int* out, int a) {
+ // Explicitly placed to generate an error
+ SYNTAX ERROR
+ *out = a * 2;
+ return 0;
+}
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/data/jitlink.cu b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/data/jitlink.cu
new file mode 100644
index 0000000000000000000000000000000000000000..4d245366c64a9b7a0308d422d3c8fdcb779b1269
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/data/jitlink.cu
@@ -0,0 +1,23 @@
+// Compile with:
+//
+// nvcc -gencode arch=compute_50,code=compute_50 -rdc true -ptx jitlink.cu
+//
+// using the oldest supported toolkit version (10.2 at the time of writing).
+
+extern "C" __device__
+int bar(int *out, int a)
+{
+ *out = a * 2;
+ return 0;
+}
+
+
+// The out argument is necessary due to Numba's CUDA calling convention, which
+// always reserves the first parameter for a pointer to a returned value, even
+// if there is no return value.
+extern "C" __device__
+int array_mutator(void *out, int *a)
+{
+ a[0] = a[1];
+ return 0;
+}
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/data/jitlink.ptx b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/data/jitlink.ptx
new file mode 100644
index 0000000000000000000000000000000000000000..dde0cc214aac1c6561534a483b60b7baa78629d2
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/data/jitlink.ptx
@@ -0,0 +1,51 @@
+//
+// Generated by NVIDIA NVVM Compiler
+//
+// Compiler Build ID: CL-27506705
+// Cuda compilation tools, release 10.2, V10.2.89
+// Based on LLVM 3.4svn
+//
+
+.version 6.5
+.target sm_50
+.address_size 64
+
+ // .globl bar
+
+.visible .func (.param .b32 func_retval0) bar(
+ .param .b64 bar_param_0,
+ .param .b32 bar_param_1
+)
+{
+ .reg .b32 %r<4>;
+ .reg .b64 %rd<2>;
+
+
+ ld.param.u64 %rd1, [bar_param_0];
+ ld.param.u32 %r1, [bar_param_1];
+ shl.b32 %r2, %r1, 1;
+ st.u32 [%rd1], %r2;
+ mov.u32 %r3, 0;
+ st.param.b32 [func_retval0+0], %r3;
+ ret;
+}
+
+ // .globl array_mutator
+.visible .func (.param .b32 func_retval0) array_mutator(
+ .param .b64 array_mutator_param_0,
+ .param .b64 array_mutator_param_1
+)
+{
+ .reg .b32 %r<3>;
+ .reg .b64 %rd<2>;
+
+
+ ld.param.u64 %rd1, [array_mutator_param_1];
+ ld.u32 %r1, [%rd1+4];
+ st.u32 [%rd1], %r1;
+ mov.u32 %r2, 0;
+ st.param.b32 [func_retval0+0], %r2;
+ ret;
+}
+
+
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/data/warn.cu b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/data/warn.cu
new file mode 100644
index 0000000000000000000000000000000000000000..4f31e951d97513c12234ef7fc2f38f29e5077e42
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/data/warn.cu
@@ -0,0 +1,7 @@
+extern "C" __device__
+int bar(int* out, int a) {
+ // Explicitly placed to generate a warning for testing the NVRTC program log
+ int unused;
+ *out = a * 2;
+ return 0;
+}
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/doc_examples/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/doc_examples/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..0465337eb70062fc004a0973c45d0be07803812a
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/doc_examples/__init__.py
@@ -0,0 +1,6 @@
+from numba.testing import load_testsuite
+import os
+
+
+def load_tests(loader, tests, pattern):
+ return load_testsuite(loader, os.path.dirname(__file__))
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/doc_examples/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/doc_examples/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c637e8937eab7f806a6b6cfe21fb9290efa7f112
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/doc_examples/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/doc_examples/__pycache__/test_cg.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/doc_examples/__pycache__/test_cg.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ea5dc5ad830d74758adaf98b5ca6ad8d9edb7cb6
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/doc_examples/__pycache__/test_cg.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/doc_examples/__pycache__/test_cpu_gpu_compat.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/doc_examples/__pycache__/test_cpu_gpu_compat.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..028d2c6678498c5994ef579142ed12a5d17076d0
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/doc_examples/__pycache__/test_cpu_gpu_compat.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/doc_examples/__pycache__/test_ffi.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/doc_examples/__pycache__/test_ffi.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b24ed2cf896c7b1e23c0a70b25d7106eaa546c1d
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/doc_examples/__pycache__/test_ffi.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/doc_examples/__pycache__/test_laplace.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/doc_examples/__pycache__/test_laplace.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..94bbe3b50cac607f1310fa16cd1f0175d196906d
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/doc_examples/__pycache__/test_laplace.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/doc_examples/__pycache__/test_matmul.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/doc_examples/__pycache__/test_matmul.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c60a57eaa40095529ebc90827d8c7f40b4580b09
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/doc_examples/__pycache__/test_matmul.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/doc_examples/__pycache__/test_montecarlo.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/doc_examples/__pycache__/test_montecarlo.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5d2a79e66a81ab76f4eab445f5368404fb0c477b
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/doc_examples/__pycache__/test_montecarlo.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/doc_examples/__pycache__/test_random.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/doc_examples/__pycache__/test_random.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..52a9706da93230e7d2d41686dc6871b56f655b67
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/doc_examples/__pycache__/test_random.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/doc_examples/__pycache__/test_reduction.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/doc_examples/__pycache__/test_reduction.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6931d96851ea93a528b1ad6566f06e3311e90cd7
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/doc_examples/__pycache__/test_reduction.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/doc_examples/__pycache__/test_sessionize.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/doc_examples/__pycache__/test_sessionize.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b5ea43212f0ffb0d5f11e459bb50a0cee01e3d92
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/doc_examples/__pycache__/test_sessionize.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/doc_examples/__pycache__/test_ufunc.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/doc_examples/__pycache__/test_ufunc.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..374c02bb94b232918c1271a8a2dc962d5a061514
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/doc_examples/__pycache__/test_ufunc.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/doc_examples/__pycache__/test_vecadd.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/doc_examples/__pycache__/test_vecadd.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..855e737a72c080e21b385fbd42ca607cbf0fd689
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/doc_examples/__pycache__/test_vecadd.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/doc_examples/ffi/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/doc_examples/ffi/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/doc_examples/ffi/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/doc_examples/ffi/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4e6e42bd96d9438434bd7d115b2baa6deaa10198
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/doc_examples/ffi/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/doc_examples/ffi/functions.cu b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/doc_examples/ffi/functions.cu
new file mode 100644
index 0000000000000000000000000000000000000000..3c568189e469c529f27d03dc4d206f46b4d1ca46
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/doc_examples/ffi/functions.cu
@@ -0,0 +1,49 @@
+// magictoken.ex_mul_f32_f32.begin
+// Foreign function example: multiplication of a pair of floats
+
+extern "C" __device__ int
+mul_f32_f32(
+ float* return_value,
+ float x,
+ float y)
+{
+ // Compute result and store in caller-provided slot
+ *return_value = x * y;
+
+ // Signal that no Python exception occurred
+ return 0;
+}
+// magictoken.ex_mul_f32_f32.end
+
+
+// magictoken.ex_sum_reduce_proto.begin
+extern "C"
+__device__ int
+sum_reduce(
+ float* return_value,
+ float* array,
+ int n
+);
+// magictoken.ex_sum_reduce_proto.end
+
+
+// Performs a simple reduction on an array passed by pointer using the
+// ffi.from_buffer() method. Implements the prototype above.
+extern "C"
+__device__ int
+sum_reduce(
+ float* return_value,
+ float* array,
+ int n
+)
+{
+ double sum = 0.0;
+
+ for (size_t i = 0; i < n; ++i) {
+ sum += array[i];
+ }
+
+ *return_value = (float)sum;
+
+ return 0;
+}
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/doc_examples/test_cg.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/doc_examples/test_cg.py
new file mode 100644
index 0000000000000000000000000000000000000000..fc8405dbb709c6617a06e03bc7dd8dc3d5fd43b5
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/doc_examples/test_cg.py
@@ -0,0 +1,77 @@
+# Contents in this file are referenced from the sphinx-generated docs.
+# "magictoken" is used for markers as beginning and ending of example text.
+
+import unittest
+from numba.cuda.testing import (CUDATestCase, skip_on_cudasim,
+ skip_if_cudadevrt_missing, skip_unless_cc_60,
+ skip_if_mvc_enabled)
+
+
+@skip_if_cudadevrt_missing
+@skip_unless_cc_60
+@skip_if_mvc_enabled('CG not supported with MVC')
+@skip_on_cudasim("cudasim doesn't support cuda import at non-top-level")
+class TestCooperativeGroups(CUDATestCase):
+ def test_ex_grid_sync(self):
+ # magictoken.ex_grid_sync_kernel.begin
+ from numba import cuda, int32
+ import numpy as np
+
+ sig = (int32[:,::1],)
+
+ @cuda.jit(sig)
+ def sequential_rows(M):
+ col = cuda.grid(1)
+ g = cuda.cg.this_grid()
+
+ rows = M.shape[0]
+ cols = M.shape[1]
+
+ for row in range(1, rows):
+ opposite = cols - col - 1
+ # Each row's elements are one greater than the previous row
+ M[row, col] = M[row - 1, opposite] + 1
+ # Wait until all threads have written their column element,
+ # and that the write is visible to all other threads
+ g.sync()
+ # magictoken.ex_grid_sync_kernel.end
+
+ # magictoken.ex_grid_sync_data.begin
+ # Empty input data
+ A = np.zeros((1024, 1024), dtype=np.int32)
+ # A somewhat arbitrary choice (one warp), but generally smaller block sizes
+ # allow more blocks to be launched (noting that other limitations on
+ # occupancy apply such as shared memory size)
+ blockdim = 32
+ griddim = A.shape[1] // blockdim
+ # magictoken.ex_grid_sync_data.end
+
+ # Skip this test if the grid size used in the example is too large for
+ # a cooperative launch on the current GPU
+ mb = sequential_rows.overloads[sig].max_cooperative_grid_blocks(blockdim)
+ if mb < griddim:
+ self.skipTest('Device does not support a large enough coop grid')
+
+ # magictoken.ex_grid_sync_launch.begin
+ # Kernel launch - this is implicitly a cooperative launch
+ sequential_rows[griddim, blockdim](A)
+
+ # What do the results look like?
+ # print(A)
+ #
+ # [[ 0 0 0 ... 0 0 0]
+ # [ 1 1 1 ... 1 1 1]
+ # [ 2 2 2 ... 2 2 2]
+ # ...
+ # [1021 1021 1021 ... 1021 1021 1021]
+ # [1022 1022 1022 ... 1022 1022 1022]
+ # [1023 1023 1023 ... 1023 1023 1023]]
+ # magictoken.ex_grid_sync_launch.end
+
+ # Sanity check - are the results what we expect?
+ reference = np.tile(np.arange(1024), (1024, 1)).T
+ np.testing.assert_equal(A, reference)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/doc_examples/test_cpu_gpu_compat.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/doc_examples/test_cpu_gpu_compat.py
new file mode 100644
index 0000000000000000000000000000000000000000..b879a12d27729868c8646435cedaae18311c855e
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/doc_examples/test_cpu_gpu_compat.py
@@ -0,0 +1,76 @@
+import unittest
+
+from numba.cuda.testing import CUDATestCase, skip_on_cudasim
+from numba.tests.support import captured_stdout
+import numpy as np
+
+
+@skip_on_cudasim("cudasim doesn't support cuda import at non-top-level")
+class TestCpuGpuCompat(CUDATestCase):
+ """
+ Test compatibility of CPU and GPU functions
+ """
+
+ def setUp(self):
+ # Prevent output from this test showing up when running the test suite
+ self._captured_stdout = captured_stdout()
+ self._captured_stdout.__enter__()
+ super().setUp()
+
+ def tearDown(self):
+ # No exception type, value, or traceback
+ self._captured_stdout.__exit__(None, None, None)
+ super().tearDown()
+
+ def test_ex_cpu_gpu_compat(self):
+ # ex_cpu_gpu_compat.import.begin
+ from math import pi
+
+ import numba
+ from numba import cuda
+ # ex_cpu_gpu_compat.import.end
+
+ # ex_cpu_gpu_compat.allocate.begin
+ X = cuda.to_device([1, 10, 234])
+ Y = cuda.to_device([2, 2, 4014])
+ Z = cuda.to_device([3, 14, 2211])
+ results = cuda.to_device([0.0, 0.0, 0.0])
+ # ex_cpu_gpu_compat.allocate.end
+
+ # ex_cpu_gpu_compat.define.begin
+ @numba.jit
+ def business_logic(x, y, z):
+ return 4 * z * (2 * x - (4 * y) / 2 * pi)
+ # ex_cpu_gpu_compat.define.end
+
+ # ex_cpu_gpu_compat.cpurun.begin
+ print(business_logic(1, 2, 3)) # -126.79644737231007
+ # ex_cpu_gpu_compat.cpurun.end
+
+ # ex_cpu_gpu_compat.usegpu.begin
+ @cuda.jit
+ def f(res, xarr, yarr, zarr):
+ tid = cuda.grid(1)
+ if tid < len(xarr):
+ # The function decorated with numba.jit may be directly reused
+ res[tid] = business_logic(xarr[tid], yarr[tid], zarr[tid])
+ # ex_cpu_gpu_compat.usegpu.end
+
+ # ex_cpu_gpu_compat.launch.begin
+ f.forall(len(X))(results, X, Y, Z)
+ print(results)
+ # [-126.79644737231007, 416.28324559588634, -218912930.2987788]
+ # ex_cpu_gpu_compat.launch.end
+
+ expect = [
+ business_logic(x, y, z) for x, y, z in zip(X, Y, Z)
+ ]
+
+ np.testing.assert_equal(
+ expect,
+ results.copy_to_host()
+ )
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/doc_examples/test_ffi.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/doc_examples/test_ffi.py
new file mode 100644
index 0000000000000000000000000000000000000000..20f1339d520c2f66a2d7812202321e9254345b53
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/doc_examples/test_ffi.py
@@ -0,0 +1,82 @@
+# Contents in this file are referenced from the sphinx-generated docs.
+# "magictoken" is used for markers as beginning and ending of example text.
+
+import unittest
+from numba.cuda.testing import (CUDATestCase, skip_on_cudasim)
+from numba.tests.support import skip_unless_cffi
+
+
+@skip_unless_cffi
+@skip_on_cudasim("cudasim doesn't support cuda import at non-top-level")
+class TestFFI(CUDATestCase):
+ def test_ex_linking_cu(self):
+ # magictoken.ex_linking_cu.begin
+ from numba import cuda
+ import numpy as np
+ import os
+
+ # Declaration of the foreign function
+ mul = cuda.declare_device('mul_f32_f32', 'float32(float32, float32)')
+
+ # Path to the source containing the foreign function
+ # (here assumed to be in a subdirectory called "ffi")
+ basedir = os.path.dirname(os.path.abspath(__file__))
+ functions_cu = os.path.join(basedir, 'ffi', 'functions.cu')
+
+ # Kernel that links in functions.cu and calls mul
+ @cuda.jit(link=[functions_cu])
+ def multiply_vectors(r, x, y):
+ i = cuda.grid(1)
+
+ if i < len(r):
+ r[i] = mul(x[i], y[i])
+
+ # Generate random data
+ N = 32
+ np.random.seed(1)
+ x = np.random.rand(N).astype(np.float32)
+ y = np.random.rand(N).astype(np.float32)
+ r = np.zeros_like(x)
+
+ # Run the kernel
+ multiply_vectors[1, 32](r, x, y)
+
+ # Sanity check - ensure the results match those expected
+ np.testing.assert_array_equal(r, x * y)
+ # magictoken.ex_linking_cu.end
+
+ def test_ex_from_buffer(self):
+ from numba import cuda
+ import os
+
+ basedir = os.path.dirname(os.path.abspath(__file__))
+ functions_cu = os.path.join(basedir, 'ffi', 'functions.cu')
+
+ # magictoken.ex_from_buffer_decl.begin
+ signature = 'float32(CPointer(float32), int32)'
+ sum_reduce = cuda.declare_device('sum_reduce', signature)
+ # magictoken.ex_from_buffer_decl.end
+
+ # magictoken.ex_from_buffer_kernel.begin
+ import cffi
+ ffi = cffi.FFI()
+
+ @cuda.jit(link=[functions_cu])
+ def reduction_caller(result, array):
+ array_ptr = ffi.from_buffer(array)
+ result[()] = sum_reduce(array_ptr, len(array))
+ # magictoken.ex_from_buffer_kernel.end
+
+ import numpy as np
+ x = np.arange(10).astype(np.float32)
+ r = np.ndarray((), dtype=np.float32)
+
+ reduction_caller[1, 1](r, x)
+
+ expected = np.sum(x)
+ actual = r[()]
+ np.testing.assert_allclose(expected, actual)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/doc_examples/test_laplace.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/doc_examples/test_laplace.py
new file mode 100644
index 0000000000000000000000000000000000000000..4caea9286c51144e3d62c1800f18974c0a61cf43
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/doc_examples/test_laplace.py
@@ -0,0 +1,155 @@
+import unittest
+
+from numba.cuda.testing import (CUDATestCase, skip_if_cudadevrt_missing,
+ skip_on_cudasim, skip_unless_cc_60,
+ skip_if_mvc_enabled)
+from numba.tests.support import captured_stdout
+
+
+@skip_if_cudadevrt_missing
+@skip_unless_cc_60
+@skip_if_mvc_enabled('CG not supported with MVC')
+@skip_on_cudasim("cudasim doesn't support cuda import at non-top-level")
+class TestLaplace(CUDATestCase):
+ """
+ Test simple vector addition
+ """
+
+ def setUp(self):
+ # Prevent output from this test showing up when running the test suite
+ self._captured_stdout = captured_stdout()
+ self._captured_stdout.__enter__()
+ super().setUp()
+
+ def tearDown(self):
+ # No exception type, value, or traceback
+ self._captured_stdout.__exit__(None, None, None)
+ super().tearDown()
+
+ def test_ex_laplace(self):
+
+ # set True to regenerate the figures that
+ # accompany this example
+ plot = False
+
+ # ex_laplace.import.begin
+ import numpy as np
+ from numba import cuda
+ # ex_laplace.import.end
+
+ # ex_laplace.allocate.begin
+ # Use an odd problem size.
+ # This is so there can be an element truly in the "middle" for symmetry.
+ size = 1001
+ data = np.zeros(size)
+
+ # Middle element is made very hot
+ data[500] = 10000
+ buf_0 = cuda.to_device(data)
+
+ # This extra array is used for synchronization purposes
+ buf_1 = cuda.device_array_like(buf_0)
+
+ niter = 10000
+ # ex_laplace.allocate.end
+
+ if plot:
+ import matplotlib.pyplot as plt
+ fig, ax = plt.subplots(figsize=(16 * 0.66, 9 * 0.66))
+ plt.plot(
+ np.arange(len(buf_0)),
+ buf_0.copy_to_host(),
+ lw=3,
+ marker="*",
+ color='black'
+ )
+
+ plt.title('Initial State', fontsize=24)
+ plt.xlabel('Position', fontsize=24)
+ plt.ylabel('Temperature', fontsize=24)
+
+ ax.set_xticks(ax.get_xticks(), fontsize=16)
+ ax.set_yticks(ax.get_yticks(), fontsize=16)
+ plt.xlim(0, len(data))
+ plt.ylim(0, 10001)
+ plt.savefig('laplace_initial.svg')
+
+ # ex_laplace.kernel.begin
+ @cuda.jit
+ def solve_heat_equation(buf_0, buf_1, timesteps, k):
+ i = cuda.grid(1)
+
+ # Don't continue if our index is outside the domain
+ if i >= len(buf_0):
+ return
+
+ # Prepare to do a grid-wide synchronization later
+ grid = cuda.cg.this_grid()
+
+ for step in range(timesteps):
+ # Select the buffer from the previous timestep
+ if (step % 2) == 0:
+ data = buf_0
+ next_data = buf_1
+ else:
+ data = buf_1
+ next_data = buf_0
+
+ # Get the current temperature associated with this point
+ curr_temp = data[i]
+
+ # Apply formula from finite difference equation
+ if i == 0:
+ # Left wall is held at T = 0
+ next_temp = curr_temp + k * (data[i + 1] - (2 * curr_temp))
+ elif i == len(data) - 1:
+ # Right wall is held at T = 0
+ next_temp = curr_temp + k * (data[i - 1] - (2 * curr_temp))
+ else:
+ # Interior points are a weighted average of their neighbors
+ next_temp = curr_temp + k * (
+ data[i - 1] - (2 * curr_temp) + data[i + 1]
+ )
+
+ # Write new value to the next buffer
+ next_data[i] = next_temp
+
+ # Wait for every thread to write before moving on
+ grid.sync()
+ # ex_laplace.kernel.end
+
+ # ex_laplace.launch.begin
+ solve_heat_equation.forall(len(data))(
+ buf_0, buf_1, niter, 0.25
+ )
+ # ex_laplace.launch.end
+
+ results = buf_1.copy_to_host()
+ if plot:
+ fig, ax = plt.subplots(figsize=(16 * 0.66, 9 * 0.66))
+ plt.plot(
+ np.arange(len(results)),
+ results, lw=3,
+ marker="*",
+ color='black'
+ )
+ plt.title(f"T = {niter}", fontsize=24)
+ plt.xlabel('Position', fontsize=24)
+ plt.ylabel('Temperature', fontsize=24)
+
+ ax.set_xticks(ax.get_xticks(), fontsize=16)
+ ax.set_yticks(ax.get_yticks(), fontsize=16)
+
+ plt.ylim(0, max(results))
+ plt.xlim(0, len(results))
+ plt.savefig('laplace_final.svg')
+
+ # Integral over the domain should be equal to its initial value.
+ # Note that this should match the initial value of data[500] above, but
+ # we don't assign it to a variable because that would make the example
+ # code look a bit oddly verbose.
+ np.testing.assert_allclose(results.sum(), 10000)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/doc_examples/test_matmul.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/doc_examples/test_matmul.py
new file mode 100644
index 0000000000000000000000000000000000000000..6e0dd44c1455d8b404327757a06a0bccd81e89bd
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/doc_examples/test_matmul.py
@@ -0,0 +1,173 @@
+"""
+Matrix multiplication example via `cuda.jit`.
+
+Reference: https://stackoverflow.com/a/64198479/13697228 by @RobertCrovella
+
+Contents in this file are referenced from the sphinx-generated docs.
+"magictoken" is used for markers as beginning and ending of example text.
+"""
+import unittest
+from numba.cuda.testing import CUDATestCase, skip_on_cudasim
+from numba.tests.support import captured_stdout
+
+
+@skip_on_cudasim("cudasim doesn't support cuda import at non-top-level")
+class TestMatMul(CUDATestCase):
+ """
+ Text matrix multiplication using simple, shared memory/square, and shared
+ memory/nonsquare cases.
+ """
+
+ def setUp(self):
+ # Prevent output from this test showing up when running the test suite
+ self._captured_stdout = captured_stdout()
+ self._captured_stdout.__enter__()
+ super().setUp()
+
+ def tearDown(self):
+ # No exception type, value, or traceback
+ self._captured_stdout.__exit__(None, None, None)
+ super().tearDown()
+
+ def test_ex_matmul(self):
+ """Test of matrix multiplication on various cases."""
+ # magictoken.ex_import.begin
+ from numba import cuda, float32
+ import numpy as np
+ import math
+ # magictoken.ex_import.end
+
+ # magictoken.ex_matmul.begin
+ @cuda.jit
+ def matmul(A, B, C):
+ """Perform square matrix multiplication of C = A * B."""
+ i, j = cuda.grid(2)
+ if i < C.shape[0] and j < C.shape[1]:
+ tmp = 0.
+ for k in range(A.shape[1]):
+ tmp += A[i, k] * B[k, j]
+ C[i, j] = tmp
+ # magictoken.ex_matmul.end
+
+ # magictoken.ex_run_matmul.begin
+ x_h = np.arange(16).reshape([4, 4])
+ y_h = np.ones([4, 4])
+ z_h = np.zeros([4, 4])
+
+ x_d = cuda.to_device(x_h)
+ y_d = cuda.to_device(y_h)
+ z_d = cuda.to_device(z_h)
+
+ threadsperblock = (16, 16)
+ blockspergrid_x = math.ceil(z_h.shape[0] / threadsperblock[0])
+ blockspergrid_y = math.ceil(z_h.shape[1] / threadsperblock[1])
+ blockspergrid = (blockspergrid_x, blockspergrid_y)
+
+ matmul[blockspergrid, threadsperblock](x_d, y_d, z_d)
+ z_h = z_d.copy_to_host()
+ print(z_h)
+ print(x_h @ y_h)
+ # magictoken.ex_run_matmul.end
+
+ # magictoken.ex_fast_matmul.begin
+ # Controls threads per block and shared memory usage.
+ # The computation will be done on blocks of TPBxTPB elements.
+ # TPB should not be larger than 32 in this example
+ TPB = 16
+
+ @cuda.jit
+ def fast_matmul(A, B, C):
+ """
+ Perform matrix multiplication of C = A * B using CUDA shared memory.
+
+ Reference: https://stackoverflow.com/a/64198479/13697228 by @RobertCrovella
+ """
+ # Define an array in the shared memory
+ # The size and type of the arrays must be known at compile time
+ sA = cuda.shared.array(shape=(TPB, TPB), dtype=float32)
+ sB = cuda.shared.array(shape=(TPB, TPB), dtype=float32)
+
+ x, y = cuda.grid(2)
+
+ tx = cuda.threadIdx.x
+ ty = cuda.threadIdx.y
+ bpg = cuda.gridDim.x # blocks per grid
+
+ # Each thread computes one element in the result matrix.
+ # The dot product is chunked into dot products of TPB-long vectors.
+ tmp = float32(0.)
+ for i in range(bpg):
+ # Preload data into shared memory
+ sA[ty, tx] = 0
+ sB[ty, tx] = 0
+ if y < A.shape[0] and (tx + i * TPB) < A.shape[1]:
+ sA[ty, tx] = A[y, tx + i * TPB]
+ if x < B.shape[1] and (ty + i * TPB) < B.shape[0]:
+ sB[ty, tx] = B[ty + i * TPB, x]
+
+ # Wait until all threads finish preloading
+ cuda.syncthreads()
+
+ # Computes partial product on the shared memory
+ for j in range(TPB):
+ tmp += sA[ty, j] * sB[j, tx]
+
+ # Wait until all threads finish computing
+ cuda.syncthreads()
+ if y < C.shape[0] and x < C.shape[1]:
+ C[y, x] = tmp
+ # magictoken.ex_fast_matmul.end
+
+ # magictoken.ex_run_fast_matmul.begin
+ x_h = np.arange(16).reshape([4, 4])
+ y_h = np.ones([4, 4])
+ z_h = np.zeros([4, 4])
+
+ x_d = cuda.to_device(x_h)
+ y_d = cuda.to_device(y_h)
+ z_d = cuda.to_device(z_h)
+
+ threadsperblock = (TPB, TPB)
+ blockspergrid_x = math.ceil(z_h.shape[0] / threadsperblock[0])
+ blockspergrid_y = math.ceil(z_h.shape[1] / threadsperblock[1])
+ blockspergrid = (blockspergrid_x, blockspergrid_y)
+
+ fast_matmul[blockspergrid, threadsperblock](x_d, y_d, z_d)
+ z_h = z_d.copy_to_host()
+ print(z_h)
+ print(x_h @ y_h)
+ # magictoken.ex_run_fast_matmul.end
+
+ # fast_matmul test(s)
+ msg = "fast_matmul incorrect for shared memory, square case."
+ self.assertTrue(np.all(z_h == x_h @ y_h), msg=msg)
+
+ # magictoken.ex_run_nonsquare.begin
+ x_h = np.arange(115).reshape([5, 23])
+ y_h = np.ones([23, 7])
+ z_h = np.zeros([5, 7])
+
+ x_d = cuda.to_device(x_h)
+ y_d = cuda.to_device(y_h)
+ z_d = cuda.to_device(z_h)
+
+ threadsperblock = (TPB, TPB)
+ grid_y_max = max(x_h.shape[0], y_h.shape[0])
+ grid_x_max = max(x_h.shape[1], y_h.shape[1])
+ blockspergrid_x = math.ceil(grid_x_max / threadsperblock[0])
+ blockspergrid_y = math.ceil(grid_y_max / threadsperblock[1])
+ blockspergrid = (blockspergrid_x, blockspergrid_y)
+
+ fast_matmul[blockspergrid, threadsperblock](x_d, y_d, z_d)
+ z_h = z_d.copy_to_host()
+ print(z_h)
+ print(x_h @ y_h)
+ # magictoken.ex_run_nonsquare.end
+
+ # nonsquare fast_matmul test(s)
+ msg = "fast_matmul incorrect for shared memory, non-square case."
+ self.assertTrue(np.all(z_h == x_h @ y_h), msg=msg)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/doc_examples/test_montecarlo.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/doc_examples/test_montecarlo.py
new file mode 100644
index 0000000000000000000000000000000000000000..92627084f468b4944c059dbdff90812334a54551
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/doc_examples/test_montecarlo.py
@@ -0,0 +1,109 @@
+import unittest
+
+from numba.cuda.testing import CUDATestCase, skip_on_cudasim
+from numba.tests.support import captured_stdout
+
+
+@skip_on_cudasim("cudasim doesn't support cuda import at non-top-level")
+class TestMonteCarlo(CUDATestCase):
+ """
+ Test monte-carlo integration
+ """
+
+ def setUp(self):
+ # Prevent output from this test showing up when running the test suite
+ self._captured_stdout = captured_stdout()
+ self._captured_stdout.__enter__()
+ super().setUp()
+
+ def tearDown(self):
+ # No exception type, value, or traceback
+ self._captured_stdout.__exit__(None, None, None)
+ super().tearDown()
+
+ def test_ex_montecarlo(self):
+ # ex_montecarlo.import.begin
+ import numba
+ import numpy as np
+ from numba import cuda
+ from numba.cuda.random import (
+ create_xoroshiro128p_states,
+ xoroshiro128p_uniform_float32,
+ )
+ # ex_montecarlo.import.end
+
+ # ex_montecarlo.define.begin
+ # number of samples, higher will lead to a more accurate answer
+ nsamps = 1000000
+ # ex_montecarlo.define.end
+
+ # ex_montecarlo.kernel.begin
+ @cuda.jit
+ def mc_integrator_kernel(out, rng_states, lower_lim, upper_lim):
+ """
+ kernel to draw random samples and evaluate the function to
+ be integrated at those sample values
+ """
+ size = len(out)
+
+ gid = cuda.grid(1)
+ if gid < size:
+ # draw a sample between 0 and 1 on this thread
+ samp = xoroshiro128p_uniform_float32(rng_states, gid)
+
+ # normalize this sample to the limit range
+ samp = samp * (upper_lim - lower_lim) + lower_lim
+
+ # evaluate the function to be
+ # integrated at the normalized
+ # value of the sample
+ y = func(samp)
+ out[gid] = y
+ # ex_montecarlo.kernel.end
+
+ # ex_montecarlo.callfunc.begin
+ @cuda.reduce
+ def sum_reduce(a, b):
+ return a + b
+
+ def mc_integrate(lower_lim, upper_lim, nsamps):
+ """
+ approximate the definite integral of `func` from
+ `lower_lim` to `upper_lim`
+ """
+ out = cuda.to_device(np.zeros(nsamps, dtype="float32"))
+ rng_states = create_xoroshiro128p_states(nsamps, seed=42)
+
+ # jit the function for use in CUDA kernels
+
+ mc_integrator_kernel.forall(nsamps)(
+ out, rng_states, lower_lim, upper_lim
+ )
+ # normalization factor to convert
+ # to the average: (b - a)/(N - 1)
+ factor = (upper_lim - lower_lim) / (nsamps - 1)
+
+ return sum_reduce(out) * factor
+ # ex_montecarlo.callfunc.end
+
+ # ex_montecarlo.launch.begin
+ # define a function to integrate
+ @numba.jit
+ def func(x):
+ return 1.0 / x
+
+ mc_integrate(1, 2, nsamps) # array(0.6929643, dtype=float32)
+ mc_integrate(2, 3, nsamps) # array(0.4054021, dtype=float32)
+ # ex_montecarlo.launch.end
+
+ # values computed independently using maple
+ np.testing.assert_allclose(
+ mc_integrate(1, 2, nsamps), 0.69315, atol=0.001
+ )
+ np.testing.assert_allclose(
+ mc_integrate(2, 3, nsamps), 0.4055, atol=0.001
+ )
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/doc_examples/test_random.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/doc_examples/test_random.py
new file mode 100644
index 0000000000000000000000000000000000000000..0e93a1f17a8193cf5907772b8cc2d340356eee3a
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/doc_examples/test_random.py
@@ -0,0 +1,59 @@
+# Contents in this file are referenced from the sphinx-generated docs.
+# "magictoken" is used for markers as beginning and ending of example text.
+
+import unittest
+from numba.cuda.testing import CUDATestCase, skip_on_cudasim
+
+
+@skip_on_cudasim("cudasim doesn't support cuda import at non-top-level")
+class TestRandom(CUDATestCase):
+ def test_ex_3d_grid(self):
+ # magictoken.ex_3d_grid.begin
+ from numba import cuda
+ from numba.cuda.random import (create_xoroshiro128p_states,
+ xoroshiro128p_uniform_float32)
+ import numpy as np
+
+ @cuda.jit
+ def random_3d(arr, rng_states):
+ # Per-dimension thread indices and strides
+ startx, starty, startz = cuda.grid(3)
+ stridex, stridey, stridez = cuda.gridsize(3)
+
+ # Linearized thread index
+ tid = (startz * stridey * stridex) + (starty * stridex) + startx
+
+ # Use strided loops over the array to assign a random value to each entry
+ for i in range(startz, arr.shape[0], stridez):
+ for j in range(starty, arr.shape[1], stridey):
+ for k in range(startx, arr.shape[2], stridex):
+ arr[i, j, k] = xoroshiro128p_uniform_float32(rng_states, tid)
+
+ # Array dimensions
+ X, Y, Z = 701, 900, 719
+
+ # Block and grid dimensions
+ bx, by, bz = 8, 8, 8
+ gx, gy, gz = 16, 16, 16
+
+ # Total number of threads
+ nthreads = bx * by * bz * gx * gy * gz
+
+ # Initialize a state for each thread
+ rng_states = create_xoroshiro128p_states(nthreads, seed=1)
+
+ # Generate random numbers
+ arr = cuda.device_array((X, Y, Z), dtype=np.float32)
+ random_3d[(gx, gy, gz), (bx, by, bz)](arr, rng_states)
+ # magictoken.ex_3d_grid.end
+
+ # Some basic tests of the randomly-generated numbers
+ host_arr = arr.copy_to_host()
+ self.assertGreater(np.mean(host_arr), 0.49)
+ self.assertLess(np.mean(host_arr), 0.51)
+ self.assertTrue(np.all(host_arr <= 1.0))
+ self.assertTrue(np.all(host_arr >= 0.0))
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/doc_examples/test_reduction.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/doc_examples/test_reduction.py
new file mode 100644
index 0000000000000000000000000000000000000000..c118fbf157d2a7627d9930424c0f9d255abfe397
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/doc_examples/test_reduction.py
@@ -0,0 +1,76 @@
+import unittest
+
+from numba.cuda.testing import CUDATestCase, skip_on_cudasim
+from numba.tests.support import captured_stdout
+
+
+@skip_on_cudasim("cudasim doesn't support cuda import at non-top-level")
+class TestReduction(CUDATestCase):
+ """
+ Test shared memory reduction
+ """
+
+ def setUp(self):
+ # Prevent output from this test showing up when running the test suite
+ self._captured_stdout = captured_stdout()
+ self._captured_stdout.__enter__()
+ super().setUp()
+
+ def tearDown(self):
+ # No exception type, value, or traceback
+ self._captured_stdout.__exit__(None, None, None)
+ super().tearDown()
+
+ def test_ex_reduction(self):
+ # ex_reduction.import.begin
+ import numpy as np
+ from numba import cuda
+ from numba.types import int32
+ # ex_reduction.import.end
+
+ # ex_reduction.allocate.begin
+ # generate data
+ a = cuda.to_device(np.arange(1024))
+ nelem = len(a)
+ # ex_reduction.allocate.end
+
+ # ex_reduction.kernel.begin
+ @cuda.jit
+ def array_sum(data):
+ tid = cuda.threadIdx.x
+ size = len(data)
+ if tid < size:
+ i = cuda.grid(1)
+
+ # Declare an array in shared memory
+ shr = cuda.shared.array(nelem, int32)
+ shr[tid] = data[i]
+
+ # Ensure writes to shared memory are visible
+ # to all threads before reducing
+ cuda.syncthreads()
+
+ s = 1
+ while s < cuda.blockDim.x:
+ if tid % (2 * s) == 0:
+ # Stride by `s` and add
+ shr[tid] += shr[tid + s]
+ s *= 2
+ cuda.syncthreads()
+
+ # After the loop, the zeroth element contains the sum
+ if tid == 0:
+ data[tid] = shr[tid]
+ # ex_reduction.kernel.end
+
+ # ex_reduction.launch.begin
+ array_sum[1, nelem](a)
+ print(a[0]) # 523776
+ print(sum(np.arange(1024))) # 523776
+ # ex_reduction.launch.end
+
+ np.testing.assert_equal(a[0], sum(np.arange(1024)))
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/doc_examples/test_sessionize.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/doc_examples/test_sessionize.py
new file mode 100644
index 0000000000000000000000000000000000000000..6c66a65996fd6d6dbd6c9a4dec13e747e4f93c90
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/doc_examples/test_sessionize.py
@@ -0,0 +1,130 @@
+import unittest
+
+from numba.cuda.testing import (CUDATestCase, skip_if_cudadevrt_missing,
+ skip_on_cudasim, skip_unless_cc_60,
+ skip_if_mvc_enabled)
+from numba.tests.support import captured_stdout
+
+
+@skip_if_cudadevrt_missing
+@skip_unless_cc_60
+@skip_if_mvc_enabled('CG not supported with MVC')
+@skip_on_cudasim("cudasim doesn't support cuda import at non-top-level")
+class TestSessionization(CUDATestCase):
+ """
+ Test click stream sessionization
+ """
+
+ def setUp(self):
+ # Prevent output from this test showing up when running the test suite
+ self._captured_stdout = captured_stdout()
+ self._captured_stdout.__enter__()
+ super().setUp()
+
+ def tearDown(self):
+ # No exception type, value, or traceback
+ self._captured_stdout.__exit__(None, None, None)
+ super().tearDown()
+
+ def test_ex_sessionize(self):
+ # ex_sessionize.import.begin
+ import numpy as np
+ from numba import cuda
+
+ # Set the timeout to one hour
+ session_timeout = np.int64(np.timedelta64("3600", "s"))
+ # ex_sessionize.import.end
+
+ # ex_sessionize.allocate.begin
+ # Generate data
+ ids = cuda.to_device(
+ np.array(
+ [
+ 1, 1, 1, 1, 1, 1,
+ 2, 2, 2,
+ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
+ 4, 4, 4, 4, 4, 4, 4, 4, 4,
+ ]
+ )
+ )
+ sec = cuda.to_device(
+ np.array(
+ [
+ 1, 2, 3, 5000, 5001, 5002, 1,
+ 2, 3, 1, 2, 5000, 5001, 10000,
+ 10001, 10002, 10003, 15000, 150001,
+ 1, 5000, 50001, 15000, 20000,
+ 25000, 25001, 25002, 25003,
+ ],
+ dtype="datetime64[ns]",
+ ).astype(
+ "int64"
+ ) # Cast to int64 for compatibility
+ )
+ # Create a vector to hold the results
+ results = cuda.to_device(np.zeros(len(ids)))
+ # ex_sessionize.allocate.end
+
+ # ex_sessionize.kernel.begin
+ @cuda.jit
+ def sessionize(user_id, timestamp, results):
+ gid = cuda.grid(1)
+ size = len(user_id)
+
+ if gid >= size:
+ return
+
+ # Determine session boundaries
+ is_first_datapoint = gid == 0
+ if not is_first_datapoint:
+ new_user = user_id[gid] != user_id[gid - 1]
+ timed_out = (
+ timestamp[gid] - timestamp[gid - 1] > session_timeout
+ )
+ is_sess_boundary = new_user or timed_out
+ else:
+ is_sess_boundary = True
+
+ # Determine session labels
+ if is_sess_boundary:
+ # This thread marks the start of a session
+ results[gid] = gid
+
+ # Make sure all session boundaries are written
+ # before populating the session id
+ grid = cuda.cg.this_grid()
+ grid.sync()
+
+ look_ahead = 1
+ # Check elements 'forward' of this one
+ # until a new session boundary is found
+ while results[gid + look_ahead] == 0:
+ results[gid + look_ahead] = gid
+ look_ahead += 1
+ # Avoid out-of-bounds accesses by the last thread
+ if gid + look_ahead == size - 1:
+ results[gid + look_ahead] = gid
+ break
+ # ex_sessionize.kernel.end
+
+ # ex_sessionize.launch.begin
+ sessionize.forall(len(ids))(ids, sec, results)
+
+ print(results.copy_to_host())
+ # array([ 0., 0., 0., 3., 3., 3.,
+ # 6., 6., 6., 9., 9., 11.,
+ # 11., 13., 13., 13., 13., 17.,
+ # 18., 19., 20., 21., 21., 23.,
+ # 24., 24., 24., 24.])
+ # ex_sessionize.launch.end
+
+ expect = [
+ 0, 0, 0, 3, 3, 3, 6, 6, 6, 9, 9,
+ 11, 11, 13, 13, 13, 13, 17, 18, 19, 20, 21,
+ 21, 23, 24, 24, 24, 24
+ ]
+ np.testing.assert_equal(expect, results.copy_to_host())
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/doc_examples/test_ufunc.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/doc_examples/test_ufunc.py
new file mode 100644
index 0000000000000000000000000000000000000000..c1f56b07e92189057dbc76a8b40a53b8daf7b678
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/doc_examples/test_ufunc.py
@@ -0,0 +1,50 @@
+import unittest
+
+from numba.cuda.testing import CUDATestCase, skip_on_cudasim
+from numba.tests.support import captured_stdout
+
+
+@skip_on_cudasim("cudasim doesn't support cuda import at non-top-level")
+class TestUFunc(CUDATestCase):
+ """
+ Test calling a UFunc
+ """
+
+ def setUp(self):
+ # Prevent output from this test showing
+ # up when running the test suite
+ self._captured_stdout = captured_stdout()
+ self._captured_stdout.__enter__()
+ super().setUp()
+
+ def tearDown(self):
+ # No exception type, value, or traceback
+ self._captured_stdout.__exit__(None, None, None)
+ super().tearDown()
+
+ def test_ex_cuda_ufunc_call(self):
+ # ex_cuda_ufunc.begin
+ import numpy as np
+ from numba import cuda
+
+ # A kernel calling a ufunc (sin, in this case)
+ @cuda.jit
+ def f(r, x):
+ # Compute sin(x) with result written to r
+ np.sin(x, r)
+
+ # Declare input and output arrays
+ x = np.arange(10, dtype=np.float32) - 5
+ r = np.zeros_like(x)
+
+ # Launch kernel that calls the ufunc
+ f[1, 1](r, x)
+
+ # A quick sanity check demonstrating equality of the sine computed by
+ # the sin ufunc inside the kernel, and NumPy's sin ufunc
+ np.testing.assert_allclose(r, np.sin(x))
+ # ex_cuda_ufunc.end
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/doc_examples/test_vecadd.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/doc_examples/test_vecadd.py
new file mode 100644
index 0000000000000000000000000000000000000000..c6ae197eeae8bbef8c8ba5284eccc4127f9b7a84
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/doc_examples/test_vecadd.py
@@ -0,0 +1,73 @@
+import unittest
+
+from numba.cuda.testing import CUDATestCase, skip_on_cudasim
+from numba.tests.support import captured_stdout
+
+
+@skip_on_cudasim("cudasim doesn't support cuda import at non-top-level")
+class TestVecAdd(CUDATestCase):
+ """
+ Test simple vector addition
+ """
+
+ def setUp(self):
+ # Prevent output from this test showing
+ # up when running the test suite
+ self._captured_stdout = captured_stdout()
+ self._captured_stdout.__enter__()
+ super().setUp()
+
+ def tearDown(self):
+ # No exception type, value, or traceback
+ self._captured_stdout.__exit__(None, None, None)
+ super().tearDown()
+
+ def test_ex_vecadd(self):
+ # ex_vecadd.import.begin
+ import numpy as np
+ from numba import cuda
+ # ex_vecadd.import.end
+
+ # ex_vecadd.kernel.begin
+ @cuda.jit
+ def f(a, b, c):
+ # like threadIdx.x + (blockIdx.x * blockDim.x)
+ tid = cuda.grid(1)
+ size = len(c)
+
+ if tid < size:
+ c[tid] = a[tid] + b[tid]
+ # ex_vecadd.kernel.end
+
+ # Seed RNG for test repeatability
+ np.random.seed(1)
+
+ # ex_vecadd.allocate.begin
+ N = 100000
+ a = cuda.to_device(np.random.random(N))
+ b = cuda.to_device(np.random.random(N))
+ c = cuda.device_array_like(a)
+ # ex_vecadd.allocate.end
+
+ # ex_vecadd.forall.begin
+ f.forall(len(a))(a, b, c)
+ print(c.copy_to_host())
+ # ex_vecadd.forall.end
+
+ # ex_vecadd.launch.begin
+ # Enough threads per block for several warps per block
+ nthreads = 256
+ # Enough blocks to cover the entire vector depending on its length
+ nblocks = (len(a) // nthreads) + 1
+ f[nblocks, nthreads](a, b, c)
+ print(c.copy_to_host())
+ # ex_vecadd.launch.end
+
+ np.testing.assert_equal(
+ c.copy_to_host(),
+ a.copy_to_host() + b.copy_to_host()
+ )
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/nocuda/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/nocuda/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..d9e7d31af3b99e121a9ae04bc855a6c80cc4594d
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/nocuda/__init__.py
@@ -0,0 +1,8 @@
+from numba.cuda.testing import ensure_supported_ccs_initialized
+from numba.testing import load_testsuite
+import os
+
+
+def load_tests(loader, tests, pattern):
+ ensure_supported_ccs_initialized()
+ return load_testsuite(loader, os.path.dirname(__file__))
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/nocuda/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/nocuda/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..76ec7205de8e73fb893468d6c301ad2bac5c8a77
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/nocuda/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/nocuda/__pycache__/test_dummyarray.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/nocuda/__pycache__/test_dummyarray.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..840a6048cdd1a66479beae37f3cea3339c43dad0
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/nocuda/__pycache__/test_dummyarray.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/nocuda/__pycache__/test_function_resolution.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/nocuda/__pycache__/test_function_resolution.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5ce33f22e317a93612713aa56d0b4365065cabf1
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/nocuda/__pycache__/test_function_resolution.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/nocuda/__pycache__/test_import.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/nocuda/__pycache__/test_import.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..57c6cd82946ba4318fed928c28f6155e344aefe9
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/nocuda/__pycache__/test_import.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/nocuda/__pycache__/test_library_lookup.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/nocuda/__pycache__/test_library_lookup.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1f8f83cabdf040c33fd0e458a03e2610d46fefe8
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/nocuda/__pycache__/test_library_lookup.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/nocuda/__pycache__/test_nvvm.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/nocuda/__pycache__/test_nvvm.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ffa934aa2a73d2ae617567b3449332976857518a
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/nocuda/__pycache__/test_nvvm.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/nocuda/test_dummyarray.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/nocuda/test_dummyarray.py
new file mode 100644
index 0000000000000000000000000000000000000000..e4ad7d0fd6638f5f5e84b00cf60430b505bf3fee
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/nocuda/test_dummyarray.py
@@ -0,0 +1,359 @@
+import unittest
+import itertools
+import numpy as np
+from numba.cuda.cudadrv.dummyarray import Array
+from numba.cuda.testing import skip_on_cudasim
+
+
+@skip_on_cudasim("Tests internals of the CUDA driver device array")
+class TestSlicing(unittest.TestCase):
+
+ def assertSameContig(self, arr, nparr):
+ attrs = 'C_CONTIGUOUS', 'F_CONTIGUOUS'
+ for attr in attrs:
+ if arr.flags[attr] != nparr.flags[attr]:
+ if arr.size == 0 and nparr.size == 0:
+ # numpy <=1.7 bug that some empty array are contiguous and
+ # some are not
+ pass
+ else:
+ self.fail("contiguous flag mismatch:\ngot=%s\nexpect=%s" %
+ (arr.flags, nparr.flags))
+
+ #### 1D
+
+ def test_slice0_1d(self):
+ nparr = np.empty(4)
+ arr = Array.from_desc(0, nparr.shape, nparr.strides,
+ nparr.dtype.itemsize)
+ self.assertSameContig(arr, nparr)
+ xx = -2, -1, 0, 1, 2
+ for x in xx:
+ expect = nparr[x:]
+ got = arr[x:]
+ self.assertSameContig(got, expect)
+ self.assertEqual(got.shape, expect.shape)
+ self.assertEqual(got.strides, expect.strides)
+
+ def test_slice1_1d(self):
+ nparr = np.empty(4)
+ arr = Array.from_desc(0, nparr.shape, nparr.strides,
+ nparr.dtype.itemsize)
+ xx = -2, -1, 0, 1, 2
+ for x in xx:
+ expect = nparr[:x]
+ got = arr[:x]
+ self.assertSameContig(got, expect)
+ self.assertEqual(got.shape, expect.shape)
+ self.assertEqual(got.strides, expect.strides)
+
+ def test_slice2_1d(self):
+ nparr = np.empty(4)
+ arr = Array.from_desc(0, nparr.shape, nparr.strides,
+ nparr.dtype.itemsize)
+ xx = -2, -1, 0, 1, 2
+ for x, y in itertools.product(xx, xx):
+ expect = nparr[x:y]
+ got = arr[x:y]
+ self.assertSameContig(got, expect)
+ self.assertEqual(got.shape, expect.shape)
+ self.assertEqual(got.strides, expect.strides)
+
+ #### 2D
+
+ def test_slice0_2d(self):
+ nparr = np.empty((4, 5))
+ arr = Array.from_desc(0, nparr.shape, nparr.strides,
+ nparr.dtype.itemsize)
+ xx = -2, 0, 1, 2
+ for x in xx:
+ expect = nparr[x:]
+ got = arr[x:]
+ self.assertSameContig(got, expect)
+ self.assertEqual(got.shape, expect.shape)
+ self.assertEqual(got.strides, expect.strides)
+
+ for x, y in itertools.product(xx, xx):
+ expect = nparr[x:, y:]
+ got = arr[x:, y:]
+ self.assertSameContig(got, expect)
+ self.assertEqual(got.shape, expect.shape)
+ self.assertEqual(got.strides, expect.strides)
+
+ def test_slice1_2d(self):
+ nparr = np.empty((4, 5))
+ arr = Array.from_desc(0, nparr.shape, nparr.strides,
+ nparr.dtype.itemsize)
+ xx = -2, 0, 2
+ for x in xx:
+ expect = nparr[:x]
+ got = arr[:x]
+ self.assertEqual(got.shape, expect.shape)
+ self.assertEqual(got.strides, expect.strides)
+ self.assertSameContig(got, expect)
+
+ for x, y in itertools.product(xx, xx):
+ expect = nparr[:x, :y]
+ got = arr[:x, :y]
+ self.assertEqual(got.shape, expect.shape)
+ self.assertEqual(got.strides, expect.strides)
+ self.assertSameContig(got, expect)
+
+ def test_slice2_2d(self):
+ nparr = np.empty((4, 5))
+ arr = Array.from_desc(0, nparr.shape, nparr.strides,
+ nparr.dtype.itemsize)
+ xx = -2, 0, 2
+ for s, t, u, v in itertools.product(xx, xx, xx, xx):
+ expect = nparr[s:t, u:v]
+ got = arr[s:t, u:v]
+ self.assertSameContig(got, expect)
+ self.assertEqual(got.shape, expect.shape)
+ self.assertEqual(got.strides, expect.strides)
+
+ for x, y in itertools.product(xx, xx):
+ expect = nparr[s:t, u:v]
+ got = arr[s:t, u:v]
+ self.assertSameContig(got, expect)
+ self.assertEqual(got.shape, expect.shape)
+ self.assertEqual(got.strides, expect.strides)
+
+ #### Strided
+
+ def test_strided_1d(self):
+ nparr = np.empty(4)
+ arr = Array.from_desc(0, nparr.shape, nparr.strides,
+ nparr.dtype.itemsize)
+ xx = -2, -1, 1, 2
+ for x in xx:
+ expect = nparr[::x]
+ got = arr[::x]
+ self.assertSameContig(got, expect)
+ self.assertEqual(got.shape, expect.shape)
+ self.assertEqual(got.strides, expect.strides)
+
+ def test_strided_2d(self):
+ nparr = np.empty((4, 5))
+ arr = Array.from_desc(0, nparr.shape, nparr.strides,
+ nparr.dtype.itemsize)
+ xx = -2, -1, 1, 2
+ for a, b in itertools.product(xx, xx):
+ expect = nparr[::a, ::b]
+ got = arr[::a, ::b]
+ self.assertSameContig(got, expect)
+ self.assertEqual(got.shape, expect.shape)
+ self.assertEqual(got.strides, expect.strides)
+
+ def test_strided_3d(self):
+ nparr = np.empty((4, 5, 6))
+ arr = Array.from_desc(0, nparr.shape, nparr.strides,
+ nparr.dtype.itemsize)
+ xx = -2, -1, 1, 2
+ for a, b, c in itertools.product(xx, xx, xx):
+ expect = nparr[::a, ::b, ::c]
+ got = arr[::a, ::b, ::c]
+ self.assertSameContig(got, expect)
+ self.assertEqual(got.shape, expect.shape)
+ self.assertEqual(got.strides, expect.strides)
+
+ def test_issue_2766(self):
+ z = np.empty((1, 2, 3))
+ z = np.transpose(z, axes=(2, 0, 1))
+ arr = Array.from_desc(0, z.shape, z.strides, z.itemsize)
+ self.assertEqual(z.flags['C_CONTIGUOUS'], arr.flags['C_CONTIGUOUS'])
+ self.assertEqual(z.flags['F_CONTIGUOUS'], arr.flags['F_CONTIGUOUS'])
+
+
+@skip_on_cudasim("Tests internals of the CUDA driver device array")
+class TestReshape(unittest.TestCase):
+ def test_reshape_2d2d(self):
+ nparr = np.empty((4, 5))
+ arr = Array.from_desc(0, nparr.shape, nparr.strides,
+ nparr.dtype.itemsize)
+ expect = nparr.reshape(5, 4)
+ got = arr.reshape(5, 4)[0]
+ self.assertEqual(got.shape, expect.shape)
+ self.assertEqual(got.strides, expect.strides)
+
+ def test_reshape_2d1d(self):
+ nparr = np.empty((4, 5))
+ arr = Array.from_desc(0, nparr.shape, nparr.strides,
+ nparr.dtype.itemsize)
+ expect = nparr.reshape(5 * 4)
+ got = arr.reshape(5 * 4)[0]
+ self.assertEqual(got.shape, expect.shape)
+ self.assertEqual(got.strides, expect.strides)
+
+ def test_reshape_3d3d(self):
+ nparr = np.empty((3, 4, 5))
+ arr = Array.from_desc(0, nparr.shape, nparr.strides,
+ nparr.dtype.itemsize)
+ expect = nparr.reshape(5, 3, 4)
+ got = arr.reshape(5, 3, 4)[0]
+ self.assertEqual(got.shape, expect.shape)
+ self.assertEqual(got.strides, expect.strides)
+
+ def test_reshape_3d2d(self):
+ nparr = np.empty((3, 4, 5))
+ arr = Array.from_desc(0, nparr.shape, nparr.strides,
+ nparr.dtype.itemsize)
+ expect = nparr.reshape(3 * 4, 5)
+ got = arr.reshape(3 * 4, 5)[0]
+ self.assertEqual(got.shape, expect.shape)
+ self.assertEqual(got.strides, expect.strides)
+
+ def test_reshape_3d1d(self):
+ nparr = np.empty((3, 4, 5))
+ arr = Array.from_desc(0, nparr.shape, nparr.strides,
+ nparr.dtype.itemsize)
+ expect = nparr.reshape(3 * 4 * 5)
+ got = arr.reshape(3 * 4 * 5)[0]
+ self.assertEqual(got.shape, expect.shape)
+ self.assertEqual(got.strides, expect.strides)
+
+ def test_reshape_infer2d2d(self):
+ nparr = np.empty((4, 5))
+ arr = Array.from_desc(0, nparr.shape, nparr.strides,
+ nparr.dtype.itemsize)
+ expect = nparr.reshape(-1, 4)
+ got = arr.reshape(-1, 4)[0]
+ self.assertEqual(got.shape, expect.shape)
+ self.assertEqual(got.strides, expect.strides)
+
+ def test_reshape_infer2d1d(self):
+ nparr = np.empty((4, 5))
+ arr = Array.from_desc(0, nparr.shape, nparr.strides,
+ nparr.dtype.itemsize)
+ expect = nparr.reshape(-1)
+ got = arr.reshape(-1)[0]
+ self.assertEqual(got.shape, expect.shape)
+ self.assertEqual(got.strides, expect.strides)
+
+ def test_reshape_infer3d3d(self):
+ nparr = np.empty((3, 4, 5))
+ arr = Array.from_desc(0, nparr.shape, nparr.strides,
+ nparr.dtype.itemsize)
+ expect = nparr.reshape(5, -1, 4)
+ got = arr.reshape(5, -1, 4)[0]
+ self.assertEqual(got.shape, expect.shape)
+ self.assertEqual(got.strides, expect.strides)
+
+ def test_reshape_infer3d2d(self):
+ nparr = np.empty((3, 4, 5))
+ arr = Array.from_desc(0, nparr.shape, nparr.strides,
+ nparr.dtype.itemsize)
+ expect = nparr.reshape(3, -1)
+ got = arr.reshape(3, -1)[0]
+ self.assertEqual(got.shape, expect.shape)
+ self.assertEqual(got.strides, expect.strides)
+
+ def test_reshape_infer3d1d(self):
+ nparr = np.empty((3, 4, 5))
+ arr = Array.from_desc(0, nparr.shape, nparr.strides,
+ nparr.dtype.itemsize)
+ expect = nparr.reshape(-1)
+ got = arr.reshape(-1)[0]
+ self.assertEqual(got.shape, expect.shape)
+ self.assertEqual(got.strides, expect.strides)
+
+ def test_reshape_infer_two_unknowns(self):
+ nparr = np.empty((3, 4, 5))
+ arr = Array.from_desc(0, nparr.shape, nparr.strides,
+ nparr.dtype.itemsize)
+
+ with self.assertRaises(ValueError) as raises:
+ arr.reshape(-1, -1, 3)
+ self.assertIn('can only specify one unknown dimension',
+ str(raises.exception))
+
+ def test_reshape_infer_invalid_shape(self):
+ nparr = np.empty((3, 4, 5))
+ arr = Array.from_desc(0, nparr.shape, nparr.strides,
+ nparr.dtype.itemsize)
+
+ with self.assertRaises(ValueError) as raises:
+ arr.reshape(-1, 7)
+
+ expected_message = 'cannot infer valid shape for unknown dimension'
+ self.assertIn(expected_message, str(raises.exception))
+
+
+@skip_on_cudasim("Tests internals of the CUDA driver device array")
+class TestSqueeze(unittest.TestCase):
+ def test_squeeze(self):
+ nparr = np.empty((1, 2, 1, 4, 1, 3))
+ arr = Array.from_desc(
+ 0, nparr.shape, nparr.strides, nparr.dtype.itemsize
+ )
+
+ def _assert_equal_shape_strides(arr1, arr2):
+ self.assertEqual(arr1.shape, arr2.shape)
+ self.assertEqual(arr1.strides, arr2.strides)
+ _assert_equal_shape_strides(arr, nparr)
+ _assert_equal_shape_strides(arr.squeeze()[0], nparr.squeeze())
+ for axis in (0, 2, 4, (0, 2), (0, 4), (2, 4), (0, 2, 4)):
+ _assert_equal_shape_strides(
+ arr.squeeze(axis=axis)[0], nparr.squeeze(axis=axis)
+ )
+
+ def test_squeeze_invalid_axis(self):
+ nparr = np.empty((1, 2, 1, 4, 1, 3))
+ arr = Array.from_desc(
+ 0, nparr.shape, nparr.strides, nparr.dtype.itemsize
+ )
+ with self.assertRaises(ValueError):
+ arr.squeeze(axis=1)
+ with self.assertRaises(ValueError):
+ arr.squeeze(axis=(2, 3))
+
+
+@skip_on_cudasim("Tests internals of the CUDA driver device array")
+class TestExtent(unittest.TestCase):
+ def test_extent_1d(self):
+ nparr = np.empty(4)
+ arr = Array.from_desc(0, nparr.shape, nparr.strides,
+ nparr.dtype.itemsize)
+ s, e = arr.extent
+ self.assertEqual(e - s, nparr.size * nparr.dtype.itemsize)
+
+ def test_extent_2d(self):
+ nparr = np.empty((4, 5))
+ arr = Array.from_desc(0, nparr.shape, nparr.strides,
+ nparr.dtype.itemsize)
+ s, e = arr.extent
+ self.assertEqual(e - s, nparr.size * nparr.dtype.itemsize)
+
+ def test_extent_iter_1d(self):
+ nparr = np.empty(4)
+ arr = Array.from_desc(0, nparr.shape, nparr.strides,
+ nparr.dtype.itemsize)
+ [ext] = list(arr.iter_contiguous_extent())
+ self.assertEqual(ext, arr.extent)
+
+ def test_extent_iter_2d(self):
+ nparr = np.empty((4, 5))
+ arr = Array.from_desc(0, nparr.shape, nparr.strides,
+ nparr.dtype.itemsize)
+ [ext] = list(arr.iter_contiguous_extent())
+ self.assertEqual(ext, arr.extent)
+
+ self.assertEqual(len(list(arr[::2].iter_contiguous_extent())), 2)
+
+
+@skip_on_cudasim("Tests internals of the CUDA driver device array")
+class TestIterate(unittest.TestCase):
+ def test_for_loop(self):
+ # for #4201
+ N = 5
+ nparr = np.empty(N)
+ arr = Array.from_desc(0, nparr.shape, nparr.strides,
+ nparr.dtype.itemsize)
+
+ x = 0 # just a placeholder
+ # this loop should not raise AssertionError
+ for val in arr:
+ x = val # noqa: F841
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/nocuda/test_function_resolution.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/nocuda/test_function_resolution.py
new file mode 100644
index 0000000000000000000000000000000000000000..1153707bbc2701194f0f85dbd6451ba8355522b8
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/nocuda/test_function_resolution.py
@@ -0,0 +1,36 @@
+from numba.cuda.testing import unittest, skip_on_cudasim
+import operator
+from numba.core import types, typing
+from numba.cuda.cudadrv import nvvm
+
+
+@unittest.skipIf(not nvvm.is_available(), "No libNVVM")
+@skip_on_cudasim("Skip on simulator due to use of cuda_target")
+class TestFunctionResolution(unittest.TestCase):
+ def test_fp16_binary_operators(self):
+ from numba.cuda.descriptor import cuda_target
+ ops = (operator.add, operator.iadd, operator.sub, operator.isub,
+ operator.mul, operator.imul)
+ for op in ops:
+ fp16 = types.float16
+ typingctx = cuda_target.typing_context
+ typingctx.refresh()
+ fnty = typingctx.resolve_value_type(op)
+ out = typingctx.resolve_function_type(fnty, (fp16, fp16), {})
+ self.assertEqual(out, typing.signature(fp16, fp16, fp16),
+ msg=str(out))
+
+ def test_fp16_unary_operators(self):
+ from numba.cuda.descriptor import cuda_target
+ ops = (operator.neg, abs)
+ for op in ops:
+ fp16 = types.float16
+ typingctx = cuda_target.typing_context
+ typingctx.refresh()
+ fnty = typingctx.resolve_value_type(op)
+ out = typingctx.resolve_function_type(fnty, (fp16,), {})
+ self.assertEqual(out, typing.signature(fp16, fp16), msg=str(out))
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/nocuda/test_import.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/nocuda/test_import.py
new file mode 100644
index 0000000000000000000000000000000000000000..73126cd6ed10d8b6668fbe4cd3fe45bf8d42f4bf
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/nocuda/test_import.py
@@ -0,0 +1,49 @@
+from numba.tests.support import run_in_subprocess
+import unittest
+
+
+class TestImport(unittest.TestCase):
+ def test_no_impl_import(self):
+ """
+ Tests that importing cuda doesn't trigger the import of modules
+ containing lowering implementation that would likely install things in
+ the builtins registry and have side effects impacting other targets.
+ """
+
+ banlist = (
+ 'numba.cpython.slicing',
+ 'numba.cpython.tupleobj',
+ 'numba.cpython.enumimpl',
+ 'numba.cpython.hashing',
+ 'numba.cpython.heapq',
+ 'numba.cpython.iterators',
+ 'numba.cpython.numbers',
+ 'numba.cpython.rangeobj',
+ 'numba.cpython.cmathimpl',
+ 'numba.cpython.mathimpl',
+ 'numba.cpython.printimpl',
+ 'numba.cpython.randomimpl',
+ 'numba.core.optional',
+ 'numba.misc.gdb_hook',
+ 'numba.misc.literal',
+ 'numba.misc.cffiimpl',
+ 'numba.np.linalg',
+ 'numba.np.polynomial',
+ 'numba.np.arraymath',
+ 'numba.np.npdatetime',
+ 'numba.np.npyimpl',
+ 'numba.typed.typeddict',
+ 'numba.typed.typedlist',
+ 'numba.experimental.jitclass.base',
+ )
+
+ code = "import sys; from numba import cuda; print(list(sys.modules))"
+
+ out, _ = run_in_subprocess(code)
+ modlist = set(eval(out.strip()))
+ unexpected = set(banlist) & set(modlist)
+ self.assertFalse(unexpected, "some modules unexpectedly imported")
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/nocuda/test_library_lookup.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/nocuda/test_library_lookup.py
new file mode 100644
index 0000000000000000000000000000000000000000..acf67082920c7296f2b199523ec7a1f94c4cf9a3
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/nocuda/test_library_lookup.py
@@ -0,0 +1,238 @@
+import sys
+import os
+import multiprocessing as mp
+import warnings
+
+from numba.core.config import IS_WIN32, IS_OSX
+from numba.core.errors import NumbaWarning
+from numba.cuda.cudadrv import nvvm
+from numba.cuda.testing import (
+ unittest,
+ skip_on_cudasim,
+ SerialMixin,
+ skip_unless_conda_cudatoolkit,
+)
+from numba.cuda.cuda_paths import (
+ _get_libdevice_path_decision,
+ _get_nvvm_path_decision,
+ _get_cudalib_dir_path_decision,
+ get_system_ctk,
+)
+
+
+has_cuda = nvvm.is_available()
+has_mp_get_context = hasattr(mp, 'get_context')
+
+
+class LibraryLookupBase(SerialMixin, unittest.TestCase):
+ def setUp(self):
+ ctx = mp.get_context('spawn')
+
+ qrecv = ctx.Queue()
+ qsend = ctx.Queue()
+ self.qsend = qsend
+ self.qrecv = qrecv
+ self.child_process = ctx.Process(
+ target=check_lib_lookup,
+ args=(qrecv, qsend),
+ daemon=True,
+ )
+ self.child_process.start()
+
+ def tearDown(self):
+ self.qsend.put(self.do_terminate)
+ self.child_process.join(3)
+ # Ensure the process is terminated
+ self.assertIsNotNone(self.child_process)
+
+ def remote_do(self, action):
+ self.qsend.put(action)
+ out = self.qrecv.get()
+ self.assertNotIsInstance(out, BaseException)
+ return out
+
+ @staticmethod
+ def do_terminate():
+ return False, None
+
+
+def remove_env(name):
+ try:
+ del os.environ[name]
+ except KeyError:
+ return False
+ else:
+ return True
+
+
+def check_lib_lookup(qout, qin):
+ status = True
+ while status:
+ try:
+ action = qin.get()
+ except Exception as e:
+ qout.put(e)
+ status = False
+ else:
+ try:
+ with warnings.catch_warnings(record=True) as w:
+ warnings.simplefilter("always", NumbaWarning)
+ status, result = action()
+ qout.put(result + (w,))
+ except Exception as e:
+ qout.put(e)
+ status = False
+
+
+@skip_on_cudasim('Library detection unsupported in the simulator')
+@unittest.skipUnless(has_mp_get_context, 'mp.get_context not available')
+@skip_unless_conda_cudatoolkit('test assumes conda installed cudatoolkit')
+class TestLibDeviceLookUp(LibraryLookupBase):
+ def test_libdevice_path_decision(self):
+ # Check that the default is using conda environment
+ by, info, warns = self.remote_do(self.do_clear_envs)
+ if has_cuda:
+ self.assertEqual(by, 'Conda environment')
+ else:
+ self.assertEqual(by, "")
+ self.assertIsNone(info)
+ self.assertFalse(warns)
+ # Check that CUDA_HOME works by removing conda-env
+ by, info, warns = self.remote_do(self.do_set_cuda_home)
+ self.assertEqual(by, 'CUDA_HOME')
+ self.assertEqual(info, os.path.join('mycudahome', 'nvvm', 'libdevice'))
+ self.assertFalse(warns)
+
+ if get_system_ctk() is None:
+ # Fake remove conda environment so no cudatoolkit is available
+ by, info, warns = self.remote_do(self.do_clear_envs)
+ self.assertEqual(by, '')
+ self.assertIsNone(info)
+ self.assertFalse(warns)
+ else:
+ # Use system available cudatoolkit
+ by, info, warns = self.remote_do(self.do_clear_envs)
+ self.assertEqual(by, 'System')
+ self.assertFalse(warns)
+
+ @staticmethod
+ def do_clear_envs():
+ remove_env('CUDA_HOME')
+ remove_env('CUDA_PATH')
+ return True, _get_libdevice_path_decision()
+
+ @staticmethod
+ def do_set_cuda_home():
+ os.environ['CUDA_HOME'] = os.path.join('mycudahome')
+ _fake_non_conda_env()
+ return True, _get_libdevice_path_decision()
+
+
+@skip_on_cudasim('Library detection unsupported in the simulator')
+@unittest.skipUnless(has_mp_get_context, 'mp.get_context not available')
+@skip_unless_conda_cudatoolkit('test assumes conda installed cudatoolkit')
+class TestNvvmLookUp(LibraryLookupBase):
+ def test_nvvm_path_decision(self):
+ # Check that the default is using conda environment
+ by, info, warns = self.remote_do(self.do_clear_envs)
+ if has_cuda:
+ self.assertEqual(by, 'Conda environment')
+ else:
+ self.assertEqual(by, "")
+ self.assertIsNone(info)
+ self.assertFalse(warns)
+ # Check that CUDA_HOME works by removing conda-env
+ by, info, warns = self.remote_do(self.do_set_cuda_home)
+ self.assertEqual(by, 'CUDA_HOME')
+ self.assertFalse(warns)
+ if IS_WIN32:
+ self.assertEqual(info, os.path.join('mycudahome', 'nvvm', 'bin'))
+ elif IS_OSX:
+ self.assertEqual(info, os.path.join('mycudahome', 'nvvm', 'lib'))
+ else:
+ self.assertEqual(info, os.path.join('mycudahome', 'nvvm', 'lib64'))
+
+ if get_system_ctk() is None:
+ # Fake remove conda environment so no cudatoolkit is available
+ by, info, warns = self.remote_do(self.do_clear_envs)
+ self.assertEqual(by, '')
+ self.assertIsNone(info)
+ self.assertFalse(warns)
+ else:
+ # Use system available cudatoolkit
+ by, info, warns = self.remote_do(self.do_clear_envs)
+ self.assertEqual(by, 'System')
+ self.assertFalse(warns)
+
+ @staticmethod
+ def do_clear_envs():
+ remove_env('CUDA_HOME')
+ remove_env('CUDA_PATH')
+ return True, _get_nvvm_path_decision()
+
+ @staticmethod
+ def do_set_cuda_home():
+ os.environ['CUDA_HOME'] = os.path.join('mycudahome')
+ _fake_non_conda_env()
+ return True, _get_nvvm_path_decision()
+
+
+@skip_on_cudasim('Library detection unsupported in the simulator')
+@unittest.skipUnless(has_mp_get_context, 'mp.get_context not available')
+@skip_unless_conda_cudatoolkit('test assumes conda installed cudatoolkit')
+class TestCudaLibLookUp(LibraryLookupBase):
+ def test_cudalib_path_decision(self):
+ # Check that the default is using conda environment
+ by, info, warns = self.remote_do(self.do_clear_envs)
+ if has_cuda:
+ self.assertEqual(by, 'Conda environment')
+ else:
+ self.assertEqual(by, "")
+ self.assertIsNone(info)
+ self.assertFalse(warns)
+
+ # Check that CUDA_HOME works by removing conda-env
+ self.remote_do(self.do_clear_envs)
+ by, info, warns = self.remote_do(self.do_set_cuda_home)
+ self.assertEqual(by, 'CUDA_HOME')
+ self.assertFalse(warns)
+ if IS_WIN32:
+ self.assertEqual(info, os.path.join('mycudahome', 'bin'))
+ elif IS_OSX:
+ self.assertEqual(info, os.path.join('mycudahome', 'lib'))
+ else:
+ self.assertEqual(info, os.path.join('mycudahome', 'lib64'))
+ if get_system_ctk() is None:
+ # Fake remove conda environment so no cudatoolkit is available
+ by, info, warns = self.remote_do(self.do_clear_envs)
+ self.assertEqual(by, "")
+ self.assertIsNone(info)
+ self.assertFalse(warns)
+ else:
+ # Use system available cudatoolkit
+ by, info, warns = self.remote_do(self.do_clear_envs)
+ self.assertEqual(by, 'System')
+ self.assertFalse(warns)
+
+ @staticmethod
+ def do_clear_envs():
+ remove_env('CUDA_HOME')
+ remove_env('CUDA_PATH')
+ return True, _get_cudalib_dir_path_decision()
+
+ @staticmethod
+ def do_set_cuda_home():
+ os.environ['CUDA_HOME'] = os.path.join('mycudahome')
+ _fake_non_conda_env()
+ return True, _get_cudalib_dir_path_decision()
+
+
+def _fake_non_conda_env():
+ """
+ Monkeypatch sys.prefix to hide the fact we are in a conda-env
+ """
+ sys.prefix = ''
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/nocuda/test_nvvm.py b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/nocuda/test_nvvm.py
new file mode 100644
index 0000000000000000000000000000000000000000..742aa1017115d7ee1841a33a3fea0cd32236e673
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/cuda/tests/nocuda/test_nvvm.py
@@ -0,0 +1,54 @@
+from numba.cuda.cudadrv import nvvm
+from numba.cuda.testing import skip_on_cudasim
+from numba.core import utils
+
+from llvmlite import ir
+from llvmlite import binding as llvm
+
+import unittest
+
+
+original = "call void @llvm.memset.p0i8.i64(" \
+ "i8* align 4 %arg.x.41, i8 0, i64 %0, i1 false)"
+
+missing_align = "call void @llvm.memset.p0i8.i64(" \
+ "i8* %arg.x.41, i8 0, i64 %0, i1 false)"
+
+
+@skip_on_cudasim('libNVVM not supported in simulator')
+@unittest.skipIf(utils.MACHINE_BITS == 32, "CUDA not support for 32-bit")
+@unittest.skipIf(not nvvm.is_available(), "No libNVVM")
+class TestNvvmWithoutCuda(unittest.TestCase):
+ def test_nvvm_accepts_encoding(self):
+ # Test that NVVM will accept a constant containing all possible 8-bit
+ # characters. Taken from the test case added in llvmlite PR #53:
+ #
+ # https://github.com/numba/llvmlite/pull/53
+ #
+ # This test case is included in Numba to ensure that the encoding used
+ # by llvmlite (e.g. utf-8, latin1, etc.) does not result in an input to
+ # NVVM that it cannot parse correctly
+
+ # Create a module with a constant containing all 8-bit characters
+ c = ir.Constant(ir.ArrayType(ir.IntType(8), 256),
+ bytearray(range(256)))
+ m = ir.Module()
+ m.triple = 'nvptx64-nvidia-cuda'
+ nvvm.add_ir_version(m)
+ gv = ir.GlobalVariable(m, c.type, "myconstant")
+ gv.global_constant = True
+ gv.initializer = c
+ m.data_layout = nvvm.NVVM().data_layout
+
+ # Parse with LLVM then dump the parsed module into NVVM
+ parsed = llvm.parse_assembly(str(m))
+ ptx = nvvm.compile_ir(str(parsed))
+
+ # Ensure all characters appear in the generated constant array.
+ elements = ", ".join([str(i) for i in range(256)])
+ myconstant = f"myconstant[256] = {{{elements}}}".encode('utf-8')
+ self.assertIn(myconstant, ptx)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/experimental/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/experimental/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..761c7288ef412f0acc4dcfdcb0aba6f00ea53da7
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/experimental/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/experimental/__pycache__/function_type.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/experimental/__pycache__/function_type.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0c840ef8f7174ac17f6f4d0468f31e290bcd988c
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/experimental/__pycache__/function_type.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/experimental/__pycache__/structref.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/experimental/__pycache__/structref.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e94e96f093cdf1ca6b433574c0ccfe89679dbf9b
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/experimental/__pycache__/structref.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/experimental/jitclass/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/numba/experimental/jitclass/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..981282f65363062d39b7dee91a6072b541404f11
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/experimental/jitclass/__init__.py
@@ -0,0 +1,3 @@
+from numba.experimental.jitclass.decorators import jitclass
+from numba.experimental.jitclass import boxing # Has import-time side effect
+from numba.experimental.jitclass import overloads # Has import-time side effect
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/experimental/jitclass/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/experimental/jitclass/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e1c3dcad1880e91da18004b5c46406acf1080678
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/experimental/jitclass/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/experimental/jitclass/__pycache__/base.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/experimental/jitclass/__pycache__/base.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c209b670808ddd4a9f69b8e54fc88676e0af72d3
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/experimental/jitclass/__pycache__/base.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/experimental/jitclass/__pycache__/boxing.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/experimental/jitclass/__pycache__/boxing.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..44575ff8f3701d9111c8a919c04604a47efbf060
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/experimental/jitclass/__pycache__/boxing.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/experimental/jitclass/__pycache__/decorators.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/experimental/jitclass/__pycache__/decorators.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d44cdc0fea837208a4e86aa09e865f1d085d453d
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/experimental/jitclass/__pycache__/decorators.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/experimental/jitclass/__pycache__/overloads.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/experimental/jitclass/__pycache__/overloads.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..044de0e6a3c588b94d9f306a388d53c50511a265
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/experimental/jitclass/__pycache__/overloads.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/experimental/jitclass/_box.cpython-312-x86_64-linux-gnu.so b/tool_server/.venv/lib/python3.12/site-packages/numba/experimental/jitclass/_box.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..381ea3e6f3a5890783e56fddce67748ab7a183bc
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/experimental/jitclass/_box.cpython-312-x86_64-linux-gnu.so differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/experimental/jitclass/base.py b/tool_server/.venv/lib/python3.12/site-packages/numba/experimental/jitclass/base.py
new file mode 100644
index 0000000000000000000000000000000000000000..6103308f1e0c77199945f7bda5eb0e298cf4a56d
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/experimental/jitclass/base.py
@@ -0,0 +1,595 @@
+import inspect
+import operator
+import types as pytypes
+import typing as pt
+from collections import OrderedDict
+from collections.abc import Sequence
+
+from llvmlite import ir as llvmir
+from numba import njit
+from numba.core import cgutils, errors, imputils, types, utils
+from numba.core.datamodel import default_manager, models
+from numba.core.registry import cpu_target
+from numba.core.typing import templates
+from numba.core.typing.asnumbatype import as_numba_type
+from numba.core.serialize import disable_pickling
+from numba.experimental.jitclass import _box
+
+##############################################################################
+# Data model
+
+
+class InstanceModel(models.StructModel):
+ def __init__(self, dmm, fe_typ):
+ cls_data_ty = types.ClassDataType(fe_typ)
+ # MemInfoPointer uses the `dtype` attribute to traverse for nested
+ # NRT MemInfo. Since we handle nested NRT MemInfo ourselves,
+ # we will replace provide MemInfoPointer with an opaque type
+ # so that it does not raise exception for nested meminfo.
+ dtype = types.Opaque('Opaque.' + str(cls_data_ty))
+ members = [
+ ('meminfo', types.MemInfoPointer(dtype)),
+ ('data', types.CPointer(cls_data_ty)),
+ ]
+ super(InstanceModel, self).__init__(dmm, fe_typ, members)
+
+
+class InstanceDataModel(models.StructModel):
+ def __init__(self, dmm, fe_typ):
+ clsty = fe_typ.class_type
+ members = [(_mangle_attr(k), v) for k, v in clsty.struct.items()]
+ super(InstanceDataModel, self).__init__(dmm, fe_typ, members)
+
+
+default_manager.register(types.ClassInstanceType, InstanceModel)
+default_manager.register(types.ClassDataType, InstanceDataModel)
+default_manager.register(types.ClassType, models.OpaqueModel)
+
+
+def _mangle_attr(name):
+ """
+ Mangle attributes.
+ The resulting name does not startswith an underscore '_'.
+ """
+ return 'm_' + name
+
+
+##############################################################################
+# Class object
+
+_ctor_template = """
+def ctor({args}):
+ return __numba_cls_({args})
+"""
+
+
+def _getargs(fn_sig):
+ """
+ Returns list of positional and keyword argument names in order.
+ """
+ params = fn_sig.parameters
+ args = []
+ for k, v in params.items():
+ if (v.kind & v.POSITIONAL_OR_KEYWORD) == v.POSITIONAL_OR_KEYWORD:
+ args.append(k)
+ else:
+ msg = "%s argument type unsupported in jitclass" % v.kind
+ raise errors.UnsupportedError(msg)
+ return args
+
+
+@disable_pickling
+class JitClassType(type):
+ """
+ The type of any jitclass.
+ """
+ def __new__(cls, name, bases, dct):
+ if len(bases) != 1:
+ raise TypeError("must have exactly one base class")
+ [base] = bases
+ if isinstance(base, JitClassType):
+ raise TypeError("cannot subclass from a jitclass")
+ assert 'class_type' in dct, 'missing "class_type" attr'
+ outcls = type.__new__(cls, name, bases, dct)
+ outcls._set_init()
+ return outcls
+
+ def _set_init(cls):
+ """
+ Generate a wrapper for calling the constructor from pure Python.
+ Note the wrapper will only accept positional arguments.
+ """
+ init = cls.class_type.instance_type.methods['__init__']
+ init_sig = utils.pysignature(init)
+ # get postitional and keyword arguments
+ # offset by one to exclude the `self` arg
+ args = _getargs(init_sig)[1:]
+ cls._ctor_sig = init_sig
+ ctor_source = _ctor_template.format(args=', '.join(args))
+ glbls = {"__numba_cls_": cls}
+ exec(ctor_source, glbls)
+ ctor = glbls['ctor']
+ cls._ctor = njit(ctor)
+
+ def __instancecheck__(cls, instance):
+ if isinstance(instance, _box.Box):
+ return instance._numba_type_.class_type is cls.class_type
+ return False
+
+ def __call__(cls, *args, **kwargs):
+ # The first argument of _ctor_sig is `cls`, which here
+ # is bound to None and then skipped when invoking the constructor.
+ bind = cls._ctor_sig.bind(None, *args, **kwargs)
+ bind.apply_defaults()
+ return cls._ctor(*bind.args[1:], **bind.kwargs)
+
+
+##############################################################################
+# Registration utils
+
+def _validate_spec(spec):
+ for k, v in spec.items():
+ if not isinstance(k, str):
+ raise TypeError("spec keys should be strings, got %r" % (k,))
+ if not isinstance(v, types.Type):
+ raise TypeError("spec values should be Numba type instances, got %r"
+ % (v,))
+
+
+def _fix_up_private_attr(clsname, spec):
+ """
+ Apply the same changes to dunder names as CPython would.
+ """
+ out = OrderedDict()
+ for k, v in spec.items():
+ if k.startswith('__') and not k.endswith('__'):
+ k = '_' + clsname + k
+ out[k] = v
+ return out
+
+
+def _add_linking_libs(context, call):
+ """
+ Add the required libs for the callable to allow inlining.
+ """
+ libs = getattr(call, "libs", ())
+ if libs:
+ context.add_linking_libs(libs)
+
+
+def register_class_type(cls, spec, class_ctor, builder):
+ """
+ Internal function to create a jitclass.
+
+ Args
+ ----
+ cls: the original class object (used as the prototype)
+ spec: the structural specification contains the field types.
+ class_ctor: the numba type to represent the jitclass
+ builder: the internal jitclass builder
+ """
+ # Normalize spec
+ if spec is None:
+ spec = OrderedDict()
+ elif isinstance(spec, Sequence):
+ spec = OrderedDict(spec)
+
+ # Extend spec with class annotations.
+ for attr, py_type in pt.get_type_hints(cls).items():
+ if attr not in spec:
+ spec[attr] = as_numba_type(py_type)
+
+ _validate_spec(spec)
+
+ # Fix up private attribute names
+ spec = _fix_up_private_attr(cls.__name__, spec)
+
+ # Copy methods from base classes
+ clsdct = {}
+ for basecls in reversed(inspect.getmro(cls)):
+ clsdct.update(basecls.__dict__)
+
+ methods, props, static_methods, others = {}, {}, {}, {}
+ for k, v in clsdct.items():
+ if isinstance(v, pytypes.FunctionType):
+ methods[k] = v
+ elif isinstance(v, property):
+ props[k] = v
+ elif isinstance(v, staticmethod):
+ static_methods[k] = v
+ else:
+ others[k] = v
+
+ # Check for name shadowing
+ shadowed = (set(methods) | set(props) | set(static_methods)) & set(spec)
+ if shadowed:
+ raise NameError("name shadowing: {0}".format(', '.join(shadowed)))
+
+ docstring = others.pop('__doc__', "")
+ _drop_ignored_attrs(others)
+ if others:
+ msg = "class members are not yet supported: {0}"
+ members = ', '.join(others.keys())
+ raise TypeError(msg.format(members))
+
+ for k, v in props.items():
+ if v.fdel is not None:
+ raise TypeError("deleter is not supported: {0}".format(k))
+
+ jit_methods = {k: njit(v) for k, v in methods.items()}
+
+ jit_props = {}
+ for k, v in props.items():
+ dct = {}
+ if v.fget:
+ dct['get'] = njit(v.fget)
+ if v.fset:
+ dct['set'] = njit(v.fset)
+ jit_props[k] = dct
+
+ jit_static_methods = {
+ k: njit(v.__func__) for k, v in static_methods.items()}
+
+ # Instantiate class type
+ class_type = class_ctor(
+ cls,
+ ConstructorTemplate,
+ spec,
+ jit_methods,
+ jit_props,
+ jit_static_methods)
+
+ jit_class_dct = dict(class_type=class_type, __doc__=docstring)
+ jit_class_dct.update(jit_static_methods)
+ cls = JitClassType(cls.__name__, (cls,), jit_class_dct)
+
+ # Register resolution of the class object
+ typingctx = cpu_target.typing_context
+ typingctx.insert_global(cls, class_type)
+
+ # Register class
+ targetctx = cpu_target.target_context
+ builder(class_type, typingctx, targetctx).register()
+ as_numba_type.register(cls, class_type.instance_type)
+
+ return cls
+
+
+class ConstructorTemplate(templates.AbstractTemplate):
+ """
+ Base class for jitclass constructor templates.
+ """
+
+ def generic(self, args, kws):
+ # Redirect resolution to __init__
+ instance_type = self.key.instance_type
+ ctor = instance_type.jit_methods['__init__']
+ boundargs = (instance_type.get_reference_type(),) + args
+ disp_type = types.Dispatcher(ctor)
+ sig = disp_type.get_call_type(self.context, boundargs, kws)
+
+ if not isinstance(sig.return_type, types.NoneType):
+ raise errors.NumbaTypeError(
+ f"__init__() should return None, not '{sig.return_type}'")
+
+ # Actual constructor returns an instance value (not None)
+ out = templates.signature(instance_type, *sig.args[1:])
+ return out
+
+
+def _drop_ignored_attrs(dct):
+ # ignore anything defined by object
+ drop = set(['__weakref__',
+ '__module__',
+ '__dict__'])
+ if utils.PYVERSION == (3, 13):
+ # new in python 3.13
+ drop |= set(['__firstlineno__', '__static_attributes__'])
+
+ if '__annotations__' in dct:
+ drop.add('__annotations__')
+
+ for k, v in dct.items():
+ if isinstance(v, (pytypes.BuiltinFunctionType,
+ pytypes.BuiltinMethodType)):
+ drop.add(k)
+ elif getattr(v, '__objclass__', None) is object:
+ drop.add(k)
+
+ # If a class defines __eq__ but not __hash__, __hash__ is implicitly set to
+ # None. This is a class member, and class members are not presently
+ # supported.
+ if '__hash__' in dct and dct['__hash__'] is None:
+ drop.add('__hash__')
+
+ for k in drop:
+ dct.pop(k)
+
+
+class ClassBuilder(object):
+ """
+ A jitclass builder for a mutable jitclass. This will register
+ typing and implementation hooks to the given typing and target contexts.
+ """
+ class_impl_registry = imputils.Registry('jitclass builder')
+ implemented_methods = set()
+
+ def __init__(self, class_type, typingctx, targetctx):
+ self.class_type = class_type
+ self.typingctx = typingctx
+ self.targetctx = targetctx
+
+ def register(self):
+ """
+ Register to the frontend and backend.
+ """
+ # Register generic implementations for all jitclasses
+ self._register_methods(self.class_impl_registry,
+ self.class_type.instance_type)
+ # NOTE other registrations are done at the top-level
+ # (see ctor_impl and attr_impl below)
+ self.targetctx.install_registry(self.class_impl_registry)
+
+ def _register_methods(self, registry, instance_type):
+ """
+ Register method implementations.
+ This simply registers that the method names are valid methods. Inside
+ of imp() below we retrieve the actual method to run from the type of
+ the receiver argument (i.e. self).
+ """
+ to_register = list(instance_type.jit_methods) + \
+ list(instance_type.jit_static_methods)
+ for meth in to_register:
+
+ # There's no way to retrieve the particular method name
+ # inside the implementation function, so we have to register a
+ # specific closure for each different name
+ if meth not in self.implemented_methods:
+ self._implement_method(registry, meth)
+ self.implemented_methods.add(meth)
+
+ def _implement_method(self, registry, attr):
+ # create a separate instance of imp method to avoid closure clashing
+ def get_imp():
+ def imp(context, builder, sig, args):
+ instance_type = sig.args[0]
+
+ if attr in instance_type.jit_methods:
+ method = instance_type.jit_methods[attr]
+ elif attr in instance_type.jit_static_methods:
+ method = instance_type.jit_static_methods[attr]
+ # imp gets called as a method, where the first argument is
+ # self. We drop this for a static method.
+ sig = sig.replace(args=sig.args[1:])
+ args = args[1:]
+
+ disp_type = types.Dispatcher(method)
+ call = context.get_function(disp_type, sig)
+ out = call(builder, args)
+ _add_linking_libs(context, call)
+ return imputils.impl_ret_new_ref(context, builder,
+ sig.return_type, out)
+ return imp
+
+ def _getsetitem_gen(getset):
+ _dunder_meth = "__%s__" % getset
+ op = getattr(operator, getset)
+
+ @templates.infer_global(op)
+ class GetSetItem(templates.AbstractTemplate):
+ def generic(self, args, kws):
+ instance = args[0]
+ if isinstance(instance, types.ClassInstanceType) and \
+ _dunder_meth in instance.jit_methods:
+ meth = instance.jit_methods[_dunder_meth]
+ disp_type = types.Dispatcher(meth)
+ sig = disp_type.get_call_type(self.context, args, kws)
+ return sig
+
+ # lower both {g,s}etitem and __{g,s}etitem__ to catch the calls
+ # from python and numba
+ imputils.lower_builtin((types.ClassInstanceType, _dunder_meth),
+ types.ClassInstanceType,
+ types.VarArg(types.Any))(get_imp())
+ imputils.lower_builtin(op,
+ types.ClassInstanceType,
+ types.VarArg(types.Any))(get_imp())
+
+ dunder_stripped = attr.strip('_')
+ if dunder_stripped in ("getitem", "setitem"):
+ _getsetitem_gen(dunder_stripped)
+ else:
+ registry.lower((types.ClassInstanceType, attr),
+ types.ClassInstanceType,
+ types.VarArg(types.Any))(get_imp())
+
+
+@templates.infer_getattr
+class ClassAttribute(templates.AttributeTemplate):
+ key = types.ClassInstanceType
+
+ def generic_resolve(self, instance, attr):
+ if attr in instance.struct:
+ # It's a struct field => the type is well-known
+ return instance.struct[attr]
+
+ elif attr in instance.jit_methods:
+ # It's a jitted method => typeinfer it
+ meth = instance.jit_methods[attr]
+ disp_type = types.Dispatcher(meth)
+
+ class MethodTemplate(templates.AbstractTemplate):
+ key = (self.key, attr)
+
+ def generic(self, args, kws):
+ args = (instance,) + tuple(args)
+ sig = disp_type.get_call_type(self.context, args, kws)
+ return sig.as_method()
+
+ return types.BoundFunction(MethodTemplate, instance)
+
+ elif attr in instance.jit_static_methods:
+ # It's a jitted method => typeinfer it
+ meth = instance.jit_static_methods[attr]
+ disp_type = types.Dispatcher(meth)
+
+ class StaticMethodTemplate(templates.AbstractTemplate):
+ key = (self.key, attr)
+
+ def generic(self, args, kws):
+ # Don't add instance as the first argument for a static
+ # method.
+ sig = disp_type.get_call_type(self.context, args, kws)
+ # sig itself does not include ClassInstanceType as it's
+ # first argument, so instead of calling sig.as_method()
+ # we insert the recvr. This is equivalent to
+ # sig.replace(args=(instance,) + sig.args).as_method().
+ return sig.replace(recvr=instance)
+
+ return types.BoundFunction(StaticMethodTemplate, instance)
+
+ elif attr in instance.jit_props:
+ # It's a jitted property => typeinfer its getter
+ impdct = instance.jit_props[attr]
+ getter = impdct['get']
+ disp_type = types.Dispatcher(getter)
+ sig = disp_type.get_call_type(self.context, (instance,), {})
+ return sig.return_type
+
+
+@ClassBuilder.class_impl_registry.lower_getattr_generic(types.ClassInstanceType)
+def get_attr_impl(context, builder, typ, value, attr):
+ """
+ Generic getattr() for @jitclass instances.
+ """
+ if attr in typ.struct:
+ # It's a struct field
+ inst = context.make_helper(builder, typ, value=value)
+ data_pointer = inst.data
+ data = context.make_data_helper(builder, typ.get_data_type(),
+ ref=data_pointer)
+ return imputils.impl_ret_borrowed(context, builder,
+ typ.struct[attr],
+ getattr(data, _mangle_attr(attr)))
+ elif attr in typ.jit_props:
+ # It's a jitted property
+ getter = typ.jit_props[attr]['get']
+ sig = templates.signature(None, typ)
+ dispatcher = types.Dispatcher(getter)
+ sig = dispatcher.get_call_type(context.typing_context, [typ], {})
+ call = context.get_function(dispatcher, sig)
+ out = call(builder, [value])
+ _add_linking_libs(context, call)
+ return imputils.impl_ret_new_ref(context, builder, sig.return_type, out)
+
+ raise NotImplementedError('attribute {0!r} not implemented'.format(attr))
+
+
+@ClassBuilder.class_impl_registry.lower_setattr_generic(types.ClassInstanceType)
+def set_attr_impl(context, builder, sig, args, attr):
+ """
+ Generic setattr() for @jitclass instances.
+ """
+ typ, valty = sig.args
+ target, val = args
+
+ if attr in typ.struct:
+ # It's a struct member
+ inst = context.make_helper(builder, typ, value=target)
+ data_ptr = inst.data
+ data = context.make_data_helper(builder, typ.get_data_type(),
+ ref=data_ptr)
+
+ # Get old value
+ attr_type = typ.struct[attr]
+ oldvalue = getattr(data, _mangle_attr(attr))
+
+ # Store n
+ setattr(data, _mangle_attr(attr), val)
+ context.nrt.incref(builder, attr_type, val)
+
+ # Delete old value
+ context.nrt.decref(builder, attr_type, oldvalue)
+
+ elif attr in typ.jit_props:
+ # It's a jitted property
+ setter = typ.jit_props[attr]['set']
+ disp_type = types.Dispatcher(setter)
+ sig = disp_type.get_call_type(context.typing_context,
+ (typ, valty), {})
+ call = context.get_function(disp_type, sig)
+ call(builder, (target, val))
+ _add_linking_libs(context, call)
+ else:
+ raise NotImplementedError(
+ 'attribute {0!r} not implemented'.format(attr))
+
+
+def imp_dtor(context, module, instance_type):
+ llvoidptr = context.get_value_type(types.voidptr)
+ llsize = context.get_value_type(types.uintp)
+ dtor_ftype = llvmir.FunctionType(llvmir.VoidType(),
+ [llvoidptr, llsize, llvoidptr])
+
+ fname = "_Dtor.{0}".format(instance_type.name)
+ dtor_fn = cgutils.get_or_insert_function(module, dtor_ftype, fname)
+ if dtor_fn.is_declaration:
+ # Define
+ builder = llvmir.IRBuilder(dtor_fn.append_basic_block())
+
+ alloc_fe_type = instance_type.get_data_type()
+ alloc_type = context.get_value_type(alloc_fe_type)
+
+ ptr = builder.bitcast(dtor_fn.args[0], alloc_type.as_pointer())
+ data = context.make_helper(builder, alloc_fe_type, ref=ptr)
+
+ context.nrt.decref(builder, alloc_fe_type, data._getvalue())
+
+ builder.ret_void()
+
+ return dtor_fn
+
+
+@ClassBuilder.class_impl_registry.lower(types.ClassType,
+ types.VarArg(types.Any))
+def ctor_impl(context, builder, sig, args):
+ """
+ Generic constructor (__new__) for jitclasses.
+ """
+ # Allocate the instance
+ inst_typ = sig.return_type
+ alloc_type = context.get_data_type(inst_typ.get_data_type())
+ alloc_size = context.get_abi_sizeof(alloc_type)
+
+ meminfo = context.nrt.meminfo_alloc_dtor(
+ builder,
+ context.get_constant(types.uintp, alloc_size),
+ imp_dtor(context, builder.module, inst_typ),
+ )
+ data_pointer = context.nrt.meminfo_data(builder, meminfo)
+ data_pointer = builder.bitcast(data_pointer,
+ alloc_type.as_pointer())
+
+ # Nullify all data
+ builder.store(cgutils.get_null_value(alloc_type),
+ data_pointer)
+
+ inst_struct = context.make_helper(builder, inst_typ)
+ inst_struct.meminfo = meminfo
+ inst_struct.data = data_pointer
+
+ # Call the jitted __init__
+ # TODO: extract the following into a common util
+ init_sig = (sig.return_type,) + sig.args
+
+ init = inst_typ.jit_methods['__init__']
+ disp_type = types.Dispatcher(init)
+ call = context.get_function(disp_type, types.void(*init_sig))
+ _add_linking_libs(context, call)
+ realargs = [inst_struct._getvalue()] + list(args)
+ call(builder, realargs)
+
+ # Prepare return value
+ ret = inst_struct._getvalue()
+
+ return imputils.impl_ret_new_ref(context, builder, inst_typ, ret)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/experimental/jitclass/boxing.py b/tool_server/.venv/lib/python3.12/site-packages/numba/experimental/jitclass/boxing.py
new file mode 100644
index 0000000000000000000000000000000000000000..95fcaadd43d4b024e58bf9e353f5fcf91a5dbce9
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/experimental/jitclass/boxing.py
@@ -0,0 +1,273 @@
+"""
+Implement logic relating to wrapping (box) and unwrapping (unbox) instances
+of jitclasses for use inside the python interpreter.
+"""
+
+from functools import wraps, partial
+
+from llvmlite import ir
+
+from numba.core import types, cgutils
+from numba.core.decorators import njit
+from numba.core.pythonapi import box, unbox, NativeValue
+from numba.core.typing.typeof import typeof_impl
+from numba.experimental.jitclass import _box
+
+
+_getter_code_template = """
+def accessor(__numba_self_):
+ return __numba_self_.{0}
+"""
+
+_setter_code_template = """
+def mutator(__numba_self_, __numba_val):
+ __numba_self_.{0} = __numba_val
+"""
+
+_method_code_template = """
+def method(__numba_self_, *args):
+ return __numba_self_.{method}(*args)
+"""
+
+
+def _generate_property(field, template, fname):
+ """
+ Generate simple function that get/set a field of the instance
+ """
+ source = template.format(field)
+ glbls = {}
+ exec(source, glbls)
+ return njit(glbls[fname])
+
+
+_generate_getter = partial(_generate_property, template=_getter_code_template,
+ fname='accessor')
+_generate_setter = partial(_generate_property, template=_setter_code_template,
+ fname='mutator')
+
+
+def _generate_method(name, func):
+ """
+ Generate a wrapper for calling a method. Note the wrapper will only
+ accept positional arguments.
+ """
+ source = _method_code_template.format(method=name)
+ glbls = {}
+ exec(source, glbls)
+ method = njit(glbls['method'])
+
+ @wraps(func)
+ def wrapper(*args, **kwargs):
+ return method(*args, **kwargs)
+
+ return wrapper
+
+
+_cache_specialized_box = {}
+
+
+def _specialize_box(typ):
+ """
+ Create a subclass of Box that is specialized to the jitclass.
+
+ This function caches the result to avoid code bloat.
+ """
+ # Check cache
+ if typ in _cache_specialized_box:
+ return _cache_specialized_box[typ]
+ dct = {'__slots__': (),
+ '_numba_type_': typ,
+ '__doc__': typ.class_type.class_doc,
+ }
+ # Inject attributes as class properties
+ for field in typ.struct:
+ getter = _generate_getter(field)
+ setter = _generate_setter(field)
+ dct[field] = property(getter, setter)
+ # Inject properties as class properties
+ for field, impdct in typ.jit_props.items():
+ getter = None
+ setter = None
+ if 'get' in impdct:
+ getter = _generate_getter(field)
+ if 'set' in impdct:
+ setter = _generate_setter(field)
+ # get docstring from either the fget or fset
+ imp = impdct.get('get') or impdct.get('set') or None
+ doc = getattr(imp, '__doc__', None)
+ dct[field] = property(getter, setter, doc=doc)
+ # Inject methods as class members
+ supported_dunders = {
+ "__abs__",
+ "__bool__",
+ "__complex__",
+ "__contains__",
+ "__float__",
+ "__getitem__",
+ "__hash__",
+ "__index__",
+ "__int__",
+ "__len__",
+ "__setitem__",
+ "__str__",
+ "__eq__",
+ "__ne__",
+ "__ge__",
+ "__gt__",
+ "__le__",
+ "__lt__",
+ "__add__",
+ "__floordiv__",
+ "__lshift__",
+ "__matmul__",
+ "__mod__",
+ "__mul__",
+ "__neg__",
+ "__pos__",
+ "__pow__",
+ "__rshift__",
+ "__sub__",
+ "__truediv__",
+ "__and__",
+ "__or__",
+ "__xor__",
+ "__iadd__",
+ "__ifloordiv__",
+ "__ilshift__",
+ "__imatmul__",
+ "__imod__",
+ "__imul__",
+ "__ipow__",
+ "__irshift__",
+ "__isub__",
+ "__itruediv__",
+ "__iand__",
+ "__ior__",
+ "__ixor__",
+ "__radd__",
+ "__rfloordiv__",
+ "__rlshift__",
+ "__rmatmul__",
+ "__rmod__",
+ "__rmul__",
+ "__rpow__",
+ "__rrshift__",
+ "__rsub__",
+ "__rtruediv__",
+ "__rand__",
+ "__ror__",
+ "__rxor__",
+ }
+ for name, func in typ.methods.items():
+ if name == "__init__":
+ continue
+ if (
+ name.startswith("__")
+ and name.endswith("__")
+ and name not in supported_dunders
+ ):
+ raise TypeError(f"Method '{name}' is not supported.")
+ dct[name] = _generate_method(name, func)
+
+ # Inject static methods as class members
+ for name, func in typ.static_methods.items():
+ dct[name] = _generate_method(name, func)
+
+ # Create subclass
+ subcls = type(typ.classname, (_box.Box,), dct)
+ # Store to cache
+ _cache_specialized_box[typ] = subcls
+
+ # Pre-compile attribute getter.
+ # Note: This must be done after the "box" class is created because
+ # compiling the getter requires the "box" class to be defined.
+ for k, v in dct.items():
+ if isinstance(v, property):
+ prop = getattr(subcls, k)
+ if prop.fget is not None:
+ fget = prop.fget
+ fast_fget = fget.compile((typ,))
+ fget.disable_compile()
+ setattr(subcls, k,
+ property(fast_fget, prop.fset, prop.fdel,
+ doc=prop.__doc__))
+
+ return subcls
+
+
+###############################################################################
+# Implement box/unbox for call wrapper
+
+@box(types.ClassInstanceType)
+def _box_class_instance(typ, val, c):
+ meminfo, dataptr = cgutils.unpack_tuple(c.builder, val)
+
+ # Create Box instance
+ box_subclassed = _specialize_box(typ)
+ # Note: the ``box_subclassed`` is kept alive by the cache
+ voidptr_boxcls = c.context.add_dynamic_addr(
+ c.builder,
+ id(box_subclassed),
+ info="box_class_instance",
+ )
+ box_cls = c.builder.bitcast(voidptr_boxcls, c.pyapi.pyobj)
+
+ box = c.pyapi.call_function_objargs(box_cls, ())
+
+ # Initialize Box instance
+ llvoidptr = ir.IntType(8).as_pointer()
+ addr_meminfo = c.builder.bitcast(meminfo, llvoidptr)
+ addr_data = c.builder.bitcast(dataptr, llvoidptr)
+
+ def set_member(member_offset, value):
+ # Access member by byte offset
+ offset = c.context.get_constant(types.uintp, member_offset)
+ ptr = cgutils.pointer_add(c.builder, box, offset)
+ casted = c.builder.bitcast(ptr, llvoidptr.as_pointer())
+ c.builder.store(value, casted)
+
+ set_member(_box.box_meminfoptr_offset, addr_meminfo)
+ set_member(_box.box_dataptr_offset, addr_data)
+ return box
+
+
+@unbox(types.ClassInstanceType)
+def _unbox_class_instance(typ, val, c):
+ def access_member(member_offset):
+ # Access member by byte offset
+ offset = c.context.get_constant(types.uintp, member_offset)
+ llvoidptr = ir.IntType(8).as_pointer()
+ ptr = cgutils.pointer_add(c.builder, val, offset)
+ casted = c.builder.bitcast(ptr, llvoidptr.as_pointer())
+ return c.builder.load(casted)
+
+ struct_cls = cgutils.create_struct_proxy(typ)
+ inst = struct_cls(c.context, c.builder)
+
+ # load from Python object
+ ptr_meminfo = access_member(_box.box_meminfoptr_offset)
+ ptr_dataptr = access_member(_box.box_dataptr_offset)
+
+ # store to native structure
+ inst.meminfo = c.builder.bitcast(ptr_meminfo, inst.meminfo.type)
+ inst.data = c.builder.bitcast(ptr_dataptr, inst.data.type)
+
+ ret = inst._getvalue()
+
+ c.context.nrt.incref(c.builder, typ, ret)
+
+ return NativeValue(ret, is_error=c.pyapi.c_api_error())
+
+
+# Add a typeof_impl implementation for boxed jitclasses to short-circut the
+# various tests in typeof. This is needed for jitclasses which implement a
+# custom hash method. Without this, typeof_impl will return None, and one of the
+# later attempts to determine the type of the jitclass (before checking for
+# _numba_type_) will look up the object in a dictionary, triggering the hash
+# method. This will cause the dispatcher to determine the call signature of the
+# jit decorated obj.__hash__ method, which will call typeof(obj), and thus
+# infinite loop.
+# This implementation is here instead of in typeof.py to avoid circular imports.
+@typeof_impl.register(_box.Box)
+def _typeof_jitclass_box(val, c):
+ return getattr(type(val), "_numba_type_")
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/experimental/jitclass/decorators.py b/tool_server/.venv/lib/python3.12/site-packages/numba/experimental/jitclass/decorators.py
new file mode 100644
index 0000000000000000000000000000000000000000..ecdae7d35d292bc4d55ea27d69012ed8f9ae6d7b
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/experimental/jitclass/decorators.py
@@ -0,0 +1,88 @@
+from numba.core import types, config
+
+
+def jitclass(cls_or_spec=None, spec=None):
+ """
+ A function for creating a jitclass.
+ Can be used as a decorator or function.
+
+ Different use cases will cause different arguments to be set.
+
+ If specified, ``spec`` gives the types of class fields.
+ It must be a dictionary or sequence.
+ With a dictionary, use collections.OrderedDict for stable ordering.
+ With a sequence, it must contain 2-tuples of (fieldname, fieldtype).
+
+ Any class annotations for field names not listed in spec will be added.
+ For class annotation `x: T` we will append ``("x", as_numba_type(T))`` to
+ the spec if ``x`` is not already a key in spec.
+
+
+ Examples
+ --------
+
+ 1) ``cls_or_spec = None``, ``spec = None``
+
+ >>> @jitclass()
+ ... class Foo:
+ ... ...
+
+ 2) ``cls_or_spec = None``, ``spec = spec``
+
+ >>> @jitclass(spec=spec)
+ ... class Foo:
+ ... ...
+
+ 3) ``cls_or_spec = Foo``, ``spec = None``
+
+ >>> @jitclass
+ ... class Foo:
+ ... ...
+
+ 4) ``cls_or_spec = spec``, ``spec = None``
+ In this case we update ``cls_or_spec, spec = None, cls_or_spec``.
+
+ >>> @jitclass(spec)
+ ... class Foo:
+ ... ...
+
+ 5) ``cls_or_spec = Foo``, ``spec = spec``
+
+ >>> JitFoo = jitclass(Foo, spec)
+
+ Returns
+ -------
+ If used as a decorator, returns a callable that takes a class object and
+ returns a compiled version.
+ If used as a function, returns the compiled class (an instance of
+ ``JitClassType``).
+ """
+
+ if (cls_or_spec is not None and
+ spec is None and
+ not isinstance(cls_or_spec, type)):
+ # Used like
+ # @jitclass([("x", intp)])
+ # class Foo:
+ # ...
+ spec = cls_or_spec
+ cls_or_spec = None
+
+ def wrap(cls):
+ if config.DISABLE_JIT:
+ return cls
+ else:
+ from numba.experimental.jitclass.base import (register_class_type,
+ ClassBuilder)
+ cls_jitted = register_class_type(cls, spec, types.ClassType,
+ ClassBuilder)
+
+ # Preserve the module name of the original class
+ cls_jitted.__module__ = cls.__module__
+
+ return cls_jitted
+
+ if cls_or_spec is None:
+ return wrap
+ else:
+ return wrap(cls_or_spec)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/experimental/jitclass/overloads.py b/tool_server/.venv/lib/python3.12/site-packages/numba/experimental/jitclass/overloads.py
new file mode 100644
index 0000000000000000000000000000000000000000..f120b40cd8a25705b4242b6eb16323b06816b3e8
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/experimental/jitclass/overloads.py
@@ -0,0 +1,238 @@
+"""
+Overloads for ClassInstanceType for built-in functions that call dunder methods
+on an object.
+"""
+from functools import wraps
+import inspect
+import operator
+
+from numba.core.extending import overload
+from numba.core.types import ClassInstanceType
+
+
+def _get_args(n_args):
+ assert n_args in (1, 2)
+ return list("xy")[:n_args]
+
+
+def class_instance_overload(target):
+ """
+ Decorator to add an overload for target that applies when the first argument
+ is a ClassInstanceType.
+ """
+ def decorator(func):
+ @wraps(func)
+ def wrapped(*args, **kwargs):
+ if not isinstance(args[0], ClassInstanceType):
+ return
+ return func(*args, **kwargs)
+
+ if target is not complex:
+ # complex ctor needs special treatment as it uses kwargs
+ params = list(inspect.signature(wrapped).parameters)
+ assert params == _get_args(len(params))
+ return overload(target)(wrapped)
+
+ return decorator
+
+
+def extract_template(template, name):
+ """
+ Extract a code-generated function from a string template.
+ """
+ namespace = {}
+ exec(template, namespace)
+ return namespace[name]
+
+
+def register_simple_overload(func, *attrs, n_args=1,):
+ """
+ Register an overload for func that checks for methods __attr__ for each
+ attr in attrs.
+ """
+ # Use a template to set the signature correctly.
+ arg_names = _get_args(n_args)
+ template = f"""
+def func({','.join(arg_names)}):
+ pass
+"""
+
+ @wraps(extract_template(template, "func"))
+ def overload_func(*args, **kwargs):
+ options = [
+ try_call_method(args[0], f"__{attr}__", n_args)
+ for attr in attrs
+ ]
+ return take_first(*options)
+
+ return class_instance_overload(func)(overload_func)
+
+
+def try_call_method(cls_type, method, n_args=1):
+ """
+ If method is defined for cls_type, return a callable that calls this method.
+ If not, return None.
+ """
+ if method in cls_type.jit_methods:
+ arg_names = _get_args(n_args)
+ template = f"""
+def func({','.join(arg_names)}):
+ return {arg_names[0]}.{method}({','.join(arg_names[1:])})
+"""
+ return extract_template(template, "func")
+
+
+def try_call_complex_method(cls_type, method):
+ """ __complex__ needs special treatment as the argument names are kwargs
+ and therefore specific in name and default value.
+ """
+ if method in cls_type.jit_methods:
+ template = f"""
+def func(real=0, imag=0):
+ return real.{method}()
+"""
+ return extract_template(template, "func")
+
+
+def take_first(*options):
+ """
+ Take the first non-None option.
+ """
+ assert all(o is None or inspect.isfunction(o) for o in options), options
+ for o in options:
+ if o is not None:
+ return o
+
+
+@class_instance_overload(bool)
+def class_bool(x):
+ using_bool_impl = try_call_method(x, "__bool__")
+
+ if '__len__' in x.jit_methods:
+ def using_len_impl(x):
+ return bool(len(x))
+ else:
+ using_len_impl = None
+
+ always_true_impl = lambda x: True
+
+ return take_first(using_bool_impl, using_len_impl, always_true_impl)
+
+
+@class_instance_overload(complex)
+def class_complex(real=0, imag=0):
+ return take_first(
+ try_call_complex_method(real, "__complex__"),
+ lambda real=0, imag=0: complex(float(real))
+ )
+
+
+@class_instance_overload(operator.contains)
+def class_contains(x, y):
+ # https://docs.python.org/3/reference/expressions.html#membership-test-operations
+ return try_call_method(x, "__contains__", 2)
+ # TODO: use __iter__ if defined.
+
+
+@class_instance_overload(float)
+def class_float(x):
+ options = [try_call_method(x, "__float__")]
+
+ if (
+ "__index__" in x.jit_methods
+ ):
+ options.append(lambda x: float(x.__index__()))
+
+ return take_first(*options)
+
+
+@class_instance_overload(int)
+def class_int(x):
+ options = [try_call_method(x, "__int__")]
+
+ options.append(try_call_method(x, "__index__"))
+
+ return take_first(*options)
+
+
+@class_instance_overload(str)
+def class_str(x):
+ return take_first(
+ try_call_method(x, "__str__"),
+ lambda x: repr(x),
+ )
+
+
+@class_instance_overload(operator.ne)
+def class_ne(x, y):
+ # This doesn't use register_reflected_overload like the other operators
+ # because it falls back to inverting __eq__ rather than reflecting its
+ # arguments (as per the definition of the Python data model).
+ return take_first(
+ try_call_method(x, "__ne__", 2),
+ lambda x, y: not (x == y),
+ )
+
+
+def register_reflected_overload(func, meth_forward, meth_reflected):
+ def class_lt(x, y):
+ normal_impl = try_call_method(x, f"__{meth_forward}__", 2)
+
+ if f"__{meth_reflected}__" in y.jit_methods:
+ def reflected_impl(x, y):
+ return y > x
+ else:
+ reflected_impl = None
+
+ return take_first(normal_impl, reflected_impl)
+
+ class_instance_overload(func)(class_lt)
+
+
+register_simple_overload(abs, "abs")
+register_simple_overload(len, "len")
+register_simple_overload(hash, "hash")
+
+# Comparison operators.
+register_reflected_overload(operator.ge, "ge", "le")
+register_reflected_overload(operator.gt, "gt", "lt")
+register_reflected_overload(operator.le, "le", "ge")
+register_reflected_overload(operator.lt, "lt", "gt")
+
+# Note that eq is missing support for fallback to `x is y`, but `is` and
+# `operator.is` are presently unsupported in general.
+register_reflected_overload(operator.eq, "eq", "eq")
+
+# Arithmetic operators.
+register_simple_overload(operator.add, "add", n_args=2)
+register_simple_overload(operator.floordiv, "floordiv", n_args=2)
+register_simple_overload(operator.lshift, "lshift", n_args=2)
+register_simple_overload(operator.mul, "mul", n_args=2)
+register_simple_overload(operator.mod, "mod", n_args=2)
+register_simple_overload(operator.neg, "neg")
+register_simple_overload(operator.pos, "pos")
+register_simple_overload(operator.pow, "pow", n_args=2)
+register_simple_overload(operator.rshift, "rshift", n_args=2)
+register_simple_overload(operator.sub, "sub", n_args=2)
+register_simple_overload(operator.truediv, "truediv", n_args=2)
+
+# Inplace arithmetic operators.
+register_simple_overload(operator.iadd, "iadd", "add", n_args=2)
+register_simple_overload(operator.ifloordiv, "ifloordiv", "floordiv", n_args=2)
+register_simple_overload(operator.ilshift, "ilshift", "lshift", n_args=2)
+register_simple_overload(operator.imul, "imul", "mul", n_args=2)
+register_simple_overload(operator.imod, "imod", "mod", n_args=2)
+register_simple_overload(operator.ipow, "ipow", "pow", n_args=2)
+register_simple_overload(operator.irshift, "irshift", "rshift", n_args=2)
+register_simple_overload(operator.isub, "isub", "sub", n_args=2)
+register_simple_overload(operator.itruediv, "itruediv", "truediv", n_args=2)
+
+# Logical operators.
+register_simple_overload(operator.and_, "and", n_args=2)
+register_simple_overload(operator.or_, "or", n_args=2)
+register_simple_overload(operator.xor, "xor", n_args=2)
+
+# Inplace logical operators.
+register_simple_overload(operator.iand, "iand", "and", n_args=2)
+register_simple_overload(operator.ior, "ior", "or", n_args=2)
+register_simple_overload(operator.ixor, "ixor", "xor", n_args=2)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/misc/__pycache__/POST.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/misc/__pycache__/POST.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..30e5b39005a6ce6caaa3ab913e06a12bc2e2b3b6
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/misc/__pycache__/POST.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/misc/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/misc/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..59d9f050059805dd2e433734877619309e536f5e
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/misc/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/misc/__pycache__/appdirs.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/misc/__pycache__/appdirs.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d9f4ca8d5c2178376d61ee4c49b96520549c967e
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/misc/__pycache__/appdirs.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/misc/__pycache__/cffiimpl.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/misc/__pycache__/cffiimpl.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..00d3dda730295184d54bc7b8a29150b802c8f74d
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/misc/__pycache__/cffiimpl.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/misc/__pycache__/coverage_support.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/misc/__pycache__/coverage_support.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5c2c803c0f8bc90b1f976efdb574765cb98391cb
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/misc/__pycache__/coverage_support.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/misc/__pycache__/dump_style.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/misc/__pycache__/dump_style.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..75564423886a29c8e47054d526069709673fe32f
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/misc/__pycache__/dump_style.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/misc/__pycache__/findlib.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/misc/__pycache__/findlib.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4fb19831650b250abd6db33edcb14ba70eb4892b
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/misc/__pycache__/findlib.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/misc/__pycache__/firstlinefinder.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/misc/__pycache__/firstlinefinder.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e9fa05302a3b7d7e550781bc49be1b054442b971
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/misc/__pycache__/firstlinefinder.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/misc/__pycache__/gdb_hook.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/misc/__pycache__/gdb_hook.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0811bd876b3df9790a757b8d8bd072b2d328f1c3
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/misc/__pycache__/gdb_hook.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/misc/__pycache__/gdb_print_extension.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/misc/__pycache__/gdb_print_extension.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..62c0c2179428770e69d7b5ed2e736d8652b4d49f
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/misc/__pycache__/gdb_print_extension.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/misc/__pycache__/init_utils.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/misc/__pycache__/init_utils.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0a8901db99bd0aa535d0119f81737aa464b8faf7
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/misc/__pycache__/init_utils.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/misc/__pycache__/inspection.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/misc/__pycache__/inspection.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..223886268369cb1e81be1f85afeb7a1f71296c9c
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/misc/__pycache__/inspection.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/misc/__pycache__/literal.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/misc/__pycache__/literal.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4b929f164deebca4153027bf23b6150f31a133de
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/misc/__pycache__/literal.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/misc/__pycache__/llvm_pass_timings.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/misc/__pycache__/llvm_pass_timings.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6400099a60d512d1ff20e18d73f4f447c30db210
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/misc/__pycache__/llvm_pass_timings.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/misc/__pycache__/mergesort.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/misc/__pycache__/mergesort.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..74616160df3d4f65ca92639e49ff7bc6bff47fc5
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/misc/__pycache__/mergesort.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/misc/__pycache__/numba_entry.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/misc/__pycache__/numba_entry.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ac680ea9870c710bad96ef2f930c04da09ec97d1
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/misc/__pycache__/numba_entry.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/misc/__pycache__/numba_gdbinfo.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/misc/__pycache__/numba_gdbinfo.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6854dcff40e32bea2210187d56a39df6b4b9fe24
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/misc/__pycache__/numba_gdbinfo.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/misc/__pycache__/numba_sysinfo.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/misc/__pycache__/numba_sysinfo.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9fd97c262d50668fbe74e1050055e082cd101a25
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/misc/__pycache__/numba_sysinfo.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/misc/__pycache__/quicksort.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/misc/__pycache__/quicksort.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c93fb7096deec3567b9e8d2182ee929368ad0b24
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/misc/__pycache__/quicksort.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/misc/__pycache__/special.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/misc/__pycache__/special.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f9f64734c92d509adf892af67bcceebe50b97cc7
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/misc/__pycache__/special.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/misc/__pycache__/timsort.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/misc/__pycache__/timsort.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4c45cfe8cb18d0a82ae45c8f3e429a7ae0e3abf1
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/misc/__pycache__/timsort.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/misc/help/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/numba/misc/help/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/misc/help/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/misc/help/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6c327db4adab837f09ea218076e02c995b510da4
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/misc/help/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/misc/help/__pycache__/inspector.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/misc/help/__pycache__/inspector.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2b13d2e559bdd356b91f4c2132a24271bb723058
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/misc/help/__pycache__/inspector.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/misc/help/inspector.py b/tool_server/.venv/lib/python3.12/site-packages/numba/misc/help/inspector.py
new file mode 100644
index 0000000000000000000000000000000000000000..284a62af653327501283c0d0ecbf9d01d2d29053
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/misc/help/inspector.py
@@ -0,0 +1,433 @@
+"""
+This file contains `__main__` so that it can be run as a commandline tool.
+
+This file contains functions to inspect Numba's support for a given Python
+module or a Python package.
+"""
+
+import argparse
+import pkgutil
+import warnings
+import types as pytypes
+
+from numba.core import errors
+from numba._version import get_versions
+from numba.core.registry import cpu_target
+from numba.tests.support import captured_stdout
+
+
+def _get_commit():
+ full = get_versions()['full-revisionid']
+ if not full:
+ warnings.warn(
+ "Cannot find git commit hash. Source links could be inaccurate.",
+ category=errors.NumbaWarning,
+ )
+ return 'main'
+ return full
+
+
+commit = _get_commit()
+github_url = 'https://github.com/numba/numba/blob/{commit}/{path}#L{firstline}-L{lastline}' # noqa: E501
+
+
+def inspect_function(function, target=None):
+ """Return information about the support of a function.
+
+ Returns
+ -------
+ info : dict
+ Defined keys:
+ - "numba_type": str or None
+ The numba type object of the function if supported.
+ - "explained": str
+ A textual description of the support.
+ - "source_infos": dict
+ A dictionary containing the source location of each definition.
+ """
+ target = target or cpu_target
+ tyct = target.typing_context
+ # Make sure we have loaded all extensions
+ tyct.refresh()
+ target.target_context.refresh()
+
+ info = {}
+ # Try getting the function type
+ source_infos = {}
+ try:
+ nbty = tyct.resolve_value_type(function)
+ except ValueError:
+ nbty = None
+ explained = 'not supported'
+ else:
+ # Make a longer explanation of the type
+ explained = tyct.explain_function_type(nbty)
+ for temp in nbty.templates:
+ try:
+ source_infos[temp] = temp.get_source_info()
+ except AttributeError:
+ source_infos[temp] = None
+
+ info['numba_type'] = nbty
+ info['explained'] = explained
+ info['source_infos'] = source_infos
+ return info
+
+
+def inspect_module(module, target=None, alias=None):
+ """Inspect a module object and yielding results from `inspect_function()`
+ for each function object in the module.
+ """
+ alias = {} if alias is None else alias
+ # Walk the module
+ for name in dir(module):
+ if name.startswith('_'):
+ # Skip
+ continue
+ obj = getattr(module, name)
+ supported_types = (pytypes.FunctionType, pytypes.BuiltinFunctionType)
+
+ if not isinstance(obj, supported_types):
+ # Skip if it's not a function
+ continue
+
+ info = dict(module=module, name=name, obj=obj)
+ if obj in alias:
+ info['alias'] = alias[obj]
+ else:
+ alias[obj] = "{module}.{name}".format(module=module.__name__,
+ name=name)
+ info.update(inspect_function(obj, target=target))
+ yield info
+
+
+class _Stat(object):
+ """For gathering simple statistic of (un)supported functions"""
+ def __init__(self):
+ self.supported = 0
+ self.unsupported = 0
+
+ @property
+ def total(self):
+ total = self.supported + self.unsupported
+ return total
+
+ @property
+ def ratio(self):
+ ratio = self.supported / self.total * 100
+ return ratio
+
+ def describe(self):
+ if self.total == 0:
+ return "empty"
+ return "supported = {supported} / {total} = {ratio:.2f}%".format(
+ supported=self.supported,
+ total=self.total,
+ ratio=self.ratio,
+ )
+
+ def __repr__(self):
+ return "{clsname}({describe})".format(
+ clsname=self.__class__.__name__,
+ describe=self.describe(),
+ )
+
+
+def filter_private_module(module_components):
+ return not any(x.startswith('_') for x in module_components)
+
+
+def filter_tests_module(module_components):
+ return not any(x == 'tests' for x in module_components)
+
+
+_default_module_filters = (
+ filter_private_module,
+ filter_tests_module,
+)
+
+
+def list_modules_in_package(package, module_filters=_default_module_filters):
+ """Yield all modules in a given package.
+
+ Recursively walks the package tree.
+ """
+ onerror_ignore = lambda _: None
+
+ prefix = package.__name__ + "."
+ package_walker = pkgutil.walk_packages(
+ package.__path__,
+ prefix,
+ onerror=onerror_ignore,
+ )
+
+ def check_filter(modname):
+ module_components = modname.split('.')
+ return any(not filter_fn(module_components)
+ for filter_fn in module_filters)
+
+ modname = package.__name__
+ if not check_filter(modname):
+ yield package
+
+ for pkginfo in package_walker:
+ modname = pkginfo[1]
+ if check_filter(modname):
+ continue
+ # In case importing of the module print to stdout
+ with captured_stdout():
+ try:
+ # Import the module
+ mod = __import__(modname)
+ except Exception:
+ continue
+
+ # Extract the module
+ for part in modname.split('.')[1:]:
+ try:
+ mod = getattr(mod, part)
+ except AttributeError:
+ # Suppress error in getting the attribute
+ mod = None
+ break
+
+ # Ignore if mod is not a module
+ if not isinstance(mod, pytypes.ModuleType):
+ # Skip non-module
+ continue
+
+ yield mod
+
+
+class Formatter(object):
+ """Base class for formatters.
+ """
+ def __init__(self, fileobj):
+ self._fileobj = fileobj
+
+ def print(self, *args, **kwargs):
+ kwargs.setdefault('file', self._fileobj)
+ print(*args, **kwargs)
+
+
+class HTMLFormatter(Formatter):
+ """Formatter that outputs HTML
+ """
+
+ def escape(self, text):
+ import html
+ return html.escape(text)
+
+ def title(self, text):
+ self.print('', text, '')
+
+ def begin_module_section(self, modname):
+ self.print('', modname, ' ')
+ self.print('')
+
+ def end_module_section(self):
+ self.print(' ')
+
+ def write_supported_item(self, modname, itemname, typename, explained,
+ sources, alias):
+ self.print(' ')
+ self.print('{}.{} '.format(
+ modname,
+ itemname,
+ ))
+ self.print(': {} '.format(typename))
+ self.print('')
+
+ self.print("")
+ self.print(' ')
+
+ def write_unsupported_item(self, modname, itemname):
+ self.print('')
+ self.print('{}.{} : UNSUPPORTED'.format(
+ modname,
+ itemname,
+ ))
+ self.print(' ')
+
+ def write_statistic(self, stats):
+ self.print('{}
'.format(stats.describe()))
+
+
+class ReSTFormatter(Formatter):
+ """Formatter that output ReSTructured text format for Sphinx docs.
+ """
+ def escape(self, text):
+ return text
+
+ def title(self, text):
+ self.print(text)
+ self.print('=' * len(text))
+ self.print()
+
+ def begin_module_section(self, modname):
+ self.print(modname)
+ self.print('-' * len(modname))
+ self.print()
+
+ def end_module_section(self):
+ self.print()
+
+ def write_supported_item(self, modname, itemname, typename, explained,
+ sources, alias):
+ self.print('.. function:: {}.{}'.format(modname, itemname))
+ self.print(' :noindex:')
+ self.print()
+
+ if alias:
+ self.print(" Alias to: ``{}``".format(alias))
+ self.print()
+
+ for tcls, source in sources.items():
+ if source:
+ impl = source['name']
+ sig = source['sig']
+ filename = source['filename']
+ lines = source['lines']
+ source_link = github_url.format(
+ commit=commit,
+ path=filename,
+ firstline=lines[0],
+ lastline=lines[1],
+ )
+ self.print(
+ " - defined by ``{}{}`` at `{}:{}-{} <{}>`_".format(
+ impl, sig, filename, lines[0], lines[1], source_link,
+ ),
+ )
+
+ else:
+ self.print(" - defined by ``{}``".format(str(tcls)))
+ self.print()
+
+ def write_unsupported_item(self, modname, itemname):
+ pass
+
+ def write_statistic(self, stat):
+ if stat.supported == 0:
+ self.print("This module is not supported.")
+ else:
+ msg = "Not showing {} unsupported functions."
+ self.print(msg.format(stat.unsupported))
+ self.print()
+ self.print(stat.describe())
+ self.print()
+
+
+def _format_module_infos(formatter, package_name, mod_sequence, target=None):
+ """Format modules.
+ """
+ formatter.title('Listings for {}'.format(package_name))
+ alias_map = {} # remember object seen to track alias
+ for mod in mod_sequence:
+ stat = _Stat()
+ modname = mod.__name__
+ formatter.begin_module_section(formatter.escape(modname))
+ for info in inspect_module(mod, target=target, alias=alias_map):
+ nbtype = info['numba_type']
+ if nbtype is not None:
+ stat.supported += 1
+ formatter.write_supported_item(
+ modname=formatter.escape(info['module'].__name__),
+ itemname=formatter.escape(info['name']),
+ typename=formatter.escape(str(nbtype)),
+ explained=formatter.escape(info['explained']),
+ sources=info['source_infos'],
+ alias=info.get('alias'),
+ )
+
+ else:
+ stat.unsupported += 1
+ formatter.write_unsupported_item(
+ modname=formatter.escape(info['module'].__name__),
+ itemname=formatter.escape(info['name']),
+ )
+
+ formatter.write_statistic(stat)
+ formatter.end_module_section()
+
+
+def write_listings(package_name, filename, output_format):
+ """Write listing information into a file.
+
+ Parameters
+ ----------
+ package_name : str
+ Name of the package to inspect.
+ filename : str
+ Output filename. Always overwrite.
+ output_format : str
+ Support formats are "html" and "rst".
+ """
+ package = __import__(package_name)
+ if hasattr(package, '__path__'):
+ mods = list_modules_in_package(package)
+ else:
+ mods = [package]
+
+ if output_format == 'html':
+ with open(filename + '.html', 'w') as fout:
+ fmtr = HTMLFormatter(fileobj=fout)
+ _format_module_infos(fmtr, package_name, mods)
+ elif output_format == 'rst':
+ with open(filename + '.rst', 'w') as fout:
+ fmtr = ReSTFormatter(fileobj=fout)
+ _format_module_infos(fmtr, package_name, mods)
+ else:
+ raise ValueError(
+ "Output format '{}' is not supported".format(output_format))
+
+
+program_description = """
+Inspect Numba support for a given top-level package.
+""".strip()
+
+
+def main():
+ parser = argparse.ArgumentParser(description=program_description)
+ parser.add_argument(
+ 'package', metavar='package', type=str,
+ help='Package to inspect',
+ )
+ parser.add_argument(
+ '--format', dest='format', default='html',
+ help='Output format; i.e. "html", "rst"',
+ )
+ parser.add_argument(
+ '--file', dest='file', default='inspector_output',
+ help='Output filename. Defaults to "inspector_output."',
+ )
+
+ args = parser.parse_args()
+ package_name = args.package
+ output_format = args.format
+ filename = args.file
+ write_listings(package_name, filename, output_format)
+
+
+if __name__ == '__main__':
+ main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/np/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/np/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..41cad84127f84d9fdedea0a2258f81f222651ca3
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/np/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/np/__pycache__/arraymath.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/np/__pycache__/arraymath.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..85e309d7370e1013e79d6441eaaad17a01b121b2
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/np/__pycache__/arraymath.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/np/__pycache__/arrayobj.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/np/__pycache__/arrayobj.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8a4169d03012efdae8f8ba355e09f14d901efcf6
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/np/__pycache__/arrayobj.cpython-312.pyc
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:adba01defcbb4c7057fae550245d5bde2b99970928e241e052586892af568d00
+size 332429
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/np/__pycache__/extensions.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/np/__pycache__/extensions.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1d6ffde96f69cc0c1a1deac54b080bdfa331c111
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/np/__pycache__/extensions.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/np/__pycache__/linalg.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/np/__pycache__/linalg.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..48711a7c0fd35e1f2acf11adb1c014068faafb48
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/np/__pycache__/linalg.cpython-312.pyc
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:f336f6d9f70e129460ba1c8b5f105c1fb5a8aa17484339fe3e8a412c5ea2f10d
+size 106506
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/np/__pycache__/new_arraymath.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/np/__pycache__/new_arraymath.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f7d918a28ed6f60070a2c46b02224138ac768bad
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/np/__pycache__/new_arraymath.cpython-312.pyc
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:8b06fd7f579c0e2db20a560f698b615e2cc8d62118dcaae8b79d4a8ec1c997ad
+size 208892
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/np/__pycache__/npdatetime.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/np/__pycache__/npdatetime.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..216f75b77d37ed6982f8cc9a540d5199bb37ffc9
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/np/__pycache__/npdatetime.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/np/__pycache__/npdatetime_helpers.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/np/__pycache__/npdatetime_helpers.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..10e45099bce4f5b4d6ece589f9d71891e8a588fd
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/np/__pycache__/npdatetime_helpers.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/np/__pycache__/npyfuncs.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/np/__pycache__/npyfuncs.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a90192fb64e5b1472745e650fd742324419ad1c9
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/np/__pycache__/npyfuncs.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/np/__pycache__/npyimpl.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/np/__pycache__/npyimpl.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3ff9c7b08230f37c9eeaa59a055c809c05f1b6e1
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/np/__pycache__/npyimpl.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/np/__pycache__/numpy_support.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/np/__pycache__/numpy_support.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..577afd39f4584e7d011a1e21b5976450075795c9
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/np/__pycache__/numpy_support.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/np/__pycache__/old_arraymath.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/np/__pycache__/old_arraymath.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3547acf09647dddc6ac847a64a9238c29dbe4602
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/np/__pycache__/old_arraymath.cpython-312.pyc
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:6e33563925025fa38851b5c132c87320d9a9221e7fbfbaa69b010a38ca5c9d1c
+size 209010
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/np/__pycache__/ufunc_db.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/np/__pycache__/ufunc_db.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a64c3589e9e0a1bc75df25dfaac64327a9eef872
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/np/__pycache__/ufunc_db.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/np/math/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/numba/np/math/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/np/math/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/np/math/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..621e77ba1fe10c47931598e0f614aa8f85fb7ee4
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/np/math/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/np/math/__pycache__/cmathimpl.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/np/math/__pycache__/cmathimpl.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ff4e7f3437e99f6725cd76e8ff2b86580cc120f3
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/np/math/__pycache__/cmathimpl.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/np/math/__pycache__/mathimpl.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/np/math/__pycache__/mathimpl.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..efef60a2df4515ea1c5a38c51c317e0f303df6e1
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/np/math/__pycache__/mathimpl.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/np/math/__pycache__/numbers.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/np/math/__pycache__/numbers.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ac967b45dcde547781374adbabd86363f3235ef6
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/np/math/__pycache__/numbers.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/np/math/cmathimpl.py b/tool_server/.venv/lib/python3.12/site-packages/numba/np/math/cmathimpl.py
new file mode 100644
index 0000000000000000000000000000000000000000..0ac32a9144ed4994e150a6a686c461978dd90d99
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/np/math/cmathimpl.py
@@ -0,0 +1,542 @@
+"""
+Implement the cmath module functions.
+"""
+
+
+import cmath
+import math
+
+from numba.core.imputils import impl_ret_untracked
+from numba.core import types
+from numba.core.typing import signature
+from numba.cpython import mathimpl
+from numba.core.extending import overload
+
+# registry = Registry('cmathimpl')
+# lower = registry.lower
+
+
+def is_nan(builder, z):
+ return builder.fcmp_unordered('uno', z.real, z.imag)
+
+def is_inf(builder, z):
+ return builder.or_(mathimpl.is_inf(builder, z.real),
+ mathimpl.is_inf(builder, z.imag))
+
+def is_finite(builder, z):
+ return builder.and_(mathimpl.is_finite(builder, z.real),
+ mathimpl.is_finite(builder, z.imag))
+
+
+# @lower(cmath.isnan, types.Complex)
+def isnan_float_impl(context, builder, sig, args):
+ [typ] = sig.args
+ [value] = args
+ z = context.make_complex(builder, typ, value=value)
+ res = is_nan(builder, z)
+ return impl_ret_untracked(context, builder, sig.return_type, res)
+
+# @lower(cmath.isinf, types.Complex)
+def isinf_float_impl(context, builder, sig, args):
+ [typ] = sig.args
+ [value] = args
+ z = context.make_complex(builder, typ, value=value)
+ res = is_inf(builder, z)
+ return impl_ret_untracked(context, builder, sig.return_type, res)
+
+
+# @lower(cmath.isfinite, types.Complex)
+def isfinite_float_impl(context, builder, sig, args):
+ [typ] = sig.args
+ [value] = args
+ z = context.make_complex(builder, typ, value=value)
+ res = is_finite(builder, z)
+ return impl_ret_untracked(context, builder, sig.return_type, res)
+
+
+# @overload(cmath.rect)
+def impl_cmath_rect(r, phi):
+ if all([isinstance(typ, types.Float) for typ in [r, phi]]):
+ def impl(r, phi):
+ if not math.isfinite(phi):
+ if not r:
+ # cmath.rect(0, phi={inf, nan}) = 0
+ return abs(r)
+ if math.isinf(r):
+ # cmath.rect(inf, phi={inf, nan}) = inf + j phi
+ return complex(r, phi)
+ real = math.cos(phi)
+ imag = math.sin(phi)
+ if real == 0. and math.isinf(r):
+ # 0 * inf would return NaN, we want to keep 0 but xor the sign
+ real /= r
+ else:
+ real *= r
+ if imag == 0. and math.isinf(r):
+ # ditto
+ imag /= r
+ else:
+ imag *= r
+ return complex(real, imag)
+ return impl
+
+
+def intrinsic_complex_unary(inner_func):
+ def wrapper(context, builder, sig, args):
+ [typ] = sig.args
+ [value] = args
+ z = context.make_complex(builder, typ, value=value)
+ x = z.real
+ y = z.imag
+ # Same as above: math.isfinite() is unavailable on 2.x so we precompute
+ # its value and pass it to the pure Python implementation.
+ x_is_finite = mathimpl.is_finite(builder, x)
+ y_is_finite = mathimpl.is_finite(builder, y)
+ inner_sig = signature(sig.return_type,
+ *(typ.underlying_float,) * 2 + (types.boolean,) * 2)
+ res = context.compile_internal(builder, inner_func, inner_sig,
+ (x, y, x_is_finite, y_is_finite))
+ return impl_ret_untracked(context, builder, sig, res)
+ return wrapper
+
+
+NAN = float('nan')
+INF = float('inf')
+
+# @lower(cmath.exp, types.Complex)
+@intrinsic_complex_unary
+def exp_impl(x, y, x_is_finite, y_is_finite):
+ """cmath.exp(x + y j)"""
+ if x_is_finite:
+ if y_is_finite:
+ c = math.cos(y)
+ s = math.sin(y)
+ r = math.exp(x)
+ return complex(r * c, r * s)
+ else:
+ return complex(NAN, NAN)
+ elif math.isnan(x):
+ if y:
+ return complex(x, x) # nan + j nan
+ else:
+ return complex(x, y) # nan + 0j
+ elif x > 0.0:
+ # x == +inf
+ if y_is_finite:
+ real = math.cos(y)
+ imag = math.sin(y)
+ # Avoid NaNs if math.cos(y) or math.sin(y) == 0
+ # (e.g. cmath.exp(inf + 0j) == inf + 0j)
+ if real != 0:
+ real *= x
+ if imag != 0:
+ imag *= x
+ return complex(real, imag)
+ else:
+ return complex(x, NAN)
+ else:
+ # x == -inf
+ if y_is_finite:
+ r = math.exp(x)
+ c = math.cos(y)
+ s = math.sin(y)
+ return complex(r * c, r * s)
+ else:
+ r = 0
+ return complex(r, r)
+
+# @lower(cmath.log, types.Complex)
+@intrinsic_complex_unary
+def log_impl(x, y, x_is_finite, y_is_finite):
+ """cmath.log(x + y j)"""
+ a = math.log(math.hypot(x, y))
+ b = math.atan2(y, x)
+ return complex(a, b)
+
+
+# @lower(cmath.log, types.Complex, types.Complex)
+def log_base_impl(context, builder, sig, args):
+ """cmath.log(z, base)"""
+ [z, base] = args
+
+ def log_base(z, base):
+ return cmath.log(z) / cmath.log(base)
+
+ res = context.compile_internal(builder, log_base, sig, args)
+ return impl_ret_untracked(context, builder, sig, res)
+
+
+# @overload(cmath.log10)
+def impl_cmath_log10(z):
+ if not isinstance(z, types.Complex):
+ return
+
+ LN_10 = 2.302585092994045684
+
+ def log10_impl(z):
+ """cmath.log10(z)"""
+ z = cmath.log(z)
+ # This formula gives better results on +/-inf than cmath.log(z, 10)
+ # See http://bugs.python.org/issue22544
+ return complex(z.real / LN_10, z.imag / LN_10)
+
+ return log10_impl
+
+
+# @overload(cmath.phase)
+def phase_impl(x):
+ """cmath.phase(x + y j)"""
+
+ if not isinstance(x, types.Complex):
+ return
+
+ def impl(x):
+ return math.atan2(x.imag, x.real)
+ return impl
+
+
+# @overload(cmath.polar)
+def polar_impl(x):
+ if not isinstance(x, types.Complex):
+ return
+
+ def impl(x):
+ r, i = x.real, x.imag
+ return math.hypot(r, i), math.atan2(i, r)
+ return impl
+
+
+# @lower(cmath.sqrt, types.Complex)
+def sqrt_impl(context, builder, sig, args):
+ # We risk spurious overflow for components >= FLT_MAX / (1 + sqrt(2)).
+
+ SQRT2 = 1.414213562373095048801688724209698079E0
+ ONE_PLUS_SQRT2 = (1. + SQRT2)
+ theargflt = sig.args[0].underlying_float
+ # Get a type specific maximum value so scaling for overflow is based on that
+ MAX = mathimpl.DBL_MAX if theargflt.bitwidth == 64 else mathimpl.FLT_MAX
+ # THRES will be double precision, should not impact typing as it's just
+ # used for comparison, there *may* be a few values near THRES which
+ # deviate from e.g. NumPy due to rounding that occurs in the computation
+ # of this value in the case of a 32bit argument.
+ THRES = MAX / ONE_PLUS_SQRT2
+
+ def sqrt_impl(z):
+ """cmath.sqrt(z)"""
+ # This is NumPy's algorithm, see npy_csqrt() in npy_math_complex.c.src
+ a = z.real
+ b = z.imag
+ if a == 0.0 and b == 0.0:
+ return complex(abs(b), b)
+ if math.isinf(b):
+ return complex(abs(b), b)
+ if math.isnan(a):
+ return complex(a, a)
+ if math.isinf(a):
+ if a < 0.0:
+ return complex(abs(b - b), math.copysign(a, b))
+ else:
+ return complex(a, math.copysign(b - b, b))
+
+ # The remaining special case (b is NaN) is handled just fine by
+ # the normal code path below.
+
+ # Scale to avoid overflow
+ if abs(a) >= THRES or abs(b) >= THRES:
+ a *= 0.25
+ b *= 0.25
+ scale = True
+ else:
+ scale = False
+ # Algorithm 312, CACM vol 10, Oct 1967
+ if a >= 0:
+ t = math.sqrt((a + math.hypot(a, b)) * 0.5)
+ real = t
+ imag = b / (2 * t)
+ else:
+ t = math.sqrt((-a + math.hypot(a, b)) * 0.5)
+ real = abs(b) / (2 * t)
+ imag = math.copysign(t, b)
+ # Rescale
+ if scale:
+ return complex(real * 2, imag)
+ else:
+ return complex(real, imag)
+
+ res = context.compile_internal(builder, sqrt_impl, sig, args)
+ return impl_ret_untracked(context, builder, sig, res)
+
+
+# @lower(cmath.cos, types.Complex)
+def cos_impl(context, builder, sig, args):
+ def cos_impl(z):
+ """cmath.cos(z) = cmath.cosh(z j)"""
+ return cmath.cosh(complex(-z.imag, z.real))
+
+ res = context.compile_internal(builder, cos_impl, sig, args)
+ return impl_ret_untracked(context, builder, sig, res)
+
+# @overload(cmath.cosh)
+def impl_cmath_cosh(z):
+ if not isinstance(z, types.Complex):
+ return
+
+ def cosh_impl(z):
+ """cmath.cosh(z)"""
+ x = z.real
+ y = z.imag
+ if math.isinf(x):
+ if math.isnan(y):
+ # x = +inf, y = NaN => cmath.cosh(x + y j) = inf + Nan * j
+ real = abs(x)
+ imag = y
+ elif y == 0.0:
+ # x = +inf, y = 0 => cmath.cosh(x + y j) = inf + 0j
+ real = abs(x)
+ imag = y
+ else:
+ real = math.copysign(x, math.cos(y))
+ imag = math.copysign(x, math.sin(y))
+ if x < 0.0:
+ # x = -inf => negate imaginary part of result
+ imag = -imag
+ return complex(real, imag)
+ return complex(math.cos(y) * math.cosh(x),
+ math.sin(y) * math.sinh(x))
+ return cosh_impl
+
+
+# @lower(cmath.sin, types.Complex)
+def sin_impl(context, builder, sig, args):
+ def sin_impl(z):
+ """cmath.sin(z) = -j * cmath.sinh(z j)"""
+ r = cmath.sinh(complex(-z.imag, z.real))
+ return complex(r.imag, -r.real)
+
+ res = context.compile_internal(builder, sin_impl, sig, args)
+ return impl_ret_untracked(context, builder, sig, res)
+
+# @overload(cmath.sinh)
+def impl_cmath_sinh(z):
+ if not isinstance(z, types.Complex):
+ return
+
+ def sinh_impl(z):
+ """cmath.sinh(z)"""
+ x = z.real
+ y = z.imag
+ if math.isinf(x):
+ if math.isnan(y):
+ # x = +/-inf, y = NaN => cmath.sinh(x + y j) = x + NaN * j
+ real = x
+ imag = y
+ else:
+ real = math.cos(y)
+ imag = math.sin(y)
+ if real != 0.:
+ real *= x
+ if imag != 0.:
+ imag *= abs(x)
+ return complex(real, imag)
+ return complex(math.cos(y) * math.sinh(x),
+ math.sin(y) * math.cosh(x))
+ return sinh_impl
+
+
+# @lower(cmath.tan, types.Complex)
+def tan_impl(context, builder, sig, args):
+ def tan_impl(z):
+ """cmath.tan(z) = -j * cmath.tanh(z j)"""
+ r = cmath.tanh(complex(-z.imag, z.real))
+ return complex(r.imag, -r.real)
+
+ res = context.compile_internal(builder, tan_impl, sig, args)
+ return impl_ret_untracked(context, builder, sig, res)
+
+
+# @overload(cmath.tanh)
+def impl_cmath_tanh(z):
+ if not isinstance(z, types.Complex):
+ return
+
+ def tanh_impl(z):
+ """cmath.tanh(z)"""
+ x = z.real
+ y = z.imag
+ if math.isinf(x):
+ real = math.copysign(1., x)
+ if math.isinf(y):
+ imag = 0.
+ else:
+ imag = math.copysign(0., math.sin(2. * y))
+ return complex(real, imag)
+ # This is CPython's algorithm (see c_tanh() in cmathmodule.c).
+ # XXX how to force float constants into single precision?
+ tx = math.tanh(x)
+ ty = math.tan(y)
+ cx = 1. / math.cosh(x)
+ txty = tx * ty
+ denom = 1. + txty * txty
+ return complex(
+ tx * (1. + ty * ty) / denom,
+ ((ty / denom) * cx) * cx)
+
+ return tanh_impl
+
+
+# @lower(cmath.acos, types.Complex)
+def acos_impl(context, builder, sig, args):
+ LN_4 = math.log(4)
+ THRES = mathimpl.FLT_MAX / 4
+
+ def acos_impl(z):
+ """cmath.acos(z)"""
+ # CPython's algorithm (see c_acos() in cmathmodule.c)
+ if abs(z.real) > THRES or abs(z.imag) > THRES:
+ # Avoid unnecessary overflow for large arguments
+ # (also handles infinities gracefully)
+ real = math.atan2(abs(z.imag), z.real)
+ imag = math.copysign(
+ math.log(math.hypot(z.real * 0.5, z.imag * 0.5)) + LN_4,
+ -z.imag)
+ return complex(real, imag)
+ else:
+ s1 = cmath.sqrt(complex(1. - z.real, -z.imag))
+ s2 = cmath.sqrt(complex(1. + z.real, z.imag))
+ real = 2. * math.atan2(s1.real, s2.real)
+ imag = math.asinh(s2.real * s1.imag - s2.imag * s1.real)
+ return complex(real, imag)
+
+ res = context.compile_internal(builder, acos_impl, sig, args)
+ return impl_ret_untracked(context, builder, sig, res)
+
+# @overload(cmath.acosh)
+def impl_cmath_acosh(z):
+ if not isinstance(z, types.Complex):
+ return
+
+ LN_4 = math.log(4)
+ THRES = mathimpl.FLT_MAX / 4
+
+ def acosh_impl(z):
+ """cmath.acosh(z)"""
+ # CPython's algorithm (see c_acosh() in cmathmodule.c)
+ if abs(z.real) > THRES or abs(z.imag) > THRES:
+ # Avoid unnecessary overflow for large arguments
+ # (also handles infinities gracefully)
+ real = math.log(math.hypot(z.real * 0.5, z.imag * 0.5)) + LN_4
+ imag = math.atan2(z.imag, z.real)
+ return complex(real, imag)
+ else:
+ s1 = cmath.sqrt(complex(z.real - 1., z.imag))
+ s2 = cmath.sqrt(complex(z.real + 1., z.imag))
+ real = math.asinh(s1.real * s2.real + s1.imag * s2.imag)
+ imag = 2. * math.atan2(s1.imag, s2.real)
+ return complex(real, imag)
+ # Condensed formula (NumPy)
+ #return cmath.log(z + cmath.sqrt(z + 1.) * cmath.sqrt(z - 1.))
+
+ return acosh_impl
+
+
+# @lower(cmath.asinh, types.Complex)
+def asinh_impl(context, builder, sig, args):
+ LN_4 = math.log(4)
+ THRES = mathimpl.FLT_MAX / 4
+
+ def asinh_impl(z):
+ """cmath.asinh(z)"""
+ # CPython's algorithm (see c_asinh() in cmathmodule.c)
+ if abs(z.real) > THRES or abs(z.imag) > THRES:
+ real = math.copysign(
+ math.log(math.hypot(z.real * 0.5, z.imag * 0.5)) + LN_4,
+ z.real)
+ imag = math.atan2(z.imag, abs(z.real))
+ return complex(real, imag)
+ else:
+ s1 = cmath.sqrt(complex(1. + z.imag, -z.real))
+ s2 = cmath.sqrt(complex(1. - z.imag, z.real))
+ real = math.asinh(s1.real * s2.imag - s2.real * s1.imag)
+ imag = math.atan2(z.imag, s1.real * s2.real - s1.imag * s2.imag)
+ return complex(real, imag)
+
+ res = context.compile_internal(builder, asinh_impl, sig, args)
+ return impl_ret_untracked(context, builder, sig, res)
+
+# @lower(cmath.asin, types.Complex)
+def asin_impl(context, builder, sig, args):
+ def asin_impl(z):
+ """cmath.asin(z) = -j * cmath.asinh(z j)"""
+ r = cmath.asinh(complex(-z.imag, z.real))
+ return complex(r.imag, -r.real)
+
+ res = context.compile_internal(builder, asin_impl, sig, args)
+ return impl_ret_untracked(context, builder, sig, res)
+
+# @lower(cmath.atan, types.Complex)
+def atan_impl(context, builder, sig, args):
+ def atan_impl(z):
+ """cmath.atan(z) = -j * cmath.atanh(z j)"""
+ r = cmath.atanh(complex(-z.imag, z.real))
+ if math.isinf(z.real) and math.isnan(z.imag):
+ # XXX this is odd but necessary
+ return complex(r.imag, r.real)
+ else:
+ return complex(r.imag, -r.real)
+
+ res = context.compile_internal(builder, atan_impl, sig, args)
+ return impl_ret_untracked(context, builder, sig, res)
+
+# @lower(cmath.atanh, types.Complex)
+def atanh_impl(context, builder, sig, args):
+ LN_4 = math.log(4)
+ THRES_LARGE = math.sqrt(mathimpl.FLT_MAX / 4)
+ THRES_SMALL = math.sqrt(mathimpl.FLT_MIN)
+ PI_12 = math.pi / 2
+
+ def atanh_impl(z):
+ """cmath.atanh(z)"""
+ # CPython's algorithm (see c_atanh() in cmathmodule.c)
+ if z.real < 0.:
+ # Reduce to case where z.real >= 0., using atanh(z) = -atanh(-z).
+ negate = True
+ z = -z
+ else:
+ negate = False
+
+ ay = abs(z.imag)
+ if math.isnan(z.real) or z.real > THRES_LARGE or ay > THRES_LARGE:
+ if math.isinf(z.imag):
+ real = math.copysign(0., z.real)
+ elif math.isinf(z.real):
+ real = 0.
+ else:
+ # may be safe from overflow, depending on hypot's implementation...
+ h = math.hypot(z.real * 0.5, z.imag * 0.5)
+ real = z.real/4./h/h
+ imag = -math.copysign(PI_12, -z.imag)
+ elif z.real == 1. and ay < THRES_SMALL:
+ # C99 standard says: atanh(1+/-0.) should be inf +/- 0j
+ if ay == 0.:
+ real = INF
+ imag = z.imag
+ else:
+ real = -math.log(math.sqrt(ay) /
+ math.sqrt(math.hypot(ay, 2.)))
+ imag = math.copysign(math.atan2(2., -ay) / 2, z.imag)
+ else:
+ sqay = ay * ay
+ zr1 = 1 - z.real
+ real = math.log1p(4. * z.real / (zr1 * zr1 + sqay)) * 0.25
+ imag = -math.atan2(-2. * z.imag,
+ zr1 * (1 + z.real) - sqay) * 0.5
+
+ if math.isnan(z.imag):
+ imag = NAN
+ if negate:
+ return complex(-real, -imag)
+ else:
+ return complex(real, imag)
+
+ res = context.compile_internal(builder, atanh_impl, sig, args)
+ return impl_ret_untracked(context, builder, sig, res)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/np/math/mathimpl.py b/tool_server/.venv/lib/python3.12/site-packages/numba/np/math/mathimpl.py
new file mode 100644
index 0000000000000000000000000000000000000000..d872b97e9eea6dd49b6725024743767391c8d4ae
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/np/math/mathimpl.py
@@ -0,0 +1,455 @@
+"""
+Provide math calls that uses intrinsics or libc math functions.
+"""
+
+import math
+import operator
+import sys
+import numpy as np
+
+import llvmlite.ir
+from llvmlite.ir import Constant
+
+from numba.core.imputils import impl_ret_untracked
+from numba.core import types, config, cgutils
+from numba.core.extending import overload
+from numba.core.typing import signature
+from numba.cpython.unsafe.numbers import trailing_zeros
+
+
+# registry = Registry('mathimpl')
+# lower = registry.lower
+
+
+# Helpers, shared with cmathimpl.
+_NP_FLT_FINFO = np.finfo(np.dtype('float32'))
+FLT_MAX = _NP_FLT_FINFO.max
+FLT_MIN = _NP_FLT_FINFO.tiny
+
+_NP_DBL_FINFO = np.finfo(np.dtype('float64'))
+DBL_MAX = _NP_DBL_FINFO.max
+DBL_MIN = _NP_DBL_FINFO.tiny
+
+FLOAT_ABS_MASK = 0x7fffffff
+FLOAT_SIGN_MASK = 0x80000000
+DOUBLE_ABS_MASK = 0x7fffffffffffffff
+DOUBLE_SIGN_MASK = 0x8000000000000000
+
+
+def is_nan(builder, val):
+ """
+ Return a condition testing whether *val* is a NaN.
+ """
+ return builder.fcmp_unordered('uno', val, val)
+
+def is_inf(builder, val):
+ """
+ Return a condition testing whether *val* is an infinite.
+ """
+ pos_inf = Constant(val.type, float("+inf"))
+ neg_inf = Constant(val.type, float("-inf"))
+ isposinf = builder.fcmp_ordered('==', val, pos_inf)
+ isneginf = builder.fcmp_ordered('==', val, neg_inf)
+ return builder.or_(isposinf, isneginf)
+
+def is_finite(builder, val):
+ """
+ Return a condition testing whether *val* is a finite.
+ """
+ # is_finite(x) <=> x - x != NaN
+ val_minus_val = builder.fsub(val, val)
+ return builder.fcmp_ordered('ord', val_minus_val, val_minus_val)
+
+def f64_as_int64(builder, val):
+ """
+ Bitcast a double into a 64-bit integer.
+ """
+ assert val.type == llvmlite.ir.DoubleType()
+ return builder.bitcast(val, llvmlite.ir.IntType(64))
+
+def int64_as_f64(builder, val):
+ """
+ Bitcast a 64-bit integer into a double.
+ """
+ assert val.type == llvmlite.ir.IntType(64)
+ return builder.bitcast(val, llvmlite.ir.DoubleType())
+
+def f32_as_int32(builder, val):
+ """
+ Bitcast a float into a 32-bit integer.
+ """
+ assert val.type == llvmlite.ir.FloatType()
+ return builder.bitcast(val, llvmlite.ir.IntType(32))
+
+def int32_as_f32(builder, val):
+ """
+ Bitcast a 32-bit integer into a float.
+ """
+ assert val.type == llvmlite.ir.IntType(32)
+ return builder.bitcast(val, llvmlite.ir.FloatType())
+
+def negate_real(builder, val):
+ """
+ Negate real number *val*, with proper handling of zeros.
+ """
+ # The negative zero forces LLVM to handle signed zeros properly.
+ return builder.fsub(Constant(val.type, -0.0), val)
+
+def call_fp_intrinsic(builder, name, args):
+ """
+ Call a LLVM intrinsic floating-point operation.
+ """
+ mod = builder.module
+ intr = mod.declare_intrinsic(name, [a.type for a in args])
+ return builder.call(intr, args)
+
+
+def _unary_int_input_wrapper_impl(wrapped_impl):
+ """
+ Return an implementation factory to convert the single integral input
+ argument to a float64, then defer to the *wrapped_impl*.
+ """
+ def implementer(context, builder, sig, args):
+ val, = args
+ input_type = sig.args[0]
+ fpval = context.cast(builder, val, input_type, types.float64)
+ inner_sig = signature(types.float64, types.float64)
+ res = wrapped_impl(context, builder, inner_sig, (fpval,))
+ return context.cast(builder, res, types.float64, sig.return_type)
+
+ return implementer
+
+def unary_math_int_impl(fn, float_impl):
+ impl = _unary_int_input_wrapper_impl(float_impl)
+ # lower(fn, types.Integer)(impl)
+
+def unary_math_intr(fn, intrcode):
+ """
+ Implement the math function *fn* using the LLVM intrinsic *intrcode*.
+ """
+ # @lower(fn, types.Float)
+ def float_impl(context, builder, sig, args):
+ res = call_fp_intrinsic(builder, intrcode, args)
+ return impl_ret_untracked(context, builder, sig.return_type, res)
+
+ unary_math_int_impl(fn, float_impl)
+ return float_impl
+
+def unary_math_extern(fn, f32extern, f64extern, int_restype=False):
+ """
+ Register implementations of Python function *fn* using the
+ external function named *f32extern* and *f64extern* (for float32
+ and float64 inputs, respectively).
+ If *int_restype* is true, then the function's return value should be
+ integral, otherwise floating-point.
+ """
+ if config.USE_LEGACY_TYPE_SYSTEM:
+ f_restype = types.int64 if int_restype else None
+ else:
+ f_restype = types.np_int64 if int_restype else None
+
+ def float_impl(context, builder, sig, args):
+ """
+ Implement *fn* for a types.Float input.
+ """
+ [val] = args
+ mod = builder.module
+ input_type = sig.args[0]
+ lty = context.get_value_type(input_type)
+ func_name = {
+ types.float32: f32extern,
+ types.float64: f64extern,
+ }[input_type]
+ fnty = llvmlite.ir.FunctionType(lty, [lty])
+ fn = cgutils.insert_pure_function(builder.module, fnty, name=func_name)
+ res = builder.call(fn, (val,))
+ res = context.cast(builder, res, input_type, sig.return_type)
+ return impl_ret_untracked(context, builder, sig.return_type, res)
+
+ # lower(fn, types.Float)(float_impl)
+
+ # Implement wrapper for integer inputs
+ unary_math_int_impl(fn, float_impl)
+
+ return float_impl
+
+
+unary_math_intr(math.fabs, 'llvm.fabs')
+exp_impl = unary_math_intr(math.exp, 'llvm.exp')
+log_impl = unary_math_intr(math.log, 'llvm.log')
+log10_impl = unary_math_intr(math.log10, 'llvm.log10')
+sin_impl = unary_math_intr(math.sin, 'llvm.sin')
+cos_impl = unary_math_intr(math.cos, 'llvm.cos')
+
+log1p_impl = unary_math_extern(math.log1p, "log1pf", "log1p")
+expm1_impl = unary_math_extern(math.expm1, "expm1f", "expm1")
+erf_impl = unary_math_extern(math.erf, "erff", "erf")
+erfc_impl = unary_math_extern(math.erfc, "erfcf", "erfc")
+
+tan_impl = unary_math_extern(math.tan, "tanf", "tan")
+asin_impl = unary_math_extern(math.asin, "asinf", "asin")
+acos_impl = unary_math_extern(math.acos, "acosf", "acos")
+atan_impl = unary_math_extern(math.atan, "atanf", "atan")
+
+asinh_impl = unary_math_extern(math.asinh, "asinhf", "asinh")
+acosh_impl = unary_math_extern(math.acosh, "acoshf", "acosh")
+atanh_impl = unary_math_extern(math.atanh, "atanhf", "atanh")
+sinh_impl = unary_math_extern(math.sinh, "sinhf", "sinh")
+cosh_impl = unary_math_extern(math.cosh, "coshf", "cosh")
+tanh_impl = unary_math_extern(math.tanh, "tanhf", "tanh")
+
+log2_impl = unary_math_extern(math.log2, "log2f", "log2")
+ceil_impl = unary_math_extern(math.ceil, "ceilf", "ceil", True)
+floor_impl = unary_math_extern(math.floor, "floorf", "floor", True)
+
+gamma_impl = unary_math_extern(math.gamma, "numba_gammaf", "numba_gamma") # work-around
+sqrt_impl = unary_math_extern(math.sqrt, "sqrtf", "sqrt")
+trunc_impl = unary_math_extern(math.trunc, "truncf", "trunc", True)
+lgamma_impl = unary_math_extern(math.lgamma, "lgammaf", "lgamma")
+
+
+# @lower(math.isnan, types.Float)
+def isnan_float_impl(context, builder, sig, args):
+ [val] = args
+ res = is_nan(builder, val)
+ return impl_ret_untracked(context, builder, sig.return_type, res)
+
+# @lower(math.isnan, types.Integer)
+def isnan_int_impl(context, builder, sig, args):
+ res = cgutils.false_bit
+ return impl_ret_untracked(context, builder, sig.return_type, res)
+
+
+# @lower(math.isinf, types.Float)
+def isinf_float_impl(context, builder, sig, args):
+ [val] = args
+ res = is_inf(builder, val)
+ return impl_ret_untracked(context, builder, sig.return_type, res)
+
+# @lower(math.isinf, types.Integer)
+def isinf_int_impl(context, builder, sig, args):
+ res = cgutils.false_bit
+ return impl_ret_untracked(context, builder, sig.return_type, res)
+
+
+# @lower(math.isfinite, types.Float)
+def isfinite_float_impl(context, builder, sig, args):
+ [val] = args
+ res = is_finite(builder, val)
+ return impl_ret_untracked(context, builder, sig.return_type, res)
+
+
+# @lower(math.isfinite, types.Integer)
+def isfinite_int_impl(context, builder, sig, args):
+ res = cgutils.true_bit
+ return impl_ret_untracked(context, builder, sig.return_type, res)
+
+
+# @lower(math.copysign, types.Float, types.Float)
+def copysign_float_impl(context, builder, sig, args):
+ lty = args[0].type
+ mod = builder.module
+ fn = cgutils.get_or_insert_function(mod, llvmlite.ir.FunctionType(lty, (lty, lty)),
+ 'llvm.copysign.%s' % lty.intrinsic_name)
+ res = builder.call(fn, args)
+ return impl_ret_untracked(context, builder, sig.return_type, res)
+
+
+# -----------------------------------------------------------------------------
+
+
+# @lower(math.frexp, types.Float)
+def frexp_impl(context, builder, sig, args):
+ val, = args
+ fltty = context.get_data_type(sig.args[0])
+ intty = context.get_data_type(sig.return_type[1])
+ expptr = cgutils.alloca_once(builder, intty, name='exp')
+ fnty = llvmlite.ir.FunctionType(fltty, (fltty, llvmlite.ir.PointerType(intty)))
+ fname = {
+ "float": "numba_frexpf",
+ "double": "numba_frexp",
+ }[str(fltty)]
+ fn = cgutils.get_or_insert_function(builder.module, fnty, fname)
+ res = builder.call(fn, (val, expptr))
+ res = cgutils.make_anonymous_struct(builder, (res, builder.load(expptr)))
+ return impl_ret_untracked(context, builder, sig.return_type, res)
+
+
+# @lower(math.ldexp, types.Float, types.intc)
+def ldexp_impl(context, builder, sig, args):
+ val, exp = args
+ fltty, intty = map(context.get_data_type, sig.args)
+ fnty = llvmlite.ir.FunctionType(fltty, (fltty, intty))
+ fname = {
+ "float": "numba_ldexpf",
+ "double": "numba_ldexp",
+ }[str(fltty)]
+ fn = cgutils.insert_pure_function(builder.module, fnty, name=fname)
+ res = builder.call(fn, (val, exp))
+ return impl_ret_untracked(context, builder, sig.return_type, res)
+
+
+# -----------------------------------------------------------------------------
+
+
+# @lower(math.atan2, types.int64, types.int64)
+def atan2_s64_impl(context, builder, sig, args):
+ [y, x] = args
+ y = builder.sitofp(y, llvmlite.ir.DoubleType())
+ x = builder.sitofp(x, llvmlite.ir.DoubleType())
+ fsig = signature(types.float64, types.float64, types.float64)
+ return atan2_float_impl(context, builder, fsig, (y, x))
+
+# @lower(math.atan2, types.uint64, types.uint64)
+def atan2_u64_impl(context, builder, sig, args):
+ [y, x] = args
+ y = builder.uitofp(y, llvmlite.ir.DoubleType())
+ x = builder.uitofp(x, llvmlite.ir.DoubleType())
+ fsig = signature(types.float64, types.float64, types.float64)
+ return atan2_float_impl(context, builder, fsig, (y, x))
+
+# @lower(math.atan2, types.Float, types.Float)
+def atan2_float_impl(context, builder, sig, args):
+ assert len(args) == 2
+ mod = builder.module
+ ty = sig.args[0]
+ lty = context.get_value_type(ty)
+ func_name = {
+ types.float32: "atan2f",
+ types.float64: "atan2"
+ }[ty]
+ fnty = llvmlite.ir.FunctionType(lty, (lty, lty))
+ fn = cgutils.insert_pure_function(builder.module, fnty, name=func_name)
+ res = builder.call(fn, args)
+ return impl_ret_untracked(context, builder, sig.return_type, res)
+
+
+# -----------------------------------------------------------------------------
+
+
+# @lower(math.hypot, types.int64, types.int64)
+def hypot_s64_impl(context, builder, sig, args):
+ [x, y] = args
+ y = builder.sitofp(y, llvmlite.ir.DoubleType())
+ x = builder.sitofp(x, llvmlite.ir.DoubleType())
+ fsig = signature(types.float64, types.float64, types.float64)
+ res = hypot_float_impl(context, builder, fsig, (x, y))
+ return impl_ret_untracked(context, builder, sig.return_type, res)
+
+
+# @lower(math.hypot, types.uint64, types.uint64)
+def hypot_u64_impl(context, builder, sig, args):
+ [x, y] = args
+ y = builder.sitofp(y, llvmlite.ir.DoubleType())
+ x = builder.sitofp(x, llvmlite.ir.DoubleType())
+ fsig = signature(types.float64, types.float64, types.float64)
+ res = hypot_float_impl(context, builder, fsig, (x, y))
+ return impl_ret_untracked(context, builder, sig.return_type, res)
+
+
+# @lower(math.hypot, types.Float, types.Float)
+def hypot_float_impl(context, builder, sig, args):
+ xty, yty = sig.args
+ assert xty == yty == sig.return_type
+ x, y = args
+
+ # Windows has alternate names for hypot/hypotf, see
+ # https://msdn.microsoft.com/fr-fr/library/a9yb3dbt%28v=vs.80%29.aspx
+ fname = {
+ types.float32: "_hypotf" if sys.platform == 'win32' else "hypotf",
+ types.float64: "_hypot" if sys.platform == 'win32' else "hypot",
+ }[xty]
+ plat_hypot = types.ExternalFunction(fname, sig)
+
+ if sys.platform == 'win32' and config.MACHINE_BITS == 32:
+ inf = xty(float('inf'))
+
+ def hypot_impl(x, y):
+ if math.isinf(x) or math.isinf(y):
+ return inf
+ return plat_hypot(x, y)
+ else:
+ def hypot_impl(x, y):
+ return plat_hypot(x, y)
+
+ res = context.compile_internal(builder, hypot_impl, sig, args)
+ return impl_ret_untracked(context, builder, sig.return_type, res)
+
+
+# -----------------------------------------------------------------------------
+
+# @lower(math.radians, types.Float)
+def radians_float_impl(context, builder, sig, args):
+ [x] = args
+ coef = context.get_constant(sig.return_type, math.pi / 180)
+ res = builder.fmul(x, coef)
+ return impl_ret_untracked(context, builder, sig.return_type, res)
+
+unary_math_int_impl(math.radians, radians_float_impl)
+
+# -----------------------------------------------------------------------------
+
+# @lower(math.degrees, types.Float)
+def degrees_float_impl(context, builder, sig, args):
+ [x] = args
+ coef = context.get_constant(sig.return_type, 180 / math.pi)
+ res = builder.fmul(x, coef)
+ return impl_ret_untracked(context, builder, sig.return_type, res)
+
+unary_math_int_impl(math.degrees, degrees_float_impl)
+
+# -----------------------------------------------------------------------------
+
+# @lower(math.pow, types.Float, types.Float)
+# @lower(math.pow, types.Float, types.Integer)
+def pow_impl(context, builder, sig, args):
+ impl = context.get_function(operator.pow, sig)
+ return impl(builder, args)
+
+# -----------------------------------------------------------------------------
+
+
+def _unsigned(T):
+ """Convert integer to unsigned integer of equivalent width."""
+ pass
+
+@overload(_unsigned)
+def _unsigned_impl(T):
+ if T in types.unsigned_domain:
+ return lambda T: T
+ elif T in types.signed_domain:
+ newT = getattr(types, 'uint{}'.format(T.bitwidth))
+ return lambda T: newT(T)
+
+
+def gcd_impl(context, builder, sig, args):
+ xty, yty = sig.args
+ assert xty == yty == sig.return_type
+ x, y = args
+
+ def gcd(a, b):
+ """
+ Stein's algorithm, heavily cribbed from Julia implementation.
+ """
+ T = type(a)
+ if a == 0: return abs(b)
+ if b == 0: return abs(a)
+ za = trailing_zeros(a)
+ zb = trailing_zeros(b)
+ k = min(za, zb)
+ # Uses np.*_shift instead of operators due to return types
+ u = _unsigned(abs(np.right_shift(a, za)))
+ v = _unsigned(abs(np.right_shift(b, zb)))
+ while u != v:
+ if u > v:
+ u, v = v, u
+ v -= u
+ v = np.right_shift(v, trailing_zeros(v))
+ r = np.left_shift(T(u), k)
+ return r
+
+ res = context.compile_internal(builder, gcd, sig, args)
+ return impl_ret_untracked(context, builder, sig.return_type, res)
+
+
+# lower(math.gcd, types.Integer, types.Integer)(gcd_impl)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/np/math/numbers.py b/tool_server/.venv/lib/python3.12/site-packages/numba/np/math/numbers.py
new file mode 100644
index 0000000000000000000000000000000000000000..2e1cda9c279cd62aed52eb9a785ef5a10eb3a8d6
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/np/math/numbers.py
@@ -0,0 +1,1395 @@
+import math
+import numbers
+
+import numpy as np
+
+from llvmlite import ir
+from llvmlite.ir import Constant
+
+from numba.core.imputils import impl_ret_untracked
+from numba.core import typing, types, errors, cgutils
+from numba.cpython.unsafe.numbers import viewer
+
+def _int_arith_flags(rettype):
+ """
+ Return the modifier flags for integer arithmetic.
+ """
+ if rettype.signed:
+ # Ignore the effects of signed overflow. This is important for
+ # optimization of some indexing operations. For example
+ # array[i+1] could see `i+1` trigger a signed overflow and
+ # give a negative number. With Python's indexing, a negative
+ # index is treated differently: its resolution has a runtime cost.
+ # Telling LLVM to ignore signed overflows allows it to optimize
+ # away the check for a negative `i+1` if it knows `i` is positive.
+ return ['nsw']
+ else:
+ return []
+
+
+def int_add_impl(context, builder, sig, args):
+ [va, vb] = args
+ [ta, tb] = sig.args
+ a = context.cast(builder, va, ta, sig.return_type)
+ b = context.cast(builder, vb, tb, sig.return_type)
+ res = builder.add(a, b, flags=_int_arith_flags(sig.return_type))
+ return impl_ret_untracked(context, builder, sig.return_type, res)
+
+
+def int_sub_impl(context, builder, sig, args):
+ [va, vb] = args
+ [ta, tb] = sig.args
+ a = context.cast(builder, va, ta, sig.return_type)
+ b = context.cast(builder, vb, tb, sig.return_type)
+ res = builder.sub(a, b, flags=_int_arith_flags(sig.return_type))
+ return impl_ret_untracked(context, builder, sig.return_type, res)
+
+
+def int_mul_impl(context, builder, sig, args):
+ [va, vb] = args
+ [ta, tb] = sig.args
+ a = context.cast(builder, va, ta, sig.return_type)
+ b = context.cast(builder, vb, tb, sig.return_type)
+ res = builder.mul(a, b, flags=_int_arith_flags(sig.return_type))
+ return impl_ret_untracked(context, builder, sig.return_type, res)
+
+
+def int_divmod_signed(context, builder, ty, x, y):
+ """
+ Reference Objects/intobject.c
+ xdivy = x / y;
+ xmody = (long)(x - (unsigned long)xdivy * y);
+ /* If the signs of x and y differ, and the remainder is non-0,
+ * C89 doesn't define whether xdivy is now the floor or the
+ * ceiling of the infinitely precise quotient. We want the floor,
+ * and we have it iff the remainder's sign matches y's.
+ */
+ if (xmody && ((y ^ xmody) < 0) /* i.e. and signs differ */) {
+ xmody += y;
+ --xdivy;
+ assert(xmody && ((y ^ xmody) >= 0));
+ }
+ *p_xdivy = xdivy;
+ *p_xmody = xmody;
+ """
+ assert x.type == y.type
+
+ ZERO = y.type(0)
+ ONE = y.type(1)
+
+ # NOTE: On x86 at least, dividing the lowest representable integer
+ # (e.g. 0x80000000 for int32) by -1 causes a SIFGPE (division overflow),
+ # causing the process to crash.
+ # We return 0, 0 instead (more or less like Numpy).
+
+ resdiv = cgutils.alloca_once_value(builder, ZERO)
+ resmod = cgutils.alloca_once_value(builder, ZERO)
+
+ is_overflow = builder.and_(
+ builder.icmp_signed('==', x, x.type(ty.minval)),
+ builder.icmp_signed('==', y, y.type(-1)))
+
+ with builder.if_then(builder.not_(is_overflow), likely=True):
+ # Note LLVM will optimize this to a single divmod instruction,
+ # if available on the target CPU (e.g. x86).
+ xdivy = builder.sdiv(x, y)
+ xmody = builder.srem(x, y)
+
+ y_xor_xmody_ltz = builder.icmp_signed('<', builder.xor(y, xmody), ZERO)
+ xmody_istrue = builder.icmp_signed('!=', xmody, ZERO)
+ cond = builder.and_(xmody_istrue, y_xor_xmody_ltz)
+
+ with builder.if_else(cond) as (if_different_signs, if_same_signs):
+ with if_same_signs:
+ builder.store(xdivy, resdiv)
+ builder.store(xmody, resmod)
+
+ with if_different_signs:
+ builder.store(builder.sub(xdivy, ONE), resdiv)
+ builder.store(builder.add(xmody, y), resmod)
+
+ return builder.load(resdiv), builder.load(resmod)
+
+
+def int_divmod(context, builder, ty, x, y):
+ """
+ Integer divmod(x, y). The caller must ensure that y != 0.
+ """
+ if ty.signed:
+ return int_divmod_signed(context, builder, ty, x, y)
+ else:
+ return builder.udiv(x, y), builder.urem(x, y)
+
+
+def _int_divmod_impl(context, builder, sig, args, zerodiv_message):
+ va, vb = args
+ ta, tb = sig.args
+
+ ty = sig.return_type
+ if isinstance(ty, types.UniTuple):
+ ty = ty.dtype
+ a = context.cast(builder, va, ta, ty)
+ b = context.cast(builder, vb, tb, ty)
+ quot = cgutils.alloca_once(builder, a.type, name="quot")
+ rem = cgutils.alloca_once(builder, a.type, name="rem")
+
+ with builder.if_else(cgutils.is_scalar_zero(builder, b), likely=False
+ ) as (if_zero, if_non_zero):
+ with if_zero:
+ if not context.error_model.fp_zero_division(
+ builder, (zerodiv_message,)):
+ # No exception raised => return 0
+ # XXX We should also set the FPU exception status, but
+ # there's no easy way to do that from LLVM.
+ builder.store(b, quot)
+ builder.store(b, rem)
+ with if_non_zero:
+ q, r = int_divmod(context, builder, ty, a, b)
+ builder.store(q, quot)
+ builder.store(r, rem)
+
+ return quot, rem
+
+
+# @lower_builtin(divmod, types.Integer, types.Integer)
+def int_divmod_impl(context, builder, sig, args):
+ quot, rem = _int_divmod_impl(context, builder, sig, args,
+ "integer divmod by zero")
+
+ return cgutils.pack_array(builder,
+ (builder.load(quot), builder.load(rem)))
+
+
+# @lower_builtin(operator.floordiv, types.Integer, types.Integer)
+# @lower_builtin(operator.ifloordiv, types.Integer, types.Integer)
+def int_floordiv_impl(context, builder, sig, args):
+ quot, rem = _int_divmod_impl(context, builder, sig, args,
+ "integer division by zero")
+ return builder.load(quot)
+
+
+# @lower_builtin(operator.truediv, types.Integer, types.Integer)
+# @lower_builtin(operator.itruediv, types.Integer, types.Integer)
+def int_truediv_impl(context, builder, sig, args):
+ [va, vb] = args
+ [ta, tb] = sig.args
+ a = context.cast(builder, va, ta, sig.return_type)
+ b = context.cast(builder, vb, tb, sig.return_type)
+ with cgutils.if_zero(builder, b):
+ context.error_model.fp_zero_division(builder, ("division by zero",))
+ res = builder.fdiv(a, b)
+ return impl_ret_untracked(context, builder, sig.return_type, res)
+
+
+# @lower_builtin(operator.mod, types.Integer, types.Integer)
+# @lower_builtin(operator.imod, types.Integer, types.Integer)
+def int_rem_impl(context, builder, sig, args):
+ quot, rem = _int_divmod_impl(context, builder, sig, args,
+ "integer modulo by zero")
+ return builder.load(rem)
+
+
+def _get_power_zerodiv_return(context, return_type):
+ if (isinstance(return_type, types.Integer)
+ and not context.error_model.raise_on_fp_zero_division):
+ # If not raising, return 0x8000... when computing 0 **
+ return -1 << (return_type.bitwidth - 1)
+ else:
+ return False
+
+
+def int_power_impl(context, builder, sig, args):
+ """
+ a ^ b, where a is an integer or real, and b an integer
+ """
+ is_integer = isinstance(sig.args[0], types.Integer)
+ tp = sig.return_type
+ zerodiv_return = _get_power_zerodiv_return(context, tp)
+
+ def int_power(a, b):
+ # Ensure computations are done with a large enough width
+ r = tp(1)
+ a = tp(a)
+ if b < 0:
+ invert = True
+ exp = -b
+ if exp < 0:
+ raise OverflowError
+ if is_integer:
+ if a == 0:
+ if zerodiv_return:
+ return zerodiv_return
+ else:
+ raise ZeroDivisionError("0 cannot be raised to a negative power")
+ if a != 1 and a != -1:
+ return 0
+ else:
+ invert = False
+ exp = b
+ if exp > 0x10000:
+ # Optimization cutoff: fallback on the generic algorithm
+ return math.pow(a, float(b))
+ while exp != 0:
+ if exp & 1:
+ r *= a
+ exp >>= 1
+ a *= a
+
+ return 1.0 / r if invert else r
+
+ res = context.compile_internal(builder, int_power, sig, args)
+ return impl_ret_untracked(context, builder, sig.return_type, res)
+
+
+# @lower_builtin(operator.pow, types.Integer, types.IntegerLiteral)
+# @lower_builtin(operator.ipow, types.Integer, types.IntegerLiteral)
+# @lower_builtin(operator.pow, types.Float, types.IntegerLiteral)
+# @lower_builtin(operator.ipow, types.Float, types.IntegerLiteral)
+def static_power_impl(context, builder, sig, args):
+ """
+ a ^ b, where a is an integer or real, and b a constant integer
+ """
+ exp = sig.args[1].value
+ if not isinstance(exp, numbers.Integral):
+ raise NotImplementedError
+ if abs(exp) > 0x10000:
+ # Optimization cutoff: fallback on the generic algorithm above
+ raise NotImplementedError
+ invert = exp < 0
+ exp = abs(exp)
+
+ tp = sig.return_type
+ is_integer = isinstance(tp, types.Integer)
+ zerodiv_return = _get_power_zerodiv_return(context, tp)
+
+ val = context.cast(builder, args[0], sig.args[0], tp)
+ lty = val.type
+
+ def mul(a, b):
+ if is_integer:
+ return builder.mul(a, b)
+ else:
+ return builder.fmul(a, b)
+
+ # Unroll the exponentiation loop
+ res = lty(1)
+ a = val
+ while exp != 0:
+ if exp & 1:
+ res = mul(res, val)
+ exp >>= 1
+ val = mul(val, val)
+
+ if invert:
+ # If the exponent was negative, fix the result by inverting it
+ if is_integer:
+ # Integer inversion
+ def invert_impl(a):
+ if a == 0:
+ if zerodiv_return:
+ return zerodiv_return
+ else:
+ raise ZeroDivisionError("0 cannot be raised to a negative power")
+ if a != 1 and a != -1:
+ return 0
+ else:
+ return a
+
+ else:
+ # Real inversion
+ def invert_impl(a):
+ return 1.0 / a
+
+ res = context.compile_internal(builder, invert_impl,
+ typing.signature(tp, tp), (res,))
+
+ return res
+
+
+def int_slt_impl(context, builder, sig, args):
+ res = builder.icmp_signed('<', *args)
+ return impl_ret_untracked(context, builder, sig.return_type, res)
+
+
+def int_sle_impl(context, builder, sig, args):
+ res = builder.icmp_signed('<=', *args)
+ return impl_ret_untracked(context, builder, sig.return_type, res)
+
+
+def int_sgt_impl(context, builder, sig, args):
+ res = builder.icmp_signed('>', *args)
+ return impl_ret_untracked(context, builder, sig.return_type, res)
+
+
+def int_sge_impl(context, builder, sig, args):
+ res = builder.icmp_signed('>=', *args)
+ return impl_ret_untracked(context, builder, sig.return_type, res)
+
+
+def int_ult_impl(context, builder, sig, args):
+ res = builder.icmp_unsigned('<', *args)
+ return impl_ret_untracked(context, builder, sig.return_type, res)
+
+
+def int_ule_impl(context, builder, sig, args):
+ res = builder.icmp_unsigned('<=', *args)
+ return impl_ret_untracked(context, builder, sig.return_type, res)
+
+
+def int_ugt_impl(context, builder, sig, args):
+ res = builder.icmp_unsigned('>', *args)
+ return impl_ret_untracked(context, builder, sig.return_type, res)
+
+
+def int_uge_impl(context, builder, sig, args):
+ res = builder.icmp_unsigned('>=', *args)
+ return impl_ret_untracked(context, builder, sig.return_type, res)
+
+
+def int_eq_impl(context, builder, sig, args):
+ res = builder.icmp_unsigned('==', *args)
+ return impl_ret_untracked(context, builder, sig.return_type, res)
+
+
+def int_ne_impl(context, builder, sig, args):
+ res = builder.icmp_unsigned('!=', *args)
+ return impl_ret_untracked(context, builder, sig.return_type, res)
+
+
+def int_signed_unsigned_cmp(op):
+ def impl(context, builder, sig, args):
+ (left, right) = args
+ # This code is translated from the NumPy source.
+ # What we're going to do is divide the range of a signed value at zero.
+ # If the signed value is less than zero, then we can treat zero as the
+ # unsigned value since the unsigned value is necessarily zero or larger
+ # and any signed comparison between a negative value and zero/infinity
+ # will yield the same result. If the signed value is greater than or
+ # equal to zero, then we can safely cast it to an unsigned value and do
+ # the expected unsigned-unsigned comparison operation.
+ # Original: https://github.com/numpy/numpy/pull/23713
+ cmp_zero = builder.icmp_signed('<', left, Constant(left.type, 0))
+ lt_zero = builder.icmp_signed(op, left, Constant(left.type, 0))
+ ge_zero = builder.icmp_unsigned(op, left, right)
+ res = builder.select(cmp_zero, lt_zero, ge_zero)
+ return impl_ret_untracked(context, builder, sig.return_type, res)
+ return impl
+
+
+def int_unsigned_signed_cmp(op):
+ def impl(context, builder, sig, args):
+ (left, right) = args
+ # See the function `int_signed_unsigned_cmp` for implementation notes.
+ cmp_zero = builder.icmp_signed('<', right, Constant(right.type, 0))
+ lt_zero = builder.icmp_signed(op, Constant(right.type, 0), right)
+ ge_zero = builder.icmp_unsigned(op, left, right)
+ res = builder.select(cmp_zero, lt_zero, ge_zero)
+ return impl_ret_untracked(context, builder, sig.return_type, res)
+ return impl
+
+
+def int_abs_impl(context, builder, sig, args):
+ [x] = args
+ ZERO = Constant(x.type, None)
+ ltz = builder.icmp_signed('<', x, ZERO)
+ negated = builder.neg(x)
+ res = builder.select(ltz, negated, x)
+ return impl_ret_untracked(context, builder, sig.return_type, res)
+
+
+def identity_impl(context, builder, sig, args):
+ [x] = args
+ return impl_ret_untracked(context, builder, sig.return_type, x)
+
+
+def uint_abs_impl(context, builder, sig, args):
+ [x] = args
+ return impl_ret_untracked(context, builder, sig.return_type, x)
+
+
+def int_shl_impl(context, builder, sig, args):
+ [valty, amtty] = sig.args
+ [val, amt] = args
+ val = context.cast(builder, val, valty, sig.return_type)
+ amt = context.cast(builder, amt, amtty, sig.return_type)
+ res = builder.shl(val, amt)
+ return impl_ret_untracked(context, builder, sig.return_type, res)
+
+
+def int_shr_impl(context, builder, sig, args):
+ [valty, amtty] = sig.args
+ [val, amt] = args
+ val = context.cast(builder, val, valty, sig.return_type)
+ amt = context.cast(builder, amt, amtty, sig.return_type)
+ if sig.return_type.signed:
+ res = builder.ashr(val, amt)
+ else:
+ res = builder.lshr(val, amt)
+ return impl_ret_untracked(context, builder, sig.return_type, res)
+
+
+def int_and_impl(context, builder, sig, args):
+ [at, bt] = sig.args
+ [av, bv] = args
+ cav = context.cast(builder, av, at, sig.return_type)
+ cbc = context.cast(builder, bv, bt, sig.return_type)
+ res = builder.and_(cav, cbc)
+ return impl_ret_untracked(context, builder, sig.return_type, res)
+
+
+def int_or_impl(context, builder, sig, args):
+ [at, bt] = sig.args
+ [av, bv] = args
+ cav = context.cast(builder, av, at, sig.return_type)
+ cbc = context.cast(builder, bv, bt, sig.return_type)
+ res = builder.or_(cav, cbc)
+ return impl_ret_untracked(context, builder, sig.return_type, res)
+
+
+def int_xor_impl(context, builder, sig, args):
+ [at, bt] = sig.args
+ [av, bv] = args
+ cav = context.cast(builder, av, at, sig.return_type)
+ cbc = context.cast(builder, bv, bt, sig.return_type)
+ res = builder.xor(cav, cbc)
+ return impl_ret_untracked(context, builder, sig.return_type, res)
+
+
+def int_negate_impl(context, builder, sig, args):
+ [typ] = sig.args
+ [val] = args
+ # Negate before upcasting, for unsigned numbers
+ res = builder.neg(val)
+ res = context.cast(builder, res, typ, sig.return_type)
+ return impl_ret_untracked(context, builder, sig.return_type, res)
+
+
+def int_positive_impl(context, builder, sig, args):
+ [typ] = sig.args
+ [val] = args
+ res = context.cast(builder, val, typ, sig.return_type)
+ return impl_ret_untracked(context, builder, sig.return_type, res)
+
+
+def int_invert_impl(context, builder, sig, args):
+ [typ] = sig.args
+ [val] = args
+ # Invert before upcasting, for unsigned numbers
+ res = builder.xor(val, Constant(val.type, int('1' * val.type.width, 2)))
+ res = context.cast(builder, res, typ, sig.return_type)
+ return impl_ret_untracked(context, builder, sig.return_type, res)
+
+
+def int_sign_impl(context, builder, sig, args):
+ """
+ np.sign(int)
+ """
+ [x] = args
+ POS = Constant(x.type, 1)
+ NEG = Constant(x.type, -1)
+ ZERO = Constant(x.type, 0)
+
+ cmp_zero = builder.icmp_unsigned('==', x, ZERO)
+ cmp_pos = builder.icmp_signed('>', x, ZERO)
+
+ presult = cgutils.alloca_once(builder, x.type)
+
+ bb_zero = builder.append_basic_block(".zero")
+ bb_postest = builder.append_basic_block(".postest")
+ bb_pos = builder.append_basic_block(".pos")
+ bb_neg = builder.append_basic_block(".neg")
+ bb_exit = builder.append_basic_block(".exit")
+
+ builder.cbranch(cmp_zero, bb_zero, bb_postest)
+
+ with builder.goto_block(bb_zero):
+ builder.store(ZERO, presult)
+ builder.branch(bb_exit)
+
+ with builder.goto_block(bb_postest):
+ builder.cbranch(cmp_pos, bb_pos, bb_neg)
+
+ with builder.goto_block(bb_pos):
+ builder.store(POS, presult)
+ builder.branch(bb_exit)
+
+ with builder.goto_block(bb_neg):
+ builder.store(NEG, presult)
+ builder.branch(bb_exit)
+
+ builder.position_at_end(bb_exit)
+ res = builder.load(presult)
+ return impl_ret_untracked(context, builder, sig.return_type, res)
+
+
+def bool_negate_impl(context, builder, sig, args):
+ [typ] = sig.args
+ [val] = args
+ res = context.cast(builder, val, typ, sig.return_type)
+ res = builder.neg(res)
+ return impl_ret_untracked(context, builder, sig.return_type, res)
+
+
+def bool_unary_positive_impl(context, builder, sig, args):
+ [typ] = sig.args
+ [val] = args
+ res = context.cast(builder, val, typ, sig.return_type)
+ return impl_ret_untracked(context, builder, sig.return_type, res)
+
+
+# lower_builtin(operator.eq, types.boolean, types.boolean)(int_eq_impl)
+# lower_builtin(operator.ne, types.boolean, types.boolean)(int_ne_impl)
+# lower_builtin(operator.lt, types.boolean, types.boolean)(int_ult_impl)
+# lower_builtin(operator.le, types.boolean, types.boolean)(int_ule_impl)
+# lower_builtin(operator.gt, types.boolean, types.boolean)(int_ugt_impl)
+# lower_builtin(operator.ge, types.boolean, types.boolean)(int_uge_impl)
+# lower_builtin(operator.neg, types.boolean)(bool_negate_impl)
+# lower_builtin(operator.pos, types.boolean)(bool_unary_positive_impl)
+
+
+# def _implement_integer_operators():
+# ty = types.Integer
+
+# lower_builtin(operator.add, ty, ty)(int_add_impl)
+# lower_builtin(operator.iadd, ty, ty)(int_add_impl)
+# lower_builtin(operator.sub, ty, ty)(int_sub_impl)
+# lower_builtin(operator.isub, ty, ty)(int_sub_impl)
+# lower_builtin(operator.mul, ty, ty)(int_mul_impl)
+# lower_builtin(operator.imul, ty, ty)(int_mul_impl)
+# lower_builtin(operator.eq, ty, ty)(int_eq_impl)
+# lower_builtin(operator.ne, ty, ty)(int_ne_impl)
+
+# lower_builtin(operator.lshift, ty, ty)(int_shl_impl)
+# lower_builtin(operator.ilshift, ty, ty)(int_shl_impl)
+# lower_builtin(operator.rshift, ty, ty)(int_shr_impl)
+# lower_builtin(operator.irshift, ty, ty)(int_shr_impl)
+
+# lower_builtin(operator.neg, ty)(int_negate_impl)
+# lower_builtin(operator.pos, ty)(int_positive_impl)
+
+# lower_builtin(operator.pow, ty, ty)(int_power_impl)
+# lower_builtin(operator.ipow, ty, ty)(int_power_impl)
+# lower_builtin(pow, ty, ty)(int_power_impl)
+
+# for ty in types.unsigned_domain:
+# lower_builtin(operator.lt, ty, ty)(int_ult_impl)
+# lower_builtin(operator.le, ty, ty)(int_ule_impl)
+# lower_builtin(operator.gt, ty, ty)(int_ugt_impl)
+# lower_builtin(operator.ge, ty, ty)(int_uge_impl)
+# lower_builtin(operator.pow, types.Float, ty)(int_power_impl)
+# lower_builtin(operator.ipow, types.Float, ty)(int_power_impl)
+# lower_builtin(pow, types.Float, ty)(int_power_impl)
+# lower_builtin(abs, ty)(uint_abs_impl)
+
+# lower_builtin(operator.lt, types.IntegerLiteral, types.IntegerLiteral)(int_slt_impl)
+# lower_builtin(operator.gt, types.IntegerLiteral, types.IntegerLiteral)(int_slt_impl)
+# lower_builtin(operator.le, types.IntegerLiteral, types.IntegerLiteral)(int_slt_impl)
+# lower_builtin(operator.ge, types.IntegerLiteral, types.IntegerLiteral)(int_slt_impl)
+# for ty in types.signed_domain:
+# lower_builtin(operator.lt, ty, ty)(int_slt_impl)
+# lower_builtin(operator.le, ty, ty)(int_sle_impl)
+# lower_builtin(operator.gt, ty, ty)(int_sgt_impl)
+# lower_builtin(operator.ge, ty, ty)(int_sge_impl)
+# lower_builtin(operator.pow, types.Float, ty)(int_power_impl)
+# lower_builtin(operator.ipow, types.Float, ty)(int_power_impl)
+# lower_builtin(pow, types.Float, ty)(int_power_impl)
+# lower_builtin(abs, ty)(int_abs_impl)
+
+# def _implement_bitwise_operators():
+# for ty in (types.Boolean, types.Integer):
+# lower_builtin(operator.and_, ty, ty)(int_and_impl)
+# lower_builtin(operator.iand, ty, ty)(int_and_impl)
+# lower_builtin(operator.or_, ty, ty)(int_or_impl)
+# lower_builtin(operator.ior, ty, ty)(int_or_impl)
+# lower_builtin(operator.xor, ty, ty)(int_xor_impl)
+# lower_builtin(operator.ixor, ty, ty)(int_xor_impl)
+
+# lower_builtin(operator.invert, ty)(int_invert_impl)
+
+# _implement_integer_operators()
+
+# _implement_bitwise_operators()
+
+
+def real_add_impl(context, builder, sig, args):
+ res = builder.fadd(*args)
+ return impl_ret_untracked(context, builder, sig.return_type, res)
+
+
+def real_sub_impl(context, builder, sig, args):
+ res = builder.fsub(*args)
+ return impl_ret_untracked(context, builder, sig.return_type, res)
+
+
+def real_mul_impl(context, builder, sig, args):
+ res = builder.fmul(*args)
+ return impl_ret_untracked(context, builder, sig.return_type, res)
+
+
+def real_div_impl(context, builder, sig, args):
+ with cgutils.if_zero(builder, args[1]):
+ context.error_model.fp_zero_division(builder, ("division by zero",))
+ res = builder.fdiv(*args)
+ return impl_ret_untracked(context, builder, sig.return_type, res)
+
+
+def real_divmod(context, builder, x, y):
+ assert x.type == y.type
+ floatty = x.type
+
+ module = builder.module
+ fname = context.mangler(".numba.python.rem", [x.type])
+ fnty = ir.FunctionType(floatty, (floatty, floatty, ir.PointerType(floatty)))
+ fn = cgutils.get_or_insert_function(module, fnty, fname)
+
+ if fn.is_declaration:
+ fn.linkage = 'linkonce_odr'
+ fnbuilder = ir.IRBuilder(fn.append_basic_block('entry'))
+ fx, fy, pmod = fn.args
+ div, mod = real_divmod_func_body(context, fnbuilder, fx, fy)
+ fnbuilder.store(mod, pmod)
+ fnbuilder.ret(div)
+
+ pmod = cgutils.alloca_once(builder, floatty)
+ quotient = builder.call(fn, (x, y, pmod))
+ return quotient, builder.load(pmod)
+
+
+def real_divmod_func_body(context, builder, vx, wx):
+ # Reference Objects/floatobject.c
+ #
+ # float_divmod(PyObject *v, PyObject *w)
+ # {
+ # double vx, wx;
+ # double div, mod, floordiv;
+ # CONVERT_TO_DOUBLE(v, vx);
+ # CONVERT_TO_DOUBLE(w, wx);
+ # mod = fmod(vx, wx);
+ # /* fmod is typically exact, so vx-mod is *mathematically* an
+ # exact multiple of wx. But this is fp arithmetic, and fp
+ # vx - mod is an approximation; the result is that div may
+ # not be an exact integral value after the division, although
+ # it will always be very close to one.
+ # */
+ # div = (vx - mod) / wx;
+ # if (mod) {
+ # /* ensure the remainder has the same sign as the denominator */
+ # if ((wx < 0) != (mod < 0)) {
+ # mod += wx;
+ # div -= 1.0;
+ # }
+ # }
+ # else {
+ # /* the remainder is zero, and in the presence of signed zeroes
+ # fmod returns different results across platforms; ensure
+ # it has the same sign as the denominator; we'd like to do
+ # "mod = wx * 0.0", but that may get optimized away */
+ # mod *= mod; /* hide "mod = +0" from optimizer */
+ # if (wx < 0.0)
+ # mod = -mod;
+ # }
+ # /* snap quotient to nearest integral value */
+ # if (div) {
+ # floordiv = floor(div);
+ # if (div - floordiv > 0.5)
+ # floordiv += 1.0;
+ # }
+ # else {
+ # /* div is zero - get the same sign as the true quotient */
+ # div *= div; /* hide "div = +0" from optimizers */
+ # floordiv = div * vx / wx; /* zero w/ sign of vx/wx */
+ # }
+ # return Py_BuildValue("(dd)", floordiv, mod);
+ # }
+ pmod = cgutils.alloca_once(builder, vx.type)
+ pdiv = cgutils.alloca_once(builder, vx.type)
+ pfloordiv = cgutils.alloca_once(builder, vx.type)
+
+ mod = builder.frem(vx, wx)
+ div = builder.fdiv(builder.fsub(vx, mod), wx)
+
+ builder.store(mod, pmod)
+ builder.store(div, pdiv)
+
+ # Note the use of negative zero for proper negating with `ZERO - x`
+ ZERO = vx.type(0.0)
+ NZERO = vx.type(-0.0)
+ ONE = vx.type(1.0)
+ mod_istrue = builder.fcmp_unordered('!=', mod, ZERO)
+ wx_ltz = builder.fcmp_ordered('<', wx, ZERO)
+ mod_ltz = builder.fcmp_ordered('<', mod, ZERO)
+
+ with builder.if_else(mod_istrue, likely=True) as (if_nonzero_mod, if_zero_mod):
+ with if_nonzero_mod:
+ # `mod` is non-zero or NaN
+ # Ensure the remainder has the same sign as the denominator
+ wx_ltz_ne_mod_ltz = builder.icmp_unsigned('!=', wx_ltz, mod_ltz)
+
+ with builder.if_then(wx_ltz_ne_mod_ltz):
+ builder.store(builder.fsub(div, ONE), pdiv)
+ builder.store(builder.fadd(mod, wx), pmod)
+
+ with if_zero_mod:
+ # `mod` is zero, select the proper sign depending on
+ # the denominator's sign
+ mod = builder.select(wx_ltz, NZERO, ZERO)
+ builder.store(mod, pmod)
+
+ del mod, div
+
+ div = builder.load(pdiv)
+ div_istrue = builder.fcmp_ordered('!=', div, ZERO)
+
+ with builder.if_then(div_istrue):
+ realtypemap = {'float': types.float32,
+ 'double': types.float64}
+ realtype = realtypemap[str(wx.type)]
+ floorfn = context.get_function(math.floor,
+ typing.signature(realtype, realtype))
+ floordiv = floorfn(builder, [div])
+ floordivdiff = builder.fsub(div, floordiv)
+ floordivincr = builder.fadd(floordiv, ONE)
+ HALF = Constant(wx.type, 0.5)
+ pred = builder.fcmp_ordered('>', floordivdiff, HALF)
+ floordiv = builder.select(pred, floordivincr, floordiv)
+ builder.store(floordiv, pfloordiv)
+
+ with cgutils.ifnot(builder, div_istrue):
+ div = builder.fmul(div, div)
+ builder.store(div, pdiv)
+ floordiv = builder.fdiv(builder.fmul(div, vx), wx)
+ builder.store(floordiv, pfloordiv)
+
+ return builder.load(pfloordiv), builder.load(pmod)
+
+
+# @lower_builtin(divmod, types.Float, types.Float)
+def real_divmod_impl(context, builder, sig, args, loc=None):
+ x, y = args
+ quot = cgutils.alloca_once(builder, x.type, name="quot")
+ rem = cgutils.alloca_once(builder, x.type, name="rem")
+
+ with builder.if_else(cgutils.is_scalar_zero(builder, y), likely=False
+ ) as (if_zero, if_non_zero):
+ with if_zero:
+ if not context.error_model.fp_zero_division(
+ builder, ("modulo by zero",), loc):
+ # No exception raised => compute the nan result,
+ # and set the FP exception word for Numpy warnings.
+ q = builder.fdiv(x, y)
+ r = builder.frem(x, y)
+ builder.store(q, quot)
+ builder.store(r, rem)
+ with if_non_zero:
+ q, r = real_divmod(context, builder, x, y)
+ builder.store(q, quot)
+ builder.store(r, rem)
+
+ return cgutils.pack_array(builder,
+ (builder.load(quot), builder.load(rem)))
+
+
+def real_mod_impl(context, builder, sig, args, loc=None):
+ x, y = args
+ res = cgutils.alloca_once(builder, x.type)
+ with builder.if_else(cgutils.is_scalar_zero(builder, y), likely=False
+ ) as (if_zero, if_non_zero):
+ with if_zero:
+ if not context.error_model.fp_zero_division(
+ builder, ("modulo by zero",), loc):
+ # No exception raised => compute the nan result,
+ # and set the FP exception word for Numpy warnings.
+ rem = builder.frem(x, y)
+ builder.store(rem, res)
+ with if_non_zero:
+ _, rem = real_divmod(context, builder, x, y)
+ builder.store(rem, res)
+ return impl_ret_untracked(context, builder, sig.return_type,
+ builder.load(res))
+
+
+def real_floordiv_impl(context, builder, sig, args, loc=None):
+ x, y = args
+ res = cgutils.alloca_once(builder, x.type)
+ with builder.if_else(cgutils.is_scalar_zero(builder, y), likely=False
+ ) as (if_zero, if_non_zero):
+ with if_zero:
+ if not context.error_model.fp_zero_division(
+ builder, ("division by zero",), loc):
+ # No exception raised => compute the +/-inf or nan result,
+ # and set the FP exception word for Numpy warnings.
+ quot = builder.fdiv(x, y)
+ builder.store(quot, res)
+ with if_non_zero:
+ quot, _ = real_divmod(context, builder, x, y)
+ builder.store(quot, res)
+ return impl_ret_untracked(context, builder, sig.return_type,
+ builder.load(res))
+
+
+def real_power_impl(context, builder, sig, args):
+ x, y = args
+ module = builder.module
+ if context.implement_powi_as_math_call:
+ imp = context.get_function(math.pow, sig)
+ res = imp(builder, args)
+ else:
+ fn = module.declare_intrinsic('llvm.pow', [y.type])
+ res = builder.call(fn, (x, y))
+ return impl_ret_untracked(context, builder, sig.return_type, res)
+
+
+def real_lt_impl(context, builder, sig, args):
+ res = builder.fcmp_ordered('<', *args)
+ return impl_ret_untracked(context, builder, sig.return_type, res)
+
+
+def real_le_impl(context, builder, sig, args):
+ res = builder.fcmp_ordered('<=', *args)
+ return impl_ret_untracked(context, builder, sig.return_type, res)
+
+
+def real_gt_impl(context, builder, sig, args):
+ res = builder.fcmp_ordered('>', *args)
+ return impl_ret_untracked(context, builder, sig.return_type, res)
+
+
+def real_ge_impl(context, builder, sig, args):
+ res = builder.fcmp_ordered('>=', *args)
+ return impl_ret_untracked(context, builder, sig.return_type, res)
+
+
+def real_eq_impl(context, builder, sig, args):
+ res = builder.fcmp_ordered('==', *args)
+ return impl_ret_untracked(context, builder, sig.return_type, res)
+
+
+def real_ne_impl(context, builder, sig, args):
+ res = builder.fcmp_unordered('!=', *args)
+ return impl_ret_untracked(context, builder, sig.return_type, res)
+
+
+def real_abs_impl(context, builder, sig, args):
+ [ty] = sig.args
+ sig = typing.signature(ty, ty)
+ impl = context.get_function(math.fabs, sig)
+ return impl(builder, args)
+
+
+def real_negate_impl(context, builder, sig, args):
+ from numba.cpython import mathimpl
+ res = mathimpl.negate_real(builder, args[0])
+ return impl_ret_untracked(context, builder, sig.return_type, res)
+
+
+def real_positive_impl(context, builder, sig, args):
+ [typ] = sig.args
+ [val] = args
+ res = context.cast(builder, val, typ, sig.return_type)
+ return impl_ret_untracked(context, builder, sig.return_type, res)
+
+
+def real_sign_impl(context, builder, sig, args):
+ """
+ np.sign(float)
+ """
+ [x] = args
+ POS = Constant(x.type, 1)
+ NEG = Constant(x.type, -1)
+ ZERO = Constant(x.type, 0)
+
+ presult = cgutils.alloca_once(builder, x.type)
+
+ is_pos = builder.fcmp_ordered('>', x, ZERO)
+ is_neg = builder.fcmp_ordered('<', x, ZERO)
+
+ with builder.if_else(is_pos) as (gt_zero, not_gt_zero):
+ with gt_zero:
+ builder.store(POS, presult)
+ with not_gt_zero:
+ with builder.if_else(is_neg) as (lt_zero, not_lt_zero):
+ with lt_zero:
+ builder.store(NEG, presult)
+ with not_lt_zero:
+ # For both NaN and 0, the result of sign() is simply
+ # the input value.
+ builder.store(x, presult)
+
+ res = builder.load(presult)
+ return impl_ret_untracked(context, builder, sig.return_type, res)
+
+
+# ty = types.Float
+
+# lower_builtin(operator.add, ty, ty)(real_add_impl)
+# lower_builtin(operator.iadd, ty, ty)(real_add_impl)
+# lower_builtin(operator.sub, ty, ty)(real_sub_impl)
+# lower_builtin(operator.isub, ty, ty)(real_sub_impl)
+# lower_builtin(operator.mul, ty, ty)(real_mul_impl)
+# lower_builtin(operator.imul, ty, ty)(real_mul_impl)
+# lower_builtin(operator.floordiv, ty, ty)(real_floordiv_impl)
+# lower_builtin(operator.ifloordiv, ty, ty)(real_floordiv_impl)
+# lower_builtin(operator.truediv, ty, ty)(real_div_impl)
+# lower_builtin(operator.itruediv, ty, ty)(real_div_impl)
+# lower_builtin(operator.mod, ty, ty)(real_mod_impl)
+# lower_builtin(operator.imod, ty, ty)(real_mod_impl)
+# lower_builtin(operator.pow, ty, ty)(real_power_impl)
+# lower_builtin(operator.ipow, ty, ty)(real_power_impl)
+# lower_builtin(pow, ty, ty)(real_power_impl)
+
+# lower_builtin(operator.eq, ty, ty)(real_eq_impl)
+# lower_builtin(operator.ne, ty, ty)(real_ne_impl)
+# lower_builtin(operator.lt, ty, ty)(real_lt_impl)
+# lower_builtin(operator.le, ty, ty)(real_le_impl)
+# lower_builtin(operator.gt, ty, ty)(real_gt_impl)
+# lower_builtin(operator.ge, ty, ty)(real_ge_impl)
+
+# lower_builtin(abs, ty)(real_abs_impl)
+
+# lower_builtin(operator.neg, ty)(real_negate_impl)
+# lower_builtin(operator.pos, ty)(real_positive_impl)
+
+# del ty
+
+
+# @lower_getattr(types.Complex, "real")
+def complex_real_impl(context, builder, typ, value):
+ cplx = context.make_complex(builder, typ, value=value)
+ res = cplx.real
+ return impl_ret_untracked(context, builder, typ, res)
+
+# @lower_getattr(types.Complex, "imag")
+def complex_imag_impl(context, builder, typ, value):
+ cplx = context.make_complex(builder, typ, value=value)
+ res = cplx.imag
+ return impl_ret_untracked(context, builder, typ, res)
+
+# @lower_builtin("complex.conjugate", types.Complex)
+def complex_conjugate_impl(context, builder, sig, args):
+ from numba.cpython import mathimpl
+ z = context.make_complex(builder, sig.args[0], args[0])
+ z.imag = mathimpl.negate_real(builder, z.imag)
+ res = z._getvalue()
+ return impl_ret_untracked(context, builder, sig.return_type, res)
+
+def real_real_impl(context, builder, typ, value):
+ return impl_ret_untracked(context, builder, typ, value)
+
+def real_imag_impl(context, builder, typ, value):
+ res = cgutils.get_null_value(value.type)
+ return impl_ret_untracked(context, builder, typ, res)
+
+def real_conjugate_impl(context, builder, sig, args):
+ return impl_ret_untracked(context, builder, sig.return_type, args[0])
+
+# for cls in (types.Float, types.Integer):
+# lower_getattr(cls, "real")(real_real_impl)
+# lower_getattr(cls, "imag")(real_imag_impl)
+# lower_builtin("complex.conjugate", cls)(real_conjugate_impl)
+
+
+# @lower_builtin(operator.pow, types.Complex, types.Complex)
+# @lower_builtin(operator.ipow, types.Complex, types.Complex)
+# @lower_builtin(pow, types.Complex, types.Complex)
+def complex_power_impl(context, builder, sig, args):
+ [ca, cb] = args
+ ty = sig.args[0]
+ fty = ty.underlying_float
+ a = context.make_helper(builder, ty, value=ca)
+ b = context.make_helper(builder, ty, value=cb)
+ c = context.make_helper(builder, ty)
+ module = builder.module
+ pa = a._getpointer()
+ pb = b._getpointer()
+ pc = c._getpointer()
+
+ # Optimize for square because cpow loses a lot of precision
+ TWO = context.get_constant(fty, 2)
+ ZERO = context.get_constant(fty, 0)
+
+ b_real_is_two = builder.fcmp_ordered('==', b.real, TWO)
+ b_imag_is_zero = builder.fcmp_ordered('==', b.imag, ZERO)
+ b_is_two = builder.and_(b_real_is_two, b_imag_is_zero)
+
+ with builder.if_else(b_is_two) as (then, otherwise):
+ with then:
+ # Lower as multiplication
+ res = complex_mul_impl(context, builder, sig, (ca, ca))
+ cres = context.make_helper(builder, ty, value=res)
+ c.real = cres.real
+ c.imag = cres.imag
+
+ with otherwise:
+ # Lower with call to external function
+ func_name = {
+ types.complex64: "numba_cpowf",
+ types.complex128: "numba_cpow",
+ }[ty]
+ fnty = ir.FunctionType(ir.VoidType(), [pa.type] * 3)
+ cpow = cgutils.get_or_insert_function(module, fnty, func_name)
+ builder.call(cpow, (pa, pb, pc))
+
+ res = builder.load(pc)
+ return impl_ret_untracked(context, builder, sig.return_type, res)
+
+def complex_add_impl(context, builder, sig, args):
+ [cx, cy] = args
+ ty = sig.args[0]
+ x = context.make_complex(builder, ty, value=cx)
+ y = context.make_complex(builder, ty, value=cy)
+ z = context.make_complex(builder, ty)
+ a = x.real
+ b = x.imag
+ c = y.real
+ d = y.imag
+ z.real = builder.fadd(a, c)
+ z.imag = builder.fadd(b, d)
+ res = z._getvalue()
+ return impl_ret_untracked(context, builder, sig.return_type, res)
+
+
+def complex_sub_impl(context, builder, sig, args):
+ [cx, cy] = args
+ ty = sig.args[0]
+ x = context.make_complex(builder, ty, value=cx)
+ y = context.make_complex(builder, ty, value=cy)
+ z = context.make_complex(builder, ty)
+ a = x.real
+ b = x.imag
+ c = y.real
+ d = y.imag
+ z.real = builder.fsub(a, c)
+ z.imag = builder.fsub(b, d)
+ res = z._getvalue()
+ return impl_ret_untracked(context, builder, sig.return_type, res)
+
+
+def complex_mul_impl(context, builder, sig, args):
+ """
+ (a+bi)(c+di)=(ac-bd)+i(ad+bc)
+ """
+ [cx, cy] = args
+ ty = sig.args[0]
+ x = context.make_complex(builder, ty, value=cx)
+ y = context.make_complex(builder, ty, value=cy)
+ z = context.make_complex(builder, ty)
+ a = x.real
+ b = x.imag
+ c = y.real
+ d = y.imag
+ ac = builder.fmul(a, c)
+ bd = builder.fmul(b, d)
+ ad = builder.fmul(a, d)
+ bc = builder.fmul(b, c)
+ z.real = builder.fsub(ac, bd)
+ z.imag = builder.fadd(ad, bc)
+ res = z._getvalue()
+ return impl_ret_untracked(context, builder, sig.return_type, res)
+
+
+NAN = float('nan')
+
+def complex_div_impl(context, builder, sig, args):
+ def complex_div(a, b):
+ # This is CPython's algorithm (in _Py_c_quot()).
+ areal = a.real
+ aimag = a.imag
+ breal = b.real
+ bimag = b.imag
+ if not breal and not bimag:
+ raise ZeroDivisionError("complex division by zero")
+ if abs(breal) >= abs(bimag):
+ # Divide tops and bottom by b.real
+ if not breal:
+ return complex(NAN, NAN)
+ ratio = bimag / breal
+ denom = breal + bimag * ratio
+ return complex(
+ (areal + aimag * ratio) / denom,
+ (aimag - areal * ratio) / denom)
+ else:
+ # Divide tops and bottom by b.imag
+ if not bimag:
+ return complex(NAN, NAN)
+ ratio = breal / bimag
+ denom = breal * ratio + bimag
+ return complex(
+ (a.real * ratio + a.imag) / denom,
+ (a.imag * ratio - a.real) / denom)
+
+ res = context.compile_internal(builder, complex_div, sig, args)
+ return impl_ret_untracked(context, builder, sig.return_type, res)
+
+
+def complex_negate_impl(context, builder, sig, args):
+ from numba.cpython import mathimpl
+ [typ] = sig.args
+ [val] = args
+ cmplx = context.make_complex(builder, typ, value=val)
+ res = context.make_complex(builder, typ)
+ res.real = mathimpl.negate_real(builder, cmplx.real)
+ res.imag = mathimpl.negate_real(builder, cmplx.imag)
+ res = res._getvalue()
+ return impl_ret_untracked(context, builder, sig.return_type, res)
+
+
+def complex_positive_impl(context, builder, sig, args):
+ [val] = args
+ return impl_ret_untracked(context, builder, sig.return_type, val)
+
+
+def complex_eq_impl(context, builder, sig, args):
+ [cx, cy] = args
+ typ = sig.args[0]
+ x = context.make_complex(builder, typ, value=cx)
+ y = context.make_complex(builder, typ, value=cy)
+
+ reals_are_eq = builder.fcmp_ordered('==', x.real, y.real)
+ imags_are_eq = builder.fcmp_ordered('==', x.imag, y.imag)
+ res = builder.and_(reals_are_eq, imags_are_eq)
+ return impl_ret_untracked(context, builder, sig.return_type, res)
+
+
+def complex_ne_impl(context, builder, sig, args):
+ [cx, cy] = args
+ typ = sig.args[0]
+ x = context.make_complex(builder, typ, value=cx)
+ y = context.make_complex(builder, typ, value=cy)
+
+ reals_are_ne = builder.fcmp_unordered('!=', x.real, y.real)
+ imags_are_ne = builder.fcmp_unordered('!=', x.imag, y.imag)
+ res = builder.or_(reals_are_ne, imags_are_ne)
+ return impl_ret_untracked(context, builder, sig.return_type, res)
+
+
+def complex_abs_impl(context, builder, sig, args):
+ """
+ abs(z) := hypot(z.real, z.imag)
+ """
+ def complex_abs(z):
+ return math.hypot(z.real, z.imag)
+
+ res = context.compile_internal(builder, complex_abs, sig, args)
+ return impl_ret_untracked(context, builder, sig.return_type, res)
+
+
+# ty = types.Complex
+
+# lower_builtin(operator.add, ty, ty)(complex_add_impl)
+# lower_builtin(operator.iadd, ty, ty)(complex_add_impl)
+# lower_builtin(operator.sub, ty, ty)(complex_sub_impl)
+# lower_builtin(operator.isub, ty, ty)(complex_sub_impl)
+# lower_builtin(operator.mul, ty, ty)(complex_mul_impl)
+# lower_builtin(operator.imul, ty, ty)(complex_mul_impl)
+# lower_builtin(operator.truediv, ty, ty)(complex_div_impl)
+# lower_builtin(operator.itruediv, ty, ty)(complex_div_impl)
+# lower_builtin(operator.neg, ty)(complex_negate_impl)
+# lower_builtin(operator.pos, ty)(complex_positive_impl)
+# # Complex modulo is deprecated in python3
+
+# lower_builtin(operator.eq, ty, ty)(complex_eq_impl)
+# lower_builtin(operator.ne, ty, ty)(complex_ne_impl)
+
+# lower_builtin(abs, ty)(complex_abs_impl)
+
+# del ty
+
+
+# @lower_builtin("number.item", types.Boolean)
+# @lower_builtin("number.item", types.Number)
+def number_item_impl(context, builder, sig, args):
+ """
+ The no-op .item() method on booleans and numbers.
+ """
+ return args[0]
+
+
+#------------------------------------------------------------------------------
+
+
+def number_not_impl(context, builder, sig, args):
+ [typ] = sig.args
+ [val] = args
+ istrue = context.cast(builder, val, typ, sig.return_type)
+ res = builder.not_(istrue)
+ return impl_ret_untracked(context, builder, sig.return_type, res)
+
+# @lower_builtin(bool, types.Boolean)
+def bool_as_bool(context, builder, sig, args):
+ [val] = args
+ return val
+
+# @lower_builtin(bool, types.Integer)
+def int_as_bool(context, builder, sig, args):
+ [val] = args
+ return builder.icmp_unsigned('!=', val, Constant(val.type, 0))
+
+# @lower_builtin(bool, types.Float)
+def float_as_bool(context, builder, sig, args):
+ [val] = args
+ return builder.fcmp_unordered('!=', val, Constant(val.type, 0.0))
+
+# @lower_builtin(bool, types.Complex)
+def complex_as_bool(context, builder, sig, args):
+ [typ] = sig.args
+ [val] = args
+ cmplx = context.make_complex(builder, typ, val)
+ real, imag = cmplx.real, cmplx.imag
+ zero = Constant(real.type, 0.0)
+ real_istrue = builder.fcmp_unordered('!=', real, zero)
+ imag_istrue = builder.fcmp_unordered('!=', imag, zero)
+ return builder.or_(real_istrue, imag_istrue)
+
+
+# for ty in (types.Integer, types.Float, types.Complex):
+# lower_builtin(operator.not_, ty)(number_not_impl)
+
+# lower_builtin(operator.not_, types.boolean)(number_not_impl)
+
+
+#------------------------------------------------------------------------------
+# Hashing numbers, see hashing.py
+
+#-------------------------------------------------------------------------------
+# Implicit casts between numerics
+
+# @lower_cast(types.IntegerLiteral, types.Integer)
+# @lower_cast(types.IntegerLiteral, types.Float)
+# @lower_cast(types.IntegerLiteral, types.Complex)
+def literal_int_to_number(context, builder, fromty, toty, val):
+ lit = context.get_constant_generic(
+ builder,
+ fromty.literal_type,
+ fromty.literal_value,
+ )
+ return context.cast(builder, lit, fromty.literal_type, toty)
+
+
+# @lower_cast(types.Integer, types.Integer)
+def integer_to_integer(context, builder, fromty, toty, val):
+ if toty.bitwidth == fromty.bitwidth:
+ # Just a change of signedness
+ return val
+ elif toty.bitwidth < fromty.bitwidth:
+ # Downcast
+ return builder.trunc(val, context.get_value_type(toty))
+ elif fromty.signed:
+ # Signed upcast
+ return builder.sext(val, context.get_value_type(toty))
+ else:
+ # Unsigned upcast
+ return builder.zext(val, context.get_value_type(toty))
+
+# @lower_cast(types.Integer, types.voidptr)
+def integer_to_voidptr(context, builder, fromty, toty, val):
+ return builder.inttoptr(val, context.get_value_type(toty))
+
+# @lower_cast(types.Float, types.Float)
+def float_to_float(context, builder, fromty, toty, val):
+ lty = context.get_value_type(toty)
+ if fromty.bitwidth < toty.bitwidth:
+ return builder.fpext(val, lty)
+ else:
+ return builder.fptrunc(val, lty)
+
+# @lower_cast(types.Integer, types.Float)
+def integer_to_float(context, builder, fromty, toty, val):
+ lty = context.get_value_type(toty)
+ if fromty.signed:
+ return builder.sitofp(val, lty)
+ else:
+ return builder.uitofp(val, lty)
+
+# @lower_cast(types.Float, types.Integer)
+def float_to_integer(context, builder, fromty, toty, val):
+ lty = context.get_value_type(toty)
+ if toty.signed:
+ return builder.fptosi(val, lty)
+ else:
+ return builder.fptoui(val, lty)
+
+# @lower_cast(types.Float, types.Complex)
+# @lower_cast(types.Integer, types.Complex)
+def non_complex_to_complex(context, builder, fromty, toty, val):
+ real = context.cast(builder, val, fromty, toty.underlying_float)
+ imag = context.get_constant(toty.underlying_float, 0)
+
+ cmplx = context.make_complex(builder, toty)
+ cmplx.real = real
+ cmplx.imag = imag
+ return cmplx._getvalue()
+
+# @lower_cast(types.Complex, types.Complex)
+def complex_to_complex(context, builder, fromty, toty, val):
+ srcty = fromty.underlying_float
+ dstty = toty.underlying_float
+
+ src = context.make_complex(builder, fromty, value=val)
+ dst = context.make_complex(builder, toty)
+ dst.real = context.cast(builder, src.real, srcty, dstty)
+ dst.imag = context.cast(builder, src.imag, srcty, dstty)
+ return dst._getvalue()
+
+# @lower_cast(types.Any, types.Boolean)
+def any_to_boolean(context, builder, fromty, toty, val):
+ return context.is_true(builder, fromty, val)
+
+# @lower_cast(types.Boolean, types.Number)
+def boolean_to_any(context, builder, fromty, toty, val):
+ # Casting from boolean to anything first casts to int32
+ asint = builder.zext(val, ir.IntType(32))
+ return context.cast(builder, asint, types.int32, toty)
+
+# @lower_cast(types.IntegerLiteral, types.Boolean)
+# @lower_cast(types.BooleanLiteral, types.Boolean)
+def literal_int_to_boolean(context, builder, fromty, toty, val):
+ lit = context.get_constant_generic(
+ builder,
+ fromty.literal_type,
+ fromty.literal_value,
+ )
+ return context.is_true(builder, fromty.literal_type, lit)
+
+#-------------------------------------------------------------------------------
+# Constants
+
+# @lower_constant(types.Complex)
+def constant_complex(context, builder, ty, pyval):
+ fty = ty.underlying_float
+ real = context.get_constant_generic(builder, fty, pyval.real)
+ imag = context.get_constant_generic(builder, fty, pyval.imag)
+ return Constant.literal_struct((real, imag))
+
+# @lower_constant(types.Integer)
+# @lower_constant(types.Float)
+# @lower_constant(types.Boolean)
+def constant_integer(context, builder, ty, pyval):
+ # See https://github.com/numba/numba/issues/6979
+ # llvmlite ir.IntType specialises the formatting of the constant for a
+ # cpython bool. A NumPy np.bool_ is not a cpython bool so force it to be one
+ # so that the constant renders correctly!
+ if isinstance(pyval, np.bool_):
+ pyval = bool(pyval)
+ lty = context.get_value_type(ty)
+ return lty(pyval)
+
+
+#-------------------------------------------------------------------------------
+# View
+
+def scalar_view(scalar, viewty):
+ """ Typing for the np scalar 'view' method. """
+ if (isinstance(scalar, (types.Float, types.Integer))
+ and isinstance(viewty, types.abstract.DTypeSpec)):
+ if scalar.bitwidth != viewty.dtype.bitwidth:
+ raise errors.TypingError(
+ "Changing the dtype of a 0d array is only supported if the "
+ "itemsize is unchanged")
+
+ def impl(scalar, viewty):
+ return viewer(scalar, viewty)
+ return impl
+
+
+# overload_method(types.Float, 'view')(scalar_view)
+# overload_method(types.Integer, 'view')(scalar_view)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/np/polynomial/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/numba/np/polynomial/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/np/polynomial/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/np/polynomial/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..aea17a1e6903dcca49f1d1b2abe3282841f34f19
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/np/polynomial/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/np/polynomial/__pycache__/polynomial_core.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/np/polynomial/__pycache__/polynomial_core.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..939af7e229d3a1597253f5e26062633c1de89491
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/np/polynomial/__pycache__/polynomial_core.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/np/polynomial/__pycache__/polynomial_functions.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/np/polynomial/__pycache__/polynomial_functions.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..788daa6837d2470468e3c8635aff05b063757a63
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/np/polynomial/__pycache__/polynomial_functions.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/np/polynomial/polynomial_core.py b/tool_server/.venv/lib/python3.12/site-packages/numba/np/polynomial/polynomial_core.py
new file mode 100644
index 0000000000000000000000000000000000000000..16448fb6c2d348e876144e5f0339e16b35283e3c
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/np/polynomial/polynomial_core.py
@@ -0,0 +1,223 @@
+from numba.extending import (models, register_model, type_callable,
+ unbox, NativeValue, make_attribute_wrapper, box,
+ lower_builtin)
+from numba.core import types, cgutils
+import warnings
+from numba.core.errors import NumbaExperimentalFeatureWarning, NumbaValueError
+from numpy.polynomial.polynomial import Polynomial
+from contextlib import ExitStack
+import numpy as np
+from llvmlite import ir
+
+
+@register_model(types.PolynomialType)
+class PolynomialModel(models.StructModel):
+ def __init__(self, dmm, fe_type):
+ members = [
+ ('coef', fe_type.coef),
+ ('domain', fe_type.domain),
+ ('window', fe_type.window)
+ # Introduced in NumPy 1.24, maybe leave it out for now
+ # ('symbol', types.string)
+ ]
+ super(PolynomialModel, self).__init__(dmm, fe_type, members)
+
+
+@type_callable(Polynomial)
+def type_polynomial(context):
+ def typer(coef, domain=None, window=None):
+ default_domain = types.Array(types.int64, 1, 'C')
+ double_domain = types.Array(types.double, 1, 'C')
+ default_window = types.Array(types.int64, 1, 'C')
+ double_window = types.Array(types.double, 1, 'C')
+ double_coef = types.Array(types.double, 1, 'C')
+
+ warnings.warn("Polynomial class is experimental",
+ category=NumbaExperimentalFeatureWarning)
+
+ if isinstance(coef, types.Array) and \
+ all([a is None for a in (domain, window)]):
+ if coef.ndim == 1:
+ # If Polynomial(coef) is called, coef is cast to double dtype,
+ # and domain and window are set to equal [-1, 1], i.e. have
+ # integer dtype
+ return types.PolynomialType(double_coef,
+ default_domain,
+ default_window,
+ 1)
+ else:
+ msg = 'Coefficient array is not 1-d'
+ raise NumbaValueError(msg)
+ elif all([isinstance(a, types.Array) for a in (coef, domain, window)]):
+ if coef.ndim == 1:
+ if all([a.ndim == 1 for a in (domain, window)]):
+ # If Polynomial(coef, domain, window) is called, then coef,
+ # domain and window are cast to double dtype
+ return types.PolynomialType(double_coef,
+ double_domain,
+ double_window,
+ 3)
+ else:
+ msg = 'Coefficient array is not 1-d'
+ raise NumbaValueError(msg)
+ return typer
+
+
+make_attribute_wrapper(types.PolynomialType, 'coef', 'coef')
+make_attribute_wrapper(types.PolynomialType, 'domain', 'domain')
+make_attribute_wrapper(types.PolynomialType, 'window', 'window')
+# Introduced in NumPy 1.24, maybe leave it out for now
+# make_attribute_wrapper(types.PolynomialType, 'symbol', 'symbol')
+
+
+@lower_builtin(Polynomial, types.Array)
+def impl_polynomial1(context, builder, sig, args):
+
+ def to_double(arr):
+ return np.asarray(arr, dtype=np.double)
+
+ def const_impl():
+ return np.asarray([-1, 1])
+
+ typ = sig.return_type
+ polynomial = cgutils.create_struct_proxy(typ)(context, builder)
+ sig_coef = sig.args[0].copy(dtype=types.double)(sig.args[0])
+ coef_cast = context.compile_internal(builder, to_double, sig_coef, args)
+ sig_domain = sig.args[0].copy(dtype=types.intp)()
+ sig_window = sig.args[0].copy(dtype=types.intp)()
+ domain_cast = context.compile_internal(builder, const_impl, sig_domain, ())
+ window_cast = context.compile_internal(builder, const_impl, sig_window, ())
+ polynomial.coef = coef_cast
+ polynomial.domain = domain_cast
+ polynomial.window = window_cast
+
+ return polynomial._getvalue()
+
+
+@lower_builtin(Polynomial, types.Array, types.Array, types.Array)
+def impl_polynomial3(context, builder, sig, args):
+
+ def to_double(coef):
+ return np.asarray(coef, dtype=np.double)
+
+ typ = sig.return_type
+ polynomial = cgutils.create_struct_proxy(typ)(context, builder)
+
+ coef_sig = sig.args[0].copy(dtype=types.double)(sig.args[0])
+ domain_sig = sig.args[1].copy(dtype=types.double)(sig.args[1])
+ window_sig = sig.args[2].copy(dtype=types.double)(sig.args[2])
+ coef_cast = context.compile_internal(builder,
+ to_double, coef_sig,
+ (args[0],))
+ domain_cast = context.compile_internal(builder,
+ to_double, domain_sig,
+ (args[1],))
+ window_cast = context.compile_internal(builder,
+ to_double, window_sig,
+ (args[2],))
+
+ domain_helper = context.make_helper(builder,
+ domain_sig.return_type,
+ value=domain_cast)
+ window_helper = context.make_helper(builder,
+ window_sig.return_type,
+ value=window_cast)
+
+ i64 = ir.IntType(64)
+ two = i64(2)
+
+ s1 = builder.extract_value(domain_helper.shape, 0)
+ s2 = builder.extract_value(window_helper.shape, 0)
+ pred1 = builder.icmp_signed('!=', s1, two)
+ pred2 = builder.icmp_signed('!=', s2, two)
+
+ with cgutils.if_unlikely(builder, pred1):
+ context.call_conv.return_user_exc(
+ builder, ValueError,
+ ("Domain has wrong number of elements.",))
+
+ with cgutils.if_unlikely(builder, pred2):
+ context.call_conv.return_user_exc(
+ builder, ValueError,
+ ("Window has wrong number of elements.",))
+
+ polynomial.coef = coef_cast
+ polynomial.domain = domain_helper._getvalue()
+ polynomial.window = window_helper._getvalue()
+
+ return polynomial._getvalue()
+
+
+@unbox(types.PolynomialType)
+def unbox_polynomial(typ, obj, c):
+ """
+ Convert a Polynomial object to a native polynomial structure.
+ """
+ is_error_ptr = cgutils.alloca_once_value(c.builder, cgutils.false_bit)
+ polynomial = cgutils.create_struct_proxy(typ)(c.context, c.builder)
+ with ExitStack() as stack:
+ natives = []
+ for name in ("coef", "domain", "window"):
+ attr = c.pyapi.object_getattr_string(obj, name)
+ with cgutils.early_exit_if_null(c.builder, stack, attr):
+ c.builder.store(cgutils.true_bit, is_error_ptr)
+ t = getattr(typ, name)
+ native = c.unbox(t, attr)
+ c.pyapi.decref(attr)
+ with cgutils.early_exit_if(c.builder, stack, native.is_error):
+ c.builder.store(cgutils.true_bit, is_error_ptr)
+ natives.append(native)
+
+ polynomial.coef = natives[0]
+ polynomial.domain = natives[1]
+ polynomial.window = natives[2]
+
+ return NativeValue(polynomial._getvalue(),
+ is_error=c.builder.load(is_error_ptr))
+
+
+@box(types.PolynomialType)
+def box_polynomial(typ, val, c):
+ """
+ Convert a native polynomial structure to a Polynomial object.
+ """
+ ret_ptr = cgutils.alloca_once(c.builder, c.pyapi.pyobj)
+ fail_obj = c.pyapi.get_null_object()
+
+ with ExitStack() as stack:
+ polynomial = cgutils.create_struct_proxy(typ)(c.context, c.builder,
+ value=val)
+ coef_obj = c.box(typ.coef, polynomial.coef)
+ with cgutils.early_exit_if_null(c.builder, stack, coef_obj):
+ c.builder.store(fail_obj, ret_ptr)
+
+ domain_obj = c.box(typ.domain, polynomial.domain)
+ with cgutils.early_exit_if_null(c.builder, stack, domain_obj):
+ c.builder.store(fail_obj, ret_ptr)
+
+ window_obj = c.box(typ.window, polynomial.window)
+ with cgutils.early_exit_if_null(c.builder, stack, window_obj):
+ c.builder.store(fail_obj, ret_ptr)
+
+ class_obj = c.pyapi.unserialize(c.pyapi.serialize_object(Polynomial))
+ with cgutils.early_exit_if_null(c.builder, stack, class_obj):
+ c.pyapi.decref(coef_obj)
+ c.pyapi.decref(domain_obj)
+ c.pyapi.decref(window_obj)
+ c.builder.store(fail_obj, ret_ptr)
+
+ if typ.n_args == 1:
+ res1 = c.pyapi.call_function_objargs(class_obj, (coef_obj,))
+ c.builder.store(res1, ret_ptr)
+ else:
+ res3 = c.pyapi.call_function_objargs(class_obj, (coef_obj,
+ domain_obj,
+ window_obj))
+ c.builder.store(res3, ret_ptr)
+
+ c.pyapi.decref(coef_obj)
+ c.pyapi.decref(domain_obj)
+ c.pyapi.decref(window_obj)
+ c.pyapi.decref(class_obj)
+
+ return c.builder.load(ret_ptr)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/np/polynomial/polynomial_functions.py b/tool_server/.venv/lib/python3.12/site-packages/numba/np/polynomial/polynomial_functions.py
new file mode 100644
index 0000000000000000000000000000000000000000..4a13f8cf0d1bb54744e74dfac8485cea8e9cbeb1
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/np/polynomial/polynomial_functions.py
@@ -0,0 +1,375 @@
+"""
+Implementation of operations involving polynomials.
+"""
+
+
+import numpy as np
+from numpy.polynomial import polynomial as poly
+from numpy.polynomial import polyutils as pu
+
+from numba import literal_unroll
+from numba.core import types, errors
+from numba.core.extending import overload
+from numba.np.numpy_support import type_can_asarray, as_dtype, from_dtype
+
+
+@overload(np.roots)
+def roots_impl(p):
+
+ # cast int vectors to float cf. numpy, this is a bit dicey as
+ # the roots could be complex which will fail anyway
+ ty = getattr(p, 'dtype', p)
+ if isinstance(ty, types.Integer):
+ cast_t = np.float64
+ else:
+ cast_t = as_dtype(ty)
+
+ def roots_impl(p):
+ # impl based on numpy:
+ # https://github.com/numpy/numpy/blob/master/numpy/lib/polynomial.py
+
+ if len(p.shape) != 1:
+ raise ValueError("Input must be a 1d array.")
+
+ non_zero = np.nonzero(p)[0]
+
+ if len(non_zero) == 0:
+ return np.zeros(0, dtype=cast_t)
+
+ tz = len(p) - non_zero[-1] - 1
+
+ # pull out the coeffs selecting between possible zero pads
+ p = p[int(non_zero[0]):int(non_zero[-1]) + 1]
+
+ n = len(p)
+ if n > 1:
+ # construct companion matrix, ensure fortran order
+ # to give to eigvals, write to upper diag and then
+ # transpose.
+ A = np.diag(np.ones((n - 2,), cast_t), 1).T
+ A[0, :] = -p[1:] / p[0] # normalize
+ roots = np.linalg.eigvals(A)
+ else:
+ roots = np.zeros(0, dtype=cast_t)
+
+ # add in additional zeros on the end if needed
+ if tz > 0:
+ return np.hstack((roots, np.zeros(tz, dtype=cast_t)))
+ else:
+ return roots
+
+ return roots_impl
+
+
+@overload(pu.trimseq)
+def polyutils_trimseq(seq):
+ if not type_can_asarray(seq):
+ msg = 'The argument "seq" must be array-like'
+ raise errors.TypingError(msg)
+
+ if isinstance(seq, types.BaseTuple):
+ msg = 'Unsupported type %r for argument "seq"'
+ raise errors.TypingError(msg % (seq))
+
+ if np.ndim(seq) > 1:
+ msg = 'Coefficient array is not 1-d'
+ raise errors.NumbaValueError(msg)
+
+ def impl(seq):
+ if len(seq) == 0:
+ return seq
+ else:
+ for i in range(len(seq) - 1, -1, -1):
+ if seq[i] != 0:
+ break
+ return seq[:i + 1]
+
+ return impl
+
+
+@overload(pu.as_series)
+def polyutils_as_series(alist, trim=True):
+ if not type_can_asarray(alist):
+ msg = 'The argument "alist" must be array-like'
+ raise errors.TypingError(msg)
+
+ if not isinstance(trim, (bool, types.Boolean)):
+ msg = 'The argument "trim" must be boolean'
+ raise errors.TypingError(msg)
+
+ res_dtype = np.float64
+
+ tuple_input = isinstance(alist, types.BaseTuple)
+ list_input = isinstance(alist, types.List)
+ if tuple_input:
+ if np.any(np.array([np.ndim(a) > 1 for a in alist])):
+ raise errors.NumbaValueError("Coefficient array is not 1-d")
+
+ res_dtype = _poly_result_dtype(*alist)
+
+ elif list_input:
+ dt = as_dtype(_get_list_type(alist))
+ res_dtype = np.result_type(dt, np.float64)
+
+ else:
+ if np.ndim(alist) <= 2:
+ res_dtype = np.result_type(res_dtype, as_dtype(alist.dtype))
+ else:
+ # If total dimension has ndim > 2, then coeff arrays are not 1D
+ raise errors.NumbaValueError("Coefficient array is not 1-d")
+
+ def impl(alist, trim=True):
+ if tuple_input:
+ arrays = []
+ for item in literal_unroll(alist):
+ arrays.append(np.atleast_1d(np.asarray(item)).astype(res_dtype))
+
+ elif list_input:
+ arrays = [np.atleast_1d(np.asarray(a)).astype(res_dtype)
+ for a in alist]
+
+ else:
+ alist_arr = np.asarray(alist)
+ arrays = [np.atleast_1d(np.asarray(a)).astype(res_dtype)
+ for a in alist_arr]
+
+ if min([a.size for a in arrays]) == 0:
+ raise ValueError("Coefficient array is empty")
+
+ if trim:
+ arrays = [pu.trimseq(a) for a in arrays]
+
+ ret = arrays
+ return ret
+
+ return impl
+
+
+def _get_list_type(l):
+ # A helper function that takes a list (possibly nested) and returns its
+ # dtype. Returns a Numba type.
+ dt = l.dtype
+ if (not isinstance(dt, types.Number)) and type_can_asarray(dt):
+ return _get_list_type(dt)
+ else:
+ return dt
+
+
+def _poly_result_dtype(*args):
+ # A helper function that takes a tuple of inputs and returns their result
+ # dtype. Used for poly functions. Returns a NumPy dtype.
+ res_dtype = np.float64
+ for item in args:
+ if isinstance(item, types.BaseTuple):
+ s1 = item.types
+ elif isinstance(item, types.List):
+ s1 = [_get_list_type(item)]
+ elif isinstance(item, types.Number):
+ s1 = [item]
+ elif isinstance(item, types.Array):
+ s1 = [item.dtype]
+ else:
+ msg = 'Input dtype must be scalar'
+ raise errors.TypingError(msg)
+
+ try:
+ l = [as_dtype(t) for t in s1]
+ l.append(res_dtype)
+ res_dtype = (np.result_type(*l))
+ except errors.NumbaNotImplementedError:
+ msg = 'Input dtype must be scalar.'
+ raise errors.TypingError(msg)
+
+ return from_dtype(res_dtype)
+
+
+@overload(poly.polyadd)
+def numpy_polyadd(c1, c2):
+ if not type_can_asarray(c1):
+ msg = 'The argument "c1" must be array-like'
+ raise errors.TypingError(msg)
+
+ if not type_can_asarray(c2):
+ msg = 'The argument "c2" must be array-like'
+ raise errors.TypingError(msg)
+
+ def impl(c1, c2):
+ arr1, arr2 = pu.as_series((c1, c2))
+ diff = len(arr2) - len(arr1)
+ if diff > 0:
+ zr = np.zeros(diff)
+ arr1 = np.concatenate((arr1, zr))
+ if diff < 0:
+ zr = np.zeros(-diff)
+ arr2 = np.concatenate((arr2, zr))
+ val = arr1 + arr2
+ return pu.trimseq(val)
+
+ return impl
+
+
+@overload(poly.polysub)
+def numpy_polysub(c1, c2):
+ if not type_can_asarray(c1):
+ msg = 'The argument "c1" must be array-like'
+ raise errors.TypingError(msg)
+
+ if not type_can_asarray(c2):
+ msg = 'The argument "c2" must be array-like'
+ raise errors.TypingError(msg)
+
+ def impl(c1, c2):
+ arr1, arr2 = pu.as_series((c1, c2))
+ diff = len(arr2) - len(arr1)
+ if diff > 0:
+ zr = np.zeros(diff)
+ arr1 = np.concatenate((arr1, zr))
+ if diff < 0:
+ zr = np.zeros(-diff)
+ arr2 = np.concatenate((arr2, zr))
+ val = arr1 - arr2
+ return pu.trimseq(val)
+
+ return impl
+
+
+@overload(poly.polymul)
+def numpy_polymul(c1, c2):
+ if not type_can_asarray(c1):
+ msg = 'The argument "c1" must be array-like'
+ raise errors.TypingError(msg)
+
+ if not type_can_asarray(c2):
+ msg = 'The argument "c2" must be array-like'
+ raise errors.TypingError(msg)
+
+ def impl(c1, c2):
+ arr1, arr2 = pu.as_series((c1, c2))
+ val = np.convolve(arr1, arr2)
+ return pu.trimseq(val)
+
+ return impl
+
+
+@overload(poly.polyval, prefer_literal=True)
+def poly_polyval(x, c, tensor=True):
+ if not type_can_asarray(x):
+ msg = 'The argument "x" must be array-like'
+ raise errors.TypingError(msg)
+
+ if not type_can_asarray(c):
+ msg = 'The argument "c" must be array-like'
+ raise errors.TypingError(msg)
+
+ if not isinstance(tensor, (bool, types.BooleanLiteral)):
+ msg = 'The argument "tensor" must be boolean'
+ raise errors.RequireLiteralValue(msg)
+
+ res_dtype = _poly_result_dtype(c, x)
+
+ # Simulate new_shape = (1,) * np.ndim(x) in the general case
+ # If x is a number, new_shape is not used
+ # If x is a tuple or a list, then it's 1d hence new_shape=(1,)
+ x_nd_array = not isinstance(x, types.Number)
+ new_shape = (1,)
+ if isinstance(x, types.Array):
+ # If x is a np.array, then take its dimension
+ new_shape = (1,) * np.ndim(x)
+
+ if isinstance(tensor, bool):
+ tensor_arg = tensor
+ else:
+ tensor_arg = tensor.literal_value
+
+ def impl(x, c, tensor=True):
+ arr = np.asarray(c).astype(res_dtype)
+ inputs = np.asarray(x).astype(res_dtype)
+ if x_nd_array and tensor_arg:
+ arr = arr.reshape(arr.shape + new_shape)
+
+ l = len(arr)
+ y = arr[l - 1] + inputs * 0
+
+ for i in range(l - 1, 0, -1):
+ y = arr[i - 1] + y * inputs
+
+ return y
+
+ return impl
+
+
+@overload(poly.polyint)
+def poly_polyint(c, m=1):
+
+ if not type_can_asarray(c):
+ msg = 'The argument "c" must be array-like'
+ raise errors.TypingError(msg)
+
+ if not isinstance(m, (int, types.Integer)):
+ msg = 'The argument "m" must be an integer'
+ raise errors.TypingError(msg)
+
+ res_dtype = as_dtype(_poly_result_dtype(c))
+
+ if not np.issubdtype(res_dtype, np.number):
+ msg = f'Input dtype must be scalar. Found {res_dtype} instead'
+ raise errors.TypingError(msg)
+
+ is1D = ((np.ndim(c) == 1) or
+ (isinstance(c, (types.List, types.BaseTuple))
+ and isinstance(c.dtype, types.Number)))
+
+ def impl(c, m=1):
+ c = np.asarray(c).astype(res_dtype)
+ cdt = c.dtype
+ for i in range(m):
+ n = len(c)
+
+ tmp = np.empty((n + 1,) + c.shape[1:], dtype=cdt)
+ tmp[0] = c[0] * 0
+ tmp[1] = c[0]
+ for j in range(1, n):
+ tmp[j + 1] = c[j] / (j + 1)
+ c = tmp
+ if is1D:
+ return pu.trimseq(c)
+ else:
+ return c
+
+ return impl
+
+
+@overload(poly.polydiv)
+def numpy_polydiv(c1, c2):
+ if not type_can_asarray(c1):
+ msg = 'The argument "c1" must be array-like'
+ raise errors.TypingError(msg)
+
+ if not type_can_asarray(c2):
+ msg = 'The argument "c2" must be array-like'
+ raise errors.TypingError(msg)
+
+ def impl(c1, c2):
+ arr1, arr2 = pu.as_series((c1, c2))
+ if arr2[-1] == 0:
+ raise ZeroDivisionError()
+
+ l1 = len(arr1)
+ l2 = len(arr2)
+ if l1 < l2:
+ return arr1[:1] * 0, arr1
+ elif l2 == 1:
+ return arr1 / arr2[-1], arr1[:1] * 0
+ else:
+ dlen = l1 - l2
+ scl = arr2[-1]
+ arr2 = arr2[:-1] / scl
+ i = dlen
+ j = l1 - 1
+ while i >= 0:
+ arr1[i:j] -= arr2 * arr1[j]
+ i -= 1
+ j -= 1
+ return arr1[j + 1:] / scl, pu.trimseq(arr1[:j + 1])
+
+ return impl
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/np/random/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/numba/np/random/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/np/random/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/np/random/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..53b041c4a5933de3c4ca807f45f8dc213579c268
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/np/random/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/np/random/__pycache__/_constants.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/np/random/__pycache__/_constants.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e9f9b2ab98dac70fe40bb263215f8d1a416b715e
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/np/random/__pycache__/_constants.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/np/random/__pycache__/distributions.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/np/random/__pycache__/distributions.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5fa1b0cda8e642c5655e076e5b0dce3f323ce68a
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/np/random/__pycache__/distributions.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/np/random/__pycache__/generator_core.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/np/random/__pycache__/generator_core.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d07f3d9e39f08fea373d5ce465d068bf14b36f45
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/np/random/__pycache__/generator_core.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/np/random/__pycache__/generator_methods.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/np/random/__pycache__/generator_methods.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9909e87d17515fe681c0b0e9a296908217ae4de9
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/np/random/__pycache__/generator_methods.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/np/random/__pycache__/new_distributions.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/np/random/__pycache__/new_distributions.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2f2529b6c6008eba1ea0605fae5ebb6af1759dfa
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/np/random/__pycache__/new_distributions.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/np/random/__pycache__/new_random_methods.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/np/random/__pycache__/new_random_methods.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8647108228930b56b2d536867f1677a642ee2533
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/np/random/__pycache__/new_random_methods.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/np/random/__pycache__/old_distributions.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/np/random/__pycache__/old_distributions.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e81fca43238e7d94ba8b5cd7ffd045c2e6e07e4b
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/np/random/__pycache__/old_distributions.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/np/random/__pycache__/old_random_methods.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/np/random/__pycache__/old_random_methods.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f728b16f1ff128d5c87572610e61f9aa3d69f6a4
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/np/random/__pycache__/old_random_methods.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/np/random/__pycache__/random_methods.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/np/random/__pycache__/random_methods.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5c085520d612c727880bd32aa1f86189c674516c
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/np/random/__pycache__/random_methods.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/np/random/_constants.py b/tool_server/.venv/lib/python3.12/site-packages/numba/np/random/_constants.py
new file mode 100644
index 0000000000000000000000000000000000000000..7676ab87f4d1020abb659b1c9d9168094b51bbd4
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/np/random/_constants.py
@@ -0,0 +1,1229 @@
+import numpy as np
+import ctypes
+
+# These constants are directly obtained from:
+# https://github.com/numpy/numpy/blob/caccd283941b0bade7b71056138ded5379b1625f/numpy/random/src/distributions/ziggurat_constants.h
+
+ki_double = np.array([
+ 0x000EF33D8025EF6A, 0x0000000000000000, 0x000C08BE98FBC6A8,
+ 0x000DA354FABD8142, 0x000E51F67EC1EEEA, 0x000EB255E9D3F77E,
+ 0x000EEF4B817ECAB9, 0x000F19470AFA44AA, 0x000F37ED61FFCB18,
+ 0x000F4F469561255C, 0x000F61A5E41BA396, 0x000F707A755396A4,
+ 0x000F7CB2EC28449A, 0x000F86F10C6357D3, 0x000F8FA6578325DE,
+ 0x000F9724C74DD0DA, 0x000F9DA907DBF509, 0x000FA360F581FA74,
+ 0x000FA86FDE5B4BF8, 0x000FACF160D354DC, 0x000FB0FB6718B90F,
+ 0x000FB49F8D5374C6, 0x000FB7EC2366FE77, 0x000FBAECE9A1E50E,
+ 0x000FBDAB9D040BED, 0x000FC03060FF6C57, 0x000FC2821037A248,
+ 0x000FC4A67AE25BD1, 0x000FC6A2977AEE31, 0x000FC87AA92896A4,
+ 0x000FCA325E4BDE85, 0x000FCBCCE902231A, 0x000FCD4D12F839C4,
+ 0x000FCEB54D8FEC99, 0x000FD007BF1DC930, 0x000FD1464DD6C4E6,
+ 0x000FD272A8E2F450, 0x000FD38E4FF0C91E, 0x000FD49A9990B478,
+ 0x000FD598B8920F53, 0x000FD689C08E99EC, 0x000FD76EA9C8E832,
+ 0x000FD848547B08E8, 0x000FD9178BAD2C8C, 0x000FD9DD07A7ADD2,
+ 0x000FDA9970105E8C, 0x000FDB4D5DC02E20, 0x000FDBF95C5BFCD0,
+ 0x000FDC9DEBB99A7D, 0x000FDD3B8118729D, 0x000FDDD288342F90,
+ 0x000FDE6364369F64, 0x000FDEEE708D514E, 0x000FDF7401A6B42E,
+ 0x000FDFF46599ED40, 0x000FE06FE4BC24F2, 0x000FE0E6C225A258,
+ 0x000FE1593C28B84C, 0x000FE1C78CBC3F99, 0x000FE231E9DB1CAA,
+ 0x000FE29885DA1B91, 0x000FE2FB8FB54186, 0x000FE35B33558D4A,
+ 0x000FE3B799D0002A, 0x000FE410E99EAD7F, 0x000FE46746D47734,
+ 0x000FE4BAD34C095C, 0x000FE50BAED29524, 0x000FE559F74EBC78,
+ 0x000FE5A5C8E41212, 0x000FE5EF3E138689, 0x000FE6366FD91078,
+ 0x000FE67B75C6D578, 0x000FE6BE661E11AA, 0x000FE6FF55E5F4F2,
+ 0x000FE73E5900A702, 0x000FE77B823E9E39, 0x000FE7B6E37070A2,
+ 0x000FE7F08D774243, 0x000FE8289053F08C, 0x000FE85EFB35173A,
+ 0x000FE893DC840864, 0x000FE8C741F0CEBC, 0x000FE8F9387D4EF6,
+ 0x000FE929CC879B1D, 0x000FE95909D388EA, 0x000FE986FB939AA2,
+ 0x000FE9B3AC714866, 0x000FE9DF2694B6D5, 0x000FEA0973ABE67C,
+ 0x000FEA329CF166A4, 0x000FEA5AAB32952C, 0x000FEA81A6D5741A,
+ 0x000FEAA797DE1CF0, 0x000FEACC85F3D920, 0x000FEAF07865E63C,
+ 0x000FEB13762FEC13, 0x000FEB3585FE2A4A, 0x000FEB56AE3162B4,
+ 0x000FEB76F4E284FA, 0x000FEB965FE62014, 0x000FEBB4F4CF9D7C,
+ 0x000FEBD2B8F449D0, 0x000FEBEFB16E2E3E, 0x000FEC0BE31EBDE8,
+ 0x000FEC2752B15A15, 0x000FEC42049DAFD3, 0x000FEC5BFD29F196,
+ 0x000FEC75406CEEF4, 0x000FEC8DD2500CB4, 0x000FECA5B6911F12,
+ 0x000FECBCF0C427FE, 0x000FECD38454FB15, 0x000FECE97488C8B3,
+ 0x000FECFEC47F91B7, 0x000FED1377358528, 0x000FED278F844903,
+ 0x000FED3B10242F4C, 0x000FED4DFBAD586E, 0x000FED605498C3DD,
+ 0x000FED721D414FE8, 0x000FED8357E4A982, 0x000FED9406A42CC8,
+ 0x000FEDA42B85B704, 0x000FEDB3C8746AB4, 0x000FEDC2DF416652,
+ 0x000FEDD171A46E52, 0x000FEDDF813C8AD3, 0x000FEDED0F909980,
+ 0x000FEDFA1E0FD414, 0x000FEE06AE124BC4, 0x000FEE12C0D95A06,
+ 0x000FEE1E579006E0, 0x000FEE29734B6524, 0x000FEE34150AE4BC,
+ 0x000FEE3E3DB89B3C, 0x000FEE47EE2982F4, 0x000FEE51271DB086,
+ 0x000FEE59E9407F41, 0x000FEE623528B42E, 0x000FEE6A0B5897F1,
+ 0x000FEE716C3E077A, 0x000FEE7858327B82, 0x000FEE7ECF7B06BA,
+ 0x000FEE84D2484AB2, 0x000FEE8A60B66343, 0x000FEE8F7ACCC851,
+ 0x000FEE94207E25DA, 0x000FEE9851A829EA, 0x000FEE9C0E13485C,
+ 0x000FEE9F557273F4, 0x000FEEA22762CCAE, 0x000FEEA4836B42AC,
+ 0x000FEEA668FC2D71, 0x000FEEA7D76ED6FA, 0x000FEEA8CE04FA0A,
+ 0x000FEEA94BE8333B, 0x000FEEA950296410, 0x000FEEA8D9C0075E,
+ 0x000FEEA7E7897654, 0x000FEEA678481D24, 0x000FEEA48AA29E83,
+ 0x000FEEA21D22E4DA, 0x000FEE9F2E352024, 0x000FEE9BBC26AF2E,
+ 0x000FEE97C524F2E4, 0x000FEE93473C0A3A, 0x000FEE8E40557516,
+ 0x000FEE88AE369C7A, 0x000FEE828E7F3DFD, 0x000FEE7BDEA7B888,
+ 0x000FEE749BFF37FF, 0x000FEE6CC3A9BD5E, 0x000FEE64529E007E,
+ 0x000FEE5B45A32888, 0x000FEE51994E57B6, 0x000FEE474A0006CF,
+ 0x000FEE3C53E12C50, 0x000FEE30B2E02AD8, 0x000FEE2462AD8205,
+ 0x000FEE175EB83C5A, 0x000FEE09A22A1447, 0x000FEDFB27E349CC,
+ 0x000FEDEBEA76216C, 0x000FEDDBE422047E, 0x000FEDCB0ECE39D3,
+ 0x000FEDB964042CF4, 0x000FEDA6DCE938C9, 0x000FED937237E98D,
+ 0x000FED7F1C38A836, 0x000FED69D2B9C02B, 0x000FED538D06AE00,
+ 0x000FED3C41DEA422, 0x000FED23E76A2FD8, 0x000FED0A732FE644,
+ 0x000FECEFDA07FE34, 0x000FECD4100EB7B8, 0x000FECB708956EB4,
+ 0x000FEC98B61230C1, 0x000FEC790A0DA978, 0x000FEC57F50F31FE,
+ 0x000FEC356686C962, 0x000FEC114CB4B335, 0x000FEBEB948E6FD0,
+ 0x000FEBC429A0B692, 0x000FEB9AF5EE0CDC, 0x000FEB6FE1C98542,
+ 0x000FEB42D3AD1F9E, 0x000FEB13B00B2D4B, 0x000FEAE2591A02E9,
+ 0x000FEAAEAE992257, 0x000FEA788D8EE326, 0x000FEA3FCFFD73E5,
+ 0x000FEA044C8DD9F6, 0x000FE9C5D62F563B, 0x000FE9843BA947A4,
+ 0x000FE93F471D4728, 0x000FE8F6BD76C5D6, 0x000FE8AA5DC4E8E6,
+ 0x000FE859E07AB1EA, 0x000FE804F690A940, 0x000FE7AB488233C0,
+ 0x000FE74C751F6AA5, 0x000FE6E8102AA202, 0x000FE67DA0B6ABD8,
+ 0x000FE60C9F38307E, 0x000FE5947338F742, 0x000FE51470977280,
+ 0x000FE48BD436F458, 0x000FE3F9BFFD1E37, 0x000FE35D35EEB19C,
+ 0x000FE2B5122FE4FE, 0x000FE20003995557, 0x000FE13C82788314,
+ 0x000FE068C4EE67B0, 0x000FDF82B02B71AA, 0x000FDE87C57EFEAA,
+ 0x000FDD7509C63BFD, 0x000FDC46E529BF13, 0x000FDAF8F82E0282,
+ 0x000FD985E1B2BA75, 0x000FD7E6EF48CF04, 0x000FD613ADBD650B,
+ 0x000FD40149E2F012, 0x000FD1A1A7B4C7AC, 0x000FCEE204761F9E,
+ 0x000FCBA8D85E11B2, 0x000FC7D26ECD2D22, 0x000FC32B2F1E22ED,
+ 0x000FBD6581C0B83A, 0x000FB606C4005434, 0x000FAC40582A2874,
+ 0x000F9E971E014598, 0x000F89FA48A41DFC, 0x000F66C5F7F0302C,
+ 0x000F1A5A4B331C4A], dtype=np.uint64)
+
+wi_double = np.array([
+ 8.68362706080130616677e-16, 4.77933017572773682428e-17,
+ 6.35435241740526230246e-17, 7.45487048124769627714e-17,
+ 8.32936681579309972857e-17, 9.06806040505948228243e-17,
+ 9.71486007656776183958e-17, 1.02947503142410192108e-16,
+ 1.08234302884476839838e-16, 1.13114701961090307945e-16,
+ 1.17663594570229211411e-16, 1.21936172787143633280e-16,
+ 1.25974399146370927864e-16, 1.29810998862640315416e-16,
+ 1.33472037368241227547e-16, 1.36978648425712032797e-16,
+ 1.40348230012423820659e-16, 1.43595294520569430270e-16,
+ 1.46732087423644219083e-16, 1.49769046683910367425e-16,
+ 1.52715150035961979750e-16, 1.55578181694607639484e-16,
+ 1.58364940092908853989e-16, 1.61081401752749279325e-16,
+ 1.63732852039698532012e-16, 1.66323990584208352778e-16,
+ 1.68859017086765964015e-16, 1.71341701765596607184e-16,
+ 1.73775443658648593310e-16, 1.76163319230009959832e-16,
+ 1.78508123169767272927e-16, 1.80812402857991522674e-16,
+ 1.83078487648267501776e-16, 1.85308513886180189386e-16,
+ 1.87504446393738816849e-16, 1.89668097007747596212e-16,
+ 1.91801140648386198029e-16, 1.93905129306251037069e-16,
+ 1.95981504266288244037e-16, 1.98031606831281739736e-16,
+ 2.00056687762733300198e-16, 2.02057915620716538808e-16,
+ 2.04036384154802118313e-16, 2.05993118874037063144e-16,
+ 2.07929082904140197311e-16, 2.09845182223703516690e-16,
+ 2.11742270357603418769e-16, 2.13621152594498681022e-16,
+ 2.15482589785814580926e-16, 2.17327301775643674990e-16,
+ 2.19155970504272708519e-16, 2.20969242822353175995e-16,
+ 2.22767733047895534948e-16, 2.24552025294143552381e-16,
+ 2.26322675592856786566e-16, 2.28080213834501706782e-16,
+ 2.29825145544246839061e-16, 2.31557953510408037008e-16,
+ 2.33279099280043561128e-16, 2.34989024534709550938e-16,
+ 2.36688152357916037468e-16, 2.38376888404542434981e-16,
+ 2.40055621981350627349e-16, 2.41724727046750252175e-16,
+ 2.43384563137110286400e-16, 2.45035476226149539878e-16,
+ 2.46677799523270498158e-16, 2.48311854216108767769e-16,
+ 2.49937950162045242375e-16, 2.51556386532965786439e-16,
+ 2.53167452417135826983e-16, 2.54771427381694417303e-16,
+ 2.56368581998939683749e-16, 2.57959178339286723500e-16,
+ 2.59543470433517070146e-16, 2.61121704706701939097e-16,
+ 2.62694120385972564623e-16, 2.64260949884118951286e-16,
+ 2.65822419160830680292e-16, 2.67378748063236329361e-16,
+ 2.68930150647261591777e-16, 2.70476835481199518794e-16,
+ 2.72019005932773206655e-16, 2.73556860440867908686e-16,
+ 2.75090592773016664571e-16, 2.76620392269639032183e-16,
+ 2.78146444075954410103e-16, 2.79668929362423005309e-16,
+ 2.81188025534502074329e-16, 2.82703906432447923059e-16,
+ 2.84216742521840606520e-16, 2.85726701075460149289e-16,
+ 2.87233946347097994381e-16, 2.88738639737848191815e-16,
+ 2.90240939955384233230e-16, 2.91741003166694553259e-16,
+ 2.93238983144718163965e-16, 2.94735031409293489611e-16,
+ 2.96229297362806647792e-16, 2.97721928420902891115e-16,
+ 2.99213070138601307081e-16, 3.00702866332133102993e-16,
+ 3.02191459196806151971e-16, 3.03678989421180184427e-16,
+ 3.05165596297821922381e-16, 3.06651417830895451744e-16,
+ 3.08136590840829717032e-16, 3.09621251066292253306e-16,
+ 3.11105533263689296831e-16, 3.12589571304399892784e-16,
+ 3.14073498269944617203e-16, 3.15557446545280064031e-16,
+ 3.17041547910402852545e-16, 3.18525933630440648871e-16,
+ 3.20010734544401137886e-16, 3.21496081152744704901e-16,
+ 3.22982103703941557538e-16, 3.24468932280169778077e-16,
+ 3.25956696882307838340e-16, 3.27445527514370671802e-16,
+ 3.28935554267536967851e-16, 3.30426907403912838589e-16,
+ 3.31919717440175233652e-16, 3.33414115231237245918e-16,
+ 3.34910232054077845412e-16, 3.36408199691876507948e-16,
+ 3.37908150518594979994e-16, 3.39410217584148914282e-16,
+ 3.40914534700312603713e-16, 3.42421236527501816058e-16,
+ 3.43930458662583133920e-16, 3.45442337727858401604e-16,
+ 3.46957011461378353333e-16, 3.48474618808741370700e-16,
+ 3.49995300016538099813e-16, 3.51519196727607440975e-16,
+ 3.53046452078274009054e-16, 3.54577210797743572160e-16,
+ 3.56111619309838843415e-16, 3.57649825837265051035e-16,
+ 3.59191980508602994994e-16, 3.60738235468235137839e-16,
+ 3.62288744989419151904e-16, 3.63843665590734438546e-16,
+ 3.65403156156136995766e-16, 3.66967378058870090021e-16,
+ 3.68536495289491401456e-16, 3.70110674588289834952e-16,
+ 3.71690085582382297792e-16, 3.73274900927794352614e-16,
+ 3.74865296456848868882e-16, 3.76461451331202869131e-16,
+ 3.78063548200896037651e-16, 3.79671773369794425924e-16,
+ 3.81286316967837738238e-16, 3.82907373130524317507e-16,
+ 3.84535140186095955858e-16, 3.86169820850914927119e-16,
+ 3.87811622433558721164e-16, 3.89460757048192620674e-16,
+ 3.91117441837820542060e-16, 3.92781899208054153270e-16,
+ 3.94454357072087711446e-16, 3.96135049107613542983e-16,
+ 3.97824215026468259474e-16, 3.99522100857856502444e-16,
+ 4.01228959246062907451e-16, 4.02945049763632792393e-16,
+ 4.04670639241074995115e-16, 4.06406002114225038723e-16,
+ 4.08151420790493873480e-16, 4.09907186035326643447e-16,
+ 4.11673597380302570170e-16, 4.13450963554423599878e-16,
+ 4.15239602940268833891e-16, 4.17039844056831587498e-16,
+ 4.18852026071011229572e-16, 4.20676499339901510978e-16,
+ 4.22513625986204937320e-16, 4.24363780509307796137e-16,
+ 4.26227350434779809917e-16, 4.28104737005311666397e-16,
+ 4.29996355916383230161e-16, 4.31902638100262944617e-16,
+ 4.33824030562279080411e-16, 4.35760997273684900553e-16,
+ 4.37714020125858747008e-16, 4.39683599951052137423e-16,
+ 4.41670257615420348435e-16, 4.43674535190656726604e-16,
+ 4.45696997211204306674e-16, 4.47738232024753387312e-16,
+ 4.49798853244554968009e-16, 4.51879501313005876278e-16,
+ 4.53980845187003400947e-16, 4.56103584156742206384e-16,
+ 4.58248449810956667052e-16, 4.60416208163115281428e-16,
+ 4.62607661954784567754e-16, 4.64823653154320737780e-16,
+ 4.67065065671263059081e-16, 4.69332828309332890697e-16,
+ 4.71627917983835129766e-16, 4.73951363232586715165e-16,
+ 4.76304248053313737663e-16, 4.78687716104872284247e-16,
+ 4.81102975314741720538e-16, 4.83551302941152515162e-16,
+ 4.86034051145081195402e-16, 4.88552653135360343280e-16,
+ 4.91108629959526955862e-16, 4.93703598024033454728e-16,
+ 4.96339277440398725619e-16, 4.99017501309182245754e-16,
+ 5.01740226071808946011e-16, 5.04509543081872748637e-16,
+ 5.07327691573354207058e-16, 5.10197073234156184149e-16,
+ 5.13120268630678373200e-16, 5.16100055774322824569e-16,
+ 5.19139431175769859873e-16, 5.22241633800023428760e-16,
+ 5.25410172417759732697e-16, 5.28648856950494511482e-16,
+ 5.31961834533840037535e-16, 5.35353631181649688145e-16,
+ 5.38829200133405320160e-16, 5.42393978220171234073e-16,
+ 5.46053951907478041166e-16, 5.49815735089281410703e-16,
+ 5.53686661246787600374e-16, 5.57674893292657647836e-16,
+ 5.61789555355541665830e-16, 5.66040892008242216739e-16,
+ 5.70440462129138908417e-16, 5.75001376891989523684e-16,
+ 5.79738594572459365014e-16, 5.84669289345547900201e-16,
+ 5.89813317647789942685e-16, 5.95193814964144415532e-16,
+ 6.00837969627190832234e-16, 6.06778040933344851394e-16,
+ 6.13052720872528159123e-16, 6.19708989458162555387e-16,
+ 6.26804696330128439415e-16, 6.34412240712750598627e-16,
+ 6.42623965954805540945e-16, 6.51560331734499356881e-16,
+ 6.61382788509766415145e-16, 6.72315046250558662913e-16,
+ 6.84680341756425875856e-16, 6.98971833638761995415e-16,
+ 7.15999493483066421560e-16, 7.37242430179879890722e-16,
+ 7.65893637080557275482e-16, 8.11384933765648418565e-16],
+ dtype=np.float64)
+
+fi_double = np.array([
+ 1.00000000000000000000e+00, 9.77101701267671596263e-01,
+ 9.59879091800106665211e-01, 9.45198953442299649730e-01,
+ 9.32060075959230460718e-01, 9.19991505039347012840e-01,
+ 9.08726440052130879366e-01, 8.98095921898343418910e-01,
+ 8.87984660755833377088e-01, 8.78309655808917399966e-01,
+ 8.69008688036857046555e-01, 8.60033621196331532488e-01,
+ 8.51346258458677951353e-01, 8.42915653112204177333e-01,
+ 8.34716292986883434679e-01, 8.26726833946221373317e-01,
+ 8.18929191603702366642e-01, 8.11307874312656274185e-01,
+ 8.03849483170964274059e-01, 7.96542330422958966274e-01,
+ 7.89376143566024590648e-01, 7.82341832654802504798e-01,
+ 7.75431304981187174974e-01, 7.68637315798486264740e-01,
+ 7.61953346836795386565e-01, 7.55373506507096115214e-01,
+ 7.48892447219156820459e-01, 7.42505296340151055290e-01,
+ 7.36207598126862650112e-01, 7.29995264561476231435e-01,
+ 7.23864533468630222401e-01, 7.17811932630721960535e-01,
+ 7.11834248878248421200e-01, 7.05928501332754310127e-01,
+ 7.00091918136511615067e-01, 6.94321916126116711609e-01,
+ 6.88616083004671808432e-01, 6.82972161644994857355e-01,
+ 6.77388036218773526009e-01, 6.71861719897082099173e-01,
+ 6.66391343908750100056e-01, 6.60975147776663107813e-01,
+ 6.55611470579697264149e-01, 6.50298743110816701574e-01,
+ 6.45035480820822293424e-01, 6.39820277453056585060e-01,
+ 6.34651799287623608059e-01, 6.29528779924836690007e-01,
+ 6.24450015547026504592e-01, 6.19414360605834324325e-01,
+ 6.14420723888913888899e-01, 6.09468064925773433949e-01,
+ 6.04555390697467776029e-01, 5.99681752619125263415e-01,
+ 5.94846243767987448159e-01, 5.90047996332826008015e-01,
+ 5.85286179263371453274e-01, 5.80559996100790898232e-01,
+ 5.75868682972353718164e-01, 5.71211506735253227163e-01,
+ 5.66587763256164445025e-01, 5.61996775814524340831e-01,
+ 5.57437893618765945014e-01, 5.52910490425832290562e-01,
+ 5.48413963255265812791e-01, 5.43947731190026262382e-01,
+ 5.39511234256952132426e-01, 5.35103932380457614215e-01,
+ 5.30725304403662057062e-01, 5.26374847171684479008e-01,
+ 5.22052074672321841931e-01, 5.17756517229756352272e-01,
+ 5.13487720747326958914e-01, 5.09245245995747941592e-01,
+ 5.05028667943468123624e-01, 5.00837575126148681903e-01,
+ 4.96671569052489714213e-01, 4.92530263643868537748e-01,
+ 4.88413284705458028423e-01, 4.84320269426683325253e-01,
+ 4.80250865909046753544e-01, 4.76204732719505863248e-01,
+ 4.72181538467730199660e-01, 4.68180961405693596422e-01,
+ 4.64202689048174355069e-01, 4.60246417812842867345e-01,
+ 4.56311852678716434184e-01, 4.52398706861848520777e-01,
+ 4.48506701507203064949e-01, 4.44635565395739396077e-01,
+ 4.40785034665803987508e-01, 4.36954852547985550526e-01,
+ 4.33144769112652261445e-01, 4.29354541029441427735e-01,
+ 4.25583931338021970170e-01, 4.21832709229495894654e-01,
+ 4.18100649837848226120e-01, 4.14387534040891125642e-01,
+ 4.10693148270188157500e-01, 4.07017284329473372217e-01,
+ 4.03359739221114510510e-01, 3.99720314980197222177e-01,
+ 3.96098818515832451492e-01, 3.92495061459315619512e-01,
+ 3.88908860018788715696e-01, 3.85340034840077283462e-01,
+ 3.81788410873393657674e-01, 3.78253817245619183840e-01,
+ 3.74736087137891138443e-01, 3.71235057668239498696e-01,
+ 3.67750569779032587814e-01, 3.64282468129004055601e-01,
+ 3.60830600989648031529e-01, 3.57394820145780500731e-01,
+ 3.53974980800076777232e-01, 3.50570941481406106455e-01,
+ 3.47182563956793643900e-01, 3.43809713146850715049e-01,
+ 3.40452257044521866547e-01, 3.37110066637006045021e-01,
+ 3.33783015830718454708e-01, 3.30470981379163586400e-01,
+ 3.27173842813601400970e-01, 3.23891482376391093290e-01,
+ 3.20623784956905355514e-01, 3.17370638029913609834e-01,
+ 3.14131931596337177215e-01, 3.10907558126286509559e-01,
+ 3.07697412504292056035e-01, 3.04501391976649993243e-01,
+ 3.01319396100803049698e-01, 2.98151326696685481377e-01,
+ 2.94997087799961810184e-01, 2.91856585617095209972e-01,
+ 2.88729728482182923521e-01, 2.85616426815501756042e-01,
+ 2.82516593083707578948e-01, 2.79430141761637940157e-01,
+ 2.76356989295668320494e-01, 2.73297054068577072172e-01,
+ 2.70250256365875463072e-01, 2.67216518343561471038e-01,
+ 2.64195763997261190426e-01, 2.61187919132721213522e-01,
+ 2.58192911337619235290e-01, 2.55210669954661961700e-01,
+ 2.52241126055942177508e-01, 2.49284212418528522415e-01,
+ 2.46339863501263828249e-01, 2.43408015422750312329e-01,
+ 2.40488605940500588254e-01, 2.37581574431238090606e-01,
+ 2.34686861872330010392e-01, 2.31804410824338724684e-01,
+ 2.28934165414680340644e-01, 2.26076071322380278694e-01,
+ 2.23230075763917484855e-01, 2.20396127480151998723e-01,
+ 2.17574176724331130872e-01, 2.14764175251173583536e-01,
+ 2.11966076307030182324e-01, 2.09179834621125076977e-01,
+ 2.06405406397880797353e-01, 2.03642749310334908452e-01,
+ 2.00891822494656591136e-01, 1.98152586545775138971e-01,
+ 1.95425003514134304483e-01, 1.92709036903589175926e-01,
+ 1.90004651670464985713e-01, 1.87311814223800304768e-01,
+ 1.84630492426799269756e-01, 1.81960655599522513892e-01,
+ 1.79302274522847582272e-01, 1.76655321443734858455e-01,
+ 1.74019770081838553999e-01, 1.71395595637505754327e-01,
+ 1.68782774801211288285e-01, 1.66181285764481906364e-01,
+ 1.63591108232365584074e-01, 1.61012223437511009516e-01,
+ 1.58444614155924284882e-01, 1.55888264724479197465e-01,
+ 1.53343161060262855866e-01, 1.50809290681845675763e-01,
+ 1.48286642732574552861e-01, 1.45775208005994028060e-01,
+ 1.43274978973513461566e-01, 1.40785949814444699690e-01,
+ 1.38308116448550733057e-01, 1.35841476571253755301e-01,
+ 1.33386029691669155683e-01, 1.30941777173644358090e-01,
+ 1.28508722279999570981e-01, 1.26086870220185887081e-01,
+ 1.23676228201596571932e-01, 1.21276805484790306533e-01,
+ 1.18888613442910059947e-01, 1.16511665625610869035e-01,
+ 1.14145977827838487895e-01, 1.11791568163838089811e-01,
+ 1.09448457146811797824e-01, 1.07116667774683801961e-01,
+ 1.04796225622487068629e-01, 1.02487158941935246892e-01,
+ 1.00189498768810017482e-01, 9.79032790388624646338e-02,
+ 9.56285367130089991594e-02, 9.33653119126910124859e-02,
+ 9.11136480663737591268e-02, 8.88735920682758862021e-02,
+ 8.66451944505580717859e-02, 8.44285095703534715916e-02,
+ 8.22235958132029043366e-02, 8.00305158146630696292e-02,
+ 7.78493367020961224423e-02, 7.56801303589271778804e-02,
+ 7.35229737139813238622e-02, 7.13779490588904025339e-02,
+ 6.92451443970067553879e-02, 6.71246538277884968737e-02,
+ 6.50165779712428976156e-02, 6.29210244377581412456e-02,
+ 6.08381083495398780614e-02, 5.87679529209337372930e-02,
+ 5.67106901062029017391e-02, 5.46664613248889208474e-02,
+ 5.26354182767921896513e-02, 5.06177238609477817000e-02,
+ 4.86135532158685421122e-02, 4.66230949019303814174e-02,
+ 4.46465522512944634759e-02, 4.26841449164744590750e-02,
+ 4.07361106559409394401e-02, 3.88027074045261474722e-02,
+ 3.68842156885673053135e-02, 3.49809414617161251737e-02,
+ 3.30932194585785779961e-02, 3.12214171919203004046e-02,
+ 2.93659397581333588001e-02, 2.75272356696031131329e-02,
+ 2.57058040085489103443e-02, 2.39022033057958785407e-02,
+ 2.21170627073088502113e-02, 2.03510962300445102935e-02,
+ 1.86051212757246224594e-02, 1.68800831525431419000e-02,
+ 1.51770883079353092332e-02, 1.34974506017398673818e-02,
+ 1.18427578579078790488e-02, 1.02149714397014590439e-02,
+ 8.61658276939872638800e-03, 7.05087547137322242369e-03,
+ 5.52240329925099155545e-03, 4.03797259336302356153e-03,
+ 2.60907274610215926189e-03, 1.26028593049859797236e-03],
+ dtype=np.float64)
+
+ki_float = np.array([
+ 0x007799EC, 0x00000000, 0x006045F5, 0x006D1AA8, 0x00728FB4,
+ 0x007592AF, 0x00777A5C, 0x0078CA38, 0x0079BF6B, 0x007A7A35,
+ 0x007B0D2F, 0x007B83D4, 0x007BE597, 0x007C3788, 0x007C7D33,
+ 0x007CB926, 0x007CED48, 0x007D1B08, 0x007D437F, 0x007D678B,
+ 0x007D87DB, 0x007DA4FC, 0x007DBF61, 0x007DD767, 0x007DED5D,
+ 0x007E0183, 0x007E1411, 0x007E2534, 0x007E3515, 0x007E43D5,
+ 0x007E5193, 0x007E5E67, 0x007E6A69, 0x007E75AA, 0x007E803E,
+ 0x007E8A32, 0x007E9395, 0x007E9C72, 0x007EA4D5, 0x007EACC6,
+ 0x007EB44E, 0x007EBB75, 0x007EC243, 0x007EC8BC, 0x007ECEE8,
+ 0x007ED4CC, 0x007EDA6B, 0x007EDFCB, 0x007EE4EF, 0x007EE9DC,
+ 0x007EEE94, 0x007EF31B, 0x007EF774, 0x007EFBA0, 0x007EFFA3,
+ 0x007F037F, 0x007F0736, 0x007F0ACA, 0x007F0E3C, 0x007F118F,
+ 0x007F14C4, 0x007F17DC, 0x007F1ADA, 0x007F1DBD, 0x007F2087,
+ 0x007F233A, 0x007F25D7, 0x007F285D, 0x007F2AD0, 0x007F2D2E,
+ 0x007F2F7A, 0x007F31B3, 0x007F33DC, 0x007F35F3, 0x007F37FB,
+ 0x007F39F3, 0x007F3BDC, 0x007F3DB7, 0x007F3F84, 0x007F4145,
+ 0x007F42F8, 0x007F449F, 0x007F463A, 0x007F47CA, 0x007F494E,
+ 0x007F4AC8, 0x007F4C38, 0x007F4D9D, 0x007F4EF9, 0x007F504C,
+ 0x007F5195, 0x007F52D5, 0x007F540D, 0x007F553D, 0x007F5664,
+ 0x007F5784, 0x007F589C, 0x007F59AC, 0x007F5AB5, 0x007F5BB8,
+ 0x007F5CB3, 0x007F5DA8, 0x007F5E96, 0x007F5F7E, 0x007F605F,
+ 0x007F613B, 0x007F6210, 0x007F62E0, 0x007F63AA, 0x007F646F,
+ 0x007F652E, 0x007F65E8, 0x007F669C, 0x007F674C, 0x007F67F6,
+ 0x007F689C, 0x007F693C, 0x007F69D9, 0x007F6A70, 0x007F6B03,
+ 0x007F6B91, 0x007F6C1B, 0x007F6CA0, 0x007F6D21, 0x007F6D9E,
+ 0x007F6E17, 0x007F6E8C, 0x007F6EFC, 0x007F6F68, 0x007F6FD1,
+ 0x007F7035, 0x007F7096, 0x007F70F3, 0x007F714C, 0x007F71A1,
+ 0x007F71F2, 0x007F723F, 0x007F7289, 0x007F72CF, 0x007F7312,
+ 0x007F7350, 0x007F738B, 0x007F73C3, 0x007F73F6, 0x007F7427,
+ 0x007F7453, 0x007F747C, 0x007F74A1, 0x007F74C3, 0x007F74E0,
+ 0x007F74FB, 0x007F7511, 0x007F7524, 0x007F7533, 0x007F753F,
+ 0x007F7546, 0x007F754A, 0x007F754B, 0x007F7547, 0x007F753F,
+ 0x007F7534, 0x007F7524, 0x007F7511, 0x007F74F9, 0x007F74DE,
+ 0x007F74BE, 0x007F749A, 0x007F7472, 0x007F7445, 0x007F7414,
+ 0x007F73DF, 0x007F73A5, 0x007F7366, 0x007F7323, 0x007F72DA,
+ 0x007F728D, 0x007F723A, 0x007F71E3, 0x007F7186, 0x007F7123,
+ 0x007F70BB, 0x007F704D, 0x007F6FD9, 0x007F6F5F, 0x007F6EDF,
+ 0x007F6E58, 0x007F6DCB, 0x007F6D37, 0x007F6C9C, 0x007F6BF9,
+ 0x007F6B4F, 0x007F6A9C, 0x007F69E2, 0x007F691F, 0x007F6854,
+ 0x007F677F, 0x007F66A1, 0x007F65B8, 0x007F64C6, 0x007F63C8,
+ 0x007F62C0, 0x007F61AB, 0x007F608A, 0x007F5F5D, 0x007F5E21,
+ 0x007F5CD8, 0x007F5B7F, 0x007F5A17, 0x007F589E, 0x007F5713,
+ 0x007F5575, 0x007F53C4, 0x007F51FE, 0x007F5022, 0x007F4E2F,
+ 0x007F4C22, 0x007F49FA, 0x007F47B6, 0x007F4553, 0x007F42CF,
+ 0x007F4028, 0x007F3D5A, 0x007F3A64, 0x007F3741, 0x007F33ED,
+ 0x007F3065, 0x007F2CA4, 0x007F28A4, 0x007F245F, 0x007F1FCE,
+ 0x007F1AEA, 0x007F15A9, 0x007F1000, 0x007F09E4, 0x007F0346,
+ 0x007EFC16, 0x007EF43E, 0x007EEBA8, 0x007EE237, 0x007ED7C8,
+ 0x007ECC2F, 0x007EBF37, 0x007EB09D, 0x007EA00A, 0x007E8D0D,
+ 0x007E7710, 0x007E5D47, 0x007E3E93, 0x007E1959, 0x007DEB2C,
+ 0x007DB036, 0x007D6203, 0x007CF4B9, 0x007C4FD2, 0x007B3630,
+ 0x0078D2D2], dtype=np.uint32)
+
+wi_float = np.array([
+ 4.66198677960027669255e-07, 2.56588335019207033255e-08,
+ 3.41146697750176784592e-08, 4.00230311410932959821e-08,
+ 4.47179475877737745459e-08, 4.86837785973537366722e-08,
+ 5.21562578925932412861e-08, 5.52695199001886257153e-08,
+ 5.81078488992733116465e-08, 6.07279932024587421409e-08,
+ 6.31701613261172047795e-08, 6.54639842900233842742e-08,
+ 6.76319905583641815324e-08, 6.96917493470166688656e-08,
+ 7.16572544283857476692e-08, 7.35398519048393832969e-08,
+ 7.53488822443557479279e-08, 7.70921367281667127885e-08,
+ 7.87761895947956022626e-08, 8.04066446825615346857e-08,
+ 8.19883218760237408659e-08, 8.35254002936857088917e-08,
+ 8.50215298165053411740e-08, 8.64799190652369040985e-08,
+ 8.79034055989140110861e-08, 8.92945125124233511541e-08,
+ 9.06554945027956262312e-08, 9.19883756905278607229e-08,
+ 9.32949809202232869780e-08, 9.45769618559625849039e-08,
+ 9.58358188855612866442e-08, 9.70729196232813152662e-08,
+ 9.82895146313061088986e-08, 9.94867508514382224721e-08,
+ 1.00665683139461669691e-07, 1.01827284217853923044e-07,
+ 1.02972453302539369464e-07, 1.04102023612124921572e-07,
+ 1.05216768930574060431e-07, 1.06317409364335657741e-07,
+ 1.07404616410877866490e-07, 1.08479017436113134283e-07,
+ 1.09541199642370962438e-07, 1.10591713595628691212e-07,
+ 1.11631076370069356306e-07, 1.12659774359245895023e-07,
+ 1.13678265795837113569e-07, 1.14686983015899673063e-07,
+ 1.15686334498432158725e-07, 1.16676706706789039179e-07,
+ 1.17658465754873988919e-07, 1.18631958917986203582e-07,
+ 1.19597516005596215528e-07, 1.20555450611113917226e-07,
+ 1.21506061251817163689e-07, 1.22449632410483948386e-07,
+ 1.23386435488872536840e-07, 1.24316729681986364321e-07,
+ 1.25240762781015530062e-07, 1.26158771911939892267e-07,
+ 1.27070984215989333455e-07, 1.27977617477468922011e-07,
+ 1.28878880703854958297e-07, 1.29774974662539874521e-07,
+ 1.30666092378141980504e-07, 1.31552419593887221722e-07,
+ 1.32434135200211397569e-07, 1.33311411633413359243e-07,
+ 1.34184415246907777059e-07, 1.35053306657377859830e-07,
+ 1.35918241067904315860e-07, 1.36779368569952053923e-07,
+ 1.37636834425917531047e-07, 1.38490779333783508675e-07,
+ 1.39341339675287344817e-07, 1.40188647748881762555e-07,
+ 1.41032831988654882776e-07, 1.41874017170273235693e-07,
+ 1.42712324604921442006e-07, 1.43547872322127921816e-07,
+ 1.44380775242292721080e-07, 1.45211145339665544509e-07,
+ 1.46039091796461362146e-07, 1.46864721148745476208e-07,
+ 1.47688137424670065700e-07, 1.48509442275598857119e-07,
+ 1.49328735100614641423e-07, 1.50146113164867617390e-07,
+ 1.50961671712187416111e-07, 1.51775504072350982845e-07,
+ 1.52587701763369746341e-07, 1.53398354589133671168e-07,
+ 1.54207550732725568797e-07, 1.55015376845697999657e-07,
+ 1.55821918133584372604e-07, 1.56627258437898192833e-07,
+ 1.57431480314857468671e-07, 1.58234665111056041043e-07,
+ 1.59036893036289199880e-07, 1.59838243233728855017e-07,
+ 1.60638793847630850137e-07, 1.61438622088746393909e-07,
+ 1.62237804297600106296e-07, 1.63036416005787357730e-07,
+ 1.63834531995435479082e-07, 1.64632226356965902954e-07,
+ 1.65429572545287097020e-07, 1.66226643434541294491e-07,
+ 1.67023511371523209274e-07, 1.67820248227882200051e-07,
+ 1.68616925451215588827e-07, 1.69413614115155757272e-07,
+ 1.70210384968549673733e-07, 1.71007308483826142122e-07,
+ 1.71804454904642543391e-07, 1.72601894292900061024e-07,
+ 1.73399696575213681990e-07, 1.74197931588920988271e-07,
+ 1.74996669127712165834e-07, 1.75795978986961275677e-07,
+ 1.76595931008838063924e-07, 1.77396595127278238022e-07,
+ 1.78198041412889183130e-07, 1.79000340117867431104e-07,
+ 1.79803561721004406185e-07, 1.80607776972855859813e-07,
+ 1.81413056941151359868e-07, 1.82219473056520464354e-07,
+ 1.83027097158612474240e-07, 1.83836001542687613069e-07,
+ 1.84646259006759307383e-07, 1.85457942899367347876e-07,
+ 1.86271127168064649331e-07, 1.87085886408701333260e-07,
+ 1.87902295915592424729e-07, 1.88720431732658022414e-07,
+ 1.89540370705627262627e-07, 1.90362190535400839128e-07,
+ 1.91185969832669990437e-07, 1.92011788173893651535e-07,
+ 1.92839726158739913768e-07, 1.93669865469102145482e-07,
+ 1.94502288929804890433e-07, 1.95337080571120616772e-07,
+ 1.96174325693223683314e-07, 1.97014110932714374919e-07,
+ 1.97856524331352952716e-07, 1.98701655407150388211e-07,
+ 1.99549595227971635348e-07, 2.00400436487814600236e-07,
+ 2.01254273585938820883e-07, 2.02111202709026498408e-07,
+ 2.02971321916571014951e-07, 2.03834731229698846698e-07,
+ 2.04701532723644121196e-07, 2.05571830624108885378e-07,
+ 2.06445731407757185541e-07, 2.07323343907107312957e-07,
+ 2.08204779420104330037e-07, 2.09090151824673600213e-07,
+ 2.09979577698577670508e-07, 2.10873176444920111011e-07,
+ 2.11771070423665379388e-07, 2.12673385089569268965e-07,
+ 2.13580249136944118603e-07, 2.14491794651713402832e-07,
+ 2.15408157271244625533e-07, 2.16329476352486921685e-07,
+ 2.17255895148978920488e-07, 2.18187560997337924713e-07,
+ 2.19124625513888206785e-07, 2.20067244802139479285e-07,
+ 2.21015579671883851683e-07, 2.21969795870742159701e-07,
+ 2.22930064329060010376e-07, 2.23896561419128954210e-07,
+ 2.24869469229791575583e-07, 2.25848975857580322189e-07,
+ 2.26835275715640744118e-07, 2.27828569861799901001e-07,
+ 2.28829066347263833069e-07, 2.29836980587561823183e-07,
+ 2.30852535757505260518e-07, 2.31875963212094114516e-07,
+ 2.32907502935486642699e-07, 2.33947404020352726160e-07,
+ 2.34995925180156140289e-07, 2.36053335297164516378e-07,
+ 2.37119914009265667728e-07, 2.38195952338983970691e-07,
+ 2.39281753368440712742e-07, 2.40377632964396957621e-07,
+ 2.41483920557958384709e-07, 2.42600959984018662258e-07,
+ 2.43729110386077326413e-07, 2.44868747192698939290e-07,
+ 2.46020263172594533433e-07, 2.47184069576113545901e-07,
+ 2.48360597371852893654e-07, 2.49550298588131851232e-07,
+ 2.50753647770270890721e-07, 2.51971143565970967140e-07,
+ 2.53203310452642767375e-07, 2.54450700622322097890e-07,
+ 2.55713896041856770961e-07, 2.56993510708419870887e-07,
+ 2.58290193123138874550e-07, 2.59604629008804833146e-07,
+ 2.60937544301314385690e-07, 2.62289708448800566945e-07,
+ 2.63661938057441759882e-07, 2.65055100928844238758e-07,
+ 2.66470120540847889467e-07, 2.67907981031821866252e-07,
+ 2.69369732758258246335e-07, 2.70856498507068313229e-07,
+ 2.72369480457841388042e-07, 2.73909968006952220135e-07,
+ 2.75479346585437289399e-07, 2.77079107626811561009e-07,
+ 2.78710859870496796972e-07, 2.80376342222588603820e-07,
+ 2.82077438439999912690e-07, 2.83816193958769527230e-07,
+ 2.85594835255375795814e-07, 2.87415792215003905739e-07,
+ 2.89281724087851835900e-07, 2.91195549750371467233e-07,
+ 2.93160483161771875581e-07, 2.95180075129332912389e-07,
+ 2.97258262785797916083e-07, 2.99399428561531794298e-07,
+ 3.01608470935804138388e-07, 3.03890889921758510417e-07,
+ 3.06252891144972267537e-07, 3.08701513613258141075e-07,
+ 3.11244787989714509378e-07, 3.13891934589336184321e-07,
+ 3.16653613755314681314e-07, 3.19542246256559459667e-07,
+ 3.22572428717978242099e-07, 3.25761480217458181578e-07,
+ 3.29130173358915628534e-07, 3.32703730345002116955e-07,
+ 3.36513208964639108346e-07, 3.40597478255417943913e-07,
+ 3.45006114675213401550e-07, 3.49803789521323211592e-07,
+ 3.55077180848341416206e-07, 3.60946392031859609868e-07,
+ 3.67584959507244041831e-07, 3.75257645787954431030e-07,
+ 3.84399301057791926300e-07, 3.95804015855768440983e-07,
+ 4.11186015434435801956e-07, 4.35608969373823260746e-07],
+ dtype=np.float32)
+
+fi_float = np.array([
+ 1.00000000000000000000e+00, 9.77101701267671596263e-01,
+ 9.59879091800106665211e-01, 9.45198953442299649730e-01,
+ 9.32060075959230460718e-01, 9.19991505039347012840e-01,
+ 9.08726440052130879366e-01, 8.98095921898343418910e-01,
+ 8.87984660755833377088e-01, 8.78309655808917399966e-01,
+ 8.69008688036857046555e-01, 8.60033621196331532488e-01,
+ 8.51346258458677951353e-01, 8.42915653112204177333e-01,
+ 8.34716292986883434679e-01, 8.26726833946221373317e-01,
+ 8.18929191603702366642e-01, 8.11307874312656274185e-01,
+ 8.03849483170964274059e-01, 7.96542330422958966274e-01,
+ 7.89376143566024590648e-01, 7.82341832654802504798e-01,
+ 7.75431304981187174974e-01, 7.68637315798486264740e-01,
+ 7.61953346836795386565e-01, 7.55373506507096115214e-01,
+ 7.48892447219156820459e-01, 7.42505296340151055290e-01,
+ 7.36207598126862650112e-01, 7.29995264561476231435e-01,
+ 7.23864533468630222401e-01, 7.17811932630721960535e-01,
+ 7.11834248878248421200e-01, 7.05928501332754310127e-01,
+ 7.00091918136511615067e-01, 6.94321916126116711609e-01,
+ 6.88616083004671808432e-01, 6.82972161644994857355e-01,
+ 6.77388036218773526009e-01, 6.71861719897082099173e-01,
+ 6.66391343908750100056e-01, 6.60975147776663107813e-01,
+ 6.55611470579697264149e-01, 6.50298743110816701574e-01,
+ 6.45035480820822293424e-01, 6.39820277453056585060e-01,
+ 6.34651799287623608059e-01, 6.29528779924836690007e-01,
+ 6.24450015547026504592e-01, 6.19414360605834324325e-01,
+ 6.14420723888913888899e-01, 6.09468064925773433949e-01,
+ 6.04555390697467776029e-01, 5.99681752619125263415e-01,
+ 5.94846243767987448159e-01, 5.90047996332826008015e-01,
+ 5.85286179263371453274e-01, 5.80559996100790898232e-01,
+ 5.75868682972353718164e-01, 5.71211506735253227163e-01,
+ 5.66587763256164445025e-01, 5.61996775814524340831e-01,
+ 5.57437893618765945014e-01, 5.52910490425832290562e-01,
+ 5.48413963255265812791e-01, 5.43947731190026262382e-01,
+ 5.39511234256952132426e-01, 5.35103932380457614215e-01,
+ 5.30725304403662057062e-01, 5.26374847171684479008e-01,
+ 5.22052074672321841931e-01, 5.17756517229756352272e-01,
+ 5.13487720747326958914e-01, 5.09245245995747941592e-01,
+ 5.05028667943468123624e-01, 5.00837575126148681903e-01,
+ 4.96671569052489714213e-01, 4.92530263643868537748e-01,
+ 4.88413284705458028423e-01, 4.84320269426683325253e-01,
+ 4.80250865909046753544e-01, 4.76204732719505863248e-01,
+ 4.72181538467730199660e-01, 4.68180961405693596422e-01,
+ 4.64202689048174355069e-01, 4.60246417812842867345e-01,
+ 4.56311852678716434184e-01, 4.52398706861848520777e-01,
+ 4.48506701507203064949e-01, 4.44635565395739396077e-01,
+ 4.40785034665803987508e-01, 4.36954852547985550526e-01,
+ 4.33144769112652261445e-01, 4.29354541029441427735e-01,
+ 4.25583931338021970170e-01, 4.21832709229495894654e-01,
+ 4.18100649837848226120e-01, 4.14387534040891125642e-01,
+ 4.10693148270188157500e-01, 4.07017284329473372217e-01,
+ 4.03359739221114510510e-01, 3.99720314980197222177e-01,
+ 3.96098818515832451492e-01, 3.92495061459315619512e-01,
+ 3.88908860018788715696e-01, 3.85340034840077283462e-01,
+ 3.81788410873393657674e-01, 3.78253817245619183840e-01,
+ 3.74736087137891138443e-01, 3.71235057668239498696e-01,
+ 3.67750569779032587814e-01, 3.64282468129004055601e-01,
+ 3.60830600989648031529e-01, 3.57394820145780500731e-01,
+ 3.53974980800076777232e-01, 3.50570941481406106455e-01,
+ 3.47182563956793643900e-01, 3.43809713146850715049e-01,
+ 3.40452257044521866547e-01, 3.37110066637006045021e-01,
+ 3.33783015830718454708e-01, 3.30470981379163586400e-01,
+ 3.27173842813601400970e-01, 3.23891482376391093290e-01,
+ 3.20623784956905355514e-01, 3.17370638029913609834e-01,
+ 3.14131931596337177215e-01, 3.10907558126286509559e-01,
+ 3.07697412504292056035e-01, 3.04501391976649993243e-01,
+ 3.01319396100803049698e-01, 2.98151326696685481377e-01,
+ 2.94997087799961810184e-01, 2.91856585617095209972e-01,
+ 2.88729728482182923521e-01, 2.85616426815501756042e-01,
+ 2.82516593083707578948e-01, 2.79430141761637940157e-01,
+ 2.76356989295668320494e-01, 2.73297054068577072172e-01,
+ 2.70250256365875463072e-01, 2.67216518343561471038e-01,
+ 2.64195763997261190426e-01, 2.61187919132721213522e-01,
+ 2.58192911337619235290e-01, 2.55210669954661961700e-01,
+ 2.52241126055942177508e-01, 2.49284212418528522415e-01,
+ 2.46339863501263828249e-01, 2.43408015422750312329e-01,
+ 2.40488605940500588254e-01, 2.37581574431238090606e-01,
+ 2.34686861872330010392e-01, 2.31804410824338724684e-01,
+ 2.28934165414680340644e-01, 2.26076071322380278694e-01,
+ 2.23230075763917484855e-01, 2.20396127480151998723e-01,
+ 2.17574176724331130872e-01, 2.14764175251173583536e-01,
+ 2.11966076307030182324e-01, 2.09179834621125076977e-01,
+ 2.06405406397880797353e-01, 2.03642749310334908452e-01,
+ 2.00891822494656591136e-01, 1.98152586545775138971e-01,
+ 1.95425003514134304483e-01, 1.92709036903589175926e-01,
+ 1.90004651670464985713e-01, 1.87311814223800304768e-01,
+ 1.84630492426799269756e-01, 1.81960655599522513892e-01,
+ 1.79302274522847582272e-01, 1.76655321443734858455e-01,
+ 1.74019770081838553999e-01, 1.71395595637505754327e-01,
+ 1.68782774801211288285e-01, 1.66181285764481906364e-01,
+ 1.63591108232365584074e-01, 1.61012223437511009516e-01,
+ 1.58444614155924284882e-01, 1.55888264724479197465e-01,
+ 1.53343161060262855866e-01, 1.50809290681845675763e-01,
+ 1.48286642732574552861e-01, 1.45775208005994028060e-01,
+ 1.43274978973513461566e-01, 1.40785949814444699690e-01,
+ 1.38308116448550733057e-01, 1.35841476571253755301e-01,
+ 1.33386029691669155683e-01, 1.30941777173644358090e-01,
+ 1.28508722279999570981e-01, 1.26086870220185887081e-01,
+ 1.23676228201596571932e-01, 1.21276805484790306533e-01,
+ 1.18888613442910059947e-01, 1.16511665625610869035e-01,
+ 1.14145977827838487895e-01, 1.11791568163838089811e-01,
+ 1.09448457146811797824e-01, 1.07116667774683801961e-01,
+ 1.04796225622487068629e-01, 1.02487158941935246892e-01,
+ 1.00189498768810017482e-01, 9.79032790388624646338e-02,
+ 9.56285367130089991594e-02, 9.33653119126910124859e-02,
+ 9.11136480663737591268e-02, 8.88735920682758862021e-02,
+ 8.66451944505580717859e-02, 8.44285095703534715916e-02,
+ 8.22235958132029043366e-02, 8.00305158146630696292e-02,
+ 7.78493367020961224423e-02, 7.56801303589271778804e-02,
+ 7.35229737139813238622e-02, 7.13779490588904025339e-02,
+ 6.92451443970067553879e-02, 6.71246538277884968737e-02,
+ 6.50165779712428976156e-02, 6.29210244377581412456e-02,
+ 6.08381083495398780614e-02, 5.87679529209337372930e-02,
+ 5.67106901062029017391e-02, 5.46664613248889208474e-02,
+ 5.26354182767921896513e-02, 5.06177238609477817000e-02,
+ 4.86135532158685421122e-02, 4.66230949019303814174e-02,
+ 4.46465522512944634759e-02, 4.26841449164744590750e-02,
+ 4.07361106559409394401e-02, 3.88027074045261474722e-02,
+ 3.68842156885673053135e-02, 3.49809414617161251737e-02,
+ 3.30932194585785779961e-02, 3.12214171919203004046e-02,
+ 2.93659397581333588001e-02, 2.75272356696031131329e-02,
+ 2.57058040085489103443e-02, 2.39022033057958785407e-02,
+ 2.21170627073088502113e-02, 2.03510962300445102935e-02,
+ 1.86051212757246224594e-02, 1.68800831525431419000e-02,
+ 1.51770883079353092332e-02, 1.34974506017398673818e-02,
+ 1.18427578579078790488e-02, 1.02149714397014590439e-02,
+ 8.61658276939872638800e-03, 7.05087547137322242369e-03,
+ 5.52240329925099155545e-03, 4.03797259336302356153e-03,
+ 2.60907274610215926189e-03, 1.26028593049859797236e-03],
+ dtype=np.float32)
+
+ke_double = np.array([
+ 0x001C5214272497C6, 0x0000000000000000, 0x00137D5BD79C317E,
+ 0x00186EF58E3F3C10, 0x001A9BB7320EB0AE, 0x001BD127F719447C,
+ 0x001C951D0F88651A, 0x001D1BFE2D5C3972, 0x001D7E5BD56B18B2,
+ 0x001DC934DD172C70, 0x001E0409DFAC9DC8, 0x001E337B71D47836,
+ 0x001E5A8B177CB7A2, 0x001E7B42096F046C, 0x001E970DAF08AE3E,
+ 0x001EAEF5B14EF09E, 0x001EC3BD07B46556, 0x001ED5F6F08799CE,
+ 0x001EE614AE6E5688, 0x001EF46ECA361CD0, 0x001F014B76DDD4A4,
+ 0x001F0CE313A796B6, 0x001F176369F1F77A, 0x001F20F20C452570,
+ 0x001F29AE1951A874, 0x001F31B18FB95532, 0x001F39125157C106,
+ 0x001F3FE2EB6E694C, 0x001F463332D788FA, 0x001F4C10BF1D3A0E,
+ 0x001F51874C5C3322, 0x001F56A109C3ECC0, 0x001F5B66D9099996,
+ 0x001F5FE08210D08C, 0x001F6414DD445772, 0x001F6809F6859678,
+ 0x001F6BC52A2B02E6, 0x001F6F4B3D32E4F4, 0x001F72A07190F13A,
+ 0x001F75C8974D09D6, 0x001F78C71B045CC0, 0x001F7B9F12413FF4,
+ 0x001F7E5346079F8A, 0x001F80E63BE21138, 0x001F835A3DAD9162,
+ 0x001F85B16056B912, 0x001F87ED89B24262, 0x001F8A10759374FA,
+ 0x001F8C1BBA3D39AC, 0x001F8E10CC45D04A, 0x001F8FF102013E16,
+ 0x001F91BD968358E0, 0x001F9377AC47AFD8, 0x001F95204F8B64DA,
+ 0x001F96B878633892, 0x001F98410C968892, 0x001F99BAE146BA80,
+ 0x001F9B26BC697F00, 0x001F9C85561B717A, 0x001F9DD759CFD802,
+ 0x001F9F1D6761A1CE, 0x001FA058140936C0, 0x001FA187EB3A3338,
+ 0x001FA2AD6F6BC4FC, 0x001FA3C91ACE0682, 0x001FA4DB5FEE6AA2,
+ 0x001FA5E4AA4D097C, 0x001FA6E55EE46782, 0x001FA7DDDCA51EC4,
+ 0x001FA8CE7CE6A874, 0x001FA9B793CE5FEE, 0x001FAA9970ADB858,
+ 0x001FAB745E588232, 0x001FAC48A3740584, 0x001FAD1682BF9FE8,
+ 0x001FADDE3B5782C0, 0x001FAEA008F21D6C, 0x001FAF5C2418B07E,
+ 0x001FB012C25B7A12, 0x001FB0C41681DFF4, 0x001FB17050B6F1FA,
+ 0x001FB2179EB2963A, 0x001FB2BA2BDFA84A, 0x001FB358217F4E18,
+ 0x001FB3F1A6C9BE0C, 0x001FB486E10CACD6, 0x001FB517F3C793FC,
+ 0x001FB5A500C5FDAA, 0x001FB62E2837FE58, 0x001FB6B388C9010A,
+ 0x001FB7353FB50798, 0x001FB7B368DC7DA8, 0x001FB82E1ED6BA08,
+ 0x001FB8A57B0347F6, 0x001FB919959A0F74, 0x001FB98A85BA7204,
+ 0x001FB9F861796F26, 0x001FBA633DEEE286, 0x001FBACB2F41EC16,
+ 0x001FBB3048B49144, 0x001FBB929CAEA4E2, 0x001FBBF23CC8029E,
+ 0x001FBC4F39D22994, 0x001FBCA9A3E140D4, 0x001FBD018A548F9E,
+ 0x001FBD56FBDE729C, 0x001FBDAA068BD66A, 0x001FBDFAB7CB3F40,
+ 0x001FBE491C7364DE, 0x001FBE9540C9695E, 0x001FBEDF3086B128,
+ 0x001FBF26F6DE6174, 0x001FBF6C9E828AE2, 0x001FBFB031A904C4,
+ 0x001FBFF1BA0FFDB0, 0x001FC03141024588, 0x001FC06ECF5B54B2,
+ 0x001FC0AA6D8B1426, 0x001FC0E42399698A, 0x001FC11BF9298A64,
+ 0x001FC151F57D1942, 0x001FC1861F770F4A, 0x001FC1B87D9E74B4,
+ 0x001FC1E91620EA42, 0x001FC217EED505DE, 0x001FC2450D3C83FE,
+ 0x001FC27076864FC2, 0x001FC29A2F90630E, 0x001FC2C23CE98046,
+ 0x001FC2E8A2D2C6B4, 0x001FC30D654122EC, 0x001FC33087DE9C0E,
+ 0x001FC3520E0B7EC6, 0x001FC371FADF66F8, 0x001FC390512A2886,
+ 0x001FC3AD137497FA, 0x001FC3C844013348, 0x001FC3E1E4CCAB40,
+ 0x001FC3F9F78E4DA8, 0x001FC4107DB85060, 0x001FC4257877FD68,
+ 0x001FC438E8B5BFC6, 0x001FC44ACF15112A, 0x001FC45B2BF447E8,
+ 0x001FC469FF6C4504, 0x001FC477495001B2, 0x001FC483092BFBB8,
+ 0x001FC48D3E457FF6, 0x001FC495E799D21A, 0x001FC49D03DD30B0,
+ 0x001FC4A29179B432, 0x001FC4A68E8E07FC, 0x001FC4A8F8EBFB8C,
+ 0x001FC4A9CE16EA9E, 0x001FC4A90B41FA34, 0x001FC4A6AD4E28A0,
+ 0x001FC4A2B0C82E74, 0x001FC49D11E62DE2, 0x001FC495CC852DF4,
+ 0x001FC48CDC265EC0, 0x001FC4823BEC237A, 0x001FC475E696DEE6,
+ 0x001FC467D6817E82, 0x001FC458059DC036, 0x001FC4466D702E20,
+ 0x001FC433070BCB98, 0x001FC41DCB0D6E0E, 0x001FC406B196BBF6,
+ 0x001FC3EDB248CB62, 0x001FC3D2C43E593C, 0x001FC3B5DE0591B4,
+ 0x001FC396F599614C, 0x001FC376005A4592, 0x001FC352F3069370,
+ 0x001FC32DC1B22818, 0x001FC3065FBD7888, 0x001FC2DCBFCBF262,
+ 0x001FC2B0D3B99F9E, 0x001FC2828C8FFCF0, 0x001FC251DA79F164,
+ 0x001FC21EACB6D39E, 0x001FC1E8F18C6756, 0x001FC1B09637BB3C,
+ 0x001FC17586DCCD10, 0x001FC137AE74D6B6, 0x001FC0F6F6BB2414,
+ 0x001FC0B348184DA4, 0x001FC06C898BAFF0, 0x001FC022A092F364,
+ 0x001FBFD5710F72B8, 0x001FBF84DD29488E, 0x001FBF30C52FC60A,
+ 0x001FBED907770CC6, 0x001FBE7D80327DDA, 0x001FBE1E094BA614,
+ 0x001FBDBA7A354408, 0x001FBD52A7B9F826, 0x001FBCE663C6201A,
+ 0x001FBC757D2C4DE4, 0x001FBBFFBF63B7AA, 0x001FBB84F23FE6A2,
+ 0x001FBB04D9A0D18C, 0x001FBA7F351A70AC, 0x001FB9F3BF92B618,
+ 0x001FB9622ED4ABFC, 0x001FB8CA33174A16, 0x001FB82B76765B54,
+ 0x001FB7859C5B895C, 0x001FB6D840D55594, 0x001FB622F7D96942,
+ 0x001FB5654C6F37E0, 0x001FB49EBFBF69D2, 0x001FB3CEC803E746,
+ 0x001FB2F4CF539C3E, 0x001FB21032442852, 0x001FB1203E5A9604,
+ 0x001FB0243042E1C2, 0x001FAF1B31C479A6, 0x001FAE045767E104,
+ 0x001FACDE9DBF2D72, 0x001FABA8E640060A, 0x001FAA61F399FF28,
+ 0x001FA908656F66A2, 0x001FA79AB3508D3C, 0x001FA61726D1F214,
+ 0x001FA47BD48BEA00, 0x001FA2C693C5C094, 0x001FA0F4F47DF314,
+ 0x001F9F04336BBE0A, 0x001F9CF12B79F9BC, 0x001F9AB84415ABC4,
+ 0x001F98555B782FB8, 0x001F95C3ABD03F78, 0x001F92FDA9CEF1F2,
+ 0x001F8FFCDA9AE41C, 0x001F8CB99E7385F8, 0x001F892AEC479606,
+ 0x001F8545F904DB8E, 0x001F80FDC336039A, 0x001F7C427839E926,
+ 0x001F7700A3582ACC, 0x001F71200F1A241C, 0x001F6A8234B7352A,
+ 0x001F630000A8E266, 0x001F5A66904FE3C4, 0x001F50724ECE1172,
+ 0x001F44C7665C6FDA, 0x001F36E5A38A59A2, 0x001F26143450340A,
+ 0x001F113E047B0414, 0x001EF6AEFA57CBE6, 0x001ED38CA188151E,
+ 0x001EA2A61E122DB0, 0x001E5961C78B267C, 0x001DDDF62BAC0BB0,
+ 0x001CDB4DD9E4E8C0], dtype=np.uint64)
+
+we_double = np.array([
+ 9.655740063209182975e-16, 7.089014243955414331e-18,
+ 1.163941249669122378e-17, 1.524391512353216015e-17,
+ 1.833284885723743916e-17, 2.108965109464486630e-17,
+ 2.361128077843138196e-17, 2.595595772310893952e-17,
+ 2.816173554197752338e-17, 3.025504130321382330e-17,
+ 3.225508254836375280e-17, 3.417632340185027033e-17,
+ 3.602996978734452488e-17, 3.782490776869649048e-17,
+ 3.956832198097553231e-17, 4.126611778175946428e-17,
+ 4.292321808442525631e-17, 4.454377743282371417e-17,
+ 4.613133981483185932e-17, 4.768895725264635940e-17,
+ 4.921928043727962847e-17, 5.072462904503147014e-17,
+ 5.220704702792671737e-17, 5.366834661718192181e-17,
+ 5.511014372835094717e-17, 5.653388673239667134e-17,
+ 5.794088004852766616e-17, 5.933230365208943081e-17,
+ 6.070922932847179572e-17, 6.207263431163193485e-17,
+ 6.342341280303076511e-17, 6.476238575956142121e-17,
+ 6.609030925769405241e-17, 6.740788167872722244e-17,
+ 6.871574991183812442e-17, 7.001451473403929616e-17,
+ 7.130473549660643409e-17, 7.258693422414648352e-17,
+ 7.386159921381791997e-17, 7.512918820723728089e-17,
+ 7.639013119550825792e-17, 7.764483290797848102e-17,
+ 7.889367502729790548e-17, 8.013701816675454434e-17,
+ 8.137520364041762206e-17, 8.260855505210038174e-17,
+ 8.383737972539139383e-17, 8.506196999385323132e-17,
+ 8.628260436784112996e-17, 8.749954859216182511e-17,
+ 8.871305660690252281e-17, 8.992337142215357066e-17,
+ 9.113072591597909173e-17, 9.233534356381788123e-17,
+ 9.353743910649128938e-17, 9.473721916312949566e-17,
+ 9.593488279457997317e-17, 9.713062202221521206e-17,
+ 9.832462230649511362e-17, 9.951706298915071878e-17,
+ 1.007081177024294931e-16, 1.018979547484694078e-16,
+ 1.030867374515421954e-16, 1.042746244856188556e-16,
+ 1.054617701794576406e-16, 1.066483248011914702e-16,
+ 1.078344348241948498e-16, 1.090202431758350473e-16,
+ 1.102058894705578110e-16, 1.113915102286197502e-16,
+ 1.125772390816567488e-16, 1.137632069661684705e-16,
+ 1.149495423059009298e-16, 1.161363711840218308e-16,
+ 1.173238175059045788e-16, 1.185120031532669434e-16,
+ 1.197010481303465158e-16, 1.208910707027385520e-16,
+ 1.220821875294706151e-16, 1.232745137888415193e-16,
+ 1.244681632985112523e-16, 1.256632486302898513e-16,
+ 1.268598812200397542e-16, 1.280581714730749379e-16,
+ 1.292582288654119552e-16, 1.304601620412028847e-16,
+ 1.316640789066572582e-16, 1.328700867207380889e-16,
+ 1.340782921828999433e-16, 1.352888015181175458e-16,
+ 1.365017205594397770e-16, 1.377171548282880964e-16,
+ 1.389352096127063919e-16, 1.401559900437571538e-16,
+ 1.413796011702485188e-16, 1.426061480319665444e-16,
+ 1.438357357315790180e-16, 1.450684695053687684e-16,
+ 1.463044547929475721e-16, 1.475437973060951633e-16,
+ 1.487866030968626066e-16, 1.500329786250736949e-16,
+ 1.512830308253539427e-16, 1.525368671738125550e-16,
+ 1.537945957544996933e-16, 1.550563253257577148e-16,
+ 1.563221653865837505e-16, 1.575922262431176140e-16,
+ 1.588666190753684151e-16, 1.601454560042916733e-16,
+ 1.614288501593278662e-16, 1.627169157465130500e-16,
+ 1.640097681172717950e-16, 1.653075238380036909e-16,
+ 1.666103007605742067e-16, 1.679182180938228863e-16,
+ 1.692313964762022267e-16, 1.705499580496629830e-16,
+ 1.718740265349031656e-16, 1.732037273081008369e-16,
+ 1.745391874792533975e-16, 1.758805359722491379e-16,
+ 1.772279036068006489e-16, 1.785814231823732619e-16,
+ 1.799412295642463721e-16, 1.813074597718501559e-16,
+ 1.826802530695252266e-16, 1.840597510598587828e-16,
+ 1.854460977797569461e-16, 1.868394397994192684e-16,
+ 1.882399263243892051e-16, 1.896477093008616722e-16,
+ 1.910629435244376536e-16, 1.924857867525243818e-16,
+ 1.939163998205899420e-16, 1.953549467624909132e-16,
+ 1.968015949351037382e-16, 1.982565151475019047e-16,
+ 1.997198817949342081e-16, 2.011918729978734671e-16,
+ 2.026726707464198289e-16, 2.041624610503588774e-16,
+ 2.056614340951917875e-16, 2.071697844044737034e-16,
+ 2.086877110088159721e-16, 2.102154176219292789e-16,
+ 2.117531128241075913e-16, 2.133010102535779087e-16,
+ 2.148593288061663316e-16, 2.164282928437604723e-16,
+ 2.180081324120784027e-16, 2.195990834682870728e-16,
+ 2.212013881190495942e-16, 2.228152948696180545e-16,
+ 2.244410588846308588e-16, 2.260789422613173739e-16,
+ 2.277292143158621037e-16, 2.293921518837311354e-16,
+ 2.310680396348213318e-16, 2.327571704043534613e-16,
+ 2.344598455404957859e-16, 2.361763752697773994e-16,
+ 2.379070790814276700e-16, 2.396522861318623520e-16,
+ 2.414123356706293277e-16, 2.431875774892255956e-16,
+ 2.449783723943070217e-16, 2.467850927069288738e-16,
+ 2.486081227895851719e-16, 2.504478596029557040e-16,
+ 2.523047132944217013e-16, 2.541791078205812227e-16,
+ 2.560714816061770759e-16, 2.579822882420530896e-16,
+ 2.599119972249746917e-16, 2.618610947423924219e-16,
+ 2.638300845054942823e-16, 2.658194886341845120e-16,
+ 2.678298485979525166e-16, 2.698617262169488933e-16,
+ 2.719157047279818500e-16, 2.739923899205814823e-16,
+ 2.760924113487617126e-16, 2.782164236246436081e-16,
+ 2.803651078006983464e-16, 2.825391728480253184e-16,
+ 2.847393572388174091e-16, 2.869664306419817679e-16,
+ 2.892211957417995598e-16, 2.915044901905293183e-16,
+ 2.938171887070028633e-16, 2.961602053345465687e-16,
+ 2.985344958730045276e-16, 3.009410605012618141e-16,
+ 3.033809466085003416e-16, 3.058552518544860874e-16,
+ 3.083651274815310004e-16, 3.109117819034266344e-16,
+ 3.134964845996663118e-16, 3.161205703467105734e-16,
+ 3.187854438219713117e-16, 3.214925846206797361e-16,
+ 3.242435527309451638e-16, 3.270399945182240440e-16,
+ 3.298836492772283149e-16, 3.327763564171671408e-16,
+ 3.357200633553244075e-16, 3.387168342045505162e-16,
+ 3.417688593525636996e-16, 3.448784660453423890e-16,
+ 3.480481301037442286e-16, 3.512804889222979418e-16,
+ 3.545783559224791863e-16, 3.579447366604276541e-16,
+ 3.613828468219060593e-16, 3.648961323764542545e-16,
+ 3.684882922095621322e-16, 3.721633036080207290e-16,
+ 3.759254510416256532e-16, 3.797793587668874387e-16,
+ 3.837300278789213687e-16, 3.877828785607895292e-16,
+ 3.919437984311428867e-16, 3.962191980786774996e-16,
+ 4.006160751056541688e-16, 4.051420882956573177e-16,
+ 4.098056438903062509e-16, 4.146159964290904582e-16,
+ 4.195833672073398926e-16, 4.247190841824385048e-16,
+ 4.300357481667470702e-16, 4.355474314693952008e-16,
+ 4.412699169036069903e-16, 4.472209874259932285e-16,
+ 4.534207798565834480e-16, 4.598922204905932469e-16,
+ 4.666615664711475780e-16, 4.737590853262492027e-16,
+ 4.812199172829237933e-16, 4.890851827392209900e-16,
+ 4.974034236191939753e-16, 5.062325072144159699e-16,
+ 5.156421828878082953e-16, 5.257175802022274839e-16,
+ 5.365640977112021618e-16, 5.483144034258703912e-16,
+ 5.611387454675159622e-16, 5.752606481503331688e-16,
+ 5.909817641652102998e-16, 6.087231416180907671e-16,
+ 6.290979034877557049e-16, 6.530492053564040799e-16,
+ 6.821393079028928626e-16, 7.192444966089361564e-16,
+ 7.706095350032096755e-16, 8.545517038584027421e-16],
+ dtype=np.float64)
+
+fe_double = np.array([
+ 1.000000000000000000e+00, 9.381436808621747003e-01,
+ 9.004699299257464817e-01, 8.717043323812035949e-01,
+ 8.477855006239896074e-01, 8.269932966430503241e-01,
+ 8.084216515230083777e-01, 7.915276369724956185e-01,
+ 7.759568520401155522e-01, 7.614633888498962833e-01,
+ 7.478686219851951034e-01, 7.350380924314234843e-01,
+ 7.228676595935720206e-01, 7.112747608050760117e-01,
+ 7.001926550827881623e-01, 6.895664961170779872e-01,
+ 6.793505722647653622e-01, 6.695063167319247333e-01,
+ 6.600008410789997004e-01, 6.508058334145710999e-01,
+ 6.418967164272660897e-01, 6.332519942143660652e-01,
+ 6.248527387036659775e-01, 6.166821809152076561e-01,
+ 6.087253820796220127e-01, 6.009689663652322267e-01,
+ 5.934009016917334289e-01, 5.860103184772680329e-01,
+ 5.787873586028450257e-01, 5.717230486648258170e-01,
+ 5.648091929124001709e-01, 5.580382822625874484e-01,
+ 5.514034165406412891e-01, 5.448982376724396115e-01,
+ 5.385168720028619127e-01, 5.322538802630433219e-01,
+ 5.261042139836197284e-01, 5.200631773682335979e-01,
+ 5.141263938147485613e-01, 5.082897764106428795e-01,
+ 5.025495018413477233e-01, 4.969019872415495476e-01,
+ 4.913438695940325340e-01, 4.858719873418849144e-01,
+ 4.804833639304542103e-01, 4.751751930373773747e-01,
+ 4.699448252839599771e-01, 4.647897562504261781e-01,
+ 4.597076156421376902e-01, 4.546961574746155033e-01,
+ 4.497532511627549967e-01, 4.448768734145485126e-01,
+ 4.400651008423538957e-01, 4.353161032156365740e-01,
+ 4.306281372884588343e-01, 4.259995411430343437e-01,
+ 4.214287289976165751e-01, 4.169141864330028757e-01,
+ 4.124544659971611793e-01, 4.080481831520323954e-01,
+ 4.036940125305302773e-01, 3.993906844752310725e-01,
+ 3.951369818332901573e-01, 3.909317369847971069e-01,
+ 3.867738290841376547e-01, 3.826621814960098344e-01,
+ 3.785957594095807899e-01, 3.745735676159021588e-01,
+ 3.705946484351460013e-01, 3.666580797815141568e-01,
+ 3.627629733548177748e-01, 3.589084729487497794e-01,
+ 3.550937528667874599e-01, 3.513180164374833381e-01,
+ 3.475804946216369817e-01, 3.438804447045024082e-01,
+ 3.402171490667800224e-01, 3.365899140286776059e-01,
+ 3.329980687618089852e-01, 3.294409642641363267e-01,
+ 3.259179723935561879e-01, 3.224284849560891675e-01,
+ 3.189719128449572394e-01, 3.155476852271289490e-01,
+ 3.121552487741795501e-01, 3.087940669345601852e-01,
+ 3.054636192445902565e-01, 3.021634006756935276e-01,
+ 2.988929210155817917e-01, 2.956517042812611962e-01,
+ 2.924392881618925744e-01, 2.892552234896777485e-01,
+ 2.860990737370768255e-01, 2.829704145387807457e-01,
+ 2.798688332369729248e-01, 2.767939284485173568e-01,
+ 2.737453096528029706e-01, 2.707225967990600224e-01,
+ 2.677254199320447947e-01, 2.647534188350622042e-01,
+ 2.618062426893629779e-01, 2.588835497490162285e-01,
+ 2.559850070304153791e-01, 2.531102900156294577e-01,
+ 2.502590823688622956e-01, 2.474310756653276266e-01,
+ 2.446259691318921070e-01, 2.418434693988772144e-01,
+ 2.390832902624491774e-01, 2.363451524570596429e-01,
+ 2.336287834374333461e-01, 2.309339171696274118e-01,
+ 2.282602939307167011e-01, 2.256076601166840667e-01,
+ 2.229757680581201940e-01, 2.203643758433594946e-01,
+ 2.177732471487005272e-01, 2.152021510753786837e-01,
+ 2.126508619929782795e-01, 2.101191593889882581e-01,
+ 2.076068277242220372e-01, 2.051136562938377095e-01,
+ 2.026394390937090173e-01, 2.001839746919112650e-01,
+ 1.977470661050988732e-01, 1.953285206795632167e-01,
+ 1.929281499767713515e-01, 1.905457696631953912e-01,
+ 1.881811994042543179e-01, 1.858342627621971110e-01,
+ 1.835047870977674633e-01, 1.811926034754962889e-01,
+ 1.788975465724783054e-01, 1.766194545904948843e-01,
+ 1.743581691713534942e-01, 1.721135353153200598e-01,
+ 1.698854013025276610e-01, 1.676736186172501919e-01,
+ 1.654780418749360049e-01, 1.632985287519018169e-01,
+ 1.611349399175920349e-01, 1.589871389693142123e-01,
+ 1.568549923693652315e-01, 1.547383693844680830e-01,
+ 1.526371420274428570e-01, 1.505511850010398944e-01,
+ 1.484803756438667910e-01, 1.464245938783449441e-01,
+ 1.443837221606347754e-01, 1.423576454324722018e-01,
+ 1.403462510748624548e-01, 1.383494288635802039e-01,
+ 1.363670709264288572e-01, 1.343990717022136294e-01,
+ 1.324453279013875218e-01, 1.305057384683307731e-01,
+ 1.285802045452281717e-01, 1.266686294375106714e-01,
+ 1.247709185808309612e-01, 1.228869795095451356e-01,
+ 1.210167218266748335e-01, 1.191600571753276827e-01,
+ 1.173168992115555670e-01, 1.154871635786335338e-01,
+ 1.136707678827443141e-01, 1.118676316700562973e-01,
+ 1.100776764051853845e-01, 1.083008254510337970e-01,
+ 1.065370040500016602e-01, 1.047861393065701724e-01,
+ 1.030481601712577161e-01, 1.013229974259536315e-01,
+ 9.961058367063713170e-02, 9.791085331149219917e-02,
+ 9.622374255043279756e-02, 9.454918937605585882e-02,
+ 9.288713355604354127e-02, 9.123751663104015530e-02,
+ 8.960028191003285847e-02, 8.797537446727021759e-02,
+ 8.636274114075691288e-02, 8.476233053236811865e-02,
+ 8.317409300963238272e-02, 8.159798070923741931e-02,
+ 8.003394754231990538e-02, 7.848194920160642130e-02,
+ 7.694194317048050347e-02, 7.541388873405840965e-02,
+ 7.389774699236474620e-02, 7.239348087570873780e-02,
+ 7.090105516237182881e-02, 6.942043649872875477e-02,
+ 6.795159342193660135e-02, 6.649449638533977414e-02,
+ 6.504911778675374900e-02, 6.361543199980733421e-02,
+ 6.219341540854099459e-02, 6.078304644547963265e-02,
+ 5.938430563342026597e-02, 5.799717563120065922e-02,
+ 5.662164128374287675e-02, 5.525768967669703741e-02,
+ 5.390531019604608703e-02, 5.256449459307169225e-02,
+ 5.123523705512628146e-02, 4.991753428270637172e-02,
+ 4.861138557337949667e-02, 4.731679291318154762e-02,
+ 4.603376107617516977e-02, 4.476229773294328196e-02,
+ 4.350241356888818328e-02, 4.225412241331623353e-02,
+ 4.101744138041481941e-02, 3.979239102337412542e-02,
+ 3.857899550307485742e-02, 3.737728277295936097e-02,
+ 3.618728478193142251e-02, 3.500903769739741045e-02,
+ 3.384258215087432992e-02, 3.268796350895953468e-02,
+ 3.154523217289360859e-02, 3.041444391046660423e-02,
+ 2.929566022463739317e-02, 2.818894876397863569e-02,
+ 2.709438378095579969e-02, 2.601204664513421735e-02,
+ 2.494202641973178314e-02, 2.388442051155817078e-02,
+ 2.283933540638524023e-02, 2.180688750428358066e-02,
+ 2.078720407257811723e-02, 1.978042433800974303e-02,
+ 1.878670074469603046e-02, 1.780620041091136169e-02,
+ 1.683910682603994777e-02, 1.588562183997316302e-02,
+ 1.494596801169114850e-02, 1.402039140318193759e-02,
+ 1.310916493125499106e-02, 1.221259242625538123e-02,
+ 1.133101359783459695e-02, 1.046481018102997894e-02,
+ 9.614413642502209895e-03, 8.780314985808975251e-03,
+ 7.963077438017040002e-03, 7.163353183634983863e-03,
+ 6.381905937319179087e-03, 5.619642207205483020e-03,
+ 4.877655983542392333e-03, 4.157295120833795314e-03,
+ 3.460264777836904049e-03, 2.788798793574076128e-03,
+ 2.145967743718906265e-03, 1.536299780301572356e-03,
+ 9.672692823271745359e-04, 4.541343538414967652e-04],
+ dtype=np.float64)
+
+ke_float = np.array([
+ 0x00714851, 0x00000000, 0x004DF56F, 0x0061BBD6, 0x006A6EDD,
+ 0x006F44A0, 0x00725474, 0x00746FF9, 0x0075F96F, 0x007724D3,
+ 0x00781027, 0x0078CDEE, 0x00796A2C, 0x0079ED08, 0x007A5C37,
+ 0x007ABBD7, 0x007B0EF4, 0x007B57DC, 0x007B9853, 0x007BD1BB,
+ 0x007C052E, 0x007C338C, 0x007C5D8E, 0x007C83C8, 0x007CA6B8,
+ 0x007CC6C6, 0x007CE449, 0x007CFF8C, 0x007D18CD, 0x007D3043,
+ 0x007D461D, 0x007D5A84, 0x007D6D9B, 0x007D7F82, 0x007D9053,
+ 0x007DA028, 0x007DAF15, 0x007DBD2D, 0x007DCA82, 0x007DD722,
+ 0x007DE31C, 0x007DEE7C, 0x007DF94D, 0x007E0399, 0x007E0D69,
+ 0x007E16C6, 0x007E1FB6, 0x007E2842, 0x007E306F, 0x007E3843,
+ 0x007E3FC4, 0x007E46F6, 0x007E4DDF, 0x007E5481, 0x007E5AE2,
+ 0x007E6104, 0x007E66EC, 0x007E6C9B, 0x007E7215, 0x007E775D,
+ 0x007E7C76, 0x007E8160, 0x007E8620, 0x007E8AB6, 0x007E8F24,
+ 0x007E936D, 0x007E9793, 0x007E9B95, 0x007E9F77, 0x007EA33A,
+ 0x007EA6DE, 0x007EAA66, 0x007EADD1, 0x007EB123, 0x007EB45A,
+ 0x007EB779, 0x007EBA80, 0x007EBD71, 0x007EC04B, 0x007EC310,
+ 0x007EC5C1, 0x007EC85E, 0x007ECAE9, 0x007ECD61, 0x007ECFC7,
+ 0x007ED21C, 0x007ED460, 0x007ED694, 0x007ED8B9, 0x007EDACE,
+ 0x007EDCD5, 0x007EDECE, 0x007EE0B8, 0x007EE296, 0x007EE466,
+ 0x007EE62A, 0x007EE7E2, 0x007EE98D, 0x007EEB2D, 0x007EECC1,
+ 0x007EEE4A, 0x007EEFC9, 0x007EF13D, 0x007EF2A7, 0x007EF406,
+ 0x007EF55C, 0x007EF6A8, 0x007EF7EB, 0x007EF924, 0x007EFA55,
+ 0x007EFB7D, 0x007EFC9C, 0x007EFDB2, 0x007EFEC1, 0x007EFFC7,
+ 0x007F00C5, 0x007F01BB, 0x007F02AA, 0x007F0391, 0x007F0470,
+ 0x007F0548, 0x007F0618, 0x007F06E2, 0x007F07A4, 0x007F0860,
+ 0x007F0914, 0x007F09C2, 0x007F0A69, 0x007F0B09, 0x007F0BA3,
+ 0x007F0C36, 0x007F0CC2, 0x007F0D48, 0x007F0DC8, 0x007F0E41,
+ 0x007F0EB4, 0x007F0F21, 0x007F0F88, 0x007F0FE8, 0x007F1042,
+ 0x007F1096, 0x007F10E4, 0x007F112B, 0x007F116D, 0x007F11A8,
+ 0x007F11DD, 0x007F120C, 0x007F1235, 0x007F1258, 0x007F1274,
+ 0x007F128A, 0x007F129A, 0x007F12A4, 0x007F12A7, 0x007F12A4,
+ 0x007F129B, 0x007F128B, 0x007F1274, 0x007F1257, 0x007F1233,
+ 0x007F1209, 0x007F11D8, 0x007F119F, 0x007F1160, 0x007F111A,
+ 0x007F10CC, 0x007F1077, 0x007F101B, 0x007F0FB7, 0x007F0F4B,
+ 0x007F0ED7, 0x007F0E5C, 0x007F0DD8, 0x007F0D4C, 0x007F0CB7,
+ 0x007F0C19, 0x007F0B73, 0x007F0AC3, 0x007F0A0A, 0x007F0947,
+ 0x007F087B, 0x007F07A4, 0x007F06C2, 0x007F05D6, 0x007F04DF,
+ 0x007F03DC, 0x007F02CD, 0x007F01B2, 0x007F008B, 0x007EFF56,
+ 0x007EFE13, 0x007EFCC3, 0x007EFB64, 0x007EF9F6, 0x007EF878,
+ 0x007EF6EA, 0x007EF54B, 0x007EF39A, 0x007EF1D6, 0x007EEFFF,
+ 0x007EEE14, 0x007EEC13, 0x007EE9FD, 0x007EE7CF, 0x007EE589,
+ 0x007EE329, 0x007EE0AE, 0x007EDE16, 0x007EDB61, 0x007ED88C,
+ 0x007ED595, 0x007ED27B, 0x007ECF3B, 0x007ECBD3, 0x007EC841,
+ 0x007EC481, 0x007EC091, 0x007EBC6D, 0x007EB811, 0x007EB37A,
+ 0x007EAEA4, 0x007EA988, 0x007EA422, 0x007E9E6B, 0x007E985D,
+ 0x007E91EF, 0x007E8B1A, 0x007E83D4, 0x007E7C11, 0x007E73C5,
+ 0x007E6AE1, 0x007E6155, 0x007E570F, 0x007E4BF7, 0x007E3FF3,
+ 0x007E32E6, 0x007E24AC, 0x007E1518, 0x007E03F7, 0x007DF10A,
+ 0x007DDC03, 0x007DC480, 0x007DAA09, 0x007D8C00, 0x007D699A,
+ 0x007D41C9, 0x007D131E, 0x007CDB97, 0x007C9851, 0x007C44F8,
+ 0x007BDABC, 0x007B4E33, 0x007A8A98, 0x00796587, 0x007777D9,
+ 0x00736D37, ], dtype=np.uint32)
+
+we_float = np.array([
+ 1.03677719e-06, 7.61177108e-09, 1.24977240e-08, 1.63680292e-08,
+ 1.96847466e-08, 2.26448404e-08, 2.53524197e-08, 2.78699974e-08,
+ 3.02384333e-08, 3.24861032e-08, 3.46336312e-08, 3.66965478e-08,
+ 3.86868855e-08, 4.06141855e-08, 4.24861622e-08, 4.43091566e-08,
+ 4.60884545e-08, 4.78285168e-08, 4.95331490e-08, 5.12056279e-08,
+ 5.28488000e-08, 5.44651557e-08, 5.60568899e-08, 5.76259484e-08,
+ 5.91740662e-08, 6.07027987e-08, 6.22135462e-08, 6.37075759e-08,
+ 6.51860386e-08, 6.66499836e-08, 6.81003709e-08, 6.95380822e-08,
+ 7.09639292e-08, 7.23786618e-08, 7.37829746e-08, 7.51775128e-08,
+ 7.65628768e-08, 7.79396272e-08, 7.93082883e-08, 8.06693516e-08,
+ 8.20232788e-08, 8.33705045e-08, 8.47114385e-08, 8.60464681e-08,
+ 8.73759596e-08, 8.87002606e-08, 9.00197010e-08, 9.13345948e-08,
+ 9.26452410e-08, 9.39519249e-08, 9.52549192e-08, 9.65544849e-08,
+ 9.78508719e-08, 9.91443202e-08, 1.00435060e-07, 1.01723315e-07,
+ 1.03009296e-07, 1.04293211e-07, 1.05575259e-07, 1.06855633e-07,
+ 1.08134518e-07, 1.09412096e-07, 1.10688542e-07, 1.11964025e-07,
+ 1.13238713e-07, 1.14512767e-07, 1.15786343e-07, 1.17059595e-07,
+ 1.18332673e-07, 1.19605723e-07, 1.20878890e-07, 1.22152313e-07,
+ 1.23426131e-07, 1.24700479e-07, 1.25975490e-07, 1.27251294e-07,
+ 1.28528022e-07, 1.29805799e-07, 1.31084751e-07, 1.32365001e-07,
+ 1.33646673e-07, 1.34929886e-07, 1.36214760e-07, 1.37501415e-07,
+ 1.38789966e-07, 1.40080532e-07, 1.41373228e-07, 1.42668169e-07,
+ 1.43965470e-07, 1.45265245e-07, 1.46567606e-07, 1.47872669e-07,
+ 1.49180545e-07, 1.50491348e-07, 1.51805191e-07, 1.53122186e-07,
+ 1.54442445e-07, 1.55766083e-07, 1.57093212e-07, 1.58423946e-07,
+ 1.59758399e-07, 1.61096684e-07, 1.62438917e-07, 1.63785214e-07,
+ 1.65135690e-07, 1.66490462e-07, 1.67849647e-07, 1.69213364e-07,
+ 1.70581733e-07, 1.71954874e-07, 1.73332908e-07, 1.74715958e-07,
+ 1.76104148e-07, 1.77497602e-07, 1.78896448e-07, 1.80300814e-07,
+ 1.81710828e-07, 1.83126623e-07, 1.84548331e-07, 1.85976086e-07,
+ 1.87410026e-07, 1.88850288e-07, 1.90297012e-07, 1.91750343e-07,
+ 1.93210424e-07, 1.94677403e-07, 1.96151428e-07, 1.97632653e-07,
+ 1.99121231e-07, 2.00617321e-07, 2.02121082e-07, 2.03632677e-07,
+ 2.05152273e-07, 2.06680040e-07, 2.08216149e-07, 2.09760777e-07,
+ 2.11314104e-07, 2.12876312e-07, 2.14447590e-07, 2.16028129e-07,
+ 2.17618123e-07, 2.19217773e-07, 2.20827283e-07, 2.22446862e-07,
+ 2.24076723e-07, 2.25717086e-07, 2.27368174e-07, 2.29030216e-07,
+ 2.30703448e-07, 2.32388110e-07, 2.34084450e-07, 2.35792720e-07,
+ 2.37513182e-07, 2.39246101e-07, 2.40991752e-07, 2.42750416e-07,
+ 2.44522382e-07, 2.46307948e-07, 2.48107418e-07, 2.49921109e-07,
+ 2.51749342e-07, 2.53592452e-07, 2.55450781e-07, 2.57324683e-07,
+ 2.59214522e-07, 2.61120673e-07, 2.63043524e-07, 2.64983476e-07,
+ 2.66940939e-07, 2.68916342e-07, 2.70910123e-07, 2.72922739e-07,
+ 2.74954660e-07, 2.77006373e-07, 2.79078382e-07, 2.81171210e-07,
+ 2.83285396e-07, 2.85421503e-07, 2.87580110e-07, 2.89761822e-07,
+ 2.91967265e-07, 2.94197089e-07, 2.96451969e-07, 2.98732610e-07,
+ 3.01039742e-07, 3.03374127e-07, 3.05736557e-07, 3.08127859e-07,
+ 3.10548894e-07, 3.13000563e-07, 3.15483804e-07, 3.17999599e-07,
+ 3.20548974e-07, 3.23133003e-07, 3.25752811e-07, 3.28409576e-07,
+ 3.31104534e-07, 3.33838984e-07, 3.36614287e-07, 3.39431878e-07,
+ 3.42293264e-07, 3.45200034e-07, 3.48153864e-07, 3.51156520e-07,
+ 3.54209871e-07, 3.57315892e-07, 3.60476673e-07, 3.63694431e-07,
+ 3.66971518e-07, 3.70310433e-07, 3.73713834e-07, 3.77184553e-07,
+ 3.80725611e-07, 3.84340234e-07, 3.88031877e-07, 3.91804239e-07,
+ 3.95661291e-07, 3.99607304e-07, 4.03646879e-07, 4.07784981e-07,
+ 4.12026980e-07, 4.16378695e-07, 4.20846449e-07, 4.25437124e-07,
+ 4.30158235e-07, 4.35018005e-07, 4.40025460e-07, 4.45190536e-07,
+ 4.50524210e-07, 4.56038644e-07, 4.61747369e-07, 4.67665494e-07,
+ 4.73809965e-07, 4.80199879e-07, 4.86856855e-07, 4.93805512e-07,
+ 5.01074042e-07, 5.08694944e-07, 5.16705952e-07, 5.25151216e-07,
+ 5.34082859e-07, 5.43563016e-07, 5.53666578e-07, 5.64484953e-07,
+ 5.76131313e-07, 5.88748108e-07, 6.02518140e-07, 6.17681418e-07,
+ 6.34561837e-07, 6.53611496e-07, 6.75488730e-07, 7.01206245e-07,
+ 7.32441505e-07, 7.72282898e-07, 8.27435688e-07, 9.17567905e-07,]
+ , dtype=np.float32)
+
+fe_float = np.array([
+ 1.00000000e+00, 9.38143681e-01, 9.00469930e-01, 8.71704332e-01,
+ 8.47785501e-01, 8.26993297e-01, 8.08421652e-01, 7.91527637e-01,
+ 7.75956852e-01, 7.61463389e-01, 7.47868622e-01, 7.35038092e-01,
+ 7.22867660e-01, 7.11274761e-01, 7.00192655e-01, 6.89566496e-01,
+ 6.79350572e-01, 6.69506317e-01, 6.60000841e-01, 6.50805833e-01,
+ 6.41896716e-01, 6.33251994e-01, 6.24852739e-01, 6.16682181e-01,
+ 6.08725382e-01, 6.00968966e-01, 5.93400902e-01, 5.86010318e-01,
+ 5.78787359e-01, 5.71723049e-01, 5.64809193e-01, 5.58038282e-01,
+ 5.51403417e-01, 5.44898238e-01, 5.38516872e-01, 5.32253880e-01,
+ 5.26104214e-01, 5.20063177e-01, 5.14126394e-01, 5.08289776e-01,
+ 5.02549502e-01, 4.96901987e-01, 4.91343870e-01, 4.85871987e-01,
+ 4.80483364e-01, 4.75175193e-01, 4.69944825e-01, 4.64789756e-01,
+ 4.59707616e-01, 4.54696157e-01, 4.49753251e-01, 4.44876873e-01,
+ 4.40065101e-01, 4.35316103e-01, 4.30628137e-01, 4.25999541e-01,
+ 4.21428729e-01, 4.16914186e-01, 4.12454466e-01, 4.08048183e-01,
+ 4.03694013e-01, 3.99390684e-01, 3.95136982e-01, 3.90931737e-01,
+ 3.86773829e-01, 3.82662181e-01, 3.78595759e-01, 3.74573568e-01,
+ 3.70594648e-01, 3.66658080e-01, 3.62762973e-01, 3.58908473e-01,
+ 3.55093753e-01, 3.51318016e-01, 3.47580495e-01, 3.43880445e-01,
+ 3.40217149e-01, 3.36589914e-01, 3.32998069e-01, 3.29440964e-01,
+ 3.25917972e-01, 3.22428485e-01, 3.18971913e-01, 3.15547685e-01,
+ 3.12155249e-01, 3.08794067e-01, 3.05463619e-01, 3.02163401e-01,
+ 2.98892921e-01, 2.95651704e-01, 2.92439288e-01, 2.89255223e-01,
+ 2.86099074e-01, 2.82970415e-01, 2.79868833e-01, 2.76793928e-01,
+ 2.73745310e-01, 2.70722597e-01, 2.67725420e-01, 2.64753419e-01,
+ 2.61806243e-01, 2.58883550e-01, 2.55985007e-01, 2.53110290e-01,
+ 2.50259082e-01, 2.47431076e-01, 2.44625969e-01, 2.41843469e-01,
+ 2.39083290e-01, 2.36345152e-01, 2.33628783e-01, 2.30933917e-01,
+ 2.28260294e-01, 2.25607660e-01, 2.22975768e-01, 2.20364376e-01,
+ 2.17773247e-01, 2.15202151e-01, 2.12650862e-01, 2.10119159e-01,
+ 2.07606828e-01, 2.05113656e-01, 2.02639439e-01, 2.00183975e-01,
+ 1.97747066e-01, 1.95328521e-01, 1.92928150e-01, 1.90545770e-01,
+ 1.88181199e-01, 1.85834263e-01, 1.83504787e-01, 1.81192603e-01,
+ 1.78897547e-01, 1.76619455e-01, 1.74358169e-01, 1.72113535e-01,
+ 1.69885401e-01, 1.67673619e-01, 1.65478042e-01, 1.63298529e-01,
+ 1.61134940e-01, 1.58987139e-01, 1.56854992e-01, 1.54738369e-01,
+ 1.52637142e-01, 1.50551185e-01, 1.48480376e-01, 1.46424594e-01,
+ 1.44383722e-01, 1.42357645e-01, 1.40346251e-01, 1.38349429e-01,
+ 1.36367071e-01, 1.34399072e-01, 1.32445328e-01, 1.30505738e-01,
+ 1.28580205e-01, 1.26668629e-01, 1.24770919e-01, 1.22886980e-01,
+ 1.21016722e-01, 1.19160057e-01, 1.17316899e-01, 1.15487164e-01,
+ 1.13670768e-01, 1.11867632e-01, 1.10077676e-01, 1.08300825e-01,
+ 1.06537004e-01, 1.04786139e-01, 1.03048160e-01, 1.01322997e-01,
+ 9.96105837e-02, 9.79108533e-02, 9.62237426e-02, 9.45491894e-02,
+ 9.28871336e-02, 9.12375166e-02, 8.96002819e-02, 8.79753745e-02,
+ 8.63627411e-02, 8.47623305e-02, 8.31740930e-02, 8.15979807e-02,
+ 8.00339475e-02, 7.84819492e-02, 7.69419432e-02, 7.54138887e-02,
+ 7.38977470e-02, 7.23934809e-02, 7.09010552e-02, 6.94204365e-02,
+ 6.79515934e-02, 6.64944964e-02, 6.50491178e-02, 6.36154320e-02,
+ 6.21934154e-02, 6.07830464e-02, 5.93843056e-02, 5.79971756e-02,
+ 5.66216413e-02, 5.52576897e-02, 5.39053102e-02, 5.25644946e-02,
+ 5.12352371e-02, 4.99175343e-02, 4.86113856e-02, 4.73167929e-02,
+ 4.60337611e-02, 4.47622977e-02, 4.35024136e-02, 4.22541224e-02,
+ 4.10174414e-02, 3.97923910e-02, 3.85789955e-02, 3.73772828e-02,
+ 3.61872848e-02, 3.50090377e-02, 3.38425822e-02, 3.26879635e-02,
+ 3.15452322e-02, 3.04144439e-02, 2.92956602e-02, 2.81889488e-02,
+ 2.70943838e-02, 2.60120466e-02, 2.49420264e-02, 2.38844205e-02,
+ 2.28393354e-02, 2.18068875e-02, 2.07872041e-02, 1.97804243e-02,
+ 1.87867007e-02, 1.78062004e-02, 1.68391068e-02, 1.58856218e-02,
+ 1.49459680e-02, 1.40203914e-02, 1.31091649e-02, 1.22125924e-02,
+ 1.13310136e-02, 1.04648102e-02, 9.61441364e-03, 8.78031499e-03,
+ 7.96307744e-03, 7.16335318e-03, 6.38190594e-03, 5.61964221e-03,
+ 4.87765598e-03, 4.15729512e-03, 3.46026478e-03, 2.78879879e-03,
+ 2.14596774e-03, 1.53629978e-03, 9.67269282e-04, 4.54134354e-04,]
+ , dtype=np.float32)
+
+
+ziggurat_nor_r = 3.6541528853610087963519472518
+ziggurat_nor_inv_r = 0.27366123732975827203338247596
+ziggurat_exp_r = 7.6971174701310497140446280481
+
+ziggurat_nor_r_f = np.float32(3.6541528853610087963519472518)
+ziggurat_nor_inv_r_f = np.float32(0.27366123732975827203338247596)
+ziggurat_exp_r_f = np.float32(7.6971174701310497140446280481)
+
+M_PI = 3.14159265358979323846
+INT64_MAX = 9223372036854775807
+UINT8_MAX = 255
+UINT16_MAX = 65535
+UINT32_MAX = 4294967295
+UINT64_MAX = 18446744073709551615
+LONG_MAX = (1 << ( 8 * ctypes.sizeof(ctypes.c_long) - 1)) - 1
+
+LS2PI = 0.91893853320467267
+TWELFTH = 0.083333333333333333333333
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/np/random/distributions.py b/tool_server/.venv/lib/python3.12/site-packages/numba/np/random/distributions.py
new file mode 100644
index 0000000000000000000000000000000000000000..6d52c79dd55ce942ea0390d60c6cc792d16c9fd7
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/np/random/distributions.py
@@ -0,0 +1,12 @@
+import sys
+from numba.core.utils import _RedirectSubpackage
+from numba.core import config
+
+if config.USE_LEGACY_TYPE_SYSTEM:
+ sys.modules[__name__] = \
+ _RedirectSubpackage(locals(),
+ "numba.np.random.old_distributions")
+else:
+ sys.modules[__name__] = \
+ _RedirectSubpackage(locals(),
+ "numba.np.random.new_distributions")
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/np/random/generator_core.py b/tool_server/.venv/lib/python3.12/site-packages/numba/np/random/generator_core.py
new file mode 100644
index 0000000000000000000000000000000000000000..42977faadbccbcd01a35613d6daf43ec7d85bed2
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/np/random/generator_core.py
@@ -0,0 +1,132 @@
+"""
+Core Implementations for Generator/BitGenerator Models.
+"""
+
+from llvmlite import ir
+from numba.core import cgutils, types, config
+from numba.core.extending import (intrinsic, make_attribute_wrapper, models,
+ overload, register_jitable,
+ register_model)
+
+
+@register_model(types.NumPyRandomBitGeneratorType)
+class NumPyRngBitGeneratorModel(models.StructModel):
+ def __init__(self, dmm, fe_type):
+ members = [
+ ('parent', types.pyobject),
+ ('state_address', types.uintp),
+ ('state', types.uintp),
+ ('fnptr_next_uint64', types.uintp),
+ ('fnptr_next_uint32', types.uintp),
+ ('fnptr_next_double', types.uintp),
+ ('bit_generator', types.uintp),
+ ]
+ super(NumPyRngBitGeneratorModel, self).__init__(dmm, fe_type, members)
+
+
+_bit_gen_type = types.NumPyRandomBitGeneratorType('bit_generator')
+
+
+@register_model(types.NumPyRandomGeneratorType)
+class NumPyRandomGeneratorTypeModel(models.StructModel):
+ def __init__(self, dmm, fe_type):
+ members = [
+ ('bit_generator', _bit_gen_type),
+ ('meminfo', types.MemInfoPointer(types.voidptr)),
+ ('parent', types.pyobject)
+ ]
+ super(
+ NumPyRandomGeneratorTypeModel,
+ self).__init__(
+ dmm,
+ fe_type,
+ members)
+
+
+# The Generator instances have a bit_generator attr
+make_attribute_wrapper(
+ types.NumPyRandomGeneratorType,
+ 'bit_generator',
+ 'bit_generator')
+
+
+def _generate_next_binding(overloadable_function, return_type):
+ """
+ Generate the overloads for "next_(some type)" functions.
+ """
+ @intrinsic
+ def intrin_NumPyRandomBitGeneratorType_next_ty(tyctx, inst):
+ sig = return_type(inst)
+
+ def codegen(cgctx, builder, sig, llargs):
+ name = overloadable_function.__name__
+ struct_ptr = cgutils.create_struct_proxy(inst)(cgctx, builder,
+ value=llargs[0])
+
+ # Get the 'state' and 'fnptr_next_(type)' members of the struct
+ state = struct_ptr.state
+ next_double_addr = getattr(struct_ptr, f'fnptr_{name}')
+
+ # LLVM IR types needed
+ ll_void_ptr_t = cgctx.get_value_type(types.voidptr)
+ ll_return_t = cgctx.get_value_type(return_type)
+ ll_uintp_t = cgctx.get_value_type(types.uintp)
+
+ # Convert the stored Generator function address to a pointer
+ next_fn_fnptr = builder.inttoptr(
+ next_double_addr, ll_void_ptr_t)
+ # Add the function to the module
+ fnty = ir.FunctionType(ll_return_t, (ll_uintp_t,))
+ next_fn = cgutils.get_or_insert_function(
+ builder.module, fnty, name)
+ # Bit cast the function pointer to the function type
+ fnptr_as_fntype = builder.bitcast(next_fn_fnptr, next_fn.type)
+ # call it with the "state" address as the arg
+ ret = builder.call(fnptr_as_fntype, (state,))
+ return ret
+ return sig, codegen
+
+ @overload(overloadable_function)
+ def ol_next_ty(bitgen):
+ if isinstance(bitgen, types.NumPyRandomBitGeneratorType):
+ def impl(bitgen):
+ return intrin_NumPyRandomBitGeneratorType_next_ty(bitgen)
+ return impl
+
+
+# Some function stubs for "next(some type)", these will be overloaded
+def next_double(bitgen):
+ return bitgen.ctypes.next_double(bitgen.ctypes.state)
+
+
+def next_uint32(bitgen):
+ return bitgen.ctypes.next_uint32(bitgen.ctypes.state)
+
+
+def next_uint64(bitgen):
+ return bitgen.ctypes.next_uint64(bitgen.ctypes.state)
+
+
+if config.USE_LEGACY_TYPE_SYSTEM:
+ _generate_next_binding(next_double, types.double)
+ _generate_next_binding(next_uint32, types.uint32)
+ _generate_next_binding(next_uint64, types.uint64)
+
+ # See: https://github.com/numpy/numpy/pull/20314
+ @register_jitable
+ def next_float(bitgen):
+ return types.float32(types.float32(next_uint32(bitgen) >> 8)
+ * types.float32(1.0)
+ / types.float32(16777216.0))
+
+else:
+ _generate_next_binding(next_double, types.np_double)
+ _generate_next_binding(next_uint32, types.np_uint32)
+ _generate_next_binding(next_uint64, types.np_uint64)
+
+ # See: https://github.com/numpy/numpy/pull/20314
+ @register_jitable
+ def next_float(bitgen):
+ return types.np_float32(types.np_float32(next_uint32(bitgen) >> 8)
+ * types.np_float32(1.0)
+ / types.np_float32(16777216.0))
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/np/random/generator_methods.py b/tool_server/.venv/lib/python3.12/site-packages/numba/np/random/generator_methods.py
new file mode 100644
index 0000000000000000000000000000000000000000..03968e8699b49e9a6478be188fcf9738a1ab9330
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/np/random/generator_methods.py
@@ -0,0 +1,971 @@
+"""
+Implementation of method overloads for Generator objects.
+"""
+
+import numpy as np
+from numba.core import types
+from numba.core.extending import overload_method, register_jitable
+from numba.np.numpy_support import as_dtype, from_dtype
+from numba.np.random.generator_core import next_float, next_double
+from numba.np.numpy_support import is_nonelike
+from numba.core.errors import TypingError
+from numba.core.types.containers import Tuple, UniTuple
+from numba.np.random.distributions import \
+ (random_standard_exponential_inv_f, random_standard_exponential_inv,
+ random_standard_exponential, random_standard_normal_f,
+ random_standard_gamma, random_standard_normal, random_uniform,
+ random_standard_exponential_f, random_standard_gamma_f, random_normal,
+ random_exponential, random_gamma, random_beta, random_power,
+ random_f,random_chisquare,random_standard_cauchy,random_pareto,
+ random_weibull, random_laplace, random_logistic,
+ random_lognormal, random_rayleigh, random_standard_t, random_wald,
+ random_geometric, random_zipf, random_triangular,
+ random_poisson, random_negative_binomial, random_logseries,
+ random_noncentral_chisquare, random_noncentral_f, random_binomial)
+from numba.np.random import random_methods
+
+
+def _get_proper_func(func_32, func_64, dtype, dist_name="the given"):
+ """
+ Most of the standard NumPy distributions that accept dtype argument
+ only support either np.float32 or np.float64 as dtypes.
+
+ This is a helper function that helps Numba select the proper underlying
+ implementation according to provided dtype.
+ """
+ if isinstance(dtype, types.Omitted):
+ dtype = dtype.value
+
+ np_dt = dtype
+ if isinstance(dtype, type):
+ nb_dt = from_dtype(np.dtype(dtype))
+ elif isinstance(dtype, types.NumberClass):
+ nb_dt = dtype
+ np_dt = as_dtype(nb_dt)
+
+ if np_dt not in [np.float32, np.float64]:
+ raise TypingError("Argument dtype is not one of the" +
+ " expected type(s): " +
+ " np.float32 or np.float64")
+
+ if np_dt == np.float32:
+ next_func = func_32
+ else:
+ next_func = func_64
+
+ return next_func, nb_dt
+
+
+def check_size(size):
+ if not any([isinstance(size, UniTuple) and
+ isinstance(size.dtype, types.Integer),
+ isinstance(size, Tuple) and size.count == 0,
+ isinstance(size, types.Integer)]):
+ raise TypingError("Argument size is not one of the" +
+ " expected type(s): " +
+ " an integer, an empty tuple or a tuple of integers")
+
+
+def check_types(obj, type_list, arg_name):
+ """
+ Check if given object is one of the provided types.
+ If not raises an TypeError
+ """
+ if isinstance(obj, types.Omitted):
+ obj = obj.value
+
+ if not isinstance(type_list, (list, tuple)):
+ type_list = [type_list]
+
+ if not any([isinstance(obj, _type) for _type in type_list]):
+ raise TypingError(f"Argument {arg_name} is not one of the" +
+ f" expected type(s): {type_list}")
+
+
+# Overload the Generator().integers()
+@overload_method(types.NumPyRandomGeneratorType, 'integers')
+def NumPyRandomGeneratorType_integers(inst, low, high, size=None,
+ dtype=np.int64, endpoint=False):
+ check_types(low, [types.Integer,
+ types.Boolean, bool, int], 'low')
+ check_types(high, [types.Integer, types.Boolean,
+ bool, int], 'high')
+ check_types(endpoint, [types.Boolean, bool], 'endpoint')
+
+ if isinstance(size, types.Omitted):
+ size = size.value
+
+ if isinstance(dtype, types.Omitted):
+ dtype = dtype.value
+
+ if isinstance(dtype, type):
+ nb_dt = from_dtype(np.dtype(dtype))
+ _dtype = dtype
+ elif isinstance(dtype, types.NumberClass):
+ nb_dt = dtype
+ _dtype = as_dtype(nb_dt)
+ else:
+ raise TypingError("Argument dtype is not one of the" +
+ " expected type(s): " +
+ "np.int32, np.int64, np.int16, np.int8, "
+ "np.uint32, np.uint64, np.uint16, np.uint8, "
+ "np.bool_")
+
+ if _dtype == np.bool_:
+ int_func = random_methods.random_bounded_bool_fill
+ lower_bound = -1
+ upper_bound = 2
+ else:
+ try:
+ i_info = np.iinfo(_dtype)
+ except ValueError:
+ raise TypingError("Argument dtype is not one of the" +
+ " expected type(s): " +
+ "np.int32, np.int64, np.int16, np.int8, "
+ "np.uint32, np.uint64, np.uint16, np.uint8, "
+ "np.bool_")
+ int_func = getattr(random_methods,
+ f'random_bounded_uint{i_info.bits}_fill')
+ lower_bound = i_info.min
+ upper_bound = i_info.max
+
+ if is_nonelike(size):
+ def impl(inst, low, high, size=None,
+ dtype=np.int64, endpoint=False):
+ random_methods._randint_arg_check(low, high, endpoint,
+ lower_bound, upper_bound)
+ if not endpoint:
+ high -= dtype(1)
+ low = dtype(low)
+ high = dtype(high)
+ rng = high - low
+ return int_func(inst.bit_generator, low, rng, 1, dtype)[0]
+ else:
+ low = dtype(low)
+ high = dtype(high)
+ rng = high - low
+ return int_func(inst.bit_generator, low, rng, 1, dtype)[0]
+ return impl
+ else:
+ check_size(size)
+
+ def impl(inst, low, high, size=None,
+ dtype=np.int64, endpoint=False):
+ random_methods._randint_arg_check(low, high, endpoint,
+ lower_bound, upper_bound)
+ if not endpoint:
+ high -= dtype(1)
+ low = dtype(low)
+ high = dtype(high)
+ rng = high - low
+ return int_func(inst.bit_generator, low, rng, size, dtype)
+ else:
+ low = dtype(low)
+ high = dtype(high)
+ rng = high - low
+ return int_func(inst.bit_generator, low, rng, size, dtype)
+ return impl
+
+
+# The following `shuffle` implementation is a direct translation from:
+# https://github.com/numpy/numpy/blob/95e3e7f445407e4f355b23d6a9991d8774f0eb0c/numpy/random/_generator.pyx#L4578
+
+# Overload the Generator().shuffle()
+@overload_method(types.NumPyRandomGeneratorType, 'shuffle')
+def NumPyRandomGeneratorType_shuffle(inst, x, axis=0):
+ check_types(x, [types.Array], 'x')
+ check_types(axis, [int, types.Integer], 'axis')
+
+ def impl(inst, x, axis=0):
+ if axis < 0:
+ axis = axis + x.ndim
+ if axis > x.ndim - 1 or axis < 0:
+ raise IndexError("Axis is out of bounds for the given array")
+
+ z = np.swapaxes(x, 0, axis)
+ buf = np.empty_like(z[0, ...])
+
+ for i in range(len(z) - 1, 0, -1):
+ j = types.intp(random_methods.random_interval(inst.bit_generator,
+ i))
+ if i == j:
+ continue
+ buf[...] = z[j, ...]
+ z[j, ...] = z[i, ...]
+ z[i, ...] = buf
+
+ return impl
+
+
+# The following `permutation` implementation is a direct translation from:
+# https://github.com/numpy/numpy/blob/95e3e7f445407e4f355b23d6a9991d8774f0eb0c/numpy/random/_generator.pyx#L4710
+# Overload the Generator().permutation()
+@overload_method(types.NumPyRandomGeneratorType, 'permutation')
+def NumPyRandomGeneratorType_permutation(inst, x, axis=0):
+ check_types(x, [types.Array, types.Integer], 'x')
+ check_types(axis, [int, types.Integer], 'axis')
+
+ IS_INT = isinstance(x, types.Integer)
+
+ def impl(inst, x, axis=0):
+ if IS_INT:
+ new_arr = np.arange(x)
+ # NumPy ignores the axis argument when x is an integer
+ inst.shuffle(new_arr)
+ else:
+ new_arr = x.copy()
+ inst.shuffle(new_arr, axis=axis)
+ return new_arr
+
+ return impl
+
+
+# Overload the Generator().random()
+@overload_method(types.NumPyRandomGeneratorType, 'random')
+def NumPyRandomGeneratorType_random(inst, size=None, dtype=np.float64):
+ dist_func, nb_dt = _get_proper_func(next_float, next_double,
+ dtype, "random")
+ if isinstance(size, types.Omitted):
+ size = size.value
+
+ if is_nonelike(size):
+ def impl(inst, size=None, dtype=np.float64):
+ return nb_dt(dist_func(inst.bit_generator))
+ return impl
+ else:
+ check_size(size)
+
+ def impl(inst, size=None, dtype=np.float64):
+ out = np.empty(size, dtype=dtype)
+ out_f = out.flat
+ for i in range(out.size):
+ out_f[i] = dist_func(inst.bit_generator)
+ return out
+ return impl
+
+
+# Overload the Generator().standard_exponential() method
+@overload_method(types.NumPyRandomGeneratorType, 'standard_exponential')
+def NumPyRandomGeneratorType_standard_exponential(inst, size=None,
+ dtype=np.float64,
+ method='zig'):
+ check_types(method, [types.UnicodeType, str], 'method')
+ dist_func_inv, nb_dt = _get_proper_func(
+ random_standard_exponential_inv_f,
+ random_standard_exponential_inv,
+ dtype
+ )
+
+ dist_func, nb_dt = _get_proper_func(random_standard_exponential_f,
+ random_standard_exponential,
+ dtype)
+
+ if isinstance(size, types.Omitted):
+ size = size.value
+
+ if is_nonelike(size):
+ def impl(inst, size=None, dtype=np.float64, method='zig'):
+ if method == 'zig':
+ return nb_dt(dist_func(inst.bit_generator))
+ elif method == 'inv':
+ return nb_dt(dist_func_inv(inst.bit_generator))
+ else:
+ raise ValueError("Method must be either 'zig' or 'inv'")
+ return impl
+ else:
+ check_size(size)
+
+ def impl(inst, size=None, dtype=np.float64, method='zig'):
+ out = np.empty(size, dtype=dtype)
+ out_f = out.flat
+ if method == 'zig':
+ for i in range(out.size):
+ out_f[i] = dist_func(inst.bit_generator)
+ elif method == 'inv':
+ for i in range(out.size):
+ out_f[i] = dist_func_inv(inst.bit_generator)
+ else:
+ raise ValueError("Method must be either 'zig' or 'inv'")
+ return out
+ return impl
+
+
+# Overload the Generator().standard_normal() method
+@overload_method(types.NumPyRandomGeneratorType, 'standard_normal')
+def NumPyRandomGeneratorType_standard_normal(inst, size=None, dtype=np.float64):
+ dist_func, nb_dt = _get_proper_func(random_standard_normal_f,
+ random_standard_normal,
+ dtype)
+ if isinstance(size, types.Omitted):
+ size = size.value
+
+ if is_nonelike(size):
+ def impl(inst, size=None, dtype=np.float64):
+ return nb_dt(dist_func(inst.bit_generator))
+ return impl
+ else:
+ check_size(size)
+
+ def impl(inst, size=None, dtype=np.float64):
+ out = np.empty(size, dtype=dtype)
+ out_f = out.flat
+ for i in range(out.size):
+ out_f[i] = dist_func(inst.bit_generator)
+ return out
+ return impl
+
+
+# Overload the Generator().standard_gamma() method
+@overload_method(types.NumPyRandomGeneratorType, 'standard_gamma')
+def NumPyRandomGeneratorType_standard_gamma(inst, shape, size=None,
+ dtype=np.float64):
+ check_types(shape, [types.Float, types.Integer, int, float], 'shape')
+ dist_func, nb_dt = _get_proper_func(random_standard_gamma_f,
+ random_standard_gamma,
+ dtype)
+ if isinstance(size, types.Omitted):
+ size = size.value
+
+ if is_nonelike(size):
+ def impl(inst, shape, size=None, dtype=np.float64):
+ return nb_dt(dist_func(inst.bit_generator, shape))
+ return impl
+ else:
+ check_size(size)
+
+ def impl(inst, shape, size=None, dtype=np.float64):
+ out = np.empty(size, dtype=dtype)
+ out_f = out.flat
+ for i in range(out.size):
+ out_f[i] = dist_func(inst.bit_generator, shape)
+ return out
+ return impl
+
+
+# Overload the Generator().normal() method
+@overload_method(types.NumPyRandomGeneratorType, 'normal')
+def NumPyRandomGeneratorType_normal(inst, loc=0.0, scale=1.0,
+ size=None):
+ check_types(loc, [types.Float, types.Integer, int, float], 'loc')
+ check_types(scale, [types.Float, types.Integer, int, float], 'scale')
+ if isinstance(size, types.Omitted):
+ size = size.value
+
+ if is_nonelike(size):
+ def impl(inst, loc=0.0, scale=1.0, size=None):
+ return random_normal(inst.bit_generator, loc, scale)
+ return impl
+ else:
+ check_size(size)
+
+ def impl(inst, loc=0.0, scale=1.0, size=None):
+ out = np.empty(size, dtype=np.float64)
+ out_f = out.flat
+ for i in range(out.size):
+ out_f[i] = random_normal(inst.bit_generator, loc, scale)
+ return out
+ return impl
+
+
+# Overload the Generator().uniform() method
+@overload_method(types.NumPyRandomGeneratorType, 'uniform')
+def NumPyRandomGeneratorType_uniform(inst, low=0.0, high=1.0,
+ size=None):
+ check_types(low, [types.Float, types.Integer, int, float], 'low')
+ check_types(high, [types.Float, types.Integer, int, float], 'high')
+ if isinstance(size, types.Omitted):
+ size = size.value
+
+ if is_nonelike(size):
+ def impl(inst, low=0.0, high=1.0, size=None):
+ return random_uniform(inst.bit_generator, low, high - low)
+ return impl
+ else:
+ check_size(size)
+
+ def impl(inst, low=0.0, high=1.0, size=None):
+ out = np.empty(size, dtype=np.float64)
+ out_f = out.flat
+ for i in range(out.size):
+ out_f[i] = random_uniform(inst.bit_generator, low, high - low)
+ return out
+ return impl
+
+
+# Overload the Generator().exponential() method
+@overload_method(types.NumPyRandomGeneratorType, 'exponential')
+def NumPyRandomGeneratorType_exponential(inst, scale=1.0, size=None):
+ check_types(scale, [types.Float, types.Integer, int, float], 'scale')
+ if isinstance(size, types.Omitted):
+ size = size.value
+
+ if is_nonelike(size):
+ def impl(inst, scale=1.0, size=None):
+ return random_exponential(inst.bit_generator, scale)
+ return impl
+ else:
+ check_size(size)
+
+ def impl(inst, scale=1.0, size=None):
+ out = np.empty(size, dtype=np.float64)
+ out_f = out.flat
+ for i in range(out.size):
+ out_f[i] = random_exponential(inst.bit_generator, scale)
+ return out
+ return impl
+
+
+# Overload the Generator().gamma() method
+@overload_method(types.NumPyRandomGeneratorType, 'gamma')
+def NumPyRandomGeneratorType_gamma(inst, shape, scale=1.0, size=None):
+ check_types(shape, [types.Float, types.Integer, int, float], 'shape')
+ check_types(scale, [types.Float, types.Integer, int, float], 'scale')
+ if isinstance(size, types.Omitted):
+ size = size.value
+
+ if is_nonelike(size):
+ def impl(inst, shape, scale=1.0, size=None):
+ return random_gamma(inst.bit_generator, shape, scale)
+ return impl
+ else:
+ check_size(size)
+
+ def impl(inst, shape, scale=1.0, size=None):
+ out = np.empty(size, dtype=np.float64)
+ out_f = out.flat
+ for i in range(out.size):
+ out_f[i] = random_gamma(inst.bit_generator, shape, scale)
+ return out
+ return impl
+
+
+# Overload the Generator().beta() method
+@overload_method(types.NumPyRandomGeneratorType, 'beta')
+def NumPyRandomGeneratorType_beta(inst, a, b, size=None):
+ check_types(a, [types.Float, types.Integer, int, float], 'a')
+ check_types(b, [types.Float, types.Integer, int, float], 'b')
+ if isinstance(size, types.Omitted):
+ size = size.value
+
+ if is_nonelike(size):
+ def impl(inst, a, b, size=None):
+ return random_beta(inst.bit_generator, a, b)
+ return impl
+ else:
+ check_size(size)
+
+ def impl(inst, a, b, size=None):
+ out = np.empty(size)
+ out_f = out.flat
+ for i in range(out.size):
+ out_f[i] = random_beta(inst.bit_generator, a, b)
+ return out
+ return impl
+
+
+# Overload the Generator().f() method
+@overload_method(types.NumPyRandomGeneratorType, 'f')
+def NumPyRandomGeneratorType_f(inst, dfnum, dfden, size=None):
+ check_types(dfnum, [types.Float, types.Integer, int, float], 'dfnum')
+ check_types(dfden, [types.Float, types.Integer, int, float], 'dfden')
+ if isinstance(size, types.Omitted):
+ size = size.value
+
+ if is_nonelike(size):
+ def impl(inst, dfnum, dfden, size=None):
+ return random_f(inst.bit_generator, dfnum, dfden)
+ return impl
+ else:
+ check_size(size)
+
+ def impl(inst, dfnum, dfden, size=None):
+ out = np.empty(size)
+ out_f = out.flat
+ for i in range(out.size):
+ out_f[i] = random_f(inst.bit_generator, dfnum, dfden)
+ return out
+ return impl
+
+
+# Overload the Generator().chisquare() method
+@overload_method(types.NumPyRandomGeneratorType, 'chisquare')
+def NumPyRandomGeneratorType_chisquare(inst, df, size=None):
+ check_types(df, [types.Float, types.Integer, int, float], 'df')
+ if isinstance(size, types.Omitted):
+ size = size.value
+
+ if is_nonelike(size):
+ def impl(inst, df, size=None):
+ return random_chisquare(inst.bit_generator, df)
+ return impl
+ else:
+ check_size(size)
+
+ def impl(inst, df, size=None):
+ out = np.empty(size)
+ out_f = out.flat
+ for i in range(out.size):
+ out_f[i] = random_chisquare(inst.bit_generator, df)
+ return out
+ return impl
+
+
+@overload_method(types.NumPyRandomGeneratorType, 'standard_cauchy')
+def NumPyRandomGeneratorType_standard_cauchy(inst, size=None):
+
+ if isinstance(size, types.Omitted):
+ size = size.value
+
+ if is_nonelike(size):
+ def impl(inst, size=None):
+ return random_standard_cauchy(inst.bit_generator)
+ return impl
+ else:
+ check_size(size)
+
+ def impl(inst, size=None):
+ out = np.empty(size)
+ out_f = out.flat
+ for i in range(out.size):
+ out_f[i] = random_standard_cauchy(inst.bit_generator)
+ return out
+ return impl
+
+
+@overload_method(types.NumPyRandomGeneratorType, 'pareto')
+def NumPyRandomGeneratorType_pareto(inst, a, size=None):
+ check_types(a, [types.Float, types.Integer, int, float], 'a')
+ if isinstance(size, types.Omitted):
+ size = size.value
+
+ if is_nonelike(size):
+ def impl(inst, a, size=None):
+ return random_pareto(inst.bit_generator, a)
+ return impl
+ else:
+ check_size(size)
+
+ def impl(inst, a, size=None):
+ out = np.empty(size)
+ out_f = out.flat
+ for i in range(out.size):
+ out_f[i] = random_pareto(inst.bit_generator, a)
+ return out
+ return impl
+
+
+@overload_method(types.NumPyRandomGeneratorType, 'weibull')
+def NumPyRandomGeneratorType_weibull(inst, a, size=None):
+ check_types(a, [types.Float, types.Integer, int, float], 'a')
+ if isinstance(size, types.Omitted):
+ size = size.value
+
+ if is_nonelike(size):
+ def impl(inst, a, size=None):
+ return random_weibull(inst.bit_generator, a)
+ return impl
+ else:
+ check_size(size)
+
+ def impl(inst, a, size=None):
+ out = np.empty(size)
+ out_f = out.flat
+ for i in range(out.size):
+ out_f[i] = random_weibull(inst.bit_generator, a)
+ return out
+ return impl
+
+
+@overload_method(types.NumPyRandomGeneratorType, 'power')
+def NumPyRandomGeneratorType_power(inst, a, size=None):
+ check_types(a, [types.Float, types.Integer, int, float], 'a')
+ if isinstance(size, types.Omitted):
+ size = size.value
+
+ if is_nonelike(size):
+ def impl(inst, a, size=None):
+ return random_power(inst.bit_generator, a)
+ return impl
+ else:
+ check_size(size)
+
+ def impl(inst, a, size=None):
+ out = np.empty(size)
+ out_f = out.flat
+ for i in range(out.size):
+ out_f[i] = random_power(inst.bit_generator, a)
+ return out
+ return impl
+
+
+@overload_method(types.NumPyRandomGeneratorType, 'laplace')
+def NumPyRandomGeneratorType_laplace(inst, loc=0.0, scale=1.0, size=None):
+ check_types(loc, [types.Float, types.Integer, int, float], 'loc')
+ check_types(scale, [types.Float, types.Integer, int, float], 'scale')
+ if isinstance(size, types.Omitted):
+ size = size.value
+
+ if is_nonelike(size):
+ def impl(inst, loc=0.0, scale=1.0, size=None):
+ return random_laplace(inst.bit_generator, loc, scale)
+ return impl
+ else:
+ check_size(size)
+
+ def impl(inst, loc=0.0, scale=1.0, size=None):
+ out = np.empty(size)
+ out_f = out.flat
+ for i in range(out.size):
+ out_f[i] = random_laplace(inst.bit_generator, loc, scale)
+ return out
+ return impl
+
+
+@overload_method(types.NumPyRandomGeneratorType, 'logistic')
+def NumPyRandomGeneratorType_logistic(inst, loc=0.0, scale=1.0, size=None):
+ check_types(loc, [types.Float, types.Integer, int, float], 'loc')
+ check_types(scale, [types.Float, types.Integer, int, float], 'scale')
+ if isinstance(size, types.Omitted):
+ size = size.value
+
+ if is_nonelike(size):
+ def impl(inst, loc=0.0, scale=1.0, size=None):
+ return random_logistic(inst.bit_generator, loc, scale)
+ return impl
+ else:
+ check_size(size)
+
+ def impl(inst, loc=0.0, scale=1.0, size=None):
+ out = np.empty(size)
+ out_f = out.flat
+ for i in range(out.size):
+ out_f[i] = random_logistic(inst.bit_generator, loc, scale)
+ return out
+ return impl
+
+
+@overload_method(types.NumPyRandomGeneratorType, 'lognormal')
+def NumPyRandomGeneratorType_lognormal(inst, mean=0.0, sigma=1.0, size=None):
+ check_types(mean, [types.Float, types.Integer, int, float], 'mean')
+ check_types(sigma, [types.Float, types.Integer, int, float], 'sigma')
+ if isinstance(size, types.Omitted):
+ size = size.value
+
+ if is_nonelike(size):
+ def impl(inst, mean=0.0, sigma=1.0, size=None):
+ return random_lognormal(inst.bit_generator, mean, sigma)
+ return impl
+ else:
+ check_size(size)
+
+ def impl(inst, mean=0.0, sigma=1.0, size=None):
+ out = np.empty(size)
+ out_f = out.flat
+ for i in range(out.size):
+ out_f[i] = random_lognormal(inst.bit_generator, mean, sigma)
+ return out
+ return impl
+
+
+@overload_method(types.NumPyRandomGeneratorType, 'rayleigh')
+def NumPyRandomGeneratorType_rayleigh(inst, scale=1.0, size=None):
+ check_types(scale, [types.Float, types.Integer, int, float], 'scale')
+ if isinstance(size, types.Omitted):
+ size = size.value
+
+ if is_nonelike(size):
+ def impl(inst, scale=1.0, size=None):
+ return random_rayleigh(inst.bit_generator, scale)
+ return impl
+ else:
+ check_size(size)
+
+ def impl(inst, scale=1.0, size=None):
+ out = np.empty(size)
+ out_f = out.flat
+ for i in range(out.size):
+ out_f[i] = random_rayleigh(inst.bit_generator, scale)
+ return out
+ return impl
+
+
+@overload_method(types.NumPyRandomGeneratorType, 'standard_t')
+def NumPyRandomGeneratorType_standard_t(inst, df, size=None):
+ check_types(df, [types.Float, types.Integer, int, float], 'df')
+ if isinstance(size, types.Omitted):
+ size = size.value
+
+ if is_nonelike(size):
+ def impl(inst, df, size=None):
+ return random_standard_t(inst.bit_generator, df)
+ return impl
+ else:
+ check_size(size)
+
+ def impl(inst, df, size=None):
+ out = np.empty(size)
+ out_f = out.flat
+ for i in range(out.size):
+ out_f[i] = random_standard_t(inst.bit_generator, df)
+ return out
+ return impl
+
+
+@overload_method(types.NumPyRandomGeneratorType, 'wald')
+def NumPyRandomGeneratorType_wald(inst, mean, scale, size=None):
+ check_types(mean, [types.Float, types.Integer, int, float], 'mean')
+ check_types(scale, [types.Float, types.Integer, int, float], 'scale')
+ if isinstance(size, types.Omitted):
+ size = size.value
+
+ if is_nonelike(size):
+ def impl(inst, mean, scale, size=None):
+ return random_wald(inst.bit_generator, mean, scale)
+ return impl
+ else:
+ check_size(size)
+
+ def impl(inst, mean, scale, size=None):
+ out = np.empty(size)
+ out_f = out.flat
+ for i in range(out.size):
+ out_f[i] = random_wald(inst.bit_generator, mean, scale)
+ return out
+ return impl
+
+
+@overload_method(types.NumPyRandomGeneratorType, 'geometric')
+def NumPyRandomGeneratorType_geometric(inst, p, size=None):
+ check_types(p, [types.Float, types.Integer, int, float], 'p')
+ if isinstance(size, types.Omitted):
+ size = size.value
+
+ if is_nonelike(size):
+ def impl(inst, p, size=None):
+ return np.int64(random_geometric(inst.bit_generator, p))
+ return impl
+ else:
+ check_size(size)
+
+ def impl(inst, p, size=None):
+ out = np.empty(size, dtype=np.int64)
+ out_f = out.flat
+ for i in range(out.size):
+ out_f[i] = random_geometric(inst.bit_generator, p)
+ return out
+ return impl
+
+
+@overload_method(types.NumPyRandomGeneratorType, 'zipf')
+def NumPyRandomGeneratorType_zipf(inst, a, size=None):
+ check_types(a, [types.Float, types.Integer, int, float], 'a')
+ if isinstance(size, types.Omitted):
+ size = size.value
+
+ if is_nonelike(size):
+ def impl(inst, a, size=None):
+ return np.int64(random_zipf(inst.bit_generator, a))
+ return impl
+ else:
+ check_size(size)
+
+ def impl(inst, a, size=None):
+ out = np.empty(size, dtype=np.int64)
+ out_f = out.flat
+ for i in range(out.size):
+ out_f[i] = random_zipf(inst.bit_generator, a)
+ return out
+ return impl
+
+
+@overload_method(types.NumPyRandomGeneratorType, 'triangular')
+def NumPyRandomGeneratorType_triangular(inst, left, mode, right, size=None):
+ check_types(left, [types.Float, types.Integer, int, float], 'left')
+ check_types(mode, [types.Float, types.Integer, int, float], 'mode')
+ check_types(right, [types.Float, types.Integer, int, float], 'right')
+ if isinstance(size, types.Omitted):
+ size = size.value
+
+ if is_nonelike(size):
+ def impl(inst, left, mode, right, size=None):
+ return random_triangular(inst.bit_generator, left, mode, right)
+ return impl
+ else:
+ check_size(size)
+
+ def impl(inst, left, mode, right, size=None):
+ out = np.empty(size)
+ out_f = out.flat
+ for i in range(out.size):
+ out_f[i] = random_triangular(inst.bit_generator,
+ left, mode, right)
+ return out
+ return impl
+
+
+@overload_method(types.NumPyRandomGeneratorType, 'poisson')
+def NumPyRandomGeneratorType_poisson(inst, lam , size=None):
+ check_types(lam, [types.Float, types.Integer, int, float], 'lam')
+ if isinstance(size, types.Omitted):
+ size = size.value
+
+ if is_nonelike(size):
+ def impl(inst, lam , size=None):
+ return np.int64(random_poisson(inst.bit_generator, lam))
+ return impl
+ else:
+ check_size(size)
+
+ def impl(inst, lam , size=None):
+ out = np.empty(size, dtype=np.int64)
+ out_f = out.flat
+ for i in range(out.size):
+ out_f[i] = random_poisson(inst.bit_generator, lam)
+ return out
+ return impl
+
+
+@overload_method(types.NumPyRandomGeneratorType, 'negative_binomial')
+def NumPyRandomGeneratorType_negative_binomial(inst, n, p, size=None):
+ check_types(n, [types.Float, types.Integer, int, float], 'n')
+ check_types(p, [types.Float, types.Integer, int, float], 'p')
+ if isinstance(size, types.Omitted):
+ size = size.value
+
+ if is_nonelike(size):
+ def impl(inst, n, p , size=None):
+ return np.int64(random_negative_binomial(inst.bit_generator, n, p))
+ return impl
+ else:
+ check_size(size)
+
+ def impl(inst, n, p , size=None):
+ out = np.empty(size, dtype=np.int64)
+ out_f = out.flat
+ for i in range(out.size):
+ out_f[i] = random_negative_binomial(inst.bit_generator, n, p)
+ return out
+ return impl
+
+
+@overload_method(types.NumPyRandomGeneratorType, 'noncentral_chisquare')
+def NumPyRandomGeneratorType_noncentral_chisquare(inst, df, nonc, size=None):
+ check_types(df, [types.Float, types.Integer, int, float], 'df')
+ check_types(nonc, [types.Float, types.Integer, int, float], 'nonc')
+ if isinstance(size, types.Omitted):
+ size = size.value
+
+ @register_jitable
+ def check_arg_bounds(df, nonc):
+ if df <= 0:
+ raise ValueError("df <= 0")
+ if nonc < 0:
+ raise ValueError("nonc < 0")
+
+ if is_nonelike(size):
+ def impl(inst, df, nonc, size=None):
+ check_arg_bounds(df, nonc)
+ return np.float64(random_noncentral_chisquare(inst.bit_generator,
+ df, nonc))
+ return impl
+ else:
+ check_size(size)
+
+ def impl(inst, df, nonc, size=None):
+ check_arg_bounds(df, nonc)
+ out = np.empty(size, dtype=np.float64)
+ out_f = out.flat
+ for i in range(out.size):
+ out_f[i] = random_noncentral_chisquare(inst.bit_generator,
+ df, nonc)
+ return out
+ return impl
+
+
+@overload_method(types.NumPyRandomGeneratorType, 'noncentral_f')
+def NumPyRandomGeneratorType_noncentral_f(inst, dfnum, dfden, nonc, size=None):
+ check_types(dfnum, [types.Float, types.Integer, int, float], 'dfnum')
+ check_types(dfden, [types.Float, types.Integer, int, float], 'dfden')
+ check_types(nonc, [types.Float, types.Integer, int, float], 'nonc')
+ if isinstance(size, types.Omitted):
+ size = size.value
+
+ @register_jitable
+ def check_arg_bounds(dfnum, dfden, nonc):
+ if dfnum <= 0:
+ raise ValueError("dfnum <= 0")
+ if dfden <= 0:
+ raise ValueError("dfden <= 0")
+ if nonc < 0:
+ raise ValueError("nonc < 0")
+
+ if is_nonelike(size):
+ def impl(inst, dfnum, dfden, nonc, size=None):
+ check_arg_bounds(dfnum, dfden, nonc)
+ return np.float64(random_noncentral_f(inst.bit_generator,
+ dfnum, dfden, nonc))
+ return impl
+ else:
+ check_size(size)
+
+ def impl(inst, dfnum, dfden, nonc, size=None):
+ check_arg_bounds(dfnum, dfden, nonc)
+ out = np.empty(size, dtype=np.float64)
+ out_f = out.flat
+ for i in range(out.size):
+ out_f[i] = random_noncentral_f(inst.bit_generator,
+ dfnum, dfden, nonc)
+ return out
+ return impl
+
+
+@overload_method(types.NumPyRandomGeneratorType, 'logseries')
+def NumPyRandomGeneratorType_logseries(inst, p, size=None):
+ check_types(p, [types.Float, types.Integer, int, float], 'p')
+ if isinstance(size, types.Omitted):
+ size = size.value
+
+ @register_jitable
+ def check_arg_bounds(p):
+ if p < 0 or p >= 1 or np.isnan(p):
+ raise ValueError("p < 0, p >= 1 or p is NaN")
+
+ if is_nonelike(size):
+ def impl(inst, p, size=None):
+ check_arg_bounds(p)
+ return np.int64(random_logseries(inst.bit_generator, p))
+ return impl
+ else:
+ check_size(size)
+
+ def impl(inst, p, size=None):
+ check_arg_bounds(p)
+ out = np.empty(size, dtype=np.int64)
+ out_f = out.flat
+ for i in range(out.size):
+ out_f[i] = random_logseries(inst.bit_generator, p)
+ return out
+ return impl
+
+
+@overload_method(types.NumPyRandomGeneratorType, 'binomial')
+def NumPyRandomGeneratorType_binomial(inst, n, p, size=None):
+ check_types(n, [types.Float, types.Integer, int, float], 'n')
+ check_types(p, [types.Float, types.Integer, int, float], 'p')
+
+ if isinstance(size, types.Omitted):
+ size = size.value
+
+ if is_nonelike(size):
+ def impl(inst, n, p, size=None):
+ return np.int64(random_binomial(inst.bit_generator, n, p))
+ return impl
+ else:
+ check_size(size)
+
+ def impl(inst, n, p, size=None):
+ out = np.empty(size, dtype=np.int64)
+ for i in np.ndindex(size):
+ out[i] = random_binomial(inst.bit_generator, n, p)
+ return out
+ return impl
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/np/random/new_distributions.py b/tool_server/.venv/lib/python3.12/site-packages/numba/np/random/new_distributions.py
new file mode 100644
index 0000000000000000000000000000000000000000..2a2e8f72d3407a788266c578982f4a6006c94cc6
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/np/random/new_distributions.py
@@ -0,0 +1,719 @@
+"""
+Algorithmic implementations for generating different types
+of random distributions.
+"""
+
+import numpy as np
+
+from numba.core.extending import register_jitable
+from numba.np.random._constants import (wi_double, ki_double,
+ ziggurat_nor_r, fi_double,
+ wi_float, ki_float,
+ ziggurat_nor_inv_r_f,
+ ziggurat_nor_r_f, fi_float,
+ we_double, ke_double,
+ ziggurat_exp_r, fe_double,
+ we_float, ke_float,
+ ziggurat_exp_r_f, fe_float,
+ INT64_MAX, ziggurat_nor_inv_r)
+from numba.np.random.generator_core import (next_double, next_float,
+ next_uint32, next_uint64)
+# All of the following implementations are direct translations from:
+# https://github.com/numpy/numpy/blob/7cfef93c77599bd387ecc6a15d186c5a46024dac/numpy/random/src/distributions/distributions.c
+
+
+@register_jitable
+def np_log1p(x):
+ return np.log1p(x)
+
+
+@register_jitable
+def np_log1pf(x):
+ return np.log1p(np.float32(x))
+
+
+@register_jitable
+def random_rayleigh(bitgen, mode):
+ return mode * np.sqrt(2.0 * random_standard_exponential(bitgen))
+
+
+@register_jitable
+def np_expm1(x):
+ return np.expm1(x)
+
+
+@register_jitable
+def random_standard_normal(bitgen):
+ while 1:
+ r = next_uint64(bitgen)
+ idx = r & 0xff
+ r >>= 8
+ sign = r & 0x1
+ rabs = (r >> 1) & 0x000fffffffffffff
+ x = rabs * wi_double[idx]
+ if (sign & 0x1):
+ x = -x
+ if rabs < ki_double[idx]:
+ return x
+ if idx == 0:
+ while 1:
+ xx = -ziggurat_nor_inv_r * np.log1p(-next_double(bitgen))
+ yy = -np.log1p(-next_double(bitgen))
+ if (yy + yy > xx * xx):
+ if ((rabs >> 8) & 0x1):
+ return -(ziggurat_nor_r + xx)
+ else:
+ return ziggurat_nor_r + xx
+ else:
+ if (((fi_double[idx - 1] - fi_double[idx]) *
+ next_double(bitgen) + fi_double[idx]) <
+ np.exp(-0.5 * x * x)):
+ return x
+
+
+@register_jitable
+def random_standard_normal_f(bitgen):
+ while 1:
+ r = next_uint32(bitgen)
+ idx = r & 0xff
+ sign = (r >> 8) & 0x1
+ rabs = (r >> 9) & 0x0007fffff
+ x = np.float32(np.float32(rabs) * wi_float[idx])
+ if (sign & 0x1):
+ x = -x
+ if (rabs < ki_float[idx]):
+ return x
+ if (idx == 0):
+ while 1:
+ xx = np.float32(-ziggurat_nor_inv_r_f *
+ np_log1pf(-next_float(bitgen)))
+ yy = np.float32(-np_log1pf(-next_float(bitgen)))
+ if (np.float32(yy + yy) > np.float32(xx * xx)):
+ if ((rabs >> 8) & 0x1):
+ return -np.float32(ziggurat_nor_r_f + xx)
+ else:
+ return np.float32(ziggurat_nor_r_f + xx)
+ else:
+ if (((fi_float[idx - 1] - fi_float[idx]) * next_float(bitgen) +
+ fi_float[idx]) < np.float32(np.exp(-np.float32(0.5) * x * x))):
+ return x
+
+
+@register_jitable
+def random_standard_exponential(bitgen):
+ while 1:
+ ri = next_uint64(bitgen)
+ ri >>= 3
+ idx = ri & 0xFF
+ ri >>= 8
+ x = ri * we_double[idx]
+ if (ri < ke_double[idx]):
+ return x
+ else:
+ if idx == 0:
+ return ziggurat_exp_r - np_log1p(-next_double(bitgen))
+ elif ((fe_double[idx - 1] - fe_double[idx]) * next_double(bitgen) +
+ fe_double[idx] < np.exp(-x)):
+ return x
+
+
+@register_jitable
+def random_standard_exponential_f(bitgen):
+ while 1:
+ ri = next_uint32(bitgen)
+ ri >>= 1
+ idx = ri & 0xFF
+ ri >>= 8
+ x = np.float32(np.float32(ri) * we_float[idx])
+ if (ri < ke_float[idx]):
+ return x
+ else:
+ if (idx == 0):
+ return np.float32(ziggurat_exp_r_f -
+ np.float32(np_log1pf(-next_float(bitgen))))
+ elif ((fe_float[idx - 1] - fe_float[idx]) * next_float(bitgen) +
+ fe_float[idx] < np.float32(np.exp(np.float32(-x)))):
+ return x
+
+
+@register_jitable
+def random_standard_exponential_inv(bitgen):
+ return -np_log1p(-next_double(bitgen))
+
+
+@register_jitable
+def random_standard_exponential_inv_f(bitgen):
+ return -np.log(np.float32(1.0) - next_float(bitgen))
+
+
+@register_jitable
+def random_standard_gamma(bitgen, shape):
+ if (shape == 1.0):
+ return random_standard_exponential(bitgen)
+ elif (shape == 0.0):
+ return 0.0
+ elif (shape < 1.0):
+ while 1:
+ U = next_double(bitgen)
+ V = random_standard_exponential(bitgen)
+ if (U <= 1.0 - shape):
+ X = pow(U, 1. / shape)
+ if (X <= V):
+ return X
+ else:
+ Y = -np.log((1 - U) / shape)
+ X = pow(1.0 - shape + shape * Y, 1. / shape)
+ if (X <= (V + Y)):
+ return X
+ else:
+ b = shape - 1. / 3.
+ c = 1. / np.sqrt(9 * b)
+ while 1:
+ while 1:
+ X = random_standard_normal(bitgen)
+ V = 1.0 + c * X
+ if (V > 0.0):
+ break
+
+ V = V * V * V
+ U = next_double(bitgen)
+ if (U < 1.0 - 0.0331 * (X * X) * (X * X)):
+ return (b * V)
+
+ if (np.log(U) < 0.5 * X * X + b * (1. - V + np.log(V))):
+ return (b * V)
+
+
+@register_jitable
+def random_standard_gamma_f(bitgen, shape):
+ f32_one = np.float32(1.0)
+ shape = np.float32(shape)
+ if (shape == f32_one):
+ return random_standard_exponential_f(bitgen)
+ elif (shape == np.float32(0.0)):
+ return np.float32(0.0)
+ elif (shape < f32_one):
+ while 1:
+ U = next_float(bitgen)
+ V = random_standard_exponential_f(bitgen)
+ if (U <= f32_one - shape):
+ X = np.float32(pow(U, np.float32(f32_one / shape)))
+ if (X <= V):
+ return X
+ else:
+ Y = np.float32(-np.log(np.float32((f32_one - U) / shape)))
+ X = np.float32(pow(f32_one - shape + np.float32(shape * Y),
+ np.float32(f32_one / shape)))
+ if (X <= (V + Y)):
+ return X
+ else:
+ b = shape - f32_one / np.float32(3.0)
+ c = np.float32(f32_one / np.float32(np.sqrt(np.float32(9.0) * b)))
+ while 1:
+ while 1:
+ X = np.float32(random_standard_normal_f(bitgen))
+ V = np.float32(f32_one + c * X)
+ if (V > np.float32(0.0)):
+ break
+
+ V = np.float32(V * V * V)
+ U = next_float(bitgen)
+ if (U < f32_one - np.float32(0.0331) * (X * X) * (X * X)):
+ return np.float32(b * V)
+
+ if (np.log(U) < np.float32(0.5) * X * X + b *
+ (f32_one - V + np.log(V))):
+ return np.float32(b * V)
+
+
+@register_jitable
+def random_normal(bitgen, loc, scale):
+ scaled_normal = scale * random_standard_normal(bitgen)
+ return loc + scaled_normal
+
+
+@register_jitable
+def random_normal_f(bitgen, loc, scale):
+ scaled_normal = np.float32(scale * random_standard_normal_f(bitgen))
+ return np.float32(loc + scaled_normal)
+
+
+@register_jitable
+def random_exponential(bitgen, scale):
+ return scale * random_standard_exponential(bitgen)
+
+
+@register_jitable
+def random_uniform(bitgen, lower, range):
+ scaled_uniform = range * next_double(bitgen)
+ return lower + scaled_uniform
+
+
+@register_jitable
+def random_gamma(bitgen, shape, scale):
+ return scale * random_standard_gamma(bitgen, shape)
+
+
+@register_jitable
+def random_gamma_f(bitgen, shape, scale):
+ return np.float32(scale * random_standard_gamma_f(bitgen, shape))
+
+
+@register_jitable
+def random_beta(bitgen, a, b):
+ if a <= 1.0 and b <= 1.0:
+ while 1:
+ U = next_double(bitgen)
+ V = next_double(bitgen)
+ X = pow(U, 1.0 / a)
+ Y = pow(V, 1.0 / b)
+ XpY = X + Y
+ if XpY <= 1.0 and XpY > 0.0:
+ if (X + Y > 0):
+ return X / XpY
+ else:
+ logX = np.log(U) / a
+ logY = np.log(V) / b
+ logM = min(logX, logY)
+ logX -= logM
+ logY -= logM
+
+ return np.exp(logX - np.log(np.exp(logX) + np.exp(logY)))
+ else:
+ Ga = random_standard_gamma(bitgen, a)
+ Gb = random_standard_gamma(bitgen, b)
+ return Ga / (Ga + Gb)
+
+
+@register_jitable
+def random_chisquare(bitgen, df):
+ return 2.0 * random_standard_gamma(bitgen, df / 2.0)
+
+
+@register_jitable
+def random_f(bitgen, dfnum, dfden):
+ return ((random_chisquare(bitgen, dfnum) * dfden) /
+ (random_chisquare(bitgen, dfden) * dfnum))
+
+
+@register_jitable
+def random_standard_cauchy(bitgen):
+ return random_standard_normal(bitgen) / random_standard_normal(bitgen)
+
+
+@register_jitable
+def random_pareto(bitgen, a):
+ return np_expm1(random_standard_exponential(bitgen) / a)
+
+
+@register_jitable
+def random_weibull(bitgen, a):
+ if (a == 0.0):
+ return 0.0
+ return pow(random_standard_exponential(bitgen), 1. / a)
+
+
+@register_jitable
+def random_power(bitgen, a):
+ return pow(-np_expm1(-random_standard_exponential(bitgen)), 1. / a)
+
+
+@register_jitable
+def random_laplace(bitgen, loc, scale):
+ U = next_double(bitgen)
+ while U <= 0:
+ U = next_double(bitgen)
+ if (U >= 0.5):
+ U = loc - scale * np.log(2.0 - U - U)
+ elif (U > 0.0):
+ U = loc + scale * np.log(U + U)
+ return U
+
+
+@register_jitable
+def random_logistic(bitgen, loc, scale):
+ U = next_double(bitgen)
+ while U <= 0.0:
+ U = next_double(bitgen)
+ return loc + scale * np.log(U / (1.0 - U))
+
+
+@register_jitable
+def random_lognormal(bitgen, mean, sigma):
+ return np.exp(random_normal(bitgen, mean, sigma))
+
+
+@register_jitable
+def random_standard_t(bitgen, df):
+ num = random_standard_normal(bitgen)
+ denom = random_standard_gamma(bitgen, df / 2)
+ return np.sqrt(df / 2) * num / np.sqrt(denom)
+
+
+@register_jitable
+def random_wald(bitgen, mean, scale):
+ mu_2l = mean / (2 * scale)
+ Y = random_standard_normal(bitgen)
+ Y = mean * Y * Y
+ X = mean + mu_2l * (Y - np.sqrt(4 * scale * Y + Y * Y))
+ U = next_double(bitgen)
+ if (U <= mean / (mean + X)):
+ return X
+ else:
+ return mean * mean / X
+
+
+@register_jitable
+def random_geometric_search(bitgen, p):
+ X = 1
+ sum = prod = p
+ q = 1.0 - p
+ U = next_double(bitgen)
+ while (U > sum):
+ prod *= q
+ sum += prod
+ X = X + 1
+ return X
+
+
+@register_jitable
+def random_geometric_inversion(bitgen, p):
+ return np.ceil(-random_standard_exponential(bitgen) / np.log1p(-p))
+
+
+@register_jitable
+def random_geometric(bitgen, p):
+ if (p >= 0.333333333333333333333333):
+ return random_geometric_search(bitgen, p)
+ else:
+ return random_geometric_inversion(bitgen, p)
+
+
+@register_jitable
+def random_zipf(bitgen, a):
+ am1 = a - 1.0
+ b = pow(2.0, am1)
+ while 1:
+ U = 1.0 - next_double(bitgen)
+ V = next_double(bitgen)
+ X = np.floor(pow(U, -1.0 / am1))
+ if (X > INT64_MAX or X < 1.0):
+ continue
+
+ T = pow(1.0 + 1.0 / X, am1)
+ if (V * X * (T - 1.0) / (b - 1.0) <= T / b):
+ return X
+
+
+@register_jitable
+def random_triangular(bitgen, left, mode,
+ right):
+ base = right - left
+ leftbase = mode - left
+ ratio = leftbase / base
+ leftprod = leftbase * base
+ rightprod = (right - mode) * base
+
+ U = next_double(bitgen)
+ if (U <= ratio):
+ return left + np.sqrt(U * leftprod)
+ else:
+ return right - np.sqrt((1.0 - U) * rightprod)
+
+
+@register_jitable
+def random_loggam(x):
+ a = [8.333333333333333e-02, -2.777777777777778e-03,
+ 7.936507936507937e-04, -5.952380952380952e-04,
+ 8.417508417508418e-04, -1.917526917526918e-03,
+ 6.410256410256410e-03, -2.955065359477124e-02,
+ 1.796443723688307e-01, -1.39243221690590e+00]
+
+ if ((x == 1.0) or (x == 2.0)):
+ return 0.0
+ elif (x < 7.0):
+ n = int(7 - x)
+ else:
+ n = 0
+
+ x0 = x + n
+ x2 = (1.0 / x0) * (1.0 / x0)
+ # /* log(2 * M_PI) */
+ lg2pi = 1.8378770664093453e+00
+ gl0 = a[9]
+
+ for k in range(0, 9):
+ gl0 *= x2
+ gl0 += a[8 - k]
+
+ gl = gl0 / x0 + 0.5 * lg2pi + (x0 - 0.5) * np.log(x0) - x0
+ if (x < 7.0):
+ for k in range(1, n + 1):
+ gl = gl - np.log(x0 - 1.0)
+ x0 = x0 - 1.0
+
+ return gl
+
+
+@register_jitable
+def random_poisson_mult(bitgen, lam):
+ enlam = np.exp(-lam)
+ X = 0
+ prod = 1.0
+ while (1):
+ U = next_double(bitgen)
+ prod *= U
+ if (prod > enlam):
+ X += 1
+ else:
+ return X
+
+
+@register_jitable
+def random_poisson_ptrs(bitgen, lam):
+
+ slam = np.sqrt(lam)
+ loglam = np.log(lam)
+ b = 0.931 + 2.53 * slam
+ a = -0.059 + 0.02483 * b
+ invalpha = 1.1239 + 1.1328 / (b - 3.4)
+ vr = 0.9277 - 3.6224 / (b - 2)
+
+ while (1):
+ U = next_double(bitgen) - 0.5
+ V = next_double(bitgen)
+ us = 0.5 - np.fabs(U)
+ k = int((2 * a / us + b) * U + lam + 0.43)
+ if ((us >= 0.07) and (V <= vr)):
+ return k
+
+ if ((k < 0) or ((us < 0.013) and (V > us))):
+ continue
+
+ # /* log(V) == log(0.0) ok here */
+ # /* if U==0.0 so that us==0.0, log is ok since always returns */
+ if ((np.log(V) + np.log(invalpha) - np.log(a / (us * us) + b)) <=
+ (-lam + k * loglam - random_loggam(k + 1))):
+ return k
+
+
+@register_jitable
+def random_poisson(bitgen, lam):
+ if (lam >= 10):
+ return random_poisson_ptrs(bitgen, lam)
+ elif (lam == 0):
+ return 0
+ else:
+ return random_poisson_mult(bitgen, lam)
+
+
+@register_jitable
+def random_negative_binomial(bitgen, n, p):
+ Y = random_gamma(bitgen, n, (1 - p) / p)
+ return random_poisson(bitgen, Y)
+
+
+@register_jitable
+def random_noncentral_chisquare(bitgen, df, nonc):
+ if np.isnan(nonc):
+ return np.nan
+
+ if nonc == 0:
+ return random_chisquare(bitgen, df)
+
+ if 1 < df:
+ Chi2 = random_chisquare(bitgen, df - 1)
+ n = random_standard_normal(bitgen) + np.sqrt(nonc)
+ return Chi2 + n * n
+ else:
+ i = random_poisson(bitgen, nonc / 2.0)
+ return random_chisquare(bitgen, df + 2 * i)
+
+
+@register_jitable
+def random_noncentral_f(bitgen, dfnum, dfden, nonc):
+ t = random_noncentral_chisquare(bitgen, dfnum, nonc) * dfden
+ return t / (random_chisquare(bitgen, dfden) * dfnum)
+
+
+@register_jitable
+def random_logseries(bitgen, p):
+ r = np_log1p(-p)
+
+ while 1:
+ V = next_double(bitgen)
+ if (V >= p):
+ return 1
+ U = next_double(bitgen)
+ q = -np.expm1(r * U)
+ if (V <= q * q):
+ result = np.int64(np.floor(1 + np.log(V) / np.log(q)))
+ if result < 1 or V == 0.0:
+ continue
+ else:
+ return result
+ if (V >= q):
+ return 1
+ else:
+ return 2
+
+
+@register_jitable
+def random_binomial_btpe(bitgen, n, p):
+ r = min(p, 1.0 - p)
+ q = 1.0 - r
+ fm = n * r + r
+ m = int(np.floor(fm))
+ p1 = int(np.floor(2.195 * np.sqrt(n * r * q) - 4.6 * q) + 0.5)
+ xm = m + 0.5
+ xl = xm - p1
+ xr = xm + p1
+ c = 0.134 + 20.5 / (15.3 + m)
+ a = (fm - xl) / (fm - xl * r)
+ laml = a * (1.0 + a / 2.0)
+ a = (xr - fm) / (xr * q)
+ lamr = a * (1.0 + a / 2.0)
+ p2 = p1 * (1.0 + 2.0 * c)
+ p3 = p2 + c / laml
+ p4 = p3 + c / lamr
+
+ case = 10
+ y = k = 0
+ while 1:
+ if case == 10:
+ nrq = n * r * q
+ u = next_double(bitgen) * p4
+ v = next_double(bitgen)
+ if (u > p1):
+ case = 20
+ continue
+ y = int(np.floor(xm - p1 * v + u))
+ case = 60
+ continue
+ elif case == 20:
+ if (u > p2):
+ case = 30
+ continue
+ x = xl + (u - p1) / c
+ v = v * c + 1.0 - np.fabs(m - x + 0.5) / p1
+ if (v > 1.0):
+ case = 10
+ continue
+ y = int(np.floor(x))
+ case = 50
+ continue
+ elif case == 30:
+ if (u > p3):
+ case = 40
+ continue
+ y = int(np.floor(xl + np.log(v) / laml))
+ if ((y < 0) or (v == 0.0)):
+ case = 10
+ continue
+ v = v * (u - p2) * laml
+ case = 50
+ continue
+ elif case == 40:
+ y = int(np.floor(xr - np.log(v) / lamr))
+ if ((y > n) or (v == 0.0)):
+ case = 10
+ continue
+ v = v * (u - p3) * lamr
+ case = 50
+ continue
+ elif case == 50:
+ k = abs(y - m)
+ if ((k > 20) and (k < ((nrq) / 2.0 - 1))):
+ case = 52
+ continue
+ s = r / q
+ a = s * (n + 1)
+ F = 1.0
+ if (m < y):
+ for i in range(m + 1, y + 1):
+ F = F * (a / i - s)
+ elif (m > y):
+ for i in range(y + 1, m + 1):
+ F = F / (a / i - s)
+ if (v > F):
+ case = 10
+ continue
+ case = 60
+ continue
+ elif case == 52:
+ rho = (k / (nrq)) * \
+ ((k * (k / 3.0 + 0.625) + 0.16666666666666666) /
+ nrq + 0.5)
+ t = -k * k / (2 * nrq)
+ A = np.log(v)
+ if (A < (t - rho)):
+ case = 60
+ continue
+ if (A > (t + rho)):
+ case = 10
+ continue
+ x1 = y + 1
+ f1 = m + 1
+ z = n + 1 - m
+ w = n - y + 1
+ x2 = x1 * x1
+ f2 = f1 * f1
+ z2 = z * z
+ w2 = w * w
+ if (A > (xm * np.log(f1 / x1) + (n - m + 0.5) * np.log(z / w) +
+ (y - m) * np.log(w * r / (x1 * q)) +
+ (13680. - (462. - (132. - (99. - 140. / f2) / f2) / f2)
+ / f2) / f1 / 166320. +
+ (13680. - (462. - (132. - (99. - 140. / z2) / z2) / z2)
+ / z2) / z / 166320. +
+ (13680. - (462. - (132. - (99. - 140. / x2) / x2) / x2)
+ / x2) / x1 / 166320. +
+ (13680. - (462. - (132. - (99. - 140. / w2) / w2) / w2)
+ / w2) / w / 66320.)):
+ case = 10
+ continue
+ elif case == 60:
+ if (p > 0.5):
+ y = n - y
+ return y
+
+
+@register_jitable
+def random_binomial_inversion(bitgen, n, p):
+ q = 1.0 - p
+ qn = np.exp(n * np.log(q))
+ _np = n * p
+ bound = min(n, _np + 10.0 * np.sqrt(_np * q + 1))
+
+ X = 0
+ px = qn
+ U = next_double(bitgen)
+ while (U > px):
+ X = X + 1
+ if (X > bound):
+ X = 0
+ px = qn
+ U = next_double(bitgen)
+ else:
+ U -= px
+ px = ((n - X + 1) * p * px) / (X * q)
+
+ return X
+
+
+@register_jitable
+def random_binomial(bitgen, n, p):
+ if ((n == 0) or (p == 0.0)):
+ return 0
+
+ if (p <= 0.5):
+ if (p * n <= 30.0):
+ return random_binomial_inversion(bitgen, n, p)
+ else:
+ return random_binomial_btpe(bitgen, n, p)
+ else:
+ q = 1.0 - p
+ if (q * n <= 30.0):
+ return n - random_binomial_inversion(bitgen, n, q)
+ else:
+ return n - random_binomial_btpe(bitgen, n, q)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/np/random/new_random_methods.py b/tool_server/.venv/lib/python3.12/site-packages/numba/np/random/new_random_methods.py
new file mode 100644
index 0000000000000000000000000000000000000000..29ddf3a0131707ebd62000871ca5bf11b9430884
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/np/random/new_random_methods.py
@@ -0,0 +1,364 @@
+import numpy as np
+
+from numba.core.extending import register_jitable
+
+from numba.np.random._constants import (UINT32_MAX, UINT64_MAX,
+ UINT16_MAX, UINT8_MAX)
+from numba.np.random.generator_core import next_uint32, next_uint64
+
+# All following implementations are direct translations from:
+# https://github.com/numpy/numpy/blob/7cfef93c77599bd387ecc6a15d186c5a46024dac/numpy/random/src/distributions/distributions.c
+
+
+@register_jitable
+def gen_mask(max):
+ mask = np.uint64(max)
+ mask |= mask >> 1
+ mask |= mask >> 2
+ mask |= mask >> 4
+ mask |= mask >> 8
+ mask |= mask >> 16
+ mask |= mask >> 32
+ return mask
+
+
+@register_jitable
+def buffered_bounded_bool(bitgen, off, rng, bcnt, buf):
+ if (rng == 0):
+ return off, bcnt, buf
+ if not bcnt:
+ buf = next_uint32(bitgen)
+ bcnt = 31
+ else:
+ buf >>= 1
+ bcnt -= 1
+
+ return ((buf & 1) != 0), bcnt, buf
+
+
+@register_jitable
+def buffered_uint8(bitgen, bcnt, buf):
+ if not bcnt:
+ buf = next_uint32(bitgen)
+ bcnt = 3
+ else:
+ buf >>= 8
+ bcnt -= 1
+
+ return np.uint8(buf), bcnt, buf
+
+
+@register_jitable
+def buffered_uint16(bitgen, bcnt, buf):
+ if not bcnt:
+ buf = next_uint32(bitgen)
+ bcnt = 1
+ else:
+ buf >>= 16
+ bcnt -= 1
+
+ return np.uint16(buf), bcnt, buf
+
+
+# The following implementations use Lemire's algorithm:
+# https://arxiv.org/abs/1805.10941
+@register_jitable
+def buffered_bounded_lemire_uint8(bitgen, rng, bcnt, buf):
+ """
+ Generates a random unsigned 8 bit integer bounded
+ within a given interval using Lemire's rejection.
+
+ The buffer acts as storage for a 32 bit integer
+ drawn from the associated BitGenerator so that
+ multiple integers of smaller bitsize can be generated
+ from a single draw of the BitGenerator.
+ """
+ # Note: `rng` should not be 0xFF. When this happens `rng_excl` becomes
+ # zero.
+ rng_excl = np.uint8(rng) + np.uint8(1)
+
+ assert (rng != 0xFF)
+
+ # Generate a scaled random number.
+ n, bcnt, buf = buffered_uint8(bitgen, bcnt, buf)
+ m = np.uint16(n * rng_excl)
+
+ # Rejection sampling to remove any bias
+ leftover = m & 0xFF
+
+ if (leftover < rng_excl):
+ # `rng_excl` is a simple upper bound for `threshold`.
+ threshold = ((np.uint8(UINT8_MAX) - rng) % rng_excl)
+
+ while (leftover < threshold):
+ n, bcnt, buf = buffered_uint8(bitgen, bcnt, buf)
+ m = np.uint16(n * rng_excl)
+ leftover = m & 0xFF
+
+ return m >> 8, bcnt, buf
+
+
+@register_jitable
+def buffered_bounded_lemire_uint16(bitgen, rng, bcnt, buf):
+ """
+ Generates a random unsigned 16 bit integer bounded
+ within a given interval using Lemire's rejection.
+
+ The buffer acts as storage for a 32 bit integer
+ drawn from the associated BitGenerator so that
+ multiple integers of smaller bitsize can be generated
+ from a single draw of the BitGenerator.
+ """
+ # Note: `rng` should not be 0xFFFF. When this happens `rng_excl` becomes
+ # zero.
+ rng_excl = np.uint16(rng) + np.uint16(1)
+
+ assert (rng != 0xFFFF)
+
+ # Generate a scaled random number.
+ n, bcnt, buf = buffered_uint16(bitgen, bcnt, buf)
+ m = np.uint32(n * rng_excl)
+
+ # Rejection sampling to remove any bias
+ leftover = m & 0xFFFF
+
+ if (leftover < rng_excl):
+ # `rng_excl` is a simple upper bound for `threshold`.
+ threshold = ((np.uint16(UINT16_MAX) - rng) % rng_excl)
+
+ while (leftover < threshold):
+ n, bcnt, buf = buffered_uint16(bitgen, bcnt, buf)
+ m = np.uint32(n * rng_excl)
+ leftover = m & 0xFFFF
+
+ return m >> 16, bcnt, buf
+
+
+@register_jitable
+def buffered_bounded_lemire_uint32(bitgen, rng):
+ """
+ Generates a random unsigned 32 bit integer bounded
+ within a given interval using Lemire's rejection.
+ """
+ rng_excl = np.uint32(rng) + np.uint32(1)
+
+ assert (rng != 0xFFFFFFFF)
+
+ # Generate a scaled random number.
+ m = np.uint64(next_uint32(bitgen)) * np.uint64(rng_excl)
+
+ # Rejection sampling to remove any bias
+ leftover = m & 0xFFFFFFFF
+
+ if (leftover < rng_excl):
+ # `rng_excl` is a simple upper bound for `threshold`.
+ threshold = (UINT32_MAX - rng) % rng_excl
+
+ while (leftover < threshold):
+ m = np.uint64(next_uint32(bitgen)) * np.uint64(rng_excl)
+ leftover = m & 0xFFFFFFFF
+
+ return (m >> 32)
+
+
+@register_jitable
+def bounded_lemire_uint64(bitgen, rng):
+ """
+ Generates a random unsigned 64 bit integer bounded
+ within a given interval using Lemire's rejection.
+ """
+ rng_excl = np.uint64(rng) + np.uint64(1)
+
+ assert (rng != 0xFFFFFFFFFFFFFFFF)
+
+ x = next_uint64(bitgen)
+
+ leftover = np.uint64(x) * np.uint64(rng_excl)
+
+ if (leftover < rng_excl):
+ threshold = (UINT64_MAX - rng) % rng_excl
+
+ while (leftover < threshold):
+ x = next_uint64(bitgen)
+ leftover = np.uint64(x) * np.uint64(rng_excl)
+
+ x0 = x & np.uint64(0xFFFFFFFF)
+ x1 = x >> 32
+ rng_excl0 = rng_excl & np.uint64(0xFFFFFFFF)
+ rng_excl1 = rng_excl >> 32
+ w0 = x0 * rng_excl0
+ t = x1 * rng_excl0 + (w0 >> 32)
+ w1 = t & np.uint64(0xFFFFFFFF)
+ w2 = t >> 32
+ w1 += x0 * rng_excl1
+ m1 = x1 * rng_excl1 + w2 + (w1 >> 32)
+
+ return m1
+
+
+@register_jitable
+def random_bounded_uint64_fill(bitgen, low, rng, size, dtype):
+ """
+ Returns a new array of given size with 64 bit integers
+ bounded by given interval.
+ """
+ out = np.empty(size, dtype=dtype)
+ if rng == 0:
+ for i in np.ndindex(size):
+ out[i] = low
+ elif rng <= 0xFFFFFFFF:
+ if (rng == 0xFFFFFFFF):
+ for i in np.ndindex(size):
+ out[i] = low + next_uint32(bitgen)
+ else:
+ for i in np.ndindex(size):
+ out[i] = low + buffered_bounded_lemire_uint32(bitgen, rng)
+
+ elif (rng == 0xFFFFFFFFFFFFFFFF):
+ for i in np.ndindex(size):
+ out[i] = low + next_uint64(bitgen)
+ else:
+ for i in np.ndindex(size):
+ out[i] = low + bounded_lemire_uint64(bitgen, rng)
+
+ return out
+
+
+@register_jitable
+def random_bounded_uint32_fill(bitgen, low, rng, size, dtype):
+ """
+ Returns a new array of given size with 32 bit integers
+ bounded by given interval.
+ """
+ out = np.empty(size, dtype=dtype)
+ if rng == 0:
+ for i in np.ndindex(size):
+ out[i] = low
+ elif rng == 0xFFFFFFFF:
+ # Lemire32 doesn't support rng = 0xFFFFFFFF.
+ for i in np.ndindex(size):
+ out[i] = low + next_uint32(bitgen)
+ else:
+ for i in np.ndindex(size):
+ out[i] = low + buffered_bounded_lemire_uint32(bitgen, rng)
+ return out
+
+
+@register_jitable
+def random_bounded_uint16_fill(bitgen, low, rng, size, dtype):
+ """
+ Returns a new array of given size with 16 bit integers
+ bounded by given interval.
+ """
+ buf = 0
+ bcnt = 0
+
+ out = np.empty(size, dtype=dtype)
+ if rng == 0:
+ for i in np.ndindex(size):
+ out[i] = low
+ elif rng == 0xFFFF:
+ # Lemire16 doesn't support rng = 0xFFFF.
+ for i in np.ndindex(size):
+ val, bcnt, buf = buffered_uint16(bitgen, bcnt, buf)
+ out[i] = low + val
+
+ else:
+ for i in np.ndindex(size):
+ val, bcnt, buf = \
+ buffered_bounded_lemire_uint16(bitgen, rng,
+ bcnt, buf)
+ out[i] = low + val
+ return out
+
+
+@register_jitable
+def random_bounded_uint8_fill(bitgen, low, rng, size, dtype):
+ """
+ Returns a new array of given size with 8 bit integers
+ bounded by given interval.
+ """
+ buf = 0
+ bcnt = 0
+
+ out = np.empty(size, dtype=dtype)
+ if rng == 0:
+ for i in np.ndindex(size):
+ out[i] = low
+ elif rng == 0xFF:
+ # Lemire8 doesn't support rng = 0xFF.
+ for i in np.ndindex(size):
+ val, bcnt, buf = buffered_uint8(bitgen, bcnt, buf)
+ out[i] = low + val
+ else:
+ for i in np.ndindex(size):
+ val, bcnt, buf = \
+ buffered_bounded_lemire_uint8(bitgen, rng,
+ bcnt, buf)
+ out[i] = low + val
+ return out
+
+
+@register_jitable
+def random_bounded_bool_fill(bitgen, low, rng, size, dtype):
+ """
+ Returns a new array of given size with boolean values.
+ """
+ buf = 0
+ bcnt = 0
+ out = np.empty(size, dtype=dtype)
+ for i in np.ndindex(size):
+ val, bcnt, buf = buffered_bounded_bool(bitgen, low, rng, bcnt, buf)
+ out[i] = low + val
+ return out
+
+
+@register_jitable
+def _randint_arg_check(low, high, endpoint, lower_bound, upper_bound):
+ """
+ Check that low and high are within the bounds
+ for the given datatype.
+ """
+
+ if low < lower_bound:
+ raise ValueError("low is out of bounds")
+
+ # This is being done to avoid high being accidentally
+ # casted to int64/32 while subtracting 1 before
+ # checking bounds, avoids overflow.
+ if high > 0:
+ high = np.uint64(high)
+ if not endpoint:
+ high -= np.uint64(1)
+ upper_bound = np.uint64(upper_bound)
+ if low > 0:
+ low = np.uint64(low)
+ if high > upper_bound:
+ raise ValueError("high is out of bounds")
+ if low > high: # -1 already subtracted, closed interval
+ raise ValueError("low is greater than high in given interval")
+ else:
+ if high > upper_bound:
+ raise ValueError("high is out of bounds")
+ if low > high: # -1 already subtracted, closed interval
+ raise ValueError("low is greater than high in given interval")
+
+
+@register_jitable
+def random_interval(bitgen, max_val):
+ if (max_val == 0):
+ return 0
+
+ max_val = np.uint64(max_val)
+ mask = np.uint64(gen_mask(max_val))
+
+ if (max_val <= 0xffffffff):
+ value = np.uint64(next_uint32(bitgen)) & mask
+ while value > max_val:
+ value = np.uint64(next_uint32(bitgen)) & mask
+ else:
+ value = next_uint64(bitgen) & mask
+ while value > max_val:
+ value = next_uint64(bitgen) & mask
+
+ return np.uint64(value)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/np/random/old_distributions.py b/tool_server/.venv/lib/python3.12/site-packages/numba/np/random/old_distributions.py
new file mode 100644
index 0000000000000000000000000000000000000000..336b1cf0339b2c373b5623b4d3e4b48ede33767a
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/np/random/old_distributions.py
@@ -0,0 +1,740 @@
+"""
+Algorithmic implementations for generating different types
+of random distributions.
+"""
+
+import numpy as np
+
+from numba.core.extending import register_jitable
+from numba.np.random._constants import (wi_double, ki_double,
+ ziggurat_nor_r, fi_double,
+ wi_float, ki_float,
+ ziggurat_nor_inv_r_f,
+ ziggurat_nor_r_f, fi_float,
+ we_double, ke_double,
+ ziggurat_exp_r, fe_double,
+ we_float, ke_float,
+ ziggurat_exp_r_f, fe_float,
+ INT64_MAX, ziggurat_nor_inv_r)
+from numba.np.random.generator_core import (next_double, next_float,
+ next_uint32, next_uint64)
+from numba import float32, int64
+from numba.np.numpy_support import numpy_version
+# All of the following implementations are direct translations from:
+# https://github.com/numpy/numpy/blob/7cfef93c77599bd387ecc6a15d186c5a46024dac/numpy/random/src/distributions/distributions.c
+
+
+@register_jitable
+def np_log1p(x):
+ return np.log1p(x)
+
+
+@register_jitable
+def np_log1pf(x):
+ return np.log1p(float32(x))
+
+
+@register_jitable
+def random_rayleigh(bitgen, mode):
+ return mode * np.sqrt(2.0 * random_standard_exponential(bitgen))
+
+
+@register_jitable
+def np_expm1(x):
+ return np.expm1(x)
+
+
+@register_jitable
+def random_standard_normal(bitgen):
+ while 1:
+ r = next_uint64(bitgen)
+ idx = r & 0xff
+ r >>= 8
+ sign = r & 0x1
+ rabs = (r >> 1) & 0x000fffffffffffff
+ x = rabs * wi_double[idx]
+ if (sign & 0x1):
+ x = -x
+ if rabs < ki_double[idx]:
+ return x
+ if idx == 0:
+ while 1:
+ xx = -ziggurat_nor_inv_r * np.log1p(-next_double(bitgen))
+ yy = -np.log1p(-next_double(bitgen))
+ if (yy + yy > xx * xx):
+ if ((rabs >> 8) & 0x1):
+ return -(ziggurat_nor_r + xx)
+ else:
+ return ziggurat_nor_r + xx
+ else:
+ if (((fi_double[idx - 1] - fi_double[idx]) *
+ next_double(bitgen) + fi_double[idx]) <
+ np.exp(-0.5 * x * x)):
+ return x
+
+
+@register_jitable
+def random_standard_normal_f(bitgen):
+ while 1:
+ r = next_uint32(bitgen)
+ idx = r & 0xff
+ sign = (r >> 8) & 0x1
+ rabs = (r >> 9) & 0x0007fffff
+ x = float32(float32(rabs) * wi_float[idx])
+ if (sign & 0x1):
+ x = -x
+ if (rabs < ki_float[idx]):
+ return x
+ if (idx == 0):
+ while 1:
+ xx = float32(-ziggurat_nor_inv_r_f *
+ np_log1pf(-next_float(bitgen)))
+ yy = float32(-np_log1pf(-next_float(bitgen)))
+ if (float32(yy + yy) > float32(xx * xx)):
+ if ((rabs >> 8) & 0x1):
+ return -float32(ziggurat_nor_r_f + xx)
+ else:
+ return float32(ziggurat_nor_r_f + xx)
+ else:
+ if (((fi_float[idx - 1] - fi_float[idx]) * next_float(bitgen) +
+ fi_float[idx]) < float32(np.exp(-float32(0.5) * x * x))):
+ return x
+
+
+@register_jitable
+def random_standard_exponential(bitgen):
+ while 1:
+ ri = next_uint64(bitgen)
+ ri >>= 3
+ idx = ri & 0xFF
+ ri >>= 8
+ x = ri * we_double[idx]
+ if (ri < ke_double[idx]):
+ return x
+ else:
+ if idx == 0:
+ return ziggurat_exp_r - np_log1p(-next_double(bitgen))
+ elif ((fe_double[idx - 1] - fe_double[idx]) * next_double(bitgen) +
+ fe_double[idx] < np.exp(-x)):
+ return x
+
+
+@register_jitable
+def random_standard_exponential_f(bitgen):
+ while 1:
+ ri = next_uint32(bitgen)
+ ri >>= 1
+ idx = ri & 0xFF
+ ri >>= 8
+ x = float32(float32(ri) * we_float[idx])
+ if (ri < ke_float[idx]):
+ return x
+ else:
+ if (idx == 0):
+ return float32(ziggurat_exp_r_f -
+ float32(np_log1pf(-next_float(bitgen))))
+ elif ((fe_float[idx - 1] - fe_float[idx]) * next_float(bitgen) +
+ fe_float[idx] < float32(np.exp(float32(-x)))):
+ return x
+
+
+@register_jitable
+def random_standard_exponential_inv(bitgen):
+ return -np_log1p(-next_double(bitgen))
+
+
+@register_jitable
+def random_standard_exponential_inv_f(bitgen):
+ return -np.log(float32(1.0) - next_float(bitgen))
+
+
+@register_jitable
+def random_standard_gamma(bitgen, shape):
+ if (shape == 1.0):
+ return random_standard_exponential(bitgen)
+ elif (shape == 0.0):
+ return 0.0
+ elif (shape < 1.0):
+ while 1:
+ U = next_double(bitgen)
+ V = random_standard_exponential(bitgen)
+ if (U <= 1.0 - shape):
+ X = pow(U, 1. / shape)
+ if (X <= V):
+ return X
+ else:
+ Y = -np.log((1 - U) / shape)
+ X = pow(1.0 - shape + shape * Y, 1. / shape)
+ if (X <= (V + Y)):
+ return X
+ else:
+ b = shape - 1. / 3.
+ c = 1. / np.sqrt(9 * b)
+ while 1:
+ while 1:
+ X = random_standard_normal(bitgen)
+ V = 1.0 + c * X
+ if (V > 0.0):
+ break
+
+ V = V * V * V
+ U = next_double(bitgen)
+ if (U < 1.0 - 0.0331 * (X * X) * (X * X)):
+ return (b * V)
+
+ if (np.log(U) < 0.5 * X * X + b * (1. - V + np.log(V))):
+ return (b * V)
+
+
+@register_jitable
+def random_standard_gamma_f(bitgen, shape):
+ f32_one = float32(1.0)
+ shape = float32(shape)
+ if (shape == f32_one):
+ return random_standard_exponential_f(bitgen)
+ elif (shape == float32(0.0)):
+ return float32(0.0)
+ elif (shape < f32_one):
+ while 1:
+ U = next_float(bitgen)
+ V = random_standard_exponential_f(bitgen)
+ if (U <= f32_one - shape):
+ X = float32(pow(U, float32(f32_one / shape)))
+ if (X <= V):
+ return X
+ else:
+ Y = float32(-np.log(float32((f32_one - U) / shape)))
+ X = float32(pow(f32_one - shape + float32(shape * Y),
+ float32(f32_one / shape)))
+ if (X <= (V + Y)):
+ return X
+ else:
+ b = shape - f32_one / float32(3.0)
+ c = float32(f32_one / float32(np.sqrt(float32(9.0) * b)))
+ while 1:
+ while 1:
+ X = float32(random_standard_normal_f(bitgen))
+ V = float32(f32_one + c * X)
+ if (V > float32(0.0)):
+ break
+
+ V = float32(V * V * V)
+ U = next_float(bitgen)
+ if (U < f32_one - float32(0.0331) * (X * X) * (X * X)):
+ return float32(b * V)
+
+ if (np.log(U) < float32(0.5) * X * X + b *
+ (f32_one - V + np.log(V))):
+ return float32(b * V)
+
+
+@register_jitable
+def random_normal(bitgen, loc, scale):
+ scaled_normal = scale * random_standard_normal(bitgen)
+ return loc + scaled_normal
+
+
+@register_jitable
+def random_normal_f(bitgen, loc, scale):
+ scaled_normal = float32(scale * random_standard_normal_f(bitgen))
+ return float32(loc + scaled_normal)
+
+
+@register_jitable
+def random_exponential(bitgen, scale):
+ return scale * random_standard_exponential(bitgen)
+
+
+@register_jitable
+def random_uniform(bitgen, lower, range):
+ scaled_uniform = range * next_double(bitgen)
+ return lower + scaled_uniform
+
+
+@register_jitable
+def random_gamma(bitgen, shape, scale):
+ return scale * random_standard_gamma(bitgen, shape)
+
+
+@register_jitable
+def random_gamma_f(bitgen, shape, scale):
+ return float32(scale * random_standard_gamma_f(bitgen, shape))
+
+
+@register_jitable
+def random_beta(bitgen, a, b):
+ if a <= 1.0 and b <= 1.0:
+ while 1:
+ U = next_double(bitgen)
+ V = next_double(bitgen)
+ X = pow(U, 1.0 / a)
+ Y = pow(V, 1.0 / b)
+ XpY = X + Y
+ if XpY <= 1.0 and XpY > 0.0:
+ if (X + Y > 0):
+ return X / XpY
+ else:
+ logX = np.log(U) / a
+ logY = np.log(V) / b
+ logM = min(logX, logY)
+ logX -= logM
+ logY -= logM
+
+ return np.exp(logX - np.log(np.exp(logX) + np.exp(logY)))
+ else:
+ Ga = random_standard_gamma(bitgen, a)
+ Gb = random_standard_gamma(bitgen, b)
+ return Ga / (Ga + Gb)
+
+
+@register_jitable
+def random_chisquare(bitgen, df):
+ return 2.0 * random_standard_gamma(bitgen, df / 2.0)
+
+
+@register_jitable
+def random_f(bitgen, dfnum, dfden):
+ return ((random_chisquare(bitgen, dfnum) * dfden) /
+ (random_chisquare(bitgen, dfden) * dfnum))
+
+
+@register_jitable
+def random_standard_cauchy(bitgen):
+ return random_standard_normal(bitgen) / random_standard_normal(bitgen)
+
+
+@register_jitable
+def random_pareto(bitgen, a):
+ return np_expm1(random_standard_exponential(bitgen) / a)
+
+
+@register_jitable
+def random_weibull(bitgen, a):
+ if (a == 0.0):
+ return 0.0
+ return pow(random_standard_exponential(bitgen), 1. / a)
+
+
+@register_jitable
+def random_power(bitgen, a):
+ return pow(-np_expm1(-random_standard_exponential(bitgen)), 1. / a)
+
+
+@register_jitable
+def random_laplace(bitgen, loc, scale):
+ U = next_double(bitgen)
+ while U <= 0:
+ U = next_double(bitgen)
+ if (U >= 0.5):
+ U = loc - scale * np.log(2.0 - U - U)
+ elif (U > 0.0):
+ U = loc + scale * np.log(U + U)
+ return U
+
+
+@register_jitable
+def random_logistic(bitgen, loc, scale):
+ U = next_double(bitgen)
+ while U <= 0.0:
+ U = next_double(bitgen)
+ return loc + scale * np.log(U / (1.0 - U))
+
+
+@register_jitable
+def random_lognormal(bitgen, mean, sigma):
+ return np.exp(random_normal(bitgen, mean, sigma))
+
+
+@register_jitable
+def random_standard_t(bitgen, df):
+ num = random_standard_normal(bitgen)
+ denom = random_standard_gamma(bitgen, df / 2)
+ return np.sqrt(df / 2) * num / np.sqrt(denom)
+
+
+@register_jitable
+def random_wald(bitgen, mean, scale):
+ mu_2l = mean / (2 * scale)
+ Y = random_standard_normal(bitgen)
+ Y = mean * Y * Y
+ X = mean + mu_2l * (Y - np.sqrt(4 * scale * Y + Y * Y))
+ U = next_double(bitgen)
+ if (U <= mean / (mean + X)):
+ return X
+ else:
+ return mean * mean / X
+
+
+@register_jitable
+def random_geometric_search(bitgen, p):
+ X = 1
+ sum = prod = p
+ q = 1.0 - p
+ U = next_double(bitgen)
+ while (U > sum):
+ prod *= q
+ sum += prod
+ X = X + 1
+ return X
+
+
+@register_jitable
+def random_geometric_inversion(bitgen, p):
+ return np.ceil(-random_standard_exponential(bitgen) / np.log1p(-p))
+
+
+@register_jitable
+def random_geometric(bitgen, p):
+ if (p >= 0.333333333333333333333333):
+ return random_geometric_search(bitgen, p)
+ else:
+ return random_geometric_inversion(bitgen, p)
+
+
+if numpy_version < (2, 1):
+ @register_jitable
+ def random_zipf(bitgen, a):
+ am1 = a - 1.0
+ b = pow(2.0, am1)
+ while 1:
+ U = 1.0 - next_double(bitgen)
+ V = next_double(bitgen)
+ X = np.floor(pow(U, -1.0 / am1))
+ if (X > INT64_MAX or X < 1.0):
+ continue
+ T = pow(1.0 + 1.0 / X, am1)
+ if (V * X * (T - 1.0) / (b - 1.0) <= T / b):
+ return X
+else:
+ @register_jitable
+ def random_zipf(bitgen, a):
+ am1 = a - 1.0
+ b = pow(2.0, am1)
+ Umin = pow(INT64_MAX, -am1)
+ while 1:
+ U01 = next_double(bitgen)
+ U = U01 * Umin + (1 - U01)
+ V = next_double(bitgen)
+ X = np.floor(pow(U, -1.0 / am1))
+ if (X > INT64_MAX or X < 1.0):
+ continue
+
+ T = pow(1.0 + 1.0 / X, am1)
+ if (V * X * (T - 1.0) / (b - 1.0) <= T / b):
+ return X
+
+
+@register_jitable
+def random_triangular(bitgen, left, mode,
+ right):
+ base = right - left
+ leftbase = mode - left
+ ratio = leftbase / base
+ leftprod = leftbase * base
+ rightprod = (right - mode) * base
+
+ U = next_double(bitgen)
+ if (U <= ratio):
+ return left + np.sqrt(U * leftprod)
+ else:
+ return right - np.sqrt((1.0 - U) * rightprod)
+
+
+@register_jitable
+def random_loggam(x):
+ a = [8.333333333333333e-02, -2.777777777777778e-03,
+ 7.936507936507937e-04, -5.952380952380952e-04,
+ 8.417508417508418e-04, -1.917526917526918e-03,
+ 6.410256410256410e-03, -2.955065359477124e-02,
+ 1.796443723688307e-01, -1.39243221690590e+00]
+
+ if ((x == 1.0) or (x == 2.0)):
+ return 0.0
+ elif (x < 7.0):
+ n = int(7 - x)
+ else:
+ n = 0
+
+ x0 = x + n
+ x2 = (1.0 / x0) * (1.0 / x0)
+ # /* log(2 * M_PI) */
+ lg2pi = 1.8378770664093453e+00
+ gl0 = a[9]
+
+ for k in range(0, 9):
+ gl0 *= x2
+ gl0 += a[8 - k]
+
+ gl = gl0 / x0 + 0.5 * lg2pi + (x0 - 0.5) * np.log(x0) - x0
+ if (x < 7.0):
+ for k in range(1, n + 1):
+ gl = gl - np.log(x0 - 1.0)
+ x0 = x0 - 1.0
+
+ return gl
+
+
+@register_jitable
+def random_poisson_mult(bitgen, lam):
+ enlam = np.exp(-lam)
+ X = 0
+ prod = 1.0
+ while (1):
+ U = next_double(bitgen)
+ prod *= U
+ if (prod > enlam):
+ X += 1
+ else:
+ return X
+
+
+@register_jitable
+def random_poisson_ptrs(bitgen, lam):
+
+ slam = np.sqrt(lam)
+ loglam = np.log(lam)
+ b = 0.931 + 2.53 * slam
+ a = -0.059 + 0.02483 * b
+ invalpha = 1.1239 + 1.1328 / (b - 3.4)
+ vr = 0.9277 - 3.6224 / (b - 2)
+
+ while (1):
+ U = next_double(bitgen) - 0.5
+ V = next_double(bitgen)
+ us = 0.5 - np.fabs(U)
+ k = int((2 * a / us + b) * U + lam + 0.43)
+ if ((us >= 0.07) and (V <= vr)):
+ return k
+
+ if ((k < 0) or ((us < 0.013) and (V > us))):
+ continue
+
+ # /* log(V) == log(0.0) ok here */
+ # /* if U==0.0 so that us==0.0, log is ok since always returns */
+ if ((np.log(V) + np.log(invalpha) - np.log(a / (us * us) + b)) <=
+ (-lam + k * loglam - random_loggam(k + 1))):
+ return k
+
+
+@register_jitable
+def random_poisson(bitgen, lam):
+ if (lam >= 10):
+ return random_poisson_ptrs(bitgen, lam)
+ elif (lam == 0):
+ return 0
+ else:
+ return random_poisson_mult(bitgen, lam)
+
+
+@register_jitable
+def random_negative_binomial(bitgen, n, p):
+ Y = random_gamma(bitgen, n, (1 - p) / p)
+ return random_poisson(bitgen, Y)
+
+
+@register_jitable
+def random_noncentral_chisquare(bitgen, df, nonc):
+ if np.isnan(nonc):
+ return np.nan
+
+ if nonc == 0:
+ return random_chisquare(bitgen, df)
+
+ if 1 < df:
+ Chi2 = random_chisquare(bitgen, df - 1)
+ n = random_standard_normal(bitgen) + np.sqrt(nonc)
+ return Chi2 + n * n
+ else:
+ i = random_poisson(bitgen, nonc / 2.0)
+ return random_chisquare(bitgen, df + 2 * i)
+
+
+@register_jitable
+def random_noncentral_f(bitgen, dfnum, dfden, nonc):
+ t = random_noncentral_chisquare(bitgen, dfnum, nonc) * dfden
+ return t / (random_chisquare(bitgen, dfden) * dfnum)
+
+
+@register_jitable
+def random_logseries(bitgen, p):
+ r = np_log1p(-p)
+
+ while 1:
+ V = next_double(bitgen)
+ if (V >= p):
+ return 1
+ U = next_double(bitgen)
+ q = -np.expm1(r * U)
+ if (V <= q * q):
+ result = int64(np.floor(1 + np.log(V) / np.log(q)))
+ if result < 1 or V == 0.0:
+ continue
+ else:
+ return result
+ if (V >= q):
+ return 1
+ else:
+ return 2
+
+
+@register_jitable
+def random_binomial_btpe(bitgen, n, p):
+ r = min(p, 1.0 - p)
+ q = 1.0 - r
+ fm = n * r + r
+ m = int(np.floor(fm))
+ p1 = np.floor(2.195 * np.sqrt(n * r * q) - 4.6 * q) + 0.5
+ xm = m + 0.5
+ xl = xm - p1
+ xr = xm + p1
+ c = 0.134 + 20.5 / (15.3 + m)
+ a = (fm - xl) / (fm - xl * r)
+ laml = a * (1.0 + a / 2.0)
+ a = (xr - fm) / (xr * q)
+ lamr = a * (1.0 + a / 2.0)
+ p2 = p1 * (1.0 + 2.0 * c)
+ p3 = p2 + c / laml
+ p4 = p3 + c / lamr
+
+ case = 10
+ y = k = 0
+ while 1:
+ if case == 10:
+ nrq = n * r * q
+ u = next_double(bitgen) * p4
+ v = next_double(bitgen)
+ if (u > p1):
+ case = 20
+ continue
+ y = int(np.floor(xm - p1 * v + u))
+ case = 60
+ continue
+ elif case == 20:
+ if (u > p2):
+ case = 30
+ continue
+ x = xl + (u - p1) / c
+ v = v * c + 1.0 - np.fabs(m - x + 0.5) / p1
+ if (v > 1.0):
+ case = 10
+ continue
+ y = int(np.floor(x))
+ case = 50
+ continue
+ elif case == 30:
+ if (u > p3):
+ case = 40
+ continue
+ y = int(np.floor(xl + np.log(v) / laml))
+ if ((y < 0) or (v == 0.0)):
+ case = 10
+ continue
+ v = v * (u - p2) * laml
+ case = 50
+ continue
+ elif case == 40:
+ y = int(np.floor(xr - np.log(v) / lamr))
+ if ((y > n) or (v == 0.0)):
+ case = 10
+ continue
+ v = v * (u - p3) * lamr
+ case = 50
+ continue
+ elif case == 50:
+ k = abs(y - m)
+ if ((k > 20) and (k < ((nrq) / 2.0 - 1))):
+ case = 52
+ continue
+ s = r / q
+ a = s * (n + 1)
+ F = 1.0
+ if (m < y):
+ for i in range(m + 1, y + 1):
+ F = F * (a / i - s)
+ elif (m > y):
+ for i in range(y + 1, m + 1):
+ F = F / (a / i - s)
+ if (v > F):
+ case = 10
+ continue
+ case = 60
+ continue
+ elif case == 52:
+ rho = (k / (nrq)) * \
+ ((k * (k / 3.0 + 0.625) + 0.16666666666666666) /
+ nrq + 0.5)
+ t = -k * k / (2 * nrq)
+ A = np.log(v)
+ if (A < (t - rho)):
+ case = 60
+ continue
+ if (A > (t + rho)):
+ case = 10
+ continue
+ x1 = y + 1
+ f1 = m + 1
+ z = n + 1 - m
+ w = n - y + 1
+ x2 = x1 * x1
+ f2 = f1 * f1
+ z2 = z * z
+ w2 = w * w
+ if (A > (xm * np.log(f1 / x1) + (n - m + 0.5) * np.log(z / w) +
+ (y - m) * np.log(w * r / (x1 * q)) +
+ (13680. - (462. - (132. - (99. - 140. / f2) / f2) / f2)
+ / f2) / f1 / 166320. +
+ (13680. - (462. - (132. - (99. - 140. / z2) / z2) / z2)
+ / z2) / z / 166320. +
+ (13680. - (462. - (132. - (99. - 140. / x2) / x2) / x2)
+ / x2) / x1 / 166320. +
+ (13680. - (462. - (132. - (99. - 140. / w2) / w2) / w2)
+ / w2) / w / 66320.)):
+ case = 10
+ continue
+ case = 60
+ continue
+ elif case == 60:
+ if (p > 0.5):
+ y = n - y
+ return y
+
+
+@register_jitable
+def random_binomial_inversion(bitgen, n, p):
+ q = 1.0 - p
+ qn = np.exp(n * np.log(q))
+ _np = n * p
+ bound = min(n, _np + 10.0 * np.sqrt(_np * q + 1))
+
+ X = 0
+ px = qn
+ U = next_double(bitgen)
+ while (U > px):
+ X = X + 1
+ if (X > bound):
+ X = 0
+ px = qn
+ U = next_double(bitgen)
+ else:
+ U -= px
+ px = ((n - X + 1) * p * px) / (X * q)
+
+ return X
+
+
+@register_jitable
+def random_binomial(bitgen, n, p):
+ if ((n == 0) or (p == 0.0)):
+ return 0
+
+ if (p <= 0.5):
+ if (p * n <= 30.0):
+ return random_binomial_inversion(bitgen, n, p)
+ else:
+ return random_binomial_btpe(bitgen, n, p)
+ else:
+ q = 1.0 - p
+ if (q * n <= 30.0):
+ return n - random_binomial_inversion(bitgen, n, q)
+ else:
+ return n - random_binomial_btpe(bitgen, n, q)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/np/random/old_random_methods.py b/tool_server/.venv/lib/python3.12/site-packages/numba/np/random/old_random_methods.py
new file mode 100644
index 0000000000000000000000000000000000000000..ff9e9729e82e9653541b11e02898f376838b6893
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/np/random/old_random_methods.py
@@ -0,0 +1,365 @@
+import numpy as np
+
+from numba import uint64, uint32, uint16, uint8
+from numba.core.extending import register_jitable
+
+from numba.np.random._constants import (UINT32_MAX, UINT64_MAX,
+ UINT16_MAX, UINT8_MAX)
+from numba.np.random.generator_core import next_uint32, next_uint64
+
+# All following implementations are direct translations from:
+# https://github.com/numpy/numpy/blob/7cfef93c77599bd387ecc6a15d186c5a46024dac/numpy/random/src/distributions/distributions.c
+
+
+@register_jitable
+def gen_mask(max):
+ mask = uint64(max)
+ mask |= mask >> 1
+ mask |= mask >> 2
+ mask |= mask >> 4
+ mask |= mask >> 8
+ mask |= mask >> 16
+ mask |= mask >> 32
+ return mask
+
+
+@register_jitable
+def buffered_bounded_bool(bitgen, off, rng, bcnt, buf):
+ if (rng == 0):
+ return off, bcnt, buf
+ if not bcnt:
+ buf = next_uint32(bitgen)
+ bcnt = 31
+ else:
+ buf >>= 1
+ bcnt -= 1
+
+ return ((buf & 1) != 0), bcnt, buf
+
+
+@register_jitable
+def buffered_uint8(bitgen, bcnt, buf):
+ if not bcnt:
+ buf = next_uint32(bitgen)
+ bcnt = 3
+ else:
+ buf >>= 8
+ bcnt -= 1
+
+ return uint8(buf), bcnt, buf
+
+
+@register_jitable
+def buffered_uint16(bitgen, bcnt, buf):
+ if not bcnt:
+ buf = next_uint32(bitgen)
+ bcnt = 1
+ else:
+ buf >>= 16
+ bcnt -= 1
+
+ return uint16(buf), bcnt, buf
+
+
+# The following implementations use Lemire's algorithm:
+# https://arxiv.org/abs/1805.10941
+@register_jitable
+def buffered_bounded_lemire_uint8(bitgen, rng, bcnt, buf):
+ """
+ Generates a random unsigned 8 bit integer bounded
+ within a given interval using Lemire's rejection.
+
+ The buffer acts as storage for a 32 bit integer
+ drawn from the associated BitGenerator so that
+ multiple integers of smaller bitsize can be generated
+ from a single draw of the BitGenerator.
+ """
+ # Note: `rng` should not be 0xFF. When this happens `rng_excl` becomes
+ # zero.
+ rng_excl = uint8(rng) + uint8(1)
+
+ assert (rng != 0xFF)
+
+ # Generate a scaled random number.
+ n, bcnt, buf = buffered_uint8(bitgen, bcnt, buf)
+ m = uint16(n * rng_excl)
+
+ # Rejection sampling to remove any bias
+ leftover = m & 0xFF
+
+ if (leftover < rng_excl):
+ # `rng_excl` is a simple upper bound for `threshold`.
+ threshold = ((uint8(UINT8_MAX) - rng) % rng_excl)
+
+ while (leftover < threshold):
+ n, bcnt, buf = buffered_uint8(bitgen, bcnt, buf)
+ m = uint16(n * rng_excl)
+ leftover = m & 0xFF
+
+ return m >> 8, bcnt, buf
+
+
+@register_jitable
+def buffered_bounded_lemire_uint16(bitgen, rng, bcnt, buf):
+ """
+ Generates a random unsigned 16 bit integer bounded
+ within a given interval using Lemire's rejection.
+
+ The buffer acts as storage for a 32 bit integer
+ drawn from the associated BitGenerator so that
+ multiple integers of smaller bitsize can be generated
+ from a single draw of the BitGenerator.
+ """
+ # Note: `rng` should not be 0xFFFF. When this happens `rng_excl` becomes
+ # zero.
+ rng_excl = uint16(rng) + uint16(1)
+
+ assert (rng != 0xFFFF)
+
+ # Generate a scaled random number.
+ n, bcnt, buf = buffered_uint16(bitgen, bcnt, buf)
+ m = uint32(n * rng_excl)
+
+ # Rejection sampling to remove any bias
+ leftover = m & 0xFFFF
+
+ if (leftover < rng_excl):
+ # `rng_excl` is a simple upper bound for `threshold`.
+ threshold = ((uint16(UINT16_MAX) - rng) % rng_excl)
+
+ while (leftover < threshold):
+ n, bcnt, buf = buffered_uint16(bitgen, bcnt, buf)
+ m = uint32(n * rng_excl)
+ leftover = m & 0xFFFF
+
+ return m >> 16, bcnt, buf
+
+
+@register_jitable
+def buffered_bounded_lemire_uint32(bitgen, rng):
+ """
+ Generates a random unsigned 32 bit integer bounded
+ within a given interval using Lemire's rejection.
+ """
+ rng_excl = uint32(rng) + uint32(1)
+
+ assert (rng != 0xFFFFFFFF)
+
+ # Generate a scaled random number.
+ m = uint64(next_uint32(bitgen)) * uint64(rng_excl)
+
+ # Rejection sampling to remove any bias
+ leftover = m & 0xFFFFFFFF
+
+ if (leftover < rng_excl):
+ # `rng_excl` is a simple upper bound for `threshold`.
+ threshold = (UINT32_MAX - rng) % rng_excl
+
+ while (leftover < threshold):
+ m = uint64(next_uint32(bitgen)) * uint64(rng_excl)
+ leftover = m & 0xFFFFFFFF
+
+ return (m >> 32)
+
+
+@register_jitable
+def bounded_lemire_uint64(bitgen, rng):
+ """
+ Generates a random unsigned 64 bit integer bounded
+ within a given interval using Lemire's rejection.
+ """
+ rng_excl = uint64(rng) + uint64(1)
+
+ assert (rng != 0xFFFFFFFFFFFFFFFF)
+
+ x = next_uint64(bitgen)
+
+ leftover = uint64(x) * uint64(rng_excl)
+
+ if (leftover < rng_excl):
+ threshold = (UINT64_MAX - rng) % rng_excl
+
+ while (leftover < threshold):
+ x = next_uint64(bitgen)
+ leftover = uint64(x) * uint64(rng_excl)
+
+ x0 = x & uint64(0xFFFFFFFF)
+ x1 = x >> 32
+ rng_excl0 = rng_excl & uint64(0xFFFFFFFF)
+ rng_excl1 = rng_excl >> 32
+ w0 = x0 * rng_excl0
+ t = x1 * rng_excl0 + (w0 >> 32)
+ w1 = t & uint64(0xFFFFFFFF)
+ w2 = t >> 32
+ w1 += x0 * rng_excl1
+ m1 = x1 * rng_excl1 + w2 + (w1 >> 32)
+
+ return m1
+
+
+@register_jitable
+def random_bounded_uint64_fill(bitgen, low, rng, size, dtype):
+ """
+ Returns a new array of given size with 64 bit integers
+ bounded by given interval.
+ """
+ out = np.empty(size, dtype=dtype)
+ if rng == 0:
+ for i in np.ndindex(size):
+ out[i] = low
+ elif rng <= 0xFFFFFFFF:
+ if (rng == 0xFFFFFFFF):
+ for i in np.ndindex(size):
+ out[i] = low + next_uint32(bitgen)
+ else:
+ for i in np.ndindex(size):
+ out[i] = low + buffered_bounded_lemire_uint32(bitgen, rng)
+
+ elif (rng == 0xFFFFFFFFFFFFFFFF):
+ for i in np.ndindex(size):
+ out[i] = low + next_uint64(bitgen)
+ else:
+ for i in np.ndindex(size):
+ out[i] = low + bounded_lemire_uint64(bitgen, rng)
+
+ return out
+
+
+@register_jitable
+def random_bounded_uint32_fill(bitgen, low, rng, size, dtype):
+ """
+ Returns a new array of given size with 32 bit integers
+ bounded by given interval.
+ """
+ out = np.empty(size, dtype=dtype)
+ if rng == 0:
+ for i in np.ndindex(size):
+ out[i] = low
+ elif rng == 0xFFFFFFFF:
+ # Lemire32 doesn't support rng = 0xFFFFFFFF.
+ for i in np.ndindex(size):
+ out[i] = low + next_uint32(bitgen)
+ else:
+ for i in np.ndindex(size):
+ out[i] = low + buffered_bounded_lemire_uint32(bitgen, rng)
+ return out
+
+
+@register_jitable
+def random_bounded_uint16_fill(bitgen, low, rng, size, dtype):
+ """
+ Returns a new array of given size with 16 bit integers
+ bounded by given interval.
+ """
+ buf = 0
+ bcnt = 0
+
+ out = np.empty(size, dtype=dtype)
+ if rng == 0:
+ for i in np.ndindex(size):
+ out[i] = low
+ elif rng == 0xFFFF:
+ # Lemire16 doesn't support rng = 0xFFFF.
+ for i in np.ndindex(size):
+ val, bcnt, buf = buffered_uint16(bitgen, bcnt, buf)
+ out[i] = low + val
+
+ else:
+ for i in np.ndindex(size):
+ val, bcnt, buf = \
+ buffered_bounded_lemire_uint16(bitgen, rng,
+ bcnt, buf)
+ out[i] = low + val
+ return out
+
+
+@register_jitable
+def random_bounded_uint8_fill(bitgen, low, rng, size, dtype):
+ """
+ Returns a new array of given size with 8 bit integers
+ bounded by given interval.
+ """
+ buf = 0
+ bcnt = 0
+
+ out = np.empty(size, dtype=dtype)
+ if rng == 0:
+ for i in np.ndindex(size):
+ out[i] = low
+ elif rng == 0xFF:
+ # Lemire8 doesn't support rng = 0xFF.
+ for i in np.ndindex(size):
+ val, bcnt, buf = buffered_uint8(bitgen, bcnt, buf)
+ out[i] = low + val
+ else:
+ for i in np.ndindex(size):
+ val, bcnt, buf = \
+ buffered_bounded_lemire_uint8(bitgen, rng,
+ bcnt, buf)
+ out[i] = low + val
+ return out
+
+
+@register_jitable
+def random_bounded_bool_fill(bitgen, low, rng, size, dtype):
+ """
+ Returns a new array of given size with boolean values.
+ """
+ buf = 0
+ bcnt = 0
+ out = np.empty(size, dtype=dtype)
+ for i in np.ndindex(size):
+ val, bcnt, buf = buffered_bounded_bool(bitgen, low, rng, bcnt, buf)
+ out[i] = low + val
+ return out
+
+
+@register_jitable
+def _randint_arg_check(low, high, endpoint, lower_bound, upper_bound):
+ """
+ Check that low and high are within the bounds
+ for the given datatype.
+ """
+
+ if low < lower_bound:
+ raise ValueError("low is out of bounds")
+
+ # This is being done to avoid high being accidentally
+ # casted to int64/32 while subtracting 1 before
+ # checking bounds, avoids overflow.
+ if high > 0:
+ high = uint64(high)
+ if not endpoint:
+ high -= uint64(1)
+ upper_bound = uint64(upper_bound)
+ if low > 0:
+ low = uint64(low)
+ if high > upper_bound:
+ raise ValueError("high is out of bounds")
+ if low > high: # -1 already subtracted, closed interval
+ raise ValueError("low is greater than high in given interval")
+ else:
+ if high > upper_bound:
+ raise ValueError("high is out of bounds")
+ if low > high: # -1 already subtracted, closed interval
+ raise ValueError("low is greater than high in given interval")
+
+
+@register_jitable
+def random_interval(bitgen, max_val):
+ if (max_val == 0):
+ return 0
+
+ max_val = uint64(max_val)
+ mask = uint64(gen_mask(max_val))
+
+ if (max_val <= 0xffffffff):
+ value = uint64(next_uint32(bitgen)) & mask
+ while value > max_val:
+ value = uint64(next_uint32(bitgen)) & mask
+ else:
+ value = next_uint64(bitgen) & mask
+ while value > max_val:
+ value = next_uint64(bitgen) & mask
+
+ return uint64(value)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/np/random/random_methods.py b/tool_server/.venv/lib/python3.12/site-packages/numba/np/random/random_methods.py
new file mode 100644
index 0000000000000000000000000000000000000000..608d3c82753fdcf54f70be5b97e0c37b08f72459
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/np/random/random_methods.py
@@ -0,0 +1,12 @@
+import sys
+from numba.core.utils import _RedirectSubpackage
+from numba.core import config
+
+if config.USE_LEGACY_TYPE_SYSTEM:
+ sys.modules[__name__] = \
+ _RedirectSubpackage(locals(),
+ "numba.np.random.old_random_methods")
+else:
+ sys.modules[__name__] = \
+ _RedirectSubpackage(locals(),
+ "numba.np.random.new_random_methods")
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/np/ufunc/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/numba/np/ufunc/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..14383e17fc7b7123b0b836710ebca1495dbb7b89
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/np/ufunc/__init__.py
@@ -0,0 +1,32 @@
+# -*- coding: utf-8 -*-
+
+from numba.np.ufunc.decorators import Vectorize, GUVectorize, vectorize, guvectorize
+from numba.np.ufunc._internal import PyUFunc_None, PyUFunc_Zero, PyUFunc_One
+from numba.np.ufunc import _internal, array_exprs
+from numba.np.ufunc.parallel import (threading_layer, get_num_threads,
+ set_num_threads, get_thread_id,
+ set_parallel_chunksize,
+ get_parallel_chunksize)
+
+
+if hasattr(_internal, 'PyUFunc_ReorderableNone'):
+ PyUFunc_ReorderableNone = _internal.PyUFunc_ReorderableNone
+del _internal, array_exprs
+
+
+def _init():
+
+ def init_cuda_vectorize():
+ from numba.cuda.vectorizers import CUDAVectorize
+ return CUDAVectorize
+
+ def init_cuda_guvectorize():
+ from numba.cuda.vectorizers import CUDAGUFuncVectorize
+ return CUDAGUFuncVectorize
+
+ Vectorize.target_registry.ondemand['cuda'] = init_cuda_vectorize
+ GUVectorize.target_registry.ondemand['cuda'] = init_cuda_guvectorize
+
+
+_init()
+del _init
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/np/ufunc/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/np/ufunc/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a46acb17ec7e17fa5dfbec5fa701df103c7154b2
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/np/ufunc/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/np/ufunc/__pycache__/array_exprs.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/np/ufunc/__pycache__/array_exprs.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d5529fdd37fd558c3a5624aa0f0ebbe3fd2b8ae4
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/np/ufunc/__pycache__/array_exprs.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/np/ufunc/__pycache__/decorators.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/np/ufunc/__pycache__/decorators.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..152a8fa5422b5c9487ec6767f7df3b00a9455940
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/np/ufunc/__pycache__/decorators.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/np/ufunc/__pycache__/dufunc.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/np/ufunc/__pycache__/dufunc.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..10f07cf4f6266e52be27b3b699c692cea4237eb6
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/np/ufunc/__pycache__/dufunc.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/np/ufunc/__pycache__/gufunc.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/np/ufunc/__pycache__/gufunc.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6159bc8fabacfff40d753cd4b91f44e6966639a3
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/np/ufunc/__pycache__/gufunc.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/np/ufunc/__pycache__/parallel.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/np/ufunc/__pycache__/parallel.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4c04c473745c035cf830b98324e15ce259f127a0
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/np/ufunc/__pycache__/parallel.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/np/ufunc/__pycache__/sigparse.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/np/ufunc/__pycache__/sigparse.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..670832cac50046904ca325cc704ca31db2ea6fb5
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/np/ufunc/__pycache__/sigparse.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/np/ufunc/__pycache__/ufunc_base.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/np/ufunc/__pycache__/ufunc_base.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..165d4364a910f2fa6e496174b0a43c68bee06b0c
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/np/ufunc/__pycache__/ufunc_base.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/np/ufunc/__pycache__/ufuncbuilder.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/np/ufunc/__pycache__/ufuncbuilder.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..98f60fb90eb11cae015359793192895ce6ebd62e
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/np/ufunc/__pycache__/ufuncbuilder.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/np/ufunc/__pycache__/wrappers.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/np/ufunc/__pycache__/wrappers.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9c2917406164ab80a67bc2fc49793afc9b21bfb8
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/np/ufunc/__pycache__/wrappers.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/np/ufunc/_internal.cpython-312-x86_64-linux-gnu.so b/tool_server/.venv/lib/python3.12/site-packages/numba/np/ufunc/_internal.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..8e0574955beb1188a985d77eaf03d31632ad6026
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/np/ufunc/_internal.cpython-312-x86_64-linux-gnu.so
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:4efd561e4f30daa12f23234ee46a71dc8077d56596c95a85ce16beefc186f9f6
+size 100832
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/np/ufunc/_num_threads.cpython-312-x86_64-linux-gnu.so b/tool_server/.venv/lib/python3.12/site-packages/numba/np/ufunc/_num_threads.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..7a0ee92e2412c0ff37db4dc7b91d568d0d40b083
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/np/ufunc/_num_threads.cpython-312-x86_64-linux-gnu.so differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/np/ufunc/array_exprs.py b/tool_server/.venv/lib/python3.12/site-packages/numba/np/ufunc/array_exprs.py
new file mode 100644
index 0000000000000000000000000000000000000000..91fceaacf40fa67c17c790e6f7fb27c428bcef13
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/np/ufunc/array_exprs.py
@@ -0,0 +1,428 @@
+import ast
+from collections import defaultdict, OrderedDict
+import contextlib
+import sys
+from types import SimpleNamespace
+
+import numpy as np
+import operator
+
+from numba.core import types, targetconfig, ir, rewrites, compiler
+from numba.core.typing import npydecl
+from numba.np.ufunc.dufunc import DUFunc
+
+
+def _is_ufunc(func):
+ return isinstance(func, (np.ufunc, DUFunc))
+
+
+@rewrites.register_rewrite('after-inference')
+class RewriteArrayExprs(rewrites.Rewrite):
+ '''The RewriteArrayExprs class is responsible for finding array
+ expressions in Numba intermediate representation code, and
+ rewriting those expressions to a single operation that will expand
+ into something similar to a ufunc call.
+ '''
+ def __init__(self, state, *args, **kws):
+ super(RewriteArrayExprs, self).__init__(state, *args, **kws)
+ # Install a lowering hook if we are using this rewrite.
+ special_ops = state.targetctx.special_ops
+ if 'arrayexpr' not in special_ops:
+ special_ops['arrayexpr'] = _lower_array_expr
+
+ def match(self, func_ir, block, typemap, calltypes):
+ """
+ Using typing and a basic block, search the basic block for array
+ expressions.
+ Return True when one or more matches were found, False otherwise.
+ """
+ # We can trivially reject everything if there are no
+ # calls in the type results.
+ if len(calltypes) == 0:
+ return False
+
+ self.crnt_block = block
+ self.typemap = typemap
+ # { variable name: IR assignment (of a function call or operator) }
+ self.array_assigns = OrderedDict()
+ # { variable name: IR assignment (of a constant) }
+ self.const_assigns = {}
+
+ assignments = block.find_insts(ir.Assign)
+ for instr in assignments:
+ target_name = instr.target.name
+ expr = instr.value
+ # Does it assign an expression to an array variable?
+ if (isinstance(expr, ir.Expr) and
+ isinstance(typemap.get(target_name, None), types.Array)):
+ self._match_array_expr(instr, expr, target_name)
+ elif isinstance(expr, ir.Const):
+ # Track constants since we might need them for an
+ # array expression.
+ self.const_assigns[target_name] = expr
+
+ return len(self.array_assigns) > 0
+
+ def _match_array_expr(self, instr, expr, target_name):
+ """
+ Find whether the given assignment (*instr*) of an expression (*expr*)
+ to variable *target_name* is an array expression.
+ """
+ # We've matched a subexpression assignment to an
+ # array variable. Now see if the expression is an
+ # array expression.
+ expr_op = expr.op
+ array_assigns = self.array_assigns
+
+ if ((expr_op in ('unary', 'binop')) and (
+ expr.fn in npydecl.supported_array_operators)):
+ # It is an array operator that maps to a ufunc.
+ # check that all args have internal types
+ if all(self.typemap[var.name].is_internal
+ for var in expr.list_vars()):
+ array_assigns[target_name] = instr
+
+ elif ((expr_op == 'call') and (expr.func.name in self.typemap)):
+ # It could be a match for a known ufunc call.
+ func_type = self.typemap[expr.func.name]
+ if isinstance(func_type, types.Function):
+ func_key = func_type.typing_key
+ if _is_ufunc(func_key):
+ # If so, check whether an explicit output is passed.
+ if not self._has_explicit_output(expr, func_key):
+ # If not, match it as a (sub)expression.
+ array_assigns[target_name] = instr
+
+ def _has_explicit_output(self, expr, func):
+ """
+ Return whether the *expr* call to *func* (a ufunc) features an
+ explicit output argument.
+ """
+ nargs = len(expr.args) + len(expr.kws)
+ if expr.vararg is not None:
+ # XXX *args unsupported here, assume there may be an explicit
+ # output
+ return True
+ return nargs > func.nin
+
+ def _get_array_operator(self, ir_expr):
+ ir_op = ir_expr.op
+ if ir_op in ('unary', 'binop'):
+ return ir_expr.fn
+ elif ir_op == 'call':
+ return self.typemap[ir_expr.func.name].typing_key
+ raise NotImplementedError(
+ "Don't know how to find the operator for '{0}' expressions.".format(
+ ir_op))
+
+ def _get_operands(self, ir_expr):
+ '''Given a Numba IR expression, return the operands to the expression
+ in order they appear in the expression.
+ '''
+ ir_op = ir_expr.op
+ if ir_op == 'binop':
+ return ir_expr.lhs, ir_expr.rhs
+ elif ir_op == 'unary':
+ return ir_expr.list_vars()
+ elif ir_op == 'call':
+ return ir_expr.args
+ raise NotImplementedError(
+ "Don't know how to find the operands for '{0}' expressions.".format(
+ ir_op))
+
+ def _translate_expr(self, ir_expr):
+ '''Translate the given expression from Numba IR to an array expression
+ tree.
+ '''
+ ir_op = ir_expr.op
+ if ir_op == 'arrayexpr':
+ return ir_expr.expr
+ operands_or_args = [self.const_assigns.get(op_var.name, op_var)
+ for op_var in self._get_operands(ir_expr)]
+ return self._get_array_operator(ir_expr), operands_or_args
+
+ def _handle_matches(self):
+ '''Iterate over the matches, trying to find which instructions should
+ be rewritten, deleted, or moved.
+ '''
+ replace_map = {}
+ dead_vars = set()
+ used_vars = defaultdict(int)
+ for instr in self.array_assigns.values():
+ expr = instr.value
+ arr_inps = []
+ arr_expr = self._get_array_operator(expr), arr_inps
+ new_expr = ir.Expr(op='arrayexpr',
+ loc=expr.loc,
+ expr=arr_expr,
+ ty=self.typemap[instr.target.name])
+ new_instr = ir.Assign(new_expr, instr.target, instr.loc)
+ replace_map[instr] = new_instr
+ self.array_assigns[instr.target.name] = new_instr
+ for operand in self._get_operands(expr):
+ operand_name = operand.name
+ if operand.is_temp and operand_name in self.array_assigns:
+ child_assign = self.array_assigns[operand_name]
+ child_expr = child_assign.value
+ child_operands = child_expr.list_vars()
+ for operand in child_operands:
+ used_vars[operand.name] += 1
+ arr_inps.append(self._translate_expr(child_expr))
+ if child_assign.target.is_temp:
+ dead_vars.add(child_assign.target.name)
+ replace_map[child_assign] = None
+ elif operand_name in self.const_assigns:
+ arr_inps.append(self.const_assigns[operand_name])
+ else:
+ used_vars[operand.name] += 1
+ arr_inps.append(operand)
+ return replace_map, dead_vars, used_vars
+
+ def _get_final_replacement(self, replacement_map, instr):
+ '''Find the final replacement instruction for a given initial
+ instruction by chasing instructions in a map from instructions
+ to replacement instructions.
+ '''
+ replacement = replacement_map[instr]
+ while replacement in replacement_map:
+ replacement = replacement_map[replacement]
+ return replacement
+
+ def apply(self):
+ '''When we've found array expressions in a basic block, rewrite that
+ block, returning a new, transformed block.
+ '''
+ # Part 1: Figure out what instructions should be rewritten
+ # based on the matches found.
+ replace_map, dead_vars, used_vars = self._handle_matches()
+ # Part 2: Using the information above, rewrite the target
+ # basic block.
+ result = self.crnt_block.copy()
+ result.clear()
+ delete_map = {}
+ for instr in self.crnt_block.body:
+ if isinstance(instr, ir.Assign):
+ if instr in replace_map:
+ replacement = self._get_final_replacement(
+ replace_map, instr)
+ if replacement:
+ result.append(replacement)
+ for var in replacement.value.list_vars():
+ var_name = var.name
+ if var_name in delete_map:
+ result.append(delete_map.pop(var_name))
+ if used_vars[var_name] > 0:
+ used_vars[var_name] -= 1
+
+ else:
+ result.append(instr)
+ elif isinstance(instr, ir.Del):
+ instr_value = instr.value
+ if used_vars[instr_value] > 0:
+ used_vars[instr_value] -= 1
+ delete_map[instr_value] = instr
+ elif instr_value not in dead_vars:
+ result.append(instr)
+ else:
+ result.append(instr)
+ if delete_map:
+ for instr in delete_map.values():
+ result.insert_before_terminator(instr)
+ return result
+
+
+_unaryops = {
+ operator.pos: ast.UAdd,
+ operator.neg: ast.USub,
+ operator.invert: ast.Invert,
+}
+
+_binops = {
+ operator.add: ast.Add,
+ operator.sub: ast.Sub,
+ operator.mul: ast.Mult,
+ operator.truediv: ast.Div,
+ operator.mod: ast.Mod,
+ operator.or_: ast.BitOr,
+ operator.rshift: ast.RShift,
+ operator.xor: ast.BitXor,
+ operator.lshift: ast.LShift,
+ operator.and_: ast.BitAnd,
+ operator.pow: ast.Pow,
+ operator.floordiv: ast.FloorDiv,
+}
+
+
+_cmpops = {
+ operator.eq: ast.Eq,
+ operator.ne: ast.NotEq,
+ operator.lt: ast.Lt,
+ operator.le: ast.LtE,
+ operator.gt: ast.Gt,
+ operator.ge: ast.GtE,
+}
+
+
+def _arr_expr_to_ast(expr):
+ '''Build a Python expression AST from an array expression built by
+ RewriteArrayExprs.
+ '''
+ if isinstance(expr, tuple):
+ op, arr_expr_args = expr
+ ast_args = []
+ env = {}
+ for arg in arr_expr_args:
+ ast_arg, child_env = _arr_expr_to_ast(arg)
+ ast_args.append(ast_arg)
+ env.update(child_env)
+ if op in npydecl.supported_array_operators:
+ if len(ast_args) == 2:
+ if op in _binops:
+ return ast.BinOp(
+ ast_args[0], _binops[op](), ast_args[1]), env
+ if op in _cmpops:
+ return ast.Compare(
+ ast_args[0], [_cmpops[op]()], [ast_args[1]]), env
+ else:
+ assert op in _unaryops
+ return ast.UnaryOp(_unaryops[op](), ast_args[0]), env
+ elif _is_ufunc(op):
+ fn_name = "__ufunc_or_dufunc_{0}".format(
+ hex(hash(op)).replace("-", "_"))
+ fn_ast_name = ast.Name(fn_name, ast.Load())
+ env[fn_name] = op # Stash the ufunc or DUFunc in the environment
+ ast_call = ast.Call(fn_ast_name, ast_args, [])
+ return ast_call, env
+ elif isinstance(expr, ir.Var):
+ return ast.Name(expr.name, ast.Load(),
+ lineno=expr.loc.line,
+ col_offset=expr.loc.col if expr.loc.col else 0), {}
+ elif isinstance(expr, ir.Const):
+ return ast.Constant(expr.value), {}
+ raise NotImplementedError(
+ "Don't know how to translate array expression '%r'" % (expr,))
+
+
+@contextlib.contextmanager
+def _legalize_parameter_names(var_list):
+ """
+ Legalize names in the variable list for use as a Python function's
+ parameter names.
+ """
+ var_map = OrderedDict()
+ for var in var_list:
+ old_name = var.name
+ new_name = var.scope.redefine(old_name, loc=var.loc).name
+ new_name = new_name.replace("$", "_").replace(".", "_")
+ # Caller should ensure the names are unique
+ if new_name in var_map:
+ raise AssertionError(f"{new_name!r} not unique")
+ var_map[new_name] = var, old_name
+ var.name = new_name
+ param_names = list(var_map)
+ try:
+ yield param_names
+ finally:
+ # Make sure the old names are restored, to avoid confusing
+ # other parts of Numba (see issue #1466)
+ for var, old_name in var_map.values():
+ var.name = old_name
+
+
+class _EraseInvalidLineRanges(ast.NodeTransformer):
+ def generic_visit(self, node: ast.AST) -> ast.AST:
+ node = super().generic_visit(node)
+ if hasattr(node, "lineno"):
+ if getattr(node, "end_lineno", None) is not None:
+ if node.lineno > node.end_lineno:
+ del node.lineno
+ del node.end_lineno
+ return node
+
+
+def _fix_invalid_lineno_ranges(astree: ast.AST):
+ """Inplace fixes invalid lineno ranges.
+ """
+ # Make sure lineno and end_lineno are present
+ ast.fix_missing_locations(astree)
+ # Delete invalid lineno ranges
+ _EraseInvalidLineRanges().visit(astree)
+ # Make sure lineno and end_lineno are present
+ ast.fix_missing_locations(astree)
+
+
+def _lower_array_expr(lowerer, expr):
+ '''Lower an array expression built by RewriteArrayExprs.
+ '''
+ expr_name = "__numba_array_expr_%s" % (hex(hash(expr)).replace("-", "_"))
+ expr_filename = expr.loc.filename
+ expr_var_list = expr.list_vars()
+ # The expression may use a given variable several times, but we
+ # should only create one parameter for it.
+ expr_var_unique = sorted(set(expr_var_list), key=lambda var: var.name)
+
+ # Arguments are the names external to the new closure
+ expr_args = [var.name for var in expr_var_unique]
+
+ # 1. Create an AST tree from the array expression.
+ with _legalize_parameter_names(expr_var_unique) as expr_params:
+ ast_args = [ast.arg(param_name, None)
+ for param_name in expr_params]
+ # Parse a stub function to ensure the AST is populated with
+ # reasonable defaults for the Python version.
+ ast_module = ast.parse('def {0}(): return'.format(expr_name),
+ expr_filename, 'exec')
+ assert hasattr(ast_module, 'body') and len(ast_module.body) == 1
+ ast_fn = ast_module.body[0]
+ ast_fn.args.args = ast_args
+ ast_fn.body[0].value, namespace = _arr_expr_to_ast(expr.expr)
+ _fix_invalid_lineno_ranges(ast_module)
+
+ # 2. Compile the AST module and extract the Python function.
+ code_obj = compile(ast_module, expr_filename, 'exec')
+ exec(code_obj, namespace)
+ impl = namespace[expr_name]
+
+ # 3. Now compile a ufunc using the Python function as kernel.
+
+ context = lowerer.context
+ builder = lowerer.builder
+ outer_sig = expr.ty(*(lowerer.typeof(name) for name in expr_args))
+ inner_sig_args = []
+ for argty in outer_sig.args:
+ if isinstance(argty, types.Optional):
+ argty = argty.type
+ if isinstance(argty, types.Array):
+ inner_sig_args.append(argty.dtype)
+ else:
+ inner_sig_args.append(argty)
+ inner_sig = outer_sig.return_type.dtype(*inner_sig_args)
+
+ flags = targetconfig.ConfigStack().top_or_none()
+ flags = compiler.Flags() if flags is None else flags.copy() # make sure it's a clone or a fresh instance
+ # Follow the Numpy error model. Note this also allows e.g. vectorizing
+ # division (issue #1223).
+ flags.error_model = 'numpy'
+ cres = context.compile_subroutine(builder, impl, inner_sig, flags=flags,
+ caching=False)
+
+ # Create kernel subclass calling our native function
+ from numba.np import npyimpl
+
+ class ExprKernel(npyimpl._Kernel):
+ def generate(self, *args):
+ arg_zip = zip(args, self.outer_sig.args, inner_sig.args)
+ cast_args = [self.cast(val, inty, outty)
+ for val, inty, outty in arg_zip]
+ result = self.context.call_internal(
+ builder, cres.fndesc, inner_sig, cast_args)
+ return self.cast(result, inner_sig.return_type,
+ self.outer_sig.return_type)
+
+ # create a fake ufunc object which is enough to trick numpy_ufunc_kernel
+ ufunc = SimpleNamespace(nin=len(expr_args), nout=1, __name__=expr_name)
+ ufunc.nargs = ufunc.nin + ufunc.nout
+
+ args = [lowerer.loadvar(name) for name in expr_args]
+ return npyimpl.numpy_ufunc_kernel(
+ context, builder, outer_sig, args, ufunc, ExprKernel)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/np/ufunc/decorators.py b/tool_server/.venv/lib/python3.12/site-packages/numba/np/ufunc/decorators.py
new file mode 100644
index 0000000000000000000000000000000000000000..bbbcff9d27c566a803924d3346ac9b66015af24e
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/np/ufunc/decorators.py
@@ -0,0 +1,208 @@
+import inspect
+
+from numba.np.ufunc import _internal
+from numba.np.ufunc.parallel import ParallelUFuncBuilder, ParallelGUFuncBuilder
+
+from numba.core.registry import DelayedRegistry
+from numba.np.ufunc import dufunc
+from numba.np.ufunc import gufunc
+
+
+class _BaseVectorize(object):
+
+ @classmethod
+ def get_identity(cls, kwargs):
+ return kwargs.pop('identity', None)
+
+ @classmethod
+ def get_cache(cls, kwargs):
+ return kwargs.pop('cache', False)
+
+ @classmethod
+ def get_writable_args(cls, kwargs):
+ return kwargs.pop('writable_args', ())
+
+ @classmethod
+ def get_target_implementation(cls, kwargs):
+ target = kwargs.pop('target', 'cpu')
+ try:
+ return cls.target_registry[target]
+ except KeyError:
+ raise ValueError("Unsupported target: %s" % target)
+
+
+class Vectorize(_BaseVectorize):
+ target_registry = DelayedRegistry({'cpu': dufunc.DUFunc,
+ 'parallel': ParallelUFuncBuilder,})
+
+ def __new__(cls, func, **kws):
+ identity = cls.get_identity(kws)
+ cache = cls.get_cache(kws)
+ imp = cls.get_target_implementation(kws)
+ return imp(func, identity=identity, cache=cache, targetoptions=kws)
+
+
+class GUVectorize(_BaseVectorize):
+ target_registry = DelayedRegistry({'cpu': gufunc.GUFunc,
+ 'parallel': ParallelGUFuncBuilder,})
+
+ def __new__(cls, func, signature, **kws):
+ identity = cls.get_identity(kws)
+ cache = cls.get_cache(kws)
+ imp = cls.get_target_implementation(kws)
+ writable_args = cls.get_writable_args(kws)
+ if imp is gufunc.GUFunc:
+ is_dyn = kws.pop('is_dynamic', False)
+ return imp(func, signature, identity=identity, cache=cache,
+ is_dynamic=is_dyn, targetoptions=kws,
+ writable_args=writable_args)
+ else:
+ return imp(func, signature, identity=identity, cache=cache,
+ targetoptions=kws, writable_args=writable_args)
+
+
+def vectorize(ftylist_or_function=(), **kws):
+ """vectorize(ftylist_or_function=(), target='cpu', identity=None, **kws)
+
+ A decorator that creates a NumPy ufunc object using Numba compiled
+ code. When no arguments or only keyword arguments are given,
+ vectorize will return a Numba dynamic ufunc (DUFunc) object, where
+ compilation/specialization may occur at call-time.
+
+ Args
+ -----
+ ftylist_or_function: function or iterable
+
+ When the first argument is a function, signatures are dealt
+ with at call-time.
+
+ When the first argument is an iterable of type signatures,
+ which are either function type object or a string describing
+ the function type, signatures are finalized at decoration
+ time.
+
+ Keyword Args
+ ------------
+
+ target: str
+ A string for code generation target. Default to "cpu".
+
+ identity: int, str, or None
+ The identity (or unit) value for the element-wise function
+ being implemented. Allowed values are None (the default), 0, 1,
+ and "reorderable".
+
+ cache: bool
+ Turns on caching.
+
+
+ Returns
+ --------
+
+ A NumPy universal function
+
+ Examples
+ -------
+ @vectorize(['float32(float32, float32)',
+ 'float64(float64, float64)'], identity=0)
+ def sum(a, b):
+ return a + b
+
+ @vectorize
+ def sum(a, b):
+ return a + b
+
+ @vectorize(identity=1)
+ def mul(a, b):
+ return a * b
+
+ """
+ if isinstance(ftylist_or_function, str):
+ # Common user mistake
+ ftylist = [ftylist_or_function]
+ elif inspect.isfunction(ftylist_or_function):
+ return dufunc.DUFunc(ftylist_or_function, **kws)
+ elif ftylist_or_function is not None:
+ ftylist = ftylist_or_function
+
+ def wrap(func):
+ vec = Vectorize(func, **kws)
+ for sig in ftylist:
+ vec.add(sig)
+ if len(ftylist) > 0:
+ vec.disable_compile()
+ return vec.build_ufunc()
+
+ return wrap
+
+
+def guvectorize(*args, **kwargs):
+ """guvectorize(ftylist, signature, target='cpu', identity=None, **kws)
+
+ A decorator to create NumPy generalized-ufunc object from Numba compiled
+ code.
+
+ Args
+ -----
+ ftylist: iterable
+ An iterable of type signatures, which are either
+ function type object or a string describing the
+ function type.
+
+ signature: str
+ A NumPy generalized-ufunc signature.
+ e.g. "(m, n), (n, p)->(m, p)"
+
+ identity: int, str, or None
+ The identity (or unit) value for the element-wise function
+ being implemented. Allowed values are None (the default), 0, 1,
+ and "reorderable".
+
+ cache: bool
+ Turns on caching.
+
+ writable_args: tuple
+ a tuple of indices of input variables that are writable.
+
+ target: str
+ A string for code generation target. Defaults to "cpu".
+
+ Returns
+ --------
+
+ A NumPy generalized universal-function
+
+ Example
+ -------
+ @guvectorize(['void(int32[:,:], int32[:,:], int32[:,:])',
+ 'void(float32[:,:], float32[:,:], float32[:,:])'],
+ '(x, y),(x, y)->(x, y)')
+ def add_2d_array(a, b, c):
+ for i in range(c.shape[0]):
+ for j in range(c.shape[1]):
+ c[i, j] = a[i, j] + b[i, j]
+
+ """
+ if len(args) == 1:
+ ftylist = []
+ signature = args[0]
+ kwargs.setdefault('is_dynamic', True)
+ elif len(args) == 2:
+ ftylist = args[0]
+ signature = args[1]
+ else:
+ raise TypeError('guvectorize() takes one or two positional arguments')
+
+ if isinstance(ftylist, str):
+ # Common user mistake
+ ftylist = [ftylist]
+
+ def wrap(func):
+ guvec = GUVectorize(func, signature, **kwargs)
+ for fty in ftylist:
+ guvec.add(fty)
+ if len(ftylist) > 0:
+ guvec.disable_compile()
+ return guvec.build_ufunc()
+
+ return wrap
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/np/ufunc/dufunc.py b/tool_server/.venv/lib/python3.12/site-packages/numba/np/ufunc/dufunc.py
new file mode 100644
index 0000000000000000000000000000000000000000..280dd1d1ccf67b10964cea278690549b76a96246
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/np/ufunc/dufunc.py
@@ -0,0 +1,879 @@
+import functools
+import operator
+import warnings
+
+import numpy as np
+
+from numba import jit, typeof
+from numba.core import cgutils, types, serialize, sigutils, errors
+from numba.core.extending import (is_jitted, overload_attribute,
+ overload_method, register_jitable,
+ intrinsic)
+from numba.core.typing import npydecl
+from numba.core.typing.templates import AbstractTemplate, signature
+from numba.cpython.unsafe.tuple import tuple_setitem
+from numba.np.ufunc import _internal
+from numba.np.ufunc.ufunc_base import UfuncBase, UfuncLowererBase
+from numba.parfors import array_analysis
+from numba.np.ufunc import ufuncbuilder
+from numba.np import numpy_support
+from typing import Callable
+from llvmlite import ir
+from numba.core.compiler_lock import global_compiler_lock
+
+
+class UfuncAtIterator:
+
+ def __init__(self, ufunc, a, a_ty, indices, indices_ty, b=None, b_ty=None):
+ self.ufunc = ufunc
+ self.a = a
+ self.a_ty = a_ty
+ self.indices = indices
+ self.indices_ty = indices_ty
+ self.b = b
+ self.b_ty = b_ty
+
+ def run(self, context, builder):
+ self._prepare(context, builder)
+ loop_indices, _ = self.indexer.begin_loops()
+ self._call_ufunc(context, builder, loop_indices)
+ self.indexer.end_loops()
+
+ def need_advanced_indexing(self):
+ return isinstance(self.indices_ty, types.BaseTuple)
+
+ def _prepare(self, context, builder):
+ from numba.np.arrayobj import normalize_indices, FancyIndexer
+
+ a, indices = self.a, self.indices
+ a_ty, indices_ty = self.a_ty, self.indices_ty
+
+ zero = context.get_value_type(types.intp)(0)
+
+ if self.b is not None:
+ self.b_indice = cgutils.alloca_once_value(builder, zero)
+
+ if self.need_advanced_indexing():
+ indices = cgutils.unpack_tuple(builder, indices,
+ count=len(indices_ty))
+ index_types = indices_ty.types
+ index_types, indices = normalize_indices(context, builder,
+ index_types, indices)
+ else:
+ indices = (indices,)
+ index_types = (indices_ty,)
+ index_types, indices = normalize_indices(context, builder,
+ index_types, indices)
+
+ self.indexer = FancyIndexer(context, builder, a_ty, a,
+ index_types, indices)
+ self.indexer.prepare()
+ self.cres = self._compile_ufunc(context, builder)
+
+ def _load_val(self, context, builder, loop_indices, array, array_ty):
+ from numba.np.arrayobj import load_item
+ shapes = cgutils.unpack_tuple(builder, array.shape)
+ strides = cgutils.unpack_tuple(builder, array.strides)
+ data = array.data
+
+ ptr = cgutils.get_item_pointer2(context, builder, data, shapes, strides,
+ array_ty.layout, loop_indices)
+ val = load_item(context, builder, array_ty, ptr)
+ return ptr, val
+
+ def _load_flat(self, context, builder, indices, array, array_ty):
+ idx = builder.load(indices)
+ sig = array_ty.dtype(array_ty, types.intp)
+ impl = context.get_function(operator.getitem, sig)
+ val = impl(builder, (array, idx))
+
+ # increment indices
+ one = context.get_value_type(types.intp)(1)
+ idx = builder.add(idx, one)
+ builder.store(idx, indices)
+
+ return None, val
+
+ def _store_val(self, context, builder, array, array_ty, ptr, val):
+ from numba.np.arrayobj import store_item
+ fromty = self.cres.signature.return_type
+ toty = array_ty.dtype
+ val = context.cast(builder, val, fromty, toty)
+ store_item(context, builder, array_ty, val, ptr)
+
+ def _compile_ufunc(self, context, builder):
+ ufunc = self.ufunc.key[0]
+
+ if self.b is None:
+ sig = (self.a_ty.dtype,)
+ else:
+ sig = (self.a_ty.dtype, self.b_ty.dtype)
+
+ cres = ufunc.add(sig)
+ context.add_linking_libs((cres.library,))
+ return cres
+
+ def _call_ufunc(self, context, builder, loop_indices):
+ cres = self.cres
+ a, a_ty = self.a, self.a_ty
+
+ ptr, val = self._load_val(context, builder, loop_indices, a, a_ty)
+
+ if self.b is None:
+ args = (val,)
+ else:
+ b, b_ty, b_idx = self.b, self.b_ty, self.b_indice
+ _, val_b = self._load_flat(context, builder, b_idx, b, b_ty)
+ args = (val, val_b)
+
+ res = context.call_internal(builder, cres.fndesc, cres.signature,
+ args)
+ self._store_val(context, builder, a, a_ty, ptr, res)
+
+
+def make_dufunc_kernel(_dufunc):
+ from numba.np import npyimpl
+
+ class DUFuncKernel(npyimpl._Kernel):
+ """
+ npyimpl._Kernel subclass responsible for lowering a DUFunc kernel
+ (element-wise function) inside a broadcast loop (which is
+ generated by npyimpl.numpy_ufunc_kernel()).
+ """
+ dufunc = _dufunc
+
+ def __init__(self, context, builder, outer_sig):
+ super().__init__(context, builder, outer_sig)
+ self.inner_sig, self.cres = self.dufunc.find_ewise_function(
+ outer_sig.args)
+
+ DUFuncKernel.__name__ += _dufunc.ufunc.__name__
+ return DUFuncKernel
+
+
+class DUFuncLowerer(UfuncLowererBase):
+ '''Callable class responsible for lowering calls to a specific DUFunc.
+ '''
+ def __init__(self, dufunc):
+ from numba.np import npyimpl
+ super().__init__(dufunc,
+ make_dufunc_kernel,
+ npyimpl.numpy_ufunc_kernel)
+
+
+class DUFunc(serialize.ReduceMixin, _internal._DUFunc, UfuncBase):
+ """
+ Dynamic universal function (DUFunc) intended to act like a normal
+ Numpy ufunc, but capable of call-time (just-in-time) compilation
+ of fast loops specialized to inputs.
+ """
+ # NOTE: __base_kwargs must be kept in synch with the kwlist in
+ # _internal.c:dufunc_init()
+ __base_kwargs = set(('identity', '_keepalive', 'nin', 'nout'))
+
+ def __init__(self, py_func, identity=None, cache=False, targetoptions={}):
+ if is_jitted(py_func):
+ py_func = py_func.py_func
+ with ufuncbuilder._suppress_deprecation_warning_nopython_not_supplied():
+ dispatcher = jit(_target='npyufunc',
+ cache=cache,
+ **targetoptions)(py_func)
+ self._initialize(dispatcher, identity)
+ functools.update_wrapper(self, py_func)
+
+ def _initialize(self, dispatcher, identity):
+ identity = ufuncbuilder.parse_identity(identity)
+ super(DUFunc, self).__init__(dispatcher, identity=identity)
+ # Loop over a copy of the keys instead of the keys themselves,
+ # since we're changing the dictionary while looping.
+ self.reorderable = (identity != _internal.PyUFunc_None)
+ self.__name__ = dispatcher.py_func.__name__
+ self.__doc__ = dispatcher.py_func.__doc__
+ self._lower_me = DUFuncLowerer(self)
+ self._install_cg()
+ self._install_type()
+
+ def _reduce_states(self):
+ """
+ NOTE: part of ReduceMixin protocol
+ """
+ siglist = list(self._dispatcher.overloads.keys())
+ return dict(
+ dispatcher=self._dispatcher,
+ identity=self.identity,
+ frozen=self._frozen,
+ siglist=siglist,
+ )
+
+ @classmethod
+ def _rebuild(cls, dispatcher, identity, frozen, siglist):
+ """
+ NOTE: part of ReduceMixin protocol
+ """
+ self = _internal._DUFunc.__new__(cls)
+ self._initialize(dispatcher, identity)
+ # Re-add signatures
+ for sig in siglist:
+ self.add(sig)
+ if frozen:
+ self.disable_compile()
+ return self
+
+ def build_ufunc(self):
+ """
+ For compatibility with the various *UFuncBuilder classes.
+ """
+ return self
+
+ @property
+ def targetoptions(self):
+ return self._dispatcher.targetoptions
+
+ @property
+ def nin(self):
+ return self.ufunc.nin
+
+ @property
+ def nout(self):
+ return self.ufunc.nout
+
+ @property
+ def nargs(self):
+ return self.ufunc.nargs
+
+ @property
+ def ntypes(self):
+ return self.ufunc.ntypes
+
+ @property
+ def types(self):
+ return self.ufunc.types
+
+ @property
+ def identity(self):
+ return self.ufunc.identity
+
+ @property
+ def signature(self):
+ return self.ufunc.signature
+
+ def disable_compile(self):
+ """
+ Disable the compilation of new signatures at call time.
+ """
+ # If disabling compilation then there must be at least one signature
+ assert len(self._dispatcher.overloads) > 0
+ self._frozen = True
+
+ def add(self, sig):
+ """
+ Compile the DUFunc for the given signature.
+ """
+ args, return_type = sigutils.normalize_signature(sig)
+ return self._compile_for_argtys(args, return_type)
+
+ def __call__(self, *args, **kws):
+ """
+ Allow any argument that has overridden __array_ufunc__ (NEP-18)
+ to take control of DUFunc.__call__.
+ """
+ default = numpy_support.np.ndarray.__array_ufunc__
+
+ for arg in args + tuple(kws.values()):
+ if getattr(type(arg), "__array_ufunc__", default) is not default:
+ output = arg.__array_ufunc__(self, "__call__", *args, **kws)
+ if output is not NotImplemented:
+ return output
+ else:
+ return super().__call__(*args, **kws)
+
+ def _compile_for_args(self, *args, **kws):
+ nin = self.ufunc.nin
+ if kws:
+ if 'out' in kws:
+ out = kws.pop('out')
+ args += (out,)
+ if kws:
+ raise TypeError("unexpected keyword arguments to ufunc: %s"
+ % ", ".join(repr(k) for k in sorted(kws)))
+
+ args_len = len(args)
+ assert (args_len == nin) or (args_len == nin + self.ufunc.nout)
+ assert not kws
+ argtys = []
+ for arg in args[:nin]:
+ argty = typeof(arg)
+ if isinstance(argty, types.Array):
+ argty = argty.dtype
+ else:
+ # To avoid a mismatch in how Numba types scalar values as
+ # opposed to Numpy, we need special logic for scalars.
+ # For example, on 64-bit systems, numba.typeof(3) => int32, but
+ # np.array(3).dtype => int64.
+
+ # Note: this will not handle numpy "duckarrays" correctly,
+ # including but not limited to those implementing `__array__`
+ # and `__array_ufunc__`.
+ argty = numpy_support.map_arrayscalar_type(arg)
+ argtys.append(argty)
+ return self._compile_for_argtys(tuple(argtys))
+
+ @global_compiler_lock
+ def _compile_for_argtys(self, argtys, return_type=None):
+ """
+ Given a tuple of argument types (these should be the array
+ dtypes, and not the array types themselves), compile the
+ element-wise function for those inputs, generate a UFunc loop
+ wrapper, and register the loop with the Numpy ufunc object for
+ this DUFunc.
+ """
+ if self._frozen:
+ raise RuntimeError("compilation disabled for %s" % (self,))
+ assert isinstance(argtys, tuple)
+ if return_type is None:
+ sig = argtys
+ else:
+ sig = return_type(*argtys)
+
+ for k, cres in self._dispatcher.overloads.items():
+ if argtys == k.args:
+ msg = ("Compilation requested for previously compiled argument"
+ f" types ({argtys}). This has no effect and perhaps "
+ "indicates a bug in the calling code (compiling a "
+ "ufunc more than once for the same signature")
+ warnings.warn(msg, errors.NumbaWarning)
+ return cres
+
+ cres, argtys, return_type = ufuncbuilder._compile_element_wise_function(
+ self._dispatcher, self.targetoptions, sig)
+ actual_sig = ufuncbuilder._finalize_ufunc_signature(
+ cres, argtys, return_type)
+ dtypenums, ptr, env = ufuncbuilder._build_element_wise_ufunc_wrapper(
+ cres, actual_sig)
+ self._add_loop(int(ptr), dtypenums)
+ self._keepalive.append((ptr, cres.library, env))
+ self._lower_me.libs.append(cres.library)
+ return cres
+
+ def match_signature(self, ewise_types, sig):
+ return sig.args == ewise_types
+
+ def _install_ufunc_attributes(self, template) -> None:
+
+ def get_attr_fn(attr: str) -> Callable:
+
+ def impl(ufunc):
+ val = getattr(ufunc.key[0], attr)
+ return lambda ufunc: val
+ return impl
+
+ # ntypes/types needs "at" to be a BoundFunction rather than a Function
+ # But this fails as it cannot a weak reference to an ufunc due to NumPy
+ # not setting the "tp_weaklistoffset" field. See:
+ # https://github.com/numpy/numpy/blob/7fc72776b972bfbfdb909e4b15feb0308cf8adba/numpy/core/src/umath/ufunc_object.c#L6968-L6983 # noqa: E501
+
+ at = types.Function(template)
+ attributes = ('nin', 'nout', 'nargs', # 'ntypes', # 'types',
+ 'identity', 'signature')
+ for attr in attributes:
+ attr_fn = get_attr_fn(attr)
+ overload_attribute(at, attr)(attr_fn)
+
+ def _install_ufunc_methods(self, template) -> None:
+ self._install_ufunc_reduce(template)
+ self._install_ufunc_at(template)
+
+ def _install_ufunc_at(self, template) -> None:
+ at = types.Function(template)
+
+ @overload_method(at, 'at')
+ def ol_at(ufunc, a, indices, b=None):
+ warnings.warn("ufunc.at feature is experimental",
+ category=errors.NumbaExperimentalFeatureWarning)
+
+ if not isinstance(a, types.Array):
+ msg = 'The first argument "a" must be array-like'
+ raise errors.NumbaTypeError(msg)
+
+ indices_arr = isinstance(indices, types.Array)
+ indices_list = isinstance(indices, types.List)
+ indices_tuple = isinstance(indices, types.Tuple)
+ indices_slice = isinstance(indices, types.SliceType)
+ indices_scalar = not (indices_arr or indices_slice or indices_tuple)
+ indices_empty_tuple = indices_tuple and len(indices) == 0
+ b_array = isinstance(b, (types.Array, types.Sequence, types.List,
+ types.Tuple))
+ b_none = cgutils.is_nonelike(b)
+ b_scalar = not (b_array or b_none)
+ need_cast = any([indices_list])
+
+ nin = self.ufunc.nin
+
+ # missing second argument?
+ if nin == 2 and cgutils.is_nonelike(b):
+ raise errors.TypingError('second operand needed for ufunc')
+
+ # extra second argument
+ if nin == 1 and not cgutils.is_nonelike(b):
+ msg = 'second operand provided when ufunc is unary'
+ raise errors.TypingError(msg)
+
+ if cgutils.is_nonelike(b):
+ self.add((a.dtype,))
+ elif b_scalar:
+ self.add((a.dtype, b))
+ else:
+ self.add((a.dtype, b.dtype))
+
+ def apply_ufunc_codegen(context, builder, sig, args):
+ from numba.np.arrayobj import make_array
+
+ if len(args) == 4:
+ _, aty, idxty, bty = sig.args
+ _, a, indices, b = args
+ else:
+ _, aty, idxty, bty = sig.args + (None,)
+ _, a, indices, b = args + (None,)
+
+ a = make_array(aty)(context, builder, a)
+ at_iter = UfuncAtIterator(ufunc, a, aty, indices, idxty, b, bty)
+ at_iter.run(context, builder)
+
+ @intrinsic
+ def apply_a_b_ufunc(typingctx, ufunc, a, indices, b):
+ sig = types.none(ufunc, a, indices, b)
+ return sig, apply_ufunc_codegen
+
+ @intrinsic
+ def apply_a_ufunc(typingctx, ufunc, a, indices):
+ sig = types.none(ufunc, a, indices)
+ return sig, apply_ufunc_codegen
+
+ def impl_cast(ufunc, a, indices, b=None):
+ if b_none:
+ return ufunc.at(a, np.asarray(indices))
+ else:
+ return ufunc.at(a,
+ np.asarray(indices),
+ np.asarray(b))
+
+ def impl_generic(ufunc, a, indices, b=None):
+ if b_none:
+ apply_a_ufunc(ufunc, a, indices,)
+ else:
+ b_ = np.asarray(b)
+ a_ = a[indices]
+ b_ = np.broadcast_to(b_, a_.shape)
+ apply_a_b_ufunc(ufunc, a, indices, b_.flat)
+
+ def impl_indices_empty_b_scalar(ufunc, a, indices, b=None):
+ a[()] = ufunc(a[()], b)
+
+ def impl_scalar_scalar(ufunc, a, indices, b=None):
+ if b_none:
+ a[indices] = ufunc(a[indices])
+ else:
+ a[indices] = ufunc(a[indices], b)
+
+ if need_cast:
+ return impl_cast
+ elif indices_empty_tuple and b_scalar:
+ return impl_indices_empty_b_scalar
+ elif indices_scalar and b_scalar:
+ return impl_scalar_scalar
+ else:
+ return impl_generic
+
+ def _install_ufunc_reduce(self, template) -> None:
+ at = types.Function(template)
+
+ @overload_method(at, 'reduce')
+ def ol_reduce(ufunc, array, axis=0, dtype=None, initial=None):
+
+ warnings.warn("ufunc.reduce feature is experimental",
+ category=errors.NumbaExperimentalFeatureWarning)
+
+ if not isinstance(array, types.Array):
+ msg = 'The first argument "array" must be array-like'
+ raise errors.NumbaTypeError(msg)
+
+ axis_int_tuple = isinstance(axis, types.UniTuple) and \
+ isinstance(axis.dtype, types.Integer)
+ axis_empty_tuple = isinstance(axis, types.Tuple) and len(axis) == 0
+ axis_none = cgutils.is_nonelike(axis)
+
+ identity_none = self.ufunc.identity is None
+ ufunc_name = self.ufunc.__name__
+
+ # In NumPy, a ufunc is reorderable if its identity type is **not**
+ # PyUfunc_None.
+ if not self.reorderable and axis_int_tuple and len(axis) > 1:
+ msg = (f"reduction operation '{ufunc_name}' is not "
+ "reorderable, so at most one axis may be specified")
+ raise errors.NumbaTypeError(msg)
+
+ tup_init = (0,) * (array.ndim)
+ tup_init_m1 = (0,) * (array.ndim - 1)
+ nb_dtype = array.dtype if cgutils.is_nonelike(dtype) else dtype
+ identity = self.identity
+
+ id_none = cgutils.is_nonelike(identity)
+ init_none = cgutils.is_nonelike(initial)
+
+ @register_jitable
+ def tuple_slice(tup, pos):
+ # Same as
+ # tup = tup[0 : pos] + tup[pos + 1:]
+ s = tup_init_m1
+ i = 0
+ for j, e in enumerate(tup):
+ if j == pos:
+ continue
+ s = tuple_setitem(s, i, e)
+ i += 1
+ return s
+
+ @register_jitable
+ def tuple_slice_append(tup, pos, val):
+ # Same as
+ # tup = tup[0 : pos] + val + tup[pos + 1:]
+ s = tup_init
+ i, j, sz = 0, 0, len(s)
+ while j < sz:
+ if j == pos:
+ s = tuple_setitem(s, j, val)
+ else:
+ e = tup[i]
+ s = tuple_setitem(s, j, e)
+ i += 1
+ j += 1
+ return s
+
+ @intrinsic
+ def compute_flat_idx(typingctx, strides, itemsize, idx, axis):
+ sig = types.intp(strides, itemsize, idx, axis)
+ len_idx = len(idx)
+
+ def gen_block(builder, block_pos, block_name, bb_end, args):
+ strides, _, idx, _ = args
+ bb = builder.append_basic_block(name=block_name)
+
+ with builder.goto_block(bb):
+ zero = ir.IntType(64)(0)
+ flat_idx = zero
+
+ if block_pos == 0:
+ for i in range(1, len_idx):
+ stride = builder.extract_value(strides, i - 1)
+ idx_i = builder.extract_value(idx, i)
+ m = builder.mul(stride, idx_i)
+ flat_idx = builder.add(flat_idx, m)
+ elif 0 < block_pos < len_idx - 1:
+ for i in range(0, block_pos):
+ stride = builder.extract_value(strides, i)
+ idx_i = builder.extract_value(idx, i)
+ m = builder.mul(stride, idx_i)
+ flat_idx = builder.add(flat_idx, m)
+
+ for i in range(block_pos + 1, len_idx):
+ stride = builder.extract_value(strides, i - 1)
+ idx_i = builder.extract_value(idx, i)
+ m = builder.mul(stride, idx_i)
+ flat_idx = builder.add(flat_idx, m)
+ else:
+ for i in range(0, len_idx - 1):
+ stride = builder.extract_value(strides, i)
+ idx_i = builder.extract_value(idx, i)
+ m = builder.mul(stride, idx_i)
+ flat_idx = builder.add(flat_idx, m)
+
+ builder.branch(bb_end)
+
+ return bb, flat_idx
+
+ def codegen(context, builder, sig, args):
+ strides, itemsize, idx, axis = args
+
+ bb = builder.basic_block
+ switch_end = builder.append_basic_block(name='axis_end')
+ l = []
+ for i in range(len_idx):
+ block, flat_idx = gen_block(builder, i, f"axis_{i}",
+ switch_end, args)
+ l.append((block, flat_idx))
+
+ with builder.goto_block(bb):
+ switch = builder.switch(axis, l[-1][0])
+ for i in range(len_idx):
+ switch.add_case(i, l[i][0])
+
+ builder.position_at_end(switch_end)
+ phi = builder.phi(l[0][1].type)
+ for block, value in l:
+ phi.add_incoming(value, block)
+ return builder.sdiv(phi, itemsize)
+
+ return sig, codegen
+
+ @register_jitable
+ def fixup_axis(axis, ndim):
+ ax = axis
+ for i in range(len(axis)):
+ val = axis[i] + ndim if axis[i] < 0 else axis[i]
+ ax = tuple_setitem(ax, i, val)
+ return ax
+
+ @register_jitable
+ def find_min(tup):
+ idx, e = 0, tup[0]
+ for i in range(len(tup)):
+ if tup[i] < e:
+ idx, e = i, tup[i]
+ return idx, e
+
+ def impl_1d(ufunc, array, axis=0, dtype=None, initial=None):
+ if identity_none and initial is None and len(array) == 0:
+ msg = ('zero-size array to reduction operation '
+ f'{ufunc_name} which has no identity')
+ raise ValueError(msg)
+
+ start = 0
+ if init_none and id_none:
+ start = 1
+ r = array[0]
+ elif init_none:
+ r = identity
+ else:
+ r = initial
+
+ sz = array.shape[0]
+ for i in range(start, sz):
+ r = ufunc(r, array[i])
+ return r
+
+ def impl_nd_axis_int(ufunc,
+ array,
+ axis=0,
+ dtype=None,
+ initial=None):
+ if axis is None:
+ raise ValueError("'axis' must be specified")
+
+ if axis < 0:
+ axis += array.ndim
+
+ if axis < 0 or axis >= array.ndim:
+ raise ValueError("Invalid axis")
+
+ if identity_none and initial is None and array.shape[axis] == 0:
+ msg = ('zero-size array to reduction operation '
+ f'{ufunc_name} which has no identity')
+ raise ValueError(msg)
+
+ # create result array
+ shape = tuple_slice(array.shape, axis)
+
+ if initial is None and identity is None:
+ r = np.empty(shape, dtype=nb_dtype)
+ for idx, _ in np.ndenumerate(r):
+ # shape[0:axis] + 0 + shape[axis:]
+ result_idx = tuple_slice_append(idx, axis, 0)
+ r[idx] = array[result_idx]
+ elif initial is None and identity is not None:
+ # Checking if identity is not none is redundant but required
+ # compile this block
+ r = np.full(shape, fill_value=identity, dtype=nb_dtype)
+ else:
+ r = np.full(shape, fill_value=initial, dtype=nb_dtype)
+
+ # One approach to implement reduce is to remove the axis index
+ # from the indexing tuple returned by "np.ndenumerate". For
+ # instance, if idx = (X, Y, Z) and axis=1, the result index
+ # is (X, Y).
+ # Another way is to compute the result index using strides,
+ # which is faster than manipulating tuples.
+ view = r.ravel()
+ if initial is None and identity is None:
+ for idx, val in np.ndenumerate(array):
+ if idx[axis] == 0:
+ continue
+ else:
+ flat_pos = compute_flat_idx(r.strides, r.itemsize,
+ idx, axis)
+ lhs, rhs = view[flat_pos], val
+ view[flat_pos] = ufunc(lhs, rhs)
+ else:
+ for idx, val in np.ndenumerate(array):
+ if initial is None and identity is None and \
+ idx[axis] == 0:
+ continue
+ flat_pos = compute_flat_idx(r.strides, r.itemsize,
+ idx, axis)
+ lhs, rhs = view[flat_pos], val
+ view[flat_pos] = ufunc(lhs, rhs)
+ return r
+
+ def impl_nd_axis_tuple(ufunc,
+ array,
+ axis=0,
+ dtype=None,
+ initial=None):
+ axis_ = fixup_axis(axis, array.ndim)
+ for i in range(0, len(axis_)):
+ if axis_[i] < 0 or axis_[i] >= array.ndim:
+ raise ValueError("Invalid axis")
+
+ for j in range(i + 1, len(axis_)):
+ if axis_[i] == axis_[j]:
+ raise ValueError("duplicate value in 'axis'")
+
+ min_idx, min_elem = find_min(axis_)
+ r = ufunc.reduce(array,
+ axis=min_elem,
+ dtype=dtype,
+ initial=initial)
+ if len(axis) == 1:
+ return r
+ elif len(axis) == 2:
+ return ufunc.reduce(r, axis=axis_[(min_idx + 1) % 2] - 1)
+ else:
+ ax = axis_tup
+ for i in range(len(ax)):
+ if i != min_idx:
+ ax = tuple_setitem(ax, i, axis_[i])
+ return ufunc.reduce(r, axis=ax)
+
+ def impl_axis_empty_tuple(ufunc,
+ array,
+ axis=0,
+ dtype=None,
+ initial=None):
+ return array
+
+ def impl_axis_none(ufunc,
+ array,
+ axis=0,
+ dtype=None,
+ initial=None):
+ return ufunc.reduce(array, axis_tup, dtype, initial)
+
+ if array.ndim == 1 and not axis_empty_tuple:
+ return impl_1d
+ elif axis_empty_tuple:
+ # ufunc(array, axis=())
+ return impl_axis_empty_tuple
+ elif axis_none:
+ # ufunc(array, axis=None)
+ axis_tup = tuple(range(array.ndim))
+ return impl_axis_none
+ elif axis_int_tuple:
+ # axis is tuple of integers
+ # ufunc(array, axis=(1, 2, ...))
+ axis_tup = (0,) * (len(axis) - 1)
+ return impl_nd_axis_tuple
+ elif axis == 0 or isinstance(axis, (types.Integer,
+ types.Omitted,
+ types.IntegerLiteral)):
+ # axis is default value (0) or an integer
+ # ufunc(array, axis=0)
+ return impl_nd_axis_int
+
+ def at(self, a, indices, b=None):
+ # dynamic compile ufunc.at
+ args = (a,) if cgutils.is_nonelike(b) else (a, b)
+ argtys = (typeof(arg) for arg in args)
+ ewise_types = tuple(arg.dtype if isinstance(arg, types.Array) else arg
+ for arg in argtys)
+
+ if self.find_ewise_function(ewise_types) == (None, None):
+ # cannot find a matching function and compilation is disabled
+ if self._frozen:
+ msg = "compilation disabled for %s.at(...)" % (self,)
+ raise RuntimeError(msg)
+
+ self._compile_for_args(*args)
+
+ # all good, just dispatch to the function
+ if cgutils.is_nonelike(b):
+ return super().at(a, indices)
+ else:
+ return super().at(*(a, indices, b))
+
+ def _install_type(self, typingctx=None):
+ """Constructs and installs a typing class for a DUFunc object in the
+ input typing context. If no typing context is given, then
+ _install_type() installs into the typing context of the
+ dispatcher object (should be same default context used by
+ jit() and njit()).
+ """
+ if typingctx is None:
+ typingctx = self._dispatcher.targetdescr.typing_context
+ _ty_cls = type('DUFuncTyping_' + self.ufunc.__name__,
+ (AbstractTemplate,),
+ dict(key=self, generic=self._type_me))
+ typingctx.insert_user_function(self, _ty_cls)
+ self._install_ufunc_attributes(_ty_cls)
+ self._install_ufunc_methods(_ty_cls)
+
+ def find_ewise_function(self, ewise_types):
+ """
+ Given a tuple of element-wise argument types, find a matching
+ signature in the dispatcher.
+
+ Return a 2-tuple containing the matching signature, and
+ compilation result. Will return two None's if no matching
+ signature was found.
+ """
+ if self._frozen:
+ # If we cannot compile, coerce to the best matching loop
+ loop = numpy_support.ufunc_find_matching_loop(self, ewise_types)
+ if loop is None:
+ return None, None
+ ewise_types = tuple(loop.inputs + loop.outputs)[:len(ewise_types)]
+ for sig, cres in self._dispatcher.overloads.items():
+ if sig.args == ewise_types:
+ return sig, cres
+ return None, None
+
+ def _type_me(self, argtys, kwtys):
+ """
+ Implement AbstractTemplate.generic() for the typing class
+ built by DUFunc._install_type().
+
+ Return the call-site signature after either validating the
+ element-wise signature or compiling for it.
+ """
+ assert not kwtys
+ ufunc = self.ufunc
+ _handle_inputs_result = npydecl.Numpy_rules_ufunc._handle_inputs(
+ ufunc, argtys, kwtys)
+ base_types, explicit_outputs, ndims, layout = _handle_inputs_result
+ explicit_output_count = len(explicit_outputs)
+ if explicit_output_count > 0:
+ ewise_types = tuple(base_types[:-len(explicit_outputs)])
+ else:
+ ewise_types = tuple(base_types)
+ sig, cres = self.find_ewise_function(ewise_types)
+ if sig is None:
+ # Matching element-wise signature was not found; must
+ # compile.
+ if self._frozen:
+ raise errors.NumbaTypeError("cannot call %s with types %s"
+ % (self, argtys))
+ self._compile_for_argtys(ewise_types)
+ sig, cres = self.find_ewise_function(ewise_types)
+ assert sig is not None
+ if explicit_output_count > 0:
+ outtys = list(explicit_outputs)
+ elif ufunc.nout == 1:
+ if ndims > 0:
+ outtys = [types.Array(sig.return_type, ndims, layout)]
+ else:
+ outtys = [sig.return_type]
+ else:
+ raise errors.NumbaNotImplementedError("typing gufuncs (nout > 1)")
+ outtys.extend(argtys)
+ return signature(*outtys)
+
+
+array_analysis.MAP_TYPES.append(DUFunc)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/np/ufunc/gufunc.py b/tool_server/.venv/lib/python3.12/site-packages/numba/np/ufunc/gufunc.py
new file mode 100644
index 0000000000000000000000000000000000000000..103ef7b5d9505cb32f48892cf474c597da160eb3
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/np/ufunc/gufunc.py
@@ -0,0 +1,323 @@
+from numba import typeof
+from numba.core import types
+from numba.np.ufunc.ufuncbuilder import GUFuncBuilder
+from numba.np.ufunc.sigparse import parse_signature
+from numba.np.ufunc.ufunc_base import UfuncBase, UfuncLowererBase
+from numba.np.numpy_support import ufunc_find_matching_loop
+from numba.core import serialize, errors
+from numba.core.typing import npydecl
+from numba.core.typing.templates import signature, AbstractTemplate
+import functools
+
+
+def make_gufunc_kernel(_dufunc):
+ from numba.np import npyimpl
+
+ class GUFuncKernel(npyimpl._Kernel):
+ """
+ npyimpl._Kernel subclass responsible for lowering a gufunc kernel
+ (element-wise function) inside a broadcast loop (which is
+ generated by npyimpl.numpy_gufunc_kernel()).
+ """
+ dufunc = _dufunc
+
+ def __init__(self, context, builder, outer_sig):
+ super().__init__(context, builder, outer_sig)
+ ewise_types = self.dufunc._get_ewise_dtypes(outer_sig.args)
+ self.inner_sig, self.cres = self.dufunc.find_ewise_function(
+ ewise_types)
+
+ def cast(self, val, fromty, toty):
+ # Handle the case where "fromty" is an array and "toty" a scalar
+ if isinstance(fromty, types.Array) and not \
+ isinstance(toty, types.Array):
+ return super().cast(val, fromty.dtype, toty)
+ return super().cast(val, fromty, toty)
+
+ def generate(self, *args):
+ if self.cres.objectmode:
+ msg = ('Calling a guvectorize function in object mode is not '
+ 'supported yet.')
+ raise errors.NumbaRuntimeError(msg)
+ self.context.add_linking_libs((self.cres.library,))
+ return super().generate(*args)
+
+ GUFuncKernel.__name__ += _dufunc.__name__
+ return GUFuncKernel
+
+
+class GUFuncLowerer(UfuncLowererBase):
+ '''Callable class responsible for lowering calls to a specific gufunc.
+ '''
+ def __init__(self, gufunc):
+ from numba.np import npyimpl
+ super().__init__(gufunc,
+ make_gufunc_kernel,
+ npyimpl.numpy_gufunc_kernel)
+
+
+class GUFunc(serialize.ReduceMixin, UfuncBase):
+ """
+ Dynamic generalized universal function (GUFunc)
+ intended to act like a normal Numpy gufunc, but capable
+ of call-time (just-in-time) compilation of fast loops
+ specialized to inputs.
+ """
+
+ def __init__(self, py_func, signature, identity=None, cache=None,
+ is_dynamic=False, targetoptions={}, writable_args=()):
+ self.ufunc = None
+ self._frozen = False
+ self._is_dynamic = is_dynamic
+ self._identity = identity
+
+ # GUFunc cannot inherit from GUFuncBuilder because "identity"
+ # is a property of GUFunc. Thus, we hold a reference to a GUFuncBuilder
+ # object here
+ self.gufunc_builder = GUFuncBuilder(
+ py_func, signature, identity, cache, targetoptions, writable_args)
+
+ self.__name__ = self.gufunc_builder.py_func.__name__
+ self.__doc__ = self.gufunc_builder.py_func.__doc__
+ self._dispatcher = self.gufunc_builder.nb_func
+ self._initialize(self._dispatcher)
+ functools.update_wrapper(self, py_func)
+
+ def _initialize(self, dispatcher):
+ self.build_ufunc()
+ self._install_type()
+ self._lower_me = GUFuncLowerer(self)
+ self._install_cg()
+
+ def _reduce_states(self):
+ gb = self.gufunc_builder
+ dct = dict(
+ py_func=gb.py_func,
+ signature=gb.signature,
+ identity=self._identity,
+ cache=gb.cache,
+ is_dynamic=self._is_dynamic,
+ targetoptions=gb.targetoptions,
+ writable_args=gb.writable_args,
+ typesigs=gb._sigs,
+ frozen=self._frozen,
+ )
+ return dct
+
+ @classmethod
+ def _rebuild(cls, py_func, signature, identity, cache, is_dynamic,
+ targetoptions, writable_args, typesigs, frozen):
+ self = cls(py_func=py_func, signature=signature, identity=identity,
+ cache=cache, is_dynamic=is_dynamic,
+ targetoptions=targetoptions, writable_args=writable_args)
+ for sig in typesigs:
+ self.add(sig)
+ self.build_ufunc()
+ self._frozen = frozen
+ return self
+
+ def __repr__(self):
+ return f""
+
+ def _install_type(self, typingctx=None):
+ """Constructs and installs a typing class for a gufunc object in the
+ input typing context. If no typing context is given, then
+ _install_type() installs into the typing context of the
+ dispatcher object (should be same default context used by
+ jit() and njit()).
+ """
+ if typingctx is None:
+ typingctx = self._dispatcher.targetdescr.typing_context
+ _ty_cls = type('GUFuncTyping_' + self.__name__,
+ (AbstractTemplate,),
+ dict(key=self, generic=self._type_me))
+ typingctx.insert_user_function(self, _ty_cls)
+
+ def add(self, fty):
+ self.gufunc_builder.add(fty)
+
+ def build_ufunc(self):
+ self.ufunc = self.gufunc_builder.build_ufunc()
+ return self
+
+ def expected_ndims(self):
+ parsed_sig = parse_signature(self.gufunc_builder.signature)
+ return (tuple(map(len, parsed_sig[0])), tuple(map(len, parsed_sig[1])))
+
+ def _type_me(self, argtys, kws):
+ """
+ Implement AbstractTemplate.generic() for the typing class
+ built by gufunc._install_type().
+
+ Return the call-site signature after either validating the
+ element-wise signature or compiling for it.
+ """
+ assert not kws
+ ufunc = self.ufunc
+ sig = self.gufunc_builder.signature
+ inp_ndims, out_ndims = self.expected_ndims()
+ ndims = inp_ndims + out_ndims
+
+ assert len(argtys), len(ndims)
+ for idx, arg in enumerate(argtys):
+ if isinstance(arg, types.Array) and arg.ndim < ndims[idx]:
+ kind = "Input" if idx < len(inp_ndims) else "Output"
+ i = idx if idx < len(inp_ndims) else idx - len(inp_ndims)
+ msg = (
+ f"{self.__name__}: {kind} operand {i} does not have "
+ f"enough dimensions (has {arg.ndim}, gufunc core with "
+ f"signature {sig} requires {ndims[idx]})")
+ raise errors.TypingError(msg)
+
+ _handle_inputs_result = npydecl.Numpy_rules_ufunc._handle_inputs(
+ ufunc, argtys, kws)
+ ewise_types, _, _, _ = _handle_inputs_result
+ sig, _ = self.find_ewise_function(ewise_types)
+
+ if sig is None:
+ # Matching element-wise signature was not found; must
+ # compile.
+ if self._frozen:
+ msg = f"cannot call {self} with types {argtys}"
+ raise errors.TypingError(msg)
+ self._compile_for_argtys(ewise_types)
+ # double check to ensure there is a match
+ sig, _ = self.find_ewise_function(ewise_types)
+ if sig == (None, None):
+ msg = f"Fail to compile {self.__name__} with types {argtys}"
+ raise errors.TypingError(msg)
+
+ assert sig is not None
+
+ return signature(types.none, *argtys)
+
+ def _compile_for_argtys(self, argtys, return_type=None):
+ # Compile a new guvectorize function! Use the gufunc signature
+ # i.e. (n,m),(m)->(n)
+ # plus ewise_types to build a numba function type
+ fnty = self._get_function_type(*argtys)
+ self.gufunc_builder.add(fnty)
+
+ def match_signature(self, ewise_types, sig):
+ dtypes = self._get_ewise_dtypes(sig.args)
+ return tuple(dtypes) == tuple(ewise_types)
+
+ @property
+ def is_dynamic(self):
+ return self._is_dynamic
+
+ def _get_ewise_dtypes(self, args):
+ argtys = map(lambda arg: arg if isinstance(arg, types.Type) else
+ typeof(arg), args)
+ tys = []
+ for argty in argtys:
+ if isinstance(argty, types.Array):
+ tys.append(argty.dtype)
+ else:
+ tys.append(argty)
+ return tys
+
+ def _num_args_match(self, *args):
+ parsed_sig = parse_signature(self.gufunc_builder.signature)
+ return len(args) == len(parsed_sig[0]) + len(parsed_sig[1])
+
+ def _get_function_type(self, *args):
+ parsed_sig = parse_signature(self.gufunc_builder.signature)
+ # ewise_types is a list of [int32, int32, int32, ...]
+ ewise_types = self._get_ewise_dtypes(args)
+
+ # first time calling the gufunc
+ # generate a signature based on input arguments
+ l = []
+ for idx, sig_dim in enumerate(parsed_sig[0]):
+ ndim = len(sig_dim)
+ if ndim == 0: # append scalar
+ l.append(ewise_types[idx])
+ else:
+ l.append(types.Array(ewise_types[idx], ndim, 'A'))
+
+ offset = len(parsed_sig[0])
+ # add return type to signature
+ for idx, sig_dim in enumerate(parsed_sig[1]):
+ retty = ewise_types[idx + offset]
+ ret_ndim = len(sig_dim) or 1 # small hack to return scalars
+ l.append(types.Array(retty, ret_ndim, 'A'))
+
+ return types.none(*l)
+
+ def __call__(self, *args, **kwargs):
+ # If compilation is disabled OR it is NOT a dynamic gufunc
+ # call the underlying gufunc
+ if self._frozen or not self.is_dynamic:
+ # Do not unwrap the ufunc if the argument is a wrapper that will
+ # potentially pickle the ufunc after it receives it in
+ # __array_ufunc__. The same logic in theory should be replicated
+ # for reduce(), outer(), etc., but they're not implemented in dask.
+ if args and _is_array_wrapper(args[0]):
+ return args[0].__array_ufunc__(
+ self, "__call__", *args, **kwargs
+ )
+ else:
+ return self.ufunc(*args, **kwargs)
+ elif "out" in kwargs:
+ # If "out" argument is supplied
+ args += (kwargs.pop("out"),)
+
+ if self._num_args_match(*args) is False:
+ # It is not allowed to call a dynamic gufunc without
+ # providing all the arguments
+ # see: https://github.com/numba/numba/pull/5938#discussion_r506429392 # noqa: E501
+ msg = (
+ f"Too few arguments for function '{self.__name__}'. "
+ "Note that the pattern `out = gufunc(Arg1, Arg2, ..., ArgN)` "
+ "is not allowed. Use `gufunc(Arg1, Arg2, ..., ArgN, out) "
+ "instead.")
+ raise TypeError(msg)
+
+ # at this point we know the gufunc is a dynamic one
+ ewise = self._get_ewise_dtypes(args)
+ if not (self.ufunc and ufunc_find_matching_loop(self.ufunc, ewise)):
+ # A previous call (@njit -> @guvectorize) may have compiled a
+ # version for the element-wise dtypes. In this case, we don't need
+ # to compile it again, just build the (g)ufunc
+ if not self.find_ewise_function(ewise) != (None, None):
+ sig = self._get_function_type(*args)
+ self.add(sig)
+ self.build_ufunc()
+
+ return self.ufunc(*args, **kwargs)
+
+
+def _is_array_wrapper(obj):
+ """Return True if obj wraps around numpy or another numpy-like library
+ and is likely going to apply the ufunc to the wrapped array; False
+ otherwise.
+
+ At the moment, this returns True for
+
+ - dask.array.Array
+ - dask.dataframe.DataFrame
+ - dask.dataframe.Series
+ - xarray.DataArray
+ - xarray.Dataset
+ - xarray.Variable
+ - pint.Quantity
+ - other potential wrappers around dask array or dask dataframe
+
+ We may need to add other libraries that pickle ufuncs from their
+ __array_ufunc__ method in the future.
+
+ Note that the below test is a lot more naive than
+ `dask.base.is_dask_collection`
+ (https://github.com/dask/dask/blob/5949e54bc04158d215814586a44d51e0eb4a964d/dask/base.py#L209-L249), # noqa: E501
+ because it doesn't need to find out if we're actually dealing with
+ a dask collection, only that we're dealing with a wrapper.
+ Namely, it will return True for a pint.Quantity wrapping around a plain float, a
+ numpy.ndarray, or a dask.array.Array, and it's OK because in all cases
+ Quantity.__array_ufunc__ is going to forward the ufunc call inwards.
+ """
+ return (
+ not isinstance(obj, type)
+ and hasattr(obj, "__dask_graph__")
+ and hasattr(obj, "__array_ufunc__")
+ )
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/np/ufunc/omppool.cpython-312-x86_64-linux-gnu.so b/tool_server/.venv/lib/python3.12/site-packages/numba/np/ufunc/omppool.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..204587f7cd6c262c0d0eef59d5c31b2e594ce746
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/np/ufunc/omppool.cpython-312-x86_64-linux-gnu.so
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:cb137ae96dad38b8f80d2cc354bd67600d9b2361cd25edf8384d621b48f31628
+size 600089
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/np/ufunc/parallel.py b/tool_server/.venv/lib/python3.12/site-packages/numba/np/ufunc/parallel.py
new file mode 100644
index 0000000000000000000000000000000000000000..b80262dcf2c6123a46cc51f14db86c4000e1eb1e
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/np/ufunc/parallel.py
@@ -0,0 +1,761 @@
+"""
+This file implements the code-generator for parallel-vectorize.
+
+ParallelUFunc is the platform independent base class for generating
+the thread dispatcher. This thread dispatcher launches threads
+that execute the generated function of UFuncCore.
+UFuncCore is subclassed to specialize for the input/output types.
+The actual workload is invoked inside the function generated by UFuncCore.
+UFuncCore also defines a work-stealing mechanism that allows idle threads
+to steal works from other threads.
+"""
+
+import os
+import sys
+import warnings
+from threading import RLock as threadRLock
+from ctypes import CFUNCTYPE, c_int, CDLL, POINTER, c_uint
+
+import numpy as np
+
+import llvmlite.binding as ll
+from llvmlite import ir
+
+from numba.np.numpy_support import as_dtype
+from numba.core import types, cgutils, config, errors
+from numba.core.typing import signature
+from numba.np.ufunc.wrappers import _wrapper_info
+from numba.np.ufunc import ufuncbuilder
+from numba.extending import overload, intrinsic
+
+_IS_OSX = sys.platform.startswith('darwin')
+_IS_LINUX = sys.platform.startswith('linux')
+_IS_WINDOWS = sys.platform.startswith('win32')
+
+
+def get_thread_count():
+ """
+ Gets the available thread count.
+ """
+ t = config.NUMBA_NUM_THREADS
+ if t < 1:
+ raise ValueError("Number of threads specified must be > 0.")
+ return t
+
+
+NUM_THREADS = get_thread_count()
+
+
+def build_gufunc_kernel(library, ctx, info, sig, inner_ndim):
+ """Wrap the original CPU ufunc/gufunc with a parallel dispatcher.
+ This function will wrap gufuncs and ufuncs something like.
+
+ Args
+ ----
+ ctx
+ numba's codegen context
+
+ info: (library, env, name)
+ inner function info
+
+ sig
+ type signature of the gufunc
+
+ inner_ndim
+ inner dimension of the gufunc (this is len(sig.args) in the case of a
+ ufunc)
+
+ Returns
+ -------
+ wrapper_info : (library, env, name)
+ The info for the gufunc wrapper.
+
+ Details
+ -------
+
+ The kernel signature looks like this:
+
+ void kernel(char **args, npy_intp *dimensions, npy_intp* steps, void* data)
+
+ args - the input arrays + output arrays
+ dimensions - the dimensions of the arrays
+ steps - the step size for the array (this is like sizeof(type))
+ data - any additional data
+
+ The parallel backend then stages multiple calls to this kernel concurrently
+ across a number of threads. Practically, for each item of work, the backend
+ duplicates `dimensions` and adjusts the first entry to reflect the size of
+ the item of work, it also forms up an array of pointers into the args for
+ offsets to read/write from/to with respect to its position in the items of
+ work. This allows the same kernel to be used for each item of work, with
+ simply adjusted reads/writes/domain sizes and is safe by virtue of the
+ domain partitioning.
+
+ NOTE: The execution backend is passed the requested thread count, but it can
+ choose to ignore it (TBB)!
+ """
+ assert isinstance(info, tuple) # guard against old usage
+ # Declare types and function
+ byte_t = ir.IntType(8)
+ byte_ptr_t = ir.PointerType(byte_t)
+ byte_ptr_ptr_t = ir.PointerType(byte_ptr_t)
+
+ intp_t = ctx.get_value_type(types.intp)
+ intp_ptr_t = ir.PointerType(intp_t)
+
+ fnty = ir.FunctionType(ir.VoidType(), [ir.PointerType(byte_ptr_t),
+ ir.PointerType(intp_t),
+ ir.PointerType(intp_t),
+ byte_ptr_t])
+ wrapperlib = ctx.codegen().create_library('parallelgufuncwrapper')
+ mod = wrapperlib.create_ir_module('parallel.gufunc.wrapper')
+ kernel_name = ".kernel.{}_{}".format(id(info.env), info.name)
+ lfunc = ir.Function(mod, fnty, name=kernel_name)
+
+ bb_entry = lfunc.append_basic_block('')
+
+ # Function body starts
+ builder = ir.IRBuilder(bb_entry)
+
+ args, dimensions, steps, data = lfunc.args
+
+ # Release the GIL (and ensure we have the GIL)
+ # Note: numpy ufunc may not always release the GIL; thus,
+ # we need to ensure we have the GIL.
+ pyapi = ctx.get_python_api(builder)
+ gil_state = pyapi.gil_ensure()
+ thread_state = pyapi.save_thread()
+
+ def as_void_ptr(arg):
+ return builder.bitcast(arg, byte_ptr_t)
+
+ # Array count depends on whether an "output" array is needed. In the case
+ # of a void return type cf. gufunc it is the number of args, in the case of
+ # a non-void return type cf. ufunc it is the number of args + 1 so as to
+ # account for the output array.
+ array_count = len(sig.args)
+ if not isinstance(sig.return_type, types.NoneType):
+ array_count += 1
+
+ parallel_for_ty = ir.FunctionType(ir.VoidType(),
+ [byte_ptr_t] * 5 + [intp_t, ] * 3)
+ parallel_for = cgutils.get_or_insert_function(mod, parallel_for_ty,
+ 'numba_parallel_for')
+
+ # Reference inner-function and link
+ innerfunc_fnty = ir.FunctionType(
+ ir.VoidType(),
+ [byte_ptr_ptr_t, intp_ptr_t, intp_ptr_t, byte_ptr_t],
+ )
+ tmp_voidptr = cgutils.get_or_insert_function(mod, innerfunc_fnty,
+ info.name,)
+ wrapperlib.add_linking_library(info.library)
+
+ get_num_threads = cgutils.get_or_insert_function(
+ builder.module,
+ ir.FunctionType(ir.IntType(types.intp.bitwidth), []),
+ "get_num_threads")
+
+ num_threads = builder.call(get_num_threads, [])
+
+ # Prepare call
+ fnptr = builder.bitcast(tmp_voidptr, byte_ptr_t)
+ innerargs = [as_void_ptr(x) for x
+ in [args, dimensions, steps, data]]
+ builder.call(parallel_for, [fnptr] + innerargs +
+ [intp_t(x) for x in (inner_ndim, array_count)] + [num_threads])
+
+ # Release the GIL
+ pyapi.restore_thread(thread_state)
+ pyapi.gil_release(gil_state)
+
+ builder.ret_void()
+
+ wrapperlib.add_ir_module(mod)
+ wrapperlib.add_linking_library(library)
+ return _wrapper_info(library=wrapperlib, name=lfunc.name, env=info.env)
+
+
+# ------------------------------------------------------------------------------
+
+class ParallelUFuncBuilder(ufuncbuilder.UFuncBuilder):
+ def build(self, cres, sig):
+ _launch_threads()
+
+ # Builder wrapper for ufunc entry point
+ ctx = cres.target_context
+ signature = cres.signature
+ library = cres.library
+ fname = cres.fndesc.llvm_func_name
+
+ info = build_ufunc_wrapper(library, ctx, fname, signature, cres)
+ ptr = info.library.get_pointer_to_function(info.name)
+ # Get dtypes
+ dtypenums = [np.dtype(a.name).num for a in signature.args]
+ dtypenums.append(np.dtype(signature.return_type.name).num)
+ keepalive = ()
+ return dtypenums, ptr, keepalive
+
+
+def build_ufunc_wrapper(library, ctx, fname, signature, cres):
+ innerfunc = ufuncbuilder.build_ufunc_wrapper(library, ctx, fname,
+ signature, objmode=False,
+ cres=cres)
+ info = build_gufunc_kernel(library, ctx, innerfunc, signature,
+ len(signature.args))
+ return info
+
+# ---------------------------------------------------------------------------
+
+
+class ParallelGUFuncBuilder(ufuncbuilder.GUFuncBuilder):
+ def __init__(self, py_func, signature, identity=None, cache=False,
+ targetoptions={}, writable_args=()):
+ # Force nopython mode
+ targetoptions.update(dict(nopython=True))
+ super(
+ ParallelGUFuncBuilder,
+ self).__init__(
+ py_func=py_func,
+ signature=signature,
+ identity=identity,
+ cache=cache,
+ targetoptions=targetoptions,
+ writable_args=writable_args)
+
+ def build(self, cres):
+ """
+ Returns (dtype numbers, function ptr, EnvironmentObject)
+ """
+ _launch_threads()
+
+ # Build wrapper for ufunc entry point
+ info = build_gufunc_wrapper(
+ self.py_func, cres, self.sin, self.sout, cache=self.cache,
+ is_parfors=False,
+ )
+ ptr = info.library.get_pointer_to_function(info.name)
+ env = info.env
+
+ # Get dtypes
+ dtypenums = []
+ for a in cres.signature.args:
+ if isinstance(a, types.Array):
+ ty = a.dtype
+ else:
+ ty = a
+ dtypenums.append(as_dtype(ty).num)
+
+ return dtypenums, ptr, env
+
+
+# This is not a member of the ParallelGUFuncBuilder function because it is
+# called without an enclosing instance from parfors
+
+def build_gufunc_wrapper(py_func, cres, sin, sout, cache, is_parfors):
+ """Build gufunc wrapper for the given arguments.
+ The *is_parfors* is a boolean indicating whether the gufunc is being
+ built for use as a ParFors kernel. This changes codegen and caching
+ behavior.
+ """
+ library = cres.library
+ ctx = cres.target_context
+ signature = cres.signature
+ innerinfo = ufuncbuilder.build_gufunc_wrapper(
+ py_func, cres, sin, sout, cache=cache, is_parfors=is_parfors,
+ )
+ sym_in = set(sym for term in sin for sym in term)
+ sym_out = set(sym for term in sout for sym in term)
+ inner_ndim = len(sym_in | sym_out)
+
+ info = build_gufunc_kernel(
+ library, ctx, innerinfo, signature, inner_ndim,
+ )
+ return info
+
+# ---------------------------------------------------------------------------
+
+
+_backend_init_thread_lock = threadRLock()
+
+_windows = sys.platform.startswith('win32')
+
+
+class _nop(object):
+ """A no-op contextmanager
+ """
+
+ def __enter__(self):
+ pass
+
+ def __exit__(self, *args):
+ pass
+
+
+_backend_init_process_lock = None
+
+
+def _set_init_process_lock():
+ global _backend_init_process_lock
+ try:
+ # Force the use of an RLock in the case a fork was used to start the
+ # process and thereby the init sequence, some of the threading backend
+ # init sequences are not fork safe. Also, windows global mp locks seem
+ # to be fine.
+ with _backend_init_thread_lock: # protect part-initialized module access
+ import multiprocessing
+ if "fork" in multiprocessing.get_start_method() or _windows:
+ ctx = multiprocessing.get_context()
+ _backend_init_process_lock = ctx.RLock()
+ else:
+ _backend_init_process_lock = _nop()
+
+ except OSError as e:
+
+ # probably lack of /dev/shm for semaphore writes, warn the user
+ msg = (
+ "Could not obtain multiprocessing lock due to OS level error: %s\n"
+ "A likely cause of this problem is '/dev/shm' is missing or "
+ "read-only such that necessary semaphores cannot be written.\n"
+ "*** The responsibility of ensuring multiprocessing safe access to "
+ "this initialization sequence/module import is deferred to the "
+ "user! ***\n"
+ )
+ warnings.warn(msg % str(e), errors.NumbaSystemWarning)
+
+ _backend_init_process_lock = _nop()
+
+
+_is_initialized = False
+
+# this is set by _launch_threads
+_threading_layer = None
+
+
+def threading_layer():
+ """
+ Get the name of the threading layer in use for parallel CPU targets
+ """
+ if _threading_layer is None:
+ raise ValueError("Threading layer is not initialized.")
+ else:
+ return _threading_layer
+
+
+def _check_tbb_version_compatible():
+ """
+ Checks that if TBB is present it is of a compatible version.
+ """
+ try:
+ # first check that the TBB version is new enough
+ if _IS_WINDOWS:
+ libtbb_name = 'tbb12.dll'
+ elif _IS_OSX:
+ libtbb_name = 'libtbb.12.dylib'
+ elif _IS_LINUX:
+ libtbb_name = 'libtbb.so.12'
+ else:
+ raise ValueError("Unknown operating system")
+ libtbb = CDLL(libtbb_name)
+ version_func = libtbb.TBB_runtime_interface_version
+ version_func.argtypes = []
+ version_func.restype = c_int
+ tbb_iface_ver = version_func()
+ if tbb_iface_ver < 12060: # magic number from TBB
+ msg = ("The TBB threading layer requires TBB "
+ "version 2021 update 6 or later i.e., "
+ "TBB_INTERFACE_VERSION >= 12060. Found "
+ "TBB_INTERFACE_VERSION = %s. The TBB "
+ "threading layer is disabled.") % tbb_iface_ver
+ problem = errors.NumbaWarning(msg)
+ warnings.warn(problem)
+ raise ImportError("Problem with TBB. Reason: %s" % msg)
+ except (ValueError, OSError) as e:
+ # Translate as an ImportError for consistent error class use, this error
+ # will never materialise
+ raise ImportError("Problem with TBB. Reason: %s" % e)
+
+
+def _launch_threads():
+ if not _backend_init_process_lock:
+ _set_init_process_lock()
+
+ with _backend_init_process_lock:
+ with _backend_init_thread_lock:
+ global _is_initialized
+ if _is_initialized:
+ return
+
+ def select_known_backend(backend):
+ """
+ Loads a specific threading layer backend based on string
+ """
+ lib = None
+ if backend.startswith("tbb"):
+ try:
+ # check if TBB is present and compatible
+ _check_tbb_version_compatible()
+ # now try and load the backend
+ from numba.np.ufunc import tbbpool as lib
+ except ImportError:
+ pass
+ elif backend.startswith("omp"):
+ # TODO: Check that if MKL is present that it is a version
+ # that understands GNU OMP might be present
+ try:
+ from numba.np.ufunc import omppool as lib
+ except ImportError:
+ pass
+ elif backend.startswith("workqueue"):
+ from numba.np.ufunc import workqueue as lib
+ else:
+ msg = "Unknown value specified for threading layer: %s"
+ raise ValueError(msg % backend)
+ return lib
+
+ def select_from_backends(backends):
+ """
+ Selects from presented backends and returns the first working
+ """
+ lib = None
+ for backend in backends:
+ lib = select_known_backend(backend)
+ if lib is not None:
+ break
+ else:
+ backend = ''
+ return lib, backend
+
+ t = str(config.THREADING_LAYER).lower()
+ namedbackends = config.THREADING_LAYER_PRIORITY
+ if not (len(namedbackends) == 3 and
+ set(namedbackends) == {'tbb', 'omp', 'workqueue'}):
+ raise ValueError(
+ "THREADING_LAYER_PRIORITY invalid: %s. "
+ "It must be a permutation of "
+ "{'tbb', 'omp', 'workqueue'}"
+ % namedbackends
+ )
+
+ lib = None
+ err_helpers = dict()
+ err_helpers['TBB'] = ("Intel TBB is required, try:\n"
+ "$ conda/pip install tbb")
+ err_helpers['OSX_OMP'] = ("Intel OpenMP is required, try:\n"
+ "$ conda/pip install intel-openmp")
+ requirements = []
+
+ def raise_with_hint(required):
+ errmsg = "No threading layer could be loaded.\n%s"
+ hintmsg = "HINT:\n%s"
+ if len(required) == 0:
+ hint = ''
+ if len(required) == 1:
+ hint = hintmsg % err_helpers[required[0]]
+ if len(required) > 1:
+ options = '\nOR\n'.join([err_helpers[x] for x in required])
+ hint = hintmsg % ("One of:\n%s" % options)
+ raise ValueError(errmsg % hint)
+
+ if t in namedbackends:
+ # Try and load the specific named backend
+ lib = select_known_backend(t)
+ if not lib:
+ # something is missing preventing a valid backend from
+ # loading, set requirements for hinting
+ if t == 'tbb':
+ requirements.append('TBB')
+ elif t == 'omp' and _IS_OSX:
+ requirements.append('OSX_OMP')
+ libname = t
+ elif t in ['threadsafe', 'forksafe', 'safe']:
+ # User wants a specific behaviour...
+ available = ['tbb']
+ requirements.append('TBB')
+ if t == "safe":
+ # "safe" is TBB, which is fork and threadsafe everywhere
+ pass
+ elif t == "threadsafe":
+ if _IS_OSX:
+ requirements.append('OSX_OMP')
+ # omp is threadsafe everywhere
+ available.append('omp')
+ elif t == "forksafe":
+ # everywhere apart from linux (GNU OpenMP) has a guaranteed
+ # forksafe OpenMP, as OpenMP has better performance, prefer
+ # this to workqueue
+ if not _IS_LINUX:
+ available.append('omp')
+ if _IS_OSX:
+ requirements.append('OSX_OMP')
+ # workqueue is forksafe everywhere
+ available.append('workqueue')
+ else: # unreachable
+ msg = "No threading layer available for purpose %s"
+ raise ValueError(msg % t)
+ # select amongst available
+ lib, libname = select_from_backends(available)
+ elif t == 'default':
+ # If default is supplied, try them in order, tbb, omp,
+ # workqueue
+ lib, libname = select_from_backends(namedbackends)
+ if not lib:
+ # set requirements for hinting
+ requirements.append('TBB')
+ if _IS_OSX:
+ requirements.append('OSX_OMP')
+ else:
+ msg = "The threading layer requested '%s' is unknown to Numba."
+ raise ValueError(msg % t)
+
+ # No lib found, raise and hint
+ if not lib:
+ raise_with_hint(requirements)
+
+ ll.add_symbol('numba_parallel_for', lib.parallel_for)
+ ll.add_symbol('do_scheduling_signed', lib.do_scheduling_signed)
+ ll.add_symbol('do_scheduling_unsigned', lib.do_scheduling_unsigned)
+ ll.add_symbol('allocate_sched', lib.allocate_sched)
+ ll.add_symbol('deallocate_sched', lib.deallocate_sched)
+
+ launch_threads = CFUNCTYPE(None, c_int)(lib.launch_threads)
+ launch_threads(NUM_THREADS)
+
+ _load_threading_functions(lib) # load late
+
+ # set library name so it can be queried
+ global _threading_layer
+ _threading_layer = libname
+ _is_initialized = True
+
+
+def _load_threading_functions(lib):
+
+ ll.add_symbol('get_num_threads', lib.get_num_threads)
+ ll.add_symbol('set_num_threads', lib.set_num_threads)
+ ll.add_symbol('get_thread_id', lib.get_thread_id)
+
+ global _set_num_threads
+ _set_num_threads = CFUNCTYPE(None, c_int)(lib.set_num_threads)
+ _set_num_threads(NUM_THREADS)
+
+ global _get_num_threads
+ _get_num_threads = CFUNCTYPE(c_int)(lib.get_num_threads)
+
+ global _get_thread_id
+ _get_thread_id = CFUNCTYPE(c_int)(lib.get_thread_id)
+
+ ll.add_symbol('set_parallel_chunksize', lib.set_parallel_chunksize)
+ ll.add_symbol('get_parallel_chunksize', lib.get_parallel_chunksize)
+ ll.add_symbol('get_sched_size', lib.get_sched_size)
+ global _set_parallel_chunksize
+ _set_parallel_chunksize = CFUNCTYPE(c_uint,
+ c_uint)(lib.set_parallel_chunksize)
+ global _get_parallel_chunksize
+ _get_parallel_chunksize = CFUNCTYPE(c_uint)(lib.get_parallel_chunksize)
+ global _get_sched_size
+ _get_sched_size = CFUNCTYPE(c_uint,
+ c_uint,
+ c_uint,
+ POINTER(c_int),
+ POINTER(c_int))(lib.get_sched_size)
+
+
+# Some helpers to make set_num_threads jittable
+
+def gen_snt_check():
+ from numba.core.config import NUMBA_NUM_THREADS
+ msg = "The number of threads must be between 1 and %s" % NUMBA_NUM_THREADS
+
+ def snt_check(n):
+ if n > NUMBA_NUM_THREADS or n < 1:
+ raise ValueError(msg)
+ return snt_check
+
+
+snt_check = gen_snt_check()
+
+
+@overload(snt_check)
+def ol_snt_check(n):
+ return snt_check
+
+
+def set_num_threads(n):
+ """
+ Set the number of threads to use for parallel execution.
+
+ By default, all :obj:`numba.config.NUMBA_NUM_THREADS` threads are used.
+
+ This functionality works by masking out threads that are not used.
+ Therefore, the number of threads *n* must be less than or equal to
+ :obj:`~.NUMBA_NUM_THREADS`, the total number of threads that are launched.
+ See its documentation for more details.
+
+ This function can be used inside of a jitted function.
+
+ Parameters
+ ----------
+ n: The number of threads. Must be between 1 and NUMBA_NUM_THREADS.
+
+ See Also
+ --------
+ get_num_threads, numba.config.NUMBA_NUM_THREADS,
+ numba.config.NUMBA_DEFAULT_NUM_THREADS, :envvar:`NUMBA_NUM_THREADS`
+
+ """
+ _launch_threads()
+ if not isinstance(n, (int, np.integer)):
+ raise TypeError("The number of threads specified must be an integer")
+ snt_check(n)
+ _set_num_threads(n)
+
+
+@overload(set_num_threads)
+def ol_set_num_threads(n):
+ _launch_threads()
+ if not isinstance(n, types.Integer):
+ msg = "The number of threads specified must be an integer"
+ raise errors.TypingError(msg)
+
+ def impl(n):
+ snt_check(n)
+ _set_num_threads(n)
+ return impl
+
+
+def get_num_threads():
+ """
+ Get the number of threads used for parallel execution.
+
+ By default (if :func:`~.set_num_threads` is never called), all
+ :obj:`numba.config.NUMBA_NUM_THREADS` threads are used.
+
+ This number is less than or equal to the total number of threads that are
+ launched, :obj:`numba.config.NUMBA_NUM_THREADS`.
+
+ This function can be used inside of a jitted function.
+
+ Returns
+ -------
+ The number of threads.
+
+ See Also
+ --------
+ set_num_threads, numba.config.NUMBA_NUM_THREADS,
+ numba.config.NUMBA_DEFAULT_NUM_THREADS, :envvar:`NUMBA_NUM_THREADS`
+
+ """
+ _launch_threads()
+ num_threads = _get_num_threads()
+ if num_threads <= 0:
+ raise RuntimeError("Invalid number of threads. "
+ "This likely indicates a bug in Numba. "
+ "(thread_id=%s, num_threads=%s)" %
+ (get_thread_id(), num_threads))
+ return num_threads
+
+
+@overload(get_num_threads)
+def ol_get_num_threads():
+ _launch_threads()
+
+ def impl():
+ num_threads = _get_num_threads()
+ if num_threads <= 0:
+ print("Broken thread_id: ", get_thread_id())
+ print("num_threads: ", num_threads)
+ raise RuntimeError("Invalid number of threads. "
+ "This likely indicates a bug in Numba.")
+ return num_threads
+ return impl
+
+
+@intrinsic
+def _iget_num_threads(typingctx):
+ _launch_threads()
+
+ def codegen(context, builder, signature, args):
+ mod = builder.module
+ fnty = ir.FunctionType(cgutils.intp_t, [])
+ fn = cgutils.get_or_insert_function(mod, fnty, "get_num_threads")
+ return builder.call(fn, [])
+ return signature(types.intp), codegen
+
+
+def get_thread_id():
+ """
+ Returns a unique ID for each thread in the range 0 (inclusive)
+ to :func:`~.get_num_threads` (exclusive).
+ """
+ # Called from the interpreter directly, this should return 0
+ # Called from a sequential JIT region, this should return 0
+ # Called from a parallel JIT region, this should return 0..N
+ # Called from objmode in a parallel JIT region, this should return 0..N
+ _launch_threads()
+ return _get_thread_id()
+
+
+@overload(get_thread_id)
+def ol_get_thread_id():
+ _launch_threads()
+
+ def impl():
+ return _iget_thread_id()
+ return impl
+
+
+@intrinsic
+def _iget_thread_id(typingctx):
+ def codegen(context, builder, signature, args):
+ mod = builder.module
+ fnty = ir.FunctionType(cgutils.intp_t, [])
+ fn = cgutils.get_or_insert_function(mod, fnty, "get_thread_id")
+ return builder.call(fn, [])
+ return signature(types.intp), codegen
+
+
+_DYLD_WORKAROUND_SET = 'NUMBA_DYLD_WORKAROUND' in os.environ
+_DYLD_WORKAROUND_VAL = int(os.environ.get('NUMBA_DYLD_WORKAROUND', 0))
+
+if _DYLD_WORKAROUND_SET and _DYLD_WORKAROUND_VAL:
+ _launch_threads()
+
+
+def set_parallel_chunksize(n):
+ _launch_threads()
+ if not isinstance(n, (int, np.integer)):
+ raise TypeError("The parallel chunksize must be an integer")
+ global _set_parallel_chunksize
+ if n < 0:
+ raise ValueError("chunksize must be greater than or equal to zero")
+ return _set_parallel_chunksize(n)
+
+
+def get_parallel_chunksize():
+ _launch_threads()
+ global _get_parallel_chunksize
+ return _get_parallel_chunksize()
+
+
+@overload(set_parallel_chunksize)
+def ol_set_parallel_chunksize(n):
+ _launch_threads()
+ if not isinstance(n, types.Integer):
+ msg = "The parallel chunksize must be an integer"
+ raise errors.TypingError(msg)
+
+ def impl(n):
+ if n < 0:
+ raise ValueError("chunksize must be greater than or equal to zero")
+ return _set_parallel_chunksize(n)
+ return impl
+
+
+@overload(get_parallel_chunksize)
+def ol_get_parallel_chunksize():
+ _launch_threads()
+
+ def impl():
+ return _get_parallel_chunksize()
+ return impl
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/np/ufunc/sigparse.py b/tool_server/.venv/lib/python3.12/site-packages/numba/np/ufunc/sigparse.py
new file mode 100644
index 0000000000000000000000000000000000000000..67ca346c903e578653cd72a861d05ee5462c2ab3
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/np/ufunc/sigparse.py
@@ -0,0 +1,63 @@
+import tokenize
+import string
+
+
+def parse_signature(sig):
+ '''Parse generalized ufunc signature.
+
+ NOTE: ',' (COMMA) is a delimiter; not separator.
+ This means trailing comma is legal.
+ '''
+ def stripws(s):
+ return ''.join(c for c in s if c not in string.whitespace)
+
+ def tokenizer(src):
+ def readline():
+ yield src
+ gen = readline()
+ return tokenize.generate_tokens(lambda: next(gen))
+
+ def parse(src):
+ tokgen = tokenizer(src)
+ while True:
+ tok = next(tokgen)
+ if tok[1] == '(':
+ symbols = []
+ while True:
+ tok = next(tokgen)
+ if tok[1] == ')':
+ break
+ elif tok[0] == tokenize.NAME:
+ symbols.append(tok[1])
+ elif tok[1] == ',':
+ continue
+ else:
+ raise ValueError('bad token in signature "%s"' % tok[1])
+ yield tuple(symbols)
+ tok = next(tokgen)
+ if tok[1] == ',':
+ continue
+ elif tokenize.ISEOF(tok[0]):
+ break
+ elif tokenize.ISEOF(tok[0]):
+ break
+ else:
+ raise ValueError('bad token in signature "%s"' % tok[1])
+
+ ins, _, outs = stripws(sig).partition('->')
+ inputs = list(parse(ins))
+ outputs = list(parse(outs))
+
+ # check that all output symbols are defined in the inputs
+ isym = set()
+ osym = set()
+ for grp in inputs:
+ isym |= set(grp)
+ for grp in outputs:
+ osym |= set(grp)
+
+ diff = osym.difference(isym)
+ if diff:
+ raise NameError('undefined output symbols: %s' % ','.join(sorted(diff)))
+
+ return inputs, outputs
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/np/ufunc/tbbpool.cpython-312-x86_64-linux-gnu.so b/tool_server/.venv/lib/python3.12/site-packages/numba/np/ufunc/tbbpool.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..02ac7b8aa6abf355fad6023a79fe187dcc5f93c5
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/np/ufunc/tbbpool.cpython-312-x86_64-linux-gnu.so
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:14fc8f4b5293dc740f146c1c27de1d486701fa5c36f2556f6e6b62874996bbcc
+size 1054537
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/np/ufunc/ufunc_base.py b/tool_server/.venv/lib/python3.12/site-packages/numba/np/ufunc/ufunc_base.py
new file mode 100644
index 0000000000000000000000000000000000000000..6864b724eda599f0e3b252006f9be37139ae35a1
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/np/ufunc/ufunc_base.py
@@ -0,0 +1,113 @@
+from numba.np import numpy_support
+from numba.core import types
+
+
+class UfuncLowererBase:
+ '''Callable class responsible for lowering calls to a specific gufunc.
+ '''
+ def __init__(self, ufunc, make_kernel_fn, make_ufunc_kernel_fn):
+ self.ufunc = ufunc
+ self.make_ufunc_kernel_fn = make_ufunc_kernel_fn
+ self.kernel = make_kernel_fn(ufunc)
+ self.libs = []
+
+ def __call__(self, context, builder, sig, args):
+ return self.make_ufunc_kernel_fn(context, builder, sig, args,
+ self.ufunc, self.kernel)
+
+
+class UfuncBase:
+
+ @property
+ def nin(self):
+ return self.ufunc.nin
+
+ @property
+ def nout(self):
+ return self.ufunc.nout
+
+ @property
+ def nargs(self):
+ return self.ufunc.nargs
+
+ @property
+ def ntypes(self):
+ return self.ufunc.ntypes
+
+ @property
+ def types(self):
+ return self.ufunc.types
+
+ @property
+ def identity(self):
+ return self.ufunc.identity
+
+ @property
+ def signature(self):
+ return self.ufunc.signature
+
+ @property
+ def accumulate(self):
+ return self.ufunc.accumulate
+
+ @property
+ def at(self):
+ return self.ufunc.at
+
+ @property
+ def outer(self):
+ return self.ufunc.outer
+
+ @property
+ def reduce(self):
+ return self.ufunc.reduce
+
+ @property
+ def reduceat(self):
+ return self.ufunc.reduceat
+
+ def disable_compile(self):
+ """
+ Disable the compilation of new signatures at call time.
+ """
+ # If disabling compilation then there must be at least one signature
+ assert len(self._dispatcher.overloads) > 0
+ self._frozen = True
+
+ def _install_cg(self, targetctx=None):
+ """
+ Install an implementation function for a GUFunc/DUFunc object in the
+ given target context. If no target context is given, then
+ _install_cg() installs into the target context of the
+ dispatcher object (should be same default context used by
+ jit() and njit()).
+ """
+ if targetctx is None:
+ targetctx = self._dispatcher.targetdescr.target_context
+ _any = types.Any
+ _arr = types.Array
+ # Either all outputs are explicit or none of them are
+ sig0 = (_any,) * self.ufunc.nin + (_arr,) * self.ufunc.nout
+ sig1 = (_any,) * self.ufunc.nin
+ targetctx.insert_func_defn(
+ [(self._lower_me, self, sig) for sig in (sig0, sig1)])
+
+ def find_ewise_function(self, ewise_types):
+ """
+ Given a tuple of element-wise argument types, find a matching
+ signature in the dispatcher.
+
+ Return a 2-tuple containing the matching signature, and
+ compilation result. Will return two None's if no matching
+ signature was found.
+ """
+ if self._frozen:
+ # If we cannot compile, coerce to the best matching loop
+ loop = numpy_support.ufunc_find_matching_loop(self, ewise_types)
+ if loop is None:
+ return None, None
+ ewise_types = tuple(loop.inputs + loop.outputs)[:len(ewise_types)]
+ for sig, cres in self._dispatcher.overloads.items():
+ if self.match_signature(ewise_types, sig):
+ return sig, cres
+ return None, None
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/np/ufunc/ufuncbuilder.py b/tool_server/.venv/lib/python3.12/site-packages/numba/np/ufunc/ufuncbuilder.py
new file mode 100644
index 0000000000000000000000000000000000000000..e23ec229e5d8a53441281924103f4a75b75c574e
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/np/ufunc/ufuncbuilder.py
@@ -0,0 +1,434 @@
+# -*- coding: utf-8 -*-
+
+import inspect
+import warnings
+from contextlib import contextmanager
+
+from numba.core import config, targetconfig
+from numba.core.decorators import jit
+from numba.core.descriptors import TargetDescriptor
+from numba.core.extending import is_jitted
+from numba.core.errors import NumbaDeprecationWarning
+from numba.core.options import TargetOptions, include_default_options
+from numba.core.registry import cpu_target
+from numba.core.target_extension import dispatcher_registry, target_registry
+from numba.core import utils, types, serialize, compiler, sigutils
+from numba.np.numpy_support import as_dtype
+from numba.np.ufunc import _internal
+from numba.np.ufunc.sigparse import parse_signature
+from numba.np.ufunc.wrappers import build_ufunc_wrapper, build_gufunc_wrapper
+from numba.core.caching import FunctionCache, NullCache
+from numba.core.compiler_lock import global_compiler_lock
+
+
+_options_mixin = include_default_options(
+ "nopython",
+ "forceobj",
+ "boundscheck",
+ "fastmath",
+ "writable_args"
+)
+
+
+class UFuncTargetOptions(_options_mixin, TargetOptions):
+
+ def finalize(self, flags, options):
+ if not flags.is_set("enable_pyobject"):
+ flags.enable_pyobject = True
+
+ if not flags.is_set("enable_looplift"):
+ flags.enable_looplift = True
+
+ flags.inherit_if_not_set("nrt", default=True)
+
+ if not flags.is_set("debuginfo"):
+ flags.debuginfo = config.DEBUGINFO_DEFAULT
+
+ if not flags.is_set("boundscheck"):
+ flags.boundscheck = flags.debuginfo
+
+ flags.enable_pyobject_looplift = True
+
+ flags.inherit_if_not_set("fastmath")
+
+
+class UFuncTarget(TargetDescriptor):
+ options = UFuncTargetOptions
+
+ def __init__(self):
+ super().__init__('ufunc')
+
+ @property
+ def typing_context(self):
+ return cpu_target.typing_context
+
+ @property
+ def target_context(self):
+ return cpu_target.target_context
+
+
+ufunc_target = UFuncTarget()
+
+
+class UFuncDispatcher(serialize.ReduceMixin):
+ """
+ An object handling compilation of various signatures for a ufunc.
+ """
+ targetdescr = ufunc_target
+
+ def __init__(self, py_func, locals={}, targetoptions={}):
+ self.py_func = py_func
+ self.overloads = utils.UniqueDict()
+ self.targetoptions = targetoptions
+ self.locals = locals
+ self.cache = NullCache()
+
+ def _reduce_states(self):
+ """
+ NOTE: part of ReduceMixin protocol
+ """
+ return dict(
+ pyfunc=self.py_func,
+ locals=self.locals,
+ targetoptions=self.targetoptions,
+ )
+
+ @classmethod
+ def _rebuild(cls, pyfunc, locals, targetoptions):
+ """
+ NOTE: part of ReduceMixin protocol
+ """
+ return cls(py_func=pyfunc, locals=locals, targetoptions=targetoptions)
+
+ def enable_caching(self):
+ self.cache = FunctionCache(self.py_func)
+
+ def compile(self, sig, locals={}, **targetoptions):
+ locs = self.locals.copy()
+ locs.update(locals)
+
+ topt = self.targetoptions.copy()
+ topt.update(targetoptions)
+
+ flags = compiler.Flags()
+ self.targetdescr.options.parse_as_flags(flags, topt)
+
+ flags.no_cpython_wrapper = True
+ flags.error_model = "numpy"
+ # Disable loop lifting
+ # The feature requires a real
+ # python function
+ flags.enable_looplift = False
+
+ return self._compile_core(sig, flags, locals)
+
+ def _compile_core(self, sig, flags, locals):
+ """
+ Trigger the compiler on the core function or load a previously
+ compiled version from the cache. Returns the CompileResult.
+ """
+ typingctx = self.targetdescr.typing_context
+ targetctx = self.targetdescr.target_context
+
+ @contextmanager
+ def store_overloads_on_success():
+ # use to ensure overloads are stored on success
+ try:
+ yield
+ except Exception:
+ raise
+ else:
+ exists = self.overloads.get(cres.signature)
+ if exists is None:
+ self.overloads[cres.signature] = cres
+
+ # Use cache and compiler in a critical section
+ with global_compiler_lock:
+ with targetconfig.ConfigStack().enter(flags.copy()):
+ with store_overloads_on_success():
+ # attempt look up of existing
+ cres = self.cache.load_overload(sig, targetctx)
+ if cres is not None:
+ return cres
+
+ # Compile
+ args, return_type = sigutils.normalize_signature(sig)
+ cres = compiler.compile_extra(typingctx, targetctx,
+ self.py_func, args=args,
+ return_type=return_type,
+ flags=flags, locals=locals)
+
+ # cache lookup failed before so safe to save
+ self.cache.save_overload(sig, cres)
+
+ return cres
+
+
+dispatcher_registry[target_registry['npyufunc']] = UFuncDispatcher
+
+
+# Utility functions
+
+def _compile_element_wise_function(nb_func, targetoptions, sig):
+ # Do compilation
+ # Return CompileResult to test
+ cres = nb_func.compile(sig, **targetoptions)
+ args, return_type = sigutils.normalize_signature(sig)
+ return cres, args, return_type
+
+
+def _finalize_ufunc_signature(cres, args, return_type):
+ '''Given a compilation result, argument types, and a return type,
+ build a valid Numba signature after validating that it doesn't
+ violate the constraints for the compilation mode.
+ '''
+ if return_type is None:
+ if cres.objectmode:
+ # Object mode is used and return type is not specified
+ raise TypeError("return type must be specified for object mode")
+ else:
+ return_type = cres.signature.return_type
+
+ assert return_type != types.pyobject
+ return return_type(*args)
+
+
+def _build_element_wise_ufunc_wrapper(cres, signature):
+ '''Build a wrapper for the ufunc loop entry point given by the
+ compilation result object, using the element-wise signature.
+ '''
+ ctx = cres.target_context
+ library = cres.library
+ fname = cres.fndesc.llvm_func_name
+
+ with global_compiler_lock:
+ info = build_ufunc_wrapper(library, ctx, fname, signature,
+ cres.objectmode, cres)
+ ptr = info.library.get_pointer_to_function(info.name)
+ # Get dtypes
+ dtypenums = [as_dtype(a).num for a in signature.args]
+ dtypenums.append(as_dtype(signature.return_type).num)
+ return dtypenums, ptr, cres.environment
+
+
+_identities = {
+ 0: _internal.PyUFunc_Zero,
+ 1: _internal.PyUFunc_One,
+ None: _internal.PyUFunc_None,
+ "reorderable": _internal.PyUFunc_ReorderableNone,
+}
+
+
+def parse_identity(identity):
+ """
+ Parse an identity value and return the corresponding low-level value
+ for Numpy.
+ """
+ try:
+ identity = _identities[identity]
+ except KeyError:
+ raise ValueError("Invalid identity value %r" % (identity,))
+ return identity
+
+
+@contextmanager
+def _suppress_deprecation_warning_nopython_not_supplied():
+ """This suppresses the NumbaDeprecationWarning that occurs through the use
+ of `jit` without the `nopython` kwarg. This use of `jit` occurs in a few
+ places in the `{g,}ufunc` mechanism in Numba, predominantly to wrap the
+ "kernel" function."""
+ with warnings.catch_warnings():
+ warnings.filterwarnings('ignore',
+ category=NumbaDeprecationWarning,
+ message=(".*The 'nopython' keyword argument "
+ "was not supplied*"),)
+ yield
+
+
+# Class definitions
+
+class _BaseUFuncBuilder(object):
+
+ def add(self, sig=None):
+ if hasattr(self, 'targetoptions'):
+ targetoptions = self.targetoptions
+ else:
+ targetoptions = self.nb_func.targetoptions
+ cres, args, return_type = _compile_element_wise_function(
+ self.nb_func, targetoptions, sig)
+ sig = self._finalize_signature(cres, args, return_type)
+ self._sigs.append(sig)
+ self._cres[sig] = cres
+ return cres
+
+ def disable_compile(self):
+ """
+ Disable the compilation of new signatures at call time.
+ """
+ # Override this for implementations that support lazy compilation
+
+
+class UFuncBuilder(_BaseUFuncBuilder):
+
+ def __init__(self, py_func, identity=None, cache=False, targetoptions={}):
+ if is_jitted(py_func):
+ py_func = py_func.py_func
+ self.py_func = py_func
+ self.identity = parse_identity(identity)
+ with _suppress_deprecation_warning_nopython_not_supplied():
+ self.nb_func = jit(_target='npyufunc',
+ cache=cache,
+ **targetoptions)(py_func)
+ self._sigs = []
+ self._cres = {}
+
+ def _finalize_signature(self, cres, args, return_type):
+ '''Slated for deprecation, use ufuncbuilder._finalize_ufunc_signature()
+ instead.
+ '''
+ return _finalize_ufunc_signature(cres, args, return_type)
+
+ def build_ufunc(self):
+ with global_compiler_lock:
+ dtypelist = []
+ ptrlist = []
+ if not self.nb_func:
+ raise TypeError("No definition")
+
+ # Get signature in the order they are added
+ keepalive = []
+ cres = None
+ for sig in self._sigs:
+ cres = self._cres[sig]
+ dtypenums, ptr, env = self.build(cres, sig)
+ dtypelist.append(dtypenums)
+ ptrlist.append(int(ptr))
+ keepalive.append((cres.library, env))
+
+ datlist = [None] * len(ptrlist)
+
+ if cres is None:
+ argspec = inspect.getfullargspec(self.py_func)
+ inct = len(argspec.args)
+ else:
+ inct = len(cres.signature.args)
+ outct = 1
+
+ # Becareful that fromfunc does not provide full error checking yet.
+ # If typenum is out-of-bound, we have nasty memory corruptions.
+ # For instance, -1 for typenum will cause segfault.
+ # If elements of type-list (2nd arg) is tuple instead,
+ # there will also memory corruption. (Seems like code rewrite.)
+ ufunc = _internal.fromfunc(
+ self.py_func.__name__, self.py_func.__doc__,
+ ptrlist, dtypelist, inct, outct, datlist,
+ keepalive, self.identity,
+ )
+
+ return ufunc
+
+ def build(self, cres, signature):
+ '''Slated for deprecation, use
+ ufuncbuilder._build_element_wise_ufunc_wrapper().
+ '''
+ return _build_element_wise_ufunc_wrapper(cres, signature)
+
+
+class GUFuncBuilder(_BaseUFuncBuilder):
+
+ # TODO handle scalar
+ def __init__(self, py_func, signature, identity=None, cache=False,
+ targetoptions={}, writable_args=()):
+ self.py_func = py_func
+ self.identity = parse_identity(identity)
+ with _suppress_deprecation_warning_nopython_not_supplied():
+ self.nb_func = jit(_target='npyufunc', cache=cache)(py_func)
+ self.signature = signature
+ self.sin, self.sout = parse_signature(signature)
+ self.targetoptions = targetoptions
+ self.cache = cache
+ self._sigs = []
+ self._cres = {}
+
+ transform_arg = _get_transform_arg(py_func)
+ self.writable_args = tuple([transform_arg(a) for a in writable_args])
+
+ def _finalize_signature(self, cres, args, return_type):
+ if not cres.objectmode and cres.signature.return_type != types.void:
+ raise TypeError("gufunc kernel must have void return type")
+
+ if return_type is None:
+ return_type = types.void
+
+ return return_type(*args)
+
+ @global_compiler_lock
+ def build_ufunc(self):
+ type_list = []
+ func_list = []
+ if not self.nb_func:
+ raise TypeError("No definition")
+
+ # Get signature in the order they are added
+ keepalive = []
+ for sig in self._sigs:
+ cres = self._cres[sig]
+ dtypenums, ptr, env = self.build(cres)
+ type_list.append(dtypenums)
+ func_list.append(int(ptr))
+ keepalive.append((cres.library, env))
+
+ datalist = [None] * len(func_list)
+
+ nin = len(self.sin)
+ nout = len(self.sout)
+
+ # Pass envs to fromfuncsig to bind to the lifetime of the ufunc object
+ ufunc = _internal.fromfunc(
+ self.py_func.__name__, self.py_func.__doc__,
+ func_list, type_list, nin, nout, datalist,
+ keepalive, self.identity, self.signature, self.writable_args
+ )
+ return ufunc
+
+ def build(self, cres):
+ """
+ Returns (dtype numbers, function ptr, EnvironmentObject)
+ """
+ # Builder wrapper for ufunc entry point
+ signature = cres.signature
+ info = build_gufunc_wrapper(
+ self.py_func, cres, self.sin, self.sout,
+ cache=self.cache, is_parfors=False,
+ )
+
+ env = info.env
+ ptr = info.library.get_pointer_to_function(info.name)
+ # Get dtypes
+ dtypenums = []
+ for a in signature.args:
+ if isinstance(a, types.Array):
+ ty = a.dtype
+ else:
+ ty = a
+ dtypenums.append(as_dtype(ty).num)
+ return dtypenums, ptr, env
+
+
+def _get_transform_arg(py_func):
+ """Return function that transform arg into index"""
+ args = inspect.getfullargspec(py_func).args
+ pos_by_arg = {arg: i for i, arg in enumerate(args)}
+
+ def transform_arg(arg):
+ if isinstance(arg, int):
+ return arg
+
+ try:
+ return pos_by_arg[arg]
+ except KeyError:
+ msg = (f"Specified writable arg {arg} not found in arg list "
+ f"{args} for function {py_func.__qualname__}")
+ raise RuntimeError(msg)
+
+ return transform_arg
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/np/ufunc/workqueue.cpython-312-x86_64-linux-gnu.so b/tool_server/.venv/lib/python3.12/site-packages/numba/np/ufunc/workqueue.cpython-312-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..21c929ddeae07c624cb1289260c9d2e527f923af
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/np/ufunc/workqueue.cpython-312-x86_64-linux-gnu.so
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:60d23006f648ad74172daaf0a51235c45155bef4a39fde4e191b0a5a463cdc7f
+size 606576
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/np/ufunc/wrappers.py b/tool_server/.venv/lib/python3.12/site-packages/numba/np/ufunc/wrappers.py
new file mode 100644
index 0000000000000000000000000000000000000000..ef37c40770aeed73253b6e0709ad5c4f5a8de352
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/np/ufunc/wrappers.py
@@ -0,0 +1,743 @@
+from collections import namedtuple
+
+import numpy as np
+
+from llvmlite.ir import Constant, IRBuilder
+from llvmlite import ir
+
+from numba.core import types, cgutils
+from numba.core.compiler_lock import global_compiler_lock
+from numba.core.caching import make_library_cache, NullCache
+
+
+_wrapper_info = namedtuple('_wrapper_info', ['library', 'env', 'name'])
+
+
+def _build_ufunc_loop_body(load, store, context, func, builder, arrays, out,
+ offsets, store_offset, signature, pyapi, env):
+ elems = load()
+
+ # Compute
+ status, retval = context.call_conv.call_function(builder, func,
+ signature.return_type,
+ signature.args, elems)
+
+ # Store
+ with builder.if_else(status.is_ok, likely=True) as (if_ok, if_error):
+ with if_ok:
+ store(retval)
+ with if_error:
+ gil = pyapi.gil_ensure()
+ context.call_conv.raise_error(builder, pyapi, status)
+ pyapi.gil_release(gil)
+
+ # increment indices
+ for off, ary in zip(offsets, arrays):
+ builder.store(builder.add(builder.load(off), ary.step), off)
+
+ builder.store(builder.add(builder.load(store_offset), out.step),
+ store_offset)
+
+ return status.code
+
+
+def _build_ufunc_loop_body_objmode(load, store, context, func, builder,
+ arrays, out, offsets, store_offset,
+ signature, env, pyapi):
+ elems = load()
+
+ # Compute
+ _objargs = [types.pyobject] * len(signature.args)
+ # We need to push the error indicator to avoid it messing with
+ # the ufunc's execution. We restore it unless the ufunc raised
+ # a new error.
+ with pyapi.err_push(keep_new=True):
+ status, retval = context.call_conv.call_function(builder, func,
+ types.pyobject,
+ _objargs, elems)
+ # Release owned reference to arguments
+ for elem in elems:
+ pyapi.decref(elem)
+ # NOTE: if an error occurred, it will be caught by the Numpy machinery
+
+ # Store
+ store(retval)
+
+ # increment indices
+ for off, ary in zip(offsets, arrays):
+ builder.store(builder.add(builder.load(off), ary.step), off)
+
+ builder.store(builder.add(builder.load(store_offset), out.step),
+ store_offset)
+
+ return status.code
+
+
+def build_slow_loop_body(context, func, builder, arrays, out, offsets,
+ store_offset, signature, pyapi, env):
+ def load():
+ elems = [ary.load_direct(builder.load(off))
+ for off, ary in zip(offsets, arrays)]
+ return elems
+
+ def store(retval):
+ out.store_direct(retval, builder.load(store_offset))
+
+ return _build_ufunc_loop_body(load, store, context, func, builder, arrays,
+ out, offsets, store_offset, signature, pyapi,
+ env=env)
+
+
+def build_obj_loop_body(context, func, builder, arrays, out, offsets,
+ store_offset, signature, pyapi, envptr, env):
+ env_body = context.get_env_body(builder, envptr)
+ env_manager = pyapi.get_env_manager(env, env_body, envptr)
+
+ def load():
+ # Load
+ elems = [ary.load_direct(builder.load(off))
+ for off, ary in zip(offsets, arrays)]
+ # Box
+ elems = [pyapi.from_native_value(t, v, env_manager)
+ for v, t in zip(elems, signature.args)]
+ return elems
+
+ def store(retval):
+ is_ok = cgutils.is_not_null(builder, retval)
+ # If an error is raised by the object mode ufunc, it will
+ # simply get caught by the Numpy ufunc machinery.
+ with builder.if_then(is_ok, likely=True):
+ # Unbox
+ native = pyapi.to_native_value(signature.return_type, retval)
+ assert native.cleanup is None
+ # Store
+ out.store_direct(native.value, builder.load(store_offset))
+ # Release owned reference
+ pyapi.decref(retval)
+
+ return _build_ufunc_loop_body_objmode(load, store, context, func, builder,
+ arrays, out, offsets, store_offset,
+ signature, envptr, pyapi)
+
+
+def build_fast_loop_body(context, func, builder, arrays, out, offsets,
+ store_offset, signature, ind, pyapi, env):
+ def load():
+ elems = [ary.load_aligned(ind)
+ for ary in arrays]
+ return elems
+
+ def store(retval):
+ out.store_aligned(retval, ind)
+
+ return _build_ufunc_loop_body(load, store, context, func, builder, arrays,
+ out, offsets, store_offset, signature, pyapi,
+ env=env)
+
+
+def build_ufunc_wrapper(library, context, fname, signature, objmode, cres):
+ """
+ Wrap the scalar function with a loop that iterates over the arguments
+
+ Returns
+ -------
+ (library, env, name)
+ """
+ assert isinstance(fname, str)
+ byte_t = ir.IntType(8)
+ byte_ptr_t = ir.PointerType(byte_t)
+ byte_ptr_ptr_t = ir.PointerType(byte_ptr_t)
+ intp_t = context.get_value_type(types.intp)
+ intp_ptr_t = ir.PointerType(intp_t)
+
+ fnty = ir.FunctionType(ir.VoidType(), [byte_ptr_ptr_t, intp_ptr_t,
+ intp_ptr_t, byte_ptr_t])
+
+ wrapperlib = context.codegen().create_library('ufunc_wrapper')
+ wrapper_module = wrapperlib.create_ir_module('')
+ if objmode:
+ func_type = context.call_conv.get_function_type(
+ types.pyobject, [types.pyobject] * len(signature.args))
+ else:
+ func_type = context.call_conv.get_function_type(
+ signature.return_type, signature.args)
+
+ func = ir.Function(wrapper_module, func_type, name=fname)
+ func.attributes.add("alwaysinline")
+
+ wrapper = ir.Function(wrapper_module, fnty, "__ufunc__." + func.name)
+ arg_args, arg_dims, arg_steps, arg_data = wrapper.args
+ arg_args.name = "args"
+ arg_dims.name = "dims"
+ arg_steps.name = "steps"
+ arg_data.name = "data"
+
+ builder = IRBuilder(wrapper.append_basic_block("entry"))
+
+ # Prepare Environment
+ envname = context.get_env_name(cres.fndesc)
+ env = cres.environment
+ envptr = builder.load(context.declare_env_global(builder.module, envname))
+
+ # Emit loop
+ loopcount = builder.load(arg_dims, name="loopcount")
+
+ # Prepare inputs
+ arrays = []
+ for i, typ in enumerate(signature.args):
+ arrays.append(UArrayArg(context, builder, arg_args, arg_steps, i, typ))
+
+ # Prepare output
+ out = UArrayArg(context, builder, arg_args, arg_steps, len(arrays),
+ signature.return_type)
+
+ # Setup indices
+ offsets = []
+ zero = context.get_constant(types.intp, 0)
+ for _ in arrays:
+ p = cgutils.alloca_once(builder, intp_t)
+ offsets.append(p)
+ builder.store(zero, p)
+
+ store_offset = cgutils.alloca_once(builder, intp_t)
+ builder.store(zero, store_offset)
+
+ unit_strided = cgutils.true_bit
+ for ary in arrays:
+ unit_strided = builder.and_(unit_strided, ary.is_unit_strided)
+
+ pyapi = context.get_python_api(builder)
+ if objmode:
+ # General loop
+ gil = pyapi.gil_ensure()
+ with cgutils.for_range(builder, loopcount, intp=intp_t):
+ build_obj_loop_body(
+ context, func, builder, arrays, out, offsets,
+ store_offset, signature, pyapi, envptr, env,
+ )
+ pyapi.gil_release(gil)
+ builder.ret_void()
+
+ else:
+ with builder.if_else(unit_strided) as (is_unit_strided, is_strided):
+ with is_unit_strided:
+ with cgutils.for_range(builder, loopcount, intp=intp_t) as loop:
+ build_fast_loop_body(
+ context, func, builder, arrays, out, offsets,
+ store_offset, signature, loop.index, pyapi,
+ env=envptr,
+ )
+
+ with is_strided:
+ # General loop
+ with cgutils.for_range(builder, loopcount, intp=intp_t):
+ build_slow_loop_body(
+ context, func, builder, arrays, out, offsets,
+ store_offset, signature, pyapi,
+ env=envptr,
+ )
+
+ builder.ret_void()
+ del builder
+
+ # Link and finalize
+ wrapperlib.add_ir_module(wrapper_module)
+ wrapperlib.add_linking_library(library)
+ return _wrapper_info(library=wrapperlib, env=env, name=wrapper.name)
+
+
+class UArrayArg(object):
+ def __init__(self, context, builder, args, steps, i, fe_type):
+ self.context = context
+ self.builder = builder
+ self.fe_type = fe_type
+ offset = self.context.get_constant(types.intp, i)
+ offseted_args = self.builder.load(builder.gep(args, [offset]))
+ data_type = context.get_data_type(fe_type)
+ self.dataptr = self.builder.bitcast(offseted_args,
+ data_type.as_pointer())
+ sizeof = self.context.get_abi_sizeof(data_type)
+ self.abisize = self.context.get_constant(types.intp, sizeof)
+ offseted_step = self.builder.gep(steps, [offset])
+ self.step = self.builder.load(offseted_step)
+ self.is_unit_strided = builder.icmp_unsigned('==',
+ self.abisize, self.step)
+ self.builder = builder
+
+ def load_direct(self, byteoffset):
+ """
+ Generic load from the given *byteoffset*. load_aligned() is
+ preferred if possible.
+ """
+ ptr = cgutils.pointer_add(self.builder, self.dataptr, byteoffset)
+ return self.context.unpack_value(self.builder, self.fe_type, ptr)
+
+ def load_aligned(self, ind):
+ # Using gep() instead of explicit pointer addition helps LLVM
+ # vectorize the loop.
+ ptr = self.builder.gep(self.dataptr, [ind])
+ return self.context.unpack_value(self.builder, self.fe_type, ptr)
+
+ def store_direct(self, value, byteoffset):
+ ptr = cgutils.pointer_add(self.builder, self.dataptr, byteoffset)
+ self.context.pack_value(self.builder, self.fe_type, value, ptr)
+
+ def store_aligned(self, value, ind):
+ ptr = self.builder.gep(self.dataptr, [ind])
+ self.context.pack_value(self.builder, self.fe_type, value, ptr)
+
+
+GufWrapperCache = make_library_cache('guf')
+
+
+class _GufuncWrapper(object):
+ def __init__(self, py_func, cres, sin, sout, cache, is_parfors):
+ """
+ The *is_parfors* argument is a boolean that indicates if the GUfunc
+ being built is to be used as a ParFors kernel. If True, it disables
+ the caching on the wrapper as a separate unit because it will be linked
+ into the caller function and cached along with it.
+ """
+ self.py_func = py_func
+ self.cres = cres
+ self.sin = sin
+ self.sout = sout
+ self.is_objectmode = self.signature.return_type == types.pyobject
+ self.cache = (GufWrapperCache(py_func=self.py_func)
+ if cache else NullCache())
+ self.is_parfors = bool(is_parfors)
+
+ @property
+ def library(self):
+ return self.cres.library
+
+ @property
+ def context(self):
+ return self.cres.target_context
+
+ @property
+ def call_conv(self):
+ return self.context.call_conv
+
+ @property
+ def signature(self):
+ return self.cres.signature
+
+ @property
+ def fndesc(self):
+ return self.cres.fndesc
+
+ @property
+ def env(self):
+ return self.cres.environment
+
+ def _wrapper_function_type(self):
+ byte_t = ir.IntType(8)
+ byte_ptr_t = ir.PointerType(byte_t)
+ byte_ptr_ptr_t = ir.PointerType(byte_ptr_t)
+ intp_t = self.context.get_value_type(types.intp)
+ intp_ptr_t = ir.PointerType(intp_t)
+
+ fnty = ir.FunctionType(ir.VoidType(), [byte_ptr_ptr_t, intp_ptr_t,
+ intp_ptr_t, byte_ptr_t])
+ return fnty
+
+ def _build_wrapper(self, library, name):
+ """
+ The LLVM IRBuilder code to create the gufunc wrapper.
+ The *library* arg is the CodeLibrary to which the wrapper should
+ be added. The *name* arg is the name of the wrapper function being
+ created.
+ """
+ intp_t = self.context.get_value_type(types.intp)
+ fnty = self._wrapper_function_type()
+
+ wrapper_module = library.create_ir_module('_gufunc_wrapper')
+ func_type = self.call_conv.get_function_type(self.fndesc.restype,
+ self.fndesc.argtypes)
+ fname = self.fndesc.llvm_func_name
+ func = ir.Function(wrapper_module, func_type, name=fname)
+
+ func.attributes.add("alwaysinline")
+ wrapper = ir.Function(wrapper_module, fnty, name)
+ # The use of weak_odr linkage avoids the function being dropped due
+ # to the order in which the wrappers and the user function are linked.
+ wrapper.linkage = 'weak_odr'
+ arg_args, arg_dims, arg_steps, arg_data = wrapper.args
+ arg_args.name = "args"
+ arg_dims.name = "dims"
+ arg_steps.name = "steps"
+ arg_data.name = "data"
+
+ builder = IRBuilder(wrapper.append_basic_block("entry"))
+ loopcount = builder.load(arg_dims, name="loopcount")
+ pyapi = self.context.get_python_api(builder)
+
+ # Unpack shapes
+ unique_syms = set()
+ for grp in (self.sin, self.sout):
+ for syms in grp:
+ unique_syms |= set(syms)
+
+ sym_map = {}
+ for syms in self.sin:
+ for s in syms:
+ if s not in sym_map:
+ sym_map[s] = len(sym_map)
+
+ sym_dim = {}
+ for s, i in sym_map.items():
+ sym_dim[s] = builder.load(builder.gep(arg_dims,
+ [self.context.get_constant(
+ types.intp,
+ i + 1)]))
+
+ # Prepare inputs
+ arrays = []
+ step_offset = len(self.sin) + len(self.sout)
+ for i, (typ, sym) in enumerate(zip(self.signature.args,
+ self.sin + self.sout)):
+ ary = GUArrayArg(self.context, builder, arg_args,
+ arg_steps, i, step_offset, typ, sym, sym_dim)
+ step_offset += len(sym)
+ arrays.append(ary)
+
+ bbreturn = builder.append_basic_block('.return')
+
+ # Prologue
+ self.gen_prologue(builder, pyapi)
+
+ # Loop
+ with cgutils.for_range(builder, loopcount, intp=intp_t) as loop:
+ args = [a.get_array_at_offset(loop.index) for a in arrays]
+ innercall, error = self.gen_loop_body(builder, pyapi, func, args)
+ # If error, escape
+ cgutils.cbranch_or_continue(builder, error, bbreturn)
+
+ builder.branch(bbreturn)
+ builder.position_at_end(bbreturn)
+
+ # Epilogue
+ self.gen_epilogue(builder, pyapi)
+
+ builder.ret_void()
+
+ # Link
+ library.add_ir_module(wrapper_module)
+ library.add_linking_library(self.library)
+
+ def _compile_wrapper(self, wrapper_name):
+ # Gufunc created by Parfors?
+ if self.is_parfors:
+ # No wrapper caching for parfors
+ wrapperlib = self.context.codegen().create_library(str(self))
+ # Build wrapper
+ self._build_wrapper(wrapperlib, wrapper_name)
+ # Non-parfors?
+ else:
+ # Use cache and compiler in a critical section
+ wrapperlib = self.cache.load_overload(
+ self.cres.signature, self.cres.target_context,
+ )
+ if wrapperlib is None:
+ # Create library and enable caching
+ wrapperlib = self.context.codegen().create_library(str(self))
+ wrapperlib.enable_object_caching()
+ # Build wrapper
+ self._build_wrapper(wrapperlib, wrapper_name)
+ # Cache
+ self.cache.save_overload(self.cres.signature, wrapperlib)
+
+ return wrapperlib
+
+ @global_compiler_lock
+ def build(self):
+ wrapper_name = "__gufunc__." + self.fndesc.mangled_name
+ wrapperlib = self._compile_wrapper(wrapper_name)
+ return _wrapper_info(
+ library=wrapperlib, env=self.env, name=wrapper_name,
+ )
+
+ def gen_loop_body(self, builder, pyapi, func, args):
+ status, retval = self.call_conv.call_function(
+ builder, func, self.signature.return_type, self.signature.args,
+ args)
+
+ with builder.if_then(status.is_error, likely=False):
+ gil = pyapi.gil_ensure()
+ self.context.call_conv.raise_error(builder, pyapi, status)
+ pyapi.gil_release(gil)
+
+ return status.code, status.is_error
+
+ def gen_prologue(self, builder, pyapi):
+ pass # Do nothing
+
+ def gen_epilogue(self, builder, pyapi):
+ pass # Do nothing
+
+
+class _GufuncObjectWrapper(_GufuncWrapper):
+ def gen_loop_body(self, builder, pyapi, func, args):
+ innercall, error = _prepare_call_to_object_mode(self.context,
+ builder, pyapi, func,
+ self.signature,
+ args)
+ return innercall, error
+
+ def gen_prologue(self, builder, pyapi):
+ # Acquire the GIL
+ self.gil = pyapi.gil_ensure()
+
+ def gen_epilogue(self, builder, pyapi):
+ # Release GIL
+ pyapi.gil_release(self.gil)
+
+
+def build_gufunc_wrapper(py_func, cres, sin, sout, cache, is_parfors):
+ signature = cres.signature
+ wrapcls = (_GufuncObjectWrapper
+ if signature.return_type == types.pyobject
+ else _GufuncWrapper)
+ return wrapcls(
+ py_func, cres, sin, sout, cache, is_parfors=is_parfors,
+ ).build()
+
+
+def _prepare_call_to_object_mode(context, builder, pyapi, func,
+ signature, args):
+ mod = builder.module
+
+ bb_core_return = builder.append_basic_block('ufunc.core.return')
+
+ # Call to
+ # PyObject* ndarray_new(int nd,
+ # npy_intp *dims, /* shape */
+ # npy_intp *strides,
+ # void* data,
+ # int type_num,
+ # int itemsize)
+
+ ll_int = context.get_value_type(types.int32)
+ ll_intp = context.get_value_type(types.intp)
+ ll_intp_ptr = ir.PointerType(ll_intp)
+ ll_voidptr = context.get_value_type(types.voidptr)
+ ll_pyobj = context.get_value_type(types.pyobject)
+ fnty = ir.FunctionType(ll_pyobj, [ll_int, ll_intp_ptr,
+ ll_intp_ptr, ll_voidptr,
+ ll_int, ll_int])
+
+ fn_array_new = cgutils.get_or_insert_function(mod, fnty,
+ "numba_ndarray_new")
+
+ # Convert each llarray into pyobject
+ error_pointer = cgutils.alloca_once(builder, ir.IntType(1), name='error')
+ builder.store(cgutils.true_bit, error_pointer)
+
+ # The PyObject* arguments to the kernel function
+ object_args = []
+ object_pointers = []
+
+ for i, (arg, argty) in enumerate(zip(args, signature.args)):
+ # Allocate NULL-initialized slot for this argument
+ objptr = cgutils.alloca_once(builder, ll_pyobj, zfill=True)
+ object_pointers.append(objptr)
+
+ if isinstance(argty, types.Array):
+ # Special case arrays: we don't need full-blown NRT reflection
+ # since the argument will be gone at the end of the kernel
+ arycls = context.make_array(argty)
+ array = arycls(context, builder, value=arg)
+
+ zero = Constant(ll_int, 0)
+
+ # Extract members of the llarray
+ nd = Constant(ll_int, argty.ndim)
+ dims = builder.gep(array._get_ptr_by_name('shape'), [zero, zero])
+ strides = builder.gep(array._get_ptr_by_name('strides'),
+ [zero, zero])
+ data = builder.bitcast(array.data, ll_voidptr)
+ dtype = np.dtype(str(argty.dtype))
+
+ # Prepare other info for reconstruction of the PyArray
+ type_num = Constant(ll_int, dtype.num)
+ itemsize = Constant(ll_int, dtype.itemsize)
+
+ # Call helper to reconstruct PyArray objects
+ obj = builder.call(fn_array_new, [nd, dims, strides, data,
+ type_num, itemsize])
+ else:
+ # Other argument types => use generic boxing
+ obj = pyapi.from_native_value(argty, arg)
+
+ builder.store(obj, objptr)
+ object_args.append(obj)
+
+ obj_is_null = cgutils.is_null(builder, obj)
+ builder.store(obj_is_null, error_pointer)
+ cgutils.cbranch_or_continue(builder, obj_is_null, bb_core_return)
+
+ # Call ufunc core function
+ object_sig = [types.pyobject] * len(object_args)
+
+ status, retval = context.call_conv.call_function(
+ builder, func, types.pyobject, object_sig,
+ object_args)
+ builder.store(status.is_error, error_pointer)
+
+ # Release returned object
+ pyapi.decref(retval)
+
+ builder.branch(bb_core_return)
+ # At return block
+ builder.position_at_end(bb_core_return)
+
+ # Release argument objects
+ for objptr in object_pointers:
+ pyapi.decref(builder.load(objptr))
+
+ innercall = status.code
+ return innercall, builder.load(error_pointer)
+
+
+class GUArrayArg(object):
+ def __init__(self, context, builder, args, steps, i, step_offset,
+ typ, syms, sym_dim):
+
+ self.context = context
+ self.builder = builder
+
+ offset = context.get_constant(types.intp, i)
+
+ data = builder.load(builder.gep(args, [offset], name="data.ptr"),
+ name="data")
+ self.data = data
+
+ core_step_ptr = builder.gep(steps, [offset], name="core.step.ptr")
+ core_step = builder.load(core_step_ptr)
+
+ if isinstance(typ, types.Array):
+ as_scalar = not syms
+
+ # number of symbol in the shape spec should match the dimension
+ # of the array type.
+ if len(syms) != typ.ndim:
+ if len(syms) == 0 and typ.ndim == 1:
+ # This is an exception for handling scalar argument.
+ # The type can be 1D array for scalar.
+ # In the future, we may deprecate this exception.
+ pass
+ else:
+ raise TypeError("type and shape signature mismatch for arg "
+ "#{0}".format(i + 1))
+
+ ndim = typ.ndim
+ shape = [sym_dim[s] for s in syms]
+ strides = []
+
+ for j in range(ndim):
+ stepptr = builder.gep(steps,
+ [context.get_constant(types.intp,
+ step_offset + j)],
+ name="step.ptr")
+ step = builder.load(stepptr)
+ strides.append(step)
+
+ ldcls = (_ArrayAsScalarArgLoader
+ if as_scalar
+ else _ArrayArgLoader)
+
+ self._loader = ldcls(dtype=typ.dtype,
+ ndim=ndim,
+ core_step=core_step,
+ as_scalar=as_scalar,
+ shape=shape,
+ strides=strides)
+ else:
+ # If typ is not an array
+ if syms:
+ raise TypeError("scalar type {0} given for non scalar "
+ "argument #{1}".format(typ, i + 1))
+ self._loader = _ScalarArgLoader(dtype=typ, stride=core_step)
+
+ def get_array_at_offset(self, ind):
+ return self._loader.load(context=self.context, builder=self.builder,
+ data=self.data, ind=ind)
+
+
+class _ScalarArgLoader(object):
+ """
+ Handle GFunc argument loading where a scalar type is used in the core
+ function.
+ Note: It still has a stride because the input to the gufunc can be an array
+ for this argument.
+ """
+
+ def __init__(self, dtype, stride):
+ self.dtype = dtype
+ self.stride = stride
+
+ def load(self, context, builder, data, ind):
+ # Load at base + ind * stride
+ data = builder.gep(data, [builder.mul(ind, self.stride)])
+ dptr = builder.bitcast(data,
+ context.get_data_type(self.dtype).as_pointer())
+ return builder.load(dptr)
+
+
+class _ArrayArgLoader(object):
+ """
+ Handle GUFunc argument loading where an array is expected.
+ """
+
+ def __init__(self, dtype, ndim, core_step, as_scalar, shape, strides):
+ self.dtype = dtype
+ self.ndim = ndim
+ self.core_step = core_step
+ self.as_scalar = as_scalar
+ self.shape = shape
+ self.strides = strides
+
+ def load(self, context, builder, data, ind):
+ arytyp = types.Array(dtype=self.dtype, ndim=self.ndim, layout="A")
+ arycls = context.make_array(arytyp)
+
+ array = arycls(context, builder)
+ offseted_data = cgutils.pointer_add(builder,
+ data,
+ builder.mul(self.core_step,
+ ind))
+
+ shape, strides = self._shape_and_strides(context, builder)
+
+ itemsize = context.get_abi_sizeof(context.get_data_type(self.dtype))
+ context.populate_array(array,
+ data=builder.bitcast(offseted_data,
+ array.data.type),
+ shape=shape,
+ strides=strides,
+ itemsize=context.get_constant(types.intp,
+ itemsize),
+ meminfo=None)
+
+ return array._getvalue()
+
+ def _shape_and_strides(self, context, builder):
+ shape = cgutils.pack_array(builder, self.shape)
+ strides = cgutils.pack_array(builder, self.strides)
+ return shape, strides
+
+
+class _ArrayAsScalarArgLoader(_ArrayArgLoader):
+ """
+ Handle GUFunc argument loading where the shape signature specifies
+ a scalar "()" but a 1D array is used for the type of the core function.
+ """
+
+ def _shape_and_strides(self, context, builder):
+ # Set shape and strides for a 1D size 1 array
+ one = context.get_constant(types.intp, 1)
+ zero = context.get_constant(types.intp, 0)
+ shape = cgutils.pack_array(builder, [one])
+ strides = cgutils.pack_array(builder, [zero])
+ return shape, strides
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/np/unsafe/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/numba/np/unsafe/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/np/unsafe/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/np/unsafe/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7e901ee728c59819b319ecce12e3e28f8794e7be
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/np/unsafe/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/np/unsafe/__pycache__/ndarray.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/np/unsafe/__pycache__/ndarray.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..349b47f30a73b89452fcdb00370e4ad490956899
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/np/unsafe/__pycache__/ndarray.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/np/unsafe/ndarray.py b/tool_server/.venv/lib/python3.12/site-packages/numba/np/unsafe/ndarray.py
new file mode 100644
index 0000000000000000000000000000000000000000..cd3e2d171ada1273e25ea895f6d0e38eb30d3a9c
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/np/unsafe/ndarray.py
@@ -0,0 +1,79 @@
+"""
+This file provides internal compiler utilities that support certain special
+operations with numpy.
+"""
+from numba.core import types, typing
+from numba.core.cgutils import unpack_tuple
+from numba.core.extending import intrinsic
+from numba.core.imputils import impl_ret_new_ref
+from numba.core.errors import RequireLiteralValue, TypingError
+
+from numba.cpython.unsafe.tuple import tuple_setitem
+
+
+@intrinsic
+def empty_inferred(typingctx, shape):
+ """A version of numpy.empty whose dtype is inferred by the type system.
+
+ Expects `shape` to be a int-tuple.
+
+ There is special logic in the type-inferencer to handle the "refine"-ing
+ of undefined dtype.
+ """
+ from numba.np.arrayobj import _empty_nd_impl
+
+ def codegen(context, builder, signature, args):
+ # check that the return type is now defined
+ arrty = signature.return_type
+ assert arrty.is_precise()
+ shapes = unpack_tuple(builder, args[0])
+ # redirect implementation to np.empty
+ res = _empty_nd_impl(context, builder, arrty, shapes)
+ return impl_ret_new_ref(context, builder, arrty, res._getvalue())
+
+ # make function signature
+ nd = len(shape)
+ array_ty = types.Array(ndim=nd, layout='C', dtype=types.undefined)
+ sig = array_ty(shape)
+ return sig, codegen
+
+
+@intrinsic
+def to_fixed_tuple(typingctx, array, length):
+ """Convert *array* into a tuple of *length*
+
+ Returns ``UniTuple(array.dtype, length)``
+
+ ** Warning **
+ - No boundchecking.
+ If *length* is longer than *array.size*, the behavior is undefined.
+ """
+ if not isinstance(length, types.IntegerLiteral):
+ raise RequireLiteralValue('*length* argument must be a constant')
+
+ if array.ndim != 1:
+ raise TypingError("Not supported on array.ndim={}".format(array.ndim))
+
+ # Determine types
+ tuple_size = int(length.literal_value)
+ tuple_type = types.UniTuple(dtype=array.dtype, count=tuple_size)
+ sig = tuple_type(array, length)
+
+ def codegen(context, builder, signature, args):
+ def impl(array, length, empty_tuple):
+ out = empty_tuple
+ for i in range(length):
+ out = tuple_setitem(out, i, array[i])
+ return out
+
+ inner_argtypes = [signature.args[0], types.intp, tuple_type]
+ inner_sig = typing.signature(tuple_type, *inner_argtypes)
+ ll_idx_type = context.get_value_type(types.intp)
+ # Allocate an empty tuple
+ empty_tuple = context.get_constant_undef(tuple_type)
+ inner_args = [args[0], ll_idx_type(tuple_size), empty_tuple]
+
+ res = context.compile_internal(builder, impl, inner_sig, inner_args)
+ return res
+
+ return sig, codegen
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/parfors/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/parfors/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8afac865847ca75e7e814fa86a655e45770d7bd4
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/parfors/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/parfors/__pycache__/array_analysis.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/parfors/__pycache__/array_analysis.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b150b14dba59571937b24ea483ffe678c301d6be
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/parfors/__pycache__/array_analysis.cpython-312.pyc
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:22830b5a6b61cf9ebada8ace5bfb514f84f7c28718751b1ff6e29a64c58f24e0
+size 138139
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/parfors/__pycache__/parfor.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/parfors/__pycache__/parfor.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..454166f11d35e10616d622070ba74dc1aff8b2a5
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/parfors/__pycache__/parfor.cpython-312.pyc
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:95630d5c649d36029b2737efec253032ba8556b15f6cfe82829127581945e54a
+size 244298
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/parfors/__pycache__/parfor_lowering.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/parfors/__pycache__/parfor_lowering.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8ce15625ce459c7274e2a60e376ad09f81aec347
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/parfors/__pycache__/parfor_lowering.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/parfors/__pycache__/parfor_lowering_utils.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/parfors/__pycache__/parfor_lowering_utils.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5794dc1bae8c9dcfe5a47b79ebe9c6a4f229cb1f
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/parfors/__pycache__/parfor_lowering_utils.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/pycc/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/pycc/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..eb7e632524b6a8eb05c6d274e60ddbc894370912
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/pycc/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/pycc/__pycache__/cc.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/pycc/__pycache__/cc.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6475b891d4fc10578e86e31de0461b0b8c5eec9c
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/pycc/__pycache__/cc.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/pycc/__pycache__/compiler.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/pycc/__pycache__/compiler.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e36c969ca561addf9e5e25a3de7d28f931543b96
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/pycc/__pycache__/compiler.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/pycc/__pycache__/decorators.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/pycc/__pycache__/decorators.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..80ed9329c7b9351400d8a10878e670a452f178ea
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/pycc/__pycache__/decorators.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/pycc/__pycache__/llvm_types.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/pycc/__pycache__/llvm_types.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..622f8d3ab8da707c23d651e86a9d6ce4c39aa74e
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/pycc/__pycache__/llvm_types.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/pycc/__pycache__/platform.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/pycc/__pycache__/platform.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..392b4015d1fef06b2b733dba54c70a3626c91516
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/pycc/__pycache__/platform.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/scripts/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/scripts/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b7321ef6f99f959c5b5ea9c8d1d844ddf4961592
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/scripts/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/scripts/__pycache__/generate_lower_listing.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/scripts/__pycache__/generate_lower_listing.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..52200a72d39e67ec6e8c5da37f7ceea13e4eb6c4
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/scripts/__pycache__/generate_lower_listing.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/stencils/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/stencils/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cea08a393f61e35aced2ce60a6da81226190972e
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/stencils/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/stencils/__pycache__/stencil.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/stencils/__pycache__/stencil.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..effc1ac98a4bd8904bfd77ae16a282bc1dba8c3c
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/stencils/__pycache__/stencil.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/stencils/__pycache__/stencilparfor.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/stencils/__pycache__/stencilparfor.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5f2b5d99717776a4ed89f7995417130bb0f8ac60
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/stencils/__pycache__/stencilparfor.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/testing/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/testing/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9276a243a61a9702ba5892b10d2433927a9aedbd
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/testing/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/testing/__pycache__/__main__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/testing/__pycache__/__main__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7d1dfda8c8db0356c332b9c9d55c5db56ec05e81
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/testing/__pycache__/__main__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/testing/__pycache__/_runtests.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/testing/__pycache__/_runtests.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..04261b2e6cbddbbd46533740ef88043282f0925a
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/testing/__pycache__/_runtests.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/testing/__pycache__/loader.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/testing/__pycache__/loader.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e0faefc4ba57aa165bdbbd0fdf37041cf1dce539
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/testing/__pycache__/loader.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/testing/__pycache__/main.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/testing/__pycache__/main.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..66e48d7bc9f4a96b5b2fb18cef1d5b006ba6aab7
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/testing/__pycache__/main.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/testing/__pycache__/notebook.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/testing/__pycache__/notebook.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f5234372f46d42dc4340ec337e125ec7cd4b6b09
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/testing/__pycache__/notebook.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7df919db11ee47265c66f2ea3eaa38f376dd4229
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/annotation_usecases.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/annotation_usecases.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6cea37403a0e653857584229ace2020ba9e18c31
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/annotation_usecases.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/cache_usecases.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/cache_usecases.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cf5d122ad6c8e1057f0497d0c63459934c9962d6
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/cache_usecases.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/cffi_usecases.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/cffi_usecases.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4b6ab16533eb324405ca724b403a88c568a5417d
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/cffi_usecases.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/cfunc_cache_usecases.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/cfunc_cache_usecases.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d56014bc21af34a7dff8973741b43cd7ad158afe
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/cfunc_cache_usecases.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/chained_assign_usecases.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/chained_assign_usecases.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7325789737be068f71d209710f4008480f5e1896
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/chained_assign_usecases.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/cloudpickle_main_class.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/cloudpickle_main_class.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..de7bcabc69414b9c442b20cc6ec36df15e8d11b2
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/cloudpickle_main_class.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/compile_with_pycc.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/compile_with_pycc.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e5271c074725a20482027bc8a3d863256eb22430
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/compile_with_pycc.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/complex_usecases.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/complex_usecases.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..56c95454000ac1ec90205ec933df0b5ec423d4b1
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/complex_usecases.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/ctypes_usecases.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/ctypes_usecases.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8a385c955ff8f38c9445957d4fafa215c0c15d27
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/ctypes_usecases.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/doctest_usecase.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/doctest_usecase.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7c04d3217599d109505ca8eb3b123bb7c28e64c5
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/doctest_usecase.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/dummy_module.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/dummy_module.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f7b22c3921eb3afd0c3e3e4c912d8e1d9d9f43b0
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/dummy_module.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/enum_usecases.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/enum_usecases.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..25844d7c190ae2d46a39e244c8b051a668ed4e02
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/enum_usecases.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/error_usecases.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/error_usecases.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..72fd1f68180ef54bcbe9ae839e14695658a65bbf
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/error_usecases.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/errorhandling_usecases.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/errorhandling_usecases.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a6cf0549e186f55c4e987f94048db16835e157dc
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/errorhandling_usecases.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/gdb_support.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/gdb_support.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e40f1d0f9192ee6681437fc23879eff2b5540cfb
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/gdb_support.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/inlining_usecases.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/inlining_usecases.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9b20e42951b4324b3d14c18bb151d6a305aa4251
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/inlining_usecases.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/matmul_usecase.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/matmul_usecase.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..772bab69b819a9fd4ae901f4d0e2a8ef384f6f3e
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/matmul_usecase.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/orphaned_semaphore_usecase.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/orphaned_semaphore_usecase.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..16d692e73d338d354809f57e850e5b8c5cc40697
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/orphaned_semaphore_usecase.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/overload_usecases.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/overload_usecases.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7d2669088ffcaababbf51d4f92daf2c2434fdc2e
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/overload_usecases.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/parfor_iss9490_usecase.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/parfor_iss9490_usecase.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..53fa60b0862337960133722341b41e9027698786
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/parfor_iss9490_usecase.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/parfors_cache_usecases.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/parfors_cache_usecases.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ee61d4d0001ecada3a66b83f317c3eedf243e434
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/parfors_cache_usecases.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/pdlike_usecase.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/pdlike_usecase.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..76627c85fa663beeab038544b55efa4400fb6ef3
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/pdlike_usecase.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/recursion_usecases.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/recursion_usecases.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..83b1128dd264748324ef2a2a43ea00b666cf20c0
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/recursion_usecases.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/serialize_usecases.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/serialize_usecases.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..adaca02ca117b038047ec555721c32e1df47abf5
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/serialize_usecases.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/support.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/support.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..097a0a0b5cce8b8303ecf4f75ad3a4862feaa4b1
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/support.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_alignment.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_alignment.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a99e879c62b3e999589f40a98a93014bc940ae17
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_alignment.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_analysis.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_analysis.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f6e8d64a3115c3dce87e99ab528477ef5d5203bc
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_analysis.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_annotations.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_annotations.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9dbf5e6d7d70c13e12ad8db313d7481fee2b065c
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_annotations.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_api.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_api.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2602d95a1c2fd674e739811324e2152fa35abded
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_api.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_array_analysis.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_array_analysis.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f47b687feb5c9d10108e40b60faa181832528894
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_array_analysis.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_array_attr.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_array_attr.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f1265b588007896c421d8ca26b0f19036c3c2f66
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_array_attr.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_array_constants.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_array_constants.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..80b3fd1eb935986d43c4b5a9730d7e622a1f359e
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_array_constants.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_array_exprs.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_array_exprs.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1615f9163b141c2e408bd4e84aef70812caebe2f
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_array_exprs.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_array_iterators.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_array_iterators.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d250d68754d24fded73f92a80b7f56ae02eb894b
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_array_iterators.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_array_manipulation.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_array_manipulation.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a2cc7ab65481cf99f7a211df765ebb05714f6425
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_array_manipulation.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_array_methods.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_array_methods.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..61117ddd5522b45e84716fb8aaa9fc71f4e35dda
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_array_methods.cpython-312.pyc
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:9b532847e7cfa479df7b8862972df253e96c4c2d2f0e8febc2806890f96d5e46
+size 112489
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_array_reductions.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_array_reductions.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8a50b0704576d34eef29d94c40aaec5e5d77a375
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_array_reductions.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_array_return.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_array_return.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3e653db0d0a93fcda17c4d0f712c9d215891eed5
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_array_return.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_asnumbatype.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_asnumbatype.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..22c402eb7a8f54133f7aed90973d61a1fe119e28
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_asnumbatype.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_auto_constants.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_auto_constants.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f71681e4e1d88f359205cbd0983b46397134295e
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_auto_constants.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_blackscholes.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_blackscholes.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b5dc6e4e76d47d877698f045e9591e4848b620e4
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_blackscholes.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_boundscheck.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_boundscheck.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ac5463c145f84c0f134c71462ac0544a5539117b
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_boundscheck.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_buffer_protocol.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_buffer_protocol.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..622c5cc4bf26eaa294cba4848d644d2a69c2cf6f
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_buffer_protocol.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_builtins.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_builtins.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9c1d936a93a349d83586a409fc803c2841c8a588
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_builtins.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_byteflow.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_byteflow.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..32a8f84c729c355adf9049ea81d53df3f9f10b32
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_byteflow.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_caching.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_caching.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d30651d005e89d4b57ff16cfd3edbf9f824d170e
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_caching.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_casting.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_casting.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3ec33086421a2c7dde98b865bb9128539e33b7cf
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_casting.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_cffi.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_cffi.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9c536d9250b642c3336376d992f12063190140f3
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_cffi.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_cfunc.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_cfunc.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..15ccae0dcd987c8922e6ff40c65819b2a6a56f27
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_cfunc.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_cgutils.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_cgutils.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4bd5f9601ecec092e4d68a1128119a180560700e
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_cgutils.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_chained_assign.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_chained_assign.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..32d6bcabf317640cbbcea8cba2a33f2a95d01740
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_chained_assign.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_chrome_trace.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_chrome_trace.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..498f192415962c324e87d04f401c33fc2195d770
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_chrome_trace.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_cli.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_cli.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d6a704360b799493e96ed2d678db15e498836ccd
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_cli.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_closure.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_closure.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d10b0b822c3fcb7ca8d534f39be3af0201a7fb91
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_closure.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_codegen.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_codegen.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3d686e1207abaeae681ae88cc2bf242f23250974
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_codegen.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_compile_cache.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_compile_cache.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..258a775f76cd89b0ccd247984be963b3018d37de
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_compile_cache.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_compiler_flags.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_compiler_flags.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8574c0ac85ea874e24db2278665540c530381d04
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_compiler_flags.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_compiler_lock.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_compiler_lock.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5cdd9c38aee22944a372136b2cbbe08550b4e5ce
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_compiler_lock.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_complex.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_complex.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b8f21ce234ccc31b47ac74ac78fc0eba4cd67262
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_complex.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_comprehension.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_comprehension.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a62308d01ab04a8dd56a5cd0af59687c37190b11
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_comprehension.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_conditions_as_predicates.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_conditions_as_predicates.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..84cf43436bacf93c6c4c325b0095e490e84ee4df
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_conditions_as_predicates.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_config.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_config.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4f2b9c8fb5fc1356ff027f6866d3619e7dbf6c95
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_config.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_conversion.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_conversion.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e221f8326962f54a9884f5ae0cdd6dad7c5714a4
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_conversion.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_copy_propagate.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_copy_propagate.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f0784df040adb17cf830baae90c34027c8b89566
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_copy_propagate.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_ctypes.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_ctypes.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..dc210562edcf2bf31d4e54664324f012690ca018
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_ctypes.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_dataflow.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_dataflow.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a202f5c98dac5df5eed1ed633ae684967c6855d5
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_dataflow.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_datamodel.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_datamodel.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5a99dc7444ae0098a523e9a562d0f74db17a2e35
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_datamodel.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_debug.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_debug.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ad7b1968512e0491a85e3d921e8ecfdecdede992
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_debug.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_debuginfo.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_debuginfo.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..70753f6d2d1540121ddbc2d89a0f5a405f9ebf65
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_debuginfo.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_deprecations.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_deprecations.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..23f708be9e6c18dc88ddad6af4dc833c0443fba1
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_deprecations.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_dictimpl.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_dictimpl.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5e1935d0be65e03a7ff48199f55adba06aed9a7a
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_dictimpl.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_dictobject.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_dictobject.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7d1fe17fdff1a5ad133b5bf2186ae41515e5a865
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_dictobject.cpython-312.pyc
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:21daec11559451d5ea98c71d7f145ad69dd1a0eb08bae32b4004c3fb5f4092a6
+size 138382
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_dicts.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_dicts.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6cb10078b6ad3d792e3c716e1e3cb602523e18f6
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_dicts.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_dispatcher.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_dispatcher.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..68c007d27b48a35b3b4c9d859375a99f8195dcd9
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_dispatcher.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_doctest.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_doctest.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b3b6032132b0f46d4032d9c426b0df29ed2b2955
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_doctest.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_dyn_array.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_dyn_array.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..16e0b8f08bca4358f7deb60d3561e7b6e80c968b
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_dyn_array.cpython-312.pyc
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:56edc4e596def096244feda44e17865d8e6824ba53c2531dfab5f74aa0a7bc8b
+size 109847
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_dyn_func.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_dyn_func.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d43ae2ce33615713cb1279e6a44599beb33f34c2
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_dyn_func.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_entrypoints.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_entrypoints.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4b393177ad69d8ff75d064970df831933d5e867e
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_entrypoints.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_enums.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_enums.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9aefa27c45725c3cba06a3e221c9ca04428bcf16
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_enums.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_errorhandling.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_errorhandling.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5439312dd970a219f85e2361b983398937f54b86
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_errorhandling.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_errormodels.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_errormodels.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..11991a293933a1e9752c0e1de5d15a8906e26336
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_errormodels.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_event.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6ca0cf4144977b9371a3f2c10c136eabb2238a75
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_event.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_exceptions.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_exceptions.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6ea33ad4945aec8763d66b312e58e5d06f4ec12d
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_exceptions.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_extended_arg.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_extended_arg.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1416328f7436a248a3225b134a18011e3a69c6ba
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_extended_arg.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_extending.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_extending.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..09ccab6b68993dffc828682bd56c4ea13a22ac18
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_extending.cpython-312.pyc
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:dd153d53f2cdc1f33443354235c2d23f6e092518d4d88f0dcc35c8ec4128ef8f
+size 116386
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_extending_types.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_extending_types.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f94ad92894902a161fa82dd04da953cddb10538b
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_extending_types.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_fancy_indexing.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_fancy_indexing.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0cca0fcc77cd9b4efbc8f5ebdb36f01fccf1f355
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_fancy_indexing.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_fastmath.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_fastmath.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5eacacd91001b9cf7663409fcf31201daf7f7e94
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_fastmath.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_findlib.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_findlib.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..34b2fa6160e7b839f7de201f3aff93beb5e4e63d
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_findlib.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_firstlinefinder.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_firstlinefinder.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..dd1a591a6fd7b7f029e2137ee5171e54337e8382
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_firstlinefinder.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_flow_control.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_flow_control.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1fb3d8ddd43b224e19c1fd12a41ca469efec165c
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_flow_control.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_func_interface.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_func_interface.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6e0a9f3105913222907c47aa2cf8967f9c949fd7
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_func_interface.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_func_lifetime.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_func_lifetime.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..48a832189595bc2a5174fae1702ad0446f201e07
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_func_lifetime.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_funcdesc.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_funcdesc.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d76398f55d5b9c0401e5f190efd1c152d5f8993c
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_funcdesc.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_function_type.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_function_type.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2620c1894acf4b32114103ec612edc69a41f8367
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_function_type.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_gdb_bindings.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_gdb_bindings.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c9813864e71427e8c17abc83f0a672fada9c7230
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_gdb_bindings.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_gdb_dwarf.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_gdb_dwarf.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2b016e055e34fc94430a16aa384ac4a548de5fb7
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_gdb_dwarf.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_generators.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_generators.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0237323b7eef97d77bbf3ce912eda2b4081cd0a2
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_generators.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_getitem_on_types.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_getitem_on_types.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bf578b8d5871ce490fc53a8c186e926d4ed2e5e2
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_getitem_on_types.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_gil.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_gil.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2b41ba96fe20b7ffca3e5a3eb4b084ef57305b8b
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_gil.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_globals.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_globals.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c58ec725cc768edddf8c33751bad4b03e4128ca7
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_globals.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_hashing.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_hashing.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5e5f2183186a4d5aa94bc2e666233b344f2c028b
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_hashing.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_heapq.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_heapq.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a126bfb93070f81be69242df340538f677b8b8c1
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_heapq.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_help.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_help.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..177e6adfff1dc2289233eaad0724b08bb66fb370
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_help.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_import.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_import.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bf61f75c500cfe044b5dab4851bfde05ab74fc79
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_import.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_indexing.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_indexing.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7cf82c1f0263ac4439bd8b0f83ca49a0d8bd7251
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_indexing.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_init_utils.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_init_utils.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ae2c9cebbaf1cb7cb0aca6565441f437c0a9d6c5
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_init_utils.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_inlining.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_inlining.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a04104d69cd86859f4409ff1882856e3b5f1e735
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_inlining.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_interpreter.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_interpreter.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8ada9b5d16d86462731aad4447ca97a0ee620a7f
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_interpreter.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_interproc.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_interproc.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..763fa85cc2858779496abe7f446d964c1345a185
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_interproc.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_intwidth.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_intwidth.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7ccb0f4d699011ef9a3607aaae6124e58d715768
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_intwidth.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_ir.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_ir.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5e049da60d321921fe3bb258309b047069b474da
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_ir.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_ir_inlining.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_ir_inlining.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f1b9c9cb59f42306d1014cb0853a276387e90bac
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_ir_inlining.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_ir_utils.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_ir_utils.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..adb8c3b2abc7a45b71a63420f0da453abf1ac620
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_ir_utils.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_itanium_mangler.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_itanium_mangler.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cb4469848ec7bb87243798c0c5cc74e84345df64
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_itanium_mangler.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_iteration.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_iteration.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fa0bf712e1c0997ea3b670f12e9bba0db2e87b84
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_iteration.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_jit_module.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_jit_module.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..67b1b34c48f824a38158eef6f4d040dc40d3fe8a
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_jit_module.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_jitclasses.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_jitclasses.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..023b16db18512bce48e6ff56b96e78b83f02bb6f
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_jitclasses.cpython-312.pyc
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:4be1b079ad91ef74f964d7a05097de9af7ff0cedb010a55ce7595251b8b85f0f
+size 127966
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_jitmethod.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_jitmethod.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7d6167518307ae8e32dfaf0841f06612d3b96b44
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_jitmethod.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_linalg.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_linalg.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c925d569dda7c0bfd79cc3c07e916bb7c4f6bc1b
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_linalg.cpython-312.pyc
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:a1395261c08b2a7658348750f05e551176d2a0c836afe28d59b246499beb87e1
+size 117608
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_listimpl.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_listimpl.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4d938170639b5f0b6d18749dba20c64215bd6b70
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_listimpl.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_listobject.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_listobject.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..34c26657ee7e5a50f03dd4314df3b030bd2db103
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_listobject.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_lists.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_lists.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7ed4c18542f3f1e1b87dd74232d4593d34b8b037
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_lists.cpython-312.pyc
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:3b494e2f6f4a3180b97265897af38286688c257ae38c14a0a510cb8271edcf27
+size 103395
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_literal_dispatch.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_literal_dispatch.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bc065ca6df23d1cbd97546fbe71ed9a6abb16ec1
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_literal_dispatch.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_llvm_pass_timings.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_llvm_pass_timings.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6451e62c796517da8699f14caf7469418848bc4f
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_llvm_pass_timings.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_llvm_version_check.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_llvm_version_check.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f07068fc70893bac202162808269c9392a94d563
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_llvm_version_check.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_locals.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_locals.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..56b3f1bacf545751913a3e1366656c46f4a0e2da
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_locals.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_looplifting.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_looplifting.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..641449e64df02c3ac04654327c90b50782d4948d
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_looplifting.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_make_function_to_jit_function.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_make_function_to_jit_function.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2810e33895d1b98a1384740b4a67d347c2315978
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_make_function_to_jit_function.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_mandelbrot.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_mandelbrot.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7ab58f52f2cf4029b1301a64c7b14c46ada8513b
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_mandelbrot.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_mangling.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_mangling.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4c69ef4b40885b8964edfd7aef2b07f086971775
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_mangling.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_map_filter_reduce.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_map_filter_reduce.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b2b8949f7dc6938837255268a5c2f94e52c395d8
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_map_filter_reduce.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_mathlib.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_mathlib.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ab98c6d2800a27638ca32347c0105324bc85257a
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_mathlib.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_maxmin.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_maxmin.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..062ae6c197393b017c6a3ca6db0c98b759c65d55
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_maxmin.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_misc_coverage_support.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_misc_coverage_support.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4d206d5a735d18ea8f24cefb6c654f3a6ed47256
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_misc_coverage_support.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_mixed_tuple_unroller.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_mixed_tuple_unroller.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..70523189068a471ae8c0ef2c57c2d4576a778684
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_mixed_tuple_unroller.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_moved_modules.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_moved_modules.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1a7291b6333601c154514d265553e53d27a5ca40
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_moved_modules.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_multi3.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_multi3.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1cb2da21323d0aa8acea4bd00df769ae84d25a7a
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_multi3.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_nan.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_nan.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b59a862f38e9b439621993c55dfc59d325e3e0bc
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_nan.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_ndarray_subclasses.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_ndarray_subclasses.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f44f6a8b1080f867d6ac09e233b9d63a286b7937
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_ndarray_subclasses.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_nested_calls.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_nested_calls.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..92c2721344fd28d415f3ddf59ec6a5669325c0df
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_nested_calls.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_new_type_system.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_new_type_system.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1eca156e99b220ea485a2d4f08b1895de1bf0507
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_new_type_system.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_np_functions.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_np_functions.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..23cd047785b1e07647b7c1cd6556ccb467744d4b
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_np_functions.cpython-312.pyc
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:9df07406d93c144de6f97eb97a8833cd3cec24191b6c1712f25e97ef95b3f1f9
+size 361467
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_np_randomgen.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_np_randomgen.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..64a5897b5d35cec581d4a548cde7708b67961c19
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_np_randomgen.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_npdatetime.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_npdatetime.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ce1d291b3edac5addc6b79dc8ce3a4d0afe1429f
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_npdatetime.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_nrt.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_nrt.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..167e04f520a6f1362dce7ee3a876b00d3363163d
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_nrt.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_nrt_refct.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_nrt_refct.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7eeb43027a6a1269393829cafdd6344e4307107d
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_nrt_refct.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_num_threads.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_num_threads.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0880b41c80578ffc06533b52ea765fa19fb105e2
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_num_threads.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_numberctor.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_numberctor.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b5331105efc719cf499fcc97d71d3f9b4a990e8f
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_numberctor.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_numbers.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_numbers.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4b893a77f3f282f824c0e7562dcbd3579c6b6dd7
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_numbers.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_numconv.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_numconv.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5ad650f20d2c688f50a0ff8ffaaf0578efecdb0b
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_numconv.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_numpy_support.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_numpy_support.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..190b1dcbe6fbfe06aab5d4b723d0a5d575a76fc9
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_numpy_support.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_numpyadapt.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_numpyadapt.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..91f1396a1a5a1e050d413384b01e47686a5598a0
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_numpyadapt.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_support.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_support.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0afc1e7a8f91cf20921c7a1124dac7e9840dec1e
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_support.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_svml.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_svml.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..50793740f2e698d47b82eae5c1a5c7deaa437b21
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_svml.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_ufuncs.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_ufuncs.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9ae2479c0ec133a6da56a085c8e37015b4ffd7fc
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/__pycache__/test_ufuncs.cpython-312.pyc
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:87f35598e5e7b28e8aad7ad44c11764a1c05848e5d7968c586dff804c4251930
+size 107906
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/doc_examples/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/doc_examples/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..b2958441fe7a098eeb66fe183b62bd4ff0edbbe2
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/doc_examples/__init__.py
@@ -0,0 +1,10 @@
+from os.path import dirname
+import unittest
+from unittest.suite import TestSuite
+
+from numba.testing import load_testsuite
+
+def load_tests(loader, tests, pattern):
+ suite = TestSuite()
+ suite.addTests(load_testsuite(loader, dirname(__file__)))
+ return suite
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/doc_examples/test_examples.py b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/doc_examples/test_examples.py
new file mode 100644
index 0000000000000000000000000000000000000000..a0f7078b17d9efd2339c25b229b7e0e3281c3cbc
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/doc_examples/test_examples.py
@@ -0,0 +1,660 @@
+# Contents in this file are referenced from the sphinx-generated docs.
+# "magictoken" is used for markers as beginning and ending of example text.
+
+import sys
+import unittest
+
+from numba.tests.support import TestCase, captured_stdout
+from numba.core.config import IS_WIN32
+from numba.np.numpy_support import numpy_version
+
+
+class MatplotlibBlocker:
+ '''Blocks the import of matplotlib, so that doc examples that attempt to
+ plot the output don't result in plots popping up and blocking testing.'''
+
+ def find_spec(self, fullname, path, target=None):
+ if fullname == 'matplotlib':
+ msg = 'Blocked import of matplotlib for test suite run'
+ raise ImportError(msg)
+
+
+class DocsExamplesTest(TestCase):
+
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ self._mpl_blocker = MatplotlibBlocker()
+
+ def setUp(self):
+ sys.meta_path.insert(0, self._mpl_blocker)
+
+ def tearDown(self):
+ sys.meta_path.remove(self._mpl_blocker)
+
+ def test_mandelbrot(self):
+ with captured_stdout():
+ # magictoken.ex_mandelbrot.begin
+ from timeit import default_timer as timer
+ try:
+ from matplotlib.pylab import imshow, show
+ have_mpl = True
+ except ImportError:
+ have_mpl = False
+ import numpy as np
+ from numba import jit
+
+ @jit(nopython=True)
+ def mandel(x, y, max_iters):
+ """
+ Given the real and imaginary parts of a complex number,
+ determine if it is a candidate for membership in the Mandelbrot
+ set given a fixed number of iterations.
+ """
+ i = 0
+ c = complex(x,y)
+ z = 0.0j
+ for i in range(max_iters):
+ z = z * z + c
+ if (z.real * z.real + z.imag * z.imag) >= 4:
+ return i
+
+ return 255
+
+ @jit(nopython=True)
+ def create_fractal(min_x, max_x, min_y, max_y, image, iters):
+ height = image.shape[0]
+ width = image.shape[1]
+
+ pixel_size_x = (max_x - min_x) / width
+ pixel_size_y = (max_y - min_y) / height
+ for x in range(width):
+ real = min_x + x * pixel_size_x
+ for y in range(height):
+ imag = min_y + y * pixel_size_y
+ color = mandel(real, imag, iters)
+ image[y, x] = color
+
+ return image
+
+ image = np.zeros((500 * 2, 750 * 2), dtype=np.uint8)
+ s = timer()
+ create_fractal(-2.0, 1.0, -1.0, 1.0, image, 20)
+ e = timer()
+ print(e - s)
+ if have_mpl:
+ imshow(image)
+ show()
+ # magictoken.ex_mandelbrot.end
+
+ def test_moving_average(self):
+ with captured_stdout():
+ # magictoken.ex_moving_average.begin
+ import numpy as np
+
+ from numba import guvectorize
+
+ @guvectorize(['void(float64[:], intp[:], float64[:])'],
+ '(n),()->(n)')
+ def move_mean(a, window_arr, out):
+ window_width = window_arr[0]
+ asum = 0.0
+ count = 0
+ for i in range(window_width):
+ asum += a[i]
+ count += 1
+ out[i] = asum / count
+ for i in range(window_width, len(a)):
+ asum += a[i] - a[i - window_width]
+ out[i] = asum / count
+
+ arr = np.arange(20, dtype=np.float64).reshape(2, 10)
+ print(arr)
+ print(move_mean(arr, 3))
+ # magictoken.ex_moving_average.end
+
+ def test_nogil(self):
+ with captured_stdout():
+ # magictoken.ex_no_gil.begin
+ import math
+ import threading
+ from timeit import repeat
+
+ import numpy as np
+ from numba import jit
+
+ nthreads = 4
+ size = 10**6
+
+ def func_np(a, b):
+ """
+ Control function using Numpy.
+ """
+ return np.exp(2.1 * a + 3.2 * b)
+
+ @jit('void(double[:], double[:], double[:])', nopython=True,
+ nogil=True)
+ def inner_func_nb(result, a, b):
+ """
+ Function under test.
+ """
+ for i in range(len(result)):
+ result[i] = math.exp(2.1 * a[i] + 3.2 * b[i])
+
+ def timefunc(correct, s, func, *args, **kwargs):
+ """
+ Benchmark *func* and print out its runtime.
+ """
+ print(s.ljust(20), end=" ")
+ # Make sure the function is compiled before the benchmark is
+ # started
+ res = func(*args, **kwargs)
+ if correct is not None:
+ assert np.allclose(res, correct), (res, correct)
+ # time it
+ print('{:>5.0f} ms'.format(min(repeat(
+ lambda: func(*args, **kwargs), number=5, repeat=2)) * 1000))
+ return res
+
+ def make_singlethread(inner_func):
+ """
+ Run the given function inside a single thread.
+ """
+ def func(*args):
+ length = len(args[0])
+ result = np.empty(length, dtype=np.float64)
+ inner_func(result, *args)
+ return result
+ return func
+
+ def make_multithread(inner_func, numthreads):
+ """
+ Run the given function inside *numthreads* threads, splitting
+ its arguments into equal-sized chunks.
+ """
+ def func_mt(*args):
+ length = len(args[0])
+ result = np.empty(length, dtype=np.float64)
+ args = (result,) + args
+ chunklen = (length + numthreads - 1) // numthreads
+ # Create argument tuples for each input chunk
+ chunks = [[arg[i * chunklen:(i + 1) * chunklen] for arg in
+ args] for i in range(numthreads)]
+ # Spawn one thread per chunk
+ threads = [threading.Thread(target=inner_func, args=chunk)
+ for chunk in chunks]
+ for thread in threads:
+ thread.start()
+ for thread in threads:
+ thread.join()
+ return result
+ return func_mt
+
+ func_nb = make_singlethread(inner_func_nb)
+ func_nb_mt = make_multithread(inner_func_nb, nthreads)
+
+ a = np.random.rand(size)
+ b = np.random.rand(size)
+
+ correct = timefunc(None, "numpy (1 thread)", func_np, a, b)
+ timefunc(correct, "numba (1 thread)", func_nb, a, b)
+ timefunc(correct, "numba (%d threads)" % nthreads, func_nb_mt, a, b)
+ # magictoken.ex_no_gil.end
+
+ def test_vectorize_one_signature(self):
+ with captured_stdout():
+ # magictoken.ex_vectorize_one_signature.begin
+ from numba import vectorize, float64
+
+ @vectorize([float64(float64, float64)])
+ def f(x, y):
+ return x + y
+ # magictoken.ex_vectorize_one_signature.end
+
+ def test_vectorize_multiple_signatures(self):
+ with captured_stdout():
+ # magictoken.ex_vectorize_multiple_signatures.begin
+ from numba import vectorize, int32, int64, float32, float64
+ import numpy as np
+
+ @vectorize([int32(int32, int32),
+ int64(int64, int64),
+ float32(float32, float32),
+ float64(float64, float64)])
+ def f(x, y):
+ return x + y
+ # magictoken.ex_vectorize_multiple_signatures.end
+
+ # magictoken.ex_vectorize_return_call_one.begin
+ a = np.arange(6)
+ result = f(a, a)
+ # result == array([ 0, 2, 4, 6, 8, 10])
+ # magictoken.ex_vectorize_return_call_one.end
+
+ self.assertIsInstance(result, np.ndarray)
+ correct = np.array([0, 2, 4, 6, 8, 10])
+ np.testing.assert_array_equal(result, correct)
+
+ # magictoken.ex_vectorize_return_call_two.begin
+ a = np.linspace(0, 1, 6)
+ result = f(a, a)
+ # Now, result == array([0. , 0.4, 0.8, 1.2, 1.6, 2. ])
+ # magictoken.ex_vectorize_return_call_two.end
+
+ self.assertIsInstance(result, np.ndarray)
+ correct = np.array([0., 0.4, 0.8, 1.2, 1.6, 2. ])
+ np.testing.assert_allclose(result, correct)
+
+ # magictoken.ex_vectorize_return_call_three.begin
+ a = np.arange(12).reshape(3, 4)
+ # a == array([[ 0, 1, 2, 3],
+ # [ 4, 5, 6, 7],
+ # [ 8, 9, 10, 11]])
+
+ result1 = f.reduce(a, axis=0)
+ # result1 == array([12, 15, 18, 21])
+
+ result2 = f.reduce(a, axis=1)
+ # result2 == array([ 6, 22, 38])
+
+ result3 = f.accumulate(a)
+ # result3 == array([[ 0, 1, 2, 3],
+ # [ 4, 6, 8, 10],
+ # [12, 15, 18, 21]])
+
+ result4 = f.accumulate(a, axis=1)
+ # result3 == array([[ 0, 1, 3, 6],
+ # [ 4, 9, 15, 22],
+ # [ 8, 17, 27, 38]])
+ # magictoken.ex_vectorize_return_call_three.end
+
+ self.assertIsInstance(result1, np.ndarray)
+ correct = np.array([12, 15, 18, 21])
+ np.testing.assert_array_equal(result1, correct)
+
+ self.assertIsInstance(result2, np.ndarray)
+ correct = np.array([6, 22, 38])
+ np.testing.assert_array_equal(result2, correct)
+
+ self.assertIsInstance(result3, np.ndarray)
+ correct = np.array([
+ [0, 1, 2, 3],
+ [4, 6, 8, 10],
+ [12, 15, 18, 21]
+ ])
+ np.testing.assert_array_equal(result3, correct)
+
+ self.assertIsInstance(result4, np.ndarray)
+ correct = np.array([
+ [0, 1, 3, 6],
+ [4, 9, 15, 22],
+ [8, 17, 27, 38]
+ ])
+ np.testing.assert_array_equal(result4, correct)
+
+ def test_guvectorize(self):
+ with captured_stdout():
+ # magictoken.ex_guvectorize.begin
+ from numba import guvectorize, int64
+ import numpy as np
+
+ @guvectorize([(int64[:], int64, int64[:])], '(n),()->(n)')
+ def g(x, y, res):
+ for i in range(x.shape[0]):
+ res[i] = x[i] + y
+ # magictoken.ex_guvectorize.end
+
+ # magictoken.ex_guvectorize_call_one.begin
+ a = np.arange(5)
+ result = g(a, 2)
+ # result == array([2, 3, 4, 5, 6])
+ # magictoken.ex_guvectorize_call_one.end
+
+ self.assertIsInstance(result, np.ndarray)
+ correct = np.array([2, 3, 4, 5, 6])
+ np.testing.assert_array_equal(result, correct)
+
+ # magictoken.ex_guvectorize_call_two.begin
+ a = np.arange(6).reshape(2, 3)
+ # a == array([[0, 1, 2],
+ # [3, 4, 5]])
+
+ result1 = g(a, 10)
+ # result1 == array([[10, 11, 12],
+ # [13, 14, 15]])
+
+ result2 = g(a, np.array([10, 20]))
+ g(a, np.array([10, 20]))
+ # result2 == array([[10, 11, 12],
+ # [23, 24, 25]])
+ # magictoken.ex_guvectorize_call_two.end
+
+ self.assertIsInstance(result1, np.ndarray)
+ correct = np.array([[10, 11, 12], [13, 14, 15]])
+ np.testing.assert_array_equal(result1, correct)
+
+ self.assertIsInstance(result2, np.ndarray)
+ correct = np.array([[10, 11, 12], [23, 24, 25]])
+ np.testing.assert_array_equal(result2, correct)
+
+ def test_guvectorize_scalar_return(self):
+ with captured_stdout():
+ # magictoken.ex_guvectorize_scalar_return.begin
+ from numba import guvectorize, int64
+ import numpy as np
+
+ @guvectorize([(int64[:], int64, int64[:])], '(n),()->()')
+ def g(x, y, res):
+ acc = 0
+ for i in range(x.shape[0]):
+ acc += x[i] + y
+ res[0] = acc
+ # magictoken.ex_guvectorize_scalar_return.end
+
+ # magictoken.ex_guvectorize_scalar_return_call.begin
+ a = np.arange(5)
+ result = g(a, 2)
+ # At this point, result == 20.
+ # magictoken.ex_guvectorize_scalar_return_call.end
+
+ self.assertIsInstance(result, np.integer)
+ self.assertEqual(result, 20)
+
+ def test_guvectorize_jit(self):
+ with captured_stdout():
+ # magictoken.gufunc_jit.begin
+ import numpy as np
+
+ from numba import jit, guvectorize
+
+ @guvectorize('(n)->(n)')
+ def copy(x, res):
+ for i in range(x.shape[0]):
+ res[i] = x[i]
+
+ @jit(nopython=True)
+ def jit_fn(x, res):
+ copy(x, res)
+ # magictoken.gufunc_jit.end
+
+ # magictoken.gufunc_jit_call.begin
+ x = np.arange(5, dtype='i4')
+ res = np.zeros_like(x)
+ jit_fn(x, res)
+ # At this point, res == np.array([0, 1, 2, 3, 4], 'i4').
+ # magictoken.gufunc_jit_call.end
+ self.assertPreciseEqual(x, res)
+
+ def test_guvectorize_jit_fail(self):
+ with captured_stdout():
+ # magictoken.gufunc_jit_fail.begin
+ import numpy as np
+ from numba import jit, guvectorize
+
+ @guvectorize('(n)->(n)')
+ def copy(x, res):
+ for i in range(x.shape[0]):
+ res[i] = x[i]
+
+ @jit(nopython=True)
+ def jit_fn(x, res):
+ copy(x, res)
+
+ x = np.ones((1, 5))
+ res = np.empty((5,))
+ with self.assertRaises(ValueError) as raises:
+ jit_fn(x, res)
+ # magictoken.gufunc_jit_fail.end
+ self.assertIn('Loop and array shapes are incompatible',
+ str(raises.exception))
+
+ def test_guvectorize_overwrite(self):
+ with captured_stdout():
+ # magictoken.ex_guvectorize_overwrite.begin
+ from numba import guvectorize, float64
+ import numpy as np
+
+ @guvectorize([(float64[:], float64[:])], '()->()')
+ def init_values(invals, outvals):
+ invals[0] = 6.5
+ outvals[0] = 4.2
+ # magictoken.ex_guvectorize_overwrite.end
+
+ # magictoken.ex_guvectorize_overwrite_call_one.begin
+ invals = np.zeros(shape=(3, 3), dtype=np.float64)
+ # invals == array([[6.5, 6.5, 6.5],
+ # [6.5, 6.5, 6.5],
+ # [6.5, 6.5, 6.5]])
+
+ outvals = init_values(invals)
+ # outvals == array([[4.2, 4.2, 4.2],
+ # [4.2, 4.2, 4.2],
+ # [4.2, 4.2, 4.2]])
+ # magictoken.ex_guvectorize_overwrite_call_one.end
+
+ self.assertIsInstance(invals, np.ndarray)
+ correct = np.array([
+ [6.5, 6.5, 6.5],
+ [6.5, 6.5, 6.5],
+ [6.5, 6.5, 6.5]])
+ np.testing.assert_array_equal(invals, correct)
+
+ self.assertIsInstance(outvals, np.ndarray)
+ correct = np.array([
+ [4.2, 4.2, 4.2],
+ [4.2, 4.2, 4.2],
+ [4.2, 4.2, 4.2]])
+ np.testing.assert_array_equal(outvals, correct)
+
+ # magictoken.ex_guvectorize_overwrite_call_two.begin
+ invals = np.zeros(shape=(3, 3), dtype=np.float32)
+ # invals == array([[0., 0., 0.],
+ # [0., 0., 0.],
+ # [0., 0., 0.]], dtype=float32)
+ outvals = init_values(invals)
+ # outvals == array([[4.2, 4.2, 4.2],
+ # [4.2, 4.2, 4.2],
+ # [4.2, 4.2, 4.2]])
+ print(invals)
+ # invals == array([[0., 0., 0.],
+ # [0., 0., 0.],
+ # [0., 0., 0.]], dtype=float32)
+ # magictoken.ex_guvectorize_overwrite_call_two.end
+
+ self.assertIsInstance(invals, np.ndarray)
+ correct = np.array([
+ [0., 0., 0.],
+ [0., 0., 0.],
+ [0., 0., 0.]], dtype=np.float32)
+ np.testing.assert_array_equal(invals, correct)
+
+ self.assertIsInstance(outvals, np.ndarray)
+ correct = np.array([
+ [4.2, 4.2, 4.2],
+ [4.2, 4.2, 4.2],
+ [4.2, 4.2, 4.2]])
+ np.testing.assert_array_equal(outvals, correct)
+
+ # magictoken.ex_guvectorize_overwrite_call_three.begin
+ @guvectorize(
+ [(float64[:], float64[:])],
+ '()->()',
+ writable_args=('invals',)
+ )
+ def init_values(invals, outvals):
+ invals[0] = 6.5
+ outvals[0] = 4.2
+
+ invals = np.zeros(shape=(3, 3), dtype=np.float32)
+ # invals == array([[0., 0., 0.],
+ # [0., 0., 0.],
+ # [0., 0., 0.]], dtype=float32)
+ outvals = init_values(invals)
+ # outvals == array([[4.2, 4.2, 4.2],
+ # [4.2, 4.2, 4.2],
+ # [4.2, 4.2, 4.2]])
+ print(invals)
+ # invals == array([[6.5, 6.5, 6.5],
+ # [6.5, 6.5, 6.5],
+ # [6.5, 6.5, 6.5]], dtype=float32)
+ # magictoken.ex_guvectorize_overwrite_call_three.end
+
+ self.assertIsInstance(invals, np.ndarray)
+ correct = np.array([
+ [6.5, 6.5, 6.5],
+ [6.5, 6.5, 6.5],
+ [6.5, 6.5, 6.5]])
+ np.testing.assert_array_equal(invals, correct)
+
+ self.assertIsInstance(outvals, np.ndarray)
+ correct = np.array([
+ [4.2, 4.2, 4.2],
+ [4.2, 4.2, 4.2],
+ [4.2, 4.2, 4.2]])
+ np.testing.assert_array_equal(outvals, correct)
+
+ def test_vectorize_dynamic(self):
+ with captured_stdout():
+ # magictoken.ex_vectorize_dynamic.begin
+ from numba import vectorize
+
+ @vectorize
+ def f(x, y):
+ return x * y
+ # magictoken.ex_vectorize_dynamic.end
+
+ # magictoken.ex_vectorize_dynamic_call_one.begin
+ result = f(3,4)
+ # result == 12
+
+ print(f.types)
+ # ['ll->l']
+ # magictoken.ex_vectorize_dynamic_call_one.end
+
+ self.assertEqual(result, 12)
+ if IS_WIN32:
+ if numpy_version < (2, 0):
+ correct = ['ll->q']
+ else:
+ correct = ['qq->q']
+ else:
+ correct = ['ll->l']
+ self.assertEqual(f.types, correct)
+
+ # magictoken.ex_vectorize_dynamic_call_two.begin
+ result = f(1.,2.)
+ # result == 2.0
+
+ print(f.types)
+ # ['ll->l', 'dd->d']
+ # magictoken.ex_vectorize_dynamic_call_two.end
+
+ self.assertEqual(result, 2.0)
+ if IS_WIN32:
+ if numpy_version < (2, 0):
+ correct = ['ll->q', 'dd->d']
+ else:
+ correct = ['qq->q', 'dd->d']
+ else:
+ correct = ['ll->l', 'dd->d']
+ self.assertEqual(f.types, correct)
+
+ # magictoken.ex_vectorize_dynamic_call_three.begin
+ result = f(1,2.)
+ # result == 2.0
+
+ print(f.types)
+ # ['ll->l', 'dd->d']
+ # magictoken.ex_vectorize_dynamic_call_three.end
+
+ self.assertEqual(result, 2.0)
+ if IS_WIN32:
+ if numpy_version < (2, 0):
+ correct = ['ll->q', 'dd->d']
+ else:
+ correct = ['qq->q', 'dd->d']
+ else:
+ correct = ['ll->l', 'dd->d']
+ self.assertEqual(f.types, correct)
+
+ # magictoken.ex_vectorize_dynamic_call_four.begin
+ @vectorize
+ def g(a, b):
+ return a / b
+
+ print(g(2.,3.))
+ # 0.66666666666666663
+
+ print(g(2,3))
+ # 0.66666666666666663
+
+ print(g.types)
+ # ['dd->d']
+ # magictoken.ex_vectorize_dynamic_call_four.end
+
+ correct = ['dd->d']
+ self.assertEqual(g.types, correct)
+
+ def test_guvectorize_dynamic(self):
+ with captured_stdout():
+ # magictoken.ex_guvectorize_dynamic.begin
+ from numba import guvectorize
+ import numpy as np
+
+ @guvectorize('(n),()->(n)')
+ def g(x, y, res):
+ for i in range(x.shape[0]):
+ res[i] = x[i] + y
+ # magictoken.ex_guvectorize_dynamic.end
+
+ # magictoken.ex_guvectorize_dynamic_call_one.begin
+ x = np.arange(5, dtype=np.int64)
+ y = 10
+ res = np.zeros_like(x)
+ g(x, y, res)
+ # res == array([10, 11, 12, 13, 14])
+ print(g.types)
+ # ['ll->l']
+ # magictoken.ex_guvectorize_dynamic_call_one.end
+
+ correct = np.array([10, 11, 12, 13, 14])
+ np.testing.assert_array_equal(res, correct)
+ if IS_WIN32:
+ correct = ['qq->q']
+ else:
+ correct = ['ll->l']
+ self.assertEqual(g.types, correct)
+
+ # magictoken.ex_guvectorize_dynamic_call_two.begin
+ x = np.arange(5, dtype=np.double)
+ y = 2.2
+ res = np.zeros_like(x)
+ g(x, y, res)
+ # res == array([2.2, 3.2, 4.2, 5.2, 6.2])
+ # magictoken.ex_guvectorize_dynamic_call_two.end
+
+ # magictoken.ex_guvectorize_dynamic_call_three.begin
+ print(g.types) # shorthand for g.ufunc.types
+ # ['ll->l', 'dd->d']
+ # magictoken.ex_guvectorize_dynamic_call_three.end
+
+ if IS_WIN32:
+ correct = ['qq->q', 'dd->d']
+ else:
+ correct = ['ll->l', 'dd->d']
+ self.assertEqual(g.types, correct)
+
+ # magictoken.ex_guvectorize_dynamic_call_four.begin
+ x = np.arange(5, dtype=np.int64)
+ y = 2
+ res = np.zeros_like(x)
+ g(x, y, res)
+ print(res)
+ # res == array([2, 3, 4, 5, 6])
+ # magictoken.ex_guvectorize_dynamic_call_four.end
+
+ correct = np.array([2, 3, 4, 5, 6])
+ np.testing.assert_array_equal(res, correct)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/doc_examples/test_interval_example.py b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/doc_examples/test_interval_example.py
new file mode 100644
index 0000000000000000000000000000000000000000..78cf7935ef20a7b57452f7802b8069c3327f9eba
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/doc_examples/test_interval_example.py
@@ -0,0 +1,242 @@
+"""
+This test is used by `docs/source/extending/interval-example.rst`.
+
+The "magictoken" comments are used as markers for the beginning and ending of
+example code.
+"""
+import unittest
+
+
+class IntervalExampleTest(unittest.TestCase):
+
+ def test_interval_class_usage(self):
+ # magictoken.interval_py_class.begin
+ class Interval(object):
+ """
+ A half-open interval on the real number line.
+ """
+ def __init__(self, lo, hi):
+ self.lo = lo
+ self.hi = hi
+
+ def __repr__(self):
+ return 'Interval(%f, %f)' % (self.lo, self.hi)
+
+ @property
+ def width(self):
+ return self.hi - self.lo
+ # magictoken.interval_py_class.end
+
+ # magictoken.interval_type_class.begin
+ from numba import types
+
+ class IntervalType(types.Type):
+ def __init__(self):
+ super(IntervalType, self).__init__(name='Interval')
+
+ interval_type = IntervalType()
+ # magictoken.interval_type_class.end
+
+ # magictoken.interval_typeof_register.begin
+ from numba.extending import typeof_impl
+
+ @typeof_impl.register(Interval)
+ def typeof_index(val, c):
+ return interval_type
+ # magictoken.interval_typeof_register.end
+
+ # magictoken.numba_type_register.begin
+ from numba.extending import as_numba_type
+
+ as_numba_type.register(Interval, interval_type)
+ # magictoken.numba_type_register.end
+
+ # magictoken.numba_type_callable.begin
+ from numba.extending import type_callable
+
+ @type_callable(Interval)
+ def type_interval(context):
+ def typer(lo, hi):
+ if isinstance(lo, types.Float) and isinstance(hi, types.Float):
+ return interval_type
+ return typer
+ # magictoken.numba_type_callable.end
+
+ # magictoken.interval_model.begin
+ from numba.extending import models, register_model
+
+ @register_model(IntervalType)
+ class IntervalModel(models.StructModel):
+ def __init__(self, dmm, fe_type):
+ members = [('lo', types.float64),
+ ('hi', types.float64),]
+ models.StructModel.__init__(self, dmm, fe_type, members)
+ # magictoken.interval_model.end
+
+ # magictoken.interval_attribute_wrapper.begin
+ from numba.extending import make_attribute_wrapper
+
+ make_attribute_wrapper(IntervalType, 'lo', 'lo')
+ make_attribute_wrapper(IntervalType, 'hi', 'hi')
+ # magictoken.interval_attribute_wrapper.end
+
+ # magictoken.interval_overload_attribute.begin
+ from numba.extending import overload_attribute
+
+ @overload_attribute(IntervalType, "width")
+ def get_width(interval):
+ def getter(interval):
+ return interval.hi - interval.lo
+ return getter
+ # magictoken.interval_overload_attribute.end
+
+ # magictoken.interval_lower_builtin.begin
+ from numba.extending import lower_builtin
+ from numba.core import cgutils
+
+ @lower_builtin(Interval, types.Float, types.Float)
+ def impl_interval(context, builder, sig, args):
+ typ = sig.return_type
+ lo, hi = args
+ interval = cgutils.create_struct_proxy(typ)(context, builder)
+ interval.lo = lo
+ interval.hi = hi
+ return interval._getvalue()
+ # magictoken.interval_lower_builtin.end
+
+ # magictoken.interval_unbox.begin
+ from numba.extending import unbox, NativeValue
+ from contextlib import ExitStack
+
+ @unbox(IntervalType)
+ def unbox_interval(typ, obj, c):
+ """
+ Convert a Interval object to a native interval structure.
+ """
+ is_error_ptr = cgutils.alloca_once_value(c.builder, cgutils.false_bit)
+ interval = cgutils.create_struct_proxy(typ)(c.context, c.builder)
+
+ with ExitStack() as stack:
+ lo_obj = c.pyapi.object_getattr_string(obj, "lo")
+ with cgutils.early_exit_if_null(c.builder, stack, lo_obj):
+ c.builder.store(cgutils.true_bit, is_error_ptr)
+ lo_native = c.unbox(types.float64, lo_obj)
+ c.pyapi.decref(lo_obj)
+ with cgutils.early_exit_if(c.builder, stack, lo_native.is_error):
+ c.builder.store(cgutils.true_bit, is_error_ptr)
+
+ hi_obj = c.pyapi.object_getattr_string(obj, "hi")
+ with cgutils.early_exit_if_null(c.builder, stack, hi_obj):
+ c.builder.store(cgutils.true_bit, is_error_ptr)
+ hi_native = c.unbox(types.float64, hi_obj)
+ c.pyapi.decref(hi_obj)
+ with cgutils.early_exit_if(c.builder, stack, hi_native.is_error):
+ c.builder.store(cgutils.true_bit, is_error_ptr)
+
+ interval.lo = lo_native.value
+ interval.hi = hi_native.value
+
+ return NativeValue(interval._getvalue(), is_error=c.builder.load(is_error_ptr))
+ # magictoken.interval_unbox.end
+
+ # magictoken.interval_box.begin
+ from numba.extending import box
+
+ @box(IntervalType)
+ def box_interval(typ, val, c):
+ """
+ Convert a native interval structure to an Interval object.
+ """
+ ret_ptr = cgutils.alloca_once(c.builder, c.pyapi.pyobj)
+ fail_obj = c.pyapi.get_null_object()
+
+ with ExitStack() as stack:
+ interval = cgutils.create_struct_proxy(typ)(c.context, c.builder, value=val)
+ lo_obj = c.box(types.float64, interval.lo)
+ with cgutils.early_exit_if_null(c.builder, stack, lo_obj):
+ c.builder.store(fail_obj, ret_ptr)
+
+ hi_obj = c.box(types.float64, interval.hi)
+ with cgutils.early_exit_if_null(c.builder, stack, hi_obj):
+ c.pyapi.decref(lo_obj)
+ c.builder.store(fail_obj, ret_ptr)
+
+ class_obj = c.pyapi.unserialize(c.pyapi.serialize_object(Interval))
+ with cgutils.early_exit_if_null(c.builder, stack, class_obj):
+ c.pyapi.decref(lo_obj)
+ c.pyapi.decref(hi_obj)
+ c.builder.store(fail_obj, ret_ptr)
+
+ # NOTE: The result of this call is not checked as the clean up
+ # has to occur regardless of whether it is successful. If it
+ # fails `res` is set to NULL and a Python exception is set.
+ res = c.pyapi.call_function_objargs(class_obj, (lo_obj, hi_obj))
+ c.pyapi.decref(lo_obj)
+ c.pyapi.decref(hi_obj)
+ c.pyapi.decref(class_obj)
+ c.builder.store(res, ret_ptr)
+
+ return c.builder.load(ret_ptr)
+ # magictoken.interval_box.end
+
+ # magictoken.interval_usage.begin
+ from numba import njit
+
+ @njit
+ def inside_interval(interval, x):
+ return interval.lo <= x < interval.hi
+
+ @njit
+ def interval_width(interval):
+ return interval.width
+
+ @njit
+ def sum_intervals(i, j):
+ return Interval(i.lo + j.lo, i.hi + j.hi)
+ # magictoken.interval_usage.end
+
+ def check_equal_intervals(x, y):
+ self.assertIsInstance(x, Interval)
+ self.assertIsInstance(y, Interval)
+ self.assertEqual(x.lo, y.lo)
+ self.assertEqual(x.hi, y.hi)
+
+ a = Interval(2, 3)
+ b = Interval(4, 5)
+ c = Interval(6, 8)
+
+ # Test box-unbox
+ return_func = njit(lambda x: x)
+ check_equal_intervals(a, return_func(a))
+
+ # Test .width attribute
+ self.assertEqual(a.width, interval_width(a))
+
+ # Test exceptions
+ class NotAFloat:
+ def __float__(self):
+ raise RuntimeError("I am not a float")
+
+ # TODO: This should produce a `RuntimeError`, but the `unbox` handler for `float` ignores
+ # the error raised by `__float__`, leading to a subsequent `TypeError` cause by passing
+ # `NULL` to `PyFloat_AsDouble`.
+ # This isn't the fault of the `Interval` extension that is being testing
+ # in this file.
+ with self.assertRaises(TypeError):
+ interval_width(Interval(2, NotAFloat()))
+
+ bad_interval = Interval(1, 2)
+ del bad_interval.hi
+
+ with self.assertRaises(AttributeError):
+ interval_width(bad_interval)
+
+ # Test .lo and .hi usage
+ self.assertFalse(inside_interval(a, 5))
+
+ # Test native Interval constructor
+ check_equal_intervals(c, sum_intervals(a, b))
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/doc_examples/test_jitclass.py b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/doc_examples/test_jitclass.py
new file mode 100644
index 0000000000000000000000000000000000000000..ca5faea423427b081cc49a9617e68f1bdb3936b5
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/doc_examples/test_jitclass.py
@@ -0,0 +1,97 @@
+# Contents in this file are referenced from the sphinx-generated docs.
+# "magictoken" is used for markers as beginning and ending of example text.
+
+import unittest
+from numba.tests.support import TestCase
+
+
+class DocsJitclassUsageTest(TestCase):
+
+ def test_ex_jitclass(self):
+ # magictoken.ex_jitclass.begin
+ import numpy as np
+ from numba import int32, float32 # import the types
+ from numba.experimental import jitclass
+
+ spec = [
+ ('value', int32), # a simple scalar field
+ ('array', float32[:]), # an array field
+ ]
+
+ @jitclass(spec)
+ class Bag(object):
+ def __init__(self, value):
+ self.value = value
+ self.array = np.zeros(value, dtype=np.float32)
+
+ @property
+ def size(self):
+ return self.array.size
+
+ def increment(self, val):
+ for i in range(self.size):
+ self.array[i] += val
+ return self.array
+
+ @staticmethod
+ def add(x, y):
+ return x + y
+
+ n = 21
+ mybag = Bag(n)
+ # magictoken.ex_jitclass.end
+
+ self.assertTrue(isinstance(mybag, Bag))
+ self.assertPreciseEqual(mybag.value, n)
+ np.testing.assert_allclose(mybag.array, np.zeros(n, dtype=np.float32))
+ self.assertPreciseEqual(mybag.size, n)
+ np.testing.assert_allclose(mybag.increment(3),
+ 3 * np.ones(n, dtype=np.float32))
+ np.testing.assert_allclose(mybag.increment(6),
+ 9 * np.ones(n, dtype=np.float32))
+ self.assertPreciseEqual(mybag.add(1, 1), 2)
+ self.assertPreciseEqual(Bag.add(1, 2), 3)
+
+ def test_ex_jitclass_type_hints(self):
+ # magictoken.ex_jitclass_type_hints.begin
+ from typing import List
+ from numba.experimental import jitclass
+ from numba.typed import List as NumbaList
+
+ @jitclass
+ class Counter:
+ value: int
+
+ def __init__(self):
+ self.value = 0
+
+ def get(self) -> int:
+ ret = self.value
+ self.value += 1
+ return ret
+
+ @jitclass
+ class ListLoopIterator:
+ counter: Counter
+ items: List[float]
+
+ def __init__(self, items: List[float]):
+ self.items = items
+ self.counter = Counter()
+
+ def get(self) -> float:
+ idx = self.counter.get() % len(self.items)
+ return self.items[idx]
+
+ items = NumbaList([3.14, 2.718, 0.123, -4.])
+ loop_itr = ListLoopIterator(items)
+ # magictoken.ex_jitclass_type_hints.end
+
+ for idx in range(10):
+ self.assertEqual(loop_itr.counter.value, idx)
+ self.assertAlmostEqual(loop_itr.get(), items[idx % len(items)])
+ self.assertEqual(loop_itr.counter.value, idx + 1)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/doc_examples/test_literal_container_usage.py b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/doc_examples/test_literal_container_usage.py
new file mode 100644
index 0000000000000000000000000000000000000000..4872faa4c0aa689e1a83a1b570a4fbed0d540964
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/doc_examples/test_literal_container_usage.py
@@ -0,0 +1,161 @@
+# Contents in this file are referenced from the sphinx-generated docs.
+# "magictoken" is used for markers as beginning and ending of example text.
+
+import unittest
+from numba.tests.support import captured_stdout
+from numba import typed
+
+
+class DocsLiteralContainerUsageTest(unittest.TestCase):
+
+ def test_ex_literal_dict_compile_time_consts(self):
+ with captured_stdout():
+ # magictoken.test_ex_literal_dict_compile_time_consts.begin
+ import numpy as np
+ from numba import njit, types
+ from numba.extending import overload
+
+ # overload this function
+ def specialize(x):
+ pass
+
+ @overload(specialize)
+ def ol_specialize(x):
+ ld = x.literal_value
+ const_expr = []
+ for k, v in ld.items():
+ if isinstance(v, types.Literal):
+ lv = v.literal_value
+ if lv == 'cat':
+ const_expr.append("Meow!")
+ elif lv == 'dog':
+ const_expr.append("Woof!")
+ elif isinstance(lv, int):
+ const_expr.append(k.literal_value * lv)
+ else: # it's an array
+ const_expr.append("Array(dim={dim}".format(dim=v.ndim))
+ const_strings = tuple(const_expr)
+
+ def impl(x):
+ return const_strings
+ return impl
+
+ @njit
+ def foo():
+ pets_ints_and_array = {'a': 1,
+ 'b': 2,
+ 'c': 'cat',
+ 'd': 'dog',
+ 'e': np.ones(5,)}
+ return specialize(pets_ints_and_array)
+
+ result = foo()
+ print(result) # ('a', 'bb', 'Meow!', 'Woof!', 'Array(dim=1')
+ # magictoken.test_ex_literal_dict_compile_time_consts.end
+
+ self.assertEqual(result, ('a', 'bb', 'Meow!', 'Woof!', 'Array(dim=1'))
+
+ def test_ex_initial_value_dict_compile_time_consts(self):
+ with captured_stdout():
+ # magictoken.test_ex_initial_value_dict_compile_time_consts.begin
+ from numba import njit, literally
+ from numba.extending import overload
+
+ # overload this function
+ def specialize(x):
+ pass
+
+ @overload(specialize)
+ def ol_specialize(x):
+ iv = x.initial_value
+ if iv is None:
+ return lambda x: literally(x) # Force literal dispatch
+ assert iv == {'a': 1, 'b': 2, 'c': 3} # INITIAL VALUE
+ return lambda x: literally(x)
+
+ @njit
+ def foo():
+ d = {'a': 1, 'b': 2, 'c': 3}
+ d['c'] = 20 # no impact on .initial_value
+ d['d'] = 30 # no impact on .initial_value
+ return specialize(d)
+
+ result = foo()
+ print(result) # {a: 1, b: 2, c: 20, d: 30} # NOT INITIAL VALUE!
+ # magictoken.test_ex_initial_value_dict_compile_time_consts.end
+
+ expected = typed.Dict()
+ for k, v in {'a': 1, 'b': 2, 'c': 20, 'd': 30}.items():
+ expected[k] = v
+ self.assertEqual(result, expected)
+
+ def test_ex_literal_list(self):
+ with captured_stdout():
+ # magictoken.test_ex_literal_list.begin
+ from numba import njit
+ from numba.extending import overload
+
+ # overload this function
+ def specialize(x):
+ pass
+
+ @overload(specialize)
+ def ol_specialize(x):
+ l = x.literal_value
+ const_expr = []
+ for v in l:
+ const_expr.append(str(v))
+ const_strings = tuple(const_expr)
+
+ def impl(x):
+ return const_strings
+ return impl
+
+ @njit
+ def foo():
+ const_list = ['a', 10, 1j, ['another', 'list']]
+ return specialize(const_list)
+
+ result = foo()
+ print(result) # ('Literal[str](a)', 'Literal[int](10)', 'complex128', 'list(unicode_type)') # noqa E501
+ # magictoken.test_ex_literal_list.end
+
+ expected = ('Literal[str](a)', 'Literal[int](10)', 'complex128',
+ "list(unicode_type)")
+ self.assertEqual(result, expected)
+
+ def test_ex_initial_value_list_compile_time_consts(self):
+ with captured_stdout():
+ # magictoken.test_ex_initial_value_list_compile_time_consts.begin
+ from numba import njit, literally
+ from numba.extending import overload
+
+ # overload this function
+ def specialize(x):
+ pass
+
+ @overload(specialize)
+ def ol_specialize(x):
+ iv = x.initial_value
+ if iv is None:
+ return lambda x: literally(x) # Force literal dispatch
+ assert iv == [1, 2, 3] # INITIAL VALUE
+ return lambda x: x
+
+ @njit
+ def foo():
+ l = [1, 2, 3]
+ l[2] = 20 # no impact on .initial_value
+ l.append(30) # no impact on .initial_value
+ return specialize(l)
+
+ result = foo()
+ print(result) # [1, 2, 20, 30] # NOT INITIAL VALUE!
+ # magictoken.test_ex_initial_value_list_compile_time_consts.end
+
+ expected = [1, 2, 20, 30]
+ self.assertEqual(result, expected)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/doc_examples/test_literally_usage.py b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/doc_examples/test_literally_usage.py
new file mode 100644
index 0000000000000000000000000000000000000000..8fe8b45d37d05e82cdaa47149f75395467e36655
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/doc_examples/test_literally_usage.py
@@ -0,0 +1,59 @@
+# "magictoken" is used for markers as beginning and ending of example text.
+
+import unittest
+from numba.tests.support import captured_stdout
+
+
+class DocsLiterallyUsageTest(unittest.TestCase):
+
+ def test_literally_usage(self):
+ with captured_stdout() as stdout:
+ # magictoken.ex_literally_usage.begin
+ import numba
+
+ def power(x, n):
+ raise NotImplementedError
+
+ @numba.extending.overload(power)
+ def ov_power(x, n):
+ if isinstance(n, numba.types.Literal):
+ # only if `n` is a literal
+ if n.literal_value == 2:
+ # special case: square
+ print("square")
+ return lambda x, n: x * x
+ elif n.literal_value == 3:
+ # special case: cubic
+ print("cubic")
+ return lambda x, n: x * x * x
+ else:
+ # If `n` is not literal, request literal dispatch
+ return lambda x, n: numba.literally(n)
+
+ print("generic")
+ return lambda x, n: x ** n
+
+ @numba.njit
+ def test_power(x, n):
+ return power(x, n)
+
+ # should print "square" and "9"
+ print(test_power(3, 2))
+
+ # should print "cubic" and "27"
+ print(test_power(3, 3))
+
+ # should print "generic" and "81"
+ print(test_power(3, 4))
+
+ # magictoken.ex_literally_usage.end
+ assert test_power(3, 2) == 3 ** 2
+ assert test_power(3, 3) == 3 ** 3
+ assert test_power(3, 4) == 3 ** 4
+
+ self.assertEqual('square\n9\ncubic\n27\ngeneric\n81\n',
+ stdout.getvalue())
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/doc_examples/test_llvm_pass_timings.py b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/doc_examples/test_llvm_pass_timings.py
new file mode 100644
index 0000000000000000000000000000000000000000..2f607c847b7bc13eeafa800f9e2151fa59e4e826
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/doc_examples/test_llvm_pass_timings.py
@@ -0,0 +1,31 @@
+# "magictoken" is used for markers as beginning and ending of example text.
+
+import unittest
+from numba.tests.support import captured_stdout, override_config
+
+
+class DocsLLVMPassTimings(unittest.TestCase):
+
+ def test_pass_timings(self):
+ with override_config('LLVM_PASS_TIMINGS', True):
+ with captured_stdout() as stdout:
+ # magictoken.ex_llvm_pass_timings.begin
+ import numba
+
+ @numba.njit
+ def foo(n):
+ c = 0
+ for i in range(n):
+ for j in range(i):
+ c += j
+ return c
+
+ foo(10)
+ md = foo.get_metadata(foo.signatures[0])
+ print(md['llvm_pass_timings'])
+ # magictoken.ex_llvm_pass_timings.end
+ self.assertIn("Finalize object", stdout.getvalue())
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/doc_examples/test_numpy_generators.py b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/doc_examples/test_numpy_generators.py
new file mode 100644
index 0000000000000000000000000000000000000000..e10266d07e03f4a38a969c20da7fe923742f0086
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/doc_examples/test_numpy_generators.py
@@ -0,0 +1,38 @@
+# "magictoken" is used for markers as beginning and ending of example text.
+
+import unittest
+import numpy as np
+import numba
+
+
+class NumpyGeneratorUsageTest(unittest.TestCase):
+
+ def test_numpy_gen_usage(self):
+ # magictoken.npgen_usage.begin
+ x = np.random.default_rng(1)
+ y = np.random.default_rng(1)
+
+ size = 10
+
+ @numba.njit
+ def do_stuff(gen):
+ return gen.random(size=int(size / 2))
+
+ original = x.random(size=size)
+ # [0.51182162 0.9504637 0.14415961 0.94864945 0.31183145
+ # 0.42332645 0.82770259 0.40919914 0.54959369 0.02755911]
+
+ numba_func_res = do_stuff(y)
+ # [0.51182162 0.9504637 0.14415961 0.94864945 0.31183145]
+
+ after_numba = y.random(size=int(size / 2))
+ # [0.42332645 0.82770259 0.40919914 0.54959369 0.02755911]
+
+ # magictoken.npgen_usage.end
+ numba_res = np.concatenate((numba_func_res, after_numba))
+ for _np_res, _nb_res in zip(original, numba_res):
+ self.assertEqual(_np_res, _nb_res)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/doc_examples/test_parallel_chunksize.py b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/doc_examples/test_parallel_chunksize.py
new file mode 100644
index 0000000000000000000000000000000000000000..36e161a029bd3fa513ce118d551eba967de3ee5e
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/doc_examples/test_parallel_chunksize.py
@@ -0,0 +1,122 @@
+# Contents in this file are referenced from the sphinx-generated docs.
+# "magictoken" is used for markers as beginning and ending of example text.
+
+import unittest
+from numba.tests.support import captured_stdout, skip_parfors_unsupported
+from numba import set_parallel_chunksize
+from numba.tests.support import TestCase
+
+
+@skip_parfors_unsupported
+class ChunksizeExamplesTest(TestCase):
+
+ _numba_parallel_test_ = False
+
+ def setUp(self):
+ set_parallel_chunksize(0)
+
+ def tearDown(self):
+ set_parallel_chunksize(0)
+
+ def test_unbalanced_example(self):
+ with captured_stdout():
+ # magictoken.ex_unbalanced.begin
+ from numba import (njit,
+ prange,
+ )
+ import numpy as np
+
+ @njit(parallel=True)
+ def func1():
+ n = 100
+ vals = np.empty(n)
+ # The work in each iteration of the following prange
+ # loop is proportional to its index.
+ for i in prange(n):
+ cur = i + 1
+ for j in range(i):
+ if cur % 2 == 0:
+ cur //= 2
+ else:
+ cur = cur * 3 + 1
+ vals[i] = cur
+ return vals
+
+ result = func1()
+ # magictoken.ex_unbalanced.end
+ self.assertPreciseEqual(result, func1.py_func())
+
+ def test_chunksize_manual(self):
+ with captured_stdout():
+ # magictoken.ex_chunksize_manual.begin
+ from numba import (njit,
+ prange,
+ set_parallel_chunksize,
+ get_parallel_chunksize,
+ )
+
+ @njit(parallel=True)
+ def func1(n):
+ acc = 0
+ print(get_parallel_chunksize()) # Will print 4.
+ for i in prange(n):
+ print(get_parallel_chunksize()) # Will print 0.
+ acc += i
+ print(get_parallel_chunksize()) # Will print 4.
+ return acc
+
+ @njit(parallel=True)
+ def func2(n):
+ acc = 0
+ # This version gets the previous chunksize explicitly.
+ old_chunksize = get_parallel_chunksize()
+ set_parallel_chunksize(8)
+ for i in prange(n):
+ acc += i
+ set_parallel_chunksize(old_chunksize)
+ return acc
+
+ # This version saves the previous chunksize as returned
+ # by set_parallel_chunksize.
+ old_chunksize = set_parallel_chunksize(4)
+ result1 = func1(12)
+ result2 = func2(12)
+ result3 = func1(12)
+ set_parallel_chunksize(old_chunksize)
+ # magictoken.ex_chunksize_manual.end
+ self.assertPreciseEqual(result1, func1.py_func(12))
+ self.assertPreciseEqual(result2, func2.py_func(12))
+ self.assertPreciseEqual(result3, func1.py_func(12))
+
+ def test_chunksize_with(self):
+ with captured_stdout():
+ # magictoken.ex_chunksize_with.begin
+ from numba import njit, prange, parallel_chunksize
+
+ @njit(parallel=True)
+ def func1(n):
+ acc = 0
+ for i in prange(n):
+ acc += i
+ return acc
+
+ @njit(parallel=True)
+ def func2(n):
+ acc = 0
+ with parallel_chunksize(8):
+ for i in prange(n):
+ acc += i
+ return acc
+
+ with parallel_chunksize(4):
+ result1 = func1(12)
+ result2 = func2(12)
+ result3 = func1(12)
+ # magictoken.ex_chunksize_with.end
+ self.assertPreciseEqual(result1, func1.py_func(12))
+ self.assertPreciseEqual(result2, func2.py_func(12))
+ self.assertPreciseEqual(result3, func1.py_func(12))
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/doc_examples/test_rec_array.py b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/doc_examples/test_rec_array.py
new file mode 100644
index 0000000000000000000000000000000000000000..74f7d9dc3c8828a1f6a2471f1dcba7f4c495ab48
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/doc_examples/test_rec_array.py
@@ -0,0 +1,46 @@
+import unittest
+
+
+class TestExample(unittest.TestCase):
+
+ def test_documentation_example1(self):
+ # magictoken.ex_rec_arr_const_index.begin
+ import numpy as np
+ from numba import njit
+
+ arr = np.array([(1, 2)], dtype=[('a1', 'f8'), ('a2', 'f8')])
+ fields_gl = ('a1', 'a2')
+
+ @njit
+ def get_field_sum(rec):
+ fields_lc = ('a1', 'a2')
+ field_name1 = fields_lc[0]
+ field_name2 = fields_gl[1]
+ return rec[field_name1] + rec[field_name2]
+
+ get_field_sum(arr[0]) # returns 3
+ # magictoken.ex_rec_arr_const_index.end
+ self.assertEqual(get_field_sum(arr[0]), 3)
+
+ def test_documentation_example2(self):
+ # magictoken.ex_rec_arr_lit_unroll_index.begin
+ import numpy as np
+ from numba import njit, literal_unroll
+
+ arr = np.array([(1, 2)], dtype=[('a1', 'f8'), ('a2', 'f8')])
+ fields_gl = ('a1', 'a2')
+
+ @njit
+ def get_field_sum(rec):
+ out = 0
+ for f in literal_unroll(fields_gl):
+ out += rec[f]
+ return out
+
+ get_field_sum(arr[0]) # returns 3
+ # magictoken.ex_rec_arr_lit_unroll_index.end
+ self.assertEqual(get_field_sum(arr[0]), 3)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/doc_examples/test_structref_usage.py b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/doc_examples/test_structref_usage.py
new file mode 100644
index 0000000000000000000000000000000000000000..9634a9b0e3688b8ac8dc4fe7b36904fab3ec00d6
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/doc_examples/test_structref_usage.py
@@ -0,0 +1,149 @@
+# "magictoken" is used for markers as beginning and ending of example text.
+
+import unittest
+
+# magictoken.ex_structref_type_definition.begin
+import numpy as np
+
+from numba import njit
+from numba.core import types
+from numba.experimental import structref
+
+from numba.tests.support import skip_unless_scipy
+
+
+# Define a StructRef.
+# `structref.register` associates the type with the default data model.
+# This will also install getters and setters to the fields of
+# the StructRef.
+@structref.register
+class MyStructType(types.StructRef):
+ def preprocess_fields(self, fields):
+ # This method is called by the type constructor for additional
+ # preprocessing on the fields.
+ # Here, we don't want the struct to take Literal types.
+ return tuple((name, types.unliteral(typ)) for name, typ in fields)
+
+
+# Define a Python type that can be use as a proxy to the StructRef
+# allocated inside Numba. Users can construct the StructRef via
+# the constructor for this type in python code and jit-code.
+class MyStruct(structref.StructRefProxy):
+ def __new__(cls, name, vector):
+ # Overriding the __new__ method is optional, doing so
+ # allows Python code to use keyword arguments,
+ # or add other customized behavior.
+ # The default __new__ takes `*args`.
+ # IMPORTANT: Users should not override __init__.
+ return structref.StructRefProxy.__new__(cls, name, vector)
+
+ # By default, the proxy type does not reflect the attributes or
+ # methods to the Python side. It is up to users to define
+ # these. (This may be automated in the future.)
+
+ @property
+ def name(self):
+ # To access a field, we can define a function that simply
+ # return the field in jit-code.
+ # The definition of MyStruct_get_name is shown later.
+ return MyStruct_get_name(self)
+
+ @property
+ def vector(self):
+ # The definition of MyStruct_get_vector is shown later.
+ return MyStruct_get_vector(self)
+
+
+@njit
+def MyStruct_get_name(self):
+ # In jit-code, the StructRef's attribute is exposed via
+ # structref.register
+ return self.name
+
+
+@njit
+def MyStruct_get_vector(self):
+ return self.vector
+
+
+# This associates the proxy with MyStructType for the given set of
+# fields. Notice how we are not constraining the type of each field.
+# Field types remain generic.
+structref.define_proxy(MyStruct, MyStructType, ["name", "vector"])
+# magictoken.ex_structref_type_definition.end
+
+
+@skip_unless_scipy
+class TestStructRefUsage(unittest.TestCase):
+ def test_type_definition(self):
+ np.random.seed(0)
+ # Redirect print
+ buf = []
+
+ def print(*args):
+ buf.append(args)
+
+ # magictoken.ex_structref_type_definition_test.begin
+ # Let's test our new StructRef.
+
+ # Define one in Python
+ alice = MyStruct("Alice", vector=np.random.random(3))
+
+ # Define one in jit-code
+ @njit
+ def make_bob():
+ bob = MyStruct("unnamed", vector=np.zeros(3))
+ # Mutate the attributes
+ bob.name = "Bob"
+ bob.vector = np.random.random(3)
+ return bob
+
+ bob = make_bob()
+
+ # Out: Alice: [0.5488135 0.71518937 0.60276338]
+ print(f"{alice.name}: {alice.vector}")
+ # Out: Bob: [0.88325739 0.73527629 0.87746707]
+ print(f"{bob.name}: {bob.vector}")
+
+ # Define a jit function to operate on the structs.
+ @njit
+ def distance(a, b):
+ return np.linalg.norm(a.vector - b.vector)
+
+ # Out: 0.4332647200356598
+ print(distance(alice, bob))
+ # magictoken.ex_structref_type_definition_test.end
+
+ self.assertEqual(len(buf), 3)
+
+ def test_overload_method(self):
+ # magictoken.ex_structref_method.begin
+ from numba.core.extending import overload_method
+ from numba.core.errors import TypingError
+
+ # Use @overload_method to add a method for
+ # MyStructType.distance(other)
+ # where *other* is an instance of MyStructType.
+ @overload_method(MyStructType, "distance")
+ def ol_distance(self, other):
+ # Guard that *other* is an instance of MyStructType
+ if not isinstance(other, MyStructType):
+ raise TypingError(
+ f"*other* must be a {MyStructType}; got {other}"
+ )
+
+ def impl(self, other):
+ return np.linalg.norm(self.vector - other.vector)
+
+ return impl
+
+ # Test
+ @njit
+ def test():
+ alice = MyStruct("Alice", vector=np.random.random(3))
+ bob = MyStruct("Bob", vector=np.random.random(3))
+ # Use the method
+ return alice.distance(bob)
+ # magictoken.ex_structref_method.end
+
+ self.assertIsInstance(test(), float)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/doc_examples/test_typed_dict_usage.py b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/doc_examples/test_typed_dict_usage.py
new file mode 100644
index 0000000000000000000000000000000000000000..93880fc92f9e41ade41d0676f84abe74b33ee388
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/doc_examples/test_typed_dict_usage.py
@@ -0,0 +1,111 @@
+# Contents in this file are referenced from the sphinx-generated docs.
+# "magictoken" is used for markers as beginning and ending of example text.
+
+import unittest
+from numba.tests.support import captured_stdout
+
+
+class DocsTypedDictUsageTest(unittest.TestCase):
+
+ def test_ex_typed_dict_from_cpython(self):
+ with captured_stdout():
+ # magictoken.ex_typed_dict_from_cpython.begin
+ import numpy as np
+ from numba import njit
+ from numba.core import types
+ from numba.typed import Dict
+
+ # The Dict.empty() constructs a typed dictionary.
+ # The key and value typed must be explicitly declared.
+ d = Dict.empty(
+ key_type=types.unicode_type,
+ value_type=types.float64[:],
+ )
+
+ # The typed-dict can be used from the interpreter.
+ d['posx'] = np.asarray([1, 0.5, 2], dtype='f8')
+ d['posy'] = np.asarray([1.5, 3.5, 2], dtype='f8')
+ d['velx'] = np.asarray([0.5, 0, 0.7], dtype='f8')
+ d['vely'] = np.asarray([0.2, -0.2, 0.1], dtype='f8')
+
+ # Here's a function that expects a typed-dict as the argument
+ @njit
+ def move(d):
+ # inplace operations on the arrays
+ d['posx'] += d['velx']
+ d['posy'] += d['vely']
+
+ print('posx: ', d['posx']) # Out: posx: [1. 0.5 2. ]
+ print('posy: ', d['posy']) # Out: posy: [1.5 3.5 2. ]
+
+ # Call move(d) to inplace update the arrays in the typed-dict.
+ move(d)
+
+ print('posx: ', d['posx']) # Out: posx: [1.5 0.5 2.7]
+ print('posy: ', d['posy']) # Out: posy: [1.7 3.3 2.1]
+ # magictoken.ex_typed_dict_from_cpython.end
+
+ # Test
+ np.testing.assert_array_equal(d['posx'], [1.5, 0.5, 2.7])
+ np.testing.assert_array_equal(d['posy'], [1.7, 3.3, 2.1])
+
+ def test_ex_typed_dict_njit(self):
+ with captured_stdout():
+ # magictoken.ex_typed_dict_njit.begin
+ import numpy as np
+ from numba import njit
+ from numba.core import types
+ from numba.typed import Dict
+
+ # Make array type. Type-expression is not supported in jit
+ # functions.
+ float_array = types.float64[:]
+
+ @njit
+ def foo():
+ # Make dictionary
+ d = Dict.empty(
+ key_type=types.unicode_type,
+ value_type=float_array,
+ )
+ # Fill the dictionary
+ d["posx"] = np.arange(3).astype(np.float64)
+ d["posy"] = np.arange(3, 6).astype(np.float64)
+ return d
+
+ d = foo()
+ # Print the dictionary
+ print(d) # Out: {posx: [0. 1. 2.], posy: [3. 4. 5.]}
+ # magictoken.ex_typed_dict_njit.end
+ np.testing.assert_array_equal(d['posx'], [0, 1, 2])
+ np.testing.assert_array_equal(d['posy'], [3, 4, 5])
+
+ def test_ex_inferred_dict_njit(self):
+ with captured_stdout():
+ # magictoken.ex_inferred_dict_njit.begin
+ from numba import njit
+ import numpy as np
+
+ @njit
+ def foo():
+ d = dict()
+ k = {1: np.arange(1), 2: np.arange(2)}
+ # The following tells the compiler what the key type and the
+ # value
+ # type are for `d`.
+ d[3] = np.arange(3)
+ d[5] = np.arange(5)
+ return d, k
+
+ d, k = foo()
+ print(d) # {3: [0 1 2], 5: [0 1 2 3 4]}
+ print(k) # {1: [0], 2: [0 1]}
+ # magictoken.ex_inferred_dict_njit.end
+ np.testing.assert_array_equal(d[3], [0, 1, 2])
+ np.testing.assert_array_equal(d[5], [0, 1, 2, 3, 4])
+ np.testing.assert_array_equal(k[1], [0])
+ np.testing.assert_array_equal(k[2], [0, 1])
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/doc_examples/test_typed_list_usage.py b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/doc_examples/test_typed_list_usage.py
new file mode 100644
index 0000000000000000000000000000000000000000..1d804625ecc69912af75a908bb1bc6432918b009
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/doc_examples/test_typed_list_usage.py
@@ -0,0 +1,95 @@
+# Contents in this file are referenced from the sphinx-generated docs.
+# "magictoken" is used for markers as beginning and ending of example text.
+
+import unittest
+from numba.tests.support import captured_stdout
+
+
+class DocsTypedListUsageTest(unittest.TestCase):
+
+ def test_ex_inferred_list_jit(self):
+ with captured_stdout():
+
+ # magictoken.ex_inferred_list_jit.begin
+ from numba import njit
+ from numba.typed import List
+
+ @njit
+ def foo():
+ # Instantiate a typed-list
+ l = List()
+ # Append a value to it, this will set the type to int32/int64
+ # (depending on platform)
+ l.append(42)
+ # The usual list operations, getitem, pop and length are
+ # supported
+ print(l[0]) # 42
+ l[0] = 23
+ print(l[0]) # 23
+ print(len(l)) # 1
+ l.pop()
+ print(len(l)) # 0
+ return l
+
+ foo()
+
+ # magictoken.ex_inferred_list_jit.end
+
+ def test_ex_inferred_list(self):
+ with captured_stdout():
+ # magictoken.ex_inferred_list.begin
+ from numba import njit
+ from numba.typed import List
+
+ @njit
+ def foo(mylist):
+ for i in range(10, 20):
+ mylist.append(i)
+ return mylist
+
+ # Instantiate a typed-list, outside of a jit context
+ l = List()
+ # Append a value to it, this will set the type to int32/int64
+ # (depending on platform)
+ l.append(42)
+ # The usual list operations, getitem, pop and length are supported
+ print(l[0]) # 42
+ l[0] = 23
+ print(l[0]) # 23
+ print(len(l)) # 1
+ l.pop()
+ print(len(l)) # 0
+
+ # And you can use the typed-list as an argument for a jit compiled
+ # function
+ l = foo(l)
+ print(len(l)) # 10
+
+ # You can also directly construct a typed-list from an existing
+ # Python list
+ py_list = [2, 3, 5]
+ numba_list = List(py_list)
+ print(len(numba_list)) # 3
+
+ # magictoken.ex_inferred_list.end
+
+ def test_ex_nested_list(self):
+ with captured_stdout():
+ # magictoken.ex_nested_list.begin
+ from numba.typed import List
+
+ # typed-lists can be nested in typed-lists
+ mylist = List()
+ for i in range(10):
+ l = List()
+ for i in range(10):
+ l.append(i)
+ mylist.append(l)
+ # mylist is now a list of 10 lists, each containing 10 integers
+ print(mylist)
+
+ # magictoken.ex_nested_list.end
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/gdb/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/gdb/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..b2958441fe7a098eeb66fe183b62bd4ff0edbbe2
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/gdb/__init__.py
@@ -0,0 +1,10 @@
+from os.path import dirname
+import unittest
+from unittest.suite import TestSuite
+
+from numba.testing import load_testsuite
+
+def load_tests(loader, tests, pattern):
+ suite = TestSuite()
+ suite.addTests(load_testsuite(loader, dirname(__file__)))
+ return suite
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/gdb/test_array_arg.py b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/gdb/test_array_arg.py
new file mode 100644
index 0000000000000000000000000000000000000000..cb48dae2c536a7b1e2568244bf2058ce934238f0
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/gdb/test_array_arg.py
@@ -0,0 +1,51 @@
+# NOTE: This test is sensitive to line numbers as it checks breakpoints
+from numba import njit, types
+import numpy as np
+from numba.tests.gdb_support import GdbMIDriver
+from numba.tests.support import TestCase, needs_subprocess
+import unittest
+
+
+@needs_subprocess
+class Test(TestCase):
+
+ def test(self):
+ @njit(debug=True)
+ def foo(x):
+ z = np.ones_like(x) # break here
+ return x, z
+
+ tmp = np.ones(5)
+ foo(tmp)
+
+ driver = GdbMIDriver(__file__)
+ driver.set_breakpoint(line=15)
+ driver.run()
+ driver.check_hit_breakpoint(1)
+ driver.stack_list_arguments(2)
+ llvm_intp = f"i{types.intp.bitwidth}"
+ expect = (
+ '[frame={level="0",args=[{name="x",type="array(float64, 1d, C) '
+ f'({{i8*, i8*, {llvm_intp}, {llvm_intp}, double*, '
+ f'[1 x {llvm_intp}], [1 x {llvm_intp}]}})"}}]}}]'
+ )
+ driver.assert_output(expect)
+ driver.stack_list_variables(1)
+ # 'z' should be zero-init
+ expect = ('{name="z",value="{meminfo = 0x0, parent = 0x0, nitems = 0, '
+ 'itemsize = 0, data = 0x0, shape = {0}, strides = {0}}"}')
+ driver.assert_output(expect)
+ driver.set_breakpoint(line=16)
+ driver.cont()
+ driver.check_hit_breakpoint(2)
+ driver.stack_list_variables(1)
+ # 'z' should be populated
+ expect = (r'^.*\{name="z",value="\{meminfo = 0x[0-9a-f]+ .*, '
+ r'parent = 0x0, nitems = 5, itemsize = 8, '
+ r'data = 0x[0-9a-f]+, shape = \{5\}, strides = \{8\}\}.*$')
+ driver.assert_regex_output(expect)
+ driver.quit()
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/gdb/test_basic.py b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/gdb/test_basic.py
new file mode 100644
index 0000000000000000000000000000000000000000..2a28d6f7468221098ac56e41cb221f704b27a0be
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/gdb/test_basic.py
@@ -0,0 +1,39 @@
+# NOTE: This test is sensitive to line numbers as it checks breakpoints
+from numba import njit, types
+from numba.tests.gdb_support import GdbMIDriver
+from numba.tests.support import TestCase, needs_subprocess
+import unittest
+
+
+@needs_subprocess
+class Test(TestCase):
+
+ def test(self):
+ @njit(debug=True)
+ def foo(x):
+ z = 7 + x # break here
+ return x, z
+
+ foo(120)
+
+ sz = types.intp.bitwidth
+ driver = GdbMIDriver(__file__)
+ driver.set_breakpoint(line=14)
+ driver.run()
+ driver.check_hit_breakpoint(1)
+ driver.stack_list_arguments(2)
+ expect = ('[frame={level="0",args=[{name="x",type="int%s",'
+ 'value="120"}]}]' % sz)
+ driver.assert_output(expect)
+ driver.stack_list_variables(1)
+ expect = '[{name="x",arg="1",value="120"},{name="z",value="0"}]'
+ driver.assert_output(expect)
+ driver.next()
+ driver.stack_list_variables(1)
+ expect = '[{name="x",arg="1",value="120"},{name="z",value="127"}]'
+ driver.assert_output(expect)
+ driver.quit()
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/gdb/test_break_on_symbol.py b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/gdb/test_break_on_symbol.py
new file mode 100644
index 0000000000000000000000000000000000000000..7743aafc3bebc87db5257452c34ada5b1cf5b682
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/gdb/test_break_on_symbol.py
@@ -0,0 +1,34 @@
+# NOTE: This test is sensitive to line numbers as it checks breakpoints
+from numba import njit, types
+from numba.tests.gdb_support import GdbMIDriver
+from numba.tests.support import TestCase, needs_subprocess
+import unittest
+
+
+@njit(debug=True)
+def foo(x):
+ z = 7 + x
+ return x, z
+
+
+@needs_subprocess
+class Test(TestCase):
+
+ def test(self):
+ foo(120)
+ sz = types.intp.bitwidth
+ driver = GdbMIDriver(__file__)
+ driver.set_breakpoint(symbol="__main__::foo")
+ driver.run() # will hit cpython symbol match
+ driver.check_hit_breakpoint(number=1)
+ driver.cont() # will hit njit symbol match
+ driver.check_hit_breakpoint(number=1, line=10) # Ensure line number
+ driver.stack_list_arguments(2)
+ expect = ('[frame={level="0",args=[{name="x",type="int%s",'
+ 'value="120"}]}]' % sz)
+ driver.assert_output(expect)
+ driver.quit()
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/gdb/test_break_on_symbol_version.py b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/gdb/test_break_on_symbol_version.py
new file mode 100644
index 0000000000000000000000000000000000000000..72f09b19ab11f11b3d6bfb68cefec554a6e9f29e
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/gdb/test_break_on_symbol_version.py
@@ -0,0 +1,65 @@
+# NOTE: This test is sensitive to line numbers as it checks breakpoints
+from numba import njit
+from numba.tests.gdb_support import GdbMIDriver
+from numba.tests.support import TestCase, needs_subprocess
+import unittest
+
+
+def foo_factory(n):
+ @njit(debug=True)
+ def foo(x):
+ z = 7 + n
+ return x, z
+
+ return foo
+
+
+foo1, foo2, foo3 = [foo_factory(x) for x in range(3)]
+
+
+@njit(debug=True)
+def call_foo():
+ a = foo1(10)
+ b = foo2(20)
+ c = foo3(30)
+ return a, b, c
+
+
+@needs_subprocess
+class Test(TestCase):
+
+ def test(self):
+ call_foo()
+ driver = GdbMIDriver(__file__)
+ # A specific foo, the first one, it has uid=2
+ vsym = "__main__::foo_factory::_3clocals_3e::foo[abi:v2]"
+ driver.set_breakpoint(symbol=vsym)
+ driver.run()
+ driver.check_hit_breakpoint(number=1)
+ driver.assert_regex_output(r'^.*foo\[abi:v2\].*line="11"')
+ driver.stack_list_arguments(2)
+ expect = ('[frame={level="0",args=[{name="x",type="Literal[int](10)",'
+ 'value="10"}]}]')
+ driver.assert_output(expect)
+ # Now break on any foo
+ driver.set_breakpoint(symbol="foo")
+ driver.cont()
+ driver.check_hit_breakpoint(number=2)
+ driver.assert_regex_output(r'^.*foo\[abi:v3\].*line="11"')
+ driver.stack_list_arguments(2)
+ expect = ('[frame={level="0",args=[{name="x",type="Literal[int](20)",'
+ 'value="20"}]}]')
+ driver.assert_output(expect)
+ # and again, hit the third foo
+ driver.cont()
+ driver.check_hit_breakpoint(number=2)
+ driver.assert_regex_output(r'^.*foo\[abi:v4\].*line="11"')
+ driver.stack_list_arguments(2)
+ expect = ('[frame={level="0",args=[{name="x",type="Literal[int](30)",'
+ 'value="30"}]}]')
+ driver.assert_output(expect)
+ driver.quit()
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/gdb/test_conditional_breakpoint.py b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/gdb/test_conditional_breakpoint.py
new file mode 100644
index 0000000000000000000000000000000000000000..867a53eb16b82cb0fbd5e03a8e833afd3640bfcf
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/gdb/test_conditional_breakpoint.py
@@ -0,0 +1,45 @@
+# NOTE: This test is sensitive to line numbers as it checks breakpoints
+from numba import njit
+from numba.tests.gdb_support import GdbMIDriver
+from numba.tests.support import TestCase, needs_subprocess
+import unittest
+
+
+@needs_subprocess
+class Test(TestCase):
+
+ def test(self):
+
+ @njit(debug=True)
+ def foo(x, y):
+ c = x + y # break-here
+ return c
+
+ @njit(debug=True)
+ def call_foo(a):
+ acc = 0
+ for i in range(10):
+ acc += foo(i, a)
+ return acc
+
+ call_foo(10)
+
+ driver = GdbMIDriver(__file__)
+ driver.set_breakpoint(line=15, condition='x == 4')
+ driver.run()
+ driver.check_hit_breakpoint(1)
+ driver.stack_list_arguments(1)
+ expect = ('[frame={level="0",args=[{name="x",value="4"},'
+ '{name="y",value="10"}]}]')
+ driver.assert_output(expect)
+ driver.set_breakpoint(line=22, condition='i == 8')
+ driver.cont()
+ driver.check_hit_breakpoint(2)
+ driver.stack_list_variables(1)
+ # i should be 8
+ driver.assert_output('{name="i",value="8"}')
+ driver.quit()
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/gdb/test_pretty_print.py b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/gdb/test_pretty_print.py
new file mode 100644
index 0000000000000000000000000000000000000000..b0be5dbe8e4fcb78e2c1edafc679a4ebe3b1bbee
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/gdb/test_pretty_print.py
@@ -0,0 +1,69 @@
+# NOTE: This test is sensitive to line numbers as it checks breakpoints
+from numba import njit
+import numpy as np
+from numba.tests.gdb_support import GdbMIDriver, needs_gdb_py3
+from numba.tests.support import TestCase, needs_subprocess
+from numba.misc.numba_gdbinfo import collect_gdbinfo
+import unittest
+import re
+
+
+@needs_gdb_py3
+@needs_subprocess
+class Test(TestCase):
+
+ def test(self):
+ rdt_a = np.dtype([("x", np.int16), ("y", np.float64)], align=True)
+
+ @njit(debug=True)
+ def foo():
+ a = 1.234
+ b = (1, 2, 3)
+ c = ('a', b, 4)
+ d = np.arange(5.)
+ e = np.array([[1, 3j], [2, 4j]])
+ f = "Some string" + " L-Padded string".lstrip()
+ g = 11 + 22j
+ h = np.arange(24).reshape((4, 6))[::2, ::3]
+ i = np.zeros(2, dtype=rdt_a)
+ return a, b, c, d, e, f, g, h, i
+
+ foo()
+
+ extension = collect_gdbinfo().extension_loc
+ driver = GdbMIDriver(__file__, init_cmds=['-x', extension], debug=False)
+ driver.set_breakpoint(line=29)
+ driver.run()
+ driver.check_hit_breakpoint(1)
+
+ # Ideally the function would be run to get the string repr of locals
+ # but not everything appears in DWARF e.g. string literals. Further,
+ # str on NumPy arrays seems to vary a bit in output. Therefore a custom
+ # match is used.
+
+ driver.stack_list_variables(1)
+ output = driver._captured.after.decode('UTF-8')
+ done_str = output.splitlines()[0]
+ pat = r'^\^done,variables=\[\{(.*)\}\]$'
+ lcls_strs = re.match(pat, done_str).groups()[0].split('},{')
+ lcls = {k: v for k, v in [re.match(r'name="(.*)",value="(.*)"',
+ x).groups() for x in lcls_strs]}
+ expected = dict()
+ expected['a'] = r'1\.234'
+ expected['b'] = r'\(1, 2, 3\)'
+ expected['c'] = r'\(0x0, \(1, 2, 3\), 4\)'
+ expected['d'] = r'\\n\[0. 1. 2. 3. 4.\]'
+ expected['e'] = r'\\n\[\[1.\+0.j 0.\+3.j\]\\n \[2.\+0.j 0.\+4.j\]\]'
+ expected['f'] = "'Some stringL-Padded string'"
+ expected['g'] = r"11\+22j"
+ expected['h'] = r'\\n\[\[ 0 3\]\\n \[12 15\]\]'
+ expected['i'] = r'\\n\[\(0, 0.\) \(0, 0.\)\]'
+
+ for k, v in expected.items():
+ self.assertRegex(lcls[k], v)
+
+ driver.quit()
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/npyufunc/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/npyufunc/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..b2958441fe7a098eeb66fe183b62bd4ff0edbbe2
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/npyufunc/__init__.py
@@ -0,0 +1,10 @@
+from os.path import dirname
+import unittest
+from unittest.suite import TestSuite
+
+from numba.testing import load_testsuite
+
+def load_tests(loader, tests, pattern):
+ suite = TestSuite()
+ suite.addTests(load_testsuite(loader, dirname(__file__)))
+ return suite
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/npyufunc/cache_usecases.py b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/npyufunc/cache_usecases.py
new file mode 100644
index 0000000000000000000000000000000000000000..4d250756d404b1e87115e4a191768925e5c2bc21
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/npyufunc/cache_usecases.py
@@ -0,0 +1,76 @@
+import numba as nb
+
+
+#
+# UFunc
+#
+
+def direct_ufunc_cache_usecase(**kwargs):
+ @nb.vectorize(["intp(intp)", "float64(float64)"], cache=True, **kwargs)
+ def ufunc(inp):
+ return inp * 2
+
+ return ufunc
+
+
+def indirect_ufunc_cache_usecase(**kwargs):
+ @nb.njit(cache=True)
+ def indirect_ufunc_core(inp):
+ return inp * 3
+
+ @nb.vectorize(["intp(intp)", "float64(float64)", "complex64(complex64)"],
+ **kwargs)
+ def ufunc(inp):
+ return indirect_ufunc_core(inp)
+
+ return ufunc
+
+
+#
+# DUFunc
+#
+
+def direct_dufunc_cache_usecase(**kwargs):
+ @nb.vectorize(cache=True, **kwargs)
+ def ufunc(inp):
+ return inp * 2
+
+ return ufunc
+
+
+def indirect_dufunc_cache_usecase(**kwargs):
+ @nb.njit(cache=True)
+ def indirect_ufunc_core(inp):
+ return inp * 3
+
+ @nb.vectorize(**kwargs)
+ def ufunc(inp):
+ return indirect_ufunc_core(inp)
+
+ return ufunc
+
+
+#
+# GUFunc
+#
+
+def direct_gufunc_cache_usecase(**kwargs):
+ @nb.guvectorize(["(intp, intp[:])", "(float64, float64[:])"],
+ "()->()", cache=True, **kwargs)
+ def gufunc(inp, out):
+ out[0] = inp * 2
+
+ return gufunc
+
+
+def indirect_gufunc_cache_usecase(**kwargs):
+ @nb.njit(cache=True)
+ def core(x):
+ return x * 3
+
+ @nb.guvectorize(["(intp, intp[:])", "(float64, float64[:])",
+ "(complex64, complex64[:])"], "()->()", **kwargs)
+ def gufunc(inp, out):
+ out[0] = core(inp)
+
+ return gufunc
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/npyufunc/test_caching.py b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/npyufunc/test_caching.py
new file mode 100644
index 0000000000000000000000000000000000000000..cfb47f113211721bdeea9ea2327f811833706e9b
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/npyufunc/test_caching.py
@@ -0,0 +1,228 @@
+import sys
+import os.path
+import re
+import subprocess
+
+import numpy as np
+
+from numba.tests.support import capture_cache_log
+from numba.tests.test_caching import BaseCacheTest
+from numba.core import config
+import unittest
+
+
+class UfuncCacheTest(BaseCacheTest):
+ """
+ Since the cache stats is not exposed by ufunc, we test by looking at the
+ cache debug log.
+ """
+ _numba_parallel_test_ = False
+
+ here = os.path.dirname(__file__)
+ usecases_file = os.path.join(here, "cache_usecases.py")
+ modname = "ufunc_caching_test_fodder"
+
+ regex_data_saved = re.compile(r'\[cache\] data saved to')
+ regex_index_saved = re.compile(r'\[cache\] index saved to')
+
+ regex_data_loaded = re.compile(r'\[cache\] data loaded from')
+ regex_index_loaded = re.compile(r'\[cache\] index loaded from')
+
+ def check_cache_saved(self, cachelog, count):
+ """
+ Check number of cache-save were issued
+ """
+ data_saved = self.regex_data_saved.findall(cachelog)
+ index_saved = self.regex_index_saved.findall(cachelog)
+ self.assertEqual(len(data_saved), count)
+ self.assertEqual(len(index_saved), count)
+
+ def check_cache_loaded(self, cachelog, count):
+ """
+ Check number of cache-load were issued
+ """
+ data_loaded = self.regex_data_loaded.findall(cachelog)
+ index_loaded = self.regex_index_loaded.findall(cachelog)
+ self.assertEqual(len(data_loaded), count)
+ self.assertEqual(len(index_loaded), count)
+
+ def check_ufunc_cache(self, usecase_name, n_overloads, **kwargs):
+ """
+ Check number of cache load/save.
+ There should be one per overloaded version.
+ """
+ mod = self.import_module()
+ usecase = getattr(mod, usecase_name)
+ # New cache entry saved
+ with capture_cache_log() as out:
+ new_ufunc = usecase(**kwargs)
+ cachelog = out.getvalue()
+ self.check_cache_saved(cachelog, count=n_overloads)
+
+ # Use cached version
+ with capture_cache_log() as out:
+ cached_ufunc = usecase(**kwargs)
+ cachelog = out.getvalue()
+ self.check_cache_loaded(cachelog, count=n_overloads)
+
+ return new_ufunc, cached_ufunc
+
+
+class TestUfuncCacheTest(UfuncCacheTest):
+
+ def test_direct_ufunc_cache(self, **kwargs):
+ new_ufunc, cached_ufunc = self.check_ufunc_cache(
+ "direct_ufunc_cache_usecase", n_overloads=2, **kwargs)
+ # Test the cached and original versions
+ inp = np.random.random(10).astype(np.float64)
+ np.testing.assert_equal(new_ufunc(inp), cached_ufunc(inp))
+ inp = np.arange(10, dtype=np.intp)
+ np.testing.assert_equal(new_ufunc(inp), cached_ufunc(inp))
+
+ def test_direct_ufunc_cache_objmode(self):
+ self.test_direct_ufunc_cache(forceobj=True)
+
+ def test_direct_ufunc_cache_parallel(self):
+ self.test_direct_ufunc_cache(target='parallel')
+
+ def test_indirect_ufunc_cache(self, **kwargs):
+ new_ufunc, cached_ufunc = self.check_ufunc_cache(
+ "indirect_ufunc_cache_usecase", n_overloads=3, **kwargs)
+ # Test the cached and original versions
+ inp = np.random.random(10).astype(np.float64)
+ np.testing.assert_equal(new_ufunc(inp), cached_ufunc(inp))
+ inp = np.arange(10, dtype=np.intp)
+ np.testing.assert_equal(new_ufunc(inp), cached_ufunc(inp))
+
+ def test_indirect_ufunc_cache_parallel(self):
+ self.test_indirect_ufunc_cache(target='parallel')
+
+
+class TestDUfuncCacheTest(UfuncCacheTest):
+ # Note: DUFunc doesn't support parallel target yet
+
+ def check_dufunc_usecase(self, usecase_name):
+ mod = self.import_module()
+ usecase = getattr(mod, usecase_name)
+ # Create dufunc
+ with capture_cache_log() as out:
+ ufunc = usecase()
+ self.check_cache_saved(out.getvalue(), count=0)
+ # Compile & cache
+ with capture_cache_log() as out:
+ ufunc(np.arange(10))
+ self.check_cache_saved(out.getvalue(), count=1)
+ self.check_cache_loaded(out.getvalue(), count=0)
+ # Use cached
+ with capture_cache_log() as out:
+ ufunc = usecase()
+ ufunc(np.arange(10))
+ self.check_cache_loaded(out.getvalue(), count=1)
+
+ def test_direct_dufunc_cache(self):
+ # We don't test for objmode because DUfunc don't support it.
+ self.check_dufunc_usecase('direct_dufunc_cache_usecase')
+
+ def test_indirect_dufunc_cache(self):
+ self.check_dufunc_usecase('indirect_dufunc_cache_usecase')
+
+
+def _fix_raw_path(rstr):
+ if config.IS_WIN32:
+ rstr = rstr.replace(r'/', r'\\\\')
+ return rstr
+
+
+class TestGUfuncCacheTest(UfuncCacheTest):
+
+ def test_filename_prefix(self):
+ mod = self.import_module()
+ usecase = getattr(mod, "direct_gufunc_cache_usecase")
+ with capture_cache_log() as out:
+ usecase()
+ cachelog = out.getvalue()
+ # find number filename with "guf-" prefix
+ fmt1 = _fix_raw_path(r'/__pycache__/guf-{}')
+ prefixed = re.findall(fmt1.format(self.modname), cachelog)
+ fmt2 = _fix_raw_path(r'/__pycache__/{}')
+ normal = re.findall(fmt2.format(self.modname), cachelog)
+ # expecting 2 overloads
+ self.assertGreater(len(normal), 2)
+ # expecting equal number of wrappers and overloads cache entries
+ self.assertEqual(len(normal), len(prefixed))
+
+ def test_direct_gufunc_cache(self, **kwargs):
+ # 2 cache entry for the 2 overloads
+ # and 2 cache entry for the gufunc wrapper
+ new_ufunc, cached_ufunc = self.check_ufunc_cache(
+ "direct_gufunc_cache_usecase", n_overloads=2 + 2, **kwargs)
+ # Test the cached and original versions
+ inp = np.random.random(10).astype(np.float64)
+ np.testing.assert_equal(new_ufunc(inp), cached_ufunc(inp))
+ inp = np.arange(10, dtype=np.intp)
+ np.testing.assert_equal(new_ufunc(inp), cached_ufunc(inp))
+
+ def test_direct_gufunc_cache_objmode(self):
+ self.test_direct_gufunc_cache(forceobj=True)
+
+ def test_direct_gufunc_cache_parallel(self):
+ self.test_direct_gufunc_cache(target='parallel')
+
+ def test_indirect_gufunc_cache(self, **kwargs):
+ # 3 cache entry for the 3 overloads
+ # and no cache entry for the gufunc wrapper
+ new_ufunc, cached_ufunc = self.check_ufunc_cache(
+ "indirect_gufunc_cache_usecase", n_overloads=3, **kwargs)
+ # Test the cached and original versions
+ inp = np.random.random(10).astype(np.float64)
+ np.testing.assert_equal(new_ufunc(inp), cached_ufunc(inp))
+ inp = np.arange(10, dtype=np.intp)
+ np.testing.assert_equal(new_ufunc(inp), cached_ufunc(inp))
+
+ def test_indirect_gufunc_cache_parallel(self, **kwargs):
+ self.test_indirect_gufunc_cache(target='parallel')
+
+
+class TestCacheSpecificIssue(UfuncCacheTest):
+
+ def run_in_separate_process(self, runcode):
+ # Based on the same name util function in test_dispatcher but modified
+ # to allow user to define what to run.
+ code = """if 1:
+ import sys
+
+ sys.path.insert(0, %(tempdir)r)
+ mod = __import__(%(modname)r)
+ mod.%(runcode)s
+ """ % dict(tempdir=self.tempdir, modname=self.modname,
+ runcode=runcode)
+
+ popen = subprocess.Popen([sys.executable, "-c", code],
+ stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+ out, err = popen.communicate()
+ if popen.returncode != 0:
+ raise AssertionError("process failed with code %s: stderr follows"
+ "\n%s\n" % (popen.returncode, err.decode()))
+
+ #
+ # The following test issue #2198 that loading cached (g)ufunc first
+ # bypasses some target context initialization.
+ #
+
+ def test_first_load_cached_ufunc(self):
+ # ensure function is cached
+ self.run_in_separate_process('direct_ufunc_cache_usecase()')
+ # use the cached function
+ # this will fail if the target context is not init'ed
+ self.run_in_separate_process('direct_ufunc_cache_usecase()')
+
+ def test_first_load_cached_gufunc(self):
+ # ensure function is cached
+ self.run_in_separate_process('direct_gufunc_cache_usecase()')
+ # use the cached function
+ # this will fail out if the target context is not init'ed
+ self.run_in_separate_process('direct_gufunc_cache_usecase()')
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/npyufunc/test_dufunc.py b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/npyufunc/test_dufunc.py
new file mode 100644
index 0000000000000000000000000000000000000000..3902e291d1365a06216ab8071a3ccdd86c3105a9
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/npyufunc/test_dufunc.py
@@ -0,0 +1,931 @@
+import itertools
+import pickle
+import textwrap
+import warnings
+
+import numpy as np
+
+from numba import njit, vectorize
+from numba.tests.support import MemoryLeakMixin, TestCase
+from numba.core.errors import (TypingError, NumbaNotImplementedError,
+ NumbaExperimentalFeatureWarning)
+import unittest
+from numba.np.ufunc import dufunc
+from numba.np.numpy_support import from_dtype
+
+
+def pyuadd(a0, a1):
+ return a0 + a1
+
+
+def pysub(a0, a1):
+ return a0 - a1
+
+
+def pymult(a0, a1):
+ return a0 * a1
+
+
+def pydiv(a0, a1):
+ return a0 // a1
+
+
+def pymin(a0, a1):
+ return a0 if a0 < a1 else a1
+
+
+class TestDUFunc(MemoryLeakMixin, unittest.TestCase):
+
+ def nopython_dufunc(self, pyfunc):
+ return dufunc.DUFunc(pyfunc, targetoptions=dict(nopython=True))
+
+ def test_frozen(self):
+ duadd = self.nopython_dufunc(pyuadd)
+ self.assertFalse(duadd._frozen)
+ duadd._frozen = True
+ self.assertTrue(duadd._frozen)
+ with self.assertRaises(ValueError):
+ duadd._frozen = False
+ with self.assertRaises(TypeError):
+ duadd(np.linspace(0,1,10), np.linspace(1,2,10))
+
+ def test_scalar(self):
+ duadd = self.nopython_dufunc(pyuadd)
+ self.assertEqual(pyuadd(1,2), duadd(1,2))
+
+ def test_npm_call(self):
+ duadd = self.nopython_dufunc(pyuadd)
+
+ @njit
+ def npmadd(a0, a1, o0):
+ duadd(a0, a1, o0)
+ X = np.linspace(0,1.9,20)
+ X0 = X[:10]
+ X1 = X[10:]
+ out0 = np.zeros(10)
+ npmadd(X0, X1, out0)
+ np.testing.assert_array_equal(X0 + X1, out0)
+ Y0 = X0.reshape((2,5))
+ Y1 = X1.reshape((2,5))
+ out1 = np.zeros((2,5))
+ npmadd(Y0, Y1, out1)
+ np.testing.assert_array_equal(Y0 + Y1, out1)
+ Y2 = X1[:5]
+ out2 = np.zeros((2,5))
+ npmadd(Y0, Y2, out2)
+ np.testing.assert_array_equal(Y0 + Y2, out2)
+
+ def test_npm_call_implicit_output(self):
+ duadd = self.nopython_dufunc(pyuadd)
+
+ @njit
+ def npmadd(a0, a1):
+ return duadd(a0, a1)
+ X = np.linspace(0,1.9,20)
+ X0 = X[:10]
+ X1 = X[10:]
+ out0 = npmadd(X0, X1)
+ np.testing.assert_array_equal(X0 + X1, out0)
+ Y0 = X0.reshape((2,5))
+ Y1 = X1.reshape((2,5))
+ out1 = npmadd(Y0, Y1)
+ np.testing.assert_array_equal(Y0 + Y1, out1)
+ Y2 = X1[:5]
+ out2 = npmadd(Y0, Y2)
+ np.testing.assert_array_equal(Y0 + Y2, out2)
+ out3 = npmadd(1.,2.)
+ self.assertEqual(out3, 3.)
+
+ def test_ufunc_props(self):
+ duadd = self.nopython_dufunc(pyuadd)
+ self.assertEqual(duadd.nin, 2)
+ self.assertEqual(duadd.nout, 1)
+ self.assertEqual(duadd.nargs, duadd.nin + duadd.nout)
+ self.assertEqual(duadd.ntypes, 0)
+ self.assertEqual(duadd.types, [])
+ self.assertEqual(duadd.identity, None)
+ duadd(1, 2)
+ self.assertEqual(duadd.ntypes, 1)
+ self.assertEqual(duadd.ntypes, len(duadd.types))
+ self.assertIsNone(duadd.signature)
+
+ def test_ufunc_props_jit(self):
+ duadd = self.nopython_dufunc(pyuadd)
+ duadd(1, 2) # initialize types attribute
+
+ attributes = {'nin': duadd.nin,
+ 'nout': duadd.nout,
+ 'nargs': duadd.nargs,
+ #'ntypes': duadd.ntypes,
+ #'types': duadd.types,
+ 'identity': duadd.identity,
+ 'signature': duadd.signature}
+
+ def get_attr_fn(attr):
+ fn = f'''
+ def impl():
+ return duadd.{attr}
+ '''
+ l = {}
+ exec(textwrap.dedent(fn), {'duadd': duadd}, l)
+ return l['impl']
+
+ for attr, val in attributes.items():
+ cfunc = njit(get_attr_fn(attr))
+ self.assertEqual(val, cfunc(),
+ f'Attribute differs from original: {attr}')
+
+ # We don't expose [n]types attributes as they are dynamic attributes
+ # and can change as the user calls the ufunc
+ # cfunc = njit(get_attr_fn('ntypes'))
+ # self.assertEqual(cfunc(), 1)
+ # duadd(1.1, 2.2)
+ # self.assertEqual(cfunc(), 2)
+
+
+class TestDUFuncAt(TestCase):
+ def _compare_output(self, fn, ufunc, a, *args):
+ expected = a.copy()
+ got = a.copy()
+ ufunc.at(expected, *args)
+ fn(got, *args)
+ self.assertPreciseEqual(expected, got)
+
+ def _generate_jit(self, ufunc):
+ if ufunc.nin == 2:
+ vec = vectorize()(lambda a, b: ufunc(a, b))
+ else:
+ vec = vectorize()(lambda a: ufunc(a))
+
+ @njit
+ def fn(*args):
+ return vec.at(*args)
+ return fn
+
+ def test_numpy_ufunc_at_basic(self):
+ # tests taken from: https://github.com/numpy/numpy/blob/27d8c43eb958b4ecee59b4d66908750759a9afc2/numpy/core/tests/test_ufunc.py#L1974-L2003 # noqa: E501
+ # NumPy also test this function with a Rational array dtype. We skip
+ # this test as Numba doesn't support Rational
+ a = np.arange(10, dtype=int)
+
+ add_at = self._generate_jit(np.add)
+ negative_at = self._generate_jit(np.negative)
+
+ negative_vec = vectorize()(lambda a: np.negative(a))
+
+ @njit
+ def negative_jit_2(a, indices, b):
+ return negative_vec.at(a, indices, b)
+
+ # basic testing
+ self._compare_output(add_at, np.add, a, [2, 5, 2], 1)
+
+ # missing second operand
+ err_msg = 'second operand needed for ufunc'
+ with self.assertRaisesRegex(TypingError, err_msg):
+ add_at(a.copy(), [2, 5, 3], None)
+
+ self._compare_output(negative_at, np.negative, a.copy(), [2, 5, 3])
+
+ b = np.array([100, 100, 100])
+ self._compare_output(add_at, np.add, a.copy(), [2, 5, 2], b)
+
+ # extraneous second operand
+ err_msg = 'second operand provided when ufunc is unary'
+ with self.assertRaisesRegex(TypingError, err_msg):
+ negative_jit_2(a.copy(), [2, 5, 3], [1, 2, 3])
+
+ with self.assertRaises(TypingError):
+ add_at(a.copy(), [2, 5, 3], [[1, 2], 1])
+
+ def test_ufunc_at_inner_loop(self):
+ typecodes = np.typecodes['Complex']
+ ufuncs = (np.add, np.subtract, np.multiply)
+ for typecode in typecodes:
+
+ try:
+ from_dtype(np.dtype(typecode))
+ except NumbaNotImplementedError:
+ continue
+
+ for ufunc in ufuncs:
+ a = np.ones(10, dtype=typecode)
+ indx = np.concatenate([np.ones(6, dtype=np.intp),
+ np.full(18, 4, dtype=np.intp)])
+ value = a.dtype.type(1j)
+ ufunc_at = self._generate_jit(ufunc)
+ ufunc_at(a, indx, value)
+ expected = np.ones_like(a)
+ if ufunc is np.multiply:
+ expected[1] = expected[4] = -1
+ else:
+ expected[1] += 6 * (value if ufunc is np.add else -value)
+ expected[4] += 18 * (value if ufunc is np.add else -value)
+
+ self.assertPreciseEqual(a, expected)
+
+ def test_ufunc_at_ellipsis(self):
+ # Make sure the indexed loop check does not choke on iters
+ # with subspaces
+ arr = np.zeros(5, dtype=int)
+ add_at = self._generate_jit(np.add)
+ self._compare_output(add_at, np.add, arr, slice(None),
+ np.ones(5, dtype=int))
+
+ def test_ufunc_at_negative(self):
+ arr = np.ones(5, dtype=np.int32)
+ indx = np.arange(5)
+ at = self._generate_jit(np.negative)
+ at(arr, indx)
+ assert np.all(arr == [-1, -1, -1, -1, -1])
+
+ def test_ufunc_at_large(self):
+ # NumPy issue gh-23457
+ indices = np.zeros(8195, dtype=np.int16)
+ b = np.zeros(8195, dtype=float)
+ b[0] = 10
+ b[1] = 5
+ b[8192:] = 100
+ a = np.zeros(1, dtype=float)
+ add_at = self._generate_jit(np.add)
+ add_at(a, indices, b)
+ assert a[0] == b.sum()
+
+ def test_cast_index_fastpath(self):
+ arr = np.zeros(10)
+ values = np.ones(100000)
+ add_at = self._generate_jit(np.add)
+ # index must be cast, which may be buffered in chunks:
+ index = np.zeros(len(values), dtype=np.uint8)
+ add_at(arr, index, values)
+ assert arr[0] == len(values)
+
+ def test_ufunc_at_scalar_value_fastpath(self):
+ values = (np.ones(1), np.ones(()), np.float64(1.), 1.)
+ for value in values:
+ arr = np.zeros(1000)
+ # index must be cast, which may be buffered in chunks:
+ index = np.repeat(np.arange(1000), 2)
+ add_at = self._generate_jit(np.add)
+ add_at(arr, index, value)
+ np.testing.assert_array_equal(arr, np.full_like(arr, 2 * value))
+
+ def test_ufunc_at_multiD(self):
+ a = np.arange(9).reshape(3, 3)
+ b = np.array([[100, 100, 100], [200, 200, 200], [300, 300, 300]])
+ add_at = self._generate_jit(np.add)
+ add_at(a, (slice(None), np.asarray([1, 2, 1])), b)
+ self.assertPreciseEqual(a, np.array(
+ [[0, 201, 102], [3, 404, 205], [6, 607, 308]]))
+
+ a = np.arange(27).reshape(3, 3, 3)
+ b = np.array([100, 200, 300])
+ add_at(a, (slice(None), slice(None), np.asarray([1, 2, 1])), b)
+ self.assertPreciseEqual(a, np.array(
+ [[[0, 401, 202],
+ [3, 404, 205],
+ [6, 407, 208]],
+
+ [[9, 410, 211],
+ [12, 413, 214],
+ [15, 416, 217]],
+
+ [[18, 419, 220],
+ [21, 422, 223],
+ [24, 425, 226]]]))
+
+ a = np.arange(9).reshape(3, 3)
+ b = np.array([[100, 100, 100], [200, 200, 200], [300, 300, 300]])
+ add_at(a, (np.asarray([1, 2, 1]), slice(None)), b)
+ self.assertPreciseEqual(a, np.asarray(
+ [[0, 1, 2], [403, 404, 405], [206, 207, 208]]))
+
+ a = np.arange(27).reshape(3, 3, 3)
+ b = np.array([100, 200, 300])
+ add_at(a, (slice(None), np.asarray([1, 2, 1]), slice(None)), b)
+ self.assertPreciseEqual(a, np.asarray(
+ [[[0, 1, 2],
+ [203, 404, 605],
+ [106, 207, 308]],
+
+ [[9, 10, 11],
+ [212, 413, 614],
+ [115, 216, 317]],
+
+ [[18, 19, 20],
+ [221, 422, 623],
+ [124, 225, 326]]]))
+
+ a = np.arange(9).reshape(3, 3)
+ b = np.array([100, 200, 300])
+ add_at(a, (0, np.asarray([1, 2, 1])), b)
+ self.assertPreciseEqual(a, np.asarray(
+ [[0, 401, 202], [3, 4, 5], [6, 7, 8]]))
+
+ a = np.arange(27).reshape(3, 3, 3)
+ b = np.array([100, 200, 300])
+ add_at(a, (np.asarray([1, 2, 1]), 0, slice(None)), b)
+ self.assertPreciseEqual(a, np.asarray(
+ [[[0, 1, 2],
+ [3, 4, 5],
+ [6, 7, 8]],
+
+ [[209, 410, 611],
+ [12, 13, 14],
+ [15, 16, 17]],
+
+ [[118, 219, 320],
+ [21, 22, 23],
+ [24, 25, 26]]]))
+
+ a = np.arange(27).reshape(3, 3, 3)
+ b = np.array([100, 200, 300])
+ add_at = self._generate_jit(np.add)
+ add_at(a, (slice(None), slice(None), slice(None)), b)
+ self.assertPreciseEqual(a, np.asarray(
+ [[[100, 201, 302],
+ [103, 204, 305],
+ [106, 207, 308]],
+
+ [[109, 210, 311],
+ [112, 213, 314],
+ [115, 216, 317]],
+
+ [[118, 219, 320],
+ [121, 222, 323],
+ [124, 225, 326]]]))
+
+ def test_ufunc_at_0D(self):
+ a = np.array(0)
+ add_at = self._generate_jit(np.add)
+ add_at(a, (), 1)
+ self.assertPreciseEqual(a, np.array(1))
+
+ with self.assertRaises(TypingError):
+ add_at(a, 0, 1)
+
+ b = np.arange(3)
+ add_at(b, 0, 1)
+ self.assertPreciseEqual(b, np.array([1, 1, 2]))
+
+ # NumPy checks for IndexError but we can't call a jit function with an
+ # empty list as Numba raises "can't compute fingerprint of empty list"
+ with self.assertRaises(ValueError):
+ add_at(a, [], 1)
+
+ def test_ufunc_at_dtypes(self):
+ # Test mixed dtypes
+ a = np.arange(10)
+ power_at = self._generate_jit(np.power)
+ power_at(a, [1, 2, 3, 2], 3.5)
+ self.assertPreciseEqual(a, np.array([0, 1, 4414, 46, 4, 5, 6, 7, 8, 9]))
+
+ def test_ufunc_at_boolean(self):
+ # Test boolean indexing and boolean ufuncs
+ a = np.arange(10)
+ index = a % 2 == 0
+ equal_at = self._generate_jit(np.equal)
+ # boolean indexing not supported
+ equal_at(a, index, [0, 2, 4, 6, 8])
+ self.assertPreciseEqual(a, np.array([1, 1, 1, 3, 1, 5, 1, 7, 1, 9]))
+
+ def test_ufunc_at_boolean2(self):
+ # Test unary operator
+ a = np.arange(10, dtype='u4')
+ invert_at = self._generate_jit(np.invert)
+ invert_at(a, [2, 5, 2])
+ self.assertPreciseEqual(a, np.array([0, 1, 2, 3, 4, 5 ^ 0xffffffff, 6,
+ 7, 8, 9], dtype=np.uint32))
+
+ def test_ufunc_at_advanced(self):
+ # Test empty subspace
+ orig = np.arange(4)
+ a = orig[:, None][:, 0:0]
+ add_at = self._generate_jit(np.add)
+ add_at(a, [0, 1], 3)
+ self.assertPreciseEqual(orig, np.arange(4))
+
+ @unittest.expectedFailure
+ def test_ufunc_at_advanced_2(self):
+ # Test with swapped byte order
+ index = np.array([1, 2, 1], np.dtype('i').newbyteorder())
+ values = np.array([1, 2, 3, 4], np.dtype('f').newbyteorder())
+ add_at = self._generate_jit(np.add)
+ add_at(values, index, 3)
+ self.assertPreciseEqual(values, [1, 8, 6, 4])
+
+ def test_ufunc_at_advanced_3(self):
+ # Test exception thrown
+ values = np.array(['a', 1], dtype=object)
+ add_at = self._generate_jit(np.add)
+ with self.assertRaises(TypingError):
+ add_at(values, [0, 1], 1)
+ self.assertPreciseEqual(values, np.array(['a', 1], dtype=object))
+
+ def test_ufunc_at_advanced_4(self):
+ # Test multiple output ufuncs raise error, NumPy gh-5665
+ modf_at = self._generate_jit(np.modf)
+ # NumPy raises ValueError as modf returns multiple outputs
+ with self.assertRaises(TypingError):
+ modf_at(np.arange(10), [1])
+
+ def test_ufunc_at_advanced_5(self):
+ # Test maximum
+ maximum_at = self._generate_jit(np.maximum)
+ a = np.array([1, 2, 3])
+ maximum_at(a, [0], 0)
+ self.assertPreciseEqual(a, np.array([1, 2, 3]))
+
+ def test_ufunc_at_negative_indexes(self):
+ dtypes = np.typecodes['AllInteger'] + np.typecodes['Float']
+ ufuncs = (np.add, np.subtract, np.divide, np.minimum, np.maximum)
+
+ for dtype in dtypes:
+
+ if dtype in ('e',): # skip float16 as we don't have an impl. for it
+ continue
+
+ try:
+ from_dtype(np.dtype(dtype))
+ except NumbaNotImplementedError:
+ continue
+
+ for ufunc in ufuncs:
+ a = np.arange(0, 10).astype(dtype)
+ indxs = np.array([-1, 1, -1, 2]).astype(np.intp)
+ vals = np.array([1, 5, 2, 10], dtype=a.dtype)
+
+ expected = a.copy()
+ for i, v in zip(indxs, vals):
+ expected[i] = ufunc(expected[i], v)
+
+ ufunc_at = self._generate_jit(ufunc)
+ ufunc_at(a, indxs, vals)
+ np.testing.assert_array_equal(a, expected)
+ assert np.all(indxs == [-1, 1, -1, 2])
+
+ @unittest.expectedFailure
+ def test_ufunc_at_not_none_signature(self):
+ # Test ufuncs with non-trivial signature raise a TypeError
+ a = np.ones((2, 2, 2))
+ b = np.ones((1, 2, 2))
+ # matmul is a gufunc, thus, this will fail atm
+ matmul_at = self._generate_jit(np.matmul)
+ err_msg = 'does not support ufunc with non-trivial signature'
+ with self.assertRaisesRegex(TypingError, err_msg):
+ matmul_at(a, [0], b)
+
+ # a = np.array([[[1, 2], [3, 4]]])
+ # assert_raises(TypeError, np.linalg._umath_linalg.det.at, a, [0])
+
+ def test_ufunc_at_no_loop_for_op(self):
+ # str dtype does not have a ufunc loop for np.add
+ arr = np.ones(10, dtype=str)
+ add_at = self._generate_jit(np.add)
+ # NumPy raises `np.core._exceptions._UFuncNoLoopError`
+ with self.assertRaises(TypingError):
+ add_at(arr, [0, 1], [0, 1])
+
+ def test_ufunc_at_output_casting(self):
+ arr = np.array([-1])
+ equal_at = self._generate_jit(np.equal)
+ equal_at(arr, [0], [0])
+ assert arr[0] == 0
+
+ def test_ufunc_at_broadcast_failure(self):
+ arr = np.arange(5)
+ add_at = self._generate_jit(np.add)
+
+ # NumPy raises ValueError('array is not broadcastable to correct shape')
+ msg = 'operands could not be broadcast together with remapped shapes'
+ with self.assertRaisesRegex(ValueError, msg):
+ add_at(arr, [0, 1], [1, 2, 3])
+
+ def test_ufunc_at_dynamic(self):
+ arr = np.arange(5)
+
+ @vectorize
+ def inc(x):
+ return x + 1
+
+ self.assertEqual(len(inc.types), 0)
+
+ # trying to call inc.at should trigger compilation
+ inc.at(arr, [1, 3])
+
+ self.assertGreater(len(inc.types), 0)
+
+ def test_ufunc_at_experimental_warning(self):
+ arr = np.arange(5)
+ add_at = self._generate_jit(np.add)
+
+ with warnings.catch_warnings(record=True) as w:
+ warnings.simplefilter('always', NumbaExperimentalFeatureWarning)
+
+ add_at(arr, [0, 3], 10)
+
+ self.assertGreater(len(w), 0)
+ self.assertIn('ufunc.at feature is experimental', str(w[0].message))
+
+
+class TestDUFuncReduceNumPyTests(TestCase):
+ # Tests taken from
+ # https://github.com/numpy/numpy/blob/51ee17b6bd4ccec60a5483ee8bff94ad0c0e8585/numpy/_core/tests/test_ufunc.py # noqa: E501
+
+ def _generate_jit(self, ufunc, identity=None):
+ if ufunc.nin == 2:
+ vec = vectorize(identity=identity)(lambda a, b: ufunc(a, b))
+ else:
+ vec = vectorize(identity=identity)(lambda a: ufunc(a))
+
+ @njit
+ def fn(array, axis=0, initial=None):
+ return vec.reduce(array, axis=axis, initial=initial)
+ return fn
+
+ @unittest.expectedFailure
+ def test_numpy_scalar_reduction(self):
+ # scalar reduction is not supported
+ power_reduce = self._generate_jit(np.power)
+ expected = np.power.reduce(3)
+ got = power_reduce(3)
+ self.assertPreciseEqual(expected, got)
+
+ def check_identityless_reduction(self, a):
+ def compare_output(a, b):
+ # We don't use self.assertPreciseEqual as the dtype differs
+ # between the value from the reduction and the hardcoded output
+ np.testing.assert_equal(a, b)
+ # test taken from:
+ # https://github.com/numpy/numpy/blob/51ee17b6bd4ccec60a5483ee8bff94ad0c0e8585/numpy/_core/tests/test_ufunc.py#L1591 # noqa: E501
+
+ minimum_reduce = self._generate_jit(np.minimum, identity='reorderable')
+
+ # np.minimum.reduce is an identityless reduction
+
+ # Verify that it sees the zero at various positions
+ a[...] = 1
+ a[1, 0, 0] = 0
+ compare_output(minimum_reduce(a, axis=None), 0)
+ compare_output(minimum_reduce(a, axis=(0, 1)), [0, 1, 1, 1])
+ compare_output(minimum_reduce(a, axis=(0, 2)), [0, 1, 1])
+ compare_output(minimum_reduce(a, axis=(1, 2)), [1, 0])
+ compare_output(minimum_reduce(a, axis=0),
+ [[0, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]])
+ compare_output(minimum_reduce(a, axis=1),
+ [[1, 1, 1, 1], [0, 1, 1, 1]])
+ compare_output(minimum_reduce(a, axis=2),
+ [[1, 1, 1], [0, 1, 1]])
+ compare_output(minimum_reduce(a, axis=()), a)
+
+ a[...] = 1
+ a[0, 1, 0] = 0
+ compare_output(minimum_reduce(a, axis=None), 0)
+ compare_output(minimum_reduce(a, axis=(0, 1)), [0, 1, 1, 1])
+ compare_output(minimum_reduce(a, axis=(0, 2)), [1, 0, 1])
+ compare_output(minimum_reduce(a, axis=(1, 2)), [0, 1])
+ compare_output(minimum_reduce(a, axis=0),
+ [[1, 1, 1, 1], [0, 1, 1, 1], [1, 1, 1, 1]])
+ compare_output(minimum_reduce(a, axis=1),
+ [[0, 1, 1, 1], [1, 1, 1, 1]])
+ compare_output(minimum_reduce(a, axis=2),
+ [[1, 0, 1], [1, 1, 1]])
+ compare_output(minimum_reduce(a, axis=()), a)
+
+ a[...] = 1
+ a[0, 0, 1] = 0
+ compare_output(minimum_reduce(a, axis=None), 0)
+ compare_output(minimum_reduce(a, axis=(0, 1)), [1, 0, 1, 1])
+ compare_output(minimum_reduce(a, axis=(0, 2)), [0, 1, 1])
+ compare_output(minimum_reduce(a, axis=(1, 2)), [0, 1])
+ compare_output(minimum_reduce(a, axis=0),
+ [[1, 0, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]])
+ compare_output(minimum_reduce(a, axis=1),
+ [[1, 0, 1, 1], [1, 1, 1, 1]])
+ compare_output(minimum_reduce(a, axis=2),
+ [[0, 1, 1], [1, 1, 1]])
+ compare_output(minimum_reduce(a, axis=()), a)
+
+ def test_numpy_identityless_reduction_corder(self):
+ a = np.empty((2, 3, 4), order='C')
+ self.check_identityless_reduction(a)
+
+ def test_numpy_identityless_reduction_forder(self):
+ a = np.empty((2, 3, 4), order='F')
+ self.check_identityless_reduction(a)
+
+ def test_numpy_identityless_reduction_otherorder(self):
+ a = np.empty((2, 4, 3), order='C').swapaxes(1, 2)
+ self.check_identityless_reduction(a)
+
+ def test_numpy_identityless_reduction_noncontig(self):
+ a = np.empty((3, 5, 4), order='C').swapaxes(1, 2)
+ a = a[1:, 1:, 1:]
+ self.check_identityless_reduction(a)
+
+ def test_numpy_identityless_reduction_noncontig_unaligned(self):
+ a = np.empty((3 * 4 * 5 * 8 + 1,), dtype='i1')
+ a = a[1:].view(dtype='f8')
+ a.shape = (3, 4, 5)
+ a = a[1:, 1:, 1:]
+ self.check_identityless_reduction(a)
+
+ def test_numpy_initial_reduction(self):
+ # np.minimum.reduce is an identityless reduction
+ add_reduce = self._generate_jit(np.add)
+ min_reduce = self._generate_jit(np.minimum)
+ max_reduce = self._generate_jit(np.maximum)
+
+ # For cases like np.maximum(np.abs(...), initial=0)
+ # More generally, a supremum over non-negative numbers.
+ self.assertPreciseEqual(max_reduce(np.asarray([]), initial=0), 0.0)
+
+ # For cases like reduction of an empty array over the reals.
+ self.assertPreciseEqual(min_reduce(np.asarray([]), initial=np.inf),
+ np.inf)
+ self.assertPreciseEqual(max_reduce(np.asarray([]), initial=-np.inf),
+ -np.inf)
+
+ # Random tests
+ self.assertPreciseEqual(min_reduce(np.asarray([5]), initial=4), 4)
+ self.assertPreciseEqual(max_reduce(np.asarray([4]), initial=5), 5)
+ self.assertPreciseEqual(max_reduce(np.asarray([5]), initial=4), 5)
+ self.assertPreciseEqual(min_reduce(np.asarray([4]), initial=5), 4)
+
+ # Check initial=None raises ValueError for both types of ufunc
+ # reductions
+ msg = 'zero-size array to reduction operation'
+ for func in (add_reduce, min_reduce):
+ with self.assertRaisesRegex(ValueError, msg):
+ func(np.asarray([]), initial=None)
+
+ def test_numpy_empty_reduction_and_identity(self):
+ arr = np.zeros((0, 5))
+ true_divide_reduce = self._generate_jit(np.true_divide)
+
+ # OK, since the reduction itself is *not* empty, the result is
+ expected = np.true_divide.reduce(arr, axis=1)
+ got = true_divide_reduce(arr, axis=1)
+ self.assertPreciseEqual(expected, got)
+ self.assertPreciseEqual(got.shape, (0,))
+
+ # Not OK, the reduction itself is empty and we have no identity
+ msg = 'zero-size array to reduction operation'
+ with self.assertRaisesRegex(ValueError, msg):
+ true_divide_reduce(arr, axis=0)
+
+ # Test that an empty reduction fails also if the result is empty
+ arr = np.zeros((0, 0, 5))
+ with self.assertRaisesRegex(ValueError, msg):
+ true_divide_reduce(arr, axis=1)
+
+ # Division reduction makes sense with `initial=1` (empty or not):
+ expected = np.true_divide.reduce(arr, axis=1, initial=1)
+ got = true_divide_reduce(arr, axis=1, initial=1)
+ self.assertPreciseEqual(expected, got)
+
+ def test_identityless_reduction_nonreorderable(self):
+ a = np.array([[8.0, 2.0, 2.0], [1.0, 0.5, 0.25]])
+
+ divide_reduce = self._generate_jit(np.divide)
+ res = divide_reduce(a, axis=0)
+ self.assertPreciseEqual(res, np.asarray([8.0, 4.0, 8.0]))
+
+ res = divide_reduce(a, axis=1)
+ self.assertPreciseEqual(res, np.asarray([2.0, 8.0]))
+
+ res = divide_reduce(a, axis=())
+ self.assertPreciseEqual(res, a)
+
+ # will not raise as per Numba issue #9283
+ # assert_raises(ValueError, np.divide.reduce, a, axis=(0, 1))
+
+ def test_reduce_zero_axis(self):
+ # If we have a n x m array and do a reduction with axis=1, then we are
+ # doing n reductions, and each reduction takes an m-element array. For
+ # a reduction operation without an identity, then:
+ # n > 0, m > 0: fine
+ # n = 0, m > 0: fine, doing 0 reductions of m-element arrays
+ # n > 0, m = 0: can't reduce a 0-element array, ValueError
+ # n = 0, m = 0: can't reduce a 0-element array, ValueError (for
+ # consistency with the above case)
+ # This test doesn't actually look at return values, it just checks to
+ # make sure that error we get an error in exactly those cases where we
+ # expect one, and assumes the calculations themselves are done
+ # correctly.
+
+ def ok(f, *args, **kwargs):
+ f(*args, **kwargs)
+
+ def err(f, *args, **kwargs):
+ with self.assertRaises(ValueError):
+ f(*args, **kwargs)
+
+ def t(expect, func, n, m):
+ expect(func, np.zeros((n, m)), axis=1)
+ expect(func, np.zeros((m, n)), axis=0)
+ expect(func, np.zeros((n // 2, n // 2, m)), axis=2)
+ expect(func, np.zeros((n // 2, m, n // 2)), axis=1)
+ expect(func, np.zeros((n, m // 2, m // 2)), axis=(1, 2))
+ expect(func, np.zeros((m // 2, n, m // 2)), axis=(0, 2))
+ expect(func, np.zeros((m // 3, m // 3, m // 3,
+ n // 2, n // 2)), axis=(0, 1, 2))
+ # Check what happens if the inner (resp. outer) dimensions are a
+ # mix of zero and non-zero:
+ expect(func, np.zeros((10, m, n)), axis=(0, 1))
+ expect(func, np.zeros((10, n, m)), axis=(0, 2))
+ expect(func, np.zeros((m, 10, n)), axis=0)
+ expect(func, np.zeros((10, m, n)), axis=1)
+ expect(func, np.zeros((10, n, m)), axis=2)
+
+ # np.maximum is just an arbitrary ufunc with no reduction identity
+ maximum_reduce = self._generate_jit(np.maximum, identity='reorderable')
+ self.assertEqual(np.maximum.identity, None)
+ t(ok, maximum_reduce, 30, 30)
+ t(ok, maximum_reduce, 0, 30)
+ t(err, maximum_reduce, 30, 0)
+ t(err, maximum_reduce, 0, 0)
+ err(maximum_reduce, [])
+ maximum_reduce(np.zeros((0, 0)), axis=())
+
+ # all of the combinations are fine for a reduction that has an
+ # identity
+ add_reduce = self._generate_jit(np.add, identity=0)
+ t(ok, add_reduce, 30, 30)
+ t(ok, add_reduce, 0, 30)
+ t(ok, add_reduce, 30, 0)
+ t(ok, add_reduce, 0, 0)
+ add_reduce(np.array([], dtype=np.int64))
+ add_reduce(np.zeros((0, 0)), axis=())
+
+
+class TestDUFuncReduce(TestCase):
+ def _check_reduce(self, ufunc, dtype=None, initial=None):
+
+ @njit
+ def foo(a, axis, dtype, initial):
+ return ufunc.reduce(a,
+ axis=axis,
+ dtype=dtype,
+ initial=initial)
+
+ inputs = [
+ np.arange(5),
+ np.arange(4).reshape(2, 2),
+ np.arange(40).reshape(5, 4, 2),
+ ]
+ for array in inputs:
+ for axis in range(array.ndim):
+ expected = foo.py_func(array, axis, dtype, initial)
+ got = foo(array, axis, dtype, initial)
+ self.assertPreciseEqual(expected, got)
+
+ def _check_reduce_axis(self, ufunc, dtype, initial=None):
+
+ @njit
+ def foo(a, axis):
+ return ufunc.reduce(a, axis=axis, initial=initial)
+
+ def _check(*args):
+ try:
+ expected = foo.py_func(array, axis)
+ except ValueError as e:
+ self.assertEqual(e.args[0], exc_msg)
+ with self.assertRaisesRegex(TypingError, exc_msg):
+ got = foo(array, axis)
+ else:
+ got = foo(array, axis)
+ self.assertPreciseEqual(expected, got)
+
+ exc_msg = (f"reduction operation '{ufunc.__name__}' is not "
+ "reorderable, so at most one axis may be specified")
+ inputs = [
+ np.arange(40, dtype=dtype).reshape(5, 4, 2),
+ np.arange(10, dtype=dtype),
+ ]
+ for array in inputs:
+ for i in range(1, array.ndim + 1):
+ for axis in itertools.combinations(range(array.ndim), r=i):
+ _check(array, axis)
+
+ # corner cases: Reduce over axis=() and axis=None
+ for axis in ((), None):
+ _check(array, axis)
+
+ def test_add_reduce(self):
+ duadd = vectorize('int64(int64, int64)', identity=0)(pyuadd)
+ self._check_reduce(duadd)
+ self._check_reduce_axis(duadd, dtype=np.int64)
+
+ def test_mul_reduce(self):
+ dumul = vectorize('int64(int64, int64)', identity=1)(pymult)
+ self._check_reduce(dumul)
+
+ def test_non_associative_reduce(self):
+ dusub = vectorize('int64(int64, int64)', identity=None)(pysub)
+ dudiv = vectorize('int64(int64, int64)', identity=None)(pydiv)
+ self._check_reduce(dusub)
+ self._check_reduce_axis(dusub, dtype=np.int64)
+ self._check_reduce(dudiv)
+ self._check_reduce_axis(dudiv, dtype=np.int64)
+
+ def test_reduce_dtype(self):
+ duadd = vectorize('float64(float64, int64)', identity=0)(pyuadd)
+ self._check_reduce(duadd, dtype=np.float64)
+
+ def test_min_reduce(self):
+ dumin = vectorize('int64(int64, int64)', identity='reorderable')(pymin)
+ self._check_reduce(dumin, initial=10)
+ self._check_reduce_axis(dumin, dtype=np.int64)
+
+ def test_add_reduce_initial(self):
+ # Initial should be used as a start
+ duadd = vectorize('int64(int64, int64)', identity=0)(pyuadd)
+ self._check_reduce(duadd, dtype=np.int64, initial=100)
+
+ def test_add_reduce_no_initial_or_identity(self):
+ # don't provide an initial or identity value
+ duadd = vectorize('int64(int64, int64)')(pyuadd)
+ self._check_reduce(duadd, dtype=np.int64)
+
+ def test_invalid_input(self):
+ duadd = vectorize('float64(float64, int64)', identity=0)(pyuadd)
+
+ @njit
+ def foo(a):
+ return duadd.reduce(a)
+
+ exc_msg = 'The first argument "array" must be array-like'
+ with self.assertRaisesRegex(TypingError, exc_msg):
+ foo('a')
+
+ def test_dufunc_negative_axis(self):
+ duadd = vectorize('int64(int64, int64)', identity=0)(pyuadd)
+
+ @njit
+ def foo(a, axis):
+ return duadd.reduce(a, axis=axis)
+
+ a = np.arange(40).reshape(5, 4, 2)
+ cases = (0, -1, (0, -1), (-1, -2), (1, -1), -3)
+ for axis in cases:
+ expected = duadd.reduce(a, axis)
+ got = foo(a, axis)
+ self.assertPreciseEqual(expected, got)
+
+ def test_dufunc_invalid_axis(self):
+ duadd = vectorize('int64(int64, int64)', identity=0)(pyuadd)
+
+ @njit
+ def foo(a, axis):
+ return duadd.reduce(a, axis=axis)
+
+ a = np.arange(40).reshape(5, 4, 2)
+ cases = ((0, 0), (0, 1, 0), (0, -3), (-1, -1), (-1, 2))
+ for axis in cases:
+ msg = "duplicate value in 'axis'"
+ with self.assertRaisesRegex(ValueError, msg):
+ foo(a, axis)
+
+ cases = (-4, 3, (0, -4),)
+ for axis in cases:
+ with self.assertRaisesRegex(ValueError, "Invalid axis"):
+ foo(a, axis)
+
+
+class TestDUFuncPickling(MemoryLeakMixin, unittest.TestCase):
+ def check(self, ident, result_type):
+ buf = pickle.dumps(ident)
+ rebuilt = pickle.loads(buf)
+
+ # Check reconstructed dufunc
+ r = rebuilt(123)
+ self.assertEqual(123, r)
+ self.assertIsInstance(r, result_type)
+
+ # Try to use reconstructed dufunc in @jit
+ @njit
+ def foo(x):
+ return rebuilt(x)
+
+ r = foo(321)
+ self.assertEqual(321, r)
+ self.assertIsInstance(r, result_type)
+
+ def test_unrestricted(self):
+ @vectorize
+ def ident(x1):
+ return x1
+
+ self.check(ident, result_type=(int, np.integer))
+
+ def test_restricted(self):
+ @vectorize(["float64(float64)"])
+ def ident(x1):
+ return x1
+
+ self.check(ident, result_type=float)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/npyufunc/test_errors.py b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/npyufunc/test_errors.py
new file mode 100644
index 0000000000000000000000000000000000000000..948655d22b44fc76faf4ed31ad57dd5b6b59a574
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/npyufunc/test_errors.py
@@ -0,0 +1,174 @@
+import contextlib
+import sys
+
+import numpy as np
+
+from numba import vectorize, guvectorize
+
+from numba.tests.support import (TestCase, CheckWarningsMixin,
+ skip_macos_fenv_errors)
+import unittest
+
+
+def sqrt(val):
+ if val < 0.0:
+ raise ValueError('Value must be positive')
+ return val ** 0.5
+
+
+def gufunc_foo(inp, n, out):
+ for i in range(inp.shape[0]):
+ if inp[i] < 0:
+ raise ValueError('Value must be positive')
+ out[i] = inp[i] * n[0]
+
+def truediv(a, b):
+ return a / b
+
+def floordiv(a, b):
+ return a // b
+
+def remainder(a, b):
+ return a % b
+
+def power(a, b):
+ return a ** b
+
+
+class TestExceptions(TestCase):
+ """
+ Test raising exceptions inside ufuncs.
+ """
+
+ def check_ufunc_raise(self, **vectorize_args):
+ f = vectorize(['float64(float64)'], **vectorize_args)(sqrt)
+ arr = np.array([1, 4, -2, 9, -1, 16], dtype=np.float64)
+ out = np.zeros_like(arr)
+ with self.assertRaises(ValueError) as cm:
+ f(arr, out)
+ self.assertIn('Value must be positive', str(cm.exception))
+ # All values were computed except for the ones giving an error
+ self.assertEqual(list(out), [1, 2, 0, 3, 0, 4])
+
+ def test_ufunc_raise(self):
+ self.check_ufunc_raise(nopython=True)
+
+ def test_ufunc_raise_objmode(self):
+ self.check_ufunc_raise(forceobj=True)
+
+ def check_gufunc_raise(self, **vectorize_args):
+ f = guvectorize(['int32[:], int32[:], int32[:]'], '(n),()->(n)',
+ **vectorize_args)(gufunc_foo)
+ arr = np.array([1, 2, -3, 4], dtype=np.int32)
+ out = np.zeros_like(arr)
+ with self.assertRaises(ValueError) as cm:
+ f(arr, 2, out)
+ # The gufunc bailed out after the error
+ self.assertEqual(list(out), [2, 4, 0, 0])
+
+ def test_gufunc_raise(self):
+ self.check_gufunc_raise(nopython=True)
+
+ def test_gufunc_raise_objmode(self):
+ self.check_gufunc_raise(forceobj=True)
+
+class TestFloatingPointExceptions(TestCase, CheckWarningsMixin):
+ """
+ Test floating-point exceptions inside ufuncs.
+
+ Note the warnings emitted by Numpy reflect IEEE-754 semantics.
+ """
+
+ def check_truediv_real(self, dtype):
+ """
+ Test 1 / 0 and 0 / 0.
+ """
+ f = vectorize(nopython=True)(truediv)
+ a = np.array([5., 6., 0., 8.], dtype=dtype)
+ b = np.array([1., 0., 0., 4.], dtype=dtype)
+ expected = np.array([5., float('inf'), float('nan'), 2.])
+ with self.check_warnings(["divide by zero encountered",
+ "invalid value encountered"]):
+ res = f(a, b)
+ self.assertPreciseEqual(res, expected)
+
+ def test_truediv_float(self):
+ self.check_truediv_real(np.float64)
+
+ def test_truediv_integer(self):
+ self.check_truediv_real(np.int32)
+
+ def check_divmod_float(self, pyfunc, values, messages):
+ """
+ Test 1 // 0 and 0 // 0.
+ """
+ f = vectorize(nopython=True)(pyfunc)
+ a = np.array([5., 6., 0., 9.])
+ b = np.array([1., 0., 0., 4.])
+ expected = np.array(values)
+ with self.check_warnings(messages):
+ res = f(a, b)
+ self.assertPreciseEqual(res, expected)
+
+ def test_floordiv_float(self):
+ self.check_divmod_float(floordiv,
+ [5.0, float('inf'), float('nan'), 2.0],
+ ["divide by zero encountered",
+ "invalid value encountered"])
+
+ @skip_macos_fenv_errors
+ def test_remainder_float(self):
+ self.check_divmod_float(remainder,
+ [0.0, float('nan'), float('nan'), 1.0],
+ ["invalid value encountered"])
+
+ def check_divmod_int(self, pyfunc, values):
+ """
+ Test 1 % 0 and 0 % 0.
+ """
+ f = vectorize(nopython=True)(pyfunc)
+ a = np.array([5, 6, 0, 9])
+ b = np.array([1, 0, 0, 4])
+ expected = np.array(values)
+ # No warnings raised because LLVM makes it difficult
+ with self.check_warnings([]):
+ res = f(a, b)
+ self.assertPreciseEqual(res, expected)
+
+ def test_floordiv_int(self):
+ self.check_divmod_int(floordiv, [5, 0, 0, 2])
+
+ def test_remainder_int(self):
+ self.check_divmod_int(remainder, [0, 0, 0, 1])
+
+ def test_power_float(self):
+ """
+ Test 0 ** -1 and 2 ** .
+ """
+ f = vectorize(nopython=True)(power)
+ a = np.array([5., 0., 2., 8.])
+ b = np.array([1., -1., 1e20, 4.])
+ expected = np.array([5., float('inf'), float('inf'), 4096.])
+ with self.check_warnings(["divide by zero encountered",
+ "overflow encountered"]):
+ res = f(a, b)
+ self.assertPreciseEqual(res, expected)
+
+ def test_power_integer(self):
+ """
+ Test 0 ** -1.
+ Note 2 ** returns an undefined value (depending
+ on the algorithm).
+ """
+ dtype = np.int64
+ f = vectorize(["int64(int64, int64)"], nopython=True)(power)
+ a = np.array([5, 0, 6], dtype=dtype)
+ b = np.array([1, -1, 2], dtype=dtype)
+ expected = np.array([5, -2**63, 36], dtype=dtype)
+ with self.check_warnings([]):
+ res = f(a, b)
+ self.assertPreciseEqual(res, expected)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/npyufunc/test_gufunc.py b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/npyufunc/test_gufunc.py
new file mode 100644
index 0000000000000000000000000000000000000000..eeb3343ffb17bbbf5d3146a272813ef6a3cd07f9
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/npyufunc/test_gufunc.py
@@ -0,0 +1,849 @@
+import unittest
+import pickle
+
+import numpy as np
+
+from numba import void, float32, float64, int32, int64, jit, guvectorize
+from numba.core.errors import TypingError
+from numba.np.ufunc import GUVectorize
+from numba.tests.support import tag, TestCase
+
+
+def matmulcore(A, B, C):
+ """docstring for matmulcore"""
+ m, n = A.shape
+ n, p = B.shape
+ for i in range(m):
+ for j in range(p):
+ C[i, j] = 0
+ for k in range(n):
+ C[i, j] += A[i, k] * B[k, j]
+
+
+def axpy(a, x, y, out):
+ out[0] = a * x + y
+
+
+class TestGUFunc(TestCase):
+ target = 'cpu'
+
+ def check_matmul_gufunc(self, gufunc):
+ matrix_ct = 1001
+ A = np.arange(matrix_ct * 2 * 4, dtype=np.float32).reshape(matrix_ct, 2, 4)
+ B = np.arange(matrix_ct * 4 * 5, dtype=np.float32).reshape(matrix_ct, 4, 5)
+
+ C = gufunc(A, B)
+ Gold = np.matmul(A, B)
+
+ np.testing.assert_allclose(C, Gold, rtol=1e-5, atol=1e-8)
+
+ def test_gufunc(self):
+ gufunc = GUVectorize(matmulcore, '(m,n),(n,p)->(m,p)',
+ target=self.target)
+ gufunc.add((float32[:, :], float32[:, :], float32[:, :]))
+ gufunc = gufunc.build_ufunc()
+
+ self.check_matmul_gufunc(gufunc)
+
+ def test_guvectorize_decor(self):
+ gufunc = guvectorize([void(float32[:,:], float32[:,:], float32[:,:])],
+ '(m,n),(n,p)->(m,p)',
+ target=self.target)(matmulcore)
+
+ self.check_matmul_gufunc(gufunc)
+
+ def test_ufunc_like(self):
+ # Test problem that the stride of "scalar" gufunc argument not properly
+ # handled when the actual argument is an array,
+ # causing the same value (first value) being repeated.
+ gufunc = GUVectorize(axpy, '(), (), () -> ()', target=self.target)
+ gufunc.add('(intp, intp, intp, intp[:])')
+ gufunc = gufunc.build_ufunc()
+
+ x = np.arange(10, dtype=np.intp)
+ out = gufunc(x, x, x)
+
+ np.testing.assert_equal(out, x * x + x)
+
+ def test_axis(self):
+ # issue https://github.com/numba/numba/issues/6773
+ @guvectorize(["f8[:],f8[:]"], "(n)->(n)")
+ def my_cumsum(x, res):
+ acc = 0
+ for i in range(x.shape[0]):
+ acc += x[i]
+ res[i] = acc
+
+ x = np.ones((20, 30))
+ # Check regular call
+ y = my_cumsum(x, axis=0)
+ expected = np.cumsum(x, axis=0)
+ np.testing.assert_equal(y, expected)
+ # Check "out" kw
+ out_kw = np.zeros_like(y)
+ my_cumsum(x, out=out_kw, axis=0)
+ np.testing.assert_equal(out_kw, expected)
+
+ def test_docstring(self):
+ @guvectorize([(int64[:], int64, int64[:])], '(n),()->(n)')
+ def gufunc(x, y, res):
+ "docstring for gufunc"
+ for i in range(x.shape[0]):
+ res[i] = x[i] + y
+
+ self.assertEqual("numba.tests.npyufunc.test_gufunc", gufunc.__module__)
+ self.assertEqual("gufunc", gufunc.__name__)
+ self.assertEqual("TestGUFunc.test_docstring..gufunc", gufunc.__qualname__)
+ self.assertEqual("docstring for gufunc", gufunc.__doc__)
+
+
+class TestMultipleOutputs(TestCase):
+ target = 'cpu'
+
+ def test_multiple_outputs_same_type_passed_in(self):
+ @guvectorize('(x)->(x),(x)',
+ target=self.target)
+ def copy(A, B, C):
+ for i in range(B.size):
+ B[i] = A[i]
+ C[i] = A[i]
+
+ A = np.arange(10, dtype=np.float32) + 1
+ B = np.zeros_like(A)
+ C = np.zeros_like(A)
+ copy(A, B, C)
+ np.testing.assert_allclose(A, B)
+ np.testing.assert_allclose(A, C)
+
+ def test_multiple_outputs_distinct_values(self):
+
+ @guvectorize('(x)->(x),(x)',
+ target=self.target)
+ def copy_and_double(A, B, C):
+ for i in range(B.size):
+ B[i] = A[i]
+ C[i] = A[i] * 2
+
+ A = np.arange(10, dtype=np.float32) + 1
+ B = np.zeros_like(A)
+ C = np.zeros_like(A)
+ copy_and_double(A, B, C)
+ np.testing.assert_allclose(A, B)
+ np.testing.assert_allclose(A * 2, C)
+
+ def test_multiple_output_dtypes(self):
+
+ @guvectorize('(x)->(x),(x)',
+ target=self.target)
+ def copy_and_multiply(A, B, C):
+ for i in range(B.size):
+ B[i] = A[i]
+ C[i] = A[i] * 1.5
+
+ A = np.arange(10, dtype=np.int32) + 1
+ B = np.zeros_like(A)
+ C = np.zeros_like(A, dtype=np.float64)
+ copy_and_multiply(A, B, C)
+ np.testing.assert_allclose(A, B)
+ np.testing.assert_allclose(A * np.float64(1.5), C)
+
+ def test_incorrect_number_of_pos_args(self):
+ @guvectorize('(m),(m)->(m),(m)', target=self.target)
+ def f(x, y, z, w):
+ pass
+
+ arr = np.arange(5, dtype=np.int32)
+
+ # Inputs only, too few
+ msg = "Too few arguments for function 'f'"
+ with self.assertRaises(TypeError) as te:
+ f(arr)
+ self.assertIn(msg, str(te.exception))
+
+ # Inputs and outputs, too many
+ with self.assertRaises(TypeError) as te:
+ f(arr, arr, arr, arr, arr)
+ self.assertIn(msg, str(te.exception))
+
+
+class TestGUFuncParallel(TestGUFunc):
+ _numba_parallel_test_ = False
+ target = 'parallel'
+
+
+class TestDynamicGUFunc(TestCase):
+ target = 'cpu'
+
+ def test_dynamic_matmul(self):
+
+ def check_matmul_gufunc(gufunc, A, B, C):
+ Gold = np.matmul(A, B)
+ gufunc(A, B, C)
+ np.testing.assert_allclose(C, Gold, rtol=1e-5, atol=1e-8)
+
+ gufunc = GUVectorize(matmulcore, '(m,n),(n,p)->(m,p)',
+ target=self.target, is_dynamic=True)
+ matrix_ct = 10
+ Ai64 = np.arange(matrix_ct * 2 * 4, dtype=np.int64).reshape(matrix_ct, 2, 4)
+ Bi64 = np.arange(matrix_ct * 4 * 5, dtype=np.int64).reshape(matrix_ct, 4, 5)
+ Ci64 = np.arange(matrix_ct * 2 * 5, dtype=np.int64).reshape(matrix_ct, 2, 5)
+ check_matmul_gufunc(gufunc, Ai64, Bi64, Ci64)
+
+ A = np.arange(matrix_ct * 2 * 4, dtype=np.float32).reshape(matrix_ct, 2, 4)
+ B = np.arange(matrix_ct * 4 * 5, dtype=np.float32).reshape(matrix_ct, 4, 5)
+ C = np.arange(matrix_ct * 2 * 5, dtype=np.float32).reshape(matrix_ct, 2, 5)
+ check_matmul_gufunc(gufunc, A, B, C) # trigger compilation
+
+ self.assertEqual(len(gufunc.types), 2) # ensure two versions of gufunc
+
+
+ def test_dynamic_ufunc_like(self):
+
+ def check_ufunc_output(gufunc, x):
+ out = np.zeros(10, dtype=x.dtype)
+ out_kw = np.zeros(10, dtype=x.dtype)
+ gufunc(x, x, x, out)
+ gufunc(x, x, x, out=out_kw)
+ golden = x * x + x
+ np.testing.assert_equal(out, golden)
+ np.testing.assert_equal(out_kw, golden)
+
+ # Test problem that the stride of "scalar" gufunc argument not properly
+ # handled when the actual argument is an array,
+ # causing the same value (first value) being repeated.
+ gufunc = GUVectorize(axpy, '(), (), () -> ()', target=self.target,
+ is_dynamic=True)
+ x = np.arange(10, dtype=np.intp)
+ check_ufunc_output(gufunc, x)
+
+
+ def test_dynamic_scalar_output(self):
+ """
+ Note that scalar output is a 0-dimension array that acts as
+ a pointer to the output location.
+ """
+
+ @guvectorize('(n)->()', target=self.target, nopython=True)
+ def sum_row(inp, out):
+ tmp = 0.
+ for i in range(inp.shape[0]):
+ tmp += inp[i]
+ out[()] = tmp
+
+ # inp is (10000, 3)
+ # out is (10000)
+ # The outer (leftmost) dimension must match or numpy broadcasting is performed.
+
+ self.assertTrue(sum_row.is_dynamic)
+ inp = np.arange(30000, dtype=np.int32).reshape(10000, 3)
+ out = np.zeros(10000, dtype=np.int32)
+ sum_row(inp, out)
+
+ # verify result
+ for i in range(inp.shape[0]):
+ self.assertEqual(out[i], inp[i].sum())
+
+ msg = "Too few arguments for function 'sum_row'."
+ with self.assertRaisesRegex(TypeError, msg):
+ sum_row(inp)
+
+ def test_axis(self):
+ # issue https://github.com/numba/numba/issues/6773
+ @guvectorize("(n)->(n)")
+ def my_cumsum(x, res):
+ acc = 0
+ for i in range(x.shape[0]):
+ acc += x[i]
+ res[i] = acc
+
+ x = np.ones((20, 30))
+ expected = np.cumsum(x, axis=0)
+ # Check regular call
+ y = np.zeros_like(expected)
+ my_cumsum(x, y, axis=0)
+ np.testing.assert_equal(y, expected)
+ # Check "out" kw
+ out_kw = np.zeros_like(y)
+ my_cumsum(x, out=out_kw, axis=0)
+ np.testing.assert_equal(out_kw, expected)
+
+ def test_gufunc_attributes(self):
+ @guvectorize("(n)->(n)")
+ def gufunc(x, res):
+ acc = 0
+ for i in range(x.shape[0]):
+ acc += x[i]
+ res[i] = acc
+
+ # ensure gufunc exports attributes
+ attrs = ['signature', 'accumulate', 'at', 'outer', 'reduce', 'reduceat']
+ for attr in attrs:
+ contains = hasattr(gufunc, attr)
+ self.assertTrue(contains, 'dynamic gufunc not exporting "%s"' % (attr,))
+
+ a = np.array([1, 2, 3, 4])
+ res = np.array([0, 0, 0, 0])
+ gufunc(a, res) # trigger compilation
+ self.assertPreciseEqual(res, np.array([1, 3, 6, 10]))
+
+ # other attributes are not callable from a gufunc with signature
+ # see: https://github.com/numba/numba/issues/2794
+ # note: this is a limitation in NumPy source code!
+ self.assertEqual(gufunc.signature, "(n)->(n)")
+
+ with self.assertRaises(RuntimeError) as raises:
+ gufunc.accumulate(a)
+ self.assertEqual(str(raises.exception), "Reduction not defined on ufunc with signature")
+
+ with self.assertRaises(RuntimeError) as raises:
+ gufunc.reduce(a)
+ self.assertEqual(str(raises.exception), "Reduction not defined on ufunc with signature")
+
+ with self.assertRaises(RuntimeError) as raises:
+ gufunc.reduceat(a, [0, 2])
+ self.assertEqual(str(raises.exception), "Reduction not defined on ufunc with signature")
+
+ with self.assertRaises(TypeError) as raises:
+ gufunc.outer(a, a)
+ self.assertEqual(str(raises.exception), "method outer is not allowed in ufunc with non-trivial signature")
+
+ def test_gufunc_attributes2(self):
+ @guvectorize('(),()->()')
+ def add(x, y, res):
+ res[0] = x + y
+
+ # add signature "(),() -> ()" is evaluated to None
+ self.assertIsNone(add.signature)
+
+ a = np.array([1, 2, 3, 4])
+ b = np.array([4, 3, 2, 1])
+ res = np.array([0, 0, 0, 0])
+ add(a, b, res) # trigger compilation
+ self.assertPreciseEqual(res, np.array([5, 5, 5, 5]))
+
+ # now test other attributes
+ self.assertIsNone(add.signature)
+ self.assertEqual(add.reduce(a), 10)
+ self.assertPreciseEqual(add.accumulate(a), np.array([1, 3, 6, 10]))
+ self.assertPreciseEqual(add.outer([0, 1], [1, 2]), np.array([[1, 2], [2, 3]]))
+ self.assertPreciseEqual(add.reduceat(a, [0, 2]), np.array([3, 7]))
+
+ x = np.array([1, 2, 3, 4])
+ y = np.array([1, 2])
+ add.at(x, [0, 1], y)
+ self.assertPreciseEqual(x, np.array([2, 4, 3, 4]))
+
+
+class TestGUVectorizeScalar(TestCase):
+ """
+ Nothing keeps user from out-of-bound memory access
+ """
+ target = 'cpu'
+
+ def test_scalar_output(self):
+ """
+ Note that scalar output is a 0-dimension array that acts as
+ a pointer to the output location.
+ """
+
+ @guvectorize(['void(int32[:], int32[:])'], '(n)->()',
+ target=self.target, nopython=True)
+ def sum_row(inp, out):
+ tmp = 0.
+ for i in range(inp.shape[0]):
+ tmp += inp[i]
+ out[()] = tmp
+
+ # inp is (10000, 3)
+ # out is (10000)
+ # The outer (leftmost) dimension must match or numpy broadcasting is performed.
+
+ inp = np.arange(30000, dtype=np.int32).reshape(10000, 3)
+ out = sum_row(inp)
+
+ # verify result
+ for i in range(inp.shape[0]):
+ self.assertEqual(out[i], inp[i].sum())
+
+ def test_scalar_input(self):
+
+ @guvectorize(['int32[:], int32[:], int32[:]'], '(n),()->(n)',
+ target=self.target, nopython=True)
+ def foo(inp, n, out):
+ for i in range(inp.shape[0]):
+ out[i] = inp[i] * n[0]
+
+ inp = np.arange(3 * 10, dtype=np.int32).reshape(10, 3)
+ # out = np.empty_like(inp)
+ out = foo(inp, 2)
+
+ # verify result
+ self.assertPreciseEqual(inp * 2, out)
+
+ def test_scalar_input_core_type(self):
+ def pyfunc(inp, n, out):
+ for i in range(inp.size):
+ out[i] = n * (inp[i] + 1)
+
+ my_gufunc = guvectorize(['int32[:], int32, int32[:]'],
+ '(n),()->(n)',
+ target=self.target)(pyfunc)
+
+ # test single core loop execution
+ arr = np.arange(10).astype(np.int32)
+ got = my_gufunc(arr, 2)
+
+ expected = np.zeros_like(got)
+ pyfunc(arr, 2, expected)
+
+ np.testing.assert_equal(got, expected)
+
+ # test multiple core loop execution
+ arr = np.arange(20).astype(np.int32).reshape(10, 2)
+ got = my_gufunc(arr, 2)
+
+ expected = np.zeros_like(got)
+ for ax in range(expected.shape[0]):
+ pyfunc(arr[ax], 2, expected[ax])
+
+ np.testing.assert_equal(got, expected)
+
+ def test_scalar_input_core_type_error(self):
+ with self.assertRaises(TypeError) as raises:
+ @guvectorize(['int32[:], int32, int32[:]'], '(n),(n)->(n)',
+ target=self.target)
+ def pyfunc(a, b, c):
+ pass
+ self.assertEqual("scalar type int32 given for non scalar argument #2",
+ str(raises.exception))
+
+ def test_ndim_mismatch(self):
+ with self.assertRaises(TypeError) as raises:
+ @guvectorize(['int32[:], int32[:]'], '(m,n)->(n)',
+ target=self.target)
+ def pyfunc(a, b):
+ pass
+ self.assertEqual("type and shape signature mismatch for arg #1",
+ str(raises.exception))
+
+
+class TestGUVectorizeScalarParallel(TestGUVectorizeScalar):
+ _numba_parallel_test_ = False
+ target = 'parallel'
+
+
+class TestGUVectorizePickling(TestCase):
+ def test_pickle_gufunc_non_dyanmic(self):
+ """Non-dynamic gufunc.
+ """
+ @guvectorize(["f8,f8[:]"], "()->()")
+ def double(x, out):
+ out[:] = x * 2
+
+ # pickle
+ ser = pickle.dumps(double)
+ cloned = pickle.loads(ser)
+
+ # attributes carried over
+ self.assertEqual(cloned._frozen, double._frozen)
+ self.assertEqual(cloned.identity, double.identity)
+ self.assertEqual(cloned.is_dynamic, double.is_dynamic)
+ self.assertEqual(cloned.gufunc_builder._sigs,
+ double.gufunc_builder._sigs)
+ # expected value of attributes
+ self.assertTrue(cloned._frozen)
+
+ cloned.disable_compile()
+ self.assertTrue(cloned._frozen)
+
+ # scalar version
+ self.assertPreciseEqual(double(0.5), cloned(0.5))
+ # array version
+ arr = np.arange(10)
+ self.assertPreciseEqual(double(arr), cloned(arr))
+
+ def test_pickle_gufunc_dyanmic_null_init(self):
+ """Dynamic gufunc w/o prepopulating before pickling.
+ """
+ @guvectorize("()->()", identity=1)
+ def double(x, out):
+ out[:] = x * 2
+
+ # pickle
+ ser = pickle.dumps(double)
+ cloned = pickle.loads(ser)
+
+ # attributes carried over
+ self.assertEqual(cloned._frozen, double._frozen)
+ self.assertEqual(cloned.identity, double.identity)
+ self.assertEqual(cloned.is_dynamic, double.is_dynamic)
+ self.assertEqual(cloned.gufunc_builder._sigs,
+ double.gufunc_builder._sigs)
+ # expected value of attributes
+ self.assertFalse(cloned._frozen)
+
+ # scalar version
+ expect = np.zeros(1)
+ got = np.zeros(1)
+ double(0.5, out=expect)
+ cloned(0.5, out=got)
+ self.assertPreciseEqual(expect, got)
+ # array version
+ arr = np.arange(10)
+ expect = np.zeros_like(arr)
+ got = np.zeros_like(arr)
+ double(arr, out=expect)
+ cloned(arr, out=got)
+ self.assertPreciseEqual(expect, got)
+
+ def test_pickle_gufunc_dynamic_initialized(self):
+ """Dynamic gufunc prepopulated before pickling.
+
+ Once unpickled, we disable compilation to verify that the gufunc
+ compilation state is carried over.
+ """
+ @guvectorize("()->()", identity=1)
+ def double(x, out):
+ out[:] = x * 2
+
+ # prepopulate scalar
+ expect = np.zeros(1)
+ got = np.zeros(1)
+ double(0.5, out=expect)
+ # prepopulate array
+ arr = np.arange(10)
+ expect = np.zeros_like(arr)
+ got = np.zeros_like(arr)
+ double(arr, out=expect)
+
+ # pickle
+ ser = pickle.dumps(double)
+ cloned = pickle.loads(ser)
+
+ # attributes carried over
+ self.assertEqual(cloned._frozen, double._frozen)
+ self.assertEqual(cloned.identity, double.identity)
+ self.assertEqual(cloned.is_dynamic, double.is_dynamic)
+ self.assertEqual(cloned.gufunc_builder._sigs,
+ double.gufunc_builder._sigs)
+ # expected value of attributes
+ self.assertFalse(cloned._frozen)
+
+ # disable compilation
+ cloned.disable_compile()
+ self.assertTrue(cloned._frozen)
+ # scalar version
+ expect = np.zeros(1)
+ got = np.zeros(1)
+ double(0.5, out=expect)
+ cloned(0.5, out=got)
+ self.assertPreciseEqual(expect, got)
+ # array version
+ expect = np.zeros_like(arr)
+ got = np.zeros_like(arr)
+ double(arr, out=expect)
+ cloned(arr, out=got)
+ self.assertPreciseEqual(expect, got)
+
+
+class TestGUVectorizeJit(TestCase):
+ target = 'cpu'
+
+ def check_add_gufunc(self, gufunc):
+ @jit(nopython=True)
+ def jit_add(x, y, res):
+ gufunc(x, y, res)
+
+ x = np.arange(40, dtype='i8').reshape(4, 2, 5)
+ y = np.int32(100)
+ res = np.zeros_like(x)
+ jit_add(x, y, res)
+ self.assertPreciseEqual(res, x + y)
+
+ def test_add_static(self):
+ @guvectorize('int64[:], int64, int64[:]', '(n),()->(n)',
+ target=self.target)
+ def add(x, y, res):
+ for i in range(x.shape[0]):
+ res[i] = x[i] + y
+
+ self.check_add_gufunc(add)
+
+ def test_add_static_cast_args(self):
+ # cast the second argument from i32 -> i64
+ @guvectorize('int64[:], int64, int64[:]', '(n),()->(n)',
+ target=self.target)
+ def add(x, y, res):
+ for i in range(x.shape[0]):
+ res[i] = x[i] + y
+
+ self.check_add_gufunc(add)
+
+ def test_add_dynamic(self):
+ @guvectorize('(n),()->(n)', target=self.target)
+ def add(x, y, res):
+ for i in range(x.shape[0]):
+ res[i] = x[i] + y
+
+ self.check_add_gufunc(add)
+
+ @unittest.expectedFailure
+ def test_object_mode(self):
+ @guvectorize('(n),()->(n)', target=self.target, forceobj=True)
+ def add(x, y, res):
+ for i in range(x.shape[0]):
+ res[i] = x[i] + y
+
+ self.check_add_gufunc(add)
+
+ def check_matmul(self, jit_func):
+ matrix_ct = 1001
+ A = np.arange(matrix_ct * 2 * 4, dtype=np.float32).reshape(matrix_ct, 2, 4)
+ B = np.arange(matrix_ct * 4 * 5, dtype=np.float32).reshape(matrix_ct, 4, 5)
+ C = np.arange(matrix_ct * 2 * 5, dtype=np.float32).reshape(matrix_ct, 2, 5)
+
+ jit_func(A, B, C)
+ Gold = np.matmul(A, B)
+
+ np.testing.assert_allclose(C, Gold, rtol=1e-5, atol=1e-8)
+
+ def test_njit_matmul_call(self):
+
+ gufunc = guvectorize('(m,n),(n,p)->(m,p)',
+ target=self.target)(matmulcore)
+
+ @jit(nopython=True)
+ def matmul_jit(A, B, C):
+ return gufunc(A, B, C)
+
+ self.check_matmul(matmul_jit)
+
+ def test_axpy(self):
+ gufunc = GUVectorize(axpy, '(),(),() -> ()', target=self.target,
+ is_dynamic=True)
+
+ @jit(nopython=True)
+ def axpy_jit(a, x, y, out):
+ gufunc(a, x, y, out)
+
+ x = np.arange(10, dtype=np.intp)
+ out = np.zeros_like(x)
+ axpy_jit(x, x, x, out)
+ self.assertPreciseEqual(out, x * x + x)
+
+ def test_output_scalar(self):
+
+ @guvectorize('(n),(m) -> ()')
+ def gufunc(x, y, res):
+ res[0] = x.sum() + y.sum()
+
+ @jit(nopython=True)
+ def jit_func(x, y, res):
+ gufunc(x, y, res)
+
+ x = np.arange(40, dtype='i8').reshape(4, 10)
+ y = np.arange(20, dtype='i8')
+ res = np.zeros(4, dtype='i8')
+ jit_func(x, y, res)
+ expected = np.zeros_like(res)
+ gufunc(x, y, expected)
+ self.assertPreciseEqual(res, expected)
+
+ def test_input_scalar(self):
+
+ @guvectorize('() -> ()')
+ def gufunc(x, res):
+ res[0] = x + 100
+
+ @jit(nopython=True)
+ def jit_func(x, res):
+ gufunc(x, res)
+
+ x = np.arange(40, dtype='i8').reshape(5, 2, 4)
+ res = np.zeros_like(x)
+ jit_func(x, res)
+ expected = np.zeros_like(res)
+ gufunc(x, expected)
+ self.assertPreciseEqual(res, expected)
+
+ def test_gufunc_ndim_mismatch(self):
+ signature = "(n, m), (n, n, n) -> (m), (n, n)"
+ @guvectorize(signature)
+ def bar(x, y, res, out):
+ res[0] = 123
+ out[0] = 456
+
+ @jit(nopython=True)
+ def foo(x, y, res, out):
+ bar(x, y, res, out)
+
+ N, M = 2, 3
+ x = np.arange(N**2).reshape(N, N)
+ y = np.arange(N**3).reshape(N, N, N)
+ res = np.arange(M)
+ out = np.arange(N**2).reshape(N, N)
+
+ # calling with a 1d array should result in an error
+ with self.assertRaises(TypingError) as raises:
+ x_ = np.arange(N * N)
+ foo(x_, y, res, out)
+ msg = ('bar: Input operand 0 does not have enough dimensions (has '
+ f'1, gufunc core with signature {signature} requires 2)')
+ self.assertIn(msg, str(raises.exception))
+
+ with self.assertRaises(TypingError) as raises:
+ y_ = np.arange(N * N).reshape(N, N)
+ foo(x, y_, res, out)
+ msg = ('bar: Input operand 1 does not have enough dimensions (has '
+ f'2, gufunc core with signature {signature} requires 3)')
+ self.assertIn(msg, str(raises.exception))
+
+ with self.assertRaises(TypingError) as raises:
+ res_ = np.array(3)
+ foo(x, y, res_, out)
+ msg = ('bar: Output operand 0 does not have enough dimensions (has '
+ f'0, gufunc core with signature {signature} requires 1)')
+ self.assertIn(msg, str(raises.exception))
+
+ with self.assertRaises(TypingError) as raises:
+ out_ = np.arange(N)
+ foo(x, y, res, out_)
+ msg = ('bar: Output operand 1 does not have enough dimensions (has '
+ f'1, gufunc core with signature {signature} requires 2)')
+ self.assertIn(msg, str(raises.exception))
+
+ def test_mismatch_inner_dimensions(self):
+ @guvectorize('(n),(n) -> ()')
+ def bar(x, y, res):
+ res[0] = 123
+
+ @jit(nopython=True)
+ def foo(x, y, res):
+ bar(x, y, res)
+
+ N = 2
+ M = 3
+ x = np.empty((5, 3, N))
+ y = np.empty((M,))
+ res = np.zeros((5, 3))
+
+ # ensure that NumPy raises an exception
+ with self.assertRaises(ValueError) as np_raises:
+ bar(x, y, res)
+ msg = ('Input operand 1 has a mismatch in its core dimension 0, with '
+ 'gufunc signature (n),(n) -> () (size 3 is different from 2)')
+ self.assertIn(msg, str(np_raises.exception))
+
+ with self.assertRaises(ValueError) as raises:
+ foo(x, y, res)
+ msg = ('Operand has a mismatch in one of its core dimensions')
+ self.assertIn(msg, str(raises.exception))
+
+ def test_mismatch_inner_dimensions_input_output(self):
+ @guvectorize('(n),(m) -> (n)')
+ def bar(x, y, res):
+ res[0] = 123
+
+ @jit(nopython=True)
+ def foo(x, y, res):
+ bar(x, y, res)
+
+ N = 2
+ M = 3
+ x = np.empty((5, 3, N))
+ y = np.empty((M,))
+ res = np.zeros((5, 3))
+
+ # ensure that NumPy raises an exception
+ with self.assertRaises(ValueError) as np_raises:
+ bar(x, y, res)
+ msg = ('Output operand 0 has a mismatch in its core dimension 0, with '
+ 'gufunc signature (n),(m) -> (n) (size 3 is different from 2)')
+ self.assertIn(msg, str(np_raises.exception))
+
+ with self.assertRaises(ValueError) as raises:
+ foo(x, y, res)
+ msg = ('Operand has a mismatch in one of its core dimensions')
+ self.assertIn(msg, str(raises.exception))
+
+ def test_mismatch_inner_dimensions_output(self):
+ @guvectorize('(n),(m) -> (m),(m)')
+ def bar(x, y, res, out):
+ res[0] = 123
+ out[0] = 456
+
+ @jit(nopython=True)
+ def foo(x, y, res, out):
+ bar(x, y, res, out)
+
+ N = 2
+ M = 3
+ x = np.empty((N,))
+ y = np.empty((M,))
+ res = np.zeros((N,))
+ out = np.zeros((M,))
+
+ # ensure that NumPy raises an exception
+ with self.assertRaises(ValueError) as np_raises:
+ bar(x, y, res, out)
+ msg = ('Output operand 0 has a mismatch in its core dimension 0, with '
+ 'gufunc signature (n),(m) -> (m),(m) (size 2 is different from 3)')
+ self.assertIn(msg, str(np_raises.exception))
+
+ with self.assertRaises(ValueError) as raises:
+ foo(x, y, res, out)
+ msg = ('Operand has a mismatch in one of its core dimensions')
+ self.assertIn(msg, str(raises.exception))
+
+ def test_mismatch_loop_shape(self):
+ @guvectorize('(n),(n) -> ()')
+ def bar(x, y, res):
+ res[0] = 123
+
+ @jit(nopython=True)
+ def foo(x, y, res):
+ bar(x, y, res)
+
+ N = 2
+ x = np.empty((1, 5, 3, N,))
+ y = np.empty((5, 3, N,))
+ res = np.zeros((5, 3))
+
+ with self.assertRaises(ValueError) as raises:
+ foo(x, y, res)
+ msg = ('Loop and array shapes are incompatible')
+ self.assertIn(msg, str(raises.exception))
+
+ def test_mismatch_loop_shape_2(self):
+ @guvectorize('(n),(n) -> (), (n)')
+ def gufunc(x, y, res, out):
+ res[0] = x.sum()
+ for i in range(x.shape[0]):
+ out[i] += x[i] + y.sum()
+
+ @jit
+ def jit_func(x, y, res, out):
+ gufunc(x, y, res, out)
+
+ N = 2
+
+ x = np.arange(4*N).reshape((4, N))
+ y = np.arange(N)
+ res = np.empty((3,))
+ out = np.zeros((3, N))
+
+ # ensure that NumPy raises an exception
+ with self.assertRaises(ValueError) as np_raises:
+ gufunc(x, y, res, out)
+ msg = ('operands could not be broadcast together with remapped shapes '
+ '[original->remapped]: (4,2)->(4,newaxis) (2,)->() '
+ '(3,)->(3,newaxis) (3,2)->(3,2) and requested shape (2)')
+ self.assertIn(msg, str(np_raises.exception))
+
+ with self.assertRaises(ValueError) as raises:
+ jit_func(x, y, res, out)
+ msg = ('Loop and array shapes are incompatible')
+ self.assertIn(msg, str(raises.exception))
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/npyufunc/test_parallel_env_variable.py b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/npyufunc/test_parallel_env_variable.py
new file mode 100644
index 0000000000000000000000000000000000000000..7d11692ad34250e1056121e570d4c18d86f93183
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/npyufunc/test_parallel_env_variable.py
@@ -0,0 +1,38 @@
+from numba.np.ufunc.parallel import get_thread_count
+from os import environ as env
+from numba.core import config
+import unittest
+
+
+class TestParallelEnvVariable(unittest.TestCase):
+ """
+ Tests environment variables related to the underlying "parallel"
+ functions for npyufuncs.
+ """
+
+ _numba_parallel_test_ = False
+
+ def test_num_threads_variable(self):
+ """
+ Tests the NUMBA_NUM_THREADS env variable behaves as expected.
+ """
+ key = 'NUMBA_NUM_THREADS'
+ current = str(getattr(env, key, config.NUMBA_NUM_THREADS))
+ threads = "3154"
+ env[key] = threads
+ try:
+ config.reload_config()
+ except RuntimeError as e:
+ # This test should fail if threads have already been launched
+ self.assertIn("Cannot set NUMBA_NUM_THREADS", e.args[0])
+ else:
+ self.assertEqual(threads, str(get_thread_count()))
+ self.assertEqual(threads, str(config.NUMBA_NUM_THREADS))
+ finally:
+ # reset the env variable/set to default. Should not fail even if
+ # threads are launched because the value is the same.
+ env[key] = current
+ config.reload_config()
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/npyufunc/test_parallel_low_work.py b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/npyufunc/test_parallel_low_work.py
new file mode 100644
index 0000000000000000000000000000000000000000..cab4d42749f643ca1b38f74f3f6ef400661c5023
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/npyufunc/test_parallel_low_work.py
@@ -0,0 +1,44 @@
+"""
+There was a deadlock problem when work count is smaller than number of threads.
+"""
+
+import numpy as np
+
+from numba import float32, float64, int32, uint32
+from numba.np.ufunc import Vectorize
+import unittest
+
+
+def vector_add(a, b):
+ return a + b
+
+
+class TestParallelLowWorkCount(unittest.TestCase):
+
+ _numba_parallel_test_ = False
+
+ def test_low_workcount(self):
+ # build parallel native code ufunc
+ pv = Vectorize(vector_add, target='parallel')
+ for ty in (int32, uint32, float32, float64):
+ pv.add(ty(ty, ty))
+ para_ufunc = pv.build_ufunc()
+
+ # build python ufunc
+ np_ufunc = np.vectorize(vector_add)
+
+ # test it out
+ def test(ty):
+ data = np.arange(1).astype(ty) # just one item
+ result = para_ufunc(data, data)
+ gold = np_ufunc(data, data)
+ np.testing.assert_allclose(gold, result)
+
+ test(np.double)
+ test(np.float32)
+ test(np.int32)
+ test(np.uint32)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/npyufunc/test_parallel_ufunc_issues.py b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/npyufunc/test_parallel_ufunc_issues.py
new file mode 100644
index 0000000000000000000000000000000000000000..2237122291960d7e437875bc9d55b96bed4a1d33
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/npyufunc/test_parallel_ufunc_issues.py
@@ -0,0 +1,128 @@
+import time
+import ctypes
+
+import numpy as np
+
+from numba.tests.support import captured_stdout
+from numba import vectorize, guvectorize
+import unittest
+
+
+class TestParUfuncIssues(unittest.TestCase):
+
+ _numba_parallel_test_ = False
+
+ def test_thread_response(self):
+ """
+ Related to #89.
+ This does not test #89 but tests the fix for it.
+ We want to make sure the worker threads can be used multiple times
+ and with different time gap between each execution.
+ """
+
+ @vectorize('float64(float64, float64)', target='parallel')
+ def fnv(a, b):
+ return a + b
+
+ sleep_time = 1 # 1 second
+ while sleep_time > 0.00001: # 10us
+ time.sleep(sleep_time)
+ a = b = np.arange(10**5)
+ np.testing.assert_equal(a + b, fnv(a, b))
+ # Reduce sleep time
+ sleep_time /= 2
+
+ def test_gil_reacquire_deadlock(self):
+ """
+ Testing issue #1998 due to GIL reacquiring
+ """
+ # make a ctypes callback that requires the GIL
+ proto = ctypes.CFUNCTYPE(None, ctypes.c_int32)
+ characters = 'abcdefghij'
+
+ def bar(x):
+ print(characters[x])
+
+ cbar = proto(bar)
+
+ # our unit under test
+ @vectorize(['int32(int32)'], target='parallel', nopython=True)
+ def foo(x):
+ print(x % 10) # this reacquires the GIL
+ cbar(x % 10) # this reacquires the GIL
+ return x * 2
+
+ # Numpy ufunc has a heuristic to determine whether to release the GIL
+ # during execution. Small input size (10) seems to not release the GIL.
+ # Large input size (1000) seems to release the GIL.
+ for nelem in [1, 10, 100, 1000]:
+ # inputs
+ a = np.arange(nelem, dtype=np.int32)
+ acopy = a.copy()
+ # run and capture stdout
+ with captured_stdout() as buf:
+ got = foo(a)
+ stdout = buf.getvalue()
+ buf.close()
+ # process outputs from print
+ got_output = sorted(map(lambda x: x.strip(), stdout.splitlines()))
+ # build expected output
+ expected_output = [str(x % 10) for x in range(nelem)]
+ expected_output += [characters[x % 10] for x in range(nelem)]
+ expected_output = sorted(expected_output)
+ # verify
+ self.assertEqual(got_output, expected_output)
+ np.testing.assert_equal(got, 2 * acopy)
+
+
+
+class TestParGUfuncIssues(unittest.TestCase):
+
+ _numba_parallel_test_ = False
+
+ def test_gil_reacquire_deadlock(self):
+ """
+ Testing similar issue to #1998 due to GIL reacquiring for Gufunc
+ """
+ # make a ctypes callback that requires the GIL
+ proto = ctypes.CFUNCTYPE(None, ctypes.c_int32)
+ characters = 'abcdefghij'
+
+ def bar(x):
+ print(characters[x])
+
+ cbar = proto(bar)
+
+ # our unit under test
+ @guvectorize(['(int32, int32[:])'], "()->()",
+ target='parallel', nopython=True)
+ def foo(x, out):
+ print(x % 10) # this reacquires the GIL
+ cbar(x % 10) # this reacquires the GIL
+ out[0] = x * 2
+
+ # Numpy ufunc has a heuristic to determine whether to release the GIL
+ # during execution. Small input size (10) seems to not release the GIL.
+ # Large input size (1000) seems to release the GIL.
+ for nelem in [1, 10, 100, 1000]:
+ # inputs
+ a = np.arange(nelem, dtype=np.int32)
+ acopy = a.copy()
+ # run and capture stdout
+ with captured_stdout() as buf:
+ got = foo(a)
+ stdout = buf.getvalue()
+ buf.close()
+ # process outputs from print
+ got_output = sorted(map(lambda x: x.strip(), stdout.splitlines()))
+ # build expected output
+ expected_output = [str(x % 10) for x in range(nelem)]
+ expected_output += [characters[x % 10] for x in range(nelem)]
+ expected_output = sorted(expected_output)
+ # verify
+ self.assertEqual(got_output, expected_output)
+ np.testing.assert_equal(got, 2 * acopy)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/npyufunc/test_ufunc.py b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/npyufunc/test_ufunc.py
new file mode 100644
index 0000000000000000000000000000000000000000..16020d8ebc4f8f7c2ecc9ff492d490ae7caa90cd
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/npyufunc/test_ufunc.py
@@ -0,0 +1,173 @@
+import numpy as np
+
+from numba import float32, jit, njit
+from numba.np.ufunc import Vectorize
+from numba.core.errors import TypingError
+from numba.tests.support import TestCase
+import unittest
+
+
+dtype = np.float32
+a = np.arange(80, dtype=dtype).reshape(8, 10)
+b = a.copy()
+c = a.copy(order='F')
+d = np.arange(16 * 20, dtype=dtype).reshape(16, 20)[::2, ::2]
+
+
+def add(a, b):
+ return a + b
+
+
+def add_multiple_args(a, b, c, d):
+ return a + b + c + d
+
+
+def gufunc_add(a, b):
+ result = 0.0
+ for i in range(a.shape[0]):
+ result += a[i] * b[i]
+
+ return result
+
+
+def ufunc_reduce(ufunc, arg):
+ for i in range(arg.ndim):
+ arg = ufunc.reduce(arg)
+ return arg
+
+
+vectorizers = [
+ Vectorize,
+ # ParallelVectorize,
+ # StreamVectorize,
+ # CudaVectorize,
+ # GUFuncVectorize,
+]
+
+
+class TestUFuncs(TestCase):
+
+ def _test_ufunc_attributes(self, cls, a, b, *args):
+ "Test ufunc attributes"
+ vectorizer = cls(add, *args)
+ vectorizer.add(float32(float32, float32))
+ ufunc = vectorizer.build_ufunc()
+
+ info = (cls, a.ndim)
+ self.assertPreciseEqual(ufunc(a, b), a + b, msg=info)
+ self.assertPreciseEqual(ufunc_reduce(ufunc, a), np.sum(a), msg=info)
+ self.assertPreciseEqual(ufunc.accumulate(a), np.add.accumulate(a),
+ msg=info)
+ self.assertPreciseEqual(ufunc.outer(a, b), np.add.outer(a, b), msg=info)
+
+ def _test_broadcasting(self, cls, a, b, c, d):
+ "Test multiple args"
+ vectorizer = cls(add_multiple_args)
+ vectorizer.add(float32(float32, float32, float32, float32))
+ ufunc = vectorizer.build_ufunc()
+
+ info = (cls, a.shape)
+ self.assertPreciseEqual(ufunc(a, b, c, d), a + b + c + d, msg=info)
+
+ def test_ufunc_attributes(self):
+ for v in vectorizers: # 1D
+ self._test_ufunc_attributes(v, a[0], b[0])
+ for v in vectorizers: # 2D
+ self._test_ufunc_attributes(v, a, b)
+ for v in vectorizers: # 3D
+ self._test_ufunc_attributes(v, a[:, np.newaxis, :],
+ b[np.newaxis, :, :])
+
+ def test_broadcasting(self):
+ for v in vectorizers: # 1D
+ self._test_broadcasting(v, a[0], b[0], c[0], d[0])
+ for v in vectorizers: # 2D
+ self._test_broadcasting(v, a, b, c, d)
+ for v in vectorizers: # 3D
+ self._test_broadcasting(v, a[:, np.newaxis, :], b[np.newaxis, :, :],
+ c[:, np.newaxis, :], d[np.newaxis, :, :])
+
+ def test_implicit_broadcasting(self):
+ for v in vectorizers:
+ vectorizer = v(add)
+ vectorizer.add(float32(float32, float32))
+ ufunc = vectorizer.build_ufunc()
+
+ broadcasting_b = b[np.newaxis, :, np.newaxis, np.newaxis, :]
+ self.assertPreciseEqual(ufunc(a, broadcasting_b),
+ a + broadcasting_b)
+
+ def test_ufunc_exception_on_write_to_readonly(self):
+ z = np.ones(10)
+ z.flags.writeable = False # flip write bit
+
+ tests = []
+ expect = "ufunc 'sin' called with an explicit output that is read-only"
+ tests.append((jit(nopython=True), TypingError, expect))
+ tests.append((jit(forceobj=True), ValueError,
+ "output array is read-only"))
+
+ for dec, exc, msg in tests:
+ def test(x):
+ a = np.ones(x.shape, x.dtype) # do not copy RO attribute from x
+ np.sin(a, x)
+
+ with self.assertRaises(exc) as raises:
+ dec(test)(z)
+
+ self.assertIn(msg, str(raises.exception))
+
+ def test_optional_type_handling(self):
+ # Tests ufunc compilation with Optional type
+
+ @njit
+ def inner(x, y):
+ if y > 2:
+ z = None
+ else:
+ z = np.ones(4)
+ return np.add(x, z)
+
+ # This causes `z` to be np.ones(4) at runtime, success
+ self.assertPreciseEqual(inner(np.arange(4), 1),
+ np.arange(1, 5).astype(np.float64))
+
+ with self.assertRaises(TypeError) as raises:
+ # This causes `z` to be None at runtime, TypeError raised on the
+ # type cast of the Optional.
+ inner(np.arange(4), 3)
+
+ msg = "expected array(float64, 1d, C), got None"
+ self.assertIn(msg, str(raises.exception))
+
+
+class TestUFuncsMisc(TestCase):
+ # Test for miscellaneous ufunc issues
+
+ def test_exp2(self):
+ # See issue #8898, and TargetLibraryInfo based fix in #9336
+ @njit
+ def foo(x):
+ return np.exp2(x)
+
+ for ty in (np.int8, np.uint16):
+ x = ty(2)
+ expected = foo.py_func(x)
+ got = foo(x)
+ self.assertPreciseEqual(expected, got)
+
+ def test_log2(self):
+ # See issue #8898, and TargetLibraryInfo based fix in #9336
+ @njit
+ def foo(x):
+ return np.log2(x)
+
+ for ty in (np.int8, np.uint16):
+ x = ty(2)
+ expected = foo.py_func(x)
+ got = foo(x)
+ self.assertPreciseEqual(expected, got)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/npyufunc/test_ufuncbuilding.py b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/npyufunc/test_ufuncbuilding.py
new file mode 100644
index 0000000000000000000000000000000000000000..df6e37dcd5c69e122c87629e410ee2ee38b2acec
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/npyufunc/test_ufuncbuilding.py
@@ -0,0 +1,471 @@
+import pickle
+import unittest
+
+import numpy as np
+from numpy.testing import assert_array_equal
+
+from numba.np.ufunc.ufuncbuilder import GUFuncBuilder
+from numba import vectorize, guvectorize
+from numba.np.ufunc import PyUFunc_One
+from numba.np.ufunc.dufunc import DUFunc as UFuncBuilder
+from numba.tests.support import tag, TestCase
+from numba.core import config
+
+
+class TestUfuncBuilding(TestCase):
+
+ def test_basic_ufunc(self):
+ from numba.tests.npyufunc.ufuncbuilding_usecases import add
+ ufb = UFuncBuilder(add)
+ cres = ufb.add("int32(int32, int32)")
+ self.assertFalse(cres.objectmode)
+ cres = ufb.add("int64(int64, int64)")
+ self.assertFalse(cres.objectmode)
+ ufunc = ufb.build_ufunc()
+
+ def check(a):
+ b = ufunc(a, a)
+ self.assertPreciseEqual(a + a, b)
+ self.assertEqual(b.dtype, a.dtype)
+
+ a = np.arange(12, dtype='int32')
+ check(a)
+ # Non-contiguous dimension
+ a = a[::2]
+ check(a)
+ a = a.reshape((2, 3))
+ check(a)
+
+ # Metadata
+ self.assertEqual(ufunc.__name__, "add")
+ self.assertIn("An addition", ufunc.__doc__)
+
+ def test_ufunc_struct(self):
+ from numba.tests.npyufunc.ufuncbuilding_usecases import add
+ ufb = UFuncBuilder(add)
+ cres = ufb.add("complex64(complex64, complex64)")
+ self.assertFalse(cres.objectmode)
+ ufunc = ufb.build_ufunc()
+
+ def check(a):
+ b = ufunc(a, a)
+ self.assertPreciseEqual(a + a, b)
+ self.assertEqual(b.dtype, a.dtype)
+
+ a = np.arange(12, dtype='complex64') + 1j
+ check(a)
+ # Non-contiguous dimension
+ a = a[::2]
+ check(a)
+ a = a.reshape((2, 3))
+ check(a)
+
+ def test_ufunc_forceobj(self):
+ from numba.tests.npyufunc.ufuncbuilding_usecases import add
+ ufb = UFuncBuilder(add, targetoptions={'forceobj': True})
+ cres = ufb.add("int32(int32, int32)")
+ self.assertTrue(cres.objectmode)
+ ufunc = ufb.build_ufunc()
+
+ a = np.arange(10, dtype='int32')
+ b = ufunc(a, a)
+ self.assertPreciseEqual(a + a, b)
+
+ def test_nested_call(self):
+ """
+ Check nested call to an implicitly-typed ufunc.
+ """
+ from numba.tests.npyufunc.ufuncbuilding_usecases import outer
+ builder = UFuncBuilder(outer,
+ targetoptions={'nopython': True})
+ builder.add("(int64, int64)")
+ ufunc = builder.build_ufunc()
+ self.assertEqual(ufunc(-1, 3), 2)
+
+ def test_nested_call_explicit(self):
+ """
+ Check nested call to an explicitly-typed ufunc.
+ """
+ from numba.tests.npyufunc.ufuncbuilding_usecases import outer_explicit
+ builder = UFuncBuilder(outer_explicit,
+ targetoptions={'nopython': True})
+ builder.add("(int64, int64)")
+ ufunc = builder.build_ufunc()
+ self.assertEqual(ufunc(-1, 3), 2)
+
+
+class TestUfuncBuildingJitDisabled(TestUfuncBuilding):
+
+ def setUp(self):
+ self.old_disable_jit = config.DISABLE_JIT
+ config.DISABLE_JIT = False
+
+ def tearDown(self):
+ config.DISABLE_JIT = self.old_disable_jit
+
+
+class TestGUfuncBuilding(TestCase):
+
+ def test_basic_gufunc(self):
+ from numba.tests.npyufunc.ufuncbuilding_usecases import guadd
+ gufb = GUFuncBuilder(guadd, "(x, y),(x, y)->(x, y)")
+ cres = gufb.add("void(int32[:,:], int32[:,:], int32[:,:])")
+ self.assertFalse(cres.objectmode)
+ ufunc = gufb.build_ufunc()
+
+ a = np.arange(10, dtype="int32").reshape(2, 5)
+ b = ufunc(a, a)
+
+ self.assertPreciseEqual(a + a, b)
+ self.assertEqual(b.dtype, np.dtype('int32'))
+
+ # Metadata
+ self.assertEqual(ufunc.__name__, "guadd")
+ self.assertIn("A generalized addition", ufunc.__doc__)
+
+ def test_gufunc_struct(self):
+ from numba.tests.npyufunc.ufuncbuilding_usecases import guadd
+ gufb = GUFuncBuilder(guadd, "(x, y),(x, y)->(x, y)")
+ cres = gufb.add("void(complex64[:,:], complex64[:,:], complex64[:,:])")
+ self.assertFalse(cres.objectmode)
+ ufunc = gufb.build_ufunc()
+
+ a = np.arange(10, dtype="complex64").reshape(2, 5) + 1j
+ b = ufunc(a, a)
+
+ self.assertPreciseEqual(a + a, b)
+
+ def test_gufunc_struct_forceobj(self):
+ from numba.tests.npyufunc.ufuncbuilding_usecases import guadd
+ gufb = GUFuncBuilder(guadd, "(x, y),(x, y)->(x, y)",
+ targetoptions=dict(forceobj=True))
+ cres = gufb.add("void(complex64[:,:], complex64[:,:], complex64[:,"
+ ":])")
+ self.assertTrue(cres.objectmode)
+ ufunc = gufb.build_ufunc()
+
+ a = np.arange(10, dtype="complex64").reshape(2, 5) + 1j
+ b = ufunc(a, a)
+
+ self.assertPreciseEqual(a + a, b)
+
+
+class TestGUfuncBuildingJitDisabled(TestGUfuncBuilding):
+
+ def setUp(self):
+ self.old_disable_jit = config.DISABLE_JIT
+ config.DISABLE_JIT = False
+
+ def tearDown(self):
+ config.DISABLE_JIT = self.old_disable_jit
+
+
+class TestVectorizeDecor(TestCase):
+
+ _supported_identities = [0, 1, None, "reorderable"]
+
+ def test_vectorize(self):
+ from numba.tests.npyufunc.ufuncbuilding_usecases import add
+ ufunc = vectorize(['int32(int32, int32)'])(add)
+ a = np.arange(10, dtype='int32')
+ b = ufunc(a, a)
+ self.assertPreciseEqual(a + a, b)
+
+ def test_vectorize_objmode(self):
+ from numba.tests.npyufunc.ufuncbuilding_usecases import add
+ ufunc = vectorize(['int32(int32, int32)'], forceobj=True)(add)
+ a = np.arange(10, dtype='int32')
+ b = ufunc(a, a)
+ self.assertPreciseEqual(a + a, b)
+
+ def test_vectorize_bool_return(self):
+ from numba.tests.npyufunc.ufuncbuilding_usecases import equals
+ ufunc = vectorize(['bool_(int32, int32)'])(equals)
+ a = np.arange(10, dtype='int32')
+ r = ufunc(a,a)
+ self.assertPreciseEqual(r, np.ones(r.shape, dtype=np.bool_))
+
+ def test_vectorize_identity(self):
+ from numba.tests.npyufunc.ufuncbuilding_usecases import add
+ sig = 'int32(int32, int32)'
+ for identity in self._supported_identities:
+ ufunc = vectorize([sig], identity=identity)(add)
+ expected = None if identity == 'reorderable' else identity
+ self.assertEqual(ufunc.identity, expected)
+ # Default value is None
+ ufunc = vectorize([sig])(add)
+ self.assertIs(ufunc.identity, None)
+ # Invalid values
+ with self.assertRaises(ValueError):
+ vectorize([sig], identity='none')(add)
+ with self.assertRaises(ValueError):
+ vectorize([sig], identity=2)(add)
+
+ def test_vectorize_no_args(self):
+ from numba.tests.npyufunc.ufuncbuilding_usecases import add
+ a = np.linspace(0,1,10)
+ b = np.linspace(1,2,10)
+ ufunc = vectorize(add)
+ self.assertPreciseEqual(ufunc(a,b), a + b)
+ ufunc2 = vectorize(add)
+ c = np.empty(10)
+ ufunc2(a, b, c)
+ self.assertPreciseEqual(c, a + b)
+
+ def test_vectorize_only_kws(self):
+ from numba.tests.npyufunc.ufuncbuilding_usecases import mul
+ a = np.linspace(0,1,10)
+ b = np.linspace(1,2,10)
+ ufunc = vectorize(identity=PyUFunc_One, nopython=True)(mul)
+ self.assertPreciseEqual(ufunc(a,b), a * b)
+
+ def test_vectorize_output_kwarg(self):
+ """
+ Passing the output array as a keyword argument (issue #1867).
+ """
+ def check(ufunc):
+ a = np.arange(10, 16, dtype='int32')
+ out = np.zeros_like(a)
+ got = ufunc(a, a, out=out)
+ self.assertIs(got, out)
+ self.assertPreciseEqual(out, a + a)
+ with self.assertRaises(TypeError):
+ ufunc(a, a, zzz=out)
+
+ # With explicit sigs
+ from numba.tests.npyufunc.ufuncbuilding_usecases import add
+ ufunc = vectorize(['int32(int32, int32)'], nopython=True)(add)
+ check(ufunc)
+ # With implicit sig
+ ufunc = vectorize(nopython=True)(add)
+ check(ufunc) # compiling
+ check(ufunc) # after compiling
+
+ def test_guvectorize(self):
+ from numba.tests.npyufunc.ufuncbuilding_usecases import guadd
+ ufunc = guvectorize(['(int32[:,:], int32[:,:], int32[:,:])'],
+ "(x,y),(x,y)->(x,y)")(guadd)
+ a = np.arange(10, dtype='int32').reshape(2, 5)
+ b = ufunc(a, a)
+ self.assertPreciseEqual(a + a, b)
+
+ def test_guvectorize_no_output(self):
+ from numba.tests.npyufunc.ufuncbuilding_usecases import guadd
+ ufunc = guvectorize(['(int32[:,:], int32[:,:], int32[:,:])'],
+ "(x,y),(x,y),(x,y)")(guadd)
+ a = np.arange(10, dtype='int32').reshape(2, 5)
+ out = np.zeros_like(a)
+ ufunc(a, a, out)
+ self.assertPreciseEqual(a + a, out)
+
+ def test_guvectorize_objectmode(self):
+ from numba.tests.npyufunc.ufuncbuilding_usecases import guadd_obj
+ ufunc = guvectorize(['(int32[:,:], int32[:,:], int32[:,:])'],
+ "(x,y),(x,y)->(x,y)", forceobj=True)(guadd_obj)
+ a = np.arange(10, dtype='int32').reshape(2, 5)
+ b = ufunc(a, a)
+ self.assertPreciseEqual(a + a, b)
+
+ def test_guvectorize_scalar_objectmode(self):
+ """
+ Test passing of scalars to object mode gufuncs.
+ """
+ from numba.tests.npyufunc.ufuncbuilding_usecases import guadd_scalar_obj
+ ufunc = guvectorize(['(int32[:,:], int32, int32[:,:])'],
+ "(x,y),()->(x,y)", forceobj=True)(guadd_scalar_obj)
+ a = np.arange(10, dtype='int32').reshape(2, 5)
+ b = ufunc(a, 3)
+ self.assertPreciseEqual(a + 3, b)
+
+ def test_guvectorize_error_in_objectmode(self):
+ from numba.tests.npyufunc.ufuncbuilding_usecases import guerror, \
+ MyException
+ ufunc = guvectorize(['(int32[:,:], int32[:,:], int32[:,:])'],
+ "(x,y),(x,y)->(x,y)", forceobj=True)(guerror)
+ a = np.arange(10, dtype='int32').reshape(2, 5)
+ with self.assertRaises(MyException):
+ ufunc(a, a)
+
+ def test_guvectorize_identity(self):
+ from numba.tests.npyufunc.ufuncbuilding_usecases import add, guadd
+ args = (['(int32[:,:], int32[:,:], int32[:,:])'], "(x,y),(x,y)->(x,y)")
+ for identity in self._supported_identities:
+ ufunc = guvectorize(*args, identity=identity)(guadd)
+ expected = None if identity == 'reorderable' else identity
+ self.assertEqual(ufunc.identity, expected)
+ # Default value is None
+ ufunc = guvectorize(*args)(guadd)
+ self.assertIs(ufunc.identity, None)
+ # Invalid values
+ with self.assertRaises(ValueError):
+ guvectorize(*args, identity='none')(add)
+ with self.assertRaises(ValueError):
+ guvectorize(*args, identity=2)(add)
+
+ def test_guvectorize_invalid_layout(self):
+ from numba.tests.npyufunc.ufuncbuilding_usecases import guadd
+ sigs = ['(int32[:,:], int32[:,:], int32[:,:])']
+ # Syntax error
+ with self.assertRaises(ValueError) as raises:
+ guvectorize(sigs, ")-:")(guadd)
+ self.assertIn("bad token in signature", str(raises.exception))
+ # Output shape can't be inferred from inputs
+ with self.assertRaises(NameError) as raises:
+ guvectorize(sigs, "(x,y),(x,y)->(x,z,v)")(guadd)
+ self.assertEqual(str(raises.exception),
+ "undefined output symbols: v,z")
+ # Arrow but no outputs
+ with self.assertRaises(ValueError) as raises:
+ guvectorize(sigs, "(x,y),(x,y),(x,y)->")(guadd)
+ # (error message depends on Numpy version)
+
+
+class NEP13Array:
+ """https://numpy.org/neps/nep-0013-ufunc-overrides.html"""
+ def __init__(self, array):
+ self.array = array
+
+ def __array__(self):
+ return self.array
+
+ def tolist(self):
+ return self.array.tolist()
+
+ def __array_ufunc__(self, ufunc, method, *args, **kwargs):
+ if method != "__call__":
+ return NotImplemented
+
+ return NEP13Array(ufunc(*[np.asarray(x) for x in args], **kwargs))
+
+
+class FakeDaskArray:
+ """This class defines both the NEP13 protocol and the dask collection protocol
+ (https://docs.dask.org/en/stable/custom-collections.html). This is a stand-in for
+ dask array, dask dataframe, and for any wrapper around them (e.g. xarray or pint).
+ """
+
+ def __init__(self, array):
+ self.array = array
+
+ def __array_ufunc__(self, ufunc, method, *args, **kwargs):
+ if method != "__call__":
+ return NotImplemented
+
+ # Simulate sending the ufunc over the network and applying it on a remote worker
+ ufunc = pickle.loads(pickle.dumps(ufunc))
+ args = [x.array if isinstance(x, FakeDaskArray) else x for x in args]
+ return FakeDaskArray(ufunc(*args, **kwargs))
+
+ def _dask_method(self, *args, **kwargs):
+ raise AssertionError("called potentially expensive method")
+
+ __array__ = _dask_method
+ __dask_graph__ = _dask_method
+ __dask_keys__ = _dask_method
+ __dask_optimize__ = _dask_method
+ __dask_postcompute__ = _dask_method
+ __dask_postpersist__ = _dask_method
+ __dask_scheduler__ = _dask_method
+ __dask_tokenize__ = _dask_method
+ compute = _dask_method
+ persist = _dask_method
+ visualize = _dask_method
+
+
+class TestNEP13WithoutSignature(TestCase):
+
+ def test_all(self):
+
+ # note: no signatures specified
+ @vectorize(nopython=True)
+ def new_ufunc(hundreds, tens, ones):
+ return 100*hundreds + 10*tens + ones
+
+ # give it integers
+ a = np.array([1, 2, 3], dtype=np.int64)
+ b = np.array([4, 5, 6], dtype=np.int64)
+ c = np.array([7, 8, 9], dtype=np.int64)
+
+ all_np = new_ufunc(a, b, c)
+ self.assertIsInstance(all_np, np.ndarray)
+ self.assertEqual(all_np.tolist(), [147, 258, 369])
+
+ nep13_1 = new_ufunc(NEP13Array(a), b, c)
+ self.assertIsInstance(nep13_1, NEP13Array)
+ self.assertEqual(nep13_1.tolist(), [147, 258, 369])
+
+ nep13_2 = new_ufunc(a, NEP13Array(b), c)
+ self.assertIsInstance(nep13_2, NEP13Array)
+ self.assertEqual(nep13_2.tolist(), [147, 258, 369])
+
+ nep13_3 = new_ufunc(a, b, NEP13Array(c))
+ self.assertIsInstance(nep13_3, NEP13Array)
+ self.assertEqual(nep13_3.tolist(), [147, 258, 369])
+
+ # give it floats
+ a = np.array([1.1, 2.2, 3.3], dtype=np.float64)
+ b = np.array([4.4, 5.5, 6.6], dtype=np.float64)
+ c = np.array([7.7, 8.8, 9.9], dtype=np.float64)
+
+ all_np = new_ufunc(a, b, c)
+ self.assertIsInstance(all_np, np.ndarray)
+ self.assertEqual(all_np.tolist(), [161.7, 283.8, 405.9])
+
+ nep13_1 = new_ufunc(NEP13Array(a), b, c)
+ self.assertIsInstance(nep13_1, NEP13Array)
+ self.assertEqual(nep13_1.tolist(), [161.7, 283.8, 405.9])
+
+ nep13_2 = new_ufunc(a, NEP13Array(b), c)
+ self.assertIsInstance(nep13_2, NEP13Array)
+ self.assertEqual(nep13_2.tolist(), [161.7, 283.8, 405.9])
+
+ nep13_3 = new_ufunc(a, b, NEP13Array(c))
+ self.assertIsInstance(nep13_3, NEP13Array)
+ self.assertEqual(nep13_3.tolist(), [161.7, 283.8, 405.9])
+
+
+class TestDask(unittest.TestCase):
+ """Test that numba ufuncs are compatible with dask collections and wrappers around
+ dask (e.g. xarray or pint) and that they can be serialized, sent over the network,
+ deserialized on a different host and applied remotely.
+ """
+
+ def test_dask_array(self):
+ a = FakeDaskArray(np.arange(4, dtype=np.float64))
+ expect = np.arange(4, dtype=np.float64) * 2
+
+ @vectorize(["f8(f8)"])
+ def double_static_vectorize(x):
+ return x * 2
+
+ @vectorize()
+ def double_dynamic_vectorize(x):
+ return x * 2
+
+ @guvectorize(["f8,f8[:]"], "()->()")
+ def double_guvectorize(x, out):
+ out[:] = x * 2
+
+ for func in (
+ double_static_vectorize,
+ double_dynamic_vectorize,
+ double_guvectorize,
+ ):
+ with self.subTest(func):
+ b = func(a)
+ assert isinstance(b, FakeDaskArray)
+ assert_array_equal(b.array, expect)
+
+
+class TestVectorizeDecorJitDisabled(TestVectorizeDecor):
+
+ def setUp(self):
+ self.old_disable_jit = config.DISABLE_JIT
+ config.DISABLE_JIT = False
+
+ def tearDown(self):
+ config.DISABLE_JIT = self.old_disable_jit
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/npyufunc/test_update_inplace.py b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/npyufunc/test_update_inplace.py
new file mode 100644
index 0000000000000000000000000000000000000000..97bc39226d3f0f7e8021dd9be993666a5b9ec3b0
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/npyufunc/test_update_inplace.py
@@ -0,0 +1,122 @@
+# -*- coding: utf-8 -*-
+from __future__ import print_function, absolute_import, division
+
+import unittest
+
+import numpy as np
+from numba import guvectorize
+from numba.tests.support import TestCase
+
+
+def py_replace_2nd(x_t, y_1):
+ for t in range(0, x_t.shape[0], 2):
+ x_t[t] = y_1[0]
+
+
+def py_update_3(x0_t, x1_t, x2_t, y_1):
+ for t in range(0, x0_t.shape[0]):
+ x0_t[t] = y_1[0]
+ x1_t[t] = 2 * y_1[0]
+ x2_t[t] = 3 * y_1[0]
+
+
+class TestUpdateInplace(TestCase):
+
+ def _run_test_for_gufunc(self, gufunc, py_func, expect_f4_to_pass=True,
+ z=2):
+ for dtype, expect_to_pass in [('f8', True), ('f4', expect_f4_to_pass)]:
+ inputs = [np.zeros(10, dtype) for _ in range(gufunc.nin - 1)]
+ ex_inputs = [x_t.copy() for x_t in inputs]
+
+ gufunc(*inputs, z)
+ py_func(*ex_inputs, np.array([z]))
+
+ for i, (x_t, ex_x_t) in enumerate(zip(inputs, ex_inputs)):
+ if expect_to_pass:
+ np.testing.assert_equal(x_t, ex_x_t, err_msg='input %s' % i)
+ else:
+ self.assertFalse((x_t == ex_x_t).all(), msg='input %s' % i)
+
+ def test_update_inplace(self):
+ # test without writable_args
+ gufunc = guvectorize(['void(f8[:], f8[:])'], '(t),()',
+ nopython=True)(py_replace_2nd)
+ self._run_test_for_gufunc(gufunc, py_replace_2nd,
+ expect_f4_to_pass=False)
+
+ # test with writable_args
+ gufunc = guvectorize(['void(f8[:], f8[:])'], '(t),()',
+ nopython=True, writable_args=(0,))(py_replace_2nd)
+ self._run_test_for_gufunc(gufunc, py_replace_2nd)
+
+ # test with writable_args as strings
+ gufunc = guvectorize(['void(f8[:], f8[:])'], '(t),()', nopython=True,
+ writable_args=('x_t',))(py_replace_2nd)
+ self._run_test_for_gufunc(gufunc, py_replace_2nd)
+
+ def test_update_inplace_with_cache(self):
+ # test with writable_args
+ gufunc = guvectorize(['void(f8[:], f8[:])'], '(t),()',
+ nopython=True, writable_args=(0,),
+ cache=True)(py_replace_2nd)
+ # 2nd time it is loaded from cache
+ gufunc = guvectorize(['void(f8[:], f8[:])'], '(t),()',
+ nopython=True, writable_args=(0,),
+ cache=True)(py_replace_2nd)
+ self._run_test_for_gufunc(gufunc, py_replace_2nd)
+
+ def test_update_inplace_parallel(self):
+ # test with writable_args
+ gufunc = guvectorize(['void(f8[:], f8[:])'], '(t),()',
+ nopython=True, writable_args=(0,),
+ target='parallel')(py_replace_2nd)
+ self._run_test_for_gufunc(gufunc, py_replace_2nd)
+
+ def test_update_inplace_3(self):
+ # test without writable_args
+ gufunc = guvectorize(['void(f8[:], f8[:], f8[:], f8[:])'],
+ '(t),(t),(t),()',
+ nopython=True)(py_update_3)
+ self._run_test_for_gufunc(gufunc, py_update_3, expect_f4_to_pass=False)
+
+ # test with writable_args
+ gufunc = guvectorize(['void(f8[:], f8[:], f8[:], f8[:])'],
+ '(t),(t),(t),()', nopython=True,
+ writable_args=(0, 1, 2))(py_update_3)
+ self._run_test_for_gufunc(gufunc, py_update_3)
+
+ # test with writable_args as mix of strings and ints
+ gufunc = guvectorize(['void(f8[:], f8[:], f8[:], f8[:])'],
+ '(t),(t),(t),()', nopython=True,
+ writable_args=('x0_t', 'x1_t', 2))(py_update_3)
+ self._run_test_for_gufunc(gufunc, py_update_3)
+
+ def test_exceptions(self):
+ # check that len(writable_args) <= nin
+ with self.assertRaises(ValueError):
+ guvectorize(['void(f8[:], f8[:])'], '(t),()', nopython=True,
+ writable_args=(0, 1, 2, 5))(py_replace_2nd)
+
+ # check that all values in writable_args are between 0 and nin
+ with self.assertRaises(ValueError):
+ guvectorize(['void(f8[:], f8[:])'], '(t),()',
+ nopython=True, writable_args=(5,))(py_replace_2nd)
+
+ with self.assertRaises(ValueError):
+ guvectorize(['void(f8[:], f8[:])'], '(t),()',
+ nopython=True, writable_args=(-1,))(py_replace_2nd)
+
+ # check that exception is raised when passing non-existing argument name
+ with self.assertRaises(RuntimeError):
+ guvectorize(['void(f8[:], f8[:])'], '(t),()',
+ nopython=True, writable_args=('z_t',))(py_replace_2nd)
+
+ # writable_args are not supported for target='cuda'
+ with self.assertRaises(TypeError):
+ guvectorize(['void(f8[:], f8[:])'], '(t),()',
+ nopython=True, writable_args=(0,),
+ target='cuda')(py_replace_2nd)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/npyufunc/test_vectorize_decor.py b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/npyufunc/test_vectorize_decor.py
new file mode 100644
index 0000000000000000000000000000000000000000..6eb984d8c04a07c12b0d690a2003b0a61defd058
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/npyufunc/test_vectorize_decor.py
@@ -0,0 +1,151 @@
+import math
+
+import numpy as np
+
+from numba import int32, uint32, float32, float64, jit, vectorize
+from numba.tests.support import tag, CheckWarningsMixin
+import unittest
+
+
+pi = math.pi
+
+
+def sinc(x):
+ if x == 0.0:
+ return 1.0
+ else:
+ return math.sin(x * pi) / (pi * x)
+
+def scaled_sinc(x, scale):
+ if x == 0.0:
+ return scale
+ else:
+ return scale * (math.sin(x * pi) / (pi * x))
+
+def vector_add(a, b):
+ return a + b
+
+
+class BaseVectorizeDecor(object):
+ target = None
+ wrapper = None
+ funcs = {
+ 'func1': sinc,
+ 'func2': scaled_sinc,
+ 'func3': vector_add,
+ }
+
+ @classmethod
+ def _run_and_compare(cls, func, sig, A, *args, **kwargs):
+ if cls.wrapper is not None:
+ func = cls.wrapper(func)
+ numba_func = vectorize(sig, target=cls.target)(func)
+ numpy_func = np.vectorize(func)
+ result = numba_func(A, *args)
+ gold = numpy_func(A, *args)
+ np.testing.assert_allclose(result, gold, **kwargs)
+
+ def test_1(self):
+ sig = ['float64(float64)', 'float32(float32)']
+ func = self.funcs['func1']
+ A = np.arange(100, dtype=np.float64)
+ self._run_and_compare(func, sig, A)
+
+ def test_2(self):
+ sig = [float64(float64), float32(float32)]
+ func = self.funcs['func1']
+ A = np.arange(100, dtype=np.float64)
+ self._run_and_compare(func, sig, A)
+
+ def test_3(self):
+ sig = ['float64(float64, uint32)']
+ func = self.funcs['func2']
+ A = np.arange(100, dtype=np.float64)
+ scale = np.uint32(3)
+ self._run_and_compare(func, sig, A, scale, atol=1e-8)
+
+ def test_4(self):
+ sig = [
+ int32(int32, int32),
+ uint32(uint32, uint32),
+ float32(float32, float32),
+ float64(float64, float64),
+ ]
+ func = self.funcs['func3']
+ A = np.arange(100, dtype=np.float64)
+ self._run_and_compare(func, sig, A, A)
+ A = A.astype(np.float32)
+ self._run_and_compare(func, sig, A, A)
+ A = A.astype(np.int32)
+ self._run_and_compare(func, sig, A, A)
+ A = A.astype(np.uint32)
+ self._run_and_compare(func, sig, A, A)
+
+
+class TestCPUVectorizeDecor(unittest.TestCase, BaseVectorizeDecor):
+ target = 'cpu'
+
+
+class TestParallelVectorizeDecor(unittest.TestCase, BaseVectorizeDecor):
+ _numba_parallel_test_ = False
+ target = 'parallel'
+
+
+class TestCPUVectorizeJitted(unittest.TestCase, BaseVectorizeDecor):
+ target = 'cpu'
+ wrapper = jit(nopython=True)
+
+
+class BaseVectorizeNopythonArg(unittest.TestCase, CheckWarningsMixin):
+ """
+ Test passing the nopython argument to the vectorize decorator.
+ """
+ def _test_target_nopython(self, target, warnings, with_sig=True):
+ a = np.array([2.0], dtype=np.float32)
+ b = np.array([3.0], dtype=np.float32)
+ sig = [float32(float32, float32)]
+ args = with_sig and [sig] or []
+ with self.check_warnings(warnings):
+ f = vectorize(*args, target=target, nopython=True)(vector_add)
+ f(a, b)
+
+class TestVectorizeNopythonArg(BaseVectorizeNopythonArg):
+ def test_target_cpu_nopython(self):
+ self._test_target_nopython('cpu', [])
+
+ def test_target_cpu_nopython_no_sig(self):
+ self._test_target_nopython('cpu', [], False)
+
+ def test_target_parallel_nopython(self):
+ self._test_target_nopython('parallel', [])
+
+
+class BaseVectorizeUnrecognizedArg(unittest.TestCase, CheckWarningsMixin):
+ """
+ Test passing an unrecognized argument to the vectorize decorator.
+ """
+ def _test_target_unrecognized_arg(self, target, with_sig=True):
+ a = np.array([2.0], dtype=np.float32)
+ b = np.array([3.0], dtype=np.float32)
+ sig = [float32(float32, float32)]
+ args = with_sig and [sig] or []
+ with self.assertRaises(KeyError) as raises:
+ f = vectorize(*args, target=target, nonexistent=2)(vector_add)
+ f(a, b)
+ self.assertIn("Unrecognized options", str(raises.exception))
+
+class TestVectorizeUnrecognizedArg(BaseVectorizeUnrecognizedArg):
+ def test_target_cpu_unrecognized_arg(self):
+ self._test_target_unrecognized_arg('cpu')
+
+ def test_target_cpu_unrecognized_arg_no_sig(self):
+ self._test_target_unrecognized_arg('cpu', False)
+
+ def test_target_parallel_unrecognized_arg(self):
+ self._test_target_unrecognized_arg('parallel')
+
+
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/npyufunc/ufuncbuilding_usecases.py b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/npyufunc/ufuncbuilding_usecases.py
new file mode 100644
index 0000000000000000000000000000000000000000..0e96dc300cf3642ee3a042bf55cda4885a98c547
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/npyufunc/ufuncbuilding_usecases.py
@@ -0,0 +1,69 @@
+from numba import vectorize
+
+
+def add(a, b):
+ """An addition"""
+ return a + b
+
+
+def equals(a, b):
+ return a == b
+
+
+def mul(a, b):
+ """A multiplication"""
+ return a * b
+
+
+def guadd(a, b, c):
+ """A generalized addition"""
+ x, y = c.shape
+ for i in range(x):
+ for j in range(y):
+ c[i, j] = a[i, j] + b[i, j]
+
+
+@vectorize(nopython=True)
+def inner(a, b):
+ return a + b
+
+
+@vectorize(["int64(int64, int64)"], nopython=True)
+def inner_explicit(a, b):
+ return a + b
+
+
+def outer(a, b):
+ return inner(a, b)
+
+
+def outer_explicit(a, b):
+ return inner_explicit(a, b)
+
+
+class Dummy:
+ pass
+
+
+def guadd_obj(a, b, c):
+ Dummy() # to force object mode
+ x, y = c.shape
+ for i in range(x):
+ for j in range(y):
+ c[i, j] = a[i, j] + b[i, j]
+
+
+def guadd_scalar_obj(a, b, c):
+ Dummy() # to force object mode
+ x, y = c.shape
+ for i in range(x):
+ for j in range(y):
+ c[i, j] = a[i, j] + b
+
+
+class MyException(Exception):
+ pass
+
+
+def guerror(a, b, c):
+ raise MyException
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/pycc_distutils_usecase/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/pycc_distutils_usecase/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/pycc_distutils_usecase/setup_distutils.py b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/pycc_distutils_usecase/setup_distutils.py
new file mode 100644
index 0000000000000000000000000000000000000000..3976af72db2547bd15da9d4ac60169f7014a8223
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/pycc_distutils_usecase/setup_distutils.py
@@ -0,0 +1,13 @@
+from setuptools import distutils
+from source_module import cc
+
+
+setup = distutils.core.setup
+
+
+def run_setup():
+ setup(ext_modules=[cc.distutils_extension()])
+
+
+if __name__ == '__main__':
+ run_setup()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/pycc_distutils_usecase/setup_distutils_nested.py b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/pycc_distutils_usecase/setup_distutils_nested.py
new file mode 100644
index 0000000000000000000000000000000000000000..750551ba51d5871d03f737b54bd9656da83c0116
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/pycc_distutils_usecase/setup_distutils_nested.py
@@ -0,0 +1,14 @@
+from setuptools import distutils
+
+from nested.source_module import cc
+
+
+setup = distutils.core.setup
+
+
+def run_setup():
+ setup(ext_modules=[cc.distutils_extension()])
+
+
+if __name__ == '__main__':
+ run_setup()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/pycc_distutils_usecase/setup_setuptools.py b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/pycc_distutils_usecase/setup_setuptools.py
new file mode 100644
index 0000000000000000000000000000000000000000..ecfe9decd3213dfff402a5818acf09129250081a
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/pycc_distutils_usecase/setup_setuptools.py
@@ -0,0 +1,11 @@
+from setuptools import setup
+
+from source_module import cc
+
+
+def run_setup():
+ setup(ext_modules=[cc.distutils_extension()])
+
+
+if __name__ == '__main__':
+ run_setup()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/pycc_distutils_usecase/setup_setuptools_nested.py b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/pycc_distutils_usecase/setup_setuptools_nested.py
new file mode 100644
index 0000000000000000000000000000000000000000..c4381fc5560e0f04a8b3ed5c8f40ac52d33ef74c
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/pycc_distutils_usecase/setup_setuptools_nested.py
@@ -0,0 +1,11 @@
+from setuptools import setup
+
+from nested.source_module import cc
+
+
+def run_setup():
+ setup(ext_modules=[cc.distutils_extension()])
+
+
+if __name__ == '__main__':
+ run_setup()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/pycc_distutils_usecase/source_module.py b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/pycc_distutils_usecase/source_module.py
new file mode 100644
index 0000000000000000000000000000000000000000..e5e6ea82f3b2ac5be2569c915ce742f40d62dfa6
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/pycc_distutils_usecase/source_module.py
@@ -0,0 +1,18 @@
+import numpy as np
+
+from numba.pycc import CC
+
+
+cc = CC('pycc_compiled_module')
+
+_const = 42
+
+# This ones references a global variable at compile time
+@cc.export('get_const', 'i8()')
+def get_const():
+ return _const
+
+# This one needs NRT and an environment
+@cc.export('ones', 'f8[:](i4)')
+def ones(n):
+ return np.ones(n)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/test_warnings.py b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/test_warnings.py
new file mode 100644
index 0000000000000000000000000000000000000000..92ea575f35c5742007f59abe48f269dc740daa1b
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/test_warnings.py
@@ -0,0 +1,187 @@
+import os
+import subprocess
+import sys
+import warnings
+import numpy as np
+
+import unittest
+from numba import jit
+from numba.core.errors import (
+ NumbaWarning,
+ deprecated,
+ NumbaDeprecationWarning,
+ NumbaPendingDeprecationWarning,
+)
+from numba.core import errors
+from numba.tests.support import ignore_internal_warnings
+
+
+class TestBuiltins(unittest.TestCase):
+
+ def check_objmode_deprecation_warning(self, w):
+ # Object mode fall-back is slated for deprecation, check the warning
+ msg = ("Fall-back from the nopython compilation path to the object "
+ "mode compilation path has been detected")
+ self.assertEqual(w.category, NumbaDeprecationWarning)
+ self.assertIn(msg, str(w.message))
+
+ def check_nopython_kwarg_missing_warning(self, w):
+ # nopython default is scheduled to change when objmode fall-back is
+ # removed, check warning.
+ msg = ("The \'nopython\' keyword argument was not supplied")
+ self.assertEqual(w.category, NumbaDeprecationWarning)
+ self.assertIn(msg, str(w.message))
+
+ def test_return_type_warning_with_nrt(self):
+ """
+ Rerun test_return_type_warning with nrt
+ """
+ y = np.ones(4, dtype=np.float32)
+
+ def return_external_array():
+ return y
+
+ with warnings.catch_warnings(record=True) as w:
+ warnings.simplefilter('always', NumbaWarning)
+ ignore_internal_warnings()
+
+ cfunc = jit(nopython=True)(return_external_array)
+ cfunc()
+ # No more warning
+ self.assertEqual(len(w), 0)
+
+ def test_no_warning_with_forceobj(self):
+ def add(x, y):
+ a = [] # noqa dead
+ return x + y
+
+ with warnings.catch_warnings(record=True) as w:
+ warnings.simplefilter('always', NumbaWarning)
+ ignore_internal_warnings()
+
+ cfunc = jit(add, forceobj=True)
+ cfunc(1, 2)
+
+ self.assertEqual(len(w), 0)
+
+ def test_deprecated(self):
+ @deprecated('foo')
+ def bar():
+ pass
+
+ with warnings.catch_warnings(record=True) as w:
+ warnings.simplefilter('always')
+ ignore_internal_warnings()
+ bar()
+
+ self.assertEqual(len(w), 1)
+ self.assertEqual(w[0].category, DeprecationWarning)
+ self.assertIn('bar', str(w[0].message))
+ self.assertIn('foo', str(w[0].message))
+
+ def test_warnings_fixer(self):
+ # For some context, see #4083
+
+ wfix = errors.WarningsFixer(errors.NumbaWarning)
+ with wfix.catch_warnings('foo', 10):
+ warnings.warn(errors.NumbaWarning('same'))
+ warnings.warn(errors.NumbaDeprecationWarning('same'))
+ ignore_internal_warnings()
+
+ with warnings.catch_warnings(record=True) as w:
+ warnings.simplefilter('always')
+ ignore_internal_warnings()
+ wfix.flush()
+
+ self.assertEqual(len(w), 2)
+ # the order of these will be backwards to the above, the
+ # WarningsFixer flush method sorts with a key based on str
+ # comparison
+ self.assertEqual(w[0].category, NumbaDeprecationWarning)
+ self.assertEqual(w[1].category, NumbaWarning)
+ self.assertIn('same', str(w[0].message))
+ self.assertIn('same', str(w[1].message))
+
+ def test_disable_performance_warnings(self):
+
+ not_found_ret_code = 55
+ found_ret_code = 99
+ expected = "'parallel=True' was specified but no transformation"
+
+ # NOTE: the error_usecases is needed as the NumbaPerformanceWarning's
+ # for parallel=True failing to parallelise do not appear for functions
+ # defined by string eval/exec etc.
+ parallel_code = """if 1:
+ import warnings
+ from numba.tests.error_usecases import foo
+ import numba
+ from numba.tests.support import ignore_internal_warnings
+ with warnings.catch_warnings(record=True) as w:
+ warnings.simplefilter('always')
+ ignore_internal_warnings()
+ foo()
+ for x in w:
+ if x.category == numba.errors.NumbaPerformanceWarning:
+ if "%s" in str(x.message):
+ exit(%s)
+ exit(%s)
+ """ % (expected, found_ret_code, not_found_ret_code)
+
+ # run in the standard env, warning should raise
+ popen = subprocess.Popen([sys.executable, "-c", parallel_code])
+ out, err = popen.communicate()
+ self.assertEqual(popen.returncode, found_ret_code)
+
+ # run in an env with performance warnings disabled, should not warn
+ env = dict(os.environ)
+ env['NUMBA_DISABLE_PERFORMANCE_WARNINGS'] = "1"
+ popen = subprocess.Popen([sys.executable, "-c", parallel_code], env=env)
+ out, err = popen.communicate()
+ self.assertEqual(popen.returncode, not_found_ret_code)
+
+ def test_filter_deprecation_warnings(self):
+ # Filter on base classes of deprecation warnings should apply to Numba's
+ # deprecation warnings
+ with warnings.catch_warnings():
+ warnings.simplefilter('error')
+ warnings.simplefilter('ignore', category=DeprecationWarning)
+ warnings.simplefilter('ignore', category=PendingDeprecationWarning)
+ warnings.warn(DeprecationWarning("this is ignored"))
+ warnings.warn(PendingDeprecationWarning("this is ignored"))
+ warnings.warn(NumbaDeprecationWarning("this is ignored"))
+ warnings.warn(NumbaPendingDeprecationWarning("this is ignored"))
+ with self.assertRaises(NumbaWarning):
+ warnings.warn(NumbaWarning("this is not ignored"))
+
+ def test_filter_ignore_numba_deprecation_only(self):
+ # Make a filter that ignores Numba's deprecation warnings but raises on
+ # other deprecation warnings
+ with warnings.catch_warnings():
+ warnings.simplefilter('error', category=DeprecationWarning)
+ warnings.simplefilter('error', category=PendingDeprecationWarning)
+ warnings.simplefilter('ignore', category=NumbaDeprecationWarning)
+ warnings.simplefilter('ignore',
+ category=NumbaPendingDeprecationWarning)
+
+ with self.assertRaises(DeprecationWarning):
+ warnings.warn(DeprecationWarning("this is not ignored"))
+ with self.assertRaises(PendingDeprecationWarning):
+ warnings.warn(PendingDeprecationWarning("this is not ignored"))
+
+ warnings.warn(NumbaDeprecationWarning("this is ignored"))
+ warnings.warn(NumbaPendingDeprecationWarning("this is ignored"))
+
+ # now make it so that Numba deprecation warnings are raising
+ warnings.simplefilter('error', category=NumbaDeprecationWarning)
+ warnings.simplefilter('error',
+ category=NumbaPendingDeprecationWarning)
+
+ with self.assertRaises(DeprecationWarning):
+ warnings.warn(NumbaDeprecationWarning("this is not ignored"))
+ with self.assertRaises(PendingDeprecationWarning):
+ warnings.warn(NumbaPendingDeprecationWarning(
+ "this is not ignored"))
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/test_withlifting.py b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/test_withlifting.py
new file mode 100644
index 0000000000000000000000000000000000000000..dda31c1ebccdaf1e28d8ccc0ebaa33c6a562cb82
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/test_withlifting.py
@@ -0,0 +1,1217 @@
+import copy
+import warnings
+import numpy as np
+
+import numba
+from numba.core.transforms import find_setupwiths, with_lifting
+from numba.core.withcontexts import bypass_context, call_context, objmode_context
+from numba.core.bytecode import FunctionIdentity, ByteCode
+from numba.core.interpreter import Interpreter
+from numba.core import errors
+from numba.core.registry import cpu_target
+from numba.core.compiler import compile_ir, DEFAULT_FLAGS
+from numba import njit, typeof, objmode, types
+from numba.core.extending import overload
+from numba.tests.support import (MemoryLeak, TestCase, captured_stdout,
+ skip_unless_scipy, linux_only,
+ strace_supported, strace,
+ expected_failure_py311,
+ expected_failure_py312,
+ expected_failure_py313)
+from numba.core.utils import PYVERSION
+from numba.experimental import jitclass
+import unittest
+
+
+def get_func_ir(func):
+ func_id = FunctionIdentity.from_function(func)
+ bc = ByteCode(func_id=func_id)
+ interp = Interpreter(func_id)
+ func_ir = interp.interpret(bc)
+ return func_ir
+
+
+def lift1():
+ print("A")
+ with bypass_context:
+ print("B")
+ b()
+ print("C")
+
+
+def lift2():
+ x = 1
+ print("A", x)
+ x = 1
+ with bypass_context:
+ print("B", x)
+ x += 100
+ b()
+ x += 1
+ with bypass_context:
+ print("C", x)
+ b()
+ x += 10
+ x += 1
+ print("D", x)
+
+
+def lift3():
+ x = 1
+ y = 100
+ print("A", x, y)
+ with bypass_context:
+ print("B")
+ b()
+ x += 100
+ with bypass_context:
+ print("C")
+ y += 100000
+ b()
+ x += 1
+ y += 1
+ print("D", x, y)
+
+
+def lift4():
+ x = 0
+ print("A", x)
+ x += 10
+ with bypass_context:
+ print("B")
+ b()
+ x += 1
+ for i in range(10):
+ with bypass_context:
+ print("C")
+ b()
+ x += i
+ with bypass_context:
+ print("D")
+ b()
+ if x:
+ x *= 10
+ x += 1
+ print("E", x)
+
+
+def lift5():
+ print("A")
+
+
+def liftcall1():
+ x = 1
+ print("A", x)
+ with call_context:
+ x += 1
+ print("B", x)
+ return x
+
+
+def liftcall2():
+ x = 1
+ print("A", x)
+ with call_context:
+ x += 1
+ print("B", x)
+ with call_context:
+ x += 10
+ print("C", x)
+ return x
+
+
+def liftcall3():
+ x = 1
+ print("A", x)
+ with call_context:
+ if x > 0:
+ x += 1
+ print("B", x)
+ with call_context:
+ for i in range(10):
+ x += i
+ print("C", x)
+ return x
+
+
+def liftcall4():
+ with call_context:
+ with call_context:
+ pass
+
+
+def liftcall5():
+ for i in range(10):
+ with call_context:
+ print(i)
+ if i == 5:
+ print("A")
+ break
+ return i
+
+
+def lift_undefiend():
+ with undefined_global_var:
+ pass
+
+
+bogus_contextmanager = object()
+
+
+def lift_invalid():
+ with bogus_contextmanager:
+ pass
+
+
+gv_type = types.intp
+
+
+class TestWithFinding(TestCase):
+ def check_num_of_with(self, func, expect_count):
+ the_ir = get_func_ir(func)
+ ct = len(find_setupwiths(the_ir)[0])
+ self.assertEqual(ct, expect_count)
+
+ def test_lift1(self):
+ self.check_num_of_with(lift1, expect_count=1)
+
+ def test_lift2(self):
+ self.check_num_of_with(lift2, expect_count=2)
+
+ def test_lift3(self):
+ self.check_num_of_with(lift3, expect_count=1)
+
+ def test_lift4(self):
+ self.check_num_of_with(lift4, expect_count=2)
+
+ def test_lift5(self):
+ self.check_num_of_with(lift5, expect_count=0)
+
+
+class BaseTestWithLifting(TestCase):
+ def setUp(self):
+ super(BaseTestWithLifting, self).setUp()
+ self.typingctx = cpu_target.typing_context
+ self.targetctx = cpu_target.target_context
+ self.flags = DEFAULT_FLAGS
+
+ def check_extracted_with(self, func, expect_count, expected_stdout):
+ the_ir = get_func_ir(func)
+ new_ir, extracted = with_lifting(
+ the_ir, self.typingctx, self.targetctx, self.flags,
+ locals={},
+ )
+ self.assertEqual(len(extracted), expect_count)
+ cres = self.compile_ir(new_ir)
+
+ with captured_stdout() as out:
+ cres.entry_point()
+
+ self.assertEqual(out.getvalue(), expected_stdout)
+
+ def compile_ir(self, the_ir, args=(), return_type=None):
+ typingctx = self.typingctx
+ targetctx = self.targetctx
+ flags = self.flags
+ return compile_ir(typingctx, targetctx, the_ir, args,
+ return_type, flags, locals={})
+
+
+class TestLiftByPass(BaseTestWithLifting):
+
+ def test_lift1(self):
+ self.check_extracted_with(lift1, expect_count=1,
+ expected_stdout="A\nC\n")
+
+ def test_lift2(self):
+ self.check_extracted_with(lift2, expect_count=2,
+ expected_stdout="A 1\nD 3\n")
+
+ def test_lift3(self):
+ self.check_extracted_with(lift3, expect_count=1,
+ expected_stdout="A 1 100\nD 2 101\n")
+
+ def test_lift4(self):
+ self.check_extracted_with(lift4, expect_count=2,
+ expected_stdout="A 0\nE 11\n")
+
+ def test_lift5(self):
+ self.check_extracted_with(lift5, expect_count=0,
+ expected_stdout="A\n")
+
+
+class TestLiftCall(BaseTestWithLifting):
+
+ def check_same_semantic(self, func):
+ """Ensure same semantic with non-jitted code
+ """
+ jitted = njit(func)
+ with captured_stdout() as got:
+ jitted()
+
+ with captured_stdout() as expect:
+ func()
+
+ self.assertEqual(got.getvalue(), expect.getvalue())
+
+ def test_liftcall1(self):
+ self.check_extracted_with(liftcall1, expect_count=1,
+ expected_stdout="A 1\nB 2\n")
+ self.check_same_semantic(liftcall1)
+
+ def test_liftcall2(self):
+ self.check_extracted_with(liftcall2, expect_count=2,
+ expected_stdout="A 1\nB 2\nC 12\n")
+ self.check_same_semantic(liftcall2)
+
+ def test_liftcall3(self):
+ self.check_extracted_with(liftcall3, expect_count=2,
+ expected_stdout="A 1\nB 2\nC 47\n")
+ self.check_same_semantic(liftcall3)
+
+ def test_liftcall4(self):
+ accept = (errors.TypingError, errors.NumbaRuntimeError,
+ errors.NumbaValueError, errors.CompilerError)
+ with self.assertRaises(accept) as raises:
+ njit(liftcall4)()
+ # Known error. We only support one context manager per function
+ # for body that are lifted.
+ msg = ("compiler re-entrant to the same function signature")
+ self.assertIn(msg, str(raises.exception))
+
+ @expected_failure_py311
+ @expected_failure_py312
+ @expected_failure_py313
+ def test_liftcall5(self):
+ self.check_extracted_with(liftcall5, expect_count=1,
+ expected_stdout="0\n1\n2\n3\n4\n5\nA\n")
+ self.check_same_semantic(liftcall5)
+
+
+def expected_failure_for_list_arg(fn):
+ def core(self, *args, **kwargs):
+ with self.assertRaises(errors.TypingError) as raises:
+ fn(self, *args, **kwargs)
+ self.assertIn('Does not support list type',
+ str(raises.exception))
+ return core
+
+
+def expected_failure_for_function_arg(fn):
+ def core(self, *args, **kwargs):
+ with self.assertRaises(errors.TypingError) as raises:
+ fn(self, *args, **kwargs)
+ self.assertIn('Does not support function type',
+ str(raises.exception))
+ return core
+
+
+class TestLiftObj(MemoryLeak, TestCase):
+
+ def setUp(self):
+ warnings.simplefilter("error", errors.NumbaWarning)
+
+ def tearDown(self):
+ warnings.resetwarnings()
+
+ def assert_equal_return_and_stdout(self, pyfunc, *args):
+ py_args = copy.deepcopy(args)
+ c_args = copy.deepcopy(args)
+ cfunc = njit(pyfunc)
+
+ with captured_stdout() as stream:
+ expect_res = pyfunc(*py_args)
+ expect_out = stream.getvalue()
+
+ # avoid compiling during stdout-capturing for easier print-debugging
+ cfunc.compile(tuple(map(typeof, c_args)))
+ with captured_stdout() as stream:
+ got_res = cfunc(*c_args)
+ got_out = stream.getvalue()
+
+ self.assertEqual(expect_out, got_out)
+ self.assertPreciseEqual(expect_res, got_res)
+
+ def test_lift_objmode_basic(self):
+ def bar(ival):
+ print("ival =", {'ival': ival // 2})
+
+ def foo(ival):
+ ival += 1
+ with objmode_context:
+ bar(ival)
+ return ival + 1
+
+ def foo_nonglobal(ival):
+ ival += 1
+ with numba.objmode:
+ bar(ival)
+ return ival + 1
+
+ self.assert_equal_return_and_stdout(foo, 123)
+ self.assert_equal_return_and_stdout(foo_nonglobal, 123)
+
+ def test_lift_objmode_array_in(self):
+ def bar(arr):
+ print({'arr': arr // 2})
+ # arr is modified. the effect is visible outside.
+ arr *= 2
+
+ def foo(nelem):
+ arr = np.arange(nelem).astype(np.int64)
+ with objmode_context:
+ # arr is modified inplace inside bar()
+ bar(arr)
+ return arr + 1
+
+ nelem = 10
+ self.assert_equal_return_and_stdout(foo, nelem)
+
+ def test_lift_objmode_define_new_unused(self):
+ def bar(y):
+ print(y)
+
+ def foo(x):
+ with objmode_context():
+ y = 2 + x # defined but unused outside
+ a = np.arange(y) # defined but unused outside
+ bar(a)
+ return x
+
+ arg = 123
+ self.assert_equal_return_and_stdout(foo, arg)
+
+ def test_lift_objmode_return_simple(self):
+ def inverse(x):
+ print(x)
+ return 1 / x
+
+ def foo(x):
+ with objmode_context(y="float64"):
+ y = inverse(x)
+ return x, y
+
+ def foo_nonglobal(x):
+ with numba.objmode(y="float64"):
+ y = inverse(x)
+ return x, y
+
+ arg = 123
+ self.assert_equal_return_and_stdout(foo, arg)
+ self.assert_equal_return_and_stdout(foo_nonglobal, arg)
+
+ def test_lift_objmode_return_array(self):
+ def inverse(x):
+ print(x)
+ return 1 / x
+
+ def foo(x):
+ with objmode_context(y="float64[:]", z="int64"):
+ y = inverse(x)
+ z = int(y[0])
+ return x, y, z
+
+ arg = np.arange(1, 10, dtype=np.float64)
+ self.assert_equal_return_and_stdout(foo, arg)
+
+ @expected_failure_for_list_arg
+ def test_lift_objmode_using_list(self):
+ def foo(x):
+ with objmode_context(y="float64[:]"):
+ print(x)
+ x[0] = 4
+ print(x)
+ y = [1, 2, 3] + x
+ y = np.asarray([1 / i for i in y])
+ return x, y
+
+ arg = [1, 2, 3]
+ self.assert_equal_return_and_stdout(foo, arg)
+
+ def test_lift_objmode_var_redef(self):
+ def foo(x):
+ for x in range(x):
+ pass
+ if x:
+ x += 1
+ with objmode_context(x="intp"):
+ print(x)
+ x -= 1
+ print(x)
+ for i in range(x):
+ x += i
+ print(x)
+ return x
+
+ arg = 123
+ self.assert_equal_return_and_stdout(foo, arg)
+
+ @expected_failure_for_list_arg
+ def test_case01_mutate_list_ahead_of_ctx(self):
+ def foo(x, z):
+ x[2] = z
+
+ with objmode_context():
+ # should print [1, 2, 15] but prints [1, 2, 3]
+ print(x)
+
+ with objmode_context():
+ x[2] = 2 * z
+ # should print [1, 2, 30] but prints [1, 2, 15]
+ print(x)
+
+ return x
+
+ self.assert_equal_return_and_stdout(foo, [1, 2, 3], 15)
+
+ def test_case02_mutate_array_ahead_of_ctx(self):
+ def foo(x, z):
+ x[2] = z
+
+ with objmode_context():
+ # should print [1, 2, 15]
+ print(x)
+
+ with objmode_context():
+ x[2] = 2 * z
+ # should print [1, 2, 30]
+ print(x)
+
+ return x
+
+ x = np.array([1, 2, 3])
+ self.assert_equal_return_and_stdout(foo, x, 15)
+
+ @expected_failure_for_list_arg
+ def test_case03_create_and_mutate(self):
+ def foo(x):
+ with objmode_context(y='List(int64)'):
+ y = [1, 2, 3]
+ with objmode_context():
+ y[2] = 10
+ return y
+ self.assert_equal_return_and_stdout(foo, 1)
+
+ def test_case04_bogus_variable_type_info(self):
+
+ def foo(x):
+ # should specifying nonsense type info be considered valid?
+ with objmode_context(k="float64[:]"):
+ print(x)
+ return x
+
+ x = np.array([1, 2, 3])
+ cfoo = njit(foo)
+ with self.assertRaises(errors.TypingError) as raises:
+ cfoo(x)
+ self.assertIn(
+ "Invalid type annotation on non-outgoing variables",
+ str(raises.exception),
+ )
+
+ def test_case05_bogus_type_info(self):
+ def foo(x):
+ # should specifying the wrong type info be considered valid?
+ # z is complex.
+ # Note: for now, we will coerce for scalar and raise for array
+ with objmode_context(z="float64[:]"):
+ z = x + 1.j
+ return z
+
+ x = np.array([1, 2, 3])
+ cfoo = njit(foo)
+ with self.assertRaises(TypeError) as raises:
+ got = cfoo(x)
+ self.assertIn(
+ ("can't unbox array from PyObject into native value."
+ " The object maybe of a different type"),
+ str(raises.exception),
+ )
+
+ def test_case06_double_objmode(self):
+ def foo(x):
+ # would nested ctx in the same scope ever make sense? Is this
+ # pattern useful?
+ with objmode_context():
+ #with npmmode_context(): not implemented yet
+ with objmode_context():
+ print(x)
+ return x
+
+ with self.assertRaises(errors.TypingError) as raises:
+ njit(foo)(123)
+ # Check that an error occurred in with-lifting in objmode
+ pat = ("During: resolving callee type: "
+ r"type\(ObjModeLiftedWith\(<.*>\)\)")
+ self.assertRegex(str(raises.exception), pat)
+
+ def test_case07_mystery_key_error(self):
+ # this raises a key error
+ def foo(x):
+ with objmode_context():
+ t = {'a': x}
+ u = 3
+ return x, t, u
+ x = np.array([1, 2, 3])
+ cfoo = njit(foo)
+
+ with self.assertRaises(errors.TypingError) as raises:
+ cfoo(x)
+
+ exstr = str(raises.exception)
+ self.assertIn("Missing type annotation on outgoing variable(s): "
+ "['t', 'u']",
+ exstr)
+ self.assertIn("Example code: with objmode"
+ "(t='')",
+ exstr)
+
+ def test_case08_raise_from_external(self):
+ # this segfaults, expect its because the dict needs to raise as '2' is
+ # not in the keys until a later loop (looking for `d['0']` works fine).
+ d = dict()
+
+ def foo(x):
+ for i in range(len(x)):
+ with objmode_context():
+ k = str(i)
+ v = x[i]
+ d[k] = v
+ print(d['2'])
+ return x
+
+ x = np.array([1, 2, 3])
+ cfoo = njit(foo)
+ with self.assertRaises(KeyError) as raises:
+ cfoo(x)
+ self.assertEqual(str(raises.exception), "'2'")
+
+ def test_case09_explicit_raise(self):
+ def foo(x):
+ with objmode_context():
+ raise ValueError()
+ return x
+
+ x = np.array([1, 2, 3])
+ cfoo = njit(foo)
+ with self.assertRaises(errors.CompilerError) as raises:
+ cfoo(x)
+ self.assertIn(
+ ('unsupported control flow due to raise statements inside '
+ 'with block'),
+ str(raises.exception),
+ )
+
+ @expected_failure_for_list_arg
+ def test_case10_mutate_across_contexts(self):
+ # This shouldn't work due to using List as input.
+ def foo(x):
+ with objmode_context(y='List(int64)'):
+ y = [1, 2, 3]
+ with objmode_context():
+ y[2] = 10
+ return y
+
+ x = np.array([1, 2, 3])
+ self.assert_equal_return_and_stdout(foo, x)
+
+ def test_case10_mutate_array_across_contexts(self):
+ # Sub-case of case-10.
+ def foo(x):
+ with objmode_context(y='int64[:]'):
+ y = np.asarray([1, 2, 3], dtype='int64')
+ with objmode_context():
+ # Note: `y` is not an output.
+ y[2] = 10
+ return y
+
+ x = np.array([1, 2, 3])
+ self.assert_equal_return_and_stdout(foo, x)
+
+ def test_case11_define_function_in_context(self):
+ # should this work? no, global name 'bar' is not defined
+ def foo(x):
+ with objmode_context():
+ def bar(y):
+ return y + 1
+ return x
+
+ x = np.array([1, 2, 3])
+ cfoo = njit(foo)
+ with self.assertRaises(NameError) as raises:
+ cfoo(x)
+ self.assertIn(
+ "global name 'bar' is not defined",
+ str(raises.exception),
+ )
+
+ def test_case12_njit_inside_a_objmode_ctx(self):
+ # TODO: is this still the cases?
+ # this works locally but not inside this test, probably due to the way
+ # compilation is being done
+ def bar(y):
+ return y + 1
+
+ def foo(x):
+ with objmode_context(y='int64[:]'):
+ y = njit(bar)(x).astype('int64')
+ return x + y
+
+ x = np.array([1, 2, 3])
+ self.assert_equal_return_and_stdout(foo, x)
+
+ def test_case14_return_direct_from_objmode_ctx(self):
+ def foo(x):
+ with objmode_context(x='int64[:]'):
+ x += 1
+ return x
+
+ result = foo(np.array([1, 2, 3]))
+ np.testing.assert_array_equal(np.array([2, 3, 4]), result)
+
+ # No easy way to handle this yet.
+ @unittest.expectedFailure
+ def test_case15_close_over_objmode_ctx(self):
+ # Fails with Unsupported constraint encountered: enter_with $phi8.1
+ def foo(x):
+ j = 10
+
+ def bar(x):
+ with objmode_context(x='int64[:]'):
+ print(x)
+ return x + j
+ return bar(x) + 2
+ x = np.array([1, 2, 3])
+ self.assert_equal_return_and_stdout(foo, x)
+
+ @skip_unless_scipy
+ def test_case16_scipy_call_in_objmode_ctx(self):
+ from scipy import sparse as sp
+
+ def foo(x):
+ with objmode_context(k='int64'):
+ print(x)
+ spx = sp.csr_matrix(x)
+ # the np.int64 call is pointless, works around:
+ # https://github.com/scipy/scipy/issues/10206
+ # which hit the SciPy 1.3 release.
+ k = np.int64(spx[0, 0])
+ return k
+ x = np.array([1, 2, 3])
+ self.assert_equal_return_and_stdout(foo, x)
+
+ def test_case17_print_own_bytecode(self):
+ import dis
+
+ def foo(x):
+ with objmode_context():
+ dis.dis(foo)
+ x = np.array([1, 2, 3])
+ self.assert_equal_return_and_stdout(foo, x)
+
+ @expected_failure_for_function_arg
+ def test_case18_njitfunc_passed_to_objmode_ctx(self):
+ def foo(func, x):
+ with objmode_context():
+ func(x[0])
+
+ x = np.array([1, 2, 3])
+ fn = njit(lambda z: z + 5)
+ self.assert_equal_return_and_stdout(foo, fn, x)
+
+ @expected_failure_py311
+ @expected_failure_py312
+ @expected_failure_py313
+ def test_case19_recursion(self):
+ def foo(x):
+ with objmode_context():
+ if x == 0:
+ return 7
+ ret = foo(x - 1)
+ return ret
+ with self.assertRaises((errors.TypingError, errors.CompilerError)) as raises:
+ cfoo = njit(foo)
+ cfoo(np.array([1, 2, 3]))
+ msg = "Untyped global name 'foo'"
+ self.assertIn(msg, str(raises.exception))
+
+ @unittest.expectedFailure
+ def test_case20_rng_works_ok(self):
+ def foo(x):
+ np.random.seed(0)
+ y = np.random.rand()
+ with objmode_context(z="float64"):
+ # It's known that the random state does not sync
+ z = np.random.rand()
+ return x + z + y
+
+ x = np.array([1, 2, 3])
+ self.assert_equal_return_and_stdout(foo, x)
+
+ def test_case21_rng_seed_works_ok(self):
+ def foo(x):
+ np.random.seed(0)
+ y = np.random.rand()
+ with objmode_context(z="float64"):
+ # Similar to test_case20_rng_works_ok but call seed
+ np.random.seed(0)
+ z = np.random.rand()
+ return x + z + y
+
+ x = np.array([1, 2, 3])
+ self.assert_equal_return_and_stdout(foo, x)
+
+ def test_example01(self):
+ # Example from _ObjModeContextType.__doc__
+ def bar(x):
+ return np.asarray(list(reversed(x.tolist())))
+
+ @njit
+ def foo():
+ x = np.arange(5)
+ with objmode(y='intp[:]'): # annotate return type
+ # this region is executed by object-mode.
+ y = x + bar(x)
+ return y
+
+ self.assertPreciseEqual(foo(), foo.py_func())
+ self.assertIs(objmode, objmode_context)
+
+ def test_objmode_in_overload(self):
+ def foo(s):
+ pass
+
+ @overload(foo)
+ def foo_overload(s):
+ def impl(s):
+ with objmode(out='intp'):
+ out = s + 3
+ return out
+ return impl
+
+ @numba.njit
+ def f():
+ return foo(1)
+
+ self.assertEqual(f(), 1 + 3)
+
+ def test_objmode_gv_variable(self):
+ @njit
+ def global_var():
+ with objmode(val=gv_type):
+ val = 12.3
+ return val
+
+ ret = global_var()
+ # the result is truncated because of the intp return-type
+ self.assertIsInstance(ret, int)
+ self.assertEqual(ret, 12)
+
+ def test_objmode_gv_variable_error(self):
+ @njit
+ def global_var():
+ with objmode(val=gv_type2):
+ val = 123
+ return val
+
+ with self.assertRaisesRegex(
+ errors.CompilerError,
+ ("Error handling objmode argument 'val'. "
+ r"Global 'gv_type2' is not defined.")
+ ):
+ global_var()
+
+ def test_objmode_gv_mod_attr(self):
+ @njit
+ def modattr1():
+ with objmode(val=types.intp):
+ val = 12.3
+ return val
+
+ @njit
+ def modattr2():
+ with objmode(val=numba.types.intp):
+ val = 12.3
+ return val
+
+ for fn in (modattr1, modattr2):
+ with self.subTest(fn=str(fn)):
+ ret = fn()
+ # the result is truncated because of the intp return-type
+ self.assertIsInstance(ret, int)
+ self.assertEqual(ret, 12)
+
+ def test_objmode_gv_mod_attr_error(self):
+ @njit
+ def moderror():
+ with objmode(val=types.THIS_DOES_NOT_EXIST):
+ val = 12.3
+ return val
+ with self.assertRaisesRegex(
+ errors.CompilerError,
+ ("Error handling objmode argument 'val'. "
+ "Getattr cannot be resolved at compile-time"),
+ ):
+ moderror()
+
+ def test_objmode_gv_mod_attr_error_multiple(self):
+ @njit
+ def moderror():
+ with objmode(v1=types.intp, v2=types.THIS_DOES_NOT_EXIST,
+ v3=types.float32):
+ v1 = 12.3
+ v2 = 12.3
+ v3 = 12.3
+ return val
+ with self.assertRaisesRegex(
+ errors.CompilerError,
+ ("Error handling objmode argument 'v2'. "
+ "Getattr cannot be resolved at compile-time"),
+ ):
+ moderror()
+
+ def test_objmode_closure_type_in_overload(self):
+ def foo():
+ pass
+
+ @overload(foo)
+ def foo_overload():
+ shrubbery = types.float64[:]
+ def impl():
+ with objmode(out=shrubbery):
+ out = np.arange(10).astype(np.float64)
+ return out
+ return impl
+
+ @njit
+ def bar():
+ return foo()
+
+ self.assertPreciseEqual(bar(), np.arange(10).astype(np.float64))
+
+ def test_objmode_closure_type_in_overload_error(self):
+ def foo():
+ pass
+
+ @overload(foo)
+ def foo_overload():
+ shrubbery = types.float64[:]
+ def impl():
+ with objmode(out=shrubbery):
+ out = np.arange(10).astype(np.float64)
+ return out
+ # Remove closure var.
+ # Otherwise, it will "shrubbery" will be a global
+ del shrubbery
+ return impl
+
+ @njit
+ def bar():
+ return foo()
+
+ with self.assertRaisesRegex(
+ errors.TypingError,
+ ("Error handling objmode argument 'out'. "
+ "Freevar 'shrubbery' is not defined"),
+ ):
+ bar()
+
+ def test_objmode_invalid_use(self):
+ @njit
+ def moderror():
+ with objmode(bad=1 + 1):
+ out = 1
+ return val
+ with self.assertRaisesRegex(
+ errors.CompilerError,
+ ("Error handling objmode argument 'bad'. "
+ "The value must be a compile-time constant either as "
+ "a non-local variable or a getattr expression that "
+ "refers to a Numba type."),
+ ):
+ moderror()
+
+ def test_objmode_multi_type_args(self):
+ array_ty = types.int32[:]
+ @njit
+ def foo():
+ # t1 is a string
+ # t2 is a global type
+ # t3 is a non-local/freevar
+ with objmode(t1="float64", t2=gv_type, t3=array_ty):
+ t1 = 793856.5
+ t2 = t1 # to observe truncation
+ t3 = np.arange(5).astype(np.int32)
+ return t1, t2, t3
+
+ t1, t2, t3 = foo()
+ self.assertPreciseEqual(t1, 793856.5)
+ self.assertPreciseEqual(t2, 793856)
+ self.assertPreciseEqual(t3, np.arange(5).astype(np.int32))
+
+ def test_objmode_jitclass(self):
+ spec = [
+ ('value', types.int32), # a simple scalar field
+ ('array', types.float32[:]), # an array field
+ ]
+
+ @jitclass(spec)
+ class Bag(object):
+ def __init__(self, value):
+ self.value = value
+ self.array = np.zeros(value, dtype=np.float32)
+
+ @property
+ def size(self):
+ return self.array.size
+
+ def increment(self, val):
+ for i in range(self.size):
+ self.array[i] += val
+ return self.array
+
+ @staticmethod
+ def add(x, y):
+ return x + y
+
+ n = 21
+ mybag = Bag(n)
+
+ def foo():
+ pass
+
+ @overload(foo)
+ def foo_overload():
+ shrubbery = mybag._numba_type_
+ def impl():
+ with objmode(out=shrubbery):
+ out = Bag(123)
+ out.increment(3)
+ return out
+ return impl
+
+ @njit
+ def bar():
+ return foo()
+
+ z = bar()
+ self.assertIsInstance(z, Bag)
+ self.assertEqual(z.add(2, 3), 2 + 3)
+ exp_array = np.zeros(123, dtype=np.float32) + 3
+ self.assertPreciseEqual(z.array, exp_array)
+
+
+ @staticmethod
+ def case_objmode_cache(x):
+ with objmode(output='float64'):
+ output = x / 10
+ return output
+
+ def test_objmode_reflected_list(self):
+ ret_type = typeof([1, 2, 3, 4, 5])
+ @njit
+ def test2():
+ with objmode(out=ret_type):
+ out = [1, 2, 3, 4, 5]
+ return out
+
+ with self.assertRaises(errors.CompilerError) as raises:
+ test2()
+ self.assertRegex(
+ str(raises.exception),
+ (r"Objmode context failed. "
+ r"Argument 'out' is declared as an unsupported type: "
+ r"reflected list\(int(32|64)\). "
+ r"Reflected types are not supported."),
+ )
+
+ def test_objmode_reflected_set(self):
+ ret_type = typeof({1, 2, 3, 4, 5})
+ @njit
+ def test2():
+ with objmode(result=ret_type):
+ result = {1, 2, 3, 4, 5}
+ return result
+
+ with self.assertRaises(errors.CompilerError) as raises:
+ test2()
+ self.assertRegex(
+ str(raises.exception),
+ (r"Objmode context failed. "
+ r"Argument 'result' is declared as an unsupported type: "
+ r"reflected set\(int(32|64)\). "
+ r"Reflected types are not supported."),
+ )
+
+ def test_objmode_typed_dict(self):
+ ret_type = types.DictType(types.unicode_type, types.int64)
+ @njit
+ def test4():
+ with objmode(res=ret_type):
+ res = {'A': 1, 'B': 2}
+ return res
+
+ with self.assertRaises(TypeError) as raises:
+ test4()
+ self.assertIn(
+ ("can't unbox a "
+ "as a "),
+ str(raises.exception),
+ )
+
+ def test_objmode_typed_list(self):
+ ret_type = types.ListType(types.int64)
+ @njit
+ def test4():
+ with objmode(res=ret_type):
+ res = [1, 2]
+ return res
+
+ with self.assertRaises(TypeError) as raises:
+ test4()
+ self.assertRegex(
+ str(raises.exception),
+ (r"can't unbox a "
+ r"as a ()?"),
+ )
+
+ def test_objmode_use_of_view(self):
+ # See issue #7158, npm functionality should only be validated if in
+ # npm.
+ @njit
+ def foo(x):
+ with numba.objmode(y="int64[::1]"):
+ y = x.view("int64")
+ return y
+
+ a = np.ones(1, np.int64).view('float64')
+ expected = foo.py_func(a)
+ got = foo(a)
+ self.assertPreciseEqual(expected, got)
+
+
+def case_inner_pyfunc(x):
+ return x / 10
+
+
+def case_objmode_cache(x):
+ with objmode(output='float64'):
+ output = case_inner_pyfunc(x)
+ return output
+
+
+class TestLiftObjCaching(MemoryLeak, TestCase):
+ # Warnings in this test class are converted to errors
+
+ def setUp(self):
+ warnings.simplefilter("error", errors.NumbaWarning)
+
+ def tearDown(self):
+ warnings.resetwarnings()
+
+ def check(self, py_func):
+ first = njit(cache=True)(py_func)
+ self.assertEqual(first(123), 12.3)
+
+ second = njit(cache=True)(py_func)
+ self.assertFalse(second._cache_hits)
+ self.assertEqual(second(123), 12.3)
+ self.assertTrue(second._cache_hits)
+
+ def test_objmode_caching_basic(self):
+ def pyfunc(x):
+ with objmode(output='float64'):
+ output = x / 10
+ return output
+
+ self.check(pyfunc)
+
+ def test_objmode_caching_call_closure_bad(self):
+ def other_pyfunc(x):
+ return x / 10
+
+ def pyfunc(x):
+ with objmode(output='float64'):
+ output = other_pyfunc(x)
+ return output
+
+ self.check(pyfunc)
+
+ def test_objmode_caching_call_closure_good(self):
+ self.check(case_objmode_cache)
+
+
+class TestBogusContext(BaseTestWithLifting):
+ def test_undefined_global(self):
+ the_ir = get_func_ir(lift_undefiend)
+
+ with self.assertRaises(errors.CompilerError) as raises:
+ with_lifting(
+ the_ir, self.typingctx, self.targetctx, self.flags, locals={},
+ )
+ self.assertIn(
+ "Undefined variable used as context manager",
+ str(raises.exception),
+ )
+
+ def test_invalid(self):
+ the_ir = get_func_ir(lift_invalid)
+
+ with self.assertRaises(errors.CompilerError) as raises:
+ with_lifting(
+ the_ir, self.typingctx, self.targetctx, self.flags, locals={},
+ )
+ self.assertIn(
+ "Unsupported context manager in use",
+ str(raises.exception),
+ )
+
+ def test_with_as_fails_gracefully(self):
+ @njit
+ def foo():
+ with open('') as f:
+ pass
+
+ with self.assertRaises(errors.UnsupportedBytecodeError) as raises:
+ foo()
+
+ excstr = str(raises.exception)
+ msg = ("The 'with (context manager) as (variable):' construct is not "
+ "supported.")
+ self.assertIn(msg, excstr)
+
+
+class TestMisc(TestCase):
+ # Tests for miscellaneous objmode issues. Run serially.
+
+ _numba_parallel_test_ = False
+
+ @linux_only
+ @TestCase.run_test_in_subprocess
+ def test_no_fork_in_compilation(self):
+ # Checks that there is no fork/clone/execve during compilation, see
+ # issue #7881. This needs running in a subprocess as the offending fork
+ # call that triggered #7881 occurs on the first call to uuid1 as it's
+ # part if the initialisation process for that function (gets hardware
+ # address of machine).
+
+ if not strace_supported():
+ # Needs strace support.
+ self.skipTest("strace support missing")
+
+ def force_compile():
+ @njit('void()') # force compilation
+ def f():
+ with numba.objmode():
+ pass
+
+ # capture these syscalls:
+ syscalls = ['fork', 'clone', 'execve']
+
+ # check that compilation does not trigger fork, clone or execve
+ strace_data = strace(force_compile, syscalls)
+ self.assertFalse(strace_data)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/threading_backend_usecases.py b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/threading_backend_usecases.py
new file mode 100644
index 0000000000000000000000000000000000000000..3188cfb9b0067de39927346cf6cb6fac011504c1
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/threading_backend_usecases.py
@@ -0,0 +1,29 @@
+import signal
+import sys
+from numba import njit
+import numpy as np
+
+
+def sigterm_handler(signum, frame):
+ raise RuntimeError("Caught SIGTERM")
+
+
+@njit(parallel=True)
+def busy_func_inner(a, b):
+ c = a + b * np.sqrt(a) + np.sqrt(b)
+ d = np.sqrt(a + b * np.sqrt(a) + np.sqrt(b))
+ return c + d
+
+
+def busy_func(a, b, q=None):
+ sys.stdout.flush()
+ sys.stderr.flush()
+ signal.signal(signal.SIGTERM, sigterm_handler)
+ try:
+ z = busy_func_inner(a, b)
+ sys.stdout.flush()
+ sys.stderr.flush()
+ return z
+ except Exception as e:
+ if q is not None:
+ q.put(e)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/typedlist_usecases.py b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/typedlist_usecases.py
new file mode 100644
index 0000000000000000000000000000000000000000..249d3c66f3e30057246152c01ba69b70c13ae230
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/typedlist_usecases.py
@@ -0,0 +1,14 @@
+from numba import int32
+from numba.typed import List
+
+
+# global typed-list for testing purposes
+global_typed_list = List.empty_list(int32)
+for i in (1, 2, 3):
+ global_typed_list.append(int32(i))
+
+
+def catch_global():
+ x = List()
+ for i in global_typed_list:
+ x.append(i)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/tests/usecases.py b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/usecases.py
new file mode 100644
index 0000000000000000000000000000000000000000..7bdc3119b5dc1d875e79435828a8c616c96efab3
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/tests/usecases.py
@@ -0,0 +1,93 @@
+import math
+import numpy as np
+from numba import jit
+
+_GLOBAL_STR = "abc"
+
+def sum1d(s, e):
+ c = 0
+ for i in range(s, e):
+ c += i
+ return c
+
+
+def sum2d(s, e):
+ c = 0
+ for i in range(s, e):
+ for j in range(s, e):
+ c += i * j
+ return c
+
+
+def while_count(s, e):
+ i = s
+ c = 0
+ while i < e:
+ c += i
+ i += 1
+ return c
+
+
+def copy_arrays(a, b):
+ for i in range(a.shape[0]):
+ b[i] = a[i]
+
+
+def copy_arrays2d(a, b):
+ for i in range(a.shape[0]):
+ for j in range(a.shape[1]):
+ b[i, j] = a[i, j]
+
+
+def redefine1():
+ x = 0
+ for i in range(5):
+ x += 1
+ x = 0. + x
+ for i in range(5):
+ x += 1
+ return x
+
+
+def andor(x, y):
+ return (x > 0 and x < 10) or (y > 0 and y < 10)
+
+andornopython = jit(nopython=True)(andor)
+
+
+def string_concat(x, y):
+ a = "whatzup"
+ return a + str(x + y)
+
+
+def string_len(s):
+ return len(s)
+
+
+def string_slicing(s, start, stop):
+ return s[start:stop]
+
+
+def string_conversion(x):
+ # the test that calls this has always relied on objmode fallback so force it
+ object()
+ return str(x)
+
+
+def string_comparison(s1, s2, op):
+ return op(s1, s2)
+
+
+def blackscholes_cnd(d):
+ A1 = 0.31938153
+ A2 = -0.356563782
+ A3 = 1.781477937
+ A4 = -1.821255978
+ A5 = 1.330274429
+ RSQRT2PI = 0.39894228040143267793994605993438
+ K = 1.0 / (1.0 + 0.2316419 * math.fabs(d))
+ ret_val = (RSQRT2PI * math.exp(-0.5 * d * d) *
+ (K * (A1 + K * (A2 + K * (A3 + K * (A4 + K * A5))))))
+ if d > 0:
+ ret_val = 1.0 - ret_val
+ return ret_val
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/typed/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/numba/typed/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..62004deb0a7c8868993b48ac4597a24433ce449c
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/typed/__init__.py
@@ -0,0 +1,20 @@
+import importlib
+
+
+_delayed_symbols = {
+ "Dict": ".typeddict",
+ "List": ".typedlist",
+}
+
+
+def __getattr__(name):
+ # Uses PEP-562 but requires python>3.6
+ if name in _delayed_symbols:
+ modpath = _delayed_symbols[name]
+ mod = importlib.import_module(modpath, __name__)
+ return getattr(mod, name)
+ else:
+ try:
+ return importlib.import_module(f".{name}", __name__)
+ except ModuleNotFoundError:
+ raise AttributeError
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/typed/dictimpl.py b/tool_server/.venv/lib/python3.12/site-packages/numba/typed/dictimpl.py
new file mode 100644
index 0000000000000000000000000000000000000000..fc35e0dc1bcea3c98db2b4f130620caca351096f
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/typed/dictimpl.py
@@ -0,0 +1,43 @@
+"""
+This file implements the lowering for `dict()`
+"""
+from numba.core import types
+from numba.core.imputils import lower_builtin
+
+
+_message_dict_support = """
+Unsupported use of `dict()` with keyword argument(s). \
+The only supported uses are `dict()` or `dict(*iterable)`.
+""".strip()
+
+
+@lower_builtin(dict, types.IterableType)
+def dict_constructor(context, builder, sig, args):
+ from numba.typed import Dict
+
+ dicttype = sig.return_type
+ kt, vt = dicttype.key_type, dicttype.value_type
+
+ def dict_impl(iterable):
+ res = Dict.empty(kt, vt)
+ for k, v in iterable:
+ res[k] = v
+ return res
+
+ return context.compile_internal(builder, dict_impl, sig, args)
+
+
+@lower_builtin(dict)
+def impl_dict(context, builder, sig, args):
+ """
+ The `dict()` implementation simply forwards the work to `Dict.empty()`.
+ """
+ from numba.typed import Dict
+
+ dicttype = sig.return_type
+ kt, vt = dicttype.key_type, dicttype.value_type
+
+ def call_ctor():
+ return Dict.empty(kt, vt)
+
+ return context.compile_internal(builder, call_ctor, sig, args)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/typed/dictobject.py b/tool_server/.venv/lib/python3.12/site-packages/numba/typed/dictobject.py
new file mode 100644
index 0000000000000000000000000000000000000000..60d9db6e0e1df5fdd5853f6d773b70b7042c46b7
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/typed/dictobject.py
@@ -0,0 +1,1367 @@
+"""
+Compiler-side implementation of the dictionary.
+"""
+import ctypes
+import operator
+from enum import IntEnum
+
+from llvmlite import ir
+
+from numba import _helperlib
+
+from numba.core.extending import (
+ overload,
+ overload_method,
+ overload_attribute,
+ intrinsic,
+ register_model,
+ models,
+ lower_builtin,
+ lower_cast,
+ make_attribute_wrapper,
+)
+from numba.core.imputils import iternext_impl, impl_ret_untracked
+from numba.core import types, cgutils
+from numba.core.types import (
+ DictType,
+ DictItemsIterableType,
+ DictKeysIterableType,
+ DictValuesIterableType,
+ DictIteratorType,
+ Type,
+)
+from numba.core.imputils import impl_ret_borrowed, RefType
+from numba.core.errors import TypingError, LoweringError, NumbaTypeError
+from numba.core import typing
+from numba.typed.typedobjectutils import (_as_bytes, _cast, _nonoptional,
+ _sentry_safe_cast_default,
+ _get_incref_decref,
+ _get_equal, _container_get_data,)
+
+ll_dict_type = cgutils.voidptr_t
+ll_dictiter_type = cgutils.voidptr_t
+ll_voidptr_type = cgutils.voidptr_t
+ll_status = cgutils.int32_t
+ll_ssize_t = cgutils.intp_t
+ll_hash = ll_ssize_t
+ll_bytes = cgutils.voidptr_t
+
+
+_meminfo_dictptr = types.MemInfoPointer(types.voidptr)
+
+
+# The following enums must match _dictobject.c
+
+class DKIX(IntEnum):
+ """Special return value of dict lookup.
+ """
+ EMPTY = -1
+
+
+class Status(IntEnum):
+ """Status code for other dict operations.
+ """
+ OK = 0
+ OK_REPLACED = 1
+ ERR_NO_MEMORY = -1
+ ERR_DICT_MUTATED = -2
+ ERR_ITER_EXHAUSTED = -3
+ ERR_DICT_EMPTY = -4
+ ERR_CMP_FAILED = -5
+
+
+def new_dict(key, value, n_keys=0):
+ """Construct a new dict with enough space for *n_keys* without a resize.
+
+ Parameters
+ ----------
+ key, value : TypeRef
+ Key type and value type of the new dict.
+ n_keys : int, default 0
+ The number of keys to insert without needing a resize.
+ A value of 0 creates a dict with minimum size.
+ """
+ # With JIT disabled, ignore all arguments and return a Python dict.
+ return dict()
+
+
+@register_model(DictType)
+class DictModel(models.StructModel):
+ def __init__(self, dmm, fe_type):
+ members = [
+ ('meminfo', _meminfo_dictptr),
+ ('data', types.voidptr), # ptr to the C dict
+ ]
+ super(DictModel, self).__init__(dmm, fe_type, members)
+
+
+@register_model(DictItemsIterableType)
+@register_model(DictKeysIterableType)
+@register_model(DictValuesIterableType)
+@register_model(DictIteratorType)
+class DictIterModel(models.StructModel):
+ def __init__(self, dmm, fe_type):
+ members = [
+ ('parent', fe_type.parent), # reference to the dict
+ ('state', types.voidptr), # iterator state in C code
+ ]
+ super(DictIterModel, self).__init__(dmm, fe_type, members)
+
+
+# Make _parent available to make len simple
+make_attribute_wrapper(DictItemsIterableType, "parent", "_parent")
+make_attribute_wrapper(DictKeysIterableType, "parent", "_parent")
+make_attribute_wrapper(DictValuesIterableType, "parent", "_parent")
+
+
+def _raise_if_error(context, builder, status, msg):
+ """Raise an internal error depending on the value of *status*
+ """
+ ok_status = status.type(int(Status.OK))
+ with builder.if_then(builder.icmp_signed('!=', status, ok_status)):
+ context.call_conv.return_user_exc(builder, RuntimeError, (msg,))
+
+
+@intrinsic
+def _as_meminfo(typingctx, dctobj):
+ """Returns the MemInfoPointer of a dictionary.
+ """
+ if not isinstance(dctobj, types.DictType):
+ raise TypingError('expected *dctobj* to be a DictType')
+
+ def codegen(context, builder, sig, args):
+ [td] = sig.args
+ [d] = args
+ # Incref
+ context.nrt.incref(builder, td, d)
+ ctor = cgutils.create_struct_proxy(td)
+ dstruct = ctor(context, builder, value=d)
+ # Returns the plain MemInfo
+ return dstruct.meminfo
+
+ sig = _meminfo_dictptr(dctobj)
+ return sig, codegen
+
+
+@intrinsic
+def _from_meminfo(typingctx, mi, dicttyperef):
+ """Recreate a dictionary from a MemInfoPointer
+ """
+ if mi != _meminfo_dictptr:
+ raise TypingError('expected a MemInfoPointer for dict.')
+ dicttype = dicttyperef.instance_type
+ if not isinstance(dicttype, DictType):
+ raise TypingError('expected a {}'.format(DictType))
+
+ def codegen(context, builder, sig, args):
+ [tmi, tdref] = sig.args
+ td = tdref.instance_type
+ [mi, _] = args
+
+ ctor = cgutils.create_struct_proxy(td)
+ dstruct = ctor(context, builder)
+
+ data_pointer = context.nrt.meminfo_data(builder, mi)
+ data_pointer = builder.bitcast(data_pointer, ll_dict_type.as_pointer())
+
+ dstruct.data = builder.load(data_pointer)
+ dstruct.meminfo = mi
+
+ return impl_ret_borrowed(
+ context,
+ builder,
+ dicttype,
+ dstruct._getvalue(),
+ )
+
+ sig = dicttype(mi, dicttyperef)
+ return sig, codegen
+
+
+def _call_dict_free(context, builder, ptr):
+ """Call numba_dict_free(ptr)
+ """
+ fnty = ir.FunctionType(
+ ir.VoidType(),
+ [ll_dict_type],
+ )
+ free = cgutils.get_or_insert_function(builder.module, fnty,
+ 'numba_dict_free')
+ builder.call(free, [ptr])
+
+
+def _imp_dtor(context, module):
+ """Define the dtor for dictionary
+ """
+ llvoidptr = context.get_value_type(types.voidptr)
+ llsize = context.get_value_type(types.uintp)
+ fnty = ir.FunctionType(
+ ir.VoidType(),
+ [llvoidptr, llsize, llvoidptr],
+ )
+ fname = '_numba_dict_dtor'
+ fn = cgutils.get_or_insert_function(module, fnty, fname)
+
+ if fn.is_declaration:
+ # Set linkage
+ fn.linkage = 'linkonce_odr'
+ # Define
+ builder = ir.IRBuilder(fn.append_basic_block())
+ dp = builder.bitcast(fn.args[0], ll_dict_type.as_pointer())
+ d = builder.load(dp)
+ _call_dict_free(context, builder, d)
+ builder.ret_void()
+
+ return fn
+
+
+@intrinsic
+def _dict_new_sized(typingctx, n_keys, keyty, valty):
+ """Wrap numba_dict_new_sized.
+
+ Allocate a new dictionary object with enough space to hold
+ *n_keys* keys without needing a resize.
+
+ Parameters
+ ----------
+ keyty, valty: Type
+ Type of the key and value, respectively.
+ n_keys: int
+ The number of keys to insert without needing a resize.
+ A value of 0 creates a dict with minimum size.
+ """
+ resty = types.voidptr
+ sig = resty(n_keys, keyty, valty)
+
+ def codegen(context, builder, sig, args):
+ n_keys = builder.bitcast(args[0], ll_ssize_t)
+
+ # Determine sizeof key and value types
+ ll_key = context.get_data_type(keyty.instance_type)
+ ll_val = context.get_data_type(valty.instance_type)
+ sz_key = context.get_abi_sizeof(ll_key)
+ sz_val = context.get_abi_sizeof(ll_val)
+
+ refdp = cgutils.alloca_once(builder, ll_dict_type, zfill=True)
+
+ argtys = [ll_dict_type.as_pointer(), ll_ssize_t, ll_ssize_t, ll_ssize_t]
+ fnty = ir.FunctionType(ll_status, argtys)
+ fn = ir.Function(builder.module, fnty, 'numba_dict_new_sized')
+
+ args = [refdp, n_keys, ll_ssize_t(sz_key), ll_ssize_t(sz_val)]
+ status = builder.call(fn, args)
+
+ allocated_failed_msg = "Failed to allocate dictionary"
+ _raise_if_error(context, builder, status, msg=allocated_failed_msg)
+
+ dp = builder.load(refdp)
+ return dp
+
+ return sig, codegen
+
+
+@intrinsic
+def _dict_set_method_table(typingctx, dp, keyty, valty):
+ """Wrap numba_dict_set_method_table
+ """
+ resty = types.void
+ sig = resty(dp, keyty, valty)
+
+ def codegen(context, builder, sig, args):
+ vtablety = ir.LiteralStructType([
+ ll_voidptr_type, # equal
+ ll_voidptr_type, # key incref
+ ll_voidptr_type, # key decref
+ ll_voidptr_type, # val incref
+ ll_voidptr_type, # val decref
+ ])
+ setmethod_fnty = ir.FunctionType(
+ ir.VoidType(),
+ [ll_dict_type, vtablety.as_pointer()]
+ )
+ setmethod_fn = ir.Function(
+ builder.module,
+ setmethod_fnty,
+ name='numba_dict_set_method_table',
+ )
+ dp = args[0]
+ vtable = cgutils.alloca_once(builder, vtablety, zfill=True)
+
+ # install key incref/decref
+ key_equal_ptr = cgutils.gep_inbounds(builder, vtable, 0, 0)
+ key_incref_ptr = cgutils.gep_inbounds(builder, vtable, 0, 1)
+ key_decref_ptr = cgutils.gep_inbounds(builder, vtable, 0, 2)
+ val_incref_ptr = cgutils.gep_inbounds(builder, vtable, 0, 3)
+ val_decref_ptr = cgutils.gep_inbounds(builder, vtable, 0, 4)
+
+ dm_key = context.data_model_manager[keyty.instance_type]
+ if dm_key.contains_nrt_meminfo():
+ equal = _get_equal(context, builder.module, dm_key, 'dict_key')
+ key_incref, key_decref = _get_incref_decref(
+ context, builder.module, dm_key, 'dict_key'
+ )
+ builder.store(
+ builder.bitcast(equal, key_equal_ptr.type.pointee),
+ key_equal_ptr,
+ )
+ builder.store(
+ builder.bitcast(key_incref, key_incref_ptr.type.pointee),
+ key_incref_ptr,
+ )
+ builder.store(
+ builder.bitcast(key_decref, key_decref_ptr.type.pointee),
+ key_decref_ptr,
+ )
+
+ dm_val = context.data_model_manager[valty.instance_type]
+ if dm_val.contains_nrt_meminfo():
+ val_incref, val_decref = _get_incref_decref(
+ context, builder.module, dm_val, 'dict_value'
+ )
+ builder.store(
+ builder.bitcast(val_incref, val_incref_ptr.type.pointee),
+ val_incref_ptr,
+ )
+ builder.store(
+ builder.bitcast(val_decref, val_decref_ptr.type.pointee),
+ val_decref_ptr,
+ )
+
+ builder.call(setmethod_fn, [dp, vtable])
+
+ return sig, codegen
+
+
+@intrinsic
+def _dict_insert(typingctx, d, key, hashval, val):
+ """Wrap numba_dict_insert
+ """
+ resty = types.int32
+ sig = resty(d, d.key_type, types.intp, d.value_type)
+
+ def codegen(context, builder, sig, args):
+ fnty = ir.FunctionType(
+ ll_status,
+ [ll_dict_type, ll_bytes, ll_hash, ll_bytes, ll_bytes],
+ )
+ [d, key, hashval, val] = args
+ [td, tkey, thashval, tval] = sig.args
+ fn = cgutils.get_or_insert_function(builder.module, fnty,
+ 'numba_dict_insert')
+
+ dm_key = context.data_model_manager[tkey]
+ dm_val = context.data_model_manager[tval]
+
+ data_key = dm_key.as_data(builder, key)
+ data_val = dm_val.as_data(builder, val)
+
+ ptr_key = cgutils.alloca_once_value(builder, data_key)
+ cgutils.memset_padding(builder, ptr_key)
+
+ ptr_val = cgutils.alloca_once_value(builder, data_val)
+ # TODO: the ptr_oldval is not used. needed for refct
+ ptr_oldval = cgutils.alloca_once(builder, data_val.type)
+
+ dp = _container_get_data(context, builder, td, d)
+ status = builder.call(
+ fn,
+ [
+ dp,
+ _as_bytes(builder, ptr_key),
+ hashval,
+ _as_bytes(builder, ptr_val),
+ _as_bytes(builder, ptr_oldval),
+ ],
+ )
+ return status
+
+ return sig, codegen
+
+
+@intrinsic
+def _dict_length(typingctx, d):
+ """Wrap numba_dict_length
+
+ Returns the length of the dictionary.
+ """
+ resty = types.intp
+ sig = resty(d)
+
+ def codegen(context, builder, sig, args):
+ fnty = ir.FunctionType(
+ ll_ssize_t,
+ [ll_dict_type],
+ )
+ fn = cgutils.get_or_insert_function(builder.module, fnty,
+ 'numba_dict_length')
+ [d] = args
+ [td] = sig.args
+ dp = _container_get_data(context, builder, td, d)
+ n = builder.call(fn, [dp])
+ return n
+
+ return sig, codegen
+
+
+@intrinsic
+def _dict_dump(typingctx, d):
+ """Dump the dictionary keys and values.
+ Wraps numba_dict_dump for debugging.
+ """
+ resty = types.void
+ sig = resty(d)
+
+ def codegen(context, builder, sig, args):
+ fnty = ir.FunctionType(
+ ir.VoidType(),
+ [ll_dict_type],
+ )
+ [td] = sig.args
+ [d] = args
+ dp = _container_get_data(context, builder, td, d)
+ fn = cgutils.get_or_insert_function(builder.module, fnty,
+ 'numba_dict_dump')
+
+ builder.call(fn, [dp])
+
+ return sig, codegen
+
+
+@intrinsic
+def _dict_lookup(typingctx, d, key, hashval):
+ """Wrap numba_dict_lookup
+
+ Returns 2-tuple of (intp, ?value_type)
+ """
+ resty = types.Tuple([types.intp, types.Optional(d.value_type)])
+ sig = resty(d, key, hashval)
+
+ def codegen(context, builder, sig, args):
+ fnty = ir.FunctionType(
+ ll_ssize_t,
+ [ll_dict_type, ll_bytes, ll_hash, ll_bytes],
+ )
+ [td, tkey, thashval] = sig.args
+ [d, key, hashval] = args
+ fn = cgutils.get_or_insert_function(builder.module, fnty,
+ 'numba_dict_lookup')
+
+ dm_key = context.data_model_manager[tkey]
+ dm_val = context.data_model_manager[td.value_type]
+
+ data_key = dm_key.as_data(builder, key)
+ ptr_key = cgutils.alloca_once_value(builder, data_key)
+ cgutils.memset_padding(builder, ptr_key)
+
+ ll_val = context.get_data_type(td.value_type)
+ ptr_val = cgutils.alloca_once(builder, ll_val)
+
+ dp = _container_get_data(context, builder, td, d)
+ ix = builder.call(
+ fn,
+ [
+ dp,
+ _as_bytes(builder, ptr_key),
+ hashval,
+ _as_bytes(builder, ptr_val),
+ ],
+ )
+ # Load value if output is available
+ found = builder.icmp_signed('>', ix, ix.type(int(DKIX.EMPTY)))
+
+ out = context.make_optional_none(builder, td.value_type)
+ pout = cgutils.alloca_once_value(builder, out)
+
+ with builder.if_then(found):
+ val = dm_val.load_from_data_pointer(builder, ptr_val)
+ context.nrt.incref(builder, td.value_type, val)
+ loaded = context.make_optional_value(builder, td.value_type, val)
+ builder.store(loaded, pout)
+
+ out = builder.load(pout)
+ return context.make_tuple(builder, resty, [ix, out])
+
+ return sig, codegen
+
+
+@intrinsic
+def _dict_popitem(typingctx, d):
+ """Wrap numba_dict_popitem
+ """
+
+ keyvalty = types.Tuple([d.key_type, d.value_type])
+ resty = types.Tuple([types.int32, types.Optional(keyvalty)])
+ sig = resty(d)
+
+ def codegen(context, builder, sig, args):
+ fnty = ir.FunctionType(
+ ll_status,
+ [ll_dict_type, ll_bytes, ll_bytes],
+ )
+ [d] = args
+ [td] = sig.args
+ fn = cgutils.get_or_insert_function(builder.module, fnty,
+ 'numba_dict_popitem')
+
+ dm_key = context.data_model_manager[td.key_type]
+ dm_val = context.data_model_manager[td.value_type]
+
+ ptr_key = cgutils.alloca_once(builder, dm_key.get_data_type())
+ ptr_val = cgutils.alloca_once(builder, dm_val.get_data_type())
+
+ dp = _container_get_data(context, builder, td, d)
+ status = builder.call(
+ fn,
+ [
+ dp,
+ _as_bytes(builder, ptr_key),
+ _as_bytes(builder, ptr_val),
+ ],
+ )
+ out = context.make_optional_none(builder, keyvalty)
+ pout = cgutils.alloca_once_value(builder, out)
+
+ cond = builder.icmp_signed('==', status, status.type(int(Status.OK)))
+ with builder.if_then(cond):
+ key = dm_key.load_from_data_pointer(builder, ptr_key)
+ val = dm_val.load_from_data_pointer(builder, ptr_val)
+ keyval = context.make_tuple(builder, keyvalty, [key, val])
+ optkeyval = context.make_optional_value(builder, keyvalty, keyval)
+ builder.store(optkeyval, pout)
+
+ out = builder.load(pout)
+ return cgutils.pack_struct(builder, [status, out])
+
+ return sig, codegen
+
+
+@intrinsic
+def _dict_delitem(typingctx, d, hk, ix):
+ """Wrap numba_dict_delitem
+ """
+ resty = types.int32
+ sig = resty(d, hk, types.intp)
+
+ def codegen(context, builder, sig, args):
+ fnty = ir.FunctionType(
+ ll_status,
+ [ll_dict_type, ll_hash, ll_ssize_t],
+ )
+ [d, hk, ix] = args
+ [td, thk, tix] = sig.args
+
+ fn = cgutils.get_or_insert_function(builder.module, fnty,
+ 'numba_dict_delitem')
+
+ dp = _container_get_data(context, builder, td, d)
+ status = builder.call(fn, [dp, hk, ix])
+ return status
+
+ return sig, codegen
+
+
+def _iterator_codegen(resty):
+ """The common codegen for iterator intrinsics.
+
+ Populates the iterator struct and increfs.
+ """
+
+ def codegen(context, builder, sig, args):
+ [d] = args
+ [td] = sig.args
+ iterhelper = context.make_helper(builder, resty)
+ iterhelper.parent = d
+ iterhelper.state = iterhelper.state.type(None)
+ return impl_ret_borrowed(
+ context,
+ builder,
+ resty,
+ iterhelper._getvalue(),
+ )
+
+ return codegen
+
+
+@intrinsic
+def _dict_items(typingctx, d):
+ """Get dictionary iterator for .items()"""
+ resty = types.DictItemsIterableType(d)
+ sig = resty(d)
+ codegen = _iterator_codegen(resty)
+ return sig, codegen
+
+
+@intrinsic
+def _dict_keys(typingctx, d):
+ """Get dictionary iterator for .keys()"""
+ resty = types.DictKeysIterableType(d)
+ sig = resty(d)
+ codegen = _iterator_codegen(resty)
+ return sig, codegen
+
+
+@intrinsic
+def _dict_values(typingctx, d):
+ """Get dictionary iterator for .values()"""
+ resty = types.DictValuesIterableType(d)
+ sig = resty(d)
+ codegen = _iterator_codegen(resty)
+ return sig, codegen
+
+
+@intrinsic
+def _make_dict(typingctx, keyty, valty, ptr):
+ """Make a dictionary struct with the given *ptr*
+
+ Parameters
+ ----------
+ keyty, valty: Type
+ Type of the key and value, respectively.
+ ptr : llvm pointer value
+ Points to the dictionary object.
+ """
+ dict_ty = types.DictType(keyty.instance_type, valty.instance_type)
+
+ def codegen(context, builder, signature, args):
+ [_, _, ptr] = args
+ ctor = cgutils.create_struct_proxy(dict_ty)
+ dstruct = ctor(context, builder)
+ dstruct.data = ptr
+
+ alloc_size = context.get_abi_sizeof(
+ context.get_value_type(types.voidptr),
+ )
+ dtor = _imp_dtor(context, builder.module)
+ meminfo = context.nrt.meminfo_alloc_dtor(
+ builder,
+ context.get_constant(types.uintp, alloc_size),
+ dtor,
+ )
+
+ data_pointer = context.nrt.meminfo_data(builder, meminfo)
+ data_pointer = builder.bitcast(data_pointer, ll_dict_type.as_pointer())
+ builder.store(ptr, data_pointer)
+
+ dstruct.meminfo = meminfo
+
+ return dstruct._getvalue()
+
+ sig = dict_ty(keyty, valty, ptr)
+ return sig, codegen
+
+
+@overload(new_dict)
+def impl_new_dict(key, value, n_keys=0):
+ """Creates a new dictionary with *key* and *value* as the type
+ of the dictionary key and value, respectively. *n_keys* is the
+ number of keys to insert without requiring a resize, where a
+ value of 0 creates a dictionary with minimum size.
+ """
+ if any([
+ not isinstance(key, Type),
+ not isinstance(value, Type),
+ ]):
+ raise NumbaTypeError("expecting *key* and *value* to be a Numba Type")
+
+ keyty, valty = key, value
+
+ def imp(key, value, n_keys=0):
+ if n_keys < 0:
+ raise RuntimeError("expecting *n_keys* to be >= 0")
+ dp = _dict_new_sized(n_keys, keyty, valty)
+ _dict_set_method_table(dp, keyty, valty)
+ d = _make_dict(keyty, valty, dp)
+ return d
+
+ return imp
+
+
+@overload(len)
+def impl_len(d):
+ """len(dict)
+ """
+ if not isinstance(d, types.DictType):
+ return
+
+ def impl(d):
+ return _dict_length(d)
+
+ return impl
+
+
+@overload(len)
+def impl_len_iters(d):
+ """len(dict.keys()), len(dict.values()), len(dict.items())
+ """
+ if not isinstance(d, (DictKeysIterableType,
+ DictValuesIterableType, DictItemsIterableType)):
+ return
+
+ def impl(d):
+ return _dict_length(d._parent)
+
+ return impl
+
+
+@overload_method(types.DictType, '__setitem__')
+@overload(operator.setitem)
+def impl_setitem(d, key, value):
+ if not isinstance(d, types.DictType):
+ return
+
+ keyty, valty = d.key_type, d.value_type
+
+ def impl(d, key, value):
+ castedkey = _cast(key, keyty)
+ castedval = _cast(value, valty)
+ status = _dict_insert(d, castedkey, hash(castedkey), castedval)
+ if status == Status.OK:
+ return
+ elif status == Status.OK_REPLACED:
+ # replaced
+ # XXX handle refcount
+ return
+ elif status == Status.ERR_CMP_FAILED:
+ raise ValueError('key comparison failed')
+ else:
+ raise RuntimeError('dict.__setitem__ failed unexpectedly')
+
+ if d.is_precise():
+ # Handle the precise case.
+ return impl
+ else:
+ # Handle the imprecise case.
+ d = d.refine(key, value)
+ # Re-bind the key type and value type to match the arguments.
+ keyty, valty = d.key_type, d.value_type
+ # Create the signature that we wanted this impl to have.
+ sig = typing.signature(types.void, d, keyty, valty)
+ return sig, impl
+
+
+@overload_method(types.DictType, 'get')
+def impl_get(dct, key, default=None):
+ if not isinstance(dct, types.DictType):
+ return
+ keyty = dct.key_type
+ valty = dct.value_type
+ _sentry_safe_cast_default(default, valty)
+
+ def impl(dct, key, default=None):
+ castedkey = _cast(key, keyty)
+ ix, val = _dict_lookup(dct, castedkey, hash(castedkey))
+ if ix > DKIX.EMPTY:
+ return val
+ return default
+
+ return impl
+
+
+@overload_attribute(types.DictType, '__hash__')
+def impl_hash(dct):
+ if not isinstance(dct, types.DictType):
+ return
+ return lambda dct: None
+
+
+@overload(operator.getitem)
+def impl_getitem(d, key):
+ if not isinstance(d, types.DictType):
+ return
+
+ keyty = d.key_type
+
+ def impl(d, key):
+ castedkey = _cast(key, keyty)
+ ix, val = _dict_lookup(d, castedkey, hash(castedkey))
+ if ix == DKIX.EMPTY:
+ raise KeyError()
+ elif ix < DKIX.EMPTY:
+ raise AssertionError("internal dict error during lookup")
+ else:
+ return _nonoptional(val)
+
+ return impl
+
+
+@overload_method(types.DictType, 'popitem')
+def impl_popitem(d):
+ if not isinstance(d, types.DictType):
+ return
+
+ def impl(d):
+ status, keyval = _dict_popitem(d)
+ if status == Status.OK:
+ return _nonoptional(keyval)
+ elif status == Status.ERR_DICT_EMPTY:
+ raise KeyError()
+ else:
+ raise AssertionError('internal dict error during popitem')
+
+ return impl
+
+
+@overload_method(types.DictType, 'pop')
+def impl_pop(dct, key, default=None):
+ if not isinstance(dct, types.DictType):
+ return
+
+ keyty = dct.key_type
+ valty = dct.value_type
+ should_raise = isinstance(default, types.Omitted)
+ _sentry_safe_cast_default(default, valty)
+
+ def impl(dct, key, default=None):
+ castedkey = _cast(key, keyty)
+ hashed = hash(castedkey)
+ ix, val = _dict_lookup(dct, castedkey, hashed)
+ if ix == DKIX.EMPTY:
+ if should_raise:
+ raise KeyError()
+ else:
+ return default
+ elif ix < DKIX.EMPTY:
+ raise AssertionError("internal dict error during lookup")
+ else:
+ status = _dict_delitem(dct, hashed, ix)
+ if status != Status.OK:
+ raise AssertionError("internal dict error during delitem")
+ return val
+
+ return impl
+
+
+@overload(operator.delitem)
+def impl_delitem(d, k):
+ if not isinstance(d, types.DictType):
+ return
+
+ def impl(d, k):
+ d.pop(k)
+ return impl
+
+
+@overload(operator.contains)
+def impl_contains(d, k):
+ if not isinstance(d, types.DictType):
+ return
+
+ keyty = d.key_type
+
+ def impl(d, k):
+ k = _cast(k, keyty)
+ ix, val = _dict_lookup(d, k, hash(k))
+ return ix > DKIX.EMPTY
+ return impl
+
+
+@overload_method(types.DictType, 'clear')
+def impl_clear(d):
+ if not isinstance(d, types.DictType):
+ return
+
+ def impl(d):
+ while len(d):
+ d.popitem()
+
+ return impl
+
+
+@overload_method(types.DictType, 'copy')
+def impl_copy(d):
+ if not isinstance(d, types.DictType):
+ return
+
+ key_type, val_type = d.key_type, d.value_type
+
+ def impl(d):
+ newd = new_dict(key_type, val_type, n_keys=len(d))
+ for k, v in d.items():
+ newd[k] = v
+ return newd
+
+ return impl
+
+
+@overload_method(types.DictType, 'setdefault')
+def impl_setdefault(dct, key, default=None):
+ if not isinstance(dct, types.DictType):
+ return
+
+ def impl(dct, key, default=None):
+ if key not in dct:
+ dct[key] = default
+ return dct[key]
+
+ return impl
+
+
+@overload_method(types.DictType, 'items')
+def impl_items(d):
+ if not isinstance(d, types.DictType):
+ return
+
+ def impl(d):
+ it = _dict_items(d)
+ return it
+
+ return impl
+
+
+@overload_method(types.DictType, 'keys')
+def impl_keys(d):
+ if not isinstance(d, types.DictType):
+ return
+
+ def impl(d):
+ return _dict_keys(d)
+
+ return impl
+
+
+@overload_method(types.DictType, 'values')
+def impl_values(d):
+ if not isinstance(d, types.DictType):
+ return
+
+ def impl(d):
+ return _dict_values(d)
+
+ return impl
+
+
+@overload_method(types.DictType, 'update')
+def ol_dict_update(d, other):
+ if not isinstance(d, types.DictType):
+ return
+ if not isinstance(other, types.DictType):
+ return
+
+ def impl(d, other):
+ for k, v in other.items():
+ d[k] = v
+ return impl
+
+
+@overload(operator.eq)
+def impl_equal(da, db):
+ if not isinstance(da, types.DictType):
+ return
+ if not isinstance(db, types.DictType):
+ # If RHS is not a dictionary, always returns False
+ def impl_type_mismatch(da, db):
+ return False
+ return impl_type_mismatch
+
+ otherkeyty = db.key_type
+
+ def impl_type_matched(da, db):
+ if len(da) != len(db):
+ return False
+ for ka, va in da.items():
+ # Cast key from LHS to the key-type of RHS
+ kb = _cast(ka, otherkeyty)
+ ix, vb = _dict_lookup(db, kb, hash(kb))
+ if ix <= DKIX.EMPTY:
+ # Quit early if the key is not found
+ return False
+ if va != vb:
+ # Quit early if the values do not match
+ return False
+ return True
+
+ return impl_type_matched
+
+
+@overload(operator.ne)
+def impl_not_equal(da, db):
+ if not isinstance(da, types.DictType):
+ return
+
+ def impl(da, db):
+ return not (da == db)
+
+ return impl
+
+
+@lower_builtin('getiter', types.DictItemsIterableType)
+@lower_builtin('getiter', types.DictKeysIterableType)
+@lower_builtin('getiter', types.DictValuesIterableType)
+def impl_iterable_getiter(context, builder, sig, args):
+ """Implement iter() for .keys(), .values(), .items()
+ """
+ iterablety = sig.args[0]
+ it = context.make_helper(builder, iterablety.iterator_type, args[0])
+
+ fnty = ir.FunctionType(
+ ir.VoidType(),
+ [ll_dictiter_type, ll_dict_type],
+ )
+
+ fn = cgutils.get_or_insert_function(builder.module, fnty,
+ 'numba_dict_iter')
+
+ proto = ctypes.CFUNCTYPE(ctypes.c_size_t)
+ dictiter_sizeof = proto(_helperlib.c_helpers['dict_iter_sizeof'])
+ state_type = ir.ArrayType(ir.IntType(8), dictiter_sizeof())
+
+ pstate = cgutils.alloca_once(builder, state_type, zfill=True)
+ it.state = _as_bytes(builder, pstate)
+
+ dp = _container_get_data(context, builder, iterablety.parent, it.parent)
+ builder.call(fn, [it.state, dp])
+ return impl_ret_borrowed(
+ context,
+ builder,
+ sig.return_type,
+ it._getvalue(),
+ )
+
+
+@lower_builtin('getiter', types.DictType)
+def impl_dict_getiter(context, builder, sig, args):
+ """Implement iter(Dict). Semantically equivalent to dict.keys()
+ """
+ [td] = sig.args
+ [d] = args
+ iterablety = types.DictKeysIterableType(td)
+ it = context.make_helper(builder, iterablety.iterator_type)
+
+ fnty = ir.FunctionType(
+ ir.VoidType(),
+ [ll_dictiter_type, ll_dict_type],
+ )
+
+ fn = cgutils.get_or_insert_function(builder.module, fnty, 'numba_dict_iter')
+
+ proto = ctypes.CFUNCTYPE(ctypes.c_size_t)
+ dictiter_sizeof = proto(_helperlib.c_helpers['dict_iter_sizeof'])
+ state_type = ir.ArrayType(ir.IntType(8), dictiter_sizeof())
+
+ pstate = cgutils.alloca_once(builder, state_type, zfill=True)
+ it.state = _as_bytes(builder, pstate)
+ it.parent = d
+
+ dp = _container_get_data(context, builder, iterablety.parent, args[0])
+ builder.call(fn, [it.state, dp])
+ return impl_ret_borrowed(
+ context,
+ builder,
+ sig.return_type,
+ it._getvalue(),
+ )
+
+
+@lower_builtin('iternext', types.DictIteratorType)
+@iternext_impl(RefType.BORROWED)
+def impl_iterator_iternext(context, builder, sig, args, result):
+ iter_type = sig.args[0]
+ it = context.make_helper(builder, iter_type, args[0])
+
+ p2p_bytes = ll_bytes.as_pointer()
+
+ iternext_fnty = ir.FunctionType(
+ ll_status,
+ [ll_bytes, p2p_bytes, p2p_bytes]
+ )
+ iternext = cgutils.get_or_insert_function(
+ builder.module, iternext_fnty, 'numba_dict_iter_next',
+ )
+ key_raw_ptr = cgutils.alloca_once(builder, ll_bytes)
+ val_raw_ptr = cgutils.alloca_once(builder, ll_bytes)
+
+ status = builder.call(iternext, (it.state, key_raw_ptr, val_raw_ptr))
+ # TODO: no handling of error state i.e. mutated dictionary
+ # all errors are treated as exhausted iterator
+ is_valid = builder.icmp_unsigned('==', status, status.type(0))
+ result.set_valid(is_valid)
+
+ with builder.if_then(is_valid):
+ yield_type = iter_type.yield_type
+ key_ty, val_ty = iter_type.parent.keyvalue_type
+
+ dm_key = context.data_model_manager[key_ty]
+ dm_val = context.data_model_manager[val_ty]
+
+ key_ptr = builder.bitcast(
+ builder.load(key_raw_ptr),
+ dm_key.get_data_type().as_pointer(),
+ )
+ val_ptr = builder.bitcast(
+ builder.load(val_raw_ptr),
+ dm_val.get_data_type().as_pointer(),
+ )
+
+ key = dm_key.load_from_data_pointer(builder, key_ptr)
+ val = dm_val.load_from_data_pointer(builder, val_ptr)
+
+ # All dict iterators use this common implementation.
+ # Their differences are resolved here.
+ if isinstance(iter_type.iterable, DictItemsIterableType):
+ # .items()
+ tup = context.make_tuple(builder, yield_type, [key, val])
+ result.yield_(tup)
+ elif isinstance(iter_type.iterable, DictKeysIterableType):
+ # .keys()
+ result.yield_(key)
+ elif isinstance(iter_type.iterable, DictValuesIterableType):
+ # .values()
+ result.yield_(val)
+ else:
+ # unreachable
+ raise AssertionError('unknown type: {}'.format(iter_type.iterable))
+
+
+def build_map(context, builder, dict_type, item_types, items):
+
+ if isinstance(dict_type, types.LiteralStrKeyDict):
+ unliteral_tys = [x for x in
+ dict_type.literal_value.values()]
+ nbty = types.NamedTuple(unliteral_tys,
+ dict_type.tuple_ty)
+ values = [x[1] for x in items]
+ # replace with make_tuple call?
+ tup = context.get_constant_undef(nbty)
+ literal_tys = [x for x in dict_type.literal_value.values()]
+
+ # this is to deal with repeated keys
+ value_index = dict_type.value_index
+ if value_index is None:
+ # 1:1 map keys:values
+ value_indexer = range(len(values))
+ else:
+ # 1:>1 map keys:values, e.g. {'a':1, 'a': 'foo'}
+ value_indexer = value_index.values()
+
+ for i, ix in enumerate(value_indexer):
+ val = values[ix]
+ casted = context.cast(builder, val, literal_tys[i],
+ unliteral_tys[i])
+ tup = builder.insert_value(tup, casted, i)
+ d = tup
+ context.nrt.incref(builder, nbty, d)
+
+ else:
+ from numba.typed import Dict
+
+ dt = types.DictType(dict_type.key_type, dict_type.value_type)
+ kt, vt = dict_type.key_type, dict_type.value_type
+ sig = typing.signature(dt)
+
+ def make_dict():
+ return Dict.empty(kt, vt)
+
+ d = context.compile_internal(builder, make_dict, sig, ())
+
+ if items:
+ for (kt, vt), (k, v) in zip(item_types, items):
+ sig = typing.signature(types.void, dt, kt, vt)
+ args = d, k, v
+
+ def put(d, k, v):
+ d[k] = v
+
+ context.compile_internal(builder, put, sig, args)
+
+ return d
+
+
+# ------------------------------------------------------------------------------
+# Literal dictionaries
+# ------------------------------------------------------------------------------
+
+@intrinsic
+def _mixed_values_to_tuple(tyctx, d):
+ keys = [x for x in d.literal_value.keys()]
+ literal_tys = [x for x in d.literal_value.values()]
+
+ def impl(cgctx, builder, sig, args):
+ lld, = args
+ impl = cgctx.get_function('static_getitem',
+ types.none(d, types.literal('dummy')))
+ items = []
+ for k in range(len(keys)):
+ item = impl(builder, (lld, k),)
+ casted = cgctx.cast(builder, item, literal_tys[k], d.types[k])
+ items.append(casted)
+ cgctx.nrt.incref(builder, d.types[k], item)
+ ret = cgctx.make_tuple(builder, sig.return_type, items)
+ return ret
+ sig = types.Tuple(d.types)(d)
+ return sig, impl
+
+
+@overload_method(types.LiteralStrKeyDict, 'values')
+def literalstrkeydict_impl_values(d):
+ # This requires faking a values() iterator simply as a tuple, creating a
+ # type specialising iterator would be possible but horrendous and end up
+ # down the "versioned" loop body route.
+ if not isinstance(d, types.LiteralStrKeyDict):
+ return
+
+ def impl(d):
+ return _mixed_values_to_tuple(d)
+ return impl
+
+
+@overload_method(types.LiteralStrKeyDict, 'keys')
+def literalstrkeydict_impl_keys(d):
+ if not isinstance(d, types.LiteralStrKeyDict):
+ return
+ # create a key iterator by specialising a DictType instance with the
+ # literal keys and returning that
+ t = tuple([x.literal_value for x in d.literal_value.keys()])
+
+ def impl(d):
+ d = dict()
+ for x in t:
+ d[x] = 0
+ return d.keys()
+ return impl
+
+
+# have to lower_builtin as this inherits from tuple and literal, both of which
+# provide a match, hence ambiguous before proper resolution gets a chance
+@lower_builtin(operator.eq, types.LiteralStrKeyDict, types.LiteralStrKeyDict)
+def literalstrkeydict_impl_equals(context, builder, sig, args):
+ tu, tv = sig.args
+ u, v = args
+ pred = tu.literal_value == tv.literal_value
+ res = context.get_constant(types.boolean, pred)
+ return impl_ret_untracked(context, builder, sig.return_type, res)
+
+
+@overload(operator.getitem)
+@overload_method(types.LiteralStrKeyDict, 'get')
+def literalstrkeydict_impl_get(dct, *args):
+ if not isinstance(dct, types.LiteralStrKeyDict):
+ return
+ msg = ("Cannot get{item}() on a literal dictionary, return type cannot be "
+ "statically determined")
+ raise TypingError(msg)
+
+
+@overload_method(types.LiteralStrKeyDict, 'copy')
+def literalstrkeydict_impl_copy(d):
+ if not isinstance(d, types.LiteralStrKeyDict):
+ return
+
+ def impl(d):
+ return d
+ return impl
+
+
+@intrinsic
+def _str_items_mixed_values_to_tuple(tyctx, d):
+ keys = [x for x in d.literal_value.keys()]
+ literal_tys = [x for x in d.literal_value.values()]
+
+ def impl(cgctx, builder, sig, args):
+
+ lld, = args
+ impl = cgctx.get_function('static_getitem',
+ types.none(d, types.literal('dummy')))
+ items = []
+ from numba.cpython.unicode import make_string_from_constant
+ for k in range(len(keys)):
+ item = impl(builder, (lld, k),)
+ casted = cgctx.cast(builder, item, literal_tys[k], d.types[k])
+ cgctx.nrt.incref(builder, d.types[k], item)
+ keydata = make_string_from_constant(cgctx, builder,
+ types.unicode_type,
+ keys[k].literal_value)
+ pair = cgctx.make_tuple(builder,
+ types.Tuple([types.unicode_type,
+ d.types[k]]), (keydata, casted))
+ items.append(pair)
+ ret = cgctx.make_tuple(builder, sig.return_type, items)
+ return ret
+ kvs = [types.Tuple((types.unicode_type, x)) for x in d.types]
+ sig = types.Tuple(kvs)(d)
+ return sig, impl
+
+
+@overload_method(types.LiteralStrKeyDict, 'items')
+def literalstrkeydict_impl_items(d):
+ if not isinstance(d, types.LiteralStrKeyDict):
+ return
+
+ def impl(d):
+ return _str_items_mixed_values_to_tuple(d)
+ return impl
+
+
+@overload(operator.contains)
+def literalstrkeydict_impl_contains(d, k):
+ if not isinstance(d, types.LiteralStrKeyDict):
+ return
+
+ def impl(d, k):
+ for key in d.keys():
+ if k == key:
+ return True
+ return False
+ return impl
+
+
+@overload(len)
+def literalstrkeydict_impl_len(d):
+ if not isinstance(d, types.LiteralStrKeyDict):
+ return
+ l = d.count
+ return lambda d: l
+
+
+@overload(operator.setitem)
+def literalstrkeydict_banned_impl_setitem(d, key, value):
+ if not isinstance(d, types.LiteralStrKeyDict):
+ return
+ raise TypingError("Cannot mutate a literal dictionary")
+
+
+@overload(operator.delitem)
+def literalstrkeydict_banned_impl_delitem(d, k):
+ if not isinstance(d, types.LiteralStrKeyDict):
+ return
+ raise TypingError("Cannot mutate a literal dictionary")
+
+
+@overload_method(types.LiteralStrKeyDict, 'popitem')
+@overload_method(types.LiteralStrKeyDict, 'pop')
+@overload_method(types.LiteralStrKeyDict, 'clear')
+@overload_method(types.LiteralStrKeyDict, 'setdefault')
+@overload_method(types.LiteralStrKeyDict, 'update')
+def literalstrkeydict_banned_impl_mutators(d, *args):
+ if not isinstance(d, types.LiteralStrKeyDict):
+ return
+ raise TypingError("Cannot mutate a literal dictionary")
+
+
+@lower_cast(types.LiteralStrKeyDict, types.LiteralStrKeyDict)
+def cast_LiteralStrKeyDict_LiteralStrKeyDict(context, builder, fromty, toty,
+ val):
+ # should have been picked up by typing
+ for (k1, v1), (k2, v2) in zip(fromty.literal_value.items(),
+ toty.literal_value.items()):
+ # these checks are just guards, typing should have picked up any
+ # problems
+ if k1 != k2: # keys must be same
+ msg = "LiteralDictionary keys are not the same {} != {}"
+ raise LoweringError(msg.format(k1, k2))
+ # values must be same ty
+ if context.typing_context.unify_pairs(v1, v2) is None:
+ msg = "LiteralDictionary values cannot by unified, have {} and {}"
+ raise LoweringError(msg.format(v1, v2))
+ else:
+ fromty = types.Tuple(fromty.types)
+ toty = types.Tuple(toty.types)
+ olditems = cgutils.unpack_tuple(builder, val, len(fromty))
+ items = [context.cast(builder, v, f, t)
+ for v, f, t in zip(olditems, fromty, toty)]
+ return context.make_tuple(builder, toty, items)
+
+
+@lower_cast(types.DictType, types.DictType)
+def cast_DictType_DictType(context, builder, fromty, toty, val):
+ # should have been picked up by typing
+ return val
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/typed/listobject.py b/tool_server/.venv/lib/python3.12/site-packages/numba/typed/listobject.py
new file mode 100644
index 0000000000000000000000000000000000000000..ce5b49cc65ff95a127db9f00ab142554c8b55a27
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/typed/listobject.py
@@ -0,0 +1,1543 @@
+"""
+Compiler-side implementation of the Numba typed-list.
+"""
+import operator
+from enum import IntEnum
+
+from llvmlite import ir
+
+from numba.core.extending import (
+ overload,
+ overload_method,
+ overload_attribute,
+ register_jitable,
+ intrinsic,
+ register_model,
+ models,
+ lower_builtin,
+)
+from numba.core.imputils import iternext_impl
+from numba.core import types, cgutils, config
+from numba.core.types import (
+ ListType,
+ ListTypeIterableType,
+ ListTypeIteratorType,
+ Type,
+ NoneType,
+)
+from numba.core.imputils import impl_ret_borrowed, RefType
+from numba.core.errors import TypingError, NumbaTypeError
+from numba.core import typing
+from numba.typed.typedobjectutils import (_as_bytes, _cast, _nonoptional,
+ _get_incref_decref,
+ _container_get_data,
+ _container_get_meminfo,)
+from numba.cpython import listobj
+
+ll_list_type = cgutils.voidptr_t
+ll_listiter_type = cgutils.voidptr_t
+ll_voidptr_type = cgutils.voidptr_t
+ll_status = cgutils.int32_t
+ll_ssize_t = cgutils.intp_t
+ll_bytes = cgutils.voidptr_t
+
+
+_meminfo_listptr = types.MemInfoPointer(types.voidptr)
+
+if config.USE_LEGACY_TYPE_SYSTEM:
+ INDEXTY = types.intp
+
+ index_types = types.integer_domain
+else:
+ INDEXTY = types.py_int
+
+ index_types = types.py_integer_domain
+
+DEFAULT_ALLOCATED = 0
+
+
+@register_model(ListType)
+class ListModel(models.StructModel):
+ def __init__(self, dmm, fe_type):
+ members = [
+ ('meminfo', _meminfo_listptr),
+ ('data', types.voidptr), # ptr to the C list
+ ]
+ super(ListModel, self).__init__(dmm, fe_type, members)
+
+
+@register_model(ListTypeIterableType)
+@register_model(ListTypeIteratorType)
+class ListIterModel(models.StructModel):
+ def __init__(self, dmm, fe_type):
+ members = [
+ ('size', types.intp), # the size of the iteration space
+ ('parent', fe_type.parent), # the parent list
+ ('index', types.EphemeralPointer(types.intp)), # current index
+ ]
+ super(ListIterModel, self).__init__(dmm, fe_type, members)
+
+
+class ListStatus(IntEnum):
+ """Status code for other list operations.
+ """
+ LIST_OK = 0,
+ LIST_ERR_INDEX = -1
+ LIST_ERR_NO_MEMORY = -2
+ LIST_ERR_MUTATED = -3
+ LIST_ERR_ITER_EXHAUSTED = -4
+ LIST_ERR_IMMUTABLE = -5
+
+
+class ErrorHandler(object):
+ """ErrorHandler for calling codegen functions from this file.
+
+ Stores the state needed to raise an exception from nopython mode.
+ """
+
+ def __init__(self, context):
+ self.context = context
+
+ def __call__(self, builder, status, msg):
+ ok_status = status.type(int(ListStatus.LIST_OK))
+ with builder.if_then(builder.icmp_signed('!=', status, ok_status),
+ likely=True):
+ self.context.call_conv.return_user_exc(
+ builder, RuntimeError, (msg,))
+
+
+def _check_for_none_typed(lst, method):
+ if isinstance(lst.dtype, NoneType):
+ raise TypingError("method support for List[None] is limited, "
+ "not supported: '{}'.".format(method))
+
+
+@intrinsic
+def _as_meminfo(typingctx, lstobj):
+ """Returns the MemInfoPointer of a list.
+ """
+ if not isinstance(lstobj, types.ListType):
+ raise TypingError('expected *lstobj* to be a ListType')
+
+ def codegen(context, builder, sig, args):
+ [tl] = sig.args
+ [l] = args
+ # Incref
+ context.nrt.incref(builder, tl, l)
+ ctor = cgutils.create_struct_proxy(tl)
+ lstruct = ctor(context, builder, value=l)
+ # Returns the plain MemInfo
+ return lstruct.meminfo
+
+ sig = _meminfo_listptr(lstobj)
+ return sig, codegen
+
+
+@intrinsic
+def _from_meminfo(typingctx, mi, listtyperef):
+ """Recreate a list from a MemInfoPointer
+ """
+ if mi != _meminfo_listptr:
+ raise TypingError('expected a MemInfoPointer for list.')
+ listtype = listtyperef.instance_type
+ if not isinstance(listtype, ListType):
+ raise TypingError('expected a {}'.format(ListType))
+
+ def codegen(context, builder, sig, args):
+ [tmi, tdref] = sig.args
+ td = tdref.instance_type
+ [mi, _] = args
+
+ ctor = cgutils.create_struct_proxy(td)
+ dstruct = ctor(context, builder)
+
+ data_pointer = context.nrt.meminfo_data(builder, mi)
+ data_pointer = builder.bitcast(data_pointer, ll_list_type.as_pointer())
+
+ dstruct.data = builder.load(data_pointer)
+ dstruct.meminfo = mi
+
+ return impl_ret_borrowed(
+ context,
+ builder,
+ listtype,
+ dstruct._getvalue(),
+ )
+
+ sig = listtype(mi, listtyperef)
+ return sig, codegen
+
+
+def _list_codegen_set_method_table(context, builder, lp, itemty):
+ vtablety = ir.LiteralStructType([
+ ll_voidptr_type, # item incref
+ ll_voidptr_type, # item decref
+ ])
+ setmethod_fnty = ir.FunctionType(
+ ir.VoidType(),
+ [ll_list_type, vtablety.as_pointer()]
+ )
+
+ setmethod_fn = cgutils.get_or_insert_function(
+ builder.module,
+ setmethod_fnty,
+ 'numba_list_set_method_table')
+ vtable = cgutils.alloca_once(builder, vtablety, zfill=True)
+
+ # install item incref/decref
+ item_incref_ptr = cgutils.gep_inbounds(builder, vtable, 0, 0)
+ item_decref_ptr = cgutils.gep_inbounds(builder, vtable, 0, 1)
+
+ dm_item = context.data_model_manager[itemty]
+ if dm_item.contains_nrt_meminfo():
+ item_incref, item_decref = _get_incref_decref(
+ context, builder.module, dm_item, "list"
+ )
+ builder.store(
+ builder.bitcast(item_incref, item_incref_ptr.type.pointee),
+ item_incref_ptr,
+ )
+ builder.store(
+ builder.bitcast(item_decref, item_decref_ptr.type.pointee),
+ item_decref_ptr,
+ )
+
+ builder.call(setmethod_fn, [lp, vtable])
+
+
+@intrinsic
+def _list_set_method_table(typingctx, lp, itemty):
+ """Wrap numba_list_set_method_table
+ """
+ resty = types.void
+ sig = resty(lp, itemty)
+
+ def codegen(context, builder, sig, args):
+ _list_codegen_set_method_table(
+ context, builder, args[0], itemty.instance_type)
+
+ return sig, codegen
+
+
+@lower_builtin(operator.is_, types.ListType, types.ListType)
+def list_is(context, builder, sig, args):
+ a_meminfo = _container_get_meminfo(context, builder, sig.args[0], args[0])
+ b_meminfo = _container_get_meminfo(context, builder, sig.args[1], args[1])
+ ma = builder.ptrtoint(a_meminfo, cgutils.intp_t)
+ mb = builder.ptrtoint(b_meminfo, cgutils.intp_t)
+ return builder.icmp_signed('==', ma, mb)
+
+
+def _call_list_free(context, builder, ptr):
+ """Call numba_list_free(ptr)
+ """
+ fnty = ir.FunctionType(
+ ir.VoidType(),
+ [ll_list_type],
+ )
+ free = cgutils.get_or_insert_function(builder.module, fnty,
+ 'numba_list_free')
+ builder.call(free, [ptr])
+
+
+# FIXME: this needs a careful review
+def _imp_dtor(context, module):
+ """Define the dtor for list
+ """
+ llvoidptr = context.get_value_type(types.voidptr)
+ llsize = context.get_value_type(types.uintp)
+ fnty = ir.FunctionType(
+ ir.VoidType(),
+ [llvoidptr, llsize, llvoidptr],
+ )
+ fname = '_numba_list_dtor'
+ fn = cgutils.get_or_insert_function(module, fnty, fname)
+
+ if fn.is_declaration:
+ # Set linkage
+ fn.linkage = 'linkonce_odr'
+ # Define
+ builder = ir.IRBuilder(fn.append_basic_block())
+ lp = builder.bitcast(fn.args[0], ll_list_type.as_pointer())
+ l = builder.load(lp)
+ _call_list_free(context, builder, l)
+ builder.ret_void()
+
+ return fn
+
+
+def new_list(item, allocated=DEFAULT_ALLOCATED):
+ """Construct a new list. (Not implemented in the interpreter yet)
+
+ Parameters
+ ----------
+ item: TypeRef
+ Item type of the new list.
+ allocated: int
+ number of items to pre-allocate
+
+ """
+ # With JIT disabled, ignore all arguments and return a Python list.
+ return list()
+
+
+def _add_meminfo(context, builder, lstruct):
+ alloc_size = context.get_abi_sizeof(
+ context.get_value_type(types.voidptr),
+ )
+ dtor = _imp_dtor(context, builder.module)
+ meminfo = context.nrt.meminfo_alloc_dtor(
+ builder,
+ context.get_constant(types.uintp, alloc_size),
+ dtor,
+ )
+
+ data_pointer = context.nrt.meminfo_data(builder, meminfo)
+ data_pointer = builder.bitcast(data_pointer, ll_list_type.as_pointer())
+ builder.store(lstruct.data, data_pointer)
+ lstruct.meminfo = meminfo
+
+
+@intrinsic
+def _make_list(typingctx, itemty, ptr):
+ """Make a list struct with the given *ptr*
+
+ Parameters
+ ----------
+ itemty: Type
+ Type of the item.
+ ptr : llvm pointer value
+ Points to the list object.
+ """
+ list_ty = types.ListType(itemty.instance_type)
+
+ def codegen(context, builder, signature, args):
+ ptr = args[1]
+ ctor = cgutils.create_struct_proxy(list_ty)
+ lstruct = ctor(context, builder)
+ lstruct.data = ptr
+ _add_meminfo(context, builder, lstruct)
+ return lstruct._getvalue()
+
+ sig = list_ty(itemty, ptr)
+ return sig, codegen
+
+
+def _list_new_codegen(context, builder, itemty, new_size, error_handler):
+ fnty = ir.FunctionType(
+ ll_status,
+ [ll_list_type.as_pointer(), ll_ssize_t, ll_ssize_t],
+ )
+ fn = cgutils.get_or_insert_function(builder.module, fnty, 'numba_list_new')
+ # Determine sizeof item types
+ ll_item = context.get_data_type(itemty)
+ sz_item = context.get_abi_sizeof(ll_item)
+ reflp = cgutils.alloca_once(builder, ll_list_type, zfill=True)
+ status = builder.call(
+ fn,
+ [reflp, ll_ssize_t(sz_item), new_size],
+ )
+ msg = "Failed to allocate list"
+ error_handler(
+ builder,
+ status,
+ msg,
+ )
+ lp = builder.load(reflp)
+ return lp
+
+
+@intrinsic
+def _list_new(typingctx, itemty, allocated):
+ """Wrap numba_list_new.
+
+ Allocate a new list object with zero capacity.
+
+ Parameters
+ ----------
+ itemty: Type
+ Type of the items
+ allocated: int
+ number of items to pre-allocate
+
+ """
+ resty = types.voidptr
+ sig = resty(itemty, allocated)
+
+ def codegen(context, builder, sig, args):
+ error_handler = ErrorHandler(context)
+ return _list_new_codegen(context,
+ builder,
+ itemty.instance_type,
+ args[1],
+ error_handler,
+ )
+
+ return sig, codegen
+
+
+@overload(new_list)
+def impl_new_list(item, allocated=DEFAULT_ALLOCATED):
+ """Creates a new list.
+
+ Parameters
+ ----------
+ item: Numba type
+ type of the list item.
+ allocated: int
+ number of items to pre-allocate
+
+ """
+ if not isinstance(item, Type):
+ raise NumbaTypeError("expecting *item* to be a Numba Type")
+
+ itemty = item
+
+ def imp(item, allocated=DEFAULT_ALLOCATED):
+ if allocated < 0:
+ raise RuntimeError("expecting *allocated* to be >= 0")
+ lp = _list_new(itemty, allocated)
+ _list_set_method_table(lp, itemty)
+ l = _make_list(itemty, lp)
+ return l
+
+ return imp
+
+
+@overload(len)
+def impl_len(l):
+ """len(list)
+ """
+ if isinstance(l, types.ListType):
+ def impl(l):
+ return _list_length(l)
+
+ return impl
+
+
+@intrinsic
+def _list_length(typingctx, l):
+ """Wrap numba_list_length
+
+ Returns the length of the list.
+ """
+ sig = types.intp(l)
+
+ def codegen(context, builder, sig, args):
+ [tl] = sig.args
+ [l] = args
+ fnty = ir.FunctionType(
+ ll_ssize_t,
+ [ll_list_type],
+ )
+ fname = 'numba_list_size_address'
+ fn = cgutils.get_or_insert_function(builder.module, fnty, fname)
+ fn.attributes.add('alwaysinline')
+ fn.attributes.add('readonly')
+ fn.attributes.add('nounwind')
+ lp = _container_get_data(context, builder, tl, l)
+ len_addr = builder.call(fn, [lp,],)
+ ptr = builder.inttoptr(len_addr, cgutils.intp_t.as_pointer())
+ return builder.load(ptr)
+
+ return sig, codegen
+
+
+@overload_method(types.ListType, "_allocated")
+def impl_allocated(l):
+ """list._allocated()
+ """
+ if isinstance(l, types.ListType):
+ def impl(l):
+ return _list_allocated(l)
+
+ return impl
+
+
+@intrinsic
+def _list_allocated(typingctx, l):
+ """Wrap numba_list_allocated
+
+ Returns the allocation of the list.
+ """
+ resty = types.intp
+ sig = resty(l)
+
+ def codegen(context, builder, sig, args):
+ fnty = ir.FunctionType(
+ ll_ssize_t,
+ [ll_list_type],
+ )
+ fn = cgutils.get_or_insert_function(builder.module, fnty,
+ 'numba_list_allocated')
+ [l] = args
+ [tl] = sig.args
+ lp = _container_get_data(context, builder, tl, l)
+ n = builder.call(fn, [lp])
+ return n
+
+ return sig, codegen
+
+
+@overload_method(types.ListType, "_is_mutable")
+def impl_is_mutable(l):
+ """list._is_mutable()"""
+ if isinstance(l, types.ListType):
+ def impl(l):
+ return bool(_list_is_mutable(l))
+
+ return impl
+
+
+@intrinsic
+def _list_is_mutable(typingctx, l):
+ """Wrap numba_list_is_mutable
+
+ Returns the state of the is_mutable member
+ """
+ resty = types.int32
+ sig = resty(l)
+
+ def codegen(context, builder, sig, args):
+ fnty = ir.FunctionType(
+ ll_status,
+ [ll_list_type],
+ )
+ fn = cgutils.get_or_insert_function(builder.module, fnty,
+ 'numba_list_is_mutable')
+ [l] = args
+ [tl] = sig.args
+ lp = _container_get_data(context, builder, tl, l)
+ n = builder.call(fn, [lp])
+ return n
+
+ return sig, codegen
+
+
+@overload_method(types.ListType, "_make_mutable")
+def impl_make_mutable(l):
+ """list._make_mutable()"""
+ if isinstance(l, types.ListType):
+ def impl(l):
+ _list_set_is_mutable(l, 1)
+
+ return impl
+
+
+@overload_method(types.ListType, "_make_immutable")
+def impl_make_immutable(l):
+ """list._make_immutable()"""
+ if isinstance(l, types.ListType):
+ def impl(l):
+ _list_set_is_mutable(l, 0)
+
+ return impl
+
+
+@intrinsic
+def _list_set_is_mutable(typingctx, l, is_mutable):
+ """Wrap numba_list_set_mutable
+
+ Sets the state of the is_mutable member.
+ """
+ resty = types.void
+ sig = resty(l, is_mutable)
+
+ def codegen(context, builder, sig, args):
+ fnty = ir.FunctionType(
+ ir.VoidType(),
+ [ll_list_type, cgutils.intp_t],
+ )
+ fn = cgutils.get_or_insert_function(builder.module, fnty,
+ 'numba_list_set_is_mutable')
+ [l, i] = args
+ [tl, ti] = sig.args
+ lp = _container_get_data(context, builder, tl, l)
+ builder.call(fn, [lp, i])
+
+ return sig, codegen
+
+
+@intrinsic
+def _list_append(typingctx, l, item):
+ """Wrap numba_list_append
+ """
+ resty = types.int32
+ sig = resty(l, l.item_type)
+
+ def codegen(context, builder, sig, args):
+ fnty = ir.FunctionType(
+ ll_status,
+ [ll_list_type, ll_bytes],
+ )
+ [l, item] = args
+ [tl, titem] = sig.args
+ fn = cgutils.get_or_insert_function(builder.module, fnty,
+ 'numba_list_append')
+
+ dm_item = context.data_model_manager[titem]
+
+ data_item = dm_item.as_data(builder, item)
+
+ ptr_item = cgutils.alloca_once_value(builder, data_item)
+
+ lp = _container_get_data(context, builder, tl, l)
+ status = builder.call(
+ fn,
+ [
+ lp,
+ _as_bytes(builder, ptr_item),
+ ],
+ )
+ return status
+
+ return sig, codegen
+
+
+@overload_method(types.ListType, 'append')
+def impl_append(l, item):
+ if not isinstance(l, types.ListType):
+ return
+
+ itemty = l.item_type
+
+ def impl(l, item):
+ casteditem = _cast(item, itemty)
+ status = _list_append(l, casteditem)
+ if status == ListStatus.LIST_OK:
+ return
+ elif status == ListStatus.LIST_ERR_IMMUTABLE:
+ raise ValueError('list is immutable')
+ elif status == ListStatus.LIST_ERR_NO_MEMORY:
+ raise MemoryError('Unable to allocate memory to append item')
+ else:
+ raise RuntimeError('list.append failed unexpectedly')
+
+ if l.is_precise():
+ # Handle the precise case.
+ return impl
+ else:
+ # Handle the imprecise case.
+ l = l.refine(item)
+ # Re-bind the item type to match the arguments.
+ itemty = l.item_type
+ # Create the signature that we wanted this impl to have.
+ sig = typing.signature(types.void, l, itemty)
+ return sig, impl
+
+
+@intrinsic
+def fix_index(tyctx, list_ty, index_ty):
+ sig = types.intp(list_ty, index_ty)
+
+ def codegen(context, builder, sig, args):
+ [list_ty, index_ty] = sig.args
+ [ll_list, ll_idx] = args
+ is_negative = builder.icmp_signed('<', ll_idx,
+ ir.Constant(ll_idx.type, 0))
+ fast_len_sig, length_fn = _list_length._defn(context.typing_context,
+ list_ty)
+ length = length_fn(context, builder, fast_len_sig, (ll_list,))
+ # length is an intp
+ # index can be any sort of int
+ # indexing in general is done with a ssize_t which correlates to an
+ # intp. In llvmlite sext and trunc are guarded to return the value
+ # itself if the types are the same, so there's no need to handle the
+ # "equal widths" case separately. This sexts/truncs the index to the
+ # length type such that `add` works for the wraparound case.
+ st = 'sext' if ll_idx.type.width < length.type.width else 'trunc'
+ op = getattr(builder, st)
+ fixedup_idx = op(ll_idx, length.type)
+ wrapped_index = builder.add(fixedup_idx, length)
+ return builder.select(is_negative, wrapped_index, fixedup_idx)
+ return sig, codegen
+
+
+@register_jitable
+def handle_index(l, index):
+ """Handle index.
+
+ If the index is negative, convert it. If the index is out of range, raise
+ an IndexError.
+ """
+ # convert negative indices to positive ones
+ index = fix_index(l, index)
+ # check that the index is in range
+ if index < 0 or index >= len(l):
+ raise IndexError("list index out of range")
+ return index
+
+
+@register_jitable
+def handle_slice(l, s):
+ """Handle slice.
+
+ Convert a slice object for a given list into a range object that can be
+ used to index the list. Many subtle caveats here, especially if the step is
+ negative.
+ """
+ if len(l) == 0: # ignore slice for empty list
+ return range(0)
+ ll, sa, so, se = len(l), s.start, s.stop, s.step
+ if se > 0:
+ start = max(ll + sa, 0) if s.start < 0 else min(ll, sa)
+ stop = max(ll + so, 0) if so < 0 else min(ll, so)
+ elif se < 0:
+ start = max(ll + sa, -1) if s.start < 0 else min(ll - 1, sa)
+ stop = max(ll + so, -1) if so < 0 else min(ll, so)
+ else:
+ # should be caught earlier, but isn't, so we raise here
+ raise ValueError("slice step cannot be zero")
+ return range(start, stop, s.step)
+
+
+def _gen_getitem(borrowed):
+
+ @intrinsic
+ def impl(typingctx, l_ty, index_ty):
+
+ is_none = isinstance(l_ty.item_type, types.NoneType)
+ if is_none:
+ resty = types.Tuple([types.int32, l_ty.item_type])
+ else:
+ resty = types.Tuple([types.int32, types.Optional(l_ty.item_type)])
+ sig = resty(l_ty, index_ty)
+
+ def codegen(context, builder, sig, args):
+ [tl, tindex] = sig.args
+ [l, index] = args
+ fnty = ir.FunctionType(
+ ll_voidptr_type,
+ [ll_list_type],
+ )
+ fname = 'numba_list_base_ptr'
+ fn = cgutils.get_or_insert_function(builder.module, fnty, fname)
+ fn.attributes.add('alwaysinline')
+ fn.attributes.add('nounwind')
+ fn.attributes.add('readonly')
+
+ lp = _container_get_data(context, builder, tl, l)
+
+ base_ptr = builder.call(
+ fn,
+ [lp,],
+ )
+
+ llty = context.get_data_type(tl.item_type)
+ casted_base_ptr = builder.bitcast(base_ptr, llty.as_pointer())
+
+ item_ptr = cgutils.gep(builder, casted_base_ptr, index)
+
+ if is_none:
+ out = builder.load(item_ptr)
+ else:
+ out = context.make_optional_none(builder, tl.item_type)
+ pout = cgutils.alloca_once_value(builder, out)
+
+ dm_item = context.data_model_manager[tl.item_type]
+ item = dm_item.load_from_data_pointer(builder, item_ptr)
+ if not borrowed:
+ context.nrt.incref(builder, tl.item_type, item)
+
+ if is_none:
+ loaded = item
+ else:
+ loaded = context.make_optional_value(builder, tl.item_type,
+ item)
+ builder.store(loaded, pout)
+
+ out = builder.load(pout)
+ return context.make_tuple(builder, resty, [ll_status(0), out])
+
+ return sig, codegen
+ return impl
+
+
+_list_getitem = _gen_getitem(False)
+_list_getitem_borrowed = _gen_getitem(True)
+
+
+@overload(operator.getitem)
+def impl_getitem(l, index):
+ if not isinstance(l, types.ListType):
+ return
+
+ indexty = INDEXTY
+ itemty = l.item_type
+ IS_NOT_NONE = not isinstance(l.item_type, types.NoneType)
+
+ if index in index_types:
+ if IS_NOT_NONE:
+ def integer_non_none_impl(l, index):
+ castedindex = _cast(index, indexty)
+ handledindex = handle_index(l, castedindex)
+ status, item = _list_getitem(l, handledindex)
+ if status == ListStatus.LIST_OK:
+ return _nonoptional(item)
+ else:
+ raise AssertionError("internal list error during getitem")
+ return integer_non_none_impl
+ else:
+ def integer_none_impl(l, index):
+ index = handle_index(l, index)
+ return None
+ return integer_none_impl
+
+ elif isinstance(index, types.SliceType):
+ def slice_impl(l, index):
+ newl = new_list(itemty)
+ for i in handle_slice(l, index):
+ newl.append(l[i])
+ return newl
+
+ return slice_impl
+
+ else:
+ raise TypingError("list indices must be integers or slices")
+
+
+@intrinsic
+def _list_setitem(typingctx, l, index, item):
+ """Wrap numba_list_setitem
+ """
+ resty = types.int32
+ sig = resty(l, index, item)
+
+ def codegen(context, builder, sig, args):
+ fnty = ir.FunctionType(
+ ll_status,
+ [ll_list_type, ll_ssize_t, ll_bytes],
+ )
+ [l, index, item] = args
+ [tl, tindex, titem] = sig.args
+ fn = cgutils.get_or_insert_function(builder.module, fnty,
+ 'numba_list_setitem')
+
+ dm_item = context.data_model_manager[titem]
+ data_item = dm_item.as_data(builder, item)
+ ptr_item = cgutils.alloca_once_value(builder, data_item)
+
+ lp = _container_get_data(context, builder, tl, l)
+ status = builder.call(
+ fn,
+ [
+ lp,
+ index,
+ _as_bytes(builder, ptr_item),
+ ],
+ )
+ return status
+
+ return sig, codegen
+
+
+@overload(operator.setitem)
+def impl_setitem(l, index, item):
+ if not isinstance(l, types.ListType):
+ return
+
+ indexty = INDEXTY
+ itemty = l.item_type
+
+ if index in index_types:
+ def impl_integer(l, index, item):
+ index = handle_index(l, index)
+ castedindex = _cast(index, indexty)
+ casteditem = _cast(item, itemty)
+ status = _list_setitem(l, castedindex, casteditem)
+ if status == ListStatus.LIST_OK:
+ return
+ elif status == ListStatus.LIST_ERR_IMMUTABLE:
+ raise ValueError("list is immutable")
+ else:
+ raise AssertionError("internal list error during settitem")
+
+ return impl_integer
+
+ elif isinstance(index, types.SliceType):
+ if not isinstance(item, types.IterableType):
+ raise TypingError("can only assign an iterable when using a slice "
+ "with assignment/setitem")
+
+ def impl_slice(l, index, item):
+ if not l._is_mutable():
+ raise ValueError("list is immutable")
+ # special case "a[i:j] = a", need to copy first
+ if l is item:
+ item = item.copy()
+ slice_range = handle_slice(l, index)
+ # non-extended (simple) slices
+ if slice_range.step == 1:
+ # replace
+ if len(item) == len(slice_range):
+ for i, j in zip(slice_range, item):
+ l[i] = j
+ # replace and insert
+ if len(item) > len(slice_range):
+ # do the replaces we can
+ for i, j in zip(slice_range, item[:len(slice_range)]):
+ l[i] = j
+ # insert the remaining ones
+ insert_range = range(slice_range.stop,
+ slice_range.stop +
+ len(item) - len(slice_range))
+ for i, k in zip(insert_range, item[len(slice_range):]):
+ # FIXME: This may be slow. Each insert can incur a
+ # memory copy of one or more items.
+ l.insert(i, k)
+ # replace and delete
+ if len(item) < len(slice_range):
+ # do the replaces we can
+ replace_range = range(slice_range.start,
+ slice_range.start + len(item))
+ for i,j in zip(replace_range, item):
+ l[i] = j
+ # delete remaining ones
+ del l[slice_range.start + len(item):slice_range.stop]
+ # Extended slices
+ else:
+ if len(slice_range) != len(item):
+ raise ValueError("length mismatch for extended slice "
+ "and sequence")
+ # extended slice can only replace
+ for i, j in zip(slice_range, item):
+ l[i] = j
+
+ return impl_slice
+
+ else:
+ raise TypingError("list indices must be integers or slices")
+
+
+@overload_method(types.ListType, 'pop')
+def impl_pop(l, index=-1):
+ if not isinstance(l, types.ListType):
+ return
+
+ _check_for_none_typed(l, 'pop')
+
+ indexty = INDEXTY
+
+ # FIXME: this type check works, but it isn't clear why and if it optimal
+ if (isinstance(index, int)
+ or index in index_types
+ or isinstance(index, types.Omitted)):
+ def impl(l, index=-1):
+ if len(l) == 0:
+ raise IndexError("pop from empty list")
+ cindex = _cast(handle_index(l, index), indexty)
+ item = l[cindex]
+ del l[cindex]
+ return item
+ return impl
+
+ else:
+ raise TypingError("argument for pop must be an integer")
+
+
+@intrinsic
+def _list_delitem(typingctx, l, index):
+ resty = types.int32
+ sig = resty(l, index)
+
+ def codegen(context, builder, sig, args):
+ fnty = ir.FunctionType(
+ ll_status,
+ [ll_list_type, ll_ssize_t],
+ )
+ [tl, tindex] = sig.args
+ [l, index] = args
+ fn = cgutils.get_or_insert_function(builder.module, fnty,
+ 'numba_list_delitem')
+
+ lp = _container_get_data(context, builder, tl, l)
+ status = builder.call(fn, [lp, index])
+ return status
+
+ return sig, codegen
+
+
+@intrinsic
+def _list_delete_slice(typingctx, l, start, stop, step):
+ """Wrap numba_list_delete_slice
+ """
+ resty = types.int32
+ sig = resty(l, start, stop, step)
+
+ def codegen(context, builder, sig, args):
+ fnty = ir.FunctionType(
+ ll_status,
+ [ll_list_type, ll_ssize_t, ll_ssize_t, ll_ssize_t],
+ )
+ [l, start, stop, step] = args
+ [tl, tstart, tstop, tstep] = sig.args
+ fn = cgutils.get_or_insert_function(builder.module, fnty,
+ 'numba_list_delete_slice')
+
+ lp = _container_get_data(context, builder, tl, l)
+ status = builder.call(
+ fn,
+ [
+ lp,
+ start,
+ stop,
+ step,
+ ],
+ )
+ return status
+
+ return sig, codegen
+
+
+@overload(operator.delitem)
+def impl_delitem(l, index):
+ if not isinstance(l, types.ListType):
+ return
+
+ _check_for_none_typed(l, 'delitem')
+
+ if index in index_types:
+ def integer_impl(l, index):
+ cindex = _cast(handle_index(l, index), INDEXTY)
+ status = _list_delitem(l, cindex)
+ if status == ListStatus.LIST_OK:
+ return
+ elif status == ListStatus.LIST_ERR_IMMUTABLE:
+ raise ValueError("list is immutable")
+ else:
+ raise AssertionError("internal list error during delitem")
+ return integer_impl
+
+ elif isinstance(index, types.SliceType):
+ def slice_impl(l, index):
+ slice_range = handle_slice(l, index)
+ status = _list_delete_slice(
+ l,
+ slice_range.start,
+ slice_range.stop,
+ slice_range.step)
+ if status == ListStatus.LIST_ERR_MUTATED:
+ raise ValueError("list is immutable")
+ return slice_impl
+
+ else:
+ raise TypingError("list indices must be integers or slices")
+
+
+@overload(operator.contains)
+def impl_contains(l, item):
+ if not isinstance(l, types.ListType):
+ return
+
+ itemty = l.item_type
+ _check_for_none_typed(l, "__contains__")
+
+ def impl(l, item):
+ casteditem = _cast(item, itemty)
+ for i in l:
+ if i == casteditem:
+ return True
+ else:
+ return False
+ return impl
+
+
+@overload_method(types.ListType, 'count')
+def impl_count(l, item):
+ if not isinstance(l, types.ListType):
+ return
+
+ _check_for_none_typed(l, 'count')
+
+ itemty = l.item_type
+
+ def impl(l, item):
+ casteditem = _cast(item, itemty)
+ total = 0
+ for i in l:
+ if i == casteditem:
+ total += 1
+ return total
+
+ return impl
+
+
+@overload_method(types.ListType, 'extend')
+def impl_extend(l, iterable):
+ if not isinstance(l, types.ListType):
+ return
+ if not isinstance(iterable, types.IterableType):
+ raise TypingError("extend argument must be iterable")
+
+ _check_for_none_typed(l, 'extend')
+
+ def select_impl():
+ if isinstance(iterable, types.ListType):
+ def impl(l, iterable):
+ if not l._is_mutable():
+ raise ValueError("list is immutable")
+ # guard against l.extend(l)
+ if l is iterable:
+ iterable = iterable.copy()
+ for i in iterable:
+ l.append(i)
+
+ return impl
+ else:
+ def impl(l, iterable):
+ for i in iterable:
+ l.append(i)
+
+ return impl
+
+ if l.is_precise():
+ # Handle the precise case.
+ return select_impl()
+ else:
+ # Handle the imprecise case, try to 'guess' the underlying type of the
+ # values in the iterable.
+ if hasattr(iterable, "dtype"): # tuples and arrays
+ ty = iterable.dtype
+ elif hasattr(iterable, "item_type"): # lists
+ ty = iterable.item_type
+ elif hasattr(iterable, "yield_type"): # iterators and generators
+ ty = iterable.yield_type
+ elif isinstance(iterable, types.UnicodeType):
+ ty = iterable
+ else:
+ raise TypingError("unable to extend list, iterable is missing "
+ "either *dtype*, *item_type* or *yield_type*.")
+ l = l.refine(ty)
+ # Create the signature that we wanted this impl to have
+ sig = typing.signature(types.void, l, iterable)
+ return sig, select_impl()
+
+
+@overload_method(types.ListType, 'insert')
+def impl_insert(l, index, item):
+ if not isinstance(l, types.ListType):
+ return
+
+ _check_for_none_typed(l, 'insert')
+ # insert can refine
+ if isinstance(item, NoneType):
+ raise TypingError("method support for List[None] is limited")
+
+ if index in index_types:
+ def impl(l, index, item):
+ # If the index is larger than the size of the list or if the list is
+ # empty, just append.
+ if index >= len(l) or len(l) == 0:
+ l.append(item)
+ # Else, do the insert dance
+ else:
+ # convert negative indices
+ if index < 0:
+ # if the index is still negative after conversion, use 0
+ index = max(len(l) + index, 0)
+ # grow the list by one, make room for item to insert
+ l.append(l[0])
+ # reverse iterate over the list and shift all elements
+ i = len(l) - 1
+ while (i > index):
+ l[i] = l[i - 1]
+ i -= 1
+ # finally, insert the item
+ l[index] = item
+
+ if l.is_precise():
+ # Handle the precise case.
+ return impl
+ else:
+ # Handle the imprecise case
+ l = l.refine(item)
+ # Re-bind the item type to match the arguments.
+ itemty = l.item_type
+ # Create the signature that we wanted this impl to have.
+ sig = typing.signature(types.void, l, INDEXTY, itemty)
+ return sig, impl
+ else:
+ raise TypingError("list insert indices must be integers")
+
+
+@overload_method(types.ListType, 'remove')
+def impl_remove(l, item):
+ if not isinstance(l, types.ListType):
+ return
+
+ _check_for_none_typed(l, 'remove')
+
+ itemty = l.item_type
+
+ def impl(l, item):
+ casteditem = _cast(item, itemty)
+ for i, n in enumerate(l):
+ if casteditem == n:
+ del l[i]
+ return
+ else:
+ raise ValueError("list.remove(x): x not in list")
+
+ return impl
+
+
+@overload_method(types.ListType, 'clear')
+def impl_clear(l):
+ if not isinstance(l, types.ListType):
+ return
+
+ def impl(l):
+ while len(l):
+ del l[-1]
+
+ return impl
+
+
+@overload_method(types.ListType, 'reverse')
+def impl_reverse(l):
+ if not isinstance(l, types.ListType):
+ return
+
+ _check_for_none_typed(l, 'reverse')
+
+ def impl(l):
+ if not l._is_mutable():
+ raise ValueError("list is immutable")
+ front = 0
+ back = len(l) - 1
+ while front < back:
+ l[front], l[back] = l[back], l[front]
+ front += 1
+ back -= 1
+
+ return impl
+
+
+@overload_method(types.ListType, 'copy')
+def impl_copy(l):
+
+ _check_for_none_typed(l, 'copy')
+
+ itemty = l.item_type
+
+ if isinstance(l, types.ListType):
+ def impl(l):
+ newl = new_list(itemty, len(l))
+ for i in l:
+ newl.append(i)
+ return newl
+
+ return impl
+
+
+@overload_method(types.ListType, 'index')
+def impl_index(l, item, start=None, end=None):
+ if not isinstance(l, types.ListType):
+ return
+
+ _check_for_none_typed(l, 'index')
+
+ itemty = l.item_type
+
+ def check_arg(arg, name):
+ if not (arg is None
+ or arg in index_types
+ or isinstance(arg, (types.Omitted, types.NoneType))):
+ raise TypingError("{} argument for index must be an integer"
+ .format(name))
+ check_arg(start, "start")
+ check_arg(end, "end")
+
+ def impl(l, item, start=None, end=None):
+ casteditem = _cast(item, itemty)
+ for i in handle_slice(l, slice(start, end, 1)):
+ if l[i] == casteditem:
+ return i
+ else:
+ raise ValueError("item not in list")
+
+ return impl
+
+
+@overload_method(types.ListType, "sort")
+def ol_list_sort(lst, key=None, reverse=False):
+ # The following is mostly borrowed from listobj.ol_list_sort
+ from numba.typed import List
+
+ listobj._sort_check_key(key)
+ listobj._sort_check_reverse(reverse)
+
+ if cgutils.is_nonelike(key):
+ KEY = False
+ sort_f = listobj.sort_forwards
+ sort_b = listobj.sort_backwards
+ elif isinstance(key, types.Dispatcher):
+ KEY = True
+ sort_f = listobj.arg_sort_forwards
+ sort_b = listobj.arg_sort_backwards
+
+ def impl(lst, key=None, reverse=False):
+ if not lst._is_mutable():
+ raise ValueError("list is immutable")
+ if KEY is True:
+ # There's an unknown refct problem in reflected list.
+ # Using an explicit loop with typedlist somehow "fixed" it.
+ _lst = List()
+ for x in lst:
+ _lst.append(key(x))
+ else:
+ _lst = lst
+ if reverse is False or reverse == 0:
+ tmp = sort_f(_lst)
+ else:
+ tmp = sort_b(_lst)
+ if KEY is True:
+ # There's an unknown refct problem in reflected list.
+ # Using an explicit loop with typedlist somehow "fixed" it.
+ ordered = List()
+ for i in tmp:
+ ordered.append(lst[i])
+ lst[:] = ordered
+ return impl
+
+
+@overload_method(types.ListType, "getitem_unchecked")
+def ol_getitem_unchecked(lst, index):
+ if not isinstance(index, types.Integer):
+ return
+
+ def impl(lst, index):
+ index = fix_index(lst, index)
+ castedindex = _cast(index, types.intp)
+ _, item = _list_getitem(lst, castedindex)
+ return _nonoptional(item)
+ return impl
+
+
+@overload_attribute(types.ListType, '__hash__')
+def ol_list_hash(lst):
+ if not isinstance(lst, types.ListType):
+ return
+ return lambda lst: None
+
+
+@overload_attribute(types.ListType, '_dtype')
+def impl_dtype(l):
+ if not isinstance(l, types.ListType):
+ return
+ dt = l.dtype
+
+ def impl(l):
+ return dt
+
+ return impl
+
+
+def _equals_helper(this, other, OP):
+ if not isinstance(this, types.ListType):
+ return
+ if not isinstance(other, types.ListType):
+ return lambda this, other: False
+
+ this_is_none = isinstance(this.dtype, types.NoneType)
+ other_is_none = isinstance(other.dtype, types.NoneType)
+
+ if this_is_none or other_is_none:
+ def impl_some_none(this, other):
+ def equals(this, other):
+ # Equal if both none-typed and have equal length
+ return bool(this_is_none == other_is_none
+ and len(this) == len(other))
+ return OP(equals(this, other))
+ return impl_some_none
+ else:
+ def impl_not_none(this, other):
+ def equals(this, other):
+ if len(this) != len(other):
+ return False
+ for i in range(len(this)):
+ if this[i] != other[i]:
+ return False
+ else:
+ return True
+ return OP(equals(this, other))
+ return impl_not_none
+
+
+@overload(operator.eq)
+def impl_equals(this, other):
+ return _equals_helper(this, other, operator.truth)
+
+
+@overload(operator.ne)
+def impl_not_equals(this, other):
+ return _equals_helper(this, other, operator.not_)
+
+
+@register_jitable
+def compare_not_none(this, other):
+ """Oldschool (python 2.x) cmp.
+
+ if this < other return -1
+ if this = other return 0
+ if this > other return 1
+ """
+ if len(this) != len(other):
+ return -1 if len(this) < len(other) else 1
+ for i in range(len(this)):
+ this_item, other_item = this[i], other[i]
+ if this_item != other_item:
+ return -1 if this_item < other_item else 1
+ else:
+ return 0
+
+
+@register_jitable
+def compare_some_none(this, other, this_is_none, other_is_none):
+ """Oldschool (python 2.x) cmp for None typed lists.
+
+ if this < other return -1
+ if this = other return 0
+ if this > other return 1
+ """
+ if len(this) != len(other):
+ return -1 if len(this) < len(other) else 1
+ if this_is_none and other_is_none: # both none
+ return 0
+ # to get here there is precisely one none, and if the first is none, by
+ # induction, the second cannot be
+ return -1 if this_is_none else 1
+
+
+def compare_helper(this, other, accepted):
+ if not isinstance(this, types.ListType):
+ return
+ if not isinstance(other, types.ListType):
+ return lambda this, other: False
+
+ this_is_none = isinstance(this.dtype, types.NoneType)
+ other_is_none = isinstance(other.dtype, types.NoneType)
+
+ if this_is_none or other_is_none:
+ def impl(this, other):
+ return compare_some_none(
+ this, other, this_is_none, other_is_none) in accepted
+ else:
+ def impl(this, other):
+ return compare_not_none(this, other) in accepted
+ return impl
+
+
+@overload(operator.lt)
+def impl_less_than(this, other):
+ return compare_helper(this, other, (-1, ))
+
+
+@overload(operator.le)
+def impl_less_than_or_equal(this, other):
+ return compare_helper(this, other, (-1, 0))
+
+
+@overload(operator.gt)
+def impl_greater_than(this, other):
+ return compare_helper(this, other, (1,))
+
+
+@overload(operator.ge)
+def impl_greater_than_or_equal(this, other):
+ return compare_helper(this, other, (0, 1))
+
+
+class ListIterInstance(object):
+
+ def __init__(self, context, builder, iter_type, iter_val):
+ self._context = context
+ self._builder = builder
+ self._iter_ty = iter_type
+ self._list_ty = self._iter_ty.parent
+ self._iter = context.make_helper(builder, iter_type, iter_val)
+
+ @classmethod
+ def from_list(cls, context, builder, iter_type, list_val):
+ self = cls(context, builder, iter_type, None)
+ index = context.get_constant(types.intp, 0)
+ self._iter.index = cgutils.alloca_once_value(builder, index)
+ self._iter.parent = list_val
+ self._iter.size = cls._size_of_list(context, builder, self._list_ty,
+ self._iter.parent)
+ return self
+
+ @classmethod
+ def _size_of_list(cls, context, builder, list_ty, ll_list):
+ tyctx = context.typing_context
+ fnty = tyctx.resolve_value_type(len)
+ sig = fnty.get_call_type(tyctx, (list_ty,), {})
+ impl = context.get_function(fnty, sig)
+ return impl(builder, (ll_list,))
+
+ @property
+ def size(self):
+ tyctx = self._context.typing_context
+ fnty = tyctx.resolve_value_type(len)
+ ty = self._list_ty
+ sig = fnty.get_call_type(tyctx, (ty,), {})
+ impl = self._context.get_function(fnty, sig)
+ return impl(self._builder, (self._iter.parent,))
+
+ @property
+ def value(self):
+ return self._iter._getvalue()
+
+ def getitem(self, index):
+ tyctx = self._context.typing_context
+ ty = self._list_ty
+ sig, fn = _list_getitem_borrowed._defn(tyctx, ty, types.intp)
+
+ statnitem = fn(self._context, self._builder, sig, (self._iter.parent,
+ index))
+ _, item = cgutils.unpack_tuple(self._builder, statnitem)
+ retty = sig.return_type[1]
+ if isinstance(self._list_ty.dtype, types.NoneType):
+ raw_ty = self._list_ty.dtype
+ else:
+ raw_ty = retty.type
+ raw_item = self._context.cast(self._builder, item, retty, raw_ty)
+ return raw_item
+
+ @property
+ def index(self):
+ return self._builder.load(self._iter.index)
+
+ @index.setter
+ def index(self, value):
+ self._builder.store(value, self._iter.index)
+
+
+@lower_builtin('getiter', types.ListType)
+def getiter_list(context, builder, sig, args):
+ inst = ListIterInstance.from_list(context, builder, sig.return_type,
+ args[0])
+ return impl_ret_borrowed(context, builder, sig.return_type, inst.value)
+
+
+@lower_builtin('iternext', types.ListTypeIteratorType)
+@iternext_impl(RefType.BORROWED)
+def iternext_listiter(context, builder, sig, args, result):
+ inst = ListIterInstance(context, builder, sig.args[0], args[0])
+ index = inst.index
+
+ nitems = inst.size # this is current size
+ init_size = inst._iter.size # this is initial size
+
+ # if the current count is different to the initial count, bail, list is
+ # being mutated whilst iterated.
+ is_mutated = builder.icmp_signed('!=', init_size, nitems)
+ with builder.if_then(is_mutated, likely=False):
+ context.call_conv.return_user_exc(
+ builder, RuntimeError, ("list was mutated during iteration",))
+
+ is_valid = builder.icmp_signed('<', index, nitems)
+ result.set_valid(is_valid)
+ with builder.if_then(is_valid):
+ result.yield_(inst.getitem(index))
+ inst.index = builder.add(index, context.get_constant(types.intp, 1))
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/typed/py.typed b/tool_server/.venv/lib/python3.12/site-packages/numba/typed/py.typed
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/typed/typeddict.py b/tool_server/.venv/lib/python3.12/site-packages/numba/typed/typeddict.py
new file mode 100644
index 0000000000000000000000000000000000000000..a542063dcb569c123f6d1ba309846edae8f8e98d
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/typed/typeddict.py
@@ -0,0 +1,417 @@
+"""
+Python wrapper that connects CPython interpreter to the numba dictobject.
+"""
+from collections.abc import MutableMapping, Iterable, Mapping
+from numba.core.types import DictType
+from numba.core.imputils import numba_typeref_ctor
+from numba import njit, typeof
+from numba.core import types, errors, config, cgutils
+from numba.core.extending import (
+ overload,
+ box,
+ unbox,
+ NativeValue,
+ type_callable,
+ overload_classmethod,
+)
+from numba.typed import dictobject
+from numba.core.typing import signature
+
+
+@njit
+def _make_dict(keyty, valty, n_keys=0):
+ return dictobject._as_meminfo(dictobject.new_dict(keyty, valty,
+ n_keys=n_keys))
+
+
+@njit
+def _length(d):
+ return len(d)
+
+
+@njit
+def _setitem(d, key, value):
+ d[key] = value
+
+
+@njit
+def _getitem(d, key):
+ return d[key]
+
+
+@njit
+def _delitem(d, key):
+ del d[key]
+
+
+@njit
+def _contains(d, key):
+ return key in d
+
+
+@njit
+def _get(d, key, default):
+ return d.get(key, default)
+
+
+@njit
+def _setdefault(d, key, default):
+ return d.setdefault(key, default)
+
+
+@njit
+def _iter(d):
+ return list(d.keys())
+
+
+@njit
+def _popitem(d):
+ return d.popitem()
+
+
+@njit
+def _copy(d):
+ return d.copy()
+
+
+def _from_meminfo_ptr(ptr, dicttype):
+ d = Dict(meminfo=ptr, dcttype=dicttype)
+ return d
+
+
+class Dict(MutableMapping):
+ """A typed-dictionary usable in Numba compiled functions.
+
+ Implements the MutableMapping interface.
+ """
+
+ def __new__(cls, dcttype=None, meminfo=None, n_keys=0):
+ if config.DISABLE_JIT:
+ return dict.__new__(dict)
+ else:
+ return object.__new__(cls)
+
+ @classmethod
+ def empty(cls, key_type, value_type, n_keys=0):
+ """Create a new empty Dict with *key_type* and *value_type*
+ as the types for the keys and values of the dictionary respectively.
+
+ Optionally, allocate enough memory to hold *n_keys* without requiring
+ resizes. The default value of 0 returns a dict with minimum size.
+ """
+ if config.DISABLE_JIT:
+ return dict()
+ else:
+ return cls(dcttype=DictType(key_type, value_type), n_keys=n_keys)
+
+ def __init__(self, *args, **kwargs):
+ """
+ For users, the constructor does not take any parameters.
+ The keyword arguments are for internal use only.
+
+ Parameters
+ ----------
+ dcttype : numba.core.types.DictType; keyword-only
+ Used internally for the dictionary type.
+ meminfo : MemInfo; keyword-only
+ Used internally to pass the MemInfo object when boxing.
+ """
+ if kwargs:
+ self._dict_type, self._opaque = self._parse_arg(**kwargs)
+ else:
+ self._dict_type = None
+
+ if args:
+ # CPython checks for at most 1 argument
+ # https://github.com/python/cpython/blob/f215d7cac9a6f9b51ba864e4252686dee4e45d64/Objects/dictobject.c#L2693-L2695
+ _len = len(args)
+ if _len > 1:
+ raise errors.TypingError("Dict expect at most 1 argument, "
+ f"got {_len}")
+
+ # check if argument is iterable
+ arg = args[0]
+ if not isinstance(arg, Iterable):
+ msg = (f"'{type(arg)}' object is not iterable. Supported type "
+ "constructor are Dict() and Dict(iterable)")
+ raise errors.TypingError(msg)
+ elif isinstance(arg, Mapping):
+ raise errors.TypingError("dict(mapping) is not supported")
+
+ for idx, item in enumerate(arg):
+ if len(item) != 2:
+ msg = (f"dictionary update sequence element #{idx} has "
+ f"length {len(item)}; 2 is required")
+ raise ValueError(msg)
+ k, v = item
+ self.__setitem__(k, v)
+
+ def _parse_arg(self, dcttype, meminfo=None, n_keys=0):
+ if not isinstance(dcttype, DictType):
+ raise TypeError('*dcttype* must be a DictType')
+
+ if meminfo is not None:
+ opaque = meminfo
+ else:
+ opaque = _make_dict(dcttype.key_type, dcttype.value_type,
+ n_keys=n_keys)
+ return dcttype, opaque
+
+ @property
+ def _numba_type_(self):
+ if self._dict_type is None:
+ raise TypeError("invalid operation on untyped dictionary")
+ return self._dict_type
+
+ @property
+ def _typed(self):
+ """Returns True if the dictionary is typed.
+ """
+ return self._dict_type is not None
+
+ def _initialise_dict(self, key, value):
+ dcttype = types.DictType(typeof(key), typeof(value))
+ self._dict_type, self._opaque = self._parse_arg(dcttype)
+
+ def __getitem__(self, key):
+ if not self._typed:
+ raise KeyError(key)
+ else:
+ return _getitem(self, key)
+
+ def __setitem__(self, key, value):
+ if not self._typed:
+ self._initialise_dict(key, value)
+ return _setitem(self, key, value)
+
+ def __delitem__(self, key):
+ if not self._typed:
+ raise KeyError(key)
+ _delitem(self, key)
+
+ def __iter__(self):
+ if not self._typed:
+ return iter(())
+ else:
+ return iter(_iter(self))
+
+ def __len__(self):
+ if not self._typed:
+ return 0
+ else:
+ return _length(self)
+
+ def __contains__(self, key):
+ if len(self) == 0:
+ return False
+ else:
+ return _contains(self, key)
+
+ def __str__(self):
+ buf = []
+ for k, v in self.items():
+ buf.append("{}: {}".format(k, v))
+ return '{{{0}}}'.format(', '.join(buf))
+
+ def __repr__(self):
+ body = str(self)
+ prefix = str(self._dict_type)
+ return "{prefix}({body})".format(prefix=prefix, body=body)
+
+ def get(self, key, default=None):
+ if not self._typed:
+ return default
+ return _get(self, key, default)
+
+ def setdefault(self, key, default=None):
+ if not self._typed:
+ if default is not None:
+ self._initialise_dict(key, default)
+ return _setdefault(self, key, default)
+
+ def popitem(self):
+ if len(self) == 0:
+ raise KeyError('dictionary is empty')
+ return _popitem(self)
+
+ def copy(self):
+ return _copy(self)
+
+
+@overload_classmethod(types.DictType, 'empty')
+def typeddict_empty(cls, key_type, value_type, n_keys=0):
+ if cls.instance_type is not DictType:
+ return
+
+ def impl(cls, key_type, value_type, n_keys=0):
+ return dictobject.new_dict(key_type, value_type, n_keys=n_keys)
+
+ return impl
+
+
+@box(types.DictType)
+def box_dicttype(typ, val, c):
+ context = c.context
+ builder = c.builder
+
+ # XXX deduplicate
+ ctor = cgutils.create_struct_proxy(typ)
+ dstruct = ctor(context, builder, value=val)
+ # Returns the plain MemInfo
+ boxed_meminfo = c.box(
+ types.MemInfoPointer(types.voidptr),
+ dstruct.meminfo,
+ )
+
+ modname = c.context.insert_const_string(
+ c.builder.module, 'numba.typed.typeddict',
+ )
+ typeddict_mod = c.pyapi.import_module(modname)
+ fmp_fn = c.pyapi.object_getattr_string(typeddict_mod, '_from_meminfo_ptr')
+
+ dicttype_obj = c.pyapi.unserialize(c.pyapi.serialize_object(typ))
+
+ result_var = builder.alloca(c.pyapi.pyobj)
+ builder.store(cgutils.get_null_value(c.pyapi.pyobj), result_var)
+ with builder.if_then(cgutils.is_not_null(builder, dicttype_obj)):
+ res = c.pyapi.call_function_objargs(
+ fmp_fn, (boxed_meminfo, dicttype_obj),
+ )
+ c.pyapi.decref(fmp_fn)
+ c.pyapi.decref(typeddict_mod)
+ c.pyapi.decref(boxed_meminfo)
+ builder.store(res, result_var)
+ return builder.load(result_var)
+
+
+@unbox(types.DictType)
+def unbox_dicttype(typ, val, c):
+ context = c.context
+
+ # Check that `type(val) is Dict`
+ dict_type = c.pyapi.unserialize(c.pyapi.serialize_object(Dict))
+ valtype = c.pyapi.object_type(val)
+ same_type = c.builder.icmp_unsigned("==", valtype, dict_type)
+
+ with c.builder.if_else(same_type) as (then, orelse):
+ with then:
+ miptr = c.pyapi.object_getattr_string(val, '_opaque')
+
+ mip_type = types.MemInfoPointer(types.voidptr)
+ native = c.unbox(mip_type, miptr)
+
+ mi = native.value
+
+ argtypes = mip_type, typeof(typ)
+
+ def convert(mi, typ):
+ return dictobject._from_meminfo(mi, typ)
+
+ sig = signature(typ, *argtypes)
+ nil_typeref = context.get_constant_null(argtypes[1])
+ args = (mi, nil_typeref)
+ is_error, dctobj = c.pyapi.call_jit_code(convert, sig, args)
+ # decref here because we are stealing a reference.
+ c.context.nrt.decref(c.builder, typ, dctobj)
+
+ c.pyapi.decref(miptr)
+ bb_unboxed = c.builder.basic_block
+
+ with orelse:
+ # Raise error on incorrect type
+ c.pyapi.err_format(
+ "PyExc_TypeError",
+ "can't unbox a %S as a %S",
+ valtype, dict_type,
+ )
+ bb_else = c.builder.basic_block
+
+ # Phi nodes to gather the output
+ dctobj_res = c.builder.phi(dctobj.type)
+ is_error_res = c.builder.phi(is_error.type)
+
+ dctobj_res.add_incoming(dctobj, bb_unboxed)
+ dctobj_res.add_incoming(dctobj.type(None), bb_else)
+
+ is_error_res.add_incoming(is_error, bb_unboxed)
+ is_error_res.add_incoming(cgutils.true_bit, bb_else)
+
+ # cleanup
+ c.pyapi.decref(dict_type)
+ c.pyapi.decref(valtype)
+
+ return NativeValue(dctobj_res, is_error=is_error_res)
+
+
+@type_callable(DictType)
+def typeddict_call(context):
+ """
+ Defines typing logic for ``Dict()`` and ``Dict(iterable)``.
+ Produces Dict[undefined, undefined] or Dict[key, value]
+ """
+ def typer(arg=None):
+ if arg is None:
+ return types.DictType(types.undefined, types.undefined)
+ elif isinstance(arg, types.DictType):
+ return arg
+ elif isinstance(arg, types.Tuple) and len(arg) == 0: # Dict(())
+ msg = "non-precise type 'dict(())'"
+ raise errors.TypingError(msg)
+ elif isinstance(arg, types.IterableType):
+ dtype = arg.iterator_type.yield_type
+ if isinstance(dtype, types.UniTuple):
+ key = value = dtype.key[0]
+ return types.DictType(key, value)
+ elif isinstance(dtype, types.Tuple):
+ key, value = dtype.key
+ return types.DictType(key, value)
+ return typer
+
+
+@overload(numba_typeref_ctor)
+def impl_numba_typeref_ctor(cls, *args):
+ """
+ Defines lowering for ``Dict()`` and ``Dict(iterable)``.
+
+ The type-inferred version of the dictionary ctor.
+
+ Parameters
+ ----------
+ cls : TypeRef
+ Expecting a TypeRef of a precise DictType.
+ args: tuple
+ A tuple that contains a single iterable (optional)
+
+ Returns
+ -------
+ impl : function
+ An implementation suitable for lowering the constructor call.
+
+ See also: `redirect_type_ctor` in numba/cpython/builtins.py
+ """
+ dict_ty = cls.instance_type
+ if not isinstance(dict_ty, types.DictType):
+ return # reject
+ # Ensure the dictionary is precisely typed.
+ if not dict_ty.is_precise():
+ msg = "expecting a precise DictType but got {}".format(dict_ty)
+ raise errors.LoweringError(msg)
+
+ key_type = types.TypeRef(dict_ty.key_type)
+ value_type = types.TypeRef(dict_ty.value_type)
+
+ if args:
+ if isinstance(args[0], types.IterableType):
+ def impl(cls, *args):
+ # Instantiate an empty dict and populate it with values from
+ # the iterable.
+ d = Dict.empty(key_type, value_type)
+ for k, v in args[0]:
+ d[k] = v
+ return d
+ else:
+ def impl(cls, *args):
+ # Simply call .empty() with the key/value types from *cls*
+ return Dict.empty(key_type, value_type)
+
+ return impl
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/typed/typedlist.py b/tool_server/.venv/lib/python3.12/site-packages/numba/typed/typedlist.py
new file mode 100644
index 0000000000000000000000000000000000000000..2c90dabeac43c5728ab2242e5ac75b7ad0e266c2
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/typed/typedlist.py
@@ -0,0 +1,688 @@
+"""
+Python wrapper that connects CPython interpreter to the Numba typed-list.
+
+This is the code that is used when creating typed lists outside of a `@jit`
+context and when returning a typed-list from a `@jit` decorated function. It
+basically a Python class that has a Numba allocated typed-list under the hood
+and uses `@jit` functions to access it. Since it inherits from MutableSequence
+it should really quack like the CPython `list`.
+
+"""
+from collections.abc import MutableSequence
+
+from numba.core.types import ListType
+from numba.core.imputils import numba_typeref_ctor
+from numba.core.dispatcher import Dispatcher
+from numba.core import types, config, cgutils
+from numba import njit, typeof
+from numba.core.extending import (
+ overload,
+ box,
+ unbox,
+ NativeValue,
+ type_callable,
+ overload_classmethod,
+)
+from numba.typed import listobject
+from numba.core.errors import TypingError, LoweringError
+from numba.core.typing.templates import Signature
+import typing as pt
+
+
+Int_or_Slice = pt.Union["pt.SupportsIndex", slice]
+
+
+T_co = pt.TypeVar('T_co', covariant=True)
+
+
+class _Sequence(pt.Protocol[T_co]):
+ def __getitem__(self, i: int) -> T_co:
+ ...
+
+ def __len__(self) -> int:
+ ...
+
+
+DEFAULT_ALLOCATED = listobject.DEFAULT_ALLOCATED
+
+
+@njit
+def _make_list(itemty, allocated=DEFAULT_ALLOCATED):
+ return listobject._as_meminfo(listobject.new_list(itemty,
+ allocated=allocated))
+
+
+@njit
+def _length(l):
+ return len(l)
+
+
+@njit
+def _allocated(l):
+ return l._allocated()
+
+
+@njit
+def _is_mutable(l):
+ return l._is_mutable()
+
+
+@njit
+def _make_mutable(l):
+ return l._make_mutable()
+
+
+@njit
+def _make_immutable(l):
+ return l._make_immutable()
+
+
+@njit
+def _append(l, item):
+ l.append(item)
+
+
+@njit
+def _setitem(l, i, item):
+ l[i] = item
+
+
+@njit
+def _getitem(l, i):
+ return l[i]
+
+
+@njit
+def _contains(l, item):
+ return item in l
+
+
+@njit
+def _count(l, item):
+ return l.count(item)
+
+
+@njit
+def _pop(l, i):
+ return l.pop(i)
+
+
+@njit
+def _delitem(l, i):
+ del l[i]
+
+
+@njit
+def _extend(l, iterable):
+ return l.extend(iterable)
+
+
+@njit
+def _insert(l, i, item):
+ l.insert(i, item)
+
+
+@njit
+def _remove(l, item):
+ l.remove(item)
+
+
+@njit
+def _clear(l):
+ l.clear()
+
+
+@njit
+def _reverse(l):
+ l.reverse()
+
+
+@njit
+def _copy(l):
+ return l.copy()
+
+
+@njit
+def _eq(t, o):
+ return t == o
+
+
+@njit
+def _ne(t, o):
+ return t != o
+
+
+@njit
+def _lt(t, o):
+ return t < o
+
+
+@njit
+def _le(t, o):
+ return t <= o
+
+
+@njit
+def _gt(t, o):
+ return t > o
+
+
+@njit
+def _ge(t, o):
+ return t >= o
+
+
+@njit
+def _index(l, item, start, end):
+ return l.index(item, start, end)
+
+
+@njit
+def _sort(l, key, reverse):
+ return l.sort(key, reverse)
+
+
+def _from_meminfo_ptr(ptr, listtype):
+ return List(meminfo=ptr, lsttype=listtype)
+
+
+T = pt.TypeVar('T')
+T_or_ListT = pt.Union[T, 'List[T]']
+
+
+class List(MutableSequence, pt.Generic[T]):
+ """A typed-list usable in Numba compiled functions.
+
+ Implements the MutableSequence interface.
+ """
+
+ _legal_kwargs = ["lsttype", "meminfo", "allocated"]
+
+ def __new__(cls,
+ *args,
+ lsttype=None,
+ meminfo=None,
+ allocated=DEFAULT_ALLOCATED,
+ **kwargs):
+ if config.DISABLE_JIT:
+ return list(*args, **kwargs)
+ else:
+ return object.__new__(cls)
+
+ @classmethod
+ def empty_list(cls, item_type, allocated=DEFAULT_ALLOCATED):
+ """Create a new empty List.
+
+ Parameters
+ ----------
+ item_type: Numba type
+ type of the list item.
+ allocated: int
+ number of items to pre-allocate
+ """
+ if config.DISABLE_JIT:
+ return list()
+ else:
+ return cls(lsttype=ListType(item_type), allocated=allocated)
+
+ def __init__(self, *args, **kwargs):
+ """
+ For users, the constructor does not take any parameters.
+ The keyword arguments are for internal use only.
+
+ Parameters
+ ----------
+ args: iterable
+ The iterable to initialize the list from
+ lsttype : numba.core.types.ListType; keyword-only
+ Used internally for the list type.
+ meminfo : MemInfo; keyword-only
+ Used internally to pass the MemInfo object when boxing.
+ allocated: int; keyword-only
+ Used internally to pre-allocate space for items
+ """
+ illegal_kwargs = any((kw not in self._legal_kwargs for kw in kwargs))
+ if illegal_kwargs or args and kwargs:
+ raise TypeError("List() takes no keyword arguments")
+ if kwargs:
+ self._list_type, self._opaque = self._parse_arg(**kwargs)
+ else:
+ self._list_type = None
+ if args:
+ if not 0 <= len(args) <= 1:
+ raise TypeError(
+ "List() expected at most 1 argument, got {}"
+ .format(len(args))
+ )
+ iterable = args[0]
+ # Special case Numpy scalars or anything that quacks like a
+ # NumPy Array.
+ if hasattr(iterable, "ndim") and iterable.ndim == 0:
+ self.append(iterable.item())
+ else:
+ try:
+ iter(iterable)
+ except TypeError:
+ raise TypeError("List() argument must be iterable")
+ for i in args[0]:
+ self.append(i)
+
+ def _parse_arg(self, lsttype, meminfo=None, allocated=DEFAULT_ALLOCATED):
+ if not isinstance(lsttype, ListType):
+ raise TypeError('*lsttype* must be a ListType')
+
+ if meminfo is not None:
+ opaque = meminfo
+ else:
+ opaque = _make_list(lsttype.item_type, allocated=allocated)
+ return lsttype, opaque
+
+ @property
+ def _numba_type_(self):
+ if self._list_type is None:
+ raise TypeError("invalid operation on untyped list")
+ return self._list_type
+
+ @property
+ def _typed(self):
+ """Returns True if the list is typed.
+ """
+ return self._list_type is not None
+
+ @property
+ def _dtype(self):
+ if not self._typed:
+ raise RuntimeError("invalid operation on untyped list")
+ return self._list_type.dtype
+
+ def _initialise_list(self, item):
+ lsttype = types.ListType(typeof(item))
+ self._list_type, self._opaque = self._parse_arg(lsttype)
+
+ def __len__(self) -> int:
+ if not self._typed:
+ return 0
+ else:
+ return _length(self)
+
+ def _allocated(self):
+ if not self._typed:
+ return DEFAULT_ALLOCATED
+ else:
+ return _allocated(self)
+
+ def _is_mutable(self):
+ return _is_mutable(self)
+
+ def _make_mutable(self):
+ return _make_mutable(self)
+
+ def _make_immutable(self):
+ return _make_immutable(self)
+
+ def __eq__(self, other):
+ return _eq(self, other)
+
+ def __ne__(self, other):
+ return _ne(self, other)
+
+ def __lt__(self, other):
+ return _lt(self, other)
+
+ def __le__(self, other):
+ return _le(self, other)
+
+ def __gt__(self, other):
+ return _gt(self, other)
+
+ def __ge__(self, other):
+ return _ge(self, other)
+
+ def append(self, item: T) -> None:
+ if not self._typed:
+ self._initialise_list(item)
+ _append(self, item)
+
+ # noqa F811 comments required due to github.com/PyCQA/pyflakes/issues/592
+ # noqa E704 required to follow overload style of using ... in the same line
+ @pt.overload # type: ignore[override]
+ def __setitem__(self, i: int, o: T) -> None: ... # noqa: F811, E704
+ @pt.overload
+ def __setitem__(self, s: slice, o: 'List[T]') -> None: ... # noqa: F811, E704, E501
+
+ def __setitem__(self, i: Int_or_Slice, item: T_or_ListT) -> None: # noqa: F811, E501
+ if not self._typed:
+ self._initialise_list(item)
+ _setitem(self, i, item)
+
+ # noqa F811 comments required due to github.com/PyCQA/pyflakes/issues/592
+ # noqa E704 required to follow overload style of using ... in the same line
+ @pt.overload
+ def __getitem__(self, i: int) -> T: ... # noqa: F811, E704
+ @pt.overload
+ def __getitem__(self, i: slice) -> 'List[T]': ... # noqa: F811, E704
+
+ def __getitem__(self, i: Int_or_Slice) -> T_or_ListT: # noqa: F811
+ if not self._typed:
+ raise IndexError
+ else:
+ return _getitem(self, i)
+
+ def __iter__(self) -> pt.Iterator[T]:
+ for i in range(len(self)):
+ yield self[i]
+
+ def __contains__(self, item: T) -> bool: # type: ignore[override]
+ return _contains(self, item)
+
+ def __delitem__(self, i: Int_or_Slice) -> None:
+ _delitem(self, i)
+
+ def insert(self, i: int, item: T) -> None:
+ if not self._typed:
+ self._initialise_list(item)
+ _insert(self, i, item)
+
+ def count(self, item: T) -> int:
+ return _count(self, item)
+
+ def pop(self, i: "pt.SupportsIndex" = -1) -> T:
+ return _pop(self, i)
+
+ def extend(self, iterable: "_Sequence[T]") -> None: #type: ignore[override]
+ # Empty iterable, do nothing
+ if len(iterable) == 0:
+ return None
+ if not self._typed:
+ # Need to get the first element of the iterable to initialise the
+ # type of the list. FIXME: this may be a problem if the iterable
+ # can not be sliced.
+ self._initialise_list(iterable[0])
+ return _extend(self, iterable)
+
+ def remove(self, item: T) -> None:
+ return _remove(self, item)
+
+ def clear(self):
+ return _clear(self)
+
+ def reverse(self):
+ return _reverse(self)
+
+ def copy(self):
+ return _copy(self)
+
+ def index(self, item: T, start: pt.Optional[int] = None,
+ stop: pt.Optional[int] = None) -> int:
+ return _index(self, item, start, stop)
+
+ def sort(self, key=None, reverse=False):
+ """Sort the list inplace.
+
+ See also ``list.sort()``
+ """
+ # If key is not already a dispatcher object, make it so
+ if callable(key) and not isinstance(key, Dispatcher):
+ key = njit(key)
+ return _sort(self, key, reverse)
+
+ def __str__(self):
+ buf = []
+ for x in self:
+ buf.append("{}".format(x))
+ # Check whether the code was invoked from IPython shell
+ try:
+ get_ipython
+ preview = ', '.join(buf[:1000])
+ suffix = ', ...' if len(buf) > 1000 else ''
+ return '[{0}{1}]'.format(preview, suffix)
+ except (NameError, IndexError):
+ return '[{0}]'.format(', '.join(buf))
+
+ def __repr__(self):
+ body = str(self)
+ prefix = str(self._list_type) if self._typed else "ListType[Undefined]"
+ return "{prefix}({body})".format(prefix=prefix, body=body)
+
+
+@overload_classmethod(ListType, 'empty_list')
+def typedlist_empty(cls, item_type, allocated=DEFAULT_ALLOCATED):
+ if cls.instance_type is not ListType:
+ return
+
+ def impl(cls, item_type, allocated=DEFAULT_ALLOCATED):
+ return listobject.new_list(item_type, allocated=allocated)
+
+ return impl
+
+
+@box(types.ListType)
+def box_lsttype(typ, val, c):
+ context = c.context
+ builder = c.builder
+
+ # XXX deduplicate
+ ctor = cgutils.create_struct_proxy(typ)
+ lstruct = ctor(context, builder, value=val)
+ # Returns the plain MemInfo
+ boxed_meminfo = c.box(
+ types.MemInfoPointer(types.voidptr),
+ lstruct.meminfo,
+ )
+
+ modname = c.context.insert_const_string(
+ c.builder.module, 'numba.typed.typedlist',
+ )
+ typedlist_mod = c.pyapi.import_module(modname)
+ fmp_fn = c.pyapi.object_getattr_string(typedlist_mod, '_from_meminfo_ptr')
+
+ lsttype_obj = c.pyapi.unserialize(c.pyapi.serialize_object(typ))
+
+ result_var = builder.alloca(c.pyapi.pyobj)
+ builder.store(cgutils.get_null_value(c.pyapi.pyobj), result_var)
+
+ with builder.if_then(cgutils.is_not_null(builder, lsttype_obj)):
+ res = c.pyapi.call_function_objargs(
+ fmp_fn, (boxed_meminfo, lsttype_obj),
+ )
+ c.pyapi.decref(fmp_fn)
+ c.pyapi.decref(typedlist_mod)
+ c.pyapi.decref(boxed_meminfo)
+ builder.store(res, result_var)
+ return builder.load(result_var)
+
+
+@unbox(types.ListType)
+def unbox_listtype(typ, val, c):
+ context = c.context
+ builder = c.builder
+
+ # Check that `type(val) is Dict`
+ list_type = c.pyapi.unserialize(c.pyapi.serialize_object(List))
+ valtype = c.pyapi.object_type(val)
+ same_type = builder.icmp_unsigned("==", valtype, list_type)
+
+ with c.builder.if_else(same_type) as (then, orelse):
+ with then:
+ miptr = c.pyapi.object_getattr_string(val, '_opaque')
+
+ native = c.unbox(types.MemInfoPointer(types.voidptr), miptr)
+
+ mi = native.value
+ ctor = cgutils.create_struct_proxy(typ)
+ lstruct = ctor(context, builder)
+
+ data_pointer = context.nrt.meminfo_data(builder, mi)
+ data_pointer = builder.bitcast(
+ data_pointer,
+ listobject.ll_list_type.as_pointer(),
+ )
+
+ lstruct.data = builder.load(data_pointer)
+ lstruct.meminfo = mi
+
+ lstobj = lstruct._getvalue()
+ c.pyapi.decref(miptr)
+ bb_unboxed = c.builder.basic_block
+
+ with orelse:
+ # Raise error on incorrect type
+ c.pyapi.err_format(
+ "PyExc_TypeError",
+ "can't unbox a %S as a %S",
+ valtype, list_type,
+ )
+ bb_else = c.builder.basic_block
+
+ # Phi nodes to gather the output
+ lstobj_res = c.builder.phi(lstobj.type)
+ is_error_res = c.builder.phi(cgutils.bool_t)
+
+ lstobj_res.add_incoming(lstobj, bb_unboxed)
+ lstobj_res.add_incoming(lstobj.type(None), bb_else)
+
+ is_error_res.add_incoming(cgutils.false_bit, bb_unboxed)
+ is_error_res.add_incoming(cgutils.true_bit, bb_else)
+
+ # cleanup
+ c.pyapi.decref(list_type)
+ c.pyapi.decref(valtype)
+
+ return NativeValue(lstobj_res, is_error=is_error_res)
+
+
+#
+# The following contains the logic for the type-inferred constructor
+#
+
+def _guess_dtype(iterable):
+ """Guess the correct dtype of the iterable type. """
+ if not isinstance(iterable, types.IterableType):
+ raise TypingError(
+ "List() argument must be iterable")
+ # Special case for nested NumPy arrays.
+ elif isinstance(iterable, types.Array) and iterable.ndim > 1:
+ return iterable.copy(ndim=iterable.ndim - 1, layout='A')
+ elif hasattr(iterable, "dtype"):
+ return iterable.dtype
+ elif hasattr(iterable, "yield_type"):
+ return iterable.yield_type
+ elif isinstance(iterable, types.UnicodeType):
+ return iterable
+ elif isinstance(iterable, types.DictType):
+ return iterable.key_type
+ else:
+ # This should never happen, since the 'dtype' of any iterable
+ # should have determined above.
+ raise TypingError(
+ "List() argument does not have a suitable dtype")
+
+
+@type_callable(ListType)
+def typedlist_call(context):
+ """Defines typing logic for ``List()`` and ``List(iterable)``.
+
+ If no argument is given, the returned typer types a new typed-list with an
+ undefined item type. If a single argument is given it must be iterable with
+ a guessable 'dtype'. In this case, the typer types a new typed-list with
+ the type set to the 'dtype' of the iterable arg.
+
+ Parameters
+ ----------
+ arg : single iterable (optional)
+ The single optional argument.
+
+ Returns
+ -------
+ typer : function
+ A typer suitable to type constructor calls.
+
+ Raises
+ ------
+ The returned typer raises a TypingError in case of unsuitable arguments.
+
+ """
+
+ class Typer(object):
+
+ def attach_sig(self):
+ from inspect import signature as mypysig
+
+ def mytyper(iterable):
+ pass
+ self.pysig = mypysig(mytyper)
+
+ def __call__(self, *args, **kwargs):
+ if kwargs:
+ raise TypingError(
+ "List() takes no keyword arguments"
+ )
+ elif args:
+ if not 0 <= len(args) <= 1:
+ raise TypingError(
+ "List() expected at most 1 argument, got {}"
+ .format(len(args))
+ )
+ rt = types.ListType(_guess_dtype(args[0]))
+ self.attach_sig()
+ return Signature(rt, args, None, pysig=self.pysig)
+ else:
+ item_type = types.undefined
+ return types.ListType(item_type)
+
+ return Typer()
+
+
+@overload(numba_typeref_ctor)
+def impl_numba_typeref_ctor(cls, *args):
+ """Defines lowering for ``List()`` and ``List(iterable)``.
+
+ This defines the lowering logic to instantiate either an empty typed-list
+ or a typed-list initialised with values from a single iterable argument.
+
+ Parameters
+ ----------
+ cls : TypeRef
+ Expecting a TypeRef of a precise ListType.
+ args: tuple
+ A tuple that contains a single iterable (optional)
+
+ Returns
+ -------
+ impl : function
+ An implementation suitable for lowering the constructor call.
+
+ See also: `redirect_type_ctor` in numba/cpython/bulitins.py
+ """
+ list_ty = cls.instance_type
+ if not isinstance(list_ty, types.ListType):
+ return # reject
+ # Ensure the list is precisely typed.
+ if not list_ty.is_precise():
+ msg = "expecting a precise ListType but got {}".format(list_ty)
+ raise LoweringError(msg)
+
+ item_type = types.TypeRef(list_ty.item_type)
+ if args:
+ # special case 0d Numpy arrays
+ if isinstance(args[0], types.Array) and args[0].ndim == 0:
+ def impl(cls, *args):
+ # Instantiate an empty list and populate it with the single
+ # value from the array.
+ r = List.empty_list(item_type)
+ r.append(args[0].item())
+ return r
+ else:
+ def impl(cls, *args):
+ # Instantiate an empty list and populate it with values from
+ # the iterable.
+ r = List.empty_list(item_type)
+ for i in args[0]:
+ r.append(i)
+ return r
+ else:
+ def impl(cls, *args):
+ # Simply call .empty_list with the item type from *cls*
+ return List.empty_list(item_type)
+
+ return impl
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/typed/typedobjectutils.py b/tool_server/.venv/lib/python3.12/site-packages/numba/typed/typedobjectutils.py
new file mode 100644
index 0000000000000000000000000000000000000000..7bb20488ea55e171b8bb0acca3c49f7b3adf484d
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/typed/typedobjectutils.py
@@ -0,0 +1,200 @@
+""" Common compiler level utilities for typed dict and list. """
+
+import operator
+import warnings
+
+from llvmlite import ir
+
+from numba.core import types, cgutils
+from numba.core import typing
+from numba.core.registry import cpu_target
+from numba.core.typeconv import Conversion
+from numba.core.extending import intrinsic
+from numba.core.errors import (TypingError, NumbaTypeSafetyWarning,
+ NumbaTypeError)
+
+
+def _as_bytes(builder, ptr):
+ """Helper to do (void*)ptr
+ """
+ return builder.bitcast(ptr, cgutils.voidptr_t)
+
+
+@intrinsic
+def _cast(typingctx, val, typ):
+ """Cast *val* to *typ*
+ """
+ def codegen(context, builder, signature, args):
+ [val, typ] = args
+ context.nrt.incref(builder, signature.return_type, val)
+ return val
+ # Using implicit casting in argument types
+ casted = typ.instance_type
+ _sentry_safe_cast(val, casted)
+ sig = casted(casted, typ)
+ return sig, codegen
+
+
+def _sentry_safe_cast(fromty, toty):
+ """Check and raise TypingError if *fromty* cannot be safely cast to *toty*
+ """
+ tyctxt = cpu_target.typing_context
+ fromty, toty = map(types.unliteral, (fromty, toty))
+ by = tyctxt.can_convert(fromty, toty)
+
+ def warn():
+ m = 'unsafe cast from {} to {}. Precision may be lost.'
+ warnings.warn(m.format(fromty, toty),
+ category=NumbaTypeSafetyWarning)
+
+ isint = lambda x: isinstance(x, types.Integer)
+ isflt = lambda x: isinstance(x, types.Float)
+ iscmplx = lambda x: isinstance(x, types.Complex)
+ isdict = lambda x: isinstance(x, types.DictType)
+ # Only check against numeric types.
+ if by is None or by > Conversion.safe:
+ if isint(fromty) and isint(toty):
+ # Accept if both types are ints
+ warn()
+ elif isint(fromty) and isflt(toty):
+ # Accept if ints to floats
+ warn()
+ elif isflt(fromty) and isflt(toty):
+ # Accept if floats to floats
+ warn()
+ elif iscmplx(fromty) and iscmplx(toty):
+ # Accept if complex to complex
+ warn()
+ elif isdict(fromty) and isdict(toty):
+ pass # it's complaining about initial values being different
+ elif not isinstance(toty, types.Number):
+ # Non-numbers
+ warn()
+ else:
+ # Make it a hard error for numeric type that changes domain.
+ m = 'cannot safely cast {} to {}. Please cast explicitly.'
+ raise TypingError(m.format(fromty, toty))
+
+
+def _sentry_safe_cast_default(default, valty):
+ """Similar to _sentry_safe_cast but handle default value.
+ """
+ # Handle default values
+ # TODO: simplify default values; too many possible way to spell None
+ if default is None:
+ return
+ if isinstance(default, (types.Omitted, types.NoneType)):
+ return
+ return _sentry_safe_cast(default, valty)
+
+
+@intrinsic
+def _nonoptional(typingctx, val):
+ """Typing trick to cast Optional[T] to T
+ """
+ if not isinstance(val, types.Optional):
+ raise NumbaTypeError('expected an optional')
+
+ def codegen(context, builder, sig, args):
+ context.nrt.incref(builder, sig.return_type, args[0])
+ return args[0]
+
+ casted = val.type
+ sig = casted(casted)
+ return sig, codegen
+
+
+def _container_get_data(context, builder, container_ty, c):
+ """Helper to get the C list pointer in a numba containers.
+ """
+ ctor = cgutils.create_struct_proxy(container_ty)
+ conatainer_struct = ctor(context, builder, value=c)
+ return conatainer_struct.data
+
+
+def _container_get_meminfo(context, builder, container_ty, c):
+ """Helper to get the meminfo for a container
+ """
+ ctor = cgutils.create_struct_proxy(container_ty)
+ conatainer_struct = ctor(context, builder, value=c)
+ return conatainer_struct.meminfo
+
+
+def _get_incref_decref(context, module, datamodel, container_element_type):
+ assert datamodel.contains_nrt_meminfo()
+
+ fe_type = datamodel.fe_type
+ data_ptr_ty = datamodel.get_data_type().as_pointer()
+ refct_fnty = ir.FunctionType(ir.VoidType(), [data_ptr_ty])
+ incref_fn = cgutils.get_or_insert_function(
+ module, refct_fnty, '.numba_{}.{}_incref'.format(
+ context.fndesc.mangled_name, container_element_type),)
+
+ builder = ir.IRBuilder(incref_fn.append_basic_block())
+ context.nrt.incref(
+ builder, fe_type,
+ datamodel.load_from_data_pointer(builder, incref_fn.args[0]),
+ )
+ builder.ret_void()
+
+ decref_fn = cgutils.get_or_insert_function(
+ module, refct_fnty, name='.numba_{}.{}_decref'.format(
+ context.fndesc.mangled_name, container_element_type),)
+ builder = ir.IRBuilder(decref_fn.append_basic_block())
+ context.nrt.decref(
+ builder, fe_type,
+ datamodel.load_from_data_pointer(builder, decref_fn.args[0]),
+ )
+ builder.ret_void()
+
+ return incref_fn, decref_fn
+
+
+def _get_equal(context, module, datamodel, container_element_type):
+ assert datamodel.contains_nrt_meminfo()
+
+ fe_type = datamodel.fe_type
+ data_ptr_ty = datamodel.get_data_type().as_pointer()
+
+ wrapfnty = context.call_conv.get_function_type(types.int32,
+ [fe_type, fe_type])
+ argtypes = [fe_type, fe_type]
+
+ def build_wrapper(fn):
+ builder = ir.IRBuilder(fn.append_basic_block())
+ args = context.call_conv.decode_arguments(builder, argtypes, fn)
+
+ sig = typing.signature(types.boolean, fe_type, fe_type)
+ op = operator.eq
+ fnop = context.typing_context.resolve_value_type(op)
+ fnop.get_call_type(context.typing_context, sig.args, {})
+ eqfn = context.get_function(fnop, sig)
+ res = eqfn(builder, args)
+ intres = context.cast(builder, res, types.boolean, types.int32)
+ context.call_conv.return_value(builder, intres)
+
+ wrapfn = cgutils.get_or_insert_function(
+ module, wrapfnty, name='.numba_{}.{}_equal.wrap'.format(
+ context.fndesc.mangled_name, container_element_type))
+ build_wrapper(wrapfn)
+
+ equal_fnty = ir.FunctionType(ir.IntType(32), [data_ptr_ty, data_ptr_ty])
+ equal_fn = cgutils.get_or_insert_function(
+ module, equal_fnty, name='.numba_{}.{}_equal'.format(
+ context.fndesc.mangled_name, container_element_type),)
+ builder = ir.IRBuilder(equal_fn.append_basic_block())
+ lhs = datamodel.load_from_data_pointer(builder, equal_fn.args[0])
+ rhs = datamodel.load_from_data_pointer(builder, equal_fn.args[1])
+
+ status, retval = context.call_conv.call_function(
+ builder, wrapfn, types.int32, argtypes, [lhs, rhs],
+ )
+ with builder.if_then(status.is_ok, likely=True):
+ with builder.if_then(status.is_none):
+ builder.ret(context.get_constant(types.int32, 0))
+ retval = context.cast(builder, retval, types.boolean, types.int32)
+ builder.ret(retval)
+ # Error out
+ builder.ret(context.get_constant(types.int32, -1))
+
+ return equal_fn
diff --git a/tool_server/.venv/lib/python3.12/site-packages/numba/types/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/numba/types/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..825cc24401cd83f70f5fa44574a0d1f33553aa23
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/numba/types/__init__.py
@@ -0,0 +1,3 @@
+import sys
+from numba.core.utils import _RedirectSubpackage
+sys.modules[__name__] = _RedirectSubpackage(locals(), "numba.core.types")