diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton-3.6.0.dist-info/INSTALLER b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton-3.6.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton-3.6.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton-3.6.0.dist-info/METADATA b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton-3.6.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..a08929b568d7f1c9e31054b7944a4aa62802974a --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton-3.6.0.dist-info/METADATA @@ -0,0 +1,46 @@ +Metadata-Version: 2.4 +Name: triton +Version: 3.6.0 +Summary: A language and compiler for custom Deep Learning operations +Home-page: https://github.com/triton-lang/triton/ +Author: Philippe Tillet +Author-email: phil@openai.com +Keywords: Compiler,Deep Learning +Classifier: Development Status :: 4 - Beta +Classifier: Intended Audience :: Developers +Classifier: Topic :: Software Development :: Build Tools +Classifier: License :: OSI Approved :: MIT License +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Requires-Python: >=3.10,<3.15 +License-File: LICENSE +Requires-Dist: importlib-metadata; python_version < "3.10" +Provides-Extra: build +Requires-Dist: cmake<4.0,>=3.20; extra == "build" +Requires-Dist: lit; extra == "build" +Provides-Extra: tests +Requires-Dist: autopep8; extra == "tests" +Requires-Dist: isort; extra == "tests" +Requires-Dist: numpy; extra == "tests" +Requires-Dist: pytest; extra == "tests" +Requires-Dist: pytest-forked; extra == "tests" +Requires-Dist: pytest-xdist; extra == "tests" +Requires-Dist: scipy>=1.7.1; extra == "tests" +Requires-Dist: llnl-hatchet; extra == "tests" +Provides-Extra: tutorials +Requires-Dist: matplotlib; extra == "tutorials" +Requires-Dist: pandas; extra == "tutorials" +Requires-Dist: tabulate; extra == "tutorials" +Dynamic: author +Dynamic: author-email +Dynamic: classifier +Dynamic: home-page +Dynamic: keywords +Dynamic: license-file +Dynamic: provides-extra +Dynamic: requires-dist +Dynamic: requires-python +Dynamic: summary diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton-3.6.0.dist-info/RECORD b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton-3.6.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..b8c686f0299dde6ac8c7572e144795eda39e5b85 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton-3.6.0.dist-info/RECORD @@ -0,0 +1,468 @@ +../../../bin/proton,sha256=9kGWY-skHgepyDWNvisL-0Y5WG1IqPulvAdOSPXfnII,219 +../../../bin/proton-viewer,sha256=55s59q0jvmeBJI3lzZIcvFHbnyQn6a7CUgKmcSvDU3k,219 +triton-3.6.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +triton-3.6.0.dist-info/METADATA,sha256=XJBx25sFe-yJzW1_dvYeXyil6NNxf_bIVCDPgBXuAyE,1663 +triton-3.6.0.dist-info/RECORD,, +triton-3.6.0.dist-info/WHEEL,sha256=Obtqci3x5vy5ZivY2BiOH9GHO8-xQ0d4HFhTOtXMNhw,152 +triton-3.6.0.dist-info/entry_points.txt,sha256=js6289FRk18_JLmbNfGsmtKP77D6aYawJOSIHv3X89I,176 +triton-3.6.0.dist-info/licenses/LICENSE,sha256=kmQPuXIi_Qppj_KM4MN4LBcmI_jWxgm1V2NqgPKPuUY,1132 +triton-3.6.0.dist-info/top_level.txt,sha256=WBiIZyv6n9Y7MIh-HPHSv2w1RDk7EFL__7ZgQRrmHYs,7 +triton/FileCheck,sha256=RuSjRod4j3qusHirPi_lw_LUqhFJi_bAVINOUxk-3S0,1087824 +triton/_C/libproton.so,sha256=h28LFUAt0ygMCCUJck5GBhkF5ZVwD2W7zUXiO515kkU,19354728 +triton/_C/libtriton.so,sha256=dUbB1zHe0hXZZHFwnCi1HAJoR28fq9gj0rrrVGoBVno,415012112 +triton/_C/libtriton/linear_layout.pyi,sha256=W6ebLarvNBCOkf2XLyao8r8xkUPCPVe66yV52Fz178k,2054 +triton/__init__.py,sha256=luaBksq13RH6MNXcldVsKc7s2lNHf8Ovjze-4Ca3oCE,1661 +triton/__pycache__/__init__.cpython-310.pyc,, +triton/__pycache__/_filecheck.cpython-310.pyc,, +triton/__pycache__/_internal_testing.cpython-310.pyc,, +triton/__pycache__/_utils.cpython-310.pyc,, +triton/__pycache__/errors.cpython-310.pyc,, +triton/__pycache__/knobs.cpython-310.pyc,, +triton/__pycache__/testing.cpython-310.pyc,, +triton/_filecheck.py,sha256=wUYaN_dlm57TuAWnRVUV4vzALLPyVD2x1o8_VSf05_M,3137 +triton/_internal_testing.py,sha256=o_E1dnddiYl0kh0pSQYTjyUBXjsbRft1EygGgWYGHhk,8800 +triton/_utils.py,sha256=Yx34bOz5Cl-_IQOy0dPQ8L3F_GjX5XHfmnbjrpedk24,3825 +triton/backends/__init__.py,sha256=yL1El3IOc2ovinwBZnqALUlFCDpK7nfTrEv-QwXEeok,2554 +triton/backends/__pycache__/__init__.cpython-310.pyc,, +triton/backends/__pycache__/compiler.cpython-310.pyc,, +triton/backends/__pycache__/driver.cpython-310.pyc,, +triton/backends/amd/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +triton/backends/amd/__pycache__/__init__.cpython-310.pyc,, +triton/backends/amd/__pycache__/compiler.cpython-310.pyc,, +triton/backends/amd/__pycache__/driver.cpython-310.pyc,, +triton/backends/amd/compiler.py,sha256=YlVvkFNJzu1ihvmSb3LO2cXpkIB-B5GHOUXpPKjih9I,22981 +triton/backends/amd/driver.c,sha256=4drnvEqTrPG86P2ErUyBQe299Q1i7MqW--EtkuFkRHk,18123 +triton/backends/amd/driver.py,sha256=j2Vpo1dUUIsn0qcOEDTTPuGfDvnySp6qXk_5mc3fIEQ,32542 +triton/backends/amd/include/hip/amd_detail/amd_channel_descriptor.h,sha256=vtPhkbVsVETTmNsAbxe9ZrAw0x0uehymm14ETYaxKH4,11574 +triton/backends/amd/include/hip/amd_detail/amd_device_functions.h,sha256=TEndX0aKosjoo70nVwMm1fuQZUvnPSejVytf4GfjFn0,31924 +triton/backends/amd/include/hip/amd_detail/amd_hip_atomic.h,sha256=bz1Vxv2ijOY2FODLQ6cDGKVz8rQAeLbgzvSB5idoXww,29043 +triton/backends/amd/include/hip/amd_detail/amd_hip_common.h,sha256=snManECE3JbCl7YYKV3VyUdLTOeszT9zUt2CtNlLQtE,1371 +triton/backends/amd/include/hip/amd_detail/amd_hip_gl_interop.h,sha256=VmiBrEVZcPaPA0I8bJR70gYAps_YkmZrW4uh7VeUR3M,3976 +triton/backends/amd/include/hip/amd_detail/amd_hip_runtime.h,sha256=5RqXP9XdngcwDLfFpR-9IFlTGrwz9npF1_583veVUsg,14276 +triton/backends/amd/include/hip/amd_detail/amd_hip_runtime_pt_api.h,sha256=voQP0IJlaAvPj8YsPGKTR54kx8v2F7RrAabH7lNt1jw,10359 +triton/backends/amd/include/hip/amd_detail/amd_hip_unsafe_atomics.h,sha256=teqqASYBdrZB6cjCWgqPyVJzGNzRHMR1TgvRSC3e3Zc,25567 +triton/backends/amd/include/hip/amd_detail/amd_hip_vector_types.h,sha256=YR8uozOKmRHjZSff9CLfpYKba8zmhYiL8Y8NnYKEoVY,56477 +triton/backends/amd/include/hip/amd_detail/amd_math_functions.h,sha256=WFUwJdsr9otWS7jqQHHTEkEmtgzeiIx7NlVgovTnvv8,3048 +triton/backends/amd/include/hip/amd_detail/amd_surface_functions.h,sha256=9GhglyiG94nDH0CiTmoK7dgCbBnfPtjk6h3QyYw9o8w,18608 +triton/backends/amd/include/hip/amd_detail/amd_warp_functions.h,sha256=o8guSyIFursD0kHy9s56j0iYgAR887N0YPUtAHwp11w,22072 +triton/backends/amd/include/hip/amd_detail/amd_warp_sync_functions.h,sha256=EZVx4RQ0L36iN_JWBOjAjOyoIbEgAUmWTvfOXj-MSiE,30172 +triton/backends/amd/include/hip/amd_detail/device_library_decls.h,sha256=_IKANb9bN46MiU4tsT-ZY3VjT3SRQqL95jgz1ynkho4,7396 +triton/backends/amd/include/hip/amd_detail/hip_assert.h,sha256=GZkGAptK0ZkyDXOEGdu00ys3paNhnnqy48OULLsVyqo,4360 +triton/backends/amd/include/hip/amd_detail/hip_fp16_math_fwd.h,sha256=5u1Z_BWZlZ59jYOvXbWsgsPWO9kQGPH0jNliK5RxtAo,4923 +triton/backends/amd/include/hip/amd_detail/hip_ldg.h,sha256=KAEZb9H4z4DDrkaloMOeWzahiDfI2V6c68vWT3jb5fU,3652 +triton/backends/amd/include/hip/amd_detail/hip_prof_str.h,sha256=P3s3HmKJ_CGUoBDeh1dbGcA6hzgiNIx-ZTxr7WeVECk,738681 +triton/backends/amd/include/hip/amd_detail/hip_runtime_prof.h,sha256=9u5l0FtaYCEKKSYLec2jVcie1edy6xyCcsmlN0Eb2Vs,2696 +triton/backends/amd/include/hip/amd_detail/host_defines.h,sha256=w6H10dznswMgXo6jJBTIvhjOOQGznhgNrHm5R_hMv7U,10131 +triton/backends/amd/include/hip/amd_detail/math_fwd.h,sha256=GgWSJPI_qWGfd50oPIhk95lZiHdkjrpWkTR7ddwpEB4,17219 +triton/backends/amd/include/hip/amd_detail/ockl_image.h,sha256=yzE8YZpmpWJEs-ZpOAGEtDYDm3gEpY02hZVHcpRJf2c,14969 +triton/backends/amd/include/hip/amd_detail/texture_fetch_functions.h,sha256=wOrUmdco-etPqO5QlKlUP0-SpFwUV3w_dfxuPsBCplU,18998 +triton/backends/amd/include/hip/amd_detail/texture_indirect_functions.h,sha256=JWs-5xj-ubwOzNEp6QJI7kuAsqfxKthkwRvOKXTH3qM,23136 +triton/backends/amd/include/hip/channel_descriptor.h,sha256=1tWF4ITCAYKWndpEigF5pwFUwkmYIknaW_ffi4JO8WI,1774 +triton/backends/amd/include/hip/driver_types.h,sha256=0fnfIiFFbBV-jcDY0VRgYnanTDK-0f8cdNhJ4ccTIE8,31339 +triton/backends/amd/include/hip/hip_common.h,sha256=QeUd37rxYiDd4Cfp4OI8O6TwGeG1GC34SOI_9bqgZUU,3430 +triton/backends/amd/include/hip/hip_deprecated.h,sha256=kzTJMz9uKKPDhbYrKdAD1p7XmMPzpr-Uyk1vO37Zsz0,7758 +triton/backends/amd/include/hip/hip_runtime.h,sha256=p_vihvfN-dHeztb7bWY7SJUDFfwyyuyWQ1v3hZnDuvo,2869 +triton/backends/amd/include/hip/hip_runtime_api.h,sha256=8O2BTE-c2Lz4kF81is2jl_-8u4OVuxpllzxbVH7EVcA,444378 +triton/backends/amd/include/hip/hip_texture_types.h,sha256=AhkvjG4cDjf_ZFLg5SsSTfBnXG614PBK1XVPa7irZbk,1237 +triton/backends/amd/include/hip/hip_vector_types.h,sha256=wVhfPuNZ4wNsq2X_fWXrLgWCt6QyXuhkAGFMO5K6IEE,1631 +triton/backends/amd/include/hip/hip_version.h,sha256=8vSeRMzQUJWCVmoy_5zxsQTkWzpd_CNWIIuPUre2w94,408 +triton/backends/amd/include/hip/library_types.h,sha256=2ahq0onhFBlpb3iRf7loed4vqZY8J_vS1BQWqf8yfxE,2433 +triton/backends/amd/include/hip/linker_types.h,sha256=BXq6VlLniYTCzypCz0yWuay2ucZzqxNek7onllpifXs,6691 +triton/backends/amd/include/hip/surface_types.h,sha256=5e3ceH_JBjhxO8c0HiLS7iMBEFGWK1DcjDOQCixsnxU,1953 +triton/backends/amd/include/hip/texture_types.h,sha256=8lyBxvKtY1QFURKN1pK2yngRvAwS2YGgrSDOH6HgTSw,6499 +triton/backends/amd/include/hipblas-common/hipblas-common.h,sha256=nZLH2WYrcDDFefz9a08p2ygP-YaYIOuxUiObGvwXPTs,5450 +triton/backends/amd/include/hsa/amd_hsa_kernel_code.h,sha256=L0ix__VDL7lqpGDTxawLzLLomWrfpezbUIci85Ef-dA,12754 +triton/backends/amd/include/hsa/hsa.h,sha256=8NxQmaFcgSy2zfM89n7DXxOGviIqbQ8FiWz_8WkW5RQ,191415 +triton/backends/amd/include/hsa/hsa_ext_amd.h,sha256=sVr04PILBcYLiyGdFf2UnBMsnZm66WxIU16bTsaerKo,136290 +triton/backends/amd/include/hsa/hsa_ext_image.h,sha256=DFLmv3Z5C00pZ4hrKlAZleDwjXigU7I2IBdKuXS3txw,56383 +triton/backends/amd/include/hsa/hsa_ven_amd_loader.h,sha256=c6cxPAzAox7u6IbFzEkQZfCuRl-Kr39WhY2_w23X1R4,26146 +triton/backends/amd/include/hsa/hsa_ven_amd_pc_sampling.h,sha256=1jQvi96s94-GjOGktmvpqjVRsTGANugOsV6XmgMfivk,18767 +triton/backends/amd/include/roctracer/ext/prof_protocol.h,sha256=6FAcvVD-dNM7uulFs2B-aTxw5xOAWGy6evdD4yUaebA,3849 +triton/backends/amd/include/roctracer/roctracer.h,sha256=B8sHz2DMNprP7EqNWIGwVLY1KQMpxmhfVy4UoR8dzzY,23849 +triton/backends/amd/include/roctracer/roctracer_ext.h,sha256=vLaZ8peAxSy0cwrdEalKnUApkKspfa04iw1Mr_Zcio0,2940 +triton/backends/amd/include/roctracer/roctracer_hip.h,sha256=RCzYuNw1vLR7xK4rb06TtM9TU546UYKHJ83IMHmZEm8,1432 +triton/backends/amd/include/roctracer/roctracer_roctx.h,sha256=gBjBk5vb0l3PbBSQ7V9iFtaM_RzkIDJEW1A_PXBihBM,2014 +triton/backends/amd/include/roctracer/roctx.h,sha256=RhJXUXRhSJ5LRE_1gm7E6-bjEMrfcFBLDLuf3UxAIh8,6717 +triton/backends/amd/lib/asanrtl.bc,sha256=1xv2RlU3WvbdsghHlmhwiHewGM2B5dKts5bERM6S89o,24508 +triton/backends/amd/lib/ockl.bc,sha256=wQKCzkKukIHbu0lyjKUYlhndc7S27xto6L54J0Bn-C0,246124 +triton/backends/amd/lib/ocml.bc,sha256=UPNTXW0gCXUNB-c6orSYwb-mz9_mjUc7zny_vfFza44,205964 +triton/backends/compiler.py,sha256=xdNAO4i1u3KPiseMVRYxmOQYQw8SbIQoksaMtLa6qng,2834 +triton/backends/driver.py,sha256=JcsL7pVHSIM13i1JWvc4KYum1MIPHTeUHcF3UcV6IR4,1802 +triton/backends/nvidia/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +triton/backends/nvidia/__pycache__/__init__.cpython-310.pyc,, +triton/backends/nvidia/__pycache__/compiler.cpython-310.pyc,, +triton/backends/nvidia/__pycache__/driver.cpython-310.pyc,, +triton/backends/nvidia/bin/cuobjdump,sha256=rR0PBpn0ZgNBbrWOe5_fmik-lfkxLJ33_W_aVqbDDUE,569008 +triton/backends/nvidia/bin/nvdisasm,sha256=EIC8kJowIHYf9MeKm3vZtJN725wJeHCcvlI4HeYSofI,5894744 +triton/backends/nvidia/bin/ptxas,sha256=yWCk8jixfVxdPAGtK7wevSxa7MRZy00iO_8QtF-bj8o,31912192 +triton/backends/nvidia/bin/ptxas-blackwell,sha256=mDsOkoOFWXn0LOv9gNQ_m254brhPA_dXC_lBxNOjxGE,34931056 +triton/backends/nvidia/compiler.py,sha256=7qVWmLqwDHJrPR1JWzkLcqY6qo0Wd4GmXqUhLTlNdvY,23589 +triton/backends/nvidia/driver.c,sha256=Q5weiG-p6sc0bXUj0DugpMUqpMm1GOqG2GWbXAfrfck,19555 +triton/backends/nvidia/driver.py,sha256=StS0RAqkpe4VrCOCrninqoApmGwi7CrL0HKpGBDoXpQ,25625 +triton/backends/nvidia/include/Openacc/cupti_openacc.h,sha256=Z0OM5e_hbd3cxdXyn3SCHqBBQawLg4QORnlm57Cr2-M,3513 +triton/backends/nvidia/include/Openmp/cupti_openmp.h,sha256=E1WNmeb_7HaUSmBegtUNe4IV1i7pXeNxgzIlyKn1zrM,3491 +triton/backends/nvidia/include/Openmp/omp-tools.h,sha256=AmuC_xPC7VPu3B-W4PmXuCNufFawhY8PjNXePaQFAOg,37403 +triton/backends/nvidia/include/builtin_types.h,sha256=JxT9Vf2q2snxTBOL9ACzNmYzTWACO2VOVUu1KdFt7_g,3150 +triton/backends/nvidia/include/channel_descriptor.h,sha256=oZIDO1kdexPb9jltUx1AsXAFknvRWAAr1456925Pqig,21846 +triton/backends/nvidia/include/common_functions.h,sha256=22LTZRVcPZzEH6MJda7nNMCvMgIjSTe0OKR7sEQj6kc,3410 +triton/backends/nvidia/include/cooperative_groups.h,sha256=y2cFxa6e-saEFA9aW22ZuTwi0wud7eEHq7XN3v30LT0,60684 +triton/backends/nvidia/include/cooperative_groups/details/async.h,sha256=xsEHCZP3nuEY3l2p8SU2d1226XiXumUvDP_Gyh8PdVY,19122 +triton/backends/nvidia/include/cooperative_groups/details/coalesced_reduce.h,sha256=pBQgFY7i64V87XNATg1UEIQHVNYOItQtHjS5B4yn8pc,4257 +triton/backends/nvidia/include/cooperative_groups/details/coalesced_scan.h,sha256=DfZv5d5W0XJv-tZVhgrIdjLjs6aCx_u0oy1lDIpjo1Q,7314 +triton/backends/nvidia/include/cooperative_groups/details/driver_abi.h,sha256=v-ZUb4UgGKJk6NR2WCWHD3x_42y-togI1urFn70Gi-g,3964 +triton/backends/nvidia/include/cooperative_groups/details/functional.h,sha256=2BV8i8Bidz0kgxuYkJCAbwFxOIZRyzHgG-c_rVKhRzc,8905 +triton/backends/nvidia/include/cooperative_groups/details/helpers.h,sha256=K9jvxnXc5-6Fum1KG4EQKJJrVZ4BhHOSAJbZR4uDL0c,26476 +triton/backends/nvidia/include/cooperative_groups/details/info.h,sha256=FOrp3Ltt4PcbK2fAM5UX9jssFZtj_LqVShzLFcKiSaY,12465 +triton/backends/nvidia/include/cooperative_groups/details/invoke.h,sha256=Osq3K-tZuXHVCMQJ708PjPo-BwMhjhjApO4b0TYLFJg,8616 +triton/backends/nvidia/include/cooperative_groups/details/memory.h,sha256=hES3SfgXIBsj2MFrC_M5COXlOirSBuuhPMAJnWoI92w,5606 +triton/backends/nvidia/include/cooperative_groups/details/partitioning.h,sha256=AQz-TheqX3onqX2RmIUipzYUVB273zhLlHJw_kX9D2U,7153 +triton/backends/nvidia/include/cooperative_groups/details/reduce.h,sha256=MjqMDwT0TyWZk4JWcF3WHw8xtwMqyizA4C3zy7f8ee0,23296 +triton/backends/nvidia/include/cooperative_groups/details/scan.h,sha256=-Ttwb2AfEEY_tsmqJjR2dojkPpoRx387SoqxgvfdBtQ,17166 +triton/backends/nvidia/include/cooperative_groups/details/sync.h,sha256=Ed4K9QrPZi43ddSqZwv1X8NG_CTsXUowSQndoUv82LU,10795 +triton/backends/nvidia/include/cooperative_groups/memcpy_async.h,sha256=erOIHuObdfxRhBWfrXE3wsZF4B2GUuqwzQrsPwKPpbg,2960 +triton/backends/nvidia/include/cooperative_groups/reduce.h,sha256=B0hgDkqM-6ueqTTgb3b34A0RH4vGz8mBf5e2jT1dJ1o,2949 +triton/backends/nvidia/include/cooperative_groups/scan.h,sha256=2EU6T5cWNwftm2B7FicV31PojoI61yo5fHXGRYkGk40,2940 +triton/backends/nvidia/include/crt/common_functions.h,sha256=-U44f4yUGmwDPwd7Q_3Cz5if05xHGPSlAzz5zMylLSQ,13559 +triton/backends/nvidia/include/crt/cudacc_ext.h,sha256=KW6n0ImOZKS0VqVmBHWTXtHI816hh88YeEgUg2aYdVU,3224 +triton/backends/nvidia/include/crt/device_double_functions.h,sha256=A1vB3g0qwnNEfcpT1d9RiGDaxqPXXgYr-Vxe2oMHyxY,39938 +triton/backends/nvidia/include/crt/device_double_functions.hpp,sha256=YYIbqYhb5Qmf8c4YfcC_jytg4FRwcXPjv3TFTwhb24E,8568 +triton/backends/nvidia/include/crt/device_fp128_functions.h,sha256=3iCKrdmPp1NIjrlGR47dCZOgV9X6MmdfmjugrF6DEts,51047 +triton/backends/nvidia/include/crt/device_functions.h,sha256=T4INuRBIlLmd3JEA8H6B5XHVANGV6j8gwyUTj5h_F18,137919 +triton/backends/nvidia/include/crt/device_functions.hpp,sha256=OVHiqBjday_aUFnDKJxTeI0VDZI8ZA6JIdUKeAKR4pA,37991 +triton/backends/nvidia/include/crt/func_macro.h,sha256=EOpDlaM917bh9cwBiFBPF689DCMBw5hFarxLxFt-i74,1755 +triton/backends/nvidia/include/crt/host_config.h,sha256=1eki3w5xuY00gIkdYbmSfZO2SoI8giZWYSTRIL2uFs0,12169 +triton/backends/nvidia/include/crt/host_defines.h,sha256=fDU_0cQdtIvEdM0zZFKY0OboMANEMgHLblifPalPGLk,10102 +triton/backends/nvidia/include/crt/host_runtime.h,sha256=lOpmkxFZVkEp8dcMAGEZRITsh-19o9jy39kdSNLc3Ng,10284 +triton/backends/nvidia/include/crt/math_functions.h,sha256=LyGJ0XUthi6WEi-YVITInha9A6SFoB4fEUUU9zii7U8,238284 +triton/backends/nvidia/include/crt/math_functions.hpp,sha256=u-CGbd0R2FZWdKG-6bdmGSor9KT_wnmISj63lPQKASM,100207 +triton/backends/nvidia/include/crt/mma.h,sha256=BooWALDWATvZupJaL7-GFQRQYOotNe_Fy11I5NGh2FA,62695 +triton/backends/nvidia/include/crt/mma.hpp,sha256=spo0LX71tUCipxK517Bssj0nc-ZHf8oMWzvHoYYB_6I,66599 +triton/backends/nvidia/include/crt/nvfunctional,sha256=FDM0zqWO6bl9jpJKz9U8CMbjt6iTKh18tQalxAvRsag,16900 +triton/backends/nvidia/include/crt/sm_100_rt.h,sha256=3cBiCU11OcjGYpr85edCN1q4m2z91FaGhBtuO0is4To,8987 +triton/backends/nvidia/include/crt/sm_100_rt.hpp,sha256=vbI2CNCY08dDI7zXwp6BNceZKl0ceXG1lveq4w-VNao,6855 +triton/backends/nvidia/include/crt/sm_70_rt.h,sha256=Kf830xymA-zmF7LsunFHLSNyhhT5UiJMocgoHBQeNns,6837 +triton/backends/nvidia/include/crt/sm_70_rt.hpp,sha256=3a_rU-Y0MSB4htBDFY4PCQ_jXiWFTe7WT1ZyhMuCJOA,7837 +triton/backends/nvidia/include/crt/sm_80_rt.h,sha256=MdJHWCRzLM__nDDf1go61rDsl9ydOW3oi6SZBfjUyc8,7743 +triton/backends/nvidia/include/crt/sm_80_rt.hpp,sha256=o-rJu-jpehCeyABGgv-8dYRB7oJTCwuNdvSCq0VURdE,6705 +triton/backends/nvidia/include/crt/sm_90_rt.h,sha256=an47m0XFBaJ3pUX9MlE4-nktP1jb3eJUXhQ3ntZtzc8,11445 +triton/backends/nvidia/include/crt/sm_90_rt.hpp,sha256=YuqVygGV6rgtWtx1J9cPpEI3BXKQBII-Ez6oZFP3wrE,9228 +triton/backends/nvidia/include/crt/storage_class.h,sha256=dzcOZ16pLaN8ejqHaXw4iHbBJ6fXWxfaU-sj2QjYzzg,4791 +triton/backends/nvidia/include/cuComplex.h,sha256=WpcgpaiPhU_o9sTPMcNTEZuyXDIc8x3sz4dUWSztL2g,12186 +triton/backends/nvidia/include/cuda.h,sha256=RWjMnnoyHkdwfNZAOYDyGsLi5VFwUA0OCj9U_rA6mss,1156988 +triton/backends/nvidia/include/cudaEGL.h,sha256=iruZU9xSGAcJ29OEX4K_Uo1o4NGP9hggv2fiOZOfDQo,39955 +triton/backends/nvidia/include/cudaEGLTypedefs.h,sha256=xF_FAN1Kar9oyHJ3cCU7jztTpxX8WylpiuYyYpGGHek,5645 +triton/backends/nvidia/include/cudaGL.h,sha256=gMT1HPGa-siuji0gAsKYr4X45Lc29HKglC_ttNSGyUM,22501 +triton/backends/nvidia/include/cudaGLTypedefs.h,sha256=dClpQI-LuXgF9rPSBsj7OkIg8g_fXDjT0hLZS8TGpOg,6576 +triton/backends/nvidia/include/cudaProfilerTypedefs.h,sha256=F2aWLIKv_AhNbxNOaZVcRsxIh0kuscnV8UMWWxkBAlY,3297 +triton/backends/nvidia/include/cudaTypedefs.h,sha256=SKfAvTOj19zxsiLGKhoxXPiopKqoe5hjj5iXkR2_v6E,115169 +triton/backends/nvidia/include/cudaVDPAU.h,sha256=Np7Nc2Wjaz--hkpbhW6f9aapr-NbcPDAgkot0sJerco,12694 +triton/backends/nvidia/include/cudaVDPAUTypedefs.h,sha256=wz8nyOUdwM9mH9JO3QZW-A9dyxt-IufSX7nggSXpCNs,4144 +triton/backends/nvidia/include/cuda_awbarrier.h,sha256=3ZH-ZlXODhSiwSY9rqSni_EQwi25QMHP6Tm-zOdxBwE,9340 +triton/backends/nvidia/include/cuda_awbarrier_helpers.h,sha256=OCskCts5bCKl_RKBe9M74zKSIsVpePn44S_aJp1tFXE,12489 +triton/backends/nvidia/include/cuda_awbarrier_primitives.h,sha256=n5__E1jYYDhlgH-f3u8MQjtz57UZ7v5VshhMye1eicM,4699 +triton/backends/nvidia/include/cuda_bf16.h,sha256=TVoq2IrbF5g67wUF7W7SoGA0l8ecEDu6gskoMB6hIxA,204512 +triton/backends/nvidia/include/cuda_bf16.hpp,sha256=OukWXoN6bgRlC-p8CFbhUN0G0uAJb_zos1mCPagscnI,136544 +triton/backends/nvidia/include/cuda_device_runtime_api.h,sha256=54l66QbwerX0wPKoJC2y7qCdGP8nv1_GgdmMV8A0x4k,46986 +triton/backends/nvidia/include/cuda_egl_interop.h,sha256=awWBBEYvUFM7AURNp2mND8H7_5kGQLRswRveXYBy-3s,37509 +triton/backends/nvidia/include/cuda_fp16.h,sha256=jrFgCo4uM9QFcr_-cAGif2BGp0lJ2ANT_gLPiLJWPdo,206851 +triton/backends/nvidia/include/cuda_fp16.hpp,sha256=o1ITDmuN67N8YUGUcvTpV3IdpS-6wwlm65M_H-8LYKs,120927 +triton/backends/nvidia/include/cuda_fp4.h,sha256=pTEQf5rLfiaU_UMXgnnsS13NH5H9FtHgdeiNuW_NkHY,13823 +triton/backends/nvidia/include/cuda_fp4.hpp,sha256=YYaUu-YRgYdj9xYu4ZDh_uPVffxkDlEr0CD_bhlF8BE,35423 +triton/backends/nvidia/include/cuda_fp6.h,sha256=6xh0E4SNmjmJZD3H5_HoZe08bQ0loUE8y3cbO19-Ad4,13963 +triton/backends/nvidia/include/cuda_fp6.hpp,sha256=qa838buZeLP32xBVqbo71uFSW5RnBWx9qp5D-SR_xc0,56455 +triton/backends/nvidia/include/cuda_fp8.h,sha256=QSTMRb9l7I9mnvT1_8KXNqLO48wWaWEgG97bDjEh1ic,18072 +triton/backends/nvidia/include/cuda_fp8.hpp,sha256=6AABZPfPlK-jmQyMdbTEE0PZTlULjuLOrsQ0Z_cubBw,97230 +triton/backends/nvidia/include/cuda_gl_interop.h,sha256=VQEswFeOBF6JN6Q0pdlkvc5WT7bD1FnTfKewvANulCc,19150 +triton/backends/nvidia/include/cuda_occupancy.h,sha256=0HavrMIWXGxIujaq72iX31-73Zprx0WBYdiln3ZNP2w,71302 +triton/backends/nvidia/include/cuda_pipeline.h,sha256=0enXG49wN4JajlQi3ahbp2ei_ufTY_Mznic7zfWmKHM,8130 +triton/backends/nvidia/include/cuda_pipeline_helpers.h,sha256=bo1L7e6vCuM-K3Il8K1z4wJUja5DyXQKdo_hSWUME-E,13852 +triton/backends/nvidia/include/cuda_pipeline_primitives.h,sha256=FnJJtuV6rHr6LgL56XDwilcSbFr6W1Hj6mf1AJaMI20,8675 +triton/backends/nvidia/include/cuda_runtime.h,sha256=GqqE7SrECGrN-Qg5Dk90LSjs-xvKlHZpRLlpH7LUehM,98570 +triton/backends/nvidia/include/cuda_runtime_api.h,sha256=EWhSESFT_vV5eYZpTBEu4EvgNtE9rhmHP503XnIGHIs,655943 +triton/backends/nvidia/include/cuda_stdint.h,sha256=XbFOk9CtJjKqk7PpYNqbSVsDxAsVM8avA4rWpPi0BjQ,4093 +triton/backends/nvidia/include/cuda_surface_types.h,sha256=Mw5Lo4b8Q-f9mogOvATGyHhu9d2t2K6XOxuqtZrSh3A,3688 +triton/backends/nvidia/include/cuda_texture_types.h,sha256=ITbX-JNnP7Rm-JSgNVdJ9pq6k8FVor8RbnruDsKq6sk,3688 +triton/backends/nvidia/include/cuda_vdpau_interop.h,sha256=bXQanWc2IFXZAKWNGl2xAz9nLvFmQpWyGrsDvfeS9FA,7727 +triton/backends/nvidia/include/cudart_platform.h,sha256=YN6sKhB0b9w5tGX1IYL7ulJVPrWAiX9A44qLv4EtW5Q,2717 +triton/backends/nvidia/include/cupti.h,sha256=JkVyAGTIMYzwm62dfVqas3nMcILhgP_Wdz6fh4_NED0,4697 +triton/backends/nvidia/include/cupti_activity.h,sha256=gJKGlG2JifW36Lx-ujJcKBlnUrNOoTxar51k28GrUtU,229848 +triton/backends/nvidia/include/cupti_activity_deprecated.h,sha256=B0p4zbll2vUn1j0ImTG6QIbpp6Hiw8y-X021Zmf7flE,137602 +triton/backends/nvidia/include/cupti_callbacks.h,sha256=aZ-SE0YMFfT9R-Uh5MHboPg0ypHMjeSSAJw3zdP7OCs,29689 +triton/backends/nvidia/include/cupti_checkpoint.h,sha256=rTz8JoWxqESBXyZWUhZJGm4xeYcx4OJOtJ7Ld13T_b0,5264 +triton/backends/nvidia/include/cupti_common.h,sha256=85m74bxUgXp3tEaPQpezeazmpsNMw41PsjNSYmQdT20,3514 +triton/backends/nvidia/include/cupti_driver_cbid.h,sha256=mkBNPYkLfcExhQZFDo0iYHlaHJWGD2vOMdtzaV-lEUk,77280 +triton/backends/nvidia/include/cupti_events.h,sha256=81wcvFvvHj8RmECbbEp5FfgjJIQDoC_81FhvqznFupY,51923 +triton/backends/nvidia/include/cupti_metrics.h,sha256=zmfZxq5VkUJp6Tj7oXEkP9oycRNw1zB9VNhoQlbhiN4,32175 +triton/backends/nvidia/include/cupti_nvtx_cbid.h,sha256=_azPtR1g4qivvX7qbvHRUg0RHCWF7iEOJyHMN9qZe9E,5912 +triton/backends/nvidia/include/cupti_pcsampling.h,sha256=ycJHT36DmPIaVzHsB3xxjXkhFyEfMCJOl3LbCsHFgyA,32144 +triton/backends/nvidia/include/cupti_pcsampling_util.h,sha256=lx8CaNXowJe5Zvc06LE-u_Zry_jODs1mM6j9Q5WIX9E,12430 +triton/backends/nvidia/include/cupti_pmsampling.h,sha256=U95hKOwIkZSbGNVP11QSmMawB8qdJsljY_tUJY4vedc,20440 +triton/backends/nvidia/include/cupti_profiler_host.h,sha256=MkkfXlKBRrRL4NfaPFiuE4D4z_gpmxiBWWTBixyyMTk,22155 +triton/backends/nvidia/include/cupti_profiler_target.h,sha256=MdLutIefwdMTI7wsce0LO3NuCm3FRgFR3GxAkqadMs4,32294 +triton/backends/nvidia/include/cupti_range_profiler.h,sha256=ue5bUA-3xCwAtQGyDe5O1d5rAmRbVbcrXKfITd4xM1I,18779 +triton/backends/nvidia/include/cupti_result.h,sha256=xQqBsZRoicBSWdk1lZAE_WeZj88MLH6ClTo58oshx-8,13114 +triton/backends/nvidia/include/cupti_runtime_cbid.h,sha256=BZJnzsvf2RjRlHKEhPjCk0CdjLI9_L-nClTwe4v9NUc,48372 +triton/backends/nvidia/include/cupti_sass_metrics.h,sha256=3RW9snJuFQdOhrEn3wDJOru05q0V_zssWrqD7tvVJKw,19674 +triton/backends/nvidia/include/cupti_target.h,sha256=x4Vz1Upb6m9ixmVpmGaKQldDWYQI3OZ-ocEXGzNK0EE,1263 +triton/backends/nvidia/include/cupti_version.h,sha256=KFXmjB4o-iZGvO8la9Sf9Urg4q4srmEimnxbPCyd2N8,4506 +triton/backends/nvidia/include/device_atomic_functions.h,sha256=OR2jNSfSKzaFri74zh4Vtz5M0z9UDBU3rKeC1rYaVQs,9500 +triton/backends/nvidia/include/device_atomic_functions.hpp,sha256=0e7MOiNNUnnloXpB_r9WT5YOws5cxgzQQAzRCYvgaFA,10486 +triton/backends/nvidia/include/device_double_functions.h,sha256=KUxId5Z1fx8SWfLRTxPD7RB-zN7zslzb4n7JaJLfL3I,3452 +triton/backends/nvidia/include/device_functions.h,sha256=bWSrhTYE9NQlss7xMSMEVusvto9j2fgUDXWVH2W_cOA,3410 +triton/backends/nvidia/include/device_launch_parameters.h,sha256=H1_CC-vvAaS26ys4XsTFkMgTxUTciAjdjswjizkisvQ,3846 +triton/backends/nvidia/include/device_types.h,sha256=2LFxoZBJPoA5V0H1EbKTEaXDi3GDJPtzOPdRHDaucIQ,3588 +triton/backends/nvidia/include/driver_functions.h,sha256=cN3IjRAz2Mj2Pj35SyxJIkZNDDusnJqaqzBdMzpQKbA,4625 +triton/backends/nvidia/include/driver_types.h,sha256=mMNbiIwg5E3k7Sk685YCSvnKYmfQ3bxWv3bkEgzOtNU,200083 +triton/backends/nvidia/include/fatbinary_section.h,sha256=NnuUfy358yGJx4enq0pBnetjv17UWa-nOlgYToUitrw,1809 +triton/backends/nvidia/include/generated_cudaGL_meta.h,sha256=dfd2QuaRdEjbStOKvaQLi1Md_qrpRQh8PfyZznJ8bWY,3115 +triton/backends/nvidia/include/generated_cudaVDPAU_meta.h,sha256=fAedsoQxaU3hIAApAWDOKsa9kgcuQw4tdyf8klLm-3k,1453 +triton/backends/nvidia/include/generated_cuda_gl_interop_meta.h,sha256=LXOqvQCej0sCgAT1LUKKYZ466EFxN4hIwf9oIhXOLF0,2250 +triton/backends/nvidia/include/generated_cuda_meta.h,sha256=DDdgfW84GVtsGbr7daNJchmmZDS_xfvDHvFCm3I1OEc,98664 +triton/backends/nvidia/include/generated_cuda_runtime_api_meta.h,sha256=CuziaDwO2Mh33paCLGKqi73PQfYNmzp38wYrhAK-fng,72208 +triton/backends/nvidia/include/generated_cuda_vdpau_interop_meta.h,sha256=8OLqWN26aEYpTWUXtbHJvA5GYhVv3ybYVOTW7yK37z8,1367 +triton/backends/nvidia/include/generated_cudart_removed_meta.h,sha256=X3I5WXmhtsJNNlgY7coJ5vg4t11G5FRR6Xo7MboIeck,5172 +triton/backends/nvidia/include/generated_nvtx_meta.h,sha256=YHb_RD8g3s4m8PJn7Z0wnxvUHarl7BOAX5ADr-BL3HI,7513 +triton/backends/nvidia/include/host_config.h,sha256=BscH_GazAZbbotddVzL5RmafbQ-QjRx8f-I1O01IBW8,3380 +triton/backends/nvidia/include/host_defines.h,sha256=bBQwQF5C1N1c2qpLV56g1c-weu9Ysgz-gIf2Kn3uz_A,3386 +triton/backends/nvidia/include/library_types.h,sha256=i-GFcw92wvcixs2bQjOj4I_q26HYY_VY4DpDvHWQCjY,5156 +triton/backends/nvidia/include/math_constants.h,sha256=cV6hAyQe8X7f7MBtaKjjIJq3BycOUDp6I5cizJX5HLw,7608 +triton/backends/nvidia/include/math_functions.h,sha256=5XcC6j-fJKttvhwc4hZNoLHNw808a2ZYIOtZ7ry7yd0,3398 +triton/backends/nvidia/include/mma.h,sha256=IY_VenxuEncwGq92MhrWUb-Xswh0ekAXLy9Rbxhxa2Y,2932 +triton/backends/nvidia/include/nvPTXCompiler.h,sha256=lF1ssKlrjsNWCsp0UdhbB6GyOgFCDO1q0ZBDzOswlj0,14471 +triton/backends/nvidia/include/nvfunctional,sha256=IkFoCi_Q4OhP9nEuBI-5jWwFlR_PfG05hJH7lSMsfWc,2975 +triton/backends/nvidia/include/nvperf_common.h,sha256=ykeTJ5I6c0z8KqMQh13hlJaMaHiqqVUB60oGXOCu7Bg,17255 +triton/backends/nvidia/include/nvperf_cuda_host.h,sha256=gC0JWoUdTyAOJs8y4uoJIhie9Xq4yF4HzoumLsYNVzU,7562 +triton/backends/nvidia/include/nvperf_host.h,sha256=wCB4mR8aIHWiqT1TsxztQgWBRh_yiq5ABFm8sb3_jwg,49197 +triton/backends/nvidia/include/nvperf_target.h,sha256=jRqQtuNLTrCzPDdyeANkTrPEijSCTjLy2A1qjKu0SdM,23607 +triton/backends/nvidia/include/sm_20_atomic_functions.h,sha256=x4ycINVq__l9B4SQPD-I48jQbKxxdBmgp8Vf2GO0Qfg,4478 +triton/backends/nvidia/include/sm_20_atomic_functions.hpp,sha256=1l5NLM8DhDbqYZ_E51LoqElQJXObkbwo57d3r-4uEbE,4107 +triton/backends/nvidia/include/sm_20_intrinsics.h,sha256=axeDr7y6nT1V6LzrSWNSaHUwXgiNjPbXn1T6Uh7hlNM,57702 +triton/backends/nvidia/include/sm_20_intrinsics.hpp,sha256=mJTejRhw1prNiP_ax1OPbkYlhEqBqO4nVI3DRDXIzpo,8392 +triton/backends/nvidia/include/sm_30_intrinsics.h,sha256=b6W8Vxp9vD9OCJI6lZuGyZYXEdQ3Ei8PTAloHNkwCcQ,16978 +triton/backends/nvidia/include/sm_30_intrinsics.hpp,sha256=yX0ebd265tJ-BDhvluP2BhadPuWXpRZPI2eeQFFt5ys,24567 +triton/backends/nvidia/include/sm_32_atomic_functions.h,sha256=HGnZgQHACE2AAb6zabGUURc53IsVZelc2BSJqvs9OgY,5703 +triton/backends/nvidia/include/sm_32_atomic_functions.hpp,sha256=CQTTvOEYp-s5hqAgLvAon11vLYDrDp8cTHdel-XRzBQ,6592 +triton/backends/nvidia/include/sm_32_intrinsics.h,sha256=Xdkogdsjy1vh8u3eGu0i5xTmHxBGAjj6_vVGR-spdOE,33539 +triton/backends/nvidia/include/sm_32_intrinsics.hpp,sha256=Gl8aSLDLcit4W3pKQS19GsDG8RYcwD65HwYB_CeZe8M,70616 +triton/backends/nvidia/include/sm_35_atomic_functions.h,sha256=a3XoEsKRCEOf0Q_5Y__rMfmC4pScv4VkUggVgVJVn44,2909 +triton/backends/nvidia/include/sm_35_intrinsics.h,sha256=0mS5-LCgvZiTvL7-MG_4YwI-zWGvM-s4xyRuMkunMC8,2664 +triton/backends/nvidia/include/sm_60_atomic_functions.h,sha256=_anfNaJsvQpDEorYeUKIkbizYkwrinBcG_ZCiECtLqI,13178 +triton/backends/nvidia/include/sm_60_atomic_functions.hpp,sha256=cgIKddDn2B3QzYlzeBILAP1IRys74QCCxsH0QqaVGls,22903 +triton/backends/nvidia/include/sm_61_intrinsics.h,sha256=h_MBL1UUDxQX_qOddSImzqyFjcrhhm_63G97pGDyreU,10902 +triton/backends/nvidia/include/sm_61_intrinsics.hpp,sha256=N-nQvcBsPMT2Umy5zR69c9K1q366W-Jqe7NpoLTqTmg,6787 +triton/backends/nvidia/include/surface_functions.h,sha256=b1O82SAvEgWWxA9uZTWQcGimzZUoem2QbAET3wh3fZc,6782 +triton/backends/nvidia/include/surface_indirect_functions.h,sha256=vy9QuFVV-ezZP-x2RT9RLp2qIUgdngACOCmalSfVFPA,10877 +triton/backends/nvidia/include/surface_types.h,sha256=XkFXD1nHbeSMgajR-UJE9uQ7TByzJnjdnUL4-yGiufk,4530 +triton/backends/nvidia/include/texture_fetch_functions.h,sha256=KLCmUxf5aY5_UalX8tSFB6e4TrjA8hyUPxLOkMFltAo,12468 +triton/backends/nvidia/include/texture_indirect_functions.h,sha256=lH_y3Ni-hq4RZ0_PMFbBM0th5-OmTn3TtqtpkHHhA8w,21163 +triton/backends/nvidia/include/texture_types.h,sha256=73ntVyg8r8fzKy5VIk6yuvC45GDeWepaLIqIk-M3Ri8,6360 +triton/backends/nvidia/include/vector_functions.h,sha256=WypGkL-IDbGOlay7g_G0p3HO7OLGRE0Do__JtiFoWxY,8003 +triton/backends/nvidia/include/vector_functions.hpp,sha256=afXhNSd3LFTZo96EPtesTLfvxd4nTmLVzgkj967rTRg,10060 +triton/backends/nvidia/include/vector_types.h,sha256=6CJ4yt3KD7zQVfm1NhrgqNYYEDEIZWwaivlFx12nhNg,13396 +triton/backends/nvidia/lib/cupti/libcheckpoint.so,sha256=BrqCvQkje5NM8W2iFy7VlDxYLKo1x5tSz8_rD_cfclA,1644872 +triton/backends/nvidia/lib/cupti/libcupti.so,sha256=_M3F_MfDL4z0s-2bF_fxh6GFpvoKW8wG40NMvRaHyAg,7595792 +triton/backends/nvidia/lib/cupti/libcupti.so.12,sha256=_M3F_MfDL4z0s-2bF_fxh6GFpvoKW8wG40NMvRaHyAg,7595792 +triton/backends/nvidia/lib/cupti/libcupti.so.2025.1.1,sha256=_M3F_MfDL4z0s-2bF_fxh6GFpvoKW8wG40NMvRaHyAg,7595792 +triton/backends/nvidia/lib/cupti/libcupti_static.a,sha256=q22dskj52HUn40wsJ6-5g9AFD_aYtOSqIlNJrbRqOko,43563448 +triton/backends/nvidia/lib/cupti/libnvperf_host.so,sha256=YJ9UBjwlPa_277p5_kklL90jJDCKsP-5kcwSXT6aHqs,25825936 +triton/backends/nvidia/lib/cupti/libnvperf_host_static.a,sha256=sTLoX5YG81JXBoSKm3fLo0RAdP3HqISmgtx8L47XF-4,33480030 +triton/backends/nvidia/lib/cupti/libnvperf_target.so,sha256=LxDhEJ_DQaV0NMKOQAa0WokkeAHiD1rOE1wwLBc-B3A,5275312 +triton/backends/nvidia/lib/cupti/libpcsamplingutil.so,sha256=5vongwd5dPsnZb-py66_mAc233Tuv5lMWcdZaYiuyDs,970064 +triton/backends/nvidia/lib/libdevice.10.bc,sha256=XC-uN8huaMOjhgWpX1EtfRLV89uYYxC-R_VzBKpype4,473728 +triton/compiler/__init__.py,sha256=S0iIXHTRJL8MUqThupDtPyJVT0PA882c2dN5VwqOGxE,284 +triton/compiler/__pycache__/__init__.cpython-310.pyc,, +triton/compiler/__pycache__/code_generator.cpython-310.pyc,, +triton/compiler/__pycache__/compiler.cpython-310.pyc,, +triton/compiler/__pycache__/errors.cpython-310.pyc,, +triton/compiler/__pycache__/make_launcher.cpython-310.pyc,, +triton/compiler/code_generator.py,sha256=yLgvcMg60QvAGQ-meGQ0i4lfcz1nZYo77K8TdGGY93g,72793 +triton/compiler/compiler.py,sha256=KgY7t5CXd9NlmUUkQnfpANn3z8Nd6adYV4Rp7kuQ_Ok,20548 +triton/compiler/errors.py,sha256=I9Y15pDWcL9heY4SWWdLeMDtW6Iiq2pFXzKfJ6dY_C0,1732 +triton/compiler/make_launcher.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +triton/errors.py,sha256=8WfnuRKLG578mgY6cBA3ECruVMf9ULEKFNgRcJ6IhWM,89 +triton/experimental/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +triton/experimental/__pycache__/__init__.cpython-310.pyc,, +triton/experimental/gluon/__init__.py,sha256=lcSGCgXqtSNqQxDuZhP4s7BStqgb81AULbtKY_nEjv4,211 +triton/experimental/gluon/__pycache__/__init__.cpython-310.pyc,, +triton/experimental/gluon/__pycache__/_compiler.cpython-310.pyc,, +triton/experimental/gluon/__pycache__/_runtime.cpython-310.pyc,, +triton/experimental/gluon/_compiler.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +triton/experimental/gluon/_runtime.py,sha256=AVoWQuzXSKD02gZLAzbZ6iHw4uccf0rH-KpWVH-7ceI,3461 +triton/experimental/gluon/amd/__init__.py,sha256=s4d3xgEuuCxSAA-0whosZP1av9RpDfiJjq-73B8mdlc,45 +triton/experimental/gluon/amd/__pycache__/__init__.cpython-310.pyc,, +triton/experimental/gluon/amd/__pycache__/gfx1250.cpython-310.pyc,, +triton/experimental/gluon/amd/gfx1250.py,sha256=vltp7sQ3yydl42yTaK9wLt_inGtkVoVLblxzHuPp5rU,2005 +triton/experimental/gluon/language/__init__.py,sha256=EWaK8cYuu82grq_CZtrIskXSYmLoojjHcGZKiep1Xto,2056 +triton/experimental/gluon/language/__pycache__/__init__.cpython-310.pyc,, +triton/experimental/gluon/language/__pycache__/_core.cpython-310.pyc,, +triton/experimental/gluon/language/__pycache__/_layouts.cpython-310.pyc,, +triton/experimental/gluon/language/__pycache__/_math.cpython-310.pyc,, +triton/experimental/gluon/language/__pycache__/_semantic.cpython-310.pyc,, +triton/experimental/gluon/language/__pycache__/_standard.cpython-310.pyc,, +triton/experimental/gluon/language/_core.py,sha256=rfN2Wi6cHc5YmL5Q6ZUQAfJARYSAcu6LEODopT_0jeA,19736 +triton/experimental/gluon/language/_layouts.py,sha256=mvf1zlM_ADn3TdUQS9atvRb0oGuxXq3ltwihI-l-P4w,24444 +triton/experimental/gluon/language/_math.py,sha256=MN9Fvt8FaQTpxEUCKhw83IGbkwBD2Whdp686av4vv04,564 +triton/experimental/gluon/language/_semantic.py,sha256=JGrIMOK0U_Og3NDDJJ4TJsB51Cuh49I47hzZ6GleQlk,28303 +triton/experimental/gluon/language/_standard.py,sha256=378S3ehrgIBfyhIHD4vzyaEf-3OIBNURMHgtQg4Oou8,2765 +triton/experimental/gluon/language/amd/__init__.py,sha256=80NUK1RoDQdRMbwJIqK79asQadcCI5rD2TlO3-H9F8o,220 +triton/experimental/gluon/language/amd/__pycache__/__init__.cpython-310.pyc,, +triton/experimental/gluon/language/amd/__pycache__/_layouts.cpython-310.pyc,, +triton/experimental/gluon/language/amd/__pycache__/_ops.cpython-310.pyc,, +triton/experimental/gluon/language/amd/_layouts.py,sha256=i6S0zl-8ZpR6Ns6YKNPOiVPLB-FWwZr_QtQY2aDjgKs,7244 +triton/experimental/gluon/language/amd/_ops.py,sha256=l5PInTbyrBIp3IkGAoQj7IVLNz8fD6JAsq8936Q-2js,3373 +triton/experimental/gluon/language/amd/cdna3/__init__.py,sha256=DVt8NOVa6LY08fapFqrYoMNXYON90iVx_b9_8VVEx1o,10397 +triton/experimental/gluon/language/amd/cdna3/__pycache__/__init__.cpython-310.pyc,, +triton/experimental/gluon/language/amd/cdna4/__init__.py,sha256=0e7PtofvZc1Ye5lXoCL-KdFez-TDbj5mtUue3ffH4os,5163 +triton/experimental/gluon/language/amd/cdna4/__pycache__/__init__.cpython-310.pyc,, +triton/experimental/gluon/language/amd/cdna4/__pycache__/async_copy.cpython-310.pyc,, +triton/experimental/gluon/language/amd/cdna4/async_copy.py,sha256=5U-g1PxqJAbYdv_YZZ3g0z8C94WkoZ35gPGqZCe6JJg,7994 +triton/experimental/gluon/language/amd/gfx1250/__init__.py,sha256=PXAxGE6lou0tKUS6zEA99x0eGPkJzHRaJg5cMDDB-j4,3622 +triton/experimental/gluon/language/amd/gfx1250/__pycache__/__init__.cpython-310.pyc,, +triton/experimental/gluon/language/amd/gfx1250/__pycache__/async_copy.cpython-310.pyc,, +triton/experimental/gluon/language/amd/gfx1250/__pycache__/mbarrier.cpython-310.pyc,, +triton/experimental/gluon/language/amd/gfx1250/__pycache__/tdm.cpython-310.pyc,, +triton/experimental/gluon/language/amd/gfx1250/async_copy.py,sha256=XiVdff5KahNi7vR0YJBRvA7wUhfo9kRttU_W9sA52B0,2589 +triton/experimental/gluon/language/amd/gfx1250/mbarrier.py,sha256=i1AbMgNiCdJDMJTI5iHtCRIECX0qD8g3s5c6jrqeCZg,2631 +triton/experimental/gluon/language/amd/gfx1250/tdm.py,sha256=MR55lnc_Am4kGTMFqYP8W6xy0sguTRUBjlKj9KjhaDQ,7383 +triton/experimental/gluon/language/amd/rdna3/__init__.py,sha256=J9a-Pw7Y86qewAvjahhG1UU3QDHKwOMVlSZeW0SiaIU,419 +triton/experimental/gluon/language/amd/rdna3/__pycache__/__init__.cpython-310.pyc,, +triton/experimental/gluon/language/amd/rdna4/__init__.py,sha256=s5_7PQYh0m1YZN9NPr_eDYckIr-jrPDobsVl3DU9jJM,419 +triton/experimental/gluon/language/amd/rdna4/__pycache__/__init__.cpython-310.pyc,, +triton/experimental/gluon/language/extra/__init__.py,sha256=FaDqvKRb8M8K47C3YceyfF3ZiZayLC8xZN248jNlxeQ,69 +triton/experimental/gluon/language/extra/__pycache__/__init__.cpython-310.pyc,, +triton/experimental/gluon/language/nvidia/__init__.py,sha256=SFBuACK5P2XoYcutHEnKjqgRTboU4CPDmJz0hT6dFRQ,80 +triton/experimental/gluon/language/nvidia/__pycache__/__init__.cpython-310.pyc,, +triton/experimental/gluon/language/nvidia/ampere/__init__.py,sha256=TZtb8V4yjN_ee7R5BPTbp7Qx7fPeYcaJBgl6EPlH0eU,1605 +triton/experimental/gluon/language/nvidia/ampere/__pycache__/__init__.cpython-310.pyc,, +triton/experimental/gluon/language/nvidia/ampere/__pycache__/async_copy.cpython-310.pyc,, +triton/experimental/gluon/language/nvidia/ampere/__pycache__/mbarrier.cpython-310.pyc,, +triton/experimental/gluon/language/nvidia/ampere/async_copy.py,sha256=YfB0AN1hcEKWU2WTyef4ggWtp-HBnoSHJGoWhUTMmis,2817 +triton/experimental/gluon/language/nvidia/ampere/mbarrier.py,sha256=UznWgajIlkZzk3Jf0T_elJR9f8BUX-y2qJ1Ee_pqv7Q,2455 +triton/experimental/gluon/language/nvidia/blackwell/__init__.py,sha256=KlGdHEU7KugJ8xBwkACEUui4UKvqk9pKtMI0Wqp8VOI,17858 +triton/experimental/gluon/language/nvidia/blackwell/__pycache__/__init__.cpython-310.pyc,, +triton/experimental/gluon/language/nvidia/blackwell/__pycache__/float2.cpython-310.pyc,, +triton/experimental/gluon/language/nvidia/blackwell/__pycache__/tma.cpython-310.pyc,, +triton/experimental/gluon/language/nvidia/blackwell/float2.py,sha256=WoFL-wMhsBTgHXyJhvjhbEOhF1NeiPdYOeardZGkWdM,3926 +triton/experimental/gluon/language/nvidia/blackwell/tma.py,sha256=wlBEA-dfP6zhz-5TBFTH9xVN0vePt2vlXEBj9z37d7g,2065 +triton/experimental/gluon/language/nvidia/hopper/__init__.py,sha256=6GVGQn67Di7YA5uH4Pu6iOS66S3P20fltFOKYvl4MZY,5369 +triton/experimental/gluon/language/nvidia/hopper/__pycache__/__init__.cpython-310.pyc,, +triton/experimental/gluon/language/nvidia/hopper/__pycache__/mbarrier.cpython-310.pyc,, +triton/experimental/gluon/language/nvidia/hopper/__pycache__/tma.cpython-310.pyc,, +triton/experimental/gluon/language/nvidia/hopper/mbarrier.py,sha256=NF2dvXMKWzQ0mtWZQpCWKJKZzkINCZ24d8cKdqDT60Q,1339 +triton/experimental/gluon/language/nvidia/hopper/tma.py,sha256=QRIK0Gb_QI3Al0ra4chyTK8xFFCWBoEkYxQjDyI_Uxc,6463 +triton/experimental/gluon/nvidia/__init__.py,sha256=ISXB4RV7RcCLsU-JhcRFeA29gCBDVk8cTwO2j99ivLc,80 +triton/experimental/gluon/nvidia/__pycache__/__init__.cpython-310.pyc,, +triton/experimental/gluon/nvidia/__pycache__/blackwell.cpython-310.pyc,, +triton/experimental/gluon/nvidia/__pycache__/hopper.cpython-310.pyc,, +triton/experimental/gluon/nvidia/blackwell.py,sha256=cllwlUCE5_YKWqySQZk7wt7Fierz345E5VwztxNRGMs,69 +triton/experimental/gluon/nvidia/hopper.py,sha256=sGuSjjCjuKaefhW-tBcyQZUNCum-7-7TwmG0gy0h8X8,1925 +triton/instrumentation/libGPUInstrumentationTestLib.so,sha256=0rA-19tttn3X5AQ92ztC1_Y1HsMijAAwrNmAGrRxn_M,6526160 +triton/instrumentation/libPrintLoadStoreMemSpaces.so,sha256=02KBRgFQRYYk4YV1ELLY1ijPec2DOLcuj_ABrjN8LgY,9017144 +triton/knobs.py,sha256=2EvaZk9zPwVH-fQ5fC2rEdofnFj5dKhAo_HGHqSMdvo,17262 +triton/language/__init__.py,sha256=WOurIQ31Sk6pYA0FbEnUNrKkPgIxO_OdmQ1sT9SSdyg,6986 +triton/language/__pycache__/__init__.cpython-310.pyc,, +triton/language/__pycache__/core.cpython-310.pyc,, +triton/language/__pycache__/math.cpython-310.pyc,, +triton/language/__pycache__/random.cpython-310.pyc,, +triton/language/__pycache__/semantic.cpython-310.pyc,, +triton/language/__pycache__/standard.cpython-310.pyc,, +triton/language/__pycache__/target_info.cpython-310.pyc,, +triton/language/core.py,sha256=k5TGAHHqC7ymwpDESlo3G4tKAmg9Up3rw74EQB2T4Zg,123101 +triton/language/extra/__init__.py,sha256=XRXFvr7416pRsh_Rh-X6qV66SiEyVDVbxp4GSAE1mfc,655 +triton/language/extra/__pycache__/__init__.cpython-310.pyc,, +triton/language/extra/__pycache__/libdevice.cpython-310.pyc,, +triton/language/extra/cuda/__init__.py,sha256=MBBu2EUYxsp6ygjiwO4Yh1X1EswMstfaiRTMSMGtbcw,407 +triton/language/extra/cuda/__pycache__/__init__.cpython-310.pyc,, +triton/language/extra/cuda/__pycache__/gdc.cpython-310.pyc,, +triton/language/extra/cuda/__pycache__/libdevice.cpython-310.pyc,, +triton/language/extra/cuda/__pycache__/utils.cpython-310.pyc,, +triton/language/extra/cuda/gdc.py,sha256=rbVOcdD_w72sQ3-8l5KXafu-Tr0D5jYcY1fyok98WVQ,2193 +triton/language/extra/cuda/libdevice.py,sha256=J7Kl0ejbAIus7-YBn2OSK71lkm3pC7G1J-5ZdHfS82U,56764 +triton/language/extra/cuda/utils.py,sha256=phDcXCFViaq3p4ThwHrO8-FtU-8A8I3nk4mZZJVvTio,4426 +triton/language/extra/hip/__init__.py,sha256=GFcuM-R0qCB5kDbysvjD5U2KUmOGNWcWzM8r8yqDI3Y,96 +triton/language/extra/hip/__pycache__/__init__.cpython-310.pyc,, +triton/language/extra/hip/__pycache__/libdevice.cpython-310.pyc,, +triton/language/extra/hip/__pycache__/utils.cpython-310.pyc,, +triton/language/extra/hip/libdevice.py,sha256=LNynTEKXgE3PSZp-nUMVq4ft_i1y9Tao_cAvKKPn2s0,17542 +triton/language/extra/hip/utils.py,sha256=tTq-k0c-s32IvDeGkgZcmosb9UtkF8sZEaE9EJGMbSA,877 +triton/language/extra/libdevice.py,sha256=9gwrstjuvhwZH0uLgZhEQU3RvOJDZFY1oJT5-SZlpY4,6350 +triton/language/math.py,sha256=CKvuIc5iMKhz7Qgx9w-VcLfOOZadv5svKK4aGZLuHMc,7399 +triton/language/random.py,sha256=9EpDURuXQg6CQ4dG0XMNtq6jEmGQMgd2h_s2_-I3J7o,7116 +triton/language/semantic.py,sha256=vjQp9tBpoi3cLKBI2A4WFt-F3lGksOHiDjBUJkpY8fg,101212 +triton/language/standard.py,sha256=Gip7Fwb-mWWd2Gsp1jl9YD19DP70-Cf-kCpJRyjM3cE,16041 +triton/language/target_info.py,sha256=UwWJDDsTPe9E4vPTQF4Psf1s540KKLISdnChlbvhHGY,1364 +triton/profiler/__init__.py,sha256=b0XtXi8lPkxUEhD9DHkS9Rzi2JvWj57RbakLGui1jA8,284 +triton/profiler/__pycache__/__init__.cpython-310.pyc,, +triton/profiler/__pycache__/context.cpython-310.pyc,, +triton/profiler/__pycache__/flags.cpython-310.pyc,, +triton/profiler/__pycache__/language.cpython-310.pyc,, +triton/profiler/__pycache__/mode.cpython-310.pyc,, +triton/profiler/__pycache__/profile.cpython-310.pyc,, +triton/profiler/__pycache__/proton.cpython-310.pyc,, +triton/profiler/__pycache__/scope.cpython-310.pyc,, +triton/profiler/__pycache__/specs.cpython-310.pyc,, +triton/profiler/__pycache__/state.cpython-310.pyc,, +triton/profiler/__pycache__/viewer.cpython-310.pyc,, +triton/profiler/context.py,sha256=JGQ1C2bPwpPvva3eITd8RxEgWcmvAkxAuB1mlKz9Jo0,506 +triton/profiler/flags.py,sha256=5GBc3Oi-d9mWY0Sq3hAadARmv4TDNtAZ64hTO5vkoag,663 +triton/profiler/hooks/__init__.py,sha256=qwb8ypLQ0oOFA3h9M3RtU1OhJR_wd2EZTKJ2pFNHeuo,123 +triton/profiler/hooks/__pycache__/__init__.cpython-310.pyc,, +triton/profiler/hooks/__pycache__/hook.cpython-310.pyc,, +triton/profiler/hooks/__pycache__/instrumentation.cpython-310.pyc,, +triton/profiler/hooks/__pycache__/launch.cpython-310.pyc,, +triton/profiler/hooks/hook.py,sha256=7x5SI016VKj5a8t3LsO8tnFRR8OVN-p8E0aE_6VQnlo,4793 +triton/profiler/hooks/instrumentation.py,sha256=2oYy9FXGU478a0zVxWWcU9ZSuIVzDfLA5JyIg0_HJOU,14849 +triton/profiler/hooks/launch.py,sha256=PTKrBs85fGT-19soqcPg0DtefAYEi95T8BCEXdktOQU,1493 +triton/profiler/language.py,sha256=u3JSs5YHQOS2uBZ-jEb2yDEo6iyuLmkTZKgLQlyOvl4,2116 +triton/profiler/mode.py,sha256=-7P8jeG7SiEUOmBuAfQWv3nzTvmsHJBvgYUh-FJXD4Y,4367 +triton/profiler/profile.py,sha256=wYXUmmEVpUEjdtdDWyp4r3FUnjjsx7Gz3m1eRxO6Jsg,8823 +triton/profiler/proton.py,sha256=9SI06y225SFh-VrPwfDoU2B78Cy4GpWe1vGlMDOY32Y,3086 +triton/profiler/scope.py,sha256=3GrGLominS6TjdfAJJyc1Gqgo0Nh--A0avskGDxwmls,3831 +triton/profiler/specs.py,sha256=3v554WIsHHREMFxofDSMEQz18i0g0W_MJZKh6Op3nqM,2341 +triton/profiler/state.py,sha256=SyXdwGYvKdpAOfFpW3OU0MVklnhPXHAX9yoIbvb26wA,1335 +triton/profiler/viewer.py,sha256=zvnpPQbUfKyfyYDqr7wKKLgFAVJhSswxqHE_W_taK0s,18191 +triton/runtime/__init__.py,sha256=mKL5cqIBDUw2WO80NRCh4s1G8KYaqgM59TTAbTkPPjQ,621 +triton/runtime/__pycache__/__init__.cpython-310.pyc,, +triton/runtime/__pycache__/_allocation.cpython-310.pyc,, +triton/runtime/__pycache__/_async_compile.cpython-310.pyc,, +triton/runtime/__pycache__/autotuner.cpython-310.pyc,, +triton/runtime/__pycache__/build.cpython-310.pyc,, +triton/runtime/__pycache__/cache.cpython-310.pyc,, +triton/runtime/__pycache__/driver.cpython-310.pyc,, +triton/runtime/__pycache__/errors.cpython-310.pyc,, +triton/runtime/__pycache__/interpreter.cpython-310.pyc,, +triton/runtime/__pycache__/jit.cpython-310.pyc,, +triton/runtime/_allocation.py,sha256=XnujNofa5UAFq5D7r0APY6sOf9dDekoKSD7h14NohCk,1846 +triton/runtime/_async_compile.py,sha256=JwPgzz-ofKn8TaNfMhR1agnCyDk_w27hzC-n63qsHRw,1953 +triton/runtime/autotuner.py,sha256=QPXhQoBiGZQlhaFnQunzch1b_viBRbVxzzifmuxkYLs,20692 +triton/runtime/build.py,sha256=Jsbd1NujU0zlR5DxLSt1cp9R5GfEiy90DdYrfHWoWzk,3928 +triton/runtime/cache.py,sha256=A1XD40UvpFABIiRLj_-IZPIrwFxBej1vXa2p8ukvgEA,11041 +triton/runtime/driver.py,sha256=2qxsJH3SFxYDSIffj2wXMGSviEatUQLkHFcmVboeK-A,1025 +triton/runtime/errors.py,sha256=oM0HonEnBlnOx8e8XZidoAVQZ2Pg_YrA1NmIXAQxf6g,1325 +triton/runtime/interpreter.py,sha256=PLbtL9oHDkshHy_2X93vhCKHvzIaYeiHTryT9sVwyVM,65073 +triton/runtime/jit.py,sha256=C3A1jZAa_XCTejRKeBHkorzRDtyop8JB5HhC3JrGYMg,41084 +triton/testing.py,sha256=ROP657TMQbTbO4tBpPCoGNf-nQNs_k4PTwgDanXqr-Q,20476 +triton/tools/__init__.py,sha256=N18MiJ8bxNa1Odq3YjYSAFtAV35Vs4R87c2O8QwCamM,59 +triton/tools/__pycache__/__init__.cpython-310.pyc,, +triton/tools/__pycache__/build_extern.cpython-310.pyc,, +triton/tools/__pycache__/compile.cpython-310.pyc,, +triton/tools/__pycache__/disasm.cpython-310.pyc,, +triton/tools/__pycache__/link.cpython-310.pyc,, +triton/tools/__pycache__/mxfp.cpython-310.pyc,, +triton/tools/__pycache__/ragged_tma.cpython-310.pyc,, +triton/tools/__pycache__/tensor_descriptor.cpython-310.pyc,, +triton/tools/build_extern.py,sha256=jCr-2hu3nLGBIJhCGUQ1jAyzLttughjkiPGEwRFjLR0,13673 +triton/tools/compile.py,sha256=WpJ8HZlDaR3OGvrT3XSFlGdUyInd4g9EqsL2rXBGZ-Y,8786 +triton/tools/disasm.py,sha256=T9jiTkdK_0nI3R_4uea0zvfioYdcR-zIZwTfuucgw6g,5026 +triton/tools/extra/cuda/compile.c,sha256=F3K725kTI03oATPBdRbSnGHpOo11fGbE1aOelPTcRD8,2172 +triton/tools/extra/cuda/compile.h,sha256=n9QKIFZTL4RSsiXtAxBP9XGSnxjyaevQQ9bBpwDsvAg,332 +triton/tools/extra/hip/compile.cpp,sha256=IGdoA-52Nrk4S87Va6WJOIIi7G_4lhWZ6yjq8wkgG7k,1862 +triton/tools/extra/hip/compile.h,sha256=BIRh2lo4kKXWcsomk89DKx3sY3_XLMGoCyJ5HYvl3GU,348 +triton/tools/link.py,sha256=u7qtfZRLriZkAMEGNvj8YF-k1cthmLL7BwHYqBgT63E,11871 +triton/tools/mxfp.py,sha256=YQdpBrGkOVNOtnLeRjMCeVFHWkSwUubGeWsItIjO8TU,11737 +triton/tools/ragged_tma.py,sha256=KXiAhMTmyEclFHoUa92yQWdfHLYd1c8HyG1JTIZnEGM,3782 +triton/tools/tensor_descriptor.py,sha256=1uA6pZF8j7W0BLXcv4KOfSdh7BLY_7VN5Kk3XGG2vlM,1562 +triton/tools/triton_to_gluon_translater/__pycache__/translator.cpython-310.pyc,, +triton/tools/triton_to_gluon_translater/__pycache__/translator_helpers.cpython-310.pyc,, +triton/tools/triton_to_gluon_translater/translator.py,sha256=YQeCu6pROgo9m7ONdl5XSSrrJ0atzGQCC603vjlmHog,19912 +triton/tools/triton_to_gluon_translater/translator_helpers.py,sha256=Hc1lUVwnyOtgdPziBLb9ybxNvVnB8pkGpEHvREQQs7w,26428 diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton-3.6.0.dist-info/WHEEL b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton-3.6.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..12e67ca29ff180ca4133d9ec4769226edb266ce4 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton-3.6.0.dist-info/WHEEL @@ -0,0 +1,6 @@ +Wheel-Version: 1.0 +Generator: setuptools (80.9.0) +Root-Is-Purelib: false +Tag: cp310-cp310-manylinux_2_27_x86_64 +Tag: cp310-cp310-manylinux_2_28_x86_64 + diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton-3.6.0.dist-info/entry_points.txt b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton-3.6.0.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..d8d06486be664b9cd4a7e4e0fddbc18703fed64a --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton-3.6.0.dist-info/entry_points.txt @@ -0,0 +1,7 @@ +[console_scripts] +proton = triton.profiler.proton:main +proton-viewer = triton.profiler.viewer:main + +[triton.backends] +amd = triton.backends.amd +nvidia = triton.backends.nvidia diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton-3.6.0.dist-info/licenses/LICENSE b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton-3.6.0.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..1d0238e86b1b43e123c9eb136eb0b2c0e1658d63 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton-3.6.0.dist-info/licenses/LICENSE @@ -0,0 +1,23 @@ +/* +* Copyright 2018-2020 Philippe Tillet +* Copyright 2020-2022 OpenAI +* +* Permission is hereby granted, free of charge, to any person obtaining +* a copy of this software and associated documentation files +* (the "Software"), to deal in the Software without restriction, +* including without limitation the rights to use, copy, modify, merge, +* publish, distribute, sublicense, and/or sell copies of the Software, +* and to permit persons to whom the Software is furnished to do so, +* subject to the following conditions: +* +* The above copyright notice and this permission notice shall be +* included in all copies or substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton-3.6.0.dist-info/top_level.txt b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton-3.6.0.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..a59a965090a6473278f0cf9e7fd1d3cb9cb385c9 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton-3.6.0.dist-info/top_level.txt @@ -0,0 +1 @@ +triton diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/device_double_functions.hpp b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/device_double_functions.hpp new file mode 100644 index 0000000000000000000000000000000000000000..f63063689d65c4a1dffb9a823ddaf6a5b353cba3 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/device_double_functions.hpp @@ -0,0 +1,197 @@ +/* + * Copyright 1993-2017 NVIDIA Corporation. All rights reserved. + * + * NOTICE TO LICENSEE: + * + * This source code and/or documentation ("Licensed Deliverables") are + * subject to NVIDIA intellectual property rights under U.S. and + * international Copyright laws. + * + * These Licensed Deliverables contained herein is PROPRIETARY and + * CONFIDENTIAL to NVIDIA and is being provided under the terms and + * conditions of a form of NVIDIA software license agreement by and + * between NVIDIA and Licensee ("License Agreement") or electronically + * accepted by Licensee. Notwithstanding any terms or conditions to + * the contrary in the License Agreement, reproduction or disclosure + * of the Licensed Deliverables to any third party without the express + * written consent of NVIDIA is prohibited. + * + * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE + * LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE + * SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE. IT IS + * PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND. + * NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED + * DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY, + * NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE. + * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE + * LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY + * SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY + * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS + * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THESE LICENSED DELIVERABLES. + * + * U.S. Government End Users. These Licensed Deliverables are a + * "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT + * 1995), consisting of "commercial computer software" and "commercial + * computer software documentation" as such terms are used in 48 + * C.F.R. 12.212 (SEPT 1995) and is provided to the U.S. Government + * only as a commercial end item. Consistent with 48 C.F.R.12.212 and + * 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all + * U.S. Government End Users acquire the Licensed Deliverables with + * only those rights set forth herein. + * + * Any use of the Licensed Deliverables in individual and commercial + * software must include, in the user documentation and internal + * comments to the code, the above Disclaimer and U.S. Government End + * Users Notice. + */ + +#if !defined(__CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__) +#if defined(_MSC_VER) +#pragma message("crt/device_double_functions.hpp is an internal header file and must not be used directly. Please use cuda_runtime_api.h or cuda_runtime.h instead.") +#else +#warning "crt/device_double_functions.hpp is an internal header file and must not be used directly. Please use cuda_runtime_api.h or cuda_runtime.h instead." +#endif +#define __CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__ +#define __UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_DEVICE_DOUBLE_FUNCTIONS_HPP__ +#endif + +#if !defined(__DEVICE_DOUBLE_FUNCTIONS_HPP__) +#define __DEVICE_DOUBLE_FUNCTIONS_HPP__ + +/******************************************************************************* +* * +* * +* * +*******************************************************************************/ + +#if defined(__cplusplus) && defined(__CUDACC__) + +/******************************************************************************* +* * +* * +* * +*******************************************************************************/ + +#if defined(__CUDACC_RTC__) +#define __DEVICE_DOUBLE_FUNCTIONS_DECL__ __device__ +#else +#define __DEVICE_DOUBLE_FUNCTIONS_DECL__ static __inline__ __device__ +#endif /* __CUDACC_RTC__ */ + +#include "builtin_types.h" +#include "device_types.h" +#include "host_defines.h" + +/******************************************************************************* +* * +* * +* * +*******************************************************************************/ + +__DEVICE_DOUBLE_FUNCTIONS_DECL__ double fma(double a, double b, double c, enum cudaRoundMode mode) +{ + return mode == cudaRoundZero ? __fma_rz(a, b, c) : + mode == cudaRoundPosInf ? __fma_ru(a, b, c) : + mode == cudaRoundMinInf ? __fma_rd(a, b, c) : + __fma_rn(a, b, c); +} + +__DEVICE_DOUBLE_FUNCTIONS_DECL__ double dmul(double a, double b, enum cudaRoundMode mode) +{ + return mode == cudaRoundZero ? __dmul_rz(a, b) : + mode == cudaRoundPosInf ? __dmul_ru(a, b) : + mode == cudaRoundMinInf ? __dmul_rd(a, b) : + __dmul_rn(a, b); +} + +__DEVICE_DOUBLE_FUNCTIONS_DECL__ double dadd(double a, double b, enum cudaRoundMode mode) +{ + return mode == cudaRoundZero ? __dadd_rz(a, b) : + mode == cudaRoundPosInf ? __dadd_ru(a, b) : + mode == cudaRoundMinInf ? __dadd_rd(a, b) : + __dadd_rn(a, b); +} + +__DEVICE_DOUBLE_FUNCTIONS_DECL__ double dsub(double a, double b, enum cudaRoundMode mode) +{ + return mode == cudaRoundZero ? __dsub_rz(a, b) : + mode == cudaRoundPosInf ? __dsub_ru(a, b) : + mode == cudaRoundMinInf ? __dsub_rd(a, b) : + __dsub_rn(a, b); +} + +__DEVICE_DOUBLE_FUNCTIONS_DECL__ int double2int(double a, enum cudaRoundMode mode) +{ + return mode == cudaRoundNearest ? __double2int_rn(a) : + mode == cudaRoundPosInf ? __double2int_ru(a) : + mode == cudaRoundMinInf ? __double2int_rd(a) : + __double2int_rz(a); +} + +__DEVICE_DOUBLE_FUNCTIONS_DECL__ unsigned int double2uint(double a, enum cudaRoundMode mode) +{ + return mode == cudaRoundNearest ? __double2uint_rn(a) : + mode == cudaRoundPosInf ? __double2uint_ru(a) : + mode == cudaRoundMinInf ? __double2uint_rd(a) : + __double2uint_rz(a); +} + +__DEVICE_DOUBLE_FUNCTIONS_DECL__ long long int double2ll(double a, enum cudaRoundMode mode) +{ + return mode == cudaRoundNearest ? __double2ll_rn(a) : + mode == cudaRoundPosInf ? __double2ll_ru(a) : + mode == cudaRoundMinInf ? __double2ll_rd(a) : + __double2ll_rz(a); +} + +__DEVICE_DOUBLE_FUNCTIONS_DECL__ unsigned long long int double2ull(double a, enum cudaRoundMode mode) +{ + return mode == cudaRoundNearest ? __double2ull_rn(a) : + mode == cudaRoundPosInf ? __double2ull_ru(a) : + mode == cudaRoundMinInf ? __double2ull_rd(a) : + __double2ull_rz(a); +} + +__DEVICE_DOUBLE_FUNCTIONS_DECL__ double ll2double(long long int a, enum cudaRoundMode mode) +{ + return mode == cudaRoundZero ? __ll2double_rz(a) : + mode == cudaRoundPosInf ? __ll2double_ru(a) : + mode == cudaRoundMinInf ? __ll2double_rd(a) : + __ll2double_rn(a); +} + +__DEVICE_DOUBLE_FUNCTIONS_DECL__ double ull2double(unsigned long long int a, enum cudaRoundMode mode) +{ + return mode == cudaRoundZero ? __ull2double_rz(a) : + mode == cudaRoundPosInf ? __ull2double_ru(a) : + mode == cudaRoundMinInf ? __ull2double_rd(a) : + __ull2double_rn(a); +} + +__DEVICE_DOUBLE_FUNCTIONS_DECL__ double int2double(int a, enum cudaRoundMode mode) +{ + return (double)a; +} + +__DEVICE_DOUBLE_FUNCTIONS_DECL__ double uint2double(unsigned int a, enum cudaRoundMode mode) +{ + return (double)a; +} + +__DEVICE_DOUBLE_FUNCTIONS_DECL__ double float2double(float a, enum cudaRoundMode mode) +{ + return (double)a; +} + +#undef __DEVICE_DOUBLE_FUNCTIONS_DECL__ + +#endif /* __cplusplus && __CUDACC__ */ + +#endif /* !__DEVICE_DOUBLE_FUNCTIONS_HPP__ */ + +#if defined(__UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_DEVICE_DOUBLE_FUNCTIONS_HPP__) +#undef __CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__ +#undef __UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_DEVICE_DOUBLE_FUNCTIONS_HPP__ +#endif diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/device_fp128_functions.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/device_fp128_functions.h new file mode 100644 index 0000000000000000000000000000000000000000..715220e121f790ab8ff2aeaed25620fe9759236f --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/device_fp128_functions.h @@ -0,0 +1,1217 @@ +/* + * Copyright 2024 NVIDIA Corporation. All rights reserved. + * + * NOTICE TO LICENSEE: + * + * This source code and/or documentation ("Licensed Deliverables") are + * subject to NVIDIA intellectual property rights under U.S. and + * international Copyright laws. + * + * These Licensed Deliverables contained herein is PROPRIETARY and + * CONFIDENTIAL to NVIDIA and is being provided under the terms and + * conditions of a form of NVIDIA software license agreement by and + * between NVIDIA and Licensee ("License Agreement") or electronically + * accepted by Licensee. Notwithstanding any terms or conditions to + * the contrary in the License Agreement, reproduction or disclosure + * of the Licensed Deliverables to any third party without the express + * written consent of NVIDIA is prohibited. + * + * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE + * LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE + * SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE. IT IS + * PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND. + * NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED + * DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY, + * NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE. + * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE + * LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY + * SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY + * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS + * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THESE LICENSED DELIVERABLES. + * + * U.S. Government End Users. These Licensed Deliverables are a + * "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT + * 1995), consisting of "commercial computer software" and "commercial + * computer software documentation" as such terms are used in 48 + * C.F.R. 12.212 (SEPT 1995) and is provided to the U.S. Government + * only as a commercial end item. Consistent with 48 C.F.R.12.212 and + * 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all + * U.S. Government End Users acquire the Licensed Deliverables with + * only those rights set forth herein. + * + * Any use of the Licensed Deliverables in individual and commercial + * software must include, in the user documentation and internal + * comments to the code, the above Disclaimer and U.S. Government End + * Users Notice. + */ + +// to easily switch off fp128 device functions if needed +#ifndef __NV_DISABLE_DEVICE_FP128_FUNCTIONS__ + +#if !defined(__DEVICE_FP128_FUNCTIONS_H__) +#define __DEVICE_FP128_FUNCTIONS_H__ + +/******************************************************************************* +* * +* * +* * +*******************************************************************************/ + +#if defined(__cplusplus) && defined(__CUDACC__) + +/******************************************************************************* +* * +* * +* * +*******************************************************************************/ + +#include "builtin_types.h" +#include "device_types.h" + +#if !defined(__CUDA_ARCH__) && !defined(_NVHPC_CUDA) +#define __DEF_IF_HOST { } +#define __INLINE_IF_HOST__ __inline__ +#else /* !__CUDA_ARCH__ */ +#define __DEF_IF_HOST ; +#define __INLINE_IF_HOST__ +#endif /* __CUDA_ARCH__ */ + +#define __DEVICE_FP128_FUNCTIONS_DECL__ __device__ __cudart_builtin__ __INLINE_IF_HOST__ + +/******************************************************************************* +* * +* Support for __float128 on: * +* - NVRTC on Linux * +* - GCC version 4.1 or later on x86_64/amd64 * +* - Clang version 3.9 or later on x86_64/amd64 * +* - NVHPC version 21.1 or later on x86_64/amd64 * +* * +*******************************************************************************/ +#if defined(__CUDACC_RTC__) +#if !_WIN64 +#define __FLOAT128_CPP_SPELLING_ENABLED__ +#endif +#else /* !__CUDACC_RTC__ */ + +#if (defined __NVCOMPILER_MAJOR__) + #if (defined(__x86_64__) || defined(__amd64__)) && \ + ((__NVCOMPILER_MAJOR__ > 21) || \ + (__NVCOMPILER_MAJOR__ == 21 && __NVCOMPILER_MINOR__ >= 1)) + #define __FLOAT128_CPP_SPELLING_ENABLED__ + #endif +#elif defined(__clang__) + #if (defined(__x86_64__) || defined(__amd64__)) && \ + ((__clang_major__ > 3) || \ + (__clang_major__ == 3 && __clang_minor__ >= 9)) + #define __FLOAT128_CPP_SPELLING_ENABLED__ + #endif +#elif defined(__GNUC__) + // check gcc version if no other host compiler is used + #if (defined(__x86_64__) || defined(__amd64__)) && \ + ((__GNUC__ > 4) || \ + (__GNUC__ == 4 && __GNUC_MINOR__ >= 1)) + #define __FLOAT128_CPP_SPELLING_ENABLED__ + #endif +#endif /* (defined __NVCOMPILER_MAJOR__) */ + +#endif /* !__CUDACC_RTC__ */ + +/******************************************************************************* +* * +* Support for _Float128 on: * +* - GCC version 13.1 or later on x86_64/amd64/aarch64 * +* * +*******************************************************************************/ +#if defined(__GNUC__) && !defined(__clang__) && !defined(__NVCOMPILER_MAJOR__) + // check gcc version if no other host compiler is used + #if (defined(__x86_64__) || defined(__amd64__) || defined(__aarch64__)) && \ + ((__GNUC__ > 13) || \ + (__GNUC__ == 13 && __GNUC_MINOR__ >= 1)) + #define __FLOAT128_C_SPELLING_ENABLED__ + #endif +#endif /* defined(__GNUC__) && !defined(__clang__) && !defined(__NVCOMPILER_MAJOR__) */ + +/** + * \defgroup CUDA_MATH_QUAD FP128 Quad Precision Mathematical Functions + * This section describes quad precision mathematical functions. + * To use these functions, include the header file \p device_fp128_functions.h in your program. + * + * Functions declared here have \p __nv_fp128_ prefix to distinguish them + * from other global namespace symbols. + * + * Note that FP128 CUDA Math functions are only available to device programs + * on platforms where host compiler supports the basic quad precision datatype + * \p __float128 or \p _Float128. + * + * Every FP128 CUDA Math function name is overloaded to support either of these + * host-compiler-specific types, whenever the types are available. See for example: + * \code + * #ifdef __FLOAT128_CPP_SPELLING_ENABLED__ + * __float128 __nv_fp128_sqrt(__float128 x); + * #endif + * #ifdef __FLOAT128_C_SPELLING_ENABLED__ + * _Float128 __nv_fp128_sqrt(_Float128 x); + * #endif + * \endcode + * + * \note_fp128_target_arch + */ + +#ifdef __FLOAT128_CPP_SPELLING_ENABLED__ +/** + * \ingroup CUDA_MATH_QUAD + * \brief Calculate \cuda_math_formula \sqrt{x} \end_cuda_math_formula, the square root of the input argument. + * + * \return + * \cuda_math_formula \sqrt{x} \end_cuda_math_formula. + * - __nv_fp128_sqrt( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - __nv_fp128_sqrt( + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - __nv_fp128_sqrt(\p x) returns NaN if \p x is less than 0. + * - __nv_fp128_sqrt(NaN) returns NaN. + * + * \note_accuracy_quad + * \note_fp128_target_arch + */ +__DEVICE_FP128_FUNCTIONS_DECL__ __float128 __nv_fp128_sqrt(__float128 x) __DEF_IF_HOST +/** + * \ingroup CUDA_MATH_QUAD + * \brief Calculate \cuda_math_formula \sin{x} \end_cuda_math_formula, the sine of input argument (measured in radians). + * + * \return + * \cuda_math_formula \sin{x} \end_cuda_math_formula. + * - __nv_fp128_sin( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - __nv_fp128_sin( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns NaN. + * - __nv_fp128_sin(NaN) returns NaN. + * + * \note_accuracy_quad + * \note_fp128_target_arch + */ +__DEVICE_FP128_FUNCTIONS_DECL__ __float128 __nv_fp128_sin(__float128 x) __DEF_IF_HOST +/** + * \ingroup CUDA_MATH_QUAD + * \brief Calculate \cuda_math_formula \cos{x} \end_cuda_math_formula, the cosine of input argument (measured in radians). + * + * \return + * \cuda_math_formula \cos{x} \end_cuda_math_formula. + * - __nv_fp128_cos( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula 1 \end_cuda_math_formula. + * - __nv_fp128_cos( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns NaN. + * - __nv_fp128_cos(NaN) returns NaN. + * + * \note_accuracy_quad + * \note_fp128_target_arch + */ +__DEVICE_FP128_FUNCTIONS_DECL__ __float128 __nv_fp128_cos(__float128 x) __DEF_IF_HOST +/** + * \ingroup CUDA_MATH_QUAD + * \brief Calculate \cuda_math_formula \tan{x} \end_cuda_math_formula, the tangent of input argument (measured in radians). + * + * \return + * \cuda_math_formula \tan{x} \end_cuda_math_formula. + * - __nv_fp128_tan( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - __nv_fp128_tan( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns NaN. + * - __nv_fp128_tan(NaN) returns NaN. + * + * \note_accuracy_quad + * \note_fp128_target_arch + */ +__DEVICE_FP128_FUNCTIONS_DECL__ __float128 __nv_fp128_tan(__float128 x) __DEF_IF_HOST +/** + * \ingroup CUDA_MATH_QUAD + * \brief Calculate \cuda_math_formula \sin^{-1}{x} \end_cuda_math_formula, the arc sine of input argument. + * + * \return + * The principal value of the arc sine of the input argument \p x. + * Result will be in radians, in the interval [- + * \cuda_math_formula \pi/2 \end_cuda_math_formula + * , + + * \cuda_math_formula \pi/2 \end_cuda_math_formula + * ] for \p x inside [-1, +1]. + * - __nv_fp128_asin( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - __nv_fp128_asin(\p x) returns NaN for \p x outside [-1, +1]. + * - __nv_fp128_asin(NaN) returns NaN. + * + * \note_accuracy_quad + * \note_fp128_target_arch + */ +__DEVICE_FP128_FUNCTIONS_DECL__ __float128 __nv_fp128_asin(__float128 x) __DEF_IF_HOST +/** + * \ingroup CUDA_MATH_QUAD + * \brief Calculate \cuda_math_formula \cos^{-1}{x} \end_cuda_math_formula, the arc cosine of input argument. + * + * \return + * The principal value of the arc cosine of the input argument \p x. + * Result will be in radians, in the interval [0, + * \cuda_math_formula \pi \end_cuda_math_formula + * ] for \p x inside [-1, +1]. + * - __nv_fp128_acos(1) returns +0. + * - __nv_fp128_acos(\p x) returns NaN for \p x outside [-1, +1]. + * - __nv_fp128_acos(NaN) returns NaN. + * + * \note_accuracy_quad + * \note_fp128_target_arch + */ +__DEVICE_FP128_FUNCTIONS_DECL__ __float128 __nv_fp128_acos(__float128 x) __DEF_IF_HOST +/** + * \ingroup CUDA_MATH_QUAD + * \brief Calculate \cuda_math_formula \tan^{-1}{x} \end_cuda_math_formula, the arc tangent of input argument. + * + * \return + * The principal value of the arc tangent of the input argument \p x. + * Result will be in radians, in the interval [- + * \cuda_math_formula \pi/2 \end_cuda_math_formula + * , + + * \cuda_math_formula \pi/2 \end_cuda_math_formula + * ]. + * - __nv_fp128_atan( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - __nv_fp128_atan( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm \pi \end_cuda_math_formula + * /2. + * - __nv_fp128_atan(NaN) returns NaN. + * + * \note_accuracy_quad + * \note_fp128_target_arch + */ +__DEVICE_FP128_FUNCTIONS_DECL__ __float128 __nv_fp128_atan(__float128 x) __DEF_IF_HOST +/** + * \ingroup CUDA_MATH_QUAD + * \brief Calculate \cuda_math_formula e^x \end_cuda_math_formula, the base + * \cuda_math_formula e \end_cuda_math_formula + * exponential of the input argument. + * + * \return + * - __nv_fp128_exp( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns 1. + * - __nv_fp128_exp( + * \cuda_math_formula -\infty \end_cuda_math_formula + * ) returns +0. + * - __nv_fp128_exp( + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - __nv_fp128_exp(NaN) returns NaN. + * + * \note_accuracy_quad + * \note_fp128_target_arch + */ +__DEVICE_FP128_FUNCTIONS_DECL__ __float128 __nv_fp128_exp(__float128 x) __DEF_IF_HOST +/** + * \ingroup CUDA_MATH_QUAD + * \brief Calculate \cuda_math_formula 2^x \end_cuda_math_formula, the base 2 exponential of the input argument. + * + * \return + * - __nv_fp128_exp2( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns 1. + * - ex__nv_fp128_exp2p2f( + * \cuda_math_formula -\infty \end_cuda_math_formula + * ) returns +0. + * - __nv_fp128_exp2( + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - __nv_fp128_exp2(NaN) returns NaN. + * + * \note_accuracy_quad + * \note_fp128_target_arch + */ +__DEVICE_FP128_FUNCTIONS_DECL__ __float128 __nv_fp128_exp2(__float128 x) __DEF_IF_HOST +/** + * \ingroup CUDA_MATH_QUAD + * \brief Calculate \cuda_math_formula 10^x \end_cuda_math_formula, the base 10 exponential of the input argument. + * + * \return + * - __nv_fp128_exp10( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns 1. + * - __nv_fp128_exp10( + * \cuda_math_formula -\infty \end_cuda_math_formula + * ) returns +0. + * - __nv_fp128_exp10( + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - __nv_fp128_exp10(NaN) returns NaN. + * + * \note_accuracy_quad + * \note_fp128_target_arch + */ +__DEVICE_FP128_FUNCTIONS_DECL__ __float128 __nv_fp128_exp10(__float128 x) __DEF_IF_HOST +/** + * \ingroup CUDA_MATH_QUAD + * \brief Calculate + * \cuda_math_formula e^x - 1 \end_cuda_math_formula, + * the base e exponential of the input argument, minus 1. + * + * \return + * - __nv_fp128_expm1( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - __nv_fp128_expm1( + * \cuda_math_formula -\infty \end_cuda_math_formula + * ) returns -1. + * - __nv_fp128_expm1( + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - __nv_fp128_expm1(NaN) returns NaN. + * + * \note_accuracy_quad + * \note_fp128_target_arch + */ +__DEVICE_FP128_FUNCTIONS_DECL__ __float128 __nv_fp128_expm1(__float128 x) __DEF_IF_HOST +/** + * \ingroup CUDA_MATH_QUAD + * \brief Calculate \cuda_math_formula \log_{e}{x} \end_cuda_math_formula, the base + * \cuda_math_formula e \end_cuda_math_formula + * logarithm of the input argument. + * + * \return + * - __nv_fp128_log( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula -\infty \end_cuda_math_formula. + * - __nv_fp128_log(1) returns +0. + * - __nv_fp128_log(\p x) returns NaN for \p x < 0. + * - __nv_fp128_log( + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - __nv_fp128_log(NaN) returns NaN. + * + * \note_accuracy_quad + * \note_fp128_target_arch + */ +__DEVICE_FP128_FUNCTIONS_DECL__ __float128 __nv_fp128_log(__float128 x) __DEF_IF_HOST +/** + * \ingroup CUDA_MATH_QUAD + * \brief Calculate \cuda_math_formula \log_{2}{x} \end_cuda_math_formula, the base 2 logarithm of the input argument. + * + * \return + * - __nv_fp128_log2( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula -\infty \end_cuda_math_formula. + * - __nv_fp128_log2(1) returns +0. + * - __nv_fp128_log2(\p x) returns NaN for \p x < 0. + * - __nv_fp128_log2( + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - __nv_fp128_log2(NaN) returns NaN. + * + * \note_accuracy_quad + * \note_fp128_target_arch + */ +__DEVICE_FP128_FUNCTIONS_DECL__ __float128 __nv_fp128_log2(__float128 x) __DEF_IF_HOST +/** + * \ingroup CUDA_MATH_QUAD + * \brief Calculate \cuda_math_formula \log_{10}{x} \end_cuda_math_formula, the base 10 logarithm of the input argument. + * + * \return + * - __nv_fp128_log10( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula -\infty \end_cuda_math_formula. + * - __nv_fp128_log10(1) returns +0. + * - __nv_fp128_log10(\p x) returns NaN for \p x < 0. + * - __nv_fp128_log10( + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - __nv_fp128_log10(NaN) returns NaN. + * + * \note_accuracy_quad + * \note_fp128_target_arch + */ +__DEVICE_FP128_FUNCTIONS_DECL__ __float128 __nv_fp128_log10(__float128 x) __DEF_IF_HOST +/** + * \ingroup CUDA_MATH_QUAD + * \brief Calculate the value of + * \cuda_math_formula \log_{e}(1+x) \end_cuda_math_formula. + * + * \return + * - __nv_fp128_log1p( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - __nv_fp128_log1p(-1) returns + * \cuda_math_formula -\infty \end_cuda_math_formula. + * - __nv_fp128_log1p(\p x) returns NaN for \p x < -1. + * - __nv_fp128_log1p( + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - __nv_fp128_log1p(NaN) returns NaN. + * + * \note_accuracy_quad + * \note_fp128_target_arch + */ +__DEVICE_FP128_FUNCTIONS_DECL__ __float128 __nv_fp128_log1p(__float128 x) __DEF_IF_HOST +/** + * \ingroup CUDA_MATH_QUAD + * \brief Calculate the value of \cuda_math_formula x^{y} \end_cuda_math_formula, first argument to the power of second argument. + * + * \return + * - __nv_fp128_pow( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * , \p y) returns + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * for \p y an odd integer less than 0. + * - __nv_fp128_pow( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * , \p y) returns + * \cuda_math_formula +\infty \end_cuda_math_formula + * for \p y less than 0 and not an odd integer. + * - __nv_fp128_pow( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * , \p y) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * for \p y an odd integer greater than 0. + * - __nv_fp128_pow( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * , \p y) returns +0 for \p y > 0 and not an odd integer. + * - __nv_fp128_pow(-1, + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns 1. + * - __nv_fp128_pow(+1, \p y) returns 1 for any \p y, even a NaN. + * - __nv_fp128_pow(\p x, + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns 1 for any \p x, even a NaN. + * - __nv_fp128_pow(\p x, \p y) returns a NaN for finite \p x < 0 and finite non-integer \p y. + * - __nv_fp128_pow(\p x, + * \cuda_math_formula -\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula + * for + * \cuda_math_formula | x | < 1 \end_cuda_math_formula. + * - __nv_fp128_pow(\p x, + * \cuda_math_formula -\infty \end_cuda_math_formula + * ) returns +0 for + * \cuda_math_formula | x | > 1 \end_cuda_math_formula. + * - __nv_fp128_pow(\p x, + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns +0 for + * \cuda_math_formula | x | < 1 \end_cuda_math_formula. + * - __nv_fp128_pow(\p x, + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula + * for + * \cuda_math_formula | x | > 1 \end_cuda_math_formula. + * - __nv_fp128_pow( + * \cuda_math_formula -\infty \end_cuda_math_formula + * , \p y) returns -0 for \p y an odd integer less than 0. + * - __nv_fp128_pow( + * \cuda_math_formula -\infty \end_cuda_math_formula + * , \p y) returns +0 for \p y < 0 and not an odd integer. + * - __nv_fp128_pow( + * \cuda_math_formula -\infty \end_cuda_math_formula + * , \p y) returns + * \cuda_math_formula -\infty \end_cuda_math_formula + * for \p y an odd integer greater than 0. + * - __nv_fp128_pow( + * \cuda_math_formula -\infty \end_cuda_math_formula + * , \p y) returns + * \cuda_math_formula +\infty \end_cuda_math_formula + * for \p y > 0 and not an odd integer. + * - __nv_fp128_pow( + * \cuda_math_formula +\infty \end_cuda_math_formula + * , \p y) returns +0 for \p y < 0. + * - __nv_fp128_pow( + * \cuda_math_formula +\infty \end_cuda_math_formula + * , \p y) returns + * \cuda_math_formula +\infty \end_cuda_math_formula + * for \p y > 0. + * - __nv_fp128_pow(\p x, \p y) returns NaN if either \p x or \p y or both are NaN and \p x \cuda_math_formula \neq \end_cuda_math_formula +1 and \p y \cuda_math_formula \neq\pm 0 \end_cuda_math_formula. + * + * \note_accuracy_quad + * \note_fp128_target_arch + */ +__DEVICE_FP128_FUNCTIONS_DECL__ __float128 __nv_fp128_pow(__float128 x, __float128 y) __DEF_IF_HOST +/** + * \ingroup CUDA_MATH_QUAD + * \brief Calculate \cuda_math_formula \sinh{x} \end_cuda_math_formula, the hyperbolic sine of the input argument. + * + * Calculate \cuda_math_formula \sinh{x} \end_cuda_math_formula, the hyperbolic sine of the input argument \p x. + * + * \return + * - __nv_fp128_sinhinh( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - __nv_fp128_sinh( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm \infty \end_cuda_math_formula. + * - __nv_fp128_sinh(NaN) returns NaN. + * + * \note_accuracy_quad + * \note_fp128_target_arch + */ +__DEVICE_FP128_FUNCTIONS_DECL__ __float128 __nv_fp128_sinh(__float128 x) __DEF_IF_HOST +/** + * \ingroup CUDA_MATH_QUAD + * \brief Calculate \cuda_math_formula \cosh{x} \end_cuda_math_formula, the hyperbolic cosine of the input argument. + * + * \return + * - __nv_fp128_cosh( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns 1. + * - __nv_fp128_cosh( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - __nv_fp128_cosh(NaN) returns NaN. + * + * \note_accuracy_quad + * \note_fp128_target_arch + */ +__DEVICE_FP128_FUNCTIONS_DECL__ __float128 __nv_fp128_cosh(__float128 x) __DEF_IF_HOST +/** + * \ingroup CUDA_MATH_QUAD + * \brief Calculate \cuda_math_formula \tanh{x} \end_cuda_math_formula, the hyperbolic tangent of the input argument. + * + * \return + * - __nv_fp128_tanh( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - __nv_fp128_tanh( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 1 \end_cuda_math_formula. + * - __nv_fp128_tanh(NaN) returns NaN. + * + * \note_accuracy_quad + * \note_fp128_target_arch + */ +__DEVICE_FP128_FUNCTIONS_DECL__ __float128 __nv_fp128_tanh(__float128 x) __DEF_IF_HOST +/** + * \ingroup CUDA_MATH_QUAD + * \brief Calculate \cuda_math_formula \sinh^{-1}{x} \end_cuda_math_formula, the inverse hyperbolic sine of the input argument. + * + * \return + * - __nv_fp128_asinh( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - __nv_fp128_asinh( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm \infty \end_cuda_math_formula. + * - __nv_fp128_asinh(NaN) returns NaN. + * + * \note_accuracy_quad + * \note_fp128_target_arch + */ +__DEVICE_FP128_FUNCTIONS_DECL__ __float128 __nv_fp128_asinh(__float128 x) __DEF_IF_HOST +/** + * \ingroup CUDA_MATH_QUAD + * \brief Calculate \cuda_math_formula \cosh^{-1}{x} \end_cuda_math_formula, the nonnegative inverse hyperbolic cosine of the input argument. + * + * \return + * Result will be in the interval [0, + * \cuda_math_formula +\infty \end_cuda_math_formula + * ]. + * - __nv_fp128_acosh(1) returns 0. + * - __nv_fp128_acosh(\p x) returns NaN for \p x in the interval [ + * \cuda_math_formula -\infty \end_cuda_math_formula + * , 1). + * - __nv_fp128_acosh( + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - __nv_fp128_acosh(NaN) returns NaN. + * + * \note_accuracy_quad + * \note_fp128_target_arch + */ +__DEVICE_FP128_FUNCTIONS_DECL__ __float128 __nv_fp128_acosh(__float128 x) __DEF_IF_HOST +/** + * \ingroup CUDA_MATH_QUAD + * \brief Calculate \cuda_math_formula \tanh^{-1}{x} \end_cuda_math_formula, the inverse hyperbolic tangent of the input argument. + * + * \return + * - __nv_fp128_atanh( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - __nv_fp128_atanh( + * \cuda_math_formula \pm 1 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm \infty \end_cuda_math_formula. + * - __nv_fp128_atanh(\p x) returns NaN for \p x outside interval [-1, 1]. + * - __nv_fp128_atanh(NaN) returns NaN. + * + * \note_accuracy_quad + * \note_fp128_target_arch + */ +__DEVICE_FP128_FUNCTIONS_DECL__ __float128 __nv_fp128_atanh(__float128 x) __DEF_IF_HOST +/** + * \ingroup CUDA_MATH_QUAD + * \brief Truncate input argument to the integral part. + * + * \return + * Rounded \p x to the nearest integer value in floating-point format, that does not exceed \p x in + * magnitude. + * - __nv_fp128_trunc( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - __nv_fp128_trunc( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm \infty \end_cuda_math_formula. + * - __nv_fp128_trunc(NaN) returns NaN. + * + * \note_accuracy_quad + * \note_fp128_target_arch + */ +__DEVICE_FP128_FUNCTIONS_DECL__ __float128 __nv_fp128_trunc(__float128 x) __DEF_IF_HOST +/** + * \ingroup CUDA_MATH_QUAD + * \brief Calculate \cuda_math_formula \lfloor x \rfloor \end_cuda_math_formula, the largest integer less than or equal to \p x. + * + * \return + * \cuda_math_formula \lfloor x \rfloor \end_cuda_math_formula + * expressed as a floating-point number. + * - __nv_fp128_floor( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm \infty \end_cuda_math_formula. + * - __nv_fp128_floor( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - __nv_fp128_floor(NaN) returns NaN. + * + * \note_accuracy_quad + * \note_fp128_target_arch + */ +__DEVICE_FP128_FUNCTIONS_DECL__ __float128 __nv_fp128_floor(__float128 x) __DEF_IF_HOST +/** + * \ingroup CUDA_MATH_QUAD + * \brief Calculate \cuda_math_formula \lceil x \rceil \end_cuda_math_formula, the smallest integer greater than or equal to \p x. + * + * \return + * \cuda_math_formula \lceil x \rceil \end_cuda_math_formula + * expressed as a floating-point number. + * - __nv_fp128_ceil( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm \infty \end_cuda_math_formula. + * - __nv_fp128_ceil( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - __nv_fp128_ceil(NaN) returns NaN. + * + * \note_accuracy_quad + * \note_fp128_target_arch + */ +__DEVICE_FP128_FUNCTIONS_DECL__ __float128 __nv_fp128_ceil(__float128 x) __DEF_IF_HOST +/** + * \ingroup CUDA_MATH_QUAD + * \brief Round to nearest integer value in floating-point format, + * with halfway cases rounded away from zero. + * + * \return + * - __nv_fp128_round( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - __nv_fp128_round( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm \infty \end_cuda_math_formula. + * - __nv_fp128_round(NaN) returns NaN. + * + * \note_accuracy_quad + * \note_fp128_target_arch + */ +__DEVICE_FP128_FUNCTIONS_DECL__ __float128 __nv_fp128_round(__float128 x) __DEF_IF_HOST +/** + * \ingroup CUDA_MATH_QUAD + * \brief Round to nearest integer value in floating-point format, + * with halfway cases rounded to the nearest even integer value. + * + * \return + * - __nv_fp128_rint( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - __nv_fp128_rint( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm \infty \end_cuda_math_formula. + * - __nv_fp128_rint(NaN) returns NaN. + * + * \note_accuracy_quad + * \note_fp128_target_arch + */ +__DEVICE_FP128_FUNCTIONS_DECL__ __float128 __nv_fp128_rint(__float128 x) __DEF_IF_HOST +/** + * \ingroup CUDA_MATH_QUAD + * \brief Calculate \cuda_math_formula |x| \end_cuda_math_formula, the absolute value of the input argument. + * + * \return + * - __nv_fp128_fabs( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - __nv_fp128_fabs( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns +0. + * - __nv_fp128_fabs(NaN) returns an unspecified NaN. + * + * \note_accuracy_quad + * \note_fp128_target_arch + */ +__DEVICE_FP128_FUNCTIONS_DECL__ __float128 __nv_fp128_fabs(__float128 x) __DEF_IF_HOST +/** + * \ingroup CUDA_MATH_QUAD + * \brief Create value with the magnitude of the first agument \p x, and the sign of the second argument \p y. + * + * \return + * - copysign(\p NaN, \p y) returns a \p NaN with the sign of \p y. + * + * \note_accuracy_quad + * \note_fp128_target_arch + */ +__DEVICE_FP128_FUNCTIONS_DECL__ __float128 __nv_fp128_copysign(__float128 x, __float128 y) __DEF_IF_HOST +/** + * \ingroup CUDA_MATH_QUAD + * \brief Determine the maximum numeric value of the arguments. + * + * \return + * The maximum numeric value of the arguments \p x and \p y. Treats NaN + * arguments as missing data. + * - If both arguments are NaN, returns NaN. + * - If one argument is NaN, returns the numeric argument. + * + * \note_accuracy_quad + * \note_fp128_target_arch + */ +__DEVICE_FP128_FUNCTIONS_DECL__ __float128 __nv_fp128_fmax(__float128 x, __float128 y) __DEF_IF_HOST +/** + * \ingroup CUDA_MATH_QUAD + * \brief Determine the minimum numeric value of the arguments. + * + * \return + * The minimum numeric value of the arguments \p x and \p y. Treats NaN + * arguments as missing data. + * - If both arguments are NaN, returns NaN. + * - If one argument is NaN, returns the numeric argument. + * + * \note_accuracy_quad + * \note_fp128_target_arch + */ +__DEVICE_FP128_FUNCTIONS_DECL__ __float128 __nv_fp128_fmin(__float128 x, __float128 y) __DEF_IF_HOST +/** + * \ingroup CUDA_MATH_QUAD + * \brief Compute the positive difference between \p x and \p y. + * + * \return + * - __nv_fp128_fdim(\p x, \p y) returns \p x - \p y if \cuda_math_formula x > y \end_cuda_math_formula. + * - __nv_fp128_fdim(\p x, \p y) returns +0 if \cuda_math_formula x \leq y \end_cuda_math_formula. + * - If either argument is NaN, NaN is returned. + * + * \note_accuracy_quad + * \note_fp128_target_arch + */ +__DEVICE_FP128_FUNCTIONS_DECL__ __float128 __nv_fp128_fdim(__float128 x, __float128 y) __DEF_IF_HOST +/** + * \ingroup CUDA_MATH_QUAD + * \brief Calculate the floating-point remainder of \p x / \p y. + * + * \return + * The floating-point remainder of the division operation \p x / \p y calculated + * by this function is exactly the value x - n*y, where \p n is \p x / \p y with its fractional part truncated. + * - The computed value will have the same sign as \p x, and its magnitude will be less than the magnitude of \p y. + * - __nv_fp128_fmod( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * , \p y) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * if \p y is not zero. + * - __nv_fp128_fmod(\p x, + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns \p x if \p x is finite. + * - __nv_fp128_fmod(\p x, \p y) returns NaN if \p x is + * \cuda_math_formula \pm\infty \end_cuda_math_formula + * or \p y is zero. + * - If either argument is NaN, NaN is returned. + * + * \note_accuracy_quad + * \note_fp128_target_arch + */ +__DEVICE_FP128_FUNCTIONS_DECL__ __float128 __nv_fp128_fmod(__float128 x, __float128 y) __DEF_IF_HOST +/** + * \ingroup CUDA_MATH_QUAD + * \brief Compute the floating-point remainder function. + * + * \return + * The floating-point remainder \p r of dividing + * \p x by \p y for nonzero \p y is defined as + * \cuda_math_formula r = x - n y \end_cuda_math_formula. + * The value \p n is the integer value nearest + * \cuda_math_formula \frac{x}{y} \end_cuda_math_formula. + * In the halfway cases when + * \cuda_math_formula | n -\frac{x}{y} | = \frac{1}{2} \end_cuda_math_formula + * , the + * even \p n value is chosen. + * - __nv_fp128_remainder(\p x, + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns NaN. + * - __nv_fp128_remainder( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * , \p y) returns NaN. + * - __nv_fp128_remainder(\p x, + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns \p x for finite \p x. + * - If either argument is NaN, NaN is returned. + * + * \note_accuracy_quad + * \note_fp128_target_arch + */ +__DEVICE_FP128_FUNCTIONS_DECL__ __float128 __nv_fp128_remainder(__float128 x, __float128 y) __DEF_IF_HOST +/** + * \ingroup CUDA_MATH_QUAD + * \brief Extract mantissa and exponent of the floating-point input argument. + * + * Decompose the floating-point value \p x into a component \p m for the + * normalized fraction element and an integral term \p n for the exponent. + * The absolute value of \p m will be greater than or equal to 0.5 and + * less than 1.0 or it will be equal to 0; + * \cuda_math_formula x = m\cdot 2^n \end_cuda_math_formula. + * The integer exponent \p n will be stored in the location to which \p nptr points. + * + * \return + * The fractional component \p m. + * - __nv_fp128_frexp( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * , \p nptr) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * and stores zero in the location pointed to by \p nptr. + * - __nv_fp128_frexp( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * , \p nptr) returns + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * and stores an unspecified value in the + * location to which \p nptr points. + * - __nv_fp128_frexp(NaN, \p y) returns a NaN and stores an unspecified value in the location to which \p nptr points. + * + * \note_accuracy_quad + * \note_fp128_target_arch + */ +__DEVICE_FP128_FUNCTIONS_DECL__ __float128 __nv_fp128_frexp(__float128 x, int* nptr) __DEF_IF_HOST +/** + * \ingroup CUDA_MATH_QUAD + * \brief Break down the input argument into fractional and integral parts. + * + * Break down the argument \p x into fractional and integral parts. The + * integral part is stored in floating-point format in the location to which \p iptr points. + * Fractional and integral parts are given the same sign as the argument \p x. + * + * \return + * - __nv_fp128_modf( + * \cuda_math_formula \pm x \end_cuda_math_formula + * , \p iptr) returns a result with the same sign as \p x. + * - __nv_fp128_modf( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * , \p iptr) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * and stores + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * in the object pointed to by \p iptr. + * - __nv_fp128_modf(NaN, \p iptr) stores a NaN in the object pointed to by \p iptr and returns a NaN. + * + * \note_accuracy_quad + * \note_fp128_target_arch + */ +__DEVICE_FP128_FUNCTIONS_DECL__ __float128 __nv_fp128_modf(__float128 x, __float128* iptr) __DEF_IF_HOST +/** + * \ingroup CUDA_MATH_QUAD + * \brief Calculate \cuda_math_formula \sqrt{x^2+y^2} \end_cuda_math_formula, the square root of the sum of squares of two arguments. + * + * \return + * The length of the hypotenuse of a right triangle whose two sides have lengths + * \cuda_math_formula |x| \end_cuda_math_formula and \cuda_math_formula |y| \end_cuda_math_formula without undue overflow or underflow. + * - __nv_fp128_hypot(\p x,\p y), __nv_fp128_hypot(\p y,\p x), and __nv_fp128_hypot(\p x, \p -y) are equivalent. + * - __nv_fp128_hypot(\p x, + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) is equivalent to __nv_fp128_fabs(\p x). + * - __nv_fp128_hypot( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ,\p y) returns + * \cuda_math_formula +\infty \end_cuda_math_formula, + * even if \p y is a NaN. + * - __nv_fp128_hypot(NaN, \p y) returns NaN, when \p y is not \cuda_math_formula \pm\infty \end_cuda_math_formula. + * + * \note_accuracy_quad + * \note_fp128_target_arch + */ +__DEVICE_FP128_FUNCTIONS_DECL__ __float128 __nv_fp128_hypot(__float128 x, __float128 y) __DEF_IF_HOST +/** + * \ingroup CUDA_MATH_QUAD + * \brief Compute + * \cuda_math_formula x \times y + z \end_cuda_math_formula + * as a single operation using round-to-nearest-even rounding mode. + * + * \return + * The value of + * \cuda_math_formula x \times y + z \end_cuda_math_formula + * as a single ternary operation, rounded once using round-to-nearest, + * ties-to-even rounding mode. + * - __nv_fp128_fma( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * , + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * , \p z) returns NaN. + * - __nv_fp128_fma( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * , + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * , \p z) returns NaN. + * - __nv_fp128_fma(\p x, \p y, + * \cuda_math_formula -\infty \end_cuda_math_formula + * ) returns NaN if + * \cuda_math_formula x \times y \end_cuda_math_formula + * is an exact + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - __nv_fp128_fma(\p x, \p y, + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns NaN if + * \cuda_math_formula x \times y \end_cuda_math_formula + * is an exact + * \cuda_math_formula -\infty \end_cuda_math_formula. + * - __nv_fp128_fma(\p x, \p y, \cuda_math_formula \pm 0 \end_cuda_math_formula) returns \cuda_math_formula \pm 0 \end_cuda_math_formula if \cuda_math_formula x \times y \end_cuda_math_formula is exact \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - __nv_fp128_fma(\p x, \p y, \cuda_math_formula \mp 0 \end_cuda_math_formula) returns \cuda_math_formula +0 \end_cuda_math_formula if \cuda_math_formula x \times y \end_cuda_math_formula is exact \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - __nv_fp128_fma(\p x, \p y, \p z) returns \cuda_math_formula +0 \end_cuda_math_formula if \cuda_math_formula x \times y + z \end_cuda_math_formula is exactly zero and \cuda_math_formula z \neq 0 \end_cuda_math_formula. + * - If either argument is NaN, NaN is returned. + * + * \note_accuracy_quad + * \note_fp128_target_arch + */ +__DEVICE_FP128_FUNCTIONS_DECL__ __float128 __nv_fp128_fma(__float128 x, __float128 y, __float128 c) __DEF_IF_HOST +/** + * \ingroup CUDA_MATH_QUAD + * \brief Calculate the value of + * \cuda_math_formula x\cdot 2^{exp} \end_cuda_math_formula. + * + * \return + * - __nv_fp128_ldexp( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * , \p exp) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - __nv_fp128_ldexp(\p x, 0) returns \p x. + * - __nv_fp128_ldexp( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * , \p exp) returns + * \cuda_math_formula \pm \infty \end_cuda_math_formula. + * - __nv_fp128_ldexp(NaN, \p exp) returns NaN. + * + * \note_accuracy_quad + * \note_fp128_target_arch + */ +__DEVICE_FP128_FUNCTIONS_DECL__ __float128 __nv_fp128_ldexp(__float128 x, int exp) __DEF_IF_HOST +/** + * \ingroup CUDA_MATH_QUAD + * \brief Compute the unbiased integer exponent of the input argument. + * + * \return + * - If successful, returns the unbiased exponent of the argument. + * - __nv_fp128_ilogb( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns INT_MIN. + * - __nv_fp128_ilogb(NaN) returns INT_MIN. + * - __nv_fp128_ilogb( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns INT_MAX. + * - Note: above behavior does not take into account FP_ILOGB0 nor FP_ILOGBNAN. + * + * \note_accuracy_quad + * \note_fp128_target_arch + */ +__DEVICE_FP128_FUNCTIONS_DECL__ int __nv_fp128_ilogb(__float128 x) __DEF_IF_HOST +/** + * \ingroup CUDA_MATH_QUAD + * \brief Compute \cuda_math_formula x \cdot y \end_cuda_math_formula, the product of the two floating-point inputs using round-to-nearest-even rounding mode. + * + * \return Returns \p x * \p y. + * - sign of the product \p x * \p y is XOR of the signs of \p x and \p y when neither inputs nor result are NaN. + * - __nv_fp128_mul(\p x, \p y) is equivalent to __nv_fp128_mul(\p y, \p x). + * - __nv_fp128_mul(\p x, \cuda_math_formula \pm\infty \end_cuda_math_formula) returns \cuda_math_formula \infty \end_cuda_math_formula of appropriate sign for \p x \cuda_math_formula \neq 0 \end_cuda_math_formula. + * - __nv_fp128_mul(\cuda_math_formula \pm 0 \end_cuda_math_formula, \cuda_math_formula \pm\infty \end_cuda_math_formula) returns NaN. + * - __nv_fp128_mul(\cuda_math_formula \pm 0 \end_cuda_math_formula, \p y) returns \cuda_math_formula 0 \end_cuda_math_formula of appropriate sign for finite \p y. + * - If either argument is NaN, NaN is returned. + * + * \note_accuracy_quad + * \note_fp128_target_arch + */ +__DEVICE_FP128_FUNCTIONS_DECL__ __float128 __nv_fp128_mul(__float128 x, __float128 y) __DEF_IF_HOST +/** + * \ingroup CUDA_MATH_QUAD + * \brief Compute \cuda_math_formula x + y \end_cuda_math_formula, the sum of the two floating-point inputs using round-to-nearest-even rounding mode. + * + * \return Returns \p x + \p y. + * - __nv_fp128_add(\p x, \p y) is equivalent to __nv_fp128_add(\p y, \p x). + * - __nv_fp128_add(\p x, \cuda_math_formula \pm\infty \end_cuda_math_formula) returns \cuda_math_formula \pm\infty \end_cuda_math_formula for finite \p x. + * - __nv_fp128_add(\cuda_math_formula \pm\infty \end_cuda_math_formula, \cuda_math_formula \pm\infty \end_cuda_math_formula) returns \cuda_math_formula \pm\infty \end_cuda_math_formula. + * - __nv_fp128_add(\cuda_math_formula \pm\infty \end_cuda_math_formula, \cuda_math_formula \mp\infty \end_cuda_math_formula) returns NaN. + * - __nv_fp128_add(\cuda_math_formula \pm 0 \end_cuda_math_formula, \cuda_math_formula \pm 0 \end_cuda_math_formula) returns \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - __nv_fp128_add(\p x, \p -x) returns \cuda_math_formula +0 \end_cuda_math_formula for finite \p x, including \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - If either argument is NaN, NaN is returned. + * + * \note_accuracy_quad + * \note_fp128_target_arch + */ +__DEVICE_FP128_FUNCTIONS_DECL__ __float128 __nv_fp128_add(__float128 x, __float128 y) __DEF_IF_HOST +/** + * \ingroup CUDA_MATH_QUAD + * \brief Compute \cuda_math_formula x - y \end_cuda_math_formula, the difference of the two floating-point inputs using round-to-nearest-even rounding mode. + * + * \return Returns \p x - \p y. + * - __nv_fp128_sub(\cuda_math_formula \pm\infty \end_cuda_math_formula, \p y) returns \cuda_math_formula \pm\infty \end_cuda_math_formula for finite \p y. + * - __nv_fp128_sub(\p x, \cuda_math_formula \pm\infty \end_cuda_math_formula) returns \cuda_math_formula \mp\infty \end_cuda_math_formula for finite \p x. + * - __nv_fp128_sub(\cuda_math_formula \pm\infty \end_cuda_math_formula, \cuda_math_formula \pm\infty \end_cuda_math_formula) returns NaN. + * - __nv_fp128_sub(\cuda_math_formula \pm\infty \end_cuda_math_formula, \cuda_math_formula \mp\infty \end_cuda_math_formula) returns \cuda_math_formula \pm\infty \end_cuda_math_formula. + * - __nv_fp128_sub(\cuda_math_formula \pm 0 \end_cuda_math_formula, \cuda_math_formula \mp 0 \end_cuda_math_formula) returns \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - __nv_fp128_sub(\p x, \p x) returns \cuda_math_formula +0 \end_cuda_math_formula for finite \p x, including \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - If either argument is NaN, NaN is returned. + * + * \note_accuracy_quad + * \note_fp128_target_arch + */ +__DEVICE_FP128_FUNCTIONS_DECL__ __float128 __nv_fp128_sub(__float128 x, __float128 y) __DEF_IF_HOST +/** + * \ingroup CUDA_MATH_QUAD + * \brief Compute \cuda_math_formula \frac{x}{y} \end_cuda_math_formula, the quotient of the two floating-point inputs using round-to-nearest-even rounding mode. + * + * \return + * - sign of the quotient \p x / \p y is XOR of the signs of \p x and \p y when neither inputs nor result are NaN. + * - __nv_fp128_div(\cuda_math_formula \pm 0 \end_cuda_math_formula, \cuda_math_formula \pm 0 \end_cuda_math_formula) returns NaN. + * - __nv_fp128_div(\cuda_math_formula \pm\infty \end_cuda_math_formula, \cuda_math_formula \pm\infty \end_cuda_math_formula) returns NaN. + * - __nv_fp128_div(\p x, \cuda_math_formula \pm\infty \end_cuda_math_formula) returns \cuda_math_formula 0 \end_cuda_math_formula of appropriate sign for finite \p x. + * - __nv_fp128_div(\cuda_math_formula \pm\infty \end_cuda_math_formula, \p y) returns \cuda_math_formula \infty \end_cuda_math_formula of appropriate sign for finite \p y. + * - __nv_fp128_div(\p x, \cuda_math_formula \pm 0 \end_cuda_math_formula) returns \cuda_math_formula \infty \end_cuda_math_formula of appropriate sign for \p x \cuda_math_formula \neq 0 \end_cuda_math_formula. + * - __nv_fp128_div(\cuda_math_formula \pm 0 \end_cuda_math_formula, \p y) returns \cuda_math_formula 0 \end_cuda_math_formula of appropriate sign for \p y \cuda_math_formula \neq 0 \end_cuda_math_formula. + * - If either argument is NaN, NaN is returned. + * + * \note_accuracy_quad + * \note_fp128_target_arch + */ +__DEVICE_FP128_FUNCTIONS_DECL__ __float128 __nv_fp128_div(__float128 x, __float128 y) __DEF_IF_HOST +/** + * \ingroup CUDA_MATH_QUAD + * \brief Determine whether the input argument is a NaN. + * + * \return + * A nonzero value if and only if \p x is a NaN value. + * + * \note_fp128_target_arch + */ +__DEVICE_FP128_FUNCTIONS_DECL__ int __nv_fp128_isnan(__float128 x) __DEF_IF_HOST +/** + * \ingroup CUDA_MATH_QUAD + * \brief Determine whether the pair of inputs is unordered. + * + * \return + * - nonzero value if at least one of input values is a NaN. + * - zero otherwise + * + * \note_fp128_target_arch + */ +__DEVICE_FP128_FUNCTIONS_DECL__ int __nv_fp128_isunordered(__float128 x, __float128 y) __DEF_IF_HOST +#endif /* __FLOAT128_CPP_SPELLING_ENABLED__ */ + + +#ifdef __FLOAT128_C_SPELLING_ENABLED__ +__DEVICE_FP128_FUNCTIONS_DECL__ _Float128 __nv_fp128_sqrt(_Float128 x) __DEF_IF_HOST +__DEVICE_FP128_FUNCTIONS_DECL__ _Float128 __nv_fp128_sin(_Float128 x) __DEF_IF_HOST +__DEVICE_FP128_FUNCTIONS_DECL__ _Float128 __nv_fp128_cos(_Float128 x) __DEF_IF_HOST +__DEVICE_FP128_FUNCTIONS_DECL__ _Float128 __nv_fp128_tan(_Float128 x) __DEF_IF_HOST +__DEVICE_FP128_FUNCTIONS_DECL__ _Float128 __nv_fp128_asin(_Float128 x) __DEF_IF_HOST +__DEVICE_FP128_FUNCTIONS_DECL__ _Float128 __nv_fp128_acos(_Float128 x) __DEF_IF_HOST +__DEVICE_FP128_FUNCTIONS_DECL__ _Float128 __nv_fp128_atan(_Float128 x) __DEF_IF_HOST +__DEVICE_FP128_FUNCTIONS_DECL__ _Float128 __nv_fp128_exp(_Float128 x) __DEF_IF_HOST +__DEVICE_FP128_FUNCTIONS_DECL__ _Float128 __nv_fp128_exp2(_Float128 x) __DEF_IF_HOST +__DEVICE_FP128_FUNCTIONS_DECL__ _Float128 __nv_fp128_exp10(_Float128 x) __DEF_IF_HOST +__DEVICE_FP128_FUNCTIONS_DECL__ _Float128 __nv_fp128_expm1(_Float128 x) __DEF_IF_HOST +__DEVICE_FP128_FUNCTIONS_DECL__ _Float128 __nv_fp128_log(_Float128 x) __DEF_IF_HOST +__DEVICE_FP128_FUNCTIONS_DECL__ _Float128 __nv_fp128_log2(_Float128 x) __DEF_IF_HOST +__DEVICE_FP128_FUNCTIONS_DECL__ _Float128 __nv_fp128_log10(_Float128 x) __DEF_IF_HOST +__DEVICE_FP128_FUNCTIONS_DECL__ _Float128 __nv_fp128_log1p(_Float128 x) __DEF_IF_HOST +__DEVICE_FP128_FUNCTIONS_DECL__ _Float128 __nv_fp128_pow(_Float128 x, _Float128 y) __DEF_IF_HOST +__DEVICE_FP128_FUNCTIONS_DECL__ _Float128 __nv_fp128_sinh(_Float128 x) __DEF_IF_HOST +__DEVICE_FP128_FUNCTIONS_DECL__ _Float128 __nv_fp128_cosh(_Float128 x) __DEF_IF_HOST +__DEVICE_FP128_FUNCTIONS_DECL__ _Float128 __nv_fp128_tanh(_Float128 x) __DEF_IF_HOST +__DEVICE_FP128_FUNCTIONS_DECL__ _Float128 __nv_fp128_asinh(_Float128 x) __DEF_IF_HOST +__DEVICE_FP128_FUNCTIONS_DECL__ _Float128 __nv_fp128_acosh(_Float128 x) __DEF_IF_HOST +__DEVICE_FP128_FUNCTIONS_DECL__ _Float128 __nv_fp128_atanh(_Float128 x) __DEF_IF_HOST +__DEVICE_FP128_FUNCTIONS_DECL__ _Float128 __nv_fp128_trunc(_Float128 x) __DEF_IF_HOST +__DEVICE_FP128_FUNCTIONS_DECL__ _Float128 __nv_fp128_floor(_Float128 x) __DEF_IF_HOST +__DEVICE_FP128_FUNCTIONS_DECL__ _Float128 __nv_fp128_ceil(_Float128 x) __DEF_IF_HOST +__DEVICE_FP128_FUNCTIONS_DECL__ _Float128 __nv_fp128_round(_Float128 x) __DEF_IF_HOST +__DEVICE_FP128_FUNCTIONS_DECL__ _Float128 __nv_fp128_rint(_Float128 x) __DEF_IF_HOST +__DEVICE_FP128_FUNCTIONS_DECL__ _Float128 __nv_fp128_fabs(_Float128 x) __DEF_IF_HOST +__DEVICE_FP128_FUNCTIONS_DECL__ _Float128 __nv_fp128_copysign(_Float128 x, _Float128 y) __DEF_IF_HOST +__DEVICE_FP128_FUNCTIONS_DECL__ _Float128 __nv_fp128_fmax(_Float128 x, _Float128 y) __DEF_IF_HOST +__DEVICE_FP128_FUNCTIONS_DECL__ _Float128 __nv_fp128_fmin(_Float128 x, _Float128 y) __DEF_IF_HOST +__DEVICE_FP128_FUNCTIONS_DECL__ _Float128 __nv_fp128_fdim(_Float128 x, _Float128 y) __DEF_IF_HOST +__DEVICE_FP128_FUNCTIONS_DECL__ _Float128 __nv_fp128_fmod(_Float128 x, _Float128 y) __DEF_IF_HOST +__DEVICE_FP128_FUNCTIONS_DECL__ _Float128 __nv_fp128_remainder(_Float128 x, _Float128 y) __DEF_IF_HOST +__DEVICE_FP128_FUNCTIONS_DECL__ _Float128 __nv_fp128_frexp(_Float128 x, int* nptr) __DEF_IF_HOST +__DEVICE_FP128_FUNCTIONS_DECL__ _Float128 __nv_fp128_modf(_Float128 x, _Float128* iptr) __DEF_IF_HOST +__DEVICE_FP128_FUNCTIONS_DECL__ _Float128 __nv_fp128_hypot(_Float128 x, _Float128 y) __DEF_IF_HOST +__DEVICE_FP128_FUNCTIONS_DECL__ _Float128 __nv_fp128_fma(_Float128 x, _Float128 y, _Float128 c) __DEF_IF_HOST +__DEVICE_FP128_FUNCTIONS_DECL__ _Float128 __nv_fp128_ldexp(_Float128 x, int exp) __DEF_IF_HOST +__DEVICE_FP128_FUNCTIONS_DECL__ int __nv_fp128_ilogb(_Float128 x) __DEF_IF_HOST +__DEVICE_FP128_FUNCTIONS_DECL__ _Float128 __nv_fp128_mul(_Float128 x, _Float128 y) __DEF_IF_HOST +__DEVICE_FP128_FUNCTIONS_DECL__ _Float128 __nv_fp128_add(_Float128 x, _Float128 y) __DEF_IF_HOST +__DEVICE_FP128_FUNCTIONS_DECL__ _Float128 __nv_fp128_sub(_Float128 x, _Float128 y) __DEF_IF_HOST +__DEVICE_FP128_FUNCTIONS_DECL__ _Float128 __nv_fp128_div(_Float128 x, _Float128 y) __DEF_IF_HOST +__DEVICE_FP128_FUNCTIONS_DECL__ int __nv_fp128_isnan(_Float128 x) __DEF_IF_HOST +__DEVICE_FP128_FUNCTIONS_DECL__ int __nv_fp128_isunordered(_Float128 x, _Float128 y) __DEF_IF_HOST +#endif /* __FLOAT_C_SPELLING_ENABLED */ + + +#undef __DEVICE_FP128_FUNCTIONS_DECL__ + +#endif /* __cplusplus && __CUDACC__ */ + +#endif /* !__DEVICE_FP128_FUNCTIONS_H__ */ + +#endif /* !__NV_DISABLE_DEVICE_FP128_FUNCTIONS__ */ diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/device_functions.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/device_functions.h new file mode 100644 index 0000000000000000000000000000000000000000..ae9de40d680c6e50c25b0c4a01c00679bd0c8fe4 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/device_functions.h @@ -0,0 +1,2993 @@ +/* + * Copyright 1993-2024 NVIDIA Corporation. All rights reserved. + * + * NOTICE TO LICENSEE: + * + * This source code and/or documentation ("Licensed Deliverables") are + * subject to NVIDIA intellectual property rights under U.S. and + * international Copyright laws. + * + * These Licensed Deliverables contained herein is PROPRIETARY and + * CONFIDENTIAL to NVIDIA and is being provided under the terms and + * conditions of a form of NVIDIA software license agreement by and + * between NVIDIA and Licensee ("License Agreement") or electronically + * accepted by Licensee. Notwithstanding any terms or conditions to + * the contrary in the License Agreement, reproduction or disclosure + * of the Licensed Deliverables to any third party without the express + * written consent of NVIDIA is prohibited. + * + * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE + * LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE + * SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE. IT IS + * PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND. + * NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED + * DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY, + * NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE. + * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE + * LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY + * SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY + * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS + * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THESE LICENSED DELIVERABLES. + * + * U.S. Government End Users. These Licensed Deliverables are a + * "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT + * 1995), consisting of "commercial computer software" and "commercial + * computer software documentation" as such terms are used in 48 + * C.F.R. 12.212 (SEPT 1995) and is provided to the U.S. Government + * only as a commercial end item. Consistent with 48 C.F.R.12.212 and + * 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all + * U.S. Government End Users acquire the Licensed Deliverables with + * only those rights set forth herein. + * + * Any use of the Licensed Deliverables in individual and commercial + * software must include, in the user documentation and internal + * comments to the code, the above Disclaimer and U.S. Government End + * Users Notice. + */ + +#if !defined(__CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__) +#if defined(_MSC_VER) +#pragma message("crt/device_functions.h is an internal header file and must not be used directly. Please use cuda_runtime_api.h or cuda_runtime.h instead.") +#else +#warning "crt/device_functions.h is an internal header file and must not be used directly. Please use cuda_runtime_api.h or cuda_runtime.h instead." +#endif +#define __CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__ +#define __UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_DEVICE_FUNCTIONS_H__ +#endif + +#if !defined(__DEVICE_FUNCTIONS_H__) +#define __DEVICE_FUNCTIONS_H__ + +/******************************************************************************* +* * +* * +* * +*******************************************************************************/ + +#if defined(__cplusplus) && defined(__CUDACC__) + +#if defined(__CUDACC_RTC__) +#define __DEVICE_FUNCTIONS_DECL__ __device__ __cudart_builtin__ +#define __DEVICE_FUNCTIONS_STATIC_DECL__ __device__ __cudart_builtin__ +#define __DEVICE_HOST_FUNCTIONS_STATIC_DECL__ __device__ __host__ __cudart_builtin__ +#else +#define __DEVICE_FUNCTIONS_DECL__ __device__ __cudart_builtin__ +#define __DEVICE_FUNCTIONS_STATIC_DECL__ static __inline__ __device__ __cudart_builtin__ +#define __DEVICE_HOST_FUNCTIONS_STATIC_DECL__ static __inline__ __device__ __host__ __cudart_builtin__ +#endif /* __CUDACC_RTC__ */ + +#include "builtin_types.h" +#include "device_types.h" +#include "host_defines.h" + + +//NOTE: For NVRTC, these declarations have been moved into the compiler (to reduce compile time) +#define EXCLUDE_FROM_RTC + +/******************************************************************************* +* * +* * +* * +*******************************************************************************/ + +extern "C" +{ +/** + * \ingroup CUDA_MATH_INTRINSIC_INT + * \brief Calculate the most significant 32 bits of the product of the two 32-bit integers. + * + * Calculate the most significant 32 bits of the 64-bit product \p x * \p y, where \p x and \p y + * are 32-bit integers. + * + * \return Returns the most significant 32 bits of the product \p x * \p y. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ int __mulhi(int x, int y); +/** + * \ingroup CUDA_MATH_INTRINSIC_INT + * \brief Calculate the most significant 32 bits of the product of the two 32-bit unsigned integers. + * + * Calculate the most significant 32 bits of the 64-bit product \p x * \p y, where \p x and \p y + * are 32-bit unsigned integers. + * + * \return Returns the most significant 32 bits of the product \p x * \p y. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __umulhi(unsigned int x, unsigned int y); +/** + * \ingroup CUDA_MATH_INTRINSIC_INT + * \brief Calculate the most significant 64 bits of the product of the two 64-bit integers. + * + * Calculate the most significant 64 bits of the 128-bit product \p x * \p y, where \p x and \p y + * are 64-bit integers. + * + * \return Returns the most significant 64 bits of the product \p x * \p y. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ long long int __mul64hi(long long int x, long long int y); +/** + * \ingroup CUDA_MATH_INTRINSIC_INT + * \brief Calculate the most significant 64 bits of the product of the two 64 unsigned bit integers. + * + * Calculate the most significant 64 bits of the 128-bit product \p x * \p y, where \p x and \p y + * are 64-bit unsigned integers. + * + * \return Returns the most significant 64 bits of the product \p x * \p y. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned long long int __umul64hi(unsigned long long int x, unsigned long long int y); +/** + * \ingroup CUDA_MATH_INTRINSIC_CAST + * \brief Reinterpret bits in an integer as a float. + * + * Reinterpret the bits in the signed integer value \p x as a single-precision + * floating-point value. + * \return Returns reinterpreted value. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __int_as_float(int x); +/** + * \ingroup CUDA_MATH_INTRINSIC_CAST + * \brief Reinterpret bits in a float as a signed integer. + * + * Reinterpret the bits in the single-precision floating-point value \p x + * as a signed integer. + * \return Returns reinterpreted value. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ int __float_as_int(float x); +/** + * \ingroup CUDA_MATH_INTRINSIC_CAST + * \brief Reinterpret bits in an unsigned integer as a float. + * + * Reinterpret the bits in the unsigned integer value \p x as a single-precision + * floating-point value. + * \return Returns reinterpreted value. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __uint_as_float(unsigned int x); +/** + * \ingroup CUDA_MATH_INTRINSIC_CAST + * \brief Reinterpret bits in a float as a unsigned integer. + * + * Reinterpret the bits in the single-precision floating-point value \p x + * as a unsigned integer. + * \return Returns reinterpreted value. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __float_as_uint(float x); +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ void __syncthreads(void); +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ void __prof_trigger(int); +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ void __threadfence(void); +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ void __threadfence_block(void); +__DEVICE_FUNCTIONS_DECL__ +#if defined(__GNUC__) || defined(__CUDACC_RTC__) +__attribute__((__noreturn__)) +#elif defined(_MSC_VER) +__declspec(noreturn) +#endif /* defined(__GNUC__) || defined(__CUDACC_RTC__) */ +__device_builtin__ void __trap(void); +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ void __brkpt(); +/** + * \ingroup CUDA_MATH_INTRINSIC_SINGLE + * \brief Clamp the input argument to [+0.0, 1.0]. + * + * Clamp the input argument \p x to be within the interval [+0.0, 1.0]. + * \return + * - __saturatef(\p x) returns +0 if \cuda_math_formula x \le 0 \end_cuda_math_formula. + * - __saturatef(\p x) returns 1 if \cuda_math_formula x \ge 1 \end_cuda_math_formula. + * - __saturatef(\p x) returns \p x if \cuda_math_formula 0 < x < 1 \end_cuda_math_formula. + * - __saturatef(NaN) returns +0. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __saturatef(float x); +/** + * \ingroup CUDA_MATH_INTRINSIC_INT + * \brief Calculate + * \cuda_math_formula |x - y| + z \end_cuda_math_formula + * , the sum of absolute difference. + * + * Calculate + * \cuda_math_formula |x - y| + z \end_cuda_math_formula + * , the 32-bit sum of the third argument \p z plus and the absolute + * value of the difference between the first argument, \p x, and second + * argument, \p y. + * + * Inputs \p x and \p y are signed 32-bit integers, input \p z is + * a 32-bit unsigned integer. + * + * \return Returns + * \cuda_math_formula |x - y| + z \end_cuda_math_formula. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __sad(int x, int y, unsigned int z); +/** + * \ingroup CUDA_MATH_INTRINSIC_INT + * \brief Calculate + * \cuda_math_formula |x - y| + z \end_cuda_math_formula + * , the sum of absolute difference. + * + * Calculate + * \cuda_math_formula |x - y| + z \end_cuda_math_formula + * , the 32-bit sum of the third argument \p z plus and the absolute + * value of the difference between the first argument, \p x, and second + * argument, \p y. + * + * Inputs \p x, \p y, and \p z are unsigned 32-bit integers. + * + * \return Returns + * \cuda_math_formula |x - y| + z \end_cuda_math_formula. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __usad(unsigned int x, unsigned int y, unsigned int z); +/** + * \ingroup CUDA_MATH_INTRINSIC_INT + * \brief Calculate the least significant 32 bits of the product of the least significant 24 bits of two integers. + * + * Calculate the least significant 32 bits of the product of the least significant 24 bits of \p x and \p y. + * The high order 8 bits of \p x and \p y are ignored. + * + * \return Returns the least significant 32 bits of the product \p x * \p y. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ int __mul24(int x, int y); +/** + * \ingroup CUDA_MATH_INTRINSIC_INT + * \brief Calculate the least significant 32 bits of the product of the least significant 24 bits of two unsigned integers. + * + * Calculate the least significant 32 bits of the product of the least significant 24 bits of \p x and \p y. + * The high order 8 bits of \p x and \p y are ignored. + * + * \return Returns the least significant 32 bits of the product \p x * \p y. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __umul24(unsigned int x, unsigned int y); +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Divide two floating-point values. + * + * Compute \p x divided by \p y. + * + * \return Returns \p x / \p y. + * - Follows the regular division operation behavior by default. + * - If \p -use_fast_math is specified and is not amended by + * an explicit \p -prec_div=true, uses ::__fdividef() for higher + * performance + * + * \note_accuracy_single + * \note_fastmath + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ float fdividef(float x, float y); +/** + * \ingroup CUDA_MATH_INTRINSIC_SINGLE + * \brief Calculate the fast approximate division of the input arguments. + * + * Calculate the fast approximate division of \p x by \p y. + * + * \return Returns \p x / \p y. + * - __fdividef( + * \cuda_math_formula \infty \end_cuda_math_formula + * , \p y) returns NaN for + * \cuda_math_formula 2^{126} < |y| < 2^{128} \end_cuda_math_formula. + * - __fdividef(\p x, \p y) returns 0 for + * \cuda_math_formula 2^{126} < |y| < 2^{128} \end_cuda_math_formula + * and finite + * \cuda_math_formula x \end_cuda_math_formula. + * \see __fdiv_rn() for further special case behavior specification. + * + * \note_accuracy_single_intrinsic + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __fdividef(float x, float y); +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ double fdivide(double x, double y); +/** + * \ingroup CUDA_MATH_INTRINSIC_SINGLE + * \brief Calculate the fast approximate sine of the input argument. + * + * Calculate the fast approximate sine of the input argument \p x, measured in radians. + * + * \return Returns the approximate sine of \p x. + * + * \see sinf() for further special case behavior specification. + * \note_accuracy_single_intrinsic + * \note Output in the denormal range is flushed to sign preserving 0.0. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ __cudart_builtin__ float __sinf(float x) __THROW; +/** + * \ingroup CUDA_MATH_INTRINSIC_SINGLE + * \brief Calculate the fast approximate cosine of the input argument. + * + * Calculate the fast approximate cosine of the input argument \p x, measured in radians. + * + * \return Returns the approximate cosine of \p x. + * + * \see cosf() for further special case behavior specification. + * \note_accuracy_single_intrinsic + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ __cudart_builtin__ float __cosf(float x) __THROW; +/** + * \ingroup CUDA_MATH_INTRINSIC_SINGLE + * \brief Calculate the fast approximate tangent of the input argument. + * + * Calculate the fast approximate tangent of the input argument \p x, measured in radians. + * + * \return Returns the approximate tangent of \p x. + * + * \note_accuracy_single_intrinsic + * \note The result is computed as the fast divide of ::__sinf() + * by ::__cosf(). Denormal output is flushed to sign-preserving 0.0. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ __cudart_builtin__ float __tanf(float x) __THROW; +/** + * \ingroup CUDA_MATH_INTRINSIC_SINGLE + * \brief Calculate the fast approximate hyperbolic tangent of the input argument. + * + * Calculate the fast approximate hyperbolic tangent of the input argument \p x, measured in radians. + * + * \return Returns the approximate hyperbolic tangent of \p x. + * + * \see tanhf() for further special case behavior specification. + * \note_accuracy_single_intrinsic + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ __cudart_builtin__ float __tanhf(float x) __THROW; +/** + * \ingroup CUDA_MATH_INTRINSIC_SINGLE + * \brief Calculate the fast approximate of sine and cosine of the first input argument. + * + * Calculate the fast approximate of sine and cosine of the first input argument \p x (measured + * in radians). The results for sine and cosine are written into the second + * argument, \p sptr, and, respectively, third argument, \p cptr. + * + * \see __sinf() and __cosf(). + * \note_accuracy_single_intrinsic + * \note Denorm input/output is flushed to sign preserving 0.0. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ __cudart_builtin__ void __sincosf(float x, float *sptr, float *cptr) __THROW; +/** + * \ingroup CUDA_MATH_INTRINSIC_SINGLE + * \brief Calculate the fast approximate base + * \cuda_math_formula e \end_cuda_math_formula + * exponential of the input argument. + * + * Calculate the fast approximate base + * \cuda_math_formula e \end_cuda_math_formula + * exponential of the input argument \p x, + * \cuda_math_formula e^x \end_cuda_math_formula. + * + * \return Returns an approximation to + * \cuda_math_formula e^x \end_cuda_math_formula. + * \see expf() for further special case behavior specification. + * + * \note_accuracy_single_intrinsic + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ __cudart_builtin__ float __expf(float x) __THROW; +/** + * \ingroup CUDA_MATH_INTRINSIC_SINGLE + * \brief Calculate the fast approximate base 10 exponential of the input argument. + * + * Calculate the fast approximate base 10 exponential of the input argument \p x, + * \cuda_math_formula 10^x \end_cuda_math_formula. + * + * \return Returns an approximation to + * \cuda_math_formula 10^x \end_cuda_math_formula. + * \see exp10f() for further special case behavior specification. + * + * \note_accuracy_single_intrinsic + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ __cudart_builtin__ float __exp10f(float x) __THROW; +/** + * \ingroup CUDA_MATH_INTRINSIC_SINGLE + * \brief Calculate the fast approximate base 2 logarithm of the input argument. + * + * Calculate the fast approximate base 2 logarithm of the input argument \p x. + * + * \return Returns an approximation to + * \cuda_math_formula \log_2(x) \end_cuda_math_formula. + * \see log2f() for further special case behavior specification. + * + * \note_accuracy_single_intrinsic + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ __cudart_builtin__ float __log2f(float x) __THROW; +/** + * \ingroup CUDA_MATH_INTRINSIC_SINGLE + * \brief Calculate the fast approximate base 10 logarithm of the input argument. + * + * Calculate the fast approximate base 10 logarithm of the input argument \p x. + * + * \return Returns an approximation to + * \cuda_math_formula \log_{10}(x) \end_cuda_math_formula. + * \see log10f() for further special case behavior specification. + * + * \note_accuracy_single_intrinsic + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ __cudart_builtin__ float __log10f(float x) __THROW; +/** + * \ingroup CUDA_MATH_INTRINSIC_SINGLE + * \brief Calculate the fast approximate base + * \cuda_math_formula e \end_cuda_math_formula + * logarithm of the input argument. + * + * Calculate the fast approximate base + * \cuda_math_formula e \end_cuda_math_formula + * logarithm of the input argument \p x. + * + * \return Returns an approximation to + * \cuda_math_formula \log_e(x) \end_cuda_math_formula. + * \see logf() for further special case behavior specification. + * + * \note_accuracy_single_intrinsic + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ __cudart_builtin__ float __logf(float x) __THROW; +/** + * \ingroup CUDA_MATH_INTRINSIC_SINGLE + * \brief Calculate the fast approximate of + * \cuda_math_formula x^y \end_cuda_math_formula. + * + * Calculate the fast approximate of \p x, the first input argument, + * raised to the power of \p y, the second input argument, + * \cuda_math_formula x^y \end_cuda_math_formula. + * + * \return Returns an approximation to + * \cuda_math_formula x^y \end_cuda_math_formula. + * + * \note_accuracy_single_intrinsic + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ __cudart_builtin__ float __powf(float x, float y) __THROW; +/** + * \ingroup CUDA_MATH_INTRINSIC_CAST + * \brief Convert a float to a signed integer in round-to-nearest-even mode. + * + * Convert the single-precision floating-point value \p x to a signed integer + * in round-to-nearest-even mode. + * \return Returns converted value. + * \note_fp_to_int_out_of_range_undefined + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ int __float2int_rn(float x); +/** + * \ingroup CUDA_MATH_INTRINSIC_CAST + * \brief Convert a float to a signed integer in round-towards-zero mode. + * + * Convert the single-precision floating-point value \p x to a signed integer + * in round-towards-zero mode. + * \return Returns converted value. + * \note_fp_to_int_out_of_range_undefined + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ int __float2int_rz(float x); +/** + * \ingroup CUDA_MATH_INTRINSIC_CAST + * \brief Convert a float to a signed integer in round-up mode. + * + * Convert the single-precision floating-point value \p x to a signed integer + * in round-up (to positive infinity) mode. + * \return Returns converted value. + * \note_fp_to_int_out_of_range_undefined + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ int __float2int_ru(float); +/** + * \ingroup CUDA_MATH_INTRINSIC_CAST + * \brief Convert a float to a signed integer in round-down mode. + * + * Convert the single-precision floating-point value \p x to a signed integer + * in round-down (to negative infinity) mode. + * \return Returns converted value. + * \note_fp_to_int_out_of_range_undefined + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ int __float2int_rd(float x); +/** + * \ingroup CUDA_MATH_INTRINSIC_CAST + * \brief Convert a float to an unsigned integer in round-to-nearest-even mode. + * + * Convert the single-precision floating-point value \p x to an unsigned integer + * in round-to-nearest-even mode. + * \return Returns converted value. + * \note_fp_to_int_out_of_range_undefined + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __float2uint_rn(float x); +/** + * \ingroup CUDA_MATH_INTRINSIC_CAST + * \brief Convert a float to an unsigned integer in round-towards-zero mode. + * + * Convert the single-precision floating-point value \p x to an unsigned integer + * in round-towards-zero mode. + * \return Returns converted value. + * \note_fp_to_int_out_of_range_undefined + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __float2uint_rz(float x); +/** + * \ingroup CUDA_MATH_INTRINSIC_CAST + * \brief Convert a float to an unsigned integer in round-up mode. + * + * Convert the single-precision floating-point value \p x to an unsigned integer + * in round-up (to positive infinity) mode. + * \return Returns converted value. + * \note_fp_to_int_out_of_range_undefined + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __float2uint_ru(float x); +/** + * \ingroup CUDA_MATH_INTRINSIC_CAST + * \brief Convert a float to an unsigned integer in round-down mode. + * + * Convert the single-precision floating-point value \p x to an unsigned integer + * in round-down (to negative infinity) mode. + * \return Returns converted value. + * \note_fp_to_int_out_of_range_undefined + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __float2uint_rd(float x); +/** + * \ingroup CUDA_MATH_INTRINSIC_CAST + * \brief Convert a signed integer to a float in round-to-nearest-even mode. + * + * Convert the signed integer value \p x to a single-precision floating-point value + * in round-to-nearest-even mode. + * \return Returns converted value. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __int2float_rn(int x); +/** + * \ingroup CUDA_MATH_INTRINSIC_CAST + * \brief Convert a signed integer to a float in round-towards-zero mode. + * + * Convert the signed integer value \p x to a single-precision floating-point value + * in round-towards-zero mode. + * \return Returns converted value. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __int2float_rz(int x); +/** + * \ingroup CUDA_MATH_INTRINSIC_CAST + * \brief Convert a signed integer to a float in round-up mode. + * + * Convert the signed integer value \p x to a single-precision floating-point value + * in round-up (to positive infinity) mode. + * \return Returns converted value. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __int2float_ru(int x); +/** + * \ingroup CUDA_MATH_INTRINSIC_CAST + * \brief Convert a signed integer to a float in round-down mode. + * + * Convert the signed integer value \p x to a single-precision floating-point value + * in round-down (to negative infinity) mode. + * \return Returns converted value. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __int2float_rd(int x); +/** + * \ingroup CUDA_MATH_INTRINSIC_CAST + * \brief Convert an unsigned integer to a float in round-to-nearest-even mode. + * + * Convert the unsigned integer value \p x to a single-precision floating-point value + * in round-to-nearest-even mode. + * \return Returns converted value. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __uint2float_rn(unsigned int x); +/** + * \ingroup CUDA_MATH_INTRINSIC_CAST + * \brief Convert an unsigned integer to a float in round-towards-zero mode. + * + * Convert the unsigned integer value \p x to a single-precision floating-point value + * in round-towards-zero mode. + * \return Returns converted value. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __uint2float_rz(unsigned int x); +/** + * \ingroup CUDA_MATH_INTRINSIC_CAST + * \brief Convert an unsigned integer to a float in round-up mode. + * + * Convert the unsigned integer value \p x to a single-precision floating-point value + * in round-up (to positive infinity) mode. + * \return Returns converted value. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __uint2float_ru(unsigned int x); +/** + * \ingroup CUDA_MATH_INTRINSIC_CAST + * \brief Convert an unsigned integer to a float in round-down mode. + * + * Convert the unsigned integer value \p x to a single-precision floating-point value + * in round-down (to negative infinity) mode. + * \return Returns converted value. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __uint2float_rd(unsigned int x); +/** + * \ingroup CUDA_MATH_INTRINSIC_CAST + * \brief Convert a float to a signed 64-bit integer in round-to-nearest-even mode. + * + * Convert the single-precision floating-point value \p x to a signed 64-bit integer + * in round-to-nearest-even mode. + * \return Returns converted value. + * \note_fp_to_int_out_of_range_undefined + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ long long int __float2ll_rn(float x); +/** + * \ingroup CUDA_MATH_INTRINSIC_CAST + * \brief Convert a float to a signed 64-bit integer in round-towards-zero mode. + * + * Convert the single-precision floating-point value \p x to a signed 64-bit integer + * in round-towards-zero mode. + * \return Returns converted value. + * \note_fp_to_int_out_of_range_undefined + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ long long int __float2ll_rz(float x); +/** + * \ingroup CUDA_MATH_INTRINSIC_CAST + * \brief Convert a float to a signed 64-bit integer in round-up mode. + * + * Convert the single-precision floating-point value \p x to a signed 64-bit integer + * in round-up (to positive infinity) mode. + * \return Returns converted value. + * \note_fp_to_int_out_of_range_undefined + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ long long int __float2ll_ru(float x); +/** + * \ingroup CUDA_MATH_INTRINSIC_CAST + * \brief Convert a float to a signed 64-bit integer in round-down mode. + * + * Convert the single-precision floating-point value \p x to a signed 64-bit integer + * in round-down (to negative infinity) mode. + * \return Returns converted value. + * \note_fp_to_int_out_of_range_undefined + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ long long int __float2ll_rd(float x); +/** + * \ingroup CUDA_MATH_INTRINSIC_CAST + * \brief Convert a float to an unsigned 64-bit integer in round-to-nearest-even mode. + * + * Convert the single-precision floating-point value \p x to an unsigned 64-bit integer + * in round-to-nearest-even mode. + * \return Returns converted value. + * \note_fp_to_int_out_of_range_undefined + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned long long int __float2ull_rn(float x); +/** + * \ingroup CUDA_MATH_INTRINSIC_CAST + * \brief Convert a float to an unsigned 64-bit integer in round-towards-zero mode. + * + * Convert the single-precision floating-point value \p x to an unsigned 64-bit integer + * in round-towards-zero mode. + * \return Returns converted value. + * \note_fp_to_int_out_of_range_undefined + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned long long int __float2ull_rz(float x); +/** + * \ingroup CUDA_MATH_INTRINSIC_CAST + * \brief Convert a float to an unsigned 64-bit integer in round-up mode. + * + * Convert the single-precision floating-point value \p x to an unsigned 64-bit integer + * in round-up (to positive infinity) mode. + * \return Returns converted value. + * \note_fp_to_int_out_of_range_undefined + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned long long int __float2ull_ru(float x); +/** + * \ingroup CUDA_MATH_INTRINSIC_CAST + * \brief Convert a float to an unsigned 64-bit integer in round-down mode. + * + * Convert the single-precision floating-point value \p x to an unsigned 64-bit integer + * in round-down (to negative infinity) mode. + * \return Returns converted value. + * \note_fp_to_int_out_of_range_undefined + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned long long int __float2ull_rd(float x); +/** + * \ingroup CUDA_MATH_INTRINSIC_CAST + * \brief Convert a signed 64-bit integer to a float in round-to-nearest-even mode. + * + * Convert the signed 64-bit integer value \p x to a single-precision floating-point value + * in round-to-nearest-even mode. + * \return Returns converted value. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __ll2float_rn(long long int x); +/** + * \ingroup CUDA_MATH_INTRINSIC_CAST + * \brief Convert a signed integer to a float in round-towards-zero mode. + * + * Convert the signed integer value \p x to a single-precision floating-point value + * in round-towards-zero mode. + * \return Returns converted value. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __ll2float_rz(long long int x); +/** + * \ingroup CUDA_MATH_INTRINSIC_CAST + * \brief Convert a signed integer to a float in round-up mode. + * + * Convert the signed integer value \p x to a single-precision floating-point value + * in round-up (to positive infinity) mode. + * \return Returns converted value. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __ll2float_ru(long long int x); +/** + * \ingroup CUDA_MATH_INTRINSIC_CAST + * \brief Convert a signed integer to a float in round-down mode. + * + * Convert the signed integer value \p x to a single-precision floating-point value + * in round-down (to negative infinity) mode. + * \return Returns converted value. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __ll2float_rd(long long int x); +/** + * \ingroup CUDA_MATH_INTRINSIC_CAST + * \brief Convert an unsigned integer to a float in round-to-nearest-even mode. + * + * Convert the unsigned integer value \p x to a single-precision floating-point value + * in round-to-nearest-even mode. + * \return Returns converted value. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __ull2float_rn(unsigned long long int x); +/** + * \ingroup CUDA_MATH_INTRINSIC_CAST + * \brief Convert an unsigned integer to a float in round-towards-zero mode. + * + * Convert the unsigned integer value \p x to a single-precision floating-point value + * in round-towards-zero mode. + * \return Returns converted value. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __ull2float_rz(unsigned long long int x); +/** + * \ingroup CUDA_MATH_INTRINSIC_CAST + * \brief Convert an unsigned integer to a float in round-up mode. + * + * Convert the unsigned integer value \p x to a single-precision floating-point value + * in round-up (to positive infinity) mode. + * \return Returns converted value. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __ull2float_ru(unsigned long long int x); +/** + * \ingroup CUDA_MATH_INTRINSIC_CAST + * \brief Convert an unsigned integer to a float in round-down mode. + * + * Convert the unsigned integer value \p x to a single-precision floating-point value + * in round-down (to negative infinity) mode. + * \return Returns converted value. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __ull2float_rd(unsigned long long int x); +/** + * \ingroup CUDA_MATH_INTRINSIC_SINGLE + * \brief Add two floating-point values in round-to-nearest-even mode. + * + * Compute the sum of \p x and \p y in round-to-nearest-even rounding mode. + * + * \return Returns \p x + \p y. + * - __fadd_rn(\p x, \p y) is equivalent to __fadd_rn(\p y, \p x). + * - __fadd_rn(\p x, \cuda_math_formula \pm\infty \end_cuda_math_formula) returns \cuda_math_formula \pm\infty \end_cuda_math_formula for finite \p x. + * - __fadd_rn(\cuda_math_formula \pm\infty \end_cuda_math_formula, \cuda_math_formula \pm\infty \end_cuda_math_formula) returns \cuda_math_formula \pm\infty \end_cuda_math_formula. + * - __fadd_rn(\cuda_math_formula \pm\infty \end_cuda_math_formula, \cuda_math_formula \mp\infty \end_cuda_math_formula) returns NaN. + * - __fadd_rn(\cuda_math_formula \pm 0 \end_cuda_math_formula, \cuda_math_formula \pm 0 \end_cuda_math_formula) returns \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - __fadd_rn(\p x, \p -x) returns \cuda_math_formula +0 \end_cuda_math_formula for finite \p x, including \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - If either argument is NaN, NaN is returned. + * + * \note_accuracy_single_intrinsic + * \note_nofma + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __fadd_rn(float x, float y); +/** + * \ingroup CUDA_MATH_INTRINSIC_SINGLE + * \brief Add two floating-point values in round-towards-zero mode. + * + * Compute the sum of \p x and \p y in round-towards-zero mode. + * + * \return Returns \p x + \p y. + * - __fadd_rz(\p x, \p y) is equivalent to __fadd_rz(\p y, \p x). + * - __fadd_rz(\p x, \cuda_math_formula \pm\infty \end_cuda_math_formula) returns \cuda_math_formula \pm\infty \end_cuda_math_formula for finite \p x. + * - __fadd_rz(\cuda_math_formula \pm\infty \end_cuda_math_formula, \cuda_math_formula \pm\infty \end_cuda_math_formula) returns \cuda_math_formula \pm\infty \end_cuda_math_formula. + * - __fadd_rz(\cuda_math_formula \pm\infty \end_cuda_math_formula, \cuda_math_formula \mp\infty \end_cuda_math_formula) returns NaN. + * - __fadd_rz(\cuda_math_formula \pm 0 \end_cuda_math_formula, \cuda_math_formula \pm 0 \end_cuda_math_formula) returns \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - __fadd_rz(\p x, \p -x) returns \cuda_math_formula +0 \end_cuda_math_formula for finite \p x, including \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - If either argument is NaN, NaN is returned. + * + * \note_accuracy_single_intrinsic + * \note_nofma + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __fadd_rz(float x, float y); +/** + * \ingroup CUDA_MATH_INTRINSIC_SINGLE + * \brief Add two floating-point values in round-up mode. + * + * Compute the sum of \p x and \p y in round-up (to positive infinity) mode. + * + * \return Returns \p x + \p y. + * - __fadd_ru(\p x, \p y) is equivalent to __fadd_ru(\p y, \p x). + * - __fadd_ru(\p x, \cuda_math_formula \pm\infty \end_cuda_math_formula) returns \cuda_math_formula \pm\infty \end_cuda_math_formula for finite \p x. + * - __fadd_ru(\cuda_math_formula \pm\infty \end_cuda_math_formula, \cuda_math_formula \pm\infty \end_cuda_math_formula) returns \cuda_math_formula \pm\infty \end_cuda_math_formula. + * - __fadd_ru(\cuda_math_formula \pm\infty \end_cuda_math_formula, \cuda_math_formula \mp\infty \end_cuda_math_formula) returns NaN. + * - __fadd_ru(\cuda_math_formula \pm 0 \end_cuda_math_formula, \cuda_math_formula \pm 0 \end_cuda_math_formula) returns \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - __fadd_ru(\p x, \p -x) returns \cuda_math_formula +0 \end_cuda_math_formula for finite \p x, including \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - If either argument is NaN, NaN is returned. + * + * \note_accuracy_single_intrinsic + * \note_nofma + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __fadd_ru(float x, float y); +/** + * \ingroup CUDA_MATH_INTRINSIC_SINGLE + * \brief Add two floating-point values in round-down mode. + * + * Compute the sum of \p x and \p y in round-down (to negative infinity) mode. + * + * \return Returns \p x + \p y. + * - __fadd_rd(\p x, \p y) is equivalent to __fadd_rd(\p y, \p x). + * - __fadd_rd(\p x, \cuda_math_formula \pm\infty \end_cuda_math_formula) returns \cuda_math_formula \pm\infty \end_cuda_math_formula for finite \p x. + * - __fadd_rd(\cuda_math_formula \pm\infty \end_cuda_math_formula, \cuda_math_formula \pm\infty \end_cuda_math_formula) returns \cuda_math_formula \pm\infty \end_cuda_math_formula. + * - __fadd_rd(\cuda_math_formula \pm\infty \end_cuda_math_formula, \cuda_math_formula \mp\infty \end_cuda_math_formula) returns NaN. + * - __fadd_rd(\cuda_math_formula \pm 0 \end_cuda_math_formula, \cuda_math_formula \pm 0 \end_cuda_math_formula) returns \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - __fadd_rd(\p x, \p -x) returns \cuda_math_formula -0 \end_cuda_math_formula for finite \p x, including \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - If either argument is NaN, NaN is returned. + * + * \note_accuracy_single_intrinsic + * \note_nofma + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __fadd_rd(float x, float y); +/** + * \ingroup CUDA_MATH_INTRINSIC_SINGLE + * \brief Subtract two floating-point values in round-to-nearest-even mode. + * + * Compute the difference of \p x and \p y in round-to-nearest-even rounding mode. + * + * \return Returns \p x - \p y. + * - __fsub_rn(\cuda_math_formula \pm\infty \end_cuda_math_formula, \p y) returns \cuda_math_formula \pm\infty \end_cuda_math_formula for finite \p y. + * - __fsub_rn(\p x, \cuda_math_formula \pm\infty \end_cuda_math_formula) returns \cuda_math_formula \mp\infty \end_cuda_math_formula for finite \p x. + * - __fsub_rn(\cuda_math_formula \pm\infty \end_cuda_math_formula, \cuda_math_formula \pm\infty \end_cuda_math_formula) returns NaN. + * - __fsub_rn(\cuda_math_formula \pm\infty \end_cuda_math_formula, \cuda_math_formula \mp\infty \end_cuda_math_formula) returns \cuda_math_formula \pm\infty \end_cuda_math_formula. + * - __fsub_rn(\cuda_math_formula \pm 0 \end_cuda_math_formula, \cuda_math_formula \mp 0 \end_cuda_math_formula) returns \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - __fsub_rn(\p x, \p x) returns \cuda_math_formula +0 \end_cuda_math_formula for finite \p x, including \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - If either argument is NaN, NaN is returned. + * + * \note_accuracy_single_intrinsic + * \note_nofma + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __fsub_rn(float x, float y); +/** + * \ingroup CUDA_MATH_INTRINSIC_SINGLE + * \brief Subtract two floating-point values in round-towards-zero mode. + * + * Compute the difference of \p x and \p y in round-towards-zero mode. + * + * \return Returns \p x - \p y. + * - __fsub_rz(\cuda_math_formula \pm\infty \end_cuda_math_formula, \p y) returns \cuda_math_formula \pm\infty \end_cuda_math_formula for finite \p y. + * - __fsub_rz(\p x, \cuda_math_formula \pm\infty \end_cuda_math_formula) returns \cuda_math_formula \mp\infty \end_cuda_math_formula for finite \p x. + * - __fsub_rz(\cuda_math_formula \pm\infty \end_cuda_math_formula, \cuda_math_formula \pm\infty \end_cuda_math_formula) returns NaN. + * - __fsub_rz(\cuda_math_formula \pm\infty \end_cuda_math_formula, \cuda_math_formula \mp\infty \end_cuda_math_formula) returns \cuda_math_formula \pm\infty \end_cuda_math_formula. + * - __fsub_rz(\cuda_math_formula \pm 0 \end_cuda_math_formula, \cuda_math_formula \mp 0 \end_cuda_math_formula) returns \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - __fsub_rz(\p x, \p x) returns \cuda_math_formula +0 \end_cuda_math_formula for finite \p x, including \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - If either argument is NaN, NaN is returned. + * + * \note_accuracy_single_intrinsic + * \note_nofma + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __fsub_rz(float x, float y); +/** + * \ingroup CUDA_MATH_INTRINSIC_SINGLE + * \brief Subtract two floating-point values in round-up mode. + * + * Compute the difference of \p x and \p y in round-up (to positive infinity) mode. + * + * \return Returns \p x - \p y. + * - __fsub_ru(\cuda_math_formula \pm\infty \end_cuda_math_formula, \p y) returns \cuda_math_formula \pm\infty \end_cuda_math_formula for finite \p y. + * - __fsub_ru(\p x, \cuda_math_formula \pm\infty \end_cuda_math_formula) returns \cuda_math_formula \mp\infty \end_cuda_math_formula for finite \p x. + * - __fsub_ru(\cuda_math_formula \pm\infty \end_cuda_math_formula, \cuda_math_formula \pm\infty \end_cuda_math_formula) returns NaN. + * - __fsub_ru(\cuda_math_formula \pm\infty \end_cuda_math_formula, \cuda_math_formula \mp\infty \end_cuda_math_formula) returns \cuda_math_formula \pm\infty \end_cuda_math_formula. + * - __fsub_ru(\cuda_math_formula \pm 0 \end_cuda_math_formula, \cuda_math_formula \mp 0 \end_cuda_math_formula) returns \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - __fsub_ru(\p x, \p x) returns \cuda_math_formula +0 \end_cuda_math_formula for finite \p x, including \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - If either argument is NaN, NaN is returned. + * + * \note_accuracy_single_intrinsic + * \note_nofma + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __fsub_ru(float x, float y); +/** + * \ingroup CUDA_MATH_INTRINSIC_SINGLE + * \brief Subtract two floating-point values in round-down mode. + * + * Compute the difference of \p x and \p y in round-down (to negative infinity) mode. + * + * \return Returns \p x - \p y. + * - __fsub_rd(\cuda_math_formula \pm\infty \end_cuda_math_formula, \p y) returns \cuda_math_formula \pm\infty \end_cuda_math_formula for finite \p y. + * - __fsub_rd(\p x, \cuda_math_formula \pm\infty \end_cuda_math_formula) returns \cuda_math_formula \mp\infty \end_cuda_math_formula for finite \p x. + * - __fsub_rd(\cuda_math_formula \pm\infty \end_cuda_math_formula, \cuda_math_formula \pm\infty \end_cuda_math_formula) returns NaN. + * - __fsub_rd(\cuda_math_formula \pm\infty \end_cuda_math_formula, \cuda_math_formula \mp\infty \end_cuda_math_formula) returns \cuda_math_formula \pm\infty \end_cuda_math_formula. + * - __fsub_rd(\cuda_math_formula \pm 0 \end_cuda_math_formula, \cuda_math_formula \mp 0 \end_cuda_math_formula) returns \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - __fsub_rd(\p x, \p x) returns \cuda_math_formula -0 \end_cuda_math_formula for finite \p x, including \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - If either argument is NaN, NaN is returned. + * + * \note_accuracy_single_intrinsic + * \note_nofma + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __fsub_rd(float x, float y); +/** + * \ingroup CUDA_MATH_INTRINSIC_SINGLE + * \brief Multiply two floating-point values in round-to-nearest-even mode. + * + * Compute the product of \p x and \p y in round-to-nearest-even mode. + * + * \return Returns \p x * \p y. + * - sign of the product \p x * \p y is XOR of the signs of \p x and \p y when neither inputs nor result are NaN. + * - __fmul_rn(\p x, \p y) is equivalent to __fmul_rn(\p y, \p x). + * - __fmul_rn(\p x, \cuda_math_formula \pm\infty \end_cuda_math_formula) returns \cuda_math_formula \infty \end_cuda_math_formula of appropriate sign for \p x \cuda_math_formula \neq 0 \end_cuda_math_formula. + * - __fmul_rn(\cuda_math_formula \pm 0 \end_cuda_math_formula, \cuda_math_formula \pm\infty \end_cuda_math_formula) returns NaN. + * - __fmul_rn(\cuda_math_formula \pm 0 \end_cuda_math_formula, \p y) returns \cuda_math_formula 0 \end_cuda_math_formula of appropriate sign for finite \p y. + * - If either argument is NaN, NaN is returned. + * + * \note_accuracy_single_intrinsic + * \note_nofma + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __fmul_rn(float x, float y); +/** + * \ingroup CUDA_MATH_INTRINSIC_SINGLE + * \brief Multiply two floating-point values in round-towards-zero mode. + * + * Compute the product of \p x and \p y in round-towards-zero mode. + * + * \return Returns \p x * \p y. + * - sign of the product \p x * \p y is XOR of the signs of \p x and \p y when neither inputs nor result are NaN. + * - __fmul_rz(\p x, \p y) is equivalent to __fmul_rz(\p y, \p x). + * - __fmul_rz(\p x, \cuda_math_formula \pm\infty \end_cuda_math_formula) returns \cuda_math_formula \infty \end_cuda_math_formula of appropriate sign for \p x \cuda_math_formula \neq 0 \end_cuda_math_formula. + * - __fmul_rz(\cuda_math_formula \pm 0 \end_cuda_math_formula, \cuda_math_formula \pm\infty \end_cuda_math_formula) returns NaN. + * - __fmul_rz(\cuda_math_formula \pm 0 \end_cuda_math_formula, \p y) returns \cuda_math_formula 0 \end_cuda_math_formula of appropriate sign for finite \p y. + * - If either argument is NaN, NaN is returned. + * + * \note_accuracy_single_intrinsic + * \note_nofma + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __fmul_rz(float x, float y); +/** + * \ingroup CUDA_MATH_INTRINSIC_SINGLE + * \brief Multiply two floating-point values in round-up mode. + * + * Compute the product of \p x and \p y in round-up (to positive infinity) mode. + * + * \return Returns \p x * \p y. + * - sign of the product \p x * \p y is XOR of the signs of \p x and \p y when neither inputs nor result are NaN. + * - __fmul_ru(\p x, \p y) is equivalent to __fmul_ru(\p y, \p x). + * - __fmul_ru(\p x, \cuda_math_formula \pm\infty \end_cuda_math_formula) returns \cuda_math_formula \infty \end_cuda_math_formula of appropriate sign for \p x \cuda_math_formula \neq 0 \end_cuda_math_formula. + * - __fmul_ru(\cuda_math_formula \pm 0 \end_cuda_math_formula, \cuda_math_formula \pm\infty \end_cuda_math_formula) returns NaN. + * - __fmul_ru(\cuda_math_formula \pm 0 \end_cuda_math_formula, \p y) returns \cuda_math_formula 0 \end_cuda_math_formula of appropriate sign for finite \p y. + * - If either argument is NaN, NaN is returned. + * + * \note_accuracy_single_intrinsic + * \note_nofma + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __fmul_ru(float x, float y); +/** + * \ingroup CUDA_MATH_INTRINSIC_SINGLE + * \brief Multiply two floating-point values in round-down mode. + * + * Compute the product of \p x and \p y in round-down (to negative infinity) mode. + * + * \return Returns \p x * \p y. + * - sign of the product \p x * \p y is XOR of the signs of \p x and \p y when neither inputs nor result are NaN. + * - __fmul_rd(\p x, \p y) is equivalent to __fmul_rd(\p y, \p x). + * - __fmul_rd(\p x, \cuda_math_formula \pm\infty \end_cuda_math_formula) returns \cuda_math_formula \infty \end_cuda_math_formula of appropriate sign for \p x \cuda_math_formula \neq 0 \end_cuda_math_formula. + * - __fmul_rd(\cuda_math_formula \pm 0 \end_cuda_math_formula, \cuda_math_formula \pm\infty \end_cuda_math_formula) returns NaN. + * - __fmul_rd(\cuda_math_formula \pm 0 \end_cuda_math_formula, \p y) returns \cuda_math_formula 0 \end_cuda_math_formula of appropriate sign for finite \p y. + * - If either argument is NaN, NaN is returned. + * + * \note_accuracy_single_intrinsic + * \note_nofma + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __fmul_rd(float x, float y); +/** + * \ingroup CUDA_MATH_INTRINSIC_SINGLE + * \brief Compute + * \cuda_math_formula x \times y + z \end_cuda_math_formula + * as a single operation, in round-to-nearest-even mode. + * + * Computes the value of + * \cuda_math_formula x \times y + z \end_cuda_math_formula + * as a single ternary operation, rounding the + * result once in round-to-nearest-even mode. + * + * \return Returns the rounded value of + * \cuda_math_formula x \times y + z \end_cuda_math_formula + * as a single operation. + * - __fmaf_rn( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * , + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * , \p z) returns NaN. + * - __fmaf_rn( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * , + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * , \p z) returns NaN. + * - __fmaf_rn(\p x, \p y, + * \cuda_math_formula -\infty \end_cuda_math_formula + * ) returns NaN if + * \cuda_math_formula x \times y \end_cuda_math_formula + * is an exact + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - __fmaf_rn(\p x, \p y, + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns NaN if + * \cuda_math_formula x \times y \end_cuda_math_formula + * is an exact + * \cuda_math_formula -\infty \end_cuda_math_formula. + * - __fmaf_rn(\p x, \p y, \cuda_math_formula \pm 0 \end_cuda_math_formula) returns \cuda_math_formula \pm 0 \end_cuda_math_formula if \cuda_math_formula x \times y \end_cuda_math_formula is exact \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - __fmaf_rn(\p x, \p y, \cuda_math_formula \mp 0 \end_cuda_math_formula) returns \cuda_math_formula +0 \end_cuda_math_formula if \cuda_math_formula x \times y \end_cuda_math_formula is exact \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - __fmaf_rn(\p x, \p y, \p z) returns \cuda_math_formula +0 \end_cuda_math_formula if \cuda_math_formula x \times y + z \end_cuda_math_formula is exactly zero and \cuda_math_formula z \neq 0 \end_cuda_math_formula. + * - If either argument is NaN, NaN is returned. + * + * \note_accuracy_single_intrinsic + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __fmaf_rn(float x, float y, float z); +/** + * \ingroup CUDA_MATH_INTRINSIC_SINGLE + * \brief Compute + * \cuda_math_formula x \times y + z \end_cuda_math_formula + * as a single operation, in round-towards-zero mode. + * + * Computes the value of + * \cuda_math_formula x \times y + z \end_cuda_math_formula + * as a single ternary operation, rounding the + * result once in round-towards-zero mode. + * + * \return Returns the rounded value of + * \cuda_math_formula x \times y + z \end_cuda_math_formula + * as a single operation. + * - __fmaf_rz( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * , + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * , \p z) returns NaN. + * - __fmaf_rz( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * , + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * , \p z) returns NaN. + * - __fmaf_rz(\p x, \p y, + * \cuda_math_formula -\infty \end_cuda_math_formula + * ) returns NaN if + * \cuda_math_formula x \times y \end_cuda_math_formula + * is an exact + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - __fmaf_rz(\p x, \p y, + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns NaN if + * \cuda_math_formula x \times y \end_cuda_math_formula + * is an exact + * \cuda_math_formula -\infty \end_cuda_math_formula. + * - __fmaf_rz(\p x, \p y, \cuda_math_formula \pm 0 \end_cuda_math_formula) returns \cuda_math_formula \pm 0 \end_cuda_math_formula if \cuda_math_formula x \times y \end_cuda_math_formula is exact \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - __fmaf_rz(\p x, \p y, \cuda_math_formula \mp 0 \end_cuda_math_formula) returns \cuda_math_formula +0 \end_cuda_math_formula if \cuda_math_formula x \times y \end_cuda_math_formula is exact \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - __fmaf_rz(\p x, \p y, \p z) returns \cuda_math_formula +0 \end_cuda_math_formula if \cuda_math_formula x \times y + z \end_cuda_math_formula is exactly zero and \cuda_math_formula z \neq 0 \end_cuda_math_formula. + * - If either argument is NaN, NaN is returned. + * + * \note_accuracy_single_intrinsic + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __fmaf_rz(float x, float y, float z); +/** + * \ingroup CUDA_MATH_INTRINSIC_SINGLE + * \brief Compute + * \cuda_math_formula x \times y + z \end_cuda_math_formula + * as a single operation, in round-up mode. + * + * Computes the value of + * \cuda_math_formula x \times y + z \end_cuda_math_formula + * as a single ternary operation, rounding the + * result once in round-up (to positive infinity) mode. + * + * \return Returns the rounded value of + * \cuda_math_formula x \times y + z \end_cuda_math_formula + * as a single operation. + * - __fmaf_ru( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * , + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * , \p z) returns NaN. + * - __fmaf_ru( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * , + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * , \p z) returns NaN. + * - __fmaf_ru(\p x, \p y, + * \cuda_math_formula -\infty \end_cuda_math_formula + * ) returns NaN if + * \cuda_math_formula x \times y \end_cuda_math_formula + * is an exact + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - __fmaf_ru(\p x, \p y, + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns NaN if + * \cuda_math_formula x \times y \end_cuda_math_formula + * is an exact + * \cuda_math_formula -\infty \end_cuda_math_formula. + * - __fmaf_ru(\p x, \p y, \cuda_math_formula \pm 0 \end_cuda_math_formula) returns \cuda_math_formula \pm 0 \end_cuda_math_formula if \cuda_math_formula x \times y \end_cuda_math_formula is exact \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - __fmaf_ru(\p x, \p y, \cuda_math_formula \mp 0 \end_cuda_math_formula) returns \cuda_math_formula +0 \end_cuda_math_formula if \cuda_math_formula x \times y \end_cuda_math_formula is exact \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - __fmaf_ru(\p x, \p y, \p z) returns \cuda_math_formula +0 \end_cuda_math_formula if \cuda_math_formula x \times y + z \end_cuda_math_formula is exactly zero and \cuda_math_formula z \neq 0 \end_cuda_math_formula. + * - If either argument is NaN, NaN is returned. + * + * \note_accuracy_single_intrinsic + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __fmaf_ru(float x, float y, float z); +/** + * \ingroup CUDA_MATH_INTRINSIC_SINGLE + * \brief Compute + * \cuda_math_formula x \times y + z \end_cuda_math_formula + * as a single operation, in round-down mode. + * + * Computes the value of + * \cuda_math_formula x \times y + z \end_cuda_math_formula + * as a single ternary operation, rounding the + * result once in round-down (to negative infinity) mode. + * + * \return Returns the rounded value of + * \cuda_math_formula x \times y + z \end_cuda_math_formula + * as a single operation. + * - __fmaf_rd( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * , + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * , \p z) returns NaN. + * - __fmaf_rd( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * , + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * , \p z) returns NaN. + * - __fmaf_rd(\p x, \p y, + * \cuda_math_formula -\infty \end_cuda_math_formula + * ) returns NaN if + * \cuda_math_formula x \times y \end_cuda_math_formula + * is an exact + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - __fmaf_rd(\p x, \p y, + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns NaN if + * \cuda_math_formula x \times y \end_cuda_math_formula + * is an exact + * \cuda_math_formula -\infty \end_cuda_math_formula. + * - __fmaf_rd(\p x, \p y, \cuda_math_formula \pm 0 \end_cuda_math_formula) returns \cuda_math_formula \pm 0 \end_cuda_math_formula if \cuda_math_formula x \times y \end_cuda_math_formula is exact \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - __fmaf_rd(\p x, \p y, \cuda_math_formula \mp 0 \end_cuda_math_formula) returns \cuda_math_formula -0 \end_cuda_math_formula if \cuda_math_formula x \times y \end_cuda_math_formula is exact \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - __fmaf_rd(\p x, \p y, \p z) returns \cuda_math_formula -0 \end_cuda_math_formula if \cuda_math_formula x \times y + z \end_cuda_math_formula is exactly zero and \cuda_math_formula z \neq 0 \end_cuda_math_formula. + * - If either argument is NaN, NaN is returned. + * + * \note_accuracy_single_intrinsic + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __fmaf_rd(float x, float y, float z); +/** + * \ingroup CUDA_MATH_INTRINSIC_SINGLE + * \brief Compute + * \cuda_math_formula \frac{1}{x} \end_cuda_math_formula + * in round-to-nearest-even mode. + * + * Compute the reciprocal of \p x in round-to-nearest-even mode. + * + * \return Returns + * \cuda_math_formula \frac{1}{x} \end_cuda_math_formula. + * - __frcp_rn(\cuda_math_formula \pm 0 \end_cuda_math_formula) returns \cuda_math_formula \pm\infty \end_cuda_math_formula. + * - __frcp_rn(\cuda_math_formula \pm\infty \end_cuda_math_formula) returns \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - __frcp_rn(NaN) returns NaN. + * + * \note_accuracy_single_intrinsic + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __frcp_rn(float x); +/** + * \ingroup CUDA_MATH_INTRINSIC_SINGLE + * \brief Compute + * \cuda_math_formula \frac{1}{x} \end_cuda_math_formula + * in round-towards-zero mode. + * + * Compute the reciprocal of \p x in round-towards-zero mode. + * + * \return Returns + * \cuda_math_formula \frac{1}{x} \end_cuda_math_formula. + * - __frcp_rz(\cuda_math_formula \pm 0 \end_cuda_math_formula) returns \cuda_math_formula \pm\infty \end_cuda_math_formula. + * - __frcp_rz(\cuda_math_formula \pm\infty \end_cuda_math_formula) returns \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - __frcp_rz(NaN) returns NaN. + * + * \note_accuracy_single_intrinsic + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __frcp_rz(float x); +/** + * \ingroup CUDA_MATH_INTRINSIC_SINGLE + * \brief Compute + * \cuda_math_formula \frac{1}{x} \end_cuda_math_formula + * in round-up mode. + * + * Compute the reciprocal of \p x in round-up (to positive infinity) mode. + * + * \return Returns + * \cuda_math_formula \frac{1}{x} \end_cuda_math_formula. + * - __frcp_ru(\cuda_math_formula \pm 0 \end_cuda_math_formula) returns \cuda_math_formula \pm\infty \end_cuda_math_formula. + * - __frcp_ru(\cuda_math_formula \pm\infty \end_cuda_math_formula) returns \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - __frcp_ru(NaN) returns NaN. + * + * \note_accuracy_single_intrinsic + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __frcp_ru(float x); +/** + * \ingroup CUDA_MATH_INTRINSIC_SINGLE + * \brief Compute + * \cuda_math_formula \frac{1}{x} \end_cuda_math_formula + * in round-down mode. + * + * Compute the reciprocal of \p x in round-down (to negative infinity) mode. + * + * \return Returns + * \cuda_math_formula \frac{1}{x} \end_cuda_math_formula. + * - __frcp_rd(\cuda_math_formula \pm 0 \end_cuda_math_formula) returns \cuda_math_formula \pm\infty \end_cuda_math_formula. + * - __frcp_rd(\cuda_math_formula \pm\infty \end_cuda_math_formula) returns \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - __frcp_rd(NaN) returns NaN. + * + * \note_accuracy_single_intrinsic + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __frcp_rd(float x); +/** + * \ingroup CUDA_MATH_INTRINSIC_SINGLE + * \brief Compute + * \cuda_math_formula \sqrt{x} \end_cuda_math_formula + * in round-to-nearest-even mode. + * + * Compute the square root of \p x in round-to-nearest-even mode. + * + * \return Returns + * \cuda_math_formula \sqrt{x} \end_cuda_math_formula. + * - __fsqrt_rn(\cuda_math_formula \pm 0 \end_cuda_math_formula) returns \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - __fsqrt_rn(\cuda_math_formula +\infty \end_cuda_math_formula) returns \cuda_math_formula +\infty \end_cuda_math_formula. + * - __fsqrt_rn(\p x) returns NaN for \p x < 0. + * - __fsqrt_rn(NaN) returns NaN. + * + * \note_accuracy_single_intrinsic + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __fsqrt_rn(float x); +/** + * \ingroup CUDA_MATH_INTRINSIC_SINGLE + * \brief Compute + * \cuda_math_formula \sqrt{x} \end_cuda_math_formula + * in round-towards-zero mode. + * + * Compute the square root of \p x in round-towards-zero mode. + * + * \return Returns + * \cuda_math_formula \sqrt{x} \end_cuda_math_formula. + * - __fsqrt_rz(\cuda_math_formula \pm 0 \end_cuda_math_formula) returns \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - __fsqrt_rz(\cuda_math_formula +\infty \end_cuda_math_formula) returns \cuda_math_formula +\infty \end_cuda_math_formula. + * - __fsqrt_rz(\p x) returns NaN for \p x < 0. + * - __fsqrt_rz(NaN) returns NaN. + * + * \note_accuracy_single_intrinsic + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __fsqrt_rz(float x); +/** + * \ingroup CUDA_MATH_INTRINSIC_SINGLE + * \brief Compute + * \cuda_math_formula \sqrt{x} \end_cuda_math_formula + * in round-up mode. + * + * Compute the square root of \p x in round-up (to positive infinity) mode. + * + * \return Returns + * \cuda_math_formula \sqrt{x} \end_cuda_math_formula. + * - __fsqrt_ru(\cuda_math_formula \pm 0 \end_cuda_math_formula) returns \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - __fsqrt_ru(\cuda_math_formula +\infty \end_cuda_math_formula) returns \cuda_math_formula +\infty \end_cuda_math_formula. + * - __fsqrt_ru(\p x) returns NaN for \p x < 0. + * - __fsqrt_ru(NaN) returns NaN. + * + * \note_accuracy_single_intrinsic + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __fsqrt_ru(float x); +/** + * \ingroup CUDA_MATH_INTRINSIC_SINGLE + * \brief Compute + * \cuda_math_formula \sqrt{x} \end_cuda_math_formula + * in round-down mode. + * + * Compute the square root of \p x in round-down (to negative infinity) mode. + * + * \return Returns + * \cuda_math_formula \sqrt{x} \end_cuda_math_formula. + * - __fsqrt_rd(\cuda_math_formula \pm 0 \end_cuda_math_formula) returns \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - __fsqrt_rd(\cuda_math_formula +\infty \end_cuda_math_formula) returns \cuda_math_formula +\infty \end_cuda_math_formula. + * - __fsqrt_rd(\p x) returns NaN for \p x < 0. + * - __fsqrt_rd(NaN) returns NaN. + * + * \note_accuracy_single_intrinsic + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __fsqrt_rd(float x); +/** + * \ingroup CUDA_MATH_INTRINSIC_SINGLE + * \brief Compute + * \cuda_math_formula 1/\sqrt{x} \end_cuda_math_formula + * in round-to-nearest-even mode. + * + * Compute the reciprocal square root of \p x in round-to-nearest-even mode. + * + * \return Returns + * \cuda_math_formula 1/\sqrt{x} \end_cuda_math_formula. + * - __frsqrt_rn(\cuda_math_formula \pm 0 \end_cuda_math_formula) returns \cuda_math_formula \pm\infty \end_cuda_math_formula. + * - __frsqrt_rn(\cuda_math_formula +\infty \end_cuda_math_formula) returns \cuda_math_formula +0 \end_cuda_math_formula. + * - __frsqrt_rn(\p x) returns NaN for \p x < 0. + * - __frsqrt_rn(NaN) returns NaN. + * + * \note_accuracy_single_intrinsic + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __frsqrt_rn(float x); +/** + * \ingroup CUDA_MATH_INTRINSIC_SINGLE + * \brief Divide two floating-point values in round-to-nearest-even mode. + * + * Divide two floating-point values \p x by \p y in round-to-nearest-even mode. + * + * \return Returns \p x / \p y. + * - sign of the quotient \p x / \p y is XOR of the signs of \p x and \p y when neither inputs nor result are NaN. + * - __fdiv_rn(\cuda_math_formula \pm 0 \end_cuda_math_formula, \cuda_math_formula \pm 0 \end_cuda_math_formula) returns NaN. + * - __fdiv_rn(\cuda_math_formula \pm\infty \end_cuda_math_formula, \cuda_math_formula \pm\infty \end_cuda_math_formula) returns NaN. + * - __fdiv_rn(\p x, \cuda_math_formula \pm\infty \end_cuda_math_formula) returns \cuda_math_formula 0 \end_cuda_math_formula of appropriate sign for finite \p x. + * - __fdiv_rn(\cuda_math_formula \pm\infty \end_cuda_math_formula, \p y) returns \cuda_math_formula \infty \end_cuda_math_formula of appropriate sign for finite \p y. + * - __fdiv_rn(\p x, \cuda_math_formula \pm 0 \end_cuda_math_formula) returns \cuda_math_formula \infty \end_cuda_math_formula of appropriate sign for \p x \cuda_math_formula \neq 0 \end_cuda_math_formula. + * - __fdiv_rn(\cuda_math_formula \pm 0 \end_cuda_math_formula, \p y) returns \cuda_math_formula 0 \end_cuda_math_formula of appropriate sign for \p y \cuda_math_formula \neq 0 \end_cuda_math_formula. + * - If either argument is NaN, NaN is returned. + * + * \note_accuracy_single_intrinsic + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __fdiv_rn(float x, float y); +/** + * \ingroup CUDA_MATH_INTRINSIC_SINGLE + * \brief Divide two floating-point values in round-towards-zero mode. + * + * Divide two floating-point values \p x by \p y in round-towards-zero mode. + * + * \return Returns \p x / \p y. + * - sign of the quotient \p x / \p y is XOR of the signs of \p x and \p y when neither inputs nor result are NaN. + * - __fdiv_rz(\cuda_math_formula \pm 0 \end_cuda_math_formula, \cuda_math_formula \pm 0 \end_cuda_math_formula) returns NaN. + * - __fdiv_rz(\cuda_math_formula \pm\infty \end_cuda_math_formula, \cuda_math_formula \pm\infty \end_cuda_math_formula) returns NaN. + * - __fdiv_rz(\p x, \cuda_math_formula \pm\infty \end_cuda_math_formula) returns \cuda_math_formula 0 \end_cuda_math_formula of appropriate sign for finite \p x. + * - __fdiv_rz(\cuda_math_formula \pm\infty \end_cuda_math_formula, \p y) returns \cuda_math_formula \infty \end_cuda_math_formula of appropriate sign for finite \p y. + * - __fdiv_rz(\p x, \cuda_math_formula \pm 0 \end_cuda_math_formula) returns \cuda_math_formula \infty \end_cuda_math_formula of appropriate sign for \p x \cuda_math_formula \neq 0 \end_cuda_math_formula. + * - __fdiv_rz(\cuda_math_formula \pm 0 \end_cuda_math_formula, \p y) returns \cuda_math_formula 0 \end_cuda_math_formula of appropriate sign for \p y \cuda_math_formula \neq 0 \end_cuda_math_formula. + * - If either argument is NaN, NaN is returned. + * + * \note_accuracy_single_intrinsic + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __fdiv_rz(float x, float y); +/** + * \ingroup CUDA_MATH_INTRINSIC_SINGLE + * \brief Divide two floating-point values in round-up mode. + * + * Divide two floating-point values \p x by \p y in round-up (to positive infinity) mode. + * + * \return Returns \p x / \p y. + * - sign of the quotient \p x / \p y is XOR of the signs of \p x and \p y when neither inputs nor result are NaN. + * - __fdiv_ru(\cuda_math_formula \pm 0 \end_cuda_math_formula, \cuda_math_formula \pm 0 \end_cuda_math_formula) returns NaN. + * - __fdiv_ru(\cuda_math_formula \pm\infty \end_cuda_math_formula, \cuda_math_formula \pm\infty \end_cuda_math_formula) returns NaN. + * - __fdiv_ru(\p x, \cuda_math_formula \pm\infty \end_cuda_math_formula) returns \cuda_math_formula 0 \end_cuda_math_formula of appropriate sign for finite \p x. + * - __fdiv_ru(\cuda_math_formula \pm\infty \end_cuda_math_formula, \p y) returns \cuda_math_formula \infty \end_cuda_math_formula of appropriate sign for finite \p y. + * - __fdiv_ru(\p x, \cuda_math_formula \pm 0 \end_cuda_math_formula) returns \cuda_math_formula \infty \end_cuda_math_formula of appropriate sign for \p x \cuda_math_formula \neq 0 \end_cuda_math_formula. + * - __fdiv_ru(\cuda_math_formula \pm 0 \end_cuda_math_formula, \p y) returns \cuda_math_formula 0 \end_cuda_math_formula of appropriate sign for \p y \cuda_math_formula \neq 0 \end_cuda_math_formula. + * - If either argument is NaN, NaN is returned. + * + * \note_accuracy_single_intrinsic + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __fdiv_ru(float x, float y); +/** + * \ingroup CUDA_MATH_INTRINSIC_SINGLE + * \brief Divide two floating-point values in round-down mode. + * + * Divide two floating-point values \p x by \p y in round-down (to negative infinity) mode. + * + * \return Returns \p x / \p y. + * - sign of the quotient \p x / \p y is XOR of the signs of \p x and \p y when neither inputs nor result are NaN. + * - __fdiv_rd(\cuda_math_formula \pm 0 \end_cuda_math_formula, \cuda_math_formula \pm 0 \end_cuda_math_formula) returns NaN. + * - __fdiv_rd(\cuda_math_formula \pm\infty \end_cuda_math_formula, \cuda_math_formula \pm\infty \end_cuda_math_formula) returns NaN. + * - __fdiv_rd(\p x, \cuda_math_formula \pm\infty \end_cuda_math_formula) returns \cuda_math_formula 0 \end_cuda_math_formula of appropriate sign for finite \p x. + * - __fdiv_rd(\cuda_math_formula \pm\infty \end_cuda_math_formula, \p y) returns \cuda_math_formula \infty \end_cuda_math_formula of appropriate sign for finite \p y. + * - __fdiv_rd(\p x, \cuda_math_formula \pm 0 \end_cuda_math_formula) returns \cuda_math_formula \infty \end_cuda_math_formula of appropriate sign for \p x \cuda_math_formula \neq 0 \end_cuda_math_formula. + * - __fdiv_rd(\cuda_math_formula \pm 0 \end_cuda_math_formula, \p y) returns \cuda_math_formula 0 \end_cuda_math_formula of appropriate sign for \p y \cuda_math_formula \neq 0 \end_cuda_math_formula. + * - If either argument is NaN, NaN is returned. + * + * \note_accuracy_single_intrinsic + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __fdiv_rd(float x, float y); +/** + * \ingroup CUDA_MATH_INTRINSIC_INT + * \brief Return the number of consecutive high-order zero bits in a 32-bit integer. + * + * Count the number of consecutive leading zero bits, starting at the most significant bit (bit 31) of \p x. + * + * \return Returns a value between 0 and 32 inclusive representing the number of zero bits. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ int __clz(int x); +/** + * \ingroup CUDA_MATH_INTRINSIC_INT + * \brief Find the position of the least significant bit set to 1 in a 32-bit integer. + * + * Find the position of the first (least significant) bit set to 1 in \p x, where the least significant + * bit position is 1. + * + * \return Returns a value between 0 and 32 inclusive representing the position of the first bit set. + * - __ffs(0) returns 0. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ int __ffs(int x); +/** + * \ingroup CUDA_MATH_INTRINSIC_INT + * \brief Count the number of bits that are set to 1 in a 32-bit integer. + * + * Count the number of bits that are set to 1 in \p x. + * + * \return Returns a value between 0 and 32 inclusive representing the number of set bits. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ int __popc(unsigned int x); +/** + * \ingroup CUDA_MATH_INTRINSIC_INT + * \brief Reverse the bit order of a 32-bit unsigned integer. + * + * Reverses the bit order of the 32-bit unsigned integer \p x. + * + * \return Returns the bit-reversed value of \p x. i.e. bit N of the return value corresponds to bit 31-N of \p x. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __brev(unsigned int x); +/** + * \ingroup CUDA_MATH_INTRINSIC_INT + * \brief Count the number of consecutive high-order zero bits in a 64-bit integer. + * + * Count the number of consecutive leading zero bits, starting at the most significant bit (bit 63) of \p x. + * + * \return Returns a value between 0 and 64 inclusive representing the number of zero bits. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ int __clzll(long long int x); +/** + * \ingroup CUDA_MATH_INTRINSIC_INT + * \brief Find the position of the least significant bit set to 1 in a 64-bit integer. + * + * Find the position of the first (least significant) bit set to 1 in \p x, where the least significant + * bit position is 1. + * + * \return Returns a value between 0 and 64 inclusive representing the position of the first bit set. + * - __ffsll(0) returns 0. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ int __ffsll(long long int x); + + +/** + * \ingroup CUDA_MATH_INTRINSIC_INT + * \brief Count the number of bits that are set to 1 in a 64-bit integer. + * + * Count the number of bits that are set to 1 in \p x. + * + * \return Returns a value between 0 and 64 inclusive representing the number of set bits. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ int __popcll(unsigned long long int x); +/** + * \ingroup CUDA_MATH_INTRINSIC_INT + * \brief Reverse the bit order of a 64-bit unsigned integer. + * + * Reverses the bit order of the 64-bit unsigned integer \p x. + * + * \return Returns the bit-reversed value of \p x. i.e. bit N of the return value corresponds to bit 63-N of \p x. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned long long int __brevll(unsigned long long int x); +/** + * \ingroup CUDA_MATH_INTRINSIC_INT + * \brief Return selected bytes from two 32-bit unsigned integers. + * + * \return Returns a 32-bit integer consisting of four bytes from eight input bytes provided in the two + * input integers \p x and \p y, as specified by a selector, \p s. + * + * Create 8-byte source + * - uint64_t \p tmp64 = ((uint64_t)\p y << 32) | \p x; + * + * Extract selector bits + * - \p selector0 = (\p s >> 0) & 0x7; + * - \p selector1 = (\p s >> 4) & 0x7; + * - \p selector2 = (\p s >> 8) & 0x7; + * - \p selector3 = (\p s >> 12) & 0x7; + * + * Return 4 selected bytes from 8-byte source: + * - \p res[07:00] = \p tmp64[\p selector0]; + * - \p res[15:08] = \p tmp64[\p selector1]; + * - \p res[23:16] = \p tmp64[\p selector2]; + * - \p res[31:24] = \p tmp64[\p selector3]; + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __byte_perm(unsigned int x, unsigned int y, unsigned int s); +/** + * \ingroup CUDA_MATH_INTRINSIC_INT + * \brief Compute average of signed input arguments, avoiding overflow + * in the intermediate sum. + * + * Compute average of signed input arguments \p x and \p y + * as ( \p x + \p y ) >> 1, avoiding overflow in the intermediate sum. + * + * \return Returns a signed integer value representing the signed + * average value of the two inputs. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ int __hadd(int x, int y); +/** + * \ingroup CUDA_MATH_INTRINSIC_INT + * \brief Compute rounded average of signed input arguments, avoiding + * overflow in the intermediate sum. + * + * Compute average of signed input arguments \p x and \p y + * as ( \p x + \p y + 1 ) >> 1, avoiding overflow in the intermediate + * sum. + * + * \return Returns a signed integer value representing the signed + * rounded average value of the two inputs. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ int __rhadd(int x, int y); +/** + * \ingroup CUDA_MATH_INTRINSIC_INT + * \brief Compute average of unsigned input arguments, avoiding overflow + * in the intermediate sum. + * + * Compute average of unsigned input arguments \p x and \p y + * as ( \p x + \p y ) >> 1, avoiding overflow in the intermediate sum. + * + * \return Returns an unsigned integer value representing the unsigned + * average value of the two inputs. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __uhadd(unsigned int x, unsigned int y); +/** + * \ingroup CUDA_MATH_INTRINSIC_INT + * \brief Compute rounded average of unsigned input arguments, avoiding + * overflow in the intermediate sum. + * + * Compute average of unsigned input arguments \p x and \p y + * as ( \p x + \p y + 1 ) >> 1, avoiding overflow in the intermediate + * sum. + * + * \return Returns an unsigned integer value representing the unsigned + * rounded average value of the two inputs. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __urhadd(unsigned int x, unsigned int y); + +/** + * \ingroup CUDA_MATH_INTRINSIC_CAST + * \brief Convert a double to a signed int in round-towards-zero mode. + * + * Convert the double-precision floating-point value \p x to a + * signed integer value in round-towards-zero mode. + * \return Returns converted value. + * \note_fp_to_int_out_of_range_undefined + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ int __double2int_rz(double x); +/** + * \ingroup CUDA_MATH_INTRINSIC_CAST + * \brief Convert a double to an unsigned int in round-towards-zero mode. + * + * Convert the double-precision floating-point value \p x to an + * unsigned integer value in round-towards-zero mode. + * \return Returns converted value. + * \note_fp_to_int_out_of_range_undefined + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __double2uint_rz(double x); +/** + * \ingroup CUDA_MATH_INTRINSIC_CAST + * \brief Convert a double to a signed 64-bit int in round-towards-zero mode. + * + * Convert the double-precision floating-point value \p x to a + * signed 64-bit integer value in round-towards-zero mode. + * \return Returns converted value. + * \note_fp_to_int_out_of_range_undefined + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ long long int __double2ll_rz(double x); +/** + * \ingroup CUDA_MATH_INTRINSIC_CAST + * \brief Convert a double to an unsigned 64-bit int in round-towards-zero mode. + * + * Convert the double-precision floating-point value \p x to an + * unsigned 64-bit integer value in round-towards-zero mode. + * \return Returns converted value. + * \note_fp_to_int_out_of_range_undefined + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned long long int __double2ull_rz(double x); +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __pm0(void); +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __pm1(void); +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __pm2(void); +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __pm3(void); + +/******************************************************************************* + * * + * FP16 SIMD functions * + * * + *******************************************************************************/ + + // #include "fp16.h" + + +/******************************************************************************* + * * + * SIMD functions * + * * + *******************************************************************************/ + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Computes per-halfword absolute value: |a|. + * + * Splits 4 bytes of argument into 2 parts, each consisting of 2 bytes, + * then computes absolute value for each of parts. + * Partial results are recombined and returned as unsigned int. + * \return Returns computed value. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __vabs2(unsigned int a); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Computes per-halfword absolute value with signed saturation: |a|. + * + * Splits 4 bytes of argument into 2 parts, each consisting of 2 bytes, + * then computes absolute value with signed saturation for each of parts. + * Partial results are recombined and returned as unsigned int. + * \return Returns computed value. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __vabsss2(unsigned int a); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Performs per-halfword (un)signed addition, with wrap-around: a + b. + * + * Splits 4 bytes of each argument into 2 parts, each consisting of 2 bytes, + * then performs unsigned addition on corresponding parts. + * Partial results are recombined and returned as unsigned int. + * \return Returns computed value. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __vadd2(unsigned int a, unsigned int b); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Performs per-halfword addition with signed saturation: a + b. + * + * Splits 4 bytes of each argument into 2 parts, each consisting of 2 bytes, + * then performs addition with signed saturation on corresponding parts. + * Partial results are recombined and returned as unsigned int. + * \return Returns computed value. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __vaddss2 (unsigned int a, unsigned int b); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Performs per-halfword addition with unsigned saturation: a + b. + * + * Splits 4 bytes of each argument into 2 parts, each consisting of 2 bytes, + * then performs addition with unsigned saturation on corresponding parts. + * \return Returns computed value. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __vaddus2 (unsigned int a, unsigned int b); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Performs per-halfword signed rounded average computation. + * + * Splits 4 bytes of each argument into 2 parts, each consisting of 2 bytes, + * then computes signed rounded average of corresponding parts. Partial results are + * recombined and returned as unsigned int. + * \return Returns computed value. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __vavgs2(unsigned int a, unsigned int b); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Performs per-halfword unsigned rounded average computation. + * + * Splits 4 bytes of each argument into 2 parts, each consisting of 2 bytes, + * then computes unsigned rounded average of corresponding parts. Partial results are + * recombined and returned as unsigned int. + * \return Returns computed value. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __vavgu2(unsigned int a, unsigned int b); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Performs per-halfword unsigned average computation. + * + * Splits 4 bytes of each argument into 2 parts, each consisting of 2 bytes, + * then computes unsigned average of corresponding parts. Partial results are + * recombined and returned as unsigned int. + * \return Returns computed value. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __vhaddu2(unsigned int a, unsigned int b); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Performs per-halfword (un)signed comparison: a == b ? 0xffff : 0. + * + * Splits 4 bytes of each argument into 2 parts, each consisting of 2 bytes. + * For corresponding parts result is ffff if they are equal, and 0000 otherwise. + * For example __vcmpeq2(0x1234aba5, 0x1234aba6) returns 0xffff0000. + * \return Returns 0xffff computed value. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __vcmpeq2(unsigned int a, unsigned int b); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Performs per-halfword signed comparison: a >= b ? 0xffff : 0. + * + * Splits 4 bytes of each argument into 2 parts, each consisting of 2 bytes. + * For corresponding parts result is ffff if 'a' part >= 'b' part, and 0000 otherwise. + * For example __vcmpges2(0x1234aba5, 0x1234aba6) returns 0xffff0000. + * \return Returns 0xffff if a >= b, else returns 0. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __vcmpges2(unsigned int a, unsigned int b); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Performs per-halfword unsigned comparison: a >= b ? 0xffff : 0. + * + * Splits 4 bytes of each argument into 2 parts, each consisting of 2 bytes. + * For corresponding parts result is ffff if 'a' part >= 'b' part, and 0000 otherwise. + * For example __vcmpgeu2(0x1234aba5, 0x1234aba6) returns 0xffff0000. + * \return Returns 0xffff if a >= b, else returns 0. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __vcmpgeu2(unsigned int a, unsigned int b); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Performs per-halfword signed comparison: a > b ? 0xffff : 0. + * + * Splits 4 bytes of each argument into 2 parts, each consisting of 2 bytes. + * For corresponding parts result is ffff if 'a' part > 'b' part, and 0000 otherwise. + * For example __vcmpgts2(0x1234aba5, 0x1234aba6) returns 0x00000000. + * \return Returns 0xffff if a > b, else returns 0. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __vcmpgts2(unsigned int a, unsigned int b); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Performs per-halfword unsigned comparison: a > b ? 0xffff : 0. + * + * Splits 4 bytes of each argument into 2 parts, each consisting of 2 bytes. + * For corresponding parts result is ffff if 'a' part > 'b' part, and 0000 otherwise. + * For example __vcmpgtu2(0x1234aba5, 0x1234aba6) returns 0x00000000. + * \return Returns 0xffff if a > b, else returns 0. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __vcmpgtu2(unsigned int a, unsigned int b); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Performs per-halfword signed comparison: a <= b ? 0xffff : 0. + * + * Splits 4 bytes of each argument into 2 parts, each consisting of 2 bytes. + * For corresponding parts result is ffff if 'a' part <= 'b' part, and 0000 otherwise. + * For example __vcmples2(0x1234aba5, 0x1234aba6) returns 0xffffffff. + * \return Returns 0xffff if a <= b, else returns 0. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __vcmples2(unsigned int a, unsigned int b); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Performs per-halfword unsigned comparison: a <= b ? 0xffff : 0. + * + * Splits 4 bytes of each argument into 2 parts, each consisting of 2 bytes. + * For corresponding parts result is ffff if 'a' part <= 'b' part, and 0000 otherwise. + * For example __vcmpleu2(0x1234aba5, 0x1234aba6) returns 0xffffffff. + * \return Returns 0xffff if a <= b, else returns 0. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __vcmpleu2(unsigned int a, unsigned int b); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Performs per-halfword signed comparison: a < b ? 0xffff : 0. + * + * Splits 4 bytes of each argument into 2 parts, each consisting of 2 bytes. + * For corresponding parts result is ffff if 'a' part < 'b' part, and 0000 otherwise. + * For example __vcmplts2(0x1234aba5, 0x1234aba6) returns 0x0000ffff. + * \return Returns 0xffff if a < b, else returns 0. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __vcmplts2(unsigned int a, unsigned int b); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Performs per-halfword unsigned comparison: a < b ? 0xffff : 0. + * + * Splits 4 bytes of each argument into 2 parts, each consisting of 2 bytes. + * For corresponding parts result is ffff if 'a' part < 'b' part, and 0000 otherwise. + * For example __vcmpltu2(0x1234aba5, 0x1234aba6) returns 0x0000ffff. + * \return Returns 0xffff if a < b, else returns 0. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __vcmpltu2(unsigned int a, unsigned int b); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Performs per-halfword (un)signed comparison: a != b ? 0xffff : 0. + * + * Splits 4 bytes of each argument into 2 parts, each consisting of 2 bytes. + * For corresponding parts result is ffff if 'a' part != 'b' part, and 0000 otherwise. + * For example __vcmplts2(0x1234aba5, 0x1234aba6) returns 0x0000ffff. + * \return Returns 0xffff if a != b, else returns 0. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __vcmpne2(unsigned int a, unsigned int b); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Computes per-halfword absolute difference of unsigned integer: |a - b|. + * + * Splits 4 bytes of each argument into 2 parts, each consisting of 2 bytes. + * For corresponding parts function computes absolute difference. Partial results + * are recombined and returned as unsigned int. + * \return Returns computed value. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __vabsdiffu2(unsigned int a, unsigned int b); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Performs per-halfword signed maximum computation. + * + * Splits 4 bytes of each argument into 2 parts, each consisting of 2 bytes. + * For corresponding parts function computes signed maximum. Partial results + * are recombined and returned as unsigned int. + * \return Returns computed value. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __vmaxs2(unsigned int a, unsigned int b); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Performs per-halfword unsigned maximum computation. + * + * Splits 4 bytes of each argument into 2 parts, each consisting of 2 bytes. + * For corresponding parts function computes unsigned maximum. Partial results + * are recombined and returned as unsigned int. + * \return Returns computed value. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __vmaxu2(unsigned int a, unsigned int b); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Performs per-halfword signed minimum computation. + * + * Splits 4 bytes of each argument into 2 parts, each consisting of 2 bytes. + * For corresponding parts function computes signed minimum. Partial results + * are recombined and returned as unsigned int. + * \return Returns computed value. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __vmins2(unsigned int a, unsigned int b); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Performs per-halfword unsigned minimum computation. + * + * Splits 4 bytes of each argument into 2 parts, each consisting of 2 bytes. + * For corresponding parts function computes unsigned minimum. Partial results + * are recombined and returned as unsigned int. + * \return Returns computed value. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __vminu2(unsigned int a, unsigned int b); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Performs per-halfword (un)signed comparison: returns 1 if both parts compare equal. + * + * Splits 4 bytes of each argument into 2 parts, each consisting of 2 bytes. + * For corresponding parts function performs comparison 'a' part == 'b' part. + * If both equalities are satisfied, function returns 1. + * \return Returns 1 if a = b, else returns 0. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __vseteq2(unsigned int a, unsigned int b); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Performs per-halfword signed comparison: returns 1 if both parts compare greater than or equal. + * + * Splits 4 bytes of each argument into 2 parts, each consisting of 2 bytes. + * For corresponding parts function performs comparison 'a' part >= 'b' part. + * If both inequalities are satisfied, function returns 1. + * \return Returns 1 if a >= b, else returns 0. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __vsetges2(unsigned int a, unsigned int b); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Performs per-halfword unsigned comparison: returns 1 if both parts compare greater than or equal. + * + * Splits 4 bytes of each argument into 2 parts, each consisting of 2 bytes. + * For corresponding parts function performs comparison 'a' part >= 'b' part. + * If both inequalities are satisfied, function returns 1. + * \return Returns 1 if a >= b, else returns 0. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __vsetgeu2(unsigned int a, unsigned int b); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Performs per-halfword signed comparison: returns 1 if both parts compare greater than. + * + * Splits 4 bytes of each argument into 2 parts, each consisting of 2 bytes. + * For corresponding parts function performs comparison 'a' part > 'b' part. + * If both inequalities are satisfied, function returns 1. + * \return Returns 1 if a > b, else returns 0. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __vsetgts2(unsigned int a, unsigned int b); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Performs per-halfword unsigned comparison: returns 1 if both parts compare greater than. + * + * Splits 4 bytes of each argument into 2 parts, each consisting of 2 bytes. + * For corresponding parts function performs comparison 'a' part > 'b' part. + * If both inequalities are satisfied, function returns 1. + * \return Returns 1 if a > b, else returns 0. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __vsetgtu2(unsigned int a, unsigned int b); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Performs per-halfword unsigned comparison: returns 1 if both parts compare less than or equal. + * + * Splits 4 bytes of each argument into 2 parts, each consisting of 2 bytes. + * For corresponding parts function performs comparison 'a' part <= 'b' part. + * If both inequalities are satisfied, function returns 1. + * \return Returns 1 if a <= b, else returns 0. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __vsetles2(unsigned int a, unsigned int b); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Performs per-halfword signed comparison: returns 1 if both parts compare less than or equal. + * + * Splits 4 bytes of each argument into 2 parts, each consisting of 2 bytes. + * For corresponding parts function performs comparison 'a' part <= 'b' part. + * If both inequalities are satisfied, function returns 1. + * \return Returns 1 if a <= b, else returns 0. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __vsetleu2(unsigned int a, unsigned int b); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Performs per-halfword signed comparison: returns 1 if both parts compare less than. + * + * Splits 4 bytes of each argument into 2 parts, each consisting of 2 bytes. + * For corresponding parts function performs comparison 'a' part <= 'b' part. + * If both inequalities are satisfied, function returns 1. + * \return Returns 1 if a < b, else returns 0. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __vsetlts2(unsigned int a, unsigned int b); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Performs per-halfword unsigned comparison: returns 1 if both parts compare less than. + * + * Splits 4 bytes of each argument into 2 parts, each consisting of 2 bytes. + * For corresponding parts function performs comparison 'a' part <= 'b' part. + * If both inequalities are satisfied, function returns 1. + * \return Returns 1 if a < b, else returns 0. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __vsetltu2(unsigned int a, unsigned int b); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Performs per-halfword (un)signed comparison: returns 1 if both parts compare not equal. + * + * Splits 4 bytes of each argument into 2 parts, each consisting of 2 bytes. + * For corresponding parts function performs comparison 'a' part != 'b' part. + * If both conditions are satisfied, function returns 1. + * \return Returns 1 if a != b, else returns 0. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __vsetne2(unsigned int a, unsigned int b); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Computes per-halfword sum of abs diff of unsigned. + * + * Splits 4 bytes of each argument into 2 parts, each consisting of 2 bytes. + * For corresponding parts function computes absolute differences and returns + * sum of those differences. + * \return Returns computed value. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __vsadu2(unsigned int a, unsigned int b); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Performs per-halfword (un)signed subtraction, with wrap-around: a - b. + * + * Splits 4 bytes of each argument into 2 parts, each consisting of 2 bytes. + * For corresponding parts function performs subtraction. Partial results + * are recombined and returned as unsigned int. + * \return Returns computed value. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __vsub2(unsigned int a, unsigned int b); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Performs per-halfword (un)signed subtraction, with signed saturation: a - b. + * + * Splits 4 bytes of each argument into 2 parts, each consisting of 2 bytes. + * For corresponding parts function performs subtraction with signed saturation. + * Partial results are recombined and returned as unsigned int. + * \return Returns computed value. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __vsubss2 (unsigned int a, unsigned int b); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Performs per-halfword subtraction with unsigned saturation: a - b. + * + * Splits 4 bytes of each argument into 2 parts, each consisting of 2 bytes. + * For corresponding parts function performs subtraction with unsigned saturation. + * Partial results are recombined and returned as unsigned int. + * \return Returns computed value. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __vsubus2 (unsigned int a, unsigned int b); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Computes per-halfword negation. + * + * Splits 4 bytes of argument into 2 parts, each consisting of 2 bytes. + * For each part function computes negation. Partial results are recombined and returned as unsigned int. + * \return Returns computed value. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __vneg2(unsigned int a); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Computes per-halfword negation with signed saturation. + * + * Splits 4 bytes of argument into 2 parts, each consisting of 2 bytes. + * For each part function computes negation. Partial results are recombined and returned as unsigned int. + * \return Returns computed value. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __vnegss2(unsigned int a); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Computes per-halfword absolute difference of signed integer: |a - b|. + * + * Splits 4 bytes of each into 2 parts, each consisting of 2 bytes. + * For corresponding parts function computes absolute difference. + * Partial results are recombined and returned as unsigned int. + * \return Returns computed value. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __vabsdiffs2(unsigned int a, unsigned int b); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Performs per-halfword sum of absolute difference of signed. + * + * Splits 4 bytes of each argument into 2 parts, each consisting of 2 bytes. + * For corresponding parts function computes absolute difference and sum it up. + * Partial results are recombined and returned as unsigned int. + * \return Returns computed value. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __vsads2(unsigned int a, unsigned int b); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Computes per-byte absolute value: |a|. + * + * Splits argument by bytes. Computes absolute value of each byte. + * Partial results are recombined and returned as unsigned int. + * \return Returns computed value. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __vabs4(unsigned int a); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Computes per-byte absolute value with signed saturation: |a|. + * + * Splits 4 bytes of argument into 4 parts, each consisting of 1 byte, + * then computes absolute value with signed saturation for each of parts. + * Partial results are recombined and returned as unsigned int. + * \return Returns computed value. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __vabsss4(unsigned int a); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Performs per-byte (un)signed addition: a + b. + * + * Splits 'a' into 4 bytes, then performs unsigned addition on each of these + * bytes with the corresponding byte from 'b', ignoring overflow. + * Partial results are recombined and returned as unsigned int. + * \return Returns computed value. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __vadd4(unsigned int a, unsigned int b); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Performs per-byte addition with signed saturation: a + b. + * + * Splits 4 bytes of each argument into 4 parts, each consisting of 1 byte, + * then performs addition with signed saturation on corresponding parts. + * Partial results are recombined and returned as unsigned int. + * \return Returns computed value. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __vaddss4 (unsigned int a, unsigned int b); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Performs per-byte addition with unsigned saturation: a + b. + * + * Splits 4 bytes of each argument into 4 parts, each consisting of 1 byte, + * then performs addition with unsigned saturation on corresponding parts. + * \return Returns computed value. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __vaddus4 (unsigned int a, unsigned int b); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Computes per-byte signed rounded average. + * + * Splits 4 bytes of each argument into 4 parts, each consisting of 1 byte. + * then computes signed rounded average of corresponding parts. Partial results are + * recombined and returned as unsigned int. + * \return Returns computed value. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __vavgs4(unsigned int a, unsigned int b); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Performs per-byte unsigned rounded average. + * + * Splits 4 bytes of each argument into 4 parts, each consisting of 1 byte. + * then computes unsigned rounded average of corresponding parts. Partial results are + * recombined and returned as unsigned int. + * \return Returns computed value. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __vavgu4(unsigned int a, unsigned int b); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Computes per-byte unsigned average. + * + * Splits 4 bytes of each argument into 4 parts, each consisting of 1 byte. + * then computes unsigned average of corresponding parts. Partial results are + * recombined and returned as unsigned int. + * \return Returns computed value. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __vhaddu4(unsigned int a, unsigned int b); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Performs per-byte (un)signed comparison: a == b ? 0xff : 0. + * + * Splits 4 bytes of each argument into 4 parts, each consisting of 1 byte. + * For corresponding parts result is ff if they are equal, and 00 otherwise. + * For example __vcmpeq4(0x1234aba5, 0x1234aba6) returns 0xffffff00. + * \return Returns 0xff if a = b, else returns 0. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __vcmpeq4(unsigned int a, unsigned int b); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Performs per-byte signed comparison: a >= b ? 0xff : 0. + * + * Splits 4 bytes of each argument into 4 parts, each consisting of 1 byte. + * For corresponding parts result is ff if 'a' part >= 'b' part, and 00 otherwise. + * For example __vcmpges4(0x1234aba5, 0x1234aba6) returns 0xffffff00. + * \return Returns 0xff if a >= b, else returns 0. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __vcmpges4(unsigned int a, unsigned int b); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Performs per-byte unsigned comparison: a >= b ? 0xff : 0. + * + * Splits 4 bytes of each argument into 4 parts, each consisting of 1 byte. + * For corresponding parts result is ff if 'a' part >= 'b' part, and 00 otherwise. + * For example __vcmpgeu4(0x1234aba5, 0x1234aba6) returns 0xffffff00. + * \return Returns 0xff if a >= b, else returns 0. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __vcmpgeu4(unsigned int a, unsigned int b); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Performs per-byte signed comparison: a > b ? 0xff : 0. + * + * Splits 4 bytes of each argument into 4 parts, each consisting of 1 byte. + * For corresponding parts result is ff if 'a' part > 'b' part, and 00 otherwise. + * For example __vcmpgts4(0x1234aba5, 0x1234aba6) returns 0x00000000. + * \return Returns 0xff if a > b, else returns 0. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __vcmpgts4(unsigned int a, unsigned int b); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Performs per-byte unsigned comparison: a > b ? 0xff : 0. + * + * Splits 4 bytes of each argument into 4 parts, each consisting of 1 byte. + * For corresponding parts result is ff if 'a' part > 'b' part, and 00 otherwise. + * For example __vcmpgtu4(0x1234aba5, 0x1234aba6) returns 0x00000000. + * \return Returns 0xff if a > b, else returns 0. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __vcmpgtu4(unsigned int a, unsigned int b); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Performs per-byte signed comparison: a <= b ? 0xff : 0. + * + * Splits 4 bytes of each argument into 4 parts, each consisting of 1 byte. + * For corresponding parts result is ff if 'a' part <= 'b' part, and 00 otherwise. + * For example __vcmples4(0x1234aba5, 0x1234aba6) returns 0xffffffff. + * \return Returns 0xff if a <= b, else returns 0. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __vcmples4(unsigned int a, unsigned int b); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Performs per-byte unsigned comparison: a <= b ? 0xff : 0. + * + * Splits 4 bytes of each argument into 4 parts, each consisting of 1 byte. + * For corresponding parts result is ff if 'a' part <= 'b' part, and 00 otherwise. + * For example __vcmpleu4(0x1234aba5, 0x1234aba6) returns 0xffffffff. + * \return Returns 0xff if a <= b, else returns 0. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __vcmpleu4(unsigned int a, unsigned int b); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Performs per-byte signed comparison: a < b ? 0xff : 0. + * + * Splits 4 bytes of each argument into 4 parts, each consisting of 1 byte. + * For corresponding parts result is ff if 'a' part < 'b' part, and 00 otherwise. + * For example __vcmplts4(0x1234aba5, 0x1234aba6) returns 0x000000ff. + * \return Returns 0xff if a < b, else returns 0. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __vcmplts4(unsigned int a, unsigned int b); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Performs per-byte unsigned comparison: a < b ? 0xff : 0. + * + * Splits 4 bytes of each argument into 4 parts, each consisting of 1 byte. + * For corresponding parts result is ff if 'a' part < 'b' part, and 00 otherwise. + * For example __vcmpltu4(0x1234aba5, 0x1234aba6) returns 0x000000ff. + * \return Returns 0xff if a < b, else returns 0. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __vcmpltu4(unsigned int a, unsigned int b); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Performs per-byte (un)signed comparison: a != b ? 0xff : 0. + * + * Splits 4 bytes of each argument into 4 parts, each consisting of 1 byte. + * For corresponding parts result is ff if 'a' part != 'b' part, and 00 otherwise. + * For example __vcmplts4(0x1234aba5, 0x1234aba6) returns 0x000000ff. + * \return Returns 0xff if a != b, else returns 0. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __vcmpne4(unsigned int a, unsigned int b); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Computes per-byte absolute difference of unsigned integer: |a - b|. + * + * Splits 4 bytes of each argument into 4 parts, each consisting of 1 byte. + * For corresponding parts function computes absolute difference. Partial results + * are recombined and returned as unsigned int. + * \return Returns computed value. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __vabsdiffu4(unsigned int a, unsigned int b); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Computes per-byte signed maximum. + * + * Splits 4 bytes of each argument into 4 parts, each consisting of 1 byte. + * For corresponding parts function computes signed maximum. Partial results + * are recombined and returned as unsigned int. + * \return Returns computed value. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __vmaxs4(unsigned int a, unsigned int b); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Computes per-byte unsigned maximum. + * + * Splits 4 bytes of each argument into 4 parts, each consisting of 1 byte. + * For corresponding parts function computes unsigned maximum. Partial results + * are recombined and returned as unsigned int. + * \return Returns computed value. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __vmaxu4(unsigned int a, unsigned int b); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Computes per-byte signed minimum. + * + * Splits 4 bytes of each argument into 4 parts, each consisting of 1 byte. + * For corresponding parts function computes signed minimum. Partial results + * are recombined and returned as unsigned int. + * \return Returns computed value. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __vmins4(unsigned int a, unsigned int b); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Computes per-byte unsigned minimum. + * + * Splits 4 bytes of each argument into 4 parts, each consisting of 1 byte. + * For corresponding parts function computes unsigned minimum. Partial results + * are recombined and returned as unsigned int. + * \return Returns computed value. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __vminu4(unsigned int a, unsigned int b); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Performs per-byte (un)signed comparison: returns 1 if all 4 pairs compare equal. + * + * Splits 4 bytes of each argument into 4 parts, each consisting of 1 byte. + * For corresponding parts function performs comparison 'a' part == 'b' part. + * If both equalities are satisfied, function returns 1. + * \return Returns 1 if a = b, else returns 0. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __vseteq4(unsigned int a, unsigned int b); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Performs per-byte signed comparison: returns 1 if all 4 pairs compare less than or equal. + * + * Splits 4 bytes of each argument into 4 parts, each consisting of 1 byte. + * For corresponding parts function performs comparison 'a' part <= 'b' part. + * If both inequalities are satisfied, function returns 1. + * \return Returns 1 if a <= b, else returns 0. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __vsetles4(unsigned int a, unsigned int b); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Performs per-byte unsigned comparison: returns 1 if all 4 pairs compare less than or equal. + * + * Splits 4 bytes of each argument into 4 part, each consisting of 1 byte. + * For corresponding parts function performs comparison 'a' part <= 'b' part. + * If both inequalities are satisfied, function returns 1. + * \return Returns 1 if a <= b, else returns 0. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __vsetleu4(unsigned int a, unsigned int b); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Performs per-byte signed comparison: returns 1 if all 4 pairs compare less than. + * + * Splits 4 bytes of each argument into 4 parts, each consisting of 1 byte. + * For corresponding parts function performs comparison 'a' part <= 'b' part. + * If both inequalities are satisfied, function returns 1. + * \return Returns 1 if a < b, else returns 0. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __vsetlts4(unsigned int a, unsigned int b); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Performs per-byte unsigned comparison: returns 1 if all 4 pairs compare less than. + * + * Splits 4 bytes of each argument into 4 parts, each consisting of 1 byte. + * For corresponding parts function performs comparison 'a' part <= 'b' part. + * If both inequalities are satisfied, function returns 1. + * \return Returns 1 if a < b, else returns 0. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __vsetltu4(unsigned int a, unsigned int b); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Performs per-byte signed comparison: returns 1 if all 4 pairs compare greater than or equal. + * + * Splits 4 bytes of each argument into 4 parts, each consisting of 1 byte. + * For corresponding parts function performs comparison 'a' part >= 'b' part. + * If both inequalities are satisfied, function returns 1. + * \return Returns 1 if a >= b, else returns 0. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __vsetges4(unsigned int a, unsigned int b); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Performs per-byte unsigned comparison: returns 1 if all 4 pairs compare greater than or equal. + * + * Splits 4 bytes of each argument into 4 parts, each consisting of 1 byte. + * For corresponding parts function performs comparison 'a' part >= 'b' part. + * If both inequalities are satisfied, function returns 1. + * \return Returns 1 if a >= b, else returns 0. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __vsetgeu4(unsigned int a, unsigned int b); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Performs per-byte signed comparison: returns 1 if all 4 pairs compare greater than. + * + * Splits 4 bytes of each argument into 4 parts, each consisting of 1 byte. + * For corresponding parts function performs comparison 'a' part > 'b' part. + * If both inequalities are satisfied, function returns 1. + * \return Returns 1 if a > b, else returns 0. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __vsetgts4(unsigned int a, unsigned int b); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Performs per-byte unsigned comparison: returns 1 if all 4 pairs compare greater than. + * + * Splits 4 bytes of each argument into 4 parts, each consisting of 1 byte. + * For corresponding parts function performs comparison 'a' part > 'b' part. + * If both inequalities are satisfied, function returns 1. + * \return Returns 1 if a > b, else returns 0. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __vsetgtu4(unsigned int a, unsigned int b); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Performs per-byte (un)signed comparison: returns 1 if all 4 pairs compare not equal. + * + * Splits 4 bytes of each argument into 4 parts, each consisting of 1 byte. + * For corresponding parts function performs comparison 'a' part != 'b' part. + * If both conditions are satisfied, function returns 1. + * \return Returns 1 if a != b, else returns 0. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __vsetne4(unsigned int a, unsigned int b); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Computes per-byte sum of abs difference of unsigned. + * + * Splits 4 bytes of each argument into 4 parts, each consisting of 1 byte. + * For corresponding parts function computes absolute differences and returns + * sum of those differences. + * \return Returns computed value. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __vsadu4(unsigned int a, unsigned int b); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Performs per-byte subtraction: a - b. + * + * Splits 4 bytes of each argument into 4 parts, each consisting of 1 byte. + * For corresponding parts function performs subtraction. Partial results + * are recombined and returned as unsigned int. + * \return Returns computed value. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __vsub4(unsigned int a, unsigned int b); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Performs per-byte subtraction with signed saturation: a - b. + * + * Splits 4 bytes of each argument into 4 parts, each consisting of 1 byte. + * For corresponding parts function performs subtraction with signed saturation. + * Partial results are recombined and returned as unsigned int. + * \return Returns computed value. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __vsubss4(unsigned int a, unsigned int b); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Performs per-byte subtraction with unsigned saturation: a - b. + * + * Splits 4 bytes of each argument into 4 parts, each consisting of 1 byte. + * For corresponding parts function performs subtraction with unsigned saturation. + * Partial results are recombined and returned as unsigned int. + * \return Returns computed value. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __vsubus4(unsigned int a, unsigned int b); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Performs per-byte negation. + * + * Splits 4 bytes of argument into 4 parts, each consisting of 1 byte. + * For each part function computes negation. Partial results are recombined and returned as unsigned int. + * \return Returns computed value. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __vneg4(unsigned int a); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Performs per-byte negation with signed saturation. + * + * Splits 4 bytes of argument into 4 parts, each consisting of 1 byte. + * For each part function computes negation. Partial results are recombined and returned as unsigned int. + * \return Returns computed value. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __vnegss4(unsigned int a); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Computes per-byte absolute difference of signed integer: |a - b|. + * + * Splits 4 bytes of each into 4 parts, each consisting of 1 byte. + * For corresponding parts function computes absolute difference. + * Partial results are recombined and returned as unsigned int. + * \return Returns computed value. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __vabsdiffs4(unsigned int a, unsigned int b); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Computes per-byte sum of abs difference of signed. + * + * Splits 4 bytes of each argument into 4 parts, each consisting of 1 byte. + * For corresponding parts function computes absolute difference and sum it up. + * Partial results are recombined and returned as unsigned int. + * \return Returns computed value. + */ +__DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int __vsads4(unsigned int a, unsigned int b); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Computes max(max(a, b), 0) + * + * Calculates the maximum of \p a and \p b of two signed ints, if this is less than \p 0 then \p 0 is returned. + * \return Returns computed value. + */ + +__DEVICE_HOST_FUNCTIONS_STATIC_DECL__ int __vimax_s32_relu(const int a, const int b); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Performs per-halfword max(max(a, b), 0) + * + * Splits 4 bytes of each argument into 2 parts, each consisting of 2 bytes. + * These 2 byte parts are interpreted as signed shorts. + * For corresponding parts function performs a max with relu ( = max(a_part, b_part, 0) ). Partial results + * are recombined and returned as unsigned int. + * \return Returns computed value. + */ +__DEVICE_HOST_FUNCTIONS_STATIC_DECL__ unsigned int __vimax_s16x2_relu(const unsigned int a, const unsigned int b); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Computes max(min(a, b), 0) + * + * Calculates the minimum of \p a and \p b of two signed ints, if this is less than \p 0 then \p 0 is returned. + * \return Returns computed value. + */ +__DEVICE_HOST_FUNCTIONS_STATIC_DECL__ int __vimin_s32_relu(const int a, const int b); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Performs per-halfword max(min(a, b), 0) + * + * Splits 4 bytes of each argument into 2 parts, each consisting of 2 bytes. + * These 2 byte parts are interpreted as signed shorts. + * For corresponding parts function performs a min with relu ( = max(min(a_part, b_part), 0) ). Partial results + * are recombined and returned as unsigned int. + * \return Returns computed value. + */ +__DEVICE_HOST_FUNCTIONS_STATIC_DECL__ unsigned int __vimin_s16x2_relu(const unsigned int a, const unsigned int b); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Computes max(max(a, b), c) + * + * Calculates the 3-way max of signed integers \p a, \p b and \p c. + * \return Returns computed value. + */ +__DEVICE_HOST_FUNCTIONS_STATIC_DECL__ int __vimax3_s32(const int a, const int b, const int c); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Performs per-halfword max(max(a, b), c) + * + * Splits 4 bytes of each argument into 2 parts, each consisting of 2 bytes. + * These 2 byte parts are interpreted as signed shorts. + * For corresponding parts function performs a 3-way max ( = max(max(a_part, b_part), c_part) ). + * Partial results are recombined and returned as unsigned int. + * \return Returns computed value. + */ +__DEVICE_HOST_FUNCTIONS_STATIC_DECL__ unsigned int __vimax3_s16x2(const unsigned int a, const unsigned int b, const unsigned int c); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Computes max(max(a, b), c) + * + * Calculates the 3-way max of unsigned integers \p a, \p b and \p c. + * \return Returns computed value. + */ +__DEVICE_HOST_FUNCTIONS_STATIC_DECL__ unsigned int __vimax3_u32(const unsigned int a, const unsigned int b, const unsigned int c); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Performs per-halfword max(max(a, b), c) + * + * Splits 4 bytes of each argument into 2 parts, each consisting of 2 bytes. + * These 2 byte parts are interpreted as unsigned shorts. + * For corresponding parts function performs a 3-way max ( = max(max(a_part, b_part), c_part) ). + * Partial results are recombined and returned as unsigned int. + * \return Returns computed value. + */ +__DEVICE_HOST_FUNCTIONS_STATIC_DECL__ unsigned int __vimax3_u16x2(const unsigned int a, const unsigned int b, const unsigned int c); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Computes min(min(a, b), c) + * + * Calculates the 3-way min of signed integers \p a, \p b and \p c. + * \return Returns computed value. + */ +__DEVICE_HOST_FUNCTIONS_STATIC_DECL__ int __vimin3_s32(const int a, const int b, const int c); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Performs per-halfword min(min(a, b), c) + * + * Splits 4 bytes of each argument into 2 parts, each consisting of 2 bytes. + * These 2 byte parts are interpreted as signed shorts. + * For corresponding parts function performs a 3-way min ( = min(min(a_part, b_part), c_part) ). + * Partial results are recombined and returned as unsigned int. + * \return Returns computed value. + */ +__DEVICE_HOST_FUNCTIONS_STATIC_DECL__ unsigned int __vimin3_s16x2(const unsigned int a, const unsigned int b, const unsigned int c); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Computes min(min(a, b), c) + * + * Calculates the 3-way min of unsigned integers \p a, \p b and \p c. + * \return Returns computed value. + */ +__DEVICE_HOST_FUNCTIONS_STATIC_DECL__ unsigned int __vimin3_u32(const unsigned int a, const unsigned int b, const unsigned int c); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Performs per-halfword min(min(a, b), c) + * + * Splits 4 bytes of each argument into 2 parts, each consisting of 2 bytes. + * These 2 byte parts are interpreted as unsigned shorts. + * For corresponding parts function performs a 3-way min ( = min(min(a_part, b_part), c_part) ). + * Partial results are recombined and returned as unsigned int. + * \return Returns computed value. + */ +__DEVICE_HOST_FUNCTIONS_STATIC_DECL__ unsigned int __vimin3_u16x2(const unsigned int a, const unsigned int b, const unsigned int c); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Computes max(max(max(a, b), c), 0) + * + * Calculates the maximum of three signed ints, if this is less than \p 0 then \p 0 is returned. + * \return Returns computed value. + */ +__DEVICE_HOST_FUNCTIONS_STATIC_DECL__ int __vimax3_s32_relu(const int a, const int b, const int c); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Performs per-halfword max(max(max(a, b), c), 0) + * + * Splits 4 bytes of each argument into 2 parts, each consisting of 2 bytes. + * These 2 byte parts are interpreted as signed shorts. + * For corresponding parts function performs a three-way max with relu ( = max(a_part, b_part, c_part, 0) ). + * Partial results are recombined and returned as unsigned int. + * \return Returns computed value. + */ +__DEVICE_HOST_FUNCTIONS_STATIC_DECL__ unsigned int __vimax3_s16x2_relu(const unsigned int a, const unsigned int b, const unsigned int c); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Computes max(min(min(a, b), c), 0) + * + * Calculates the minimum of three signed ints, if this is less than \p 0 then \p 0 is returned. + * \return Returns computed value. + */ +__DEVICE_HOST_FUNCTIONS_STATIC_DECL__ int __vimin3_s32_relu(const int a, const int b, const int c); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Performs per-halfword max(min(min(a, b), c), 0) + * + * Splits 4 bytes of each argument into 2 parts, each consisting of 2 bytes. + * These 2 byte parts are interpreted as signed shorts. + * For corresponding parts function performs a three-way min with relu ( = max(min(a_part, b_part, c_part), 0) ). + * Partial results are recombined and returned as unsigned int. + * \return Returns computed value. + */ +__DEVICE_HOST_FUNCTIONS_STATIC_DECL__ unsigned int __vimin3_s16x2_relu(const unsigned int a, const unsigned int b, const unsigned int c); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Computes max(a + b, c) + * + * Calculates the sum of signed integers \p a and \p b and takes the max with \p c. + * \return Returns computed value. + */ +__DEVICE_HOST_FUNCTIONS_STATIC_DECL__ int __viaddmax_s32(const int a, const int b, const int c); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Performs per-halfword max(a + b, c) + * + * Splits 4 bytes of each argument into 2 parts, each consisting of 2 bytes. + * These 2 byte parts are interpreted as signed shorts. + * For corresponding parts function performs an add and compare: max(a_part + b_part), c_part) + * Partial results are recombined and returned as unsigned int. + * \return Returns computed value. + */ +__DEVICE_HOST_FUNCTIONS_STATIC_DECL__ unsigned int __viaddmax_s16x2(const unsigned int a, const unsigned int b, const unsigned int c); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Computes max(a + b, c) + * + * Calculates the sum of unsigned integers \p a and \p b and takes the max with \p c. + * \return Returns computed value. + */ +__DEVICE_HOST_FUNCTIONS_STATIC_DECL__ unsigned int __viaddmax_u32(const unsigned int a, const unsigned int b, const unsigned int c); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Performs per-halfword max(a + b, c) + * + * Splits 4 bytes of each argument into 2 parts, each consisting of 2 bytes. + * These 2 byte parts are interpreted as unsigned shorts. + * For corresponding parts function performs an add and compare: max(a_part + b_part), c_part) + * Partial results are recombined and returned as unsigned int. + * \return Returns computed value. + */ +__DEVICE_HOST_FUNCTIONS_STATIC_DECL__ unsigned int __viaddmax_u16x2(const unsigned int a, const unsigned int b, const unsigned int c); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Computes min(a + b, c) + * + * Calculates the sum of signed integers \p a and \p b and takes the min with \p c. + * \return Returns computed value. + */ +__DEVICE_HOST_FUNCTIONS_STATIC_DECL__ int __viaddmin_s32(const int a, const int b, const int c); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Performs per-halfword min(a + b, c) + * + * Splits 4 bytes of each argument into 2 parts, each consisting of 2 bytes. + * These 2 byte parts are interpreted as signed shorts. + * For corresponding parts function performs an add and compare: min(a_part + b_part), c_part) + * Partial results are recombined and returned as unsigned int. + * \return Returns computed value. + */ +__DEVICE_HOST_FUNCTIONS_STATIC_DECL__ unsigned int __viaddmin_s16x2(const unsigned int a, const unsigned int b, const unsigned int c); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Computes min(a + b, c) + * + * Calculates the sum of unsigned integers \p a and \p b and takes the min with \p c. + * \return Returns computed value. + */ +__DEVICE_HOST_FUNCTIONS_STATIC_DECL__ unsigned int __viaddmin_u32(const unsigned int a, const unsigned int b, const unsigned int c); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Performs per-halfword min(a + b, c) + * + * Splits 4 bytes of each argument into 2 parts, each consisting of 2 bytes. + * These 2 byte parts are interpreted as unsigned shorts. + * For corresponding parts function performs an add and compare: min(a_part + b_part), c_part) + * Partial results are recombined and returned as unsigned int. + * \return Returns computed value. + */ +__DEVICE_HOST_FUNCTIONS_STATIC_DECL__ unsigned int __viaddmin_u16x2(const unsigned int a, const unsigned int b, const unsigned int c); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Computes max(max(a + b, c), 0) + * + * Calculates the sum of signed integers \p a and \p b and takes the max with \p c. + * If the result is less than \p 0 then \p 0 is returned. + * \return Returns computed value. + */ +__DEVICE_HOST_FUNCTIONS_STATIC_DECL__ int __viaddmax_s32_relu(const int a, const int b, const int c); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Performs per-halfword max(max(a + b, c), 0) + * + * Splits 4 bytes of each argument into 2 parts, each consisting of 2 bytes. + * These 2 byte parts are interpreted as signed shorts. + * For corresponding parts function performs an add, followed by a max with relu: max(max(a_part + b_part), c_part), 0) + * Partial results are recombined and returned as unsigned int. + * \return Returns computed value. + */ +__DEVICE_HOST_FUNCTIONS_STATIC_DECL__ unsigned int __viaddmax_s16x2_relu(const unsigned int a, const unsigned int b, const unsigned int c); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Computes max(min(a + b, c), 0) + * + * Calculates the sum of signed integers \p a and \p b and takes the min with \p c. + * If the result is less than \p 0 then \p 0 is returned. + * \return Returns computed value. + */ +__DEVICE_HOST_FUNCTIONS_STATIC_DECL__ int __viaddmin_s32_relu(const int a, const int b, const int c); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Performs per-halfword max(min(a + b, c), 0) + * + * Splits 4 bytes of each argument into 2 parts, each consisting of 2 bytes. + * These 2 byte parts are interpreted as signed shorts. + * For corresponding parts function performs an add, followed by a min with relu: max(min(a_part + b_part), c_part), 0) + * Partial results are recombined and returned as unsigned int. + * \return Returns computed value. + */ +__DEVICE_HOST_FUNCTIONS_STATIC_DECL__ unsigned int __viaddmin_s16x2_relu(const unsigned int a, const unsigned int b, const unsigned int c); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Computes max(a, b), also sets the value pointed to by pred to (a >= b). + * + * Calculates the maximum of \p a and \p b of two signed ints. Also sets the value pointed to by \p pred to the value (a >= b). + * \return Returns computed values. + */ +__DEVICE_HOST_FUNCTIONS_STATIC_DECL__ int __vibmax_s32(const int a, const int b, bool* const pred); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Computes max(a, b), also sets the value pointed to by pred to (a >= b). + * + * Calculates the maximum of \p a and \p b of two unsigned ints. Also sets the value pointed to by \p pred to the value (a >= b). + * \return Returns computed values. + */ +__DEVICE_HOST_FUNCTIONS_STATIC_DECL__ unsigned int __vibmax_u32(const unsigned int a, const unsigned int b, bool* const pred); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Computes min(a, b), also sets the value pointed to by pred to (a <= b). + * + * Calculates the minimum of \p a and \p b of two signed ints. Also sets the value pointed to by \p pred to the value (a <= b). + * \return Returns computed values. + */ +__DEVICE_HOST_FUNCTIONS_STATIC_DECL__ int __vibmin_s32(const int a, const int b, bool* const pred); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Computes min(a, b), also sets the value pointed to by pred to (a <= b). + * + * Calculates the minimum of \p a and \p b of two unsigned ints. Also sets the value pointed to by \p pred to the value (a <= b). + * \return Returns computed values. + */ +__DEVICE_HOST_FUNCTIONS_STATIC_DECL__ unsigned int __vibmin_u32(const unsigned int a, const unsigned int b, bool* const pred); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Performs per-halfword max(a, b), also sets the value pointed to by pred_hi and pred_lo to the per-halfword result of (a >= b). + * + * Splits 4 bytes of each argument into 2 parts, each consisting of 2 bytes. + * These 2 byte parts are interpreted as signed shorts. + * For corresponding parts function performs a maximum ( = max(a_part, b_part) ). + * Partial results are recombined and returned as unsigned int. + * Sets the value pointed to by \p pred_hi to the value (a_high_part >= b_high_part). + * Sets the value pointed to by \p pred_lo to the value (a_low_part >= b_low_part). + * \return Returns computed values. + */ +__DEVICE_HOST_FUNCTIONS_STATIC_DECL__ unsigned int __vibmax_s16x2(const unsigned int a, const unsigned int b, bool* const pred_hi, bool* const pred_lo); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Performs per-halfword max(a, b), also sets the value pointed to by pred_hi and pred_lo to the per-halfword result of (a >= b). + * + * Splits 4 bytes of each argument into 2 parts, each consisting of 2 bytes. + * These 2 byte parts are interpreted as unsigned shorts. + * For corresponding parts function performs a maximum ( = max(a_part, b_part) ). + * Partial results are recombined and returned as unsigned int. + * Sets the value pointed to by \p pred_hi to the value (a_high_part >= b_high_part). + * Sets the value pointed to by \p pred_lo to the value (a_low_part >= b_low_part). + * \return Returns computed values. + */ +__DEVICE_HOST_FUNCTIONS_STATIC_DECL__ unsigned int __vibmax_u16x2(const unsigned int a, const unsigned int b, bool* const pred_hi, bool* const pred_lo); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Performs per-halfword min(a, b), also sets the value pointed to by pred_hi and pred_lo to the per-halfword result of (a <= b). + * + * Splits 4 bytes of each argument into 2 parts, each consisting of 2 bytes. + * These 2 byte parts are interpreted as signed shorts. + * For corresponding parts function performs a maximum ( = max(a_part, b_part) ). + * Partial results are recombined and returned as unsigned int. + * Sets the value pointed to by \p pred_hi to the value (a_high_part <= b_high_part). + * Sets the value pointed to by \p pred_lo to the value (a_low_part <= b_low_part). + * \return Returns computed values. + */ +__DEVICE_HOST_FUNCTIONS_STATIC_DECL__ unsigned int __vibmin_s16x2(const unsigned int a, const unsigned int b, bool* const pred_hi, bool* const pred_lo); + +/** + * \ingroup CUDA_MATH_INTRINSIC_SIMD + * \brief Performs per-halfword min(a, b), also sets the value pointed to by pred_hi and pred_lo to the per-halfword result of (a <= b). + * + * Splits 4 bytes of each argument into 2 parts, each consisting of 2 bytes. + * These 2 byte parts are interpreted as unsigned shorts. + * For corresponding parts function performs a maximum ( = max(a_part, b_part) ). + * Partial results are recombined and returned as unsigned int. + * Sets the value pointed to by \p pred_hi to the value (a_high_part <= b_high_part). + * Sets the value pointed to by \p pred_lo to the value (a_low_part <= b_low_part). + * \return Returns computed values. + */ +__DEVICE_HOST_FUNCTIONS_STATIC_DECL__ unsigned int __vibmin_u16x2(const unsigned int a, const unsigned int b, bool* const pred_hi, bool* const pred_lo); + +/******************************************************************************* + * * + * END SIMD functions * + * * + *******************************************************************************/ +} //extern "c" +#undef EXCLUDE_FROM_RTC + +#undef __DEVICE_FUNCTIONS_DECL__ +#undef __DEVICE_FUNCTIONS_STATIC_DECL__ +#undef __DEVICE_HOST_FUNCTIONS_STATIC_DECL__ + +#endif /* __cplusplus && __CUDACC__ */ + +/******************************************************************************* +* * +* * +* * +*******************************************************************************/ + +#if !defined(__CUDACC_RTC__) +#include "device_functions.hpp" +#endif /* !defined(__CUDACC_RTC__) */ + +#include "device_atomic_functions.h" +#include "device_double_functions.h" +#include "sm_20_atomic_functions.h" +#include "sm_32_atomic_functions.h" +#include "sm_35_atomic_functions.h" +#include "sm_60_atomic_functions.h" +#include "sm_20_intrinsics.h" +#include "sm_30_intrinsics.h" +#include "sm_32_intrinsics.h" +#include "sm_35_intrinsics.h" +#include "sm_61_intrinsics.h" +#include "sm_70_rt.h" +#include "sm_80_rt.h" +#include "sm_90_rt.h" +#include "sm_100_rt.h" +#ifndef __CUDACC_RTC_MINIMAL__ +#include "texture_indirect_functions.h" +#include "surface_indirect_functions.h" +#endif /* !__CUDACC_RTC_MINIMAL__ */ +#include "cudacc_ext.h" + +#ifdef __CUDACC__ +extern "C" __host__ __device__ unsigned CUDARTAPI __cudaPushCallConfiguration(dim3 gridDim, + dim3 blockDim, + size_t sharedMem = 0, + struct CUstream_st *stream = 0); + +#if !defined(__CUDACC_RTC__) &&!defined(__NV_LEGACY_LAUNCH) +extern "C" cudaError_t CUDARTAPI __cudaGetKernel(cudaKernel_t *, const void *); + +extern "C" cudaError_t CUDARTAPI __cudaLaunchKernel( + cudaKernel_t kernel, + dim3 gridDim, + dim3 blockDim, + void **args, + size_t sharedMem, + cudaStream_t stream +); + +extern "C" cudaError_t CUDARTAPI __cudaLaunchKernel_ptsz( + cudaKernel_t kernel, + dim3 gridDim, + dim3 blockDim, + void **args, + size_t sharedMem, + cudaStream_t stream +); + +//referenced from compiler generated kernel launch code +static inline cudaError_t __cudaLaunchKernel_helper( + cudaKernel_t kernel, + dim3 gridDim, + dim3 blockDim, + void **args, + size_t sharedMem, + cudaStream_t stream) +{ +#if defined(__CUDART_API_PER_THREAD_DEFAULT_STREAM) + return __cudaLaunchKernel_ptsz(kernel, gridDim, blockDim, args, sharedMem, + stream); +#else /* !__CUDART_API_PER_THREAD_DEFAULT_STREAM */ + return __cudaLaunchKernel(kernel, gridDim, blockDim, args, sharedMem, + stream); +#endif /* __CUDART_API_PER_THREAD_DEFAULT_STREAM */ +} +#endif /* !defined(__CUDACC_RTC__) && !defined(__NV_LEGACY_LAUNCH) */ + +enum { + __NV_ATOMIC_RELAXED, + __NV_ATOMIC_CONSUME, + __NV_ATOMIC_ACQUIRE, + __NV_ATOMIC_RELEASE, + __NV_ATOMIC_ACQ_REL, + __NV_ATOMIC_SEQ_CST +}; + +enum { + __NV_THREAD_SCOPE_THREAD, + __NV_THREAD_SCOPE_BLOCK, + __NV_THREAD_SCOPE_CLUSTER, + __NV_THREAD_SCOPE_DEVICE, + __NV_THREAD_SCOPE_SYSTEM +}; + +#endif /* __CUDACC__ */ + +#endif /* !__DEVICE_FUNCTIONS_H__ */ + +#if defined(__UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_DEVICE_FUNCTIONS_H__) +#undef __CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__ +#undef __UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_DEVICE_FUNCTIONS_H__ +#endif diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/device_functions.hpp b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/device_functions.hpp new file mode 100644 index 0000000000000000000000000000000000000000..429b2298a8fdd95338c132996b1d9dca74130193 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/device_functions.hpp @@ -0,0 +1,1163 @@ +/* + * Copyright 1993-2024 NVIDIA Corporation. All rights reserved. + * + * NOTICE TO LICENSEE: + * + * This source code and/or documentation ("Licensed Deliverables") are + * subject to NVIDIA intellectual property rights under U.S. and + * international Copyright laws. + * + * These Licensed Deliverables contained herein is PROPRIETARY and + * CONFIDENTIAL to NVIDIA and is being provided under the terms and + * conditions of a form of NVIDIA software license agreement by and + * between NVIDIA and Licensee ("License Agreement") or electronically + * accepted by Licensee. Notwithstanding any terms or conditions to + * the contrary in the License Agreement, reproduction or disclosure + * of the Licensed Deliverables to any third party without the express + * written consent of NVIDIA is prohibited. + * + * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE + * LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE + * SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE. IT IS + * PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND. + * NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED + * DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY, + * NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE. + * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE + * LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY + * SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY + * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS + * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THESE LICENSED DELIVERABLES. + * + * U.S. Government End Users. These Licensed Deliverables are a + * "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT + * 1995), consisting of "commercial computer software" and "commercial + * computer software documentation" as such terms are used in 48 + * C.F.R. 12.212 (SEPT 1995) and is provided to the U.S. Government + * only as a commercial end item. Consistent with 48 C.F.R.12.212 and + * 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all + * U.S. Government End Users acquire the Licensed Deliverables with + * only those rights set forth herein. + * + * Any use of the Licensed Deliverables in individual and commercial + * software must include, in the user documentation and internal + * comments to the code, the above Disclaimer and U.S. Government End + * Users Notice. + */ + +#if !defined(__CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__) +#if defined(_MSC_VER) +#pragma message("crt/device_functions.hpp is an internal header file and must not be used directly. Please use cuda_runtime_api.h or cuda_runtime.h instead.") +#else +#warning "crt/device_functions.hpp is an internal header file and must not be used directly. Please use cuda_runtime_api.h or cuda_runtime.h instead." +#endif +#define __CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__ +#define __UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_DEVICE_FUNCTIONS_HPP__ +#endif + +#if !defined(__DEVICE_FUNCTIONS_HPP__) +#define __DEVICE_FUNCTIONS_HPP__ + +/******************************************************************************* +* * +* * +* * +*******************************************************************************/ + +#if defined(__cplusplus) && defined(__CUDACC__) + +#if defined(__CUDACC_RTC__) +#define __DEVICE_FUNCTIONS_DECL__ __device__ +#define __DEVICE_FUNCTIONS_STATIC_DECL__ __device__ +#define __DEVICE_HOST_FUNCTIONS_STATIC_DECL__ __device__ __host__ __cudart_builtin__ +#else +#define __DEVICE_FUNCTIONS_DECL__ __device__ +#define __DEVICE_FUNCTIONS_STATIC_DECL__ static __inline__ __device__ +#define __DEVICE_HOST_FUNCTIONS_STATIC_DECL__ static __inline__ __device__ __host__ __cudart_builtin__ +#endif /* __CUDACC_RTC__ */ + +#include "builtin_types.h" +#include "device_types.h" +#include "host_defines.h" + +#undef __DEVICE_FUNCTIONS_DECL__ +#undef __DEVICE_FUNCTIONS_STATIC_DECL__ + +#endif /* __cplusplus && __CUDACC__ */ + +/******************************************************************************* +* * +* * +* * +*******************************************************************************/ + +#ifdef __CUDACC__ +# if defined(__CUDA_ARCH__) && (__CUDA_ARCH__ >= 900) +#define __CUDA_AND_AT_LEAST_SM_90__ +#endif /* defined(__CUDA_ARCH__) && (__CUDA_ARCH__ >= 900) */ +# if defined(__CUDA_ARCH__) && (__CUDA_ARCH__ >= 700) +#define __CUDA_AND_AT_LEAST_SM_70__ +#endif /* defined(__CUDA_ARCH__) && (__CUDA_ARCH__ >= 700) */ +# if defined(__CUDA_ARCH__) && (__CUDA_ARCH__ >= 750) +#define __CUDA_AND_AT_LEAST_SM_75__ +#endif /* defined(__CUDA_ARCH__) && (__CUDA_ARCH__ >= 750) */ +#endif /* __CUDACC__ */ + +/* C++ header for std::memcpy (used for type punning in host-side implementations). + * When compiling as a CUDA source file memcpy is provided implicitly. + * !defined(__CUDACC__) implies !defined(__CUDACC_RTC__). + */ +#if defined(__cplusplus) && !defined(__CUDACC__) +#include +#endif /* defined(__cplusplus) && !defined(__CUDACC__) */ + +static __host__ __device__ short __internal_cast_u2s(unsigned short x) +{ + short res; +#if defined(__CUDACC__) + (void)memcpy(&res, &x, sizeof(x)); +#else + (void)std::memcpy(&res, &x, sizeof(x)); +#endif + return res; +} + +__DEVICE_HOST_FUNCTIONS_STATIC_DECL__ int __vimax_s32_relu(const int a, const int b){ +#ifdef __CUDA_AND_AT_LEAST_SM_90__ + int res; + asm("{max.s32.relu %0, %1, %2;}" : "=r"(res) : "r"(a), "r"(b)); + return res; +#else + // Host and older architecture code + int ans = max(a, b); + + return (ans > 0) ? ans : 0; +#endif +} + +__DEVICE_HOST_FUNCTIONS_STATIC_DECL__ unsigned int __vimax_s16x2_relu(const unsigned int a, const unsigned int b){ + unsigned int res; +#ifdef __CUDA_AND_AT_LEAST_SM_90__ + asm("{max.s16x2.relu %0, %1, %2;}" : "=r"(res) : "r"(a), "r"(b)); +#elif defined(__CUDA_ARCH__) + res = __vmaxs2(__vmaxs2(a, b), 0U); +#else + // Host and older architecture code + // Separate our high and low bit: + unsigned short aU_lo = (unsigned short)(a & 0xFFFFU); + unsigned short aU_hi = (unsigned short)(a >> 16); + + unsigned short bU_lo = (unsigned short)(b & 0xFFFFU); + unsigned short bU_hi = (unsigned short)(b >> 16); + + //cast to signed: + short aS_lo = __internal_cast_u2s(aU_lo); + short aS_hi = __internal_cast_u2s(aU_hi); + + short bS_lo = __internal_cast_u2s(bU_lo); + short bS_hi = __internal_cast_u2s(bU_hi); + + // Get answer + int ansI_lo = max(aS_lo, bS_lo); + int ansI_hi = max(aS_hi, bS_hi); + + // relu + if(ansI_lo < 0){ ansI_lo = 0; } + if(ansI_hi < 0){ ansI_hi = 0; } + + // Cast back to unsigned: + unsigned ansU_lo = (unsigned)ansI_lo; + unsigned ansU_hi = (unsigned)ansI_hi; + + // Put answer back together: + res = ansU_lo | (ansU_hi << 16); +#endif + + return res; +} + +__DEVICE_HOST_FUNCTIONS_STATIC_DECL__ int __vimin_s32_relu(const int a, const int b){ +#ifdef __CUDA_AND_AT_LEAST_SM_90__ + int res; + asm("{min.s32.relu %0, %1, %2;}" : "=r"(res) : "r"(a), "r"(b)); + return res; +#else + // Host and older architecture code + int ans = min(a, b); + + return (ans > 0) ? ans : 0; +#endif +} + +__DEVICE_HOST_FUNCTIONS_STATIC_DECL__ unsigned int __vimin_s16x2_relu(const unsigned int a, const unsigned int b){ + unsigned int res; +#ifdef __CUDA_AND_AT_LEAST_SM_90__ + asm("{min.s16x2.relu %0, %1, %2;}" : "=r"(res) : "r"(a), "r"(b)); +#elif defined(__CUDA_ARCH__) + res = __vmaxs2(__vmins2(a, b), 0U); +#else + // Host and older architecture code + // Separate our high and low bit: + unsigned short aU_lo = (unsigned short)(a & 0xFFFFU); + unsigned short aU_hi = (unsigned short)(a >> 16); + + unsigned short bU_lo = (unsigned short)(b & 0xFFFFU); + unsigned short bU_hi = (unsigned short)(b >> 16); + + //cast to signed: + short aS_lo = __internal_cast_u2s(aU_lo); + short aS_hi = __internal_cast_u2s(aU_hi); + + short bS_lo = __internal_cast_u2s(bU_lo); + short bS_hi = __internal_cast_u2s(bU_hi); + + // Get answer + int ansI_lo = min(aS_lo, bS_lo); + int ansI_hi = min(aS_hi, bS_hi); + + // relu + if(ansI_lo < 0){ ansI_lo = 0; } + if(ansI_hi < 0){ ansI_hi = 0; } + + // Cast back to unsigned: + unsigned ansU_lo = (unsigned)ansI_lo; + unsigned ansU_hi = (unsigned)ansI_hi; + + // Put answer back together: + res = ansU_lo | (ansU_hi << 16); +#endif + + return res; +} + +__DEVICE_HOST_FUNCTIONS_STATIC_DECL__ int __vimax3_s32(const int a, const int b, const int c){ +#ifdef __CUDA_AND_AT_LEAST_SM_90__ + int res; + asm ("{.reg .s32 t1; \n\t" + "max.s32 t1, %1, %2; \n\t" + "max.s32 %0, t1, %3;}\n\t" + : "=r"(res) : "r"(a), "r"(b), "r"(c)); + return res; +#else + // Host and older architecture code + return max(max(a, b), c); +#endif +} + +__DEVICE_HOST_FUNCTIONS_STATIC_DECL__ unsigned int __vimax3_s16x2(const unsigned int a, const unsigned int b, const unsigned int c){ + unsigned int res; +#ifdef __CUDA_AND_AT_LEAST_SM_90__ + // Future asm code (naming/syntax may change): + asm ("{.reg .b32 t1; \n\t" + "max.s16x2 t1, %1, %2; \n\t" + "max.s16x2 %0, t1, %3;}\n\t" + : "=r"(res) : "r"(a), "r"(b), "r"(c)); +#elif defined(__CUDA_AND_AT_LEAST_SM_70__) + res = __vmaxs2(__vmaxs2(a, b), c); +#else + // Host and older architecture code + // Separate our high and low bit: + unsigned short aU_lo = (unsigned short)(a & 0xFFFFU); + unsigned short aU_hi = (unsigned short)(a >> 16); + + unsigned short bU_lo = (unsigned short)(b & 0xFFFFU); + unsigned short bU_hi = (unsigned short)(b >> 16); + + unsigned short cU_lo = (unsigned short)(c & 0xFFFFU); + unsigned short cU_hi = (unsigned short)(c >> 16); + + //cast to signed: + short aS_lo = __internal_cast_u2s(aU_lo); + short aS_hi = __internal_cast_u2s(aU_hi); + + short bS_lo = __internal_cast_u2s(bU_lo); + short bS_hi = __internal_cast_u2s(bU_hi); + + short cS_lo = __internal_cast_u2s(cU_lo); + short cS_hi = __internal_cast_u2s(cU_hi); + + // Get answer + unsigned int ansU_lo = (unsigned int)max(max(aS_lo, bS_lo), cS_lo); + unsigned int ansU_hi = (unsigned int)max(max(aS_hi, bS_hi), cS_hi); + + // Put answer back together: + res = (ansU_lo & 0x0000FFFFU) | (ansU_hi << 16); +#endif + return res; +} + +__DEVICE_HOST_FUNCTIONS_STATIC_DECL__ unsigned int __vimax3_u32(const unsigned int a, const unsigned int b, const unsigned int c){ +#ifdef __CUDA_AND_AT_LEAST_SM_90__ +int res; + asm ("{.reg .u32 t1; \n\t" + "max.u32 t1, %1, %2; \n\t" + "max.u32 %0, t1, %3;}\n\t" + : "=r"(res) : "r"(a), "r"(b), "r"(c)); + return res; +#else + // Host and older architecture code + return max(max(a, b), c); +#endif +} + +__DEVICE_HOST_FUNCTIONS_STATIC_DECL__ unsigned int __vimax3_u16x2(const unsigned int a, const unsigned int b, const unsigned int c){ + unsigned int res; +#ifdef __CUDA_AND_AT_LEAST_SM_90__ + asm ("{.reg .b32 t1; \n\t" + "max.u16x2 t1, %1, %2; \n\t" + "max.u16x2 %0, t1, %3;}\n\t" + : "=r"(res) : "r"(a), "r"(b), "r"(c)); +#elif defined(__CUDA_ARCH__) + res = __vmaxu2(__vmaxu2(a, b), c); +#else + // Host and older architecture code + // Separate our high and low bit: + unsigned short aU_lo = (unsigned short)(a & 0xFFFFU); + unsigned short aU_hi = (unsigned short)(a >> 16); + + unsigned short bU_lo = (unsigned short)(b & 0xFFFFU); + unsigned short bU_hi = (unsigned short)(b >> 16); + + unsigned short cU_lo = (unsigned short)(c & 0xFFFFU); + unsigned short cU_hi = (unsigned short)(c >> 16); + + // Get answer + unsigned short ansU_lo = (unsigned short)max(max(aU_lo, bU_lo), cU_lo); + unsigned short ansU_hi = (unsigned short)max(max(aU_hi, bU_hi), cU_hi); + + // Put answer back together: + res = ((unsigned int) ansU_lo) | (((unsigned int) ansU_hi) << 16); +#endif + + return res; +} + +__DEVICE_HOST_FUNCTIONS_STATIC_DECL__ int __vimin3_s32(const int a, const int b, const int c){ +#ifdef __CUDA_AND_AT_LEAST_SM_90__ + int res; + asm ("{.reg .s32 t1; \n\t" + "min.s32 t1, %1, %2; \n\t" + "min.s32 %0, t1, %3;}\n\t" + : "=r"(res) : "r"(a), "r"(b), "r"(c)); + return res; +#else + // Host and older architecture code + return min(min(a, b), c); +#endif +} + +__DEVICE_HOST_FUNCTIONS_STATIC_DECL__ unsigned int __vimin3_s16x2(const unsigned int a, const unsigned int b, const unsigned int c){ + unsigned int res; +#ifdef __CUDA_AND_AT_LEAST_SM_90__ + asm ("{.reg .b32 t1; \n\t" + "min.s16x2 t1, %1, %2; \n\t" + "min.s16x2 %0, t1, %3;}\n\t" + : "=r"(res) : "r"(a), "r"(b), "r"(c)); +#elif defined(__CUDA_AND_AT_LEAST_SM_70__) + res = __vmins2(__vmins2(a, b), c); +#else + // Host and older architecture code + // Separate our high and low bit: + unsigned short aU_lo = (unsigned short)(a & 0xFFFFU); + unsigned short aU_hi = (unsigned short)(a >> 16); + + unsigned short bU_lo = (unsigned short)(b & 0xFFFFU); + unsigned short bU_hi = (unsigned short)(b >> 16); + + unsigned short cU_lo = (unsigned short)(c & 0xFFFFU); + unsigned short cU_hi = (unsigned short)(c >> 16); + + //cast to signed: + short aS_lo = __internal_cast_u2s(aU_lo); + short aS_hi = __internal_cast_u2s(aU_hi); + + short bS_lo = __internal_cast_u2s(bU_lo); + short bS_hi = __internal_cast_u2s(bU_hi); + + short cS_lo = __internal_cast_u2s(cU_lo); + short cS_hi = __internal_cast_u2s(cU_hi); + + // Get answer + unsigned int ansU_lo = (unsigned int)min(min(aS_lo, bS_lo), cS_lo); + unsigned int ansU_hi = (unsigned int)min(min(aS_hi, bS_hi), cS_hi); + + // Put answer back together: + res = (ansU_lo & 0x0000FFFFU) | (ansU_hi << 16); +#endif + + return res; +} + +__DEVICE_HOST_FUNCTIONS_STATIC_DECL__ unsigned int __vimin3_u32(const unsigned int a, const unsigned int b, const unsigned int c){ +#ifdef __CUDA_AND_AT_LEAST_SM_90__ + int res; + asm ("{.reg .u32 t1; \n\t" + "min.u32 t1, %1, %2; \n\t" + "min.u32 %0, t1, %3;}\n\t" + : "=r"(res) : "r"(a), "r"(b), "r"(c)); + return res; +#else + // Host and older architecture code + return min(min(a, b), c); +#endif +} + +__DEVICE_HOST_FUNCTIONS_STATIC_DECL__ unsigned int __vimin3_u16x2(const unsigned int a, const unsigned int b, const unsigned int c){ + unsigned int res; +#ifdef __CUDA_AND_AT_LEAST_SM_90__ + asm ("{.reg .b32 t1; \n\t" + "min.u16x2 t1, %1, %2; \n\t" + "min.u16x2 %0, t1, %3;}\n\t" + : "=r"(res) : "r"(a), "r"(b), "r"(c)); +#elif defined(__CUDA_ARCH__) + res = __vminu2(__vminu2(a, b), c); +#else + // Host and older architecture code + // Separate our high and low bit: + unsigned short aU_lo = (unsigned short)(a & 0xFFFFU); + unsigned short aU_hi = (unsigned short)(a >> 16); + + unsigned short bU_lo = (unsigned short)(b & 0xFFFFU); + unsigned short bU_hi = (unsigned short)(b >> 16); + + unsigned short cU_lo = (unsigned short)(c & 0xFFFFU); + unsigned short cU_hi = (unsigned short)(c >> 16); + + // Get answer + unsigned short ansU_lo = (unsigned short)min(min(aU_lo, bU_lo), cU_lo); + unsigned short ansU_hi = (unsigned short)min(min(aU_hi, bU_hi), cU_hi); + + // Put answer back together: + res = ((unsigned int) ansU_lo) | (((unsigned int) ansU_hi) << 16); +#endif + + return res; +} + +__DEVICE_HOST_FUNCTIONS_STATIC_DECL__ int __vimax3_s32_relu(const int a, const int b, const int c){ +#ifdef __CUDA_AND_AT_LEAST_SM_90__ + int res; + asm ("{.reg .s32 t1; \n\t" + "max.s32.relu t1, %1, %2; \n\t" + "max.s32.relu %0, t1, %3;}\n\t" + : "=r"(res) : "r"(a), "r"(b), "r"(c)); + return res; +#else + // Host and older architecture code + int ans = max(max(a, b), c); + + return (ans > 0) ? ans : 0; +#endif +} + +__DEVICE_HOST_FUNCTIONS_STATIC_DECL__ unsigned int __vimax3_s16x2_relu(const unsigned int a, const unsigned int b, const unsigned int c){ + unsigned int res; +#ifdef __CUDA_AND_AT_LEAST_SM_90__ + asm ("{.reg .b32 t1; \n\t" + "max.s16x2.relu t1, %1, %2; \n\t" + "max.s16x2.relu %0, t1, %3;}\n\t" + : "=r"(res) : "r"(a), "r"(b), "r"(c)); +#elif defined(__CUDA_AND_AT_LEAST_SM_75__) + res = __vimax_s16x2_relu(__vmaxs2(a, b), c); +#else + // Host and older architecture code + // Separate our high and low bit: + unsigned short aU_lo = (unsigned short)(a & 0xFFFFU); + unsigned short aU_hi = (unsigned short)(a >> 16); + + unsigned short bU_lo = (unsigned short)(b & 0xFFFFU); + unsigned short bU_hi = (unsigned short)(b >> 16); + + unsigned short cU_lo = (unsigned short)(c & 0xFFFFU); + unsigned short cU_hi = (unsigned short)(c >> 16); + + //cast to signed: + short aS_lo = __internal_cast_u2s(aU_lo); + short aS_hi = __internal_cast_u2s(aU_hi); + + short bS_lo = __internal_cast_u2s(bU_lo); + short bS_hi = __internal_cast_u2s(bU_hi); + + short cS_lo = __internal_cast_u2s(cU_lo); + short cS_hi = __internal_cast_u2s(cU_hi); + + // Get answer + unsigned ansU_lo = (unsigned)max(0, max(max(aS_lo, bS_lo), cS_lo)); + unsigned ansU_hi = (unsigned)max(0, max(max(aS_hi, bS_hi), cS_hi)); + + // Put answer back together: + res = ansU_lo | (ansU_hi << 16); +#endif + + return res; +} + +__DEVICE_HOST_FUNCTIONS_STATIC_DECL__ int __vimin3_s32_relu(const int a, const int b, const int c){ +#ifdef __CUDA_AND_AT_LEAST_SM_90__ + int res; + asm ("{.reg .s32 t1; \n\t" + "min.s32.relu t1, %1, %2; \n\t" + "min.s32.relu %0, t1, %3;}\n\t" + : "=r"(res) : "r"(a), "r"(b), "r"(c)); + return res; +#else + // Host and older architecture code + int ans = min(min(a, b), c); + + return (ans > 0) ? ans : 0; +#endif +} + +__DEVICE_HOST_FUNCTIONS_STATIC_DECL__ unsigned int __vimin3_s16x2_relu(const unsigned int a, const unsigned int b, const unsigned int c){ + unsigned res; +#ifdef __CUDA_AND_AT_LEAST_SM_90__ + asm ("{.reg .b32 t1; \n\t" + "min.s16x2.relu t1, %1, %2; \n\t" + "min.s16x2.relu %0, t1, %3;}\n\t" + : "=r"(res) : "r"(a), "r"(b), "r"(c)); +#elif defined(__CUDA_AND_AT_LEAST_SM_75__) + res = __vimin_s16x2_relu(__vmins2(a, b), c); +#else + // Host and older architecture code + // Separate our high and low bit: + unsigned short aU_lo = (unsigned short)(a & 0xFFFFU); + unsigned short aU_hi = (unsigned short)(a >> 16); + + unsigned short bU_lo = (unsigned short)(b & 0xFFFFU); + unsigned short bU_hi = (unsigned short)(b >> 16); + + unsigned short cU_lo = (unsigned short)(c & 0xFFFFU); + unsigned short cU_hi = (unsigned short)(c >> 16); + + //cast to signed: + short aS_lo = __internal_cast_u2s(aU_lo); + short aS_hi = __internal_cast_u2s(aU_hi); + + short bS_lo = __internal_cast_u2s(bU_lo); + short bS_hi = __internal_cast_u2s(bU_hi); + + short cS_lo = __internal_cast_u2s(cU_lo); + short cS_hi = __internal_cast_u2s(cU_hi); + + // Get answer + unsigned ansU_lo = (unsigned)max(0, min(min(aS_lo, bS_lo), cS_lo)); + unsigned ansU_hi = (unsigned)max(0, min(min(aS_hi, bS_hi), cS_hi)); + + // Put answer back together: + res = ansU_lo | (ansU_hi << 16); + +#endif + + return res; +} + +__DEVICE_HOST_FUNCTIONS_STATIC_DECL__ int __viaddmax_s32(const int a, const int b, const int c){ +#ifdef __CUDA_AND_AT_LEAST_SM_90__ + int res; + asm ("{.reg .s32 t1; \n\t" + "add.s32 t1, %1, %2; \n\t" + "max.s32 %0, t1, %3;}\n\t" + : "=r"(res) : "r"(a), "r"(b), "r"(c)); + return res; +#else + // Host and older architecture code + return max(a + b, c); +#endif +} + +__DEVICE_HOST_FUNCTIONS_STATIC_DECL__ unsigned int __viaddmax_s16x2(const unsigned int a, const unsigned int b, const unsigned int c){ + unsigned int res; +#ifdef __CUDA_AND_AT_LEAST_SM_90__ + asm ("{.reg .b32 t1; \n\t" + "add.s16x2 t1, %1, %2; \n\t" + "max.s16x2 %0, t1, %3;}\n\t" + : "=r"(res) : "r"(a), "r"(b), "r"(c)); +#elif defined(__CUDA_ARCH__) + res = __vmaxs2(__vadd2(a, b), c); +#else + // Host and older architecture code + // Separate our high and low bit: + unsigned short aU_lo = (unsigned short)(a & 0xFFFFU); + unsigned short aU_hi = (unsigned short)(a >> 16); + + unsigned short bU_lo = (unsigned short)(b & 0xFFFFU); + unsigned short bU_hi = (unsigned short)(b >> 16); + + unsigned short cU_lo = (unsigned short)(c & 0xFFFFU); + unsigned short cU_hi = (unsigned short)(c >> 16); + + aU_lo += bU_lo; + aU_hi += bU_hi; + + //cast to signed: + short sS_lo = __internal_cast_u2s(aU_lo); + short sS_hi = __internal_cast_u2s(aU_hi); + + short cS_lo = __internal_cast_u2s(cU_lo); + short cS_hi = __internal_cast_u2s(cU_hi); + + // Get answer + unsigned ansU_lo = (unsigned)max(sS_lo, cS_lo); + unsigned ansU_hi = (unsigned)max(sS_hi, cS_hi); + + // Put answer back together: + res = (ansU_lo & 0x0000FFFFU) | (ansU_hi << 16); +#endif + + return res; +} + +__DEVICE_HOST_FUNCTIONS_STATIC_DECL__ unsigned int __viaddmax_u32(const unsigned int a, const unsigned int b, const unsigned int c){ +#ifdef __CUDA_AND_AT_LEAST_SM_90__ + unsigned int res; + asm ("{.reg .u32 t1; \n\t" + "add.u32 t1, %1, %2; \n\t" + "max.u32 %0, t1, %3;}\n\t" + : "=r"(res) : "r"(a), "r"(b), "r"(c)); + return res; +#else + // Host and older architecture code + return max(a + b, c); +#endif +} + +__DEVICE_HOST_FUNCTIONS_STATIC_DECL__ unsigned int __viaddmax_u16x2(const unsigned int a, const unsigned int b, const unsigned int c){ + unsigned int res; +#ifdef __CUDA_AND_AT_LEAST_SM_90__ + asm ("{.reg .b32 t1; \n\t" + "add.u16x2 t1, %1, %2; \n\t" + "max.u16x2 %0, t1, %3;}\n\t" + : "=r"(res) : "r"(a), "r"(b), "r"(c)); +#elif defined(__CUDA_ARCH__) + res = __vmaxu2(__vadd2(a, b), c); +#else + // Host and older architecture code + // Separate our high and low bit: + unsigned short aU_lo = (unsigned short)(a & 0xFFFFU); + unsigned short aU_hi = (unsigned short)(a >> 16); + + unsigned short bU_lo = (unsigned short)(b & 0xFFFFU); + unsigned short bU_hi = (unsigned short)(b >> 16); + + unsigned short cU_lo = (unsigned short)(c & 0xFFFFU); + unsigned short cU_hi = (unsigned short)(c >> 16); + + // Get answer + unsigned short ansU_lo = (unsigned short)max((unsigned short)(aU_lo + bU_lo), cU_lo); + unsigned short ansU_hi = (unsigned short)max((unsigned short)(aU_hi + bU_hi), cU_hi); + + // Put answer back together: + res = ((unsigned int) ansU_lo) | (((unsigned int) ansU_hi) << 16); +#endif + + return res; +} + +__DEVICE_HOST_FUNCTIONS_STATIC_DECL__ int __viaddmin_s32(const int a, const int b, const int c){ +#ifdef __CUDA_AND_AT_LEAST_SM_90__ + int res; + asm ("{.reg .s32 t1; \n\t" + "add.s32 t1, %1, %2; \n\t" + "min.s32 %0, t1, %3;}\n\t" + : "=r"(res) : "r"(a), "r"(b), "r"(c)); + return res; +#else + // Host and older architecture code + return min(a + b, c); +#endif +} + +__DEVICE_HOST_FUNCTIONS_STATIC_DECL__ unsigned int __viaddmin_s16x2(const unsigned int a, const unsigned int b, const unsigned int c){ + unsigned int res; +#ifdef __CUDA_AND_AT_LEAST_SM_90__ + asm ("{.reg .b32 t1; \n\t" + "add.s16x2 t1, %1, %2; \n\t" + "min.s16x2 %0, t1, %3;}\n\t" + : "=r"(res) : "r"(a), "r"(b), "r"(c)); +#elif defined(__CUDA_ARCH__) + res = __vmins2(__vadd2(a, b), c); +#else + // Host and older architecture code + // Separate our high and low bit: + unsigned short aU_lo = (unsigned short)(a & 0xFFFFU); + unsigned short aU_hi = (unsigned short)(a >> 16); + + unsigned short bU_lo = (unsigned short)(b & 0xFFFFU); + unsigned short bU_hi = (unsigned short)(b >> 16); + + unsigned short cU_lo = (unsigned short)(c & 0xFFFFU); + unsigned short cU_hi = (unsigned short)(c >> 16); + + aU_lo += bU_lo; + aU_hi += bU_hi; + + //cast to signed: + short sS_lo = __internal_cast_u2s(aU_lo); + short sS_hi = __internal_cast_u2s(aU_hi); + + short cS_lo = __internal_cast_u2s(cU_lo); + short cS_hi = __internal_cast_u2s(cU_hi); + + // Get answer + unsigned ansU_lo = (unsigned)min(sS_lo, cS_lo); + unsigned ansU_hi = (unsigned)min(sS_hi, cS_hi); + + // Put answer back together: + res = (ansU_lo & 0x0000FFFFU) | (ansU_hi << 16); +#endif + + return res; +} + +__DEVICE_HOST_FUNCTIONS_STATIC_DECL__ unsigned int __viaddmin_u32(const unsigned int a, const unsigned int b, const unsigned int c){ +#ifdef __CUDA_AND_AT_LEAST_SM_90__ + unsigned int res; + asm ("{.reg .u32 t1; \n\t" + "add.u32 t1, %1, %2; \n\t" + "min.u32 %0, t1, %3;}\n\t" + : "=r"(res) : "r"(a), "r"(b), "r"(c)); + return res; +#else + // Host and older architecture code + return min(a + b, c); +#endif +} + +__DEVICE_HOST_FUNCTIONS_STATIC_DECL__ unsigned int __viaddmin_u16x2(const unsigned int a, const unsigned int b, const unsigned int c){ + unsigned int res; +#ifdef __CUDA_AND_AT_LEAST_SM_90__ + asm ("{.reg .b32 t1; \n\t" + "add.u16x2 t1, %1, %2; \n\t" + "min.u16x2 %0, t1, %3;}\n\t" + : "=r"(res) : "r"(a), "r"(b), "r"(c)); +#elif defined(__CUDA_ARCH__) + res = __vminu2(__vadd2(a, b), c); +#else + // Host and older architecture code + // Separate our high and low bit: + unsigned short aU_lo = (unsigned short)(a & 0xFFFFU); + unsigned short aU_hi = (unsigned short)(a >> 16); + + unsigned short bU_lo = (unsigned short)(b & 0xFFFFU); + unsigned short bU_hi = (unsigned short)(b >> 16); + + unsigned short cU_lo = (unsigned short)(c & 0xFFFFU); + unsigned short cU_hi = (unsigned short)(c >> 16); + + // Get answer + unsigned short ansU_lo = (unsigned short)min((unsigned short)(aU_lo + bU_lo), cU_lo); + unsigned short ansU_hi = (unsigned short)min((unsigned short)(aU_hi + bU_hi), cU_hi); + + // Put answer back together: + res = ((unsigned int) ansU_lo) | (((unsigned int) ansU_hi) << 16); +#endif + + return res; +} + +__DEVICE_HOST_FUNCTIONS_STATIC_DECL__ int __viaddmax_s32_relu(const int a, const int b, const int c){ +#ifdef __CUDA_AND_AT_LEAST_SM_90__ + int res; + asm ("{.reg .s32 t1; \n\t" + "add.s32 t1, %1, %2; \n\t" + "max.s32.relu %0, t1, %3;}\n\t" + : "=r"(res) : "r"(a), "r"(b), "r"(c)); + return res; +#else + // Host and older architecture code + int ans = max(a + b, c); + + return (ans > 0) ? ans : 0; +#endif +} + +__DEVICE_HOST_FUNCTIONS_STATIC_DECL__ unsigned int __viaddmax_s16x2_relu(const unsigned int a, const unsigned int b, const unsigned int c){ + unsigned int res; +#ifdef __CUDA_AND_AT_LEAST_SM_90__ + asm ("{.reg .b32 t1; \n\t" + "add.s16x2 t1, %1, %2; \n\t" + "max.s16x2.relu %0, t1, %3;}\n\t" + : "=r"(res) : "r"(a), "r"(b), "r"(c)); +#elif defined(__CUDA_ARCH__) + res = __vimax_s16x2_relu(__vadd2(a, b), c); +#else + // Host and older architecture code + // Separate our high and low bit: + unsigned short aU_lo = (unsigned short)(a & 0xFFFFU); + unsigned short aU_hi = (unsigned short)(a >> 16); + + unsigned short bU_lo = (unsigned short)(b & 0xFFFFU); + unsigned short bU_hi = (unsigned short)(b >> 16); + + unsigned short cU_lo = (unsigned short)(c & 0xFFFFU); + unsigned short cU_hi = (unsigned short)(c >> 16); + + aU_lo += bU_lo; + aU_hi += bU_hi; + + //cast to signed: + short sS_lo = __internal_cast_u2s(aU_lo); + short sS_hi = __internal_cast_u2s(aU_hi); + + short cS_lo = __internal_cast_u2s(cU_lo); + short cS_hi = __internal_cast_u2s(cU_hi); + + // Get answer + unsigned ansU_lo = (unsigned)max(0, max(sS_lo, cS_lo)); + unsigned ansU_hi = (unsigned)max(0, max(sS_hi, cS_hi)); + + // Put answer back together: + res = ansU_lo | (ansU_hi << 16); +#endif + + return res; +} + +__DEVICE_HOST_FUNCTIONS_STATIC_DECL__ int __viaddmin_s32_relu(const int a, const int b, const int c){ +#ifdef __CUDA_AND_AT_LEAST_SM_90__ + int res; + asm ("{.reg .s32 t1; \n\t" + "add.s32 t1, %1, %2; \n\t" + "min.s32.relu %0, t1, %3;}\n\t" + : "=r"(res) : "r"(a), "r"(b), "r"(c)); + return res; +#else + // Host and older architecture code + int ans = min(a + b, c); + + return (ans > 0) ? ans : 0; +#endif +} + +__DEVICE_HOST_FUNCTIONS_STATIC_DECL__ unsigned int __viaddmin_s16x2_relu(const unsigned int a, const unsigned int b, const unsigned int c){ + unsigned int res; +#ifdef __CUDA_AND_AT_LEAST_SM_90__ + asm ("{.reg .b32 t1; \n\t" + "add.s16x2 t1, %1, %2; \n\t" + "min.s16x2.relu %0, t1, %3;}\n\t" + : "=r"(res) : "r"(a), "r"(b), "r"(c)); +#elif defined(__CUDA_ARCH__) + res = __vimin_s16x2_relu(__vadd2(a, b), c); +#else + // Host and older architecture code + // Separate our high and low bit: + unsigned short aU_lo = (unsigned short)(a & 0xFFFFU); + unsigned short aU_hi = (unsigned short)(a >> 16); + + unsigned short bU_lo = (unsigned short)(b & 0xFFFFU); + unsigned short bU_hi = (unsigned short)(b >> 16); + + unsigned short cU_lo = (unsigned short)(c & 0xFFFFU); + unsigned short cU_hi = (unsigned short)(c >> 16); + + aU_lo += bU_lo; + aU_hi += bU_hi; + + //cast to signed: + short sS_lo = __internal_cast_u2s(aU_lo); + short sS_hi = __internal_cast_u2s(aU_hi); + + short cS_lo = __internal_cast_u2s(cU_lo); + short cS_hi = __internal_cast_u2s(cU_hi); + + // Get answer + unsigned ansU_lo = (unsigned)max(0, min(sS_lo, cS_lo)); + unsigned ansU_hi = (unsigned)max(0, min(sS_hi, cS_hi)); + + // Put answer back together: + res = ansU_lo | (ansU_hi << 16); +#endif + + return res; +} + +// vimax vimin with predicate +// *pred gets set to '(a >= b)' +__DEVICE_HOST_FUNCTIONS_STATIC_DECL__ int __vibmax_s32(const int a, const int b, bool* const pred){ +#ifdef __CUDA_AND_AT_LEAST_SM_90__ + int val; + unsigned int predicate_local; + asm ("{ .reg .pred __$temp1;\n\t" + " setp.ge.s32 __$temp1, %2, %3;\n\t" + " selp.s32 %0, %2, %3, __$temp1;\n\t" + " selp.s32 %1, 1, 0, __$temp1;}\n\t" + : "=r"(val), "=r"(predicate_local) : "r"(a), "r"(b)); + + *pred = (bool)predicate_local; + return val; +#else + // Host and older architecture code + int ans = max(a, b); + + *pred = (a >= b); + return ans; +#endif +} + +__DEVICE_HOST_FUNCTIONS_STATIC_DECL__ unsigned int __vibmax_u32(const unsigned int a, const unsigned int b, bool* const pred){ +#ifdef __CUDA_AND_AT_LEAST_SM_90__ + unsigned int val; + unsigned int predicate_local; + asm ("{ .reg .pred __$temp1;\n\t" + " setp.ge.u32 __$temp1, %2, %3;\n\t" + " selp.u32 %0, %2, %3, __$temp1;\n\t" + " selp.u32 %1, 1, 0, __$temp1;}\n\t" + : "=r"(val), "=r"(predicate_local) : "r"(a), "r"(b)); + + *pred = (bool)predicate_local; + return val; +#else + // Host and older architecture code + unsigned int ans = max(a, b); + + *pred = (a >= b); + return ans; +#endif +} + +// *pred gets set to '(a <= b)' +__DEVICE_HOST_FUNCTIONS_STATIC_DECL__ int __vibmin_s32(const int a, const int b, bool* const pred){ +#ifdef __CUDA_AND_AT_LEAST_SM_90__ + int val; + unsigned int predicate_local; + asm ("{ .reg .pred __$temp1;\n\t" + " setp.le.s32 __$temp1, %2, %3;\n\t" + " selp.s32 %0, %2, %3, __$temp1;\n\t" + " selp.s32 %1, 1, 0, __$temp1;}\n\t" + : "=r"(val), "=r"(predicate_local) : "r"(a), "r"(b)); + + *pred = (bool)predicate_local; + return val; +#else + // Host and older architecture code + int ans = min(a, b); + + *pred = (a <= b); + return ans; +#endif +} + +// *pred gets set to '(a <= b)' +__DEVICE_HOST_FUNCTIONS_STATIC_DECL__ unsigned int __vibmin_u32(const unsigned int a, const unsigned int b, bool* const pred){ +#ifdef __CUDA_AND_AT_LEAST_SM_90__ + unsigned int val; + unsigned int predicate_local; + asm ("{ .reg .pred __$temp1;\n\t" + " setp.le.u32 __$temp1, %2, %3;\n\t" + " selp.u32 %0, %2, %3, __$temp1;\n\t" + " selp.u32 %1, 1, 0, __$temp1;}\n\t" + : "=r"(val), "=r"(predicate_local) : "r"(a), "r"(b)); + + *pred = (bool)predicate_local; + return val; +#else + // Host and older architecture code + unsigned int ans = min(a, b); + + *pred = (a <= b); + return ans; +#endif +} + +__DEVICE_HOST_FUNCTIONS_STATIC_DECL__ unsigned int __vibmax_s16x2(const unsigned int a, const unsigned int b, bool* const pred_hi, bool* const pred_lo){ +#ifdef __CUDA_AND_AT_LEAST_SM_90__ + unsigned int val; + unsigned int predicate_local_hi; + unsigned int predicate_local_lo; + asm ("{.reg .pred pu, pv; \n\t" + ".reg .s16 rs0, rs1, rs2, rs3; \n\t" + "max.s16x2 %0, %3, %4; \n\t" + "mov.b32 {rs0, rs1}, %0; \n\t" + "mov.b32 {rs2, rs3}, %3; \n\t" + "setp.eq.s16 pv, rs0, rs2; \n\t" + "setp.eq.s16 pu, rs1, rs3; \n\t" + "selp.b32 %1, 1, 0, pu; \n\t" + "selp.b32 %2, 1, 0, pv;} \n\t" + : "=r"(val), "=r"(predicate_local_hi),"=r"(predicate_local_lo) : "r"(a), "r"(b)); + + *pred_hi = (bool)predicate_local_hi; + *pred_lo = (bool)predicate_local_lo; + return val; +#else + // Host and older architecture code + // Separate our high and low bit: + unsigned short aU_lo = (unsigned short)(a & 0xFFFFU); + unsigned short aU_hi = (unsigned short)(a >> 16); + + unsigned short bU_lo = (unsigned short)(b & 0xFFFFU); + unsigned short bU_hi = (unsigned short)(b >> 16); + + //cast to signed: + short aS_lo = __internal_cast_u2s(aU_lo); + short aS_hi = __internal_cast_u2s(aU_hi); + + short bS_lo = __internal_cast_u2s(bU_lo); + short bS_hi = __internal_cast_u2s(bU_hi); + + // Get answer + unsigned int ansU_lo = (unsigned int)max(aS_lo, bS_lo); + unsigned int ansU_hi = (unsigned int)max(aS_hi, bS_hi); + + *pred_hi = (aS_hi >= bS_hi); + *pred_lo = (aS_lo >= bS_lo); + + // Put answer back together: + unsigned int ans = (ansU_lo & 0x0000FFFFU) | (ansU_hi << 16); + + return ans; +#endif +} + +__DEVICE_HOST_FUNCTIONS_STATIC_DECL__ unsigned int __vibmax_u16x2(const unsigned int a, const unsigned int b, bool* const pred_hi, bool* const pred_lo){ +#ifdef __CUDA_AND_AT_LEAST_SM_90__ + unsigned int val; + unsigned int predicate_local_hi; + unsigned int predicate_local_lo; + asm ("{.reg .pred pu, pv; \n\t" + ".reg .u16 rs0, rs1, rs2, rs3; \n\t" + "max.u16x2 %0, %3, %4; \n\t" + "mov.b32 {rs0, rs1}, %0; \n\t" + "mov.b32 {rs2, rs3}, %3; \n\t" + "setp.eq.u16 pv, rs0, rs2; \n\t" + "setp.eq.u16 pu, rs1, rs3; \n\t" + "selp.b32 %1, 1, 0, pu; \n\t" + "selp.b32 %2, 1, 0, pv;} \n\t" + : "=r"(val), "=r"(predicate_local_hi),"=r"(predicate_local_lo) : "r"(a), "r"(b)); + + *pred_hi = (bool)predicate_local_hi; + *pred_lo = (bool)predicate_local_lo; + return val; +#else + // Host and older architecture code + // Separate our high and low bit: + unsigned short aU_lo = (unsigned short)(a & 0xFFFFU); + unsigned short aU_hi = (unsigned short)(a >> 16); + + unsigned short bU_lo = (unsigned short)(b & 0xFFFFU); + unsigned short bU_hi = (unsigned short)(b >> 16); + + // Get answer + unsigned short ansU_lo = (unsigned short)max(aU_lo, bU_lo); + unsigned short ansU_hi = (unsigned short)max(aU_hi, bU_hi); + + *pred_hi = (aU_hi >= bU_hi); + *pred_lo = (aU_lo >= bU_lo); + + // Put answer back together: + unsigned int ans = ((unsigned int) ansU_lo) | (((unsigned int) ansU_hi) << 16); + + return ans; +#endif +} + +__DEVICE_HOST_FUNCTIONS_STATIC_DECL__ unsigned int __vibmin_s16x2(const unsigned int a, const unsigned int b, bool* const pred_hi, bool* const pred_lo){ +#ifdef __CUDA_AND_AT_LEAST_SM_90__ + unsigned int val; + unsigned int predicate_local_hi; + unsigned int predicate_local_lo; + asm ("{.reg .pred pu, pv; \n\t" + ".reg .u16 rs0, rs1, rs2, rs3; \n\t" + "min.s16x2 %0, %3, %4; \n\t" + "mov.b32 {rs0, rs1}, %0; \n\t" + "mov.b32 {rs2, rs3}, %3; \n\t" + "setp.eq.s16 pv, rs0, rs2; \n\t" + "setp.eq.s16 pu, rs1, rs3; \n\t" + "selp.b32 %1, 1, 0, pu; \n\t" + "selp.b32 %2, 1, 0, pv;} \n\t" + : "=r"(val), "=r"(predicate_local_hi),"=r"(predicate_local_lo) : "r"(a), "r"(b)); + + *pred_hi = (bool)predicate_local_hi; + *pred_lo = (bool)predicate_local_lo; + return val; +#else + // Host and older architecture code + // Separate our high and low bit: + unsigned short aU_lo = (unsigned short)(a & 0xFFFFU); + unsigned short aU_hi = (unsigned short)(a >> 16); + + unsigned short bU_lo = (unsigned short)(b & 0xFFFFU); + unsigned short bU_hi = (unsigned short)(b >> 16); + + //cast to signed: + short aS_lo = __internal_cast_u2s(aU_lo); + short aS_hi = __internal_cast_u2s(aU_hi); + + short bS_lo = __internal_cast_u2s(bU_lo); + short bS_hi = __internal_cast_u2s(bU_hi); + + // Get answer + unsigned int ansU_lo = (unsigned int)min(aS_lo, bS_lo); + unsigned int ansU_hi = (unsigned int)min(aS_hi, bS_hi); + + *pred_hi = (aS_hi <= bS_hi); + *pred_lo = (aS_lo <= bS_lo); + + // Put answer back together: + unsigned int ans = (ansU_lo & 0x0000FFFFU) | (ansU_hi << 16); + + return ans; +#endif +} + +__DEVICE_HOST_FUNCTIONS_STATIC_DECL__ unsigned int __vibmin_u16x2(const unsigned int a, const unsigned int b, bool* const pred_hi, bool* const pred_lo){ +#ifdef __CUDA_AND_AT_LEAST_SM_90__ + unsigned int val; + unsigned int predicate_local_hi; + unsigned int predicate_local_lo; + asm ("{.reg .pred pu, pv; \n\t" + ".reg .u16 rs0, rs1, rs2, rs3; \n\t" + "min.u16x2 %0, %3, %4; \n\t" + "mov.b32 {rs0, rs1}, %0; \n\t" + "mov.b32 {rs2, rs3}, %3; \n\t" + "setp.eq.u16 pv, rs0, rs2; \n\t" + "setp.eq.u16 pu, rs1, rs3; \n\t" + "selp.b32 %1, 1, 0, pu; \n\t" + "selp.b32 %2, 1, 0, pv;} \n\t" + : "=r"(val), "=r"(predicate_local_hi),"=r"(predicate_local_lo) : "r"(a), "r"(b)); + + *pred_hi = (bool)predicate_local_hi; + *pred_lo = (bool)predicate_local_lo; + return val; +#else + // Host and older architecture code + // Separate our high and low bit: + unsigned short aU_lo = (unsigned short)(a & 0xFFFFU); + unsigned short aU_hi = (unsigned short)(a >> 16); + + unsigned short bU_lo = (unsigned short)(b & 0xFFFFU); + unsigned short bU_hi = (unsigned short)(b >> 16); + + // Get answer + unsigned short ansU_lo = (unsigned short)min(aU_lo, bU_lo); + unsigned short ansU_hi = (unsigned short)min(aU_hi, bU_hi); + + *pred_hi = (aU_hi <= bU_hi); + *pred_lo = (aU_lo <= bU_lo); + + // Put answer back together: + unsigned int ans = ((unsigned int) ansU_lo) | (((unsigned int) ansU_hi) << 16); + + return ans; +#endif +} + +#ifdef __CUDA_AND_AT_LEAST_SM_90__ +#undef __CUDA_AND_AT_LEAST_SM_90__ +#endif + +#undef __DEVICE_HOST_FUNCTIONS_STATIC_DECL__ + +/******************************************************************************* +* * +* * +* * +*******************************************************************************/ + +#endif /* !__DEVICE_FUNCTIONS_HPP__ */ + +#if defined(__UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_DEVICE_FUNCTIONS_HPP__) +#undef __CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__ +#undef __UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_DEVICE_FUNCTIONS_HPP__ +#endif diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/func_macro.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/func_macro.h new file mode 100644 index 0000000000000000000000000000000000000000..633554a01aaabd1bca5ae278c276710f323d5d7b --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/func_macro.h @@ -0,0 +1,57 @@ +/* + * NVIDIA_COPYRIGHT_BEGIN + * + * Copyright (c) 2008-2018, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + * + * NVIDIA_COPYRIGHT_END + */ + +#if !defined(__CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__) +#if defined(_MSC_VER) +#pragma message("crt/func_macro.h is an internal header file and must not be used directly. Please use cuda_runtime_api.h or cuda_runtime.h instead.") +#else +#warning "crt/func_macro.h is an internal header file and must not be used directly. Please use cuda_runtime_api.h or cuda_runtime.h instead." +#endif +#define __CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__ +#define __UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_FUNC_MACRO_H__ +#endif + +#if !defined(__FUNC_MACRO_H__) +#define __FUNC_MACRO_H__ + +#if !defined(__CUDA_INTERNAL_COMPILATION__) + +#error -- incorrect inclusion of a cudart header file + +#endif /* !__CUDA_INTERNAL_COMPILATION__ */ + +#if defined(__GNUC__) + +#define __func__(decl) \ + inline decl + +#define __device_func__(decl) \ + static __attribute__((__unused__)) decl + +#elif defined(_WIN32) + +#define __func__(decl) \ + static inline decl + +#define __device_func__(decl) \ + static decl + +#endif /* __GNUC__ */ + +#endif /* __FUNC_MACRO_H__ */ + +#if defined(__UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_FUNC_MACRO_H__) +#undef __CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__ +#undef __UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_FUNC_MACRO_H__ +#endif diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/host_config.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/host_config.h new file mode 100644 index 0000000000000000000000000000000000000000..820b81c2945d8dcc241329673a558090a4922e52 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/host_config.h @@ -0,0 +1,310 @@ +/* + * Copyright 1993-2024 NVIDIA Corporation. All rights reserved. + * + * NOTICE TO LICENSEE: + * + * This source code and/or documentation ("Licensed Deliverables") are + * subject to NVIDIA intellectual property rights under U.S. and + * international Copyright laws. + * + * These Licensed Deliverables contained herein is PROPRIETARY and + * CONFIDENTIAL to NVIDIA and is being provided under the terms and + * conditions of a form of NVIDIA software license agreement by and + * between NVIDIA and Licensee ("License Agreement") or electronically + * accepted by Licensee. Notwithstanding any terms or conditions to + * the contrary in the License Agreement, reproduction or disclosure + * of the Licensed Deliverables to any third party without the express + * written consent of NVIDIA is prohibited. + * + * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE + * LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE + * SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE. IT IS + * PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND. + * NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED + * DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY, + * NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE. + * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE + * LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY + * SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY + * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS + * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THESE LICENSED DELIVERABLES. + * + * U.S. Government End Users. These Licensed Deliverables are a + * "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT + * 1995), consisting of "commercial computer software" and "commercial + * computer software documentation" as such terms are used in 48 + * C.F.R. 12.212 (SEPT 1995) and is provided to the U.S. Government + * only as a commercial end item. Consistent with 48 C.F.R.12.212 and + * 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all + * U.S. Government End Users acquire the Licensed Deliverables with + * only those rights set forth herein. + * + * Any use of the Licensed Deliverables in individual and commercial + * software must include, in the user documentation and internal + * comments to the code, the above Disclaimer and U.S. Government End + * Users Notice. + */ + +#if !defined(__CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__) +#if defined(_MSC_VER) +#pragma message("crt/host_config.h is an internal header file and must not be used directly. Please use cuda_runtime_api.h or cuda_runtime.h instead.") +#else +#warning "crt/host_config.h is an internal header file and must not be used directly. Please use cuda_runtime_api.h or cuda_runtime.h instead." +#endif +#define __CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__ +#define __UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_HOST_CONFIG_H__ +#endif + +#if !defined(__HOST_CONFIG_H__) +#define __HOST_CONFIG_H__ + +/******************************************************************************* +* * +* * +* * +*******************************************************************************/ + +#if defined(__CUDACC__) + +#if defined(__CUDACC_RTC__) + +#define _CRTIMP +#define __THROW + +#else /* __CUDACC_RTC__ */ + +/* check for host compilers that are compatible with nvcc */ +#if !defined(__GNUC__) && !defined(_WIN32) + +#error --- !!! UNSUPPORTED COMPILER !!! --- + +#endif /* !__GNUC__ && !_WIN32 */ + +/* check invalid configurations */ +#if defined(__PGIC__) +#if !defined(__GNUC__) || !defined(__LP64__) || !defined(__linux__) +#error -- unsupported pgc++ configuration! pgc++ is supported only on Linux x86_64! +#endif /* !defined(__GNUC__) || !defined(__LP64__) || !defined(__linux__) */ +#endif /* defined(__PGIC__) */ + +#if defined(__powerpc__) +#if !defined(__powerpc64__) || !defined(__LITTLE_ENDIAN__) +#error -- unsupported PPC platform! Only 64-bit little endian PPC is supported! +#endif /* !__powerpc64__ || !__LITTLE_ENDIAN__ */ +#endif /* __powerpc__ */ + +#if defined(__APPLE__) && defined(__MACH__) && !defined(__clang__) +#error -- clang and clang++ are the only supported host compilers on Mac OS X! +#endif /* __APPLE__ && __MACH__ && !__clang__ */ + + +/* check host compiler version */ +#if !__NV_NO_HOST_COMPILER_CHECK + +#if defined(__ICC) + +#if (__ICC != 1500 && __ICC != 1600 && __ICC != 1700 && __ICC != 1800 && !(__ICC >= 1900 && __ICC <= 2021)) || !defined(__GNUC__) || !defined(__LP64__) + +#error -- unsupported ICC configuration! Only ICC 15.0, ICC 16.0, ICC 17.0, ICC 18.0, ICC 19.x and 20.x on Linux x86_64 are supported! The nvcc flag '-allow-unsupported-compiler' can be used to override this version check; however, using an unsupported host compiler may cause compilation failure or incorrect run time execution. Use at your own risk. + +#endif /* (__ICC != 1500 && __ICC != 1600 && __ICC != 1700 && __ICC != 1800 && __ICC != 1900) || !__GNUC__ || !__LP64__ */ + +#endif /* __ICC */ + +#if defined(__GRCO_CLANG_COMPILER__) +#if (__GRCO_CLANG_COMPILER__ == 1) && ((__clang_major__ < 16) || (__clang_major__ > 19)) +#error -- unsupported Grace clang version! The version must be 16.x to 19.x. The nvcc flag '-allow-unsupported-compiler' can be used to override this version check; however, using an unsupported host compiler may cause compilation failure or incorrect run time execution. Use at your own risk. +#endif /* (__GRCO_CLANG_COMPILER__ == 1) && ((__clang_major__ < 16) || (__clang_major__ > 19)) */ + +#endif /* __GRCO_CLANG_COMPILER__ */ + +#if defined(__INTEL_CLANG_COMPILER) +#error -- unsupported Intel ICX compiler! The nvcc flag '-allow-unsupported-compiler' can be used to override this version check; however, using an unsupported host compiler may cause compilation failure or incorrect run time execution. Use at your own risk. +#endif /* __INTEL_CLANG_COMPILER */ + +#if defined(__powerpc__) + +#if defined(__ibmxl_vrm__) && !(__ibmxl_vrm__ >= 0x0d010000 && __ibmxl_vrm__ < 0x0d020000) && \ + !(__ibmxl_vrm__ >= 0x10010000 && __ibmxl_vrm__ < 0x10020000) + +#error -- unsupported xlC version! only xlC 13.1 and 16.1 are supported. The nvcc flag '-allow-unsupported-compiler' can be used to override this version check; however, using an unsupported host compiler may cause compilation failure or incorrect run time execution. Use at your own risk. + +#endif /* __ibmxl_vrm__ && !(__ibmxl_vrm__ >= 0x0d010000 && __ibmxl_vrm__ < 0x0d020000) && + !(__ibmxl_vrm__ >= 0x10010000 && __ibmxl_vrm__ < 0x10020000) */ + +#endif /* __powerpc__ */ + +#if defined(__GNUC__) + +#if __GNUC__ > 14 + +#error -- unsupported GNU version! gcc versions later than 14 are not supported! The nvcc flag '-allow-unsupported-compiler' can be used to override this version check; however, using an unsupported host compiler may cause compilation failure or incorrect run time execution. Use at your own risk. + +#endif /* __GNUC__ > 14 */ + + +#if defined(__HORIZON__) +#if (__clang_major__ >= 20) || (__clang_major__ < 3) || ((__clang_major__ == 3) && (__clang_minor__ < 3)) +#error -- unsupported HOS clang version! The version must be must be less than 20 and greater than 3.2 . The nvcc flag '-allow-unsupported-compiler' can be used to override this version check; however, using an unsupported host compiler may cause compilation failure or incorrect run time execution. Use at your own risk. +#endif /* (__clang_major__ >= 20) || (__clang_major__ < 3) || ((__clang_major__ == 3) && (__clang_minor__ < 3)) */ +#endif /* __HORIZON__ */ + +#if defined(__clang__) && !defined(__ibmxl_vrm__) && !defined(__ICC) && !defined(__HORIZON__) && !defined(__APPLE__) && !defined(__GRCO_CLANG_COMPILER__) + +#if (__clang_major__ >= 20) || (__clang_major__ < 3) || ((__clang_major__ == 3) && (__clang_minor__ < 3)) +#error -- unsupported clang version! clang version must be less than 20 and greater than 3.2 . The nvcc flag '-allow-unsupported-compiler' can be used to override this version check; however, using an unsupported host compiler may cause compilation failure or incorrect run time execution. Use at your own risk. + +#endif /* (__clang_major__ >= 20) || (__clang_major__ < 3) || ((__clang_major__ == 3) && (__clang_minor__ < 3)) */ + +#endif /* defined(__clang__) && !defined(__ibmxl_vrm__) && !defined(__ICC) && !defined(__HORIZON__) && !defined(__APPLE__) && !defined(__GRCO_CLANG_COMPILER__) */ + + +#endif /* __GNUC__ */ + +#if defined(_WIN32) + +#if _MSC_VER < 1910 || _MSC_VER >= 1950 + +#error -- unsupported Microsoft Visual Studio version! Only the versions between 2017 and 2022 (inclusive) are supported! The nvcc flag '-allow-unsupported-compiler' can be used to override this version check; however, using an unsupported host compiler may cause compilation failure or incorrect run time execution. Use at your own risk. + +#elif _MSC_VER >= 1910 && _MSC_VER < 1910 + +#pragma message("support for this version of Microsoft Visual Studio has been deprecated! Only the versions between 2017 and 2022 (inclusive) are supported!") + +#endif /* (_MSC_VER < 1910 || _MSC_VER >= 1950) || (_MSC_VER >= 1910 && _MSC_VER < 1910) */ + +#endif /* _WIN32 */ +#endif /* !__NV_NO_HOST_COMPILER_CHECK */ + + +/* configure host compiler */ +#if defined(__APPLE__) + +#define _CRTIMP +#define _ACRTIMP +#define __THROW + +#if defined(__BLOCKS__) /* nvcc does not support closures */ + +#undef __BLOCKS__ + +#endif /* __BLOCKS__ */ + +#elif defined(__ANDROID__) + +#define _CRTIMP +#define _ACRTIMP +#define __THROW + +#elif defined(__QNX__) + +#define _CRTIMP +#define _ACRTIMP +#define __THROW + +#elif defined(__HORIZON__) + +#define _CRTIMP +#define _ACRTIMP +#define __THROW + +#elif defined(__GNUC__) + +#define _CRTIMP +#define _ACRTIMP + +#include /* for __THROW */ + +#elif defined(_WIN32) + +#if _MSC_VER >= 1500 + +#undef _USE_DECLSPECS_FOR_SAL +#define _USE_DECLSPECS_FOR_SAL \ + 1 + +#endif /* _MSC_VER >= 1500 */ + +#if !defined(_CRT_NONSTDC_NO_WARNINGS) + +#define _CRT_NONSTDC_NO_WARNINGS /* to suppress warnings */ + +#endif /* !_CRT_NONSTDC_NO_WARNINGS */ + +#if !defined(_CRT_SECURE_NO_WARNINGS) + +#define _CRT_SECURE_NO_WARNINGS /* to suppress warnings */ + +#endif /* !_CRT_SECURE_NO_WARNINGS */ + +#if !defined(NOMINMAX) + +#define NOMINMAX /* min and max are part of cuda runtime */ + +#endif /* !NOMINMAX */ + +#include /* for _CRTIMP */ +#if _MSC_VER >= 1900 +#include /* for _ACRTIMP */ +#endif /* _MSC_VER >= 1900 */ + +#define __THROW + +#endif /* __APPLE__ */ + +#endif /* __CUDACC_RTC__ */ + + +#if defined(__cplusplus) && defined(__CUDA_ARCH__) && (defined(__PGIC__) || defined(__CUDACC_RTC__) || (defined(_WIN32) && defined(_MSC_VER))) + +#if __CUDACC_RTC__ +typedef char *va_list; +#else /* !__CUDACC_RTC__ */ +#include +#endif /* __CUDACC_RTC__ */ + + +#undef va_start +#undef va_end +#undef va_arg + +#ifdef __PGIC__ + +#undef __builtin_va_end + +#define va_start(v,l) __builtin_alt_va_start(v,l) +#define va_end(v) __builtin_va_end(v) +#define va_arg(v,l) __builtin_alt_va_arg(v,l) + +#if (__cplusplus >= 201103L) +#undef va_copy +#define va_copy(d,s) __builtin_va_copy(d,s) +#endif + +#else /* !__PGIC__ */ + + +#define va_start(ap, x) (__cu_va_start(&ap, x)) +#define va_end(ap) (__cu_va_end(&ap)) +#define va_arg(ap, t) (*((t *)__cu_va_arg(&ap, (t *)0))) + +#if (_MSC_VER >= 1800) || (defined(__CUDACC_RTC__) && (__cplusplus >= 201103L)) +#undef va_copy +#define va_copy(apd, aps) (__cu_va_copy(&(apd), &(aps))) +#endif /* (_MSC_VER >= 1800) || (defined(__CUDACC_RTC__) && (__cplusplus >= 201103L)) */ +#endif /* __PGIC__ */ + +#endif /* defined(__cplusplus) && (defined(__CUDACC_RTC__) || (defined(_WIN32) && defined(_MSC_VER))) */ + + + +#endif /* __CUDACC__ */ + +#endif /* !__HOST_CONFIG_H__ */ + +#if defined(__UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_HOST_CONFIG_H__) +#undef __CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__ +#undef __UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_HOST_CONFIG_H__ +#endif diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/host_defines.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/host_defines.h new file mode 100644 index 0000000000000000000000000000000000000000..b58cb3cc1086bdc6e0376f042c86b2755ef2ff00 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/host_defines.h @@ -0,0 +1,283 @@ +/* + * Copyright 1993-2023 NVIDIA Corporation. All rights reserved. + * + * NOTICE TO LICENSEE: + * + * This source code and/or documentation ("Licensed Deliverables") are + * subject to NVIDIA intellectual property rights under U.S. and + * international Copyright laws. + * + * These Licensed Deliverables contained herein is PROPRIETARY and + * CONFIDENTIAL to NVIDIA and is being provided under the terms and + * conditions of a form of NVIDIA software license agreement by and + * between NVIDIA and Licensee ("License Agreement") or electronically + * accepted by Licensee. Notwithstanding any terms or conditions to + * the contrary in the License Agreement, reproduction or disclosure + * of the Licensed Deliverables to any third party without the express + * written consent of NVIDIA is prohibited. + * + * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE + * LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE + * SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE. IT IS + * PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND. + * NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED + * DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY, + * NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE. + * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE + * LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY + * SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY + * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS + * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THESE LICENSED DELIVERABLES. + * + * U.S. Government End Users. These Licensed Deliverables are a + * "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT + * 1995), consisting of "commercial computer software" and "commercial + * computer software documentation" as such terms are used in 48 + * C.F.R. 12.212 (SEPT 1995) and is provided to the U.S. Government + * only as a commercial end item. Consistent with 48 C.F.R.12.212 and + * 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all + * U.S. Government End Users acquire the Licensed Deliverables with + * only those rights set forth herein. + * + * Any use of the Licensed Deliverables in individual and commercial + * software must include, in the user documentation and internal + * comments to the code, the above Disclaimer and U.S. Government End + * Users Notice. + */ + +#if !defined(__CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__) +#if defined(_MSC_VER) +#pragma message("crt/host_defines.h is an internal header file and must not be used directly. Please use cuda_runtime_api.h or cuda_runtime.h instead.") +#else +#warning "crt/host_defines.h is an internal header file and must not be used directly. Please use cuda_runtime_api.h or cuda_runtime.h instead." +#endif +#define __CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__ +#define __UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_HOST_DEFINES_H__ +#endif + +#if !defined(__HOST_DEFINES_H__) +#define __HOST_DEFINES_H__ + +#if defined(__CUDACC__) && !defined(__CUDACC_RTC__) && !defined(__CUDADEVRT_INTERNAL__) && !defined(_ALLOW_UNSUPPORTED_LIBCPP) +#include +#if ((defined(_MSC_VER ) && (defined(_M_X64) || defined(_M_AMD64))) ||\ + (defined(__x86_64__) || defined(__amd64__))) && defined(_LIBCPP_VERSION) && !(defined(__HORIZON__) || defined(__ANDROID__) || defined(__QNX__)) +#error "libc++ is not supported on x86 system" +#endif +#endif + +/* CUDA JIT mode (__CUDACC_RTC__) also uses GNU style attributes */ +#if defined(__GNUC__) || (defined(__PGIC__) && defined(__linux__)) || defined(__CUDA_LIBDEVICE__) || defined(__CUDACC_RTC__) + +#if defined(__CUDACC_RTC__) +#define __volatile__ volatile +#endif /* __CUDACC_RTC__ */ + +#define __no_return__ \ + __attribute__((noreturn)) + +#if defined(__CUDACC__) || defined(__CUDA_ARCH__) || defined(__CUDA_LIBDEVICE__) +/* gcc allows users to define attributes with underscores, + e.g., __attribute__((__noinline__)). + Consider a non-CUDA source file (e.g. .cpp) that has the + above attribute specification, and includes this header file. In that case, + defining __noinline__ as below would cause a gcc compilation error. + Hence, only define __noinline__ when the code is being processed + by a CUDA compiler component. +*/ +#define __noinline__ \ + __attribute__((noinline)) +#endif /* __CUDACC__ || __CUDA_ARCH__ || __CUDA_LIBDEVICE__ */ + +#undef __forceinline__ +#define __forceinline__ \ + __inline__ __attribute__((always_inline)) +#define __inline_hint__ \ + __attribute__((nv_inline_hint)) +#define __align__(n) \ + __attribute__((aligned(n))) +#define __maxnreg__(a) \ + __attribute__((maxnreg(a))) +#define __thread__ \ + __thread +#define __import__ +#define __export__ +#define __cdecl +#define __annotate__(a) \ + __attribute__((a)) +#define __location__(a) \ + __annotate__(a) +#define CUDARTAPI +#define CUDARTAPI_CDECL + +#elif defined(_MSC_VER) + +#if _MSC_VER >= 1400 + +#define __restrict__ \ + __restrict + +#else /* _MSC_VER >= 1400 */ + +#define __restrict__ + +#endif /* _MSC_VER >= 1400 */ + +#define __inline__ \ + __inline +#define __no_return__ \ + __declspec(noreturn) +#define __noinline__ \ + __declspec(noinline) +#define __forceinline__ \ + __forceinline +#define __inline_hint__ \ + __declspec(nv_inline_hint) +#define __align__(n) \ + __declspec(align(n)) +#define __maxnreg__(n) \ + __declspec(maxnreg(n)) +#define __thread__ \ + __declspec(thread) +#define __import__ \ + __declspec(dllimport) +#define __export__ \ + __declspec(dllexport) +#define __annotate__(a) \ + __declspec(a) +#define __location__(a) \ + __annotate__(__##a##__) +#define CUDARTAPI \ + __stdcall +#define CUDARTAPI_CDECL \ + __cdecl + +#else /* __GNUC__ || __CUDA_LIBDEVICE__ || __CUDACC_RTC__ */ + +#define __inline__ + +#if !defined(__align__) + +#error --- !!! UNKNOWN COMPILER: please provide a CUDA compatible definition for '__align__' !!! --- + +#endif /* !__align__ */ + +#if !defined(CUDARTAPI) + +#error --- !!! UNKNOWN COMPILER: please provide a CUDA compatible definition for 'CUDARTAPI' !!! --- + +#endif /* !CUDARTAPI */ + +#endif /* __GNUC__ || __CUDA_LIBDEVICE__ || __CUDACC_RTC__ */ + +#if (defined(__GNUC__) && (__GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 3 && !defined(__clang__)))) || \ + (defined(_MSC_VER) && _MSC_VER < 1900) || \ + (!defined(__GNUC__) && !defined(_MSC_VER)) + +#define __specialization_static \ + static + +#else /* (__GNUC__ && (__GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 3 && !__clang__))) || + (_MSC_VER && _MSC_VER < 1900) || + (!__GNUC__ && !_MSC_VER) */ + +#define __specialization_static + +#endif /* (__GNUC__ && (__GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 3 && !__clang__))) || + (_MSC_VER && _MSC_VER < 1900) || + (!__GNUC__ && !_MSC_VER) */ + +#if !defined(__CUDACC__) && !defined(__CUDA_LIBDEVICE__) + +#undef __annotate__ +#define __annotate__(a) + +#else /* !__CUDACC__ && !__CUDA_LIBDEVICE__ */ + +#define __launch_bounds__(...) \ + __annotate__(launch_bounds(__VA_ARGS__)) + +#endif /* !__CUDACC__ && !__CUDA_LIBDEVICE__ */ + +#if defined(__CUDACC__) || defined(__CUDA_LIBDEVICE__) || \ + defined(__GNUC__) || defined(_WIN64) + +#define __builtin_align__(a) \ + __align__(a) + +#else /* __CUDACC__ || __CUDA_LIBDEVICE__ || __GNUC__ || _WIN64 */ + +#define __builtin_align__(a) + +#endif /* __CUDACC__ || __CUDA_LIBDEVICE__ || __GNUC__ || _WIN64 */ + +#if defined(__CUDACC__) || !defined(__grid_constant__) +#define __grid_constant__ \ + __location__(grid_constant) +#endif /* defined(__CUDACC__) || !defined(__grid_constant__) */ + +#if defined(__CUDACC__) || !defined(__host__) +#define __host__ \ + __location__(host) +#endif /* defined(__CUDACC__) || !defined(__host__) */ +#if defined(__CUDACC__) || !defined(__device__) +#define __device__ \ + __location__(device) +#endif /* defined(__CUDACC__) || !defined(__device__) */ +#if defined(__CUDACC__) || !defined(__global__) +#define __global__ \ + __location__(global) +#endif /* defined(__CUDACC__) || !defined(__global__) */ +#if defined(__CUDACC__) || !defined(__shared__) +#define __shared__ \ + __location__(shared) +#endif /* defined(__CUDACC__) || !defined(__shared__) */ +#if defined(__CUDACC__) || !defined(__constant__) +#define __constant__ \ + __location__(constant) +#endif /* defined(__CUDACC__) || !defined(__constant__) */ +#if defined(__CUDACC__) || !defined(__managed__) +#define __managed__ \ + __location__(managed) +#endif /* defined(__CUDACC__) || !defined(__managed__) */ +#if defined(__CUDACC__) || !defined(__nv_pure__) +#define __nv_pure__ \ + __location__(nv_pure) +#endif /* defined(__CUDACC__) || !defined(__nv_pure__) */ +#if !defined(__CUDACC__) +#define __device_builtin__ +#define __device_builtin_texture_type__ +#define __device_builtin_surface_type__ +#define __cudart_builtin__ +#else /* defined(__CUDACC__) */ +#define __device_builtin__ \ + __location__(device_builtin) +#define __device_builtin_texture_type__ \ + __location__(device_builtin_texture_type) +#define __device_builtin_surface_type__ \ + __location__(device_builtin_surface_type) +#define __cudart_builtin__ \ + __location__(cudart_builtin) +#endif /* !defined(__CUDACC__) */ + +#if defined(__CUDACC__) || !defined(__cluster_dims__) +#if defined(_MSC_VER) +#define __cluster_dims__(...) \ + __declspec(__cluster_dims__(__VA_ARGS__)) + +#else /* !defined(_MSC_VER) */ +#define __cluster_dims__(...) \ + __attribute__((cluster_dims(__VA_ARGS__))) +#endif /* defined(_MSC_VER) */ +#endif /* defined(__CUDACC__) || !defined(__cluster_dims__) */ + +#define __CUDA_ARCH_HAS_FEATURE__(_FEAT) __CUDA_ARCH_FEAT_##_FEAT + +#endif /* !__HOST_DEFINES_H__ */ + +#if defined(__UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_HOST_DEFINES_H__) +#undef __CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__ +#undef __UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_HOST_DEFINES_H__ +#endif diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/host_runtime.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/host_runtime.h new file mode 100644 index 0000000000000000000000000000000000000000..22e3a1bea875ddb2a15075f6e0ecb10b7ce1a6a7 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/host_runtime.h @@ -0,0 +1,306 @@ +/* + * NVIDIA_COPYRIGHT_BEGIN + * + * Copyright (c) 2008-2023, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + * + * NVIDIA_COPYRIGHT_END + */ + +#if !defined(__CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__) +#if defined(_MSC_VER) +#pragma message("crt/device_functions.h is an internal header file and must not be used directly. Please use cuda_runtime_api.h or cuda_runtime.h instead.") +#else +#warning "crt/device_functions.h is an internal header file and must not be used directly. Please use cuda_runtime_api.h or cuda_runtime.h instead." +#endif +#define __CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__ +#define __UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_HOST_RUNTIME_H__ +#endif + +#if !defined(__CUDA_INTERNAL_COMPILATION__) + +#define __CUDA_INTERNAL_COMPILATION__ +#define __text__ +#define __surf__ +#define __name__shadow_var(c, cpp) \ + #c +#define __name__text_var(c, cpp) \ + #cpp +#define __host__shadow_var(c, cpp) \ + cpp +#define __text_var(c, cpp) \ + cpp +#define __device_fun(fun) \ + #fun +#define __device_var(var) \ + #var +#define __device__text_var(c, cpp) \ + #c +#define __device__shadow_var(c, cpp) \ + #c + +#if defined(_WIN32) && !defined(_WIN64) + +#define __pad__(f) \ + f + +#else /* _WIN32 && !_WIN64 */ + +#define __pad__(f) + +#endif /* _WIN32 && !_WIN64 */ + +#include "builtin_types.h" +#include "storage_class.h" + +#else /* !__CUDA_INTERNAL_COMPILATION__ */ + +template +static inline T *__cudaAddressOf(T &val) +{ + return (T *)((void *)(&(const_cast(reinterpret_cast(val))))); +} + +#define __cudaRegisterBinary(X) \ + __cudaFatCubinHandle = __cudaRegisterFatBinary((void*)&__fatDeviceText); \ + { void (*callback_fp)(void **) = (void (*)(void **))(X); (*callback_fp)(__cudaFatCubinHandle); __cudaRegisterFatBinaryEnd(__cudaFatCubinHandle); }\ + atexit(__cudaUnregisterBinaryUtil) + +#define __cudaRegisterVariable(handle, var, ext, size, constant, global) \ + __cudaRegisterVar(handle, (char*)&__host##var, (char*)__device##var, __name##var, ext, size, constant, global) +#define __cudaRegisterManagedVariable(handle, var, ext, size, constant, global) \ + __cudaRegisterManagedVar(handle, (void **)&__host##var, (char*)__device##var, __name##var, ext, size, constant, global) + +#define __cudaRegisterGlobalTexture(handle, tex, dim, norm, ext) \ + __cudaRegisterTexture(handle, (const struct textureReference*)&tex, (const void**)(void*)__device##tex, __name##tex, dim, norm, ext) +#define __cudaRegisterGlobalSurface(handle, surf, dim, ext) \ + __cudaRegisterSurface(handle, (const struct surfaceReference*)&surf, (const void**)(void*)__device##surf, __name##surf, dim, ext) +#define __cudaRegisterEntry(handle, funptr, fun, thread_limit) \ + __cudaRegisterFunction(handle, (const char*)funptr, (char*)__device_fun(fun), #fun, -1, (uint3*)0, (uint3*)0, (dim3*)0, (dim3*)0, (int*)0) + +extern "C" cudaError_t CUDARTAPI __cudaPopCallConfiguration( + dim3 *gridDim, + dim3 *blockDim, + size_t *sharedMem, + void *stream +); + +#define __cudaLaunchPrologue(size) \ + void * __args_arr[size]; \ + int __args_idx = 0 + +#define __cudaSetupArg(arg, offset) \ + __args_arr[__args_idx] = (void *)__cudaAddressOf(arg); ++__args_idx + +#define __cudaSetupArgSimple(arg, offset) \ + __args_arr[__args_idx] = (void *)(char *)&arg; ++__args_idx + +#if defined(__GNUC__) +#define __NV_ATTR_UNUSED_FOR_LAUNCH __attribute__((unused)) +#else /* !__GNUC__ */ +#define __NV_ATTR_UNUSED_FOR_LAUNCH +#endif /* __GNUC__ */ + +#ifdef __NV_LEGACY_LAUNCH +/* the use of __args_idx in the expression below avoids host compiler warning about it being an + unused variable when the launch has no arguments */ +#define __cudaLaunch(fun) \ + { volatile static char *__f __NV_ATTR_UNUSED_FOR_LAUNCH; __f = fun; \ + dim3 __gridDim, __blockDim;\ + size_t __sharedMem; \ + cudaStream_t __stream; \ + if (__cudaPopCallConfiguration(&__gridDim, &__blockDim, &__sharedMem, &__stream) != cudaSuccess) \ + return; \ + if (__args_idx == 0) {\ + (void)cudaLaunchKernel(fun, __gridDim, __blockDim, &__args_arr[__args_idx], __sharedMem, __stream);\ + } else { \ + (void)cudaLaunchKernel(fun, __gridDim, __blockDim, &__args_arr[0], __sharedMem, __stream);\ + }\ + } +#else /* !__NV_LEGACY_LAUNCH */ +#define __cudaLaunch(fun) \ + { volatile static char *__f __NV_ATTR_UNUSED_FOR_LAUNCH; __f = fun; \ + static cudaKernel_t __handle = 0; \ + volatile static bool __tmp __NV_ATTR_UNUSED_FOR_LAUNCH = (__cudaGetKernel(&__handle, (const void *)fun) == cudaSuccess); \ + dim3 __gridDim, __blockDim;\ + size_t __sharedMem; \ + cudaStream_t __stream; \ + if (__cudaPopCallConfiguration(&__gridDim, &__blockDim, &__sharedMem, &__stream) != cudaSuccess) \ + return; \ + if (__args_idx == 0) {\ + (void)__cudaLaunchKernel_helper(__handle, __gridDim, __blockDim, &__args_arr[__args_idx], __sharedMem, __stream);\ + } else { \ + (void)__cudaLaunchKernel_helper(__handle, __gridDim, __blockDim, &__args_arr[0], __sharedMem, __stream);\ + }\ + } +#endif /* __NV_LEGACY_LAUNCH */ + +#if defined(__GNUC__) +#define __nv_dummy_param_ref(param) \ + { volatile static void **__ref __attribute__((unused)); __ref = (volatile void **)param; } +#else /* __GNUC__ */ +#define __nv_dummy_param_ref(param) \ + { volatile static void **__ref; __ref = (volatile void **)param; } +#endif /* __GNUC__ */ + +static void ____nv_dummy_param_ref(void *param) __nv_dummy_param_ref(param) + +#define __REGISTERFUNCNAME_CORE(X) __cudaRegisterLinkedBinary##X +#define __REGISTERFUNCNAME(X) __REGISTERFUNCNAME_CORE(X) + +extern "C" { +void __REGISTERFUNCNAME( __NV_MODULE_ID ) ( void (*)(void **), void *, void *, void (*)(void *)); +} + +#define __TO_STRING_CORE(X) #X +#define __TO_STRING(X) __TO_STRING_CORE(X) + +extern "C" { +#if defined(_WIN32) +#pragma data_seg("__nv_module_id") + static const __declspec(allocate("__nv_module_id")) unsigned char __module_id_str[] = __TO_STRING(__NV_MODULE_ID); +#pragma data_seg() +#elif defined(__APPLE__) + static const unsigned char __module_id_str[] __attribute__((section ("__NV_CUDA,__nv_module_id"))) = __TO_STRING(__NV_MODULE_ID); +#else + static const unsigned char __module_id_str[] __attribute__((section ("__nv_module_id"))) = __TO_STRING(__NV_MODULE_ID); +#endif + +#undef __FATIDNAME_CORE +#undef __FATIDNAME +#define __FATIDNAME_CORE(X) __fatbinwrap##X +#define __FATIDNAME(X) __FATIDNAME_CORE(X) + +#define ____cudaRegisterLinkedBinary(X) \ +{ __REGISTERFUNCNAME(__NV_MODULE_ID) (( void (*)(void **))(X), (void *)&__FATIDNAME(__NV_MODULE_ID), (void *)&__module_id_str, (void (*)(void *))&____nv_dummy_param_ref); } + +} + +extern "C" { +extern void** CUDARTAPI __cudaRegisterFatBinary( + void *fatCubin +); + +extern void CUDARTAPI __cudaRegisterFatBinaryEnd( + void **fatCubinHandle +); + +extern void CUDARTAPI __cudaUnregisterFatBinary( + void **fatCubinHandle +); + +extern void CUDARTAPI __cudaRegisterVar( + void **fatCubinHandle, + char *hostVar, + char *deviceAddress, + const char *deviceName, + int ext, + size_t size, + int constant, + int global +); + +extern void CUDARTAPI __cudaRegisterManagedVar( + void **fatCubinHandle, + void **hostVarPtrAddress, + char *deviceAddress, + const char *deviceName, + int ext, + size_t size, + int constant, + int global +); + +extern char CUDARTAPI __cudaInitModule( + void **fatCubinHandle +); + +extern void CUDARTAPI __cudaRegisterTexture( + void **fatCubinHandle, + const struct textureReference *hostVar, + const void **deviceAddress, + const char *deviceName, + int dim, + int norm, + int ext +); + +extern void CUDARTAPI __cudaRegisterSurface( + void **fatCubinHandle, + const struct surfaceReference *hostVar, + const void **deviceAddress, + const char *deviceName, + int dim, + int ext +); + +extern void CUDARTAPI __cudaRegisterFunction( + void **fatCubinHandle, + const char *hostFun, + char *deviceFun, + const char *deviceName, + int thread_limit, + uint3 *tid, + uint3 *bid, + dim3 *bDim, + dim3 *gDim, + int *wSize +); + +#if defined(__APPLE__) +extern "C" int atexit(void (*)(void)); + +#elif defined(__GNUC__) && !defined(__ANDROID__) && !defined(__HORIZON__) +extern int atexit(void(*)(void)) throw(); + +#elif defined(__HORIZON__) + +// __TEMP_WAR__ 200132570 HOS : Disable atexit call until it works +#define atexit(p) + +#else /* __GNUC__ && !__ANDROID__ */ +extern int __cdecl atexit(void(__cdecl *)(void)); +#endif + +} + +static void **__cudaFatCubinHandle; + +static void __cdecl __cudaUnregisterBinaryUtil(void) +{ + ____nv_dummy_param_ref((void *)&__cudaFatCubinHandle); + __cudaUnregisterFatBinary(__cudaFatCubinHandle); +} + +static char __nv_init_managed_rt_with_module(void **handle) +{ + return __cudaInitModule(handle); +} + +#include "common_functions.h" + +#pragma pack() + +#if defined(_WIN32) + +#pragma warning(disable: 4099) + +#if !defined(_WIN64) + +#pragma warning(disable: 4408) + +#endif /* !_WIN64 */ + +#endif /* _WIN32 */ + +#endif /* !__CUDA_INTERNAL_COMPILATION__ */ + +#if defined(__UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_HOST_RUNTIME_H__) +#undef __CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__ +#undef __UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_HOST_RUNTIME_H__ +#endif diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/math_functions.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/math_functions.h new file mode 100644 index 0000000000000000000000000000000000000000..d8201f97efb3aed940f62360d90899a5171eeb0d --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/math_functions.h @@ -0,0 +1,6257 @@ +/* + * Copyright 1993-2024 NVIDIA Corporation. All rights reserved. + * + * NOTICE TO LICENSEE: + * + * This source code and/or documentation ("Licensed Deliverables") are + * subject to NVIDIA intellectual property rights under U.S. and + * international Copyright laws. + * + * These Licensed Deliverables contained herein is PROPRIETARY and + * CONFIDENTIAL to NVIDIA and is being provided under the terms and + * conditions of a form of NVIDIA software license agreement by and + * between NVIDIA and Licensee ("License Agreement") or electronically + * accepted by Licensee. Notwithstanding any terms or conditions to + * the contrary in the License Agreement, reproduction or disclosure + * of the Licensed Deliverables to any third party without the express + * written consent of NVIDIA is prohibited. + * + * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE + * LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE + * SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE. IT IS + * PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND. + * NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED + * DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY, + * NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE. + * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE + * LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY + * SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY + * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS + * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THESE LICENSED DELIVERABLES. + * + * U.S. Government End Users. These Licensed Deliverables are a + * "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT + * 1995), consisting of "commercial computer software" and "commercial + * computer software documentation" as such terms are used in 48 + * C.F.R. 12.212 (SEPT 1995) and is provided to the U.S. Government + * only as a commercial end item. Consistent with 48 C.F.R.12.212 and + * 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all + * U.S. Government End Users acquire the Licensed Deliverables with + * only those rights set forth herein. + * + * Any use of the Licensed Deliverables in individual and commercial + * software must include, in the user documentation and internal + * comments to the code, the above Disclaimer and U.S. Government End + * Users Notice. + */ + +#if !defined(__CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__) +#if defined(_MSC_VER) +#pragma message("crt/math_functions.h is an internal header file and must not be used directly. Please use cuda_runtime_api.h or cuda_runtime.h instead.") +#else +#warning "crt/math_functions.h is an internal header file and must not be used directly. Please use cuda_runtime_api.h or cuda_runtime.h instead." +#endif +#define __CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__ +#define __UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_MATH_FUNCTIONS_H__ +#endif + +#if !defined(__MATH_FUNCTIONS_H__) +#define __MATH_FUNCTIONS_H__ + +#if defined(__QNX__) && (__GNUC__ >= 5) && defined(__CUDACC__) +#if __has_include(<__config>) +#include <__config> +#endif +#endif + +/** + * \defgroup CUDA_MATH Mathematical Functions + * + * CUDA mathematical functions are always available in device code. + * + * Host implementations of the common mathematical functions are mapped + * in a platform-specific way to standard math library functions, provided + * by the host compiler and respective host libm where available. + * Some functions, not available with the host compilers, are implemented + * in crt/math_functions.hpp header file. + * For example, see ::erfinv(). Other, less common functions, + * like ::rhypot(), ::cyl_bessel_i0() are only available in device code. + * + * CUDA Math device functions are no-throw for well-formed CUDA programs. + * + * Note that many floating-point and integer functions names are + * overloaded for different argument types. For example, the ::log() + * function has the following prototypes: + * \code + * double log(double x); + * float log(float x); + * float logf(float x); + * \endcode + * + * Note also that due to implementation constraints, certain math functions + * from std:: namespace may be callable in device code even via explicitly + * qualified std:: names. However, such use is discouraged, since this + * capability is unsupported, unverified, undocumented, not portable, and + * may change without notice. + */ + +/******************************************************************************* +* * +* * +* * +*******************************************************************************/ + +#if defined(__cplusplus) && defined(__CUDACC__) + +/******************************************************************************* +* * +* * +* * +*******************************************************************************/ + +#include "builtin_types.h" +#include "host_defines.h" + +//NOTE: For NVRTC, these declarations have been moved into the compiler (to reduce compile time) +#define EXCLUDE_FROM_RTC + +/******************************************************************************* +* * +* * +* * +*******************************************************************************/ + +extern "C" +{ + +/** + * @{ + */ + +/* Define math function DOXYGEN toplevel groups, functions will + be added to these groups later. +*/ +/** + * \defgroup CUDA_MATH_SINGLE Single Precision Mathematical Functions + * This section describes single precision mathematical functions. + * To use these functions, you do not need to include any additional + * header file in your program. + */ + +/** + * \defgroup CUDA_MATH_DOUBLE Double Precision Mathematical Functions + * This section describes double precision mathematical functions. + * To use these functions, you do not need to include any additional + * header file in your program. + */ + +/** + * \defgroup CUDA_MATH_INT Integer Mathematical Functions + * This section describes integer mathematical functions. + * To use these functions, you do not need to include any additional + * header file in your program. + */ + +/** + * \defgroup CUDA_MATH_INTRINSIC_SINGLE Single Precision Intrinsics + * This section describes single precision intrinsic functions that are + * only supported in device code. + * To use these functions, you do not need to include any additional + * header file in your program. + */ + +/** + * \defgroup CUDA_MATH_INTRINSIC_DOUBLE Double Precision Intrinsics + * This section describes double precision intrinsic functions that are + * only supported in device code. + * To use these functions, you do not need to include any additional + * header file in your program. + */ + +/** + * \defgroup CUDA_MATH_INTRINSIC_INT Integer Intrinsics + * This section describes integer intrinsic functions. All of these + * functions are supported in device code. For some of the functions, + * host-specific implementations are also provided. For example, + * see `::__nv_bswap16()`. + * To use these functions, you do not need to include any additional + * header file in your program. + */ + +/** + * \defgroup CUDA_MATH_INTRINSIC_CAST Type Casting Intrinsics + * This section describes type casting intrinsic functions that are + * only supported in device code. + * To use these functions, you do not need to include any additional + * header file in your program. + */ + +/** + * + * \defgroup CUDA_MATH_INTRINSIC_SIMD SIMD Intrinsics + * This section describes SIMD intrinsic functions that are + * only supported in device code. + * To use these functions, you do not need to include any additional + * header file in your program. + */ + + +/** + * @} + */ +#define __DEVICE_FUNCTIONS_DECL__ __host__ __device__ +#if !defined(_MSC_VER) +#define __CUDA_MATH_CRTIMP +#else +#if _MSC_VER < 1900 +#define __CUDA_MATH_CRTIMP _CRTIMP +#else +#define __CUDA_MATH_CRTIMP _ACRTIMP +#endif +#endif + +#if defined(__ANDROID__) && (__ANDROID_API__ <= 20) && !defined(__aarch64__) +static __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __cudart_builtin__ int abs(int); +static __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __cudart_builtin__ long int labs(long int); +static __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __cudart_builtin__ long long int llabs(long long int); +#else /* __ANDROID__ */ +#if defined(__QNX__) && !defined(_LIBCPP_VERSION) +namespace std { +#endif +/** + * \ingroup CUDA_MATH_INT + * \brief Calculate the absolute value of the input \p int argument. + * + * Calculate the absolute value of the input argument \p a. + * + * \return + * Returns the absolute value of the input argument. + * - abs(\p INT_MIN) is \p Undefined + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __cudart_builtin__ int __cdecl abs(int a) __THROW; +/** + * \ingroup CUDA_MATH_INT + * \brief Calculate the absolute value of the input \p long \p int argument. + * + * Calculate the absolute value of the input argument \p a. + * + * \return + * Returns the absolute value of the input argument. + * - labs(\p LONG_MIN) is \p Undefined + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __cudart_builtin__ long int __cdecl labs(long int a) __THROW; +/** + * \ingroup CUDA_MATH_INT + * \brief Calculate the absolute value of the input \p long \p long \p int argument. + * + * Calculate the absolute value of the input argument \p a. + * + * \return + * Returns the absolute value of the input argument. + * - llabs(\p LLONG_MIN) is \p Undefined + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __cudart_builtin__ long long int llabs(long long int a) __THROW; +#if defined(__QNX__) && !defined(_LIBCPP_VERSION) +} +#endif +#endif /* __ANDROID__ */ + +#if defined(__QNX__) && !defined(_LIBCPP_VERSION) +/* put all math functions in std */ +namespace std { +#endif +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the absolute value of the input argument. + * + * Calculate the absolute value of the input argument \p x. + * + * \return + * Returns the absolute value of the input argument. + * - fabs( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - fabs( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns +0. + * - fabs(NaN) returns an unspecified NaN. + * \note_accuracy_double + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double __cdecl fabs(double x) __THROW; +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the absolute value of its argument + * + * Calculate the absolute value of the input argument \p x. + * + * \return + * Returns the absolute value of its argument. + * - fabsf( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - fabsf( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns +0. + * - fabsf(NaN) returns an unspecified NaN. + * + * \note_accuracy_single + */ +#if defined(_WIN32) && defined(_M_ARM64) +extern __CUDA_MATH_CRTIMP __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __cdecl fabsf(float x) __THROW; +#else +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float fabsf(float x) __THROW; +#endif +#if defined(__QNX__) && !defined(_LIBCPP_VERSION) +} /* std */ +#endif +/** + * \ingroup CUDA_MATH_INT + * \brief Calculate the minimum value of the input \p int arguments. + * + * Calculate the minimum value of the arguments \p a and \p b. + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ int min(const int a, const int b); +/** + * \ingroup CUDA_MATH_INT + * \brief Calculate the minimum value of the input \p unsigned \p int arguments. + * + * Calculate the minimum value of the arguments \p a and \p b. + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int umin(const unsigned int a, const unsigned int b); +/** + * \ingroup CUDA_MATH_INT + * \brief Calculate the minimum value of the input \p long \p long \p int arguments. + * + * Calculate the minimum value of the arguments \p a and \p b. + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ long long int llmin(const long long int a, const long long int b); +/** + * \ingroup CUDA_MATH_INT + * \brief Calculate the minimum value of the input \p unsigned \p long \p long \p int arguments. + * + * Calculate the minimum value of the arguments \p a and \p b. + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned long long int ullmin(const unsigned long long int a, const unsigned long long int b); + +#if defined(__QNX__) && !defined(_LIBCPP_VERSION) +namespace std { +#endif +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Determine the minimum numeric value of the arguments. + * + * Determines the minimum numeric value of the arguments \p x and \p y. Treats NaN + * arguments as missing data. If one argument is a NaN and the other is legitimate numeric + * value, the numeric value is chosen. + * + * \return + * Returns the minimum numeric value of the arguments \p x and \p y. + * - If both arguments are NaN, returns NaN. + * - If one argument is NaN, returns the numeric argument. + * + * \note_accuracy_single + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float fminf(float x, float y) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP float __cdecl fminf(float x, float y); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Determine the minimum numeric value of the arguments. + * + * Determines the minimum numeric value of the arguments \p x and \p y. Treats NaN + * arguments as missing data. If one argument is a NaN and the other is legitimate numeric + * value, the numeric value is chosen. + * + * \return + * Returns the minimum numeric value of the arguments \p x and \p y. + * - If both arguments are NaN, returns NaN. + * - If one argument is NaN, returns the numeric argument. + * + * \note_accuracy_double + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double fmin(double x, double y) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl fmin(double x, double y); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +#if defined(__QNX__) && !defined(_LIBCPP_VERSION) +} /* std */ +#endif +/** + * \ingroup CUDA_MATH_INT + * \brief Calculate the maximum value of the input \p int arguments. + * + * Calculate the maximum value of the arguments \p a and \p b. + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ int max(const int a, const int b); + +/** + * \ingroup CUDA_MATH_INT + * \brief Calculate the maximum value of the input \p unsigned \p int arguments. + * + * Calculate the maximum value of the arguments \p a and \p b. + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned int umax(const unsigned int a, const unsigned int b); +/** + * \ingroup CUDA_MATH_INT + * \brief Calculate the maximum value of the input \p long \p long \p int arguments. + * + * Calculate the maximum value of the arguments \p a and \p b. + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ long long int llmax(const long long int a, const long long int b); +/** + * \ingroup CUDA_MATH_INT + * \brief Calculate the maximum value of the input \p unsigned \p long \p long \p int arguments. + * + * Calculate the maximum value of the arguments \p a and \p b. + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ unsigned long long int ullmax(const unsigned long long int a, const unsigned long long int b); + +#if defined(__QNX__) && !defined(_LIBCPP_VERSION) +namespace std { +#endif +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Determine the maximum numeric value of the arguments. + * + * Determines the maximum numeric value of the arguments \p x and \p y. Treats NaN + * arguments as missing data. If one argument is a NaN and the other is legitimate numeric + * value, the numeric value is chosen. + * + * \return + * Returns the maximum numeric values of the arguments \p x and \p y. + * - If both arguments are NaN, returns NaN. + * - If one argument is NaN, returns the numeric argument. + * + * \note_accuracy_single + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float fmaxf(float x, float y) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP float __cdecl fmaxf(float x, float y); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Determine the maximum numeric value of the arguments. + * + * Determines the maximum numeric value of the arguments \p x and \p y. Treats NaN + * arguments as missing data. If one argument is a NaN and the other is legitimate numeric + * value, the numeric value is chosen. + * + * \return + * Returns the maximum numeric values of the arguments \p x and \p y. + * - If both arguments are NaN, returns NaN. + * - If one argument is NaN, returns the numeric argument. + * + * \note_accuracy_double + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double fmax(double, double) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl fmax(double, double); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the sine of the input argument. + * + * Calculate the sine of the input argument \p x (measured in radians). + * + * \return + * - sin( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - sin( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns NaN. + * - sin(NaN) returns NaN. + * + * \note_accuracy_double + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double __cdecl sin(double x) __THROW; +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the cosine of the input argument. + * + * Calculate the cosine of the input argument \p x (measured in radians). + * + * \return + * - cos( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns 1. + * - cos( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns NaN. + * - cos(NaN) returns NaN. + * + * \note_accuracy_double + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double __cdecl cos(double x) __THROW; +#if defined(__QNX__) && !defined(_LIBCPP_VERSION) +} /* std */ +#endif + +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the sine and cosine of the first input argument. + * + * Calculate the sine and cosine of the first input argument \p x (measured + * in radians). The results for sine and cosine are written into the + * second argument, \p sptr, and, respectively, third argument, \p cptr. + * + * \see ::sin() and ::cos(). + * \note_accuracy_double + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ void sincos(double x, double *sptr, double *cptr) __THROW; +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the sine and cosine of the first input argument. + * + * Calculate the sine and cosine of the first input argument \p x (measured + * in radians). The results for sine and cosine are written into the second + * argument, \p sptr, and, respectively, third argument, \p cptr. + * + * \see ::sinf() and ::cosf(). + * \note_accuracy_single + * \note_fastmath + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ void sincosf(float x, float *sptr, float *cptr) __THROW; + +#if defined(__QNX__) && !defined(_LIBCPP_VERSION) +namespace std { +#endif +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the tangent of the input argument. + * + * Calculate the tangent of the input argument \p x (measured in radians). + * + * \return + * - tan( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - tan( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns NaN. + * - tan(NaN) returns NaN. + * + * \note_accuracy_double + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double __cdecl tan(double x) __THROW; +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the square root of the input argument. + * + * Calculate the nonnegative square root of \p x, + * \cuda_math_formula \sqrt{x} \end_cuda_math_formula. + * + * \return + * Returns + * \cuda_math_formula \sqrt{x} \end_cuda_math_formula. + * - sqrt( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - sqrt( + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - sqrt(\p x) returns NaN if \p x is less than 0. + * - sqrt(NaN) returns NaN. + * + * \note_accuracy_double + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double __cdecl sqrt(double x) __THROW; +#if defined(__QNX__) && !defined(_LIBCPP_VERSION) +} /* std */ +#endif +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the reciprocal of the square root of the input argument. + * + * Calculate the reciprocal of the nonnegative square root of \p x, + * \cuda_math_formula 1/\sqrt{x} \end_cuda_math_formula. + * + * \return + * Returns + * \cuda_math_formula 1/\sqrt{x} \end_cuda_math_formula. + * - rsqrt( + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns +0. + * - rsqrt( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm \infty \end_cuda_math_formula. + * - rsqrt(\p x) returns NaN if \p x is less than 0. + * - rsqrt(NaN) returns NaN. + * + * \note_accuracy_double + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double rsqrt(double x); + +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the reciprocal of the square root of the input argument. + * + * Calculate the reciprocal of the nonnegative square root of \p x, + * \cuda_math_formula 1/\sqrt{x} \end_cuda_math_formula. + * + * \return + * Returns + * \cuda_math_formula 1/\sqrt{x} \end_cuda_math_formula. + * - rsqrtf( + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns +0. + * - rsqrtf( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm \infty \end_cuda_math_formula. + * - rsqrtf(\p x) returns NaN if \p x is less than 0. + * - rsqrtf(NaN) returns NaN. + * + * \note_accuracy_single + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float rsqrtf(float x); + +#if defined(__QNX__) && !defined(_LIBCPP_VERSION) +namespace std { +#endif +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the base 2 logarithm of the input argument. + * + * Calculate the base 2 logarithm of the input argument \p x. + * + * \return + * - log2( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula -\infty \end_cuda_math_formula. + * - log2(1) returns +0. + * - log2(\p x) returns NaN for \p x < 0. + * - log2( + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - log2(NaN) returns NaN. + * + * \note_accuracy_double + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double log2(double x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl log2(double x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the base 2 exponential of the input argument. + * + * Calculate + * \cuda_math_formula 2^x \end_cuda_math_formula +, + * the base 2 exponential of the input argument \p x. + * + * \return + * - exp2( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns 1. + * - exp2( + * \cuda_math_formula -\infty \end_cuda_math_formula + * ) returns +0. + * - exp2( + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - exp2(NaN) returns NaN. + * + * \note_accuracy_double + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double exp2(double x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl exp2(double x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the base 2 exponential of the input argument. + * + * Calculate + * \cuda_math_formula 2^x \end_cuda_math_formula +, + * the base 2 exponential of the input argument \p x. + * + * \return + * - exp2f( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns 1. + * - exp2f( + * \cuda_math_formula -\infty \end_cuda_math_formula + * ) returns +0. + * - exp2f( + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - exp2f(NaN) returns NaN. + * + * \note_accuracy_single + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float exp2f(float x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP float __cdecl exp2f(float x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +#if defined(__QNX__) && !defined(_LIBCPP_VERSION) +} /* std */ +#endif +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the base 10 exponential of the input argument. + * + * Calculate + * \cuda_math_formula 10^x \end_cuda_math_formula +, + * the base 10 exponential of the input argument \p x. + * + * \return + * - exp10( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns 1. + * - exp10( + * \cuda_math_formula -\infty \end_cuda_math_formula + * ) returns +0. + * - exp10( + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - exp10(NaN) returns NaN. + * + * \note_accuracy_double + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double exp10(double x) __THROW; + +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the base 10 exponential of the input argument. + * + * Calculate + * \cuda_math_formula 10^x \end_cuda_math_formula +, + * the base 10 exponential of the input argument \p x. + * + * \return + * - exp10f( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns 1. + * - exp10f( + * \cuda_math_formula -\infty \end_cuda_math_formula + * ) returns +0. + * - exp10f( + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - exp10f(NaN) returns NaN. + * + * \note_accuracy_single + * \note_fastmath + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float exp10f(float x) __THROW; + +#if defined(__QNX__) && !defined(_LIBCPP_VERSION) +namespace std { +#endif +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the base + * \cuda_math_formula e \end_cuda_math_formula + * exponential of the input argument, minus 1. + * + * Calculate + * \cuda_math_formula e^x \end_cuda_math_formula + * -1, the base + * \cuda_math_formula e \end_cuda_math_formula + * exponential of the input argument \p x, minus 1. + * + * \return + * - expm1( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - expm1( + * \cuda_math_formula -\infty \end_cuda_math_formula + * ) returns -1. + * - expm1( + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - expm1(NaN) returns NaN. + * + * \note_accuracy_double + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double expm1(double x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl expm1(double x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the base + * \cuda_math_formula e \end_cuda_math_formula + * exponential of the input argument, minus 1. + * + * Calculate + * \cuda_math_formula e^x \end_cuda_math_formula + * -1, the base + * \cuda_math_formula e \end_cuda_math_formula + * exponential of the input argument \p x, minus 1. + * + * \return + * - expm1f( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - expm1f( + * \cuda_math_formula -\infty \end_cuda_math_formula + * ) returns -1. + * - expm1f( + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - expm1f(NaN) returns NaN. + * + * \note_accuracy_single + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float expm1f(float x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP float __cdecl expm1f(float x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the base 2 logarithm of the input argument. + * + * Calculate the base 2 logarithm of the input argument \p x. + * + * \return + * - log2f( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula -\infty \end_cuda_math_formula. + * - log2f(1) returns +0. + * - log2f(\p x) returns NaN for \p x < 0. + * - log2f( + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - log2f(NaN) returns NaN. + * + * \note_accuracy_single + * \note_fastmath + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float log2f(float x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP float __cdecl log2f(float x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the base 10 logarithm of the input argument. + * + * Calculate the base 10 logarithm of the input argument \p x. + * + * \return + * - log10( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula -\infty \end_cuda_math_formula. + * - log10(1) returns +0. + * - log10(\p x) returns NaN for \p x < 0. + * - log10( + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - log10(NaN) returns NaN. + * + * \note_accuracy_double + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double __cdecl log10(double x) __THROW; +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the base + * \cuda_math_formula e \end_cuda_math_formula + * logarithm of the input argument. + * + * Calculate the base + * \cuda_math_formula e \end_cuda_math_formula + * logarithm of the input argument \p x. + * + * \return + * - log( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula -\infty \end_cuda_math_formula. + * - log(1) returns +0. + * - log(\p x) returns NaN for \p x < 0. + * - log( + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - log(NaN) returns NaN. + * + * \note_accuracy_double + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double __cdecl log(double x) __THROW; +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the value of + * \cuda_math_formula \log_{e}(1+x) \end_cuda_math_formula. + * + * Calculate the value of + * \cuda_math_formula \log_{e}(1+x) \end_cuda_math_formula + * of the input argument \p x. + * + * \return + * - log1p( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - log1p(-1) returns + * \cuda_math_formula -\infty \end_cuda_math_formula. + * - log1p(\p x) returns NaN for \p x < -1. + * - log1p( + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - log1p(NaN) returns NaN. + * + * \note_accuracy_double + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double log1p(double x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl log1p(double x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the value of + * \cuda_math_formula \log_{e}(1+x) \end_cuda_math_formula. + * + * Calculate the value of + * \cuda_math_formula \log_{e}(1+x) \end_cuda_math_formula + * of the input argument \p x. + * + * \return + * - log1pf( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - log1pf(-1) returns + * \cuda_math_formula -\infty \end_cuda_math_formula. + * - log1pf(\p x) returns NaN for \p x < -1. + * - log1pf( + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - log1pf(NaN) returns NaN. + * + * \note_accuracy_single + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float log1pf(float x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP float __cdecl log1pf(float x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the largest integer less than or equal to \p x. + * + * Calculates the largest integer value which is less than or equal to \p x. + * + * \return + * Returns + * \cuda_math_formula \lfloor x \rfloor \end_cuda_math_formula + * expressed as a floating-point number. + * - floor( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm \infty \end_cuda_math_formula. + * - floor( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - floor(NaN) returns NaN. + * + * \note_accuracy_double + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl floor(double x) __THROW; +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the base + * \cuda_math_formula e \end_cuda_math_formula + * exponential of the input argument. + * + * Calculate + * \cuda_math_formula e^x \end_cuda_math_formula +, + * the base + * \cuda_math_formula e \end_cuda_math_formula + * exponential of the input argument \p x. + * + * \return + * - exp( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns 1. + * - exp( + * \cuda_math_formula -\infty \end_cuda_math_formula + * ) returns +0. + * - exp( + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - exp(NaN) returns NaN. + * + * \note_accuracy_double + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double __cdecl exp(double x) __THROW; +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the hyperbolic cosine of the input argument. + * + * Calculate the hyperbolic cosine of the input argument \p x. + * + * \return + * - cosh( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns 1. + * - cosh( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - cosh(NaN) returns NaN. + * + * \note_accuracy_double + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double __cdecl cosh(double x) __THROW; +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the hyperbolic sine of the input argument. + * + * Calculate the hyperbolic sine of the input argument \p x. + * + * \return + * - sinh( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - sinh( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm \infty \end_cuda_math_formula. + * - sinh(NaN) returns NaN. + * + * \note_accuracy_double + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double __cdecl sinh(double x) __THROW; +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the hyperbolic tangent of the input argument. + * + * Calculate the hyperbolic tangent of the input argument \p x. + * + * \return + * - tanh( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - tanh( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 1 \end_cuda_math_formula. + * - tanh(NaN) returns NaN. + * + * \note_accuracy_double + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double __cdecl tanh(double x) __THROW; +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the nonnegative inverse hyperbolic cosine of the input argument. + * + * Calculate the nonnegative inverse hyperbolic cosine of the input argument \p x. + * + * \return + * Result will be in the interval [0, + * \cuda_math_formula +\infty \end_cuda_math_formula + * ]. + * - acosh(1) returns 0. + * - acosh(\p x) returns NaN for \p x in the interval [ + * \cuda_math_formula -\infty \end_cuda_math_formula + * , 1). + * - acosh( + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - acosh(NaN) returns NaN. + * + * \note_accuracy_double + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double acosh(double x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl acosh(double x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the nonnegative inverse hyperbolic cosine of the input argument. + * + * Calculate the nonnegative inverse hyperbolic cosine of the input argument \p x. + * + * \return + * Result will be in the interval [0, + * \cuda_math_formula +\infty \end_cuda_math_formula + * ]. + * - acoshf(1) returns 0. + * - acoshf(\p x) returns NaN for \p x in the interval [ + * \cuda_math_formula -\infty \end_cuda_math_formula + * , 1). + * - acoshf( + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - acoshf(NaN) returns NaN. + * + * \note_accuracy_single + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float acoshf(float x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP float __cdecl acoshf(float x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the inverse hyperbolic sine of the input argument. + * + * Calculate the inverse hyperbolic sine of the input argument \p x. + * + * \return + * - asinh( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - asinh( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm \infty \end_cuda_math_formula. + * - asinh(NaN) returns NaN. + * + * \note_accuracy_double + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double asinh(double x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl asinh(double x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the inverse hyperbolic sine of the input argument. + * + * Calculate the inverse hyperbolic sine of the input argument \p x. + * + * \return + * - asinhf( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - asinhf( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm \infty \end_cuda_math_formula. + * - asinhf(NaN) returns NaN. + * + * \note_accuracy_single + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float asinhf(float x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP float __cdecl asinhf(float x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the inverse hyperbolic tangent of the input argument. + * + * Calculate the inverse hyperbolic tangent of the input argument \p x. + * + * \return + * - atanh( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - atanh( + * \cuda_math_formula \pm 1 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm \infty \end_cuda_math_formula. + * - atanh(\p x) returns NaN for \p x outside interval [-1, 1]. + * - atanh(NaN) returns NaN. + * + * \note_accuracy_double + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double atanh(double x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl atanh(double x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the inverse hyperbolic tangent of the input argument. + * + * Calculate the inverse hyperbolic tangent of the input argument \p x. + * + * \return + * - atanhf( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - atanhf( + * \cuda_math_formula \pm 1 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm \infty \end_cuda_math_formula. + * - atanhf(\p x) returns NaN for \p x outside interval [-1, 1]. + * - atanhf(NaN) returns NaN. + * + * \note_accuracy_single + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float atanhf(float x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP float __cdecl atanhf(float x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the value of + * \cuda_math_formula x\cdot 2^{exp} \end_cuda_math_formula. + * + * Calculate the value of + * \cuda_math_formula x\cdot 2^{exp} \end_cuda_math_formula + * of the input arguments \p x and \p exp. + * + * \return + * - ldexp(\p x, \p exp) is equivalent to scalbn(\p x, \p exp). + * + * \note_accuracy_double + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl ldexp(double x, int exp) __THROW; +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the value of + * \cuda_math_formula x\cdot 2^{exp} \end_cuda_math_formula. + * + * Calculate the value of + * \cuda_math_formula x\cdot 2^{exp} \end_cuda_math_formula + * of the input arguments \p x and \p exp. + * + * \return + * - ldexpf(\p x, \p exp) is equivalent to scalbnf(\p x, \p exp). + * + * \note_accuracy_single + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float ldexpf(float x, int exp) __THROW; +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the floating-point representation of the exponent of the input argument. + * + * Calculate the floating-point representation of the exponent of the input argument \p x. + * + * \return + * - logb( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula -\infty \end_cuda_math_formula. + * - logb( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - logb(NaN) returns NaN. + * + * \note_accuracy_double + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double logb(double x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl logb(double x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the floating-point representation of the exponent of the input argument. + * + * Calculate the floating-point representation of the exponent of the input argument \p x. + * + * \return + * - logbf( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula -\infty \end_cuda_math_formula. + * - logbf( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - logbf(NaN) returns NaN. + * + * \note_accuracy_single + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float logbf(float x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP float __cdecl logbf(float x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Compute the unbiased integer exponent of the argument. + * + * Calculates the unbiased integer exponent of the input argument \p x. + * + * \return + * - If successful, returns the unbiased exponent of the argument. + * - ilogb( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns INT_MIN. + * - ilogb(NaN) returns INT_MIN. + * - ilogb( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns INT_MAX. + * - Note: above behavior does not take into account FP_ILOGB0 nor FP_ILOGBNAN. + * + * \note_accuracy_double + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ int ilogb(double x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP int __cdecl ilogb(double x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Compute the unbiased integer exponent of the argument. + * + * Calculates the unbiased integer exponent of the input argument \p x. + * + * \return + * - If successful, returns the unbiased exponent of the argument. + * - ilogbf( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns INT_MIN. + * - ilogbf(NaN) returns INT_MIN. + * - ilogbf( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns INT_MAX. + * - Note: above behavior does not take into account FP_ILOGB0 nor FP_ILOGBNAN. + * + * \note_accuracy_single + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ int ilogbf(float x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP int __cdecl ilogbf(float x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Scale floating-point input by integer power of two. + * + * Scale \p x by + * \cuda_math_formula 2^n \end_cuda_math_formula + * by efficient manipulation of the floating-point + * exponent. + * + * \return + * Returns \p x * + * \cuda_math_formula 2^n \end_cuda_math_formula. + * - scalbn( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * , \p n) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - scalbn(\p x, 0) returns \p x. + * - scalbn( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * , \p n) returns + * \cuda_math_formula \pm \infty \end_cuda_math_formula. + * - scalbn(NaN, \p n) returns NaN. + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double scalbn(double x, int n) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl scalbn(double x, int n); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Scale floating-point input by integer power of two. + * + * Scale \p x by + * \cuda_math_formula 2^n \end_cuda_math_formula + * by efficient manipulation of the floating-point + * exponent. + * + * \return + * Returns \p x * + * \cuda_math_formula 2^n \end_cuda_math_formula. + * - scalbnf( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * , \p n) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - scalbnf(\p x, 0) returns \p x. + * - scalbnf( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * , \p n) returns + * \cuda_math_formula \pm \infty \end_cuda_math_formula. + * - scalbnf(NaN, \p n) returns NaN. + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float scalbnf(float x, int n) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP float __cdecl scalbnf(float x, int n); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Scale floating-point input by integer power of two. + * + * Scale \p x by + * \cuda_math_formula 2^n \end_cuda_math_formula + * by efficient manipulation of the floating-point + * exponent. + * + * \return + * Returns \p x * + * \cuda_math_formula 2^n \end_cuda_math_formula. + * - scalbln( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * , \p n) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - scalbln(\p x, 0) returns \p x. + * - scalbln( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * , \p n) returns + * \cuda_math_formula \pm \infty \end_cuda_math_formula. + * - scalbln(NaN, \p n) returns NaN. + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double scalbln(double x, long int n) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl scalbln(double x, long int n); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Scale floating-point input by integer power of two. + * + * Scale \p x by + * \cuda_math_formula 2^n \end_cuda_math_formula + * by efficient manipulation of the floating-point + * exponent. + * + * \return + * Returns \p x * + * \cuda_math_formula 2^n \end_cuda_math_formula. + * - scalblnf( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * , \p n) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - scalblnf(\p x, 0) returns \p x. + * - scalblnf( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * , \p n) returns + * \cuda_math_formula \pm \infty \end_cuda_math_formula. + * - scalblnf(NaN, \p n) returns NaN. + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float scalblnf(float x, long int n) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP float __cdecl scalblnf(float x, long int n); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Extract mantissa and exponent of a floating-point value + * + * Decompose the floating-point value \p x into a component \p m for the + * normalized fraction element and another term \p n for the exponent. + * The absolute value of \p m will be greater than or equal to 0.5 and + * less than 1.0 or it will be equal to 0; + * \cuda_math_formula x = m\cdot 2^n \end_cuda_math_formula. + * The integer exponent \p n will be stored in the location to which \p nptr points. + * + * \return + * Returns the fractional component \p m. + * - frexp( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * , \p nptr) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * and stores zero in the location pointed to by \p nptr. + * - frexp( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * , \p nptr) returns + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * and stores an unspecified value in the + * location to which \p nptr points. + * - frexp(NaN, \p y) returns a NaN and stores an unspecified value in the location to which \p nptr points. + * + * \note_accuracy_double + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl frexp(double x, int *nptr) __THROW; +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Extract mantissa and exponent of a floating-point value + * + * Decomposes the floating-point value \p x into a component \p m for the + * normalized fraction element and another term \p n for the exponent. + * The absolute value of \p m will be greater than or equal to 0.5 and + * less than 1.0 or it will be equal to 0; + * \cuda_math_formula x = m\cdot 2^n \end_cuda_math_formula. + * The integer exponent \p n will be stored in the location to which \p nptr points. + * + * \return + * Returns the fractional component \p m. + * - frexpf( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * , \p nptr) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * and stores zero in the location pointed to by \p nptr. + * - frexpf( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * , \p nptr) returns + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * and stores an unspecified value in the + * location to which \p nptr points. + * - frexpf(NaN, \p y) returns a NaN and stores an unspecified value in the location to which \p nptr points. + * + * \note_accuracy_single + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float frexpf(float x, int *nptr) __THROW; +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Round to nearest integer value in floating-point. + * + * Round \p x to the nearest integer value in floating-point format, + * with halfway cases rounded away from zero. + * + * \return + * Returns rounded integer value. + * - round( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - round( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm \infty \end_cuda_math_formula. + * - round(NaN) returns NaN. + * + * \note_slow_round See ::rint(). + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double round(double x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl round(double x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Round to nearest integer value in floating-point. + * + * Round \p x to the nearest integer value in floating-point format, + * with halfway cases rounded away from zero. + * + * \return + * Returns rounded integer value. + * - roundf( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - roundf( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm \infty \end_cuda_math_formula. + * - roundf(NaN) returns NaN. + * + * \note_slow_round See ::rintf(). + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float roundf(float x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP float __cdecl roundf(float x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Round to nearest integer value. + * + * Round \p x to the nearest integer value, with halfway cases rounded + * away from zero. If the result is outside the range of the return type, + * the behavior is undefined. + * + * \return + * Returns rounded integer value. + * + * \note_slow_round See ::lrint(). + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ long int lround(double x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP long int __cdecl lround(double x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Round to nearest integer value. + * + * Round \p x to the nearest integer value, with halfway cases rounded + * away from zero. If the result is outside the range of the return type, + * the behavior is undefined. + * + * \return + * Returns rounded integer value. + * + * \note_slow_round See ::lrintf(). + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ long int lroundf(float x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP long int __cdecl lroundf(float x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Round to nearest integer value. + * + * Round \p x to the nearest integer value, with halfway cases rounded + * away from zero. If the result is outside the range of the return type, + * the behavior is undefined. + * + * \return + * Returns rounded integer value. + * + * \note_slow_round See ::llrint(). + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ long long int llround(double x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP long long int __cdecl llround(double x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Round to nearest integer value. + * + * Round \p x to the nearest integer value, with halfway cases rounded + * away from zero. If the result is outside the range of the return type, + * the behavior is undefined. + * + * \return + * Returns rounded integer value. + * + * \note_slow_round See ::llrintf(). + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ long long int llroundf(float x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP long long int __cdecl llroundf(float x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Round to nearest integer value in floating-point. + * + * Round \p x to the nearest integer value in floating-point format, + * with halfway cases rounded to the nearest even integer value. + * + * \return + * Returns rounded integer value. + * - rint( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - rint( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm \infty \end_cuda_math_formula. + * - rint(NaN) returns NaN. + */ +#if defined(__CUDA_ARCH__) || defined(__DOXYGEN_ONLY__) +/* + * We don't generate the declaration of rint for host compilation. + * This is acaully a workaround to compile the boost header file when + * Clang 3.8 is used as the host compiler. The boost header file has + * the following example code: + * namespace NS { extern "C" { double rint(double); } + * } + * + * After preprocessing, we get something like below: + * + * extern "C" { double rint(double x) throw(); } + * # 30 "/usr/include/math.h" 3 + * extern "C" { double rint(double x) throw(); } + * namespace NS { extern "C" { double rint(double); } } + * + * Although GCC accepts this output, Clang 3.8 doesn't. + * Furthermore, we cannot change the boost header file by adding "throw()" + * to rint's declaration there. So, as a workaround, we just don't generate + * our re-declaration for the host compilation. + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double rint(double x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl rint(double x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +#endif /* __CUDA_ARCH__ || __DOXYGEN_ONLY__ */ +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Round input to nearest integer value in floating-point. + * + * Round \p x to the nearest integer value in floating-point format, + * with halfway cases rounded to the nearest even integer value. + * + * \return + * Returns rounded integer value. + * - rintf( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - rintf( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm \infty \end_cuda_math_formula. + * - rintf(NaN) returns NaN. + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float rintf(float x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP float __cdecl rintf(float x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Round input to nearest integer value. + * + * Round \p x to the nearest integer value, + * with halfway cases rounded to the nearest even integer value. + * If the result is outside the range of the return type, + * the behavior is undefined. + * + * \return + * Returns rounded integer value. + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ long int lrint(double x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP long int __cdecl lrint(double x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Round input to nearest integer value. + * + * Round \p x to the nearest integer value, + * with halfway cases rounded to the nearest even integer value. + * If the result is outside the range of the return type, + * the behavior is undefined. + * + * \return + * Returns rounded integer value. + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ long int lrintf(float x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP long int __cdecl lrintf(float x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Round input to nearest integer value. + * + * Round \p x to the nearest integer value, + * with halfway cases rounded to the nearest even integer value. + * If the result is outside the range of the return type, + * the behavior is undefined. + * + * \return + * Returns rounded integer value. + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ long long int llrint(double x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP long long int __cdecl llrint(double x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Round input to nearest integer value. + * + * Round \p x to the nearest integer value, + * with halfway cases rounded to the nearest even integer value. + * If the result is outside the range of the return type, + * the behavior is undefined. + * + * \return + * Returns rounded integer value. + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ long long int llrintf(float x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP long long int __cdecl llrintf(float x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Round the input argument to the nearest integer. + * + * Round argument \p x to an integer value in double precision floating-point format. Uses round to nearest rounding, with ties rounding to even. + * + * \return + * - nearbyint( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - nearbyint( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm \infty \end_cuda_math_formula. + * - nearbyint(NaN) returns NaN. + * + * \note_accuracy_double + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double nearbyint(double x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl nearbyint(double x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Round the input argument to the nearest integer. + * + * Round argument \p x to an integer value in single precision floating-point format. Uses round to nearest rounding, with ties rounding to even. + * + * \return + * - nearbyintf( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - nearbyintf( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm \infty \end_cuda_math_formula. + * - nearbyintf(NaN) returns NaN. + * + * \note_accuracy_single + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float nearbyintf(float x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP float __cdecl nearbyintf(float x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate ceiling of the input argument. + * + * Compute the smallest integer value not less than \p x. + * + * \return + * Returns + * \cuda_math_formula \lceil x \rceil \end_cuda_math_formula + expressed as a floating-point number. + * - ceil( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - ceil( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm \infty \end_cuda_math_formula. + * - ceil(NaN) returns NaN. + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl ceil(double x) __THROW; +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Truncate input argument to the integral part. + * + * Round \p x to the nearest integer value that does not exceed \p x in + * magnitude. + * + * \return + * Returns truncated integer value. + * - trunc( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - trunc( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm \infty \end_cuda_math_formula. + * - trunc(NaN) returns NaN. + * + * \note_accuracy_double + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double trunc(double x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl trunc(double x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Truncate input argument to the integral part. + * + * Round \p x to the nearest integer value that does not exceed \p x in + * magnitude. + * + * \return + * Returns truncated integer value. + * - truncf( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - truncf( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm \infty \end_cuda_math_formula. + * - truncf(NaN) returns NaN. + * + * \note_accuracy_single + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float truncf(float x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP float __cdecl truncf(float x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Compute the positive difference between \p x and \p y. + * + * Compute the positive difference between \p x and \p y. The positive + * difference is \p x - \p y when \p x > \p y and +0 otherwise. + * + * \return + * Returns the positive difference between \p x and \p y. + * - fdim(\p x, \p y) returns \p x - \p y if \p x > \p y. + * - fdim(\p x, \p y) returns +0 if \p x + * \cuda_math_formula \leq \end_cuda_math_formula + \p y. + * - If either argument is NaN, NaN is returned. + * + * \note_accuracy_double + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double fdim(double x, double y) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl fdim(double x, double y); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Compute the positive difference between \p x and \p y. + * + * Compute the positive difference between \p x and \p y. The positive + * difference is \p x - \p y when \p x > \p y and +0 otherwise. + * + * \return + * Returns the positive difference between \p x and \p y. + * - fdimf(\p x, \p y) returns \p x - \p y if \p x > \p y. + * - fdimf(\p x, \p y) returns +0 if \p x + * \cuda_math_formula \leq \end_cuda_math_formula + \p y. + * - If either argument is NaN, NaN is returned. + * \note_accuracy_single + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float fdimf(float x, float y) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP float __cdecl fdimf(float x, float y); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the arc tangent of the ratio of first and second input arguments. + * + * Calculate the principal value of the arc tangent of the ratio of first + * and second input arguments \p y / \p x. The quadrant of the result is + * determined by the signs of inputs \p y and \p x. + * + * \return + * Result will be in radians, in the interval [- + * \cuda_math_formula \pi \end_cuda_math_formula + * , + + * \cuda_math_formula \pi \end_cuda_math_formula + * ]. + * - atan2( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * , -0) returns + * \cuda_math_formula \pm \pi \end_cuda_math_formula. + * - atan2( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * , +0) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - atan2( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * , \p x) returns + * \cuda_math_formula \pm \pi \end_cuda_math_formula + * for \p x < 0. + * - atan2( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * , \p x) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * for \p x > 0. + * - atan2(\p y, + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula -\pi \end_cuda_math_formula + * /2 for \p y < 0. + * - atan2(\p y, + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pi \end_cuda_math_formula + * /2 for \p y > 0. + * - atan2( + * \cuda_math_formula \pm y \end_cuda_math_formula + * , + * \cuda_math_formula -\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm \pi \end_cuda_math_formula + * for finite \p y > 0. + * - atan2( + * \cuda_math_formula \pm y \end_cuda_math_formula + * , + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * for finite \p y > 0. + * - atan2( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * , \p x) returns + * \cuda_math_formula \pm \pi \end_cuda_math_formula + * /2 for finite \p x. + * - atan2( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * , + * \cuda_math_formula -\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 3\pi \end_cuda_math_formula + * /4. + * - atan2( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * , + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm \pi \end_cuda_math_formula + * /4. + * - If either argument is NaN, NaN is returned. + * + * \note_accuracy_double + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double __cdecl atan2(double y, double x) __THROW; +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the arc tangent of the input argument. + * + * Calculate the principal value of the arc tangent of the input argument \p x. + * + * \return + * Result will be in radians, in the interval [- + * \cuda_math_formula \pi \end_cuda_math_formula + * /2, + + * \cuda_math_formula \pi \end_cuda_math_formula + * /2]. + * - atan( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - atan( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm \pi \end_cuda_math_formula + * /2. + * - atan(NaN) returns NaN. + * + * \note_accuracy_double + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double __cdecl atan(double x) __THROW; +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the arc cosine of the input argument. + * + * Calculate the principal value of the arc cosine of the input argument \p x. + * + * \return + * Result will be in radians, in the interval [0, + * \cuda_math_formula \pi \end_cuda_math_formula + * ] for \p x inside [-1, +1]. + * - acos(1) returns +0. + * - acos(\p x) returns NaN for \p x outside [-1, +1]. + * - acos(NaN) returns NaN. + * + * \note_accuracy_double + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double __cdecl acos(double x) __THROW; +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the arc sine of the input argument. + * + * Calculate the principal value of the arc sine of the input argument \p x. + * + * \return + * Result will be in radians, in the interval [- + * \cuda_math_formula \pi \end_cuda_math_formula + * /2, + + * \cuda_math_formula \pi \end_cuda_math_formula + * /2] for \p x inside [-1, +1]. + * - asin( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - asin(\p x) returns NaN for \p x outside [-1, +1]. + * - asin(NaN) returns NaN. + * + * \note_accuracy_double + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double __cdecl asin(double x) __THROW; +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the square root of the sum of squares of two arguments. + * + * Calculate the length of the hypotenuse of a right triangle whose two sides have lengths + * \p x and \p y without undue overflow or underflow. + * + * \return Returns the length of the hypotenuse + * \cuda_math_formula \sqrt{x^2+y^2} \end_cuda_math_formula. + * - hypot(\p x,\p y), hypot(\p y,\p x), and hypot(\p x, \p -y) are equivalent. + * - hypot(\p x, + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) is equivalent to fabs(\p x). + * - hypot( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ,\p y) returns + * \cuda_math_formula +\infty \end_cuda_math_formula +, + * even if \p y is a NaN. + * - hypot(NaN, \p y) returns NaN, when \p y is not \cuda_math_formula \pm\infty \end_cuda_math_formula. + * + * \note_accuracy_double + */ +#if defined(_WIN32) +#if defined(_MSC_VER) && _MSC_VER < 1900 +static __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double __CRTDECL hypot(double x, double y); +#else +extern _ACRTIMP __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double __cdecl hypot(double x, double y); +#endif +#else /* _WIN32 */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double hypot(double x, double y) __THROW; +#endif /* _WIN32 */ + +#if defined(__QNX__) && !defined(_LIBCPP_VERSION) +} /* std */ +#endif + +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate one over the square root of the sum of squares of two arguments. + * + * Calculate one over the length of the hypotenuse of a right triangle whose two sides have + * lengths \p x and \p y without undue overflow or underflow. + * + * \return Returns one over the length of the hypotenuse + * \cuda_math_formula \frac{1}{\sqrt{x^2+y^2}} \end_cuda_math_formula. + * - rhypot(\p x,\p y), rhypot(\p y,\p x), and rhypot(\p x, \p -y) are equivalent. + * - rhypot( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ,\p y) returns +0, + * even if \p y is a NaN. + * - rhypot(\cuda_math_formula \pm 0, \pm 0 \end_cuda_math_formula) returns \cuda_math_formula +\infty \end_cuda_math_formula. + * - rhypot(NaN, \p y) returns NaN, when \p y is not \cuda_math_formula \pm\infty \end_cuda_math_formula. + * + * \note_accuracy_double + */ +extern __device__ __device_builtin__ double rhypot(double x, double y) __THROW; + +#if defined(__QNX__) && !defined(_LIBCPP_VERSION) +namespace std { +#endif +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the square root of the sum of squares of two arguments. + * + * Calculates the length of the hypotenuse of a right triangle whose two sides have lengths + * \p x and \p y without undue overflow or underflow. + * + * \return Returns the length of the hypotenuse + * \cuda_math_formula \sqrt{x^2+y^2} \end_cuda_math_formula. + * - hypotf(\p x,\p y), hypotf(\p y,\p x), and hypotf(\p x, \p -y) are equivalent. + * - hypotf(\p x, + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) is equivalent to fabsf(\p x). + * - hypotf( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ,\p y) returns + * \cuda_math_formula +\infty \end_cuda_math_formula +, + * even if \p y is a NaN. + * - hypotf(NaN, \p y) returns NaN, when \p y is not \cuda_math_formula \pm\infty \end_cuda_math_formula. + * + * \note_accuracy_single + */ +#if defined(_WIN32) +static __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __CRTDECL hypotf(float x, float y); +#else /* _WIN32 */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float hypotf(float x, float y) __THROW; +#endif /* _WIN32 */ + +#if defined(__QNX__) && !defined(_LIBCPP_VERSION) +} /* std */ +#endif + +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate one over the square root of the sum of squares of two arguments. + * + * Calculates one over the length of the hypotenuse of a right triangle whose two sides have + * lengths \p x and \p y without undue overflow or underflow. + * + * \return Returns one over the length of the hypotenuse + * \cuda_math_formula \frac{1}{\sqrt{x^2+y^2}} \end_cuda_math_formula. + * - rhypotf(\p x,\p y), rhypotf(\p y,\p x), and rhypotf(\p x, \p -y) are equivalent. + * - rhypotf( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ,\p y) returns +0, + * even if \p y is a NaN. + * - rhypotf(\cuda_math_formula \pm 0, \pm 0 \end_cuda_math_formula) returns \cuda_math_formula +\infty \end_cuda_math_formula. + * - rhypotf(NaN, \p y) returns NaN, when \p y is not \cuda_math_formula \pm\infty \end_cuda_math_formula. + * + * \note_accuracy_single + */ +extern __device__ __device_builtin__ float rhypotf(float x, float y) __THROW; + +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the square root of the sum of squares of three coordinates of the argument. + * + * Calculate the length of three dimensional vector in Euclidean space without undue overflow or underflow. + * + * \return Returns the length of 3D vector + * \cuda_math_formula \sqrt{a^2+b^2+c^2} \end_cuda_math_formula. + * - In the presence of an exactly infinite coordinate + * \cuda_math_formula +\infty \end_cuda_math_formula + * is returned, even if there are NaNs. + * - returns +0, when all coordinates are \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - returns NaN, when at least one of the coordinates is NaN and none are infinite. + * + * \note_accuracy_double + */ +extern __device__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl norm3d(double a, double b, double c) __THROW; + +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate one over the square root of the sum of squares of three coordinates. + * + * Calculate one over the length of three dimensional vector in Euclidean space without undue overflow or underflow. + * + * \return Returns one over the length of the 3D vector + * \cuda_math_formula \frac{1}{\sqrt{a^2+b^2+c^2}} \end_cuda_math_formula. + * - In the presence of an exactly infinite coordinate + * \cuda_math_formula +0 \end_cuda_math_formula + * is returned, even if there are NaNs. + * - returns \cuda_math_formula +\infty \end_cuda_math_formula, when all coordinates are \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - returns NaN, when at least one of the coordinates is NaN and none are infinite. + * + * \note_accuracy_double + */ +extern __device__ __device_builtin__ double rnorm3d(double a, double b, double c) __THROW; + +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the square root of the sum of squares of four coordinates of the argument. + * + * Calculate the length of four dimensional vector in Euclidean space without undue overflow or underflow. + * + * \return Returns the length of 4D vector + * \cuda_math_formula \sqrt{a^2+b^2+c^2+d^2} \end_cuda_math_formula. + * - In the presence of an exactly infinite coordinate + * \cuda_math_formula +\infty \end_cuda_math_formula + * is returned, even if there are NaNs. + * - returns +0, when all coordinates are \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - returns NaN, when at least one of the coordinates is NaN and none are infinite. + * + * \note_accuracy_double + */ +extern __device__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl norm4d(double a, double b, double c, double d) __THROW; + +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate one over the square root of the sum of squares of four coordinates. + * + * Calculate one over the length of four dimensional vector in Euclidean space without undue overflow or underflow. + * + * \return Returns one over the length of the 3D vector + * \cuda_math_formula \frac{1}{\sqrt{a^2+b^2+c^2+d^2}} \end_cuda_math_formula. + * - In the presence of an exactly infinite coordinate + * \cuda_math_formula +0 \end_cuda_math_formula + * is returned, even if there are NaNs. + * - returns \cuda_math_formula +\infty \end_cuda_math_formula, when all coordinates are \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - returns NaN, when at least one of the coordinates is NaN and none are infinite. + * + * \note_accuracy_double + */ +extern __device__ __device_builtin__ double rnorm4d(double a, double b, double c, double d) __THROW; + +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the square root of the sum of squares of any number of coordinates. + * + * Calculate the length of a vector p, dimension of which is passed as an argument \p without undue overflow or underflow. + * + * \return Returns the length of the dim-D vector + * \cuda_math_formula \sqrt{\sum_{i=0}^{dim-1} p_i^2} \end_cuda_math_formula. + * - In the presence of an exactly infinite coordinate + * \cuda_math_formula +\infty \end_cuda_math_formula + * is returned, even if there are NaNs. + * - returns +0, when all coordinates are \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - returns NaN, when at least one of the coordinates is NaN and none are infinite. + * + * \note_accuracy_double + */ +__device__ __device_builtin__ double norm(int dim, double const * p) __THROW; + +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the reciprocal of square root of the sum of squares of any number of coordinates. + * + * Calculates one over the length of vector \p p, dimension of which is passed as an argument, in Euclidean space without undue overflow or underflow. + * + * \return Returns one over the length of the vector + * \cuda_math_formula \frac{1}{\sqrt{\sum_{i=0}^{dim-1} p_i^2}} \end_cuda_math_formula. + * - In the presence of an exactly infinite coordinate + * \cuda_math_formula +0 \end_cuda_math_formula + * is returned, even if there are NaNs. + * - returns \cuda_math_formula +\infty \end_cuda_math_formula, when all coordinates are \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - returns NaN, when at least one of the coordinates is NaN and none are infinite. + * + * \note_accuracy_double + */ +extern __device__ __device_builtin__ double rnorm(int dim, double const * p) __THROW; + +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the reciprocal of square root of the sum of squares of any number of coordinates. + * + * Calculates one over the length of vector \p p, dimension of which is passed as an argument, in Euclidean space without undue overflow or underflow. + * + * \return Returns one over the length of the vector + * \cuda_math_formula \frac{1}{\sqrt{\sum_{i=0}^{dim-1} p_i^2}} \end_cuda_math_formula. + * - In the presence of an exactly infinite coordinate + * \cuda_math_formula +0 \end_cuda_math_formula + * is returned, even if there are NaNs. + * - returns \cuda_math_formula +\infty \end_cuda_math_formula, when all coordinates are \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - returns NaN, when at least one of the coordinates is NaN and none are infinite. + * + * \note_accuracy_single + */ + +extern __device__ __device_builtin__ float rnormf(int dim, float const * p) __THROW; + +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the square root of the sum of squares of any number of coordinates. + * + * Calculates the length of a vector \p p, dimension of which is passed as an argument without undue overflow or underflow. + * + * \return Returns the length of the dim-D vector + * \cuda_math_formula \sqrt{\sum_{i=0}^{dim-1} p_i^2} \end_cuda_math_formula. + * - In the presence of an exactly infinite coordinate + * \cuda_math_formula +\infty \end_cuda_math_formula + * is returned, even if there are NaNs. + * - returns +0, when all coordinates are \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - returns NaN, when at least one of the coordinates is NaN and none are infinite. + * + * \note_accuracy_single + */ +__device__ __device_builtin__ float normf(int dim, float const * p) __THROW; + +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the square root of the sum of squares of three coordinates of the argument. + * + * Calculates the length of three dimensional vector in Euclidean space without undue overflow or underflow. + * + * \return Returns the length of the 3D vector + * \cuda_math_formula \sqrt{a^2+b^2+c^2} \end_cuda_math_formula. + * - In the presence of an exactly infinite coordinate + * \cuda_math_formula +\infty \end_cuda_math_formula + * is returned, even if there are NaNs. + * - returns +0, when all coordinates are \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - returns NaN, when at least one of the coordinates is NaN and none are infinite. + * + * \note_accuracy_single + */ + +extern __device__ __device_builtin__ float norm3df(float a, float b, float c) __THROW; + +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate one over the square root of the sum of squares of three coordinates. + * + * Calculates one over the length of three dimension vector in Euclidean space without undue overflow or underflow. + * + * \return Returns one over the length of the 3D vector + * \cuda_math_formula \frac{1}{\sqrt{a^2+b^2+c^2}} \end_cuda_math_formula. + * - In the presence of an exactly infinite coordinate + * \cuda_math_formula +0 \end_cuda_math_formula + * is returned, even if there are NaNs. + * - returns \cuda_math_formula +\infty \end_cuda_math_formula, when all coordinates are \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - returns NaN, when at least one of the coordinates is NaN and none are infinite. + * + * \note_accuracy_single + */ +extern __device__ __device_builtin__ float rnorm3df(float a, float b, float c) __THROW; + +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the square root of the sum of squares of four coordinates of the argument. + * + * Calculates the length of four dimensional vector in Euclidean space without undue overflow or underflow. + * + * \return Returns the length of the 4D vector + * \cuda_math_formula \sqrt{a^2+b^2+c^2+d^2} \end_cuda_math_formula. + * - In the presence of an exactly infinite coordinate + * \cuda_math_formula +\infty \end_cuda_math_formula + * is returned, even if there are NaNs. + * - returns +0, when all coordinates are \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - returns NaN, when at least one of the coordinates is NaN and none are infinite. + * + * \note_accuracy_single + */ +extern __device__ __device_builtin__ float norm4df(float a, float b, float c, float d) __THROW; + +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate one over the square root of the sum of squares of four coordinates. + * + * Calculates one over the length of four dimension vector in Euclidean space without undue overflow or underflow. + * + * \return Returns one over the length of the 3D vector + * \cuda_math_formula \frac{1}{\sqrt{a^2+b^2+c^2+d^2}} \end_cuda_math_formula. + * - In the presence of an exactly infinite coordinate + * \cuda_math_formula +0 \end_cuda_math_formula + * is returned, even if there are NaNs. + * - returns \cuda_math_formula +\infty \end_cuda_math_formula, when all coordinates are \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - returns NaN, when at least one of the coordinates is NaN and none are infinite. + * + * \note_accuracy_single + */ +extern __device__ __device_builtin__ float rnorm4df(float a, float b, float c, float d) __THROW; + +#if defined(__QNX__) && !defined(_LIBCPP_VERSION) +namespace std { +#endif +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the cube root of the input argument. + * + * Calculate the cube root of \p x, + * \cuda_math_formula x^{1/3} \end_cuda_math_formula. + * + * \return + * Returns + * \cuda_math_formula x^{1/3} \end_cuda_math_formula. + * - cbrt( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - cbrt( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm \infty \end_cuda_math_formula. + * - cbrt(NaN) returns NaN. + * + * \note_accuracy_double + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double cbrt(double x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl cbrt(double x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the cube root of the input argument. + * + * Calculate the cube root of \p x, + * \cuda_math_formula x^{1/3} \end_cuda_math_formula. + * + * \return + * Returns + * \cuda_math_formula x^{1/3} \end_cuda_math_formula. + * - cbrtf( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - cbrtf( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm \infty \end_cuda_math_formula. + * - cbrtf(NaN) returns NaN. + * + * \note_accuracy_single + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float cbrtf(float x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP float __cdecl cbrtf(float x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +#if defined(__QNX__) && !defined(_LIBCPP_VERSION) +} /* std */ +#endif +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate reciprocal cube root function. + * + * Calculate reciprocal cube root function of \p x. + * + * \return + * - rcbrt( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm \infty \end_cuda_math_formula. + * - rcbrt( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - rcbrt(NaN) returns NaN. + * + * \note_accuracy_double + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double rcbrt(double x); + +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate reciprocal cube root function. + * + * Calculate reciprocal cube root function of \p x. + * + * \return + * - rcbrtf( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm \infty \end_cuda_math_formula. + * - rcbrtf( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - rcbrtf(NaN) returns NaN. + * + * \note_accuracy_single + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float rcbrtf(float x); +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the sine of the input argument + * \cuda_math_formula \times \pi \end_cuda_math_formula. + * + * Calculate the sine of \p x + * \cuda_math_formula \times \pi \end_cuda_math_formula + * (measured in radians), + * where \p x is the input argument. + * + * \return + * - sinpi( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - sinpi( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns NaN. + * - sinpi(NaN) returns NaN. + * + * \note_accuracy_double + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double sinpi(double x); +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the sine of the input argument + * \cuda_math_formula \times \pi \end_cuda_math_formula. + * + * Calculate the sine of \p x + * \cuda_math_formula \times \pi \end_cuda_math_formula + * (measured in radians), + * where \p x is the input argument. + * + * \return + * - sinpif( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - sinpif( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns NaN. + * - sinpif(NaN) returns NaN. + * + * \note_accuracy_single + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float sinpif(float x); +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the cosine of the input argument + * \cuda_math_formula \times \pi \end_cuda_math_formula. + * + * Calculate the cosine of \p x + * \cuda_math_formula \times \pi \end_cuda_math_formula + * (measured in radians), + * where \p x is the input argument. + * + * \return + * - cospi( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns 1. + * - cospi( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns NaN. + * - cospi(NaN) returns NaN. + * + * \note_accuracy_double + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double cospi(double x); +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the cosine of the input argument + * \cuda_math_formula \times \pi \end_cuda_math_formula. + * + * Calculate the cosine of \p x + * \cuda_math_formula \times \pi \end_cuda_math_formula + * (measured in radians), + * where \p x is the input argument. + * + * \return + * - cospif( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns 1. + * - cospif( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns NaN. + * - cospif(NaN) returns NaN. + * + * \note_accuracy_single + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float cospif(float x); +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the sine and cosine of the first input argument + * \cuda_math_formula \times \pi \end_cuda_math_formula. + * + * Calculate the sine and cosine of the first input argument, \p x (measured in radians), + * \cuda_math_formula \times \pi \end_cuda_math_formula. The results for sine and cosine are written into the + * second argument, \p sptr, and, respectively, third argument, \p cptr. + * + * \see ::sinpi() and ::cospi(). + * \note_accuracy_double + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ void sincospi(double x, double *sptr, double *cptr); +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the sine and cosine of the first input argument + * \cuda_math_formula \times \pi \end_cuda_math_formula. + * + * Calculate the sine and cosine of the first input argument, \p x (measured in radians), + * \cuda_math_formula \times \pi \end_cuda_math_formula. The results for sine and cosine are written into the + * second argument, \p sptr, and, respectively, third argument, \p cptr. + * + * \see ::sinpif() and ::cospif(). + * \note_accuracy_single + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ void sincospif(float x, float *sptr, float *cptr); + +#if defined(__QNX__) && !defined(_LIBCPP_VERSION) +namespace std { +#endif +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the value of first argument to the power of second argument. + * + * Calculate the value of \p x to the power of \p y. + * + * \return + * - pow( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * , \p y) returns + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * for \p y an odd integer less than 0. + * - pow( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * , \p y) returns + * \cuda_math_formula +\infty \end_cuda_math_formula + * for \p y less than 0 and not an odd integer. + * - pow( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * , \p y) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * for \p y an odd integer greater than 0. + * - pow( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * , \p y) returns +0 for \p y > 0 and not an odd integer. + * - pow(-1, + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns 1. + * - pow(+1, \p y) returns 1 for any \p y, even a NaN. + * - pow(\p x, + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns 1 for any \p x, even a NaN. + * - pow(\p x, \p y) returns a NaN for finite \p x < 0 and finite non-integer \p y. + * - pow(\p x, + * \cuda_math_formula -\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula + * for + * \cuda_math_formula | x | < 1 \end_cuda_math_formula. + * - pow(\p x, + * \cuda_math_formula -\infty \end_cuda_math_formula + * ) returns +0 for + * \cuda_math_formula | x | > 1 \end_cuda_math_formula. + * - pow(\p x, + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns +0 for + * \cuda_math_formula | x | < 1 \end_cuda_math_formula. + * - pow(\p x, + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula + * for + * \cuda_math_formula | x | > 1 \end_cuda_math_formula. + * - pow( + * \cuda_math_formula -\infty \end_cuda_math_formula + * , \p y) returns -0 for \p y an odd integer less than 0. + * - pow( + * \cuda_math_formula -\infty \end_cuda_math_formula + * , \p y) returns +0 for \p y < 0 and not an odd integer. + * - pow( + * \cuda_math_formula -\infty \end_cuda_math_formula + * , \p y) returns + * \cuda_math_formula -\infty \end_cuda_math_formula + * for \p y an odd integer greater than 0. + * - pow( + * \cuda_math_formula -\infty \end_cuda_math_formula + * , \p y) returns + * \cuda_math_formula +\infty \end_cuda_math_formula + * for \p y > 0 and not an odd integer. + * - pow( + * \cuda_math_formula +\infty \end_cuda_math_formula + * , \p y) returns +0 for \p y < 0. + * - pow( + * \cuda_math_formula +\infty \end_cuda_math_formula + * , \p y) returns + * \cuda_math_formula +\infty \end_cuda_math_formula + * for \p y > 0. + * - pow(\p x, \p y) returns NaN if either \p x or \p y or both are NaN and \p x \cuda_math_formula \neq \end_cuda_math_formula +1 and \p y \cuda_math_formula \neq\pm 0 \end_cuda_math_formula. + * + * \note_accuracy_double + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double __cdecl pow(double x, double y) __THROW; +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Break down the input argument into fractional and integral parts. + * + * Break down the argument \p x into fractional and integral parts. The + * integral part is stored in the argument \p iptr. + * Fractional and integral parts are given the same sign as the argument \p x. + * + * \return + * - modf( + * \cuda_math_formula \pm x \end_cuda_math_formula + * , \p iptr) returns a result with the same sign as \p x. + * - modf( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * , \p iptr) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * and stores + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * in the object pointed to by \p iptr. + * - modf(NaN, \p iptr) stores a NaN in the object pointed to by \p iptr and returns a NaN. + * + * \note_accuracy_double + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl modf(double x, double *iptr) __THROW; +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the double-precision floating-point remainder of \p x / \p y. + * + * Calculate the double-precision floating-point remainder of \p x / \p y. + * The floating-point remainder of the division operation \p x / \p y calculated + * by this function is exactly the value x - n*y, where \p n is \p x / \p y with its fractional part truncated. + * The computed value will have the same sign as \p x, and its magnitude will be less than the magnitude of \p y. + * + * \return + * - Returns the floating-point remainder of \p x / \p y. + * - fmod( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * , \p y) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * if \p y is not zero. + * - fmod(\p x, + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns \p x if \p x is finite. + * - fmod(\p x, \p y) returns NaN if \p x is + * \cuda_math_formula \pm\infty \end_cuda_math_formula + * or \p y is zero. + * - If either argument is NaN, NaN is returned. + * + * \note_accuracy_double + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double __cdecl fmod(double x, double y) __THROW; +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Compute double-precision floating-point remainder. + * + * Compute double-precision floating-point remainder \p r of dividing + * \p x by \p y for nonzero \p y. Thus + * \cuda_math_formula r = x - n y \end_cuda_math_formula. + * The value \p n is the integer value nearest + * \cuda_math_formula \frac{x}{y} \end_cuda_math_formula. + * In the case when + * \cuda_math_formula | n -\frac{x}{y} | = \frac{1}{2} \end_cuda_math_formula + * , the + * even \p n value is chosen. + * + * \return + * - remainder(\p x, + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns NaN. + * - remainder( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * , \p y) returns NaN. + * - remainder(\p x, + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns \p x for finite \p x. + * - If either argument is NaN, NaN is returned. + * + * \note_accuracy_double + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double remainder(double x, double y) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl remainder(double x, double y); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Compute single-precision floating-point remainder. + * + * Compute single-precision floating-point remainder \p r of dividing + * \p x by \p y for nonzero \p y. Thus + * \cuda_math_formula r = x - n y \end_cuda_math_formula. + * The value \p n is the integer value nearest + * \cuda_math_formula \frac{x}{y} \end_cuda_math_formula. + * In the case when + * \cuda_math_formula | n -\frac{x}{y} | = \frac{1}{2} \end_cuda_math_formula + * , the + * even \p n value is chosen. + * + * \return + * - remainderf(\p x, + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns NaN. + * - remainderf( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * , \p y) returns NaN. + * - remainderf(\p x, + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns \p x for finite \p x. + * - If either argument is NaN, NaN is returned. + * + * \note_accuracy_single + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float remainderf(float x, float y) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP float __cdecl remainderf(float x, float y); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Compute double-precision floating-point remainder and part of quotient. + * + * Compute a double-precision floating-point remainder in the same way as the + * ::remainder() function. Argument \p quo returns part of quotient upon + * division of \p x by \p y. Value \p quo has the same sign as + * \cuda_math_formula \frac{x}{y} \end_cuda_math_formula + * and may not be the exact quotient but agrees with the exact quotient + * in the low order 3 bits. + * + * \return + * Returns the remainder. + * - remquo(\p x, + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * , \p quo) returns NaN + * and stores an unspecified value in the + * location to which \p quo points. + * - remquo( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * , \p y, \p quo) returns NaN + * and stores an unspecified value in the + * location to which \p quo points. + * - remquo(\p x, \p y, \p quo) returns NaN + * and stores an unspecified value in the + * location to which \p quo points if either of \p x or \p y is NaN. + * - remquo(\p x, + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * , \p quo) returns \p x and stores zero + * in the location to which \p quo points for finite \p x. + * + * \note_accuracy_double + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double remquo(double x, double y, int *quo) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl remquo(double x, double y, int *quo); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Compute single-precision floating-point remainder and part of quotient. + * + * Compute a single-precision floating-point remainder in the same way as the + * ::remainderf() function. Argument \p quo returns part of quotient upon + * division of \p x by \p y. Value \p quo has the same sign as + * \cuda_math_formula \frac{x}{y} \end_cuda_math_formula + * and may not be the exact quotient but agrees with the exact quotient + * in the low order 3 bits. + * + * \return + * Returns the remainder. + * - remquof(\p x, + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * , \p quo) returns NaN + * and stores an unspecified value in the + * location to which \p quo points. + * - remquof( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * , \p y, \p quo) returns NaN + * and stores an unspecified value in the + * location to which \p quo points. + * - remquof(\p x, \p y, \p quo) returns NaN + * and stores an unspecified value in the + * location to which \p quo points if either of \p x or \p y is NaN. + * - remquof(\p x, + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * , \p quo) returns \p x and stores zero + * in the location to which \p quo points for finite \p x. + * + * \note_accuracy_single + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float remquof(float x, float y, int *quo) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP float __cdecl remquof(float x, float y, int *quo); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the value of the Bessel function of the first kind of order 0 for the input argument. + * + * Calculate the value of the Bessel function of the first kind of order 0 for + * the input argument \p x, + * \cuda_math_formula J_0(x) \end_cuda_math_formula. + * + * \return + * Returns the value of the Bessel function of the first kind of order 0. + * - j0( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns +0. + * - j0(NaN) returns NaN. + * + * \note_accuracy_double + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl j0(double x) __THROW; +#if defined(__QNX__) && !defined(_LIBCPP_VERSION) +} /* std */ +#endif + +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the value of the Bessel function of the first kind of order 0 for the input argument. + * + * Calculate the value of the Bessel function of the first kind of order 0 for + * the input argument \p x, + * \cuda_math_formula J_0(x) \end_cuda_math_formula. + * + * \return + * Returns the value of the Bessel function of the first kind of order 0. + * - j0f( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns +0. + * - j0f(NaN) returns NaN. + * + * \note_accuracy_single + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float j0f(float x) __THROW; + +#if defined(__QNX__) && !defined(_LIBCPP_VERSION) +namespace std { +#endif +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the value of the Bessel function of the first kind of order 1 for the input argument. + * + * Calculate the value of the Bessel function of the first kind of order 1 for + * the input argument \p x, + * \cuda_math_formula J_1(x) \end_cuda_math_formula. + * + * \return + * Returns the value of the Bessel function of the first kind of order 1. + * - j1( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - j1( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - j1(NaN) returns NaN. + * + * \note_accuracy_double + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl j1(double x) __THROW; +#if defined(__QNX__) && !defined(_LIBCPP_VERSION) +} /* std */ +#endif + +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the value of the Bessel function of the first kind of order 1 for the input argument. + * + * Calculate the value of the Bessel function of the first kind of order 1 for + * the input argument \p x, + * \cuda_math_formula J_1(x) \end_cuda_math_formula. + * + * \return + * Returns the value of the Bessel function of the first kind of order 1. + * - j1f( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - j1f( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - j1f(NaN) returns NaN. + * + * \note_accuracy_single + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float j1f(float x) __THROW; + +#if defined(__QNX__) && !defined(_LIBCPP_VERSION) +namespace std { +#endif +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the value of the Bessel function of the first kind of order n for the input argument. + * + * Calculate the value of the Bessel function of the first kind of order \p n for + * the input argument \p x, + * \cuda_math_formula J_n(x) \end_cuda_math_formula. + * + * \return + * Returns the value of the Bessel function of the first kind of order \p n. + * - jn(\p n, NaN) returns NaN. + * - jn(\p n, \p x) returns NaN for \p n < 0. + * - jn(\p n, + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns +0. + * + * \note_accuracy_double + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl jn(int n, double x) __THROW; +#if defined(__QNX__) && !defined(_LIBCPP_VERSION) +} /* std */ +#endif + +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the value of the Bessel function of the first kind of order n for the input argument. + * + * Calculate the value of the Bessel function of the first kind of order \p n for + * the input argument \p x, + * \cuda_math_formula J_n(x) \end_cuda_math_formula. + * + * \return + * Returns the value of the Bessel function of the first kind of order \p n. + * - jnf(\p n, NaN) returns NaN. + * - jnf(\p n, \p x) returns NaN for \p n < 0. + * - jnf(\p n, + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns +0. + * + * \note_accuracy_single + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float jnf(int n, float x) __THROW; + +#if defined(__QNX__) && !defined(_LIBCPP_VERSION) +namespace std { +#endif +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the value of the Bessel function of the second kind of order 0 for the input argument. + * + * Calculate the value of the Bessel function of the second kind of order 0 for + * the input argument \p x, + * \cuda_math_formula Y_0(x) \end_cuda_math_formula. + * + * \return + * Returns the value of the Bessel function of the second kind of order 0. + * - y0( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula -\infty \end_cuda_math_formula. + * - y0(\p x) returns NaN for \p x < 0. + * - y0( + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns +0. + * - y0(NaN) returns NaN. + * + * \note_accuracy_double + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl y0(double x) __THROW; +#if defined(__QNX__) && !defined(_LIBCPP_VERSION) +} /* std */ +#endif + +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the value of the Bessel function of the second kind of order 0 for the input argument. + * + * Calculate the value of the Bessel function of the second kind of order 0 for + * the input argument \p x, + * \cuda_math_formula Y_0(x) \end_cuda_math_formula. + * + * \return + * Returns the value of the Bessel function of the second kind of order 0. + * - y0f( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula -\infty \end_cuda_math_formula. + * - y0f(\p x) returns NaN for \p x < 0. + * - y0f( + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns +0. + * - y0f(NaN) returns NaN. + * + * \note_accuracy_single + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float y0f(float x) __THROW; + +#if defined(__QNX__) && !defined(_LIBCPP_VERSION) +namespace std { +#endif +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the value of the Bessel function of the second kind of order 1 for the input argument. + * + * Calculate the value of the Bessel function of the second kind of order 1 for + * the input argument \p x, + * \cuda_math_formula Y_1(x) \end_cuda_math_formula. + * + * \return + * Returns the value of the Bessel function of the second kind of order 1. + * - y1( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula -\infty \end_cuda_math_formula. + * - y1(\p x) returns NaN for \p x < 0. + * - y1( + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns +0. + * - y1(NaN) returns NaN. + * + * \note_accuracy_double + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl y1(double x) __THROW; +#if defined(__QNX__) && !defined(_LIBCPP_VERSION) +} /* std */ +#endif + +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the value of the Bessel function of the second kind of order 1 for the input argument. + * + * Calculate the value of the Bessel function of the second kind of order 1 for + * the input argument \p x, + * \cuda_math_formula Y_1(x) \end_cuda_math_formula. + * + * \return + * Returns the value of the Bessel function of the second kind of order 1. + * - y1f( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula -\infty \end_cuda_math_formula. + * - y1f(\p x) returns NaN for \p x < 0. + * - y1f( + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns +0. + * - y1f(NaN) returns NaN. + * + * \note_accuracy_single + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float y1f(float x) __THROW; + +#if defined(__QNX__) && !defined(_LIBCPP_VERSION) +namespace std { +#endif +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the value of the Bessel function of the second kind of order n for the input argument. + * + * Calculate the value of the Bessel function of the second kind of order \p n for + * the input argument \p x, + * \cuda_math_formula Y_n(x) \end_cuda_math_formula. + * + * \return + * Returns the value of the Bessel function of the second kind of order \p n. + * - yn(\p n, \p x) returns NaN for \p n < 0. + * - yn(\p n, + * \cuda_math_formula \pm 0 \end_cuda_math_formula + *) returns + * \cuda_math_formula -\infty \end_cuda_math_formula. + * - yn(\p n, \p x) returns NaN for \p x < 0. + * - yn(\p n, + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns +0. + * - yn(\p n, NaN) returns NaN. + * + * \note_accuracy_double + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl yn(int n, double x) __THROW; +#if defined(__QNX__) && !defined(_LIBCPP_VERSION) +} /* std */ +#endif + +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the value of the Bessel function of the second kind of order n for the input argument. + * + * Calculate the value of the Bessel function of the second kind of order \p n for + * the input argument \p x, + * \cuda_math_formula Y_n(x) \end_cuda_math_formula. + * + * \return + * Returns the value of the Bessel function of the second kind of order \p n. + * - ynf(\p n, \p x) returns NaN for \p n < 0. + * - ynf(\p n, + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula -\infty \end_cuda_math_formula. + * - ynf(\p n, \p x) returns NaN for \p x < 0. + * - ynf(\p n, + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns +0. + * - ynf(\p n, NaN) returns NaN. + * + * \note_accuracy_single + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float ynf(int n, float x) __THROW; + +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the value of the regular modified cylindrical Bessel function of order 0 for the input argument. + * + * Calculate the value of the regular modified cylindrical Bessel function of order 0 for + * the input argument \p x, + * \cuda_math_formula I_0(x) \end_cuda_math_formula. + * + * \return + * Returns the value of the regular modified cylindrical Bessel function of order 0. + * - cyl_bessel_i0(\cuda_math_formula \pm 0 \end_cuda_math_formula) returns +1. + * - cyl_bessel_i0(\cuda_math_formula \pm\infty \end_cuda_math_formula) returns \cuda_math_formula +\infty \end_cuda_math_formula. + * - cyl_bessel_i0(NaN) returns NaN. + * + * \note_accuracy_double + */ +extern __device__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl cyl_bessel_i0(double x) __THROW; +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the value of the regular modified cylindrical Bessel function of order 0 for the input argument. + * + * Calculate the value of the regular modified cylindrical Bessel function of order 0 for + * the input argument \p x, + * \cuda_math_formula I_0(x) \end_cuda_math_formula. + * + * \return + * Returns the value of the regular modified cylindrical Bessel function of order 0. + * - cyl_bessel_i0f(\cuda_math_formula \pm 0 \end_cuda_math_formula) returns +1. + * - cyl_bessel_i0f(\cuda_math_formula \pm\infty \end_cuda_math_formula) returns \cuda_math_formula +\infty \end_cuda_math_formula. + * - cyl_bessel_i0f(NaN) returns NaN. + * + * \note_accuracy_single + */ +extern __device__ __device_builtin__ float cyl_bessel_i0f(float x) __THROW; + +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the value of the regular modified cylindrical Bessel function of order 1 for the input argument. + * + * Calculate the value of the regular modified cylindrical Bessel function of order 1 for + * the input argument \p x, + * \cuda_math_formula I_1(x) \end_cuda_math_formula. + * + * \return + * Returns the value of the regular modified cylindrical Bessel function of order 1. + * - cyl_bessel_i1(\cuda_math_formula \pm 0 \end_cuda_math_formula) returns \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - cyl_bessel_i1(\cuda_math_formula \pm\infty \end_cuda_math_formula) returns \cuda_math_formula \pm\infty \end_cuda_math_formula. + * - cyl_bessel_i1(NaN) returns NaN. + * + * \note_accuracy_double + */ +extern __device__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl cyl_bessel_i1(double x) __THROW; +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the value of the regular modified cylindrical Bessel function of order 1 for the input argument. + * + * Calculate the value of the regular modified cylindrical Bessel function of order 1 for + * the input argument \p x, + * \cuda_math_formula I_1(x) \end_cuda_math_formula. + * + * \return + * Returns the value of the regular modified cylindrical Bessel function of order 1. + * - cyl_bessel_i1f(\cuda_math_formula \pm 0 \end_cuda_math_formula) returns \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - cyl_bessel_i1f(\cuda_math_formula \pm\infty \end_cuda_math_formula) returns \cuda_math_formula \pm\infty \end_cuda_math_formula. + * - cyl_bessel_i1f(NaN) returns NaN. + * + * \note_accuracy_single + */ +extern __device__ __device_builtin__ float cyl_bessel_i1f(float x) __THROW; + +#if defined(__QNX__) && !defined(_LIBCPP_VERSION) +namespace std { +#endif +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the error function of the input argument. + * + * Calculate the value of the error function for the input argument \p x, + * \cuda_math_formula \frac{2}{\sqrt \pi} \int_0^x e^{-t^2} dt \end_cuda_math_formula. + * + * \return + * - erf( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - erf( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 1 \end_cuda_math_formula. + * - erf(NaN) returns NaN. + * + * \note_accuracy_double + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double erf(double x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl erf(double x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the error function of the input argument. + * + * Calculate the value of the error function for the input argument \p x, + * \cuda_math_formula \frac{2}{\sqrt \pi} \int_0^x e^{-t^2} dt \end_cuda_math_formula. + * + * \return + * - erff( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - erff( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 1 \end_cuda_math_formula. + * - erff(NaN) returns NaN. + * + * \note_accuracy_single + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float erff(float x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP float __cdecl erff(float x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +#if defined(__QNX__) && !defined(_LIBCPP_VERSION) +} /* std */ +#endif + +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the inverse error function of the input argument. + * + * Calculate the inverse error function + * \cuda_math_formula \operatorname{erf}^{-1} \end_cuda_math_formula + * (\p x), of the input argument \p x in the interval [-1, 1]. + * + * \return + * - erfinv( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - erfinv(1) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - erfinv(-1) returns + * \cuda_math_formula -\infty \end_cuda_math_formula. + * - erfinv(\p x) returns NaN for \p x outside [-1, +1]. + * - erfinv(NaN) returns NaN. + * + * \note_accuracy_double + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double erfinv(double x); +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the inverse error function of the input argument. + * + * Calculate the inverse error function + * \cuda_math_formula \operatorname{erf}^{-1} \end_cuda_math_formula + * (\p x), of the input argument \p x in the interval [-1, 1]. + * + * \return + * - erfinvf( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - erfinvf(1) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - erfinvf(-1) returns + * \cuda_math_formula -\infty \end_cuda_math_formula. + * - erfinvf(\p x) returns NaN for \p x outside [-1, +1]. + * - erfinvf(NaN) returns NaN. + * + * \note_accuracy_single + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float erfinvf(float x); + +#if defined(__QNX__) && !defined(_LIBCPP_VERSION) +namespace std { +#endif +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the complementary error function of the input argument. + * + * Calculate the complementary error function of the input argument \p x, + * 1 - erf(\p x). + * + * \return + * - erfc( + * \cuda_math_formula -\infty \end_cuda_math_formula + * ) returns 2. + * - erfc( + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns +0. + * - erfc(NaN) returns NaN. + * + * \note_accuracy_double + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double erfc(double x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl erfc(double x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the complementary error function of the input argument. + * + * Calculate the complementary error function of the input argument \p x, + * 1 - erf(\p x). + * + * \return + * - erfcf( + * \cuda_math_formula -\infty \end_cuda_math_formula + * ) returns 2. + * - erfcf( + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns +0. + * - erfcf(NaN) returns NaN. + * + * \note_accuracy_single + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float erfcf(float x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP float __cdecl erfcf(float x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the natural logarithm of the absolute value of the gamma function of the input argument. + * + * Calculate the natural logarithm of the absolute value of the gamma function of the input argument \p x, namely the value of + * \cuda_math_formula \log_{e}\left|\Gamma(x)\right| \end_cuda_math_formula + * + * \return + * - lgamma(1) returns +0. + * - lgamma(2) returns +0. + * - lgamma(\p x) returns + * \cuda_math_formula +\infty \end_cuda_math_formula + * if \p x + * \cuda_math_formula \leq \end_cuda_math_formula + 0 and \p x is an integer. + * - lgamma( + * \cuda_math_formula -\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - lgamma( + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - lgamma(NaN) returns NaN. + * + * \note_accuracy_double + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double lgamma(double x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl lgamma(double x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +#if defined(__QNX__) && !defined(_LIBCPP_VERSION) +} /* std */ +#endif + +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the inverse complementary error function of the input argument. + * + * Calculate the inverse complementary error function + * \cuda_math_formula \operatorname{erfc}^{-1} \end_cuda_math_formula + * (\p x), of the input argument \p x in the interval [0, 2]. + * + * \return + * - erfcinv( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - erfcinv(2) returns + * \cuda_math_formula -\infty \end_cuda_math_formula. + * - erfcinv(\p x) returns NaN for \p x outside [0, 2]. + * - erfcinv(NaN) returns NaN. + * + * \note_accuracy_double + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double erfcinv(double x); +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the inverse complementary error function of the input argument. + * + * Calculate the inverse complementary error function + * \cuda_math_formula \operatorname{erfc}^{-1} \end_cuda_math_formula + * (\p x), of the input argument \p x in the interval [0, 2]. + * + * \return + * - erfcinvf( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - erfcinvf(2) returns + * \cuda_math_formula -\infty \end_cuda_math_formula. + * - erfcinvf(\p x) returns NaN for \p x outside [0, 2]. + * - erfcinvf(NaN) returns NaN. + * + * \note_accuracy_single + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float erfcinvf(float x); +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the inverse of the standard normal cumulative distribution function. + * + * Calculate the inverse of the standard normal cumulative distribution function for input argument \p x, + * \cuda_math_formula \Phi^{-1}(x) \end_cuda_math_formula. The function is defined for input values in the interval + * \cuda_math_formula (0, 1) \end_cuda_math_formula. + * + * \return + * - normcdfinv( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula -\infty \end_cuda_math_formula. + * - normcdfinv(1) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - normcdfinv(\p x) returns NaN + * if \p x is not in the interval [0,1]. + * - normcdfinv(NaN) returns NaN. + * + * \note_accuracy_double + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double normcdfinv(double x); +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the inverse of the standard normal cumulative distribution function. + * + * Calculate the inverse of the standard normal cumulative distribution function for input argument \p x, + * \cuda_math_formula \Phi^{-1}(x) \end_cuda_math_formula. The function is defined for input values in the interval + * \cuda_math_formula (0, 1) \end_cuda_math_formula. + * + * \return + * - normcdfinvf( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula -\infty \end_cuda_math_formula. + * - normcdfinvf(1) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - normcdfinvf(\p x) returns NaN + * if \p x is not in the interval [0,1]. + * - normcdfinvf(NaN) returns NaN. + * + * \note_accuracy_single + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float normcdfinvf(float x); +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the standard normal cumulative distribution function. + * + * Calculate the cumulative distribution function of the standard normal distribution for input argument \p x, + * \cuda_math_formula \Phi(x) \end_cuda_math_formula. + * + * \return + * - normcdf( + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns 1. + * - normcdf( + * \cuda_math_formula -\infty \end_cuda_math_formula + * ) returns +0. + * - normcdf(NaN) returns NaN. + * + * \note_accuracy_double + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double normcdf(double x); +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the standard normal cumulative distribution function. + * + * Calculate the cumulative distribution function of the standard normal distribution for input argument \p x, + * \cuda_math_formula \Phi(x) \end_cuda_math_formula. + * + * \return + * - normcdff( + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns 1. + * - normcdff( + * \cuda_math_formula -\infty \end_cuda_math_formula + * ) returns +0 + * - normcdff(NaN) returns NaN. + * + * \note_accuracy_single + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float normcdff(float x); +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the scaled complementary error function of the input argument. + * + * Calculate the scaled complementary error function of the input argument \p x, + * \cuda_math_formula e^{x^2}\cdot \operatorname{erfc}(x) \end_cuda_math_formula. + * + * \return + * - erfcx( + * \cuda_math_formula -\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - erfcx( + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns +0. + * - erfcx(NaN) returns NaN. + * + * \note_accuracy_double + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double erfcx(double x); +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the scaled complementary error function of the input argument. + * + * Calculate the scaled complementary error function of the input argument \p x, + * \cuda_math_formula e^{x^2}\cdot \operatorname{erfc}(x) \end_cuda_math_formula. + * + * \return + * - erfcxf( + * \cuda_math_formula -\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - erfcxf( + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns +0. + * - erfcxf(NaN) returns NaN. + * + * \note_accuracy_single + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float erfcxf(float x); + +#if defined(__QNX__) && !defined(_LIBCPP_VERSION) +namespace std { +#endif +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the natural logarithm of the absolute value of the gamma function of the input argument. + * + * Calculate the natural logarithm of the absolute value of the gamma function of the input argument \p x, namely the value of + * \cuda_math_formula \log_{e}\left|\Gamma(x)\right| \end_cuda_math_formula + * + * \return + * - lgammaf(1) returns +0. + * - lgammaf(2) returns +0. + * - lgammaf(\p x) returns + * \cuda_math_formula +\infty \end_cuda_math_formula + * if \p x + * \cuda_math_formula \leq \end_cuda_math_formula + * 0 and \p x is an integer. + * - lgammaf( + * \cuda_math_formula -\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - lgammaf( + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - lgammaf(NaN) returns NaN. + * + * \note_accuracy_single + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float lgammaf(float x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP float __cdecl lgammaf(float x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the gamma function of the input argument. + * + * Calculate the gamma function of the input argument \p x, namely the value of + * \cuda_math_formula \Gamma(x) \end_cuda_math_formula. + * + * \return + * - tgamma( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm \infty \end_cuda_math_formula. + * - tgamma(\p x) returns NaN if \p x < 0 and \p x is an integer. + * - tgamma( + * \cuda_math_formula -\infty \end_cuda_math_formula + * ) returns NaN. + * - tgamma( + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - tgamma(NaN) returns NaN. + * + * \note_accuracy_double + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double tgamma(double x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl tgamma(double x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the gamma function of the input argument. + * + * Calculate the gamma function of the input argument \p x, namely the value of + * \cuda_math_formula \Gamma(x) \end_cuda_math_formula. + * + * \return + * - tgammaf( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm \infty \end_cuda_math_formula. + * - tgammaf(\p x) returns NaN if \p x < 0 and \p x is an integer. + * - tgammaf( + * \cuda_math_formula -\infty \end_cuda_math_formula + * ) returns NaN. + * - tgammaf( + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - tgammaf(NaN) returns NaN. + * + * \note_accuracy_single + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float tgammaf(float x) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP float __cdecl tgammaf(float x); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** \ingroup CUDA_MATH_DOUBLE + * \brief Create value with given magnitude, copying sign of second value. + * + * Create a floating-point value with the magnitude \p x and the sign of \p y. + * + * \return + * - a value with the magnitude of \p x and the sign of \p y. + * - copysign(\p NaN, \p y) returns a \p NaN with the sign of \p y. + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double copysign(double x, double y) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl copysign(double x, double y); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** \ingroup CUDA_MATH_SINGLE + * \brief Create value with given magnitude, copying sign of second value. + * + * Create a floating-point value with the magnitude \p x and the sign of \p y. + * + * \return + * - a value with the magnitude of \p x and the sign of \p y. + * - copysignf(\p NaN, \p y) returns a \p NaN with the sign of \p y. + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float copysignf(float x, float y) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP float __cdecl copysignf(float x, float y); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Return next representable double-precision floating-point value after argument \p x in the direction of \p y. + * + * Calculate the next representable double-precision floating-point value + * following \p x in the direction of \p y. For example, if \p y is greater than \p x, ::nextafter() + * returns the smallest representable number greater than \p x + * + * \return + * - nextafter(\p x, \p y) = \p y if \p x equals \p y. + * - nextafter(\p x, \p y) = \p NaN if either \p x or \p y are \p NaN. + * + * \note_accuracy_double + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double nextafter(double x, double y) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl nextafter(double x, double y); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Return next representable single-precision floating-point value after argument \p x in the direction of \p y. + * + * Calculate the next representable single-precision floating-point value + * following \p x in the direction of \p y. For example, if \p y is greater than \p x, ::nextafterf() + * returns the smallest representable number greater than \p x + * + * \return + * - nextafterf(\p x, \p y) = \p y if \p x equals \p y. + * - nextafterf(\p x, \p y) = \p NaN if either \p x or \p y are \p NaN. + * + * \note_accuracy_single + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float nextafterf(float x, float y) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP float __cdecl nextafterf(float x, float y); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Returns "Not a Number" value. + * + * Return a representation of a quiet NaN. Argument \p tagp selects one of the possible representations. + * + * \return + * - nan(\p tagp) returns NaN. + * + * \note_accuracy_double + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double nan(const char *tagp) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl nan(const char *tagp); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Returns "Not a Number" value + * + * Return a representation of a quiet NaN. Argument \p tagp selects one of the possible representations. + * + * \return + * - nanf(\p tagp) returns NaN. + * + * \note_accuracy_single + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float nanf(const char *tagp) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP float __cdecl nanf(const char *tagp); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +#if defined(__QNX__) && !defined(_LIBCPP_VERSION) +} /* namespace std */ +#endif +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ int __isinff(float) __THROW; +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ int __isnanf(float) __THROW; + + +#if defined(__APPLE__) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ int __isfinited(double) __THROW; +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ int __isfinitef(float) __THROW; +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ int __signbitd(double) __THROW; +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ int __isnand(double) __THROW; +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ int __isinfd(double) __THROW; +#else /* __APPLE__ */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ int __finite(double) __THROW; +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ int __finitef(float) __THROW; +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ int __signbit(double) __THROW; +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ int __isnan(double) __THROW; +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ int __isinf(double) __THROW; +#endif /* __APPLE__ */ + +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ int __signbitf(float) __THROW; + +#if defined(__QNX__) && !defined(_LIBCPP_VERSION) +namespace std { +#endif +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Compute + * \cuda_math_formula x \times y + z \end_cuda_math_formula + * as a single operation. + * + * Compute the value of + * \cuda_math_formula x \times y + z \end_cuda_math_formula + * as a single ternary operation. After computing the value + * to infinite precision, the value is rounded once using round-to-nearest, + * ties-to-even rounding mode. + * + * \return + * Returns the rounded value of + * \cuda_math_formula x \times y + z \end_cuda_math_formula + * as a single operation. + * - fma( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * , + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * , \p z) returns NaN. + * - fma( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * , + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * , \p z) returns NaN. + * - fma(\p x, \p y, + * \cuda_math_formula -\infty \end_cuda_math_formula + * ) returns NaN if + * \cuda_math_formula x \times y \end_cuda_math_formula + * is an exact + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - fma(\p x, \p y, + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns NaN if + * \cuda_math_formula x \times y \end_cuda_math_formula + * is an exact + * \cuda_math_formula -\infty \end_cuda_math_formula. + * - fma(\p x, \p y, \cuda_math_formula \pm 0 \end_cuda_math_formula) returns \cuda_math_formula \pm 0 \end_cuda_math_formula if \cuda_math_formula x \times y \end_cuda_math_formula is exact \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - fma(\p x, \p y, \cuda_math_formula \mp 0 \end_cuda_math_formula) returns \cuda_math_formula +0 \end_cuda_math_formula if \cuda_math_formula x \times y \end_cuda_math_formula is exact \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - fma(\p x, \p y, \p z) returns \cuda_math_formula +0 \end_cuda_math_formula if \cuda_math_formula x \times y + z \end_cuda_math_formula is exactly zero and \cuda_math_formula z \neq 0 \end_cuda_math_formula. + * - If either argument is NaN, NaN is returned. + * + * \note_accuracy_double + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double fma(double x, double y, double z) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP double __cdecl fma(double x, double y, double z); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Compute + * \cuda_math_formula x \times y + z \end_cuda_math_formula + * as a single operation. + * + * Compute the value of + * \cuda_math_formula x \times y + z \end_cuda_math_formula + * as a single ternary operation. After computing the value + * to infinite precision, the value is rounded once using round-to-nearest, + * ties-to-even rounding mode. + * + * \return + * Returns the rounded value of + * \cuda_math_formula x \times y + z \end_cuda_math_formula + * as a single operation. + * - fmaf( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * , + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * , \p z) returns NaN. + * - fmaf( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * , + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * , \p z) returns NaN. + * - fmaf(\p x, \p y, + * \cuda_math_formula -\infty \end_cuda_math_formula + * ) returns NaN if + * \cuda_math_formula x \times y \end_cuda_math_formula + * is an exact + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - fmaf(\p x, \p y, + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns NaN if + * \cuda_math_formula x \times y \end_cuda_math_formula + * is an exact + * \cuda_math_formula -\infty \end_cuda_math_formula. + * - fmaf(\p x, \p y, \cuda_math_formula \pm 0 \end_cuda_math_formula) returns \cuda_math_formula \pm 0 \end_cuda_math_formula if \cuda_math_formula x \times y \end_cuda_math_formula is exact \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - fmaf(\p x, \p y, \cuda_math_formula \mp 0 \end_cuda_math_formula) returns \cuda_math_formula +0 \end_cuda_math_formula if \cuda_math_formula x \times y \end_cuda_math_formula is exact \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - fmaf(\p x, \p y, \p z) returns \cuda_math_formula +0 \end_cuda_math_formula if \cuda_math_formula x \times y + z \end_cuda_math_formula is exactly zero and \cuda_math_formula z \neq 0 \end_cuda_math_formula. + * - If either argument is NaN, NaN is returned. + * + * \note_accuracy_single + */ +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float fmaf(float x, float y, float z) __THROW; +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ __CUDA_MATH_CRTIMP float __cdecl fmaf(float x, float y, float z); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +#if defined(__QNX__) && !defined(_LIBCPP_VERSION) +} /* std */ +#endif + + +/* these are here to avoid warnings on the call graph. + long double is not supported on the device */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ int __signbitl(long double) __THROW; +#if defined(__APPLE__) +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ int __isfinite(long double) __THROW; +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ int __isinf(long double) __THROW; +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ int __isnan(long double) __THROW; +#else /* __APPLE__ */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ int __finitel(long double) __THROW; +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ int __isinfl(long double) __THROW; +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ int __isnanl(long double) __THROW; +#endif /* __APPLE__ */ + +#if defined(_WIN32) && ( defined(_M_AMD64) || defined(_M_ARM64) ) +extern __CUDA_MATH_CRTIMP __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __cdecl acosf(float) __THROW; +extern __CUDA_MATH_CRTIMP __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __cdecl asinf(float) __THROW; +extern __CUDA_MATH_CRTIMP __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __cdecl atanf(float) __THROW; +extern __CUDA_MATH_CRTIMP __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __cdecl atan2f(float, float) __THROW; +extern __CUDA_MATH_CRTIMP __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __cdecl cosf(float) __THROW; +extern __CUDA_MATH_CRTIMP __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __cdecl sinf(float) __THROW; +extern __CUDA_MATH_CRTIMP __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __cdecl tanf(float) __THROW; +extern __CUDA_MATH_CRTIMP __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __cdecl coshf(float) __THROW; +extern __CUDA_MATH_CRTIMP __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __cdecl sinhf(float) __THROW; +extern __CUDA_MATH_CRTIMP __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __cdecl tanhf(float) __THROW; +extern __CUDA_MATH_CRTIMP __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __cdecl expf(float) __THROW; +extern __CUDA_MATH_CRTIMP __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __cdecl logf(float) __THROW; +extern __CUDA_MATH_CRTIMP __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __cdecl log10f(float) __THROW; +extern __CUDA_MATH_CRTIMP __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __cdecl modff(float, float*) __THROW; +extern __CUDA_MATH_CRTIMP __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __cdecl powf(float, float) __THROW; +extern __CUDA_MATH_CRTIMP __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __cdecl sqrtf(float) __THROW; +extern __CUDA_MATH_CRTIMP __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __cdecl ceilf(float) __THROW; +extern __CUDA_MATH_CRTIMP __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __cdecl floorf(float) __THROW; +extern __CUDA_MATH_CRTIMP __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float __cdecl fmodf(float, float) __THROW; +#else /* _WIN32 && (_M_AMD64 || _M_ARM64) */ + +#if defined(__QNX__) && !defined(_LIBCPP_VERSION) +namespace std { +#endif +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the arc cosine of the input argument. + * + * Calculate the principal value of the arc cosine of the input argument \p x. + * + * \return + * Result will be in radians, in the interval [0, + * \cuda_math_formula \pi \end_cuda_math_formula + * ] for \p x inside [-1, +1]. + * - acosf(1) returns +0. + * - acosf(\p x) returns NaN for \p x outside [-1, +1]. + * - acosf(NaN) returns NaN. + * + * \note_accuracy_single + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float acosf(float x) __THROW; +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the arc sine of the input argument. + * + * Calculate the principal value of the arc sine of the input argument \p x. + * + * \return + * Result will be in radians, in the interval [- + * \cuda_math_formula \pi/2 \end_cuda_math_formula + * , + + * \cuda_math_formula \pi/2 \end_cuda_math_formula + * ] for \p x inside [-1, +1]. + * - asinf( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - asinf(\p x) returns NaN for \p x outside [-1, +1]. + * - asinf(NaN) returns NaN. + * + * \note_accuracy_single + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float asinf(float x) __THROW; + +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the arc tangent of the input argument. + * + * Calculate the principal value of the arc tangent of the input argument \p x. + * + * \return + * Result will be in radians, in the interval [- + * \cuda_math_formula \pi/2 \end_cuda_math_formula + * , + + * \cuda_math_formula \pi/2 \end_cuda_math_formula + * ]. + * - atanf( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - atanf( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm \pi \end_cuda_math_formula + * /2. + * - atanf(NaN) returns NaN. + * + * \note_accuracy_single + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float atanf(float x) __THROW; +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the arc tangent of the ratio of first and second input arguments. + * + * Calculate the principal value of the arc tangent of the ratio of first + * and second input arguments \p y / \p x. The quadrant of the result is + * determined by the signs of inputs \p y and \p x. + * + * \return + * Result will be in radians, in the interval [- + * \cuda_math_formula \pi \end_cuda_math_formula + * , + + * \cuda_math_formula \pi \end_cuda_math_formula + * ]. + * - atan2f( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * , -0) returns + * \cuda_math_formula \pm \pi \end_cuda_math_formula. + * - atan2f( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * , +0) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - atan2f( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * , \p x) returns + * \cuda_math_formula \pm \pi \end_cuda_math_formula + * for \p x < 0. + * - atan2f( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * , \p x) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * for \p x > 0. + * - atan2f(\p y, + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula -\pi \end_cuda_math_formula + * /2 for \p y < 0. + * - atan2f(\p y, + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pi \end_cuda_math_formula + * /2 for \p y > 0. + * - atan2f( + * \cuda_math_formula \pm y \end_cuda_math_formula + * , + * \cuda_math_formula -\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm \pi \end_cuda_math_formula + * for finite \p y > 0. + * - atan2f( + * \cuda_math_formula \pm y \end_cuda_math_formula + * , + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * for finite \p y > 0. + * - atan2f( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * , \p x) returns + * \cuda_math_formula \pm \pi \end_cuda_math_formula + * /2 for finite \p x. + * - atan2f( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * , + * \cuda_math_formula -\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 3\pi \end_cuda_math_formula + * /4. + * - atan2f( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * , + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm \pi \end_cuda_math_formula + * /4. + * - If either argument is NaN, NaN is returned. + * + * \note_accuracy_single + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float atan2f(float y, float x) __THROW; +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the cosine of the input argument. + * + * Calculate the cosine of the input argument \p x (measured in radians). + * + * \return + * - cosf( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns 1. + * - cosf( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns NaN. + * - cosf(NaN) returns NaN. + * + * \note_accuracy_single + * \note_fastmath + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float cosf(float x) __THROW; +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the sine of the input argument. + * + * Calculate the sine of the input argument \p x (measured in radians). + * + * \return + * - sinf( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - sinf( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns NaN. + * - sinf(NaN) returns NaN. + * + * \note_accuracy_single + * \note_fastmath + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float sinf(float x) __THROW; +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the tangent of the input argument. + * + * Calculate the tangent of the input argument \p x (measured in radians). + * + * \return + * - tanf( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - tanf( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns NaN. + * - tanf(NaN) returns NaN. + * + * \note_accuracy_single + * \note_fastmath + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float tanf(float x) __THROW; +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the hyperbolic cosine of the input argument. + * + * Calculate the hyperbolic cosine of the input argument \p x. + * + * \return + * - coshf( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns 1. + * - coshf( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - coshf(NaN) returns NaN. + * + * \note_accuracy_single + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float coshf(float x) __THROW; +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the hyperbolic sine of the input argument. + * + * Calculate the hyperbolic sine of the input argument \p x. + * + * \return + * - sinhf( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - sinhf( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm \infty \end_cuda_math_formula. + * - sinhf(NaN) returns NaN. + * + * \note_accuracy_single + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float sinhf(float x) __THROW; +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the hyperbolic tangent of the input argument. + * + * Calculate the hyperbolic tangent of the input argument \p x. + * + * \return + * - tanhf( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - tanhf( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 1 \end_cuda_math_formula. + * - tanhf(NaN) returns NaN. + * + * \note_accuracy_single + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float tanhf(float x) __THROW; +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the natural logarithm of the input argument. + * + * Calculate the natural logarithm of the input argument \p x. + * + * \return + * - logf( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula -\infty \end_cuda_math_formula. + * - logf(1) returns +0. + * - logf(\p x) returns NaN for \p x < 0. + * - logf( + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - logf(NaN) returns NaN. + * + * \note_accuracy_single + * \note_fastmath + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float logf(float x) __THROW; +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the base + * \cuda_math_formula e \end_cuda_math_formula + * exponential of the input argument. + * + * Calculate + * \cuda_math_formula e^x \end_cuda_math_formula +, + * the base + * \cuda_math_formula e \end_cuda_math_formula + * exponential of the input argument \p x. + * + * \return + * - expf( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns 1. + * - expf( + * \cuda_math_formula -\infty \end_cuda_math_formula + * ) returns +0. + * - expf( + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - expf(NaN) returns NaN. + * + * \note_accuracy_single + * \note_fastmath + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float expf(float x) __THROW; +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the base 10 logarithm of the input argument. + * + * Calculate the base 10 logarithm of the input argument \p x. + * + * \return + * - log10f( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula -\infty \end_cuda_math_formula. + * - log10f(1) returns +0. + * - log10f(\p x) returns NaN for \p x < 0. + * - log10f( + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - log10f(NaN) returns NaN. + * + * \note_accuracy_single + * \note_fastmath + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float log10f(float x) __THROW; +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Break down the input argument into fractional and integral parts. + * + * Break down the argument \p x into fractional and integral parts. The integral part is stored in the argument \p iptr. + * Fractional and integral parts are given the same sign as the argument \p x. + * + * \return + * - modff( + * \cuda_math_formula \pm x \end_cuda_math_formula + * , \p iptr) returns a result with the same sign as \p x. + * - modff( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * , \p iptr) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * and stores + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * in the object pointed to by \p iptr. + * - modff(NaN, \p iptr) stores a NaN in the object pointed to by \p iptr and returns a NaN. + * + * \note_accuracy_single + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float modff(float x, float *iptr) __THROW; +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the value of first argument to the power of second argument. + * + * Calculate the value of \p x to the power of \p y. + * + * \return + * - powf( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * , \p y) returns + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * for \p y an odd integer less than 0. + * - powf( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * , \p y) returns + * \cuda_math_formula +\infty \end_cuda_math_formula + * for \p y less than 0 and not an odd integer. + * - powf( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * , \p y) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * for \p y an odd integer greater than 0. + * - powf( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * , \p y) returns +0 for \p y > 0 and not an odd integer. + * - powf(-1, + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns 1. + * - powf(+1, \p y) returns 1 for any \p y, even a NaN. + * - powf(\p x, + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns 1 for any \p x, even a NaN. + * - powf(\p x, \p y) returns a NaN for finite \p x < 0 and finite non-integer \p y. + * - powf(\p x, + * \cuda_math_formula -\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula + * for + * \cuda_math_formula | x | < 1 \end_cuda_math_formula. + * - powf(\p x, + * \cuda_math_formula -\infty \end_cuda_math_formula + * ) returns +0 for + * \cuda_math_formula | x | > 1 \end_cuda_math_formula. + * - powf(\p x, + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns +0 for + * \cuda_math_formula | x | < 1 \end_cuda_math_formula. + * - powf(\p x, + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula + * for + * \cuda_math_formula | x | > 1 \end_cuda_math_formula. + * - powf( + * \cuda_math_formula -\infty \end_cuda_math_formula + * , \p y) returns -0 for \p y an odd integer less than 0. + * - powf( + * \cuda_math_formula -\infty \end_cuda_math_formula + * , \p y) returns +0 for \p y < 0 and not an odd integer. + * - powf( + * \cuda_math_formula -\infty \end_cuda_math_formula + * , \p y) returns + * \cuda_math_formula -\infty \end_cuda_math_formula + * for \p y an odd integer greater than 0. + * - powf( + * \cuda_math_formula -\infty \end_cuda_math_formula + * , \p y) returns + * \cuda_math_formula +\infty \end_cuda_math_formula + * for \p y > 0 and not an odd integer. + * - powf( + * \cuda_math_formula +\infty \end_cuda_math_formula + * , \p y) returns +0 for \p y < 0. + * - powf( + * \cuda_math_formula +\infty \end_cuda_math_formula + * , \p y) returns + * \cuda_math_formula +\infty \end_cuda_math_formula + * for \p y > 0. + * - powf(\p x, \p y) returns NaN if either \p x or \p y or both are NaN and \p x \cuda_math_formula \neq \end_cuda_math_formula +1 and \p y \cuda_math_formula \neq\pm 0 \end_cuda_math_formula. + * + * \note_accuracy_single + * \note_fastmath + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float powf(float x, float y) __THROW; +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the square root of the input argument. + * + * Calculate the nonnegative square root of \p x, + * \cuda_math_formula \sqrt{x} \end_cuda_math_formula. + * + * \return + * Returns + * \cuda_math_formula \sqrt{x} \end_cuda_math_formula. + * - sqrtf( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - sqrtf( + * \cuda_math_formula +\infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula +\infty \end_cuda_math_formula. + * - sqrtf(\p x) returns NaN if \p x is less than 0. + * - sqrtf(NaN) returns NaN. + * + * \note_accuracy_single + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float sqrtf(float x) __THROW; +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate ceiling of the input argument. + * + * Compute the smallest integer value not less than \p x. + * + * \return + * Returns + * \cuda_math_formula \lceil x \rceil \end_cuda_math_formula + * expressed as a floating-point number. + * - ceilf( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - ceilf( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm \infty \end_cuda_math_formula. + * - ceilf(NaN) returns NaN. + * + * \note_accuracy_single + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float ceilf(float x) __THROW; +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the largest integer less than or equal to \p x. + * + * Calculate the largest integer value which is less than or equal to \p x. + * + * \return + * Returns + * \cuda_math_formula \lfloor x \rfloor \end_cuda_math_formula + * expressed as a floating-point number. + * - floorf( + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm \infty \end_cuda_math_formula. + * - floorf( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * ) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula. + * - floorf(NaN) returns NaN. + * + * \note_accuracy_single + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float floorf(float x) __THROW; +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the floating-point remainder of \p x / \p y. + * + * Calculate the floating-point remainder of \p x / \p y. + * The floating-point remainder of the division operation \p x / \p y calculated + * by this function is exactly the value x - n*y, where \p n is \p x / \p y with its fractional part truncated. + * The computed value will have the same sign as \p x, and its magnitude will be less than the magnitude of \p y. + * \return + * - Returns the floating-point remainder of \p x / \p y. + * - fmodf( + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * , \p y) returns + * \cuda_math_formula \pm 0 \end_cuda_math_formula + * if \p y is not zero. + * - fmodf(\p x, + * \cuda_math_formula \pm \infty \end_cuda_math_formula + * ) returns \p x if \p x is finite. + * - fmodf(\p x, \p y) returns NaN if \p x is + * \cuda_math_formula \pm\infty \end_cuda_math_formula + * or \p y is zero. + * - If either argument is NaN, NaN is returned. + * + * \note_accuracy_single + */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float fmodf(float x, float y) __THROW; +#if defined(__QNX__) +/* redeclare some builtins that QNX uses */ +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float _FLog(float, int); +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float _FCosh(float, float); +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float _FSinh(float, float); +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float _FSinx(float, unsigned int, int); +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ int _FDsign(float); +extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ int _Dsign(double); +#endif +#if defined(__QNX__) && !defined(_LIBCPP_VERSION) +} /* std */ +#endif +#endif /* _WIN32 && (_M_AMD64 || _M_ARM64) */ + +} + +#if !defined(__CUDACC_RTC__) +#include +#include + +#ifndef __CUDA_INTERNAL_SKIP_CPP_HEADERS__ +#include +#include +#endif /* __CUDA_INTERNAL_SKIP_CPP_HEADERS__ */ +#endif /* __CUDACC_RTC__ */ + +/******************************************************************************* +* * +* * +* * +*******************************************************************************/ + +#if defined(__CUDACC_RTC__) + +__DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ int signbit(float x); +__DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ int signbit(double x); +__DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ int signbit(long double x); + +__DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ int isfinite(float x); +__DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ int isfinite(double x); +__DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ int isfinite(long double x); + +__DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ int isnan(float x); +__DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ int isnan(double x); +__DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ int isnan(long double x); + +__DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ int isinf(float x); +__DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ int isinf(double x); +__DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ int isinf(long double x); + +#elif defined(__GNUC__) + +#undef signbit +#undef isfinite +#undef isnan +#undef isinf + +#if defined(__APPLE__) + +__forceinline__ __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ int signbit(float x); +__forceinline__ __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ int signbit(double x); +__forceinline__ __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ int signbit(long double x); + +__forceinline__ __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ int isfinite(float x); +__forceinline__ __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ int isfinite(double x); +__forceinline__ __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ int isfinite(long double x); + +__forceinline__ __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ int isnan(double x) throw(); +#if !defined(_LIBCPP_VERSION) || _LIBCPP_VERSION < 7000 +__forceinline__ __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ int isnan(float x); +__forceinline__ __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ int isnan(long double x); +#else /* !(!defined(_LIBCPP_VERSION) || _LIBCPP_VERSION < 7000) */ +template +__DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ bool __libcpp_isnan(T) _NOEXCEPT; +inline _LIBCPP_INLINE_VISIBILITY __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ bool isnan(float x) _NOEXCEPT; +inline _LIBCPP_INLINE_VISIBILITY __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ bool isnan(long double x) _NOEXCEPT; +#endif /* !defined(_LIBCPP_VERSION) || _LIBCPP_VERSION < 7000 */ + +__forceinline__ __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ int isinf(double x) throw(); +#if !defined(_LIBCPP_VERSION) || _LIBCPP_VERSION < 7000 +__forceinline__ __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ int isinf(float x); +__forceinline__ __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ int isinf(long double x); +#else /* !(!defined(_LIBCPP_VERSION) || _LIBCPP_VERSION < 7000) */ +template +__cudart_builtin__ __DEVICE_FUNCTIONS_DECL__ bool __libcpp_isinf(T) _NOEXCEPT; +inline _LIBCPP_INLINE_VISIBILITY __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ bool isinf(float x) _NOEXCEPT; +inline _LIBCPP_INLINE_VISIBILITY __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ bool isinf(long double x) _NOEXCEPT; +#endif /* !defined(_LIBCPP_VERSION) || _LIBCPP_VERSION < 7000 */ + +#else /* __APPLE__ */ + +#if ((defined _GLIBCXX_MATH_H) && _GLIBCXX_MATH_H) && (__cplusplus >= 201103L) +#if !defined(_NVHPC_CUDA) +namespace std { +__DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ constexpr bool signbit(float x); +__DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ constexpr bool signbit(double x); +__DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ constexpr bool signbit(long double x); +__DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ constexpr bool isfinite(float x); +__DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ constexpr bool isfinite(double x); +__DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ constexpr bool isfinite(long double x); +__DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ constexpr bool isnan(float x); +/* GCC 6.1 uses ::isnan(double x) for isnan(double x) if the condition is true */ +#if _GLIBCXX_HAVE_OBSOLETE_ISNAN && !_GLIBCXX_NO_OBSOLETE_ISINF_ISNAN_DYNAMIC +__DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ int isnan(double x) throw(); +#else /* !(_GLIBCXX_HAVE_OBSOLETE_ISNAN && !_GLIBCXX_NO_OBSOLETE_ISINF_ISNAN_DYNAMIC) */ +__DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ constexpr bool isnan(double x); +#endif /* _GLIBCXX_HAVE_OBSOLETE_ISNAN && !_GLIBCXX_NO_OBSOLETE_ISINF_ISNAN_DYNAMIC */ +__DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ constexpr bool isnan(long double x); +__DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ constexpr bool isinf(float x); +/* GCC 6.1 uses ::isinf(double x) for isinf(double x) if the condition is true. */ +#if _GLIBCXX_HAVE_OBSOLETE_ISINF && !_GLIBCXX_NO_OBSOLETE_ISINF_ISNAN_DYNAMIC +__DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ int isinf(double x) throw(); +#else /* !(_GLIBCXX_HAVE_OBSOLETE_ISINF && !_GLIBCXX_NO_OBSOLETE_ISINF_ISNAN_DYNAMIC) */ +__DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ constexpr bool isinf(double x); +#endif /* _GLIBCXX_HAVE_OBSOLETE_ISINF && !_GLIBCXX_NO_OBSOLETE_ISINF_ISNAN_DYNAMIC */ +__DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ constexpr bool isinf(long double x); +} +#endif + +#else /* !(((defined _GLIBCXX_MATH_H) && _GLIBCXX_MATH_H) && (__cplusplus >= 201103L)) */ + +#if defined(__QNX__) +#if (__QNX__) && !defined(_LIBCPP_VERSION) +/* QNX defines functions in std, need to declare them here */ +namespace std { +__DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ bool signbit(float x); +__DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ bool signbit(double x); +__DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ bool signbit(long double x); +} +#else +static __inline__ __DEVICE_FUNCTIONS_DECL__ bool signbit(const float x); +static __inline__ __DEVICE_FUNCTIONS_DECL__ bool signbit(const double x); +static __inline__ __DEVICE_FUNCTIONS_DECL__ bool signbit(const long double x); +#endif +static __inline__ __DEVICE_FUNCTIONS_DECL__ bool isfinite(const float a); +static __inline__ __DEVICE_FUNCTIONS_DECL__ bool isfinite(const double a); +static __inline__ __DEVICE_FUNCTIONS_DECL__ bool isfinite(const long double a); +static __inline__ __DEVICE_FUNCTIONS_DECL__ bool isnan(const float a); +static __inline__ __DEVICE_FUNCTIONS_DECL__ bool isnan(const double a); +static __inline__ __DEVICE_FUNCTIONS_DECL__ bool isnan(const long double a); +static __inline__ __DEVICE_FUNCTIONS_DECL__ bool isinf(const float a); +static __inline__ __DEVICE_FUNCTIONS_DECL__ bool isinf(const double a); +static __inline__ __DEVICE_FUNCTIONS_DECL__ bool isinf(const long double a); +#else /* ! __QNX__ */ +__forceinline__ __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ int signbit(const float x); +#if defined(__ICC) +__forceinline__ __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ int signbit(const double x) throw(); +#else /* !__ICC */ +__forceinline__ __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ int signbit(const double x); +#endif /* __ICC */ +__forceinline__ __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ int signbit(const long double x); + +__forceinline__ __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ int isfinite(const float x); +#if defined(__ICC) +__forceinline__ __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ int isfinite(const double x) throw(); +#else /* !__ICC */ +__forceinline__ __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ int isfinite(const double x); +#endif /* __ICC */ +__forceinline__ __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ int isfinite(const long double x); + +#if (defined(__ANDROID__) || defined(__HORIZON__)) && _LIBCPP_VERSION >= 8000 +template +__DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ bool __libcpp_isnan(T) _NOEXCEPT; +inline _LIBCPP_INLINE_VISIBILITY __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ bool isnan(float x) _NOEXCEPT; +#else /* !((defined(__ANDROID__) || defined(__HORIZON__)) && _LIBCPP_VERSION >= 8000) */ +__forceinline__ __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ int isnan(float x); +#endif /* (defined(__ANDROID__) || defined(__HORIZON__)) && _LIBCPP_VERSION >= 8000 */ +#if defined(__ANDROID__) || defined(__HORIZON__) +#if !defined(_LIBCPP_VERSION) +__forceinline__ +#endif /* !defined(_LIBCPP_VERSION) */ +#if _LIBCPP_VERSION >= 7000 +#ifdef _LIBCPP_PREFERRED_OVERLOAD +_LIBCPP_INLINE_VISIBILITY _LIBCPP_PREFERRED_OVERLOAD __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ bool isnan(double x) _NOEXCEPT; +#endif /* _LIBCPP_PREFERRED_OVERLOAD */ +#else /* _LIBCPP_VERSION < 7000 */ +__DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ int isnan(double x); +#endif /* _LIBCPP_VERSION >= 7000 */ +#else /* !(__ANDROID__ || __HORIZON__) */ +__forceinline__ __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ int isnan(double x) throw(); +#endif /* __ANDROID__ */ +#if (defined(__ANDROID__) || defined(__HORIZON__)) && _LIBCPP_VERSION >= 8000 +inline _LIBCPP_INLINE_VISIBILITY __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ bool isnan(long double x) _NOEXCEPT; +#else /* !( (defined(__ANDROID__) || defined(__HORIZON__)) && _LIBCPP_VERSION >= 8000) */ +__forceinline__ __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ int isnan(long double x); +#endif /* (defined(__ANDROID__) || defined(__HORIZON__)) && _LIBCPP_VERSION >= 8000 */ + +#if (defined(__ANDROID__) || defined(__HORIZON__)) && _LIBCPP_VERSION >= 8000 +static __inline__ __cudart_builtin__ __DEVICE_FUNCTIONS_DECL__ unsigned __FLOAT_BITS(float __f); +static __inline__ __cudart_builtin__ __DEVICE_FUNCTIONS_DECL__ unsigned long long __DOUBLE_BITS(double __f); +template +__cudart_builtin__ __DEVICE_FUNCTIONS_DECL__ bool __libcpp_isinf(T) _NOEXCEPT; +inline _LIBCPP_INLINE_VISIBILITY __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ bool isinf(float x) _NOEXCEPT; +#else /* !( (defined(__ANDROID__) || defined(__HORIZON__)) && _LIBCPP_VERSION >= 8000) */ +__forceinline__ __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ int isinf(float x); +#endif /* (defined(__ANDROID__) || defined(__HORIZON__)) && _LIBCPP_VERSION >= 8000 */ + +#if defined(__ANDROID__) || defined(__HORIZON__) +#if !defined(_LIBCPP_VERSION) +__forceinline__ +#endif /* !defined(_LIBCPP_VERSION) */ +#if _LIBCPP_VERSION >= 7000 +#ifdef _LIBCPP_PREFERRED_OVERLOAD +_LIBCPP_INLINE_VISIBILITY _LIBCPP_PREFERRED_OVERLOAD __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ bool isinf(double x) _NOEXCEPT; +#endif /* _LIBCPP_PREFERRED_OVERLOAD */ +#else /* _LIBCPP_VERSION < 7000 */ +__DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ int isinf(double x); +#endif /* _LIBCPP_VERSION >= 7000 */ +#else /* ! (__ANDROID__ || __HORIZON__) */ +__forceinline__ __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ int isinf(double x) throw(); +#endif /* __ANDROID__ || __HORIZON__ */ +#if (defined(__ANDROID__) || defined(__HORIZON__)) && _LIBCPP_VERSION >= 8000 +inline _LIBCPP_INLINE_VISIBILITY __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ bool isinf(long double x) _NOEXCEPT; +#else /* !( (defined(__ANDROID__) || defined(__HORIZON__)) && _LIBCPP_VERSION >= 8000) */ +__forceinline__ __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ int isinf(long double x); +#endif /* (defined(__ANDROID__) || defined(__HORIZON__)) && _LIBCPP_VERSION >= 8000 */ +#endif /* __QNX__ */ + +#endif /* ((defined _GLIBCXX_MATH_H) && _GLIBCXX_MATH_H) && (__cplusplus >= 201103L) */ +#endif /* __APPLE__ */ + +#if !defined(_LIBCPP_VERSION) +#if defined(__clang__) +#if __has_include() +#define __NV_GLIBCXX_VERSION 40800 +#endif /* __has_include() */ +#endif /* __clang__ */ + +#if !defined(__NV_GLIBCXX_VERSION) +#define __NV_GLIBCXX_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) +#endif /* !__NV_GLIBCXX_VERSION */ +#endif /* !defined(_LIBCPP_VERSION) */ + +#if !defined(__HORIZON__) || !defined(_LIBCPP_VERSION) || _LIBCPP_VERSION < 3800 +#if defined(__arm__) && !defined(_STLPORT_VERSION) && !_GLIBCXX_USE_C99 +#if !defined(__ANDROID__) || (defined(__NV_GLIBCXX_VERSION) && __NV_GLIBCXX_VERSION < 40800) + +#if defined(__QNX__) +/* QNX defines functions in std, need to declare them here */ +namespace std { +__DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ long long int abs (long long int a); +} +#elif defined(__HORIZON__) +#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) +#pragma GCC system_header +#endif +_LIBCPP_BEGIN_NAMESPACE_STD +__DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ long long int abs (long long int a) throw(); +_LIBCPP_END_NAMESPACE_STD +#else +static __inline__ __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ long long int abs(long long int a); +#endif /* __QNX__ || __HORIZON__*/ + +#endif /* !__ANDROID__ || (defined(__NV_GLIBCXX_VERSION) && __NV_GLIBCXX_VERSION < 40800) */ +#endif /* __arm__ && !_STLPORT_VERSION && !_GLIBCXX_USE_C99 */ +#endif /* !defined(__HORIZON__) || !defined(_LIBCPP_VERSION) || _LIBCPP_VERSION < 3800 */ + +#if defined(__NV_GLIBCXX_VERSION) && __NV_GLIBCXX_VERSION < 40800 && !defined(__ibmxl__) + +#if !defined(_STLPORT_VERSION) +namespace __gnu_cxx +{ +#endif /* !_STLPORT_VERSION */ + +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ long long int abs(long long int a); + +#if !defined(_STLPORT_VERSION) +} +#endif /* !_STLPORT_VERSION */ + +#endif /* defined(__NV_GLIBCXX_VERSION) && __NV_GLIBCXX_VERSION < 40800 && !__ibmxl__ */ + +namespace std +{ + template extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ T __pow_helper(T, int); + template extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ T __cmath_power(T, unsigned int); +} + +using std::abs; +using std::fabs; +using std::ceil; +using std::floor; +using std::sqrt; +#if !defined(_LIBCPP_VERSION) || _LIBCPP_VERSION < 3800 +using std::pow; +#endif /* !defined(_LIBCPP_VERSION) || _LIBCPP_VERSION < 3800 */ +using std::log; +using std::log10; +using std::fmod; +using std::modf; +using std::exp; +using std::frexp; +using std::ldexp; +using std::asin; +using std::sin; +using std::sinh; +using std::acos; +using std::cos; +using std::cosh; +using std::atan; +using std::atan2; +using std::tan; +using std::tanh; + +#elif defined(_WIN32) + +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ __CUDA_MATH_CRTIMP double __cdecl _hypot(double x, double y); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ __CUDA_MATH_CRTIMP float __cdecl _hypotf(float x, float y); + +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +static __inline__ __DEVICE_FUNCTIONS_DECL__ int signbit(long double a); +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +#if _MSC_VER >= 1900 +#define __SIGNBIT_THROW throw() +#else +#define __SIGNBIT_THROW +#endif +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ bool signbit(long double) __SIGNBIT_THROW; +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ __device_builtin__ __CUDA_MATH_CRTIMP int _ldsign(long double); +#undef __SIGNBIT_THROW +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ + +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +#define __RETURN_TYPE int +/** + * \ingroup CUDA_MATH_DOUBLE + * + * \brief Return the sign bit of the input. + * + * Determine whether the floating-point value \p a is negative. + * + * \return + * Reports the sign bit of all values including infinities, zeros, and NaNs. + * - With Visual Studio 2013 host compiler: __RETURN_TYPE is 'bool'. Returns + * true if and only if \p a is negative. + * - With other host compilers: __RETURN_TYPE is 'int'. Returns a + * nonzero value if and only if \p a is negative. + */ +static __inline__ __DEVICE_FUNCTIONS_DECL__ __RETURN_TYPE signbit(double a); +#undef __RETURN_TYPE +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +#define __RETURN_TYPE bool +#if _MSC_VER >= 1900 +#define __SIGNBIT_THROW throw() +#else +#define __SIGNBIT_THROW +#endif +/** + * \ingroup CUDA_MATH_DOUBLE + * + * \brief Return the sign bit of the input. + * + * Determine whether the floating-point value \p a is negative. + * + * \return + * Reports the sign bit of all values including infinities, zeros, and NaNs. + * - With Visual Studio 2013 host compiler: __RETURN_TYPE is 'bool'. Returns + * true if and only if \p a is negative. + * - With other host compilers: __RETURN_TYPE is 'int'. Returns a + * nonzero value if and only if \p a is negative. + */ +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ __RETURN_TYPE signbit(double) __SIGNBIT_THROW; +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ __device_builtin__ __CUDA_MATH_CRTIMP int _dsign(double); +#undef __RETURN_TYPE +#undef __SIGNBIT_THROW +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ + +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +#define __RETURN_TYPE int +/** + * \ingroup CUDA_MATH_SINGLE + * + * \brief Return the sign bit of the input. + * + * Determine whether the floating-point value \p a is negative. + * + * \return + * Reports the sign bit of all values including infinities, zeros, and NaNs. + * - With Visual Studio 2013 host compiler: __RETURN_TYPE is 'bool'. Returns + * true if and only if \p a is negative. + * - With other host compilers: __RETURN_TYPE is 'int'. Returns a nonzero value + * if and only if \p a is negative. + */ +static __inline__ __DEVICE_FUNCTIONS_DECL__ __RETURN_TYPE signbit(float a); +#undef __RETURN_TYPE +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +#define __RETURN_TYPE bool +#if _MSC_VER >= 1900 +#define __SIGNBIT_THROW throw() +#else +#define __SIGNBIT_THROW +#endif +/** + * \ingroup CUDA_MATH_SINGLE + * + * \brief Return the sign bit of the input. + * + * Determine whether the floating-point value \p a is negative. + * + * \return + * Reports the sign bit of all values including infinities, zeros, and NaNs. + * - With Visual Studio 2013 host compiler: __RETURN_TYPE is 'bool'. Returns + * true if and only if \p a is negative. + * - With other host compilers: __RETURN_TYPE is 'int'. Returns a nonzero value + * if and only if \p a is negative. + */ +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ __RETURN_TYPE signbit(float) __SIGNBIT_THROW; +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ __device_builtin__ __CUDA_MATH_CRTIMP int _fdsign(float); +#undef __RETURN_TYPE +#undef __SIGNBIT_THROW +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ + +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +static __inline__ __DEVICE_FUNCTIONS_DECL__ int isinf(long double a); +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +static __inline__ __DEVICE_FUNCTIONS_DECL__ bool isinf(long double a); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ + +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +#define __RETURN_TYPE int +/** + * \ingroup CUDA_MATH_DOUBLE + * + * \brief Determine whether argument is infinite. + * + * Determine whether the floating-point value \p a is an infinite value + * (positive or negative). + * \return + * - With Visual Studio 2013 host compiler: Returns true if and only + * if \p a is an infinite value. + * - With other host compilers: Returns a nonzero value if and only + * if \p a is an infinite value. + */ +static __inline__ __DEVICE_FUNCTIONS_DECL__ __RETURN_TYPE isinf(double a); +#undef __RETURN_TYPE +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +#define __RETURN_TYPE bool +/** + * \ingroup CUDA_MATH_DOUBLE + * + * \brief Determine whether argument is infinite. + * + * Determine whether the floating-point value \p a is an infinite value + * (positive or negative). + * \return + * - With Visual Studio 2013 host compiler: Returns true if and only + * if \p a is an infinite value. + * - With other host compilers: Returns a nonzero value if and only + * if \p a is an infinite value. + */ +static __inline__ __DEVICE_FUNCTIONS_DECL__ __RETURN_TYPE isinf(double a); +#undef __RETURN_TYPE +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ + +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +#define __RETURN_TYPE int +/** + * \ingroup CUDA_MATH_SINGLE + * + * \brief Determine whether argument is infinite. + * + * Determine whether the floating-point value \p a is an infinite value + * (positive or negative). + * + * \return + * - With Visual Studio 2013 host compiler: __RETURN_TYPE is 'bool'. Returns + * true if and only if \p a is an infinite value. + * - With other host compilers: __RETURN_TYPE is 'int'. Returns a nonzero + * value if and only if \p a is an infinite value. + */ +static __inline__ __DEVICE_FUNCTIONS_DECL__ __RETURN_TYPE isinf(float a); +#undef __RETURN_TYPE +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +#define __RETURN_TYPE bool +/** + * \ingroup CUDA_MATH_SINGLE + * + * \brief Determine whether argument is infinite. + * + * Determine whether the floating-point value \p a is an infinite value + * (positive or negative). + * + * \return + * - With Visual Studio 2013 host compiler: __RETURN_TYPE is 'bool'. Returns + * true if and only if \p a is an infinite value. + * - With other host compilers: __RETURN_TYPE is 'int'. Returns a nonzero + * value if and only if \p a is an infinite value. + */ +static __inline__ __DEVICE_FUNCTIONS_DECL__ __RETURN_TYPE isinf(float a); +#undef __RETURN_TYPE +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ + +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +static __inline__ __DEVICE_FUNCTIONS_DECL__ int isnan(long double a); +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +static __inline__ __DEVICE_FUNCTIONS_DECL__ bool isnan(long double a); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ + +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +#define __RETURN_TYPE int +/** + * \ingroup CUDA_MATH_DOUBLE + * + * \brief Determine whether argument is a NaN. + * + * Determine whether the floating-point value \p a is a NaN. + * \return + * - With Visual Studio 2013 host compiler: __RETURN_TYPE is 'bool'. + * Returns true if and only if \p a is a NaN value. + * - With other host compilers: __RETURN_TYPE is 'int'. Returns a + * nonzero value if and only if \p a is a NaN value. + */ +static __inline__ __DEVICE_FUNCTIONS_DECL__ __RETURN_TYPE isnan(double a); +#undef __RETURN_TYPE +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +#define __RETURN_TYPE bool +/** + * \ingroup CUDA_MATH_DOUBLE + * + * \brief Determine whether argument is a NaN. + * + * Determine whether the floating-point value \p a is a NaN. + * \return + * - With Visual Studio 2013 host compiler: __RETURN_TYPE is 'bool'. + * Returns true if and only if \p a is a NaN value. + * - With other host compilers: __RETURN_TYPE is 'int'. Returns a + * nonzero value if and only if \p a is a NaN value. + */ +static __inline__ __DEVICE_FUNCTIONS_DECL__ __RETURN_TYPE isnan(double a); +#undef __RETURN_TYPE +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ + +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +#define __RETURN_TYPE int +/** + * \ingroup CUDA_MATH_SINGLE + * + * + * \brief Determine whether argument is a NaN. + * + * Determine whether the floating-point value \p a is a NaN. + * \return + * - With Visual Studio 2013 host compiler: __RETURN_TYPE is 'bool'. + * Returns true if and only if \p a is a NaN value. + * - With other host compilers: __RETURN_TYPE is 'int'. Returns a + * nonzero value if and only if \p a is a NaN value. + */ +static __inline__ __DEVICE_FUNCTIONS_DECL__ __RETURN_TYPE isnan(float a); +#undef __RETURN_TYPE +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +#define __RETURN_TYPE bool +/** + * \ingroup CUDA_MATH_SINGLE + * + * + * \brief Determine whether argument is a NaN. + * + * Determine whether the floating-point value \p a is a NaN. + * \return + * - With Visual Studio 2013 host compiler: __RETURN_TYPE is 'bool'. + * Returns true if and only if \p a is a NaN value. + * - With other host compilers: __RETURN_TYPE is 'int'. Returns a + * nonzero value if and only if \p a is a NaN value. + */ +static __inline__ __DEVICE_FUNCTIONS_DECL__ __RETURN_TYPE isnan(float a); +#undef __RETURN_TYPE +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ + +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +static __inline__ __DEVICE_FUNCTIONS_DECL__ int isfinite(long double a); +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +static __inline__ __DEVICE_FUNCTIONS_DECL__ bool isfinite(long double a); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ + +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +#define __RETURN_TYPE int +/** + * \ingroup CUDA_MATH_DOUBLE + * + * \brief Determine whether argument is finite. + * + * Determine whether the floating-point value \p a is a finite value + * (zero, subnormal, or normal and not infinity or NaN). + * + * \return + * - With Visual Studio 2013 host compiler: __RETURN_TYPE is 'bool'. Returns + * true if and only if \p a is a finite value. + * - With other host compilers: __RETURN_TYPE is 'int'. Returns + * a nonzero value if and only if \p a is a finite value. + */ +static __inline__ __DEVICE_FUNCTIONS_DECL__ __RETURN_TYPE isfinite(double a); +#undef __RETURN_TYPE +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +#define __RETURN_TYPE bool +/** + * \ingroup CUDA_MATH_DOUBLE + * + * \brief Determine whether argument is finite. + * + * Determine whether the floating-point value \p a is a finite value + * (zero, subnormal, or normal and not infinity or NaN). + * + * \return + * - With Visual Studio 2013 host compiler: __RETURN_TYPE is 'bool'. Returns + * true if and only if \p a is a finite value. + * - With other host compilers: __RETURN_TYPE is 'int'. Returns + * a nonzero value if and only if \p a is a finite value. + */ +static __inline__ __DEVICE_FUNCTIONS_DECL__ __RETURN_TYPE isfinite(double a); +#undef __RETURN_TYPE +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ + +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +#define __RETURN_TYPE int +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Determine whether argument is finite. + * + * Determine whether the floating-point value \p a is a finite value + * (zero, subnormal, or normal and not infinity or NaN). + * + * \return + * - With Visual Studio 2013 host compiler: __RETURN_TYPE is 'bool'. Returns + * true if and only if \p a is a finite value. + * - With other host compilers: __RETURN_TYPE is 'int'. Returns + * a nonzero value if and only if \p a is a finite value. + */ +static __inline__ __DEVICE_FUNCTIONS_DECL__ __RETURN_TYPE isfinite(float a); +#undef __RETURN_TYPE +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +#define __RETURN_TYPE bool +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Determine whether argument is finite. + * + * Determine whether the floating-point value \p a is a finite value + * (zero, subnormal, or normal and not infinity or NaN). + * + * \return + * - With Visual Studio 2013 host compiler: __RETURN_TYPE is 'bool'. Returns + * true if and only if \p a is a finite value. + * - With other host compilers: __RETURN_TYPE is 'int'. Returns + * a nonzero value if and only if \p a is a finite value. + */ +static __inline__ __DEVICE_FUNCTIONS_DECL__ __RETURN_TYPE isfinite(float a); +#undef __RETURN_TYPE +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ + +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +template extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ T _Pow_int(T, int); +/** + * \ingroup CUDA_MATH_INT + * \brief Calculate the absolute value of the input \p long \p long \p int argument. + * + * Calculate the absolute value of the input argument \p a. + * + * \return + * Returns the absolute value of the input argument. + * - abs(\p LLONG_MIN) is \p Undefined + */ +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ long long int abs(long long int a); +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +template extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ T _Pow_int(T, int) throw(); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ long long int abs(long long int) throw(); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ + +#endif /* __CUDACC_RTC__ */ + +#if __cplusplus >= 201103L +#define __NV_NOEXCEPT noexcept +#else /* !__cplusplus >= 201103L */ +#define __NV_NOEXCEPT throw() +#endif /* __cplusplus >= 201103L */ + +#if defined(_LIBCPP_VERSION) && defined(_LIBCPP_BEGIN_NAMESPACE_STD) && !defined(_STLPORT_VERSION) +#if defined(__clang__) +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wc++11-extensions" +#endif /* __clang__ */ +#if _LIBCPP_VERSION < 3800 +_LIBCPP_BEGIN_NAMESPACE_STD +#endif /* _LIBCPP_VERSION < 3800 */ +#elif defined(__GNUC__) && !defined(_STLPORT_VERSION) +namespace std { +#endif /* defined(_LIBCPP_VERSION) && defined(_LIBCPP_BEGIN_NAMESPACE_STD) && !defined(_STLPORT_VERSION) || + __GNUC__ && !_STLPORT_VERSION */ + +#if defined(__CUDACC_RTC__) || defined(__GNUC__) + +#if defined(__CUDACC_RTC__) || \ + (defined(__NV_GLIBCXX_VERSION) && __NV_GLIBCXX_VERSION >= 40800) || \ + defined(__ibmxl__) +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ long long int abs(long long int); +#endif /* __CUDACC__RTC__ || + (defined(__NV_GLIBCXX_VERSION) && __NV_GLIBCXX_VERSION >= 40800) || + __ibmxl__ */ + +#endif /* __CUDACC_RTC__ || __GNUC__ */ + +#if defined(__CUDACC_RTC__) || \ + (!defined(_MSC_VER) || _MSC_VER < 1800) && \ + (!defined(_LIBCPP_VERSION) || (_LIBCPP_VERSION < 1101)) +/** + * \ingroup CUDA_MATH_INT + * \brief Calculate the absolute value of the input \p long \p int argument. + * + * Calculate the absolute value of the input argument \p a. + * + * \return + * Returns the absolute value of the input argument. + * - abs(\p LONG_MIN) is \p Undefined + */ +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ long int __cdecl abs(long int a); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl abs(float); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ double __cdecl abs(double); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl fabs(float); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl ceil(float); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl floor(float); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl sqrt(float); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl pow(float, float); + +#if !defined(__QNX__) + +#if defined(__GNUC__) && __cplusplus >= 201103L && !defined(_LIBCPP_VERSION) +template +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ +typename __gnu_cxx::__promote_2<_Tp, _Up>::__type pow(_Tp, _Up); +#else /* !(defined(__GNUC__) && __cplusplus >= 201103L && !defined(_LIBCPP_VERSION)) */ +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl pow(float, int); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ double __cdecl pow(double, int); +#endif /* defined(__GNUC__) && __cplusplus >= 201103L && !defined(_LIBCPP_VERSION) */ + +#endif /* !defined(__QNX__) */ + +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl log(float); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl log10(float); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl fmod(float, float); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl modf(float, float*); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl exp(float); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl frexp(float, int*); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl ldexp(float, int); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl asin(float); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl sin(float); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl sinh(float); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl acos(float); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl cos(float); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl cosh(float); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl atan(float); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl atan2(float, float); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl tan(float); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl tanh(float); +#else /* __CUDACC_RTC__ || + (!defined(_MSC_VER) || _MSC_VER < 1800) && + (!defined(_LIBCPP_VERSION) || (_LIBCPP_VERSION < 1101)) */ +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ long int __cdecl abs(long int) throw(); +#if defined(_LIBCPP_VERSION) +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ long long int __cdecl abs(long long int) throw(); +#endif /* defined(_LIBCPP_VERSION) */ +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl abs(float) throw(); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ double __cdecl abs(double) throw(); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl fabs(float) throw(); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl ceil(float) throw(); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl floor(float) throw(); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl sqrt(float) throw(); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl pow(float, float) throw(); +#if defined(_LIBCPP_VERSION) +#if (defined (__ANDROID__) || defined(__HORIZON__)) && (_LIBCPP_VERSION >= 9000) +template +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ +#if _LIBCPP_VERSION >= 14000 +typename std::__enable_if_t +#else /* _LIBCPP_VERSION < 14000 */ +typename std::_EnableIf +#endif /* _LIBCPP_VERSION >= 14000 */ +< + std::is_arithmetic<_A1>::value && + std::is_arithmetic<_A2>::value, + std::__promote<_A1, _A2> +>::type pow(_A1 __lcpp_x, _A2 __lcpp_y) __NV_NOEXCEPT; +#elif (defined(__APPLE__) && __clang_major__ >= 7) || _LIBCPP_VERSION >= 3800 || defined(__QNX__) +template +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ +#if defined(__QNX__) && (_LIBCPP_VERSION >= 160000) +typename std::__enable_if_t < +#elif _LIBCPP_VERSION >= 13000 +typename std::enable_if < +#else /* #defined(__QNX__) && (_LIBCPP_VERSION >= 160000) */ +typename std::__lazy_enable_if < +#endif /* _LIBCPP_VERSION >= 160000 */ + std::is_arithmetic<_Tp>::value && std::is_arithmetic<_Up>::value, + std::__promote<_Tp, _Up> +>::type pow(_Tp __x, _Up __y) __NV_NOEXCEPT; +#else /* !((__APPLE__ && __clang_major__ >= 7) || _LIBCPP_VERSION >= 3800) */ +template +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ +typename enable_if < + std::is_arithmetic<_Tp>::value && std::is_arithmetic<_Up>::value, + typename std::__promote<_Tp, _Up>::type +>::type pow(_Tp __x, _Up __y) __NV_NOEXCEPT; +#endif /* (__APPLE__ && __clang_major__ >= 7) || _LIBCPP_VERSION >= 3800 */ +#else /* !defined(_LIBCPP_VERSION) */ +#if !(defined(__GNUC__) && __cplusplus >= 201103L) +#if (defined(_MSC_VER) && (_MSC_VER >= 1928)) && !(defined __CUDA_INTERNAL_SKIP_CPP_HEADERS__) +template && ::std:: is_arithmetic_v<_Ty2>, int> > [[nodiscard]] __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ ::std:: _Common_float_type_t<_Ty1, _Ty2> __cdecl pow(_Ty1 _Left, _Ty2 _Right) noexcept; +#else +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl pow(float, int) throw(); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ double __cdecl pow(double, int) throw(); +#endif /* (defined(_MSC_VER) && (_MSC_VER >= 1928)) && !(defined __CUDA_INTERNAL_SKIP_CPP_HEADERS__) */ +#endif /* !(defined(__GNUC__) && __cplusplus >= 201103L) */ +#endif /* defined(_LIBCPP_VERSION) */ +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl log(float) throw(); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl log10(float) throw(); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl fmod(float, float) throw(); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl modf(float, float*) throw(); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl exp(float) throw(); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl frexp(float, int*) throw(); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl ldexp(float, int) throw(); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl asin(float) throw(); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl sin(float) throw(); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl sinh(float) throw(); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl acos(float) throw(); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl cos(float) throw(); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl cosh(float) throw(); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl atan(float) throw(); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl atan2(float, float) throw(); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl tan(float) throw(); +extern __DEVICE_FUNCTIONS_DECL__ __cudart_builtin__ float __cdecl tanh(float) throw(); +#endif /* __CUDACC_RTC__ || + (!defined(_MSC_VER) || _MSC_VER < 1800) && + (!defined(_LIBCPP_VERSION) || (_LIBCPP_VERSION < 1101)) */ + +#if defined(_LIBCPP_VERSION) && defined(_LIBCPP_END_NAMESPACE_STD) && !defined(_STLPORT_VERSION) +#if _LIBCPP_VERSION < 3800 +_LIBCPP_END_NAMESPACE_STD +#endif /* _LIBCPP_VERSION < 3800 */ +#if defined(__clang__) +#pragma clang diagnostic pop +#endif /* __clang__ */ +#elif defined(__GNUC__) && !defined(_STLPORT_VERSION) +} +#endif /* defined(_LIBCPP_VERSION) && defined(_LIBCPP_BEGIN_NAMESPACE_STD) && !defined(_STLPORT_VERSION) || + __GNUC__ && !_STLPORT_VERSION */ + +#undef __DEVICE_FUNCTIONS_DECL__ +#undef __NV_NOEXCEPT + +#if defined(__CUDACC_RTC__) +#define __MATH_FUNCTIONS_DECL__ __host__ __device__ +#define __MATH_FUNCTIONS_DEVICE_DECL__ __device__ +#else /* __CUDACC_RTC__ */ +#define __MATH_FUNCTIONS_DECL__ static inline __host__ __device__ __cudart_builtin__ +#define __MATH_FUNCTIONS_DEVICE_DECL__ static inline __device__ __cudart_builtin__ +#endif /* __CUDACC_RTC__ */ + +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +#if defined(__QNX__) || (defined(_LIBCPP_VERSION) && _LIBCPP_VERSION >= 3800) +#if defined(__QNX__) && (!defined(_LIBCPP_VERSION) || _LIBCPP_VERSION < 8000) +#if defined(_LIBCPP_VERSION) +#define __NV_NOEXCEPT _NOEXCEPT +_LIBCPP_BEGIN_NAMESPACE_STD +#else +#define __NV_NOEXCEPT +namespace std { +__host__ __device__ __cudart_builtin__ int ilogbf(float a); +#endif +#else /* !(defined(__QNX__) && (!defined(_LIBCPP_VERSION) || _LIBCPP_VERSION < 8000)) */ +#define __NV_NOEXCEPT _NOEXCEPT +#endif /* defined(__QNX__) && (!defined(_LIBCPP_VERSION) || _LIBCPP_VERSION < 8000) */ +__host__ __device__ __cudart_builtin__ float logb(float a) __NV_NOEXCEPT; +__host__ __device__ __cudart_builtin__ int ilogb(float a) __NV_NOEXCEPT; + +__host__ __device__ __cudart_builtin__ float scalbn(float a, int b) __NV_NOEXCEPT; +__host__ __device__ __cudart_builtin__ float scalbln(float a, long int b) __NV_NOEXCEPT; +__host__ __device__ __cudart_builtin__ float exp2(float a) __NV_NOEXCEPT; +__host__ __device__ __cudart_builtin__ float expm1(float a) __NV_NOEXCEPT; +__host__ __device__ __cudart_builtin__ float log2(float a) __NV_NOEXCEPT; +__host__ __device__ __cudart_builtin__ float log1p(float a) __NV_NOEXCEPT; +__host__ __device__ __cudart_builtin__ float acosh(float a) __NV_NOEXCEPT; +__host__ __device__ __cudart_builtin__ float asinh(float a) __NV_NOEXCEPT; +__host__ __device__ __cudart_builtin__ float atanh(float a) __NV_NOEXCEPT; +__host__ __device__ __cudart_builtin__ float hypot(float a, float b) __NV_NOEXCEPT; +__host__ __device__ __cudart_builtin__ float cbrt(float a) __NV_NOEXCEPT; +__host__ __device__ __cudart_builtin__ float erf(float a) __NV_NOEXCEPT; +__host__ __device__ __cudart_builtin__ float erfc(float a) __NV_NOEXCEPT; +__host__ __device__ __cudart_builtin__ float lgamma(float a) __NV_NOEXCEPT; +__host__ __device__ __cudart_builtin__ float tgamma(float a) __NV_NOEXCEPT; +__host__ __device__ __cudart_builtin__ float copysign(float a, float b) __NV_NOEXCEPT; +__host__ __device__ __cudart_builtin__ float nextafter(float a, float b) __NV_NOEXCEPT; +__host__ __device__ __cudart_builtin__ float remainder(float a, float b) __NV_NOEXCEPT; +__host__ __device__ __cudart_builtin__ float remquo(float a, float b, int *quo) __NV_NOEXCEPT; +__host__ __device__ __cudart_builtin__ float round(float a) __NV_NOEXCEPT; +__host__ __device__ __cudart_builtin__ long int lround(float a) __NV_NOEXCEPT; +__host__ __device__ __cudart_builtin__ long long int llround(float a) __NV_NOEXCEPT; +__host__ __device__ __cudart_builtin__ float trunc(float a) __NV_NOEXCEPT; +__host__ __device__ __cudart_builtin__ float rint(float a) __NV_NOEXCEPT; +__host__ __device__ __cudart_builtin__ long int lrint(float a) __NV_NOEXCEPT; +__host__ __device__ __cudart_builtin__ long long int llrint(float a) __NV_NOEXCEPT; +__host__ __device__ __cudart_builtin__ float nearbyint(float a) __NV_NOEXCEPT; +__host__ __device__ __cudart_builtin__ float fdim(float a, float b) __NV_NOEXCEPT; +__host__ __device__ __cudart_builtin__ float fma(float a, float b, float c) __NV_NOEXCEPT; +__host__ __device__ __cudart_builtin__ float fmax(float a, float b) __NV_NOEXCEPT; +__host__ __device__ __cudart_builtin__ float fmin(float a, float b) __NV_NOEXCEPT; +#if defined(__QNX__) && (!defined(_LIBCPP_VERSION) || _LIBCPP_VERSION < 8000) +#if defined(_LIBCPP_VERSION) +_LIBCPP_END_NAMESPACE_STD +using _VSTD::logb; +using _VSTD::ilogb; +using _VSTD::scalbn; +using _VSTD::scalbln; +using _VSTD::exp2; +using _VSTD::expm1; +using _VSTD::log2; +using _VSTD::log1p; +using _VSTD::acosh; +using _VSTD::asinh; +using _VSTD::atanh; +using _VSTD::hypot; +using _VSTD::cbrt; +using _VSTD::erf; +using _VSTD::erfc; +using _VSTD::lgamma; +using _VSTD::tgamma; +using _VSTD::copysign; +using _VSTD::nextafter; +using _VSTD::remainder; +using _VSTD::remquo; +using _VSTD::round; +using _VSTD::lround; +using _VSTD::llround; +using _VSTD::trunc; +using _VSTD::rint; +using _VSTD::lrint; +using _VSTD::llrint; +using _VSTD::nearbyint; +using _VSTD::fdim; +using _VSTD::fma; +using _VSTD::fmax; +using _VSTD::fmin; +#else +} +#endif +#endif /* defined(__QNX__) && (!defined(_LIBCPP_VERSION) || _LIBCPP_VERSION < 8000) */ +#undef __NV_NOEXCEPT +#else /* !(defined(__QNX__ ) || (defined(_LIBCPP_VERSION) && _LIBCPP_VERSION >= 3800)) */ +#if ((defined _GLIBCXX_MATH_H) && _GLIBCXX_MATH_H) && (__cplusplus >= 201103L) +namespace std { +__host__ __device__ __cudart_builtin__ constexpr float logb(float a); +__host__ __device__ __cudart_builtin__ constexpr int ilogb(float a); +__host__ __device__ __cudart_builtin__ constexpr float scalbn(float a, int b); +__host__ __device__ __cudart_builtin__ constexpr float scalbln(float a, long int b); +__host__ __device__ __cudart_builtin__ constexpr float exp2(float a); +__host__ __device__ __cudart_builtin__ constexpr float expm1(float a); +__host__ __device__ __cudart_builtin__ constexpr float log2(float a); +__host__ __device__ __cudart_builtin__ constexpr float log1p(float a); +__host__ __device__ __cudart_builtin__ constexpr float acosh(float a); +__host__ __device__ __cudart_builtin__ constexpr float asinh(float a); +__host__ __device__ __cudart_builtin__ constexpr float atanh(float a); +__host__ __device__ __cudart_builtin__ constexpr float hypot(float a, float b); +__host__ __device__ __cudart_builtin__ constexpr float cbrt(float a); +__host__ __device__ __cudart_builtin__ constexpr float erf(float a); +__host__ __device__ __cudart_builtin__ constexpr float erfc(float a); +__host__ __device__ __cudart_builtin__ constexpr float lgamma(float a); +__host__ __device__ __cudart_builtin__ constexpr float tgamma(float a); +__host__ __device__ __cudart_builtin__ constexpr float copysign(float a, float b); +__host__ __device__ __cudart_builtin__ constexpr float nextafter(float a, float b); +__host__ __device__ __cudart_builtin__ constexpr float remainder(float a, float b); +__host__ __device__ __cudart_builtin__ float remquo(float a, float b, int *quo); +__host__ __device__ __cudart_builtin__ constexpr float round(float a); +__host__ __device__ __cudart_builtin__ constexpr long int lround(float a); +__host__ __device__ __cudart_builtin__ constexpr long long int llround(float a); +__host__ __device__ __cudart_builtin__ constexpr float trunc(float a); +__host__ __device__ __cudart_builtin__ constexpr float rint(float a); +__host__ __device__ __cudart_builtin__ constexpr long int lrint(float a); +__host__ __device__ __cudart_builtin__ constexpr long long int llrint(float a); +__host__ __device__ __cudart_builtin__ constexpr float nearbyint(float a); +__host__ __device__ __cudart_builtin__ constexpr float fdim(float a, float b); +__host__ __device__ __cudart_builtin__ constexpr float fma(float a, float b, float c); +__host__ __device__ __cudart_builtin__ constexpr float fmax(float a, float b); +__host__ __device__ __cudart_builtin__ constexpr float fmin(float a, float b); +} +#else /* !(((defined _GLIBCXX_MATH_H) && _GLIBCXX_MATH_H) && (__cplusplus >= 201103L)) */ +__MATH_FUNCTIONS_DECL__ float logb(float a); + +__MATH_FUNCTIONS_DECL__ int ilogb(float a); + +__MATH_FUNCTIONS_DECL__ float scalbn(float a, int b); + +__MATH_FUNCTIONS_DECL__ float scalbln(float a, long int b); + +__MATH_FUNCTIONS_DECL__ float exp2(float a); + +__MATH_FUNCTIONS_DECL__ float expm1(float a); + +__MATH_FUNCTIONS_DECL__ float log2(float a); + +__MATH_FUNCTIONS_DECL__ float log1p(float a); + +__MATH_FUNCTIONS_DECL__ float acosh(float a); + +__MATH_FUNCTIONS_DECL__ float asinh(float a); + +__MATH_FUNCTIONS_DECL__ float atanh(float a); + +__MATH_FUNCTIONS_DECL__ float hypot(float a, float b); + +__MATH_FUNCTIONS_DECL__ float cbrt(float a); + +__MATH_FUNCTIONS_DECL__ float erf(float a); + +__MATH_FUNCTIONS_DECL__ float erfc(float a); + +__MATH_FUNCTIONS_DECL__ float lgamma(float a); + +__MATH_FUNCTIONS_DECL__ float tgamma(float a); + +__MATH_FUNCTIONS_DECL__ float copysign(float a, float b); + +__MATH_FUNCTIONS_DECL__ float nextafter(float a, float b); + +__MATH_FUNCTIONS_DECL__ float remainder(float a, float b); + +__MATH_FUNCTIONS_DECL__ float remquo(float a, float b, int *quo); + +__MATH_FUNCTIONS_DECL__ float round(float a); + +__MATH_FUNCTIONS_DECL__ long int lround(float a); + +__MATH_FUNCTIONS_DECL__ long long int llround(float a); + +__MATH_FUNCTIONS_DECL__ float trunc(float a); + +__MATH_FUNCTIONS_DECL__ float rint(float a); + +__MATH_FUNCTIONS_DECL__ long int lrint(float a); + +__MATH_FUNCTIONS_DECL__ long long int llrint(float a); + +__MATH_FUNCTIONS_DECL__ float nearbyint(float a); + +__MATH_FUNCTIONS_DECL__ float fdim(float a, float b); + +__MATH_FUNCTIONS_DECL__ float fma(float a, float b, float c); + +__MATH_FUNCTIONS_DECL__ float fmax(float a, float b); + +__MATH_FUNCTIONS_DECL__ float fmin(float a, float b); +#endif /* ((defined _GLIBCXX_MATH_H) && _GLIBCXX_MATH_H) && (__cplusplus >= 201103L) */ +#endif /* defined(__QNX__) || (defined(_LIBCPP_VERSION) && _LIBCPP_VERSION >= 3800) */ +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +extern __host__ __device__ __cudart_builtin__ float __cdecl logb(float) throw(); +extern __host__ __device__ __cudart_builtin__ int __cdecl ilogb(float) throw(); +extern __host__ __device__ __cudart_builtin__ float __cdecl scalbn(float, float) throw(); +extern __host__ __device__ __cudart_builtin__ float __cdecl scalbln(float, long int) throw(); +extern __host__ __device__ __cudart_builtin__ float __cdecl exp2(float) throw(); +extern __host__ __device__ __cudart_builtin__ float __cdecl expm1(float) throw(); +extern __host__ __device__ __cudart_builtin__ float __cdecl log2(float) throw(); +extern __host__ __device__ __cudart_builtin__ float __cdecl log1p(float) throw(); +extern __host__ __device__ __cudart_builtin__ float __cdecl acosh(float) throw(); +extern __host__ __device__ __cudart_builtin__ float __cdecl asinh(float) throw(); +extern __host__ __device__ __cudart_builtin__ float __cdecl atanh(float) throw(); +extern __host__ __device__ __cudart_builtin__ float __cdecl hypot(float, float) throw(); +extern __host__ __device__ __cudart_builtin__ float __cdecl cbrt(float) throw(); +extern __host__ __device__ __cudart_builtin__ float __cdecl erf(float) throw(); +extern __host__ __device__ __cudart_builtin__ float __cdecl erfc(float) throw(); +extern __host__ __device__ __cudart_builtin__ float __cdecl lgamma(float) throw(); +extern __host__ __device__ __cudart_builtin__ float __cdecl tgamma(float) throw(); +extern __host__ __device__ __cudart_builtin__ float __cdecl copysign(float, float) throw(); +extern __host__ __device__ __cudart_builtin__ float __cdecl nextafter(float, float) throw(); +extern __host__ __device__ __cudart_builtin__ float __cdecl remainder(float, float) throw(); +extern __host__ __device__ __cudart_builtin__ float __cdecl remquo(float, float, int *) throw(); +extern __host__ __device__ __cudart_builtin__ float __cdecl round(float) throw(); +extern __host__ __device__ __cudart_builtin__ long int __cdecl lround(float) throw(); +extern __host__ __device__ __cudart_builtin__ long long int __cdecl llround(float) throw(); +extern __host__ __device__ __cudart_builtin__ float __cdecl trunc(float) throw(); +extern __host__ __device__ __cudart_builtin__ float __cdecl rint(float) throw(); +extern __host__ __device__ __cudart_builtin__ long int __cdecl lrint(float) throw(); +extern __host__ __device__ __cudart_builtin__ long long int __cdecl llrint(float) throw(); +extern __host__ __device__ __cudart_builtin__ float __cdecl nearbyint(float) throw(); +extern __host__ __device__ __cudart_builtin__ float __cdecl fdim(float, float) throw(); +extern __host__ __device__ __cudart_builtin__ float __cdecl fma(float, float, float) throw(); +extern __host__ __device__ __cudart_builtin__ float __cdecl fmax(float, float) throw(); +extern __host__ __device__ __cudart_builtin__ float __cdecl fmin(float, float) throw(); +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ + +__MATH_FUNCTIONS_DECL__ float exp10(const float a); + +__MATH_FUNCTIONS_DECL__ float rsqrt(const float a); + +__MATH_FUNCTIONS_DECL__ float rcbrt(const float a); + +__MATH_FUNCTIONS_DECL__ float sinpi(const float a); + +__MATH_FUNCTIONS_DECL__ float cospi(const float a); + +__MATH_FUNCTIONS_DECL__ void sincospi(const float a, float *const sptr, float *const cptr); + +__MATH_FUNCTIONS_DECL__ void sincos(const float a, float *const sptr, float *const cptr); + +__MATH_FUNCTIONS_DECL__ float j0(const float a); + +__MATH_FUNCTIONS_DECL__ float j1(const float a); + +__MATH_FUNCTIONS_DECL__ float jn(const int n, const float a); + +__MATH_FUNCTIONS_DECL__ float y0(const float a); + +__MATH_FUNCTIONS_DECL__ float y1(const float a); + +__MATH_FUNCTIONS_DECL__ float yn(const int n, const float a); + +__MATH_FUNCTIONS_DEVICE_DECL__ float cyl_bessel_i0(const float a); + +__MATH_FUNCTIONS_DEVICE_DECL__ float cyl_bessel_i1(const float a); + +__MATH_FUNCTIONS_DECL__ float erfinv(const float a); + +__MATH_FUNCTIONS_DECL__ float erfcinv(const float a); + +__MATH_FUNCTIONS_DECL__ float normcdfinv(const float a); + +__MATH_FUNCTIONS_DECL__ float normcdf(const float a); + +__MATH_FUNCTIONS_DECL__ float erfcx(const float a); + +__MATH_FUNCTIONS_DECL__ double copysign(const double a, const float b); + +__MATH_FUNCTIONS_DECL__ double copysign(const float a, const double b); + +/** + * \ingroup CUDA_MATH_INT + * \brief Calculate the minimum value of the input \p unsigned \p int arguments. + * + * Calculate the minimum value of the arguments \p a and \p b. + */ +__MATH_FUNCTIONS_DECL__ unsigned int min(const unsigned int a, const unsigned int b); + +/** + * \ingroup CUDA_MATH_INT + * \brief Calculate the minimum value of the input \p int and \p unsigned \p int arguments. + * + * Calculate the minimum value of the arguments \p a and \p b, perform integer promotion first. + */ +__MATH_FUNCTIONS_DECL__ unsigned int min(const int a, const unsigned int b); + +/** + * \ingroup CUDA_MATH_INT + * \brief Calculate the minimum value of the input \p unsigned \p int and \p int arguments. + * + * Calculate the minimum value of the arguments \p a and \p b, perform integer promotion first. + */ +__MATH_FUNCTIONS_DECL__ unsigned int min(const unsigned int a, const int b); + +/** + * \ingroup CUDA_MATH_INT + * \brief Calculate the minimum value of the input \p long \p int arguments. + * + * Calculate the minimum value of the arguments \p a and \p b. + */ +__MATH_FUNCTIONS_DECL__ long int min(const long int a, const long int b); + +/** + * \ingroup CUDA_MATH_INT + * \brief Calculate the minimum value of the input \p unsigned \p long \p int arguments. + * + * Calculate the minimum value of the arguments \p a and \p b. + */ +__MATH_FUNCTIONS_DECL__ unsigned long int min(const unsigned long int a, const unsigned long int b); + +/** + * \ingroup CUDA_MATH_INT + * \brief Calculate the minimum value of the input \p long \p int and \p unsigned \p long \p int arguments. + * + * Calculate the minimum value of the arguments \p a and \p b, perform integer promotion first. + */ +__MATH_FUNCTIONS_DECL__ unsigned long int min(const long int a, const unsigned long int b); + +/** + * \ingroup CUDA_MATH_INT + * \brief Calculate the minimum value of the input \p unsigned \p long \p int and \p long \p int arguments. + * + * Calculate the minimum value of the arguments \p a and \p b, perform integer promotion first. + */ +__MATH_FUNCTIONS_DECL__ unsigned long int min(const unsigned long int a, const long int b); + +/** + * \ingroup CUDA_MATH_INT + * \brief Calculate the minimum value of the input \p long \p long \p int arguments. + * + * Calculate the minimum value of the arguments \p a and \p b. + */ +__MATH_FUNCTIONS_DECL__ long long int min(const long long int a, const long long int b); + +/** + * \ingroup CUDA_MATH_INT + * \brief Calculate the minimum value of the input \p unsigned \p long \p long \p int arguments. + * + * Calculate the minimum value of the arguments \p a and \p b. + */ +__MATH_FUNCTIONS_DECL__ unsigned long long int min(const unsigned long long int a, const unsigned long long int b); + +/** + * \ingroup CUDA_MATH_INT + * \brief Calculate the minimum value of the input \p long \p long \p int and \p unsigned \p long \p long \p int arguments. + * + * Calculate the minimum value of the arguments \p a and \p b, perform integer promotion first. + */ +__MATH_FUNCTIONS_DECL__ unsigned long long int min(const long long int a, const unsigned long long int b); + +/** + * \ingroup CUDA_MATH_INT + * \brief Calculate the minimum value of the input \p unsigned \p long \p long \p int and \p long \p long \p int arguments. + * + * Calculate the minimum value of the arguments \p a and \p b, perform integer promotion first. + */ +__MATH_FUNCTIONS_DECL__ unsigned long long int min(const unsigned long long int a, const long long int b); + +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the minimum value of the input \p float arguments. + * + * Calculate the minimum value of the arguments \p a and \p b. + * Behavior is equivalent to ::fminf() function. + * + * Note, this is different from \p std:: specification + */ +__MATH_FUNCTIONS_DECL__ float min(const float a, const float b); + +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the minimum value of the input \p float arguments. + * + * Calculate the minimum value of the arguments \p a and \p b. + * Behavior is equivalent to ::fmin() function. + * + * Note, this is different from \p std:: specification + */ +__MATH_FUNCTIONS_DECL__ double min(const double a, const double b); + +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the minimum value of the input \p float and \p double arguments. + * + * Convert \p float argument \p a to \p double, followed by ::fmin(). + * + * Note, this is different from \p std:: specification + */ +__MATH_FUNCTIONS_DECL__ double min(const float a, const double b); + +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the minimum value of the input \p double and \p float arguments. + * + * Convert \p float argument \p b to \p double, followed by ::fmin(). + * + * Note, this is different from \p std:: specification + */ +__MATH_FUNCTIONS_DECL__ double min(const double a, const float b); + +/** + * \ingroup CUDA_MATH_INT + * \brief Calculate the maximum value of the input \p unsigned \p int arguments. + * + * Calculate the maximum value of the arguments \p a and \p b. + */ +__MATH_FUNCTIONS_DECL__ unsigned int max(const unsigned int a, const unsigned int b); + +/** + * \ingroup CUDA_MATH_INT + * \brief Calculate the maximum value of the input \p int and \p unsigned \p int arguments. + * + * Calculate the maximum value of the arguments \p a and \p b, perform integer promotion first. + */ +__MATH_FUNCTIONS_DECL__ unsigned int max(const int a, const unsigned int b); + +/** + * \ingroup CUDA_MATH_INT + * \brief Calculate the maximum value of the input \p unsigned \p int and \p int arguments. + * + * Calculate the maximum value of the arguments \p a and \p b, perform integer promotion first. + */ +__MATH_FUNCTIONS_DECL__ unsigned int max(const unsigned int a, const int b); + +/** + * \ingroup CUDA_MATH_INT + * \brief Calculate the maximum value of the input \p long \p int arguments. + * + * Calculate the maximum value of the arguments \p a and \p b. + */ +__MATH_FUNCTIONS_DECL__ long int max(const long int a, const long int b); + +/** + * \ingroup CUDA_MATH_INT + * \brief Calculate the maximum value of the input \p unsigned \p long \p int arguments. + * + * Calculate the maximum value of the arguments \p a and \p b. + */ +__MATH_FUNCTIONS_DECL__ unsigned long int max(const unsigned long int a, const unsigned long int b); + +/** + * \ingroup CUDA_MATH_INT + * \brief Calculate the maximum value of the input \p long \p int and \p unsigned \p long \p int arguments. + * + * Calculate the maximum value of the arguments \p a and \p b, perform integer promotion first. + */ +__MATH_FUNCTIONS_DECL__ unsigned long int max(const long int a, const unsigned long int b); + +/** + * \ingroup CUDA_MATH_INT + * \brief Calculate the maximum value of the input \p unsigned \p long \p int and \p long \p int arguments. + * + * Calculate the maximum value of the arguments \p a and \p b, perform integer promotion first. + */ +__MATH_FUNCTIONS_DECL__ unsigned long int max(const unsigned long int a, const long int b); + +/** + * \ingroup CUDA_MATH_INT + * \brief Calculate the maximum value of the input \p long \p long \p int arguments. + * + * Calculate the maximum value of the arguments \p a and \p b. + */ +__MATH_FUNCTIONS_DECL__ long long int max(const long long int a, const long long int b); + +/** + * \ingroup CUDA_MATH_INT + * \brief Calculate the maximum value of the input \p unsigned \p long \p long \p int arguments. + * + * Calculate the maximum value of the arguments \p a and \p b. + */ +__MATH_FUNCTIONS_DECL__ unsigned long long int max(const unsigned long long int a, const unsigned long long int b); + +/** + * \ingroup CUDA_MATH_INT + * \brief Calculate the maximum value of the input \p long \p long \p int and \p unsigned \p long \p long \p int arguments. + * + * Calculate the maximum value of the arguments \p a and \p b, perform integer promotion first. + */ +__MATH_FUNCTIONS_DECL__ unsigned long long int max(const long long int a, const unsigned long long int b); + +/** + * \ingroup CUDA_MATH_INT + * \brief Calculate the maximum value of the input \p unsigned \p long \p long \p int and \p long \p long \p int arguments. + * + * Calculate the maximum value of the arguments \p a and \p b, perform integer promotion first. + */ +__MATH_FUNCTIONS_DECL__ unsigned long long int max(const unsigned long long int a, const long long int b); + +/** + * \ingroup CUDA_MATH_SINGLE + * \brief Calculate the maximum value of the input \p float arguments. + * + * Calculate the maximum value of the arguments \p a and \p b. + * Behavior is equivalent to ::fmaxf() function. + * + * Note, this is different from \p std:: specification + */ +__MATH_FUNCTIONS_DECL__ float max(const float a, const float b); + +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the maximum value of the input \p float arguments. + * + * Calculate the maximum value of the arguments \p a and \p b. + * Behavior is equivalent to ::fmax() function. + * + * Note, this is different from \p std:: specification + */ +__MATH_FUNCTIONS_DECL__ double max(const double a, const double b); + +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the maximum value of the input \p float and \p double arguments. + * + * Convert \p float argument \p a to \p double, followed by ::fmax(). + * + * Note, this is different from \p std:: specification + */ +__MATH_FUNCTIONS_DECL__ double max(const float a, const double b); + +/** + * \ingroup CUDA_MATH_DOUBLE + * \brief Calculate the maximum value of the input \p double and \p float arguments. + * + * Convert \p float argument \p b to \p double, followed by ::fmax(). + * + * Note, this is different from \p std:: specification + */ +__MATH_FUNCTIONS_DECL__ double max(const double a, const float b); + +#undef __MATH_FUNCTIONS_DECL__ +#undef __MATH_FUNCTIONS_DEVICE_DECL__ + +/******************************************************************************* +* * +* * +* * +*******************************************************************************/ +#undef EXCLUDE_FROM_RTC + +extern "C"{ +inline __device__ void *__nv_aligned_device_malloc(size_t size, size_t align) +{ + __device__ void *__nv_aligned_device_malloc_impl(size_t, size_t); + return __nv_aligned_device_malloc_impl(size, align); +} +} + +#endif /* __cplusplus && __CUDACC__ */ + +#define EXCLUDE_FROM_RTC + +#if !defined(__CUDACC__) + +/******************************************************************************* +* * +* ONLY FOR HOST CODE! NOT FOR DEVICE EXECUTION * +* * +*******************************************************************************/ + +#include + +#if defined(_WIN32) +#pragma warning (push) +#pragma warning (disable : 4211) + +#endif /* _WIN32 */ + +__func__(double rsqrt(double a)); + +__func__(double rcbrt(double a)); + +__func__(double sinpi(double a)); + +__func__(double cospi(double a)); + +__func__(void sincospi(double a, double *sptr, double *cptr)); + +__func__(double erfinv(double a)); + +__func__(double erfcinv(double a)); + +__func__(double normcdfinv(double a)); + +__func__(double normcdf(double a)); + +__func__(double erfcx(double a)); + +__func__(float rsqrtf(float a)); + +__func__(float rcbrtf(float a)); + +__func__(float sinpif(float a)); + +__func__(float cospif(float a)); + +__func__(void sincospif(float a, float *sptr, float *cptr)); + +__func__(float erfinvf(float a)); + +__func__(float erfcinvf(float a)); + +__func__(float normcdfinvf(float a)); + +__func__(float normcdff(float a)); + +__func__(float erfcxf(float a)); + +__func__(int min(int a, int b)); + +__func__(unsigned int umin(unsigned int a, unsigned int b)); + +__func__(long long int llmin(long long int a, long long int b)); + +__func__(unsigned long long int ullmin(unsigned long long int a, unsigned long long int b)); + +__func__(int max(int a, int b)); + +__func__(unsigned int umax(unsigned int a, unsigned int b)); + +__func__(long long int llmax(long long int a, long long int b)); + +__func__(unsigned long long int ullmax(unsigned long long int a, unsigned long long int b)); + +#if defined(_WIN32) || defined(__APPLE__) || defined (__ANDROID__) + +__func__(int __isnan(double a)); + +#endif /* _WIN32 || __APPLE__ || __ANDROID__ */ + +#if defined(_WIN32) || defined(__APPLE__) || defined (__QNX__) + +__func__(void sincos(double a, double *sptr, double *cptr)); + +#endif /* _WIN32 || __APPLE__ || __QNX__ */ + +#if defined(_WIN32) || defined(__APPLE__) + +__func__(double exp10(double a)); + +__func__(float exp10f(float a)); + +__func__(void sincosf(float a, float *sptr, float *cptr)); + +__func__(int __isinf(double a)); + +#endif /* _WIN32 || __APPLE__ */ + +#if (defined(_WIN32) && (!defined(_MSC_VER) || _MSC_VER < 1800)) || defined (__ANDROID__) + +__func__(double log2(double a)); + +#endif /* (_WIN32 && (!defined(_MSC_VER) || _MSC_VER < 1800)) || __ANDROID__ */ + +#if defined(_WIN32) + +__func__(int __signbit(double a)); + +__func__(int __finite(double a)); + +__func__(int __signbitl(long double a)); + +__func__(int __signbitf(float a)); + +__func__(int __finitel(long double a)); + +__func__(int __finitef(float a)); + +__func__(int __isinfl(long double a)); + +__func__(int __isinff(float a)); + +__func__(int __isnanl(long double a)); + +__func__(int __isnanf(float a)); + +#endif /* _WIN32 */ + +#if defined(_WIN32) && (!defined(_MSC_VER) || _MSC_VER < 1800) + +__func__(double copysign(double a, double b)); + +__func__(double fmax(double a, double b)); + +__func__(double fmin(double a, double b)); + +__func__(double trunc(double a)); + +__func__(double round(double a)); + +__func__(long int lround(double a)); + +__func__(long long int llround(double a)); + +__func__(double rint(double a)); + +__func__(double nearbyint(double a)); + +__func__(long int lrint(double a)); + +__func__(long long int llrint(double a)); + +__func__(double fdim(double a, double b)); + +__func__(double scalbn(double a, int b)); + +__func__(double scalbln(double a, long int b)); + +__func__(double exp2(double a)); + +__func__(double log1p(double a)); + +__func__(double expm1(double a)); + +__func__(double cbrt(double a)); + +__func__(double acosh(double a)); + +__func__(double asinh(double a)); + +__func__(double atanh(double a)); + +__func__(int ilogb(double a)); + +__func__(double logb(double a)); + +__func__(double remquo(double a, double b, int *quo)); + +__func__(double remainder(double a, double b)); + +__func__(double fma (double a, double b, double c)); + +__func__(double nextafter(double a, double b)); + +__func__(double erf(double a)); + +__func__(double erfc(double a)); + +__func__(double lgamma(double a)); + +__func__(unsigned long long int __internal_host_nan_kernel(const char *s)); + +__func__(double nan(const char *tagp)); + +__func__(double __host_tgamma_kernel(double a)); + +__func__(double __host_stirling_poly(double a)); + +__func__(double __host_tgamma_stirling(double a)); + +__func__(double tgamma(double a)); + +__func__(float fmaxf(float a, float b)); + +__func__(float fminf(float a, float b)); + +__func__(float roundf(float a)); + +__func__(long int lroundf(float a)); + +__func__(long long int llroundf(float a)); + +__func__(float truncf(float a)); + +__func__(float rintf(float a)); + +__func__(float nearbyintf(float a)); + +__func__(long int lrintf(float a)); + +__func__(long long int llrintf(float a)); + +__func__(float logbf(float a)); + +__func__(float scalblnf(float a, long int b)); + +__func__(float log2f(float a)); + +__func__(float exp2f(float a)); + +__func__(float acoshf(float a)); + +__func__(float asinhf(float a)); + +__func__(float atanhf(float a)); + +__func__(float cbrtf(float a)); + +__func__(float expm1f(float a)); + +__func__(float fdimf(float a, float b)); + +__func__(float log1pf(float a)); + +__func__(float scalbnf(float a, int b)); + +__func__(float fmaf(float a, float b, float c)); + +__func__(int ilogbf(float a)); + +__func__(float erff(float a)); + +__func__(float erfcf(float a)); + +__func__(float lgammaf(float a)); + +__func__(float tgammaf(float a)); + +__func__(float remquof(float a, float b, int *quo)); + +__func__(float remainderf(float a, float b)); + +__func__(float copysignf(float a, float b)); + +__func__(float nextafterf(float a, float b)); + +__func__(float nanf(const char *tagp)); + +#endif /* _WIN32 && (!defined(_MSC_VER) || _MSC_VER < 1800) */ + +#if defined(_WIN32) +#pragma warning (pop) +#endif /* _WIN32 */ + +#endif /* !__CUDACC__ */ + +#undef EXCLUDE_FROM_RTC + +#if !defined(__CUDACC_RTC__) + +#include "math_functions.hpp" + +#endif /* !__CUDACC_RTC__ */ + +#endif /* !__MATH_FUNCTIONS_H__ */ + +#if defined(__UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_MATH_FUNCTIONS_H__) +#undef __CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__ +#undef __UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_MATH_FUNCTIONS_H__ +#endif diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/math_functions.hpp b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/math_functions.hpp new file mode 100644 index 0000000000000000000000000000000000000000..cc09b915ea07f8ef376f5c3640f963a09e86dbfd --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/math_functions.hpp @@ -0,0 +1,3398 @@ +/* + * Copyright 1993-2023 NVIDIA Corporation. All rights reserved. + * + * NOTICE TO LICENSEE: + * + * This source code and/or documentation ("Licensed Deliverables") are + * subject to NVIDIA intellectual property rights under U.S. and + * international Copyright laws. + * + * These Licensed Deliverables contained herein is PROPRIETARY and + * CONFIDENTIAL to NVIDIA and is being provided under the terms and + * conditions of a form of NVIDIA software license agreement by and + * between NVIDIA and Licensee ("License Agreement") or electronically + * accepted by Licensee. Notwithstanding any terms or conditions to + * the contrary in the License Agreement, reproduction or disclosure + * of the Licensed Deliverables to any third party without the express + * written consent of NVIDIA is prohibited. + * + * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE + * LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE + * SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE. IT IS + * PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND. + * NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED + * DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY, + * NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE. + * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE + * LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY + * SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY + * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS + * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THESE LICENSED DELIVERABLES. + * + * U.S. Government End Users. These Licensed Deliverables are a + * "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT + * 1995), consisting of "commercial computer software" and "commercial + * computer software documentation" as such terms are used in 48 + * C.F.R. 12.212 (SEPT 1995) and is provided to the U.S. Government + * only as a commercial end item. Consistent with 48 C.F.R.12.212 and + * 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all + * U.S. Government End Users acquire the Licensed Deliverables with + * only those rights set forth herein. + * + * Any use of the Licensed Deliverables in individual and commercial + * software must include, in the user documentation and internal + * comments to the code, the above Disclaimer and U.S. Government End + * Users Notice. + */ + +#if !defined(__CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__) +#if defined(_MSC_VER) +#pragma message("crt/math_functions.hpp is an internal header file and must not be used directly. Please use cuda_runtime_api.h or cuda_runtime.h instead.") +#else +#warning "crt/math_functions.hpp is an internal header file and must not be used directly. Please use cuda_runtime_api.h or cuda_runtime.h instead." +#endif +#define __CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__ +#define __UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_MATH_FUNCTIONS_HPP__ +#endif + +#if !defined(__MATH_FUNCTIONS_HPP__) +#define __MATH_FUNCTIONS_HPP__ + +/******************************************************************************* +* * +* * +* * +*******************************************************************************/ + +#if defined(__cplusplus) && defined(__CUDACC__) + +/******************************************************************************* +* * +* * +* * +*******************************************************************************/ + +#include "builtin_types.h" +#include "host_defines.h" + +/******************************************************************************* +* * +* * +* * +*******************************************************************************/ + +#if defined(__CUDACC_RTC__) + +__host__ __device__ __cudart_builtin__ int signbit(const float x) { return __signbitf(x); } +__host__ __device__ __cudart_builtin__ int signbit(const double x) { return __signbit(x); } +__host__ __device__ __cudart_builtin__ int signbit(const long double x) { return __signbitl(static_cast(x));} + +__host__ __device__ __cudart_builtin__ int isfinite(const float x) { return __finitef(x); } +__host__ __device__ __cudart_builtin__ int isfinite(const double x) { return __finite(x); } +__host__ __device__ __cudart_builtin__ int isfinite(const long double x) { return __finitel(static_cast(x)); } + +__host__ __device__ __cudart_builtin__ int isnan(const float x) { return __isnanf(x); } +__host__ __device__ __cudart_builtin__ int isnan(const double x) { return __isnan(x); } +__host__ __device__ __cudart_builtin__ int isnan(const long double x) { return __isnanl(static_cast(x)); } + +__host__ __device__ __cudart_builtin__ int isinf(const float x) { return __isinff(x); } +__host__ __device__ __cudart_builtin__ int isinf(const double x) { return __isinf(x); } +__host__ __device__ __cudart_builtin__ int isinf(const long double x) { return __isinfl(static_cast(x)); } + +__host__ __device__ __cudart_builtin__ long long int abs(const long long int a) { return llabs(a); } + +__host__ __device__ __cudart_builtin__ long int abs(const long int in) { return llabs(in); } +__host__ __device__ __cudart_builtin__ float abs(const float in) { return fabsf(in); } +__host__ __device__ __cudart_builtin__ double abs(const double in) { return fabs(in); } +__host__ __device__ __cudart_builtin__ float fabs(const float in) { return fabsf(in); } +__host__ __device__ __cudart_builtin__ float ceil(const float in) { return ceilf(in); } +__host__ __device__ __cudart_builtin__ float floor(const float in) { return floorf(in); } +__host__ __device__ __cudart_builtin__ float sqrt(const float in) { return sqrtf(in); } +__host__ __device__ __cudart_builtin__ float pow(const float a, const float b) { return powf(a, b); } +extern "C" __device__ float powif(float, int); +__host__ __device__ __cudart_builtin__ float pow(const float a, const int b) { return powif(a, b); } +extern "C" __device__ double powi(double, int); +__host__ __device__ __cudart_builtin__ double pow(const double a, const int b) { return powi(a, b); } +__host__ __device__ __cudart_builtin__ float log(const float in) { return logf(in); } +__host__ __device__ __cudart_builtin__ float log10(const float in) { return log10f(in); } +__host__ __device__ __cudart_builtin__ float fmod(const float a, const float b) { return fmodf(a, b); } +__host__ __device__ __cudart_builtin__ float modf(const float a, float*b) { return modff(a, b); } +__host__ __device__ __cudart_builtin__ float exp(const float in) { return expf(in); } +__host__ __device__ __cudart_builtin__ float frexp(const float a, int*b) { return frexpf(a, b); } +__host__ __device__ __cudart_builtin__ float ldexp(const float a, int b) { return ldexpf(a, b); } +__host__ __device__ __cudart_builtin__ float asin(const float in) { return asinf(in); } +__host__ __device__ __cudart_builtin__ float sin(const float in) { return sinf(in); } +__host__ __device__ __cudart_builtin__ float sinh(const float in) { return sinhf(in); } +__host__ __device__ __cudart_builtin__ float acos(const float in) { return acosf(in); } +__host__ __device__ __cudart_builtin__ float cos(const float in) { return cosf(in); } +__host__ __device__ __cudart_builtin__ float cosh(const float in) { return coshf(in); } +__host__ __device__ __cudart_builtin__ float atan(const float in) { return atanf(in); } +__host__ __device__ __cudart_builtin__ float atan2(const float a, const float b) { return atan2f(a, b); } +__host__ __device__ __cudart_builtin__ float tan(const float in) { return tanf(in); } +__host__ __device__ __cudart_builtin__ float tanh(const float in) { return tanhf(in); } + +#elif defined(__GNUC__) + +#undef signbit +#undef isfinite +#undef isnan +#undef isinf + +#if defined(_LIBCPP_VERSION) +extern "C" __device__ float powif(float, int); +extern "C" __device__ double powi(double, int); +#endif /* _LIBCPP_VERSION */ + +#if defined(__APPLE__) +__forceinline__ __host__ __device__ __cudart_builtin__ int signbit(const float x) { return __signbitf(x); } +__forceinline__ __host__ __device__ __cudart_builtin__ int signbit(const double x) { return __signbitd(x); } +__forceinline__ __host__ __device__ __cudart_builtin__ int signbit(const long double x) { return __signbitl(x);} + +__forceinline__ __host__ __device__ __cudart_builtin__ int isfinite(const float x) { return __isfinitef(x); } +__forceinline__ __host__ __device__ __cudart_builtin__ int isfinite(const double x) { return __isfinited(x); } +__forceinline__ __host__ __device__ __cudart_builtin__ int isfinite(const long double x) { return __isfinite(x); } + +__forceinline__ __host__ __device__ __cudart_builtin__ int isnan(const double x) throw() { return __isnand(x); } +#if defined(_LIBCPP_VERSION) && _LIBCPP_VERSION < 7000 +__forceinline__ __host__ __device__ __cudart_builtin__ int isnan(const float x) { return __isnanf(x); } +__forceinline__ __host__ __device__ __cudart_builtin__ int isnan(const long double x) { return __isnan(x); } +#endif /* defined(_LIBCPP_VERSION) && _LIBCPP_VERSION < 7000 */ + +__forceinline__ __host__ __device__ __cudart_builtin__ int isinf(const double x) throw() { return __isinfd(x); } +#if defined(_LIBCPP_VERSION) && _LIBCPP_VERSION < 7000 +__forceinline__ __host__ __device__ __cudart_builtin__ int isinf(const float x) { return __isinff(x); } +__forceinline__ __host__ __device__ __cudart_builtin__ int isinf(const long double x) { return __isinf(x); } +#endif /* defined(_LIBCPP_VERSION) && _LIBCPP_VERSION < 7000 */ +#else /* __APPLE__ */ + +#if ((defined _GLIBCXX_MATH_H) && _GLIBCXX_MATH_H) && (__cplusplus >= 201103L) +#if defined(__CUDA_ARCH__) +#define __NV_BUILTIN_FUNC_DECL__ __forceinline__ __host__ __device__ __cudart_builtin__ +#if _GLIBCXX_HAVE_OBSOLETE_ISNAN && !_GLIBCXX_NO_OBSOLETE_ISINF_ISNAN_DYNAMIC +__NV_BUILTIN_FUNC_DECL__ int isnan(const double a) throw() { return __isnan(a); } +__NV_BUILTIN_FUNC_DECL__ int isinf(const double x) throw() { return __isinf(x); } +#endif /* _GLIBCXX_HAVE_OBSOLETE_ISNAN && !_GLIBCXX_NO_OBSOLETE_ISINF_ISNAN_DYNAMIC */ +#undef __NV_BUILTIN_FUNC_DECL__ +#endif /* __CUDA_ARCH */ +#else /* !(((defined _GLIBCXX_MATH_H) && _GLIBCXX_MATH_H) && (__cplusplus >= 201103L)) */ + +#if defined(__QNX__) +#if defined(__QNX__) && defined(_LIBCPP_VERSION) +static __inline__ __host__ __device__ __cudart_builtin__ bool signbit(const float x) +{ +#if defined(__CUDA_ARCH__) + return (__signbitf(x) != 0); +#else /* !__CUDA_ARCH__ */ + return signbit(x); +#endif /* __CUDA_ARCH__ */ +} +static __inline__ __host__ __device__ __cudart_builtin__ bool signbit(const double x) +{ +#if defined(__CUDA_ARCH__) + return (__signbit(x) != 0); +#else /* !__CUDA_ARCH__ */ + return signbit(x); +#endif /* __CUDA_ARCH__ */ +} +static __inline__ __host__ __device__ __cudart_builtin__ bool signbit(const long double x) +{ +#if defined(__CUDA_ARCH__) + return (__signbitl(x) != 0); +#else /* !__CUDA_ARCH__ */ + return signbit(x); +#endif /* __CUDA_ARCH__ */ +} +#endif /* (__QNX__ && _LIBCPP_VERSION) */ + +static __inline__ __host__ __device__ __cudart_builtin__ bool isfinite(const long double a) +{ +#if defined(__CUDA_ARCH__) + return (__finitel(a) != 0); +#else /* defined(__CUDA_ARCH__) */ + return isfinite(a); +#endif /* defined(__CUDA_ARCH__) */ +} +static __inline__ __host__ __device__ __cudart_builtin__ bool isfinite(const double a) +{ +#if defined(__CUDA_ARCH__) + return (__finite(a) != 0); +#else /* defined(__CUDA_ARCH__) */ + return isfinite(a); +#endif /* defined(__CUDA_ARCH__) */ +} +static __inline__ __host__ __device__ __cudart_builtin__ bool isfinite(const float a) +{ +#if defined(__CUDA_ARCH__) + return (__finitef(a) != 0); +#else /* defined(__CUDA_ARCH__) */ + return isfinite(a); +#endif /* defined(__CUDA_ARCH__) */ +} + +static __inline__ __host__ __device__ __cudart_builtin__ bool isnan(const long double a) +{ +#if defined(__CUDA_ARCH__) + return (__isnanl(a) != 0); +#else /* defined(__CUDA_ARCH__) */ + return isnan(a); +#endif /* defined(__CUDA_ARCH__) */ +} +static __inline__ __host__ __device__ __cudart_builtin__ bool isnan(const double a) +{ +#if defined(__CUDA_ARCH__) + return (__isnan(a) != 0); +#else /* defined(__CUDA_ARCH__) */ + return isnan(a); +#endif /* defined(__CUDA_ARCH__) */ +} +static __inline__ __host__ __device__ __cudart_builtin__ bool isnan(const float a) +{ +#if defined(__CUDA_ARCH__) + return (__isnanf(a) != 0); +#else /* defined(__CUDA_ARCH__) */ + return isnan(a); +#endif /* defined(__CUDA_ARCH__) */ +} + +static __inline__ __host__ __device__ __cudart_builtin__ bool isinf(const long double a) +{ +#if defined(__CUDA_ARCH__) + return (__isinfl(a) != 0); +#else /* defined(__CUDA_ARCH__) */ + return isinf(a); +#endif /* defined(__CUDA_ARCH__) */ +} +static __inline__ __host__ __device__ __cudart_builtin__ bool isinf(const double a) +{ +#if defined(__CUDA_ARCH__) + return (__isinf(a) != 0); +#else /* defined(__CUDA_ARCH__) */ + return isinf(a); +#endif /* defined(__CUDA_ARCH__) */ +} +static __inline__ __host__ __device__ __cudart_builtin__ bool isinf(const float a) +{ +#if defined(__CUDA_ARCH__) + return (__isinff(a) != 0); +#else /* defined(__CUDA_ARCH__) */ + return isinf(a); +#endif /* defined(__CUDA_ARCH__) */ +} + +#elif ( (defined(__ANDROID__) || defined(__HORIZON__)) && defined(_LIBCPP_VERSION)) +#if defined(__CUDA_ARCH__) +__forceinline__ __host__ __device__ __cudart_builtin__ int signbit(const float x) { return __signbitf(x); } +__forceinline__ __host__ __device__ __cudart_builtin__ int signbit(const double x) { return __signbit(x); } +__forceinline__ __host__ __device__ __cudart_builtin__ int signbit(const long double x) { return __signbitl(x);} + +__forceinline__ __host__ __device__ __cudart_builtin__ int isfinite(const float x) { return __finitef(x); } +__forceinline__ __host__ __device__ __cudart_builtin__ int isfinite(const double x) { return __finite(x); } +__forceinline__ __host__ __device__ __cudart_builtin__ int isfinite(const long double x) { return __finitel(x); } + +__forceinline__ __host__ __device__ __cudart_builtin__ int isnan(const double x) { return __isnan(x); } +#if _LIBCPP_VERSION < 8000 +__forceinline__ __host__ __device__ __cudart_builtin__ int isnan(const float x) { return __isnanf(x); } +__forceinline__ __host__ __device__ __cudart_builtin__ int isnan(const long double x) { return __isnanl(x); } +#endif /* _LIBCPP_VERSION < 8000 */ + +__forceinline__ __host__ __device__ __cudart_builtin__ int isinf(const double x) { return __isinf(x); } +#if _LIBCPP_VERSION < 8000 +__forceinline__ __host__ __device__ __cudart_builtin__ int isinf(const float x) { return __isinff(x); } +__forceinline__ __host__ __device__ __cudart_builtin__ int isinf(const long double x) { return __isinfl(x); } +#endif /* _LIBCPP_VERSION < 8000 */ +#else /* !defined(__CUDA_ARCH__) */ +__forceinline__ __host__ __device__ __cudart_builtin__ int signbit(const float x) { return signbit(x); } +__forceinline__ __host__ __device__ __cudart_builtin__ int signbit(const double x) { return signbit(x); } +__forceinline__ __host__ __device__ __cudart_builtin__ int signbit(const long double x) { return signbit(x);} + +__forceinline__ __host__ __device__ __cudart_builtin__ int isfinite(const float x) { return isfinite(x); } +__forceinline__ __host__ __device__ __cudart_builtin__ int isfinite(const double x) { return isfinite(x); } +__forceinline__ __host__ __device__ __cudart_builtin__ int isfinite(const long double x) { return isfinite(x); } + +#if _LIBCPP_VERSION < 8000 +__forceinline__ __host__ __device__ __cudart_builtin__ int isnan(const float x) { return isnan(x); } +/* int isnan(double) provided by math.h */ +__forceinline__ __host__ __device__ __cudart_builtin__ int isnan(const long double x) { return isnan(x); } + +__forceinline__ __host__ __device__ __cudart_builtin__ int isinf(const float x) { return isinf(x); } +/* int isinf(double) provided by math.h */ +__forceinline__ __host__ __device__ __cudart_builtin__ int isinf(const long double x) { return isinf(x); } +#endif /* _LIBCPP_VERSION < 8000 */ + +#endif /* defined(__CUDA_ARCH__) */ + +#else /* !__QNX__ */ +__forceinline__ __host__ __device__ __cudart_builtin__ int signbit(const float x) { return __signbitf(x); } +#if defined(__ICC) +__forceinline__ __host__ __device__ __cudart_builtin__ int signbit(const double x) throw() { return __signbit(x); } +#else /* !__ICC */ +__forceinline__ __host__ __device__ __cudart_builtin__ int signbit(const double x) { return __signbit(x); } +#endif /* __ICC */ +__forceinline__ __host__ __device__ __cudart_builtin__ int signbit(const long double x) { return __signbitl(x);} + +#if defined(__ANDROID__) +__forceinline__ __host__ __device__ __cudart_builtin__ int isfinite(const float x) { +#if defined(__CUDA_ARCH__) + return __finitef(x); +#else /* !__CUDA_ARCH__ */ + return __isfinitef(x); +#endif /* __CUDA_ARCH__ */ +} +#else /* !__ANDROID__ */ +__forceinline__ __host__ __device__ __cudart_builtin__ int isfinite(const float x) { return __finitef(x); } +#endif /* __ANDROID__ */ + +#if defined(__ANDROID__) +__forceinline__ __host__ __device__ __cudart_builtin__ int isfinite(const double x) +{ +#ifdef __CUDA_ARCH__ + return __finite(x); +#else /* !__CUDA_ARCH__ */ + return __isfinite(x); +#endif /* __CUDA_ARCH__ */ +} +#elif defined(__ICC) +__forceinline__ __host__ __device__ __cudart_builtin__ int isfinite(const double x) throw() { return __finite(x); } +#else +__forceinline__ __host__ __device__ __cudart_builtin__ int isfinite(const double x) { return __finite(x); } +#endif /* __ANDROID__ */ + +#if defined(__ANDROID__) +__forceinline__ __host__ __device__ __cudart_builtin__ int isfinite(const long double x) +{ +#ifdef __CUDA_ARCH__ + return __finitel(x); +#else /* !__CUDA_ARCH__ */ + return __isfinitel(x); +#endif /* __CUDA_ARCH__ */ +} +#else /* !__ANDROID__ */ +__forceinline__ __host__ __device__ __cudart_builtin__ int isfinite(const long double x) { return __finitel(x); } +#endif /* __ANDROID__ */ + +__forceinline__ __host__ __device__ __cudart_builtin__ int isnan(const float x) { return __isnanf(x); } +#if defined(__ANDROID__) +__forceinline__ __host__ __device__ __cudart_builtin__ int isnan(const double x) { return __isnan(x); } +#else /* !__ANDROID__ */ +__forceinline__ __host__ __device__ __cudart_builtin__ int isnan(const double x) throw() { return __isnan(x); } +#endif /* __ANDROID__ */ +__forceinline__ __host__ __device__ __cudart_builtin__ int isnan(const long double x) { return __isnanl(x); } + +__forceinline__ __host__ __device__ __cudart_builtin__ int isinf(const float x) { return __isinff(x); } +#if defined(__ANDROID__) +__forceinline__ __host__ __device__ __cudart_builtin__ int isinf(const double x) { return __isinf(x); } +#else /* !__ANDROID__ */ +__forceinline__ __host__ __device__ __cudart_builtin__ int isinf(const double x) throw() { return __isinf(x); } +#endif /* __ANDROID__ */ +__forceinline__ __host__ __device__ __cudart_builtin__ int isinf(const long double x) { return __isinfl(x); } +#endif /* __QNX__ || __HORIZON__ */ + +#endif /* ((defined _GLIBCXX_MATH_H) && _GLIBCXX_MATH_H) && (__cplusplus >= 201103L) */ +#endif /* __APPLE__ */ + +#if defined(__arm__) && !defined(_STLPORT_VERSION) && !_GLIBCXX_USE_C99 +#if !defined(__ANDROID__) || (!defined(_LIBCPP_VERSION) && (__GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 8))) + +#if !defined(__QNX__) && !defined(__HORIZON__) +static __inline__ __host__ __device__ __cudart_builtin__ long long int abs(const long long int a) +{ + return llabs(a); +} +#endif /* !__QNX__ && !__HORIZON__*/ + +#endif /* !defined(__ANDROID__) || (!defined(_LIBCPP_VERSION) && (__GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 8))) */ +#endif /* __arm__ && !_STLPORT_VERSION && !_GLIBCXX_USE_C99 */ + +#elif defined(_WIN32) + +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +static __inline__ __host__ __device__ __cudart_builtin__ int signbit(const long double a) +{ + return __signbitl(a); +} + +static __inline__ __host__ __device__ __cudart_builtin__ int signbit(const double a) +{ + return __signbit(a); +} + +static __inline__ __host__ __device__ __cudart_builtin__ int signbit(const float a) +{ + return __signbitf(a); +} +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ + +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +static __inline__ __host__ __device__ __cudart_builtin__ int isinf(const long double a) +{ + return __isinfl(a); +} +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +static __inline__ __host__ __device__ __cudart_builtin__ bool isinf(const long double a) +{ +#if defined(__CUDA_ARCH__) + return (__isinfl(a) != 0); +#else /* defined(__CUDA_ARCH__) */ + return isinf(a); +#endif /* defined(__CUDA_ARCH__) */ +} +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ + +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +static __inline__ __host__ __device__ __cudart_builtin__ int isinf(const double a) +{ + return __isinf(a); +} +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +static __inline__ __host__ __device__ __cudart_builtin__ bool isinf(const double a) +{ +#if defined(__CUDA_ARCH__) + return (__isinf(a) != 0); +#else /* defined(__CUDA_ARCH__) */ + return isinf(a); +#endif /* defined(__CUDA_ARCH__) */ +} +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ + +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +static __inline__ __host__ __device__ __cudart_builtin__ int isinf(const float a) +{ + return __isinff(a); +} +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +static __inline__ __host__ __device__ bool isinf(const float a) +{ +#if defined(__CUDA_ARCH__) + return (__isinff(a) != 0); +#else /* defined(__CUDA_ARCH__) */ + return isinf(a); +#endif /* defined(__CUDA_ARCH__) */ +} +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ + +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +static __inline__ __host__ __device__ __cudart_builtin__ int isnan(const long double a) +{ + return __isnanl(a); +} +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +static __inline__ __host__ __device__ __cudart_builtin__ bool isnan(const long double a) +{ +#if defined(__CUDA_ARCH__) + return (__isnanl(a) != 0); +#else /* defined(__CUDA_ARCH__) */ + return isnan(a); +#endif /* defined(__CUDA_ARCH__) */ +} +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ + +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +static __inline__ __host__ __device__ __cudart_builtin__ int isnan(const double a) +{ + return __isnan(a); +} +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +static __inline__ __host__ __device__ __cudart_builtin__ bool isnan(const double a) +{ +#if defined(__CUDA_ARCH__) + return (__isnan(a) != 0); +#else /* defined(__CUDA_ARCH__) */ + return isnan(a); +#endif /* defined(__CUDA_ARCH__) */ +} +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ + +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +static __inline__ __host__ __device__ __cudart_builtin__ int isnan(const float a) +{ + return __isnanf(a); +} +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +static __inline__ __host__ __device__ __cudart_builtin__ bool isnan(const float a) +{ +#if defined(__CUDA_ARCH__) + return (__isnanf(a) != 0); +#else /* defined(__CUDA_ARCH__) */ + return isnan(a); +#endif /* defined(__CUDA_ARCH__) */ +} +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ + +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +static __inline__ __host__ __device__ __cudart_builtin__ int isfinite(const long double a) +{ + return __finitel(a); +} +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +static __inline__ __host__ __device__ __cudart_builtin__ bool isfinite(const long double a) +{ +#if defined(__CUDA_ARCH__) + return (__finitel(a) != 0); +#else /* defined(__CUDA_ARCH__) */ + return isfinite(a); +#endif /* defined(__CUDA_ARCH__) */ +} +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ + +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +static __inline__ __host__ __device__ __cudart_builtin__ int isfinite(const double a) +{ + return __finite(a); +} +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +static __inline__ __host__ __device__ __cudart_builtin__ bool isfinite(const double a) +{ +#if defined(__CUDA_ARCH__) + return (__finite(a) != 0); +#else /* defined(__CUDA_ARCH__) */ + return isfinite(a); +#endif /* defined(__CUDA_ARCH__) */ +} +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ + +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +static __inline__ __host__ __device__ __cudart_builtin__ int isfinite(const float a) +{ + return __finitef(a); +} +#else /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ +static __inline__ __host__ __device__ __cudart_builtin__ bool isfinite(const float a) +{ +#if defined(__CUDA_ARCH__) + return (__finitef(a) != 0); +#else /* defined(__CUDA_ARCH__) */ + return isfinite(a); +#endif /* defined(__CUDA_ARCH__) */ +} +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ + +#endif /* __CUDACC_RTC__ */ + +#if defined(__CUDACC_RTC__) +#define __MATH_FUNCTIONS_DECL__ __host__ __device__ +#define __MATH_FUNCTIONS_DEVICE_DECL__ __device__ +#else /* __CUDACC_RTC__ */ +#define __MATH_FUNCTIONS_DECL__ static inline __host__ __device__ +#define __MATH_FUNCTIONS_DEVICE_DECL__ static inline __device__ +#endif /* __CUDACC_RTC__ */ + +#if defined(__CUDACC_RTC__) || (!defined(_MSC_VER) || _MSC_VER < 1800) +#if defined(__QNX__) && defined(_LIBCPP_VERSION) +_LIBCPP_BEGIN_NAMESPACE_STD +#endif /* __QNX__ && _LIBCPP_VERSION */ +#if !defined(__QNX__) && !(defined(_LIBCPP_VERSION) && _LIBCPP_VERSION >= 3800) +#if !(((defined _GLIBCXX_MATH_H) && _GLIBCXX_MATH_H) && (__cplusplus >= 201103L)) +__MATH_FUNCTIONS_DECL__ float logb(const float a) +{ + return logbf(a); +} + +__MATH_FUNCTIONS_DECL__ int ilogb(const float a) +{ + return ilogbf(a); +} + +__MATH_FUNCTIONS_DECL__ float scalbn(const float a, const int b) +{ + return scalbnf(a, b); +} + +__MATH_FUNCTIONS_DECL__ float scalbln(const float a, const long int b) +{ + return scalblnf(a, b); +} + +__MATH_FUNCTIONS_DECL__ float exp2(const float a) +{ + return exp2f(a); +} + +__MATH_FUNCTIONS_DECL__ float expm1(const float a) +{ + return expm1f(a); +} + +__MATH_FUNCTIONS_DECL__ float log2(const float a) +{ + return log2f(a); +} + +__MATH_FUNCTIONS_DECL__ float log1p(const float a) +{ + return log1pf(a); +} + +__MATH_FUNCTIONS_DECL__ float acosh(const float a) +{ + return acoshf(a); +} + +__MATH_FUNCTIONS_DECL__ float asinh(const float a) +{ + return asinhf(a); +} + +__MATH_FUNCTIONS_DECL__ float atanh(const float a) +{ + return atanhf(a); +} + +__MATH_FUNCTIONS_DECL__ float hypot(const float a, const float b) +{ + return hypotf(a, b); +} + +__MATH_FUNCTIONS_DECL__ float cbrt(const float a) +{ + return cbrtf(a); +} + +__MATH_FUNCTIONS_DECL__ float erf(const float a) +{ + return erff(a); +} + +__MATH_FUNCTIONS_DECL__ float erfc(const float a) +{ + return erfcf(a); +} + +__MATH_FUNCTIONS_DECL__ float lgamma(const float a) +{ + return lgammaf(a); +} + +__MATH_FUNCTIONS_DECL__ float tgamma(const float a) +{ + return tgammaf(a); +} + +__MATH_FUNCTIONS_DECL__ float copysign(const float a, const float b) +{ + return copysignf(a, b); +} + +__MATH_FUNCTIONS_DECL__ float nextafter(const float a, const float b) +{ + return nextafterf(a, b); +} + +__MATH_FUNCTIONS_DECL__ float remainder(const float a, const float b) +{ + return remainderf(a, b); +} + +__MATH_FUNCTIONS_DECL__ float remquo(const float a, const float b, int *quo) +{ + return remquof(a, b, quo); +} + +__MATH_FUNCTIONS_DECL__ float round(const float a) +{ + return roundf(a); +} + +__MATH_FUNCTIONS_DECL__ long int lround(const float a) +{ + return lroundf(a); +} + +__MATH_FUNCTIONS_DECL__ long long int llround(const float a) +{ + return llroundf(a); +} + +__MATH_FUNCTIONS_DECL__ float trunc(const float a) +{ + return truncf(a); +} + +__MATH_FUNCTIONS_DECL__ float rint(const float a) +{ + return rintf(a); +} + +__MATH_FUNCTIONS_DECL__ long int lrint(const float a) +{ + return lrintf(a); +} + +__MATH_FUNCTIONS_DECL__ long long int llrint(const float a) +{ + return llrintf(a); +} + +__MATH_FUNCTIONS_DECL__ float nearbyint(const float a) +{ + return nearbyintf(a); +} + +__MATH_FUNCTIONS_DECL__ float fdim(const float a, const float b) +{ + return fdimf(a, b); +} + +__MATH_FUNCTIONS_DECL__ float fma(const float a, const float b, const float c) +{ + return fmaf(a, b, c); +} + +__MATH_FUNCTIONS_DECL__ float fmax(const float a, const float b) +{ + return fmaxf(a, b); +} + +__MATH_FUNCTIONS_DECL__ float fmin(const float a, const float b) +{ + return fminf(a, b); +} +#endif /* !(((defined _GLIBCXX_MATH_H) && _GLIBCXX_MATH_H) && (__cplusplus >= 201103L)) */ +#endif /* !(!defined(__QNX__) && !(defined(_LIBCPP_VERSION) && _LIBCPP_VERSION >= 3800)) */ +#if defined(__QNX__) && defined(_LIBCPP_VERSION) +_LIBCPP_END_NAMESPACE_STD +#endif +#endif /* __CUDACC_RTC__ || (!defined(_MSC_VER) || _MSC_VER < 1800) */ + +__MATH_FUNCTIONS_DECL__ float exp10(const float a) +{ + return exp10f(a); +} + +__MATH_FUNCTIONS_DECL__ float rsqrt(const float a) +{ + return rsqrtf(a); +} + +__MATH_FUNCTIONS_DECL__ float rcbrt(const float a) +{ + return rcbrtf(a); +} + +__MATH_FUNCTIONS_DECL__ float sinpi(const float a) +{ + return sinpif(a); +} + +__MATH_FUNCTIONS_DECL__ float cospi(const float a) +{ + return cospif(a); +} + +__MATH_FUNCTIONS_DECL__ void sincospi(const float a, float *const sptr, float *const cptr) +{ + sincospif(a, sptr, cptr); +} + +__MATH_FUNCTIONS_DECL__ void sincos(const float a, float *const sptr, float *const cptr) +{ + sincosf(a, sptr, cptr); +} + +__MATH_FUNCTIONS_DECL__ float j0(const float a) +{ + return j0f(a); +} + +__MATH_FUNCTIONS_DECL__ float j1(const float a) +{ + return j1f(a); +} + +__MATH_FUNCTIONS_DECL__ float jn(const int n, const float a) +{ + return jnf(n, a); +} + +__MATH_FUNCTIONS_DECL__ float y0(const float a) +{ + return y0f(a); +} + +__MATH_FUNCTIONS_DECL__ float y1(const float a) +{ + return y1f(a); +} + +__MATH_FUNCTIONS_DECL__ float yn(const int n, const float a) +{ + return ynf(n, a); +} + +__MATH_FUNCTIONS_DEVICE_DECL__ float cyl_bessel_i0(const float a) +{ + return cyl_bessel_i0f(a); +} + +__MATH_FUNCTIONS_DEVICE_DECL__ float cyl_bessel_i1(const float a) +{ + return cyl_bessel_i1f(a); +} + +__MATH_FUNCTIONS_DECL__ float erfinv(const float a) +{ + return erfinvf(a); +} + +__MATH_FUNCTIONS_DECL__ float erfcinv(const float a) +{ + return erfcinvf(a); +} + +__MATH_FUNCTIONS_DECL__ float normcdfinv(const float a) +{ + return normcdfinvf(a); +} + +__MATH_FUNCTIONS_DECL__ float normcdf(const float a) +{ + return normcdff(a); +} + +__MATH_FUNCTIONS_DECL__ float erfcx(const float a) +{ + return erfcxf(a); +} + +__MATH_FUNCTIONS_DECL__ double copysign(const double a, const float b) +{ + return copysign(a, static_cast(b)); +} + +__MATH_FUNCTIONS_DECL__ double copysign(const float a, const double b) +{ + return copysign(static_cast(a), b); +} + +__MATH_FUNCTIONS_DECL__ unsigned int min(const unsigned int a, const unsigned int b) +{ + return umin(a, b); +} + +__MATH_FUNCTIONS_DECL__ unsigned int min(const int a, const unsigned int b) +{ + return umin(static_cast(a), b); +} + +__MATH_FUNCTIONS_DECL__ unsigned int min(const unsigned int a, const int b) +{ + return umin(a, static_cast(b)); +} + +__MATH_FUNCTIONS_DECL__ long int min(const long int a, const long int b) +{ + long int retval; + /* Suppress VS warning: warning C4127: conditional expression is constant */ +#if defined(_MSC_VER) && !defined(__CUDA_ARCH__) +#pragma warning (push) +#pragma warning (disable: 4127) +#endif /* _MSC_VER && !defined(__CUDA_ARCH__) */ + /* long can be of 32-bit type on some systems. */ + if (sizeof(long int) == sizeof(int)) { +#if defined(_MSC_VER) && !defined(__CUDA_ARCH__) +#pragma warning (pop) +#endif /* _MSC_VER && !defined(__CUDA_ARCH__) */ + retval = static_cast(min(static_cast(a), static_cast(b))); + } else { + retval = static_cast(llmin(static_cast(a), static_cast(b))); + } + return retval; +} + +__MATH_FUNCTIONS_DECL__ unsigned long int min(const unsigned long int a, const unsigned long int b) +{ + unsigned long int retval; +#if defined(_MSC_VER) && !defined(__CUDA_ARCH__) +#pragma warning (push) +#pragma warning (disable: 4127) +#endif /* _MSC_VER && !defined(__CUDA_ARCH__) */ + if (sizeof(unsigned long int) == sizeof(unsigned int)) { +#if defined(_MSC_VER) && !defined(__CUDA_ARCH__) +#pragma warning (pop) +#endif /* _MSC_VER && !defined(__CUDA_ARCH__) */ + retval = static_cast(umin(static_cast(a), static_cast(b))); + } else { + retval = static_cast(ullmin(static_cast(a), static_cast(b))); + } + return retval; +} + +__MATH_FUNCTIONS_DECL__ unsigned long int min(const long int a, const unsigned long int b) +{ + unsigned long int retval; +#if defined(_MSC_VER) && !defined(__CUDA_ARCH__) +#pragma warning (push) +#pragma warning (disable: 4127) +#endif /* _MSC_VER && !defined(__CUDA_ARCH__) */ + if (sizeof(unsigned long int) == sizeof(unsigned int)) { +#if defined(_MSC_VER) && !defined(__CUDA_ARCH__) +#pragma warning (pop) +#endif /* _MSC_VER && !defined(__CUDA_ARCH__) */ + retval = static_cast(umin(static_cast(a), static_cast(b))); + } else { + retval = static_cast(ullmin(static_cast(a), static_cast(b))); + } + return retval; +} + +__MATH_FUNCTIONS_DECL__ unsigned long int min(const unsigned long int a, const long int b) +{ + unsigned long int retval; +#if defined(_MSC_VER) && !defined(__CUDA_ARCH__) +#pragma warning (push) +#pragma warning (disable: 4127) +#endif /* _MSC_VER && !defined(__CUDA_ARCH__) */ + if (sizeof(unsigned long int) == sizeof(unsigned int)) { +#if defined(_MSC_VER) && !defined(__CUDA_ARCH__) +#pragma warning (pop) +#endif /* _MSC_VER && !defined(__CUDA_ARCH__) */ + retval = static_cast(umin(static_cast(a), static_cast(b))); + } else { + retval = static_cast(ullmin(static_cast(a), static_cast(b))); + } + return retval; +} + +__MATH_FUNCTIONS_DECL__ long long int min(const long long int a, const long long int b) +{ + return llmin(a, b); +} + +__MATH_FUNCTIONS_DECL__ unsigned long long int min(const unsigned long long int a, const unsigned long long int b) +{ + return ullmin(a, b); +} + +__MATH_FUNCTIONS_DECL__ unsigned long long int min(const long long int a, const unsigned long long int b) +{ + return ullmin(static_cast(a), b); +} + +__MATH_FUNCTIONS_DECL__ unsigned long long int min(const unsigned long long int a, const long long int b) +{ + return ullmin(a, static_cast(b)); +} + +__MATH_FUNCTIONS_DECL__ float min(const float a, const float b) +{ + return fminf(a, b); +} + +__MATH_FUNCTIONS_DECL__ double min(const double a, const double b) +{ + return fmin(a, b); +} + +__MATH_FUNCTIONS_DECL__ double min(const float a, const double b) +{ + return fmin(static_cast(a), b); +} + +__MATH_FUNCTIONS_DECL__ double min(const double a, const float b) +{ + return fmin(a, static_cast(b)); +} + +__MATH_FUNCTIONS_DECL__ unsigned int max(const unsigned int a, const unsigned int b) +{ + return umax(a, b); +} + +__MATH_FUNCTIONS_DECL__ unsigned int max(const int a, const unsigned int b) +{ + return umax(static_cast(a), b); +} + +__MATH_FUNCTIONS_DECL__ unsigned int max(const unsigned int a, const int b) +{ + return umax(a, static_cast(b)); +} + +__MATH_FUNCTIONS_DECL__ long int max(const long int a, const long int b) +{ + long int retval; + /* long can be of 32-bit type on some systems. */ +#if defined(_MSC_VER) && !defined(__CUDA_ARCH__) +#pragma warning (push) +#pragma warning (disable: 4127) +#endif /* _MSC_VER && !defined(__CUDA_ARCH__) */ + if (sizeof(long int) == sizeof(int)) { +#if defined(_MSC_VER) && !defined(__CUDA_ARCH__) +#pragma warning (pop) +#endif /* _MSC_VER && !defined(__CUDA_ARCH__) */ + retval = static_cast(max(static_cast(a), static_cast(b))); + } else { + retval = static_cast(llmax(static_cast(a), static_cast(b))); + } + return retval; +} + +__MATH_FUNCTIONS_DECL__ unsigned long int max(const unsigned long int a, const unsigned long int b) +{ + unsigned long int retval; +#if defined(_MSC_VER) && !defined(__CUDA_ARCH__) +#pragma warning (push) +#pragma warning (disable: 4127) +#endif /* _MSC_VER && !defined(__CUDA_ARCH__) */ + if (sizeof(unsigned long int) == sizeof(unsigned int)) { +#if defined(_MSC_VER) && !defined(__CUDA_ARCH__) +#pragma warning (pop) +#endif /* _MSC_VER && !defined(__CUDA_ARCH__) */ + retval = static_cast(umax(static_cast(a), static_cast(b))); + } else { + retval = static_cast(ullmax(static_cast(a), static_cast(b))); + } + return retval; +} + +__MATH_FUNCTIONS_DECL__ unsigned long int max(const long int a, const unsigned long int b) +{ + unsigned long int retval; +#if defined(_MSC_VER) && !defined(__CUDA_ARCH__) +#pragma warning (push) +#pragma warning (disable: 4127) +#endif /* _MSC_VER && !defined(__CUDA_ARCH__) */ + if (sizeof(unsigned long int) == sizeof(unsigned int)) { +#if defined(_MSC_VER) && !defined(__CUDA_ARCH__) +#pragma warning (pop) +#endif /* _MSC_VER && !defined(__CUDA_ARCH__) */ + retval = static_cast(umax(static_cast(a), static_cast(b))); + } else { + retval = static_cast(ullmax(static_cast(a), static_cast(b))); + } + return retval; +} + +__MATH_FUNCTIONS_DECL__ unsigned long int max(const unsigned long int a, const long int b) +{ + unsigned long int retval; +#if defined(_MSC_VER) && !defined(__CUDA_ARCH__) +#pragma warning (push) +#pragma warning (disable: 4127) +#endif /* _MSC_VER && !defined(__CUDA_ARCH__) */ + if (sizeof(unsigned long int) == sizeof(unsigned int)) { +#if defined(_MSC_VER) && !defined(__CUDA_ARCH__) +#pragma warning (pop) +#endif /* _MSC_VER && !defined(__CUDA_ARCH__) */ + retval = static_cast(umax(static_cast(a), static_cast(b))); + } else { + retval = static_cast(ullmax(static_cast(a), static_cast(b))); + } + return retval; +} + +__MATH_FUNCTIONS_DECL__ long long int max(const long long int a, const long long int b) +{ + return llmax(a, b); +} + +__MATH_FUNCTIONS_DECL__ unsigned long long int max(const unsigned long long int a, const unsigned long long int b) +{ + return ullmax(a, b); +} + +__MATH_FUNCTIONS_DECL__ unsigned long long int max(const long long int a, const unsigned long long int b) +{ + return ullmax(static_cast(a), b); +} + +__MATH_FUNCTIONS_DECL__ unsigned long long int max(const unsigned long long int a, const long long int b) +{ + return ullmax(a, static_cast(b)); +} + +__MATH_FUNCTIONS_DECL__ float max(const float a, const float b) +{ + return fmaxf(a, b); +} + +__MATH_FUNCTIONS_DECL__ double max(const double a, const double b) +{ + return fmax(a, b); +} + +__MATH_FUNCTIONS_DECL__ double max(const float a, const double b) +{ + return fmax(static_cast(a), b); +} + +__MATH_FUNCTIONS_DECL__ double max(const double a, const float b) +{ + return fmax(a, static_cast(b)); +} + + +#if !defined(__CUDA_ARCH__) +#if defined(_WIN32) +#define __HELPER_FUNC_LINKAGE static inline __host__ __device__ +#pragma warning (push) +#pragma warning (disable : 4211) +#else /* !defined(_WIN32) */ +#define __HELPER_FUNC_LINKAGE inline __host__ __device__ +#endif /* defined(_WIN32) */ + +__HELPER_FUNC_LINKAGE int min(const int a, const int b) +{ + return (a < b) ? a : b; +} + +__HELPER_FUNC_LINKAGE unsigned int umin(const unsigned int a, const unsigned int b) +{ + return (a < b) ? a : b; +} + +__HELPER_FUNC_LINKAGE long long int llmin(const long long int a, const long long int b) +{ + return (a < b) ? a : b; +} + +__HELPER_FUNC_LINKAGE unsigned long long int ullmin(const unsigned long long int a, + const unsigned long long int b) +{ + return (a < b) ? a : b; +} + +__HELPER_FUNC_LINKAGE int max(const int a, const int b) +{ + return (a > b) ? a : b; +} + +__HELPER_FUNC_LINKAGE unsigned int umax(const unsigned int a, const unsigned int b) +{ + return (a > b) ? a : b; +} + +__HELPER_FUNC_LINKAGE long long int llmax(const long long int a, const long long int b) +{ + return (a > b) ? a : b; +} + +__HELPER_FUNC_LINKAGE unsigned long long int ullmax(const unsigned long long int a, + const unsigned long long int b) +{ + return (a > b) ? a : b; +} + +#if defined(_WIN32) +#pragma warning (pop) +#endif /* defined(_WIN32) */ + +#undef __HELPER_FUNC_LINKAGE + +#endif /* !defined(__CUDA_ARCH__) */ + +#undef __MATH_FUNCTIONS_DECL__ +#undef __MATH_FUNCTIONS_DEVICE_DECL__ + +/******************************************************************************* +* * +* * +* * +*******************************************************************************/ + +#endif /* __cplusplus && __CUDACC__ */ +#if !defined(__CUDACC__) + +#include "host_defines.h" +#include "math_constants.h" + +#define __cuda_INT_MAX \ + ((int)((unsigned int)-1 >> 1)) + +/******************************************************************************* +* * +* ONLY FOR HOST CODE! NOT FOR DEVICE EXECUTION * +* * +*******************************************************************************/ + +#include + +#if defined(_WIN32) +#pragma warning (push) +#pragma warning (disable : 4211) + +#endif /* _WIN32 */ + +#if defined(_WIN32) || defined(__APPLE__) || defined (__ANDROID__) || defined(__QNX__) + +__func__(int __isnan(const double a)) +{ + unsigned long long int l; + memcpy(&l, &a, sizeof(double)); + return (l << 1ULL) > 0xffe0000000000000ULL; +} + +#endif /* _WIN32 || __APPLE__ || __ANDROID__ || __QNX__ */ + +#if defined(_WIN32) || defined(__APPLE__) || defined(__QNX__) + +/******************************************************************************* +* * +* HOST IMPLEMENTATION FOR DOUBLE ROUTINES FOR WINDOWS & APPLE PLATFORMS * +* * +*******************************************************************************/ + +__func__(double exp10(const double a)) +{ + return pow(10.0, a); +} + +__func__(float exp10f(const float a)) +{ + return static_cast(exp10(static_cast(a))); +} + +__func__(void sincos(const double a, double *sptr, double *cptr)) +{ + *sptr = sin(a); + *cptr = cos(a); +} + +__func__(void sincosf(const float a, float *sptr, float *cptr)) +{ + double s, c; + + sincos(static_cast(a), &s, &c); + *sptr = static_cast(s); + *cptr = static_cast(c); +} + +__func__(int __isinf(const double a)) +{ + unsigned long long int l; + memcpy(&l, &a, sizeof(double)); + return (l << 1ULL) == 0xffe0000000000000ULL; +} + +#endif /* _WIN32 || __APPLE__ */ + +#if defined(_WIN32) || defined (__ANDROID__) + +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +__func__(double log2(const double a)) +{ + return log(a) * 1.44269504088896340; +} +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ + +#endif /* _WIN32 || __ANDROID__ */ + +#if defined(_WIN32) + +/******************************************************************************* +* * +* HOST IMPLEMENTATION FOR DOUBLE ROUTINES FOR WINDOWS PLATFORM * +* * +*******************************************************************************/ + +__func__(int __signbit(double a)) +{ + signed long long int l; + memcpy(&l, &a, sizeof(double)); + return l < 0LL; +} + +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +__func__(double copysign(double a, double b)) +{ + unsigned long long int la, lb; + memcpy(&la, &a, sizeof(double)); + memcpy(&lb, &b, sizeof(double)); + la = (la & 0x7fffffffffffffffULL) | (lb & 0x8000000000000000ULL); + memcpy(&a, &la, sizeof(double)); + return a; +} +#endif /* MSC_VER < 1800 */ + +__func__(int __finite(double a)) +{ + unsigned long long int l; + memcpy(&l, &a, sizeof(double)); + return (l << 1ULL) < 0xffe0000000000000ULL; +} + +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +__func__(double fmax(double a, double b)) +{ + if (__isnan(a) && __isnan(b)) return a + b; + if (__isnan(a)) return b; + if (__isnan(b)) return a; + if ((a == 0.0) && (b == 0.0) && __signbit(b)) return a; + return a > b ? a : b; +} + +__func__(double fmin(double a, double b)) +{ + if (__isnan(a) && __isnan(b)) return a + b; + if (__isnan(a)) return b; + if (__isnan(b)) return a; + if ((a == 0.0) && (b == 0.0) && __signbit(a)) return a; + return a < b ? a : b; +} + +__func__(double trunc(double a)) +{ + return a < 0.0 ? ceil(a) : floor(a); +} + +__func__(double round(double a)) +{ + double fa = fabs(a); + + if (fa > CUDART_TWO_TO_52) { + return a; + } else { + double u = floor(fa + 0.5); + if (fa < 0.5) u = 0; + u = copysign (u, a); + return u; + } +} + +__func__(long int lround(double a)) +{ + return static_cast(round(a)); +} + +__func__(long long int llround(double a)) +{ + return static_cast(round(a)); +} + +__func__(double rint(double a)) +{ + double fa = fabs(a); + double u = CUDART_TWO_TO_52 + fa; + if (fa >= CUDART_TWO_TO_52) { + u = a; + } else { + u = u - CUDART_TWO_TO_52; + u = copysign (u, a); + } + return u; +} + +__func__(double nearbyint(double a)) +{ + return rint(a); +} + +__func__(long int lrint(double a)) +{ + return static_cast(rint(a)); +} + +__func__(long long int llrint(double a)) +{ + return static_cast(rint(a)); +} + +__func__(double fdim(double a, double b)) +{ + if (a > b) { + return (a - b); + } else if (a <= b) { + return 0.0; + } else if (__isnan(a)) { + return a; + } else { + return b; + } +} + +__func__(double scalbn(double a, int b)) +{ + return ldexp(a, b); +} + +__func__(double scalbln(double a, long int b)) +{ + int t; + + if (b > 2147483647L) { + t = 2147483647; + } else if (b < (-2147483647 - 1)) { + t = (-2147483647 - 1); + } else { + t = static_cast(b); + } + return scalbn(a, t); +} + +__func__(double exp2(double a)) +{ + return pow(2.0, a); +} + +/* + * The following is based on: David Goldberg, "What every computer scientist + * should know about floating-point arithmetic", ACM Computing Surveys, Volume + * 23, Issue 1, March 1991. + */ +__func__(double log1p(double a)) +{ + volatile double u, m; + + u = 1.0 + a; + if (u == 1.0) { + /* a very close to zero */ + u = a; + } else { + m = u - 1.0; + u = log(u); + if (a < 1.0) { + /* a somewhat close to zero */ + u = a * u; + u = u / m; + } + } + return u; +} + +/* + * This code based on: http://www.cs.berkeley.edu/~wkahan/Math128/Sumnfp.pdf + */ +__func__(double expm1(double a)) +{ + volatile double u, m; + + u = exp(a); + m = u - 1.0; + if (m == 0.0) { + /* a very close zero */ + m = a; + } + else if (fabs(a) < 1.0) { + /* a somewhat close zero */ + u = log(u); + m = m * a; + m = m / u; + } + return m; +} + +__func__(double cbrt(double a)) +{ + double s, t; + + if (a == 0.0 || __isinf(a)) { + return a; + } + s = fabs(a); + t = exp2(CUDART_THIRD * log2(s)); /* initial approximation */ + t = t - (t - (s / (t * t))) * CUDART_THIRD; /* refine approximation */ + t = copysign(t, a); + return t; +} + +__func__(double acosh(double a)) +{ + double s, t; + + t = a - 1.0; + if (t == a) { + return log(2.0) + log(a); + } else { + s = a + 1.0; + t = t + sqrt(s * t); + return log1p(t); + } +} + +__func__(double asinh(double a)) +{ + double fa, oofa, t; + + fa = fabs(a); + if (fa > 1e18) { + t = log(2.0) + log(fa); + } else { + oofa = 1.0 / fa; + t = fa + fa / (oofa + sqrt(1.0 + oofa * oofa)); + t = log1p(t); + } + t = copysign(t, a); + return t; +} + +__func__(double atanh(double a)) +{ + double fa, t; + + if (__isnan(a)) { + return a + a; + } + fa = fabs(a); + t = (2.0 * fa) / (1.0 - fa); + t = 0.5 * log1p(t); + if (__isnan(t) || !__signbit(a)) { + return t; + } + return -t; +} + +__func__(int ilogb(double a)) +{ + unsigned long long int i; + int expo = -1022; + + if (__isnan(a)) return -__cuda_INT_MAX-1; + if (__isinf(a)) return __cuda_INT_MAX; + memcpy(&i, &a, sizeof(double)); + i = i & 0x7fffffffffffffffULL; + if (i == 0) return -__cuda_INT_MAX-1; + if (i >= 0x0010000000000000ULL) { + return (int)(((i >> 52ULL) & 0x7ffU) - 1023); + } + while (i < 0x0010000000000000ULL) { + expo--; + i <<= 1; + } + return expo; +} + +__func__(double logb(double a)) +{ + unsigned long long int i; + int expo = -1022; + + if (__isnan(a)) return a + a; + if (__isinf(a)) return fabs(a); + memcpy(&i, &a, sizeof(double)); + i = i & 0x7fffffffffffffffULL; + if (i == 0) return -1.0/fabs(a); + if (i >= 0x0010000000000000ULL) { + return (double)((int)((i >> 52ULL) & 0x7ffU) - 1023); + } + while (i < 0x0010000000000000ULL) { + expo--; + i <<= 1; + } + return static_cast(expo); +} + +__func__(double remquo(double a, double b, int *quo)) +{ + unsigned long long int aa, bb; + int rem1 = 1; /* do FPREM1, a.k.a IEEE remainder */ + int expo_a; + int expo_b; + unsigned long long mant_a; + unsigned long long mant_b; + unsigned long long mant_c; + unsigned long long temp; + int sign_a; + int sign_b; + int sign_c; + int expo_c; + int expodiff; + int quot = 0; /* initialize quotient */ + int l; + int iter; + + memcpy(&aa, &a, sizeof(double)); + mant_a = (aa << 11ULL) | 0x8000000000000000ULL; + expo_a = (int)((aa >> 52ULL) & 0x7ffU) - 1023; + sign_a = (int)(aa >> 63ULL); + + memcpy(&bb, &b, sizeof(double)); + mant_b = (bb << 11ULL) | 0x8000000000000000ULL; + expo_b = (int)((bb >> 52ULL) & 0x7ffU) - 1023; + sign_b = (int)(bb >> 63ULL); + + sign_c = sign_a; /* remainder has sign of dividend */ + expo_c = expo_a; /* default */ + + /* handled NaNs and infinities */ + if (__isnan(a) || __isnan(b)) { + *quo = quot; + return a + b; + } + if (__isinf(a) || (b == 0.0)) { + *quo = quot; + aa = 0xfff8000000000000ULL; + memcpy(&a, &aa, sizeof(double)); + return a; + } + if ((a == 0.0) || (__isinf(b))) { + *quo = quot; + return a; + } + /* normalize denormals */ + if (expo_a < -1022) { + mant_a = mant_a + mant_a; + while (mant_a < 0x8000000000000000ULL) { + mant_a = mant_a + mant_a; + expo_a--; + } + } + if (expo_b < -1022) { + mant_b = mant_b + mant_b; + while (mant_b < 0x8000000000000000ULL) { + mant_b = mant_b + mant_b; + expo_b--; + } + } + expodiff = expo_a - expo_b; + /* clamp iterations if exponent difference negative */ + if (expodiff < 0) { + iter = -1; + } else { + iter = expodiff; + } + /* Shift dividend and divisor right by one bit to prevent overflow + during the division algorithm. + */ + mant_a = mant_a >> 1ULL; + mant_b = mant_b >> 1ULL; + expo_c = expo_a - iter; /* default exponent of result */ + + /* Use binary longhand division (restoring) */ + for (l = 0; l < (iter + 1); l++) { + mant_a = mant_a - mant_b; + if (mant_a & 0x8000000000000000ULL) { + mant_a = mant_a + mant_b; + quot = quot + quot; + } else { + quot = quot + quot + 1; + } + mant_a = mant_a + mant_a; + } + + /* Save current remainder */ + mant_c = mant_a; + /* If remainder's mantissa is all zeroes, final result is zero. */ + if (mant_c == 0) { + quot = quot & 7; + *quo = (sign_a ^ sign_b) ? -quot : quot; + aa = static_cast(sign_c) << 63ULL; + memcpy(&a, &aa, sizeof(double)); + return a; + } + /* Normalize result */ + while (!(mant_c & 0x8000000000000000ULL)) { + mant_c = mant_c + mant_c; + expo_c--; + } + /* For IEEE remainder (quotient rounded to nearest-even we might need to + do a final subtraction of the divisor from the remainder. + */ + if (rem1 && ((expodiff+1) >= 0)) { + temp = mant_a - mant_b; + /* round quotient to nearest even */ + if (((temp != 0ULL) && (!(temp & 0x8000000000000000ULL))) || + ((temp == 0ULL) && (quot & 1))) { + mant_a = mant_a >> 1ULL; + quot++; + /* Since the divisor is greater than the remainder, the result will + have opposite sign of the dividend. To avoid a negative mantissa + when subtracting the divisor from remainder, reverse subtraction + */ + sign_c = 1 ^ sign_c; + expo_c = expo_a - iter + 1; + mant_c = mant_b - mant_a; + /* normalize result */ + while (!(mant_c & 0x8000000000000000ULL)) { + mant_c = mant_c + mant_c; + expo_c--; + } + } + } + /* package up result */ + if (expo_c >= -1022) { /* normal */ + mant_c = ((mant_c >> 11ULL) + + (((static_cast(sign_c)) << 63ULL) + + (((unsigned long long)(expo_c + 1022)) << 52ULL))); + } else { /* denormal */ + mant_c = (((static_cast(sign_c)) << 63ULL) + + (mant_c >> (unsigned long long)(11 - expo_c - 1022))); + } + quot = quot & 7; /* mask quotient down to least significant three bits */ + *quo = (sign_a ^ sign_b) ? -quot : quot; + memcpy(&a, &mant_c, sizeof(double)); + return a; +} + +__func__(double remainder(double a, double b)) +{ + int quo; + return remquo (a, b, &quo); +} + +__func__(double fma (double a, double b, double c)) +{ + struct { + unsigned int lo; + unsigned int hi; + } xx, yy, zz, ww; + double d; + unsigned int s, t, u, prod0, prod1, prod2, prod3, expo_x, expo_y, expo_z; + + memcpy(&xx, &a, sizeof(double)); + memcpy(&yy, &b, sizeof(double)); + memcpy(&zz, &c, sizeof(double)); + + expo_z = 0x7FFU; + t = xx.hi >> 20; + expo_x = expo_z & t; + expo_x = expo_x - 1; /* expo(x) - 1 */ + t = yy.hi >> 20; + expo_y = expo_z & t; + expo_y = expo_y - 1; /* expo(y) - 1 */ + t = zz.hi >> 20; + expo_z = expo_z & t; + expo_z = expo_z - 1; /* expo(z) - 1 */ + + if (!((expo_x <= 0x7FDU) && + (expo_y <= 0x7FDU) && + (expo_z <= 0x7FDU))) { + + /* fma (nan, y, z) --> nan + fma (x, nan, z) --> nan + fma (x, y, nan) --> nan + */ + if (((yy.hi << 1) | (yy.lo != 0)) > 0xffe00000U) { + yy.hi |= 0x00080000U; + memcpy(&d, &yy, sizeof(double)); + return d; + } + if (((zz.hi << 1) | (zz.lo != 0)) > 0xffe00000U) { + zz.hi |= 0x00080000U; + memcpy(&d, &zz, sizeof(double)); + return d; + } + if (((xx.hi << 1) | (xx.lo != 0)) > 0xffe00000U) { + xx.hi |= 0x00080000U; + memcpy(&d, &xx, sizeof(double)); + return d; + } + + /* fma (0, inf, z) --> INDEFINITE + fma (inf, 0, z) --> INDEFINITE + fma (-inf,+y,+inf) --> INDEFINITE + fma (+x,-inf,+inf) --> INDEFINITE + fma (+inf,-y,+inf) --> INDEFINITE + fma (-x,+inf,+inf) --> INDEFINITE + fma (-inf,-y,-inf) --> INDEFINITE + fma (-x,-inf,-inf) --> INDEFINITE + fma (+inf,+y,-inf) --> INDEFINITE + fma (+x,+inf,-inf) --> INDEFINITE + */ + if (((((xx.hi << 1) | xx.lo) == 0) && + (((yy.hi << 1) | (yy.lo != 0)) == 0xffe00000U)) || + ((((yy.hi << 1) | yy.lo) == 0) && + (((xx.hi << 1) | (xx.lo != 0)) == 0xffe00000U))) { + xx.hi = 0xfff80000U; + xx.lo = 0x00000000U; + memcpy(&d, &xx, sizeof(double)); + return d; + } + if (((zz.hi << 1) | (zz.lo != 0)) == 0xffe00000U) { + if ((((yy.hi << 1) | (yy.lo != 0)) == 0xffe00000U) || + (((xx.hi << 1) | (xx.lo != 0)) == 0xffe00000U)) { + if ((int)(xx.hi ^ yy.hi ^ zz.hi) < 0) { + xx.hi = 0xfff80000U; + xx.lo = 0x00000000U; + memcpy(&d, &xx, sizeof(double)); + return d; + } + } + } + /* fma (inf, y, z) --> inf + fma (x, inf, z) --> inf + fma (x, y, inf) --> inf + */ + if (((xx.hi << 1) | (xx.lo != 0)) == 0xffe00000U) { + xx.hi = xx.hi ^ (yy.hi & 0x80000000U); + memcpy(&d, &xx, sizeof(double)); + return d; + } + if (((yy.hi << 1) | (yy.lo != 0)) == 0xffe00000U) { + yy.hi = yy.hi ^ (xx.hi & 0x80000000U); + memcpy(&d, &yy, sizeof(double)); + return d; + } + if (((zz.hi << 1) | (zz.lo != 0)) == 0xffe00000U) { + memcpy(&d, &zz, sizeof(double)); + return d; + } + /* fma (+0, -y, -0) --> -0 + fma (-0, +y, -0) --> -0 + fma (+x, -0, -0) --> -0 + fma (-x, +0, -0) --> -0 + */ + if ((zz.hi == 0x80000000U) && (zz.lo == 0)) { + if ((((xx.hi << 1) | xx.lo) == 0) || + (((yy.hi << 1) | yy.lo) == 0)) { + if ((int)(xx.hi ^ yy.hi) < 0) { + memcpy(&d, &zz, sizeof(double)); + return d; + } + } + } + /* fma (0, y, 0) --> +0 (-0 if round down and signs of addend differ) + fma (x, 0, 0) --> +0 (-0 if round down and signs of addend differ) + */ + if ((((zz.hi << 1) | zz.lo) == 0) && + ((((xx.hi << 1) | xx.lo) == 0) || + (((yy.hi << 1) | yy.lo) == 0))) { + zz.hi &= 0x7fffffffU; + memcpy(&d, &zz, sizeof(double)); + return d; + } + + /* fma (0, y, z) --> z + fma (x, 0, z) --> z + */ + if ((((xx.hi << 1) | xx.lo) == 0) || + (((yy.hi << 1) | yy.lo) == 0)) { + memcpy(&d, &zz, sizeof(double)); + return d; + } + + if (expo_x == 0xffffffffU) { + expo_x++; + t = xx.hi & 0x80000000U; + s = xx.lo >> 21; + xx.lo = xx.lo << 11; + xx.hi = xx.hi << 11; + xx.hi = xx.hi | s; + if (!xx.hi) { + xx.hi = xx.lo; + xx.lo = 0; + expo_x -= 32; + } + while (static_cast(xx.hi) > 0) { + s = xx.lo >> 31; + xx.lo = xx.lo + xx.lo; + xx.hi = xx.hi + xx.hi; + xx.hi = xx.hi | s; + expo_x--; + } + xx.lo = (xx.lo >> 11); + xx.lo |= (xx.hi << 21); + xx.hi = (xx.hi >> 11) | t; + } + if (expo_y == 0xffffffffU) { + expo_y++; + t = yy.hi & 0x80000000U; + s = yy.lo >> 21; + yy.lo = yy.lo << 11; + yy.hi = yy.hi << 11; + yy.hi = yy.hi | s; + if (!yy.hi) { + yy.hi = yy.lo; + yy.lo = 0; + expo_y -= 32; + } + while (static_cast(yy.hi) > 0) { + s = yy.lo >> 31; + yy.lo = yy.lo + yy.lo; + yy.hi = yy.hi + yy.hi; + yy.hi = yy.hi | s; + expo_y--; + } + yy.lo = (yy.lo >> 11); + yy.lo |= (yy.hi << 21); + yy.hi = (yy.hi >> 11) | t; + } + if (expo_z == 0xffffffffU) { + expo_z++; + t = zz.hi & 0x80000000U; + s = zz.lo >> 21; + zz.lo = zz.lo << 11; + zz.hi = zz.hi << 11; + zz.hi = zz.hi | s; + if (!zz.hi) { + zz.hi = zz.lo; + zz.lo = 0; + expo_z -= 32; + } + while (static_cast(zz.hi) > 0) { + s = zz.lo >> 31; + zz.lo = zz.lo + zz.lo; + zz.hi = zz.hi + zz.hi; + zz.hi = zz.hi | s; + expo_z--; + } + zz.lo = (zz.lo >> 11); + zz.lo |= (zz.hi << 21); + zz.hi = (zz.hi >> 11) | t; + } + } + + expo_x = expo_x + expo_y; + expo_y = xx.hi ^ yy.hi; + t = xx.lo >> 21; + xx.lo = xx.lo << 11; + xx.hi = xx.hi << 11; + xx.hi = xx.hi | t; + yy.hi = yy.hi & 0x000fffffU; + xx.hi = xx.hi | 0x80000000U; /* set mantissa hidden bit */ + yy.hi = yy.hi | 0x00100000U; /* set mantissa hidden bit */ + + prod0 = xx.lo * yy.lo; + prod1 =(unsigned)((static_cast(xx.lo)*static_cast(yy.lo))>>32ULL); + prod2 = xx.hi * yy.lo; + prod3 = xx.lo * yy.hi; + prod1 += prod2; + t = (unsigned)(prod1 < prod2); + prod1 += prod3; + t += prod1 < prod3; + prod2 =(unsigned)((static_cast(xx.hi)*static_cast(yy.lo))>>32ULL); + prod3 =(unsigned)((static_cast(xx.lo)*static_cast(yy.hi))>>32ULL); + prod2 += prod3; + s = (unsigned)(prod2 < prod3); + prod3 = xx.hi * yy.hi; + prod2 += prod3; + s += prod2 < prod3; + prod2 += t; + s += prod2 < t; + prod3 =(unsigned)((static_cast(xx.hi)*static_cast(yy.hi))>>32ULL); + prod3 = prod3 + s; + + yy.lo = prod0; /* mantissa */ + yy.hi = prod1; /* mantissa */ + xx.lo = prod2; /* mantissa */ + xx.hi = prod3; /* mantissa */ + expo_x = expo_x - (1023 - 2); /* expo-1 */ + expo_y = expo_y & 0x80000000U; /* sign */ + + if (xx.hi < 0x00100000U) { + s = xx.lo >> 31; + s = (xx.hi << 1) + s; + xx.hi = s; + s = yy.hi >> 31; + s = (xx.lo << 1) + s; + xx.lo = s; + s = yy.lo >> 31; + s = (yy.hi << 1) + s; + yy.hi = s; + s = yy.lo << 1; + yy.lo = s; + expo_x--; + } + + t = 0; + if (((zz.hi << 1) | zz.lo) != 0) { /* z is not zero */ + + s = zz.hi & 0x80000000U; + + zz.hi &= 0x000fffffU; + zz.hi |= 0x00100000U; + ww.hi = 0; + ww.lo = 0; + + /* compare and swap. put augend into xx:yy */ + if (static_cast(expo_z) > static_cast(expo_x)) { + t = expo_z; + expo_z = expo_x; + expo_x = t; + t = zz.hi; + zz.hi = xx.hi; + xx.hi = t; + t = zz.lo; + zz.lo = xx.lo; + xx.lo = t; + t = ww.hi; + ww.hi = yy.hi; + yy.hi = t; + t = ww.lo; + ww.lo = yy.lo; + yy.lo = t; + t = expo_y; + expo_y = s; + s = t; + } + + /* augend_sign = expo_y, augend_mant = xx:yy, augend_expo = expo_x */ + /* addend_sign = s, addend_mant = zz:ww, addend_expo = expo_z */ + expo_z = expo_x - expo_z; + u = expo_y ^ s; + if (expo_z <= 107) { + /* denormalize addend */ + t = 0; + while (expo_z >= 32) { + t = ww.lo | (t != 0); + ww.lo = ww.hi; + ww.hi = zz.lo; + zz.lo = zz.hi; + zz.hi = 0; + expo_z -= 32; + } + if (expo_z) { + t = (t >> expo_z) | (ww.lo << (32 - expo_z)) | + ((t << (32 - expo_z)) != 0); + ww.lo = (ww.lo >> expo_z) | (ww.hi << (32 - expo_z)); + ww.hi = (ww.hi >> expo_z) | (zz.lo << (32 - expo_z)); + zz.lo = (zz.lo >> expo_z) | (zz.hi << (32 - expo_z)); + zz.hi = (zz.hi >> expo_z); + } + } else { + t = 1; + ww.lo = 0; + ww.hi = 0; + zz.lo = 0; + zz.hi = 0; + } + if (static_cast(u) < 0) { + /* signs differ, effective subtraction */ + t = (unsigned)(-static_cast(t)); + s = (unsigned)(t != 0); + u = yy.lo - s; + s = (unsigned)(u > yy.lo); + yy.lo = u - ww.lo; + s += yy.lo > u; + u = yy.hi - s; + s = (unsigned)(u > yy.hi); + yy.hi = u - ww.hi; + s += yy.hi > u; + u = xx.lo - s; + s = (unsigned)(u > xx.lo); + xx.lo = u - zz.lo; + s += xx.lo > u; + xx.hi = (xx.hi - zz.hi) - s; + if (!(xx.hi | xx.lo | yy.hi | yy.lo | t)) { + /* complete cancelation, return 0 */ + memcpy(&d, &xx, sizeof(double)); + return d; + } + if (static_cast(xx.hi) < 0) { + /* Oops, augend had smaller mantissa. Negate mantissa and flip + sign of result + */ + t = ~t; + yy.lo = ~yy.lo; + yy.hi = ~yy.hi; + xx.lo = ~xx.lo; + xx.hi = ~xx.hi; + if (++t == 0) { + if (++yy.lo == 0) { + if (++yy.hi == 0) { + if (++xx.lo == 0) { + ++xx.hi; + } + } + } + } + expo_y ^= 0x80000000U; + } + + /* normalize mantissa, if necessary */ + while (!(xx.hi & 0x00100000U)) { + xx.hi = (xx.hi << 1) | (xx.lo >> 31); + xx.lo = (xx.lo << 1) | (yy.hi >> 31); + yy.hi = (yy.hi << 1) | (yy.lo >> 31); + yy.lo = (yy.lo << 1); + expo_x--; + } + } else { + /* signs are the same, effective addition */ + yy.lo = yy.lo + ww.lo; + s = (unsigned)(yy.lo < ww.lo); + yy.hi = yy.hi + s; + u = (unsigned)(yy.hi < s); + yy.hi = yy.hi + ww.hi; + u += yy.hi < ww.hi; + xx.lo = xx.lo + u; + s = (unsigned)(xx.lo < u); + xx.lo = xx.lo + zz.lo; + s += xx.lo < zz.lo; + xx.hi = xx.hi + zz.hi + s; + if (xx.hi & 0x00200000U) { + t = t | (yy.lo << 31); + yy.lo = (yy.lo >> 1) | (yy.hi << 31); + yy.hi = (yy.hi >> 1) | (xx.lo << 31); + xx.lo = (xx.lo >> 1) | (xx.hi << 31); + xx.hi = ((xx.hi & 0x80000000U) | (xx.hi >> 1)) & ~0x40000000U; + expo_x++; + } + } + } + t = yy.lo | (t != 0); + t = yy.hi | (t != 0); + + xx.hi |= expo_y; /* or in sign bit */ + if (expo_x <= 0x7FDU) { + /* normal */ + xx.hi = xx.hi & ~0x00100000U; /* lop off integer bit */ + s = xx.lo & 1; /* mantissa lsb */ + u = xx.lo; + xx.lo += (t == 0x80000000U) ? s : (t >> 31); + xx.hi += (u > xx.lo); + xx.hi += ((expo_x + 1) << 20); + memcpy(&d, &xx, sizeof(double)); + return d; + } else if (static_cast(expo_x) >= 2046) { + /* overflow */ + xx.hi = (xx.hi & 0x80000000U) | 0x7ff00000U; + xx.lo = 0; + memcpy(&d, &xx, sizeof(double)); + return d; + } + /* subnormal */ + expo_x = (unsigned)(-static_cast(expo_x)); + if (expo_x > 54) { + xx.hi = xx.hi & 0x80000000U; + xx.lo = 0; + memcpy(&d, &xx, sizeof(double)); + return d; + } + yy.hi = xx.hi & 0x80000000U; /* save sign bit */ + xx.hi = xx.hi & ~0xffe00000U; + if (expo_x >= 32) { + t = xx.lo | (t != 0); + xx.lo = xx.hi; + xx.hi = 0; + expo_x -= 32; + } + if (expo_x) { + t = (t >> expo_x) | (xx.lo << (32 - expo_x)) | (t != 0); + xx.lo = (xx.lo >> expo_x) | (xx.hi << (32 - expo_x)); + xx.hi = (xx.hi >> expo_x); + } + expo_x = xx.lo & 1; + u = xx.lo; + xx.lo += (t == 0x80000000U) ? expo_x : (t >> 31); + xx.hi += (u > xx.lo); + xx.hi |= yy.hi; + memcpy(&d, &xx, sizeof(double)); + return d; +} + +__func__(double nextafter(double a, double b)) +{ + unsigned long long int ia; + unsigned long long int ib; + memcpy(&ia, &a, sizeof(double)); + memcpy(&ib, &b, sizeof(double)); + if (__isnan(a) || __isnan(b)) return a + b; /* NaN */ + if (((ia | ib) << 1ULL) == 0ULL) return b; + if (a == 0.0) { + return copysign (4.9406564584124654e-324, b); /* crossover */ + } + if ((a < b) && (a < 0.0)) ia--; + if ((a < b) && (a > 0.0)) ia++; + if ((a > b) && (a < 0.0)) ia++; + if ((a > b) && (a > 0.0)) ia--; + memcpy(&a, &ia, sizeof(double)); + return a; +} + +__func__(double erf(double a)) +{ + double t, r, q; + + t = fabs(a); + if (t >= 1.0) { + r = -1.28836351230756500E-019; + r = r * t + 1.30597472161093370E-017; + r = r * t - 6.33924401259620500E-016; + r = r * t + 1.96231865908940140E-014; + r = r * t - 4.35272243559990750E-013; + r = r * t + 7.37083927929352150E-012; + r = r * t - 9.91402142550461630E-011; + r = r * t + 1.08817017167760820E-009; + r = r * t - 9.93918713097634620E-009; + r = r * t + 7.66739923255145500E-008; + r = r * t - 5.05440278302806720E-007; + r = r * t + 2.87474157099000620E-006; + r = r * t - 1.42246725399722510E-005; + r = r * t + 6.16994555079419460E-005; + r = r * t - 2.36305221938908790E-004; + r = r * t + 8.05032844055371070E-004; + r = r * t - 2.45833366629108140E-003; + r = r * t + 6.78340988296706120E-003; + r = r * t - 1.70509103597554640E-002; + r = r * t + 3.93322852515666300E-002; + r = r * t - 8.37271292613764040E-002; + r = r * t + 1.64870423707623280E-001; + r = r * t - 2.99729521787681470E-001; + r = r * t + 4.99394435612628580E-001; + r = r * t - 7.52014596480123030E-001; + r = r * t + 9.99933138314926250E-001; + r = r * t - 1.12836725321102670E+000; + r = r * t + 9.99998988715182450E-001; + q = exp (-t * t); + r = 1.0 - r * q; + if (t >= 6.5) { + r = 1.0; + } + a = copysign (r, a); + } else { + q = a * a; + r = -7.77946848895991420E-010; + r = r * q + 1.37109803980285950E-008; + r = r * q - 1.62063137584932240E-007; + r = r * q + 1.64471315712790040E-006; + r = r * q - 1.49247123020098620E-005; + r = r * q + 1.20552935769006260E-004; + r = r * q - 8.54832592931448980E-004; + r = r * q + 5.22397760611847340E-003; + r = r * q - 2.68661706431114690E-002; + r = r * q + 1.12837916709441850E-001; + r = r * q - 3.76126389031835210E-001; + r = r * q + 1.12837916709551260E+000; + a = r * a; + } + return a; +} + +__func__(double erfc(double a)) +{ + double p, q, h, l; + + if (a < 0.75) { + return 1.0 - erf(a); + } + if (a > 27.3) { + return 0.0; + } + if (a < 5.0) { + double t; + t = 1.0 / a; + p = 1.9759923722227928E-008; + p = p * t - 1.0000002670474897E+000; + p = p * t - 7.4935303236347828E-001; + p = p * t - 1.5648136328071860E-001; + p = p * t + 1.2871196242447239E-001; + p = p * t + 1.1126459974811195E-001; + p = p * t + 4.0678642255914332E-002; + p = p * t + 7.9915414156678296E-003; + p = p * t + 7.1458332107840234E-004; + q = t + 2.7493547525030619E+000; + q = q * t + 3.3984254815725423E+000; + q = q * t + 2.4635304979947761E+000; + q = q * t + 1.1405284734691286E+000; + q = q * t + 3.4130157606195649E-001; + q = q * t + 6.2250967676044953E-002; + q = q * t + 5.5661370941268700E-003; + q = q * t + 1.0575248365468671E-009; + p = p / q; + p = p * t; + h = ((int)(a * 16.0)) * 0.0625; + l = (a - h) * (a + h); + q = exp(-h * h) * exp(-l); + q = q * 0.5; + p = p * q + q; + p = p * t; + } else { + double ooa, ooasq; + + ooa = 1.0 / a; + ooasq = ooa * ooa; + p = -4.0025406686930527E+005; + p = p * ooasq + 1.4420582543942123E+005; + p = p * ooasq - 2.7664185780951841E+004; + p = p * ooasq + 4.1144611644767283E+003; + p = p * ooasq - 5.8706000519209351E+002; + p = p * ooasq + 9.1490086446323375E+001; + p = p * ooasq - 1.6659491387740221E+001; + p = p * ooasq + 3.7024804085481784E+000; + p = p * ooasq - 1.0578553994424316E+000; + p = p * ooasq + 4.2314218745087778E-001; + p = p * ooasq - 2.8209479177354962E-001; + p = p * ooasq + 5.6418958354775606E-001; + h = a * a; + h = ((int)(a * 16.0)) * 0.0625; + l = (a - h) * (a + h); + q = exp(-h * h) * exp(-l); + p = p * ooa; + p = p * q; + } + return p; +} + +__func__(double lgamma(double a)) +{ + double s; + double t; + double i; + double fa; + double sum; + long long int quot; + if (__isnan(a) || __isinf(a)) { + return a * a; + } + fa = fabs(a); + if (fa >= 3.0) { + if (fa >= 8.0) { + /* Stirling approximation; coefficients from Hart et al, "Computer + * Approximations", Wiley 1968. Approximation 5404. + */ + s = 1.0 / fa; + t = s * s; + sum = -0.1633436431e-2; + sum = sum * t + 0.83645878922e-3; + sum = sum * t - 0.5951896861197e-3; + sum = sum * t + 0.793650576493454e-3; + sum = sum * t - 0.277777777735865004e-2; + sum = sum * t + 0.833333333333331018375e-1; + sum = sum * s + 0.918938533204672; + s = 0.5 * log (fa); + t = fa - 0.5; + s = s * t; + t = s - fa; + s = s + sum; + t = t + s; + } else { + i = fa - 3.0; + s = -4.02412642744125560E+003; + s = s * i - 2.97693796998962000E+005; + s = s * i - 6.38367087682528790E+006; + s = s * i - 5.57807214576539320E+007; + s = s * i - 2.24585140671479230E+008; + s = s * i - 4.70690608529125090E+008; + s = s * i - 7.62587065363263010E+008; + s = s * i - 9.71405112477113250E+008; + t = i - 1.02277248359873170E+003; + t = t * i - 1.34815350617954480E+005; + t = t * i - 4.64321188814343610E+006; + t = t * i - 6.48011106025542540E+007; + t = t * i - 4.19763847787431360E+008; + t = t * i - 1.25629926018000720E+009; + t = t * i - 1.40144133846491690E+009; + t = s / t; + t = t + i; + } + } else if (fa >= 1.5) { + i = fa - 2.0; + t = 9.84839283076310610E-009; + t = t * i - 6.69743850483466500E-008; + t = t * i + 2.16565148880011450E-007; + t = t * i - 4.86170275781575260E-007; + t = t * i + 9.77962097401114400E-007; + t = t * i - 2.03041287574791810E-006; + t = t * i + 4.36119725805364580E-006; + t = t * i - 9.43829310866446590E-006; + t = t * i + 2.05106878496644220E-005; + t = t * i - 4.49271383742108440E-005; + t = t * i + 9.94570466342226000E-005; + t = t * i - 2.23154589559238440E-004; + t = t * i + 5.09669559149637430E-004; + t = t * i - 1.19275392649162300E-003; + t = t * i + 2.89051032936815490E-003; + t = t * i - 7.38555102806811700E-003; + t = t * i + 2.05808084278121250E-002; + t = t * i - 6.73523010532073720E-002; + t = t * i + 3.22467033424113040E-001; + t = t * i + 4.22784335098467190E-001; + t = t * i; + } else if (fa >= 0.7) { + i = 1.0 - fa; + t = 1.17786911519331130E-002; + t = t * i + 3.89046747413522300E-002; + t = t * i + 5.90045711362049900E-002; + t = t * i + 6.02143305254344420E-002; + t = t * i + 5.61652708964839180E-002; + t = t * i + 5.75052755193461370E-002; + t = t * i + 6.21061973447320710E-002; + t = t * i + 6.67614724532521880E-002; + t = t * i + 7.14856037245421020E-002; + t = t * i + 7.69311251313347100E-002; + t = t * i + 8.33503129714946310E-002; + t = t * i + 9.09538288991182800E-002; + t = t * i + 1.00099591546322310E-001; + t = t * i + 1.11334278141734510E-001; + t = t * i + 1.25509666613462880E-001; + t = t * i + 1.44049896457704160E-001; + t = t * i + 1.69557177031481600E-001; + t = t * i + 2.07385551032182120E-001; + t = t * i + 2.70580808427600350E-001; + t = t * i + 4.00685634386517050E-001; + t = t * i + 8.22467033424113540E-001; + t = t * i + 5.77215664901532870E-001; + t = t * i; + } else { + t = -9.04051686831357990E-008; + t = t * fa + 7.06814224969349250E-007; + t = t * fa - 3.80702154637902830E-007; + t = t * fa - 2.12880892189316100E-005; + t = t * fa + 1.29108470307156190E-004; + t = t * fa - 2.15932815215386580E-004; + t = t * fa - 1.16484324388538480E-003; + t = t * fa + 7.21883433044470670E-003; + t = t * fa - 9.62194579514229560E-003; + t = t * fa - 4.21977386992884450E-002; + t = t * fa + 1.66538611813682460E-001; + t = t * fa - 4.20026350606819980E-002; + t = t * fa - 6.55878071519427450E-001; + t = t * fa + 5.77215664901523870E-001; + t = t * fa; + t = t * fa + fa; + t = -log (t); + } + if (a >= 0.0) return t; + if (fa < 1e-19) return -log(fa); + i = floor(fa); + if (fa == i) return 1.0 / (fa - i); /* a is an integer: return infinity */ + i = rint (2.0 * fa); + quot = static_cast(i); + i = fa - 0.5 * i; + i = i * CUDART_PI; + if (quot & 1) { + i = cos(i); + } else { + i = sin(i); + } + i = fabs(i); + t = log(CUDART_PI / (i * fa)) - t; + return t; +} + +__func__(unsigned long long int __internal_host_nan_kernel(const char *s)) +{ + unsigned long long i = 0; + int c; + int ovfl = 0; + int invld = 0; + if (s && (*s == '0')) { + s++; + if ((*s == 'x') || (*s == 'X')) { + s++; + while (*s == '0') s++; + while (*s) { + if (i > 0x0fffffffffffffffULL) { + ovfl = 1; + } + c = (((*s) >= 'A') && ((*s) <= 'F')) ? (*s + 'a' - 'A') : (*s); + if ((c >= 'a') && (c <= 'f')) { + c = c - 'a' + 10; + i = i * 16 + c; + } else if ((c >= '0') && (c <= '9')) { + c = c - '0'; + i = i * 16 + c; + } else { + invld = 1; + } + s++; + } + } else { + while (*s == '0') s++; + while (*s) { + if (i > 0x1fffffffffffffffULL) { + ovfl = 1; + } + c = *s; + if ((c >= '0') && (c <= '7')) { + c = c - '0'; + i = i * 8 + c; + } else { + invld = 1; + } + s++; + } + } + } else if (s) { + while (*s) { + c = *s; + if ((i > 1844674407370955161ULL) || + ((i == 1844674407370955161ULL) && (c > '5'))) { + ovfl = 1; + } + if ((c >= '0') && (c <= '9')) { + c = c - '0'; + i = i * 10 + c; + } else { + invld = 1; + } + s++; + } + } + if (ovfl) { + i = ~0ULL; + } + if (invld) { + i = 0ULL; + } + i = (i & 0x000fffffffffffffULL) | 0x7ff8000000000000ULL; + return i; +} + +__func__(double nan(const char *tagp)) +{ + unsigned long long l; + double d; + l = __internal_host_nan_kernel(tagp); + memcpy(&d, &l, sizeof(double)); + return d; +} + +__func__(double __host_tgamma_kernel(double a)) +{ + double t; + t = - 4.4268934071252475E-010; + t = t * a - 2.0266591846658954E-007; + t = t * a + 1.1381211721119527E-006; + t = t * a - 1.2507734816630748E-006; + t = t * a - 2.0136501740408771E-005; + t = t * a + 1.2805012607354486E-004; + t = t * a - 2.1524140811527418E-004; + t = t * a - 1.1651675459704604E-003; + t = t * a + 7.2189432248466381E-003; + t = t * a - 9.6219715326862632E-003; + t = t * a - 4.2197734554722394E-002; + t = t * a + 1.6653861138250356E-001; + t = t * a - 4.2002635034105444E-002; + t = t * a - 6.5587807152025712E-001; + t = t * a + 5.7721566490153287E-001; + t = t * a + 1.0000000000000000E+000; + return t; +} + +__func__(double __host_stirling_poly(double a)) +{ + double x = 1.0 / a; + double z = 0.0; + z = + 8.3949872067208726e-004; + z = z * x - 5.1717909082605919e-005; + z = z * x - 5.9216643735369393e-004; + z = z * x + 6.9728137583658571e-005; + z = z * x + 7.8403922172006662e-004; + z = z * x - 2.2947209362139917e-004; + z = z * x - 2.6813271604938273e-003; + z = z * x + 3.4722222222222220e-003; + z = z * x + 8.3333333333333329e-002; + z = z * x + 1.0000000000000000e+000; + return z; +} + +__func__(double __host_tgamma_stirling(double a)) +{ + double z; + double x; + z = __host_stirling_poly (a); + if (a < 142.0) { + x = pow (a, a - 0.5); + a = x * exp (-a); + a = a * CUDART_SQRT_2PI; + return a * z; + } else if (a < 172.0) { + x = pow (a, 0.5 * a - 0.25); + a = x * exp (-a); + a = a * CUDART_SQRT_2PI; + a = a * z; + return a * x; + } else { + return exp(1000.0); /* INF */ + } +} + +__func__(double tgamma(double a)) +{ + double s, xx, x = a; + if (__isnan(a)) { + return a + a; + } + if (fabs(x) < 20.0) { + if (x >= 0.0) { + s = 1.0; + xx = x; + while (xx > 1.5) { + xx = xx - 1.0; + s = s * xx; + } + if (x >= 0.5) { + xx = xx - 1.0; + } + xx = __host_tgamma_kernel (xx); + if (x < 0.5) { + xx = xx * x; + } + s = s / xx; + } else { + xx = x; + s = xx; + if (x == floor(x)) { + return 0.0 / (x - floor(x)); + } + while (xx < -0.5) { + xx = xx + 1.0; + s = s * xx; + } + xx = __host_tgamma_kernel (xx); + s = s * xx; + s = 1.0 / s; + } + return s; + } else { + if (x >= 0.0) { + return __host_tgamma_stirling (x); + } else { + double t; + int quot; + if (x == floor(x)) { + return 0.0 / (x - floor(x)); + } + if (x < -185.0) { + int negative; + x = floor(x); + negative = ((x - (2.0 * floor(0.5 * x))) == 1.0); + return negative ? (-1.0 / 1e308 / 1e308) : CUDART_ZERO; + } + /* compute sin(pi*x) accurately */ + xx = rint (2.0 * x); + quot = static_cast(xx); + xx = -0.5 * xx + x; + xx = xx * CUDART_PI; + if (quot & 1) { + xx = cos (xx); + } else { + xx = sin (xx); + } + if (quot & 2) { + xx = -xx; + } + x = fabs (x); + s = exp (-x); + t = x - 0.5; + if (x > 140.0) t = 0.5 * t; + t = pow (x, t); + if (x > 140.0) s = s * t; + s = s * __host_stirling_poly (x); + s = s * x; + s = s * xx; + s = 1.0 / s; + s = s * CUDART_SQRT_PIO2; + s = s / t; + return s; + } + } +} +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ + +/******************************************************************************* +* * +* HOST IMPLEMENTATION FOR FLOAT AND LONG DOUBLE ROUTINES FOR WINDOWS PLATFORM * +* MAP FLOAT AND LONG DOUBLE ROUTINES TO DOUBLE ROUTINES * +* * +*******************************************************************************/ + +__func__(int __signbitl(const long double a)) +{ + return __signbit(static_cast(a)); +} + +__func__(int __signbitf(const float a)) +{ + return __signbit(static_cast(a)); +} + +__func__(int __finitel(const long double a)) +{ + return __finite(static_cast(a)); +} + +__func__(int __finitef(const float a)) +{ + return __finite(static_cast(a)); +} + +__func__(int __isinfl(const long double a)) +{ + return __isinf(static_cast(a)); +} + +__func__(int __isinff(const float a)) +{ + return __isinf(static_cast(a)); +} + +__func__(int __isnanl(const long double a)) +{ + return __isnan(static_cast(a)); +} + +__func__(int __isnanf(const float a)) +{ + return __isnan(static_cast(a)); +} + +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +__func__(float fmaxf(const float a, const float b)) +{ + return static_cast(fmax(static_cast(a), static_cast(b))); +} + +__func__(float fminf(const float a, const float b)) +{ + return static_cast(fmin(static_cast(a), static_cast(b))); +} + +__func__(float roundf(const float a)) +{ + return static_cast(round(static_cast(a))); +} + +__func__(long int lroundf(const float a)) +{ + return lround(static_cast(a)); +} + +__func__(long long int llroundf(const float a)) +{ + return llround(static_cast(a)); +} + +__func__(float truncf(const float a)) +{ + return static_cast(trunc(static_cast(a))); +} + +__func__(float rintf(const float a)) +{ + return static_cast(rint(static_cast(a))); +} + +__func__(float nearbyintf(const float a)) +{ + return static_cast(nearbyint(static_cast(a))); +} + +__func__(long int lrintf(const float a)) +{ + return lrint(static_cast(a)); +} + +__func__(long long int llrintf(const float a)) +{ + return llrint(static_cast(a)); +} + +__func__(float logbf(const float a)) +{ + return static_cast(logb(static_cast(a))); +} + +__func__(float scalblnf(const float a, const long int b)) +{ + return static_cast(scalbln(static_cast(a), b)); +} + +__func__(float log2f(const float a)) +{ + return static_cast(log2(static_cast(a))); +} + +__func__(float exp2f(const float a)) +{ + return static_cast(exp2(static_cast(a))); +} + +__func__(float acoshf(const float a)) +{ + return static_cast(acosh(static_cast(a))); +} + +__func__(float asinhf(const float a)) +{ + return static_cast(asinh(static_cast(a))); +} + +__func__(float atanhf(const float a)) +{ + return static_cast(atanh(static_cast(a))); +} + +__func__(float cbrtf(const float a)) +{ + return static_cast(cbrt(static_cast(a))); +} + +__func__(float expm1f(const float a)) +{ + return static_cast(expm1(static_cast(a))); +} + +__func__(float fdimf(const float a, const float b)) +{ + return static_cast(fdim(static_cast(a), static_cast(b))); +} + +__func__(float log1pf(const float a)) +{ + return static_cast(log1p(static_cast(a))); +} + +__func__(float scalbnf(const float a, const int b)) +{ + return static_cast(scalbn(static_cast(a), b)); +} + +__func__(float fmaf(const float a, const float b, const float c)) +{ + return static_cast(fma(static_cast(a), static_cast(b), static_cast(c))); +} + +__func__(int ilogbf(const float a)) +{ + return ilogb(static_cast(a)); +} + +__func__(float erff(const float a)) +{ + return static_cast(erf(static_cast(a))); +} + +__func__(float erfcf(const float a)) +{ + return static_cast(erfc(static_cast(a))); +} + +__func__(float lgammaf(const float a)) +{ + return static_cast(lgamma(static_cast(a))); +} + +__func__(float tgammaf(const float a)) +{ + return static_cast(tgamma(static_cast(a))); +} + +__func__(float remquof(const float a, const float b, int *quo)) +{ + return static_cast(remquo(static_cast(a), static_cast(b), quo)); +} + +__func__(float remainderf(const float a, const float b)) +{ + return static_cast(remainder(static_cast(a), static_cast(b))); +} +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ + +#if (defined _MSC_VER) && (_MSC_VER >= 1700) +__func__(float j0f(const float a)) +{ + return static_cast(_j0(static_cast(a))); +} + +__func__(float j1f(const float a)) +{ + return static_cast(_j1(static_cast(a))); +} + +__func__(float jnf(const int n, const float a)) +{ + return static_cast(_jn(n, static_cast(a))); +} + +__func__(float y0f(const float a)) +{ + return static_cast(_y0(static_cast(a))); +} + +__func__(float y1f(const float a)) +{ + return static_cast(_y1(static_cast(a))); +} + +__func__(float ynf(const int n, const float a)) +{ + return static_cast(_yn(n, static_cast(a))); +} +#endif /* (defined _MSC_VER) && (_MSC_VER >= 1700) */ + + +/******************************************************************************* +* * +* HOST IMPLEMENTATION FOR FLOAT ROUTINES FOR WINDOWS PLATFORM * +* * +*******************************************************************************/ + +#if (!defined(_MSC_VER) || _MSC_VER < 1800) +__func__(float copysignf(float a, const float b)) +{ + unsigned int aa, bb; + memcpy(&aa, &a, sizeof(float)); + memcpy(&bb, &b, sizeof(float)); + aa = (aa & ~0x80000000U) | (bb & 0x80000000U); + memcpy(&a, &aa, sizeof(float)); + return a; +} + +__func__(float nextafterf(float a, const float b)) +{ + unsigned int ia; + unsigned int ib; + memcpy(&ia, &a, sizeof(float)); + memcpy(&ib, &b, sizeof(float)); + if (__isnanf(a) || __isnanf(b)) return a + b; /*NaN*/ + if (((ia | ib) << 1U) == 0U) return b; + if (a == 0.0F) { + return copysignf(1.401298464e-045F, b); /*crossover*/ + } + if ((a < b) && (a < 0.0F)) ia--; + if ((a < b) && (a > 0.0F)) ia++; + if ((a > b) && (a < 0.0F)) ia++; + if ((a > b) && (a > 0.0F)) ia--; + memcpy(&a, &ia, sizeof(float)); + return a; +} + +__func__(float nanf(const char *tagp)) +{ + float f; + unsigned int i; + i = static_cast(__internal_host_nan_kernel(tagp)); + i = (i & 0x007fffffU) | 0x7fc00000U; + memcpy(&f, &i, sizeof(float)); + return f; +} + +#endif /* (!defined(_MSC_VER) || _MSC_VER < 1800) */ + +#endif /* _WIN32 */ + +/******************************************************************************* +* * +* HOST IMPLEMENTATION FOR DOUBLE AND FLOAT ROUTINES. ALL PLATFORMS * +* * +*******************************************************************************/ + +__func__(double rsqrt(const double a)) +{ + return 1.0 / sqrt(a); +} + +__func__(double rcbrt(const double a)) +{ + double s, t; + + if (__isnan(a)) { + return a + a; + } + if (a == 0.0 || __isinf(a)) { + return 1.0 / a; + } + s = fabs(a); + t = exp2(-CUDART_THIRD * log2(s)); /* initial approximation */ + t = ((t*t) * (-s*t) + 1.0) * (CUDART_THIRD*t) + t;/* refine approximation */ +#if defined(__APPLE__) + if (__signbitd(a)) +#else /* __APPLE__ */ + if (__signbit(a)) +#endif /* __APPLE__ */ + { + t = -t; + } + return t; +} + +__func__(double sinpi(double a)) +{ + int n; + + if (__isnan(a)) { + return a + a; + } + if (a == 0.0 || __isinf(a)) { + return sin (a); + } + if (a == floor(a)) { + return ((a / 1.0e308) / 1.0e308) / 1.0e308; + } + double twoa = a + a; + double rtwoa = round(twoa); + long long int l = (long long int)rtwoa; + n = (int)l; + a -= rtwoa * 0.5; + a = a * CUDART_PI; + if (n & 1) { + a = cos (a); + } else { + a = sin (a); + } + if (n & 2) { + a = -a; + } + return a; +} + +__func__(double cospi(double a)) +{ + int n; + + if (__isnan(a)) { + return a + a; + } + if (__isinf(a)) { + return cos (a); + } + if (fabs(a) > 9.0071992547409920e+015) { + a = 0.0; + } + double twoa = a + a; + double rtwoa = round(twoa); + long long int l = (long long int)rtwoa; + n = (int)l; + a -= rtwoa * 0.5; + a = a * CUDART_PI; + n++; + if (n & 1) { + a = cos (a); + } else { + a = sin (a); + } + if (n & 2) { + a = -a; + } + if (a == 0.0) { + a = fabs(a); + } + return a; +} + +__func__(void sincospi(const double a, double *sptr, double *cptr)) +{ + *sptr = sinpi(a); + *cptr = cospi(a); +} + +__func__(double erfinv(const double a)) +{ + double p, q, t, fa; + unsigned long long int l; + + fa = fabs(a); + if (fa >= 1.0) { + l = 0xfff8000000000000ULL; + memcpy(&t, &l, sizeof(double)); /* INDEFINITE */ + if (fa == 1.0) { + t = a * exp(1000.0); /* Infinity */ + } + } else if (fa >= 0.9375) { + /* Based on: J.M. Blair, C.A. Edwards, J.H. Johnson: Rational Chebyshev + Approximations for the Inverse of the Error Function. Mathematics of + Computation, Vol. 30, No. 136 (Oct. 1976), pp. 827-830. Table 59 + */ + t = log1p(-fa); + t = 1.0 / sqrt(-t); + p = 2.7834010353747001060e-3; + p = p * t + 8.6030097526280260580e-1; + p = p * t + 2.1371214997265515515e+0; + p = p * t + 3.1598519601132090206e+0; + p = p * t + 3.5780402569085996758e+0; + p = p * t + 1.5335297523989890804e+0; + p = p * t + 3.4839207139657522572e-1; + p = p * t + 5.3644861147153648366e-2; + p = p * t + 4.3836709877126095665e-3; + p = p * t + 1.3858518113496718808e-4; + p = p * t + 1.1738352509991666680e-6; + q = t + 2.2859981272422905412e+0; + q = q * t + 4.3859045256449554654e+0; + q = q * t + 4.6632960348736635331e+0; + q = q * t + 3.9846608184671757296e+0; + q = q * t + 1.6068377709719017609e+0; + q = q * t + 3.5609087305900265560e-1; + q = q * t + 5.3963550303200816744e-2; + q = q * t + 4.3873424022706935023e-3; + q = q * t + 1.3858762165532246059e-4; + q = q * t + 1.1738313872397777529e-6; + t = p / (q * t); + if (a < 0.0) t = -t; + } else if (fa >= 0.75) { + /* Based on: J.M. Blair, C.A. Edwards, J.H. Johnson: Rational Chebyshev + Approximations for the Inverse of the Error Function. Mathematics of + Computation, Vol. 30, No. 136 (Oct. 1976), pp. 827-830. Table 39 + */ + t = a * a - .87890625; + p = .21489185007307062000e+0; + p = p * t - .64200071507209448655e+1; + p = p * t + .29631331505876308123e+2; + p = p * t - .47644367129787181803e+2; + p = p * t + .34810057749357500873e+2; + p = p * t - .12954198980646771502e+2; + p = p * t + .25349389220714893917e+1; + p = p * t - .24758242362823355486e+0; + p = p * t + .94897362808681080020e-2; + q = t - .12831383833953226499e+2; + q = q * t + .41409991778428888716e+2; + q = q * t - .53715373448862143349e+2; + q = q * t + .33880176779595142685e+2; + q = q * t - .11315360624238054876e+2; + q = q * t + .20369295047216351160e+1; + q = q * t - .18611650627372178511e+0; + q = q * t + .67544512778850945940e-2; + p = p / q; + t = a * p; + } else { + /* Based on: J.M. Blair, C.A. Edwards, J.H. Johnson: Rational Chebyshev + Approximations for the Inverse of the Error Function. Mathematics of + Computation, Vol. 30, No. 136 (Oct. 1976), pp. 827-830. Table 18 + */ + t = a * a - .5625; + p = - .23886240104308755900e+2; + p = p * t + .45560204272689128170e+3; + p = p * t - .22977467176607144887e+4; + p = p * t + .46631433533434331287e+4; + p = p * t - .43799652308386926161e+4; + p = p * t + .19007153590528134753e+4; + p = p * t - .30786872642313695280e+3; + q = t - .83288327901936570000e+2; + q = q * t + .92741319160935318800e+3; + q = q * t - .35088976383877264098e+4; + q = q * t + .59039348134843665626e+4; + q = q * t - .48481635430048872102e+4; + q = q * t + .18997769186453057810e+4; + q = q * t - .28386514725366621129e+3; + p = p / q; + t = a * p; + } + return t; +} + +__func__(double erfcinv(const double a)) +{ + double t; + unsigned long long int l; + + if (__isnan(a)) { + return a + a; + } + if (a <= 0.0) { + l = 0xfff8000000000000ULL; + memcpy(&t, &l, sizeof(double)); /* INDEFINITE */ + if (a == 0.0) { + t = (1.0 - a) * exp(1000.0); /* Infinity */ + } + } + else if (a >= 0.0625) { + t = erfinv (1.0 - a); + } + else if (a >= 1e-100) { + /* Based on: J.M. Blair, C.A. Edwards, J.H. Johnson: Rational Chebyshev + Approximations for the Inverse of the Error Function. Mathematics of + Computation, Vol. 30, No. 136 (Oct. 1976), pp. 827-830. Table 59 + */ + double p, q; + t = log(a); + t = 1.0 / sqrt(-t); + p = 2.7834010353747001060e-3; + p = p * t + 8.6030097526280260580e-1; + p = p * t + 2.1371214997265515515e+0; + p = p * t + 3.1598519601132090206e+0; + p = p * t + 3.5780402569085996758e+0; + p = p * t + 1.5335297523989890804e+0; + p = p * t + 3.4839207139657522572e-1; + p = p * t + 5.3644861147153648366e-2; + p = p * t + 4.3836709877126095665e-3; + p = p * t + 1.3858518113496718808e-4; + p = p * t + 1.1738352509991666680e-6; + q = t + 2.2859981272422905412e+0; + q = q * t + 4.3859045256449554654e+0; + q = q * t + 4.6632960348736635331e+0; + q = q * t + 3.9846608184671757296e+0; + q = q * t + 1.6068377709719017609e+0; + q = q * t + 3.5609087305900265560e-1; + q = q * t + 5.3963550303200816744e-2; + q = q * t + 4.3873424022706935023e-3; + q = q * t + 1.3858762165532246059e-4; + q = q * t + 1.1738313872397777529e-6; + t = p / (q * t); + } + else { + /* Based on: J.M. Blair, C.A. Edwards, J.H. Johnson: Rational Chebyshev + Approximations for the Inverse of the Error Function. Mathematics of + Computation, Vol. 30, No. 136 (Oct. 1976), pp. 827-830. Table 82 + */ + double p, q; + t = log(a); + t = 1.0 / sqrt(-t); + p = 6.9952990607058154858e-1; + p = p * t + 1.9507620287580568829e+0; + p = p * t + 8.2810030904462690216e-1; + p = p * t + 1.1279046353630280005e-1; + p = p * t + 6.0537914739162189689e-3; + p = p * t + 1.3714329569665128933e-4; + p = p * t + 1.2964481560643197452e-6; + p = p * t + 4.6156006321345332510e-9; + p = p * t + 4.5344689563209398450e-12; + q = t + 1.5771922386662040546e+0; + q = q * t + 2.1238242087454993542e+0; + q = q * t + 8.4001814918178042919e-1; + q = q * t + 1.1311889334355782065e-1; + q = q * t + 6.0574830550097140404e-3; + q = q * t + 1.3715891988350205065e-4; + q = q * t + 1.2964671850944981713e-6; + q = q * t + 4.6156017600933592558e-9; + q = q * t + 4.5344687377088206783e-12; + t = p / (q * t); + } + return t; +} + +__func__(double normcdfinv(const double a)) +{ + return -1.4142135623730951 * erfcinv(a + a); +} + +__func__(double normcdf(double a)) +{ + double ah, al, t1, t2, u1, u2, v1, v2, z; + if (fabs (a) > 38.5) a = copysign (38.5, a); + ah = a * 134217729.0; + u1 = (a - ah) + ah; + u2 = a - u1; + v1 = -7.0710678398609161e-01; + v2 = 2.7995440410322203e-09; + t1 = a * -CUDART_SQRT_HALF_HI; + t2 = (((u1 * v1 - t1) + u1 * v2) + u2 * v1) + u2 * v2; + t2 = (a * -CUDART_SQRT_HALF_LO) + t2; + ah = t1 + t2; + z = erfc (ah); + if (a < -1.0) { + al = (t1 - ah) + t2; + t1 = -2.0 * ah * z; + z = t1 * al + z; + } + return 0.5 * z; +} + +__func__(double erfcx(const double a)) +{ + double x, t1, t2, t3; + + if (__isnan(a)) { + return a + a; + } + x = fabs(a); + if (x < 32.0) { + /* + * This implementation of erfcx() is based on the algorithm in: M. M. + * Shepherd and J. G. Laframboise, "Chebyshev Approximation of (1 + 2x) + * exp(x^2)erfc x in 0 <= x < INF", Mathematics of Computation, Vol. + * 36, No. 153, January 1981, pp. 249-253. For the core approximation, + * the input domain [0,INF] is transformed via (x-k) / (x+k) where k is + * a precision-dependent constant. Here, we choose k = 4.0, so the input + * domain [0, 27.3] is transformed into the core approximation domain + * [-1, 0.744409]. + */ + /* + // Compute (1+2*x)*exp(x*x)*erfc(x) + */ + /* t2 = (x-4.0)/(x+4.0), transforming [0,INF] to [-1,+1] */ + t1 = x - 4.0; + t2 = x + 4.0; + t2 = t1 / t2; + /* approximate on [-1, 0.744409] */ + t1 = - 3.5602694826817400E-010; + t1 = t1 * t2 - 9.7239122591447274E-009; + t1 = t1 * t2 - 8.9350224851649119E-009; + t1 = t1 * t2 + 1.0404430921625484E-007; + t1 = t1 * t2 + 5.8806698585341259E-008; + t1 = t1 * t2 - 8.2147414929116908E-007; + t1 = t1 * t2 + 3.0956409853306241E-007; + t1 = t1 * t2 + 5.7087871844325649E-006; + t1 = t1 * t2 - 1.1231787437600085E-005; + t1 = t1 * t2 - 2.4399558857200190E-005; + t1 = t1 * t2 + 1.5062557169571788E-004; + t1 = t1 * t2 - 1.9925637684786154E-004; + t1 = t1 * t2 - 7.5777429182785833E-004; + t1 = t1 * t2 + 5.0319698792599572E-003; + t1 = t1 * t2 - 1.6197733895953217E-002; + t1 = t1 * t2 + 3.7167515553018733E-002; + t1 = t1 * t2 - 6.6330365827532434E-002; + t1 = t1 * t2 + 9.3732834997115544E-002; + t1 = t1 * t2 - 1.0103906603555676E-001; + t1 = t1 * t2 + 6.8097054254735140E-002; + t1 = t1 * t2 + 1.5379652102605428E-002; + t1 = t1 * t2 - 1.3962111684056291E-001; + t1 = t1 * t2 + 1.2329951186255526E+000; + /* + // Note: (1+2*x)*exp(x*x)*erfc(x) / (1+2*x) = exp(x*x)*erfc(x) + */ + t2 = 2.0 * x + 1.0; + t1 = t1 / t2; + } else { + /* asymptotic expansion for large aguments */ + t2 = 1.0 / x; + t3 = t2 * t2; + t1 = -29.53125; + t1 = t1 * t3 + 6.5625; + t1 = t1 * t3 - 1.875; + t1 = t1 * t3 + 0.75; + t1 = t1 * t3 - 0.5; + t1 = t1 * t3 + 1.0; + t2 = t2 * 5.6418958354775628e-001; + t1 = t1 * t2; + } + if (a < 0.0) { + /* + // Note: erfcx(x) = 2*exp(x^2) - erfcx(|x|) + */ + t2 = (static_cast(x * 16.0)) * 0.0625; + t3 = (x - t2) * (x + t2); + t3 = exp(t2 * t2) * exp(t3); + t3 = t3 + t3; + t1 = t3 - t1; + } + return t1; +} + +__func__(float rsqrtf(const float a)) +{ + return static_cast(rsqrt(static_cast(a))); +} + +__func__(float rcbrtf(const float a)) +{ + return static_cast(rcbrt(static_cast(a))); +} + +__func__(float sinpif(const float a)) +{ + return static_cast(sinpi(static_cast(a))); +} + +__func__(float cospif(const float a)) +{ + return static_cast(cospi(static_cast(a))); +} + +__func__(void sincospif(const float a, float *sptr, float *cptr)) +{ + double s, c; + + sincospi(static_cast(a), &s, &c); + *sptr = static_cast(s); + *cptr = static_cast(c); +} + +__func__(float erfinvf(const float a)) +{ + return static_cast(erfinv(static_cast(a))); +} + +__func__(float erfcinvf(const float a)) +{ + return static_cast(erfcinv(static_cast(a))); +} + +__func__(float normcdfinvf(const float a)) +{ + return static_cast(normcdfinv(static_cast(a))); +} + +__func__(float normcdff(const float a)) +{ + return static_cast(normcdf(static_cast(a))); +} + +__func__(float erfcxf(const float a)) +{ + return static_cast(erfcx(static_cast(a))); +} + +#if defined(_WIN32) +#pragma warning (pop) +#endif /* _WIN32 */ + +#endif /* !__CUDACC__ */ + +#endif /* !__MATH_FUNCTIONS_HPP__ */ + +#if defined(__UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_MATH_FUNCTIONS_HPP__) +#undef __CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__ +#undef __UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_MATH_FUNCTIONS_HPP__ +#endif diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/mma.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/mma.h new file mode 100644 index 0000000000000000000000000000000000000000..7d0b79141f65461e0384f34f9e30c482969041ca --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/mma.h @@ -0,0 +1,761 @@ +/* + * Copyright 2017-2024 NVIDIA Corporation. All rights reserved. + * + * NOTICE TO LICENSEE: + * + * This source code and/or documentation ("Licensed Deliverables") are + * subject to NVIDIA intellectual property rights under U.S. and + * international Copyright laws. + * + * These Licensed Deliverables contained herein is PROPRIETARY and + * CONFIDENTIAL to NVIDIA and is being provided under the terms and + * conditions of a form of NVIDIA software license agreement by and + * between NVIDIA and Licensee ("License Agreement") or electronically + * accepted by Licensee. Notwithstanding any terms or conditions to + * the contrary in the License Agreement, reproduction or disclosure + * of the Licensed Deliverables to any third party without the express + * written consent of NVIDIA is prohibited. + * + * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE + * LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE + * SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE. IT IS + * PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND. + * NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED + * DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY, + * NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE. + * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE + * LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY + * SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY + * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS + * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THESE LICENSED DELIVERABLES. + * + * U.S. Government End Users. These Licensed Deliverables are a + * "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT + * 1995), consisting of "commercial computer software" and "commercial + * computer software documentation" as such terms are used in 48 + * C.F.R. 12.212 (SEPT 1995) and is provided to the U.S. Government + * only as a commercial end item. Consistent with 48 C.F.R.12.212 and + * 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all + * U.S. Government End Users acquire the Licensed Deliverables with + * only those rights set forth herein. + * + * Any use of the Licensed Deliverables in individual and commercial + * software must include, in the user documentation and internal + * comments to the code, the above Disclaimer and U.S. Government End + * Users Notice. + */ + +#if !defined(__CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__) +#if defined(_MSC_VER) +#pragma message("crt/mma.h is an internal header file and must not be used directly. Please use mma.h instead.") +#else +#warning "crt/mma.h is an internal header file and must not be used directly. Please use mma.h instead." +#endif +#define __CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__ +#define __UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_CUDA_MMA_H__ +#endif + +#if !defined(__CUDA_MMA_H__) +#define __CUDA_MMA_H__ + +#include +#include + +#define __CUDA_MMA_DEVICE_DECL__ static __device__ __inline__ + +#if defined(__cplusplus) && defined(__CUDACC__) + +#if !defined(__CUDA_ARCH__) || __CUDA_ARCH__ >= 700 + + +#if !defined(__CUDA_ARCH__) && !defined(_NVHPC_CUDA) +#define __DEF_IF_HOST { } +#else /* !__CUDA_ARCH__ && !_NVHPC_CUDA */ +#define __DEF_IF_HOST ; +#endif /* __CUDA_ARCH__ || _NVHPC_CUDA */ + +#if !defined(__CUDA_ARCH__) || __CUDA_ARCH__ >= 720 +#define __CUDA_IMMA__ 1 +#endif /* !defined(__CUDA_ARCH__) || __CUDA_ARCH__ >= 720 */ + +#if !defined(__CUDA_ARCH__) || __CUDA_ARCH__ >= 730 +#define __CUDA_SUBBYTE_IMMA__ 1 +#endif /* !defined(__CUDA_ARCH__) || __CUDA_ARCH__ >= 730 */ + +#if !defined(__CUDA_ARCH__) || __CUDA_ARCH__ >= 800 +#define __CUDA_AMPERE_MMA__ 1 +#endif /* !defined(__CUDA_ARCH__) || __CUDA_ARCH__ >= 800 */ + +namespace nvcuda { +namespace wmma { + + // utility functions +#ifdef __CUDA_AMPERE_MMA__ + inline __device__ float __float_to_tf32(float in) + { + float ret; + asm("{\n .reg .b32 __$1;" + "\n cvt.rna.tf32.f32 __$1, %1;" + "\n mov.b32 %0, __$1;\n}\n" : "=f"(ret) : "f"(in) ); + return ret; + } +#endif /* __CUDA_AMPERE_MMA__ */ + + // + // tags + // + struct row_major; + struct col_major; + struct matrix_a; + struct matrix_b; + struct accumulator; + +#ifdef __CUDA_AMPERE_MMA__ + namespace precision { + struct tf32; + } +#endif /* __CUDA_AMPERE_MMA__ */ +#ifdef __CUDA_SUBBYTE_IMMA__ + namespace experimental { + namespace precision { + struct u4; // 4-bit unsigned + struct s4; // 4-bit signed + struct b1; // 1-bit + } + enum bmmaBitOp { bmmaBitOpXOR = 1 +#ifdef __CUDA_AMPERE_MMA__ + , bmmaBitOpAND = 2 +#endif /* __CUDA_AMPERE_MMA__ */ + }; + enum bmmaAccumulateOp { bmmaAccumulateOpPOPC = 1 }; + } +#endif /* __CUDA_SUBBYTE_IMMA__ */ + + // + // layout + // + enum layout_t { + mem_row_major, mem_col_major + }; + + template + struct helper_traits { + typedef T element_type; + typedef T storage_element_type; + typedef T fill_argument_type; + }; + +#ifdef __CUDA_SUBBYTE_IMMA__ + template<> struct helper_traits { + typedef experimental::precision::u4 element_type; + typedef unsigned int storage_element_type; + typedef unsigned int fill_argument_type; + }; + + template<> struct helper_traits { + typedef experimental::precision::s4 element_type; + typedef int storage_element_type; + typedef int fill_argument_type; + }; + + template<> struct helper_traits { + typedef experimental::precision::b1 element_type; + typedef unsigned int storage_element_type; + typedef unsigned int fill_argument_type; + }; +#endif /* __CUDA_SUBBYTE_IMMA__ */ + +#ifdef __CUDA_AMPERE_MMA__ + template<> struct helper_traits { + typedef precision::tf32 element_type; + typedef float storage_element_type; + typedef float fill_argument_type; + }; +#endif /* __CUDA_AMPERE_MMA__ */ + +#if defined(_MSC_VER) +#pragma warning(push) +#pragma warning(disable:4324) +#endif + // + // The base fragment type + // + /* note: alignment required for compiler implementation */ + template + struct __align__(8) __frag_base { + + /* Number of elements in the fragment */ + enum {num_elements = size}; + + /* Number of storage elements in the fragment. + + The elements of the fragment are packed together when the + fragment element type is experimental::precision::u4, + experimental::precision::s4 or experimental::precision::b1. + When elements are packed, num_storage_elements + will be smaller than num_elements. + */ + enum {num_storage_elements = packed_size}; + + /* element type of the fragment */ + typedef T element_type; + + /* element type of the storage representation. + + The mapping from element_type to storage_element_type is as follows: + experimental::precision::u4 -> unsigned (8 elements in 1 storage element) + experimental::precision::s4 -> int (8 elements in 1 storage element) + experimental::precision::b1 -> unsigned (32 elements in 1 storage element) + precision::tf32 -> float (1 element in 1 storage element) + all other types T -> T + */ + typedef typename helper_traits::storage_element_type storage_element_type; + + /* Storage for the (possibly packed) fragment elements. */ + storage_element_type x[num_storage_elements]; + }; +#if defined(_MSC_VER) +#pragma warning(pop) +#endif + + template + static inline __device__ StorageType __get_storage_value(ArgType in) { return in; } + +#ifdef __CUDA_SUBBYTE_IMMA__ + template<> + __device__ inline unsigned + __get_storage_value(unsigned in) + { + /* For experimental::precision::u4 fragment element type, pack 8 elements into a single + 32-bit unsigned int storage element */ + unsigned val = in & 0xf; + return (val | (val << 4) | (val << 8) | (val << 12) | (val << 16) | + (val << 20) | (val << 24) | (val << 28)); + }; + + template<> + __device__ inline int + __get_storage_value(int in) + { + /* For experimental::precision::s4 fragment element type, pack 8 elements into a single + 32-bit signed int storage element */ + int val = in & 0xf; + return (val | (val << 4) | (val << 8) | (val << 12) | (val << 16) | + (val << 20) | (val << 24) | (val << 28)); + }; + + template<> + __device__ inline unsigned + __get_storage_value(unsigned in) + { + /* For experimental::precision::b1 fragment element type, pack 32 elements into a + single 32-bit unsigned int storage element */ + return (in & 0x1) ? 0xFFFFFFFFU : 0; + } +#endif /* __CUDA_SUBBYTE_IMMA__ */ + + template + __CUDA_MMA_DEVICE_DECL__ void fill_fragment(__frag_base& f, + /* The mapping from fragment element type (FragEleType) to fill_argument_type is: + experimental::precision::u4 -> unsigned (only lower 4 bits taken) + experimental::precision::s4 -> int (only lower 4 bits taken) + experimental::precision::b1 -> unsigned (only lowest 1 bit taken) + precision::tf32 -> float + all other types T -> T + */ + const typename helper_traits::fill_argument_type & in) { + + /* get the (possibly packed) storage element value. See the specializations above for fragment + element types where the storage representation is packed */ + typedef typename helper_traits::storage_element_type storage_type; + storage_type v = __get_storage_value(in); +#pragma unroll + for (int i=0; i< f.num_storage_elements; i++) + f.x[i] = v; + } + + // + // Fragment template + // + template class fragment; + + // + // Fragments for 16x16x16 + // + template<> class fragment : public __frag_base<__half, 16> {}; + template<> class fragment : public __frag_base<__half, 16> {}; + template<> class fragment : public __frag_base<__half, 16> {}; + template<> class fragment : public __frag_base<__half, 16> {}; + template<> class fragment : public __frag_base<__half, 8> {}; + template<> class fragment : public __frag_base {}; + +#ifdef __CUDA_IMMA__ + template<> class fragment : public __frag_base {}; + template<> class fragment : public __frag_base {}; + template<> class fragment : public __frag_base {}; + template<> class fragment : public __frag_base {}; + template<> class fragment : public __frag_base {}; + template<> class fragment : public __frag_base {}; + template<> class fragment : public __frag_base {}; + template<> class fragment : public __frag_base {}; + template<> class fragment : public __frag_base {}; +#endif /* __CUDA_IMMA__ */ + +#ifdef __CUDA_AMPERE_MMA__ + template<> class fragment : public __frag_base<__nv_bfloat16, 8> {}; + template<> class fragment : public __frag_base<__nv_bfloat16, 8> {}; + template<> class fragment : public __frag_base<__nv_bfloat16, 8> {}; + template<> class fragment : public __frag_base<__nv_bfloat16, 8> {}; +#endif /* __CUDA_AMPERE_MMA__ */ + + // + // Fragments for 32x8x16 + // + template<> class fragment : public __frag_base<__half, 16> {}; + template<> class fragment : public __frag_base<__half, 16> {}; + template<> class fragment : public __frag_base<__half, 16> {}; + template<> class fragment : public __frag_base<__half, 16> {}; + template<> class fragment : public __frag_base<__half, 8> {}; + template<> class fragment : public __frag_base {}; + +#ifdef __CUDA_IMMA__ + template<> class fragment : public __frag_base {}; + template<> class fragment : public __frag_base {}; + template<> class fragment : public __frag_base {}; + template<> class fragment : public __frag_base {}; + template<> class fragment : public __frag_base {}; + template<> class fragment : public __frag_base {}; + template<> class fragment : public __frag_base {}; + template<> class fragment : public __frag_base {}; + template<> class fragment : public __frag_base {}; +#endif /* __CUDA_IMMA__ */ + +#ifdef __CUDA_AMPERE_MMA__ + template<> class fragment : public __frag_base<__nv_bfloat16, 16> {}; + template<> class fragment : public __frag_base<__nv_bfloat16, 16> {}; + template<> class fragment : public __frag_base<__nv_bfloat16, 4> {}; + template<> class fragment : public __frag_base<__nv_bfloat16, 4> {}; +#endif /* __CUDA_AMPERE_MMA__ */ + + // + // Fragments for 8x32x16 + // + template<> class fragment : public __frag_base<__half, 16> {}; + template<> class fragment : public __frag_base<__half, 16> {}; + template<> class fragment : public __frag_base<__half, 16> {}; + template<> class fragment : public __frag_base<__half, 16> {}; + template<> class fragment : public __frag_base<__half, 8> {}; + template<> class fragment : public __frag_base {}; + +#ifdef __CUDA_IMMA__ + template<> class fragment : public __frag_base {}; + template<> class fragment : public __frag_base {}; + template<> class fragment : public __frag_base {}; + template<> class fragment : public __frag_base {}; + template<> class fragment : public __frag_base {}; + template<> class fragment : public __frag_base {}; + template<> class fragment : public __frag_base {}; + template<> class fragment : public __frag_base {}; + template<> class fragment : public __frag_base {}; +#endif /* __CUDA_IMMA__ */ + +#ifdef __CUDA_AMPERE_MMA__ + template<> class fragment : public __frag_base<__nv_bfloat16, 4> {}; + template<> class fragment : public __frag_base<__nv_bfloat16, 4> {}; + template<> class fragment : public __frag_base<__nv_bfloat16, 16> {}; + template<> class fragment : public __frag_base<__nv_bfloat16, 16> {}; +#endif /* __CUDA_AMPERE_MMA__ */ + +#ifdef __CUDA_SUBBYTE_IMMA__ + // + // Fragments for 8x8x32 + // + template<> class fragment : public __frag_base {}; + template<> class fragment : public __frag_base {}; + template<> class fragment : public __frag_base {}; + template<> class fragment : public __frag_base {}; + template<> class fragment : public __frag_base {}; + + // + // Fragments for 8x8x128 + // + template<> class fragment : public __frag_base {}; + template<> class fragment : public __frag_base {}; + template<> class fragment : public __frag_base {}; +#endif /* __CUDA_SUBBYTE_IMMA__ */ + +#ifdef __CUDA_AMPERE_MMA__ + // + // Fragments for 16x16x8 + // + template<> class fragment : public __frag_base {}; + template<> class fragment : public __frag_base {}; + template<> class fragment : public __frag_base {}; + template<> class fragment : public __frag_base {}; + template<> class fragment : public __frag_base {}; + + // + // Fragments for 8x8x4 + // + template<> class fragment : public __frag_base {}; + template<> class fragment : public __frag_base {}; + template<> class fragment : public __frag_base {}; + template<> class fragment : public __frag_base {}; + template<> class fragment : public __frag_base {}; +#endif /* __CUDA_AMPERE_MMA__ */ + + + // + // Load functions for frags of shape m16n16k16 + // + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const __half* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const __half* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const __half* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const __half* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const __half* p, unsigned ldm, layout_t layout) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const float* p, unsigned ldm, layout_t layout) __DEF_IF_HOST + +#ifdef __CUDA_IMMA__ + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const signed char* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const signed char* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const unsigned char* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const unsigned char* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const signed char* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const signed char* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const unsigned char* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const unsigned char* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const int* p, unsigned ldm, layout_t layout) __DEF_IF_HOST +#endif /* __CUDA_IMMA__ */ + +#ifdef __CUDA_AMPERE_MMA__ + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const __nv_bfloat16* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const __nv_bfloat16* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const __nv_bfloat16* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const __nv_bfloat16* p, unsigned ldm) __DEF_IF_HOST +#endif /* __CUDA_AMPERE_MMA__ */ + + // + // Load functions for frags of shape m32n8k16 + // + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const __half* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const __half* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const __half* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const __half* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const __half* p, unsigned ldm, layout_t layout) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const float* p, unsigned ldm, layout_t layout) __DEF_IF_HOST + +#ifdef __CUDA_IMMA__ + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const signed char* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const signed char* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const unsigned char* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const unsigned char* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const signed char* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const signed char* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const unsigned char* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const unsigned char* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const int* p, unsigned ldm, layout_t layout) __DEF_IF_HOST +#endif /* __CUDA_IMMA__ */ + +#ifdef __CUDA_AMPERE_MMA__ + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const __nv_bfloat16* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const __nv_bfloat16* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const __nv_bfloat16* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const __nv_bfloat16* p, unsigned ldm) __DEF_IF_HOST +#endif /* __CUDA_AMPERE_MMA__ */ + + // + // Load functions for frags of shape m8n32k16 + // + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const __half* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const __half* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const __half* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const __half* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const __half* p, unsigned ldm, layout_t layout) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const float* p, unsigned ldm, layout_t layout) __DEF_IF_HOST + +#ifdef __CUDA_IMMA__ + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const signed char* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const signed char* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const unsigned char* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const unsigned char* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const signed char* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const signed char* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const unsigned char* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const unsigned char* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const int* p, unsigned ldm, layout_t layout) __DEF_IF_HOST +#endif /* __CUDA_IMMA__ */ + +#ifdef __CUDA_AMPERE_MMA__ + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const __nv_bfloat16* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const __nv_bfloat16* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const __nv_bfloat16* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const __nv_bfloat16* p, unsigned ldm) __DEF_IF_HOST +#endif /* __CUDA_AMPERE_MMA__ */ + +#ifdef __CUDA_SUBBYTE_IMMA__ + // + // Load functions for frags of shape m8n8k32 + // + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const void* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const void* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const void* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const void* p, unsigned ldm) __DEF_IF_HOST + + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const int* p, unsigned ldm, layout_t layout) __DEF_IF_HOST + + // + // Load functions for frags of shape m8n8k128 + // + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const void* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const void* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const int* p, unsigned ldm, layout_t layout) __DEF_IF_HOST + +#endif /* __CUDA_SUBBYTE_IMMA__ */ + + +#ifdef __CUDA_AMPERE_MMA__ + // + // Load functions for frags of shape m16n16k8 + // + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const float* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const float* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const float* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const float* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const float* p, unsigned ldm, layout_t layout) __DEF_IF_HOST + + // + // Load functions for frags of shape m8n8k4 + // + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const double* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const double* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const double* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const double* p, unsigned ldm) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const double* p, unsigned ldm, layout_t layout) __DEF_IF_HOST +#endif /* __CUDA_AMPERE_MMA__ */ + + // + // Store functions for frags of shape m16n16k16 + // + __CUDA_MMA_DEVICE_DECL__ void store_matrix_sync(__half *p, const fragment& a, unsigned ldm, layout_t layout) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void store_matrix_sync(float *p, const fragment& a, unsigned ldm, layout_t layout) __DEF_IF_HOST +#ifdef __CUDA_IMMA__ + __CUDA_MMA_DEVICE_DECL__ void store_matrix_sync(int *p, const fragment& a, unsigned ldm, layout_t layout) __DEF_IF_HOST +#endif /* __CUDA_IMMA__ */ + + // + // Store functions for frags of shape m32n8k16 + // + __CUDA_MMA_DEVICE_DECL__ void store_matrix_sync(__half *p, const fragment& a, unsigned ldm, layout_t layout) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void store_matrix_sync(float *p, const fragment& a, unsigned ldm, layout_t layout) __DEF_IF_HOST +#ifdef __CUDA_IMMA__ + __CUDA_MMA_DEVICE_DECL__ void store_matrix_sync(int *p, const fragment& a, unsigned ldm, layout_t layout) __DEF_IF_HOST +#endif /* __CUDA_IMMA__ */ + + // + // Store functions for frags of shape m8n32k16 + // + __CUDA_MMA_DEVICE_DECL__ void store_matrix_sync(__half *p, const fragment& a, unsigned ldm, layout_t layout) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void store_matrix_sync(float *p, const fragment& a, unsigned ldm, layout_t layout) __DEF_IF_HOST +#ifdef __CUDA_IMMA__ + __CUDA_MMA_DEVICE_DECL__ void store_matrix_sync(int *p, const fragment& a, unsigned ldm, layout_t layout) __DEF_IF_HOST +#endif /* __CUDA_IMMA__ */ + +#ifdef __CUDA_SUBBYTE_IMMA__ + // + // Store functions for frags of shape m8n8k32 + // + __CUDA_MMA_DEVICE_DECL__ void store_matrix_sync(int *p, const fragment& a, unsigned ldm, layout_t layout) __DEF_IF_HOST + + // + // Store functions for frags of shape m8n8k128 + // + __CUDA_MMA_DEVICE_DECL__ void store_matrix_sync(int *p, const fragment& a, unsigned ldm, layout_t layout) __DEF_IF_HOST + +#endif /* __CUDA_SUBBYTE_IMMA__ */ + +#ifdef __CUDA_AMPERE_MMA__ + // + // Store functions for frags of shape m16n16k8 + // + __CUDA_MMA_DEVICE_DECL__ void store_matrix_sync(float *p, const fragment& a, unsigned ldm, layout_t layout) __DEF_IF_HOST + + // + // Store functions for frags of shape m8n8k4 + // + __CUDA_MMA_DEVICE_DECL__ void store_matrix_sync(double *p, const fragment& a, unsigned ldm, layout_t layout) __DEF_IF_HOST +#endif /* __CUDA_AMPERE_MMA__ */ + + // + // MMA functions for shape m16n16k16 + // + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + +#ifdef __CUDA_IMMA__ + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c, bool satf=false) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c, bool satf=false) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c, bool satf=false) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c, bool satf=false) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c, bool satf=false) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c, bool satf=false) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c, bool satf=false) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c, bool satf=false) __DEF_IF_HOST +#endif /* __CUDA_IMMA__ */ + +#ifdef __CUDA_AMPERE_MMA__ + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST +#endif /* __CUDA_AMPERE_MMA__ */ + + // + // MMA functions for shape m32n8k16 + // + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + +#ifdef __CUDA_IMMA__ + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c, bool satf=false) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c, bool satf=false) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c, bool satf=false) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c, bool satf=false) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c, bool satf=false) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c, bool satf=false) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c, bool satf=false) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c, bool satf=false) __DEF_IF_HOST +#endif /* __CUDA_IMMA__ */ + +#ifdef __CUDA_AMPERE_MMA__ + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST +#endif /* __CUDA_AMPERE_MMA__ */ + + // + // MMA functions for shape m8n32k16 + // + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + +#ifdef __CUDA_IMMA__ + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c, bool satf=false) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c, bool satf=false) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c, bool satf=false) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c, bool satf=false) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c, bool satf=false) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c, bool satf=false) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c, bool satf=false) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c, bool satf=false) __DEF_IF_HOST +#endif /* __CUDA_IMMA__ */ + +#ifdef __CUDA_AMPERE_MMA__ + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST +#endif /* __CUDA_AMPERE_MMA__ */ + +#ifdef __CUDA_SUBBYTE_IMMA__ + // + // MMA functions for shape m8n8k32 + // + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c, bool satf=false) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c, bool satf=false) __DEF_IF_HOST + + + // + // MMA functions for shape m8n8k128 + // + __CUDA_MMA_DEVICE_DECL__ void bmma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c, + experimental::bmmaBitOp = experimental::bmmaBitOpXOR, + experimental::bmmaAccumulateOp = experimental::bmmaAccumulateOpPOPC) __DEF_IF_HOST + +#endif /* __CUDA_SUBBYTE_IMMA__ */ + +#ifdef __CUDA_AMPERE_MMA__ + // + // MMA functions for shape m16n16k8 + // + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + + // + // MMA functions for shape m8n8k4 + // + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) __DEF_IF_HOST +#endif /* __CUDA_AMPERE_MMA__ */ +}; +}; + +#undef __DEF_IF_HOST +#undef __CUDA_IMMA__ +#undef __CUDA_SUBBYTE_IMMA__ +#undef __CUDA_AMPERE_MMA__ +#endif /* !__CUDA_ARCH__ || __CUDA_ARCH__ >= 700 */ + +#endif /* __cplusplus && __CUDACC__ */ + +#undef __CUDA_MMA_DEVICE_DECL__ + +#if defined(__CUDA_ARCH__) +#include "mma.hpp" +#endif /* defined(__CUDA_ARCH__) */ + + +#endif /* !__CUDA_MMA_H__ */ + +#if defined(__UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_CUDA_MMA_H__) +#undef __CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__ +#undef __UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_CUDA_MMA_H__ +#endif diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/mma.hpp b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/mma.hpp new file mode 100644 index 0000000000000000000000000000000000000000..3e10f2a982bd2dcf9814a2fc05a3f200d5a1cb07 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/mma.hpp @@ -0,0 +1,1128 @@ +/* + * Copyright 2017-2020 NVIDIA Corporation. All rights reserved. + * + * NOTICE TO LICENSEE: + * + * This source code and/or documentation ("Licensed Deliverables") are + * subject to NVIDIA intellectual property rights under U.S. and + * international Copyright laws. + * + * These Licensed Deliverables contained herein is PROPRIETARY and + * CONFIDENTIAL to NVIDIA and is being provided under the terms and + * conditions of a form of NVIDIA software license agreement by and + * between NVIDIA and Licensee ("License Agreement") or electronically + * accepted by Licensee. Notwithstanding any terms or conditions to + * the contrary in the License Agreement, reproduction or disclosure + * of the Licensed Deliverables to any third party without the express + * written consent of NVIDIA is prohibited. + * + * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE + * LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE + * SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE. IT IS + * PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND. + * NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED + * DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY, + * NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE. + * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE + * LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY + * SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY + * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS + * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THESE LICENSED DELIVERABLES. + * + * U.S. Government End Users. These Licensed Deliverables are a + * "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT + * 1995), consisting of "commercial computer software" and "commercial + * computer software documentation" as such terms are used in 48 + * C.F.R. 12.212 (SEPT 1995) and is provided to the U.S. Government + * only as a commercial end item. Consistent with 48 C.F.R.12.212 and + * 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all + * U.S. Government End Users acquire the Licensed Deliverables with + * only those rights set forth herein. + * + * Any use of the Licensed Deliverables in individual and commercial + * software must include, in the user documentation and internal + * comments to the code, the above Disclaimer and U.S. Government End + * Users Notice. + */ + +#if !defined(__CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__) +#if defined(_MSC_VER) +#pragma message("crt/mma.hpp is an internal header file and must not be used directly. Please use cuda_runtime_api.h or cuda_runtime.h instead.") +#else +#warning "crt/mma.hpp is an internal header file and must not be used directly. Please use cuda_runtime_api.h or cuda_runtime.h instead." +#endif +#define __CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__ +#define __UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_CUDA_MMA_HPP__ +#endif + +#if !defined(__CUDA_MMA_HPP__) +#define __CUDA_MMA_HPP__ + +#if defined(__cplusplus) && defined(__CUDACC__) + +#if !defined(__CUDA_ARCH__) || __CUDA_ARCH__ >= 700 + +#include +#include + +#define __CUDA_MMA_DEVICE_DECL__ static __device__ __inline__ + +#if !defined(__CUDA_ARCH__) || __CUDA_ARCH__ >= 720 +#define __CUDA_IMMA__ 1 +#endif /* !defined(__CUDA_ARCH__) || __CUDA_ARCH__ >= 720 */ + +#if !defined(__CUDA_ARCH__) || __CUDA_ARCH__ >= 730 +#define __CUDA_SUBBYTE_IMMA__ 1 +#endif /* !defined(__CUDA_ARCH__) || __CUDA_ARCH__ >= 730 */ + +#if !defined(__CUDA_ARCH__) || __CUDA_ARCH__ >= 800 +#define __CUDA_AMPERE_MMA__ 1 +#endif /* !defined(__CUDA_ARCH__) || __CUDA_ARCH__ >= 800 */ + +namespace nvcuda { +namespace wmma { + + // + // Load functions for frags of shape m16n16k16 + // + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const __half* p, unsigned ldm) { + __hmma_m16n16k16_ld_a((int*)&a, (const int*)p, ldm, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const __half* p, unsigned ldm) { + __hmma_m16n16k16_ld_a((int*)&a, (const int*)p, ldm, 1); + } + + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const __half* p, unsigned ldm) { + __hmma_m16n16k16_ld_b((int*)&a, (const int*)p, ldm, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const __half* p, unsigned ldm) { + __hmma_m16n16k16_ld_b((int*)&a, (const int*)p, ldm, 1); + } + + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const __half* p, unsigned ldm, layout_t layout) { + if (layout == mem_row_major) + __hmma_m16n16k16_ld_c_f16((int*)&a, (const int*)p, ldm, 0); + else + __hmma_m16n16k16_ld_c_f16((int*)&a, (const int*)p, ldm, 1); + } + + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const float* p, unsigned ldm, layout_t layout) { + if (layout == mem_row_major) + __hmma_m16n16k16_ld_c_f32((float*)&a, (const float*)p, ldm, 0); + else + __hmma_m16n16k16_ld_c_f32((float*)&a, (const float*)p, ldm, 1); + } + +#ifdef __CUDA_IMMA__ + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const signed char* p, unsigned ldm) { + __imma_m16n16k16_ld_a_s8((int *)&a, (const int *)p, ldm, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const signed char* p, unsigned ldm) { + __imma_m16n16k16_ld_a_s8((int *)&a, (const int *)p, ldm, 1); + } + + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const unsigned char* p, unsigned ldm) { + __imma_m16n16k16_ld_a_u8((int *)&a, (const int *)p, ldm, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const unsigned char* p, unsigned ldm) { + __imma_m16n16k16_ld_a_u8((int *)&a, (const int *)p, ldm, 1); + } + + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const signed char* p, unsigned ldm) { + __imma_m16n16k16_ld_b_s8((int *)&a, (const int *)p, ldm, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const signed char* p, unsigned ldm) { + __imma_m16n16k16_ld_b_s8((int *)&a, (const int *)p, ldm, 1); + } + + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const unsigned char* p, unsigned ldm) { + __imma_m16n16k16_ld_b_u8((int *)&a, (const int *)p, ldm, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const unsigned char* p, unsigned ldm) { + __imma_m16n16k16_ld_b_u8((int *)&a, (const int *)p, ldm, 1); + } + + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const int* p, unsigned ldm, layout_t layout) { + if (layout == mem_row_major) + __imma_m16n16k16_ld_c((int *)&a, (const int*)p, ldm, 0); + else + __imma_m16n16k16_ld_c((int *)&a, (const int*)p, ldm, 1); + } +#endif /* __CUDA_IMMA__ */ + +#ifdef __CUDA_AMPERE_MMA__ + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const __nv_bfloat16* p, unsigned ldm) { + __mma_bf16_m16n16k16_ld_a((int*)&a, (const int*)p, ldm, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const __nv_bfloat16* p, unsigned ldm) { + __mma_bf16_m16n16k16_ld_a((int*)&a, (const int*)p, ldm, 1); + } + + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const __nv_bfloat16* p, unsigned ldm) { + __mma_bf16_m16n16k16_ld_b((int*)&a, (const int*)p, ldm, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const __nv_bfloat16* p, unsigned ldm) { + __mma_bf16_m16n16k16_ld_b((int*)&a, (const int*)p, ldm, 1); + } +#endif /* __CUDA_AMPERE_MMA__ */ + + + // + // Load functions for frags of shape m32n8k16 + // + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const __half* p, unsigned ldm) { + __hmma_m32n8k16_ld_a((int*)&a, (const int*)p, ldm, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const __half* p, unsigned ldm) { + __hmma_m32n8k16_ld_a((int*)&a, (const int*)p, ldm, 1); + } + + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const __half* p, unsigned ldm) { + __hmma_m32n8k16_ld_b((int*)&a, (const int*)p, ldm, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const __half* p, unsigned ldm) { + __hmma_m32n8k16_ld_b((int*)&a, (const int*)p, ldm, 1); + } + + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const __half* p, unsigned ldm, layout_t layout) { + if (layout == mem_row_major) + __hmma_m32n8k16_ld_c_f16((int*)&a, (const int*)p, ldm, 0); + else + __hmma_m32n8k16_ld_c_f16((int*)&a, (const int*)p, ldm, 1); + } + + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const float* p, unsigned ldm, layout_t layout) { + if (layout == mem_row_major) + __hmma_m32n8k16_ld_c_f32((float*)&a, (const float*)p, ldm, 0); + else + __hmma_m32n8k16_ld_c_f32((float*)&a, (const float*)p, ldm, 1); + } + +#ifdef __CUDA_IMMA__ + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const signed char* p, unsigned ldm) { + __imma_m32n8k16_ld_a_s8((int *)&a, (const int *)p, ldm, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const signed char* p, unsigned ldm) { + __imma_m32n8k16_ld_a_s8((int *)&a, (const int *)p, ldm, 1); + } + + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const unsigned char* p, unsigned ldm) { + __imma_m32n8k16_ld_a_u8((int *)&a, (const int *)p, ldm, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const unsigned char* p, unsigned ldm) { + __imma_m32n8k16_ld_a_u8((int *)&a, (const int *)p, ldm, 1); + } + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const signed char* p, unsigned ldm) { + __imma_m32n8k16_ld_b_s8((int *)&a, (const int *)p, ldm, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const signed char* p, unsigned ldm) { + __imma_m32n8k16_ld_b_s8((int *)&a, (const int *)p, ldm, 1); + } + + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const unsigned char* p, unsigned ldm) { + __imma_m32n8k16_ld_b_u8((int *)&a, (const int *)p, ldm, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const unsigned char* p, unsigned ldm) { + __imma_m32n8k16_ld_b_u8((int *)&a, (const int *)p, ldm, 1); + } + + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const int* p, unsigned ldm, layout_t layout) { + if (layout == mem_row_major) + __imma_m32n8k16_ld_c((int *)&a, (const int*)p, ldm, 0); + else + __imma_m32n8k16_ld_c((int *)&a, (const int*)p, ldm, 1); + } +#endif /* __CUDA_IMMA__ */ + +#ifdef __CUDA_AMPERE_MMA__ + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const __nv_bfloat16* p, unsigned ldm) { + __mma_bf16_m32n8k16_ld_a((int*)&a, (const int*)p, ldm, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const __nv_bfloat16* p, unsigned ldm) { + __mma_bf16_m32n8k16_ld_a((int*)&a, (const int*)p, ldm, 1); + } + + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const __nv_bfloat16* p, unsigned ldm) { + __mma_bf16_m32n8k16_ld_b((int*)&a, (const int*)p, ldm, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const __nv_bfloat16* p, unsigned ldm) { + __mma_bf16_m32n8k16_ld_b((int*)&a, (const int*)p, ldm, 1); + } +#endif /* __CUDA_AMPERE_MMA__ */ + + + // + // Load functions for frags of shape m8n32k16 + // + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const __half* p, unsigned ldm) { + __hmma_m8n32k16_ld_a((int*)&a, (const int*)p, ldm, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const __half* p, unsigned ldm) { + __hmma_m8n32k16_ld_a((int*)&a, (const int*)p, ldm, 1); + } + + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const __half* p, unsigned ldm) { + __hmma_m8n32k16_ld_b((int*)&a, (const int*)p, ldm, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const __half* p, unsigned ldm) { + __hmma_m8n32k16_ld_b((int*)&a, (const int*)p, ldm, 1); + } + + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const __half* p, unsigned ldm, layout_t layout) { + if (layout == mem_row_major) + __hmma_m8n32k16_ld_c_f16((int*)&a, (const int*)p, ldm, 0); + else + __hmma_m8n32k16_ld_c_f16((int*)&a, (const int*)p, ldm, 1); + } + + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const float* p, unsigned ldm, layout_t layout) { + if (layout == mem_row_major) + __hmma_m8n32k16_ld_c_f32((float*)&a, (const float*)p, ldm, 0); + else + __hmma_m8n32k16_ld_c_f32((float*)&a, (const float*)p, ldm, 1); + } + +#ifdef __CUDA_IMMA__ + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const signed char* p, unsigned ldm) { + __imma_m8n32k16_ld_a_s8((int *)&a, (const int *)p, ldm, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const signed char* p, unsigned ldm) { + __imma_m8n32k16_ld_a_s8((int *)&a, (const int *)p, ldm, 1); + } + + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const unsigned char* p, unsigned ldm) { + __imma_m8n32k16_ld_a_u8((int *)&a, (const int *)p, ldm, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const unsigned char* p, unsigned ldm) { + __imma_m8n32k16_ld_a_u8((int *)&a, (const int *)p, ldm, 1); + } + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const signed char* p, unsigned ldm) { + __imma_m8n32k16_ld_b_s8((int *)&a, (const int *)p, ldm, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const signed char* p, unsigned ldm) { + __imma_m8n32k16_ld_b_s8((int *)&a, (const int *)p, ldm, 1); + } + + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const unsigned char* p, unsigned ldm) { + __imma_m8n32k16_ld_b_u8((int *)&a, (const int *)p, ldm, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const unsigned char* p, unsigned ldm) { + __imma_m8n32k16_ld_b_u8((int *)&a, (const int *)p, ldm, 1); + } + + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const int* p, unsigned ldm, layout_t layout) { + if (layout == mem_row_major) + __imma_m8n32k16_ld_c((int *)&a, (const int*)p, ldm, 0); + else + __imma_m8n32k16_ld_c((int *)&a, (const int*)p, ldm, 1); + } +#endif /* __CUDA_IMMA__ */ + +#ifdef __CUDA_AMPERE_MMA__ + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const __nv_bfloat16* p, unsigned ldm) { + __mma_bf16_m8n32k16_ld_a((int*)&a, (const int*)p, ldm, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const __nv_bfloat16* p, unsigned ldm) { + __mma_bf16_m8n32k16_ld_a((int*)&a, (const int*)p, ldm, 1); + } + + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const __nv_bfloat16* p, unsigned ldm) { + __mma_bf16_m8n32k16_ld_b((int*)&a, (const int*)p, ldm, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const __nv_bfloat16* p, unsigned ldm) { + __mma_bf16_m8n32k16_ld_b((int*)&a, (const int*)p, ldm, 1); + } +#endif /* __CUDA_AMPERE_MMA__ */ + + +#ifdef __CUDA_SUBBYTE_IMMA__ + // + // Load functions for frags of shape m8n8k32 + // + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const void* p, unsigned ldm) { + __imma_m8n8k32_ld_a_s4((int *)&a, (const int *)p, ldm, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const void* p, unsigned ldm) { + __imma_m8n8k32_ld_a_u4((int *)&a, (const int *)p, ldm, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const void* p, unsigned ldm) { + __imma_m8n8k32_ld_b_s4((int *)&a, (const int *)p, ldm, 1); + } + + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const void* p, unsigned ldm) { + __imma_m8n8k32_ld_b_u4((int *)&a, (const int *)p, ldm, 1); + } + + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const int* p, unsigned ldm, layout_t layout) { + if (layout == mem_row_major) + __imma_m8n8k32_ld_c((int *)&a, (const int*)p, ldm, 0); + else + __imma_m8n8k32_ld_c((int *)&a, (const int*)p, ldm, 1); + } + + // + // Load functions for frags of shape m8n8k128 + // + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const void* p, unsigned ldm) { + __bmma_m8n8k128_ld_a_b1((int *)&a, (const int *)p, ldm, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const void* p, unsigned ldm) { + __bmma_m8n8k128_ld_b_b1((int *)&a, (const int *)p, ldm, 1); + } + + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const int* p, unsigned ldm, layout_t layout) { + if (layout == mem_row_major) + __bmma_m8n8k128_ld_c((int *)&a, (const int*)p, ldm, 0); + else + __bmma_m8n8k128_ld_c((int *)&a, (const int*)p, ldm, 1); + } +#endif /* __CUDA_SUBBYTE_IMMA__ */ + + + +#ifdef __CUDA_AMPERE_MMA__ + // load functions for frags of shape m16n16k8 + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const float* p, unsigned ldm) { + __mma_tf32_m16n16k8_ld_a((int *)&a, (const int *)p, ldm, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const float* p, unsigned ldm) { + __mma_tf32_m16n16k8_ld_a((int *)&a, (const int *)p, ldm, 1); + } + + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const float* p, unsigned ldm) { + __mma_tf32_m16n16k8_ld_b((int *)&a, (const int *)p, ldm, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const float* p, unsigned ldm) { + __mma_tf32_m16n16k8_ld_b((int *)&a, (const int *)p, ldm, 1); + } + + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const float* p, unsigned ldm, layout_t layout) { + if (layout == mem_row_major) + __mma_tf32_m16n16k8_ld_c((float *)&a, p, ldm, 0); + else + __mma_tf32_m16n16k8_ld_c((float *)&a, p, ldm, 1); + } + + // load functions for frags of shape m8n8k4 + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const double* p, unsigned ldm) { + __dmma_m8n8k4_ld_a((double *)&a, p, ldm, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const double* p, unsigned ldm) { + __dmma_m8n8k4_ld_a((double *)&a, p, ldm, 1); + } + + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const double* p, unsigned ldm) { + __dmma_m8n8k4_ld_b((double *)&a, p, ldm, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const double* p, unsigned ldm) { + __dmma_m8n8k4_ld_b((double *)&a, p, ldm, 1); + } + + __CUDA_MMA_DEVICE_DECL__ void load_matrix_sync(fragment& a, const double* p, unsigned ldm, layout_t layout) { + if (layout == mem_row_major) + __dmma_m8n8k4_ld_c((double *)&a, p, ldm, 0); + else + __dmma_m8n8k4_ld_c((double *)&a, p, ldm, 1); + } +#endif /* __CUDA_AMPERE_MMA__ */ + + // + // Store functions for frags of shape m16n16k16 + // + __CUDA_MMA_DEVICE_DECL__ void store_matrix_sync(__half *p, const fragment& a, unsigned ldm, layout_t layout) { + if (layout == mem_row_major) + __hmma_m16n16k16_st_c_f16((int*)p, (int*)&a, ldm, 0); + else + __hmma_m16n16k16_st_c_f16((int*)p, (int*)&a, ldm, 1); + } + + __CUDA_MMA_DEVICE_DECL__ void store_matrix_sync(float *p, const fragment& a, unsigned ldm, layout_t layout) { + if (layout == mem_row_major) + __hmma_m16n16k16_st_c_f32((float*)p, (float*)&a, ldm, 0); + else + __hmma_m16n16k16_st_c_f32((float*)p, (float*)&a, ldm, 1); + } + +#ifdef __CUDA_IMMA__ + __CUDA_MMA_DEVICE_DECL__ void store_matrix_sync(int *p, const fragment& a, unsigned ldm, layout_t layout) { + if (layout == mem_row_major) + __imma_m16n16k16_st_c_i32(p, (const int*)&a, ldm, 0); + else + __imma_m16n16k16_st_c_i32(p, (const int*)&a, ldm, 1); + } +#endif /* __CUDA_IMMA__ */ + + // + // Store functions for frags of shape m32n8k16 + // + __CUDA_MMA_DEVICE_DECL__ void store_matrix_sync(__half *p, const fragment& a, unsigned ldm, layout_t layout) { + if (layout == mem_row_major) + __hmma_m32n8k16_st_c_f16((int*)p, (int*)&a, ldm, 0); + else + __hmma_m32n8k16_st_c_f16((int*)p, (int*)&a, ldm, 1); + } + + __CUDA_MMA_DEVICE_DECL__ void store_matrix_sync(float *p, const fragment& a, unsigned ldm, layout_t layout) { + if (layout == mem_row_major) + __hmma_m32n8k16_st_c_f32((float*)p, (float*)&a, ldm, 0); + else + __hmma_m32n8k16_st_c_f32((float*)p, (float*)&a, ldm, 1); + } + +#ifdef __CUDA_IMMA__ + __CUDA_MMA_DEVICE_DECL__ void store_matrix_sync(int *p, const fragment& a, unsigned ldm, layout_t layout) { + if (layout == mem_row_major) + __imma_m32n8k16_st_c_i32(p, (const int*)&a, ldm, 0); + else + __imma_m32n8k16_st_c_i32(p, (const int*)&a, ldm, 1); + } +#endif /* __CUDA_IMMA__ */ + + // + // Store functions for frags of shape m8n32k16 + // + __CUDA_MMA_DEVICE_DECL__ void store_matrix_sync(__half *p, const fragment& a, unsigned ldm, layout_t layout) { + if (layout == mem_row_major) + __hmma_m8n32k16_st_c_f16((int*)p, (int*)&a, ldm, 0); + else + __hmma_m8n32k16_st_c_f16((int*)p, (int*)&a, ldm, 1); + } + + __CUDA_MMA_DEVICE_DECL__ void store_matrix_sync(float *p, const fragment& a, unsigned ldm, layout_t layout) { + if (layout == mem_row_major) + __hmma_m8n32k16_st_c_f32((float*)p, (float*)&a, ldm, 0); + else + __hmma_m8n32k16_st_c_f32((float*)p, (float*)&a, ldm, 1); + } + +#ifdef __CUDA_IMMA__ + __CUDA_MMA_DEVICE_DECL__ void store_matrix_sync(int *p, const fragment& a, unsigned ldm, layout_t layout) { + if (layout == mem_row_major) + __imma_m8n32k16_st_c_i32(p, (const int*)&a, ldm, 0); + else + __imma_m8n32k16_st_c_i32(p, (const int*)&a, ldm, 1); + } +#endif /* __CUDA_IMMA__ */ + +#ifdef __CUDA_SUBBYTE_IMMA__ + // + // Store functions for frags of shape m8n8k32 + // + __CUDA_MMA_DEVICE_DECL__ void store_matrix_sync(int *p, const fragment& a, unsigned ldm, layout_t layout) { + if (layout == mem_row_major) + __imma_m8n8k32_st_c_i32(p, (const int*)&a, ldm, 0); + else + __imma_m8n8k32_st_c_i32(p, (const int*)&a, ldm, 1); + } + + // + // Store functions for frags of shape m8n8k128 + // + __CUDA_MMA_DEVICE_DECL__ void store_matrix_sync(int *p, const fragment& a, unsigned ldm, layout_t layout) { + if (layout == mem_row_major) + __bmma_m8n8k128_st_c_i32(p, (const int*)&a, ldm, 0); + else + __bmma_m8n8k128_st_c_i32(p, (const int*)&a, ldm, 1); + } +#endif /* __CUDA_SUBBYTE_IMMA__ */ + + +#ifdef __CUDA_AMPERE_MMA__ + + // + // Store functions for frags of shape m16n16k8 + // + __CUDA_MMA_DEVICE_DECL__ void store_matrix_sync(float *p, const fragment& a, unsigned ldm, layout_t layout) { + if (layout == mem_row_major) + __mma_m16n16k8_st_c_f32(p, (const float*)&a, ldm, 0); + else + __mma_m16n16k8_st_c_f32(p, (const float*)&a, ldm, 1); + } + + + // + // Store functions for frags of shape m8n8k4 + // + __CUDA_MMA_DEVICE_DECL__ void store_matrix_sync(double *p, const fragment& a, unsigned ldm, layout_t layout) { + if (layout == mem_row_major) + __dmma_m8n8k4_st_c_f64(p, (const double*)&a, ldm, 0); + else + __dmma_m8n8k4_st_c_f64(p, (const double*)&a, ldm, 1); + } +#endif /* __CUDA_AMPERE_MMA__ */ + + // + // MMA functions for shape m16n16k16 + // + // D fp16, C fp16 + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) { + __hmma_m16n16k16_mma_f16f16((int*)&d, (const int*)&a, (const int*)&b, (const int*)&c, 1, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) { + __hmma_m16n16k16_mma_f16f16((int*)&d, (const int*)&a, (const int*)&b, (const int*)&c, 3, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) { + __hmma_m16n16k16_mma_f16f16((int*)&d, (const int*)&a, (const int*)&b, (const int*)&c, 0, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) { + __hmma_m16n16k16_mma_f16f16((int*)&d, (const int*)&a, (const int*)&b, (const int*)&c, 2, 0); + } + + // D fp32, C fp16 + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) { + __hmma_m16n16k16_mma_f32f16((float*)&d, (const int*)&a, (const int*)&b, (const int*)&c, 1, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) { + __hmma_m16n16k16_mma_f32f16((float*)&d, (const int*)&a, (const int*)&b, (const int*)&c, 3, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) { + __hmma_m16n16k16_mma_f32f16((float*)&d, (const int*)&a, (const int*)&b, (const int*)&c, 0, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) { + __hmma_m16n16k16_mma_f32f16((float*)&d, (const int*)&a, (const int*)&b, (const int*)&c, 2, 0); + } + + // D fp32, C fp32 + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) { + __hmma_m16n16k16_mma_f32f32((float*)&d, (const int*)&a, (const int*)&b, (const float*)&c, 1, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) { + __hmma_m16n16k16_mma_f32f32((float*)&d, (const int*)&a, (const int*)&b, (const float*)&c, 3, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) { + __hmma_m16n16k16_mma_f32f32((float*)&d, (const int*)&a, (const int*)&b, (const float*)&c, 0, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) { + __hmma_m16n16k16_mma_f32f32((float*)&d, (const int*)&a, (const int*)&b, (const float*)&c, 2, 0); + } + + // D fp16, C fp32 + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) { + __hmma_m16n16k16_mma_f16f32((int*)&d, (const int*)&a, (const int*)&b, (const float*)&c, 1, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) { + __hmma_m16n16k16_mma_f16f32((int*)&d, (const int*)&a, (const int*)&b, (const float*)&c, 3, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) { + __hmma_m16n16k16_mma_f16f32((int*)&d, (const int*)&a, (const int*)&b, (const float*)&c, 0, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) { + __hmma_m16n16k16_mma_f16f32((int*)&d, (const int*)&a, (const int*)&b, (const float*)&c, 2, 0); + } + +#ifdef __CUDA_IMMA__ + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c, bool satf) { + if (satf) + __imma_m16n16k16_mma_s8((int*)&d, (const int *)&a, (const int *)&b, (const int *)&c, 1, 1); + else + __imma_m16n16k16_mma_s8((int*)&d, (const int *)&a, (const int *)&b, (const int *)&c, 1, 0); + } + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c, bool satf) { + if (satf) + __imma_m16n16k16_mma_s8((int*)&d, (const int *)&a, (const int *)&b, (const int *)&c, 3, 1); + else + __imma_m16n16k16_mma_s8((int*)&d, (const int *)&a, (const int *)&b, (const int *)&c, 3, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c, bool satf) { + if (satf) + __imma_m16n16k16_mma_s8((int*)&d, (const int *)&a, (const int *)&b, (const int *)&c, 0, 1); + else + __imma_m16n16k16_mma_s8((int*)&d, (const int *)&a, (const int *)&b, (const int *)&c, 0, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c, bool satf) { + if (satf) + __imma_m16n16k16_mma_s8((int*)&d, (const int *)&a, (const int *)&b, (const int *)&c, 2, 1); + else + __imma_m16n16k16_mma_s8((int*)&d, (const int *)&a, (const int *)&b, (const int *)&c, 2, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c, bool satf) { + if (satf) + __imma_m16n16k16_mma_u8((int*)&d, (const int *)&a, (const int *)&b, (const int *)&c, 1, 1); + else + __imma_m16n16k16_mma_u8((int*)&d, (const int *)&a, (const int *)&b, (const int *)&c, 1, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c, bool satf) { + if (satf) + __imma_m16n16k16_mma_u8((int*)&d, (const int *)&a, (const int *)&b, (const int *)&c, 3, 1); + else + __imma_m16n16k16_mma_u8((int*)&d, (const int *)&a, (const int *)&b, (const int *)&c, 3, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c, bool satf) { + if (satf) + __imma_m16n16k16_mma_u8((int*)&d, (const int *)&a, (const int *)&b, (const int *)&c, 0, 1); + else + __imma_m16n16k16_mma_u8((int*)&d, (const int *)&a, (const int *)&b, (const int *)&c, 0, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c, bool satf) { + if (satf) + __imma_m16n16k16_mma_u8((int*)&d, (const int *)&a, (const int *)&b, (const int *)&c, 2, 1); + else + __imma_m16n16k16_mma_u8((int*)&d, (const int *)&a, (const int *)&b, (const int *)&c, 2, 0); + } +#endif /* __CUDA_IMMA__ */ + +#ifdef __CUDA_AMPERE_MMA__ + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) { + __mma_bf16_m16n16k16_mma_f32((float*)&d, (const int*)&a, (const int*)&b, (const float*)&c, 1, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) { + __mma_bf16_m16n16k16_mma_f32((float*)&d, (const int*)&a, (const int*)&b, (const float*)&c, 3, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) { + __mma_bf16_m16n16k16_mma_f32((float*)&d, (const int*)&a, (const int*)&b, (const float*)&c, 0, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) { + __mma_bf16_m16n16k16_mma_f32((float*)&d, (const int*)&a, (const int*)&b, (const float*)&c, 2, 0); + } +#endif /* __CUDA_AMPERE_MMA__ */ + + + // + // MMA functions for shape m32n8k16 + // + // D fp16, C fp16 + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) { + __hmma_m32n8k16_mma_f16f16((int*)&d, (const int*)&a, (const int*)&b, (const int*)&c, 1, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) { + __hmma_m32n8k16_mma_f16f16((int*)&d, (const int*)&a, (const int*)&b, (const int*)&c, 3, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) { + __hmma_m32n8k16_mma_f16f16((int*)&d, (const int*)&a, (const int*)&b, (const int*)&c, 0, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) { + __hmma_m32n8k16_mma_f16f16((int*)&d, (const int*)&a, (const int*)&b, (const int*)&c, 2, 0); + } + + // D fp32, C fp16 + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) { + __hmma_m32n8k16_mma_f32f16((float*)&d, (const int*)&a, (const int*)&b, (const int*)&c, 1, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) { + __hmma_m32n8k16_mma_f32f16((float*)&d, (const int*)&a, (const int*)&b, (const int*)&c, 3, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) { + __hmma_m32n8k16_mma_f32f16((float*)&d, (const int*)&a, (const int*)&b, (const int*)&c, 0, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) { + __hmma_m32n8k16_mma_f32f16((float*)&d, (const int*)&a, (const int*)&b, (const int*)&c, 2, 0); + } + + // D fp32, C fp32 + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) { + __hmma_m32n8k16_mma_f32f32((float*)&d, (const int*)&a, (const int*)&b, (const float*)&c, 1, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) { + __hmma_m32n8k16_mma_f32f32((float*)&d, (const int*)&a, (const int*)&b, (const float*)&c, 3, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) { + __hmma_m32n8k16_mma_f32f32((float*)&d, (const int*)&a, (const int*)&b, (const float*)&c, 0, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) { + __hmma_m32n8k16_mma_f32f32((float*)&d, (const int*)&a, (const int*)&b, (const float*)&c, 2, 0); + } + + // D fp16, C fp32 + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) { + __hmma_m32n8k16_mma_f16f32((int*)&d, (const int*)&a, (const int*)&b, (const float*)&c, 1, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) { + __hmma_m32n8k16_mma_f16f32((int*)&d, (const int*)&a, (const int*)&b, (const float*)&c, 3, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) { + __hmma_m32n8k16_mma_f16f32((int*)&d, (const int*)&a, (const int*)&b, (const float*)&c, 0, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) { + __hmma_m32n8k16_mma_f16f32((int*)&d, (const int*)&a, (const int*)&b, (const float*)&c, 2, 0); + } + +#ifdef __CUDA_IMMA__ + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c, bool satf) { + if (satf) + __imma_m32n8k16_mma_s8((int*)&d, (const int *)&a, (const int *)&b, (const int*)&c, 1, 1); + else + __imma_m32n8k16_mma_s8((int*)&d, (const int *)&a, (const int *)&b, (const int*)&c, 1, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c, bool satf) { + if (satf) + __imma_m32n8k16_mma_s8((int*)&d, (const int *)&a, (const int *)&b, (const int*)&c, 3, 1); + else + __imma_m32n8k16_mma_s8((int*)&d, (const int *)&a, (const int *)&b, (const int*)&c, 3, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c, bool satf) { + if (satf) + __imma_m32n8k16_mma_s8((int*)&d, (const int *)&a, (const int *)&b, (const int*)&c, 0, 1); + else + __imma_m32n8k16_mma_s8((int*)&d, (const int *)&a, (const int *)&b, (const int*)&c, 0, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c, bool satf) { + if (satf) + __imma_m32n8k16_mma_s8((int*)&d, (const int *)&a, (const int *)&b, (const int*)&c, 2, 1); + else + __imma_m32n8k16_mma_s8((int*)&d, (const int *)&a, (const int *)&b, (const int*)&c, 2, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c, bool satf) { + if (satf) + __imma_m32n8k16_mma_u8((int*)&d, (const int *)&a, (const int *)&b, (const int*)&c, 1, 1); + else + __imma_m32n8k16_mma_u8((int*)&d, (const int *)&a, (const int *)&b, (const int*)&c, 1, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c, bool satf) { + if (satf) + __imma_m32n8k16_mma_u8((int*)&d, (const int *)&a, (const int *)&b, (const int*)&c, 3, 1); + else + __imma_m32n8k16_mma_u8((int*)&d, (const int *)&a, (const int *)&b, (const int*)&c, 3, 0); + + } + + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c, bool satf) { + if (satf) + __imma_m32n8k16_mma_u8((int*)&d, (const int *)&a, (const int *)&b, (const int*)&c, 0, 1); + else + __imma_m32n8k16_mma_u8((int*)&d, (const int *)&a, (const int *)&b, (const int*)&c, 0, 0); + + } + + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c, bool satf) { + if (satf) + __imma_m32n8k16_mma_u8((int*)&d, (const int *)&a, (const int *)&b, (const int*)&c, 2, 1); + else + __imma_m32n8k16_mma_u8((int*)&d, (const int *)&a, (const int *)&b, (const int*)&c, 2, 0); + + } +#endif /* __CUDA_IMMA__ */ + +#ifdef __CUDA_AMPERE_MMA__ + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) { + __mma_bf16_m32n8k16_mma_f32((float*)&d, (const int*)&a, (const int*)&b, (const float*)&c, 1, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) { + __mma_bf16_m32n8k16_mma_f32((float*)&d, (const int*)&a, (const int*)&b, (const float*)&c, 3, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) { + __mma_bf16_m32n8k16_mma_f32((float*)&d, (const int*)&a, (const int*)&b, (const float*)&c, 0, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) { + __mma_bf16_m32n8k16_mma_f32((float*)&d, (const int*)&a, (const int*)&b, (const float*)&c, 2, 0); + } +#endif /* __CUDA_AMPERE_MMA__ */ + + // + // MMA functions for shape m8n32k16 + // + // D fp16, C fp16 + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) { + __hmma_m8n32k16_mma_f16f16((int*)&d, (const int*)&a, (const int*)&b, (const int*)&c, 1, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) { + __hmma_m8n32k16_mma_f16f16((int*)&d, (const int*)&a, (const int*)&b, (const int*)&c, 3, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) { + __hmma_m8n32k16_mma_f16f16((int*)&d, (const int*)&a, (const int*)&b, (const int*)&c, 0, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) { + __hmma_m8n32k16_mma_f16f16((int*)&d, (const int*)&a, (const int*)&b, (const int*)&c, 2, 0); + } + + // D fp32, C fp16 + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) { + __hmma_m8n32k16_mma_f32f16((float*)&d, (const int*)&a, (const int*)&b, (const int*)&c, 1, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) { + __hmma_m8n32k16_mma_f32f16((float*)&d, (const int*)&a, (const int*)&b, (const int*)&c, 3, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) { + __hmma_m8n32k16_mma_f32f16((float*)&d, (const int*)&a, (const int*)&b, (const int*)&c, 0, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) { + __hmma_m8n32k16_mma_f32f16((float*)&d, (const int*)&a, (const int*)&b, (const int*)&c, 2, 0); + } + + // D fp32, C fp32 + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) { + __hmma_m8n32k16_mma_f32f32((float*)&d, (const int*)&a, (const int*)&b, (const float*)&c, 1, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) { + __hmma_m8n32k16_mma_f32f32((float*)&d, (const int*)&a, (const int*)&b, (const float*)&c, 3, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) { + __hmma_m8n32k16_mma_f32f32((float*)&d, (const int*)&a, (const int*)&b, (const float*)&c, 0, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) { + __hmma_m8n32k16_mma_f32f32((float*)&d, (const int*)&a, (const int*)&b, (const float*)&c, 2, 0); + } + + // D fp16, C fp32 + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) { + __hmma_m8n32k16_mma_f16f32((int*)&d, (const int*)&a, (const int*)&b, (const float*)&c, 1, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) { + __hmma_m8n32k16_mma_f16f32((int*)&d, (const int*)&a, (const int*)&b, (const float*)&c, 3, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) { + __hmma_m8n32k16_mma_f16f32((int*)&d, (const int*)&a, (const int*)&b, (const float*)&c, 0, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) { + __hmma_m8n32k16_mma_f16f32((int*)&d, (const int*)&a, (const int*)&b, (const float*)&c, 2, 0); + } + +#ifdef __CUDA_IMMA__ + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c, bool satf) { + if (satf) + __imma_m8n32k16_mma_s8((int*)&d, (const int *)&a, (const int *)&b, (const int*)&c, 1, 1); + else + __imma_m8n32k16_mma_s8((int*)&d, (const int *)&a, (const int *)&b, (const int*)&c, 1, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c, bool satf) { + if (satf) + __imma_m8n32k16_mma_s8((int*)&d, (const int *)&a, (const int *)&b, (const int*)&c, 3, 1); + else + __imma_m8n32k16_mma_s8((int*)&d, (const int *)&a, (const int *)&b, (const int*)&c, 3, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c, bool satf) { + if (satf) + __imma_m8n32k16_mma_s8((int*)&d, (const int *)&a, (const int *)&b, (const int*)&c, 0, 1); + else + __imma_m8n32k16_mma_s8((int*)&d, (const int *)&a, (const int *)&b, (const int*)&c, 0, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c, bool satf) { + if (satf) + __imma_m8n32k16_mma_s8((int*)&d, (const int *)&a, (const int *)&b, (const int*)&c, 2, 1); + else + __imma_m8n32k16_mma_s8((int*)&d, (const int *)&a, (const int *)&b, (const int*)&c, 2, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c, bool satf) { + if (satf) + __imma_m8n32k16_mma_u8((int*)&d, (const int *)&a, (const int *)&b, (const int*)&c, 1, 1); + else + __imma_m8n32k16_mma_u8((int*)&d, (const int *)&a, (const int *)&b, (const int*)&c, 1, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c, bool satf) { + if (satf) + __imma_m8n32k16_mma_u8((int*)&d, (const int *)&a, (const int *)&b, (const int*)&c, 3, 1); + else + __imma_m8n32k16_mma_u8((int*)&d, (const int *)&a, (const int *)&b, (const int*)&c, 3, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c, bool satf) { + if (satf) + __imma_m8n32k16_mma_u8((int*)&d, (const int *)&a, (const int *)&b, (const int*)&c, 0, 1); + else + __imma_m8n32k16_mma_u8((int*)&d, (const int *)&a, (const int *)&b, (const int*)&c, 0, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c, bool satf) { + if (satf) + __imma_m8n32k16_mma_u8((int*)&d, (const int *)&a, (const int *)&b, (const int*)&c, 2, 1); + else + __imma_m8n32k16_mma_u8((int*)&d, (const int *)&a, (const int *)&b, (const int*)&c, 2, 0); + } +#endif /* __CUDA_IMMA__ */ + +#ifdef __CUDA_AMPERE_MMA__ + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) { + __mma_bf16_m8n32k16_mma_f32((float*)&d, (const int*)&a, (const int*)&b, (const float*)&c, 1, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) { + __mma_bf16_m8n32k16_mma_f32((float*)&d, (const int*)&a, (const int*)&b, (const float*)&c, 3, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) { + __mma_bf16_m8n32k16_mma_f32((float*)&d, (const int*)&a, (const int*)&b, (const float*)&c, 0, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) { + __mma_bf16_m8n32k16_mma_f32((float*)&d, (const int*)&a, (const int*)&b, (const float*)&c, 2, 0); + } +#endif /* __CUDA_AMPERE_MMA__ */ + + +#ifdef __CUDA_SUBBYTE_IMMA__ + // + // MMA functions for shape m8n8k32 + // + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c, bool satf) { + if (satf) + __imma_m8n8k32_mma_s4((int*)&d, (const int *)&a, (const int *)&b, (const int*)&c, 1, 1); + else + __imma_m8n8k32_mma_s4((int*)&d, (const int *)&a, (const int *)&b, (const int*)&c, 1, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c, bool satf) { + if (satf) + __imma_m8n8k32_mma_u4((int*)&d, (const int *)&a, (const int *)&b, (const int*)&c, 1, 1); + else + __imma_m8n8k32_mma_u4((int*)&d, (const int *)&a, (const int *)&b, (const int*)&c, 1, 0); + } + + // + // MMA functions for shape m8n8k128 + // + __CUDA_MMA_DEVICE_DECL__ void bmma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c, + experimental::bmmaBitOp op, experimental::bmmaAccumulateOp) + { + +#ifdef __CUDA_AMPERE_MMA__ + if (op == experimental::bmmaBitOpAND) + __bmma_m8n8k128_mma_and_popc_b1((int*)&d, (const int *)&a, (const int *)&b, (const int*)&c, 1); + else +#endif /* __CUDA_AMPERE_MMA__ */ + __bmma_m8n8k128_mma_xor_popc_b1((int*)&d, (const int *)&a, (const int *)&b, (const int*)&c, 1); + } + + +#endif /* __CUDA_SUBBYTE_IMMA__ */ + +#ifdef __CUDA_AMPERE_MMA__ + // + // MMA functions for shape m16n16k8 + // + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) { + __mma_tf32_m16n16k8_mma_f32((float *)&d, (const int*)&a, (const int*)&b, (const float*)&c, 1, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) { + __mma_tf32_m16n16k8_mma_f32((float *)&d, (const int*)&a, (const int*)&b, (const float*)&c, 3, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) { + __mma_tf32_m16n16k8_mma_f32((float *)&d, (const int*)&a, (const int*)&b, (const float*)&c, 0, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) { + __mma_tf32_m16n16k8_mma_f32((float *)&d, (const int*)&a, (const int*)&b, (const float*)&c, 2, 0); + } + + + // + // MMA functions for shape m8n8k4 + // + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) { + __dmma_m8n8k4_mma_f64((double *)&d, (const double*)&a, (const double*)&b, (const double*)&c, 1, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) { + __dmma_m8n8k4_mma_f64((double *)&d, (const double*)&a, (const double*)&b, (const double*)&c, 3, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) { + __dmma_m8n8k4_mma_f64((double *)&d, (const double*)&a, (const double*)&b, (const double*)&c, 0, 0); + } + + __CUDA_MMA_DEVICE_DECL__ void mma_sync(fragment& d, const fragment& a, const fragment& b, const fragment& c) { + __dmma_m8n8k4_mma_f64((double *)&d, (const double*)&a, (const double*)&b, (const double*)&c, 2, 0); + } + +#endif /* __CUDA_AMPERE_MMA__ */ + +}; +}; + +#undef __CUDA_IMMA__ +#undef __CUDA_SUBBYTE_IMMA__ +#undef __CUDA_MMA_DEVICE_DECL__ +#undef __CUDA_AMPERE_MMA__ + +#endif /* !__CUDA_ARCH__ || __CUDA_ARCH__ >= 700 */ + +#endif /* __cplusplus && __CUDACC__ */ + + +#endif /* __CUDA_MMA_HPP__ */ + +#if defined(__UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_CUDA_MMA_HPP__) +#undef __CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__ +#undef __UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_CUDA_MMA_HPP__ +#endif diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/nvfunctional b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/nvfunctional new file mode 100644 index 0000000000000000000000000000000000000000..5cb9ffeb9cb9f1d202cb1f5cb1d4d7e88a416475 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/nvfunctional @@ -0,0 +1,621 @@ +/* + * NVIDIA_COPYRIGHT_BEGIN + * + * Copyright (c) 2014-2018, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + * + * NVIDIA_COPYRIGHT_END + */ + +#if !defined(__CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__) +#if defined(_MSC_VER) +#pragma message("crt/nvfunctional is an internal header file and must not be used directly. Please use nvfunctional instead.") +#else +#warning "crt/nvfunctional is an internal header file and must not be used directly. Please use nvfunctional instead." +#endif +#define __CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__ +#define __UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_NV_LIBCXX_FUNCTIONAL_H__ +#endif + +#ifndef __NV_LIBCXX_FUNCTIONAL_H__ +#define __NV_LIBCXX_FUNCTIONAL_H__ + +#if __cplusplus < 201103L + #if defined(_MSC_VER) + #if _MSC_VER < 1800 + #error This library requires VS 2013 and above + #endif /* _MSC_VER < 1800 */ + #else /* !_MSC_VER */ + #error This library requires support for the ISO C++ 2011 standard + #endif /* _MSC_VER */ +#endif /* __cplusplus */ + +#if defined(_MSC_VER) + #define __NV_ALIGNOF __alignof + #define __NV_NOEXCEPT + #define __NV_CONSTEXPR +#else /* !_MSC_VER */ + #define __NV_ALIGNOF alignof + #define __NV_NOEXCEPT noexcept + #define __NV_CONSTEXPR constexpr +#endif /* _MSC_VER */ + +#include +#include +#include + +// n3290 20.8 +namespace nvstd +{ + +namespace internal { + +// D.8.1 base (deprecated) [depr.base] +template +struct unary_function +{ + typedef _Arg argument_type; + typedef _Result result_type; +}; + +template +struct binary_function +{ + typedef _Arg1 first_argument_type; + typedef _Arg2 second_argument_type; + typedef _Result result_type; +}; + +// move +template +inline __device__ __host__ +typename std::remove_reference<_T>::type&& move(_T&& __t) __NV_NOEXCEPT +{ + return static_cast::type&&>(__t); +} + +// 20.2.2 swap [utility.swap] +// swap +template::value && + std::is_move_assignable<_T>::value>::type> +inline __device__ __host__ +void swap(_T& __a, _T& __b) +#if !defined(_MSC_VER) +noexcept(std::is_nothrow_move_constructible<_T>::value && + std::is_nothrow_move_assignable<_T>::value) +#endif /* !defined(_MSC_VER) */ +{ + _T __t(internal::move(__a)); + __a = internal::move(__b); + __b = internal::move(__t); +} + +// 20.2.3 forward/move helpers [forward] +// forward +template +inline __device__ __host__ +_T&& forward(typename std::remove_reference<_T>::type& __t) __NV_NOEXCEPT +{ + return static_cast<_T&&>(__t); +} + +template +inline __device__ __host__ +_T&& forward(typename std::remove_reference<_T>::type&& __t) __NV_NOEXCEPT +{ + static_assert(!std::is_lvalue_reference<_T>::value, + "Error: __t is instantiated with an lvalue reference type"); + return static_cast<_T&&>(__t); +} + +} // namespace internal + +namespace __functional_helpers +{ + +struct __dummy_class; + +// Store small functors locally: +// a functor is legitimate to local storage if it is one of the following types: +// * member object pointer; +// * member function pointer; +// * closure type of size less than or equal to the largest size of +// the above types; +// * function pointer; +// * any callable class whose size is less than or equal to +// the largest one of the above types; +union _Small_functor_types +{ + void *__obj; + void (*__func_ptr)(); + void (__dummy_class::*mem_fn_ptr)(); +}; + +struct _Small_functor_data { + char __data[sizeof(_Small_functor_types)]; +}; + +template +struct __maybe_base_function +{ }; + +template +struct __maybe_base_function<_RetType(_T1)> + : public internal::unary_function<_T1, _RetType> +{ }; + +template +struct __maybe_base_function<_RetType(_T1, _T2)> + : public internal::binary_function<_T1, _T2, _RetType> +{ }; + +} // namespace __functional_helpers + +// 20.8.11 Polymorphic function wrappers [func.wrap] + +// 20.8.11.1 Class bad_function_call [func.wrap.badcall] +// unimplemented because of exception +// class bad_function_call : public std::exception + +// 20.8.11.2 Class template function [func.wrap.func] + +template class function; // undefined + +// Simplified version of template class function, which +// * does not support allocator_arg_t; +// * does not support target and target_type that rely on RTTI +// * does not throw bad_function_call exception on invoking a NULL target +template +class function<_RetType(_ArgTypes...)> + : public __functional_helpers::__maybe_base_function<_RetType(_ArgTypes...)> +{ + __functional_helpers::_Small_functor_data __small_functor_data; + void *__obj; + typedef _RetType(*__meta_fn_type)(void *, _ArgTypes...); + __meta_fn_type __meta_fn; + typedef void(*__cloner_type)(function &, const function &); + __cloner_type __cloner; + typedef void(*__destructor_type)(function *); + __destructor_type __destructor; + + #pragma nv_exec_check_disable + template + __device__ __host__ + __NV_CONSTEXPR bool __use_small_functor_data() const + { + return (sizeof(_F) <= sizeof(__small_functor_data) && + __NV_ALIGNOF(_F) <= __NV_ALIGNOF( + __functional_helpers::_Small_functor_types)); + } + + #pragma nv_exec_check_disable + __device__ __host__ + void* __get_small_functor_data() const + { + return (void*)(&__small_functor_data.__data[0]); + } + + #pragma nv_exec_check_disable + __device__ __host__ + bool __is_small_functor_data() const + { + return __obj == __get_small_functor_data(); + } + + #pragma nv_exec_check_disable + template + __device__ __host__ + static _F& __get_functor(void *__p) + { + return *((_F*)__p); + } + + #pragma nv_exec_check_disable + template + __device__ __host__ + static bool __is_empty_functor(const _F& /*__p*/) + { + return false; + } + + #pragma nv_exec_check_disable + template + __device__ __host__ + static bool __is_empty_functor(const _F* __p) + { + return !__p; + } + + #pragma nv_exec_check_disable + template + __device__ __host__ + static bool __is_empty_functor(const _Res _C::* __p) + { + return !__p; + } + + #pragma nv_exec_check_disable + template + __device__ __host__ + static bool __is_empty_functor(const function<_Res(_Args...)>& __p) + { + return !__p; + } + + template + struct __make_cloner + { + #pragma nv_exec_check_disable + __device__ __host__ + static void __clone_data(function &__dest, const function &__src) + { + if (__dest.__use_small_functor_data<_F>()) { + __dest.__obj = __dest.__get_small_functor_data(); + new (__dest.__obj) _F(__src.__get_functor<_F>(__src.__obj)); + } + else { + __dest.__obj = new _F(__src.__get_functor<_F>(__src.__obj)); + } + } + }; + + template + struct __make_destructor + { + #pragma nv_exec_check_disable + __device__ __host__ + static void __destruct(function *__fn) + { + if (__fn->__use_small_functor_data<_F>()) { + (__fn->__get_functor<_F>(__fn->__obj)).~_F(); + } + else { + delete (_F*)(__fn->__obj); + } + } + }; + + // We cannot simple define __make_functor in the following way: + // template + // __make_functor; + // template + // struct __make_functor<_RetType1(_ArgTypes1...), _F> + // + // because VS 2013 cannot unpack _RetType1(_ArgTypes1...) + template + struct __make_functor + { + typedef _RetType1 type; + + #pragma nv_exec_check_disable + __device__ __host__ + static _RetType1 __invoke(void *__d, _ArgTypes1... __args) + { + return __get_functor<_F>(__d)( + internal::forward<_ArgTypes1>(__args)...); + } + }; + + template + struct __make_functor<_RetType1, _M _C::*,_ArgTypes1...> + { + typedef _RetType1 type; + typedef _RetType1(*_Fn)(_ArgTypes1...); + + #pragma nv_exec_check_disable + __device__ __host__ + static _RetType1 __invoke(void *__d, _ArgTypes1... __args) + { + return __get_functor<_Fn>(__d)( + internal::forward<_ArgTypes1>(__args)...); + } + }; + +// workaround for GCC version below 4.8 +#if (__GNUC__ == 4) && (__GNUC_MINOR__ < 8) + template + struct __check_callability + : public std::integral_constant::value> + { }; +#elif defined(_MSC_VER) + // simulate VC 2013's behavior... + template + struct __check_callability1 + : public + std::integral_constant::value || + std::is_convertible< + _RetType, + typename std::result_of<_F(_ArgTypes...)>::type + >::value + > + { }; + + template + struct __check_callability + : public std::integral_constant< + bool, + !std::is_same<_F, function>::value && + __check_callability1::type>::value> + { }; +#else /* !((__GNUC__ == 4) && (__GNUC_MINOR__ < 8)) _MSC_VER */ + template ::type> + struct __check_callability + : public std::integral_constant< + bool, + !std::is_same<_F, function>::value && + std::is_convertible< _T, _RetType>::value> + { }; +#endif /* __GNUC__ == 4) && (__GNUC_MINOR__ < 8) */ + + #pragma nv_exec_check_disable + __device__ __host__ + void __destroy() + { + if (__obj) { + __destructor(this); + __obj = 0; + } + } + + #pragma nv_exec_check_disable + __device__ __host__ + void __clear() + { + __obj = 0; + __meta_fn = 0; + __cloner = 0; + __destructor = 0; + } + +public: + typedef _RetType result_type; + +/* + * These typedef(s) are derived from __maybe_base_function + * typedef T1 argument_type; // only if sizeof...(ArgTypes) == 1 and + * // the type in ArgTypes is T1 + * typedef T1 first_argument_type; // only if sizeof...(ArgTypes) == 2 and + * // ArgTypes contains T1 and T2 + * typedef T2 second_argument_type; // only if sizeof...(ArgTypes) == 2 and + * // ArgTypes contains T1 and T2 + */ + + // 20.8.11.2.1 construct/copy/destroy [func.wrap.con] + + #pragma nv_exec_check_disable + __device__ __host__ + function() __NV_NOEXCEPT + : __obj(0), __meta_fn(0), __cloner(0), __destructor(0) {} + + #pragma nv_exec_check_disable + __device__ __host__ + function(std::nullptr_t) __NV_NOEXCEPT + : __obj(0), __meta_fn(0), __cloner(0), __destructor(0) {} + + #pragma nv_exec_check_disable + __device__ __host__ + function(const function &__fn) + { + if (__fn.__obj == 0) { + __clear(); + } + else { + __meta_fn = __fn.__meta_fn; + __destructor = __fn.__destructor; + __fn.__cloner(*this, __fn); + __cloner = __fn.__cloner; + } + } + + #pragma nv_exec_check_disable + __device__ __host__ + function(function &&__fn) + { + __fn.swap(*this); + } + + // VS 2013 cannot process __check_callability type trait. + // So, we check callability using static_assert instead of + // using SFINAE such as + // template::value + // >::type> + + #pragma nv_exec_check_disable + template + __device__ __host__ + function(_F); + + // copy and swap + #pragma nv_exec_check_disable + __device__ __host__ + function& operator=(const function& __fn) + { + function(__fn).swap(*this); + return *this; + } + + #pragma nv_exec_check_disable + __device__ __host__ + function& operator=(function&& __fn) + { + function(internal::move(__fn)).swap(*this); + return *this; + } + + #pragma nv_exec_check_disable + __device__ __host__ + function& operator=(std::nullptr_t) + { + __destroy(); + return *this; + } + + #pragma nv_exec_check_disable + template + __device__ __host__ + function& + operator=(_F&& __fn) + { + static_assert(__check_callability<_F>::value, + "Unable to create functor object!"); + function(internal::forward<_F>(__fn)).swap(*this); + return *this; + } + + #pragma nv_exec_check_disable + __device__ __host__ + ~function() + { + __destroy(); + } + + // 20.8.11.2.2 function modifiers [func.wrap.func.mod] + #pragma nv_exec_check_disable + __device__ __host__ + void swap(function& __fn) __NV_NOEXCEPT + { + internal::swap(__meta_fn, __fn.__meta_fn); + internal::swap(__cloner, __fn.__cloner); + internal::swap(__destructor, __fn.__destructor); + + if (__is_small_functor_data() && __fn.__is_small_functor_data()) { + internal::swap(__small_functor_data, __fn.__small_functor_data); + } + else if (__is_small_functor_data()) { + internal::swap(__small_functor_data, __fn.__small_functor_data); + internal::swap(__obj, __fn.__obj); + __fn.__obj = __fn.__get_small_functor_data(); + } + else if (__fn.__is_small_functor_data()) { + internal::swap(__small_functor_data, __fn.__small_functor_data); + internal::swap(__obj, __fn.__obj); + __obj = __get_small_functor_data(); + } + else { + internal::swap(__obj, __fn.__obj); + } + } + + // 20.8.11.2.3 function capacity [func.wrap.func.cap] + #pragma nv_exec_check_disable + __device__ __host__ + explicit operator bool() const __NV_NOEXCEPT + { + return __obj; + } + + // 20.8.11.2.4 function invocation [func.wrap.func.inv] + // function::operator() can only be called in device code + // to avoid cross-execution space calls + #pragma nv_exec_check_disable + __device__ __host__ + _RetType operator()(_ArgTypes...) const; + +}; + +// Out-of-line definitions +#pragma nv_exec_check_disable +template +template +__device__ __host__ +function<_RetType(_ArgTypes...)>::function(_F __fn) + : __obj(0), __meta_fn(0), __cloner(0), __destructor(0) +{ + static_assert(__check_callability<_F>::value, + "Unable to construct functor object!"); + if (__is_empty_functor(__fn)) + return; + __meta_fn = &__make_functor<_RetType, _F, _ArgTypes...>::__invoke; + __cloner = &__make_cloner<_F>::__clone_data; + __destructor = &__make_destructor<_F>::__destruct; + + if (__use_small_functor_data<_F>()) { + __obj = __get_small_functor_data(); + new ((void*)__obj) _F(internal::move(__fn)); + } + else { + __obj = new _F(internal::move(__fn)); + } +} + +#pragma nv_exec_check_disable +template +__device__ __host__ +_RetType +function<_RetType(_ArgTypes...)>::operator()(_ArgTypes... __args) const +{ + return __meta_fn(__obj, internal::forward<_ArgTypes>(__args)...); +} + +// 20.8.11.2.6, Null pointer comparisons: + +#pragma nv_exec_check_disable +template +__device__ __host__ +bool operator==(const function<_R(_ArgTypes...)>& __fn, std::nullptr_t) +__NV_NOEXCEPT +{ + return !__fn; +} + +#pragma nv_exec_check_disable +template +__device__ __host__ +bool operator==(std::nullptr_t, const function<_R(_ArgTypes...)>& __fn) +__NV_NOEXCEPT +{ + return !__fn; +} + +#pragma nv_exec_check_disable +template +__device__ __host__ +bool operator!=(const function<_R(_ArgTypes...)>& __fn, std::nullptr_t) +__NV_NOEXCEPT +{ + return static_cast(__fn); +} + +#pragma nv_exec_check_disable +template +__device__ __host__ +bool operator!=(std::nullptr_t, const function<_R(_ArgTypes...)>& __fn) +__NV_NOEXCEPT +{ + return static_cast(__fn); +} + +// 20.8.11.2.7, specialized algorithms: +#pragma nv_exec_check_disable +template +__device__ __host__ +void swap(function<_R(_ArgTypes...)>& __fn1, function<_R(_ArgTypes...)>& __fn2) +{ + __fn1.swap(__fn2); +} + +} // namespace nvstd + +#undef __NV_NOEXCEPT +#undef __NV_CONSTEXPR +#undef __NV_ALIGNOF + +#endif // __NV_LIBCXX_FUNCTIONAL_H__ + +#if defined(__UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_NV_LIBCXX_FUNCTIONAL_H__) +#undef __CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__ +#undef __UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_NV_LIBCXX_FUNCTIONAL_H__ +#endif diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/sm_100_rt.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/sm_100_rt.h new file mode 100644 index 0000000000000000000000000000000000000000..3d798a6e5392ed631ed3b546304b16c94d65a1c8 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/sm_100_rt.h @@ -0,0 +1,252 @@ +/* + * Copyright 2024 NVIDIA Corporation. All rights reserved. + * + * NOTICE TO LICENSEE: + * + * This source code and/or documentation ("Licensed Deliverables") are + * subject to NVIDIA intellectual property rights under U.S. and + * international Copyright laws. + * + * These Licensed Deliverables contained herein is PROPRIETARY and + * CONFIDENTIAL to NVIDIA and is being provided under the terms and + * conditions of a form of NVIDIA software license agreement by and + * between NVIDIA and Licensee ("License Agreement") or electronically + * accepted by Licensee. Notwithstanding any terms or conditions to + * the contrary in the License Agreement, reproduction or disclosure + * of the Licensed Deliverables to any third party without the express + * written consent of NVIDIA is prohibited. + * + * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE + * LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE + * SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE. IT IS + * PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND. + * NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED + * DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY, + * NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE. + * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE + * LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY + * SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY + * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS + * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THESE LICENSED DELIVERABLES. + * + * U.S. Government End Users. These Licensed Deliverables are a + * "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT + * 1995), consisting of "commercial computer software" and "commercial + * computer software documentation" as such terms are used in 48 + * C.F.R. 12.212 (SEPT 1995) and is provided to the U.S. Government + * only as a commercial end item. Consistent with 48 C.F.R.12.212 and + * 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all + * U.S. Government End Users acquire the Licensed Deliverables with + * only those rights set forth herein. + * + * Any use of the Licensed Deliverables in individual and commercial + * software must include, in the user documentation and internal + * comments to the code, the above Disclaimer and U.S. Government End + * Users Notice. + */ + +#if !defined(__CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__) +#if defined(_MSC_VER) +#pragma message("crt/sm_100_rt.h is an internal header file and must not be used directly. Please use cuda_runtime_api.h or cuda_runtime.h instead.") +#else +#warning "crt/sm_100_rt.h is an internal header file and must not be used directly. Please use cuda_runtime_api.h or cuda_runtime.h instead." +#endif +#define __CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__ +#define __UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_SM_100_RT_H__ +#endif + +#if !defined(__SM_100_RT_H__) +#define __SM_100_RT_H__ + +#if defined(__CUDACC_RTC__) +#define __SM_100_RT_DECL__ __host__ __device__ +#else /* !__CUDACC_RTC__ */ +#define __SM_100_RT_DECL__ static __device__ __inline__ +#endif /* __CUDACC_RTC__ */ + +#if defined(__cplusplus) && defined(__CUDACC__) + +#if !defined(__CUDA_ARCH__) || __CUDA_ARCH__ >= 1000 + +/******************************************************************************* +* * +* * +* * +*******************************************************************************/ + +#include "builtin_types.h" +#include "device_types.h" +#include "host_defines.h" + +#if !defined(__CUDA_ARCH__) && !defined(_NVHPC_CUDA) +#define __DEF_IF_HOST { } +#else /* !__CUDA_ARCH__ && !_NVHPC_CUDA */ +#define __DEF_IF_HOST ; +#endif /* __CUDA_ARCH__ || _NVHPC_CUDA */ + +/** + * \ingroup CUDA_MATH_INTRINSIC_SINGLE + * \brief Compute vector fused multiply-add operation + * \cuda_math_formula x \times y + z \end_cuda_math_formula + * in round-to-nearest-even mode. + * + * Numeric behavior per component is the same as ::__fmaf_rn(). + * + * \note_requires_sm100 + * \note_float2_perf + */ +__SM_100_RT_DECL__ float2 __ffma2_rn(float2 x, float2 y, float2 z) __DEF_IF_HOST +/** + * \ingroup CUDA_MATH_INTRINSIC_SINGLE + * \brief Compute vector fused multiply-add operation + * \cuda_math_formula x \times y + z \end_cuda_math_formula + * in round-towards-zero mode. + * + * Numeric behavior per component is the same as ::__fmaf_rz(). + * + * \note_requires_sm100 + * \note_float2_perf + */ +__SM_100_RT_DECL__ float2 __ffma2_rz(float2 x, float2 y, float2 z) __DEF_IF_HOST +/** + * \ingroup CUDA_MATH_INTRINSIC_SINGLE + * \brief Compute vector fused multiply-add operation + * \cuda_math_formula x \times y + z \end_cuda_math_formula + * in round-down mode. + * + * Numeric behavior per component is the same as ::__fmaf_rd(). + * + * \note_requires_sm100 + * \note_float2_perf + */ +__SM_100_RT_DECL__ float2 __ffma2_rd(float2 x, float2 y, float2 z) __DEF_IF_HOST +/** + * \ingroup CUDA_MATH_INTRINSIC_SINGLE + * \brief Compute vector fused multiply-add operation + * \cuda_math_formula x \times y + z \end_cuda_math_formula + * in round-up mode. + * + * Numeric behavior per component is the same as ::__fmaf_ru(). + * + * \note_requires_sm100 + * \note_float2_perf + */ +__SM_100_RT_DECL__ float2 __ffma2_ru(float2 x, float2 y, float2 z) __DEF_IF_HOST + +/** + * \ingroup CUDA_MATH_INTRINSIC_SINGLE + * \brief Compute vector add operation + * \cuda_math_formula x + y \end_cuda_math_formula + * in round-to-nearest-even mode. + * + * Numeric behavior per component is the same as ::__fadd_rn(). + * + * \note_requires_sm100 + * \note_float2_perf + */ +__SM_100_RT_DECL__ float2 __fadd2_rn(float2 x, float2 y) __DEF_IF_HOST +/** + * \ingroup CUDA_MATH_INTRINSIC_SINGLE + * \brief Compute vector add operation + * \cuda_math_formula x + y \end_cuda_math_formula + * in round-towards-zero mode. + * + * Numeric behavior per component is the same as ::__fadd_rz(). + * + * \note_requires_sm100 + * \note_float2_perf + */ +__SM_100_RT_DECL__ float2 __fadd2_rz(float2 x, float2 y) __DEF_IF_HOST +/** + * \ingroup CUDA_MATH_INTRINSIC_SINGLE + * \brief Compute vector add operation + * \cuda_math_formula x + y \end_cuda_math_formula + * in round-down mode. + * + * Numeric behavior per component is the same as ::__fadd_rd(). + * + * \note_requires_sm100 + * \note_float2_perf + */ +__SM_100_RT_DECL__ float2 __fadd2_rd(float2 x, float2 y) __DEF_IF_HOST +/** + * \ingroup CUDA_MATH_INTRINSIC_SINGLE + * \brief Compute vector add operation + * \cuda_math_formula x + y \end_cuda_math_formula + * in round-up mode. + * + * Numeric behavior per component is the same as ::__fadd_ru(). + * + * \note_requires_sm100 + * \note_float2_perf + */ +__SM_100_RT_DECL__ float2 __fadd2_ru(float2 x, float2 y) __DEF_IF_HOST + +/** + * \ingroup CUDA_MATH_INTRINSIC_SINGLE + * \brief Compute vector multiply operation + * \cuda_math_formula x \times y \end_cuda_math_formula + * in round-to-nearest-even mode. + * + * Numeric behavior per component is the same as ::__fmul_rn(). + * + * \note_requires_sm100 + * \note_float2_perf + */ +__SM_100_RT_DECL__ float2 __fmul2_rn(float2 x, float2 y) __DEF_IF_HOST +/** + * \ingroup CUDA_MATH_INTRINSIC_SINGLE + * \brief Compute vector multiply operation + * \cuda_math_formula x \times y \end_cuda_math_formula + * in round-towards-zero mode. + * + * Numeric behavior per component is the same as ::__fmul_rz(). + * + * \note_requires_sm100 + * \note_float2_perf + */ +__SM_100_RT_DECL__ float2 __fmul2_rz(float2 x, float2 y) __DEF_IF_HOST +/** + * \ingroup CUDA_MATH_INTRINSIC_SINGLE + * \brief Compute vector multiply operation + * \cuda_math_formula x \times y \end_cuda_math_formula + * in round-down mode. + * + * Numeric behavior per component is the same as ::__fmul_rd(). + * + * \note_requires_sm100 + * \note_float2_perf + */ +__SM_100_RT_DECL__ float2 __fmul2_rd(float2 x, float2 y) __DEF_IF_HOST +/** + * \ingroup CUDA_MATH_INTRINSIC_SINGLE + * \brief Compute vector multiply operation + * \cuda_math_formula x \times y \end_cuda_math_formula + * in round-up mode. + * + * Numeric behavior per component is the same as ::__fmul_ru(). + * + * \note_requires_sm100 + * \note_float2_perf + */ +__SM_100_RT_DECL__ float2 __fmul2_ru(float2 x, float2 y) __DEF_IF_HOST + +#endif /* !__CUDA_ARCH__ || __CUDA_ARCH__ >= 1000 */ + +#endif /* __cplusplus && __CUDACC__ */ + +#undef __DEF_IF_HOST +#undef __SM_100_RT_DECL__ + +#if (!defined(__CUDACC_RTC__) && defined(__CUDA_ARCH__)) || defined(_NVHPC_CUDA) +#include "sm_100_rt.hpp" +#endif /* (!defined(__CUDACC_RTC__) && defined(__CUDA_ARCH__)) || defined(_NVHPC_CUDA) */ + +#endif /* !__SM_100_RT_H__ */ + +#if defined(__UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_SM_100_RT_H__) +#undef __CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__ +#undef __UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_SM_100_RT_H__ +#endif diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/sm_100_rt.hpp b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/sm_100_rt.hpp new file mode 100644 index 0000000000000000000000000000000000000000..a5d620bf0b8091e0ea6cd48da00e8689b92cdd88 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/sm_100_rt.hpp @@ -0,0 +1,157 @@ +/* + * Copyright 2024 NVIDIA Corporation. All rights reserved. + * + * NOTICE TO LICENSEE: + * + * This source code and/or documentation ("Licensed Deliverables") are + * subject to NVIDIA intellectual property rights under U.S. and + * international Copyright laws. + * + * These Licensed Deliverables contained herein is PROPRIETARY and + * CONFIDENTIAL to NVIDIA and is being provided under the terms and + * conditions of a form of NVIDIA software license agreement by and + * between NVIDIA and Licensee ("License Agreement") or electronically + * accepted by Licensee. Notwithstanding any terms or conditions to + * the contrary in the License Agreement, reproduction or disclosure + * of the Licensed Deliverables to any third party without the express + * written consent of NVIDIA is prohibited. + * + * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE + * LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE + * SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE. IT IS + * PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND. + * NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED + * DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY, + * NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE. + * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE + * LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY + * SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY + * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS + * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THESE LICENSED DELIVERABLES. + * + * U.S. Government End Users. These Licensed Deliverables are a + * "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT + * 1995), consisting of "commercial computer software" and "commercial + * computer software documentation" as such terms are used in 48 + * C.F.R. 12.212 (SEPT 1995) and is provided to the U.S. Government + * only as a commercial end item. Consistent with 48 C.F.R.12.212 and + * 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all + * U.S. Government End Users acquire the Licensed Deliverables with + * only those rights set forth herein. + * + * Any use of the Licensed Deliverables in individual and commercial + * software must include, in the user documentation and internal + * comments to the code, the above Disclaimer and U.S. Government End + * Users Notice. + */ + +#if !defined(__CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__) +#if defined(_MSC_VER) +#pragma message("crt/sm_100_rt.hpp is an internal header file and must not be used directly. Please use cuda_runtime_api.h or cuda_runtime.h instead.") +#else +#warning "crt/sm_100_rt.hpp is an internal header file and must not be used directly. Please use cuda_runtime_api.h or cuda_runtime.h instead." +#endif +#define __CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__ +#define __UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_SM_100_RT_HPP__ +#endif + +#if !defined(__SM_100_RT_HPP__) +#define __SM_100_RT_HPP__ + +#if defined(__CUDACC_RTC__) +#define __SM_100_RT_DECL__ __host__ __device__ +#else /* !__CUDACC_RTC__ */ +#define __SM_100_RT_DECL__ static __device__ __inline__ +#endif /* __CUDACC_RTC__ */ + +#if defined(__cplusplus) && defined(__CUDACC__) + +#if !defined(__CUDA_ARCH__) || __CUDA_ARCH__ >= 1000 + +/******************************************************************************* +* * +* * +* * +*******************************************************************************/ + +#include "builtin_types.h" +#include "device_types.h" +#include "host_defines.h" + +/******************************************************************************* +* * +* Below are implementations of SM-10.0 builtin functions which are included * +* as source (instead of being built in to the compiler) * +* * +*******************************************************************************/ + +extern "C" { + __device__ __device_builtin__ float2 __ffma2_rn_impl(float2 x, float2 y, float2 z); + __device__ __device_builtin__ float2 __ffma2_rz_impl(float2 x, float2 y, float2 z); + __device__ __device_builtin__ float2 __ffma2_rd_impl(float2 x, float2 y, float2 z); + __device__ __device_builtin__ float2 __ffma2_ru_impl(float2 x, float2 y, float2 z); + + __device__ __device_builtin__ float2 __fadd2_rn_impl(float2 x, float2 y); + __device__ __device_builtin__ float2 __fadd2_rz_impl(float2 x, float2 y); + __device__ __device_builtin__ float2 __fadd2_rd_impl(float2 x, float2 y); + __device__ __device_builtin__ float2 __fadd2_ru_impl(float2 x, float2 y); + + __device__ __device_builtin__ float2 __fmul2_rn_impl(float2 x, float2 y); + __device__ __device_builtin__ float2 __fmul2_rz_impl(float2 x, float2 y); + __device__ __device_builtin__ float2 __fmul2_rd_impl(float2 x, float2 y); + __device__ __device_builtin__ float2 __fmul2_ru_impl(float2 x, float2 y); +} // extern "C" + +__SM_100_RT_DECL__ float2 __ffma2_rn(float2 x, float2 y, float2 z) { + return __ffma2_rn_impl(x, y, z); +} +__SM_100_RT_DECL__ float2 __ffma2_rz(float2 x, float2 y, float2 z) { + return __ffma2_rz_impl(x, y, z); +} +__SM_100_RT_DECL__ float2 __ffma2_rd(float2 x, float2 y, float2 z) { + return __ffma2_rd_impl(x, y, z); +} +__SM_100_RT_DECL__ float2 __ffma2_ru(float2 x, float2 y, float2 z) { + return __ffma2_ru_impl(x, y, z); +} + +__SM_100_RT_DECL__ float2 __fadd2_rn(float2 x, float2 y) { + return __fadd2_rn_impl(x, y); +} +__SM_100_RT_DECL__ float2 __fadd2_rz(float2 x, float2 y) { + return __fadd2_rz_impl(x, y); +} +__SM_100_RT_DECL__ float2 __fadd2_rd(float2 x, float2 y) { + return __fadd2_rd_impl(x, y); +} +__SM_100_RT_DECL__ float2 __fadd2_ru(float2 x, float2 y) { + return __fadd2_ru_impl(x, y); +} + +__SM_100_RT_DECL__ float2 __fmul2_rn(float2 x, float2 y) { + return __fmul2_rn_impl(x, y); +} +__SM_100_RT_DECL__ float2 __fmul2_rz(float2 x, float2 y) { + return __fmul2_rz_impl(x, y); +} +__SM_100_RT_DECL__ float2 __fmul2_rd(float2 x, float2 y) { + return __fmul2_rd_impl(x, y); +} +__SM_100_RT_DECL__ float2 __fmul2_ru(float2 x, float2 y) { + return __fmul2_ru_impl(x, y); +} + +#endif /* !__CUDA_ARCH__ || __CUDA_ARCH__ >= 1000 */ + +#endif /* __cplusplus && __CUDACC__ */ + +#undef __SM_100_RT_DECL__ + +#endif /* !__SM_100_RT_HPP__ */ + +#if defined(__UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_SM_100_RT_HPP__) +#undef __CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__ +#undef __UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_SM_100_RT_HPP__ +#endif diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/sm_70_rt.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/sm_70_rt.h new file mode 100644 index 0000000000000000000000000000000000000000..6046953afa8c5f71cf7058436de10397d6353e9e --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/sm_70_rt.h @@ -0,0 +1,139 @@ +/* + * Copyright 2017-2018 NVIDIA Corporation. All rights reserved. + * + * NOTICE TO LICENSEE: + * + * This source code and/or documentation ("Licensed Deliverables") are + * subject to NVIDIA intellectual property rights under U.S. and + * international Copyright laws. + * + * These Licensed Deliverables contained herein is PROPRIETARY and + * CONFIDENTIAL to NVIDIA and is being provided under the terms and + * conditions of a form of NVIDIA software license agreement by and + * between NVIDIA and Licensee ("License Agreement") or electronically + * accepted by Licensee. Notwithstanding any terms or conditions to + * the contrary in the License Agreement, reproduction or disclosure + * of the Licensed Deliverables to any third party without the express + * written consent of NVIDIA is prohibited. + * + * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE + * LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE + * SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE. IT IS + * PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND. + * NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED + * DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY, + * NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE. + * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE + * LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY + * SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY + * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS + * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THESE LICENSED DELIVERABLES. + * + * U.S. Government End Users. These Licensed Deliverables are a + * "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT + * 1995), consisting of "commercial computer software" and "commercial + * computer software documentation" as such terms are used in 48 + * C.F.R. 12.212 (SEPT 1995) and is provided to the U.S. Government + * only as a commercial end item. Consistent with 48 C.F.R.12.212 and + * 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all + * U.S. Government End Users acquire the Licensed Deliverables with + * only those rights set forth herein. + * + * Any use of the Licensed Deliverables in individual and commercial + * software must include, in the user documentation and internal + * comments to the code, the above Disclaimer and U.S. Government End + * Users Notice. + */ + + //NOTE: For NVRTC, these declarations have been moved into the compiler (to reduce compile time) +#define EXCLUDE_FROM_RTC + +#if !defined(__CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__) +#if defined(_MSC_VER) +#pragma message("crt/sm_70_rt.h is an internal header file and must not be used directly. Please use cuda_runtime_api.h or cuda_runtime.h instead.") +#else +#warning "crt/sm_70_rt.h is an internal header file and must not be used directly. Please use cuda_runtime_api.h or cuda_runtime.h instead." +#endif +#define __CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__ +#define __UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_SM_70_RT_H__ +#endif + +#if !defined(__SM_70_RT_H__) +#define __SM_70_RT_H__ + +#if defined(__CUDACC_RTC__) +#define __SM_70_RT_DECL__ __host__ __device__ +#elif defined(_NVHPC_CUDA) +#define __SM_70_RT_DECL__ extern __device__ __cudart_builtin__ +#else /* !__CUDACC_RTC__ */ +#define __SM_70_RT_DECL__ static __device__ __inline__ +#endif /* __CUDACC_RTC__ */ + +#if defined(__cplusplus) && defined(__CUDACC__) + +#if !defined(__CUDA_ARCH__) || __CUDA_ARCH__ >= 700 + +/******************************************************************************* +* * +* * +* * +*******************************************************************************/ + +#include "builtin_types.h" +#include "device_types.h" +#include "host_defines.h" + +#if !defined(__CUDA_ARCH__) && !defined(_NVHPC_CUDA) +#define __DEF_IF_HOST { } +#else /* !__CUDA_ARCH__ */ +#define __DEF_IF_HOST ; +#endif /* __CUDA_ARCH__ */ + + +/****************************************************************************** + * match * + ******************************************************************************/ +__SM_70_RT_DECL__ unsigned int __match_any_sync(unsigned mask, unsigned value) __DEF_IF_HOST +__SM_70_RT_DECL__ unsigned int __match_any_sync(unsigned mask, int value) __DEF_IF_HOST +__SM_70_RT_DECL__ unsigned int __match_any_sync(unsigned mask, unsigned long value) __DEF_IF_HOST +__SM_70_RT_DECL__ unsigned int __match_any_sync(unsigned mask, long value) __DEF_IF_HOST +__SM_70_RT_DECL__ unsigned int __match_any_sync(unsigned mask, unsigned long long value) __DEF_IF_HOST +__SM_70_RT_DECL__ unsigned int __match_any_sync(unsigned mask, long long value) __DEF_IF_HOST +__SM_70_RT_DECL__ unsigned int __match_any_sync(unsigned mask, float value) __DEF_IF_HOST +__SM_70_RT_DECL__ unsigned int __match_any_sync(unsigned mask, double value) __DEF_IF_HOST + +__SM_70_RT_DECL__ unsigned int __match_all_sync(unsigned mask, unsigned value, int *pred) __DEF_IF_HOST +__SM_70_RT_DECL__ unsigned int __match_all_sync(unsigned mask, int value, int *pred) __DEF_IF_HOST +__SM_70_RT_DECL__ unsigned int __match_all_sync(unsigned mask, unsigned long value, int *pred) __DEF_IF_HOST +__SM_70_RT_DECL__ unsigned int __match_all_sync(unsigned mask, long value, int *pred) __DEF_IF_HOST +__SM_70_RT_DECL__ unsigned int __match_all_sync(unsigned mask, unsigned long long value, int *pred) __DEF_IF_HOST +__SM_70_RT_DECL__ unsigned int __match_all_sync(unsigned mask, long long value, int *pred) __DEF_IF_HOST +__SM_70_RT_DECL__ unsigned int __match_all_sync(unsigned mask, float value, int *pred) __DEF_IF_HOST +__SM_70_RT_DECL__ unsigned int __match_all_sync(unsigned mask, double value, int *pred) __DEF_IF_HOST + +__SM_70_RT_DECL__ void __nanosleep(unsigned int ns) __DEF_IF_HOST + +__SM_70_RT_DECL__ unsigned short int atomicCAS(unsigned short int *address, unsigned short int compare, unsigned short int val) __DEF_IF_HOST + +#endif /* !__CUDA_ARCH__ || __CUDA_ARCH__ >= 700 */ + +#endif /* __cplusplus && __CUDACC__ */ + +#undef __DEF_IF_HOST +#undef __SM_70_RT_DECL__ + +#if (!defined(__CUDACC_RTC__) && defined(__CUDA_ARCH__)) || defined(_NVHPC_CUDA) +#include "sm_70_rt.hpp" +#endif /* (!defined(__CUDACC_RTC__) && defined(__CUDA_ARCH__)) || defined(_NVHPC_CUDA) */ + +#endif /* !__SM_70_RT_H__ */ + +#if defined(__UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_SM_70_RT_H__) +#undef __CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__ +#undef __UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_SM_70_RT_H__ +#endif + + +#undef EXCLUDE_FROM_RTC \ No newline at end of file diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/sm_70_rt.hpp b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/sm_70_rt.hpp new file mode 100644 index 0000000000000000000000000000000000000000..322496587325a1387e4280a509455e3ccc7caa1b --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/sm_70_rt.hpp @@ -0,0 +1,192 @@ +/* + * Copyright 2017-2021 NVIDIA Corporation. All rights reserved. + * + * NOTICE TO LICENSEE: + * + * This source code and/or documentation ("Licensed Deliverables") are + * subject to NVIDIA intellectual property rights under U.S. and + * international Copyright laws. + * + * These Licensed Deliverables contained herein is PROPRIETARY and + * CONFIDENTIAL to NVIDIA and is being provided under the terms and + * conditions of a form of NVIDIA software license agreement by and + * between NVIDIA and Licensee ("License Agreement") or electronically + * accepted by Licensee. Notwithstanding any terms or conditions to + * the contrary in the License Agreement, reproduction or disclosure + * of the Licensed Deliverables to any third party without the express + * written consent of NVIDIA is prohibited. + * + * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE + * LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE + * SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE. IT IS + * PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND. + * NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED + * DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY, + * NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE. + * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE + * LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY + * SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY + * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS + * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THESE LICENSED DELIVERABLES. + * + * U.S. Government End Users. These Licensed Deliverables are a + * "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT + * 1995), consisting of "commercial computer software" and "commercial + * computer software documentation" as such terms are used in 48 + * C.F.R. 12.212 (SEPT 1995) and is provided to the U.S. Government + * only as a commercial end item. Consistent with 48 C.F.R.12.212 and + * 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all + * U.S. Government End Users acquire the Licensed Deliverables with + * only those rights set forth herein. + * + * Any use of the Licensed Deliverables in individual and commercial + * software must include, in the user documentation and internal + * comments to the code, the above Disclaimer and U.S. Government End + * Users Notice. + */ + +#if !defined(__CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__) +#if defined(_MSC_VER) +#pragma message("crt/sm_70_rt.hpp is an internal header file and must not be used directly. Please use cuda_runtime_api.h or cuda_runtime.h instead.") +#else +#warning "crt/sm_70_rt.hpp is an internal header file and must not be used directly. Please use cuda_runtime_api.h or cuda_runtime.h instead." +#endif +#define __CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__ +#define __UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_SM_70_RT_HPP__ +#endif + +#if !defined(__SM_70_RT_HPP__) +#define __SM_70_RT_HPP__ + +#if defined(__CUDACC_RTC__) +#define __SM_70_RT_DECL__ __host__ __device__ +#else /* !__CUDACC_RTC__ */ +#define __SM_70_RT_DECL__ static __device__ __inline__ +#endif /* __CUDACC_RTC__ */ + +#if defined(__cplusplus) && defined(__CUDACC__) + +#if !defined(__CUDA_ARCH__) || __CUDA_ARCH__ >= 700 + +/******************************************************************************* +* * +* * +* * +*******************************************************************************/ + +#include "builtin_types.h" +#include "device_types.h" +#include "host_defines.h" + +/******************************************************************************* +* * +* Below are implementations of SM-7.0 builtin functions which are included as * +* source (instead of being built in to the compiler) * +* * +*******************************************************************************/ + +// +// __match_any_sync +// +__SM_70_RT_DECL__ unsigned int __match_any_sync(unsigned mask, unsigned value) { + return __match32_any_sync(mask, value); +} + +__SM_70_RT_DECL__ unsigned int __match_any_sync(unsigned mask, int value) { + return __match32_any_sync(mask, value); +} + +__SM_70_RT_DECL__ unsigned int __match_any_sync(unsigned mask, unsigned long value) { + return (sizeof(long) == sizeof(long long)) ? + __match64_any_sync(mask, (unsigned long long)value): + __match32_any_sync(mask, (unsigned)value); +} + +__SM_70_RT_DECL__ unsigned int __match_any_sync(unsigned mask, long value) { + return (sizeof(long) == sizeof(long long)) ? + __match64_any_sync(mask, (unsigned long long)value): + __match32_any_sync(mask, (unsigned)value); +} + +__SM_70_RT_DECL__ unsigned int __match_any_sync(unsigned mask, unsigned long long value) { + return __match64_any_sync(mask, value); +} + +__SM_70_RT_DECL__ unsigned int __match_any_sync(unsigned mask, long long value) { + return __match64_any_sync(mask, value); +} + +__SM_70_RT_DECL__ unsigned int __match_any_sync(unsigned mask, float value) { + return __match32_any_sync(mask, __float_as_uint(value)); +} + +__SM_70_RT_DECL__ unsigned int __match_any_sync(unsigned mask, double value) { + return __match64_any_sync(mask, __double_as_longlong(value)); +} + +// +// __match_all_sync +// +__SM_70_RT_DECL__ unsigned int __match_all_sync(unsigned mask, unsigned value, int *pred) { + return __match32_all_sync(mask, value, pred); +} + +__SM_70_RT_DECL__ unsigned int __match_all_sync(unsigned mask, int value, int *pred) { + return __match32_all_sync(mask, value, pred); +} + +__SM_70_RT_DECL__ unsigned int __match_all_sync(unsigned mask, unsigned long value, int *pred) { + return (sizeof(long) == sizeof(long long)) ? + __match64_all_sync(mask, (unsigned long long)value, pred): + __match32_all_sync(mask, (unsigned)value, pred); +} + +__SM_70_RT_DECL__ unsigned int __match_all_sync(unsigned mask, long value, int *pred) { + return (sizeof(long) == sizeof(long long)) ? + __match64_all_sync(mask, (unsigned long long)value, pred): + __match32_all_sync(mask, (unsigned)value, pred); +} + +__SM_70_RT_DECL__ unsigned int __match_all_sync(unsigned mask, unsigned long long value, int *pred) { + return __match64_all_sync(mask, value, pred); +} + +__SM_70_RT_DECL__ unsigned int __match_all_sync(unsigned mask, long long value, int *pred) { + return __match64_all_sync(mask, value, pred); +} + +__SM_70_RT_DECL__ unsigned int __match_all_sync(unsigned mask, float value, int *pred) { + return __match32_all_sync(mask, __float_as_uint(value), pred); +} + +__SM_70_RT_DECL__ unsigned int __match_all_sync(unsigned mask, double value, int *pred) { + return __match64_all_sync(mask, __double_as_longlong(value), pred); +} + +__SM_70_RT_DECL__ void __nanosleep(unsigned int ns) { + asm volatile("nanosleep.u32 %0;" :: "r"(ns)); +} + + +extern "C" __device__ __device_builtin__ +unsigned short __usAtomicCAS(unsigned short *, unsigned short, unsigned short); + +__SM_70_RT_DECL__ unsigned short int atomicCAS(unsigned short int *address, unsigned short int compare, unsigned short int val) { + return __usAtomicCAS(address, compare, val); +} + + +#endif /* !__CUDA_ARCH__ || __CUDA_ARCH__ >= 700 */ + +#endif /* __cplusplus && __CUDACC__ */ + +#undef __SM_70_RT_DECL__ + +#endif /* !__SM_70_RT_HPP__ */ + +#if defined(__UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_SM_70_RT_HPP__) +#undef __CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__ +#undef __UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_SM_70_RT_HPP__ +#endif diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/sm_80_rt.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/sm_80_rt.h new file mode 100644 index 0000000000000000000000000000000000000000..cc18290966875591b6a6efa1f8564eb76e5aa34b --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/sm_80_rt.h @@ -0,0 +1,164 @@ +/* + * Copyright 2017-2021 NVIDIA Corporation. All rights reserved. + * + * NOTICE TO LICENSEE: + * + * This source code and/or documentation ("Licensed Deliverables") are + * subject to NVIDIA intellectual property rights under U.S. and + * international Copyright laws. + * + * These Licensed Deliverables contained herein is PROPRIETARY and + * CONFIDENTIAL to NVIDIA and is being provided under the terms and + * conditions of a form of NVIDIA software license agreement by and + * between NVIDIA and Licensee ("License Agreement") or electronically + * accepted by Licensee. Notwithstanding any terms or conditions to + * the contrary in the License Agreement, reproduction or disclosure + * of the Licensed Deliverables to any third party without the express + * written consent of NVIDIA is prohibited. + * + * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE + * LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE + * SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE. IT IS + * PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND. + * NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED + * DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY, + * NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE. + * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE + * LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY + * SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY + * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS + * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THESE LICENSED DELIVERABLES. + * + * U.S. Government End Users. These Licensed Deliverables are a + * "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT + * 1995), consisting of "commercial computer software" and "commercial + * computer software documentation" as such terms are used in 48 + * C.F.R. 12.212 (SEPT 1995) and is provided to the U.S. Government + * only as a commercial end item. Consistent with 48 C.F.R.12.212 and + * 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all + * U.S. Government End Users acquire the Licensed Deliverables with + * only those rights set forth herein. + * + * Any use of the Licensed Deliverables in individual and commercial + * software must include, in the user documentation and internal + * comments to the code, the above Disclaimer and U.S. Government End + * Users Notice. + */ + +#if !defined(__CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__) +#if defined(_MSC_VER) +#pragma message("crt/sm_80_rt.h is an internal header file and must not be used directly. Please use cuda_runtime_api.h or cuda_runtime.h instead.") +#else +#warning "crt/sm_80_rt.h is an internal header file and must not be used directly. Please use cuda_runtime_api.h or cuda_runtime.h instead." +#endif +#define __CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__ +#define __UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_SM_80_RT_H__ +#endif + +#if !defined(__SM_80_RT_H__) +#define __SM_80_RT_H__ + +#if defined(__CUDACC_RTC__) +#define __SM_80_RT_DECL__ __host__ __device__ +#elif defined(_NVHPC_CUDA) +#define __SM_80_RT_DECL__ extern __device__ __cudart_builtin__ +#else /* !__CUDACC_RTC__ */ +#define __SM_80_RT_DECL__ static __device__ __inline__ +#endif /* __CUDACC_RTC__ */ + +#if defined(__cplusplus) && defined(__CUDACC__) + +#if !defined(__CUDA_ARCH__) || __CUDA_ARCH__ >= 800 + +/******************************************************************************* +* * +* * +* * +*******************************************************************************/ + +#include "builtin_types.h" +#include "device_types.h" +#include "host_defines.h" + +#if !defined(__CUDA_ARCH__) && !defined(_NVHPC_CUDA) +#define __DEF_IF_HOST { } +#else /* !__CUDA_ARCH__ */ +#define __DEF_IF_HOST ; +#endif /* __CUDA_ARCH__ */ + + +//NOTE: For NVRTC, these declarations have been moved into the compiler (to reduce compile time) +#define EXCLUDE_FROM_RTC +/****************************************************************************** + * reduce * + ******************************************************************************/ +__SM_80_RT_DECL__ unsigned __reduce_add_sync(unsigned mask, unsigned value) __DEF_IF_HOST +__SM_80_RT_DECL__ unsigned __reduce_min_sync(unsigned mask, unsigned value) __DEF_IF_HOST +__SM_80_RT_DECL__ unsigned __reduce_max_sync(unsigned mask, unsigned value) __DEF_IF_HOST + +__SM_80_RT_DECL__ int __reduce_add_sync(unsigned mask, int value) __DEF_IF_HOST +__SM_80_RT_DECL__ int __reduce_min_sync(unsigned mask, int value) __DEF_IF_HOST +__SM_80_RT_DECL__ int __reduce_max_sync(unsigned mask, int value) __DEF_IF_HOST + +__SM_80_RT_DECL__ unsigned __reduce_and_sync(unsigned mask, unsigned value) __DEF_IF_HOST +__SM_80_RT_DECL__ unsigned __reduce_or_sync(unsigned mask, unsigned value) __DEF_IF_HOST +__SM_80_RT_DECL__ unsigned __reduce_xor_sync(unsigned mask, unsigned value) __DEF_IF_HOST + +#undef EXCLUDE_FROM_RTC + + +extern "C" { +inline __device__ void *__nv_associate_access_property(const void *ptr, + unsigned long long property) { + extern __device__ void *__nv_associate_access_property_impl(const void *, + unsigned long long); + return __nv_associate_access_property_impl(ptr, property); +} + +inline __device__ void __nv_memcpy_async_shared_global_4(void *dst, + const void *src, + unsigned src_size) { + extern __device__ void __nv_memcpy_async_shared_global_4_impl(void *, + const void *, + unsigned); + __nv_memcpy_async_shared_global_4_impl(dst, src, src_size); +} + +inline __device__ void __nv_memcpy_async_shared_global_8(void *dst, + const void *src, + unsigned src_size) { + extern __device__ void __nv_memcpy_async_shared_global_8_impl(void *, + const void *, + unsigned); + __nv_memcpy_async_shared_global_8_impl(dst, src, src_size); +} + +inline __device__ void __nv_memcpy_async_shared_global_16(void *dst, + const void *src, + unsigned src_size) { + extern __device__ void __nv_memcpy_async_shared_global_16_impl(void *, + const void *, + unsigned); + __nv_memcpy_async_shared_global_16_impl(dst, src, src_size); +} + +} +#endif /* !__CUDA_ARCH__ || __CUDA_ARCH__ >= 800 */ + +#endif /* __cplusplus && __CUDACC__ */ + +#undef __DEF_IF_HOST +#undef __SM_80_RT_DECL__ + +#if (!defined(__CUDACC_RTC__) && defined(__CUDA_ARCH__)) || defined(_NVHPC_CUDA) +#include "sm_80_rt.hpp" +#endif /* !__CUDACC_RTC__ && defined(__CUDA_ARCH__) */ + +#endif /* !__SM_80_RT_H__ */ + +#if defined(__UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_SM_80_RT_H__) +#undef __CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__ +#undef __UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_SM_80_RT_H__ +#endif diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/sm_80_rt.hpp b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/sm_80_rt.hpp new file mode 100644 index 0000000000000000000000000000000000000000..857bd44a3bb0d8480560047a85f9059bc370b52f --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/sm_80_rt.hpp @@ -0,0 +1,148 @@ +/* + * Copyright 2017-2021 NVIDIA Corporation. All rights reserved. + * + * NOTICE TO LICENSEE: + * + * This source code and/or documentation ("Licensed Deliverables") are + * subject to NVIDIA intellectual property rights under U.S. and + * international Copyright laws. + * + * These Licensed Deliverables contained herein is PROPRIETARY and + * CONFIDENTIAL to NVIDIA and is being provided under the terms and + * conditions of a form of NVIDIA software license agreement by and + * between NVIDIA and Licensee ("License Agreement") or electronically + * accepted by Licensee. Notwithstanding any terms or conditions to + * the contrary in the License Agreement, reproduction or disclosure + * of the Licensed Deliverables to any third party without the express + * written consent of NVIDIA is prohibited. + * + * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE + * LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE + * SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE. IT IS + * PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND. + * NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED + * DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY, + * NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE. + * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE + * LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY + * SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY + * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS + * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THESE LICENSED DELIVERABLES. + * + * U.S. Government End Users. These Licensed Deliverables are a + * "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT + * 1995), consisting of "commercial computer software" and "commercial + * computer software documentation" as such terms are used in 48 + * C.F.R. 12.212 (SEPT 1995) and is provided to the U.S. Government + * only as a commercial end item. Consistent with 48 C.F.R.12.212 and + * 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all + * U.S. Government End Users acquire the Licensed Deliverables with + * only those rights set forth herein. + * + * Any use of the Licensed Deliverables in individual and commercial + * software must include, in the user documentation and internal + * comments to the code, the above Disclaimer and U.S. Government End + * Users Notice. + */ + +#if !defined(__CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__) +#if defined(_MSC_VER) +#pragma message("crt/sm_80_rt.hpp is an internal header file and must not be used directly. Please use cuda_runtime_api.h or cuda_runtime.h instead.") +#else +#warning "crt/sm_80_rt.hpp is an internal header file and must not be used directly. Please use cuda_runtime_api.h or cuda_runtime.h instead." +#endif +#define __CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__ +#define __UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_SM_80_RT_HPP__ +#endif + +#if !defined(__SM_80_RT_HPP__) +#define __SM_80_RT_HPP__ + +#if defined(__CUDACC_RTC__) +#define __SM_80_RT_DECL__ __host__ __device__ +#else /* !__CUDACC_RTC__ */ +#define __SM_80_RT_DECL__ static __device__ __inline__ +#endif /* __CUDACC_RTC__ */ + +#if defined(__cplusplus) && defined(__CUDACC__) + +#if !defined(__CUDA_ARCH__) || __CUDA_ARCH__ >= 800 + +/******************************************************************************* +* * +* * +* * +*******************************************************************************/ + +#include "builtin_types.h" +#include "device_types.h" +#include "host_defines.h" + +/******************************************************************************* +* * +* Below are implementations of SM-8.0 builtin functions which are included as * +* source (instead of being built in to the compiler) * +* * +*******************************************************************************/ + +extern "C" { + __device_builtin__ __device__ unsigned __reduce_add_sync_unsigned_impl(unsigned, unsigned); + __device_builtin__ __device__ unsigned __reduce_min_sync_unsigned_impl(unsigned, unsigned); + __device_builtin__ __device__ unsigned __reduce_max_sync_unsigned_impl(unsigned, unsigned); + __device_builtin__ __device__ int __reduce_add_sync_signed_impl(unsigned, int); + __device_builtin__ __device__ int __reduce_min_sync_signed_impl(unsigned, int); + __device_builtin__ __device__ int __reduce_max_sync_signed_impl(unsigned, int); + __device_builtin__ __device__ unsigned __reduce_or_sync_unsigned_impl(unsigned, unsigned); + __device_builtin__ __device__ unsigned __reduce_and_sync_unsigned_impl(unsigned, unsigned); + __device_builtin__ __device__ unsigned __reduce_xor_sync_unsigned_impl(unsigned, unsigned); +} + +__SM_80_RT_DECL__ unsigned __reduce_add_sync(unsigned mask, unsigned value) { + return __reduce_add_sync_unsigned_impl(mask, value); +} + +__SM_80_RT_DECL__ unsigned __reduce_min_sync(unsigned mask, unsigned value) { + return __reduce_min_sync_unsigned_impl(mask, value); +} + +__SM_80_RT_DECL__ unsigned __reduce_max_sync(unsigned mask, unsigned value) { + return __reduce_max_sync_unsigned_impl(mask, value); +} + +__SM_80_RT_DECL__ int __reduce_add_sync(unsigned mask, int value) { + return __reduce_add_sync_signed_impl(mask, value); +} + +__SM_80_RT_DECL__ int __reduce_min_sync(unsigned mask, int value) { + return __reduce_min_sync_signed_impl(mask, value); +} + +__SM_80_RT_DECL__ int __reduce_max_sync(unsigned mask, int value) { + return __reduce_max_sync_signed_impl(mask, value); +} + +__SM_80_RT_DECL__ unsigned __reduce_and_sync(unsigned mask, unsigned value) { + return __reduce_and_sync_unsigned_impl(mask, value); +} + +__SM_80_RT_DECL__ unsigned __reduce_or_sync(unsigned mask, unsigned value) { + return __reduce_or_sync_unsigned_impl(mask, value); +} + +__SM_80_RT_DECL__ unsigned __reduce_xor_sync(unsigned mask, unsigned value) { + return __reduce_xor_sync_unsigned_impl(mask, value); +} +#endif /* !__CUDA_ARCH__ || __CUDA_ARCH__ >= 800 */ + +#endif /* __cplusplus && __CUDACC__ */ + +#undef __SM_80_RT_DECL__ + +#endif /* !__SM_80_RT_HPP__ */ + +#if defined(__UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_SM_80_RT_HPP__) +#undef __CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__ +#undef __UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_SM_80_RT_HPP__ +#endif diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/sm_90_rt.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/sm_90_rt.h new file mode 100644 index 0000000000000000000000000000000000000000..8e250634fe76651c2a15b5b492378efec1d3e0c5 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/sm_90_rt.h @@ -0,0 +1,282 @@ +/* + * Copyright 2022-2023 NVIDIA Corporation. All rights reserved. + * + * NOTICE TO LICENSEE: + * + * This source code and/or documentation ("Licensed Deliverables") are + * subject to NVIDIA intellectual property rights under U.S. and + * international Copyright laws. + * + * These Licensed Deliverables contained herein is PROPRIETARY and + * CONFIDENTIAL to NVIDIA and is being provided under the terms and + * conditions of a form of NVIDIA software license agreement by and + * between NVIDIA and Licensee ("License Agreement") or electronically + * accepted by Licensee. Notwithstanding any terms or conditions to + * the contrary in the License Agreement, reproduction or disclosure + * of the Licensed Deliverables to any third party without the express + * written consent of NVIDIA is prohibited. + * + * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE + * LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE + * SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE. IT IS + * PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND. + * NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED + * DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY, + * NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE. + * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE + * LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY + * SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY + * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS + * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THESE LICENSED DELIVERABLES. + * + * U.S. Government End Users. These Licensed Deliverables are a + * "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT + * 1995), consisting of "commercial computer software" and "commercial + * computer software documentation" as such terms are used in 48 + * C.F.R. 12.212 (SEPT 1995) and is provided to the U.S. Government + * only as a commercial end item. Consistent with 48 C.F.R.12.212 and + * 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all + * U.S. Government End Users acquire the Licensed Deliverables with + * only those rights set forth herein. + * + * Any use of the Licensed Deliverables in individual and commercial + * software must include, in the user documentation and internal + * comments to the code, the above Disclaimer and U.S. Government End + * Users Notice. + */ + +#if !defined(__CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__) +#if defined(_MSC_VER) +#pragma message("crt/sm_90_rt.h is an internal header file and must not be used directly. Please use cuda_runtime_api.h or cuda_runtime.h instead.") +#else +#warning "crt/sm_90_rt.h is an internal header file and must not be used directly. Please use cuda_runtime_api.h or cuda_runtime.h instead." +#endif +#define __CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__ +#define __UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_SM_90_RT_H__ +#endif + +#if !defined(__SM_90_RT_H__) +#define __SM_90_RT_H__ + +#if defined(__CUDACC_RTC__) +#define __SM_90_RT_DECL__ __host__ __device__ +#else /* !__CUDACC_RTC__ */ +#define __SM_90_RT_DECL__ static __device__ __inline__ +#endif /* __CUDACC_RTC__ */ + +#if defined(__cplusplus) && defined(__CUDACC__) + +#if !defined(__CUDA_ARCH__) || __CUDA_ARCH__ >= 900 + +/******************************************************************************* +* * +* * +* * +*******************************************************************************/ + +#include "builtin_types.h" +#include "device_types.h" +#include "host_defines.h" + +#if !defined(__CUDA_ARCH__) && !defined(_NVHPC_CUDA) +#define __DEF_IF_HOST { } +#else /* !__CUDA_ARCH__ && !_NVHPC_CUDA */ +#define __DEF_IF_HOST ; +#endif /* __CUDA_ARCH__ || _NVHPC_CUDA */ + +//NOTE: For NVRTC, these declarations have been moved into the compiler (to reduce compile time) +#define EXCLUDE_FROM_RTC + +__SM_90_RT_DECL__ unsigned __isCtaShared(const void *ptr) __DEF_IF_HOST +__SM_90_RT_DECL__ unsigned __isClusterShared(const void *ptr) __DEF_IF_HOST +__SM_90_RT_DECL__ void *__cluster_map_shared_rank(const void *ptr, unsigned target_block_rank) __DEF_IF_HOST +__SM_90_RT_DECL__ unsigned __cluster_query_shared_rank(const void *ptr) __DEF_IF_HOST +__SM_90_RT_DECL__ uint2 __cluster_map_shared_multicast(const void *ptr, unsigned cluster_cta_mask) __DEF_IF_HOST +__SM_90_RT_DECL__ unsigned __clusterDimIsSpecified() __DEF_IF_HOST +__SM_90_RT_DECL__ dim3 __clusterDim() __DEF_IF_HOST +__SM_90_RT_DECL__ dim3 __clusterRelativeBlockIdx() __DEF_IF_HOST +__SM_90_RT_DECL__ dim3 __clusterGridDimInClusters() __DEF_IF_HOST +__SM_90_RT_DECL__ dim3 __clusterIdx() __DEF_IF_HOST +__SM_90_RT_DECL__ unsigned __clusterRelativeBlockRank() __DEF_IF_HOST +__SM_90_RT_DECL__ unsigned __clusterSizeInBlocks() __DEF_IF_HOST +__SM_90_RT_DECL__ void __cluster_barrier_arrive() __DEF_IF_HOST +__SM_90_RT_DECL__ void __cluster_barrier_arrive_relaxed() __DEF_IF_HOST +__SM_90_RT_DECL__ void __cluster_barrier_wait() __DEF_IF_HOST +__SM_90_RT_DECL__ void __threadfence_cluster() __DEF_IF_HOST + +__SM_90_RT_DECL__ float2 atomicAdd(float2 *__address, float2 val) __DEF_IF_HOST +__SM_90_RT_DECL__ float2 atomicAdd_block(float2 *__address, float2 val) __DEF_IF_HOST +__SM_90_RT_DECL__ float2 atomicAdd_system(float2 *__address, float2 val) __DEF_IF_HOST +__SM_90_RT_DECL__ float4 atomicAdd(float4 *__address, float4 val) __DEF_IF_HOST +__SM_90_RT_DECL__ float4 atomicAdd_block(float4 *__address, float4 val) __DEF_IF_HOST +__SM_90_RT_DECL__ float4 atomicAdd_system(float4 *__address, float4 val) __DEF_IF_HOST + +#undef EXCLUDE_FROM_RTC + +//Note: below atomic functions are templates, so cannot be represented in NVRTC +//builtins representation, so they have to be parsed on every NVRTC compilation. +//(notice 'EXCLUDE_FROM_RTC' ends above) + + +#ifndef __NV_DISABLE_128_ATOMICS +// lgen definitions for 128b atomics +extern "C" { + __device__ __device_builtin__ void __u128AtomicCAS(void *, void *, void *, void *); + __device__ __device_builtin__ void __u128AtomicCAS_block(void *, void *, void *, void *); + __device__ __device_builtin__ void __u128AtomicCAS_system(void *, void *, void *, void *); + __device__ __device_builtin__ void __u128AtomicExch(void *, void *, void *); + __device__ __device_builtin__ void __u128AtomicExch_block(void *, void *, void *); + __device__ __device_builtin__ void __u128AtomicExch_system(void *, void *, void *); +} + +// macro to get address of object, to workaround situations where the type overloads the "&" operator +#define __NV_ATOMIC_ADDRESSOF(__val) \ + (void *)(&(const_cast(reinterpret_cast(__val)))) + +// enable_if +template +struct __nv_atomic_enable_if { }; + +template +struct __nv_atomic_enable_if { typedef _T __type; }; + +// alignof +#if defined(__CUDACC_RTC__) +#define __NV_ATOMIC_ALIGNOF __alignof__ +#else +#define __NV_ATOMIC_ALIGNOF __alignof +#endif + +// trivially copyable +template +struct __nv_atomic_triv_cp_helper { +#if defined(__GNUC__) +#if (__GNUC__ < 4) || (__GNUC__ == 4 && __GNUC_MINOR__ < 3) + static const bool __val = true; +#elif (__GNUC__ < 5) + static const bool __val = __has_trivial_copy(_T); +#else + static const bool __val = __is_trivially_copyable(_T); +#endif +#else + static const bool __val = __is_trivially_copyable(_T); +#endif +}; +#define __NV_ATOMIC_TRIVIALLY_COPYABLE(_T) \ + __nv_atomic_triv_cp_helper<_T>::__val + +// return type +#if __cplusplus >= 202002L // C++20 or greater +#define __NV_ATOMIC_RET_TYPE(_T) _T +#else +#define __NV_ATOMIC_RET_TYPE(_T) typename \ + __nv_atomic_enable_if= 16 && \ + __NV_ATOMIC_TRIVIALLY_COPYABLE(_T), _T>::__type +#endif + +// requires +#if __cplusplus >= 202002L // C++20 or greater +#define __NV_ATOMIC_REQUIRES(_T) \ + requires(sizeof(_T) == 16 && \ + __NV_ATOMIC_ALIGNOF(_T) >= 16 && \ + __NV_ATOMIC_TRIVIALLY_COPYABLE(_T)) +#else +#define __NV_ATOMIC_REQUIRES(_T) +#endif + +// temp value and return value +#if __cplusplus >= 201103L || defined(_MSC_VER) // C++11 or greater, or MSC +#define __NV_ATOMIC_TEMP(_T) union _U \ + {_T __ret; __device__ __inline__ _U() {}}; _U __u +#define __NV_ATOMIC_RET(_T) __u.__ret +#else +#define __NV_ATOMIC_TEMP(_T) _T __ret +#define __NV_ATOMIC_RET(_T) __ret +#endif + +// templated 128-bit atomics +template +__SM_90_RT_DECL__ __NV_ATOMIC_RET_TYPE(_T) +atomicCAS(_T *__address, _T __compare, _T __val) __NV_ATOMIC_REQUIRES(_T) { + __NV_ATOMIC_TEMP(_T); + __u128AtomicCAS((void *)(__address), + __NV_ATOMIC_ADDRESSOF(__compare), + __NV_ATOMIC_ADDRESSOF(__val), + __NV_ATOMIC_ADDRESSOF(__NV_ATOMIC_RET(_T))); + return __NV_ATOMIC_RET(_T); +} + +template +__SM_90_RT_DECL__ __NV_ATOMIC_RET_TYPE(_T) +atomicCAS_block(_T *__address, _T __compare, _T __val) __NV_ATOMIC_REQUIRES(_T) { + __NV_ATOMIC_TEMP(_T); + __u128AtomicCAS_block((void *)(__address), + __NV_ATOMIC_ADDRESSOF(__compare), + __NV_ATOMIC_ADDRESSOF(__val), + __NV_ATOMIC_ADDRESSOF(__NV_ATOMIC_RET(_T))); + return __NV_ATOMIC_RET(_T); +} + +template +__SM_90_RT_DECL__ __NV_ATOMIC_RET_TYPE(_T) +atomicCAS_system(_T *__address, _T __compare, _T __val) __NV_ATOMIC_REQUIRES(_T) { + __NV_ATOMIC_TEMP(_T); + __u128AtomicCAS_system((void *)(__address), + __NV_ATOMIC_ADDRESSOF(__compare), + __NV_ATOMIC_ADDRESSOF(__val), + __NV_ATOMIC_ADDRESSOF(__NV_ATOMIC_RET(_T))); + return __NV_ATOMIC_RET(_T); +} + +template +__SM_90_RT_DECL__ __NV_ATOMIC_RET_TYPE(_T) +atomicExch(_T *__address, _T __val) __NV_ATOMIC_REQUIRES(_T) { + __NV_ATOMIC_TEMP(_T); + __u128AtomicExch((void *)(__address), + __NV_ATOMIC_ADDRESSOF(__val), + __NV_ATOMIC_ADDRESSOF(__NV_ATOMIC_RET(_T))); + return __NV_ATOMIC_RET(_T); +} + +template +__SM_90_RT_DECL__ __NV_ATOMIC_RET_TYPE(_T) +atomicExch_block(_T *__address, _T __val) __NV_ATOMIC_REQUIRES(_T) { + __NV_ATOMIC_TEMP(_T); + __u128AtomicExch_block((void *)(__address), + __NV_ATOMIC_ADDRESSOF(__val), + __NV_ATOMIC_ADDRESSOF(__NV_ATOMIC_RET(_T))); + return __NV_ATOMIC_RET(_T); +} + +template +__SM_90_RT_DECL__ __NV_ATOMIC_RET_TYPE(_T) +atomicExch_system(_T *__address, _T __val) __NV_ATOMIC_REQUIRES(_T) { + __NV_ATOMIC_TEMP(_T); + __u128AtomicExch_system((void *)(__address), + __NV_ATOMIC_ADDRESSOF(__val), + __NV_ATOMIC_ADDRESSOF(__NV_ATOMIC_RET(_T))); + return __NV_ATOMIC_RET(_T); +} +#endif /* !__NV_DISABLE_128_ATOMICS */ + +#endif /* !__CUDA_ARCH__ || __CUDA_ARCH__ >= 900 */ + +#endif /* __cplusplus && __CUDACC__ */ + +#undef __DEF_IF_HOST +#undef __SM_90_RT_DECL__ + +#if (!defined(__CUDACC_RTC__) && defined(__CUDA_ARCH__)) || defined(_NVHPC_CUDA) +#include "sm_90_rt.hpp" +#endif /* (!defined(__CUDACC_RTC__) && defined(__CUDA_ARCH__)) || defined(_NVHPC_CUDA) */ + +#endif /* !__SM_90_RT_H__ */ + +#if defined(__UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_SM_90_RT_H__) +#undef __CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__ +#undef __UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_SM_90_RT_H__ +#endif + diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/sm_90_rt.hpp b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/sm_90_rt.hpp new file mode 100644 index 0000000000000000000000000000000000000000..4e61ac78b996fa03cadf60208bbd58f2e781f3ec --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/sm_90_rt.hpp @@ -0,0 +1,248 @@ +/* + * Copyright 2022 NVIDIA Corporation. All rights reserved. + * + * NOTICE TO LICENSEE: + * + * This source code and/or documentation ("Licensed Deliverables") are + * subject to NVIDIA intellectual property rights under U.S. and + * international Copyright laws. + * + * These Licensed Deliverables contained herein is PROPRIETARY and + * CONFIDENTIAL to NVIDIA and is being provided under the terms and + * conditions of a form of NVIDIA software license agreement by and + * between NVIDIA and Licensee ("License Agreement") or electronically + * accepted by Licensee. Notwithstanding any terms or conditions to + * the contrary in the License Agreement, reproduction or disclosure + * of the Licensed Deliverables to any third party without the express + * written consent of NVIDIA is prohibited. + * + * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE + * LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE + * SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE. IT IS + * PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND. + * NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED + * DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY, + * NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE. + * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE + * LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY + * SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY + * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS + * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THESE LICENSED DELIVERABLES. + * + * U.S. Government End Users. These Licensed Deliverables are a + * "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT + * 1995), consisting of "commercial computer software" and "commercial + * computer software documentation" as such terms are used in 48 + * C.F.R. 12.212 (SEPT 1995) and is provided to the U.S. Government + * only as a commercial end item. Consistent with 48 C.F.R.12.212 and + * 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all + * U.S. Government End Users acquire the Licensed Deliverables with + * only those rights set forth herein. + * + * Any use of the Licensed Deliverables in individual and commercial + * software must include, in the user documentation and internal + * comments to the code, the above Disclaimer and U.S. Government End + * Users Notice. + */ + +#if !defined(__CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__) +#if defined(_MSC_VER) +#pragma message("crt/sm_90_rt.hpp is an internal header file and must not be used directly. Please use cuda_runtime_api.h or cuda_runtime.h instead.") +#else +#warning "crt/sm_90_rt.hpp is an internal header file and must not be used directly. Please use cuda_runtime_api.h or cuda_runtime.h instead." +#endif +#define __CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__ +#define __UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_SM_90_RT_HPP__ +#endif + +#if !defined(__SM_90_RT_HPP__) +#define __SM_90_RT_HPP__ + +#if defined(__CUDACC_RTC__) +#define __SM_90_RT_DECL__ __host__ __device__ +#else /* !__CUDACC_RTC__ */ +#define __SM_90_RT_DECL__ static __device__ __inline__ +#endif /* __CUDACC_RTC__ */ + +#if defined(__cplusplus) && defined(__CUDACC__) + +#if !defined(__CUDA_ARCH__) || __CUDA_ARCH__ >= 900 + +/******************************************************************************* +* * +* * +* * +*******************************************************************************/ + +#include "builtin_types.h" +#include "device_types.h" +#include "host_defines.h" + +/******************************************************************************* +* * +* Below are implementations of SM-9.0 builtin functions which are included as * +* source (instead of being built in to the compiler) * +* * +*******************************************************************************/ +extern "C" { + __device__ unsigned __nv_isClusterShared_impl(const void *); + __device__ void * __nv_cluster_map_shared_rank_impl(const void *, unsigned); + __device__ unsigned __nv_cluster_query_shared_rank_impl(const void *); + __device__ unsigned __nv_clusterDimIsSpecifed_impl(); + __device__ void __nv_clusterDim_impl(unsigned *, unsigned *, unsigned *); + __device__ void __nv_clusterRelativeBlockIdx_impl(unsigned *, + unsigned *, unsigned *); + __device__ void __nv_clusterGridDimInClusters_impl(unsigned *, + unsigned *, unsigned *); + __device__ void __nv_clusterIdx_impl(unsigned *, unsigned *, unsigned *); + __device__ unsigned __nv_clusterRelativeBlockRank_impl(); + __device__ unsigned __nv_clusterSizeInBlocks_impl(); + __device__ void __nv_cluster_barrier_arrive_impl(); + __device__ void __nv_cluster_barrier_arrive_relaxed_impl(); + __device__ void __nv_cluster_barrier_wait_impl(); + __device__ void __nv_threadfence_cluster_impl(); + + __device__ __device_builtin__ float2 __f2AtomicAdd(float2 *, float2); + __device__ __device_builtin__ float2 __f2AtomicAdd_block(float2 *, float2); + __device__ __device_builtin__ float2 __f2AtomicAdd_system(float2 *, float2); + __device__ __device_builtin__ float4 __f4AtomicAdd(float4 *, float4); + __device__ __device_builtin__ float4 __f4AtomicAdd_block(float4 *, float4); + __device__ __device_builtin__ float4 __f4AtomicAdd_system(float4 *, float4); +} // extern "C" + +__SM_90_RT_DECL__ unsigned __isCtaShared(const void *ptr) +{ + return __isShared(ptr); +} + +__SM_90_RT_DECL__ unsigned __isClusterShared(const void *ptr) +{ + return __nv_isClusterShared_impl(ptr); +} + +__SM_90_RT_DECL__ void *__cluster_map_shared_rank(const void *ptr, + unsigned target_block_rank) +{ + return __nv_cluster_map_shared_rank_impl(ptr, target_block_rank); +} + +__SM_90_RT_DECL__ unsigned __cluster_query_shared_rank(const void *ptr) +{ + return __nv_cluster_query_shared_rank_impl(ptr); +} + +__SM_90_RT_DECL__ uint2 __cluster_map_shared_multicast(const void *ptr, + unsigned int cluster_cta_mask) +{ + return make_uint2((unsigned)__cvta_generic_to_shared(ptr), cluster_cta_mask); +} + +__SM_90_RT_DECL__ unsigned __clusterDimIsSpecified() +{ + return __nv_clusterDimIsSpecifed_impl(); +} + +__SM_90_RT_DECL__ dim3 __clusterDim() +{ + unsigned x, y, z; + __nv_clusterDim_impl(&x, &y, &z); + return dim3(x,y,z); +} + +__SM_90_RT_DECL__ dim3 __clusterRelativeBlockIdx() +{ + unsigned x, y, z; + __nv_clusterRelativeBlockIdx_impl(&x, &y, &z); + return dim3(x,y,z); +} + +__SM_90_RT_DECL__ dim3 __clusterGridDimInClusters() +{ + unsigned x, y, z; + __nv_clusterGridDimInClusters_impl(&x, &y, &z); + return dim3(x,y,z); +} + +__SM_90_RT_DECL__ dim3 __clusterIdx() +{ + unsigned x, y, z; + __nv_clusterIdx_impl(&x, &y, &z); + return dim3(x,y,z); +} + +__SM_90_RT_DECL__ unsigned __clusterRelativeBlockRank() +{ + return __nv_clusterRelativeBlockRank_impl(); +} + +__SM_90_RT_DECL__ unsigned __clusterSizeInBlocks() +{ + return __nv_clusterSizeInBlocks_impl(); +} + +__SM_90_RT_DECL__ void __cluster_barrier_arrive() +{ + __nv_cluster_barrier_arrive_impl(); +} + +__SM_90_RT_DECL__ void __cluster_barrier_arrive_relaxed() +{ + __nv_cluster_barrier_arrive_relaxed_impl(); +} + +__SM_90_RT_DECL__ void __cluster_barrier_wait() +{ + __nv_cluster_barrier_wait_impl(); +} + +__SM_90_RT_DECL__ void __threadfence_cluster() +{ + __nv_threadfence_cluster_impl(); +} + + +/* Define __PTR for atomicAdd prototypes below, undef after done */ +#if (defined(_MSC_VER) && defined(_WIN64)) || defined(__LP64__) || defined(__CUDACC_RTC__) +#define __PTR "l" +#else +#define __PTR "r" +#endif /*(defined(_MSC_VER) && defined(_WIN64)) || defined(__LP64__) || defined(__CUDACC_RTC__)*/ + +__SM_90_RT_DECL__ float2 atomicAdd(float2 *address, float2 val) { + return __f2AtomicAdd(address, val); +} + +__SM_90_RT_DECL__ float2 atomicAdd_block(float2 *address, float2 val) { + return __f2AtomicAdd_block(address, val); +} + +__SM_90_RT_DECL__ float2 atomicAdd_system(float2 *address, float2 val) { + return __f2AtomicAdd_system(address, val); +} + +__SM_90_RT_DECL__ float4 atomicAdd(float4 *address, float4 val) { + return __f4AtomicAdd(address, val); +} + +__SM_90_RT_DECL__ float4 atomicAdd_block(float4 *address, float4 val) { + return __f4AtomicAdd_block(address, val); +} + +__SM_90_RT_DECL__ float4 atomicAdd_system(float4 *address, float4 val) { + return __f4AtomicAdd_system(address, val); +} + +#endif /* !__CUDA_ARCH__ || __CUDA_ARCH__ >= 900 */ + +#endif /* __cplusplus && __CUDACC__ */ + +#undef __SM_90_RT_DECL__ + +#endif /* !__SM_90_RT_HPP__ */ + +#if defined(__UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_SM_90_RT_HPP__) +#undef __CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__ +#undef __UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_SM_90_RT_HPP__ +#endif diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/storage_class.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/storage_class.h new file mode 100644 index 0000000000000000000000000000000000000000..1fb19bd46ebde4a53dfad866050fad9fb0cbd222 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/backends/nvidia/include/crt/storage_class.h @@ -0,0 +1,142 @@ +/* + * NVIDIA_COPYRIGHT_BEGIN + * + * Copyright (c) 2008-2018, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + * + * NVIDIA_COPYRIGHT_END + */ + +#if !defined(__CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__) +#if defined(_MSC_VER) +#pragma message("crt/storage_class.h is an internal header file and must not be used directly. Please use cuda_runtime_api.h or cuda_runtime.h instead.") +#else +#warning "crt/storage_class.h is an internal header file and must not be used directly. Please use cuda_runtime_api.h or cuda_runtime.h instead." +#endif +#define __CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__ +#define __UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_STORAGE_CLASS_H__ +#endif + +#if !defined(__STORAGE_CLASS_H__) +#define __STORAGE_CLASS_H__ + +#if !defined(__var_used__) + +#define __var_used__ + +#endif /* __var_used__ */ + +#if !defined(__loc_sc__) + +#define __loc_sc__(loc, size, sc) \ + __storage##_##sc##size##loc loc + +#endif /* !__loc_sc__ */ + +#if !defined(__storage___device__) +#define __storage___device__ static __var_used__ +#endif /* __storage___device__ */ + +#if !defined(__storage_extern__device__) +#define __storage_extern__device__ static __var_used__ +#endif /* __storage_extern__device__ */ + +#if !defined(__storage_auto__device__) +#define __storage_auto__device__ @@@ COMPILER @@@ ERROR @@@ +#endif /* __storage_auto__device__ */ + +#if !defined(__storage_static__device__) +#define __storage_static__device__ static __var_used__ +#endif /* __storage_static__device__ */ + +#if !defined(__storage___constant__) +#define __storage___constant__ static __var_used__ +#endif /* __storage___constant__ */ + +#if !defined(__storage_extern__constant__) +#define __storage_extern__constant__ static __var_used__ +#endif /* __storage_extern__constant__ */ + +#if !defined(__storage_auto__constant__) +#define __storage_auto__constant__ @@@ COMPILER @@@ ERROR @@@ +#endif /* __storage_auto__constant__ */ + +#if !defined(__storage_static__constant__) +#define __storage_static__constant__ static __var_used__ +#endif /* __storage_static__constant__ */ + +#if !defined(__storage___shared__) +#define __storage___shared__ static __var_used__ +#endif /* __storage___shared__ */ + +#if !defined(__storage_extern__shared__) +#define __storage_extern__shared__ static __var_used__ +#endif /* __storage_extern__shared__ */ + +#if !defined(__storage_auto__shared__) +#define __storage_auto__shared__ static +#endif /* __storage_auto__shared__ */ + +#if !defined(__storage_static__shared__) +#define __storage_static__shared__ static __var_used__ +#endif /* __storage_static__shared__ */ + +#if !defined(__storage__unsized__shared__) +#define __storage__unsized__shared__ @@@ COMPILER @@@ ERROR @@@ +#endif /* __storage__unsized__shared__ */ + +#if !defined(__storage_extern_unsized__shared__) +#define __storage_extern_unsized__shared__ static __var_used__ +#endif /* __storage_extern_unsized__shared__ */ + +#if !defined(__storage_auto_unsized__shared__) +#define __storage_auto_unsized__shared__ @@@ COMPILER @@@ ERROR @@@ +#endif /* __storage_auto_unsized__shared__ */ + +#if !defined(__storage_static_unsized__shared__) +#define __storage_static_unsized__shared__ @@@ COMPILER @@@ ERROR @@@ +#endif /* __storage_static_unsized__shared__ */ + +#if !defined(__storage___text__) +#define __storage___text__ static __var_used__ +#endif /* __storage___text__ */ + +#if !defined(__storage_extern__text__) +#define __storage_extern__text__ static __var_used__ +#endif /* __storage_extern__text__ */ + +#if !defined(__storage_auto__text__) +#define __storage_auto__text__ @@@ COMPILER @@@ ERROR @@@ +#endif /* __storage_auto__text__ */ + +#if !defined(__storage_static__text__) +#define __storage_static__text__ static __var_used__ +#endif /* __storage_static__text__ */ + +#if !defined(__storage___surf__) +#define __storage___surf__ static __var_used__ +#endif /* __storage___surf__ */ + +#if !defined(__storage_extern__surf__) +#define __storage_extern__surf__ static __var_used__ +#endif /* __storage_extern__surf__ */ + +#if !defined(__storage_auto__surf__) +#define __storage_auto__surf__ @@@ COMPILER @@@ ERROR @@@ +#endif /* __storage_auto__surf__ */ + +#if !defined(__storage_static__surf__) +#define __storage_static__surf__ static __var_used__ +#endif /* __storage_static__surf__ */ + +#endif /* !__STORAGE_CLASS_H__ */ + +#if defined(__UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_STORAGE_CLASS_H__) +#undef __CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS__ +#undef __UNDEF_CUDA_INCLUDE_COMPILER_INTERNAL_HEADERS_STORAGE_CLASS_H__ +#endif diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/compiler/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/compiler/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..127ccf90fbef0c9b89a1d899cedeecc6ed52b3e3 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/compiler/__init__.py @@ -0,0 +1,7 @@ +from .compiler import CompiledKernel, ASTSource, IRSource, compile, make_backend, LazyDict, get_cache_key +from .errors import CompilationError + +__all__ = [ + "compile", "make_backend", "ASTSource", "IRSource", "CompiledKernel", "CompilationError", "LazyDict", + "get_cache_key" +] diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/compiler/code_generator.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/compiler/code_generator.py new file mode 100644 index 0000000000000000000000000000000000000000..c572f81e3e13fe7f3f6f2dd72542c3ef737e581d --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/compiler/code_generator.py @@ -0,0 +1,1639 @@ +import ast +import builtins +import contextlib +import copy +import inspect +import re +import warnings +import textwrap +from dataclasses import dataclass +from types import ModuleType +from typing import Any, Callable, Dict, Optional, Tuple, Type, Union, Iterable, List + +from .. import knobs, language +from .._C.libtriton import ir, gluon_ir +from ..language import constexpr, str_to_ty, tensor, tuple as tl_tuple +from ..language.core import _unwrap_if_constexpr, base_value, base_type +# ideally we wouldn't need any runtime component +from ..runtime.jit import get_jit_fn_file_line, get_full_name, JITCallable, BoundConstexprFunction, ConstexprFunction, JITFunction +from .._utils import find_paths_if, get_iterable_path, set_iterable_path, is_namedtuple + +from .errors import (CompilationError, CompileTimeAssertionFailure, UnsupportedLanguageConstruct) + + +def check_identifier_legality(name, type): + pattern = r'^[a-zA-Z_][a-zA-Z0-9_]*$' + if not re.match(pattern, name): + raise CompilationError(f"invalid {type} identifier: {name}", name) + return name + + +def mangle_fn(name, arg_tys, constants, caller_context): + # doesn't mangle ret type, which must be a function of arg tys + mangled_arg_names = '_'.join([ty.mangle() for ty in arg_tys]) + mangled_constants = '_'.join([f'{i}c{repr(constants[i])}' for i in sorted(constants)]) + mangled_constants = mangled_constants.replace('.', '_d_') + mangled_constants = mangled_constants.replace("'", '_sq_') + # [ and ] are not allowed in LLVM identifiers + mangled_constants = mangled_constants.replace('[', '_').replace(']', '_') + ret = f'{name}__{mangled_arg_names}__{mangled_constants}' + if caller_context is not None: + ret += caller_context.mangle() + return ret + + +def _is_triton_value(o: Any) -> bool: + return isinstance(o, base_value) + + +def _is_triton_tensor(o: Any) -> bool: + return isinstance(o, tensor) + + +def _is_constexpr(o: Any) -> bool: + return o is None or isinstance(o, (constexpr, language.core.dtype, JITCallable)) + + +def _is_non_scalar_tensor(o: Any) -> bool: + return _is_triton_tensor(o) and (o.type.is_block() and o.type.numel != 1) + + +def _is_list_like(o: Any) -> bool: + return isinstance(o, (list, tuple)) + + +def _check_fn_args(node, fn, args): + if fn.noinline: + for idx, arg in enumerate(args): + if not _is_constexpr(arg) and _is_non_scalar_tensor(arg): + raise UnsupportedLanguageConstruct( + fn.src, node, + f'Function {fn.__name__} is marked noinline, but was called with non-scalar argument {fn.arg_names[idx]}:{arg}' + ) + + +def _apply_to_tuple_values(value, fn): + if is_namedtuple(type(value)): + fields = value._fields + elif isinstance(value, language.tuple): + fields = value.type.fields + else: + assert False, f"Unsupported type {type(value)}" + + vals = [fn(v) for v in value] + vals = [constexpr(v) if v is None else v for v in vals] + types = [v.type for v in vals] + return language.tuple(vals, language.tuple_type(types, fields)) + + +def flatten_values_to_ir(values: Iterable[base_value]): + handles = [] + for v in values: + v._flatten_ir(handles) + return handles + + +def unflatten_ir_values(handles: List[ir.value], types: List[base_type]): + cursor = 0 + for ty in types: + value, cursor = ty._unflatten_ir(handles, cursor) + yield value + assert cursor == len(handles) + + +_condition_types = {bool, int, type(None)} # Python types accepted for conditionals inside kernels + + +def _clone_triton_value(val): + handles = [] + val._flatten_ir(handles) + clone, _ = val.type._unflatten_ir(handles, 0) + return clone + + +def _clone_scope(scope): + return {name: _clone_triton_value(val) if _is_triton_value(val) else val for name, val in scope.items()} + + +class enter_sub_region: + + def __init__(self, generator): + self.generator = generator + + def __enter__(self): + # record lscope & local_defs in the parent scope + self.liveins = _clone_scope(self.generator.lscope) + self.prev_defs = _clone_scope(self.generator.local_defs) + self.generator.local_defs = {} + self.insert_block = self.generator.builder.get_insertion_block() + self.insert_point = self.generator.builder.get_insertion_point() + return self.liveins, self.insert_block + + def __exit__(self, *args, **kwargs): + self.generator.builder.restore_insertion_point(self.insert_point) + self.generator.lscope = self.liveins + self.generator.local_defs = self.prev_defs + + +# Check if the given syntax node has an "early" return +class ContainsReturnChecker(ast.NodeVisitor): + + def __init__(self, gscope): + self.gscope = gscope + + def _visit_stmts(self, body) -> bool: + return any(self.visit(s) for s in body) + + def _visit_function(self, fn) -> bool: + # No need to check within the function as it won't cause an early return. + # If the function itself has unstructured control flow we may not be able to inline it causing poor performance, + # we should check for this and emit a warning. + return False + + def generic_visit(self, node) -> bool: + ret = False + for _, value in ast.iter_fields(node): + if isinstance(value, list): + for item in value: + if isinstance(item, ast.AST): + ret = ret or self.visit(item) + elif isinstance(value, ast.AST): + ret = ret or self.visit(value) + return ret + + def visit_Attribute(self, node: ast.Attribute) -> bool: + # If the left part is a name, it's possible that + # we call triton native function or a jit function from another module. + # If the left part is not a name, it must return a tensor or a constexpr + # whose methods do not contain return statements + # e.g., (tl.load(x)).to(y) + # So we only check if the expressions within value have return or not + if isinstance(node.value, ast.Name): + if node.value.id in self.gscope: + value = self.gscope[node.value.id] + fn = getattr(value, node.attr) + return self._visit_function(fn) + return False + return self.visit(node.value) + + def visit_Name(self, node: ast.Name) -> bool: + if type(node.ctx) is ast.Store: + return False + if node.id in self.gscope: + fn = self.gscope[node.id] + return self._visit_function(fn) + return False + + def visit_Return(self, node: ast.Return) -> bool: + return True + + def visit_Assign(self, node: ast.Assign) -> bool: + # There couldn't be an early return + # x = ... + return False + + def visit_AugAssign(self, node: ast.AugAssign) -> bool: + # There couldn't be an early return + # x += ... + return False + + def visit_Module(self, node: ast.Module) -> bool: + return self._visit_stmts(node.body) + + def visit_FunctionDef(self, node: ast.FunctionDef) -> bool: + return self._visit_stmts(node.body) + + def visit_If(self, node: ast.If) -> bool: + # TODO: optimize the following case in which we actually don't have + # a return when static_cond is false: + # if dynamic_cond + # if static_cond + # func_with_return + # else + # func_without_return + ret = self._visit_stmts(node.body) + if node.orelse: + ret = ret or self._visit_stmts(node.orelse) + return ret + + def visit_IfExp(self, node: ast.IfExp) -> bool: + return self.visit(node.body) or self.visit(node.orelse) + + def visit_Call(self, node: ast.Call) -> bool: + return self.visit(node.func) + + +class ASTFunction: + + def __init__(self, ret_types, arg_types, constants, attrs): + self.ret_types = ret_types + self.arg_types = arg_types + self.constants = constants + self.attrs = attrs + + def flatten_ir_types(self, builder: ir.builder, types: List[base_type]) -> List[ir.type]: + ir_types = [] + for ty in types: + if ty is None: + continue + ty._flatten_ir_types(builder, ir_types) + return ir_types + + def return_types_ir(self, builder: ir.builder) -> List[ir.type]: + return self.flatten_ir_types(builder, self.ret_types) + + def serialize(self, builder: ir.builder): + # fill up IR values in template + # > build function + is_val = lambda path, _: path not in self.constants and _ is not None + val_paths = list(find_paths_if(self.arg_types, is_val)) + arg_types = [get_iterable_path(self.arg_types, path) for path in val_paths] + arg_types_ir = self.flatten_ir_types(builder, arg_types) + ret_types_ir = self.return_types_ir(builder) + return builder.get_function_ty(arg_types_ir, ret_types_ir) + + def deserialize(self, fn): + # create "template" + def make_template(ty): + if isinstance(ty, (list, tuple, language.tuple_type)): + return language.tuple([make_template(x) for x in ty], ty) + return language.constexpr(None) + + vals = make_template(self.arg_types) + is_val = lambda path, _: path not in self.constants and _ is not None + val_paths = list(find_paths_if(self.arg_types, is_val)) + # > add IR values to the template + cursor = 0 + handles = [fn.args(i) for i in range(fn.get_num_args())] + for path in val_paths: + ty = get_iterable_path(self.arg_types, path) + # > set attributes + attr_specs = self.attrs.get(path, []) + for attr_name, attr_val in attr_specs: + fn.set_arg_attr(cursor, attr_name, attr_val) + # > build frontend value + val, cursor = ty._unflatten_ir(handles, cursor) + set_iterable_path(vals, path, val) + # > add constexpr values to the template + constants = self.constants + for path, val in constants.items(): + set_iterable_path(vals, path, language.constexpr(val)) + return vals + + +@dataclass(frozen=True) +class BoundJITMethod: + __self__: base_value + __func__: JITFunction + + +class CodeGenerator(ast.NodeVisitor): + + def __init__(self, context, prototype, gscope, function_name, jit_fn: JITFunction, *, options, codegen_fns, + module_map, is_gluon, module=None, is_kernel=False, function_types: Optional[Dict] = None, + noinline=False, caller_context=None, file_name: Optional[str] = None, begin_line=0): + self.context = context + self.is_gluon = is_gluon + if is_gluon: + from triton.experimental.gluon.language._semantic import GluonSemantic + self.builder = gluon_ir.GluonOpBuilder(context) + self.semantic = GluonSemantic(self.builder) + else: + from triton.language.semantic import TritonSemantic + self.builder = ir.builder(context) + self.semantic = TritonSemantic(self.builder) + + self.name_loc_as_prefix = None + self.file_name = file_name + # node.lineno starts from 1, so we need to subtract 1 + self.begin_line = begin_line - 1 + self.builder.set_loc(file_name, begin_line, 0) + self.builder.options = options + # dict of functions provided by the backend. Below are the list of possible functions: + # Convert custom types not natively supported on HW. + # convert_custom_types(input_tensor, dtype, fp_downcast_rounding=None, _builder=None) + self.builder.codegen_fns = codegen_fns + self.builder.module_map = {} if module_map is None else module_map + self.module = self.builder.create_module() if module is None else module + self.function_ret_types = {} if function_types is None else function_types + self.prototype = prototype + + self.gscope = {} + for k, v in gscope.items(): + if isinstance(v, ModuleType): + self.gscope[k] = module_map.get(v.__name__, v) + continue + + module_name = getattr(v, "__module__", "") + if module_name in module_map: + self.gscope[k] = getattr(module_map[module_name], v.__name__) + else: + self.gscope[k] = v + + self.lscope = {} + self.jit_fn = jit_fn + # TODO: we currently generate illegal names for non-kernel functions involving constexprs! + if is_kernel: + function_name = function_name[function_name.rfind('.') + 1:] + function_name = check_identifier_legality(function_name, "function") + self.function_name = function_name + self.is_kernel = is_kernel + self.cur_node = None + self.noinline = noinline + self.caller_context = caller_context + self.scf_stack = [] + self.ret_type = None + # SSA-construction + # name => language.tensor + self.local_defs: Dict[str, tensor] = {} + self.dereference_name: Callable[[str], Any] = self._define_name_lookup() + self.fn = None + # Are we currently visiting an ast.arg's default value? These have some + # special handling. + self.visiting_arg_default_value = False + + builtin_namespace: Dict[str, Any] = { + _.__name__: _ + for _ in (len, list, range, float, int, isinstance, getattr, hasattr) + } + builtin_namespace.update(( + ('print', language.core.device_print), + ('min', language.core.builtin_min), + ('max', language.core.builtin_max), + )) + + def _unsupported(self, node, message): + return UnsupportedLanguageConstruct(self.jit_fn.src, node, message) + + def _is_constexpr_global(self, name): + absent_marker = object() + val = self.gscope.get(name, absent_marker) + if val is absent_marker: + return False + + if _is_constexpr(val): + return True + + return False + + def _define_name_lookup(self): + + def local_lookup(name: str, absent): + # this needs to be re-fetched from `self` every time, because it gets switched occasionally + return self.lscope.get(name, absent) + + def global_lookup(name: str, absent): + val = self.gscope.get(name, absent) + # The high-level rule is that only constexpr globals are allowed. + # But actually a bunch of other things, such as module imports, are + # technically Python globals. We have to allow these too! + if any([ + val is absent, + name in self.builtin_namespace, # + type(val) is ModuleType, # + isinstance(val, JITCallable), # + getattr(val, "__triton_builtin__", False), # + getattr(val, "__triton_aggregate__", False), # + getattr(val, "__module__", "").startswith("triton.language"), # + getattr(val, "__module__", "").startswith("triton.experimental.gluon.language"), # + isinstance(val, language.dtype), # + is_namedtuple(val), + self._is_constexpr_global(name), # + # Allow accesses to globals while visiting an ast.arg + # because you should be able to do + # @triton.jit def fn(x: tl.constexpr = GLOBAL): ... + self.visiting_arg_default_value, # + knobs.compilation.allow_non_constexpr_globals, + ]): + return val + raise NameError( + textwrap.dedent(f"""\ + Cannot access global variable {name} from within @jit'ed + function. Triton kernels can only access global variables that + are instanstiated as constexpr (`x = triton.language.constexpr(42)`). Note that this is different from + annotating a variable as constexpr (`x: triton.language.constexpr = 42`), which is not supported. Alternatively, set the + envvar TRITON_ALLOW_NON_CONSTEXPR_GLOBALS=1, but we do not + promise to support this forever.""").replace("\n", " ")) + + absent_marker = object() + + def name_lookup(name: str) -> Any: + absent = absent_marker + for lookup_function in local_lookup, global_lookup, self.builtin_namespace.get: + value = lookup_function(name, absent) + if value is not absent: + return value + raise NameError(f'{name} is not defined') + + return name_lookup + + @contextlib.contextmanager + def _name_loc_prefix(self, prefix): + self.name_loc_as_prefix = prefix + yield + self.name_loc_as_prefix = None + + def _maybe_set_loc_to_name(self, val, name): + if isinstance(val, (ir.value, ir.block_argument)): + val.set_loc(self.builder.create_name_loc(name, val.get_loc())) + elif _is_triton_value(val): + handles = [] + val._flatten_ir(handles) + for handle in handles: + handle.set_loc(self.builder.create_name_loc(name, handle.get_loc())) + + def set_value(self, name: str, value: Union[base_value, constexpr]) -> None: + ''' This function: + called by visit_Assign() & visit_FunctionDef() to store left value (lvalue) + 1. record local defined name (FIXME: should consider control flow) + 2. store tensor in self.lvalue + ''' + self.lscope[name] = value + self.local_defs[name] = value + + def _get_insertion_point_and_loc(self): + # XXX: this is a hack to get the location of the insertion point. + # The insertion point's location could be invalid sometimes, + # so we need to explicitly set the location + loc = self.builder.get_loc() + ip = self.builder.get_insertion_point() + return ip, loc + + def _set_insertion_point_and_loc(self, ip, loc): + self.builder.restore_insertion_point(ip) + self.builder.set_loc(loc) + + def _find_carries(self, node, liveins, ignore: set[str] = set()): + # create loop body block + block = self.builder.create_block() + self.builder.set_insertion_point_to_start(block) + # dry visit loop body + self.scf_stack.append(node) + self.visit_compound_statement(node.body) + self.scf_stack.pop() + block.erase() + + # If a variable (name) has changed value within the loop, then it's + # a loop-carried variable. (The new and old value must be of the + # same type) + init_tys = [] + init_handles = [] + names = [] + + for name, live_val in liveins.items(): + if name in ignore: + continue + + if _is_triton_value(live_val): + loop_val = self.lscope[name] + self._verify_loop_carried_variable(name, loop_val, live_val) + + live_handles = flatten_values_to_ir([live_val]) + loop_handles = flatten_values_to_ir([loop_val]) + if live_handles != loop_handles: + names.append(name) + init_tys.append(live_val.type) + init_handles.extend(live_handles) + else: + assert name not in self.local_defs, f'Loop carried variable {name} is not a triton value' + + # reset local scope to not pick up local defs from the dry run. + self.lscope = liveins.copy() + self.local_defs = {} + + return names, init_handles, init_tys + + # + # AST visitor + # + def visit_compound_statement(self, stmts): + # Ensure that stmts is iterable + if not _is_list_like(stmts): + stmts = [stmts] + for stmt in stmts: + self.visit(stmt) + # Stop parsing as soon as we hit a `return` statement; everything + # after this is dead code. + if isinstance(stmt, ast.Return): + break + + def visit_Module(self, node): + ast.NodeVisitor.generic_visit(self, node) + + def visit_List(self, node): + ctx = self.visit(node.ctx) + assert ctx is None + elts = language.tuple([self.visit(elt) for elt in node.elts]) + return elts + + def visit_ListComp(self, node: ast.ListComp): + if len(node.generators) != 1: + raise ValueError("nested comprehensions are not supported") + + comp = node.generators[0] + iter = self.visit(comp.iter) + if not isinstance(iter, tl_tuple): + raise NotImplementedError("only tuple comprehensions are supported") + + results = [] + for item in iter: + self.set_value(comp.target.id, item) + results.append(self.visit(node.elt)) + return tl_tuple(results) + + # By design, only non-kernel functions can return + def visit_Return(self, node): + ret_value = self.visit(node.value) + handles = [] + + def decay(value): + if isinstance(value, language.tuple): + return _apply_to_tuple_values(value, decay) + elif isinstance(value, (language.constexpr, int, float)): + return self.semantic.to_tensor(value) + return value + + ret_value = decay(ret_value) + + if ret_value is None: + ret_ty = language.void + else: + assert isinstance(ret_value, language.core.base_value) + ret_value._flatten_ir(handles) + ret_ty = ret_value.type + self.builder.ret(handles) + if self.ret_type is None: + self.ret_type = ret_ty + elif self.ret_type != ret_ty: + raise TypeError(f'Inconsistent return types: {self.ret_type} and {ret_ty}') + + # A return op must always terminate the basic block, so we create a dead + # basic block in case there are any ops after the return. + post_ret_block = self.builder.create_block() + self.builder.set_insertion_point_to_end(post_ret_block) + + def visit_FunctionDef(self, node): + arg_names, kwarg_names = self.visit(node.args) + if self.fn: + raise self._unsupported(node, "nested function definition is not supported.") + # initialize defaults + for i, default_value in enumerate(node.args.defaults[::-1]): + arg_node = node.args.args[-i - 1] + annotation = arg_node.annotation + name = arg_node.arg + st_target = ast.Name(id=name, ctx=ast.Store()) + if annotation is None: + init_node = ast.Assign(targets=[st_target], value=default_value) + else: + init_node = ast.AnnAssign(target=st_target, value=default_value, annotation=annotation) + try: + assert not self.visiting_arg_default_value + self.visiting_arg_default_value = True + self.visit(init_node) + finally: + self.visiting_arg_default_value = False + + # initialize function + visibility = "public" if self.is_kernel else "private" + fn_ty = self.prototype.serialize(self.builder) + self.fn = self.builder.get_or_insert_function(self.module, self.function_name, fn_ty, visibility, self.noinline) + self.module.push_back(self.fn) + entry = self.fn.add_entry_block() + arg_values = self.prototype.deserialize(self.fn) + if self.caller_context is not None: + self.caller_context.initialize_callee(self.fn, self.builder) + # bind arguments to symbols + for arg_name, arg_value in zip(arg_names, arg_values): + self._maybe_set_loc_to_name(arg_value, arg_name) + self.set_value(arg_name, arg_value) + insert_pt = self.builder.get_insertion_block() + self.builder.set_insertion_point_to_start(entry) + # visit function body + self.visit_compound_statement(node.body) + + # finalize function + assert not self.builder.get_insertion_block().has_terminator() + if self.ret_type is None or self.ret_type == language.void: + self.ret_type = language.void + self.builder.ret([]) + else: + if isinstance(self.ret_type, language.tuple_type): + self.prototype.ret_types = self.ret_type.types + else: + self.prototype.ret_types = [self.ret_type] + self.fn.reset_type(self.prototype.serialize(self.builder)) + self.builder.ret([self.builder.create_poison(ty) for ty in self.prototype.return_types_ir(self.builder)]) + self.fn.finalize() + + if insert_pt: + self.builder.set_insertion_point_to_end(insert_pt) + + def visit_arguments(self, node): + arg_names = [] + for arg in node.args: + arg_names += [self.visit(arg)] + kwarg_names = self.visit(node.kwarg) + return arg_names, kwarg_names + + def visit_arg(self, node): + ast.NodeVisitor.generic_visit(self, node) + param = next(p for p in self.jit_fn.params if p.name == node.arg) + if param.is_constexpr and (param.do_not_specialize or param.do_not_specialize_on_alignment): + raise CompilationError( + self.jit_fn.src, node, + f"{node.arg} marked as constexpr and listed in do_not_specialize/do_not_specialize_on_alignment. " + "Remove constexpr designation to skip specialization.") + return node.arg + + def visit_AnnAssign(self, node): + # extract attributes + annotation = self.visit(node.annotation) + target = self.visit(node.target) + value = self.visit(node.value) + # constexpr + if annotation == constexpr: + if target in self.lscope: + raise ValueError(f'{target} is already defined.' + f' constexpr cannot be reassigned.') + value = constexpr(value) + self.lscope[target] = value + return self.lscope[target] + # default: call visit_Assign + return self.visit_Assign(node) + + def assignTarget(self, target, value): + assert isinstance(target.ctx, ast.Store) + if isinstance(target, ast.Subscript): + return self.visit_Subscript_Store(target, value) + if isinstance(target, ast.Tuple): + for i, target in enumerate(target.elts): + self.assignTarget(target, value.values[i]) + return + if isinstance(target, ast.Attribute): + raise NotImplementedError("Attribute assignment is not supported in triton") + assert isinstance(target, ast.Name) + self.set_value(self.visit(target), value) + + def visit_Assign(self, node): + # construct values to assign + def _sanitize_value(value): + if isinstance(value, language.tuple): + return _apply_to_tuple_values(value, _sanitize_value) + native_nontensor_types = (language.dtype, language.tuple) + value = _unwrap_if_constexpr(value) + if value is not None and \ + not _is_triton_value(value) and \ + not isinstance(value, native_nontensor_types): + value = self.semantic.to_tensor(value) + return value + + targets = [node.target] if isinstance(node, ast.AnnAssign) else node.targets + assert len(targets) == 1 + target = targets[0] + if isinstance(target, ast.Name): + with self._name_loc_prefix(target.id): + values = _sanitize_value(self.visit(node.value)) + else: + values = _sanitize_value(self.visit(node.value)) + self.assignTarget(target, values) + + def visit_AugAssign(self, node): + lhs = copy.deepcopy(node.target) + lhs.ctx = ast.Load() + rhs = ast.BinOp(lhs, node.op, node.value) + assign = ast.Assign(targets=[node.target], value=rhs) + for x in ['lineno', 'col_offset', 'end_lineno', 'end_col_offset']: + if hasattr(node, x): + y = getattr(node, x) + setattr(rhs, x, y) + setattr(assign, x, y) + self.visit(assign) + return self.visit(lhs) + + def visit_Name(self, node): + if type(node.ctx) is ast.Store: + return node.id + return self.dereference_name(node.id) + + def visit_Store(self, node): + ast.NodeVisitor.generic_visit(self, node) + + def visit_Load(self, node): + ast.NodeVisitor.generic_visit(self, node) + + def visit_Tuple(self, node): + args = [self.visit(x) for x in node.elts] + return language.tuple(args) + + def _apply_binary_method(self, node, method_name, lhs, rhs): + # TODO: raise something meaningful if getattr fails below, esp for reverse method + if _is_triton_tensor(lhs): + return getattr(lhs, method_name)(rhs, _semantic=self.semantic) + if _is_triton_tensor(rhs): + reverse_method_name = re.sub(r"__(.*)__", r"__r\1__", method_name) + return getattr(rhs, reverse_method_name)(lhs, _semantic=self.semantic) + if not isinstance(lhs, (constexpr, language.tuple)) and isinstance(rhs, constexpr): + lhs = constexpr(lhs) + if isinstance(lhs, constexpr): + fn = getattr(lhs, method_name) + else: + fn = self.get_Attribute(lhs, method_name) + return self.call_Function(node, fn, [rhs], {}) + + def visit_BinOp(self, node): + lhs = self.visit(node.left) + rhs = self.visit(node.right) + method_name = self._method_name_for_bin_op.get(type(node.op)) + if method_name is None: + raise self._unsupported(node, + "AST binary operator '{}' is not (currently) implemented.".format(node.op.__name__)) + return self._apply_binary_method(node, method_name, lhs, rhs) + + _method_name_for_bin_op: Dict[Type[ast.operator], str] = { + ast.Add: '__add__', + ast.Sub: '__sub__', + ast.Mult: '__mul__', + ast.Div: '__truediv__', + ast.FloorDiv: '__floordiv__', + ast.Mod: '__mod__', + ast.Pow: '__pow__', + ast.LShift: '__lshift__', + ast.RShift: '__rshift__', + ast.BitAnd: '__and__', + ast.BitOr: '__or__', + ast.BitXor: '__xor__', + } + + def visit_then_else_blocks(self, node, liveins, then_block, else_block): + # then block + self.builder.set_insertion_point_to_start(then_block) + self.visit_compound_statement(node.body) + then_block = self.builder.get_insertion_block() + then_defs = self.local_defs.copy() + then_vals = self.lscope.copy() + # else block + else_defs = {} + else_vals = liveins.copy() + if node.orelse: + self.builder.set_insertion_point_to_start(else_block) + self.lscope = liveins.copy() + self.local_defs = {} + self.visit_compound_statement(node.orelse) + else_defs = self.local_defs.copy() + else_block = self.builder.get_insertion_block() + else_vals = self.lscope.copy() + + # update block arguments + names = [] + # variables in livein whose value is updated in `if` + for name, value in liveins.items(): + # livein variable changed value in either then or else + if not _is_triton_value(value): + continue + then_handles = flatten_values_to_ir([then_vals[name]]) + else_handles = flatten_values_to_ir([else_vals[name]]) + if then_handles == else_handles: + continue + names.append(name) + then_defs[name] = then_vals[name] + else_defs[name] = else_vals[name] + # check type + for defs, block_name in [(then_defs, 'then'), (else_defs, 'else')]: + type_equal = type(defs[name]) == type(value) # noqa: E721 + assert type_equal and defs[name].type == value.type, \ + f'initial value for `{name}` is of type {value}, '\ + f'but the {block_name} block redefines it as {defs[name]}' + + # variables that are both in then and else but not in liveins + # TODO: could probably be cleaned up + for name in sorted(then_defs.keys() & else_defs.keys()): + if name in names: + continue + then_val = then_defs[name] + then_ty = then_val.type + else_val = else_defs[name] + else_ty = else_val.type + type_equal = type(then_val) == type(else_val) # noqa: E721 + assert type_equal and then_ty == else_ty, \ + f'Mismatched type for {name} between then block ({then_ty}) '\ + f'and else block ({else_ty})' + names.append(name) + + return then_defs, else_defs, then_block, else_block, names + + def visit_if_top_level(self, cond, node): + with enter_sub_region(self) as sr: + liveins, ip_block = sr + then_block = self.builder.create_block() + else_block = self.builder.create_block() + # create branch + self.builder.set_insertion_point_to_end(ip_block) + self.builder.create_cond_branch(cond.handle, then_block, else_block) + # visit then and else blocks + then_defs, else_defs, then_block, else_block, names = \ + self.visit_then_else_blocks(node, liveins, then_block, else_block) + # create basic-block after conditional + endif_block = self.builder.create_block() + # then terminator + self.builder.set_insertion_point_to_end(then_block) + assert not then_block.has_terminator(), f"{then_block}" + then_handles = flatten_values_to_ir(then_defs[name] for name in names) + self.builder.create_branch(endif_block, then_handles) + # else terminator + self.builder.set_insertion_point_to_end(else_block) + assert not else_block.has_terminator(), f"{else_block}" + else_handles = flatten_values_to_ir(else_defs[name] for name in names) + self.builder.create_branch(endif_block, else_handles) + assert len(then_handles) == len(else_handles) + for then_h, else_h in zip(then_handles, else_handles): + ty = then_h.get_type() + assert ty == else_h.get_type() + endif_block.add_argument(ty) + + # change block + self.builder.set_insertion_point_to_start(endif_block) + # update value + res_handles = [endif_block.arg(i) for i in range(len(then_handles))] + types = [then_defs[name].type for name in names] + new_values = unflatten_ir_values(res_handles, types) + for name, new_value in zip(names, new_values): + self.set_value(name, new_value) + + # TODO: refactor + def visit_if_scf(self, cond, node): + with enter_sub_region(self) as sr: + liveins, _ = sr + ip, last_loc = self._get_insertion_point_and_loc() + then_block = self.builder.create_block() + else_block = self.builder.create_block() if node.orelse else None + then_defs, else_defs, then_block, else_block, names = \ + self.visit_then_else_blocks(node, liveins, then_block, else_block) + # create if op + then_handles = flatten_values_to_ir(then_defs[name] for name in names) + for name, val in zip(names, then_handles): + self._maybe_set_loc_to_name(val, name) + self._set_insertion_point_and_loc(ip, last_loc) + if_op = self.builder.create_if_op([h.get_type() for h in then_handles], cond.handle, True) + then_block.merge_block_before(if_op.get_then_block()) + self.builder.set_insertion_point_to_end(if_op.get_then_block()) + if len(names) > 0: + self.builder.create_yield_op(then_handles) + if not node.orelse: + else_block = if_op.get_else_block() + else: + else_block.merge_block_before(if_op.get_else_block()) + self.builder.set_insertion_point_to_end(if_op.get_else_block()) + if len(names) > 0: + else_handles = flatten_values_to_ir(else_defs[name] for name in names) + for name, val in zip(names, else_handles): + self._maybe_set_loc_to_name(val, name) + self.builder.create_yield_op(else_handles) + # update values + res_handles = [if_op.get_result(i) for i in range(len(then_handles))] + types = [then_defs[name].type for name in names] + new_values = unflatten_ir_values(res_handles, types) + for name, new_value in zip(names, new_values): + self.set_value(name, new_value) + + def visit_If(self, node): + cond = self.visit(node.test) + + if _is_triton_tensor(cond): + if _is_non_scalar_tensor(cond): + raise self._unsupported(node, "Boolean value of Tensor with more than one value is ambiguous") + if cond.type.is_block(): + warnings.warn( + "If conditional called with multidimensional Tensor instead of scalar; please use \"if (%s).item()\" instead" + % ast.unparse(node.test)) + cond = language.core._unsplat(cond, _semantic=self.semantic, _generator=self) + cond = cond.to(language.int1, _semantic=self.semantic) + if ContainsReturnChecker(self.gscope).visit(node): + if self.scf_stack: + raise self._unsupported( + node, "Cannot have `return` statements inside `while` or `for` statements in triton.") + self.visit_if_top_level(cond, node) + else: + self.visit_if_scf(cond, node) + else: + cond = _unwrap_if_constexpr(cond) + # not isinstance - we insist the real thing, no subclasses and no ducks + if type(cond) not in _condition_types: + raise self._unsupported( + node, "`if` conditionals can only accept values of type {{{}}}, not objects of type {}".format( + ', '.join(_.__name__ for _ in _condition_types), + type(cond).__name__)) + + active_block = node.body if cond else node.orelse + self.visit_compound_statement(active_block) + + def visit_IfExp(self, node): + cond = self.visit(node.test) + if _is_triton_tensor(cond): + cond = cond.to(language.int1, _semantic=self.semantic) + # TODO: Deal w/ more complicated return types (e.g tuple) + with enter_sub_region(self): + ip, last_loc = self._get_insertion_point_and_loc() + + then_block = self.builder.create_block() + self.builder.set_insertion_point_to_start(then_block) + then_val = self.semantic.to_tensor(self.visit(node.body)) + then_block = self.builder.get_insertion_block() + + else_block = self.builder.create_block() + self.builder.set_insertion_point_to_start(else_block) + # do not need to reset lscope since + # ternary expressions cannot define new variables + else_val = self.semantic.to_tensor(self.visit(node.orelse)) + else_block = self.builder.get_insertion_block() + + self._set_insertion_point_and_loc(ip, last_loc) + + assert then_val.type == else_val.type, \ + f'Ternary expression with dynamic condition has inconsistent types {then_val.type} and {else_val.type}' + ret_type = then_val.type + + ret_type_ir = [ret_type.to_ir(self.builder)] if ret_type != language.void else [] + if_op = self.builder.create_if_op(ret_type_ir, cond.handle, True) + then_block.merge_block_before(if_op.get_then_block()) + if ret_type_ir: + self.builder.set_insertion_point_to_end(if_op.get_then_block()) + self.builder.create_yield_op([then_val.handle]) + + self.builder.set_insertion_point_to_end(if_op.get_then_block()) + else_block.merge_block_before(if_op.get_else_block()) + if ret_type_ir: + self.builder.set_insertion_point_to_end(if_op.get_else_block()) + self.builder.create_yield_op([else_val.handle]) + return language.core.tensor(if_op.get_result(0), ret_type) if ret_type_ir else None + else: + cond = _unwrap_if_constexpr(cond) + + # not isinstance - we insist the real thing, no subclasses and no ducks + if type(cond) not in _condition_types: + raise self._unsupported( + node, "`if` conditionals can only accept values of type {{{}}}, not objects of type {}".format( + ', '.join(_.__name__ for _ in _condition_types), + type(cond).__name__)) + if cond: + return self.visit(node.body) + else: + return self.visit(node.orelse) + + def visit_With(self, node): + # Lower `with` statements by constructing context managers and calling their enter/exit hooks + # Instantiate each context manager with builder injection + cm_list = [] + for item in node.items: + call = item.context_expr + fn = self.visit(call.func) + args = [self.visit(arg) for arg in call.args] + kws = dict(self.visit(kw) for kw in call.keywords) + cm = fn(*args, _semantic=self.semantic, **kws) + cm_list.append(cm) + for cm, item in zip(cm_list, node.items): + res = cm.__enter__() + if item.optional_vars is not None: + var_name = self.visit(item.optional_vars) + self.set_value(var_name, res) + if ContainsReturnChecker(self.gscope).visit(node): + raise self._unsupported(node, "Cannot have `return` statements inside `with` statements in triton ") + self.visit_compound_statement(node.body) + for cm in reversed(cm_list): + cm.__exit__(None, None, None) + + def visit_Pass(self, node): + pass + + def visit_Compare(self, node): + if not (len(node.comparators) == 1 and len(node.ops) == 1): + raise self._unsupported(node, "simultaneous multiple comparison is not supported") + lhs = self.visit(node.left) + rhs = self.visit(node.comparators[0]) + lhs_value = _unwrap_if_constexpr(lhs) + rhs_value = _unwrap_if_constexpr(rhs) + if type(node.ops[0]) is ast.Is: + return constexpr(lhs_value is rhs_value) + if type(node.ops[0]) is ast.IsNot: + return constexpr(lhs_value is not rhs_value) + method_name = self._method_name_for_comp_op.get(type(node.ops[0])) + if method_name is None: + raise self._unsupported( + node, "AST comparison operator '{}' is not (currently) implemented.".format(node.ops[0].__name__)) + return self._apply_binary_method(node, method_name, lhs, rhs) + + _method_name_for_comp_op: Dict[Type[ast.cmpop], str] = { + ast.Eq: '__eq__', ast.NotEq: '__ne__', ast.Lt: '__lt__', ast.LtE: '__le__', ast.Gt: '__gt__', ast.GtE: '__ge__' + } + + def visit_UnaryOp(self, node): + operand = self.visit(node.operand) + fn = self._method_name_for_unary_op.get(type(node.op)) + if fn is None: + raise self._unsupported(node, f"AST unary operator '{node.op.__name__}' is not (currently) implemented.") + if _is_triton_tensor(operand): + return getattr(operand, fn)(_semantic=self.semantic) + try: + return getattr(operand, fn)() + except AttributeError: + if fn == "__not__": + return constexpr(not operand) + raise self._unsupported( + node, f"AST unary operator '{fn}' is not (currently) implemented on type {type(operand).__name__}") + + _method_name_for_unary_op: Dict[Type[ast.unaryop], str] = { + ast.USub: '__neg__', ast.UAdd: '__pos__', ast.Not: '__not__', ast.Invert: '__invert__' + } + + def _verify_loop_carried_variable(self, name, loop_val, live_val): + assert _is_triton_value(loop_val), f'cannot reassign constexpr {name} in the loop' + assert _is_triton_value(live_val), f'cannot reassign constexpr {name} in the loop' + assert type(loop_val) is type(live_val), ( + f'Loop carried variable {name} changed type, was {type(loop_val)} but is now {type(live_val)}') + assert not _is_triton_tensor(loop_val) or loop_val.type == live_val.type, \ + f'Loop-carried variable {name} has initial type {live_val.type} '\ + f'but is re-assigned to {loop_val.type} in loop! '\ + f'Please make sure that the type stays consistent.' + + def visit_While(self, node): + with enter_sub_region(self) as sr: + liveins, insert_block = sr + ip, last_loc = self._get_insertion_point_and_loc() + + names, init_handles, init_fe_tys = self._find_carries(node, liveins) + + init_tys = [h.get_type() for h in init_handles] + self._set_insertion_point_and_loc(ip, last_loc) + while_op = self.builder.create_while_op(init_tys, init_handles) + # merge the condition region + before_block = self.builder.create_block_with_parent(while_op.get_before(), init_tys) + self.builder.set_insertion_point_to_start(before_block) + block_args = [before_block.arg(i) for i in range(len(init_handles))] + condition_args = unflatten_ir_values(block_args, init_fe_tys) + for name, val in zip(names, condition_args): + self.lscope[name] = val + self.local_defs[name] = val + self._maybe_set_loc_to_name(val, name) + cond = self.visit(node.test) + if isinstance(cond, language.condition): + if cond.disable_licm: + while_op.set_attr("llvm.loop_annotation", self.builder.get_disable_loop_licm_attr()) + cond = cond.condition + self.builder.set_insertion_point_to_end(before_block) + # create ConditionOp: e.g., scf.condition(%cond) %arg0, %arg1, ... + self.builder.create_condition_op(cond.handle, block_args) + # merge the loop body + after_block = self.builder.create_block_with_parent(while_op.get_after(), init_tys) + + # generate loop body + self.builder.set_insertion_point_to_start(after_block) + body_handles = [after_block.arg(i) for i in range(len(init_handles))] + body_args = unflatten_ir_values(body_handles, init_fe_tys) + for name, val in zip(names, body_args): + self.lscope[name] = val + self.local_defs[name] = val + self._maybe_set_loc_to_name(val, name) + self.scf_stack.append(node) + self.visit_compound_statement(node.body) + self.scf_stack.pop() + + yield_handles = flatten_values_to_ir(self.lscope[name] for name in names) + self.builder.create_yield_op(yield_handles) + + # WhileOp defines new values, update the symbol table (lscope, local_defs) + result_handles = [while_op.get_result(i) for i in range(len(init_handles))] + result_vals = unflatten_ir_values(result_handles, init_fe_tys) + for name, new_def in zip(names, result_vals): + self.lscope[name] = new_def + self.local_defs[name] = new_def + self._maybe_set_loc_to_name(new_def, name) + + for stmt in node.orelse: + assert False, "Not implemented" + ast.NodeVisitor.generic_visit(self, stmt) + + def visit_Subscript_Load(self, node): + assert isinstance(node.ctx, ast.Load) + lhs = self.visit(node.value) + slices = self.visit(node.slice) + if _is_triton_value(lhs): + return self.call_Method(node, lhs.__getitem__, lhs, [slices], {}) + return lhs[slices] + + def visit_Subscript_Store(self, node, value): + raise NotImplementedError("__setitem__ is not supported in triton") + + def visit_Subscript(self, node): + return self.visit_Subscript_Load(node) + + def visit_ExtSlice(self, node): + return [self.visit(dim) for dim in node.dims] + + def visit_For(self, node): + IteratorClass = self.visit(node.iter.func) + iter_args = [self.visit(arg) for arg in node.iter.args] + iter_kwargs = dict(self.visit(keyword) for keyword in node.iter.keywords) + if IteratorClass == language.static_range: + iterator = IteratorClass(*iter_args, **iter_kwargs) + static_range = range(iterator.start.value, iterator.end.value, iterator.step.value) + for i in static_range: + self.lscope[node.target.id] = constexpr(i) + self.visit_compound_statement(node.body) + for stmt in node.orelse: + ast.NodeVisitor.generic_visit(self, stmt) + return + num_stages = None + loop_unroll_factor = None + disallow_acc_multi_buffer = False + flatten = False + warp_specialize = False + disable_licm = False + if IteratorClass is language.range: + iterator = IteratorClass(*iter_args, **iter_kwargs) + # visit iterator arguments + # note: only `range` iterator is supported now + # collect lower bound (lb), upper bound (ub), and step + lb = iterator.start + ub = iterator.end + step = iterator.step + num_stages = iterator.num_stages + loop_unroll_factor = iterator.loop_unroll_factor + disallow_acc_multi_buffer = iterator.disallow_acc_multi_buffer + flatten = iterator.flatten + warp_specialize = iterator.warp_specialize + disable_licm = iterator.disable_licm + elif IteratorClass is range: + # visit iterator arguments + # note: only `range` iterator is supported now + # collect lower bound (lb), upper bound (ub), and step + lb = iter_args[0] if len(iter_args) > 1 else self.visit(ast.Constant(0)) + ub = iter_args[1] if len(iter_args) > 1 else self.visit(node.iter.args[0]) + step = iter_args[2] if len(iter_args) > 2 else self.visit(ast.Constant(1)) + else: + raise RuntimeError('Only `range` and `static_range` iterators are currently supported') + # handle negative constant step (not supported by scf.for in MLIR) + negative_step = False + if _is_constexpr(step) and step.value < 0: + step = constexpr(-step.value) + negative_step = True + lb, ub = ub, lb + lb = self.semantic.to_tensor(lb) + ub = self.semantic.to_tensor(ub) + step = self.semantic.to_tensor(step) + # induction variable type + if not lb.dtype.is_int() or not ub.dtype.is_int() or not step.dtype.is_int(): + raise TypeError(f"For loop bounds and step must all be ints, are ({lb.dtype}, {ub.dtype}, {step.dtype})") + if _is_non_scalar_tensor(lb): + raise TypeError(f"For lower bound must be a scalar, got {lb.type}") + if _is_non_scalar_tensor(ub): + raise TypeError(f"For upper bound must be a scalar, got {ub.type}") + if _is_non_scalar_tensor(step): + raise TypeError(f"For step must be a scalar, got {step.type}") + iv_type = self.semantic.integer_promote_impl(lb.dtype, ub.dtype) + iv_type = self.semantic.integer_promote_impl(iv_type, step.dtype) + iv_ir_type = iv_type.to_ir(self.builder) + iv_is_signed = iv_type.int_signedness == language.core.dtype.SIGNEDNESS.SIGNED + # lb/ub/step might be constexpr, we need to cast them to tensor + lb = lb.handle + ub = ub.handle + step = step.handle + # ForOp can only accept IndexType as lb/ub/step. Cast integer to Index + lb = self.builder.create_int_cast(lb, iv_ir_type, iv_is_signed) + ub = self.builder.create_int_cast(ub, iv_ir_type, iv_is_signed) + step = self.builder.create_int_cast(step, iv_ir_type, iv_is_signed) + # Create placeholder for the loop induction variable + iv_placeholder = self.builder.create_poison(iv_ir_type) + self.set_value(node.target.id, language.core.tensor(iv_placeholder, iv_type)) + + with enter_sub_region(self) as sr: + liveins, insert_block = sr + ip, last_loc = self._get_insertion_point_and_loc() + + names, init_handles, init_tys = self._find_carries(node, liveins, ignore={node.target.id}) + + # create ForOp + self._set_insertion_point_and_loc(ip, last_loc) + for_op = self.builder.create_for_op(lb, ub, step, init_handles) + if _unwrap_if_constexpr(num_stages) is not None: + for_op.set_attr("tt.num_stages", self.builder.get_int32_attr(num_stages)) + if _unwrap_if_constexpr(loop_unroll_factor) is not None: + for_op.set_attr("tt.loop_unroll_factor", self.builder.get_int32_attr(loop_unroll_factor)) + if disallow_acc_multi_buffer: + for_op.set_attr("tt.disallow_acc_multi_buffer", self.builder.get_unit_attr()) + if flatten: + for_op.set_attr("tt.flatten", self.builder.get_unit_attr()) + if warp_specialize: + for_op.set_attr("tt.warp_specialize", self.builder.get_unit_attr()) + if disable_licm: + for_op.set_attr("llvm.loop_annotation", self.builder.get_disable_loop_licm_attr()) + + self.scf_stack.append(node) + for_op_body = for_op.get_body(0) + self.builder.set_insertion_point_to_start(for_op_body) + block_handles = [for_op_body.arg(i + 1) for i in range(len(init_handles))] + block_args = unflatten_ir_values(block_handles, init_tys) + for name, val in zip(names, block_args): + self._maybe_set_loc_to_name(val, name) + self.set_value(name, val) + self.visit_compound_statement(node.body) + self.scf_stack.pop() + yield_handles = flatten_values_to_ir(self.lscope[name] for name in names) + + # create YieldOp + if len(yield_handles) > 0: + self.builder.create_yield_op(yield_handles) + for_op_region = for_op_body.get_parent() + assert for_op_region.size() == 1, "We use SCF, so the loop body should only have one block" + + # update induction variable with actual value, and replace all uses + self.builder.set_insertion_point_to_start(for_op_body) + iv = for_op.get_induction_var() + if negative_step: + iv = self.builder.create_sub(ub, iv) + iv = self.builder.create_add(iv, lb) + iv_placeholder.replace_all_uses_with(iv) + self.set_value(node.target.id, language.core.tensor(iv, iv_type)) + self._maybe_set_loc_to_name(iv, node.target.id) + + # update lscope & local_defs (ForOp defines new values) + result_handles = [for_op.get_result(i) for i in range(len(init_handles))] + result_values = unflatten_ir_values(result_handles, init_tys) + for name, val in zip(names, result_values): + self.set_value(name, val) + self._maybe_set_loc_to_name(val, name) + + for stmt in node.orelse: + assert False, "Don't know what to do with else after for" + ast.NodeVisitor.generic_visit(self, stmt) + + def visit_Slice(self, node): + lower = self.visit(node.lower) + upper = self.visit(node.upper) + step = self.visit(node.step) + return language.slice(lower, upper, step) + + def visit_Index(self, node): + return self.visit(node.value) + + def visit_keyword(self, node) -> Tuple[str, Any]: + return node.arg, self.visit(node.value) + + def visit_Assert(self, node) -> Any: + test = self.visit(node.test) + msg = self.visit(node.msg) if node.msg is not None else "" + return language.core.device_assert(test, msg, _semantic=self.semantic) + + def call_JitFunction(self, fn: JITFunction, args, kwargs, caller_context=None): + args = inspect.getcallargs(fn.fn, *args, **kwargs) + args = [args[name] for name in fn.arg_names] + for i, arg in enumerate(args): + if isinstance(arg, (language.dtype, float, int, bool, JITFunction)): + args[i] = language.core.constexpr(arg) + args_cst = find_paths_if(args, lambda _, x: _is_constexpr(x)) + args_cst = {path: get_iterable_path(args, path) for path in args_cst} + args_path = find_paths_if(args, lambda _, x: not _is_constexpr(x)) + args_val = [get_iterable_path(args, path) for path in args_path] + # mangle + caller_context = caller_context or self.caller_context + fn_name = mangle_fn(get_full_name(fn), [arg.type for arg in args_val], args_cst, caller_context) + # generate function def if necessary + if not self.module.has_function(fn_name): + # If the callee is not set, we use the same debug setting as the caller + file_name, begin_line = get_jit_fn_file_line(fn) + arg_types = [ + language.core.constexpr if arg is None or isinstance(arg, + (bool, int, language.core.dtype)) else arg.type + for arg in args + ] + prototype = ASTFunction([], arg_types, args_cst, dict()) + generator = CodeGenerator(self.context, prototype, fn.get_capture_scope(), module=self.module, jit_fn=fn, + function_name=fn_name, function_types=self.function_ret_types, + noinline=fn.noinline, file_name=file_name, begin_line=begin_line, + options=self.builder.options, codegen_fns=self.builder.codegen_fns, + module_map=self.builder.module_map, caller_context=caller_context, + is_gluon=self.is_gluon) + try: + generator.visit(fn.parse()) + except Exception as e: + # Wrap the error in the callee with the location of the call. + if knobs.compilation.front_end_debugging: + raise + raise CompilationError(self.jit_fn.src, self.cur_node, None) from e + + callee_ret_type = generator.ret_type + self.function_ret_types[fn_name] = callee_ret_type + else: + callee_ret_type = self.function_ret_types[fn_name] + symbol = self.module.get_function(fn_name) + args_val = flatten_values_to_ir(args_val) + call_op = self.builder.call(symbol, args_val) + if callee_ret_type == language.void: + return None + handles = [call_op.get_result(i) for i in range(call_op.get_num_results())] + return next(unflatten_ir_values(handles, [callee_ret_type])) + + def call_Function(self, node, fn, args, kws): + if isinstance(fn, (BoundJITMethod, BoundConstexprFunction)): + args.insert(0, fn.__self__) + fn = fn.__func__ + if isinstance(fn, JITFunction): + _check_fn_args(node, fn, args) + return self.call_JitFunction(fn, args, kws) + if (hasattr(fn, '__self__') and _is_triton_value(fn.__self__)) or language.core.is_builtin(fn) or isinstance( + fn, ConstexprFunction): + extra_kwargs = dict() + + if isinstance(fn, ConstexprFunction): + sig = inspect.signature(fn.__call__) + else: + sig = inspect.signature(fn) + if '_semantic' in sig.parameters: + extra_kwargs["_semantic"] = self.semantic + if '_generator' in sig.parameters: + extra_kwargs['_generator'] = self + try: + ret = fn(*args, **extra_kwargs, **kws) + # builtin functions return plain tuples for readability + if isinstance(ret, tuple): + ret = language.tuple(ret) + return ret + except Exception as e: + if knobs.compilation.front_end_debugging: + raise + # Normally when we raise a CompilationError, we raise it as + # `from None`, because the original fileline from the exception + # is not relevant (and often points into code_generator.py + # itself). But when calling a function, we raise as `from e` to + # preserve the traceback of the original error, which may e.g. + # be in core.py. + raise CompilationError(self.jit_fn.src, node, str(e)) from e + + if fn in self.builtin_namespace.values() or (hasattr(fn, '__self__') and not _is_triton_value(fn.__self__)): + args = map(_unwrap_if_constexpr, args) + ret = fn(*args, **kws) + + def wrap_constexpr(x): + if _is_triton_value(x): + return x + return constexpr(x) + + if isinstance(ret, (builtins.tuple, language.tuple)): + return _apply_to_tuple_values(ret, wrap_constexpr) + return wrap_constexpr(ret) + + def call_Method(self, node, fn, fn_self, args, kws): + if isinstance(fn, JITFunction): + args.insert(0, fn_self) + return self.call_Function(node, fn, args, kws) + + def visit_Call(self, node): + fn = _unwrap_if_constexpr(self.visit(node.func)) + if not isinstance(fn, BoundJITMethod): + static_implementation = self.statically_implemented_functions.get(fn) + if static_implementation is not None: + return static_implementation(self, node) + + mur = getattr(fn, '_must_use_result', False) + if mur and getattr(node, '_is_unused', False): + error_message = ["The result of %s is not being used." % ast.unparse(node.func)] + if isinstance(mur, str): + error_message.append(mur) + raise CompilationError(self.jit_fn.src, node, " ".join(error_message)) + + kws = dict(self.visit(keyword) for keyword in node.keywords) + args = [] + for arg in node.args: + if isinstance(arg, ast.Starred): + arg = self.visit(arg.value) + assert isinstance(arg, language.core.tuple) + args.extend(arg.values) + else: + args.append(self.visit(arg)) + + return self.call_Function(node, fn, args, kws) + + def visit_Constant(self, node): + return constexpr(node.value) + + def visit_BoolOp(self, node: ast.BoolOp): + method_name = self._method_name_for_bool_op.get(type(node.op)) + if method_name is None: + raise self._unsupported( + node, "AST boolean operator '{}' is not (currently) implemented.".format(node.op.__name__)) + + nontrivial_values = [] + + for subnode in node.values: + # we visit the values in order, executing their side-effects + # and possibly early-exiting: + value = self.visit(subnode) + if not _is_triton_tensor(value): + # this is a constexpr, so we might be able to short-circuit: + bv = bool(value) + if (bv is False) and (method_name == "logical_and"): + # value is falsey so return that: + return value + if (bv is True) and (method_name == "logical_or"): + # value is truthy so return that: + return value + # otherwise, our constexpr has no effect on the output of the + # expression so we do not append it to nontrivial_values. + else: + if value.type.is_block(): + lineno = getattr(node, "lineno", None) + if lineno is not None: + lineno += self.begin_line + warnings.warn_explicit( + "Logical operators 'and' and 'or' are deprecated for non-scalar tensors; please use '&' or '|' instead", + category=UserWarning, + filename=self.file_name, + lineno=lineno, + source=ast.unparse(node), + ) + # not a constexpr so we must append it: + nontrivial_values.append(value) + + if len(nontrivial_values) == 0: + # the semantics of a disjunction of falsey values or conjunction + # of truthy values is to return the final value: + nontrivial_values.append(value) + + while len(nontrivial_values) >= 2: + rhs = nontrivial_values.pop() + lhs = nontrivial_values.pop() + res = self._apply_binary_method(node, method_name, lhs, rhs) + nontrivial_values.append(res) + + assert len(nontrivial_values) == 1 + return nontrivial_values[0] + + _method_name_for_bool_op: Dict[Type[ast.boolop], str] = {ast.And: 'logical_and', ast.Or: 'logical_or'} + + def get_Attribute(self, lhs, attr): + if _is_triton_tensor(lhs) and attr == "T": + return self.semantic.permute(lhs, (1, 0)) + # NOTE: special case ".value" for BC + if isinstance(lhs, constexpr) and attr not in ("value", "type"): + lhs = lhs.value + attr = getattr(lhs, attr) + if _is_triton_value(lhs) and isinstance(attr, JITFunction): + return BoundJITMethod(lhs, attr) + return attr + + def visit_Attribute(self, node): + lhs = self.visit(node.value) + if isinstance(lhs, ModuleType): + # follow module_map until reaching fixed-point: + while (name := lhs.__name__) in self.builder.module_map: + lhs = self.builder.module_map[name] + if lhs.__name__ == name: + break + return self.get_Attribute(lhs, node.attr) + + def visit_Expr(self, node): + node.value._is_unused = True + ast.NodeVisitor.generic_visit(self, node) + + def visit_NoneType(self, node): + return None + + def visit_JoinedStr(self, node): + values = list(node.values) + for i, value in enumerate(values): + if isinstance(value, ast.Constant): + values[i] = str(value.value) + elif isinstance(value, ast.FormattedValue): + conversion_code = value.conversion + evaluated = self.visit(value.value) + if not _is_constexpr(evaluated): + raise self._unsupported( + node, + "Cannot evaluate f-string containing non-constexpr conversion values, found conversion of type " + + str(type(evaluated))) + values[i] = ("{}" if conversion_code < 0 else "{!" + chr(conversion_code) + "}").format(evaluated.value) + else: + raise AssertionError("encountered unexpected node of type {} in a JoinedStr node".format(type(value))) + return ''.join(values) + + def visit(self, node): + if node is None: + return + with warnings.catch_warnings(): + # The ast library added visit_Constant and deprecated some other + # methods but we can't move to that without breaking Python 3.6 and 3.7. + warnings.simplefilter("ignore", DeprecationWarning) # python 3.9 + warnings.simplefilter("ignore", PendingDeprecationWarning) # python 3.8 + last_node = self.cur_node + last_loc = self.builder.get_loc() + self.cur_node = node + if hasattr(node, 'lineno') and hasattr(node, 'col_offset'): + here_loc = self.builder.create_loc(self.file_name, self.begin_line + node.lineno, node.col_offset) + if self.name_loc_as_prefix is not None: + self.builder.set_loc(self.builder.create_name_loc(self.name_loc_as_prefix, here_loc)) + else: + self.builder.set_loc(here_loc) + last_loc = self.builder.get_loc() + try: + ret = super().visit(node) + except CompilationError: + raise + except Exception as e: + if knobs.compilation.front_end_debugging: + raise + # Wrap the error in a CompilationError which contains the source + # of the @jit function. + raise CompilationError(self.jit_fn.src, self.cur_node, repr(e)) from None + + # Reset the location to the last one before the visit + if last_loc: + self.cur_node = last_node + self.builder.set_loc(last_loc) + return ret + + def generic_visit(self, node): + raise self._unsupported(node, "unsupported AST node type: {}".format(type(node).__name__)) + + def execute_static_assert(self, node: ast.Call) -> None: + arg_count = len(node.args) + if not (0 < arg_count <= 2) or len(node.keywords): + raise TypeError("`static_assert` requires one or two positional arguments only") + + passed = _unwrap_if_constexpr(self.visit(node.args[0])) + if not isinstance(passed, bool): + raise NotImplementedError( + "Assertion condition could not be determined at compile-time. Make sure that it depends only on `constexpr` values" + ) + if not passed: + if arg_count == 1: + message = "" + else: + try: + message = self.visit(node.args[1]) + except Exception as e: + message = "" + + raise CompileTimeAssertionFailure(self.jit_fn.src, node, _unwrap_if_constexpr(message)) + return None + + def static_executor(python_fn): + + def ret(self, node: ast.Call): + kws = { + name: _unwrap_if_constexpr(value) + for name, value in (self.visit(keyword) for keyword in node.keywords) + } + args = [_unwrap_if_constexpr(self.visit(arg)) for arg in node.args] + return constexpr(python_fn(*args, **kws)) + + return ret + + from ..experimental.gluon import language as ttgl + statically_implemented_functions: Dict[object, Callable[[ast.Call], Any]] = { + language.core.static_assert: execute_static_assert, + language.core.static_print: static_executor(print), + ttgl.static_assert: execute_static_assert, + ttgl.static_print: static_executor(print), + int: static_executor(int), + len: static_executor(len), + } + + +def ast_to_ttir(fn, src, context, options, codegen_fns, module_map, module=None): + arg_types = [None] * len(fn.arg_names) + + for k, v in src.signature.items(): + idx = fn.arg_names.index(k) + arg_types[idx] = str_to_ty(v, None) + + def apply_constexpr_types(argument, indices, value): + index = indices.pop() + if len(indices) == 0: + if isinstance(argument, list): + argument[index] = constexpr(value).type + else: + argument.types[index] = constexpr(value).type + else: + apply_constexpr_types(argument[index], indices, value) + + for path, value in src.constants.items(): + apply_constexpr_types(arg_types, list(path)[::-1], value) + + prototype = ASTFunction([], arg_types, src.constants, src.attrs) + file_name, begin_line = get_jit_fn_file_line(fn) + # query function representation + from collections import namedtuple + leaves = filter(lambda v: len(v) == 1, src.constants) + constants = {fn.arg_names[i[0]]: src.constants[i] for i in leaves} + signature = src.signature + proxy = namedtuple("SpecializationProxy", ["constants", "signature"])(constants, signature) + generator = CodeGenerator(context, prototype, gscope=fn.get_capture_scope(), function_name=fn.repr(proxy), + jit_fn=fn, is_kernel=True, file_name=file_name, begin_line=begin_line, options=options, + codegen_fns=codegen_fns, module_map=module_map, module=module, is_gluon=fn.is_gluon()) + generator.visit(fn.parse()) + module = generator.module + # module takes ownership of the context + module.context = context + if not module.verify(): + if not fn.is_gluon(): + print(module) + raise RuntimeError("error encountered during parsing") + return module diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/compiler/compiler.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/compiler/compiler.py new file mode 100644 index 0000000000000000000000000000000000000000..d4872a463589d2cfdf302a546b8c2e021fb1a7c3 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/compiler/compiler.py @@ -0,0 +1,501 @@ +from __future__ import annotations +import hashlib +import json +from .._C.libtriton import get_cache_invalidating_env_vars, ir +from ..backends import backends +from ..backends.compiler import Language +from ..backends.compiler import BaseBackend, GPUTarget +from .. import __version__, knobs +from ..runtime.autotuner import OutOfResources +from ..runtime.cache import get_cache_manager, get_dump_manager, get_override_manager, get_cache_key +from ..runtime.driver import driver +from ..tools.disasm import get_sass +from pathlib import Path +import re +import functools +import os +import time +import copy + +# - ^\s*tt\.func\s+ : match the start of the string, any leading whitespace, the keyword func, +# and any following whitespace +# - (public\s+)? : optionally match the keyword public and any following whitespace +# - (@\w+) : match an @ symbol followed by one or more word characters +# (letters, digits, or underscores), and capture it as group 1 (the function name) +# - (\((?:%\w+: \S+(?: \{\S+ = \S+ : \S+\})?(?:, )?)*\)) : match a pair of parentheses enclosing +# zero or more arguments separated by commas, and capture it as group 2 (the argument list) +# - (attributes \{[\S\s]+\})? : optionally match attributes enclosed in braces and capture it as group 3 +ptx_prototype_pattern = r"\.(?:visible|extern)\s+\.(?:entry|func)\s+(\w+)\s*\(([^)]*)\)" +prototype_pattern = { + "ptx": ptx_prototype_pattern, +} + +ptx_arg_type_pattern = r"\.param\s+\.(\w+)" +arg_type_pattern = { + "ptx": ptx_arg_type_pattern, +} + + +def convert_type_repr(x): + # Currently we only capture the pointer type and assume the pointer is on global memory. + # TODO: Capture and support shared memory space + match = re.search(r'!tt\.ptr<([^,]+)', x) + tma = re.search(r'tt.nv_tma_desc = 1', x) + if tma is not None: + return 'nvTmaDesc' + x = re.sub(r' {[^}]+}', '', x) + if match is not None: + return '*' + convert_type_repr(match.group(1)) + return x + + +class ASTSource: + + def __init__(self, fn, signature, constexprs=None, attrs=None) -> None: + self.fn = fn + self.language = Language.TRITON + self.ext = "ttir" + self.name = fn.__name__ + self.signature = signature + self.constants = dict() + if constexprs is not None: + for k, v in constexprs.items(): + k = (fn.arg_names.index(k), ) if isinstance(k, str) else k + assert isinstance(k, tuple) + self.constants[k] = v + self.attrs = attrs or dict() + for k in self.signature.keys(): + if not isinstance(k, str): + raise TypeError("Signature keys must be string") + + def hash(self): + sorted_sig = [v for k, v in sorted(self.signature.items())] + get_key = lambda x: x.cache_key if hasattr(x, 'cache_key') else str(x) + constants_key = '-'.join([get_key(v) for k, v in sorted(self.constants.items())]) + key = f"{self.fn.cache_key}-{str(self.attrs)}-{sorted_sig}-{constants_key}" + return hashlib.sha256(key.encode("utf-8")).hexdigest() + + def make_ir(self, target: GPUTarget, options, codegen_fns, module_map, context): + from .code_generator import ast_to_ttir + return ast_to_ttir(self.fn, self, context=context, options=options, codegen_fns=codegen_fns, + module_map=module_map) + + def parse_options(self): + return dict() + + +class IRSource: + + def __init__(self, path, context, backend): + self.path = path + path = Path(path) + self.ext = path.suffix[1:] + self.language = Language.TRITON + self.src = path.read_text() + ir.load_dialects(context) + backend.load_dialects(context) + + # We don't have a easy-to-use PTX parser that we can use, so keep that regex for now. + # TODO - replace with a proper parser + if self.ext == "ptx": + match = re.search(prototype_pattern[self.ext], self.src, re.MULTILINE) + self.name = match.group(1) + signature = match.group(2) + types = re.findall(arg_type_pattern[self.ext], signature) + self.signature = {k: convert_type_repr(ty) for k, ty in enumerate(types)} + else: + self.module = ir.parse_mlir_module(self.path, context) + fn_name = self.module.get_entry_func_name() + self.name = "@" + fn_name + funcOp = self.module.get_function(fn_name) + func_ty = self.module.get_function_signature(funcOp) + self.signature = {k: ty for k, ty in enumerate(func_ty)} + + def hash(self): + return hashlib.sha256(self.src.encode("utf-8")).hexdigest() + + def make_ir(self, target: GPUTarget, options, codegen_fns, module_map, context): + self.module.context = context + return self.module + + def parse_options(self): + if self.ext == "ttgir": + num_warps = self.module.get_int_attr("ttg.num-warps") + assert num_warps is not None, "Unable to parse ttg.num-warps attribute" + options = {'num_warps': num_warps} + num_ctas = self.module.get_int_attr("ttg.num-ctas") + if num_ctas is not None: + options['num_ctas'] = num_ctas + return options + return dict() + + +@functools.lru_cache() +def max_shared_mem(device): + return driver.active.utils.get_device_properties(device)["max_shared_mem"] + + +def parse(full_name, ext, context): + if ext == "ttir" or ext == "ttgir": + module = ir.parse_mlir_module(full_name, context) + module.context = context + return module + if ext == "llir" or ext == "ptx" or ext == "amdgcn": + return Path(full_name).read_text() + if ext == "cubin" or ext == "hsaco": + return Path(full_name).read_bytes() + + +def filter_traceback(e: BaseException): + """ + Removes code_generator.py and related files from tracebacks. + + These are uninteresting to the user -- "just show me *my* code!" + """ + if knobs.compilation.front_end_debugging: + return + + if e.__cause__ is not None: + filter_traceback(e.__cause__) + if e.__context__ is not None: + filter_traceback(e.__context__) + + # If a user has a file that matches one of these, they're out of luck. + BAD_FILES = [ + "/triton/compiler/code_generator.py", + "/ast.py", + ] + BAD_FILES = [bad_file.replace("/", os.sep) for bad_file in BAD_FILES] + + tb = e.__traceback__ + frames = [] + while tb is not None: + if not any(f for f in BAD_FILES if tb.tb_frame.f_code.co_filename.endswith(f)): + frames.append(tb) + tb = tb.tb_next + + for (cur_frame, next_frame) in zip(frames, frames[1:]): + cur_frame.tb_next = next_frame + + if not frames: + e.__traceback__ = None + else: + frames[-1].tb_next = None + e.__traceback__ = frames[0] + + +class CompileTimer: + + def __init__(self) -> None: + self.start: float = time.time() + self.ir_initialization_end: float | None = None + self.lowering_stage_ends: list[tuple[str, float]] = [] + self.store_results_end: float | None = None + + def finished_ir_initialization(self) -> None: + self.ir_initialization_end = time.time() + + def stage_finished(self, stage_name: str) -> None: + self.lowering_stage_ends.append((stage_name, time.time())) + + def end(self) -> knobs.CompileTimes: + timestamp = time.time() + if self.ir_initialization_end is None: + self.ir_initialization_end = timestamp + else: + self.store_results_end = timestamp + + def delta(start: float, end: float | None) -> int: + if end is None: + return 0 + return int((end - start) * 1000000) + + lowering_stage_durations = [] + stage_start = self.ir_initialization_end + for stage_name, stage_end in self.lowering_stage_ends: + lowering_stage_durations.append((stage_name, delta(stage_start, stage_end))) + stage_start = stage_end + + return knobs.CompileTimes( + ir_initialization=delta(self.start, self.ir_initialization_end), + lowering_stages=lowering_stage_durations, + store_results=delta(stage_start, self.store_results_end), + ) + + +def compile(src, target=None, options=None, _env_vars=None): + compilation_listener = knobs.compilation.listener + if compilation_listener: + timer = CompileTimer() + + if target is None: + target = driver.active.get_current_target() + assert isinstance(target, GPUTarget), "target must be of GPUTarget type" + backend = make_backend(target) + ir_source = not isinstance(src, ASTSource) + # create backend + if ir_source: + assert isinstance(src, str), "source must be either AST or a filepath" + context = ir.context() + src = IRSource(src, context, backend) + + extra_options = src.parse_options() + options = backend.parse_options(dict(options or dict(), **extra_options)) + # create cache manager + env_vars = get_cache_invalidating_env_vars() if _env_vars is None else _env_vars + key = get_cache_key(src, backend, options, env_vars=env_vars) + hash = hashlib.sha256(key.encode("utf-8")).hexdigest() + fn_cache_manager = get_cache_manager(hash) + # For dumping/overriding only hash the source as we want it to be independent of triton + # core changes to make it easier to track kernels by hash. + enable_override = knobs.compilation.override + enable_ir_dump = knobs.compilation.dump_ir + store_only_binary = knobs.compilation.store_binary_only + fn_override_manager = get_override_manager(src.hash()) if enable_override else None + fn_dump_manager = get_dump_manager(src.hash()) if enable_ir_dump else None + # Pre-truncate the file name here to avoid hitting the 255 character limit on common platforms. + # The final file name in the cache will have a format of f"{filename}.{ext}.tmp.pid_{pid}_{uuid}". + # A PID string can be 5-character long. A UUID string has typically 36 characters. Let's truncate + # the file name to 150 characters to be safe. + file_name = src.name[:150] + metadata_filename = f"{file_name}.json" + metadata_group = fn_cache_manager.get_group(metadata_filename) or {} + metadata_path = metadata_group.get(metadata_filename) + always_compile = knobs.compilation.always_compile + if not always_compile and metadata_path is not None: + # cache hit! + res = CompiledKernel(src, metadata_group, hash) + if compilation_listener: + compilation_listener( + src=src, + metadata=res.metadata._asdict(), + metadata_group=metadata_group, + times=timer.end(), + cache_hit=True, + ) + return res + + # initialize metadata + metadata = { + "hash": hash, + "target": target, + **options.__dict__, + **env_vars, + } + metadata["triton_version"] = __version__ + # run compilation pipeline and populate metadata + stages = dict() + backend.add_stages(stages, options, src.language) + first_stage = list(stages.keys()).index(src.ext) + # when the source is an IR file, don't apply the passes related to this stage. This makes it easier to write IR level tests. + if ir_source: + first_stage += 1 + + # For IRSource, we have already grabbed the context + called both + # ir.load_dialects and backend.load_dialects. + if not isinstance(src, IRSource): + context = ir.context() + ir.load_dialects(context) + backend.load_dialects(context) + + codegen_fns = backend.get_codegen_implementation(options) + module_map = backend.get_module_map() + try: + module = src.make_ir(target, options, codegen_fns, module_map, context) + except Exception as e: + filter_traceback(e) + raise + + if ir_source: + ir_filename = f"{file_name}.{src.ext}" + metadata_group[ir_filename] = fn_cache_manager.put(module, ir_filename) + else: + ir_filename = f"{file_name}.source" + metadata_group[ir_filename] = fn_cache_manager.put(module, ir_filename) + + use_ir_loc = knobs.compilation.use_ir_loc + if ir_source and use_ir_loc: + module.create_location_snapshot(src.path) + print(f"Creating new locations for {src.path}") + + if compilation_listener: + timer.finished_ir_initialization() + for ext, compile_ir in list(stages.items())[first_stage:]: + next_module = compile_ir(module, metadata) + ir_filename = f"{file_name}.{ext}" + if fn_override_manager is None: + # Users can override kernels at scale by setting `ir_override` in autotune config + # without TRITON_KERNEL_OVERRIDE + if (ir_override := metadata.get("ir_override", None)) and ir_override.endswith(f".{ext}"): + next_module = parse(ir_override, ext, context) + elif full_name := fn_override_manager.get_file(ir_filename): + print(f"\nOverriding kernel with file {full_name}") + next_module = parse(full_name, ext, context) + # If TRITON_STORE_BINARY_ONLY is 1, only store cubin/hsaco/json + if (not store_only_binary) or (ext in ("cubin", "hsaco", "json")): + metadata_group[ir_filename] = fn_cache_manager.put(next_module, ir_filename) + if fn_dump_manager is not None: + fn_dump_manager.put(next_module, ir_filename) + if ext == "cubin": + sass = get_sass(next_module) + fn_dump_manager.put(sass, file_name + ".sass") + # use an env variable to parse ir from file + if use_ir_loc == ext: + ir_full_name = fn_cache_manager.get_file(ir_filename) + next_module.create_location_snapshot(ir_full_name) + print(f"Creating new locations for {ir_full_name}") + module = next_module + if compilation_listener: + timer.stage_finished(ext) + # write-back metadata + metadata_group[metadata_filename] = fn_cache_manager.put(json.dumps(metadata, default=vars), metadata_filename, + binary=False) + fn_cache_manager.put_group(metadata_filename, metadata_group) + + # notify any listener + if compilation_listener: + compilation_listener(src=src, metadata=metadata, metadata_group=metadata_group, times=timer.end(), + cache_hit=False) + # return handle to compiled kernel + return CompiledKernel(src, metadata_group, hash) + + +def make_backend(target: GPUTarget) -> BaseBackend: + actives = [x.compiler for x in backends.values() if x.compiler.supports_target(target)] + if len(actives) != 1: + raise RuntimeError( + f"{len(actives)} compatible backends for target ({target.backend}) ({actives}). There should only be one.") + return actives[0](target) + + +class LazyDict: + + def __init__(self, data): + self.data = data + self.extras = [] + + def get(self): + for func, args in self.extras: + self.data = self.data | func(*args) + self.extras.clear() + return self.data + + def add(self, func, args): + self.extras.append((func, args)) + + +class AsmDict(dict): + + def __missing__(self, key): + + if key == "sass": + value = get_sass(self["cubin"]) + else: + raise KeyError("Unknown key: '%s'" % key) + + self[key] = value + return value + + +def _raise_error(err, *args, **kwargs): + raise copy.deepcopy(err) + + +class CompiledKernel: + + def __init__(self, src, metadata_group, hash): + from collections import namedtuple + metadata_path = next((Path(p) for c, p in metadata_group.items() if c.endswith(".json"))) + metadata = json.loads(metadata_path.read_text()) + # JSON serialization dumps the target as a dict. Restore it to a GPUTarget. + target = metadata['target'] + metadata['target'] = GPUTarget(target['backend'], target['arch'], target['warp_size']) + KernelMetadata = namedtuple('KernelMetadata', sorted(list(metadata.keys()))) + self.metadata = KernelMetadata(**metadata) + backend = make_backend(self.metadata.target) + self.packed_metadata = backend.pack_metadata(self.metadata) + self.src = src + self.hash = hash + self.name = self.metadata.name + # stores the text of each level of IR that was generated during compilation + asm_files = [Path(p) for c, p in metadata_group.items() if not c.endswith(".json")] + binary_ext = backend.binary_ext + self.asm = AsmDict({ + file.suffix[1:]: file.read_bytes() if file.suffix[1:] == binary_ext else file.read_text() + for file in asm_files + }) + self.metadata_group = metadata_group + self.kernel = self.asm[binary_ext] + # binaries are lazily initialized + # because it involves doing runtime things + # (e.g., checking amount of shared memory on current device) + self.module = None + self.function = None + self._run = None + + def _init_handles(self): + if self.module is not None: + return + + def raise_(err): + # clone the exception object so that the one saved in the closure + # of the partial function below doesn't get assigned a stack trace + # after the subsequent raise. otherwise, the CompiledKernel instance + # saved in the (global) kernel cache will keep references to all the + # locals in the traceback via the exception instance in the closure. + cloned_err = copy.deepcopy(err) + self._run = functools.partial(_raise_error, cloned_err) + raise err + + device = driver.active.get_current_device() + # create launcher + self._run = driver.active.launcher_cls(self.src, self.metadata) + # not enough shared memory to run the kernel + max_shared = max_shared_mem(device) + if self.metadata.shared > max_shared: + raise_(OutOfResources(self.metadata.shared, max_shared, "shared memory")) + if hasattr(self.metadata, "tmem_size") and self.metadata.tmem_size is not None: + # Use blackwell max tmem size for now, this should be moved in device properties + max_tmem_size = 512 # tmem size in number of columns + if self.metadata.tmem_size > max_tmem_size: + raise_(OutOfResources(self.metadata.tmem_size, max_tmem_size, "tensor memory")) + if knobs.runtime.kernel_load_start_hook is not None: + knobs.runtime.kernel_load_start_hook(self.module, self.function, self.name, self.metadata_group, self.hash) + # TODO: n_regs, n_spills should be metadata generated when calling `ptxas` + self.module, self.function, self.n_regs, self.n_spills, self.n_max_threads = driver.active.utils.load_binary( + self.name, self.kernel, self.metadata.shared, device) + warp_size = driver.active.get_current_target().warp_size + if self.metadata.num_warps * warp_size > self.n_max_threads: + raise_(OutOfResources(self.metadata.num_warps * warp_size, self.n_max_threads, "threads")) + if knobs.runtime.kernel_load_end_hook is not None: + knobs.runtime.kernel_load_end_hook(self.module, self.function, self.name, self.metadata_group, self.hash) + + @property + def run(self): + if self._run is None: + self._init_handles() + return self._run + + def launch_metadata(self, grid, stream, *args): + if knobs.runtime.launch_enter_hook is None: + return None + self._init_handles() + ret = LazyDict({"name": self.name, "function": self.function, "stream": stream}) + if not isinstance(self.src, ASTSource) or self.src.fn.launch_metadata is None: + return ret + arg_dict = {name: arg for name, arg in zip(self.src.fn.arg_names, args)} + ret.add(self.src.fn.launch_metadata, (grid, self.metadata, arg_dict)) + return ret + + def __getitem__(self, grid): + self._init_handles() + + def runner(*args, stream=None): + if stream is None: + device = driver.active.get_current_device() + stream = driver.active.get_current_stream(device) + launch_metadata = self.launch_metadata(grid, stream, *args) + self.run(grid[0], grid[1], grid[2], stream, self.function, self.packed_metadata, launch_metadata, + knobs.runtime.launch_enter_hook, knobs.runtime.launch_exit_hook, *args) + + return runner diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/compiler/errors.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/compiler/errors.py new file mode 100644 index 0000000000000000000000000000000000000000..39e6c4dfb04dd2067d50ce7c79f762c5e7e2d5b8 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/compiler/errors.py @@ -0,0 +1,51 @@ +import ast +from typing import Optional +from ..errors import TritonError + + +class CompilationError(TritonError): + """Base class for all errors raised during compilation""" + source_line_count_max_in_message = 12 + + def _format_message(self) -> str: + node = self.node + if self.src is None: + source_excerpt = " " + else: + if hasattr(node, 'lineno'): + source_excerpt = self.src.split('\n')[:node.lineno][-self.source_line_count_max_in_message:] + if source_excerpt: + source_excerpt.append(' ' * node.col_offset + '^') + source_excerpt = '\n'.join(source_excerpt) + else: + source_excerpt = " " + else: + source_excerpt = self.src + + message = "at {}:{}:\n{}".format(node.lineno, node.col_offset, source_excerpt) if hasattr( + node, 'lineno') else source_excerpt + if self.error_message: + message += '\n' + self.error_message + return message + + def __init__(self, src: Optional[str], node: ast.AST, error_message: Optional[str] = None): + self.src = src + self.node = node + self.error_message = error_message + self.message = self._format_message() + + def __str__(self): + return self.message + + def __reduce__(self): + # this is necessary to make CompilationError picklable + return type(self), (self.src, self.node, self.error_message) + + +class CompileTimeAssertionFailure(CompilationError): + """Specific exception for failed tests in `static_assert` invocations""" + pass + + +class UnsupportedLanguageConstruct(CompilationError): + pass diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/compiler/make_launcher.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/compiler/make_launcher.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6e286a20f2d132003bc6f9415e18b2c3c7cd401b --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/__init__.py @@ -0,0 +1,6 @@ +from . import nvidia +from . import amd +from ._runtime import constexpr_function, jit +from triton.language.core import must_use_result + +__all__ = ["constexpr_function", "jit", "must_use_result", "nvidia", "amd"] diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/_compiler.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/_compiler.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/_runtime.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/_runtime.py new file mode 100644 index 0000000000000000000000000000000000000000..d98bb2098b1385e0d338b5dffec62884d3d9a5d9 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/_runtime.py @@ -0,0 +1,102 @@ +from __future__ import annotations +from triton.compiler.compiler import ASTSource +from triton.backends.compiler import Language +from triton.runtime.jit import JITFunction, constexpr_function +from typing import TypeVar, Optional, Callable, Iterable, Union +from triton._C.libtriton import ir + +T = TypeVar("T") + +__all__ = ["constexpr_function", "jit"] + + +class GluonASTSource(ASTSource): + + def __init__(self, fn, signature, constexprs=None, attrs=None) -> None: + super().__init__(fn, signature, constexprs, attrs) + self.language = Language.GLUON + self.ext = "ttgir" + + def make_ir(self, target, options, codegen_fns, module_map, context): + from triton.compiler.compiler import make_backend + from triton.compiler.code_generator import ast_to_ttir + + builder = ir.builder(context) + module = builder.create_module() + + # Assign module attributes eagerly, as they are needed to verify layouts + backend = make_backend(target) + target = backend.get_target_name(options) + + module.set_attr("ttg.target", builder.get_string_attr(target)) + module.set_attr("ttg.num-warps", builder.get_int32_attr(options.num_warps)) + module.set_attr("ttg.num-ctas", builder.get_int32_attr(options.num_ctas)) + module.set_attr("ttg.threads-per-warp", builder.get_int32_attr(options.warp_size)) + + is_cuda = options.backend_name == "cuda" + if is_cuda and options.maxnreg is not None: + module.set_attr("ttg.maxnreg", builder.get_int32_attr(options.maxnreg)) + + module = ast_to_ttir(self.fn, self, context=context, options=options, codegen_fns=codegen_fns, + module_map=module_map, module=module) + return module + + +class GluonJITFunction(JITFunction[T]): + + def create_binder(self): + result = super().create_binder() + self.ASTSource = GluonASTSource + return result + + def is_gluon(self): + return True + + +def jit( + fn: Optional[T] = None, + *, + version=None, + repr: Optional[Callable] = None, + launch_metadata: Optional[Callable] = None, + do_not_specialize: Optional[Iterable[int | str]] = None, + do_not_specialize_on_alignment: Optional[Iterable[int | str]] = None, + debug: Optional[bool] = None, + noinline: Optional[bool] = None, +) -> Union[GluonJITFunction[T], Callable[[T], JITFunction[T]]]: + """ + Decorator for JIT-compiling a function using the Triton compiler. + + :note: When a jit'd function is called, arguments are + implicitly converted to pointers if they have a :code:`.data_ptr()` method + and a `.dtype` attribute. + + :note: This function will be compiled and run on the GPU. It will only have access to: + + * python primitives, + * builtins within the triton package, + * arguments to this function, + * other jit'd functions + + :param fn: the function to be jit-compiled + :type fn: Callable + """ + + def decorator(fn: T) -> JITFunction[T]: + assert callable(fn) + return GluonJITFunction( + fn, + version=version, + do_not_specialize=do_not_specialize, + do_not_specialize_on_alignment=do_not_specialize_on_alignment, + debug=debug, + noinline=noinline, + repr=repr, + launch_metadata=launch_metadata, + ) + + if fn is not None: + return decorator(fn) + + else: + return decorator diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/amd/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/amd/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3271153da6f7f0d01ebac221ac934e7f99c0e9ff --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/amd/__init__.py @@ -0,0 +1,3 @@ +from . import gfx1250 + +__all__ = ["gfx1250"] diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/amd/gfx1250.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/amd/gfx1250.py new file mode 100644 index 0000000000000000000000000000000000000000..0cab725920b0f47ad05739e4e1be08bbb20c91b0 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/amd/gfx1250.py @@ -0,0 +1,46 @@ +from dataclasses import dataclass +from typing import List, Any +from triton._utils import validate_block_shape +from triton.experimental.gluon.language._layouts import PaddedSharedLayout, SwizzledSharedLayout + +__all__ = ["TensorDescriptor"] + + +@dataclass +class TensorDescriptor: + base: Any + shape: List[int] + strides: List[int] + block_shape: List[int] + layout: PaddedSharedLayout | SwizzledSharedLayout + padding: str = "zero" + + def __post_init__(self): + ndim = len(self.shape) + # TODO: support 1D-5D tensor descriptors + assert ndim == 2, f"Expected 2 dimensions but got {ndim} dimensions" + assert len(self.strides) == ndim, f"Expected {ndim} strides but got {len(self.strides)}" + assert len(self.block_shape) == ndim, \ + f"Expected block_shape to have {ndim} dimensions but got {len(self.strides)}" + validate_block_shape(self.block_shape) + assert self.strides[-1] == 1, "Last dimension must be contiguous" + assert isinstance(self.layout, (PaddedSharedLayout, SwizzledSharedLayout)), \ + "Expected layout to be a PaddedSharedLayout or SwizzledSharedLayout" + if isinstance(self.layout, SwizzledSharedLayout): + assert self.layout.max_phase == 1, "Expected max_phase to be 1 for SwizzledSharedLayout" + assert self.padding == "zero", "Only 'zero' padding is supported" + + @staticmethod + def from_tensor(tensor: Any, block_shape: List[int], layout: PaddedSharedLayout | SwizzledSharedLayout): + """ Create a TensorDescriptor object from a tensor. + + Args: + tensor (torch.Tensor): The input tensor. + block_shape (List[int]): The block shape of the tensor. + layout (PaddedSharedLayout | SwizzledSharedLayout): The layout of the tensor in shared memory. + + Returns: + tensor_descriptor: the created TensorDescriptor object + + """ + return TensorDescriptor(tensor, tensor.shape, tensor.stride(), block_shape, layout) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d2842cc0f35f4ba7c5d4bff3a084ae7cd6c1f1fd --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/__init__.py @@ -0,0 +1,137 @@ +from ._core import ( + base_value, + base_type, + block_type, + broadcast, + cast, + constexpr, + dtype, + void, + int1, + int8, + int16, + int32, + int64, + uint8, + uint16, + uint32, + uint64, + float8e5, + float8e5b16, + float8e4nv, + float8e4b8, + float8e4b15, + float16, + bfloat16, + float32, + float64, + pointer_type, + shared_memory_descriptor, + tensor, + tuple, + tuple_type, + _unwrap_if_constexpr, + # API Functions + add, + allocate_shared_memory, + arange, + associative_scan, + assume, + atomic_add, + atomic_and, + atomic_cas, + atomic_max, + atomic_min, + atomic_or, + atomic_xchg, + atomic_xor, + bank_conflicts, + convert_layout, + device_assert, + device_print, + dot_fma, + expand_dims, + full, + fp4_to_fp, + gather, + num_warps, + num_ctas, + histogram, + inline_asm_elementwise, + join, + load, + map_elementwise, + max_constancy, + max_contiguous, + maximum, + minimum, + mul, + multiple_of, + num_programs, + permute, + program_id, + reduce, + reshape, + distributed_type, + shared_memory_descriptor_type, + set_auto_layout, + split, + static_assert, + static_print, + static_range, + store, + sub, + thread_barrier, + to_linear_layout, + to_tensor, + warp_specialize, + where, +) +from ._layouts import ( + AutoLayout, + BlockedLayout, + SliceLayout, + DistributedLinearLayout, + DotOperandLayout, + NVMMADistributedLayout, + NVMMASharedLayout, + SwizzledSharedLayout, + PaddedSharedLayout, + SharedLinearLayout, + CoalescedLayout, +) +from ._math import ( + umulhi, + exp, + exp2, + fma, + log, + log2, + cos, + rsqrt, + sin, + sqrt, + sqrt_rn, + abs, + fdiv, + div_rn, + erf, + floor, + ceil, +) +from ._standard import ( + cdiv, + full_like, + max, + min, + ravel, + reduce_or, + sum, + xor_sum, + zeros, + zeros_like, +) + +from . import nvidia +from . import amd +from . import extra diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/_core.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/_core.py new file mode 100644 index 0000000000000000000000000000000000000000..a00f87fe58491227a1bb657e9dbf9743ef6b76e2 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/_core.py @@ -0,0 +1,592 @@ +from __future__ import annotations +import math +from typing import TypeVar, List, TYPE_CHECKING, Tuple +from functools import wraps +import warnings + +if TYPE_CHECKING: + from triton._C.libtriton.gluon_ir import GluonOpBuilder + from ._semantic import GluonSemantic + +from ._layouts import SharedLayout, DistributedLayout, BlockedLayout, DotOperandLayout, AutoLayout, CoalescedLayout +from triton._C.libtriton import ir +import triton.language.core as tl_core +from triton.language.core import ( + constexpr, + base_value, + base_type, + dtype, + block_type, # TODO: block type with layout info + pointer_type, + void, + int1, + int8, + int16, + int32, + int64, + uint8, + uint16, + uint32, + uint64, + float8e5, + float8e5b16, + float8e4nv, + float8e4b8, + float8e4b15, + float16, + bfloat16, + float32, + float64, + _unwrap_if_constexpr, + _unwrap_shape, + static_range, + tensor, + tuple, + tuple_type, +) + +# We define __all__ only to appease the python linter, these are not used in +# this file but we want to import them anyway so they are importable from here. +__all__ = [ + "constexpr", + "pointer_type", + "void", + "int1", + "int8", + "int16", + "int32", + "int64", + "uint8", + "uint16", + "uint32", + "uint64", + "float8e5", + "float8e5b16", + "float8e4nv", + "float8e4b8", + "float8e4b15", + "float16", + "bfloat16", + "float32", + "float64", + "distributed_type", + "shared_memory_descriptor_type", + "static_range", + "tuple", + "tuple_type", + "num_ctas", +] + +T = TypeVar("T") + +# TODO: split these +GLUON_BUILTIN = "__triton_builtin__" + + +def builtin(fn: T) -> T: + """Mark a function as a builtin.""" + assert callable(fn) + + @wraps(fn) + def wrapper(*args, **kwargs): + if "_semantic" not in kwargs or kwargs["_semantic"] is None: + raise ValueError("Did you forget to add @triton.gluon.jit ? " + "(`_semantic` argument must be provided outside of JIT functions.)") + return fn(*args, **kwargs) + + setattr(wrapper, GLUON_BUILTIN, True) + + return wrapper + + +# Explicitly import forwarded Triton language symbols so mypy sees them. +add = builtin(tl_core.add) +associative_scan = builtin(tl_core.associative_scan) +assume = builtin(tl_core.assume) +atomic_add = builtin(tl_core.atomic_add) +atomic_and = builtin(tl_core.atomic_and) +atomic_cas = builtin(tl_core.atomic_cas) +atomic_max = builtin(tl_core.atomic_max) +atomic_min = builtin(tl_core.atomic_min) +atomic_or = builtin(tl_core.atomic_or) +atomic_xchg = builtin(tl_core.atomic_xchg) +atomic_xor = builtin(tl_core.atomic_xor) +broadcast = builtin(tl_core.broadcast) +cast = builtin(tl_core.cast) +device_assert = builtin(tl_core.device_assert) +device_print = builtin(tl_core.device_print) +expand_dims = builtin(tl_core.expand_dims) +gather = builtin(tl_core.gather) +inline_asm_elementwise = builtin(tl_core.inline_asm_elementwise) +join = builtin(tl_core.join) +load = builtin(tl_core.load) +map_elementwise = builtin(tl_core.map_elementwise) +max_constancy = builtin(tl_core.max_constancy) +max_contiguous = builtin(tl_core.max_contiguous) +maximum = builtin(tl_core.maximum) +minimum = builtin(tl_core.minimum) +mul = builtin(tl_core.mul) +multiple_of = builtin(tl_core.multiple_of) +num_programs = builtin(tl_core.num_programs) +permute = builtin(tl_core.permute) +program_id = builtin(tl_core.program_id) +reduce = builtin(tl_core.reduce) +reshape = builtin(tl_core.reshape) +split = builtin(tl_core.split) +static_assert = builtin(tl_core.static_assert) +static_print = builtin(tl_core.static_print) +store = builtin(tl_core.store) +sub = builtin(tl_core.sub) +to_tensor = builtin(tl_core.to_tensor) +where = builtin(tl_core.where) + + +class distributed_type(block_type): + + def __init__(self, element_ty: dtype, shape: List[int], layout): + layout = _unwrap_if_constexpr(layout) + shape = _unwrap_if_constexpr(shape) + super().__init__(element_ty, shape) + self.layout = layout + self.name = f"<{self.shape}, {self.element_ty}, {self.layout}>" + assert isinstance(layout, DistributedLayout), "tensor layout must be a DistributedLayout" + if not isinstance(layout, (AutoLayout, CoalescedLayout)): + assert len( + shape + ) == layout.rank, f"tensor shape and layout rank mismatch: shape={shape}, layout={layout}, shape rank={len(shape)}, layout rank={layout.rank}" + + def to_ir(self, builder: ir.builder) -> ir.type: + elem_ty = self.element_ty.to_ir(builder) + layout = self.layout._to_ir(builder) + return builder.get_distributed_ty(elem_ty, self.shape, layout) + + def mangle(self) -> str: + elt = self.scalar.mangle() + shape = "_".join(map(str, self.shape)) + layout = self.layout.mangle() + return f"{elt}S{shape}SL{layout}L" + + def with_element_ty(self, scalar_ty: dtype) -> block_type: + return distributed_type(scalar_ty, self.shape, self.layout) + + def __eq__(self, other) -> bool: + if not isinstance(other, distributed_type): + return False + return super().__eq__(other) and self.layout == other.layout + + +class shared_memory_descriptor_type(base_type): + + def __init__(self, element_ty, shape, layout, alloc_shape): + shape = _unwrap_if_constexpr(shape) + alloc_shape = _unwrap_if_constexpr(alloc_shape) + layout = _unwrap_if_constexpr(layout) + self.element_ty = element_ty + self.shape = shape + self.layout = layout + self.alloc_shape = alloc_shape + assert isinstance(layout, SharedLayout) + + def to_ir(self, builder: GluonOpBuilder) -> None: + return builder.get_shared_mem_desc_ty( + self.element_ty.to_ir(builder), + self.shape, + self.layout._to_ir(builder), + self.alloc_shape, + ) + + def _unflatten_ir(self, handles: List[ir.Value], cursor: int) -> Tuple[shared_memory_descriptor, int]: + value = shared_memory_descriptor(handles[cursor], self.element_ty, self.shape, self.layout, self.alloc_shape) + return value, cursor + 1 + + def _flatten_ir_types(self, builder: GluonOpBuilder, out: List[ir.type]) -> None: + out.append(self.to_ir(builder)) + + def __str__(self) -> str: + return f"shared_memory_descriptor<{self.element_ty}, {self.shape}, {self.layout}, {self.alloc_shape}>" + + def __eq__(self, other) -> bool: + return (type(self) is type(other) and self.shape == other.shape and self.layout == other.layout + and self.alloc_shape == other.alloc_shape) + + def __neq__(self, other) -> bool: + return not (self == other) + + def mangle(self) -> str: + shape_str = "_".join([str(s) for s in self.shape]) + return f"MD{self.element_ty.mangle()}S{shape_str}SL{self.layout.mangle()}LAS{self.alloc_shape}ASMD" + + +class shared_memory_descriptor(base_value): + """ + Represents a handle to a shared memory allocation in Gluon IR. + """ + + def __init__(self, handle, element_ty, shape, layout, alloc_shape): + self.handle = handle + self.type = shared_memory_descriptor_type(element_ty, shape, layout, alloc_shape) + + def _flatten_ir(self, handles: List[ir.value]) -> None: + handles.append(self.handle) + + @property + def dtype(self): + return self.type.element_ty + + @property + def shape(self): + return self.type.shape + + @property + def rank(self): + return len(self.shape) + + @property + def numel(self) -> int: + return math.prod(self.shape) + + @property + def layout(self): + return self.type.layout + + def __str__(self) -> str: + return str(self.type) + + @builtin + def load(self, layout, _semantic: GluonSemantic = None) -> tensor: + """ + Load a tensor from shared memory. + + Args: + layout (DistributedLayout): The destination layout of the tensor. + + Returns: + tensor: A Gluon tensor containing the loaded data. + """ + layout = _unwrap_if_constexpr(layout) + return _semantic.shared_load(self, layout) + + @builtin + def store(self, value, _semantic: GluonSemantic = None) -> None: + """ + Store a tensor into shared memory. + + Args: + value (tensor): The tensor whose contents to store. + """ + return _semantic.shared_store(self, value) + + @builtin + def slice(self, start, length, dim=0, _semantic: GluonSemantic = None) -> shared_memory_descriptor: + """ + Create a subview of shared memory by slicing along a given dimension. + + Args: + start (int): The starting index of the slice. + length (int): The length of the slice. + dim (int): The dimension to slice (default: 0). + + Returns: + shared_memory_descriptor: Descriptor for the sliced subview. + """ + start = _unwrap_if_constexpr(start) + length = _unwrap_if_constexpr(length) + dim = _unwrap_if_constexpr(dim) + return _semantic.memdesc_slice(self, start, length, dim) + + @builtin + def index(self, index, _semantic: GluonSemantic = None) -> shared_memory_descriptor: + """ + Create a subview of shared memory by indexing along the first dimension. + + Args: + index (int): The index at which to take the subview. + + Returns: + shared_memory_descriptor: Descriptor for the indexed subview. + """ + index = _unwrap_if_constexpr(index) + return _semantic.memdesc_index(self, index) + + @builtin + def permute(self, order, _semantic: GluonSemantic = None) -> shared_memory_descriptor: + """ + Permute the dimensions of the shared memory descriptor. + + Args: + order (List[int]): The new ordering of dimensions. + + Returns: + shared_memory_descriptor: Descriptor with permuted dimensions. + """ + order = [_unwrap_if_constexpr(o) for o in order] + return _semantic.memdesc_trans(self, order) + + @builtin + def reshape(self, shape, _semantic: GluonSemantic = None) -> shared_memory_descriptor: + """ + Reshape the shared memory descriptor to a new shape and layout. + + Args: + shape (List[int]): The target shape. + + Returns: + shared_memory_descriptor: Descriptor with the new shape and layout. + """ + shape = [_unwrap_if_constexpr(s) for s in shape] + + return _semantic.memdesc_reshape(self, shape) + + @builtin + def _reinterpret(self, dtype, shape, layout, _semantic: GluonSemantic = None) -> shared_memory_descriptor: + """ + Reinterpret the shared memory descriptor as a different dtype, shape, or layout. + + Args: + dtype (dtype): The new data type. + shape (List[int]): The new shape. + layout (SharedLayout): The new layout. + + Returns: + shared_memory_descriptor: Descriptor with updated type and layout. + """ + dtype = _unwrap_if_constexpr(dtype) + shape = [_unwrap_if_constexpr(s) for s in shape] + layout = _unwrap_if_constexpr(layout) + + return _semantic.memdesc_reinterpret(self, dtype, shape, layout) + + @builtin + def _keep_alive(self, _semantic: GluonSemantic = None) -> None: + """ + Dummy use to keep the shared memory descriptor alive. + """ + return _semantic.shared_dealloc(self) + + +@builtin +def arange(start, end, layout=None, _semantic=None): + """ + Generate a sequence tensor with values in [start, end) using a specified layout. + + Args: + start (int): Inclusive start of the sequence. + end (int): Exclusive end of the sequence. + layout (DistributedLayout): The layout of the output tensor. Defaults to AutoLayout. + + Returns: + tensor: A 1D tensor containing sequential values. + """ + start = _unwrap_if_constexpr(start) + end = _unwrap_if_constexpr(end) + layout = _unwrap_if_constexpr(layout) + return _semantic.arange(start, end, layout) + + +@builtin +def convert_layout(value, layout, assert_trivial=False, _semantic=None): + """ + Convert a tensor to a different distributed layout. + + Args: + value (tensor): The input tensor. + layout (DistributedLayout): The target layout. + assert_trivial (bool): If True, asserts that the conversion is trivial (no data movement). + + Returns: + tensor: The tensor with the new layout. + """ + layout = _unwrap_if_constexpr(layout) + return _semantic.convert_layout(value, layout, assert_trivial) + + +@builtin +def full(shape, value, dtype, layout=None, _semantic=None): + """ + Create a tensor filled with a scalar value, with specified shape, dtype, and layout. + + Args: + shape (Sequence[int]): The shape of the tensor. + value (int or float): The fill value. + dtype (dtype): The data type for the tensor. + layout (Optional[DistributedLayout]): The layout of the output tensor, defaults to AutoLayout(). + + Returns: + tensor: A tensor where every element equals value. + """ + shape = _unwrap_shape(shape) + value = _unwrap_if_constexpr(value) + dtype = _unwrap_if_constexpr(dtype) + layout = _unwrap_if_constexpr(layout) + return _semantic.full(shape, value, dtype, layout) + + +@builtin +def histogram(input, num_bins, mask=None, layout=None, _semantic=None, _generator=None): + """ + Compute a histogram of a 1D integer tensor. + + Args: + input (tensor): 1D tensor of integer values. + num_bins (int): Number of bins. Bins have width 1 and start at 0. + mask (Optional[tensor]): Boolean mask to exclude elements when False. + layout (DistributedLayout): Destination layout of the output histogram. + + Returns: + tensor: 1D int32 tensor of length `num_bins` with the requested layout. + """ + num_bins = _unwrap_if_constexpr(num_bins) + layout = _unwrap_if_constexpr(layout) + if mask is not None: + mask = _semantic.to_tensor(mask) + return _semantic.histogram(input, num_bins, mask, layout) + + +@builtin +def allocate_shared_memory(element_ty, shape, layout, value=None, _semantic=None) -> shared_memory_descriptor: + """ + Allocate shared memory for a tensor with the given element type, shape, and layout. + + Args: + element_ty (dtype): The element data type. + shape (Sequence[int]): The dimensions of the shared memory. + layout (SharedLayout): The shared memory layout. + value (tensor, optional): Initial value to copy into shared memory. + + Returns: + shared_memory_descriptor: Descriptor for the allocated memory. + """ + element_ty = _unwrap_if_constexpr(element_ty) + shape = _unwrap_if_constexpr(shape) + shape = [_unwrap_if_constexpr(s) for s in shape] + layout = _unwrap_if_constexpr(layout) + return _semantic.allocate_shared(element_ty, shape, layout, value) + + +@builtin +def set_auto_layout(value, layout, _semantic=None): + """ + Set a tensor with AutoLayout to a concrete layout + + Args: + value (tensor): The input tensor. + layout (DistribtedLayout): The target layout. + + Returns: + tensor: The tensor with the new layout. + """ + layout = _unwrap_if_constexpr(layout) + return _semantic.set_auto_layout(value, layout) + + +@builtin +def fp4_to_fp(src, elem_type, axis, _semantic=None): + """ + Upcast a tensor from fp4 (e2m1) to another floating point type. + """ + axis = _unwrap_if_constexpr(axis) + elem_type = _unwrap_if_constexpr(elem_type) + return _semantic.fp4_to_fp(src, elem_type, axis) + + +@builtin +def warp_specialize(functions_and_args, worker_num_warps, worker_num_regs, _semantic=None, _generator=None): + """ + Create a warp-specialized execution region, partitioning work across warps. + + This forks the current execution into a "default partition" and an arbitrary number of + "worker partitons". The default partition is executed in the same :code:`num_warps` warps as + the parent region, and may accept tensor arguments and return tensors. Worker partitions are + executed in additional warps, which sit idle while executing the parent region. + + Note that calling warp_specialize recursively is not supported. + + Args: + functions_and_args (List[Tuple[Callable, Any]]): List of functions and arguments for each partition. The first of which is the default partition. + worker_num_warps (List[int]): Number of warps used for each worker partition. + worker_num_regs (List[int]): Number of registers for each worker partition. + + Returns: + Tuple[Any, ...]: Results from the default partition. + """ + worker_num_warps = [_unwrap_if_constexpr(w) for w in worker_num_warps] + worker_num_regs = [_unwrap_if_constexpr(r) for r in worker_num_regs] + return _semantic.warp_specialize(functions_and_args, worker_num_warps, worker_num_regs, _generator) + + +@builtin +def num_warps(_semantic=None, _generator=None): + """ + Returns the number of warps that execute the current context, including in warp-specialized regions. + """ + return _semantic.num_warps(_generator) + + +@builtin +def num_ctas(_semantic=None): + """ + Returns the number of CTAs in the current kernel + """ + return _semantic.num_ctas() + + +@builtin +def thread_barrier(_semantic=None): + """ + Insert a barrier to synchronize threads within a CTA. + """ + return _semantic.debug_barrier() + + +@builtin +def bank_conflicts(distr_ty, shared_ty, _semantic=None) -> int: + """ + Count the bank conflicts per wavefront of each instruction generated when + reading/writing the distributed tensor from/to the shared memory descriptor + using ld.shared/st.shared instructions. + + We define a bank conflict of N to be the excess number of memory accesses that each + wavefront needs to access the shared memory descriptor. When one uses no ld/st + vectorization, this is equal to t he number of excess memory accesses per instruction. + + Args: + distr_ty (distributed_type): The distributed tensor. + shared_ty (shared_memory_descriptor_type): The shared memory descriptor. + + Returns: + int: The number of bank conflicts. + """ + distr_ty = _unwrap_if_constexpr(distr_ty) + shared_ty = _unwrap_if_constexpr(shared_ty) + return _semantic.bank_conflicts(distr_ty, shared_ty) + + +@builtin +def to_linear_layout(layout, shape, _semantic=None): + layout = _unwrap_if_constexpr(layout) + shape = _unwrap_shape(shape) + return _semantic.to_linear_layout(layout, shape) + + +@builtin +def dot_fma(a, b, acc, _semantic=None): + assert isinstance(a, tensor), "a must be a tensor" + assert isinstance(b, tensor), "b must be a tensor" + assert isinstance(acc, tensor), "acc must be a tensor" + + mma_layout = acc.type.layout + assert isinstance(mma_layout, BlockedLayout), "acc must have a BlockedLayout" + assert isinstance(a.type.layout, DotOperandLayout), "a must have a DotOperandLayout" + assert isinstance(b.type.layout, DotOperandLayout), "b must have a DotOperandLayout" + assert a.type.layout.parent == mma_layout, "a's parent layout must be the same as acc's layout" + assert b.type.layout.parent == mma_layout, "b's parent layout must be the same as acc's layout" + assert a.type.layout.operand_index == 0, "a's operand index must be 0" + assert b.type.layout.operand_index == 1, "b's operand index must be 1" + + M, N = acc.shape + K = a.shape[1] + if M * N * K > 2**19: + warnings.warn(f"Large dot FMA instruction size {M}x{N}x{K} may have slow compile times") + + handle = _semantic.dot(a, b, acc, input_precision=None, max_num_imprecise_acc=None, out_dtype=acc.dtype).handle + return tensor(handle, acc.type) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/_layouts.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/_layouts.py new file mode 100644 index 0000000000000000000000000000000000000000..7f5a2c4002986b672bb1ecb49414eebf805ad165 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/_layouts.py @@ -0,0 +1,676 @@ +from dataclasses import dataclass, field +from typing import List + +from triton.language.core import _unwrap_if_constexpr, _unwrap_shape, constexpr_type +from triton.runtime.jit import constexpr_function +import math + + +class DistributedLayout: + """ + Base class for distributed memory layouts in Gluon IR. + """ + + @property + def type(self): + return constexpr_type(self) + + @property + def rank(self): + raise NotImplementedError("DistributedLayout subclasses must define rank") + + +@dataclass(frozen=True) +class AutoLayout(DistributedLayout): + + def _to_ir(self, builder): + return builder.get_auto_layout() + + def mangle(self): + return "AL" + + @property + def rank(self): + raise ValueError("AutoLayout has no rank") + + +@dataclass(frozen=True) +class CoalescedLayout(DistributedLayout): + + def _to_ir(self, builder): + return builder.get_coalesced_layout() + + def mangle(self): + return "CL" + + @property + def rank(self): + raise ValueError("CoalescedLayout has no rank") + + +@dataclass(frozen=True) +class BlockedLayout(DistributedLayout): + """ + Represents a blocked layout, partitioning a tensor across threads, warps, and CTAs. + + Args: + size_per_thread (List[int]): Number of elements per thread per dimension. + threads_per_warp (List[int]): Number of threads per warp per dimension. + warps_per_cta (List[int]): Number of warps per CTA per dimension. + order (List[int]): The ordering of dimensions for partitioning. + cga_layout (Optional[List[List[int]]]): Bases describing how CTAs tile each dimension. + """ + size_per_thread: List[int] + threads_per_warp: List[int] + warps_per_cta: List[int] + order: List[int] + cga_layout: List[List[int]] = field(default_factory=list) + + def __post_init__(self): + super().__setattr__("size_per_thread", _unwrap_if_constexpr(self.size_per_thread)) + super().__setattr__("threads_per_warp", _unwrap_if_constexpr(self.threads_per_warp)) + super().__setattr__("warps_per_cta", _unwrap_if_constexpr(self.warps_per_cta)) + super().__setattr__("order", _unwrap_if_constexpr(self.order)) + + rank = len(self.size_per_thread) + object.__setattr__(self, "cga_layout", self.cga_layout) + assert len(self.threads_per_warp) == rank + assert len(self.warps_per_cta) == rank + assert len(self.order) == rank + + def _to_ir(self, builder): + return builder.get_blocked_layout( + self.size_per_thread, + self.threads_per_warp, + self.warps_per_cta, + self.order, + self.cga_layout, + ) + + def mangle(self) -> str: + + def stringify(x): + if x is None: + return "" + return "_".join(map(str, x)) + + size_per_thread = stringify(self.size_per_thread) + threads_per_warp = stringify(self.threads_per_warp) + warps_per_cta = stringify(self.warps_per_cta) + order = stringify(self.order) + cga_layout = "_".join("~".join(map(str, vec)) for vec in self.cga_layout) if self.cga_layout else "" + return f"B{size_per_thread}_{threads_per_warp}_{warps_per_cta}_{order}_{cga_layout}B" + + def __hash__(self): + return hash((tuple(self.size_per_thread), tuple(self.threads_per_warp), tuple(self.warps_per_cta), + tuple(self.order), tuple(tuple(vec) for vec in self.cga_layout))) + + @property + def rank(self): + return len(self.order) + + +@dataclass(frozen=True) +class SliceLayout(DistributedLayout): + """ + Represents a layout corresponding to slicing a distributed tensor along one dimension. + + Args: + dim (int): The dimension index to slice. + parent (DistributedLayout): The parent layout before slicing. + """ + dim: int + parent: DistributedLayout + + def __post_init__(self): + super().__setattr__("dim", _unwrap_if_constexpr(self.dim)) + super().__setattr__("parent", _unwrap_if_constexpr(self.parent)) + + def _to_ir(self, builder): + return builder.get_slice_layout( + self.dim, + self.parent._to_ir(builder), + ) + + def mangle(self) -> str: + return f"SL{self.dim}_{self.parent.mangle()}SL" + + def __hash__(self): + return hash((self.dim, self.parent)) + + @property + def rank(self): + return self.parent.rank - 1 + + @property + def cga_layout(self): + parent_cga_layout = self.parent.cga_layout + if not parent_cga_layout: + return [] + + rank = self.parent.rank + assert 0 <= self.dim < rank + return [basis[:self.dim] + basis[self.dim + 1:] for basis in parent_cga_layout] + + +@dataclass(frozen=True) +class DistributedLinearLayout(DistributedLayout): + """ + Represents a linear distributed layout with explicit bases at register, lane, warp, and block levels. + See: https://arxiv.org/abs/2505.23819 for reference. + + Args: + reg_bases (List[List[int]]): Bases for register-level distribution. + lane_bases (List[List[int]]): Bases for lane-level distribution. + warp_bases (List[List[int]]): Bases for warp-level distribution. + block_bases (List[List[int]]): Bases for block-level distribution. + shape (List[int]): The tensor global shape. + """ + reg_bases: List[List[int]] + lane_bases: List[List[int]] + warp_bases: List[List[int]] + block_bases: List[List[int]] + shape: List[int] + + def __post_init__(self): + super().__setattr__("reg_bases", _unwrap_shape(self.reg_bases)) + super().__setattr__("lane_bases", _unwrap_shape(self.lane_bases)) + super().__setattr__("warp_bases", _unwrap_shape(self.warp_bases)) + super().__setattr__("block_bases", _unwrap_shape(self.block_bases)) + super().__setattr__("shape", _unwrap_shape(self.shape)) + + rank = len(self.shape) + + for basis in self.reg_bases: + assert len(basis) == rank + for basis in self.lane_bases: + assert len(basis) == rank + for basis in self.warp_bases: + assert len(basis) == rank + for basis in self.block_bases: + assert len(basis) == rank + + def _to_ir(self, builder): + return builder.get_distributed_linear_layout(self.reg_bases, self.lane_bases, self.warp_bases, self.block_bases, + self.shape) + + def mangle(self): + return f"DLL{self.reg_bases}_{self.lane_bases}_{self.warp_bases}_{self.block_bases}_{self.shape}DLL" + + def __hash__(self): + return hash(( + tuple(map(tuple, self.reg_bases)), + tuple(map(tuple, self.lane_bases)), + tuple(map(tuple, self.warp_bases)), + tuple(map(tuple, self.block_bases)), + tuple(self.shape), + )) + + @property + def rank(self): + return len(self.shape) + + +@dataclass(frozen=True) +class DotOperandLayout(DistributedLayout): + """ + Represents a layout for a dot operand. + + Args: + operand_index (int): 0 for LHS and 1 for RHS of the dot operation. + parent (DistributedLayout): The parent layout, representing the MMA. + k_width (int): Number of elements per 32-bits. + """ + operand_index: int + parent: DistributedLayout + k_width: int + + def __post_init__(self): + super().__setattr__("operand_index", _unwrap_if_constexpr(self.operand_index)) + super().__setattr__("parent", _unwrap_if_constexpr(self.parent)) + super().__setattr__("k_width", _unwrap_if_constexpr(self.k_width)) + + def _to_ir(self, builder): + return builder.get_dot_operand_layout(self.operand_index, self.parent._to_ir(builder), self.k_width) + + def mangle(self) -> str: + return f"DO{self.operand_index}_{self.parent.mangle()}_{self.k_width}DO" + + def __hash__(self): + return hash((self.operand_index, self.parent, self.k_width)) + + @property + def rank(self): + return self.parent.rank + + @property + def cga_layout(self): + parent_cga_layout = _unwrap_if_constexpr(getattr(self.parent, "cga_layout", [])) or [] + if not parent_cga_layout: + return [] + + rank = self.parent.rank + assert all(len(basis) == rank for basis in parent_cga_layout) + + k_dim = rank - 1 if self.operand_index == 0 else rank - 2 + assert 0 <= k_dim < rank + + derived = [] + for basis in parent_cga_layout: + new_basis = list(basis) + new_basis[k_dim] = 0 + derived.append(new_basis) + return derived + + +@dataclass(frozen=True, eq=True) +class NVMMADistributedLayout(DistributedLayout): + """ + Represents a layout for NVIDIA MMA (tensor core) operations. + + Args: + version (List[int]): Version identifier for the MMA instruction. + warps_per_cta (List[int]): Number of warps per CTA. + instr_shape (List[int]): Instruction shape for MMA. + cga_layout (Optional[List[List[int]]]): Bases describing CTA tiling. + """ + version: List[int] + warps_per_cta: List[int] + instr_shape: List[int] + cga_layout: List[List[int]] = field(default_factory=list) + + def __post_init__(self): + super().__setattr__("version", _unwrap_if_constexpr(self.version)) + super().__setattr__("warps_per_cta", _unwrap_if_constexpr(self.warps_per_cta)) + super().__setattr__("instr_shape", _unwrap_if_constexpr(self.instr_shape)) + + object.__setattr__(self, "cga_layout", self.cga_layout) + + def _to_ir(self, builder): + return builder.get_mma_layout( + self.version, + self.warps_per_cta, + self.cga_layout, + self.instr_shape, + ) + + def mangle(self) -> str: + cga_layout = "_".join("~".join(map(str, vec)) for vec in self.cga_layout) if self.cga_layout else "" + return f"MMA_{self.version}_{self.warps_per_cta}_{self.instr_shape}_{cga_layout}_MMA" + + def __hash__(self): + return hash((tuple(self.version), tuple(self.warps_per_cta), tuple(self.instr_shape), + tuple(tuple(vec) for vec in self.cga_layout))) + + @property + def rank(self): + return len(self.warps_per_cta) + + +class SharedLayout: + """ + Base class for shared memory layouts in Gluon IR. + """ + + @property + def type(self): + return constexpr_type(self) + + +@constexpr_function +def _get_shape_per_cta(shape, cga_layout): + if not cga_layout: + return shape + shape_per_cta = list(shape) + rank = len(cga_layout[0]) + cga_shape = [1] * rank + for basis in cga_layout: + assert len(basis) == rank + for i in range(rank): + cga_shape[i] = max(cga_shape[i], basis[i]) + # The shape is the largest stride * 2 + for i in range(rank): + cga_shape[i] *= 2 + for dim in range(rank): + assert shape_per_cta[dim] % cga_shape[dim] == 0, f"Shape {shape} is not divisible by CGA layout {cga_layout}" + shape_per_cta[dim] //= cga_shape[dim] + return shape_per_cta + + +@dataclass(frozen=True) +class NVMMASharedLayout(SharedLayout): + """ + Represents a layout for shared memory suitable for NVIDIA MMA operations. + + Args: + swizzle_byte_width (int): Width in bytes for swizzling. + element_bitwidth (int): Bitwidth of element type. + rank (int): Rank of the tensor. + transposed (bool): Whether the layout is transposed. + fp4_padded (bool): Whether FP4 padding is used. + cga_layout (Optional[List[List[int]]]): Bases describing CTA tiling. + """ + swizzle_byte_width: int + element_bitwidth: int + rank: int = 2 + transposed: bool = False + fp4_padded: bool = False + cga_layout: List[List[int]] = field(default_factory=list) + + def __post_init__(self): + super().__setattr__("swizzle_byte_width", _unwrap_if_constexpr(self.swizzle_byte_width)) + super().__setattr__("element_bitwidth", _unwrap_if_constexpr(self.element_bitwidth)) + super().__setattr__("transposed", _unwrap_if_constexpr(self.transposed)) + super().__setattr__("fp4_padded", _unwrap_if_constexpr(self.fp4_padded)) + + # TODO: Make rank optional and check that (rank or cga_layout) + cga_layout = self.cga_layout or [] + if cga_layout: + assert len(cga_layout[0]) == self.rank + + super().__setattr__("rank", _unwrap_if_constexpr(self.rank)) + super().__setattr__("cga_layout", _unwrap_if_constexpr(cga_layout)) + + assert self.element_bitwidth in [8, 16, 32, 64] + assert self.swizzle_byte_width in [0, 32, 64, 128] + + def _to_ir(self, builder): + return builder.get_nvmma_shared_layout( + self.swizzle_byte_width, + self.element_bitwidth, + self.transposed, + self.fp4_padded, + self.cga_layout, + self.rank, + ) + + @staticmethod + @constexpr_function + def get_default_for(block_shape, dtype, transposed=False, fp4_padded=False, cga_layout=None): + """Returns an NVMMASharedLayout with default swizzling for a given shape. + + This picks the largest swizzle pattern compatible with the shape, which + allows emitting the fewest TMA or MMA messages. + """ + packing_factor = 2 if fp4_padded else 1 + shape_per_cta = block_shape if cga_layout is None else _get_shape_per_cta(block_shape, cga_layout) + rank = len(block_shape) + if transposed: + shape_per_cta = shape_per_cta[1:] + shape_per_cta[:1] + contig_dim_size = shape_per_cta[-1] * packing_factor + contig_dim_bytes = contig_dim_size * dtype.primitive_bitwidth // 8 + if contig_dim_bytes >= 128 and contig_dim_bytes % 128 == 0: + swizzle_byte_width = 128 + elif contig_dim_bytes >= 64 and contig_dim_bytes % 64 == 0: + swizzle_byte_width = 64 + elif contig_dim_bytes >= 32 and contig_dim_bytes % 32 == 0: + swizzle_byte_width = 32 + else: + swizzle_byte_width = 0 + + flatten_outer_dim = 1 + for size in shape_per_cta[:-1]: + flatten_outer_dim *= size + if len(block_shape) < 2 or flatten_outer_dim < 8: + swizzle_byte_width = 0 + + return NVMMASharedLayout( + swizzle_byte_width=swizzle_byte_width, + element_bitwidth=dtype.primitive_bitwidth, + rank=rank, + transposed=transposed, + fp4_padded=fp4_padded, + cga_layout=cga_layout, + ) + + def mangle(self) -> str: + cga_layout = "_".join("~".join(map(str, vec)) for vec in self.cga_layout) if self.cga_layout else "" + return f"NVMMA_{self.swizzle_byte_width}_{self.element_bitwidth}_{self.transposed}_{self.fp4_padded}_{cga_layout}_NVMMA" + + def __hash__(self): + return hash((self.swizzle_byte_width, self.element_bitwidth, self.rank, self.transposed, self.fp4_padded, + tuple(tuple(vec) for vec in self.cga_layout) if self.cga_layout else None)) + + +@dataclass(frozen=True, eq=True) +class SwizzledSharedLayout(SharedLayout): + """ + Represents a generic swizzled shared memory layout. + + Args: + vec (int): Vector width for swizzling. + per_phase (int): Elements per swizzle phase. + max_phase (int): Maximum number of swizzle phases. + order (List[int]): Dimension ordering for swizzling. + cga_layout (Optional[List[List[int]]]): Bases describing CTA tiling. + """ + vec: int + per_phase: int + max_phase: int + order: List[int] + cga_layout: List[List[int]] = field(default_factory=list) + + def __post_init__(self): + super().__setattr__("vec", _unwrap_if_constexpr(self.vec)) + super().__setattr__("per_phase", _unwrap_if_constexpr(self.per_phase)) + super().__setattr__("max_phase", _unwrap_if_constexpr(self.max_phase)) + super().__setattr__("order", _unwrap_if_constexpr(self.order)) + + object.__setattr__(self, "cga_layout", self.cga_layout) + + def _to_ir(self, builder): + return builder.get_swizzled_shared_layout( + self.vec, + self.per_phase, + self.max_phase, + self.order, + self.cga_layout, + ) + + def mangle(self) -> str: + + def stringify(x): + if x is None: + return "" + return "_".join(map(str, x)) + + cga_layout = "_".join("~".join(map(str, vec)) for vec in self.cga_layout) if self.cga_layout else "" + return f"SSS_{self.vec}_{self.per_phase}_{self.max_phase}_{stringify(self.order)}_{cga_layout}_SSS" + + def __hash__(self): + return hash( + (self.vec, self.per_phase, self.max_phase, tuple(self.order), tuple(tuple(vec) for vec in self.cga_layout))) + + +@dataclass(frozen=True, eq=True) +class PaddedSharedLayout(SharedLayout): + """ + Represents a layout for the access to shared memory. Compared to SwizzledSharedLayout, + it combined padding and element reordering via linear transformation (e.g. row permutation) + to avoid shared memory bank conflicts. After every interval tensor elements, the + corresponding number of padding elements are inserted. If a position corresponds to + multiple intervals, the padding amounts are summed. + + In the following example of a tensor, + `eM` represents original elements in the and `pN` represents padded element. + + Before padding, the shared memory looks like: + [e0, e1, + e2, e3, + e4, e5, + e6, e7, + ...] + + After padding with interval-padding list [[2, 1], [4, 2]] with an identity remapping, + the shared memory will be + [e0, e1, p0, + e2, e3, p1, p2, p3, + e4, e5, p4, + e6, e7, p5, p6, p7, + ...] + + Furthermore this encoding allows for a linear remapping from the 1-D shared + memory offset to logical n-D tensor elements. The remapping is given in the form + of linear bases mapping from offset to [dim0, dim1...dimN-1]. + See LinearLayout.h for more details how linear layouts are applied to remap + elements. + Some concrete examples using `xN` and `yN` to mean the logical n-D tensor elements + and `pN` to mean padding: + + After padding for shape = [8] with interval-padding list [[2, 2]], offset_bases = [[2], [1]] and block_bases = []: + [x0, x2, p0 p1, x1, x3] + + After padding for shape = [8, 4] with interval_padding_pairs = [[8, 1]], offset_bases = [[0, 1], [0, 2], /*gap, stride by 2 rows*/[2, 0], [4, 0], [1, 0]]] and block_bases = []: + [ + x0y0, x0y1, x0y2, x0y3, + x2y0, x2y1, x2y2, x2y3, + p0, + x4y0, x4y1, x4y2, x4y3, + x6y0, x6y1, x6y2, x6y3, + p1, + x1y0, x1y1, x1y2, x1y3, + x3y0, x3y1, x3y2, x3y3, + p2, + x5y0, x5y1, x5y2, x5y3, + x7y0, x7y1, x7y2, x7y3, + ] + + Args: + interval_padding_pairs (List[int]): List of [interval, padding] pair and both interval and padding must be powers of 2. + offset_bases (List[int]): Bases for shared memory offsets + block_bases (List[List[int]]): Bases for block-level shared memory offsets. + shape (List[int]): n-D logical shared memory shape + """ + interval_padding_pairs: List[List[int]] + offset_bases: List[List[int]] + block_bases: List[List[int]] + shape: List[int] + + def __post_init__(self): + super().__setattr__("interval_padding_pairs", _unwrap_shape(self.interval_padding_pairs)) + super().__setattr__("offset_bases", _unwrap_shape(self.offset_bases)) + super().__setattr__("block_bases", _unwrap_shape(self.block_bases)) + super().__setattr__("shape", _unwrap_shape(self.shape)) + + rank = len(self.shape) + + for basis in self.offset_bases: + assert len(basis) == rank + for basis in self.block_bases: + assert len(basis) == rank + + self.verify() + + def _to_ir(self, builder): + intervals, paddings = zip(*self.interval_padding_pairs) + return builder.get_padded_shared_layout(intervals, paddings, self.offset_bases, self.block_bases, self.shape) + + def mangle(self) -> str: + return f"PaddedShared_{self.interval_padding_pairs}_{self.offset_bases}_{self.block_bases}_{self.shape}_PaddedShared" + + def verify(self): + pairs = self.interval_padding_pairs + assert len(pairs) > 0, "PaddedSharedLayout interval_padding_pairs must have at least one interval-padding pair" + assert all(len(pair) == 2 for pair in pairs) + intervals, paddings = zip(*pairs) + + unique_intervals = list(set(intervals)) + assert len(unique_intervals) == len(intervals) + + is_power_of_2 = lambda n: n > 0 and n & (n - 1) == 0 + assert all(is_power_of_2(n) for n in intervals), "PaddedSharedLayout interval values must all be power of two" + assert all(is_power_of_2(n) for n in paddings), "PaddedSharedLayout padding values must all be power of two" + + rank = len(self.shape) + assert rank > 0, "PaddedSharedLayout order must not be empty" + + @staticmethod + @constexpr_function + def with_identity_for(interval_padding_pairs, shape, order): + """Returns a PaddedSharedLayout with the given interval and padding pairs and an identity mapping as the linear component for the given shape and order. + """ + assert len(shape) == len(order) + is_power_of_2 = lambda n: n > 0 and n & (n - 1) == 0 + assert all(is_power_of_2(n) for n in shape) + + rank = len(shape) + # Create a idendity mapping based on shape + order + offset_bases = [] + for dim in order: + for basis in range(int(math.log2(shape[dim]))): + offset_bases.append([1 << basis if i == dim else 0 for i in range(rank)]) + + return PaddedSharedLayout(interval_padding_pairs, offset_bases, [], shape) + + def __hash__(self): + return hash((tuple(map(tuple, self.interval_padding_pairs)), tuple(map(tuple, self.offset_bases)), + tuple(map(tuple, self.block_bases)), tuple(self.shape))) + + +@dataclass(frozen=True) +class SharedLinearLayout(SharedLayout): + """Represents a shared memory layout defined via an explicit LinearLayout.""" + + offset_bases: List[List[int]] + block_bases: List[List[int]] = field(default_factory=list) + alignment: int = 16 + + def __post_init__(self): + super().__setattr__("offset_bases", _unwrap_shape(self.offset_bases)) + super().__setattr__("block_bases", _unwrap_shape(self.block_bases)) + super().__setattr__("alignment", _unwrap_if_constexpr(self.alignment)) + + assert len(self.offset_bases) != 0, "SharedLinearLayout offset_bases must not be empty" + rank = len(self.offset_bases[0]) + assert rank > 0, "SharedLinearLayout offset_bases must not be empty" + for basis in self.offset_bases: + assert len(basis) == rank + for basis in self.block_bases: + assert len(basis) == rank + assert self.alignment > 0 and (self.alignment & (self.alignment - 1)) == 0, \ + "SharedLinearLayout alignment must be a positive power of two" + + def _to_ir(self, builder): + return builder.get_shared_linear_layout(self.offset_bases, self.block_bases, self.alignment) + + def mangle(self) -> str: + return f"SharedLinear_{self.offset_bases}_{self.block_bases}_{self.alignment}_SharedLinear" + + def __hash__(self): + return hash(( + tuple(map(tuple, self.offset_bases)), + tuple(map(tuple, self.block_bases)), + self.alignment, + )) + + +# Python impl of LinearEncodingAttr::basesPerDim +def bases_per_dim(bases, rank, skip_broadcast=True): + result = [1] * rank + + if not bases: + return result + + non_zero_idx = None + + for basis in bases: + # Find the first non-zero index in the current basis + idx = next((i for i, v in enumerate(basis) if v != 0), None) + if idx is not None: + non_zero_idx = idx + result[idx] *= 2 + elif not skip_broadcast: + # If no non-zero found and we're not skipping broadcasts, use the last found non-zero index + assert non_zero_idx is not None + result[non_zero_idx] *= 2 + + return result + + +def warps_per_cta(layout, shape): + if isinstance(layout, DistributedLinearLayout): + return bases_per_dim(layout.warp_bases, len(shape)) + elif isinstance(layout, (SliceLayout, DotOperandLayout)): + return warps_per_cta(layout.parent, shape) + else: + return layout.warps_per_cta diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/_math.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/_math.py new file mode 100644 index 0000000000000000000000000000000000000000..b9c8d7605e0c25ef5b063027e320486c7c697d66 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/_math.py @@ -0,0 +1,20 @@ +import triton.language.math as tl_math +from ._core import builtin + +umulhi = builtin(tl_math.umulhi) +exp = builtin(tl_math.exp) +exp2 = builtin(tl_math.exp2) +fma = builtin(tl_math.fma) +log = builtin(tl_math.log) +log2 = builtin(tl_math.log2) +cos = builtin(tl_math.cos) +rsqrt = builtin(tl_math.rsqrt) +sin = builtin(tl_math.sin) +sqrt = builtin(tl_math.sqrt) +sqrt_rn = builtin(tl_math.sqrt_rn) +abs = builtin(tl_math.abs) +fdiv = builtin(tl_math.fdiv) +div_rn = builtin(tl_math.div_rn) +erf = builtin(tl_math.erf) +floor = builtin(tl_math.floor) +ceil = builtin(tl_math.ceil) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/_semantic.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/_semantic.py new file mode 100644 index 0000000000000000000000000000000000000000..ec019cbe4a4e0e22fc66f54230bc07dc03cf9e84 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/_semantic.py @@ -0,0 +1,573 @@ +from typing import Sequence, List, TypeVar, Tuple, Callable +import math +from triton.language.semantic import TritonSemantic +from . import _core as ttgl +from ._layouts import AutoLayout, DistributedLayout, DistributedLinearLayout, SliceLayout, SharedLayout, CoalescedLayout +from triton._C.libtriton.gluon_ir import GluonOpBuilder, compute_tmem_reg_layout +from triton.compiler.code_generator import flatten_values_to_ir, unflatten_ir_values + +TensorTy = TypeVar("TensorTy") + + +def _check(cond: bool, msg_fn: Callable[[], str], category=ValueError): + if not cond: + raise category(msg_fn()) + + +def _is_int_list(value): + return isinstance(value, Sequence) and all(isinstance(i, int) for i in value) + + +def _compute_tmem_reg_layout(element_ty, shape, layout, num_warps, instr_variant, cga_layout=None): + _check(isinstance(instr_variant, str), lambda: "instr_variant must be a string") + _check(instr_variant in ("32x32b", "16x64b", "16x128b", "16x256b", "16x32bx2", "32x32b_splitn"), + lambda: f"unknown instr_variant: {instr_variant}") + _check(isinstance(num_warps, int), lambda: f"num_warps must be an int but got {type(num_warps)!r}") + _check(num_warps >= 4 and (num_warps & (num_warps - 1)) == 0, lambda: "num_warps must be a power of two and >= 4") + + shape = list(shape) + _check(all(isinstance(dim, int) for dim in shape), lambda: f"shape entries must be ints but got {shape}") + rank = len(shape) + _check(rank == 2, lambda: "expected a 2D tensor") + + if cga_layout is None: + cga_layout = [] + splitn = instr_variant == "32x32b_splitn" + atom_variant = "32x32b" if splitn else instr_variant + + if cga_layout: + for basis in cga_layout: + _check(len(basis) == rank, lambda: "cga_layout basis rank mismatch") + + layout_obj = compute_tmem_reg_layout( + element_ty, + shape, + layout, + num_warps, + atom_variant, + cga_layout, + ) + _check(layout_obj is not None, + lambda: f"TMEM layout '{atom_variant}' unsupported for shape {shape} and num_warps {num_warps}") + + if splitn: + N = shape[1] + if not layout_obj.reg_bases: + # We cannot use this layout in a load or a store ATM due to a PTX bug! + # You can work around this by loading to 32x32b and follow by a convert_layout to this layout. + _check(layout_obj.lane_bases[-1] == [0, N // 2], + lambda: f"splitn with 1 register requires the last lane basis to be [0, N / 2]. Got {layout_obj}") + layout_obj.reg_bases.append([0, N // 2]) + layout_obj.lane_bases[-1] = [0, 0] + elif layout_obj.reg_bases[-1] != [0, N // 2]: + bitwidth = element_ty.primitive_bitwidth + num_reg = 2**len(layout_obj.reg_bases) + _check( + num_reg > 32 // bitwidth, lambda: "To be able to `tmem.load` into `tl.split` you need to have more " + f"than {32 // bitwidth} {bitwidth}-bit registers, as you need to use " + "the instruction 32x32b.x1 twice. You can always load into " + "instr_variant=\"32x32b\" and then convert_layout to this layout otherwise.") + + reg_bases = layout_obj.reg_bases + for bases_str in ("lane_bases", "warp_bases"): + bases = getattr(layout_obj, bases_str) + for i, basis in enumerate(bases): + if basis == [0, N // 2]: + reg_bases[-1], bases[i] = bases[i], reg_bases[-1] + return layout_obj + assert False, f"splitn requires at least one basis of [0, N / 2]. Got {layout}" + return layout_obj + + +_compute_tmem_reg_layout.__triton_builtin__ = True + + +class GluonCallerContext: + + def __init__(self, num_warps: int): + self.num_warps = num_warps + + def mangle(self): + return f"_NW{self.num_warps}" + + def initialize_callee(self, fn, builder): + fn.set_attr("ttg.num-warps", builder.get_int32_attr(self.num_warps)) + + +class GluonSemantic(TritonSemantic[TensorTy]): + tensor = ttgl.tensor + lang = ttgl + + builder: GluonOpBuilder + + def __init__(self, builder: GluonOpBuilder): + self.builder = builder + + def _wrap_handle_infer_layout(self, handle, scalar_ty, shape): + if shape == []: + ty = scalar_ty + else: + ty = ttgl.distributed_type(scalar_ty, shape, self.builder.get_gluon_layout_from_tensor(handle)) + return self.tensor(handle, ty) + + def _wrap_tensor_infer_layout(self, tensor): + return self._wrap_handle_infer_layout(tensor.handle, tensor.type.scalar, tensor.shape) + + def _broadcast_shapes(self, lhs_shape: List[int], rhs_shape: List[int]): + if len(lhs_shape) != len(rhs_shape): + raise ValueError(f"Cannot broadcast, rank mismatch: {lhs_shape}, {rhs_shape}") + + ret_shape = [] + for i, left in enumerate(lhs_shape): + right = rhs_shape[i] + if left == 1: + ret_shape.append(right) + elif (right == 1) or (right == left): + ret_shape.append(left) + else: + raise ValueError("Cannot make_shape_compatible: incompatible dimensions " + "at index " + str(i) + ": " + str(left) + " and " + str(right)) + return ret_shape + + def expand_dims(self, input: TensorTy, axis: int) -> TensorTy: + dst_shape = [ttgl._unwrap_if_constexpr(x) for x in input.shape] + dst_shape.insert(axis, 1) + + if axis < 0: + axis += len(input.shape) + + _check(isinstance(input.type, ttgl.distributed_type), + lambda: f"expected expand_dims input to be a distributed_type but got: {input.type!r}") + layout = input.type.layout + _check(isinstance(layout, (SliceLayout, AutoLayout, CoalescedLayout)), + lambda: f"expected expand_dims input to have a SliceLayout, but got: {layout}") + _check( + isinstance(layout, (AutoLayout, CoalescedLayout)) or layout.dim == axis, + lambda: f"expected expand_dims input layout to be sliced in axis {axis} but got {layout.dim}") + + handle = self.builder.create_expand_dims(input.handle, axis) + return self._wrap_handle_infer_layout(handle, input.type.scalar, dst_shape) + + def join(self, a: TensorTy, b: TensorTy) -> TensorTy: + a, b = self.broadcast_impl_value(a, b) + _check(a.shape != [], lambda: "Cannot join scalars in gluon") + value = super().join(a, b) + return self._wrap_tensor_infer_layout(value) + + def split(self, a: TensorTy) -> Tuple[TensorTy, TensorTy]: + lhs, rhs = super().split(a) + return self._wrap_tensor_infer_layout(lhs), self._wrap_tensor_infer_layout(rhs) + + def permute(self, input: TensorTy, dims: Tuple[int]) -> TensorTy: + value = super().permute(input, dims) + return self._wrap_tensor_infer_layout(value) + + def broadcast_impl_shape(self, input: TensorTy, shape: Tuple[int]) -> TensorTy: + _check(isinstance(input.type, ttgl.distributed_type), + lambda: f"expected expand_dims input to be a distributed_type but got: {input.type!r}") + src_shape = input.type.get_block_shapes() + _check(len(src_shape) == len(shape), lambda: f"Cannot broadcast, rank mismatch: {src_shape}, {shape}") + if shape == src_shape: + return input + for i, item in enumerate(src_shape): + if shape[i] != item and item != 1: + raise ValueError(f"Cannot broadcast, the expanded size of the tensor ({shape[i]})" + f" must match the existing size ({item}) at non-singleton dimension" + f" {i}: {src_shape}, {shape}") + ret_ty = ttgl.distributed_type(input.type.scalar, shape, input.type.layout) + handle = self.builder.create_broadcast(input.handle, ret_ty.to_ir(self.builder)) + return self.tensor(handle, ret_ty) + + def broadcast_impl_value(self, lhs: TensorTy, rhs: TensorTy) -> TensorTy: + lhs_ty = lhs.type + rhs_ty = rhs.type + + if not lhs_ty.is_block() or not rhs_ty.is_block(): + return super().broadcast_impl_value(lhs, rhs) + + _check(isinstance(lhs_ty, ttgl.distributed_type), + lambda: f"expected broadcast left input to be a distributed_type but got: {lhs_ty!r}") + _check(isinstance(rhs_ty, ttgl.distributed_type), + lambda: f"expected broadcast right input to be a distributed_type but got: {rhs_ty!r}") + + lhs_shape = lhs_ty.get_block_shapes() + rhs_shape = rhs_ty.get_block_shapes() + ret_shape = self._broadcast_shapes(lhs_shape, rhs_shape) + + is_lhs_auto = isinstance(lhs_ty.layout, AutoLayout) + is_rhs_auto = isinstance(rhs_ty.layout, AutoLayout) + if is_lhs_auto and not is_rhs_auto: + lhs = self.set_auto_layout(lhs, rhs_ty.layout) + elif is_rhs_auto and not is_lhs_auto: + rhs = self.set_auto_layout(rhs, lhs_ty.layout) + elif lhs_ty.layout != rhs_ty.layout: + raise ValueError(f"Layout mismatch in broadcast: {lhs_ty.layout} vs {rhs_ty.layout}") + + lhs = self.broadcast_impl_shape(lhs, ret_shape) + rhs = self.broadcast_impl_shape(rhs, ret_shape) + return lhs, rhs + + def arange(self, start, end, layout): + shape = [end - start] + if layout is None: + layout = AutoLayout() + ret_ty = ttgl.distributed_type(ttgl.int32, shape, layout) + return super().arange(start, end, ret_ty=ret_ty) + + def reshape(self, input: TensorTy, dst_shape: List[int], can_reorder: bool): + _check(not can_reorder, lambda: "can_reorder is not supported in gluon") + value = super().reshape(input, dst_shape, can_reorder) + return self._wrap_tensor_infer_layout(value) + + def splat(self, value, shape, layout): + if len(shape) == 0: + return value + ret_ty = ttgl.distributed_type(value.dtype, shape, layout) + handle = self.builder.create_splat(ret_ty.to_ir(self.builder), value.handle) + return ttgl.tensor(handle, ret_ty) + + def full(self, shape, value, dtype, layout): + scalar = self.make_scalar(value, dtype) + if layout is None: + layout = AutoLayout() + return self.splat(scalar, shape, layout) + + def convert_layout(self, value, layout, assert_trivial=False): + ty = value.type + _check(isinstance(ty, ttgl.distributed_type), + lambda: f"expected convert_layout input to be a distributed_type but got: {ty!r}") + _check(isinstance(layout, ttgl.DistributedLayout), + lambda: f"expected 'layout' to be a DistributedLayout but got {layout}") + ret_ty = ttgl.distributed_type(ty.element_ty, ty.shape, layout) + ret_ty_ir = ret_ty.to_ir(self.builder) + if assert_trivial and not self.builder.is_convert_layout_trivial(ret_ty_ir, value.handle): + raise TypeError(f"layout conversion from {ty.layout} to {layout} is not trivial.\n" + f"The linear layouts are:\n{self.to_linear_layout(ty.layout, ty.shape)}\n" + f"{self.to_linear_layout(layout, ty.shape)}") + handle = self.builder.create_convert_layout(ret_ty_ir, value.handle) + return ttgl.tensor(handle, ret_ty) + + def allocate_shared(self, element_ty, shape, layout, value): + _check(isinstance(element_ty, ttgl.dtype), lambda: f"expected 'element_ty' to be a dtype but got {element_ty}") + _check(_is_int_list(shape), lambda: f"all elements of 'shape' must be integers but got {shape}") + _check(isinstance(layout, ttgl.SharedLayout), + lambda: f"expected 'layout' to be a SharedLayout but got {layout}") + ty = ttgl.shared_memory_descriptor_type(element_ty, shape, layout, shape) + if value is not None: + handle = self.builder.create_local_alloc(ty.to_ir(self.builder), value.handle) + else: + handle = self.builder.create_local_alloc(ty.to_ir(self.builder)) + return ttgl.shared_memory_descriptor(handle, element_ty, shape, layout, shape) + + def shared_load(self, mem_desc, layout): + _check(isinstance(layout, ttgl.DistributedLayout), + lambda: f"expected 'layout' to be a DistributedLayout but got {layout}") + ret_ty = ttgl.distributed_type(mem_desc.dtype, mem_desc.shape, layout) + handle = self.builder.create_local_load(ret_ty.to_ir(self.builder), mem_desc.handle) + return ttgl.tensor(handle, ret_ty) + + def shared_store(self, mem_desc, value): + _check(isinstance(value, ttgl.tensor), lambda: f"expected 'value' to be a tensor, but got a {type(value)}") + _check(value.shape == mem_desc.shape, + lambda: f"source shape {value.shape} and destination shape {mem_desc.shape} must match") + _check(value.dtype == mem_desc.dtype, + lambda: f"source dtype {value.dtype} and destination dtype {mem_desc.dtype} must match") + self.builder.create_local_store(mem_desc.handle, value.handle) + + def bank_conflicts(self, distr_ty, shared_ty): + if not isinstance(distr_ty, ttgl.distributed_type): + raise TypeError( + f"bank_conflicts expects the register layout to be a distributed_type, got {type(distr_ty)}") + + if not isinstance(shared_ty, ttgl.shared_memory_descriptor_type): + raise TypeError( + f"bank_conflicts expects the shared layout to be a shared_memory_descriptor_type, got {type(shared_ty)}" + ) + + if distr_ty.shape != shared_ty.shape: + raise ValueError(f"register shape {distr_ty.shape} and shared shape {shared_ty.shape} must match") + if shared_ty.element_ty != distr_ty.element_ty: + raise ValueError( + f"mismatched dtypes between register ({distr_ty.element_ty}) and shared ({shared_ty.element_ty}) layouts" + ) + if shared_ty.shape != shared_ty.alloc_shape[-len(shared_ty.shape):]: + raise ValueError( + f"bank_conflicts NYI for subslices. Got shape {shared_ty.shape} and alloc_shape {shared_ty.alloc_shape}" + ) + + reg_attr = distr_ty.layout._to_ir(self.builder) + shared_attr = shared_ty.layout._to_ir(self.builder) + return self.builder.get_shared_bank_conflicts(reg_attr, shared_attr, list(distr_ty.shape), + distr_ty.element_ty.primitive_bitwidth) + + def to_linear_layout(self, layout, shape): + _check(isinstance(layout, (DistributedLayout, SharedLayout)), + lambda: f"Expected a DistributedLayout or SharedLayout, got {type(layout)}") + + if not isinstance(shape, list): + shape = list(shape) + + layout = ttgl._unwrap_if_constexpr(layout) + + if isinstance(layout, (AutoLayout, DistributedLinearLayout)): + return ttgl.constexpr(layout) + + return ttgl.constexpr(self.builder.to_linear_layout(layout._to_ir(self.builder), shape)) + + def shared_dealloc(self, mem_desc): + self.builder.create_local_dealloc(mem_desc.handle) + + def set_auto_layout(self, value, layout): + src_ty = value.type + _check(isinstance(layout, DistributedLayout), + lambda: f"set_auto_layout must set to a distributed layout but got {layout}") + _check(isinstance(src_ty.layout, AutoLayout), + lambda: f"set_auto_layout input must have auto layout but got {value.type.layout}") + handle = self.builder.create_set_auto_layout(layout._to_ir(self.builder), value.handle) + res_ty = ttgl.distributed_type(src_ty.element_ty, src_ty.shape, layout) + return self.tensor(handle, res_ty) + + def memdesc_slice(self, mem_desc, start, length, dim): + _check(isinstance(start, int), lambda: f"expected 'start' to be an int but got {start}") + _check(isinstance(length, int), lambda: f"expected 'length' to be an int but got {length}") + _check(isinstance(dim, int), lambda: f"expected 'dim' to be an int but got {dim}") + offsets = [0] * mem_desc.rank + offsets[dim] = start + shape = list(mem_desc.shape) + shape[dim] = length + layout = mem_desc.layout + ty = ttgl.shared_memory_descriptor_type(mem_desc.dtype, shape, layout, mem_desc.type.alloc_shape) + builder = self.builder + handle = builder.create_memdesc_subslice(ty.to_ir(builder), mem_desc.handle, offsets) + return ttgl.shared_memory_descriptor(handle, **ty.__dict__) + + def memdesc_index(self, mem_desc, index): + index = self.to_tensor(index) + _check(index.type == ttgl.int32, lambda: f"expected 'index' to be int32 but got {index.type}") + shape = mem_desc.shape[1:] + index = self.to_tensor(index).handle + layout = mem_desc.layout + ty = ttgl.shared_memory_descriptor_type(mem_desc.dtype, shape, layout, shape) + builder = self.builder + handle = builder.create_memdesc_index(ty.to_ir(builder), mem_desc.handle, index) + return ttgl.shared_memory_descriptor(handle, **ty.__dict__) + + def memdesc_trans(self, mem_desc, order): + _check(_is_int_list(order), lambda: f"all elements of 'order' must be integers but got {order}") + _check( + len(order) == len(mem_desc.shape), + lambda: f"source rank ({mem_desc.rank}) and order length ({len(order)}) must match") + + shape = [mem_desc.shape[i] for i in order] + alloc_shape = mem_desc.type.alloc_shape + new_alloc_shape = alloc_shape[:len(alloc_shape) - mem_desc.rank] + new_alloc_shape += [alloc_shape[len(alloc_shape) - mem_desc.rank:][i] for i in order] + + handle = self.builder.create_memdesc_trans(mem_desc.handle, order) + layout = self.builder.get_gluon_layout_from_memdesc(handle) + return ttgl.shared_memory_descriptor(handle, element_ty=mem_desc.dtype, shape=shape, + alloc_shape=new_alloc_shape, layout=layout) + + def memdesc_reshape(self, mem_desc, shape): + _check(_is_int_list(shape), lambda: f"all elements of 'shape' must be integers but got {shape}") + _check( + math.prod(shape) == math.prod(mem_desc.shape), + lambda: (f"memdesc_reshape total elements mismatch: " + f"{mem_desc.shape} -> {shape}"), + ) + + handle = self.builder.create_memdesc_reshape(mem_desc.handle, shape) + layout = self.builder.get_gluon_layout_from_memdesc(handle) + alloc_shape = mem_desc.type.alloc_shape + prefix_len = len(alloc_shape) - mem_desc.rank + new_alloc_shape = alloc_shape[:prefix_len] + list(shape) + + return ttgl.shared_memory_descriptor( + handle, + element_ty=mem_desc.dtype, + shape=shape, + alloc_shape=new_alloc_shape, + layout=layout, + ) + + def memdesc_reinterpret(self, mem_desc, dtype, shape, layout): + _check(isinstance(dtype, ttgl.dtype), lambda: f"expected 'dtype' to be a dtype but got {dtype}") + _check(_is_int_list(shape), lambda: f"all elements of 'shape' must be integers but got {shape}") + _check(isinstance(layout, ttgl.SharedLayout), + lambda: f"expected 'layout' to be a SharedLayout but got {layout}") + ty = ttgl.shared_memory_descriptor_type(dtype, shape, layout, shape) + handle = self.builder.create_memdesc_reinterpret(ty.to_ir(self.builder), mem_desc.handle) + return ttgl.shared_memory_descriptor(handle, **ty.__dict__) + + def wrap_tensor(self, x, scalar_ty, ret_shape, layout): + if ret_shape: + res_ty = ttgl.distributed_type(scalar_ty, ret_shape, layout) + else: + res_ty = scalar_ty + return self.tensor(x, res_ty) + + @staticmethod + def _check_same_layout(xs): + for x in xs: + _check(isinstance(x.type, ttgl.distributed_type), lambda: f"expected distributed_type but got: {x.type!r}") + layouts = [x.type.layout for x in xs] + l0 = layouts[0] + _check(all(l == l0 for l in layouts[1:]), + lambda: f"Expected inputs to have matching layouts, but got: {layouts}") + + def associative_scan(self, inputs: Sequence[TensorTy], axis: int, region_builder_fn, + reverse: bool) -> Tuple[TensorTy, ...]: + shape = inputs[0].type.shape + rank = len(shape) + + assert -rank <= axis < rank, f"scan axis {axis} must be < inputs rank ({rank})" + + if axis < 0: + axis += rank + + for t in inputs: + assert t.type.shape == shape, "all scan inputs must have the same shape" + + scan_op = self.builder.create_scan([t.handle for t in inputs], axis, reverse) + region_builder_fn(scan_op) + assert scan_op.verify() + + return tuple( + self._wrap_handle_infer_layout(scan_op.get_result(i), inputs[i].type.scalar, shape) + for i in range(len(inputs))) + + def reduction(self, inputs: Sequence[TensorTy], axis: int, region_builder_fn) -> Tuple[TensorTy, ...]: + if axis is None: + inputs = tuple(self.reshape(t, [t.numel.value], can_reorder=False) for t in inputs) + axis = 0 + # get result shape + shape = inputs[0].type.shape + rank = len(shape) + _check(0 <= axis < rank, lambda: f"expected reduction axis to be in the range [0, {rank}) but got {axis}") + self._check_same_layout(inputs) + ret_shape = [s for i, s in enumerate(shape) if i != axis] + assert all(t.type.shape == shape for t in inputs), "all reduction inputs must have the same shape" + + reduce_op = self.builder.create_reduce([t.handle for t in inputs], axis) + region_builder_fn(reduce_op) + assert reduce_op.verify() + + return tuple( + self._wrap_handle_infer_layout(reduce_op.get_result(i), inputs[i].type.scalar, ret_shape) + for i in range(len(inputs))) + + def histogram(self, input: TensorTy, num_bins: int, mask: TensorTy, layout) -> TensorTy: + _check(len(input.shape) == 1, lambda: "histogram only supports 1D input") + _check(input.dtype.is_int(), lambda: "histogram only supports integer input") + _check(layout is not None, lambda: "histogram requires a destination layout") + if mask is not None: + mask, input = self.broadcast_impl_value(mask, input) + _check(mask.type.scalar.is_bool(), lambda: "Mask must have boolean scalar type") + mask = mask.handle + layout_attr = layout._to_ir(self.builder) + handle = self.builder.create_histogram(input.handle, num_bins, mask, layout_attr) + return self.wrap_tensor(handle, ttgl.int32, [num_bins], layout) + + def cat(self, lhs: TensorTy, rhs: TensorTy, can_reorder: bool, layout) -> TensorTy: + _check(layout is not None, lambda: "cat requires a destination layout") + _check(can_reorder, lambda: "current implementation of `cat` always may reorder elements") + _check(len(lhs.shape) == 1, lambda: "cat requires a rank-1 input") + ret_type = ttgl.distributed_type(lhs.type.scalar, [lhs.shape[0] + rhs.shape[0]], layout) + return self.tensor(self.builder.create_cat(lhs.handle, rhs.handle, ret_type.to_ir(self.builder)), ret_type) + + def gather(self, src: TensorTy, index: TensorTy, axis: int) -> TensorTy: + _check(isinstance(src.type, ttgl.distributed_type), lambda: f"expected distributed_type but got: {src.type!r}") + _check(isinstance(index.type, ttgl.distributed_type), + lambda: f"expected distributed_type but got: {index.type!r}") + _check(index.type.scalar.is_int(), lambda: f"expected integer scalar type but got: {index.type.scalar!r}") + + rank = len(src.type.shape) + _check(len(index.type.shape) == rank, lambda: "source and index tensors must have the same rank") + _check(-rank <= axis < rank, lambda: f"gather axis {axis} must be < source rank ({rank})") + if axis < 0: + axis += rank + + for d in range(rank): + if d == axis: + continue + _check( + index.type.shape[d] == src.type.shape[d], + lambda: f"index dim {axis} must match the corresponding source dim", + ) + gather = self.builder.create_gather(src.handle, index.handle, axis) + return self.wrap_tensor(gather, src.type.scalar, index.type.shape, index.type.layout) + + def fp4_to_fp(self, src: TensorTy, elem_type, axis) -> TensorTy: + result = self.builder.create_fp4_to_fp(src.handle, elem_type.to_ir(self.builder), axis) + shape = list(src.type.shape) + shape[axis] *= 2 + return self._wrap_handle_infer_layout(result, elem_type, shape) + + def warp_specialize(self, functions_and_args, worker_num_warps: Sequence[int], worker_num_regs: Sequence[int], + generator): + for _, args in functions_and_args: + _check(isinstance(args, (tuple, ttgl.tuple)), + lambda: f"function arguments must be a tuple of arguments, but got {type(args)}") + + assert len(functions_and_args) >= 1, "expected at least one function for the default partition" + default_partition, default_args = functions_and_args[0] + num_partitions = len(functions_and_args) - 1 + workers = functions_and_args[1:] + + assert num_partitions == len( + worker_num_warps + ), f"warp specialize got {num_partitions} partitions but {len(worker_num_warps)} warp counts" + assert num_partitions == len( + worker_num_regs + ), f"warp specialize got {num_partitions} partitions but {len(worker_num_regs)} register counts" + + builder = self.builder + insert_pt = builder.get_insertion_point() + + # Emit the default partition to get the result types. + default_block = builder.new_block() + builder.set_insertion_point_to_start(default_block) + default_results = generator.call_JitFunction(default_partition, default_args, kwargs={}) + mlir_results = [] + if default_results is not None: + mlir_results = flatten_values_to_ir(default_results) + builder.create_warp_yield(mlir_results) + result_types = [r.get_type() for r in mlir_results] + + # Create the warp specialize op. + worker_args = [flatten_values_to_ir(args) for _, args in workers] + mlir_args = sum(worker_args, []) + builder.restore_insertion_point(insert_pt) + ws_op = builder.create_warp_specialize(result_types, mlir_args, worker_num_warps) + ws_op.get_default_region().push_back(default_block) + ws_op.set_requested_registers(worker_num_regs) + + # Emit the partition regions. + builder.create_block_with_parent(ws_op.get_partition_op_holder(), []) + partitions_op = builder.create_warp_specialize_partitions(num_partitions) + arg_types = [arg.get_type() for arg in mlir_args] + arg_it = 0 + for i, (func, args) in enumerate(workers): + caller_context = GluonCallerContext(num_warps=worker_num_warps[i]) + block = builder.create_block_with_parent(partitions_op.get_region(i), arg_types) + mlir_args = worker_args[i] + block_args = [block.get_argument(arg_it + j) for j in range(len(mlir_args))] + block_args = unflatten_ir_values(block_args, [arg.type for arg in args]) + generator.call_JitFunction(func, block_args, kwargs={}, caller_context=caller_context) + builder.create_warp_return() + arg_it += len(mlir_args) + + builder.set_insertion_point_after(ws_op.get_operation()) + mlir_results = [ws_op.get_result(i) for i in range(len(result_types))] + if default_results is None: + return + return tuple(unflatten_ir_values(mlir_results, [r.type for r in default_results])) + + def num_ctas(self): + return ttgl.constexpr(self.builder.options.num_ctas) + + def num_warps(self, generator): + if generator.caller_context is not None: + assert isinstance(generator.caller_context, GluonCallerContext) + return ttgl.constexpr(generator.caller_context.num_warps) + return ttgl.constexpr(self.builder.options.num_warps) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/_standard.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/_standard.py new file mode 100644 index 0000000000000000000000000000000000000000..caa0e6fb0f5d210048f51cb60ffcdba2bd74715f --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/_standard.py @@ -0,0 +1,81 @@ +from typing import TypeVar +from triton.runtime.jit import JITFunction +import triton.language.standard as tl_standard +from .._runtime import GluonJITFunction, jit +from triton import knobs +from . import _core as ttgl + +T = TypeVar("T") + + +def _import_from_triton(fn: JITFunction[T]) -> GluonJITFunction[T]: + assert knobs.runtime.interpret or isinstance(fn, JITFunction) + # Wrap the function and preserve its original docstring + gluon_fn = jit(fn.fn) + gluon_fn.__doc__ = fn.__doc__ + return gluon_fn + + +cdiv = _import_from_triton(tl_standard.cdiv) +sum = _import_from_triton(tl_standard.sum) +max = _import_from_triton(tl_standard.max) +min = _import_from_triton(tl_standard.min) +ravel = _import_from_triton(tl_standard.ravel) +reduce_or = _import_from_triton(tl_standard.reduce_or) +xor_sum = _import_from_triton(tl_standard.xor_sum) + + +@jit +def zeros(shape, dtype, layout=None): + """ + Create a tensor filled with zeros. + + Args: + shape (Sequence[int]): The shape of the tensor. + dtype (dtype): The data type for the tensor. + layout (Optional[DistributedLayout]): The distributed layout of the tensor, defaults to AutoLayout(). + + Returns: + tensor: A tensor where every element is zero. + """ + return ttgl.full(shape, 0, dtype, layout) + + +@jit +def full_like(input, value, shape=None, dtype=None, layout=None): + """ + Create a tensor with the same properties as a given tensor, filled with a specified value. + + Args: + input (tensor): Reference tensor to infer default shape, dtype, and layout. + value (int or float): The fill value. + shape (Sequence[int], optional): Target shape. Defaults to input.shape. + dtype (dtype, optional): Target data type. Defaults to input.dtype. + layout (DistributedLayout, optional): Target layout. Defaults to input.layout. + + Returns: + tensor: A tensor where every element equals value. + """ + return ttgl.full( + input.shape if shape is None else shape, + value, + input.dtype if dtype is None else dtype, + input.type.layout if layout is None else layout, + ) + + +@jit +def zeros_like(input, shape=None, dtype=None, layout=None): + """ + Create a tensor with the same properties as a given tensor, filled with zeros. + + Args: + input (tensor): Reference tensor to infer default shape, dtype, and layout. + shape (Sequence[int], optional): Target shape. Defaults to input.shape. + dtype (dtype, optional): Target data type. Defaults to input.dtype. + layout (DistributedLayout, optional): Target layout. Defaults to input.layout. + + Returns: + tensor: A tensor where every element is zero. + """ + return full_like(input, 0, shape=shape, dtype=dtype, layout=layout) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/amd/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/amd/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..89f534c60446d26e3cc27b70061648e29adfba43 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/amd/__init__.py @@ -0,0 +1,6 @@ +from ._layouts import AMDMFMALayout, AMDWMMALayout +from . import cdna3, cdna4 +from . import rdna3, rdna4 +from . import gfx1250 + +__all__ = ["AMDMFMALayout", "AMDWMMALayout", "cdna3", "cdna4", "rdna3", "rdna4", "gfx1250"] diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/amd/_layouts.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/amd/_layouts.py new file mode 100644 index 0000000000000000000000000000000000000000..a3d616fea94255b36312cc0713776f897a1cd04e --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/amd/_layouts.py @@ -0,0 +1,187 @@ +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import List, Optional +from triton.language.core import _unwrap_if_constexpr + +from triton.experimental.gluon.language._layouts import DistributedLayout + +__all__ = [ + "AMDMFMALayout", + "AMDWMMALayout", +] + + +@dataclass(frozen=True) +class AMDMFMALayout(DistributedLayout): + """ + Represents a layout for AMD MFMA (matrix core) operations. + + Args: + version (int): The GPU architecture. + instr_shape (List[int]): The shape in the form of (M, N, K) of the matrix. + transposed (bool): Indicates the result tensor is transposed so that each thread holds consecutive elements in the same row instead of column, which is good for chained dot and global write. + warps_per_cta (List[int]): The warp layout in the block. + element_bitwidth Optional(int): Bit width of the output element type. Supported values are 32 and 64. Defaults to 32. + tiles_per_warp Optional(List[int]): The tile layout within a warp. Defaults to unit tile layout, i.e., single tile on all dimensions. + cga_layout (Optional[List[List[int]]]): Bases describing CTA tiling. + + Current supported versions: + + - 1: gfx908 + - 2: gfx90a + - 3: gfx942 + - 4: gfx950 + """ + version: int + instr_shape: List[int] + transposed: bool + warps_per_cta: List[int] + element_bitwidth: Optional[int] = None + tiles_per_warp: Optional[List[int]] = None + cga_layout: List[List[int]] = field(default_factory=list) + + def __post_init__(self): + super().__setattr__("version", _unwrap_if_constexpr(self.version)) + super().__setattr__("instr_shape", _unwrap_if_constexpr(self.instr_shape)) + super().__setattr__("transposed", _unwrap_if_constexpr(self.transposed)) + super().__setattr__("warps_per_cta", _unwrap_if_constexpr(self.warps_per_cta)) + super().__setattr__("element_bitwidth", _unwrap_if_constexpr(self.element_bitwidth)) + super().__setattr__("tiles_per_warp", _unwrap_if_constexpr(self.tiles_per_warp)) + + if self.element_bitwidth is None: + object.__setattr__(self, "element_bitwidth", 32) + if self.tiles_per_warp is None: + object.__setattr__(self, "tiles_per_warp", [1] * len(self.warps_per_cta)) + + object.__setattr__(self, "cga_layout", self.cga_layout) + self.verify() + + def _to_ir(self, builder): + return builder.get_amd_mfma_layout( + self.version, + self.warps_per_cta, + self.instr_shape, + self.transposed, + self.cga_layout, + self.tiles_per_warp, + self.element_bitwidth, + ) + + def mangle(self) -> str: + + def stringify(x): + if x is None: + return "" + return "_".join(map(str, x)) + + cga_layout = stringify(["~".join(map(str, vec)) for vec in self.cga_layout] if self.cga_layout else None) + return f"MFMA_{self.version}_{stringify(self.instr_shape)}_{self.transposed}_{stringify(self.warps_per_cta)}_{self.element_bitwidth}_{stringify(self.tiles_per_warp)}_{cga_layout}_MFMA" + + def verify(self): + assert self.version >= 1 and self.version <= 4, "version must be in the [1, 4] range" + assert len(self.instr_shape) == 3, "instr_shape must follow the (M, N, K) format" + valid_shapes = [[32, 32], [16, 16], [64, 4], [4, 64]] + assert self.instr_shape[0:2] in valid_shapes, f"invalid intrinsic shape {self.instr_shape}" + assert self.element_bitwidth in [32, 64], "element bitwidth must be 32 or 64" + + rank = len(self.warps_per_cta) + assert all(len(vec) == rank for vec in self.cga_layout), "cga_layout basis rank mismatch" + + def __hash__(self): + return hash(( + self.version, + tuple(self.instr_shape), + self.transposed, + tuple(self.warps_per_cta), + self.element_bitwidth if self.element_bitwidth else None, + tuple(self.tiles_per_warp) if self.tiles_per_warp else None, + tuple(tuple(vec) for vec in self.cga_layout), + )) + + @property + def rank(self): + return len(self.warps_per_cta) + + +@dataclass(frozen=True) +class AMDWMMALayout(DistributedLayout): + """ + Represents a layout for AMD WMMA (matrix core) operations. + + Args: + version (int): Indicates the GPU architecture. + transposed (bool): Indicates the result tensor is transposed. + warps_per_cta (List[int]): Number of warps per CTA. + instr_shape (Optional[List[int]]): Instruction shape (M, N, K). Defaults to (16, 16, 16). + cga_layout (Optional[List[List[int]]]): Bases describing CTA tiling. + + Current supported versions: + + - 1: RDNA3; e.g., gfx1100, gfx1101 + - 2: RDNA4; e.g., gfx1200, gfx1201 + - 3: gfx1250 + """ + version: int + transposed: bool + warps_per_cta: List[int] + instr_shape: Optional[List[int]] = None + tiles_per_warp: Optional[List[int]] = None + cga_layout: List[List[int]] = field(default_factory=list) + + def __post_init__(self): + super().__setattr__("version", _unwrap_if_constexpr(self.version)) + super().__setattr__("transposed", _unwrap_if_constexpr(self.transposed)) + super().__setattr__("warps_per_cta", _unwrap_if_constexpr(self.warps_per_cta)) + + if self.tiles_per_warp is None: + tiles_per_warp = [1] * len(self.warps_per_cta) + else: + tiles_per_warp = _unwrap_if_constexpr(self.tiles_per_warp) + + super().__setattr__("tiles_per_warp", tiles_per_warp) + + instr_shape = _unwrap_if_constexpr(self.instr_shape) if self.instr_shape is not None else [16, 16, 16] + super().__setattr__("instr_shape", _unwrap_if_constexpr(instr_shape)) + object.__setattr__(self, "cga_layout", self.cga_layout) + self.verify() + + def _to_ir(self, builder): + return builder.get_amd_wmma_layout( + self.version, + self.transposed, + self.warps_per_cta, + self.tiles_per_warp, + self.cga_layout, + self.instr_shape, + ) + + def mangle(self) -> str: + + def stringify(x): + if x is None: + return "" + return "_".join(map(str, x)) + + cga_layout = stringify(["~".join(map(str, vec)) for vec in self.cga_layout] if self.cga_layout else None) + return f"WMMA_{self.version}_{self.transposed}_{stringify(self.warps_per_cta)}_{stringify(self.tiles_per_warp)}_{stringify(self.instr_shape)}_{cga_layout}_WMMA" + + def verify(self): + assert self.version >= 1 and self.version <= 3, "version must be in the [1, 3] range" + + rank = len(self.warps_per_cta) + assert all(len(vec) == rank for vec in self.cga_layout), "cga_layout basis rank mismatch" + + def __hash__(self): + return hash(( + self.version, + self.transposed, + tuple(self.warps_per_cta), + tuple(self.tiles_per_warp) if self.tiles_per_warp else None, + tuple(self.instr_shape) if self.instr_shape else None, + tuple(tuple(vec) for vec in self.cga_layout), + )) + + @property + def rank(self): + return len(self.warps_per_cta) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/amd/_ops.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/amd/_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..547761307dc4bce878afb33991758961bc064eb4 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/amd/_ops.py @@ -0,0 +1,77 @@ +import math + +from triton import knobs +from triton.experimental.gluon.language import _core as ttgl +from triton.experimental.gluon.language._semantic import _check + +from .._core import _unwrap_if_constexpr +from .._layouts import DotOperandLayout +from ._layouts import AMDWMMALayout + + +def _verify_wmma(version, a, b, acc): + _check(acc is not None, lambda: "acc is required") + + layout = acc.type.layout + _check( + isinstance(layout, AMDWMMALayout) and layout.version == version, + lambda: f"Expected layout to be an instance of AMDWMMALayout with version {version}") + + a_layout = a.type.layout + _check( + isinstance(a_layout, DotOperandLayout) and isinstance(a_layout.parent, AMDWMMALayout) + and a_layout.parent.version == version, + lambda: "Expected a's layout to be a DotOperandLayout with parent matching AMDWMMALayout") + + b_layout = b.type.layout + _check( + isinstance(b_layout, DotOperandLayout) and isinstance(b_layout.parent, AMDWMMALayout) + and b_layout.parent.version == version, + lambda: "Expected b's layout to be a DotOperandLayout with parent matching AMDWMMALayout") + + +def _wmma(version, a, b, acc, semantic): + """ Shared implementation for AMD WMMA operations for Gluon builtins """ + _verify_wmma(version, a, b, acc) + + handle = semantic.dot(a, b, acc, input_precision=knobs.language.fp32_default, max_num_imprecise_acc=None, + out_dtype=acc.dtype).handle + return ttgl.tensor(handle, acc.type) + + +def _mma_scaled(a, a_scale, a_format, b, b_scale, b_format, acc, scale_fn, semantic): + """ Shared implementation for AMD WMMA scaled and MFMA scaled operation. """ + + def _get_scale_shape(op_idx, operand, format): + operand_shape = [s for s in operand.type.shape] + scale_shape = operand_shape + unpack_factor = 2 if format.value == "e2m1" else 1 + if op_idx == 0: + k = scale_shape[-1] * unpack_factor + scale_shape[-1] = k // 32 + else: + k = scale_shape[-2] * unpack_factor + scale_shape[-2] = k // 32 + scale_shape[-2], scale_shape[-1] = scale_shape[-1], scale_shape[-2] + return scale_shape + + def _create_and_broadcast_default_scale(op_idx, scale, format): + operand = a if op_idx == 0 else b + + scale_shape = _get_scale_shape(op_idx, operand, format) + if isinstance(scale, ttgl.tensor) and scale.numel.value != 1: + # In the case of scale pre-shuffling, the input shape is different from the default shape. We only check + # the number of elements here. + assert math.prod(scale_shape) == scale.numel.value, "Incompatible scale shape" + return scale + + scale_layout = scale_fn(operand.type.layout, scale_shape) + scale_value = _unwrap_if_constexpr(scale) + scale_value = 0x7F if scale_value is None else scale_value + return semantic.full(scale_shape, scale_value, ttgl.uint8, scale_layout) + + a_scale = _create_and_broadcast_default_scale(0, a_scale, a_format) + b_scale = _create_and_broadcast_default_scale(1, b_scale, b_format) + output = semantic.dot_scaled(a, a_scale, a_format, b, b_scale, b_format, acc, fast_math=False, lhs_k_pack=True, + rhs_k_pack=True, out_dtype=ttgl.float32) + return ttgl.tensor(output.handle, acc.type) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/amd/cdna3/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/amd/cdna3/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7d88a62b84a99de5f3f706cb76d078ef6a06c2a9 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/amd/cdna3/__init__.py @@ -0,0 +1,238 @@ +from __future__ import annotations +from typing import TYPE_CHECKING + +from triton import knobs +from triton.experimental.gluon.language import _core as ttgl +from triton._C.libtriton import ir +from ..._core import builtin, _unwrap_if_constexpr + +if TYPE_CHECKING: + from ..._semantic import GluonSemantic + +__all__ = [ + "buffer_atomic_add", "buffer_atomic_and", "buffer_atomic_min", "buffer_atomic_max", "buffer_atomic_or", + "buffer_atomic_xor", "buffer_atomic_xor", "buffer_load", "buffer_store", "mfma" +] + +_atomic_op_str_to_op = { + "smax": ir.ATOMIC_OP.MAX, "smin": ir.ATOMIC_OP.MIN, "umax": ir.ATOMIC_OP.UMAX, "umin": ir.ATOMIC_OP.UMIN, "fadd": + ir.ATOMIC_OP.FADD, "iadd": ir.ATOMIC_OP.ADD, "and": ir.ATOMIC_OP.AND, "or": ir.ATOMIC_OP.OR, "xor": + ir.ATOMIC_OP.XOR, "xchg": ir.ATOMIC_OP.XCHG +} + + +def _verify_buffer_ops(ptr, offsets, mask=None, other=None): + assert ptr.type.is_ptr(), "ptr must be a scalar pointer type" + + assert isinstance(offsets.type, ttgl.distributed_type), "expected offsets type to be a distributed_type" + assert offsets.dtype.is_int32() or offsets.dtype.is_uint32(), "offsets element type must be int32 or uint32" + + if other is not None: + assert mask is not None, "when other is not None, mask should not be None" + + +def _verify_element_type_and_dispatch_op(op, elem_type, arch): + supported_types = [ + ttgl.float16, ttgl.float32, ttgl.bfloat16, ttgl.float64, ttgl.int32, ttgl.int64, ttgl.uint32, ttgl.uint64 + ] + assert elem_type in supported_types, f"{elem_type} is not supported in buffer atomic on {arch}." + + if op in ['and', 'or', 'xor', 'xchg']: + assert elem_type in [ttgl.int32, ttgl.int64], f"{op} with {elem_type} is not supported on CDNA3 or CDNA4" + return _atomic_op_str_to_op[_unwrap_if_constexpr(op)] + + if op in ['max', 'min']: + if elem_type in [ttgl.int32, ttgl.int64, ttgl.float64]: + op = 's' + op + return _atomic_op_str_to_op[_unwrap_if_constexpr(op)] + elif elem_type in [ttgl.uint32, ttgl.uint64]: + op = 'u' + op + return _atomic_op_str_to_op[_unwrap_if_constexpr(op)] + else: + raise ValueError(f"{op} with {elem_type} is not supported on CDNA3 and CDNA4") + + if op == 'add': + if elem_type in [ttgl.uint32, ttgl.uint64]: + op = 'i' + op + return _atomic_op_str_to_op[_unwrap_if_constexpr(op)] + elif elem_type in [ttgl.float16, ttgl.float32, ttgl.float64]: + op = 'f' + op + return _atomic_op_str_to_op[_unwrap_if_constexpr(op)] + elif elem_type is ttgl.bfloat16: + assert arch == "cdna4", "Buffer atomic fadd with bf16 is only supported on CDNA4 for now." + op = 'f' + op + return _atomic_op_str_to_op[_unwrap_if_constexpr(op)] + else: + raise ValueError(f"{op} with {elem_type} is not supported on CDNA3 and CDNA4") + + raise ValueError(f"Unknown {op} on CDNA3 or CDNA4") + + +def _buffer_atomic_rmw_impl(op, ptr, offsets, value, arch, mask, sem, scope, _semantic): + _verify_buffer_ops(ptr, offsets, mask) + + op = _verify_element_type_and_dispatch_op(op, ptr.type.scalar.element_ty, arch) + + mask = _unwrap_if_constexpr(mask) + if mask is not None: + mask = _semantic.to_tensor(mask) + mask = _semantic.cast(mask, ttgl.int1) + _, mask = _semantic.broadcast_impl_value(offsets, mask) + mask = mask.handle if mask is not None else ir.value() + + value = _unwrap_if_constexpr(value) + value = _semantic.to_tensor(value) + _, value = _semantic.broadcast_impl_value(offsets, value) + + sem = _semantic._str_to_sem(sem) + scope = _semantic._str_to_scope(scope) + return _semantic.tensor( + _semantic.builder.create_buffer_atomic_rmw(op, ptr.handle, offsets.handle, value.handle, sem, scope, mask), + value.type) + + +@builtin +def buffer_load(ptr, offsets, mask=None, other=None, cache=None, _semantic=None): + """ + AMD buffer load from global memory via a scalar base pointer and a tensor of + offsets instead of a tensor of pointers. This operation will load data + directly into registers. + + Args: + ptr (pointer to scalar): Global memory scalar base pointer to load from. + offsets (tensor): Offsets tensor for the load operation. + mask (tensor, optional): Mask tensor for predicated loads. Defaults to None. + other (tensor or scalar, optional): Tensor or scalar providing default values for masked elements. Defaults to None. + cache_modifier (str): Cache modifier specifier. Defaults to "". + """ + _verify_buffer_ops(ptr, offsets, mask, other) + + mask = _unwrap_if_constexpr(mask) + if mask is not None: + offsets, mask = _semantic.broadcast_impl_value(offsets, mask) + + other = _unwrap_if_constexpr(other) + if other is not None: + other = _semantic.to_tensor(other) + other = _semantic.cast(other, ptr.dtype.element_ty) + offsets, other = _semantic.broadcast_impl_value(offsets, other) + + other = other.handle if other is not None else ir.value() + mask = mask.handle if mask is not None else ir.value() + cache_modifier = _semantic._str_to_load_cache_modifier(cache) if cache is not None else ir.CACHE_MODIFIER.NONE + + ret_ty = offsets.type.with_element_ty(ptr.type.scalar.element_ty) + builder = _semantic.builder + handle = builder.create_buffer_load(ret_ty.to_ir(builder), ptr.handle, offsets.handle, mask, other, cache_modifier) + return ttgl.tensor(handle, ret_ty) + + +@builtin +def buffer_store(stored_value, ptr, offsets, mask=None, cache=None, _semantic: GluonSemantic = None): + """ + AMD buffer store a tensor directly to global memory via a scalar base pointer and a tensor of + offsets instead of a tensor of pointers. + Args: + stored_value (tensor to be stored): The tensor to be stored to global memory. + ptr (pointer to scalar): Global memory scalar base pointer to store to. + offsets (tensor): Offsets tensor for the store operation. + mask (tensor, optional): Mask tensor for predicated store. Defaults to None. + cache_modifier (str): Cache modifier specifier. Defaults to "". + """ + _verify_buffer_ops(ptr, offsets, mask) + + if mask is not None: + offsets, mask = _semantic.broadcast_impl_value(offsets, mask) + + mask = mask.handle if mask is not None else ir.value() + cache_modifier = _semantic._str_to_store_cache_modifier(cache) if cache is not None else ir.CACHE_MODIFIER.NONE + + _semantic.builder.create_buffer_store(stored_value.handle, ptr.handle, offsets.handle, mask, cache_modifier) + + +@builtin +def mfma(a, b, acc, _semantic: GluonSemantic = None): + """ + Computes matrix-multiplication of a * b + acc using AMD native matrix core units. + Args: + a (tensor): The first operand of mfma. + b (tensor): The second operand of mfma. + acc (tensor): The accumulator tensor. + """ + assert acc is not None, "acc is required" + ret_type = acc.type + acc = ttgl._unwrap_if_constexpr(acc) + + handle = _semantic.dot(a, b, acc, input_precision=knobs.language.fp32_default, max_num_imprecise_acc=None, + out_dtype=acc.dtype).handle + return ttgl.tensor(handle, ret_type) + + +""" +AMD Buffer Atomic RMW operations. +The supported operatios are max, min, add, and, or, xor, xchg. +Similar to normal atomic ops: it loads data at ptr plus offsets, do `op` with `value`, and store result to `ptr` plus `offsets` with +the specified memory semantics and scope. + +Buffer atomics access global memory via a scalar base pointer and a tensor of offsets instead of a tensor of pointers. +Similar to other buffer ops, the `mask` is a boolean vector that determines if a given element should be processed with +the atomic RMW op. Elements with `mask[i] == 0` are dropped (i.e., the atomic is not executed). + +Buffer Atomic RMW ops return the pre-op value in the global memory. + +Args: + ptr (pointer to scalar): Global memory scalar base pointer to load from. + offsets (tensor): Offsets tensor for the load operation. + value (tensor): Another operand of `op`. + mask (tensor, optional): Mask tensor for predicated loads. Defaults to None. + sem (str, optional): Memory Semantic Descriptor. Default is None which means acq_rel memory semantic. + scope (str, optional): Memory Sync Scope for atomic accesses. Default is None and it will be mapped to `gpu`, which is called `agent` for AMDGPU. Please ref https://llvm.org/docs/AMDGPUUsage.html#memory-model-gfx942 for details. +""" + + +@builtin +def buffer_atomic_max(ptr, offsets, value, mask=None, sem=None, scope=None, _semantic=None): + return _buffer_atomic_rmw_impl('max', ptr, offsets, value, "cdna3", mask=mask, sem=sem, scope=scope, + _semantic=_semantic) + + +@builtin +def buffer_atomic_min(ptr, offsets, value, mask=None, sem=None, scope=None, _semantic=None): + + return _buffer_atomic_rmw_impl('min', ptr, offsets, value, "cdna3", mask=mask, sem=sem, scope=scope, + _semantic=_semantic) + + +@builtin +def buffer_atomic_add(ptr, offsets, value, mask=None, sem=None, scope=None, _semantic=None): + + return _buffer_atomic_rmw_impl('add', ptr, offsets, value, "cdna3", mask=mask, sem=sem, scope=scope, + _semantic=_semantic) + + +@builtin +def buffer_atomic_and(ptr, offsets, value, mask=None, sem=None, scope=None, _semantic=None): + + return _buffer_atomic_rmw_impl('and', ptr, offsets, value, "cdna3", mask=mask, sem=sem, scope=scope, + _semantic=_semantic) + + +@builtin +def buffer_atomic_or(ptr, offsets, value, mask=None, sem=None, scope=None, _semantic=None): + + return _buffer_atomic_rmw_impl('or', ptr, offsets, value, "cdna3", mask=mask, sem=sem, scope=scope, + _semantic=_semantic) + + +@builtin +def buffer_atomic_xor(ptr, offsets, value, mask=None, sem=None, scope=None, _semantic=None): + + return _buffer_atomic_rmw_impl('xor', ptr, offsets, value, "cdna3", mask=mask, sem=sem, scope=scope, + _semantic=_semantic) + + +@builtin +def buffer_atomic_xchg(ptr, offsets, value, mask=None, sem=None, scope=None, _semantic=None): + + return _buffer_atomic_rmw_impl('xchg', ptr, offsets, value, "cdna3", mask=mask, sem=sem, scope=scope, + _semantic=_semantic) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/amd/cdna4/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/amd/cdna4/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4ba53d2ed0b1f34f3a464c261fd09d9ecdbb057d --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/amd/cdna4/__init__.py @@ -0,0 +1,130 @@ +from triton.runtime.jit import constexpr_function +from triton._C.libtriton.gluon_ir import get_amd_mfma_scale_layout as _get_mfma_scale_layout + +from ..._core import builtin +from ..._layouts import DotOperandLayout +from .._layouts import AMDMFMALayout +from .._ops import _mma_scaled +from ..cdna3 import _buffer_atomic_rmw_impl +from ..cdna3 import * # NOQA: F403 +from ..cdna3 import __all__ as __cdna3_all +from . import async_copy + +__all__ = [*__cdna3_all, "async_copy", "mfma_scaled", "get_mfma_scale_layout"] + + +@builtin +def mfma_scaled(a, a_scale, a_format, b, b_scale, b_format, acc, _semantic=None): + """ + AMD Scaled MFMA operation. + + ``` + c = a * a_scale @ b * b_scale + acc + ``` + + `a` and `b` use microscaling formats described in + "OCP Microscaling Formats (MX) Specification": + https://www.opencompute.org/documents/ocp-microscaling-formats-mx-v1-0-spec-final-pdf. + Currently supported only on CDNA4 hardware. + + Args: + a (tensor): The operand A to be multiplied. + a_scale (Optional[tensor]): Scale factor for operand A. + a_format (str): Format of the operand A. Available formats: `e2m1`, `e4m3`, `e5m2`. + b (tensor): The operand B to be multiplied. + b_scale (Optional[tensor]): Scale factor for operand B. + b_format (str): Format of the operand B. Available formats: `e2m1`, `e4m3`, `e5m2`. + acc (tensor): Accumulator tensor. + """ + layout = acc.type.layout + assert isinstance(layout, AMDMFMALayout), "Expected layout to be an instance of AMDMFMALayout" + assert (isinstance(a.type.layout, DotOperandLayout) and a.type.layout.parent== layout), \ + "Expected lhs layout to be a DotOperandLayout with parent matching MFMA layout" + assert (isinstance(b.type.layout, DotOperandLayout) and b.type.layout.parent == layout), \ + "Expected rhs layout to be a DotOperandLayout with parent matching MFMA layout" + + assert a_format.value in {"e2m1", "e4m3", "e5m2"}, f"Unsupported lhs_format: {a_format.value}" + assert b_format.value in {"e2m1", "e4m3", "e5m2"}, f"Unsupported rhs_format: {b_format.value}" + + return _mma_scaled(a, a_scale, a_format, b, b_scale, b_format, acc, get_mfma_scale_layout, _semantic) + + +def _get_mfma_scale_layout_impl(*args, **kwargs): + return _get_mfma_scale_layout(*args, **kwargs) + + +_get_mfma_scale_layout_impl.__triton_builtin__ = True + + +@constexpr_function +def get_mfma_scale_layout(dot_operand_layout, shape): + """ Get the scale layout for MFMA scaled operands. + + Args: + dot_operand_layout (DotOperandLayout): The dot operand layout. + shape (List[int]): The shape of the scale tensor. + + Return: + layout (DistributedLinearLayout): The scale layout. + """ + op_idx = dot_operand_layout.operand_index + parent = dot_operand_layout.parent + assert isinstance(parent, AMDMFMALayout), "Expected parent to be an instance of AMDMFMALayout" + mdim = parent.instr_shape[0] + tiles_per_warp = parent.tiles_per_warp + warps_per_cta = parent.warps_per_cta + return _get_mfma_scale_layout_impl(op_idx, shape, mdim, tiles_per_warp, warps_per_cta) + + +""" +buffer_atomic_rmw of cnda4 shares the same signature and functionalities as cdna3.buffer_atomic_rmw. +The cdna4 version additionally supports `fadd` with `bf16`. +""" + + +@builtin +def buffer_atomic_max(ptr, offsets, value, mask=None, sem=None, scope=None, _semantic=None): + return _buffer_atomic_rmw_impl('max', ptr, offsets, value, "cdna4", mask=mask, sem=sem, scope=scope, + _semantic=_semantic) + + +@builtin +def buffer_atomic_min(ptr, offsets, value, mask=None, sem=None, scope=None, _semantic=None): + + return _buffer_atomic_rmw_impl('min', ptr, offsets, value, "cdna4", mask=mask, sem=sem, scope=scope, + _semantic=_semantic) + + +@builtin +def buffer_atomic_add(ptr, offsets, value, mask=None, sem=None, scope=None, _semantic=None): + + return _buffer_atomic_rmw_impl('add', ptr, offsets, value, "cdna4", mask=mask, sem=sem, scope=scope, + _semantic=_semantic) + + +@builtin +def buffer_atomic_and(ptr, offsets, value, mask=None, sem=None, scope=None, _semantic=None): + + return _buffer_atomic_rmw_impl('and', ptr, offsets, value, "cdna4", mask=mask, sem=sem, scope=scope, + _semantic=_semantic) + + +@builtin +def buffer_atomic_or(ptr, offsets, value, mask=None, sem=None, scope=None, _semantic=None): + + return _buffer_atomic_rmw_impl('or', ptr, offsets, value, "cdna4", mask=mask, sem=sem, scope=scope, + _semantic=_semantic) + + +@builtin +def buffer_atomic_xor(ptr, offsets, value, mask=None, sem=None, scope=None, _semantic=None): + + return _buffer_atomic_rmw_impl('xor', ptr, offsets, value, "cdna4", mask=mask, sem=sem, scope=scope, + _semantic=_semantic) + + +@builtin +def buffer_atomic_xchg(ptr, offsets, value, mask=None, sem=None, scope=None, _semantic=None): + + return _buffer_atomic_rmw_impl('xchg', ptr, offsets, value, "cdna4", mask=mask, sem=sem, scope=scope, + _semantic=_semantic) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/amd/cdna4/async_copy.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/amd/cdna4/async_copy.py new file mode 100644 index 0000000000000000000000000000000000000000..009707c77924dba04bc2418cc536e67b5486bd21 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/amd/cdna4/async_copy.py @@ -0,0 +1,170 @@ +from ..._core import ir, builtin, _unwrap_if_constexpr +from ..._semantic import _check +from ..._layouts import BlockedLayout, SliceLayout +from ..cdna3 import _verify_buffer_ops + +__all__ = [ + "global_load_to_shared", + "buffer_load_to_shared", + "commit_group", + "wait_group", + "load_shared_relaxed", +] + + +@builtin +def global_load_to_shared(dest, ptr, mask=None, other=None, cache_modifier="", _semantic=None): + """ + AMD global load to shared operation. This operation loads data directly + from global memory to shared memory without going through registers. It + happens asynchronously and requires a subsequent `async_wait` to ensure the + data is available in shared memory. Note that this operation does still + complete in order with ttgl.loads/stores or buffer_loads/stores on CDNA4, + so interleaving with them will hurt performance. + + Compared to `buffer_load_to_shared`, it requires a tensor pointer which + supports 64-bit indexing range for each thread in a block, which gives more + flexibility, but at the cost of higher register pressure and no hardware + out-of-bound masking support. Prefer to use `buffer_load_to_shared` when + possible for better performance. + + The underlying hardware instruction uses separate registers for global + memory address for each thread but the same register for local memory + address for the whole warp. Therefore, while using this operation + the following conditions must be met or lowering to LLVM will fail: + + - For the `ptr` layout, size per thread * bits per element must be 128 or 32. + To get ideal performance, it is recommended to use 128 bits per element. + - Writes to `dest` must be coalesced. + - If `dest` is swizzled, it only can be swizzled within warp boundary. + + Args: + dest (shared_memory_descriptor): Destination shared memory descriptor. + ptr (pointer tensor): Tensor of pointers to global memory to load from. + mask (tensor, optional): Mask tensor for predicated loads. Defaults to None. + other (tensor or scalar, optional): Tensor or scalar providing default values for masked elements. Defaults to None. + cache_modifier (str): Cache modifier specifier. Defaults to "". + """ + _check(ptr.type.is_block(), lambda: "expected ptr to be a tensor") + _check(isinstance(ptr.type.layout, (BlockedLayout, SliceLayout)), + lambda: "expected ptr type layout to be BlockedLayout or SliceLayout") + _check( + dest.shape == ptr.shape, lambda: + f"expected dest shape to match pointer shape but got dest.shape = {dest.shape}, pointer.shape = {ptr.shape}") + + mask = _unwrap_if_constexpr(mask) + if mask is not None: + ptr, mask = _semantic.broadcast_impl_value(ptr, mask) + other = _unwrap_if_constexpr(other) + if other is not None: + other = _semantic.to_tensor(other) + other = _semantic.cast(other, ptr.dtype.element_ty) + ptr, other = _semantic.broadcast_impl_value(ptr, other) + + cache_modifier = _semantic._str_to_load_cache_modifier(cache_modifier) + mask_handle = mask.handle if mask is not None else ir.value() + other_handle = other.handle if other is not None else ir.value() + _semantic.builder.create_async_copy_global_to_local(dest.handle, ptr.handle, mask_handle, other_handle, + cache_modifier, ir.EVICTION_POLICY.NORMAL, False) + + +@builtin +def buffer_load_to_shared(dest, ptr, offsets, mask=None, other=None, cache_modifier="", _semantic=None): + """ + AMD buffer load to shared operation. Buffer load is similar to global load + but it accesses global memory via a scalar base pointer and a tensor of + 32-bit offsets instead of a tensor of pointers. This operation loads data + directly from global memory to shared memory without going through + registers. It happens asynchronously and requires a subsequent `async_wait` + to ensure thedata is available in shared memory. Note that this operation + does still complete in order with ttgl.loads/stores or buffer_loads/stores + on CDNA4, so interleaving with them will hurt performance. + + Compared to `global_load_to_shared`, it has better performance and also + supports hardware out-of-bound masking. But it strictly requires a + 32-bit offset instead of a 64-bit tensor pointer. + + The underlying hardware instruction uses separate registers for global + memory address for each thread but the same register for local memory + address for the whole warp. Therefore, while using this operation + the following conditions must be met or lowering to LLVM will fail: + + - For the `offsets` layout, size per thread * bits per element must be 128 or 32. + To get ideal performance, it is recommended to use 128 bits per element. + - Writes to `dest` must be coalesced. + - If `dest` is swizzled, it only can be swizzled within warp boundary. + + Args: + dest (shared_memory_descriptor): Destination shared memory descriptor. + ptr (pointer to scalar): Global memory scalar base pointer to load from. + offsets (tensor): Offsets tensor for the load operation. + mask (tensor, optional): Mask tensor for predicated loads. Defaults to None. + other (tensor or scalar, optional): Tensor or scalar providing default values for masked elements. Defaults to None. + cache_modifier (str): Cache modifier specifier. Defaults to "". + """ + _check(isinstance(offsets.type.layout, (BlockedLayout, SliceLayout)), + lambda: "expected offsets type layout to be BlockedLayout or SliceLayout") + _verify_buffer_ops(ptr, offsets, mask, other) + + mask = _unwrap_if_constexpr(mask) + if mask is not None: + offsets, mask = _semantic.broadcast_impl_value(offsets, mask) + other = _unwrap_if_constexpr(other) + if other is not None: + other = _semantic.to_tensor(other) + other = _semantic.cast(other, ptr.type.scalar.element_ty) + offsets, other = _semantic.broadcast_impl_value(offsets, other) + + mask = mask.handle if mask is not None else ir.value() + other = other.handle if other is not None else ir.value() + stride = ir.value() + cache_modifier = _semantic._str_to_load_cache_modifier(cache_modifier) + + _semantic.builder.create_buffer_load_to_local(dest.handle, ptr.handle, offsets.handle, mask, other, stride, + cache_modifier) + + +@builtin +def commit_group(_semantic=None): + """ + Commit oustanding async operations. + + This finalizes a set of async copy operations which can be waited upon via `wait_group`. + """ + _semantic.builder.create_async_commit_group() + + +@builtin +def wait_group(num_outstanding=0, _semantic=None): + """ + Wait for outstanding commit groups. It will block until the number of + outstanding commit groups is less than or equal to `num_outstanding`. Note that uncommited + async operations will be waited upon even if `num_outstanding` is 0. + + Args: + num_outstanding (int): The number of outstanding commit groups to wait for. Defaults to 0. + """ + num_outstanding = _unwrap_if_constexpr(num_outstanding) + _semantic.builder.create_async_wait_group(num_outstanding) + + +@builtin +def load_shared_relaxed(smem, layout, _semantic=None): + """ + Load a tensor from shared memory with extra hints for the underlying + compiler to avoid emitting unnecessary waits before loading from the target + shared memory. + + Args: + smem (shared_memory_descriptor): Shared memory descriptor to load from. + layout (DistributedLayout): The destination layout of the tensor. + + Returns: + tensor: A Gluon tensor containing the loaded data. + """ + SYNCED_VIA_WAIT_ATTR_NAME = "ttg.amdg.syncedViaAsyncWait" + + layout = _unwrap_if_constexpr(layout) + ret = _semantic.shared_load(smem, layout) + ret.handle.set_attr(SYNCED_VIA_WAIT_ATTR_NAME, _semantic.builder.get_bool_attr(True)) + return ret diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/amd/gfx1250/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/amd/gfx1250/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8c32f877f590e6821a5fec381c8c55ece8ccbc54 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/amd/gfx1250/__init__.py @@ -0,0 +1,96 @@ +from triton.runtime.jit import constexpr_function +from triton._C.libtriton.gluon_ir import get_amd_wmma_scale_layout as _get_wmma_scale_layout + +from ..._core import builtin +from .._ops import _wmma, _verify_wmma, _mma_scaled +from .._layouts import AMDWMMALayout +from ..cdna3 import buffer_load, buffer_store +from . import tdm +from . import async_copy +from . import mbarrier + +__all__ = [ + "async_copy", "tdm", "mbarrier", "wmma", "wmma_scaled", "buffer_load", "buffer_store", "get_wmma_scale_layout" +] + + +@builtin +def wmma(a, b, acc, _semantic=None): + """ + Computes matrix-multiplication of a * b + acc using AMD WMMA instruction. + + Args: + a (tensor): The operand a to be multiplied. + b (tensor): The operand b to be multiplied. + acc (tensor): The accumulator tensor. + """ + return _wmma(3, a, b, acc, _semantic) + + +@builtin +def wmma_scaled(a, a_scale, a_format, b, b_scale, b_format, acc, _semantic=None): + """ + AMD Scaled WMMA operation. + + ``` + c = a * a_scale @ b * b_scale + acc + ``` + + `a` and `b` use microscaling formats described in + "OCP Microscaling Formats (MX) Specification": + https://www.opencompute.org/documents/ocp-microscaling-formats-mx-v1-0-spec-final-pdf. + + Args: + a (tensor): The operand A to be multiplied. + a_scale (Optional[tensor]): Scale factor for operand A. + a_format (str): Format of the operand A. Available formats: `e2m1`, `e4m3`, `e5m2`. + b (tensor): The operand B to be multiplied. + b_scale (Optional[tensor]): Scale factor for operand B. + b_format (str): Format of the operand B. Available formats: `e2m1`, `e4m3`, `e5m2`. + acc (tensor): Accumulator tensor. + """ + _verify_wmma(3, a, b, acc) + if a_format.value == "e2m1": + wmma_layout = a.type.layout.parent + assert isinstance(wmma_layout, AMDWMMALayout) and wmma_layout.instr_shape == [16, 16, 64], \ + "e2m1 format expects instr_shape to be [16, 16, 64]" + if b_format.value == "e2m1": + wmma_layout = b.type.layout.parent + assert isinstance(wmma_layout, AMDWMMALayout) and wmma_layout.instr_shape == [16, 16, 64], \ + "e2m1 format expects instr_shape to be [16, 16, 64]" + + acc_layout = acc.type.layout + assert isinstance(acc_layout, AMDWMMALayout) and acc_layout.instr_shape == [16, 16, 128], \ + "accumulator tensor's layout must be [16, 16, 128]" + + assert a_format.value in {"e2m1", "e4m3", "e5m2"}, f"Unsupported lhs_format: {a_format.value}" + assert b_format.value in {"e2m1", "e4m3", "e5m2"}, f"Unsupported rhs_format: {b_format.value}" + + return _mma_scaled(a, a_scale, a_format, b, b_scale, b_format, acc, get_wmma_scale_layout, _semantic) + + +def _get_wmma_scale_layout_impl(*args, **kwargs): + return _get_wmma_scale_layout(*args, **kwargs) + + +_get_wmma_scale_layout_impl.__triton_builtin__ = True + + +@constexpr_function +def get_wmma_scale_layout(dot_operand_layout, shape): + """ Get the scale layout for WMMA scaled operands. + + Args: + dot_operand_layout (DotOperandLayout): The dot operand layout. + shape (List[int]): The shape of the scale tensor. + + Return: + layout (DistributedLinearLayout): The scale layout. + """ + op_idx = dot_operand_layout.operand_index + parent = dot_operand_layout.parent + assert isinstance(parent, AMDWMMALayout), "Expected parent to be an instance of AMDMFMALayout" + mdim = parent.instr_shape[0] + tiles_per_warp = parent.tiles_per_warp + warps_per_cta = parent.warps_per_cta + return _get_wmma_scale_layout_impl(op_idx, shape, mdim, tiles_per_warp, warps_per_cta) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/amd/gfx1250/async_copy.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/amd/gfx1250/async_copy.py new file mode 100644 index 0000000000000000000000000000000000000000..cfba91356bb1fefc7760608716954f3b0a2d83a3 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/amd/gfx1250/async_copy.py @@ -0,0 +1,51 @@ +from ..._core import ir, builtin, _unwrap_if_constexpr +from ..._semantic import _check +from triton.experimental.gluon.language._layouts import DistributedLayout +from ..cdna4.async_copy import commit_group, wait_group + +__all__ = ["global_to_shared", "commit_group", "wait_group", "mbarrier_arrive"] + + +@builtin +def global_to_shared(smem, pointer, mask=None, other=None, cache_modifier="", _semantic=None): + """ + Asynchronously copy elements from global memory to shared memory. Requires manual syncronization via `wait_group` before accessing the loaded data. + + Args: + smem (shared_memory_descriptor): Destination shared memory descriptor. + pointer (tensor): Source pointer tensor. + mask (tensor, optional): Mask tensor for predicated loads. Defaults to None. + other (tensor or scalar, optional): Tensor or scalar providing default values for masked elements. Defaults to None(0). + cache_modifier (str): Cache modifier specifier. Defaults to "". + eviction_policy (str): Eviction policy specifier. Defaults to "". + """ + _check(pointer.type.is_block(), lambda: "expected ptr to be a tensor") + _check(isinstance(pointer.type.layout, DistributedLayout), + lambda: "expected ptr type layout to be BlockedLayout or SliceLayout") + _check( + smem.shape == pointer.shape, lambda: + f"expected smem shape to match pointer shape but got smem.shape = {smem.shape}, pointer.shape = {pointer.shape}" + ) + mask = _unwrap_if_constexpr(mask) + if mask is not None: + pointer, mask = _semantic.broadcast_impl_value(pointer, mask) + other = _unwrap_if_constexpr(other) + if other is not None: + other = _semantic.to_tensor(other) + other = _semantic.cast(other, pointer.dtype.element_ty) + pointer, other = _semantic.broadcast_impl_value(pointer, other) + cache_modifier = _semantic._str_to_load_cache_modifier(cache_modifier) + mask_handle = mask.handle if mask is not None else ir.value() + other_handle = other.handle if other is not None else ir.value() + _semantic.builder.create_async_copy_global_to_local(smem.handle, pointer.handle, mask_handle, other_handle, + cache_modifier, ir.EVICTION_POLICY.NORMAL, False) + + +@builtin +def mbarrier_arrive(mbarrier, _semantic=None): + """ + Arrive on the mbarrier once all outstanding async copies are complete. + Args: + mbarrier (shared_memory_descriptor): Barrier object to arrive on. + """ + _semantic.builder.create_async_copy_lds_barrier_arrive(mbarrier.handle) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/amd/gfx1250/mbarrier.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/amd/gfx1250/mbarrier.py new file mode 100644 index 0000000000000000000000000000000000000000..f69d3005fbbd727c79ce1321c433e8fc1fabcff7 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/amd/gfx1250/mbarrier.py @@ -0,0 +1,67 @@ +import triton.experimental.gluon.language._core as ttgl +from triton.experimental.gluon.language._layouts import SwizzledSharedLayout +from triton.experimental.gluon.language._core import builtin, _unwrap_if_constexpr + +__all__ = ["MBarrierLayout", "init", "wait", "arrive"] + + +class MBarrierLayout(SwizzledSharedLayout): + """ + Layout for mbarrier synchronization. + + Args: + cga_layout (List[List[int]]): CTA layout bases. Defaults to []. + """ + + def __init__(self, cga_layout=None): + super().__init__(vec=1, per_phase=1, max_phase=1, order=[0], cga_layout=cga_layout or []) + + +@builtin +def init(mbarrier, count, _semantic=None): + """ + Initialize an mbarrier with a specified count. An mbarrier consists of an init count, a pending count and a phase. + At initialization, the init count and pending count are initialized with the given 'count' and the phase is initialized to 0. + + Args: + mbarrier (shared_memory_descriptor): The barrier object to initialize. + count (int): The initial count for the barrier. Must be a positive integer. + """ + count = _unwrap_if_constexpr(count) + _semantic.builder.create_lds_barrier_init(mbarrier.handle, count) + + +@builtin +def wait(mbarrier, phase, _semantic=None): + """ + Wait until the mbarrier's phase differs from the provided phase value. + This means that the given 'phase' has completed. + + Args: + mbarrier (shared_memory_descriptor): The barrier object to wait on. + phase (int): The phase value to compare against. The wait completes when + the barrier's phase becomes different from this value. + """ + phase = _semantic.to_tensor(phase) + + _semantic.builder.create_lds_barrier_wait(mbarrier.handle, phase.handle) + + +@builtin +def arrive(mbarrier, *, count=1, _semantic=None): + """ + Arrive at an mbarrier with a specified count. The operation requires a `count` attribute + of at least 1, and decreases the pending arrival count of the mbarrier by the specific count. + If the pending count reaches zero, the phase changes (is decremented in a wraparound manner) and the + pending count is reloaded with the init count value. Returns the mbarrier's phase prior to the "arrive" operation. + + Args: + mbarrier (shared_memory_descriptor): Barrier to be signalled. + count (int): Count to arrive with. Defaults to 1. + + Returns: + prior phase (int): phase of mbarrier, prior to "arrive" operation. + """ + count = _unwrap_if_constexpr(count) + handle = _semantic.builder.create_lds_barrier_arrive(mbarrier.handle, count) + return ttgl.tensor(handle, ttgl.int32) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/amd/gfx1250/tdm.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/amd/gfx1250/tdm.py new file mode 100644 index 0000000000000000000000000000000000000000..b7ec8b04a22bbd4df8f9aee392dbec01ddd4bc60 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/amd/gfx1250/tdm.py @@ -0,0 +1,171 @@ +from __future__ import annotations +from typing import List, Tuple, TYPE_CHECKING +from dataclasses import dataclass + +import triton.experimental.gluon.language._core as ttgl +from triton.experimental.gluon.language._layouts import PaddedSharedLayout, SwizzledSharedLayout +from triton.experimental.gluon.language._core import builtin, _unwrap_if_constexpr + +if TYPE_CHECKING: + from triton._C import ir + from triton.experimental.gluon.language._core import shared_memory_descriptor + +__all__ = ["async_load", "async_wait", "make_tensor_descriptor", "tensor_descriptor", "tensor_descriptor_type"] + + +@dataclass(eq=True) +class tensor_descriptor_type(ttgl.base_type): + """The type for a tensor descriptor.""" + + block_type: ttgl.block_type + shape_type: ttgl.tuple_type + strides_type: ttgl.tuple_type + layout: PaddedSharedLayout | SwizzledSharedLayout + + def __str__(self) -> str: + return f"tensor_descriptor<{self.block_type}, {self.layout}>" + + def _unflatten_ir(self, handles: List[ir.value], cursor: int) -> Tuple[tensor_descriptor, int]: + handle = handles[cursor] + cursor += 1 + shape, cursor = self.shape_type._unflatten_ir(handles, cursor) + strides, cursor = self.strides_type._unflatten_ir(handles, cursor) + value = tensor_descriptor(handle, shape, strides, self) + return value, cursor + + def _to_ir(self, builder: ir.builder) -> ir.type: + is_signed = self.block_type.element_ty.is_int_signed() + return builder.get_tensor_descriptor_layout_type( + self.block_type.to_ir(builder), + is_signed, + self.layout._to_ir(builder), + ) + + def _flatten_ir_types(self, builder: ir.builder, out: List[ir.type]) -> None: + out.append(self._to_ir(builder)) + self.shape_type._flatten_ir_types(builder, out) + self.strides_type._flatten_ir_types(builder, out) + + def mangle(self) -> str: + return f"TD{self.block_type.mangle()}_{self.shape_type.mangle()}_{self.strides_type.mangle()}_{self.layout.mangle()}TD" + + +@dataclass +class tensor_descriptor(ttgl.base_value): + """A descriptor representing a tensor in global memory.""" + + handle: ir.value + shape: ttgl.tuple + strides: ttgl.tuple + type: tensor_descriptor_type + + def _flatten_ir(self, handles: List[ir.value]) -> None: + handles.append(self.handle) + self.shape._flatten_ir(handles) + self.strides._flatten_ir(handles) + + @property + def block_type(self): + return self.type.block_type + + @property + def block_shape(self): + return self.type.block_type.shape + + @property + def dtype(self): + return self.type.block_type.element_ty + + @property + def layout(self): + return self.type.layout + + +@builtin +def make_tensor_descriptor(base: ttgl.tensor, shape: List[ttgl.constexpr | ttgl.tensor], + strides: List[ttgl.constexpr | ttgl.tensor], block_shape: List[ttgl.constexpr], + layout: PaddedSharedLayout | SwizzledSharedLayout, _semantic=None) -> tensor_descriptor: + """Make a tensor descriptor object. + + Args: + base (tensor): base pointer of the tensor in global memory. + shape (List[int]): shape of the tensor. + strides (List[int]): strides of the tensor. + block_shape (List[int]): block shape of the tensor. + layout (PaddedSharedLayout | SwizzledSharedLayout): the layout of the tensor in shared memory. + + Returns: + tensor_descriptor: the created tensor descriptor object + """ + ndim = len(shape) + assert 1 <= ndim <= 5, f"Expected 1 <= ndim <= 5 but got {ndim} dimensions" + assert len(strides) == ndim, f"Expected {ndim} strides but got {len(strides)}" + assert len(block_shape) == ndim, f"Expected block_shape to have {ndim} dimensions but got {len(strides)}" + assert isinstance(base.dtype, ttgl.pointer_type), "Expected base to be a pointer" + + layout = _unwrap_if_constexpr(layout) + assert isinstance(layout, (PaddedSharedLayout, SwizzledSharedLayout)), \ + "Expected layout to be a PaddedSharedLayout or SwizzledSharedLayout" + if isinstance(layout, SwizzledSharedLayout): + assert layout.max_phase == 1, "Expected max_phase to be 1 for SwizzledSharedLayout" + + base_handle = base.handle + shape_handles = _semantic._convert_to_ir_values(shape, require_i64=False) # i32 shape + stride_handles = _semantic._convert_to_ir_values(strides, require_i64=True) # i64 stride + + shape = ttgl.tuple(shape) + strides = ttgl.tuple(strides) + block_type = ttgl.block_type(base.type.element_ty, block_shape) + type = tensor_descriptor_type(block_type, shape.type, strides.type, layout) + + padding = _semantic._str_to_padding_option("zero") + handle = _semantic.builder.create_make_tensor_descriptor(type._to_ir(_semantic.builder), base_handle, shape_handles, + stride_handles, padding) + + return tensor_descriptor(handle, shape, strides, type) + + +@builtin +def async_load(src: tensor_descriptor, offsets: List[ttgl.constexpr | ttgl.tensor], dest: shared_memory_descriptor, + pred: bool = True, mbarrier: shared_memory_descriptor = None, _semantic=None) -> None: + """Load a block of tensor specified in tensor descriptor from global memory to shared memory asynchronously. + + Args: + src (tensor_descriptor): the source tensor descriptor. + offsets (List[int]): the offsets from the base pointer in the tensor descriptor. + dest (shared_memory_descriptor): the shared memory destination to store the loaded data. + pred (bool, optional): Predicate to enable or disable the load. Defaults to True. + mbarrier (shared_memory_descriptor, optional): The barrier object to signal "arrive" on. + """ + offset_handles = _semantic._convert_to_ir_values(offsets, require_i64=False) + pred = _semantic.to_tensor(pred) + pred_handle = pred.handle + mbarrier = _unwrap_if_constexpr(mbarrier) + mbarrier_handle = mbarrier.handle if mbarrier is not None else ttgl.ir.value() + _semantic.builder.create_async_tdm_copy_global_to_local(src.handle, offset_handles, dest.handle, pred_handle, + mbarrier_handle) + + +@builtin +def async_store(dest: tensor_descriptor, offsets: List[ttgl.constexpr | ttgl.tensor], src: shared_memory_descriptor, + _semantic=None) -> None: + """Store a block of tensor specified in tensor descriptor from shared memory to global memory asynchronously. + + Args: + dest (tensor_descriptor): the destination tensor descriptor. + offsets (List[int]): the offsets from the base pointer in the tensor descriptor. + src (shared_memory_descriptor): the shared memory source to load the data. + """ + offset_handles = _semantic._convert_to_ir_values(offsets, require_i64=False) + _semantic.builder.create_async_tdm_copy_local_to_global(dest.handle, offset_handles, src.handle) + + +@builtin +def async_wait(num_outstanding=0, _semantic=None) -> None: + """Wait for the outstanding asynchronous tensor operations to complete. + + Args: + num_outstanding (int): number of outstanding async tensor operations to wait for. + """ + num_outstanding = _unwrap_if_constexpr(num_outstanding) + _semantic.builder.create_async_tdm_wait(num_outstanding) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/amd/rdna3/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/amd/rdna3/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d4359442167982bd9c1d49324c3756a39b7f3920 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/amd/rdna3/__init__.py @@ -0,0 +1,17 @@ +from ..._core import builtin +from .._ops import _wmma + +__all__ = ["wmma"] + + +@builtin +def wmma(a, b, acc, _semantic=None): + """ + Computes matrix-multiplication of a * b + acc using AMD WMMA instruction. + + Args: + a (tensor): The operand a to be multiplied. + b (tensor): The operand b to be multiplied. + acc (tensor): The accumulator tensor. + """ + return _wmma(1, a, b, acc, _semantic) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/amd/rdna4/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/amd/rdna4/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..59e3e169bd727ad67ced467fd778bba2b9947093 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/amd/rdna4/__init__.py @@ -0,0 +1,17 @@ +from ..._core import builtin +from .._ops import _wmma + +__all__ = ["wmma"] + + +@builtin +def wmma(a, b, acc, _semantic=None): + """ + Computes matrix-multiplication of a * b + acc using AMD WMMA instruction. + + Args: + a (tensor): The operand a to be multiplied. + b (tensor): The operand b to be multiplied. + acc (tensor): The accumulator tensor. + """ + return _wmma(2, a, b, acc, _semantic) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/extra/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/extra/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2091e0b7e2afcd9fb914745dc64c35351d487f92 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/extra/__init__.py @@ -0,0 +1,3 @@ +from triton.language.extra import libdevice + +__all__ = ["libdevice"] diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/nvidia/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/nvidia/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3ecf36d3b950635111e792c62a48497ee621ae02 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/nvidia/__init__.py @@ -0,0 +1,4 @@ +from . import blackwell +from . import hopper + +__all__ = ["blackwell", "hopper"] diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/nvidia/ampere/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/nvidia/ampere/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..38b012f017bfef9be182d70b4e6fe768565bfc1e --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/nvidia/ampere/__init__.py @@ -0,0 +1,32 @@ +from __future__ import annotations + +from triton import knobs +from triton.experimental.gluon.language import _core as ttgl +from triton.experimental.gluon.language._layouts import DotOperandLayout, NVMMADistributedLayout +from ..._core import builtin, _unwrap_if_constexpr +from . import async_copy, mbarrier + +__all__ = ["async_copy", "mbarrier", "mma_v2"] + + +@builtin +def mma_v2(a, b, acc, input_precision=None, _semantic=None): + input_precision = _unwrap_if_constexpr(input_precision) + assert isinstance(a, ttgl.tensor), "a must be a tensor" + assert isinstance(b, ttgl.tensor), "b must be a tensor" + assert isinstance(acc, ttgl.tensor), "acc must be a tensor" + + mma_layout = acc.type.layout + assert isinstance(mma_layout, NVMMADistributedLayout), "acc must have an NVMMADistributedLayout" + assert mma_layout.version == [2, 0], "MMA layout must have version 2.0" + + assert isinstance(a.type.layout, DotOperandLayout), "a must have a DotOperandLayout" + assert isinstance(b.type.layout, DotOperandLayout), "b must have a DotOperandLayout" + assert a.type.layout.parent == mma_layout, "a's parent layout must be the same as acc's layout" + assert b.type.layout.parent == mma_layout, "b's parent layout must be the same as acc's layout" + assert a.type.layout.operand_index == 0, "a's operand index must be 0" + assert b.type.layout.operand_index == 1, "b's operand index must be 1" + + handle = _semantic.dot(a, b, acc, input_precision=input_precision, max_num_imprecise_acc=None, + out_dtype=acc.dtype).handle + return ttgl.tensor(handle, acc.type) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/nvidia/ampere/async_copy.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/nvidia/ampere/async_copy.py new file mode 100644 index 0000000000000000000000000000000000000000..b6752402bfda1f308724f9fc5a11d2ce2d010fa7 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/nvidia/ampere/async_copy.py @@ -0,0 +1,74 @@ +from ..._semantic import _check +from ..._core import _unwrap_if_constexpr, builtin +from triton._C.libtriton import ir + +__all__ = [ + "async_copy_global_to_shared", + "mbarrier_arrive", + "commit_group", + "wait_group", +] + + +@builtin +def async_copy_global_to_shared(smem, pointer, mask=None, cache_modifier="", eviction_policy="", volatile=False, + _semantic=None): + """ + Asynchronously copy elements from global memory to shared memory. + + Args: + smem (shared_memory_descriptor): Destination shared memory descriptor. + pointer (tensor): Source pointer tensor. + mask (tensor, optional): Mask tensor for predicated loads. Defaults to None. + cache_modifier (str): Cache modifier specifier. Defaults to "". + eviction_policy (str): Eviction policy specifier. Defaults to "". + volatile (bool): Whether the load is volatile. Defaults to False. + """ + mask = _unwrap_if_constexpr(mask) + cache_modifier = _semantic._str_to_load_cache_modifier(cache_modifier) + eviction_policy = _semantic._str_to_eviction_policy(eviction_policy) + volatile = _unwrap_if_constexpr(volatile) + if mask is not None: + pointer, mask = _semantic.broadcast_impl_value(pointer, mask) + _check( + smem.shape == pointer.shape, lambda: + f"expected smem shape to match pointer shape but got smem.shape = {smem.shape}, pointer.shape = {pointer.shape}" + ) + mask_handle = mask.handle if mask is not None else ir.value() + _semantic.builder.create_async_copy_global_to_local(smem.handle, pointer.handle, mask_handle, ir.value(), + cache_modifier, eviction_policy, volatile) + + +@builtin +def mbarrier_arrive(mbarrier, increment_count=True, _semantic=None): + """ + Arrive on the mbarrier once all outstanding async copies are complete. + + Args: + mbarrier (shared_memory_descriptor): Barrier object to arrive on. + increment_count (bool): Whether to increment the arrival count. Defaults to True. + """ + increment_count = _unwrap_if_constexpr(increment_count) + _semantic.builder.create_async_copy_mbarrier_arrive(mbarrier.handle, increment_count) + + +@builtin +def commit_group(_semantic=None): + """ + Commit the current asynchronous copy group. + + This finalizes a set of asynchronous copy operations. + """ + _semantic.builder.create_async_commit_group() + + +@builtin +def wait_group(num_outstanding=0, _semantic=None): + """ + Wait for outstanding asynchronous copy group operations. + + Args: + num_outstanding (int): Wait until `num_outstanding` or less async copy groups in-flight. Defaults to 0. + """ + num_outstanding = _unwrap_if_constexpr(num_outstanding) + _semantic.builder.create_async_wait_group(num_outstanding) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/nvidia/ampere/mbarrier.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/nvidia/ampere/mbarrier.py new file mode 100644 index 0000000000000000000000000000000000000000..8f7ac3457075255646f37a78fa22e656cf0ed769 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/nvidia/ampere/mbarrier.py @@ -0,0 +1,71 @@ +from triton.experimental.gluon.language._layouts import SwizzledSharedLayout +from triton.experimental.gluon.language._core import builtin, _unwrap_if_constexpr + +__all__ = ["arrive", "init", "invalidate", "MBarrierLayout", "wait"] + + +class MBarrierLayout(SwizzledSharedLayout): + """ + Layout for mbarrier synchronization in Ampere and later architectures. + + Args: + cga_layout (List[List[int]]): CTA layout bases. Defaults to []. + """ + + def __init__(self, cga_layout=None): + super().__init__(vec=1, per_phase=1, max_phase=1, order=[0], cga_layout=cga_layout or []) + + +@builtin +def init(mbarrier, count, _semantic=None): + """ + Initialize an mbarrier with a specified count. + + Args: + mbarrier (shared_memory_descriptor): The barrier object to initialize. + count (int): The initial count for the barrier. + """ + count = _unwrap_if_constexpr(count) + _semantic.builder.create_mbarrier_init(mbarrier.handle, count) + + +@builtin +def invalidate(mbarrier, _semantic=None): + """ + Invalidate an mbarrier, resetting its state. + + Args: + mbarrier (shared_memory_descriptor): The barrier object to invalidate. + """ + _semantic.builder.create_mbarrier_inval(mbarrier.handle) + + +@builtin +def wait(mbarrier, phase, pred=True, deps=(), _semantic=None): + """ + Wait until the mbarrier object completes its current phase. + + Args: + mbarrier (shared_memory_descriptor): The barrier object to wait on. + phase (int): The phase index to wait for. + pred (bool): Predicate. Operation is skipped if predicate is False. Defaults to True. + deps (Sequence[shared_memory_descriptor]): Dependent allocations barrier is waiting on. Used to track liveness of dependent allocations. Defaults to (). + """ + phase = _semantic.to_tensor(phase) + pred = _semantic.to_tensor(pred) + deps = [x.handle for x in deps] + _semantic.builder.create_mbarrier_wait(mbarrier.handle, phase.handle, pred.handle, deps) + + +@builtin +def arrive(mbarrier, *, pred=True, _semantic=None): + """ + Arrive on an mbarrier, signaling that a thread has reached the barrier. + + Args: + mbarrier (shared_memory_descriptor): The barrier object to arrive on. + pred (bool): Predicate. Operation is skipped if predicate is False. Defaults to True. + """ + count = 1 + pred = _semantic.to_tensor(pred) + _semantic.builder.create_mbarrier_arrive(mbarrier.handle, count, pred.handle) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/nvidia/blackwell/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/nvidia/blackwell/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6d1b21c011f15d374eac1a1a5bd894e15c1b0d1a --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/nvidia/blackwell/__init__.py @@ -0,0 +1,449 @@ +from __future__ import annotations +from typing import Optional, Tuple, List, TYPE_CHECKING + +from dataclasses import dataclass +from triton.runtime.jit import constexpr_function +from triton.experimental.gluon.language import _core as ttgl +from triton.experimental.gluon.language._core import builtin, base_type, base_value, _unwrap_if_constexpr +from triton.experimental.gluon.language._layouts import SharedLinearLayout +from triton.experimental.gluon.language._semantic import _check, _compute_tmem_reg_layout + +from . import tma +from ..hopper import fence_async_shared, mbarrier +from ..ampere import async_copy, mma_v2 + +from triton._C.libtriton import ir +if TYPE_CHECKING: + from triton._C.libtriton.gluon_ir import GluonOpBuilder + from ..._semantic import GluonSemantic + +__all__ = [ + "allocate_tensor_memory", + "async_copy", + "fence_async_shared", + "get_tmem_reg_layout", + "mbarrier", + "mma_v2", + "tensor_memory_descriptor", + "TensorMemoryLayout", + "tma", +] + + +@dataclass(frozen=True, eq=True) +class TensorMemoryLayout: + """ + Describes the layout for tensor memory in Blackwell architecture. + + Args: + block (Tuple[int, int]): Number of contiguous elements per row / column in a CTA. + col_stride (int): Number of 32-bit columns to advance between logically + adjacent columns. Packed layouts use a stride of 1. Unpacked + layouts use ``32 / bitwidth``. + cta_split_num (Optional[Tuple[int, int]]): CTA split factors. Defaults to None. + two_ctas (bool): Whether the layout is for two-CTA mode. Defaults to False. + """ + block: Tuple[int, int] + col_stride: int + cta_split_num: Optional[Tuple[int, int]] = None + two_ctas: bool = False + + def __post_init__(self): + super().__setattr__("block", _unwrap_if_constexpr(self.block)) + super().__setattr__("col_stride", _unwrap_if_constexpr(self.col_stride)) + super().__setattr__("cta_split_num", _unwrap_if_constexpr(self.cta_split_num)) + super().__setattr__("two_ctas", _unwrap_if_constexpr(self.two_ctas)) + assert len(self.block) == 2 + assert self.cta_split_num is None or len(self.cta_split_num) == 2 + assert self.col_stride >= 1 and (self.col_stride & + (self.col_stride - 1)) == 0, "tensor memory col_stride must be a power of two" + + def _to_ir(self, builder): + cta_split_num = list(self.cta_split_num) if self.cta_split_num else [1, 1] + return builder.get_tensor_memory_layout( + self.block, + self.col_stride, + cta_split_num, + self.two_ctas, + ) + + def mangle(self) -> str: + block_str = f"{self.block[0]}x{self.block[1]}" + stride_str = f"C{self.col_stride}" + cta_split_str = (f"CS{self.cta_split_num[0]}x{self.cta_split_num[1]}" if self.cta_split_num else "") + two_ctas_str = "2CT" if self.two_ctas else "" + return f"TL{block_str}{stride_str}{cta_split_str}{two_ctas_str}TL" + + def __hash__(self): + return hash((self.block, self.col_stride, self.cta_split_num, self.two_ctas)) + + +@dataclass(frozen=True, eq=True) +class TensorMemoryScalesLayout: + """ + Describes the layout for tensor memory scales in Blackwell architecture. + + Args: + cta_split_num (Optional[Tuple[int, int]]): CTA split factors. Defaults to None. + """ + cta_split_num: Optional[Tuple[int, int]] = None + + def __post_init__(self): + super().__setattr__("cta_split_num", _unwrap_if_constexpr(self.cta_split_num)) + assert self.cta_split_num is None or len(self.cta_split_num) == 2 + + def _to_ir(self, builder): + cta_split_num = list(self.cta_split_num) if self.cta_split_num else [1, 1] + return builder.get_tensor_memory_scales_layout(cta_split_num) + + def mangle(self) -> str: + cta_split_str = f"CS{self.cta_split_num[0]}x{self.cta_split_num[1]}" if self.cta_split_num else "" + return f"TLS{cta_split_str}TLS" + + def __hash__(self): + return hash(self.cta_split_num) + + +@constexpr_function +def get_tmem_reg_layout( + element_ty, + shape, + layout, + num_warps, + instr_variant="32x32b", + cga_layout=(), +): + """ + Returns a DistributedLinearLayout compatible with TMEM load/store instructions. + + Args: + element_ty (dtype): Element type stored in tensor memory. + shape (Sequence[int]): Global tensor shape addressed by the TMEM descriptor. + layout (TensorMemoryLayout): Tensor memory layout descriptor. + num_warps (int): Number of warps participating in the operation. + instr_variant (str): TMEM instruction variant (e.g. ``\"32x32b\"``). + cga_layout (Sequence[Sequence[int]]): CTA layout bases describing CTA distribution. + """ + + def _unwrap(x): + if isinstance(x, ttgl.constexpr): + return _unwrap(x.value) + if isinstance(x, list): + return [_unwrap(i) for i in x] + if isinstance(x, tuple): + return tuple(_unwrap(i) for i in x) + return x + + return _compute_tmem_reg_layout( + _unwrap(element_ty), + _unwrap(shape), + _unwrap(layout), + _unwrap(num_warps), + _unwrap(instr_variant), + _unwrap(cga_layout), + ) + + +class tensor_memory_descriptor_type(base_type): + + def __init__(self, element_ty, shape, layout, alloc_shape): + self.element_ty = element_ty + self.shape = shape + self.layout = layout + self.alloc_shape = alloc_shape + assert isinstance(layout, TensorMemoryLayout) or isinstance(layout, TensorMemoryScalesLayout) + + def to_ir(self, builder: GluonOpBuilder) -> None: + return builder.get_tensor_mem_desc_ty( + self.element_ty.to_ir(builder), + self.shape, + self.layout._to_ir(builder), + self.alloc_shape, + ) + + def _unflatten_ir(self, handles: List[ir.Value], cursor: int) -> Tuple[tensor_memory_descriptor, int]: + value = tensor_memory_descriptor(handles[cursor], self.element_ty, self.shape, self.layout, self.alloc_shape) + return value, cursor + 1 + + def _flatten_ir_types(self, builder: GluonOpBuilder, out: List[ir.type]) -> None: + out.append(self.to_ir(builder)) + + def __str__(self) -> str: + return f"tensor_memory_descriptor<{self.element_ty}, {self.shape}, {self.layout}>" + + def __eq__(self, other) -> bool: + return (type(self) is type(other) and self.shape == other.shape and self.layout == other.layout + and self.alloc_shape == other.alloc_shape) + + def __neq__(self, other) -> bool: + return not (self == other) + + def mangle(self) -> str: + shape_str = "_".join([str(s) for s in self.shape]) + return f"MD{self.element_ty.mangle()}S{shape_str}SL{self.layout.mangle()}LAS{self.alloc_shape}ASMD" + + +class tensor_memory_descriptor(base_value): + """ + Represents a tensor memory descriptor handle for Tensor Core Gen5 operations. + """ + + def __init__(self, handle, element_ty, shape, layout, alloc_shape): + self.handle = handle + self.type = tensor_memory_descriptor_type(element_ty, shape, layout, alloc_shape) + + def _flatten_ir(self, handles: List[ir.value]) -> None: + handles.append(self.handle) + + @property + def dtype(self): + return self.type.element_ty + + @property + def shape(self): + return self.type.shape + + @property + def rank(self): + return len(self.shape) + + @property + def layout(self): + return self.type.layout + + def __str__(self) -> str: + return str(self.type) + + @builtin + def load(self, layout, _semantic: GluonSemantic) -> ttgl.tensor: + """ + Load a tensor from tensor memory. + + Args: + layout (DistributedLayout): Destination layout of the tensor. + + Returns: + tensor: A distributed tensor containing the loaded data. + """ + layout = _unwrap_if_constexpr(layout) + ret_ty = ttgl.distributed_type(self.dtype, self.shape, layout) + builder = _semantic.builder + handle = builder.create_tmem_load(ret_ty.to_ir(builder), self.handle) + return ttgl.tensor(handle, ret_ty) + + @builtin + def store(self, value, pred=True, _semantic: GluonSemantic = None) -> None: + """ + Store a tensor into tensor memory. + + Args: + value (tensor): The tensor to store. + pred (bool): Scalar predicate. Operation is skipped if predicate is False. Defaults to True. + """ + pred = _unwrap_if_constexpr(pred) + pred = _semantic.to_tensor(pred) + assert value.shape == self.shape, f"source shape {value.shape} does not match destination shape {self.shape}" + assert value.dtype == self.dtype, f"source dtype {value.dtype} does not match destination dtype {self.dtype}" + _semantic.builder.create_tmem_store(self.handle, value.handle, pred.handle) + + @builtin + def slice(self, start, length, _semantic: GluonSemantic) -> None: + """ + Create a slice of the tensor memory descriptor along the last dimension. + + Args: + start (int): The starting index for subslice. + length (int): The length of the subslice. + + Returns: + tensor_memory_descriptor: Descriptor for the subslice. + """ + start = _unwrap_if_constexpr(start) + length = _unwrap_if_constexpr(length) + _check(isinstance(start, int), lambda: "start must be a constant int") + _check(isinstance(length, int), lambda: "length must be a constant int") + shape = self.shape[:-1] + [length] + layout = self.type.layout + layout = TensorMemoryLayout( + (layout.block[0], min(layout.block[1], length)), + layout.col_stride, + layout.cta_split_num, + layout.two_ctas, + ) + ret = tensor_memory_descriptor(None, self.dtype, shape, layout, self.type.alloc_shape) + builder = _semantic.builder + ret.handle = builder.create_tmem_subslice(ret.type.to_ir(builder), self.handle, start) + return ret + + @builtin + def index(self, index, _semantic: GluonSemantic = None) -> tensor_memory_descriptor: + """ + Create a subview of tensor memory by indexing the first dimension. + + Args: + index (tensor): The index tensor for the subview. + + Returns: + tensor_memory_descriptor: Descriptor for the indexed subview. + """ + index = _semantic.to_tensor(index) + builder = _semantic.builder + shape = self.shape[1:] + layout = self.layout + ret = tensor_memory_descriptor(None, self.dtype, shape, layout, shape) + ret.handle = builder.create_memdesc_index(ret.type.to_ir(builder), self.handle, index.handle) + return ret + + @builtin + def _reinterpret(self, dtype, shape, layout, _semantic: GluonSemantic = None) -> tensor_memory_descriptor: + """ + Reinterpret tensor memory descriptor with a new dtype, shape, and layout. + + Args: + dtype (dtype): The new data type. + shape (Sequence[int]): The new shape. + layout (TensorMemoryLayout): The new layout. + + Returns: + tensor_memory_descriptor: Descriptor with updated type and layout. + """ + dtype = _unwrap_if_constexpr(dtype) + shape = [_unwrap_if_constexpr(s) for s in shape] + layout = _unwrap_if_constexpr(layout) + + ty = tensor_memory_descriptor_type(dtype, shape, layout, shape) + handle = _semantic.builder.create_memdesc_reinterpret(ty.to_ir(_semantic.builder), self.handle) + return tensor_memory_descriptor(handle, **ty.__dict__) + + +@builtin +def allocate_tensor_memory(element_ty, shape, layout, value=None, _semantic=None): + """ + Allocate tensor memory. + + Args: + element_ty (dtype): The element data type. + shape (Sequence[int]): The descriptor shape. + layout (TensorMemoryLayout): The layout of the tensor memory. + value (tensor, optional): Initial tensor to copy. Defaults to None. + + Returns: + tensor_memory_descriptor: Descriptor for the allocated memory. + """ + element_ty = _unwrap_if_constexpr(element_ty) + shape = _unwrap_if_constexpr(shape) + layout = _unwrap_if_constexpr(layout) + value = value.handle if value is not None else None + + ty = tensor_memory_descriptor_type(element_ty, shape, layout, shape) + builder = _semantic.builder + handle = builder.create_tmem_alloc(ty.to_ir(builder), value) + return tensor_memory_descriptor(handle, element_ty, shape, layout, shape) + + +@builtin +def tcgen05_copy(src, dst, _semantic=None): + """ + Start an asynchronous copy from shared memory to tensor memory. + + WARNING: The current semantics of the instruction are not well defined and + the API will change in the future. Use at your own risk. + + Args: + src (shared_memory_descriptor): Shared memory to copy from. + dst (tensor_memory_descriptor): Tensor memory to copy to. + """ + assert isinstance(src, ttgl.shared_memory_descriptor), "source must be a shared memory descriptor" + assert isinstance(dst, tensor_memory_descriptor), "destination must be a tensor memory descriptor" + _semantic.builder.create_tmem_copy(src.handle, dst.handle) + + +@builtin +def tcgen05_mma(a, b, acc, *, use_acc=True, pred=True, mbarriers=None, mbarrier_preds=None, _semantic=None): + """ + Emit a 5th generation TensorCore MMA instruction. + acc = a * b + (acc if use_acc else 0) + + Args: + a (shared_memory_descriptor): Left hand side operand in shared memory. + b (shared_memory_descriptor or tensor_memory_descriptor): Right hand side operand in shared or tensor memory. + acc (tensor_memory_descriptor): Accumulator value in tensor memory (mutated). + use_acc (bool): Whether to use the initial value of the accumulator. Defaults to True. + pred (bool): Scalar predicate. Operation is skipped if predicate is False. Defaults to True. + mbarriers (Sequence[shared_memory_descriptor], optional): Barriers to signal when the operation is complete. If None, mma is synchronous. Defaults to None. + mbarrier_preds (Sequence[bool], optional): Predicates for barriers. Defaults to None. + """ + use_acc = _semantic.to_tensor(use_acc) + pred = _semantic.to_tensor(pred) + + if mbarriers is None: + assert mbarrier_preds is None + mbarriers = [] + mbarrier_preds = [] + else: + mbarriers = [bar.handle for bar in mbarriers] + if mbarrier_preds is None: + true = _semantic.to_tensor(True) + mbarrier_preds = [true.handle] * len(mbarriers) + else: + mbarrier_preds = _semantic._convert_to_ir_values(mbarrier_preds, require_i64=False) + + _semantic.builder.create_tcgen05_mma(a.handle, b.handle, acc.handle, use_acc.handle, pred.handle, mbarriers, + mbarrier_preds, acc.layout.two_ctas) + + +@builtin +def tcgen05_mma_scaled(a, b, acc, a_scale, b_scale, a_type, b_type, *, use_acc=True, pred=True, mbarriers=None, + mbarrier_preds=None, _semantic=None): + """ + Emit a 5th generation TensorCore MMA scaled instruction. + acc = (a * a_scale) * (b * b_scale) + (acc if use_acc else 0) + + Args: + a (shared_memory_descriptor): Left hand side operand in shared memory. + b (shared_memory_descriptor or tensor_memory_descriptor): Right hand side operand in shared or tensor memory. + acc (tensor_memory_descriptor): Accumulator value in tensor memory (mutated). + a_scale (tensor): Scale factor for operand A. + b_scale (tensor): Scale factor for operand B. + a_type (str): Type of operand A. One of {"e2m1", "e4m3", "e5m2"}. + b_type (str): Type of operand B. One of {"e2m1", "e4m3", "e5m2"}. + use_acc (bool): Whether to use the initial value of the accumulator. Defaults to True. + pred (bool): Scalar predicate. Operation is skipped if predicate is False. Defaults to True. + mbarriers (Sequence[mbarrier], optional): Barriers to signal when the operation is complete. If None, mma is synchronous. Defaults to None. + mbarrier_preds (Sequence[bool], optional): Predicates for barriers. Defaults to None. + """ + use_acc = _semantic.to_tensor(use_acc) + pred = _semantic.to_tensor(pred) + + if mbarriers is None: + assert mbarrier_preds is None + mbarriers = [] + mbarrier_preds = [] + else: + mbarriers = [bar.handle for bar in mbarriers] + if mbarrier_preds is None: + true = _semantic.to_tensor(True) + mbarrier_preds = [true.handle] * len(mbarriers) + else: + mbarrier_preds = _semantic._convert_to_ir_values(mbarrier_preds, require_i64=False) + + allowed_formats = {"e2m1", "e4m3", "e5m2"} + assert a_type.value in allowed_formats, f"Unsupported lhs_format: {a_type.value}" + assert b_type.value in allowed_formats, f"Unsupported rhs_format: {b_type.value}" + a_type = _semantic._str_to_fp_type(a_type.value) + b_type = _semantic._str_to_fp_type(b_type.value) + _semantic.builder.create_tcgen05_mma_scaled(a.handle, b.handle, acc.handle, a_scale.handle, b_scale.handle, a_type, + b_type, use_acc.handle, pred.handle, mbarriers, mbarrier_preds) + + +@builtin +def tcgen05_commit(barrier, _semantic=None): + """ + This instruction causes the provided mbarrier to be arrived-on with a count + of 1 when all async tcgen05 MMA and copy instructions previously issued by + the thread are complete. + + Args: + barrier (shared_memory_descriptor): The barrier to track completion of tcgen05 MMA and copy instructions. + """ + _semantic.builder.create_tcgen05_commit(barrier.handle) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/nvidia/blackwell/float2.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/nvidia/blackwell/float2.py new file mode 100644 index 0000000000000000000000000000000000000000..c06b103f3675ec38107b292d770b56cecdea450f --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/nvidia/blackwell/float2.py @@ -0,0 +1,172 @@ +from triton.language.core import _aggregate as aggregate +from triton.experimental.gluon.language import _core as ttgl, _standard as stdlib +from triton.experimental.gluon._runtime import constexpr_function, jit + +__all__ = [ + "pack2", + "unpack2", + "pack", + "unpack", + "fma", + "Float2Tensor", +] + + +@jit +def _add_f32x2(a, b): + return ttgl.inline_asm_elementwise( + """ + add.f32x2 $0, $1, $2; + """, + "=l,l,l", + [a, b], + dtype=ttgl.int64, + is_pure=True, + pack=1, + ) + + +@jit +def _sub_f32x2(a, b): + return ttgl.inline_asm_elementwise( + """ + sub.f32x2 $0, $1, $2; + """, + "=l,l,l", + [a, b], + dtype=ttgl.int64, + is_pure=True, + pack=1, + ) + + +@jit +def _mul_f32x2(a, b): + return ttgl.inline_asm_elementwise( + """ + mul.f32x2 $0, $1, $2; + """, + "=l,l,l", + [a, b], + dtype=ttgl.int64, + is_pure=True, + pack=1, + ) + + +@jit +def _fma_f32x2(a, b, c): + return ttgl.inline_asm_elementwise( + """ + fma.rn.f32x2 $0, $1, $2, $3; + """, + "=l,l,l,l", + [a, b, c], + dtype=ttgl.int64, + is_pure=True, + pack=1, + ) + + +@aggregate +class Float2Tensor: + value: ttgl.tensor + + @constexpr_function + def __init__(self, value: ttgl.tensor): + self.value = value + + @jit + def __add__(self, rhs): + ttgl.static_assert(isinstance(rhs, Float2Tensor), "rhs must be a Float2Tensor") + return Float2Tensor(_add_f32x2(self.value, rhs.value)) + + @jit + def __sub__(self, rhs): + ttgl.static_assert(isinstance(rhs, Float2Tensor), "rhs must be a Float2Tensor") + return Float2Tensor(_sub_f32x2(self.value, rhs.value)) + + @jit + def __mul__(self, rhs): + ttgl.static_assert(isinstance(rhs, Float2Tensor), "rhs must be a Float2Tensor") + return Float2Tensor(_mul_f32x2(self.value, rhs.value)) + + @jit + def sum(self, axis: ttgl.constexpr): + return Float2Tensor(ttgl.reduce(self.value, axis=axis, combine_fn=_add_f32x2)) + + +@jit +def pack2(x0, x1): + value = ttgl.inline_asm_elementwise( + """ + mov.b64 $0, { $1, $2 }; + """, + "=l,r,r", + [x0, x1], + dtype=ttgl.int64, + is_pure=True, + pack=1, + ) + return Float2Tensor(value) + + +@jit +def unpack2(x): + return ttgl.inline_asm_elementwise( + """ + mov.b64 { $0, $1 }, $2; + """, + "=r,=r,l", + [x.value], + dtype=[ttgl.float32, ttgl.float32], + is_pure=True, + pack=1, + ) + + +@constexpr_function +def _get_split_shape(shape, axis): + shape = [d for d in shape] + assert shape[axis] >= 2, f"not enough elements to pack along axis {axis}" + shape[axis] //= 2 + shape.insert(axis + 1, 2) + permute = list(range(len(shape))) + permute[axis + 1], permute[len(permute) - 1] = permute[len(permute) - 1], permute[axis + 1] + return ttgl.tuple(shape), ttgl.tuple(permute) + + +@constexpr_function +def _get_join_shape(shape, axis): + shape = [d for d in shape] + shape[axis] *= 2 + permute = list(range(len(shape))) + permute.insert(axis + 1, len(permute)) + return ttgl.tuple(shape), ttgl.tuple(permute) + + +@jit +def pack(x, axis): + sp: ttgl.constexpr = _get_split_shape(x.shape, axis) + x0, x1 = x.reshape(*sp[0]).permute(*sp[1]).split() + return pack2(x0, x1) + + +@jit +def unpack(x, axis): + shape: ttgl.constexpr = x.value.shape + sp: ttgl.constexpr = _get_join_shape(shape, axis) + x0, x1 = unpack2(x) + return ttgl.join(x0, x1).permute(*sp[1]).reshape(*sp[0]) + + +@jit +def full_like(x, fill_value): + ttgl.static_assert(fill_value.dtype == ttgl.float32, "fill_value must be a float32") + fill = stdlib.full_like(x.value, fill_value, dtype=ttgl.float32) + return pack2(fill, fill) + + +@jit +def fma(a, b, c): + return Float2Tensor(_fma_f32x2(a.value, b.value, c.value)) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/nvidia/blackwell/tma.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/nvidia/blackwell/tma.py new file mode 100644 index 0000000000000000000000000000000000000000..717331e53c04d7d27e2f8369ceae402c1f95d87c --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/nvidia/blackwell/tma.py @@ -0,0 +1,54 @@ +from triton.experimental.gluon.language._core import builtin +from triton.experimental.gluon.language.nvidia.hopper.tma import ( + async_copy_global_to_shared, + async_copy_shared_to_global, + store_wait, + tensor_descriptor, + tensor_descriptor_type, + make_tensor_descriptor, +) + +__all__ = [ + "async_gather", + "async_scatter", + "async_copy_global_to_shared", + "async_copy_shared_to_global", + "store_wait", + "tensor_descriptor", + "tensor_descriptor_type", + "make_tensor_descriptor", +] + + +@builtin +def async_gather(tensor_desc, x_offsets, y_offset, barrier, result, pred=True, _semantic=None): + """ + Asynchronously gather elements from global memory to shared memory using TMA. + + Args: + tensor_desc (tensor_descriptor): The tensor descriptor. + x_offsets (tensor): 1D tensor of X offsets. + y_offset (int): Scalar Y offset. + barrier (shared_memory_descriptor): Barrier that will be signaled when the operation is complete. + result (tensor_memory_descriptor): Result shared memory, must have NVMMASharedLayout. + pred (bool): Scalar predicate. Operation is skipped if predicate is False. Defaults to True. + """ + pred = _semantic.to_tensor(pred) + y_offset = _semantic.to_tensor(y_offset) + _semantic.builder.create_async_tma_gather(tensor_desc.handle, x_offsets.handle, y_offset.handle, barrier.handle, + result.handle, pred.handle) + + +@builtin +def async_scatter(tensor_desc, x_offsets, y_offset, src, _semantic=None): + """ + Asynchronously scatter elements from shared memory to global memory using TMA. + + Args: + tensor_desc (tensor_descriptor): The tensor descriptor. + x_offsets (tensor): 1D tensor of X offsets. + y_offset (int): Scalar Y offset. + src (tensor_memory_descriptor): The source data, must be in NVMMASharedLayout. + """ + y_offset = _semantic.to_tensor(y_offset) + _semantic.builder.create_async_tma_scatter(tensor_desc.handle, x_offsets.handle, y_offset.handle, src.handle) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/nvidia/hopper/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/nvidia/hopper/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..28557303685b3d6aca734d9ff7a926f4d71b94b0 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/nvidia/hopper/__init__.py @@ -0,0 +1,132 @@ +from __future__ import annotations +from triton.compiler.code_generator import unflatten_ir_values +from ..ampere import async_copy, mma_v2 +from . import mbarrier, tma +from ... import _core + +from typing import List, Tuple, TYPE_CHECKING +if TYPE_CHECKING: + from triton._C.libtriton import ir + +__all__ = ["async_copy", "fence_async_shared", "mbarrier", "mma_v2", "tma", "warpgroup_mma", "warpgroup_mma_wait"] + + +@_core.builtin +def fence_async_shared(cluster=False, _semantic=None): + """ + Issue a fence to complete asynchronous shared memory operations. + + Args: + cluster (bool): Whether to fence across cluster. Defaults to False. + """ + cluster = _core._unwrap_if_constexpr(cluster) + _semantic.builder.create_fence_async_shared(cluster) + + +class warpgroup_mma_accumulator_type(_core.base_type): + tensor_type: _core.dtype + + def __init__(self, tensor_type: _core.dtype): + self.tensor_type = tensor_type + + def __str__(self) -> str: + return f"warpgroup_mma_accumulator<{self.tensor_type}>" + + def _unflatten_ir(self, handles: List[ir.value], cursor: int) -> Tuple[warpgroup_mma_accumulator, int]: + return warpgroup_mma_accumulator(handles[cursor], self.tensor_type), cursor + 1 + + def _flatten_ir_types(self, builder: ir.builder, out: List[ir.type]) -> None: + self.tensor_type._flatten_ir_types(builder, out) + + def __eq__(self, other) -> bool: + return type(self) is type(other) and self.tensor_type == other.tensor_type + + def mangle(self) -> str: + return f"FT{self.tensor_type.mangle()}FT" + + +class warpgroup_mma_accumulator(_core.base_value): + handle: ir.value + type: warpgroup_mma_accumulator_type + + def __init__(self, handle, tensor_type: _core.dtype): + self.handle = handle + self.type = warpgroup_mma_accumulator_type(tensor_type) + + def _flatten_ir(self, handles: List[ir.value]) -> None: + handles.append(self.handle) + + +@_core.builtin +def warpgroup_mma_init(value, _semantic): + assert isinstance(value, _core.tensor) + return warpgroup_mma_accumulator(value.handle, value.type) + + +@_core.builtin +def warpgroup_mma(a, b, acc, *, use_acc=True, precision=None, max_num_imprecise_acc=None, is_async=False, + _semantic=None): + """ + Perform warpgroup MMA (Tensor Core) operations. + acc = a * b + (acc if use_acc else 0) + + Args: + a (tensor or shared_memory_descriptor): Left hand side operand. + b (shared_memory_descriptor): Right hand side operand. + acc (tensor): Accumulator tensor. + use_acc (bool): Whether to use the initial value of the accumulator. Defaults to True. + precision (str, optional): Dot input precision. Defaults to builder default. + max_num_imprecise_acc (int): Max imprecise accumulations. Used for fp8 -> fp32 dot. Determines how many accumulation are done in limited precision. Defaults to None, which means no upcasting is done. + is_async (bool): Whether operation is asynchronous. Defaults to False. + + Returns: + tensor or warpgroup_mma_accumulator: Returns the result if synchronous, or a token to load the value once computed if asynchronous. + """ + use_acc = _semantic.to_tensor(use_acc) + + if precision is None: + precision = _semantic.builder.options.default_dot_input_precision + + precision = _semantic._str_to_dot_input_precision(precision) + + K = a.type.shape[-1] + if max_num_imprecise_acc is None: + if a.dtype.is_fp8() and b.dtype.is_fp8(): + max_num_imprecise_acc = _semantic.builder.options.max_num_imprecise_acc_default + else: + max_num_imprecise_acc = 0 + else: + if a.dtype.is_fp8() and b.dtype.is_fp8() and max_num_imprecise_acc > K: + raise ValueError(f"max_num_imprecise_acc ({max_num_imprecise_acc}) must be <= K ({K})") + + max_num_imprecise_acc = _core._unwrap_if_constexpr(max_num_imprecise_acc) + is_async = _core._unwrap_if_constexpr(is_async) + + handle = _semantic.builder.create_warpgroup_mma(a.handle, b.handle, acc.handle, use_acc.handle, precision, + max_num_imprecise_acc, is_async) + tensor_ty = acc.type.tensor_type if isinstance(acc, warpgroup_mma_accumulator) else acc.type + if is_async: + return warpgroup_mma_accumulator(handle, tensor_ty) + else: + return _core.tensor(handle, tensor_ty) + + +@_core.builtin +def warpgroup_mma_wait(num_outstanding=0, deps=None, _semantic=None): + """ + Wait until `num_outstanding` or less warpgroup MMA operations are in-flight. + + Args: + num_outstanding (int): Number of outstanding warpgroup MMA operations to wait for. Defaults to 0. + deps (Sequence[tensor]): List of dependencies that need to be kept alive while the mma is unfinished. + """ + if deps is None: + raise ValueError("warpgroup_mma_wait deps must be given") + deps_handles = [x.handle for x in deps] if deps is not None else [] + num_outstanding = _core._unwrap_if_constexpr(num_outstanding) + results = _semantic.builder.create_warpgroup_mma_wait(deps_handles, num_outstanding) + result_types = [dep.type.tensor_type if isinstance(dep, warpgroup_mma_accumulator) else dep.type for dep in deps] + results = unflatten_ir_values(results, result_types) + if len(deps) == 1: + return next(results) + return tuple(results) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/nvidia/hopper/mbarrier.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/nvidia/hopper/mbarrier.py new file mode 100644 index 0000000000000000000000000000000000000000..93bf51ebadac0dfeaeb8a4bfec975b61ab35e90c --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/nvidia/hopper/mbarrier.py @@ -0,0 +1,34 @@ +from ..ampere.mbarrier import MBarrierLayout, init, invalidate, wait +from ..._core import _unwrap_if_constexpr, builtin + +__all__ = ["arrive", "expect", "init", "invalidate", "MBarrierLayout", "wait"] + + +@builtin +def expect(mbarrier, bytes, pred=True, _semantic=None): + """ + Expect a specific number of bytes being copied. When they are copied, the barrier is signaled. + + Args: + mbarrier (shared_memory_descriptor): Barrier that will be signaled when the operation is complete. + bytes (int): Expected byte count. + pred (bool): Scalar predicate. Operation is skipped if predicate is False. Defaults to True. + """ + bytes = _unwrap_if_constexpr(bytes) + pred = _semantic.to_tensor(pred) + _semantic.builder.create_mbarrier_expect(mbarrier.handle, bytes, pred.handle) + + +@builtin +def arrive(mbarrier, *, count=1, pred=True, _semantic=None): + """ + Arrive at an mbarrier with a specified count. + + Args: + mbarrier (shared_memory_descriptor): Barrier to be signalled. + count (int): Count to arrive with. Defaults to 1. + pred (bool): Scalar predicate. Operation is skipped if predicate is False. Defaults to True. + """ + count = _unwrap_if_constexpr(count) + pred = _semantic.to_tensor(pred) + _semantic.builder.create_mbarrier_arrive(mbarrier.handle, count, pred.handle) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/nvidia/hopper/tma.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/nvidia/hopper/tma.py new file mode 100644 index 0000000000000000000000000000000000000000..dc4ef3ace2958336ce0c0a5c6c5ce0240b5f3ccd --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/language/nvidia/hopper/tma.py @@ -0,0 +1,169 @@ +from __future__ import annotations +from typing import List, Tuple, TYPE_CHECKING +from dataclasses import dataclass +from triton.language.core import base_type, base_value +import triton.experimental.gluon.language._core as ttgl +from triton.experimental.gluon.language._layouts import NVMMASharedLayout +from triton.experimental.gluon.language._core import builtin, _unwrap_if_constexpr + +if TYPE_CHECKING: + from triton._C import ir + +__all__ = ["async_copy_global_to_shared", "async_copy_shared_to_global", "store_wait"] + + +@dataclass(eq=True) +class tensor_descriptor_type(base_type): + block_type: ttgl.block_type + shape_type: ttgl.tuple_type + strides_type: ttgl.tuple_type + layout: NVMMASharedLayout + + def __str__(self) -> str: + return f"tensor_descriptor<{self.block_type}, {self.layout}>" + + def _to_ir(self, builder: ir.builder) -> ir.type: + is_signed = self.block_type.element_ty.is_int_signed() + return builder.get_tensor_descriptor_layout_type( + self.block_type.to_ir(builder), + is_signed, + self.layout._to_ir(builder), + ) + + def _unflatten_ir(self, handles: List[ir.value], cursor: int) -> Tuple[tensor_descriptor, int]: + handle = handles[cursor] + cursor += 1 + shape, cursor = self.shape_type._unflatten_ir(handles, cursor) + strides, cursor = self.strides_type._unflatten_ir(handles, cursor) + value = tensor_descriptor(handle, shape, strides, self.block_type, layout=self.layout) + return value, cursor + + def _flatten_ir_types(self, builder: ir.builder, out: List[ir.type]) -> None: + is_signed = self.block_type.element_ty.is_int_signed() + ty = builder.get_tensor_descriptor_layout_type( + self.block_type.to_ir(builder), + is_signed, + self.layout._to_ir(builder), + ) + out.append(ty) + self.shape_type._flatten_ir_types(builder, out) + self.strides_type._flatten_ir_types(builder, out) + + def mangle(self) -> str: + return f"TD{self.block_type.mangle()}_{self.layout.mangle()}TD" + + +class tensor_descriptor(base_value): + + def __init__(self, handle, shape: List[ttgl.tensor], strides: List[ttgl.tensor], block_type: ttgl.block_type, + layout: NVMMASharedLayout): + self.handle = handle + self.shape = ttgl.tuple(shape) + self.strides = ttgl.tuple(strides) + self.type = tensor_descriptor_type(block_type, shape_type=self.shape.type, strides_type=self.strides.type, + layout=layout) + + def _flatten_ir(self, handles: List[ir.value]) -> None: + handles.append(self.handle) + self.shape._flatten_ir(handles) + self.strides._flatten_ir(handles) + + @property + def block_type(self): + return self.type.block_type + + @property + def block_shape(self): + return self.type.block_type.shape + + @property + def dtype(self): + return self.type.block_type.element_ty + + @property + def layout(self): + return self.type.layout + + +@builtin +def async_copy_global_to_shared(tensor_desc, coord, barrier, result, pred=True, _semantic=None): + coord = _semantic._convert_to_ir_values(coord, require_i64=False) + pred = _semantic.to_tensor(pred) + _semantic.builder.create_async_tma_copy_global_to_local(tensor_desc.handle, coord, barrier.handle, result.handle, + pred.handle) + + +@builtin +def async_copy_shared_to_global(tensor_desc, coord, src, _semantic=None): + coord = _semantic._convert_to_ir_values(coord, require_i64=False) + _semantic.builder.create_async_tma_copy_local_to_global(tensor_desc.handle, coord, src.handle) + + +@builtin +def store_wait(pendings, _semantic=None): + pendings = _unwrap_if_constexpr(pendings) + _semantic.builder.create_async_tma_store_wait(pendings) + + +@builtin +def make_tensor_descriptor( + base: ttgl.tensor, + shape: List[ttgl.tensor], + strides: List[ttgl.tensor], + block_shape: List[ttgl.constexpr], + layout: NVMMASharedLayout, + padding_option="zero", + _semantic=None, +) -> tensor_descriptor: + padding_option = _unwrap_if_constexpr(padding_option) + block_shape = _unwrap_if_constexpr(block_shape) + + ndim = len(shape) + if not (1 <= ndim <= 5): + raise ValueError(f"Expected 1 <= ndim <= 5 but got {ndim} dimensions") + if len(strides) != ndim: + raise ValueError(f"Expected {ndim} strides but got {len(strides)}") + if len(block_shape) != ndim: + raise ValueError(f"Expected block_shape to have {ndim} dimensions but got {len(strides)}") + assert isinstance(base.dtype, ttgl.pointer_type) + elem_size = base.dtype.element_ty.primitive_bitwidth // 8 + contig_dim_size = ttgl._unwrap_if_constexpr(block_shape[-1]) + if contig_dim_size * elem_size < 16: + raise ValueError( + f"Descriptor block shape must have at least 16 bytes in the last dimension, but got {contig_dim_size} * {elem_size} = {contig_dim_size * elem_size} bytes" + ) + + last_stride = ttgl._unwrap_if_constexpr(strides[-1]) + if last_stride != 1: + raise ValueError(f"Tensor descriptor last dim must be 1 but got {last_stride}") + + shape = [_semantic.make_scalar(x, ttgl.int32) for x in shape] + strides = [_semantic.make_scalar(ttgl._unwrap_if_constexpr(x), ttgl.int64) for x in strides] + + # Check whether `block_shape` is static + block_shape = ttgl._unwrap_shape(block_shape) + + assert isinstance(base.type, ttgl.pointer_type) + block_type = ttgl.block_type(base.type.element_ty, block_shape) + base_handle = base.handle + + padding = _semantic._str_to_padding_option(padding_option) + + layout = _unwrap_if_constexpr(layout) + assert isinstance(layout, NVMMASharedLayout), \ + "Expected layout to be a NVMMASharedLayout" + + shape_type = ttgl.tuple(shape).type + strides_type = ttgl.tuple(strides).type + ty = tensor_descriptor_type(block_type, shape_type, strides_type, layout) + + if base.type.element_ty.is_int() and padding == ttgl.ir.PADDING_OPTION.PAD_NAN: + raise ValueError("Padding option `nan` is not supported for integer blocks") + handle = _semantic.builder.create_make_tensor_descriptor( + ty._to_ir(_semantic.builder), + base_handle, + [s.handle for s in shape], + [s.handle for s in strides], + padding, + ) + return tensor_descriptor(handle, shape, strides, block_type, layout) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/nvidia/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/nvidia/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8184c7388eaa11e018905df24982af333a9df6d5 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/nvidia/__init__.py @@ -0,0 +1,4 @@ +from . import hopper +from . import blackwell + +__all__ = ["hopper", "blackwell"] diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/nvidia/blackwell.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/nvidia/blackwell.py new file mode 100644 index 0000000000000000000000000000000000000000..abf919805191d9ebddbf416b3be95187fdf893cb --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/nvidia/blackwell.py @@ -0,0 +1,3 @@ +from .hopper import TensorDescriptor + +__all__ = ["TensorDescriptor"] diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/nvidia/hopper.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/nvidia/hopper.py new file mode 100644 index 0000000000000000000000000000000000000000..83bcfc55ce7f659ff38a3a360e4a846315d24835 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/experimental/gluon/nvidia/hopper.py @@ -0,0 +1,47 @@ +from dataclasses import dataclass +from typing import List, Any +from triton._utils import validate_block_shape, canonicalize_dtype, get_primitive_bitwidth +from triton.experimental.gluon.language._layouts import NVMMASharedLayout + +__all__ = ["TensorDescriptor"] + + +@dataclass +class TensorDescriptor: + base: Any + shape: List[int] + strides: List[int] + block_shape: List[int] + layout: NVMMASharedLayout + padding: str = "zero" + + def __post_init__(self): + rank = len(self.shape) + assert len(self.strides) == rank, f"rank mismatch: {self}" + assert len(self.block_shape) == rank, f"rank mismatch: {self}" + assert rank > 0, "rank must not be zero" + assert rank <= 5, "rank cannot be more than 5" + assert self.base.data_ptr() % 16 == 0, "base must be 16-byte aligned" + validate_block_shape(self.block_shape) + dtype_str = canonicalize_dtype(self.base.dtype) + elem_bytes = get_primitive_bitwidth(dtype_str) // 8 + for stride in self.strides[:-1]: + assert (stride * elem_bytes) % 16 == 0, "strides must be 16-byte aligned" + for shape_dim in self.shape: + assert shape_dim > 0, "shape must be positive" + assert self.strides[-1] == 1, "Last dimension must be contiguous" + assert isinstance(self.layout, NVMMASharedLayout), "Layout must be NVMMASharedLayout" + assert self.padding == "zero" or self.padding == "nan", "Illegal value for padding" + if self.padding == "nan": + assert self.base.dtype.is_floating_point, "Padding option `nan` is only supported for floating point tensors" + + @staticmethod + def from_tensor(tensor: Any, block_shape: List[int], layout: NVMMASharedLayout, padding="zero"): + return TensorDescriptor( + tensor, + tensor.shape, + tensor.stride(), + block_shape, + layout, + padding, + ) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/language/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/language/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..04d548c9a5d2d8d29af0b6e7f47ceeb4af40ba86 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/language/__init__.py @@ -0,0 +1,350 @@ +"""isort:skip_file""" +# Import order is significant here. + +from . import math +from . import extra +from .standard import ( + argmax, + argmin, + bitonic_merge, + cdiv, + cumprod, + cumsum, + flip, + interleave, + max, + min, + ravel, + reduce_or, + sigmoid, + softmax, + sort, + sum, + swizzle2d, + topk, + xor_sum, + zeros, + zeros_like, +) +from .core import ( + PropagateNan, + TRITON_MAX_TENSOR_NUMEL, + load_tensor_descriptor, + store_tensor_descriptor, + make_tensor_descriptor, + tensor_descriptor, + tensor_descriptor_type, + add, + advance, + arange, + associative_scan, + assume, + atomic_add, + atomic_and, + atomic_cas, + atomic_max, + atomic_min, + atomic_or, + atomic_xchg, + atomic_xor, + bfloat16, + block_type, + broadcast, + broadcast_to, + cat, + cast, + clamp, + condition, + const, + constexpr, + constexpr_type, + debug_barrier, + device_assert, + device_print, + dot, + dot_scaled, + dtype, + expand_dims, + float16, + float32, + float64, + float8e4b15, + float8e4nv, + float8e4b8, + float8e5, + float8e5b16, + full, + gather, + histogram, + inline_asm_elementwise, + int1, + int16, + int32, + int64, + int8, + join, + load, + make_block_ptr, + map_elementwise, + max_constancy, + max_contiguous, + maximum, + minimum, + mul, + multiple_of, + num_programs, + permute, + pi32_t, + pointer_type, + program_id, + range, + reduce, + reshape, + slice, + split, + static_assert, + static_print, + static_range, + store, + sub, + tensor, + trans, + tuple, + tuple_type, + uint16, + uint32, + uint64, + uint8, + view, + void, + where, +) +from .math import (umulhi, exp, exp2, fma, log, log2, cos, rsqrt, sin, sqrt, sqrt_rn, abs, fdiv, div_rn, erf, floor, + ceil) +from .random import ( + pair_uniform_to_normal, + philox, + philox_impl, + rand, + rand4x, + randint, + randint4x, + randn, + randn4x, + uint_to_uniform_float, +) +from . import target_info + +__all__ = [ + "PropagateNan", + "TRITON_MAX_TENSOR_NUMEL", + "load_tensor_descriptor", + "store_tensor_descriptor", + "make_tensor_descriptor", + "tensor_descriptor", + "abs", + "add", + "advance", + "arange", + "argmax", + "argmin", + "associative_scan", + "assume", + "atomic_add", + "atomic_and", + "atomic_cas", + "atomic_max", + "atomic_min", + "atomic_or", + "atomic_xchg", + "atomic_xor", + "bfloat16", + "bitonic_merge", + "block_type", + "broadcast", + "broadcast_to", + "cat", + "cast", + "cdiv", + "ceil", + "clamp", + "condition", + "const", + "constexpr", + "constexpr_type", + "cos", + "cumprod", + "cumsum", + "debug_barrier", + "device_assert", + "device_print", + "div_rn", + "dot", + "dot_scaled", + "dtype", + "erf", + "exp", + "exp2", + "expand_dims", + "extra", + "fdiv", + "flip", + "float16", + "float32", + "float64", + "float8e4b15", + "float8e4nv", + "float8e4b8", + "float8e5", + "float8e5b16", + "floor", + "fma", + "full", + "gather", + "histogram", + "inline_asm_elementwise", + "interleave", + "int1", + "int16", + "int32", + "int64", + "int8", + "join", + "load", + "log", + "log2", + "make_block_ptr", + "map_elementwise", + "math", + "max", + "max_constancy", + "max_contiguous", + "maximum", + "min", + "minimum", + "mul", + "multiple_of", + "num_programs", + "pair_uniform_to_normal", + "permute", + "philox", + "philox_impl", + "pi32_t", + "pointer_type", + "program_id", + "rand", + "rand4x", + "randint", + "randint4x", + "randn", + "randn4x", + "range", + "ravel", + "reduce", + "reduce_or", + "reshape", + "rsqrt", + "slice", + "sigmoid", + "sin", + "softmax", + "sort", + "split", + "sqrt", + "sqrt_rn", + "static_assert", + "static_print", + "static_range", + "store", + "sub", + "sum", + "swizzle2d", + "target_info", + "tensor", + "topk", + "trans", + "tuple", + "uint16", + "uint32", + "uint64", + "uint8", + "uint_to_uniform_float", + "umulhi", + "view", + "void", + "where", + "xor_sum", + "zeros", + "zeros_like", +] + + +def str_to_ty(name, c): + from builtins import tuple + + if isinstance(name, tuple): + fields = type(name).__dict__.get("_fields", None) + return tuple_type([str_to_ty(x, c) for x in name], fields) + + if name[0] == "*": + name = name[1:] + const = False + if name[0] == "k": + name = name[1:] + const = True + ty = str_to_ty(name, c) + return pointer_type(element_ty=ty, const=const) + + if name.startswith("tensordesc"): + inner = name.split("<")[1].rstrip(">") + dtype, rest = inner.split("[", maxsplit=1) + block_shape, rest = rest.split("]", maxsplit=1) + block_shape = [int(s.strip()) for s in block_shape.rstrip("]").split(",")] + layout = rest.lstrip(",") + is_gluon = len(layout) + dtype = str_to_ty(dtype, None) + ndim = len(block_shape) + shape_type = tuple_type([int32] * ndim) + # FIXME: Last dim stride should be constexpr(1) + stride_type = tuple_type(([int64] * ndim)) + block = block_type(dtype, block_shape) + if is_gluon: + from triton.experimental.gluon.language._layouts import NVMMASharedLayout, PaddedSharedLayout, SwizzledSharedLayout + from triton.experimental.gluon.language.nvidia.hopper.tma import tensor_descriptor_type as nvidia_tensor_descriptor_type + from triton.experimental.gluon.language.amd.gfx1250.tdm import tensor_descriptor_type as amd_tensor_descriptor_type + layout = eval( + layout, + dict(NVMMASharedLayout=NVMMASharedLayout, PaddedSharedLayout=PaddedSharedLayout, + SwizzledSharedLayout=SwizzledSharedLayout)) + if isinstance(layout, NVMMASharedLayout): + return nvidia_tensor_descriptor_type(block, shape_type, stride_type, layout) + else: + return amd_tensor_descriptor_type(block, shape_type, stride_type, layout) + return tensor_descriptor_type(block, shape_type, stride_type) + + if name.startswith("constexpr"): + return constexpr_type(c) + + tys = { + "fp8e4nv": float8e4nv, + "fp8e4b8": float8e4b8, + "fp8e5": float8e5, + "fp8e5b16": float8e5b16, + "fp8e4b15": float8e4b15, + "fp16": float16, + "bf16": bfloat16, + "fp32": float32, + "fp64": float64, + "i1": int1, + "i8": int8, + "i16": int16, + "i32": int32, + "i64": int64, + "u1": int1, + "u8": uint8, + "u16": uint16, + "u32": uint32, + "u64": uint64, + "B": int1, + } + return tys[name] diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/language/core.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/language/core.py new file mode 100644 index 0000000000000000000000000000000000000000..29f6a367f3680162dbba9dc6e8bededdf03d12fe --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/language/core.py @@ -0,0 +1,3490 @@ +from __future__ import annotations + +import math +from warnings import warn +from contextlib import contextmanager +from enum import Enum +from functools import partial, wraps +import typing +from typing import Union, Callable, List, Sequence, TypeVar, Optional, Tuple +from dataclasses import dataclass +import builtins +from .. import knobs +from ..runtime.jit import JITCallable +import inspect + +from .._C.libtriton import ir +from .._utils import TRITON_MAX_TENSOR_NUMEL, validate_block_shape, get_primitive_bitwidth + +T = TypeVar('T') + +TRITON_BUILTIN = "__triton_builtin__" + +PropagateNan = ir.PROPAGATE_NAN + + +def must_use_result(x, s=True): + """If the result of this function is unused, throw an error.""" + if isinstance(x, str): + return (lambda fn: must_use_result(fn, x)) + x._must_use_result = s + return x + + +def builtin(fn: T) -> T: + """Mark a function as a builtin.""" + assert callable(fn) + + @wraps(fn) + def wrapper(*args, **kwargs): + if "_semantic" not in kwargs or kwargs["_semantic"] is None: + raise ValueError("Did you forget to add @triton.jit ? " + "(`_semantic` argument must be provided outside of JIT functions.)") + return fn(*args, **kwargs) + + setattr(wrapper, TRITON_BUILTIN, True) + + return wrapper + + +def _tensor_member_fn(fn: T) -> T: + """Decorator that adds this free function as a member fn on class tensor. + + When called as a member function on class tensor, the first argument to `fn` + is `self`, i.e. the tensor object. + + If there are multiple decorators on a function, you probably want this one + to be the highest one (i.e. furthest from the function's `def`), so it's + applied last. + + Unfortunately you still need to add a type stub to the body of class tensor + in order for pytype to know about it. + """ + assert callable(fn) + orig_sig = inspect.signature(fn) + # Does fn take args other than _semantic, _generator, and the tensor itself? + has_args = len(orig_sig.parameters.keys() - {"_semantic", "_generator"}) > 1 + + if not fn.__doc__: + fn.__doc__ = "" + fn.__doc__ += f""" + This function can also be called as a member function on :py:class:`tensor`, + as :code:`x.{fn.__name__}({"..." if has_args else ""})` instead of + :code:`{fn.__name__}(x{", ..." if has_args else ""})`. + """ + + def wrapper(*args, **kwargs): + return fn(*args, **kwargs) + + # Match the signature of `fn`, but change the first arg to `self` so the + # docs are a little less weird. + new_params = list(orig_sig.parameters.values()) + new_params[0] = new_params[0].replace(name='self') + new_sig = orig_sig.replace(parameters=new_params) + wrapper.__signature__ = new_sig + wrapper.__doc__ = f"Forwards to :py:func:`{fn.__name__}` free function" + # If fn is a builtin, mark the wrapper as a builtin too. + if is_builtin(fn): + setattr(wrapper, TRITON_BUILTIN, True) + + setattr(tensor, fn.__name__, fn if isinstance(fn, JITCallable) else wrapper) + return fn + + +def _unwrap_iterable(x): + """Returns x[0] if x has one element and x[0] is iterable.""" + if len(x) == 1: + # Determine whether x[0] is iterable. + # + # You might want to use collections.abc.Iterable instead of this + # try/except block. Unfortunately, this doesn't work with constexpr. + # + # The problem is that abc.Iterable checks for __iter__ on the *class*. + # But we want constexpr to expose an __iter__ method if and only if the + # wrapped *object* (i.e. self.value) is iterable. Therefore there's no + # right answer for whether the class constexpr defines __iter__, and + # abc.Iterable doesn't work (at least not without some metaclass magic). + try: + iter(x[0]) + return x[0] + except TypeError: + pass + + return x + + +def is_builtin(fn) -> bool: + """Is this a registered triton builtin function?""" + return getattr(fn, TRITON_BUILTIN, False) + + +@builtin +def to_tensor(x, _semantic=None): + return _semantic.to_tensor(x) + + +# ----------------------- +# constexpr +# ----------------------- + + +class const: + """ + This class is used as a type annotation to mark pointers to constant data. + The `store` function cannot be called with a pointer to const. Constness + is part of the pointer type and the usual Triton type consistency rules + apply. For example you cannot have a function that returns constant pointer + in one return statement and non-constant pointer in another. + """ + pass + + +class base_value: + """Base class of values that exist in the triton IR (i.e. not constexprs). + """ + type: base_type + + def _flatten_ir(self, handles: List[ir.value]) -> None: + """Flatten frontend value into a sequence of mlir handles, which are appended + to the output list + """ + raise NotImplementedError + + +class base_type: + + def __eq__(self, other) -> bool: + raise NotImplementedError("Types must implement __eq__") + + def __ne__(self, other) -> bool: + return not (self == other) + + def _unflatten_ir(self, handles: List[ir.value], cursor: int) -> Tuple[base_value, int]: + """Build a frontend value with the current dtype, wrapping a list of existing handles. + cursor is the index of the first handle relevant to this value, and the function + should return the updated cursor position after any handles consumed by the created value. + """ + raise NotImplementedError + + def mangle(self) -> str: + raise NotImplementedError(f"NYI: Type mangling for type {self.__class__}") + + def _flatten_ir_types(self, builder: ir.builder, out: List[ir.type]) -> None: + raise NotImplementedError + + +class constexpr_type(base_type): + + def __init__(self, value): + self.value = value + + def __eq__(self, other): + return isinstance(other, constexpr_type) and self.value == other.value + + def __repr__(self) -> str: + return f"constexpr_type[{self.value}]" + + def __hash__(self): + return hash(self.value) + + def mangle(self) -> str: + return repr(self) + + def _flatten_ir_types(self, builder: ir.builder, out: List[ir.type]) -> None: + return + + def _unflatten_ir(self, handles: List[ir.value], cursor: int) -> Tuple[base_value, int]: + return constexpr(self.value), cursor + + +class constexpr(base_value): + """ + This class is used to store a value that is known at compile-time. + """ + + def __init__(self, value): + while isinstance(value, constexpr): + value = value.value + self.value = value + self.type = constexpr_type(value) + + def __repr__(self) -> str: + return f"constexpr[{self.value}]" + + def __hash__(self): + return hash((self.value, self.type)) + + def _flatten_ir(self, handles: List[ir.value]) -> None: + return + + def __index__(self): + return self.value + + # In interpreter mode, constant values are not wrapped in constexpr, + # and therefore do not have a .value attribute. + # As a result, from here and below, we need to call the _unwrap_if_constexpr + # function to obtain either constexpr.value or the value itself. + def __add__(self, other): + return constexpr(self.value + _unwrap_if_constexpr(other)) + + def __radd__(self, other): + return constexpr(_unwrap_if_constexpr(other) + self.value) + + def __sub__(self, other): + return constexpr(self.value - _unwrap_if_constexpr(other)) + + def __rsub__(self, other): + return constexpr(_unwrap_if_constexpr(other) - self.value) + + def __mul__(self, other): + return constexpr(self.value * _unwrap_if_constexpr(other)) + + def __mod__(self, other): + return constexpr(self.value % _unwrap_if_constexpr(other)) + + def __rmul__(self, other): + return constexpr(_unwrap_if_constexpr(other) * self.value) + + def __truediv__(self, other): + return constexpr(self.value / _unwrap_if_constexpr(other)) + + def __rtruediv__(self, other): + return constexpr(_unwrap_if_constexpr(other) / self.value) + + def __floordiv__(self, other): + return constexpr(self.value // _unwrap_if_constexpr(other)) + + def __rfloordiv__(self, other): + return constexpr(_unwrap_if_constexpr(other) // self.value) + + def __gt__(self, other): + return constexpr(self.value > _unwrap_if_constexpr(other)) + + def __rgt__(self, other): + return constexpr(_unwrap_if_constexpr(other) > self.value) + + def __ge__(self, other): + return constexpr(self.value >= _unwrap_if_constexpr(other)) + + def __rge__(self, other): + return constexpr(_unwrap_if_constexpr(other) >= self.value) + + def __lt__(self, other): + return constexpr(self.value < _unwrap_if_constexpr(other)) + + def __rlt__(self, other): + return constexpr(_unwrap_if_constexpr(other) < self.value) + + def __le__(self, other): + return constexpr(self.value <= _unwrap_if_constexpr(other)) + + def __rle__(self, other): + return constexpr(_unwrap_if_constexpr(other) <= self.value) + + def __eq__(self, other): + return constexpr(self.value == _unwrap_if_constexpr(other)) + + def __ne__(self, other): + return constexpr(self.value != _unwrap_if_constexpr(other)) + + def __bool__(self): + return bool(self.value) + + def __neg__(self): + return constexpr(-self.value) + + def __and__(self, other): + return constexpr(self.value & _unwrap_if_constexpr(other)) + + def logical_and(self, other): + return constexpr(self.value and _unwrap_if_constexpr(other)) + + def __or__(self, other): + return constexpr(self.value | _unwrap_if_constexpr(other)) + + def __xor__(self, other): + return constexpr(self.value ^ _unwrap_if_constexpr(other)) + + def logical_or(self, other): + return constexpr(self.value or _unwrap_if_constexpr(other)) + + def __pos__(self): + return constexpr(+self.value) + + def __invert__(self): + return constexpr(~self.value) + + def __pow__(self, other): + return constexpr(self.value**_unwrap_if_constexpr(other)) + + def __rpow__(self, other): + return constexpr(_unwrap_if_constexpr(other)**self.value) + + def __rshift__(self, other): + return constexpr(self.value >> _unwrap_if_constexpr(other)) + + def __lshift__(self, other): + return constexpr(self.value << _unwrap_if_constexpr(other)) + + def __not__(self): + return constexpr(not self.value) + + def __iter__(self): + return iter(self.value) + + def __call__(self, *args, **kwds): + return self.value(*args, **kwds) + + def __getitem__(self, *args): + args = (_unwrap_if_constexpr(x) for x in _normalize_tuple(args)) + return self.value.__getitem__(*args) + + +CONSTEXPR_0 = constexpr(0) + + +def _unwrap_if_constexpr(o): + if isinstance(o, list): + return [_unwrap_if_constexpr(x) for x in o] + if isinstance(o, builtins.tuple): + return builtins.tuple(_unwrap_if_constexpr(x) for x in o) + if isinstance(o, tuple): + return tuple(_unwrap_if_constexpr(x) for x in o) + return o.value if isinstance(o, constexpr) else o + + +def _normalize_tuple(t): + normalized_tuple = _unwrap_if_constexpr(t) + if isinstance(normalized_tuple, (list, builtins.tuple)): + normalized_tuple = tuple(normalized_tuple) + return normalized_tuple + + +def check_bit_width(value, shift_value): + if isinstance(value, tensor) and isinstance(shift_value, constexpr): + bitwidth = value.type.scalar.primitive_bitwidth + if shift_value.value >= bitwidth: + warn( + f"Value {shift_value.value} exceeds the maximum bitwidth ({bitwidth}) for type '{value.dtype}'. This may result in undefined behavior." + ) + + +# ----------------------- +# dtype +# ----------------------- + + +class dtype(base_type): + SINT_TYPES = ['int8', 'int16', 'int32', 'int64'] + UINT_TYPES = ['int1', 'uint8', 'uint16', 'uint32', 'uint64'] + FP_TYPES = ['fp8e4b15', 'fp8e4nv', 'fp8e4b8', 'fp8e5', 'fp8e5b16', 'fp16', 'bf16', 'fp32', 'fp64'] + STANDARD_FP_TYPES = ['fp16', 'bf16', 'fp32', 'fp64'] + OTHER_TYPES = ['void'] + + class SIGNEDNESS(Enum): + SIGNED = 0 + UNSIGNED = 1 + + class KIND(Enum): + BOOLEAN = 0 + INTEGRAL = 1 + FLOATING = 2 + + def __init__(self, name): + name = _unwrap_if_constexpr(name) + self.name = name + assert name in dtype.SINT_TYPES + dtype.UINT_TYPES + dtype.FP_TYPES + dtype.OTHER_TYPES, name + self.primitive_bitwidth = get_primitive_bitwidth(name) + self.itemsize = self.primitive_bitwidth // 8 + if name in dtype.SINT_TYPES: + self.int_signedness = dtype.SIGNEDNESS.SIGNED + self.int_bitwidth = self.primitive_bitwidth + elif name in dtype.UINT_TYPES: + self.int_signedness = dtype.SIGNEDNESS.UNSIGNED + self.int_bitwidth = self.primitive_bitwidth + elif name in dtype.FP_TYPES: + if name == 'fp8e4b15': + self.fp_mantissa_width = 3 + self.exponent_bias = 15 + elif name == 'fp8e4nv': + self.fp_mantissa_width = 3 + self.exponent_bias = 7 + elif name == 'fp8e4b8': + self.fp_mantissa_width = 3 + self.exponent_bias = 8 + elif name == 'fp8e5': + self.fp_mantissa_width = 2 + self.exponent_bias = 15 + elif name == 'fp8e5b16': + self.fp_mantissa_width = 2 + self.exponent_bias = 16 + elif name == 'fp16': + self.fp_mantissa_width = 10 + self.exponent_bias = 15 + elif name == 'bf16': + self.fp_mantissa_width = 7 + self.exponent_bias = 127 + elif name == 'fp32': + self.fp_mantissa_width = 23 + self.exponent_bias = 127 + elif name == 'fp64': + self.fp_mantissa_width = 52 + self.exponent_bias = 1023 + else: + raise RuntimeError(f'Unsupported floating-point type {name}') + + def is_fp8(self): + return 'fp8' in self.name + + def is_fp8e4nv(self): + return self.name == 'fp8e4nv' + + def is_fp8e4b8(self): + return self.name == 'fp8e4b8' + + def is_fp8e4b15(self): + return self.name == 'fp8e4b15' + + def is_fp8e5(self): + return self.name == 'fp8e5' + + def is_fp8e5b16(self): + return self.name == 'fp8e5b16' + + def is_fp16(self): + return self.name == 'fp16' + + def is_bf16(self): + return self.name == 'bf16' + + def is_fp32(self): + return self.name == 'fp32' + + def is_fp64(self): + return self.name == 'fp64' + + def is_int1(self): + return self.name == 'int1' + + def is_int8(self): + return self.name == 'int8' + + def is_int16(self): + return self.name == 'int16' + + def is_int32(self): + return self.name == 'int32' + + def is_int64(self): + return self.name == 'int64' + + def is_uint8(self): + return self.name == 'uint8' + + def is_uint16(self): + return self.name == 'uint16' + + def is_uint32(self): + return self.name == 'uint32' + + def is_uint64(self): + return self.name == 'uint64' + + def is_floating(self): + return self.name in dtype.FP_TYPES + + def is_standard_floating(self): + return self.name in dtype.STANDARD_FP_TYPES + + def is_int_signed(self): + return self.name in dtype.SINT_TYPES + + def is_int_unsigned(self): + return self.name in dtype.UINT_TYPES + + def is_int(self): + return self.name in dtype.SINT_TYPES + dtype.UINT_TYPES + + def is_bool(self): + return self.is_int1() + + def kind(self): + # Return int value following the type ordering bool < integer < fp + if self.is_bool(): + return dtype.KIND.BOOLEAN + elif self.is_int(): + return dtype.KIND.INTEGRAL + else: + assert self.is_floating() + return dtype.KIND.FLOATING + + def get_int_max_value(self): + if self.is_int_signed(): + return 2**(self.int_bitwidth - 1) - 1 + if self.is_int_unsigned(): + return 2**self.int_bitwidth - 1 + assert False + + def get_int_min_value(self): + if self.is_int_signed(): + return -2**(self.int_bitwidth - 1) + if self.is_int_unsigned(): + return 0 + assert False + + @staticmethod + def is_dtype(type_str): + return type_str in dtype.SINT_TYPES + dtype.UINT_TYPES + dtype.FP_TYPES + dtype.OTHER_TYPES + + @staticmethod + def is_void(): + raise RuntimeError("Not implemented") + + @staticmethod + def is_block(): + return False + + @staticmethod + def is_ptr(): + return False + + @staticmethod + def is_const(): + return False + + def __eq__(self, other) -> bool: + other = _unwrap_if_constexpr(other) + if not isinstance(other, dtype): + return False + return self.name == other.name + + def __hash__(self): + return hash((self.name, )) + + @property + def scalar(self): + return self + + def _flatten_ir_types(self, builder: ir.builder, out: List[ir.type]) -> None: + out.append(self.to_ir(builder)) + + def to_ir(self, builder: ir.builder) -> ir.type: + if self.name.startswith("fp8"): + if hasattr(builder, "options") and self.name not in builder.options.supported_fp8_dtypes: + raise ValueError(f'type {self} not supported in this architecture. ' + f'The supported fp8 dtypes are {builder.options.supported_fp8_dtypes}') + + if self.name == 'void': + return builder.get_void_ty() + elif self.name == 'int1': + return builder.get_int1_ty() + elif self.name in ('int8', 'uint8'): + return builder.get_int8_ty() + elif self.name in ('int16', 'uint16'): + return builder.get_int16_ty() + elif self.name in ('int32', 'uint32'): + return builder.get_int32_ty() + elif self.name in ('int64', 'uint64'): + return builder.get_int64_ty() + elif self.name == 'fp8e5': + return builder.get_fp8e5_ty() + elif self.name == 'fp8e5b16': + return builder.get_fp8e5b16_ty() + elif self.name == 'fp8e4nv': + return builder.get_fp8e4nv_ty() + elif self.name == 'fp8e4b8': + return builder.get_fp8e4b8_ty() + elif self.name == 'fp8e4b15': + return builder.get_fp8e4b15_ty() + elif self.name == 'fp16': + return builder.get_half_ty() + elif self.name == 'bf16': + return builder.get_bf16_ty() + elif self.name == 'fp32': + return builder.get_float_ty() + elif self.name == 'fp64': + return builder.get_double_ty() + raise ValueError(f'fail to convert {self} to ir type') + + def __str__(self): + return self.name + + def codegen_name(self): + if self.name.startswith("fp"): + return "float" + self.name[2:] + elif self.name.startswith("bf"): + return "bfloat" + self.name[2:] + else: + return self.name + + @property + def cache_key_part(self) -> str: + """See cache_key_part() in triton.cc.""" + return self.name + + def __repr__(self): + """Output of repr needs to be an evaluatable expression""" + return f'triton.language.{self.codegen_name()}' + + def _unflatten_ir(self, handles: List[ir.value], cursor: int) -> Tuple[base_value, int]: + return tensor(handles[cursor], self), cursor + 1 + + def mangle(self) -> str: + if self.is_int(): + SIGNED = dtype.SIGNEDNESS.SIGNED + prefix = 'i' if self.int_signedness == SIGNED else 'u' + return prefix + str(self.int_bitwidth) + if self.is_floating(): + return str(self) + if self.is_void(): + return 'V' + return super().mangle() + + def with_element_ty(self, element_ty: dtype): + assert not self.is_block() + return element_ty + + +# Some functions have a param named `dtype`, which shadows the `dtype` class. +# We can't change the param name because it is part of function's public API. +# Declare an alias so those functions can still reference the dtype class. +_DtypeClass = dtype + + +class pointer_type(dtype): + + def __init__(self, element_ty: dtype, address_space: int = 1, const: bool = False): + element_ty = _unwrap_if_constexpr(element_ty) + if not isinstance(element_ty, dtype): + raise TypeError(f'element_ty has type `{type(element_ty).__name__}`; expected `dtype`.') + self.element_ty = element_ty + self.address_space = address_space + self.const = const + self.name = f'pointer<{element_ty}>' if not const else f'const_pointer<{element_ty}>' + + def to_ir(self, builder: ir.builder) -> ir.pointer_type: + return builder.get_ptr_ty(self.element_ty.to_ir(builder), self.address_space) + + def __str__(self): + return self.name + + def __repr__(self): + return self.__str__() + + def is_ptr(self): + return True + + def is_const(self): + return self.const + + def __eq__(self, other) -> bool: + other = _unwrap_if_constexpr(other) + if not isinstance(other, pointer_type): + return False + return self.element_ty == other.element_ty and self.address_space == other.address_space and self.const == other.const + + @property + def scalar(self): + return self + + def mangle(self) -> str: + return f"P{self.element_ty.mangle()}" + + +class block_type(dtype): + + def __init__(self, element_ty: dtype, shape: List): + self.element_ty = element_ty + + # Note that block_type's shape is a list of int + # while tensor's shape is a list of constexpr. + assert (isinstance(shape, (list, tuple))) + + # shape can be empty ([]) when an input is a 0D tensor. + self.shape = tuple(_unwrap_shape(shape)) + if not self.shape: + raise TypeError('0d block_type is forbidden') + + self.numel = validate_block_shape(self.shape) + self.name = f'<{self.shape}, {self.element_ty}>' + + def to_ir(self, builder: ir.builder) -> ir.block_type: + return builder.get_block_ty(self.element_ty.to_ir(builder), self.shape) + + def __str__(self): + return self.name + + def __repr__(self): + return self.__str__() + + def is_block(self): + return True + + def get_block_shapes(self) -> Tuple[int]: + return self.shape + + def with_element_ty(self, scalar_ty: dtype) -> block_type: + return block_type(scalar_ty, self.shape) + + def __eq__(self, other) -> bool: + if not isinstance(other, block_type): + return False + return self.element_ty == other.element_ty and self.shape == other.shape + + @property + def scalar(self): + return self.element_ty + + @property + def nbytes(self): + return self.numel * (self.element_ty.primitive_bitwidth // 8) + + def mangle(self) -> str: + elt = self.scalar.mangle() + shape = '_'.join(map(str, self.shape)) + return f'{elt}S{shape}S' + + +class tuple_type(base_type): + + def __init__(self, types, fields=None): + self.types = types + self.fields = fields or [''] * len(types) + self.name = '[' + ','.join([f"{k}:{v}" for k, v in zip(self.fields, self.types)]) + ']' + + def __str__(self): + return self.name + + def __iter__(self): + return iter(self.types) + + def _flatten_ir_types(self, builder: ir.builder, out: List[ir.type]): + for ty in self.types: + if not isinstance(ty, constexpr): + ty._flatten_ir_types(builder, out) + + def __getitem__(self, index: int) -> dtype: + return self.types[index] + + def __eq__(self, other): + return type(self) is type(other) and self.types == other.types and self.fields == other.fields + + def _unflatten_ir(self, handles: List[ir.value], cursor: int) -> Tuple[tuple, int]: + values = [] + for ty in self.types: + value, cursor = ty._unflatten_ir(handles, cursor) + values.append(value) + return tuple(values, self), cursor + + def mangle(self): + return 'T' + '_'.join(ty.mangle() for ty in self.types) + 'T' + + +class slice_type(dtype): + + def __init__(self): + self.name = 'slice_type' + + +# scalar types +void = dtype('void') +int1 = dtype('int1') +int8 = dtype('int8') +int16 = dtype('int16') +int32 = dtype('int32') +int64 = dtype('int64') +uint8 = dtype('uint8') +uint16 = dtype('uint16') +uint32 = dtype('uint32') +uint64 = dtype('uint64') +float8e5 = dtype('fp8e5') +float8e5b16 = dtype('fp8e5b16') +float8e4nv = dtype('fp8e4nv') +float8e4b8 = dtype('fp8e4b8') +float8e4b15 = dtype('fp8e4b15') +float16 = dtype('fp16') +bfloat16 = dtype('bf16') +float32 = dtype('fp32') +float64 = dtype('fp64') +# pointer types +pi32_t = pointer_type(int32) + + +def get_int_dtype(bitwidth: int, signed: bool) -> dtype: + if bitwidth == 1: + return int1 + elif bitwidth == 8 and signed: + return int8 + elif bitwidth == 8 and not signed: + return uint8 + elif bitwidth == 16 and signed: + return int16 + elif bitwidth == 16 and not signed: + return uint16 + elif bitwidth == 32 and signed: + return int32 + elif bitwidth == 32 and not signed: + return uint32 + elif bitwidth == 64 and signed: + return int64 + elif bitwidth == 64 and not signed: + return uint64 + else: + raise ValueError(f'Unsupported bitwidth {bitwidth} and signedness {signed}') + + +# ----------------------- +# tensor +# ----------------------- + + +class tensor(base_value): + """Represents an N-dimensional array of values or pointers. + + :code:`tensor` is the fundamental data structure in Triton programs. Most + functions in :py:mod:`triton.language` operate on and return tensors. + + Most of the named member functions here are duplicates of the free functions + in :code:`triton.language`. For example, :code:`triton.language.sqrt(x)` is + equivalent to :code:`x.sqrt()`. + + :code:`tensor` also defines most of the magic/dunder methods, so you can + write :code:`x+y`, :code:`x << 2`, etc. + + .. rubric:: Constructors + .. + For some reason Sphinx includes __init__ before printing the full table + of methods. Not what I want, but I can't figure out how to fix it. Give + it its own section so it looks intentional. :) + """ + + def __init__(self, handle, type: dtype): + """Not called by user code.""" + super().__init__() + # IR handle + self.handle = handle + # Block shape + self.shape = type.shape if type.is_block() else () + self.numel = constexpr(math.prod(self.shape)) + self.type = type # Tensor type (can be block_type) + # Following the practice in pytorch, dtype is scalar type + self.dtype = type.scalar + self.shape = tuple([constexpr(s) for s in self.shape]) + + def _flatten_ir(self, handles: List[ir.value]) -> None: + handles.append(self.handle) + + def __str__(self) -> str: + # ex. "float32[16, 32]" + return str(self.dtype) + '[' + ', '.join(str(s) for s in self.shape) + ']' + + @builtin + def __add__(self, other, _semantic=None): + return add(self, other, sanitize_overflow=True, _semantic=_semantic) + + @builtin + def __radd__(self, other, _semantic=None): + return add(other, self, sanitize_overflow=True, _semantic=_semantic) + + @builtin + def __sub__(self, other, _semantic=None): + return sub(self, other, sanitize_overflow=True, _semantic=_semantic) + + @builtin + def __rsub__(self, other, _semantic=None): + return sub(other, self, sanitize_overflow=True, _semantic=_semantic) + + @builtin + def __mul__(self, other, _semantic=None): + return mul(self, other, sanitize_overflow=True, _semantic=_semantic) + + @builtin + def __rmul__(self, other, _semantic=None): + return mul(other, self, sanitize_overflow=True, _semantic=_semantic) + + @builtin + def __truediv__(self, other, _semantic=None): + other = _unwrap_if_constexpr(other) + return _semantic.truediv(self, other) + + @builtin + def __rtruediv__(self, other, _semantic=None): + other = _unwrap_if_constexpr(other) + return _semantic.truediv(other, self) + + @builtin + def __floordiv__(self, other, _semantic=None): + other = _unwrap_if_constexpr(other) + return _semantic.floordiv(self, other) + + @builtin + def __rfloordiv__(self, other, _semantic=None): + other = _unwrap_if_constexpr(other) + return _semantic.floordiv(other, self) + + @builtin + def __mod__(self, other, _semantic=None): + other = _unwrap_if_constexpr(other) + return _semantic.mod(self, other) + + @builtin + def __rmod__(self, other, _semantic=None): + other = _unwrap_if_constexpr(other) + return _semantic.mod(other, self) + + # unary operators + @builtin + def __neg__(self, _semantic=None): + return _semantic.minus(self) + + @builtin + def __invert__(self, _semantic=None): + return _semantic.invert(self) + + # bitwise operators + + @builtin + def __and__(self, other, _semantic=None): + other = _unwrap_if_constexpr(other) + return _semantic.and_(self, other) + + @builtin + def __rand__(self, other, _semantic=None): + other = _unwrap_if_constexpr(other) + return _semantic.and_(other, self) + + @builtin + def __or__(self, other, _semantic=None): + other = _unwrap_if_constexpr(other) + return _semantic.or_(self, other) + + @builtin + def __ror__(self, other, _semantic=None): + other = _unwrap_if_constexpr(other) + return _semantic.or_(other, self) + + @builtin + def __xor__(self, other, _semantic=None): + other = _unwrap_if_constexpr(other) + return _semantic.xor_(self, other) + + @builtin + def __rxor__(self, other, _semantic=None): + other = _unwrap_if_constexpr(other) + return _semantic.xor_(other, self) + + @builtin + def __lshift__(self, other, _semantic=None): + check_bit_width(self, other) + other = _unwrap_if_constexpr(other) + return _semantic.shl(self, other) + + @builtin + def __rlshift__(self, other, _semantic=None): + check_bit_width(other, self) + other = _unwrap_if_constexpr(other) + return _semantic.shl(other, self) + + @builtin + def __rshift__(self, other, _semantic=None): + check_bit_width(self, other) + other = _unwrap_if_constexpr(other) + if self.dtype.is_int_signed(): + return _semantic.ashr(self, other) + else: + return _semantic.lshr(self, other) + + @builtin + def __rrshift__(self, other, _semantic=None): + check_bit_width(other, self) + other = _unwrap_if_constexpr(other) + if self.dtype.is_int_signed(): + return _semantic.ashr(other, self) + else: + return _semantic.lshr(other, self) + + # > + @builtin + def __gt__(self, other, _semantic=None): + other = _semantic.to_tensor(other) + return _semantic.greater_than(self, other) + + @builtin + def __rgt__(self, other, _semantic=None): + other = _semantic.to_tensor(other) + return _semantic.greater_than(other, self) + + # >= + @builtin + def __ge__(self, other, _semantic=None): + other = _semantic.to_tensor(other) + return _semantic.greater_equal(self, other) + + @builtin + def __rge__(self, other, _semantic=None): + other = _semantic.to_tensor(other) + return _semantic.greater_equal(other, self) + + # < + @builtin + def __lt__(self, other, _semantic=None): + other = _semantic.to_tensor(other) + return _semantic.less_than(self, other) + + @builtin + def __rlt__(self, other, _semantic=None): + other = _semantic.to_tensor(other) + return _semantic.less_than(other, self) + + # <= + @builtin + def __le__(self, other, _semantic=None): + other = _semantic.to_tensor(other) + return _semantic.less_equal(self, other) + + @builtin + def __rle__(self, other, _semantic=None): + other = _semantic.to_tensor(other) + return _semantic.less_equal(other, self) + + # == + @builtin + def __eq__(self, other, _semantic=None): + other = _semantic.to_tensor(other) + return _semantic.equal(self, other) + + @builtin + def __req__(self, other, _semantic=None): + other = _semantic.to_tensor(other) + return _semantic.equal(other, self) + + @builtin + def __ne__(self, other, _semantic=None): + other = _semantic.to_tensor(other) + return _semantic.not_equal(self, other) + + @builtin + def __rne__(self, other, _semantic=None): + other = _semantic.to_tensor(other) + return _semantic.not_equal(other, self) + + @builtin + def logical_and(self, other, _semantic=None): + other = _semantic.to_tensor(other) + return _semantic.logical_and(self, other) + + @builtin + def logical_or(self, other, _semantic=None): + other = _semantic.to_tensor(other) + return _semantic.logical_or(self, other) + + # note: __not__ isn't actually a magic method in python + # but it's ok because our ASTVisitor handles it + @builtin + def __not__(self, _semantic=None): + return _semantic.not_(self) + + @builtin + def __getitem__(self, slices, _semantic=None): + if isinstance(slices, (builtins.slice, slice, constexpr)) or slices is None: + slices = [slices] + if isinstance(slices, tuple): + slices = slices.values + ret = self + for dim, sl in enumerate(slices): + if _unwrap_if_constexpr(sl) is None: + ret = _semantic.expand_dims(ret, dim) + elif isinstance(sl, (builtins.slice, slice)) and all( + _unwrap_if_constexpr(arg) is None for arg in (sl.start, sl.stop, sl.step)): + pass # an unsqueeze + else: + raise ValueError(f"unsupported tensor index: {sl}") + return ret + + @property + def T(self): + """Transposes a 2D tensor.""" + assert False, "Transposition must be created by the AST Visitor" + + @builtin + def to(self, dtype: dtype, fp_downcast_rounding: Optional[str] = None, bitcast: bool = False, _semantic=None): + """ + Alias for :py:func:`tensor.cast`. + """ + return cast(self, dtype, fp_downcast_rounding, bitcast, _semantic=_semantic) + + # Type stubs for functions added by the _tensor_member_fn decorator. + # (Unfortunately these can't be created automatically.) + # + # We couldn't write these definitions out even if we wanted to, because some + # of these functions are defined in standard.py. + def broadcast_to(self, *shape) -> tensor: + ... + + def trans(self, *dims) -> tensor: + ... + + def permute(self, *dims) -> tensor: + ... + + def split(self) -> tuple[tensor, tensor]: + ... + + def view(self, *shape) -> tensor: + ... + + def reshape(self, *shape) -> tensor: + ... + + def expand_dims(self, axis) -> tensor: + ... + + def cast(self, dtype, fp_downcast_rounding=None, bitcast=False) -> tensor: + ... + + def store(self, value, mask=None, boundary_check=(), cache_modifier="", eviction_policy="") -> tensor: + ... + + def advance(self, offsets) -> tensor: + ... + + def atomic_cas(self, cmp, val, sem=None, scope=None) -> tensor: + ... + + def atomic_xchg(self, val, mask=None, sem=None, scope=None) -> tensor: + ... + + def atomic_add(self, val, mask=None, sem=None, scope=None) -> tensor: + ... + + def atomic_max(self, val, mask=None, sem=None, scope=None) -> tensor: + ... + + def atomic_min(self, val, mask=None, sem=None, scope=None) -> tensor: + ... + + def atomic_and(self, val, mask=None, sem=None, scope=None) -> tensor: + ... + + def atomic_or(self, val, mask=None, sem=None, scope=None) -> tensor: + ... + + def atomic_xor(self, val, mask=None, sem=None, scope=None) -> tensor: + ... + + def exp(self) -> tensor: + ... + + def log(self) -> tensor: + ... + + def cos(self) -> tensor: + ... + + def sin(self) -> tensor: + ... + + def sqrt(self) -> tensor: + ... + + def rsqrt(self) -> tensor: + ... + + def abs(self) -> tensor: + ... + + def reduce(self, axis, combine_fn, keep_dims=False) -> tensor: + ... + + def associative_scan(self, axis, combine_fn, reverse=False) -> tensor: + ... + + def gather(self, indices, axis) -> tensor: + ... + + def histogram(self, num_bins) -> tensor: + ... + + def cdiv(self, div) -> tensor: + ... + + def sigmoid(self) -> tensor: + ... + + def softmax(self, dim=None, keep_dims=False, ieee_rounding=False) -> tensor: + ... + + def ravel(self) -> tensor: + ... + + def max(self, axis=None, return_indices=False, return_indices_tie_break_left=True, keep_dims=False) -> tensor: + ... + + def argmax(self, axis, tie_break_left=True, keep_dims=False) -> tensor: + ... + + def min(self, axis=None, return_indices=False, return_indices_tie_break_left=True, keep_dims=False) -> tensor: + ... + + def argmin(self, axis, tie_break_left=True, keep_dims=False) -> tensor: + ... + + def sum(self, axis=None, keep_dims=False, dtype=None) -> tensor: + ... + + def xor_sum(self, axis=None, keep_dims=False) -> tensor: + ... + + def reduce_or(self, axis=None, keep_dims=False) -> tensor: + ... + + def cumsum(self, axis=0, reverse=False) -> tensor: + ... + + def cumprod(self, axis=0, reverse=False) -> tensor: + ... + + def sort(self, dim: constexpr = None, descending: constexpr = CONSTEXPR_0) -> tensor: + ... + + def flip(self, dim=None) -> tensor: + ... + + +def _type_for_tuple_values(values, fields=None): + return tuple_type([constexpr_type(x) if isinstance(x, (int, float, dtype)) else x.type for x in values], fields) + + +class tuple(base_value): + + def __init__(self, args: Sequence, type: Optional[tuple_type] = None): + self.values = [i for i in args] + if isinstance(type, tuple_type): + self.type = type + elif type is not None: # make_template in ASTFunction.deserialize may pass us a list/tuple + self.type = tuple_type(type) + else: + self.type = _type_for_tuple_values(self.values) + + def __getitem__(self, idx: constexpr): + if isinstance(idx, int): + idx = constexpr(idx) + if isinstance(idx, constexpr): + return self.values[idx] + else: + assert isinstance(idx, (slice, builtins.slice)) + return tuple(self.values[idx.start:idx.stop:idx.step]) + + def __getattr__(self, name): + return self.values[self.type.fields.index(name)] + + # TODO: remove + def _setitem(self, idx, value): + idx = _unwrap_if_constexpr(idx) + assert isinstance(idx, int) + self.values[idx] = value + self.type = _type_for_tuple_values(self.values, self.type.fields) + + def __add__(self, other): + other = _normalize_tuple(other) + return tuple(self.values + other.values) + # return tuple(a + b for a, b in zip(self.values, other.values)) + + def __mul__(self, other): + assert isinstance(other, constexpr) + return tuple(self.values * other.value) + + def __eq__(self, other): + other = _normalize_tuple(other) + return constexpr(self.values == other.values) + + def __hash__(self): + return hash(builtins.tuple(self.values)) + + def __str__(self): + return str([str(x) for x in self.values]) + + def __iter__(self): + return iter(self.values) + + def __len__(self): + return len(self.values) + + def _flatten_ir(self, handles: List[ir.value]): + for v in self.values: + v._flatten_ir(handles) + + def __repr__(self): + return f"({', '.join(repr(x) for x in self.values)})" + + +class slice: + + def __init__(self, start, stop, step): + self.start = start + self.stop = stop + self.step = step + self.type = slice_type() + + +class tensor_descriptor_base_type(base_type): + + def __init__(self, block_type: block_type): + self.block_type = block_type + + def _unflatten_ir(self, handles: List[ir.value], cursor: int) -> Tuple[tensor_descriptor_base, int]: + value = tensor_descriptor_base(handles[cursor], self.block_type) + return value, cursor + 1 + + def _flatten_ir_types(self, builder: ir.builder, out: List[ir.type]) -> None: + is_signed = self.block_type.element_ty.is_int_signed() + out.append(builder.create_tensor_descriptor_type(self.block_type.to_ir(builder), is_signed)) + + def __str__(self) -> str: + # ex. "tensor_descriptor" + return f"tensor_descriptor<{self.block_type}>" + + def __eq__(self, other) -> bool: + if type(other) is not type(self): + return False + return self.block_type == other.block_type + + def __neq__(self, other) -> bool: + return not (self == other) + + def mangle(self) -> str: + return f"TD{self.block_type.mangle()}" + + +class tensor_descriptor_base(base_value): + """" + A tensor descriptor with unknown shape and strides + """ + + def __init__(self, handle, block_type: block_type): + """Not called by user code.""" + super().__init__() + + self.handle = handle # IR handle + self.type = tensor_descriptor_base_type(block_type) # Tensor type (block_type) + + def _flatten_ir(self, handles: List[ir.value]) -> None: + handles.append(self.handle) + + @property + def block_type(self): + return self.type.block_type + + @property + def block_shape(self): + return self.type.block_type.shape + + @property + def dtype(self): + return self.type.block_type.element_ty + + def __str__(self) -> str: + return str(self.type) + + @builtin + def load(self, offsets: Sequence[constexpr | tensor], _semantic=None) -> tensor: + """Load a block from the descriptor starting at the given element offsets. + + Values outside of the tensor bounds will be filled with zeros. + + :note: Offset must be a multiple of 16-bytes + """ + return _semantic.descriptor_load(self, offsets, "", "") + + @builtin + def store(self, offsets: Sequence[constexpr | tensor], value: tensor, _semantic=None) -> tensor: + """Store a block from the descriptor starting at the given element offsets. + + Values outside of the tensor bounds will be ignored. + + :note: Offset must be a multiple of 16-bytes + """ + return _semantic.descriptor_store(self, value, offsets) + + @builtin + def atomic_add(self, offsets: Sequence[constexpr | tensor], value: tensor, _semantic=None) -> tensor: + return _semantic.descriptor_atomic_add(self, value, offsets) + + @builtin + def atomic_min(self, offsets: Sequence[constexpr | tensor], value: tensor, _semantic=None) -> tensor: + return _semantic.descriptor_atomic_min(self, value, offsets) + + @builtin + def atomic_max(self, offsets: Sequence[constexpr | tensor], value: tensor, _semantic=None) -> tensor: + return _semantic.descriptor_atomic_max(self, value, offsets) + + @builtin + def atomic_and(self, offsets: Sequence[constexpr | tensor], value: tensor, _semantic=None) -> tensor: + return _semantic.descriptor_atomic_and(self, value, offsets) + + @builtin + def atomic_or(self, offsets: Sequence[constexpr | tensor], value: tensor, _semantic=None) -> tensor: + return _semantic.descriptor_atomic_or(self, value, offsets) + + @builtin + def atomic_xor(self, offsets: Sequence[constexpr | tensor], value: tensor, _semantic=None) -> tensor: + return _semantic.descriptor_atomic_xor(self, value, offsets) + + @builtin + def gather(self, *args, _semantic=None) -> tensor: + """Gather multiple descriptors worth of data""" + assert len(args) == 2, f"descriptor gather only supports 2D indexing, but got {len(args)}" + x_offsets = args[0] + y_offset = args[1] + return _semantic.descriptor_gather(self, x_offsets, y_offset, "", "") + + @builtin + def scatter(self, value, *args, _semantic=None) -> tensor: + """Scatter multiple descriptors worth of data""" + assert len(args) == 2, f"descriptor scatter only supports 2D indexing, but got {len(args)}" + x_offsets = args[0] + y_offset = args[1] + return _semantic.descriptor_scatter(self, value, x_offsets, y_offset) + + +class tensor_descriptor_type(tensor_descriptor_base_type): + + def __init__(self, block_type: block_type, shape_type: tuple_type, strides_type: tuple_type): + self.block_type = block_type + self.shape_type = shape_type + self.strides_type = strides_type + + def _unflatten_ir(self, handles: List[ir.value], cursor: int) -> Tuple[tensor_descriptor_base, int]: + handle = handles[cursor] + cursor += 1 + shape, cursor = self.shape_type._unflatten_ir(handles, cursor) + strides, cursor = self.strides_type._unflatten_ir(handles, cursor) + shape = shape.values + strides = strides.values + value = tensor_descriptor(handle, shape, strides, self.block_type) + return value, cursor + + def _flatten_ir_types(self, builder: ir.builder, out: List[ir.type]) -> None: + super()._flatten_ir_types(builder, out) + self.shape_type._flatten_ir_types(builder, out) + self.strides_type._flatten_ir_types(builder, out) + + def __eq__(self, other): + return super().__eq__(other) and (self.shape_type == other.shape_type) and (self.strides_type + == other.strides_type) + + +class tensor_descriptor(tensor_descriptor_base): + """A descriptor representing a tensor in global memory. + """ + + def __init__(self, handle, shape: List[tensor], strides: List[tensor], block_type: block_type): + """Not called by user code.""" + # IR handle + super().__init__(handle, block_type) + # Global shape + self.shape = tuple(shape) + self.strides = tuple(strides) + self.type = tensor_descriptor_type( + block_type, + shape_type=self.shape.type, + strides_type=self.strides.type, + ) + + def _flatten_ir(self, handles: List[ir.value]) -> None: + handles.append(self.handle) + self.shape._flatten_ir(handles) + self.strides._flatten_ir(handles) + + +# ----------------------- +# aggregate +# ----------------------- + + +@dataclass(frozen=True) +class _aggregate_type(base_type): + """A generic base type for all Triton aggregate types. + + This class contains a reference to the original user-defined Python class + and a list of class fields with their Triton types. + """ + + base_cls: type + fields: List[Tuple[str, base_type]] + + def _unflatten_ir(self, handles: List[ir.value], cursor: int) -> Tuple[ir.value, int]: + instance = self.base_cls._get_instance() + for name, ty in self.fields: + value, cursor = ty._unflatten_ir(handles, cursor) + setattr(instance, name, value) + return instance, cursor + + def _flatten_ir_types(self, builder: ir.builder, out: List[ir.type]) -> None: + for name, ty in self.fields: + ty._flatten_ir_types(builder, out) + + def mangle(self) -> str: + name = f"{self.base_cls.__module__}.{self.base_cls.__qualname__}" + fields = [ty.mangle() for (name, ty) in self.fields] + return f"{name}<{', '.join(fields)}>" + + +def _aggregate(cls): + + # Define the wrapped Triton value type. + class aggregate_value(base_value): + __triton_builtin__ = True + __triton_aggregate__ = True + + @classmethod + def _get_instance(this_cls): + return super().__new__(this_cls) + + def __new__(this_cls, *args, _semantic=None, _generator=None, **kwargs): + # Call into the user-defined constructor. + instance = this_cls._get_instance() + extra_kwargs = {} + if isinstance(cls.__init__, JITCallable): + # raise ValueError(f"{cls.__name__}.__init__ cannot be a @triton.jit function") + pass + else: + if "_semantic" in inspect.signature(cls.__init__).parameters: + extra_kwargs["_semantic"] = _semantic + if "_generator" in inspect.signature(cls.__init__).parameters: + extra_kwargs["_generator"] = _generator + cls.__init__(instance, *args, **extra_kwargs, **kwargs) + + # Require that the user-defined constructor initialized all fields. + for name in cls.__annotations__.keys(): + if not hasattr(instance, name): + raise AttributeError(f"constructor for {cls.__name__} did not initialize attribute '{name}'") + + return instance + + # Only allow setting attributes defined in the class annotations. + def __setattr__(self, name, value): + if name not in cls.__annotations__: + raise AttributeError(f"{cls.__name__} has no attribute '{name}'") + if not isinstance(value, cls.__annotations__[name]): + raise TypeError(f"Expected {cls.__annotations__[name]} for attribute '{name}', got {type(value)}") + super().__setattr__(name, value) + + def _flatten_ir(self, handles: List[ir.value]) -> None: + for name in cls.__annotations__.keys(): + getattr(self, name)._flatten_ir(handles) + + @property + def type(self): + return _aggregate_type(aggregate_value, + [(name, getattr(self, name).type) for name in cls.__annotations__.keys()]) + + hash_attrs = [cls.__init__] + + for (name, member) in inspect.getmembers(cls): + if inspect.isfunction(member) or inspect.ismethod(member) or isinstance(member, JITCallable): + if name != "__init__": + setattr(aggregate_value, name, member) + hash_attrs.append(member) + + aggregate_value.hash_attrs = hash_attrs + aggregate_value.__name__ = cls.__name__ + aggregate_value.__module__ = cls.__module__ + aggregate_value.__qualname__ = cls.__qualname__ + aggregate_value.__doc__ = cls.__doc__ + + return aggregate_value + + +# ----------------------- +# SPMD Programming Model +# ----------------------- + + +@builtin +def program_id(axis, _semantic=None): + """ + Returns the id of the current program instance along the given :code:`axis`. + + :param axis: The axis of the 3D launch grid. Must be 0, 1 or 2. + :type axis: int + """ + # if axis == -1: + # pid0 = _semantic.program_id(0) + # pid1 = _semantic.program_id(1) + # pid2 = _semantic.program_id(2) + # npg0 = _semantic.num_programs(0) + # npg1 = _semantic.num_programs(1) + # return pid0 + pid1*npg0 + pid2*npg0*npg1 + axis = _unwrap_if_constexpr(axis) + return _semantic.program_id(axis) + + +@builtin +def num_programs(axis, _semantic=None): + """ + Returns the number of program instances launched along the given :code:`axis`. + + :param axis: The axis of the 3D launch grid. Must be 0, 1 or 2. + :type axis: int + """ + axis = _unwrap_if_constexpr(axis) + return _semantic.num_programs(axis) + + +# ----------------------- +# Block Initialization +# ----------------------- + + +@builtin +def arange(start, end, _semantic=None): + start = _unwrap_if_constexpr(start) + end = _unwrap_if_constexpr(end) + return _semantic.arange(start, end) + + +arange.__doc__ = f""" + Returns contiguous values within the half-open interval :code:`[start, + end)`. :code:`end - start` must be less than or equal to + :code:`TRITON_MAX_TENSOR_NUMEL = {TRITON_MAX_TENSOR_NUMEL}` + + :param start: Start of the interval. Must be a power of two. + :type start: int32 + :param end: End of the interval. Must be a power of two greater than + :code:`start`. + :type end: int32 +""" + + +def _unwrap_shape(shape): + shape = _unwrap_if_constexpr(shape) + return [_unwrap_if_constexpr(s) for s in shape] + + +def _shape_check_impl(shape): + shape = _unwrap_shape(shape) + validate_block_shape(shape) + return shape + + +@builtin +def full(shape, value, dtype, _semantic=None): + """ + Returns a tensor filled with the scalar value for the given :code:`shape` and :code:`dtype`. + + :param shape: Shape of the new array, e.g., (8, 16) or (8, ) + :type shape: tuple of ints + :param value: A scalar value to fill the array with + :type value: scalar + :param dtype: Data type of the new array, e.g., :code:`tl.float16` + :type dtype: tl.dtype + """ + shape = _shape_check_impl(shape) + value = _unwrap_if_constexpr(value) + dtype = _unwrap_if_constexpr(dtype) + return _semantic.full(shape, value, dtype) + + +# ----------------------- +# Shape Manipulation +# ----------------------- + + +@builtin +def broadcast(input, other, _semantic=None): + """ + Tries to broadcast the two given blocks to a common compatible shape. + + :param input: The first input tensor. + :type input: Block + :param other: The second input tensor. + :type other: Block + """ + return _semantic.broadcast_impl_value(input, other) + + +@_tensor_member_fn +@builtin +def broadcast_to(input, *shape, _semantic=None): + """ + Tries to broadcast the given tensor to a new :code:`shape`. + + :param input: The input tensor. + :type input: Block + :param shape: The desired shape. + :type shape: + + :code:`shape` can be passed as a tuple or as individual parameters: :: + + # These are equivalent + broadcast_to(x, (32, 32)) + broadcast_to(x, 32, 32) + """ + shape = _shape_check_impl(_unwrap_iterable(shape)) + return _semantic.broadcast_impl_shape(input, shape) + + +@_tensor_member_fn +@builtin +def trans(input: tensor, *dims, _semantic=None): + """ + Permutes the dimensions of a tensor. + + If the parameter :code:`dims` is not specified, the function defaults to + swapping the last two axes, thereby performing an (optionally batched) + 2D transpose. + + :param input: The input tensor. + :param dims: The desired ordering of dimensions. For example, + :code:`(2, 1, 0)` reverses the order dims in a 3D tensor. + + :code:`dims` can be passed as a tuple or as individual parameters: :: + + # These are equivalent + trans(x, (2, 1, 0)) + trans(x, 2, 1, 0) + + :py:func:`permute` is equivalent to this function, except it doesn't + have the special case when no permutation is specified. + """ + dims = _unwrap_iterable(dims) + if not dims: + n = len(input.shape) + if n < 2: + raise ValueError("tl.trans invoked with a 0- or 1-dimensional tensor") + dims = list(builtins.range(n - 2)) + [n - 1, n - 2] + return _semantic.permute(input, dims) + + +@_tensor_member_fn +@builtin +def permute(input, *dims, _semantic=None): + """ + Permutes the dimensions of a tensor. + + :param input: The input tensor. + :type input: Block + :param dims: The desired ordering of dimensions. For example, + :code:`(2, 1, 0)` reverses the order dims in a 3D tensor. + + :code:`dims` can be passed as a tuple or as individual parameters: :: + + # These are equivalent + permute(x, (2, 1, 0)) + permute(x, 2, 1, 0) + + :py:func:`trans` is equivalent to this function, except when + :code:`dims` is empty, it tries to swap the last two axes. + """ + dims = _unwrap_iterable(dims) + return _semantic.permute(input, dims) + + +@builtin +def cat(input, other, can_reorder=False, _semantic=None): + """ + Concatenate the given blocks + + :param input: The first input tensor. + :type input: Tensor + :param other: The second input tensor. + :type other: Tensor + :param reorder: Compiler hint. If true, the compiler is + allowed to reorder elements while concatenating inputs. Only use if the + order does not matter (e.g., result is only used in reduction ops). + Current implementation of `cat` supports only can_reorder=True. + """ + return _semantic.cat(input, other, can_reorder) + + +@builtin +def join(a, b, _semantic=None): + """ + Join the given tensors in a new, minor dimension. + + For example, given two tensors of shape (4,8), produces a new tensor of + shape (4,8,2). Given two scalars, returns a tensor of shape (2). + + The two inputs are broadcasted to be the same shape. + + If you want to join more than two elements, you can use multiple calls to + this function. This reflects the constraint in Triton that tensors must + have power-of-two sizes. + + join is the inverse of split. + + :param a: The first input tensor. + :type a: Tensor + :param b: The second input tensor. + :type b: Tensor + """ + return _semantic.join(a, b) + + +def _unsplat(x, _semantic=None, _generator=None): + """ + Convert a single-element tensor to a scalar. + """ + if len(x.shape) == 0: + return x + numel = 1 + for d in x.shape: + numel *= d + assert numel == 1, "can only unsplat single-element tensors" + return _semantic.unsplat(x) + + +@_tensor_member_fn +@builtin +def split(a, _semantic=None, _generator=None) -> tuple[tensor, tensor]: + """ + Split a tensor in two along its last dim, which must have size 2. + + For example, given a tensor of shape (4,8,2), produces two tensors of shape + (4,8). Given a tensor of shape (2), returns two scalars. + + If you want to split into more than two pieces, you can use multiple calls + to this function (probably plus calling reshape). This reflects the + constraint in Triton that tensors must have power-of-two sizes. + + split is the inverse of join. + + :param a: The tensor to split. + :type a: Tensor + """ + # If len(a.shape) == 1, i.e. a.shape == [2], we should return two scalars. + # But _semantic.split can only handle returning tensors. Work around this by + # expanding the input to shape [1,2] and then reducing the result. + was_rank_1 = len(a.shape) == 1 + if was_rank_1: + a = _semantic.expand_dims(a, 0) + + out_lhs, out_rhs = _semantic.split(a) + + if was_rank_1: + # Currently `reduce` is the best way to convert a tensor of shape [1] to a scalar. + out_lhs = _unsplat(out_lhs, _semantic=_semantic, _generator=_generator) + out_rhs = _unsplat(out_rhs, _semantic=_semantic, _generator=_generator) + + return out_lhs, out_rhs + + +@_tensor_member_fn +@builtin +def view(input, *shape, _semantic=None): + """ + Returns a tensor with the same elements as `input` but a different shape. + The order of the elements may not be preserved. + + :param input: The input tensor. + :type input: Block + :param shape: The desired shape. + + :code:`shape` can be passed as a tuple or as individual parameters: :: + + # These are equivalent + view(x, (32, 32)) + view(x, 32, 32) + """ + warn("view is deprecated, please use reshape with can_reorder being true.") + shape = _shape_check_impl(_unwrap_iterable(shape)) + return _semantic.reshape(input, shape, can_reorder=True) + + +@_tensor_member_fn +@builtin +def item(input, _semantic=None, _generator=None): + """ + Converts a single-element tensor into a scalar. + """ + return _unsplat(input, _semantic=_semantic, _generator=_generator) + + +@_tensor_member_fn +@builtin +def reshape(input, *shape, can_reorder=False, _semantic=None, _generator=None): + """ + Returns a tensor with the same number of elements as input but with the + provided shape. + + :param input: The input tensor. + :type input: Block + :param shape: The new shape. + + :code:`shape` can be passed as a tuple or as individual parameters: :: + + # These are equivalent + reshape(x, (32, 32)) + reshape(x, 32, 32) + """ + shape = _shape_check_impl(_unwrap_iterable(shape)) + if len(shape) == 0: + return _unsplat(input, _semantic=_semantic, _generator=_generator) + return _semantic.reshape(input, shape, can_reorder) + + +def _wrap_axis(axis, ndim): + if not (-ndim <= axis < ndim): + raise ValueError(f"invalid axis {axis}. Expected {-ndim} <= axis < {ndim}") + + return axis if axis >= 0 else axis + ndim + + +@_tensor_member_fn +@builtin +def expand_dims(input, axis, _semantic=None): + """ + Expand the shape of a tensor, by inserting new length-1 dimensions. + + Axis indices are with respect to the resulting tensor, so + ``result.shape[axis]`` will be 1 for each axis. + + :param input: The input tensor. + :type input: tl.tensor + :param axis: The indices to add new axes + :type axis: int | Sequence[int] + + """ + input = _semantic.to_tensor(input) + axis = _unwrap_if_constexpr(axis) + axes = list(axis) if isinstance(axis, (Sequence, tuple)) else [axis] + new_ndim = len(input.shape) + len(axes) + axes = [_wrap_axis(_unwrap_if_constexpr(d), new_ndim) for d in axes] + + if len(set(axes)) != len(axes): + raise ValueError(f"expand_dims received duplicate axes, normalized axes = {axes}") + + ret = input + for a in sorted(axes): + ret = _semantic.expand_dims(ret, a) + return ret + + +@_tensor_member_fn +@builtin +def cast(input, dtype: dtype, fp_downcast_rounding: Optional[str] = None, bitcast: bool = False, _semantic=None): + """ + Casts a tensor to the given :code:`dtype`. + + :param dtype: The target data type. + :type dtype: tl.dtype + :param fp_downcast_rounding: The rounding mode for downcasting + floating-point values. This parameter is only used when self is a + floating-point tensor and dtype is a floating-point type with a + smaller bitwidth. Supported values are :code:`"rtne"` (round to + nearest, ties to even) and :code:`"rtz"` (round towards zero). + :type fp_downcast_rounding: str, optional + :param bitcast: If true, the tensor is bitcasted to the given + :code:`dtype`, instead of being numerically casted. + :type bitcast: bool, optional + """ + input = _semantic.to_tensor(input) + dtype = _unwrap_if_constexpr(dtype) + fp_downcast_rounding = _unwrap_if_constexpr(fp_downcast_rounding) + bitcast = _unwrap_if_constexpr(bitcast) + if bitcast: + return _semantic.bitcast(input, dtype) + return _semantic.cast(input, dtype, fp_downcast_rounding) + + +# ----------------------- +# Linear Algebra +# ----------------------- + + +@builtin +def dot(input, other, acc=None, input_precision=None, allow_tf32=None, max_num_imprecise_acc=None, out_dtype=float32, + _semantic=None): + """ + Returns the matrix product of two blocks. + + The two blocks must both be two-dimensional or three-dimensional and have compatible inner dimensions. + For three-dimensional blocks, `tl.dot` performs the batched matrix product, + where the first dimension of each block represents the batch dimension. + + :param input: The first tensor to be multiplied. + :type input: 2D or 3D tensor of scalar-type in {:code:`int8`, :code:`float8_e5m2`, :code:`float16`, :code:`bfloat16`, :code:`float32`} + :param other: The second tensor to be multiplied. + :type other: 2D or 3D tensor of scalar-type in {:code:`int8`, :code:`float8_e5m2`, :code:`float16`, :code:`bfloat16`, :code:`float32`} + :param acc: The accumulator tensor. If not None, the result is added to this tensor. + :type acc: 2D or 3D tensor of scalar-type in {:code:`float16`, :code:`float32`, :code:`int32`} + :param input_precision: How to exercise the Tensor Cores for f32 x f32. If + the device does not have Tensor Cores or the inputs are not of dtype f32, + this option is ignored. For devices that do have tensor cores, the + default precision is tf32. + :type input_precision: string. Available options for nvidia: :code:`"tf32"`, :code:`"tf32x3"`, :code:`"ieee"`. Default: :code:`"tf32"`. Available options for amd: :code:`"ieee"`, (CDNA3 only) :code:`"tf32"`. + :param allow_tf32: *Deprecated.* If true, input_precision is set to "tf32". + Only one of :code:`input_precision` and :code:`allow_tf32` can be + specified (i.e. at least one must be :code:`None`). + """ + assert input_precision is None or allow_tf32 is None, "Only one of input_precision and allow_tf32 can be specified" + if input_precision is None: + supports_tf32 = "tf32" in _semantic.builder.options.allowed_dot_input_precisions + input_precision = knobs.language.fp32_default or ("tf32" if (supports_tf32 and + (allow_tf32 or allow_tf32 is None)) else "ieee") + + input_precision = _unwrap_if_constexpr(input_precision) + out_dtype = _unwrap_if_constexpr(out_dtype) + max_num_imprecise_acc = _unwrap_if_constexpr(max_num_imprecise_acc) + acc = _unwrap_if_constexpr(acc) + + # check shapes make sense: + a_shape = list(input.shape) + b_shape = list(other.shape) + assert len(a_shape) == len(b_shape) >= 2, "input and other must have equal ranks >= 2" + assert a_shape[:-2] == b_shape[:-2], "input and other must have equal batch shapes" + assert a_shape[-1] == b_shape[-2], "input and other must have equal reduction dimensions" + + # compute shape of accumulator: + c_shape = a_shape[:-1] + [b_shape[-1]] + if acc is not None: + assert list(acc.shape) == c_shape, "accumulator shape is incompatible" + rank = len(c_shape) + + if rank >= 4: + batch_size = 1 + for i in builtins.range(rank - 2): + batch_size *= c_shape[i] + input = _semantic.reshape(input, [batch_size] + a_shape[-2:], can_reorder=False) + other = _semantic.reshape(other, [batch_size] + b_shape[-2:], can_reorder=False) + if acc is not None: + acc = _semantic.reshape(acc, [batch_size] + c_shape[-2:], can_reorder=False) + + res = _semantic.dot(input, other, acc, input_precision, max_num_imprecise_acc, out_dtype) + + if rank >= 4: + res = _semantic.reshape(res, c_shape, can_reorder=False) + + assert list(res.shape) == c_shape, "output shape is unexpected" + return res + + +@builtin +def dot_scaled(lhs, lhs_scale, lhs_format, rhs, rhs_scale, rhs_format, acc=None, fast_math=False, lhs_k_pack=True, + rhs_k_pack=True, out_dtype=float32, _semantic=None): + """ + Returns the matrix product of two blocks in microscaling format. + + lhs and rhs use microscaling formats described here: + https://www.opencompute.org/documents/ocp-microscaling-formats-mx-v1-0-spec-final-pdf + + Software emulation enables targeting hardware architectures without native microscaling + operation support. Right now for such case, microscaled lhs/rhs are upcasted to + :code:`bf16` element type beforehand for dot computation, with one exception: + for AMD CDNA3 specifically, if one of the inputs is of :code:`fp16` element type, + the other input is also upcasted to :code:`fp16` element type instead. + This behavior is experimental and may be subject to change in the future. + + :param lhs: The first tensor to be multiplied. + :type lhs: 2D tensor representing fp4, fp8 or bf16 elements. Fp4 elements are packed into uint8 inputs with the first element in lower bits. Fp8 are stored as uint8 or the corresponding fp8 type. + :param lhs_scale: Scale factor for lhs tensor. Shape should be [M, K//group_size] when lhs is [M, K], where group_size is 32 if scales type are `e8m0`. + :type lhs_scale: e8m0 type represented as an uint8 tensor, or None. + :param lhs_format: format of the lhs tensor. Available formats: {:code:`e2m1`, :code:`e4m3`, :code:`e5m2`, :code:`bf16`, :code:`fp16`}. + :type lhs_format: str + :param rhs: The second tensor to be multiplied. + :type rhs: 2D tensor representing fp4, fp8 or bf16 elements. Fp4 elements are packed into uint8 inputs with the first element in lower bits. Fp8 are stored as uint8 or the corresponding fp8 type. + :param rhs_scale: Scale factor for rhs tensor. Shape should be [N, K//group_size] where rhs is [K, N]. + Important: Do NOT transpose rhs_scale + :type rhs_scale: e8m0 type represented as an uint8 tensor, or None. + :param rhs_format: format of the rhs tensor. Available formats: {:code:`e2m1`, :code:`e4m3`, :code:`e5m2`, :code:`bf16`, :code:`fp16`}. + :type rhs_format: str + :param acc: The accumulator tensor. If not None, the result is added to this tensor. + :param lhs_k_pack: If false, the lhs tensor is packed into uint8 along M dimension. + :type lhs_k_pack: bool, optional + :param rhs_k_pack: If false, the rhs tensor is packed into uint8 along N dimension. + :type rhs_k_pack: bool, optional + """ + out_dtype = _unwrap_if_constexpr(out_dtype) + acc = _unwrap_if_constexpr(acc) + assert out_dtype == float32, "Only float32 is supported for out_dtype at the moment" + return _semantic.dot_scaled(lhs, lhs_scale, lhs_format, rhs, rhs_scale, rhs_format, acc, fast_math, lhs_k_pack, + rhs_k_pack, out_dtype) + + +# ----------------------- +# Non-Atomic Memory Operations +# ----------------------- + + +@builtin +def load(pointer, mask=None, other=None, boundary_check=(), padding_option="", cache_modifier="", eviction_policy="", + volatile=False, _semantic=None): + """ + Return a tensor of data whose values are loaded from memory at location defined by `pointer`: + + (1) If `pointer` is a single element pointer, a scalar is be loaded. In + this case: + + - `mask` and `other` must also be scalars, + - `other` is implicitly typecast to `pointer.dtype.element_ty`, and + - `boundary_check` and `padding_option` must be empty. + + (2) If `pointer` is an N-dimensional tensor of pointers, an + N-dimensional tensor is loaded. In this case: + + - `mask` and `other` are implicitly broadcast to `pointer.shape`, + - `other` is implicitly typecast to `pointer.dtype.element_ty`, and + - `boundary_check` and `padding_option` must be empty. + + (3) If `pointer` is a block pointer defined by `make_block_ptr`, a + tensor is loaded. In this case: + + - `mask` and `other` must be `None`, and + - `boundary_check` and `padding_option` can be specified to control the behavior of out-of-bound access. + + :param pointer: Pointer to the data to be loaded + :type pointer: `triton.PointerType`, or block of `dtype=triton.PointerType` + :param mask: if `mask[idx]` is false, do not load the data at address `pointer[idx]` + (must be `None` with block pointers) + :type mask: Block of `triton.int1`, optional + :param other: if `mask[idx]` is false, return `other[idx]` + :type other: Block, optional + :param boundary_check: tuple of integers, indicating the dimensions which should do the boundary check + :type boundary_check: tuple of ints, optional + :param padding_option: should be one of {"", "zero", "nan"}, the padding value to use while out of bounds. "" means an undefined value. + :param cache_modifier: changes cache option in NVIDIA PTX + :type cache_modifier: str, optional, should be one of {"", ".ca", ".cg", ".cv"}, where ".ca" stands for + cache at all levels, ".cg" stands for cache at global level (cache in L2 and below, not L1), + and ".cv" means don’t cache and fetch again. see + `cache operator `_ for more details. + :param eviction_policy: changes eviction policy in NVIDIA PTX + :type eviction_policy: str, optional + :param volatile: changes volatile option in NVIDIA PTX + :type volatile: bool, optional + """ + # `mask` and `other` can be constexpr + mask = _unwrap_if_constexpr(mask) + other = _unwrap_if_constexpr(other) + if mask is not None: + mask = _semantic.to_tensor(mask) + if other is not None: + other = _semantic.to_tensor(other) + padding_option = _unwrap_if_constexpr(padding_option) + cache_modifier = _unwrap_if_constexpr(cache_modifier) + eviction_policy = _unwrap_if_constexpr(eviction_policy) + volatile = _unwrap_if_constexpr(volatile) + return _semantic.load(pointer, mask, other, boundary_check, padding_option, cache_modifier, eviction_policy, + volatile) + + +@builtin +def load_tensor_descriptor(desc: tensor_descriptor_base, offsets: Sequence[constexpr | tensor], + _semantic=None) -> tensor: + """Load a block of data from a tensor descriptor.""" + return desc.load(offsets, _semantic=_semantic) + + +@builtin +def store_tensor_descriptor(desc: tensor_descriptor_base, offsets: Sequence[constexpr | tensor], value: tensor, + _semantic=None) -> tensor: + """Store a block of data to a tensor descriptor.""" + return desc.store(offsets, value, _semantic=_semantic) + + +@_tensor_member_fn +@builtin +def store(pointer, value, mask=None, boundary_check=(), cache_modifier="", eviction_policy="", _semantic=None): + """ + Store a tensor of data into memory locations defined by `pointer`. + + (1) If `pointer` is a single element pointer, a scalar is stored. In + this case: + + - `mask` must also be scalar, and + - `boundary_check` and `padding_option` must be empty. + + (2) If `pointer` is an N-dimensional tensor of pointers, an + N-dimensional block is stored. In this case: + + - `mask` is implicitly broadcast to `pointer.shape`, and + - `boundary_check` must be empty. + + (3) If `pointer` is a block pointer defined by `make_block_ptr`, a block + of data is stored. In this case: + + - `mask` must be None, and + - `boundary_check` can be specified to control the behavior of out-of-bound access. + + `value` is implicitly broadcast to `pointer.shape` and typecast to `pointer.dtype.element_ty`. + + :param pointer: The memory location where the elements of `value` are stored + :type pointer: `triton.PointerType`, or block of `dtype=triton.PointerType` + :param value: The tensor of elements to be stored + :type value: Block + :param mask: If `mask[idx]` is false, do not store `value[idx]` at `pointer[idx]` + :type mask: Block of triton.int1, optional + :param boundary_check: tuple of integers, indicating the dimensions which should do the boundary check + :type boundary_check: tuple of ints, optional + :param cache_modifier: changes cache option in NVIDIA PTX + :type cache_modifier: str, optional, should be one of {"", ".wb", ".cg", ".cs", ".wt"}, where ".wb" stands for + cache write-back all coherent levels, ".cg" stands for cache global, ".cs" stands for cache streaming, ".wt" + stands for cache write-through, see `cache operator `_ for more details. + :param eviction_policy: changes eviction policy in NVIDIA PTX + :type eviction_policy: str, optional, should be one of {"", "evict_first", "evict_last"} + """ + # `value` can be constexpr + value = _semantic.to_tensor(value) + mask = _unwrap_if_constexpr(mask) + if mask is not None: + mask = _semantic.to_tensor(mask) + cache_modifier = _unwrap_if_constexpr(cache_modifier) + eviction_policy = _unwrap_if_constexpr(eviction_policy) + return _semantic.store(pointer, value, mask, boundary_check, cache_modifier, eviction_policy) + + +@builtin +def make_block_ptr(base: tensor, shape, strides, offsets, block_shape, order, _semantic=None): + """ + Returns a pointer to a block in a parent tensor + + :param base: The base pointer to the parent tensor + :param shape: The shape of the parent tensor + :param strides: The strides of the parent tensor + :param offsets: The offsets to the block + :param block_shape: The shape of the block + :param order: The order of the original data format + """ + return _semantic.make_block_ptr(base, shape, strides, offsets, block_shape, order) + + +@must_use_result( + "Note that tl.advance does not have any side effects. To move the block pointer, you need to assign the result of tl.advance to a variable." +) +@_tensor_member_fn +@builtin +def advance(base, offsets, _semantic=None): + """ + Advance a block pointer + + :param base: the block pointer to advance + :param offsets: the offsets to advance, a tuple by dimension + """ + return _semantic.advance(base, offsets) + + +@builtin +def make_tensor_descriptor( + base: tensor, + shape: List[tensor], + strides: List[tensor], + block_shape: List[constexpr], + padding_option="zero", + _semantic=None, +) -> tensor_descriptor: + """Make a tensor descriptor object + + :param base: the base pointer of the tensor, must be 16-byte aligned + :param shape: A list of non-negative integers representing the tensor shape + :param strides: A list of tensor strides. Leading dimensions must be multiples + of 16-byte strides and the last dimension must be contiguous. + :param block_shape: The shape of block to be loaded/stored from global memory + + Notes + ***** + On NVIDIA GPUs with TMA support, this will result in a TMA descriptor object + and loads and stores from the descriptor will be backed by the TMA hardware. + + Currently only 2-5 dimensional tensors are supported. + + Example + ******* + .. code-block:: python + + @triton.jit + def inplace_abs(in_out_ptr, M, N, M_BLOCK: tl.constexpr, N_BLOCK: tl.constexpr): + desc = tl.make_tensor_descriptor( + in_out_ptr, + shape=[M, N], + strides=[N, 1], + block_shape=[M_BLOCK, N_BLOCK], + ) + + moffset = tl.program_id(0) * M_BLOCK + noffset = tl.program_id(1) * N_BLOCK + + value = desc.load([moffset, noffset]) + desc.store([moffset, noffset], tl.abs(value)) + + # TMA descriptors require a global memory allocation + def alloc_fn(size: int, alignment: int, stream: Optional[int]): + return torch.empty(size, device="cuda", dtype=torch.int8) + + triton.set_allocator(alloc_fn) + + M, N = 256, 256 + x = torch.randn(M, N, device="cuda") + M_BLOCK, N_BLOCK = 32, 32 + grid = (M / M_BLOCK, N / N_BLOCK) + inplace_abs[grid](x, M, N, M_BLOCK, N_BLOCK) + + """ + + padding_option = _unwrap_if_constexpr(padding_option) + return _semantic.make_tensor_descriptor(base, shape, strides, block_shape, padding_option) + + +# ----------------------- +# Atomic Memory Operations +# ----------------------- + + +def _add_atomic_docstr(name: str, has_cmp: bool = False) -> Callable[[T], T]: + + def _decorator(func: T) -> T: + docstr = f""" + Performs an atomic {name} at the memory location specified by :code:`pointer`. + + Return the data stored at :code:`pointer` before the atomic operation. + + :param pointer: The memory locations to operate on + :type pointer: Block of dtype=triton.PointerDType""" + if has_cmp: + docstr += """ + :param cmp: The values expected to be found in the atomic object + :type cmp: Block of dtype=pointer.dtype.element_ty""" + docstr += """ + :param val: The values with which to perform the atomic operation + :type val: Block of dtype=pointer.dtype.element_ty + :param sem: Specifies the memory semantics for the operation. Acceptable values are "acquire", + "release", "acq_rel" (stands for "ACQUIRE_RELEASE"), and "relaxed". If not provided, + the function defaults to using "acq_rel" semantics. + :type sem: str, optional + :param scope: Defines the scope of threads that observe the synchronizing effect of the atomic operation. + Acceptable values are "gpu" (default), "cta" (cooperative thread array, thread block), or "sys" (stands for "SYSTEM"). The default value is "gpu". + :type scope: str, optional + """ + func.__doc__ = docstr + return func + + return _decorator + + +@_tensor_member_fn +@builtin +@_add_atomic_docstr("compare-and-swap", has_cmp=True) +def atomic_cas(pointer, cmp, val, sem=None, scope=None, _semantic=None): + cmp = _semantic.to_tensor(cmp) + val = _semantic.to_tensor(val) + sem = _unwrap_if_constexpr(sem) + scope = _unwrap_if_constexpr(scope) + return _semantic.atomic_cas(pointer, cmp, val, sem, scope) + + +@_tensor_member_fn +@builtin +@_add_atomic_docstr("exchange") +def atomic_xchg(pointer, val, mask=None, sem=None, scope=None, _semantic=None): + val = _semantic.to_tensor(val) + sem = _unwrap_if_constexpr(sem) + scope = _unwrap_if_constexpr(scope) + mask = _unwrap_if_constexpr(mask) + return _semantic.atomic_xchg(pointer, val, mask, sem, scope) + + +@_tensor_member_fn +@builtin +@_add_atomic_docstr("add") +def atomic_add(pointer, val, mask=None, sem=None, scope=None, _semantic=None): + val = _semantic.to_tensor(val) + sem = _unwrap_if_constexpr(sem) + scope = _unwrap_if_constexpr(scope) + mask = _unwrap_if_constexpr(mask) + return _semantic.atomic_add(pointer, val, mask, sem, scope) + + +@_tensor_member_fn +@builtin +@_add_atomic_docstr("max") +def atomic_max(pointer, val, mask=None, sem=None, scope=None, _semantic=None): + val = _semantic.to_tensor(val) + sem = _unwrap_if_constexpr(sem) + scope = _unwrap_if_constexpr(scope) + mask = _unwrap_if_constexpr(mask) + return _semantic.atomic_max(pointer, val, mask, sem, scope) + + +@_tensor_member_fn +@builtin +@_add_atomic_docstr("min") +def atomic_min(pointer, val, mask=None, sem=None, scope=None, _semantic=None): + val = _semantic.to_tensor(val) + sem = _unwrap_if_constexpr(sem) + scope = _unwrap_if_constexpr(scope) + mask = _unwrap_if_constexpr(mask) + return _semantic.atomic_min(pointer, val, mask, sem, scope) + + +@_tensor_member_fn +@builtin +@_add_atomic_docstr("logical and") +def atomic_and(pointer, val, mask=None, sem=None, scope=None, _semantic=None): + val = _semantic.to_tensor(val) + sem = _unwrap_if_constexpr(sem) + scope = _unwrap_if_constexpr(scope) + mask = _unwrap_if_constexpr(mask) + return _semantic.atomic_and(pointer, val, mask, sem, scope) + + +@_tensor_member_fn +@builtin +@_add_atomic_docstr("logical or") +def atomic_or(pointer, val, mask=None, sem=None, scope=None, _semantic=None): + val = _semantic.to_tensor(val) + sem = _unwrap_if_constexpr(sem) + scope = _unwrap_if_constexpr(scope) + mask = _unwrap_if_constexpr(mask) + return _semantic.atomic_or(pointer, val, mask, sem, scope) + + +@_tensor_member_fn +@builtin +@_add_atomic_docstr("logical xor") +def atomic_xor(pointer, val, mask=None, sem=None, scope=None, _semantic=None): + val = _semantic.to_tensor(val) + sem = _unwrap_if_constexpr(sem) + scope = _unwrap_if_constexpr(scope) + mask = _unwrap_if_constexpr(mask) + return _semantic.atomic_xor(pointer, val, mask, sem, scope) + + +# ----------------------- +# Conditioning +# ----------------------- + + +@builtin +def where(condition, x, y, _semantic=None): + """ + Returns a tensor of elements from either :code:`x` or :code:`y`, depending on :code:`condition`. + + Note that :code:`x` and :code:`y` are always evaluated regardless of the value of :code:`condition`. + + If you want to avoid unintended memory operations, use the :code:`mask` arguments in `triton.load` and `triton.store` instead. + + The shape of :code:`x` and :code:`y` are both broadcast to the shape of :code:`condition`. + :code:`x` and :code:`y` must have the same data type. + + :param condition: When True (nonzero), yield x, otherwise yield y. + :type condition: Block of triton.bool + :param x: values selected at indices where condition is True. + :param y: values selected at indices where condition is False. + """ + condition = _semantic.to_tensor(condition) + x = _unwrap_if_constexpr(x) + y = _unwrap_if_constexpr(y) + return _semantic.where(condition, x, y) + + +# ----------------------- +# Math +# ----------------------- + + +@builtin +def add(x, y, sanitize_overflow: constexpr = True, _semantic=None): + x = _unwrap_if_constexpr(x) + y = _unwrap_if_constexpr(y) + return _semantic.add(x, y, sanitize_overflow) + + +@builtin +def sub(x, y, sanitize_overflow: constexpr = True, _semantic=None): + x = _unwrap_if_constexpr(x) + y = _unwrap_if_constexpr(y) + return _semantic.sub(x, y, sanitize_overflow) + + +@builtin +def mul(x, y, sanitize_overflow: constexpr = True, _semantic=None): + x = _unwrap_if_constexpr(x) + y = _unwrap_if_constexpr(y) + return _semantic.mul(x, y, sanitize_overflow) + + +@builtin +def minimum(x, y, propagate_nan: constexpr = PropagateNan.NONE, _semantic=None): + """ + Computes the element-wise minimum of :code:`x` and :code:`y`. + + :param x: the first input tensor + :type x: Block + :param y: the second input tensor + :type y: Block + :param propagate_nan: whether to propagate NaN values. + :type propagate_nan: tl.PropagateNan + + .. seealso:: :class:`tl.PropagateNan` + """ + x = _semantic.to_tensor(x) + y = _semantic.to_tensor(y) + x = _promote_bfloat16_to_float32(x, _semantic=_semantic) + y = _promote_bfloat16_to_float32(y, _semantic=_semantic) + propagate_nan = _unwrap_if_constexpr(propagate_nan) + return _semantic.minimum(x, y, propagate_nan) + + +@builtin +def maximum(x, y, propagate_nan: constexpr = PropagateNan.NONE, _semantic=None): + """ + Computes the element-wise maximum of :code:`x` and :code:`y`. + + :param x: the first input tensor + :type x: Block + :param y: the second input tensor + :type y: Block + :param propagate_nan: whether to propagate NaN values. + :type propagate_nan: tl.PropagateNan + + .. seealso:: :class:`tl.PropagateNan` + """ + x = _semantic.to_tensor(x) + y = _semantic.to_tensor(y) + x = _promote_bfloat16_to_float32(x, _semantic=_semantic) + y = _promote_bfloat16_to_float32(y, _semantic=_semantic) + propagate_nan = _unwrap_if_constexpr(propagate_nan) + return _semantic.maximum(x, y, propagate_nan) + + +@builtin +def clamp(x, min, max, propagate_nan: constexpr = PropagateNan.NONE, _semantic=None): + """ + Clamps the input tensor :code:`x` within the range [min, max]. + Behavior when :code:`min` > :code:`max` is undefined. + + :param x: the input tensor + :type x: Block + :param min: the lower bound for clamping + :type min: Block + :param max: the upper bound for clamping + :type max: Block + :param propagate_nan: whether to propagate NaN values. Applies only to the :code:`x` tensor. + If either :code:`min` or :code:`max` is NaN, the result is undefined. + :type propagate_nan: tl.PropagateNan + + .. seealso:: :class:`tl.PropagateNan` + """ + x = _semantic.to_tensor(x) + min = _semantic.to_tensor(min) + max = _semantic.to_tensor(max) + x = _promote_bfloat16_to_float32(x, _semantic=_semantic) + min = _promote_bfloat16_to_float32(min, _semantic=_semantic) + max = _promote_bfloat16_to_float32(max, _semantic=_semantic) + + propagate_nan = _unwrap_if_constexpr(propagate_nan) + + return _semantic.clamp(x, min, max, propagate_nan) + + +# ----------------------- +# Reductions +# ----------------------- + + +def _add_reduction_docstr(name: str, return_indices_arg: str = None, tie_break_arg: str = None, + dtype_arg: str = None) -> Callable[[T], T]: + + def _decorator(func: T) -> T: + docstr = """ + Returns the {name} of all elements in the :code:`input` tensor along the provided :code:`axis` + + :param input: the input values + :type input: Tensor + :param axis: the dimension along which the reduction should be done. If None, reduce all dimensions + :type axis: int + :param keep_dims: if true, keep the reduced dimensions with length 1 + :type keep_dims: bool""" + if return_indices_arg is not None: + docstr += f""" + :param {return_indices_arg}: if true, return index corresponding to the {name} value + :type {return_indices_arg}: bool""" + if tie_break_arg is not None: + docstr += f""" + :param {tie_break_arg}: if true, in case of a tie (i.e., multiple elements have the same {name} value), return the left-most index for values that aren't NaN + :type {tie_break_arg}: bool""" + if dtype_arg is not None: + docstr += f""" + :param {dtype_arg}: the desired data type of the returned tensor. If specified, the input tensor is casted to :code:`{dtype_arg}` before the operation is performed. This is useful for preventing data overflows. If not specified, integer and bool dtypes are upcasted to :code:`tl.int32` and float dtypes are upcasted to at least :code:`tl.float32`. + :type {dtype_arg}: tl.dtype""" + + func.__doc__ = docstr.format(name=name) + return func + + return _decorator + + +@contextmanager +def _insertion_guard(builder): + ip = builder.get_insertion_point() + yield + builder.restore_insertion_point(ip) + + +@_tensor_member_fn +@builtin +def reduce(input, axis, combine_fn, keep_dims=False, _semantic=None, _generator=None): + """Applies the combine_fn to all elements in :code:`input` tensors along the provided :code:`axis` + + :param input: the input tensor, or tuple of tensors + :type input: Tensor + :param axis: the dimension along which the reduction should be done. If None, reduce all dimensions + :type axis: int | None + :param combine_fn: a function to combine two groups of scalar tensors (must be marked with @triton.jit) + :type combine_fn: Callable + :param keep_dims: if true, keep the reduced dimensions with length 1 + :type keep_dims: bool + + """ + if isinstance(input, tensor): + return reduce((input, ), axis, combine_fn, keep_dims=keep_dims, _semantic=_semantic, _generator=_generator)[0] + + def make_combine_region(reduce_op): + param_types = [t.type.scalar for t in input] * 2 + region = reduce_op.get_region(0) + builder = _semantic.builder + with _insertion_guard(builder): + to_ir = lambda T: T.to_ir(builder) + block = builder.create_block_with_parent(region, list(map(to_ir, param_types))) + args = [tensor(block.arg(i), ty) for i, ty in enumerate(param_types)] + results = _generator.call_JitFunction(combine_fn, args, kwargs={}) + if isinstance(results, tensor): + handles = [results.handle] + else: + handles = [r.handle for r in results] + builder.create_reduce_ret(*handles) + + def expand_ndims(t, ndims): + for _ in builtins.range(ndims): + t = expand_dims(t, 0, _semantic=_semantic) + return t + + axis = _unwrap_if_constexpr(axis) + keep_dims = _unwrap_if_constexpr(keep_dims) + if axis is not None: + axis = _wrap_axis(axis, len(input[0].shape)) + ret = _semantic.reduction(input, axis, make_combine_region) + if keep_dims: + if axis is not None: + ret = tuple(expand_dims(t, axis, _semantic=_semantic) for t in ret) + else: + ret = tuple(expand_ndims(t, len(input[0].shape)) for t in ret) + return ret + + +@builtin +def _promote_bfloat16_to_float32(t, _semantic=None): + scalar_ty = t.type.scalar + + # hardware doesn't support FMAX, FMIN, CMP for bfloat16 + if scalar_ty is bfloat16: + return t.to(float32, _semantic=_semantic) + return t + + +@builtin +def _reduce_with_indices(input, axis, combine_fn, keep_dims=False, _semantic=None, _generator=None): + axis = _unwrap_if_constexpr(axis) + n = input.shape[axis] + index = arange(0, n, _semantic=_semantic) + + if len(input.shape) > 1: + # Broadcast index across the non-reduced axes + axes_to_expand = [constexpr(d) for d in builtins.range(len(input.shape))] + del axes_to_expand[axis] + index = expand_dims(index, axes_to_expand, _semantic=_semantic) + index = broadcast_to(index, input.shape, _semantic=_semantic) + + rvalue, rindices = reduce((input, index), axis, combine_fn, keep_dims=keep_dims, _semantic=_semantic, + _generator=_generator) + return rvalue, rindices + + +# ----------------------- +# Scans +# ----------------------- + + +def _add_scan_docstr(name: str, dtype_arg: str = None) -> Callable[[T], T]: + + def _decorator(func: T) -> T: + docstr = """ + Returns the {name} of all elements in the :code:`input` tensor along the provided :code:`axis` + + :param input: the input values + :type input: Tensor + :param axis: the dimension along which the scan should be done + :type axis: int + :param reverse: if true, the scan is performed in the reverse direction + :type reverse: bool""" + + if dtype_arg is not None: + docstr += f""" + :param {dtype_arg}: the desired data type of the returned tensor. If specified, the input tensor is casted to :code:`{dtype_arg}` before the operation is performed. If not specified, small integer types (< 32 bits) are upcasted to prevent overflow. Note that :code:`tl.bfloat16` inputs are automatically promoted to :code:`tl.float32`. + :type {dtype_arg}: tl.dtype""" + + func.__doc__ = docstr.format(name=name) + return func + + return _decorator + + +@_tensor_member_fn +@builtin +def associative_scan(input, axis, combine_fn, reverse=False, _semantic=None, _generator=None): + """Applies the combine_fn to each elements with a carry in :code:`input` tensors along the provided :code:`axis` and update the carry + + :param input: the input tensor, or tuple of tensors + :type input: Tensor + :param axis: the dimension along which the reduction should be done + :type axis: int + :param combine_fn: a function to combine two groups of scalar tensors (must be marked with @triton.jit) + :type combine_fn: Callable + :param reverse: whether to apply the associative scan in the reverse direction along axis + :type reverse: bool + + """ + if isinstance(input, tensor): + return associative_scan((input, ), axis, combine_fn, reverse, _semantic=_semantic, _generator=_generator)[0] + + def make_combine_region(scan_op): + param_types = [t.type.scalar for t in input] * 2 + region = scan_op.get_region(0) + builder = _semantic.builder + with _insertion_guard(builder): + to_ir = lambda T: T.to_ir(builder) + block = builder.create_block_with_parent(region, list(map(to_ir, param_types))) + args = [tensor(block.arg(i), ty) for i, ty in enumerate(param_types)] + results = _generator.call_JitFunction(combine_fn, args, kwargs={}) + if isinstance(results, tensor): + handles = [results.handle] + else: + handles = [r.handle for r in results] + builder.create_scan_ret(*handles) + + axis = _unwrap_if_constexpr(axis) + if axis is not None: + axis = _wrap_axis(axis, len(input[0].shape)) + return _semantic.associative_scan(input, axis, make_combine_region, reverse) + + +@_tensor_member_fn +@builtin +def histogram(input, num_bins, mask=None, _semantic=None, _generator=None): + """computes an histogram based on input tensor with num_bins bins, the bins have a width of 1 and start at 0. + + :param input: the input tensor + :type input: Tensor + :param num_bins: number of histogram bins + :type num_bins: int + :param mask: if `mask[idx]` is false, exclude `input[idx]` from histogram + :type mask: Block of `triton.int1`, optional + + """ + num_bins = _unwrap_if_constexpr(num_bins) + mask = _unwrap_if_constexpr(mask) + if mask is not None: + mask = _semantic.to_tensor(mask) + return _semantic.histogram(input, num_bins, mask) + + +@_tensor_member_fn +@builtin +def gather(src, index, axis, _semantic=None): + """Gather from a tensor along a given dimension. + + :param src: the source tensor + :type src: Tensor + :param index: the index tensor + :type index: Tensor + :param axis: the dimension to gather along + :type axis: int + + """ + src = _unwrap_if_constexpr(src) + index = _unwrap_if_constexpr(index) + axis = _unwrap_if_constexpr(axis) + return _semantic.gather(src, index, axis) + + +@builtin +def map_elementwise( + scalar_fn: Callable[..., Tuple[tensor, ...]], + *args: tensor, + pack=1, + _semantic=None, + _generator=None, +): + ''' + Map a scalar function over a tensor. + + The input tensors :code:`args` are implicitly broadcasted to the same shape. + + This may be useful in allowing control flow over single elements in a tensor, + for example a multi-branch function where one branch is more expensive. With + :code:`tl.where` you are forced to calculate both sides of the branch, but + with an if we only execute one side. + + .. highlight:: python + .. code-block:: python + + @triton.jit + def selu_scalar(x, alpha): + if x > 0: + return a + else: + return alpha * (tl.exp(x) - 1) + + @triton.jit + def selu(x, alpha): + return tl.map_elementwise(selu_scalar, x, alpha) + + :param scalar_fn: the function to map over. + :param pack: the number of elements to be processed by one function call. + :return: one tensor or a tuple of tensors, depending on the mapped function. + ''' + # Build the block for the nested region first to discover the return types + assert pack >= 1 + in_scalar_tys = [t.type.scalar for t in args] + builder = _semantic.builder + block = builder.new_block() + scalar_args = [] + original_loc = builder.get_loc() + for i, ty in enumerate(in_scalar_tys): + for j in builtins.range(pack): + block.add_argument_at(ty.to_ir(builder), original_loc) + scalar_args.append(tensor(block.arg(i * pack + j), ty)) + + with _insertion_guard(builder): + builder.set_insertion_point_to_start(block) + scalar_results = _generator.call_JitFunction(scalar_fn, scalar_args, kwargs={}) + + is_single = isinstance(scalar_results, tensor) + if is_single: + scalar_results = scalar_results, + + handles = [r.handle for r in scalar_results] + builder.set_loc(original_loc) + builder.create_map_elementwise_ret(handles) + + fn_result_types = [x.type for x in scalar_results] + scalar_result_types = fn_result_types + if pack > 1: + scalar_result_types = fn_result_types[::pack] + for offset in builtins.range(1, pack): + assert scalar_result_types == fn_result_types[offset::pack], "type mismatch in unpacked results" + + def make_elementwise_region(elementwise_op): + region = elementwise_op.get_region(0) + region.push_back(block) + + builder.set_loc(original_loc) + result = _semantic.map_elementwise(args, scalar_result_types, pack, make_elementwise_region) + return result[0] if is_single else result + + +# ----------------------- +# Compiler Hint Ops +# ----------------------- + + +@builtin +def debug_barrier(_semantic=None): + ''' + Insert a barrier to synchronize all threads in a block. + ''' + return _semantic.debug_barrier() + + +@builtin +def multiple_of(input, values, _semantic=None): + """ + Let the compiler know that the values in :code:`input` are all multiples of :code:`value`. + """ + if isinstance(values, constexpr): + values = [values] + for i, d in enumerate(values): + if not isinstance(d, constexpr): + raise TypeError(f"values element {i} must have type `constexpr`") + if not isinstance(d.value, int): + raise TypeError(f"values element {i} must have type `constexpr[int]`, got `constexpr[{type(d.value)}]") + values = [x.value for x in values] + return _semantic.multiple_of(input, values) + + +@builtin +def max_contiguous(input, values, _semantic=None): + """ + Let the compiler know that the `value` first values in :code:`input` are contiguous. + """ + if isinstance(values, constexpr): + values = [values] + for i, d in enumerate(values): + if not isinstance(d, constexpr): + raise TypeError(f"values element {i} must have type `constexpr`") + if not isinstance(d.value, int): + raise TypeError(f"values element {i} must have type `constexpr[int]`, got `constexpr[{type(d.value)}]") + values = [x.value for x in values] + return _semantic.max_contiguous(input, values) + + +@builtin +def max_constancy(input, values, _semantic=None): + """ + Let the compiler know that the `value` first values in :code:`input` are constant. + + e.g. if :code:`values` is [4], then each group of 4 values in :code:`input` should all be equal, + for example [0, 0, 0, 0, 1, 1, 1, 1]. + """ + if isinstance(values, constexpr): + values = [values] + for i, d in enumerate(values): + if not isinstance(d, constexpr): + raise TypeError(f"values element {i} must have type `constexpr`") + if not isinstance(d.value, int): + raise TypeError(f"values element {i} must have type `constexpr[int]`, got `constexpr[{type(d.value)}]") + values = [x.value for x in values] + return _semantic.max_constancy(input, values) + + +@builtin +def assume(cond, _semantic=None): + ''' + Allow compiler to assume the :code:`cond` is True. + ''' + return _semantic.assume(_semantic.to_tensor(cond)) + + +# ----------------------- +# Debugging functions +# ----------------------- + + +@builtin +def static_print(*values, sep: str = " ", end: str = "\n", file=None, flush=False, _semantic=None): + ''' + Print the values at compile time. The parameters are the same as the builtin :code:`print`. + + NOTE: Calling the Python builtin :code:`print` is not the same as calling this, it instead maps to :code:`device_print`, + which has special requirements for the arguments. + + .. highlight:: python + .. code-block:: python + + tl.static_print(f"BLOCK_SIZE={BLOCK_SIZE}") + ''' + pass + + +@builtin +def static_assert(cond, msg="", _semantic=None): + ''' + Assert the condition at compile time. Does not require that the :code:`TRITON_DEBUG` environment variable + is set. + + .. highlight:: python + .. code-block:: python + + tl.static_assert(BLOCK_SIZE == 1024) + ''' + pass + + +@builtin +def device_print(prefix, *args, hex=False, _semantic=None): + ''' + Print the values at runtime from the device. String formatting does not work for runtime values, so you should + provide the values you want to print as arguments. The first value must be a string, all following values must + be scalars or tensors. + + Calling the Python builtin :code:`print` is the same as calling this function, and the requirements for the arguments will match + this function (not the normal requirements for :code:`print`). + + .. highlight:: python + .. code-block:: python + + tl.device_print("pid", pid) + print("pid", pid) + + On CUDA, printfs are streamed through a buffer of limited size (on one host, + we measured the default as 6912 KiB, but this may not be consistent across + GPUs and CUDA versions). If you notice some printfs are being dropped, you + can increase the buffer size by calling + + .. highlight:: python + .. code-block:: python + + triton.runtime.driver.active.utils.set_printf_fifo_size(size_bytes) + + CUDA may raise an error if you try to change this value after running a + kernel that uses printfs. The value set here may only affect the current + device (so if you have multiple GPUs, you'd need to call it multiple times). + + :param prefix: a prefix to print before the values. This is required to be a string literal. + :param args: the values to print. They can be any tensor or scalar. + :param hex: print all values as hex instead of decimal + ''' + import string + prefix = _unwrap_if_constexpr(prefix) + assert isinstance(prefix, str), f"{prefix} is not string" + b_ascii = True + for ch in prefix: + if ch not in string.printable: + b_ascii = False + break + assert b_ascii, f"{prefix} is not an ascii string" + new_args = [] + for arg in args: + new_args.append(_semantic.to_tensor(arg)) + return _semantic.device_print(prefix, new_args, hex) + + +@builtin +def device_assert(cond, msg="", mask=None, _semantic=None): + ''' + Assert the condition at runtime from the device. Requires that the environment variable :code:`TRITON_DEBUG` + is set to a value besides :code:`0` in order for this to have any effect. + + Using the Python :code:`assert` statement is the same as calling this function, except that the second argument + must be provided and must be a string, e.g. :code:`assert pid == 0, "pid != 0"`. The environment variable must + be set for this :code:`assert` statement to have any effect. + + .. highlight:: python + .. code-block:: python + + tl.device_assert(pid == 0) + assert pid == 0, f"pid != 0" + + :param cond: the condition to assert. This is required to be a boolean tensor. + :param msg: the message to print if the assertion fails. This is required to be a string literal. + ''' + msg = _unwrap_if_constexpr(msg) + mask = _unwrap_if_constexpr(mask) + if mask is not None: + mask = _semantic.to_tensor(mask) + return _semantic.device_assert(_semantic.to_tensor(cond), msg, mask) + + +@builtin +def inline_asm_elementwise(asm: str, constraints: str, args: Sequence, dtype: Union[dtype, Sequence[dtype]], + is_pure: bool, pack: int, _semantic=None): + ''' + Execute inline assembly over a tensor. Essentially, this is :code:`map` + where the function is inline assembly. + + The input tensors :code:`args` are implicitly broadcasted to the same shape. + + :code:`dtype` can be a tuple of types, in which case the output is a + tuple of tensors. + + Each invocation of the inline asm processes :code:`pack` elements at a + time. Exactly which set of inputs a block receives is unspecified. + Input elements of size less than 4 bytes are packed into 4-byte + registers. + + This op does not support empty :code:`dtype` -- the inline asm must + return at least one tensor, even if you don't need it. You can work + around this by returning a dummy tensor of arbitrary type; it shouldn't + cost you anything if you don't use it. + + Example using + `PTX `_ + assembly: + + .. highlight:: python + .. code-block:: python + + @triton.jit + def kernel(A, B, C, D, BLOCK: tl.constexpr): + a = tl.load(A + tl.arange(0, BLOCK)) # uint8 tensor + b = tl.load(B + tl.arange(0, BLOCK)) # float32 tensor + + # For each (a,b) in zip(a,b), perform the following: + # - Let ai be `a` converted to int32. + # - Let af be `a` converted to float. + # - Let m be the max of ai and b. + # - Return ai and mi. + # Do the above 4 elements at a time. + (c, d) = tl.inline_asm_elementwise( + asm=""" + { + // Unpack `a` into `ai`. + .reg .b8 tmp<4>; + mov.b32 {tmp0, tmp1, tmp2, tmp3}, $8; + cvt.u32.u8 $0, tmp0; + cvt.u32.u8 $1, tmp1; + cvt.u32.u8 $2, tmp2; + cvt.u32.u8 $3, tmp3; + } + // Convert `ai` to float. + cvt.rn.f32.s32 $4, $0; + cvt.rn.f32.s32 $5, $1; + cvt.rn.f32.s32 $6, $2; + cvt.rn.f32.s32 $7, $3; + // Take max of `ai` and `b`. + max.f32 $4, $4, $9; + max.f32 $5, $5, $10; + max.f32 $6, $6, $11; + max.f32 $7, $7, $12; + """, + constraints=( + # 8 output registers, namely + # $0=ai0, $1=ai1, $2=ai2, $3=ai3, + # $4=m0, $5=m1, $6=m2, $7=m3. + "=r,=r,=r,=r,=r,=r,=r,=r," + # 5 input registers, namely + # $8=ai, + # $9=b0, $10=b1, $11=b2, $12=b3. + # The four elements from `a` are all packed into one register. + "r,r,r,r,r"), + args=[a, b], + dtype=(tl.int32, tl.float32), + is_pure=True, + pack=4, + ) + tl.store(C + tl.arange(0, BLOCK), c) + tl.store(D + tl.arange(0, BLOCK), d) + + :param asm: assembly to run. Must match target's assembly format. + :param constraints: asm constraints in + `LLVM format `_ + :param args: the input tensors, whose values are passed to the asm block + :param dtype: the element type(s) of the returned tensor(s) + :param is_pure: if true, the compiler assumes the asm block has no side-effects + :param pack: the number of elements to be processed by one instance of inline assembly + :return: one tensor or a tuple of tensors of the given dtypes + ''' + asm = _unwrap_if_constexpr(asm) + constraints = _unwrap_if_constexpr(constraints) + pack = _unwrap_if_constexpr(pack) + is_pure = _unwrap_if_constexpr(is_pure) + + # Wrap `dtype` in a tuple if it's not already. + try: + iter(dtype) # type: ignore + has_multiple_outputs = True + except TypeError: + has_multiple_outputs = False + dtype = (dtype, ) # type: ignore + + dtype = typing.cast(Sequence[_DtypeClass], dtype) + + res_tys = dtype + if dispatch_args := [_semantic.to_tensor(arg) for arg in args]: + bin_op_type_checking = partial( + _semantic.binary_op_type_checking_impl, + arithmetic_check=False, + allow_lhs_ptr=True, + allow_rhs_ptr=True, + ) + broadcast_arg = dispatch_args[0] + # Get the broadcast shape over all the arguments + for item in dispatch_args: + _, broadcast_arg = bin_op_type_checking(item, broadcast_arg) + if broadcast_arg.shape: + # Change the shape of each argument based on the broadcast shape + for i, item in enumerate(dispatch_args): + dispatch_args[i], _ = bin_op_type_checking(item, broadcast_arg) + res_tys = [broadcast_arg.type.with_element_ty(dt) for dt in dtype] + handles = [t.handle for t in dispatch_args] + builder = _semantic.builder + call = builder.create_inline_asm(asm, constraints, handles, [ty.to_ir(builder) for ty in res_tys], is_pure, pack) + + if not has_multiple_outputs: + return tensor(call.get_result(0), res_tys[0]) + return tuple(tensor(call.get_result(i), ty) for i, ty in enumerate(res_tys)) + + +# ----------------------- +# Iterators +# ----------------------- + + +class static_range(base_value): + """ + Iterator that counts upward forever. + + .. highlight:: python + .. code-block:: python + + @triton.jit + def kernel(...): + for i in tl.static_range(10): + ... + :note: This is a special iterator used to implement similar semantics to Python's :code:`range` in the context of + :code:`triton.jit` functions. In addition, it also guides the compiler to unroll the loop aggressively. + :param arg1: the start value. + :param arg2: the end value. + :param step: the step value. + """ + + def __init__(self, arg1, arg2=None, step=None): + assert isinstance(arg1, constexpr), f"{arg1} used as tl.static_range start value is not a constexpr" + if step is None: + self.step = constexpr(1) + else: + assert isinstance(step, constexpr), f"{step} used as tl.static_range step value is not a constexpr" + self.step = step + if arg2 is None: + self.start = constexpr(0) + self.end = arg1 + else: + assert isinstance(arg2, constexpr), f"{arg2} used as tl.static_range end value is not a constexpr" + self.start = arg1 + self.end = arg2 + + def __iter__(self): + raise RuntimeError("static_range can only be used in @triton.jit'd functions") + + def __next__(self): + raise RuntimeError("static_range can only be used in @triton.jit'd functions") + + +class range(base_value): + """ + Iterator that counts upward forever. + + .. highlight:: python + .. code-block:: python + + @triton.jit + def kernel(...): + for i in tl.range(10, num_stages=3): + ... + :note: This is a special iterator used to implement similar semantics to Python's :code:`range` in the context of + :code:`triton.jit` functions. In addition, it allows user to pass extra attributes to the compiler. + :param arg1: the start value. + :param arg2: the end value. + :param step: the step value. + :param num_stages: pipeline the loop into this many stages (so there are + :code:`num_stages` iterations of the loop in flight at once). + + Note this is subtly different than passing :code:`num_stages` as a + kernel argument. The kernel argument only pipelines loads that feed + into :code:`dot` operations, while this attribute tries to pipeline most + (though not all) loads in this loop. + :param loop_unroll_factor: Tells the Triton IR level loop unroller how many + times to unroll a for loop that this range is used with. Less than 2 for + this value implies no unrolling. + :param disallow_acc_multi_buffer: If true, prevent the accumulator of the dot + operation in the loop to be multi-buffered, if applicable. + :param flatten: automatically flatten the loop nest starting at this loop to + create a single flattened loop. The compiler will try to pipeline the + flattened loop which can avoid stage stalling. + :param warp_specialize: Enable automatic warp specialization on the loop. + The compiler will attempt to partition memory, MMA, and vector + operations in the loop into separate async partitions. This will + increase the total number of warps required by the kernel. + :param disable_licm: Tells the compiler it shouldn't hoist loop invariant + code outside the loop. This is often useful to avoid creating long liveranges + within a loop. + + Note that warp specialization is only supported on Blackwell GPUs and + only works on simple matmul loops. Support for arbitrary loops will be + expanded over time. + """ + + def __init__(self, arg1, arg2=None, step=None, num_stages=None, loop_unroll_factor=None, + disallow_acc_multi_buffer=False, flatten=False, warp_specialize=False, disable_licm=False): + if step is None: + self.step = constexpr(1) + else: + self.step = step + if arg2 is None: + self.start = constexpr(0) + self.end = arg1 + else: + self.start = arg1 + self.end = arg2 + self.num_stages = num_stages + self.loop_unroll_factor = loop_unroll_factor + self.disallow_acc_multi_buffer = disallow_acc_multi_buffer + self.flatten = flatten + self.warp_specialize = warp_specialize + self.disable_licm = disable_licm + + def __iter__(self): + raise RuntimeError("tl.range can only be used in @triton.jit'd functions") + + def __next__(self): + raise RuntimeError("tl.range can only be used in @triton.jit'd functions") + + +class condition(base_value): + """ + While loop condition wrapper. + + .. highlight:: python + .. code-block:: python + + @triton.jit + def kernel(...): + while tl.condition(c, disable_licm) + ... + :note: This is a special wrapper used to annotate while loops in the context of + :code:`triton.jit` functions. It allows user to pass extra attributes to the compiler. + :param disable_licm: Tells the compiler it shouldn't hoist loop invariant + code outside the loop. This is often useful to avoid creating long liveranges + within a loop. + """ + + def __init__(self, arg1, disable_licm=False): + self.condition = arg1 + self.disable_licm = disable_licm + + +# ----------------------- +# Extern functions +# ----------------------- + + +def dispatch(func, lib_name: str, lib_path: str, args: list, arg_type_symbol_dict: dict, ret_type: dtype, is_pure: bool, + _semantic): + ''' + Dispatch a function to a library + :param func: the function to dispatch + :param lib_name: the name of the library + :param lib_path: the path of the library + :param args: the arguments of the function + :param arg_type_symbol_dict: the type of the arguments + :param ret_type: the type of the return value + :return: the return value of the function + ''' + if len(arg_type_symbol_dict) == 0: + raise ValueError("arg_type_symbol_dict is empty") + + num_args = len(list(arg_type_symbol_dict.keys())[0]) + if len(args) != num_args: + raise ValueError(f"length of input args does not match." + f"Expect {len(args)}, got {num_args}") + + arg_types = [] + arg_list = [] + for arg in args: + if isinstance(arg, tensor): + arg_types.append(arg.dtype) + arg_list.append(arg.handle) + else: + arg_types.append(type(arg)) + arg_list.append(arg) + arg_types = tuple(arg_types) + + if arg_types not in arg_type_symbol_dict: + raise ValueError(f"input arg type does not match." + f"Expect one of {arg_type_symbol_dict.keys()}, got {arg_types}") + else: + symbol = arg_type_symbol_dict[arg_types][0] + builder = _semantic.builder + return tensor(func(lib_name, lib_path, symbol, arg_list, ret_type.to_ir(builder), is_pure), ret_type) + + +@builtin +def extern_elementwise(lib_name: str, lib_path: str, args: list, arg_type_symbol_dict: dict, is_pure: bool, + _semantic=None): + ''' + Dispatch an elementwise function to a library + :param lib_name: the name of the library + :param lib_path: the path of the library + :param args: the arguments of the function + :param arg_type_symbol_dict: the type of the arguments + :param is_pure: whether the function is pure + :return: the return value of the function + ''' + dispatch_args = args.copy() + all_scalar = True + arg_types = [] + for i in builtins.range(len(dispatch_args)): + dispatch_args[i] = _semantic.to_tensor(dispatch_args[i]) + arg_types.append(dispatch_args[i].dtype) + if dispatch_args[i].type.is_block(): + all_scalar = False + + arg_types = tuple(arg_types) + ret_type = arg_type_symbol_dict[arg_types][1] + if len(arg_types) > 0: + arithmetic_check = True + # If there's a type tuple that is not supported by the library, we will do arithmetic check + if arg_types in arg_type_symbol_dict: + arithmetic_check = False + broadcast_arg = dispatch_args[0] + # Get the broadcast shape over all the arguments + for item in dispatch_args: + _, broadcast_arg = _semantic.binary_op_type_checking_impl(item, broadcast_arg, + arithmetic_check=arithmetic_check) + # Change the shape of each argument based on the broadcast shape + for i in builtins.range(len(dispatch_args)): + dispatch_args[i], _ = _semantic.binary_op_type_checking_impl(dispatch_args[i], broadcast_arg, + arithmetic_check=arithmetic_check) + if not all_scalar: + ret_type = broadcast_arg.type.with_element_ty(ret_type) + func = _semantic.builder.create_extern_elementwise + return dispatch(func, lib_name, lib_path, dispatch_args, arg_type_symbol_dict, ret_type, is_pure, _semantic) + + +def binary_op_type_legalization(lhs, rhs, semantic): + ''' + Convert both operands to a single common type + :param lhs: the left operand + :param rhs: the right operand + :param builder: the builder + ''' + return semantic.binary_op_type_checking_impl(lhs, rhs) + + +def extern(fn): + """A decorator for external functions.""" + return builtin(fn) + + +_NOTHING = object() + + +def is_negative_zero(x): + return x == 0.0 and math.copysign(1.0, x) < 0 + + +@builtin +def builtin_max(*args, propagate_nan=_NOTHING, _semantic=None): + args = _unwrap_if_constexpr(args) + is_constexpr = all(not isinstance(x, base_value) for x in args) + if is_constexpr: + assert propagate_nan is _NOTHING, "propagate_nan is not supported on builtin max" + assert not any(math.isnan(x) for x in args) + assert not any(is_negative_zero(x) for x in args) + return constexpr(builtins.max(_unwrap_if_constexpr(args))) + + if propagate_nan is _NOTHING: + propagate_nan = PropagateNan.NONE + else: + warn("passing propagate_nan to builtin max is deprecated, use tl.minimum instead", DeprecationWarning) + + assert len(args) >= 2, "min requires at least 2 values" + max_val = args[0] + for arg in args[1:]: + max_val = maximum(max_val, arg, propagate_nan=propagate_nan, _semantic=_semantic) + if max_val.type.is_block(): + warn("builtin max on non-scalar tensor values is deprecated, use tl.maximum instead", DeprecationWarning) + return max_val + + +@builtin +def builtin_min(*args, propagate_nan=_NOTHING, _semantic=None): + args = _unwrap_if_constexpr(args) + is_constexpr = all(not isinstance(x, base_value) for x in args) + if is_constexpr: + assert propagate_nan is _NOTHING, "propagate_nan is not supported on builtin min" + assert not any(math.isnan(x) for x in args) + assert not any(is_negative_zero(x) for x in args) + return constexpr(builtins.min(_unwrap_if_constexpr(args))) + + if propagate_nan is _NOTHING: + propagate_nan = PropagateNan.NONE + else: + warn("passing propagate_nan to builtin min is deprecated, use tl.minimum instead", DeprecationWarning) + + assert len(args) >= 2, "min requires at least 2 values" + min_val = args[0] + for arg in args[1:]: + min_val = minimum(min_val, arg, propagate_nan=propagate_nan, _semantic=_semantic) + if min_val.type.is_block(): + warn("builtin min on non-scalar tensor values is deprecated, use tl.minimum instead", DeprecationWarning) + return min_val diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/language/extra/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/language/extra/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3f8c70a716a3da3473a4906b44aec7d35fcc35a5 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/language/extra/__init__.py @@ -0,0 +1,26 @@ +import pkgutil +from importlib.util import module_from_spec +from sys import modules + +_backends = [] +for module_finder, module_name, is_pkg in pkgutil.iter_modules( + __path__, + prefix=__name__ + ".", +): + # skip .py files (like libdevice.py) + if not is_pkg: + continue + + # import backends (like cuda and hip) that are included during setup.py + spec = module_finder.find_spec(module_name) + if spec is None or spec.loader is None: + continue + module = module_from_spec(spec) + spec.loader.exec_module(module) + + _backends.append(module_name) + modules[module_name] = module + +__all__ = _backends + +del _backends diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/language/extra/cuda/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/language/extra/cuda/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fbececf1defce4a9493a9e75cc7cb39571465175 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/language/extra/cuda/__init__.py @@ -0,0 +1,16 @@ +from . import libdevice + +from .utils import (globaltimer, num_threads, num_warps, smid, convert_custom_float8_sm70, convert_custom_float8_sm80) +from .gdc import (gdc_launch_dependents, gdc_wait) + +__all__ = [ + "libdevice", + "globaltimer", + "num_threads", + "num_warps", + "smid", + "convert_custom_float8_sm70", + "convert_custom_float8_sm80", + "gdc_launch_dependents", + "gdc_wait", +] diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/language/extra/cuda/gdc.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/language/extra/cuda/gdc.py new file mode 100644 index 0000000000000000000000000000000000000000..4376719e3dbe63ac2dfe65bfc6bf936116056676 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/language/extra/cuda/gdc.py @@ -0,0 +1,42 @@ +""" +Grid Dependency Control (GDC) is a mechanism used when enabling programmatic dependent launch to launch and +synchronize grids. These APIs expose GDC to the programmer. + +Programmatic dependent launch is supported on SM90 (Hopper) and beyond. +For PTX reference on grid dependency control see https://docs.nvidia.com/cuda/parallel-thread-execution/index.html#parallel-synchronization-and-communication-instructions-griddepcontrol. +""" + +from triton.language import core + + +@core.extern +def gdc_wait(_semantic=None): + """ + GDC wait is a blocking instruction that waits for all instructions in a prior kernel to complete before continuing. + This ensures all memory operations happening before the wait is visible to instructions after it, + e.g. if the prior kernel writes to address "x" the new values will be visible in this kernel after the wait. + + This instruction is also safe to execute when programmatic dependent launch is disabled. + + See https://docs.nvidia.com/cuda/parallel-thread-execution/index.html#parallel-synchronization-and-communication-instructions-griddepcontrol for more details. + """ + core.inline_asm_elementwise("griddepcontrol.wait; // dummy $0", "=r", [], dtype=core.int32, is_pure=False, pack=1, + _semantic=_semantic) + + +@core.extern +def gdc_launch_dependents(_semantic=None): + """ + This operation when launched with programmatic dependent launch signals that + the next program may launch once all programs in the current kernel + call this function or complete. + + Repeated calls to this function have no effect past the first call, and the first call should be + treated by the programmer as a hint to the runtime system to launch the next kernel. + + This instruction is also safe to execute when programmatic dependent launch is disabled. + + See https://docs.nvidia.com/cuda/parallel-thread-execution/index.html#parallel-synchronization-and-communication-instructions-griddepcontrol for more details. + """ + core.inline_asm_elementwise("griddepcontrol.launch_dependents; // dummy $0", "=r", [], dtype=core.int32, + is_pure=False, pack=1, _semantic=_semantic) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/language/extra/cuda/libdevice.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/language/extra/cuda/libdevice.py new file mode 100644 index 0000000000000000000000000000000000000000..08661f5414a68f43b1fe35a2de945ed30322d73f --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/language/extra/cuda/libdevice.py @@ -0,0 +1,1629 @@ +from triton.language import core + + +@core.extern +def clz(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("int32"), ): ("__nv_clz", core.dtype("int32")), + (core.dtype("int64"), ): ("__nv_clzll", core.dtype("int32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def popc(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("int32"), ): ("__nv_popc", core.dtype("int32")), + (core.dtype("int64"), ): ("__nv_popcll", core.dtype("int32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def byte_perm(arg0, arg1, arg2, _semantic=None): + return core.extern_elementwise("", "", [arg0, arg1, arg2], { + (core.dtype("int32"), core.dtype("int32"), core.dtype("int32")): ("__nv_byte_perm", core.dtype("int32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def mulhi(arg0, arg1, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1], { + (core.dtype("int32"), core.dtype("int32")): ("__nv_mulhi", core.dtype("int32")), + (core.dtype("uint32"), core.dtype("uint32")): ("__nv_umulhi", core.dtype("uint32")), + (core.dtype("int64"), core.dtype("int64")): ("__nv_mul64hi", core.dtype("int64")), + (core.dtype("uint64"), core.dtype("uint64")): ("__nv_umul64hi", core.dtype("uint64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def mul24(arg0, arg1, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1], { + (core.dtype("int32"), core.dtype("int32")): ("__nv_mul24", core.dtype("int32")), + (core.dtype("uint32"), core.dtype("uint32")): ("__nv_umul24", core.dtype("uint32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def brev(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("int32"), ): ("__nv_brev", core.dtype("int32")), + (core.dtype("int64"), ): ("__nv_brevll", core.dtype("int64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def sad(arg0, arg1, arg2, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1, arg2], { + (core.dtype("int32"), core.dtype("int32"), core.dtype("uint32")): ("__nv_sad", core.dtype("int32")), + (core.dtype("uint32"), core.dtype("uint32"), core.dtype("uint32")): ("__nv_usad", core.dtype("uint32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def abs(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("int32"), ): ("__nv_abs", core.dtype("int32")), + (core.dtype("int64"), ): ("__nv_llabs", core.dtype("int64")), + (core.dtype("fp32"), ): ("__nv_fabsf", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_fabs", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def floor(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_floorf", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_floor", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def rcp64h(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp64"), ): ("__nv_rcp64h", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def rsqrt(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_rsqrtf", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_rsqrt", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def ceil(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp64"), ): ("__nv_ceil", core.dtype("fp64")), + (core.dtype("fp32"), ): ("__nv_ceilf", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def trunc(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp64"), ): ("__nv_trunc", core.dtype("fp64")), + (core.dtype("fp32"), ): ("__nv_truncf", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def exp2(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_exp2f", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_exp2", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def saturatef(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_saturatef", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def fma_rn(arg0, arg1, arg2, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1, arg2], { + (core.dtype("fp32"), core.dtype("fp32"), core.dtype("fp32")): ("__nv_fmaf_rn", core.dtype("fp32")), + (core.dtype("fp64"), core.dtype("fp64"), core.dtype("fp64")): ("__nv_fma_rn", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def fma_rz(arg0, arg1, arg2, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1, arg2], { + (core.dtype("fp32"), core.dtype("fp32"), core.dtype("fp32")): ("__nv_fmaf_rz", core.dtype("fp32")), + (core.dtype("fp64"), core.dtype("fp64"), core.dtype("fp64")): ("__nv_fma_rz", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def fma_rd(arg0, arg1, arg2, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1, arg2], { + (core.dtype("fp32"), core.dtype("fp32"), core.dtype("fp32")): ("__nv_fmaf_rd", core.dtype("fp32")), + (core.dtype("fp64"), core.dtype("fp64"), core.dtype("fp64")): ("__nv_fma_rd", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def fma_ru(arg0, arg1, arg2, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1, arg2], { + (core.dtype("fp32"), core.dtype("fp32"), core.dtype("fp32")): ("__nv_fmaf_ru", core.dtype("fp32")), + (core.dtype("fp64"), core.dtype("fp64"), core.dtype("fp64")): ("__nv_fma_ru", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def fast_dividef(arg0, arg1, _semantic=None): + return core.extern_elementwise("", "", [arg0, arg1], { + (core.dtype("fp32"), core.dtype("fp32")): ("__nv_fast_fdividef", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def div_rn(arg0, arg1, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1], { + (core.dtype("fp32"), core.dtype("fp32")): ("__nv_fdiv_rn", core.dtype("fp32")), + (core.dtype("fp64"), core.dtype("fp64")): ("__nv_ddiv_rn", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def div_rz(arg0, arg1, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1], { + (core.dtype("fp32"), core.dtype("fp32")): ("__nv_fdiv_rz", core.dtype("fp32")), + (core.dtype("fp64"), core.dtype("fp64")): ("__nv_ddiv_rz", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def div_rd(arg0, arg1, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1], { + (core.dtype("fp32"), core.dtype("fp32")): ("__nv_fdiv_rd", core.dtype("fp32")), + (core.dtype("fp64"), core.dtype("fp64")): ("__nv_ddiv_rd", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def div_ru(arg0, arg1, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1], { + (core.dtype("fp32"), core.dtype("fp32")): ("__nv_fdiv_ru", core.dtype("fp32")), + (core.dtype("fp64"), core.dtype("fp64")): ("__nv_ddiv_ru", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def rcp_rn(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_frcp_rn", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_drcp_rn", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def rcp_rz(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_frcp_rz", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_drcp_rz", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def rcp_rd(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_frcp_rd", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_drcp_rd", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def rcp_ru(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_frcp_ru", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_drcp_ru", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def sqrt_rn(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_fsqrt_rn", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_dsqrt_rn", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def sqrt_rz(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_fsqrt_rz", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_dsqrt_rz", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def sqrt_rd(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_fsqrt_rd", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_dsqrt_rd", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def sqrt_ru(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_fsqrt_ru", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_dsqrt_ru", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def sqrt(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_sqrtf", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_sqrt", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def add_rn(arg0, arg1, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1], { + (core.dtype("fp64"), core.dtype("fp64")): ("__nv_dadd_rn", core.dtype("fp64")), + (core.dtype("fp32"), core.dtype("fp32")): ("__nv_fadd_rn", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def add_rz(arg0, arg1, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1], { + (core.dtype("fp64"), core.dtype("fp64")): ("__nv_dadd_rz", core.dtype("fp64")), + (core.dtype("fp32"), core.dtype("fp32")): ("__nv_fadd_rz", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def add_rd(arg0, arg1, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1], { + (core.dtype("fp64"), core.dtype("fp64")): ("__nv_dadd_rd", core.dtype("fp64")), + (core.dtype("fp32"), core.dtype("fp32")): ("__nv_fadd_rd", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def add_ru(arg0, arg1, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1], { + (core.dtype("fp64"), core.dtype("fp64")): ("__nv_dadd_ru", core.dtype("fp64")), + (core.dtype("fp32"), core.dtype("fp32")): ("__nv_fadd_ru", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def mul_rn(arg0, arg1, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1], { + (core.dtype("fp64"), core.dtype("fp64")): ("__nv_dmul_rn", core.dtype("fp64")), + (core.dtype("fp32"), core.dtype("fp32")): ("__nv_fmul_rn", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def mul_rz(arg0, arg1, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1], { + (core.dtype("fp64"), core.dtype("fp64")): ("__nv_dmul_rz", core.dtype("fp64")), + (core.dtype("fp32"), core.dtype("fp32")): ("__nv_fmul_rz", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def mul_rd(arg0, arg1, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1], { + (core.dtype("fp64"), core.dtype("fp64")): ("__nv_dmul_rd", core.dtype("fp64")), + (core.dtype("fp32"), core.dtype("fp32")): ("__nv_fmul_rd", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def mul_ru(arg0, arg1, _semantic=None): + return core.extern_elementwise( + "", "", [ + arg0, + arg1, + ], { + ( + core.dtype("fp64"), + core.dtype("fp64"), + ): ("__nv_dmul_ru", core.dtype("fp64")), + ( + core.dtype("fp32"), + core.dtype("fp32"), + ): ("__nv_fmul_ru", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def double2float_rn(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp64"), ): ("__nv_double2float_rn", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def double2float_rz(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp64"), ): ("__nv_double2float_rz", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def double2float_rd(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp64"), ): ("__nv_double2float_rd", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def double2float_ru(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp64"), ): ("__nv_double2float_ru", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def double2int_rn(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp64"), ): ("__nv_double2int_rn", core.dtype("int32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def double2int_rz(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp64"), ): ("__nv_double2int_rz", core.dtype("int32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def double2int_rd(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp64"), ): ("__nv_double2int_rd", core.dtype("int32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def double2int_ru(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp64"), ): ("__nv_double2int_ru", core.dtype("int32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def double2uint_rn(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp64"), ): ("__nv_double2uint_rn", core.dtype("int32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def double2uint_rz(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp64"), ): ("__nv_double2uint_rz", core.dtype("int32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def double2uint_rd(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp64"), ): ("__nv_double2uint_rd", core.dtype("int32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def double2uint_ru(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp64"), ): ("__nv_double2uint_ru", core.dtype("int32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def int2double_rn(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("int32"), ): ("__nv_int2double_rn", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def uint2double_rn(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("uint32"), ): ("__nv_uint2double_rn", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def float2int_rn(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_float2int_rn", core.dtype("int32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def float2int_rz(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_float2int_rz", core.dtype("int32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def float2int_rd(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_float2int_rd", core.dtype("int32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def float2int_ru(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_float2int_ru", core.dtype("int32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def float2uint_rn(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_float2uint_rn", core.dtype("int32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def float2uint_rz(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_float2uint_rz", core.dtype("int32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def float2uint_rd(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_float2uint_rd", core.dtype("int32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def float2uint_ru(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_float2uint_ru", core.dtype("int32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def int2float_rn(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("int32"), ): ("__nv_int2float_rn", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def int2float_rz(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("int32"), ): ("__nv_int2float_rz", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def int2float_rd(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("int32"), ): ("__nv_int2float_rd", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def int2float_ru(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("int32"), ): ("__nv_int2float_ru", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def uint2float_rn(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("uint32"), ): ("__nv_uint2float_rn", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def uint2float_rz(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("uint32"), ): ("__nv_uint2float_rz", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def uint2float_rd(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("uint32"), ): ("__nv_uint2float_rd", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def uint2float_ru(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("uint32"), ): ("__nv_uint2float_ru", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def hiloint2double(arg0, arg1, _semantic=None): + return core.extern_elementwise("", "", [arg0, arg1], { + (core.dtype("int32"), core.dtype("int32")): ("__nv_hiloint2double", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def double2loint(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp64"), ): ("__nv_double2loint", core.dtype("int32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def double2hiint(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp64"), ): ("__nv_double2hiint", core.dtype("int32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def float2ll_rn(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_float2ll_rn", core.dtype("int64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def float2ll_rz(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_float2ll_rz", core.dtype("int64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def float2ll_rd(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_float2ll_rd", core.dtype("int64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def float2ll_ru(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_float2ll_ru", core.dtype("int64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def float2ull_rn(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_float2ull_rn", core.dtype("int64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def float2ull_rz(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_float2ull_rz", core.dtype("int64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def float2ull_rd(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_float2ull_rd", core.dtype("int64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def float2ull_ru(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_float2ull_ru", core.dtype("int64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def double2ll_rn(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp64"), ): ("__nv_double2ll_rn", core.dtype("int64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def double2ll_rz(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp64"), ): ("__nv_double2ll_rz", core.dtype("int64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def double2ll_rd(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp64"), ): ("__nv_double2ll_rd", core.dtype("int64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def double2ll_ru(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp64"), ): ("__nv_double2ll_ru", core.dtype("int64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def double2ull_rn(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp64"), ): ("__nv_double2ull_rn", core.dtype("int64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def double2ull_rz(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp64"), ): ("__nv_double2ull_rz", core.dtype("int64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def double2ull_rd(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp64"), ): ("__nv_double2ull_rd", core.dtype("int64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def double2ull_ru(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp64"), ): ("__nv_double2ull_ru", core.dtype("int64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def ll2float_rn(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("int64"), ): ("__nv_ll2float_rn", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def ll2float_rz(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("int64"), ): ("__nv_ll2float_rz", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def ll2float_rd(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("int64"), ): ("__nv_ll2float_rd", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def ll2float_ru(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("int64"), ): ("__nv_ll2float_ru", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def ull2float_rn(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("uint64"), ): ("__nv_ull2float_rn", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def ull2float_rz(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("uint64"), ): ("__nv_ull2float_rz", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def ull2float_rd(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("uint64"), ): ("__nv_ull2float_rd", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def ull2float_ru(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("uint64"), ): ("__nv_ull2float_ru", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def ll2double_rn(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("int64"), ): ("__nv_ll2double_rn", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def ll2double_rz(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("int64"), ): ("__nv_ll2double_rz", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def ll2double_rd(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("int64"), ): ("__nv_ll2double_rd", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def ll2double_ru(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("int64"), ): ("__nv_ll2double_ru", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def ull2double_rn(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("uint64"), ): ("__nv_ull2double_rn", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def ull2double_rz(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("uint64"), ): ("__nv_ull2double_rz", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def ull2double_rd(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("uint64"), ): ("__nv_ull2double_rd", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def ull2double_ru(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("uint64"), ): ("__nv_ull2double_ru", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def int_as_float(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("int32"), ): ("__nv_int_as_float", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def float_as_int(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_float_as_int", core.dtype("int32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def uint_as_float(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("uint32"), ): ("__nv_uint_as_float", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def float_as_uint(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_float_as_uint", core.dtype("int32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def longlong_as_double(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("int64"), ): ("__nv_longlong_as_double", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def double_as_longlong(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp64"), ): ("__nv_double_as_longlong", core.dtype("int64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def fast_sinf(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_fast_sinf", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def fast_cosf(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_fast_cosf", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def fast_log2f(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_fast_log2f", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def fast_logf(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_fast_logf", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def fast_expf(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_fast_expf", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def fast_tanf(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_fast_tanf", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def fast_exp10f(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_fast_exp10f", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def fast_log10f(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_fast_log10f", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def fast_powf(arg0, arg1, _semantic=None): + return core.extern_elementwise("", "", [arg0, arg1], { + (core.dtype("fp32"), core.dtype("fp32")): ("__nv_fast_powf", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def hadd(arg0, arg1, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1], { + (core.dtype("int32"), core.dtype("int32")): ("__nv_hadd", core.dtype("int32")), + (core.dtype("uint32"), core.dtype("uint32")): ("__nv_uhadd", core.dtype("uint32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def rhadd(arg0, arg1, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1], { + (core.dtype("int32"), core.dtype("int32")): ("__nv_rhadd", core.dtype("int32")), + (core.dtype("uint32"), core.dtype("uint32")): ("__nv_urhadd", core.dtype("uint32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def sub_rn(arg0, arg1, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1], { + (core.dtype("fp32"), core.dtype("fp32")): ("__nv_fsub_rn", core.dtype("fp32")), + (core.dtype("fp64"), core.dtype("fp64")): ("__nv_dsub_rn", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def sub_rz(arg0, arg1, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1], { + (core.dtype("fp32"), core.dtype("fp32")): ("__nv_fsub_rz", core.dtype("fp32")), + (core.dtype("fp64"), core.dtype("fp64")): ("__nv_dsub_rz", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def sub_rd(arg0, arg1, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1], { + (core.dtype("fp32"), core.dtype("fp32")): ("__nv_fsub_rd", core.dtype("fp32")), + (core.dtype("fp64"), core.dtype("fp64")): ("__nv_dsub_rd", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def sub_ru(arg0, arg1, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1], { + (core.dtype("fp32"), core.dtype("fp32")): ("__nv_fsub_ru", core.dtype("fp32")), + (core.dtype("fp64"), core.dtype("fp64")): ("__nv_dsub_ru", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def rsqrt_rn(arg0, _semantic=None): + return core.extern_elementwise("", "", [ + arg0, + ], { + (core.dtype("fp32"), ): ("__nv_frsqrt_rn", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def ffs(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [ + arg0, + ], { + (core.dtype("int32"), ): ("__nv_ffs", core.dtype("int32")), + (core.dtype("int64"), ): ("__nv_ffsll", core.dtype("int32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def rint(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [ + arg0, + ], { + (core.dtype("fp32"), ): ("__nv_rintf", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_rint", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def llrint(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [ + arg0, + ], { + (core.dtype("fp32"), ): ("__nv_llrintf", core.dtype("int64")), + (core.dtype("fp64"), ): ("__nv_llrint", core.dtype("int64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def nearbyint(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [ + arg0, + ], { + (core.dtype("fp32"), ): ("__nv_nearbyintf", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_nearbyint", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def isnan(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [ + arg0, + ], { + (core.dtype("fp32"), ): ("__nv_isnanf", core.dtype("int32")), + (core.dtype("fp64"), ): ("__nv_isnand", core.dtype("int32")), + }, is_pure=True, _semantic=_semantic).to(core.int1, _semantic=_semantic) + + +@core.extern +def signbit(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [ + arg0, + ], { + (core.dtype("fp32"), ): ("__nv_signbitf", core.dtype("int32")), + (core.dtype("fp64"), ): ("__nv_signbitd", core.dtype("int32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def copysign(arg0, arg1, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1], { + (core.dtype("fp32"), core.dtype("fp32")): ("__nv_copysignf", core.dtype("fp32")), + (core.dtype("fp64"), core.dtype("fp64")): ("__nv_copysign", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def finitef(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_finitef", core.dtype("int32")), + }, is_pure=True, _semantic=_semantic).to(core.int1, _semantic=_semantic) + + +@core.extern +def isinf(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_isinff", core.dtype("int32")), + (core.dtype("fp64"), ): ("__nv_isinfd", core.dtype("int32")), + }, is_pure=True, _semantic=_semantic).to(core.int1, _semantic=_semantic) + + +@core.extern +def nextafter(arg0, arg1, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1], { + (core.dtype("fp32"), core.dtype("fp32")): ("__nv_nextafterf", core.dtype("fp32")), + (core.dtype("fp64"), core.dtype("fp64")): ("__nv_nextafter", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def sin(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_sinf", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_sin", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def cos(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_cosf", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_cos", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def sinpi(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_sinpif", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_sinpi", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def cospi(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_cospif", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_cospi", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def tan(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_tanf", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_tan", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def log2(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_log2f", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_log2", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def exp(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_expf", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_exp", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def exp10(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_exp10f", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_exp10", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def cosh(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_coshf", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_cosh", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def sinh(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_sinhf", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_sinh", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def tanh(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_tanhf", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_tanh", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def atan2(arg0, arg1, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1], { + (core.dtype("fp32"), core.dtype("fp32")): ("__nv_atan2f", core.dtype("fp32")), + (core.dtype("fp64"), core.dtype("fp64")): ("__nv_atan2", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def atan(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_atanf", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_atan", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def asin(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_asinf", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_asin", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def acos(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_acosf", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_acos", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def log(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_logf", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_log", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def log10(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_log10f", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_log10", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def log1p(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_log1pf", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_log1p", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def acosh(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_acoshf", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_acosh", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def asinh(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_asinhf", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_asinh", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def atanh(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_atanhf", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_atanh", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def expm1(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_expm1f", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_expm1", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def hypot(arg0, arg1, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1], { + (core.dtype("fp32"), core.dtype("fp32")): ("__nv_hypotf", core.dtype("fp32")), + (core.dtype("fp64"), core.dtype("fp64")): ("__nv_hypot", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def rhypot(arg0, arg1, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1], { + (core.dtype("fp32"), core.dtype("fp32")): ("__nv_rhypotf", core.dtype("fp32")), + (core.dtype("fp64"), core.dtype("fp64")): ("__nv_rhypot", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def norm3d(arg0, arg1, arg2, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1, arg2], { + (core.dtype("fp32"), core.dtype("fp32"), core.dtype("fp32")): ("__nv_norm3df", core.dtype("fp32")), + (core.dtype("fp64"), core.dtype("fp64"), core.dtype("fp64")): ("__nv_norm3d", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def rnorm3d(arg0, arg1, arg2, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1, arg2], { + (core.dtype("fp32"), core.dtype("fp32"), core.dtype("fp32")): ("__nv_rnorm3df", core.dtype("fp32")), + (core.dtype("fp64"), core.dtype("fp64"), core.dtype("fp64")): ("__nv_rnorm3d", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def norm4d(arg0, arg1, arg2, arg3, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1, arg2, arg3], { + (core.dtype("fp32"), core.dtype("fp32"), core.dtype("fp32"), core.dtype("fp32")): + ("__nv_norm4df", core.dtype("fp32")), + (core.dtype("fp64"), core.dtype("fp64"), core.dtype("fp64"), core.dtype("fp64")): + ("__nv_norm4d", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def rnorm4d(arg0, arg1, arg2, arg3, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1, arg2, arg3], { + (core.dtype("fp32"), core.dtype("fp32"), core.dtype("fp32"), core.dtype("fp32")): + ("__nv_rnorm4df", core.dtype("fp32")), + (core.dtype("fp64"), core.dtype("fp64"), core.dtype("fp64"), core.dtype("fp64")): + ("__nv_rnorm4d", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def cbrt(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_cbrtf", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_cbrt", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def rcbrt(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_rcbrtf", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_rcbrt", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def j0(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_j0f", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_j0", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def j1(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_j1f", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_j1", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def y0(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_y0f", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_y0", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def y1(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_y1f", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_y1", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def yn(arg0, arg1, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1], { + (core.dtype("int32"), core.dtype("fp32")): ("__nv_ynf", core.dtype("fp32")), + (core.dtype("int32"), core.dtype("fp64")): ("__nv_yn", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def jn(arg0, arg1, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1], { + (core.dtype("int32"), core.dtype("fp32")): ("__nv_jnf", core.dtype("fp32")), + (core.dtype("int32"), core.dtype("fp64")): ("__nv_jn", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def cyl_bessel_i0(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_cyl_bessel_i0f", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_cyl_bessel_i0", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def cyl_bessel_i1(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_cyl_bessel_i1f", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_cyl_bessel_i1", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def erf(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_erff", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_erf", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def erfinv(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_erfinvf", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_erfinv", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def erfc(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_erfcf", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_erfc", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def erfcx(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_erfcxf", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_erfcx", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def erfcinv(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_erfcinvf", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_erfcinv", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def normcdfinv(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_normcdfinvf", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_normcdfinv", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def normcdf(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_normcdff", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_normcdf", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def lgamma(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_lgammaf", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_lgamma", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def ldexp(arg0, arg1, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1], { + (core.dtype("fp32"), core.dtype("int32")): ("__nv_ldexpf", core.dtype("fp32")), + (core.dtype("fp64"), core.dtype("int32")): ("__nv_ldexp", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def scalbn(arg0, arg1, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1], { + (core.dtype("fp32"), core.dtype("int32")): ("__nv_scalbnf", core.dtype("fp32")), + (core.dtype("fp64"), core.dtype("int32")): ("__nv_scalbn", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def fmod(arg0, arg1, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1], { + (core.dtype("fp32"), core.dtype("fp32")): ("__nv_fmodf", core.dtype("fp32")), + (core.dtype("fp64"), core.dtype("fp64")): ("__nv_fmod", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def remainder(arg0, arg1, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1], { + (core.dtype("fp32"), core.dtype("fp32")): ("__nv_remainderf", core.dtype("fp32")), + (core.dtype("fp64"), core.dtype("fp64")): ("__nv_remainder", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def fma(arg0, arg1, arg2, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1, arg2], { + (core.dtype("fp32"), core.dtype("fp32"), core.dtype("fp32")): ("__nv_fmaf", core.dtype("fp32")), + (core.dtype("fp64"), core.dtype("fp64"), core.dtype("fp64")): ("__nv_fma", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def pow(arg0, arg1, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1], { + (core.dtype("fp32"), core.dtype("int32")): ("__nv_powif", core.dtype("fp32")), + (core.dtype("fp64"), core.dtype("int32")): ("__nv_powi", core.dtype("fp64")), + (core.dtype("fp32"), core.dtype("fp32")): ("__nv_powf", core.dtype("fp32")), + (core.dtype("fp64"), core.dtype("fp64")): ("__nv_pow", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def tgamma(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_tgammaf", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_tgamma", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def round(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_roundf", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_round", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def llround(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_llroundf", core.dtype("int64")), + (core.dtype("fp64"), ): ("__nv_llround", core.dtype("int64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def fdim(arg0, arg1, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1], { + (core.dtype("fp32"), core.dtype("fp32")): ("__nv_fdimf", core.dtype("fp32")), + (core.dtype("fp64"), core.dtype("fp64")): ("__nv_fdim", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def ilogb(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_ilogbf", core.dtype("int32")), + (core.dtype("fp64"), ): ("__nv_ilogb", core.dtype("int32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def logb(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__nv_logbf", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__nv_logb", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def isfinited(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp64"), ): ("__nv_isfinited", core.dtype("int32")), + }, is_pure=True, _semantic=_semantic).to(core.int1, _semantic=_semantic) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/language/extra/cuda/utils.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/language/extra/cuda/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..bb67b573a381156e7713a3359db859409701d7d7 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/language/extra/cuda/utils.py @@ -0,0 +1,109 @@ +from triton.language import core + + +@core.extern +def globaltimer(_semantic=None): + return core.inline_asm_elementwise("mov.u64 $0, %globaltimer;", "=l", [], dtype=core.int64, is_pure=False, pack=1, + _semantic=_semantic) + + +@core.extern +def smid(_semantic=None): + return core.inline_asm_elementwise("mov.u32 $0, %smid;", "=r", [], dtype=core.int32, is_pure=True, pack=1, + _semantic=_semantic) + + +@core.builtin +def num_threads(_semantic=None): + return core.constexpr(_semantic.builder.options.num_warps * 32) + + +@core.builtin +def num_warps(_semantic=None): + return core.constexpr(_semantic.builder.options.num_warps) + + +# ----- FP8E4M3B15 ------ +# This data-type is a variant of the standard FP8E4M3 format. +# It was designed for fast software conversion to FP16 on +# nvidia GPUs that do not support it natively. +# This is the same format as FP8E4M3Nv, but: +# - the exponent bias is 15 instead of 7 +# - 0xff and 0x7f are mapped to +-1.750 instead of +-nan +@core.builtin +def convert_fp8e4b15_to_float16(arg, _semantic=None): + return core.inline_asm_elementwise( + "{ \n" + ".reg .b32 a<2>, b<2>; \n" + "prmt.b32 a0, 0, $2, 0x5746; \n" + "and.b32 b0, a0, 0x7f007f00; \n" + "and.b32 b1, a0, 0x00ff00ff; \n" + "and.b32 a1, a0, 0x00800080; \n" + "shr.b32 b0, b0, 1; \n" + "add.u32 b1, b1, a1; \n" + "lop3.b32 $0, b0, 0x80008000, a0, 0xf8; \n" + "shl.b32 $1, b1, 7; \n" + "} \n", "=r,=r,r", [arg], dtype=core.float16, is_pure=True, pack=4, + _semantic=_semantic) + + +@core.builtin +def convert_float16_to_fp8e4b15(arg, has_minx2, _semantic=None): + asm = """{ + .reg .pred p<4>; + .reg .b32 a<2>, b<2>; + .reg .b16 c<4>; + .reg .b16 max_val_f16; + .reg .b32 max_val_f16x2; + mov.b16 max_val_f16, 0x3F00; + mov.b32 max_val_f16x2, 0x3F003F00; + and.b32 a0, $1, 0x7fff7fff; + and.b32 a1, $2, 0x7fff7fff;""" + if has_minx2: + asm += """min.f16x2 a0, a0, max_val_f16x2; + min.f16x2 a1, a1, max_val_f16x2;""" + else: + asm += """setp.lt.f16x2 p0|p1, a0, max_val_f16x2; + setp.lt.f16x2 p2|p3, a1, max_val_f16x2; + mov.b32 {c0, c1}, a0; + mov.b32 {c2, c3}, a1; + selp.b16 c0, c0, max_val_f16, p0; + selp.b16 c1, c1, max_val_f16, p1; + selp.b16 c2, c2, max_val_f16, p2; + selp.b16 c3, c3, max_val_f16, p3; + mov.b32 a0, {c0, c1}; + mov.b32 a1, {c2, c3};""" + asm += """mad.lo.u32 a0, a0, 2, 0x00800080; + mad.lo.u32 a1, a1, 2, 0x00800080; + lop3.b32 b0, $1, 0x80008000, a0, 0xea; + lop3.b32 b1, $2, 0x80008000, a1, 0xea; + prmt.b32 $0, b0, b1, 0x7531; + }""" + return core.inline_asm_elementwise(asm, "=r,r,r", [arg], dtype=core.float8e4b15, is_pure=True, pack=4, + _semantic=_semantic) + + +@core.builtin +def convert_custom_float8(arg, dst_ty, fp_downcast_rounding, has_minx2, _semantic=None): + if arg.type.scalar.is_fp8e4b15(): + upcast_val = convert_fp8e4b15_to_float16(arg, _semantic=_semantic) + if dst_ty.scalar.is_fp32(): + upcast_val = upcast_val.to(core.float32, _semantic=_semantic) + return upcast_val + + assert arg.type.scalar.is_fp16() or arg.type.scalar.is_fp32() + downcast_val = arg + if arg.type.scalar.is_fp32(): + downcast_val = downcast_val.to(core.float16, fp_downcast_rounding="rtz", _semantic=_semantic) + downcast_val = convert_float16_to_fp8e4b15(downcast_val, has_minx2=has_minx2, _semantic=_semantic) + return downcast_val + + +@core.builtin +def convert_custom_float8_sm80(arg, dst_ty, fp_downcast_rounding=None, _semantic=None): + return convert_custom_float8(arg, dst_ty, fp_downcast_rounding, has_minx2=True, _semantic=_semantic) + + +@core.builtin +def convert_custom_float8_sm70(arg, dst_ty, fp_downcast_rounding=None, _semantic=None): + return convert_custom_float8(arg, dst_ty, fp_downcast_rounding, has_minx2=False, _semantic=_semantic) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/language/extra/hip/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/language/extra/hip/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..dc9b571ddfacbd15b1e8258cce592313f7d45a3e --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/language/extra/hip/__init__.py @@ -0,0 +1,5 @@ +from . import libdevice + +from .utils import memrealtime + +__all__ = ["libdevice", "memrealtime"] diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/language/extra/hip/libdevice.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/language/extra/hip/libdevice.py new file mode 100644 index 0000000000000000000000000000000000000000..fc8d1b11a80299ae9f203bc48f039020faa80353 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/language/extra/hip/libdevice.py @@ -0,0 +1,491 @@ +from triton.language import core + + +@core.extern +def abs(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("int32"), ): ("__triton_hip_iabs", core.dtype("int32")), + (core.dtype("int64"), ): ("__triton_hip_iabs", core.dtype("int64")), + (core.dtype("fp32"), ): ("__triton_hip_fabs", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__triton_hip_fabs", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def floor(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__ocml_floor_f32", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__ocml_floor_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def rsqrt(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__ocml_rsqrt_f32", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__ocml_rsqrt_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def ceil(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__ocml_ceil_f32", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__ocml_ceil_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def trunc(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__ocml_trunc_f32", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__ocml_trunc_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def exp2(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__ocml_exp2_f32", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__ocml_exp2_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def exp(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__ocml_exp_f32", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__ocml_exp_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def fast_expf(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp32"), ): ("__triton_hip_fast_expf", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def fast_tanhf(arg0, _semantic=None): + return core.extern_elementwise("", "", [arg0], { + (core.dtype("fp32"), ): ("__triton_hip_fast_tanhf", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def fast_dividef(arg0, arg1, _semantic=None): + return core.extern_elementwise("", "", [arg0, arg1], { + (core.dtype("fp32"), core.dtype("fp32")): ("__triton_hip_fast_fdividef", core.dtype("fp32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def sqrt(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__ocml_sqrt_f32", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__ocml_sqrt_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def llrint(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__triton_hip_llrint", core.dtype("int64")), + (core.dtype("fp64"), ): ("__triton_hip_llrint", core.dtype("int64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def nearbyint(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [ + arg0, + ], { + (core.dtype("fp32"), ): ("__ocml_nearbyint_f32", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__ocml_nearbyint_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def isnan(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [ + arg0, + ], { + (core.dtype("fp32"), ): ("__ocml_isnan_f32", core.dtype("int32")), + (core.dtype("fp64"), ): ("__ocml_isnan_f64", core.dtype("int32")), + }, is_pure=True, _semantic=_semantic).to(core.int1, _semantic=_semantic) + + +@core.extern +def signbit(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [ + arg0, + ], { + (core.dtype("fp32"), ): ("__ocml_signbit_f32", core.dtype("int32")), + (core.dtype("fp64"), ): ("__ocml_signbit_f64", core.dtype("int32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def copysign(arg0, arg1, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1], { + (core.dtype("fp32"), core.dtype("fp32")): ("__ocml_copysign_f32", core.dtype("fp32")), + (core.dtype("fp64"), core.dtype("fp64")): ("__ocml_copysign_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def isinf(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__ocml_isinf_f32", core.dtype("int32")), + (core.dtype("fp64"), ): ("__ocml_isinf_f64", core.dtype("int32")), + }, is_pure=True, _semantic=_semantic).to(core.int1, _semantic=_semantic) + + +@core.extern +def nextafter(arg0, arg1, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1], { + (core.dtype("fp32"), core.dtype("fp32")): ("__ocml_nextafter_f32", core.dtype("fp32")), + (core.dtype("fp64"), core.dtype("fp64")): ("__ocml_nextafter_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def sin(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__ocml_sin_f32", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__ocml_sin_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def cos(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__ocml_cos_f32", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__ocml_cos_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def tan(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__ocml_tan_f32", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__ocml_tan_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def log2(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__ocml_log2_f32", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__ocml_log2_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def cosh(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__ocml_cosh_f32", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__ocml_cosh_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def sinh(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__ocml_sinh_f32", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__ocml_sinh_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def tanh(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__ocml_tanh_f32", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__ocml_tanh_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def atan2(arg0, arg1, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1], { + (core.dtype("fp32"), core.dtype("fp32")): ("__ocml_atan2_f32", core.dtype("fp32")), + (core.dtype("fp64"), core.dtype("fp64")): ("__ocml_atan2_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def atan(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__ocml_atan_f32", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__ocml_atan_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def asin(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__ocml_asin_f32", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__ocml_asin_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def acos(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__ocml_acos_f32", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__ocml_acos_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def log(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__ocml_log_f32", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__ocml_log_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def log10(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__ocml_log10_f32", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__ocml_log10_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def log1p(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__ocml_log1p_f32", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__ocml_log1p_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def acosh(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__ocml_acosh_f32", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__ocml_acosh_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def asinh(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__ocml_asinh_f32", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__ocml_asinh_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def atanh(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__ocml_atanh_f32", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__ocml_atanh_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def expm1(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__ocml_expm1_f32", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__ocml_expm1_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def hypot(arg0, arg1, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1], { + (core.dtype("fp32"), core.dtype("fp32")): ("__ocml_hypot_f32", core.dtype("fp32")), + (core.dtype("fp64"), core.dtype("fp64")): ("__ocml_hypot_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def j0(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__ocml_j0_f32", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__ocml_j0_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def j1(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__ocml_j1_f32", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__ocml_j1_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def y0(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__ocml_y0_f32", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__ocml_y0_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def y1(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__ocml_y1_f32", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__ocml_y1_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def cyl_bessel_i0(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__ocml_i0_f32", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__ocml_i0_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def cyl_bessel_i1(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__ocml_i1_f32", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__ocml_i1_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def erf(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__ocml_erf_f32", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__ocml_erf_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def erfinv(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__ocml_erfinv_f32", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__ocml_erfinv_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def erfc(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__ocml_erfc_f32", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__ocml_erfc_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def erfcx(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__ocml_erfcx_f32", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__ocml_erfcx_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def lgamma(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__ocml_lgamma_f32", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__ocml_lgamma_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def ldexp(arg0, arg1, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1], { + (core.dtype("fp32"), core.dtype("int32")): ("__ocml_ldexp_f32", core.dtype("fp32")), + (core.dtype("fp64"), core.dtype("int32")): ("__ocml_ldexp_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def fmod(arg0, arg1, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1], { + (core.dtype("fp32"), core.dtype("fp32")): ("__ocml_fmod_f32", core.dtype("fp32")), + (core.dtype("fp64"), core.dtype("fp64")): ("__ocml_fmod_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def fma(arg0, arg1, arg2, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1, arg2], { + (core.dtype("fp32"), core.dtype("fp32"), core.dtype("fp32")): ("__ocml_fma_f32", core.dtype("fp32")), + (core.dtype("fp64"), core.dtype("fp64"), core.dtype("fp64")): ("__ocml_fma_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def pow(arg0, arg1, _semantic=None): + return core.extern_elementwise( + "", "", [arg0, arg1], { + (core.dtype("fp32"), core.dtype("int32")): ("__ocml_pown_f32", core.dtype("fp32")), + (core.dtype("fp64"), core.dtype("int32")): ("__ocml_pown_f64", core.dtype("fp64")), + (core.dtype("fp32"), core.dtype("fp32")): ("__ocml_pow_f32", core.dtype("fp32")), + (core.dtype("fp64"), core.dtype("fp64")): ("__ocml_pow_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def ilogb(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__ocml_ilogb_f32", core.dtype("int32")), + (core.dtype("fp64"), ): ("__ocml_ilogb_f64", core.dtype("int32")), + }, is_pure=True, _semantic=_semantic) + + +@core.extern +def round(arg0, _semantic=None): + return core.extern_elementwise( + "", "", [arg0], { + (core.dtype("fp32"), ): ("__ocml_round_f32", core.dtype("fp32")), + (core.dtype("fp64"), ): ("__ocml_round_f64", core.dtype("fp64")), + }, is_pure=True, _semantic=_semantic) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/language/extra/hip/utils.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/language/extra/hip/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..c9dbabc4d3cfdbd5ee91b38ef3be969b9f187046 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/language/extra/hip/utils.py @@ -0,0 +1,35 @@ +from triton.language import core + + +@core.extern +def memrealtime(_semantic=None): + """ + Returns a 64-bit real time-counter value + """ + target_arch = _semantic.builder.options.arch + if 'gfx11' in target_arch or 'gfx12' in target_arch: + return core.inline_asm_elementwise( + """ + s_sendmsg_rtn_b64 $0, sendmsg(MSG_RTN_GET_REALTIME) + s_waitcnt lgkmcnt(0) + """, + "=r", + [], + dtype=core.int64, + is_pure=False, + pack=1, + _semantic=_semantic, + ) + else: + return core.inline_asm_elementwise( + """ + s_memrealtime $0 + s_waitcnt vmcnt(0) + """, + "=r", + [], + dtype=core.int64, + is_pure=False, + pack=1, + _semantic=_semantic, + ) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/language/extra/libdevice.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/language/extra/libdevice.py new file mode 100644 index 0000000000000000000000000000000000000000..e29810bfbabdcc09d6a28f062c18ee6af3fe7575 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/language/extra/libdevice.py @@ -0,0 +1,790 @@ +def clz(arg0): + ... + + +def popc(arg0): + ... + + +def byte_perm(arg0, arg1, arg2): + ... + + +def mulhi(arg0, arg1): + ... + + +def mul24(arg0, arg1): + ... + + +def brev(arg0): + ... + + +def sad(arg0, arg1, arg2): + ... + + +def abs(arg0): + ... + + +def floor(arg0): + ... + + +def rcp64h(arg0): + ... + + +def rsqrt(arg0): + ... + + +def ceil(arg0): + ... + + +def trunc(arg0): + ... + + +def exp2(arg0): + ... + + +def saturatef(arg0): + ... + + +def fma_rn(arg0, arg1, arg2): + ... + + +def fma_rz(arg0, arg1, arg2): + ... + + +def fma_rd(arg0, arg1, arg2): + ... + + +def fma_ru(arg0, arg1, arg2): + ... + + +def fast_dividef(arg0, arg1): + ... + + +def div_rn(arg0, arg1): + ... + + +def div_rz(arg0, arg1): + ... + + +def div_rd(arg0, arg1): + ... + + +def div_ru(arg0, arg1): + ... + + +def rcp_rn(arg0): + ... + + +def rcp_rz(arg0): + ... + + +def rcp_rd(arg0): + ... + + +def rcp_ru(arg0): + ... + + +def sqrt_rn(arg0): + ... + + +def sqrt_rz(arg0): + ... + + +def sqrt_rd(arg0): + ... + + +def sqrt_ru(arg0): + ... + + +def sqrt(arg0): + ... + + +def add_rn(arg0, arg1): + ... + + +def add_rz(arg0, arg1): + ... + + +def add_rd(arg0, arg1): + ... + + +def add_ru(arg0, arg1): + ... + + +def mul_rn(arg0, arg1): + ... + + +def mul_rz(arg0, arg1): + ... + + +def mul_rd(arg0, arg1): + ... + + +def mul_ru(arg0, arg1): + ... + + +def double2float_rn(arg0): + ... + + +def double2float_rz(arg0): + ... + + +def double2float_rd(arg0): + ... + + +def double2float_ru(arg0): + ... + + +def double2int_rn(arg0): + ... + + +def double2int_rz(arg0): + ... + + +def double2int_rd(arg0): + ... + + +def double2int_ru(arg0): + ... + + +def double2uint_rn(arg0): + ... + + +def double2uint_rz(arg0): + ... + + +def double2uint_rd(arg0): + ... + + +def double2uint_ru(arg0): + ... + + +def int2double_rn(arg0): + ... + + +def uint2double_rn(arg0): + ... + + +def float2int_rn(arg0): + ... + + +def float2int_rz(arg0): + ... + + +def float2int_rd(arg0): + ... + + +def float2int_ru(arg0): + ... + + +def float2uint_rn(arg0): + ... + + +def float2uint_rz(arg0): + ... + + +def float2uint_rd(arg0): + ... + + +def float2uint_ru(arg0): + ... + + +def int2float_rn(arg0): + ... + + +def int2float_rz(arg0): + ... + + +def int2float_rd(arg0): + ... + + +def int2float_ru(arg0): + ... + + +def uint2float_rn(arg0): + ... + + +def uint2float_rz(arg0): + ... + + +def uint2float_rd(arg0): + ... + + +def uint2float_ru(arg0): + ... + + +def hiloint2double(arg0, arg1): + ... + + +def double2loint(arg0): + ... + + +def double2hiint(arg0): + ... + + +def float2ll_rn(arg0): + ... + + +def float2ll_rz(arg0): + ... + + +def float2ll_rd(arg0): + ... + + +def float2ll_ru(arg0): + ... + + +def float2ull_rn(arg0): + ... + + +def float2ull_rz(arg0): + ... + + +def float2ull_rd(arg0): + ... + + +def float2ull_ru(arg0): + ... + + +def double2ll_rn(arg0): + ... + + +def double2ll_rz(arg0): + ... + + +def double2ll_rd(arg0): + ... + + +def double2ll_ru(arg0): + ... + + +def double2ull_rn(arg0): + ... + + +def double2ull_rz(arg0): + ... + + +def double2ull_rd(arg0): + ... + + +def double2ull_ru(arg0): + ... + + +def ll2float_rn(arg0): + ... + + +def ll2float_rz(arg0): + ... + + +def ll2float_rd(arg0): + ... + + +def ll2float_ru(arg0): + ... + + +def ull2float_rn(arg0): + ... + + +def ull2float_rz(arg0): + ... + + +def ull2float_rd(arg0): + ... + + +def ull2float_ru(arg0): + ... + + +def ll2double_rn(arg0): + ... + + +def ll2double_rz(arg0): + ... + + +def ll2double_rd(arg0): + ... + + +def ll2double_ru(arg0): + ... + + +def ull2double_rn(arg0): + ... + + +def ull2double_rz(arg0): + ... + + +def ull2double_rd(arg0): + ... + + +def ull2double_ru(arg0): + ... + + +def int_as_float(arg0): + ... + + +def float_as_int(arg0): + ... + + +def uint_as_float(arg0): + ... + + +def float_as_uint(arg0): + ... + + +def longlong_as_double(arg0): + ... + + +def double_as_longlong(arg0): + ... + + +def fast_sinf(arg0): + ... + + +def fast_cosf(arg0): + ... + + +def fast_log2f(arg0): + ... + + +def fast_logf(arg0): + ... + + +def fast_expf(arg0): + ... + + +def fast_tanhf(arg0): + ... + + +def fast_tanf(arg0): + ... + + +def fast_exp10f(arg0): + ... + + +def fast_log10f(arg0): + ... + + +def fast_powf(arg0, arg1): + ... + + +def hadd(arg0, arg1): + ... + + +def rhadd(arg0, arg1): + ... + + +def sub_rn(arg0, arg1): + ... + + +def sub_rz(arg0, arg1): + ... + + +def sub_rd(arg0, arg1): + ... + + +def sub_ru(arg0, arg1): + ... + + +def rsqrt_rn(arg0): + ... + + +def ffs(arg0): + ... + + +def rint(arg0): + ... + + +def llrint(arg0): + ... + + +def nearbyint(arg0): + ... + + +def isnan(arg0): + ... + + +def signbit(arg0): + ... + + +def copysign(arg0, arg1): + ... + + +def finitef(arg0): + ... + + +def isinf(arg0): + ... + + +def nextafter(arg0, arg1): + ... + + +def sin(arg0): + ... + + +def cos(arg0): + ... + + +def sinpi(arg0): + ... + + +def cospi(arg0): + ... + + +def tan(arg0): + ... + + +def log2(arg0): + ... + + +def exp(arg0): + ... + + +def exp10(arg0): + ... + + +def cosh(arg0): + ... + + +def sinh(arg0): + ... + + +def tanh(arg0): + ... + + +def atan2(arg0, arg1): + ... + + +def atan(arg0): + ... + + +def asin(arg0): + ... + + +def acos(arg0): + ... + + +def log(arg0): + ... + + +def log10(arg0): + ... + + +def log1p(arg0): + ... + + +def acosh(arg0): + ... + + +def asinh(arg0): + ... + + +def atanh(arg0): + ... + + +def expm1(arg0): + ... + + +def hypot(arg0, arg1): + ... + + +def rhypot(arg0, arg1): + ... + + +def norm3d(arg0, arg1, arg2): + ... + + +def rnorm3d(arg0, arg1, arg2): + ... + + +def norm4d(arg0, arg1, arg2, arg3): + ... + + +def rnorm4d(arg0, arg1, arg2, arg3): + ... + + +def cbrt(arg0): + ... + + +def rcbrt(arg0): + ... + + +def j0(arg0): + ... + + +def j1(arg0): + ... + + +def y0(arg0): + ... + + +def y1(arg0): + ... + + +def yn(arg0, arg1): + ... + + +def jn(arg0, arg1): + ... + + +def cyl_bessel_i0(arg0): + ... + + +def cyl_bessel_i1(arg0): + ... + + +def erf(arg0): + ... + + +def erfinv(arg0): + ... + + +def erfc(arg0): + ... + + +def erfcx(arg0): + ... + + +def erfcinv(arg0): + ... + + +def normcdfinv(arg0): + ... + + +def normcdf(arg0): + ... + + +def lgamma(arg0): + ... + + +def ldexp(arg0, arg1): + ... + + +def scalbn(arg0, arg1): + ... + + +def fmod(arg0, arg1): + ... + + +def remainder(arg0, arg1): + ... + + +def fma(arg0, arg1, arg2): + ... + + +def pow(arg0, arg1): + ... + + +def tgamma(arg0): + ... + + +def round(arg0): + ... + + +def llround(arg0): + ... + + +def fdim(arg0, arg1): + ... + + +def ilogb(arg0): + ... + + +def logb(arg0): + ... + + +def isfinited(arg0): + ... diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/language/math.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/language/math.py new file mode 100644 index 0000000000000000000000000000000000000000..582cd876cb13374a0d31e8c783e4fea1a1003c4a --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/language/math.py @@ -0,0 +1,249 @@ +from . import core +from functools import wraps +from typing import List + +T = core.TypeVar('T') + + +def _check_dtype(dtypes: List[str]) -> T: + """ + We're following libdevice's convention to check accepted data types for math functions. + It is not a good practice to support all data types as accelerators/GPUs don't support + many float16 and bfloat16 math operations. + We should let the users know that they are using and invoke explicit cast to convert + the data type to the supported one. + """ + + def wrapper(fn): + + @wraps(fn) + def check(*args, **kwargs): + # concatenate args and kwargs + all_args = list(args) + list(kwargs.values()) + for arg in [a for a in all_args if isinstance(a, core.tensor)]: + if arg.type.scalar.name not in dtypes: + raise ValueError(f"Expected dtype {dtypes} but got {arg.type.scalar.name}") + return fn(*args, **kwargs) + + return check + + return wrapper + + +def _add_math_1arg_docstr(name: str) -> core.Callable[[T], T]: + + def _decorator(func: T) -> T: + docstr = """ + Computes the element-wise {name} of :code:`x`. + + :param x: the input values + :type x: Block + """ + func.__doc__ = docstr.format(name=name) + return func + + return _decorator + + +def _add_math_2arg_docstr(name: str) -> core.Callable[[T], T]: + + def _decorator(func: T) -> T: + docstr = """ + Computes the element-wise {name} of :code:`x` and :code:`y`. + + :param x: the input values + :type x: Block + :param y: the input values + :type y: Block + """ + func.__doc__ = docstr.format(name=name) + return func + + return _decorator + + +def _add_math_3arg_docstr(name: str) -> core.Callable[[T], T]: + + def _decorator(func: T) -> T: + docstr = """ + Computes the element-wise {name} of :code:`x`, :code:`y`, and :code:`z`. + + :param x: the input values + :type x: Block + :param y: the input values + :type y: Block + :param z: the input values + :type z: Block + """ + func.__doc__ = docstr.format(name=name) + return func + + return _decorator + + +@core.builtin +@_check_dtype(dtypes=["int32", "int64", "uint32", "uint64"]) +@_add_math_2arg_docstr("most significant N bits of the 2N-bit product") +def umulhi(x, y, _semantic=None): + x = _semantic.to_tensor(x) + y = _semantic.to_tensor(y) + x, y = core.binary_op_type_legalization(x, y, _semantic) + return core.tensor(_semantic.builder.create_umulhi(x.handle, y.handle), x.type) + + +@core.builtin +@_check_dtype(dtypes=["fp32", "fp64"]) +@_add_math_1arg_docstr("exponential") +@core._tensor_member_fn +def exp(x, _semantic=None): + x = _semantic.to_tensor(x) + return core.tensor(_semantic.builder.create_exp(x.handle), x.type) + + +@core.builtin +@_check_dtype(dtypes=["fp32", "fp64"]) +@_add_math_1arg_docstr("exponential (base 2)") +@core._tensor_member_fn +def exp2(x, _semantic=None): + x = _semantic.to_tensor(x) + return core.tensor(_semantic.builder.create_exp2(x.handle), x.type) + + +@core.builtin +@_check_dtype(dtypes=["fp32", "fp64"]) +@_add_math_1arg_docstr("natural logarithm") +@core._tensor_member_fn +def log(x, _semantic=None): + x = _semantic.to_tensor(x) + return core.tensor(_semantic.builder.create_log(x.handle), x.type) + + +@core.builtin +@_check_dtype(dtypes=["fp32", "fp64"]) +@_add_math_1arg_docstr("logarithm (base 2)") +@core._tensor_member_fn +def log2(x, _semantic=None): + x = _semantic.to_tensor(x) + return core.tensor(_semantic.builder.create_log2(x.handle), x.type) + + +@core.builtin +@_check_dtype(dtypes=["fp32", "fp64"]) +@_add_math_1arg_docstr("cosine") +@core._tensor_member_fn +def cos(x, _semantic=None): + x = _semantic.to_tensor(x) + return core.tensor(_semantic.builder.create_cos(x.handle), x.type) + + +@core.builtin +@_check_dtype(dtypes=["fp32", "fp64"]) +@_add_math_1arg_docstr("sine") +@core._tensor_member_fn +def sin(x, _semantic=None): + x = _semantic.to_tensor(x) + return core.tensor(_semantic.builder.create_sin(x.handle), x.type) + + +@core.builtin +@_check_dtype(dtypes=["fp32", "fp64"]) +@_add_math_1arg_docstr("fast square root") +@core._tensor_member_fn +def sqrt(x, _semantic=None): + x = _semantic.to_tensor(x) + return core.tensor(_semantic.builder.create_sqrt(x.handle), x.type) + + +@core.builtin +@_check_dtype(dtypes=["fp32"]) +@_add_math_1arg_docstr("precise square root (rounding to nearest wrt the IEEE standard)") +@core._tensor_member_fn +def sqrt_rn(x, _semantic=None): + x = _semantic.to_tensor(x) + return core.tensor(_semantic.builder.create_precise_sqrt(x.handle), x.type) + + +@core.builtin +@_check_dtype(dtypes=["fp32", "fp64"]) +@_add_math_1arg_docstr("inverse square root") +@core._tensor_member_fn +def rsqrt(x, _semantic=None): + x = _semantic.to_tensor(x) + return core.tensor(_semantic.builder.create_rsqrt(x.handle), x.type) + + +@core._tensor_member_fn +@core.builtin +@_add_math_1arg_docstr("absolute value") +def abs(x, _semantic=None): + x = _semantic.to_tensor(x) + dtype = x.dtype + if dtype.is_fp8e4b15(): + mask = core.full(x.shape, 0x7F, core.int8, _semantic=_semantic) + return core.tensor(_semantic.builder.create_and(x.handle, mask.handle), x.type) + elif dtype.is_floating(): + return core.tensor(_semantic.builder.create_fabs(x.handle), x.type) + elif dtype.is_int_signed(): + return core.tensor(_semantic.builder.create_iabs(x.handle), x.type) + elif dtype.is_int_unsigned(): + return x # no-op + else: + assert False, f"Unexpected dtype {dtype}" + + +@core.builtin +@_add_math_2arg_docstr("fast division") +def fdiv(x, y, ieee_rounding=False, _semantic=None): + ieee_rounding = core._unwrap_if_constexpr(ieee_rounding) + x = _semantic.to_tensor(x) + y = _semantic.to_tensor(y) + return _semantic.fdiv(x, y, ieee_rounding) + + +@core.builtin +@_check_dtype(dtypes=["fp32"]) +@_add_math_2arg_docstr("precise division (rounding to nearest wrt the IEEE standard)") +def div_rn(x, y, _semantic=None): + x = _semantic.to_tensor(x) + y = _semantic.to_tensor(y) + x, y = core.binary_op_type_legalization(x, y, _semantic) + return core.tensor(_semantic.builder.create_precise_divf(x.handle, y.handle), x.type) + + +@core.builtin +@_check_dtype(dtypes=["fp32", "fp64"]) +@_add_math_1arg_docstr("error function") +@core._tensor_member_fn +def erf(x, _semantic=None): + x = _semantic.to_tensor(x) + return core.tensor(_semantic.builder.create_erf(x.handle), x.type) + + +@core.builtin +@_check_dtype(dtypes=["fp32", "fp64"]) +@_add_math_1arg_docstr("floor") +@core._tensor_member_fn +def floor(x, _semantic=None): + x = _semantic.to_tensor(x) + return core.tensor(_semantic.builder.create_floor(x.handle), x.type) + + +@core.builtin +@_check_dtype(dtypes=["fp32", "fp64"]) +@_add_math_1arg_docstr("ceil") +@core._tensor_member_fn +def ceil(x, _semantic=None): + x = _semantic.to_tensor(x) + return core.tensor(_semantic.builder.create_ceil(x.handle), x.type) + + +@core.builtin +@_add_math_3arg_docstr("fused multiply-add") +def fma(x, y, z, _semantic=None): + x = _semantic.to_tensor(x) + y = _semantic.to_tensor(y) + z = _semantic.to_tensor(z) + x, y = core.binary_op_type_legalization(x, y, _semantic) + z, x = core.binary_op_type_legalization(z, x, _semantic) + z, y = core.binary_op_type_legalization(z, y, _semantic) + return core.tensor(_semantic.builder.create_fma(x.handle, y.handle, z.handle), x.type) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/language/random.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/language/random.py new file mode 100644 index 0000000000000000000000000000000000000000..b4790def8767599c9786ce3d03c4f28d8aea2683 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/language/random.py @@ -0,0 +1,218 @@ +from ..runtime.jit import jit +from . import core as tl +from . import math + +N_ROUNDS_DEFAULT = tl.constexpr(10) # Default number of rounds for philox + +# ------------------- +# randint +# ------------------- + + +@jit +def philox_impl(c0, c1, c2, c3, k0, k1, n_rounds: tl.constexpr = N_ROUNDS_DEFAULT): + """ + Run `n_rounds` rounds of Philox for state (c0, c1, c2, c3) and key (k0, k1). + """ + if c0.dtype == tl.uint32: + PHILOX_KEY_A: tl.constexpr = 0x9E3779B9 + PHILOX_KEY_B: tl.constexpr = 0xBB67AE85 + PHILOX_ROUND_A: tl.constexpr = 0xD2511F53 + PHILOX_ROUND_B: tl.constexpr = 0xCD9E8D57 + else: + tl.static_assert(c0.dtype == tl.uint64, "dtype not supported in philox_impl") + PHILOX_KEY_A: tl.constexpr = 0x9E3779B97F4A7C15 + PHILOX_KEY_B: tl.constexpr = 0xBB67AE8584CAA73B + PHILOX_ROUND_A: tl.constexpr = 0xD2E7470EE14C6C93 + PHILOX_ROUND_B: tl.constexpr = 0xCA5A826395121157 + + for _ in tl.static_range(n_rounds): + # for _ in range(n_rounds): + # update random state + A = PHILOX_ROUND_A + B = PHILOX_ROUND_B + _c0, _c2 = c0, c2 + c0 = math.umulhi(B, _c2) ^ c1 ^ k0 + c2 = math.umulhi(A, _c0) ^ c3 ^ k1 + c1 = tl.mul(B, _c2, sanitize_overflow=False) + c3 = tl.mul(A, _c0, sanitize_overflow=False) + # raise key + k0 = tl.add(k0, PHILOX_KEY_A, sanitize_overflow=False) + k1 = tl.add(k1, PHILOX_KEY_B, sanitize_overflow=False) + return c0, c1, c2, c3 + + +@jit +def philox(seed, c0, c1, c2, c3, n_rounds: tl.constexpr = N_ROUNDS_DEFAULT): + seed = tl.to_tensor(seed) + tl.static_assert(seed.dtype.is_int()) + seed = seed.to(tl.uint64) + c0 = tl.to_tensor(c0) + c1 = tl.to_tensor(c1) + c2 = tl.to_tensor(c2) + c3 = tl.to_tensor(c3) + + if tl.constexpr(c0.dtype.primitive_bitwidth) == 32: + int_dtype = tl.uint32 + seed_hi = ((seed >> 32) & 0xffffffff).to(tl.uint32) + seed_lo = (seed & 0xffffffff).to(tl.uint32) + else: + tl.static_assert(tl.constexpr(c0.dtype.primitive_bitwidth) == 64, "bitwidth not supported in philox") + int_dtype = tl.uint64 + seed_hi = tl.full((1, ), 0, dtype=int_dtype) + seed_lo = seed + + c0 = c0.to(int_dtype, bitcast=True) + c1 = c1.to(int_dtype, bitcast=True) + c2 = c2.to(int_dtype, bitcast=True) + c3 = c3.to(int_dtype, bitcast=True) + return philox_impl(c0, c1, c2, c3, seed_lo, seed_hi, n_rounds) + + +@jit +def randint(seed, offset, n_rounds: tl.constexpr = N_ROUNDS_DEFAULT): + """ + Given a :code:`seed` scalar and an :code:`offset` block, returns a single + block of random :code:`int32`. + + If you need multiple streams of random numbers, + using `randint4x` is likely to be faster than calling `randint` 4 times. + + :param seed: The seed for generating random numbers. + :param offset: The offsets to generate random numbers for. + """ + ret, _, _, _ = randint4x(seed, offset, n_rounds) + return ret + + +@jit +def randint4x(seed, offset, n_rounds: tl.constexpr = N_ROUNDS_DEFAULT): + """ + Given a :code:`seed` scalar and an :code:`offset` block, returns four + blocks of random :code:`int32`. + + This is the maximally efficient entry point + to Triton's Philox pseudo-random number generator. + + :param seed: The seed for generating random numbers. + :param offsets: The offsets to generate random numbers for. + """ + # _0 = tl.zeros(offset.shape, offset.dtype) + + offset_lo = offset.to(tl.uint32) + _0 = offset_lo * 0 + + if tl.constexpr(offset.dtype.primitive_bitwidth) > 32: + offset_hi = (offset >> 32).to(tl.uint32) + else: + offset_hi = _0 + + return philox(seed, offset_lo, offset_hi, _0, _0, n_rounds) + + +# ------------------- +# rand +# ------------------- + +# @jit +# def uint32_to_uniform_float(x): +# """ +# Numerically stable function to convert a random uint32 into a random float uniformly sampled in [0, 1). +# """ +# two_to_the_minus_32: tl.constexpr = 2.328306e-10 +# return x * two_to_the_minus_32 + + +@jit +def uint_to_uniform_float(x): + """ + Numerically stable function to convert a random uint into a random float uniformly sampled in [0, 1). + """ + # TODO: fix frontend issues and cleanup + # conditions can be simplified + # scale is ((2**23 - 1) / 2**23) * 2**(N_BITS - 1) + if tl.constexpr(x.dtype == tl.uint32) or tl.constexpr(x.dtype == tl.int32): + # maximum value such that `MAX_INT * scale < 1.0` (with float rounding) + x = x.to(tl.int32, bitcast=True) + scale = 4.6566127342e-10 + else: + tl.static_assert(tl.constexpr(x.dtype == tl.uint64) or tl.constexpr(x.dtype == tl.int64)) + x = x.to(tl.int64, bitcast=True) + scale = 1.0842020432385337e-19 + x = tl.where(x < 0, -x - 1, x) + return x * scale + + +@jit +def rand(seed, offset, n_rounds: tl.constexpr = N_ROUNDS_DEFAULT): + """ + Given a :code:`seed` scalar and an :code:`offset` block, + returns a block of random :code:`float32` in :math:`U(0, 1)`. + + :param seed: The seed for generating random numbers. + :param offsets: The offsets to generate random numbers for. + """ + source = randint(seed, offset, n_rounds) + return uint_to_uniform_float(source) + + +@jit +def rand4x(seed, offsets, n_rounds: tl.constexpr = N_ROUNDS_DEFAULT): + """ + Given a :code:`seed` scalar and an :code:`offsets` block, + returns 4 blocks of random :code:`float32` in :math:`U(0, 1)`. + + :param seed: The seed for generating random numbers. + :param offsets: The offsets to generate random numbers for. + """ + i1, i2, i3, i4 = randint4x(seed, offsets, n_rounds) + u1 = uint_to_uniform_float(i1) + u2 = uint_to_uniform_float(i2) + u3 = uint_to_uniform_float(i3) + u4 = uint_to_uniform_float(i4) + return u1, u2, u3, u4 + + +# ------------------- +# randn +# ------------------- + + +@jit +def pair_uniform_to_normal(u1, u2): + """Box-Muller transform""" + u1 = tl.maximum(1.0e-7, u1) + th = 6.283185307179586 * u2 + r = math.sqrt(-2.0 * math.log(u1)) + return r * math.cos(th), r * math.sin(th) + + +@jit +def randn(seed, offset, n_rounds: tl.constexpr = N_ROUNDS_DEFAULT): + """ + Given a :code:`seed` scalar and an :code:`offset` block, + returns a block of random :code:`float32` in :math:`\\mathcal{N}(0, 1)`. + + :param seed: The seed for generating random numbers. + :param offsets: The offsets to generate random numbers for. + """ + i1, i2, _, _ = randint4x(seed, offset, n_rounds) + u1 = uint_to_uniform_float(i1) + u2 = uint_to_uniform_float(i2) + n1, _ = pair_uniform_to_normal(u1, u2) + return n1 + + +@jit +def randn4x(seed, offset, n_rounds: tl.constexpr = N_ROUNDS_DEFAULT): + """ + Given a :code:`seed` scalar and an :code:`offset` block, + returns 4 blocks of random :code:`float32` in :math:`\\mathcal{N}(0, 1)`. + + :param seed: The seed for generating random numbers. + :param offsets: The offsets to generate random numbers for. + """ + u1, u2, u3, u4 = rand4x(seed, offset, n_rounds) + n1, n2 = pair_uniform_to_normal(u1, u2) + n3, n4 = pair_uniform_to_normal(u3, u4) + return n1, n2, n3, n4 diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/language/semantic.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/language/semantic.py new file mode 100644 index 0000000000000000000000000000000000000000..42bf7024f41090e0680f9f262c15074c956c250d --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/language/semantic.py @@ -0,0 +1,1966 @@ +from __future__ import annotations # remove after python 3.11 +import warnings + +from typing import List, Optional, Sequence, Tuple, TypeVar, Generic, Type +import numbers + +from triton.runtime import driver + +from .._C.libtriton import ir +from . import core as tl + +T = TypeVar('T') +TensorTy = TypeVar('TensorTy') + + +class IncompatibleTypeErrorImpl(Exception): + + def __init__(self, type_a, type_b): + self.type_a = type_a + self.type_b = type_b + self.message = "invalid operands of type " + self.type_a.__repr__() + " and " + self.type_b.__repr__() + super(IncompatibleTypeErrorImpl, self).__init__(self.message) + + +class TritonSemantic(Generic[TensorTy]): + tensor: Type[TensorTy] = tl.tensor + lang = tl + + builder: ir.builder + + def __init__(self, builder): + self.builder = builder + +# ===----------------------------------------------------------------------===## +# Programming Model +# ===----------------------------------------------------------------------===## + + def program_id(self, axis: int) -> TensorTy: + if axis not in (0, 1, 2): + raise ValueError(f"program_id axis must be 0, 1, or 2 but got {axis}") + return self.tensor(self.builder.create_get_program_id(axis), tl.int32) + + def num_programs(self, axis: int) -> TensorTy: + if axis not in (0, 1, 2): + raise ValueError(f"num_programs axis must be 0, 1, or 2 but got {axis}") + return self.tensor(self.builder.create_get_num_programs(axis), tl.int32) + +# ===----------------------------------------------------------------------===// +# Implicit Casting Utilities +# ===----------------------------------------------------------------------===// + + def integer_promote_impl(self, a_ty: tl.dtype, b_ty: tl.dtype) -> tl.dtype: + a_rank = a_ty.int_bitwidth + b_rank = b_ty.int_bitwidth + a_sn = a_ty.int_signedness + b_sn = b_ty.int_signedness + # Rules for signedness taken from "Usual arithmetic conversions" on + # https://en.cppreference.com/w/c/language/conversion. + if a_sn == b_sn: + return a_ty if a_rank > b_rank else b_ty + elif a_sn == tl.dtype.SIGNEDNESS.UNSIGNED: + return a_ty if a_rank >= b_rank else b_ty + elif b_sn == tl.dtype.SIGNEDNESS.UNSIGNED: + return b_ty if b_rank >= a_rank else a_ty + raise TypeError(f"unexpected signedness {a_sn} and {b_sn}") + + def computation_type_impl(self, a_ty: tl.dtype, a_is_scalar: bool, b_ty: tl.dtype, b_is_scalar: bool, + div_or_mod: bool) -> tl.dtype: + # 0) For scalars we follow semantics similar to PyTorch, namely: + # - If the scalar is of a lower or equal kind (bool < uint < int < fp), + # it doesn't participate in the promotion + if a_is_scalar != b_is_scalar: + scalar_ty, tensor_ty = (a_ty, b_ty) if a_is_scalar else (b_ty, a_ty) + if scalar_ty.kind().value <= tensor_ty.kind().value: + # Upcast because of 3) and 4) below! + if div_or_mod and (tensor_ty in (tl.float16, tl.bfloat16)): + return tl.float32 + return tensor_ty + + # 1) if one operand is double, the other is implicitly + # converted to double + if a_ty.is_fp64() or b_ty.is_fp64(): + return tl.float64 + # 2) if one operand is float, the other is implicitly + # converted to float + if a_ty.is_fp32() or b_ty.is_fp32(): + return tl.float32 + # 3 ) if one operand is half, the other is implicitly converted to half + # unless we're doing / or %, which do not exist natively in PTX for fp16. + # Supported PTX op: add, sub, mul, fma, neg, abs, min, max, tanh, ex2, setp + if a_ty.is_fp16() or b_ty.is_fp16(): + if div_or_mod: + return tl.float32 + else: + return tl.float16 + # 4) return bf16 only if both operands are of bf16 + if a_ty.is_bf16() and b_ty.is_bf16(): + if div_or_mod: + return tl.float32 + else: + return tl.bfloat16 + if a_ty.is_bf16() or b_ty.is_bf16(): + return tl.float32 + # 5) return fp16 if operands are different fp8 + if a_ty.is_fp8() and b_ty.is_fp8(): + return a_ty if a_ty == b_ty else tl.float16 + if not a_ty.is_int() or not b_ty.is_int(): + raise TypeError(f"unexpected type {a_ty} and {b_ty}") + # 6 ) both operands are integer and undergo + # integer promotion + if div_or_mod and a_ty.int_signedness != b_ty.int_signedness: + raise TypeError("Cannot use /, #, or % with " + a_ty.__repr__() + " and " + b_ty.__repr__() + + " because they have different signedness;" + "this is unlikely to result in a useful answer. Cast them to the same signedness.") + return self.integer_promote_impl(a_ty, b_ty) + + def to_tensor(self, x, check_type: bool = True): + if isinstance(x, bool): + return self.tensor(self.builder.get_int1(x), tl.int1) + # Note: compile-time const integers are represented by unsigned values + elif isinstance(x, int): + if -2**31 <= x < 2**31: + dtype = tl.int32 + elif 2**31 <= x < 2**32: + dtype = tl.uint32 + elif -2**63 <= x < 2**63: + dtype = tl.int64 + elif 2**63 <= x < 2**64: + dtype = tl.uint64 + else: + raise ValueError(f'Nonrepresentable integer {x}.') + return self.scalar_constant(x, dtype=dtype) + elif isinstance(x, float): + min_float32 = 2**-126 + max_float32 = (2 - 2**-23) * 2**127 + abs_x = __builtins__['abs'](x) + if abs_x == float("inf") or\ + abs_x == 0.0 or \ + x != x or \ + min_float32 <= abs_x <= max_float32: + dtype = tl.float32 + else: + dtype = tl.float64 + return self.scalar_constant(x, dtype=dtype) + + elif isinstance(x, tl.constexpr): + return self.to_tensor(x.value) + elif isinstance(x, self.tensor): + return x + if check_type: + raise TypeError(f"cannot convert {x} of type {type(x)} to tensor") + return x + +# ===----------------------------------------------------------------------===// +# Binary Operators +# ===----------------------------------------------------------------------===// + + def check_ptr_type_impl(self, type_a: tl.dtype, type_b: tl.dtype, allow_ptr_a: bool) -> None: + if type_a.is_ptr(): + if not allow_ptr_a: + raise IncompatibleTypeErrorImpl(type_a, type_b) + # T* + U* with T != U + if type_b.is_ptr() and (type_a != type_b): + raise IncompatibleTypeErrorImpl(type_a, type_b) + # T* + float + if type_b.is_floating(): + raise IncompatibleTypeErrorImpl(type_a, type_b) + + def binary_op_type_checking_impl(self, lhs: TensorTy | numbers.Number, rhs: TensorTy | numbers.Number, + allow_lhs_ptr=False, allow_rhs_ptr=False, arithmetic_check=True, + div_or_mod=False) -> Tuple[TensorTy, TensorTy]: + lhs_is_scalar = isinstance(lhs, numbers.Number) + rhs_is_scalar = isinstance(rhs, numbers.Number) + if lhs_is_scalar: + lhs_scalar = lhs + lhs = self.to_tensor(lhs) + if rhs_is_scalar: + rhs_scalar = rhs + rhs = self.to_tensor(rhs) + + # implicit typecasting + lhs_sca_ty = lhs.type.scalar + rhs_sca_ty = rhs.type.scalar + self.check_ptr_type_impl(lhs_sca_ty, rhs_sca_ty, allow_lhs_ptr) + self.check_ptr_type_impl(rhs_sca_ty, lhs_sca_ty, allow_rhs_ptr) + if arithmetic_check and not lhs_sca_ty.is_ptr() and not rhs_sca_ty.is_ptr(): + ret_sca_ty = self.computation_type_impl(lhs_sca_ty, lhs_is_scalar, rhs_sca_ty, rhs_is_scalar, div_or_mod) + if (lhs_is_scalar and lhs_scalar < 0 and ret_sca_ty.is_int_unsigned() + or rhs_is_scalar and rhs_scalar < 0 and ret_sca_ty.is_int_unsigned()): + raise ValueError("Cannot perform a binary operation between an unsigned tensor and a negative scalar. " + "Perform a explicit cast on one of them.") + if ret_sca_ty.is_int(): + if lhs_is_scalar and not (ret_sca_ty.get_int_min_value() <= lhs_scalar <= + ret_sca_ty.get_int_max_value()): + raise ValueError(f"Scalar {lhs_scalar} is out of range for type {ret_sca_ty}") + if rhs_is_scalar and not (ret_sca_ty.get_int_min_value() <= rhs_scalar <= + ret_sca_ty.get_int_max_value()): + raise ValueError(f"Scalar {rhs_scalar} is out of range for type {ret_sca_ty}") + lhs = self.scalar_constant(lhs_scalar, dtype=ret_sca_ty) if lhs_is_scalar else self.cast(lhs, ret_sca_ty) + rhs = self.scalar_constant(rhs_scalar, dtype=ret_sca_ty) if rhs_is_scalar else self.cast(rhs, ret_sca_ty) + + # implicit broadcasting + lhs, rhs = self.broadcast_impl_value(lhs, rhs) + return lhs, rhs + + def binary_op_sanitize_overflow_impl(self, lhs: TensorTy, rhs: TensorTy, binary_op: callable): + if lhs.type.scalar.int_bitwidth >= 64 or not self.builder.options.sanitize_overflow: + return + lhs_sca_ty = lhs.type.scalar + rhs_sca_ty = rhs.type.scalar + assert lhs_sca_ty == rhs_sca_ty + assert lhs_sca_ty.is_int() + lhs = self.cast(lhs, tl.int64) + rhs = self.cast(rhs, tl.int64) + ret = binary_op(lhs, rhs, False) + max_value = lhs_sca_ty.get_int_max_value() + max_value = self.scalar_constant(max_value, tl.int64) + min_value = lhs_sca_ty.get_int_min_value() + min_value = self.scalar_constant(min_value, tl.int64) + cond = self.and_(self.less_equal(ret, max_value), self.greater_equal(ret, min_value)) + msg = f"int{lhs_sca_ty.int_bitwidth} overflow detected for operation {binary_op.__name__}" + self.device_assert(cond, msg, None) + + def add(self, input: TensorTy | numbers.Number, other: TensorTy | numbers.Number, + sanitize_overflow: bool) -> TensorTy: + input, other = self.binary_op_type_checking_impl(input, other, True, True) + input_scalar_ty = input.type.scalar + other_scalar_ty = other.type.scalar + if input_scalar_ty.is_ptr() and other_scalar_ty.is_ptr(): + raise TypeError("cannot add pointers together") + + # offset + ptr + # ptr + offset + if other_scalar_ty.is_ptr() and not input_scalar_ty.is_ptr(): + input, other = other, input + input_scalar_ty = input.type.scalar + other_scalar_ty = other.type.scalar + if input_scalar_ty.is_ptr(): + other_handle = other.handle + if other.dtype.is_int_unsigned() and other.dtype.int_bitwidth < 64: + # addptr treats offset as signed. Zero-extend unsigned offsets to ensure they're positive + i64_ty = other.type.with_element_ty(tl.int64).to_ir(self.builder) + other_handle = self.builder.create_int_cast(other.handle, i64_ty, False) + return self.tensor(self.builder.create_addptr(input.handle, other_handle), input.type) + # float + float + elif input_scalar_ty.is_floating(): + return self.tensor(self.builder.create_fadd(input.handle, other.handle), input.type) + # int + int + elif input_scalar_ty.is_int(): + if sanitize_overflow: + self.binary_op_sanitize_overflow_impl(input, other, self.add) + return self.tensor(self.builder.create_add(input.handle, other.handle), input.type) + raise TypeError(f"unexpected type {input_scalar_ty}") + + def sub(self, input: TensorTy | numbers.Number, other: TensorTy | numbers.Number, + sanitize_overflow: bool) -> TensorTy: + input, other = self.binary_op_type_checking_impl(input, other, True, False) + scalar_ty = input.type.scalar + # ptr - offset + if scalar_ty.is_ptr(): + return self.add(input, self.minus(other), sanitize_overflow=False) + # float - float + if scalar_ty.is_floating(): + return self.tensor(self.builder.create_fsub(input.handle, other.handle), input.type) + # int - int + elif scalar_ty.is_int(): + if sanitize_overflow: + self.binary_op_sanitize_overflow_impl(input, other, self.sub) + return self.tensor(self.builder.create_sub(input.handle, other.handle), input.type) + raise TypeError(f"unexpected type {scalar_ty}") + + def mul(self, input: TensorTy | numbers.Number, other: TensorTy | numbers.Number, + sanitize_overflow: bool) -> TensorTy: + input, other = self.binary_op_type_checking_impl(input, other) + scalar_ty = input.type.scalar + # float * float + if scalar_ty.is_floating(): + return self.tensor(self.builder.create_fmul(input.handle, other.handle), input.type) + # int * int + elif scalar_ty.is_int(): + if sanitize_overflow: + self.binary_op_sanitize_overflow_impl(input, other, self.mul) + return self.tensor(self.builder.create_mul(input.handle, other.handle), input.type) + raise TypeError(f"unexpected type {scalar_ty}") + + def truediv(self, input: TensorTy | numbers.Number, other: TensorTy | numbers.Number) -> TensorTy: + input, other = self.binary_op_type_checking_impl(input, other, False, False, True, True) + input_scalar_ty = input.type.scalar + other_scalar_ty = other.type.scalar + # float / int + if input_scalar_ty.is_floating() and other_scalar_ty.is_int(): + other = self.cast(other, input_scalar_ty) + # int / float + elif input_scalar_ty.is_int() and other_scalar_ty.is_floating(): + input = self.cast(input, other_scalar_ty) + # int / int (cast to tl.float32) + elif input_scalar_ty.is_int() and other_scalar_ty.is_int(): + input = self.cast(input, tl.float32) + other = self.cast(other, tl.float32) + # float / float (cast to the highest exponent type) + elif input_scalar_ty.is_floating() and other_scalar_ty.is_floating(): + if input_scalar_ty.fp_mantissa_width > other_scalar_ty.fp_mantissa_width: + other = self.cast(other, input_scalar_ty) + else: + input = self.cast(input, other_scalar_ty) + # unreachable + else: + raise TypeError(f"unexpected type {input_scalar_ty}") + return self.tensor(self.builder.create_fdiv(input.handle, other.handle), input.type) + + def floordiv(self, input: TensorTy | numbers.Number, other: TensorTy | numbers.Number) -> TensorTy: + input, other = self.binary_op_type_checking_impl(input, other, False, False, True, True) + input_scalar_ty = input.type.scalar + other_scalar_ty = other.type.scalar + if input_scalar_ty.is_int() and other_scalar_ty.is_int(): + ret_ty = self.integer_promote_impl(input_scalar_ty, other_scalar_ty) + input = self.cast(input, ret_ty) + other = self.cast(other, ret_ty) + if ret_ty.is_int_signed(): + return self.tensor(self.builder.create_sdiv(input.handle, other.handle), input.type) + else: + return self.tensor(self.builder.create_udiv(input.handle, other.handle), input.type) + raise TypeError(f"unexpected type {input_scalar_ty}") + + def fdiv(self, input: TensorTy | numbers.Number, other: TensorTy | numbers.Number, ieee_rounding: bool) -> TensorTy: + input_scalar_ty = input.type.scalar + other_scalar_ty = other.type.scalar + if not input_scalar_ty.is_floating() or not other_scalar_ty.is_floating(): + raise TypeError("both operands of fdiv must have floating scalar type") + input, other = self.binary_op_type_checking_impl(input, other, False, False, False, True) + ret = self.builder.create_fdiv(input.handle, other.handle) + return self.tensor(ret, input.type) + + def mod(self, input: TensorTy | numbers.Number, other: TensorTy | numbers.Number) -> TensorTy: + input, other = self.binary_op_type_checking_impl(input, other, False, False, True, True) + scalar_ty = input.type.scalar + other_scalar_ty = other.type.scalar + # float % float + if scalar_ty.is_floating(): + return self.tensor(self.builder.create_frem(input.handle, other.handle), input.type) + # % int + elif scalar_ty.is_int(): + if scalar_ty.int_signedness != other_scalar_ty.int_signedness: + raise TypeError("Cannot mod " + scalar_ty.__repr__() + " by " + other_scalar_ty.__repr__() + " " + "because they have different signedness;" + "this is unlikely to result in a useful answer. Cast them to the same signedness.") + if scalar_ty.is_int_signed(): + return self.tensor(self.builder.create_srem(input.handle, other.handle), input.type) + else: + return self.tensor(self.builder.create_urem(input.handle, other.handle), input.type) + raise TypeError(f"unexpected type {scalar_ty}") + +############## +# other arithmetic ops +############## + + def minimum(self, x: TensorTy, y: TensorTy, propagate_nan: tl.PropagateNan): + x, y = self.binary_op_type_checking_impl(x, y) + dtype = x.dtype + if dtype.is_floating(): + if propagate_nan == tl.PropagateNan.ALL: + return self.tensor(self.builder.create_minimumf(x.handle, y.handle), x.type) + elif propagate_nan == tl.PropagateNan.NONE: + return self.tensor(self.builder.create_minnumf(x.handle, y.handle), x.type) + else: + raise ValueError(f"Unexpected propagate_nan {propagate_nan}") + elif dtype.is_int_signed(): + return self.tensor(self.builder.create_minsi(x.handle, y.handle), x.type) + elif dtype.is_int_unsigned(): + return self.tensor(self.builder.create_minui(x.handle, y.handle), x.type) + else: + raise TypeError(f"Unexpected dtype {dtype}") + + def maximum(self, x: TensorTy, y: TensorTy, propagate_nan: tl.PropagateNan): + x, y = self.binary_op_type_checking_impl(x, y) + dtype = x.dtype + if dtype.is_floating(): + if propagate_nan == tl.PropagateNan.ALL: + return self.tensor(self.builder.create_maximumf(x.handle, y.handle), x.type) + elif propagate_nan == tl.PropagateNan.NONE: + return self.tensor(self.builder.create_maxnumf(x.handle, y.handle), x.type) + else: + raise ValueError(f"Unexpected propagate_nan {propagate_nan}") + elif dtype.is_int_signed(): + return self.tensor(self.builder.create_maxsi(x.handle, y.handle), x.type) + elif dtype.is_int_unsigned(): + return self.tensor(self.builder.create_maxui(x.handle, y.handle), x.type) + else: + raise TypeError(f"Unexpected dtype {dtype}") + + def clamp(self, x: TensorTy, min: TensorTy, max: TensorTy, propagate_nan: tl.PropagateNan): + min, max = self.binary_op_type_checking_impl(min, max) + x, min = self.binary_op_type_checking_impl(x, min) + x, max = self.binary_op_type_checking_impl(x, max) + + dtype = x.dtype + if dtype.is_floating(): + return self.tensor(self.builder.create_clampf(x.handle, min.handle, max.handle, propagate_nan), x.type) + else: + raise TypeError(f"Unexpected dtype {dtype}. Only floating point clamp is supported") + +############## +# bitwise ops +############## + + def bitwise_op_type_checking_impl(self, input: TensorTy, other: TensorTy) -> Tuple[TensorTy, TensorTy]: + input, other = self.binary_op_type_checking_impl(input, other) + input_sca_ty = input.type.scalar + other_sca_ty = other.type.scalar + if not input_sca_ty.is_int() or not other_sca_ty.is_int(): + raise IncompatibleTypeErrorImpl(input_sca_ty, other_sca_ty) + ret_sca_ty = self.integer_promote_impl(input_sca_ty, other_sca_ty) + if ret_sca_ty != input_sca_ty: + input = self.cast(input, ret_sca_ty) + if ret_sca_ty != other_sca_ty: + other = self.cast(other, ret_sca_ty) + return input, other + + def and_(self, input: TensorTy, other: TensorTy) -> TensorTy: + input, other = self.bitwise_op_type_checking_impl(input, other) + return self.tensor(self.builder.create_and(input.handle, other.handle), input.type) + + def or_(self, input: TensorTy, other: TensorTy) -> TensorTy: + input, other = self.bitwise_op_type_checking_impl(input, other) + return self.tensor(self.builder.create_or(input.handle, other.handle), input.type) + + def xor_(self, input: TensorTy, other: TensorTy) -> TensorTy: + input, other = self.bitwise_op_type_checking_impl(input, other) + return self.tensor(self.builder.create_xor(input.handle, other.handle), input.type) + + def logical_and(self, input: TensorTy, other: TensorTy) -> TensorTy: + if not input.type.is_int1(): + input = self.bitcast(input, tl.int1) + if not other.type.is_int1(): + other = self.bitcast(other, tl.int1) + return self.and_(input, other) + + def logical_or(self, input: TensorTy, other: TensorTy) -> TensorTy: + if not input.type.is_int1(): + input = self.bitcast(input, tl.int1) + if not other.type.is_int1(): + other = self.bitcast(other, tl.int1) + return self.or_(input, other) + + def not_(self, input: TensorTy): + if not input.type.is_int1(): + input = self.bitcast(input, tl.int1) + return self.invert(input) + + def lshr(self, input: TensorTy, other: TensorTy) -> TensorTy: + input, other = self.bitwise_op_type_checking_impl(input, other) + return self.tensor(self.builder.create_lshr(input.handle, other.handle), input.type) + + def ashr(self, input: TensorTy, other: TensorTy) -> TensorTy: + input, other = self.bitwise_op_type_checking_impl(input, other) + return self.tensor(self.builder.create_ashr(input.handle, other.handle), input.type) + + def shl(self, input: TensorTy, other: TensorTy) -> TensorTy: + input, other = self.bitwise_op_type_checking_impl(input, other) + return self.tensor(self.builder.create_shl(input.handle, other.handle), input.type) + +# ===----------------------------------------------------------------------===// +# Unary Operators +# ===----------------------------------------------------------------------===// + + def plus(self, input: TensorTy) -> TensorTy: + return input + + def minus(self, input: TensorTy) -> TensorTy: + input_sca_ty = input.type.scalar + if input_sca_ty.is_ptr(): + raise ValueError("wrong type argument to unary minus (" + input_sca_ty.__repr__() + ")") + _0 = self.tensor(self.builder.get_null_value(input_sca_ty.to_ir(self.builder)), input_sca_ty) + return self.sub(_0, input, True) + + def invert(self, input: TensorTy) -> TensorTy: + input_sca_ty = input.type.scalar + if input_sca_ty.is_ptr() or input_sca_ty.is_floating(): + raise ValueError("wrong type argument to unary invert (" + input_sca_ty.__repr__() + ")") + _1 = self.tensor(self.builder.get_all_ones_value(input_sca_ty.to_ir(self.builder)), input_sca_ty) + return self.xor_(input, _1) + +# ===----------------------------------------------------------------------===// +# Comparison Operators +# ===----------------------------------------------------------------------===// + + def _bool_like(self, v: TensorTy) -> tl.block_type: + return v.type.with_element_ty(tl.int1) + + def greater_than(self, input: TensorTy, other: TensorTy) -> TensorTy: + input, other = self.binary_op_type_checking_impl(input, other) + scalar_ty = input.type.scalar + # float > float + if scalar_ty.is_floating(): + return self.tensor(self.builder.create_fcmpOGT(input.handle, other.handle), self._bool_like(input)) + # > int + elif scalar_ty.is_int(): + if scalar_ty.is_int_signed(): + return self.tensor(self.builder.create_icmpSGT(input.handle, other.handle), self._bool_like(input)) + else: + return self.tensor(self.builder.create_icmpUGT(input.handle, other.handle), self._bool_like(input)) + raise TypeError(f"unexpected type {scalar_ty}") + + def greater_equal(self, input: TensorTy, other: TensorTy) -> TensorTy: + input, other = self.binary_op_type_checking_impl(input, other) + scalar_ty = input.type.scalar + # float >= float + if scalar_ty.is_floating(): + return self.tensor(self.builder.create_fcmpOGE(input.handle, other.handle), self._bool_like(input)) + # >= int + elif scalar_ty.is_int(): + if scalar_ty.is_int_signed(): + return self.tensor(self.builder.create_icmpSGE(input.handle, other.handle), self._bool_like(input)) + else: + return self.tensor(self.builder.create_icmpUGE(input.handle, other.handle), self._bool_like(input)) + raise TypeError(f"unexpected type {scalar_ty}") + + def less_than(self, input: TensorTy, other: TensorTy) -> TensorTy: + input, other = self.binary_op_type_checking_impl(input, other) + scalar_ty = input.type.scalar + # float < float + if scalar_ty.is_floating(): + return self.tensor(self.builder.create_fcmpOLT(input.handle, other.handle), self._bool_like(input)) + # < int + elif scalar_ty.is_int(): + if scalar_ty.is_int_signed(): + return self.tensor(self.builder.create_icmpSLT(input.handle, other.handle), self._bool_like(input)) + else: + return self.tensor(self.builder.create_icmpULT(input.handle, other.handle), self._bool_like(input)) + raise TypeError(f"unexpected type {scalar_ty}") + + def less_equal(self, input: TensorTy, other: TensorTy) -> TensorTy: + input, other = self.binary_op_type_checking_impl(input, other) + scalar_ty = input.type.scalar + # float < float + if scalar_ty.is_floating(): + return self.tensor(self.builder.create_fcmpOLE(input.handle, other.handle), self._bool_like(input)) + # < int + elif scalar_ty.is_int(): + if scalar_ty.is_int_signed(): + return self.tensor(self.builder.create_icmpSLE(input.handle, other.handle), self._bool_like(input)) + else: + return self.tensor(self.builder.create_icmpULE(input.handle, other.handle), self._bool_like(input)) + raise TypeError(f"unexpected type {scalar_ty}") + + def equal(self, input: TensorTy, other: TensorTy) -> TensorTy: + input, other = self.binary_op_type_checking_impl(input, other) + scalar_ty = input.type.scalar + # float == float + if scalar_ty.is_floating(): + return self.tensor(self.builder.create_fcmpOEQ(input.handle, other.handle), self._bool_like(input)) + # == int + elif scalar_ty.is_int(): + return self.tensor(self.builder.create_icmpEQ(input.handle, other.handle), self._bool_like(input)) + raise TypeError(f"unexpected type {scalar_ty}") + + def not_equal(self, input: TensorTy, other: TensorTy) -> TensorTy: + input, other = self.binary_op_type_checking_impl(input, other) + scalar_ty = input.type.scalar + # float == float + if scalar_ty.is_floating(): + return self.tensor(self.builder.create_fcmpUNE(input.handle, other.handle), self._bool_like(input)) + # == int + elif scalar_ty.is_int(): + return self.tensor(self.builder.create_icmpNE(input.handle, other.handle), self._bool_like(input)) + raise TypeError(f"unexpected type {scalar_ty}") + +# ===----------------------------------------------------------------------===// +# Block Creation +# ===----------------------------------------------------------------------===// + + def arange(self, start: int, end: int, *, ret_ty: tl.block_type = None) -> TensorTy: + if not isinstance(start, int) or not isinstance(end, int): + raise ValueError("arange's arguments must be of type tl.constexpr") + is_start_int64 = bool(start >> 32) + is_end_int64 = bool(end >> 32) + if is_start_int64 or is_end_int64: + raise ValueError("arange must fit in int32") + if end <= start: + raise ValueError("arange's end argument must be greater than the start argument") + range = end - start + if (range & (range - 1)) != 0: + raise ValueError("arange's range must be a power of 2") + shape = [range] + if ret_ty is None: + ret_ty = tl.block_type(tl.int32, shape) + ret_ty_ir = ret_ty.to_ir(self.builder) + return self.tensor(self.builder.create_make_range(ret_ty_ir, start, end), ret_ty) + + def scalar_constant(self, value, dtype: tl.dtype) -> TensorTy: + # scalar + if dtype is None: + raise ValueError("dtype must be specified when value is not a tensor") + if value == 0: + value = self.builder.get_null_value(dtype.to_ir(self.builder)) + else: + get_value_fn = getattr(self.builder, f"get_{dtype.name}") + value = get_value_fn(value) + return self.tensor(value, dtype) + + def make_scalar(self, value, dtype: tl.dtype) -> TensorTy: + if isinstance(value, tl.tensor): + assert value.numel.value == 1, "only accepts size-1 tensor" + return self.cast(value, dtype) + # scalar + return self.scalar_constant(value, dtype) + + def full(self, shape: List[int], value, dtype: tl.dtype) -> TensorTy: + return self.splat(self.make_scalar(value, dtype), shape) + +# ===----------------------------------------------------------------------===// +# Shape Manipulation +# ===----------------------------------------------------------------------===// + + def splat(self, value: TensorTy, shape: List[int]) -> TensorTy: + assert not value.type.is_block(), "Cannot splat a block tensor" + if len(shape) == 0: + return value + ret_ty = tl.block_type(value.dtype, shape) + return self.tensor(self.builder.create_splat(ret_ty.to_ir(self.builder), value.handle), ret_ty) + + def unsplat(self, value: TensorTy) -> TensorTy: + return self.tensor(self.builder.create_unsplat(value.handle), value.dtype) + + def reshape(self, input: TensorTy, dst_shape: List[int], can_reorder: bool) -> TensorTy: + numel = 1 + for s in dst_shape: + numel *= s + if input.type.numel != numel: + raise ValueError("reshape() cannot change total number of elements in tensor") + ret_ty = tl.block_type(input.type.scalar, dst_shape) + return self.tensor(self.builder.create_reshape(input.handle, dst_shape, can_reorder), ret_ty) + + def expand_dims(self, input: TensorTy, axis: int) -> TensorTy: + dst_shape = [tl._unwrap_if_constexpr(x) for x in input.shape] + dst_shape.insert(axis, 1) + + if not input.type.is_block(): + return self.splat(input, shape=dst_shape) + + ret_ty = tl.block_type(input.type.scalar, dst_shape) + return self.tensor(self.builder.create_expand_dims(input.handle, axis), ret_ty) + + def cat(self, lhs: TensorTy, rhs: TensorTy, can_reorder: bool) -> TensorTy: + assert can_reorder, "current implementation of `cat` always may reorder elements" + assert len(lhs.shape) == 1 + ret_type = tl.block_type(lhs.type.scalar, [lhs.shape[0] + rhs.shape[0]]) + return self.tensor(self.builder.create_cat(lhs.handle, rhs.handle), ret_type) + + def join(self, a: TensorTy, b: TensorTy) -> TensorTy: + a, b = self.broadcast_impl_value(a, b) + + # The IR can't handle joining two scalars, so upcast them to 1D tensors, + # then downcast the result. + was_rank_1 = a.shape == [] + if was_rank_1: + a = self.expand_dims(a, 0) + b = self.expand_dims(b, 0) + + if isinstance(a.shape[-1], tl.constexpr): + two = tl.constexpr(2) + else: + two = 2 + new_shape = a.shape + [two] + + ret_type = tl.block_type(a.type.scalar, new_shape) + ret = self.tensor(self.builder.create_join(a.handle, b.handle), ret_type) + + if was_rank_1: + ret = self.reshape(ret, [2], can_reorder=False) + + return ret + + def split(self, a: TensorTy) -> Tuple[TensorTy, TensorTy]: + assert (len(a.shape) > 0) + assert (tl._unwrap_if_constexpr(a.shape[-1]) == 2) + + new_shape = a.shape[:-1] + ret_type = tl.block_type(a.type.scalar, new_shape) + outLHS, outRHS = self.builder.create_split(a.handle) + return ( + self.tensor(outLHS, ret_type), + self.tensor(outRHS, ret_type), + ) + + def permute(self, input: TensorTy, dims: Tuple[int]) -> TensorTy: + if len(input.shape) != len(dims): + raise ValueError("permute dims must have the same length as input shape") + if sorted(tl._unwrap_if_constexpr(d) for d in dims) != list(range(len(dims))): + raise ValueError(f"permute dims must be a permutation of 0, 1, ..., n-1, but were {dims}") + + ret_type = tl.block_type(input.type.scalar, [input.shape[d] for d in dims]) + return self.tensor(self.builder.create_trans(input.handle, dims), ret_type) + + def broadcast_impl_shape(self, input: TensorTy, shape: Tuple[int]) -> TensorTy: + if not input.type.is_block(): + return self.splat(input, shape) + src_shape = input.type.get_block_shapes() + if len(src_shape) != len(shape): + raise ValueError(f"Cannot broadcast, rank mismatch: {src_shape}, {shape}") + if shape == src_shape: + return input + for i, item in enumerate(src_shape): + if shape[i] != item and item != 1: + raise ValueError(f"Cannot broadcast, the expanded size of the tensor ({shape[i]})" + f" must match the existing size ({item}) at non-singleton dimension" + f" {i}: {src_shape}, {shape}") + ret_ty = tl.block_type(input.type.scalar, shape) + return self.tensor(self.builder.create_broadcast(input.handle, shape), ret_ty) + + def broadcast_impl_value(self, lhs: TensorTy, rhs: TensorTy) -> TensorTy: + lhs_ty = lhs.type + rhs_ty = rhs.type + + # make_shape_compatible(block, scalar) + if lhs_ty.is_block() and not rhs_ty.is_block(): + rhs_ty = lhs_ty.with_element_ty(rhs_ty.scalar) + rhs = self.tensor(self.builder.create_splat(rhs_ty.to_ir(self.builder), rhs.handle), rhs_ty) + # make_shape_compatible(scalar, block) + elif not lhs_ty.is_block() and rhs_ty.is_block(): + lhs_ty = rhs_ty.with_element_ty(lhs_ty.scalar) + lhs = self.tensor(self.builder.create_splat(lhs_ty.to_ir(self.builder), lhs.handle), lhs_ty) + # make_shape_compatible(block, block) + elif lhs_ty.is_block() and rhs_ty.is_block(): + lhs_shape = lhs_ty.get_block_shapes() + rhs_shape = rhs_ty.get_block_shapes() + + if len(lhs_shape) < len(rhs_shape): + # Add new axes to lhs + for _ in range(len(lhs_shape), len(rhs_shape)): + lhs = self.tensor(self.builder.create_expand_dims(lhs.handle, 0), + tl.block_type(lhs_ty.scalar, [1] + lhs_shape.values)) + lhs_ty = lhs.type + lhs_shape = lhs_ty.get_block_shapes() + elif len(rhs_shape) < len(lhs_shape): + # Add new axes to rhs + for _ in range(len(rhs_shape), len(lhs_shape)): + rhs = self.tensor(self.builder.create_expand_dims(rhs.handle, 0), + tl.block_type(rhs_ty.scalar, [1] + rhs_shape.values)) + rhs_ty = rhs.type + rhs_shape = rhs_ty.get_block_shapes() + assert len(rhs_shape) == len(lhs_shape) + + ret_shape = [] + for i, left in enumerate(lhs_shape): + right = rhs_shape[i] + if left == 1: + ret_shape.append(right) + elif (right == 1) or (right == left): + ret_shape.append(left) + else: + raise ValueError("Cannot make_shape_compatible: incompatible dimensions " + "at index " + str(i) + ": " + str(left) + " and " + str(right)) + if lhs_shape != ret_shape: + ret_ty = tl.block_type(lhs_ty.scalar, ret_shape) + lhs = self.tensor(self.builder.create_broadcast(lhs.handle, ret_shape), ret_ty) + if rhs_shape != ret_shape: + ret_ty = tl.block_type(rhs_ty.scalar, ret_shape) + rhs = self.tensor(self.builder.create_broadcast(rhs.handle, ret_shape), ret_ty) + # (scalar, scalar) => returns original blocks + return lhs, rhs + +####### +# cast +####### + + def _str_to_rounding_mode(self, rounding_mode: Optional[str]): + if rounding_mode is None: + return None + if rounding_mode == 'rtne': + return ir.ROUNDING_MODE.RTNE + if rounding_mode == 'rtz': + return ir.ROUNDING_MODE.RTZ + raise ValueError(f"Invalid rounding mode: {rounding_mode}. Supported rounding modes are 'rtne' and 'rtz'.") + + def bitcast(self, input: TensorTy, dst_ty: tl.dtype) -> TensorTy: + src_ty = input.type + if src_ty.is_block(): + dst_ty = src_ty.with_element_ty(dst_ty.scalar) + if src_ty == dst_ty: + return input + src_sca_ty = src_ty.scalar + dst_sca_ty = dst_ty.scalar + if src_sca_ty.is_ptr() or dst_sca_ty.is_ptr(): + return self.cast(input, dst_ty) + # Bitcast + src_bits = src_sca_ty.primitive_bitwidth + dst_bits = dst_sca_ty.primitive_bitwidth + if src_bits != dst_bits: + raise ValueError("Cannot bitcast data-type of size " + str(src_bits) + " to " + "data-type of size " + str(dst_bits)) + return self.tensor(self.builder.create_bitcast(input.handle, dst_ty.to_ir(self.builder)), dst_ty) + + def cast(self, input: TensorTy, dst_ty: tl.dtype, fp_downcast_rounding: Optional[str] = None) -> TensorTy: + src_ty = input.type + src_sca_ty = src_ty.scalar + dst_sca_ty = dst_ty.scalar + if src_sca_ty == dst_sca_ty: + return input + if src_ty.is_block(): + dst_ty = src_ty.with_element_ty(dst_sca_ty) + + # For fp downcasting default rounding mode should be RTNE, for all other conversions it should + # not be set + fp_downcast_rounding = self._str_to_rounding_mode(fp_downcast_rounding) + use_custom_rounding = False + if dst_sca_ty.is_floating() and src_sca_ty.is_floating( + ) and dst_sca_ty.primitive_bitwidth < src_sca_ty.primitive_bitwidth: + if fp_downcast_rounding is None: fp_downcast_rounding = ir.ROUNDING_MODE.RTNE + elif fp_downcast_rounding != ir.ROUNDING_MODE.RTNE: use_custom_rounding = True + else: + if fp_downcast_rounding is not None: + raise ValueError("fp_downcast_rounding should be set only for truncating fp conversions. " + "Source scalar type is " + str(src_sca_ty) + " and destination type is " + + str(dst_sca_ty)) + + if (src_sca_ty.is_fp8e4b15() or dst_sca_ty.is_fp8e4b15()): + assert self.builder.codegen_fns.get( + "convert_custom_types") is not None, "target doesn't provide conversion for this type." + return self.builder.codegen_fns["convert_custom_types"](input, dst_ty, fp_downcast_rounding, _semantic=self) + # Casting with customized floating types involved: fp8 <=> bf16, fp16, fp32, fp64 + # and non-default rounding modes for downcasting + if (src_sca_ty.is_fp8() and dst_sca_ty.is_floating()) or \ + (src_sca_ty.is_floating() and dst_sca_ty.is_fp8()) or \ + use_custom_rounding: + return self.tensor( + self.builder.create_fp_to_fp(input.handle, dst_ty.to_ir(self.builder), fp_downcast_rounding), dst_ty) + + # bf16 <=> (not fp32) + if (src_sca_ty.is_fp16() and not dst_sca_ty.is_fp32()) or \ + (src_sca_ty.is_bf16() and not dst_sca_ty.is_fp32()): + return self.cast(self.cast(input, tl.float32), dst_sca_ty) + + # Standard floating types' casting: truncation + # fp64 => fp32, fp16, bf16 + # fp32 => fp16, bf16 + truncate_fp = src_sca_ty.is_floating() and \ + dst_sca_ty.is_floating() and \ + src_sca_ty.primitive_bitwidth > dst_sca_ty.primitive_bitwidth + if truncate_fp: + return self.tensor(self.builder.create_fp_trunc(input.handle, dst_ty.to_ir(self.builder)), dst_ty) + + # Standard floating types' casting: extension + # fp32 => fp64 + # fp16 => fp32, fp64 + # bf16 => fp32, fp64 + ext_fp = src_sca_ty.is_floating() and \ + dst_sca_ty.is_floating() and \ + src_sca_ty.primitive_bitwidth < dst_sca_ty.primitive_bitwidth + if ext_fp: + return self.tensor(self.builder.create_fp_ext(input.handle, dst_ty.to_ir(self.builder)), dst_ty) + + # Casting between integer types + if src_sca_ty.is_int() and dst_sca_ty.is_int() and \ + (src_sca_ty.int_bitwidth != dst_sca_ty.int_bitwidth or src_sca_ty.int_signedness != dst_sca_ty.int_signedness): + sign_extend = src_sca_ty.is_int_signed() and not src_sca_ty.is_bool() + if dst_sca_ty.is_bool(): + ty = input.dtype.to_ir(self.builder) + _0 = self.tensor(self.builder.get_null_value(ty), input.dtype) + return self.not_equal(input, _0) + else: + return self.tensor(self.builder.create_int_cast(input.handle, dst_ty.to_ir(self.builder), sign_extend), + dst_ty) + + # Casting standard floating types to integer types + if src_sca_ty.is_standard_floating() and dst_sca_ty.is_int(): + if dst_sca_ty.is_bool(): + ty = input.dtype.to_ir(self.builder) + _0 = self.tensor(self.builder.get_null_value(ty), input.dtype) + return self.not_equal(input, _0) + elif dst_sca_ty.is_int_signed(): + return self.tensor(self.builder.create_fp_to_si(input.handle, dst_ty.to_ir(self.builder)), dst_ty) + else: + return self.tensor(self.builder.create_fp_to_ui(input.handle, dst_ty.to_ir(self.builder)), dst_ty) + + # Casting integer types to standard floating types + if src_sca_ty.is_int() and dst_sca_ty.is_standard_floating(): + if src_sca_ty.is_bool() or not src_sca_ty.is_int_signed(): + return self.tensor(self.builder.create_ui_to_fp(input.handle, dst_ty.to_ir(self.builder)), dst_ty) + else: + return self.tensor(self.builder.create_si_to_fp(input.handle, dst_ty.to_ir(self.builder)), dst_ty) + + # Casting pointer types to integer types + if src_sca_ty.is_ptr() and dst_sca_ty.is_int(): + bitwidth = dst_sca_ty.int_bitwidth + if bitwidth == 64: + return self.tensor(self.builder.create_ptr_to_int(input.handle, dst_ty.to_ir(self.builder)), dst_ty) + if bitwidth == 1: + return self.not_equal(self.cast(input, tl.int64), self.tensor(self.builder.get_int64(0), tl.int64)) + + # Casting integer types to pointer types + if src_sca_ty.is_int() and dst_sca_ty.is_ptr(): + return self.tensor(self.builder.create_int_to_ptr(input.handle, dst_ty.to_ir(self.builder)), dst_ty) + + # Casting pointer types to pointer types + if src_sca_ty.is_ptr() and dst_sca_ty.is_ptr(): + return self.tensor(self.builder.create_bitcast(input.handle, dst_ty.to_ir(self.builder)), dst_ty) + + assert False, f'cannot cast {input} to {dst_ty}' + +# ===----------------------------------------------------------------------===// +# Memory Operators +# ===----------------------------------------------------------------------===// + + def _str_to_load_cache_modifier(self, cache_modifier): + cache = ir.CACHE_MODIFIER.NONE # default + if cache_modifier: + if cache_modifier == ".ca": + cache = ir.CACHE_MODIFIER.CA + elif cache_modifier == ".cg": + cache = ir.CACHE_MODIFIER.CG + elif cache_modifier == ".cv": + cache = ir.CACHE_MODIFIER.CV + else: + raise ValueError(f"Cache modifier {cache_modifier} not supported") + return cache + + def _str_to_store_cache_modifier(self, cache_modifier): + cache = ir.CACHE_MODIFIER.NONE # default + if cache_modifier: + if cache_modifier == ".wb": + cache = ir.CACHE_MODIFIER.WB + elif cache_modifier == ".cg": + cache = ir.CACHE_MODIFIER.CG + elif cache_modifier == ".cs": + cache = ir.CACHE_MODIFIER.CS + elif cache_modifier == ".wt": + cache = ir.CACHE_MODIFIER.WT + else: + raise ValueError(f"Cache modifier {cache_modifier} not supported") + return cache + + def _str_to_eviction_policy(self, eviction_policy): + eviction = ir.EVICTION_POLICY.NORMAL # default + if eviction_policy: + if eviction_policy == "evict_last": + eviction = ir.EVICTION_POLICY.EVICT_LAST + elif eviction_policy == "evict_first": + eviction = ir.EVICTION_POLICY.EVICT_FIRST + else: + raise ValueError(f"Eviction policy {eviction_policy} not supported") + return eviction + + def _str_to_padding_option(self, padding_option): + padding = None # default + if padding_option: + if padding_option == "zero": + padding = ir.PADDING_OPTION.PAD_ZERO + elif padding_option == "nan": + padding = ir.PADDING_OPTION.PAD_NAN + else: + raise ValueError(f"Padding option {padding_option} not supported") + return padding + + def _str_to_sem(self, sem_option): + sem = ir.MEM_SEMANTIC.ACQUIRE_RELEASE + if sem_option: + if sem_option == "acquire": + sem = ir.MEM_SEMANTIC.ACQUIRE + elif sem_option == "release": + sem = ir.MEM_SEMANTIC.RELEASE + elif sem_option == "acq_rel": + sem = ir.MEM_SEMANTIC.ACQUIRE_RELEASE + elif sem_option == "relaxed": + sem = ir.MEM_SEMANTIC.RELAXED + else: + raise ValueError(f"Memory semantic {sem_option} not supported") + return sem + + def _str_to_scope(self, scope_option): + scope = ir.MEM_SYNC_SCOPE.GPU + if scope_option: + if scope_option == "gpu": + scope = ir.MEM_SYNC_SCOPE.GPU + elif scope_option == "cta": + scope = ir.MEM_SYNC_SCOPE.CTA + elif scope_option == "sys": + scope = ir.MEM_SYNC_SCOPE.SYSTEM + else: + raise ValueError(f"Memory semantic {scope_option} not supported") + return scope + + def _canonicalize_boundary_check(self, boundary_check, block_shape): + if boundary_check: + if not hasattr(boundary_check, "__iter__"): + boundary_check = [boundary_check] + boundary_check = [elem.value if isinstance(elem, tl.constexpr) else elem for elem in boundary_check] + for dim in boundary_check: + assert isinstance(dim, int) and 0 <= dim < len(block_shape) + assert len(boundary_check) > 0 + assert len(boundary_check) == len(set(boundary_check)), "Duplicate dimension in `boundary_check`" + return sorted(boundary_check) + return () + + def _load_block_pointer(self, ptr, mask, other, boundary_check, padding, cache, eviction, is_volatile): + # Load by a block pointer: `pointer_type>` + # Block pointer can not have `mask` and `other` arguments + if mask is not None or other is not None: + raise ValueError("`mask` and `other` arguments cannot be specified for loading block pointers") + + elt_ty = ptr.type.element_ty.element_ty + assert elt_ty != tl.int1, "`tl.int1` should be rewritten in `tl.make_block_ptr`" + if elt_ty.is_int() and padding == ir.PADDING_OPTION.PAD_NAN: + raise ValueError("Padding option `nan` is not supported for integer block pointers") + + # `dst_ty` is de-referenced type of the pointer type + dst_ty = ptr.type.element_ty + + # Check `boundary_check` argument + boundary_check = self._canonicalize_boundary_check(boundary_check, dst_ty.get_block_shapes()) + + # Build IR + return self.tensor( + self.builder.create_tensor_pointer_load(ptr.handle, boundary_check, padding, cache, eviction, is_volatile), + dst_ty) + + def _load_legacy(self, ptr, mask, other, boundary_check, padding, cache, eviction, is_volatile): + # Load by a tensor of pointers or a pointer of scalar: `block_type>` or `pointer_type<>` + if not ptr.type.scalar.is_ptr(): + raise ValueError(f"Unsupported ptr type {ptr.type.__repr__()} in `tl.load`") + + # Check `mask`, `other`, `boundary_check`, and `padding` arguments + if mask is None and other is not None: + raise ValueError("`other` cannot be provided without `mask`") + if padding or boundary_check: + raise ValueError("`padding_option` or `boundary_check` argument is not supported for loading a tensor of" + "pointers or loading a scalar. Because the compiler does not know the boundary; please " + "use block pointers (defined by `make_block_ptr`) instead") + + # For a pointer of scalar, check the type of `mask` and `other` + if not ptr.type.is_block(): + if mask and mask.type.is_block(): + raise ValueError("Mask argument cannot be block type if pointer argument is not a block") + if other and other.type.is_block(): + raise ValueError("Other argument cannot be block type if pointer argument is not a block") + + # Make `mask` and `other` into the same shape as `ptr` + if ptr.type.is_block(): + if mask is not None: + ptr, mask = self.broadcast_impl_value(ptr, mask) + if other is not None: + ptr, other = self.broadcast_impl_value(ptr, other) + + # Get `pointer_type` and `elt_ty` + ptr_ty = ptr.type.scalar + elt_ty = ptr_ty.element_ty + + # Treat `pointer_type` as `pointer_type` + is_bool = elt_ty == tl.int1 + if is_bool: + elt_ty = tl.int8 + ptr_ty = tl.pointer_type(elt_ty, ptr_ty.address_space) + ptr = self.cast(ptr, ptr_ty) + + # Cast `other` into `elt_ty` type + if other is not None: + other = self.cast(other, elt_ty) + + # Create loaded result type `dst_ty` + if ptr.type.is_block(): + dst_ty = ptr.type.with_element_ty(elt_ty) + else: + # Load by de-referencing the pointer of scalar + dst_ty = elt_ty + + # Build IR + if mask is None: + ret = self.tensor(self.builder.create_load(ptr.handle, cache, eviction, is_volatile), dst_ty) + else: + ret = self.tensor( + self.builder.create_masked_load(ptr.handle, mask.handle, other.handle if other else None, cache, + eviction, is_volatile), dst_ty) + if is_bool: + ret = self.cast(ret, tl.int1) + return ret + + def load(self, ptr: TensorTy, mask: Optional[TensorTy], other: Optional[TensorTy], boundary_check: Tuple, + padding_option: str, cache_modifier: str, eviction_policy: str, is_volatile: bool) -> TensorTy: + # Cache, eviction and padding options + cache = self._str_to_load_cache_modifier(cache_modifier) + eviction = self._str_to_eviction_policy(eviction_policy) + padding = self._str_to_padding_option(padding_option) + + if ptr.type.is_ptr() and ptr.type.element_ty.is_block(): + # Load by a block pointer: `pointer_type>` + return self._load_block_pointer(ptr, mask, other, boundary_check, padding, cache, eviction, is_volatile) + else: + # Load by a tensor of pointers or a pointer of scalar: `block_type>` or `pointer_type<>` + return self._load_legacy(ptr, mask, other, boundary_check, padding, cache, eviction, is_volatile) + + def descriptor_load(self, desc: tl.tensor_descriptor_base, offsets, cache_modifier: str, + eviction_policy: str) -> TensorTy: + assert isinstance(desc, tl.tensor_descriptor_base) + ndim = len(desc.block_shape) + assert len(offsets) == ndim, f"expected {ndim} offsets, but got {len(offsets)}" + + offsets = self._convert_to_ir_values(offsets, require_i64=False) + x = self.builder.create_descriptor_load(desc.handle, offsets, self._str_to_load_cache_modifier(cache_modifier), + self._str_to_eviction_policy(eviction_policy)) + return self.tensor(x, desc.block_type) + + def validate_store_like(self, desc: tl.tensor_descriptor_base, value: TensorTy, offsets) -> None: + assert isinstance(desc, tl.tensor_descriptor_base) + ndim = len(desc.block_shape) + assert len(offsets) == ndim, f"expected {ndim} offsets, but got {len(offsets)}" + assert value.shape == desc.block_shape + + def descriptor_store(self, desc: tl.tensor_descriptor_base, value: TensorTy, offsets) -> TensorTy: + self.validate_store_like(desc, value, offsets) + # implicitly cast to the descriptor's type + value = self.cast(value, desc.dtype) + offsets = self._convert_to_ir_values(offsets, require_i64=False) + return self.tensor(self.builder.create_descriptor_store(desc.handle, value.handle, offsets), tl.void) + + def descriptor_atomic_add(self, desc: tl.tensor_descriptor_base, value: TensorTy, offsets) -> TensorTy: + self.validate_store_like(desc, value, offsets) + assert desc.dtype in {tl.uint32, tl.int32, tl.uint64, tl.float32, tl.float16, tl.bfloat16}, "Unsupported dtype" + offsets = self._convert_to_ir_values(offsets, require_i64=False) + kind = ir.DESCRIPTOR_REDUCE_KIND.ADD + return self.tensor(self.builder.create_descriptor_reduce(kind, desc.handle, value.handle, offsets), tl.void) + + def _has_native_tma(self, ): + target = driver.active.get_current_target() + return (target.backend == "cuda" and target.arch >= 90) + + def _descriptor_atomic_min_max_supported(self, dtype): + assert dtype in {tl.uint32, tl.int32, tl.uint64, tl.int64, tl.float16, tl.bfloat16}, "Unsupported dtype" + if dtype in {tl.float16, tl.bfloat16}: + assert self._has_native_tma(), "16-bit float types require native tma support" + + def descriptor_atomic_min(self, desc: tl.tensor_descriptor_base, value: TensorTy, offsets) -> TensorTy: + self.validate_store_like(desc, value, offsets) + self._descriptor_atomic_min_max_supported(desc.dtype) + offsets = self._convert_to_ir_values(offsets, require_i64=False) + kind = ir.DESCRIPTOR_REDUCE_KIND.MIN + return self.tensor(self.builder.create_descriptor_reduce(kind, desc.handle, value.handle, offsets), tl.void) + + def descriptor_atomic_max(self, desc: tl.tensor_descriptor_base, value: TensorTy, offsets) -> TensorTy: + self.validate_store_like(desc, value, offsets) + self._descriptor_atomic_min_max_supported(desc.dtype) + offsets = self._convert_to_ir_values(offsets, require_i64=False) + kind = ir.DESCRIPTOR_REDUCE_KIND.MAX + return self.tensor(self.builder.create_descriptor_reduce(kind, desc.handle, value.handle, offsets), tl.void) + + def descriptor_atomic_and(self, desc: tl.tensor_descriptor_base, value: TensorTy, offsets) -> TensorTy: + self.validate_store_like(desc, value, offsets) + assert desc.dtype in {tl.uint32, tl.int32, tl.uint64, tl.int64}, "Unsupported dtype" + offsets = self._convert_to_ir_values(offsets, require_i64=False) + kind = ir.DESCRIPTOR_REDUCE_KIND.AND + return self.tensor(self.builder.create_descriptor_reduce(kind, desc.handle, value.handle, offsets), tl.void) + + def descriptor_atomic_or(self, desc: tl.tensor_descriptor_base, value: TensorTy, offsets) -> TensorTy: + self.validate_store_like(desc, value, offsets) + assert desc.dtype in {tl.uint32, tl.int32, tl.uint64, tl.int64}, "Unsupported dtype" + offsets = self._convert_to_ir_values(offsets, require_i64=False) + kind = ir.DESCRIPTOR_REDUCE_KIND.OR + return self.tensor(self.builder.create_descriptor_reduce(kind, desc.handle, value.handle, offsets), tl.void) + + def descriptor_atomic_xor(self, desc: tl.tensor_descriptor_base, value: TensorTy, offsets) -> TensorTy: + self.validate_store_like(desc, value, offsets) + assert desc.dtype in {tl.uint32, tl.int32, tl.uint64, tl.int64}, "Unsupported dtype" + offsets = self._convert_to_ir_values(offsets, require_i64=False) + kind = ir.DESCRIPTOR_REDUCE_KIND.XOR + return self.tensor(self.builder.create_descriptor_reduce(kind, desc.handle, value.handle, offsets), tl.void) + + def descriptor_gather(self, desc, x_offsets, y_offset, cache_modifier: str, eviction_policy: str) -> TensorTy: + assert isinstance(desc, tl.tensor_descriptor_base) + assert cache_modifier == "", "cache modifier is not supported yet" + assert eviction_policy == "", "eviction policy is not supported yet" + + # Validate descriptor. + assert len(desc.block_shape) == 2, f"descriptor must be 2D, but got {desc.block_shape}" + assert desc.block_shape[0] == 1, f"descriptor block must have 1 row, but got {desc.block_shape}" + + # Validate offsets. + assert len(x_offsets.shape) == 1, f"x offsets must be 1D, but got {x_offsets.shape}" + + # Validate minimum block size. + assert x_offsets.shape[0] >= 8, f"descriptor gather must have at least 8 rows, but got {x_offsets.shape}" + dtype = desc.dtype + min_cols = 32 // dtype.primitive_bitwidth * 8 + assert desc.block_shape[ + 1] >= min_cols, f"descriptor gather of {dtype} must have at least {min_cols} columns, but got {desc.block_shape[1]}" + + type = tl.block_type(desc.dtype, [x_offsets.shape[0], desc.block_shape[1]]) + y_offset = self._convert_to_ir_values((y_offset, ), require_i64=False)[0] + x = self.builder.create_descriptor_gather(desc.handle, x_offsets.handle, y_offset, type.to_ir(self.builder)) + return self.tensor(x, type) + + def descriptor_scatter(self, desc, value: TensorTy, x_offsets, y_offset) -> TensorTy: + assert isinstance(desc, tl.tensor_descriptor_base) + + # Validate descriptor. + assert len(desc.block_shape) == 2, f"descriptor must be 2D, but got {desc.block_shape}" + assert desc.block_shape[0] == 1, f"descriptor block must have 1 row, but got {desc.block_shape}" + + # Validate offsets. + assert len(x_offsets.shape) == 1, f"x offsets must be 1D, but got {x_offsets.shapae}" + + # Validate minimum block size. + assert x_offsets.shape[0] >= 8, f"descriptor scatter must have at least 8 rows, but got {x_offsets.shape}" + dtype = desc.dtype + min_cols = 32 // dtype.primitive_bitwidth * 8 + assert desc.block_shape[ + 1] >= min_cols, f"descriptor scatter of {dtype} must have at least {min_cols} columns, but got {desc.block_shape[1]}" + + y_offset = self._convert_to_ir_values((y_offset, ), require_i64=False)[0] + self.builder.create_descriptor_scatter(desc.handle, value.handle, x_offsets.handle, y_offset) + return self.tensor(None, tl.void) + + def _store_block_pointer(self, ptr, val, mask, boundary_check, cache, eviction): + # Store by a block pointer: `pointer_type>` + # Block pointers can not have the `mask` argument + if mask is not None: + raise ValueError("`mask` and `other` arguments cannot be specified for loading block pointers") + + # Check same shape and element type + block_shape = ptr.type.element_ty.get_block_shapes() + if not val.type.is_block(): + val = self.broadcast_impl_shape(val, block_shape) + assert val.type.is_block(), "Value argument must be block type or a scalar" + assert block_shape == val.type.get_block_shapes( + ), f"Block shape({block_shape}) and value shape({val.type.get_block_shapes()}) mismatch" + assert ptr.type.element_ty.element_ty == val.type.element_ty, f"Block element type({ptr.type.element_ty.element_ty}) and value element type({val.type.element_ty}) mismatch" + + elt_ty = ptr.type.element_ty.element_ty + assert elt_ty != tl.int1, "`tl.int1` should be rewritten in `tl.make_block_ptr`" + + # Check `boundary_check` argument + boundary_check = self._canonicalize_boundary_check(boundary_check, block_shape) + + # Cast to target data type + val = self.cast(val, elt_ty) + + # Build IR + return self.tensor( + self.builder.create_tensor_pointer_store(ptr.handle, val.handle, boundary_check, cache, eviction), tl.void) + + def _store_legacy(self, ptr, val, mask, boundary_check, cache, eviction): + # Store by a tensor of pointers or a pointer of scalar: `block_type>` or `pointer_type<>` + if not ptr.type.scalar.is_ptr(): + raise ValueError(f"Unsupported ptr type {ptr.type.__repr__()} in `tl.store`") + + # Check `boundary_check` argument + if boundary_check: + raise ValueError("`boundary_check` argument is not supported for storing a tensor of pointers or storing a " + "scalar. Because the compiler does not know the boundary; please use block pointers " + "(defined by `make_block_ptr`) instead") + + # For a pointer of scalar, check the type of `val` and `mask` + if not ptr.type.is_block(): + if val.type.is_block(): + raise ValueError("Value argument cannot be block type if pointer argument is not a block") + if mask and mask.type.is_block(): + raise ValueError("Mask argument cannot be block type if pointer argument is not a block") + + # Make `mask` and `val` into the same shape as `ptr` + if ptr.type.is_block(): + ptr_shape = ptr.shape + if mask is None: + ptr, val = self.broadcast_tensors(ptr, val) + else: + ptr, val, mask = self.broadcast_tensors(ptr, val, mask) + if ptr_shape != ptr.shape: + raise ValueError(f"Expected pointer argument to have shape {ptr.shape} but got {ptr_shape}") + + ptr_ty = ptr.type.scalar + elt_ty = ptr_ty.element_ty + + # Treat `pointer_type` as `pointer_type` + if elt_ty == tl.int1: + elt_ty = tl.int8 + ptr_ty = tl.pointer_type(elt_ty, ptr_ty.address_space) + ptr = self.cast(ptr, ptr_ty) + + # Cast to target data type + val = self.cast(val, elt_ty) + + # Build IR + if mask is None: + return self.tensor(self.builder.create_store(ptr.handle, val.handle, cache, eviction), tl.void) + if not mask.type.scalar.is_bool(): + raise ValueError("Mask must have boolean scalar type") + return self.tensor(self.builder.create_masked_store(ptr.handle, val.handle, mask.handle, cache, eviction), + tl.void) + + def store(self, ptr: TensorTy, val: TensorTy, mask: Optional[TensorTy], boundary_check, cache_modifier: str, + eviction_policy: str) -> TensorTy: + # Cache and eviction options + cache = self._str_to_store_cache_modifier(cache_modifier) + eviction = self._str_to_eviction_policy(eviction_policy) + + if ptr.type.is_const() or ptr.type.scalar.is_const(): + raise ValueError("Cannot store to a constant pointer") + + if ptr.type.is_ptr() and ptr.type.element_ty.is_block(): + # Store by a block pointer: `pointer_type>` + return self._store_block_pointer(ptr, val, mask, boundary_check, cache, eviction) + else: + # Store by a tensor of pointers or a pointer of scalar: `block_type>` or `pointer_type<>` + return self._store_legacy(ptr, val, mask, boundary_check, cache, eviction) + +######### +# atomic +######### + + def atomic_cas(self, ptr: TensorTy, cmp: TensorTy, val: TensorTy, sem: str, scope: str) -> TensorTy: + sem = self._str_to_sem(sem) + scope = self._str_to_scope(scope) + element_ty = ptr.type.scalar.element_ty + if element_ty.primitive_bitwidth not in [16, 32, 64]: + raise ValueError("atomic_cas only supports elements with width {16, 32, 64}") + return self.tensor(self.builder.create_atomic_cas(ptr.handle, cmp.handle, val.handle, sem, scope), val.type) + + def atom_red_typechecking_impl(self, ptr: TensorTy, val: TensorTy, mask: TensorTy, + op: str) -> Tuple[TensorTy, TensorTy, TensorTy]: + if not ptr.type.scalar.is_ptr(): + raise ValueError("Pointer argument of store instruction is " + ptr.type.__repr__()) + if ptr.type.is_const() or ptr.type.element_ty.is_const(): + raise ValueError("Cannot store to a constant pointer") + element_ty = ptr.type.scalar.element_ty + if element_ty is tl.float16 and op != 'add': + raise ValueError("atomic_" + op + " does not support fp16") + if element_ty is tl.bfloat16 and op != 'add': + raise ValueError("atomic_" + op + " does not support bf16") + if element_ty in [tl.int16, tl.uint16] or element_ty.primitive_bitwidth < 16: + raise ValueError("atomic_" + op + " does not support " + str(element_ty)) + if ptr.type.is_block(): + if mask is not None: + mask = self.broadcast_impl_shape(mask, ptr.type.get_block_shapes()) + if val is not None: + val = self.broadcast_impl_shape(val, ptr.type.get_block_shapes()) + val = self.cast(val, ptr.type.scalar.element_ty) + if mask is None: + mask_ir = self.builder.get_int1(True) + mask_ty = tl.int1 + if ptr.type.is_block(): + mask_ty = ptr.type.with_element_ty(tl.int1) + mask_ir = self.builder.create_splat(mask_ty.to_ir(self.builder), mask_ir) + mask = self.tensor(mask_ir, mask_ty) + return ptr, val, mask + + def _signbit(self, x: TensorTy) -> TensorTy: + bitwidth = x.dtype.primitive_bitwidth + idtype = tl.get_int_dtype(bitwidth=bitwidth, signed=False) + ix = self.bitcast(x, idtype) + signbit = self.lshr(ix, bitwidth - 1) + return self.cast(signbit, tl.int1) + + def atomic_max(self, ptr: TensorTy, val: TensorTy, mask: TensorTy, sem: str, scope: str) -> TensorTy: + ptr, val, mask = self.atom_red_typechecking_impl(ptr, val, mask, 'max') + sem = self._str_to_sem(sem) + scope = self._str_to_scope(scope) + sca_ty = val.type.scalar + # direct call to atomic_max for integers + if sca_ty.is_int(): + if sca_ty.is_int_signed(): + return self.tensor( + self.builder.create_atomic_rmw(ir.ATOMIC_OP.MAX, ptr.handle, val.handle, mask.handle, sem, scope), + val.type) + else: + return self.tensor( + self.builder.create_atomic_rmw(ir.ATOMIC_OP.UMAX, ptr.handle, val.handle, mask.handle, sem, scope), + val.type) + # for float + # return atomic_smax(i_ptr, i_val) if val >= 0 + # return atomic_umin(i_ptr, i_val) if val < 0 + if sca_ty not in {tl.float32, tl.float64}: + raise TypeError(f"atomic_max not supported for dtype {sca_ty}") + + i_type = tl.int32 if sca_ty == tl.float32 else tl.int64 + i_val = self.bitcast(val, i_type) + i_ptr = self.bitcast(ptr, tl.pointer_type(i_type, 1)) + ui_type = tl.uint32 if sca_ty == tl.float32 else tl.uint64 + ui_val = self.bitcast(val, ui_type) + ui_ptr = self.bitcast(ptr, tl.pointer_type(ui_type, 1)) + neg = self._signbit(val) + pos = self.not_(neg) + pos_ret = self.tensor( + self.builder.create_atomic_rmw(ir.ATOMIC_OP.MAX, i_ptr.handle, i_val.handle, + self.and_(mask, pos).handle, sem, scope), i_val.type) + neg_ret = self.tensor( + self.builder.create_atomic_rmw(ir.ATOMIC_OP.UMIN, ui_ptr.handle, ui_val.handle, + self.and_(mask, neg).handle, sem, scope), ui_val.type) + ret = self.where(pos, pos_ret, neg_ret) + return self.bitcast(ret, sca_ty) + + def atomic_min(self, ptr: TensorTy, val: TensorTy, mask: TensorTy, sem: str, scope: str) -> TensorTy: + ptr, val, mask = self.atom_red_typechecking_impl(ptr, val, mask, 'min') + sem = self._str_to_sem(sem) + scope = self._str_to_scope(scope) + sca_ty = val.type.scalar + # direct call to atomic_min for integers + if sca_ty.is_int(): + if sca_ty.is_int_signed(): + return self.tensor( + self.builder.create_atomic_rmw(ir.ATOMIC_OP.MIN, ptr.handle, val.handle, mask.handle, sem, scope), + val.type) + else: + return self.tensor( + self.builder.create_atomic_rmw(ir.ATOMIC_OP.UMIN, ptr.handle, val.handle, mask.handle, sem, scope), + val.type) + # for float + # return atomic_smin(i_ptr, i_val) if val >= 0 + # return atomic_umax(i_ptr, i_val) if val < 0 + if sca_ty not in {tl.float32, tl.float64}: + raise TypeError(f"atomic_min not supported for dtype {sca_ty}") + + i_type = tl.int32 if sca_ty == tl.float32 else tl.int64 + i_val = self.bitcast(val, i_type) + i_ptr = self.bitcast(ptr, tl.pointer_type(i_type, 1)) + ui_type = tl.uint32 if sca_ty == tl.float32 else tl.uint64 + ui_val = self.bitcast(val, ui_type) + ui_ptr = self.bitcast(ptr, tl.pointer_type(ui_type, 1)) + neg = self._signbit(val) + pos = self.not_(neg) + pos_ret = self.tensor( + self.builder.create_atomic_rmw(ir.ATOMIC_OP.MIN, i_ptr.handle, i_val.handle, + self.and_(mask, pos).handle, sem, scope), i_val.type) + neg_ret = self.tensor( + self.builder.create_atomic_rmw(ir.ATOMIC_OP.UMAX, ui_ptr.handle, ui_val.handle, + self.and_(mask, neg).handle, sem, scope), ui_ptr.type) + ret = self.where(pos, pos_ret, neg_ret) + return self.bitcast(ret, sca_ty) + + def atomic_add(self, ptr: TensorTy, val: TensorTy, mask: TensorTy, sem: str, scope: str) -> TensorTy: + ptr, val, mask = self.atom_red_typechecking_impl(ptr, val, mask, 'add') + sem = self._str_to_sem(sem) + scope = self._str_to_scope(scope) + sca_ty = val.type.scalar + op = ir.ATOMIC_OP.FADD if sca_ty.is_floating() else ir.ATOMIC_OP.ADD + return self.tensor(self.builder.create_atomic_rmw(op, ptr.handle, val.handle, mask.handle, sem, scope), + val.type) + + def atomic_and(self, ptr: TensorTy, val: TensorTy, mask: TensorTy, sem: str, scope: str) -> TensorTy: + ptr, val, mask = self.atom_red_typechecking_impl(ptr, val, mask, 'and') + sem = self._str_to_sem(sem) + scope = self._str_to_scope(scope) + return self.tensor( + self.builder.create_atomic_rmw(ir.ATOMIC_OP.AND, ptr.handle, val.handle, mask.handle, sem, scope), val.type) + + def atomic_or(self, ptr: TensorTy, val: TensorTy, mask: TensorTy, sem: str, scope: str) -> TensorTy: + ptr, val, mask = self.atom_red_typechecking_impl(ptr, val, mask, 'or') + sem = self._str_to_sem(sem) + scope = self._str_to_scope(scope) + return self.tensor( + self.builder.create_atomic_rmw(ir.ATOMIC_OP.OR, ptr.handle, val.handle, mask.handle, sem, scope), val.type) + + def atomic_xor(self, ptr: TensorTy, val: TensorTy, mask: TensorTy, sem: str, scope: str) -> TensorTy: + ptr, val, mask = self.atom_red_typechecking_impl(ptr, val, mask, 'xor') + sem = self._str_to_sem(sem) + scope = self._str_to_scope(scope) + return self.tensor( + self.builder.create_atomic_rmw(ir.ATOMIC_OP.XOR, ptr.handle, val.handle, mask.handle, sem, scope), val.type) + + def atomic_xchg(self, ptr: TensorTy, val: TensorTy, mask: TensorTy, sem: str, scope: str) -> TensorTy: + ptr, val, mask = self.atom_red_typechecking_impl(ptr, val, mask, 'xchg') + sem = self._str_to_sem(sem) + scope = self._str_to_scope(scope) + return self.tensor( + self.builder.create_atomic_rmw(ir.ATOMIC_OP.XCHG, ptr.handle, val.handle, mask.handle, sem, scope), + val.type) + +# ===----------------------------------------------------------------------===// +# Linear Algebra +# ===----------------------------------------------------------------------===// + + def _str_to_dot_input_precision(self, input_precision): + assert input_precision.lower() in self.builder.options.allowed_dot_input_precisions, \ + f"input_precision must be one of {self.builder.options.allowed_dot_input_precisions}. Got {input_precision}" + input_precision = input_precision.upper() + if input_precision == "TF32X3": + input_precision = "TF32x3" + if input_precision == "BF16X3": + input_precision = "BF16x3" + if input_precision == "BF16X6": + input_precision = "BF16x6" + return getattr(ir.INPUT_PRECISION, input_precision) + + def dot(self, lhs: TensorTy, rhs: TensorTy, acc: TensorTy, input_precision: Optional[str], + max_num_imprecise_acc: int, out_dtype: tl.dtype) -> TensorTy: + assert lhs.type.is_block() and rhs.type.is_block() + + if lhs.dtype.is_fp8() and rhs.dtype.is_fp8(): + # All combinations of supported fp8 x fp8 are permitted + pass + else: + assert lhs.dtype in (tl.int8, tl.uint8, tl.float16, tl.bfloat16, tl.float32, + tl.float64), f"Unsupported lhs dtype {lhs.dtype}" + assert rhs.dtype in (tl.int8, tl.uint8, tl.float16, tl.bfloat16, tl.float32, + tl.float64), f"Unsupported rhs dtype {rhs.dtype}" + assert lhs.dtype == rhs.dtype, f"Both operands must be same dtype. Got {lhs.dtype} and {rhs.dtype}" + + if lhs.dtype.is_fp8e4b15() or rhs.dtype.is_fp8e4b15(): + if "fp8e4b15" in self.builder.options.deprecated_fp8_dot_operand_dtypes: + warnings.warn( + "the use of fp8e4b15 is deprecated on Hopper and later architectures and can cause significant slow down. It will be removed in a future triton release" + ) + # We upcast because there's no fp8e4b15 type in MLIR + lhs = self.cast(lhs, tl.float16) + rhs = self.cast(rhs, tl.float16) + + uses_fp8e4b8 = lhs.dtype.is_fp8e4b8() or rhs.dtype.is_fp8e4b8() + uses_fp8e5b16 = lhs.dtype.is_fp8e5b16() or rhs.dtype.is_fp8e5b16() + if uses_fp8e4b8 or uses_fp8e5b16: + type_name = "fp8e4b8" if uses_fp8e4b8 else "fp8e5b16" + if type_name in self.builder.options.deprecated_fp8_dot_operand_dtypes: + arch = self.builder.options.arch + warnings.warn( + f"{type_name} is AMD gfx942 specific and not supported on {arch} so it's upcasted to fp16 and can cause significant slow down. " + f"Please use OCP fp8 variants on {arch} for performance") + lhs = self.cast(lhs, tl.float16) + rhs = self.cast(rhs, tl.float16) + + if input_precision is None: + input_precision = self.builder.options.default_dot_input_precision + + input_precision = self._str_to_dot_input_precision(input_precision) + + lhs_rank = len(lhs.shape) + rhs_rank = len(rhs.shape) + assert lhs_rank == rhs_rank == 2 or lhs_rank == rhs_rank == 3, f"Both inputs must be either 2D or 3D; (lhs: {lhs.shape} vs rhs: {rhs.shape})" + assert lhs.shape[-1].value == rhs.shape[ + -2].value, f"First input shape ({lhs.shape}) and second input shape {rhs.shape} are not compatible for matmul (second index of first shape ({lhs.shape[-1].value}) must be equal to first index of second shape ({rhs.shape[-2].value})" + assert self.builder.codegen_fns.get( + "min_dot_size") is not None, "target doesn't provide lower shape bounds for dot." + min_dot_size = self.builder.codegen_fns["min_dot_size"](lhs.type, rhs.type) + assert lhs.shape[-2].value >= min_dot_size[0] and lhs.shape[-1].value >= min_dot_size[2] \ + and rhs.shape[-1].value >= min_dot_size[1], \ + f"Input shapes should have M >= {min_dot_size[0]}, N >= {min_dot_size[1]} and K >= {min_dot_size[2]}" + if lhs.type.scalar.is_int(): + assert lhs.type.scalar == tl.int8, "only int8 supported!" + _0 = self.builder.get_int32(0) + ret_scalar_ty = tl.int32 + elif out_dtype.is_bf16(): + raise ValueError( + "out_dtype=bfloat16 is unsupported. Please use out_dtype=float32/float16 and cast with `.to(tl.bfloat16)`" + ) + elif lhs.type.scalar.is_fp32() or lhs.type.scalar.is_bf16(): + _0 = self.builder.get_fp32(0) + ret_scalar_ty = tl.float32 + elif lhs.type.scalar.is_fp64(): + _0 = self.builder.get_fp64(0) + ret_scalar_ty = tl.float64 + else: + _0 = self.builder.get_fp16(0) if out_dtype.is_fp16() else self.builder.get_fp32(0) + ret_scalar_ty = out_dtype + + M = lhs.type.shape[-2] + N = rhs.type.shape[-1] + K = lhs.type.shape[-1] + B = lhs.type.shape[0] if lhs_rank == 3 else None + ret_ty = tl.block_type(ret_scalar_ty, [B, M, N] if B else [M, N]) + if acc is None: + acc_handle = self.builder.create_splat(ret_ty.to_ir(self.builder), _0) + else: + acc_handle = acc.handle + assert acc.type.shape == ret_ty.shape and acc.type.element_ty == out_dtype + + # max_num_imprecise_acc only applies to fp8 -> fp32 dot on sm_90 + if max_num_imprecise_acc is None: + if lhs.dtype.is_fp8() and rhs.dtype.is_fp8(): + max_num_imprecise_acc = self.builder.options.max_num_imprecise_acc_default + else: + max_num_imprecise_acc = 0 + else: + if lhs.dtype.is_fp8() and rhs.dtype.is_fp8() and max_num_imprecise_acc > K: + raise ValueError(f"max_num_imprecise_acc ({max_num_imprecise_acc}) must be <= K ({K})") + + return self.tensor( + self.builder.create_dot(lhs.handle, rhs.handle, acc_handle, input_precision, max_num_imprecise_acc), ret_ty) + + def _str_to_fp_type(self, float_format: str): + ty_enum = getattr(ir.ScaleDotElemTypeTY, float_format.upper(), None) + if ty_enum is None: + raise ValueError(f"Invalid float format: {float_format}.") + return ty_enum + + def _bitcast_to_fp_type(self, val: TensorTy, float_format: str): + """ + If float_format is subbyte, make sure it's packed as uint8 and return it. + Otherwise, return a tensor (perhaps bitcasting) of the specified float format. + """ + triton_ty = {"e5m2": tl.float8e5, "e4m3": tl.float8e4nv, "bf16": tl.bfloat16, "fp16": + tl.float16}.get(float_format) + if triton_ty is None: + assert float_format == "e2m1", f"Internal Error: Unexpected float format: {float_format}" + assert val.dtype == tl.uint8, f"e2m1 format must be packed as uint8. Got {val.dtype}" + return val + if val.dtype == triton_ty: + return val + else: + unsigned_ty = {"e5m2": tl.uint8, "e4m3": tl.uint8, "bf16": tl.uint16, "fp16": tl.uint16}[float_format] + assert val.dtype == unsigned_ty, f"Unexpected dtype for {float_format}. Got {val.dtype}" + return self.bitcast(val, triton_ty) + + def verify_scaled_shape(self, M, N, K, lhs_scale, rhs_scale): + if lhs_scale is not None: + scale_factor = 16 if lhs_scale.dtype.is_fp8e4nv() else 32 + lhs_scale_shape = lhs_scale.type.shape + assert lhs_scale_shape == [ + M, K // scale_factor + ], f"lhs_scale must be a tensor of shape [{M}, {K // scale_factor}]. Got {lhs_scale_shape}" + if rhs_scale is not None: + scale_factor = 16 if rhs_scale.dtype.is_fp8e4nv() else 32 + rhs_scale_shape = rhs_scale.type.shape + assert rhs_scale_shape == [ + N, K // scale_factor + ], f"rhs_scale must be a tensor of shape [{N}, {K // scale_factor}]. Got {rhs_scale_shape}" + + def dot_scaled(self, lhs: TensorTy, lhs_scale: TensorTy, lhs_format: str, rhs: TensorTy, + rhs_scale: Optional[TensorTy], rhs_format: str, acc: TensorTy | None, fast_math: bool, + lhs_k_pack: bool, rhs_k_pack: bool, out_dtype: tl.dtype) -> TensorTy: + assert lhs.type.is_block() and rhs.type.is_block() + #TODO: validate types. + lhs_rank = len(lhs.shape) + rhs_rank = len(rhs.shape) + assert lhs_rank == rhs_rank == 2 or lhs_rank == rhs_rank == 3, f"Both inputs must be either 2D or 3D; (lhs: {lhs.shape} vs rhs: {rhs.shape})" + lhs_format: str = lhs_format.value + rhs_format: str = rhs_format.value + lhs_format_enum = self._str_to_fp_type(lhs_format) + rhs_format_enum = self._str_to_fp_type(rhs_format) + allowed_formats = {"e2m1", "e4m3", "e5m2", "bf16", "fp16"} + assert lhs_format in allowed_formats, f"NYI: lhs_format {lhs_format}" + assert rhs_format in allowed_formats, f"NYI: rhs_format {rhs_format}" + rhs_scale_is_none = rhs_scale is None or (isinstance(rhs_scale, tl.constexpr) and rhs_scale.value is None) + lhs_scale_is_none = lhs_scale is None or (isinstance(lhs_scale, tl.constexpr) and lhs_scale.value is None) + lhs = self._bitcast_to_fp_type(lhs, lhs_format) + rhs = self._bitcast_to_fp_type(rhs, rhs_format) + + assert lhs_k_pack or lhs_format == "e2m1", "only mxfp4 inputs can be packed along a dimension different than K" + assert rhs_k_pack or rhs_format == "e2m1", "only mxfp4 inputs can be packed along a dimension different than K" + M, K_LHS = lhs.type.shape[-2:] + K_RHS, N = rhs.type.shape[-2:] + PACKED_A = 2 if lhs_format == "e2m1" else 1 + PACKED_B = 2 if rhs_format == "e2m1" else 1 + PACKED_A_DIM = PACKED_A * K_LHS if lhs_k_pack else K_LHS + PACKED_B_DIM = PACKED_B * K_RHS if rhs_k_pack else K_RHS + assert PACKED_B_DIM == PACKED_A_DIM, f"Reduction dimension should pack the same number of elements; (lhs: {lhs.shape} vs rhs: {rhs.shape})" + #assert K * PACKED_B >= 64, f"scaled_dot NYI for K < 64. Got {K=}" + B = lhs.type.shape[0] if lhs_rank == 3 else None + K = K_LHS + if not lhs_k_pack: + M = M * PACKED_A + else: + K = K * PACKED_A + if not rhs_k_pack: + N = N * PACKED_B + ret_ty = tl.block_type(out_dtype, [B, M, N] if B else [M, N]) + _0 = self.builder.get_fp32(0) + if acc is None: + acc_handle = self.builder.create_splat(ret_ty.to_ir(self.builder), _0) + else: + acc_handle = acc.handle + assert acc.type.shape == ret_ty.shape and acc.type.element_ty == out_dtype + rhs_scale_handle = None if rhs_scale_is_none else rhs_scale.handle + lhs_scale_handle = None if lhs_scale_is_none else lhs_scale.handle + self.verify_scaled_shape(M, N, K, None if lhs_scale_is_none else lhs_scale, + None if rhs_scale_is_none else rhs_scale) + return self.tensor( + self.builder.create_dot_scaled(lhs.handle, lhs_scale_handle, lhs_format_enum, rhs.handle, rhs_scale_handle, + rhs_format_enum, fast_math, lhs_k_pack, rhs_k_pack, acc_handle), ret_ty) + +# ===----------------------------------------------------------------------===// +# Indexing +# ===----------------------------------------------------------------------===// + + def where(self, condition: TensorTy, x: TensorTy, y: TensorTy) -> TensorTy: + if condition.dtype != tl.int1: + warnings.warn( + f"tl.where with a non-boolean condition is deprecated and will error out in a future triton release. Got {condition.dtype}" + ) + condition = self.cast(condition, tl.int1) + x, y = self.binary_op_type_checking_impl(x, y, True, True) + # x, y are broadcasted + if condition.type.is_block(): + condition, x = self.broadcast_impl_value(condition, x) + x, y = self.broadcast_impl_value(x, y) + else: + condition, _ = self.broadcast_impl_value(condition, x) + ret_ty = x.type + return self.tensor(self.builder.create_select(condition.handle, x.handle, y.handle), ret_ty) + +# ===----------------------------------------------------------------------===// +# Reduction +# ===----------------------------------------------------------------------=== + + def wrap_tensor(self, x, scalar_ty, ret_shape): + if ret_shape: + res_ty = tl.block_type(scalar_ty, ret_shape) + else: + # 0d-tensor -> scalar + res_ty = scalar_ty + return self.tensor(x, res_ty) + + def reduction(self, inputs: Sequence[TensorTy], axis: int, region_builder_fn) -> Tuple[TensorTy, ...]: + if axis is None: + inputs = tuple(self.reshape(t, [t.numel.value], can_reorder=True) for t in inputs) + axis = 0 + # get result shape + shape = inputs[0].type.shape + rank = len(shape) + assert axis < rank, f"reduction axis must be < inputs rank ({rank})" + ret_shape = [s for i, s in enumerate(shape) if i != axis] + assert all(t.type.shape == shape for t in inputs), "all reduction inputs must have the same shape" + + reduce_op = self.builder.create_reduce([t.handle for t in inputs], axis) + region_builder_fn(reduce_op) + assert reduce_op.verify() + + return tuple( + self.wrap_tensor(reduce_op.get_result(i), inputs[i].type.scalar, ret_shape) for i in range(len(inputs))) + +# ===----------------------------------------------------------------------=== +# Associative Scan +# ===----------------------------------------------------------------------=== + + def associative_scan(self, inputs: Sequence[TensorTy], axis: int, region_builder_fn, + reverse: bool) -> Tuple[TensorTy, ...]: + shape = inputs[0].type.shape + rank = len(shape) + + assert -rank <= axis < rank, f"scan axis {axis} must be < inputs rank ({rank})" + + if axis < 0: + axis += rank + + for t in inputs: + assert t.type.shape == shape, "all scan inputs must have the same shape" + + scan_op = self.builder.create_scan([t.handle for t in inputs], axis, reverse) + region_builder_fn(scan_op) + assert scan_op.verify() + + return tuple(self.wrap_tensor(scan_op.get_result(i), inputs[i].type.scalar, shape) for i in range(len(inputs))) + +# ===----------------------------------------------------------------------=== +# Gather +# ===----------------------------------------------------------------------=== + + def gather(self, src: TensorTy, index: TensorTy, axis: int) -> TensorTy: + assert index.dtype.is_int(), "index must be an integer tensor" + + rank = len(src.type.shape) + assert len(index.type.shape) == rank, "source and index tensors must have the same rank" + + assert -rank <= axis < rank, f"gather axis {axis} must be < source rank ({rank})" + if axis < 0: + axis += rank + + for d in range(rank): + if d == axis: + continue + assert index.type.shape[d] == src.type.shape[d], f"index dim {axis} must match the corresponding source dim" + + gather = self.builder.create_gather(src.handle, index.handle, axis) + return self.wrap_tensor(gather, src.type.scalar, index.type.shape) + +# ===----------------------------------------------------------------------=== +# Map Elementwise +# ===----------------------------------------------------------------------=== + + def broadcast_tensors(self, *inputs): + if not inputs: + return () + head, *tail = inputs + for i in range(len(tail)): + head, tail[i] = self.broadcast_impl_value(head, tail[i]) + for i in range(len(tail) - 1): + head, tail[i] = self.broadcast_impl_value(head, tail[i]) + return (head, *tail) + + def map_elementwise(self, inputs: Sequence[tl.tensor], result_types: Sequence[tl.dtype], pack: int, + region_builder_fn) -> Tuple[tl.tensor, ...]: + inputs = self.broadcast_tensors(*inputs) + + assert len(inputs) > 0, "map_elementwise must have at least 1 input tensor" + result_types = [inputs[0].type.with_element_ty(ty.scalar) for ty in result_types] + elementwise_op = self.builder.create_map_elementwise( + [t.handle for t in inputs], + [ty.to_ir(self.builder) for ty in result_types], + pack, + ) + region_builder_fn(elementwise_op) + assert elementwise_op.verify() + + return tuple(self.tensor(elementwise_op.get_result(i), ty) for i, ty in enumerate(result_types)) + + +# ===----------------------------------------------------------------------=== +# Histogram +# ===----------------------------------------------------------------------=== + + def histogram(self, input: TensorTy, num_bins: int, mask: Optional[TensorTy]) -> TensorTy: + assert len(input.shape) == 1, "histogram only supports 1D input" + assert input.dtype.is_int(), "histogram only supports integer input" + if mask is not None: + mask = self.broadcast_impl_shape(mask, input.shape) + if not mask.type.scalar.is_bool(): + raise ValueError("Mask must have boolean scalar type") + mask = mask.handle + return self.tensor(self.builder.create_histogram(input.handle, num_bins, mask), + tl.block_type(tl.int32, [num_bins])) + + def multiple_of(self, x: TensorTy, values: List[int]) -> TensorTy: + if max(1, len(x.shape)) != len(values): + raise ValueError("Shape of input to multiple_of does not match the length of values") + x.handle.set_attr("tt.divisibility", ir.make_attr(values, x.handle.get_context())) + return x + + def max_contiguous(self, x: TensorTy, values: List[int]) -> TensorTy: + if len(x.shape) != len(values): + raise ValueError("Shape of input to max_contiguous does not match the length of values") + x.handle.set_attr("tt.contiguity", ir.make_attr(values, x.handle.get_context())) + return x + + def max_constancy(self, x: TensorTy, values: List[int]) -> TensorTy: + if len(x.shape) != len(values): + raise ValueError("Shape of input to max_constancy does not match the length of values") + x.handle.set_attr("tt.constancy", ir.make_attr(values, x.handle.get_context())) + return x + + def debug_barrier(self) -> TensorTy: + return self.tensor(self.builder.create_barrier(), tl.void) + + def device_print(self, prefix: str, args: List[TensorTy], hex: bool) -> TensorTy: + # It makes sense visually for prefix to end in ": "; make it so. Also, + # non-empty prefixes should start with " ". + if not prefix.endswith(" ") and args: + prefix += " " + if not prefix.endswith(": ") and args: + prefix = prefix[:-1] + ": " + if len(prefix) > 2 and not prefix.startswith(" "): + prefix = " " + prefix + + new_args = [arg.handle for arg in args] + is_signed = [arg.dtype.is_int_signed() for arg in args] + return self.tensor(self.builder.create_print(prefix, hex, new_args, is_signed), tl.void) + + def device_assert(self, cond: TensorTy, msg: str, mask: Optional[TensorTy]) -> TensorTy: + if not self.builder.options.debug: + return + if mask is not None: + cond = self.or_(cond, self.not_(mask)) + return self.tensor(self.builder.create_assert(cond.handle, msg), tl.void) + + def assume(self, cond) -> TensorTy: + return self.tensor(self.builder.create_assume(cond.handle), tl.void) + + def _convert_elem_to_ir_value(self, elem, require_i64): + if isinstance(elem, int): + elem = tl.constexpr(elem) + if isinstance(elem, tl.constexpr): + if isinstance(elem.value, bool): + return self.builder.get_int1(elem.value) + if require_i64: + assert -2**63 <= elem.value < 2**63, f"Block pointers only support 64 bit `shape/strides`, " \ + f"got a value {elem.value} which is out of the range" + return self.builder.get_int64(elem.value) + else: + assert -2**31 <= elem.value < 2**31, f"Block pointers only support 32 bit `offsets/block_shape`, " \ + f"got a value {elem.value} which is out of the range" + return self.builder.get_int32(elem.value) + elif isinstance(elem, tl.tensor): + assert elem.numel.value == 1, "Expected a scalar in shape/strides/offsets" + assert elem.dtype.is_int(), "Expected an integer scalar type in shape/strides/offsets" + if elem.dtype != tl.int64 and require_i64: + return self.builder.create_int_cast(elem.handle, self.builder.get_int64_ty(), + elem.dtype.is_int_signed()) + elif elem.dtype == tl.int64 and not require_i64: + assert False, "Block pointers only support 32 bit `offsets/block_shape`, " \ + "add a `.to(tl.int32)` or use regular indexing for 64 bit support" + return elem.handle + assert False, f"Unsupported element type in shape/strides/offsets: {type(elem)}" + + def _convert_to_ir_values(self, list_like, require_i64=True): + if hasattr(list_like, "__iter__"): + return [self._convert_elem_to_ir_value(elem, require_i64) for elem in list_like] + return [self._convert_elem_to_ir_value(list_like, require_i64)] + + def make_block_ptr(self, base: TensorTy, shape, strides, offsets, block_shape, order) -> TensorTy: + # Convert dynamic arguments to IR values + # NOTES(Chenggang): current `shape/strides` are `int64_t`, while `offsets/block_shape` are `int32_t` + shape = self._convert_to_ir_values(shape) + strides = self._convert_to_ir_values(strides) + offsets = self._convert_to_ir_values(offsets, require_i64=False) + + # Check `base` type + if not base.type.is_ptr() or base.type.element_ty.is_block(): + raise ValueError("Expected `base` to be a pointer type (but not a block pointer type or others)") + + # Treat `pointer_type` as `pointer_type` + if base.type.element_ty == tl.int1: + base = self.cast(base, tl.pointer_type(tl.int8, base.type.address_space)) + + # Check whether `block_shape` is static + if not hasattr(block_shape, "__iter__"): + block_shape = [block_shape] + block_shape = [elem.value if isinstance(elem, tl.constexpr) else elem for elem in block_shape] + assert all(isinstance(elem, int) and -2**31 <= elem < 2**31 for elem in block_shape), \ + "Expected a list of constant integers (`int32_t` range) in `block_shape`" + + # Check `order` + if not hasattr(order, "__iter__"): + order = [order] + order = [elem.value if isinstance(elem, tl.constexpr) else elem for elem in order] + assert sorted(order) == list(range(len(order))), "Expected a permutation of (0, 1, ..., len(order)-1) in order" + + # Must have same length + assert all(len(block_shape) == len(list_like) for list_like in [shape, strides, offsets, order]), \ + "Expected shape/strides/offsets/block_shape to have the same length" + + # Build value, the type is: + # `pointer_type>` in Python + # `tt.ptr>` in MLIR + handle = self.builder.create_make_block_ptr(base.handle, shape, strides, offsets, block_shape, order) + return self.tensor(handle, tl.pointer_type(tl.block_type(base.type.element_ty, block_shape))) + + def advance(self, base: TensorTy, offsets) -> TensorTy: + # Convert dynamic offsets to IR values + offsets = self._convert_to_ir_values(offsets, require_i64=False) + + # Advanced block pointer type is the same as before + return self.tensor(self.builder.create_advance(base.handle, offsets), base.type) + + def make_tensor_descriptor(self, base: TensorTy, shape: List[TensorTy], strides: List[TensorTy], + block_shape: List[tl.constexpr], padding_option: str = "zero") -> tl.tensor_descriptor: + ndim = len(shape) + if not (1 <= ndim <= 5): + raise ValueError(f"Expected 1 <= ndim <= 5 but got {ndim} dimensions") + if len(strides) != ndim: + raise ValueError(f"Expected {ndim} strides but got {len(strides)}") + if len(block_shape) != ndim: + raise ValueError(f"Expected block_shape to have {ndim} dimensions but got {len(strides)}") + assert isinstance(base.dtype, tl.pointer_type) + elem_size = base.dtype.element_ty.primitive_bitwidth // 8 + contig_dim_size = tl._unwrap_if_constexpr(block_shape[-1]) + if contig_dim_size * elem_size < 16: + raise ValueError( + f"Descriptor block shape must have at least 16 bytes in the last dimension, but got {contig_dim_size} * {elem_size} = {contig_dim_size * elem_size} bytes" + ) + + last_stride = tl._unwrap_if_constexpr(strides[-1]) + if last_stride != 1: + raise ValueError(f"Tensor descriptor last dim must be 1 but got {last_stride}") + + shape = [self.make_scalar(x, tl.int32) for x in shape] + strides = [self.make_scalar(tl._unwrap_if_constexpr(x), tl.int64) for x in strides] + + # Check whether `block_shape` is static + block_shape = tl._unwrap_shape(block_shape) + + assert isinstance(base.type, tl.pointer_type) + type = tl.block_type(base.type.element_ty, block_shape) + base_handle = base.handle + is_signed_int = base.type.element_ty.is_int_signed() + + padding = self._str_to_padding_option(padding_option) + + if base.type.element_ty.is_int() and padding == ir.PADDING_OPTION.PAD_NAN: + raise ValueError("Padding option `nan` is not supported for integer blocks") + + handle = self.builder.create_make_tensor_descriptor(base_handle, [s.handle for s in shape], + [s.handle for s in strides], block_shape, is_signed_int, + padding) + return tl.tensor_descriptor(handle, shape, strides, type) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/language/standard.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/language/standard.py new file mode 100644 index 0000000000000000000000000000000000000000..b1dd327bb9947c0c70786912c70863db6c8a905f --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/language/standard.py @@ -0,0 +1,536 @@ +from __future__ import annotations + +from ..runtime.jit import jit, constexpr_function +from . import core +from . import math + +# constexpr utilities + + +@constexpr_function +def _log2(i): + log2 = 0 + n = i + while n > 1: + n >>= 1 + log2 += 1 + return log2 + + +@constexpr_function +def _is_power_of_two(i): + return (i & (i - 1)) == 0 and i != 0 + + +_get_int_dtype = constexpr_function(core.get_int_dtype) + +# ----------------------- +# Standard library +# ----------------------- + + +@core._tensor_member_fn +@jit +def cdiv(x, div): + """ + Computes the ceiling division of :code:`x` by :code:`div` + + :param x: the input number + :type x: Block + :param div: the divisor + :type div: Block + """ + return (x + (div - 1)) // div + + +@core._tensor_member_fn +@jit +@math._add_math_1arg_docstr("sigmoid") +def sigmoid(x): + return 1 / (1 + math.exp(-x)) + + +@core._tensor_member_fn +@jit +@math._add_math_1arg_docstr("softmax") +def softmax(x, dim=None, keep_dims=False, ieee_rounding=False): + if dim is None: + _dim: core.constexpr = 0 + else: + _dim: core.constexpr = dim + z = x - max(x, _dim, keep_dims=keep_dims) + num = math.exp(z) + den = sum(num, _dim, keep_dims=keep_dims) + return math.fdiv(num, den, ieee_rounding) + + +@core._tensor_member_fn +@jit +def ravel(x, can_reorder=False): + """ + Returns a contiguous flattened view of :code:`x`. + + :param x: the input tensor + :type x: Block + """ + return core.reshape(x, [x.numel], can_reorder=can_reorder) + + +@jit +def swizzle2d(i, j, size_i, size_j, size_g): + """ + Transforms the indices of a row-major `size_i * size_j` matrix into + the indices of a column-major matrix for each group of `size_g` rows. + + For example, for :code:`size_i = size_j = 4` and :code:`size_g = 2`, it will + transform :: + + [[0 , 1 , 2 , 3 ], + [4 , 5 , 6 , 7 ], + [8 , 9 , 10, 11], + [12, 13, 14, 15]] + + into :: + + [[0, 2, 4 , 6 ], + [1, 3, 5 , 7 ], + [8, 10, 12, 14], + [9, 11, 13, 15]] + """ + # "unrolled index in array" + ij = i * size_j + j + # number of elements in `size_g` groups + # of `size_j` columns + size_gj = size_g * size_j + # index of the group in which (i,j) is + group_id = ij // size_gj + # row-index of the first element of this group + off_i = group_id * size_g + # last group may have fewer rows + size_g = core.minimum(size_i - off_i, size_g) + # linear index with respect to the first element in this group + ij = ij % size_gj + # new row and column indices + new_i = off_i + ij % size_g + new_j = ij // size_g + return new_i, new_j + + +@jit +def zeros(shape, dtype): + """ + Returns a tensor filled with the scalar value 0 for the given :code:`shape` and :code:`dtype`. + + :param shape: Shape of the new array, e.g., (8, 16) or (8, ) + :type shape: tuple of ints + :param dtype: Data-type of the new array, e.g., :code:`tl.float16` + :type dtype: DType + """ + return core.full(shape, 0, dtype) + + +@jit +def zeros_like(input): + """ + Returns a tensor of zeros with the same shape and type as a given tensor. + + :param input: input tensor + :type input: Tensor + """ + return zeros(input.shape, input.dtype) + + +# max and argmax + + +@jit +def _argmax_combine(value1, index1, value2, index2, tie_break_left): + if tie_break_left: + tie = value1 == value2 and index1 < index2 + else: + tie = False + gt = value1 > value2 or tie + v_ret = core.where(gt, value1, value2) + i_ret = core.where(gt, index1, index2) + return v_ret, i_ret + + +@jit +def _argmax_combine_tie_break_left(value1, index1, value2, index2): + return _argmax_combine(value1, index1, value2, index2, True) + + +@jit +def _argmax_combine_tie_break_fast(value1, index1, value2, index2): + return _argmax_combine(value1, index1, value2, index2, False) + + +@jit +def _elementwise_max(a, b): + return core.maximum(a, b) + + +@core._tensor_member_fn +@jit +@core._add_reduction_docstr("maximum", return_indices_arg="return_indices", + tie_break_arg="return_indices_tie_break_left") +def max(input, axis=None, return_indices=False, return_indices_tie_break_left=True, keep_dims=False): + input = core._promote_bfloat16_to_float32(input) + if return_indices: + if return_indices_tie_break_left: + return core._reduce_with_indices(input, axis, _argmax_combine_tie_break_left, keep_dims=keep_dims) + else: + return core._reduce_with_indices(input, axis, _argmax_combine_tie_break_fast, keep_dims=keep_dims) + else: + if core.constexpr(input.dtype.primitive_bitwidth) < core.constexpr(32): + if core.constexpr(input.dtype.is_floating()): + input = input.to(core.float32) + else: + assert input.dtype.is_int(), "Expecting input to be integer type" + input = input.to(core.int32) + return core.reduce(input, axis, _elementwise_max, keep_dims=keep_dims) + + +@core._tensor_member_fn +@jit +@core._add_reduction_docstr("maximum index", tie_break_arg="tie_break_left") +def argmax(input, axis, tie_break_left=True, keep_dims=False): + (_, ret) = max(input, axis, return_indices=True, return_indices_tie_break_left=tie_break_left, keep_dims=keep_dims) + return ret + + +# min and argmin + + +@jit +def _argmin_combine(value1, index1, value2, index2, tie_break_left): + if tie_break_left: + tie = value1 == value2 and index1 < index2 + else: + tie = False + lt = value1 < value2 or tie + value_ret = core.where(lt, value1, value2) + index_ret = core.where(lt, index1, index2) + return value_ret, index_ret + + +@jit +def _argmin_combine_tie_break_left(value1, index1, value2, index2): + return _argmin_combine(value1, index1, value2, index2, True) + + +@jit +def _argmin_combine_tie_break_fast(value1, index1, value2, index2): + return _argmin_combine(value1, index1, value2, index2, False) + + +@jit +def _elementwise_min(a, b): + return core.minimum(a, b) + + +@core._tensor_member_fn +@jit +@core._add_reduction_docstr("minimum", return_indices_arg="return_indices", + tie_break_arg="return_indices_tie_break_left") +def min(input, axis=None, return_indices=False, return_indices_tie_break_left=True, keep_dims=False): + input = core._promote_bfloat16_to_float32(input) + if return_indices: + if return_indices_tie_break_left: + return core._reduce_with_indices(input, axis, _argmin_combine_tie_break_left, keep_dims=keep_dims) + else: + return core._reduce_with_indices(input, axis, _argmin_combine_tie_break_fast, keep_dims=keep_dims) + else: + if core.constexpr(input.dtype.primitive_bitwidth) < 32: + if core.constexpr(input.dtype.is_floating()): + input = input.to(core.float32) + else: + assert input.dtype.is_int(), "Expecting input to be integer type" + input = input.to(core.int32) + return core.reduce(input, axis, _elementwise_min, keep_dims=keep_dims) + + +@core._tensor_member_fn +@jit +@core._add_reduction_docstr("minimum index", tie_break_arg="tie_break_left") +def argmin(input, axis, tie_break_left=True, keep_dims=False): + _, ret = min(input, axis, return_indices=True, return_indices_tie_break_left=tie_break_left, keep_dims=keep_dims) + return ret + + +@jit +def _sum_combine(a, b): + return a + b + + +# sum + + +@constexpr_function +def _pick_sum_dtype(in_dtype, dtype): + if dtype is not None: + return dtype + + # For integer bitwidths less than 32, pick int32 with the same sign to + # avoid overflow. + out_dtype = None + if in_dtype.is_int_signed(): + out_dtype = core.int32 if in_dtype.int_bitwidth < 32 else None + elif in_dtype.is_int_unsigned(): + out_dtype = core.uint32 if in_dtype.int_bitwidth < 32 else None + return out_dtype + + +@core._tensor_member_fn +@jit +@core._add_reduction_docstr("sum", dtype_arg="dtype") +def sum(input, axis=None, keep_dims=False, dtype: core.constexpr = None): + # Pick a default dtype for the reduction if one was not specified. + out_dtype: core.constexpr = _pick_sum_dtype(input.dtype, dtype) + + if out_dtype is not None: + input = input.to(out_dtype) + return core.reduce(input, axis, _sum_combine, keep_dims=keep_dims) + + +@jit +def _xor_combine(a, b): + return a ^ b + + +# xor sum + + +@core._tensor_member_fn +@jit +@core._add_reduction_docstr("xor sum") +def xor_sum(input, axis=None, keep_dims=False): + core.static_assert(input.type.scalar.is_int(), "xor_sum only supported for integers") + return core.reduce(input, axis, _xor_combine, keep_dims=keep_dims) + + +# or reduction + + +@jit +def _or_combine(x, y): + return x | y + + +@core._tensor_member_fn +@jit +@core._add_reduction_docstr("reduce_or") +def reduce_or(input, axis, keep_dims=False): + core.static_assert(input.type.scalar.is_int(), "reduce_or only supported for integers") + return core.reduce(input, axis, _or_combine, keep_dims=keep_dims) + + +# cumsum + + +@core._tensor_member_fn +@jit +@core._add_scan_docstr("cumsum", dtype_arg="dtype") +def cumsum(input, axis=0, reverse=False, dtype: core.constexpr = None): + # todo rename this to a generic function name + + input = core._promote_bfloat16_to_float32(input) + out_dtype: core.constexpr = _pick_sum_dtype(input.dtype, dtype) + + if out_dtype is not None: + input = input.to(out_dtype) + + return core.associative_scan(input, axis, _sum_combine, reverse) + + +# cumprod + + +@jit +def _prod_combine(a, b): + return a * b + + +@core._tensor_member_fn +@jit +@core._add_scan_docstr("cumprod") +def cumprod(input, axis=0, reverse=False): + # todo rename this to a generic function name + input = core._promote_bfloat16_to_float32(input) + return core.associative_scan(input, axis, _prod_combine, reverse) + + +# sort + + +@jit +def _indicator(n_dims: core.constexpr, j: core.constexpr): + ar = core.arange(0, 2) + ar = core.reshape(ar, [1] * (n_dims - j - 1) + [2] + [1] * j) + return ar + + +@jit +def _compare_and_swap(x, flip, i: core.constexpr): + # compare-and-swap on the ith *innermost* dimension + n_dims: core.constexpr = _log2(x.numel) + + # flip along middle dimension (the bitwise XORs will be optimised away): + idtype = _get_int_dtype(bitwidth=x.dtype.primitive_bitwidth, signed=True) + ix = x.to(idtype, bitcast=True) + iy = ix ^ xor_sum(ix, n_dims - 1 - i, True) + y = iy.to(x.dtype, bitcast=True) + + # determines whether we are in the right (rather than left) position along the axis: + is_right = _indicator(n_dims, i) + + # conditional swap: + ret = core.where((x > y) != (flip ^ is_right), y, x) + return ret + + +@jit +def _bitonic_merge_hypercube(x, stage: core.constexpr, order: core.constexpr): + ''' + order_type 0 == ascending + order_type 1 == descending + order_type 2 == alternating + ''' + # flip denotes whether to re-arrange sub-sequences of elements in ascending or + # descending order. + # if flip = 00000000... then all elements will be re-arranged ascendingly at this stage + # if flip = 00110011... then all the elements will be re-arranged alternatingly (with + # a stride of 2) at this stage + if order == 2: + flip = _indicator(_log2(x.numel), stage) + else: + flip = order + # perform `stage` rounds of `compare-and-swap` + for i in core.static_range(stage): + x = _compare_and_swap(x, flip, stage - 1 - i) + return x + + +@jit +def _bitonic_merge(x, stage: core.constexpr, order: core.constexpr, n_dims: core.constexpr): + h = core.reshape(x, [2] * _log2(x.numel)) + h = _bitonic_merge_hypercube(h, stage, order) + x = core.reshape(h, x.shape) + return x + + +@jit +def sort_impl(x, k: core.constexpr = None, dim: core.constexpr = None, descending: core.constexpr = core.CONSTEXPR_0): + """ + Sorts a tensor along a specified dimension. + + :param x: The input tensor to be sorted. + :type x: Tensor + :param dim: The dimension along which to sort the tensor. If None, the tensor is sorted along the last dimension. Currently, only sorting along the last dimension is supported. + :type dim: int, optional + :param k: the number of top elements to select. If none, assume k = x.shape[dim] + :type k: int, optional + :param descending: If set to True, the tensor is sorted in descending order. If set to False, the tensor is sorted in ascending order. + :type descending: bool, optional + """ + # handle default dimension or check that it is the most minor dim + _dim: core.constexpr = len(x.shape) - 1 if dim is None else dim + core.static_assert(_dim == len(x.shape) - 1, "only minor dimension is currently supported") + + log_n: core.constexpr = _log2(x.shape[_dim]) + log_k: core.constexpr = log_n if k is None else _log2(k) + + n_dims: core.constexpr = _log2(x.numel) + + # reshape to hypercube: + h = core.reshape(x, [2] * n_dims if n_dims else [1]) + + # run first log_k bitonic sort iterations: + for i in core.static_range(1, log_k + 1): + h = _bitonic_merge_hypercube(h, i, 2 if i < log_n else descending) + + # select top k elements using bitonic top-k + # https://www.doc.ic.ac.uk/~hlgr/pdfs/MassivelyParallelTopK.pdf + for i in core.static_range(log_k + 1, log_n + 1): + h = max(h, axis=(_log2(h.numel) - 1 - log_k)) if descending else min(h, axis=(_log2(h.numel) - 1 - log_k)) + h = _bitonic_merge_hypercube(h, log_k, 2 if i < log_n else descending) + + # reshape back: + x = core.reshape(h, x.shape[:-1] + [2**log_k]) + return x + + +@jit +def sort(x, dim: core.constexpr = None, descending: core.constexpr = core.CONSTEXPR_0): + return sort_impl(x, dim=dim, descending=descending) + + +@jit +def topk(x, k: core.constexpr, dim: core.constexpr = None): + return sort_impl(x, k=k, dim=dim, descending=True) + + +@jit +def bitonic_merge(x, dim: core.constexpr = None, descending: core.constexpr = core.CONSTEXPR_0): + # handle default dimension or check that it is the most minor dim + _dim: core.constexpr = len(x.shape) - 1 if dim is None else dim + core.static_assert(_dim == len(x.shape) - 1, "only minor dimension is currently supported") + n_dims: core.constexpr = _log2(x.shape[-1]) + return _bitonic_merge(x, n_dims, descending, n_dims) + + +@constexpr_function +def _get_flip_dim(dim, shape): + if dim is None: + dim = len(shape) - 1 + if dim < 0: # flip doesn't work if dim < 0 because the xor-swap for loop will start/end at the wrong index + dim += len(shape) + return dim + + +@core._tensor_member_fn +@jit +def flip(x, dim=None): + """ + Flips a tensor `x` along the dimension `dim`. + + :param x: the first input tensor + :type x: Block + :param dim: the dimension to flip along + :type dim: int + """ + core.static_assert(-len(x.shape) <= dim and dim < len(x.shape)) + _dim: core.constexpr = _get_flip_dim(dim, x.shape) + core.static_assert(_is_power_of_two(x.shape[_dim])) + steps: core.constexpr = _log2(x.shape[_dim]) + + # reshape the swap dimension to (2, 2, ..., 2) + idtype = _get_int_dtype(bitwidth=x.dtype.primitive_bitwidth, signed=True) + y = core.reshape(x.to(idtype, bitcast=True), x.shape[:_dim] + [2] * steps + x.shape[_dim + 1:]) + for i in core.static_range(steps): + y = y ^ xor_sum(y, _dim + i, True) + x = core.reshape(y, x.shape).to(x.dtype, bitcast=True) + return x + + +@jit +def interleave(a, b): + """ + Interleaves the values of two tensors along their last dimension. The two tensors must have the same shape. + Equivalent to `tl.join(a, b).reshape(a.shape[:-1] + [2 * a.shape[-1]])` + + :param a: The first input tensor. + :type a: Tensor + :param b: The second input tensor. + :type b: Tensor + """ + c = core.join(a, b) + + if len(c.shape) == 1: + # We must have interleaved two scalars. + return c + else: + # This `else` is necessary because Triton's AST parser doesn't + # understand that if we take the `if` above we definitely don't run this + # `else`. + return core.reshape(c, c.shape[:-2] + [2 * c.shape[-2]]) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/language/target_info.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/language/target_info.py new file mode 100644 index 0000000000000000000000000000000000000000..2c1a277f04d5dd79bf506a49f8aa8d2f0e6d8e90 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/language/target_info.py @@ -0,0 +1,54 @@ +from triton.runtime import driver +from triton.runtime.jit import constexpr_function + +__all__ = ["current_target"] + + +def current_target(): + try: + active_driver = driver.active + except RuntimeError: + # If there is no active driver, return None + return None + return active_driver.get_current_target() + + +current_target.__triton_builtin__ = True + + +@constexpr_function +def is_cuda(): + target = current_target() + return target is not None and target.backend == "cuda" + + +@constexpr_function +def cuda_capability_geq(major, minor=0): + """ + Determines whether we have compute capability >= (major, minor) and + returns this as a constexpr boolean. This can be used for guarding + inline asm implementations that require a certain compute capability. + """ + target = current_target() + if target is None or target.backend != "cuda": + return False + assert isinstance(target.arch, int) + return target.arch >= major * 10 + minor + + +@constexpr_function +def is_hip(): + target = current_target() + return target is not None and target.backend == "hip" + + +@constexpr_function +def is_hip_cdna3(): + target = current_target() + return target is not None and target.arch == "gfx942" + + +@constexpr_function +def is_hip_cdna4(): + target = current_target() + return target is not None and target.arch == "gfx950" diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/profiler/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/profiler/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..efbd85819526b7556809c6927a02512835c830d7 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/profiler/__init__.py @@ -0,0 +1,12 @@ +# ruff: noqa +from .scope import scope, cpu_timed_scope, enter_scope, exit_scope +from .state import state, enter_state, exit_state +from .profile import ( + start, + activate, + deactivate, + finalize, + profile, + DEFAULT_PROFILE_NAME, +) +from . import context, specs, mode diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/profiler/context.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/profiler/context.py new file mode 100644 index 0000000000000000000000000000000000000000..f7dff1f071edb28ef11f08d2ea44c34915d103da --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/profiler/context.py @@ -0,0 +1,18 @@ +from typing import Optional +from triton._C.libproton import proton as libproton +from .flags import flags + + +def depth(session: Optional[int] = 0) -> Optional[int]: + """ + Get the depth of the context. + + Args: + session (int): The session ID of the profiling session. Defaults to 0. + + Returns: + depth (int or None): The depth of the context. If profiling is off, returns None. + """ + if not flags.profiling_on: + return None + return libproton.get_context_depth(session) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/profiler/flags.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/profiler/flags.py new file mode 100644 index 0000000000000000000000000000000000000000..bef762101454284ae5e183665aaf950260cb0b25 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/profiler/flags.py @@ -0,0 +1,28 @@ +""" +Centralized, process-local flags with a minimal interface (no environment variables). + +Usage: + from triton.profiler.flags import flags + + # Toggle + flags.profiling_on = True + flags.instrumentation_on = False + + # Check + if flags.command_line: + ... +""" +from dataclasses import dataclass + + +@dataclass +class ProfilerFlags: + # Whether profiling is enabled. Default is False. + profiling_on: bool = False + # Whether instrumentation is enabled. Default is False. + instrumentation_on: bool = False + # Whether the script is run from the command line. Default is False. + command_line: bool = False + + +flags = ProfilerFlags() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/profiler/hooks/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/profiler/hooks/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5ba3ff539527cd54e488828e92db7c4f7aaed882 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/profiler/hooks/__init__.py @@ -0,0 +1,4 @@ +# ruff: noqa +from .hook import HookManager +from .instrumentation import InstrumentationHook +from .launch import LaunchHook diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/profiler/hooks/hook.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/profiler/hooks/hook.py new file mode 100644 index 0000000000000000000000000000000000000000..a672722a1279f68cf80d5fde3d0b654100611d7a --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/profiler/hooks/hook.py @@ -0,0 +1,128 @@ +from triton.compiler import LazyDict +from abc import abstractmethod +from typing import Dict, Any, Optional +from collections import defaultdict +import triton.knobs as knobs + + +class Hook: + priority: int = 0 + + @abstractmethod + def init_handle(self, module: Any, function: Any, name: str, metadata_group: Dict[str, str], + hash: str) -> None: # noqa: D401 + raise NotImplementedError + + @abstractmethod + def enter(self, metadata: LazyDict) -> None: + raise NotImplementedError + + @abstractmethod + def exit(self, metadata: LazyDict) -> None: + raise NotImplementedError + + @abstractmethod + def activate(self) -> None: + raise NotImplementedError + + @abstractmethod + def deactivate(self) -> None: + raise NotImplementedError + + +class HookManager: + # active hooks + active_hooks: list[Hook] = [] + # session_id -> (hook_type -> active) + session_hooks: Dict[int, Dict[Hook, bool]] = defaultdict(lambda: defaultdict(bool)) + + @staticmethod + def init_handle(module: Any, function: Any, name: str, metadata_group: Dict[str, str], hash: str) -> None: + for hook in HookManager.active_hooks: + hook.init_handle(module, function, name, metadata_group, hash) + + @staticmethod + def enter(metadata: LazyDict) -> None: + for hook in HookManager.active_hooks: + hook.enter(metadata) + + @staticmethod + def exit(metadata: LazyDict) -> None: + # It's important to reverse the order of hooks so that we keep the first in last out order + for hook in reversed(HookManager.active_hooks): + hook.exit(metadata) + + @staticmethod + def activate(session: Optional[int] = None) -> None: + if session is None: + sessions = HookManager.session_hooks.keys() + else: + sessions = [session] + + for session in sessions: + for hook in HookManager.session_hooks[session]: + if hook not in HookManager.active_hooks: + hook.activate() + HookManager.active_hooks.append(hook) + HookManager.session_hooks[session][hook] = True + # Sort active_hooks by priority + HookManager.active_hooks.sort(key=lambda x: x.priority, reverse=True) + + @staticmethod + def deactivate(session: Optional[int] = None) -> None: + if session is None: + sessions = HookManager.session_hooks.keys() + else: + sessions = [session] + + deactivated_hooks = set() + for session in sessions: + for hook in HookManager.session_hooks[session]: + if hook in HookManager.active_hooks: + deactivated_hooks.add(hook) + HookManager.session_hooks[session][hook] = False + + # Check if any other sessions rely on this hook + for hook in deactivated_hooks: + if not any(session_hooks[hook] for session_hooks in HookManager.session_hooks.values()): + hook.deactivate() + HookManager.active_hooks.remove(hook) + + @staticmethod + def register(hook: Hook, session: int) -> None: + HookManager.session_hooks[session][hook] = True + if hook not in HookManager.active_hooks: + hook.activate() + HookManager.active_hooks.append(hook) + # Sort active_hooks by priority + HookManager.active_hooks.sort(key=lambda x: x.priority, reverse=True) + + # Register the heads + knobs.runtime.kernel_load_end_hook.add(HookManager.init_handle) + knobs.runtime.launch_enter_hook.add(HookManager.enter) + knobs.runtime.launch_exit_hook.add(HookManager.exit) + + @staticmethod + def unregister(session: Optional[int] = None) -> None: + if session is not None and session not in HookManager.session_hooks: + return + + if session is None: + for hook in HookManager.active_hooks: + hook.deactivate() + HookManager.active_hooks.clear() + HookManager.session_hooks.clear() + else: + popped_hooks = HookManager.session_hooks.pop(session) + # Deactivate hooks that are not used by any other session + for hook, active in popped_hooks.items(): + if not active: + continue + if not any(session_hooks[hook] for session_hooks in HookManager.session_hooks.values()): + hook.deactivate() + HookManager.active_hooks.remove(hook) + # Unregister the heads + if not HookManager.active_hooks: + knobs.runtime.kernel_load_end_hook.remove(HookManager.init_handle) + knobs.runtime.launch_enter_hook.remove(HookManager.enter) + knobs.runtime.launch_exit_hook.remove(HookManager.exit) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/profiler/hooks/instrumentation.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/profiler/hooks/instrumentation.py new file mode 100644 index 0000000000000000000000000000000000000000..aac27ad1887339d44c3d16e47ce48c456b474d4c --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/profiler/hooks/instrumentation.py @@ -0,0 +1,348 @@ +from typing import Dict, Optional, Union, Any + +import triton +from triton._C.libtriton import ir as triton_ir +from triton._C.libtriton import proton as triton_proton +from triton._C.libtriton import amd as triton_amd +from triton._C.libtriton import nvidia as triton_nvidia +from triton._C.libtriton import passes as triton_passes +from triton._C.libproton import proton as libproton +from triton.compiler import LazyDict +from triton.runtime._allocation import set_profile_allocator, NullAllocator +from triton.backends import backends + +from .hook import Hook +from ..flags import flags +from .. import mode + +# TODO(fywkevin): add support for major.minor +VERSION = 1 + + +class CudaAllocator: + + def __init__(self, instrumentation_hook): + self.instrumentation_hook = instrumentation_hook + + def __call__(self, size: int, alignment: int, stream: Optional[int]): + if alignment != self.instrumentation_hook.profile_buffer_alignment: + raise RuntimeError( + f"Alignment mismatch: {alignment} != {self.instrumentation_hook.profile_buffer_alignment}") + aligned_size = (size + alignment - 1) // alignment * alignment + # Note: profile_buffer_size may be smaller than the aligned size if the kernel launches many blocks + # and the host CPU cannot store all profiling data in memory. This streaming mode is not yet implemented. + # In the future, we should support copying data incrementally from device to host to enable + # more efficient profiling data processing, rather than relying solely on post-processing. + aligned_size = max(aligned_size, self.instrumentation_hook.profile_buffer_size) + + # Create the buffer + import torch + buffer = torch.empty((aligned_size, ), dtype=torch.uint8, device="cuda") + self.instrumentation_hook.buffer = buffer + return buffer + + +class Instrumentation: + + def __init__(self, ir_map: Dict[str, Any]): + self.manager = ir_map + + def register(self, ir: str, func): + if ir in self.manager: + raise RuntimeError(f"IR already registered: {ir}") + self.manager[ir] = func + + def patch(self, ir: str, pm, context): + self.load_dialects(context) + if ir in self.manager: + self.manager[ir](pm) + + def load_dialects(self, ctx): + triton_proton.load_dialects(ctx) + + +def _interpret_mode(mode_obj: Union[str, mode.InstrumentationMode]) -> mode.InstrumentationMode: + if isinstance(mode_obj, mode.InstrumentationMode): + return mode_obj + elif not mode_obj: + mode_obj = "default" + + parts = mode_obj.split(":") + mode_name = parts[0] + opts: Dict[str, str] = {} + for opt in parts[1:]: + if "=" in opt: + key, val = opt.split("=", 1) + opts[key] = val + else: + raise ValueError(f"Malformed instrumentation option: '{opt}'") + + # Get option values or empty strings + options = { + "metric_type": opts.get("metric_type", "cycle"), "buffer_type": opts.get("buffer_type", "shared"), + "buffer_strategy": opts.get("buffer_strategy", "circular"), "buffer_size": int(opts.get("buffer_size", "0")), + "granularity": opts.get("granularity", "warp"), "sampling_strategy": opts.get("sampling_strategy", "none"), + "sampling_options": opts.get("sampling_options", ""), "optimizations": opts.get("optimizations", "") + } + + # Helper function to validate and map options to their enum values + def get_option_value(opt_name, mapping): + value = options[opt_name] + if value and value not in mapping: + raise ValueError(f"Unknown {opt_name}: {value}") + return mapping[value] if value else value + + # Look up enum values for each option + options["metric_type"] = get_option_value("metric_type", mode.metric_types) + options["buffer_type"] = get_option_value("buffer_type", mode.buffer_types) + options["buffer_strategy"] = get_option_value("buffer_strategy", mode.buffer_strategies) + options["granularity"] = get_option_value("granularity", mode.granularities) + options["sampling_strategy"] = get_option_value("sampling_strategy", mode.sampling_strategies) + + values = ([value.strip() + for value in options["optimizations"].split(",")] if len(options["optimizations"]) > 0 else []) + for value in values: + if value not in mode.optimizations: + raise ValueError(f"Unknown optimization: {value}") + options["optimizations"] = [mode.optimizations[value] for value in values] + + # Create the appropriate mode instance + if mode_name == "default": + return mode.Default(**options) + elif mode_name == "mma": + return mode.MMA(**options) + else: + raise ValueError(f"Unknown mode: {mode_obj}") + + +def _get_backend_name() -> str: + backend = triton.runtime.driver.active.get_current_target().backend + if backend == "cuda": + return "nvidia" + elif backend == "hip": + return "amd" + else: + raise RuntimeError(f"Unsupported backend: {backend}") + + +class InstrumentationHook(Hook): + priority: int = 0 + # It's important to note that only one instance of the instrumentation hook can be active at a time. + active_count: int = 0 + enable_host_buffer: bool = False + host_buffer: Optional[Any] = None + # FIXME(fywkevin): change to a more reasonable value after we have support for periodic buffer dumping. + profile_buffer_size: int = 1 + profile_buffer_alignment: int = 128 + + def __init__(self, mode_obj: Union[None, str, mode.InstrumentationMode]): + # Mapping of function objects to their scope ID pairs + self.mode: mode.InstrumentationMode = _interpret_mode(mode_obj) + + self.allocator = CudaAllocator(self) + self.buffer = None + self.metadata_path: Dict[Any, Optional[str]] = {} + + def activate(self): + if InstrumentationHook.active_count > 0: + raise RuntimeError("Only one instance of the instrumentation hook can be active at a time.") + + InstrumentationHook.active_count += 1 + + flags.instrumentation_on = True + + device = triton.runtime.driver.active.get_current_device() + max_shared_mem = triton.runtime.driver.active.utils.get_device_properties(device)["max_shared_mem"] + backend_name = _get_backend_name() + + def to_llvmir_passes(pm): + is_long_clk = False if mode.Optimize.CLOCK32 in self.mode.optimizations else True + triton_proton.add_convert_proton_to_protongpu(pm, self.mode.metric_type, self.mode.sampling_strategy, + self.mode.sampling_options, self.mode.granularity, + self.mode.buffer_strategy, self.mode.buffer_type, + self.mode.buffer_size, max_shared_mem, + self.profile_buffer_size, self.profile_buffer_alignment, + is_long_clk) + triton_passes.common.add_cse(pm) + + if mode.Optimize.SCHED_STORES in self.mode.optimizations: + triton_proton.add_schedule_buffer_store(pm) + + triton_proton.add_allocate_proton_shared_memory(pm) + + if mode.Optimize.SCHED_BARRIERS in self.mode.optimizations and backend_name == "amd": + triton_proton.add_sched_barriers(pm) + + def to_llvm_passes(pm): + triton_proton.add_allocate_proton_global_scratch_buffer(pm) + if backend_name == "nvidia": + triton_proton.add_convert_proton_nvidia_gpu_to_llvm(pm) + elif backend_name == "amd": + arch = triton.runtime.driver.active.utils.get_device_properties(device)["arch"].split(":")[0] + triton_proton.add_convert_proton_amd_gpu_to_llvm(pm, arch) + + backends[backend_name].compiler.instrumentation = Instrumentation({ + "ttgpuir_to_llvmir": + lambda pm: to_llvmir_passes(pm), + "llvmir_to_llvm": + lambda pm: to_llvm_passes(pm), + }) + + # Set up the profiling allocator + set_profile_allocator(self.allocator) + + # Set the instrumentation mode + triton.knobs.compilation.instrumentation_mode = str(self.mode) + + def deactivate(self): + if InstrumentationHook.active_count == 0: + return + + InstrumentationHook.active_count -= 1 + + backend_name = _get_backend_name() + + # No instrumentation passes are registered anymore + backends[backend_name].compiler.instrumentation = {} + + # No runtime instrumentation hook is active anymore + flags.instrumentation_on = False + + # Restore the instrumentation mode + triton.knobs.compilation.instrumentation_mode = "" + + # Reset profile allocator + set_profile_allocator(NullAllocator()) + + # Reset host memory for external processing + InstrumentationHook.host_buffer = None + + # Reset the buffer reference + self.buffer = None + + def init_handle(self, module: Any, function: Any, name: str, metadata_group: Dict[str, str], hash: str) -> None: + if not function: + return + + # Find the IR path in metadata + ir_path = next((path for key, path in metadata_group.items() if key.endswith(("ttgir"))), None) + metadata_path = next((path for key, path in metadata_group.items() if key.endswith(("json"))), None) + self.metadata_path[function] = metadata_path + + if ir_path: + context = triton_ir.context() + triton_ir.load_dialects(context) + backend_name = _get_backend_name() + if backend_name == "nvidia": + triton_nvidia.load_dialects(context) + elif backend_name == "amd": + triton_amd.load_dialects(context) + triton_proton.load_dialects(context) + module = triton_ir.parse_mlir_module(ir_path, context) + module.context = context + + scope_id_names = triton_proton.get_scope_id_names(module) + scope_id_parents = triton_proton.get_scope_id_parents(module) + libproton.init_function_metadata(function, name, scope_id_names, scope_id_parents, metadata_path) + else: + raise RuntimeError(f"IR path not found in metadata for function {function}") + + def _data_ptr(self) -> int: + return 0 if self.buffer is None else self.buffer.data_ptr() + + def enter(self, metadata: LazyDict) -> None: + func = metadata.data.get("function") + stream = metadata.data.get("stream") + alloc_size = 0 if self.buffer is None else self.buffer.element_size() * self.buffer.numel() + libproton.enter_instrumented_op(stream, func, self._data_ptr(), alloc_size) + if InstrumentationHook.enable_host_buffer: + InstrumentationHook.host_buffer = None + + def exit(self, metadata: LazyDict) -> None: + func = metadata.data.get("function") + stream = metadata.data.get("stream") + alloc_size = 0 if self.buffer is None else self.buffer.element_size() * self.buffer.numel() + libproton.exit_instrumented_op(stream, func, self._data_ptr(), alloc_size) + + if InstrumentationHook.enable_host_buffer: + self._populate_host_buffer(func) + + def _populate_host_buffer(self, function: Any) -> None: + if function and self.metadata_path[function]: + import torch + import struct + import json + + def encode_target(target: Dict[str, Any]) -> int: + #TODO(fywkevin): also account for `arch` + if target["backend"] == "cuda": + return 1 + elif target["backend"] == "hip": + return 2 + return 0 + + alloc_size = 0 if self.buffer is None else self.buffer.element_size() * self.buffer.numel() + sampled_warps = self.mode.sampling_options.strip().split(",") + data = {} + with open(self.metadata_path[function], 'r') as file: + data = json.load(file) + + device_type = encode_target(data["target"]) + scratch_mem_size = data["profile_scratch_size"] + total_unit = data["num_warps"] + uid_num = total_unit if self.mode.sampling_strategy == triton_proton.SAMPLING_STRATEGY.NONE else len( + sampled_warps) + block_num = int(alloc_size / scratch_mem_size) + + # Binary trace layout: + # +------------------+ + # | version | 4 bytes + # +------------------+ + # | header_offset | 4 bytes + # +------------------+ + # | header_size | 4 bytes + # +------------------+ + # | payload_offset | 4 bytes + # +------------------+ + # | payload_size | 4 bytes + # +------------------+ + # | device_type | 4 bytes + # +------------------+ + # | block_num | 4 bytes + # +------------------+ + # | total_unit | 4 bytes + # +------------------+ + # | scratch_mem_size | 4 bytes + # +------------------+ + # | uid_num | 4 bytes + # +------------------+ + # | | + # | uid_vec | uid_num * 4 bytes + # | | + # +------------------+ + # | | + # | payload | size_payload bytes + # | | + # +------------------+ + + is_all_warps = self.mode.sampling_options == "" and self.mode.granularity == triton_proton.GRANULARITY.WARP + if is_all_warps: + uid_vec = [i for i in range(total_unit)] + else: + uid_vec = [int(i) for i in sampled_warps] + + header_size = 40 + uid_num * 4 + header_offset = 4 + payload_offset = header_size + payload_size = alloc_size + header_values = [ + VERSION, header_offset, header_size, payload_offset, payload_size, device_type, block_num, total_unit, + scratch_mem_size, uid_num, *uid_vec + ] + header_bytes = struct.pack("I" * len(header_values), *header_values) + + InstrumentationHook.host_buffer = torch.empty(header_size + alloc_size, dtype=torch.uint8, device="cpu") + config_portion = InstrumentationHook.host_buffer[:header_size] + config_portion.copy_(torch.tensor(list(header_bytes), dtype=torch.uint8)) + data_portion = InstrumentationHook.host_buffer[header_size:].view_as(self.buffer) + data_portion.copy_(self.buffer.cpu()) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/profiler/hooks/launch.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/profiler/hooks/launch.py new file mode 100644 index 0000000000000000000000000000000000000000..0243c8b67f1adf07b409e11e18a66775f601f1b6 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/profiler/hooks/launch.py @@ -0,0 +1,49 @@ +from ..state import enter_state, exit_state +from triton.compiler import LazyDict +from .hook import Hook +from triton._C.libproton import proton as libproton +from contextvars import ContextVar + +COMPUTE_METADATA_SCOPE_NAME = "__proton_launch_metadata" + +op_name = ContextVar("op_name", default=None) +id = ContextVar("id", default=None) + + +class LaunchHook(Hook): + # Highest priority + priority = 100 + # This is a singleton class + _instance = None + flops_width = [8, 16, 32, 64] + metrics = [f"flops{width}" for width in flops_width] + ["bytes"] + ["flops"] + + def __init__(self): + pass + + def __new__(cls): + if cls._instance is None: + cls._instance = super(LaunchHook, cls).__new__(cls) + return cls._instance + + def init_handle(self, module, function, name: str, metadata_group: dict, hash: str) -> None: + pass + + def activate(self): + pass + + def deactivate(self): + pass + + def enter(self, metadata: LazyDict) -> None: + enter_state(COMPUTE_METADATA_SCOPE_NAME) + lazy_metadata = metadata.get() + exit_state() + fn_metrics = {k: lazy_metadata[k] for k in LaunchHook.metrics if k in lazy_metadata} + op_name.set(lazy_metadata["name"]) + id.set(libproton.record_scope()) + libproton.enter_op(id.get(), lazy_metadata["name"]) + libproton.add_metrics(id.get(), fn_metrics) + + def exit(self, metadata: LazyDict) -> None: + libproton.exit_op(id.get(), op_name.get()) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/profiler/language.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/profiler/language.py new file mode 100644 index 0000000000000000000000000000000000000000..2785938194ed0abd4de258a90df21280f64fc342 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/profiler/language.py @@ -0,0 +1,65 @@ +from triton.language import core as tl +from triton.language.core import builtin +from triton._C.libtriton import proton as triton_proton +from triton.language.semantic import TritonSemantic +from triton.experimental.gluon.language._semantic import GluonSemantic + +from .flags import flags + +_ALL_SEMANTICS = { + "triton": TritonSemantic, + "gluon": GluonSemantic, +} +""" +By default **only Gluon** semantic is enabled. +Instrumenting kernels written in Triton DSL is disable because Triton's higher-level IR undergoes +aggressive compiler rewrites (loop pipelining, instruction re-ordering, IR duplication, etc.). +These transformations can invalidate naïve instrumentation and lead to misleading results. +""" +_SEMANTICS = {_ALL_SEMANTICS["gluon"]} + + +def _check_supported_semantic(semantic): + if not isinstance(semantic, tuple(_SEMANTICS)): + raise TypeError(f"Unsupported semantic type: {type(semantic)}. " + f"Supported semantics are: {_SEMANTICS}") + + +def enable_semantic(semantic_name: str): + _SEMANTICS.add(_ALL_SEMANTICS[semantic_name]) + + +def disable_semantic(semantic_name: str): + _SEMANTICS.remove(_ALL_SEMANTICS[semantic_name]) + + +def record(is_start: tl.constexpr, scope_name: tl.constexpr, semantic): + if not flags.instrumentation_on: + return + _check_supported_semantic(semantic) + is_start = tl._unwrap_if_constexpr(is_start) + scope_name = tl._unwrap_if_constexpr(scope_name) + return tl.tensor(triton_proton.create_proton_record(semantic.builder, is_start, scope_name), tl.void) + + +@builtin +def enter_scope(name: tl.constexpr, _semantic=None): + record(is_start=True, scope_name=name, semantic=_semantic) + + +@builtin +def exit_scope(name: tl.constexpr, _semantic=None): + record(is_start=False, scope_name=name, semantic=_semantic) + + +class scope: + + def __init__(self, name: str, _semantic=None): + self.name = name + self.semantic = _semantic + + def __enter__(self): + enter_scope(self.name, _semantic=self.semantic) + + def __exit__(self, exc_type, exc_value, traceback): + exit_scope(self.name, _semantic=self.semantic) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/profiler/mode.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/profiler/mode.py new file mode 100644 index 0000000000000000000000000000000000000000..ff41d58872f906ed2a9895c47bbe4514fad32ee6 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/profiler/mode.py @@ -0,0 +1,123 @@ +from dataclasses import dataclass, field +from triton._C.libtriton import proton as triton_proton +from typing import List +from enum import Enum + +metric_types = {"cycle": triton_proton.METRIC_TYPE.CYCLE} + +buffer_strategies = { + "circular": triton_proton.BUFFER_STRATEGY.CIRCULAR, + "flush": triton_proton.BUFFER_STRATEGY.FLUSH, +} + +buffer_types = { + "shared": triton_proton.BUFFER_TYPE.SHARED, + "global": triton_proton.BUFFER_TYPE.GLOBAL, +} + +sampling_strategies = { + "none": triton_proton.SAMPLING_STRATEGY.NONE, + "selective": triton_proton.SAMPLING_STRATEGY.SELECTIVE, +} + +granularities = { + "cta": triton_proton.GRANULARITY.CTA, + "warp": triton_proton.GRANULARITY.WARP, + "warp_2": triton_proton.GRANULARITY.WARP_2, + "warp_4": triton_proton.GRANULARITY.WARP_4, + "warp_8": triton_proton.GRANULARITY.WARP_8, + "warp_group": triton_proton.GRANULARITY.WARP_GROUP, + "warp_group_2": triton_proton.GRANULARITY.WARP_GROUP_2, + "warp_group_4": triton_proton.GRANULARITY.WARP_GROUP_4, + "warp_group_8": triton_proton.GRANULARITY.WARP_GROUP_8, +} + + +class Optimize(Enum): + TIMESHIFT = "time_shift" + SCHED_STORES = "sched_stores" + SCHED_BARRIERS = "sched_barriers" + CLOCK32 = "clock32" + + def __str__(self): + return self.value + + +optimizations = { + "time_shift": Optimize.TIMESHIFT, + "sched_stores": Optimize.SCHED_STORES, + "sched_barriers": Optimize.SCHED_BARRIERS, + "clock32": Optimize.CLOCK32, +} + + +@dataclass(frozen=True) +class BaseMode: + name: str + + +@dataclass(frozen=True) +class PCSampling(BaseMode): + name: str = field(default="pcsampling", init=False) + interval: int = 1000 + + def __post_init__(self): + if self.interval <= 0: + raise ValueError("Interval must be a positive integer.") + + def __str__(self): + return f"{self.name}:interval={self.interval}" + + +@dataclass(frozen=True) +class InstrumentationMode(BaseMode): + """Common base class for instrumentation modes with shared configuration.""" + metric_type: triton_proton.METRIC_TYPE = triton_proton.METRIC_TYPE.CYCLE + sampling_strategy: triton_proton.SAMPLING_STRATEGY = triton_proton.SAMPLING_STRATEGY.NONE + sampling_options: str = "" + granularity: triton_proton.GRANULARITY = triton_proton.GRANULARITY.WARP + buffer_strategy: triton_proton.BUFFER_STRATEGY = triton_proton.BUFFER_STRATEGY.CIRCULAR + buffer_type: triton_proton.BUFFER_TYPE = triton_proton.BUFFER_TYPE.SHARED + buffer_size: int = 0 + optimizations: List[Optimize] = field(default_factory=list) + + def __post_init__(self): + # automatically map string inputs to enums using the global lookup dicts + mappings = [ + ("metric_type", metric_types), + ("sampling_strategy", sampling_strategies), + ("granularity", granularities), + ("buffer_strategy", buffer_strategies), + ("buffer_type", buffer_types), + ] + for field_name, lookup in mappings: + value = getattr(self, field_name) + if isinstance(value, str): + if value not in lookup: + raise ValueError(f"Unknown {field_name}: {value}") + object.__setattr__(self, field_name, lookup[value]) + + values_str = getattr(self, "optimizations") + if isinstance(values_str, str): + values = [value.strip() for value in values_str.split(",")] if len(values_str) > 0 else [] + for value in values: + if value not in optimizations: + raise ValueError(f"Unknown optimization: {value}") + object.__setattr__(self, "optimizations", [optimizations[value] for value in values]) + + def __str__(self): + optimizations_str = ",".join([str(opt) for opt in self.optimizations]) + return (f"{self.name}:metric_type={self.metric_type}:sampling_strategy={self.sampling_strategy}" + f":sampling_options={self.sampling_options}:granularity={self.granularity}" + f":buffer_strategy={self.buffer_strategy}:buffer_type={self.buffer_type}" + f":buffer_size={self.buffer_size}:optimizations={optimizations_str}") + + +@dataclass(frozen=True) +class Default(InstrumentationMode): + name: str = field(default="default", init=False) + + +@dataclass(frozen=True) +class MMA(InstrumentationMode): + name: str = field(default="mma", init=False) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/profiler/profile.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/profiler/profile.py new file mode 100644 index 0000000000000000000000000000000000000000..126b3abbeaf71fed1781f283fd53704cca41b42e --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/profiler/profile.py @@ -0,0 +1,252 @@ +import functools +import triton + +from triton._C.libproton import proton as libproton # type: ignore +from triton._C.libtriton import getenv # type: ignore +from .flags import flags +from .hooks import HookManager, LaunchHook, InstrumentationHook +from .mode import BaseMode +from typing import Optional, Union + +DEFAULT_PROFILE_NAME = "proton" + + +def _select_backend() -> str: + backend = triton.runtime.driver.active.get_current_target().backend + if backend == "cuda": + return "cupti" + elif backend == "hip": + return "roctracer" + else: + raise ValueError("No backend is available for the current target.") + + +def _get_mode_str(backend: str, mode: Optional[Union[str, BaseMode]]) -> str: + if backend == "instrumentation": + prefix = triton.runtime.driver.active.get_current_target().backend + return f"{prefix}:{mode}" if mode else prefix + return str(mode) if mode else "" + + +def _check_env(backend: str) -> None: + if backend == "roctracer": + hip_device_envs = ["HIP_VISIBLE_DEVICES", "CUDA_VISIBLE_DEVICES"] + for env in hip_device_envs: + if getenv(env, None) is not None: + raise ValueError( + f"Proton does not work when the environment variable {env} is set on AMD GPUs. Please unset it and use `ROCR_VISIBLE_DEVICES` instead" + ) + + # Ensure default envs are set for Proton knobs if not already set by the user. + for attr, desc in triton.knobs.proton.knob_descriptors.items(): + key = desc.key + if getenv(key, None) is None: + val = getattr(triton.knobs.proton, attr) + if val is not None: + if env_val := triton.knobs.toenv(val): + triton.knobs.setenv(key, env_val[0]) + + +def start( + name: Optional[str] = None, + *, + context: Optional[str] = "shadow", + data: Optional[str] = "tree", + backend: Optional[str] = None, + mode: Optional[Union[str, BaseMode]] = None, + hook: Optional[str] = None, +): + """ + Start profiling with the given name and backend. + + Usage: + + ```python + proton.start("my_profile") + # do something + proton.finalize() + ``` + + Args: + name (str, optional): The name (with path) of the profiling session. + If not provided, the default name is "~/proton.", where suffix is the default + format according to the data type. For example, if data is "tree", the default name is "~/proton.hatchet". + context (str, optional): The context to use for profiling. + Available options are ["shadow", "python"]. + Defaults to "shadow". + data (str, optional): The data structure to use for profiling. + Available options are ["tree", "trace"]. + Defaults to "tree". + backend (str, optional): The backend to use for profiling. + Available options are [None, "cupti", "roctracer", "instrumentation"]. + Defaults to None, which automatically selects the backend matching the current active runtime. + mode (Union[str, BaseMode], optional): The "mode" to use for profiling, which is specific to the backend. + Can be a string or an instance of BaseMode (or any subclass thereof). + Defaults to None. + For "cupti", available options are [None, "pcsampling"]. + For "roctracer", available options are [None]. + For "instrumentation", available options are [None]. + Each mode has a set of control knobs following with the mode name. + For example, "pcsampling" has an "interval" control knob, expressed as "pcsampling:interval=1000". + hook (str, optional): The hook to use for profiling. + Available options are [None, "launch"]. + Defaults to None. + Returns: + session (int): The session ID of the profiling session. + """ + if flags.command_line or triton.knobs.proton.disable: + # Ignore the start() call if the script is run from the command line or profiling is disabled. + return + + flags.profiling_on = True + + name = DEFAULT_PROFILE_NAME if name is None else name + backend = _select_backend() if backend is None else backend + # Convert mode to its string representation for libproton's runtime + mode_str = _get_mode_str(backend, mode) + + _check_env(backend) + + session = libproton.start(name, context, data, backend, mode_str) + + if hook == "triton": + HookManager.register(LaunchHook(), session) + if backend == "instrumentation": + HookManager.register(InstrumentationHook(mode), session) + + return session + + +def activate(session: Optional[int] = None) -> None: + """ + Activate the specified session. + The profiling session will be active and data will be recorded. + + Args: + session (int): The session ID of the profiling session. Defaults to None (all sessions) + + Returns: + None + """ + if flags.command_line and session != 0: + raise ValueError("Only one session can be activated when running from the command line.") + + HookManager.activate(session) + + if session is None: + libproton.activate_all() + else: + libproton.activate(session) + + +def deactivate(session: Optional[int] = None) -> None: + """ + Stop the specified session. + The profiling session's data will still be in the memory, but no more data will be recorded. + + Args: + session (int): The session ID of the profiling session. Defaults to None (all sessions) + + Returns: + None + """ + if flags.command_line and session != 0: + raise ValueError("Only one session can be deactivated when running from the command line.") + + HookManager.deactivate(session) + + if session is None: + libproton.deactivate_all() + else: + libproton.deactivate(session) + + +def finalize(session: Optional[int] = None, output_format: Optional[str] = "") -> None: + """ + Finalizes a profiling session. + Flush and write the profiling data to the file specified by the session name. + + Args: + session (int, optional): The session ID to finalize. If None, all sessions are finalized. Defaults to None. + output_format (str, optional): The output format for the profiling results. + Available options are ["hatchet", "chrome_trace"]. + + Returns: + None + """ + HookManager.unregister(session) + + if session is None: + flags.profiling_on = False + libproton.finalize_all(output_format) + else: + if flags.command_line and session != 0: + raise ValueError("Only one session can be finalized when running from the command line.") + libproton.finalize(session, output_format) + + +def _profiling( + func, + name: Optional[str] = None, + context: Optional[str] = "shadow", + data: Optional[str] = "tree", + backend: Optional[str] = None, + mode: Optional[str] = None, + hook: Optional[str] = None, +): + """ + Context manager for profiling. Internally use only. + + Args: + See start() for the arguments. + + Returns: + wrapper (function): The wrapped function. + """ + + @functools.wraps(func) + def wrapper(*args, **kwargs): + session = start(name, context=context, data=data, backend=backend, mode=mode, hook=hook) + ret = func(*args, **kwargs) + deactivate(session) + return ret + + return wrapper + + +def profile( + func=None, + *, + name: Optional[str] = None, + context: Optional[str] = "shadow", + data: Optional[str] = "tree", + backend: Optional[str] = None, + mode: Optional[str] = None, + hook: Optional[str] = None, +): + """ + Decorator for profiling. + + Usage: + + ```python + @proton.profile + def foo(): + pass + ``` + + Args: + See start() for the arguments. + + Returns: + decorator (function): The decorator function. + """ + if func is None: + # It's being used with parentheses, so return a decorator + def decorator(f): + return _profiling(f, name=name, context=context, data=data, backend=backend, mode=mode, hook=hook) + + return decorator + else: + # It's being used without parentheses, so apply the decorator directly + return _profiling(func, name=name, context=context, data=data, backend=backend, mode=mode, hook=hook) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/profiler/proton.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/profiler/proton.py new file mode 100644 index 0000000000000000000000000000000000000000..80d3a971e92cf9766dd8a82d6a695e8abd8074b2 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/profiler/proton.py @@ -0,0 +1,88 @@ +import argparse +import sys +import os +from .profile import start, finalize, _select_backend +from .flags import flags + + +def parse_arguments(): + parser = argparse.ArgumentParser( + description="The proton command utility for profiling scripts and pytest tests.", usage=""" + proton [options] script.py [script_args] [script_options] + proton [options] pytest [pytest_args] [script_options] + python -m triton.profiler.proton [options] script.py [script_args] [script_options] +""", formatter_class=argparse.RawTextHelpFormatter) + parser.add_argument("-n", "--name", type=str, help="Name of the profiling session") + parser.add_argument("-b", "--backend", type=str, help="Profiling backend", default=None, + choices=["cupti", "roctracer", "instrumentation"]) + parser.add_argument("-c", "--context", type=str, help="Profiling context", default="shadow", + choices=["shadow", "python"]) + parser.add_argument("-m", "--mode", type=str, help="Profiling mode", default=None) + parser.add_argument("-d", "--data", type=str, help="Profiling data", default="tree", choices=["tree", "trace"]) + parser.add_argument("-k", "--hook", type=str, help="Profiling hook", default=None, choices=[None, "triton"]) + parser.add_argument('target_args', nargs=argparse.REMAINDER, help='Subcommand and its arguments') + args = parser.parse_args() + return args, args.target_args + + +def is_pytest(script): + return os.path.basename(script) == 'pytest' + + +def execute_as_main(script, args): + script_path = os.path.abspath(script) + # Prepare a clean global environment + clean_globals = { + "__name__": "__main__", + "__file__": script_path, + "__builtins__": __builtins__, + sys.__name__: sys, + } + + original_argv = sys.argv + sys.argv = [script] + args + # Append the script's directory in case the script uses relative imports + sys.path.append(os.path.dirname(script_path)) + + # Execute in the isolated environment + try: + with open(script_path, 'rb') as file: + code = compile(file.read(), script_path, 'exec') + exec(code, clean_globals) + except Exception as e: + print(f"An error occurred while executing the script: {e}") + sys.exit(1) + finally: + sys.argv = original_argv + + +def do_setup_and_execute(target_args): + # Set the command line mode to avoid any `start` calls in the script. + flags.command_line = True + + script = target_args[0] + script_args = target_args[1:] if len(target_args) > 1 else [] + if is_pytest(script): + import pytest + pytest.main(script_args) + else: + execute_as_main(script, script_args) + + +def run_profiling(args, target_args): + backend = args.backend if args.backend else _select_backend() + + start(args.name, context=args.context, data=args.data, backend=backend, hook=args.hook) + + do_setup_and_execute(target_args) + + finalize() + + +def main(): + args, target_args = parse_arguments() + run_profiling(args, target_args) + + +if __name__ == "__main__": + main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/profiler/scope.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/profiler/scope.py new file mode 100644 index 0000000000000000000000000000000000000000..911ebc46ecb58fa1deb44d45f255cdd9934d8b04 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/profiler/scope.py @@ -0,0 +1,129 @@ +import threading +import time +from functools import wraps +from typing import Optional, Union + +from .flags import flags +from triton._C.libproton import proton as libproton + +thread_local_scopes = threading.local() + +MetricValueType = Union[float, int] + + +class scope: + """ + A context manager and decorator for entering and exiting a scope. + + Usage: + context manager: + ```python + with proton.scope("test0", {metric_name: metric_value}): + foo[1,](x, y) + ``` + + decorator: + ```python + @proton.scope("test0", {metric_name: metric_value}) + def foo(x, y): + ... + ``` + + Args: + name (str): The name of the scope. + metrics (dict[str, float], optional): The metrics of the scope. Default is None. + """ + + def __init__(self, name: str, metrics: Optional[dict[str, MetricValueType]] = None) -> None: + self.name = name + self.metrics = metrics + self.id = None + + def _enter_scope(self): + if not flags.profiling_on: + return + self.id = libproton.record_scope() + libproton.enter_scope(self.id, self.name) + if self.metrics: + libproton.add_metrics(self.id, self.metrics) + + def _exit_scope(self): + if not flags.profiling_on or self.id is None: + return + libproton.exit_scope(self.id, self.name) + + def __enter__(self): + self._enter_scope() + return self + + def __exit__(self, exc_type, exc_value, traceback): + self._exit_scope() + + def __call__(self, func): + + @wraps(func) + def wrapper(*args, **kwargs): + self._enter_scope() + try: + return func(*args, **kwargs) + finally: + self._exit_scope() + + return wrapper + + +class cpu_timed_scope(scope): + """ + A scope that measures elapsed time (cpu_time). + + Args: + name (str): The name of the scope. + metrics (dict[str, float], optional): Additional metrics to add. Default is None. + """ + + def __init__(self, name: str, metrics: Optional[dict[str, float]] = None) -> None: + super().__init__(name, metrics) + self.start_time = None + if metrics and "cpu_time" in metrics: + raise ValueError("The metric name 'cpu_time' is reserved.") + + def _enter_scope(self): + if not flags.profiling_on: + return + self.start_time = time.time_ns() + super()._enter_scope() + + def _exit_scope(self): + if not flags.profiling_on: + return + super()._exit_scope() + if self.start_time is not None: + cpu_time = time.time_ns() - self.start_time + libproton.add_metrics(self.id, {"cpu_time (ns)(exc)": cpu_time}) + + +def enter_scope(name: str, *, metrics: Optional[dict[str, MetricValueType]] = None) -> Optional[int]: + if not flags.profiling_on: + return None + id = libproton.record_scope() + thread_local_scopes.scopes = getattr(thread_local_scopes, "scopes", []) + thread_local_scopes.scopes.append((id, name)) + libproton.enter_scope(id, name) + if metrics: + libproton.add_metrics(id, metrics) + return id + + +def exit_scope(name: Optional[str] = None, *, metrics: Optional[dict[str, MetricValueType]] = None) -> Optional[int]: + # `name` is an optional argument here, only to match the counterpart in enter_scope to make the API consistent with `proton.language.exit_scope` + if not flags.profiling_on: + return None + id, popped_name = thread_local_scopes.scopes.pop() + if name and name != popped_name: + raise ValueError(f"Scope name mismatch: {name} != {popped_name}") + elif not name: + name = popped_name + libproton.exit_scope(id, name) + if metrics: + libproton.add_metrics(id, metrics) + return id diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/profiler/specs.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/profiler/specs.py new file mode 100644 index 0000000000000000000000000000000000000000..b30c3416d8ebc60351d6a4ce07b711512f3b22ef --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/profiler/specs.py @@ -0,0 +1,69 @@ +flops_by_device = { + "CUDA": { + "80": + lambda width, **kwargs: 624e12 / (width / 8), + "89": + lambda width, **kwargs: (330.3 * 1e12) / (width / 8), # TODO(Keren): Implement fp16 acc-> 660.6 fp8 + "90": + lambda width, num_sms, clock_rate, **kwargs: ((num_sms / 114 * clock_rate / (1755 * 1e3) * 1513) * 1e12) / + (width / 8), + "100": + lambda width, num_sms, clock_rate, **kwargs: (num_sms * 16384 * (clock_rate / 1e3) * 1e6) / (width / 8), + } +} + +amd_bps_by_arch = { + 'gfx90a': 3.2 * 1e12, + 'gfx942': 5.3 * 1e12, + 'gfx950': 8.0 * 1e12, +} + +# FP8 Matrix Performance(FLOPS/clock/CU) +# For gfx90a we use the performance of INT8 since it doesn't support FP8 matrix operations. +amd_fp8_flops_by_arch = {'gfx90a': 1024, 'gfx942': 4096, 'gfx950': 8192} + + +def max_flops(device_type, arch, width, num_sms, clock_rate): + """ + Calculate the maximum FLOPS for a given device type and width. + + Args: + device_type (str): The type of device (e.g., "CUDA", "HIP"). + arch (str): The architecture of the device (e.g., "80", "90"). + width (int): The width in bits. + num_sms (int): The number of streaming multiprocessors. + clock_rate (float): The clock rate in GHz. + + Returns: + float: The maximum FLOPS for the given device type and width. + """ + if device_type == "HIP": + return amd_fp8_flops_by_arch[arch] * num_sms * clock_rate * 1e3 / (width / 8) + + if device_type not in flops_by_device: + raise ValueError(f"Unsupported device type: {device_type}") + + if arch not in flops_by_device[device_type]: + raise ValueError(f"Unsupported architecture: {arch}") + + flops_func = flops_by_device[device_type][arch] + + return flops_func(width, num_sms=num_sms, clock_rate=clock_rate) + + +def max_bps(device_type, arch, bus_width, memory_clock_rate): + """ + Calculate the maximum bytes per second for a given bus width and memory clock rate. + + Args: + bus_width (int): The bus width in bits. + memory_clock_rate (float): The memory clock rate in GHz. + + Returns: + float: The maximum bytes per second. + """ + if device_type == "CUDA": + return 2 * bus_width * memory_clock_rate * 1e3 / 8 + else: + assert device_type == "HIP" + return amd_bps_by_arch[arch] diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/profiler/state.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/profiler/state.py new file mode 100644 index 0000000000000000000000000000000000000000..decb8e1d0112f312ce1366f7a56df4d60c57d09b --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/profiler/state.py @@ -0,0 +1,61 @@ +from triton._C.libproton import proton as libproton +from .flags import flags +from functools import wraps + + +class state: + """ + A context manager and decorator for entering and exiting a state. + + Usage: + context manager: + ```python + with proton.state("test0"): + foo[1,](x, y) + ``` + + decorator: + ```python + @proton.state("test0") + def foo(x, y): + ... + ``` + + Args: + name (str): The name of the state. + """ + + def __init__(self, name: str) -> None: + self.name = name + + def __enter__(self): + if not flags.profiling_on: + return self + libproton.enter_state(self.name) + return self + + def __exit__(self, exc_type, exc_value, traceback) -> None: + if not flags.profiling_on: + return + libproton.exit_state() + + def __call__(self, func): + + @wraps(func) + def wrapper(*args, **kwargs): + if flags.profiling_on: + libproton.enter_state(self.name) + ret = func(*args, **kwargs) + if flags.profiling_on: + libproton.exit_state() + return ret + + return wrapper + + +def enter_state(name: str) -> None: + libproton.enter_state(name) + + +def exit_state() -> None: + libproton.exit_state() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/profiler/viewer.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/profiler/viewer.py new file mode 100644 index 0000000000000000000000000000000000000000..86d25e59ba093a3cf0fc76422236879975815175 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/profiler/viewer.py @@ -0,0 +1,426 @@ +import argparse +from collections import namedtuple +import json +import pandas as pd + +try: + import hatchet as ht + from hatchet.query import NegationQuery +except ImportError: + raise ImportError("Failed to import hatchet. `pip install llnl-hatchet` to get the correct version.") +import numpy as np +from triton.profiler.hooks.launch import COMPUTE_METADATA_SCOPE_NAME, LaunchHook +from triton.profiler import specs + + +def match_available_metrics(metrics, inclusive_metrics, exclusive_metrics): + ret = [] + if not isinstance(metrics, list): + metrics = [metrics] + if metrics: + for metric in metrics: + metric = metric.lower() + for raw_metric in inclusive_metrics + exclusive_metrics: + suffix = " (inc)" if raw_metric in inclusive_metrics else "" + raw_metric_no_unit = raw_metric.split("(")[0].strip().lower() + if metric in (raw_metric, raw_metric_no_unit): + ret.append(raw_metric + suffix) + break + if len(ret) == 0: + raise RuntimeError(f"Metric {metric} is not found. Use the --list flag to list available metrics") + return ret + + +def remove_frames(database: json): + # We first fine frames that match either one of the two conditions: + # 1. The frame name is COMPUTE_METADATA_SCOPE_NAME + # 2. The frame has no metrics and no children + # Then we go up from the located nodes and remove the parents if all children were + # metadata nodes + def remove_frame_helper(node): + if "frame" not in node: + return node + if node["frame"]["name"] == COMPUTE_METADATA_SCOPE_NAME: + return None + if len(node["metrics"]) == 0 and len(node["children"]) == 0: + return None + children = node.get("children", []) + new_children = [] + for child in children: + new_child = remove_frame_helper(child) + if new_child is not None: + new_children.append(new_child) + if len(new_children) > 0 or len(children) == 0: + node["children"] = new_children + return node + return None + + new_database = [] + for node in database: + new_node = remove_frame_helper(node) + if new_node is not None: + new_database.append(new_node) + return new_database + + +def get_raw_metrics(file): + database = json.load(file) + database = remove_frames(database) + device_info = database.pop(1) + gf = ht.GraphFrame.from_literal(database) + inclusive_metrics = gf.show_metric_columns() + exclusive_metrics = [metric for metric in gf.dataframe.columns if metric not in inclusive_metrics] + return gf, inclusive_metrics, exclusive_metrics, device_info + + +def get_min_time_flops(df, device_info): + min_time_flops = pd.DataFrame(0.0, index=df.index, columns=["min_time"]) + for device_type in device_info: + for device_index in device_info[device_type]: + arch = device_info[device_type][device_index]["arch"] + num_sms = device_info[device_type][device_index]["num_sms"] + clock_rate = device_info[device_type][device_index]["clock_rate"] + for width in LaunchHook.flops_width: + idx = df["device_id"] == device_index + device_frames = df[idx] + if f"flops{width}" not in device_frames.columns: + continue + max_flops = specs.max_flops(device_type, arch, width, num_sms, clock_rate) + min_time_flops.loc[idx, "min_time"] += device_frames[f"flops{width}"].fillna(0) / max_flops + return min_time_flops + + +def get_min_time_bytes(df, device_info): + min_time_bytes = pd.DataFrame(0.0, index=df.index, columns=["min_time"]) + for device_type in device_info: + for device_index in device_info[device_type]: + idx = df["device_id"] == device_index + device_frames = df[idx] + device = device_info[device_type][device_index] + memory_clock_rate = device["memory_clock_rate"] # in khz + bus_width = device["bus_width"] # in bits + peak_bandwidth = specs.max_bps(device_type, device['arch'], bus_width, memory_clock_rate) + min_time_bytes.loc[idx, "min_time"] += device_frames["bytes"] / peak_bandwidth + return min_time_bytes + + +FactorDict = namedtuple("FactorDict", ["name", "factor"]) +time_factor_dict = FactorDict("time", {"time/s": 1, "time/ms": 1e-3, "time/us": 1e-6, "time/ns": 1e-9}) +avg_time_factor_dict = FactorDict("avg_time", {f"avg_{key}": value for key, value in time_factor_dict.factor.items()}) +cpu_time_factor_dict = FactorDict("cpu_time", + {"cpu_time/s": 1, "cpu_time/ms": 1e-3, "cpu_time/us": 1e-6, "cpu_time/ns": 1e-9}) +avg_cpu_time_factor_dict = FactorDict("avg_cpu_time", + {f"avg_{key}": value + for key, value in cpu_time_factor_dict.factor.items()}) +bytes_factor_dict = FactorDict("bytes", {"byte/s": 1, "gbyte/s": 1e9, "tbyte/s": 1e12}) + +derivable_metrics = { + **{key: bytes_factor_dict + for key in bytes_factor_dict.factor.keys()}, +} + +# FLOPS have a specific width to their metric +default_flop_factor_dict = {"flop/s": 1, "gflop/s": 1e9, "tflop/s": 1e12} +derivable_metrics.update( + {key: FactorDict("flops", default_flop_factor_dict) + for key in default_flop_factor_dict.keys()}) +for width in LaunchHook.flops_width: + factor_name = f"flops{width}" + factor_dict = {f"flop{width}/s": 1, f"gflop{width}/s": 1e9, f"tflop{width}/s": 1e12} + derivable_metrics.update({key: FactorDict(factor_name, factor_dict) for key in factor_dict.keys()}) + + +def derive_metrics(gf, metrics, inclusive_metrics, exclusive_metrics, device_info): + derived_metrics = [] + + def get_time_seconds(df, metric, factor_dict): + time_metric_name = match_available_metrics(metric, inclusive_metrics, exclusive_metrics)[0] + time_unit = factor_dict.name + "/" + time_metric_name.split("(")[1].split(")")[0] + return df[time_metric_name] * factor_dict.factor[time_unit] + + for metric in metrics: + if metric == "util": # exclusive + min_time_bytes = get_min_time_bytes(gf.dataframe, device_info) + min_time_flops = get_min_time_flops(gf.dataframe, device_info) + time_sec = get_time_seconds(gf.dataframe, "time", time_factor_dict) + internal_frame_indices = gf.dataframe["device_id"].isna() + gf.dataframe["util"] = min_time_flops["min_time"].combine(min_time_bytes["min_time"], max) / time_sec + gf.dataframe.loc[internal_frame_indices, "util"] = np.nan + derived_metrics.append("util") + elif metric in derivable_metrics: # flop/s, byte/s, inclusive + derivable_metric = derivable_metrics[metric] + metric_name = derivable_metric.name + metric_factor_dict = derivable_metric.factor + matched_metric_name = match_available_metrics(metric_name, inclusive_metrics, exclusive_metrics)[0] + gf.dataframe[f"{metric} (inc)"] = (gf.dataframe[matched_metric_name] / + (get_time_seconds(gf.dataframe, "time", time_factor_dict)) / + metric_factor_dict[metric]) + derived_metrics.append(f"{metric} (inc)") + elif (metric in time_factor_dict.factor or metric in cpu_time_factor_dict.factor + or metric in avg_time_factor_dict.factor or metric in avg_cpu_time_factor_dict.factor): # inclusive + is_cpu = metric in cpu_time_factor_dict.factor or metric in avg_cpu_time_factor_dict.factor + is_avg = metric in avg_time_factor_dict.factor or metric in avg_cpu_time_factor_dict.factor + + factor_dict = ((avg_cpu_time_factor_dict if is_avg else cpu_time_factor_dict) if is_cpu else + (avg_time_factor_dict if is_avg else time_factor_dict)) + metric_name = "cpu_time" if is_cpu else "time" + metric_time_unit = factor_dict.name + "/" + metric.split("/")[1] + + time_value = get_time_seconds(gf.dataframe, metric_name, factor_dict) + if is_avg: + time_value = time_value / gf.dataframe["count (inc)"] + + gf.dataframe[f"{metric} (inc)"] = time_value / factor_dict.factor[metric_time_unit] + derived_metrics.append(f"{metric} (inc)") + else: + metric_name_and_unit = metric.split("/") + metric_name = metric_name_and_unit[0] + if len(metric_name_and_unit) > 1: # percentage, exclusive or inclusive + metric_unit = metric_name_and_unit[1] + if metric_unit != "%": + raise ValueError(f"Unsupported unit {metric_unit}") + matched_metric_name = match_available_metrics(metric_name, inclusive_metrics, exclusive_metrics)[0] + single_frame = gf.dataframe[matched_metric_name] + suffix = "" + if "(inc)" in matched_metric_name: + suffix = " (inc)" + total = gf.dataframe[matched_metric_name].iloc[0] + else: + total = gf.dataframe[matched_metric_name].sum() + gf.dataframe[metric + suffix] = (single_frame / total) * 100.0 + derived_metrics.append(metric + suffix) + else: + matched_metric_name = match_available_metrics(metric_name, inclusive_metrics, exclusive_metrics)[0] + derived_metrics.append(matched_metric_name) + + # Update derived metrics to the graph frame + for derived_metric in derived_metrics: + if derived_metric.endswith("(inc)"): + gf.inc_metrics.append(derived_metric) + else: + gf.exc_metrics.append(derived_metric) + + return derived_metrics + + +def format_frames(gf, format): + if format == "file_function_line": + gf.dataframe["name"] = gf.dataframe["name"].apply(lambda x: x.split("/")[-1]) + elif format == "function_line": + gf.dataframe["name"] = gf.dataframe["name"].apply(lambda x: x.split(":")[-1]) + elif format == "file_function": + gf.dataframe["name"] = gf.dataframe["name"].apply( + lambda x: f"{x.split('/')[-1].split(':')[0]}@{x.split('@')[-1].split(':')[0]}") + return gf + + +def filter_frames(gf, include=None, exclude=None, threshold=None, metric=None): + if include: + query = f""" +MATCH ("*")->(".", p)->("*") +WHERE p."name" =~ "{include}" +""" + gf = gf.filter(query, squash=True) + if exclude: + inclusion_query = f""" +MATCH (".", p)->("*") +WHERE p."name" =~ "{exclude}" +""" + query = NegationQuery(inclusion_query) + gf = gf.filter(query, squash=True) + if threshold: + query = ["*", {metric: f">= {threshold}"}] + gf = gf.filter(query, squash=True) + return gf + + +def emit_warnings(gf, metrics): + if "bytes (inc)" in metrics: + byte_values = gf.dataframe["bytes (inc)"].values + min_byte_value = np.nanmin(byte_values) + if min_byte_value < 0: + print("Warning: Negative byte values detected, this is usually the result of a datatype overflow\n") + + +def print_tree(gf, metrics, depth=100, format=None, print_sorted=False): + gf = format_frames(gf, format) + print(gf.tree(metric_column=metrics, expand_name=True, depth=depth, render_header=False)) + + if print_sorted: + print("Sorted kernels by metric " + metrics[0]) + sorted_df = gf.dataframe.sort_values(by=[metrics[0]], ascending=False) + for row in range(1, len(sorted_df)): + kernel_name = (sorted_df.iloc[row]["name"][:100] + + "..." if len(sorted_df.iloc[row]["name"]) > 100 else sorted_df.iloc[row]["name"]) + print("{:105} {:.4}".format(kernel_name, sorted_df.iloc[row][metrics[0]])) + emit_warnings(gf, metrics) + + +def read(filename): + with open(filename, "r") as f: + gf, inclusive_metrics, exclusive_metrics, device_info = get_raw_metrics(f) + assert len(inclusive_metrics + exclusive_metrics) > 0, "No metrics found in the input file" + gf.update_inclusive_columns() + return gf, inclusive_metrics, exclusive_metrics, device_info + + +def parse(metrics, filename, include=None, exclude=None, threshold=None): + gf, inclusive_metrics, exclusive_metrics, device_info = read(filename) + metrics = derive_metrics(gf, metrics, inclusive_metrics, exclusive_metrics, device_info) + # TODO: generalize to support multiple metrics, not just the first one + gf = filter_frames(gf, include, exclude, threshold, metrics[0]) + return gf, metrics + + +def apply_diff_profile(gf, derived_metrics, diff_file, metrics, include, exclude, threshold): + # Compute the diff against a secondary profile while keeping derived metrics consistent. + gf2, _ = parse(metrics, diff_file, include, exclude, threshold) + + derived_inc_metrics = [metric for metric in derived_metrics if metric.endswith("(inc)")] + derived_exc_metrics = [metric for metric in derived_metrics if not metric.endswith("(inc)")] + + gf.inc_metrics = derived_inc_metrics + gf.exc_metrics = derived_exc_metrics + gf2.inc_metrics = derived_inc_metrics + gf2.exc_metrics = derived_exc_metrics + return gf.sub(gf2) + + +def show_metrics(file_name): + with open(file_name, "r") as f: + _, inclusive_metrics, exclusive_metrics, _ = get_raw_metrics(f) + print("Available inclusive metrics:") + if inclusive_metrics: + for raw_metric in inclusive_metrics: + raw_metric_no_unit = raw_metric.split("(")[0].strip().lower() + print(f"- {raw_metric_no_unit}") + print("Available exclusive metrics:") + if exclusive_metrics: + for raw_metric in exclusive_metrics: + raw_metric_no_unit = raw_metric.split("(")[0].strip().lower() + print(f"- {raw_metric_no_unit}") + + +def main(): + argparser = argparse.ArgumentParser( + description="Performance data viewer for proton profiles.", + formatter_class=argparse.RawTextHelpFormatter, + ) + argparser.add_argument( + "-l", + "--list", + action="store_true", + help="""List available metrics. Metric names are case insensitive and ignore units. +Derived metrics can be created when source metrics are available. +- time/s, time/ms, time/us, time/ns: time +- avg_time/s, avg_time/ms, avg_time/us, avg_time/ns: time / count +- flop[<8/16/32/64>]/s, gflop[<8/16/32/64>]/s, tflop[<8/16/32/64>]/s: flops / time +- byte/s, gbyte/s, tbyte/s: bytes / time +- util: max(sum(flops) / peak_flops_time, sum(bytes) / peak_bandwidth_time) +- /%%: frame(metric) / sum(metric). Only available for inclusive metrics (e.g. time) +""", + ) + argparser.add_argument( + "-m", + "--metrics", + type=str, + default=None, + help="""At maximum two metrics can be specified, separated by comma. +There are two modes: +1) Choose the output metric to display. It's case insensitive and ignore units. +2) Derive a new metric from existing metrics. +""", + ) + argparser.add_argument( + "-i", + "--include", + type=str, + default=None, + help= + """Find frames that match the given regular expression and return all nodes in the paths that pass through the matching frames. +For example, the following command will display all paths that contain frames that contains "test": +``` +proton-viewer -i ".*test.*" path/to/file.json +``` +""", + ) + argparser.add_argument( + "-e", + "--exclude", + type=str, + default=None, + help="""Exclude frames that match the given regular expression and their children. +For example, the following command will exclude all paths starting from frames that contains "test": +``` +proton-viewer -e ".*test.*" path/to/file.json +``` +""", + ) + argparser.add_argument( + "-t", + "--threshold", + type=float, + default=None, + help= + "Exclude frames(kernels) whose metrics are below the given threshold. This filter only applies on the first metric.", + ) + argparser.add_argument( + "-d", + "--depth", + type=int, + default=100, + help="The depth of the tree to display", + ) + argparser.add_argument( + "-f", + "--format", + type=str, + choices=["full", "file_function_line", "function_line", "file_function"], + default="full", + help="""Formatting the frame name. +- full: include the path, file name, function name and line number. +- file_function_line: include the file name, function name and line number. +- function_line: include the function name and line number. +- file_function: include the file name and function name. +""", + ) + argparser.add_argument( + "--print-sorted", + action="store_true", + default=False, + help="Sort output by metric value instead of chronologically", + ) + argparser.add_argument( + "--diff-profile", + "-diff", + type=str, + default=None, + help="Compare two profiles. When used as 'proton-viewer -m time -diff file1.log file2.log', " + "computes the difference: file2['time'] - file1['time']", + ) + + args, target_args = argparser.parse_known_args() + assert len(target_args) == 1, "Must specify a file to read" + + file_name = target_args[0] + metrics = args.metrics.split(",") if args.metrics else None + include = args.include + exclude = args.exclude + threshold = args.threshold + depth = args.depth + format = args.format + diff = args.diff_profile + print_sorted = args.print_sorted + if include and exclude: + raise ValueError("Cannot specify both include and exclude") + if args.list: + show_metrics(file_name) + elif metrics: + gf, derived_metrics = parse(metrics, file_name, include, exclude, threshold) + if diff: + gf = apply_diff_profile(gf, derived_metrics, diff, metrics, include, exclude, threshold) + print_tree(gf, derived_metrics, depth, format, print_sorted) + + +if __name__ == "__main__": + main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/runtime/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/runtime/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0b3979d28d9a4359be5ceb3d2dea08f4d56899e6 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/runtime/__init__.py @@ -0,0 +1,23 @@ +from .autotuner import (Autotuner, Config, Heuristics, autotune, heuristics) +from .cache import RedisRemoteCacheBackend, RemoteCacheBackend +from .driver import driver +from .jit import JITFunction, KernelInterface, MockTensor, TensorWrapper, reinterpret +from .errors import OutOfResources, InterpreterError + +__all__ = [ + "autotune", + "Autotuner", + "Config", + "driver", + "Heuristics", + "heuristics", + "InterpreterError", + "JITFunction", + "KernelInterface", + "MockTensor", + "OutOfResources", + "RedisRemoteCacheBackend", + "reinterpret", + "RemoteCacheBackend", + "TensorWrapper", +] diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/runtime/_allocation.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/runtime/_allocation.py new file mode 100644 index 0000000000000000000000000000000000000000..f3ef7d56c4c7a595a5bce9be72be7fb4e0e3f4ed --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/runtime/_allocation.py @@ -0,0 +1,64 @@ +from typing import Optional, Protocol +from contextvars import ContextVar + + +class Buffer(Protocol): + + def data_ptr(self) -> int: + ... + + +class Allocator(Protocol): + + def __call__(self, size: int, alignment: int, stream: Optional[int]) -> Buffer: + ... + + +class NullAllocator: + + def __call__(self, size: int, alignment: int, stream: Optional[int]) -> Buffer: + raise RuntimeError("Kernel requires a runtime memory allocation, but no allocator was set. " + + "Use triton.set_allocator to specify an allocator.") + + +_NULL_ALLOCATOR = NullAllocator() + +_allocator: ContextVar[Allocator] = ContextVar("_allocator", default=_NULL_ALLOCATOR) + + +def set_allocator(allocator: Allocator) -> None: + """ + The allocator function is called during kernel launch for kernels that + require additional global memory workspace. + """ + _allocator.set(allocator) + + +class _AllocatorWrapper: + """ + Wrapper to provide ContextVar-like .get()/.set() methods. profile_allocator is + used in same way as allocator so it is useful to maintain the interface. + """ + + def __init__(self, allocator: Allocator) -> None: + self._allocator = allocator + + def get(self) -> Allocator: + return self._allocator + + def set(self, allocator: Allocator) -> None: + self._allocator = allocator + + def __call__(self, size: int, alignment: int, stream: Optional[int]) -> Buffer: + return self._allocator(size, alignment, stream) + + +_profile_allocator = _AllocatorWrapper(_NULL_ALLOCATOR) + + +def set_profile_allocator(allocator: Optional[Allocator]) -> None: + """ + The profile allocator function is called before kernel launch for kernels + that require additional global memory workspace. + """ + _profile_allocator.set(allocator if allocator is not None else _NULL_ALLOCATOR) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/runtime/_async_compile.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/runtime/_async_compile.py new file mode 100644 index 0000000000000000000000000000000000000000..518743bde7afae92ee2100f16cdb804ef4338c90 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/runtime/_async_compile.py @@ -0,0 +1,62 @@ +from __future__ import annotations +from typing import Callable, Optional +from concurrent.futures import Executor, as_completed, Future +from contextvars import ContextVar + +active_mode: ContextVar[Optional[AsyncCompileMode]] = ContextVar("async_compile_active_mode", default=None) + + +class FutureKernel: + + def __init__(self, finalize_compile: Callable, future: Future): + self.finalize_compile = finalize_compile + self.kernel = None + self.future = future + + def result(self, ignore_errors: bool = False): + if self.kernel is not None: + return self.kernel + + try: + kernel = self.future.result() + except Exception: + if ignore_errors: + return + else: + raise + self.finalize_compile(kernel) + self.kernel = kernel + return kernel + + +class AsyncCompileMode: + + def __init__(self, executor: Executor, *, ignore_errors=False): + self.executor = executor + self.ignore_errors = ignore_errors + self.raw_futures = [] + self.future_kernels = {} + + def submit(self, key, compile_fn, finalize_fn): + future = self.future_kernels.get(key) + if future is not None: + return future + + future = self.executor.submit(compile_fn) + future._key = key + self.raw_futures.append(future) + future_kernel = FutureKernel(finalize_fn, future) + self.future_kernels[key] = future_kernel + return future_kernel + + def __enter__(self): + if active_mode.get() is not None: + raise RuntimeError("Another AsyncCompileMode is already active") + active_mode.set(self) + return self + + def __exit__(self, exc_type, exc_value, traceback): + # Finalize any outstanding compiles + for future in as_completed(self.raw_futures): + self.future_kernels[future._key].result(self.ignore_errors) + active_mode.set(None) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/runtime/autotuner.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/runtime/autotuner.py new file mode 100644 index 0000000000000000000000000000000000000000..0c4d710496fa4143597da86d45bd3b9942ca65fe --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/runtime/autotuner.py @@ -0,0 +1,483 @@ +from __future__ import annotations + +import builtins +import time +import inspect +import hashlib +import json +from functools import cached_property +from typing import Dict, Tuple, List, Optional + +from .. import knobs +from .jit import KernelInterface, JITFunction +from .errors import OutOfResources, PTXASError, AutotunerError +from .driver import driver +from .cache import get_cache_manager, triton_key +from triton._C.libtriton import get_cache_invalidating_env_vars + + +class Autotuner(KernelInterface): + + def __init__(self, fn, arg_names, configs, key, reset_to_zero, restore_value, pre_hook=None, post_hook=None, + prune_configs_by: Optional[Dict] = None, warmup=None, rep=None, use_cuda_graph=False, do_bench=None, + cache_results=False): + """ + :param prune_configs_by: a dict of functions that are used to prune configs, fields: + 'perf_model': performance model used to predicate running time with different configs, returns running time + 'top_k': number of configs to bench + 'early_config_prune': a function used to prune configs. It should have the signature + `prune_configs_by( configs: List[triton.Config], named_args: Dict[str, Any], **kwargs: Dict[str, Any]) -> List[triton.Config]:` + and return pruned configs. It should return at least one config. + """ + if not configs: + self.configs = [Config({}, num_warps=4, num_stages=3, num_ctas=1)] + else: + self.configs = configs + self.keys = key + self.cache: Dict[Tuple, Config] = {} + self.arg_names = arg_names + self.cache_results = (cache_results or knobs.autotuning.cache) and not knobs.runtime.interpret + + # Reset to zero or restore values + self.reset_to_zero = [] + if reset_to_zero is not None: + self.reset_to_zero = list(reset_to_zero) + self.restore_value = [] + if restore_value is not None: + self.restore_value = list(restore_value) + + # Hook to reset or restore for required tensors + self.pre_hook = lambda kwargs, reset_only=False: 0 + self.post_hook = lambda kwargs, exception: 0 + self.user_defined_pre_hook = False + self.user_defined_post_hook = False + if pre_hook: + self.pre_hook = pre_hook + self.user_defined_pre_hook = True + elif (len(self.reset_to_zero) > 0 or len(self.restore_value) > 0): + + def _pre_hook(kwargs, reset_only=False): + for name in self.reset_to_zero: + kwargs[name].zero_() + if not reset_only: + self.restore_copies = {name: kwargs[name].clone() for name in self.restore_value} + + self.pre_hook = _pre_hook + + if post_hook: + self.post_hook = post_hook + self.user_defined_post_hook = True + elif len(self.restore_value) > 0: + + def _post_hook(kwargs, exception): + for name in self.restore_value: + kwargs[name].copy_(self.restore_copies[name]) + self.restore_copies = {} + + self.post_hook = _post_hook + + self.perf_model = None + self.configs_top_k = 1.0 + self.early_config_prune = None + if prune_configs_by: + self.perf_model = prune_configs_by.get("perf_model", self.perf_model) + self.configs_top_k = prune_configs_by.get("top_k", self.configs_top_k) + self.early_config_prune = prune_configs_by.get("early_config_prune", self.early_config_prune) + + self.fn = fn + self.base_fn = fn + while not inspect.isfunction(self.base_fn): + self.base_fn = self.base_fn.fn + + self._do_bench = do_bench + self.num_warmups = warmup + self.num_reps = rep + self.use_cuda_graph = use_cuda_graph + + # If we got explicitly called via the old interface, raise a warning + # and proceed with the old behavior. + if warmup is not None or rep is not None or use_cuda_graph: + import warnings + warnings.warn(("warmup, rep, and use_cuda_graph parameters are deprecated. See " + "https://github.com/triton-lang/triton/pull/4496 for details."), DeprecationWarning, + stacklevel=1) + if use_cuda_graph: + from ..testing import do_bench_cudagraph + self._do_bench = lambda kernel_call, quantiles: do_bench_cudagraph( + kernel_call, + rep=rep if rep is not None else 100, + quantiles=quantiles, + ) + return + + import triton.testing + self._do_bench = lambda kernel_call, quantiles: triton.testing.do_bench( + kernel_call, + warmup=warmup if warmup is not None else 25, + rep=rep if rep is not None else 100, + quantiles=quantiles, + ) + return + + @cached_property + def do_bench(self): + if self._do_bench is None: + return driver.active.get_benchmarker() + return self._do_bench + + def _bench(self, *args, config, **meta): + from ..compiler.errors import CompileTimeAssertionFailure + + verbose = knobs.autotuning.print + if verbose: + print(f"Autotuning kernel {self.base_fn.__name__} with config {config}") + + # check for conflicts, i.e. meta-parameters both provided + # as kwargs and by the autotuner + conflicts = meta.keys() & config.kwargs.keys() + if conflicts: + raise ValueError(f"Conflicting meta-parameters: {', '.join(conflicts)}." + " Make sure that you don't re-define auto-tuned symbols.") + # augment meta-parameters with tunable ones + current = dict(meta, **config.all_kwargs()) + full_nargs = {**self.nargs, **current} + + def kernel_call(): + if config.pre_hook: + config.pre_hook(full_nargs) + self.pre_hook(full_nargs) + try: + self.fn.run( + *args, + **current, + ) + except Exception as e: + try: + self.post_hook(full_nargs, exception=e) + finally: + # Throw exception raised by `self.fn.run` + raise + + self.post_hook(full_nargs, exception=None) + + try: + return self.do_bench(kernel_call, quantiles=(0.5, 0.2, 0.8)) + except (OutOfResources, CompileTimeAssertionFailure, PTXASError) as e: + if verbose: + print(f"Autotuning failed with {e}") + return [float("inf"), float("inf"), float("inf")] + + def check_disk_cache(self, tuning_key, configs, bench_fn): + # We can't serialize prehooks, so just give up and run the benchmarks. + if not tuning_key or any(cfg.pre_hook for cfg in configs): + bench_fn() + return False + + from triton.compiler.compiler import make_backend + + fn = self.fn + while not isinstance(fn, JITFunction): + fn = fn.fn + + env_vars = get_cache_invalidating_env_vars() + cache_key = [ + triton_key(), + make_backend(driver.active.get_current_target()).hash(), + fn.cache_key, + str(sorted(env_vars.items())), + str(tuning_key), + ] + [str(c) for c in configs] + cache_key = hashlib.sha256("-".join(cache_key).encode("utf-8")).hexdigest() + cache = get_cache_manager(cache_key) + file_name = f"{fn.__name__[:150]}.autotune.json" + path = cache.get_file(file_name) + if path: + with open(path, "r") as cached_configs: + timings = json.load(cached_configs)["configs_timings"] + timings = {Config(**config): timing for config, timing in timings} + self.cache[tuning_key] = builtins.min(timings, key=timings.get) + self.configs_timings = timings + return True + + bench_fn() + cache.put( + json.dumps({ + "key": + tuning_key, + "configs_timings": + [(config.__dict__, timings) for config, timings in self.configs_timings.items() if not config.pre_hook], + }), file_name, binary=False) + return False + + def run(self, *args, **kwargs): + self.nargs = dict(zip(self.arg_names, args)) + used_cached_result = True + if len(self.configs) > 1: + all_args = {**self.nargs, **kwargs} + _args = {k: v for (k, v) in all_args.items() if k in self.arg_names} + key = [_args[key] for key in self.keys if key in _args] + for _, arg in _args.items(): + if hasattr(arg, "dtype"): + key.append(str(arg.dtype)) + key = tuple(key) + if key not in self.cache: + used_cached_result = False + pruned_configs = self.prune_configs(kwargs) + + def benchmark(): + bench_start = time.time() + timings = {config: self._bench(*args, config=config, **kwargs) for config in pruned_configs} + bench_end = time.time() + self.bench_time = bench_end - bench_start + self.cache[key] = builtins.min(timings, key=timings.get) + full_nargs = {**self.nargs, **kwargs, **self.cache[key].all_kwargs()} + self.pre_hook(full_nargs, reset_only=True) + self.configs_timings = timings + + if self.cache_results: + used_cached_result = self.check_disk_cache(key, pruned_configs, benchmark) + else: + benchmark() + + config = self.cache[key] + else: + config = self.configs[0] + self.best_config = config + if knobs.autotuning.print and not used_cached_result: + print(f"Triton autotuning for function {self.base_fn.__name__},\nwith key as {key},\n" + f"finished after {self.bench_time:.2f}s,\nbest config selected: {self.best_config};") + if config.pre_hook is not None: + full_nargs = {**self.nargs, **kwargs, **config.all_kwargs()} + config.pre_hook(full_nargs) + ret = self.fn.run( + *args, + **kwargs, + **config.all_kwargs(), + ) + self.nargs = None + return ret + + def prune_configs(self, kwargs: Dict) -> List[Config]: + pruned_configs = self.configs + if self.early_config_prune: + pruned_configs = self.early_config_prune(self.configs, self.nargs, **kwargs) + if not pruned_configs: + raise AutotunerError( + "No valid autotuner configs after pruning. `early_config_prune` should return at least one config.") + if self.perf_model: + top_k = self.configs_top_k + if isinstance(top_k, float) and top_k <= 1.0: + top_k = int(len(self.configs) * top_k) + elif not isinstance(top_k, int): + # Slice index must be an integer + raise TypeError("Error while pruning configs, top_k must be either 1) a float <= 1.0 or 2) an int") + + if len(pruned_configs) > top_k: + est_timing = { + config: self.perf_model( + **self.nargs, + **kwargs, + **config.all_kwargs(), + ) + for config in pruned_configs + } + pruned_configs = sorted(est_timing.keys(), key=lambda x: est_timing[x])[:top_k] + return pruned_configs + + def warmup(self, *args, **kwargs): + self.nargs = dict(zip(self.arg_names, args)) + ret = [] + for autotune_config in self.prune_configs(kwargs): + ret.append(self.fn.warmup( + *args, + **kwargs, + **autotune_config.all_kwargs(), + )) + self.nargs = None + return ret + + +class Config: + """ + An object that represents a possible kernel configuration for the auto-tuner to try. + + :ivar kwargs: a dictionary of meta-parameters to pass to the kernel as keyword arguments. + :type kwargs: dict[Str, Any] + :ivar num_warps: the number of warps to use for the kernel when compiled for GPUs. For example, if + `num_warps=8`, then each kernel instance will be automatically parallelized to + cooperatively execute using `8 * 32 = 256` threads. + :type num_warps: int + :ivar num_stages: the number of stages that the compiler should use when software-pipelining loops. + Mostly useful for matrix multiplication workloads on SM80+ GPUs. + :type num_stages: int + :ivar num_ctas: number of blocks in a block cluster. SM90+ only. + :type num_ctas: int + :type maxnreg: Optional[int] + :ivar maxnreg: maximum number of registers one thread can use. Corresponds + to ptx .maxnreg directive. Not supported on all platforms. + :ivar pre_hook: a function that will be called before the kernel is called. Parameters of this + function are args. + :ivar ir_override: filename of a user-defined IR (*.{ttgir|llir|ptx|amdgcn}). + """ + + def __init__(self, kwargs, num_warps=4, num_stages=3, num_ctas=1, maxnreg=None, pre_hook=None, ir_override=None): + self.kwargs = kwargs + self.num_warps = num_warps + self.num_ctas = num_ctas + self.num_stages = num_stages + self.maxnreg = maxnreg + self.pre_hook = pre_hook + self.ir_override = ir_override + + def __setstate__(self, state): + self.kwargs = state.get("kwargs", {}) + self.num_warps = state.get("num_warps", 4) + self.num_stages = state.get("num_stages", 3) + self.num_ctas = state.get("num_ctas", 1) + self.maxnreg = state.get("maxnreg", None) + self.pre_hook = state.get("pre_hook", None) + self.ir_override = state.get("ir_override", None) + + def all_kwargs(self): + return { + **self.kwargs, **{ + k: v + for (k, v) in ( + ("num_warps", self.num_warps), + ("num_ctas", self.num_ctas), + ("num_stages", self.num_stages), + ("maxnreg", self.maxnreg), + ("ir_override", self.ir_override), + ) if v is not None + } + } + + def __str__(self): + res = [] + for k, v in self.kwargs.items(): + res.append(f"{k}: {v}") + res.append(f"num_warps: {self.num_warps}") + res.append(f"num_ctas: {self.num_ctas}") + res.append(f"num_stages: {self.num_stages}") + res.append(f"maxnreg: {self.maxnreg}") + return ", ".join(res) + + def __hash__(self): + return hash((*self.all_kwargs().items(), self.pre_hook)) + + def __eq__(self, other): + self_tuple = tuple(( + *self.all_kwargs().items(), + self.pre_hook, + )) + other_tuple = tuple(( + *other.all_kwargs().items(), + other.pre_hook, + )) + return self_tuple == other_tuple + + +def autotune(configs, key, prune_configs_by=None, reset_to_zero=None, restore_value=None, pre_hook=None, post_hook=None, + warmup=None, rep=None, use_cuda_graph=False, do_bench=None, cache_results=False): + """ + Decorator for auto-tuning a :code:`triton.jit`'d function. + + .. highlight:: python + .. code-block:: python + + @triton.autotune(configs=[ + triton.Config(kwargs={'BLOCK_SIZE': 128}, num_warps=4), + triton.Config(kwargs={'BLOCK_SIZE': 1024}, num_warps=8), + ], + key=['x_size'] # the two above configs will be evaluated anytime + # the value of x_size changes + ) + @triton.jit + def kernel(x_ptr, x_size, BLOCK_SIZE: tl.constexpr): + ... + :note: When all the configurations are evaluated, the kernel will run multiple times. + This means that whatever value the kernel updates will be updated multiple times. + To avoid this undesired behavior, you can use the `reset_to_zero` argument, which + resets the value of the provided tensor to `zero` before running any configuration. + + If the environment variable :code:`TRITON_PRINT_AUTOTUNING` is set to + :code:`"1"`, Triton will print a message to stdout after autotuning each + kernel, including the time spent autotuning and the best configuration. + + :param configs: a list of :code:`triton.Config` objects + :type configs: list[triton.Config] + :param key: a list of argument names whose change in value will trigger the evaluation of all provided configs. + :type key: list[str] + :param prune_configs_by: a dict of functions that are used to prune configs, fields: + 'perf_model': performance model used to predicate running time with different configs, returns running time + 'top_k': number of configs to bench + 'early_config_prune': a function used to prune configs. It should have the signature + `prune_configs_by( configs: List[triton.Config], named_args: Dict[str, Any], **kwargs: Dict[str, Any]) -> List[triton.Config]:` + and return pruned configs. It should return at least one config. + :param reset_to_zero: a list of argument names whose value will be reset to zero before evaluating any configs. + :type reset_to_zero: list[str] + :param restore_value: a list of argument names whose value will be restored after evaluating any configs. + :type restore_value: list[str] + :param pre_hook: a function that will be called before the kernel is called. + This overrides the default pre_hook used for 'reset_to_zero' and 'restore_value'. + 'kwargs': a dict of all arguments passed to the kernel. + 'reset_only': a boolean indicating whether the pre_hook is called to reset the values only, without a corresponding post_hook. + :type pre_hook: lambda args, reset_only + :param post_hook: a function that will be called after the kernel is called. + This overrides the default post_hook used for 'restore_value'. + 'kwargs': a dict of all arguments passed to the kernel. + 'exception': the exception raised by the kernel in case of a compilation or runtime error. + :type post_hook: lambda args, exception + :param warmup: warmup time (in ms) to pass to benchmarking (deprecated). + :type warmup: int + :param rep: repetition time (in ms) to pass to benchmarking (deprecated). + :type rep: int + :param do_bench: a benchmark function to measure the time of each run. + :type do_bench: lambda fn, quantiles + :param cache_results: whether to cache autotune timings to disk. Defaults to False. + "type cache_results: bool + """ + + def decorator(fn): + return Autotuner(fn, fn.arg_names, configs, key, reset_to_zero, restore_value, pre_hook=pre_hook, + post_hook=post_hook, prune_configs_by=prune_configs_by, warmup=warmup, rep=rep, + use_cuda_graph=use_cuda_graph, do_bench=do_bench, cache_results=cache_results) + + return decorator + + +class Heuristics(KernelInterface): + + def __init__(self, fn, arg_names, values) -> None: + self.fn = fn + self.values = values + self.arg_names = arg_names + + def run(self, *args, **kwargs): + for v, heur in self.values.items(): + kwargs[v] = heur({**dict(zip(self.arg_names, args)), **kwargs}) + return self.fn.run(*args, **kwargs) + + +def heuristics(values): + """ + Decorator for specifying how the values of certain meta-parameters may be computed. + This is useful for cases where auto-tuning is prohibitively expensive, or just not applicable. + + .. highlight:: python + .. code-block:: python + + # smallest power-of-two >= x_size + @triton.heuristics(values={'BLOCK_SIZE': lambda args: triton.next_power_of_2(args['x_size'])}) + @triton.jit + def kernel(x_ptr, x_size, BLOCK_SIZE: tl.constexpr): + ... + :param values: a dictionary of meta-parameter names and functions that compute the value of the meta-parameter. + each such function takes a list of positional arguments as input. + :type values: dict[str, Callable[[dict[str, Any]], Any]] + """ + + def decorator(fn): + return Heuristics(fn, fn.arg_names, values) + + return decorator diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/runtime/build.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/runtime/build.py new file mode 100644 index 0000000000000000000000000000000000000000..786f51e54db77a5e0c04a42a72ce01060f436631 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/runtime/build.py @@ -0,0 +1,97 @@ +from __future__ import annotations + +import functools +import hashlib +import importlib.util +import logging +import os +import shutil +import subprocess +import sysconfig +import tempfile +import re + +from types import ModuleType + +from .cache import get_cache_manager +from .. import knobs + + +def _build(name: str, src: str, srcdir: str, library_dirs: list[str], include_dirs: list[str], libraries: list[str], + ccflags: list[str]) -> str: + if impl := knobs.build.impl: + return impl(name, src, srcdir, library_dirs, include_dirs, libraries) + suffix = sysconfig.get_config_var('EXT_SUFFIX') + so = os.path.join(srcdir, '{name}{suffix}'.format(name=name, suffix=suffix)) + cc = os.environ.get("CC") + if cc is None: + clang = shutil.which("clang") + gcc = shutil.which("gcc") + cc = gcc if gcc is not None else clang + if cc is None: + raise RuntimeError( + "Failed to find C compiler. Please specify via CC environment variable or set triton.knobs.build.impl.") + scheme = sysconfig.get_default_scheme() + # 'posix_local' is a custom scheme on Debian. However, starting Python 3.10, the default install + # path changes to include 'local'. This change is required to use triton with system-wide python. + if scheme == 'posix_local': + scheme = 'posix_prefix' + py_include_dir = sysconfig.get_paths(scheme=scheme)["include"] + custom_backend_dirs = knobs.build.backend_dirs + include_dirs = include_dirs + [srcdir, py_include_dir, *custom_backend_dirs] + # for -Wno-psabi, see https://gcc.gnu.org/bugzilla/show_bug.cgi?id=111047 + cc_cmd = [cc, src, "-O3", "-shared", "-fPIC", "-Wno-psabi", "-o", so] + cc_cmd += [_library_flag(lib) for lib in libraries] + cc_cmd += [f"-L{dir}" for dir in library_dirs] + cc_cmd += [f"-I{dir}" for dir in include_dirs if dir is not None] + cc_cmd.extend(ccflags) + subprocess.check_call(cc_cmd, stdout=subprocess.DEVNULL) + return so + + +def _library_flag(lib: str) -> str: + # Match .so files with optional version numbers (e.g., .so, .so.1, .so.513.50.1) + if re.search(r'\.so(\.\d+)*$', lib) or lib.endswith(".a"): + return f"-l:{lib}" + return f"-l{lib}" + + +@functools.lru_cache +def platform_key() -> str: + from platform import machine, system, architecture + return ",".join([machine(), system(), *architecture()]) + + +def _load_module_from_path(name: str, path: str) -> ModuleType: + spec = importlib.util.spec_from_file_location(name, path) + if not spec or not spec.loader: + raise RuntimeError(f"Failed to load newly compiled {name} from {path}") + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + return mod + + +def compile_module_from_src(src: str, name: str, library_dirs: list[str] | None = None, + include_dirs: list[str] | None = None, libraries: list[str] | None = None, + ccflags: list[str] | None = None) -> ModuleType: + key = hashlib.sha256((src + platform_key()).encode("utf-8")).hexdigest() + cache = get_cache_manager(key) + suffix = sysconfig.get_config_var("EXT_SUFFIX") + cache_path = cache.get_file(f"{name}{suffix}") + + if cache_path is not None: + try: + return _load_module_from_path(name, cache_path) + except (RuntimeError, ImportError): + log = logging.getLogger(__name__) + log.warning(f"Triton cache error: compiled module {name}.so could not be loaded") + + with tempfile.TemporaryDirectory() as tmpdir: + src_path = os.path.join(tmpdir, name + ".c") + with open(src_path, "w") as f: + f.write(src) + so = _build(name, src_path, tmpdir, library_dirs or [], include_dirs or [], libraries or [], ccflags or []) + with open(so, "rb") as f: + cache_path = cache.put(f.read(), f"{name}{suffix}", binary=True) + + return _load_module_from_path(name, cache_path) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/runtime/cache.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/runtime/cache.py new file mode 100644 index 0000000000000000000000000000000000000000..0442f00e68f5f907a4da56ebd7689e8c469219ef --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/runtime/cache.py @@ -0,0 +1,309 @@ +import json +import os +import uuid +from abc import ABC, abstractmethod +from typing import Dict, List, Optional +import base64 +import hashlib +import functools +import sysconfig + +from triton import __version__, knobs + + +class CacheManager(ABC): + + def __init__(self, key, override=False, dump=False): + pass + + @abstractmethod + def get_file(self, filename) -> Optional[str]: + pass + + @abstractmethod + def put(self, data, filename, binary=True) -> str: + pass + + @abstractmethod + def get_group(self, filename: str) -> Optional[Dict[str, str]]: + pass + + @abstractmethod + def put_group(self, filename: str, group: Dict[str, str]): + pass + + +class FileCacheManager(CacheManager): + + def __init__(self, key, override=False, dump=False): + self.key = key + self.lock_path = None + if dump: + self.cache_dir = knobs.cache.dump_dir + self.cache_dir = os.path.join(self.cache_dir, self.key) + self.lock_path = os.path.join(self.cache_dir, "lock") + os.makedirs(self.cache_dir, exist_ok=True) + elif override: + self.cache_dir = knobs.cache.override_dir + self.cache_dir = os.path.join(self.cache_dir, self.key) + else: + # create cache directory if it doesn't exist + self.cache_dir = knobs.cache.dir + if self.cache_dir: + self.cache_dir = os.path.join(self.cache_dir, self.key) + self.lock_path = os.path.join(self.cache_dir, "lock") + os.makedirs(self.cache_dir, exist_ok=True) + else: + raise RuntimeError("Could not create or locate cache dir") + + def _make_path(self, filename) -> str: + return os.path.join(self.cache_dir, filename) + + def has_file(self, filename) -> bool: + if not self.cache_dir: + raise RuntimeError("Could not create or locate cache dir") + return os.path.exists(self._make_path(filename)) + + def get_file(self, filename) -> Optional[str]: + if self.has_file(filename): + return self._make_path(filename) + else: + return None + + def get_group(self, filename: str) -> Optional[Dict[str, str]]: + grp_filename = f"__grp__{filename}" + if not self.has_file(grp_filename): + return None + grp_filepath = self._make_path(grp_filename) + with open(grp_filepath) as f: + grp_data = json.load(f) + child_paths = grp_data.get("child_paths", None) + # Invalid group data. + if child_paths is None: + return None + result = {} + for c, p in child_paths.items(): + if os.path.exists(p): + result[c] = p + return result + + # Note a group of pushed files as being part of a group + def put_group(self, filename: str, group: Dict[str, str]) -> str: + if not self.cache_dir: + raise RuntimeError("Could not create or locate cache dir") + grp_contents = json.dumps({"child_paths": group}) + grp_filename = f"__grp__{filename}" + return self.put(grp_contents, grp_filename, binary=False) + + def put(self, data, filename, binary=True) -> str: + if not self.cache_dir: + raise RuntimeError("Could not create or locate cache dir") + binary = isinstance(data, bytes) + if not binary: + data = str(data) + assert self.lock_path is not None + filepath = self._make_path(filename) + # Random ID to avoid any collisions + rnd_id = str(uuid.uuid4()) + # we use the PID in case a bunch of these around so we can see what PID made it + pid = os.getpid() + # use temp dir to be robust against program interruptions + temp_dir = os.path.join(self.cache_dir, f"tmp.pid_{pid}_{rnd_id}") + os.makedirs(temp_dir, exist_ok=True) + temp_path = os.path.join(temp_dir, filename) + + mode = "wb" if binary else "w" + with open(temp_path, mode) as f: + f.write(data) + # Replace is guaranteed to be atomic on POSIX systems if it succeeds + # so filepath cannot see a partial write + os.replace(temp_path, filepath) + os.removedirs(temp_dir) + return filepath + + +class RemoteCacheBackend: + """ + A backend implementation for accessing a remote/distributed cache. + """ + + def __init__(self, key: str): + pass + + @abstractmethod + def get(self, filenames: List[str]) -> Dict[str, bytes]: + pass + + @abstractmethod + def put(self, filename: str, data: bytes): + pass + + +class RedisRemoteCacheBackend(RemoteCacheBackend): + + def __init__(self, key): + import redis + self._key = key + self._key_fmt = knobs.cache.redis.key_format + self._redis = redis.Redis( + host=knobs.cache.redis.host, + port=knobs.cache.redis.port, + ) + + def _get_key(self, filename: str) -> str: + return self._key_fmt.format(key=self._key, filename=filename) + + def get(self, filenames: List[str]) -> Dict[str, str]: + results = self._redis.mget([self._get_key(f) for f in filenames]) + return {filename: result for filename, result in zip(filenames, results) if result is not None} + + def put(self, filename: str, data: bytes) -> Dict[str, bytes]: + self._redis.set(self._get_key(filename), data) + + +class RemoteCacheManager(CacheManager): + + def __init__(self, key, override=False, dump=False): + # Setup backend pointed too by `TRITON_REMOTE_CACHE_BACKEND`. + remote_cache_cls = knobs.cache.remote_manager_class + if not remote_cache_cls: + raise RuntimeError( + "Unable to instantiate RemoteCacheManager, TRITON_REMOTE_CACHE_BACKEND doesn't point to a valid class") + self._backend = remote_cache_cls(key) + + self._override = override + self._dump = dump + + # Use a `FileCacheManager` to materialize remote cache paths locally. + self._file_cache_manager = FileCacheManager(key, override=override, dump=dump) + + def _materialize(self, filename: str, data: bytes): + # We use a backing `FileCacheManager` to provide the materialized data. + return self._file_cache_manager.put(data, filename, binary=True) + + def get_file(self, filename: str) -> Optional[str]: + # We don't handle the dump/override cases. + if self._dump or self._override: + return self._file_cache_manager.get_file(filename) + + # We always check the remote cache backend -- even if our internal file- + # based cache has the item -- to make sure LRU accounting works as + # expected. + results = self._backend.get([filename]) + if len(results) == 0: + return None + (_, data), = results.items() + return self._materialize(filename, data) + + def put(self, data, filename: str, binary=True) -> str: + # We don't handle the dump/override cases. + if self._dump or self._override: + return self._file_cache_manager.put(data, filename, binary=binary) + + if not isinstance(data, bytes): + data = str(data).encode("utf-8") + self._backend.put(filename, data) + return self._materialize(filename, data) + + def get_group(self, filename: str) -> Optional[Dict[str, str]]: + # We don't handle the dump/override cases. + if self._dump or self._override: + return self._file_cache_manager.get_group(filename) + + grp_filename = f"__grp__{filename}" + grp_filepath = self.get_file(grp_filename) + if grp_filepath is None: + return None + with open(grp_filepath) as f: + grp_data = json.load(f) + child_paths = grp_data.get("child_paths", None) + + result = None + + # Found group data. + if child_paths is not None: + result = {} + for child_path, data in self._backend.get(child_paths).items(): + result[child_path] = self._materialize(child_path, data) + + return result + + def put_group(self, filename: str, group: Dict[str, str]): + # We don't handle the dump/override cases. + if self._dump or self._override: + return self._file_cache_manager.put_group(filename, group) + + grp_contents = json.dumps({"child_paths": sorted(list(group.keys()))}) + grp_filename = f"__grp__{filename}" + return self.put(grp_contents, grp_filename) + + +def _base32(key): + # Assume key is a hex string. + return base64.b32encode(bytes.fromhex(key)).decode("utf-8").rstrip("=") + + +def get_cache_manager(key) -> CacheManager: + cls = knobs.cache.manager_class or FileCacheManager + return cls(_base32(key)) + + +def get_override_manager(key) -> CacheManager: + cls = knobs.cache.manager_class or FileCacheManager + return cls(_base32(key), override=True) + + +def get_dump_manager(key) -> CacheManager: + cls = knobs.cache.manager_class or FileCacheManager + return cls(_base32(key), dump=True) + + +def make_so_cache_key(version_hash, signature, constants, ids, **kwargs): + # Get unique key for the compiled code + signature = {k: 'ptr' if v[0] == '*' else v for k, v in signature.items()} + key = f"{version_hash}-{''.join(signature.values())}-{constants}-{ids}" + for kw in kwargs: + key = f"{key}-{kwargs.get(kw)}" + key = hashlib.sha256(key.encode("utf-8")).hexdigest() + return _base32(key) + + +@functools.lru_cache() +def triton_key(): + import pkgutil + TRITON_PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + contents = [] + # frontend + with open(__file__, "rb") as f: + contents += [hashlib.sha256(f.read()).hexdigest()] + # compiler + path_prefixes = [ + (os.path.join(TRITON_PATH, "compiler"), "triton.compiler."), + (os.path.join(TRITON_PATH, "backends"), "triton.backends."), + ] + for path, prefix in path_prefixes: + for lib in pkgutil.walk_packages([path], prefix=prefix): + with open(lib.module_finder.find_spec(lib.name).origin, "rb") as f: + contents += [hashlib.sha256(f.read()).hexdigest()] + + # backend + libtriton_hash = hashlib.sha256() + ext = sysconfig.get_config_var("EXT_SUFFIX").split(".")[-1] + with open(os.path.join(TRITON_PATH, "_C", f"libtriton.{ext}"), "rb") as f: + while True: + chunk = f.read(1024**2) + if not chunk: + break + libtriton_hash.update(chunk) + contents.append(libtriton_hash.hexdigest()) + # language + language_path = os.path.join(TRITON_PATH, 'language') + for lib in pkgutil.walk_packages([language_path], prefix="triton.language."): + with open(lib.module_finder.find_spec(lib.name).origin, "rb") as f: + contents += [hashlib.sha256(f.read()).hexdigest()] + return f'{__version__}' + '-'.join(contents) + + +def get_cache_key(src, backend, backend_options, env_vars): + key = f"{triton_key()}-{src.hash()}-{backend.hash()}-{backend_options.hash()}-{str(sorted(env_vars.items()))}" + return key diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/runtime/driver.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/runtime/driver.py new file mode 100644 index 0000000000000000000000000000000000000000..0092156792991984045e6158678ec85f74b1776a --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/runtime/driver.py @@ -0,0 +1,38 @@ +from __future__ import annotations + +from ..backends import backends, DriverBase + + +def _create_driver() -> DriverBase: + active_drivers = [x.driver for x in backends.values() if x.driver.is_active()] + if len(active_drivers) != 1: + raise RuntimeError(f"{len(active_drivers)} active drivers ({active_drivers}). There should only be one.") + return active_drivers[0]() + + +class DriverConfig: + + def __init__(self) -> None: + self._default: DriverBase | None = None + self._active: DriverBase | None = None + + @property + def default(self) -> DriverBase: + if self._default is None: + self._default = _create_driver() + return self._default + + @property + def active(self) -> DriverBase: + if self._active is None: + self._active = self.default + return self._active + + def set_active(self, driver: DriverBase) -> None: + self._active = driver + + def reset_active(self) -> None: + self._active = self.default + + +driver = DriverConfig() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/runtime/errors.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/runtime/errors.py new file mode 100644 index 0000000000000000000000000000000000000000..d9a1b60bd6d9debf4d3df57235b87b08bd9330f7 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/runtime/errors.py @@ -0,0 +1,46 @@ +from ..errors import TritonError +from typing import Optional + + +class InterpreterError(TritonError): + + def __init__(self, error_message: Optional[str] = None): + self.error_message = error_message + + def __str__(self) -> str: + return self.error_message or "" + + +class OutOfResources(TritonError): + + def __init__(self, required, limit, name): + self.required = required + self.limit = limit + self.name = name + + def __str__(self) -> str: + return f"out of resource: {self.name}, Required: {self.required}, Hardware limit: {self.limit}. Reducing block sizes or `num_stages` may help." + + def __reduce__(self): + # this is necessary to make CompilationError picklable + return (type(self), (self.required, self.limit, self.name)) + + +class PTXASError(TritonError): + + def __init__(self, error_message: Optional[str] = None): + self.error_message = error_message + + def __str__(self) -> str: + error_message = self.error_message or "" + return f"PTXAS error: {error_message}" + + +class AutotunerError(TritonError): + + def __init__(self, error_message: Optional[str] = None): + self.error_message = error_message + + def __str__(self) -> str: + error_message = self.error_message or "" + return f"Autotuner error: {error_message}" diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/runtime/interpreter.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/runtime/interpreter.py new file mode 100644 index 0000000000000000000000000000000000000000..cd871cb2e1f1205bf9368235cd6193435aaff12d --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/runtime/interpreter.py @@ -0,0 +1,1492 @@ +from __future__ import annotations +import ast +import textwrap +import inspect +from typing import Tuple, List, Dict, Callable, TypeVar + +import math +import numpy as np + +import triton +import triton.language as tl +import dataclasses +from dataclasses import dataclass + +from triton.language.semantic import TritonSemantic +from triton.runtime.jit import KernelInterface +from triton.tools.tensor_descriptor import TensorDescriptor +from .errors import InterpreterError +from functools import partial +from .._C.libtriton import interpreter as _interpreter +from .._C.libtriton import ir as _ir + +T = TypeVar("T") + + +@dataclass +class TensorHandle: + ''' + data: numpy array + dtype: triton type, either pointer_type or scalar_type. + we don't store block_type here because the shape information is already available in the data field + attr: a dictionary of attributes + ''' + data: np.array + dtype: tl.dtype + attr: Dict = dataclasses.field(default_factory=dict) + + def __post_init__(self): + if not _validate_np_data_size(self.data, self.dtype): + raise ValueError(f"numpy data itemsize ({self.data.itemsize * 8} bits) exceeds dtype primitive_bitwidth " + f"({self.dtype.primitive_bitwidth} bits) for triton type {self.dtype}") + + def __bool__(self): + return bool(self.data.all()) + + def get_element_ty(self): + dtype = self.dtype + while hasattr(dtype, "element_ty"): + dtype = dtype.element_ty + return dtype + + def clone(self): + return TensorHandle(self.data.copy(), self.dtype) + + def set_attr(self, key, value): + self.attr[key] = value + + +class BlockPointerHandle: + + def __init__(self, base, shape, strides, offsets, block_shape, order): + self.base = base + self.shape = shape + self.strides = strides + self.offsets = offsets + self.block_shape = block_shape + self.order = order + + def materialize_pointers(self, boundary_check): + dtype_tt = self.base.get_element_ty() + n_bytes = dtype_tt.primitive_bitwidth // 8 + ptrs = np.broadcast_to(self.base.data, self.block_shape) + masks = np.ones(self.block_shape, dtype=bool) + for dim in range(len(self.block_shape)): + bcast_dims = [1] * len(self.block_shape) + bcast_dims[dim] = self.block_shape[dim] + off = (self.offsets[dim].data + np.arange(self.block_shape[dim])).reshape(bcast_dims) + ptrs = ptrs + (n_bytes * off * self.strides[dim].data).astype(np.uint64) + if dim in boundary_check: + masks = masks & (off < self.shape[dim].data) & (off >= 0) + ptrs = TensorHandle(ptrs, self.base.dtype.scalar) + return ptrs, masks + + +class TensorDescHandle: + + def __init__(self, base: TensorHandle, shape: List[TensorHandle], strides: List[TensorHandle], + block_shape: List[int], padding): + self.base = base + self.ndim = len(shape) + self.shape = shape + self.strides = strides + self.block_shape = block_shape + self.padding = padding + + def validate(self): + assert self.base.data.item() % 16 == 0, "base must be 16-byte aligned" + assert len(self.strides) == self.ndim + assert len(self.block_shape) == self.ndim + assert self.ndim >= 1, "descriptor cannot be 0 dimensional" + + scalar_ty = self.base.dtype.element_ty + itemsize = scalar_ty.primitive_bitwidth // 8 + for stride in self.strides[:-1]: + byte_stride = stride.data.item() * itemsize + assert byte_stride % 16 == 0, "stride must be 16-byte aligned" + assert self.strides[-1].data.item() == 1, "last dim must be contiguous" + + def materialize_pointers(self, offsets: List[TensorHandle]): + assert len(offsets) == self.ndim + scalar_ty = self.base.dtype.element_ty + itemsize = scalar_ty.primitive_bitwidth // 8 + assert (offsets[-1].data * itemsize) % 16 == 0, "block offset start must be 16-byte aligned" + + ptrs = np.broadcast_to(self.base.data, self.block_shape) + masks = np.ones(self.block_shape, dtype=bool) + for dim in range(len(self.block_shape)): + bcast_dims = [1] * len(self.block_shape) + bcast_dims[dim] = self.block_shape[dim] + off = (offsets[dim].data + np.arange(self.block_shape[dim])).reshape(bcast_dims) + ptrs = ptrs + (itemsize * off * self.strides[dim].data).astype(np.uint64) + masks = masks & (0 <= off) & (off < self.shape[dim].data) + assert ptrs.dtype == np.uint64 + ptrs = TensorHandle(ptrs, self.base.dtype.scalar) + return ptrs, masks + + +@dataclass(frozen=True) +class InterpreterOptions: + extern_libs: dict = None + debug: bool = False + sanitize_overflow: bool = True + arch: str = None + supported_fp8_dtypes: Tuple[str] = ("fp8e5", "fp8e5b16", "fp8e4nv", "fp8e4b8", "fp8e4b15") + deprecated_fp8_dot_operand_dtypes: Tuple[str] = () + default_dot_input_precision: str = "tf32" + allowed_dot_input_precisions: Tuple[str] = ("tf32", "tf32x3", "ieee") + max_num_imprecise_acc_default: int = 0 + backend_name: str = "interpreter" + + +def _validate_np_data_size(np_array, tl_dtype): + if isinstance(tl_dtype, tl.pointer_type): + return True + + np_dtype_bitwidth = np_array.itemsize * 8 + tl_dtype_bitwidth = tl_dtype.primitive_bitwidth + + # numpy lowest itemsize is at least 8 bits + if tl_dtype_bitwidth < 8: + tl_dtype_bitwidth = 8 + + if np_dtype_bitwidth > tl_dtype_bitwidth: + return False + return True + + +def _get_signed_np_dtype(dtype): + if dtype == np.uint8: + return np.int8 + if dtype == np.uint16: + return np.int16 + if dtype == np.uint32: + return np.int32 + if dtype == np.uint64: + return np.int64 + return dtype + + +def _get_np_dtype(tt_dtype): + if isinstance(tt_dtype, tl.pointer_type): + return np.dtype(np.uint64) + np_types = { + tl.int1: np.dtype(bool), + tl.float16: np.dtype(np.float16), + tl.float32: np.dtype(np.float32), + tl.float64: np.dtype(np.float64), + tl.int8: np.dtype(np.int8), + tl.uint8: np.dtype(np.uint8), + tl.int16: np.dtype(np.int16), + tl.uint16: np.dtype(np.uint16), + tl.int32: np.dtype(np.int32), + tl.uint32: np.dtype(np.uint32), + tl.int64: np.dtype(np.int64), + tl.uint64: np.dtype(np.uint64), + # bfloat16 types are stored as uint16 + tl.bfloat16: np.dtype(np.uint16), + # float8 types are stored as uint8 + tl.float8e5: np.dtype(np.uint8), + tl.float8e5b16: np.dtype(np.uint8), + tl.float8e4nv: np.dtype(np.uint8), + tl.float8e4b8: np.dtype(np.uint8), + tl.float8e4b15: np.dtype(np.uint8), + } + if isinstance(tt_dtype, tl.block_type): + if isinstance(tt_dtype.element_ty, tl.pointer_type): + return np.dtype(np.uint64) + return np_types[tt_dtype.element_ty] + return np_types[tt_dtype] + + +def _convert_float(input, input_dtype, output_dtype, rounding_mode): + input_uint_dtype = getattr(np, f"uint{input_dtype.primitive_bitwidth}") + output_unint_dtype = getattr(np, f"uint{output_dtype.primitive_bitwidth}") + input_bin = np.frombuffer(input.tobytes(), dtype=input_uint_dtype) + sign = (input_bin >> (input_dtype.primitive_bitwidth - 1)) & 0x01 + input_exponent_width = input_dtype.primitive_bitwidth - input_dtype.fp_mantissa_width - 1 + output_exponent_width = output_dtype.primitive_bitwidth - output_dtype.fp_mantissa_width - 1 + significand = input_bin & ((1 << input_dtype.fp_mantissa_width) - 1) + bias_input = input_dtype.exponent_bias + bias_output = output_dtype.exponent_bias + exponent = ((input_bin >> input_dtype.fp_mantissa_width) & ((1 << input_exponent_width) - 1)).astype(np.int32) + subnormal_index = exponent == 0 + if np.any(subnormal_index): + # Credit to Phil: phil@openai.com + # subnormal repr: ((-1.0)**sign) * (2.0**(1 - exp_bias)) * (2^(m0) + 2^(m1) + ... + 2^(mn)) + # where m0, m1, ..., mn are the 1-bit of the mantissa + # convert it to normal repr: ((-1.0)**sign) * (2.0**(1 + m0 - exp_bias)) * (1 + 2^(m1 - m0) + ... + 2^(mn - m0)) + bit_pos = np.zeros_like(input_bin, dtype=np.int32) + # Find the most significant bit of the mantissa in the significand + for i in range(input_dtype.fp_mantissa_width): + bit_index = ((significand >> i) & 0x01) + # pos should be >= 1 + bit_pos[bit_index == 1] = input_dtype.fp_mantissa_width - i + zero_significand_index = significand == 0 + exponent[subnormal_index] = 1 - bit_pos[subnormal_index] + # 0 significand and subnormal should be treated as 0 + exponent[zero_significand_index & subnormal_index] = bias_input - bias_output + significand[subnormal_index] = (significand[subnormal_index] << bit_pos[subnormal_index]) & ( + (1 << input_dtype.fp_mantissa_width) - 1) + # Prevent overflow and underflow + exponent_output = np.maximum(0, np.minimum((exponent - bias_input + bias_output), (1 << output_exponent_width) - 1)) + exponent_output = exponent_output.astype(output_unint_dtype) + sign_output = sign.astype(output_unint_dtype) + if input_dtype.primitive_bitwidth > output_dtype.primitive_bitwidth: # Downcast + significand_output = (significand >> (input_dtype.fp_mantissa_width - output_dtype.fp_mantissa_width)) & ( + (1 << output_dtype.fp_mantissa_width) - 1) + if rounding_mode == _ir.ROUNDING_MODE.RTNE: # Round to nearst even + # find the cut-off bit + cut_off = significand & (1 << (input_dtype.fp_mantissa_width - output_dtype.fp_mantissa_width - 1)) + significand_output = significand_output + (cut_off > 0) + significand_output = significand_output.astype(output_unint_dtype) + else: # Upcast + significand_output = (significand.astype(output_unint_dtype) << + (output_dtype.fp_mantissa_width - input_dtype.fp_mantissa_width)) & ( + (1 << output_dtype.fp_mantissa_width) - 1) + subnormal_index = exponent_output == 0 + if np.any(subnormal_index): # underflow + # normal repr: ((-1.0)**sign) * (2.0**(exp - exp_bias_input)) * (1 + 2^(m0) + 2^(m1) + ... + 2^(mn)) + # where m0, m1, ..., mn are the 1-bit of the mantissa + # shift = (1 - exp_bias_output) - (exp - exp_bias_input) + # convert it to subnormal repr: ((-1.0)**sign) * (2.0**(1 - exp_bias_output)) * (2^(-shift) + 2^(m0 - shift) + 2^(m1 - shift) + ... + 2^(mn - shift)) + exponent = ((input_bin >> input_dtype.fp_mantissa_width) & ((1 << input_exponent_width) - 1)).astype(np.int32) + non_zero_exponent_index = exponent != 0 + # If the original exponent is not zero, we still need to shift the significand and consider the 1.0 part in mantissa + subnormal_index = subnormal_index & non_zero_exponent_index + shift = np.zeros_like(input_bin, dtype=np.int32) + shift[subnormal_index] = (1 - bias_output) - (exponent[subnormal_index] - bias_input) + significand_output[subnormal_index] = (significand_output[subnormal_index] >> shift[subnormal_index]) | ( + 1 << (output_dtype.fp_mantissa_width - shift[subnormal_index])) + output = (sign_output << (output_dtype.primitive_bitwidth - 1)) | ( + exponent_output << output_dtype.fp_mantissa_width) | significand_output + return output.reshape(input.shape) + + +def _erf(x): + # Numpy does not support erf + return math.erf(x) + + +def _umulhi_64(a, b): + # Numpy does not support 128-bit multiplication + # So we have to implement it manually + return (int(a) * int(b)) >> 64 + + +np_erf_fp32 = np.vectorize(_erf, otypes=[np.float32]) +np_erf_fp64 = np.vectorize(_erf, otypes=[np.float64]) +np_umulhi_u64 = np.vectorize(_umulhi_64, otypes=[np.uint64]) + + +class ExtraFunctions: + + @staticmethod + def _convert_custom_types(input, dst_ty, fp_downcast_rounding, _semantic): + return tl.tensor(_semantic.builder.create_fp_to_fp(input.handle, dst_ty, fp_downcast_rounding), dst_ty) + + +class InterpreterBuilder: + ir_sem_to_interpreter_sem = { + _ir.MEM_SEMANTIC.ACQUIRE: _interpreter.MEM_SEMANTIC.ACQUIRE, + _ir.MEM_SEMANTIC.RELEASE: _interpreter.MEM_SEMANTIC.RELEASE, + _ir.MEM_SEMANTIC.RELAXED: _interpreter.MEM_SEMANTIC.RELAXED, + _ir.MEM_SEMANTIC.ACQUIRE_RELEASE: _interpreter.MEM_SEMANTIC.ACQUIRE_RELEASE, + } + + ir_rmw_op_to_interpreter_rmw_op = { + _ir.ATOMIC_OP.ADD: _interpreter.RMW_OP.ADD, + _ir.ATOMIC_OP.FADD: _interpreter.RMW_OP.FADD, + _ir.ATOMIC_OP.MIN: _interpreter.RMW_OP.MIN, + _ir.ATOMIC_OP.UMIN: _interpreter.RMW_OP.UMIN, + _ir.ATOMIC_OP.MAX: _interpreter.RMW_OP.MAX, + _ir.ATOMIC_OP.UMAX: _interpreter.RMW_OP.UMAX, + _ir.ATOMIC_OP.AND: _interpreter.RMW_OP.AND, + _ir.ATOMIC_OP.OR: _interpreter.RMW_OP.OR, + _ir.ATOMIC_OP.XOR: _interpreter.RMW_OP.XOR, + _ir.ATOMIC_OP.XCHG: _interpreter.RMW_OP.XCHG, + } + + def __init__(self) -> None: + self.arch = None + self.options = InterpreterOptions() + self.codegen_fns = {} + self.codegen_fns["convert_custom_types"] = ExtraFunctions._convert_custom_types + self.codegen_fns["min_dot_size"] = lambda lhsType, rhsType: (1, 1, 1) + + def set_grid_idx(self, x, y, z): + if not x < self.grid_dim[0]: + raise ValueError("x >= grid_dim[0]") + if not y < self.grid_dim[1]: + raise ValueError("y >= grid_dim[1]") + if not z < self.grid_dim[2]: + raise ValueError("z >= grid_dim[2]") + self.grid_idx = (x, y, z) + + def set_grid_dim(self, nx, ny, nz): + self.grid_dim = (nx, ny, nz) + + # constants + + def get_half_ty(self): + return tl.float16 + + def get_bf16_ty(self): + return tl.bfloat16 + + def get_float_ty(self): + return tl.float32 + + def get_double_ty(self): + return tl.float64 + + def get_int1_ty(self): + return tl.int1 + + def get_int8_ty(self): + return tl.int8 + + def get_uint8_ty(self): + return tl.uint8 + + def get_int16_ty(self): + return tl.int16 + + def get_uint16_ty(self): + return tl.uint16 + + def get_int32_ty(self): + return tl.int32 + + def get_uint32_ty(self): + return tl.uint32 + + def get_int64_ty(self): + return tl.int64 + + def get_uint64_ty(self): + return tl.uint64 + + def get_fp8e4nv_ty(self): + return tl.float8e4nv + + def get_fp8e4b15_ty(self): + return tl.float8e4b15 + + def get_fp8e4b8_ty(self): + return tl.float8e4b8 + + def get_fp8e5_ty(self): + return tl.float8e5 + + def get_fp8e5b16_ty(self): + return tl.float8e5b16 + + def get_ptr_ty(self, elt_ty, addr_space): + return tl.pointer_type(elt_ty, addr_space) + + def get_block_ty(self, dtype, shape): + return tl.block_type(dtype, shape) + + def get_int1(self, value): + return TensorHandle(np.array([value], dtype=np.bool_), tl.int1) + + def get_uint8(self, value): + return TensorHandle(np.array([value], dtype=np.uint8), tl.uint8) + + def get_int8(self, value): + return TensorHandle(np.array([value], dtype=np.int8), tl.int8) + + def get_uint16(self, value): + return TensorHandle(np.array([value], dtype=np.uint16), tl.uint16) + + def get_int16(self, value): + return TensorHandle(np.array([value], dtype=np.int16), tl.int16) + + def get_uint32(self, value): + return TensorHandle(np.array([value], dtype=np.uint32), tl.uint32) + + def get_int32(self, value): + return TensorHandle(np.array([value], dtype=np.int32), tl.int32) + + def get_uint64(self, value): + return TensorHandle(np.array([value], dtype=np.uint64), tl.uint64) + + def get_int64(self, value): + return TensorHandle(np.array([value], dtype=np.int64), tl.int64) + + def get_fp16(self, value): + return TensorHandle(np.array([value], dtype=np.float16), tl.float16) + + def get_fp32(self, value): + return TensorHandle(np.array([value], dtype=np.float32), tl.float32) + + def get_fp64(self, value): + return TensorHandle(np.array([value], dtype=np.float64), tl.float64) + + def get_null_value(self, type): + return TensorHandle(np.array([0], dtype=_get_np_dtype(type)), type) + + # programming model + def create_get_program_id(self, axis): + if self.grid_idx is None: + raise ValueError("grid_idx is None") + return TensorHandle(np.array([self.grid_idx[axis]], dtype=np.int32), tl.int32) + + def create_get_num_programs(self, axis): + return TensorHandle(np.array([self.grid_dim[axis]], dtype=np.int32), tl.int32) + + # memory ops + def create_load(self, ptr, _0, _1, is_volatile): + mask = TensorHandle(np.ones_like(ptr.data, dtype=bool), tl.int1) + other = None + return self.create_masked_load(ptr, mask, other, _0, _1, is_volatile) + + def create_store(self, ptr, val, _0, _1): + mask = TensorHandle(np.ones_like(ptr.data, dtype=bool), tl.int1) + return self.create_masked_store(ptr, val, mask, None, None) + + def create_masked_load(self, ptrs, mask, other, cache_modifier, eviction_policy, is_volatile): + dtype_tt = ptrs.get_element_ty() + dtype_np = _get_np_dtype(dtype_tt) + if other is None: + other = TensorHandle(np.zeros_like(ptrs.data, dtype=dtype_np), dtype_tt) + ret = _interpreter.load(ptrs.data, mask.data, other.data, dtype_np) + return TensorHandle(ret, dtype_tt) + + def create_masked_store(self, ptrs, value, mask, cache_modifier, eviction_policy): + return _interpreter.store(ptrs.data, value.data, mask.data) + + # casting ops + def cast_impl(self, src, dst_type): + src_element_type = src.dtype.scalar + dst_element_type = dst_type.scalar + if (src_element_type == tl.bfloat16 and dst_element_type == tl.float32) or \ + (src_element_type == tl.float32 and dst_element_type == tl.bfloat16): + data = _convert_float(src.data, src_element_type, dst_element_type, None).view(_get_np_dtype(dst_type)) + return TensorHandle(data, dst_type.scalar) + else: + return TensorHandle(src.data.astype(_get_np_dtype(dst_type)), dst_type.scalar) + + create_si_to_fp = lambda self, src, dst_type: self.cast_impl(src, dst_type) + create_ui_to_fp = lambda self, src, dst_type: self.cast_impl(src, dst_type) + create_fp_to_si = lambda self, src, dst_type: self.cast_impl(src, dst_type) + create_fp_to_ui = lambda self, src, dst_type: self.cast_impl(src, dst_type) + create_fp_ext = lambda self, src, dst_type: self.cast_impl(src, dst_type) + create_fp_trunc = lambda self, src, dst_type: self.cast_impl(src, dst_type) + create_int_cast = lambda self, src, dst_type, is_signed: self.cast_impl(src, dst_type) + + def create_fp_to_fp(self, src, dst_type, rounding_mode): + src_element_type = src.dtype.scalar + dst_element_type = dst_type.scalar + data = _convert_float(src.data, src_element_type, dst_element_type, rounding_mode).view(_get_np_dtype(dst_type)) + return TensorHandle(data, dst_type.scalar) + + def create_bitcast(self, src, dst_type): + return TensorHandle(src.data.view(_get_np_dtype(dst_type)), dst_type.scalar) + + # binary operators + def binary_op(self, lhs, rhs, op): + output = op(lhs.data, rhs.data) + tl_dtype = lhs.dtype.scalar + + if not _validate_np_data_size(output, tl_dtype): + output = output.astype(_get_np_dtype(tl_dtype)) + + return TensorHandle(output, tl_dtype) + + create_fadd = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.add) + create_fmul = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.multiply) + create_fdiv = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.divide) + create_frem = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.fmod) + create_fsub = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.subtract) + create_mul = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.multiply) + create_precise_divf = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.divide) + create_sdiv = lambda self, lhs, rhs: self.create_idiv(lhs, rhs) + create_udiv = lambda self, lhs, rhs: self.create_idiv(lhs, rhs) + # LLVM has 'numpy.fmod', not 'numpy.remainder', semantics on integer remainders. + create_srem = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.fmod) + create_urem = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.fmod) + create_add = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.add) + create_sub = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.subtract) + create_shl = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.left_shift) + create_lshr = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.right_shift) + create_minsi = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.minimum) + create_minui = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.minimum) + create_minimumf = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.minimum) + create_minnumf = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.minimum) + create_maxsi = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.maximum) + create_maxui = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.maximum) + create_maximumf = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.maximum) + create_maxnumf = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.maximum) + create_icmpSLE = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.less_equal) + create_icmpSLT = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.less) + create_icmpSGE = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.greater_equal) + create_icmpSGT = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.greater) + create_icmpULE = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.less_equal) + create_icmpULT = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.less) + create_icmpUGE = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.greater_equal) + create_icmpUGT = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.greater) + create_icmpEQ = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.equal) + create_icmpNE = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.not_equal) + create_fcmpOLT = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.less) + create_fcmpOGT = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.greater) + create_fcmpOLE = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.less_equal) + create_fcmpOGE = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.greater_equal) + create_fcmpOEQ = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.equal) + create_fcmpONE = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.not_equal) + create_fcmpULT = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.less) + create_fcmpUGT = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.greater) + create_fcmpULE = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.less_equal) + create_fcmpUGE = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.greater_equal) + create_fcmpUEQ = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.equal) + create_fcmpUNE = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.not_equal) + create_and = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.bitwise_and) + create_xor = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.bitwise_xor) + create_or = lambda self, lhs, rhs: self.binary_op(lhs, rhs, np.bitwise_or) + create_int_to_ptr = create_bitcast + create_ptr_to_int = create_bitcast + + def create_idiv(self, lhs, rhs): + # Triton has IEEE, not numpy/torch, semantics for %, and those carry + # through to //, so we have to use a nonstandard expression to get a + # reference result for //. + return TensorHandle((lhs.data - np.fmod(lhs.data, rhs.data)) // rhs.data, lhs.dtype.scalar) + + def create_ashr(self, lhs, rhs): + # Triton's rshift operator depends on the signedness of the left operand + lhs_dtype = _get_signed_np_dtype(lhs.data.dtype) + rhs_dtype = _get_signed_np_dtype(rhs.data.dtype) + lhs.data = lhs.data.astype(lhs_dtype) + rhs.data = rhs.data.astype(rhs_dtype) + return self.binary_op(lhs, rhs, np.right_shift) + + def create_umulhi(self, lhs, rhs): + dtype = lhs.data.dtype + if dtype == np.int64 or dtype == np.uint64: + return TensorHandle(np_umulhi_u64(lhs.data, rhs.data), lhs.dtype.scalar) + else: + compute_dtype = getattr(np, f"uint{dtype.itemsize * 8 * 2}") + lhs_data = lhs.data.astype(compute_dtype) + rhs_data = rhs.data.astype(compute_dtype) + ret_data = np.multiply(lhs_data, rhs_data) >> (dtype.itemsize * 8) + return TensorHandle(ret_data.astype(dtype), lhs.dtype.scalar) + + # ternary functions + def ternary_op(self, lhs, rhs, other, op): + output = op(lhs.data, rhs.data, other.data) + tl_dtype = other.dtype.scalar + + if not _validate_np_data_size(output, tl_dtype): + output = output.astype(_get_np_dtype(tl_dtype)) + + return TensorHandle(output, tl_dtype) + + create_clampf = lambda self, arg, lo, hi, propagate_nans: self.ternary_op(arg, lo, hi, np.clip) + create_select = lambda self, cond, lhs, rhs: self.ternary_op(cond, lhs, rhs, np.where) + + def create_fma(self, x, y, z): + return TensorHandle(x.data * y.data + z.data, z.dtype.scalar) + + # unary functions + def unary_op(self, arg, op): + return TensorHandle(op(arg.data), arg.dtype.scalar) + + def create_fabs(self, arg): + # Mask out the sign bit based on the primitive length + dtype_tt = arg.dtype + mask_bitwidth = dtype_tt.primitive_bitwidth - 1 + np_uint_dtype = getattr(np, f"uint{dtype_tt.primitive_bitwidth}") + data = arg.data.view(np_uint_dtype) + mask = (1 << mask_bitwidth) - 1 + ret = (data & mask).view(_get_np_dtype(dtype_tt)) + return TensorHandle(ret, arg.dtype.scalar) + + create_cos = lambda self, arg: self.unary_op(arg, np.cos) + create_exp = lambda self, arg: self.unary_op(arg, np.exp) + create_exp2 = lambda self, arg: self.unary_op(arg, np.exp2) + create_iabs = lambda self, arg: self.unary_op(arg, np.abs) + create_floor = lambda self, arg: self.unary_op(arg, np.floor) + create_ceil = lambda self, arg: self.unary_op(arg, np.ceil) + create_log = lambda self, arg: self.unary_op(arg, np.log) + create_log2 = lambda self, arg: self.unary_op(arg, np.log2) + create_precise_sqrt = lambda self, arg: self.unary_op(arg, np.sqrt) + create_sqrt = lambda self, arg: self.unary_op(arg, np.sqrt) + create_sin = lambda self, arg: self.unary_op(arg, np.sin) + + def create_erf(self, arg): + ret = np_erf_fp32(arg.data) if arg.data.dtype == np.float32 else np_erf_fp64(arg.data) + return TensorHandle(ret, arg.dtype.scalar) + + def create_rsqrt(self, arg): + return TensorHandle(1 / np.sqrt(arg.data), arg.dtype.scalar) + + # tensor operators + create_reshape = lambda self, arg, shape, allow_reorder: TensorHandle(arg.data.reshape(shape), arg.dtype.scalar) + + def create_trans(self, arg, perm): + return TensorHandle(np.transpose(arg.data, perm), arg.dtype.scalar) + + def create_dot(self, a, b, d, input_precision, max_num_imprecise_acc): + a_data = a.data + b_data = b.data + if (a.dtype.primitive_bitwidth == 8 and a.dtype.is_floating()) or \ + (b.dtype.primitive_bitwidth == 8 and b.dtype.is_floating()): + a_data = _convert_float(a_data, a.dtype, tl.float16, None).view(np.float16) + b_data = _convert_float(b_data, b.dtype, tl.float16, None).view(np.float16) + return TensorHandle(np.matmul(a_data, b_data, dtype=d.data.dtype) + d.data, d.dtype.scalar) + + def create_make_range(self, ret_ty, start, stop): + return TensorHandle(np.arange(start, stop, dtype=np.int32), tl.int32) + + def create_histogram(self, data, bins, mask): + if mask is None: + mask = TensorHandle(np.ones_like(data.data, dtype=bool), tl.int1) + + # By default np.histogram returns int64 dtype values + # Docs specify that returned dtype is taken based on optional weights.dtype + # This is fix for interpreter cases where for example int32 tensor is being passed + # But unexpectedly int64 values are being returned causing + # tl.store to write 8 bytes instead of 4 bytes which lead to silent data corruption + dummy_weights = np.ones_like(data.data, dtype=data.data.dtype) + + # force all masked elements to zero + data = np.where(mask.data, data.data, np.zeros_like(data.data)) + histogram = np.histogram(data, bins=bins, range=(0, bins), weights=dummy_weights)[0] + # remove overcounted elements + histogram[0] -= np.logical_not(mask.data).sum() + return TensorHandle(histogram, tl.int32) + + def create_gather(self, src, indices, axis): + return TensorHandle(np.take_along_axis(src.data, indices.data, axis=axis), src.dtype.scalar) + + # pointer arithmetic + + def create_addptr(self, ptr, offset): + dtype_tt = ptr.get_element_ty() + element_bitwidth = dtype_tt.primitive_bitwidth + # int1's bitwidth is 1, but we need to use 8 for pointer arithmetic + element_bytewidth = max(1, element_bitwidth // 8) + return TensorHandle(ptr.data + element_bytewidth * offset.data.astype(np.uint64), ptr.dtype) + + def create_tensor_pointer_load(self, ptr, boundary_check, padding_option, cache_modifier, eviction_policy, + is_volatile): + ptrs, masks = ptr.materialize_pointers(boundary_check) + dtype_tt = ptrs.get_element_ty() + dtype_np = _get_np_dtype(dtype_tt) + if padding_option is None: + other = None + elif padding_option == _ir.PADDING_OPTION.PAD_ZERO: + other = TensorHandle(np.zeros_like(ptrs.data, dtype=dtype_np), dtype_tt) + elif padding_option == _ir.PADDING_OPTION.PAD_NAN: + other = TensorHandle(np.full_like(ptrs.data, float('nan'), dtype=dtype_np), dtype_tt) + else: + raise ValueError(f"unsupported padding option {padding_option}") + return self.create_masked_load(ptrs, masks, other, cache_modifier, eviction_policy, is_volatile) + + def create_tensor_pointer_store(self, ptr, value, boundary_check, cache_modifier, eviction_policy): + ptrs, masks = ptr.materialize_pointers(boundary_check) + return self.create_masked_store(ptrs, value, masks, cache_modifier, eviction_policy) + + def create_expand_dims(self, arg, axis): + return TensorHandle(np.expand_dims(arg.data, axis), arg.dtype.scalar) + + def create_broadcast(self, arg, shape): + return TensorHandle(np.broadcast_to(arg.data, shape), arg.dtype.scalar) + + def create_cat(self, lhs, rhs): + return TensorHandle(np.concatenate([lhs.data, rhs.data]), lhs.dtype.scalar) + + def create_join(self, lhs, rhs): + # Triton only supports joining two original tensors into a new one along the last axis + return TensorHandle(np.stack([lhs.data, rhs.data], axis=-1), lhs.dtype.scalar) + + def create_split(self, val): + # Triton only supports splitting the original tensor into two along the last axis + return (TensorHandle(val.data[..., 0], val.dtype.scalar), TensorHandle(val.data[..., 1], val.dtype.scalar)) + + def create_splat(self, ret_ty, arg): + shape = ret_ty.shape + if isinstance(arg.dtype, tl.block_type): + return TensorHandle(np.full(shape, arg.data[0], dtype=_get_np_dtype(arg.dtype)), arg.dtype.scalar) + else: # scalar + return TensorHandle(np.full(shape, arg.data, dtype=_get_np_dtype(arg.dtype)), arg.dtype.scalar) + + def create_unsplat(self, arg): + return TensorHandle(np.full((1, ), arg.data[0], dtype=_get_np_dtype(arg.dtype)), arg.dtype.scalar) + + def create_atomic_cas(self, ptr, cmp, val, sem, scope): + if sem not in self.ir_sem_to_interpreter_sem: + raise ValueError(f"unsupported semantic {sem}") + sem = self.ir_sem_to_interpreter_sem[sem] + return TensorHandle(_interpreter.atomic_cas(ptr.data, cmp.data, val.data, sem), cmp.dtype.scalar) + + def create_atomic_rmw(self, rmwOp, ptr, val, mask, sem, scope): + if rmwOp not in self.ir_rmw_op_to_interpreter_rmw_op: + raise ValueError(f"unsupported rmwOp {rmwOp}") + if sem not in self.ir_sem_to_interpreter_sem: + raise ValueError(f"unsupported semantic {sem}") + rmwOp = self.ir_rmw_op_to_interpreter_rmw_op[rmwOp] + sem = self.ir_sem_to_interpreter_sem[sem] + return TensorHandle(_interpreter.atomic_rmw(rmwOp, ptr.data, val.data, mask.data, sem), val.dtype.scalar) + + def create_extern_elementwise(self, libName, libPath, symbol, argList, retType, isPure): + raise NotImplementedError("extern_elementwise not supported in interpreter mode") + + def create_inline_asm(self, inlineAsm, constraints, values, type, isPure, pack): + raise NotImplementedError("inline_asm not supported in interpreter mode") + + def create_print(self, prefix, hex, values, isSigned): + # NOTE: the `isSigned` variable is not really used here; because Signness is already known + # by `values` themselves in python interpreter, thus not really needed here; + # it is only used for triton PrintOpToLLVM to correctly construct the format specifier. + # Interpreter's device_print function has a different format than Triton's device_print + msg = f"({self.grid_idx[0]}, {self.grid_idx[1]}, {self.grid_idx[2]})" + if prefix: + msg += f" {prefix}" + if hex: + np.set_printoptions(formatter={'all': lambda x: f"0x{x:02x}"}) + for value in values: + print(msg + f" {value.data}") + if hex: + np.set_printoptions(formatter=None) + + def create_assert(self, condition, message): + # Interpreter's device_assert function has a different format than Triton's device_assert + assert condition, f"{message}" + + def create_assume(self, condition): + assert condition, "Assume failed" + + def create_barrier(self): + # Triton's barrier applies to each program in a grid, so it's a no-op in the interpreter + pass + + def create_make_block_ptr(self, base, shape, strides, offsets, block_shape, order): + # Create new offsets to avoid modifying the original + new_offsets = [offset.clone() for offset in offsets] + return BlockPointerHandle(base, shape, strides, new_offsets, block_shape, order) + + def create_advance(self, ptr, offsets): + if len(ptr.offsets) != len(offsets): + raise ValueError("len(ptr.offsets) != len(offsets)") + # Create new offsets to avoid modifying the original + new_offsets = [offset.clone() for offset in ptr.offsets] + ret = BlockPointerHandle(ptr.base, ptr.shape, ptr.strides, new_offsets, ptr.block_shape, ptr.order) + for i in range(len(offsets)): + ret.offsets[i].data += offsets[i].data + return ret + + def create_make_tensor_descriptor(self, base: TensorHandle, shape: List[TensorHandle], strides: List[TensorHandle], + tensor_shape: List[int], is_signed: bool, padding: str = "zero"): + desc = TensorDescHandle(base, shape, strides, tensor_shape, padding) + desc.validate() + return desc + + def create_descriptor_load(self, desc: TensorDescHandle, indices: List[TensorHandle], cache_modifier, + eviction_policy): + assert isinstance(desc, TensorDescHandle) + ptrs, mask = desc.materialize_pointers(indices) + dtype_tt = ptrs.get_element_ty() + dtype_np = _get_np_dtype(dtype_tt) + padding = desc.padding + if padding == _ir.PADDING_OPTION.PAD_ZERO: + other = TensorHandle(np.zeros_like(ptrs.data, dtype=dtype_np), dtype_tt) + elif padding == _ir.PADDING_OPTION.PAD_NAN: + other = TensorHandle(np.full_like(ptrs.data, float('nan'), dtype=dtype_np), dtype_tt) + else: + raise ValueError(f"unsupported padding {padding}") + return self.create_masked_load(ptrs, mask, other, cache_modifier=cache_modifier, + eviction_policy=eviction_policy, is_volatile=False) + + def create_descriptor_store(self, desc: TensorDescHandle, value: TensorHandle, indices: List[TensorHandle]): + ptrs, mask = desc.materialize_pointers(indices) + return self.create_masked_store(ptrs, value, mask, None, None) + + def create_descriptor_gather(self, desc: TensorDescHandle, x_offsets: TensorHandle, y_offset: TensorHandle, type): + dtype = desc.base.dtype.element_ty + np_dtype = _get_np_dtype(dtype) + result = np.zeros([x_offsets.data.shape[0], desc.block_shape[-1]], dtype=np_dtype) + cache_modifier = None + eviction_policy = None + for i, x_offset in enumerate(x_offsets.data): + indices = [TensorHandle(x_offset, tl.int32), y_offset] + result[i, :] = self.create_descriptor_load(desc, indices, cache_modifier, eviction_policy).data + return TensorHandle(result, dtype) + + def create_descriptor_scatter(self, desc: TensorDescHandle, value: TensorHandle, x_offsets: TensorHandle, + y_offset: TensorHandle): + for i, x_offset in enumerate(x_offsets.data): + slice = TensorHandle(value.data[i], value.dtype) + indices = [TensorHandle(x_offset, tl.int32), y_offset] + self.create_descriptor_store(desc, slice, indices) + + def get_all_ones_value(self, type): + np_type = _get_np_dtype(type) + if "int" in np_type.name: + return TensorHandle(np.full(1, -1, dtype=np_type), type.scalar) + elif np_type == np.bool_: + return TensorHandle(np.full(1, True, dtype=np_type), type.scalar) + else: + raise TypeError(f"unsupported type {type}") + + +_MISSING = object() + + +class _LangPatchScope: + """Tracks patched attributes so they can be restored.""" + + def __init__(self) -> None: + self._changes: list[tuple[object, str, object]] = [] + + def set_attr(self, obj: object, name: str, value: object) -> None: + original = getattr(obj, name, _MISSING) + self._changes.append((obj, name, original)) + setattr(obj, name, value) + + def restore(self) -> None: + while self._changes: + obj, name, original = self._changes.pop() + if original is _MISSING: + delattr(obj, name) + else: + setattr(obj, name, original) + + +def _patch_attr(obj, name, member, builder, scope: _LangPatchScope): + semantic = TritonSemantic(builder) + new_member = lambda *args, member=member, **kwargs: (member(*args, ** + {k: v + for k, v in kwargs.items() + if k != "_semantic"}, _semantic=semantic)) + scope.set_attr(obj, name, new_member) + + +def _patch_builtin(pkg, builder, scope: _LangPatchScope): + for name, member in inspect.getmembers(pkg): + if tl.core.is_builtin(member): + _patch_attr(pkg, name, member, builder, scope) + + +def _patch_lang_tensor(tensor, scope: _LangPatchScope): + + def _get_bool(self): + data = self.handle.data + # in triton, only scalars can be converted to booleans + # here we need this hack because all scalars are tensors + return bool(data) if data.size == 1 else True + + def _get_transpose(self): + handle = TensorHandle(np.transpose(self.handle.data), self.handle.dtype) + assert self.type.is_block() + block_shape = list(self.type.shape) + block_shape[-1], block_shape[-2] = block_shape[-2], block_shape[-1] + res_ty = tl.core.block_type(self.dtype, block_shape) + return tl.core.tensor(handle, res_ty) + + scope.set_attr(tensor, "__index__", lambda self: int(self.handle.data)) + scope.set_attr(tensor, "__bool__", lambda self: _get_bool(self)) + scope.set_attr(tensor, "__repr__", lambda self: repr(self.handle.data)) + scope.set_attr(tensor, "__str__", lambda self: str(self.handle.data)) + scope.set_attr(tensor, "T", property(_get_transpose)) + + +class ReduceScanOpInterface: + + def __init__(self, axis, combine_fn): + self.axis = axis + self.combine_fn = combine_fn + + def check_axis(self, shape, axis): + if axis is not None and axis >= len(shape): + raise ValueError(f"axis {axis} out of bounds for shape {shape}") + + def check_tensor(self, input): + for arg in input: + if not isinstance(arg, tl.core.tensor): + raise ValueError(f"input must be a tensor, got {type(arg)}") + self.check_axis(arg.shape, self.axis) + + def to_tensor(self, ret, dtype): + np_dtype = _get_np_dtype(dtype) + if hasattr(ret, "shape") and ret.shape: + ret = ret.astype(np_dtype) + ret_type = tl.block_type(dtype, list(ret.shape)) + else: + ret = np.array([ret], dtype=np_dtype) + ret_type = dtype + return tl.core.tensor(TensorHandle(ret, dtype.scalar), ret_type) + + def apply(self, input): + if not isinstance(input, tuple): + return self.apply((input, ))[0] + self.check_tensor(input) + ret = self.apply_impl(input) + return tuple(ret) if isinstance(ret, (list, tuple)) else (ret, ) + + +class ReduceOps(ReduceScanOpInterface): + + def __init__(self, axis, combine_fn, keep_dims): + super().__init__(axis, combine_fn) + self.keep_dims = keep_dims + + def unravel(self, input, axis): + ret = [] + for data in input: + if axis is not None: + ret.append(data) + else: + axis = 0 + ret.append(self.to_tensor(data.handle.data.flatten(), data.dtype)) + return tuple(ret), axis + + def generic_reduce(self, input): + original_axis = self.axis + input, axis = self.unravel(input, self.axis) + input_data = [] + output_data = [] + input_shape = input[0].handle.data.shape + output_shape = input_shape[0:axis] + input_shape[axis + 1:] + for arg in input: + input_data.append(arg.handle.data) + output_data.append(np.zeros(output_shape, dtype=arg.handle.data.dtype)) + # Reduce on axis + for i in range(input_data[0].size): + # Recover input_index from i using input_shape + input_index = np.unravel_index(i, input_shape) + output_index = input_index[0:axis] + input_index[axis + 1:] + input_tuple = tuple(self.to_tensor(d[input_index], input[ii].dtype) for ii, d in enumerate(input_data)) + if input_index[axis] == 0: + # First element + for j in range(len(output_data)): + output_data[j][output_index] = input_tuple[j].handle.data.item() + else: + acc_tuple = tuple(self.to_tensor(o[output_index], input[oi].dtype) for oi, o in enumerate(output_data)) + combine_fn_ret = self.combine_fn.fn(*acc_tuple, *input_tuple) + acc_tuple = (combine_fn_ret, ) if not isinstance(combine_fn_ret, tuple) else combine_fn_ret + for j in range(len(output_data)): + output_data[j][output_index] = acc_tuple[j].handle.data.item() if isinstance( + acc_tuple[j], tl.core.tensor) else acc_tuple[j] + # Pack output + ret = [] + for i, data in enumerate(output_data): + if self.keep_dims: + if original_axis is not None: + data = np.expand_dims(data, axis) + else: + for _ in range(len(input_shape)): + data = np.expand_dims(data, 0) + + elif original_axis is None: + # Take a scalar + data = data.item() + ret.append(self.to_tensor(data, input[i].dtype)) + return ret + + def min_max(self, input, val_reduce_op, idx_reduce_op=None): + # If input is a tuple, it must be (val, index), and we only take val + input = input[0] if isinstance(input, tuple) else input + val = None + idx = None + if val_reduce_op: + val = self.to_tensor(val_reduce_op(input.handle.data, axis=self.axis, keepdims=self.keep_dims), input.dtype) + if idx_reduce_op: + idx = self.to_tensor(idx_reduce_op(input.handle.data, axis=self.axis, keepdims=self.keep_dims), tl.int32) + if val is not None and idx is not None: + return val, idx + elif val is not None: + return val + elif idx is not None: + return idx + else: + raise ValueError("val_reduce_op and idx_reduce_op are both None") + + def sum(self, input): + return self.to_tensor(np.sum(input.handle.data, axis=self.axis, keepdims=self.keep_dims), input.dtype) + + def apply_impl(self, input): + if self.combine_fn == tl.standard._argmin_combine_tie_break_left: + return self.min_max(input[0], val_reduce_op=np.min, idx_reduce_op=np.argmin) + elif self.combine_fn == tl.standard._argmax_combine_tie_break_left: + return self.min_max(input[0], val_reduce_op=np.max, idx_reduce_op=np.argmax) + elif self.combine_fn == tl.standard._elementwise_max: + return self.min_max(input[0], val_reduce_op=np.nanmax, idx_reduce_op=None) + elif self.combine_fn == tl.standard._elementwise_min: + return self.min_max(input[0], val_reduce_op=np.nanmin, idx_reduce_op=None) + elif self.combine_fn == tl.standard._sum_combine: + return self.sum(input[0]) + else: + # Fall back to the slow mode + return self.generic_reduce(input) + + +class ScanOps(ReduceScanOpInterface): + + def __init__(self, axis, combine_fn, reverse): + super().__init__(axis, combine_fn) + self.reverse = reverse + + def cumsum(self, input): + return [self.to_tensor(np.cumsum(input.handle.data, axis=self.axis), dtype=input.dtype)] + + def cumprod(self, input): + return [self.to_tensor(np.cumprod(input.handle.data, axis=self.axis), dtype=input.dtype)] + + def generic_scan(self, input): + input_data = [] + output_data = [] + shape = input[0].handle.data.shape + for arg in input: + input_data.append(arg.handle.data) + output_data.append(np.zeros(shape, dtype=arg.handle.data.dtype)) + # Scan on axis + for i in range(input_data[0].size): + # Recover index from i using shape + index = np.unravel_index(i, shape) + data = tuple(self.to_tensor(d[index], input[ii].dtype) for ii, d in enumerate(input_data)) + if index[self.axis] == 0: + # First element + for j in range(len(output_data)): + output_data[j][index] = data[j].handle.data.item() + else: + prev_index = tuple(index[i] - 1 if i == self.axis else index[i] for i in range(len(index))) + acc_tuple = tuple(self.to_tensor(o[prev_index], input[oi].dtype) for oi, o in enumerate(output_data)) + combine_fn_ret = self.combine_fn.fn(*acc_tuple, *data) + acc_tuple = (combine_fn_ret, ) if not isinstance(combine_fn_ret, tuple) else combine_fn_ret + for j in range(len(output_data)): + output_data[j][index] = acc_tuple[j].handle.data.item() if isinstance( + acc_tuple[j], tl.core.tensor) else acc_tuple[j] + # Pack output + ret = [] + for i, data in enumerate(output_data): + ret.append(self.to_tensor(data, input[i].dtype)) + return ret + + def apply_impl(self, input): + new_input = [] + if self.reverse: + for arg in input: + new_input.append(self.to_tensor(np.flip(arg.handle.data, axis=self.axis), arg.dtype)) + else: + new_input = input + if self.combine_fn == tl.standard._sum_combine: + ret = self.cumsum(new_input[0]) + elif self.combine_fn == tl.standard._prod_combine: + ret = self.cumprod(new_input[0]) + else: + # Fall back to the slow mode + ret = self.generic_scan(new_input) + if self.reverse: + for arg in ret: + arg.handle.data = np.flip(arg.handle.data, axis=self.axis) + return ret + + +def _patch_reduce_scan(scope: _LangPatchScope): + # Because interpreter doesn't support region_builder_fn, we cannot patch the builder + # to use the new reduce and scan functions. + # Instead, we need to patch reduce and reduce functions in tl and tl.core + def _new_reduce(input, axis, combine_fn, keep_dims=False, **kwargs): + return ReduceOps(axis, combine_fn, keep_dims).apply(input) + + def _new_scan(input, axis, combine_fn, reverse=False, **kwargs): + return ScanOps(axis, combine_fn, reverse).apply(input) + + scope.set_attr(tl, "reduce", _new_reduce) + scope.set_attr(tl, "associative_scan", _new_scan) + scope.set_attr(tl.core, "reduce", _new_reduce) + scope.set_attr(tl.core, "associative_scan", _new_scan) + + +def _patch_lang_core(lang, scope: _LangPatchScope): + + def _new_to_ir(self, builder): + # We need to specify signedness for integer types in the numpy mode + if self.name == 'void': + return builder.get_void_ty() + elif self.name == 'int1': + return builder.get_int1_ty() + elif self.name == 'int8': + return builder.get_int8_ty() + elif self.name == 'uint8': + return builder.get_uint8_ty() + elif self.name == 'int16': + return builder.get_int16_ty() + elif self.name == 'uint16': + return builder.get_uint16_ty() + elif self.name == 'int32': + return builder.get_int32_ty() + elif self.name == 'uint32': + return builder.get_uint32_ty() + elif self.name == 'int64': + return builder.get_int64_ty() + elif self.name == 'uint64': + return builder.get_uint64_ty() + elif self.name == 'fp8e5': + return builder.get_fp8e5_ty() + elif self.name == 'fp8e4nv': + return builder.get_fp8e4nv_ty() + elif self.name == 'fp8e4b15': + return builder.get_fp8e4b15_ty() + elif self.name == 'fp16': + return builder.get_half_ty() + elif self.name == 'bf16': + return builder.get_bf16_ty() + elif self.name == 'fp32': + return builder.get_float_ty() + elif self.name == 'fp64': + return builder.get_double_ty() + raise ValueError(f'fail to convert {self} to ir type') + + # can't just map lang.static_range to `range`, because `tl.static_range` + # can get `step` passed by keyword + def _new_range(arg1, arg2=None, step=None, **kwargs): + if step is None: + step = 1 + if arg2 is None: + start, end = 0, arg1 + else: + start, end = arg1, arg2 + return range(start, end, step) + + def _new_static_assert(cond, msg=""): + assert cond, msg + + def _set_attr(input, values, name): + # skip non tensor types. This may happen for induction variables. + if not isinstance(input, tl.tensor): + return input + # Unwrap constexpr + values = [values] if not isinstance(values, (list, tuple)) else values + values = [v.value if isinstance(v, tl.constexpr) else v for v in values] + if len(values) != max(1, len(input.shape)): + raise ValueError(f"len(values) != len(input.shape) for {name}") + input.handle.set_attr(name, values) + return input + + scope.set_attr(lang, "range", _new_range) + scope.set_attr(lang, "static_range", _new_range) + scope.set_attr(lang, "static_assert", _new_static_assert) + scope.set_attr(lang, "static_print", print) + scope.set_attr(lang.dtype, "to_ir", _new_to_ir) + scope.set_attr(lang, "multiple_of", partial(_set_attr, name="tt.divisibility")) + scope.set_attr(lang, "max_contiguous", partial(_set_attr, name="tt.contiguity")) + scope.set_attr(lang, "max_constancy", partial(_set_attr, name="tt.constancy")) + + _patch_reduce_scan(scope) + + +def _patch_lang(fn): + scope = _LangPatchScope() + langs = [value for _, value in fn.__globals__.items() if inspect.ismodule(value) and value in [tl, tl.core]] + assert len(langs) >= 1, "triton.language must be visible from within jit'd function" + for lang in langs: + _patch_builtin(lang, interpreter_builder, scope) + _patch_builtin(lang.tensor, interpreter_builder, scope) + if lang == tl: + _patch_builtin(lang.math, interpreter_builder, scope) + _patch_lang_tensor(lang.tensor, scope) + _patch_lang_core(lang, scope) + _patch_builtin(tl.core.tensor_descriptor_base, interpreter_builder, scope) + return scope + + +def _tuple_create(arg, contents): + # NamedTuples and tuples have different construction semantics. NamedTuple + # has a constructor that takes individual arguments, while tuple takes an + # iterable. Both have type "tuple" making it difficult to distinguish + # between them, but only NamedTuple has "_fields" and apparently this is how + # everyone does the check. + return type(arg)(*contents) if hasattr(arg, "_fields") else type(arg)(contents) + + +# TODO: wrap everything in triton tensors +def _implicit_cvt(arg): + if isinstance(arg, int): + ty = tl.str_to_ty(triton.runtime.jit.mangle_type(arg), None) + dtype = np.int32 + if -2**31 <= arg < 2**31: + dtype = np.int32 + elif 2**31 <= arg < 2**32: + dtype = np.uint32 + elif -2**63 <= arg < 2**63: + dtype = np.int64 + elif 2**63 <= arg < 2**64: + dtype = np.uint64 + else: + raise ValueError(f"Unsupported integer value {arg}") + handle = TensorHandle(np.array([arg], dtype=dtype), ty) + return tl.tensor(handle, ty) + if hasattr(arg, "data_ptr"): + ty = tl.str_to_ty(triton.runtime.jit.mangle_type(arg), None) + handle = TensorHandle(np.array([arg.data_ptr()], dtype=np.uint64), ty) + return tl.tensor(handle, ty) + elif isinstance(arg, tuple): + return _tuple_create(arg, map(_implicit_cvt, arg)) + elif isinstance(arg, TensorDescriptor): + strides = [_implicit_cvt(s) for s in arg.strides] + assert arg.strides[-1] == 1 + strides[-1] = tl.constexpr(1) + semantic = TritonSemantic(InterpreterBuilder()) + return semantic.make_tensor_descriptor(base=_implicit_cvt(arg.base), + shape=[_implicit_cvt(s) for s in arg.shape], strides=strides, + block_shape=[tl.constexpr(b) + for b in arg.block_shape], padding_option=arg.padding) + return arg + + +interpreter_builder = InterpreterBuilder() +interpreter_semantic = TritonSemantic(interpreter_builder) + + +def _unwrap_tensor(t): + if isinstance(t, triton.runtime.jit.TensorWrapper): + return t.base + return t + + +def _rewrap_tensor(t, original_tensor): + if isinstance(original_tensor, triton.runtime.jit.TensorWrapper): + return triton.runtime.jit.TensorWrapper(t, original_tensor.dtype) + return t + + +class GridExecutor: + + def __init__(self, fn, arg_names, grid, pre_run_hooks=[]): + from .jit import _normalize_ty # TODO: modularize + + self.fn = fn + self.arg_names = arg_names + self.grid = grid + self.pre_run_hooks = pre_run_hooks + __annotations__ = {name: _normalize_ty(ty) for name, ty in fn.__annotations__.items()} + self.constexprs = [name for name in arg_names if __annotations__.get(name) == "constexpr"] + + def _init_args_hst(self, args_dev, kwargs): + storages = {} + + def _to_cpu(arg): + if isinstance(arg, tuple): + return _tuple_create(arg, map(_to_cpu, arg)) + elif isinstance(arg, TensorDescriptor): + return TensorDescriptor( + _to_cpu(arg.base), + arg.shape, + arg.strides, + arg.block_shape, + arg.padding, + ) + elif not hasattr(arg, "data_ptr"): + return arg + + unwrapped_arg = _unwrap_tensor(arg) + if unwrapped_arg.untyped_storage().data_ptr() not in storages: + storage = unwrapped_arg.untyped_storage() + storages[storage.data_ptr()] = storage.cpu() + + storage = storages[unwrapped_arg.untyped_storage().data_ptr()] + cpu_arg = unwrapped_arg.new_empty(0, device='cpu') + cpu_arg.set_(storage, unwrapped_arg.storage_offset(), unwrapped_arg.size(), unwrapped_arg.stride()) + cpu_arg = _rewrap_tensor(cpu_arg, original_tensor=arg) + return cpu_arg + + args_hst = [_to_cpu(arg) for arg in args_dev] + + # Process keyword arguments + kwargs_hst = {} + for key, value in kwargs.items(): + kwargs_hst[key] = _to_cpu(value) + return args_hst, kwargs_hst + + def _restore_args_dev(self, args_dev, args_hst, kwargs, kwargs_hst): + storages = {} + + def _from_cpu(arg_dev, arg_hst): + if hasattr(arg_dev, "data_ptr"): + # No need to rewrap because this just modifies internal + arg_dev, arg_hst = _unwrap_tensor(arg_dev), _unwrap_tensor(arg_hst) + storages[arg_dev.untyped_storage().data_ptr()] = (arg_dev.untyped_storage(), arg_hst.untyped_storage()) + elif isinstance(arg_dev, tuple): + for (arg_dev, arg_hst) in zip(arg_dev, arg_hst): + _from_cpu(arg_dev, arg_hst) + elif isinstance(arg_dev, TensorDescriptor): + _from_cpu(arg_dev.base, arg_hst.base) + + for arg_dev, arg_hst in zip(args_dev, args_hst): + _from_cpu(arg_dev, arg_hst) + + # Restore keyword arguments + for key, kwarg_dev in kwargs.items(): + kwarg_hst = kwargs_hst[key] + _from_cpu(kwarg_dev, kwarg_hst) + + for (arg_dev, arg_hst) in storages.values(): + arg_dev.copy_(arg_hst) + + def __call__(self, *args_dev, **kwargs): + # Removes not used reserved keywords from kwargs + # Triton doesn't support keyword-only, variable positional or variable keyword arguments + # It's safe to inspect only positional or keyword arguments (i.e., argspec.args) + argspec = inspect.getfullargspec(self.fn) + kwargs = {k: v for k, v in kwargs.items() if k in argspec.args} + # copy arguments to the host + args_hst, kwargs_hst = self._init_args_hst(args_dev, kwargs) + # run pre-run hooks + for hook in self.pre_run_hooks: + hook(*args_hst, **kwargs_hst) + # remaps core language functions to interpreted ones + patch_scope = _patch_lang(self.fn) + try: + # we need to copy arguments to the host for the interpreter + # implicitly convert tensor arguments to their base pointers + args = inspect.getcallargs(self.fn, *args_hst, **kwargs_hst) + args = {name: arg if name in self.constexprs else _implicit_cvt(arg) for name, arg in args.items()} + # iterate through grid + grid = self.grid(args) if callable(self.grid) else self.grid + assert len(grid) <= 3, "grid must have at most 3 dimensions" + grid = grid + (1, ) * (3 - len(grid)) + interpreter_builder.set_grid_dim(*grid) + try: + for x in range(grid[0]): + for y in range(grid[1]): + for z in range(grid[2]): + interpreter_builder.set_grid_idx(x, y, z) + self.fn(**args) + except Exception as e: + if triton.knobs.compilation.front_end_debugging: + raise + raise InterpreterError(repr(e)) from e + finally: + patch_scope.restore() + # copy arguments back to propagate side-effects + self._restore_args_dev(args_dev, args_hst, kwargs, kwargs_hst) + + +class ASTTransformer(ast.NodeTransformer): + + def visit_Assign(self, node): + names = [] + for target in node.targets: + names += [self.visit(target)] + if len(names) > 1: + raise ValueError("Multiple assignments are not supported") + # Modify the assignment x = value to + # interpreter_semantic.to_tensor(value, False) + node.value = ast.Call( + func=ast.Attribute(value=ast.Name(id="interpreter_semantic", ctx=ast.Load()), attr="to_tensor", + ctx=ast.Load()), args=[node.value, ast.Constant(value=False)], keywords=[]) + return node + + +class FunctionRewriter: + ast_transformer = ASTTransformer() + + def __init__(self, fn, **kwargs): + self.fn = fn + self.kwargs = kwargs + self.filename: str = "" + # Absolute line number in the file + self.def_file_lineno: int = 0 + + def rewrite_ast(self): + # If exception is raise, it means the function does not have source code available, + # e.g., dynamically generated functions, we cannot rewrite it so just return the original function + try: + lines, _ = inspect.getsourcelines(self.fn) + except Exception: + return self.fn + + # truncate lines before def + # @triton.autotune(...) + # ... + # @triton.jit + # ... + # def foo(...): <- this line is the function definition + self.filename, self.def_file_lineno = self._get_jit_fn_file_line() + self.def_lineno = self._find_def(lines) + src = self._prepare_source(lines) + transformed_ast = self._transform_ast(src) + return self._compile_and_exec(transformed_ast) + + def _get_jit_fn_file_line(self): + from .jit import get_jit_fn_file_line, JITFunction + return get_jit_fn_file_line(JITFunction(self.fn)) + + def _find_def(self, lines): + def_lineno = 0 + # Line numbers start from 1 + for i, line in enumerate(lines): + if line.strip().startswith("def "): + def_lineno = i + 1 + return def_lineno + + def _prepare_source(self, lines): + lines = lines[self.def_lineno - 1:] + src = ''.join(lines) + return textwrap.dedent(src) + + def _transform_ast(self, src): + # src is like: + # 1: def foo(...): + # 2: ... + parsed_ast = ast.parse(src) + transformed_ast = self.ast_transformer.visit(parsed_ast) + ast.fix_missing_locations(transformed_ast) + inc_lineno = self.def_file_lineno - 1 + ast.increment_lineno(transformed_ast, inc_lineno) + return transformed_ast + + def _compile_and_exec(self, transformed_ast): + compiled_code = compile(transformed_ast, filename=self.filename, mode='exec') + local_namespace = {**self.kwargs} + fn_globals = self.fn.__globals__ + for key, value in globals().items(): + if key not in fn_globals: + fn_globals[key] = value + exec(compiled_code, fn_globals, local_namespace) + return local_namespace[self.fn.__name__] + + +class InterpretedFunction(KernelInterface[T]): + # Cache all rewritten functions + rewritten_fn: Dict[Callable, Callable] = {} + + def __init__(self, fn, **kwargs) -> None: + self.fn = fn + self.rewriter = FunctionRewriter(fn, **kwargs) + self.kwargs = kwargs + self.pre_run_hooks = [] + + signature = inspect.signature(fn) + self.arg_names = [v.name for v in signature.parameters.values()] + + def run(self, *args, grid, warmup, **kwargs): + if warmup: + return + fn = self.rewrite() + return GridExecutor(fn, self.arg_names, grid, self.pre_run_hooks)(*args, **kwargs) + + def add_pre_run_hook(self, hook): + assert callable(hook) + self.pre_run_hooks.append(hook) + + def rewrite(self): + if self.fn not in self.rewritten_fn: + self.rewritten_fn[self.fn] = self.rewriter.rewrite_ast() + return self.rewritten_fn[self.fn] + + @property + def __name__(self): + return self.fn.__name__ + + def __call__(self, *args, **kwargs): + # This is a device function call + _patch_lang(self.fn) + fn = self.rewrite() + try: + return fn(*args, **kwargs) + except Exception as e: + raise InterpreterError(repr(e)) from e diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/runtime/jit.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/runtime/jit.py new file mode 100644 index 0000000000000000000000000000000000000000..0f506818f9d9790961fbd519f7a6067ca1e9c303 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/runtime/jit.py @@ -0,0 +1,1099 @@ +from __future__ import annotations, division +import ast +import copy +import hashlib +import inspect +import itertools +import threading +import re +import textwrap +from collections import defaultdict +from dataclasses import dataclass +from functools import cached_property +from typing import Callable, Generic, Iterable, Optional, TypeVar, overload, Dict, Any, Tuple + +from triton.backends import BaseBackend +from types import ModuleType +from .. import knobs +from .driver import driver +from . import _async_compile +from .._utils import find_paths_if, get_iterable_path, type_canonicalisation_dict, is_namedtuple +from .cache import get_cache_key +from triton._C.libtriton import get_cache_invalidating_env_vars, native_specialize_impl + +TRITON_MODULE = "triton.language" +GLUON_MODULE = "triton.experimental.gluon.language" + +T = TypeVar("T") + +# ----------------------------------------------------------------------------- +# Dependencies Finder +# ----------------------------------------------------------------------------- + + +class DependenciesFinder(ast.NodeVisitor): + """ + This AST visitor is used to find dependencies of a JITFunction. This can + be used to invalidate a JITFunction's hash when its source code -- or + that of its dependencies -- changes. + + This visitor also keeps track of the global variables touched by the + JITFunction. When we launch the kernel, we check that these have the same + values as they did when we ran this visitor. If not, we raise an error (or + otherwise we could recompile). + """ + + def __init__(self, name, globals, nonlocals, src) -> None: + super().__init__() + self.name = name + self.hasher = hashlib.sha256(src.encode("utf-8")) + + # This function's __globals__ dict. + self.globals = globals + self.nonlocals = nonlocals + + # Python builtins that can be accessed from Triton kernels. + self.supported_python_builtins = { + 'float', + 'getattr', + 'int', + 'isinstance', + 'len', + 'list', + 'max', + 'min', + 'print', + 'range', + } + self.supported_modules = { + GLUON_MODULE, + TRITON_MODULE, + "copy", + "math", + } + + # used_global_vals tells us which global variables are used by this + # function and all those it transitively calls, plus the values of those + # variables when each function was initially run. (That is, if A calls + # C, and B calls C, then the values for C in used_global_vals will be + # from the first time C was run, either by A or B.) + # + # Each function may have a different __globals__ dict, so the global + # variable `foo` may actually have a different value in the different + # functions. Thus this map is actually + # (var_name, id(__globals__)) -> (var_value, __globals__). + self.used_global_vals: Dict[Tuple[str, int], Tuple[Any, Dict[str, Any]]] = {} + + self.visiting_arg_default_value = False + + @property + def ret(self): + return self.hasher.hexdigest() + + def _is_triton_builtin(self, node, func): + if inspect.isbuiltin(node.func): + return True + module = getattr(func, "__module__", "") + return module.startswith(TRITON_MODULE) + + def _update_hash(self, func): + assert isinstance(func, JITCallable) + # Merge our used_global_vals with those of the called function, + # after checking that all overlapping values are consistent. + for k in self.used_global_vals.keys() & func.used_global_vals.keys(): + var_name, _ = k + v1, _ = self.used_global_vals[k] + v2, _ = func.used_global_vals[k] + if v1 != v2: + raise RuntimeError( + f"Global variable {var_name} has value {v1} when compiling {self.name}, but inner kernel {func.__name__} has conflicting value {v2} from when it was first compiled. This is not allowed." + ) + self.used_global_vals.update(func.used_global_vals) + # update hash + func_key = func.cache_key + func_key += str(getattr(func, "noinline", False)) + self.hasher.update(func_key.encode("utf-8")) + + def record_reference(self, val, var_dict=None, name=None): + from ..language.core import constexpr + # Only keep track of "interesting" global variables, that non-evil users + # might change. Don't consider functions, modules, builtins, etc. This + # helps keep the list of vars we have to check small. + if val is None or type(val) is ModuleType: + return + + if getattr(val, "__triton_aggregate__", False): + for attr in val.hash_attrs: + self.record_reference(attr) + return + + if getattr(val, "__triton_builtin__", False): + return + + # Stubs that aren't real functions + if getattr(val, "__module__", "") == "triton.language.extra.libdevice": + return + + if isinstance(val, JITCallable): + self._update_hash(val) + return + + if callable(val) and not isinstance(val, type) and not isinstance(val, constexpr): + raise RuntimeError(f"Unsupported function referenced: {val}") + + # Python default arguments are resolved only once, when the + # function is defined. So if you do `foo(a=A)` and the value of + # A changes, foo will still use the old value of A. + # It would be pretty evil if someone did `import x` and then + # `x = blah`. + if self.visiting_arg_default_value: + return + + if var_dict is not None: + self.used_global_vals[(name, id(var_dict))] = (copy.deepcopy(val), var_dict) + return + + def visit_Name(self, node): + if type(node.ctx) is ast.Store: + return node.id + + if node.id in self.local_names: + # The global name is hidden by the local name. + return None + + def name_lookup(name): + val = self.globals.get(name, None) + if val is not None: + return val, self.globals + val = self.nonlocals.get(name, None) + if val is not None: + return val, self.nonlocals + return None, None + + val, var_dict = name_lookup(node.id) + if node.id in self.supported_python_builtins: + return val + + self.record_reference(val, var_dict, node.id) + return val + + def visit_Tuple(self, node): + # We need to explicitly return the tuple values so that visit_Assign can + # access them in the case of `a, b = ...`. + return [self.visit(elt) for elt in node.elts] + + def visit_Attribute(self, node): + lhs = self.visit(node.value) + while isinstance(lhs, ast.Attribute): + lhs = self.visit(lhs.value) + lhs_name = getattr(lhs, "__name__", "") + if lhs is None or lhs_name in self.supported_modules: + return None + ret = getattr(lhs, node.attr) + self.record_reference(ret) + return ret + + def visit_FunctionDef(self, node): + # Save the local name, which may hide the global name. + self.local_names = {arg.arg for arg in node.args.args} + self.generic_visit(node) + + def visit_arguments(self, node): + # The purpose of this function is to visit everything in `arguments` + # just like `generic_visit`, except when we're visiting default values + # (i.e. the `foo` part of `def fn(x = foo)`), we set + # self.visiting_arg_default_value = True. This allows visit_Name to be + # aware that we're inside function default values, which have special + # semantics. + + # According to the AST docs, the arguments node has the following structure. + # + # arguments = (arg* posonlyargs, arg* args, arg? vararg, arg* kwonlyargs, + # expr* kw_defaults, arg? kwarg, expr* defaults) + def visit_defaults(defaults): + try: + assert not self.visiting_arg_default_value + self.visiting_arg_default_value = True + for expr in defaults: + if expr is not None: + self.visit(expr) + finally: + self.visiting_arg_default_value = False + + for arg in itertools.chain(node.posonlyargs, node.args, [node.vararg] if node.vararg else [], node.kwonlyargs): + self.visit(arg) + + visit_defaults(node.kw_defaults) + + if node.kwarg is not None: + self.visit(node.kwarg) + + visit_defaults(node.defaults) + + def visitAssnTarget(self, node): + # Target is either a single string, or a list of strings (if the assn + # target is a tuple). + target = self.visit(node) + if isinstance(target, list): + self.local_names |= set(target) + else: + self.local_names.add(target) + + def visit_Assign(self, node): + if len(node.targets) != 1: + # TODO(jlebar): I don't actually know how to hit this. You don't + # get it from `a, b = ...` -- in that case, node.targets is a single + # Tuple, and in fact we *do* need to handle that case if we want + # existing code to work. + raise TypeError("Simultaneous multiple assignment is not supported.") + + self.visitAssnTarget(node.targets[0]) + + # This will re-visit the target, but that's OK. + self.generic_visit(node) + + def visit_AnnAssign(self, node): + self.visitAssnTarget(node.target) + + # This will re-visit the target, but that's OK. + self.generic_visit(node) + + def visit_For(self, node): + self.visitAssnTarget(node.target) + + # This will re-visit the target, but that's fine. + self.generic_visit(node) + + +# ----------------------------------------------------------------------------- +# JITFunction +# ----------------------------------------------------------------------------- + + +def _normalize_ty(ty) -> str: + import triton.language.core as core + if isinstance(ty, str): + ty = ty.strip() + if ty.startswith("const "): + ty = ty.removeprefix("const") + ty = _normalize_ty(ty) + assert ty.startswith("*") + return "*k" + ty[1:] + if ty.endswith("*"): + return "*" + _normalize_ty(ty[:-1]) + if ty.startswith("*"): + return "*" + _normalize_ty(ty[1:]) + if ty.startswith("tl."): + return _normalize_ty(ty.removeprefix("tl.")) + elif isinstance(ty, core.pointer_type): + return f"*{_normalize_ty(ty.element_ty)}" + elif isinstance(ty, core.dtype): + ty = ty.name + elif isinstance(ty, type): + ty = ty.__name__ + else: + ty = str(ty) + return type_canonicalisation_dict.get(ty.replace("_t", ""), ty) + + +class KernelParam: + """Represents a parameter (name plus metadata) to a @jit'ed function.""" + + def __init__(self, num: int, param: inspect.Parameter, do_not_specialize: bool, + do_not_specialize_on_alignment: bool): + self.num = num + self._param = param + self.do_not_specialize = do_not_specialize + self.do_not_specialize_on_alignment = do_not_specialize_on_alignment + + @cached_property + def name(self): + return self._param.name + + @cached_property + def annotation(self) -> str: + if not self._param.annotation or self._param.annotation == inspect.Parameter.empty: + return "" + return _normalize_ty(self._param.annotation) + + @cached_property + def annotation_type(self) -> str: + a = self.annotation + if a.startswith("*k"): + a = a[2:] + elif a.startswith("*"): + a = a[1:] + if a in set(type_canonicalisation_dict.values()): + return self.annotation + return "" + + @cached_property + def is_constexpr(self): + return "constexpr" in self.annotation + + @cached_property + def is_const(self): + if self.is_constexpr: + return False + return "const" in self.annotation or self.annotation.startswith("*k") + + @property + def default(self): + return self._param.default + + @property + def has_default(self): + return self._param.default != inspect.Parameter.empty + + +def mangle_type(arg, specialize=False): + is_const = False + align = True + return native_specialize_impl(BaseBackend, arg, is_const, specialize, align)[0] + + +class KernelInterface(Generic[T]): + run: T + + def warmup(self, *args, grid, **kwargs): + return self.run(grid=grid, warmup=True, *map(MockTensor.wrap_dtype, args), **kwargs) + + def run(self, *args, grid, warmup, **kwargs): + raise NotImplementedError("run not implemented") + + def __getitem__(self, grid) -> T: + """ + A JIT function is launched with: fn[grid](*args, **kwargs). + Hence JITFunction.__getitem__ returns a callable proxy that + memorizes the grid. + """ + return lambda *args, **kwargs: self.run(grid=grid, warmup=False, *args, **kwargs) + # return cast(T, functools.partial(cast(Callable, self.run), grid=grid)) + + +def serialize_specialization_data(name, signature, constants, attrs, options, key): + constants = { + key: str(value) if value.__class__.__name__ == "dtype" else + {"constexpr": value.value} if value.__class__.__name__ == "constexpr" else value + for key, value in constants.items() + } + + import json + obj = { + 'name': name, 'signature': signature, 'constant_keys': [list(x) for x in constants.keys()], 'constant_vals': + list(constants.values()), 'attrs_keys': [list(x) for x in attrs.keys()], 'attrs_vals': list(attrs.values()), + 'options': options.__dict__, 'key': key + } + serialized_obj = json.dumps(obj) + return serialized_obj + + +def create_function_from_signature(sig, kparams, backend): + """ + Equivalent to sig.bind followed by apply_defaults. This generates a + native Python function (using exec) which can be memoized on a per-kernel + basis to avoid having to run these expensive functions -- which constitute + much of the kernel launch overhead -- every time we run the kernel. + """ + assert len(sig.parameters) == len(kparams) + # Create the function argument list and the dict entries for the return statement + specialization = [] + # signature + for name, kp in zip(sig.parameters.keys(), kparams): + if kp.is_constexpr: + specialization.append(f'("constexpr", {name})') + else: + is_const = 'True' if kp.is_const else 'False' + specialize = 'False' if kp.do_not_specialize else 'True' + align = 'False' if kp.do_not_specialize_on_alignment else 'True' + ret = f"specialize_impl(backend, {name}, {is_const}, {specialize}, {align})" + if kp.annotation_type: + if isinstance(kp.annotation_type, str): + if kp.annotation_type == "u1" or kp.annotation_type[:2] in ["fp", "bf"]: + # we do not specialize non-constexpr floats and bools: + specialize = False + if specialize: + specialization.append(f'("{kp.annotation_type}",) + {ret}[1:]') + else: + # skip runtime specialization: + specialization.append(f'("{kp.annotation_type}", None)') + else: + specialization.append(f"{ret}") + + # compute argument string for a given parameter + arg = lambda x: x[0] if x[1].default is inspect.Parameter.empty else f"{x[0]}=default_{x[0]}" + func_body = f""" +def dynamic_func({", ".join(list(map(arg, sig.parameters.items())) + ["**options"])}): + params = {{{', '.join([f"'{name}': {name}" for name in sig.parameters.keys()])}}} + specialization = [{','.join(specialization)}] + return params, specialization, options +""" + + # Prepare defaults to be inserted into function namespace + func_namespace = { + f"default_{name}": param.default + for name, param in sig.parameters.items() + if param.default is not inspect.Parameter.empty + } + + specialize_impl = native_specialize_impl + func_namespace["specialize_impl"] = specialize_impl + func_namespace["backend"] = backend + func_namespace["JITCallable"] = JITCallable + + # Execute the function string in func_namespace to create the function + exec(func_body, func_namespace) + + # Extract the newly created function from the namespace + return func_namespace['dynamic_func'] + + +def get_full_name(fn): + return f"{fn.__module__}.{fn.__qualname__}" + + +class JITCallable: + + def __init__(self, fn): + self.fn = fn + self.signature = inspect.signature(fn) + try: + self.raw_src, self.starting_line_number = inspect.getsourcelines(fn) + except OSError as e: + raise ValueError("@jit functions should be defined in a Python file") from e + self._fn_name = get_full_name(fn) + self._hash_lock = threading.RLock() + + # function source code (without decorators) + src = textwrap.dedent("".join(self.raw_src)) + src = src[re.search(r"^def\s+\w+\s*\(", src, re.MULTILINE).start():] + self._src = src + self.hash = None + + # Map of global variables used by the function and any functions it + # transitively calls, plus their values. The values are collected when + # the function is first compiled. Then every time we run the function, + # we check that the values of the globals match what's expected, + # otherwise we raise an error. + # + # Different functions can have different __globals__ maps, so the map + # key is actually (var name, id(__globals__)), and the map value is + # (value, __globals__). + self.used_global_vals: Dict[Tuple[str, int], Tuple[Any, Dict[str, Any]]] = {} + + # reuse docs of wrapped function + self.__doc__ = fn.__doc__ + self.__name__ = fn.__name__ + self.__qualname__ = fn.__qualname__ + self.__globals__ = fn.__globals__ + self.__module__ = fn.__module__ + + def get_capture_scope(self): + return self.__globals__ | inspect.getclosurevars(self.fn).nonlocals + + @property + def cache_key(self) -> str: + # TODO : hash should be attribute of `self` + with self._hash_lock: + if self.hash is not None: + return self.hash + # Set a placeholder hash to break recursion in case the function + # transitively calls itself. The full hash is set after. + self.hash = f"recursion:{self._fn_name}" + nonlocals = inspect.getclosurevars(self.fn).nonlocals + dependencies_finder = DependenciesFinder(name=self._fn_name, globals=self.__globals__, nonlocals=nonlocals, + src=self.src) + dependencies_finder.visit(self.parse()) + self.hash = dependencies_finder.ret + str(self.starting_line_number) + self.used_global_vals = dict(sorted(dependencies_finder.used_global_vals.items())) + + from triton.language.core import constexpr + self.hash += str([(name, val) + for (name, _), (val, _) in self.used_global_vals.items() + if isinstance(val, constexpr)]) + self.hash = hashlib.sha256(self.hash.encode("utf-8")).hexdigest() + return self.hash + + def __hash__(self): + return hash(self.cache_key) + + # we do not parse `src` in the constructor because + # the user might want to monkey-patch self.src dynamically. + # Our unit tests do this, for example. + def parse(self): + tree = ast.parse(self._src) + assert isinstance(tree, ast.Module) + assert len(tree.body) == 1 + assert isinstance(tree.body[0], ast.FunctionDef) + return tree + + @property + def type(self): + from triton.language.core import constexpr_type + return constexpr_type(self) + + def _unsafe_update_src(self, new_src): + """ + The only method allowed to modify src. + Bypasses the __setattr__ restriction by calling super().__setattr__ directly. + + Note that it is the callers responsibility to make sure any triton functions that call this function have the `.hash` value reset to None. + """ + self.hash = None + self._src = new_src + + def _set_src(self): + raise AttributeError("Cannot set attribute 'src' directly. " + "Use '_unsafe_update_src()' and manually clear `.hash` of all callers" + "instead.") + + def _get_src(self): + return self._src + + src = property(fget=_get_src, fset=_set_src) + + +@dataclass +class JitFunctionInfo: + module: ModuleType + name: str + jit_function: JITFunction + + +def compute_cache_key(kernel_key_cache, specialization, options): + key = (tuple(specialization), str(options)) + cache_key = kernel_key_cache.get(key, None) + if cache_key is not None: + return cache_key + + # Replace JITCallable objects with their hash, so the cache key will change if the src is updated + def replace_callables(obj): + if isinstance(obj, list): + return [replace_callables(arg) for arg in obj] + elif is_namedtuple(obj): + results = [replace_callables(arg) for arg in obj] + return obj.__class__(*results) + elif isinstance(obj, tuple): + return tuple(replace_callables(arg) for arg in obj) + elif isinstance(obj, JITCallable): + return obj.cache_key + return obj + + cache_key = str(replace_callables(specialization)) + str(options) + kernel_key_cache[key] = cache_key + return cache_key + + +def convert_to_tuple_if_list(item): + # If the incoming item is a list, recursively iterate through it to convert all lists therein into tuples + if not isinstance(item, list): + return item + + # The value must be a list at this point + for i, nested_value in enumerate(item): + item[i] = convert_to_tuple_if_list(nested_value) + + return tuple(item) + + +class JITFunction(JITCallable, KernelInterface[T]): + + def is_gluon(self): + return False + + def _call_hook( + self, + hook, + key, + signature, + device, + constants, + options, + configs, + is_warmup, + ) -> bool | None: + if not hook: + return None + + name = self.fn.__qualname__ + module = self.fn.__module__ + arg_reprs = ", ".join([f"{param.name}: {ty}" for param, ty in zip(self.params, key[1])]) + repr = f"{name}[num_warps={options.num_warps}, num_ctas={options.num_ctas}, num_stages={options.num_stages}, enable_fp_fusion={options.enable_fp_fusion}, launch_cooperative_grid={options.launch_cooperative_grid}]({arg_reprs})" + full_name = get_full_name(self.fn) + + specialization_data = serialize_specialization_data(full_name, signature, constants, configs[0], options, key) + + kwargs = { + 'signature': signature, + 'device': device, + 'constants': constants, + 'num_warps': options.num_warps, + 'num_ctas': options.num_ctas, + 'num_stages': options.num_stages, + 'enable_fp_fusion': options.enable_fp_fusion, + 'launch_cooperative_grid': options.launch_cooperative_grid, + 'extern_libs': options.extern_libs, + 'configs': configs, + 'specialization_data': specialization_data, + 'is_warmup': is_warmup, + } + + return hook( + key=key, + repr=repr, + fn=JitFunctionInfo(module, name, self), + compile={"key": key, **kwargs}, + is_manual_warmup=is_warmup, + already_compiled=False, + ) + + def add_pre_run_hook(self, hook): + ''' + Add a hook that will be executed prior to the execution of run + function with args and kwargs passed into the kernel + ''' + assert callable(hook) + self.pre_run_hooks.append(hook) + + def create_binder(self): + """ + Precompute as much as possible. + """ + from ..compiler import CompiledKernel, compile, ASTSource, make_backend + target = driver.active.get_current_target() + backend = make_backend(target) + self.CompiledKernel = CompiledKernel + self.compile = compile + self.ASTSource = ASTSource + binder = create_function_from_signature(self.signature, self.params, backend) + return {}, {}, target, backend, binder + + def _pack_args(self, backend, kwargs, bound_args, specialization, options): + # options + options = backend.parse_options(kwargs) + # signature + sigkeys = [x.name for x in self.params] + sigvals = [x[0] for x in specialization] + signature = {k: v for (k, v) in zip(sigkeys, sigvals)} + # check arguments + assert "device_type" not in kwargs, "device_type option is deprecated; current target will be used" + assert "device" not in kwargs, "device option is deprecated; current device will be used" + assert "stream" not in kwargs, "stream option is deprecated; current stream will be used" + for k in kwargs: + if k not in options.__dict__ and k not in sigkeys: + raise KeyError("Keyword argument %s was specified but unrecognised" % k) + # constexprs + constexprs = find_paths_if(sigvals, lambda _, val: val == "constexpr") + constexprs = {path: get_iterable_path(list(bound_args.values()), path) for path in constexprs} + # attributes + attrvals = [x[1] for x in specialization] + attrs = find_paths_if(attrvals, lambda _, x: isinstance(x, str)) + attrs = {k: backend.parse_attr(get_iterable_path(attrvals, k)) for k in attrs} + + return options, signature, constexprs, attrs + + def run(self, *args, grid, warmup, **kwargs): + kwargs["debug"] = kwargs.get("debug", self.debug) or knobs.runtime.debug + kwargs["instrumentation_mode"] = knobs.compilation.instrumentation_mode + + # parse options + device = driver.active.get_current_device() + stream = driver.active.get_current_stream(device) + + # Execute pre run hooks with args and kwargs + for hook in self.pre_run_hooks: + hook(*args, **kwargs) + + kernel_cache, kernel_key_cache, target, backend, binder = self.device_caches[device] + # specialization is list[tuple[str, Any]], where first element of tuple is + # the type and the second parameter is the 'specialization' value. + bound_args, specialization, options = binder(*args, **kwargs) + + key = compute_cache_key(kernel_key_cache, specialization, options) + kernel = kernel_cache.get(key, None) + + # Kernel is not cached; we have to compile. + if kernel is None: + options, signature, constexprs, attrs = self._pack_args(backend, kwargs, bound_args, specialization, + options) + + kernel = self._do_compile(key, signature, device, constexprs, options, attrs, warmup) + if kernel is None: + return None + + # Check that used global values have not changed. + not_present = object() + for (name, _), (val, globals_dict) in self.used_global_vals.items(): + if (newVal := globals_dict.get(name, not_present)) != val: + raise RuntimeError( + f"Global variable {name} has changed since we compiled this kernel, from {val} to {newVal}") + + if not warmup: + # canonicalize grid + assert grid is not None + if callable(grid): + grid = grid(bound_args) + grid_size = len(grid) + grid_0 = grid[0] + grid_1 = grid[1] if grid_size > 1 else 1 + grid_2 = grid[2] if grid_size > 2 else 1 + if hasattr(kernel, "result"): + kernel = kernel.result() + # launch kernel + launch_metadata = kernel.launch_metadata(grid, stream, *bound_args.values()) + kernel.run(grid_0, grid_1, grid_2, stream, kernel.function, kernel.packed_metadata, launch_metadata, + knobs.runtime.launch_enter_hook, knobs.runtime.launch_exit_hook, *bound_args.values()) + return kernel + + def repr(self, _): + return self._fn_name if self._repr is None else self._repr(_) + + def __init__(self, fn, version=None, do_not_specialize=None, do_not_specialize_on_alignment=None, debug=None, + noinline=None, repr=None, launch_metadata=None): + do_not_specialize = do_not_specialize if do_not_specialize else [] + do_not_specialize_on_alignment = do_not_specialize_on_alignment if do_not_specialize_on_alignment else [] + + super().__init__(fn) + self.module = fn.__module__ + self.version = version + self.do_not_specialize = do_not_specialize + self.do_not_specialize_on_alignment = do_not_specialize_on_alignment + self._repr = repr + self.launch_metadata = launch_metadata + + self.params = [] + for i, param in enumerate(self.signature.parameters.values()): + dns = i in do_not_specialize or param.name in do_not_specialize + dns_oa = i in do_not_specialize_on_alignment or param.name in do_not_specialize_on_alignment + self.params.append(KernelParam(i, param, dns, dns_oa)) + + # cache of just-in-time compiled kernels + self.device_caches = defaultdict(self.create_binder) + + # JITFunction can be instantiated as kernel + # when called with a grid using __getitem__ + self.kernel = None + self.debug = debug + self.noinline = noinline + + # TODO(jlebar): Remove uses of these fields outside this file, then + # remove the fields here. + self.arg_names = [p.name for p in self.params] + self.constexprs = [p.num for p in self.params if p.is_constexpr] + + # Hooks that will be called prior to executing "run" + self.pre_run_hooks = [] + + def preload(self, specialization_data): + import json + import triton.language as tl + device = driver.active.get_current_device() + deserialized_obj = json.loads(specialization_data) + if deserialized_obj['name'] != self._fn_name: + raise RuntimeError( + f"Specialization data is for {deserialized_obj['name']} but trying to preload for {self._fn_name}") + constant_keys = map(tuple, deserialized_obj['constant_keys']) + constant_vals = deserialized_obj['constant_vals'] + constexprs = { + key: + tl.dtype(value) if tl.dtype.is_dtype(value) else + tl.constexpr(value['constexpr']) if isinstance(value, dict) and 'constexpr' in value else value + for key, value in zip(constant_keys, constant_vals) + } + attrs_keys = map(tuple, deserialized_obj['attrs_keys']) + attrs_vals = deserialized_obj['attrs_vals'] + attrs = dict(zip(attrs_keys, attrs_vals)) + # JSON serializes tuples as lists, so they need to be converted back; + # This can be done unconditionally, since lists are not accepted in Triton kernel signatures. + signature = {key: convert_to_tuple_if_list(value) for key, value in deserialized_obj['signature'].items()} + options = { + key: tuple(value) if isinstance(value, list) else value + for key, value in deserialized_obj['options'].items() + } + key = deserialized_obj['key'] + _, _, _, backend, _ = self.device_caches[device] + options = backend.parse_options(options) + return self._do_compile( + key, + signature, + device, + constexprs, + options, + attrs, + warmup=True, + ) + + def _do_compile(self, key, signature, device, constexprs, options, attrs, warmup): + kernel_cache, _, target, backend, _ = self.device_caches[device] + + if self._call_hook(knobs.runtime.jit_cache_hook, key, signature, device, constexprs, options, [attrs], warmup): + return None + src = self.ASTSource(self, signature, constexprs, attrs) + + async_mode = _async_compile.active_mode.get() + if async_mode is not None: + + env_vars = get_cache_invalidating_env_vars() + cache_key = get_cache_key(src, backend, options, env_vars) + + def async_compile(): + return self.compile(src, target=target, options=options.__dict__, _env_vars=env_vars) + + def finalize_compile(kernel): + kernel_cache[key] = kernel + self._call_hook(knobs.runtime.jit_post_compile_hook, key, signature, device, constexprs, options, + [attrs], warmup) + + kernel = async_mode.submit(cache_key, async_compile, finalize_compile) + else: + kernel = self.compile(src, target=target, options=options.__dict__) + kernel_cache[key] = kernel + self._call_hook(knobs.runtime.jit_post_compile_hook, key, signature, device, constexprs, options, [attrs], + warmup) + return kernel + + def __call__(self, *args, **kwargs): + raise RuntimeError("Cannot call @triton.jit'd outside of the scope of a kernel") + + def __repr__(self): + return f"JITFunction({self.module}:{self.fn.__qualname__})" + + +# ----------------------------------------------------------------------------- +# `jit` decorator +# ----------------------------------------------------------------------------- + + +@overload +def jit(fn: T) -> JITFunction[T]: + ... + + +@overload +def jit( + *, + version=None, + repr: Optional[Callable] = None, + launch_metadata: Optional[Callable] = None, + do_not_specialize: Optional[Iterable[int | str]] = None, + do_not_specialize_on_alignment: Optional[Iterable[int | str]] = None, + debug: Optional[bool] = None, + noinline: Optional[bool] = None, +) -> Callable[[T], JITFunction[T]]: + ... + + +def jit( + fn: Optional[T] = None, + *, + version=None, + repr: Optional[Callable] = None, + launch_metadata: Optional[Callable] = None, + do_not_specialize: Optional[Iterable[int | str]] = None, + do_not_specialize_on_alignment: Optional[Iterable[int | str]] = None, + debug: Optional[bool] = None, + noinline: Optional[bool] = None, +) -> KernelInterface[T]: + """ + Decorator for JIT-compiling a function using the Triton compiler. + + :note: When a jit'd function is called, arguments are + implicitly converted to pointers if they have a :code:`.data_ptr()` method + and a `.dtype` attribute. + + :note: This function will be compiled and run on the GPU. It will only have access to: + + * python primitives, + * builtins within the triton package, + * arguments to this function, + * other jit'd functions + + :param fn: the function to be jit-compiled + :type fn: Callable + """ + + def decorator(fn: T) -> JITFunction[T]: + assert callable(fn) + if knobs.runtime.interpret: + from .interpreter import InterpretedFunction + return InterpretedFunction(fn, version=version, do_not_specialize=do_not_specialize, + do_not_specialize_on_alignment=do_not_specialize_on_alignment, debug=debug, + noinline=noinline, repr=repr, launch_metadata=launch_metadata) + else: + return JITFunction( + fn, + version=version, + do_not_specialize=do_not_specialize, + do_not_specialize_on_alignment=do_not_specialize_on_alignment, + debug=debug, + noinline=noinline, + repr=repr, + launch_metadata=launch_metadata, + ) + + if fn is not None: + return decorator(fn) + + else: + return decorator + + +# ----------------------------------------------------------------------------- +# Utilities for mocking tensors +# ----------------------------------------------------------------------------- + + +class MockTensor: + """ + Can be used in place of real tensors when calling: + kernel.warmup(MockTensor(torch.float32), ...) + """ + + @staticmethod + def wrap_dtype(arg): + if arg.__class__.__name__ == "dtype" and arg.__module__ == "torch": + return MockTensor(arg) + return arg + + def __init__(self, dtype, shape=None): + if shape is None: + shape = [1] + self.dtype = dtype + self.shape = shape + + def stride(self): + strides = [1] + for size in self.shape[1:]: + strides.append(strides[-1] * size) + return tuple(reversed(strides)) + + @staticmethod + def data_ptr(): + return 0 # optimistically assumes multiple of 16 + + @staticmethod + def ptr_range(): + return 0 # optimistically assumes 32 bit pointer range + + +class TensorWrapper: + + def __init__(self, base, dtype): + self.dtype = dtype + self.base = base + self.data = base.data + self.device = base.device + self.shape = self.base.shape + + def data_ptr(self): + return self.base.data_ptr() + + def stride(self, *args): + return self.base.stride(*args) + + def __str__(self) -> str: + return f"TensorWrapper[{self.dtype}]({self.base})" + + def element_size(self): + return self.base.element_size() + + def cpu(self): + return TensorWrapper(self.base.cpu(), self.dtype) + + def copy_(self, other): + self.base.copy_(other.base) + + def clone(self): + return TensorWrapper(self.base.clone(), self.dtype) + + def to(self, device): + return TensorWrapper(self.base.to(device), self.dtype) + + def new_empty(self, sizes): + return TensorWrapper(self.base.new_empty(sizes), self.dtype) + + +def reinterpret(tensor, dtype): + if isinstance(tensor, TensorWrapper): + if dtype == tensor.base.dtype: + # Reinterpreting to the original interpretation; return the base. + return tensor.base + else: + # Reinterpreting a wrapped tensor to a different type. + return TensorWrapper(tensor.base, dtype) + elif hasattr(tensor, "data_ptr"): + # A new wrapper is needed around an unwrapped tensor. + return TensorWrapper(tensor, dtype) + else: + raise TypeError(f"Cannot reinterpret a {type(tensor)}.") + + +def get_jit_fn_file_line(fn): + base_fn = fn + while not isinstance(base_fn, JITCallable): + base_fn = base_fn.fn + file_name = base_fn.fn.__code__.co_filename + begin_line = base_fn.starting_line_number + # Match the following pattern: + # @triton.autotune(...) <- foo.__code__.co_firstlineno + # @triton.heuristics(...) + # @triton.jit + # def foo(...): <- this line is the first line + for idx, line in enumerate(base_fn.raw_src): + if line.strip().startswith("def "): + begin_line += idx + break + return file_name, begin_line + + +class BoundConstexprFunction(JITCallable): + + def __init__(self, instance, fn): + self.__self__ = instance + self.__func__ = fn + + @property + def cache_key(self): + return self.__func__.cache_key + + def __call__(self, *args, **kwargs): + return self.__func__(self.__self__, *args, **kwargs) + + +class ConstexprFunction(JITCallable): + + def __init__(self, fn): + super().__init__(fn) + + def __get__(self, obj, objclass): + # Create a bound function to support constexpr_function methods + if obj is not None: + return BoundConstexprFunction(obj, self) + return self + + def __call__(self, *args, _semantic=None, **kwargs): + from triton.language.core import _unwrap_if_constexpr, constexpr + # de-constexpr arguments and discard the _semantic keyword argument: + args = [_unwrap_if_constexpr(x) for x in args] + kwargs = {k: _unwrap_if_constexpr(v) for (k, v) in kwargs.items()} + + # call the raw Python function f: + res = self.fn(*args, **kwargs) + + if _semantic is None: + # Not called by triton code generator, e.g. in host code, another constexpr function, or even an aggreate's __init__ function + return res + + # convert result back to a Triton constexpr: + if knobs.runtime.interpret: + return res # No constexpr in interpreter + return constexpr(res) + + +def constexpr_function(fn): + """ + Wraps an arbitrary Python function so that it can be called at + compile-time on constexpr arguments in a Triton function and + returns a constexpr result. + """ + return ConstexprFunction(fn) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/tools/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/tools/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fb4e3a7a82c5aa7d3c6144ac7f6e793f8c4e9d5a --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/tools/__init__.py @@ -0,0 +1 @@ +from triton._C.libtriton.linear_layout import LinearLayout diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/tools/build_extern.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/tools/build_extern.py new file mode 100644 index 0000000000000000000000000000000000000000..8f0168d59d7af045bde68a508a000654f4893bb1 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/tools/build_extern.py @@ -0,0 +1,365 @@ +import argparse +import subprocess +from abc import ABC, abstractmethod +from typing import Dict, List, Optional + + +class Symbol: + _name: str + _op_name: str + _ret_type: str + _arg_names: List[str] + _arg_types: List[str] + + def __init__( + self, + name: str, + op_name: str, + ret_type: str, + arg_names: List[str], + arg_types: List[str], + ) -> None: + ''' + A symbol is a function declaration. + :param name: name of the symbol + :param op_name: name of the operation + :param ret_type: return type of the operation + :param arg_names: names of the arguments + :param arg_types: types of the arguments + ''' + self._name = name + self._op_name = op_name + self._ret_type = ret_type + self._arg_names = list(arg_names) + self._arg_types = list(arg_types) + + @property + def name(self) -> str: + return self._name + + @property + def op_name(self) -> str: + return self._op_name + + @property + def ret_type(self) -> str: + return self._ret_type + + @property + def arg_names(self) -> List[str]: + return self._arg_names + + @property + def arg_types(self) -> List[str]: + return self._arg_types + + +def convert_type(type_str) -> Optional[str]: + if type_str == "i32": + return "int32" + elif type_str == "u32": + return "uint32" + elif type_str == "i64": + return "int64" + elif type_str == "u64": + return "uint64" + elif type_str == "float": + return "fp32" + elif type_str == "double": + return "fp64" + else: + # ignore other types, such as pointer types + return None + + +def to_unsigned(type_str) -> str: + if type_str == "int32": + return "uint32" + elif type_str == "int64": + return "uint64" + else: + return type_str + + +class ExternLibrary(ABC): + _name: str + _path: str + _symbols: Dict[str, Symbol] + _format: bool + _grouping: bool + + def __init__( + self, + name: str, + path: str, + format: bool = True, + grouping: bool = True, + ) -> None: + ''' + Abstract class for extern library. + :param name: name of the library + :param path: path of the library + :param format: whether to format the generated stub file + ''' + self._name = name + self._path = path + self._symbols = {} + self._format = format + self._grouping = grouping + + @property + def name(self) -> str: + return self._name + + @property + def path(self) -> str: + return self._path + + @property + def symbols(self) -> Dict[str, Symbol]: + return self._symbols + + @property + def grouping(self) -> bool: + return self._grouping + + @abstractmethod + def parse_symbols(self, input_file) -> None: + pass + + @abstractmethod + def _output_stubs(self) -> str: + pass + + def generate_stub_file(self, output_dir) -> None: + file_str = self._output_stubs() + if file_str is None or len(file_str) == 0: + raise Exception("file_str is empty") + + output_file = f"{output_dir}/{self._name}.py" + with open(output_file, "w") as f: + f.write(file_str) + f.close() + if self._format: + subprocess.Popen(["autopep8", "-a", "-r", "-i", output_file], stdout=subprocess.PIPE).communicate() + subprocess.Popen(["isort", output_file], stdout=subprocess.PIPE).communicate() + + +class Libdevice(ExternLibrary): + _symbol_groups: Dict[str, List[Symbol]] + + def __init__(self, path) -> None: + ''' + Constructor for Libdevice. + :param path: path of the libdevice library + ''' + super().__init__("libdevice", path) + self._symbol_groups = {} + self.is_pure = True + + @staticmethod + def _extract_symbol(line) -> Optional[Symbol]: + # Extract symbols from line in the following format: + # "define [internal] @(,)" + entries = line.split("@") + ret_str = entries[0] + func_str = entries[1] + # Get ret_type, skip internal symbols + ret_strs = ret_str.split() + if ret_strs[1] == "internal": + return None + ret_type = convert_type(ret_strs[1]) + if ret_type is None: + return None + # Get function name + func_strs = func_str.split("(") + func_name = func_strs[0].replace("@", "") + op_name = func_name.replace("__nv_", "") + if 'ieee' in op_name: + return None + # Get arg_types + arg_strs = func_strs[1].split(",") + arg_types = [] + arg_names = [] + for i, arg_str in enumerate(arg_strs): + arg_type = convert_type(arg_str.split()[0]) + if arg_type is None: + return None + arg_name = 'arg' + str(i) + arg_types.append(arg_type) + arg_names.append(arg_name) + if op_name == "sad": + # Special case for sad, where the last argument is an unsigned int + arg_types[-1] = to_unsigned(arg_types[-1]) + elif op_name.startswith("u"): + # LLVM does not differentiate between signed and unsigned integer type. + # We have to convert the types to unsigned + ret_type = to_unsigned(ret_type) + for i, arg_type in enumerate(arg_types): + arg_types[i] = to_unsigned(arg_type) + return Symbol(func_name, op_name, ret_type, arg_names, arg_types) + + def _group_symbols(self) -> None: + symbol_set = {} + for symbol in self._symbols.values(): + op_name = symbol.op_name + symbol_set[op_name] = symbol + + # Group functions together by renaming. + renaming = { + 'llabs': 'abs', 'acosf': 'acos', 'acoshf': 'acosh', 'dadd_rd': 'add_rd', 'fadd_rd': 'add_rd', 'dadd_rn': + 'add_rn', 'fadd_rn': 'add_rn', 'dadd_ru': 'add_ru', 'fadd_ru': 'add_ru', 'dadd_rz': 'add_rz', 'fadd_rz': + 'add_rz', 'asinf': 'asin', 'asinhf': 'asinh', 'atanf': 'atan', 'atan2f': 'atan2', 'atanhf': 'atanh', + 'brevll': 'brev', 'cbrtf': 'cbrt', 'ceilf': 'ceil', 'clzll': 'clz', 'copysignf': 'copysign', 'cosf': 'cos', + 'coshf': 'cosh', 'cospif': 'cospi', 'cyl_bessel_i0f': 'cyl_bessel_i0', 'cyl_bessel_i1f': 'cyl_bessel_i1', + 'fdiv_rd': 'div_rd', 'ddiv_rd': 'div_rd', 'fdiv_rn': 'div_rn', 'ddiv_rn': 'div_rn', 'fdiv_ru': 'div_ru', + 'ddiv_ru': 'div_ru', 'fdiv_rz': 'div_rz', 'ddiv_rz': 'div_rz', 'erff': 'erf', 'erfcf': 'erfc', 'erfcinvf': + 'erfcinv', 'erfcxf': 'erfcx', 'erfinvf': 'erfinv', 'expf': 'exp', 'exp10f': 'exp10', 'exp2f': 'exp2', + 'expm1f': 'expm1', 'fabsf': 'abs', 'fabs': 'abs', 'fast_fdividef': 'fast_dividef', 'fdimf': 'fdim', 'ffsll': + 'ffs', 'floorf': 'floor', 'fmaf': 'fma', 'fmaf_rd': 'fma_rd', 'fmaf_rn': 'fma_rn', 'fmaf_ru': 'fma_ru', + 'fmaf_rz': 'fma_rz', 'fmodf': 'fmod', 'uhadd': 'hadd', 'hypotf': 'hypot', 'ilogbf': 'ilogb', 'isinff': + 'isinf', 'isinfd': 'isinf', 'isnanf': 'isnan', 'isnand': 'isnan', 'j0f': 'j0', 'j1f': 'j1', 'jnf': 'jn', + 'ldexpf': 'ldexp', 'lgammaf': 'lgamma', 'llrintf': 'llrint', 'llroundf': 'llround', 'logf': 'log', 'log10f': + 'log10', 'log1pf': 'log1p', 'log2f': 'log2', 'logbf': 'logb', 'umax': 'max', 'llmax': 'max', 'ullmax': + 'max', 'fmaxf': 'max', 'fmax': 'max', 'umin': 'min', 'llmin': 'min', 'ullmin': 'min', 'fminf': 'min', + 'fmin': 'min', 'dmul_rd': 'mul_rd', 'fmul_rd': 'mul_rd', 'dmul_rn': 'mul_rn', 'fmul_rn': 'mul_rn', + 'dmul_ru': 'mul_ru', 'fmul_ru': 'mul_ru', 'dmul_rz': 'mul_rz', 'fmul_rz': 'mul_rz', 'umul24': 'mul24', + 'umulhi': 'mulhi', 'mul64hi': 'mulhi', 'umul64hi': 'mulhi', 'nearbyintf': 'nearbyint', 'nextafterf': + 'nextafter', 'norm3df': 'norm3d', 'norm4df': 'norm4d', 'normcdff': 'normcdf', 'normcdfinvf': 'normcdfinv', + 'popcll': 'popc', 'powif': 'pow', 'powi': 'pow', 'powf': 'pow', 'rcbrtf': 'rcbrt', 'frcp_rd': 'rcp_rd', + 'drcp_rd': 'rcp_rd', 'frcp_rn': 'rcp_rn', 'drcp_rn': 'rcp_rn', 'frcp_ru': 'rcp_ru', 'drcp_ru': 'rcp_ru', + 'frcp_rz': 'rcp_rz', 'drcp_rz': 'rcp_rz', 'remainderf': 'remainder', 'urhadd': 'rhadd', 'rhypotf': 'rhypot', + 'rintf': 'rint', 'rnorm3df': 'rnorm3d', 'rnorm4df': 'rnorm4d', 'roundf': 'round', 'rsqrtf': 'rsqrt', + 'frsqrt_rn': 'rsqrt_rn', 'usad': 'sad', 'scalbnf': 'scalbn', 'signbitf': 'signbit', 'signbitd': 'signbit', + 'sinf': 'sin', 'sinhf': 'sinh', 'sinpif': 'sinpi', 'sqrtf': 'sqrt', 'fsqrt_rd': 'sqrt_rd', 'dsqrt_rd': + 'sqrt_rd', 'fsqrt_rn': 'sqrt_rn', 'dsqrt_rn': 'sqrt_rn', 'fsqrt_ru': 'sqrt_ru', 'dsqrt_ru': 'sqrt_ru', + 'fsqrt_rz': 'sqrt_rz', 'dsqrt_rz': 'sqrt_rz', 'fsub_rd': 'sub_rd', 'dsub_rd': 'sub_rd', 'fsub_rn': 'sub_rn', + 'dsub_rn': 'sub_rn', 'fsub_ru': 'sub_ru', 'dsub_ru': 'sub_ru', 'fsub_rz': 'sub_rz', 'dsub_rz': 'sub_rz', + 'tanf': 'tan', 'tanhf': 'tanh', 'tgammaf': 'tgamma', 'truncf': 'trunc', 'y0f': 'y0', 'y1f': 'y1', 'ynf': + 'yn' + } + + for symbol in self._symbols.values(): + op_name = symbol.op_name + if op_name in renaming: + op_name = renaming[op_name] + symbol._op_name = op_name + if op_name in self._symbol_groups: + self._symbol_groups[op_name].append(symbol) + else: + self._symbol_groups[op_name] = [symbol] + + def parse_symbols(self, input_file) -> None: + if len(self.symbols) > 0: + return + output = subprocess.check_output(["grep", "define", input_file]).decode().splitlines() + for line in output: + symbol = self._extract_symbol(line) + if symbol is None: + continue + self._symbols[symbol.name] = symbol + + self._group_symbols() + + def _output_stubs(self) -> str: + # Generate python functions in the following format: + # @extern.extern + # def (, _builder=None): + # arg_type_symbol_dict = {[arg_type]: {(symbol, ret_type)}} + # return core.extern_elementwise("libdevice", , , , _builder) + import_str = "from . import core\n" + + header_str = "" + func_str = "" + for symbols in self._symbol_groups.values(): + func_str += "@core.extern\n" + func_name_str = f"def {symbols[0].op_name}(" + for arg_name in symbols[0].arg_names: + func_name_str += f"{arg_name}, " + func_name_str += "_builder=None):\n" + + return_str = f"\treturn core.extern_elementwise(\"{self._name}\", libdevice_path(), [" + for arg_name in symbols[0].arg_names: + return_str += f"{arg_name}, " + return_str += "], \n" + + arg_type_symbol_dict_str = "{" + for symbol in symbols: + arg_type_symbol_dict_str += "(" + for arg_type in symbol.arg_types: + arg_type_symbol_dict_str += f'core.dtype("{arg_type}"),' + ret_type = f'core.dtype("{symbol.ret_type}")' + arg_type_symbol_dict_str += "): (\"" + symbol.name + "\", " + ret_type + "),\n" + arg_type_symbol_dict_str += "}" + + return_str += arg_type_symbol_dict_str + return_str += f", is_pure={self.is_pure}" + return_str += ", _builder=_builder)\n" + + func_str += func_name_str + return_str + "\n" + file_str = import_str + header_str + func_str + + return file_str + + +class LLVMDisassembler: + _path: str + _ll_file: str + + def __init__(self, path) -> None: + ''' + Invoke llvm-dis to disassemble the given file. + :param path: path to llvm-dis + ''' + self._path = path + self._ll_file = "/tmp/extern_lib.ll" + + def disasm(self, lib_path: str) -> None: + subprocess.Popen([self._path, lib_path, "-o", self.ll_file], stdout=subprocess.PIPE).communicate() + + @property + def ll_file(self) -> str: + return self._ll_file + + @property + def path(self) -> str: + return self._path + + +extern_libs = ["libdevice"] + + +def build( + llvm_dis_path: str, + lib_path: str, + lib_name: str, + output_dir: str, +) -> None: + ''' + Interface function to build the library file. + :param llvm_dis_path: path to the llvm-dis binary + :param lib_path: path to the external library file + :param lib_name: name of the library + :param output_dir: path to the output directory + ''' + if lib_name == "libdevice": + extern_lib = Libdevice(lib_path) + else: + raise Exception(f"Unknown extern library: {lib_name}") + + llvm_disassembler = LLVMDisassembler(llvm_dis_path) + llvm_disassembler.disasm(lib_path) + + extern_lib.parse_symbols(llvm_disassembler.ll_file) + extern_lib.generate_stub_file(output_dir) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--llvm-dis", dest="llvm_dis_path", help="Path to llvm-dis", default="llvm-dis") + parser.add_argument("--lib-path", dest="lib_path", help="Path to the extern library") + parser.add_argument("--lib-name", dest="lib_name", help="Name of the extern library") + parser.add_argument("--output", dest="output_dir", help="Output file path", default="/tmp/") + args = parser.parse_args() + + build(args.llvm_dis_path, args.lib_path, args.lib_name, args.output_dir) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/tools/compile.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/tools/compile.py new file mode 100644 index 0000000000000000000000000000000000000000..73085d3d316094cbd8b3ce3141f47968412cbe6c --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/tools/compile.py @@ -0,0 +1,211 @@ +import binascii +import hashlib +import importlib.util +import sys +from argparse import ArgumentParser +from dataclasses import dataclass +from pathlib import Path +from typing import List + +import triton +import triton.backends + + +@dataclass +class CompileArgs: + ''' + A class to contain arguments from command-line parser. + ''' + path: str = '' + kernel_name: str = '' + signature: str = '' + grid: str = '' + target: str | None = None + num_warps: int = 1 + num_stages: int = 3 + out_name: str | None = None + out_path: Path | None = None + + +desc = """ +Triton ahead-of-time compiler: + +This program compiles the kernel with name `kernel-name` in the file at the +provided `path` into self-contained C source-code that embeds the `cubin` +data along with utilities to load, unload and launch the kernel. + +signature is provided as a list of (optionally divisibility-hinted) types +or constexpr values, e.g. + +`compile.py --kernel-name kernel --signature "*fp32:16, i32:16, 1024, i32" --out-name kernel /path/to/kernel.py` + +will compile triton.JITFunction of name `kernel` inside the file `/path/to/kernel.py`. +Said kernel will be specialized such that argument 0, 1 are assumed to be multiple of 16, +and argument 2 is assumed to be a compile-time constant of value 1024, i.e. it won't be part of the generated prototype. + +The resulting entry point will have signature + +CUresult kernel_{specialization_suffix}(CUstream stream, unsigned gX, unsigned gY, unsigned gZ, float* arg0, int32_t arg1, int32_t arg2) + +Different such specialized entry points can be combined using the `linker.py` script. + +NOTE: when resolving the scope of /path/to/kernel.py, the file will be executed from within its parent directory with the python interpreter +used to run this `compile.py` script +""" + + +def main(): + # command-line arguments + parser = ArgumentParser(description=desc) + parser.add_argument("path", + help="Path to Python source containing desired kernel in its scope. File will be executed.") + parser.add_argument("--kernel-name", "-n", type=str, default="", help="Name of the kernel to compile", + required=True) + parser.add_argument( + "--target", "-t", type=str, default=None, + help="The target to compile towards, in format of '::'; " + "e.g., 'cuda:80:32', 'hip:gfx942:64'. Default to None, which means using current machine's GPU target") + parser.add_argument("--num-warps", "-w", type=int, default=1, help="Number of warps to launch the kernel") + parser.add_argument("--num-stages", "-ns", type=int, default=3, + help="Number of stages (meta-parameter of the kernel)") + parser.add_argument("--out-name", "-on", type=str, default=None, help="Out name for the compiled kernel") + parser.add_argument("--out-path", "-o", type=Path, default=None, help="Out filename") + parser.add_argument("--signature", "-s", type=str, help="Signature of the kernel", required=True) + parser.add_argument("--grid", "-g", type=str, help="Launch grid of the kernel", required=True) + cli_args = parser.parse_args() + args = CompileArgs(**vars(cli_args)) # A sanity check to ensure class CompileArgs is updated as well. + compile_kernel(args) + + +def compile_kernel(args: CompileArgs): + out_name = args.out_name if args.out_name else args.kernel_name + out_path = args.out_path if args.out_path else Path(out_name) + + # execute python sources and extract functions wrapped in JITFunction + arg_path = Path(args.path) + sys.path.insert(0, str(arg_path.parent)) + spec = importlib.util.spec_from_file_location(arg_path.stem, arg_path) + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + kernel = getattr(mod, args.kernel_name) + grid = args.grid.split(",") + assert len(grid) == 3 + + # validate and parse signature + signature = list(map(lambda s: s.strip(" "), args.signature.split(","))) + + def hash_signature(signature: List[str]): + m = hashlib.sha256() + m.update(" ".join(signature).encode()) + return m.hexdigest()[:8] + + meta_sig = f"warps{args.num_warps}xstages{args.num_stages}" + sig_hash = hash_signature(signature + [meta_sig]) + + def constexpr(s): + try: + ret = int(s) + return ret + except ValueError: + pass + try: + ret = float(s) + return ret + except ValueError: + pass + return None + + hints = {(i, ): constexpr(s.split(":")[1]) for i, s in enumerate(signature) if ":" in s} + hints = {k: v for k, v in hints.items() if v is not None} + constants = {kernel.arg_names[i]: constexpr(s) for i, s in enumerate(signature)} + constants = {k: v for k, v in constants.items() if v is not None} + for key, value in hints.items(): + if value == 1: + constants[kernel.arg_names[key[0]]] = value + signature = {kernel.arg_names[i]: s.split(":")[0] for i, s in enumerate(signature)} + for key in constants: + signature[key] = 'constexpr' + const_sig = 'x'.join([str(v) for v in constants.values()]) + doc_string = [f"{k}={v}" for k, v in constants.items()] + doc_string += [f"num_warps={args.num_warps}", f"num_stages={args.num_stages}"] + # compile ast into cubin + for h in hints.values(): + assert h in [1, 16], f"Only 1 and 16 are valid hints, got {h}" + attrs = {k: [["tt.divisibility", 16]] for k, v in hints.items() if v == 16} + kernel.create_binder() + src = kernel.ASTSource(fn=kernel, constexprs=constants, signature=signature, attrs=attrs) + target = triton.backends.compiler.GPUTarget(*args.target.split(":")) \ + if args.target else triton.runtime.driver.active.get_current_target() + backend = triton.compiler.make_backend(target) + kwargs = {"num_warps": args.num_warps, "num_stages": args.num_stages} + options = backend.parse_options(kwargs) + ccinfo = triton.compile(src, target=target, options=options.__dict__) + + if getattr(ccinfo.metadata, "global_scratch_size", 0) > 0: + raise RuntimeError("AOT compiling kernels with global scratch requirements is not yet implemented") + if ccinfo.metadata.profile_scratch_size > 0: + raise RuntimeError("AOT compiling kernels with profile scratch requirements is not yet implemented") + + arg_names = [] + arg_types = [] + arg_names_not_1 = [] + arg_types_not_1 = [] + for i, arg_name in enumerate(kernel.arg_names): + if arg_name not in constants: + arg_names.append(arg_name) + arg_types.append(signature[arg_name]) + arg_names_not_1.append(arg_name) + arg_types_not_1.append(signature[arg_name]) + elif hints.get((i, ), None) == 1: + arg_names.append(arg_name) + arg_types.append("i32") + + # dump C stub code + suffix = '' + for i, ty in enumerate(signature.values()): + suffix += str(i) + if hints.get((i, ), None) == 1: + suffix += 'c' + if hints.get((i, ), None) == 16: + suffix += 'd' + func_name = '_'.join([out_name, sig_hash, suffix]) + asm = ccinfo.asm[backend.binary_ext] # store binary data once + + hex_ = str(binascii.hexlify(asm))[2:-1] + + ty_to_cpp = triton.runtime.driver.active.map_python_to_cpp_type + + params = { + "kernel_name": func_name, + "triton_kernel_name": args.kernel_name, + "bin_size": len(asm), + "bin_data": ", ".join([f"0x{x}{y}" for x, y in zip(hex_[::2], hex_[1::2])]), + "signature": ", ".join([f"{ty_to_cpp(ty)} {name}" for name, ty in zip(arg_names_not_1, arg_types_not_1)]), + "full_signature": ", ".join([f"{ty_to_cpp(ty)} {name}" for name, ty in zip(arg_names, arg_types)]), + "arg_pointers": ", ".join([f"&{arg}" for arg in arg_names_not_1] + ["&global_scratch"] + ["&profile_scratch"]), + "num_args": len(arg_names_not_1) + 2, # +2 for global and profile scratch + "kernel_docstring": doc_string, + "shared": ccinfo.metadata.shared, + "num_warps": args.num_warps, + "algo_info": "_".join([const_sig, meta_sig]), + "gridX": grid[0], + "gridY": grid[1], + "gridZ": grid[2], + "_placeholder": "", + "warp_size": target.warp_size, + } + output_files = [] + backend_name = target.backend + template_dir = Path(__file__).parent / "extra" / backend_name + for template_path in template_dir.glob('compile.*'): + ext = template_path.suffix + output_file = out_path.with_suffix(f".{sig_hash}_{suffix}{ext}") + with output_file.open("w") as fp: + fp.write(template_path.read_text().format(**params)) + output_files.append(output_file) + + return func_name, output_files + + +if __name__ == "__main__": + main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/tools/disasm.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/tools/disasm.py new file mode 100644 index 0000000000000000000000000000000000000000..c2301fd2eaab5b7e1e7b6b1f2f18e2962b26cabd --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/tools/disasm.py @@ -0,0 +1,143 @@ +# MIT License + +# Copyright (c) 2020 Da Yan @ HKUST + +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: + +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. + +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +import functools +import os +import re +import subprocess +import tempfile + +FLINE_RE = re.compile(r'\s*/\*\w{4}\*/\s*([^;]*;)\s*/\* 0x(\w{16}) \*/\s*') +SLINE_RE = re.compile(r'\s*/\* 0x(\w{16}) \*/\s*') +FNAME_RE = re.compile(r'\s*Function : (\w+)\s*') +BRA_RE = re.compile(r'(.*BRA(?:\.U)? )(0x\w+);') + + +def parseCtrl(sline): + enc = int(SLINE_RE.match(sline).group(1), 16) + stall = (enc >> 41) & 0xf + yld = (enc >> 45) & 0x1 + wrtdb = (enc >> 46) & 0x7 + readb = (enc >> 49) & 0x7 + watdb = (enc >> 52) & 0x3f + + yld_str = 'Y' if yld == 0 else '-' + wrtdb_str = '-' if wrtdb == 7 else str(wrtdb) + readb_str = '-' if readb == 7 else str(readb) + watdb_str = '--' if watdb == 0 else f'{watdb:02d}' + return f'{watdb_str}:{readb_str}:{wrtdb_str}:{yld_str}:{stall:x}' + + +def processSassLines(fline, sline, labels): + asm = FLINE_RE.match(fline).group(1) + # Remove tailing space + if asm.endswith(" ;"): + asm = asm[:-2] + ";" + ctrl = parseCtrl(sline) + # BRA target address + if BRA_RE.match(asm) is not None: + target = int(BRA_RE.match(asm).group(2), 16) + if target in labels: + pass + else: + labels[target] = len(labels) + return (f'{ctrl}', f'{asm}') + + +@functools.lru_cache() +def get_sass(cubin_asm, fun=None): + fd, path = tempfile.mkstemp() + try: + with open(fd, 'wb') as cubin: + cubin.write(cubin_asm) + sass = extract(path, fun) + finally: + os.remove(path) + return sass + + +def path_to_cuobjdump(): + from triton import knobs + return knobs.nvidia.cuobjdump.path + + +def extract(file_path, fun): + cuobjdump = path_to_cuobjdump() + if fun is None: + sass_str = subprocess.check_output([cuobjdump, "-sass", file_path]) + else: + sass_str = subprocess.check_output([cuobjdump, "-fun", fun, "-sass", file_path]) + sass_lines = sass_str.splitlines() + line_idx = 0 + while line_idx < len(sass_lines): + line = sass_lines[line_idx].decode() + # format: + # function : + # .headerflags: ... + # /*0000*/ asmstr /*0x...*/ + # /*0x...*/ + + # Looking for new function header (function: ) + while FNAME_RE.match(line) is None: + line_idx += 1 + if line_idx < len(sass_lines): + line = sass_lines[line_idx].decode() + else: + return + + fname = FNAME_RE.match(line).group(1) + ret = '' + ret += f'Function:{fname}\n' + line_idx += 2 # bypass .headerflags + line = sass_lines[line_idx].decode() + # Remapping address to label + labels = {} # address -> label_idx + # store sass asm in buffer and them print them (for labels) + # (ctrl, asm) + asm_buffer = [] + while FLINE_RE.match(line) is not None: + # First line (Offset ASM Encoding) + fline = sass_lines[line_idx].decode() + line_idx += 1 + # Second line (Encoding) + sline = sass_lines[line_idx].decode() + line_idx += 1 + asm_buffer.append(processSassLines(fline, sline, labels)) + # peek the next line + line = sass_lines[line_idx].decode() + # Print sass + # label naming convention: LBB#i + for idx, (ctrl, asm) in enumerate(asm_buffer): + # Print label if this is BRA target + offset = idx * 16 + if offset in labels: + label_name = f'LBB{labels[offset]}' + ret += f'{label_name}:\n' + ret += ctrl + '\t' + # if this is BRA, remap offset to label + if BRA_RE.match(asm): + target = int(BRA_RE.match(asm).group(2), 16) + target_name = f'LBB{labels[target]}' + asm = BRA_RE.sub(rf'\1{target_name};', asm) + ret += asm + '\n' + ret += '\n' + return ret diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/tools/extra/cuda/compile.c b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/tools/extra/cuda/compile.c new file mode 100644 index 0000000000000000000000000000000000000000..94e4d15086c7c62ef562a81d99e600950941b1f7 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/tools/extra/cuda/compile.c @@ -0,0 +1,69 @@ +/* clang-format off */ +#include +#include +#include +#include +#include + + +// helpers to check for cuda errors +#define CUDA_CHECK(ans) {{\ + gpuAssert((ans), __FILE__, __LINE__);\ + }}\ + +static inline void gpuAssert(CUresult code, const char *file, int line) {{ + if (code != CUDA_SUCCESS) {{ + const char *prefix = "Triton Error [CUDA]: "; + const char *str; + cuGetErrorString(code, &str); + char err[1024] = {{0}}; + strcat(err, prefix); + strcat(err, str); + printf("%s\\n", err); + exit(code); + }} +}} + +// globals +#define CUBIN_NAME {kernel_name}_cubin +CUmodule {kernel_name}_mod = NULL; +CUfunction {kernel_name}_func = NULL; +unsigned char CUBIN_NAME[{bin_size}] = {{ {bin_data} }}; + + +void unload_{kernel_name}(void) {{ + CUDA_CHECK(cuModuleUnload({kernel_name}_mod)); +}} + +// TODO: some code duplication with `runtime/backend/cuda.c` +void load_{kernel_name}() {{ + int dev = 0; + void *bin = (void *)&CUBIN_NAME; + int shared = {shared}; + CUDA_CHECK(cuModuleLoadData(&{kernel_name}_mod, bin)); + CUDA_CHECK(cuModuleGetFunction(&{kernel_name}_func, {kernel_name}_mod, "{triton_kernel_name}")); + // set dynamic shared memory if necessary + int shared_optin; + CUDA_CHECK(cuDeviceGetAttribute(&shared_optin, CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_BLOCK_OPTIN, dev)); + if (shared > 49152 && shared_optin > 49152) {{ + CUDA_CHECK(cuFuncSetCacheConfig({kernel_name}_func, CU_FUNC_CACHE_PREFER_SHARED)); + CUDA_CHECK(cuFuncSetAttribute({kernel_name}_func, CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES, shared_optin)) + }} +}} + +/* +{kernel_docstring} +*/ +CUresult {kernel_name}(CUstream stream, {signature}) {{ + if ({kernel_name}_func == NULL) + load_{kernel_name}(); + unsigned int gX = {gridX}; + unsigned int gY = {gridY}; + unsigned int gZ = {gridZ}; + CUdeviceptr global_scratch = 0; + CUdeviceptr profile_scratch = 0; + void *args[{num_args}] = {{ {arg_pointers} }}; + // TODO: shared memory + if(gX * gY * gZ > 0) + return cuLaunchKernel({kernel_name}_func, gX, gY, gZ, {num_warps} * {warp_size}, 1, 1, {shared}, stream, args, NULL); +}} diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/tools/extra/cuda/compile.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/tools/extra/cuda/compile.h new file mode 100644 index 0000000000000000000000000000000000000000..d98b7063b6ae6292b65b61abf5a30c58b7d28e95 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/tools/extra/cuda/compile.h @@ -0,0 +1,14 @@ +#ifndef TT_KERNEL_INCLUDES +#define TT_KERNEL_INCLUDES + +#include +#include +#include +#include + +#endif + +void unload_{kernel_name}(void); +void load_{kernel_name}(void); +// tt-linker: {kernel_name}:{full_signature}:{algo_info} +CUresult{_placeholder} {kernel_name}(CUstream stream, {signature}); diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/tools/extra/hip/compile.cpp b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/tools/extra/hip/compile.cpp new file mode 100644 index 0000000000000000000000000000000000000000..dd554e96cc5e45f69e69d2e0096785615dc769b3 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/tools/extra/hip/compile.cpp @@ -0,0 +1,67 @@ +// SPDX-License-Identifier: MIT +// Copyright (c) 2025, Advanced Micro Devices, Inc. All rights reserved. + +/* clang-format off */ +#include +#include +#include +#include +#include + +// helpers to check for hip errors +#define HIP_CHECK(ans) {{\ + gpuAssert((ans), __FILE__, __LINE__);\ + }}\ + +static inline void gpuAssert(hipError_t code, const char *file, int line) {{ + if (code != hipSuccess) {{ + const char *prefix = "Triton Error [HIP]: "; + const char *str; + hipDrvGetErrorString(code, &str); + char err[1024] = {{0}}; + strcat(err, prefix); + strcat(err, str); + printf("%s\\n", err); + exit(code); + }} +}} + +// globals +#define HSACO_NAME {kernel_name}_hsaco +hipModule_t {kernel_name}_mod = nullptr; +hipFunction_t {kernel_name}_func = nullptr; +unsigned char HSACO_NAME[{bin_size}] = {{ {bin_data} }}; + + +void unload_{kernel_name}(void) {{ + HIP_CHECK(hipModuleUnload({kernel_name}_mod)); +}} + + +void load_{kernel_name}() {{ + int dev = 0; + void *bin = (void *)&HSACO_NAME; + int shared = {shared}; + HIP_CHECK(hipModuleLoadData(&{kernel_name}_mod, bin)); + HIP_CHECK(hipModuleGetFunction(&{kernel_name}_func, {kernel_name}_mod, "{triton_kernel_name}")); +}} + +/* +{kernel_docstring} +*/ +hipError_t {kernel_name}(hipStream_t stream, {signature}) {{ + if ({kernel_name}_func == nullptr) + load_{kernel_name}(); + unsigned int gX = {gridX}; + unsigned int gY = {gridY}; + unsigned int gZ = {gridZ}; + hipDeviceptr_t global_scratch = 0; + hipDeviceptr_t profile_scratch = 0; + void *args[{num_args}] = {{ {arg_pointers} }}; + + // TODO: shared memory + if(gX * gY * gZ > 0) + return hipModuleLaunchKernel({kernel_name}_func, gX, gY, gZ, {num_warps} * {warp_size}, 1, 1, {shared}, stream, args, nullptr); + else + return hipErrorInvalidValue; +}} diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/tools/extra/hip/compile.h b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/tools/extra/hip/compile.h new file mode 100644 index 0000000000000000000000000000000000000000..cc5007ad939277df890306a84a91c0b87f1c8825 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/tools/extra/hip/compile.h @@ -0,0 +1,13 @@ +// SPDX-License-Identifier: MIT +// Copyright (c) 2025, Advanced Micro Devices, Inc. All rights reserved. + +#pragma once + +#include +#include +#include +#include + +void unload_{kernel_name}(void); +void load_{kernel_name}(void); +hipError_t{_placeholder} {kernel_name}(hipStream_t stream, {signature}); diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/tools/link.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/tools/link.py new file mode 100644 index 0000000000000000000000000000000000000000..75a1157a52f92bbd5d2eae640af97ea360da2ef3 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/tools/link.py @@ -0,0 +1,322 @@ +from collections import defaultdict +from pathlib import Path +from typing import Sequence, Union + +from dataclasses import dataclass + + +def _exists(x): + return x is not None + + +class LinkerError(Exception): + pass + + +@dataclass +class KernelLinkerMeta: + orig_kernel_name: str + arg_names: Sequence[str] + arg_ctypes: Sequence[str] + sizes: Sequence[Union[int, None]] + sig_hash: str + triton_suffix: str + suffix: str + num_specs: int + """ number of specialized arguments """ + + +class HeaderParser: + + def __init__(self) -> None: + import re + + # [kernel_name, c signature] + self.linker_directives = re.compile("//[\\s]*tt-linker:[\\s]*([\\w]+):(.+):(.+)") + # [name, hash, suffix] + self.kernel_name = re.compile("^([\\w]+)_([\\w]+)_([\\w]+)$") + # [(type, name)] + self.c_sig = re.compile("[\\s]*(\\w+)\\s(\\w+)[,]?") + # [d|c] + self.arg_suffix = re.compile("[c,d]") + + self.kernels = defaultdict(list) + + def extract_linker_meta(self, header: str): + for ln in header.splitlines(): + if ln.startswith("//"): + m = self.linker_directives.match(ln) + if _exists(m): + ker_name, c_sig, algo_info = m.group(1), m.group(2), m.group(3) + name, sig_hash, suffix = self._match_name(ker_name) + c_types, arg_names = self._match_c_sig(c_sig) + num_specs, sizes = self._match_suffix(suffix, c_sig) + self._add_kernel( + "_".join([name, algo_info]), + KernelLinkerMeta( + orig_kernel_name=name, + arg_names=arg_names, + arg_ctypes=c_types, + sizes=sizes, + sig_hash=sig_hash, + triton_suffix=suffix, + suffix=suffix, + num_specs=num_specs, + ), + ) + + def _match_name(self, ker_name: str): + m = self.kernel_name.match(ker_name) + if _exists(m): + name, sig_hash, suffix = m.group(1), m.group(2), m.group(3) + return name, sig_hash, suffix + raise LinkerError(f"{ker_name} is not a valid kernel name") + + def _match_c_sig(self, c_sig: str): + m = self.c_sig.findall(c_sig) + if len(m): + tys, args = [], [] + for ty, arg_name in m: + tys.append(ty) + args.append(arg_name) + return tys, args + + raise LinkerError(f"{c_sig} is not a valid argument signature") + + def _match_suffix(self, suffix: str, c_sig: str): + args = c_sig.split(",") + s2i = {"c": 1, "d": 16} + num_specs = 0 + sizes = [] + # scan through suffix, first find the index, + # then see if it is followed by d or c + for i in range(len(args)): + pos = suffix.find(str(i)) + if pos == -1: + raise LinkerError(f"{suffix} is not a valid kernel suffix") + pos += len(str(i)) + if self.arg_suffix.match(suffix, pos): + num_specs += 1 + sizes.extend([None] * (i - len(sizes))) + sizes.append(s2i[suffix[pos]]) + pos += 1 + if i < len(args) - 1: + suffix = suffix[pos:] + else: + sizes.extend([None] * (len(args) - len(sizes))) + return num_specs, sizes + + def _add_kernel(self, name: str, ker: KernelLinkerMeta): + if name in self.kernels: + last: KernelLinkerMeta = self.kernels[name][-1] + + for cur, new_ in zip(last.arg_ctypes, ker.arg_ctypes): + if cur != new_: + raise LinkerError( + f"Mismatched signature for kernel {name}: \n\texisting sig is: {','.join(last.arg_ctypes)}\n\tcurrent is: {','.join(ker.arg_ctypes)}" + ) + + self.kernels[name].append(ker) + + +def gen_signature_with_full_args(m): + return ", ".join([f"{ty} {arg}" for ty, arg in zip(m.arg_ctypes, m.arg_names)]) + + +def gen_signature(m): + arg_types = [ty for ty, hint in zip(m.arg_ctypes, m.sizes) if hint != 1] + arg_names = [arg for arg, hint in zip(m.arg_names, m.sizes) if hint != 1] + sig = ", ".join([f"{ty} {arg}" for ty, arg in zip(arg_types, arg_names)]) + return sig + + +# generate declarations of kernels with meta-parameter and constant values +def make_algo_decls(name: str, metas: Sequence[KernelLinkerMeta]) -> str: + return f""" +CUresult {name}(CUstream stream, {gen_signature_with_full_args(metas[-1])}); +void load_{name}(); +void unload_{name}(); + """ + + +# generate declarations of kernels with meta-parameter and constant values +def make_global_decl(meta: KernelLinkerMeta) -> str: + return f""" +CUresult {meta.orig_kernel_name}_default(CUstream stream, {gen_signature_with_full_args(meta)}); +CUresult {meta.orig_kernel_name}(CUstream stream, {gen_signature_with_full_args(meta)}, int algo_id); +void load_{meta.orig_kernel_name}(); +void unload_{meta.orig_kernel_name}(); + """ + + +# generate dispatcher function for kernels with different meta-parameter and constant values +def make_default_algo_kernel(meta: KernelLinkerMeta) -> str: + src = f"CUresult {meta.orig_kernel_name}_default(CUstream stream, {gen_signature_with_full_args(meta)}){{\n" + src += (f" return {meta.orig_kernel_name}(stream, {', '.join(meta.arg_names)}, 0);\n") + src += "}\n" + return src + + +# generate dispatcher function for kernels with different integer value hints +def make_kernel_hints_dispatcher(name: str, metas: Sequence[KernelLinkerMeta]) -> str: + src = f"// launcher for: {name}\n" + for meta in sorted(metas, key=lambda m: -m.num_specs): + src += f"CUresult {meta.orig_kernel_name}_{meta.sig_hash}_{meta.suffix}(CUstream stream, {gen_signature(meta)});\n" + src += "\n" + + src += (f"CUresult {name}(CUstream stream, {gen_signature_with_full_args(metas[-1])}){{") + src += "\n" + for meta in sorted(metas, key=lambda m: -m.num_specs): + cond_fn = ( # + lambda val, hint: f"({val} % {hint} == 0)" # + if hint == 16 # + else f"({val} == {hint})" # + if hint == 1 # + else None) + conds = " && ".join([ # + cond_fn(val, hint) # + for val, hint in zip(meta.arg_names, meta.sizes) # + if hint is not None + ]) + src += (f" if ({conds})\n" if any(meta.sizes) else "if (1)\n" + ) # Edge case where no specializations hence no dispatching required + arg_names = [arg for arg, hint in zip(meta.arg_names, meta.sizes) if hint != 1] + src += f" return {meta.orig_kernel_name}_{meta.sig_hash}_{meta.suffix}(stream, {', '.join(arg_names)});\n" + src += "\n" + src += " return CUDA_ERROR_INVALID_VALUE;\n" + src += "}\n" + + for mode in ["load", "unload"]: + src += f"\n// {mode} for: {name}\n" + for meta in sorted(metas, key=lambda m: -m.num_specs): + src += f"void {mode}_{meta.orig_kernel_name}_{meta.sig_hash}_{meta.suffix}();\n" + src += f"void {mode}_{name}() {{" + src += "\n" + for meta in sorted(metas, key=lambda m: -m.num_specs): + src += (f" {mode}_{meta.orig_kernel_name}_{meta.sig_hash}_{meta.suffix}();\n") + src += "}\n" + return src + + +# generate dispatcher function for kernels with different meta-parameter and constant values +def make_kernel_meta_const_dispatcher(meta: KernelLinkerMeta) -> str: + src = f"CUresult {meta.orig_kernel_name}(CUstream stream, {gen_signature_with_full_args(meta)}, int algo_id){{\n" + src += f" assert (algo_id < (int)sizeof({meta.orig_kernel_name}_kernels));\n" + src += f" return {meta.orig_kernel_name}_kernels[algo_id](stream, {', '.join(meta.arg_names)});\n" + src += "}\n" + return src + + +# generate definition of function pointers of kernel dispatchers based on meta-parameter and constant values +def make_func_pointers(names: str, meta: KernelLinkerMeta) -> str: + # the table of hint dispatchers + src = f"typedef CUresult (*kernel_func_t)(CUstream stream, {gen_signature_with_full_args(meta)});\n" + src += f"kernel_func_t {meta.orig_kernel_name}_kernels[] = {{\n" + for name in names: + src += f" {name},\n" + src += "};\n" + return src + + +# generate definition for load/unload functions for kernels with different meta-parameter and constant values +def make_kernel_load_def(names: str, meta: KernelLinkerMeta) -> str: + src = "" + for mode in ["load", "unload"]: + src += f"void {mode}_{meta.orig_kernel_name}(void){{\n" + for name in names: + src += f" {mode}_{name}();\n" + src += "}\n\n" + return src + + +def make_get_num_algos_decl(meta: KernelLinkerMeta) -> str: + src = f"int {meta.orig_kernel_name}_get_num_algos(void);" + return src + + +def make_get_num_algos_def(meta: KernelLinkerMeta) -> str: + src = f"int {meta.orig_kernel_name}_get_num_algos(void){{\n" + src += f" return (int)(sizeof({meta.orig_kernel_name}_kernels) / sizeof({meta.orig_kernel_name}_kernels[0]));\n" + src += "}\n" + return src + + +desc = """ +Triton ahead-of-time linker: + +This program takes in header files generated by compile.py, and generates a +single entry-point responsible for dispatching the user's input to the right +kernel given the specializations that were compiled. + +Example usage: +python link.py /path/to/headers/*.h -o kernel_name +""" + +if __name__ == "__main__": + from argparse import ArgumentParser + + parser = ArgumentParser(description=desc) + parser.add_argument( + "headers", + nargs="+", + help="Paths to header files to link. Must include linker directive annotations (autogenerated by ttc)", + ) + parser.add_argument("--out", "-o", type=Path, help="Out filename") + parser.add_argument( + "--prefix", + type=str, + default="", + help="String to prefix kernel dispatcher names", + ) + args = parser.parse_args() + + # metadata + parser = HeaderParser() + includes = [] + for header in args.headers: + h_path = Path(header) + h_str = h_path.read_text() + includes.append(h_path.name) + parser.extract_linker_meta(h_str) + + # generate headers + algo_decls = [make_algo_decls(name, meta) for name, meta in parser.kernels.items()] + meta_lists = [meta for name, meta in parser.kernels.items()] + meta = meta_lists[0][0] + get_num_algos_decl = make_get_num_algos_decl(meta) + global_decl = make_global_decl(meta) + with args.out.with_suffix(".h").open("w") as fp: + out = "#include \n" + out += "\n".join(algo_decls) + out += "\n" + out += get_num_algos_decl + out += "\n" + out += global_decl + fp.write(out) + + # generate source + defs = [make_kernel_hints_dispatcher(name, meta) for name, meta in parser.kernels.items()] + names = [name for name in parser.kernels.keys()] + func_pointers_def = make_func_pointers(names, meta) + meta_const_def = make_kernel_meta_const_dispatcher(meta) + load_unload_def = make_kernel_load_def(names, meta) + get_num_algos_def = make_get_num_algos_def(meta) + default_algo_kernel = make_default_algo_kernel(meta) + with args.out.with_suffix(".c").open("w") as fp: + out = "" + out += "#include \n" + out += "#include \n" + out += "#include \n" + out += "\n" + out += "\n".join(defs) + out += "\n" + out += func_pointers_def + out += "\n" + out += get_num_algos_def + out += "\n" + out += meta_const_def + out += "\n" + out += load_unload_def + out += "\n" + out += default_algo_kernel + fp.write(out) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/tools/mxfp.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/tools/mxfp.py new file mode 100644 index 0000000000000000000000000000000000000000..1b129c1aef2ddc8165a2f81718b1be980573c458 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/tools/mxfp.py @@ -0,0 +1,301 @@ +""" +Helper classes for working with low precision floating point types that +align with the opencompute (OCP) microscaling (MX) specification. + * MXFP4Tensor: 4-bit E2M1 floating point data + * MXScaleTensor: 8-bit E8M0 floating point data +Reference: https://www.opencompute.org/documents/ocp-microscaling-formats-mx-v1-0-spec-final-pdf +""" + +import torch + + +class MXFP4Tensor: + + def __init__(self, data=None, size=None, device=None): + """ + Tensor class for working with four bit E2M1 floating point data as defined by the + opencompute microscaling specification. + + + Parameters: + - data: A torch tensor of float32 numbers to convert to fp4e2m1 microscaling format. + - size: The size of the tensor to create. + - device: The device on which to create the tensor. + """ + self.device = device + if data is not None: + assert isinstance(data, torch.Tensor), "Parameter data must be a torch tensor" + self.device = data.device + self.data = self._from_float(data) + elif size is not None: + self.size = size if isinstance(size, tuple) else (size, ) + else: + raise ValueError("Either parameter data or size must be provided") + + def random(self): + S = torch.randint(0, 2, size=self.size, dtype=torch.uint8, device=self.device) + E = torch.randint(0, 4, size=self.size, dtype=torch.uint8, device=self.device) + M = torch.randint(0, 2, size=self.size, dtype=torch.uint8, device=self.device) + + self.data = ((S << 3) | (E << 1) | M).type(torch.uint8) + return self + + def to(self, dtype): + """ + Convert fp4e2m1 data to float32. + + Returns: + - A torch tensor of type dtype representing the fp4e2m1 data. + """ + assert dtype == torch.float32, "Currently only float32 is supported for fp4e2m1 to float conversion" + + data = self.data + S = ((data >> 3) & 0x1).type(dtype) + E = ((data >> 1) & 0x3).type(dtype) + M = (data & 0x1).type(dtype) + + # The MXF4 E2M1 spec defines 0bS000 as zero + value = torch.zeros_like(S) + is_zero = (E == 0) & (M == 0) + non_zero_mask = ~is_zero + if non_zero_mask.any(): + S_nz = S[non_zero_mask] + E_nz = E[non_zero_mask] + M_nz = M[non_zero_mask] + + sign = torch.pow(-1, S_nz) + # Normal and subnormal handling for the exponent and mantissa + exponent = torch.where(E_nz == 0, E_nz, E_nz - 1) + mantissa = torch.where(E_nz == 0, M_nz * 0.5, 1.0 + M_nz * 0.5) + value_nz = sign * torch.pow(2, exponent) * mantissa + + value[non_zero_mask] = value_nz + + # For zeros, the values must remain zero with the correct sign + value[is_zero & (S == 1)] *= -1 + return value.type(torch.float32) + + def _from_float(self, values): + """ + Convert float32 numbers to mxf4 e2m1 format. + * No encodings are reserved for Inf or NaN in mxf4. + * Conversion from float supports roundTiesToEven rounding mode. + * If a value exceeds the mxf4 representable range after rounding, + clamps to the maximum mxf4 magnitude, preserving the sign. + * If a value has magnitude less than the minimum subnormal magnitude + in mxf4 after rounding, converts to zero. + + Parameters: + - values: A torch tensor of float32 numbers to convert to fp4 format. + """ + S = torch.signbit(values).type(torch.uint8) + abs_values = torch.abs(values) + + is_zero = (abs_values == 0) + is_invalid = torch.isnan(values) | torch.isinf(values) + + # Enumerate all possible E2M1 exponent and mantissa values. We will + # use these to compare the distance between float32 and all possible + # E2M1 floats to find the nearest E2M1 representable value + E_bits = torch.tensor([0, 1, 2, 3], dtype=torch.uint8, device=self.device) + M_bits = torch.tensor([0, 1], dtype=torch.uint8, device=self.device) + + candidate_values = [] + candidate_E = [] + candidate_M = [] + + for E in E_bits: + if E == 0: + # Subnormals + exponent = 0 + for M in M_bits: + significand = M * 0.5 + value = significand * (2**exponent) + candidate_values.append(value) + candidate_E.append(E) + candidate_M.append(M) + else: + # Normals + exponent = E.item() - 1 + for M in M_bits: + significand = 1.0 + M * 0.5 + value = significand * (2**exponent) + candidate_values.append(value) + candidate_E.append(E) + candidate_M.append(M) + + candidates = torch.tensor(candidate_values, dtype=torch.float32, device=self.device) + candidate_E = torch.tensor(candidate_E, dtype=torch.uint8, device=self.device) + candidate_M = torch.tensor(candidate_M, dtype=torch.uint8, device=self.device) + + abs_values_flat = abs_values.view(-1) + N = abs_values_flat.shape[0] + abs_values_expanded = abs_values_flat.unsqueeze(1) + + # Clamp invalid values to the max e2m1 representable value + max_candidate_value = candidates.max().item() + abs_values_flat[is_invalid.view(-1)] = max_candidate_value + + # Compute distance between all abs_values and candidate e2m1 values + errors = torch.abs(abs_values_expanded - candidates.unsqueeze(0)) + + # To implement roundTiesToEven, we need to break ties by preferring + # even mantissas (M == 0). We do so by adding an epsilon bias to shift + # the closest candidate with an even mantissa closer to the float value + min_errors, _ = torch.min(errors, dim=1, keepdim=True) + is_tie = (errors == min_errors) + # More than one candidate has the min error for some float value + if is_tie.sum() > 1: + M_bits_expanded = candidate_M.unsqueeze(0).expand(N, -1) + tie_breaker = (M_bits_expanded == 0).type(torch.int32) + + errors = errors - (tie_breaker * 1e-6) + + best_indices = torch.argmin(errors, dim=1) + + E_selected = candidate_E[best_indices] + M_selected = candidate_M[best_indices] + E = E_selected.view(abs_values.shape) + M = M_selected.view(abs_values.shape) + + E[is_zero] = 0 + M[is_zero] = 0 + + return ((S << 3) | (E << 1) | M).type(torch.uint8) + + def to_packed_tensor(self, dim): + """ + Packs two e2m1 elements into a single uint8 along the specified dimension. + + Parameters: + - dim: The dimension along which to pack the elements. + + Returns: + - A torch tensor of dtype uint8 with two e2m1 elements packed into one uint8. + """ + data = self.data + assert 0 <= dim < data.ndim, \ + "The dimension to pack along is not within the range of tensor dimensions" + + size_along_dim = data.size(dim) + new_size_along_dim = (size_along_dim + 1) // 2 + + # If the size is odd, we pad the data along dim with zeros at the end + if size_along_dim % 2 != 0: + pad_sizes = [0] * (2 * data.ndim) + pad_index = (data.ndim - dim - 1) * 2 + 1 + pad_sizes[pad_index] = 1 + data = torch.nn.functional.pad(data, pad_sizes, mode='constant', value=0) + + new_shape = list(data.shape) + new_shape[dim] = new_size_along_dim + new_shape.insert(dim + 1, 2) # packed dimension of length 2 + data = data.reshape(*new_shape) + + low = data.select(dim + 1, 0) + high = data.select(dim + 1, 1) + packed = (high << 4) | low + + return packed + + def unpack_packed_tensor(self, packed_tensor, dim, original_shape): + """ + Unpacks a tensor where two fp4 elements are packed into a single uint8. + + Parameters: + - packed_tensor: The packed tensor + - dim: The dimension along which the tensor was packed. + - original_shape: The shape of the original tensor before packing. + + Returns: + - A tensor with the original data unpacked into uint8 elements containing one + fp4e2m1 element in the least significant bits. + """ + high = (packed_tensor >> 4) & 0xF + low = packed_tensor & 0xF + + stacked = torch.stack((low, high), dim=dim + 1) + + # Flatten along dim and dim+1 and then merge + shape = list(stacked.shape) + new_shape = shape[:dim] + [shape[dim] * 2] + shape[dim + 2:] + data = stacked.reshape(*new_shape) + + # Remove any padding + if original_shape[dim] % 2 != 0: + indices = [slice(None)] * data.ndim + indices[dim] = slice(0, original_shape[dim]) + data = data[tuple(indices)] + + return data.type(torch.uint8) + + +class MXScaleTensor: + + def __init__(self, data=None, size=None, device=None): + """ + Tensor class for working with microscaling E8M0 block scale factors. + + Parameters: + - data: A torch tensor of float32 numbers to convert to fp8e8m0 microscaling format. + - size: The size of the tensor to create. + - device: The device on which to create the tensor. + """ + self.device = device + if data is not None: + assert isinstance(data, torch.Tensor), "Parameter data must be a torch tensor" + self.device = data.device + self.data = self._from_float(data) + elif size is not None: + self.size = size if isinstance(size, tuple) else (size, ) + else: + raise ValueError("Either parameter data or size must be provided") + + def random(self, low=None, high=None): + """ + Generate random E8M0 data within a specified range. + * Excludes the NaN encoding (255). + """ + bias = 127 + + min_exponent = 0 if low is None else max(0, int(torch.log2(torch.tensor(low))) + bias) + max_exponent = 254 if high is None else min(254, max(0, int(torch.log2(torch.tensor(high))) + bias)) + assert min_exponent <= max_exponent, "Low must be less than or equal to high" + + E = torch.randint(min_exponent, max_exponent + 1, size=self.size, dtype=torch.uint8, device=self.device) + self.data = E + return self + + def to(self, dtype): + assert dtype == torch.float32, "Currently only float32 is supported for f8e8m0 to float conversion" + data = self.data.type(dtype) + is_nan = (data == 255) + e_biased = data.clone() + e_biased[is_nan] = 0 + e = e_biased - 127 + value = torch.pow(2.0, e) + value[is_nan] = torch.nan + return value.type(dtype) + + def _from_float(self, values): + """ + Convert float32 numbers to E8M0 format. + * Values <= 0, NaNs, and Infs are converted to the NaN encoding (255). + * Positive values are converted by computing the floor of log2(value) to get the exponent. + + Parameters: + - values: A torch tensor of float32 numbers to convert to E8M0 format. + """ + result = torch.empty_like(values, dtype=torch.uint8, device=self.device) + + is_invalid = torch.isnan(values) | torch.isinf(values) | (values <= 0) + result[is_invalid] = 255 + + valid_values = values[~is_invalid] + e = torch.floor(torch.log2(valid_values)) + e_biased = e + 127 + e_biased_int = e_biased.type(torch.int32) + e_biased_clamped = torch.clamp(e_biased_int, 0, 254) + result[~is_invalid] = e_biased_clamped.type(torch.uint8) + + return result diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/tools/ragged_tma.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/tools/ragged_tma.py new file mode 100644 index 0000000000000000000000000000000000000000..728dfcd42b3fab01c2b504a37f1e716d00bcef85 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/tools/ragged_tma.py @@ -0,0 +1,108 @@ +import triton +import triton.language as tl +from triton.tools.tensor_descriptor import TensorDescriptor + +# fmt: off + + +def create_ragged_descriptor(T, block_shape, ragged_dim=0): + """ + Given a 2- or 3-dimensional tensor T, this creates a 'ragged descriptor' + which behaves like a concatenation (along the first axis) of subarrays + of potentially unequal size. + + The load_ragged and store_ragged device functions can be used to read + and write from subarrays T[batch_offset : batch_offset + batch_size] + with hardware bounds-checking preventing any sort of leakage outside + the subarray. + """ + + block_shape = list(block_shape) + tensor_shape = list(T.shape) + rank = len(tensor_shape) + + if ragged_dim < 0: + ragged_dim += rank + + assert 0 <= ragged_dim < rank - 1, "last dimension cannot be ragged" + assert rank <= 3, "read-write ragged descriptors must have at most 3 dimensions" + + assert len(block_shape) == rank, "block shape must have same length as tensor shape" + + max_int = 0x7fff0000 + billion = 0x40000000 # == 2**30 + + assert tensor_shape[ragged_dim] <= billion, "number of rows may not exceed 2**30" + tensor_shape[ragged_dim] = billion + ragged_stride = T.stride(ragged_dim) + + # we prepend an extra two dimensions and rely on the fact that pointers + # have 64-bit wraparound semantics: + tma_stride = [2**34 - ragged_stride, ragged_stride] + [T.stride(i) for i in range(rank)] + tma_shape = [max_int, max_int] + tensor_shape + box_shape = [1, 1] + block_shape + + return TensorDescriptor(T, tma_shape, tma_stride, box_shape) + + +@triton.jit +def to_ragged_indices(batch_offset, batch_size, row): + """ + Helper function for load_ragged and store_ragged. + """ + + billion = 0x40000000 # == 2**30 + x = billion - batch_size + row + y = batch_offset + batch_size + + return billion, y, x + + +@triton.jit +def load_ragged(TMA, batch_offset, batch_size, coords, ragged_dim: tl.constexpr = 0): + """ + Read from a subarray T[batch_offset : batch_offset + batch_size] with + hardware bounds-checking, where reading outside the subarray gives zeros. + + Coords should be an appropriately-sized list of integers, just like in + TMA.load(). + """ + + tl.static_assert(len(TMA.shape) == len(coords) + 2, "TMA must be a read-write ragged descriptor") + + c0, c1, c2 = to_ragged_indices(batch_offset, batch_size, coords[ragged_dim]) + data = TMA.load([c0, c1] + coords[:ragged_dim] + [c2] + coords[ragged_dim + 1:]) + data = tl.reshape(data, data.shape[2:]) + return data + + +@triton.jit +def store_ragged(TMA, batch_offset, batch_size, coords, data, ragged_dim: tl.constexpr = 0): + """ + Write to a subarray T[batch_offset : batch_offset + batch_size] with + hardware bounds-checking, where writes outside the subarray are masked + correctly. + + Coords should be an appropriately-sized list of integers, just like in + TMA.store(). + """ + + c0, c1, c2 = to_ragged_indices(batch_offset, batch_size, coords[ragged_dim]) + data = tl.reshape(data, [1, 1] + data.shape) + TMA.store([c0, c1] + coords[:ragged_dim] + [c2] + coords[ragged_dim + 1:], data) + + +@triton.jit +def atomic_add_ragged(TMA, batch_offset, batch_size, coords, data, ragged_dim: tl.constexpr = 0): + """ + Atomic add into a subarray T[batch_offset : batch_offset + batch_size] with + hardware bounds-checking, where adds outside the subarray are masked + correctly. + + Coords should be an appropriately-sized list of integers, just like in + TMA.atomic_add(). + """ + + c0, c1, c2 = to_ragged_indices(batch_offset, batch_size, coords[ragged_dim]) + data = tl.reshape(data, [1, 1] + data.shape) + TMA.atomic_add([c0, c1] + coords[:ragged_dim] + [c2] + coords[ragged_dim + 1:], data) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/tools/tensor_descriptor.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/tools/tensor_descriptor.py new file mode 100644 index 0000000000000000000000000000000000000000..21c359aa308a0aa14a7d3ca873e21fbba978e347 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/tools/tensor_descriptor.py @@ -0,0 +1,36 @@ +from dataclasses import dataclass +from typing import List, Any +from triton._utils import validate_block_shape + + +@dataclass +class TensorDescriptor: + base: Any + shape: List[int] + strides: List[int] + block_shape: List[int] + padding: str = "zero" + + def __post_init__(self): + rank = len(self.shape) + assert len(self.strides) == rank, f"rank mismatch: {self}" + assert len(self.block_shape) == rank, f"rank mismatch: {self}" + assert rank > 0, "rank must not be zero" + assert rank <= 5, "rank cannot be more than 5" + ty = type(self.base) + if ty.__name__ not in ("FakeTensor", "FunctionalTensor"): + assert self.base.data_ptr() % 16 == 0, "base must be 16-byte aligned" + validate_block_shape(self.block_shape) + elem_bytes = self.base.dtype.itemsize + for stride in self.strides[:-1]: + assert (stride * elem_bytes) % 16 == 0, "strides must be 16-byte aligned" + for shape_dim in self.shape: + assert shape_dim > 0, "shape must be positive" + assert self.strides[-1] == 1, "Last dimension must be contiguous" + assert self.padding == "zero" or self.padding == "nan", "Illegal value for padding" + if self.padding == "nan": + assert self.base.dtype.is_floating_point, "Padding option `nan` is only supported for floating point tensors" + + @staticmethod + def from_tensor(tensor: Any, block_shape: List[int], padding="zero"): + return TensorDescriptor(tensor, tensor.shape, tensor.stride(), block_shape, padding) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/tools/triton_to_gluon_translater/translator.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/tools/triton_to_gluon_translater/translator.py new file mode 100644 index 0000000000000000000000000000000000000000..0fe9106fb35e333e68c163070621c2fb12f81e57 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/tools/triton_to_gluon_translater/translator.py @@ -0,0 +1,383 @@ +# Experimental Triton to Gluon AST translator. +# This file takes a Triton JIT entry point and generates a Gluon equivalent including all +# its dependencies. This generates highly inefficient Gluon code and is only used for +# functional testing. +# +import ast +from typing import Optional +import triton +import triton.language.core as tlc +import triton.experimental.gluon.language as ttgl +import sys +import importlib +import importlib.util +import copy + +GLUON_IMPORT_LINES = ("from triton.experimental import gluon\n" + "from triton.experimental.gluon import language as ttgl\n" + "from triton.tools.triton_to_gluon_translater.translator_helpers import *\n") + + +class TritonToGluonTransformer(ast.NodeTransformer): + """Transforms Triton kernel source into a functionally equivalent Gluon source. + + This transformer rewrites builtins, dtype/tensor attributes, constexpr annotations, + and records nested JIT callables to be converted and appended to the output. + """ + + def __init__(self, globals_map: dict, shared_jit_set: set, shared_queue: list, is_jit, constexpr_globals: dict): + super().__init__() + # Resolution scope (globals ∪ nonlocals) + self.scope: dict = globals_map or {} + # Track discovered JIT functions to inline/append later + self.jit_functions: set = shared_jit_set + self.queue: list = shared_queue + self.is_jit = is_jit + # Maps module_file -> {name: value} to pull constexpr globals from the original source code + self.constexpr_globals: dict = constexpr_globals + + def is_triton_constexpr_annotation(self, ann: ast.expr) -> bool: + # Resolve the annotation to a Python object and compare by identity + obj = self.resolve_value(ann) + return obj is tlc.constexpr + + def as_ttgl_constexpr(self) -> ast.expr: + # Build ttgl.constexpr + return self.ttgl_attr("constexpr") + + def maybe_rewrite_constexpr_annotation(self, ann: Optional[ast.expr]) -> Optional[ast.expr]: + if ann is None: + return None + if self.is_triton_constexpr_annotation(ann): + return self.as_ttgl_constexpr() + return ann + + def ttgl_attr(self, name: str) -> ast.AST: + return ast.Attribute(value=ast.Name(id="ttgl", ctx=ast.Load()), attr=name, ctx=ast.Load()) + + def resolve_value(self, expr: ast.expr): + if isinstance(expr, ast.Name): + value = self.scope.get(expr.id) or sys.modules.get(expr.id) + return value + if isinstance(expr, ast.Attribute): + base = self.resolve_value(expr.value) + if base is None: + return None + return getattr(base, expr.attr, None) + return None + + def forward_call(self, node: ast.Call, target_func: ast.expr, filter_keywords: list[str] = []) -> ast.Call: + new_keywords = [kw for kw in node.keywords if kw.arg not in filter_keywords] + return ast.Call(func=target_func, args=list(node.args), keywords=list(new_keywords)) + + def visit_Call(self, node: ast.Call) -> ast.AST: + node = self.generic_visit(node) + resolved_callable = self.resolve_value(node.func) + if resolved_callable is not None: + resolved_callable = triton.language.core._unwrap_if_constexpr(resolved_callable) + base_function = getattr(resolved_callable, "fn", resolved_callable) + function_name = getattr(base_function, "__qualname__", getattr(base_function, "__name__", + str(base_function))) + if triton.language.core.is_builtin(resolved_callable): + builtin_name = function_name.split(".")[-1] + builtin_mapping: dict[str, ast.expr] = { + "arange": ast.Name(id="tl_arange", ctx=ast.Load()), + "full": ast.Name(id="tl_full", ctx=ast.Load()), + "trans": ast.Name(id="tl_trans", ctx=ast.Load()), + "dot": ast.Name(id="tl_dot", ctx=ast.Load()), + "dot_scaled": ast.Name(id="tl_dot_scaled", ctx=ast.Load()), + "make_tensor_descriptor": ast.Name(id="tl_make_tensor_descriptor", ctx=ast.Load()), + "load_tensor_descriptor": ast.Name(id="tl_load_tensor_descriptor", ctx=ast.Load()), + "store_tensor_descriptor": ast.Name(id="tl_store_tensor_descriptor", ctx=ast.Load()), + "num_threads": ast.Name(id="get_num_threads_per_program", ctx=ast.Load()), + } + mapped_target = builtin_mapping.get(builtin_name) + if mapped_target is None and hasattr(ttgl, builtin_name): + mapped_target = self.ttgl_attr(builtin_name) + + filter_keywords = [] + # for reshape drop the can_reorder keyword, it is just an optimization and doesn't help much in Gluon. + if builtin_name == "reshape": + filter_keywords = ["can_reorder"] + if mapped_target is not None: + node = self.forward_call(node, mapped_target, filter_keywords) + # For split, apply on the source argument rather than wrapping destination + if builtin_name == "split": + source_arg = node.args[0] + wrapped_src = ast.Call(func=ast.Name(id="set_split_src_layout", ctx=ast.Load()), + args=[source_arg], keywords=[]) + node.args[0] = ast.copy_location(wrapped_src, source_arg) + # For shape/layout changing ops, wrap to reset layout + if builtin_name in {"reshape", "trans", "permute", "join", "reduce", "split"}: + reset_layout_wrapped = ast.Call(func=ast.Name(id="reset_to_default_layout", ctx=ast.Load()), + args=[node], keywords=[]) + node = ast.copy_location(reset_layout_wrapped, node) + return node + # Track JITFunction callees + if isinstance(resolved_callable, triton.runtime.jit.JITCallable): + if resolved_callable not in self.jit_functions: + self.jit_functions.add(resolved_callable) + self.queue.append(resolved_callable) + # Strip namespace: rewrite to local function name + return self.forward_call(node, ast.Name(id=getattr(base_function, "__name__", ""), ctx=ast.Load())) + if resolved_callable is triton.language.core.range: + # skip all keywords except arg1, arg2, and step and replace with range. + allowed = {"arg1", "arg2", "step"} + new_keywords = [kw for kw in node.keywords if kw.arg in allowed] + new_args = list(node.args[:3]) + return ast.copy_location( + ast.Call(func=ast.Name(id="range", ctx=ast.Load()), args=new_args, keywords=new_keywords), + node, + ) + if resolved_callable is triton.language.core.static_range: + return self.forward_call(node, self.ttgl_attr("static_range")) + else: + if isinstance(node.func, ast.Attribute) and node.func.attr in ["store", "load", "gather", "scatter"]: + helper_name = "tl_obj_" + node.func.attr + return ast.Call( + func=ast.Name(id=helper_name, ctx=ast.Load()), + args=[node.func.value] + list(node.args), + keywords=list(node.keywords), + ) + if isinstance(node.func, + ast.Attribute) and node.func.attr in ["reshape", "trans", "split", "join", "reduce"]: + if node.func.attr == "split": + receiver_expr = node.func.value + wrapped_receiver = ast.Call(func=ast.Name(id="set_split_src_layout", ctx=ast.Load()), + args=[receiver_expr], keywords=[]) + new_func = ast.Attribute(value=ast.copy_location(wrapped_receiver, receiver_expr), + attr=node.func.attr, ctx=ast.Load()) + node = ast.copy_location( + ast.Call(func=new_func, args=list(node.args), keywords=list(node.keywords)), node) + wrapped = ast.Call( + func=ast.Name(id="reset_to_default_layout", ctx=ast.Load()), + args=[node], + keywords=[], + ) + return ast.copy_location(wrapped, node) + return node + + def visit_Attribute(self, node: ast.Attribute) -> ast.AST: + node = self.generic_visit(node) + last_part = node.attr + # Only rewrite dtypes when the resolved object is a tl.dtype instance + # or the tl.dtype class itself (e.g., tl.float16 or tl.dtype.float16 / tl.dtype) + resolved_obj = self.resolve_value(node) + if resolved_obj is not None: + if isinstance(resolved_obj, tlc.dtype): + return self.ttgl_attr(last_part) + if resolved_obj is tlc.dtype and last_part == "dtype": + return self.ttgl_attr("dtype") + if resolved_obj is tlc.tensor and last_part == "tensor": + return self.ttgl_attr("tensor") + if resolved_obj is tlc.constexpr and last_part == "constexpr": + return self.ttgl_attr("constexpr") + if last_part == "tensor_descriptor": + return self.ttgl_attr("nvidia.hopper.tma.tensor_descriptor") + return node + + def visit_Name(self, node): + node = self.generic_visit(node) + resolved_obj = self.resolve_value(node) + if resolved_obj is not None: + # Track standalone references to JITCallable and normalize name + if isinstance(resolved_obj, triton.runtime.jit.JITCallable): + if resolved_obj not in self.jit_functions: + self.jit_functions.add(resolved_obj) + self.queue.append(resolved_obj) + base_function = getattr(resolved_obj, "fn", resolved_obj) + normalized_name = getattr(base_function, "__name__", + getattr(base_function, "__qualname__", getattr(node, "id", ""))) + return ast.copy_location(ast.Name(id=normalized_name, ctx=node.ctx), node) + if isinstance(resolved_obj, triton.language.core.constexpr): + identifier = getattr(node, "id", None) + if identifier is not None: + # Use the current capture scope's file for the defining module + module_file = self.scope.get("__file__") + if isinstance(module_file, str): + bucket = self.constexpr_globals.setdefault(module_file, {}) + bucket[identifier] = resolved_obj + return node + + def visit_Subscript(self, node: ast.Subscript) -> ast.AST: + node = self.generic_visit(node) + # TODO: generalize to + # For patterns like x[None, :] or x[:, None], ensure x has a SliceLayout along the expanded dim + expanded_dim = None + if isinstance(node.slice, ast.Tuple) and len(node.slice.elts) == 2: + first, second = node.slice.elts + if isinstance(first, ast.Constant) and first.value is None: + expanded_dim = 0 + elif isinstance(second, ast.Constant) and second.value is None: + expanded_dim = 1 + if expanded_dim is not None: + value_expr = node.value + # Construct a 2D parent shape with a dummy dimension of size 1 at the expanded dim + # Use value.type.shape[0] as the vector length + type_attr = ast.Attribute(value=value_expr, attr="type", ctx=ast.Load()) + shape_attr = ast.Attribute(value=type_attr, attr="shape", ctx=ast.Load()) + len_expr = ast.Subscript(value=shape_attr, slice=ast.Constant(value=0), ctx=ast.Load()) + if expanded_dim == 0: + parent_shape = ast.List(elts=[len_expr, ast.Constant(value=1)], ctx=ast.Load()) + else: + parent_shape = ast.List(elts=[ast.Constant(value=1), len_expr], ctx=ast.Load()) + # Build SliceLayout(dim, default_blocked_layout(parent_shape, ttgl.num_warps())) + slice_layout = ast.Call( + func=self.ttgl_attr("SliceLayout"), + args=[ + ast.Constant(value=expanded_dim), + ast.Call( + func=ast.Name(id="default_blocked_layout", ctx=ast.Load()), + args=[parent_shape, + ast.Call(func=self.ttgl_attr("num_warps"), args=[], keywords=[])], + keywords=[], + ), + ], + keywords=[], + ) + converted_value = ast.Call( + func=self.ttgl_attr("convert_layout"), + args=[value_expr, slice_layout], + keywords=[], + ) + return ast.Subscript(value=converted_value, slice=node.slice, ctx=node.ctx) + return node + + def visit_FunctionDef(self, node: ast.FunctionDef) -> ast.AST: + # Rewrite parameter annotations: triton.language.constexpr -> ttgl.constexpr + # Positional-only and regular args + for arg in list(getattr(node.args, "posonlyargs", [])) + list(node.args.args): + arg.annotation = self.maybe_rewrite_constexpr_annotation(arg.annotation) + # Vararg / kwarg + if node.args.vararg is not None: + node.args.vararg.annotation = self.maybe_rewrite_constexpr_annotation(node.args.vararg.annotation) + if node.args.kwarg is not None: + node.args.kwarg.annotation = self.maybe_rewrite_constexpr_annotation(node.args.kwarg.annotation) + # Keyword-only args + for arg in node.args.kwonlyargs: + arg.annotation = self.maybe_rewrite_constexpr_annotation(arg.annotation) + if self.is_jit: + node.decorator_list.insert( + 0, ast.Attribute(value=ast.Name(id="gluon", ctx=ast.Load()), attr="jit", ctx=ast.Load())) + else: + node.decorator_list.insert( + 0, ast.Attribute(value=ast.Name(id="gluon", ctx=ast.Load()), attr="constexpr_function", ctx=ast.Load())) + # Process body + return self.generic_visit(node) + + +def unparse_original_assignments(constexpr_globals: dict) -> list[str]: + """Reconstruct original assignments for captured constexpr globals. + + We parse each defining module once to extract assignments, and rewrite tl.constexpr + calls to ttgl.constexpr so the generated code remains consistent. + """ + + # Build assignment strings for captured globals by parsing each module once. + def collect_names(target_node, names_out): + if isinstance(target_node, ast.Name): + names_out.append(target_node.id) + elif isinstance(target_node, (ast.Tuple, ast.List)): + for element in target_node.elts: + collect_names(element, names_out) + + def parse_assigns_and_imports(path: str) -> tuple[dict[str, ast.AST], dict[str, str]]: + try: + with open(path, "r") as f: + module_ast = ast.parse(f.read()) + except Exception: + return {}, {} + assigns: dict[str, ast.AST] = {} + imports: dict[str, str] = {} + for stmt in getattr(module_ast, "body", []): + if isinstance(stmt, ast.Assign): + names: list[str] = [] + for target in stmt.targets: + collect_names(target, names) + for identifier in names: + assigns[identifier] = stmt + elif isinstance(stmt, ast.AnnAssign): + names: list[str] = [] + collect_names(stmt.target, names) + if stmt.value is not None: + for identifier in names: + assigns[identifier] = stmt + elif isinstance(stmt, ast.ImportFrom) and stmt.level == 0 and isinstance(stmt.module, str): + for alias in stmt.names: + alias_name = alias.asname or alias.name.split(".")[-1] + imports[alias_name] = stmt.module + return assigns, imports + + def rewrite_constexpr_to_ttgl(node: ast.AST) -> ast.AST: + + class ConstexprToTtglRewriter(ast.NodeTransformer): + + def visit_Call(self, call_node: ast.Call) -> ast.AST: + call_node = self.generic_visit(call_node) + if isinstance(call_node.func, ast.Attribute) and call_node.func.attr == "constexpr": + call_node.func = ast.copy_location( + ast.Attribute(value=ast.Name(id="ttgl", ctx=ast.Load()), attr="constexpr", ctx=ast.Load()), + call_node.func) + return call_node + + return ConstexprToTtglRewriter().visit(node) + + results: list[str] = [] + imported_cache: dict[str, dict[str, ast.AST]] = {} + for mod_file, name_to_obj in constexpr_globals.items(): + assigns, imports = parse_assigns_and_imports(mod_file) + for identifier in sorted(name_to_obj.keys()): + node = assigns.get(identifier) + if node is None: + imported_module_name = imports.get(identifier) + if imported_module_name: + try: + module_spec = importlib.util.find_spec(imported_module_name) + origin = getattr(module_spec, "origin", None) if module_spec is not None else None + except Exception: + origin = None + if origin: + assignment_map = imported_cache.get(origin) + if assignment_map is None: + assignment_map, _ = parse_assigns_and_imports(origin) + imported_cache[origin] = assignment_map + node = assignment_map.get(identifier) + if node is not None: + edited_node = rewrite_constexpr_to_ttgl(copy.deepcopy(node)) + ast.fix_missing_locations(edited_node) + results.append(ast.unparse(edited_node)) + else: + results.append(f"{identifier} = {repr(name_to_obj[identifier])}") + return results + + +def convert_triton_to_gluon(src: list[triton.runtime.jit.JITCallable]) -> str: + """Convert a Triton JIT entry point into a Gluon source string.""" + shared_jit_set: set = set() + function_queue: list = list(src) + constexpr_globals: dict = {} + out = "" + # Process discovered callee JITFunctions, converting and appending them + while function_queue: + callee = function_queue.pop(0) + callee_src = callee._src + callee_tree = ast.parse(callee_src) + callee_scope = getattr(callee, "__globals__", {}) or {} + jit = isinstance(callee, triton.runtime.JITFunction) + callee_transformer = TritonToGluonTransformer(globals_map=callee_scope, shared_jit_set=shared_jit_set, + shared_queue=function_queue, is_jit=jit, + constexpr_globals=constexpr_globals) + callee_new = callee_transformer.visit(callee_tree) + ast.fix_missing_locations(callee_new) + out += "\n\n" + ast.unparse(callee_new) + + out = "\n\n" + out + + # Pull constexpr globals from the original source code + for line in unparse_original_assignments(constexpr_globals): + out = line + "\n" + out + + # Prepend required Gluon imports + out = GLUON_IMPORT_LINES + "\n\n" + out + + return out diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/tools/triton_to_gluon_translater/translator_helpers.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/tools/triton_to_gluon_translater/translator_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..2b946ee3bf9f304f80cd3cc13a5a3502f517098e --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/triton/tools/triton_to_gluon_translater/translator_helpers.py @@ -0,0 +1,618 @@ +from triton.experimental import gluon +from triton.experimental.gluon import language as ttgl +from triton.experimental.gluon.language.nvidia.hopper import mbarrier +from triton.experimental.gluon.language.nvidia.blackwell import ( + TensorMemoryLayout, + TensorMemoryScalesLayout, + allocate_tensor_memory, + get_tmem_reg_layout, + tcgen05_mma, + tcgen05_mma_scaled, + tcgen05_commit, +) +from triton.experimental.gluon.language.nvidia.ampere import mma_v2 +from triton.experimental.gluon.language.nvidia.hopper import tma, fence_async_shared +from triton.experimental.gluon.language.nvidia.blackwell import tma as tma_blackwell + + +@gluon.constexpr_function +def tl_dot_mma_sync_layout(shape, num_warps): + rank = len(shape) + assert rank in [2, 3], "MMA sync only supports 2D shapes or 3D shapes with a batch outer dimension" + if rank == 2: + return ttgl.NVMMADistributedLayout(version=[2, 0], warps_per_cta=[num_warps, 1], instr_shape=[16, 8]) + return ttgl.NVMMADistributedLayout(version=[2, 0], warps_per_cta=[num_warps, 1, 1], instr_shape=[1, 16, 8]) + + +@gluon.constexpr_function +def tl_dot_mma_sync_k_width(a_ty, b_ty): + a_bitwidth = a_ty.element_ty.primitive_bitwidth + b_bitwidth = b_ty.element_ty.primitive_bitwidth + min_bitwidth = min(a_bitwidth, b_bitwidth) + return max(32 // min_bitwidth, 1) + + +@gluon.jit +def tl_dot_mma_sync(a, b, acc_init=None, input_precision=None, out_dtype=ttgl.float32): + mma_layout: ttgl.constexpr = tl_dot_mma_sync_layout(a.type.shape, ttgl.num_warps()) + k_width: ttgl.constexpr = tl_dot_mma_sync_k_width(a.type, b.type) + a_layout: ttgl.constexpr = ttgl.DotOperandLayout(parent=mma_layout, operand_index=0, k_width=k_width) + b_layout: ttgl.constexpr = ttgl.DotOperandLayout(parent=mma_layout, operand_index=1, k_width=k_width) + a = ttgl.convert_layout(a, a_layout) + b = ttgl.convert_layout(b, b_layout) + if acc_init is not None: + acc = ttgl.convert_layout(acc_init, mma_layout) + else: + acc = ttgl.full([a.shape[0], a.shape[1], b.shape[2]], 0.0, out_dtype, layout=mma_layout) + result = mma_v2(a, b, acc, input_precision) + if acc_init is not None: + result = ttgl.convert_layout(result, acc_init.type.layout) + return result + + +@gluon.constexpr_function +def tl_dot_mmav5_supported(a_ty, b_ty, num_warps, input_precision, allow_tf32, max_num_imprecise_acc): + assert max_num_imprecise_acc is None, "max_num_imprecise_acc only applies to Hopper warp_group_dot" + assert input_precision is None or allow_tf32 is None, "Only one of input_precision and allow_tf32 can be specified" + if input_precision is None and (allow_tf32 or allow_tf32 is None): + input_precision = "tf32" + + M = a_ty.shape[0] + N = b_ty.shape[1] + K = a_ty.shape[1] + min_K = 256 // a_ty.element_ty.primitive_bitwidth + if a_ty.element_ty.is_int() or b_ty.element_ty.is_int(): + return False + if min(a_ty.element_ty.primitive_bitwidth, b_ty.element_ty.primitive_bitwidth) >= 32 and input_precision != "tf32": + return False + return num_warps in [4, 8] and len(a_ty.shape) == 2 and len(b_ty.shape) == 2 and K >= min_K and M >= 64 and N >= 16 + + +@gluon.constexpr_function +def get_shared_memory_mma_layout(type, operand_index, allow_transpose, is_fp4_padded=False, force_transpose=False): + if not allow_transpose: + if operand_index == 1: + transposed = True + else: + transposed = False + if force_transpose: + transposed = not transposed + else: + transposed = operand_index == 1 + + shape = type.shape + swizzle_byte_width = 0 + ele_bit_width = type.element_ty.primitive_bitwidth + packing_factor = 2 if is_fp4_padded else 1 + + contig_dim_size_in_byte = (shape[0] if transposed else shape[1]) * packing_factor * ele_bit_width // 8 + if contig_dim_size_in_byte >= 128 and contig_dim_size_in_byte % 128 == 0: + swizzle_byte_width = 128 + elif contig_dim_size_in_byte >= 64 and contig_dim_size_in_byte % 64 == 0: + swizzle_byte_width = 64 + elif contig_dim_size_in_byte >= 32 and contig_dim_size_in_byte % 32 == 0: + swizzle_byte_width = 32 + else: + swizzle_byte_width = 0 + + flatten_outer_dim = 1 + for dim in shape: + flatten_outer_dim *= dim + if len(shape) < 2 or flatten_outer_dim < 8: + swizzle_byte_width = 0 + return ttgl.NVMMASharedLayout(swizzle_byte_width=swizzle_byte_width, transposed=transposed, + element_bitwidth=ele_bit_width, rank=len(shape), fp4_padded=is_fp4_padded) + + +@gluon.jit +def get_shared_memory_mma_operand(value, operand_index, allow_transpose, is_fp4_padded=False, force_transpose=False): + layout: ttgl.constexpr = get_shared_memory_mma_layout(value.type, operand_index, allow_transpose, is_fp4_padded, + force_transpose) + return ttgl.allocate_shared_memory(value.dtype, value.shape, layout, value) + + +@gluon.jit +def tl_dot_blackwell(a, b, acc=None, input_precision=None, allow_tf32=None, max_num_imprecise_acc=None, + out_dtype=ttgl.float32): + M: ttgl.constexpr = a.type.shape[0] + N: ttgl.constexpr = b.type.shape[1] + + allow_transpose = not a.type.element_ty.is_fp32() + a_smem = get_shared_memory_mma_operand(a, 0, allow_transpose) + b_smem = get_shared_memory_mma_operand(b, 1, allow_transpose) + + # MMA instruction shape + m: ttgl.constexpr = 128 if M >= 128 else 64 + n: ttgl.constexpr = 256 if N >= 256 else N + + acc_dtype: ttgl.constexpr = acc.dtype if acc is not None else out_dtype + col_stride: ttgl.constexpr = 32 // acc_dtype.primitive_bitwidth + acc_tmem_layout: ttgl.constexpr = TensorMemoryLayout([m, n], col_stride=col_stride) + + tmem_reg_layout: ttgl.constexpr = get_tmem_reg_layout(acc_dtype, (M, N), acc_tmem_layout, ttgl.num_warps()) + if acc is not None: + acc_temp = ttgl.convert_layout(acc, tmem_reg_layout) + else: + acc_temp = ttgl.zeros([M, N], out_dtype, layout=tmem_reg_layout) + acc_tmem = allocate_tensor_memory(acc_temp.dtype, [M, N], acc_tmem_layout, acc_temp) + fence_async_shared() + bar = ttgl.allocate_shared_memory(ttgl.int64, [1], mbarrier.MBarrierLayout()) + mbarrier.init(bar, count=1) + tcgen05_mma(a_smem, b_smem, acc_tmem, use_acc=True) + tcgen05_commit(bar) + mbarrier.wait(bar, phase=0) + mbarrier.invalidate(bar) + + # Load back from TMEM using a register layout and convert to acc layout + out = acc_tmem.load(tmem_reg_layout) + ret_layout: ttgl.constexpr = default_blocked_layout([M, N], ttgl.num_warps()) + out = ttgl.convert_layout(out, ret_layout) + return out + + +@gluon.jit +def tl_dot(a, b, acc=None, input_precision=None, allow_tf32=None, max_num_imprecise_acc=None, out_dtype=ttgl.float32): + num_warps: ttgl.constexpr = ttgl.num_warps() + if tl_dot_mmav5_supported(a.type, b.type, num_warps, input_precision, allow_tf32, max_num_imprecise_acc): + return tl_dot_blackwell(a, b, acc, input_precision, allow_tf32, max_num_imprecise_acc, out_dtype) + else: + return tl_dot_mma_sync(a, b, acc, input_precision, out_dtype) + + +@gluon.constexpr_function +def tl_dot_scaled_mmav5_supported(a_ty, b_ty, num_warps): + M = a_ty.shape[0] + N = b_ty.shape[1] + K = a_ty.shape[1] + min_K = 256 // a_ty.element_ty.primitive_bitwidth + return num_warps in [4, 8] and len(a_ty.shape) == 2 and len(b_ty.shape) == 2 and K >= min_K and M >= 128 and N >= 16 + + +@gluon.constexpr_function +def get_swizzle_byte_width(bitwidth): + swizzle = min(bitwidth, 128) + swizzle = 0 if swizzle < 32 else swizzle + return swizzle + + +@gluon.constexpr_function +def get_int_type(bitwidth): + if bitwidth == 64: + return ttgl.int64 + elif bitwidth == 32: + return ttgl.int32 + elif bitwidth == 16: + return ttgl.int16 + elif bitwidth == 8: + return ttgl.int8 + else: + assert False, f"Unsupported bitwidth: {bitwidth}" + + +@gluon.jit +def tl_dot_decomposed_scale_to_16(scale, compute_type): + large_fp_type: ttgl.constexpr = ttgl.float32 if compute_type == ttgl.float16 else compute_type + int_width: ttgl.constexpr = large_fp_type.primitive_bitwidth + int_type: ttgl.constexpr = get_int_type(int_width) + + zexted = ttgl.cast(scale, int_type) + shift_value: ttgl.constexpr = large_fp_type.fp_mantissa_width + shl_res = zexted << shift_value + scale_fp = ttgl.cast(shl_res, large_fp_type, bitcast=True) + if large_fp_type != compute_type: + scale_fp = ttgl.cast(scale_fp, compute_type) + return scale_fp + + +@gluon.constexpr_function +def tl_dot_get_expand_dims_layout(scale_ty, num_warps, rank): + shape = scale_ty.shape.values + [1] + blocked = default_blocked_layout(shape, num_warps) + slice = ttgl.SliceLayout(rank, blocked) + return slice + + +@gluon.constexpr_function +def tl_dot_get_permute_order(rank, dim): + order = list(range(rank)) + order.insert(dim + 1, rank) + return order + + +@gluon.constexpr_function +def tl_dot_get_reshape_shape(scale_ty, dim): + shape = list(scale_ty.shape.values) + shape.pop() + shape[dim] *= 32 + return shape + + +@gluon.jit +def tl_dot_decomposed_broadcast_scale(scale, dim): + scale_ty: ttgl.constexpr = scale.type + rank: ttgl.constexpr = len(scale_ty.shape) + + num_warps: ttgl.constexpr = ttgl.num_warps() + slice_enc: ttgl.constexpr = tl_dot_get_expand_dims_layout(scale_ty, num_warps, rank) + scale = ttgl.convert_layout(scale, slice_enc) + expand_scale = scale.expand_dims(rank) + broadcast_scale = expand_scale.broadcast_to(scale.type.shape + (32, )) + permute_order: ttgl.constexpr = tl_dot_get_permute_order(rank, dim) + transposed_scale = broadcast_scale.permute(permute_order.value) + reshape_shape: ttgl.constexpr = tl_dot_get_reshape_shape(broadcast_scale.type, dim) + return transposed_scale.reshape(reshape_shape) + + +@gluon.constexpr_function +def tl_dot_decomposed_get_transposed_order(rank): + assert rank >= 2 + order = list(range(rank - 2)) + order += [rank - 1, rank - 2] + return order + + +@gluon.jit +def tl_dot_decomposed_extend_and_broadcast_scale(v, scale, compute_type, operand_index): + rank: ttgl.constexpr = len(v.type.shape) + k_dim: ttgl.constexpr = rank - 1 if operand_index == 0 else rank - 2 + + if operand_index == 1: + order: ttgl.constexpr = tl_dot_decomposed_get_transposed_order(rank) + scale = ttgl.permute(scale, order.value) + + scale16 = tl_dot_decomposed_scale_to_16(scale, compute_type) + reshape_scale = tl_dot_decomposed_broadcast_scale(scale16, k_dim) + return ttgl.convert_layout(reshape_scale, v.type.layout), scale + + +@gluon.jit +def tl_dot_decomposed_mask_nan(mxfp, scale, fast_math): + ttgl.static_assert(fast_math, "TODO: support non-fast-math") + return mxfp + + +@gluon.jit +def tl_dot_decomposed_scale_arg(v, scale, arg_format, operand_index, compute_type, fast_math): + is_fp4: ttgl.constexpr = arg_format == "e2m1" + rank: ttgl.constexpr = len(v.type.shape) + k_dim: ttgl.constexpr = rank - 1 if operand_index == 0 else rank - 2 + + if is_fp4: + v = ttgl.fp4_to_fp(v, compute_type, k_dim) + else: + v = ttgl.cast(v, compute_type) + if scale is None: + return v + else: + reshape_scale, scale = tl_dot_decomposed_extend_and_broadcast_scale(v, scale, compute_type, operand_index) + mxfp = ttgl.mul(v, reshape_scale) + return tl_dot_decomposed_mask_nan(mxfp, scale, fast_math) + + +@gluon.jit +def tl_dot_scaled(lhs, lhs_scale, lhs_format, rhs, rhs_scale, rhs_format, acc=None, fast_math=False, lhs_k_pack=True, + rhs_k_pack=True, out_dtype=ttgl.float32): + if tl_dot_scaled_mmav5_supported(lhs.type, rhs.type, + ttgl.num_warps() and lhs_scale is not None and rhs_scale is not None): + return tl_dot_scaled_blackwell(lhs, lhs_scale, lhs_format, rhs, rhs_scale, rhs_format, acc, fast_math, + lhs_k_pack, rhs_k_pack, out_dtype) + else: + return tl_dot_decomposed_block_scales(lhs, lhs_scale, lhs_format, rhs, rhs_scale, rhs_format, acc, fast_math, + lhs_k_pack, rhs_k_pack, out_dtype) + + +@gluon.jit +def tl_dot_decomposed_block_scales(lhs, lhs_scale, lhs_format, rhs, rhs_scale, rhs_format, acc=None, fast_math=False, + lhs_k_pack=True, rhs_k_pack=True, out_dtype=ttgl.float32): + if lhs_scale is None and rhs_scale is not None: + lhs_trans = tl_trans(lhs) + rhs_trans = tl_trans(rhs) + if acc is not None: + orig_layout: ttgl.constexpr = acc.type.layout + acc = tl_trans(acc) + result = tl_dot_scaled(rhs_trans, rhs_scale, rhs_format, lhs_trans, lhs_scale, lhs_format, acc, fast_math, + lhs_k_pack, rhs_k_pack, out_dtype) + result = tl_trans(result) + if acc is not None: + result = ttgl.convert_layout(result, orig_layout) + return result + else: + ttgl.static_assert(not (not lhs_k_pack or not rhs_k_pack), "TODO: support m/n packed formats") + compute_type: ttgl.constexpr = ttgl.float16 if (lhs_format == "fp16" or rhs_format == "fp16") else ttgl.bfloat16 + + scale_a = tl_dot_decomposed_scale_arg(lhs, lhs_scale, lhs_format, 0, compute_type, fast_math) + scale_b = tl_dot_decomposed_scale_arg(rhs, rhs_scale, rhs_format, 1, compute_type, fast_math) + + return tl_dot(scale_a, scale_b, acc, out_dtype=out_dtype) + + +@gluon.jit +def tl_dot_scaled_blackwell(lhs, lhs_scale, lhs_format, rhs, rhs_scale, rhs_format, acc=None, fast_math=False, + lhs_k_pack=True, rhs_k_pack=True, out_dtype=ttgl.float32): + is_a_fp4: ttgl.constexpr = lhs_format == "e2m1" + is_b_fp4: ttgl.constexpr = rhs_format == "e2m1" + + mixed_prec: ttgl.constexpr = lhs_format != rhs_format + is_a_mixed_prec_fp4: ttgl.constexpr = mixed_prec and is_a_fp4 + is_b_mixed_prec_fp4: ttgl.constexpr = mixed_prec and not is_a_fp4 and is_b_fp4 + + is_mmav5_fp4_padded_a: ttgl.constexpr = is_a_mixed_prec_fp4 or not lhs_k_pack + is_mmav5_fp4_padded_b: ttgl.constexpr = is_b_mixed_prec_fp4 or not rhs_k_pack + + a_smem = get_shared_memory_mma_operand(lhs, 0, allow_transpose=not is_a_fp4, is_fp4_padded=is_mmav5_fp4_padded_a, + force_transpose=not lhs_k_pack) + b_smem = get_shared_memory_mma_operand(rhs, 1, allow_transpose=not is_b_fp4, is_fp4_padded=is_mmav5_fp4_padded_b, + force_transpose=not rhs_k_pack) + + M: ttgl.constexpr = lhs.type.shape[0] + N: ttgl.constexpr = rhs.type.shape[1] + + m: ttgl.constexpr = 128 + n: ttgl.constexpr = 256 if N >= 256 else N + + acc_dtype: ttgl.constexpr = acc.dtype if acc is not None else out_dtype + col_stride: ttgl.constexpr = 32 // acc_dtype.primitive_bitwidth + acc_tmem_layout: ttgl.constexpr = TensorMemoryLayout([m, n], col_stride=col_stride) + tmem_reg_layout: ttgl.constexpr = get_tmem_reg_layout(acc_dtype, (M, N), acc_tmem_layout, ttgl.num_warps()) + if acc is not None: + acc_temp = ttgl.convert_layout(acc, tmem_reg_layout) + else: + acc_temp = ttgl.zeros([M, N], out_dtype, layout=tmem_reg_layout) + acc_tmem = allocate_tensor_memory(acc_temp.dtype, [M, N], acc_tmem_layout, acc_temp) + fence_async_shared() + + bar = ttgl.allocate_shared_memory(ttgl.int64, [1], mbarrier.MBarrierLayout()) + mbarrier.init(bar, count=1) + scale_layout: ttgl.constexpr = TensorMemoryScalesLayout() + scale_layout_reg_lhs: ttgl.constexpr = get_tmem_reg_layout(lhs_scale.dtype, lhs_scale.type.shape, scale_layout, + ttgl.num_warps()) + scale_layout_reg_rhs: ttgl.constexpr = get_tmem_reg_layout(rhs_scale.dtype, rhs_scale.type.shape, scale_layout, + ttgl.num_warps()) + lhs_scale = ttgl.convert_layout(lhs_scale, scale_layout_reg_lhs) + rhs_scale = ttgl.convert_layout(rhs_scale, scale_layout_reg_rhs) + a_scale_tmem = allocate_tensor_memory(lhs_scale.dtype, lhs_scale.shape, scale_layout, lhs_scale) + b_scale_tmem = allocate_tensor_memory(rhs_scale.dtype, rhs_scale.shape, scale_layout, rhs_scale) + + tcgen05_mma_scaled(a_smem, b_smem, acc_tmem, a_scale_tmem, b_scale_tmem, lhs_format, rhs_format, use_acc=True) + tcgen05_commit(bar) + mbarrier.wait(bar, phase=0) + mbarrier.invalidate(bar) + # Load back from TMEM using a register layout and convert to acc layout + out = acc_tmem.load(tmem_reg_layout) + ret_layout: ttgl.constexpr = default_blocked_layout([M, N], ttgl.num_warps()) + out = ttgl.convert_layout(out, ret_layout) + return out + + +@gluon.constexpr_function +def get_num_threads_per_warp() -> ttgl.constexpr: + return ttgl.constexpr(32) + + +@ttgl._core.builtin +def get_num_threads_per_program(_semantic=None, _generator=None): + return ttgl.num_warps(_semantic=_semantic, _generator=_generator) * get_num_threads_per_warp(_semantic=_semantic) + + +@gluon.constexpr_function +def default_blocked_layout(shape: ttgl.constexpr, num_warps: ttgl.constexpr) -> ttgl.constexpr: + rank = len(shape) + # 1 element per thread for all dimensions + size_per_thread = [1 for _ in range(rank)] + # Distribute 32 threads per warp across dimensions (simple heuristic: last-fastest) + threads_per_warp = [1 for _ in range(rank)] + # TODO: pick a better layout based on shape. Using this allows to not have to convert layout when broadcasting but may blow up register pressure. + threads_per_warp[rank - 1] = get_num_threads_per_warp() + # remaining_threads = get_num_threads_per_warp() + # for dim in range(rank - 1, -1, -1): + # threads_per_warp[dim] = min(remaining_threads, shape[dim]) + # remaining_threads = remaining_threads // threads_per_warp[dim] + # Use provided num_warps to distribute warps per CTA (put all on first dim) + warps_per_cta = [1 for _ in range(rank)] + warps_per_cta[0] = num_warps + # Natural order [rank-1, rank-2, ..., 0] + order = [i for i in range(rank - 1, -1, -1)] + return ttgl.BlockedLayout(size_per_thread=size_per_thread, threads_per_warp=threads_per_warp, + warps_per_cta=warps_per_cta, order=order) + + +@gluon.jit +def tl_obj_store(obj, offsets, value): + if isinstance(obj, ttgl.nvidia.hopper.tma.tensor_descriptor): + return tl_store_tensor_descriptor(obj, offsets, value) + else: + return obj.store(offsets, value) + + +@gluon.jit +def tl_obj_load(obj, offsets): + if isinstance(obj, ttgl.nvidia.hopper.tma.tensor_descriptor): + return tl_load_tensor_descriptor(obj, offsets) + else: + return obj.load(offsets) + + +@gluon.jit +def tl_obj_gather(obj, x_offsets, y_offset): + if isinstance(obj, ttgl.nvidia.hopper.tma.tensor_descriptor): + desc = obj + desc_shape: ttgl.constexpr = [x_offsets.shape[0], desc.block_shape[1]] + alloc = ttgl.allocate_shared_memory(desc.dtype, desc_shape, desc.layout) + bar = ttgl.allocate_shared_memory(ttgl.int64, [1], mbarrier.MBarrierLayout()) + mbarrier.init(bar, count=1) + x_offsets_layout: ttgl.constexpr = ttgl.SliceLayout( + 0, ttgl.BlockedLayout([1, 4], [get_num_threads_per_warp(), 1], [1, ttgl.num_warps()], [1, 0])) + x_offsets = ttgl.convert_layout(x_offsets, x_offsets_layout) + mbarrier.expect(bar, x_offsets.shape[0] * obj.block_type.nbytes) + tma_blackwell.async_gather(desc, x_offsets, y_offset, bar, alloc) + mbarrier.wait(bar, phase=0) + mbarrier.invalidate(bar) + # Load from shared memory into a register tensor using a reasonable default layout + ret_layout: ttgl.constexpr = default_blocked_layout(desc.block_shape, ttgl.num_warps()) + out = alloc.load(ret_layout) + return out + else: + return obj.gather(x_offsets, y_offset) + + +@gluon.jit +def tl_obj_scatter(obj, value, x_offsets, y_offset): + if isinstance(obj, ttgl.nvidia.hopper.tma.tensor_descriptor): + desc = obj + desc_shape: ttgl.constexpr = [x_offsets.shape[0], desc.block_shape[1]] + alloc = ttgl.allocate_shared_memory(desc.dtype, desc_shape, desc.layout, value) + fence_async_shared() + x_offsets_layout: ttgl.constexpr = ttgl.SliceLayout( + 0, ttgl.BlockedLayout([1, 4], [get_num_threads_per_warp(), 1], [1, ttgl.num_warps()], [1, 0])) + x_offsets = ttgl.convert_layout(x_offsets, x_offsets_layout) + tma_blackwell.async_scatter(desc, x_offsets, y_offset, alloc) + tma.store_wait(0) + else: + obj.scatter(value, x_offsets, y_offset) + + +@ttgl._core.builtin +def tl_make_tensor_descriptor(base, shape, strides, block_shape, padding_option="zero", _semantic=None): + layout = ttgl.NVMMASharedLayout.get_default_for(block_shape, base.dtype.element_ty) + return tma.make_tensor_descriptor(base, shape, strides, block_shape, layout, padding_option, _semantic=_semantic) + + +@gluon.jit +def tl_store_tensor_descriptor(desc, offsets, value): + alloc = ttgl.allocate_shared_memory(desc.dtype, desc.block_shape, desc.layout, value) + fence_async_shared() + tma.async_copy_shared_to_global(desc, offsets, alloc) + tma.store_wait(0) + alloc._keep_alive() + + +@gluon.jit +def tl_load_tensor_descriptor(desc, offsets): + smem = ttgl.allocate_shared_memory(desc.dtype, desc.block_shape, desc.layout) + bar = ttgl.allocate_shared_memory(ttgl.int64, [1], mbarrier.MBarrierLayout()) + mbarrier.init(bar, count=1) + # Issue async copy from global (descriptor) to shared memory and wait for completion + mbarrier.expect(bar, desc.block_type.nbytes) + tma.async_copy_global_to_shared(desc, offsets, bar, smem) + mbarrier.wait(bar, phase=0) + mbarrier.invalidate(bar) + # Load from shared memory into a register tensor using a reasonable default layout + ret_layout: ttgl.constexpr = default_blocked_layout(desc.block_shape, ttgl.num_warps()) + out = smem.load(ret_layout) + return out + + +@gluon.jit +def tl_arange(start: ttgl.constexpr, stop: ttgl.constexpr = None): + layout: ttgl.constexpr = default_blocked_layout([stop - start], ttgl.num_warps()) + return ttgl.arange(start, stop, layout=layout) + + +@gluon.jit +def tl_full(shape, value, dtype=None): + layout: ttgl.constexpr = default_blocked_layout(shape, ttgl.num_warps()) + return ttgl.full(shape, value, dtype, layout=layout) + + +@ttgl._core.builtin +def tl_trans(value, *dims, _semantic=None): + return value.trans(*dims, _semantic=_semantic) + + +@ttgl._core.builtin +def cat(input, other, can_reorder=False, layout=None, _semantic=None): + """ + Concatenate the two tensors. + + Args: + input (tensor): The first input tensor. + other (tensor): The second input tensor. + can_reorder (bool): Compiler hint. If true, the compiler is allowed to reorder elements while concatenating inputs. Only use if the order does not matter (e.g., result is only used in reduction ops). Current implementation of `cat` supports only can_reorder=True. + layout (DistributedLayout): The destination layout of the output tensor. + + Returns: + tensor: The concatenated tensor. + """ + can_reorder = ttgl._core._unwrap_if_constexpr(can_reorder) + layout = ttgl._core._unwrap_if_constexpr(layout) + return _semantic.cat(input, other, can_reorder, layout) + + +@gluon.jit +def tl_cat(lhs, rhs, can_reorder=False): + return cat(lhs, rhs, can_reorder, layout=default_blocked_layout([lhs.shape[0] + rhs.shape[0]], ttgl.num_warps())) + + +@gluon.jit +def reset_to_default_layout(value): + ty: ttgl.constexpr = value.type + if isinstance(ty, ttgl.tuple_type): + out = () + for i in ttgl.static_range(len(value)): + r = ttgl.convert_layout(value[i], layout=default_blocked_layout(value[i].type.shape, ttgl.num_warps())) + out = out + (r, ) + return out + elif isinstance(value, ttgl.tensor) and isinstance(value.type, ttgl.distributed_type): + layout: ttgl.constexpr = default_blocked_layout(ty.shape, ttgl.num_warps()) + return ttgl.convert_layout(value, layout=layout) + else: + return value + + +@gluon.constexpr_function +def get_split_src_layout(shape: ttgl.constexpr, num_warps: ttgl.constexpr) -> ttgl.constexpr: + rank = len(shape) + size_per_thread = [1 if i != rank - 1 else 2 for i in range(rank)] + # Distribute 32 threads per warp across dimensions (simple heuristic: last-fastest) + threads_per_warp = [1 for _ in range(rank)] + remaining_threads = get_num_threads_per_warp() + for dim in range(rank - 2, -1, -1): + threads_per_warp[dim] = min(shape[dim], remaining_threads) + remaining_threads = remaining_threads // threads_per_warp[dim] + # Use provided num_warps to distribute warps per CTA (put all on first dim) + warps_per_cta = [1 for _ in range(rank)] + warps_per_cta[0] = num_warps + # Natural order [rank-1, rank-2, ..., 0] + order = [i for i in range(rank - 1, -1, -1)] + return ttgl.BlockedLayout(size_per_thread=size_per_thread, threads_per_warp=threads_per_warp, + warps_per_cta=warps_per_cta, order=order) + + +@gluon.jit +def set_split_src_layout(value): + layout: ttgl.constexpr = get_split_src_layout(value.type.shape, ttgl.num_warps()) + return ttgl.convert_layout(value, layout=layout) + + +def convert_host_descriptor(desc): + + def torch_dtype_to_triton(dtype): + import torch + if dtype == torch.float8_e5m2: + return ttgl.float8e5 + if dtype == torch.float8_e4m3fn: + return ttgl.float8e4nv + return getattr(ttgl, str(dtype).split('.')[1]) + + from triton.tools.tensor_descriptor import TensorDescriptor + assert isinstance(desc, TensorDescriptor) + block_shape = desc.block_shape + dtype = desc.base.dtype + tensor = desc.base + layout = ttgl.NVMMASharedLayout.get_default_for(block_shape, torch_dtype_to_triton(dtype)) + return gluon.nvidia.hopper.TensorDescriptor(tensor, desc.shape, desc.strides, block_shape, layout) + + +# hacks to workaround limited dependencies tracking. +# TODO: fix this by pulling imports into the generated file. +def current_target(): + from triton.runtime import driver + try: + active_driver = driver.active + except RuntimeError: + # If there is no active driver, return None + return None + return active_driver.get_current_target() + + +current_target.__triton_builtin__ = True diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/typer-0.24.1.dist-info/INSTALLER b/miniconda3/envs/ladir/lib/python3.10/site-packages/typer-0.24.1.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/typer-0.24.1.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/typer-0.24.1.dist-info/METADATA b/miniconda3/envs/ladir/lib/python3.10/site-packages/typer-0.24.1.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..8fc14ea2b68c0df97b52da5802a44e0083973d26 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/typer-0.24.1.dist-info/METADATA @@ -0,0 +1,412 @@ +Metadata-Version: 2.4 +Name: typer +Version: 0.24.1 +Summary: Typer, build great CLIs. Easy to code. Based on Python type hints. +Author-Email: =?utf-8?q?Sebasti=C3=A1n_Ram=C3=ADrez?= +License-Expression: MIT +License-File: LICENSE +Classifier: Intended Audience :: Information Technology +Classifier: Intended Audience :: System Administrators +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python +Classifier: Topic :: Software Development :: Libraries :: Application Frameworks +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Classifier: Topic :: Software Development :: Libraries +Classifier: Topic :: Software Development +Classifier: Typing :: Typed +Classifier: Development Status :: 4 - Beta +Classifier: Intended Audience :: Developers +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Project-URL: Homepage, https://github.com/fastapi/typer +Project-URL: Documentation, https://typer.tiangolo.com +Project-URL: Repository, https://github.com/fastapi/typer +Project-URL: Issues, https://github.com/fastapi/typer/issues +Project-URL: Changelog, https://typer.tiangolo.com/release-notes/ +Requires-Python: >=3.10 +Requires-Dist: click>=8.2.1 +Requires-Dist: shellingham>=1.3.0 +Requires-Dist: rich>=12.3.0 +Requires-Dist: annotated-doc>=0.0.2 +Description-Content-Type: text/markdown + +

+ Typer + +

+

+ Typer, build great CLIs. Easy to code. Based on Python type hints. +

+

+ + Test + + + Publish + + + Coverage + + Package version + +

+ +--- + +**Documentation**: https://typer.tiangolo.com + +**Source Code**: https://github.com/fastapi/typer + +--- + +Typer is a library for building CLI applications that users will **love using** and developers will **love creating**. Based on Python type hints. + +It's also a command line tool to run scripts, automatically converting them to CLI applications. + +The key features are: + +* **Intuitive to write**: Great editor support. Completion everywhere. Less time debugging. Designed to be easy to use and learn. Less time reading docs. +* **Easy to use**: It's easy to use for the final users. Automatic help, and automatic completion for all shells. +* **Short**: Minimize code duplication. Multiple features from each parameter declaration. Fewer bugs. +* **Start simple**: The simplest example adds only 2 lines of code to your app: **1 import, 1 function call**. +* **Grow large**: Grow in complexity as much as you want, create arbitrarily complex trees of commands and groups of subcommands, with options and arguments. +* **Run scripts**: Typer includes a `typer` command/program that you can use to run scripts, automatically converting them to CLIs, even if they don't use Typer internally. + +## 2026 February - Typer developer survey + +Help us define Typer's future by filling the Typer developer survey. ✨ + +## FastAPI of CLIs + +**Typer** is FastAPI's little sibling, it's the FastAPI of CLIs. + +## Installation + +Create and activate a virtual environment and then install **Typer**: + +
+ +```console +$ pip install typer +---> 100% +Successfully installed typer rich shellingham +``` + +
+ +## Example + +### The absolute minimum + +* Create a file `main.py` with: + +```Python +def main(name: str): + print(f"Hello {name}") +``` + +This script doesn't even use Typer internally. But you can use the `typer` command to run it as a CLI application. + +### Run it + +Run your application with the `typer` command: + +
+ +```console +// Run your application +$ typer main.py run + +// You get a nice error, you are missing NAME +Usage: typer [PATH_OR_MODULE] run [OPTIONS] NAME +Try 'typer [PATH_OR_MODULE] run --help' for help. +╭─ Error ───────────────────────────────────────────╮ +│ Missing argument 'NAME'. │ +╰───────────────────────────────────────────────────╯ + + +// You get a --help for free +$ typer main.py run --help + +Usage: typer [PATH_OR_MODULE] run [OPTIONS] NAME + +Run the provided Typer app. + +╭─ Arguments ───────────────────────────────────────╮ +│ * name TEXT [default: None] [required] | +╰───────────────────────────────────────────────────╯ +╭─ Options ─────────────────────────────────────────╮ +│ --help Show this message and exit. │ +╰───────────────────────────────────────────────────╯ + +// Now pass the NAME argument +$ typer main.py run Camila + +Hello Camila + +// It works! 🎉 +``` + +
+ +This is the simplest use case, not even using Typer internally, but it can already be quite useful for simple scripts. + +**Note**: auto-completion works when you create a Python package and run it with `--install-completion` or when you use the `typer` command. + +## Use Typer in your code + +Now let's start using Typer in your own code, update `main.py` with: + +```Python +import typer + + +def main(name: str): + print(f"Hello {name}") + + +if __name__ == "__main__": + typer.run(main) +``` + +Now you could run it with Python directly: + +
+ +```console +// Run your application +$ python main.py + +// You get a nice error, you are missing NAME +Usage: main.py [OPTIONS] NAME +Try 'main.py --help' for help. +╭─ Error ───────────────────────────────────────────╮ +│ Missing argument 'NAME'. │ +╰───────────────────────────────────────────────────╯ + + +// You get a --help for free +$ python main.py --help + +Usage: main.py [OPTIONS] NAME + +╭─ Arguments ───────────────────────────────────────╮ +│ * name TEXT [default: None] [required] | +╰───────────────────────────────────────────────────╯ +╭─ Options ─────────────────────────────────────────╮ +│ --help Show this message and exit. │ +╰───────────────────────────────────────────────────╯ + +// Now pass the NAME argument +$ python main.py Camila + +Hello Camila + +// It works! 🎉 +``` + +
+ +**Note**: you can also call this same script with the `typer` command, but you don't need to. + +## Example upgrade + +This was the simplest example possible. + +Now let's see one a bit more complex. + +### An example with two subcommands + +Modify the file `main.py`. + +Create a `typer.Typer()` app, and create two subcommands with their parameters. + +```Python hl_lines="3 6 11 20" +import typer + +app = typer.Typer() + + +@app.command() +def hello(name: str): + print(f"Hello {name}") + + +@app.command() +def goodbye(name: str, formal: bool = False): + if formal: + print(f"Goodbye Ms. {name}. Have a good day.") + else: + print(f"Bye {name}!") + + +if __name__ == "__main__": + app() +``` + +And that will: + +* Explicitly create a `typer.Typer` app. + * The previous `typer.run` actually creates one implicitly for you. +* Add two subcommands with `@app.command()`. +* Execute the `app()` itself, as if it was a function (instead of `typer.run`). + +### Run the upgraded example + +Check the new help: + +
+ +```console +$ python main.py --help + + Usage: main.py [OPTIONS] COMMAND [ARGS]... + +╭─ Options ─────────────────────────────────────────╮ +│ --install-completion Install completion │ +│ for the current │ +│ shell. │ +│ --show-completion Show completion for │ +│ the current shell, │ +│ to copy it or │ +│ customize the │ +│ installation. │ +│ --help Show this message │ +│ and exit. │ +╰───────────────────────────────────────────────────╯ +╭─ Commands ────────────────────────────────────────╮ +│ goodbye │ +│ hello │ +╰───────────────────────────────────────────────────╯ + +// When you create a package you get ✨ auto-completion ✨ for free, installed with --install-completion + +// You have 2 subcommands (the 2 functions): goodbye and hello +``` + +
+ +Now check the help for the `hello` command: + +
+ +```console +$ python main.py hello --help + + Usage: main.py hello [OPTIONS] NAME + +╭─ Arguments ───────────────────────────────────────╮ +│ * name TEXT [default: None] [required] │ +╰───────────────────────────────────────────────────╯ +╭─ Options ─────────────────────────────────────────╮ +│ --help Show this message and exit. │ +╰───────────────────────────────────────────────────╯ +``` + +
+ +And now check the help for the `goodbye` command: + +
+ +```console +$ python main.py goodbye --help + + Usage: main.py goodbye [OPTIONS] NAME + +╭─ Arguments ───────────────────────────────────────╮ +│ * name TEXT [default: None] [required] │ +╰───────────────────────────────────────────────────╯ +╭─ Options ─────────────────────────────────────────╮ +│ --formal --no-formal [default: no-formal] │ +│ --help Show this message │ +│ and exit. │ +╰───────────────────────────────────────────────────╯ + +// Automatic --formal and --no-formal for the bool option 🎉 +``` + +
+ +Now you can try out the new command line application: + +
+ +```console +// Use it with the hello command + +$ python main.py hello Camila + +Hello Camila + +// And with the goodbye command + +$ python main.py goodbye Camila + +Bye Camila! + +// And with --formal + +$ python main.py goodbye --formal Camila + +Goodbye Ms. Camila. Have a good day. +``` + +
+ +**Note**: If your app only has one command, by default the command name is **omitted** in usage: `python main.py Camila`. However, when there are multiple commands, you must **explicitly include the command name**: `python main.py hello Camila`. See [One or Multiple Commands](https://typer.tiangolo.com/tutorial/commands/one-or-multiple/) for more details. + +### Recap + +In summary, you declare **once** the types of parameters (*CLI arguments* and *CLI options*) as function parameters. + +You do that with standard modern Python types. + +You don't have to learn a new syntax, the methods or classes of a specific library, etc. + +Just standard **Python**. + +For example, for an `int`: + +```Python +total: int +``` + +or for a `bool` flag: + +```Python +force: bool +``` + +And similarly for **files**, **paths**, **enums** (choices), etc. And there are tools to create **groups of subcommands**, add metadata, extra **validation**, etc. + +**You get**: great editor support, including **completion** and **type checks** everywhere. + +**Your users get**: automatic **`--help`**, **auto-completion** in their terminal (Bash, Zsh, Fish, PowerShell) when they install your package or when using the `typer` command. + +For a more complete example including more features, see the Tutorial - User Guide. + +## Dependencies + +**Typer** stands on the shoulders of giants. It has three required dependencies: + +* Click: a popular tool for building CLIs in Python. Typer is based on it. +* rich: to show nicely formatted errors automatically. +* shellingham: to automatically detect the current shell when installing completion. + +### `typer-slim` + +There used to be a slimmed-down version of Typer called `typer-slim`, which didn't include the dependencies `rich` and `shellingham`, nor the `typer` command. + +However, since version 0.22.0, we have stopped supporting this, and `typer-slim` now simply installs (all of) Typer. + +If you want to disable Rich globally, you can set an environmental variable `TYPER_USE_RICH` to `False` or `0`. + +## License + +This project is licensed under the terms of the MIT license. diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/typer-0.24.1.dist-info/RECORD b/miniconda3/envs/ladir/lib/python3.10/site-packages/typer-0.24.1.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..e9ef82173a385651da0ce1a17a45ca0ac23ad44f --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/typer-0.24.1.dist-info/RECORD @@ -0,0 +1,40 @@ +../../../bin/typer,sha256=4utZvgIyrl_EOjcyCf6SMAgHBKs2BOGW7zFsJkDTexQ,206 +typer-0.24.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +typer-0.24.1.dist-info/METADATA,sha256=V4OWoWjBhPNcoIaOxhr1cszo69nePKOHMRXERkMscKs,16057 +typer-0.24.1.dist-info/RECORD,, +typer-0.24.1.dist-info/WHEEL,sha256=Wb0ASbVj8JvWHpOiIpPi7ucfIgJeCi__PzivviEAQFc,90 +typer-0.24.1.dist-info/entry_points.txt,sha256=YO13ByiqWeuas9V0JADLUARZFUe_cwU_7wmTNvxBYQ8,57 +typer-0.24.1.dist-info/licenses/LICENSE,sha256=WJks68-N-25AxOIRLtEhJsJDZm3KORKj14t-ysSFnUk,1086 +typer/__init__.py,sha256=WOelHJu4PW0hk9nfjEX0Qxssb58NCh1km_Xq5LY_33s,1596 +typer/__main__.py,sha256=bYt9eEaoRQWdejEHFD8REx9jxVEdZptECFsV7F49Ink,30 +typer/__pycache__/__init__.cpython-310.pyc,, +typer/__pycache__/__main__.cpython-310.pyc,, +typer/__pycache__/_completion_classes.cpython-310.pyc,, +typer/__pycache__/_completion_shared.cpython-310.pyc,, +typer/__pycache__/_types.cpython-310.pyc,, +typer/__pycache__/_typing.cpython-310.pyc,, +typer/__pycache__/cli.cpython-310.pyc,, +typer/__pycache__/colors.cpython-310.pyc,, +typer/__pycache__/completion.cpython-310.pyc,, +typer/__pycache__/core.cpython-310.pyc,, +typer/__pycache__/main.cpython-310.pyc,, +typer/__pycache__/models.cpython-310.pyc,, +typer/__pycache__/params.cpython-310.pyc,, +typer/__pycache__/rich_utils.cpython-310.pyc,, +typer/__pycache__/testing.cpython-310.pyc,, +typer/__pycache__/utils.cpython-310.pyc,, +typer/_completion_classes.py,sha256=R9v4D8pJ_-n8fLOuyxrRSu7sP5lpXIy5fsLUW8zwsDU,7039 +typer/_completion_shared.py,sha256=-uhCUIMc2S1ywdB-fBSSccH70mIBEsVTxHomcmy-klE,9129 +typer/_types.py,sha256=0lcBDLcsxqr1sxTsqObj_u0Dfa37lWJYUY4PNkX4QlA,974 +typer/_typing.py,sha256=QOw5o-B2L--C3ly2DQH6aUwag6x5brV5FhVaBZ5gzMg,1727 +typer/cli.py,sha256=icRbazvdRdbYeaidPZOmJDOzrP3RAa7vj2INVV9Zb8Q,10183 +typer/colors.py,sha256=e42j8uB520hLpX5C_0fiR3OOoIFMbhO3ADZvv6hlAV8,430 +typer/completion.py,sha256=FRTR9hP_IPdJp-4GXPOq0btXo5SvgAtLVfS3ZkAMpgQ,4793 +typer/core.py,sha256=O5NywSwHPyYbLhZkPYSfwIj7Za2hPnoPP4xPXRa97a0,27947 +typer/main.py,sha256=xyNex-QfGUi-enu9j9rl-_wofApxs5VwdpCthAUAAkk,69005 +typer/models.py,sha256=OwPG3MAXiUD5ih3p8eNVciXUsL07UIJfNWy3JiNpDfg,19843 +typer/params.py,sha256=AovViRtl-VvUIXnmKKpnxoWK9_gHUbyQgXxxv3h_7lI,59713 +typer/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +typer/rich_utils.py,sha256=RTyeoxwz16ZZXYbwoEixB_LSEnqpoStG_TGCRTz6zFQ,25424 +typer/testing.py,sha256=-ovLNjUNNEFCJoau-41iTJIobsjPbqyTrRq7-8ac4z4,871 +typer/utils.py,sha256=wnJ1DWXBFMnxLHaMN_HDYntxLRby0K-rux63aokHInI,7599 diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/typer-0.24.1.dist-info/WHEEL b/miniconda3/envs/ladir/lib/python3.10/site-packages/typer-0.24.1.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..18c430c1f6411c0532096b13de4384ab50a79abd --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/typer-0.24.1.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: pdm-backend (2.4.7) +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/typer-0.24.1.dist-info/entry_points.txt b/miniconda3/envs/ladir/lib/python3.10/site-packages/typer-0.24.1.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..ca44c05a071b87fe02a3724bd895838305fe4e5d --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/typer-0.24.1.dist-info/entry_points.txt @@ -0,0 +1,5 @@ +[console_scripts] +typer = typer.cli:main + +[gui_scripts] + diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/typer-0.24.1.dist-info/licenses/LICENSE b/miniconda3/envs/ladir/lib/python3.10/site-packages/typer-0.24.1.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..a7694736cf37716aafec14b24aa8d6316ebe07a3 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/typer-0.24.1.dist-info/licenses/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2019 Sebastián Ramírez + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/typer/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/typer/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..cb0921c06c9c0eddcb32ef016236ea98c2a42375 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/typer/__init__.py @@ -0,0 +1,39 @@ +"""Typer, build great CLIs. Easy to code. Based on Python type hints.""" + +__version__ = "0.24.1" + +from shutil import get_terminal_size as get_terminal_size + +from click.exceptions import Abort as Abort +from click.exceptions import BadParameter as BadParameter +from click.exceptions import Exit as Exit +from click.termui import clear as clear +from click.termui import confirm as confirm +from click.termui import echo_via_pager as echo_via_pager +from click.termui import edit as edit +from click.termui import getchar as getchar +from click.termui import pause as pause +from click.termui import progressbar as progressbar +from click.termui import prompt as prompt +from click.termui import secho as secho +from click.termui import style as style +from click.termui import unstyle as unstyle +from click.utils import echo as echo +from click.utils import format_filename as format_filename +from click.utils import get_app_dir as get_app_dir +from click.utils import get_binary_stream as get_binary_stream +from click.utils import get_text_stream as get_text_stream +from click.utils import open_file as open_file + +from . import colors as colors +from .main import Typer as Typer +from .main import launch as launch +from .main import run as run +from .models import CallbackParam as CallbackParam +from .models import Context as Context +from .models import FileBinaryRead as FileBinaryRead +from .models import FileBinaryWrite as FileBinaryWrite +from .models import FileText as FileText +from .models import FileTextWrite as FileTextWrite +from .params import Argument as Argument +from .params import Option as Option diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/typer/__main__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/typer/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..4e28416e104515e90fca4b69cc60d0c61fd15d61 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/typer/__main__.py @@ -0,0 +1,3 @@ +from .cli import main + +main() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/typer/_completion_classes.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/typer/_completion_classes.py new file mode 100644 index 0000000000000000000000000000000000000000..8548fb4d6a3e2e274811b0935276e1c0e6f2a9a0 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/typer/_completion_classes.py @@ -0,0 +1,199 @@ +import importlib.util +import os +import re +import sys +from typing import Any + +import click +import click.parser +import click.shell_completion +from click.shell_completion import split_arg_string as click_split_arg_string + +from ._completion_shared import ( + COMPLETION_SCRIPT_BASH, + COMPLETION_SCRIPT_FISH, + COMPLETION_SCRIPT_POWER_SHELL, + COMPLETION_SCRIPT_ZSH, + Shells, +) + + +def _sanitize_help_text(text: str) -> str: + """Sanitizes the help text by removing rich tags""" + if not importlib.util.find_spec("rich"): + return text + from . import rich_utils + + return rich_utils.rich_render_text(text) + + +class BashComplete(click.shell_completion.BashComplete): + name = Shells.bash.value + source_template = COMPLETION_SCRIPT_BASH + + def source_vars(self) -> dict[str, Any]: + return { + "complete_func": self.func_name, + "autocomplete_var": self.complete_var, + "prog_name": self.prog_name, + } + + def get_completion_args(self) -> tuple[list[str], str]: + cwords = click_split_arg_string(os.environ["COMP_WORDS"]) + cword = int(os.environ["COMP_CWORD"]) + args = cwords[1:cword] + + try: + incomplete = cwords[cword] + except IndexError: + incomplete = "" + + return args, incomplete + + def format_completion(self, item: click.shell_completion.CompletionItem) -> str: + # TODO: Explore replicating the new behavior from Click, with item types and + # triggering completion for files and directories + # return f"{item.type},{item.value}" + return f"{item.value}" + + def complete(self) -> str: + args, incomplete = self.get_completion_args() + completions = self.get_completions(args, incomplete) + out = [self.format_completion(item) for item in completions] + return "\n".join(out) + + +class ZshComplete(click.shell_completion.ZshComplete): + name = Shells.zsh.value + source_template = COMPLETION_SCRIPT_ZSH + + def source_vars(self) -> dict[str, Any]: + return { + "complete_func": self.func_name, + "autocomplete_var": self.complete_var, + "prog_name": self.prog_name, + } + + def get_completion_args(self) -> tuple[list[str], str]: + completion_args = os.getenv("_TYPER_COMPLETE_ARGS", "") + cwords = click_split_arg_string(completion_args) + args = cwords[1:] + if args and not completion_args.endswith(" "): + incomplete = args[-1] + args = args[:-1] + else: + incomplete = "" + return args, incomplete + + def format_completion(self, item: click.shell_completion.CompletionItem) -> str: + def escape(s: str) -> str: + return ( + s.replace('"', '""') + .replace("'", "''") + .replace("$", "\\$") + .replace("`", "\\`") + .replace(":", r"\\:") + ) + + # TODO: Explore replicating the new behavior from Click, pay attention to + # the difference with and without escape + # return f"{item.type}\n{item.value}\n{item.help if item.help else '_'}" + if item.help: + return f'"{escape(item.value)}":"{_sanitize_help_text(escape(item.help))}"' + else: + return f'"{escape(item.value)}"' + + def complete(self) -> str: + args, incomplete = self.get_completion_args() + completions = self.get_completions(args, incomplete) + res = [self.format_completion(item) for item in completions] + if res: + args_str = "\n".join(res) + return f"_arguments '*: :(({args_str}))'" + else: + return "_files" + + +class FishComplete(click.shell_completion.FishComplete): + name = Shells.fish.value + source_template = COMPLETION_SCRIPT_FISH + + def source_vars(self) -> dict[str, Any]: + return { + "complete_func": self.func_name, + "autocomplete_var": self.complete_var, + "prog_name": self.prog_name, + } + + def get_completion_args(self) -> tuple[list[str], str]: + completion_args = os.getenv("_TYPER_COMPLETE_ARGS", "") + cwords = click_split_arg_string(completion_args) + args = cwords[1:] + if args and not completion_args.endswith(" "): + incomplete = args[-1] + args = args[:-1] + else: + incomplete = "" + return args, incomplete + + def format_completion(self, item: click.shell_completion.CompletionItem) -> str: + # TODO: Explore replicating the new behavior from Click, pay attention to + # the difference with and without formatted help + # if item.help: + # return f"{item.type},{item.value}\t{item.help}" + + # return f"{item.type},{item.value} + if item.help: + formatted_help = re.sub(r"\s", " ", item.help) + return f"{item.value}\t{_sanitize_help_text(formatted_help)}" + else: + return f"{item.value}" + + def complete(self) -> str: + complete_action = os.getenv("_TYPER_COMPLETE_FISH_ACTION", "") + args, incomplete = self.get_completion_args() + completions = self.get_completions(args, incomplete) + show_args = [self.format_completion(item) for item in completions] + if complete_action == "get-args": + if show_args: + return "\n".join(show_args) + elif complete_action == "is-args": + if show_args: + # Activate complete args (no files) + sys.exit(0) + else: + # Deactivate complete args (allow files) + sys.exit(1) + return "" # pragma: no cover + + +class PowerShellComplete(click.shell_completion.ShellComplete): + name = Shells.powershell.value + source_template = COMPLETION_SCRIPT_POWER_SHELL + + def source_vars(self) -> dict[str, Any]: + return { + "complete_func": self.func_name, + "autocomplete_var": self.complete_var, + "prog_name": self.prog_name, + } + + def get_completion_args(self) -> tuple[list[str], str]: + completion_args = os.getenv("_TYPER_COMPLETE_ARGS", "") + incomplete = os.getenv("_TYPER_COMPLETE_WORD_TO_COMPLETE", "") + cwords = click_split_arg_string(completion_args) + args = cwords[1:-1] if incomplete else cwords[1:] + return args, incomplete + + def format_completion(self, item: click.shell_completion.CompletionItem) -> str: + return f"{item.value}:::{_sanitize_help_text(item.help) if item.help else ' '}" + + +def completion_init() -> None: + click.shell_completion.add_completion_class(BashComplete, Shells.bash.value) + click.shell_completion.add_completion_class(ZshComplete, Shells.zsh.value) + click.shell_completion.add_completion_class(FishComplete, Shells.fish.value) + click.shell_completion.add_completion_class( + PowerShellComplete, Shells.powershell.value + ) + click.shell_completion.add_completion_class(PowerShellComplete, Shells.pwsh.value) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/typer/_completion_shared.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/typer/_completion_shared.py new file mode 100644 index 0000000000000000000000000000000000000000..5a81dcf68cddda410becd393e5cf0d7e9e83042e --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/typer/_completion_shared.py @@ -0,0 +1,252 @@ +import os +import re +import subprocess +from enum import Enum +from pathlib import Path + +import click +import shellingham + + +class Shells(str, Enum): + bash = "bash" + zsh = "zsh" + fish = "fish" + powershell = "powershell" + pwsh = "pwsh" + + +COMPLETION_SCRIPT_BASH = """ +%(complete_func)s() { + local IFS=$'\n' + COMPREPLY=( $( env COMP_WORDS="${COMP_WORDS[*]}" \\ + COMP_CWORD=$COMP_CWORD \\ + %(autocomplete_var)s=complete_bash $1 ) ) + return 0 +} + +complete -o default -F %(complete_func)s %(prog_name)s +""" + +COMPLETION_SCRIPT_ZSH = """ +#compdef %(prog_name)s + +%(complete_func)s() { + eval $(env _TYPER_COMPLETE_ARGS="${words[1,$CURRENT]}" %(autocomplete_var)s=complete_zsh %(prog_name)s) +} + +compdef %(complete_func)s %(prog_name)s +""" + +COMPLETION_SCRIPT_FISH = 'complete --command %(prog_name)s --no-files --arguments "(env %(autocomplete_var)s=complete_fish _TYPER_COMPLETE_FISH_ACTION=get-args _TYPER_COMPLETE_ARGS=(commandline -cp) %(prog_name)s)" --condition "env %(autocomplete_var)s=complete_fish _TYPER_COMPLETE_FISH_ACTION=is-args _TYPER_COMPLETE_ARGS=(commandline -cp) %(prog_name)s"' + +COMPLETION_SCRIPT_POWER_SHELL = """ +Import-Module PSReadLine +Set-PSReadLineKeyHandler -Chord Tab -Function MenuComplete +$scriptblock = { + param($wordToComplete, $commandAst, $cursorPosition) + $Env:%(autocomplete_var)s = "complete_powershell" + $Env:_TYPER_COMPLETE_ARGS = $commandAst.ToString() + $Env:_TYPER_COMPLETE_WORD_TO_COMPLETE = $wordToComplete + %(prog_name)s | ForEach-Object { + $commandArray = $_ -Split ":::" + $command = $commandArray[0] + $helpString = $commandArray[1] + [System.Management.Automation.CompletionResult]::new( + $command, $command, 'ParameterValue', $helpString) + } + $Env:%(autocomplete_var)s = "" + $Env:_TYPER_COMPLETE_ARGS = "" + $Env:_TYPER_COMPLETE_WORD_TO_COMPLETE = "" +} +Register-ArgumentCompleter -Native -CommandName %(prog_name)s -ScriptBlock $scriptblock +""" + +_completion_scripts = { + "bash": COMPLETION_SCRIPT_BASH, + "zsh": COMPLETION_SCRIPT_ZSH, + "fish": COMPLETION_SCRIPT_FISH, + "powershell": COMPLETION_SCRIPT_POWER_SHELL, + "pwsh": COMPLETION_SCRIPT_POWER_SHELL, +} + +# TODO: Probably refactor this, copied from Click 7.x +_invalid_ident_char_re = re.compile(r"[^a-zA-Z0-9_]") + + +def get_completion_script(*, prog_name: str, complete_var: str, shell: str) -> str: + cf_name = _invalid_ident_char_re.sub("", prog_name.replace("-", "_")) + script = _completion_scripts.get(shell) + if script is None: + click.echo(f"Shell {shell} not supported.", err=True) + raise click.exceptions.Exit(1) + return ( + script + % { + "complete_func": f"_{cf_name}_completion", + "prog_name": prog_name, + "autocomplete_var": complete_var, + } + ).strip() + + +def install_bash(*, prog_name: str, complete_var: str, shell: str) -> Path: + # Ref: https://github.com/scop/bash-completion#faq + # It seems bash-completion is the official completion system for bash: + # Ref: https://www.gnu.org/software/bash/manual/html_node/A-Programmable-Completion-Example.html + # But installing in the locations from the docs doesn't seem to have effect + completion_path = Path.home() / ".bash_completions" / f"{prog_name}.sh" + rc_path = Path.home() / ".bashrc" + rc_path.parent.mkdir(parents=True, exist_ok=True) + rc_content = "" + if rc_path.is_file(): + rc_content = rc_path.read_text() + completion_init_lines = [f"source '{completion_path}'"] + for line in completion_init_lines: + if line not in rc_content: # pragma: no cover + rc_content += f"\n{line}" + rc_content += "\n" + rc_path.write_text(rc_content) + # Install completion + completion_path.parent.mkdir(parents=True, exist_ok=True) + script_content = get_completion_script( + prog_name=prog_name, complete_var=complete_var, shell=shell + ) + completion_path.write_text(script_content) + return completion_path + + +def install_zsh(*, prog_name: str, complete_var: str, shell: str) -> Path: + # Setup Zsh and load ~/.zfunc + zshrc_path = Path.home() / ".zshrc" + zshrc_path.parent.mkdir(parents=True, exist_ok=True) + zshrc_content = "" + if zshrc_path.is_file(): + zshrc_content = zshrc_path.read_text() + completion_line = "fpath+=~/.zfunc; autoload -Uz compinit; compinit" + if completion_line not in zshrc_content: + zshrc_content += f"\n{completion_line}\n" + style_line = "zstyle ':completion:*' menu select" + # TODO: consider setting the style only for the current program + # style_line = f"zstyle ':completion:*:*:{prog_name}:*' menu select" + # Install zstyle completion config only if the user doesn't have a customization + if "zstyle" not in zshrc_content: + zshrc_content += f"\n{style_line}\n" + zshrc_content = f"{zshrc_content.strip()}\n" + zshrc_path.write_text(zshrc_content) + # Install completion under ~/.zfunc/ + path_obj = Path.home() / f".zfunc/_{prog_name}" + path_obj.parent.mkdir(parents=True, exist_ok=True) + script_content = get_completion_script( + prog_name=prog_name, complete_var=complete_var, shell=shell + ) + path_obj.write_text(script_content) + return path_obj + + +def install_fish(*, prog_name: str, complete_var: str, shell: str) -> Path: + path_obj = Path.home() / f".config/fish/completions/{prog_name}.fish" + parent_dir: Path = path_obj.parent + parent_dir.mkdir(parents=True, exist_ok=True) + script_content = get_completion_script( + prog_name=prog_name, complete_var=complete_var, shell=shell + ) + path_obj.write_text(f"{script_content}\n") + return path_obj + + +def install_powershell(*, prog_name: str, complete_var: str, shell: str) -> Path: + subprocess.run( + [ + shell, + "-Command", + "Set-ExecutionPolicy", + "Unrestricted", + "-Scope", + "CurrentUser", + ] + ) + result = subprocess.run( + [shell, "-NoProfile", "-Command", "echo", "$profile"], + check=True, + stdout=subprocess.PIPE, + ) + if result.returncode != 0: # pragma: no cover + click.echo("Couldn't get PowerShell user profile", err=True) + raise click.exceptions.Exit(result.returncode) + path_str = "" + if isinstance(result.stdout, str): # pragma: no cover + path_str = result.stdout + if isinstance(result.stdout, bytes): + for encoding in ["windows-1252", "utf8", "cp850"]: + try: + path_str = result.stdout.decode(encoding) + break + except UnicodeDecodeError: # pragma: no cover + pass + if not path_str: # pragma: no cover + click.echo("Couldn't decode the path automatically", err=True) + raise click.exceptions.Exit(1) + path_obj = Path(path_str.strip()) + parent_dir: Path = path_obj.parent + parent_dir.mkdir(parents=True, exist_ok=True) + script_content = get_completion_script( + prog_name=prog_name, complete_var=complete_var, shell=shell + ) + with path_obj.open(mode="a") as f: + f.write(f"{script_content}\n") + return path_obj + + +def install( + shell: str | None = None, + prog_name: str | None = None, + complete_var: str | None = None, +) -> tuple[str, Path]: + prog_name = prog_name or click.get_current_context().find_root().info_name + assert prog_name + if complete_var is None: + complete_var = "_{}_COMPLETE".format(prog_name.replace("-", "_").upper()) + test_disable_detection = os.getenv("_TYPER_COMPLETE_TEST_DISABLE_SHELL_DETECTION") + if shell is None and not test_disable_detection: + shell = _get_shell_name() + if shell == "bash": + installed_path = install_bash( + prog_name=prog_name, complete_var=complete_var, shell=shell + ) + return shell, installed_path + elif shell == "zsh": + installed_path = install_zsh( + prog_name=prog_name, complete_var=complete_var, shell=shell + ) + return shell, installed_path + elif shell == "fish": + installed_path = install_fish( + prog_name=prog_name, complete_var=complete_var, shell=shell + ) + return shell, installed_path + elif shell in {"powershell", "pwsh"}: + installed_path = install_powershell( + prog_name=prog_name, complete_var=complete_var, shell=shell + ) + return shell, installed_path + else: + click.echo(f"Shell {shell} is not supported.") + raise click.exceptions.Exit(1) + + +def _get_shell_name() -> str | None: + """Get the current shell name, if available. + + The name will always be lowercase. If the shell cannot be detected, None is + returned. + """ + name: str | None # N.B. shellingham is untyped + try: + # N.B. detect_shell returns a tuple of (shell name, shell command). + # We only need the name. + name, _cmd = shellingham.detect_shell() # noqa: TID251 + except shellingham.ShellDetectionFailure: # pragma: no cover + name = None + + return name diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/typer/_types.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/typer/_types.py new file mode 100644 index 0000000000000000000000000000000000000000..dc9fc63220d91b5c7ecc16170bb9de7afb135fb4 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/typer/_types.py @@ -0,0 +1,27 @@ +from enum import Enum +from typing import TypeVar + +import click + +ParamTypeValue = TypeVar("ParamTypeValue") + + +class TyperChoice(click.Choice[ParamTypeValue]): + def normalize_choice( + self, choice: ParamTypeValue, ctx: click.Context | None + ) -> str: + # Click 8.2.0 added a new method `normalize_choice` to the `Choice` class + # to support enums, but it uses the enum names, while Typer has always used the + # enum values. + # This class overrides that method to maintain the previous behavior. + # In Click: + # normed_value = choice.name if isinstance(choice, Enum) else str(choice) + normed_value = str(choice.value) if isinstance(choice, Enum) else str(choice) + + if ctx is not None and ctx.token_normalize_func is not None: + normed_value = ctx.token_normalize_func(normed_value) + + if not self.case_sensitive: + normed_value = normed_value.casefold() + + return normed_value diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/typer/_typing.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/typer/_typing.py new file mode 100644 index 0000000000000000000000000000000000000000..218f674c2220589738656294fdd8ec243965376f --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/typer/_typing.py @@ -0,0 +1,73 @@ +# Copied from pydantic 1.9.2 (the latest version to support python 3.6.) +# https://github.com/pydantic/pydantic/blob/v1.9.2/pydantic/typing.py +# Reduced drastically to only include Typer-specific 3.9+ functionality +# mypy: ignore-errors + +import types +from collections.abc import Callable +from typing import ( + Annotated, + Any, + Literal, + Union, + get_args, + get_origin, + get_type_hints, +) + + +def is_union(tp: type[Any] | None) -> bool: + return tp is Union or tp is types.UnionType # noqa: E721 + + +__all__ = ( + "NoneType", + "is_none_type", + "is_callable_type", + "is_literal_type", + "all_literal_values", + "is_union", + "Annotated", + "Literal", + "get_args", + "get_origin", + "get_type_hints", +) + + +NoneType = None.__class__ + + +NONE_TYPES: tuple[Any, Any, Any] = (None, NoneType, Literal[None]) + + +def is_none_type(type_: Any) -> bool: + for none_type in NONE_TYPES: + if type_ is none_type: + return True + return False + + +def is_callable_type(type_: type[Any]) -> bool: + return type_ is Callable or get_origin(type_) is Callable + + +def is_literal_type(type_: type[Any]) -> bool: + return get_origin(type_) is Literal + + +def literal_values(type_: type[Any]) -> tuple[Any, ...]: + return get_args(type_) + + +def all_literal_values(type_: type[Any]) -> tuple[Any, ...]: + """ + This method is used to retrieve all Literal values as + Literal can be used recursively (see https://www.python.org/dev/peps/pep-0586) + e.g. `Literal[Literal[Literal[1, 2, 3], "foo"], 5, None]` + """ + if not is_literal_type(type_): + return (type_,) + + values = literal_values(type_) + return tuple(x for value in values for x in all_literal_values(value)) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/typer/cli.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/typer/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..4b4356f8bdafcd5fc9e8de6c0c95f6f8f4f8bda1 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/typer/cli.py @@ -0,0 +1,317 @@ +import importlib.util +import re +import sys +from pathlib import Path +from typing import Any + +import click +import typer +import typer.core +from click import Command, Group, Option + +from . import __version__ +from .core import HAS_RICH, MARKUP_MODE_KEY + +default_app_names = ("app", "cli", "main") +default_func_names = ("main", "cli", "app") + +app = typer.Typer() +utils_app = typer.Typer(help="Extra utility commands for Typer apps.") +app.add_typer(utils_app, name="utils") + + +class State: + def __init__(self) -> None: + self.app: str | None = None + self.func: str | None = None + self.file: Path | None = None + self.module: str | None = None + + +state = State() + + +def maybe_update_state(ctx: click.Context) -> None: + path_or_module = ctx.params.get("path_or_module") + if path_or_module: + file_path = Path(path_or_module) + if file_path.exists() and file_path.is_file(): + state.file = file_path + else: + if not re.fullmatch(r"[a-zA-Z_]\w*(\.[a-zA-Z_]\w*)*", path_or_module): + typer.echo( + f"Not a valid file or Python module: {path_or_module}", err=True + ) + sys.exit(1) + state.module = path_or_module + app_name = ctx.params.get("app") + if app_name: + state.app = app_name + func_name = ctx.params.get("func") + if func_name: + state.func = func_name + + +class TyperCLIGroup(typer.core.TyperGroup): + def list_commands(self, ctx: click.Context) -> list[str]: + self.maybe_add_run(ctx) + return super().list_commands(ctx) + + def get_command(self, ctx: click.Context, name: str) -> Command | None: # ty: ignore[invalid-method-override] + self.maybe_add_run(ctx) + return super().get_command(ctx, name) + + def invoke(self, ctx: click.Context) -> Any: + self.maybe_add_run(ctx) + return super().invoke(ctx) + + def maybe_add_run(self, ctx: click.Context) -> None: + maybe_update_state(ctx) + maybe_add_run_to_cli(self) + + +def get_typer_from_module(module: Any) -> typer.Typer | None: + # Try to get defined app + if state.app: + obj = getattr(module, state.app, None) + if not isinstance(obj, typer.Typer): + typer.echo(f"Not a Typer object: --app {state.app}", err=True) + sys.exit(1) + return obj + # Try to get defined function + if state.func: + func_obj = getattr(module, state.func, None) + if not callable(func_obj): + typer.echo(f"Not a function: --func {state.func}", err=True) + raise typer.Exit(1) + sub_app = typer.Typer() + sub_app.command()(func_obj) + return sub_app + # Iterate and get a default object to use as CLI + local_names = dir(module) + local_names_set = set(local_names) + # Try to get a default Typer app + for name in default_app_names: + if name in local_names_set: + obj = getattr(module, name, None) + if isinstance(obj, typer.Typer): + return obj + # Try to get any Typer app + for name in local_names_set - set(default_app_names): + obj = getattr(module, name) + if isinstance(obj, typer.Typer): + return obj + # Try to get a default function + for func_name in default_func_names: + func_obj = getattr(module, func_name, None) + if callable(func_obj): + sub_app = typer.Typer() + sub_app.command()(func_obj) + return sub_app + # Try to get any func app + for func_name in local_names_set - set(default_func_names): + func_obj = getattr(module, func_name) + if callable(func_obj): + sub_app = typer.Typer() + sub_app.command()(func_obj) + return sub_app + return None + + +def get_typer_from_state() -> typer.Typer | None: + spec = None + if state.file: + module_name = state.file.name + spec = importlib.util.spec_from_file_location(module_name, str(state.file)) + elif state.module: + spec = importlib.util.find_spec(state.module) + if spec is None: + if state.file: + typer.echo(f"Could not import as Python file: {state.file}", err=True) + else: + typer.echo(f"Could not import as Python module: {state.module}", err=True) + sys.exit(1) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) # type: ignore + obj = get_typer_from_module(module) + return obj + + +def maybe_add_run_to_cli(cli: click.Group) -> None: + if "run" not in cli.commands: + if state.file or state.module: + obj = get_typer_from_state() + if obj: + obj._add_completion = False + click_obj = typer.main.get_command(obj) + click_obj.name = "run" + if not click_obj.help: + click_obj.help = "Run the provided Typer app." + cli.add_command(click_obj) + + +def print_version(ctx: click.Context, param: Option, value: bool) -> None: + if not value or ctx.resilient_parsing: + return + typer.echo(f"Typer version: {__version__}") + raise typer.Exit() + + +@app.callback(cls=TyperCLIGroup, no_args_is_help=True) +def callback( + ctx: typer.Context, + *, + path_or_module: str = typer.Argument(None), + app: str = typer.Option(None, help="The typer app object/variable to use."), + func: str = typer.Option(None, help="The function to convert to Typer."), + version: bool = typer.Option( + False, + "--version", + help="Print version and exit.", + callback=print_version, + ), +) -> None: + """ + Run Typer scripts with completion, without having to create a package. + + You probably want to install completion for the typer command: + + $ typer --install-completion + + https://typer.tiangolo.com/ + """ + maybe_update_state(ctx) + + +def get_docs_for_click( + *, + obj: Command, + ctx: typer.Context, + indent: int = 0, + name: str = "", + call_prefix: str = "", + title: str | None = None, +) -> str: + docs = "#" * (1 + indent) + command_name = name or obj.name + if call_prefix: + command_name = f"{call_prefix} {command_name}" + if not title: + title = f"`{command_name}`" if command_name else "CLI" + docs += f" {title}\n\n" + rich_markup_mode = None + if hasattr(ctx, "obj") and isinstance(ctx.obj, dict): + rich_markup_mode = ctx.obj.get(MARKUP_MODE_KEY, None) + to_parse: bool = bool(HAS_RICH and (rich_markup_mode == "rich")) + if obj.help: + docs += f"{_parse_html(to_parse, obj.help)}\n\n" + usage_pieces = obj.collect_usage_pieces(ctx) + if usage_pieces: + docs += "**Usage**:\n\n" + docs += "```console\n" + docs += "$ " + if command_name: + docs += f"{command_name} " + docs += f"{' '.join(usage_pieces)}\n" + docs += "```\n\n" + args = [] + opts = [] + for param in obj.get_params(ctx): + rv = param.get_help_record(ctx) + if rv is not None: + if param.param_type_name == "argument": + args.append(rv) + elif param.param_type_name == "option": + opts.append(rv) + if args: + docs += "**Arguments**:\n\n" + for arg_name, arg_help in args: + docs += f"* `{arg_name}`" + if arg_help: + docs += f": {_parse_html(to_parse, arg_help)}" + docs += "\n" + docs += "\n" + if opts: + docs += "**Options**:\n\n" + for opt_name, opt_help in opts: + docs += f"* `{opt_name}`" + if opt_help: + docs += f": {_parse_html(to_parse, opt_help)}" + docs += "\n" + docs += "\n" + if obj.epilog: + docs += f"{obj.epilog}\n\n" + if isinstance(obj, Group): + group = obj + commands = group.list_commands(ctx) + if commands: + docs += "**Commands**:\n\n" + for command in commands: + command_obj = group.get_command(ctx, command) + assert command_obj + docs += f"* `{command_obj.name}`" + command_help = command_obj.get_short_help_str() + if command_help: + docs += f": {_parse_html(to_parse, command_help)}" + docs += "\n" + docs += "\n" + for command in commands: + command_obj = group.get_command(ctx, command) + assert command_obj + use_prefix = "" + if command_name: + use_prefix += f"{command_name}" + docs += get_docs_for_click( + obj=command_obj, ctx=ctx, indent=indent + 1, call_prefix=use_prefix + ) + return docs + + +def _parse_html(to_parse: bool, input_text: str) -> str: + if not to_parse: + return input_text + from . import rich_utils + + return rich_utils.rich_to_html(input_text) + + +@utils_app.command() +def docs( + ctx: typer.Context, + name: str = typer.Option("", help="The name of the CLI program to use in docs."), + output: Path | None = typer.Option( + None, + help="An output file to write docs to, like README.md.", + file_okay=True, + dir_okay=False, + ), + title: str | None = typer.Option( + None, + help="The title for the documentation page. If not provided, the name of " + "the program is used.", + ), +) -> None: + """ + Generate Markdown docs for a Typer app. + """ + typer_obj = get_typer_from_state() + if not typer_obj: + typer.echo("No Typer app found", err=True) + raise typer.Abort() + if hasattr(typer_obj, "rich_markup_mode"): + if not hasattr(ctx, "obj") or ctx.obj is None: + ctx.ensure_object(dict) + if isinstance(ctx.obj, dict): + ctx.obj[MARKUP_MODE_KEY] = typer_obj.rich_markup_mode + click_obj = typer.main.get_command(typer_obj) + docs = get_docs_for_click(obj=click_obj, ctx=ctx, name=name, title=title) + clean_docs = f"{docs.strip()}\n" + if output: + output.write_text(clean_docs) + typer.echo(f"Docs saved to: {output}") + else: + typer.echo(clean_docs) + + +def main() -> Any: + return app() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/typer/colors.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/typer/colors.py new file mode 100644 index 0000000000000000000000000000000000000000..54e7b166cb1de83321a4965cc4915824b47a7f4f --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/typer/colors.py @@ -0,0 +1,20 @@ +# Variable names to colors, just for completion +BLACK = "black" +RED = "red" +GREEN = "green" +YELLOW = "yellow" +BLUE = "blue" +MAGENTA = "magenta" +CYAN = "cyan" +WHITE = "white" + +RESET = "reset" + +BRIGHT_BLACK = "bright_black" +BRIGHT_RED = "bright_red" +BRIGHT_GREEN = "bright_green" +BRIGHT_YELLOW = "bright_yellow" +BRIGHT_BLUE = "bright_blue" +BRIGHT_MAGENTA = "bright_magenta" +BRIGHT_CYAN = "bright_cyan" +BRIGHT_WHITE = "bright_white" diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/typer/completion.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/typer/completion.py new file mode 100644 index 0000000000000000000000000000000000000000..0d621e411d7bab9a6d4ab14102670adbcabaf962 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/typer/completion.py @@ -0,0 +1,146 @@ +import os +import sys +from collections.abc import MutableMapping +from typing import Any + +import click + +from ._completion_classes import completion_init +from ._completion_shared import Shells, _get_shell_name, get_completion_script, install +from .models import ParamMeta +from .params import Option +from .utils import get_params_from_function + +_click_patched = False + + +def get_completion_inspect_parameters() -> tuple[ParamMeta, ParamMeta]: + completion_init() + test_disable_detection = os.getenv("_TYPER_COMPLETE_TEST_DISABLE_SHELL_DETECTION") + if not test_disable_detection: + parameters = get_params_from_function(_install_completion_placeholder_function) + else: + parameters = get_params_from_function( + _install_completion_no_auto_placeholder_function + ) + install_param, show_param = parameters.values() + return install_param, show_param + + +def install_callback(ctx: click.Context, param: click.Parameter, value: Any) -> Any: + if not value or ctx.resilient_parsing: + return value # pragma: no cover + if isinstance(value, str): + shell, path = install(shell=value) + else: + shell, path = install() + click.secho(f"{shell} completion installed in {path}", fg="green") + click.echo("Completion will take effect once you restart the terminal") + sys.exit(0) + + +def show_callback(ctx: click.Context, param: click.Parameter, value: Any) -> Any: + if not value or ctx.resilient_parsing: + return value # pragma: no cover + prog_name = ctx.find_root().info_name + assert prog_name + complete_var = "_{}_COMPLETE".format(prog_name.replace("-", "_").upper()) + shell = "" + test_disable_detection = os.getenv("_TYPER_COMPLETE_TEST_DISABLE_SHELL_DETECTION") + if isinstance(value, str): + shell = value + elif not test_disable_detection: + detected_shell = _get_shell_name() + if detected_shell is not None: + shell = detected_shell + script_content = get_completion_script( + prog_name=prog_name, complete_var=complete_var, shell=shell + ) + click.echo(script_content) + sys.exit(0) + + +# Create a fake command function to extract the completion parameters +def _install_completion_placeholder_function( + install_completion: bool = Option( + None, + "--install-completion", + callback=install_callback, + expose_value=False, + help="Install completion for the current shell.", + ), + show_completion: bool = Option( + None, + "--show-completion", + callback=show_callback, + expose_value=False, + help="Show completion for the current shell, to copy it or customize the installation.", + ), +) -> Any: + pass # pragma: no cover + + +def _install_completion_no_auto_placeholder_function( + install_completion: Shells = Option( + None, + callback=install_callback, + expose_value=False, + help="Install completion for the specified shell.", + ), + show_completion: Shells = Option( + None, + callback=show_callback, + expose_value=False, + help="Show completion for the specified shell, to copy it or customize the installation.", + ), +) -> Any: + pass # pragma: no cover + + +# Re-implement Click's shell_complete to add error message with: +# Invalid completion instruction +# To use 7.x instruction style for compatibility +# And to add extra error messages, for compatibility with Typer in previous versions +# This is only called in new Command method, only used by Click 8.x+ +def shell_complete( + cli: click.Command, + ctx_args: MutableMapping[str, Any], + prog_name: str, + complete_var: str, + instruction: str, +) -> int: + import click + import click.shell_completion + + if "_" not in instruction: + click.echo("Invalid completion instruction.", err=True) + return 1 + + # Click 8 changed the order/style of shell instructions from e.g. + # source_bash to bash_source + # Typer override to preserve the old style for compatibility + # Original in Click 8.x commented: + # shell, _, instruction = instruction.partition("_") + instruction, _, shell = instruction.partition("_") + # Typer override end + + comp_cls = click.shell_completion.get_completion_class(shell) + + if comp_cls is None: + click.echo(f"Shell {shell} not supported.", err=True) + return 1 + + comp = comp_cls(cli, ctx_args, prog_name, complete_var) + + if instruction == "source": + click.echo(comp.source()) + return 0 + + # Typer override to print the completion help msg with Rich + if instruction == "complete": + click.echo(comp.complete()) + return 0 + # Typer override end + + click.echo(f'Completion instruction "{instruction}" not supported.', err=True) + return 1 diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/typer/core.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/typer/core.py new file mode 100644 index 0000000000000000000000000000000000000000..3e72d839893185826dfdc9e9d6d8006a279db48d --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/typer/core.py @@ -0,0 +1,821 @@ +import errno +import inspect +import os +import sys +from collections.abc import Callable, MutableMapping, Sequence +from difflib import get_close_matches +from enum import Enum +from gettext import gettext as _ +from typing import ( + Any, + TextIO, + Union, + cast, +) + +import click +import click.core +import click.formatting +import click.shell_completion +import click.types +import click.utils + +from ._typing import Literal +from .utils import parse_boolean_env_var + +MarkupMode = Literal["markdown", "rich", None] +MARKUP_MODE_KEY = "TYPER_RICH_MARKUP_MODE" + +HAS_RICH = parse_boolean_env_var(os.getenv("TYPER_USE_RICH"), default=True) + +if HAS_RICH: + DEFAULT_MARKUP_MODE: MarkupMode = "rich" +else: + DEFAULT_MARKUP_MODE = None + + +# Copy from click.parser._split_opt +def _split_opt(opt: str) -> tuple[str, str]: + first = opt[:1] + if first.isalnum(): + return "", opt + if opt[1:2] == first: + return opt[:2], opt[2:] + return first, opt[1:] + + +def _typer_param_setup_autocompletion_compat( + self: click.Parameter, + *, + autocompletion: Callable[ + [click.Context, list[str], str], list[tuple[str, str] | str] + ] + | None = None, +) -> None: + if self._custom_shell_complete is not None: + import warnings + + warnings.warn( + "In Typer, only the parameter 'autocompletion' is supported. " + "The support for 'shell_complete' is deprecated and will be removed in upcoming versions. ", + DeprecationWarning, + stacklevel=2, + ) + + if autocompletion is not None: + + def compat_autocompletion( + ctx: click.Context, param: click.core.Parameter, incomplete: str + ) -> list["click.shell_completion.CompletionItem"]: + from click.shell_completion import CompletionItem + + out = [] + + for c in autocompletion(ctx, [], incomplete): + if isinstance(c, tuple): + use_completion = CompletionItem(c[0], help=c[1]) + else: + assert isinstance(c, str) + use_completion = CompletionItem(c) + + if use_completion.value.startswith(incomplete): + out.append(use_completion) + + return out + + self._custom_shell_complete = compat_autocompletion + + +def _get_default_string( + obj: Union["TyperArgument", "TyperOption"], + *, + ctx: click.Context, + show_default_is_str: bool, + default_value: list[Any] | tuple[Any, ...] | str | Callable[..., Any] | Any, +) -> str: + # Extracted from click.core.Option.get_help_record() to be reused by + # rich_utils avoiding RegEx hacks + if show_default_is_str: + default_string = f"({obj.show_default})" + elif isinstance(default_value, (list, tuple)): + default_string = ", ".join( + _get_default_string( + obj, ctx=ctx, show_default_is_str=show_default_is_str, default_value=d + ) + for d in default_value + ) + elif isinstance(default_value, Enum): + default_string = str(default_value.value) + elif inspect.isfunction(default_value): + default_string = _("(dynamic)") + elif isinstance(obj, TyperOption) and obj.is_bool_flag and obj.secondary_opts: + # For boolean flags that have distinct True/False opts, + # use the opt without prefix instead of the value. + # Typer override, original commented + # default_string = click.parser.split_opt( + # (self.opts if self.default else self.secondary_opts)[0] + # )[1] + if obj.default: + if obj.opts: + default_string = _split_opt(obj.opts[0])[1] + else: + default_string = str(default_value) + else: + default_string = _split_opt(obj.secondary_opts[0])[1] + # Typer override end + elif ( + isinstance(obj, TyperOption) + and obj.is_bool_flag + and not obj.secondary_opts + and not default_value + ): + default_string = "" + else: + default_string = str(default_value) + return default_string + + +def _extract_default_help_str( + obj: Union["TyperArgument", "TyperOption"], *, ctx: click.Context +) -> Any | Callable[[], Any] | None: + # Extracted from click.core.Option.get_help_record() to be reused by + # rich_utils avoiding RegEx hacks + # Temporarily enable resilient parsing to avoid type casting + # failing for the default. Might be possible to extend this to + # help formatting in general. + resilient = ctx.resilient_parsing + ctx.resilient_parsing = True + + try: + default_value = obj.get_default(ctx, call=False) + finally: + ctx.resilient_parsing = resilient + return default_value + + +def _main( + self: click.Command, + *, + args: Sequence[str] | None = None, + prog_name: str | None = None, + complete_var: str | None = None, + standalone_mode: bool = True, + windows_expand_args: bool = True, + rich_markup_mode: MarkupMode = DEFAULT_MARKUP_MODE, + **extra: Any, +) -> Any: + # Typer override, duplicated from click.main() to handle custom rich exceptions + # Verify that the environment is configured correctly, or reject + # further execution to avoid a broken script. + if args is None: + args = sys.argv[1:] + + # Covered in Click tests + if os.name == "nt" and windows_expand_args: # pragma: no cover + args = click.utils._expand_args(args) + else: + args = list(args) + + if prog_name is None: + prog_name = click.utils._detect_program_name() + + # Process shell completion requests and exit early. + self._main_shell_completion(extra, prog_name, complete_var) + + try: + try: + with self.make_context(prog_name, args, **extra) as ctx: + rv = self.invoke(ctx) + if not standalone_mode: + return rv + # it's not safe to `ctx.exit(rv)` here! + # note that `rv` may actually contain data like "1" which + # has obvious effects + # more subtle case: `rv=[None, None]` can come out of + # chained commands which all returned `None` -- so it's not + # even always obvious that `rv` indicates success/failure + # by its truthiness/falsiness + ctx.exit() + except EOFError as e: + click.echo(file=sys.stderr) + raise click.Abort() from e + except KeyboardInterrupt as e: + raise click.exceptions.Exit(130) from e + except click.ClickException as e: + if not standalone_mode: + raise + # Typer override + if HAS_RICH and rich_markup_mode is not None: + from . import rich_utils + + rich_utils.rich_format_error(e) + else: + e.show() + # Typer override end + sys.exit(e.exit_code) + except OSError as e: + if e.errno == errno.EPIPE: + sys.stdout = cast(TextIO, click.utils.PacifyFlushWrapper(sys.stdout)) + sys.stderr = cast(TextIO, click.utils.PacifyFlushWrapper(sys.stderr)) + sys.exit(1) + else: + raise + except click.exceptions.Exit as e: + if standalone_mode: + sys.exit(e.exit_code) + else: + # in non-standalone mode, return the exit code + # note that this is only reached if `self.invoke` above raises + # an Exit explicitly -- thus bypassing the check there which + # would return its result + # the results of non-standalone execution may therefore be + # somewhat ambiguous: if there are codepaths which lead to + # `ctx.exit(1)` and to `return 1`, the caller won't be able to + # tell the difference between the two + return e.exit_code + except click.Abort: + if not standalone_mode: + raise + # Typer override + if HAS_RICH and rich_markup_mode is not None: + from . import rich_utils + + rich_utils.rich_abort_error() + else: + click.echo(_("Aborted!"), file=sys.stderr) + # Typer override end + sys.exit(1) + + +class TyperArgument(click.core.Argument): + def __init__( + self, + *, + # Parameter + param_decls: list[str], + type: Any | None = None, + required: bool | None = None, + default: Any | None = None, + callback: Callable[..., Any] | None = None, + nargs: int | None = None, + metavar: str | None = None, + expose_value: bool = True, + is_eager: bool = False, + envvar: str | list[str] | None = None, + # Note that shell_complete is not fully supported and will be removed in future versions + # TODO: Remove shell_complete in a future version (after 0.16.0) + shell_complete: Callable[ + [click.Context, click.Parameter, str], + list["click.shell_completion.CompletionItem"] | list[str], + ] + | None = None, + autocompletion: Callable[..., Any] | None = None, + # TyperArgument + show_default: bool | str = True, + show_choices: bool = True, + show_envvar: bool = True, + help: str | None = None, + hidden: bool = False, + # Rich settings + rich_help_panel: str | None = None, + ): + self.help = help + self.show_default = show_default + self.show_choices = show_choices + self.show_envvar = show_envvar + self.hidden = hidden + self.rich_help_panel = rich_help_panel + + super().__init__( + param_decls=param_decls, + type=type, + required=required, + default=default, + callback=callback, + nargs=nargs, + metavar=metavar, + expose_value=expose_value, + is_eager=is_eager, + envvar=envvar, + shell_complete=shell_complete, + ) + _typer_param_setup_autocompletion_compat(self, autocompletion=autocompletion) + + def _get_default_string( + self, + *, + ctx: click.Context, + show_default_is_str: bool, + default_value: list[Any] | tuple[Any, ...] | str | Callable[..., Any] | Any, + ) -> str: + return _get_default_string( + self, + ctx=ctx, + show_default_is_str=show_default_is_str, + default_value=default_value, + ) + + def _extract_default_help_str( + self, *, ctx: click.Context + ) -> Any | Callable[[], Any] | None: + return _extract_default_help_str(self, ctx=ctx) + + def get_help_record(self, ctx: click.Context) -> tuple[str, str] | None: + # Modified version of click.core.Option.get_help_record() + # to support Arguments + if self.hidden: + return None + name = self.make_metavar(ctx=ctx) + help = self.help or "" + extra = [] + if self.show_envvar: + envvar = self.envvar + # allow_from_autoenv is currently not supported in Typer for CLI Arguments + if envvar is not None: + var_str = ( + ", ".join(str(d) for d in envvar) + if isinstance(envvar, (list, tuple)) + else envvar + ) + extra.append(f"env var: {var_str}") + + # Typer override: + # Extracted to _extract_default_help_str() to allow re-using it in rich_utils + default_value = self._extract_default_help_str(ctx=ctx) + # Typer override end + + show_default_is_str = isinstance(self.show_default, str) + + if show_default_is_str or ( + default_value is not None and (self.show_default or ctx.show_default) + ): + # Typer override: + # Extracted to _get_default_string() to allow re-using it in rich_utils + default_string = self._get_default_string( + ctx=ctx, + show_default_is_str=show_default_is_str, + default_value=default_value, + ) + # Typer override end + if default_string: + extra.append(_("default: {default}").format(default=default_string)) + if self.required: + extra.append(_("required")) + if extra: + extra_str = "; ".join(extra) + extra_str = f"[{extra_str}]" + rich_markup_mode = None + if hasattr(ctx, "obj") and isinstance(ctx.obj, dict): + rich_markup_mode = ctx.obj.get(MARKUP_MODE_KEY, None) + if HAS_RICH and rich_markup_mode == "rich": + # This is needed for when we want to export to HTML + from . import rich_utils + + extra_str = rich_utils.escape_before_html_export(extra_str) + + help = f"{help} {extra_str}" if help else f"{extra_str}" + return name, help + + def make_metavar(self, ctx: click.Context | None = None) -> str: + # Modified version of click.core.Argument.make_metavar() + # to include Argument name + if self.metavar is not None: + var = self.metavar + if not self.required and not var.startswith("["): + var = f"[{var}]" + return var + var = (self.name or "").upper() + if not self.required: + var = f"[{var}]" + type_var = self.type.get_metavar(self, ctx=ctx) # type: ignore[arg-type] + # type_var = self.type.get_metavar(self, ctx=ctx) + if type_var: + var += f":{type_var}" + if self.nargs != 1: + var += "..." + return var + + def value_is_missing(self, value: Any) -> bool: + return _value_is_missing(self, value) + + +class TyperOption(click.core.Option): + def __init__( + self, + *, + # Parameter + param_decls: list[str], + type: click.types.ParamType | Any | None = None, + required: bool | None = None, + default: Any | None = None, + callback: Callable[..., Any] | None = None, + nargs: int | None = None, + metavar: str | None = None, + expose_value: bool = True, + is_eager: bool = False, + envvar: str | list[str] | None = None, + # Note that shell_complete is not fully supported and will be removed in future versions + # TODO: Remove shell_complete in a future version (after 0.16.0) + shell_complete: Callable[ + [click.Context, click.Parameter, str], + list["click.shell_completion.CompletionItem"] | list[str], + ] + | None = None, + autocompletion: Callable[..., Any] | None = None, + # Option + show_default: bool | str = False, + prompt: bool | str = False, + confirmation_prompt: bool | str = False, + prompt_required: bool = True, + hide_input: bool = False, + is_flag: bool | None = None, + multiple: bool = False, + count: bool = False, + allow_from_autoenv: bool = True, + help: str | None = None, + hidden: bool = False, + show_choices: bool = True, + show_envvar: bool = False, + # Rich settings + rich_help_panel: str | None = None, + ): + super().__init__( + param_decls=param_decls, + type=type, + required=required, + default=default, + callback=callback, + nargs=nargs, + metavar=metavar, + expose_value=expose_value, + is_eager=is_eager, + envvar=envvar, + show_default=show_default, + prompt=prompt, + confirmation_prompt=confirmation_prompt, + hide_input=hide_input, + is_flag=is_flag, + multiple=multiple, + count=count, + allow_from_autoenv=allow_from_autoenv, + help=help, + hidden=hidden, + show_choices=show_choices, + show_envvar=show_envvar, + prompt_required=prompt_required, + shell_complete=shell_complete, + ) + _typer_param_setup_autocompletion_compat(self, autocompletion=autocompletion) + self.rich_help_panel = rich_help_panel + + def _get_default_string( + self, + *, + ctx: click.Context, + show_default_is_str: bool, + default_value: list[Any] | tuple[Any, ...] | str | Callable[..., Any] | Any, + ) -> str: + return _get_default_string( + self, + ctx=ctx, + show_default_is_str=show_default_is_str, + default_value=default_value, + ) + + def _extract_default_help_str( + self, *, ctx: click.Context + ) -> Any | Callable[[], Any] | None: + return _extract_default_help_str(self, ctx=ctx) + + def make_metavar(self, ctx: click.Context | None = None) -> str: + return super().make_metavar(ctx=ctx) # type: ignore[arg-type] + + def get_help_record(self, ctx: click.Context) -> tuple[str, str] | None: + # Duplicate all of Click's logic only to modify a single line, to allow boolean + # flags with only names for False values as it's currently supported by Typer + # Ref: https://typer.tiangolo.com/tutorial/parameter-types/bool/#only-names-for-false + if self.hidden: + return None + + any_prefix_is_slash = False + + def _write_opts(opts: Sequence[str]) -> str: + nonlocal any_prefix_is_slash + + rv, any_slashes = click.formatting.join_options(opts) + + if any_slashes: + any_prefix_is_slash = True + + if not self.is_flag and not self.count: + rv += f" {self.make_metavar(ctx=ctx)}" + + return rv + + rv = [_write_opts(self.opts)] + + if self.secondary_opts: + rv.append(_write_opts(self.secondary_opts)) + + help = self.help or "" + extra = [] + + if self.show_envvar: + envvar = self.envvar + + if envvar is None: + if ( + self.allow_from_autoenv + and ctx.auto_envvar_prefix is not None + and self.name is not None + ): + envvar = f"{ctx.auto_envvar_prefix}_{self.name.upper()}" + + if envvar is not None: + var_str = ( + envvar + if isinstance(envvar, str) + else ", ".join(str(d) for d in envvar) + ) + extra.append(_("env var: {var}").format(var=var_str)) + + # Typer override: + # Extracted to _extract_default() to allow re-using it in rich_utils + default_value = self._extract_default_help_str(ctx=ctx) + # Typer override end + + show_default_is_str = isinstance(self.show_default, str) + + if show_default_is_str or ( + default_value is not None and (self.show_default or ctx.show_default) + ): + # Typer override: + # Extracted to _get_default_string() to allow re-using it in rich_utils + default_string = self._get_default_string( + ctx=ctx, + show_default_is_str=show_default_is_str, + default_value=default_value, + ) + # Typer override end + if default_string: + extra.append(_("default: {default}").format(default=default_string)) + + if isinstance(self.type, click.types._NumberRangeBase): + range_str = self.type._describe_range() + + if range_str: + extra.append(range_str) + + if self.required: + extra.append(_("required")) + + if extra: + extra_str = "; ".join(extra) + extra_str = f"[{extra_str}]" + rich_markup_mode = None + if hasattr(ctx, "obj") and isinstance(ctx.obj, dict): + rich_markup_mode = ctx.obj.get(MARKUP_MODE_KEY, None) + if HAS_RICH and rich_markup_mode == "rich": + # This is needed for when we want to export to HTML + from . import rich_utils + + extra_str = rich_utils.escape_before_html_export(extra_str) + + help = f"{help} {extra_str}" if help else f"{extra_str}" + + return ("; " if any_prefix_is_slash else " / ").join(rv), help + + def value_is_missing(self, value: Any) -> bool: + return _value_is_missing(self, value) + + +def _value_is_missing(param: click.Parameter, value: Any) -> bool: + if value is None: + return True + + # Click 8.3 and beyond + # if value is UNSET: + # return True + + if (param.nargs != 1 or param.multiple) and value == (): + return True # pragma: no cover + + return False + + +def _typer_format_options( + self: click.core.Command, *, ctx: click.Context, formatter: click.HelpFormatter +) -> None: + args = [] + opts = [] + for param in self.get_params(ctx): + rv = param.get_help_record(ctx) + if rv is not None: + if param.param_type_name == "argument": + args.append(rv) + elif param.param_type_name == "option": + opts.append(rv) + + if args: + with formatter.section(_("Arguments")): + formatter.write_dl(args) + if opts: + with formatter.section(_("Options")): + formatter.write_dl(opts) + + +def _typer_main_shell_completion( + self: click.core.Command, + *, + ctx_args: MutableMapping[str, Any], + prog_name: str, + complete_var: str | None = None, +) -> None: + if complete_var is None: + complete_var = f"_{prog_name}_COMPLETE".replace("-", "_").upper() + + instruction = os.environ.get(complete_var) + + if not instruction: + return + + from .completion import shell_complete + + rv = shell_complete(self, ctx_args, prog_name, complete_var, instruction) + sys.exit(rv) + + +class TyperCommand(click.core.Command): + def __init__( + self, + name: str | None, + *, + context_settings: dict[str, Any] | None = None, + callback: Callable[..., Any] | None = None, + params: list[click.Parameter] | None = None, + help: str | None = None, + epilog: str | None = None, + short_help: str | None = None, + options_metavar: str | None = "[OPTIONS]", + add_help_option: bool = True, + no_args_is_help: bool = False, + hidden: bool = False, + deprecated: bool = False, + # Rich settings + rich_markup_mode: MarkupMode = DEFAULT_MARKUP_MODE, + rich_help_panel: str | None = None, + ) -> None: + super().__init__( + name=name, + context_settings=context_settings, + callback=callback, + params=params, + help=help, + epilog=epilog, + short_help=short_help, + options_metavar=options_metavar, + add_help_option=add_help_option, + no_args_is_help=no_args_is_help, + hidden=hidden, + deprecated=deprecated, + ) + self.rich_markup_mode: MarkupMode = rich_markup_mode + self.rich_help_panel = rich_help_panel + + def format_options( + self, ctx: click.Context, formatter: click.HelpFormatter + ) -> None: + _typer_format_options(self, ctx=ctx, formatter=formatter) + + def _main_shell_completion( + self, + ctx_args: MutableMapping[str, Any], + prog_name: str, + complete_var: str | None = None, + ) -> None: + _typer_main_shell_completion( + self, ctx_args=ctx_args, prog_name=prog_name, complete_var=complete_var + ) + + def main( + self, + args: Sequence[str] | None = None, + prog_name: str | None = None, + complete_var: str | None = None, + standalone_mode: bool = True, + windows_expand_args: bool = True, + **extra: Any, + ) -> Any: + return _main( + self, + args=args, + prog_name=prog_name, + complete_var=complete_var, + standalone_mode=standalone_mode, + windows_expand_args=windows_expand_args, + rich_markup_mode=self.rich_markup_mode, + **extra, + ) + + def format_help(self, ctx: click.Context, formatter: click.HelpFormatter) -> None: + if not HAS_RICH or self.rich_markup_mode is None: + if not hasattr(ctx, "obj") or ctx.obj is None: + ctx.ensure_object(dict) + if isinstance(ctx.obj, dict): + ctx.obj[MARKUP_MODE_KEY] = self.rich_markup_mode + return super().format_help(ctx, formatter) + from . import rich_utils + + return rich_utils.rich_format_help( + obj=self, + ctx=ctx, + markup_mode=self.rich_markup_mode, + ) + + +class TyperGroup(click.core.Group): + def __init__( + self, + *, + name: str | None = None, + commands: dict[str, click.Command] | Sequence[click.Command] | None = None, + # Rich settings + rich_markup_mode: MarkupMode = DEFAULT_MARKUP_MODE, + rich_help_panel: str | None = None, + suggest_commands: bool = True, + **attrs: Any, + ) -> None: + super().__init__(name=name, commands=commands, **attrs) + self.rich_markup_mode: MarkupMode = rich_markup_mode + self.rich_help_panel = rich_help_panel + self.suggest_commands = suggest_commands + + def format_options( + self, ctx: click.Context, formatter: click.HelpFormatter + ) -> None: + _typer_format_options(self, ctx=ctx, formatter=formatter) + self.format_commands(ctx, formatter) + + def _main_shell_completion( + self, + ctx_args: MutableMapping[str, Any], + prog_name: str, + complete_var: str | None = None, + ) -> None: + _typer_main_shell_completion( + self, ctx_args=ctx_args, prog_name=prog_name, complete_var=complete_var + ) + + def resolve_command( + self, ctx: click.Context, args: list[str] + ) -> tuple[str | None, click.Command | None, list[str]]: + try: + return super().resolve_command(ctx, args) + except click.UsageError as e: + if self.suggest_commands: + available_commands = list(self.commands.keys()) + if available_commands and args: + typo = args[0] + matches = get_close_matches(typo, available_commands) + if matches: + suggestions = ", ".join(f"{m!r}" for m in matches) + message = e.message.rstrip(".") + e.message = f"{message}. Did you mean {suggestions}?" + raise + + def main( + self, + args: Sequence[str] | None = None, + prog_name: str | None = None, + complete_var: str | None = None, + standalone_mode: bool = True, + windows_expand_args: bool = True, + **extra: Any, + ) -> Any: + return _main( + self, + args=args, + prog_name=prog_name, + complete_var=complete_var, + standalone_mode=standalone_mode, + windows_expand_args=windows_expand_args, + rich_markup_mode=self.rich_markup_mode, + **extra, + ) + + def format_help(self, ctx: click.Context, formatter: click.HelpFormatter) -> None: + if not HAS_RICH or self.rich_markup_mode is None: + return super().format_help(ctx, formatter) + from . import rich_utils + + return rich_utils.rich_format_help( + obj=self, + ctx=ctx, + markup_mode=self.rich_markup_mode, + ) + + def list_commands(self, ctx: click.Context) -> list[str]: + """Returns a list of subcommand names. + Note that in Click's Group class, these are sorted. + In Typer, we wish to maintain the original order of creation (cf Issue #933)""" + return [n for n, c in self.commands.items()] diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/typer/main.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/typer/main.py new file mode 100644 index 0000000000000000000000000000000000000000..f4f21bb8444a80af5ad8ab82822fc972f0207b9c --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/typer/main.py @@ -0,0 +1,2013 @@ +import inspect +import os +import platform +import shutil +import subprocess +import sys +import traceback +from collections.abc import Callable, Sequence +from datetime import datetime +from enum import Enum +from functools import update_wrapper +from pathlib import Path +from traceback import FrameSummary, StackSummary +from types import TracebackType +from typing import Annotated, Any +from uuid import UUID + +import click +from annotated_doc import Doc +from typer._types import TyperChoice + +from ._typing import get_args, get_origin, is_literal_type, is_union, literal_values +from .completion import get_completion_inspect_parameters +from .core import ( + DEFAULT_MARKUP_MODE, + HAS_RICH, + MarkupMode, + TyperArgument, + TyperCommand, + TyperGroup, + TyperOption, +) +from .models import ( + AnyType, + ArgumentInfo, + CommandFunctionType, + CommandInfo, + Default, + DefaultPlaceholder, + DeveloperExceptionConfig, + FileBinaryRead, + FileBinaryWrite, + FileText, + FileTextWrite, + NoneType, + OptionInfo, + ParameterInfo, + ParamMeta, + Required, + TyperInfo, + TyperPath, +) +from .utils import get_params_from_function + +_original_except_hook = sys.excepthook +_typer_developer_exception_attr_name = "__typer_developer_exception__" + + +def except_hook( + exc_type: type[BaseException], exc_value: BaseException, tb: TracebackType | None +) -> None: + exception_config: DeveloperExceptionConfig | None = getattr( + exc_value, _typer_developer_exception_attr_name, None + ) + standard_traceback = os.getenv( + "TYPER_STANDARD_TRACEBACK", os.getenv("_TYPER_STANDARD_TRACEBACK") + ) + if ( + standard_traceback + or not exception_config + or not exception_config.pretty_exceptions_enable + ): + _original_except_hook(exc_type, exc_value, tb) + return + typer_path = os.path.dirname(__file__) + click_path = os.path.dirname(click.__file__) + internal_dir_names = [typer_path, click_path] + exc = exc_value + if HAS_RICH: + from . import rich_utils + + rich_tb = rich_utils.get_traceback(exc, exception_config, internal_dir_names) + console_stderr = rich_utils._get_rich_console(stderr=True) + console_stderr.print(rich_tb) + return + tb_exc = traceback.TracebackException.from_exception(exc) + stack: list[FrameSummary] = [] + for frame in tb_exc.stack: + if any(frame.filename.startswith(path) for path in internal_dir_names): + if not exception_config.pretty_exceptions_short: + # Hide the line for internal libraries, Typer and Click + stack.append( + traceback.FrameSummary( + filename=frame.filename, + lineno=frame.lineno, + name=frame.name, + line="", + ) + ) + else: + stack.append(frame) + # Type ignore ref: https://github.com/python/typeshed/pull/8244 + final_stack_summary = StackSummary.from_list(stack) + tb_exc.stack = final_stack_summary + for line in tb_exc.format(): + print(line, file=sys.stderr) + return + + +def get_install_completion_arguments() -> tuple[click.Parameter, click.Parameter]: + install_param, show_param = get_completion_inspect_parameters() + click_install_param, _ = get_click_param(install_param) + click_show_param, _ = get_click_param(show_param) + return click_install_param, click_show_param + + +class Typer: + """ + `Typer` main class, the main entrypoint to use Typer. + + Read more in the + [Typer docs for First Steps](https://typer.tiangolo.com/tutorial/typer-app/). + + ## Example + + ```python + import typer + + app = typer.Typer() + ``` + """ + + def __init__( + self, + *, + name: Annotated[ + str | None, + Doc( + """ + The name of this application. + Mostly used to set the name for [subcommands](https://typer.tiangolo.com/tutorial/subcommands/), in which case it can be overridden by `add_typer(name=...)`. + + **Example** + + ```python + import typer + + app = typer.Typer(name="users") + ``` + """ + ), + ] = Default(None), + cls: Annotated[ + type[TyperGroup] | None, + Doc( + """ + The class of this app. Mainly used when [using the Click library underneath](https://typer.tiangolo.com/tutorial/using-click/). Can usually be left at the default value `None`. + Otherwise, should be a subtype of `TyperGroup`. + + **Example** + + ```python + import typer + + app = typer.Typer(cls=TyperGroup) + ``` + """ + ), + ] = Default(None), + invoke_without_command: Annotated[ + bool, + Doc( + """ + By setting this to `True`, you can make sure a callback is executed even when no subcommand is provided. + + **Example** + + ```python + import typer + + app = typer.Typer(invoke_without_command=True) + ``` + """ + ), + ] = Default(False), + no_args_is_help: Annotated[ + bool, + Doc( + """ + If this is set to `True`, running a command without any arguments will automatically show the help page. + + **Example** + + ```python + import typer + + app = typer.Typer(no_args_is_help=True) + ``` + """ + ), + ] = Default(False), + subcommand_metavar: Annotated[ + str | None, + Doc( + """ + **Note**: you probably shouldn't use this parameter, it is inherited + from Click and supported for compatibility. + + --- + + How to represent the subcommand argument in help. + """ + ), + ] = Default(None), + chain: Annotated[ + bool, + Doc( + """ + **Note**: you probably shouldn't use this parameter, it is inherited + from Click and supported for compatibility. + + --- + + Allow passing more than one subcommand argument. + """ + ), + ] = Default(False), + result_callback: Annotated[ + Callable[..., Any] | None, + Doc( + """ + **Note**: you probably shouldn't use this parameter, it is inherited + from Click and supported for compatibility. + + --- + + A function to call after the group's and subcommand's callbacks. + """ + ), + ] = Default(None), + # Command + context_settings: Annotated[ + dict[Any, Any] | None, + Doc( + """ + Pass configurations for the [context](https://typer.tiangolo.com/tutorial/commands/context/). + Available configurations can be found in the docs for Click's `Context` [here](https://click.palletsprojects.com/en/stable/api/#context). + + **Example** + + ```python + import typer + + app = typer.Typer(context_settings={"help_option_names": ["-h", "--help"]}) + ``` + """ + ), + ] = Default(None), + callback: Annotated[ + Callable[..., Any] | None, + Doc( + """ + Add a callback to the main Typer app. Can be overridden with `@app.callback()`. + See [the tutorial about callbacks](https://typer.tiangolo.com/tutorial/commands/callback/) for more details. + + **Example** + + ```python + import typer + + def callback(): + print("Running a command") + + app = typer.Typer(callback=callback) + ``` + """ + ), + ] = Default(None), + help: Annotated[ + str | None, + Doc( + """ + Help text for the main Typer app. + See [the tutorial about name and help](https://typer.tiangolo.com/tutorial/subcommands/name-and-help) for different ways of setting a command's help, + and which one takes priority. + + **Example** + + ```python + import typer + + app = typer.Typer(help="Some help.") + ``` + """ + ), + ] = Default(None), + epilog: Annotated[ + str | None, + Doc( + """ + Text that will be printed right after the help text. + + **Example** + + ```python + import typer + + app = typer.Typer(epilog="May the force be with you") + ``` + """ + ), + ] = Default(None), + short_help: Annotated[ + str | None, + Doc( + """ + A shortened version of the help text that can be used e.g. in the help table listing subcommands. + When not defined, the normal `help` text will be used instead. + + **Example** + + ```python + import typer + + app = typer.Typer(help="A lot of explanation about user management", short_help="user management") + ``` + """ + ), + ] = Default(None), + options_metavar: Annotated[ + str, + Doc( + """ + In the example usage string of the help text for a command, the default placeholder for various arguments is `[OPTIONS]`. + Set `options_metavar` to change this into a different string. + + **Example** + + ```python + import typer + + app = typer.Typer(options_metavar="[OPTS]") + ``` + """ + ), + ] = Default("[OPTIONS]"), + add_help_option: Annotated[ + bool, + Doc( + """ + **Note**: you probably shouldn't use this parameter, it is inherited + from Click and supported for compatibility. + + --- + + By default each command registers a `--help` option. This can be disabled by this parameter. + """ + ), + ] = Default(True), + hidden: Annotated[ + bool, + Doc( + """ + Hide this command from help outputs. `False` by default. + + **Example** + + ```python + import typer + + app = typer.Typer(hidden=True) + ``` + """ + ), + ] = Default(False), + deprecated: Annotated[ + bool, + Doc( + """ + Mark this command as being deprecated in the help text. `False` by default. + + **Example** + + ```python + import typer + + app = typer.Typer(deprecated=True) + ``` + """ + ), + ] = Default(False), + add_completion: Annotated[ + bool, + Doc( + """ + Toggle whether or not to add the `--install-completion` and `--show-completion` options to the app. + Set to `True` by default. + + **Example** + + ```python + import typer + + app = typer.Typer(add_completion=False) + ``` + """ + ), + ] = True, + # Rich settings + rich_markup_mode: Annotated[ + MarkupMode, + Doc( + """ + Enable markup text if you have Rich installed. This can be set to `"markdown"`, `"rich"`, or `None`. + By default, `rich_markup_mode` is `None` if Rich is not installed, and `"rich"` if it is installed. + See [the tutorial on help formatting](https://typer.tiangolo.com/tutorial/commands/help/#rich-markdown-and-markup) for more information. + + **Example** + + ```python + import typer + + app = typer.Typer(rich_markup_mode="rich") + ``` + """ + ), + ] = DEFAULT_MARKUP_MODE, + rich_help_panel: Annotated[ + str | None, + Doc( + """ + Set the panel name of the command when the help is printed with Rich. + + **Example** + + ```python + import typer + + app = typer.Typer(rich_help_panel="Utils and Configs") + ``` + """ + ), + ] = Default(None), + suggest_commands: Annotated[ + bool, + Doc( + """ + As of version 0.20.0, Typer provides [support for mistyped command names](https://typer.tiangolo.com/tutorial/commands/help/#suggest-commands) by printing helpful suggestions. + You can turn this setting off with `suggest_commands`: + + **Example** + + ```python + import typer + + app = typer.Typer(suggest_commands=False) + ``` + """ + ), + ] = True, + pretty_exceptions_enable: Annotated[ + bool, + Doc( + """ + If you want to disable [pretty exceptions with Rich](https://typer.tiangolo.com/tutorial/exceptions/#exceptions-with-rich), + you can set `pretty_exceptions_enable` to `False`. When doing so, you will see the usual standard exception trace. + + **Example** + + ```python + import typer + + app = typer.Typer(pretty_exceptions_enable=False) + ``` + """ + ), + ] = True, + pretty_exceptions_show_locals: Annotated[ + bool, + Doc( + """ + If Rich is installed, [error messages](https://typer.tiangolo.com/tutorial/exceptions/#exceptions-and-errors) + will be nicely printed. + + If you set `pretty_exceptions_show_locals=True` it will also include the values of local variables for easy debugging. + + However, if such a variable contains delicate information, you should consider leaving `pretty_exceptions_show_locals=False` + (the default) to `False` to enhance security. + + **Example** + + ```python + import typer + + app = typer.Typer(pretty_exceptions_show_locals=True) + ``` + """ + ), + ] = False, + pretty_exceptions_short: Annotated[ + bool, + Doc( + """ + By default, [pretty exceptions formatted with Rich](https://typer.tiangolo.com/tutorial/exceptions/#exceptions-with-rich) hide the long stack trace. + If you want to show the full trace instead, you can set the parameter `pretty_exceptions_short` to `False`: + + **Example** + + ```python + import typer + + app = typer.Typer(pretty_exceptions_short=False) + ``` + """ + ), + ] = True, + ): + self._add_completion = add_completion + self.rich_markup_mode: MarkupMode = rich_markup_mode + self.rich_help_panel = rich_help_panel + self.suggest_commands = suggest_commands + self.pretty_exceptions_enable = pretty_exceptions_enable + self.pretty_exceptions_show_locals = pretty_exceptions_show_locals + self.pretty_exceptions_short = pretty_exceptions_short + self.info = TyperInfo( + name=name, + cls=cls, + invoke_without_command=invoke_without_command, + no_args_is_help=no_args_is_help, + subcommand_metavar=subcommand_metavar, + chain=chain, + result_callback=result_callback, + context_settings=context_settings, + callback=callback, + help=help, + epilog=epilog, + short_help=short_help, + options_metavar=options_metavar, + add_help_option=add_help_option, + hidden=hidden, + deprecated=deprecated, + ) + self.registered_groups: list[TyperInfo] = [] + self.registered_commands: list[CommandInfo] = [] + self.registered_callback: TyperInfo | None = None + + def callback( + self, + *, + cls: Annotated[ + type[TyperGroup] | None, + Doc( + """ + The class of this app. Mainly used when [using the Click library underneath](https://typer.tiangolo.com/tutorial/using-click/). Can usually be left at the default value `None`. + Otherwise, should be a subtype of `TyperGroup`. + """ + ), + ] = Default(None), + invoke_without_command: Annotated[ + bool, + Doc( + """ + By setting this to `True`, you can make sure a callback is executed even when no subcommand is provided. + """ + ), + ] = Default(False), + no_args_is_help: Annotated[ + bool, + Doc( + """ + If this is set to `True`, running a command without any arguments will automatically show the help page. + """ + ), + ] = Default(False), + subcommand_metavar: Annotated[ + str | None, + Doc( + """ + **Note**: you probably shouldn't use this parameter, it is inherited + from Click and supported for compatibility. + + --- + + How to represent the subcommand argument in help. + """ + ), + ] = Default(None), + chain: Annotated[ + bool, + Doc( + """ + **Note**: you probably shouldn't use this parameter, it is inherited + from Click and supported for compatibility. + + --- + + Allow passing more than one subcommand argument. + """ + ), + ] = Default(False), + result_callback: Annotated[ + Callable[..., Any] | None, + Doc( + """ + **Note**: you probably shouldn't use this parameter, it is inherited + from Click and supported for compatibility. + + --- + + A function to call after the group's and subcommand's callbacks. + """ + ), + ] = Default(None), + # Command + context_settings: Annotated[ + dict[Any, Any] | None, + Doc( + """ + Pass configurations for the [context](https://typer.tiangolo.com/tutorial/commands/context/). + Available configurations can be found in the docs for Click's `Context` [here](https://click.palletsprojects.com/en/stable/api/#context). + """ + ), + ] = Default(None), + help: Annotated[ + str | None, + Doc( + """ + Help text for the command. + See [the tutorial about name and help](https://typer.tiangolo.com/tutorial/subcommands/name-and-help) for different ways of setting a command's help, + and which one takes priority. + """ + ), + ] = Default(None), + epilog: Annotated[ + str | None, + Doc( + """ + Text that will be printed right after the help text. + """ + ), + ] = Default(None), + short_help: Annotated[ + str | None, + Doc( + """ + A shortened version of the help text that can be used e.g. in the help table listing subcommands. + When not defined, the normal `help` text will be used instead. + """ + ), + ] = Default(None), + options_metavar: Annotated[ + str | None, + Doc( + """ + In the example usage string of the help text for a command, the default placeholder for various arguments is `[OPTIONS]`. + Set `options_metavar` to change this into a different string. When `None`, the default value will be used. + """ + ), + ] = Default(None), + add_help_option: Annotated[ + bool, + Doc( + """ + **Note**: you probably shouldn't use this parameter, it is inherited + from Click and supported for compatibility. + + --- + + By default each command registers a `--help` option. This can be disabled by this parameter. + """ + ), + ] = Default(True), + hidden: Annotated[ + bool, + Doc( + """ + Hide this command from help outputs. `False` by default. + """ + ), + ] = Default(False), + deprecated: Annotated[ + bool, + Doc( + """ + Mark this command as deprecated in the help text. `False` by default. + """ + ), + ] = Default(False), + # Rich settings + rich_help_panel: Annotated[ + str | None, + Doc( + """ + Set the panel name of the command when the help is printed with Rich. + """ + ), + ] = Default(None), + ) -> Callable[[CommandFunctionType], CommandFunctionType]: + """ + Using the decorator `@app.callback`, you can declare the CLI parameters for the main CLI application. + + Read more in the + [Typer docs for Callbacks](https://typer.tiangolo.com/tutorial/commands/callback/). + + ## Example + + ```python + import typer + + app = typer.Typer() + state = {"verbose": False} + + @app.callback() + def main(verbose: bool = False): + if verbose: + print("Will write verbose output") + state["verbose"] = True + + @app.command() + def delete(username: str): + # define subcommand + ... + ``` + """ + + def decorator(f: CommandFunctionType) -> CommandFunctionType: + self.registered_callback = TyperInfo( + cls=cls, + invoke_without_command=invoke_without_command, + no_args_is_help=no_args_is_help, + subcommand_metavar=subcommand_metavar, + chain=chain, + result_callback=result_callback, + context_settings=context_settings, + callback=f, + help=help, + epilog=epilog, + short_help=short_help, + options_metavar=( + options_metavar or self._info_val_str("options_metavar") + ), + add_help_option=add_help_option, + hidden=hidden, + deprecated=deprecated, + rich_help_panel=rich_help_panel, + ) + return f + + return decorator + + def command( + self, + name: Annotated[ + str | None, + Doc( + """ + The name of this command. + """ + ), + ] = None, + *, + cls: Annotated[ + type[TyperCommand] | None, + Doc( + """ + The class of this command. Mainly used when [using the Click library underneath](https://typer.tiangolo.com/tutorial/using-click/). Can usually be left at the default value `None`. + Otherwise, should be a subtype of `TyperCommand`. + """ + ), + ] = None, + context_settings: Annotated[ + dict[Any, Any] | None, + Doc( + """ + Pass configurations for the [context](https://typer.tiangolo.com/tutorial/commands/context/). + Available configurations can be found in the docs for Click's `Context` [here](https://click.palletsprojects.com/en/stable/api/#context). + """ + ), + ] = None, + help: Annotated[ + str | None, + Doc( + """ + Help text for the command. + See [the tutorial about name and help](https://typer.tiangolo.com/tutorial/subcommands/name-and-help) for different ways of setting a command's help, + and which one takes priority. + """ + ), + ] = None, + epilog: Annotated[ + str | None, + Doc( + """ + Text that will be printed right after the help text. + """ + ), + ] = None, + short_help: Annotated[ + str | None, + Doc( + """ + A shortened version of the help text that can be used e.g. in the help table listing subcommands. + When not defined, the normal `help` text will be used instead. + """ + ), + ] = None, + options_metavar: Annotated[ + str | None, + Doc( + """ + In the example usage string of the help text for a command, the default placeholder for various arguments is `[OPTIONS]`. + Set `options_metavar` to change this into a different string. When `None`, the default value will be used. + """ + ), + ] = Default(None), + add_help_option: Annotated[ + bool, + Doc( + """ + **Note**: you probably shouldn't use this parameter, it is inherited + from Click and supported for compatibility. + + --- + + By default each command registers a `--help` option. This can be disabled by this parameter. + """ + ), + ] = True, + no_args_is_help: Annotated[ + bool, + Doc( + """ + If this is set to `True`, running a command without any arguments will automatically show the help page. + """ + ), + ] = False, + hidden: Annotated[ + bool, + Doc( + """ + Hide this command from help outputs. `False` by default. + """ + ), + ] = False, + deprecated: Annotated[ + bool, + Doc( + """ + Mark this command as deprecated in the help outputs. `False` by default. + """ + ), + ] = False, + # Rich settings + rich_help_panel: Annotated[ + str | None, + Doc( + """ + Set the panel name of the command when the help is printed with Rich. + """ + ), + ] = Default(None), + ) -> Callable[[CommandFunctionType], CommandFunctionType]: + """ + Using the decorator `@app.command`, you can define a subcommand of the previously defined Typer app. + + Read more in the + [Typer docs for Commands](https://typer.tiangolo.com/tutorial/commands/). + + ## Example + + ```python + import typer + + app = typer.Typer() + + @app.command() + def create(): + print("Creating user: Hiro Hamada") + + @app.command() + def delete(): + print("Deleting user: Hiro Hamada") + ``` + """ + if cls is None: + cls = TyperCommand + + def decorator(f: CommandFunctionType) -> CommandFunctionType: + self.registered_commands.append( + CommandInfo( + name=name, + cls=cls, + context_settings=context_settings, + callback=f, + help=help, + epilog=epilog, + short_help=short_help, + options_metavar=( + options_metavar or self._info_val_str("options_metavar") + ), + add_help_option=add_help_option, + no_args_is_help=no_args_is_help, + hidden=hidden, + deprecated=deprecated, + # Rich settings + rich_help_panel=rich_help_panel, + ) + ) + return f + + return decorator + + def add_typer( + self, + typer_instance: "Typer", + *, + name: Annotated[ + str | None, + Doc( + """ + The name of this subcommand. + See [the tutorial about name and help](https://typer.tiangolo.com/tutorial/subcommands/name-and-help) for different ways of setting a command's name, + and which one takes priority. + """ + ), + ] = Default(None), + cls: Annotated[ + type[TyperGroup] | None, + Doc( + """ + The class of this subcommand. Mainly used when [using the Click library underneath](https://typer.tiangolo.com/tutorial/using-click/). Can usually be left at the default value `None`. + Otherwise, should be a subtype of `TyperGroup`. + """ + ), + ] = Default(None), + invoke_without_command: Annotated[ + bool, + Doc( + """ + By setting this to `True`, you can make sure a callback is executed even when no subcommand is provided. + """ + ), + ] = Default(False), + no_args_is_help: Annotated[ + bool, + Doc( + """ + If this is set to `True`, running a command without any arguments will automatically show the help page. + """ + ), + ] = Default(False), + subcommand_metavar: Annotated[ + str | None, + Doc( + """ + **Note**: you probably shouldn't use this parameter, it is inherited + from Click and supported for compatibility. + + --- + + How to represent the subcommand argument in help. + """ + ), + ] = Default(None), + chain: Annotated[ + bool, + Doc( + """ + **Note**: you probably shouldn't use this parameter, it is inherited + from Click and supported for compatibility. + + --- + + Allow passing more than one subcommand argument. + """ + ), + ] = Default(False), + result_callback: Annotated[ + Callable[..., Any] | None, + Doc( + """ + **Note**: you probably shouldn't use this parameter, it is inherited + from Click and supported for compatibility. + + --- + + A function to call after the group's and subcommand's callbacks. + """ + ), + ] = Default(None), + # Command + context_settings: Annotated[ + dict[Any, Any] | None, + Doc( + """ + Pass configurations for the [context](https://typer.tiangolo.com/tutorial/commands/context/). + Available configurations can be found in the docs for Click's `Context` [here](https://click.palletsprojects.com/en/stable/api/#context). + """ + ), + ] = Default(None), + callback: Annotated[ + Callable[..., Any] | None, + Doc( + """ + Add a callback to this app. + See [the tutorial about callbacks](https://typer.tiangolo.com/tutorial/commands/callback/) for more details. + """ + ), + ] = Default(None), + help: Annotated[ + str | None, + Doc( + """ + Help text for the subcommand. + See [the tutorial about name and help](https://typer.tiangolo.com/tutorial/subcommands/name-and-help) for different ways of setting a command's help, + and which one takes priority. + """ + ), + ] = Default(None), + epilog: Annotated[ + str | None, + Doc( + """ + Text that will be printed right after the help text. + """ + ), + ] = Default(None), + short_help: Annotated[ + str | None, + Doc( + """ + A shortened version of the help text that can be used e.g. in the help table listing subcommands. + When not defined, the normal `help` text will be used instead. + """ + ), + ] = Default(None), + options_metavar: Annotated[ + str | None, + Doc( + """ + In the example usage string of the help text for a command, the default placeholder for various arguments is `[OPTIONS]`. + Set `options_metavar` to change this into a different string. When `None`, the default value will be used. + """ + ), + ] = Default(None), + add_help_option: Annotated[ + bool, + Doc( + """ + **Note**: you probably shouldn't use this parameter, it is inherited + from Click and supported for compatibility. + + --- + + By default each command registers a `--help` option. This can be disabled by this parameter. + """ + ), + ] = Default(True), + hidden: Annotated[ + bool, + Doc( + """ + Hide this command from help outputs. `False` by default. + """ + ), + ] = Default(False), + deprecated: Annotated[ + bool, + Doc( + """ + Mark this command as deprecated in the help outputs. `False` by default. + """ + ), + ] = False, + # Rich settings + rich_help_panel: Annotated[ + str | None, + Doc( + """ + Set the panel name of the command when the help is printed with Rich. + """ + ), + ] = Default(None), + ) -> None: + """ + Add subcommands to the main app using `app.add_typer()`. + Subcommands may be defined in separate modules, ensuring clean separation of code by functionality. + + Read more in the + [Typer docs for SubCommands](https://typer.tiangolo.com/tutorial/subcommands/add-typer/). + + ## Example + + ```python + import typer + + from .add import app as add_app + from .delete import app as delete_app + + app = typer.Typer() + + app.add_typer(add_app) + app.add_typer(delete_app) + ``` + """ + self.registered_groups.append( + TyperInfo( + typer_instance, + name=name, + cls=cls, + invoke_without_command=invoke_without_command, + no_args_is_help=no_args_is_help, + subcommand_metavar=subcommand_metavar, + chain=chain, + result_callback=result_callback, + context_settings=context_settings, + callback=callback, + help=help, + epilog=epilog, + short_help=short_help, + options_metavar=( + options_metavar or self._info_val_str("options_metavar") + ), + add_help_option=add_help_option, + hidden=hidden, + deprecated=deprecated, + rich_help_panel=rich_help_panel, + ) + ) + + def __call__(self, *args: Any, **kwargs: Any) -> Any: + if sys.excepthook != except_hook: + sys.excepthook = except_hook + try: + return get_command(self)(*args, **kwargs) + except Exception as e: + # Set a custom attribute to tell the hook to show nice exceptions for user + # code. An alternative/first implementation was a custom exception with + # raise custom_exc from e + # but that means the last error shown is the custom exception, not the + # actual error. This trick improves developer experience by showing the + # actual error last. + setattr( + e, + _typer_developer_exception_attr_name, + DeveloperExceptionConfig( + pretty_exceptions_enable=self.pretty_exceptions_enable, + pretty_exceptions_show_locals=self.pretty_exceptions_show_locals, + pretty_exceptions_short=self.pretty_exceptions_short, + ), + ) + raise e + + def _info_val_str(self, name: str) -> str: + val = getattr(self.info, name) + val_str = val.value if isinstance(val, DefaultPlaceholder) else val + assert isinstance(val_str, str) + return val_str + + +def get_group(typer_instance: Typer) -> TyperGroup: + group = get_group_from_info( + TyperInfo(typer_instance), + pretty_exceptions_short=typer_instance.pretty_exceptions_short, + rich_markup_mode=typer_instance.rich_markup_mode, + suggest_commands=typer_instance.suggest_commands, + ) + return group + + +def get_command(typer_instance: Typer) -> click.Command: + if typer_instance._add_completion: + click_install_param, click_show_param = get_install_completion_arguments() + if ( + typer_instance.registered_callback + or typer_instance.info.callback + or typer_instance.registered_groups + or len(typer_instance.registered_commands) > 1 + ): + # Create a Group + click_command: click.Command = get_group(typer_instance) + if typer_instance._add_completion: + click_command.params.append(click_install_param) + click_command.params.append(click_show_param) + return click_command + elif len(typer_instance.registered_commands) == 1: + # Create a single Command + single_command = typer_instance.registered_commands[0] + + if not single_command.context_settings and not isinstance( + typer_instance.info.context_settings, DefaultPlaceholder + ): + single_command.context_settings = typer_instance.info.context_settings + + click_command = get_command_from_info( + single_command, + pretty_exceptions_short=typer_instance.pretty_exceptions_short, + rich_markup_mode=typer_instance.rich_markup_mode, + ) + if typer_instance._add_completion: + click_command.params.append(click_install_param) + click_command.params.append(click_show_param) + return click_command + raise RuntimeError( + "Could not get a command for this Typer instance" + ) # pragma: no cover + + +def solve_typer_info_help(typer_info: TyperInfo) -> str: + # Priority 1: Explicit value was set in app.add_typer() + if not isinstance(typer_info.help, DefaultPlaceholder): + return inspect.cleandoc(typer_info.help or "") + # Priority 2: Explicit value was set in sub_app.callback() + if typer_info.typer_instance and typer_info.typer_instance.registered_callback: + callback_help = typer_info.typer_instance.registered_callback.help + if not isinstance(callback_help, DefaultPlaceholder): + return inspect.cleandoc(callback_help or "") + # Priority 3: Explicit value was set in sub_app = typer.Typer() + if typer_info.typer_instance and typer_info.typer_instance.info: + instance_help = typer_info.typer_instance.info.help + if not isinstance(instance_help, DefaultPlaceholder): + return inspect.cleandoc(instance_help or "") + # Priority 4: Implicit inference from callback docstring in app.add_typer() + if typer_info.callback: + doc = inspect.getdoc(typer_info.callback) + if doc: + return doc + # Priority 5: Implicit inference from callback docstring in @app.callback() + if typer_info.typer_instance and typer_info.typer_instance.registered_callback: + callback = typer_info.typer_instance.registered_callback.callback + if not isinstance(callback, DefaultPlaceholder): + doc = inspect.getdoc(callback or "") + if doc: + return doc + # Priority 6: Implicit inference from callback docstring in typer.Typer() + if typer_info.typer_instance and typer_info.typer_instance.info: + instance_callback = typer_info.typer_instance.info.callback + if not isinstance(instance_callback, DefaultPlaceholder): + doc = inspect.getdoc(instance_callback) + if doc: + return doc + # Value not set, use the default + return typer_info.help.value + + +def solve_typer_info_defaults(typer_info: TyperInfo) -> TyperInfo: + values: dict[str, Any] = {} + for name, value in typer_info.__dict__.items(): + # Priority 1: Value was set in app.add_typer() + if not isinstance(value, DefaultPlaceholder): + values[name] = value + continue + # Priority 2: Value was set in @subapp.callback() + try: + callback_value = getattr( + typer_info.typer_instance.registered_callback, # type: ignore + name, + ) + if not isinstance(callback_value, DefaultPlaceholder): + values[name] = callback_value + continue + except AttributeError: + pass + # Priority 3: Value set in subapp = typer.Typer() + try: + instance_value = getattr( + typer_info.typer_instance.info, # type: ignore + name, + ) + if not isinstance(instance_value, DefaultPlaceholder): + values[name] = instance_value + continue + except AttributeError: + pass + # Value not set, use the default + values[name] = value.value + values["help"] = solve_typer_info_help(typer_info) + return TyperInfo(**values) + + +def get_group_from_info( + group_info: TyperInfo, + *, + pretty_exceptions_short: bool, + suggest_commands: bool, + rich_markup_mode: MarkupMode, +) -> TyperGroup: + assert group_info.typer_instance, ( + "A Typer instance is needed to generate a Click Group" + ) + commands: dict[str, click.Command] = {} + for command_info in group_info.typer_instance.registered_commands: + command = get_command_from_info( + command_info=command_info, + pretty_exceptions_short=pretty_exceptions_short, + rich_markup_mode=rich_markup_mode, + ) + if command.name: + commands[command.name] = command + for sub_group_info in group_info.typer_instance.registered_groups: + sub_group = get_group_from_info( + sub_group_info, + pretty_exceptions_short=pretty_exceptions_short, + rich_markup_mode=rich_markup_mode, + suggest_commands=suggest_commands, + ) + if sub_group.name: + commands[sub_group.name] = sub_group + else: + if sub_group.callback: + import warnings + + warnings.warn( + "The 'callback' parameter is not supported by Typer when using `add_typer` without a name", + stacklevel=5, + ) + for sub_command_name, sub_command in sub_group.commands.items(): + commands[sub_command_name] = sub_command + solved_info = solve_typer_info_defaults(group_info) + ( + params, + convertors, + context_param_name, + ) = get_params_convertors_ctx_param_name_from_function(solved_info.callback) + cls = solved_info.cls or TyperGroup + assert issubclass(cls, TyperGroup), f"{cls} should be a subclass of {TyperGroup}" + group = cls( + name=solved_info.name or "", + commands=commands, + invoke_without_command=solved_info.invoke_without_command, + no_args_is_help=solved_info.no_args_is_help, + subcommand_metavar=solved_info.subcommand_metavar, + chain=solved_info.chain, + result_callback=solved_info.result_callback, + context_settings=solved_info.context_settings, + callback=get_callback( + callback=solved_info.callback, + params=params, + convertors=convertors, + context_param_name=context_param_name, + pretty_exceptions_short=pretty_exceptions_short, + ), + params=params, + help=solved_info.help, + epilog=solved_info.epilog, + short_help=solved_info.short_help, + options_metavar=solved_info.options_metavar, + add_help_option=solved_info.add_help_option, + hidden=solved_info.hidden, + deprecated=solved_info.deprecated, + rich_markup_mode=rich_markup_mode, + # Rich settings + rich_help_panel=solved_info.rich_help_panel, + suggest_commands=suggest_commands, + ) + return group + + +def get_command_name(name: str) -> str: + return name.lower().replace("_", "-") + + +def get_params_convertors_ctx_param_name_from_function( + callback: Callable[..., Any] | None, +) -> tuple[list[click.Argument | click.Option], dict[str, Any], str | None]: + params = [] + convertors = {} + context_param_name = None + if callback: + parameters = get_params_from_function(callback) + for param_name, param in parameters.items(): + if lenient_issubclass(param.annotation, click.Context): + context_param_name = param_name + continue + click_param, convertor = get_click_param(param) + if convertor: + convertors[param_name] = convertor + params.append(click_param) + return params, convertors, context_param_name + + +def get_command_from_info( + command_info: CommandInfo, + *, + pretty_exceptions_short: bool, + rich_markup_mode: MarkupMode, +) -> click.Command: + assert command_info.callback, "A command must have a callback function" + name = command_info.name or get_command_name(command_info.callback.__name__) # ty:ignore[unresolved-attribute] + use_help = command_info.help + if use_help is None: + use_help = inspect.getdoc(command_info.callback) + else: + use_help = inspect.cleandoc(use_help) + ( + params, + convertors, + context_param_name, + ) = get_params_convertors_ctx_param_name_from_function(command_info.callback) + cls = command_info.cls or TyperCommand + command = cls( + name=name, + context_settings=command_info.context_settings, + callback=get_callback( + callback=command_info.callback, + params=params, + convertors=convertors, + context_param_name=context_param_name, + pretty_exceptions_short=pretty_exceptions_short, + ), + params=params, # type: ignore + help=use_help, + epilog=command_info.epilog, + short_help=command_info.short_help, + options_metavar=command_info.options_metavar, + add_help_option=command_info.add_help_option, + no_args_is_help=command_info.no_args_is_help, + hidden=command_info.hidden, + deprecated=command_info.deprecated, + rich_markup_mode=rich_markup_mode, + # Rich settings + rich_help_panel=command_info.rich_help_panel, + ) + return command + + +def determine_type_convertor(type_: Any) -> Callable[[Any], Any] | None: + convertor: Callable[[Any], Any] | None = None + if lenient_issubclass(type_, Path): + convertor = param_path_convertor + if lenient_issubclass(type_, Enum): + convertor = generate_enum_convertor(type_) + return convertor + + +def param_path_convertor(value: str | None = None) -> Path | None: + if value is not None: + # allow returning any subclass of Path created by an annotated parser without converting + # it back to a Path + return value if isinstance(value, Path) else Path(value) + return None + + +def generate_enum_convertor(enum: type[Enum]) -> Callable[[Any], Any]: + val_map = {str(val.value): val for val in enum} + + def convertor(value: Any) -> Any: + if value is not None: + val = str(value) + if val in val_map: + key = val_map[val] + return enum(key) + + return convertor + + +def generate_list_convertor( + convertor: Callable[[Any], Any] | None, default_value: Any | None +) -> Callable[[Sequence[Any] | None], list[Any] | None]: + def internal_convertor(value: Sequence[Any] | None) -> list[Any] | None: + if (value is None) or (default_value is None and len(value) == 0): + return None + return [convertor(v) if convertor else v for v in value] + + return internal_convertor + + +def generate_tuple_convertor( + types: Sequence[Any], +) -> Callable[[tuple[Any, ...] | None], tuple[Any, ...] | None]: + convertors = [determine_type_convertor(type_) for type_ in types] + + def internal_convertor( + param_args: tuple[Any, ...] | None, + ) -> tuple[Any, ...] | None: + if param_args is None: + return None + return tuple( + convertor(arg) if convertor else arg + for (convertor, arg) in zip(convertors, param_args, strict=False) + ) + + return internal_convertor + + +def get_callback( + *, + callback: Callable[..., Any] | None = None, + params: Sequence[click.Parameter] = [], + convertors: dict[str, Callable[[str], Any]] | None = None, + context_param_name: str | None = None, + pretty_exceptions_short: bool, +) -> Callable[..., Any] | None: + use_convertors = convertors or {} + if not callback: + return None + parameters = get_params_from_function(callback) + use_params: dict[str, Any] = {} + for param_name in parameters: + use_params[param_name] = None + for param in params: + if param.name: + use_params[param.name] = param.default + + def wrapper(**kwargs: Any) -> Any: + _rich_traceback_guard = pretty_exceptions_short # noqa: F841 + for k, v in kwargs.items(): + if k in use_convertors: + use_params[k] = use_convertors[k](v) + else: + use_params[k] = v + if context_param_name: + use_params[context_param_name] = click.get_current_context() + return callback(**use_params) + + update_wrapper(wrapper, callback) + return wrapper + + +def get_click_type( + *, annotation: Any, parameter_info: ParameterInfo +) -> click.ParamType: + if parameter_info.click_type is not None: + return parameter_info.click_type + + elif parameter_info.parser is not None: + return click.types.FuncParamType(parameter_info.parser) + + elif annotation is str: + return click.STRING + elif annotation is int: + if parameter_info.min is not None or parameter_info.max is not None: + min_ = None + max_ = None + if parameter_info.min is not None: + min_ = int(parameter_info.min) + if parameter_info.max is not None: + max_ = int(parameter_info.max) + return click.IntRange(min=min_, max=max_, clamp=parameter_info.clamp) + else: + return click.INT + elif annotation is float: + if parameter_info.min is not None or parameter_info.max is not None: + return click.FloatRange( + min=parameter_info.min, + max=parameter_info.max, + clamp=parameter_info.clamp, + ) + else: + return click.FLOAT + elif annotation is bool: + return click.BOOL + elif annotation == UUID: + return click.UUID + elif annotation == datetime: + return click.DateTime(formats=parameter_info.formats) + elif ( + annotation == Path + or parameter_info.allow_dash + or parameter_info.path_type + or parameter_info.resolve_path + ): + return TyperPath( + exists=parameter_info.exists, + file_okay=parameter_info.file_okay, + dir_okay=parameter_info.dir_okay, + writable=parameter_info.writable, + readable=parameter_info.readable, + resolve_path=parameter_info.resolve_path, + allow_dash=parameter_info.allow_dash, + path_type=parameter_info.path_type, + ) + elif lenient_issubclass(annotation, FileTextWrite): + return click.File( + mode=parameter_info.mode or "w", + encoding=parameter_info.encoding, + errors=parameter_info.errors, + lazy=parameter_info.lazy, + atomic=parameter_info.atomic, + ) + elif lenient_issubclass(annotation, FileText): + return click.File( + mode=parameter_info.mode or "r", + encoding=parameter_info.encoding, + errors=parameter_info.errors, + lazy=parameter_info.lazy, + atomic=parameter_info.atomic, + ) + elif lenient_issubclass(annotation, FileBinaryRead): + return click.File( + mode=parameter_info.mode or "rb", + encoding=parameter_info.encoding, + errors=parameter_info.errors, + lazy=parameter_info.lazy, + atomic=parameter_info.atomic, + ) + elif lenient_issubclass(annotation, FileBinaryWrite): + return click.File( + mode=parameter_info.mode or "wb", + encoding=parameter_info.encoding, + errors=parameter_info.errors, + lazy=parameter_info.lazy, + atomic=parameter_info.atomic, + ) + elif lenient_issubclass(annotation, Enum): + # The custom TyperChoice is only needed for Click < 8.2.0, to parse the + # command line values matching them to the enum values. Click 8.2.0 added + # support for enum values but reading enum names. + # Passing here the list of enum values (instead of just the enum) accounts for + # Click < 8.2.0. + return TyperChoice( + [item.value for item in annotation], + case_sensitive=parameter_info.case_sensitive, + ) + elif is_literal_type(annotation): + return click.Choice( + literal_values(annotation), + case_sensitive=parameter_info.case_sensitive, + ) + raise RuntimeError(f"Type not yet supported: {annotation}") # pragma: no cover + + +def lenient_issubclass(cls: Any, class_or_tuple: AnyType | tuple[AnyType, ...]) -> bool: + return isinstance(cls, type) and issubclass(cls, class_or_tuple) + + +def get_click_param( + param: ParamMeta, +) -> tuple[click.Argument | click.Option, Any]: + # First, find out what will be: + # * ParamInfo (ArgumentInfo or OptionInfo) + # * default_value + # * required + default_value = None + required = False + if isinstance(param.default, ParameterInfo): + parameter_info = param.default + if parameter_info.default == Required: + required = True + else: + default_value = parameter_info.default + elif param.default == Required or param.default is param.empty: + required = True + parameter_info = ArgumentInfo() + else: + default_value = param.default + parameter_info = OptionInfo() + annotation: Any + if param.annotation is not param.empty: + annotation = param.annotation + else: + annotation = str + main_type = annotation + is_list = False + is_tuple = False + parameter_type: Any = None + is_flag = None + origin = get_origin(main_type) + + if origin is not None: + # Handle SomeType | None and Optional[SomeType] + if is_union(origin): + types = [] + for type_ in get_args(main_type): + if type_ is NoneType: + continue + types.append(type_) + assert len(types) == 1, "Typer Currently doesn't support Union types" + main_type = types[0] + origin = get_origin(main_type) + # Handle Tuples and Lists + if lenient_issubclass(origin, list): + main_type = get_args(main_type)[0] + assert not get_origin(main_type), ( + "List types with complex sub-types are not currently supported" + ) + is_list = True + elif lenient_issubclass(origin, tuple): + types = [] + for type_ in get_args(main_type): + assert not get_origin(type_), ( + "Tuple types with complex sub-types are not currently supported" + ) + types.append( + get_click_type(annotation=type_, parameter_info=parameter_info) + ) + parameter_type = tuple(types) + is_tuple = True + if parameter_type is None: + parameter_type = get_click_type( + annotation=main_type, parameter_info=parameter_info + ) + convertor = determine_type_convertor(main_type) + if is_list: + convertor = generate_list_convertor( + convertor=convertor, default_value=default_value + ) + if is_tuple: + convertor = generate_tuple_convertor(get_args(main_type)) + if isinstance(parameter_info, OptionInfo): + if main_type is bool: + is_flag = True + # Click doesn't accept a flag of type bool, only None, and then it sets it + # to bool internally + parameter_type = None + default_option_name = get_command_name(param.name) + if is_flag: + default_option_declaration = ( + f"--{default_option_name}/--no-{default_option_name}" + ) + else: + default_option_declaration = f"--{default_option_name}" + param_decls = [param.name] + if parameter_info.param_decls: + param_decls.extend(parameter_info.param_decls) + else: + param_decls.append(default_option_declaration) + return ( + TyperOption( + # Option + param_decls=param_decls, + show_default=parameter_info.show_default, + prompt=parameter_info.prompt, + confirmation_prompt=parameter_info.confirmation_prompt, + prompt_required=parameter_info.prompt_required, + hide_input=parameter_info.hide_input, + is_flag=is_flag, + multiple=is_list, + count=parameter_info.count, + allow_from_autoenv=parameter_info.allow_from_autoenv, + type=parameter_type, + help=parameter_info.help, + hidden=parameter_info.hidden, + show_choices=parameter_info.show_choices, + show_envvar=parameter_info.show_envvar, + # Parameter + required=required, + default=default_value, + callback=get_param_callback( + callback=parameter_info.callback, convertor=convertor + ), + metavar=parameter_info.metavar, + expose_value=parameter_info.expose_value, + is_eager=parameter_info.is_eager, + envvar=parameter_info.envvar, + shell_complete=parameter_info.shell_complete, + autocompletion=get_param_completion(parameter_info.autocompletion), + # Rich settings + rich_help_panel=parameter_info.rich_help_panel, + ), + convertor, + ) + elif isinstance(parameter_info, ArgumentInfo): + param_decls = [param.name] + nargs = None + if is_list: + nargs = -1 + return ( + TyperArgument( + # Argument + param_decls=param_decls, + type=parameter_type, + required=required, + nargs=nargs, + # TyperArgument + show_default=parameter_info.show_default, + show_choices=parameter_info.show_choices, + show_envvar=parameter_info.show_envvar, + help=parameter_info.help, + hidden=parameter_info.hidden, + # Parameter + default=default_value, + callback=get_param_callback( + callback=parameter_info.callback, convertor=convertor + ), + metavar=parameter_info.metavar, + expose_value=parameter_info.expose_value, + is_eager=parameter_info.is_eager, + envvar=parameter_info.envvar, + shell_complete=parameter_info.shell_complete, + autocompletion=get_param_completion(parameter_info.autocompletion), + # Rich settings + rich_help_panel=parameter_info.rich_help_panel, + ), + convertor, + ) + raise AssertionError("A click.Parameter should be returned") # pragma: no cover + + +def get_param_callback( + *, + callback: Callable[..., Any] | None = None, + convertor: Callable[..., Any] | None = None, +) -> Callable[..., Any] | None: + if not callback: + return None + parameters = get_params_from_function(callback) + ctx_name = None + click_param_name = None + value_name = None + untyped_names: list[str] = [] + for param_name, param_sig in parameters.items(): + if lenient_issubclass(param_sig.annotation, click.Context): + ctx_name = param_name + elif lenient_issubclass(param_sig.annotation, click.Parameter): + click_param_name = param_name + else: + untyped_names.append(param_name) + # Extract value param name first + if untyped_names: + value_name = untyped_names.pop() + # If context and Click param were not typed (old/Click callback style) extract them + if untyped_names: + if ctx_name is None: + ctx_name = untyped_names.pop(0) + if click_param_name is None: + if untyped_names: + click_param_name = untyped_names.pop(0) + if untyped_names: + raise click.ClickException( + "Too many CLI parameter callback function parameters" + ) + + def wrapper(ctx: click.Context, param: click.Parameter, value: Any) -> Any: + use_params: dict[str, Any] = {} + if ctx_name: + use_params[ctx_name] = ctx + if click_param_name: + use_params[click_param_name] = param + if value_name: + if convertor: + use_value = convertor(value) + else: + use_value = value + use_params[value_name] = use_value + return callback(**use_params) + + update_wrapper(wrapper, callback) + return wrapper + + +def get_param_completion( + callback: Callable[..., Any] | None = None, +) -> Callable[..., Any] | None: + if not callback: + return None + parameters = get_params_from_function(callback) + ctx_name = None + args_name = None + incomplete_name = None + unassigned_params = list(parameters.values()) + for param_sig in unassigned_params[:]: + origin = get_origin(param_sig.annotation) + if lenient_issubclass(param_sig.annotation, click.Context): + ctx_name = param_sig.name + unassigned_params.remove(param_sig) + elif lenient_issubclass(origin, list): + args_name = param_sig.name + unassigned_params.remove(param_sig) + elif lenient_issubclass(param_sig.annotation, str): + incomplete_name = param_sig.name + unassigned_params.remove(param_sig) + # If there are still unassigned parameters (not typed), extract by name + for param_sig in unassigned_params[:]: + if ctx_name is None and param_sig.name == "ctx": + ctx_name = param_sig.name + unassigned_params.remove(param_sig) + elif args_name is None and param_sig.name == "args": + args_name = param_sig.name + unassigned_params.remove(param_sig) + elif incomplete_name is None and param_sig.name == "incomplete": + incomplete_name = param_sig.name + unassigned_params.remove(param_sig) + # Extract value param name first + if unassigned_params: + show_params = " ".join([param.name for param in unassigned_params]) + raise click.ClickException( + f"Invalid autocompletion callback parameters: {show_params}" + ) + + def wrapper(ctx: click.Context, args: list[str], incomplete: str | None) -> Any: + use_params: dict[str, Any] = {} + if ctx_name: + use_params[ctx_name] = ctx + if args_name: + use_params[args_name] = args + if incomplete_name: + use_params[incomplete_name] = incomplete + return callback(**use_params) + + update_wrapper(wrapper, callback) + return wrapper + + +def run( + function: Annotated[ + Callable[..., Any], + Doc( + """ + The function that should power this CLI application. + """ + ), + ], +) -> None: + """ + This function converts a given function to a CLI application with `Typer()` and executes it. + + ## Example + + ```python + import typer + + def main(name: str): + print(f"Hello {name}") + + if __name__ == "__main__": + typer.run(main) + ``` + """ + app = Typer(add_completion=False) + app.command()(function) + app() + + +def _is_macos() -> bool: + return platform.system() == "Darwin" + + +def _is_linux_or_bsd() -> bool: + if platform.system() == "Linux": + return True + + return "BSD" in platform.system() + + +def launch( + url: Annotated[ + str, + Doc( + """ + URL or filename of the thing to launch. + """ + ), + ], + wait: Annotated[ + bool, + Doc( + """ + Wait for the program to exit before returning. This only works if the launched program blocks. + In particular, `xdg-open` on Linux does not block. + """ + ), + ] = False, + locate: Annotated[ + bool, + Doc( + """ + If this is set to `True`, then instead of launching the application associated with the URL, it will attempt to + launch a file manager with the file located. This might have weird effects if the URL does not point to the filesystem. + """ + ), + ] = False, +) -> int: + """ + This function launches the given URL (or filename) in the default + viewer application for this file type. If this is an executable, it + might launch the executable in a new session. The return value is + the exit code of the launched application. Usually, `0` indicates + success. + + This function handles url in different operating systems separately: + - On macOS (Darwin), it uses the `open` command. + - On Linux and BSD, it uses `xdg-open` if available. + - On Windows (and other OSes), it uses the standard webbrowser module. + + The function avoids, when possible, using the webbrowser module on Linux and macOS + to prevent spammy terminal messages from some browsers (e.g., Chrome). + + ## Examples + ```python + import typer + + typer.launch("https://typer.tiangolo.com/") + ``` + + ```python + import typer + + typer.launch("/my/downloaded/file", locate=True) + ``` + """ + + if url.startswith("http://") or url.startswith("https://"): + if _is_macos(): + return subprocess.Popen( + ["open", url], stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT + ).wait() + + has_xdg_open = _is_linux_or_bsd() and shutil.which("xdg-open") is not None + + if has_xdg_open: + return subprocess.Popen( + ["xdg-open", url], stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT + ).wait() + + import webbrowser + + webbrowser.open(url) + + return 0 + + else: + return click.launch(url) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/typer/models.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/typer/models.py new file mode 100644 index 0000000000000000000000000000000000000000..3285a96a2433176a22c11c2402116e5f7562218e --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/typer/models.py @@ -0,0 +1,651 @@ +import inspect +import io +from collections.abc import Callable, Sequence +from typing import ( + TYPE_CHECKING, + Any, + Optional, + TypeVar, +) + +import click +import click.shell_completion + +if TYPE_CHECKING: # pragma: no cover + from .core import TyperCommand, TyperGroup + from .main import Typer + + +NoneType = type(None) + +AnyType = type[Any] + +Required = ... + + +class Context(click.Context): + """ + The [`Context`](https://click.palletsprojects.com/en/stable/api/#click.Context) has some additional data about the current execution of your program. + When declaring it in a [callback](https://typer.tiangolo.com/tutorial/options/callback-and-context/) function, + you can access this additional information. + """ + + pass + + +class FileText(io.TextIOWrapper): + """ + Gives you a file-like object for reading text, and you will get a `str` data from it. + The default mode of this class is `mode="r"`. + + **Example** + + ```python + from typing import Annotated + + import typer + + app = typer.Typer() + + @app.command() + def main(config: Annotated[typer.FileText, typer.Option()]): + for line in config: + print(f"Config line: {line}") + + if __name__ == "__main__": + app() + ``` + """ + + pass + + +class FileTextWrite(FileText): + """ + You can use this class for writing text. Alternatively, you can use `FileText` with `mode="w"`. + The default mode of this class is `mode="w"`. + + **Example** + + ```python + from typing import Annotated + + import typer + + app = typer.Typer() + + @app.command() + def main(config: Annotated[typer.FileTextWrite, typer.Option()]): + config.write("Some config written by the app") + print("Config written") + + if __name__ == "__main__": + app() + ``` + """ + + pass + + +class FileBinaryRead(io.BufferedReader): + """ + You can use this class to read binary data, receiving `bytes`. + The default mode of this class is `mode="rb"`. + It is useful for reading binary files like images: + + **Example** + + ```python + from typing import Annotated + + import typer + + app = typer.Typer() + + @app.command() + def main(file: Annotated[typer.FileBinaryRead, typer.Option()]): + processed_total = 0 + for bytes_chunk in file: + # Process the bytes in bytes_chunk + processed_total += len(bytes_chunk) + print(f"Processed bytes total: {processed_total}") + + if __name__ == "__main__": + app() + ``` + """ + + pass + + +class FileBinaryWrite(io.BufferedWriter): + """ + You can use this class to write binary data: you pass `bytes` to it instead of strings. + The default mode of this class is `mode="wb"`. + It is useful for writing binary files like images: + + **Example** + + ```python + from typing import Annotated + + import typer + + app = typer.Typer() + + @app.command() + def main(file: Annotated[typer.FileBinaryWrite, typer.Option()]): + first_line_str = "some settings\\n" + # You cannot write str directly to a binary file; encode it first + first_line_bytes = first_line_str.encode("utf-8") + # Then you can write the bytes + file.write(first_line_bytes) + # This is already bytes, it starts with b" + second_line = b"la cig\xc3\xbce\xc3\xb1a trae al ni\xc3\xb1o" + file.write(second_line) + print("Binary file written") + + if __name__ == "__main__": + app() + ``` + """ + + pass + + +class CallbackParam(click.Parameter): + """ + In a callback function, you can declare a function parameter with type `CallbackParam` + to access the specific Click [`Parameter`](https://click.palletsprojects.com/en/stable/api/#click.Parameter) object. + """ + + pass + + +class DefaultPlaceholder: + """ + You shouldn't use this class directly. + + It's used internally to recognize when a default value has been overwritten, even + if the new value is `None`. + """ + + def __init__(self, value: Any): + self.value = value + + def __bool__(self) -> bool: + return bool(self.value) + + +DefaultType = TypeVar("DefaultType") + +CommandFunctionType = TypeVar("CommandFunctionType", bound=Callable[..., Any]) + + +def Default(value: DefaultType) -> DefaultType: + """ + You shouldn't use this function directly. + + It's used internally to recognize when a default value has been overwritten, even + if the new value is `None`. + """ + return DefaultPlaceholder(value) # type: ignore + + +class CommandInfo: + def __init__( + self, + name: str | None = None, + *, + cls: type["TyperCommand"] | None = None, + context_settings: dict[Any, Any] | None = None, + callback: Callable[..., Any] | None = None, + help: str | None = None, + epilog: str | None = None, + short_help: str | None = None, + options_metavar: str = "[OPTIONS]", + add_help_option: bool = True, + no_args_is_help: bool = False, + hidden: bool = False, + deprecated: bool = False, + # Rich settings + rich_help_panel: str | None = None, + ): + self.name = name + self.cls = cls + self.context_settings = context_settings + self.callback = callback + self.help = help + self.epilog = epilog + self.short_help = short_help + self.options_metavar = options_metavar + self.add_help_option = add_help_option + self.no_args_is_help = no_args_is_help + self.hidden = hidden + self.deprecated = deprecated + # Rich settings + self.rich_help_panel = rich_help_panel + + +class TyperInfo: + def __init__( + self, + typer_instance: Optional["Typer"] = Default(None), + *, + name: str | None = Default(None), + cls: type["TyperGroup"] | None = Default(None), + invoke_without_command: bool = Default(False), + no_args_is_help: bool = Default(False), + subcommand_metavar: str | None = Default(None), + chain: bool = Default(False), + result_callback: Callable[..., Any] | None = Default(None), + # Command + context_settings: dict[Any, Any] | None = Default(None), + callback: Callable[..., Any] | None = Default(None), + help: str | None = Default(None), + epilog: str | None = Default(None), + short_help: str | None = Default(None), + options_metavar: str = Default("[OPTIONS]"), + add_help_option: bool = Default(True), + hidden: bool = Default(False), + deprecated: bool = Default(False), + # Rich settings + rich_help_panel: str | None = Default(None), + ): + self.typer_instance = typer_instance + self.name = name + self.cls = cls + self.invoke_without_command = invoke_without_command + self.no_args_is_help = no_args_is_help + self.subcommand_metavar = subcommand_metavar + self.chain = chain + self.result_callback = result_callback + self.context_settings = context_settings + self.callback = callback + self.help = help + self.epilog = epilog + self.short_help = short_help + self.options_metavar = options_metavar + self.add_help_option = add_help_option + self.hidden = hidden + self.deprecated = deprecated + self.rich_help_panel = rich_help_panel + + +class ParameterInfo: + def __init__( + self, + *, + default: Any | None = None, + param_decls: Sequence[str] | None = None, + callback: Callable[..., Any] | None = None, + metavar: str | None = None, + expose_value: bool = True, + is_eager: bool = False, + envvar: str | list[str] | None = None, + # Note that shell_complete is not fully supported and will be removed in future versions + # TODO: Remove shell_complete in a future version (after 0.16.0) + shell_complete: Callable[ + [click.Context, click.Parameter, str], + list["click.shell_completion.CompletionItem"] | list[str], + ] + | None = None, + autocompletion: Callable[..., Any] | None = None, + default_factory: Callable[[], Any] | None = None, + # Custom type + parser: Callable[[str], Any] | None = None, + click_type: click.ParamType | None = None, + # TyperArgument + show_default: bool | str = True, + show_choices: bool = True, + show_envvar: bool = True, + help: str | None = None, + hidden: bool = False, + # Choice + case_sensitive: bool = True, + # Numbers + min: int | float | None = None, + max: int | float | None = None, + clamp: bool = False, + # DateTime + formats: list[str] | None = None, + # File + mode: str | None = None, + encoding: str | None = None, + errors: str | None = "strict", + lazy: bool | None = None, + atomic: bool = False, + # Path + exists: bool = False, + file_okay: bool = True, + dir_okay: bool = True, + writable: bool = False, + readable: bool = True, + resolve_path: bool = False, + allow_dash: bool = False, + path_type: None | type[str] | type[bytes] = None, + # Rich settings + rich_help_panel: str | None = None, + ): + # Check if user has provided multiple custom parsers + if parser and click_type: + raise ValueError( + "Multiple custom type parsers provided. " + "`parser` and `click_type` may not both be provided." + ) + + self.default = default + self.param_decls = param_decls + self.callback = callback + self.metavar = metavar + self.expose_value = expose_value + self.is_eager = is_eager + self.envvar = envvar + self.shell_complete = shell_complete + self.autocompletion = autocompletion + self.default_factory = default_factory + # Custom type + self.parser = parser + self.click_type = click_type + # TyperArgument + self.show_default = show_default + self.show_choices = show_choices + self.show_envvar = show_envvar + self.help = help + self.hidden = hidden + # Choice + self.case_sensitive = case_sensitive + # Numbers + self.min = min + self.max = max + self.clamp = clamp + # DateTime + self.formats = formats + # File + self.mode = mode + self.encoding = encoding + self.errors = errors + self.lazy = lazy + self.atomic = atomic + # Path + self.exists = exists + self.file_okay = file_okay + self.dir_okay = dir_okay + self.writable = writable + self.readable = readable + self.resolve_path = resolve_path + self.allow_dash = allow_dash + self.path_type = path_type + # Rich settings + self.rich_help_panel = rich_help_panel + + +class OptionInfo(ParameterInfo): + def __init__( + self, + *, + # ParameterInfo + default: Any | None = None, + param_decls: Sequence[str] | None = None, + callback: Callable[..., Any] | None = None, + metavar: str | None = None, + expose_value: bool = True, + is_eager: bool = False, + envvar: str | list[str] | None = None, + # Note that shell_complete is not fully supported and will be removed in future versions + # TODO: Remove shell_complete in a future version (after 0.16.0) + shell_complete: Callable[ + [click.Context, click.Parameter, str], + list["click.shell_completion.CompletionItem"] | list[str], + ] + | None = None, + autocompletion: Callable[..., Any] | None = None, + default_factory: Callable[[], Any] | None = None, + # Custom type + parser: Callable[[str], Any] | None = None, + click_type: click.ParamType | None = None, + # Option + show_default: bool | str = True, + prompt: bool | str = False, + confirmation_prompt: bool = False, + prompt_required: bool = True, + hide_input: bool = False, + # TODO: remove is_flag and flag_value in a future release + is_flag: bool | None = None, + flag_value: Any | None = None, + count: bool = False, + allow_from_autoenv: bool = True, + help: str | None = None, + hidden: bool = False, + show_choices: bool = True, + show_envvar: bool = True, + # Choice + case_sensitive: bool = True, + # Numbers + min: int | float | None = None, + max: int | float | None = None, + clamp: bool = False, + # DateTime + formats: list[str] | None = None, + # File + mode: str | None = None, + encoding: str | None = None, + errors: str | None = "strict", + lazy: bool | None = None, + atomic: bool = False, + # Path + exists: bool = False, + file_okay: bool = True, + dir_okay: bool = True, + writable: bool = False, + readable: bool = True, + resolve_path: bool = False, + allow_dash: bool = False, + path_type: None | type[str] | type[bytes] = None, + # Rich settings + rich_help_panel: str | None = None, + ): + super().__init__( + default=default, + param_decls=param_decls, + callback=callback, + metavar=metavar, + expose_value=expose_value, + is_eager=is_eager, + envvar=envvar, + shell_complete=shell_complete, + autocompletion=autocompletion, + default_factory=default_factory, + # Custom type + parser=parser, + click_type=click_type, + # TyperArgument + show_default=show_default, + show_choices=show_choices, + show_envvar=show_envvar, + help=help, + hidden=hidden, + # Choice + case_sensitive=case_sensitive, + # Numbers + min=min, + max=max, + clamp=clamp, + # DateTime + formats=formats, + # File + mode=mode, + encoding=encoding, + errors=errors, + lazy=lazy, + atomic=atomic, + # Path + exists=exists, + file_okay=file_okay, + dir_okay=dir_okay, + writable=writable, + readable=readable, + resolve_path=resolve_path, + allow_dash=allow_dash, + path_type=path_type, + # Rich settings + rich_help_panel=rich_help_panel, + ) + if is_flag is not None or flag_value is not None: + import warnings + + warnings.warn( + "The 'is_flag' and 'flag_value' parameters are not supported by Typer " + "and will be removed entirely in a future release.", + DeprecationWarning, + stacklevel=2, + ) + self.prompt = prompt + self.confirmation_prompt = confirmation_prompt + self.prompt_required = prompt_required + self.hide_input = hide_input + self.count = count + self.allow_from_autoenv = allow_from_autoenv + + +class ArgumentInfo(ParameterInfo): + def __init__( + self, + *, + # ParameterInfo + default: Any | None = None, + param_decls: Sequence[str] | None = None, + callback: Callable[..., Any] | None = None, + metavar: str | None = None, + expose_value: bool = True, + is_eager: bool = False, + envvar: str | list[str] | None = None, + # Note that shell_complete is not fully supported and will be removed in future versions + # TODO: Remove shell_complete in a future version (after 0.16.0) + shell_complete: Callable[ + [click.Context, click.Parameter, str], + list["click.shell_completion.CompletionItem"] | list[str], + ] + | None = None, + autocompletion: Callable[..., Any] | None = None, + default_factory: Callable[[], Any] | None = None, + # Custom type + parser: Callable[[str], Any] | None = None, + click_type: click.ParamType | None = None, + # TyperArgument + show_default: bool | str = True, + show_choices: bool = True, + show_envvar: bool = True, + help: str | None = None, + hidden: bool = False, + # Choice + case_sensitive: bool = True, + # Numbers + min: int | float | None = None, + max: int | float | None = None, + clamp: bool = False, + # DateTime + formats: list[str] | None = None, + # File + mode: str | None = None, + encoding: str | None = None, + errors: str | None = "strict", + lazy: bool | None = None, + atomic: bool = False, + # Path + exists: bool = False, + file_okay: bool = True, + dir_okay: bool = True, + writable: bool = False, + readable: bool = True, + resolve_path: bool = False, + allow_dash: bool = False, + path_type: None | type[str] | type[bytes] = None, + # Rich settings + rich_help_panel: str | None = None, + ): + super().__init__( + default=default, + param_decls=param_decls, + callback=callback, + metavar=metavar, + expose_value=expose_value, + is_eager=is_eager, + envvar=envvar, + shell_complete=shell_complete, + autocompletion=autocompletion, + default_factory=default_factory, + # Custom type + parser=parser, + click_type=click_type, + # TyperArgument + show_default=show_default, + show_choices=show_choices, + show_envvar=show_envvar, + help=help, + hidden=hidden, + # Choice + case_sensitive=case_sensitive, + # Numbers + min=min, + max=max, + clamp=clamp, + # DateTime + formats=formats, + # File + mode=mode, + encoding=encoding, + errors=errors, + lazy=lazy, + atomic=atomic, + # Path + exists=exists, + file_okay=file_okay, + dir_okay=dir_okay, + writable=writable, + readable=readable, + resolve_path=resolve_path, + allow_dash=allow_dash, + path_type=path_type, + # Rich settings + rich_help_panel=rich_help_panel, + ) + + +class ParamMeta: + empty = inspect.Parameter.empty + + def __init__( + self, + *, + name: str, + default: Any = inspect.Parameter.empty, + annotation: Any = inspect.Parameter.empty, + ) -> None: + self.name = name + self.default = default + self.annotation = annotation + + +class DeveloperExceptionConfig: + def __init__( + self, + *, + pretty_exceptions_enable: bool = True, + pretty_exceptions_show_locals: bool = True, + pretty_exceptions_short: bool = True, + ) -> None: + self.pretty_exceptions_enable = pretty_exceptions_enable + self.pretty_exceptions_show_locals = pretty_exceptions_show_locals + self.pretty_exceptions_short = pretty_exceptions_short + + +class TyperPath(click.Path): + # Overwrite Click's behaviour to be compatible with Typer's autocompletion system + def shell_complete( + self, ctx: click.Context, param: click.Parameter, incomplete: str + ) -> list[click.shell_completion.CompletionItem]: + """Return an empty list so that the autocompletion functionality + will work properly from the commandline. + """ + return [] diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/typer/params.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/typer/params.py new file mode 100644 index 0000000000000000000000000000000000000000..b325b273c43860f79f598c11e971f60f2c95676f --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/typer/params.py @@ -0,0 +1,1831 @@ +from collections.abc import Callable +from typing import TYPE_CHECKING, Annotated, Any, overload + +import click +from annotated_doc import Doc + +from .models import ArgumentInfo, OptionInfo + +if TYPE_CHECKING: # pragma: no cover + import click.shell_completion + + +# Overload for Option created with custom type 'parser' +@overload +def Option( + # Parameter + default: Any | None = ..., + *param_decls: str, + callback: Callable[..., Any] | None = None, + metavar: str | None = None, + expose_value: bool = True, + is_eager: bool = False, + envvar: str | list[str] | None = None, + # Note that shell_complete is not fully supported and will be removed in future versions + # TODO: Remove shell_complete in a future version (after 0.16.0) + shell_complete: Callable[ + [click.Context, click.Parameter, str], + list["click.shell_completion.CompletionItem"] | list[str], + ] + | None = None, + autocompletion: Callable[..., Any] | None = None, + default_factory: Callable[[], Any] | None = None, + # Custom type + parser: Callable[[str], Any] | None = None, + # Option + show_default: bool | str = True, + prompt: bool | str = False, + confirmation_prompt: bool = False, + prompt_required: bool = True, + hide_input: bool = False, + # TODO: remove is_flag and flag_value in a future release + is_flag: bool | None = None, + flag_value: Any | None = None, + count: bool = False, + allow_from_autoenv: bool = True, + help: str | None = None, + hidden: bool = False, + show_choices: bool = True, + show_envvar: bool = True, + # Choice + case_sensitive: bool = True, + # Numbers + min: int | float | None = None, + max: int | float | None = None, + clamp: bool = False, + # DateTime + formats: list[str] | None = None, + # File + mode: str | None = None, + encoding: str | None = None, + errors: str | None = "strict", + lazy: bool | None = None, + atomic: bool = False, + # Path + exists: bool = False, + file_okay: bool = True, + dir_okay: bool = True, + writable: bool = False, + readable: bool = True, + resolve_path: bool = False, + allow_dash: bool = False, + path_type: None | type[str] | type[bytes] = None, + # Rich settings + rich_help_panel: str | None = None, +) -> Any: ... + + +# Overload for Option created with custom type 'click_type' +@overload +def Option( + # Parameter + default: Any | None = ..., + *param_decls: str, + callback: Callable[..., Any] | None = None, + metavar: str | None = None, + expose_value: bool = True, + is_eager: bool = False, + envvar: str | list[str] | None = None, + # Note that shell_complete is not fully supported and will be removed in future versions + # TODO: Remove shell_complete in a future version (after 0.16.0) + shell_complete: Callable[ + [click.Context, click.Parameter, str], + list["click.shell_completion.CompletionItem"] | list[str], + ] + | None = None, + autocompletion: Callable[..., Any] | None = None, + default_factory: Callable[[], Any] | None = None, + # Custom type + click_type: click.ParamType | None = None, + # Option + show_default: bool | str = True, + prompt: bool | str = False, + confirmation_prompt: bool = False, + prompt_required: bool = True, + hide_input: bool = False, + # TODO: remove is_flag and flag_value in a future release + is_flag: bool | None = None, + flag_value: Any | None = None, + count: bool = False, + allow_from_autoenv: bool = True, + help: str | None = None, + hidden: bool = False, + show_choices: bool = True, + show_envvar: bool = True, + # Choice + case_sensitive: bool = True, + # Numbers + min: int | float | None = None, + max: int | float | None = None, + clamp: bool = False, + # DateTime + formats: list[str] | None = None, + # File + mode: str | None = None, + encoding: str | None = None, + errors: str | None = "strict", + lazy: bool | None = None, + atomic: bool = False, + # Path + exists: bool = False, + file_okay: bool = True, + dir_okay: bool = True, + writable: bool = False, + readable: bool = True, + resolve_path: bool = False, + allow_dash: bool = False, + path_type: None | type[str] | type[bytes] = None, + # Rich settings + rich_help_panel: str | None = None, +) -> Any: ... + + +def Option( + # Parameter + default: Annotated[ + Any | None, + Doc( + """ + Usually, [CLI options](https://typer.tiangolo.com/tutorial/options/) are optional and have a default value, passed on like this: + + **Example** + + ```python + @app.command() + def main(network: str = typer.Option("CNN")): + print(f"Training neural network of type: {network}") + ``` + + Note that this usage is deprecated, and we recommend to use `Annotated` instead: + ``` + @app.command() + def main(network: Annotated[str, typer.Option()] = "CNN"): + print(f"Hello {name}!") + ``` + + You can also use `...` ([Ellipsis](https://docs.python.org/3/library/constants.html#Ellipsis)) as the "default" value to clarify that this is a required CLI option. + """ + ), + ] = ..., + *param_decls: Annotated[ + str, + Doc( + """ + Positional argument that defines how users can call this option on the command line. This may be one or multiple aliases, all strings. + If not defined, Typer will automatically use the function parameter as default name. + See [the tutorial about CLI Option Names](https://typer.tiangolo.com/tutorial/options/name/) for more details. + + **Example** + + ```python + @app.command() + def main(user_name: Annotated[str, typer.Option("--user", "-u", "-x")]): + print(f"Hello {user_name}") + ``` + """ + ), + ], + callback: Annotated[ + Callable[..., Any] | None, + Doc( + """ + Add a callback to this CLI Option, to execute additional logic after its value was received from the terminal. + See [the tutorial about callbacks](https://typer.tiangolo.com/tutorial/options/callback-and-context/) for more details. + + **Example** + + ```python + def name_callback(value: str): + if value != "Deadpool": + raise typer.BadParameter("Only Deadpool is allowed") + return value + + @app.command() + def main(name: Annotated[str, typer.Option(callback=name_callback)]): + print(f"Hello {name}") + ``` + """ + ), + ] = None, + metavar: Annotated[ + str | None, + Doc( + """ + Customize the name displayed in the [help text](https://typer.tiangolo.com/tutorial/options/help/) to represent this CLI option. + Note that this doesn't influence the way the option must be called. + + **Example** + + ```python + @app.command() + def main(user: Annotated[str, typer.Option(metavar="User name")]): + print(f"Hello {user}") + ``` + """ + ), + ] = None, + expose_value: Annotated[ + bool, + Doc( + """ + **Note**: you probably shouldn't use this parameter, it is inherited from Click and supported for compatibility. + + --- + + If this is `True` then the value is passed onwards to the command callback and stored on the context, otherwise it’s skipped. + """ + ), + ] = True, + is_eager: Annotated[ + bool, + Doc( + """ + Mark a CLI Option to be "eager", ensuring it gets processed before other CLI parameters. This could be relevant when there are other parameters with callbacks that could exit the program early. + For more information and an extended example, see the documentation [here](https://typer.tiangolo.com/tutorial/options/version/#fix-with-is_eager). + """ + ), + ] = False, + envvar: Annotated[ + str | list[str] | None, + Doc( + """ + Configure a CLI Option to read its value from an environment variable if it is not provided in the command line. + For more information, see the [documentation on Environment Variables](https://typer.tiangolo.com/tutorial/arguments/envvar/). + + **Example** + + ```python + @app.command() + def main(user: Annotated[str, typer.Option(envvar="ME")]): + print(f"Hello {user}") + ``` + """ + ), + ] = None, + # TODO: Remove shell_complete in a future version (after 0.16.0) + shell_complete: Annotated[ + Callable[ + [click.Context, click.Parameter, str], + list["click.shell_completion.CompletionItem"] | list[str], + ] + | None, + Doc( + """ + **Note**: you probably shouldn't use this parameter, it is inherited from Click and supported for compatibility. + It is however not fully functional, and will likely be removed in future versions. + """ + ), + ] = None, + autocompletion: Annotated[ + Callable[..., Any] | None, + Doc( + """ + Provide a custom function that helps to autocomplete the values of this CLI Option. + See [the tutorial on parameter autocompletion](https://typer.tiangolo.com/tutorial/options-autocompletion) for more details. + + **Example** + + ```python + def complete(): + return ["Me", "Myself", "I"] + + @app.command() + def main(name: Annotated[str, typer.Option(autocompletion=complete)]): + print(f"Hello {name}") + ``` + """ + ), + ] = None, + default_factory: Annotated[ + Callable[[], Any] | None, + Doc( + """ + Provide a custom function that dynamically generates a [default](https://typer.tiangolo.com/tutorial/arguments/default) for this CLI Option. + + **Example** + + ```python + def get_name(): + return random.choice(["Me", "Myself", "I"]) + + @app.command() + def main(name: Annotated[str, typer.Option(default_factory=get_name)]): + print(f"Hello {name}") + ``` + """ + ), + ] = None, + # Custom type + parser: Annotated[ + Callable[[str], Any] | None, + Doc( + """ + Use your own custom types in Typer applications by defining a `parser` function that parses input into your own types: + + **Example** + + ```python + class CustomClass: + def __init__(self, value: str): + self.value = value + + def __str__(self): + return f"" + + def my_parser(value: str): + return CustomClass(value * 2) + + @app.command() + def main(opt: Annotated[CustomClass, typer.Option(parser=my_parser)] = "Foo"): + print(f"--opt is {opt}") + ``` + """ + ), + ] = None, + click_type: Annotated[ + click.ParamType | None, + Doc( + """ + Define this parameter to use a [custom Click type](https://click.palletsprojects.com/en/stable/parameters/#implementing-custom-types) in your Typer applications. + + **Example** + + ```python + class MyClass: + def __init__(self, value: str): + self.value = value + + def __str__(self): + return f"" + + class MyParser(click.ParamType): + name = "MyClass" + + def convert(self, value, param, ctx): + return MyClass(value * 3) + + @app.command() + def main(opt: Annotated[MyClass, typer.Option(click_type=MyParser())] = "Foo"): + print(f"--opt is {opt}") + ``` + """ + ), + ] = None, + # Option + show_default: Annotated[ + bool | str, + Doc( + """ + When set to `False`, don't show the default value of this CLI Option in the [help text](https://typer.tiangolo.com/tutorial/options/help/). + + **Example** + + ```python + @app.command() + def main(name: Annotated[str, typer.Option(show_default=False)] = "Rick"): + print(f"Hello {name}") + ``` + """ + ), + ] = True, + prompt: Annotated[ + bool | str, + Doc( + """ + When set to `True`, a prompt will appear to ask for the value of this CLI Option if it was not provided: + + **Example** + + ```python + @app.command() + def main(name: str, lastname: Annotated[str, typer.Option(prompt=True)]): + print(f"Hello {name} {lastname}") + ``` + """ + ), + ] = False, + confirmation_prompt: Annotated[ + bool, + Doc( + """ + When set to `True`, a user will need to type a prompted value twice (may be useful for passwords etc.). + + **Example** + + ```python + @app.command() + def main(project: Annotated[str, typer.Option(prompt=True, confirmation_prompt=True)]): + print(f"Deleting project {project}") + ``` + """ + ), + ] = False, + prompt_required: Annotated[ + bool, + Doc( + """ + **Note**: you probably shouldn't use this parameter, it is inherited from Click and supported for compatibility. + + --- + + If this is `False` then a prompt is only shown if the option's flag is given without a value. + """ + ), + ] = True, + hide_input: Annotated[ + bool, + Doc( + """ + When you've configured a prompt, for instance for [querying a password](https://typer.tiangolo.com/tutorial/options/password/), + don't show anything on the screen while the user is typing the value. + + **Example** + + ```python + @app.command() + def login( + name: str, + password: Annotated[str, typer.Option(prompt=True, hide_input=True)], + ): + print(f"Hello {name}. Doing something very secure with password.") + ``` + """ + ), + ] = False, + # TODO: remove is_flag and flag_value in a future release + is_flag: Annotated[ + bool | None, + Doc( + """ + **Note**: you probably shouldn't use this parameter, it is inherited from Click and supported for compatibility. + It is however not fully functional, and will likely be removed in future versions. + """ + ), + ] = None, + flag_value: Annotated[ + Any | None, + Doc( + """ + **Note**: you probably shouldn't use this parameter, it is inherited from Click and supported for compatibility. + It is however not fully functional, and will likely be removed in future versions. + """ + ), + ] = None, + count: Annotated[ + bool, + Doc( + """ + Make a CLI Option work as a [counter](https://typer.tiangolo.com/tutorial/parameter-types/number/#counter-cli-options). + The CLI option will have the `int` value representing the number of times the option was used on the command line. + + **Example** + + ```python + @app.command() + def main(verbose: Annotated[int, typer.Option("--verbose", "-v", count=True)] = 0): + print(f"Verbose level is {verbose}") + ``` + """ + ), + ] = False, + allow_from_autoenv: Annotated[ + bool, + Doc( + """ + **Note**: you probably shouldn't use this parameter, it is inherited from Click and supported for compatibility. + + --- + + If this is enabled then the value of this parameter will be pulled from an environment variable in case a prefix is defined on the context. + """ + ), + ] = True, + help: Annotated[ + str | None, + Doc( + """ + Help text for this CLI Option. + See [the tutorial about CLI Options with help](https://typer.tiangolo.com/tutorial/options/help/) for more dedails. + + **Example** + + ```python + @app.command() + def greet(name: Annotated[str, typer.Option(help="Person to greet")] = "Deadpool"): + print(f"Hello {name}") + ``` + """ + ), + ] = None, + hidden: Annotated[ + bool, + Doc( + """ + Hide this CLI Option from [help outputs](https://typer.tiangolo.com/tutorial/options/help). `False` by default. + + **Example** + + ```python + @app.command() + def greet(name: Annotated[str, typer.Option(hidden=True)] = "Deadpool"): + print(f"Hello {name}") + ``` + """ + ), + ] = False, + show_choices: Annotated[ + bool, + Doc( + """ + **Note**: you probably shouldn't use this parameter, it is inherited from Click and supported for compatibility. + + --- + + When set to `False`, this suppresses choices from being displayed inline when `prompt` is used. + """ + ), + ] = True, + show_envvar: Annotated[ + bool, + Doc( + """ + When an ["envvar"](https://typer.tiangolo.com/tutorial/arguments/envvar) is defined, prevent it from showing up in the help text: + + **Example** + + ```python + @app.command() + def main(user: Annotated[str, typer.Option(envvar="ME", show_envvar=False)]): + print(f"Hello {user}") + ``` + """ + ), + ] = True, + # Choice + case_sensitive: Annotated[ + bool, + Doc( + """ + For a CLI Option representing an [Enum (choice)](https://typer.tiangolo.com/tutorial/parameter-types/enum), + you can allow case-insensitive matching with this parameter: + + **Example** + + ```python + from enum import Enum + + class NeuralNetwork(str, Enum): + simple = "simple" + conv = "conv" + lstm = "lstm" + + @app.command() + def main( + network: Annotated[NeuralNetwork, typer.Option(case_sensitive=False)]): + print(f"Training neural network of type: {network.value}") + ``` + + With this setting, "LSTM" or "lstm" will both be valid values that will be resolved to `NeuralNetwork.lstm`. + """ + ), + ] = True, + # Numbers + min: Annotated[ + int | float | None, + Doc( + """ + For a CLI Option representing a [number](https://typer.tiangolo.com/tutorial/parameter-types/number/) (`int` or `float`), + you can define numeric validations with `min` and `max` values: + + **Example** + + ```python + @app.command() + def main( + user: Annotated[str, typer.Argument()], + user_id: Annotated[int, typer.Option(min=1, max=1000)], + ): + print(f"ID for {user} is {user_id}") + ``` + + If the user attempts to input an invalid number, an error will be shown, explaining why the value is invalid. + """ + ), + ] = None, + max: Annotated[ + int | float | None, + Doc( + """ + For a CLI Option representing a [number](https://typer.tiangolo.com/tutorial/parameter-types/number/) (`int` or `float`), + you can define numeric validations with `min` and `max` values: + + **Example** + + ```python + @app.command() + def main( + user: Annotated[str, typer.Argument()], + user_id: Annotated[int, typer.Option(min=1, max=1000)], + ): + print(f"ID for {user} is {user_id}") + ``` + + If the user attempts to input an invalid number, an error will be shown, explaining why the value is invalid. + """ + ), + ] = None, + clamp: Annotated[ + bool, + Doc( + """ + For a CLI Option representing a [number](https://typer.tiangolo.com/tutorial/parameter-types/number/) and that is bounded by using `min` and/or `max`, + you can opt to use the closest minimum or maximum value instead of raising an error when the value is out of bounds. This is done by setting `clamp` to `True`. + + **Example** + + ```python + @app.command() + def main( + user: Annotated[str, typer.Argument()], + user_id: Annotated[int, typer.Option(min=1, max=1000, clamp=True)], + ): + print(f"ID for {user} is {user_id}") + ``` + + If the user attempts to input 3420 for `user_id`, this will internally be converted to `1000`. + """ + ), + ] = False, + # DateTime + formats: Annotated[ + list[str] | None, + Doc( + """ + For a CLI Option representing a [DateTime object](https://typer.tiangolo.com/tutorial/parameter-types/datetime), + you can customize the formats that can be parsed automatically: + + **Example** + + ```python + from datetime import datetime + + @app.command() + def main( + birthday: Annotated[ + datetime, + typer.Option( + formats=["%Y-%m-%d", "%Y-%m-%d %H:%M:%S", "%m/%d/%Y"] + ), + ], + ): + print(f"Birthday defined at: {birthday}") + ``` + """ + ), + ] = None, + # File + mode: Annotated[ + str | None, + Doc( + """ + For a CLI Option representing a [File object](https://typer.tiangolo.com/tutorial/parameter-types/file/), + you can customize the mode to open the file with. If unset, Typer will set a [sensible value by default](https://typer.tiangolo.com/tutorial/parameter-types/file/#advanced-mode). + + **Example** + + ```python + @app.command() + def main(config: Annotated[typer.FileText, typer.Option(mode="a")]): + config.write("This is a single line\\n") + print("Config line written") + ``` + """ + ), + ] = None, + encoding: Annotated[ + str | None, + Doc( + """ + Customize the encoding of this CLI Option represented by a [File object](https://typer.tiangolo.com/tutorial/parameter-types/file/). + + **Example** + + ```python + @app.command() + def main(config: Annotated[typer.FileText, typer.Option(encoding="utf-8")]): + config.write("All the text gets written\\n") + ``` + """ + ), + ] = None, + errors: Annotated[ + str | None, + Doc( + """ + **Note**: you probably shouldn't use this parameter, it is inherited from Click and supported for compatibility. + + --- + + The error handling mode. + """ + ), + ] = "strict", + lazy: Annotated[ + bool | None, + Doc( + """ + For a CLI Option representing a [File object](https://typer.tiangolo.com/tutorial/parameter-types/file/), + by default the file will not be created until you actually start writing to it. + You can change this behaviour by setting this parameter. + By default, it's set to `True` for writing and to `False` for reading. + + **Example** + + ```python + @app.command() + def main(config: Annotated[typer.FileText, typer.Option(mode="a", lazy=False)]): + config.write("This is a single line\\n") + print("Config line written") + ``` + """ + ), + ] = None, + atomic: Annotated[ + bool, + Doc( + """ + For a CLI Option representing a [File object](https://typer.tiangolo.com/tutorial/parameter-types/file/), + you can ensure that all write instructions first go into a temporal file, and are only moved to the final destination after completing + by setting `atomic` to `True`. This can be useful for files with potential concurrent access. + + **Example** + + ```python + @app.command() + def main(config: Annotated[typer.FileText, typer.Option(mode="a", atomic=True)]): + config.write("All the text") + ``` + """ + ), + ] = False, + # Path + exists: Annotated[ + bool, + Doc( + """ + When set to `True` for a [`Path` CLI Option](https://typer.tiangolo.com/tutorial/parameter-types/path/), + additional validation is performed to check that the file or directory exists. If not, the value will be invalid. + + **Example** + + ```python + from pathlib import Path + + @app.command() + def main(config: Annotated[Path, typer.Option(exists=True)]): + text = config.read_text() + print(f"Config file contents: {text}") + ``` + """ + ), + ] = False, + file_okay: Annotated[ + bool, + Doc( + """ + Determine whether or not a [`Path` CLI Option](https://typer.tiangolo.com/tutorial/parameter-types/path/) + is allowed to refer to a file. When this is set to `False`, the application will raise a validation error when a path to a file is given. + + **Example** + + ```python + from pathlib import Path + + @app.command() + def main(config: Annotated[Path, typer.Option(exists=True, file_okay=False)]): + print(f"Directory listing: {[x.name for x in config.iterdir()]}") + ``` + """ + ), + ] = True, + dir_okay: Annotated[ + bool, + Doc( + """ + Determine whether or not a [`Path` CLI Option](https://typer.tiangolo.com/tutorial/parameter-types/path/) + is allowed to refer to a directory. When this is set to `False`, the application will raise a validation error when a path to a directory is given. + + **Example** + + ```python + from pathlib import Path + + @app.command() + def main(config: Annotated[Path, typer.Argument(exists=True, dir_okay=False)]): + text = config.read_text() + print(f"Config file contents: {text}") + ``` + """ + ), + ] = True, + writable: Annotated[ + bool, + Doc( + """ + Whether or not to perform a writable check for this [`Path` CLI Option](https://typer.tiangolo.com/tutorial/parameter-types/path/). + + **Example** + + ```python + from pathlib import Path + + @app.command() + def main(config: Annotated[Path, typer.Option(writable=True)]): + config.write_text("All the text") + ``` + """ + ), + ] = False, + readable: Annotated[ + bool, + Doc( + """ + Whether or not to perform a readable check for this [`Path` CLI Option](https://typer.tiangolo.com/tutorial/parameter-types/path/). + + **Example** + + ```python + from pathlib import Path + + @app.command() + def main(config: Annotated[Path, typer.Option(readable=True)]): + config.read_text("All the text") + ``` + """ + ), + ] = True, + resolve_path: Annotated[ + bool, + Doc( + """ + Whether or not to fully resolve the path of this [`Path` CLI Option](https://typer.tiangolo.com/tutorial/parameter-types/path/), + meaning that the path becomes absolute and symlinks are resolved. + + **Example** + + ```python + from pathlib import Path + + @app.command() + def main(config: Annotated[Path, typer.Option(resolve_path=True)]): + config.read_text("All the text") + ``` + """ + ), + ] = False, + allow_dash: Annotated[ + bool, + Doc( + """ + When set to `True`, a single dash for this [`Path` CLI Option](https://typer.tiangolo.com/tutorial/parameter-types/path/) + would be a valid value, indicating standard streams. This is a more advanced use-case. + """ + ), + ] = False, + path_type: Annotated[ + None | type[str] | type[bytes], + Doc( + """ + A string type that will be used to represent this [`Path` argument](https://typer.tiangolo.com/tutorial/parameter-types/path/). + The default is `None` which means the return value will be either bytes or unicode, depending on what makes most sense given the input data. + This is a more advanced use-case. + """ + ), + ] = None, + # Rich settings + rich_help_panel: Annotated[ + str | None, + Doc( + """ + Set the panel name where you want this CLI Option to be shown in the [help text](https://typer.tiangolo.com/tutorial/arguments/help). + + **Example** + + ```python + @app.command() + def main( + name: Annotated[str, typer.Argument(help="Who to greet")], + age: Annotated[str, typer.Option(help="Their age", rich_help_panel="Data")], + ): + print(f"Hello {name} of age {age}") + ``` + """ + ), + ] = None, +) -> Any: + """ + A [CLI Option](https://typer.tiangolo.com/tutorial/options) is a parameter to your command line application that is called with a single or double dash, something like `--verbose` or `-v`. + + Often, CLI Options are optional, meaning that users can omit them from the command. However, you can set them to be required by using `Annotated` + and omitting a default value. + + ## Example + + ```python + @app.command() + def register( + user: Annotated[str, typer.Argument()], + age: Annotated[int, typer.Option(min=18)], + ): + print(f"User is {user}") + print(f"--age is {age}") + ``` + + Note how in this example, `--age` is a required CLI Option. + """ + return OptionInfo( + # Parameter + default=default, + param_decls=param_decls, + callback=callback, + metavar=metavar, + expose_value=expose_value, + is_eager=is_eager, + envvar=envvar, + shell_complete=shell_complete, + autocompletion=autocompletion, + default_factory=default_factory, + # Custom type + parser=parser, + click_type=click_type, + # Option + show_default=show_default, + prompt=prompt, + confirmation_prompt=confirmation_prompt, + prompt_required=prompt_required, + hide_input=hide_input, + is_flag=is_flag, + flag_value=flag_value, + count=count, + allow_from_autoenv=allow_from_autoenv, + help=help, + hidden=hidden, + show_choices=show_choices, + show_envvar=show_envvar, + # Choice + case_sensitive=case_sensitive, + # Numbers + min=min, + max=max, + clamp=clamp, + # DateTime + formats=formats, + # File + mode=mode, + encoding=encoding, + errors=errors, + lazy=lazy, + atomic=atomic, + # Path + exists=exists, + file_okay=file_okay, + dir_okay=dir_okay, + writable=writable, + readable=readable, + resolve_path=resolve_path, + allow_dash=allow_dash, + path_type=path_type, + # Rich settings + rich_help_panel=rich_help_panel, + ) + + +# Overload for Argument created with custom type 'parser' +@overload +def Argument( + # Parameter + default: Any | None = ..., + *, + callback: Callable[..., Any] | None = None, + metavar: str | None = None, + expose_value: bool = True, + is_eager: bool = False, + envvar: str | list[str] | None = None, + # Note that shell_complete is not fully supported and will be removed in future versions + # TODO: Remove shell_complete in a future version (after 0.16.0) + shell_complete: Callable[ + [click.Context, click.Parameter, str], + list["click.shell_completion.CompletionItem"] | list[str], + ] + | None = None, + autocompletion: Callable[..., Any] | None = None, + default_factory: Callable[[], Any] | None = None, + # Custom type + parser: Callable[[str], Any] | None = None, + # TyperArgument + show_default: bool | str = True, + show_choices: bool = True, + show_envvar: bool = True, + help: str | None = None, + hidden: bool = False, + # Choice + case_sensitive: bool = True, + # Numbers + min: int | float | None = None, + max: int | float | None = None, + clamp: bool = False, + # DateTime + formats: list[str] | None = None, + # File + mode: str | None = None, + encoding: str | None = None, + errors: str | None = "strict", + lazy: bool | None = None, + atomic: bool = False, + # Path + exists: bool = False, + file_okay: bool = True, + dir_okay: bool = True, + writable: bool = False, + readable: bool = True, + resolve_path: bool = False, + allow_dash: bool = False, + path_type: None | type[str] | type[bytes] = None, + # Rich settings + rich_help_panel: str | None = None, +) -> Any: ... + + +# Overload for Argument created with custom type 'click_type' +@overload +def Argument( + # Parameter + default: Any | None = ..., + *, + callback: Callable[..., Any] | None = None, + metavar: str | None = None, + expose_value: bool = True, + is_eager: bool = False, + envvar: str | list[str] | None = None, + # Note that shell_complete is not fully supported and will be removed in future versions + # TODO: Remove shell_complete in a future version (after 0.16.0) + shell_complete: Callable[ + [click.Context, click.Parameter, str], + list["click.shell_completion.CompletionItem"] | list[str], + ] + | None = None, + autocompletion: Callable[..., Any] | None = None, + default_factory: Callable[[], Any] | None = None, + # Custom type + click_type: click.ParamType | None = None, + # TyperArgument + show_default: bool | str = True, + show_choices: bool = True, + show_envvar: bool = True, + help: str | None = None, + hidden: bool = False, + # Choice + case_sensitive: bool = True, + # Numbers + min: int | float | None = None, + max: int | float | None = None, + clamp: bool = False, + # DateTime + formats: list[str] | None = None, + # File + mode: str | None = None, + encoding: str | None = None, + errors: str | None = "strict", + lazy: bool | None = None, + atomic: bool = False, + # Path + exists: bool = False, + file_okay: bool = True, + dir_okay: bool = True, + writable: bool = False, + readable: bool = True, + resolve_path: bool = False, + allow_dash: bool = False, + path_type: None | type[str] | type[bytes] = None, + # Rich settings + rich_help_panel: str | None = None, +) -> Any: ... + + +def Argument( + # Parameter + default: Annotated[ + Any | None, + Doc( + """ + By default, CLI arguments are required. However, by giving them a default value they become [optional](https://typer.tiangolo.com/tutorial/arguments/optional): + + **Example** + + ```python + @app.command() + def main(name: str = typer.Argument("World")): + print(f"Hello {name}!") + ``` + + Note that this usage is deprecated, and we recommend to use `Annotated` instead: + ```python + @app.command() + def main(name: Annotated[str, typer.Argument()] = "World"): + print(f"Hello {name}!") + ``` + """ + ), + ] = ..., + *, + callback: Annotated[ + Callable[..., Any] | None, + Doc( + """ + Add a callback to this CLI Argument, to execute additional logic with the value received from the terminal. + See [the tutorial about callbacks](https://typer.tiangolo.com/tutorial/options/callback-and-context/) for more details. + + **Example** + + ```python + def name_callback(value: str): + if value != "Deadpool": + raise typer.BadParameter("Only Deadpool is allowed") + return value + + @app.command() + def main(name: Annotated[str, typer.Argument(callback=name_callback)]): + print(f"Hello {name}") + ``` + """ + ), + ] = None, + metavar: Annotated[ + str | None, + Doc( + """ + Customize the name displayed in the help text to represent this CLI Argument. + By default, it will be the same name you declared, in uppercase. + See [the tutorial about CLI Arguments with Help](https://typer.tiangolo.com/tutorial/arguments/help/#custom-help-name-metavar) for more details. + + **Example** + + ```python + @app.command() + def main(name: Annotated[str, typer.Argument(metavar="✨username✨")]): + print(f"Hello {name}") + ``` + """ + ), + ] = None, + expose_value: Annotated[ + bool, + Doc( + """ + **Note**: you probably shouldn't use this parameter, it is inherited from Click and supported for compatibility. + + --- + + If this is `True` then the value is passed onwards to the command callback and stored on the context, otherwise it’s skipped. + """ + ), + ] = True, + is_eager: Annotated[ + bool, + Doc( + """ + Set an argument to "eager" to ensure it gets processed before other CLI parameters. This could be relevant when there are other parameters with callbacks that could exit the program early. + For more information and an extended example, see the documentation [here](https://typer.tiangolo.com/tutorial/options/version/#fix-with-is_eager). + """ + ), + ] = False, + envvar: Annotated[ + str | list[str] | None, + Doc( + """ + Configure an argument to read a value from an environment variable if it is not provided in the command line as a CLI argument. + For more information, see the [documentation on Environment Variables](https://typer.tiangolo.com/tutorial/arguments/envvar/). + + **Example** + + ```python + @app.command() + def main(name: Annotated[str, typer.Argument(envvar="ME")]): + print(f"Hello Mr. {name}") + ``` + """ + ), + ] = None, + # TODO: Remove shell_complete in a future version (after 0.16.0) + shell_complete: Annotated[ + Callable[ + [click.Context, click.Parameter, str], + list["click.shell_completion.CompletionItem"] | list[str], + ] + | None, + Doc( + """ + **Note**: you probably shouldn't use this parameter, it is inherited from Click and supported for compatibility. + It is however not fully functional, and will likely be removed in future versions. + """ + ), + ] = None, + autocompletion: Annotated[ + Callable[..., Any] | None, + Doc( + """ + Provide a custom function that helps to autocomplete the values of this CLI Argument. + See [the tutorial on parameter autocompletion](https://typer.tiangolo.com/tutorial/options-autocompletion) for more details. + + **Example** + + ```python + def complete(): + return ["Me", "Myself", "I"] + + @app.command() + def main(name: Annotated[str, typer.Argument(autocompletion=complete)]): + print(f"Hello {name}") + ``` + """ + ), + ] = None, + default_factory: Annotated[ + Callable[[], Any] | None, + Doc( + """ + Provide a custom function that dynamically generates a [default](https://typer.tiangolo.com/tutorial/arguments/default) for this CLI Argument. + + **Example** + + ```python + def get_name(): + return random.choice(["Me", "Myself", "I"]) + + @app.command() + def main(name: Annotated[str, typer.Argument(default_factory=get_name)]): + print(f"Hello {name}") + ``` + """ + ), + ] = None, + # Custom type + parser: Annotated[ + Callable[[str], Any] | None, + Doc( + """ + Use your own custom types in Typer applications by defining a `parser` function that parses input into your own types: + + **Example** + + ```python + class CustomClass: + def __init__(self, value: str): + self.value = value + + def __str__(self): + return f"" + + def my_parser(value: str): + return CustomClass(value * 2) + + @app.command() + def main(arg: Annotated[CustomClass, typer.Argument(parser=my_parser): + print(f"arg is {arg}") + ``` + """ + ), + ] = None, + click_type: Annotated[ + click.ParamType | None, + Doc( + """ + Define this parameter to use a [custom Click type](https://click.palletsprojects.com/en/stable/parameters/#implementing-custom-types) in your Typer applications. + + **Example** + + ```python + class MyClass: + def __init__(self, value: str): + self.value = value + + def __str__(self): + return f"" + + class MyParser(click.ParamType): + name = "MyClass" + + def convert(self, value, param, ctx): + return MyClass(value * 3) + + @app.command() + def main(arg: Annotated[MyClass, typer.Argument(click_type=MyParser())]): + print(f"arg is {arg}") + ``` + """ + ), + ] = None, + # TyperArgument + show_default: Annotated[ + bool | str, + Doc( + """ + When set to `False`, don't show the default value of this CLI Argument in the [help text](https://typer.tiangolo.com/tutorial/arguments/help/). + + **Example** + + ```python + @app.command() + def main(name: Annotated[str, typer.Argument(show_default=False)] = "Rick"): + print(f"Hello {name}") + ``` + """ + ), + ] = True, + show_choices: Annotated[ + bool, + Doc( + """ + **Note**: you probably shouldn't use this parameter, it is inherited from Click and supported for compatibility. + + --- + + When set to `False`, this suppresses choices from being displayed inline when `prompt` is used. + """ + ), + ] = True, + show_envvar: Annotated[ + bool, + Doc( + """ + When an ["envvar"](https://typer.tiangolo.com/tutorial/arguments/envvar) is defined, prevent it from showing up in the help text: + + **Example** + + ```python + @app.command() + def main(name: Annotated[str, typer.Argument(envvar="ME", show_envvar=False)]): + print(f"Hello Mr. {name}") + ``` + """ + ), + ] = True, + help: Annotated[ + str | None, + Doc( + """ + Help text for this CLI Argument. + See [the tutorial about CLI Arguments with help](https://typer.tiangolo.com/tutorial/arguments/help/) for more dedails. + + **Example** + + ```python + @app.command() + def greet(name: Annotated[str, typer.Argument(help="Person to greet")]): + print(f"Hello {name}") + ``` + """ + ), + ] = None, + hidden: Annotated[ + bool, + Doc( + """ + Hide this CLI Argument from [help outputs](https://typer.tiangolo.com/tutorial/arguments/help). `False` by default. + + **Example** + + ```python + @app.command() + def main(name: Annotated[str, typer.Argument(hidden=True)] = "World"): + print(f"Hello {name}") + ``` + """ + ), + ] = False, + # Choice + case_sensitive: Annotated[ + bool, + Doc( + """ + For a CLI Argument representing an [Enum (choice)](https://typer.tiangolo.com/tutorial/parameter-types/enum), + you can allow case-insensitive matching with this parameter: + + **Example** + + ```python + from enum import Enum + + class NeuralNetwork(str, Enum): + simple = "simple" + conv = "conv" + lstm = "lstm" + + @app.command() + def main( + network: Annotated[NeuralNetwork, typer.Argument(case_sensitive=False)]): + print(f"Training neural network of type: {network.value}") + ``` + + With this setting, "LSTM" or "lstm" will both be valid values that will be resolved to `NeuralNetwork.lstm`. + """ + ), + ] = True, + # Numbers + min: Annotated[ + int | float | None, + Doc( + """ + For a CLI Argument representing a [number](https://typer.tiangolo.com/tutorial/parameter-types/number/) (`int` or `float`), + you can define numeric validations with `min` and `max` values: + + **Example** + + ```python + @app.command() + def main( + user: Annotated[str, typer.Argument()], + user_id: Annotated[int, typer.Argument(min=1, max=1000)], + ): + print(f"ID for {user} is {user_id}") + ``` + + If the user attempts to input an invalid number, an error will be shown, explaining why the value is invalid. + """ + ), + ] = None, + max: Annotated[ + int | float | None, + Doc( + """ + For a CLI Argument representing a [number](https://typer.tiangolo.com/tutorial/parameter-types/number/) (`int` or `float`), + you can define numeric validations with `min` and `max` values: + + **Example** + + ```python + @app.command() + def main( + user: Annotated[str, typer.Argument()], + user_id: Annotated[int, typer.Argument(min=1, max=1000)], + ): + print(f"ID for {user} is {user_id}") + ``` + + If the user attempts to input an invalid number, an error will be shown, explaining why the value is invalid. + """ + ), + ] = None, + clamp: Annotated[ + bool, + Doc( + """ + For a CLI Argument representing a [number](https://typer.tiangolo.com/tutorial/parameter-types/number/) and that is bounded by using `min` and/or `max`, + you can opt to use the closest minimum or maximum value instead of raising an error. This is done by setting `clamp` to `True`. + + **Example** + + ```python + @app.command() + def main( + user: Annotated[str, typer.Argument()], + user_id: Annotated[int, typer.Argument(min=1, max=1000, clamp=True)], + ): + print(f"ID for {user} is {user_id}") + ``` + + If the user attempts to input 3420 for `user_id`, this will internally be converted to `1000`. + """ + ), + ] = False, + # DateTime + formats: Annotated[ + list[str] | None, + Doc( + """ + For a CLI Argument representing a [DateTime object](https://typer.tiangolo.com/tutorial/parameter-types/datetime), + you can customize the formats that can be parsed automatically: + + **Example** + + ```python + from datetime import datetime + + @app.command() + def main( + birthday: Annotated[ + datetime, + typer.Argument( + formats=["%Y-%m-%d", "%Y-%m-%d %H:%M:%S", "%m/%d/%Y"] + ), + ], + ): + print(f"Birthday defined at: {birthday}") + ``` + """ + ), + ] = None, + # File + mode: Annotated[ + str | None, + Doc( + """ + For a CLI Argument representing a [File object](https://typer.tiangolo.com/tutorial/parameter-types/file/), + you can customize the mode to open the file with. If unset, Typer will set a [sensible value by default](https://typer.tiangolo.com/tutorial/parameter-types/file/#advanced-mode). + + **Example** + + ```python + @app.command() + def main(config: Annotated[typer.FileText, typer.Argument(mode="a")]): + config.write("This is a single line\\n") + print("Config line written") + ``` + """ + ), + ] = None, + encoding: Annotated[ + str | None, + Doc( + """ + Customize the encoding of this CLI Argument represented by a [File object](https://typer.tiangolo.com/tutorial/parameter-types/file/). + + **Example** + + ```python + @app.command() + def main(config: Annotated[typer.FileText, typer.Argument(encoding="utf-8")]): + config.write("All the text gets written\\n") + ``` + """ + ), + ] = None, + errors: Annotated[ + str | None, + Doc( + """ + **Note**: you probably shouldn't use this parameter, it is inherited from Click and supported for compatibility. + + --- + + The error handling mode. + """ + ), + ] = "strict", + lazy: Annotated[ + bool | None, + Doc( + """ + For a CLI Argument representing a [File object](https://typer.tiangolo.com/tutorial/parameter-types/file/), + by default the file will not be created until you actually start writing to it. + You can change this behaviour by setting this parameter. + By default, it's set to `True` for writing and to `False` for reading. + + **Example** + + ```python + @app.command() + def main(config: Annotated[typer.FileText, typer.Argument(mode="a", lazy=False)]): + config.write("This is a single line\\n") + print("Config line written") + ``` + """ + ), + ] = None, + atomic: Annotated[ + bool, + Doc( + """ + For a CLI Argument representing a [File object](https://typer.tiangolo.com/tutorial/parameter-types/file/), + you can ensure that all write instructions first go into a temporal file, and are only moved to the final destination after completing + by setting `atomic` to `True`. This can be useful for files with potential concurrent access. + + **Example** + + ```python + @app.command() + def main(config: Annotated[typer.FileText, typer.Argument(mode="a", atomic=True)]): + config.write("All the text") + ``` + """ + ), + ] = False, + # Path + exists: Annotated[ + bool, + Doc( + """ + When set to `True` for a [`Path` argument](https://typer.tiangolo.com/tutorial/parameter-types/path/), + additional validation is performed to check that the file or directory exists. If not, the value will be invalid. + + **Example** + + ```python + from pathlib import Path + + @app.command() + def main(config: Annotated[Path, typer.Argument(exists=True)]): + text = config.read_text() + print(f"Config file contents: {text}") + ``` + """ + ), + ] = False, + file_okay: Annotated[ + bool, + Doc( + """ + Determine whether or not a [`Path` argument](https://typer.tiangolo.com/tutorial/parameter-types/path/) + is allowed to refer to a file. When this is set to `False`, the application will raise a validation error when a path to a file is given. + + **Example** + + ```python + from pathlib import Path + + @app.command() + def main(config: Annotated[Path, typer.Argument(exists=True, file_okay=False)]): + print(f"Directory listing: {[x.name for x in config.iterdir()]}") + ``` + """ + ), + ] = True, + dir_okay: Annotated[ + bool, + Doc( + """ + Determine whether or not a [`Path` argument](https://typer.tiangolo.com/tutorial/parameter-types/path/) + is allowed to refer to a directory. When this is set to `False`, the application will raise a validation error when a path to a directory is given. + + **Example** + + ```python + from pathlib import Path + + @app.command() + def main(config: Annotated[Path, typer.Argument(exists=True, dir_okay=False)]): + text = config.read_text() + print(f"Config file contents: {text}") + ``` + """ + ), + ] = True, + writable: Annotated[ + bool, + Doc( + """ + Whether or not to perform a writable check for this [`Path` argument](https://typer.tiangolo.com/tutorial/parameter-types/path/). + + **Example** + + ```python + from pathlib import Path + + @app.command() + def main(config: Annotated[Path, typer.Argument(writable=True)]): + config.write_text("All the text") + ``` + """ + ), + ] = False, + readable: Annotated[ + bool, + Doc( + """ + Whether or not to perform a readable check for this [`Path` argument](https://typer.tiangolo.com/tutorial/parameter-types/path/). + + **Example** + + ```python + from pathlib import Path + + @app.command() + def main(config: Annotated[Path, typer.Argument(readable=True)]): + config.read_text("All the text") + ``` + """ + ), + ] = True, + resolve_path: Annotated[ + bool, + Doc( + """ + Whether or not to fully resolve the path of this [`Path` argument](https://typer.tiangolo.com/tutorial/parameter-types/path/), + meaning that the path becomes absolute and symlinks are resolved. + + **Example** + + ```python + from pathlib import Path + + @app.command() + def main(config: Annotated[Path, typer.Argument(resolve_path=True)]): + config.read_text("All the text") + ``` + """ + ), + ] = False, + allow_dash: Annotated[ + bool, + Doc( + """ + When set to `True`, a single dash for this [`Path` argument](https://typer.tiangolo.com/tutorial/parameter-types/path/) + would be a valid value, indicating standard streams. This is a more advanced use-case. + """ + ), + ] = False, + path_type: Annotated[ + None | type[str] | type[bytes], + Doc( + """ + A string type that will be used to represent this [`Path` argument](https://typer.tiangolo.com/tutorial/parameter-types/path/). + The default is `None` which means the return value will be either bytes or unicode, depending on what makes most sense given the input data. + This is a more advanced use-case. + """ + ), + ] = None, + # Rich settings + rich_help_panel: Annotated[ + str | None, + Doc( + """ + Set the panel name where you want this CLI Argument to be shown in the [help text](https://typer.tiangolo.com/tutorial/arguments/help). + + **Example** + + ```python + @app.command() + def main( + name: Annotated[str, typer.Argument(help="Who to greet")], + age: Annotated[str, typer.Option(help="Their age", rich_help_panel="Data")], + ): + print(f"Hello {name} of age {age}") + ``` + """ + ), + ] = None, +) -> Any: + """ + A [CLI Argument](https://typer.tiangolo.com/tutorial/arguments) is a positional parameter to your command line application. + + Often, CLI Arguments are required, meaning that users have to specify them. However, you can set them to be optional by defining a default value: + + ## Example + + ```python + @app.command() + def main(name: Annotated[str, typer.Argument()] = "World"): + print(f"Hello {name}!") + ``` + + Note how in this example, if `name` is not specified on the command line, the application will still execute normally and print "Hello World!". + """ + return ArgumentInfo( + # Parameter + default=default, + # Arguments can only have one param declaration + # it will be generated from the param name + param_decls=None, + callback=callback, + metavar=metavar, + expose_value=expose_value, + is_eager=is_eager, + envvar=envvar, + shell_complete=shell_complete, + autocompletion=autocompletion, + default_factory=default_factory, + # Custom type + parser=parser, + click_type=click_type, + # TyperArgument + show_default=show_default, + show_choices=show_choices, + show_envvar=show_envvar, + help=help, + hidden=hidden, + # Choice + case_sensitive=case_sensitive, + # Numbers + min=min, + max=max, + clamp=clamp, + # DateTime + formats=formats, + # File + mode=mode, + encoding=encoding, + errors=errors, + lazy=lazy, + atomic=atomic, + # Path + exists=exists, + file_okay=file_okay, + dir_okay=dir_okay, + writable=writable, + readable=readable, + resolve_path=resolve_path, + allow_dash=allow_dash, + path_type=path_type, + # Rich settings + rich_help_panel=rich_help_panel, + ) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/typer/py.typed b/miniconda3/envs/ladir/lib/python3.10/site-packages/typer/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/typer/rich_utils.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/typer/rich_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..d85043238c3d47a89cd6d5127fce198c0564f0b7 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/typer/rich_utils.py @@ -0,0 +1,753 @@ +# Extracted and modified from https://github.com/ewels/rich-click + +import inspect +import io +from collections import defaultdict +from collections.abc import Iterable +from gettext import gettext as _ +from os import getenv +from typing import Any, Literal + +import click +from rich import box +from rich.align import Align +from rich.columns import Columns +from rich.console import Console, RenderableType, group +from rich.emoji import Emoji +from rich.highlighter import RegexHighlighter +from rich.markdown import Markdown +from rich.markup import escape +from rich.padding import Padding +from rich.panel import Panel +from rich.table import Table +from rich.text import Text +from rich.theme import Theme +from rich.traceback import Traceback +from typer.models import DeveloperExceptionConfig + +# Default styles +STYLE_OPTION = "bold cyan" +STYLE_SWITCH = "bold green" +STYLE_NEGATIVE_OPTION = "bold magenta" +STYLE_NEGATIVE_SWITCH = "bold red" +STYLE_METAVAR = "bold yellow" +STYLE_METAVAR_SEPARATOR = "dim" +STYLE_USAGE = "yellow" +STYLE_USAGE_COMMAND = "bold" +STYLE_DEPRECATED = "red" +STYLE_DEPRECATED_COMMAND = "dim" +STYLE_HELPTEXT_FIRST_LINE = "" +STYLE_HELPTEXT = "dim" +STYLE_OPTION_HELP = "" +STYLE_OPTION_DEFAULT = "dim" +STYLE_OPTION_ENVVAR = "dim yellow" +STYLE_REQUIRED_SHORT = "red" +STYLE_REQUIRED_LONG = "dim red" +STYLE_OPTIONS_PANEL_BORDER = "dim" +ALIGN_OPTIONS_PANEL: Literal["left", "center", "right"] = "left" +STYLE_OPTIONS_TABLE_SHOW_LINES = False +STYLE_OPTIONS_TABLE_LEADING = 0 +STYLE_OPTIONS_TABLE_PAD_EDGE = False +STYLE_OPTIONS_TABLE_PADDING = (0, 1) +STYLE_OPTIONS_TABLE_BOX = "" +STYLE_OPTIONS_TABLE_ROW_STYLES = None +STYLE_OPTIONS_TABLE_BORDER_STYLE = None +STYLE_COMMANDS_PANEL_BORDER = "dim" +ALIGN_COMMANDS_PANEL: Literal["left", "center", "right"] = "left" +STYLE_COMMANDS_TABLE_SHOW_LINES = False +STYLE_COMMANDS_TABLE_LEADING = 0 +STYLE_COMMANDS_TABLE_PAD_EDGE = False +STYLE_COMMANDS_TABLE_PADDING = (0, 1) +STYLE_COMMANDS_TABLE_BOX = "" +STYLE_COMMANDS_TABLE_ROW_STYLES = None +STYLE_COMMANDS_TABLE_BORDER_STYLE = None +STYLE_COMMANDS_TABLE_FIRST_COLUMN = "bold cyan" +STYLE_ERRORS_PANEL_BORDER = "red" +ALIGN_ERRORS_PANEL: Literal["left", "center", "right"] = "left" +STYLE_ERRORS_SUGGESTION = "dim" +STYLE_ABORTED = "red" +_TERMINAL_WIDTH = getenv("TERMINAL_WIDTH") +MAX_WIDTH = int(_TERMINAL_WIDTH) if _TERMINAL_WIDTH else None +COLOR_SYSTEM: Literal["auto", "standard", "256", "truecolor", "windows"] | None = ( + "auto" # Set to None to disable colors +) +_TYPER_FORCE_DISABLE_TERMINAL = getenv("_TYPER_FORCE_DISABLE_TERMINAL") +FORCE_TERMINAL = ( + True + if getenv("GITHUB_ACTIONS") or getenv("FORCE_COLOR") or getenv("PY_COLORS") + else None +) +if _TYPER_FORCE_DISABLE_TERMINAL: + FORCE_TERMINAL = False + +# Fixed strings +DEPRECATED_STRING = _("(deprecated) ") +DEFAULT_STRING = _("[default: {}]") +ENVVAR_STRING = _("[env var: {}]") +REQUIRED_SHORT_STRING = "*" +REQUIRED_LONG_STRING = _("[required]") +RANGE_STRING = " [{}]" +ARGUMENTS_PANEL_TITLE = _("Arguments") +OPTIONS_PANEL_TITLE = _("Options") +COMMANDS_PANEL_TITLE = _("Commands") +ERRORS_PANEL_TITLE = _("Error") +ABORTED_TEXT = _("Aborted.") +RICH_HELP = _("Try [blue]'{command_path} {help_option}'[/] for help.") + +MARKUP_MODE_MARKDOWN = "markdown" +MARKUP_MODE_RICH = "rich" +_RICH_HELP_PANEL_NAME = "rich_help_panel" +ANSI_PREFIX = "\033[" + +MarkupModeStrict = Literal["markdown", "rich"] + + +# Rich regex highlighter +class OptionHighlighter(RegexHighlighter): + """Highlights our special options.""" + + highlights = [ + r"(^|\W)(?P\-\w+)(?![a-zA-Z0-9])", + r"(^|\W)(?P