diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/CL/cl.h b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/CL/cl.h new file mode 100644 index 0000000000000000000000000000000000000000..45b28ccf1df0e234b466c624abfa3aacacfa1615 --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/CL/cl.h @@ -0,0 +1,2012 @@ +/******************************************************************************* + * Copyright (c) 2008-2020 The Khronos Group Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + ******************************************************************************/ + +#ifndef __OPENCL_CL_H +#define __OPENCL_CL_H + + +#ifndef __CL_VERSION_H +#define __CL_VERSION_H + +/* Detect which version to target */ +#if !defined(CL_TARGET_OPENCL_VERSION) +#pragma message("cl_version.h: CL_TARGET_OPENCL_VERSION is not defined. Defaulting to 300 (OpenCL 3.0)") +#define CL_TARGET_OPENCL_VERSION 300 +#endif +#if CL_TARGET_OPENCL_VERSION != 100 && \ + CL_TARGET_OPENCL_VERSION != 110 && \ + CL_TARGET_OPENCL_VERSION != 120 && \ + CL_TARGET_OPENCL_VERSION != 200 && \ + CL_TARGET_OPENCL_VERSION != 210 && \ + CL_TARGET_OPENCL_VERSION != 220 && \ + CL_TARGET_OPENCL_VERSION != 300 +#pragma message("cl_version: CL_TARGET_OPENCL_VERSION is not a valid value (100, 110, 120, 200, 210, 220, 300). Defaulting to 300 (OpenCL 3.0)") +#undef CL_TARGET_OPENCL_VERSION +#define CL_TARGET_OPENCL_VERSION 300 +#endif + + +/* OpenCL Version */ +#if CL_TARGET_OPENCL_VERSION >= 300 && !defined(CL_VERSION_3_0) +#define CL_VERSION_3_0 1 +#endif +#if CL_TARGET_OPENCL_VERSION >= 220 && !defined(CL_VERSION_2_2) +#define CL_VERSION_2_2 1 +#endif +#if CL_TARGET_OPENCL_VERSION >= 210 && !defined(CL_VERSION_2_1) +#define CL_VERSION_2_1 1 +#endif +#if CL_TARGET_OPENCL_VERSION >= 200 && !defined(CL_VERSION_2_0) +#define CL_VERSION_2_0 1 +#endif +#if CL_TARGET_OPENCL_VERSION >= 120 && !defined(CL_VERSION_1_2) +#define CL_VERSION_1_2 1 +#endif +#if CL_TARGET_OPENCL_VERSION >= 110 && !defined(CL_VERSION_1_1) +#define CL_VERSION_1_1 1 +#endif +#if CL_TARGET_OPENCL_VERSION >= 100 && !defined(CL_VERSION_1_0) +#define CL_VERSION_1_0 1 +#endif + +/* Allow deprecated APIs for older OpenCL versions. */ +#if CL_TARGET_OPENCL_VERSION <= 220 && !defined(CL_USE_DEPRECATED_OPENCL_2_2_APIS) +#define CL_USE_DEPRECATED_OPENCL_2_2_APIS +#endif +#if CL_TARGET_OPENCL_VERSION <= 210 && !defined(CL_USE_DEPRECATED_OPENCL_2_1_APIS) +#define CL_USE_DEPRECATED_OPENCL_2_1_APIS +#endif +#if CL_TARGET_OPENCL_VERSION <= 200 && !defined(CL_USE_DEPRECATED_OPENCL_2_0_APIS) +#define CL_USE_DEPRECATED_OPENCL_2_0_APIS +#endif +#if CL_TARGET_OPENCL_VERSION <= 120 && !defined(CL_USE_DEPRECATED_OPENCL_1_2_APIS) +#define CL_USE_DEPRECATED_OPENCL_1_2_APIS +#endif +#if CL_TARGET_OPENCL_VERSION <= 110 && !defined(CL_USE_DEPRECATED_OPENCL_1_1_APIS) +#define CL_USE_DEPRECATED_OPENCL_1_1_APIS +#endif +#if CL_TARGET_OPENCL_VERSION <= 100 && !defined(CL_USE_DEPRECATED_OPENCL_1_0_APIS) +#define CL_USE_DEPRECATED_OPENCL_1_0_APIS +#endif + +#endif /* __CL_VERSION_H */ + + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/******************************************************************************/ + +typedef struct _cl_platform_id * cl_platform_id; +typedef struct _cl_device_id * cl_device_id; +typedef struct _cl_context * cl_context; +typedef struct _cl_command_queue * cl_command_queue; +typedef struct _cl_mem * cl_mem; +typedef struct _cl_program * cl_program; +typedef struct _cl_kernel * cl_kernel; +typedef struct _cl_event * cl_event; +typedef struct _cl_sampler * cl_sampler; + +typedef cl_uint cl_bool; /* WARNING! Unlike cl_ types in cl_platform.h, cl_bool is not guaranteed to be the same size as the bool in kernels. */ +typedef cl_ulong cl_bitfield; +typedef cl_ulong cl_properties; +typedef cl_bitfield cl_device_type; +typedef cl_uint cl_platform_info; +typedef cl_uint cl_device_info; +typedef cl_bitfield cl_device_fp_config; +typedef cl_uint cl_device_mem_cache_type; +typedef cl_uint cl_device_local_mem_type; +typedef cl_bitfield cl_device_exec_capabilities; +#ifdef CL_VERSION_2_0 +typedef cl_bitfield cl_device_svm_capabilities; +#endif +typedef cl_bitfield cl_command_queue_properties; +#ifdef CL_VERSION_1_2 +typedef intptr_t cl_device_partition_property; +typedef cl_bitfield cl_device_affinity_domain; +#endif + +typedef intptr_t cl_context_properties; +typedef cl_uint cl_context_info; +#ifdef CL_VERSION_2_0 +typedef cl_properties cl_queue_properties; +#endif +typedef cl_uint cl_command_queue_info; +typedef cl_uint cl_channel_order; +typedef cl_uint cl_channel_type; +typedef cl_bitfield cl_mem_flags; +#ifdef CL_VERSION_2_0 +typedef cl_bitfield cl_svm_mem_flags; +#endif +typedef cl_uint cl_mem_object_type; +typedef cl_uint cl_mem_info; +#ifdef CL_VERSION_1_2 +typedef cl_bitfield cl_mem_migration_flags; +#endif +typedef cl_uint cl_image_info; +#ifdef CL_VERSION_1_1 +typedef cl_uint cl_buffer_create_type; +#endif +typedef cl_uint cl_addressing_mode; +typedef cl_uint cl_filter_mode; +typedef cl_uint cl_sampler_info; +typedef cl_bitfield cl_map_flags; +#ifdef CL_VERSION_2_0 +typedef intptr_t cl_pipe_properties; +typedef cl_uint cl_pipe_info; +#endif +typedef cl_uint cl_program_info; +typedef cl_uint cl_program_build_info; +#ifdef CL_VERSION_1_2 +typedef cl_uint cl_program_binary_type; +#endif +typedef cl_int cl_build_status; +typedef cl_uint cl_kernel_info; +#ifdef CL_VERSION_1_2 +typedef cl_uint cl_kernel_arg_info; +typedef cl_uint cl_kernel_arg_address_qualifier; +typedef cl_uint cl_kernel_arg_access_qualifier; +typedef cl_bitfield cl_kernel_arg_type_qualifier; +#endif +typedef cl_uint cl_kernel_work_group_info; +#ifdef CL_VERSION_2_1 +typedef cl_uint cl_kernel_sub_group_info; +#endif +typedef cl_uint cl_event_info; +typedef cl_uint cl_command_type; +typedef cl_uint cl_profiling_info; +#ifdef CL_VERSION_2_0 +typedef cl_properties cl_sampler_properties; +typedef cl_uint cl_kernel_exec_info; +#endif +#ifdef CL_VERSION_3_0 +typedef cl_bitfield cl_device_atomic_capabilities; +typedef cl_bitfield cl_device_device_enqueue_capabilities; +typedef cl_uint cl_khronos_vendor_id; +typedef cl_properties cl_mem_properties; +typedef cl_uint cl_version; +#endif + +typedef struct _cl_image_format { + cl_channel_order image_channel_order; + cl_channel_type image_channel_data_type; +} cl_image_format; + +#ifdef CL_VERSION_1_2 + +typedef struct _cl_image_desc { + cl_mem_object_type image_type; + size_t image_width; + size_t image_height; + size_t image_depth; + size_t image_array_size; + size_t image_row_pitch; + size_t image_slice_pitch; + cl_uint num_mip_levels; + cl_uint num_samples; +#ifdef CL_VERSION_2_0 +#if defined(__GNUC__) + __extension__ /* Prevents warnings about anonymous union in -pedantic builds */ +#endif +#if defined(_MSC_VER) && !defined(__STDC__) +#pragma warning( push ) +#pragma warning( disable : 4201 ) /* Prevents warning about nameless struct/union in /W4 builds */ +#endif +#ifdef __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wc11-extensions" /* Prevents warning about nameless union being C11 extension*/ +#endif +#if defined(_MSC_VER) && defined(__STDC__) + /* Anonymous unions are not supported in /Za builds */ +#else + union { +#endif +#endif + cl_mem buffer; +#ifdef CL_VERSION_2_0 +#if defined(_MSC_VER) && defined(__STDC__) + /* Anonymous unions are not supported in /Za builds */ +#else + cl_mem mem_object; + }; +#endif +#if defined(_MSC_VER) && !defined(__STDC__) +#pragma warning( pop ) +#endif +#ifdef __clang__ +#pragma clang diagnostic pop +#endif +#endif +} cl_image_desc; + +#endif + +#ifdef CL_VERSION_1_1 + +typedef struct _cl_buffer_region { + size_t origin; + size_t size; +} cl_buffer_region; + +#endif + +#ifdef CL_VERSION_3_0 + +#define CL_NAME_VERSION_MAX_NAME_SIZE 64 + +typedef struct _cl_name_version { + cl_version version; + char name[CL_NAME_VERSION_MAX_NAME_SIZE]; +} cl_name_version; + +#endif + +/******************************************************************************/ + +/* Error Codes */ +#define CL_SUCCESS 0 +#define CL_DEVICE_NOT_FOUND -1 +#define CL_DEVICE_NOT_AVAILABLE -2 +#define CL_COMPILER_NOT_AVAILABLE -3 +#define CL_MEM_OBJECT_ALLOCATION_FAILURE -4 +#define CL_OUT_OF_RESOURCES -5 +#define CL_OUT_OF_HOST_MEMORY -6 +#define CL_PROFILING_INFO_NOT_AVAILABLE -7 +#define CL_MEM_COPY_OVERLAP -8 +#define CL_IMAGE_FORMAT_MISMATCH -9 +#define CL_IMAGE_FORMAT_NOT_SUPPORTED -10 +#define CL_BUILD_PROGRAM_FAILURE -11 +#define CL_MAP_FAILURE -12 +#ifdef CL_VERSION_1_1 +#define CL_MISALIGNED_SUB_BUFFER_OFFSET -13 +#define CL_EXEC_STATUS_ERROR_FOR_EVENTS_IN_WAIT_LIST -14 +#endif +#ifdef CL_VERSION_1_2 +#define CL_COMPILE_PROGRAM_FAILURE -15 +#define CL_LINKER_NOT_AVAILABLE -16 +#define CL_LINK_PROGRAM_FAILURE -17 +#define CL_DEVICE_PARTITION_FAILED -18 +#define CL_KERNEL_ARG_INFO_NOT_AVAILABLE -19 +#endif + +#define CL_INVALID_VALUE -30 +#define CL_INVALID_DEVICE_TYPE -31 +#define CL_INVALID_PLATFORM -32 +#define CL_INVALID_DEVICE -33 +#define CL_INVALID_CONTEXT -34 +#define CL_INVALID_QUEUE_PROPERTIES -35 +#define CL_INVALID_COMMAND_QUEUE -36 +#define CL_INVALID_HOST_PTR -37 +#define CL_INVALID_MEM_OBJECT -38 +#define CL_INVALID_IMAGE_FORMAT_DESCRIPTOR -39 +#define CL_INVALID_IMAGE_SIZE -40 +#define CL_INVALID_SAMPLER -41 +#define CL_INVALID_BINARY -42 +#define CL_INVALID_BUILD_OPTIONS -43 +#define CL_INVALID_PROGRAM -44 +#define CL_INVALID_PROGRAM_EXECUTABLE -45 +#define CL_INVALID_KERNEL_NAME -46 +#define CL_INVALID_KERNEL_DEFINITION -47 +#define CL_INVALID_KERNEL -48 +#define CL_INVALID_ARG_INDEX -49 +#define CL_INVALID_ARG_VALUE -50 +#define CL_INVALID_ARG_SIZE -51 +#define CL_INVALID_KERNEL_ARGS -52 +#define CL_INVALID_WORK_DIMENSION -53 +#define CL_INVALID_WORK_GROUP_SIZE -54 +#define CL_INVALID_WORK_ITEM_SIZE -55 +#define CL_INVALID_GLOBAL_OFFSET -56 +#define CL_INVALID_EVENT_WAIT_LIST -57 +#define CL_INVALID_EVENT -58 +#define CL_INVALID_OPERATION -59 +#define CL_INVALID_GL_OBJECT -60 +#define CL_INVALID_BUFFER_SIZE -61 +#define CL_INVALID_MIP_LEVEL -62 +#define CL_INVALID_GLOBAL_WORK_SIZE -63 +#ifdef CL_VERSION_1_1 +#define CL_INVALID_PROPERTY -64 +#endif +#ifdef CL_VERSION_1_2 +#define CL_INVALID_IMAGE_DESCRIPTOR -65 +#define CL_INVALID_COMPILER_OPTIONS -66 +#define CL_INVALID_LINKER_OPTIONS -67 +#define CL_INVALID_DEVICE_PARTITION_COUNT -68 +#endif +#ifdef CL_VERSION_2_0 +#define CL_INVALID_PIPE_SIZE -69 +#define CL_INVALID_DEVICE_QUEUE -70 +#endif +#ifdef CL_VERSION_2_2 +#define CL_INVALID_SPEC_ID -71 +#define CL_MAX_SIZE_RESTRICTION_EXCEEDED -72 +#endif + + +/* cl_bool */ +#define CL_FALSE 0 +#define CL_TRUE 1 +#ifdef CL_VERSION_1_2 +#define CL_BLOCKING CL_TRUE +#define CL_NON_BLOCKING CL_FALSE +#endif + +/* cl_platform_info */ +#define CL_PLATFORM_PROFILE 0x0900 +#define CL_PLATFORM_VERSION 0x0901 +#define CL_PLATFORM_NAME 0x0902 +#define CL_PLATFORM_VENDOR 0x0903 +#define CL_PLATFORM_EXTENSIONS 0x0904 +#ifdef CL_VERSION_2_1 +#define CL_PLATFORM_HOST_TIMER_RESOLUTION 0x0905 +#endif +#ifdef CL_VERSION_3_0 +#define CL_PLATFORM_NUMERIC_VERSION 0x0906 +#define CL_PLATFORM_EXTENSIONS_WITH_VERSION 0x0907 +#endif + +/* cl_device_type - bitfield */ +#define CL_DEVICE_TYPE_DEFAULT (1 << 0) +#define CL_DEVICE_TYPE_CPU (1 << 1) +#define CL_DEVICE_TYPE_GPU (1 << 2) +#define CL_DEVICE_TYPE_ACCELERATOR (1 << 3) +#ifdef CL_VERSION_1_2 +#define CL_DEVICE_TYPE_CUSTOM (1 << 4) +#endif +#define CL_DEVICE_TYPE_ALL 0xFFFFFFFF + +/* cl_device_info */ +#define CL_DEVICE_TYPE 0x1000 +#define CL_DEVICE_VENDOR_ID 0x1001 +#define CL_DEVICE_MAX_COMPUTE_UNITS 0x1002 +#define CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS 0x1003 +#define CL_DEVICE_MAX_WORK_GROUP_SIZE 0x1004 +#define CL_DEVICE_MAX_WORK_ITEM_SIZES 0x1005 +#define CL_DEVICE_PREFERRED_VECTOR_WIDTH_CHAR 0x1006 +#define CL_DEVICE_PREFERRED_VECTOR_WIDTH_SHORT 0x1007 +#define CL_DEVICE_PREFERRED_VECTOR_WIDTH_INT 0x1008 +#define CL_DEVICE_PREFERRED_VECTOR_WIDTH_LONG 0x1009 +#define CL_DEVICE_PREFERRED_VECTOR_WIDTH_FLOAT 0x100A +#define CL_DEVICE_PREFERRED_VECTOR_WIDTH_DOUBLE 0x100B +#define CL_DEVICE_MAX_CLOCK_FREQUENCY 0x100C +#define CL_DEVICE_ADDRESS_BITS 0x100D +#define CL_DEVICE_MAX_READ_IMAGE_ARGS 0x100E +#define CL_DEVICE_MAX_WRITE_IMAGE_ARGS 0x100F +#define CL_DEVICE_MAX_MEM_ALLOC_SIZE 0x1010 +#define CL_DEVICE_IMAGE2D_MAX_WIDTH 0x1011 +#define CL_DEVICE_IMAGE2D_MAX_HEIGHT 0x1012 +#define CL_DEVICE_IMAGE3D_MAX_WIDTH 0x1013 +#define CL_DEVICE_IMAGE3D_MAX_HEIGHT 0x1014 +#define CL_DEVICE_IMAGE3D_MAX_DEPTH 0x1015 +#define CL_DEVICE_IMAGE_SUPPORT 0x1016 +#define CL_DEVICE_MAX_PARAMETER_SIZE 0x1017 +#define CL_DEVICE_MAX_SAMPLERS 0x1018 +#define CL_DEVICE_MEM_BASE_ADDR_ALIGN 0x1019 +#define CL_DEVICE_MIN_DATA_TYPE_ALIGN_SIZE 0x101A +#define CL_DEVICE_SINGLE_FP_CONFIG 0x101B +#define CL_DEVICE_GLOBAL_MEM_CACHE_TYPE 0x101C +#define CL_DEVICE_GLOBAL_MEM_CACHELINE_SIZE 0x101D +#define CL_DEVICE_GLOBAL_MEM_CACHE_SIZE 0x101E +#define CL_DEVICE_GLOBAL_MEM_SIZE 0x101F +#define CL_DEVICE_MAX_CONSTANT_BUFFER_SIZE 0x1020 +#define CL_DEVICE_MAX_CONSTANT_ARGS 0x1021 +#define CL_DEVICE_LOCAL_MEM_TYPE 0x1022 +#define CL_DEVICE_LOCAL_MEM_SIZE 0x1023 +#define CL_DEVICE_ERROR_CORRECTION_SUPPORT 0x1024 +#define CL_DEVICE_PROFILING_TIMER_RESOLUTION 0x1025 +#define CL_DEVICE_ENDIAN_LITTLE 0x1026 +#define CL_DEVICE_AVAILABLE 0x1027 +#define CL_DEVICE_COMPILER_AVAILABLE 0x1028 +#define CL_DEVICE_EXECUTION_CAPABILITIES 0x1029 +#define CL_DEVICE_QUEUE_PROPERTIES 0x102A /* deprecated */ +#ifdef CL_VERSION_2_0 +#define CL_DEVICE_QUEUE_ON_HOST_PROPERTIES 0x102A +#endif +#define CL_DEVICE_NAME 0x102B +#define CL_DEVICE_VENDOR 0x102C +#define CL_DRIVER_VERSION 0x102D +#define CL_DEVICE_PROFILE 0x102E +#define CL_DEVICE_VERSION 0x102F +#define CL_DEVICE_EXTENSIONS 0x1030 +#define CL_DEVICE_PLATFORM 0x1031 +#ifdef CL_VERSION_1_2 +#define CL_DEVICE_DOUBLE_FP_CONFIG 0x1032 +#endif +/* 0x1033 reserved for CL_DEVICE_HALF_FP_CONFIG which is already defined in "cl_ext.h" */ +#ifdef CL_VERSION_1_1 +#define CL_DEVICE_PREFERRED_VECTOR_WIDTH_HALF 0x1034 +#define CL_DEVICE_HOST_UNIFIED_MEMORY 0x1035 /* deprecated */ +#define CL_DEVICE_NATIVE_VECTOR_WIDTH_CHAR 0x1036 +#define CL_DEVICE_NATIVE_VECTOR_WIDTH_SHORT 0x1037 +#define CL_DEVICE_NATIVE_VECTOR_WIDTH_INT 0x1038 +#define CL_DEVICE_NATIVE_VECTOR_WIDTH_LONG 0x1039 +#define CL_DEVICE_NATIVE_VECTOR_WIDTH_FLOAT 0x103A +#define CL_DEVICE_NATIVE_VECTOR_WIDTH_DOUBLE 0x103B +#define CL_DEVICE_NATIVE_VECTOR_WIDTH_HALF 0x103C +#define CL_DEVICE_OPENCL_C_VERSION 0x103D +#endif +#ifdef CL_VERSION_1_2 +#define CL_DEVICE_LINKER_AVAILABLE 0x103E +#define CL_DEVICE_BUILT_IN_KERNELS 0x103F +#define CL_DEVICE_IMAGE_MAX_BUFFER_SIZE 0x1040 +#define CL_DEVICE_IMAGE_MAX_ARRAY_SIZE 0x1041 +#define CL_DEVICE_PARENT_DEVICE 0x1042 +#define CL_DEVICE_PARTITION_MAX_SUB_DEVICES 0x1043 +#define CL_DEVICE_PARTITION_PROPERTIES 0x1044 +#define CL_DEVICE_PARTITION_AFFINITY_DOMAIN 0x1045 +#define CL_DEVICE_PARTITION_TYPE 0x1046 +#define CL_DEVICE_REFERENCE_COUNT 0x1047 +#define CL_DEVICE_PREFERRED_INTEROP_USER_SYNC 0x1048 +#define CL_DEVICE_PRINTF_BUFFER_SIZE 0x1049 +#endif +#ifdef CL_VERSION_2_0 +#define CL_DEVICE_IMAGE_PITCH_ALIGNMENT 0x104A +#define CL_DEVICE_IMAGE_BASE_ADDRESS_ALIGNMENT 0x104B +#define CL_DEVICE_MAX_READ_WRITE_IMAGE_ARGS 0x104C +#define CL_DEVICE_MAX_GLOBAL_VARIABLE_SIZE 0x104D +#define CL_DEVICE_QUEUE_ON_DEVICE_PROPERTIES 0x104E +#define CL_DEVICE_QUEUE_ON_DEVICE_PREFERRED_SIZE 0x104F +#define CL_DEVICE_QUEUE_ON_DEVICE_MAX_SIZE 0x1050 +#define CL_DEVICE_MAX_ON_DEVICE_QUEUES 0x1051 +#define CL_DEVICE_MAX_ON_DEVICE_EVENTS 0x1052 +#define CL_DEVICE_SVM_CAPABILITIES 0x1053 +#define CL_DEVICE_GLOBAL_VARIABLE_PREFERRED_TOTAL_SIZE 0x1054 +#define CL_DEVICE_MAX_PIPE_ARGS 0x1055 +#define CL_DEVICE_PIPE_MAX_ACTIVE_RESERVATIONS 0x1056 +#define CL_DEVICE_PIPE_MAX_PACKET_SIZE 0x1057 +#define CL_DEVICE_PREFERRED_PLATFORM_ATOMIC_ALIGNMENT 0x1058 +#define CL_DEVICE_PREFERRED_GLOBAL_ATOMIC_ALIGNMENT 0x1059 +#define CL_DEVICE_PREFERRED_LOCAL_ATOMIC_ALIGNMENT 0x105A +#endif +#ifdef CL_VERSION_2_1 +#define CL_DEVICE_IL_VERSION 0x105B +#define CL_DEVICE_MAX_NUM_SUB_GROUPS 0x105C +#define CL_DEVICE_SUB_GROUP_INDEPENDENT_FORWARD_PROGRESS 0x105D +#endif +#ifdef CL_VERSION_3_0 +#define CL_DEVICE_NUMERIC_VERSION 0x105E +#define CL_DEVICE_EXTENSIONS_WITH_VERSION 0x1060 +#define CL_DEVICE_ILS_WITH_VERSION 0x1061 +#define CL_DEVICE_BUILT_IN_KERNELS_WITH_VERSION 0x1062 +#define CL_DEVICE_ATOMIC_MEMORY_CAPABILITIES 0x1063 +#define CL_DEVICE_ATOMIC_FENCE_CAPABILITIES 0x1064 +#define CL_DEVICE_NON_UNIFORM_WORK_GROUP_SUPPORT 0x1065 +#define CL_DEVICE_OPENCL_C_ALL_VERSIONS 0x1066 +#define CL_DEVICE_PREFERRED_WORK_GROUP_SIZE_MULTIPLE 0x1067 +#define CL_DEVICE_WORK_GROUP_COLLECTIVE_FUNCTIONS_SUPPORT 0x1068 +#define CL_DEVICE_GENERIC_ADDRESS_SPACE_SUPPORT 0x1069 +/* 0x106A to 0x106E - Reserved for upcoming KHR extension */ +#define CL_DEVICE_OPENCL_C_FEATURES 0x106F +#define CL_DEVICE_DEVICE_ENQUEUE_CAPABILITIES 0x1070 +#define CL_DEVICE_PIPE_SUPPORT 0x1071 +#define CL_DEVICE_LATEST_CONFORMANCE_VERSION_PASSED 0x1072 +#endif + +/* cl_device_fp_config - bitfield */ +#define CL_FP_DENORM (1 << 0) +#define CL_FP_INF_NAN (1 << 1) +#define CL_FP_ROUND_TO_NEAREST (1 << 2) +#define CL_FP_ROUND_TO_ZERO (1 << 3) +#define CL_FP_ROUND_TO_INF (1 << 4) +#define CL_FP_FMA (1 << 5) +#ifdef CL_VERSION_1_1 +#define CL_FP_SOFT_FLOAT (1 << 6) +#endif +#ifdef CL_VERSION_1_2 +#define CL_FP_CORRECTLY_ROUNDED_DIVIDE_SQRT (1 << 7) +#endif + +/* cl_device_mem_cache_type */ +#define CL_NONE 0x0 +#define CL_READ_ONLY_CACHE 0x1 +#define CL_READ_WRITE_CACHE 0x2 + +/* cl_device_local_mem_type */ +#define CL_LOCAL 0x1 +#define CL_GLOBAL 0x2 + +/* cl_device_exec_capabilities - bitfield */ +#define CL_EXEC_KERNEL (1 << 0) +#define CL_EXEC_NATIVE_KERNEL (1 << 1) + +/* cl_command_queue_properties - bitfield */ +#define CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE (1 << 0) +#define CL_QUEUE_PROFILING_ENABLE (1 << 1) +#ifdef CL_VERSION_2_0 +#define CL_QUEUE_ON_DEVICE (1 << 2) +#define CL_QUEUE_ON_DEVICE_DEFAULT (1 << 3) +#endif + +/* cl_context_info */ +#define CL_CONTEXT_REFERENCE_COUNT 0x1080 +#define CL_CONTEXT_DEVICES 0x1081 +#define CL_CONTEXT_PROPERTIES 0x1082 +#ifdef CL_VERSION_1_1 +#define CL_CONTEXT_NUM_DEVICES 0x1083 +#endif + +/* cl_context_properties */ +#define CL_CONTEXT_PLATFORM 0x1084 +#ifdef CL_VERSION_1_2 +#define CL_CONTEXT_INTEROP_USER_SYNC 0x1085 +#endif + +#ifdef CL_VERSION_1_2 + +/* cl_device_partition_property */ +#define CL_DEVICE_PARTITION_EQUALLY 0x1086 +#define CL_DEVICE_PARTITION_BY_COUNTS 0x1087 +#define CL_DEVICE_PARTITION_BY_COUNTS_LIST_END 0x0 +#define CL_DEVICE_PARTITION_BY_AFFINITY_DOMAIN 0x1088 + +#endif + +#ifdef CL_VERSION_1_2 + +/* cl_device_affinity_domain */ +#define CL_DEVICE_AFFINITY_DOMAIN_NUMA (1 << 0) +#define CL_DEVICE_AFFINITY_DOMAIN_L4_CACHE (1 << 1) +#define CL_DEVICE_AFFINITY_DOMAIN_L3_CACHE (1 << 2) +#define CL_DEVICE_AFFINITY_DOMAIN_L2_CACHE (1 << 3) +#define CL_DEVICE_AFFINITY_DOMAIN_L1_CACHE (1 << 4) +#define CL_DEVICE_AFFINITY_DOMAIN_NEXT_PARTITIONABLE (1 << 5) + +#endif + +#ifdef CL_VERSION_2_0 + +/* cl_device_svm_capabilities */ +#define CL_DEVICE_SVM_COARSE_GRAIN_BUFFER (1 << 0) +#define CL_DEVICE_SVM_FINE_GRAIN_BUFFER (1 << 1) +#define CL_DEVICE_SVM_FINE_GRAIN_SYSTEM (1 << 2) +#define CL_DEVICE_SVM_ATOMICS (1 << 3) + +#endif + +/* cl_command_queue_info */ +#define CL_QUEUE_CONTEXT 0x1090 +#define CL_QUEUE_DEVICE 0x1091 +#define CL_QUEUE_REFERENCE_COUNT 0x1092 +#define CL_QUEUE_PROPERTIES 0x1093 +#ifdef CL_VERSION_2_0 +#define CL_QUEUE_SIZE 0x1094 +#endif +#ifdef CL_VERSION_2_1 +#define CL_QUEUE_DEVICE_DEFAULT 0x1095 +#endif +#ifdef CL_VERSION_3_0 +#define CL_QUEUE_PROPERTIES_ARRAY 0x1098 +#endif + +/* cl_mem_flags and cl_svm_mem_flags - bitfield */ +#define CL_MEM_READ_WRITE (1 << 0) +#define CL_MEM_WRITE_ONLY (1 << 1) +#define CL_MEM_READ_ONLY (1 << 2) +#define CL_MEM_USE_HOST_PTR (1 << 3) +#define CL_MEM_ALLOC_HOST_PTR (1 << 4) +#define CL_MEM_COPY_HOST_PTR (1 << 5) +/* reserved (1 << 6) */ +#ifdef CL_VERSION_1_2 +#define CL_MEM_HOST_WRITE_ONLY (1 << 7) +#define CL_MEM_HOST_READ_ONLY (1 << 8) +#define CL_MEM_HOST_NO_ACCESS (1 << 9) +#endif +#ifdef CL_VERSION_2_0 +#define CL_MEM_SVM_FINE_GRAIN_BUFFER (1 << 10) /* used by cl_svm_mem_flags only */ +#define CL_MEM_SVM_ATOMICS (1 << 11) /* used by cl_svm_mem_flags only */ +#define CL_MEM_KERNEL_READ_AND_WRITE (1 << 12) +#endif + +#ifdef CL_VERSION_1_2 + +/* cl_mem_migration_flags - bitfield */ +#define CL_MIGRATE_MEM_OBJECT_HOST (1 << 0) +#define CL_MIGRATE_MEM_OBJECT_CONTENT_UNDEFINED (1 << 1) + +#endif + +/* cl_channel_order */ +#define CL_R 0x10B0 +#define CL_A 0x10B1 +#define CL_RG 0x10B2 +#define CL_RA 0x10B3 +#define CL_RGB 0x10B4 +#define CL_RGBA 0x10B5 +#define CL_BGRA 0x10B6 +#define CL_ARGB 0x10B7 +#define CL_INTENSITY 0x10B8 +#define CL_LUMINANCE 0x10B9 +#ifdef CL_VERSION_1_1 +#define CL_Rx 0x10BA +#define CL_RGx 0x10BB +#define CL_RGBx 0x10BC +#endif +#ifdef CL_VERSION_1_2 +#define CL_DEPTH 0x10BD +#define CL_DEPTH_STENCIL 0x10BE +#endif +#ifdef CL_VERSION_2_0 +#define CL_sRGB 0x10BF +#define CL_sRGBx 0x10C0 +#define CL_sRGBA 0x10C1 +#define CL_sBGRA 0x10C2 +#define CL_ABGR 0x10C3 +#endif + +/* cl_channel_type */ +#define CL_SNORM_INT8 0x10D0 +#define CL_SNORM_INT16 0x10D1 +#define CL_UNORM_INT8 0x10D2 +#define CL_UNORM_INT16 0x10D3 +#define CL_UNORM_SHORT_565 0x10D4 +#define CL_UNORM_SHORT_555 0x10D5 +#define CL_UNORM_INT_101010 0x10D6 +#define CL_SIGNED_INT8 0x10D7 +#define CL_SIGNED_INT16 0x10D8 +#define CL_SIGNED_INT32 0x10D9 +#define CL_UNSIGNED_INT8 0x10DA +#define CL_UNSIGNED_INT16 0x10DB +#define CL_UNSIGNED_INT32 0x10DC +#define CL_HALF_FLOAT 0x10DD +#define CL_FLOAT 0x10DE +#ifdef CL_VERSION_1_2 +#define CL_UNORM_INT24 0x10DF +#endif +#ifdef CL_VERSION_2_1 +#define CL_UNORM_INT_101010_2 0x10E0 +#endif + +/* cl_mem_object_type */ +#define CL_MEM_OBJECT_BUFFER 0x10F0 +#define CL_MEM_OBJECT_IMAGE2D 0x10F1 +#define CL_MEM_OBJECT_IMAGE3D 0x10F2 +#ifdef CL_VERSION_1_2 +#define CL_MEM_OBJECT_IMAGE2D_ARRAY 0x10F3 +#define CL_MEM_OBJECT_IMAGE1D 0x10F4 +#define CL_MEM_OBJECT_IMAGE1D_ARRAY 0x10F5 +#define CL_MEM_OBJECT_IMAGE1D_BUFFER 0x10F6 +#endif +#ifdef CL_VERSION_2_0 +#define CL_MEM_OBJECT_PIPE 0x10F7 +#endif + +/* cl_mem_info */ +#define CL_MEM_TYPE 0x1100 +#define CL_MEM_FLAGS 0x1101 +#define CL_MEM_SIZE 0x1102 +#define CL_MEM_HOST_PTR 0x1103 +#define CL_MEM_MAP_COUNT 0x1104 +#define CL_MEM_REFERENCE_COUNT 0x1105 +#define CL_MEM_CONTEXT 0x1106 +#ifdef CL_VERSION_1_1 +#define CL_MEM_ASSOCIATED_MEMOBJECT 0x1107 +#define CL_MEM_OFFSET 0x1108 +#endif +#ifdef CL_VERSION_2_0 +#define CL_MEM_USES_SVM_POINTER 0x1109 +#endif +#ifdef CL_VERSION_3_0 +#define CL_MEM_PROPERTIES 0x110A +#endif + +/* cl_image_info */ +#define CL_IMAGE_FORMAT 0x1110 +#define CL_IMAGE_ELEMENT_SIZE 0x1111 +#define CL_IMAGE_ROW_PITCH 0x1112 +#define CL_IMAGE_SLICE_PITCH 0x1113 +#define CL_IMAGE_WIDTH 0x1114 +#define CL_IMAGE_HEIGHT 0x1115 +#define CL_IMAGE_DEPTH 0x1116 +#ifdef CL_VERSION_1_2 +#define CL_IMAGE_ARRAY_SIZE 0x1117 +#define CL_IMAGE_BUFFER 0x1118 +#define CL_IMAGE_NUM_MIP_LEVELS 0x1119 +#define CL_IMAGE_NUM_SAMPLES 0x111A +#endif + + +/* cl_pipe_info */ +#ifdef CL_VERSION_2_0 +#define CL_PIPE_PACKET_SIZE 0x1120 +#define CL_PIPE_MAX_PACKETS 0x1121 +#endif +#ifdef CL_VERSION_3_0 +#define CL_PIPE_PROPERTIES 0x1122 +#endif + +/* cl_addressing_mode */ +#define CL_ADDRESS_NONE 0x1130 +#define CL_ADDRESS_CLAMP_TO_EDGE 0x1131 +#define CL_ADDRESS_CLAMP 0x1132 +#define CL_ADDRESS_REPEAT 0x1133 +#ifdef CL_VERSION_1_1 +#define CL_ADDRESS_MIRRORED_REPEAT 0x1134 +#endif + +/* cl_filter_mode */ +#define CL_FILTER_NEAREST 0x1140 +#define CL_FILTER_LINEAR 0x1141 + +/* cl_sampler_info */ +#define CL_SAMPLER_REFERENCE_COUNT 0x1150 +#define CL_SAMPLER_CONTEXT 0x1151 +#define CL_SAMPLER_NORMALIZED_COORDS 0x1152 +#define CL_SAMPLER_ADDRESSING_MODE 0x1153 +#define CL_SAMPLER_FILTER_MODE 0x1154 +#ifdef CL_VERSION_2_0 +/* These enumerants are for the cl_khr_mipmap_image extension. + They have since been added to cl_ext.h with an appropriate + KHR suffix, but are left here for backwards compatibility. */ +#define CL_SAMPLER_MIP_FILTER_MODE 0x1155 +#define CL_SAMPLER_LOD_MIN 0x1156 +#define CL_SAMPLER_LOD_MAX 0x1157 +#endif +#ifdef CL_VERSION_3_0 +#define CL_SAMPLER_PROPERTIES 0x1158 +#endif + +/* cl_map_flags - bitfield */ +#define CL_MAP_READ (1 << 0) +#define CL_MAP_WRITE (1 << 1) +#ifdef CL_VERSION_1_2 +#define CL_MAP_WRITE_INVALIDATE_REGION (1 << 2) +#endif + +/* cl_program_info */ +#define CL_PROGRAM_REFERENCE_COUNT 0x1160 +#define CL_PROGRAM_CONTEXT 0x1161 +#define CL_PROGRAM_NUM_DEVICES 0x1162 +#define CL_PROGRAM_DEVICES 0x1163 +#define CL_PROGRAM_SOURCE 0x1164 +#define CL_PROGRAM_BINARY_SIZES 0x1165 +#define CL_PROGRAM_BINARIES 0x1166 +#ifdef CL_VERSION_1_2 +#define CL_PROGRAM_NUM_KERNELS 0x1167 +#define CL_PROGRAM_KERNEL_NAMES 0x1168 +#endif +#ifdef CL_VERSION_2_1 +#define CL_PROGRAM_IL 0x1169 +#endif +#ifdef CL_VERSION_2_2 +#define CL_PROGRAM_SCOPE_GLOBAL_CTORS_PRESENT 0x116A +#define CL_PROGRAM_SCOPE_GLOBAL_DTORS_PRESENT 0x116B +#endif + +/* cl_program_build_info */ +#define CL_PROGRAM_BUILD_STATUS 0x1181 +#define CL_PROGRAM_BUILD_OPTIONS 0x1182 +#define CL_PROGRAM_BUILD_LOG 0x1183 +#ifdef CL_VERSION_1_2 +#define CL_PROGRAM_BINARY_TYPE 0x1184 +#endif +#ifdef CL_VERSION_2_0 +#define CL_PROGRAM_BUILD_GLOBAL_VARIABLE_TOTAL_SIZE 0x1185 +#endif + +#ifdef CL_VERSION_1_2 + +/* cl_program_binary_type */ +#define CL_PROGRAM_BINARY_TYPE_NONE 0x0 +#define CL_PROGRAM_BINARY_TYPE_COMPILED_OBJECT 0x1 +#define CL_PROGRAM_BINARY_TYPE_LIBRARY 0x2 +#define CL_PROGRAM_BINARY_TYPE_EXECUTABLE 0x4 + +#endif + +/* cl_build_status */ +#define CL_BUILD_SUCCESS 0 +#define CL_BUILD_NONE -1 +#define CL_BUILD_ERROR -2 +#define CL_BUILD_IN_PROGRESS -3 + +/* cl_kernel_info */ +#define CL_KERNEL_FUNCTION_NAME 0x1190 +#define CL_KERNEL_NUM_ARGS 0x1191 +#define CL_KERNEL_REFERENCE_COUNT 0x1192 +#define CL_KERNEL_CONTEXT 0x1193 +#define CL_KERNEL_PROGRAM 0x1194 +#ifdef CL_VERSION_1_2 +#define CL_KERNEL_ATTRIBUTES 0x1195 +#endif + +#ifdef CL_VERSION_1_2 + +/* cl_kernel_arg_info */ +#define CL_KERNEL_ARG_ADDRESS_QUALIFIER 0x1196 +#define CL_KERNEL_ARG_ACCESS_QUALIFIER 0x1197 +#define CL_KERNEL_ARG_TYPE_NAME 0x1198 +#define CL_KERNEL_ARG_TYPE_QUALIFIER 0x1199 +#define CL_KERNEL_ARG_NAME 0x119A + +#endif + +#ifdef CL_VERSION_1_2 + +/* cl_kernel_arg_address_qualifier */ +#define CL_KERNEL_ARG_ADDRESS_GLOBAL 0x119B +#define CL_KERNEL_ARG_ADDRESS_LOCAL 0x119C +#define CL_KERNEL_ARG_ADDRESS_CONSTANT 0x119D +#define CL_KERNEL_ARG_ADDRESS_PRIVATE 0x119E + +#endif + +#ifdef CL_VERSION_1_2 + +/* cl_kernel_arg_access_qualifier */ +#define CL_KERNEL_ARG_ACCESS_READ_ONLY 0x11A0 +#define CL_KERNEL_ARG_ACCESS_WRITE_ONLY 0x11A1 +#define CL_KERNEL_ARG_ACCESS_READ_WRITE 0x11A2 +#define CL_KERNEL_ARG_ACCESS_NONE 0x11A3 + +#endif + +#ifdef CL_VERSION_1_2 + +/* cl_kernel_arg_type_qualifier */ +#define CL_KERNEL_ARG_TYPE_NONE 0 +#define CL_KERNEL_ARG_TYPE_CONST (1 << 0) +#define CL_KERNEL_ARG_TYPE_RESTRICT (1 << 1) +#define CL_KERNEL_ARG_TYPE_VOLATILE (1 << 2) +#ifdef CL_VERSION_2_0 +#define CL_KERNEL_ARG_TYPE_PIPE (1 << 3) +#endif + +#endif + +/* cl_kernel_work_group_info */ +#define CL_KERNEL_WORK_GROUP_SIZE 0x11B0 +#define CL_KERNEL_COMPILE_WORK_GROUP_SIZE 0x11B1 +#define CL_KERNEL_LOCAL_MEM_SIZE 0x11B2 +#define CL_KERNEL_PREFERRED_WORK_GROUP_SIZE_MULTIPLE 0x11B3 +#define CL_KERNEL_PRIVATE_MEM_SIZE 0x11B4 +#ifdef CL_VERSION_1_2 +#define CL_KERNEL_GLOBAL_WORK_SIZE 0x11B5 +#endif + +#ifdef CL_VERSION_2_1 + +/* cl_kernel_sub_group_info */ +#define CL_KERNEL_MAX_SUB_GROUP_SIZE_FOR_NDRANGE 0x2033 +#define CL_KERNEL_SUB_GROUP_COUNT_FOR_NDRANGE 0x2034 +#define CL_KERNEL_LOCAL_SIZE_FOR_SUB_GROUP_COUNT 0x11B8 +#define CL_KERNEL_MAX_NUM_SUB_GROUPS 0x11B9 +#define CL_KERNEL_COMPILE_NUM_SUB_GROUPS 0x11BA + +#endif + +#ifdef CL_VERSION_2_0 + +/* cl_kernel_exec_info */ +#define CL_KERNEL_EXEC_INFO_SVM_PTRS 0x11B6 +#define CL_KERNEL_EXEC_INFO_SVM_FINE_GRAIN_SYSTEM 0x11B7 + +#endif + +/* cl_event_info */ +#define CL_EVENT_COMMAND_QUEUE 0x11D0 +#define CL_EVENT_COMMAND_TYPE 0x11D1 +#define CL_EVENT_REFERENCE_COUNT 0x11D2 +#define CL_EVENT_COMMAND_EXECUTION_STATUS 0x11D3 +#ifdef CL_VERSION_1_1 +#define CL_EVENT_CONTEXT 0x11D4 +#endif + +/* cl_command_type */ +#define CL_COMMAND_NDRANGE_KERNEL 0x11F0 +#define CL_COMMAND_TASK 0x11F1 +#define CL_COMMAND_NATIVE_KERNEL 0x11F2 +#define CL_COMMAND_READ_BUFFER 0x11F3 +#define CL_COMMAND_WRITE_BUFFER 0x11F4 +#define CL_COMMAND_COPY_BUFFER 0x11F5 +#define CL_COMMAND_READ_IMAGE 0x11F6 +#define CL_COMMAND_WRITE_IMAGE 0x11F7 +#define CL_COMMAND_COPY_IMAGE 0x11F8 +#define CL_COMMAND_COPY_IMAGE_TO_BUFFER 0x11F9 +#define CL_COMMAND_COPY_BUFFER_TO_IMAGE 0x11FA +#define CL_COMMAND_MAP_BUFFER 0x11FB +#define CL_COMMAND_MAP_IMAGE 0x11FC +#define CL_COMMAND_UNMAP_MEM_OBJECT 0x11FD +#define CL_COMMAND_MARKER 0x11FE +#define CL_COMMAND_ACQUIRE_GL_OBJECTS 0x11FF +#define CL_COMMAND_RELEASE_GL_OBJECTS 0x1200 +#ifdef CL_VERSION_1_1 +#define CL_COMMAND_READ_BUFFER_RECT 0x1201 +#define CL_COMMAND_WRITE_BUFFER_RECT 0x1202 +#define CL_COMMAND_COPY_BUFFER_RECT 0x1203 +#define CL_COMMAND_USER 0x1204 +#endif +#ifdef CL_VERSION_1_2 +#define CL_COMMAND_BARRIER 0x1205 +#define CL_COMMAND_MIGRATE_MEM_OBJECTS 0x1206 +#define CL_COMMAND_FILL_BUFFER 0x1207 +#define CL_COMMAND_FILL_IMAGE 0x1208 +#endif +#ifdef CL_VERSION_2_0 +#define CL_COMMAND_SVM_FREE 0x1209 +#define CL_COMMAND_SVM_MEMCPY 0x120A +#define CL_COMMAND_SVM_MEMFILL 0x120B +#define CL_COMMAND_SVM_MAP 0x120C +#define CL_COMMAND_SVM_UNMAP 0x120D +#endif +#ifdef CL_VERSION_3_0 +#define CL_COMMAND_SVM_MIGRATE_MEM 0x120E +#endif + +/* command execution status */ +#define CL_COMPLETE 0x0 +#define CL_RUNNING 0x1 +#define CL_SUBMITTED 0x2 +#define CL_QUEUED 0x3 + +/* cl_buffer_create_type */ +#ifdef CL_VERSION_1_1 +#define CL_BUFFER_CREATE_TYPE_REGION 0x1220 +#endif + +/* cl_profiling_info */ +#define CL_PROFILING_COMMAND_QUEUED 0x1280 +#define CL_PROFILING_COMMAND_SUBMIT 0x1281 +#define CL_PROFILING_COMMAND_START 0x1282 +#define CL_PROFILING_COMMAND_END 0x1283 +#ifdef CL_VERSION_2_0 +#define CL_PROFILING_COMMAND_COMPLETE 0x1284 +#endif + +/* cl_device_atomic_capabilities - bitfield */ +#ifdef CL_VERSION_3_0 +#define CL_DEVICE_ATOMIC_ORDER_RELAXED (1 << 0) +#define CL_DEVICE_ATOMIC_ORDER_ACQ_REL (1 << 1) +#define CL_DEVICE_ATOMIC_ORDER_SEQ_CST (1 << 2) +#define CL_DEVICE_ATOMIC_SCOPE_WORK_ITEM (1 << 3) +#define CL_DEVICE_ATOMIC_SCOPE_WORK_GROUP (1 << 4) +#define CL_DEVICE_ATOMIC_SCOPE_DEVICE (1 << 5) +#define CL_DEVICE_ATOMIC_SCOPE_ALL_DEVICES (1 << 6) +#endif + +/* cl_device_device_enqueue_capabilities - bitfield */ +#ifdef CL_VERSION_3_0 +#define CL_DEVICE_QUEUE_SUPPORTED (1 << 0) +#define CL_DEVICE_QUEUE_REPLACEABLE_DEFAULT (1 << 1) +#endif + +/* cl_khronos_vendor_id */ +#define CL_KHRONOS_VENDOR_ID_CODEPLAY 0x10004 + +#ifdef CL_VERSION_3_0 + +/* cl_version */ +#define CL_VERSION_MAJOR_BITS (10) +#define CL_VERSION_MINOR_BITS (10) +#define CL_VERSION_PATCH_BITS (12) + +#define CL_VERSION_MAJOR_MASK ((1 << CL_VERSION_MAJOR_BITS) - 1) +#define CL_VERSION_MINOR_MASK ((1 << CL_VERSION_MINOR_BITS) - 1) +#define CL_VERSION_PATCH_MASK ((1 << CL_VERSION_PATCH_BITS) - 1) + +#define CL_VERSION_MAJOR(version) \ + ((version) >> (CL_VERSION_MINOR_BITS + CL_VERSION_PATCH_BITS)) + +#define CL_VERSION_MINOR(version) \ + (((version) >> CL_VERSION_PATCH_BITS) & CL_VERSION_MINOR_MASK) + +#define CL_VERSION_PATCH(version) ((version) & CL_VERSION_PATCH_MASK) + +#define CL_MAKE_VERSION(major, minor, patch) \ + ((((major) & CL_VERSION_MAJOR_MASK) \ + << (CL_VERSION_MINOR_BITS + CL_VERSION_PATCH_BITS)) | \ + (((minor) & CL_VERSION_MINOR_MASK) << CL_VERSION_PATCH_BITS) | \ + ((patch) & CL_VERSION_PATCH_MASK)) + +#endif + +/********************************************************************************************************/ + +/* CL_NO_PROTOTYPES implies CL_NO_CORE_PROTOTYPES: */ +#if defined(CL_NO_PROTOTYPES) && !defined(CL_NO_CORE_PROTOTYPES) +#define CL_NO_CORE_PROTOTYPES +#endif + +#if !defined(CL_NO_CORE_PROTOTYPES) + +/* Platform API */ +extern CL_API_ENTRY cl_int CL_API_CALL +clGetPlatformIDs(cl_uint num_entries, + cl_platform_id * platforms, + cl_uint * num_platforms) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY cl_int CL_API_CALL +clGetPlatformInfo(cl_platform_id platform, + cl_platform_info param_name, + size_t param_value_size, + void * param_value, + size_t * param_value_size_ret) CL_API_SUFFIX__VERSION_1_0; + +/* Device APIs */ +extern CL_API_ENTRY cl_int CL_API_CALL +clGetDeviceIDs(cl_platform_id platform, + cl_device_type device_type, + cl_uint num_entries, + cl_device_id * devices, + cl_uint * num_devices) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY cl_int CL_API_CALL +clGetDeviceInfo(cl_device_id device, + cl_device_info param_name, + size_t param_value_size, + void * param_value, + size_t * param_value_size_ret) CL_API_SUFFIX__VERSION_1_0; + +#ifdef CL_VERSION_1_2 + +extern CL_API_ENTRY cl_int CL_API_CALL +clCreateSubDevices(cl_device_id in_device, + const cl_device_partition_property * properties, + cl_uint num_devices, + cl_device_id * out_devices, + cl_uint * num_devices_ret) CL_API_SUFFIX__VERSION_1_2; + +extern CL_API_ENTRY cl_int CL_API_CALL +clRetainDevice(cl_device_id device) CL_API_SUFFIX__VERSION_1_2; + +extern CL_API_ENTRY cl_int CL_API_CALL +clReleaseDevice(cl_device_id device) CL_API_SUFFIX__VERSION_1_2; + +#endif + +#ifdef CL_VERSION_2_1 + +extern CL_API_ENTRY cl_int CL_API_CALL +clSetDefaultDeviceCommandQueue(cl_context context, + cl_device_id device, + cl_command_queue command_queue) CL_API_SUFFIX__VERSION_2_1; + +extern CL_API_ENTRY cl_int CL_API_CALL +clGetDeviceAndHostTimer(cl_device_id device, + cl_ulong* device_timestamp, + cl_ulong* host_timestamp) CL_API_SUFFIX__VERSION_2_1; + +extern CL_API_ENTRY cl_int CL_API_CALL +clGetHostTimer(cl_device_id device, + cl_ulong * host_timestamp) CL_API_SUFFIX__VERSION_2_1; + +#endif + +/* Context APIs */ +extern CL_API_ENTRY cl_context CL_API_CALL +clCreateContext(const cl_context_properties * properties, + cl_uint num_devices, + const cl_device_id * devices, + void (CL_CALLBACK * pfn_notify)(const char * errinfo, + const void * private_info, + size_t cb, + void * user_data), + void * user_data, + cl_int * errcode_ret) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY cl_context CL_API_CALL +clCreateContextFromType(const cl_context_properties * properties, + cl_device_type device_type, + void (CL_CALLBACK * pfn_notify)(const char * errinfo, + const void * private_info, + size_t cb, + void * user_data), + void * user_data, + cl_int * errcode_ret) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY cl_int CL_API_CALL +clRetainContext(cl_context context) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY cl_int CL_API_CALL +clReleaseContext(cl_context context) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY cl_int CL_API_CALL +clGetContextInfo(cl_context context, + cl_context_info param_name, + size_t param_value_size, + void * param_value, + size_t * param_value_size_ret) CL_API_SUFFIX__VERSION_1_0; + +#ifdef CL_VERSION_3_0 + +extern CL_API_ENTRY cl_int CL_API_CALL +clSetContextDestructorCallback(cl_context context, + void (CL_CALLBACK* pfn_notify)(cl_context context, + void* user_data), + void* user_data) CL_API_SUFFIX__VERSION_3_0; + +#endif + +/* Command Queue APIs */ + +#ifdef CL_VERSION_2_0 + +extern CL_API_ENTRY cl_command_queue CL_API_CALL +clCreateCommandQueueWithProperties(cl_context context, + cl_device_id device, + const cl_queue_properties * properties, + cl_int * errcode_ret) CL_API_SUFFIX__VERSION_2_0; + +#endif + +extern CL_API_ENTRY cl_int CL_API_CALL +clRetainCommandQueue(cl_command_queue command_queue) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY cl_int CL_API_CALL +clReleaseCommandQueue(cl_command_queue command_queue) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY cl_int CL_API_CALL +clGetCommandQueueInfo(cl_command_queue command_queue, + cl_command_queue_info param_name, + size_t param_value_size, + void * param_value, + size_t * param_value_size_ret) CL_API_SUFFIX__VERSION_1_0; + +/* Memory Object APIs */ +extern CL_API_ENTRY cl_mem CL_API_CALL +clCreateBuffer(cl_context context, + cl_mem_flags flags, + size_t size, + void * host_ptr, + cl_int * errcode_ret) CL_API_SUFFIX__VERSION_1_0; + +#ifdef CL_VERSION_1_1 + +extern CL_API_ENTRY cl_mem CL_API_CALL +clCreateSubBuffer(cl_mem buffer, + cl_mem_flags flags, + cl_buffer_create_type buffer_create_type, + const void * buffer_create_info, + cl_int * errcode_ret) CL_API_SUFFIX__VERSION_1_1; + +#endif + +#ifdef CL_VERSION_1_2 + +extern CL_API_ENTRY cl_mem CL_API_CALL +clCreateImage(cl_context context, + cl_mem_flags flags, + const cl_image_format * image_format, + const cl_image_desc * image_desc, + void * host_ptr, + cl_int * errcode_ret) CL_API_SUFFIX__VERSION_1_2; + +#endif + +#ifdef CL_VERSION_2_0 + +extern CL_API_ENTRY cl_mem CL_API_CALL +clCreatePipe(cl_context context, + cl_mem_flags flags, + cl_uint pipe_packet_size, + cl_uint pipe_max_packets, + const cl_pipe_properties * properties, + cl_int * errcode_ret) CL_API_SUFFIX__VERSION_2_0; + +#endif + +#ifdef CL_VERSION_3_0 + +extern CL_API_ENTRY cl_mem CL_API_CALL +clCreateBufferWithProperties(cl_context context, + const cl_mem_properties * properties, + cl_mem_flags flags, + size_t size, + void * host_ptr, + cl_int * errcode_ret) CL_API_SUFFIX__VERSION_3_0; + +extern CL_API_ENTRY cl_mem CL_API_CALL +clCreateImageWithProperties(cl_context context, + const cl_mem_properties * properties, + cl_mem_flags flags, + const cl_image_format * image_format, + const cl_image_desc * image_desc, + void * host_ptr, + cl_int * errcode_ret) CL_API_SUFFIX__VERSION_3_0; + +#endif + +extern CL_API_ENTRY cl_int CL_API_CALL +clRetainMemObject(cl_mem memobj) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY cl_int CL_API_CALL +clReleaseMemObject(cl_mem memobj) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY cl_int CL_API_CALL +clGetSupportedImageFormats(cl_context context, + cl_mem_flags flags, + cl_mem_object_type image_type, + cl_uint num_entries, + cl_image_format * image_formats, + cl_uint * num_image_formats) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY cl_int CL_API_CALL +clGetMemObjectInfo(cl_mem memobj, + cl_mem_info param_name, + size_t param_value_size, + void * param_value, + size_t * param_value_size_ret) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY cl_int CL_API_CALL +clGetImageInfo(cl_mem image, + cl_image_info param_name, + size_t param_value_size, + void * param_value, + size_t * param_value_size_ret) CL_API_SUFFIX__VERSION_1_0; + +#ifdef CL_VERSION_2_0 + +extern CL_API_ENTRY cl_int CL_API_CALL +clGetPipeInfo(cl_mem pipe, + cl_pipe_info param_name, + size_t param_value_size, + void * param_value, + size_t * param_value_size_ret) CL_API_SUFFIX__VERSION_2_0; + +#endif + +#ifdef CL_VERSION_1_1 + +extern CL_API_ENTRY cl_int CL_API_CALL +clSetMemObjectDestructorCallback(cl_mem memobj, + void (CL_CALLBACK * pfn_notify)(cl_mem memobj, + void * user_data), + void * user_data) CL_API_SUFFIX__VERSION_1_1; + +#endif + +/* SVM Allocation APIs */ + +#ifdef CL_VERSION_2_0 + +extern CL_API_ENTRY void * CL_API_CALL +clSVMAlloc(cl_context context, + cl_svm_mem_flags flags, + size_t size, + cl_uint alignment) CL_API_SUFFIX__VERSION_2_0; + +extern CL_API_ENTRY void CL_API_CALL +clSVMFree(cl_context context, + void * svm_pointer) CL_API_SUFFIX__VERSION_2_0; + +#endif + +/* Sampler APIs */ + +#ifdef CL_VERSION_2_0 + +extern CL_API_ENTRY cl_sampler CL_API_CALL +clCreateSamplerWithProperties(cl_context context, + const cl_sampler_properties * sampler_properties, + cl_int * errcode_ret) CL_API_SUFFIX__VERSION_2_0; + +#endif + +extern CL_API_ENTRY cl_int CL_API_CALL +clRetainSampler(cl_sampler sampler) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY cl_int CL_API_CALL +clReleaseSampler(cl_sampler sampler) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY cl_int CL_API_CALL +clGetSamplerInfo(cl_sampler sampler, + cl_sampler_info param_name, + size_t param_value_size, + void * param_value, + size_t * param_value_size_ret) CL_API_SUFFIX__VERSION_1_0; + +/* Program Object APIs */ +extern CL_API_ENTRY cl_program CL_API_CALL +clCreateProgramWithSource(cl_context context, + cl_uint count, + const char ** strings, + const size_t * lengths, + cl_int * errcode_ret) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY cl_program CL_API_CALL +clCreateProgramWithBinary(cl_context context, + cl_uint num_devices, + const cl_device_id * device_list, + const size_t * lengths, + const unsigned char ** binaries, + cl_int * binary_status, + cl_int * errcode_ret) CL_API_SUFFIX__VERSION_1_0; + +#ifdef CL_VERSION_1_2 + +extern CL_API_ENTRY cl_program CL_API_CALL +clCreateProgramWithBuiltInKernels(cl_context context, + cl_uint num_devices, + const cl_device_id * device_list, + const char * kernel_names, + cl_int * errcode_ret) CL_API_SUFFIX__VERSION_1_2; + +#endif + +#ifdef CL_VERSION_2_1 + +extern CL_API_ENTRY cl_program CL_API_CALL +clCreateProgramWithIL(cl_context context, + const void* il, + size_t length, + cl_int* errcode_ret) CL_API_SUFFIX__VERSION_2_1; + +#endif + +extern CL_API_ENTRY cl_int CL_API_CALL +clRetainProgram(cl_program program) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY cl_int CL_API_CALL +clReleaseProgram(cl_program program) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY cl_int CL_API_CALL +clBuildProgram(cl_program program, + cl_uint num_devices, + const cl_device_id * device_list, + const char * options, + void (CL_CALLBACK * pfn_notify)(cl_program program, + void * user_data), + void * user_data) CL_API_SUFFIX__VERSION_1_0; + +#ifdef CL_VERSION_1_2 + +extern CL_API_ENTRY cl_int CL_API_CALL +clCompileProgram(cl_program program, + cl_uint num_devices, + const cl_device_id * device_list, + const char * options, + cl_uint num_input_headers, + const cl_program * input_headers, + const char ** header_include_names, + void (CL_CALLBACK * pfn_notify)(cl_program program, + void * user_data), + void * user_data) CL_API_SUFFIX__VERSION_1_2; + +extern CL_API_ENTRY cl_program CL_API_CALL +clLinkProgram(cl_context context, + cl_uint num_devices, + const cl_device_id * device_list, + const char * options, + cl_uint num_input_programs, + const cl_program * input_programs, + void (CL_CALLBACK * pfn_notify)(cl_program program, + void * user_data), + void * user_data, + cl_int * errcode_ret) CL_API_SUFFIX__VERSION_1_2; + +#endif + +#ifdef CL_VERSION_2_2 + +extern CL_API_ENTRY CL_API_PREFIX__VERSION_2_2_DEPRECATED cl_int CL_API_CALL +clSetProgramReleaseCallback(cl_program program, + void (CL_CALLBACK * pfn_notify)(cl_program program, + void * user_data), + void * user_data) CL_API_SUFFIX__VERSION_2_2_DEPRECATED; + +extern CL_API_ENTRY cl_int CL_API_CALL +clSetProgramSpecializationConstant(cl_program program, + cl_uint spec_id, + size_t spec_size, + const void* spec_value) CL_API_SUFFIX__VERSION_2_2; + +#endif + +#ifdef CL_VERSION_1_2 + +extern CL_API_ENTRY cl_int CL_API_CALL +clUnloadPlatformCompiler(cl_platform_id platform) CL_API_SUFFIX__VERSION_1_2; + +#endif + +extern CL_API_ENTRY cl_int CL_API_CALL +clGetProgramInfo(cl_program program, + cl_program_info param_name, + size_t param_value_size, + void * param_value, + size_t * param_value_size_ret) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY cl_int CL_API_CALL +clGetProgramBuildInfo(cl_program program, + cl_device_id device, + cl_program_build_info param_name, + size_t param_value_size, + void * param_value, + size_t * param_value_size_ret) CL_API_SUFFIX__VERSION_1_0; + +/* Kernel Object APIs */ +extern CL_API_ENTRY cl_kernel CL_API_CALL +clCreateKernel(cl_program program, + const char * kernel_name, + cl_int * errcode_ret) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY cl_int CL_API_CALL +clCreateKernelsInProgram(cl_program program, + cl_uint num_kernels, + cl_kernel * kernels, + cl_uint * num_kernels_ret) CL_API_SUFFIX__VERSION_1_0; + +#ifdef CL_VERSION_2_1 + +extern CL_API_ENTRY cl_kernel CL_API_CALL +clCloneKernel(cl_kernel source_kernel, + cl_int* errcode_ret) CL_API_SUFFIX__VERSION_2_1; + +#endif + +extern CL_API_ENTRY cl_int CL_API_CALL +clRetainKernel(cl_kernel kernel) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY cl_int CL_API_CALL +clReleaseKernel(cl_kernel kernel) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY cl_int CL_API_CALL +clSetKernelArg(cl_kernel kernel, + cl_uint arg_index, + size_t arg_size, + const void * arg_value) CL_API_SUFFIX__VERSION_1_0; + +#ifdef CL_VERSION_2_0 + +extern CL_API_ENTRY cl_int CL_API_CALL +clSetKernelArgSVMPointer(cl_kernel kernel, + cl_uint arg_index, + const void * arg_value) CL_API_SUFFIX__VERSION_2_0; + +extern CL_API_ENTRY cl_int CL_API_CALL +clSetKernelExecInfo(cl_kernel kernel, + cl_kernel_exec_info param_name, + size_t param_value_size, + const void * param_value) CL_API_SUFFIX__VERSION_2_0; + +#endif + +extern CL_API_ENTRY cl_int CL_API_CALL +clGetKernelInfo(cl_kernel kernel, + cl_kernel_info param_name, + size_t param_value_size, + void * param_value, + size_t * param_value_size_ret) CL_API_SUFFIX__VERSION_1_0; + +#ifdef CL_VERSION_1_2 + +extern CL_API_ENTRY cl_int CL_API_CALL +clGetKernelArgInfo(cl_kernel kernel, + cl_uint arg_indx, + cl_kernel_arg_info param_name, + size_t param_value_size, + void * param_value, + size_t * param_value_size_ret) CL_API_SUFFIX__VERSION_1_2; + +#endif + +extern CL_API_ENTRY cl_int CL_API_CALL +clGetKernelWorkGroupInfo(cl_kernel kernel, + cl_device_id device, + cl_kernel_work_group_info param_name, + size_t param_value_size, + void * param_value, + size_t * param_value_size_ret) CL_API_SUFFIX__VERSION_1_0; + +#ifdef CL_VERSION_2_1 + +extern CL_API_ENTRY cl_int CL_API_CALL +clGetKernelSubGroupInfo(cl_kernel kernel, + cl_device_id device, + cl_kernel_sub_group_info param_name, + size_t input_value_size, + const void* input_value, + size_t param_value_size, + void* param_value, + size_t* param_value_size_ret) CL_API_SUFFIX__VERSION_2_1; + +#endif + +/* Event Object APIs */ +extern CL_API_ENTRY cl_int CL_API_CALL +clWaitForEvents(cl_uint num_events, + const cl_event * event_list) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY cl_int CL_API_CALL +clGetEventInfo(cl_event event, + cl_event_info param_name, + size_t param_value_size, + void * param_value, + size_t * param_value_size_ret) CL_API_SUFFIX__VERSION_1_0; + +#ifdef CL_VERSION_1_1 + +extern CL_API_ENTRY cl_event CL_API_CALL +clCreateUserEvent(cl_context context, + cl_int * errcode_ret) CL_API_SUFFIX__VERSION_1_1; + +#endif + +extern CL_API_ENTRY cl_int CL_API_CALL +clRetainEvent(cl_event event) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY cl_int CL_API_CALL +clReleaseEvent(cl_event event) CL_API_SUFFIX__VERSION_1_0; + +#ifdef CL_VERSION_1_1 + +extern CL_API_ENTRY cl_int CL_API_CALL +clSetUserEventStatus(cl_event event, + cl_int execution_status) CL_API_SUFFIX__VERSION_1_1; + +extern CL_API_ENTRY cl_int CL_API_CALL +clSetEventCallback(cl_event event, + cl_int command_exec_callback_type, + void (CL_CALLBACK * pfn_notify)(cl_event event, + cl_int event_command_status, + void * user_data), + void * user_data) CL_API_SUFFIX__VERSION_1_1; + +#endif + +/* Profiling APIs */ +extern CL_API_ENTRY cl_int CL_API_CALL +clGetEventProfilingInfo(cl_event event, + cl_profiling_info param_name, + size_t param_value_size, + void * param_value, + size_t * param_value_size_ret) CL_API_SUFFIX__VERSION_1_0; + +/* Flush and Finish APIs */ +extern CL_API_ENTRY cl_int CL_API_CALL +clFlush(cl_command_queue command_queue) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY cl_int CL_API_CALL +clFinish(cl_command_queue command_queue) CL_API_SUFFIX__VERSION_1_0; + +/* Enqueued Commands APIs */ +extern CL_API_ENTRY cl_int CL_API_CALL +clEnqueueReadBuffer(cl_command_queue command_queue, + cl_mem buffer, + cl_bool blocking_read, + size_t offset, + size_t size, + void * ptr, + cl_uint num_events_in_wait_list, + const cl_event * event_wait_list, + cl_event * event) CL_API_SUFFIX__VERSION_1_0; + +#ifdef CL_VERSION_1_1 + +extern CL_API_ENTRY cl_int CL_API_CALL +clEnqueueReadBufferRect(cl_command_queue command_queue, + cl_mem buffer, + cl_bool blocking_read, + const size_t * buffer_origin, + const size_t * host_origin, + const size_t * region, + size_t buffer_row_pitch, + size_t buffer_slice_pitch, + size_t host_row_pitch, + size_t host_slice_pitch, + void * ptr, + cl_uint num_events_in_wait_list, + const cl_event * event_wait_list, + cl_event * event) CL_API_SUFFIX__VERSION_1_1; + +#endif + +extern CL_API_ENTRY cl_int CL_API_CALL +clEnqueueWriteBuffer(cl_command_queue command_queue, + cl_mem buffer, + cl_bool blocking_write, + size_t offset, + size_t size, + const void * ptr, + cl_uint num_events_in_wait_list, + const cl_event * event_wait_list, + cl_event * event) CL_API_SUFFIX__VERSION_1_0; + +#ifdef CL_VERSION_1_1 + +extern CL_API_ENTRY cl_int CL_API_CALL +clEnqueueWriteBufferRect(cl_command_queue command_queue, + cl_mem buffer, + cl_bool blocking_write, + const size_t * buffer_origin, + const size_t * host_origin, + const size_t * region, + size_t buffer_row_pitch, + size_t buffer_slice_pitch, + size_t host_row_pitch, + size_t host_slice_pitch, + const void * ptr, + cl_uint num_events_in_wait_list, + const cl_event * event_wait_list, + cl_event * event) CL_API_SUFFIX__VERSION_1_1; + +#endif + +#ifdef CL_VERSION_1_2 + +extern CL_API_ENTRY cl_int CL_API_CALL +clEnqueueFillBuffer(cl_command_queue command_queue, + cl_mem buffer, + const void * pattern, + size_t pattern_size, + size_t offset, + size_t size, + cl_uint num_events_in_wait_list, + const cl_event * event_wait_list, + cl_event * event) CL_API_SUFFIX__VERSION_1_2; + +#endif + +extern CL_API_ENTRY cl_int CL_API_CALL +clEnqueueCopyBuffer(cl_command_queue command_queue, + cl_mem src_buffer, + cl_mem dst_buffer, + size_t src_offset, + size_t dst_offset, + size_t size, + cl_uint num_events_in_wait_list, + const cl_event * event_wait_list, + cl_event * event) CL_API_SUFFIX__VERSION_1_0; + +#ifdef CL_VERSION_1_1 + +extern CL_API_ENTRY cl_int CL_API_CALL +clEnqueueCopyBufferRect(cl_command_queue command_queue, + cl_mem src_buffer, + cl_mem dst_buffer, + const size_t * src_origin, + const size_t * dst_origin, + const size_t * region, + size_t src_row_pitch, + size_t src_slice_pitch, + size_t dst_row_pitch, + size_t dst_slice_pitch, + cl_uint num_events_in_wait_list, + const cl_event * event_wait_list, + cl_event * event) CL_API_SUFFIX__VERSION_1_1; + +#endif + +extern CL_API_ENTRY cl_int CL_API_CALL +clEnqueueReadImage(cl_command_queue command_queue, + cl_mem image, + cl_bool blocking_read, + const size_t * origin, + const size_t * region, + size_t row_pitch, + size_t slice_pitch, + void * ptr, + cl_uint num_events_in_wait_list, + const cl_event * event_wait_list, + cl_event * event) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY cl_int CL_API_CALL +clEnqueueWriteImage(cl_command_queue command_queue, + cl_mem image, + cl_bool blocking_write, + const size_t * origin, + const size_t * region, + size_t input_row_pitch, + size_t input_slice_pitch, + const void * ptr, + cl_uint num_events_in_wait_list, + const cl_event * event_wait_list, + cl_event * event) CL_API_SUFFIX__VERSION_1_0; + +#ifdef CL_VERSION_1_2 + +extern CL_API_ENTRY cl_int CL_API_CALL +clEnqueueFillImage(cl_command_queue command_queue, + cl_mem image, + const void * fill_color, + const size_t * origin, + const size_t * region, + cl_uint num_events_in_wait_list, + const cl_event * event_wait_list, + cl_event * event) CL_API_SUFFIX__VERSION_1_2; + +#endif + +extern CL_API_ENTRY cl_int CL_API_CALL +clEnqueueCopyImage(cl_command_queue command_queue, + cl_mem src_image, + cl_mem dst_image, + const size_t * src_origin, + const size_t * dst_origin, + const size_t * region, + cl_uint num_events_in_wait_list, + const cl_event * event_wait_list, + cl_event * event) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY cl_int CL_API_CALL +clEnqueueCopyImageToBuffer(cl_command_queue command_queue, + cl_mem src_image, + cl_mem dst_buffer, + const size_t * src_origin, + const size_t * region, + size_t dst_offset, + cl_uint num_events_in_wait_list, + const cl_event * event_wait_list, + cl_event * event) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY cl_int CL_API_CALL +clEnqueueCopyBufferToImage(cl_command_queue command_queue, + cl_mem src_buffer, + cl_mem dst_image, + size_t src_offset, + const size_t * dst_origin, + const size_t * region, + cl_uint num_events_in_wait_list, + const cl_event * event_wait_list, + cl_event * event) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY void * CL_API_CALL +clEnqueueMapBuffer(cl_command_queue command_queue, + cl_mem buffer, + cl_bool blocking_map, + cl_map_flags map_flags, + size_t offset, + size_t size, + cl_uint num_events_in_wait_list, + const cl_event * event_wait_list, + cl_event * event, + cl_int * errcode_ret) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY void * CL_API_CALL +clEnqueueMapImage(cl_command_queue command_queue, + cl_mem image, + cl_bool blocking_map, + cl_map_flags map_flags, + const size_t * origin, + const size_t * region, + size_t * image_row_pitch, + size_t * image_slice_pitch, + cl_uint num_events_in_wait_list, + const cl_event * event_wait_list, + cl_event * event, + cl_int * errcode_ret) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY cl_int CL_API_CALL +clEnqueueUnmapMemObject(cl_command_queue command_queue, + cl_mem memobj, + void * mapped_ptr, + cl_uint num_events_in_wait_list, + const cl_event * event_wait_list, + cl_event * event) CL_API_SUFFIX__VERSION_1_0; + +#ifdef CL_VERSION_1_2 + +extern CL_API_ENTRY cl_int CL_API_CALL +clEnqueueMigrateMemObjects(cl_command_queue command_queue, + cl_uint num_mem_objects, + const cl_mem * mem_objects, + cl_mem_migration_flags flags, + cl_uint num_events_in_wait_list, + const cl_event * event_wait_list, + cl_event * event) CL_API_SUFFIX__VERSION_1_2; + +#endif + +extern CL_API_ENTRY cl_int CL_API_CALL +clEnqueueNDRangeKernel(cl_command_queue command_queue, + cl_kernel kernel, + cl_uint work_dim, + const size_t * global_work_offset, + const size_t * global_work_size, + const size_t * local_work_size, + cl_uint num_events_in_wait_list, + const cl_event * event_wait_list, + cl_event * event) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY cl_int CL_API_CALL +clEnqueueNativeKernel(cl_command_queue command_queue, + void (CL_CALLBACK * user_func)(void *), + void * args, + size_t cb_args, + cl_uint num_mem_objects, + const cl_mem * mem_list, + const void ** args_mem_loc, + cl_uint num_events_in_wait_list, + const cl_event * event_wait_list, + cl_event * event) CL_API_SUFFIX__VERSION_1_0; + +#ifdef CL_VERSION_1_2 + +extern CL_API_ENTRY cl_int CL_API_CALL +clEnqueueMarkerWithWaitList(cl_command_queue command_queue, + cl_uint num_events_in_wait_list, + const cl_event * event_wait_list, + cl_event * event) CL_API_SUFFIX__VERSION_1_2; + +extern CL_API_ENTRY cl_int CL_API_CALL +clEnqueueBarrierWithWaitList(cl_command_queue command_queue, + cl_uint num_events_in_wait_list, + const cl_event * event_wait_list, + cl_event * event) CL_API_SUFFIX__VERSION_1_2; + +#endif + +#ifdef CL_VERSION_2_0 + +extern CL_API_ENTRY cl_int CL_API_CALL +clEnqueueSVMFree(cl_command_queue command_queue, + cl_uint num_svm_pointers, + void * svm_pointers[], + void (CL_CALLBACK * pfn_free_func)(cl_command_queue queue, + cl_uint num_svm_pointers, + void * svm_pointers[], + void * user_data), + void * user_data, + cl_uint num_events_in_wait_list, + const cl_event * event_wait_list, + cl_event * event) CL_API_SUFFIX__VERSION_2_0; + +extern CL_API_ENTRY cl_int CL_API_CALL +clEnqueueSVMMemcpy(cl_command_queue command_queue, + cl_bool blocking_copy, + void * dst_ptr, + const void * src_ptr, + size_t size, + cl_uint num_events_in_wait_list, + const cl_event * event_wait_list, + cl_event * event) CL_API_SUFFIX__VERSION_2_0; + +extern CL_API_ENTRY cl_int CL_API_CALL +clEnqueueSVMMemFill(cl_command_queue command_queue, + void * svm_ptr, + const void * pattern, + size_t pattern_size, + size_t size, + cl_uint num_events_in_wait_list, + const cl_event * event_wait_list, + cl_event * event) CL_API_SUFFIX__VERSION_2_0; + +extern CL_API_ENTRY cl_int CL_API_CALL +clEnqueueSVMMap(cl_command_queue command_queue, + cl_bool blocking_map, + cl_map_flags flags, + void * svm_ptr, + size_t size, + cl_uint num_events_in_wait_list, + const cl_event * event_wait_list, + cl_event * event) CL_API_SUFFIX__VERSION_2_0; + +extern CL_API_ENTRY cl_int CL_API_CALL +clEnqueueSVMUnmap(cl_command_queue command_queue, + void * svm_ptr, + cl_uint num_events_in_wait_list, + const cl_event * event_wait_list, + cl_event * event) CL_API_SUFFIX__VERSION_2_0; + +#endif + +#ifdef CL_VERSION_2_1 + +extern CL_API_ENTRY cl_int CL_API_CALL +clEnqueueSVMMigrateMem(cl_command_queue command_queue, + cl_uint num_svm_pointers, + const void ** svm_pointers, + const size_t * sizes, + cl_mem_migration_flags flags, + cl_uint num_events_in_wait_list, + const cl_event * event_wait_list, + cl_event * event) CL_API_SUFFIX__VERSION_2_1; + +#endif + +#ifdef CL_VERSION_1_2 + +/* Extension function access + * + * Returns the extension function address for the given function name, + * or NULL if a valid function can not be found. The client must + * check to make sure the address is not NULL, before using or + * calling the returned function address. + */ +extern CL_API_ENTRY void * CL_API_CALL +clGetExtensionFunctionAddressForPlatform(cl_platform_id platform, + const char * func_name) CL_API_SUFFIX__VERSION_1_2; + +#endif + +#ifdef CL_USE_DEPRECATED_OPENCL_1_0_APIS + /* + * WARNING: + * This API introduces mutable state into the OpenCL implementation. It has been REMOVED + * to better facilitate thread safety. The 1.0 API is not thread safe. It is not tested by the + * OpenCL 1.1 conformance test, and consequently may not work or may not work dependably. + * It is likely to be non-performant. Use of this API is not advised. Use at your own risk. + * + * Software developers previously relying on this API are instructed to set the command queue + * properties when creating the queue, instead. + */ + extern CL_API_ENTRY cl_int CL_API_CALL + clSetCommandQueueProperty(cl_command_queue command_queue, + cl_command_queue_properties properties, + cl_bool enable, + cl_command_queue_properties * old_properties) CL_API_SUFFIX__VERSION_1_0_DEPRECATED; +#endif /* CL_USE_DEPRECATED_OPENCL_1_0_APIS */ + +/* Deprecated OpenCL 1.1 APIs */ +extern CL_API_ENTRY CL_API_PREFIX__VERSION_1_1_DEPRECATED cl_mem CL_API_CALL +clCreateImage2D(cl_context context, + cl_mem_flags flags, + const cl_image_format * image_format, + size_t image_width, + size_t image_height, + size_t image_row_pitch, + void * host_ptr, + cl_int * errcode_ret) CL_API_SUFFIX__VERSION_1_1_DEPRECATED; + +extern CL_API_ENTRY CL_API_PREFIX__VERSION_1_1_DEPRECATED cl_mem CL_API_CALL +clCreateImage3D(cl_context context, + cl_mem_flags flags, + const cl_image_format * image_format, + size_t image_width, + size_t image_height, + size_t image_depth, + size_t image_row_pitch, + size_t image_slice_pitch, + void * host_ptr, + cl_int * errcode_ret) CL_API_SUFFIX__VERSION_1_1_DEPRECATED; + +extern CL_API_ENTRY CL_API_PREFIX__VERSION_1_1_DEPRECATED cl_int CL_API_CALL +clEnqueueMarker(cl_command_queue command_queue, + cl_event * event) CL_API_SUFFIX__VERSION_1_1_DEPRECATED; + +extern CL_API_ENTRY CL_API_PREFIX__VERSION_1_1_DEPRECATED cl_int CL_API_CALL +clEnqueueWaitForEvents(cl_command_queue command_queue, + cl_uint num_events, + const cl_event * event_list) CL_API_SUFFIX__VERSION_1_1_DEPRECATED; + +extern CL_API_ENTRY CL_API_PREFIX__VERSION_1_1_DEPRECATED cl_int CL_API_CALL +clEnqueueBarrier(cl_command_queue command_queue) CL_API_SUFFIX__VERSION_1_1_DEPRECATED; + +extern CL_API_ENTRY CL_API_PREFIX__VERSION_1_1_DEPRECATED cl_int CL_API_CALL +clUnloadCompiler(void) CL_API_SUFFIX__VERSION_1_1_DEPRECATED; + +extern CL_API_ENTRY CL_API_PREFIX__VERSION_1_1_DEPRECATED void * CL_API_CALL +clGetExtensionFunctionAddress(const char * func_name) CL_API_SUFFIX__VERSION_1_1_DEPRECATED; + +/* Deprecated OpenCL 2.0 APIs */ +extern CL_API_ENTRY CL_API_PREFIX__VERSION_1_2_DEPRECATED cl_command_queue CL_API_CALL +clCreateCommandQueue(cl_context context, + cl_device_id device, + cl_command_queue_properties properties, + cl_int * errcode_ret) CL_API_SUFFIX__VERSION_1_2_DEPRECATED; + +extern CL_API_ENTRY CL_API_PREFIX__VERSION_1_2_DEPRECATED cl_sampler CL_API_CALL +clCreateSampler(cl_context context, + cl_bool normalized_coords, + cl_addressing_mode addressing_mode, + cl_filter_mode filter_mode, + cl_int * errcode_ret) CL_API_SUFFIX__VERSION_1_2_DEPRECATED; + +extern CL_API_ENTRY CL_API_PREFIX__VERSION_1_2_DEPRECATED cl_int CL_API_CALL +clEnqueueTask(cl_command_queue command_queue, + cl_kernel kernel, + cl_uint num_events_in_wait_list, + const cl_event * event_wait_list, + cl_event * event) CL_API_SUFFIX__VERSION_1_2_DEPRECATED; + +#endif /* !defined(CL_NO_CORE_PROTOTYPES) */ + +#ifdef __cplusplus +} +#endif + +#endif /* __OPENCL_CL_H */ diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/CL/cl_version.h b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/CL/cl_version.h new file mode 100644 index 0000000000000000000000000000000000000000..3844938d548b6751a68ec015c08dea6a9935860f --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/CL/cl_version.h @@ -0,0 +1,81 @@ +/******************************************************************************* + * Copyright (c) 2018-2020 The Khronos Group Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + ******************************************************************************/ + +#ifndef __CL_VERSION_H +#define __CL_VERSION_H + +/* Detect which version to target */ +#if !defined(CL_TARGET_OPENCL_VERSION) +#pragma message("cl_version.h: CL_TARGET_OPENCL_VERSION is not defined. Defaulting to 300 (OpenCL 3.0)") +#define CL_TARGET_OPENCL_VERSION 300 +#endif +#if CL_TARGET_OPENCL_VERSION != 100 && \ + CL_TARGET_OPENCL_VERSION != 110 && \ + CL_TARGET_OPENCL_VERSION != 120 && \ + CL_TARGET_OPENCL_VERSION != 200 && \ + CL_TARGET_OPENCL_VERSION != 210 && \ + CL_TARGET_OPENCL_VERSION != 220 && \ + CL_TARGET_OPENCL_VERSION != 300 +#pragma message("cl_version: CL_TARGET_OPENCL_VERSION is not a valid value (100, 110, 120, 200, 210, 220, 300). Defaulting to 300 (OpenCL 3.0)") +#undef CL_TARGET_OPENCL_VERSION +#define CL_TARGET_OPENCL_VERSION 300 +#endif + + +/* OpenCL Version */ +#if CL_TARGET_OPENCL_VERSION >= 300 && !defined(CL_VERSION_3_0) +#define CL_VERSION_3_0 1 +#endif +#if CL_TARGET_OPENCL_VERSION >= 220 && !defined(CL_VERSION_2_2) +#define CL_VERSION_2_2 1 +#endif +#if CL_TARGET_OPENCL_VERSION >= 210 && !defined(CL_VERSION_2_1) +#define CL_VERSION_2_1 1 +#endif +#if CL_TARGET_OPENCL_VERSION >= 200 && !defined(CL_VERSION_2_0) +#define CL_VERSION_2_0 1 +#endif +#if CL_TARGET_OPENCL_VERSION >= 120 && !defined(CL_VERSION_1_2) +#define CL_VERSION_1_2 1 +#endif +#if CL_TARGET_OPENCL_VERSION >= 110 && !defined(CL_VERSION_1_1) +#define CL_VERSION_1_1 1 +#endif +#if CL_TARGET_OPENCL_VERSION >= 100 && !defined(CL_VERSION_1_0) +#define CL_VERSION_1_0 1 +#endif + +/* Allow deprecated APIs for older OpenCL versions. */ +#if CL_TARGET_OPENCL_VERSION <= 220 && !defined(CL_USE_DEPRECATED_OPENCL_2_2_APIS) +#define CL_USE_DEPRECATED_OPENCL_2_2_APIS +#endif +#if CL_TARGET_OPENCL_VERSION <= 210 && !defined(CL_USE_DEPRECATED_OPENCL_2_1_APIS) +#define CL_USE_DEPRECATED_OPENCL_2_1_APIS +#endif +#if CL_TARGET_OPENCL_VERSION <= 200 && !defined(CL_USE_DEPRECATED_OPENCL_2_0_APIS) +#define CL_USE_DEPRECATED_OPENCL_2_0_APIS +#endif +#if CL_TARGET_OPENCL_VERSION <= 120 && !defined(CL_USE_DEPRECATED_OPENCL_1_2_APIS) +#define CL_USE_DEPRECATED_OPENCL_1_2_APIS +#endif +#if CL_TARGET_OPENCL_VERSION <= 110 && !defined(CL_USE_DEPRECATED_OPENCL_1_1_APIS) +#define CL_USE_DEPRECATED_OPENCL_1_1_APIS +#endif +#if CL_TARGET_OPENCL_VERSION <= 100 && !defined(CL_USE_DEPRECATED_OPENCL_1_0_APIS) +#define CL_USE_DEPRECATED_OPENCL_1_0_APIS +#endif + +#endif /* __CL_VERSION_H */ diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cooperative_groups/details/functional.h b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cooperative_groups/details/functional.h new file mode 100644 index 0000000000000000000000000000000000000000..0f151fe2c270421ba56e22935e84c4bf93790eff --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cooperative_groups/details/functional.h @@ -0,0 +1,212 @@ + /* Copyright 1993-2016 NVIDIA Corporation. All rights reserved. + * + * NOTICE TO LICENSEE: + * + * The source code and/or documentation ("Licensed Deliverables") are + * subject to NVIDIA intellectual property rights under U.S. and + * international Copyright laws. + * + * The Licensed Deliverables contained herein are PROPRIETARY and + * CONFIDENTIAL to NVIDIA and are 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. THEY ARE + * 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 are 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. + */ + +#ifndef _CG_FUNCTIONAL_H +#define _CG_FUNCTIONAL_H + +#include "info.h" +#include "helpers.h" + +#ifdef _CG_CPP11_FEATURES +#ifdef _CG_USE_CUDA_STL +# include +#endif + +_CG_BEGIN_NAMESPACE + +namespace details { +#ifdef _CG_USE_CUDA_STL + using cuda::std::plus; + using cuda::std::bit_and; + using cuda::std::bit_xor; + using cuda::std::bit_or; +#else + template struct plus {__device__ __forceinline__ Ty operator()(Ty arg1, Ty arg2) const {return arg1 + arg2;}}; + template struct bit_and {__device__ __forceinline__ Ty operator()(Ty arg1, Ty arg2) const {return arg1 & arg2;}}; + template struct bit_xor {__device__ __forceinline__ Ty operator()(Ty arg1, Ty arg2) const {return arg1 ^ arg2;}}; + template struct bit_or {__device__ __forceinline__ Ty operator()(Ty arg1, Ty arg2) const {return arg1 | arg2;}}; +#endif // _CG_USE_PLATFORM_STL +} // details + +template +struct plus : public details::plus {}; + +template +struct less { + __device__ __forceinline__ Ty operator()(Ty arg1, Ty arg2) const { + return (arg2 < arg1) ? arg2 : arg1; + } +}; + +template +struct greater { + __device__ __forceinline__ Ty operator()(Ty arg1, Ty arg2) const { + return (arg1 < arg2) ? arg2 : arg1; + } +}; + +template +struct bit_and : public details::bit_and {}; + +template +struct bit_xor : public details::bit_xor {}; + +template +struct bit_or : public details::bit_or {}; + +#if defined(_CG_HAS_STL_ATOMICS) +namespace details { + template + using _atomic_is_type_supported = _CG_STL_NAMESPACE::integral_constant::value && (sizeof(Ty) == 4 || sizeof(Ty) == 8)>; + + template struct _atomic_op_supported : public _CG_STL_NAMESPACE::false_type {}; + template struct _atomic_op_supported> : public _atomic_is_type_supported {}; + template struct _atomic_op_supported> : public _atomic_is_type_supported {}; + template struct _atomic_op_supported> : public _atomic_is_type_supported {}; + template struct _atomic_op_supported> : public _atomic_is_type_supported {}; + template struct _atomic_op_supported> : public _atomic_is_type_supported {}; + template struct _atomic_op_supported> : public _atomic_is_type_supported {}; + + template + _CG_QUALIFIER remove_qual atomic_cas_fallback(TyAtomic&& atomic, TyVal&& val, TyOp&& op) { + auto old = atomic.load(cuda::std::memory_order_relaxed); + while(!atomic.compare_exchange_weak(old, op(old, val), cuda::std::memory_order_relaxed)); + return old; + } + + template + struct op_picker; + + template + struct op_picker> { + template + _CG_STATIC_QUALIFIER TyVal atomic_update(TyAtomic& atomic, TyVal val) { + return atomic.fetch_add(val, cuda::std::memory_order_relaxed); + } + }; + + template + struct op_picker> { + template + _CG_STATIC_QUALIFIER TyVal atomic_update(TyAtomic& atomic, TyVal val) { + return atomic.fetch_min(val, cuda::std::memory_order_relaxed); + } + }; + + template + struct op_picker> { + template + _CG_STATIC_QUALIFIER TyVal atomic_update(TyAtomic& atomic, TyVal val) { + return atomic.fetch_max(val, cuda::std::memory_order_relaxed); + } + }; + + template + struct op_picker> { + template + _CG_STATIC_QUALIFIER TyVal atomic_update(TyAtomic& atomic, TyVal val) { + return atomic.fetch_and(val, cuda::std::memory_order_relaxed); + } + }; + + template + struct op_picker> { + template + _CG_STATIC_QUALIFIER TyVal atomic_update(TyAtomic& atomic, TyVal val) { + return atomic.fetch_xor(val, cuda::std::memory_order_relaxed); + } + }; + + template + struct op_picker> { + template + _CG_STATIC_QUALIFIER TyVal atomic_update(TyAtomic& atomic, TyVal val) { + return atomic.fetch_or(val, cuda::std::memory_order_relaxed); + } + }; + + template + struct atomic_update_dispatch {}; + + template<> + struct atomic_update_dispatch { + template + _CG_STATIC_QUALIFIER remove_qual atomic_update(TyAtomic& atomic, TyVal&& val, TyOp&& op) { + return atomic_cas_fallback(atomic, _CG_STL_NAMESPACE::forward(val), _CG_STL_NAMESPACE::forward(op)); + } + }; + + template<> + struct atomic_update_dispatch { + template + _CG_STATIC_QUALIFIER TyVal atomic_update(TyAtomic& atomic, TyVal val, TyOp&& op) { + using dispatch = op_picker>; + + return dispatch::atomic_update(atomic, val); + } + }; + + template + _CG_QUALIFIER remove_qual atomic_update(TyAtomic& atomic, TyVal&& val, TyOp&& op) { + using dispatch = atomic_update_dispatch<_atomic_op_supported>::value>; + + return dispatch::atomic_update(atomic, _CG_STL_NAMESPACE::forward(val), _CG_STL_NAMESPACE::forward(op)); + } + + template + _CG_QUALIFIER void atomic_store(TyAtomic& atomic, TyVal&& val) { + atomic.store(val, cuda::std::memory_order_relaxed); + } +} +#endif + +_CG_END_NAMESPACE + +#endif +#endif //_CG_FUNCTIONAL_H diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cooperative_groups/details/helpers.h b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cooperative_groups/details/helpers.h new file mode 100644 index 0000000000000000000000000000000000000000..1485d9f503daa8d518af75775f7a7a415cb031d4 --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cooperative_groups/details/helpers.h @@ -0,0 +1,693 @@ + /* Copyright 1993-2021 NVIDIA Corporation. All rights reserved. + * + * NOTICE TO LICENSEE: + * + * The source code and/or documentation ("Licensed Deliverables") are + * subject to NVIDIA intellectual property rights under U.S. and + * international Copyright laws. + * + * The Licensed Deliverables contained herein are PROPRIETARY and + * CONFIDENTIAL to NVIDIA and are 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. THEY ARE + * 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 are 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. + */ + +#ifndef _COOPERATIVE_GROUPS_HELPERS_H_ +# define _COOPERATIVE_GROUPS_HELPERS_H_ + +#include "info.h" +#include "sync.h" + +_CG_BEGIN_NAMESPACE + +namespace details { +#ifdef _CG_CPP11_FEATURES + template struct _is_float_or_half : public _CG_STL_NAMESPACE::is_floating_point {}; +# ifdef _CG_HAS_FP16_COLLECTIVE + template <> struct _is_float_or_half<__half> : public _CG_STL_NAMESPACE::true_type {}; + template <> struct _is_float_or_half<__half2> : public _CG_STL_NAMESPACE::true_type {}; +# endif + template + using is_float_or_half = _is_float_or_half::type>; + + // Non-STL utility templates + template + using remove_qual = typename _CG_STL_NAMESPACE::remove_cv::type>::type; + + template + using is_op_type_same = _CG_STL_NAMESPACE::is_same, remove_qual + >; +#endif + + template + _CG_STATIC_QUALIFIER TyTrunc vec3_to_linear(dim3 index, dim3 nIndex) { + return ((TyTrunc)index.z * nIndex.y * nIndex.x) + + ((TyTrunc)index.y * nIndex.x) + + (TyTrunc)index.x; + } + + namespace cta { + + _CG_STATIC_QUALIFIER void sync() + { + __barrier_sync(0); + } + + _CG_STATIC_QUALIFIER unsigned int num_threads() + { + return static_cast(blockDim.x * blockDim.y * blockDim.z); + } + + _CG_STATIC_QUALIFIER unsigned int thread_rank() + { + return vec3_to_linear(threadIdx, blockDim); + } + + _CG_STATIC_QUALIFIER dim3 group_index() + { + return dim3(blockIdx.x, blockIdx.y, blockIdx.z); + } + + _CG_STATIC_QUALIFIER dim3 thread_index() + { + return dim3(threadIdx.x, threadIdx.y, threadIdx.z); + } + + _CG_STATIC_QUALIFIER dim3 dim_threads() + { + return dim3(blockDim.x, blockDim.y, blockDim.z); + } + + // Legacy aliases + _CG_STATIC_QUALIFIER unsigned int size() + { + return num_threads(); + } + + _CG_STATIC_QUALIFIER dim3 block_dim() + { + return dim_threads(); + } + + }; + + class _coalesced_group_data_access { + public: + // Retrieve mask of coalesced groups and tiles + template + _CG_STATIC_QUALIFIER unsigned int get_mask(const TyGroup &group) { + return group.get_mask(); + } + + template + _CG_STATIC_QUALIFIER TyGroup construct_from_mask(unsigned int mask) { + return TyGroup(mask); + } + + template + _CG_STATIC_QUALIFIER void modify_meta_group(TyGroup &group, unsigned int mgRank, unsigned int mgSize) { + group._data.coalesced.metaGroupRank = mgRank; + group._data.coalesced.metaGroupSize = mgSize; + } + }; + + namespace tile { + template + struct _tile_helpers{ + _CG_STATIC_CONST_DECL unsigned int tileCount = TileCount; + _CG_STATIC_CONST_DECL unsigned int tileMask = TileMask; + _CG_STATIC_CONST_DECL unsigned int laneMask = LaneMask; + _CG_STATIC_CONST_DECL unsigned int shiftCount = ShiftCount; + }; + + template struct tile_helpers; + template <> struct tile_helpers<32> : public _tile_helpers<1, 0xFFFFFFFF, 0x1F, 5> {}; + template <> struct tile_helpers<16> : public _tile_helpers<2, 0x0000FFFF, 0x0F, 4> {}; + template <> struct tile_helpers<8> : public _tile_helpers<4, 0x000000FF, 0x07, 3> {}; + template <> struct tile_helpers<4> : public _tile_helpers<8, 0x0000000F, 0x03, 2> {}; + template <> struct tile_helpers<2> : public _tile_helpers<16, 0x00000003, 0x01, 1> {}; + template <> struct tile_helpers<1> : public _tile_helpers<32, 0x00000001, 0x00, 0> {}; + +#ifdef _CG_CPP11_FEATURES + namespace shfl { + /*********************************************************************************** + * Recursively Sliced Shuffle + * Purpose: + * Slices an input type a number of times into integral types so that shuffles + * are well defined + * Expectations: + * This object *should not* be used from a reinterpret_cast pointer unless + * some alignment guarantees can be met. Use a memcpy to guarantee that loads + * from the integral types stored within are aligned and correct. + **********************************************************************************/ + template + struct recursive_sliced_shuffle_helper; + + template + struct recursive_sliced_shuffle_helper { + int val; + + template + _CG_QUALIFIER void invoke_shuffle(const TyFn &shfl) { + val = shfl(val); + } + }; + + template + struct recursive_sliced_shuffle_helper { + int val; + recursive_sliced_shuffle_helper next; + + template + _CG_QUALIFIER void invoke_shuffle(const TyFn &shfl) { + val = shfl(val); + next.invoke_shuffle(shfl); + } + }; + } + + struct _memory_shuffle { + template + _CG_STATIC_QUALIFIER TyElem _shfl_internal(TyElem elem, const TyShflFn& fn) { + static_assert(sizeof(TyElem) <= 32, "Cooperative groups collectives are limited to types smaller than 32B"); + return TyElem{}; + } + + template > + _CG_STATIC_QUALIFIER TyRet shfl(TyElem&& elem, unsigned int gMask, unsigned int srcRank, unsigned int threads) { + auto shfl = [=](int val) -> int { + return 0; + }; + + return _shfl_internal(_CG_STL_NAMESPACE::forward(elem), shfl); + } + + template > + _CG_STATIC_QUALIFIER TyRet shfl_down(TyElem&& elem, unsigned int gMask, unsigned int delta, unsigned int threads) { + auto shfl = [=](int val) -> int { + return 0; + }; + + return _shfl_internal(_CG_STL_NAMESPACE::forward(elem), shfl); + } + + template > + _CG_STATIC_QUALIFIER TyRet shfl_up(TyElem&& elem, unsigned int gMask, unsigned int delta, unsigned int threads) { + auto shfl = [=](int val) -> int { + return 0; + }; + + return _shfl_internal(_CG_STL_NAMESPACE::forward(elem), shfl); + } + + template > + _CG_STATIC_QUALIFIER TyRet shfl_xor(TyElem&& elem, unsigned int gMask, unsigned int lMask, unsigned int threads) { + auto shfl = [=](int val) -> int { + return 0; + }; + + return _shfl_internal(_CG_STL_NAMESPACE::forward(elem), shfl); + } + }; + + /*********************************************************************************** + * Intrinsic Device Function Shuffle + * Purpose: + * Uses a shuffle helper that has characteristics best suited for moving + * elements between threads + * Expectations: + * Object given will be forced into an l-value type so that it can be used + * with a helper structure that reinterprets the data into intrinsic compatible + * types + * Notes: + * !! TyRet is required so that objects are returned by value and not as + * dangling references depending on the value category of the passed object + **********************************************************************************/ + struct _intrinsic_compat_shuffle { + template + using shfl_helper = shfl::recursive_sliced_shuffle_helper; + + template + _CG_STATIC_QUALIFIER TyElem _shfl_internal(TyElem elem, const TyShflFn& fn) { + static_assert(__is_trivially_copyable(TyElem), "Type is not compatible with device shuffle"); + shfl_helper helper; + memcpy(&helper, &elem, sizeof(TyElem)); + helper.invoke_shuffle(fn); + memcpy(&elem, &helper, sizeof(TyElem)); + return elem; + } + + template > + _CG_STATIC_QUALIFIER TyRet shfl(TyElem&& elem, unsigned int gMask, unsigned int srcRank, unsigned int threads) { + auto shfl = [=](int val) -> int { + return __shfl_sync(gMask, val, srcRank, threads); + }; + + return _shfl_internal(_CG_STL_NAMESPACE::forward(elem), shfl); + } + + template > + _CG_STATIC_QUALIFIER TyRet shfl_down(TyElem&& elem, unsigned int gMask, unsigned int delta, unsigned int threads) { + auto shfl = [=](int val) -> int { + return __shfl_down_sync(gMask, val, delta, threads); + }; + + return _shfl_internal(_CG_STL_NAMESPACE::forward(elem), shfl); + } + + template > + _CG_STATIC_QUALIFIER TyRet shfl_up(TyElem&& elem, unsigned int gMask, unsigned int delta, unsigned int threads) { + auto shfl = [=](int val) -> int { + return __shfl_up_sync(gMask, val, delta, threads); + }; + + return _shfl_internal(_CG_STL_NAMESPACE::forward(elem), shfl); + } + + template > + _CG_STATIC_QUALIFIER TyRet shfl_xor(TyElem&& elem, unsigned int gMask, unsigned int lMask, unsigned int threads) { + auto shfl = [=](int val) -> int { + return __shfl_xor_sync(gMask, val, lMask, threads); + }; + + return _shfl_internal(_CG_STL_NAMESPACE::forward(elem), shfl); + } + }; + + struct _native_shuffle { + template + _CG_STATIC_QUALIFIER TyElem shfl( + TyElem elem, unsigned int gMask, unsigned int srcRank, unsigned int threads) { + return static_cast(__shfl_sync(gMask, elem, srcRank, threads)); + } + + template + _CG_STATIC_QUALIFIER TyElem shfl_down( + TyElem elem, unsigned int gMask, unsigned int delta, unsigned int threads) { + return static_cast(__shfl_down_sync(gMask, elem, delta, threads)); + } + + template + _CG_STATIC_QUALIFIER TyElem shfl_up( + TyElem elem, unsigned int gMask, unsigned int delta, unsigned int threads) { + return static_cast(__shfl_up_sync(gMask, elem, delta, threads)); + } + + template + _CG_STATIC_QUALIFIER TyElem shfl_xor( + TyElem elem, unsigned int gMask, unsigned int lMask, unsigned int threads) { + return static_cast(__shfl_xor_sync(gMask, elem, lMask, threads)); + } + }; + + // Almost all arithmetic types are supported by native shuffle + // Vector types are the exception + template + using use_native_shuffle = _CG_STL_NAMESPACE::integral_constant< + bool, + _CG_STL_NAMESPACE::is_integral< + remove_qual>::value || + details::is_float_or_half< + remove_qual>::value + >; + + constexpr unsigned long long _MemoryShuffleCutoff = 32; + + template ::value, + bool InMem = (sizeof(TyElem) > _MemoryShuffleCutoff)> + struct shuffle_dispatch; + + template + struct shuffle_dispatch : public _native_shuffle {}; + + template + struct shuffle_dispatch : public _intrinsic_compat_shuffle {}; + + template + struct shuffle_dispatch : public _memory_shuffle {}; + +#endif //_CG_CPP11_FEATURES + }; + + namespace multi_grid { + struct multi_grid_functions; + }; + + namespace grid { + _CG_STATIC_QUALIFIER unsigned int barrier_arrive(unsigned int *bar) { + return details::sync_grids_arrive(bar); + } + + _CG_STATIC_QUALIFIER void barrier_wait(unsigned int token, unsigned int *bar) { + details::sync_grids_wait(token, bar); + } + + _CG_STATIC_QUALIFIER void sync(unsigned int *bar) { + unsigned int token = details::sync_grids_arrive(bar); + details::sync_grids_wait(token, bar); + } + + _CG_STATIC_QUALIFIER unsigned long long num_blocks() + { + // grid.y * grid.z -> [max(65535) * max(65535)] fits within 4b, promote after multiplication + // grid.x * (grid.y * grid.z) -> [max(2^31-1) * max(65535 * 65535)] exceeds 4b, promote before multiplication + return (unsigned long long)gridDim.x * (gridDim.y * gridDim.z); + } + + _CG_STATIC_QUALIFIER unsigned long long num_threads() + { + return num_blocks() * cta::num_threads(); + } + + _CG_STATIC_QUALIFIER unsigned long long block_rank() + { + return vec3_to_linear(blockIdx, gridDim); + } + + _CG_STATIC_QUALIFIER unsigned long long thread_rank() + { + return block_rank() * cta::num_threads() + cta::thread_rank(); + } + + _CG_STATIC_QUALIFIER dim3 dim_blocks() + { + return dim3(gridDim.x, gridDim.y, gridDim.z); + } + + _CG_STATIC_QUALIFIER dim3 block_index() + { + return dim3(blockIdx.x, blockIdx.y, blockIdx.z); + } + + _CG_STATIC_QUALIFIER dim3 dim_threads() + { + return dim3(gridDim.x * blockDim.x, gridDim.y * blockDim.y, gridDim.z * blockDim.z); + } + + _CG_STATIC_QUALIFIER dim3 thread_index() + { + return dim3(blockIdx.x * blockDim.x + threadIdx.x, + blockIdx.y * blockDim.y + threadIdx.y, + blockIdx.z * blockDim.z + threadIdx.z); + } + +#if defined(_CG_HAS_CLUSTER_GROUP) + _CG_STATIC_QUALIFIER dim3 dim_clusters() { + return __clusterGridDimInClusters(); + } + + _CG_STATIC_QUALIFIER unsigned long long num_clusters() { + const dim3 dimClusters = dim_clusters(); + return dimClusters.x * dimClusters.y * dimClusters.z; + } + + _CG_STATIC_QUALIFIER dim3 cluster_index() { + return __clusterIdx(); + } + + _CG_STATIC_QUALIFIER unsigned long long cluster_rank() { + return vec3_to_linear(cluster_index(), dim_clusters()); + } +#endif + + // Legacy aliases + _CG_STATIC_QUALIFIER unsigned long long size() + { + return num_threads(); + } + + _CG_STATIC_QUALIFIER dim3 grid_dim() + { + return dim_blocks(); + } + }; + + +#if defined(_CG_HAS_MULTI_GRID_GROUP) + + namespace multi_grid { + _CG_STATIC_QUALIFIER unsigned long long get_intrinsic_handle() + { +#if defined(__CUDACC_RDC__) || defined(__CUDACC_EWP__) + //this function is defined in device runtime library + //which requires separate compilation mode (__CUDACC_RDC__) + //or extended whole program mode (__CUDACC_EWP__) + return (cudaCGGetIntrinsicHandle(cudaCGScopeMultiGrid)); +#else /* !(__CUDACC_RDC__ || __CUDACC_EWP__) */ + return 0; +#endif /* __CUDACC_RDC__ || __CUDACC_EWP__ */ + } + + _CG_STATIC_QUALIFIER void sync(const unsigned long long handle) + { +#if defined(__CUDACC_RDC__) || defined(__CUDACC_EWP__) + //this function is defined in device runtime library + //which requires separate compilation mode (__CUDACC_RDC__) + //or extended whole program mode (__CUDACC_EWP__) + cudaError_t err = cudaCGSynchronize(handle, 0); +#endif /* __CUDACC_RDC__ || __CUDACC_EWP__ */ + } + + _CG_STATIC_QUALIFIER unsigned int size(const unsigned long long handle) + { + unsigned int numThreads = 0; +#if defined(__CUDACC_RDC__) || defined(__CUDACC_EWP__) + //this function is defined in device runtime library + //which requires separate compilation mode (__CUDACC_RDC__) + //or extended whole program mode (__CUDACC_EWP__) + cudaCGGetSize(&numThreads, NULL, handle); +#endif /* __CUDACC_RDC__ || __CUDACC_EWP__ */ + return numThreads; + } + + _CG_STATIC_QUALIFIER unsigned int thread_rank(const unsigned long long handle) + { + unsigned int threadRank = 0; +#if defined(__CUDACC_RDC__) || defined(__CUDACC_EWP__) + //this function is defined in device runtime library + //which requires separate compilation mode (__CUDACC_RDC__) + //or extended whole program mode (__CUDACC_EWP__) + cudaCGGetRank(&threadRank, NULL, handle); +#endif /* __CUDACC_RDC__ || __CUDACC_EWP__ */ + return threadRank; + } + + _CG_STATIC_QUALIFIER unsigned int grid_rank(const unsigned long long handle) + { + unsigned int gridRank = 0; +#if defined(__CUDACC_RDC__) || defined(__CUDACC_EWP__) + //this function is defined in device runtime library + //which requires separate compilation mode (__CUDACC_RDC__) + //or extended whole program mode (__CUDACC_EWP__) + cudaCGGetRank(NULL, &gridRank, handle); +#endif /* __CUDACC_RDC__ || __CUDACC_EWP__ */ + return gridRank; + } + + _CG_STATIC_QUALIFIER unsigned int num_grids(const unsigned long long handle) + { + unsigned int numGrids = 0; +#if defined(__CUDACC_RDC__) || defined(__CUDACC_EWP__) + //this function is defined in device runtime library + //which requires separate compilation mode (__CUDACC_RDC__) + //or extended whole program mode (__CUDACC_EWP__) + cudaCGGetSize(NULL, &numGrids, handle); +#endif /* __CUDACC_RDC__ || __CUDACC_EWP__ */ + return numGrids; + } + +# ifdef _CG_CPP11_FEATURES + struct multi_grid_functions { + decltype(multi_grid::get_intrinsic_handle) *get_intrinsic_handle; + decltype(multi_grid::sync) *sync; + decltype(multi_grid::size) *size; + decltype(multi_grid::thread_rank) *thread_rank; + decltype(multi_grid::grid_rank) *grid_rank; + decltype(multi_grid::num_grids) *num_grids; + }; + + template + _CG_STATIC_QUALIFIER const multi_grid_functions* load_grid_intrinsics() { + __constant__ static const multi_grid_functions mgf { + &multi_grid::get_intrinsic_handle, + &multi_grid::sync, + &multi_grid::size, + &multi_grid::thread_rank, + &multi_grid::grid_rank, + &multi_grid::num_grids + }; + + return &mgf; + } +# endif + }; +#endif + +#if defined(_CG_HAS_CLUSTER_GROUP) + namespace cluster { + + _CG_STATIC_QUALIFIER bool isReal() + { + return __clusterDimIsSpecified(); + } + + _CG_STATIC_QUALIFIER void barrier_arrive() + { + __cluster_barrier_arrive(); + } + + _CG_STATIC_QUALIFIER void barrier_wait() + { + __cluster_barrier_wait(); + } + + _CG_STATIC_QUALIFIER void sync() + { + barrier_arrive(); + barrier_wait(); + } + + _CG_STATIC_QUALIFIER unsigned int query_shared_rank(const void *addr) + { + return __cluster_query_shared_rank(addr); + } + + template + _CG_STATIC_QUALIFIER T* map_shared_rank(T *addr, int rank) + { + return static_cast(__cluster_map_shared_rank(addr, rank)); + } + + _CG_STATIC_QUALIFIER dim3 block_index() + { + return __clusterRelativeBlockIdx(); + } + + _CG_STATIC_QUALIFIER unsigned int block_rank() + { + return __clusterRelativeBlockRank(); + } + + _CG_STATIC_QUALIFIER dim3 thread_index() + { + const dim3 blockIndex = block_index(); + return dim3(blockIndex.x * blockDim.x + threadIdx.x, + blockIndex.y * blockDim.y + threadIdx.y, + blockIndex.z * blockDim.z + threadIdx.z); + } + + _CG_STATIC_QUALIFIER unsigned int thread_rank() + { + return block_rank() * cta::num_threads() + cta::thread_rank(); + } + + _CG_STATIC_QUALIFIER dim3 dim_blocks() + { + return __clusterDim(); + } + + _CG_STATIC_QUALIFIER unsigned int num_blocks() + { + return __clusterSizeInBlocks(); + } + + _CG_STATIC_QUALIFIER dim3 dim_threads() + { + const dim3 dimBlocks = dim_blocks(); + const unsigned int x = dimBlocks.x * blockDim.x; + const unsigned int y = dimBlocks.y * blockDim.y; + const unsigned int z = dimBlocks.z * blockDim.z; + return dim3(x, y, z); + } + + _CG_STATIC_QUALIFIER unsigned int num_threads() + { + return num_blocks() * cta::num_threads(); + } + + }; +#endif + + _CG_STATIC_QUALIFIER unsigned int laneid() + { + unsigned int laneid; + asm ("mov.u32 %0, %%laneid;" : "=r"(laneid)); + return laneid; + } + + _CG_STATIC_QUALIFIER unsigned int lanemask32_eq() + { + unsigned int lanemask32_eq; + asm ("mov.u32 %0, %%lanemask_eq;" : "=r"(lanemask32_eq)); + return (lanemask32_eq); + } + + _CG_STATIC_QUALIFIER unsigned int lanemask32_lt() + { + unsigned int lanemask32_lt; + asm ("mov.u32 %0, %%lanemask_lt;" : "=r"(lanemask32_lt)); + return (lanemask32_lt); + } + + _CG_STATIC_QUALIFIER void abort() + { + _CG_ABORT(); + } + + template + _CG_QUALIFIER void assert_if_not_arithmetic() { +#ifdef _CG_CPP11_FEATURES + static_assert( + _CG_STL_NAMESPACE::is_integral::value || + details::is_float_or_half::value, + "Error: Ty is neither integer or float" + ); +#endif //_CG_CPP11_FEATURES + } + +#ifdef _CG_CPP11_FEATURES + _CG_STATIC_QUALIFIER constexpr unsigned int log2(unsigned int x) { + return x == 1 ? 0 : 1 + log2(x / 2); + } +#endif //_CG_CPP11_FEATURES + +}; // !Namespace internal + +_CG_END_NAMESPACE + +#endif /* !_COOPERATIVE_GROUPS_HELPERS_H_ */ diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cooperative_groups/details/partitioning.h b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cooperative_groups/details/partitioning.h new file mode 100644 index 0000000000000000000000000000000000000000..9c219756c594c87be85a0a154cfa5579241a861f --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cooperative_groups/details/partitioning.h @@ -0,0 +1,159 @@ +/* + * Copyright 1993-2016 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. + */ + +#ifndef _CG_PARTITIONING_H +#define _CG_PARTITIONING_H + +#include "info.h" +#include "helpers.h" + +_CG_BEGIN_NAMESPACE + +namespace details { + + template + _CG_STATIC_QUALIFIER coalesced_group _binary_partition(const TyGroup &tile, bool pred) { + const unsigned int fullMask = ~0u; + + unsigned int thisMask = _coalesced_group_data_access::get_mask(tile); + unsigned int predMask = pred ? 0 : fullMask; + unsigned int setMask = __ballot_sync(thisMask, pred); + + if (setMask == thisMask || setMask == 0) { + coalesced_group subTile = _coalesced_group_data_access::construct_from_mask(thisMask); + _coalesced_group_data_access::modify_meta_group(subTile, 0, 1); + return subTile; + } + else { + unsigned int subMask = thisMask & (setMask ^ predMask); + coalesced_group subTile = _coalesced_group_data_access::construct_from_mask(subMask); + _coalesced_group_data_access::modify_meta_group(subTile, pred, 2); + return subTile; + } + } + +#if defined(_CG_HAS_MATCH_COLLECTIVE) && defined(_CG_CPP11_FEATURES) + template + struct _labeled_partition_dispatch { + template + _CG_QUALIFIER coalesced_group operator()(const TyGroup &tile, TyPredicate pred) { + unsigned int thisMask = _coalesced_group_data_access::get_mask(tile); + unsigned int thisBias = __ffs(thisMask) - 1; // Subtract 1 to index properly from [1-32] + unsigned int subMask = __match_any_sync(thisMask, pred); + + coalesced_group subTile = _coalesced_group_data_access::construct_from_mask(subMask); + + int leaderLaneId = subTile.shfl(details::laneid(), 0); + + bool isLeader = !subTile.thread_rank(); + unsigned int leaderMask = __ballot_sync(thisMask, isLeader); + unsigned int tileRank = __fns(leaderMask, leaderLaneId, 0) - thisBias; + + _coalesced_group_data_access::modify_meta_group(subTile, tileRank, __popc(leaderMask)); + + return subTile; + } + }; + + template <> + struct _labeled_partition_dispatch { + template + _CG_QUALIFIER coalesced_group operator()(const TyGroup &tile, bool pred) { + return _binary_partition(tile, pred); + } + }; + + template + struct _labeled_partition_dispatch { + template + _CG_QUALIFIER coalesced_group operator()(const TyGroup &tile, TyPredicate* pred) { + auto impl = _labeled_partition_dispatch(); + return impl(tile, reinterpret_cast(pred)); + } + }; +#endif +}; // namespace details + +_CG_STATIC_QUALIFIER coalesced_group binary_partition(const coalesced_group &tile, bool pred) { + return details::_binary_partition(tile, pred); +} + +template +_CG_STATIC_QUALIFIER coalesced_group binary_partition(const thread_block_tile &tile, bool pred) { +#ifdef _CG_CPP11_FEATURES + static_assert(Size <= 32, "Binary partition is available only for tiles of size smaller or equal to 32"); +#endif + return details::_binary_partition(tile, pred); +} + + +#if defined(_CG_HAS_MATCH_COLLECTIVE) && defined(_CG_CPP11_FEATURES) +template +_CG_STATIC_QUALIFIER coalesced_group labeled_partition(const coalesced_group &tile, TyPredicate pred) { + static_assert(_CG_STL_NAMESPACE::is_integral::value || + _CG_STL_NAMESPACE::is_pointer::value, + "labeled_partition predicate must be an integral or pointer type"); + auto dispatch = details::_labeled_partition_dispatch>(); + return dispatch(tile, pred); +} + +template +_CG_STATIC_QUALIFIER coalesced_group labeled_partition(const thread_block_tile &tile, TyPredicate pred) { + static_assert(_CG_STL_NAMESPACE::is_integral::value || + _CG_STL_NAMESPACE::is_pointer::value, + "labeled_partition predicate must be an integral or pointer type"); + static_assert(Size <= 32, "Labeled partition is available only for tiles of size smaller or equal to 32"); + auto dispatch = details::_labeled_partition_dispatch>(); + return dispatch(tile, pred); +} +#endif + +_CG_END_NAMESPACE + +#endif // _CG_PARTITIONING_H diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/agent/agent_merge_sort.cuh b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/agent/agent_merge_sort.cuh new file mode 100644 index 0000000000000000000000000000000000000000..2e994dd97e125d1594751bdc51677da0c699001d --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/agent/agent_merge_sort.cuh @@ -0,0 +1,750 @@ +/****************************************************************************** + * Copyright (c) 2011-2021, NVIDIA CORPORATION. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the NVIDIA CORPORATION nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ******************************************************************************/ + +#pragma once + +#include "../config.cuh" +#include "../util_type.cuh" +#include "../util_namespace.cuh" +#include "../block/block_load.cuh" +#include "../block/block_store.cuh" +#include "../block/block_merge_sort.cuh" + +#include + +CUB_NAMESPACE_BEGIN + + +template < + int _BLOCK_THREADS, + int _ITEMS_PER_THREAD = 1, + cub::BlockLoadAlgorithm _LOAD_ALGORITHM = cub::BLOCK_LOAD_DIRECT, + cub::CacheLoadModifier _LOAD_MODIFIER = cub::LOAD_LDG, + cub::BlockStoreAlgorithm _STORE_ALGORITHM = cub::BLOCK_STORE_DIRECT> +struct AgentMergeSortPolicy +{ + static constexpr int BLOCK_THREADS = _BLOCK_THREADS; + static constexpr int ITEMS_PER_THREAD = _ITEMS_PER_THREAD; + static constexpr int ITEMS_PER_TILE = BLOCK_THREADS * ITEMS_PER_THREAD; + + static constexpr cub::BlockLoadAlgorithm LOAD_ALGORITHM = _LOAD_ALGORITHM; + static constexpr cub::CacheLoadModifier LOAD_MODIFIER = _LOAD_MODIFIER; + static constexpr cub::BlockStoreAlgorithm STORE_ALGORITHM = _STORE_ALGORITHM; +}; + +/// \brief This agent is responsible for the initial in-tile sorting. +template +struct AgentBlockSort +{ + //--------------------------------------------------------------------- + // Types and constants + //--------------------------------------------------------------------- + + static constexpr bool KEYS_ONLY = std::is_same::value; + + using BlockMergeSortT = + BlockMergeSort; + + using KeysLoadIt = typename THRUST_NS_QUALIFIER::cuda_cub::core::LoadIterator::type; + using ItemsLoadIt = typename THRUST_NS_QUALIFIER::cuda_cub::core::LoadIterator::type; + + using BlockLoadKeys = typename cub::BlockLoadType::type; + using BlockLoadItems = typename cub::BlockLoadType::type; + + using BlockStoreKeysIt = typename cub::BlockStoreType::type; + using BlockStoreItemsIt = typename cub::BlockStoreType::type; + using BlockStoreKeysRaw = typename cub::BlockStoreType::type; + using BlockStoreItemsRaw = typename cub::BlockStoreType::type; + + union _TempStorage + { + typename BlockLoadKeys::TempStorage load_keys; + typename BlockLoadItems::TempStorage load_items; + typename BlockStoreKeysIt::TempStorage store_keys_it; + typename BlockStoreItemsIt::TempStorage store_items_it; + typename BlockStoreKeysRaw::TempStorage store_keys_raw; + typename BlockStoreItemsRaw::TempStorage store_items_raw; + typename BlockMergeSortT::TempStorage block_merge; + }; + + /// Alias wrapper allowing storage to be unioned + struct TempStorage : Uninitialized<_TempStorage> {}; + + static constexpr int BLOCK_THREADS = Policy::BLOCK_THREADS; + static constexpr int ITEMS_PER_THREAD = Policy::ITEMS_PER_THREAD; + static constexpr int ITEMS_PER_TILE = Policy::ITEMS_PER_TILE; + static constexpr int SHARED_MEMORY_SIZE = + static_cast(sizeof(TempStorage)); + + //--------------------------------------------------------------------- + // Per thread data + //--------------------------------------------------------------------- + + bool ping; + _TempStorage &storage; + KeysLoadIt keys_in; + ItemsLoadIt items_in; + OffsetT keys_count; + KeyIteratorT keys_out_it; + ValueIteratorT items_out_it; + KeyT *keys_out_raw; + ValueT *items_out_raw; + CompareOpT compare_op; + + __device__ __forceinline__ AgentBlockSort(bool ping_, + TempStorage &storage_, + KeysLoadIt keys_in_, + ItemsLoadIt items_in_, + OffsetT keys_count_, + KeyIteratorT keys_out_it_, + ValueIteratorT items_out_it_, + KeyT *keys_out_raw_, + ValueT *items_out_raw_, + CompareOpT compare_op_) + : ping(ping_) + , storage(storage_.Alias()) + , keys_in(keys_in_) + , items_in(items_in_) + , keys_count(keys_count_) + , keys_out_it(keys_out_it_) + , items_out_it(items_out_it_) + , keys_out_raw(keys_out_raw_) + , items_out_raw(items_out_raw_) + , compare_op(compare_op_) + { + } + + __device__ __forceinline__ void Process() + { + auto tile_idx = static_cast(blockIdx.x); + auto num_tiles = static_cast(gridDim.x); + auto tile_base = tile_idx * ITEMS_PER_TILE; + int items_in_tile = (cub::min)(keys_count - tile_base, int{ITEMS_PER_TILE}); + + if (tile_idx < num_tiles - 1) + { + consume_tile(tile_base, ITEMS_PER_TILE); + } + else + { + consume_tile(tile_base, items_in_tile); + } + } + + template + __device__ __forceinline__ void consume_tile(OffsetT tile_base, + int num_remaining) + { + ValueT items_local[ITEMS_PER_THREAD]; + if (!KEYS_ONLY) + { + if (IS_LAST_TILE) + { + BlockLoadItems(storage.load_items) + .Load(items_in + tile_base, + items_local, + num_remaining, + *(items_in + tile_base)); + } + else + { + BlockLoadItems(storage.load_items).Load(items_in + tile_base, items_local); + } + + CTA_SYNC(); + } + + KeyT keys_local[ITEMS_PER_THREAD]; + if (IS_LAST_TILE) + { + BlockLoadKeys(storage.load_keys) + .Load(keys_in + tile_base, + keys_local, + num_remaining, + *(keys_in + tile_base)); + } + else + { + BlockLoadKeys(storage.load_keys) + .Load(keys_in + tile_base, keys_local); + } + + CTA_SYNC(); + + if (IS_LAST_TILE) + { + BlockMergeSortT(storage.block_merge) + .Sort(keys_local, items_local, compare_op, num_remaining, keys_local[0]); + } + else + { + BlockMergeSortT(storage.block_merge).Sort(keys_local, items_local, compare_op); + } + + CTA_SYNC(); + + if (ping) + { + if (IS_LAST_TILE) + { + BlockStoreKeysIt(storage.store_keys_it) + .Store(keys_out_it + tile_base, keys_local, num_remaining); + } + else + { + BlockStoreKeysIt(storage.store_keys_it) + .Store(keys_out_it + tile_base, keys_local); + } + + if (!KEYS_ONLY) + { + CTA_SYNC(); + + if (IS_LAST_TILE) + { + BlockStoreItemsIt(storage.store_items_it) + .Store(items_out_it + tile_base, items_local, num_remaining); + } + else + { + BlockStoreItemsIt(storage.store_items_it) + .Store(items_out_it + tile_base, items_local); + } + } + } + else + { + if (IS_LAST_TILE) + { + BlockStoreKeysRaw(storage.store_keys_raw) + .Store(keys_out_raw + tile_base, keys_local, num_remaining); + } + else + { + BlockStoreKeysRaw(storage.store_keys_raw) + .Store(keys_out_raw + tile_base, keys_local); + } + + if (!KEYS_ONLY) + { + CTA_SYNC(); + + if (IS_LAST_TILE) + { + BlockStoreItemsRaw(storage.store_items_raw) + .Store(items_out_raw + tile_base, items_local, num_remaining); + } + else + { + BlockStoreItemsRaw(storage.store_items_raw) + .Store(items_out_raw + tile_base, items_local); + } + } + } + } +}; + +/** + * \brief This agent is responsible for partitioning a merge path into equal segments + * + * There are two sorted arrays to be merged into one array. If the first array + * is partitioned between parallel workers by slicing it into ranges of equal + * size, there could be a significant workload imbalance. The imbalance is + * caused by the fact that the distribution of elements from the second array + * is unknown beforehand. Instead, the MergePath is partitioned between workers. + * This approach guarantees an equal amount of work being assigned to each worker. + * + * This approach is outlined in the paper: + * Odeh et al, "Merge Path - Parallel Merging Made Simple" + * doi:10.1109/IPDPSW.2012.202 + */ +template < + typename KeyIteratorT, + typename OffsetT, + typename CompareOpT, + typename KeyT> +struct AgentPartition +{ + bool ping; + KeyIteratorT keys_ping; + KeyT *keys_pong; + OffsetT keys_count; + OffsetT partition_idx; + OffsetT *merge_partitions; + CompareOpT compare_op; + OffsetT target_merged_tiles_number; + int items_per_tile; + + __device__ __forceinline__ AgentPartition(bool ping, + KeyIteratorT keys_ping, + KeyT *keys_pong, + OffsetT keys_count, + OffsetT partition_idx, + OffsetT *merge_partitions, + CompareOpT compare_op, + OffsetT target_merged_tiles_number, + int items_per_tile) + : ping(ping) + , keys_ping(keys_ping) + , keys_pong(keys_pong) + , keys_count(keys_count) + , partition_idx(partition_idx) + , merge_partitions(merge_partitions) + , compare_op(compare_op) + , target_merged_tiles_number(target_merged_tiles_number) + , items_per_tile(items_per_tile) + {} + + __device__ __forceinline__ void Process() + { + OffsetT merged_tiles_number = target_merged_tiles_number / 2; + + // target_merged_tiles_number is a power of two. + OffsetT mask = target_merged_tiles_number - 1; + + // The first tile number in the tiles group being merged, equal to: + // target_merged_tiles_number * (partition_idx / target_merged_tiles_number) + OffsetT list = ~mask & partition_idx; + OffsetT start = items_per_tile * list; + OffsetT size = items_per_tile * merged_tiles_number; + + // Tile number within the tile group being merged, equal to: + // partition_idx / target_merged_tiles_number + OffsetT local_tile_idx = mask & partition_idx; + + OffsetT keys1_beg = (cub::min)(keys_count, start); + OffsetT keys1_end = (cub::min)(keys_count, start + size); + OffsetT keys2_beg = keys1_end; + OffsetT keys2_end = (cub::min)(keys_count, keys2_beg + size); + + OffsetT partition_at = (cub::min)(keys2_end - keys1_beg, + items_per_tile * local_tile_idx); + + OffsetT partition_diag = ping ? MergePath(keys_ping + keys1_beg, + keys_ping + keys2_beg, + keys1_end - keys1_beg, + keys2_end - keys2_beg, + partition_at, + compare_op) + : MergePath(keys_pong + keys1_beg, + keys_pong + keys2_beg, + keys1_end - keys1_beg, + keys2_end - keys2_beg, + partition_at, + compare_op); + + merge_partitions[partition_idx] = keys1_beg + partition_diag; + } +}; + +/// \brief The agent is responsible for merging N consecutive sorted arrays into N/2 sorted arrays. +template < + typename Policy, + typename KeyIteratorT, + typename ValueIteratorT, + typename OffsetT, + typename CompareOpT, + typename KeyT, + typename ValueT> +struct AgentMerge +{ + + //--------------------------------------------------------------------- + // Types and constants + //--------------------------------------------------------------------- + using KeysLoadPingIt = typename THRUST_NS_QUALIFIER::cuda_cub::core::LoadIterator::type; + using ItemsLoadPingIt = typename THRUST_NS_QUALIFIER::cuda_cub::core::LoadIterator::type; + using KeysLoadPongIt = typename THRUST_NS_QUALIFIER::cuda_cub::core::LoadIterator::type; + using ItemsLoadPongIt = typename THRUST_NS_QUALIFIER::cuda_cub::core::LoadIterator::type; + + using KeysOutputPongIt = KeyIteratorT; + using ItemsOutputPongIt = ValueIteratorT; + using KeysOutputPingIt = KeyT*; + using ItemsOutputPingIt = ValueT*; + + using BlockStoreKeysPong = typename BlockStoreType::type; + using BlockStoreItemsPong = typename BlockStoreType::type; + using BlockStoreKeysPing = typename BlockStoreType::type; + using BlockStoreItemsPing = typename BlockStoreType::type; + + /// Parameterized BlockReduce primitive + + union _TempStorage + { + typename BlockStoreKeysPing::TempStorage store_keys_ping; + typename BlockStoreItemsPing::TempStorage store_items_ping; + typename BlockStoreKeysPong::TempStorage store_keys_pong; + typename BlockStoreItemsPong::TempStorage store_items_pong; + + KeyT keys_shared[Policy::ITEMS_PER_TILE + 1]; + ValueT items_shared[Policy::ITEMS_PER_TILE + 1]; + }; + + /// Alias wrapper allowing storage to be unioned + struct TempStorage : Uninitialized<_TempStorage> {}; + + static constexpr bool KEYS_ONLY = std::is_same::value; + static constexpr int BLOCK_THREADS = Policy::BLOCK_THREADS; + static constexpr int ITEMS_PER_THREAD = Policy::ITEMS_PER_THREAD; + static constexpr int ITEMS_PER_TILE = Policy::ITEMS_PER_TILE; + static constexpr int SHARED_MEMORY_SIZE = + static_cast(sizeof(TempStorage)); + + //--------------------------------------------------------------------- + // Per thread data + //--------------------------------------------------------------------- + + bool ping; + _TempStorage& storage; + + KeysLoadPingIt keys_in_ping; + ItemsLoadPingIt items_in_ping; + KeysLoadPongIt keys_in_pong; + ItemsLoadPongIt items_in_pong; + + OffsetT keys_count; + + KeysOutputPongIt keys_out_pong; + ItemsOutputPongIt items_out_pong; + KeysOutputPingIt keys_out_ping; + ItemsOutputPingIt items_out_ping; + + CompareOpT compare_op; + OffsetT *merge_partitions; + OffsetT target_merged_tiles_number; + + //--------------------------------------------------------------------- + // Utility functions + //--------------------------------------------------------------------- + + /** + * \brief Concatenates up to ITEMS_PER_THREAD elements from input{1,2} into output array + * + * Reads data in a coalesced fashion [BLOCK_THREADS * item + tid] and + * stores the result in output[item]. + */ + template + __device__ __forceinline__ void + gmem_to_reg(T (&output)[ITEMS_PER_THREAD], + It1 input1, + It2 input2, + int count1, + int count2) + { + if (IS_FULL_TILE) + { +#pragma unroll + for (int item = 0; item < ITEMS_PER_THREAD; ++item) + { + int idx = BLOCK_THREADS * item + threadIdx.x; + output[item] = (idx < count1) ? input1[idx] : input2[idx - count1]; + } + } + else + { +#pragma unroll + for (int item = 0; item < ITEMS_PER_THREAD; ++item) + { + int idx = BLOCK_THREADS * item + threadIdx.x; + if (idx < count1 + count2) + { + output[item] = (idx < count1) ? input1[idx] : input2[idx - count1]; + } + } + } + } + + /// \brief Stores data in a coalesced fashion in[item] -> out[BLOCK_THREADS * item + tid] + template + __device__ __forceinline__ void + reg_to_shared(It output, + T (&input)[ITEMS_PER_THREAD]) + { +#pragma unroll + for (int item = 0; item < ITEMS_PER_THREAD; ++item) + { + int idx = BLOCK_THREADS * item + threadIdx.x; + output[idx] = input[item]; + } + } + + template + __device__ __forceinline__ void + consume_tile(int tid, OffsetT tile_idx, OffsetT tile_base, int count) + { + OffsetT partition_beg = merge_partitions[tile_idx + 0]; + OffsetT partition_end = merge_partitions[tile_idx + 1]; + + // target_merged_tiles_number is a power of two. + OffsetT merged_tiles_number = target_merged_tiles_number / 2; + + OffsetT mask = target_merged_tiles_number - 1; + + // The first tile number in the tiles group being merged, equal to: + // target_merged_tiles_number * (tile_idx / target_merged_tiles_number) + OffsetT list = ~mask & tile_idx; + OffsetT start = ITEMS_PER_TILE * list; + OffsetT size = ITEMS_PER_TILE * merged_tiles_number; + + OffsetT diag = ITEMS_PER_TILE * tile_idx - start; + + OffsetT keys1_beg = partition_beg; + OffsetT keys1_end = partition_end; + OffsetT keys2_beg = (cub::min)(keys_count, 2 * start + size + diag - partition_beg); + OffsetT keys2_end = (cub::min)(keys_count, 2 * start + size + diag + ITEMS_PER_TILE - partition_end); + + // Check if it's the last tile in the tile group being merged + if (mask == (mask & tile_idx)) + { + keys1_end = (cub::min)(keys_count, start + size); + keys2_end = (cub::min)(keys_count, start + size * 2); + } + + // number of keys per tile + // + int num_keys1 = static_cast(keys1_end - keys1_beg); + int num_keys2 = static_cast(keys2_end - keys2_beg); + + // load keys1 & keys2 + KeyT keys_local[ITEMS_PER_THREAD]; + if (ping) + { + gmem_to_reg(keys_local, + keys_in_ping + keys1_beg, + keys_in_ping + keys2_beg, + num_keys1, + num_keys2); + } + else + { + gmem_to_reg(keys_local, + keys_in_pong + keys1_beg, + keys_in_pong + keys2_beg, + num_keys1, + num_keys2); + } + reg_to_shared(&storage.keys_shared[0], keys_local); + + // preload items into registers already + // + ValueT items_local[ITEMS_PER_THREAD]; + if (!KEYS_ONLY) + { + if (ping) + { + gmem_to_reg(items_local, + items_in_ping + keys1_beg, + items_in_ping + keys2_beg, + num_keys1, + num_keys2); + } + else + { + gmem_to_reg(items_local, + items_in_pong + keys1_beg, + items_in_pong + keys2_beg, + num_keys1, + num_keys2); + } + } + + CTA_SYNC(); + + // use binary search in shared memory + // to find merge path for each of thread + // we can use int type here, because the number of + // items in shared memory is limited + // + int diag0_local = (cub::min)(num_keys1 + num_keys2, ITEMS_PER_THREAD * tid); + + int keys1_beg_local = MergePath(&storage.keys_shared[0], + &storage.keys_shared[num_keys1], + num_keys1, + num_keys2, + diag0_local, + compare_op); + int keys1_end_local = num_keys1; + int keys2_beg_local = diag0_local - keys1_beg_local; + int keys2_end_local = num_keys2; + + int num_keys1_local = keys1_end_local - keys1_beg_local; + int num_keys2_local = keys2_end_local - keys2_beg_local; + + // perform serial merge + // + int indices[ITEMS_PER_THREAD]; + + SerialMerge(&storage.keys_shared[0], + keys1_beg_local, + keys2_beg_local + num_keys1, + num_keys1_local, + num_keys2_local, + keys_local, + indices, + compare_op); + + CTA_SYNC(); + + // write keys + // + if (ping) + { + if (IS_FULL_TILE) + { + BlockStoreKeysPing(storage.store_keys_ping) + .Store(keys_out_ping + tile_base, keys_local); + } + else + { + BlockStoreKeysPing(storage.store_keys_ping) + .Store(keys_out_ping + tile_base, keys_local, num_keys1 + num_keys2); + } + } + else + { + if (IS_FULL_TILE) + { + BlockStoreKeysPong(storage.store_keys_pong) + .Store(keys_out_pong + tile_base, keys_local); + } + else + { + BlockStoreKeysPong(storage.store_keys_pong) + .Store(keys_out_pong + tile_base, keys_local, num_keys1 + num_keys2); + } + } + + // if items are provided, merge them + if (!KEYS_ONLY) + { + CTA_SYNC(); + + reg_to_shared(&storage.items_shared[0], items_local); + + CTA_SYNC(); + + // gather items from shared mem + // +#pragma unroll + for (int item = 0; item < ITEMS_PER_THREAD; ++item) + { + items_local[item] = storage.items_shared[indices[item]]; + } + + CTA_SYNC(); + + // write from reg to gmem + // + if (ping) + { + if (IS_FULL_TILE) + { + BlockStoreItemsPing(storage.store_items_ping) + .Store(items_out_ping + tile_base, items_local); + } + else + { + BlockStoreItemsPing(storage.store_items_ping) + .Store(items_out_ping + tile_base, items_local, count); + } + } + else + { + if (IS_FULL_TILE) + { + BlockStoreItemsPong(storage.store_items_pong) + .Store(items_out_pong + tile_base, items_local); + } + else + { + BlockStoreItemsPong(storage.store_items_pong) + .Store(items_out_pong + tile_base, items_local, count); + } + } + } + } + + __device__ __forceinline__ AgentMerge(bool ping_, + TempStorage &storage_, + KeysLoadPingIt keys_in_ping_, + ItemsLoadPingIt items_in_ping_, + KeysLoadPongIt keys_in_pong_, + ItemsLoadPongIt items_in_pong_, + OffsetT keys_count_, + KeysOutputPingIt keys_out_ping_, + ItemsOutputPingIt items_out_ping_, + KeysOutputPongIt keys_out_pong_, + ItemsOutputPongIt items_out_pong_, + CompareOpT compare_op_, + OffsetT *merge_partitions_, + OffsetT target_merged_tiles_number_) + : ping(ping_) + , storage(storage_.Alias()) + , keys_in_ping(keys_in_ping_) + , items_in_ping(items_in_ping_) + , keys_in_pong(keys_in_pong_) + , items_in_pong(items_in_pong_) + , keys_count(keys_count_) + , keys_out_pong(keys_out_pong_) + , items_out_pong(items_out_pong_) + , keys_out_ping(keys_out_ping_) + , items_out_ping(items_out_ping_) + , compare_op(compare_op_) + , merge_partitions(merge_partitions_) + , target_merged_tiles_number(target_merged_tiles_number_) + {} + + __device__ __forceinline__ void Process() + { + int tile_idx = static_cast(blockIdx.x); + int num_tiles = static_cast(gridDim.x); + OffsetT tile_base = OffsetT(tile_idx) * ITEMS_PER_TILE; + int tid = static_cast(threadIdx.x); + int items_in_tile = static_cast( + (cub::min)(static_cast(ITEMS_PER_TILE), keys_count - tile_base)); + + if (tile_idx < num_tiles - 1) + { + consume_tile(tid, tile_idx, tile_base, ITEMS_PER_TILE); + } + else + { + consume_tile(tid, tile_idx, tile_base, items_in_tile); + } + } +}; + + +CUB_NAMESPACE_END diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/agent/agent_radix_sort_downsweep.cuh b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/agent/agent_radix_sort_downsweep.cuh new file mode 100644 index 0000000000000000000000000000000000000000..a6157a0974571d0f6ae8084209914122375e9c50 --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/agent/agent_radix_sort_downsweep.cuh @@ -0,0 +1,775 @@ +/****************************************************************************** + * Copyright (c) 2011, Duane Merrill. All rights reserved. + * Copyright (c) 2011-2018, NVIDIA CORPORATION. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the NVIDIA CORPORATION nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ******************************************************************************/ + +/** + * \file + * AgentRadixSortDownsweep implements a stateful abstraction of CUDA thread + * blocks for participating in device-wide radix sort downsweep . + */ + + +#pragma once + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +CUB_NAMESPACE_BEGIN + + +/****************************************************************************** + * Tuning policy types + ******************************************************************************/ + +/** + * Parameterizable tuning policy type for AgentRadixSortDownsweep + */ +template < + int NOMINAL_BLOCK_THREADS_4B, ///< Threads per thread block + int NOMINAL_ITEMS_PER_THREAD_4B, ///< Items per thread (per tile of input) + typename ComputeT, ///< Dominant compute type + BlockLoadAlgorithm _LOAD_ALGORITHM, ///< The BlockLoad algorithm to use + CacheLoadModifier _LOAD_MODIFIER, ///< Cache load modifier for reading keys (and values) + RadixRankAlgorithm _RANK_ALGORITHM, ///< The radix ranking algorithm to use + BlockScanAlgorithm _SCAN_ALGORITHM, ///< The block scan algorithm to use + int _RADIX_BITS, ///< The number of radix bits, i.e., log2(bins) + typename ScalingType = RegBoundScaling > +struct AgentRadixSortDownsweepPolicy : + ScalingType +{ + enum + { + RADIX_BITS = _RADIX_BITS, ///< The number of radix bits, i.e., log2(bins) + }; + + static const BlockLoadAlgorithm LOAD_ALGORITHM = _LOAD_ALGORITHM; ///< The BlockLoad algorithm to use + static const CacheLoadModifier LOAD_MODIFIER = _LOAD_MODIFIER; ///< Cache load modifier for reading keys (and values) + static const RadixRankAlgorithm RANK_ALGORITHM = _RANK_ALGORITHM; ///< The radix ranking algorithm to use + static const BlockScanAlgorithm SCAN_ALGORITHM = _SCAN_ALGORITHM; ///< The BlockScan algorithm to use +}; + + +/****************************************************************************** + * Thread block abstractions + ******************************************************************************/ + + + + + +/** + * \brief AgentRadixSortDownsweep implements a stateful abstraction of CUDA thread blocks for participating in device-wide radix sort downsweep . + */ +template < + typename AgentRadixSortDownsweepPolicy, ///< Parameterized AgentRadixSortDownsweepPolicy tuning policy type + bool IS_DESCENDING, ///< Whether or not the sorted-order is high-to-low + typename KeyT, ///< KeyT type + typename ValueT, ///< ValueT type + typename OffsetT, ///< Signed integer type for global offsets + typename DecomposerT = detail::identity_decomposer_t> +struct AgentRadixSortDownsweep +{ + //--------------------------------------------------------------------- + // Type definitions and constants + //--------------------------------------------------------------------- + + using traits = detail::radix::traits_t; + using bit_ordered_type = typename traits::bit_ordered_type; + using bit_ordered_conversion = typename traits::bit_ordered_conversion_policy; + + static const BlockLoadAlgorithm LOAD_ALGORITHM = AgentRadixSortDownsweepPolicy::LOAD_ALGORITHM; + static const CacheLoadModifier LOAD_MODIFIER = AgentRadixSortDownsweepPolicy::LOAD_MODIFIER; + static const RadixRankAlgorithm RANK_ALGORITHM = AgentRadixSortDownsweepPolicy::RANK_ALGORITHM; + static const BlockScanAlgorithm SCAN_ALGORITHM = AgentRadixSortDownsweepPolicy::SCAN_ALGORITHM; + + enum + { + BLOCK_THREADS = AgentRadixSortDownsweepPolicy::BLOCK_THREADS, + ITEMS_PER_THREAD = AgentRadixSortDownsweepPolicy::ITEMS_PER_THREAD, + RADIX_BITS = AgentRadixSortDownsweepPolicy::RADIX_BITS, + TILE_ITEMS = BLOCK_THREADS * ITEMS_PER_THREAD, + + RADIX_DIGITS = 1 << RADIX_BITS, + KEYS_ONLY = std::is_same::value, + LOAD_WARP_STRIPED = RANK_ALGORITHM == RADIX_RANK_MATCH || + RANK_ALGORITHM == RADIX_RANK_MATCH_EARLY_COUNTS_ANY || + RANK_ALGORITHM == RADIX_RANK_MATCH_EARLY_COUNTS_ATOMIC_OR, + }; + + // Input iterator wrapper type (for applying cache modifier)s + using KeysItr = CacheModifiedInputIterator; + using ValuesItr = CacheModifiedInputIterator; + + // Radix ranking type to use + using BlockRadixRankT = + cub::detail::block_radix_rank_t< + RANK_ALGORITHM, BLOCK_THREADS, RADIX_BITS, IS_DESCENDING, SCAN_ALGORITHM>; + + // Digit extractor type + using fundamental_digit_extractor_t = BFEDigitExtractor; + using digit_extractor_t = + typename traits::template digit_extractor_t; + + enum + { + /// Number of bin-starting offsets tracked per thread + BINS_TRACKED_PER_THREAD = BlockRadixRankT::BINS_TRACKED_PER_THREAD + }; + + // BlockLoad type (keys) + using BlockLoadKeysT = + BlockLoad; + + // BlockLoad type (values) + using BlockLoadValuesT = + BlockLoad; + + // Value exchange array type + typedef ValueT ValueExchangeT[TILE_ITEMS]; + + /** + * Shared memory storage layout + */ + union __align__(16) _TempStorage + { + typename BlockLoadKeysT::TempStorage load_keys; + typename BlockLoadValuesT::TempStorage load_values; + typename BlockRadixRankT::TempStorage radix_rank; + + struct KeysAndOffsets + { + bit_ordered_type exchange_keys[TILE_ITEMS]; + OffsetT relative_bin_offsets[RADIX_DIGITS]; + } keys_and_offsets; + + Uninitialized exchange_values; + + OffsetT exclusive_digit_prefix[RADIX_DIGITS]; + }; + + + /// Alias wrapper allowing storage to be unioned + struct TempStorage : Uninitialized<_TempStorage> {}; + + + //--------------------------------------------------------------------- + // Thread fields + //--------------------------------------------------------------------- + + // Shared storage for this CTA + _TempStorage &temp_storage; + + // Input and output device pointers + KeysItr d_keys_in; + ValuesItr d_values_in; + bit_ordered_type *d_keys_out; + ValueT *d_values_out; + + // The global scatter base offset for each digit (valid in the first RADIX_DIGITS threads) + OffsetT bin_offset[BINS_TRACKED_PER_THREAD]; + + std::uint32_t current_bit; + std::uint32_t num_bits; + + // Whether to short-cirucit + int short_circuit; + + DecomposerT decomposer; + + //--------------------------------------------------------------------- + // Utility methods + //--------------------------------------------------------------------- + + __device__ __forceinline__ digit_extractor_t digit_extractor() + { + return traits::template digit_extractor(current_bit, + num_bits, + decomposer); + } + + /** + * Scatter ranked keys through shared memory, then to device-accessible memory + */ + template + __device__ __forceinline__ void ScatterKeys( + bit_ordered_type (&twiddled_keys)[ITEMS_PER_THREAD], + OffsetT (&relative_bin_offsets)[ITEMS_PER_THREAD], + int (&ranks)[ITEMS_PER_THREAD], + OffsetT valid_items) + { + #pragma unroll + for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ++ITEM) + { + temp_storage.keys_and_offsets.exchange_keys[ranks[ITEM]] = twiddled_keys[ITEM]; + } + + CTA_SYNC(); + + #pragma unroll + for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ++ITEM) + { + bit_ordered_type key = temp_storage.keys_and_offsets.exchange_keys[threadIdx.x + (ITEM * BLOCK_THREADS)]; + std::uint32_t digit = digit_extractor().Digit(key); + relative_bin_offsets[ITEM] = temp_storage.keys_and_offsets.relative_bin_offsets[digit]; + + key = bit_ordered_conversion::from_bit_ordered(decomposer, key); + + if (FULL_TILE || + (static_cast(threadIdx.x + (ITEM * BLOCK_THREADS)) < valid_items)) + { + d_keys_out[relative_bin_offsets[ITEM] + threadIdx.x + (ITEM * BLOCK_THREADS)] = key; + } + } + } + + + /** + * Scatter ranked values through shared memory, then to device-accessible memory + */ + template + __device__ __forceinline__ void ScatterValues( + ValueT (&values)[ITEMS_PER_THREAD], + OffsetT (&relative_bin_offsets)[ITEMS_PER_THREAD], + int (&ranks)[ITEMS_PER_THREAD], + OffsetT valid_items) + { + CTA_SYNC(); + + ValueExchangeT &exchange_values = temp_storage.exchange_values.Alias(); + + #pragma unroll + for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ++ITEM) + { + exchange_values[ranks[ITEM]] = values[ITEM]; + } + + CTA_SYNC(); + + #pragma unroll + for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ++ITEM) + { + ValueT value = exchange_values[threadIdx.x + (ITEM * BLOCK_THREADS)]; + + if (FULL_TILE || + (static_cast(threadIdx.x + (ITEM * BLOCK_THREADS)) < valid_items)) + { + d_values_out[relative_bin_offsets[ITEM] + threadIdx.x + (ITEM * BLOCK_THREADS)] = value; + } + } + } + + /** + * Load a tile of keys (specialized for full tile, block load) + */ + __device__ __forceinline__ void LoadKeys( + bit_ordered_type (&keys)[ITEMS_PER_THREAD], + OffsetT block_offset, + OffsetT valid_items, + bit_ordered_type oob_item, + Int2Type is_full_tile, + Int2Type warp_striped) + { + BlockLoadKeysT(temp_storage.load_keys).Load( + d_keys_in + block_offset, keys); + + CTA_SYNC(); + } + + + /** + * Load a tile of keys (specialized for partial tile, block load) + */ + __device__ __forceinline__ void LoadKeys( + bit_ordered_type (&keys)[ITEMS_PER_THREAD], + OffsetT block_offset, + OffsetT valid_items, + bit_ordered_type oob_item, + Int2Type is_full_tile, + Int2Type warp_striped) + { + // Register pressure work-around: moving valid_items through shfl prevents compiler + // from reusing guards/addressing from prior guarded loads + valid_items = ShuffleIndex(valid_items, 0, 0xffffffff); + + BlockLoadKeysT(temp_storage.load_keys).Load( + d_keys_in + block_offset, keys, valid_items, oob_item); + + CTA_SYNC(); + } + + + /** + * Load a tile of keys (specialized for full tile, warp-striped load) + */ + __device__ __forceinline__ void LoadKeys( + bit_ordered_type (&keys)[ITEMS_PER_THREAD], + OffsetT block_offset, + OffsetT valid_items, + bit_ordered_type oob_item, + Int2Type is_full_tile, + Int2Type warp_striped) + { + LoadDirectWarpStriped(threadIdx.x, d_keys_in + block_offset, keys); + } + + /** + * Load a tile of keys (specialized for partial tile, warp-striped load) + */ + __device__ __forceinline__ void LoadKeys( + bit_ordered_type (&keys)[ITEMS_PER_THREAD], + OffsetT block_offset, + OffsetT valid_items, + bit_ordered_type oob_item, + Int2Type is_full_tile, + Int2Type warp_striped) + { + // Register pressure work-around: moving valid_items through shfl prevents compiler + // from reusing guards/addressing from prior guarded loads + valid_items = ShuffleIndex(valid_items, 0, 0xffffffff); + + LoadDirectWarpStriped(threadIdx.x, d_keys_in + block_offset, keys, valid_items, oob_item); + } + + /** + * Load a tile of values (specialized for full tile, block load) + */ + __device__ __forceinline__ void LoadValues( + ValueT (&values)[ITEMS_PER_THREAD], + OffsetT block_offset, + OffsetT valid_items, + Int2Type is_full_tile, + Int2Type warp_striped) + { + BlockLoadValuesT(temp_storage.load_values).Load( + d_values_in + block_offset, values); + + CTA_SYNC(); + } + + + /** + * Load a tile of values (specialized for partial tile, block load) + */ + __device__ __forceinline__ void LoadValues( + ValueT (&values)[ITEMS_PER_THREAD], + OffsetT block_offset, + OffsetT valid_items, + Int2Type is_full_tile, + Int2Type warp_striped) + { + // Register pressure work-around: moving valid_items through shfl prevents compiler + // from reusing guards/addressing from prior guarded loads + valid_items = ShuffleIndex(valid_items, 0, 0xffffffff); + + BlockLoadValuesT(temp_storage.load_values).Load( + d_values_in + block_offset, values, valid_items); + + CTA_SYNC(); + } + + + /** + * Load a tile of items (specialized for full tile, warp-striped load) + */ + __device__ __forceinline__ void LoadValues( + ValueT (&values)[ITEMS_PER_THREAD], + OffsetT block_offset, + OffsetT valid_items, + Int2Type is_full_tile, + Int2Type warp_striped) + { + LoadDirectWarpStriped(threadIdx.x, d_values_in + block_offset, values); + } + + /** + * Load a tile of items (specialized for partial tile, warp-striped load) + */ + __device__ __forceinline__ void LoadValues( + ValueT (&values)[ITEMS_PER_THREAD], + OffsetT block_offset, + OffsetT valid_items, + Int2Type is_full_tile, + Int2Type warp_striped) + { + // Register pressure work-around: moving valid_items through shfl prevents compiler + // from reusing guards/addressing from prior guarded loads + valid_items = ShuffleIndex(valid_items, 0, 0xffffffff); + + LoadDirectWarpStriped(threadIdx.x, d_values_in + block_offset, values, valid_items); + } + + /** + * Truck along associated values + */ + template + __device__ __forceinline__ void GatherScatterValues( + OffsetT (&relative_bin_offsets)[ITEMS_PER_THREAD], + int (&ranks)[ITEMS_PER_THREAD], + OffsetT block_offset, + OffsetT valid_items, + Int2Type /*is_keys_only*/) + { + ValueT values[ITEMS_PER_THREAD]; + + CTA_SYNC(); + + LoadValues( + values, + block_offset, + valid_items, + Int2Type(), + Int2Type()); + + ScatterValues( + values, + relative_bin_offsets, + ranks, + valid_items); + } + + + /** + * Truck along associated values (specialized for key-only sorting) + */ + template + __device__ __forceinline__ void GatherScatterValues( + OffsetT (&/*relative_bin_offsets*/)[ITEMS_PER_THREAD], + int (&/*ranks*/)[ITEMS_PER_THREAD], + OffsetT /*block_offset*/, + OffsetT /*valid_items*/, + Int2Type /*is_keys_only*/) + {} + + + /** + * Process tile + */ + template + __device__ __forceinline__ void ProcessTile( + OffsetT block_offset, + const OffsetT &valid_items = TILE_ITEMS) + { + bit_ordered_type keys[ITEMS_PER_THREAD]; + int ranks[ITEMS_PER_THREAD]; + OffsetT relative_bin_offsets[ITEMS_PER_THREAD]; + + // Assign default (min/max) value to all keys + bit_ordered_type default_key = IS_DESCENDING + ? traits::min_raw_binary_key(decomposer) + : traits::max_raw_binary_key(decomposer); + + // Load tile of keys + LoadKeys( + keys, + block_offset, + valid_items, + default_key, + Int2Type(), + Int2Type()); + + #pragma unroll + for (int KEY = 0; KEY < ITEMS_PER_THREAD; KEY++) + { + keys[KEY] = bit_ordered_conversion::to_bit_ordered(decomposer, keys[KEY]); + } + + // Rank the twiddled keys + int exclusive_digit_prefix[BINS_TRACKED_PER_THREAD]; + BlockRadixRankT(temp_storage.radix_rank).RankKeys( + keys, + ranks, + digit_extractor(), + exclusive_digit_prefix); + + CTA_SYNC(); + + // Share exclusive digit prefix + #pragma unroll + for (int track = 0; track < BINS_TRACKED_PER_THREAD; ++track) + { + int bin_idx = (threadIdx.x * BINS_TRACKED_PER_THREAD) + track; + if ((BLOCK_THREADS == RADIX_DIGITS) || (bin_idx < RADIX_DIGITS)) + { + // Store exclusive prefix + temp_storage.exclusive_digit_prefix[bin_idx] = + exclusive_digit_prefix[track]; + } + } + + CTA_SYNC(); + + // Get inclusive digit prefix + int inclusive_digit_prefix[BINS_TRACKED_PER_THREAD]; + + #pragma unroll + for (int track = 0; track < BINS_TRACKED_PER_THREAD; ++track) + { + int bin_idx = (threadIdx.x * BINS_TRACKED_PER_THREAD) + track; + if ((BLOCK_THREADS == RADIX_DIGITS) || (bin_idx < RADIX_DIGITS)) + { + if (IS_DESCENDING) + { + // Get inclusive digit prefix from exclusive prefix (higher bins come first) + inclusive_digit_prefix[track] = (bin_idx == 0) ? + (BLOCK_THREADS * ITEMS_PER_THREAD) : + temp_storage.exclusive_digit_prefix[bin_idx - 1]; + } + else + { + // Get inclusive digit prefix from exclusive prefix (lower bins come first) + inclusive_digit_prefix[track] = (bin_idx == RADIX_DIGITS - 1) ? + (BLOCK_THREADS * ITEMS_PER_THREAD) : + temp_storage.exclusive_digit_prefix[bin_idx + 1]; + } + } + } + + CTA_SYNC(); + + // Update global scatter base offsets for each digit + #pragma unroll + for (int track = 0; track < BINS_TRACKED_PER_THREAD; ++track) + { + int bin_idx = (threadIdx.x * BINS_TRACKED_PER_THREAD) + track; + if ((BLOCK_THREADS == RADIX_DIGITS) || (bin_idx < RADIX_DIGITS)) + { + bin_offset[track] -= exclusive_digit_prefix[track]; + temp_storage.keys_and_offsets.relative_bin_offsets[bin_idx] = bin_offset[track]; + bin_offset[track] += inclusive_digit_prefix[track]; + } + } + + CTA_SYNC(); + + // Scatter keys + ScatterKeys(keys, relative_bin_offsets, ranks, valid_items); + + // Gather/scatter values + GatherScatterValues(relative_bin_offsets , ranks, block_offset, valid_items, Int2Type()); + } + + //--------------------------------------------------------------------- + // Copy shortcut + //--------------------------------------------------------------------- + + /** + * Copy tiles within the range of input + */ + template < + typename InputIteratorT, + typename T> + __device__ __forceinline__ void Copy( + InputIteratorT d_in, + T *d_out, + OffsetT block_offset, + OffsetT block_end) + { + // Simply copy the input + while (block_end - block_offset >= TILE_ITEMS) + { + T items[ITEMS_PER_THREAD]; + + LoadDirectStriped(threadIdx.x, d_in + block_offset, items); + CTA_SYNC(); + StoreDirectStriped(threadIdx.x, d_out + block_offset, items); + + block_offset += TILE_ITEMS; + } + + // Clean up last partial tile with guarded-I/O + if (block_offset < block_end) + { + OffsetT valid_items = block_end - block_offset; + + T items[ITEMS_PER_THREAD]; + + LoadDirectStriped(threadIdx.x, d_in + block_offset, items, valid_items); + CTA_SYNC(); + StoreDirectStriped(threadIdx.x, d_out + block_offset, items, valid_items); + } + } + + + /** + * Copy tiles within the range of input (specialized for NullType) + */ + template + __device__ __forceinline__ void Copy( + InputIteratorT /*d_in*/, + NullType * /*d_out*/, + OffsetT /*block_offset*/, + OffsetT /*block_end*/) + {} + + + //--------------------------------------------------------------------- + // Interface + //--------------------------------------------------------------------- + + /** + * Constructor + */ + __device__ __forceinline__ AgentRadixSortDownsweep( + TempStorage &temp_storage, + OffsetT (&bin_offset)[BINS_TRACKED_PER_THREAD], + OffsetT num_items, + const KeyT *d_keys_in, + KeyT *d_keys_out, + const ValueT *d_values_in, + ValueT *d_values_out, + int current_bit, + int num_bits, + DecomposerT decomposer = {}) + : + temp_storage(temp_storage.Alias()), + d_keys_in(reinterpret_cast(d_keys_in)), + d_values_in(d_values_in), + d_keys_out(reinterpret_cast(d_keys_out)), + d_values_out(d_values_out), + current_bit(current_bit), + num_bits(num_bits), + short_circuit(1), + decomposer(decomposer) + { + #pragma unroll + for (int track = 0; track < BINS_TRACKED_PER_THREAD; ++track) + { + this->bin_offset[track] = bin_offset[track]; + + int bin_idx = (threadIdx.x * BINS_TRACKED_PER_THREAD) + track; + if ((BLOCK_THREADS == RADIX_DIGITS) || (bin_idx < RADIX_DIGITS)) + { + // Short circuit if the histogram has only bin counts of only zeros or problem-size + short_circuit = short_circuit && ((bin_offset[track] == 0) || (bin_offset[track] == num_items)); + } + } + + short_circuit = CTA_SYNC_AND(short_circuit); + } + + + /** + * Constructor + */ + __device__ __forceinline__ AgentRadixSortDownsweep( + TempStorage &temp_storage, + OffsetT num_items, + OffsetT *d_spine, + const KeyT *d_keys_in, + KeyT *d_keys_out, + const ValueT *d_values_in, + ValueT *d_values_out, + int current_bit, + int num_bits, + DecomposerT decomposer = {}) + : + temp_storage(temp_storage.Alias()), + d_keys_in(reinterpret_cast(d_keys_in)), + d_values_in(d_values_in), + d_keys_out(reinterpret_cast(d_keys_out)), + d_values_out(d_values_out), + current_bit(current_bit), + num_bits(num_bits), + short_circuit(1), + decomposer(decomposer) + { + #pragma unroll + for (int track = 0; track < BINS_TRACKED_PER_THREAD; ++track) + { + int bin_idx = (threadIdx.x * BINS_TRACKED_PER_THREAD) + track; + + // Load digit bin offsets (each of the first RADIX_DIGITS threads will load an offset for that digit) + if ((BLOCK_THREADS == RADIX_DIGITS) || (bin_idx < RADIX_DIGITS)) + { + if (IS_DESCENDING) + bin_idx = RADIX_DIGITS - bin_idx - 1; + + // Short circuit if the first block's histogram has only bin counts of only zeros or problem-size + OffsetT first_block_bin_offset = d_spine[gridDim.x * bin_idx]; + short_circuit = short_circuit && ((first_block_bin_offset == 0) || (first_block_bin_offset == num_items)); + + // Load my block's bin offset for my bin + bin_offset[track] = d_spine[(gridDim.x * bin_idx) + blockIdx.x]; + } + } + + short_circuit = CTA_SYNC_AND(short_circuit); + } + + + /** + * Distribute keys from a segment of input tiles. + */ + __device__ __forceinline__ void ProcessRegion( + OffsetT block_offset, + OffsetT block_end) + { + if (short_circuit) + { + // Copy keys + Copy(d_keys_in, d_keys_out, block_offset, block_end); + + // Copy values + Copy(d_values_in, d_values_out, block_offset, block_end); + } + else + { + // Process full tiles of tile_items + #pragma unroll 1 + while (block_end - block_offset >= TILE_ITEMS) + { + ProcessTile(block_offset); + block_offset += TILE_ITEMS; + + CTA_SYNC(); + } + + // Clean up last partial tile with guarded-I/O + if (block_offset < block_end) + { + ProcessTile(block_offset, block_end - block_offset); + } + + } + } + +}; + + + +CUB_NAMESPACE_END + diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/agent/agent_radix_sort_histogram.cuh b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/agent/agent_radix_sort_histogram.cuh new file mode 100644 index 0000000000000000000000000000000000000000..43649fc481b7a16a42388ac15488a49d823e5e03 --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/agent/agent_radix_sort_histogram.cuh @@ -0,0 +1,282 @@ +/****************************************************************************** + * Copyright (c) 2011-2020, NVIDIA CORPORATION. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the NVIDIA CORPORATION nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ******************************************************************************/ + +/** + * \file + * agent_radix_sort_histogram.cuh implements a stateful abstraction of CUDA + * thread blocks for participating in the device histogram kernel used for + * one-sweep radix sorting. + */ + +#pragma once + +#include "../block/block_load.cuh" +#include "../block/radix_rank_sort_operations.cuh" +#include "../config.cuh" +#include "../thread/thread_reduce.cuh" +#include "../util_math.cuh" +#include "../util_type.cuh" + + +CUB_NAMESPACE_BEGIN + +template < + int _BLOCK_THREADS, + int _ITEMS_PER_THREAD, + int NOMINAL_4B_NUM_PARTS, + typename ComputeT, + int _RADIX_BITS> +struct AgentRadixSortHistogramPolicy +{ + enum + { + BLOCK_THREADS = _BLOCK_THREADS, + ITEMS_PER_THREAD = _ITEMS_PER_THREAD, + /** NUM_PARTS is the number of private histograms (parts) each histogram is split + * into. Each warp lane is assigned to a specific part based on the lane + * ID. However, lanes with the same ID in different warp use the same private + * histogram. This arrangement helps reduce the degree of conflicts in atomic + * operations. */ + NUM_PARTS = CUB_MAX(1, NOMINAL_4B_NUM_PARTS * 4 / CUB_MAX(sizeof(ComputeT), 4)), + RADIX_BITS = _RADIX_BITS, + }; +}; + +template < + int _BLOCK_THREADS, + int _RADIX_BITS> +struct AgentRadixSortExclusiveSumPolicy +{ + enum + { + BLOCK_THREADS = _BLOCK_THREADS, + RADIX_BITS = _RADIX_BITS, + }; +}; + +template < + typename AgentRadixSortHistogramPolicy, + bool IS_DESCENDING, + typename KeyT, + typename OffsetT, + typename DecomposerT = detail::identity_decomposer_t> +struct AgentRadixSortHistogram +{ + // constants + enum + { + ITEMS_PER_THREAD = AgentRadixSortHistogramPolicy::ITEMS_PER_THREAD, + BLOCK_THREADS = AgentRadixSortHistogramPolicy::BLOCK_THREADS, + TILE_ITEMS = BLOCK_THREADS * ITEMS_PER_THREAD, + RADIX_BITS = AgentRadixSortHistogramPolicy::RADIX_BITS, + RADIX_DIGITS = 1 << RADIX_BITS, + MAX_NUM_PASSES = (sizeof(KeyT) * 8 + RADIX_BITS - 1) / RADIX_BITS, + NUM_PARTS = AgentRadixSortHistogramPolicy::NUM_PARTS, + }; + + using traits = detail::radix::traits_t; + using bit_ordered_type = typename traits::bit_ordered_type; + using bit_ordered_conversion = typename traits::bit_ordered_conversion_policy; + + typedef RadixSortTwiddle Twiddle; + typedef std::uint32_t ShmemCounterT; + typedef ShmemCounterT ShmemAtomicCounterT; + + using fundamental_digit_extractor_t = ShiftDigitExtractor; + using digit_extractor_t = + typename traits::template digit_extractor_t; + + struct _TempStorage + { + ShmemAtomicCounterT bins[MAX_NUM_PASSES][RADIX_DIGITS][NUM_PARTS]; + }; + + struct TempStorage : Uninitialized<_TempStorage> {}; + + // thread fields + // shared memory storage + _TempStorage& s; + + // bins for the histogram + OffsetT* d_bins_out; + + // data to compute the histogram + const bit_ordered_type* d_keys_in; + + // number of data items + OffsetT num_items; + + // begin and end bits for sorting + int begin_bit, end_bit; + + // number of sorting passes + int num_passes; + + DecomposerT decomposer; + + __device__ __forceinline__ AgentRadixSortHistogram(TempStorage &temp_storage, + OffsetT *d_bins_out, + const KeyT *d_keys_in, + OffsetT num_items, + int begin_bit, + int end_bit, + DecomposerT decomposer = {}) + : s(temp_storage.Alias()) + , d_bins_out(d_bins_out) + , d_keys_in(reinterpret_cast(d_keys_in)) + , num_items(num_items) + , begin_bit(begin_bit) + , end_bit(end_bit) + , num_passes((end_bit - begin_bit + RADIX_BITS - 1) / RADIX_BITS) + , decomposer(decomposer) + {} + + __device__ __forceinline__ void Init() + { + // Initialize bins to 0. + #pragma unroll + for (int bin = threadIdx.x; bin < RADIX_DIGITS; bin += BLOCK_THREADS) + { + #pragma unroll + for (int pass = 0; pass < num_passes; ++pass) + { + #pragma unroll + for (int part = 0; part < NUM_PARTS; ++part) + { + s.bins[pass][bin][part] = 0; + } + } + } + CTA_SYNC(); + } + + __device__ __forceinline__ + void LoadTileKeys(OffsetT tile_offset, bit_ordered_type (&keys)[ITEMS_PER_THREAD]) + { + // tile_offset < num_items always, hence the line below works + bool full_tile = num_items - tile_offset >= TILE_ITEMS; + if (full_tile) + { + LoadDirectStriped( + threadIdx.x, d_keys_in + tile_offset, keys); + } + else + { + LoadDirectStriped( + threadIdx.x, d_keys_in + tile_offset, keys, + num_items - tile_offset, Twiddle::DefaultKey(decomposer)); + } + + #pragma unroll + for (int u = 0; u < ITEMS_PER_THREAD; ++u) + { + keys[u] = Twiddle::In(keys[u], decomposer); + } + } + + __device__ __forceinline__ + void AccumulateSharedHistograms(OffsetT tile_offset, bit_ordered_type (&keys)[ITEMS_PER_THREAD]) + { + int part = LaneId() % NUM_PARTS; + #pragma unroll + for (int current_bit = begin_bit, pass = 0; + current_bit < end_bit; current_bit += RADIX_BITS, ++pass) + { + int num_bits = CUB_MIN(RADIX_BITS, end_bit - current_bit); + #pragma unroll + for (int u = 0; u < ITEMS_PER_THREAD; ++u) + { + std::uint32_t bin = digit_extractor(current_bit, num_bits).Digit(keys[u]); + // Using cuda::atomic<> results in lower performance on GP100, + // so atomicAdd() is used instead. + atomicAdd(&s.bins[pass][bin][part], 1); + } + } + } + + __device__ __forceinline__ void AccumulateGlobalHistograms() + { + #pragma unroll + for (int bin = threadIdx.x; bin < RADIX_DIGITS; bin += BLOCK_THREADS) + { + #pragma unroll + for (int pass = 0; pass < num_passes; ++pass) + { + OffsetT count = internal::ThreadReduce(s.bins[pass][bin], Sum()); + if (count > 0) + { + // Using cuda::atomic<> here would also require using it in + // other kernels. However, other kernels of onesweep sorting + // (ExclusiveSum, Onesweep) don't need atomic + // access. Therefore, atomicAdd() is used, until + // cuda::atomic_ref<> becomes available. + atomicAdd(&d_bins_out[pass * RADIX_DIGITS + bin], count); + } + } + } + } + + __device__ __forceinline__ void Process() + { + // Within a portion, avoid overflowing (u)int32 counters. + // Between portions, accumulate results in global memory. + const OffsetT MAX_PORTION_SIZE = 1 << 30; + OffsetT num_portions = cub::DivideAndRoundUp(num_items, MAX_PORTION_SIZE); + for (OffsetT portion = 0; portion < num_portions; ++portion) + { + // Reset the counters. + Init(); + CTA_SYNC(); + + // Process the tiles. + OffsetT portion_offset = portion * MAX_PORTION_SIZE; + OffsetT portion_size = CUB_MIN(MAX_PORTION_SIZE, num_items - portion_offset); + for (OffsetT offset = blockIdx.x * TILE_ITEMS; offset < portion_size; + offset += TILE_ITEMS * gridDim.x) + { + OffsetT tile_offset = portion_offset + offset; + bit_ordered_type keys[ITEMS_PER_THREAD]; + LoadTileKeys(tile_offset, keys); + AccumulateSharedHistograms(tile_offset, keys); + } + CTA_SYNC(); + + // Accumulate the result in global memory. + AccumulateGlobalHistograms(); + CTA_SYNC(); + } + } + + __device__ __forceinline__ digit_extractor_t digit_extractor(int current_bit, int num_bits) + { + return traits::template digit_extractor(current_bit, + num_bits, + decomposer); + } +}; + +CUB_NAMESPACE_END diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/agent/agent_radix_sort_upsweep.cuh b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/agent/agent_radix_sort_upsweep.cuh new file mode 100644 index 0000000000000000000000000000000000000000..1918fb5f5ebc8e9d190052c58cbf838ad8e44af8 --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/agent/agent_radix_sort_upsweep.cuh @@ -0,0 +1,531 @@ +/****************************************************************************** + * Copyright (c) 2011, Duane Merrill. All rights reserved. + * Copyright (c) 2011-2018, NVIDIA CORPORATION. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the NVIDIA CORPORATION nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ******************************************************************************/ + +/** + * \file + * AgentRadixSortUpsweep implements a stateful abstraction of CUDA thread blocks for participating in device-wide radix sort upsweep . + */ + +#pragma once + +#include "../thread/thread_reduce.cuh" +#include "../thread/thread_load.cuh" +#include "../warp/warp_reduce.cuh" +#include "../block/block_load.cuh" +#include "../block/radix_rank_sort_operations.cuh" +#include "../config.cuh" +#include "../util_type.cuh" +#include "../iterator/cache_modified_input_iterator.cuh" + +CUB_NAMESPACE_BEGIN + +/****************************************************************************** + * Tuning policy types + ******************************************************************************/ + +/** + * Parameterizable tuning policy type for AgentRadixSortUpsweep + */ +template < + int NOMINAL_BLOCK_THREADS_4B, ///< Threads per thread block + int NOMINAL_ITEMS_PER_THREAD_4B, ///< Items per thread (per tile of input) + typename ComputeT, ///< Dominant compute type + CacheLoadModifier _LOAD_MODIFIER, ///< Cache load modifier for reading keys + int _RADIX_BITS, ///< The number of radix bits, i.e., log2(bins) + typename ScalingType = RegBoundScaling > +struct AgentRadixSortUpsweepPolicy : + ScalingType +{ + enum + { + RADIX_BITS = _RADIX_BITS, ///< The number of radix bits, i.e., log2(bins) + }; + + static const CacheLoadModifier LOAD_MODIFIER = _LOAD_MODIFIER; ///< Cache load modifier for reading keys +}; + + +/****************************************************************************** + * Thread block abstractions + ******************************************************************************/ + +/** + * \brief AgentRadixSortUpsweep implements a stateful abstraction of CUDA thread blocks for participating in device-wide radix sort upsweep . + */ +template < + typename AgentRadixSortUpsweepPolicy, ///< Parameterized AgentRadixSortUpsweepPolicy tuning policy type + typename KeyT, ///< KeyT type + typename OffsetT, + typename DecomposerT = detail::identity_decomposer_t> ///< Signed integer type for global offsets +struct AgentRadixSortUpsweep +{ + + //--------------------------------------------------------------------- + // Type definitions and constants + //--------------------------------------------------------------------- + using traits = detail::radix::traits_t; + using bit_ordered_type = typename traits::bit_ordered_type; + using bit_ordered_conversion = typename traits::bit_ordered_conversion_policy; + + // Integer type for digit counters (to be packed into words of PackedCounters) + typedef unsigned char DigitCounter; + + // Integer type for packing DigitCounters into columns of shared memory banks + typedef unsigned int PackedCounter; + + static const CacheLoadModifier LOAD_MODIFIER = AgentRadixSortUpsweepPolicy::LOAD_MODIFIER; + + enum + { + RADIX_BITS = AgentRadixSortUpsweepPolicy::RADIX_BITS, + BLOCK_THREADS = AgentRadixSortUpsweepPolicy::BLOCK_THREADS, + KEYS_PER_THREAD = AgentRadixSortUpsweepPolicy::ITEMS_PER_THREAD, + + RADIX_DIGITS = 1 << RADIX_BITS, + + LOG_WARP_THREADS = CUB_PTX_LOG_WARP_THREADS, + WARP_THREADS = 1 << LOG_WARP_THREADS, + WARPS = (BLOCK_THREADS + WARP_THREADS - 1) / WARP_THREADS, + + TILE_ITEMS = BLOCK_THREADS * KEYS_PER_THREAD, + + BYTES_PER_COUNTER = sizeof(DigitCounter), + LOG_BYTES_PER_COUNTER = Log2::VALUE, + + PACKING_RATIO = sizeof(PackedCounter) / sizeof(DigitCounter), + LOG_PACKING_RATIO = Log2::VALUE, + + LOG_COUNTER_LANES = CUB_MAX(0, int(RADIX_BITS) - int(LOG_PACKING_RATIO)), + COUNTER_LANES = 1 << LOG_COUNTER_LANES, + + // To prevent counter overflow, we must periodically unpack and aggregate the + // digit counters back into registers. Each counter lane is assigned to a + // warp for aggregation. + + LANES_PER_WARP = CUB_MAX(1, (COUNTER_LANES + WARPS - 1) / WARPS), + + // Unroll tiles in batches without risk of counter overflow + UNROLL_COUNT = CUB_MIN(64, 255 / KEYS_PER_THREAD), + UNROLLED_ELEMENTS = UNROLL_COUNT * TILE_ITEMS, + }; + + + // Input iterator wrapper type (for applying cache modifier)s + typedef CacheModifiedInputIterator KeysItr; + + // Digit extractor type + using fundamental_digit_extractor_t = BFEDigitExtractor; + using digit_extractor_t = + typename traits::template digit_extractor_t; + + /** + * Shared memory storage layout + */ + union __align__(16) _TempStorage + { + DigitCounter thread_counters[COUNTER_LANES][BLOCK_THREADS][PACKING_RATIO]; + PackedCounter packed_thread_counters[COUNTER_LANES][BLOCK_THREADS]; + OffsetT block_counters[WARP_THREADS][RADIX_DIGITS]; + }; + + + /// Alias wrapper allowing storage to be unioned + struct TempStorage : Uninitialized<_TempStorage> {}; + + + //--------------------------------------------------------------------- + // Thread fields (aggregate state bundle) + //--------------------------------------------------------------------- + + // Shared storage for this CTA + _TempStorage &temp_storage; + + // Thread-local counters for periodically aggregating composite-counter lanes + OffsetT local_counts[LANES_PER_WARP][PACKING_RATIO]; + + // Input and output device pointers + KeysItr d_keys_in; + + // Target bits + int current_bit; + int num_bits; + DecomposerT decomposer; + + //--------------------------------------------------------------------- + // Helper structure for templated iteration + //--------------------------------------------------------------------- + + // Iterate + template + struct Iterate + { + // BucketKeys + static __device__ __forceinline__ void BucketKeys( + AgentRadixSortUpsweep &cta, + bit_ordered_type keys[KEYS_PER_THREAD]) + { + cta.Bucket(keys[COUNT]); + + // Next + Iterate::BucketKeys(cta, keys); + } + }; + + // Terminate + template + struct Iterate + { + // BucketKeys + static __device__ __forceinline__ void BucketKeys(AgentRadixSortUpsweep &/*cta*/, bit_ordered_type /*keys*/[KEYS_PER_THREAD]) {} + }; + + + //--------------------------------------------------------------------- + // Utility methods + //--------------------------------------------------------------------- + __device__ __forceinline__ digit_extractor_t digit_extractor() + { + return traits::template digit_extractor(current_bit, num_bits, decomposer); + } + + /** + * Decode a key and increment corresponding smem digit counter + */ + __device__ __forceinline__ void Bucket(bit_ordered_type key) + { + // Perform transform op + bit_ordered_type converted_key = bit_ordered_conversion::to_bit_ordered(decomposer, key); + + // Extract current digit bits + std::uint32_t digit = digit_extractor().Digit(converted_key); + + // Get sub-counter offset + std::uint32_t sub_counter = digit & (PACKING_RATIO - 1); + + // Get row offset + std::uint32_t row_offset = digit >> LOG_PACKING_RATIO; + + // Increment counter + temp_storage.thread_counters[row_offset][threadIdx.x][sub_counter]++; + } + + + /** + * Reset composite counters + */ + __device__ __forceinline__ void ResetDigitCounters() + { + #pragma unroll + for (int LANE = 0; LANE < COUNTER_LANES; LANE++) + { + temp_storage.packed_thread_counters[LANE][threadIdx.x] = 0; + } + } + + + /** + * Reset the unpacked counters in each thread + */ + __device__ __forceinline__ void ResetUnpackedCounters() + { + #pragma unroll + for (int LANE = 0; LANE < LANES_PER_WARP; LANE++) + { + #pragma unroll + for (int UNPACKED_COUNTER = 0; UNPACKED_COUNTER < PACKING_RATIO; UNPACKED_COUNTER++) + { + local_counts[LANE][UNPACKED_COUNTER] = 0; + } + } + } + + + /** + * Extracts and aggregates the digit counters for each counter lane + * owned by this warp + */ + __device__ __forceinline__ void UnpackDigitCounts() + { + unsigned int warp_id = threadIdx.x >> LOG_WARP_THREADS; + unsigned int warp_tid = LaneId(); + + #pragma unroll + for (int LANE = 0; LANE < LANES_PER_WARP; LANE++) + { + const int counter_lane = (LANE * WARPS) + warp_id; + if (counter_lane < COUNTER_LANES) + { + #pragma unroll + for (int PACKED_COUNTER = 0; PACKED_COUNTER < BLOCK_THREADS; PACKED_COUNTER += WARP_THREADS) + { + #pragma unroll + for (int UNPACKED_COUNTER = 0; UNPACKED_COUNTER < PACKING_RATIO; UNPACKED_COUNTER++) + { + OffsetT counter = temp_storage.thread_counters[counter_lane][warp_tid + PACKED_COUNTER][UNPACKED_COUNTER]; + local_counts[LANE][UNPACKED_COUNTER] += counter; + } + } + } + } + } + + + /** + * Processes a single, full tile + */ + __device__ __forceinline__ void ProcessFullTile(OffsetT block_offset) + { + // Tile of keys + bit_ordered_type keys[KEYS_PER_THREAD]; + + LoadDirectStriped(threadIdx.x, d_keys_in + block_offset, keys); + + // Prevent hoisting + CTA_SYNC(); + + // Bucket tile of keys + Iterate<0, KEYS_PER_THREAD>::BucketKeys(*this, keys); + } + + + /** + * Processes a single load (may have some threads masked off) + */ + __device__ __forceinline__ void ProcessPartialTile( + OffsetT block_offset, + const OffsetT &block_end) + { + // Process partial tile if necessary using single loads + for (OffsetT offset = threadIdx.x; offset < block_end - block_offset; offset += BLOCK_THREADS) + { + // Load and bucket key + bit_ordered_type key = d_keys_in[block_offset + offset]; + Bucket(key); + } + } + + + //--------------------------------------------------------------------- + // Interface + //--------------------------------------------------------------------- + + /** + * Constructor + */ + __device__ __forceinline__ AgentRadixSortUpsweep( + TempStorage &temp_storage, + const KeyT *d_keys_in, + int current_bit, + int num_bits, + DecomposerT decomposer = {}) + : + temp_storage(temp_storage.Alias()), + d_keys_in(reinterpret_cast(d_keys_in)), + current_bit(current_bit), + num_bits(num_bits), + decomposer(decomposer) + {} + + + /** + * Compute radix digit histograms from a segment of input tiles. + */ + __device__ __forceinline__ void ProcessRegion( + OffsetT block_offset, + const OffsetT &block_end) + { + // Reset digit counters in smem and unpacked counters in registers + ResetDigitCounters(); + ResetUnpackedCounters(); + + // Unroll batches of full tiles + while (block_end - block_offset >= UNROLLED_ELEMENTS) + { + for (int i = 0; i < UNROLL_COUNT; ++i) + { + ProcessFullTile(block_offset); + block_offset += TILE_ITEMS; + } + + CTA_SYNC(); + + // Aggregate back into local_count registers to prevent overflow + UnpackDigitCounts(); + + CTA_SYNC(); + + // Reset composite counters in lanes + ResetDigitCounters(); + } + + // Unroll single full tiles + while (block_end - block_offset >= TILE_ITEMS) + { + ProcessFullTile(block_offset); + block_offset += TILE_ITEMS; + } + + // Process partial tile if necessary + ProcessPartialTile( + block_offset, + block_end); + + CTA_SYNC(); + + // Aggregate back into local_count registers + UnpackDigitCounts(); + } + + + /** + * Extract counts (saving them to the external array) + */ + template + __device__ __forceinline__ void ExtractCounts( + OffsetT *counters, + int bin_stride = 1, + int bin_offset = 0) + { + unsigned int warp_id = threadIdx.x >> LOG_WARP_THREADS; + unsigned int warp_tid = LaneId(); + + // Place unpacked digit counters in shared memory + #pragma unroll + for (int LANE = 0; LANE < LANES_PER_WARP; LANE++) + { + int counter_lane = (LANE * WARPS) + warp_id; + if (counter_lane < COUNTER_LANES) + { + int digit_row = counter_lane << LOG_PACKING_RATIO; + + #pragma unroll + for (int UNPACKED_COUNTER = 0; UNPACKED_COUNTER < PACKING_RATIO; UNPACKED_COUNTER++) + { + int bin_idx = digit_row + UNPACKED_COUNTER; + + temp_storage.block_counters[warp_tid][bin_idx] = + local_counts[LANE][UNPACKED_COUNTER]; + } + } + } + + CTA_SYNC(); + + // Rake-reduce bin_count reductions + + // Whole blocks + #pragma unroll + for (int BIN_BASE = RADIX_DIGITS % BLOCK_THREADS; + (BIN_BASE + BLOCK_THREADS) <= RADIX_DIGITS; + BIN_BASE += BLOCK_THREADS) + { + int bin_idx = BIN_BASE + threadIdx.x; + + OffsetT bin_count = 0; + #pragma unroll + for (int i = 0; i < WARP_THREADS; ++i) + bin_count += temp_storage.block_counters[i][bin_idx]; + + if (IS_DESCENDING) + bin_idx = RADIX_DIGITS - bin_idx - 1; + + counters[(bin_stride * bin_idx) + bin_offset] = bin_count; + } + + // Remainder + if ((RADIX_DIGITS % BLOCK_THREADS != 0) && (threadIdx.x < RADIX_DIGITS)) + { + int bin_idx = threadIdx.x; + + OffsetT bin_count = 0; + #pragma unroll + for (int i = 0; i < WARP_THREADS; ++i) + bin_count += temp_storage.block_counters[i][bin_idx]; + + if (IS_DESCENDING) + bin_idx = RADIX_DIGITS - bin_idx - 1; + + counters[(bin_stride * bin_idx) + bin_offset] = bin_count; + } + } + + + /** + * Extract counts + */ + template + __device__ __forceinline__ void ExtractCounts( + OffsetT (&bin_count)[BINS_TRACKED_PER_THREAD]) ///< [out] The exclusive prefix sum for the digits [(threadIdx.x * BINS_TRACKED_PER_THREAD) ... (threadIdx.x * BINS_TRACKED_PER_THREAD) + BINS_TRACKED_PER_THREAD - 1] + { + unsigned int warp_id = threadIdx.x >> LOG_WARP_THREADS; + unsigned int warp_tid = LaneId(); + + // Place unpacked digit counters in shared memory + #pragma unroll + for (int LANE = 0; LANE < LANES_PER_WARP; LANE++) + { + int counter_lane = (LANE * WARPS) + warp_id; + if (counter_lane < COUNTER_LANES) + { + int digit_row = counter_lane << LOG_PACKING_RATIO; + + #pragma unroll + for (int UNPACKED_COUNTER = 0; UNPACKED_COUNTER < PACKING_RATIO; UNPACKED_COUNTER++) + { + int bin_idx = digit_row + UNPACKED_COUNTER; + + temp_storage.block_counters[warp_tid][bin_idx] = + local_counts[LANE][UNPACKED_COUNTER]; + } + } + } + + CTA_SYNC(); + + // Rake-reduce bin_count reductions + #pragma unroll + for (int track = 0; track < BINS_TRACKED_PER_THREAD; ++track) + { + int bin_idx = (threadIdx.x * BINS_TRACKED_PER_THREAD) + track; + + if ((BLOCK_THREADS == RADIX_DIGITS) || (bin_idx < RADIX_DIGITS)) + { + bin_count[track] = 0; + + #pragma unroll + for (int i = 0; i < WARP_THREADS; ++i) + bin_count[track] += temp_storage.block_counters[i][bin_idx]; + } + } + } + +}; + + +CUB_NAMESPACE_END + diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/agent/agent_scan.cuh b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/agent/agent_scan.cuh new file mode 100644 index 0000000000000000000000000000000000000000..7a5eef11ae3014c2323fa75b5087afb16485e4fd --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/agent/agent_scan.cuh @@ -0,0 +1,587 @@ +/****************************************************************************** + * Copyright (c) 2011, Duane Merrill. All rights reserved. + * Copyright (c) 2011-2022, NVIDIA CORPORATION. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the NVIDIA CORPORATION nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ******************************************************************************/ + +/** + * @file cub::AgentScan implements a stateful abstraction of CUDA thread blocks + * for participating in device-wide prefix scan . + */ + +#pragma once + +#include + +#include +#include +#include +#include +#include +#include +#include + +CUB_NAMESPACE_BEGIN + +/****************************************************************************** + * Tuning policy types + ******************************************************************************/ + +/** + * @brief Parameterizable tuning policy type for AgentScan + * + * @tparam NOMINAL_BLOCK_THREADS_4B + * Threads per thread block + * + * @tparam NOMINAL_ITEMS_PER_THREAD_4B + * Items per thread (per tile of input) + * + * @tparam ComputeT + * Dominant compute type + * + * @tparam _LOAD_ALGORITHM + * The BlockLoad algorithm to use + * + * @tparam _LOAD_MODIFIER + * Cache load modifier for reading input elements + * + * @tparam _STORE_ALGORITHM + * The BlockStore algorithm to use + * + * @tparam _SCAN_ALGORITHM + * The BlockScan algorithm to use + * + * @tparam DelayConstructorT + * Implementation detail, do not specify directly, requirements on the + * content of this type are subject to breaking change. + */ +template , + typename DelayConstructorT = detail::default_delay_constructor_t> +struct AgentScanPolicy : ScalingType +{ + static const BlockLoadAlgorithm LOAD_ALGORITHM = _LOAD_ALGORITHM; + static const CacheLoadModifier LOAD_MODIFIER = _LOAD_MODIFIER; + static const BlockStoreAlgorithm STORE_ALGORITHM = _STORE_ALGORITHM; + static const BlockScanAlgorithm SCAN_ALGORITHM = _SCAN_ALGORITHM; + + struct detail + { + using delay_constructor_t = DelayConstructorT; + }; +}; + +/****************************************************************************** + * Thread block abstractions + ******************************************************************************/ + +/** + * @brief AgentScan implements a stateful abstraction of CUDA thread blocks for + * participating in device-wide prefix scan. + * @tparam AgentScanPolicyT + * Parameterized AgentScanPolicyT tuning policy type + * + * @tparam InputIteratorT + * Random-access input iterator type + * + * @tparam OutputIteratorT + * Random-access output iterator type + * + * @tparam ScanOpT + * Scan functor type + * + * @tparam InitValueT + * The init_value element for ScanOpT type (cub::NullType for inclusive scan) + * + * @tparam OffsetT + * Signed integer type for global offsets + * + */ +template +struct AgentScan +{ + //--------------------------------------------------------------------- + // Types and constants + //--------------------------------------------------------------------- + + // The input value type + using InputT = cub::detail::value_t; + + // Tile status descriptor interface type + using ScanTileStateT = ScanTileState; + + // Input iterator wrapper type (for applying cache modifier) + // Wrap the native input pointer with CacheModifiedInputIterator + // or directly use the supplied input iterator type + using WrappedInputIteratorT = cub::detail::conditional_t< + std::is_pointer::value, + CacheModifiedInputIterator, + InputIteratorT>; + + // Constants + enum + { + // Inclusive scan if no init_value type is provided + IS_INCLUSIVE = std::is_same::value, + BLOCK_THREADS = AgentScanPolicyT::BLOCK_THREADS, + ITEMS_PER_THREAD = AgentScanPolicyT::ITEMS_PER_THREAD, + TILE_ITEMS = BLOCK_THREADS * ITEMS_PER_THREAD, + }; + + // Parameterized BlockLoad type + typedef BlockLoad + BlockLoadT; + + // Parameterized BlockStore type + typedef BlockStore + BlockStoreT; + + // Parameterized BlockScan type + typedef BlockScan + BlockScanT; + + // Callback type for obtaining tile prefix during block scan + using DelayConstructorT = typename AgentScanPolicyT::detail::delay_constructor_t; + using TilePrefixCallbackOpT = + TilePrefixCallbackOp; + + // Stateful BlockScan prefix callback type for managing a running total while + // scanning consecutive tiles + typedef BlockScanRunningPrefixOp RunningPrefixCallbackOp; + + // Shared memory type for this thread block + union _TempStorage + { + // Smem needed for tile loading + typename BlockLoadT::TempStorage load; + + // Smem needed for tile storing + typename BlockStoreT::TempStorage store; + + struct ScanStorage + { + // Smem needed for cooperative prefix callback + typename TilePrefixCallbackOpT::TempStorage prefix; + + // Smem needed for tile scanning + typename BlockScanT::TempStorage scan; + } scan_storage; + }; + + // Alias wrapper allowing storage to be unioned + struct TempStorage : Uninitialized<_TempStorage> + {}; + + //--------------------------------------------------------------------- + // Per-thread fields + //--------------------------------------------------------------------- + + _TempStorage &temp_storage; ///< Reference to temp_storage + WrappedInputIteratorT d_in; ///< Input data + OutputIteratorT d_out; ///< Output data + ScanOpT scan_op; ///< Binary scan operator + InitValueT init_value; ///< The init_value element for ScanOpT + + //--------------------------------------------------------------------- + // Block scan utility methods + //--------------------------------------------------------------------- + + /** + * Exclusive scan specialization (first tile) + */ + __device__ __forceinline__ void ScanTile(AccumT (&items)[ITEMS_PER_THREAD], + AccumT init_value, + ScanOpT scan_op, + AccumT &block_aggregate, + Int2Type /*is_inclusive*/) + { + BlockScanT(temp_storage.scan_storage.scan) + .ExclusiveScan(items, items, init_value, scan_op, block_aggregate); + block_aggregate = scan_op(init_value, block_aggregate); + } + + /** + * Inclusive scan specialization (first tile) + */ + __device__ __forceinline__ void ScanTile(AccumT (&items)[ITEMS_PER_THREAD], + InitValueT /*init_value*/, + ScanOpT scan_op, + AccumT &block_aggregate, + Int2Type /*is_inclusive*/) + { + BlockScanT(temp_storage.scan_storage.scan) + .InclusiveScan(items, items, scan_op, block_aggregate); + } + + /** + * Exclusive scan specialization (subsequent tiles) + */ + template + __device__ __forceinline__ void ScanTile(AccumT (&items)[ITEMS_PER_THREAD], + ScanOpT scan_op, + PrefixCallback &prefix_op, + Int2Type /*is_inclusive*/) + { + BlockScanT(temp_storage.scan_storage.scan) + .ExclusiveScan(items, items, scan_op, prefix_op); + } + + /** + * Inclusive scan specialization (subsequent tiles) + */ + template + __device__ __forceinline__ void ScanTile(AccumT (&items)[ITEMS_PER_THREAD], + ScanOpT scan_op, + PrefixCallback &prefix_op, + Int2Type /*is_inclusive*/) + { + BlockScanT(temp_storage.scan_storage.scan) + .InclusiveScan(items, items, scan_op, prefix_op); + } + + //--------------------------------------------------------------------- + // Constructor + //--------------------------------------------------------------------- + + /** + * @param temp_storage + * Reference to temp_storage + * + * @param d_in + * Input data + * + * @param d_out + * Output data + * + * @param scan_op + * Binary scan operator + * + * @param init_value + * Initial value to seed the exclusive scan + */ + __device__ __forceinline__ AgentScan(TempStorage &temp_storage, + InputIteratorT d_in, + OutputIteratorT d_out, + ScanOpT scan_op, + InitValueT init_value) + : temp_storage(temp_storage.Alias()) + , d_in(d_in) + , d_out(d_out) + , scan_op(scan_op) + , init_value(init_value) + {} + + //--------------------------------------------------------------------- + // Cooperatively scan a device-wide sequence of tiles with other CTAs + //--------------------------------------------------------------------- + + /** + * Process a tile of input (dynamic chained scan) + * @tparam IS_LAST_TILE + * Whether the current tile is the last tile + * + * @param num_remaining + * Number of global input items remaining (including this tile) + * + * @param tile_idx + * Tile index + * + * @param tile_offset + * Tile offset + * + * @param tile_state + * Global tile state descriptor + */ + template + __device__ __forceinline__ void ConsumeTile(OffsetT num_remaining, + int tile_idx, + OffsetT tile_offset, + ScanTileStateT &tile_state) + { + // Load items + AccumT items[ITEMS_PER_THREAD]; + + if (IS_LAST_TILE) + { + // Fill last element with the first element because collectives are + // not suffix guarded. + BlockLoadT(temp_storage.load) + .Load(d_in + tile_offset, items, num_remaining, *(d_in + tile_offset)); + } + else + { + BlockLoadT(temp_storage.load).Load(d_in + tile_offset, items); + } + + CTA_SYNC(); + + // Perform tile scan + if (tile_idx == 0) + { + // Scan first tile + AccumT block_aggregate; + ScanTile(items, + init_value, + scan_op, + block_aggregate, + Int2Type()); + + if ((!IS_LAST_TILE) && (threadIdx.x == 0)) + { + tile_state.SetInclusive(0, block_aggregate); + } + } + else + { + // Scan non-first tile + TilePrefixCallbackOpT prefix_op(tile_state, + temp_storage.scan_storage.prefix, + scan_op, + tile_idx); + ScanTile(items, scan_op, prefix_op, Int2Type()); + } + + CTA_SYNC(); + + // Store items + if (IS_LAST_TILE) + { + BlockStoreT(temp_storage.store) + .Store(d_out + tile_offset, items, num_remaining); + } + else + { + BlockStoreT(temp_storage.store).Store(d_out + tile_offset, items); + } + } + + /** + * @brief Scan tiles of items as part of a dynamic chained scan + * + * @param num_items + * Total number of input items + * + * @param tile_state + * Global tile state descriptor + * + * @param start_tile + * The starting tile for the current grid + */ + __device__ __forceinline__ void ConsumeRange(OffsetT num_items, + ScanTileStateT &tile_state, + int start_tile) + { + // Blocks are launched in increasing order, so just assign one tile per + // block + + // Current tile index + int tile_idx = start_tile + blockIdx.x; + + // Global offset for the current tile + OffsetT tile_offset = OffsetT(TILE_ITEMS) * tile_idx; + + // Remaining items (including this tile) + OffsetT num_remaining = num_items - tile_offset; + + if (num_remaining > TILE_ITEMS) + { + // Not last tile + ConsumeTile(num_remaining, tile_idx, tile_offset, tile_state); + } + else if (num_remaining > 0) + { + // Last tile + ConsumeTile(num_remaining, tile_idx, tile_offset, tile_state); + } + } + + //--------------------------------------------------------------------------- + // Scan an sequence of consecutive tiles (independent of other thread blocks) + //--------------------------------------------------------------------------- + + /** + * @brief Process a tile of input + * + * @param tile_offset + * Tile offset + * + * @param prefix_op + * Running prefix operator + * + * @param valid_items + * Number of valid items in the tile + */ + template + __device__ __forceinline__ void ConsumeTile(OffsetT tile_offset, + RunningPrefixCallbackOp &prefix_op, + int valid_items = TILE_ITEMS) + { + // Load items + AccumT items[ITEMS_PER_THREAD]; + + if (IS_LAST_TILE) + { + // Fill last element with the first element because collectives are + // not suffix guarded. + BlockLoadT(temp_storage.load) + .Load(d_in + tile_offset, items, valid_items, *(d_in + tile_offset)); + } + else + { + BlockLoadT(temp_storage.load).Load(d_in + tile_offset, items); + } + + CTA_SYNC(); + + // Block scan + if (IS_FIRST_TILE) + { + AccumT block_aggregate; + ScanTile(items, + init_value, + scan_op, + block_aggregate, + Int2Type()); + prefix_op.running_total = block_aggregate; + } + else + { + ScanTile(items, scan_op, prefix_op, Int2Type()); + } + + CTA_SYNC(); + + // Store items + if (IS_LAST_TILE) + { + BlockStoreT(temp_storage.store) + .Store(d_out + tile_offset, items, valid_items); + } + else + { + BlockStoreT(temp_storage.store).Store(d_out + tile_offset, items); + } + } + + /** + * @brief Scan a consecutive share of input tiles + * + * @param[in] range_offset + * Threadblock begin offset (inclusive) + * + * @param[in] range_end + * Threadblock end offset (exclusive) + */ + __device__ __forceinline__ void ConsumeRange(OffsetT range_offset, + OffsetT range_end) + { + BlockScanRunningPrefixOp prefix_op(scan_op); + + if (range_offset + TILE_ITEMS <= range_end) + { + // Consume first tile of input (full) + ConsumeTile(range_offset, prefix_op); + range_offset += TILE_ITEMS; + + // Consume subsequent full tiles of input + while (range_offset + TILE_ITEMS <= range_end) + { + ConsumeTile(range_offset, prefix_op); + range_offset += TILE_ITEMS; + } + + // Consume a partially-full tile + if (range_offset < range_end) + { + int valid_items = range_end - range_offset; + ConsumeTile(range_offset, prefix_op, valid_items); + } + } + else + { + // Consume the first tile of input (partially-full) + int valid_items = range_end - range_offset; + ConsumeTile(range_offset, prefix_op, valid_items); + } + } + + /** + * @brief Scan a consecutive share of input tiles, seeded with the + * specified prefix value + * @param[in] range_offset + * Threadblock begin offset (inclusive) + * + * @param[in] range_end + * Threadblock end offset (exclusive) + * + * @param[in] prefix + * The prefix to apply to the scan segment + */ + __device__ __forceinline__ void ConsumeRange(OffsetT range_offset, + OffsetT range_end, + AccumT prefix) + { + BlockScanRunningPrefixOp prefix_op(prefix, scan_op); + + // Consume full tiles of input + while (range_offset + TILE_ITEMS <= range_end) + { + ConsumeTile(range_offset, prefix_op); + range_offset += TILE_ITEMS; + } + + // Consume a partially-full tile + if (range_offset < range_end) + { + int valid_items = range_end - range_offset; + ConsumeTile(range_offset, prefix_op, valid_items); + } + } +}; + +CUB_NAMESPACE_END + diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/agent/agent_scan_by_key.cuh b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/agent/agent_scan_by_key.cuh new file mode 100644 index 0000000000000000000000000000000000000000..dffe38f86489e55eb5330fb0cfdb5e06aa1f44aa --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/agent/agent_scan_by_key.cuh @@ -0,0 +1,515 @@ +/****************************************************************************** + * Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the NVIDIA CORPORATION nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ******************************************************************************/ + +/** + * @file AgentScanByKey implements a stateful abstraction of CUDA thread blocks + * for participating in device-wide prefix scan by key. + */ + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +CUB_NAMESPACE_BEGIN + +/****************************************************************************** + * Tuning policy types + ******************************************************************************/ + +/** + * Parameterizable tuning policy type for AgentScanByKey + * + * @tparam DelayConstructorT + * Implementation detail, do not specify directly, requirements on the + * content of this type are subject to breaking change. + */ +template > +struct AgentScanByKeyPolicy +{ + static constexpr int BLOCK_THREADS = _BLOCK_THREADS; + static constexpr int ITEMS_PER_THREAD = _ITEMS_PER_THREAD; + + static constexpr BlockLoadAlgorithm LOAD_ALGORITHM = _LOAD_ALGORITHM; + static constexpr CacheLoadModifier LOAD_MODIFIER = _LOAD_MODIFIER; + static constexpr BlockScanAlgorithm SCAN_ALGORITHM = _SCAN_ALGORITHM; + static constexpr BlockStoreAlgorithm STORE_ALGORITHM = _STORE_ALGORITHM; + + struct detail + { + using delay_constructor_t = DelayConstructorT; + }; +}; + +/****************************************************************************** + * Thread block abstractions + ******************************************************************************/ + +/** + * @brief AgentScanByKey implements a stateful abstraction of CUDA thread + * blocks for participating in device-wide prefix scan by key. + * + * @tparam AgentScanByKeyPolicyT + * Parameterized AgentScanPolicyT tuning policy type + * + * @tparam KeysInputIteratorT + * Random-access input iterator type + * + * @tparam ValuesInputIteratorT + * Random-access input iterator type + * + * @tparam ValuesOutputIteratorT + * Random-access output iterator type + * + * @tparam EqualityOp + * Equality functor type + * + * @tparam ScanOpT + * Scan functor type + * + * @tparam InitValueT + * The init_value element for ScanOpT type (cub::NullType for inclusive scan) + * + * @tparam OffsetT + * Signed integer type for global offsets + * + */ +template +struct AgentScanByKey +{ + //--------------------------------------------------------------------- + // Types and constants + //--------------------------------------------------------------------- + + using KeyT = cub::detail::value_t; + using InputT = cub::detail::value_t; + using SizeValuePairT = KeyValuePair; + using KeyValuePairT = KeyValuePair; + using ReduceBySegmentOpT = ReduceBySegmentOp; + + using ScanTileStateT = ReduceByKeyScanTileState; + + // Constants + // Inclusive scan if no init_value type is provided + static constexpr int IS_INCLUSIVE = std::is_same::value; + static constexpr int BLOCK_THREADS = AgentScanByKeyPolicyT::BLOCK_THREADS; + static constexpr int ITEMS_PER_THREAD = + AgentScanByKeyPolicyT::ITEMS_PER_THREAD; + static constexpr int ITEMS_PER_TILE = BLOCK_THREADS * ITEMS_PER_THREAD; + + using WrappedKeysInputIteratorT = cub::detail::conditional_t< + std::is_pointer::value, + CacheModifiedInputIterator, + KeysInputIteratorT>; + + using WrappedValuesInputIteratorT = cub::detail::conditional_t< + std::is_pointer::value, + CacheModifiedInputIterator, + ValuesInputIteratorT>; + + using BlockLoadKeysT = BlockLoad; + + using BlockLoadValuesT = BlockLoad; + + using BlockStoreValuesT = BlockStore; + + using BlockDiscontinuityKeysT = BlockDiscontinuity; + + using DelayConstructorT = typename AgentScanByKeyPolicyT::detail::delay_constructor_t; + using TilePrefixCallbackT = + TilePrefixCallbackOp; + + using BlockScanT = BlockScan; + + union TempStorage_ + { + struct ScanStorage + { + typename BlockScanT::TempStorage scan; + typename TilePrefixCallbackT::TempStorage prefix; + typename BlockDiscontinuityKeysT::TempStorage discontinuity; + } scan_storage; + + typename BlockLoadKeysT::TempStorage load_keys; + typename BlockLoadValuesT::TempStorage load_values; + typename BlockStoreValuesT::TempStorage store_values; + }; + + struct TempStorage : cub::Uninitialized + {}; + + //--------------------------------------------------------------------- + // Per-thread fields + //--------------------------------------------------------------------- + + TempStorage_ &storage; + WrappedKeysInputIteratorT d_keys_in; + KeyT *d_keys_prev_in; + WrappedValuesInputIteratorT d_values_in; + ValuesOutputIteratorT d_values_out; + InequalityWrapper inequality_op; + ScanOpT scan_op; + ReduceBySegmentOpT pair_scan_op; + InitValueT init_value; + + //--------------------------------------------------------------------- + // Block scan utility methods (first tile) + //--------------------------------------------------------------------- + + // Exclusive scan specialization + __device__ __forceinline__ void + ScanTile(SizeValuePairT (&scan_items)[ITEMS_PER_THREAD], + SizeValuePairT &tile_aggregate, + Int2Type /* is_inclusive */) + { + BlockScanT(storage.scan_storage.scan) + .ExclusiveScan(scan_items, scan_items, pair_scan_op, tile_aggregate); + } + + // Inclusive scan specialization + __device__ __forceinline__ void + ScanTile(SizeValuePairT (&scan_items)[ITEMS_PER_THREAD], + SizeValuePairT &tile_aggregate, + Int2Type /* is_inclusive */) + { + BlockScanT(storage.scan_storage.scan) + .InclusiveScan(scan_items, scan_items, pair_scan_op, tile_aggregate); + } + + //--------------------------------------------------------------------- + // Block scan utility methods (subsequent tiles) + //--------------------------------------------------------------------- + + // Exclusive scan specialization (with prefix from predecessors) + __device__ __forceinline__ void + ScanTile(SizeValuePairT (&scan_items)[ITEMS_PER_THREAD], + SizeValuePairT &tile_aggregate, + TilePrefixCallbackT &prefix_op, + Int2Type /* is_incclusive */) + { + BlockScanT(storage.scan_storage.scan) + .ExclusiveScan(scan_items, scan_items, pair_scan_op, prefix_op); + tile_aggregate = prefix_op.GetBlockAggregate(); + } + + // Inclusive scan specialization (with prefix from predecessors) + __device__ __forceinline__ void + ScanTile(SizeValuePairT (&scan_items)[ITEMS_PER_THREAD], + SizeValuePairT &tile_aggregate, + TilePrefixCallbackT &prefix_op, + Int2Type /* is_inclusive */) + { + BlockScanT(storage.scan_storage.scan) + .InclusiveScan(scan_items, scan_items, pair_scan_op, prefix_op); + tile_aggregate = prefix_op.GetBlockAggregate(); + } + + //--------------------------------------------------------------------- + // Zip utility methods + //--------------------------------------------------------------------- + + template + __device__ __forceinline__ void + ZipValuesAndFlags(OffsetT num_remaining, + AccumT (&values)[ITEMS_PER_THREAD], + OffsetT (&segment_flags)[ITEMS_PER_THREAD], + SizeValuePairT (&scan_items)[ITEMS_PER_THREAD]) + { +// Zip values and segment_flags +#pragma unroll + for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ++ITEM) + { + // Set segment_flags for first out-of-bounds item, zero for others + if (IS_LAST_TILE && + OffsetT(threadIdx.x * ITEMS_PER_THREAD) + ITEM == num_remaining) + { + segment_flags[ITEM] = 1; + } + + scan_items[ITEM].value = values[ITEM]; + scan_items[ITEM].key = segment_flags[ITEM]; + } + } + + __device__ __forceinline__ void + UnzipValues(AccumT (&values)[ITEMS_PER_THREAD], + SizeValuePairT (&scan_items)[ITEMS_PER_THREAD]) + { +// Zip values and segment_flags +#pragma unroll + for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ++ITEM) + { + values[ITEM] = scan_items[ITEM].value; + } + } + + template ::value, + typename std::enable_if::type = 0> + __device__ __forceinline__ void + AddInitToScan(AccumT (&items)[ITEMS_PER_THREAD], + OffsetT (&flags)[ITEMS_PER_THREAD]) + { +#pragma unroll + for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ++ITEM) + { + items[ITEM] = flags[ITEM] ? init_value : scan_op(init_value, items[ITEM]); + } + } + + template ::value, + typename std::enable_if::type = 0> + __device__ __forceinline__ void + AddInitToScan(AccumT (&/*items*/)[ITEMS_PER_THREAD], + OffsetT (&/*flags*/)[ITEMS_PER_THREAD]) + {} + + //--------------------------------------------------------------------- + // Cooperatively scan a device-wide sequence of tiles with other CTAs + //--------------------------------------------------------------------- + + // Process a tile of input (dynamic chained scan) + // + template + __device__ __forceinline__ void ConsumeTile(OffsetT /*num_items*/, + OffsetT num_remaining, + int tile_idx, + OffsetT tile_base, + ScanTileStateT &tile_state) + { + // Load items + KeyT keys[ITEMS_PER_THREAD]; + AccumT values[ITEMS_PER_THREAD]; + OffsetT segment_flags[ITEMS_PER_THREAD]; + SizeValuePairT scan_items[ITEMS_PER_THREAD]; + + if (IS_LAST_TILE) + { + // Fill last element with the first element + // because collectives are not suffix guarded + BlockLoadKeysT(storage.load_keys) + .Load(d_keys_in + tile_base, + keys, + num_remaining, + *(d_keys_in + tile_base)); + } + else + { + BlockLoadKeysT(storage.load_keys).Load(d_keys_in + tile_base, keys); + } + + CTA_SYNC(); + + if (IS_LAST_TILE) + { + // Fill last element with the first element + // because collectives are not suffix guarded + BlockLoadValuesT(storage.load_values) + .Load(d_values_in + tile_base, + values, + num_remaining, + *(d_values_in + tile_base)); + } + else + { + BlockLoadValuesT(storage.load_values) + .Load(d_values_in + tile_base, values); + } + + CTA_SYNC(); + + // first tile + if (tile_idx == 0) + { + BlockDiscontinuityKeysT(storage.scan_storage.discontinuity) + .FlagHeads(segment_flags, keys, inequality_op); + + // Zip values and segment_flags + ZipValuesAndFlags(num_remaining, + values, + segment_flags, + scan_items); + + // Exclusive scan of values and segment_flags + SizeValuePairT tile_aggregate; + ScanTile(scan_items, tile_aggregate, Int2Type()); + + if (threadIdx.x == 0) + { + if (!IS_LAST_TILE) + { + tile_state.SetInclusive(0, tile_aggregate); + } + + scan_items[0].key = 0; + } + } + else + { + KeyT tile_pred_key = (threadIdx.x == 0) ? d_keys_prev_in[tile_idx] + : KeyT(); + + BlockDiscontinuityKeysT(storage.scan_storage.discontinuity) + .FlagHeads(segment_flags, keys, inequality_op, tile_pred_key); + + // Zip values and segment_flags + ZipValuesAndFlags(num_remaining, + values, + segment_flags, + scan_items); + + SizeValuePairT tile_aggregate; + TilePrefixCallbackT prefix_op(tile_state, + storage.scan_storage.prefix, + pair_scan_op, + tile_idx); + ScanTile(scan_items, tile_aggregate, prefix_op, Int2Type()); + } + + CTA_SYNC(); + + UnzipValues(values, scan_items); + + AddInitToScan(values, segment_flags); + + // Store items + if (IS_LAST_TILE) + { + BlockStoreValuesT(storage.store_values) + .Store(d_values_out + tile_base, values, num_remaining); + } + else + { + BlockStoreValuesT(storage.store_values) + .Store(d_values_out + tile_base, values); + } + } + + //--------------------------------------------------------------------- + // Constructor + //--------------------------------------------------------------------- + + // Dequeue and scan tiles of items as part of a dynamic chained scan + // with Init functor + __device__ __forceinline__ AgentScanByKey(TempStorage &storage, + KeysInputIteratorT d_keys_in, + KeyT *d_keys_prev_in, + ValuesInputIteratorT d_values_in, + ValuesOutputIteratorT d_values_out, + EqualityOp equality_op, + ScanOpT scan_op, + InitValueT init_value) + : storage(storage.Alias()) + , d_keys_in(d_keys_in) + , d_keys_prev_in(d_keys_prev_in) + , d_values_in(d_values_in) + , d_values_out(d_values_out) + , inequality_op(equality_op) + , scan_op(scan_op) + , pair_scan_op(scan_op) + , init_value(init_value) + {} + + /** + * Scan tiles of items as part of a dynamic chained scan + * + * @param num_items + * Total number of input items + * + * @param tile_state + * Global tile state descriptor + * + * start_tile + * The starting tile for the current grid + */ + __device__ __forceinline__ void ConsumeRange(OffsetT num_items, + ScanTileStateT &tile_state, + int start_tile) + { + int tile_idx = blockIdx.x; + OffsetT tile_base = OffsetT(ITEMS_PER_TILE) * tile_idx; + OffsetT num_remaining = num_items - tile_base; + + if (num_remaining > ITEMS_PER_TILE) + { + // Not the last tile (full) + ConsumeTile(num_items, + num_remaining, + tile_idx, + tile_base, + tile_state); + } + else if (num_remaining > 0) + { + // The last tile (possibly partially-full) + ConsumeTile(num_items, + num_remaining, + tile_idx, + tile_base, + tile_state); + } + } +}; + +CUB_NAMESPACE_END + diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/agent/agent_segment_fixup.cuh b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/agent/agent_segment_fixup.cuh new file mode 100644 index 0000000000000000000000000000000000000000..bd2837ce06bb7aeef00e3ef8afd6ed36ce58a215 --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/agent/agent_segment_fixup.cuh @@ -0,0 +1,372 @@ +/****************************************************************************** + * Copyright (c) 2011, Duane Merrill. All rights reserved. + * Copyright (c) 2011-2018, NVIDIA CORPORATION. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the NVIDIA CORPORATION nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ******************************************************************************/ + +/** + * \file + * cub::AgentSegmentFixup implements a stateful abstraction of CUDA thread blocks for participating in device-wide reduce-value-by-key. + */ + +#pragma once + +#include + +#include "single_pass_scan_operators.cuh" +#include "../block/block_load.cuh" +#include "../block/block_store.cuh" +#include "../block/block_scan.cuh" +#include "../block/block_discontinuity.cuh" +#include "../config.cuh" +#include "../iterator/cache_modified_input_iterator.cuh" +#include "../iterator/constant_input_iterator.cuh" + +CUB_NAMESPACE_BEGIN + + +/****************************************************************************** + * Tuning policy types + ******************************************************************************/ + +/** + * Parameterizable tuning policy type for AgentSegmentFixup + */ +template < + int _BLOCK_THREADS, ///< Threads per thread block + int _ITEMS_PER_THREAD, ///< Items per thread (per tile of input) + BlockLoadAlgorithm _LOAD_ALGORITHM, ///< The BlockLoad algorithm to use + CacheLoadModifier _LOAD_MODIFIER, ///< Cache load modifier for reading input elements + BlockScanAlgorithm _SCAN_ALGORITHM> ///< The BlockScan algorithm to use +struct AgentSegmentFixupPolicy +{ + enum + { + BLOCK_THREADS = _BLOCK_THREADS, ///< Threads per thread block + ITEMS_PER_THREAD = _ITEMS_PER_THREAD, ///< Items per thread (per tile of input) + }; + + static const BlockLoadAlgorithm LOAD_ALGORITHM = _LOAD_ALGORITHM; ///< The BlockLoad algorithm to use + static const CacheLoadModifier LOAD_MODIFIER = _LOAD_MODIFIER; ///< Cache load modifier for reading input elements + static const BlockScanAlgorithm SCAN_ALGORITHM = _SCAN_ALGORITHM; ///< The BlockScan algorithm to use +}; + + +/****************************************************************************** + * Thread block abstractions + ******************************************************************************/ + +/** + * \brief AgentSegmentFixup implements a stateful abstraction of CUDA thread blocks for participating in device-wide reduce-value-by-key + */ +template < + typename AgentSegmentFixupPolicyT, ///< Parameterized AgentSegmentFixupPolicy tuning policy type + typename PairsInputIteratorT, ///< Random-access input iterator type for keys + typename AggregatesOutputIteratorT, ///< Random-access output iterator type for values + typename EqualityOpT, ///< KeyT equality operator type + typename ReductionOpT, ///< ValueT reduction operator type + typename OffsetT> ///< Signed integer type for global offsets +struct AgentSegmentFixup +{ + //--------------------------------------------------------------------- + // Types and constants + //--------------------------------------------------------------------- + + // Data type of key-value input iterator + using KeyValuePairT = cub::detail::value_t; + + // Value type + using ValueT = typename KeyValuePairT::Value; + + // Tile status descriptor interface type + using ScanTileStateT = ReduceByKeyScanTileState; + + // Constants + enum + { + BLOCK_THREADS = AgentSegmentFixupPolicyT::BLOCK_THREADS, + ITEMS_PER_THREAD = AgentSegmentFixupPolicyT::ITEMS_PER_THREAD, + TILE_ITEMS = BLOCK_THREADS * ITEMS_PER_THREAD, + + // Whether or not do fixup using RLE + global atomics + USE_ATOMIC_FIXUP = (std::is_same::value || + std::is_same::value || + std::is_same::value || + std::is_same::value), + + // Whether or not the scan operation has a zero-valued identity value + // (true if we're performing addition on a primitive type) + HAS_IDENTITY_ZERO = (std::is_same::value) && + (Traits::PRIMITIVE), + }; + + // Cache-modified Input iterator wrapper type (for applying cache modifier) for keys + // Wrap the native input pointer with CacheModifiedValuesInputIterator + // or directly use the supplied input iterator type + using WrappedPairsInputIteratorT = cub::detail::conditional_t< + std::is_pointer::value, + CacheModifiedInputIterator, + PairsInputIteratorT>; + + // Cache-modified Input iterator wrapper type (for applying cache modifier) for fixup values + // Wrap the native input pointer with CacheModifiedValuesInputIterator + // or directly use the supplied input iterator type + using WrappedFixupInputIteratorT = cub::detail::conditional_t< + std::is_pointer::value, + CacheModifiedInputIterator, + AggregatesOutputIteratorT>; + + // Reduce-value-by-segment scan operator + using ReduceBySegmentOpT = ReduceByKeyOp; + + // Parameterized BlockLoad type for pairs + using BlockLoadPairs = BlockLoad; + + // Parameterized BlockScan type + using BlockScanT = BlockScan; + + // Callback type for obtaining tile prefix during block scan + using TilePrefixCallbackOpT = + TilePrefixCallbackOp; + + // Shared memory type for this thread block + union _TempStorage + { + struct ScanStorage + { + typename BlockScanT::TempStorage scan; // Smem needed for tile scanning + typename TilePrefixCallbackOpT::TempStorage prefix; // Smem needed for cooperative prefix callback + } scan_storage; + + // Smem needed for loading keys + typename BlockLoadPairs::TempStorage load_pairs; + }; + + // Alias wrapper allowing storage to be unioned + struct TempStorage : Uninitialized<_TempStorage> {}; + + + //--------------------------------------------------------------------- + // Per-thread fields + //--------------------------------------------------------------------- + + _TempStorage& temp_storage; ///< Reference to temp_storage + WrappedPairsInputIteratorT d_pairs_in; ///< Input keys + AggregatesOutputIteratorT d_aggregates_out; ///< Output value aggregates + WrappedFixupInputIteratorT d_fixup_in; ///< Fixup input values + InequalityWrapper inequality_op; ///< KeyT inequality operator + ReductionOpT reduction_op; ///< Reduction operator + ReduceBySegmentOpT scan_op; ///< Reduce-by-segment scan operator + + + //--------------------------------------------------------------------- + // Constructor + //--------------------------------------------------------------------- + + // Constructor + __device__ __forceinline__ + AgentSegmentFixup( + TempStorage& temp_storage, ///< Reference to temp_storage + PairsInputIteratorT d_pairs_in, ///< Input keys + AggregatesOutputIteratorT d_aggregates_out, ///< Output value aggregates + EqualityOpT equality_op, ///< KeyT equality operator + ReductionOpT reduction_op) ///< ValueT reduction operator + : + temp_storage(temp_storage.Alias()), + d_pairs_in(d_pairs_in), + d_aggregates_out(d_aggregates_out), + d_fixup_in(d_aggregates_out), + inequality_op(equality_op), + reduction_op(reduction_op), + scan_op(reduction_op) + {} + + + //--------------------------------------------------------------------- + // Cooperatively scan a device-wide sequence of tiles with other CTAs + //--------------------------------------------------------------------- + + + /** + * Process input tile. Specialized for atomic-fixup + */ + template + __device__ __forceinline__ void ConsumeTile( + OffsetT num_remaining, ///< Number of global input items remaining (including this tile) + int tile_idx, ///< Tile index + OffsetT tile_offset, ///< Tile offset + ScanTileStateT& tile_state, ///< Global tile state descriptor + Int2Type use_atomic_fixup) ///< Marker whether to use atomicAdd (instead of reduce-by-key) + { + KeyValuePairT pairs[ITEMS_PER_THREAD]; + + // Load pairs + KeyValuePairT oob_pair; + oob_pair.key = -1; + + if (IS_LAST_TILE) + BlockLoadPairs(temp_storage.load_pairs).Load(d_pairs_in + tile_offset, pairs, num_remaining, oob_pair); + else + BlockLoadPairs(temp_storage.load_pairs).Load(d_pairs_in + tile_offset, pairs); + + // RLE + #pragma unroll + for (int ITEM = 1; ITEM < ITEMS_PER_THREAD; ++ITEM) + { + ValueT* d_scatter = d_aggregates_out + pairs[ITEM - 1].key; + if (pairs[ITEM].key != pairs[ITEM - 1].key) + atomicAdd(d_scatter, pairs[ITEM - 1].value); + else + pairs[ITEM].value = reduction_op(pairs[ITEM - 1].value, pairs[ITEM].value); + } + + // Flush last item if valid + ValueT* d_scatter = d_aggregates_out + pairs[ITEMS_PER_THREAD - 1].key; + if ((!IS_LAST_TILE) || (pairs[ITEMS_PER_THREAD - 1].key >= 0)) + atomicAdd(d_scatter, pairs[ITEMS_PER_THREAD - 1].value); + } + + + /** + * Process input tile. Specialized for reduce-by-key fixup + */ + template + __device__ __forceinline__ void ConsumeTile( + OffsetT num_remaining, ///< Number of global input items remaining (including this tile) + int tile_idx, ///< Tile index + OffsetT tile_offset, ///< Tile offset + ScanTileStateT& tile_state, ///< Global tile state descriptor + Int2Type use_atomic_fixup) ///< Marker whether to use atomicAdd (instead of reduce-by-key) + { + KeyValuePairT pairs[ITEMS_PER_THREAD]; + KeyValuePairT scatter_pairs[ITEMS_PER_THREAD]; + + // Load pairs + KeyValuePairT oob_pair; + oob_pair.key = -1; + + if (IS_LAST_TILE) + BlockLoadPairs(temp_storage.load_pairs).Load(d_pairs_in + tile_offset, pairs, num_remaining, oob_pair); + else + BlockLoadPairs(temp_storage.load_pairs).Load(d_pairs_in + tile_offset, pairs); + + CTA_SYNC(); + + KeyValuePairT tile_aggregate; + if (tile_idx == 0) + { + // Exclusive scan of values and segment_flags + BlockScanT(temp_storage.scan_storage.scan).ExclusiveScan(pairs, scatter_pairs, scan_op, tile_aggregate); + + // Update tile status if this is not the last tile + if (threadIdx.x == 0) + { + // Set first segment id to not trigger a flush (invalid from exclusive scan) + scatter_pairs[0].key = pairs[0].key; + + if (!IS_LAST_TILE) + tile_state.SetInclusive(0, tile_aggregate); + + } + } + else + { + // Exclusive scan of values and segment_flags + TilePrefixCallbackOpT prefix_op(tile_state, temp_storage.scan_storage.prefix, scan_op, tile_idx); + BlockScanT(temp_storage.scan_storage.scan).ExclusiveScan(pairs, scatter_pairs, scan_op, prefix_op); + tile_aggregate = prefix_op.GetBlockAggregate(); + } + + // Scatter updated values + #pragma unroll + for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ++ITEM) + { + if (scatter_pairs[ITEM].key != pairs[ITEM].key) + { + // Update the value at the key location + ValueT value = d_fixup_in[scatter_pairs[ITEM].key]; + value = reduction_op(value, scatter_pairs[ITEM].value); + + d_aggregates_out[scatter_pairs[ITEM].key] = value; + } + } + + // Finalize the last item + if (IS_LAST_TILE) + { + // Last thread will output final count and last item, if necessary + if (threadIdx.x == BLOCK_THREADS - 1) + { + // If the last tile is a whole tile, the inclusive prefix contains accumulated value reduction for the last segment + if (num_remaining == TILE_ITEMS) + { + // Update the value at the key location + OffsetT last_key = pairs[ITEMS_PER_THREAD - 1].key; + d_aggregates_out[last_key] = reduction_op(tile_aggregate.value, d_fixup_in[last_key]); + } + } + } + } + + + /** + * Scan tiles of items as part of a dynamic chained scan + */ + __device__ __forceinline__ void ConsumeRange( + OffsetT num_items, ///< Total number of input items + int num_tiles, ///< Total number of input tiles + ScanTileStateT& tile_state) ///< Global tile state descriptor + { + // Blocks are launched in increasing order, so just assign one tile per block + int tile_idx = (blockIdx.x * gridDim.y) + blockIdx.y; // Current tile index + OffsetT tile_offset = tile_idx * TILE_ITEMS; // Global offset for the current tile + OffsetT num_remaining = num_items - tile_offset; // Remaining items (including this tile) + + if (num_remaining > TILE_ITEMS) + { + // Not the last tile (full) + ConsumeTile(num_remaining, tile_idx, tile_offset, tile_state, Int2Type()); + } + else if (num_remaining > 0) + { + // The last tile (possibly partially-full) + ConsumeTile(num_remaining, tile_idx, tile_offset, tile_state, Int2Type()); + } + } + +}; + + +CUB_NAMESPACE_END + diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/agent/agent_segmented_radix_sort.cuh b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/agent/agent_segmented_radix_sort.cuh new file mode 100644 index 0000000000000000000000000000000000000000..a629771120e2f6b14d246efe82491761269acb97 --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/agent/agent_segmented_radix_sort.cuh @@ -0,0 +1,297 @@ +/****************************************************************************** + * Copyright (c) 2011-2021, NVIDIA CORPORATION. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the NVIDIA CORPORATION nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ******************************************************************************/ + +#pragma once + +#include +#include +#include +#include +#include +#include + + +CUB_NAMESPACE_BEGIN + + +/** + * This agent will be implementing the `DeviceSegmentedRadixSort` when the + * https://github.com/NVIDIA/cub/issues/383 is addressed. + * + * @tparam IS_DESCENDING + * Whether or not the sorted-order is high-to-low + * + * @tparam SegmentedPolicyT + * Chained tuning policy + * + * @tparam KeyT + * Key type + * + * @tparam ValueT + * Value type + * + * @tparam OffsetT + * Signed integer type for global offsets + */ +template +struct AgentSegmentedRadixSort +{ + OffsetT num_items; + + static constexpr int ITEMS_PER_THREAD = SegmentedPolicyT::ITEMS_PER_THREAD; + static constexpr int BLOCK_THREADS = SegmentedPolicyT::BLOCK_THREADS; + static constexpr int RADIX_BITS = SegmentedPolicyT::RADIX_BITS; + static constexpr int RADIX_DIGITS = 1 << RADIX_BITS; + static constexpr int KEYS_ONLY = std::is_same::value; + + using traits = detail::radix::traits_t; + using bit_ordered_type = typename traits::bit_ordered_type; + + // Huge segment handlers + using BlockUpsweepT = AgentRadixSortUpsweep; + using DigitScanT = BlockScan; + using BlockDownsweepT = + AgentRadixSortDownsweep; + + /// Number of bin-starting offsets tracked per thread + static constexpr int BINS_TRACKED_PER_THREAD = BlockDownsweepT::BINS_TRACKED_PER_THREAD; + + // Small segment handlers + using BlockRadixSortT = + BlockRadixSort; + + using BlockKeyLoadT = BlockLoad; + + using BlockValueLoadT = BlockLoad; + + union _TempStorage + { + // Huge segment handlers + typename BlockUpsweepT::TempStorage upsweep; + typename BlockDownsweepT::TempStorage downsweep; + + struct UnboundBlockSort + { + OffsetT reverse_counts_in[RADIX_DIGITS]; + OffsetT reverse_counts_out[RADIX_DIGITS]; + typename DigitScanT::TempStorage scan; + } unbound_sort; + + // Small segment handlers + typename BlockKeyLoadT::TempStorage keys_load; + typename BlockValueLoadT::TempStorage values_load; + typename BlockRadixSortT::TempStorage sort; + }; + + using TempStorage = Uninitialized<_TempStorage>; + _TempStorage &temp_storage; + + DecomposerT decomposer; + + __device__ __forceinline__ + AgentSegmentedRadixSort(OffsetT num_items, + TempStorage &temp_storage, + DecomposerT decomposer = {}) + : num_items(num_items) + , temp_storage(temp_storage.Alias()) + , decomposer(decomposer) + {} + + __device__ __forceinline__ void ProcessSinglePass(int begin_bit, + int end_bit, + const KeyT *d_keys_in, + const ValueT *d_values_in, + KeyT *d_keys_out, + ValueT *d_values_out) + { + KeyT thread_keys[ITEMS_PER_THREAD]; + ValueT thread_values[ITEMS_PER_THREAD]; + + // For FP64 the difference is: + // Lowest() -> -1.79769e+308 = 00...00b -> TwiddleIn -> -0 = 10...00b + // LOWEST -> -nan = 11...11b -> TwiddleIn -> 0 = 00...00b + + bit_ordered_type default_key_bits = IS_DESCENDING + ? traits::min_raw_binary_key(decomposer) + : traits::max_raw_binary_key(decomposer); + KeyT oob_default = reinterpret_cast(default_key_bits); + + if (!KEYS_ONLY) + { + BlockValueLoadT(temp_storage.values_load) + .Load(d_values_in, thread_values, num_items); + + CTA_SYNC(); + } + + { + BlockKeyLoadT(temp_storage.keys_load) + .Load(d_keys_in, thread_keys, num_items, oob_default); + + CTA_SYNC(); + } + + BlockRadixSortT(temp_storage.sort).SortBlockedToStriped( + thread_keys, + thread_values, + begin_bit, + end_bit, + Int2Type(), + Int2Type(), + decomposer); + + cub::StoreDirectStriped( + threadIdx.x, d_keys_out, thread_keys, num_items); + + if (!KEYS_ONLY) + { + cub::StoreDirectStriped( + threadIdx.x, d_values_out, thread_values, num_items); + } + } + + __device__ __forceinline__ void ProcessIterative(int current_bit, + int pass_bits, + const KeyT *d_keys_in, + const ValueT *d_values_in, + KeyT *d_keys_out, + ValueT *d_values_out) + { + // Upsweep + BlockUpsweepT upsweep(temp_storage.upsweep, + d_keys_in, + current_bit, + pass_bits, + decomposer); + upsweep.ProcessRegion(OffsetT{}, num_items); + + CTA_SYNC(); + + // The count of each digit value in this pass (valid in the first RADIX_DIGITS threads) + OffsetT bin_count[BINS_TRACKED_PER_THREAD]; + upsweep.ExtractCounts(bin_count); + + CTA_SYNC(); + + if (IS_DESCENDING) + { + // Reverse bin counts + #pragma unroll + for (int track = 0; track < BINS_TRACKED_PER_THREAD; ++track) + { + int bin_idx = (threadIdx.x * BINS_TRACKED_PER_THREAD) + track; + + if ((BLOCK_THREADS == RADIX_DIGITS) || (bin_idx < RADIX_DIGITS)) + { + temp_storage.unbound_sort.reverse_counts_in[bin_idx] = bin_count[track]; + } + } + + CTA_SYNC(); + + #pragma unroll + for (int track = 0; track < BINS_TRACKED_PER_THREAD; ++track) + { + int bin_idx = (threadIdx.x * BINS_TRACKED_PER_THREAD) + track; + + if ((BLOCK_THREADS == RADIX_DIGITS) || (bin_idx < RADIX_DIGITS)) + { + bin_count[track] = temp_storage.unbound_sort.reverse_counts_in[RADIX_DIGITS - bin_idx - 1]; + } + } + } + + // Scan + // The global scatter base offset for each digit value in this pass + // (valid in the first RADIX_DIGITS threads) + OffsetT bin_offset[BINS_TRACKED_PER_THREAD]; + DigitScanT(temp_storage.unbound_sort.scan).ExclusiveSum(bin_count, bin_offset); + + if (IS_DESCENDING) + { + // Reverse bin offsets + #pragma unroll + for (int track = 0; track < BINS_TRACKED_PER_THREAD; ++track) + { + int bin_idx = (threadIdx.x * BINS_TRACKED_PER_THREAD) + track; + + if ((BLOCK_THREADS == RADIX_DIGITS) || (bin_idx < RADIX_DIGITS)) + { + temp_storage.unbound_sort.reverse_counts_out[threadIdx.x] = bin_offset[track]; + } + } + + CTA_SYNC(); + + #pragma unroll + for (int track = 0; track < BINS_TRACKED_PER_THREAD; ++track) + { + int bin_idx = (threadIdx.x * BINS_TRACKED_PER_THREAD) + track; + + if ((BLOCK_THREADS == RADIX_DIGITS) || (bin_idx < RADIX_DIGITS)) + { + bin_offset[track] = temp_storage.unbound_sort.reverse_counts_out[RADIX_DIGITS - bin_idx - 1]; + } + } + } + + CTA_SYNC(); + + // Downsweep + BlockDownsweepT downsweep(temp_storage.downsweep, + bin_offset, + num_items, + d_keys_in, + d_keys_out, + d_values_in, + d_values_out, + current_bit, + pass_bits, + decomposer); + downsweep.ProcessRegion(OffsetT{}, num_items); + } +}; + + +CUB_NAMESPACE_END diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/agent/agent_select_if.cuh b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/agent/agent_select_if.cuh new file mode 100644 index 0000000000000000000000000000000000000000..4347602c19b980dce9e516d06f692373c80dfe2c --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/agent/agent_select_if.cuh @@ -0,0 +1,712 @@ +/****************************************************************************** + * Copyright (c) 2011, Duane Merrill. All rights reserved. + * Copyright (c) 2011-2018, NVIDIA CORPORATION. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the NVIDIA CORPORATION nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ******************************************************************************/ + +/** + * \file + * cub::AgentSelectIf implements a stateful abstraction of CUDA thread blocks for participating in device-wide select. + */ + +#pragma once + +#include + +#include "single_pass_scan_operators.cuh" +#include "../block/block_load.cuh" +#include "../block/block_store.cuh" +#include "../block/block_scan.cuh" +#include "../block/block_exchange.cuh" +#include "../block/block_discontinuity.cuh" +#include "../config.cuh" +#include "../grid/grid_queue.cuh" +#include "../iterator/cache_modified_input_iterator.cuh" + +CUB_NAMESPACE_BEGIN + + +/****************************************************************************** + * Tuning policy types + ******************************************************************************/ + +/** + * Parameterizable tuning policy type for AgentSelectIf + * + * @tparam _BLOCK_THREADS + * Threads per thread block + * + * @tparam _ITEMS_PER_THREAD + * Items per thread (per tile of input) + * + * @tparam _LOAD_ALGORITHM + * The BlockLoad algorithm to use + * + * @tparam _LOAD_MODIFIER + * Cache load modifier for reading input elements + * + * @tparam _SCAN_ALGORITHM + * The BlockScan algorithm to use + * + * @tparam DelayConstructorT + * Implementation detail, do not specify directly, requirements on the + * content of this type are subject to breaking change. + */ +template > +struct AgentSelectIfPolicy +{ + enum + { + BLOCK_THREADS = _BLOCK_THREADS, ///< Threads per thread block + ITEMS_PER_THREAD = _ITEMS_PER_THREAD, ///< Items per thread (per tile of input) + }; + + static const BlockLoadAlgorithm LOAD_ALGORITHM = _LOAD_ALGORITHM; ///< The BlockLoad algorithm to use + static const CacheLoadModifier LOAD_MODIFIER = _LOAD_MODIFIER; ///< Cache load modifier for reading input elements + static const BlockScanAlgorithm SCAN_ALGORITHM = _SCAN_ALGORITHM; ///< The BlockScan algorithm to use + + struct detail + { + using delay_constructor_t = DelayConstructorT; + }; +}; + + + + +/****************************************************************************** + * Thread block abstractions + ******************************************************************************/ + + +/** + * \brief AgentSelectIf implements a stateful abstraction of CUDA thread blocks for participating in device-wide selection + * + * Performs functor-based selection if SelectOpT functor type != NullType + * Otherwise performs flag-based selection if FlagsInputIterator's value type != NullType + * Otherwise performs discontinuity selection (keep unique) + */ +template < + typename AgentSelectIfPolicyT, ///< Parameterized AgentSelectIfPolicy tuning policy type + typename InputIteratorT, ///< Random-access input iterator type for selection items + typename FlagsInputIteratorT, ///< Random-access input iterator type for selections (NullType* if a selection functor or discontinuity flagging is to be used for selection) + typename SelectedOutputIteratorT, ///< Random-access output iterator type for selection_flags items + typename SelectOpT, ///< Selection operator type (NullType if selections or discontinuity flagging is to be used for selection) + typename EqualityOpT, ///< Equality operator type (NullType if selection functor or selections is to be used for selection) + typename OffsetT, ///< Signed integer type for global offsets + bool KEEP_REJECTS> ///< Whether or not we push rejected items to the back of the output +struct AgentSelectIf +{ + //--------------------------------------------------------------------- + // Types and constants + //--------------------------------------------------------------------- + + // The input value type + using InputT = cub::detail::value_t; + + // The flag value type + using FlagT = cub::detail::value_t; + + // Tile status descriptor interface type + using ScanTileStateT = ScanTileState; + + // Constants + enum + { + USE_SELECT_OP, + USE_SELECT_FLAGS, + USE_DISCONTINUITY, + + BLOCK_THREADS = AgentSelectIfPolicyT::BLOCK_THREADS, + ITEMS_PER_THREAD = AgentSelectIfPolicyT::ITEMS_PER_THREAD, + TILE_ITEMS = BLOCK_THREADS * ITEMS_PER_THREAD, + TWO_PHASE_SCATTER = (ITEMS_PER_THREAD > 1), + + SELECT_METHOD = + (!std::is_same::value) ? USE_SELECT_OP + : (!std::is_same::value) ? USE_SELECT_FLAGS + : USE_DISCONTINUITY + }; + + // Cache-modified Input iterator wrapper type (for applying cache modifier) for items + // Wrap the native input pointer with CacheModifiedValuesInputIterator + // or directly use the supplied input iterator type + using WrappedInputIteratorT = cub::detail::conditional_t< + std::is_pointer::value, + CacheModifiedInputIterator, + InputIteratorT>; + + // Cache-modified Input iterator wrapper type (for applying cache modifier) for values + // Wrap the native input pointer with CacheModifiedValuesInputIterator + // or directly use the supplied input iterator type + using WrappedFlagsInputIteratorT = cub::detail::conditional_t< + std::is_pointer::value, + CacheModifiedInputIterator, + FlagsInputIteratorT>; + + // Parameterized BlockLoad type for input data + using BlockLoadT = BlockLoad; + + // Parameterized BlockLoad type for flags + using BlockLoadFlags = BlockLoad; + + // Parameterized BlockDiscontinuity type for items + using BlockDiscontinuityT = BlockDiscontinuity; + + // Parameterized BlockScan type + using BlockScanT = + BlockScan; + + + // Callback type for obtaining tile prefix during block scan + using DelayConstructorT = typename AgentSelectIfPolicyT::detail::delay_constructor_t; + using TilePrefixCallbackOpT = + TilePrefixCallbackOp; + + // Item exchange type + typedef InputT ItemExchangeT[TILE_ITEMS]; + + // Shared memory type for this thread block + union _TempStorage + { + struct ScanStorage + { + typename BlockScanT::TempStorage scan; // Smem needed for tile scanning + typename TilePrefixCallbackOpT::TempStorage prefix; // Smem needed for cooperative prefix callback + typename BlockDiscontinuityT::TempStorage discontinuity; // Smem needed for discontinuity detection + } scan_storage; + + // Smem needed for loading items + typename BlockLoadT::TempStorage load_items; + + // Smem needed for loading values + typename BlockLoadFlags::TempStorage load_flags; + + // Smem needed for compacting items (allows non POD items in this union) + Uninitialized raw_exchange; + }; + + // Alias wrapper allowing storage to be unioned + struct TempStorage : Uninitialized<_TempStorage> {}; + + + //--------------------------------------------------------------------- + // Per-thread fields + //--------------------------------------------------------------------- + + _TempStorage& temp_storage; ///< Reference to temp_storage + WrappedInputIteratorT d_in; ///< Input items + SelectedOutputIteratorT d_selected_out; ///< Unique output items + WrappedFlagsInputIteratorT d_flags_in; ///< Input selection flags (if applicable) + InequalityWrapper inequality_op; ///< T inequality operator + SelectOpT select_op; ///< Selection operator + OffsetT num_items; ///< Total number of input items + + + //--------------------------------------------------------------------- + // Constructor + //--------------------------------------------------------------------- + + // Constructor + __device__ __forceinline__ + AgentSelectIf( + TempStorage &temp_storage, ///< Reference to temp_storage + InputIteratorT d_in, ///< Input data + FlagsInputIteratorT d_flags_in, ///< Input selection flags (if applicable) + SelectedOutputIteratorT d_selected_out, ///< Output data + SelectOpT select_op, ///< Selection operator + EqualityOpT equality_op, ///< Equality operator + OffsetT num_items) ///< Total number of input items + : + temp_storage(temp_storage.Alias()), + d_in(d_in), + d_selected_out(d_selected_out), + d_flags_in(d_flags_in), + inequality_op(equality_op), + select_op(select_op), + num_items(num_items) + {} + + + //--------------------------------------------------------------------- + // Utility methods for initializing the selections + //--------------------------------------------------------------------- + + /** + * Initialize selections (specialized for selection operator) + */ + template + __device__ __forceinline__ void InitializeSelections( + OffsetT /*tile_offset*/, + OffsetT num_tile_items, + InputT (&items)[ITEMS_PER_THREAD], + OffsetT (&selection_flags)[ITEMS_PER_THREAD], + Int2Type /*select_method*/) + { + #pragma unroll + for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ++ITEM) + { + // Out-of-bounds items are selection_flags + selection_flags[ITEM] = 1; + + if (!IS_LAST_TILE || (OffsetT(threadIdx.x * ITEMS_PER_THREAD) + ITEM < num_tile_items)) + selection_flags[ITEM] = select_op(items[ITEM]); + } + } + + + /** + * Initialize selections (specialized for valid flags) + */ + template + __device__ __forceinline__ void InitializeSelections( + OffsetT tile_offset, + OffsetT num_tile_items, + InputT (&/*items*/)[ITEMS_PER_THREAD], + OffsetT (&selection_flags)[ITEMS_PER_THREAD], + Int2Type /*select_method*/) + { + CTA_SYNC(); + + FlagT flags[ITEMS_PER_THREAD]; + + if (IS_LAST_TILE) + { + // Out-of-bounds items are selection_flags + BlockLoadFlags(temp_storage.load_flags).Load(d_flags_in + tile_offset, flags, num_tile_items, 1); + } + else + { + BlockLoadFlags(temp_storage.load_flags).Load(d_flags_in + tile_offset, flags); + } + + // Convert flag type to selection_flags type + #pragma unroll + for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ++ITEM) + { + selection_flags[ITEM] = static_cast(flags[ITEM]); + } + } + + + /** + * Initialize selections (specialized for discontinuity detection) + */ + template + __device__ __forceinline__ void InitializeSelections( + OffsetT tile_offset, + OffsetT num_tile_items, + InputT (&items)[ITEMS_PER_THREAD], + OffsetT (&selection_flags)[ITEMS_PER_THREAD], + Int2Type /*select_method*/) + { + if (IS_FIRST_TILE) + { + CTA_SYNC(); + + // Set head selection_flags. First tile sets the first flag for the first item + BlockDiscontinuityT(temp_storage.scan_storage.discontinuity).FlagHeads(selection_flags, items, inequality_op); + } + else + { + InputT tile_predecessor; + if (threadIdx.x == 0) + tile_predecessor = d_in[tile_offset - 1]; + + CTA_SYNC(); + + BlockDiscontinuityT(temp_storage.scan_storage.discontinuity).FlagHeads(selection_flags, items, inequality_op, tile_predecessor); + } + + // Set selection flags for out-of-bounds items + #pragma unroll + for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ++ITEM) + { + // Set selection_flags for out-of-bounds items + if ((IS_LAST_TILE) && (OffsetT(threadIdx.x * ITEMS_PER_THREAD) + ITEM >= num_tile_items)) + selection_flags[ITEM] = 1; + } + } + + + //--------------------------------------------------------------------- + // Scatter utility methods + //--------------------------------------------------------------------- + + /** + * Scatter flagged items to output offsets (specialized for direct scattering) + */ + template + __device__ __forceinline__ void ScatterDirect( + InputT (&items)[ITEMS_PER_THREAD], + OffsetT (&selection_flags)[ITEMS_PER_THREAD], + OffsetT (&selection_indices)[ITEMS_PER_THREAD], + OffsetT num_selections) + { + // Scatter flagged items + #pragma unroll + for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ++ITEM) + { + if (selection_flags[ITEM]) + { + if ((!IS_LAST_TILE) || selection_indices[ITEM] < num_selections) + { + d_selected_out[selection_indices[ITEM]] = items[ITEM]; + } + } + } + } + + + /** + * Scatter flagged items to output offsets (specialized for two-phase scattering) + */ + template + __device__ __forceinline__ void ScatterTwoPhase( + InputT (&items)[ITEMS_PER_THREAD], + OffsetT (&selection_flags)[ITEMS_PER_THREAD], + OffsetT (&selection_indices)[ITEMS_PER_THREAD], + int /*num_tile_items*/, ///< Number of valid items in this tile + int num_tile_selections, ///< Number of selections in this tile + OffsetT num_selections_prefix, ///< Total number of selections prior to this tile + OffsetT /*num_rejected_prefix*/, ///< Total number of rejections prior to this tile + Int2Type /*is_keep_rejects*/) ///< Marker type indicating whether to keep rejected items in the second partition + { + CTA_SYNC(); + + // Compact and scatter items + #pragma unroll + for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ++ITEM) + { + int local_scatter_offset = selection_indices[ITEM] - num_selections_prefix; + if (selection_flags[ITEM]) + { + temp_storage.raw_exchange.Alias()[local_scatter_offset] = items[ITEM]; + } + } + + CTA_SYNC(); + + for (int item = threadIdx.x; item < num_tile_selections; item += BLOCK_THREADS) + { + d_selected_out[num_selections_prefix + item] = temp_storage.raw_exchange.Alias()[item]; + } + } + + + /** + * Scatter flagged items to output offsets (specialized for two-phase scattering) + */ + template + __device__ __forceinline__ void ScatterTwoPhase( + InputT (&items)[ITEMS_PER_THREAD], + OffsetT (&selection_flags)[ITEMS_PER_THREAD], + OffsetT (&selection_indices)[ITEMS_PER_THREAD], + int num_tile_items, ///< Number of valid items in this tile + int num_tile_selections, ///< Number of selections in this tile + OffsetT num_selections_prefix, ///< Total number of selections prior to this tile + OffsetT num_rejected_prefix, ///< Total number of rejections prior to this tile + Int2Type /*is_keep_rejects*/) ///< Marker type indicating whether to keep rejected items in the second partition + { + CTA_SYNC(); + + int tile_num_rejections = num_tile_items - num_tile_selections; + + // Scatter items to shared memory (rejections first) + #pragma unroll + for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ++ITEM) + { + int item_idx = (threadIdx.x * ITEMS_PER_THREAD) + ITEM; + int local_selection_idx = selection_indices[ITEM] - num_selections_prefix; + int local_rejection_idx = item_idx - local_selection_idx; + int local_scatter_offset = (selection_flags[ITEM]) ? + tile_num_rejections + local_selection_idx : + local_rejection_idx; + + temp_storage.raw_exchange.Alias()[local_scatter_offset] = items[ITEM]; + } + + CTA_SYNC(); + + // Gather items from shared memory and scatter to global + #pragma unroll + for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ++ITEM) + { + int item_idx = (ITEM * BLOCK_THREADS) + threadIdx.x; + int rejection_idx = item_idx; + int selection_idx = item_idx - tile_num_rejections; + OffsetT scatter_offset = (item_idx < tile_num_rejections) ? + num_items - num_rejected_prefix - rejection_idx - 1 : + num_selections_prefix + selection_idx; + + InputT item = temp_storage.raw_exchange.Alias()[item_idx]; + + if (!IS_LAST_TILE || (item_idx < num_tile_items)) + { + d_selected_out[scatter_offset] = item; + } + } + } + + + /** + * Scatter flagged items + */ + template + __device__ __forceinline__ void Scatter( + InputT (&items)[ITEMS_PER_THREAD], + OffsetT (&selection_flags)[ITEMS_PER_THREAD], + OffsetT (&selection_indices)[ITEMS_PER_THREAD], + int num_tile_items, ///< Number of valid items in this tile + int num_tile_selections, ///< Number of selections in this tile + OffsetT num_selections_prefix, ///< Total number of selections prior to this tile + OffsetT num_rejected_prefix, ///< Total number of rejections prior to this tile + OffsetT num_selections) ///< Total number of selections including this tile + { + // Do a two-phase scatter if (a) keeping both partitions or (b) two-phase is enabled and the average number of selection_flags items per thread is greater than one + if (KEEP_REJECTS || (TWO_PHASE_SCATTER && (num_tile_selections > BLOCK_THREADS))) + { + ScatterTwoPhase( + items, + selection_flags, + selection_indices, + num_tile_items, + num_tile_selections, + num_selections_prefix, + num_rejected_prefix, + Int2Type()); + } + else + { + ScatterDirect( + items, + selection_flags, + selection_indices, + num_selections); + } + } + + //--------------------------------------------------------------------- + // Cooperatively scan a device-wide sequence of tiles with other CTAs + //--------------------------------------------------------------------- + + + /** + * Process first tile of input (dynamic chained scan). Returns the running count of selections (including this tile) + */ + template + __device__ __forceinline__ OffsetT ConsumeFirstTile( + int num_tile_items, ///< Number of input items comprising this tile + OffsetT tile_offset, ///< Tile offset + ScanTileStateT& tile_state) ///< Global tile state descriptor + { + InputT items[ITEMS_PER_THREAD]; + OffsetT selection_flags[ITEMS_PER_THREAD]; + OffsetT selection_indices[ITEMS_PER_THREAD]; + + // Load items + if (IS_LAST_TILE) + BlockLoadT(temp_storage.load_items).Load(d_in + tile_offset, items, num_tile_items); + else + BlockLoadT(temp_storage.load_items).Load(d_in + tile_offset, items); + + // Initialize selection_flags + InitializeSelections( + tile_offset, + num_tile_items, + items, + selection_flags, + Int2Type()); + + CTA_SYNC(); + + // Exclusive scan of selection_flags + OffsetT num_tile_selections; + BlockScanT(temp_storage.scan_storage.scan).ExclusiveSum(selection_flags, selection_indices, num_tile_selections); + + if (threadIdx.x == 0) + { + // Update tile status if this is not the last tile + if (!IS_LAST_TILE) + tile_state.SetInclusive(0, num_tile_selections); + } + + // Discount any out-of-bounds selections + if (IS_LAST_TILE) + num_tile_selections -= (TILE_ITEMS - num_tile_items); + + // Scatter flagged items + Scatter( + items, + selection_flags, + selection_indices, + num_tile_items, + num_tile_selections, + 0, + 0, + num_tile_selections); + + return num_tile_selections; + } + + + /** + * Process subsequent tile of input (dynamic chained scan). Returns the running count of selections (including this tile) + */ + template + __device__ __forceinline__ OffsetT ConsumeSubsequentTile( + int num_tile_items, ///< Number of input items comprising this tile + int tile_idx, ///< Tile index + OffsetT tile_offset, ///< Tile offset + ScanTileStateT& tile_state) ///< Global tile state descriptor + { + InputT items[ITEMS_PER_THREAD]; + OffsetT selection_flags[ITEMS_PER_THREAD]; + OffsetT selection_indices[ITEMS_PER_THREAD]; + + // Load items + if (IS_LAST_TILE) + BlockLoadT(temp_storage.load_items).Load(d_in + tile_offset, items, num_tile_items); + else + BlockLoadT(temp_storage.load_items).Load(d_in + tile_offset, items); + + // Initialize selection_flags + InitializeSelections( + tile_offset, + num_tile_items, + items, + selection_flags, + Int2Type()); + + CTA_SYNC(); + + // Exclusive scan of values and selection_flags + TilePrefixCallbackOpT prefix_op(tile_state, temp_storage.scan_storage.prefix, cub::Sum(), tile_idx); + BlockScanT(temp_storage.scan_storage.scan).ExclusiveSum(selection_flags, selection_indices, prefix_op); + + OffsetT num_tile_selections = prefix_op.GetBlockAggregate(); + OffsetT num_selections = prefix_op.GetInclusivePrefix(); + OffsetT num_selections_prefix = prefix_op.GetExclusivePrefix(); + OffsetT num_rejected_prefix = (tile_idx * TILE_ITEMS) - num_selections_prefix; + + // Discount any out-of-bounds selections + if (IS_LAST_TILE) + { + int num_discount = TILE_ITEMS - num_tile_items; + num_selections -= num_discount; + num_tile_selections -= num_discount; + } + + // Scatter flagged items + Scatter( + items, + selection_flags, + selection_indices, + num_tile_items, + num_tile_selections, + num_selections_prefix, + num_rejected_prefix, + num_selections); + + return num_selections; + } + + + /** + * Process a tile of input + */ + template + __device__ __forceinline__ OffsetT ConsumeTile( + int num_tile_items, ///< Number of input items comprising this tile + int tile_idx, ///< Tile index + OffsetT tile_offset, ///< Tile offset + ScanTileStateT& tile_state) ///< Global tile state descriptor + { + OffsetT num_selections; + if (tile_idx == 0) + { + num_selections = ConsumeFirstTile(num_tile_items, tile_offset, tile_state); + } + else + { + num_selections = ConsumeSubsequentTile(num_tile_items, tile_idx, tile_offset, tile_state); + } + + return num_selections; + } + + + /** + * Scan tiles of items as part of a dynamic chained scan + */ + template ///< Output iterator type for recording number of items selection_flags + __device__ __forceinline__ void ConsumeRange( + int num_tiles, ///< Total number of input tiles + ScanTileStateT& tile_state, ///< Global tile state descriptor + NumSelectedIteratorT d_num_selected_out) ///< Output total number selection_flags + { + // Blocks are launched in increasing order, so just assign one tile per block + int tile_idx = (blockIdx.x * gridDim.y) + blockIdx.y; // Current tile index + OffsetT tile_offset = tile_idx * TILE_ITEMS; // Global offset for the current tile + + if (tile_idx < num_tiles - 1) + { + // Not the last tile (full) + ConsumeTile(TILE_ITEMS, tile_idx, tile_offset, tile_state); + } + else + { + // The last tile (possibly partially-full) + OffsetT num_remaining = num_items - tile_offset; + OffsetT num_selections = ConsumeTile(num_remaining, tile_idx, tile_offset, tile_state); + + if (threadIdx.x == 0) + { + // Output the total number of items selection_flags + *d_num_selected_out = num_selections; + } + } + } + +}; + + + +CUB_NAMESPACE_END diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/agent/agent_spmv_orig.cuh b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/agent/agent_spmv_orig.cuh new file mode 100644 index 0000000000000000000000000000000000000000..c89bc4a3cd1518e0f5bd0e54a899d847a3523149 --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/agent/agent_spmv_orig.cuh @@ -0,0 +1,680 @@ +/****************************************************************************** + * Copyright (c) 2011, Duane Merrill. All rights reserved. + * Copyright (c) 2011-2018, NVIDIA CORPORATION. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the NVIDIA CORPORATION nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ******************************************************************************/ + +/** + * \file + * cub::AgentSpmv implements a stateful abstraction of CUDA thread blocks for participating in device-wide SpMV. + */ + +#pragma once + +#include + +#include "../util_type.cuh" +#include "../block/block_reduce.cuh" +#include "../block/block_scan.cuh" +#include "../block/block_exchange.cuh" +#include "../config.cuh" +#include "../thread/thread_search.cuh" +#include "../thread/thread_operators.cuh" +#include "../iterator/cache_modified_input_iterator.cuh" +#include "../iterator/counting_input_iterator.cuh" + +CUB_NAMESPACE_BEGIN + + +/****************************************************************************** + * Tuning policy + ******************************************************************************/ + +/** + * Parameterizable tuning policy type for AgentSpmv + */ +template < + int _BLOCK_THREADS, ///< Threads per thread block + int _ITEMS_PER_THREAD, ///< Items per thread (per tile of input) + CacheLoadModifier _ROW_OFFSETS_SEARCH_LOAD_MODIFIER, ///< Cache load modifier for reading CSR row-offsets during search + CacheLoadModifier _ROW_OFFSETS_LOAD_MODIFIER, ///< Cache load modifier for reading CSR row-offsets + CacheLoadModifier _COLUMN_INDICES_LOAD_MODIFIER, ///< Cache load modifier for reading CSR column-indices + CacheLoadModifier _VALUES_LOAD_MODIFIER, ///< Cache load modifier for reading CSR values + CacheLoadModifier _VECTOR_VALUES_LOAD_MODIFIER, ///< Cache load modifier for reading vector values + bool _DIRECT_LOAD_NONZEROS, ///< Whether to load nonzeros directly from global during sequential merging (vs. pre-staged through shared memory) + BlockScanAlgorithm _SCAN_ALGORITHM> ///< The BlockScan algorithm to use +struct AgentSpmvPolicy +{ + enum + { + BLOCK_THREADS = _BLOCK_THREADS, ///< Threads per thread block + ITEMS_PER_THREAD = _ITEMS_PER_THREAD, ///< Items per thread (per tile of input) + DIRECT_LOAD_NONZEROS = _DIRECT_LOAD_NONZEROS, ///< Whether to load nonzeros directly from global during sequential merging (pre-staged through shared memory) + }; + + static const CacheLoadModifier ROW_OFFSETS_SEARCH_LOAD_MODIFIER = _ROW_OFFSETS_SEARCH_LOAD_MODIFIER; ///< Cache load modifier for reading CSR row-offsets + static const CacheLoadModifier ROW_OFFSETS_LOAD_MODIFIER = _ROW_OFFSETS_LOAD_MODIFIER; ///< Cache load modifier for reading CSR row-offsets + static const CacheLoadModifier COLUMN_INDICES_LOAD_MODIFIER = _COLUMN_INDICES_LOAD_MODIFIER; ///< Cache load modifier for reading CSR column-indices + static const CacheLoadModifier VALUES_LOAD_MODIFIER = _VALUES_LOAD_MODIFIER; ///< Cache load modifier for reading CSR values + static const CacheLoadModifier VECTOR_VALUES_LOAD_MODIFIER = _VECTOR_VALUES_LOAD_MODIFIER; ///< Cache load modifier for reading vector values + static const BlockScanAlgorithm SCAN_ALGORITHM = _SCAN_ALGORITHM; ///< The BlockScan algorithm to use + +}; + + +/****************************************************************************** + * Thread block abstractions + ******************************************************************************/ + +template < + typename ValueT, ///< Matrix and vector value type + typename OffsetT> ///< Signed integer type for sequence offsets +struct SpmvParams +{ + const ValueT* d_values; ///< Pointer to the array of \p num_nonzeros values of the corresponding nonzero elements of matrix A. + const OffsetT* d_row_end_offsets; ///< Pointer to the array of \p m offsets demarcating the end of every row in \p d_column_indices and \p d_values + const OffsetT* d_column_indices; ///< Pointer to the array of \p num_nonzeros column-indices of the corresponding nonzero elements of matrix A. (Indices are zero-valued.) + const ValueT* d_vector_x; ///< Pointer to the array of \p num_cols values corresponding to the dense input vector x + ValueT* d_vector_y; ///< Pointer to the array of \p num_rows values corresponding to the dense output vector y + int num_rows; ///< Number of rows of matrix A. + int num_cols; ///< Number of columns of matrix A. + int num_nonzeros; ///< Number of nonzero elements of matrix A. + ValueT alpha; ///< Alpha multiplicand + ValueT beta; ///< Beta addend-multiplicand +}; + + +/** + * \brief AgentSpmv implements a stateful abstraction of CUDA thread blocks for participating in device-wide SpMV. + */ +template < + typename AgentSpmvPolicyT, ///< Parameterized AgentSpmvPolicy tuning policy type + typename ValueT, ///< Matrix and vector value type + typename OffsetT, ///< Signed integer type for sequence offsets + bool HAS_ALPHA, ///< Whether the input parameter \p alpha is 1 + bool HAS_BETA, ///< Whether the input parameter \p beta is 0 + int LEGACY_PTX_ARCH = 0> ///< PTX compute capability (unused) +struct AgentSpmv +{ + //--------------------------------------------------------------------- + // Types and constants + //--------------------------------------------------------------------- + + /// Constants + enum + { + BLOCK_THREADS = AgentSpmvPolicyT::BLOCK_THREADS, + ITEMS_PER_THREAD = AgentSpmvPolicyT::ITEMS_PER_THREAD, + TILE_ITEMS = BLOCK_THREADS * ITEMS_PER_THREAD, + }; + + /// 2D merge path coordinate type + typedef typename CubVector::Type CoordinateT; + + /// Input iterator wrapper types (for applying cache modifiers) + + typedef CacheModifiedInputIterator< + AgentSpmvPolicyT::ROW_OFFSETS_SEARCH_LOAD_MODIFIER, + OffsetT, + OffsetT> + RowOffsetsSearchIteratorT; + + typedef CacheModifiedInputIterator< + AgentSpmvPolicyT::ROW_OFFSETS_LOAD_MODIFIER, + OffsetT, + OffsetT> + RowOffsetsIteratorT; + + typedef CacheModifiedInputIterator< + AgentSpmvPolicyT::COLUMN_INDICES_LOAD_MODIFIER, + OffsetT, + OffsetT> + ColumnIndicesIteratorT; + + typedef CacheModifiedInputIterator< + AgentSpmvPolicyT::VALUES_LOAD_MODIFIER, + ValueT, + OffsetT> + ValueIteratorT; + + typedef CacheModifiedInputIterator< + AgentSpmvPolicyT::VECTOR_VALUES_LOAD_MODIFIER, + ValueT, + OffsetT> + VectorValueIteratorT; + + // Tuple type for scanning (pairs accumulated segment-value with segment-index) + typedef KeyValuePair KeyValuePairT; + + // Reduce-value-by-segment scan operator + typedef ReduceByKeyOp ReduceBySegmentOpT; + + // BlockReduce specialization + typedef BlockReduce< + ValueT, + BLOCK_THREADS, + BLOCK_REDUCE_WARP_REDUCTIONS> + BlockReduceT; + + // BlockScan specialization + typedef BlockScan< + KeyValuePairT, + BLOCK_THREADS, + AgentSpmvPolicyT::SCAN_ALGORITHM> + BlockScanT; + + // BlockScan specialization + typedef BlockScan< + ValueT, + BLOCK_THREADS, + AgentSpmvPolicyT::SCAN_ALGORITHM> + BlockPrefixSumT; + + // BlockExchange specialization + typedef BlockExchange< + ValueT, + BLOCK_THREADS, + ITEMS_PER_THREAD> + BlockExchangeT; + + /// Merge item type (either a non-zero value or a row-end offset) + union MergeItem + { + // Value type to pair with index type OffsetT + // (NullType if loading values directly during merge) + using MergeValueT = + cub::detail::conditional_t< + AgentSpmvPolicyT::DIRECT_LOAD_NONZEROS, NullType, ValueT>; + + OffsetT row_end_offset; + MergeValueT nonzero; + }; + + /// Shared memory type required by this thread block + struct _TempStorage + { + CoordinateT tile_coords[2]; + + union Aliasable + { + // Smem needed for tile of merge items + MergeItem merge_items[ITEMS_PER_THREAD + TILE_ITEMS + 1]; + + // Smem needed for block exchange + typename BlockExchangeT::TempStorage exchange; + + // Smem needed for block-wide reduction + typename BlockReduceT::TempStorage reduce; + + // Smem needed for tile scanning + typename BlockScanT::TempStorage scan; + + // Smem needed for tile prefix sum + typename BlockPrefixSumT::TempStorage prefix_sum; + + } aliasable; + }; + + /// Temporary storage type (unionable) + struct TempStorage : Uninitialized<_TempStorage> {}; + + + //--------------------------------------------------------------------- + // Per-thread fields + //--------------------------------------------------------------------- + + + _TempStorage& temp_storage; /// Reference to temp_storage + + SpmvParams& spmv_params; + + ValueIteratorT wd_values; ///< Wrapped pointer to the array of \p num_nonzeros values of the corresponding nonzero elements of matrix A. + RowOffsetsIteratorT wd_row_end_offsets; ///< Wrapped Pointer to the array of \p m offsets demarcating the end of every row in \p d_column_indices and \p d_values + ColumnIndicesIteratorT wd_column_indices; ///< Wrapped Pointer to the array of \p num_nonzeros column-indices of the corresponding nonzero elements of matrix A. (Indices are zero-valued.) + VectorValueIteratorT wd_vector_x; ///< Wrapped Pointer to the array of \p num_cols values corresponding to the dense input vector x + VectorValueIteratorT wd_vector_y; ///< Wrapped Pointer to the array of \p num_cols values corresponding to the dense input vector x + + + //--------------------------------------------------------------------- + // Interface + //--------------------------------------------------------------------- + + /** + * Constructor + */ + __device__ __forceinline__ AgentSpmv( + TempStorage& temp_storage, ///< Reference to temp_storage + SpmvParams& spmv_params) ///< SpMV input parameter bundle + : + temp_storage(temp_storage.Alias()), + spmv_params(spmv_params), + wd_values(spmv_params.d_values), + wd_row_end_offsets(spmv_params.d_row_end_offsets), + wd_column_indices(spmv_params.d_column_indices), + wd_vector_x(spmv_params.d_vector_x), + wd_vector_y(spmv_params.d_vector_y) + {} + + + + + /** + * Consume a merge tile, specialized for direct-load of nonzeros + */ + __device__ __forceinline__ KeyValuePairT ConsumeTile( + int tile_idx, + CoordinateT tile_start_coord, + CoordinateT tile_end_coord, + Int2Type is_direct_load) ///< Marker type indicating whether to load nonzeros directly during path-discovery or beforehand in batch + { + int tile_num_rows = tile_end_coord.x - tile_start_coord.x; + int tile_num_nonzeros = tile_end_coord.y - tile_start_coord.y; + OffsetT* s_tile_row_end_offsets = &temp_storage.aliasable.merge_items[0].row_end_offset; + + // Gather the row end-offsets for the merge tile into shared memory + for (int item = threadIdx.x; item < tile_num_rows + ITEMS_PER_THREAD; item += BLOCK_THREADS) + { + const OffsetT offset = + (cub::min)(static_cast(tile_start_coord.x + item), + static_cast(spmv_params.num_rows - 1)); + s_tile_row_end_offsets[item] = wd_row_end_offsets[offset]; + } + + CTA_SYNC(); + + // Search for the thread's starting coordinate within the merge tile + CountingInputIterator tile_nonzero_indices(tile_start_coord.y); + CoordinateT thread_start_coord; + + MergePathSearch( + OffsetT(threadIdx.x * ITEMS_PER_THREAD), // Diagonal + s_tile_row_end_offsets, // List A + tile_nonzero_indices, // List B + tile_num_rows, + tile_num_nonzeros, + thread_start_coord); + + CTA_SYNC(); // Perf-sync + + // Compute the thread's merge path segment + CoordinateT thread_current_coord = thread_start_coord; + KeyValuePairT scan_segment[ITEMS_PER_THREAD]; + + ValueT running_total = 0.0; + + #pragma unroll + for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ++ITEM) + { + OffsetT nonzero_idx = CUB_MIN(tile_nonzero_indices[thread_current_coord.y], spmv_params.num_nonzeros - 1); + OffsetT column_idx = wd_column_indices[nonzero_idx]; + ValueT value = wd_values[nonzero_idx]; + + ValueT vector_value = wd_vector_x[column_idx]; + + ValueT nonzero = value * vector_value; + + OffsetT row_end_offset = s_tile_row_end_offsets[thread_current_coord.x]; + + if (tile_nonzero_indices[thread_current_coord.y] < row_end_offset) + { + // Move down (accumulate) + running_total += nonzero; + scan_segment[ITEM].value = running_total; + scan_segment[ITEM].key = tile_num_rows; + ++thread_current_coord.y; + } + else + { + // Move right (reset) + scan_segment[ITEM].value = running_total; + scan_segment[ITEM].key = thread_current_coord.x; + running_total = 0.0; + ++thread_current_coord.x; + } + } + + CTA_SYNC(); + + // Block-wide reduce-value-by-segment + KeyValuePairT tile_carry; + ReduceBySegmentOpT scan_op; + KeyValuePairT scan_item; + + scan_item.value = running_total; + scan_item.key = thread_current_coord.x; + + BlockScanT(temp_storage.aliasable.scan).ExclusiveScan(scan_item, scan_item, scan_op, tile_carry); + + if (tile_num_rows > 0) + { + if (threadIdx.x == 0) + scan_item.key = -1; + + // Direct scatter + #pragma unroll + for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ++ITEM) + { + if (scan_segment[ITEM].key < tile_num_rows) + { + if (scan_item.key == scan_segment[ITEM].key) + scan_segment[ITEM].value = scan_item.value + scan_segment[ITEM].value; + + if (HAS_ALPHA) + { + scan_segment[ITEM].value *= spmv_params.alpha; + } + + if (HAS_BETA) + { + // Update the output vector element + ValueT addend = spmv_params.beta * wd_vector_y[tile_start_coord.x + scan_segment[ITEM].key]; + scan_segment[ITEM].value += addend; + } + + // Set the output vector element + spmv_params.d_vector_y[tile_start_coord.x + scan_segment[ITEM].key] = scan_segment[ITEM].value; + } + } + } + + // Return the tile's running carry-out + return tile_carry; + } + + + + /** + * Consume a merge tile, specialized for indirect load of nonzeros + */ + __device__ __forceinline__ KeyValuePairT ConsumeTile( + int tile_idx, + CoordinateT tile_start_coord, + CoordinateT tile_end_coord, + Int2Type is_direct_load) ///< Marker type indicating whether to load nonzeros directly during path-discovery or beforehand in batch + { + int tile_num_rows = tile_end_coord.x - tile_start_coord.x; + int tile_num_nonzeros = tile_end_coord.y - tile_start_coord.y; + +#if (CUB_PTX_ARCH >= 520) + + OffsetT* s_tile_row_end_offsets = &temp_storage.aliasable.merge_items[0].row_end_offset; + ValueT* s_tile_nonzeros = &temp_storage.aliasable.merge_items[tile_num_rows + ITEMS_PER_THREAD].nonzero; + + // Gather the nonzeros for the merge tile into shared memory + #pragma unroll + for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ++ITEM) + { + int nonzero_idx = threadIdx.x + (ITEM * BLOCK_THREADS); + + ValueIteratorT a = wd_values + tile_start_coord.y + nonzero_idx; + ColumnIndicesIteratorT ci = wd_column_indices + tile_start_coord.y + nonzero_idx; + ValueT* s = s_tile_nonzeros + nonzero_idx; + + if (nonzero_idx < tile_num_nonzeros) + { + + OffsetT column_idx = *ci; + ValueT value = *a; + + ValueT vector_value = wd_vector_x[column_idx]; + + ValueT nonzero = value * vector_value; + + *s = nonzero; + } + } + + +#else + + OffsetT* s_tile_row_end_offsets = &temp_storage.aliasable.merge_items[0].row_end_offset; + ValueT* s_tile_nonzeros = &temp_storage.aliasable.merge_items[tile_num_rows + ITEMS_PER_THREAD].nonzero; + + // Gather the nonzeros for the merge tile into shared memory + if (tile_num_nonzeros > 0) + { + #pragma unroll + for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ++ITEM) + { + int nonzero_idx = threadIdx.x + (ITEM * BLOCK_THREADS); + nonzero_idx = CUB_MIN(nonzero_idx, tile_num_nonzeros - 1); + + OffsetT column_idx = wd_column_indices[tile_start_coord.y + nonzero_idx]; + ValueT value = wd_values[tile_start_coord.y + nonzero_idx]; + + ValueT vector_value = wd_vector_x[column_idx]; + + ValueT nonzero = value * vector_value; + + s_tile_nonzeros[nonzero_idx] = nonzero; + } + } + +#endif + + // Gather the row end-offsets for the merge tile into shared memory + #pragma unroll 1 + for (int item = threadIdx.x; item < tile_num_rows + ITEMS_PER_THREAD; item += BLOCK_THREADS) + { + const OffsetT offset = + (cub::min)(static_cast(tile_start_coord.x + item), + static_cast(spmv_params.num_rows - 1)); + s_tile_row_end_offsets[item] = wd_row_end_offsets[offset]; + } + + CTA_SYNC(); + + // Search for the thread's starting coordinate within the merge tile + CountingInputIterator tile_nonzero_indices(tile_start_coord.y); + CoordinateT thread_start_coord; + + MergePathSearch( + OffsetT(threadIdx.x * ITEMS_PER_THREAD), // Diagonal + s_tile_row_end_offsets, // List A + tile_nonzero_indices, // List B + tile_num_rows, + tile_num_nonzeros, + thread_start_coord); + + CTA_SYNC(); // Perf-sync + + // Compute the thread's merge path segment + CoordinateT thread_current_coord = thread_start_coord; + KeyValuePairT scan_segment[ITEMS_PER_THREAD]; + ValueT running_total = 0.0; + + OffsetT row_end_offset = s_tile_row_end_offsets[thread_current_coord.x]; + ValueT nonzero = s_tile_nonzeros[thread_current_coord.y]; + + #pragma unroll + for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ++ITEM) + { + if (tile_nonzero_indices[thread_current_coord.y] < row_end_offset) + { + // Move down (accumulate) + scan_segment[ITEM].value = nonzero; + running_total += nonzero; + ++thread_current_coord.y; + nonzero = s_tile_nonzeros[thread_current_coord.y]; + } + else + { + // Move right (reset) + scan_segment[ITEM].value = 0.0; + running_total = 0.0; + ++thread_current_coord.x; + row_end_offset = s_tile_row_end_offsets[thread_current_coord.x]; + } + + scan_segment[ITEM].key = thread_current_coord.x; + } + + CTA_SYNC(); + + // Block-wide reduce-value-by-segment + KeyValuePairT tile_carry; + ReduceBySegmentOpT scan_op; + KeyValuePairT scan_item; + + scan_item.value = running_total; + scan_item.key = thread_current_coord.x; + + BlockScanT(temp_storage.aliasable.scan).ExclusiveScan(scan_item, scan_item, scan_op, tile_carry); + + if (threadIdx.x == 0) + { + scan_item.key = thread_start_coord.x; + scan_item.value = 0.0; + } + + if (tile_num_rows > 0) + { + + CTA_SYNC(); + + // Scan downsweep and scatter + ValueT* s_partials = &temp_storage.aliasable.merge_items[0].nonzero; + + if (scan_item.key != scan_segment[0].key) + { + s_partials[scan_item.key] = scan_item.value; + } + else + { + scan_segment[0].value += scan_item.value; + } + + #pragma unroll + for (int ITEM = 1; ITEM < ITEMS_PER_THREAD; ++ITEM) + { + if (scan_segment[ITEM - 1].key != scan_segment[ITEM].key) + { + s_partials[scan_segment[ITEM - 1].key] = scan_segment[ITEM - 1].value; + } + else + { + scan_segment[ITEM].value += scan_segment[ITEM - 1].value; + } + } + + CTA_SYNC(); + + #pragma unroll 1 + for (int item = threadIdx.x; item < tile_num_rows; item += BLOCK_THREADS) + { + spmv_params.d_vector_y[tile_start_coord.x + item] = s_partials[item]; + } + } + + // Return the tile's running carry-out + return tile_carry; + } + + + /** + * Consume input tile + */ + __device__ __forceinline__ void ConsumeTile( + CoordinateT* d_tile_coordinates, ///< [in] Pointer to the temporary array of tile starting coordinates + KeyValuePairT* d_tile_carry_pairs, ///< [out] Pointer to the temporary array carry-out dot product row-ids, one per block + int num_merge_tiles) ///< [in] Number of merge tiles + { + int tile_idx = (blockIdx.x * gridDim.y) + blockIdx.y; // Current tile index + + if (tile_idx >= num_merge_tiles) + return; + + // Read our starting coordinates + if (threadIdx.x < 2) + { + if (d_tile_coordinates == NULL) + { + // Search our starting coordinates + OffsetT diagonal = (tile_idx + threadIdx.x) * TILE_ITEMS; + CoordinateT tile_coord; + CountingInputIterator nonzero_indices(0); + + // Search the merge path + MergePathSearch( + diagonal, + RowOffsetsSearchIteratorT(spmv_params.d_row_end_offsets), + nonzero_indices, + spmv_params.num_rows, + spmv_params.num_nonzeros, + tile_coord); + + temp_storage.tile_coords[threadIdx.x] = tile_coord; + } + else + { + temp_storage.tile_coords[threadIdx.x] = d_tile_coordinates[tile_idx + threadIdx.x]; + } + } + + CTA_SYNC(); + + CoordinateT tile_start_coord = temp_storage.tile_coords[0]; + CoordinateT tile_end_coord = temp_storage.tile_coords[1]; + + // Consume multi-segment tile + KeyValuePairT tile_carry = ConsumeTile( + tile_idx, + tile_start_coord, + tile_end_coord, + Int2Type()); + + // Output the tile's carry-out + if (threadIdx.x == 0) + { + if (HAS_ALPHA) + { + tile_carry.value *= spmv_params.alpha; + } + + tile_carry.key += tile_start_coord.x; + if (tile_carry.key >= spmv_params.num_rows) + { + // FIXME: This works around an invalid memory access in the + // fixup kernel. The underlying issue needs to be debugged and + // properly fixed, but this hack prevents writes to + // out-of-bounds addresses. It doesn't appear to have an effect + // on the validity of the results, since this only affects the + // carry-over from last tile in the input. + tile_carry.key = spmv_params.num_rows - 1; + tile_carry.value = ValueT{}; + }; + + d_tile_carry_pairs[tile_idx] = tile_carry; + } + } + + +}; + + + + +CUB_NAMESPACE_END + diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/agent/agent_unique_by_key.cuh b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/agent/agent_unique_by_key.cuh new file mode 100644 index 0000000000000000000000000000000000000000..54c87cd4125a4fe6bb2a6465ddac63637fe09e6f --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/agent/agent_unique_by_key.cuh @@ -0,0 +1,583 @@ +/****************************************************************************** + * Copyright (c) NVIDIA CORPORATION. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the NVIDIA CORPORATION nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ******************************************************************************/ + +/** + * \file + * cub::AgentUniqueByKey implements a stateful abstraction of CUDA thread blocks for participating in device-wide unique-by-key. + */ + +#pragma once + +#include +#include + +#include "../thread/thread_operators.cuh" +#include "../block/block_load.cuh" +#include "../block/block_scan.cuh" +#include "../agent/single_pass_scan_operators.cuh" +#include "../block/block_discontinuity.cuh" + +CUB_NAMESPACE_BEGIN + + +/****************************************************************************** + * Tuning policy types + ******************************************************************************/ + +/** + * Parameterizable tuning policy type for AgentUniqueByKey + * + * @tparam DelayConstructorT + * Implementation detail, do not specify directly, requirements on the + * content of this type are subject to breaking change. + */ +template > +struct AgentUniqueByKeyPolicy +{ + enum + { + BLOCK_THREADS = _BLOCK_THREADS, + ITEMS_PER_THREAD = _ITEMS_PER_THREAD, + }; + static const cub::BlockLoadAlgorithm LOAD_ALGORITHM = _LOAD_ALGORITHM; + static const cub::CacheLoadModifier LOAD_MODIFIER = _LOAD_MODIFIER; + static const cub::BlockScanAlgorithm SCAN_ALGORITHM = _SCAN_ALGORITHM; + + struct detail + { + using delay_constructor_t = DelayConstructorT; + }; +}; + + + + +/****************************************************************************** + * Thread block abstractions + ******************************************************************************/ + + +/** + * \brief AgentUniqueByKey implements a stateful abstraction of CUDA thread blocks for participating in device-wide unique-by-key + */ +template < + typename AgentUniqueByKeyPolicyT, ///< Parameterized AgentUniqueByKeyPolicy tuning policy type + typename KeyInputIteratorT, ///< Random-access input iterator type for keys + typename ValueInputIteratorT, ///< Random-access input iterator type for values + typename KeyOutputIteratorT, ///< Random-access output iterator type for keys + typename ValueOutputIteratorT, ///< Random-access output iterator type for values + typename EqualityOpT, ///< Equality operator type + typename OffsetT> ///< Signed integer type for global offsets +struct AgentUniqueByKey +{ + //--------------------------------------------------------------------- + // Types and constants + //--------------------------------------------------------------------- + + // The input key and value type + using KeyT = typename std::iterator_traits::value_type; + using ValueT = typename std::iterator_traits::value_type; + + // Tile status descriptor interface type + using ScanTileStateT = ScanTileState; + + // Constants + enum + { + BLOCK_THREADS = AgentUniqueByKeyPolicyT::BLOCK_THREADS, + ITEMS_PER_THREAD = AgentUniqueByKeyPolicyT::ITEMS_PER_THREAD, + ITEMS_PER_TILE = BLOCK_THREADS * ITEMS_PER_THREAD, + }; + + // Cache-modified Input iterator wrapper type (for applying cache modifier) for keys + using WrappedKeyInputIteratorT = typename std::conditional::value, + CacheModifiedInputIterator, // Wrap the native input pointer with CacheModifiedValuesInputIterator + KeyInputIteratorT>::type; // Directly use the supplied input iterator type + + // Cache-modified Input iterator wrapper type (for applying cache modifier) for values + using WrappedValueInputIteratorT = typename std::conditional::value, + CacheModifiedInputIterator, // Wrap the native input pointer with CacheModifiedValuesInputIterator + ValueInputIteratorT>::type; // Directly use the supplied input iterator type + + // Parameterized BlockLoad type for input data + using BlockLoadKeys = BlockLoad< + KeyT, + BLOCK_THREADS, + ITEMS_PER_THREAD, + AgentUniqueByKeyPolicyT::LOAD_ALGORITHM>; + + // Parameterized BlockLoad type for flags + using BlockLoadValues = BlockLoad< + ValueT, + BLOCK_THREADS, + ITEMS_PER_THREAD, + AgentUniqueByKeyPolicyT::LOAD_ALGORITHM>; + + // Parameterized BlockDiscontinuity type for items + using BlockDiscontinuityKeys = cub::BlockDiscontinuity; + + // Parameterized BlockScan type + using BlockScanT = cub::BlockScan; + + // Parameterized BlockDiscontinuity type for items + using DelayConstructorT = typename AgentUniqueByKeyPolicyT::detail::delay_constructor_t; + using TilePrefixCallback = + cub::TilePrefixCallbackOp; + + // Key exchange type + using KeyExchangeT = KeyT[ITEMS_PER_TILE]; + + // Value exchange type + using ValueExchangeT = ValueT[ITEMS_PER_TILE]; + + // Shared memory type for this thread block + union _TempStorage + { + struct ScanStorage + { + typename BlockScanT::TempStorage scan; + typename TilePrefixCallback::TempStorage prefix; + typename BlockDiscontinuityKeys::TempStorage discontinuity; + } scan_storage; + + // Smem needed for loading keys + typename BlockLoadKeys::TempStorage load_keys; + + // Smem needed for loading values + typename BlockLoadValues::TempStorage load_values; + + // Smem needed for compacting items (allows non POD items in this union) + Uninitialized shared_keys; + Uninitialized shared_values; + }; + + // Alias wrapper allowing storage to be unioned + struct TempStorage : Uninitialized<_TempStorage> {}; + + + //--------------------------------------------------------------------- + // Per-thread fields + //--------------------------------------------------------------------- + + _TempStorage& temp_storage; + WrappedKeyInputIteratorT d_keys_in; + WrappedValueInputIteratorT d_values_in; + KeyOutputIteratorT d_keys_out; + ValueOutputIteratorT d_values_out; + cub::InequalityWrapper inequality_op; + OffsetT num_items; + + + //--------------------------------------------------------------------- + // Constructor + //--------------------------------------------------------------------- + + // Constructor + __device__ __forceinline__ + AgentUniqueByKey( + TempStorage &temp_storage_, + WrappedKeyInputIteratorT d_keys_in_, + WrappedValueInputIteratorT d_values_in_, + KeyOutputIteratorT d_keys_out_, + ValueOutputIteratorT d_values_out_, + EqualityOpT equality_op_, + OffsetT num_items_) + : + temp_storage(temp_storage_.Alias()), + d_keys_in(d_keys_in_), + d_values_in(d_values_in_), + d_keys_out(d_keys_out_), + d_values_out(d_values_out_), + inequality_op(equality_op_), + num_items(num_items_) + {} + + + + //--------------------------------------------------------------------- + // Utility functions + //--------------------------------------------------------------------- + + struct KeyTagT {}; + struct ValueTagT {}; + + __device__ __forceinline__ + KeyExchangeT &GetShared(KeyTagT) + { + return temp_storage.shared_keys.Alias(); + } + __device__ __forceinline__ + ValueExchangeT &GetShared(ValueTagT) + { + return temp_storage.shared_values.Alias(); + } + + + //--------------------------------------------------------------------- + // Scatter utility methods + //--------------------------------------------------------------------- + template + __device__ __forceinline__ void Scatter( + Tag tag, + OutputIt items_out, + T (&items)[ITEMS_PER_THREAD], + OffsetT (&selection_flags)[ITEMS_PER_THREAD], + OffsetT (&selection_indices)[ITEMS_PER_THREAD], + int /*num_tile_items*/, + int num_tile_selections, + OffsetT num_selections_prefix, + OffsetT /*num_selections*/) + { + #pragma unroll + for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ++ITEM) + { + int local_scatter_offset = selection_indices[ITEM] - + num_selections_prefix; + if (selection_flags[ITEM]) + { + GetShared(tag)[local_scatter_offset] = items[ITEM]; + } + } + + CTA_SYNC(); + + for (int item = threadIdx.x; + item < num_tile_selections; + item += BLOCK_THREADS) + { + items_out[num_selections_prefix + item] = GetShared(tag)[item]; + } + + CTA_SYNC(); + } + + + //--------------------------------------------------------------------- + // Cooperatively scan a device-wide sequence of tiles with other CTAs + //--------------------------------------------------------------------- + + + /** + * Process first tile of input (dynamic chained scan). Returns the running count of selections (including this tile) + */ + template + __device__ __forceinline__ OffsetT ConsumeFirstTile( + int num_tile_items, ///< Number of input items comprising this tile + OffsetT tile_offset, ///< Tile offset + ScanTileStateT& tile_state) ///< Global tile state descriptor + { + KeyT keys[ITEMS_PER_THREAD]; + OffsetT selection_flags[ITEMS_PER_THREAD]; + OffsetT selection_idx[ITEMS_PER_THREAD]; + + if (IS_LAST_TILE) + { + // Fill last elements with the first element + // because collectives are not suffix guarded + BlockLoadKeys(temp_storage.load_keys) + .Load(d_keys_in + tile_offset, + keys, + num_tile_items, + *(d_keys_in + tile_offset)); + } + else + { + BlockLoadKeys(temp_storage.load_keys).Load(d_keys_in + tile_offset, keys); + } + + + CTA_SYNC(); + + ValueT values[ITEMS_PER_THREAD]; + if (IS_LAST_TILE) + { + // Fill last elements with the first element + // because collectives are not suffix guarded + BlockLoadValues(temp_storage.load_values) + .Load(d_values_in + tile_offset, + values, + num_tile_items, + *(d_values_in + tile_offset)); + } + else + { + BlockLoadValues(temp_storage.load_values) + .Load(d_values_in + tile_offset, values); + } + + CTA_SYNC(); + + BlockDiscontinuityKeys(temp_storage.scan_storage.discontinuity) + .FlagHeads(selection_flags, keys, inequality_op); + #pragma unroll + for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ++ITEM) + { + // Set selection_flags for out-of-bounds items + if ((IS_LAST_TILE) && (OffsetT(threadIdx.x * ITEMS_PER_THREAD) + ITEM >= num_tile_items)) + selection_flags[ITEM] = 1; + } + + CTA_SYNC(); + + + OffsetT num_tile_selections = 0; + OffsetT num_selections = 0; + OffsetT num_selections_prefix = 0; + + BlockScanT(temp_storage.scan_storage.scan) + .ExclusiveSum(selection_flags, + selection_idx, + num_tile_selections); + + if (threadIdx.x == 0) + { + // Update tile status if this is not the last tile + if (!IS_LAST_TILE) + tile_state.SetInclusive(0, num_tile_selections); + } + + // Do not count any out-of-bounds selections + if (IS_LAST_TILE) + { + int num_discount = ITEMS_PER_TILE - num_tile_items; + num_tile_selections -= num_discount; + } + num_selections = num_tile_selections; + + CTA_SYNC(); + + Scatter(KeyTagT(), + d_keys_out, + keys, + selection_flags, + selection_idx, + num_tile_items, + num_tile_selections, + num_selections_prefix, + num_selections); + + CTA_SYNC(); + + Scatter(ValueTagT(), + d_values_out, + values, + selection_flags, + selection_idx, + num_tile_items, + num_tile_selections, + num_selections_prefix, + num_selections); + + return num_selections; + } + + /** + * Process subsequent tile of input (dynamic chained scan). Returns the running count of selections (including this tile) + */ + template + __device__ __forceinline__ OffsetT ConsumeSubsequentTile( + int num_tile_items, ///< Number of input items comprising this tile + int tile_idx, ///< Tile index + OffsetT tile_offset, ///< Tile offset + ScanTileStateT& tile_state) ///< Global tile state descriptor + { + KeyT keys[ITEMS_PER_THREAD]; + OffsetT selection_flags[ITEMS_PER_THREAD]; + OffsetT selection_idx[ITEMS_PER_THREAD]; + + if (IS_LAST_TILE) + { + // Fill last elements with the first element + // because collectives are not suffix guarded + BlockLoadKeys(temp_storage.load_keys) + .Load(d_keys_in + tile_offset, + keys, + num_tile_items, + *(d_keys_in + tile_offset)); + } + else + { + BlockLoadKeys(temp_storage.load_keys).Load(d_keys_in + tile_offset, keys); + } + + + CTA_SYNC(); + + ValueT values[ITEMS_PER_THREAD]; + if (IS_LAST_TILE) + { + // Fill last elements with the first element + // because collectives are not suffix guarded + BlockLoadValues(temp_storage.load_values) + .Load(d_values_in + tile_offset, + values, + num_tile_items, + *(d_values_in + tile_offset)); + } + else + { + BlockLoadValues(temp_storage.load_values) + .Load(d_values_in + tile_offset, values); + } + + CTA_SYNC(); + + KeyT tile_predecessor = d_keys_in[tile_offset - 1]; + BlockDiscontinuityKeys(temp_storage.scan_storage.discontinuity) + .FlagHeads(selection_flags, keys, inequality_op, tile_predecessor); + + #pragma unroll + for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ++ITEM) + { + // Set selection_flags for out-of-bounds items + if ((IS_LAST_TILE) && (OffsetT(threadIdx.x * ITEMS_PER_THREAD) + ITEM >= num_tile_items)) + selection_flags[ITEM] = 1; + } + + CTA_SYNC(); + + + OffsetT num_tile_selections = 0; + OffsetT num_selections = 0; + OffsetT num_selections_prefix = 0; + + TilePrefixCallback prefix_cb(tile_state, + temp_storage.scan_storage.prefix, + cub::Sum(), + tile_idx); + BlockScanT(temp_storage.scan_storage.scan) + .ExclusiveSum(selection_flags, + selection_idx, + prefix_cb); + + num_selections = prefix_cb.GetInclusivePrefix(); + num_tile_selections = prefix_cb.GetBlockAggregate(); + num_selections_prefix = prefix_cb.GetExclusivePrefix(); + + if (IS_LAST_TILE) + { + int num_discount = ITEMS_PER_TILE - num_tile_items; + num_tile_selections -= num_discount; + num_selections -= num_discount; + } + + CTA_SYNC(); + + Scatter(KeyTagT(), + d_keys_out, + keys, + selection_flags, + selection_idx, + num_tile_items, + num_tile_selections, + num_selections_prefix, + num_selections); + + CTA_SYNC(); + + Scatter(ValueTagT(), + d_values_out, + values, + selection_flags, + selection_idx, + num_tile_items, + num_tile_selections, + num_selections_prefix, + num_selections); + + return num_selections; + } + + + /** + * Process a tile of input + */ + template + __device__ __forceinline__ OffsetT ConsumeTile( + int num_tile_items, ///< Number of input items comprising this tile + int tile_idx, ///< Tile index + OffsetT tile_offset, ///< Tile offset + ScanTileStateT& tile_state) ///< Global tile state descriptor + { + OffsetT num_selections; + if (tile_idx == 0) + { + num_selections = ConsumeFirstTile(num_tile_items, tile_offset, tile_state); + } + else + { + num_selections = ConsumeSubsequentTile(num_tile_items, tile_idx, tile_offset, tile_state); + } + + return num_selections; + } + + /** + * Scan tiles of items as part of a dynamic chained scan + */ + template ///< Output iterator type for recording number of items selection_flags + __device__ __forceinline__ void ConsumeRange( + int num_tiles, ///< Total number of input tiles + ScanTileStateT& tile_state, ///< Global tile state descriptor + NumSelectedIteratorT d_num_selected_out) ///< Output total number selection_flags + { + // Blocks are launched in increasing order, so just assign one tile per block + int tile_idx = (blockIdx.x * gridDim.y) + blockIdx.y; // Current tile index + OffsetT tile_offset = tile_idx * ITEMS_PER_TILE; // Global offset for the current tile + + if (tile_idx < num_tiles - 1) + { + ConsumeTile(ITEMS_PER_TILE, + tile_idx, + tile_offset, + tile_state); + } + else + { + int num_remaining = static_cast(num_items - tile_offset); + OffsetT num_selections = ConsumeTile(num_remaining, + tile_idx, + tile_offset, + tile_state); + if (threadIdx.x == 0) + { + *d_num_selected_out = num_selections; + } + } + } +}; + + + +CUB_NAMESPACE_END diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/block/block_discontinuity.cuh b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/block/block_discontinuity.cuh new file mode 100644 index 0000000000000000000000000000000000000000..a3bf17f319034c1b1754198cdb93856b8212d46d --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/block/block_discontinuity.cuh @@ -0,0 +1,1119 @@ +/****************************************************************************** + * Copyright (c) 2011, Duane Merrill. All rights reserved. + * Copyright (c) 2011-2018, NVIDIA CORPORATION. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the NVIDIA CORPORATION nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ******************************************************************************/ + +/** + * \file + * The cub::BlockDiscontinuity class provides [collective](index.html#sec0) methods for flagging discontinuities within an ordered set of items partitioned across a CUDA thread block. + */ + +#pragma once + +#include "../config.cuh" +#include "../util_type.cuh" +#include "../util_ptx.cuh" + +CUB_NAMESPACE_BEGIN + +/** + * \brief The BlockDiscontinuity class provides [collective](index.html#sec0) methods for flagging discontinuities within an ordered set of items partitioned across a CUDA thread block. ![](discont_logo.png) + * \ingroup BlockModule + * + * \tparam T The data type to be flagged. + * \tparam BLOCK_DIM_X The thread block length in threads along the X dimension + * \tparam BLOCK_DIM_Y [optional] The thread block length in threads along the Y dimension (default: 1) + * \tparam BLOCK_DIM_Z [optional] The thread block length in threads along the Z dimension (default: 1) + * \tparam LEGACY_PTX_ARCH [optional] Unused. + * + * \par Overview + * - A set of "head flags" (or "tail flags") is often used to indicate corresponding items + * that differ from their predecessors (or successors). For example, head flags are convenient + * for demarcating disjoint data segments as part of a segmented scan or reduction. + * - \blocked + * + * \par Performance Considerations + * - \granularity + * + * \par A Simple Example + * \blockcollective{BlockDiscontinuity} + * \par + * The code snippet below illustrates the head flagging of 512 integer items that + * are partitioned in a [blocked arrangement](index.html#sec5sec3) across 128 threads + * where each thread owns 4 consecutive items. + * \par + * \code + * #include // or equivalently + * + * __global__ void ExampleKernel(...) + * { + * // Specialize BlockDiscontinuity for a 1D block of 128 threads of type int + * typedef cub::BlockDiscontinuity BlockDiscontinuity; + * + * // Allocate shared memory for BlockDiscontinuity + * __shared__ typename BlockDiscontinuity::TempStorage temp_storage; + * + * // Obtain a segment of consecutive items that are blocked across threads + * int thread_data[4]; + * ... + * + * // Collectively compute head flags for discontinuities in the segment + * int head_flags[4]; + * BlockDiscontinuity(temp_storage).FlagHeads(head_flags, thread_data, cub::Inequality()); + * + * \endcode + * \par + * Suppose the set of input \p thread_data across the block of threads is + * { [0,0,1,1], [1,1,1,1], [2,3,3,3], [3,4,4,4], ... }. + * The corresponding output \p head_flags in those threads will be + * { [1,0,1,0], [0,0,0,0], [1,1,0,0], [0,1,0,0], ... }. + * + * \par Performance Considerations + * - Incurs zero bank conflicts for most types + * + * \par Re-using dynamically allocating shared memory + * The following example under the examples/block folder illustrates usage of + * dynamically shared memory with BlockReduce and how to re-purpose + * the same memory region: + * example_block_reduce_dyn_smem.cu + * + * This example can be easily adapted to the storage required by BlockDiscontinuity. + */ +template < + typename T, + int BLOCK_DIM_X, + int BLOCK_DIM_Y = 1, + int BLOCK_DIM_Z = 1, + int LEGACY_PTX_ARCH = 0> +class BlockDiscontinuity +{ +private: + + /****************************************************************************** + * Constants and type definitions + ******************************************************************************/ + + /// Constants + enum + { + /// The thread block size in threads + BLOCK_THREADS = BLOCK_DIM_X * BLOCK_DIM_Y * BLOCK_DIM_Z, + }; + + + /// Shared memory storage layout type (last element from each thread's input) + struct _TempStorage + { + T first_items[BLOCK_THREADS]; + T last_items[BLOCK_THREADS]; + }; + + + /****************************************************************************** + * Utility methods + ******************************************************************************/ + + /// Internal storage allocator + __device__ __forceinline__ _TempStorage& PrivateStorage() + { + __shared__ _TempStorage private_storage; + return private_storage; + } + + + /// Specialization for when FlagOp has third index param + template ::HAS_PARAM> + struct ApplyOp + { + // Apply flag operator + static __device__ __forceinline__ bool FlagT(FlagOp flag_op, const T &a, const T &b, int idx) + { + return flag_op(a, b, idx); + } + }; + + /// Specialization for when FlagOp does not have a third index param + template + struct ApplyOp + { + // Apply flag operator + static __device__ __forceinline__ bool FlagT(FlagOp flag_op, const T &a, const T &b, int /*idx*/) + { + return flag_op(a, b); + } + }; + + /// Templated unrolling of item comparison (inductive case) + struct Iterate + { + // Head flags + template < + int ITEMS_PER_THREAD, + typename FlagT, + typename FlagOp> + static __device__ __forceinline__ void FlagHeads( + int linear_tid, + FlagT (&flags)[ITEMS_PER_THREAD], ///< [out] Calling thread's discontinuity head_flags + T (&input)[ITEMS_PER_THREAD], ///< [in] Calling thread's input items + T (&preds)[ITEMS_PER_THREAD], ///< [out] Calling thread's predecessor items + FlagOp flag_op) ///< [in] Binary boolean flag predicate + { + #pragma unroll + for (int i = 1; i < ITEMS_PER_THREAD; ++i) { + preds[i] = input[i - 1]; + flags[i] = ApplyOp::FlagT( + flag_op, + preds[i], + input[i], + (linear_tid * ITEMS_PER_THREAD) + i); + } + } + + // Tail flags + template < + int ITEMS_PER_THREAD, + typename FlagT, + typename FlagOp> + static __device__ __forceinline__ void FlagTails( + int linear_tid, + FlagT (&flags)[ITEMS_PER_THREAD], ///< [out] Calling thread's discontinuity head_flags + T (&input)[ITEMS_PER_THREAD], ///< [in] Calling thread's input items + FlagOp flag_op) ///< [in] Binary boolean flag predicate + { + #pragma unroll + for (int i = 0; i < ITEMS_PER_THREAD - 1; ++i) { + flags[i] = ApplyOp::FlagT( + flag_op, + input[i], + input[i + 1], + (linear_tid * ITEMS_PER_THREAD) + i + 1); + } + } + + }; + + /****************************************************************************** + * Thread fields + ******************************************************************************/ + + /// Shared storage reference + _TempStorage &temp_storage; + + /// Linear thread-id + unsigned int linear_tid; + + +public: + + /// \smemstorage{BlockDiscontinuity} + struct TempStorage : Uninitialized<_TempStorage> {}; + + + /******************************************************************//** + * \name Collective constructors + *********************************************************************/ + //@{ + + /** + * \brief Collective constructor using a private static allocation of shared memory as temporary storage. + */ + __device__ __forceinline__ BlockDiscontinuity() + : + temp_storage(PrivateStorage()), + linear_tid(RowMajorTid(BLOCK_DIM_X, BLOCK_DIM_Y, BLOCK_DIM_Z)) + {} + + + /** + * \brief Collective constructor using the specified memory allocation as temporary storage. + */ + __device__ __forceinline__ BlockDiscontinuity( + TempStorage &temp_storage) ///< [in] Reference to memory allocation having layout type TempStorage + : + temp_storage(temp_storage.Alias()), + linear_tid(RowMajorTid(BLOCK_DIM_X, BLOCK_DIM_Y, BLOCK_DIM_Z)) + {} + + + //@} end member group + /******************************************************************//** + * \name Head flag operations + *********************************************************************/ + //@{ + + +#ifndef DOXYGEN_SHOULD_SKIP_THIS // Do not document + + template < + int ITEMS_PER_THREAD, + typename FlagT, + typename FlagOp> + __device__ __forceinline__ void FlagHeads( + FlagT (&head_flags)[ITEMS_PER_THREAD], ///< [out] Calling thread's discontinuity head_flags + T (&input)[ITEMS_PER_THREAD], ///< [in] Calling thread's input items + T (&preds)[ITEMS_PER_THREAD], ///< [out] Calling thread's predecessor items + FlagOp flag_op) ///< [in] Binary boolean flag predicate + { + // Share last item + temp_storage.last_items[linear_tid] = input[ITEMS_PER_THREAD - 1]; + + CTA_SYNC(); + + if (linear_tid == 0) + { + // Set flag for first thread-item (preds[0] is undefined) + head_flags[0] = 1; + } + else + { + preds[0] = temp_storage.last_items[linear_tid - 1]; + head_flags[0] = ApplyOp::FlagT(flag_op, preds[0], input[0], linear_tid * ITEMS_PER_THREAD); + } + + // Set head_flags for remaining items + Iterate::FlagHeads(linear_tid, head_flags, input, preds, flag_op); + } + + template < + int ITEMS_PER_THREAD, + typename FlagT, + typename FlagOp> + __device__ __forceinline__ void FlagHeads( + FlagT (&head_flags)[ITEMS_PER_THREAD], ///< [out] Calling thread's discontinuity head_flags + T (&input)[ITEMS_PER_THREAD], ///< [in] Calling thread's input items + T (&preds)[ITEMS_PER_THREAD], ///< [out] Calling thread's predecessor items + FlagOp flag_op, ///< [in] Binary boolean flag predicate + T tile_predecessor_item) ///< [in] [thread0 only] Item with which to compare the first tile item (input0 from thread0). + { + // Share last item + temp_storage.last_items[linear_tid] = input[ITEMS_PER_THREAD - 1]; + + CTA_SYNC(); + + // Set flag for first thread-item + preds[0] = (linear_tid == 0) ? + tile_predecessor_item : // First thread + temp_storage.last_items[linear_tid - 1]; + + head_flags[0] = ApplyOp::FlagT(flag_op, preds[0], input[0], linear_tid * ITEMS_PER_THREAD); + + // Set head_flags for remaining items + Iterate::FlagHeads(linear_tid, head_flags, input, preds, flag_op); + } + +#endif // DOXYGEN_SHOULD_SKIP_THIS + + + /** + * \brief Sets head flags indicating discontinuities between items partitioned across the thread block, for which the first item has no reference and is always flagged. + * + * \par + * - The flag head_flagsi is set for item + * inputi when + * flag_op(previous-item, inputi) + * returns \p true (where previous-item is either the preceding item + * in the same thread or the last item in the previous thread). + * - For thread0, item input0 is always flagged. + * - \blocked + * - \granularity + * - \smemreuse + * + * \par Snippet + * The code snippet below illustrates the head-flagging of 512 integer items that + * are partitioned in a [blocked arrangement](index.html#sec5sec3) across 128 threads + * where each thread owns 4 consecutive items. + * \par + * \code + * #include // or equivalently + * + * __global__ void ExampleKernel(...) + * { + * // Specialize BlockDiscontinuity for a 1D block of 128 threads of type int + * typedef cub::BlockDiscontinuity BlockDiscontinuity; + * + * // Allocate shared memory for BlockDiscontinuity + * __shared__ typename BlockDiscontinuity::TempStorage temp_storage; + * + * // Obtain a segment of consecutive items that are blocked across threads + * int thread_data[4]; + * ... + * + * // Collectively compute head flags for discontinuities in the segment + * int head_flags[4]; + * BlockDiscontinuity(temp_storage).FlagHeads(head_flags, thread_data, cub::Inequality()); + * + * \endcode + * \par + * Suppose the set of input \p thread_data across the block of threads is + * { [0,0,1,1], [1,1,1,1], [2,3,3,3], [3,4,4,4], ... }. + * The corresponding output \p head_flags in those threads will be + * { [1,0,1,0], [0,0,0,0], [1,1,0,0], [0,1,0,0], ... }. + * + * \tparam ITEMS_PER_THREAD [inferred] The number of consecutive items partitioned onto each thread. + * \tparam FlagT [inferred] The flag type (must be an integer type) + * \tparam FlagOp [inferred] Binary predicate functor type having member T operator()(const T &a, const T &b) or member T operator()(const T &a, const T &b, unsigned int b_index), and returning \p true if a discontinuity exists between \p a and \p b, otherwise \p false. \p b_index is the rank of b in the aggregate tile of data. + */ + template < + int ITEMS_PER_THREAD, + typename FlagT, + typename FlagOp> + __device__ __forceinline__ void FlagHeads( + FlagT (&head_flags)[ITEMS_PER_THREAD], ///< [out] Calling thread's discontinuity head_flags + T (&input)[ITEMS_PER_THREAD], ///< [in] Calling thread's input items + FlagOp flag_op) ///< [in] Binary boolean flag predicate + { + T preds[ITEMS_PER_THREAD]; + FlagHeads(head_flags, input, preds, flag_op); + } + + + /** + * \brief Sets head flags indicating discontinuities between items partitioned across the thread block. + * + * \par + * - The flag head_flagsi is set for item + * inputi when + * flag_op(previous-item, inputi) + * returns \p true (where previous-item is either the preceding item + * in the same thread or the last item in the previous thread). + * - For thread0, item input0 is compared + * against \p tile_predecessor_item. + * - \blocked + * - \granularity + * - \smemreuse + * + * \par Snippet + * The code snippet below illustrates the head-flagging of 512 integer items that + * are partitioned in a [blocked arrangement](index.html#sec5sec3) across 128 threads + * where each thread owns 4 consecutive items. + * \par + * \code + * #include // or equivalently + * + * __global__ void ExampleKernel(...) + * { + * // Specialize BlockDiscontinuity for a 1D block of 128 threads of type int + * typedef cub::BlockDiscontinuity BlockDiscontinuity; + * + * // Allocate shared memory for BlockDiscontinuity + * __shared__ typename BlockDiscontinuity::TempStorage temp_storage; + * + * // Obtain a segment of consecutive items that are blocked across threads + * int thread_data[4]; + * ... + * + * // Have thread0 obtain the predecessor item for the entire tile + * int tile_predecessor_item; + * if (threadIdx.x == 0) tile_predecessor_item == ... + * + * // Collectively compute head flags for discontinuities in the segment + * int head_flags[4]; + * BlockDiscontinuity(temp_storage).FlagHeads( + * head_flags, thread_data, cub::Inequality(), tile_predecessor_item); + * + * \endcode + * \par + * Suppose the set of input \p thread_data across the block of threads is + * { [0,0,1,1], [1,1,1,1], [2,3,3,3], [3,4,4,4], ... }, + * and that \p tile_predecessor_item is \p 0. The corresponding output \p head_flags in those threads will be + * { [0,0,1,0], [0,0,0,0], [1,1,0,0], [0,1,0,0], ... }. + * + * \tparam ITEMS_PER_THREAD [inferred] The number of consecutive items partitioned onto each thread. + * \tparam FlagT [inferred] The flag type (must be an integer type) + * \tparam FlagOp [inferred] Binary predicate functor type having member T operator()(const T &a, const T &b) or member T operator()(const T &a, const T &b, unsigned int b_index), and returning \p true if a discontinuity exists between \p a and \p b, otherwise \p false. \p b_index is the rank of b in the aggregate tile of data. + */ + template < + int ITEMS_PER_THREAD, + typename FlagT, + typename FlagOp> + __device__ __forceinline__ void FlagHeads( + FlagT (&head_flags)[ITEMS_PER_THREAD], ///< [out] Calling thread's discontinuity head_flags + T (&input)[ITEMS_PER_THREAD], ///< [in] Calling thread's input items + FlagOp flag_op, ///< [in] Binary boolean flag predicate + T tile_predecessor_item) ///< [in] [thread0 only] Item with which to compare the first tile item (input0 from thread0). + { + T preds[ITEMS_PER_THREAD]; + FlagHeads(head_flags, input, preds, flag_op, tile_predecessor_item); + } + + + + //@} end member group + /******************************************************************//** + * \name Tail flag operations + *********************************************************************/ + //@{ + + + /** + * \brief Sets tail flags indicating discontinuities between items partitioned across the thread block, for which the last item has no reference and is always flagged. + * + * \par + * - The flag tail_flagsi is set for item + * inputi when + * flag_op(inputi, next-item) + * returns \p true (where next-item is either the next item + * in the same thread or the first item in the next thread). + * - For threadBLOCK_THREADS-1, item + * inputITEMS_PER_THREAD-1 is always flagged. + * - \blocked + * - \granularity + * - \smemreuse + * + * \par Snippet + * The code snippet below illustrates the tail-flagging of 512 integer items that + * are partitioned in a [blocked arrangement](index.html#sec5sec3) across 128 threads + * where each thread owns 4 consecutive items. + * \par + * \code + * #include // or equivalently + * + * __global__ void ExampleKernel(...) + * { + * // Specialize BlockDiscontinuity for a 1D block of 128 threads of type int + * typedef cub::BlockDiscontinuity BlockDiscontinuity; + * + * // Allocate shared memory for BlockDiscontinuity + * __shared__ typename BlockDiscontinuity::TempStorage temp_storage; + * + * // Obtain a segment of consecutive items that are blocked across threads + * int thread_data[4]; + * ... + * + * // Collectively compute tail flags for discontinuities in the segment + * int tail_flags[4]; + * BlockDiscontinuity(temp_storage).FlagTails(tail_flags, thread_data, cub::Inequality()); + * + * \endcode + * \par + * Suppose the set of input \p thread_data across the block of threads is + * { [0,0,1,1], [1,1,1,1], [2,3,3,3], ..., [124,125,125,125] }. + * The corresponding output \p tail_flags in those threads will be + * { [0,1,0,0], [0,0,0,1], [1,0,0,...], ..., [1,0,0,1] }. + * + * \tparam ITEMS_PER_THREAD [inferred] The number of consecutive items partitioned onto each thread. + * \tparam FlagT [inferred] The flag type (must be an integer type) + * \tparam FlagOp [inferred] Binary predicate functor type having member T operator()(const T &a, const T &b) or member T operator()(const T &a, const T &b, unsigned int b_index), and returning \p true if a discontinuity exists between \p a and \p b, otherwise \p false. \p b_index is the rank of b in the aggregate tile of data. + */ + template < + int ITEMS_PER_THREAD, + typename FlagT, + typename FlagOp> + __device__ __forceinline__ void FlagTails( + FlagT (&tail_flags)[ITEMS_PER_THREAD], ///< [out] Calling thread's discontinuity tail_flags + T (&input)[ITEMS_PER_THREAD], ///< [in] Calling thread's input items + FlagOp flag_op) ///< [in] Binary boolean flag predicate + { + // Share first item + temp_storage.first_items[linear_tid] = input[0]; + + CTA_SYNC(); + + // Set flag for last thread-item + tail_flags[ITEMS_PER_THREAD - 1] = (linear_tid == BLOCK_THREADS - 1) ? + 1 : // Last thread + ApplyOp::FlagT( + flag_op, + input[ITEMS_PER_THREAD - 1], + temp_storage.first_items[linear_tid + 1], + (linear_tid * ITEMS_PER_THREAD) + ITEMS_PER_THREAD); + + // Set tail_flags for remaining items + Iterate::FlagTails(linear_tid, tail_flags, input, flag_op); + } + + + /** + * \brief Sets tail flags indicating discontinuities between items partitioned across the thread block. + * + * \par + * - The flag tail_flagsi is set for item + * inputi when + * flag_op(inputi, next-item) + * returns \p true (where next-item is either the next item + * in the same thread or the first item in the next thread). + * - For threadBLOCK_THREADS-1, item + * inputITEMS_PER_THREAD-1 is compared + * against \p tile_successor_item. + * - \blocked + * - \granularity + * - \smemreuse + * + * \par Snippet + * The code snippet below illustrates the tail-flagging of 512 integer items that + * are partitioned in a [blocked arrangement](index.html#sec5sec3) across 128 threads + * where each thread owns 4 consecutive items. + * \par + * \code + * #include // or equivalently + * + * __global__ void ExampleKernel(...) + * { + * // Specialize BlockDiscontinuity for a 1D block of 128 threads of type int + * typedef cub::BlockDiscontinuity BlockDiscontinuity; + * + * // Allocate shared memory for BlockDiscontinuity + * __shared__ typename BlockDiscontinuity::TempStorage temp_storage; + * + * // Obtain a segment of consecutive items that are blocked across threads + * int thread_data[4]; + * ... + * + * // Have thread127 obtain the successor item for the entire tile + * int tile_successor_item; + * if (threadIdx.x == 127) tile_successor_item == ... + * + * // Collectively compute tail flags for discontinuities in the segment + * int tail_flags[4]; + * BlockDiscontinuity(temp_storage).FlagTails( + * tail_flags, thread_data, cub::Inequality(), tile_successor_item); + * + * \endcode + * \par + * Suppose the set of input \p thread_data across the block of threads is + * { [0,0,1,1], [1,1,1,1], [2,3,3,3], ..., [124,125,125,125] } + * and that \p tile_successor_item is \p 125. The corresponding output \p tail_flags in those threads will be + * { [0,1,0,0], [0,0,0,1], [1,0,0,...], ..., [1,0,0,0] }. + * + * \tparam ITEMS_PER_THREAD [inferred] The number of consecutive items partitioned onto each thread. + * \tparam FlagT [inferred] The flag type (must be an integer type) + * \tparam FlagOp [inferred] Binary predicate functor type having member T operator()(const T &a, const T &b) or member T operator()(const T &a, const T &b, unsigned int b_index), and returning \p true if a discontinuity exists between \p a and \p b, otherwise \p false. \p b_index is the rank of b in the aggregate tile of data. + */ + template < + int ITEMS_PER_THREAD, + typename FlagT, + typename FlagOp> + __device__ __forceinline__ void FlagTails( + FlagT (&tail_flags)[ITEMS_PER_THREAD], ///< [out] Calling thread's discontinuity tail_flags + T (&input)[ITEMS_PER_THREAD], ///< [in] Calling thread's input items + FlagOp flag_op, ///< [in] Binary boolean flag predicate + T tile_successor_item) ///< [in] [threadBLOCK_THREADS-1 only] Item with which to compare the last tile item (inputITEMS_PER_THREAD-1 from threadBLOCK_THREADS-1). + { + // Share first item + temp_storage.first_items[linear_tid] = input[0]; + + CTA_SYNC(); + + // Set flag for last thread-item + T successor_item = (linear_tid == BLOCK_THREADS - 1) ? + tile_successor_item : // Last thread + temp_storage.first_items[linear_tid + 1]; + + tail_flags[ITEMS_PER_THREAD - 1] = ApplyOp::FlagT( + flag_op, + input[ITEMS_PER_THREAD - 1], + successor_item, + (linear_tid * ITEMS_PER_THREAD) + ITEMS_PER_THREAD); + + // Set tail_flags for remaining items + Iterate::FlagTails(linear_tid, tail_flags, input, flag_op); + } + + + //@} end member group + /******************************************************************//** + * \name Head & tail flag operations + *********************************************************************/ + //@{ + + + /** + * \brief Sets both head and tail flags indicating discontinuities between items partitioned across the thread block. + * + * \par + * - The flag head_flagsi is set for item + * inputi when + * flag_op(previous-item, inputi) + * returns \p true (where previous-item is either the preceding item + * in the same thread or the last item in the previous thread). + * - For thread0, item input0 is always flagged. + * - The flag tail_flagsi is set for item + * inputi when + * flag_op(inputi, next-item) + * returns \p true (where next-item is either the next item + * in the same thread or the first item in the next thread). + * - For threadBLOCK_THREADS-1, item + * inputITEMS_PER_THREAD-1 is always flagged. + * - \blocked + * - \granularity + * - \smemreuse + * + * \par Snippet + * The code snippet below illustrates the head- and tail-flagging of 512 integer items that + * are partitioned in a [blocked arrangement](index.html#sec5sec3) across 128 threads + * where each thread owns 4 consecutive items. + * \par + * \code + * #include // or equivalently + * + * __global__ void ExampleKernel(...) + * { + * // Specialize BlockDiscontinuity for a 1D block of 128 threads of type int + * typedef cub::BlockDiscontinuity BlockDiscontinuity; + * + * // Allocate shared memory for BlockDiscontinuity + * __shared__ typename BlockDiscontinuity::TempStorage temp_storage; + * + * // Obtain a segment of consecutive items that are blocked across threads + * int thread_data[4]; + * ... + * + * // Collectively compute head and flags for discontinuities in the segment + * int head_flags[4]; + * int tail_flags[4]; + * BlockDiscontinuity(temp_storage).FlagTails( + * head_flags, tail_flags, thread_data, cub::Inequality()); + * + * \endcode + * \par + * Suppose the set of input \p thread_data across the block of threads is + * { [0,0,1,1], [1,1,1,1], [2,3,3,3], ..., [124,125,125,125] } + * and that the tile_successor_item is \p 125. The corresponding output \p head_flags + * in those threads will be { [1,0,1,0], [0,0,0,0], [1,1,0,0], [0,1,0,0], ... }. + * and the corresponding output \p tail_flags in those threads will be + * { [0,1,0,0], [0,0,0,1], [1,0,0,...], ..., [1,0,0,1] }. + * + * \tparam ITEMS_PER_THREAD [inferred] The number of consecutive items partitioned onto each thread. + * \tparam FlagT [inferred] The flag type (must be an integer type) + * \tparam FlagOp [inferred] Binary predicate functor type having member T operator()(const T &a, const T &b) or member T operator()(const T &a, const T &b, unsigned int b_index), and returning \p true if a discontinuity exists between \p a and \p b, otherwise \p false. \p b_index is the rank of b in the aggregate tile of data. + */ + template < + int ITEMS_PER_THREAD, + typename FlagT, + typename FlagOp> + __device__ __forceinline__ void FlagHeadsAndTails( + FlagT (&head_flags)[ITEMS_PER_THREAD], ///< [out] Calling thread's discontinuity head_flags + FlagT (&tail_flags)[ITEMS_PER_THREAD], ///< [out] Calling thread's discontinuity tail_flags + T (&input)[ITEMS_PER_THREAD], ///< [in] Calling thread's input items + FlagOp flag_op) ///< [in] Binary boolean flag predicate + { + // Share first and last items + temp_storage.first_items[linear_tid] = input[0]; + temp_storage.last_items[linear_tid] = input[ITEMS_PER_THREAD - 1]; + + CTA_SYNC(); + + T preds[ITEMS_PER_THREAD]; + + // Set flag for first thread-item + if (linear_tid == 0) + { + head_flags[0] = 1; + } + else + { + preds[0] = temp_storage.last_items[linear_tid - 1]; + head_flags[0] = ApplyOp::FlagT( + flag_op, + preds[0], + input[0], + linear_tid * ITEMS_PER_THREAD); + } + + + // Set flag for last thread-item + tail_flags[ITEMS_PER_THREAD - 1] = (linear_tid == BLOCK_THREADS - 1) ? + 1 : // Last thread + ApplyOp::FlagT( + flag_op, + input[ITEMS_PER_THREAD - 1], + temp_storage.first_items[linear_tid + 1], + (linear_tid * ITEMS_PER_THREAD) + ITEMS_PER_THREAD); + + // Set head_flags for remaining items + Iterate::FlagHeads(linear_tid, head_flags, input, preds, flag_op); + + // Set tail_flags for remaining items + Iterate::FlagTails(linear_tid, tail_flags, input, flag_op); + } + + + /** + * \brief Sets both head and tail flags indicating discontinuities between items partitioned across the thread block. + * + * \par + * - The flag head_flagsi is set for item + * inputi when + * flag_op(previous-item, inputi) + * returns \p true (where previous-item is either the preceding item + * in the same thread or the last item in the previous thread). + * - For thread0, item input0 is always flagged. + * - The flag tail_flagsi is set for item + * inputi when + * flag_op(inputi, next-item) + * returns \p true (where next-item is either the next item + * in the same thread or the first item in the next thread). + * - For threadBLOCK_THREADS-1, item + * inputITEMS_PER_THREAD-1 is compared + * against \p tile_predecessor_item. + * - \blocked + * - \granularity + * - \smemreuse + * + * \par Snippet + * The code snippet below illustrates the head- and tail-flagging of 512 integer items that + * are partitioned in a [blocked arrangement](index.html#sec5sec3) across 128 threads + * where each thread owns 4 consecutive items. + * \par + * \code + * #include // or equivalently + * + * __global__ void ExampleKernel(...) + * { + * // Specialize BlockDiscontinuity for a 1D block of 128 threads of type int + * typedef cub::BlockDiscontinuity BlockDiscontinuity; + * + * // Allocate shared memory for BlockDiscontinuity + * __shared__ typename BlockDiscontinuity::TempStorage temp_storage; + * + * // Obtain a segment of consecutive items that are blocked across threads + * int thread_data[4]; + * ... + * + * // Have thread127 obtain the successor item for the entire tile + * int tile_successor_item; + * if (threadIdx.x == 127) tile_successor_item == ... + * + * // Collectively compute head and flags for discontinuities in the segment + * int head_flags[4]; + * int tail_flags[4]; + * BlockDiscontinuity(temp_storage).FlagTails( + * head_flags, tail_flags, tile_successor_item, thread_data, cub::Inequality()); + * + * \endcode + * \par + * Suppose the set of input \p thread_data across the block of threads is + * { [0,0,1,1], [1,1,1,1], [2,3,3,3], ..., [124,125,125,125] } + * and that the tile_successor_item is \p 125. The corresponding output \p head_flags + * in those threads will be { [1,0,1,0], [0,0,0,0], [1,1,0,0], [0,1,0,0], ... }. + * and the corresponding output \p tail_flags in those threads will be + * { [0,1,0,0], [0,0,0,1], [1,0,0,...], ..., [1,0,0,0] }. + * + * \tparam ITEMS_PER_THREAD [inferred] The number of consecutive items partitioned onto each thread. + * \tparam FlagT [inferred] The flag type (must be an integer type) + * \tparam FlagOp [inferred] Binary predicate functor type having member T operator()(const T &a, const T &b) or member T operator()(const T &a, const T &b, unsigned int b_index), and returning \p true if a discontinuity exists between \p a and \p b, otherwise \p false. \p b_index is the rank of b in the aggregate tile of data. + */ + template < + int ITEMS_PER_THREAD, + typename FlagT, + typename FlagOp> + __device__ __forceinline__ void FlagHeadsAndTails( + FlagT (&head_flags)[ITEMS_PER_THREAD], ///< [out] Calling thread's discontinuity head_flags + FlagT (&tail_flags)[ITEMS_PER_THREAD], ///< [out] Calling thread's discontinuity tail_flags + T tile_successor_item, ///< [in] [threadBLOCK_THREADS-1 only] Item with which to compare the last tile item (inputITEMS_PER_THREAD-1 from threadBLOCK_THREADS-1). + T (&input)[ITEMS_PER_THREAD], ///< [in] Calling thread's input items + FlagOp flag_op) ///< [in] Binary boolean flag predicate + { + // Share first and last items + temp_storage.first_items[linear_tid] = input[0]; + temp_storage.last_items[linear_tid] = input[ITEMS_PER_THREAD - 1]; + + CTA_SYNC(); + + T preds[ITEMS_PER_THREAD]; + + // Set flag for first thread-item + if (linear_tid == 0) + { + head_flags[0] = 1; + } + else + { + preds[0] = temp_storage.last_items[linear_tid - 1]; + head_flags[0] = ApplyOp::FlagT( + flag_op, + preds[0], + input[0], + linear_tid * ITEMS_PER_THREAD); + } + + // Set flag for last thread-item + T successor_item = (linear_tid == BLOCK_THREADS - 1) ? + tile_successor_item : // Last thread + temp_storage.first_items[linear_tid + 1]; + + tail_flags[ITEMS_PER_THREAD - 1] = ApplyOp::FlagT( + flag_op, + input[ITEMS_PER_THREAD - 1], + successor_item, + (linear_tid * ITEMS_PER_THREAD) + ITEMS_PER_THREAD); + + // Set head_flags for remaining items + Iterate::FlagHeads(linear_tid, head_flags, input, preds, flag_op); + + // Set tail_flags for remaining items + Iterate::FlagTails(linear_tid, tail_flags, input, flag_op); + } + + + /** + * \brief Sets both head and tail flags indicating discontinuities between items partitioned across the thread block. + * + * \par + * - The flag head_flagsi is set for item + * inputi when + * flag_op(previous-item, inputi) + * returns \p true (where previous-item is either the preceding item + * in the same thread or the last item in the previous thread). + * - For thread0, item input0 is compared + * against \p tile_predecessor_item. + * - The flag tail_flagsi is set for item + * inputi when + * flag_op(inputi, next-item) + * returns \p true (where next-item is either the next item + * in the same thread or the first item in the next thread). + * - For threadBLOCK_THREADS-1, item + * inputITEMS_PER_THREAD-1 is always flagged. + * - \blocked + * - \granularity + * - \smemreuse + * + * \par Snippet + * The code snippet below illustrates the head- and tail-flagging of 512 integer items that + * are partitioned in a [blocked arrangement](index.html#sec5sec3) across 128 threads + * where each thread owns 4 consecutive items. + * \par + * \code + * #include // or equivalently + * + * __global__ void ExampleKernel(...) + * { + * // Specialize BlockDiscontinuity for a 1D block of 128 threads of type int + * typedef cub::BlockDiscontinuity BlockDiscontinuity; + * + * // Allocate shared memory for BlockDiscontinuity + * __shared__ typename BlockDiscontinuity::TempStorage temp_storage; + * + * // Obtain a segment of consecutive items that are blocked across threads + * int thread_data[4]; + * ... + * + * // Have thread0 obtain the predecessor item for the entire tile + * int tile_predecessor_item; + * if (threadIdx.x == 0) tile_predecessor_item == ... + * + * // Have thread127 obtain the successor item for the entire tile + * int tile_successor_item; + * if (threadIdx.x == 127) tile_successor_item == ... + * + * // Collectively compute head and flags for discontinuities in the segment + * int head_flags[4]; + * int tail_flags[4]; + * BlockDiscontinuity(temp_storage).FlagTails( + * head_flags, tile_predecessor_item, tail_flags, tile_successor_item, + * thread_data, cub::Inequality()); + * + * \endcode + * \par + * Suppose the set of input \p thread_data across the block of threads is + * { [0,0,1,1], [1,1,1,1], [2,3,3,3], ..., [124,125,125,125] }, + * that the \p tile_predecessor_item is \p 0, and that the + * \p tile_successor_item is \p 125. The corresponding output \p head_flags + * in those threads will be { [0,0,1,0], [0,0,0,0], [1,1,0,0], [0,1,0,0], ... }. + * and the corresponding output \p tail_flags in those threads will be + * { [0,1,0,0], [0,0,0,1], [1,0,0,...], ..., [1,0,0,1] }. + * + * \tparam ITEMS_PER_THREAD [inferred] The number of consecutive items partitioned onto each thread. + * \tparam FlagT [inferred] The flag type (must be an integer type) + * \tparam FlagOp [inferred] Binary predicate functor type having member T operator()(const T &a, const T &b) or member T operator()(const T &a, const T &b, unsigned int b_index), and returning \p true if a discontinuity exists between \p a and \p b, otherwise \p false. \p b_index is the rank of b in the aggregate tile of data. + */ + template < + int ITEMS_PER_THREAD, + typename FlagT, + typename FlagOp> + __device__ __forceinline__ void FlagHeadsAndTails( + FlagT (&head_flags)[ITEMS_PER_THREAD], ///< [out] Calling thread's discontinuity head_flags + T tile_predecessor_item, ///< [in] [thread0 only] Item with which to compare the first tile item (input0 from thread0). + FlagT (&tail_flags)[ITEMS_PER_THREAD], ///< [out] Calling thread's discontinuity tail_flags + T (&input)[ITEMS_PER_THREAD], ///< [in] Calling thread's input items + FlagOp flag_op) ///< [in] Binary boolean flag predicate + { + // Share first and last items + temp_storage.first_items[linear_tid] = input[0]; + temp_storage.last_items[linear_tid] = input[ITEMS_PER_THREAD - 1]; + + CTA_SYNC(); + + T preds[ITEMS_PER_THREAD]; + + // Set flag for first thread-item + preds[0] = (linear_tid == 0) ? + tile_predecessor_item : // First thread + temp_storage.last_items[linear_tid - 1]; + + head_flags[0] = ApplyOp::FlagT( + flag_op, + preds[0], + input[0], + linear_tid * ITEMS_PER_THREAD); + + // Set flag for last thread-item + tail_flags[ITEMS_PER_THREAD - 1] = (linear_tid == BLOCK_THREADS - 1) ? + 1 : // Last thread + ApplyOp::FlagT( + flag_op, + input[ITEMS_PER_THREAD - 1], + temp_storage.first_items[linear_tid + 1], + (linear_tid * ITEMS_PER_THREAD) + ITEMS_PER_THREAD); + + // Set head_flags for remaining items + Iterate::FlagHeads(linear_tid, head_flags, input, preds, flag_op); + + // Set tail_flags for remaining items + Iterate::FlagTails(linear_tid, tail_flags, input, flag_op); + } + + + /** + * \brief Sets both head and tail flags indicating discontinuities between items partitioned across the thread block. + * + * \par + * - The flag head_flagsi is set for item + * inputi when + * flag_op(previous-item, inputi) + * returns \p true (where previous-item is either the preceding item + * in the same thread or the last item in the previous thread). + * - For thread0, item input0 is compared + * against \p tile_predecessor_item. + * - The flag tail_flagsi is set for item + * inputi when + * flag_op(inputi, next-item) + * returns \p true (where next-item is either the next item + * in the same thread or the first item in the next thread). + * - For threadBLOCK_THREADS-1, item + * inputITEMS_PER_THREAD-1 is compared + * against \p tile_successor_item. + * - \blocked + * - \granularity + * - \smemreuse + * + * \par Snippet + * The code snippet below illustrates the head- and tail-flagging of 512 integer items that + * are partitioned in a [blocked arrangement](index.html#sec5sec3) across 128 threads + * where each thread owns 4 consecutive items. + * \par + * \code + * #include // or equivalently + * + * __global__ void ExampleKernel(...) + * { + * // Specialize BlockDiscontinuity for a 1D block of 128 threads of type int + * typedef cub::BlockDiscontinuity BlockDiscontinuity; + * + * // Allocate shared memory for BlockDiscontinuity + * __shared__ typename BlockDiscontinuity::TempStorage temp_storage; + * + * // Obtain a segment of consecutive items that are blocked across threads + * int thread_data[4]; + * ... + * + * // Have thread0 obtain the predecessor item for the entire tile + * int tile_predecessor_item; + * if (threadIdx.x == 0) tile_predecessor_item == ... + * + * // Have thread127 obtain the successor item for the entire tile + * int tile_successor_item; + * if (threadIdx.x == 127) tile_successor_item == ... + * + * // Collectively compute head and flags for discontinuities in the segment + * int head_flags[4]; + * int tail_flags[4]; + * BlockDiscontinuity(temp_storage).FlagTails( + * head_flags, tile_predecessor_item, tail_flags, tile_successor_item, + * thread_data, cub::Inequality()); + * + * \endcode + * \par + * Suppose the set of input \p thread_data across the block of threads is + * { [0,0,1,1], [1,1,1,1], [2,3,3,3], ..., [124,125,125,125] }, + * that the \p tile_predecessor_item is \p 0, and that the + * \p tile_successor_item is \p 125. The corresponding output \p head_flags + * in those threads will be { [0,0,1,0], [0,0,0,0], [1,1,0,0], [0,1,0,0], ... }. + * and the corresponding output \p tail_flags in those threads will be + * { [0,1,0,0], [0,0,0,1], [1,0,0,...], ..., [1,0,0,0] }. + * + * \tparam ITEMS_PER_THREAD [inferred] The number of consecutive items partitioned onto each thread. + * \tparam FlagT [inferred] The flag type (must be an integer type) + * \tparam FlagOp [inferred] Binary predicate functor type having member T operator()(const T &a, const T &b) or member T operator()(const T &a, const T &b, unsigned int b_index), and returning \p true if a discontinuity exists between \p a and \p b, otherwise \p false. \p b_index is the rank of b in the aggregate tile of data. + */ + template < + int ITEMS_PER_THREAD, + typename FlagT, + typename FlagOp> + __device__ __forceinline__ void FlagHeadsAndTails( + FlagT (&head_flags)[ITEMS_PER_THREAD], ///< [out] Calling thread's discontinuity head_flags + T tile_predecessor_item, ///< [in] [thread0 only] Item with which to compare the first tile item (input0 from thread0). + FlagT (&tail_flags)[ITEMS_PER_THREAD], ///< [out] Calling thread's discontinuity tail_flags + T tile_successor_item, ///< [in] [threadBLOCK_THREADS-1 only] Item with which to compare the last tile item (inputITEMS_PER_THREAD-1 from threadBLOCK_THREADS-1). + T (&input)[ITEMS_PER_THREAD], ///< [in] Calling thread's input items + FlagOp flag_op) ///< [in] Binary boolean flag predicate + { + // Share first and last items + temp_storage.first_items[linear_tid] = input[0]; + temp_storage.last_items[linear_tid] = input[ITEMS_PER_THREAD - 1]; + + CTA_SYNC(); + + T preds[ITEMS_PER_THREAD]; + + // Set flag for first thread-item + preds[0] = (linear_tid == 0) ? + tile_predecessor_item : // First thread + temp_storage.last_items[linear_tid - 1]; + + head_flags[0] = ApplyOp::FlagT( + flag_op, + preds[0], + input[0], + linear_tid * ITEMS_PER_THREAD); + + // Set flag for last thread-item + T successor_item = (linear_tid == BLOCK_THREADS - 1) ? + tile_successor_item : // Last thread + temp_storage.first_items[linear_tid + 1]; + + tail_flags[ITEMS_PER_THREAD - 1] = ApplyOp::FlagT( + flag_op, + input[ITEMS_PER_THREAD - 1], + successor_item, + (linear_tid * ITEMS_PER_THREAD) + ITEMS_PER_THREAD); + + // Set head_flags for remaining items + Iterate::FlagHeads(linear_tid, head_flags, input, preds, flag_op); + + // Set tail_flags for remaining items + Iterate::FlagTails(linear_tid, tail_flags, input, flag_op); + } + + + + + //@} end member group + +}; + + +CUB_NAMESPACE_END diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/block/block_exchange.cuh b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/block/block_exchange.cuh new file mode 100644 index 0000000000000000000000000000000000000000..5f4bc2e84a8373ceb49969f69a291841ff77293c --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/block/block_exchange.cuh @@ -0,0 +1,1144 @@ +/****************************************************************************** + * Copyright (c) 2011, Duane Merrill. All rights reserved. + * Copyright (c) 2011-2018, NVIDIA CORPORATION. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the NVIDIA CORPORATION nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ******************************************************************************/ + +/** + * \file + * The cub::BlockExchange class provides [collective](index.html#sec0) methods for rearranging data partitioned across a CUDA thread block. + */ + +#pragma once + +#include +#include +#include +#include +#include + +CUB_NAMESPACE_BEGIN + +/** + * \brief The BlockExchange class provides [collective](index.html#sec0) methods for rearranging data partitioned across a CUDA thread block. ![](transpose_logo.png) + * \ingroup BlockModule + * + * \tparam T The data type to be exchanged. + * \tparam BLOCK_DIM_X The thread block length in threads along the X dimension + * \tparam ITEMS_PER_THREAD The number of items partitioned onto each thread. + * \tparam WARP_TIME_SLICING [optional] When \p true, only use enough shared memory for a single warp's worth of tile data, time-slicing the block-wide exchange over multiple synchronized rounds. Yields a smaller memory footprint at the expense of decreased parallelism. (Default: false) + * \tparam BLOCK_DIM_Y [optional] The thread block length in threads along the Y dimension (default: 1) + * \tparam BLOCK_DIM_Z [optional] The thread block length in threads along the Z dimension (default: 1) + * \tparam LEGACY_PTX_ARCH [optional] Unused. + * + * \par Overview + * - It is commonplace for blocks of threads to rearrange data items between + * threads. For example, the device-accessible memory subsystem prefers access patterns + * where data items are "striped" across threads (where consecutive threads access consecutive items), + * yet most block-wide operations prefer a "blocked" partitioning of items across threads + * (where consecutive items belong to a single thread). + * - BlockExchange supports the following types of data exchanges: + * - Transposing between [blocked](index.html#sec5sec3) and [striped](index.html#sec5sec3) arrangements + * - Transposing between [blocked](index.html#sec5sec3) and [warp-striped](index.html#sec5sec3) arrangements + * - Scattering ranked items to a [blocked arrangement](index.html#sec5sec3) + * - Scattering ranked items to a [striped arrangement](index.html#sec5sec3) + * - \rowmajor + * + * \par A Simple Example + * \blockcollective{BlockExchange} + * \par + * The code snippet below illustrates the conversion from a "blocked" to a "striped" arrangement + * of 512 integer items partitioned across 128 threads where each thread owns 4 items. + * \par + * \code + * #include // or equivalently + * + * __global__ void ExampleKernel(int *d_data, ...) + * { + * // Specialize BlockExchange for a 1D block of 128 threads owning 4 integer items each + * typedef cub::BlockExchange BlockExchange; + * + * // Allocate shared memory for BlockExchange + * __shared__ typename BlockExchange::TempStorage temp_storage; + * + * // Load a tile of data striped across threads + * int thread_data[4]; + * cub::LoadDirectStriped<128>(threadIdx.x, d_data, thread_data); + * + * // Collectively exchange data into a blocked arrangement across threads + * BlockExchange(temp_storage).StripedToBlocked(thread_data); + * + * \endcode + * \par + * Suppose the set of striped input \p thread_data across the block of threads is + * { [0,128,256,384], [1,129,257,385], ..., [127,255,383,511] }. + * The corresponding output \p thread_data in those threads will be + * { [0,1,2,3], [4,5,6,7], [8,9,10,11], ..., [508,509,510,511] }. + * + * \par Performance Considerations + * - Proper device-specific padding ensures zero bank conflicts for most types. + * + * \par Re-using dynamically allocating shared memory + * The following example under the examples/block folder illustrates usage of + * dynamically shared memory with BlockReduce and how to re-purpose + * the same memory region: + * example_block_reduce_dyn_smem.cu + * + * This example can be easily adapted to the storage required by BlockExchange. + */ +template < + typename InputT, + int BLOCK_DIM_X, + int ITEMS_PER_THREAD, + bool WARP_TIME_SLICING = false, + int BLOCK_DIM_Y = 1, + int BLOCK_DIM_Z = 1, + int LEGACY_PTX_ARCH = 0> +class BlockExchange +{ +private: + + /****************************************************************************** + * Constants + ******************************************************************************/ + + /// Constants + enum + { + /// The thread block size in threads + BLOCK_THREADS = BLOCK_DIM_X * BLOCK_DIM_Y * BLOCK_DIM_Z, + + LOG_WARP_THREADS = CUB_LOG_WARP_THREADS(0), + WARP_THREADS = 1 << LOG_WARP_THREADS, + WARPS = (BLOCK_THREADS + WARP_THREADS - 1) / WARP_THREADS, + + LOG_SMEM_BANKS = CUB_LOG_SMEM_BANKS(0), + SMEM_BANKS = 1 << LOG_SMEM_BANKS, + + TILE_ITEMS = BLOCK_THREADS * ITEMS_PER_THREAD, + + TIME_SLICES = (WARP_TIME_SLICING) ? WARPS : 1, + + TIME_SLICED_THREADS = (WARP_TIME_SLICING) ? CUB_MIN(BLOCK_THREADS, WARP_THREADS) : BLOCK_THREADS, + TIME_SLICED_ITEMS = TIME_SLICED_THREADS * ITEMS_PER_THREAD, + + WARP_TIME_SLICED_THREADS = CUB_MIN(BLOCK_THREADS, WARP_THREADS), + WARP_TIME_SLICED_ITEMS = WARP_TIME_SLICED_THREADS * ITEMS_PER_THREAD, + + // Insert padding to avoid bank conflicts during raking when items per thread is a power of two and > 4 (otherwise we can typically use 128b loads) + INSERT_PADDING = (ITEMS_PER_THREAD > 4) && (PowerOfTwo::VALUE), + PADDING_ITEMS = (INSERT_PADDING) ? (TIME_SLICED_ITEMS >> LOG_SMEM_BANKS) : 0, + }; + + /****************************************************************************** + * Type definitions + ******************************************************************************/ + + /// Shared memory storage layout type + struct __align__(16) _TempStorage + { + InputT buff[TIME_SLICED_ITEMS + PADDING_ITEMS]; + }; + +public: + + /// \smemstorage{BlockExchange} + struct TempStorage : Uninitialized<_TempStorage> {}; + +private: + + + /****************************************************************************** + * Thread fields + ******************************************************************************/ + + /// Shared storage reference + _TempStorage &temp_storage; + + /// Linear thread-id + unsigned int linear_tid; + unsigned int lane_id; + unsigned int warp_id; + unsigned int warp_offset; + + + /****************************************************************************** + * Utility methods + ******************************************************************************/ + + /// Internal storage allocator + __device__ __forceinline__ _TempStorage& PrivateStorage() + { + __shared__ _TempStorage private_storage; + return private_storage; + } + + + /** + * Transposes data items from blocked arrangement to striped arrangement. Specialized for no timeslicing. + */ + template + __device__ __forceinline__ void BlockedToStriped( + InputT (&input_items)[ITEMS_PER_THREAD], ///< [in] Items to exchange, converting between blocked and striped arrangements. + OutputT (&output_items)[ITEMS_PER_THREAD], ///< [out] Items to exchange, converting between blocked and striped arrangements. + Int2Type /*time_slicing*/) + { + #pragma unroll + for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ITEM++) + { + int item_offset = (linear_tid * ITEMS_PER_THREAD) + ITEM; + if (INSERT_PADDING) item_offset += item_offset >> LOG_SMEM_BANKS; + detail::uninitialized_copy(temp_storage.buff + item_offset, + input_items[ITEM]); + } + + CTA_SYNC(); + + #pragma unroll + for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ITEM++) + { + int item_offset = int(ITEM * BLOCK_THREADS) + linear_tid; + if (INSERT_PADDING) item_offset += item_offset >> LOG_SMEM_BANKS; + output_items[ITEM] = temp_storage.buff[item_offset]; + } + } + + + /** + * Transposes data items from blocked arrangement to striped arrangement. Specialized for warp-timeslicing. + */ + template + __device__ __forceinline__ void BlockedToStriped( + InputT (&input_items)[ITEMS_PER_THREAD], ///< [in] Items to exchange, converting between blocked and striped arrangements. + OutputT (&output_items)[ITEMS_PER_THREAD], ///< [out] Items to exchange, converting between blocked and striped arrangements. + Int2Type /*time_slicing*/) + { + InputT temp_items[ITEMS_PER_THREAD]; + + #pragma unroll + for (int SLICE = 0; SLICE < TIME_SLICES; SLICE++) + { + const int SLICE_OFFSET = SLICE * TIME_SLICED_ITEMS; + const int SLICE_OOB = SLICE_OFFSET + TIME_SLICED_ITEMS; + + CTA_SYNC(); + + if (warp_id == SLICE) + { + #pragma unroll + for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ITEM++) + { + int item_offset = (lane_id * ITEMS_PER_THREAD) + ITEM; + if (INSERT_PADDING) item_offset += item_offset >> LOG_SMEM_BANKS; + detail::uninitialized_copy(temp_storage.buff + item_offset, + input_items[ITEM]); + } + } + + CTA_SYNC(); + + #pragma unroll + for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ITEM++) + { + // Read a strip of items + const int STRIP_OFFSET = ITEM * BLOCK_THREADS; + const int STRIP_OOB = STRIP_OFFSET + BLOCK_THREADS; + + if ((SLICE_OFFSET < STRIP_OOB) && (SLICE_OOB > STRIP_OFFSET)) + { + int item_offset = STRIP_OFFSET + linear_tid - SLICE_OFFSET; + if ((item_offset >= 0) && (item_offset < TIME_SLICED_ITEMS)) + { + if (INSERT_PADDING) item_offset += item_offset >> LOG_SMEM_BANKS; + temp_items[ITEM] = temp_storage.buff[item_offset]; + } + } + } + } + + // Copy + #pragma unroll + for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ITEM++) + { + output_items[ITEM] = temp_items[ITEM]; + } + } + + + /** + * Transposes data items from blocked arrangement to warp-striped arrangement. Specialized for no timeslicing + */ + template + __device__ __forceinline__ void BlockedToWarpStriped( + InputT (&input_items)[ITEMS_PER_THREAD], ///< [in] Items to exchange, converting between blocked and striped arrangements. + OutputT (&output_items)[ITEMS_PER_THREAD], ///< [out] Items to exchange, converting between blocked and striped arrangements. + Int2Type /*time_slicing*/) + { + #pragma unroll + for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ITEM++) + { + int item_offset = warp_offset + ITEM + (lane_id * ITEMS_PER_THREAD); + if (INSERT_PADDING) item_offset += item_offset >> LOG_SMEM_BANKS; + detail::uninitialized_copy(temp_storage.buff + item_offset, + input_items[ITEM]); + } + + WARP_SYNC(0xffffffff); + + #pragma unroll + for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ITEM++) + { + int item_offset = warp_offset + (ITEM * WARP_TIME_SLICED_THREADS) + lane_id; + if (INSERT_PADDING) item_offset += item_offset >> LOG_SMEM_BANKS; + output_items[ITEM] = temp_storage.buff[item_offset]; + } + } + + /** + * Transposes data items from blocked arrangement to warp-striped arrangement. Specialized for warp-timeslicing + */ + template + __device__ __forceinline__ void BlockedToWarpStriped( + InputT (&input_items)[ITEMS_PER_THREAD], ///< [in] Items to exchange, converting between blocked and striped arrangements. + OutputT (&output_items)[ITEMS_PER_THREAD], ///< [out] Items to exchange, converting between blocked and striped arrangements. + Int2Type /*time_slicing*/) + { + if (warp_id == 0) + { + #pragma unroll + for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ITEM++) + { + int item_offset = ITEM + (lane_id * ITEMS_PER_THREAD); + if (INSERT_PADDING) item_offset += item_offset >> LOG_SMEM_BANKS; + detail::uninitialized_copy(temp_storage.buff + item_offset, + input_items[ITEM]); + } + + WARP_SYNC(0xffffffff); + + #pragma unroll + for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ITEM++) + { + int item_offset = (ITEM * WARP_TIME_SLICED_THREADS) + lane_id; + if (INSERT_PADDING) item_offset += item_offset >> LOG_SMEM_BANKS; + output_items[ITEM] = temp_storage.buff[item_offset]; + } + } + + #pragma unroll + for (unsigned int SLICE = 1; SLICE < TIME_SLICES; ++SLICE) + { + CTA_SYNC(); + + if (warp_id == SLICE) + { + #pragma unroll + for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ITEM++) + { + int item_offset = ITEM + (lane_id * ITEMS_PER_THREAD); + if (INSERT_PADDING) item_offset += item_offset >> LOG_SMEM_BANKS; + detail::uninitialized_copy(temp_storage.buff + item_offset, + input_items[ITEM]); + } + + WARP_SYNC(0xffffffff); + + #pragma unroll + for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ITEM++) + { + int item_offset = (ITEM * WARP_TIME_SLICED_THREADS) + lane_id; + if (INSERT_PADDING) item_offset += item_offset >> LOG_SMEM_BANKS; + output_items[ITEM] = temp_storage.buff[item_offset]; + } + } + } + } + + + /** + * Transposes data items from striped arrangement to blocked arrangement. Specialized for no timeslicing. + */ + template + __device__ __forceinline__ void StripedToBlocked( + InputT (&input_items)[ITEMS_PER_THREAD], ///< [in] Items to exchange, converting between blocked and striped arrangements. + OutputT (&output_items)[ITEMS_PER_THREAD], ///< [out] Items to exchange, converting between blocked and striped arrangements. + Int2Type /*time_slicing*/) + { + #pragma unroll + for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ITEM++) + { + int item_offset = int(ITEM * BLOCK_THREADS) + linear_tid; + if (INSERT_PADDING) item_offset += item_offset >> LOG_SMEM_BANKS; + detail::uninitialized_copy(temp_storage.buff + item_offset, + input_items[ITEM]); + } + + CTA_SYNC(); + + // No timeslicing + #pragma unroll + for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ITEM++) + { + int item_offset = (linear_tid * ITEMS_PER_THREAD) + ITEM; + if (INSERT_PADDING) item_offset += item_offset >> LOG_SMEM_BANKS; + output_items[ITEM] = temp_storage.buff[item_offset]; + } + } + + + /** + * Transposes data items from striped arrangement to blocked arrangement. Specialized for warp-timeslicing. + */ + template + __device__ __forceinline__ void StripedToBlocked( + InputT (&input_items)[ITEMS_PER_THREAD], ///< [in] Items to exchange, converting between blocked and striped arrangements. + OutputT (&output_items)[ITEMS_PER_THREAD], ///< [out] Items to exchange, converting between blocked and striped arrangements. + Int2Type /*time_slicing*/) + { + // Warp time-slicing + InputT temp_items[ITEMS_PER_THREAD]; + + #pragma unroll + for (int SLICE = 0; SLICE < TIME_SLICES; SLICE++) + { + const int SLICE_OFFSET = SLICE * TIME_SLICED_ITEMS; + const int SLICE_OOB = SLICE_OFFSET + TIME_SLICED_ITEMS; + + CTA_SYNC(); + + #pragma unroll + for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ITEM++) + { + // Write a strip of items + const int STRIP_OFFSET = ITEM * BLOCK_THREADS; + const int STRIP_OOB = STRIP_OFFSET + BLOCK_THREADS; + + if ((SLICE_OFFSET < STRIP_OOB) && (SLICE_OOB > STRIP_OFFSET)) + { + int item_offset = STRIP_OFFSET + linear_tid - SLICE_OFFSET; + if ((item_offset >= 0) && (item_offset < TIME_SLICED_ITEMS)) + { + if (INSERT_PADDING) item_offset += item_offset >> LOG_SMEM_BANKS; + detail::uninitialized_copy(temp_storage.buff + + item_offset, + input_items[ITEM]); + } + } + } + + CTA_SYNC(); + + if (warp_id == SLICE) + { + #pragma unroll + for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ITEM++) + { + int item_offset = (lane_id * ITEMS_PER_THREAD) + ITEM; + if (INSERT_PADDING) item_offset += item_offset >> LOG_SMEM_BANKS; + temp_items[ITEM] = temp_storage.buff[item_offset]; + } + } + } + + // Copy + #pragma unroll + for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ITEM++) + { + output_items[ITEM] = temp_items[ITEM]; + } + } + + + /** + * Transposes data items from warp-striped arrangement to blocked arrangement. Specialized for no timeslicing + */ + template + __device__ __forceinline__ void WarpStripedToBlocked( + InputT (&input_items)[ITEMS_PER_THREAD], ///< [in] Items to exchange, converting between blocked and striped arrangements. + OutputT (&output_items)[ITEMS_PER_THREAD], ///< [out] Items to exchange, converting between blocked and striped arrangements. + Int2Type /*time_slicing*/) + { + #pragma unroll + for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ITEM++) + { + int item_offset = warp_offset + (ITEM * WARP_TIME_SLICED_THREADS) + lane_id; + if (INSERT_PADDING) item_offset += item_offset >> LOG_SMEM_BANKS; + detail::uninitialized_copy(temp_storage.buff + item_offset, + input_items[ITEM]); + } + + WARP_SYNC(0xffffffff); + + #pragma unroll + for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ITEM++) + { + int item_offset = warp_offset + ITEM + (lane_id * ITEMS_PER_THREAD); + if (INSERT_PADDING) item_offset += item_offset >> LOG_SMEM_BANKS; + detail::uninitialized_copy(output_items + ITEM, + temp_storage.buff[item_offset]); + } + } + + + /** + * Transposes data items from warp-striped arrangement to blocked arrangement. Specialized for warp-timeslicing + */ + template + __device__ __forceinline__ void WarpStripedToBlocked( + InputT (&input_items)[ITEMS_PER_THREAD], ///< [in] Items to exchange, converting between blocked and striped arrangements. + OutputT (&output_items)[ITEMS_PER_THREAD], ///< [out] Items to exchange, converting between blocked and striped arrangements. + Int2Type /*time_slicing*/) + { + #pragma unroll + for (unsigned int SLICE = 0; SLICE < TIME_SLICES; ++SLICE) + { + CTA_SYNC(); + + if (warp_id == SLICE) + { + #pragma unroll + for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ITEM++) + { + int item_offset = (ITEM * WARP_TIME_SLICED_THREADS) + lane_id; + if (INSERT_PADDING) item_offset += item_offset >> LOG_SMEM_BANKS; + detail::uninitialized_copy(temp_storage.buff + item_offset, + input_items[ITEM]); + } + + WARP_SYNC(0xffffffff); + + #pragma unroll + for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ITEM++) + { + int item_offset = ITEM + (lane_id * ITEMS_PER_THREAD); + if (INSERT_PADDING) item_offset += item_offset >> LOG_SMEM_BANKS; + output_items[ITEM] = temp_storage.buff[item_offset]; + } + } + } + } + + + /** + * Exchanges data items annotated by rank into blocked arrangement. Specialized for no timeslicing. + */ + template + __device__ __forceinline__ void ScatterToBlocked( + InputT (&input_items)[ITEMS_PER_THREAD], ///< [in] Items to exchange, converting between blocked and striped arrangements. + OutputT (&output_items)[ITEMS_PER_THREAD], ///< [out] Items to exchange, converting between blocked and striped arrangements. + OffsetT (&ranks)[ITEMS_PER_THREAD], ///< [in] Corresponding scatter ranks + Int2Type /*time_slicing*/) + { + #pragma unroll + for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ITEM++) + { + int item_offset = ranks[ITEM]; + if (INSERT_PADDING) item_offset = SHR_ADD(item_offset, LOG_SMEM_BANKS, item_offset); + detail::uninitialized_copy(temp_storage.buff + item_offset, + input_items[ITEM]); + } + + CTA_SYNC(); + + #pragma unroll + for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ITEM++) + { + int item_offset = (linear_tid * ITEMS_PER_THREAD) + ITEM; + if (INSERT_PADDING) item_offset = SHR_ADD(item_offset, LOG_SMEM_BANKS, item_offset); + output_items[ITEM] = temp_storage.buff[item_offset]; + } + } + + /** + * Exchanges data items annotated by rank into blocked arrangement. Specialized for warp-timeslicing. + */ + template + __device__ __forceinline__ void ScatterToBlocked( + InputT (&input_items)[ITEMS_PER_THREAD], ///< [in] Items to exchange, converting between blocked and striped arrangements. + OutputT (&output_items)[ITEMS_PER_THREAD], ///< [out] Items to exchange, converting between blocked and striped arrangements. + OffsetT ranks[ITEMS_PER_THREAD], ///< [in] Corresponding scatter ranks + Int2Type /*time_slicing*/) + { + InputT temp_items[ITEMS_PER_THREAD]; + + #pragma unroll + for (int SLICE = 0; SLICE < TIME_SLICES; SLICE++) + { + CTA_SYNC(); + + const int SLICE_OFFSET = TIME_SLICED_ITEMS * SLICE; + + #pragma unroll + for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ITEM++) + { + int item_offset = ranks[ITEM] - SLICE_OFFSET; + if ((item_offset >= 0) && (item_offset < WARP_TIME_SLICED_ITEMS)) + { + if (INSERT_PADDING) item_offset = SHR_ADD(item_offset, LOG_SMEM_BANKS, item_offset); + detail::uninitialized_copy(temp_storage.buff + item_offset, + input_items[ITEM]); + } + } + + CTA_SYNC(); + + if (warp_id == SLICE) + { + #pragma unroll + for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ITEM++) + { + int item_offset = (lane_id * ITEMS_PER_THREAD) + ITEM; + if (INSERT_PADDING) item_offset = SHR_ADD(item_offset, LOG_SMEM_BANKS, item_offset); + temp_items[ITEM] = temp_storage.buff[item_offset]; + } + } + } + + // Copy + #pragma unroll + for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ITEM++) + { + output_items[ITEM] = temp_items[ITEM]; + } + } + + + /** + * Exchanges data items annotated by rank into striped arrangement. Specialized for no timeslicing. + */ + template + __device__ __forceinline__ void ScatterToStriped( + InputT (&input_items)[ITEMS_PER_THREAD], ///< [in] Items to exchange, converting between blocked and striped arrangements. + OutputT (&output_items)[ITEMS_PER_THREAD], ///< [out] Items to exchange, converting between blocked and striped arrangements. + OffsetT (&ranks)[ITEMS_PER_THREAD], ///< [in] Corresponding scatter ranks + Int2Type /*time_slicing*/) + { + #pragma unroll + for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ITEM++) + { + int item_offset = ranks[ITEM]; + if (INSERT_PADDING) item_offset = SHR_ADD(item_offset, LOG_SMEM_BANKS, item_offset); + detail::uninitialized_copy(temp_storage.buff + item_offset, + input_items[ITEM]); + } + + CTA_SYNC(); + + #pragma unroll + for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ITEM++) + { + int item_offset = int(ITEM * BLOCK_THREADS) + linear_tid; + if (INSERT_PADDING) item_offset = SHR_ADD(item_offset, LOG_SMEM_BANKS, item_offset); + output_items[ITEM] = temp_storage.buff[item_offset]; + } + } + + + /** + * Exchanges data items annotated by rank into striped arrangement. Specialized for warp-timeslicing. + */ + template + __device__ __forceinline__ void ScatterToStriped( + InputT (&input_items)[ITEMS_PER_THREAD], ///< [in] Items to exchange, converting between blocked and striped arrangements. + OutputT (&output_items)[ITEMS_PER_THREAD], ///< [out] Items to exchange, converting between blocked and striped arrangements. + OffsetT (&ranks)[ITEMS_PER_THREAD], ///< [in] Corresponding scatter ranks + Int2Type /*time_slicing*/) + { + InputT temp_items[ITEMS_PER_THREAD]; + + #pragma unroll + for (int SLICE = 0; SLICE < TIME_SLICES; SLICE++) + { + const int SLICE_OFFSET = SLICE * TIME_SLICED_ITEMS; + const int SLICE_OOB = SLICE_OFFSET + TIME_SLICED_ITEMS; + + CTA_SYNC(); + + #pragma unroll + for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ITEM++) + { + int item_offset = ranks[ITEM] - SLICE_OFFSET; + if ((item_offset >= 0) && (item_offset < WARP_TIME_SLICED_ITEMS)) + { + if (INSERT_PADDING) item_offset = SHR_ADD(item_offset, LOG_SMEM_BANKS, item_offset); + detail::uninitialized_copy(temp_storage.buff + item_offset, + input_items[ITEM]); + } + } + + CTA_SYNC(); + + #pragma unroll + for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ITEM++) + { + // Read a strip of items + const int STRIP_OFFSET = ITEM * BLOCK_THREADS; + const int STRIP_OOB = STRIP_OFFSET + BLOCK_THREADS; + + if ((SLICE_OFFSET < STRIP_OOB) && (SLICE_OOB > STRIP_OFFSET)) + { + int item_offset = STRIP_OFFSET + linear_tid - SLICE_OFFSET; + if ((item_offset >= 0) && (item_offset < TIME_SLICED_ITEMS)) + { + if (INSERT_PADDING) item_offset += item_offset >> LOG_SMEM_BANKS; + temp_items[ITEM] = temp_storage.buff[item_offset]; + } + } + } + } + + // Copy + #pragma unroll + for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ITEM++) + { + output_items[ITEM] = temp_items[ITEM]; + } + } + + +public: + + /******************************************************************//** + * \name Collective constructors + *********************************************************************/ + //@{ + + /** + * \brief Collective constructor using a private static allocation of shared memory as temporary storage. + */ + __device__ __forceinline__ BlockExchange() + : + temp_storage(PrivateStorage()), + linear_tid(RowMajorTid(BLOCK_DIM_X, BLOCK_DIM_Y, BLOCK_DIM_Z)), + lane_id(LaneId()), + warp_id((WARPS == 1) ? 0 : linear_tid / WARP_THREADS), + warp_offset(warp_id * WARP_TIME_SLICED_ITEMS) + {} + + + /** + * \brief Collective constructor using the specified memory allocation as temporary storage. + */ + __device__ __forceinline__ BlockExchange( + TempStorage &temp_storage) ///< [in] Reference to memory allocation having layout type TempStorage + : + temp_storage(temp_storage.Alias()), + linear_tid(RowMajorTid(BLOCK_DIM_X, BLOCK_DIM_Y, BLOCK_DIM_Z)), + lane_id(LaneId()), + warp_id((WARPS == 1) ? 0 : linear_tid / WARP_THREADS), + warp_offset(warp_id * WARP_TIME_SLICED_ITEMS) + {} + + + //@} end member group + /******************************************************************//** + * \name Structured exchanges + *********************************************************************/ + //@{ + + /** + * \brief Transposes data items from striped arrangement to blocked arrangement. + * + * \par + * - \smemreuse + * + * \par Snippet + * The code snippet below illustrates the conversion from a "striped" to a "blocked" arrangement + * of 512 integer items partitioned across 128 threads where each thread owns 4 items. + * \par + * \code + * #include // or equivalently + * + * __global__ void ExampleKernel(int *d_data, ...) + * { + * // Specialize BlockExchange for a 1D block of 128 threads owning 4 integer items each + * typedef cub::BlockExchange BlockExchange; + * + * // Allocate shared memory for BlockExchange + * __shared__ typename BlockExchange::TempStorage temp_storage; + * + * // Load a tile of ordered data into a striped arrangement across block threads + * int thread_data[4]; + * cub::LoadDirectStriped<128>(threadIdx.x, d_data, thread_data); + * + * // Collectively exchange data into a blocked arrangement across threads + * BlockExchange(temp_storage).StripedToBlocked(thread_data, thread_data); + * + * \endcode + * \par + * Suppose the set of striped input \p thread_data across the block of threads is + * { [0,128,256,384], [1,129,257,385], ..., [127,255,383,511] } after loading from device-accessible memory. + * The corresponding output \p thread_data in those threads will be + * { [0,1,2,3], [4,5,6,7], [8,9,10,11], ..., [508,509,510,511] }. + * + */ + template + __device__ __forceinline__ void StripedToBlocked( + InputT (&input_items)[ITEMS_PER_THREAD], ///< [in] Items to exchange, converting between striped and blocked arrangements. + OutputT (&output_items)[ITEMS_PER_THREAD]) ///< [out] Items from exchange, converting between striped and blocked arrangements. + { + StripedToBlocked(input_items, output_items, Int2Type()); + } + + + /** + * \brief Transposes data items from blocked arrangement to striped arrangement. + * + * \par + * - \smemreuse + * + * \par Snippet + * The code snippet below illustrates the conversion from a "blocked" to a "striped" arrangement + * of 512 integer items partitioned across 128 threads where each thread owns 4 items. + * \par + * \code + * #include // or equivalently + * + * __global__ void ExampleKernel(int *d_data, ...) + * { + * // Specialize BlockExchange for a 1D block of 128 threads owning 4 integer items each + * typedef cub::BlockExchange BlockExchange; + * + * // Allocate shared memory for BlockExchange + * __shared__ typename BlockExchange::TempStorage temp_storage; + * + * // Obtain a segment of consecutive items that are blocked across threads + * int thread_data[4]; + * ... + * + * // Collectively exchange data into a striped arrangement across threads + * BlockExchange(temp_storage).BlockedToStriped(thread_data, thread_data); + * + * // Store data striped across block threads into an ordered tile + * cub::StoreDirectStriped(threadIdx.x, d_data, thread_data); + * + * \endcode + * \par + * Suppose the set of blocked input \p thread_data across the block of threads is + * { [0,1,2,3], [4,5,6,7], [8,9,10,11], ..., [508,509,510,511] }. + * The corresponding output \p thread_data in those threads will be + * { [0,128,256,384], [1,129,257,385], ..., [127,255,383,511] } in + * preparation for storing to device-accessible memory. + * + */ + template + __device__ __forceinline__ void BlockedToStriped( + InputT (&input_items)[ITEMS_PER_THREAD], ///< [in] Items to exchange, converting between striped and blocked arrangements. + OutputT (&output_items)[ITEMS_PER_THREAD]) ///< [out] Items from exchange, converting between striped and blocked arrangements. + { + BlockedToStriped(input_items, output_items, Int2Type()); + } + + + + /** + * \brief Transposes data items from warp-striped arrangement to blocked arrangement. + * + * \par + * - \smemreuse + * + * \par Snippet + * The code snippet below illustrates the conversion from a "warp-striped" to a "blocked" arrangement + * of 512 integer items partitioned across 128 threads where each thread owns 4 items. + * \par + * \code + * #include // or equivalently + * + * __global__ void ExampleKernel(int *d_data, ...) + * { + * // Specialize BlockExchange for a 1D block of 128 threads owning 4 integer items each + * typedef cub::BlockExchange BlockExchange; + * + * // Allocate shared memory for BlockExchange + * __shared__ typename BlockExchange::TempStorage temp_storage; + * + * // Load a tile of ordered data into a warp-striped arrangement across warp threads + * int thread_data[4]; + * cub::LoadSWarptriped(threadIdx.x, d_data, thread_data); + * + * // Collectively exchange data into a blocked arrangement across threads + * BlockExchange(temp_storage).WarpStripedToBlocked(thread_data); + * + * \endcode + * \par + * Suppose the set of warp-striped input \p thread_data across the block of threads is + * { [0,32,64,96], [1,33,65,97], [2,34,66,98], ..., [415,447,479,511] } + * after loading from device-accessible memory. (The first 128 items are striped across + * the first warp of 32 threads, the second 128 items are striped across the second warp, etc.) + * The corresponding output \p thread_data in those threads will be + * { [0,1,2,3], [4,5,6,7], [8,9,10,11], ..., [508,509,510,511] }. + * + */ + template + __device__ __forceinline__ void WarpStripedToBlocked( + InputT (&input_items)[ITEMS_PER_THREAD], ///< [in] Items to exchange, converting between striped and blocked arrangements. + OutputT (&output_items)[ITEMS_PER_THREAD]) ///< [out] Items from exchange, converting between striped and blocked arrangements. + { + WarpStripedToBlocked(input_items, output_items, Int2Type()); + } + + + + /** + * \brief Transposes data items from blocked arrangement to warp-striped arrangement. + * + * \par + * - \smemreuse + * + * \par Snippet + * The code snippet below illustrates the conversion from a "blocked" to a "warp-striped" arrangement + * of 512 integer items partitioned across 128 threads where each thread owns 4 items. + * \par + * \code + * #include // or equivalently + * + * __global__ void ExampleKernel(int *d_data, ...) + * { + * // Specialize BlockExchange for a 1D block of 128 threads owning 4 integer items each + * typedef cub::BlockExchange BlockExchange; + * + * // Allocate shared memory for BlockExchange + * __shared__ typename BlockExchange::TempStorage temp_storage; + * + * // Obtain a segment of consecutive items that are blocked across threads + * int thread_data[4]; + * ... + * + * // Collectively exchange data into a warp-striped arrangement across threads + * BlockExchange(temp_storage).BlockedToWarpStriped(thread_data, thread_data); + * + * // Store data striped across warp threads into an ordered tile + * cub::StoreDirectStriped(threadIdx.x, d_data, thread_data); + * + * \endcode + * \par + * Suppose the set of blocked input \p thread_data across the block of threads is + * { [0,1,2,3], [4,5,6,7], [8,9,10,11], ..., [508,509,510,511] }. + * The corresponding output \p thread_data in those threads will be + * { [0,32,64,96], [1,33,65,97], [2,34,66,98], ..., [415,447,479,511] } + * in preparation for storing to device-accessible memory. (The first 128 items are striped across + * the first warp of 32 threads, the second 128 items are striped across the second warp, etc.) + * + */ + template + __device__ __forceinline__ void BlockedToWarpStriped( + InputT (&input_items)[ITEMS_PER_THREAD], ///< [in] Items to exchange, converting between striped and blocked arrangements. + OutputT (&output_items)[ITEMS_PER_THREAD]) ///< [out] Items from exchange, converting between striped and blocked arrangements. + { + BlockedToWarpStriped(input_items, output_items, Int2Type()); + } + + + + //@} end member group + /******************************************************************//** + * \name Scatter exchanges + *********************************************************************/ + //@{ + + + /** + * \brief Exchanges data items annotated by rank into blocked arrangement. + * + * \par + * - \smemreuse + * + * \tparam OffsetT [inferred] Signed integer type for local offsets + */ + template + __device__ __forceinline__ void ScatterToBlocked( + InputT (&input_items)[ITEMS_PER_THREAD], ///< [in] Items to exchange, converting between striped and blocked arrangements. + OutputT (&output_items)[ITEMS_PER_THREAD], ///< [out] Items from exchange, converting between striped and blocked arrangements. + OffsetT (&ranks)[ITEMS_PER_THREAD]) ///< [in] Corresponding scatter ranks + { + ScatterToBlocked(input_items, output_items, ranks, Int2Type()); + } + + + + /** + * \brief Exchanges data items annotated by rank into striped arrangement. + * + * \par + * - \smemreuse + * + * \tparam OffsetT [inferred] Signed integer type for local offsets + */ + template + __device__ __forceinline__ void ScatterToStriped( + InputT (&input_items)[ITEMS_PER_THREAD], ///< [in] Items to exchange, converting between striped and blocked arrangements. + OutputT (&output_items)[ITEMS_PER_THREAD], ///< [out] Items from exchange, converting between striped and blocked arrangements. + OffsetT (&ranks)[ITEMS_PER_THREAD]) ///< [in] Corresponding scatter ranks + { + ScatterToStriped(input_items, output_items, ranks, Int2Type()); + } + + + + /** + * \brief Exchanges data items annotated by rank into striped arrangement. Items with rank -1 are not exchanged. + * + * \par + * - \smemreuse + * + * \tparam OffsetT [inferred] Signed integer type for local offsets + */ + template + __device__ __forceinline__ void ScatterToStripedGuarded( + InputT (&input_items)[ITEMS_PER_THREAD], ///< [in] Items to exchange, converting between striped and blocked arrangements. + OutputT (&output_items)[ITEMS_PER_THREAD], ///< [out] Items from exchange, converting between striped and blocked arrangements. + OffsetT (&ranks)[ITEMS_PER_THREAD]) ///< [in] Corresponding scatter ranks + { + #pragma unroll + for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ITEM++) + { + int item_offset = ranks[ITEM]; + if (INSERT_PADDING) item_offset = SHR_ADD(item_offset, LOG_SMEM_BANKS, item_offset); + if (ranks[ITEM] >= 0) + temp_storage.buff[item_offset] = input_items[ITEM]; + } + + CTA_SYNC(); + + #pragma unroll + for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ITEM++) + { + int item_offset = int(ITEM * BLOCK_THREADS) + linear_tid; + if (INSERT_PADDING) item_offset = SHR_ADD(item_offset, LOG_SMEM_BANKS, item_offset); + output_items[ITEM] = temp_storage.buff[item_offset]; + } + } + + + + + /** + * \brief Exchanges valid data items annotated by rank into striped arrangement. + * + * \par + * - \smemreuse + * + * \tparam OffsetT [inferred] Signed integer type for local offsets + * \tparam ValidFlag [inferred] FlagT type denoting which items are valid + */ + template + __device__ __forceinline__ void ScatterToStripedFlagged( + InputT (&input_items)[ITEMS_PER_THREAD], ///< [in] Items to exchange, converting between striped and blocked arrangements. + OutputT (&output_items)[ITEMS_PER_THREAD], ///< [out] Items from exchange, converting between striped and blocked arrangements. + OffsetT (&ranks)[ITEMS_PER_THREAD], ///< [in] Corresponding scatter ranks + ValidFlag (&is_valid)[ITEMS_PER_THREAD]) ///< [in] Corresponding flag denoting item validity + { + #pragma unroll + for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ITEM++) + { + int item_offset = ranks[ITEM]; + if (INSERT_PADDING) item_offset = SHR_ADD(item_offset, LOG_SMEM_BANKS, item_offset); + if (is_valid[ITEM]) + temp_storage.buff[item_offset] = input_items[ITEM]; + } + + CTA_SYNC(); + + #pragma unroll + for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ITEM++) + { + int item_offset = int(ITEM * BLOCK_THREADS) + linear_tid; + if (INSERT_PADDING) item_offset = SHR_ADD(item_offset, LOG_SMEM_BANKS, item_offset); + output_items[ITEM] = temp_storage.buff[item_offset]; + } + } + + + //@} end member group + + + +#ifndef DOXYGEN_SHOULD_SKIP_THIS // Do not document + + + __device__ __forceinline__ void StripedToBlocked( + InputT (&items)[ITEMS_PER_THREAD]) ///< [in-out] Items to exchange, converting between striped and blocked arrangements. + { + StripedToBlocked(items, items); + } + + __device__ __forceinline__ void BlockedToStriped( + InputT (&items)[ITEMS_PER_THREAD]) ///< [in-out] Items to exchange, converting between striped and blocked arrangements. + { + BlockedToStriped(items, items); + } + + __device__ __forceinline__ void WarpStripedToBlocked( + InputT (&items)[ITEMS_PER_THREAD]) ///< [in-out] Items to exchange, converting between striped and blocked arrangements. + { + WarpStripedToBlocked(items, items); + } + + __device__ __forceinline__ void BlockedToWarpStriped( + InputT (&items)[ITEMS_PER_THREAD]) ///< [in-out] Items to exchange, converting between striped and blocked arrangements. + { + BlockedToWarpStriped(items, items); + } + + template + __device__ __forceinline__ void ScatterToBlocked( + InputT (&items)[ITEMS_PER_THREAD], ///< [in-out] Items to exchange, converting between striped and blocked arrangements. + OffsetT (&ranks)[ITEMS_PER_THREAD]) ///< [in] Corresponding scatter ranks + { + ScatterToBlocked(items, items, ranks); + } + + template + __device__ __forceinline__ void ScatterToStriped( + InputT (&items)[ITEMS_PER_THREAD], ///< [in-out] Items to exchange, converting between striped and blocked arrangements. + OffsetT (&ranks)[ITEMS_PER_THREAD]) ///< [in] Corresponding scatter ranks + { + ScatterToStriped(items, items, ranks); + } + + template + __device__ __forceinline__ void ScatterToStripedGuarded( + InputT (&items)[ITEMS_PER_THREAD], ///< [in-out] Items to exchange, converting between striped and blocked arrangements. + OffsetT (&ranks)[ITEMS_PER_THREAD]) ///< [in] Corresponding scatter ranks + { + ScatterToStripedGuarded(items, items, ranks); + } + + template + __device__ __forceinline__ void ScatterToStripedFlagged( + InputT (&items)[ITEMS_PER_THREAD], ///< [in-out] Items to exchange, converting between striped and blocked arrangements. + OffsetT (&ranks)[ITEMS_PER_THREAD], ///< [in] Corresponding scatter ranks + ValidFlag (&is_valid)[ITEMS_PER_THREAD]) ///< [in] Corresponding flag denoting item validity + { + ScatterToStriped(items, items, ranks, is_valid); + } + +#endif // DOXYGEN_SHOULD_SKIP_THIS + + +}; + + +CUB_NAMESPACE_END diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/block/block_load.cuh b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/block/block_load.cuh new file mode 100644 index 0000000000000000000000000000000000000000..b419ab6e726cdc4a77992a1b1fde3bc52a00d4a0 --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/block/block_load.cuh @@ -0,0 +1,1306 @@ +/****************************************************************************** + * Copyright (c) 2011, Duane Merrill. All rights reserved. + * Copyright (c) 2011-2016, NVIDIA CORPORATION. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the NVIDIA CORPORATION nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ******************************************************************************/ + +/** + * \file + * Operations for reading linear tiles of data into the CUDA thread block. + */ + +#pragma once + +#include +#include + +#include "../block/block_exchange.cuh" +#include "../iterator/cache_modified_input_iterator.cuh" +#include "../config.cuh" +#include "../util_ptx.cuh" +#include "../util_type.cuh" + +CUB_NAMESPACE_BEGIN + +/** + * \addtogroup UtilIo + * @{ + */ + + +/******************************************************************//** + * \name Blocked arrangement I/O (direct) + *********************************************************************/ +//@{ + + +/** + * \brief Load a linear segment of items into a blocked arrangement across the thread block. + * + * \blocked + * + * \tparam T [inferred] The data type to load. + * \tparam ITEMS_PER_THREAD [inferred] The number of consecutive items partitioned onto each thread. + * \tparam InputIteratorT [inferred] The random-access iterator type for input \iterator. + */ +template < + typename InputT, + int ITEMS_PER_THREAD, + typename InputIteratorT> +__device__ __forceinline__ void LoadDirectBlocked( + int linear_tid, ///< [in] A suitable 1D thread-identifier for the calling thread (e.g., (threadIdx.y * blockDim.x) + linear_tid for 2D thread blocks) + InputIteratorT block_itr, ///< [in] The thread block's base input iterator for loading from + InputT (&items)[ITEMS_PER_THREAD]) ///< [out] Data to load +{ + // Load directly in thread-blocked order + #pragma unroll + for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ITEM++) + { + items[ITEM] = block_itr[(linear_tid * ITEMS_PER_THREAD) + ITEM]; + } +} + + +/** + * \brief Load a linear segment of items into a blocked arrangement across the thread block, guarded by range. + * + * \blocked + * + * \tparam T [inferred] The data type to load. + * \tparam ITEMS_PER_THREAD [inferred] The number of consecutive items partitioned onto each thread. + * \tparam InputIteratorT [inferred] The random-access iterator type for input \iterator. + */ +template < + typename InputT, + int ITEMS_PER_THREAD, + typename InputIteratorT> +__device__ __forceinline__ void LoadDirectBlocked( + int linear_tid, ///< [in] A suitable 1D thread-identifier for the calling thread (e.g., (threadIdx.y * blockDim.x) + linear_tid for 2D thread blocks) + InputIteratorT block_itr, ///< [in] The thread block's base input iterator for loading from + InputT (&items)[ITEMS_PER_THREAD], ///< [out] Data to load + int valid_items) ///< [in] Number of valid items to load +{ + + #pragma unroll + for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ITEM++) + { + if ((linear_tid * ITEMS_PER_THREAD) + ITEM < valid_items) + { + items[ITEM] = block_itr[(linear_tid * ITEMS_PER_THREAD) + ITEM]; + } + } +} + + +/** + * \brief Load a linear segment of items into a blocked arrangement across the thread block, guarded by range, with a fall-back assignment of out-of-bound elements.. + * + * \blocked + * + * \tparam T [inferred] The data type to load. + * \tparam ITEMS_PER_THREAD [inferred] The number of consecutive items partitioned onto each thread. + * \tparam InputIteratorT [inferred] The random-access iterator type for input \iterator. + */ +template < + typename InputT, + typename DefaultT, + int ITEMS_PER_THREAD, + typename InputIteratorT> +__device__ __forceinline__ void LoadDirectBlocked( + int linear_tid, ///< [in] A suitable 1D thread-identifier for the calling thread (e.g., (threadIdx.y * blockDim.x) + linear_tid for 2D thread blocks) + InputIteratorT block_itr, ///< [in] The thread block's base input iterator for loading from + InputT (&items)[ITEMS_PER_THREAD], ///< [out] Data to load + int valid_items, ///< [in] Number of valid items to load + DefaultT oob_default) ///< [in] Default value to assign out-of-bound items +{ + #pragma unroll + for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ITEM++) + items[ITEM] = oob_default; + + LoadDirectBlocked(linear_tid, block_itr, items, valid_items); +} + + +#ifndef DOXYGEN_SHOULD_SKIP_THIS // Do not document + +/** + * Internal implementation for load vectorization + */ +template < + CacheLoadModifier MODIFIER, + typename T, + int ITEMS_PER_THREAD> +__device__ __forceinline__ void InternalLoadDirectBlockedVectorized( + int linear_tid, ///< [in] A suitable 1D thread-identifier for the calling thread (e.g., (threadIdx.y * blockDim.x) + linear_tid for 2D thread blocks) + T *block_ptr, ///< [in] Input pointer for loading from + T (&items)[ITEMS_PER_THREAD]) ///< [out] Data to load +{ + // Biggest memory access word that T is a whole multiple of + typedef typename UnitWord::DeviceWord DeviceWord; + + enum + { + TOTAL_WORDS = sizeof(items) / sizeof(DeviceWord), + + VECTOR_SIZE = (TOTAL_WORDS % 4 == 0) ? + 4 : + (TOTAL_WORDS % 2 == 0) ? + 2 : + 1, + + VECTORS_PER_THREAD = TOTAL_WORDS / VECTOR_SIZE, + }; + + // Vector type + typedef typename CubVector::Type Vector; + + // Vector items + Vector vec_items[VECTORS_PER_THREAD]; + + // Aliased input ptr + Vector* vec_ptr = reinterpret_cast(block_ptr) + (linear_tid * VECTORS_PER_THREAD); + + // Load directly in thread-blocked order + #pragma unroll + for (int ITEM = 0; ITEM < VECTORS_PER_THREAD; ITEM++) + { + vec_items[ITEM] = ThreadLoad(vec_ptr + ITEM); + } + + // Copy + #pragma unroll + for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ITEM++) + { + items[ITEM] = *(reinterpret_cast(vec_items) + ITEM); + } +} + +#endif // DOXYGEN_SHOULD_SKIP_THIS + + +/** + * \brief Load a linear segment of items into a blocked arrangement across the thread block. + * + * \blocked + * + * The input offset (\p block_ptr + \p block_offset) must be quad-item aligned + * + * The following conditions will prevent vectorization and loading will fall back to cub::BLOCK_LOAD_DIRECT: + * - \p ITEMS_PER_THREAD is odd + * - The data type \p T is not a built-in primitive or CUDA vector type (e.g., \p short, \p int2, \p double, \p float2, etc.) + * + * \tparam T [inferred] The data type to load. + * \tparam ITEMS_PER_THREAD [inferred] The number of consecutive items partitioned onto each thread. + */ +template < + typename T, + int ITEMS_PER_THREAD> +__device__ __forceinline__ void LoadDirectBlockedVectorized( + int linear_tid, ///< [in] A suitable 1D thread-identifier for the calling thread (e.g., (threadIdx.y * blockDim.x) + linear_tid for 2D thread blocks) + T *block_ptr, ///< [in] Input pointer for loading from + T (&items)[ITEMS_PER_THREAD]) ///< [out] Data to load +{ + InternalLoadDirectBlockedVectorized(linear_tid, block_ptr, items); +} + + +//@} end member group +/******************************************************************//** + * \name Striped arrangement I/O (direct) + *********************************************************************/ +//@{ + + +/** + * \brief Load a linear segment of items into a striped arrangement across the thread block. + * + * \striped + * + * \tparam BLOCK_THREADS The thread block size in threads + * \tparam T [inferred] The data type to load. + * \tparam ITEMS_PER_THREAD [inferred] The number of consecutive items partitioned onto each thread. + * \tparam InputIteratorT [inferred] The random-access iterator type for input \iterator. + */ +template < + int BLOCK_THREADS, + typename InputT, + int ITEMS_PER_THREAD, + typename InputIteratorT> +__device__ __forceinline__ void LoadDirectStriped( + int linear_tid, ///< [in] A suitable 1D thread-identifier for the calling thread (e.g., (threadIdx.y * blockDim.x) + linear_tid for 2D thread blocks) + InputIteratorT block_itr, ///< [in] The thread block's base input iterator for loading from + InputT (&items)[ITEMS_PER_THREAD]) ///< [out] Data to load +{ + #pragma unroll + for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ITEM++) + { + items[ITEM] = block_itr[linear_tid + ITEM * BLOCK_THREADS]; + } +} + + +/** + * \brief Load a linear segment of items into a striped arrangement across the thread block, guarded by range + * + * \striped + * + * \tparam BLOCK_THREADS The thread block size in threads + * \tparam T [inferred] The data type to load. + * \tparam ITEMS_PER_THREAD [inferred] The number of consecutive items partitioned onto each thread. + * \tparam InputIteratorT [inferred] The random-access iterator type for input \iterator. + */ +template < + int BLOCK_THREADS, + typename InputT, + int ITEMS_PER_THREAD, + typename InputIteratorT> +__device__ __forceinline__ void LoadDirectStriped( + int linear_tid, ///< [in] A suitable 1D thread-identifier for the calling thread (e.g., (threadIdx.y * blockDim.x) + linear_tid for 2D thread blocks) + InputIteratorT block_itr, ///< [in] The thread block's base input iterator for loading from + InputT (&items)[ITEMS_PER_THREAD], ///< [out] Data to load + int valid_items) ///< [in] Number of valid items to load +{ + #pragma unroll + for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ITEM++) + { + if (linear_tid + (ITEM * BLOCK_THREADS) < valid_items) + { + items[ITEM] = block_itr[linear_tid + ITEM * BLOCK_THREADS]; + } + } +} + + +/** + * \brief Load a linear segment of items into a striped arrangement across the thread block, guarded by range, with a fall-back assignment of out-of-bound elements. + * + * \striped + * + * \tparam BLOCK_THREADS The thread block size in threads + * \tparam T [inferred] The data type to load. + * \tparam ITEMS_PER_THREAD [inferred] The number of consecutive items partitioned onto each thread. + * \tparam InputIteratorT [inferred] The random-access iterator type for input \iterator. + */ +template < + int BLOCK_THREADS, + typename InputT, + typename DefaultT, + int ITEMS_PER_THREAD, + typename InputIteratorT> +__device__ __forceinline__ void LoadDirectStriped( + int linear_tid, ///< [in] A suitable 1D thread-identifier for the calling thread (e.g., (threadIdx.y * blockDim.x) + linear_tid for 2D thread blocks) + InputIteratorT block_itr, ///< [in] The thread block's base input iterator for loading from + InputT (&items)[ITEMS_PER_THREAD], ///< [out] Data to load + int valid_items, ///< [in] Number of valid items to load + DefaultT oob_default) ///< [in] Default value to assign out-of-bound items +{ + #pragma unroll + for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ITEM++) + items[ITEM] = oob_default; + + LoadDirectStriped(linear_tid, block_itr, items, valid_items); +} + + + +//@} end member group +/******************************************************************//** + * \name Warp-striped arrangement I/O (direct) + *********************************************************************/ +//@{ + + +/** + * \brief Load a linear segment of items into a warp-striped arrangement across the thread block. + * + * \warpstriped + * + * \par Usage Considerations + * The number of threads in the thread block must be a multiple of the architecture's warp size. + * + * \tparam T [inferred] The data type to load. + * \tparam ITEMS_PER_THREAD [inferred] The number of consecutive items partitioned onto each thread. + * \tparam InputIteratorT [inferred] The random-access iterator type for input \iterator. + */ +template < + typename InputT, + int ITEMS_PER_THREAD, + typename InputIteratorT> +__device__ __forceinline__ void LoadDirectWarpStriped( + int linear_tid, ///< [in] A suitable 1D thread-identifier for the calling thread (e.g., (threadIdx.y * blockDim.x) + linear_tid for 2D thread blocks) + InputIteratorT block_itr, ///< [in] The thread block's base input iterator for loading from + InputT (&items)[ITEMS_PER_THREAD]) ///< [out] Data to load +{ + int tid = linear_tid & (CUB_PTX_WARP_THREADS - 1); + int wid = linear_tid >> CUB_PTX_LOG_WARP_THREADS; + int warp_offset = wid * CUB_PTX_WARP_THREADS * ITEMS_PER_THREAD; + + // Load directly in warp-striped order + #pragma unroll + for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ITEM++) + { + new(&items[ITEM]) InputT(block_itr[warp_offset + tid + (ITEM * CUB_PTX_WARP_THREADS)]); + } +} + + +/** + * \brief Load a linear segment of items into a warp-striped arrangement across the thread block, guarded by range + * + * \warpstriped + * + * \par Usage Considerations + * The number of threads in the thread block must be a multiple of the architecture's warp size. + * + * \tparam T [inferred] The data type to load. + * \tparam ITEMS_PER_THREAD [inferred] The number of consecutive items partitioned onto each thread. + * \tparam InputIteratorT [inferred] The random-access iterator type for input \iterator. + */ +template < + typename InputT, + int ITEMS_PER_THREAD, + typename InputIteratorT> +__device__ __forceinline__ void LoadDirectWarpStriped( + int linear_tid, ///< [in] A suitable 1D thread-identifier for the calling thread (e.g., (threadIdx.y * blockDim.x) + linear_tid for 2D thread blocks) + InputIteratorT block_itr, ///< [in] The thread block's base input iterator for loading from + InputT (&items)[ITEMS_PER_THREAD], ///< [out] Data to load + int valid_items) ///< [in] Number of valid items to load +{ + int tid = linear_tid & (CUB_PTX_WARP_THREADS - 1); + int wid = linear_tid >> CUB_PTX_LOG_WARP_THREADS; + int warp_offset = wid * CUB_PTX_WARP_THREADS * ITEMS_PER_THREAD; + + // Load directly in warp-striped order + #pragma unroll + for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ITEM++) + { + if (warp_offset + tid + (ITEM * CUB_PTX_WARP_THREADS) < valid_items) + { + new(&items[ITEM]) InputT(block_itr[warp_offset + tid + (ITEM * CUB_PTX_WARP_THREADS)]); + } + } +} + + +/** + * \brief Load a linear segment of items into a warp-striped arrangement across the thread block, guarded by range, with a fall-back assignment of out-of-bound elements. + * + * \warpstriped + * + * \par Usage Considerations + * The number of threads in the thread block must be a multiple of the architecture's warp size. + * + * \tparam T [inferred] The data type to load. + * \tparam ITEMS_PER_THREAD [inferred] The number of consecutive items partitioned onto each thread. + * \tparam InputIteratorT [inferred] The random-access iterator type for input \iterator. + */ +template < + typename InputT, + typename DefaultT, + int ITEMS_PER_THREAD, + typename InputIteratorT> +__device__ __forceinline__ void LoadDirectWarpStriped( + int linear_tid, ///< [in] A suitable 1D thread-identifier for the calling thread (e.g., (threadIdx.y * blockDim.x) + linear_tid for 2D thread blocks) + InputIteratorT block_itr, ///< [in] The thread block's base input iterator for loading from + InputT (&items)[ITEMS_PER_THREAD], ///< [out] Data to load + int valid_items, ///< [in] Number of valid items to load + DefaultT oob_default) ///< [in] Default value to assign out-of-bound items +{ + // Load directly in warp-striped order + #pragma unroll + for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ITEM++) + items[ITEM] = oob_default; + + LoadDirectWarpStriped(linear_tid, block_itr, items, valid_items); +} + + + +//@} end member group + +/** @} */ // end group UtilIo + + + +//----------------------------------------------------------------------------- +// Generic BlockLoad abstraction +//----------------------------------------------------------------------------- + +/** + * \brief cub::BlockLoadAlgorithm enumerates alternative algorithms for cub::BlockLoad to read a linear segment of data from memory into a blocked arrangement across a CUDA thread block. + */ +enum BlockLoadAlgorithm +{ + /** + * \par Overview + * + * A [blocked arrangement](index.html#sec5sec3) of data is read + * directly from memory. + * + * \par Performance Considerations + * The utilization of memory transactions (coalescing) decreases as the + * access stride between threads increases (i.e., the number items per thread). + */ + BLOCK_LOAD_DIRECT, + + /** + * \par Overview + * + * A [striped arrangement](index.html#sec5sec3) of data is read + * directly from memory. + * + * \par Performance Considerations + * The utilization of memory transactions (coalescing) doesn't depend on + * the number of items per thread. + */ + BLOCK_LOAD_STRIPED, + + /** + * \par Overview + * + * A [blocked arrangement](index.html#sec5sec3) of data is read + * from memory using CUDA's built-in vectorized loads as a coalescing optimization. + * For example, ld.global.v4.s32 instructions will be generated + * when \p T = \p int and \p ITEMS_PER_THREAD % 4 == 0. + * + * \par Performance Considerations + * - The utilization of memory transactions (coalescing) remains high until the the + * access stride between threads (i.e., the number items per thread) exceeds the + * maximum vector load width (typically 4 items or 64B, whichever is lower). + * - The following conditions will prevent vectorization and loading will fall + * back to cub::BLOCK_LOAD_DIRECT: + * - \p ITEMS_PER_THREAD is odd + * - The \p InputIteratorT is not a simple pointer type + * - The block input offset is not quadword-aligned + * - The data type \p T is not a built-in primitive or CUDA vector type + * (e.g., \p short, \p int2, \p double, \p float2, etc.) + */ + BLOCK_LOAD_VECTORIZE, + + /** + * \par Overview + * + * A [striped arrangement](index.html#sec5sec3) of data is read + * efficiently from memory and then locally transposed into a + * [blocked arrangement](index.html#sec5sec3). + * + * \par Performance Considerations + * - The utilization of memory transactions (coalescing) remains high regardless + * of items loaded per thread. + * - The local reordering incurs slightly longer latencies and throughput than the + * direct cub::BLOCK_LOAD_DIRECT and cub::BLOCK_LOAD_VECTORIZE alternatives. + */ + BLOCK_LOAD_TRANSPOSE, + + /** + * \par Overview + * + * A [warp-striped arrangement](index.html#sec5sec3) of data is + * read efficiently from memory and then locally transposed into a + * [blocked arrangement](index.html#sec5sec3). + * + * \par Usage Considerations + * - BLOCK_THREADS must be a multiple of WARP_THREADS + * + * \par Performance Considerations + * - The utilization of memory transactions (coalescing) remains high regardless + * of items loaded per thread. + * - The local reordering incurs slightly larger latencies than the + * direct cub::BLOCK_LOAD_DIRECT and cub::BLOCK_LOAD_VECTORIZE alternatives. + * - Provisions more shared storage, but incurs smaller latencies than the + * BLOCK_LOAD_WARP_TRANSPOSE_TIMESLICED alternative. + */ + BLOCK_LOAD_WARP_TRANSPOSE, + + /** + * \par Overview + * + * Like \p BLOCK_LOAD_WARP_TRANSPOSE, a [warp-striped arrangement](index.html#sec5sec3) + * of data is read directly from memory and then is locally transposed into a + * [blocked arrangement](index.html#sec5sec3). To reduce the shared memory + * requirement, only one warp's worth of shared memory is provisioned and is + * subsequently time-sliced among warps. + * + * \par Usage Considerations + * - BLOCK_THREADS must be a multiple of WARP_THREADS + * + * \par Performance Considerations + * - The utilization of memory transactions (coalescing) remains high regardless + * of items loaded per thread. + * - Provisions less shared memory temporary storage, but incurs larger + * latencies than the BLOCK_LOAD_WARP_TRANSPOSE alternative. + */ + BLOCK_LOAD_WARP_TRANSPOSE_TIMESLICED, +}; + + +/** + * \brief The BlockLoad class provides [collective](index.html#sec0) data movement methods for loading a linear segment of items from memory into a [blocked arrangement](index.html#sec5sec3) across a CUDA thread block. ![](block_load_logo.png) + * \ingroup BlockModule + * \ingroup UtilIo + * + * \tparam InputT The data type to read into (which must be convertible from the input iterator's value type). + * \tparam BLOCK_DIM_X The thread block length in threads along the X dimension + * \tparam ITEMS_PER_THREAD The number of consecutive items partitioned onto each thread. + * \tparam ALGORITHM [optional] cub::BlockLoadAlgorithm tuning policy. default: cub::BLOCK_LOAD_DIRECT. + * \tparam WARP_TIME_SLICING [optional] Whether or not only one warp's worth of shared memory should be allocated and time-sliced among block-warps during any load-related data transpositions (versus each warp having its own storage). (default: false) + * \tparam BLOCK_DIM_Y [optional] The thread block length in threads along the Y dimension (default: 1) + * \tparam BLOCK_DIM_Z [optional] The thread block length in threads along the Z dimension (default: 1) + * \tparam LEGACY_PTX_ARCH [optional] Unused. + * + * \par Overview + * - The BlockLoad class provides a single data movement abstraction that can be specialized + * to implement different cub::BlockLoadAlgorithm strategies. This facilitates different + * performance policies for different architectures, data types, granularity sizes, etc. + * - BlockLoad can be optionally specialized by different data movement strategies: + * -# cub::BLOCK_LOAD_DIRECT. A [blocked arrangement](index.html#sec5sec3) + * of data is read directly from memory. [More...](\ref cub::BlockLoadAlgorithm) +* -# cub::BLOCK_LOAD_STRIPED,. A [striped arrangement](index.html#sec5sec3) + * of data is read directly from memory. [More...](\ref cub::BlockLoadAlgorithm) + * -# cub::BLOCK_LOAD_VECTORIZE. A [blocked arrangement](index.html#sec5sec3) + * of data is read directly from memory using CUDA's built-in vectorized loads as a + * coalescing optimization. [More...](\ref cub::BlockLoadAlgorithm) + * -# cub::BLOCK_LOAD_TRANSPOSE. A [striped arrangement](index.html#sec5sec3) + * of data is read directly from memory and is then locally transposed into a + * [blocked arrangement](index.html#sec5sec3). [More...](\ref cub::BlockLoadAlgorithm) + * -# cub::BLOCK_LOAD_WARP_TRANSPOSE. A [warp-striped arrangement](index.html#sec5sec3) + * of data is read directly from memory and is then locally transposed into a + * [blocked arrangement](index.html#sec5sec3). [More...](\ref cub::BlockLoadAlgorithm) + * -# cub::BLOCK_LOAD_WARP_TRANSPOSE_TIMESLICED,. A [warp-striped arrangement](index.html#sec5sec3) + * of data is read directly from memory and is then locally transposed into a + * [blocked arrangement](index.html#sec5sec3) one warp at a time. [More...](\ref cub::BlockLoadAlgorithm) + * - \rowmajor + * + * \par A Simple Example + * \blockcollective{BlockLoad} + * \par + * The code snippet below illustrates the loading of a linear + * segment of 512 integers into a "blocked" arrangement across 128 threads where each + * thread owns 4 consecutive items. The load is specialized for \p BLOCK_LOAD_WARP_TRANSPOSE, + * meaning memory references are efficiently coalesced using a warp-striped access + * pattern (after which items are locally reordered among threads). + * \par + * \code + * #include // or equivalently + * + * __global__ void ExampleKernel(int *d_data, ...) + * { + * // Specialize BlockLoad for a 1D block of 128 threads owning 4 integer items each + * typedef cub::BlockLoad BlockLoad; + * + * // Allocate shared memory for BlockLoad + * __shared__ typename BlockLoad::TempStorage temp_storage; + * + * // Load a segment of consecutive items that are blocked across threads + * int thread_data[4]; + * BlockLoad(temp_storage).Load(d_data, thread_data); + * + * \endcode + * \par + * Suppose the input \p d_data is 0, 1, 2, 3, 4, 5, .... + * The set of \p thread_data across the block of threads in those threads will be + * { [0,1,2,3], [4,5,6,7], ..., [508,509,510,511] }. + * + * \par Re-using dynamically allocating shared memory + * The following example under the examples/block folder illustrates usage of + * dynamically shared memory with BlockReduce and how to re-purpose + * the same memory region: + * example_block_reduce_dyn_smem.cu + * + * This example can be easily adapted to the storage required by BlockLoad. + */ +template < + typename InputT, + int BLOCK_DIM_X, + int ITEMS_PER_THREAD, + BlockLoadAlgorithm ALGORITHM = BLOCK_LOAD_DIRECT, + int BLOCK_DIM_Y = 1, + int BLOCK_DIM_Z = 1, + int LEGACY_PTX_ARCH = 0> +class BlockLoad +{ +private: + + /****************************************************************************** + * Constants and typed definitions + ******************************************************************************/ + + /// Constants + enum + { + /// The thread block size in threads + BLOCK_THREADS = BLOCK_DIM_X * BLOCK_DIM_Y * BLOCK_DIM_Z, + }; + + + /****************************************************************************** + * Algorithmic variants + ******************************************************************************/ + + /// Load helper + template + struct LoadInternal; + + + /** + * BLOCK_LOAD_DIRECT specialization of load helper + */ + template + struct LoadInternal + { + /// Shared memory storage layout type + typedef NullType TempStorage; + + /// Linear thread-id + int linear_tid; + + /// Constructor + __device__ __forceinline__ LoadInternal( + TempStorage &/*temp_storage*/, + int linear_tid) + : + linear_tid(linear_tid) + {} + + /// Load a linear segment of items from memory + template + __device__ __forceinline__ void Load( + InputIteratorT block_itr, ///< [in] The thread block's base input iterator for loading from + InputT (&items)[ITEMS_PER_THREAD]) ///< [out] Data to load + { + LoadDirectBlocked(linear_tid, block_itr, items); + } + + /// Load a linear segment of items from memory, guarded by range + template + __device__ __forceinline__ void Load( + InputIteratorT block_itr, ///< [in] The thread block's base input iterator for loading from + InputT (&items)[ITEMS_PER_THREAD], ///< [out] Data to load + int valid_items) ///< [in] Number of valid items to load + { + LoadDirectBlocked(linear_tid, block_itr, items, valid_items); + } + + /// Load a linear segment of items from memory, guarded by range, with a fall-back assignment of out-of-bound elements + template + __device__ __forceinline__ void Load( + InputIteratorT block_itr, ///< [in] The thread block's base input iterator for loading from + InputT (&items)[ITEMS_PER_THREAD], ///< [out] Data to load + int valid_items, ///< [in] Number of valid items to load + DefaultT oob_default) ///< [in] Default value to assign out-of-bound items + { + LoadDirectBlocked(linear_tid, block_itr, items, valid_items, oob_default); + } + + }; + + + /** + * BLOCK_LOAD_STRIPED specialization of load helper + */ + template + struct LoadInternal + { + /// Shared memory storage layout type + typedef NullType TempStorage; + + /// Linear thread-id + int linear_tid; + + /// Constructor + __device__ __forceinline__ LoadInternal( + TempStorage &/*temp_storage*/, + int linear_tid) + : + linear_tid(linear_tid) + {} + + /// Load a linear segment of items from memory + template + __device__ __forceinline__ void Load( + InputIteratorT block_itr, ///< [in] The thread block's base input iterator for loading from + InputT (&items)[ITEMS_PER_THREAD]) ///< [out] Data to load + { + LoadDirectStriped(linear_tid, block_itr, items); + } + + /// Load a linear segment of items from memory, guarded by range + template + __device__ __forceinline__ void Load( + InputIteratorT block_itr, ///< [in] The thread block's base input iterator for loading from + InputT (&items)[ITEMS_PER_THREAD], ///< [out] Data to load + int valid_items) ///< [in] Number of valid items to load + { + LoadDirectStriped(linear_tid, block_itr, items, valid_items); + } + + /// Load a linear segment of items from memory, guarded by range, with a fall-back assignment of out-of-bound elements + template + __device__ __forceinline__ void Load( + InputIteratorT block_itr, ///< [in] The thread block's base input iterator for loading from + InputT (&items)[ITEMS_PER_THREAD], ///< [out] Data to load + int valid_items, ///< [in] Number of valid items to load + DefaultT oob_default) ///< [in] Default value to assign out-of-bound items + { + LoadDirectStriped(linear_tid, block_itr, items, valid_items, oob_default); + } + + }; + + + /** + * BLOCK_LOAD_VECTORIZE specialization of load helper + */ + template + struct LoadInternal + { + /// Shared memory storage layout type + typedef NullType TempStorage; + + /// Linear thread-id + int linear_tid; + + /// Constructor + __device__ __forceinline__ LoadInternal( + TempStorage &/*temp_storage*/, + int linear_tid) + : + linear_tid(linear_tid) + {} + + /// Load a linear segment of items from memory, specialized for native pointer types (attempts vectorization) + template + __device__ __forceinline__ void Load( + InputT *block_ptr, ///< [in] The thread block's base input iterator for loading from + InputT (&items)[ITEMS_PER_THREAD]) ///< [out] Data to load + { + InternalLoadDirectBlockedVectorized(linear_tid, block_ptr, items); + } + + /// Load a linear segment of items from memory, specialized for native pointer types (attempts vectorization) + template + __device__ __forceinline__ void Load( + const InputT *block_ptr, ///< [in] The thread block's base input iterator for loading from + InputT (&items)[ITEMS_PER_THREAD]) ///< [out] Data to load + { + InternalLoadDirectBlockedVectorized(linear_tid, block_ptr, items); + } + + /// Load a linear segment of items from memory, specialized for native pointer types (attempts vectorization) + template < + CacheLoadModifier MODIFIER, + typename ValueType, + typename OffsetT> + __device__ __forceinline__ void Load( + CacheModifiedInputIterator block_itr, ///< [in] The thread block's base input iterator for loading from + InputT (&items)[ITEMS_PER_THREAD]) ///< [out] Data to load + { + InternalLoadDirectBlockedVectorized(linear_tid, block_itr.ptr, items); + } + + /// Load a linear segment of items from memory, specialized for opaque input iterators (skips vectorization) + template + __device__ __forceinline__ void Load( + _InputIteratorT block_itr, ///< [in] The thread block's base input iterator for loading from + InputT (&items)[ITEMS_PER_THREAD]) ///< [out] Data to load + { + LoadDirectBlocked(linear_tid, block_itr, items); + } + + /// Load a linear segment of items from memory, guarded by range (skips vectorization) + template + __device__ __forceinline__ void Load( + InputIteratorT block_itr, ///< [in] The thread block's base input iterator for loading from + InputT (&items)[ITEMS_PER_THREAD], ///< [out] Data to load + int valid_items) ///< [in] Number of valid items to load + { + LoadDirectBlocked(linear_tid, block_itr, items, valid_items); + } + + /// Load a linear segment of items from memory, guarded by range, with a fall-back assignment of out-of-bound elements (skips vectorization) + template + __device__ __forceinline__ void Load( + InputIteratorT block_itr, ///< [in] The thread block's base input iterator for loading from + InputT (&items)[ITEMS_PER_THREAD], ///< [out] Data to load + int valid_items, ///< [in] Number of valid items to load + DefaultT oob_default) ///< [in] Default value to assign out-of-bound items + { + LoadDirectBlocked(linear_tid, block_itr, items, valid_items, oob_default); + } + + }; + + + /** + * BLOCK_LOAD_TRANSPOSE specialization of load helper + */ + template + struct LoadInternal + { + // BlockExchange utility type for keys + typedef BlockExchange BlockExchange; + + /// Shared memory storage layout type + struct _TempStorage : BlockExchange::TempStorage + {}; + + /// Alias wrapper allowing storage to be unioned + struct TempStorage : Uninitialized<_TempStorage> {}; + + /// Thread reference to shared storage + _TempStorage &temp_storage; + + /// Linear thread-id + int linear_tid; + + /// Constructor + __device__ __forceinline__ LoadInternal( + TempStorage &temp_storage, + int linear_tid) + : + temp_storage(temp_storage.Alias()), + linear_tid(linear_tid) + {} + + /// Load a linear segment of items from memory + template + __device__ __forceinline__ void Load( + InputIteratorT block_itr, ///< [in] The thread block's base input iterator for loading from + InputT (&items)[ITEMS_PER_THREAD]) ///< [out] Data to load{ + { + LoadDirectStriped(linear_tid, block_itr, items); + BlockExchange(temp_storage).StripedToBlocked(items, items); + } + + /// Load a linear segment of items from memory, guarded by range + template + __device__ __forceinline__ void Load( + InputIteratorT block_itr, ///< [in] The thread block's base input iterator for loading from + InputT (&items)[ITEMS_PER_THREAD], ///< [out] Data to load + int valid_items) ///< [in] Number of valid items to load + { + LoadDirectStriped(linear_tid, block_itr, items, valid_items); + BlockExchange(temp_storage).StripedToBlocked(items, items); + } + + /// Load a linear segment of items from memory, guarded by range, with a fall-back assignment of out-of-bound elements + template + __device__ __forceinline__ void Load( + InputIteratorT block_itr, ///< [in] The thread block's base input iterator for loading from + InputT (&items)[ITEMS_PER_THREAD], ///< [out] Data to load + int valid_items, ///< [in] Number of valid items to load + DefaultT oob_default) ///< [in] Default value to assign out-of-bound items + { + LoadDirectStriped(linear_tid, block_itr, items, valid_items, oob_default); + BlockExchange(temp_storage).StripedToBlocked(items, items); + } + + }; + + + /** + * BLOCK_LOAD_WARP_TRANSPOSE specialization of load helper + */ + template + struct LoadInternal + { + enum + { + WARP_THREADS = CUB_WARP_THREADS(0) + }; + + // Assert BLOCK_THREADS must be a multiple of WARP_THREADS + CUB_STATIC_ASSERT((int(BLOCK_THREADS) % int(WARP_THREADS) == 0), "BLOCK_THREADS must be a multiple of WARP_THREADS"); + + // BlockExchange utility type for keys + typedef BlockExchange BlockExchange; + + /// Shared memory storage layout type + struct _TempStorage : BlockExchange::TempStorage + {}; + + /// Alias wrapper allowing storage to be unioned + struct TempStorage : Uninitialized<_TempStorage> {}; + + /// Thread reference to shared storage + _TempStorage &temp_storage; + + /// Linear thread-id + int linear_tid; + + /// Constructor + __device__ __forceinline__ LoadInternal( + TempStorage &temp_storage, + int linear_tid) + : + temp_storage(temp_storage.Alias()), + linear_tid(linear_tid) + {} + + /// Load a linear segment of items from memory + template + __device__ __forceinline__ void Load( + InputIteratorT block_itr, ///< [in] The thread block's base input iterator for loading from + InputT (&items)[ITEMS_PER_THREAD]) ///< [out] Data to load{ + { + LoadDirectWarpStriped(linear_tid, block_itr, items); + BlockExchange(temp_storage).WarpStripedToBlocked(items, items); + } + + /// Load a linear segment of items from memory, guarded by range + template + __device__ __forceinline__ void Load( + InputIteratorT block_itr, ///< [in] The thread block's base input iterator for loading from + InputT (&items)[ITEMS_PER_THREAD], ///< [out] Data to load + int valid_items) ///< [in] Number of valid items to load + { + LoadDirectWarpStriped(linear_tid, block_itr, items, valid_items); + BlockExchange(temp_storage).WarpStripedToBlocked(items, items); + } + + + /// Load a linear segment of items from memory, guarded by range, with a fall-back assignment of out-of-bound elements + template + __device__ __forceinline__ void Load( + InputIteratorT block_itr, ///< [in] The thread block's base input iterator for loading from + InputT (&items)[ITEMS_PER_THREAD], ///< [out] Data to load + int valid_items, ///< [in] Number of valid items to load + DefaultT oob_default) ///< [in] Default value to assign out-of-bound items + { + LoadDirectWarpStriped(linear_tid, block_itr, items, valid_items, oob_default); + BlockExchange(temp_storage).WarpStripedToBlocked(items, items); + } + }; + + + /** + * BLOCK_LOAD_WARP_TRANSPOSE_TIMESLICED specialization of load helper + */ + template + struct LoadInternal + { + enum + { + WARP_THREADS = CUB_WARP_THREADS(0) + }; + + // Assert BLOCK_THREADS must be a multiple of WARP_THREADS + CUB_STATIC_ASSERT((int(BLOCK_THREADS) % int(WARP_THREADS) == 0), "BLOCK_THREADS must be a multiple of WARP_THREADS"); + + // BlockExchange utility type for keys + typedef BlockExchange BlockExchange; + + /// Shared memory storage layout type + struct _TempStorage : BlockExchange::TempStorage + {}; + + /// Alias wrapper allowing storage to be unioned + struct TempStorage : Uninitialized<_TempStorage> {}; + + /// Thread reference to shared storage + _TempStorage &temp_storage; + + /// Linear thread-id + int linear_tid; + + /// Constructor + __device__ __forceinline__ LoadInternal( + TempStorage &temp_storage, + int linear_tid) + : + temp_storage(temp_storage.Alias()), + linear_tid(linear_tid) + {} + + /// Load a linear segment of items from memory + template + __device__ __forceinline__ void Load( + InputIteratorT block_itr, ///< [in] The thread block's base input iterator for loading from + InputT (&items)[ITEMS_PER_THREAD]) ///< [out] Data to load{ + { + LoadDirectWarpStriped(linear_tid, block_itr, items); + BlockExchange(temp_storage).WarpStripedToBlocked(items, items); + } + + /// Load a linear segment of items from memory, guarded by range + template + __device__ __forceinline__ void Load( + InputIteratorT block_itr, ///< [in] The thread block's base input iterator for loading from + InputT (&items)[ITEMS_PER_THREAD], ///< [out] Data to load + int valid_items) ///< [in] Number of valid items to load + { + LoadDirectWarpStriped(linear_tid, block_itr, items, valid_items); + BlockExchange(temp_storage).WarpStripedToBlocked(items, items); + } + + + /// Load a linear segment of items from memory, guarded by range, with a fall-back assignment of out-of-bound elements + template + __device__ __forceinline__ void Load( + InputIteratorT block_itr, ///< [in] The thread block's base input iterator for loading from + InputT (&items)[ITEMS_PER_THREAD], ///< [out] Data to load + int valid_items, ///< [in] Number of valid items to load + DefaultT oob_default) ///< [in] Default value to assign out-of-bound items + { + LoadDirectWarpStriped(linear_tid, block_itr, items, valid_items, oob_default); + BlockExchange(temp_storage).WarpStripedToBlocked(items, items); + } + }; + + + /****************************************************************************** + * Type definitions + ******************************************************************************/ + + /// Internal load implementation to use + typedef LoadInternal InternalLoad; + + + /// Shared memory storage layout type + typedef typename InternalLoad::TempStorage _TempStorage; + + + /****************************************************************************** + * Utility methods + ******************************************************************************/ + + /// Internal storage allocator + __device__ __forceinline__ _TempStorage& PrivateStorage() + { + __shared__ _TempStorage private_storage; + return private_storage; + } + + + /****************************************************************************** + * Thread fields + ******************************************************************************/ + + /// Thread reference to shared storage + _TempStorage &temp_storage; + + /// Linear thread-id + int linear_tid; + +public: + + /// \smemstorage{BlockLoad} + struct TempStorage : Uninitialized<_TempStorage> {}; + + + /******************************************************************//** + * \name Collective constructors + *********************************************************************/ + //@{ + + /** + * \brief Collective constructor using a private static allocation of shared memory as temporary storage. + */ + __device__ __forceinline__ BlockLoad() + : + temp_storage(PrivateStorage()), + linear_tid(RowMajorTid(BLOCK_DIM_X, BLOCK_DIM_Y, BLOCK_DIM_Z)) + {} + + + /** + * \brief Collective constructor using the specified memory allocation as temporary storage. + */ + __device__ __forceinline__ BlockLoad( + TempStorage &temp_storage) ///< [in] Reference to memory allocation having layout type TempStorage + : + temp_storage(temp_storage.Alias()), + linear_tid(RowMajorTid(BLOCK_DIM_X, BLOCK_DIM_Y, BLOCK_DIM_Z)) + {} + + + + + //@} end member group + /******************************************************************//** + * \name Data movement + *********************************************************************/ + //@{ + + + /** + * \brief Load a linear segment of items from memory. + * + * \par + * - \blocked + * - \smemreuse + * + * \par Snippet + * The code snippet below illustrates the loading of a linear + * segment of 512 integers into a "blocked" arrangement across 128 threads where each + * thread owns 4 consecutive items. The load is specialized for \p BLOCK_LOAD_WARP_TRANSPOSE, + * meaning memory references are efficiently coalesced using a warp-striped access + * pattern (after which items are locally reordered among threads). + * \par + * \code + * #include // or equivalently + * + * __global__ void ExampleKernel(int *d_data, ...) + * { + * // Specialize BlockLoad for a 1D block of 128 threads owning 4 integer items each + * typedef cub::BlockLoad BlockLoad; + * + * // Allocate shared memory for BlockLoad + * __shared__ typename BlockLoad::TempStorage temp_storage; + * + * // Load a segment of consecutive items that are blocked across threads + * int thread_data[4]; + * BlockLoad(temp_storage).Load(d_data, thread_data); + * + * \endcode + * \par + * Suppose the input \p d_data is 0, 1, 2, 3, 4, 5, .... + * The set of \p thread_data across the block of threads in those threads will be + * { [0,1,2,3], [4,5,6,7], ..., [508,509,510,511] }. + * + */ + template + __device__ __forceinline__ void Load( + InputIteratorT block_itr, ///< [in] The thread block's base input iterator for loading from + InputT (&items)[ITEMS_PER_THREAD]) ///< [out] Data to load + { + InternalLoad(temp_storage, linear_tid).Load(block_itr, items); + } + + + /** + * \brief Load a linear segment of items from memory, guarded by range. + * + * \par + * - \blocked + * - \smemreuse + * + * \par Snippet + * The code snippet below illustrates the guarded loading of a linear + * segment of 512 integers into a "blocked" arrangement across 128 threads where each + * thread owns 4 consecutive items. The load is specialized for \p BLOCK_LOAD_WARP_TRANSPOSE, + * meaning memory references are efficiently coalesced using a warp-striped access + * pattern (after which items are locally reordered among threads). + * \par + * \code + * #include // or equivalently + * + * __global__ void ExampleKernel(int *d_data, int valid_items, ...) + * { + * // Specialize BlockLoad for a 1D block of 128 threads owning 4 integer items each + * typedef cub::BlockLoad BlockLoad; + * + * // Allocate shared memory for BlockLoad + * __shared__ typename BlockLoad::TempStorage temp_storage; + * + * // Load a segment of consecutive items that are blocked across threads + * int thread_data[4]; + * BlockLoad(temp_storage).Load(d_data, thread_data, valid_items); + * + * \endcode + * \par + * Suppose the input \p d_data is 0, 1, 2, 3, 4, 5, 6... and \p valid_items is \p 5. + * The set of \p thread_data across the block of threads in those threads will be + * { [0,1,2,3], [4,?,?,?], ..., [?,?,?,?] }, with only the first two threads + * being unmasked to load portions of valid data (and other items remaining unassigned). + * + */ + template + __device__ __forceinline__ void Load( + InputIteratorT block_itr, ///< [in] The thread block's base input iterator for loading from + InputT (&items)[ITEMS_PER_THREAD], ///< [out] Data to load + int valid_items) ///< [in] Number of valid items to load + { + InternalLoad(temp_storage, linear_tid).Load(block_itr, items, valid_items); + } + + + /** + * \brief Load a linear segment of items from memory, guarded by range, with a fall-back assignment of out-of-bound elements + * + * \par + * - \blocked + * - \smemreuse + * + * \par Snippet + * The code snippet below illustrates the guarded loading of a linear + * segment of 512 integers into a "blocked" arrangement across 128 threads where each + * thread owns 4 consecutive items. The load is specialized for \p BLOCK_LOAD_WARP_TRANSPOSE, + * meaning memory references are efficiently coalesced using a warp-striped access + * pattern (after which items are locally reordered among threads). + * \par + * \code + * #include // or equivalently + * + * __global__ void ExampleKernel(int *d_data, int valid_items, ...) + * { + * // Specialize BlockLoad for a 1D block of 128 threads owning 4 integer items each + * typedef cub::BlockLoad BlockLoad; + * + * // Allocate shared memory for BlockLoad + * __shared__ typename BlockLoad::TempStorage temp_storage; + * + * // Load a segment of consecutive items that are blocked across threads + * int thread_data[4]; + * BlockLoad(temp_storage).Load(d_data, thread_data, valid_items, -1); + * + * \endcode + * \par + * Suppose the input \p d_data is 0, 1, 2, 3, 4, 5, 6..., + * \p valid_items is \p 5, and the out-of-bounds default is \p -1. + * The set of \p thread_data across the block of threads in those threads will be + * { [0,1,2,3], [4,-1,-1,-1], ..., [-1,-1,-1,-1] }, with only the first two threads + * being unmasked to load portions of valid data (and other items are assigned \p -1) + * + */ + template + __device__ __forceinline__ void Load( + InputIteratorT block_itr, ///< [in] The thread block's base input iterator for loading from + InputT (&items)[ITEMS_PER_THREAD], ///< [out] Data to load + int valid_items, ///< [in] Number of valid items to load + DefaultT oob_default) ///< [in] Default value to assign out-of-bound items + { + InternalLoad(temp_storage, linear_tid).Load(block_itr, items, valid_items, oob_default); + } + + + //@} end member group + +}; + +template > +struct BlockLoadType +{ + using type = cub::BlockLoad; +}; + + +CUB_NAMESPACE_END + diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/block/block_radix_sort.cuh b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/block/block_radix_sort.cuh new file mode 100644 index 0000000000000000000000000000000000000000..e275d6f611e9f9e642e06c2af3cc45c41f6d24f3 --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/block/block_radix_sort.cuh @@ -0,0 +1,2111 @@ +/****************************************************************************** + * Copyright (c) 2011, Duane Merrill. All rights reserved. + * Copyright (c) 2011-2018, NVIDIA CORPORATION. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the NVIDIA CORPORATION nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ******************************************************************************/ + +/** + * \file + * The cub::BlockRadixSort class provides [collective](index.html#sec0) methods for radix sorting of items partitioned across a CUDA thread block. + */ + + +#pragma once + +#include "block_exchange.cuh" +#include "block_radix_rank.cuh" +#include "radix_rank_sort_operations.cuh" +#include "../config.cuh" +#include "../util_ptx.cuh" +#include "../util_type.cuh" + +CUB_NAMESPACE_BEGIN + +//! @rst +//! BlockRadixSort class provides :ref:`collective ` methods for sorting +//! items partitioned across a CUDA thread block using a radix sorting method. +//! +//! .. image:: ../img/sorting_logo.png +//! :align: center +//! +//! Overview +//! -------------------------------------------------- +//! +//! The `radix sorting method `_ arranges +//! items into ascending order. It relies upon a positional representation for +//! keys, i.e., each key is comprised of an ordered sequence of symbols (e.g., digits, +//! characters, etc.) specified from least-significant to most-significant. For a +//! given input sequence of keys and a set of rules specifying a total ordering +//! of the symbolic alphabet, the radix sorting method produces a lexicographic +//! ordering of those keys. +//! +//! @rowmajor +//! +//! Supported Types +//! -------------------------------------------------- +//! +//! BlockRadixSort can sort all of the built-in C++ numeric primitive types +//! (``unsigned char``, ``int``, ``double``, etc.) as well as CUDA's ``__half`` +//! half-precision floating-point type. User-defined types are supported as long +//! as decomposer object is provided. +//! +//! Floating-Point Special Cases +//! -------------------------------------------------- +//! +//! - Positive and negative zeros are considered equivalent, and will be treated +//! as such in the output. +//! - No special handling is implemented for NaN values; these are sorted +//! according to their bit representations after any transformations. +//! +//! Bitwise Key Transformations +//! -------------------------------------------------- +//! +//! Although the direct radix sorting method can only be applied to unsigned +//! integral types, BlockRadixSort is able to sort signed and floating-point +//! types via simple bit-wise transformations that ensure lexicographic key +//! ordering. +//! +//! These transformations must be considered when restricting the +//! ``[begin_bit, end_bit)`` range, as the bitwise transformations will occur +//! before the bit-range truncation. +//! +//! Any transformations applied to the keys prior to sorting are reversed +//! while writing to the final output buffer. +//! +//! Type Specific Bitwise Transformations +//! -------------------------------------------------- +//! +//! To convert the input values into a radix-sortable bitwise representation, +//! the following transformations take place prior to sorting: +//! +//! * For unsigned integral values, the keys are used directly. +//! * For signed integral values, the sign bit is inverted. +//! * For positive floating point values, the sign bit is inverted. +//! * For negative floating point values, the full key is inverted. +//! +//! No Descending Sort Transformations +//! -------------------------------------------------- +//! +//! Unlike ``DeviceRadixSort``, ``BlockRadixSort`` does not invert the input key bits +//! when performing a descending sort. Instead, it has special logic to reverse +//! the order of the keys while sorting. +//! +//! Stability +//! -------------------------------------------------- +//! +//! BlockRadixSort is stable. For floating-point types -0.0 and +0.0 +//! are considered equal and appear in the result in the same order as they +//! appear in the input. +//! +//! +//! Performance Considerations +//! -------------------------------------------------- +//! +//! * @granularity +//! +//! A Simple Example +//! -------------------------------------------------- +//! +//! @blockcollective{BlockRadixSort} +//! +//! The code snippet below illustrates a sort of 512 integer keys that +//! are partitioned in a [blocked arrangement](index.html#sec5sec3) across 128 threads +//! where each thread owns 4 consecutive items. +//! +//! .. code-block:: c++ +//! +//! #include // or equivalently +//! +//! __global__ void ExampleKernel(...) +//! { +//! // Specialize BlockRadixSort for a 1D block of 128 threads owning 4 integer items each +//! typedef cub::BlockRadixSort BlockRadixSort; +//! +//! // Allocate shared memory for BlockRadixSort +//! __shared__ typename BlockRadixSort::TempStorage temp_storage; +//! +//! // Obtain a segment of consecutive items that are blocked across threads +//! int thread_keys[4]; +//! ... +//! +//! // Collectively sort the keys +//! BlockRadixSort(temp_storage).Sort(thread_keys); +//! +//! ... +//! +//! Suppose the set of input ``thread_keys`` across the block of threads is +//! ``{ [0,511,1,510], [2,509,3,508], [4,507,5,506], ..., [254,257,255,256] }``. +//! The corresponding output ``thread_keys`` in those threads will be +//! ``{ [0,1,2,3], [4,5,6,7], [8,9,10,11], ..., [508,509,510,511] }``. +//! +//! Re-using dynamically allocating shared memory +//! -------------------------------------------------- +//! +//! The following example under the examples/block folder illustrates usage of +//! dynamically shared memory with BlockReduce and how to re-purpose +//! the same memory region: +//! example_block_reduce_dyn_smem.cu +//! +//! This example can be easily adapted to the storage required by BlockRadixSort. +//! @endrst +//! +//! @ingroup BlockModule +//! +//! @tparam KeyT +//! KeyT type +//! +//! @tparam BLOCK_DIM_X +//! The thread block length in threads along the X dimension +//! +//! @tparam ITEMS_PER_THREAD +//! The number of items per thread +//! +//! @tparam ValueT +//! **[optional]** ValueT type (default: cub::NullType, which indicates a keys-only sort) +//! +//! @tparam RADIX_BITS +//! **[optional]** The number of radix bits per digit place (default: 4 bits) +//! +//! @tparam MEMOIZE_OUTER_SCAN +//! **[optional]** Whether or not to buffer outer raking scan partials to incur fewer shared memory +//! reads at the expense of higher register pressure (default: true for architectures SM35 and +//! newer, false otherwise). +//! +//! @tparam INNER_SCAN_ALGORITHM +//! **[optional]** The cub::BlockScanAlgorithm algorithm to use +//! (default: cub::BLOCK_SCAN_WARP_SCANS) +//! +//! @tparam SMEM_CONFIG +//! **[optional]*8 Shared memory bank mode (default: `cudaSharedMemBankSizeFourByte`) +//! +//! @tparam BLOCK_DIM_Y +//! **[optional]** The thread block length in threads along the Y dimension (default: 1) +//! +//! @tparam BLOCK_DIM_Z +//! **[optional]** The thread block length in threads along the Z dimension (default: 1) +//! +//! @tparam LEGACY_PTX_ARCH +//! **[optional]** Unused +template < + typename KeyT, + int BLOCK_DIM_X, + int ITEMS_PER_THREAD, + typename ValueT = NullType, + int RADIX_BITS = 4, + bool MEMOIZE_OUTER_SCAN = true, + BlockScanAlgorithm INNER_SCAN_ALGORITHM = BLOCK_SCAN_WARP_SCANS, + cudaSharedMemConfig SMEM_CONFIG = cudaSharedMemBankSizeFourByte, + int BLOCK_DIM_Y = 1, + int BLOCK_DIM_Z = 1, + int LEGACY_PTX_ARCH = 0> +class BlockRadixSort +{ +private: + + /****************************************************************************** + * Constants and type definitions + ******************************************************************************/ + + enum + { + // The thread block size in threads + BLOCK_THREADS = BLOCK_DIM_X * BLOCK_DIM_Y * BLOCK_DIM_Z, + + // Whether or not there are values to be trucked along with keys + KEYS_ONLY = std::is_same::value, + }; + + // KeyT traits and unsigned bits type + using traits = detail::radix::traits_t; + using bit_ordered_type = typename traits::bit_ordered_type; + using bit_ordered_conversion = typename traits::bit_ordered_conversion_policy; + + /// Ascending BlockRadixRank utility type + typedef BlockRadixRank< + BLOCK_DIM_X, + RADIX_BITS, + false, + MEMOIZE_OUTER_SCAN, + INNER_SCAN_ALGORITHM, + SMEM_CONFIG, + BLOCK_DIM_Y, + BLOCK_DIM_Z> + AscendingBlockRadixRank; + + /// Descending BlockRadixRank utility type + typedef BlockRadixRank< + BLOCK_DIM_X, + RADIX_BITS, + true, + MEMOIZE_OUTER_SCAN, + INNER_SCAN_ALGORITHM, + SMEM_CONFIG, + BLOCK_DIM_Y, + BLOCK_DIM_Z> + DescendingBlockRadixRank; + + /// Digit extractor type + using fundamental_digit_extractor_t = BFEDigitExtractor; + + /// BlockExchange utility type for keys + typedef BlockExchange BlockExchangeKeys; + + /// BlockExchange utility type for values + typedef BlockExchange BlockExchangeValues; + + /// Shared memory storage layout type + union _TempStorage + { + typename AscendingBlockRadixRank::TempStorage asending_ranking_storage; + typename DescendingBlockRadixRank::TempStorage descending_ranking_storage; + typename BlockExchangeKeys::TempStorage exchange_keys; + typename BlockExchangeValues::TempStorage exchange_values; + }; + + + /****************************************************************************** + * Thread fields + ******************************************************************************/ + + /// Shared storage reference + _TempStorage &temp_storage; + + /// Linear thread-id + unsigned int linear_tid; + + /****************************************************************************** + * Utility methods + ******************************************************************************/ + + /// Internal storage allocator + __device__ __forceinline__ _TempStorage& PrivateStorage() + { + __shared__ _TempStorage private_storage; + return private_storage; + } + + /// Rank keys (specialized for ascending sort) + template + __device__ __forceinline__ void RankKeys( + bit_ordered_type (&unsigned_keys)[ITEMS_PER_THREAD], + int (&ranks)[ITEMS_PER_THREAD], + DigitExtractorT digit_extractor, + Int2Type /*is_descending*/) + { + AscendingBlockRadixRank(temp_storage.asending_ranking_storage).RankKeys( + unsigned_keys, + ranks, + digit_extractor); + } + + /// Rank keys (specialized for descending sort) + template + __device__ __forceinline__ void RankKeys( + bit_ordered_type (&unsigned_keys)[ITEMS_PER_THREAD], + int (&ranks)[ITEMS_PER_THREAD], + DigitExtractorT digit_extractor, + Int2Type /*is_descending*/) + { + DescendingBlockRadixRank(temp_storage.descending_ranking_storage).RankKeys( + unsigned_keys, + ranks, + digit_extractor); + } + + /// ExchangeValues (specialized for key-value sort, to-blocked arrangement) + __device__ __forceinline__ void ExchangeValues( + ValueT (&values)[ITEMS_PER_THREAD], + int (&ranks)[ITEMS_PER_THREAD], + Int2Type /*is_keys_only*/, + Int2Type /*is_blocked*/) + { + CTA_SYNC(); + + // Exchange values through shared memory in blocked arrangement + BlockExchangeValues(temp_storage.exchange_values).ScatterToBlocked(values, ranks); + } + + /// ExchangeValues (specialized for key-value sort, to-striped arrangement) + __device__ __forceinline__ void ExchangeValues( + ValueT (&values)[ITEMS_PER_THREAD], + int (&ranks)[ITEMS_PER_THREAD], + Int2Type /*is_keys_only*/, + Int2Type /*is_blocked*/) + { + CTA_SYNC(); + + // Exchange values through shared memory in blocked arrangement + BlockExchangeValues(temp_storage.exchange_values).ScatterToStriped(values, ranks); + } + + /// ExchangeValues (specialized for keys-only sort) + template + __device__ __forceinline__ void ExchangeValues( + ValueT (&/*values*/)[ITEMS_PER_THREAD], + int (&/*ranks*/)[ITEMS_PER_THREAD], + Int2Type /*is_keys_only*/, + Int2Type /*is_blocked*/) + {} + + /// Sort blocked arrangement + template + __device__ __forceinline__ void SortBlocked( + KeyT (&keys)[ITEMS_PER_THREAD], ///< Keys to sort + ValueT (&values)[ITEMS_PER_THREAD], ///< Values to sort + int begin_bit, ///< The beginning (least-significant) bit index needed for key comparison + int end_bit, ///< The past-the-end (most-significant) bit index needed for key comparison + Int2Type is_descending, ///< Tag whether is a descending-order sort + Int2Type is_keys_only, ///< Tag whether is keys-only sort + DecomposerT decomposer = {}) + { + bit_ordered_type (&unsigned_keys)[ITEMS_PER_THREAD] = + reinterpret_cast(keys); + + #pragma unroll + for (int KEY = 0; KEY < ITEMS_PER_THREAD; KEY++) + { + unsigned_keys[KEY] = bit_ordered_conversion::to_bit_ordered(decomposer, unsigned_keys[KEY]); + } + + // Radix sorting passes + while (true) + { + int pass_bits = CUB_MIN(RADIX_BITS, end_bit - begin_bit); + auto digit_extractor = traits::template digit_extractor(begin_bit, pass_bits, decomposer); + + // Rank the blocked keys + int ranks[ITEMS_PER_THREAD]; + RankKeys(unsigned_keys, ranks, digit_extractor, is_descending); + begin_bit += RADIX_BITS; + + CTA_SYNC(); + + // Exchange keys through shared memory in blocked arrangement + BlockExchangeKeys(temp_storage.exchange_keys).ScatterToBlocked(keys, ranks); + + // Exchange values through shared memory in blocked arrangement + ExchangeValues(values, ranks, is_keys_only, Int2Type()); + + // Quit if done + if (begin_bit >= end_bit) break; + + CTA_SYNC(); + } + + // Untwiddle bits if necessary + #pragma unroll + for (int KEY = 0; KEY < ITEMS_PER_THREAD; KEY++) + { + unsigned_keys[KEY] = bit_ordered_conversion::from_bit_ordered(decomposer, unsigned_keys[KEY]); + } + } + +public: + +#ifndef DOXYGEN_SHOULD_SKIP_THIS // Do not document + + /// Sort blocked -> striped arrangement + template + __device__ __forceinline__ void SortBlockedToStriped( + KeyT (&keys)[ITEMS_PER_THREAD], ///< Keys to sort + ValueT (&values)[ITEMS_PER_THREAD], ///< Values to sort + int begin_bit, ///< The beginning (least-significant) bit index needed for key comparison + int end_bit, ///< The past-the-end (most-significant) bit index needed for key comparison + Int2Type is_descending, ///< Tag whether is a descending-order sort + Int2Type is_keys_only, ///< Tag whether is keys-only sort + DecomposerT decomposer = {}) + { + bit_ordered_type (&unsigned_keys)[ITEMS_PER_THREAD] = + reinterpret_cast(keys); + + #pragma unroll + for (int KEY = 0; KEY < ITEMS_PER_THREAD; KEY++) + { + unsigned_keys[KEY] = bit_ordered_conversion::to_bit_ordered(decomposer, unsigned_keys[KEY]); + } + + // Radix sorting passes + while (true) + { + int pass_bits = CUB_MIN(RADIX_BITS, end_bit - begin_bit); + auto digit_extractor = traits::template digit_extractor(begin_bit, pass_bits, decomposer); + + // Rank the blocked keys + int ranks[ITEMS_PER_THREAD]; + RankKeys(unsigned_keys, ranks, digit_extractor, is_descending); + begin_bit += RADIX_BITS; + + CTA_SYNC(); + + // Check if this is the last pass + if (begin_bit >= end_bit) + { + // Last pass exchanges keys through shared memory in striped arrangement + BlockExchangeKeys(temp_storage.exchange_keys).ScatterToStriped(keys, ranks); + + // Last pass exchanges through shared memory in striped arrangement + ExchangeValues(values, ranks, is_keys_only, Int2Type()); + + // Quit + break; + } + + // Exchange keys through shared memory in blocked arrangement + BlockExchangeKeys(temp_storage.exchange_keys).ScatterToBlocked(keys, ranks); + + // Exchange values through shared memory in blocked arrangement + ExchangeValues(values, ranks, is_keys_only, Int2Type()); + + CTA_SYNC(); + } + + // Untwiddle bits if necessary + #pragma unroll + for (int KEY = 0; KEY < ITEMS_PER_THREAD; KEY++) + { + unsigned_keys[KEY] = bit_ordered_conversion::from_bit_ordered(decomposer, unsigned_keys[KEY]); + } + } + +#endif // DOXYGEN_SHOULD_SKIP_THIS + + /// \smemstorage{BlockRadixSort} + struct TempStorage : Uninitialized<_TempStorage> {}; + + + /******************************************************************//** + * \name Collective constructors + *********************************************************************/ + //@{ + + /** + * \brief Collective constructor using a private static allocation of shared memory as temporary storage. + */ + __device__ __forceinline__ BlockRadixSort() + : + temp_storage(PrivateStorage()), + linear_tid(RowMajorTid(BLOCK_DIM_X, BLOCK_DIM_Y, BLOCK_DIM_Z)) + {} + + + /** + * \brief Collective constructor using the specified memory allocation as temporary storage. + */ + __device__ __forceinline__ BlockRadixSort( + TempStorage &temp_storage) ///< [in] Reference to memory allocation having layout type TempStorage + : + temp_storage(temp_storage.Alias()), + linear_tid(RowMajorTid(BLOCK_DIM_X, BLOCK_DIM_Y, BLOCK_DIM_Z)) + {} + + + //@} end member group + /******************************************************************//** + * \name Sorting (blocked arrangements) + *********************************************************************/ + //@{ + + /** + * \brief Performs an ascending block-wide radix sort over a [blocked arrangement](index.html#sec5sec3) of keys. + * + * \par + * - \granularity + * - \smemreuse + * + * \par Snippet + * The code snippet below illustrates a sort of 512 integer keys that + * are partitioned in a [blocked arrangement](index.html#sec5sec3) across 128 threads + * where each thread owns 4 consecutive keys. + * \par + * \code + * #include // or equivalently + * + * __global__ void ExampleKernel(...) + * { + * // Specialize BlockRadixSort for a 1D block of 128 threads owning 4 integer keys each + * typedef cub::BlockRadixSort BlockRadixSort; + * + * // Allocate shared memory for BlockRadixSort + * __shared__ typename BlockRadixSort::TempStorage temp_storage; + * + * // Obtain a segment of consecutive items that are blocked across threads + * int thread_keys[4]; + * ... + * + * // Collectively sort the keys + * BlockRadixSort(temp_storage).Sort(thread_keys); + * + * \endcode + * \par + * Suppose the set of input \p thread_keys across the block of threads is + * { [0,511,1,510], [2,509,3,508], [4,507,5,506], ..., [254,257,255,256] }. + * The corresponding output \p thread_keys in those threads will be + * { [0,1,2,3], [4,5,6,7], [8,9,10,11], ..., [508,509,510,511] }. + */ + __device__ __forceinline__ void Sort( + KeyT (&keys)[ITEMS_PER_THREAD], ///< [in-out] Keys to sort + int begin_bit = 0, ///< [in] [optional] The beginning (least-significant) bit index needed for key comparison + int end_bit = sizeof(KeyT) * 8) ///< [in] [optional] The past-the-end (most-significant) bit index needed for key comparison + { + NullType values[ITEMS_PER_THREAD]; + + SortBlocked(keys, values, begin_bit, end_bit, Int2Type(), Int2Type()); + } + + //! @rst + //! Performs an ascending block-wide radix sort over a + //! :ref:`blocked arrangement ` of keys. + //! + //! * @granularity + //! * @smemreuse + //! + //! Snippet + //! ========================================================================== + //! + //! Let's consider a user-defined ``custom_t`` type below. To sort an array of + //! ``custom_t`` objects, we have to tell CUB about relevant members of the + //! ``custom_t`` type. We do this by providing a decomposer that returns a + //! tuple of references to relevant members of the key. + //! + //! .. literalinclude:: ../../test/catch2_test_block_radix_sort_custom.cu + //! :language: c++ + //! :dedent: + //! :start-after: example-begin custom-type + //! :end-before: example-end custom-type + //! + //! The code snippet below illustrates a sort of 2 keys that + //! are partitioned in a :ref:`blocked arrangement ` across 2 threads + //! where each thread owns 1 key. + //! + //! .. literalinclude:: ../../test/catch2_test_block_radix_sort_custom.cu + //! :language: c++ + //! :dedent: + //! :start-after: example-begin keys-bits + //! :end-before: example-end keys-bits + //! + //! @endrst + //! + //! @tparam DecomposerT + //! **[inferred]** Type of a callable object responsible for decomposing a + //! ``KeyT`` into a tuple of references to its constituent arithmetic types: + //! ``::cuda::std::tuple operator()(KeyT &key)``. + //! The leftmost element of the tuple is considered the most significant. + //! The call operator must not modify members of the key. + //! + //! @param[in,out] keys + //! Keys to sort + //! + //! @param decomposer + //! Callable object responsible for decomposing a ``KeyT`` into a tuple of + //! references to its constituent arithmetic types. The leftmost element of + //! the tuple is considered the most significant. The call operator must not + //! modify members of the key. + //! + //! @param[in] begin_bit + //! The least-significant bit index (inclusive) needed for + //! key comparison + //! + //! @param[in] end_bit + //! The most-significant bit index (exclusive) needed for key + //! comparison (e.g., `(sizeof(float) + sizeof(long long int)) * 8`) + template + __device__ __forceinline__ // + typename ::cuda::std::enable_if< // + !::cuda::std::is_convertible::value>::type + Sort(KeyT (&keys)[ITEMS_PER_THREAD], DecomposerT decomposer, int begin_bit, int end_bit) + { + NullType values[ITEMS_PER_THREAD]; + + SortBlocked(keys, + values, + begin_bit, + end_bit, + Int2Type(), + Int2Type(), + decomposer); + } + + //! @rst + //! Performs an ascending block-wide radix sort over a + //! :ref:`blocked arrangement ` of keys. + //! + //! * @granularity + //! * @smemreuse + //! + //! Snippet + //! ========================================================================== + //! + //! Let's consider a user-defined ``custom_t`` type below. To sort an array of + //! ``custom_t`` objects, we have to tell CUB about relevant members of the + //! ``custom_t`` type. We do this by providing a decomposer that returns a + //! tuple of references to relevant members of the key. + //! + //! .. literalinclude:: ../../test/catch2_test_block_radix_sort_custom.cu + //! :language: c++ + //! :dedent: + //! :start-after: example-begin custom-type + //! :end-before: example-end custom-type + //! + //! The code snippet below illustrates a sort of 6 keys that + //! are partitioned in a :ref:`blocked arrangement ` across 2 threads + //! where each thread owns 3 consecutive keys. + //! + //! .. literalinclude:: ../../test/catch2_test_block_radix_sort_custom.cu + //! :language: c++ + //! :dedent: + //! :start-after: example-begin keys + //! :end-before: example-end keys + //! + //! @endrst + //! + //! @tparam DecomposerT + //! **[inferred]** Type of a callable object responsible for decomposing a + //! ``KeyT`` into a tuple of references to its constituent arithmetic types: + //! ``::cuda::std::tuple operator()(KeyT &key)``. + //! The leftmost element of the tuple is considered the most significant. + //! The call operator must not modify members of the key. + //! + //! @param[in,out] keys + //! Keys to sort + //! + //! @param decomposer + //! Callable object responsible for decomposing a ``KeyT`` into a tuple of + //! references to its constituent arithmetic types. The leftmost element of + //! the tuple is considered the most significant. The call operator must not + //! modify members of the key. + template + __device__ __forceinline__ // + typename ::cuda::std::enable_if< // + !::cuda::std::is_convertible::value>::type + Sort(KeyT (&keys)[ITEMS_PER_THREAD], DecomposerT decomposer) + { + Sort(keys, decomposer, 0, detail::radix::traits_t::default_end_bit(decomposer)); + } + + /** + * \brief Performs an ascending block-wide radix sort across a [blocked arrangement](index.html#sec5sec3) of keys and values. + * + * \par + * - BlockRadixSort can only accommodate one associated tile of values. To "truck along" + * more than one tile of values, simply perform a key-value sort of the keys paired + * with a temporary value array that enumerates the key indices. The reordered indices + * can then be used as a gather-vector for exchanging other associated tile data through + * shared memory. + * - \granularity + * - \smemreuse + * + * \par Snippet + * The code snippet below illustrates a sort of 512 integer keys and values that + * are partitioned in a [blocked arrangement](index.html#sec5sec3) across 128 threads + * where each thread owns 4 consecutive pairs. + * \par + * \code + * #include // or equivalently + * + * __global__ void ExampleKernel(...) + * { + * // Specialize BlockRadixSort for a 1D block of 128 threads owning 4 integer keys and values each + * typedef cub::BlockRadixSort BlockRadixSort; + * + * // Allocate shared memory for BlockRadixSort + * __shared__ typename BlockRadixSort::TempStorage temp_storage; + * + * // Obtain a segment of consecutive items that are blocked across threads + * int thread_keys[4]; + * int thread_values[4]; + * ... + * + * // Collectively sort the keys and values among block threads + * BlockRadixSort(temp_storage).Sort(thread_keys, thread_values); + * + * \endcode + * \par + * Suppose the set of input \p thread_keys across the block of threads is + * { [0,511,1,510], [2,509,3,508], [4,507,5,506], ..., [254,257,255,256] }. The + * corresponding output \p thread_keys in those threads will be + * { [0,1,2,3], [4,5,6,7], [8,9,10,11], ..., [508,509,510,511] }. + * + */ + __device__ __forceinline__ void Sort( + KeyT (&keys)[ITEMS_PER_THREAD], ///< [in-out] Keys to sort + ValueT (&values)[ITEMS_PER_THREAD], ///< [in-out] Values to sort + int begin_bit = 0, ///< [in] [optional] The beginning (least-significant) bit index needed for key comparison + int end_bit = sizeof(KeyT) * 8) ///< [in] [optional] The past-the-end (most-significant) bit index needed for key comparison + { + SortBlocked(keys, values, begin_bit, end_bit, Int2Type(), Int2Type()); + } + + //! @rst + //! Performs an ascending block-wide radix sort over a + //! :ref:`blocked arrangement ` of keys and values. + //! + //! * BlockRadixSort can only accommodate one associated tile of values. To "truck along" + //! more than one tile of values, simply perform a key-value sort of the keys paired + //! with a temporary value array that enumerates the key indices. The reordered indices + //! can then be used as a gather-vector for exchanging other associated tile data through + //! shared memory. + //! * @granularity + //! * @smemreuse + //! + //! Snippet + //! ========================================================================== + //! + //! Let's consider a user-defined ``custom_t`` type below. To sort an array of + //! ``custom_t`` objects, we have to tell CUB about relevant members of the + //! ``custom_t`` type. We do this by providing a decomposer that returns a + //! tuple of references to relevant members of the key. + //! + //! .. literalinclude:: ../../test/catch2_test_block_radix_sort_custom.cu + //! :language: c++ + //! :dedent: + //! :start-after: example-begin custom-type + //! :end-before: example-end custom-type + //! + //! The code snippet below illustrates a sort of 2 keys and values that + //! are partitioned in a :ref:`blocked arrangement ` across 2 threads + //! where each thread owns 1 pair. + //! + //! .. literalinclude:: ../../test/catch2_test_block_radix_sort_custom.cu + //! :language: c++ + //! :dedent: + //! :start-after: example-begin pairs-bits + //! :end-before: example-end pairs-bits + //! + //! @endrst + //! + //! @tparam DecomposerT + //! **[inferred]** Type of a callable object responsible for decomposing a + //! ``KeyT`` into a tuple of references to its constituent arithmetic types: + //! ``::cuda::std::tuple operator()(KeyT &key)``. + //! The leftmost element of the tuple is considered the most significant. + //! The call operator must not modify members of the key. + //! + //! @param[in,out] keys + //! Keys to sort + //! + //! @param[in,out] values + //! Values to sort + //! + //! @param decomposer + //! Callable object responsible for decomposing a ``KeyT`` into a tuple of + //! references to its constituent arithmetic types. The leftmost element of + //! the tuple is considered the most significant. The call operator must not + //! modify members of the key. + //! + //! @param[in] begin_bit + //! The least-significant bit index (inclusive) needed for + //! key comparison + //! + //! @param[in] end_bit + //! The most-significant bit index (exclusive) needed for key + //! comparison (e.g., `(sizeof(float) + sizeof(long long int)) * 8`) + template + __device__ __forceinline__ // + typename ::cuda::std::enable_if< // + !::cuda::std::is_convertible::value>::type + Sort(KeyT (&keys)[ITEMS_PER_THREAD], + ValueT (&values)[ITEMS_PER_THREAD], + DecomposerT decomposer, + int begin_bit, + int end_bit) + { + SortBlocked(keys, + values, + begin_bit, + end_bit, + Int2Type(), + Int2Type(), + decomposer); + } + + //! @rst + //! Performs an ascending block-wide radix sort over a + //! :ref:`blocked arrangement ` of keys and values. + //! + //! * BlockRadixSort can only accommodate one associated tile of values. To "truck along" + //! more than one tile of values, simply perform a key-value sort of the keys paired + //! with a temporary value array that enumerates the key indices. The reordered indices + //! can then be used as a gather-vector for exchanging other associated tile data through + //! shared memory. + //! * @granularity + //! * @smemreuse + //! + //! Snippet + //! ========================================================================== + //! + //! Let's consider a user-defined ``custom_t`` type below. To sort an array of + //! ``custom_t`` objects, we have to tell CUB about relevant members of the + //! ``custom_t`` type. We do this by providing a decomposer that returns a + //! tuple of references to relevant members of the key. + //! + //! .. literalinclude:: ../../test/catch2_test_block_radix_sort_custom.cu + //! :language: c++ + //! :dedent: + //! :start-after: example-begin custom-type + //! :end-before: example-end custom-type + //! + //! The code snippet below illustrates a sort of 6 keys and values that + //! are partitioned in a :ref:`blocked arrangement ` across 2 threads + //! where each thread owns 3 consecutive pairs. + //! + //! .. literalinclude:: ../../test/catch2_test_block_radix_sort_custom.cu + //! :language: c++ + //! :dedent: + //! :start-after: example-begin pairs + //! :end-before: example-end pairs + //! + //! @endrst + //! + //! @tparam DecomposerT + //! **[inferred]** Type of a callable object responsible for decomposing a + //! ``KeyT`` into a tuple of references to its constituent arithmetic types: + //! ``::cuda::std::tuple operator()(KeyT &key)``. + //! The leftmost element of the tuple is considered the most significant. + //! The call operator must not modify members of the key. + //! + //! @param[in,out] keys + //! Keys to sort + //! + //! @param[in,out] values + //! Values to sort + //! + //! @param decomposer + //! Callable object responsible for decomposing a ``KeyT`` into a tuple of + //! references to its constituent arithmetic types. The leftmost element of + //! the tuple is considered the most significant. The call operator must not + //! modify members of the key. + template + __device__ __forceinline__ // + typename ::cuda::std::enable_if< // + !::cuda::std::is_convertible::value>::type + Sort(KeyT (&keys)[ITEMS_PER_THREAD], + ValueT (&values)[ITEMS_PER_THREAD], + DecomposerT decomposer) + { + Sort(keys, + values, + decomposer, + 0, + detail::radix::traits_t::default_end_bit(decomposer)); + } + + /** + * \brief Performs a descending block-wide radix sort over a [blocked arrangement](index.html#sec5sec3) of keys. + * + * \par + * - \granularity + * - \smemreuse + * + * \par Snippet + * The code snippet below illustrates a sort of 512 integer keys that + * are partitioned in a [blocked arrangement](index.html#sec5sec3) across 128 threads + * where each thread owns 4 consecutive keys. + * \par + * \code + * #include // or equivalently + * + * __global__ void ExampleKernel(...) + * { + * // Specialize BlockRadixSort for a 1D block of 128 threads owning 4 integer keys each + * typedef cub::BlockRadixSort BlockRadixSort; + * + * // Allocate shared memory for BlockRadixSort + * __shared__ typename BlockRadixSort::TempStorage temp_storage; + * + * // Obtain a segment of consecutive items that are blocked across threads + * int thread_keys[4]; + * ... + * + * // Collectively sort the keys + * BlockRadixSort(temp_storage).Sort(thread_keys); + * + * \endcode + * \par + * Suppose the set of input \p thread_keys across the block of threads is + * { [0,511,1,510], [2,509,3,508], [4,507,5,506], ..., [254,257,255,256] }. + * The corresponding output \p thread_keys in those threads will be + * { [511,510,509,508], [11,10,9,8], [7,6,5,4], ..., [3,2,1,0] }. + */ + __device__ __forceinline__ void SortDescending( + KeyT (&keys)[ITEMS_PER_THREAD], ///< [in-out] Keys to sort + int begin_bit = 0, ///< [in] [optional] The beginning (least-significant) bit index needed for key comparison + int end_bit = sizeof(KeyT) * 8) ///< [in] [optional] The past-the-end (most-significant) bit index needed for key comparison + { + NullType values[ITEMS_PER_THREAD]; + + SortBlocked(keys, values, begin_bit, end_bit, Int2Type(), Int2Type()); + } + + //! @rst + //! Performs a descending block-wide radix sort over a + //! :ref:`blocked arrangement ` of keys. + //! + //! * @granularity + //! * @smemreuse + //! + //! Snippet + //! ========================================================================== + //! + //! Let's consider a user-defined ``custom_t`` type below. To sort an array of + //! ``custom_t`` objects, we have to tell CUB about relevant members of the + //! ``custom_t`` type. We do this by providing a decomposer that returns a + //! tuple of references to relevant members of the key. + //! + //! .. literalinclude:: ../../test/catch2_test_block_radix_sort_custom.cu + //! :language: c++ + //! :dedent: + //! :start-after: example-begin custom-type + //! :end-before: example-end custom-type + //! + //! The code snippet below illustrates a sort of 2 keys that + //! are partitioned in a :ref:`blocked arrangement ` across 2 threads + //! where each thread owns 1 key. + //! + //! .. literalinclude:: ../../test/catch2_test_block_radix_sort_custom.cu + //! :language: c++ + //! :dedent: + //! :start-after: example-begin keys-descending-bits + //! :end-before: example-end keys-descending-bits + //! + //! @endrst + //! + //! @tparam DecomposerT + //! **[inferred]** Type of a callable object responsible for decomposing a + //! ``KeyT`` into a tuple of references to its constituent arithmetic types: + //! ``::cuda::std::tuple operator()(KeyT &key)``. + //! The leftmost element of the tuple is considered the most significant. + //! The call operator must not modify members of the key. + //! + //! @param[in,out] keys + //! Keys to sort + //! + //! @param decomposer + //! Callable object responsible for decomposing a ``KeyT`` into a tuple of + //! references to its constituent arithmetic types. The leftmost element of + //! the tuple is considered the most significant. The call operator must not + //! modify members of the key. + //! + //! @param[in] begin_bit + //! The least-significant bit index (inclusive) needed for + //! key comparison + //! + //! @param[in] end_bit + //! The most-significant bit index (exclusive) needed for key + //! comparison (e.g., `(sizeof(float) + sizeof(long long int)) * 8`) + template + __device__ __forceinline__ // + typename ::cuda::std::enable_if< // + !::cuda::std::is_convertible::value>::type + SortDescending(KeyT (&keys)[ITEMS_PER_THREAD], + DecomposerT decomposer, + int begin_bit, + int end_bit) + { + NullType values[ITEMS_PER_THREAD]; + + SortBlocked(keys, + values, + begin_bit, + end_bit, + Int2Type(), + Int2Type(), + decomposer); + } + + //! @rst + //! Performs a descending block-wide radix sort over a + //! :ref:`blocked arrangement ` of keys. + //! + //! * @granularity + //! * @smemreuse + //! + //! Snippet + //! ========================================================================== + //! + //! Let's consider a user-defined ``custom_t`` type below. To sort an array of + //! ``custom_t`` objects, we have to tell CUB about relevant members of the + //! ``custom_t`` type. We do this by providing a decomposer that returns a + //! tuple of references to relevant members of the key. + //! + //! .. literalinclude:: ../../test/catch2_test_block_radix_sort_custom.cu + //! :language: c++ + //! :dedent: + //! :start-after: example-begin custom-type + //! :end-before: example-end custom-type + //! + //! The code snippet below illustrates a sort of 6 keys that + //! are partitioned in a :ref:`blocked arrangement ` across 2 threads + //! where each thread owns 3 consecutive keys. + //! + //! .. literalinclude:: ../../test/catch2_test_block_radix_sort_custom.cu + //! :language: c++ + //! :dedent: + //! :start-after: example-begin keys-descending + //! :end-before: example-end keys-descending + //! + //! @endrst + //! + //! @tparam DecomposerT + //! **[inferred]** Type of a callable object responsible for decomposing a + //! ``KeyT`` into a tuple of references to its constituent arithmetic types: + //! ``::cuda::std::tuple operator()(KeyT &key)``. + //! The leftmost element of the tuple is considered the most significant. + //! The call operator must not modify members of the key. + //! + //! @param[in,out] keys + //! Keys to sort + //! + //! @param decomposer + //! Callable object responsible for decomposing a ``KeyT`` into a tuple of + //! references to its constituent arithmetic types. The leftmost element of + //! the tuple is considered the most significant. The call operator must not + //! modify members of the key. + template + __device__ __forceinline__ // + typename ::cuda::std::enable_if< // + !::cuda::std::is_convertible::value>::type + SortDescending(KeyT (&keys)[ITEMS_PER_THREAD], DecomposerT decomposer) + { + NullType values[ITEMS_PER_THREAD]; + + SortBlocked(keys, + values, + 0, + detail::radix::traits_t::default_end_bit(decomposer), + Int2Type(), + Int2Type(), + decomposer); + } + + /** + * \brief Performs a descending block-wide radix sort across a [blocked arrangement](index.html#sec5sec3) of keys and values. + * + * \par + * - BlockRadixSort can only accommodate one associated tile of values. To "truck along" + * more than one tile of values, simply perform a key-value sort of the keys paired + * with a temporary value array that enumerates the key indices. The reordered indices + * can then be used as a gather-vector for exchanging other associated tile data through + * shared memory. + * - \granularity + * - \smemreuse + * + * \par Snippet + * The code snippet below illustrates a sort of 512 integer keys and values that + * are partitioned in a [blocked arrangement](index.html#sec5sec3) across 128 threads + * where each thread owns 4 consecutive pairs. + * \par + * \code + * #include // or equivalently + * + * __global__ void ExampleKernel(...) + * { + * // Specialize BlockRadixSort for a 1D block of 128 threads owning 4 integer keys and values each + * typedef cub::BlockRadixSort BlockRadixSort; + * + * // Allocate shared memory for BlockRadixSort + * __shared__ typename BlockRadixSort::TempStorage temp_storage; + * + * // Obtain a segment of consecutive items that are blocked across threads + * int thread_keys[4]; + * int thread_values[4]; + * ... + * + * // Collectively sort the keys and values among block threads + * BlockRadixSort(temp_storage).Sort(thread_keys, thread_values); + * + * \endcode + * \par + * Suppose the set of input \p thread_keys across the block of threads is + * { [0,511,1,510], [2,509,3,508], [4,507,5,506], ..., [254,257,255,256] }. The + * corresponding output \p thread_keys in those threads will be + * { [511,510,509,508], [11,10,9,8], [7,6,5,4], ..., [3,2,1,0] }. + * + */ + __device__ __forceinline__ void SortDescending( + KeyT (&keys)[ITEMS_PER_THREAD], ///< [in-out] Keys to sort + ValueT (&values)[ITEMS_PER_THREAD], ///< [in-out] Values to sort + int begin_bit = 0, ///< [in] [optional] The beginning (least-significant) bit index needed for key comparison + int end_bit = sizeof(KeyT) * 8) ///< [in] [optional] The past-the-end (most-significant) bit index needed for key comparison + { + SortBlocked(keys, values, begin_bit, end_bit, Int2Type(), Int2Type()); + } + + //! @rst + //! Performs a descending block-wide radix sort over a + //! :ref:`blocked arrangement ` of keys and values. + //! + //! * BlockRadixSort can only accommodate one associated tile of values. To "truck along" + //! more than one tile of values, simply perform a key-value sort of the keys paired + //! with a temporary value array that enumerates the key indices. The reordered indices + //! can then be used as a gather-vector for exchanging other associated tile data through + //! shared memory. + //! * @granularity + //! * @smemreuse + //! + //! Snippet + //! ========================================================================== + //! + //! Let's consider a user-defined ``custom_t`` type below. To sort an array of + //! ``custom_t`` objects, we have to tell CUB about relevant members of the + //! ``custom_t`` type. We do this by providing a decomposer that returns a + //! tuple of references to relevant members of the key. + //! + //! .. literalinclude:: ../../test/catch2_test_block_radix_sort_custom.cu + //! :language: c++ + //! :dedent: + //! :start-after: example-begin custom-type + //! :end-before: example-end custom-type + //! + //! The code snippet below illustrates a sort of 2 pairs that + //! are partitioned in a :ref:`blocked arrangement ` across 2 threads + //! where each thread owns 1 pair. + //! + //! .. literalinclude:: ../../test/catch2_test_block_radix_sort_custom.cu + //! :language: c++ + //! :dedent: + //! :start-after: example-begin pairs-descending-bits + //! :end-before: example-end pairs-descending-bits + //! + //! @endrst + //! + //! @tparam DecomposerT + //! **[inferred]** Type of a callable object responsible for decomposing a + //! ``KeyT`` into a tuple of references to its constituent arithmetic types: + //! ``::cuda::std::tuple operator()(KeyT &key)``. + //! The leftmost element of the tuple is considered the most significant. + //! The call operator must not modify members of the key. + //! + //! @param[in,out] keys + //! Keys to sort + //! + //! @param[in,out] values + //! Values to sort + //! + //! @param decomposer + //! Callable object responsible for decomposing a ``KeyT`` into a tuple of + //! references to its constituent arithmetic types. The leftmost element of + //! the tuple is considered the most significant. The call operator must not + //! modify members of the key. + //! + //! @param[in] begin_bit + //! The least-significant bit index (inclusive) needed for + //! key comparison + //! + //! @param[in] end_bit + //! The most-significant bit index (exclusive) needed for key + //! comparison (e.g., `(sizeof(float) + sizeof(long long int)) * 8`) + template + __device__ __forceinline__ // + typename ::cuda::std::enable_if< // + !::cuda::std::is_convertible::value>::type + SortDescending(KeyT (&keys)[ITEMS_PER_THREAD], + ValueT (&values)[ITEMS_PER_THREAD], + DecomposerT decomposer, + int begin_bit, + int end_bit) + { + SortBlocked(keys, + values, + begin_bit, + end_bit, + Int2Type(), + Int2Type(), + decomposer); + } + + //! @rst + //! Performs a descending block-wide radix sort over a + //! :ref:`blocked arrangement ` of keys and values. + //! + //! * BlockRadixSort can only accommodate one associated tile of values. To "truck along" + //! more than one tile of values, simply perform a key-value sort of the keys paired + //! with a temporary value array that enumerates the key indices. The reordered indices + //! can then be used as a gather-vector for exchanging other associated tile data through + //! shared memory. + //! * @granularity + //! * @smemreuse + //! + //! Snippet + //! ========================================================================== + //! + //! Let's consider a user-defined ``custom_t`` type below. To sort an array of + //! ``custom_t`` objects, we have to tell CUB about relevant members of the + //! ``custom_t`` type. We do this by providing a decomposer that returns a + //! tuple of references to relevant members of the key. + //! + //! .. literalinclude:: ../../test/catch2_test_block_radix_sort_custom.cu + //! :language: c++ + //! :dedent: + //! :start-after: example-begin custom-type + //! :end-before: example-end custom-type + //! + //! The code snippet below illustrates a sort of 6 keys and values that + //! are partitioned in a :ref:`blocked arrangement ` across 2 threads + //! where each thread owns 3 consecutive pairs. + //! + //! .. literalinclude:: ../../test/catch2_test_block_radix_sort_custom.cu + //! :language: c++ + //! :dedent: + //! :start-after: example-begin pairs-descending + //! :end-before: example-end pairs-descending + //! + //! @endrst + //! + //! @tparam DecomposerT + //! **[inferred]** Type of a callable object responsible for decomposing a + //! ``KeyT`` into a tuple of references to its constituent arithmetic types: + //! ``::cuda::std::tuple operator()(KeyT &key)``. + //! The leftmost element of the tuple is considered the most significant. + //! The call operator must not modify members of the key. + //! + //! @param[in,out] keys + //! Keys to sort + //! + //! @param[in,out] values + //! Values to sort + //! + //! @param decomposer + //! Callable object responsible for decomposing a ``KeyT`` into a tuple of + //! references to its constituent arithmetic types. The leftmost element of + //! the tuple is considered the most significant. The call operator must not + //! modify members of the key. + template + __device__ __forceinline__ // + typename ::cuda::std::enable_if< // + !::cuda::std::is_convertible::value>::type + SortDescending(KeyT (&keys)[ITEMS_PER_THREAD], + ValueT (&values)[ITEMS_PER_THREAD], + DecomposerT decomposer) + { + SortBlocked(keys, + values, + 0, + detail::radix::traits_t::default_end_bit(decomposer), + Int2Type(), + Int2Type(), + decomposer); + } + + //@} end member group + /******************************************************************//** + * \name Sorting (blocked arrangement -> striped arrangement) + *********************************************************************/ + //@{ + + + /** + * \brief Performs an ascending radix sort across a [blocked arrangement](index.html#sec5sec3) of keys, leaving them in a [striped arrangement](index.html#sec5sec3). + * + * \par + * - \granularity + * - \smemreuse + * + * \par Snippet + * The code snippet below illustrates a sort of 512 integer keys that + * are initially partitioned in a [blocked arrangement](index.html#sec5sec3) across 128 threads + * where each thread owns 4 consecutive keys. The final partitioning is striped. + * \par + * \code + * #include // or equivalently + * + * __global__ void ExampleKernel(...) + * { + * // Specialize BlockRadixSort for a 1D block of 128 threads owning 4 integer keys each + * typedef cub::BlockRadixSort BlockRadixSort; + * + * // Allocate shared memory for BlockRadixSort + * __shared__ typename BlockRadixSort::TempStorage temp_storage; + * + * // Obtain a segment of consecutive items that are blocked across threads + * int thread_keys[4]; + * ... + * + * // Collectively sort the keys + * BlockRadixSort(temp_storage).SortBlockedToStriped(thread_keys); + * + * \endcode + * \par + * Suppose the set of input \p thread_keys across the block of threads is + * { [0,511,1,510], [2,509,3,508], [4,507,5,506], ..., [254,257,255,256] }. The + * corresponding output \p thread_keys in those threads will be + * { [0,128,256,384], [1,129,257,385], [2,130,258,386], ..., [127,255,383,511] }. + * + */ + __device__ __forceinline__ void SortBlockedToStriped( + KeyT (&keys)[ITEMS_PER_THREAD], ///< [in-out] Keys to sort + int begin_bit = 0, ///< [in] [optional] The beginning (least-significant) bit index needed for key comparison + int end_bit = sizeof(KeyT) * 8) ///< [in] [optional] The past-the-end (most-significant) bit index needed for key comparison + { + NullType values[ITEMS_PER_THREAD]; + + SortBlockedToStriped(keys, values, begin_bit, end_bit, Int2Type(), Int2Type()); + } + + //! @rst + //! Performs an ascending block-wide radix sort over a + //! :ref:`blocked arrangement ` of keys, leaving them in a + //! :ref:`striped arrangement `. + //! + //! * @granularity + //! * @smemreuse + //! + //! Snippet + //! ========================================================================== + //! + //! Let's consider a user-defined ``custom_t`` type below. To sort an array of + //! ``custom_t`` objects, we have to tell CUB about relevant members of the + //! ``custom_t`` type. We do this by providing a decomposer that returns a + //! tuple of references to relevant members of the key. + //! + //! .. literalinclude:: ../../test/catch2_test_block_radix_sort_custom.cu + //! :language: c++ + //! :dedent: + //! :start-after: example-begin custom-type + //! :end-before: example-end custom-type + //! + //! The code snippet below illustrates a sort of 4 keys that + //! are partitioned in a :ref:`blocked arrangement ` across 2 threads + //! where each thread owns 2 consecutive keys. The final partitioning is striped. + //! + //! .. literalinclude:: ../../test/catch2_test_block_radix_sort_custom.cu + //! :language: c++ + //! :dedent: + //! :start-after: example-begin keys-striped-bits + //! :end-before: example-end keys-striped-bits + //! + //! @endrst + //! + //! @tparam DecomposerT + //! **[inferred]** Type of a callable object responsible for decomposing a + //! ``KeyT`` into a tuple of references to its constituent arithmetic types: + //! ``::cuda::std::tuple operator()(KeyT &key)``. + //! The leftmost element of the tuple is considered the most significant. + //! The call operator must not modify members of the key. + //! + //! @param[in,out] keys + //! Keys to sort + //! + //! @param decomposer + //! Callable object responsible for decomposing a ``KeyT`` into a tuple of + //! references to its constituent arithmetic types. The leftmost element of + //! the tuple is considered the most significant. The call operator must not + //! modify members of the key. + //! + //! @param[in] begin_bit + //! The least-significant bit index (inclusive) needed for + //! key comparison + //! + //! @param[in] end_bit + //! The most-significant bit index (exclusive) needed for key + //! comparison (e.g., `(sizeof(float) + sizeof(long long int)) * 8`) + template + __device__ __forceinline__ // + typename ::cuda::std::enable_if< // + !::cuda::std::is_convertible::value>::type + SortBlockedToStriped(KeyT (&keys)[ITEMS_PER_THREAD], + DecomposerT decomposer, + int begin_bit, + int end_bit) + { + NullType values[ITEMS_PER_THREAD]; + + SortBlockedToStriped(keys, + values, + begin_bit, + end_bit, + Int2Type(), + Int2Type(), + decomposer); + } + + //! @rst + //! Performs an ascending block-wide radix sort over a + //! :ref:`blocked arrangement ` of keys, leaving them in a + //! :ref:`striped arrangement `. + //! + //! * @granularity + //! * @smemreuse + //! + //! Snippet + //! ========================================================================== + //! + //! Let's consider a user-defined ``custom_t`` type below. To sort an array of + //! ``custom_t`` objects, we have to tell CUB about relevant members of the + //! ``custom_t`` type. We do this by providing a decomposer that returns a + //! tuple of references to relevant members of the key. + //! + //! .. literalinclude:: ../../test/catch2_test_block_radix_sort_custom.cu + //! :language: c++ + //! :dedent: + //! :start-after: example-begin custom-type + //! :end-before: example-end custom-type + //! + //! The code snippet below illustrates a sort of 6 keys that + //! are partitioned in a :ref:`blocked arrangement ` across 2 threads + //! where each thread owns 3 consecutive keys. The final partitioning is striped. + //! + //! .. literalinclude:: ../../test/catch2_test_block_radix_sort_custom.cu + //! :language: c++ + //! :dedent: + //! :start-after: example-begin keys-striped + //! :end-before: example-end keys-striped + //! + //! @endrst + //! + //! @tparam DecomposerT + //! **[inferred]** Type of a callable object responsible for decomposing a + //! ``KeyT`` into a tuple of references to its constituent arithmetic types: + //! ``::cuda::std::tuple operator()(KeyT &key)``. + //! The leftmost element of the tuple is considered the most significant. + //! The call operator must not modify members of the key. + //! + //! @param[in,out] keys + //! Keys to sort + //! + //! @param decomposer + //! Callable object responsible for decomposing a ``KeyT`` into a tuple of + //! references to its constituent arithmetic types. The leftmost element of + //! the tuple is considered the most significant. The call operator must not + //! modify members of the key. + template + __device__ __forceinline__ // + typename ::cuda::std::enable_if< // + !::cuda::std::is_convertible::value>::type + SortBlockedToStriped(KeyT (&keys)[ITEMS_PER_THREAD], DecomposerT decomposer) + { + NullType values[ITEMS_PER_THREAD]; + + SortBlockedToStriped(keys, + values, + 0, + detail::radix::traits_t::default_end_bit(decomposer), + Int2Type(), + Int2Type(), + decomposer); + } + + /** + * \brief Performs an ascending radix sort across a [blocked arrangement](index.html#sec5sec3) of keys and values, leaving them in a [striped arrangement](index.html#sec5sec3). + * + * \par + * - BlockRadixSort can only accommodate one associated tile of values. To "truck along" + * more than one tile of values, simply perform a key-value sort of the keys paired + * with a temporary value array that enumerates the key indices. The reordered indices + * can then be used as a gather-vector for exchanging other associated tile data through + * shared memory. + * - \granularity + * - \smemreuse + * + * \par Snippet + * The code snippet below illustrates a sort of 512 integer keys and values that + * are initially partitioned in a [blocked arrangement](index.html#sec5sec3) across 128 threads + * where each thread owns 4 consecutive pairs. The final partitioning is striped. + * \par + * \code + * #include // or equivalently + * + * __global__ void ExampleKernel(...) + * { + * // Specialize BlockRadixSort for a 1D block of 128 threads owning 4 integer keys and values each + * typedef cub::BlockRadixSort BlockRadixSort; + * + * // Allocate shared memory for BlockRadixSort + * __shared__ typename BlockRadixSort::TempStorage temp_storage; + * + * // Obtain a segment of consecutive items that are blocked across threads + * int thread_keys[4]; + * int thread_values[4]; + * ... + * + * // Collectively sort the keys and values among block threads + * BlockRadixSort(temp_storage).SortBlockedToStriped(thread_keys, thread_values); + * + * \endcode + * \par + * Suppose the set of input \p thread_keys across the block of threads is + * { [0,511,1,510], [2,509,3,508], [4,507,5,506], ..., [254,257,255,256] }. The + * corresponding output \p thread_keys in those threads will be + * { [0,128,256,384], [1,129,257,385], [2,130,258,386], ..., [127,255,383,511] }. + * + */ + __device__ __forceinline__ void SortBlockedToStriped( + KeyT (&keys)[ITEMS_PER_THREAD], ///< [in-out] Keys to sort + ValueT (&values)[ITEMS_PER_THREAD], ///< [in-out] Values to sort + int begin_bit = 0, ///< [in] [optional] The beginning (least-significant) bit index needed for key comparison + int end_bit = sizeof(KeyT) * 8) ///< [in] [optional] The past-the-end (most-significant) bit index needed for key comparison + { + SortBlockedToStriped(keys, values, begin_bit, end_bit, Int2Type(), Int2Type()); + } + + //! @rst + //! Performs an ascending block-wide radix sort over a + //! :ref:`blocked arrangement ` of keys and values, leaving them in a + //! :ref:`striped arrangement `. + //! + //! * @granularity + //! * @smemreuse + //! + //! Snippet + //! ========================================================================== + //! + //! Let's consider a user-defined ``custom_t`` type below. To sort an array of + //! ``custom_t`` objects, we have to tell CUB about relevant members of the + //! ``custom_t`` type. We do this by providing a decomposer that returns a + //! tuple of references to relevant members of the key. + //! + //! .. literalinclude:: ../../test/catch2_test_block_radix_sort_custom.cu + //! :language: c++ + //! :dedent: + //! :start-after: example-begin custom-type + //! :end-before: example-end custom-type + //! + //! The code snippet below illustrates a sort of 4 pairs that + //! are partitioned in a :ref:`blocked arrangement ` across 2 threads + //! where each thread owns 2 consecutive pairs. The final partitioning is striped. + //! + //! .. literalinclude:: ../../test/catch2_test_block_radix_sort_custom.cu + //! :language: c++ + //! :dedent: + //! :start-after: example-begin pairs-striped-bits + //! :end-before: example-end pairs-striped-bits + //! + //! @endrst + //! + //! @tparam DecomposerT + //! **[inferred]** Type of a callable object responsible for decomposing a + //! ``KeyT`` into a tuple of references to its constituent arithmetic types: + //! ``::cuda::std::tuple operator()(KeyT &key)``. + //! The leftmost element of the tuple is considered the most significant. + //! The call operator must not modify members of the key. + //! + //! @param[in,out] keys + //! Keys to sort + //! + //! @param[in,out] values + //! Values to sort + //! + //! @param decomposer + //! Callable object responsible for decomposing a ``KeyT`` into a tuple of + //! references to its constituent arithmetic types. The leftmost element of + //! the tuple is considered the most significant. The call operator must not + //! modify members of the key. + //! + //! @param[in] begin_bit + //! The least-significant bit index (inclusive) needed for + //! key comparison + //! + //! @param[in] end_bit + //! The most-significant bit index (exclusive) needed for key + //! comparison (e.g., `(sizeof(float) + sizeof(long long int)) * 8`) + template + __device__ __forceinline__ // + typename ::cuda::std::enable_if< // + !::cuda::std::is_convertible::value>::type + SortBlockedToStriped(KeyT (&keys)[ITEMS_PER_THREAD], + ValueT (&values)[ITEMS_PER_THREAD], + DecomposerT decomposer, + int begin_bit, + int end_bit) + { + SortBlockedToStriped(keys, + values, + begin_bit, + end_bit, + Int2Type(), + Int2Type(), + decomposer); + } + + //! @rst + //! Performs an ascending block-wide radix sort over a + //! :ref:`blocked arrangement ` of keys and values, leaving them in a + //! :ref:`striped arrangement `. + //! + //! * @granularity + //! * @smemreuse + //! + //! Snippet + //! ========================================================================== + //! + //! Let's consider a user-defined ``custom_t`` type below. To sort an array of + //! ``custom_t`` objects, we have to tell CUB about relevant members of the + //! ``custom_t`` type. We do this by providing a decomposer that returns a + //! tuple of references to relevant members of the key. + //! + //! .. literalinclude:: ../../test/catch2_test_block_radix_sort_custom.cu + //! :language: c++ + //! :dedent: + //! :start-after: example-begin custom-type + //! :end-before: example-end custom-type + //! + //! The code snippet below illustrates a sort of 6 pairs that + //! are partitioned in a :ref:`blocked arrangement ` across 2 threads + //! where each thread owns 3 consecutive pairs. The final partitioning is striped. + //! + //! .. literalinclude:: ../../test/catch2_test_block_radix_sort_custom.cu + //! :language: c++ + //! :dedent: + //! :start-after: example-begin pairs-striped + //! :end-before: example-end pairs-striped + //! + //! @endrst + //! + //! @tparam DecomposerT + //! **[inferred]** Type of a callable object responsible for decomposing a + //! ``KeyT`` into a tuple of references to its constituent arithmetic types: + //! ``::cuda::std::tuple operator()(KeyT &key)``. + //! The leftmost element of the tuple is considered the most significant. + //! The call operator must not modify members of the key. + //! + //! @param[in,out] keys + //! Keys to sort + //! + //! @param[in,out] values + //! Values to sort + //! + //! @param decomposer + //! Callable object responsible for decomposing a ``KeyT`` into a tuple of + //! references to its constituent arithmetic types. The leftmost element of + //! the tuple is considered the most significant. The call operator must not + //! modify members of the key. + template + __device__ __forceinline__ // + typename ::cuda::std::enable_if< // + !::cuda::std::is_convertible::value>::type + SortBlockedToStriped(KeyT (&keys)[ITEMS_PER_THREAD], + ValueT (&values)[ITEMS_PER_THREAD], + DecomposerT decomposer) + { + SortBlockedToStriped(keys, + values, + 0, + detail::radix::traits_t::default_end_bit(decomposer), + Int2Type(), + Int2Type(), + decomposer); + } + + /** + * \brief Performs a descending radix sort across a [blocked arrangement](index.html#sec5sec3) of keys, leaving them in a [striped arrangement](index.html#sec5sec3). + * + * \par + * - \granularity + * - \smemreuse + * + * \par Snippet + * The code snippet below illustrates a sort of 512 integer keys that + * are initially partitioned in a [blocked arrangement](index.html#sec5sec3) across 128 threads + * where each thread owns 4 consecutive keys. The final partitioning is striped. + * \par + * \code + * #include // or equivalently + * + * __global__ void ExampleKernel(...) + * { + * // Specialize BlockRadixSort for a 1D block of 128 threads owning 4 integer keys each + * typedef cub::BlockRadixSort BlockRadixSort; + * + * // Allocate shared memory for BlockRadixSort + * __shared__ typename BlockRadixSort::TempStorage temp_storage; + * + * // Obtain a segment of consecutive items that are blocked across threads + * int thread_keys[4]; + * ... + * + * // Collectively sort the keys + * BlockRadixSort(temp_storage).SortBlockedToStriped(thread_keys); + * + * \endcode + * \par + * Suppose the set of input \p thread_keys across the block of threads is + * { [0,511,1,510], [2,509,3,508], [4,507,5,506], ..., [254,257,255,256] }. The + * corresponding output \p thread_keys in those threads will be + * { [511,383,255,127], [386,258,130,2], [385,257,128,1], ..., [384,256,128,0] }. + * + */ + __device__ __forceinline__ void SortDescendingBlockedToStriped( + KeyT (&keys)[ITEMS_PER_THREAD], ///< [in-out] Keys to sort + int begin_bit = 0, ///< [in] [optional] The beginning (least-significant) bit index needed for key comparison + int end_bit = sizeof(KeyT) * 8) ///< [in] [optional] The past-the-end (most-significant) bit index needed for key comparison + { + NullType values[ITEMS_PER_THREAD]; + + SortBlockedToStriped(keys, values, begin_bit, end_bit, Int2Type(), Int2Type()); + } + + //! @rst + //! Performs a descending block-wide radix sort over a + //! :ref:`blocked arrangement ` of keys, leaving them in a + //! :ref:`striped arrangement `. + //! + //! * @granularity + //! * @smemreuse + //! + //! Snippet + //! ========================================================================== + //! + //! Let's consider a user-defined ``custom_t`` type below. To sort an array of + //! ``custom_t`` objects, we have to tell CUB about relevant members of the + //! ``custom_t`` type. We do this by providing a decomposer that returns a + //! tuple of references to relevant members of the key. + //! + //! .. literalinclude:: ../../test/catch2_test_block_radix_sort_custom.cu + //! :language: c++ + //! :dedent: + //! :start-after: example-begin custom-type + //! :end-before: example-end custom-type + //! + //! The code snippet below illustrates a sort of 4 keys that + //! are partitioned in a :ref:`blocked arrangement ` across 2 threads + //! where each thread owns 2 consecutive keys. The final partitioning is striped. + //! + //! .. literalinclude:: ../../test/catch2_test_block_radix_sort_custom.cu + //! :language: c++ + //! :dedent: + //! :start-after: example-begin keys-striped-descending-bits + //! :end-before: example-end keys-striped-descending-bits + //! + //! @endrst + //! + //! @tparam DecomposerT + //! **[inferred]** Type of a callable object responsible for decomposing a + //! ``KeyT`` into a tuple of references to its constituent arithmetic types: + //! ``::cuda::std::tuple operator()(KeyT &key)``. + //! The leftmost element of the tuple is considered the most significant. + //! The call operator must not modify members of the key. + //! + //! @param[in,out] keys + //! Keys to sort + //! + //! @param decomposer + //! Callable object responsible for decomposing a ``KeyT`` into a tuple of + //! references to its constituent arithmetic types. The leftmost element of + //! the tuple is considered the most significant. The call operator must not + //! modify members of the key. + //! + //! @param[in] begin_bit + //! The least-significant bit index (inclusive) needed for + //! key comparison + //! + //! @param[in] end_bit + //! The most-significant bit index (exclusive) needed for key + //! comparison (e.g., `(sizeof(float) + sizeof(long long int)) * 8`) + template + __device__ __forceinline__ // + typename ::cuda::std::enable_if< // + !::cuda::std::is_convertible::value>::type + SortDescendingBlockedToStriped(KeyT (&keys)[ITEMS_PER_THREAD], + DecomposerT decomposer, + int begin_bit, + int end_bit) + { + NullType values[ITEMS_PER_THREAD]; + + SortBlockedToStriped(keys, + values, + begin_bit, + end_bit, + Int2Type(), + Int2Type(), + decomposer); + } + + //! @rst + //! Performs a descending block-wide radix sort over a + //! :ref:`blocked arrangement ` of keys, leaving them in a + //! :ref:`striped arrangement `. + //! + //! * @granularity + //! * @smemreuse + //! + //! Snippet + //! ========================================================================== + //! + //! Let's consider a user-defined ``custom_t`` type below. To sort an array of + //! ``custom_t`` objects, we have to tell CUB about relevant members of the + //! ``custom_t`` type. We do this by providing a decomposer that returns a + //! tuple of references to relevant members of the key. + //! + //! .. literalinclude:: ../../test/catch2_test_block_radix_sort_custom.cu + //! :language: c++ + //! :dedent: + //! :start-after: example-begin custom-type + //! :end-before: example-end custom-type + //! + //! The code snippet below illustrates a sort of 6 keys that + //! are partitioned in a :ref:`blocked arrangement ` across 2 threads + //! where each thread owns 3 consecutive keys. The final partitioning is striped. + //! + //! .. literalinclude:: ../../test/catch2_test_block_radix_sort_custom.cu + //! :language: c++ + //! :dedent: + //! :start-after: example-begin keys-striped-descending + //! :end-before: example-end keys-striped-descending + //! + //! @endrst + //! + //! @tparam DecomposerT + //! **[inferred]** Type of a callable object responsible for decomposing a + //! ``KeyT`` into a tuple of references to its constituent arithmetic types: + //! ``::cuda::std::tuple operator()(KeyT &key)``. + //! The leftmost element of the tuple is considered the most significant. + //! The call operator must not modify members of the key. + //! + //! @param[in,out] keys + //! Keys to sort + //! + //! @param decomposer + //! Callable object responsible for decomposing a ``KeyT`` into a tuple of + //! references to its constituent arithmetic types. The leftmost element of + //! the tuple is considered the most significant. The call operator must not + //! modify members of the key. + template + __device__ __forceinline__ // + typename ::cuda::std::enable_if< // + !::cuda::std::is_convertible::value>::type + SortDescendingBlockedToStriped(KeyT (&keys)[ITEMS_PER_THREAD], DecomposerT decomposer) + { + NullType values[ITEMS_PER_THREAD]; + + SortBlockedToStriped(keys, + values, + 0, + detail::radix::traits_t::default_end_bit(decomposer), + Int2Type(), + Int2Type(), + decomposer); + } + + /** + * \brief Performs a descending radix sort across a [blocked arrangement](index.html#sec5sec3) of keys and values, leaving them in a [striped arrangement](index.html#sec5sec3). + * + * \par + * - BlockRadixSort can only accommodate one associated tile of values. To "truck along" + * more than one tile of values, simply perform a key-value sort of the keys paired + * with a temporary value array that enumerates the key indices. The reordered indices + * can then be used as a gather-vector for exchanging other associated tile data through + * shared memory. + * - \granularity + * - \smemreuse + * + * \par Snippet + * The code snippet below illustrates a sort of 512 integer keys and values that + * are initially partitioned in a [blocked arrangement](index.html#sec5sec3) across 128 threads + * where each thread owns 4 consecutive pairs. The final partitioning is striped. + * \par + * \code + * #include // or equivalently + * + * __global__ void ExampleKernel(...) + * { + * // Specialize BlockRadixSort for a 1D block of 128 threads owning 4 integer keys and values each + * typedef cub::BlockRadixSort BlockRadixSort; + * + * // Allocate shared memory for BlockRadixSort + * __shared__ typename BlockRadixSort::TempStorage temp_storage; + * + * // Obtain a segment of consecutive items that are blocked across threads + * int thread_keys[4]; + * int thread_values[4]; + * ... + * + * // Collectively sort the keys and values among block threads + * BlockRadixSort(temp_storage).SortBlockedToStriped(thread_keys, thread_values); + * + * \endcode + * \par + * Suppose the set of input \p thread_keys across the block of threads is + * { [0,511,1,510], [2,509,3,508], [4,507,5,506], ..., [254,257,255,256] }. The + * corresponding output \p thread_keys in those threads will be + * { [511,383,255,127], [386,258,130,2], [385,257,128,1], ..., [384,256,128,0] }. + * + */ + __device__ __forceinline__ void SortDescendingBlockedToStriped( + KeyT (&keys)[ITEMS_PER_THREAD], ///< [in-out] Keys to sort + ValueT (&values)[ITEMS_PER_THREAD], ///< [in-out] Values to sort + int begin_bit = 0, ///< [in] [optional] The beginning (least-significant) bit index needed for key comparison + int end_bit = sizeof(KeyT) * 8) ///< [in] [optional] The past-the-end (most-significant) bit index needed for key comparison + { + SortBlockedToStriped(keys, values, begin_bit, end_bit, Int2Type(), Int2Type()); + } + + //! @rst + //! Performs a descending block-wide radix sort over a + //! :ref:`blocked arrangement ` of keys and values, leaving them in a + //! :ref:`striped arrangement `. + //! + //! * @granularity + //! * @smemreuse + //! + //! Snippet + //! ========================================================================== + //! + //! Let's consider a user-defined ``custom_t`` type below. To sort an array of + //! ``custom_t`` objects, we have to tell CUB about relevant members of the + //! ``custom_t`` type. We do this by providing a decomposer that returns a + //! tuple of references to relevant members of the key. + //! + //! .. literalinclude:: ../../test/catch2_test_block_radix_sort_custom.cu + //! :language: c++ + //! :dedent: + //! :start-after: example-begin custom-type + //! :end-before: example-end custom-type + //! + //! The code snippet below illustrates a sort of 4 keys and values that + //! are partitioned in a :ref:`blocked arrangement ` across 2 threads + //! where each thread owns 2 consecutive pairs. The final partitioning is striped. + //! + //! .. literalinclude:: ../../test/catch2_test_block_radix_sort_custom.cu + //! :language: c++ + //! :dedent: + //! :start-after: example-begin pairs-striped-descending-bits + //! :end-before: example-end pairs-striped-descending-bits + //! + //! @endrst + //! + //! @tparam DecomposerT + //! **[inferred]** Type of a callable object responsible for decomposing a + //! ``KeyT`` into a tuple of references to its constituent arithmetic types: + //! ``::cuda::std::tuple operator()(KeyT &key)``. + //! The leftmost element of the tuple is considered the most significant. + //! The call operator must not modify members of the key. + //! + //! @param[in,out] keys + //! Keys to sort + //! + //! @param[in,out] values + //! Values to sort + //! + //! @param decomposer + //! Callable object responsible for decomposing a ``KeyT`` into a tuple of + //! references to its constituent arithmetic types. The leftmost element of + //! the tuple is considered the most significant. The call operator must not + //! modify members of the key. + //! + //! @param[in] begin_bit + //! The least-significant bit index (inclusive) needed for + //! key comparison + //! + //! @param[in] end_bit + //! The most-significant bit index (exclusive) needed for key + //! comparison (e.g., `(sizeof(float) + sizeof(long long int)) * 8`) + template + __device__ __forceinline__ // + typename ::cuda::std::enable_if< // + !::cuda::std::is_convertible::value>::type + SortDescendingBlockedToStriped(KeyT (&keys)[ITEMS_PER_THREAD], + ValueT (&values)[ITEMS_PER_THREAD], + DecomposerT decomposer, + int begin_bit, + int end_bit) + { + SortBlockedToStriped(keys, + values, + begin_bit, + end_bit, + Int2Type(), + Int2Type(), + decomposer); + } + + //! @rst + //! Performs a descending block-wide radix sort over a + //! :ref:`blocked arrangement ` of keys and values, leaving them in a + //! :ref:`striped arrangement `. + //! + //! * @granularity + //! * @smemreuse + //! + //! Snippet + //! ========================================================================== + //! + //! Let's consider a user-defined ``custom_t`` type below. To sort an array of + //! ``custom_t`` objects, we have to tell CUB about relevant members of the + //! ``custom_t`` type. We do this by providing a decomposer that returns a + //! tuple of references to relevant members of the key. + //! + //! .. literalinclude:: ../../test/catch2_test_block_radix_sort_custom.cu + //! :language: c++ + //! :dedent: + //! :start-after: example-begin custom-type + //! :end-before: example-end custom-type + //! + //! The code snippet below illustrates a sort of 6 keys and values that + //! are partitioned in a :ref:`blocked arrangement ` across 2 threads + //! where each thread owns 3 consecutive pairs. The final partitioning is striped. + //! + //! .. literalinclude:: ../../test/catch2_test_block_radix_sort_custom.cu + //! :language: c++ + //! :dedent: + //! :start-after: example-begin pairs-striped-descending + //! :end-before: example-end pairs-striped-descending + //! + //! @endrst + //! + //! @tparam DecomposerT + //! **[inferred]** Type of a callable object responsible for decomposing a + //! ``KeyT`` into a tuple of references to its constituent arithmetic types: + //! ``::cuda::std::tuple operator()(KeyT &key)``. + //! The leftmost element of the tuple is considered the most significant. + //! The call operator must not modify members of the key. + //! + //! @param[in,out] keys + //! Keys to sort + //! + //! @param[in,out] values + //! Values to sort + //! + //! @param decomposer + //! Callable object responsible for decomposing a ``KeyT`` into a tuple of + //! references to its constituent arithmetic types. The leftmost element of + //! the tuple is considered the most significant. The call operator must not + //! modify members of the key. + template + __device__ __forceinline__ // + typename ::cuda::std::enable_if< // + !::cuda::std::is_convertible::value>::type + SortDescendingBlockedToStriped(KeyT (&keys)[ITEMS_PER_THREAD], + ValueT (&values)[ITEMS_PER_THREAD], + DecomposerT decomposer) + { + SortBlockedToStriped(keys, + values, + 0, + detail::radix::traits_t::default_end_bit(decomposer), + Int2Type(), + Int2Type(), + decomposer); + } + + //@} end member group + +}; + +/** + * \example example_block_radix_sort.cu + */ + +CUB_NAMESPACE_END + diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/block/block_raking_layout.cuh b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/block/block_raking_layout.cuh new file mode 100644 index 0000000000000000000000000000000000000000..4d49f54f2c8a90071c38f9a011a9933792bb84ed --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/block/block_raking_layout.cuh @@ -0,0 +1,145 @@ +/****************************************************************************** + * Copyright (c) 2011, Duane Merrill. All rights reserved. + * Copyright (c) 2011-2018, NVIDIA CORPORATION. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the NVIDIA CORPORATION nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ******************************************************************************/ + +/** + * \file + * cub::BlockRakingLayout provides a conflict-free shared memory layout abstraction for warp-raking across thread block data. + */ + + +#pragma once + +#include "../config.cuh" +#include "../util_type.cuh" + +CUB_NAMESPACE_BEGIN + +/** + * \brief BlockRakingLayout provides a conflict-free shared memory layout abstraction for 1D raking across thread block data. ![](raking.png) + * \ingroup BlockModule + * + * \par Overview + * This type facilitates a shared memory usage pattern where a block of CUDA + * threads places elements into shared memory and then reduces the active + * parallelism to one "raking" warp of threads for serially aggregating consecutive + * sequences of shared items. Padding is inserted to eliminate bank conflicts + * (for most data types). + * + * \tparam T The data type to be exchanged. + * \tparam BLOCK_THREADS The thread block size in threads. + * \tparam LEGACY_PTX_ARCH [optional] Unused. + */ +template < + typename T, + int BLOCK_THREADS, + int LEGACY_PTX_ARCH = 0> +struct BlockRakingLayout +{ + //--------------------------------------------------------------------- + // Constants and type definitions + //--------------------------------------------------------------------- + + enum + { + /// The total number of elements that need to be cooperatively reduced + SHARED_ELEMENTS = BLOCK_THREADS, + + /// Maximum number of warp-synchronous raking threads + MAX_RAKING_THREADS = CUB_MIN(BLOCK_THREADS, CUB_WARP_THREADS(0)), + + /// Number of raking elements per warp-synchronous raking thread (rounded up) + SEGMENT_LENGTH = (SHARED_ELEMENTS + MAX_RAKING_THREADS - 1) / MAX_RAKING_THREADS, + + /// Never use a raking thread that will have no valid data (e.g., when BLOCK_THREADS is 62 and SEGMENT_LENGTH is 2, we should only use 31 raking threads) + RAKING_THREADS = (SHARED_ELEMENTS + SEGMENT_LENGTH - 1) / SEGMENT_LENGTH, + + /// Whether we will have bank conflicts (technically we should find out if the GCD is > 1) + HAS_CONFLICTS = (CUB_SMEM_BANKS(0) % SEGMENT_LENGTH == 0), + + /// Degree of bank conflicts (e.g., 4-way) + CONFLICT_DEGREE = (HAS_CONFLICTS) ? + (MAX_RAKING_THREADS * SEGMENT_LENGTH) / CUB_SMEM_BANKS(0) : + 1, + + /// Pad each segment length with one element if segment length is not relatively prime to warp size and can't be optimized as a vector load + USE_SEGMENT_PADDING = ((SEGMENT_LENGTH & 1) == 0) && (SEGMENT_LENGTH > 2), + + /// Total number of elements in the raking grid + GRID_ELEMENTS = RAKING_THREADS * (SEGMENT_LENGTH + USE_SEGMENT_PADDING), + + /// Whether or not we need bounds checking during raking (the number of reduction elements is not a multiple of the number of raking threads) + UNGUARDED = (SHARED_ELEMENTS % RAKING_THREADS == 0), + }; + + + /** + * \brief Shared memory storage type + */ + struct __align__(16) _TempStorage + { + T buff[BlockRakingLayout::GRID_ELEMENTS]; + }; + + /// Alias wrapper allowing storage to be unioned + struct TempStorage : Uninitialized<_TempStorage> {}; + + + /** + * \brief Returns the location for the calling thread to place data into the grid + */ + static __device__ __forceinline__ T* PlacementPtr( + TempStorage &temp_storage, + unsigned int linear_tid) + { + // Offset for partial + unsigned int offset = linear_tid; + + // Add in one padding element for every segment + if (USE_SEGMENT_PADDING > 0) + { + offset += offset / SEGMENT_LENGTH; + } + + // Incorporating a block of padding partials every shared memory segment + return temp_storage.Alias().buff + offset; + } + + + /** + * \brief Returns the location for the calling thread to begin sequential raking + */ + static __device__ __forceinline__ T* RakingPtr( + TempStorage &temp_storage, + unsigned int linear_tid) + { + return temp_storage.Alias().buff + (linear_tid * (SEGMENT_LENGTH + USE_SEGMENT_PADDING)); + } +}; + +CUB_NAMESPACE_END + diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/block/block_reduce.cuh b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/block/block_reduce.cuh new file mode 100644 index 0000000000000000000000000000000000000000..5a9db703db9f5ff86fcfa8fa2684b33ebe15c583 --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/block/block_reduce.cuh @@ -0,0 +1,608 @@ +/****************************************************************************** + * Copyright (c) 2011, Duane Merrill. All rights reserved. + * Copyright (c) 2011-2018, NVIDIA CORPORATION. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the NVIDIA CORPORATION nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ******************************************************************************/ + +/** + * \file + * The cub::BlockReduce class provides [collective](index.html#sec0) methods for computing a parallel reduction of items partitioned across a CUDA thread block. + */ + +#pragma once + +#include "specializations/block_reduce_raking.cuh" +#include "specializations/block_reduce_raking_commutative_only.cuh" +#include "specializations/block_reduce_warp_reductions.cuh" +#include "../config.cuh" +#include "../util_ptx.cuh" +#include "../util_type.cuh" +#include "../thread/thread_operators.cuh" + +CUB_NAMESPACE_BEGIN + + + +/****************************************************************************** + * Algorithmic variants + ******************************************************************************/ + +/** + * BlockReduceAlgorithm enumerates alternative algorithms for parallel + * reduction across a CUDA thread block. + */ +enum BlockReduceAlgorithm +{ + + /** + * \par Overview + * An efficient "raking" reduction algorithm that only supports commutative + * reduction operators (true for most operations, e.g., addition). + * + * \par + * Execution is comprised of three phases: + * -# Upsweep sequential reduction in registers (if threads contribute more + * than one input each). Threads in warps other than the first warp place + * their partial reductions into shared memory. + * -# Upsweep sequential reduction in shared memory. Threads within the first + * warp continue to accumulate by raking across segments of shared partial reductions + * -# A warp-synchronous Kogge-Stone style reduction within the raking warp. + * + * \par + * \image html block_reduce.png + *
\p BLOCK_REDUCE_RAKING data flow for a hypothetical 16-thread thread block and 4-thread raking warp.
+ * + * \par Performance Considerations + * - This variant performs less communication than BLOCK_REDUCE_RAKING_NON_COMMUTATIVE + * and is preferable when the reduction operator is commutative. This variant + * applies fewer reduction operators than BLOCK_REDUCE_WARP_REDUCTIONS, and can provide higher overall + * throughput across the GPU when suitably occupied. However, turn-around latency may be + * higher than to BLOCK_REDUCE_WARP_REDUCTIONS and thus less-desirable + * when the GPU is under-occupied. + */ + BLOCK_REDUCE_RAKING_COMMUTATIVE_ONLY, + + + /** + * \par Overview + * An efficient "raking" reduction algorithm that supports commutative + * (e.g., addition) and non-commutative (e.g., string concatenation) reduction + * operators. \blocked. + * + * \par + * Execution is comprised of three phases: + * -# Upsweep sequential reduction in registers (if threads contribute more + * than one input each). Each thread then places the partial reduction + * of its item(s) into shared memory. + * -# Upsweep sequential reduction in shared memory. Threads within a + * single warp rake across segments of shared partial reductions. + * -# A warp-synchronous Kogge-Stone style reduction within the raking warp. + * + * \par + * \image html block_reduce.png + *
\p BLOCK_REDUCE_RAKING data flow for a hypothetical 16-thread thread block and 4-thread raking warp.
+ * + * \par Performance Considerations + * - This variant performs more communication than BLOCK_REDUCE_RAKING + * and is only preferable when the reduction operator is non-commutative. This variant + * applies fewer reduction operators than BLOCK_REDUCE_WARP_REDUCTIONS, and can provide higher overall + * throughput across the GPU when suitably occupied. However, turn-around latency may be + * higher than to BLOCK_REDUCE_WARP_REDUCTIONS and thus less-desirable + * when the GPU is under-occupied. + */ + BLOCK_REDUCE_RAKING, + + + /** + * \par Overview + * A quick "tiled warp-reductions" reduction algorithm that supports commutative + * (e.g., addition) and non-commutative (e.g., string concatenation) reduction + * operators. + * + * \par + * Execution is comprised of four phases: + * -# Upsweep sequential reduction in registers (if threads contribute more + * than one input each). Each thread then places the partial reduction + * of its item(s) into shared memory. + * -# Compute a shallow, but inefficient warp-synchronous Kogge-Stone style + * reduction within each warp. + * -# A propagation phase where the warp reduction outputs in each warp are + * updated with the aggregate from each preceding warp. + * + * \par + * \image html block_scan_warpscans.png + *
\p BLOCK_REDUCE_WARP_REDUCTIONS data flow for a hypothetical 16-thread thread block and 4-thread raking warp.
+ * + * \par Performance Considerations + * - This variant applies more reduction operators than BLOCK_REDUCE_RAKING + * or BLOCK_REDUCE_RAKING_NON_COMMUTATIVE, which may result in lower overall + * throughput across the GPU. However turn-around latency may be lower and + * thus useful when the GPU is under-occupied. + */ + BLOCK_REDUCE_WARP_REDUCTIONS, +}; + + +/****************************************************************************** + * Block reduce + ******************************************************************************/ + +/** + * \brief The BlockReduce class provides [collective](index.html#sec0) methods for computing a parallel reduction of items partitioned across a CUDA thread block. ![](reduce_logo.png) + * \ingroup BlockModule + * + * \tparam T Data type being reduced + * \tparam BLOCK_DIM_X The thread block length in threads along the X dimension + * \tparam ALGORITHM [optional] cub::BlockReduceAlgorithm enumerator specifying the underlying algorithm to use (default: cub::BLOCK_REDUCE_WARP_REDUCTIONS) + * \tparam BLOCK_DIM_Y [optional] The thread block length in threads along the Y dimension (default: 1) + * \tparam BLOCK_DIM_Z [optional] The thread block length in threads along the Z dimension (default: 1) + * \tparam LEGACY_PTX_ARCH [optional] Unused. + * + * \par Overview + * - A reduction (or fold) + * uses a binary combining operator to compute a single aggregate from a list of input elements. + * - \rowmajor + * - BlockReduce can be optionally specialized by algorithm to accommodate different latency/throughput workload profiles: + * -# cub::BLOCK_REDUCE_RAKING_COMMUTATIVE_ONLY. An efficient "raking" reduction algorithm that only supports commutative reduction operators. [More...](\ref cub::BlockReduceAlgorithm) + * -# cub::BLOCK_REDUCE_RAKING. An efficient "raking" reduction algorithm that supports commutative and non-commutative reduction operators. [More...](\ref cub::BlockReduceAlgorithm) + * -# cub::BLOCK_REDUCE_WARP_REDUCTIONS. A quick "tiled warp-reductions" reduction algorithm that supports commutative and non-commutative reduction operators. [More...](\ref cub::BlockReduceAlgorithm) + * + * \par Performance Considerations + * - \granularity + * - Very efficient (only one synchronization barrier). + * - Incurs zero bank conflicts for most types + * - Computation is slightly more efficient (i.e., having lower instruction overhead) for: + * - Summation (vs. generic reduction) + * - \p BLOCK_THREADS is a multiple of the architecture's warp size + * - Every thread has a valid input (i.e., full vs. partial-tiles) + * - See cub::BlockReduceAlgorithm for performance details regarding algorithmic alternatives + * + * \par A Simple Example + * \blockcollective{BlockReduce} + * \par + * The code snippet below illustrates a sum reduction of 512 integer items that + * are partitioned in a [blocked arrangement](index.html#sec5sec3) across 128 threads + * where each thread owns 4 consecutive items. + * \par + * \code + * #include // or equivalently + * + * __global__ void ExampleKernel(...) + * { + * // Specialize BlockReduce for a 1D block of 128 threads of type int + * typedef cub::BlockReduce BlockReduce; + * + * // Allocate shared memory for BlockReduce + * __shared__ typename BlockReduce::TempStorage temp_storage; + * + * // Obtain a segment of consecutive items that are blocked across threads + * int thread_data[4]; + * ... + * + * // Compute the block-wide sum for thread0 + * int aggregate = BlockReduce(temp_storage).Sum(thread_data); + * + * \endcode + * + * \par Re-using dynamically allocating shared memory + * The following example under the examples/block folder illustrates usage of + * dynamically shared memory with BlockReduce and how to re-purpose + * the same memory region: + * example_block_reduce_dyn_smem.cu + */ +template < + typename T, + int BLOCK_DIM_X, + BlockReduceAlgorithm ALGORITHM = BLOCK_REDUCE_WARP_REDUCTIONS, + int BLOCK_DIM_Y = 1, + int BLOCK_DIM_Z = 1, + int LEGACY_PTX_ARCH = 0> +class BlockReduce +{ +private: + + /****************************************************************************** + * Constants and type definitions + ******************************************************************************/ + + /// Constants + enum + { + /// The thread block size in threads + BLOCK_THREADS = BLOCK_DIM_X * BLOCK_DIM_Y * BLOCK_DIM_Z, + }; + + typedef BlockReduceWarpReductions WarpReductions; + typedef BlockReduceRakingCommutativeOnly RakingCommutativeOnly; + typedef BlockReduceRaking Raking; + + /// Internal specialization type + using InternalBlockReduce = cub::detail::conditional_t< + ALGORITHM == BLOCK_REDUCE_WARP_REDUCTIONS, + WarpReductions, + cub::detail::conditional_t>; // BlockReduceRaking + + /// Shared memory storage layout type for BlockReduce + typedef typename InternalBlockReduce::TempStorage _TempStorage; + + + /****************************************************************************** + * Utility methods + ******************************************************************************/ + + /// Internal storage allocator + __device__ __forceinline__ _TempStorage& PrivateStorage() + { + __shared__ _TempStorage private_storage; + return private_storage; + } + + + /****************************************************************************** + * Thread fields + ******************************************************************************/ + + /// Shared storage reference + _TempStorage &temp_storage; + + /// Linear thread-id + unsigned int linear_tid; + + +public: + + /// \smemstorage{BlockReduce} + struct TempStorage : Uninitialized<_TempStorage> {}; + + + /******************************************************************//** + * \name Collective constructors + *********************************************************************/ + //@{ + + /** + * \brief Collective constructor using a private static allocation of shared memory as temporary storage. + */ + __device__ __forceinline__ BlockReduce() + : + temp_storage(PrivateStorage()), + linear_tid(RowMajorTid(BLOCK_DIM_X, BLOCK_DIM_Y, BLOCK_DIM_Z)) + {} + + + /** + * \brief Collective constructor using the specified memory allocation as temporary storage. + */ + __device__ __forceinline__ BlockReduce( + TempStorage &temp_storage) ///< [in] Reference to memory allocation having layout type TempStorage + : + temp_storage(temp_storage.Alias()), + linear_tid(RowMajorTid(BLOCK_DIM_X, BLOCK_DIM_Y, BLOCK_DIM_Z)) + {} + + + //@} end member group + /******************************************************************//** + * \name Generic reductions + *********************************************************************/ + //@{ + + + /** + * \brief Computes a block-wide reduction for thread0 using the specified binary reduction functor. Each thread contributes one input element. + * + * \par + * - The return value is undefined in threads other than thread0. + * - \rowmajor + * - \smemreuse + * + * \par Snippet + * The code snippet below illustrates a max reduction of 128 integer items that + * are partitioned across 128 threads. + * \par + * \code + * #include // or equivalently + * + * __global__ void ExampleKernel(...) + * { + * // Specialize BlockReduce for a 1D block of 128 threads of type int + * typedef cub::BlockReduce BlockReduce; + * + * // Allocate shared memory for BlockReduce + * __shared__ typename BlockReduce::TempStorage temp_storage; + * + * // Each thread obtains an input item + * int thread_data; + * ... + * + * // Compute the block-wide max for thread0 + * int aggregate = BlockReduce(temp_storage).Reduce(thread_data, cub::Max()); + * + * \endcode + * + * \tparam ReductionOp [inferred] Binary reduction functor type having member T operator()(const T &a, const T &b) + */ + template + __device__ __forceinline__ T Reduce( + T input, ///< [in] Calling thread's input + ReductionOp reduction_op) ///< [in] Binary reduction functor + { + return InternalBlockReduce(temp_storage).template Reduce(input, BLOCK_THREADS, reduction_op); + } + + + /** + * \brief Computes a block-wide reduction for thread0 using the specified binary reduction functor. Each thread contributes an array of consecutive input elements. + * + * \par + * - The return value is undefined in threads other than thread0. + * - \granularity + * - \smemreuse + * + * \par Snippet + * The code snippet below illustrates a max reduction of 512 integer items that + * are partitioned in a [blocked arrangement](index.html#sec5sec3) across 128 threads + * where each thread owns 4 consecutive items. + * \par + * \code + * #include // or equivalently + * + * __global__ void ExampleKernel(...) + * { + * // Specialize BlockReduce for a 1D block of 128 threads of type int + * typedef cub::BlockReduce BlockReduce; + * + * // Allocate shared memory for BlockReduce + * __shared__ typename BlockReduce::TempStorage temp_storage; + * + * // Obtain a segment of consecutive items that are blocked across threads + * int thread_data[4]; + * ... + * + * // Compute the block-wide max for thread0 + * int aggregate = BlockReduce(temp_storage).Reduce(thread_data, cub::Max()); + * + * \endcode + * + * \tparam ITEMS_PER_THREAD [inferred] The number of consecutive items partitioned onto each thread. + * \tparam ReductionOp [inferred] Binary reduction functor type having member T operator()(const T &a, const T &b) + */ + template < + int ITEMS_PER_THREAD, + typename ReductionOp> + __device__ __forceinline__ T Reduce( + T (&inputs)[ITEMS_PER_THREAD], ///< [in] Calling thread's input segment + ReductionOp reduction_op) ///< [in] Binary reduction functor + { + // Reduce partials + T partial = internal::ThreadReduce(inputs, reduction_op); + return Reduce(partial, reduction_op); + } + + + /** + * \brief Computes a block-wide reduction for thread0 using the specified binary reduction functor. The first \p num_valid threads each contribute one input element. + * + * \par + * - The return value is undefined in threads other than thread0. + * - \rowmajor + * - \smemreuse + * + * \par Snippet + * The code snippet below illustrates a max reduction of a partially-full tile of integer items that + * are partitioned across 128 threads. + * \par + * \code + * #include // or equivalently + * + * __global__ void ExampleKernel(int num_valid, ...) + * { + * // Specialize BlockReduce for a 1D block of 128 threads of type int + * typedef cub::BlockReduce BlockReduce; + * + * // Allocate shared memory for BlockReduce + * __shared__ typename BlockReduce::TempStorage temp_storage; + * + * // Each thread obtains an input item + * int thread_data; + * if (threadIdx.x < num_valid) thread_data = ... + * + * // Compute the block-wide max for thread0 + * int aggregate = BlockReduce(temp_storage).Reduce(thread_data, cub::Max(), num_valid); + * + * \endcode + * + * \tparam ReductionOp [inferred] Binary reduction functor type having member T operator()(const T &a, const T &b) + */ + template + __device__ __forceinline__ T Reduce( + T input, ///< [in] Calling thread's input + ReductionOp reduction_op, ///< [in] Binary reduction functor + int num_valid) ///< [in] Number of threads containing valid elements (may be less than BLOCK_THREADS) + { + // Determine if we skip bounds checking + if (num_valid >= BLOCK_THREADS) + { + return InternalBlockReduce(temp_storage).template Reduce(input, num_valid, reduction_op); + } + else + { + return InternalBlockReduce(temp_storage).template Reduce(input, num_valid, reduction_op); + } + } + + + //@} end member group + /******************************************************************//** + * \name Summation reductions + *********************************************************************/ + //@{ + + + /** + * \brief Computes a block-wide reduction for thread0 using addition (+) as the reduction operator. Each thread contributes one input element. + * + * \par + * - The return value is undefined in threads other than thread0. + * - \rowmajor + * - \smemreuse + * + * \par Snippet + * The code snippet below illustrates a sum reduction of 128 integer items that + * are partitioned across 128 threads. + * \par + * \code + * #include // or equivalently + * + * __global__ void ExampleKernel(...) + * { + * // Specialize BlockReduce for a 1D block of 128 threads of type int + * typedef cub::BlockReduce BlockReduce; + * + * // Allocate shared memory for BlockReduce + * __shared__ typename BlockReduce::TempStorage temp_storage; + * + * // Each thread obtains an input item + * int thread_data; + * ... + * + * // Compute the block-wide sum for thread0 + * int aggregate = BlockReduce(temp_storage).Sum(thread_data); + * + * \endcode + * + */ + __device__ __forceinline__ T Sum( + T input) ///< [in] Calling thread's input + { + return InternalBlockReduce(temp_storage).template Sum(input, BLOCK_THREADS); + } + + /** + * \brief Computes a block-wide reduction for thread0 using addition (+) as the reduction operator. Each thread contributes an array of consecutive input elements. + * + * \par + * - The return value is undefined in threads other than thread0. + * - \granularity + * - \smemreuse + * + * \par Snippet + * The code snippet below illustrates a sum reduction of 512 integer items that + * are partitioned in a [blocked arrangement](index.html#sec5sec3) across 128 threads + * where each thread owns 4 consecutive items. + * \par + * \code + * #include // or equivalently + * + * __global__ void ExampleKernel(...) + * { + * // Specialize BlockReduce for a 1D block of 128 threads of type int + * typedef cub::BlockReduce BlockReduce; + * + * // Allocate shared memory for BlockReduce + * __shared__ typename BlockReduce::TempStorage temp_storage; + * + * // Obtain a segment of consecutive items that are blocked across threads + * int thread_data[4]; + * ... + * + * // Compute the block-wide sum for thread0 + * int aggregate = BlockReduce(temp_storage).Sum(thread_data); + * + * \endcode + * + * \tparam ITEMS_PER_THREAD [inferred] The number of consecutive items partitioned onto each thread. + */ + template + __device__ __forceinline__ T Sum( + T (&inputs)[ITEMS_PER_THREAD]) ///< [in] Calling thread's input segment + { + // Reduce partials + T partial = internal::ThreadReduce(inputs, cub::Sum()); + return Sum(partial); + } + + + /** + * \brief Computes a block-wide reduction for thread0 using addition (+) as the reduction operator. The first \p num_valid threads each contribute one input element. + * + * \par + * - The return value is undefined in threads other than thread0. + * - \rowmajor + * - \smemreuse + * + * \par Snippet + * The code snippet below illustrates a sum reduction of a partially-full tile of integer items that + * are partitioned across 128 threads. + * \par + * \code + * #include // or equivalently + * + * __global__ void ExampleKernel(int num_valid, ...) + * { + * // Specialize BlockReduce for a 1D block of 128 threads of type int + * typedef cub::BlockReduce BlockReduce; + * + * // Allocate shared memory for BlockReduce + * __shared__ typename BlockReduce::TempStorage temp_storage; + * + * // Each thread obtains an input item (up to num_items) + * int thread_data; + * if (threadIdx.x < num_valid) + * thread_data = ... + * + * // Compute the block-wide sum for thread0 + * int aggregate = BlockReduce(temp_storage).Sum(thread_data, num_valid); + * + * \endcode + * + */ + __device__ __forceinline__ T Sum( + T input, ///< [in] Calling thread's input + int num_valid) ///< [in] Number of threads containing valid elements (may be less than BLOCK_THREADS) + { + // Determine if we skip bounds checking + if (num_valid >= BLOCK_THREADS) + { + return InternalBlockReduce(temp_storage).template Sum(input, num_valid); + } + else + { + return InternalBlockReduce(temp_storage).template Sum(input, num_valid); + } + } + + + //@} end member group +}; + +/** + * \example example_block_reduce.cu + */ + +CUB_NAMESPACE_END + diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/block/block_shuffle.cuh b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/block/block_shuffle.cuh new file mode 100644 index 0000000000000000000000000000000000000000..58938301c1115758600f176ecb3ea097150a58ee --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/block/block_shuffle.cuh @@ -0,0 +1,296 @@ +/****************************************************************************** + * Copyright (c) 2011, Duane Merrill. All rights reserved. + * Copyright (c) 2011-2018, NVIDIA CORPORATION. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the NVIDIA CORPORATION nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ******************************************************************************/ + +/** + * \file + * The cub::BlockShuffle class provides [collective](index.html#sec0) methods for shuffling data partitioned across a CUDA thread block. + */ + +#pragma once + +#include "../config.cuh" +#include "../util_ptx.cuh" +#include "../util_type.cuh" + +CUB_NAMESPACE_BEGIN + +/** + * \brief The BlockShuffle class provides [collective](index.html#sec0) methods for shuffling data partitioned across a CUDA thread block. + * \ingroup BlockModule + * + * \tparam T The data type to be exchanged. + * \tparam BLOCK_DIM_X The thread block length in threads along the X dimension + * \tparam BLOCK_DIM_Y [optional] The thread block length in threads along the Y dimension (default: 1) + * \tparam BLOCK_DIM_Z [optional] The thread block length in threads along the Z dimension (default: 1) + * \tparam LEGACY_PTX_ARCH [optional] Unused. + * + * \par Overview + * It is commonplace for blocks of threads to rearrange data items between + * threads. The BlockShuffle abstraction allows threads to efficiently shift items + * either (a) up to their successor or (b) down to their predecessor. + * + */ +template < + typename T, + int BLOCK_DIM_X, + int BLOCK_DIM_Y = 1, + int BLOCK_DIM_Z = 1, + int LEGACY_PTX_ARCH = 0> +class BlockShuffle +{ +private: + + /****************************************************************************** + * Constants + ******************************************************************************/ + + enum + { + BLOCK_THREADS = BLOCK_DIM_X * BLOCK_DIM_Y * BLOCK_DIM_Z, + + LOG_WARP_THREADS = CUB_LOG_WARP_THREADS(0), + WARP_THREADS = 1 << LOG_WARP_THREADS, + WARPS = (BLOCK_THREADS + WARP_THREADS - 1) / WARP_THREADS, + }; + + /****************************************************************************** + * Type definitions + ******************************************************************************/ + + /// Shared memory storage layout type (last element from each thread's input) + typedef T _TempStorage[BLOCK_THREADS]; + + +public: + + /// \smemstorage{BlockShuffle} + struct TempStorage : Uninitialized<_TempStorage> {}; + +private: + + + /****************************************************************************** + * Thread fields + ******************************************************************************/ + + /// Shared storage reference + _TempStorage &temp_storage; + + /// Linear thread-id + unsigned int linear_tid; + + + /****************************************************************************** + * Utility methods + ******************************************************************************/ + + /// Internal storage allocator + __device__ __forceinline__ _TempStorage& PrivateStorage() + { + __shared__ _TempStorage private_storage; + return private_storage; + } + + +public: + + /******************************************************************//** + * \name Collective constructors + *********************************************************************/ + //@{ + + /** + * \brief Collective constructor using a private static allocation of shared memory as temporary storage. + */ + __device__ __forceinline__ BlockShuffle() + : + temp_storage(PrivateStorage()), + linear_tid(RowMajorTid(BLOCK_DIM_X, BLOCK_DIM_Y, BLOCK_DIM_Z)) + {} + + + /** + * \brief Collective constructor using the specified memory allocation as temporary storage. + */ + __device__ __forceinline__ BlockShuffle( + TempStorage &temp_storage) ///< [in] Reference to memory allocation having layout type TempStorage + : + temp_storage(temp_storage.Alias()), + linear_tid(RowMajorTid(BLOCK_DIM_X, BLOCK_DIM_Y, BLOCK_DIM_Z)) + {} + + + //@} end member group + /******************************************************************//** + * \name Shuffle movement + *********************************************************************/ + //@{ + + + /** + * \brief Each threadi obtains the \p input provided by threadi+distance. The offset \p distance may be negative. + * + * \par + * - \smemreuse + */ + __device__ __forceinline__ void Offset( + T input, ///< [in] The input item from the calling thread (threadi) + T& output, ///< [out] The \p input item from the successor (or predecessor) thread threadi+distance (may be aliased to \p input). This value is only updated for for threadi when 0 <= (i + \p distance) < BLOCK_THREADS-1 + int distance = 1) ///< [in] Offset distance (may be negative) + { + temp_storage[linear_tid] = input; + + CTA_SYNC(); + + const int offset_tid = static_cast(linear_tid) + distance; + if ((offset_tid >= 0) && (offset_tid < BLOCK_THREADS)) + { + output = temp_storage[static_cast(offset_tid)]; + } + } + + + /** + * \brief Each threadi obtains the \p input provided by threadi+distance. + * + * \par + * - \smemreuse + */ + __device__ __forceinline__ void Rotate( + T input, ///< [in] The calling thread's input item + T& output, ///< [out] The \p input item from thread thread(i+distance>)%BLOCK_THREADS (may be aliased to \p input). This value is not updated for threadBLOCK_THREADS-1 + unsigned int distance = 1) ///< [in] Offset distance (0 < \p distance < BLOCK_THREADS) + { + temp_storage[linear_tid] = input; + + CTA_SYNC(); + + unsigned int offset = linear_tid + distance; + if (offset >= BLOCK_THREADS) + offset -= BLOCK_THREADS; + + output = temp_storage[offset]; + } + + + /** + * \brief The thread block rotates its [blocked arrangement](index.html#sec5sec3) of \p input items, shifting it up by one item + * + * \par + * - \blocked + * - \granularity + * - \smemreuse + */ + template + __device__ __forceinline__ void Up( + T (&input)[ITEMS_PER_THREAD], ///< [in] The calling thread's input items + T (&prev)[ITEMS_PER_THREAD]) ///< [out] The corresponding predecessor items (may be aliased to \p input). The item \p prev[0] is not updated for thread0. + { + temp_storage[linear_tid] = input[ITEMS_PER_THREAD - 1]; + + CTA_SYNC(); + + #pragma unroll + for (int ITEM = ITEMS_PER_THREAD - 1; ITEM > 0; --ITEM) + prev[ITEM] = input[ITEM - 1]; + + if (linear_tid > 0) + prev[0] = temp_storage[linear_tid - 1]; + } + + + /** + * \brief The thread block rotates its [blocked arrangement](index.html#sec5sec3) of \p input items, shifting it up by one item. All threads receive the \p input provided by threadBLOCK_THREADS-1. + * + * \par + * - \blocked + * - \granularity + * - \smemreuse + */ + template + __device__ __forceinline__ void Up( + T (&input)[ITEMS_PER_THREAD], ///< [in] The calling thread's input items + T (&prev)[ITEMS_PER_THREAD], ///< [out] The corresponding predecessor items (may be aliased to \p input). The item \p prev[0] is not updated for thread0. + T &block_suffix) ///< [out] The item \p input[ITEMS_PER_THREAD-1] from threadBLOCK_THREADS-1, provided to all threads + { + Up(input, prev); + block_suffix = temp_storage[BLOCK_THREADS - 1]; + } + + + /** + * \brief The thread block rotates its [blocked arrangement](index.html#sec5sec3) of \p input items, shifting it down by one item + * + * \par + * - \blocked + * - \granularity + * - \smemreuse + */ + template + __device__ __forceinline__ void Down( + T (&input)[ITEMS_PER_THREAD], ///< [in] The calling thread's input items + T (&prev)[ITEMS_PER_THREAD]) ///< [out] The corresponding predecessor items (may be aliased to \p input). The value \p prev[0] is not updated for threadBLOCK_THREADS-1. + { + temp_storage[linear_tid] = input[0]; + + CTA_SYNC(); + + #pragma unroll + for (int ITEM = 0; ITEM < ITEMS_PER_THREAD - 1; ITEM++) + prev[ITEM] = input[ITEM + 1]; + + if (linear_tid < BLOCK_THREADS - 1) + prev[ITEMS_PER_THREAD - 1] = temp_storage[linear_tid + 1]; + } + + + /** + * \brief The thread block rotates its [blocked arrangement](index.html#sec5sec3) of input items, shifting it down by one item. All threads receive \p input[0] provided by thread0. + * + * \par + * - \blocked + * - \granularity + * - \smemreuse + */ + template + __device__ __forceinline__ void Down( + T (&input)[ITEMS_PER_THREAD], ///< [in] The calling thread's input items + T (&prev)[ITEMS_PER_THREAD], ///< [out] The corresponding predecessor items (may be aliased to \p input). The value \p prev[0] is not updated for threadBLOCK_THREADS-1. + T &block_prefix) ///< [out] The item \p input[0] from thread0, provided to all threads + { + Down(input, prev); + block_prefix = temp_storage[0]; + } + + //@} end member group + + +}; + +CUB_NAMESPACE_END + diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/block/radix_rank_sort_operations.cuh b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/block/radix_rank_sort_operations.cuh new file mode 100644 index 0000000000000000000000000000000000000000..a2f7b83900692b3544535dc67050c6428a19abc7 --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/block/radix_rank_sort_operations.cuh @@ -0,0 +1,628 @@ +/****************************************************************************** + * Copyright (c) 2011-2020, NVIDIA CORPORATION. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the NVIDIA CORPORATION nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ******************************************************************************/ + +/** + * \file + * radix_rank_sort_operations.cuh contains common abstractions, definitions and + * operations used for radix sorting and ranking. + */ + +#pragma once + +#include + +#include +#include + +#include + +#include "../config.cuh" +#include "../util_ptx.cuh" +#include "../util_type.cuh" +#include "cub/detail/cpp_compatibility.cuh" +#include "cub/detail/type_traits.cuh" + + +CUB_NAMESPACE_BEGIN + +/** \brief Base struct for digit extractor. Contains common code to provide + special handling for floating-point -0.0. + + \note This handles correctly both the case when the keys are + bitwise-complemented after twiddling for descending sort (in onesweep) as + well as when the keys are not bit-negated, but the implementation handles + descending sort separately (in other implementations in CUB). Twiddling + alone maps -0.0f to 0x7fffffff and +0.0f to 0x80000000 for float, which are + subsequent bit patterns and bitwise complements of each other. For onesweep, + both -0.0f and +0.0f are mapped to the bit pattern of +0.0f (0x80000000) for + ascending sort, and to the pattern of -0.0f (0x7fffffff) for descending + sort. For all other sorting implementations in CUB, both are always mapped + to +0.0f. Since bit patterns for both -0.0f and +0.0f are next to each other + and only one of them is used, the sorting works correctly. For double, the + same applies, but with 64-bit patterns. +*/ +template ::CATEGORY> +struct BaseDigitExtractor +{ + using TraitsT = Traits; + using UnsignedBits = typename TraitsT::UnsignedBits; + + static __host__ __device__ __forceinline__ UnsignedBits ProcessFloatMinusZero(UnsignedBits key) + { + return key; + } +}; + +template +struct BaseDigitExtractor +{ + using TraitsT = Traits; + using UnsignedBits = typename TraitsT::UnsignedBits; + + static __host__ __device__ __forceinline__ UnsignedBits ProcessFloatMinusZero(UnsignedBits key) + { + UnsignedBits TWIDDLED_MINUS_ZERO_BITS = + TraitsT::TwiddleIn(UnsignedBits(1) << UnsignedBits(8 * sizeof(UnsignedBits) - 1)); + UnsignedBits TWIDDLED_ZERO_BITS = TraitsT::TwiddleIn(0); + return key == TWIDDLED_MINUS_ZERO_BITS ? TWIDDLED_ZERO_BITS : key; + } +}; + +/** \brief A wrapper type to extract digits. Uses the BFE intrinsic to extract a + * key from a digit. */ +template +struct BFEDigitExtractor : BaseDigitExtractor +{ + using typename BaseDigitExtractor::UnsignedBits; + + std::uint32_t bit_start; + std::uint32_t num_bits; + + explicit __device__ __forceinline__ BFEDigitExtractor( + std::uint32_t bit_start = 0, + std::uint32_t num_bits = 0) + : bit_start(bit_start) + , num_bits(num_bits) + { } + + __device__ __forceinline__ std::uint32_t Digit(UnsignedBits key) const + { + return BFE(this->ProcessFloatMinusZero(key), bit_start, num_bits); + } +}; + +/** \brief A wrapper type to extract digits. Uses a combination of shift and + * bitwise and to extract digits. */ +template +struct ShiftDigitExtractor : BaseDigitExtractor +{ + using typename BaseDigitExtractor::UnsignedBits; + + std::uint32_t bit_start; + std::uint32_t mask; + + explicit __device__ __forceinline__ ShiftDigitExtractor( + std::uint32_t bit_start = 0, std::uint32_t num_bits = 0) + : bit_start(bit_start) + , mask((1 << num_bits) - 1) + { } + + __device__ __forceinline__ std::uint32_t Digit(UnsignedBits key) const + { + return std::uint32_t(this->ProcessFloatMinusZero(key) >> UnsignedBits(bit_start)) & mask; + } +}; + + +#ifndef DOXYGEN_SHOULD_SKIP_THIS // Do not document +namespace detail +{ + +template +struct logic_helper_t; + +template +struct true_t +{ + static constexpr bool value = true; +}; + +template +using all_t = // + ::cuda::std::is_same< // + logic_helper_t, // + logic_helper_t::value...>>; + +struct identity_decomposer_t +{ + template + __host__ __device__ T& operator()(T &key) const + { + return key; + } +}; + +template +__host__ __device__ void +for_each_member_impl_helper(F f, const ::cuda::std::tuple& tpl, THRUST_NS_QUALIFIER::index_sequence) +{ + auto sink = { (f(::cuda::std::get(tpl)), 0)... }; + (void)sink; +} + +template +__host__ __device__ void +for_each_member_impl(F f, const ::cuda::std::tuple& tpl) +{ + static_assert(sizeof...(Ts), "Empty aggregates are not supported"); + + // Most radix operations are indifferent to the order of operations. + // Conversely, the digit extractor traverses fields from the least significant + // to the most significant to imitate bitset printing where higher bits are on + // the left. It also maps to intuition, where something coming first is more + // important. Therefore, we traverse fields on the opposite order. + for_each_member_impl_helper(f, tpl, THRUST_NS_QUALIFIER::make_reversed_index_sequence{}); +} + +template +__host__ __device__ void for_each_member(F f, DecomposerT decomposer, T& aggregate) +{ + for_each_member_impl(f, decomposer(aggregate)); +} + +namespace radix +{ + +template +using void_t = void; + +template +struct is_fundamental_type +{ + static constexpr bool value = false; +}; + +template +struct is_fundamental_type::UnsignedBits>> +{ + static constexpr bool value = true; +}; + +template +struct is_tuple_of_references_to_fundamental_types_t : ::cuda::std::false_type +{}; + +template +struct is_tuple_of_references_to_fundamental_types_t< // + ::cuda::std::tuple, // + typename ::cuda::std::enable_if< // + all_t::value...>::value // + >::type> // + : ::cuda::std::true_type +{}; + +template +using decomposer_check_t = + is_tuple_of_references_to_fundamental_types_t>; + +template +struct bit_ordered_conversion_policy_t +{ + using bit_ordered_type = typename Traits::UnsignedBits; + + static __host__ __device__ bit_ordered_type to_bit_ordered(detail::identity_decomposer_t, + bit_ordered_type val) + { + return Traits::TwiddleIn(val); + } + + static __host__ __device__ bit_ordered_type from_bit_ordered(detail::identity_decomposer_t, + bit_ordered_type val) + { + return Traits::TwiddleOut(val); + } +}; + +template +struct bit_ordered_inversion_policy_t +{ + using bit_ordered_type = typename Traits::UnsignedBits; + + static __host__ __device__ bit_ordered_type inverse(detail::identity_decomposer_t, + bit_ordered_type val) + { + return ~val; + } +}; + +template ::value> +struct traits_t +{ + using bit_ordered_type = typename Traits::UnsignedBits; + using bit_ordered_conversion_policy = bit_ordered_conversion_policy_t; + using bit_ordered_inversion_policy = bit_ordered_inversion_policy_t; + + template + using digit_extractor_t = FundamentalExtractorT; + + static __host__ __device__ bit_ordered_type min_raw_binary_key(detail::identity_decomposer_t) + { + return Traits::LOWEST_KEY; + } + + static __host__ __device__ bit_ordered_type max_raw_binary_key(detail::identity_decomposer_t) + { + return Traits::MAX_KEY; + } + + static __host__ __device__ int default_end_bit(detail::identity_decomposer_t) + { + return sizeof(T) * 8; + } + + template + static __host__ + __device__ digit_extractor_t + digit_extractor(int begin_bit, int num_bits, detail::identity_decomposer_t) + { + return FundamentalExtractorT(begin_bit, num_bits); + } +}; + +template +struct min_raw_binary_key_f +{ + DecomposerT decomposer; + + template + __host__ __device__ void operator()(T &field) + { + using traits = traits_t::type>; + using bit_ordered_type = typename traits::bit_ordered_type; + reinterpret_cast(field) = + traits::min_raw_binary_key(detail::identity_decomposer_t{}); + } +}; + +template +__host__ __device__ void min_raw_binary_key(DecomposerT decomposer, T &aggregate) +{ + detail::for_each_member(min_raw_binary_key_f{decomposer}, decomposer, aggregate); +} + +template +struct max_raw_binary_key_f +{ + DecomposerT decomposer; + + template + __host__ __device__ void operator()(T &field) + { + using traits = traits_t::type>; + using bit_ordered_type = typename traits::bit_ordered_type; + reinterpret_cast(field) = + traits::max_raw_binary_key(detail::identity_decomposer_t{}); + } +}; + +template +__host__ __device__ void max_raw_binary_key(DecomposerT decomposer, T &aggregate) +{ + detail::for_each_member(max_raw_binary_key_f{decomposer}, decomposer, aggregate); +} + +template +struct to_bit_ordered_f +{ + DecomposerT decomposer; + + template + __host__ __device__ void operator()(T &field) + { + using traits = traits_t::type>; + using bit_ordered_type = typename traits::bit_ordered_type; + using bit_ordered_conversion = typename traits::bit_ordered_conversion_policy; + + auto &ordered_field = reinterpret_cast(field); + ordered_field = bit_ordered_conversion::to_bit_ordered(detail::identity_decomposer_t{}, + ordered_field); + } +}; + +template +__host__ __device__ void to_bit_ordered(DecomposerT decomposer, T &aggregate) +{ + detail::for_each_member(to_bit_ordered_f{decomposer}, decomposer, aggregate); +} + +template +struct from_bit_ordered_f +{ + DecomposerT decomposer; + + template + __host__ __device__ void operator()(T &field) + { + using traits = traits_t::type>; + using bit_ordered_type = typename traits::bit_ordered_type; + using bit_ordered_conversion = typename traits::bit_ordered_conversion_policy; + + auto &ordered_field = reinterpret_cast(field); + ordered_field = bit_ordered_conversion::from_bit_ordered(detail::identity_decomposer_t{}, + ordered_field); + } +}; + +template +__host__ __device__ void from_bit_ordered(DecomposerT decomposer, T &aggregate) +{ + detail::for_each_member(from_bit_ordered_f{decomposer}, decomposer, aggregate); +} + +template +struct inverse_f +{ + DecomposerT decomposer; + + template + __host__ __device__ void operator()(T &field) + { + using traits = traits_t::type>; + using bit_ordered_type = typename traits::bit_ordered_type; + + auto &ordered_field = reinterpret_cast(field); + ordered_field = ~ordered_field; + } +}; + +template +__host__ __device__ void inverse(DecomposerT decomposer, T &aggregate) +{ + detail::for_each_member(inverse_f{decomposer}, decomposer, aggregate); +} + +template +struct default_end_bit_f +{ + int &result; + DecomposerT decomposer; + + template + __host__ __device__ void operator()(T &field) + { + result += sizeof(field) * 8; + } +}; + +template +__host__ __device__ int default_end_bit(DecomposerT decomposer, T &aggregate) +{ + int result{}; + detail::for_each_member(default_end_bit_f{result, decomposer}, + decomposer, + aggregate); + return result; +} + +struct digit_f +{ + std::uint32_t &dst; + std::uint32_t &dst_bit_start; + std::uint32_t &src_bit_start; + std::uint32_t &num_bits; + + template + __host__ __device__ void operator()(T &src) + { + const std::uint32_t src_size = sizeof(T) * 8; + + if (src_bit_start >= src_size) + { + src_bit_start -= src_size; + } + else + { + using traits = traits_t::type>; + using bit_ordered_type = typename traits::bit_ordered_type; + + const std::uint32_t bits_to_copy = min(src_size - src_bit_start, num_bits); + + if (bits_to_copy) + { + bit_ordered_type ordered_src = BaseDigitExtractor::ProcessFloatMinusZero( + reinterpret_cast(src)); + + const std::uint32_t mask = (1 << bits_to_copy) - 1; + dst = dst | (((ordered_src >> src_bit_start) & mask) << dst_bit_start); + + num_bits -= bits_to_copy; + dst_bit_start += bits_to_copy; + } + src_bit_start = 0; + } + } +}; + +template +__host__ __device__ void digit(DecomposerT decomposer, + std::uint32_t &dst, + T &src, + std::uint32_t &dst_bit_start, + std::uint32_t &src_bit_start, + std::uint32_t &num_bits) +{ + detail::for_each_member(digit_f{dst, dst_bit_start, src_bit_start, num_bits}, decomposer, src); +} + +template +struct custom_digit_extractor_t +{ + DecomposerT decomposer; + std::uint32_t bit_start; + std::uint32_t num_bits; + + __host__ __device__ __forceinline__ custom_digit_extractor_t(DecomposerT decomposer, + std::uint32_t bit_start, + std::uint32_t num_bits) + : decomposer(decomposer) + , bit_start(bit_start) + , num_bits(num_bits) + {} + + template + __host__ __device__ __forceinline__ std::uint32_t Digit(T &key) const + { + std::uint32_t result{}; + std::uint32_t dst_bit_start{}; + std::uint32_t src_bit_start = bit_start; + std::uint32_t bits_remaining{num_bits}; + digit(decomposer, result, key, dst_bit_start, src_bit_start, bits_remaining); + return result; + } +}; + +struct custom_bit_conversion_policy_t +{ + template + static __host__ __device__ T to_bit_ordered(DecomposerT decomposer, T val) + { + detail::radix::to_bit_ordered(decomposer, val); + return val; + } + + template + static __host__ __device__ T from_bit_ordered(DecomposerT decomposer, T val) + { + detail::radix::from_bit_ordered(decomposer, val); + return val; + } +}; + +struct custom_bit_inversion_policy_t +{ + template + static __host__ __device__ T inverse(DecomposerT decomposer, T val) + { + detail::radix::inverse(decomposer, val); + return val; + } +}; + +template +struct traits_t +{ + using bit_ordered_type = T; + using bit_ordered_conversion_policy = custom_bit_conversion_policy_t; + using bit_ordered_inversion_policy = custom_bit_inversion_policy_t; + + template + using digit_extractor_t = custom_digit_extractor_t; + + template + static __host__ __device__ bit_ordered_type min_raw_binary_key(DecomposerT decomposer) + { + T val{}; + detail::radix::min_raw_binary_key(decomposer, val); + return val; + } + + template + static __host__ __device__ bit_ordered_type max_raw_binary_key(DecomposerT decomposer) + { + T val{}; + detail::radix::max_raw_binary_key(decomposer, val); + return val; + } + + template + static __host__ __device__ int default_end_bit(DecomposerT decomposer) + { + T aggregate{}; + return detail::radix::default_end_bit(decomposer, aggregate); + } + + template + static __host__ __device__ digit_extractor_t + digit_extractor(int begin_bit, int num_bits, DecomposerT decomposer) + { + return custom_digit_extractor_t(decomposer, begin_bit, num_bits); + } +}; + +} // namespace radix + +} // namespace detail +#endif // DOXYGEN_SHOULD_SKIP_THIS + +//! Twiddling keys for radix sort +template +struct RadixSortTwiddle +{ +private: + using traits = detail::radix::traits_t; + using bit_ordered_type = typename traits::bit_ordered_type; + using bit_ordered_conversion_policy = typename traits::bit_ordered_conversion_policy; + using bit_ordered_inversion_policy = typename traits::bit_ordered_inversion_policy; + +public: + template + static __host__ __device__ __forceinline__ // + bit_ordered_type + In(bit_ordered_type key, DecomposerT decomposer = {}) + { + key = bit_ordered_conversion_policy::to_bit_ordered(decomposer, key); + CUB_IF_CONSTEXPR(IS_DESCENDING) + { + key = bit_ordered_inversion_policy::inverse(decomposer, key); + } + return key; + } + + template + static __host__ __device__ __forceinline__ // + bit_ordered_type + Out(bit_ordered_type key, DecomposerT decomposer = {}) + { + CUB_IF_CONSTEXPR(IS_DESCENDING) + { + key = bit_ordered_inversion_policy::inverse(decomposer, key); + } + key = bit_ordered_conversion_policy::from_bit_ordered(decomposer, key); + return key; + } + + template + static __host__ __device__ __forceinline__ // + bit_ordered_type + DefaultKey(DecomposerT decomposer = {}) + { + return IS_DESCENDING ? traits::min_raw_binary_key(decomposer) + : traits::max_raw_binary_key(decomposer); + } +}; + +CUB_NAMESPACE_END diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/block/specializations/block_histogram_atomic.cuh b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/block/specializations/block_histogram_atomic.cuh new file mode 100644 index 0000000000000000000000000000000000000000..93299fa7192b6081c6ab0de16d7e42014969b991 --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/block/specializations/block_histogram_atomic.cuh @@ -0,0 +1,77 @@ +/****************************************************************************** + * Copyright (c) 2011, Duane Merrill. All rights reserved. + * Copyright (c) 2011-2018, NVIDIA CORPORATION. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the NVIDIA CORPORATION nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ******************************************************************************/ + +/** + * \file + * The cub::BlockHistogramAtomic class provides atomic-based methods for constructing block-wide histograms from data samples partitioned across a CUDA thread block. + */ + +#pragma once + +#include "../../config.cuh" + +CUB_NAMESPACE_BEGIN + + +/** + * \brief The BlockHistogramAtomic class provides atomic-based methods for constructing block-wide histograms from data samples partitioned across a CUDA thread block. + */ +template +struct BlockHistogramAtomic +{ + /// Shared memory storage layout type + struct TempStorage {}; + + + /// Constructor + __device__ __forceinline__ BlockHistogramAtomic( + TempStorage &temp_storage) + {} + + + /// Composite data onto an existing histogram + template < + typename T, + typename CounterT, + int ITEMS_PER_THREAD> + __device__ __forceinline__ void Composite( + T (&items)[ITEMS_PER_THREAD], ///< [in] Calling thread's input values to histogram + CounterT histogram[BINS]) ///< [out] Reference to shared/device-accessible memory histogram + { + // Update histogram + #pragma unroll + for (int i = 0; i < ITEMS_PER_THREAD; ++i) + { + atomicAdd(histogram + items[i], 1); + } + } + +}; + +CUB_NAMESPACE_END + diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/block/specializations/block_histogram_sort.cuh b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/block/specializations/block_histogram_sort.cuh new file mode 100644 index 0000000000000000000000000000000000000000..79659ae106d9b0b8e5991345da27ae9956cc167e --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/block/specializations/block_histogram_sort.cuh @@ -0,0 +1,219 @@ +/****************************************************************************** + * Copyright (c) 2011, Duane Merrill. All rights reserved. + * Copyright (c) 2011-2018, NVIDIA CORPORATION. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the NVIDIA CORPORATION nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ******************************************************************************/ + +/** + * \file + * The cub::BlockHistogramSort class provides sorting-based methods for constructing block-wide histograms from data samples partitioned across a CUDA thread block. + */ + +#pragma once + +#include "../../block/block_radix_sort.cuh" +#include "../../block/block_discontinuity.cuh" +#include "../../config.cuh" +#include "../../util_ptx.cuh" + +CUB_NAMESPACE_BEGIN + + + +/** + * \brief The BlockHistogramSort class provides sorting-based methods for constructing block-wide histograms from data samples partitioned across a CUDA thread block. + */ +template < + typename T, ///< Sample type + int BLOCK_DIM_X, ///< The thread block length in threads along the X dimension + int ITEMS_PER_THREAD, ///< The number of samples per thread + int BINS, ///< The number of bins into which histogram samples may fall + int BLOCK_DIM_Y, ///< The thread block length in threads along the Y dimension + int BLOCK_DIM_Z, ///< The thread block length in threads along the Z dimension + int LEGACY_PTX_ARCH = 0> ///< The PTX compute capability for which to to specialize this collective (unused) +struct BlockHistogramSort +{ + /// Constants + enum + { + /// The thread block size in threads + BLOCK_THREADS = BLOCK_DIM_X * BLOCK_DIM_Y * BLOCK_DIM_Z, + }; + + // Parameterize BlockRadixSort type for our thread block + typedef BlockRadixSort< + T, + BLOCK_DIM_X, + ITEMS_PER_THREAD, + NullType, + 4, + true, + BLOCK_SCAN_WARP_SCANS, + cudaSharedMemBankSizeFourByte, + BLOCK_DIM_Y, + BLOCK_DIM_Z> + BlockRadixSortT; + + // Parameterize BlockDiscontinuity type for our thread block + typedef BlockDiscontinuity< + T, + BLOCK_DIM_X, + BLOCK_DIM_Y, + BLOCK_DIM_Z> + BlockDiscontinuityT; + + /// Shared memory + union _TempStorage + { + // Storage for sorting bin values + typename BlockRadixSortT::TempStorage sort; + + struct Discontinuities + { + // Storage for detecting discontinuities in the tile of sorted bin values + typename BlockDiscontinuityT::TempStorage flag; + + // Storage for noting begin/end offsets of bin runs in the tile of sorted bin values + unsigned int run_begin[BINS]; + unsigned int run_end[BINS]; + } discontinuities; + }; + + + /// Alias wrapper allowing storage to be unioned + struct TempStorage : Uninitialized<_TempStorage> {}; + + + // Thread fields + _TempStorage &temp_storage; + unsigned int linear_tid; + + + /// Constructor + __device__ __forceinline__ BlockHistogramSort( + TempStorage &temp_storage) + : + temp_storage(temp_storage.Alias()), + linear_tid(RowMajorTid(BLOCK_DIM_X, BLOCK_DIM_Y, BLOCK_DIM_Z)) + {} + + + // Discontinuity functor + struct DiscontinuityOp + { + // Reference to temp_storage + _TempStorage &temp_storage; + + // Constructor + __device__ __forceinline__ DiscontinuityOp(_TempStorage &temp_storage) : + temp_storage(temp_storage) + {} + + // Discontinuity predicate + __device__ __forceinline__ bool operator()(const T &a, const T &b, int b_index) + { + if (a != b) + { + // Note the begin/end offsets in shared storage + temp_storage.discontinuities.run_begin[b] = b_index; + temp_storage.discontinuities.run_end[a] = b_index; + + return true; + } + else + { + return false; + } + } + }; + + + // Composite data onto an existing histogram + template < + typename CounterT > + __device__ __forceinline__ void Composite( + T (&items)[ITEMS_PER_THREAD], ///< [in] Calling thread's input values to histogram + CounterT histogram[BINS]) ///< [out] Reference to shared/device-accessible memory histogram + { + enum { TILE_SIZE = BLOCK_THREADS * ITEMS_PER_THREAD }; + + // Sort bytes in blocked arrangement + BlockRadixSortT(temp_storage.sort).Sort(items); + + CTA_SYNC(); + + // Initialize the shared memory's run_begin and run_end for each bin + int histo_offset = 0; + + #pragma unroll + for(; histo_offset + BLOCK_THREADS <= BINS; histo_offset += BLOCK_THREADS) + { + temp_storage.discontinuities.run_begin[histo_offset + linear_tid] = TILE_SIZE; + temp_storage.discontinuities.run_end[histo_offset + linear_tid] = TILE_SIZE; + } + // Finish up with guarded initialization if necessary + if ((BINS % BLOCK_THREADS != 0) && (histo_offset + linear_tid < BINS)) + { + temp_storage.discontinuities.run_begin[histo_offset + linear_tid] = TILE_SIZE; + temp_storage.discontinuities.run_end[histo_offset + linear_tid] = TILE_SIZE; + } + + CTA_SYNC(); + + int flags[ITEMS_PER_THREAD]; // unused + + // Compute head flags to demarcate contiguous runs of the same bin in the sorted tile + DiscontinuityOp flag_op(temp_storage); + BlockDiscontinuityT(temp_storage.discontinuities.flag).FlagHeads(flags, items, flag_op); + + // Update begin for first item + if (linear_tid == 0) temp_storage.discontinuities.run_begin[items[0]] = 0; + + CTA_SYNC(); + + // Composite into histogram + histo_offset = 0; + + #pragma unroll + for(; histo_offset + BLOCK_THREADS <= BINS; histo_offset += BLOCK_THREADS) + { + int thread_offset = histo_offset + linear_tid; + CounterT count = temp_storage.discontinuities.run_end[thread_offset] - temp_storage.discontinuities.run_begin[thread_offset]; + histogram[thread_offset] += count; + } + + // Finish up with guarded composition if necessary + if ((BINS % BLOCK_THREADS != 0) && (histo_offset + linear_tid < BINS)) + { + int thread_offset = histo_offset + linear_tid; + CounterT count = temp_storage.discontinuities.run_end[thread_offset] - temp_storage.discontinuities.run_begin[thread_offset]; + histogram[thread_offset] += count; + } + } + +}; + +CUB_NAMESPACE_END + diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/block/specializations/block_reduce_raking.cuh b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/block/specializations/block_reduce_raking.cuh new file mode 100644 index 0000000000000000000000000000000000000000..423f18f86797575ea4a2479aaf207c8a850ab6f3 --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/block/specializations/block_reduce_raking.cuh @@ -0,0 +1,221 @@ +/****************************************************************************** + * Copyright (c) 2011, Duane Merrill. All rights reserved. + * Copyright (c) 2011-2018, NVIDIA CORPORATION. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the NVIDIA CORPORATION nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ******************************************************************************/ + +/** + * \file + * cub::BlockReduceRaking provides raking-based methods of parallel reduction across a CUDA thread block. Supports non-commutative reduction operators. + */ + +#pragma once + +#include "../../block/block_raking_layout.cuh" +#include "../../warp/warp_reduce.cuh" +#include "../../thread/thread_reduce.cuh" +#include "../../config.cuh" +#include "../../util_ptx.cuh" + +CUB_NAMESPACE_BEGIN + + +/** + * \brief BlockReduceRaking provides raking-based methods of parallel reduction across a CUDA thread block. Supports non-commutative reduction operators. + * + * Supports non-commutative binary reduction operators. Unlike commutative + * reduction operators (e.g., addition), the application of a non-commutative + * reduction operator (e.g, string concatenation) across a sequence of inputs must + * honor the relative ordering of items and partial reductions when applying the + * reduction operator. + * + * Compared to the implementation of BlockReduceRakingCommutativeOnly (which + * does not support non-commutative operators), this implementation requires a + * few extra rounds of inter-thread communication. + */ +template < + typename T, ///< Data type being reduced + int BLOCK_DIM_X, ///< The thread block length in threads along the X dimension + int BLOCK_DIM_Y, ///< The thread block length in threads along the Y dimension + int BLOCK_DIM_Z, ///< The thread block length in threads along the Z dimension + int LEGACY_PTX_ARCH = 0> ///< The PTX compute capability for which to to specialize this collective +struct BlockReduceRaking +{ + /// Constants + enum + { + /// The thread block size in threads + BLOCK_THREADS = BLOCK_DIM_X * BLOCK_DIM_Y * BLOCK_DIM_Z, + }; + + /// Layout type for padded thread block raking grid + typedef BlockRakingLayout BlockRakingLayout; + + /// WarpReduce utility type + typedef typename WarpReduce::InternalWarpReduce WarpReduce; + + /// Constants + enum + { + /// Number of raking threads + RAKING_THREADS = BlockRakingLayout::RAKING_THREADS, + + /// Number of raking elements per warp synchronous raking thread + SEGMENT_LENGTH = BlockRakingLayout::SEGMENT_LENGTH, + + /// Cooperative work can be entirely warp synchronous + WARP_SYNCHRONOUS = (int(RAKING_THREADS) == int(BLOCK_THREADS)), + + /// Whether or not warp-synchronous reduction should be unguarded (i.e., the warp-reduction elements is a power of two + WARP_SYNCHRONOUS_UNGUARDED = PowerOfTwo::VALUE, + + /// Whether or not accesses into smem are unguarded + RAKING_UNGUARDED = BlockRakingLayout::UNGUARDED, + + }; + + + /// Shared memory storage layout type + union _TempStorage + { + typename WarpReduce::TempStorage warp_storage; ///< Storage for warp-synchronous reduction + typename BlockRakingLayout::TempStorage raking_grid; ///< Padded thread block raking grid + }; + + + /// Alias wrapper allowing storage to be unioned + struct TempStorage : Uninitialized<_TempStorage> {}; + + + // Thread fields + _TempStorage &temp_storage; + unsigned int linear_tid; + + + /// Constructor + __device__ __forceinline__ BlockReduceRaking( + TempStorage &temp_storage) + : + temp_storage(temp_storage.Alias()), + linear_tid(RowMajorTid(BLOCK_DIM_X, BLOCK_DIM_Y, BLOCK_DIM_Z)) + {} + + + template + __device__ __forceinline__ T RakingReduction( + ReductionOp reduction_op, ///< [in] Binary reduction operator + T *raking_segment, + T partial, ///< [in] [lane0 only] Warp-wide aggregate reduction of input items + int num_valid, ///< [in] Number of valid elements (may be less than BLOCK_THREADS) + Int2Type /*iteration*/) + { + // Update partial if addend is in range + if ((IS_FULL_TILE && RAKING_UNGUARDED) || ((linear_tid * SEGMENT_LENGTH) + ITERATION < num_valid)) + { + T addend = raking_segment[ITERATION]; + partial = reduction_op(partial, addend); + } + return RakingReduction(reduction_op, raking_segment, partial, num_valid, Int2Type()); + } + + template + __device__ __forceinline__ T RakingReduction( + ReductionOp /*reduction_op*/, ///< [in] Binary reduction operator + T * /*raking_segment*/, + T partial, ///< [in] [lane0 only] Warp-wide aggregate reduction of input items + int /*num_valid*/, ///< [in] Number of valid elements (may be less than BLOCK_THREADS) + Int2Type /*iteration*/) + { + return partial; + } + + + + /// Computes a thread block-wide reduction using the specified reduction operator. The first num_valid threads each contribute one reduction partial. The return value is only valid for thread0. + template < + bool IS_FULL_TILE, + typename ReductionOp> + __device__ __forceinline__ T Reduce( + T partial, ///< [in] Calling thread's input partial reductions + int num_valid, ///< [in] Number of valid elements (may be less than BLOCK_THREADS) + ReductionOp reduction_op) ///< [in] Binary reduction operator + { + if (WARP_SYNCHRONOUS) + { + // Short-circuit directly to warp synchronous reduction (unguarded if active threads is a power-of-two) + partial = WarpReduce(temp_storage.warp_storage).template Reduce( + partial, + num_valid, + reduction_op); + } + else + { + // Place partial into shared memory grid. + *BlockRakingLayout::PlacementPtr(temp_storage.raking_grid, linear_tid) = partial; + + CTA_SYNC(); + + // Reduce parallelism to one warp + if (linear_tid < RAKING_THREADS) + { + // Raking reduction in grid + T *raking_segment = BlockRakingLayout::RakingPtr(temp_storage.raking_grid, linear_tid); + partial = raking_segment[0]; + + partial = RakingReduction(reduction_op, raking_segment, partial, num_valid, Int2Type<1>()); + + int valid_raking_threads = (IS_FULL_TILE) ? + RAKING_THREADS : + (num_valid + SEGMENT_LENGTH - 1) / SEGMENT_LENGTH; + + partial = WarpReduce(temp_storage.warp_storage).template Reduce( + partial, + valid_raking_threads, + reduction_op); + + } + } + + return partial; + } + + + /// Computes a thread block-wide reduction using addition (+) as the reduction operator. The first num_valid threads each contribute one reduction partial. The return value is only valid for thread0. + template + __device__ __forceinline__ T Sum( + T partial, ///< [in] Calling thread's input partial reductions + int num_valid) ///< [in] Number of valid elements (may be less than BLOCK_THREADS) + { + cub::Sum reduction_op; + + return Reduce(partial, num_valid, reduction_op); + } + + + +}; + +CUB_NAMESPACE_END + diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/block/specializations/block_reduce_warp_reductions.cuh b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/block/specializations/block_reduce_warp_reductions.cuh new file mode 100644 index 0000000000000000000000000000000000000000..1e51a9fcfe101ac07ac4522500bcd53e2c97498a --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/block/specializations/block_reduce_warp_reductions.cuh @@ -0,0 +1,214 @@ +/****************************************************************************** + * Copyright (c) 2011, Duane Merrill. All rights reserved. + * Copyright (c) 2011-2018, NVIDIA CORPORATION. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the NVIDIA CORPORATION nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ******************************************************************************/ + +/** + * \file + * cub::BlockReduceWarpReductions provides variants of warp-reduction-based parallel reduction across a CUDA thread block. Supports non-commutative reduction operators. + */ + +#pragma once + +#include +#include +#include +#include + +CUB_NAMESPACE_BEGIN + + +/** + * \brief BlockReduceWarpReductions provides variants of warp-reduction-based parallel reduction across a CUDA thread block. Supports non-commutative reduction operators. + */ +template < + typename T, ///< Data type being reduced + int BLOCK_DIM_X, ///< The thread block length in threads along the X dimension + int BLOCK_DIM_Y, ///< The thread block length in threads along the Y dimension + int BLOCK_DIM_Z, ///< The thread block length in threads along the Z dimension + int LEGACY_PTX_ARCH = 0> ///< The PTX compute capability for which to to specialize this collective +struct BlockReduceWarpReductions +{ + /// Constants + enum + { + /// The thread block size in threads + BLOCK_THREADS = BLOCK_DIM_X * BLOCK_DIM_Y * BLOCK_DIM_Z, + + /// Number of warp threads + WARP_THREADS = CUB_WARP_THREADS(0), + + /// Number of active warps + WARPS = (BLOCK_THREADS + WARP_THREADS - 1) / WARP_THREADS, + + /// The logical warp size for warp reductions + LOGICAL_WARP_SIZE = CUB_MIN(BLOCK_THREADS, WARP_THREADS), + + /// Whether or not the logical warp size evenly divides the thread block size + EVEN_WARP_MULTIPLE = (BLOCK_THREADS % LOGICAL_WARP_SIZE == 0) + }; + + + /// WarpReduce utility type + typedef typename WarpReduce::InternalWarpReduce WarpReduce; + + + /// Shared memory storage layout type + struct _TempStorage + { + typename WarpReduce::TempStorage warp_reduce[WARPS]; ///< Buffer for warp-synchronous reduction + T warp_aggregates[WARPS]; ///< Shared totals from each warp-synchronous reduction + T block_prefix; ///< Shared prefix for the entire thread block + }; + + /// Alias wrapper allowing storage to be unioned + struct TempStorage : Uninitialized<_TempStorage> {}; + + + // Thread fields + _TempStorage &temp_storage; + int linear_tid; + int warp_id; + int lane_id; + + + /// Constructor + __device__ __forceinline__ BlockReduceWarpReductions( + TempStorage &temp_storage) + : + temp_storage(temp_storage.Alias()), + linear_tid(RowMajorTid(BLOCK_DIM_X, BLOCK_DIM_Y, BLOCK_DIM_Z)), + warp_id((WARPS == 1) ? 0 : linear_tid / WARP_THREADS), + lane_id(LaneId()) + {} + + + template + __device__ __forceinline__ T ApplyWarpAggregates( + ReductionOp reduction_op, ///< [in] Binary reduction operator + T warp_aggregate, ///< [in] [lane0 only] Warp-wide aggregate reduction of input items + int num_valid, ///< [in] Number of valid elements (may be less than BLOCK_THREADS) + Int2Type /*successor_warp*/) + { + if (FULL_TILE || (SUCCESSOR_WARP * LOGICAL_WARP_SIZE < num_valid)) + { + T addend = temp_storage.warp_aggregates[SUCCESSOR_WARP]; + warp_aggregate = reduction_op(warp_aggregate, addend); + } + return ApplyWarpAggregates(reduction_op, warp_aggregate, num_valid, Int2Type()); + } + + template + __device__ __forceinline__ T ApplyWarpAggregates( + ReductionOp /*reduction_op*/, ///< [in] Binary reduction operator + T warp_aggregate, ///< [in] [lane0 only] Warp-wide aggregate reduction of input items + int /*num_valid*/, ///< [in] Number of valid elements (may be less than BLOCK_THREADS) + Int2Type /*successor_warp*/) + { + return warp_aggregate; + } + + + /// Returns block-wide aggregate in thread0. + template < + bool FULL_TILE, + typename ReductionOp> + __device__ __forceinline__ T ApplyWarpAggregates( + ReductionOp reduction_op, ///< [in] Binary reduction operator + T warp_aggregate, ///< [in] [lane0 only] Warp-wide aggregate reduction of input items + int num_valid) ///< [in] Number of valid elements (may be less than BLOCK_THREADS) + { + // Share lane aggregates + if (lane_id == 0) + { + detail::uninitialized_copy(temp_storage.warp_aggregates + warp_id, + warp_aggregate); + } + + CTA_SYNC(); + + // Update total aggregate in warp 0, lane 0 + if (linear_tid == 0) + { + warp_aggregate = ApplyWarpAggregates(reduction_op, warp_aggregate, num_valid, Int2Type<1>()); + } + + return warp_aggregate; + } + + + /// Computes a thread block-wide reduction using addition (+) as the reduction operator. The first num_valid threads each contribute one reduction partial. The return value is only valid for thread0. + template + __device__ __forceinline__ T Sum( + T input, ///< [in] Calling thread's input partial reductions + int num_valid) ///< [in] Number of valid elements (may be less than BLOCK_THREADS) + { + cub::Sum reduction_op; + int warp_offset = (warp_id * LOGICAL_WARP_SIZE); + int warp_num_valid = ((FULL_TILE && EVEN_WARP_MULTIPLE) || (warp_offset + LOGICAL_WARP_SIZE <= num_valid)) ? + LOGICAL_WARP_SIZE : + num_valid - warp_offset; + + // Warp reduction in every warp + T warp_aggregate = WarpReduce(temp_storage.warp_reduce[warp_id]).template Reduce<(FULL_TILE && EVEN_WARP_MULTIPLE)>( + input, + warp_num_valid, + cub::Sum()); + + // Update outputs and block_aggregate with warp-wide aggregates from lane-0s + return ApplyWarpAggregates(reduction_op, warp_aggregate, num_valid); + } + + + /// Computes a thread block-wide reduction using the specified reduction operator. The first num_valid threads each contribute one reduction partial. The return value is only valid for thread0. + template < + bool FULL_TILE, + typename ReductionOp> + __device__ __forceinline__ T Reduce( + T input, ///< [in] Calling thread's input partial reductions + int num_valid, ///< [in] Number of valid elements (may be less than BLOCK_THREADS) + ReductionOp reduction_op) ///< [in] Binary reduction operator + { + int warp_offset = warp_id * LOGICAL_WARP_SIZE; + int warp_num_valid = ((FULL_TILE && EVEN_WARP_MULTIPLE) || (warp_offset + LOGICAL_WARP_SIZE <= num_valid)) ? + LOGICAL_WARP_SIZE : + num_valid - warp_offset; + + // Warp reduction in every warp + T warp_aggregate = WarpReduce(temp_storage.warp_reduce[warp_id]).template Reduce<(FULL_TILE && EVEN_WARP_MULTIPLE)>( + input, + warp_num_valid, + reduction_op); + + // Update outputs and block_aggregate with warp-wide aggregates from lane-0s + return ApplyWarpAggregates(reduction_op, warp_aggregate, num_valid); + } + +}; + + +CUB_NAMESPACE_END + diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/device/device_copy.cuh b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/device/device_copy.cuh new file mode 100644 index 0000000000000000000000000000000000000000..445f5d862bc87c612f635efb4a12b6d60ec4617d --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/device/device_copy.cuh @@ -0,0 +1,172 @@ +/****************************************************************************** + * Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the NVIDIA CORPORATION nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ******************************************************************************/ + +/** + * \file + * cub::DeviceCopy provides device-wide, parallel operations for copying data. + */ + +#pragma once + +#include +#include + +#include + +#include + +CUB_NAMESPACE_BEGIN + +/** + * @brief cub::DeviceCopy provides device-wide, parallel operations for copying data. + * \ingroup SingleModule + */ +struct DeviceCopy +{ + /** + * @brief Copies data from a batch of given source ranges to their corresponding destination + * ranges. + * @note If any input range aliases any output range the behavior is undefined. If + * any output range aliases another output range the behavior is undefined. Input + * ranges can alias one another. + * + * @par Snippet + * The code snippet below illustrates usage of DeviceCopy::Batched to perform a DeviceRunLength + * Decode operation. + * @par + * @code + * struct GetIteratorToRange + * { + * __host__ __device__ __forceinline__ auto operator()(uint32_t index) + * { + * return thrust::make_constant_iterator(d_data_in[index]); + * } + * int32_t *d_data_in; + * }; + * + * struct GetPtrToRange + * { + * __host__ __device__ __forceinline__ auto operator()(uint32_t index) + * { + * return d_data_out + d_offsets[index]; + * } + * int32_t *d_data_out; + * uint32_t *d_offsets; + * }; + * + * struct GetRunLength + * { + * __host__ __device__ __forceinline__ uint32_t operator()(uint32_t index) + * { + * return d_offsets[index + 1] - d_offsets[index]; + * } + * uint32_t *d_offsets; + * }; + * + * uint32_t num_ranges = 5; + * int32_t *d_data_in; // e.g., [4, 2, 7, 3, 1] + * int32_t *d_data_out; // e.g., [0, ... ] + * uint32_t *d_offsets; // e.g., [0, 2, 5, 6, 9, 14] + * + * // Returns a constant iterator to the element of the i-th run + * thrust::counting_iterator iota(0); + * auto iterators_in = thrust::make_transform_iterator(iota, GetIteratorToRange{d_data_in}); + * + * // Returns the run length of the i-th run + * auto sizes = thrust::make_transform_iterator(iota, GetRunLength{d_offsets}); + * + * // Returns pointers to the output range for each run + * auto ptrs_out = thrust::make_transform_iterator(iota, GetPtrToRange{d_data_out, d_offsets}); + * + * // Determine temporary device storage requirements + * void *d_temp_storage = nullptr; + * size_t temp_storage_bytes = 0; + * cub::DeviceCopy::Batched(d_temp_storage, temp_storage_bytes, iterators_in, ptrs_out, sizes, + * num_ranges); + * + * // Allocate temporary storage + * cudaMalloc(&d_temp_storage, temp_storage_bytes); + * + * // Run batched copy algorithm (used to perform runlength decoding) + * cub::DeviceCopy::Batched(d_temp_storage, temp_storage_bytes, iterators_in, ptrs_out, sizes, + * num_ranges); + * + * // d_data_out <-- [4, 4, 2, 2, 2, 7, 3, 3, 3, 1, 1, 1, 1, 1] + * @endcode + * @tparam InputIt [inferred] Device-accessible random-access input iterator type + * providing the iterators to the source ranges + * @tparam OutputIt [inferred] Device-accessible random-access input iterator type + * providing the iterators to the destination ranges + * @tparam SizeIteratorT [inferred] Device-accessible random-access input iterator + * type providing the number of items to be copied for each pair of ranges + * @param d_temp_storage [in] Device-accessible allocation of temporary storage. When NULL, the + * required allocation size is written to \p temp_storage_bytes and no work is done. + * @param temp_storage_bytes [in,out] Reference to size in bytes of \p d_temp_storage allocation + * @param input_it [in] Device-accessible iterator providing the iterators to the source + * ranges + * @param output_it [in] Device-accessible iterator providing the iterators to the + * destination ranges + * @param sizes [in] Device-accessible iterator providing the number of elements to be copied + * for each pair of ranges + * @param num_ranges [in] The total number of range pairs + * @param stream [in] [optional] CUDA stream to launch kernels within. Default is + * stream0. + */ + template + CUB_RUNTIME_FUNCTION static cudaError_t Batched(void *d_temp_storage, + size_t &temp_storage_bytes, + InputIt input_it, + OutputIt output_it, + SizeIteratorT sizes, + uint32_t num_ranges, + cudaStream_t stream = 0) + { + // Integer type large enough to hold any offset in [0, num_ranges) + using RangeOffsetT = uint32_t; + + // Integer type large enough to hold any offset in [0, num_thread_blocks_launched), where a safe + // uppper bound on num_thread_blocks_launched can be assumed to be given by + // IDIV_CEIL(num_ranges, 64) + using BlockOffsetT = uint32_t; + + return detail::DispatchBatchMemcpy, + false>::Dispatch(d_temp_storage, + temp_storage_bytes, + input_it, + output_it, + sizes, + num_ranges, + stream); + } +}; + +CUB_NAMESPACE_END diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/device/device_histogram.cuh b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/device/device_histogram.cuh new file mode 100644 index 0000000000000000000000000000000000000000..4e71c04ed82e3a2f7814b55607ae39a0ec793d61 --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/device/device_histogram.cuh @@ -0,0 +1,1672 @@ +/****************************************************************************** + * Copyright (c) 2011, Duane Merrill. All rights reserved. + * Copyright (c) 2011-2022, NVIDIA CORPORATION. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the NVIDIA CORPORATION nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ******************************************************************************/ + +/** + * @file cub::DeviceHistogram provides device-wide parallel operations for + * constructing histogram(s) from a sequence of samples data residing + * within device-accessible memory. + */ + +#pragma once + +#include +#include +#include + +#include +#include +#include + +CUB_NAMESPACE_BEGIN + + +/** + * @brief DeviceHistogram provides device-wide parallel operations for + * constructing histogram(s) from a sequence of samples data residing + * within device-accessible memory. ![](histogram_logo.png) + * @ingroup SingleModule + * + * @par Overview + * A histogram + * counts the number of observations that fall into each of the disjoint categories (known as bins). + * + * @par Usage Considerations + * @cdp_class{DeviceHistogram} + * + */ +struct DeviceHistogram +{ + /******************************************************************//** + * @name Evenly-segmented bin ranges + *********************************************************************/ + //@{ + + /** + * @brief Computes an intensity histogram from a sequence of data samples + * using equal-width bins. + * + * @par + * - The number of histogram bins is (`num_levels - 1`) + * - All bins comprise the same width of sample values: + * `(upper_level - lower_level) / (num_levels - 1)`. + * - If the common type of `SampleT` and `LevelT` is of integral type, the bin for a sample is + * computed as `(sample - lower_level) * (num_levels - 1) / (upper_level - lower_level)`, round + * down to the nearest whole number. To protect against potential overflows, if the product + * `(upper_level - lower_level) * (num_levels - 1)` exceeds the number representable by an + * `uint64_t`, the cuda error `cudaErrorInvalidValue` is returned. If the common type is 128 + * bits wide, bin computation will use 128-bit arithmetic and `cudaErrorInvalidValue` will only + * be returned if bin computation would overflow for 128-bit arithmetic. + * - The ranges `[d_samples, d_samples + num_samples)` and + * `[d_histogram, d_histogram + num_levels - 1)` shall not overlap + * in any way. + * - `cuda::std::common_type` must be valid, and both LevelT + * and SampleT must be valid arithmetic types. The common type must be + * convertible to `int` and trivially copyable. + * - @devicestorage + * + * @par Snippet + * The code snippet below illustrates the computation of a six-bin histogram + * from a sequence of float samples + * + * @par + * @code + * #include // or equivalently + * + * // Declare, allocate, and initialize device-accessible pointers for + * // input samples and output histogram + * int num_samples; // e.g., 10 + * float* d_samples; // e.g., [2.2, 6.1, 7.1, 2.9, 3.5, 0.3, 2.9, 2.1, 6.1, 999.5] + * int* d_histogram; // e.g., [ -, -, -, -, -, -] + * int num_levels; // e.g., 7 (seven level boundaries for six bins) + * float lower_level; // e.g., 0.0 (lower sample value boundary of lowest bin) + * float upper_level; // e.g., 12.0 (upper sample value boundary of upper bin) + * ... + * + * // Determine temporary device storage requirements + * void* d_temp_storage = NULL; + * size_t temp_storage_bytes = 0; + * cub::DeviceHistogram::HistogramEven( + * d_temp_storage, temp_storage_bytes, + * d_samples, d_histogram, num_levels, + * lower_level, upper_level, num_samples); + * + * // Allocate temporary storage + * cudaMalloc(&d_temp_storage, temp_storage_bytes); + * + * // Compute histograms + * cub::DeviceHistogram::HistogramEven( + * d_temp_storage, temp_storage_bytes, + * d_samples, d_histogram, num_levels, + * lower_level, upper_level, num_samples); + * + * // d_histogram <-- [1, 5, 0, 3, 0, 0]; + * @endcode + * + * @tparam SampleIteratorT + * **[inferred]** Random-access input iterator type for reading input + * samples \iterator + * + * @tparam CounterT + * **[inferred]** Integer type for histogram bin counters + * + * @tparam LevelT + * **[inferred]** Type for specifying boundaries (levels) + * + * @tparam OffsetT + * **[inferred]** Signed integer type for sequence offsets, list lengths, + * pointer differences, etc. \offset_size1 + * + * @param[in] d_temp_storage + * Device-accessible allocation of temporary storage. When `nullptr`, the + * required allocation size is written to `temp_storage_bytes` and no + * work is done. + * + * @param[in,out] temp_storage_bytes + * Reference to size in bytes of `d_temp_storage` allocation + * + * @param[in] d_samples + * The pointer to the input sequence of data samples. + * + * @param[out] d_histogram + * The pointer to the histogram counter output array of length + * `num_levels - 1`. + * + * @param[in] num_levels + * The number of boundaries (levels) for delineating histogram samples. + * Implies that the number of bins is `num_levels - 1`. + * + * @param[in] lower_level + * The lower sample value bound (inclusive) for the lowest histogram bin. + * + * @param[in] upper_level + * The upper sample value bound (exclusive) for the highest histogram bin. + * + * @param[in] num_samples + * The number of input samples (i.e., the length of `d_samples`) + * + * @param[in] stream + * **[optional]** CUDA stream to launch kernels within. + * Default is stream0. + */ + template + CUB_RUNTIME_FUNCTION static cudaError_t + HistogramEven(void *d_temp_storage, + size_t &temp_storage_bytes, + SampleIteratorT d_samples, + CounterT *d_histogram, + int num_levels, + LevelT lower_level, + LevelT upper_level, + OffsetT num_samples, + cudaStream_t stream = 0) + { + /// The sample value type of the input iterator + using SampleT = cub::detail::value_t; + + CounterT *d_histogram1[1] = {d_histogram}; + int num_levels1[1] = {num_levels}; + LevelT lower_level1[1] = {lower_level}; + LevelT upper_level1[1] = {upper_level}; + + return MultiHistogramEven<1, 1>(d_temp_storage, + temp_storage_bytes, + d_samples, + d_histogram1, + num_levels1, + lower_level1, + upper_level1, + num_samples, + static_cast(1), + sizeof(SampleT) * num_samples, + stream); + } + + template + CUB_DETAIL_RUNTIME_DEBUG_SYNC_IS_NOT_SUPPORTED + CUB_RUNTIME_FUNCTION static cudaError_t + HistogramEven(void *d_temp_storage, + size_t &temp_storage_bytes, + SampleIteratorT d_samples, + CounterT *d_histogram, + int num_levels, + LevelT lower_level, + LevelT upper_level, + OffsetT num_samples, + cudaStream_t stream, + bool debug_synchronous) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + + return HistogramEven(d_temp_storage, + temp_storage_bytes, + d_samples, + d_histogram, + num_levels, + lower_level, + upper_level, + num_samples, + stream); + } + + /** + * @brief Computes an intensity histogram from a sequence of data samples + * using equal-width bins. + * + * @par + * - A two-dimensional *region of interest* within `d_samples` can be + * specified using the `num_row_samples`, `num_rows`, and + * `row_stride_bytes` parameters. + * - The row stride must be a whole multiple of the sample data type + * size, i.e., `(row_stride_bytes % sizeof(SampleT)) == 0`. + * - The number of histogram bins is (`num_levels - 1`) + * - All bins comprise the same width of sample values: + * `(upper_level - lower_level) / (num_levels - 1)` + * - If the common type of `SampleT` and `LevelT` is of integral type, the bin for a sample is + * computed as `(sample - lower_level) * (num_levels - 1) / (upper_level - lower_level)`, round + * down to the nearest whole number. To protect against potential overflows, if the product + * `(upper_level - lower_level) * (num_levels - 1)` exceeds the number representable by an + * `uint64_t`, the cuda error `cudaErrorInvalidValue` is returned. If the common type is 128 + * bits wide, bin computation will use 128-bit arithmetic and `cudaErrorInvalidValue` will only + * be returned if bin computation would overflow for 128-bit arithmetic. + * - For a given row `r` in `[0, num_rows)`, let + * `row_begin = d_samples + r * row_stride_bytes / sizeof(SampleT)` and + * `row_end = row_begin + num_row_samples`. The ranges + * `[row_begin, row_end)` and `[d_histogram, d_histogram + num_levels - 1)` + * shall not overlap in any way. + * - `cuda::std::common_type` must be valid, and both LevelT + * and SampleT must be valid arithmetic types. The common type must be + * convertible to `int` and trivially copyable. + * - @devicestorage + * + * @par Snippet + * The code snippet below illustrates the computation of a six-bin histogram + * from a 2x5 region of interest within a flattened 2x7 array of float samples. + * + * @par + * @code + * #include // or equivalently + * + * // Declare, allocate, and initialize device-accessible pointers for + * // input samples and output histogram + * int num_row_samples; // e.g., 5 + * int num_rows; // e.g., 2; + * size_t row_stride_bytes; // e.g., 7 * sizeof(float) + * float* d_samples; // e.g., [2.2, 6.1, 7.1, 2.9, 3.5, -, -, + * // 0.3, 2.9, 2.1, 6.1, 999.5, -, -] + * int* d_histogram; // e.g., [ -, -, -, -, -, -] + * int num_levels; // e.g., 7 (seven level boundaries for six bins) + * float lower_level; // e.g., 0.0 (lower sample value boundary of lowest bin) + * float upper_level; // e.g., 12.0 (upper sample value boundary of upper bin) + * ... + * + * // Determine temporary device storage requirements + * void* d_temp_storage = NULL; + * size_t temp_storage_bytes = 0; + * cub::DeviceHistogram::HistogramEven( + * d_temp_storage, temp_storage_bytes, + * d_samples, d_histogram, num_levels, lower_level, upper_level, + * num_row_samples, num_rows, row_stride_bytes); + * + * // Allocate temporary storage + * cudaMalloc(&d_temp_storage, temp_storage_bytes); + * + * // Compute histograms + * cub::DeviceHistogram::HistogramEven( + * d_temp_storage, temp_storage_bytes, d_samples, d_histogram, + * d_samples, d_histogram, num_levels, lower_level, upper_level, + * num_row_samples, num_rows, row_stride_bytes); + * + * // d_histogram <-- [1, 5, 0, 3, 0, 0]; + * @endcode + * + * @tparam SampleIteratorT + * **[inferred]** Random-access input iterator type for reading + * input samples. \iterator + * + * @tparam CounterT + * **[inferred]** Integer type for histogram bin counters + * + * @tparam LevelT + * **[inferred]** Type for specifying boundaries (levels) + * + * @tparam OffsetT + * **[inferred]** Signed integer type for sequence offsets, list lengths, + * pointer differences, etc. \offset_size1 + + * @param[in] d_temp_storage + * Device-accessible allocation of temporary storage. When `nullptr`, the + * required allocation size is written to `temp_storage_bytes` and no + * work is done. + * + * @param[in,out] temp_storage_bytes + * Reference to size in bytes of `d_temp_storage` allocation + * + * @param[in] d_samples + * The pointer to the input sequence of data samples. + * + * @param[out] d_histogram + * The pointer to the histogram counter output array of + * length `num_levels - 1`. + * + * @param[in] num_levels + * The number of boundaries (levels) for delineating histogram samples. + * Implies that the number of bins is `num_levels - 1`. + * + * @param[in] lower_level + * The lower sample value bound (inclusive) for the lowest histogram bin. + * + * @param[in] upper_level + * The upper sample value bound (exclusive) for the highest histogram bin. + * + * @param[in] num_row_samples + * The number of data samples per row in the region of interest + * + * @param[in] num_rows + * The number of rows in the region of interest + * + * @param[in] row_stride_bytes + * The number of bytes between starts of consecutive rows in + * the region of interest + * + * @param[in] stream + * **[optional]** CUDA stream to launch kernels within. + * Default is stream0. + */ + template + CUB_RUNTIME_FUNCTION static cudaError_t + HistogramEven(void *d_temp_storage, + size_t &temp_storage_bytes, + SampleIteratorT d_samples, + CounterT *d_histogram, + int num_levels, + LevelT lower_level, + LevelT upper_level, + OffsetT num_row_samples, + OffsetT num_rows, + size_t row_stride_bytes, + cudaStream_t stream = 0) + { + CounterT *d_histogram1[1] = {d_histogram}; + int num_levels1[1] = {num_levels}; + LevelT lower_level1[1] = {lower_level}; + LevelT upper_level1[1] = {upper_level}; + + return MultiHistogramEven<1, 1>(d_temp_storage, + temp_storage_bytes, + d_samples, + d_histogram1, + num_levels1, + lower_level1, + upper_level1, + num_row_samples, + num_rows, + row_stride_bytes, + stream); + } + + template + CUB_DETAIL_RUNTIME_DEBUG_SYNC_IS_NOT_SUPPORTED + CUB_RUNTIME_FUNCTION static cudaError_t + HistogramEven(void *d_temp_storage, + size_t &temp_storage_bytes, + SampleIteratorT d_samples, + CounterT *d_histogram, + int num_levels, + LevelT lower_level, + LevelT upper_level, + OffsetT num_row_samples, + OffsetT num_rows, + size_t row_stride_bytes, + cudaStream_t stream, + bool debug_synchronous) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + + return HistogramEven(d_temp_storage, + temp_storage_bytes, + d_samples, + d_histogram, + num_levels, + lower_level, + upper_level, + num_row_samples, + num_rows, + row_stride_bytes, + stream); + } + + /** + * @brief Computes per-channel intensity histograms from a sequence of + * multi-channel "pixel" data samples using equal-width bins. + * + * @par + * - The input is a sequence of *pixel* structures, where each pixel comprises + * a record of `NUM_CHANNELS` consecutive data samples + * (e.g., an *RGBA* pixel). + * - Of the `NUM_CHANNELS` specified, the function will only compute + * histograms for the first `NUM_ACTIVE_CHANNELS` + * (e.g., only *RGB* histograms from *RGBA* pixel samples). + * - The number of histogram bins for channeli is + * `num_levels[i] - 1`. + * - For channeli, the range of values for all histogram bins + * have the same width: + * `(upper_level[i] - lower_level[i]) / (num_levels[i] - 1)` + * - If the common type of sample and level is of integral type, the bin for a sample is + * computed as `(sample - lower_level[i]) * (num_levels - 1) / (upper_level[i] - + * lower_level[i])`, round down to the nearest whole number. To protect against potential + * overflows, if, for any channel `i`, the product `(upper_level[i] - lower_level[i]) * + * (num_levels[i] - 1)` exceeds the number representable by an `uint64_t`, the cuda error + * `cudaErrorInvalidValue` is returned. If the common type is 128 bits wide, bin computation + * will use 128-bit arithmetic and `cudaErrorInvalidValue` will only be returned if bin + * computation would overflow for 128-bit arithmetic. + * - For a given channel `c` in `[0, NUM_ACTIVE_CHANNELS)`, the ranges + * `[d_samples, d_samples + NUM_CHANNELS * num_pixels)` and + * `[d_histogram[c], d_histogram[c] + num_levels[c] - 1)` shall not overlap + * in any way. + * - `cuda::std::common_type` must be valid, and both LevelT + * and SampleT must be valid arithmetic types. The common type must be + * convertible to `int` and trivially copyable. + * - @devicestorage + * + * @par Snippet + * The code snippet below illustrates the computation of three 256-bin RGB histograms + * from a quad-channel sequence of RGBA pixels (8 bits per channel per pixel) + * + * @par + * @code + * #include // or equivalently + * + * // Declare, allocate, and initialize device-accessible pointers for + * // input samples and output histograms + * int num_pixels; // e.g., 5 + * unsigned char* d_samples; // e.g., [(2, 6, 7, 5), (3, 0, 2, 1), (7, 0, 6, 2), + * // (0, 6, 7, 5), (3, 0, 2, 6)] + * int* d_histogram[3]; // e.g., three device pointers to three device buffers, + * // each allocated with 256 integer counters + * int num_levels[3]; // e.g., {257, 257, 257}; + * unsigned int lower_level[3]; // e.g., {0, 0, 0}; + * unsigned int upper_level[3]; // e.g., {256, 256, 256}; + * ... + * + * // Determine temporary device storage requirements + * void* d_temp_storage = NULL; + * size_t temp_storage_bytes = 0; + * cub::DeviceHistogram::MultiHistogramEven<4, 3>( + * d_temp_storage, temp_storage_bytes, + * d_samples, d_histogram, num_levels, + * lower_level, upper_level, num_pixels); + * + * // Allocate temporary storage + * cudaMalloc(&d_temp_storage, temp_storage_bytes); + * + * // Compute histograms + * cub::DeviceHistogram::MultiHistogramEven<4, 3>( + * d_temp_storage, temp_storage_bytes, + * d_samples, d_histogram, num_levels, + * lower_level, upper_level, num_pixels); + * + * // d_histogram <-- [ [1, 0, 1, 2, 0, 0, 0, 1, 0, 0, 0, ..., 0], + * // [0, 3, 0, 0, 0, 0, 2, 0, 0, 0, 0, ..., 0], + * // [0, 0, 2, 0, 0, 0, 1, 2, 0, 0, 0, ..., 0] ] + * @endcode + * + * @tparam NUM_CHANNELS + * Number of channels interleaved in the input data (may be greater than + * the number of channels being actively histogrammed) + * + * @tparam NUM_ACTIVE_CHANNELS + * **[inferred]** Number of channels actively being histogrammed + * + * @tparam SampleIteratorT + * **[inferred]** Random-access input iterator type for reading + * input samples. \iterator + * + * @tparam CounterT + * **[inferred]** Integer type for histogram bin counters + * + * @tparam LevelT + * **[inferred]** Type for specifying boundaries (levels) + * + * @tparam OffsetT + * **[inferred]** Signed integer type for sequence offsets, list lengths, + * pointer differences, etc. \offset_size1 + * + * @param[in] d_temp_storage + * Device-accessible allocation of temporary storage. When `nullptr`, the + * required allocation size is written to `temp_storage_bytes` and no + * work is done. + * + * @param[in,out] temp_storage_bytes + * Reference to size in bytes of `d_temp_storage` allocation + * + * @param[in] d_samples + * The pointer to the multi-channel input sequence of data samples. + * The samples from different channels are assumed to be interleaved + * (e.g., an array of 32-bit pixels where each pixel consists of four + * *RGBA* 8-bit samples). + * + * @param[out] d_histogram + * The pointers to the histogram counter output arrays, one for each active + * channel. For channeli, the allocation length of + * `d_histogram[i]` should be `num_levels[i] - 1`. + * + * @param[in] num_levels + * The number of boundaries (levels) for delineating histogram samples in + * each active channel. Implies that the number of bins for + * channeli is `num_levels[i] - 1`. + * + * @param[in] lower_level + * The lower sample value bound (inclusive) for the lowest histogram bin in + * each active channel. + * + * @param[in] upper_level + * The upper sample value bound (exclusive) for the highest histogram bin + * in each active channel. + * + * @param[in] num_pixels + * The number of multi-channel pixels + * (i.e., the length of `d_samples / NUM_CHANNELS`) + * + * @param[in] stream + * **[optional]** CUDA stream to launch kernels within. + * Default is stream0. + */ + template + CUB_RUNTIME_FUNCTION static cudaError_t + MultiHistogramEven(void *d_temp_storage, + size_t &temp_storage_bytes, + SampleIteratorT d_samples, + CounterT *d_histogram[NUM_ACTIVE_CHANNELS], + int num_levels[NUM_ACTIVE_CHANNELS], + LevelT lower_level[NUM_ACTIVE_CHANNELS], + LevelT upper_level[NUM_ACTIVE_CHANNELS], + OffsetT num_pixels, + cudaStream_t stream = 0) + { + /// The sample value type of the input iterator + using SampleT = cub::detail::value_t; + + return MultiHistogramEven( + d_temp_storage, + temp_storage_bytes, + d_samples, + d_histogram, + num_levels, + lower_level, + upper_level, + num_pixels, + static_cast(1), + sizeof(SampleT) * NUM_CHANNELS * num_pixels, + stream); + } + + template + CUB_DETAIL_RUNTIME_DEBUG_SYNC_IS_NOT_SUPPORTED + CUB_RUNTIME_FUNCTION static cudaError_t + MultiHistogramEven(void *d_temp_storage, + size_t &temp_storage_bytes, + SampleIteratorT d_samples, + CounterT *d_histogram[NUM_ACTIVE_CHANNELS], + int num_levels[NUM_ACTIVE_CHANNELS], + LevelT lower_level[NUM_ACTIVE_CHANNELS], + LevelT upper_level[NUM_ACTIVE_CHANNELS], + OffsetT num_pixels, + cudaStream_t stream, + bool debug_synchronous) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + + return MultiHistogramEven(d_temp_storage, + temp_storage_bytes, + d_samples, + d_histogram, + num_levels, + lower_level, + upper_level, + num_pixels, + stream); + } + + /** + * @brief Computes per-channel intensity histograms from a sequence of + * multi-channel "pixel" data samples using equal-width bins. + * + * @par + * - The input is a sequence of *pixel* structures, where each pixel + * comprises a record of `NUM_CHANNELS` consecutive data samples + * (e.g., an *RGBA* pixel). + * - Of the `NUM_CHANNELS` specified, the function will only compute + * histograms for the first `NUM_ACTIVE_CHANNELS` (e.g., only *RGB* + * histograms from *RGBA* pixel samples). + * - A two-dimensional *region of interest* within `d_samples` can be + * specified using the `num_row_samples`, `num_rows`, and + * `row_stride_bytes` parameters. + * - The row stride must be a whole multiple of the sample data type + * size, i.e., `(row_stride_bytes % sizeof(SampleT)) == 0`. + * - The number of histogram bins for channeli is + * `num_levels[i] - 1`. + * - For channeli, the range of values for all histogram + * bins have the same width: + * `(upper_level[i] - lower_level[i]) / (num_levels[i] - 1)` + * - If the common type of sample and level is of integral type, the bin for a sample is + * computed as `(sample - lower_level[i]) * (num_levels - 1) / (upper_level[i] - + * lower_level[i])`, round down to the nearest whole number. To protect against potential + * overflows, if, for any channel `i`, the product `(upper_level[i] - lower_level[i]) * + * (num_levels[i] - 1)` exceeds the number representable by an `uint64_t`, the cuda error + * `cudaErrorInvalidValue` is returned. If the common type is 128 bits wide, bin computation + * will use 128-bit arithmetic and `cudaErrorInvalidValue` will only be returned if bin + * computation would overflow for 128-bit arithmetic. + * - For a given row `r` in `[0, num_rows)`, and sample `s` in + * `[0, num_row_pixels)`, let + * `row_begin = d_samples + r * row_stride_bytes / sizeof(SampleT)`, + * `sample_begin = row_begin + s * NUM_CHANNELS`, and + * `sample_end = sample_begin + NUM_ACTIVE_CHANNELS`. For a given channel + * `c` in `[0, NUM_ACTIVE_CHANNELS)`, the ranges + * `[sample_begin, sample_end)` and + * `[d_histogram[c], d_histogram[c] + num_levels[c] - 1)` shall not overlap + * in any way. + * - `cuda::std::common_type` must be valid, and both LevelT + * and SampleT must be valid arithmetic types. The common type must be + * convertible to `int` and trivially copyable. + * - @devicestorage + * + * @par Snippet + * The code snippet below illustrates the computation of three 256-bin + * *RGB* histograms from a 2x3 region of interest of within a flattened 2x4 + * array of quad-channel *RGBA* pixels (8 bits per channel per pixel). + * + * @par + * @code + * #include // or equivalently + * + * // Declare, allocate, and initialize device-accessible pointers for input + * // samples and output histograms + * int num_row_pixels; // e.g., 3 + * int num_rows; // e.g., 2 + * size_t row_stride_bytes; // e.g., 4 * sizeof(unsigned char) * NUM_CHANNELS + * unsigned char* d_samples; // e.g., [(2, 6, 7, 5), (3, 0, 2, 1), (7, 0, 6, 2), (-, -, -, -), + * // (0, 6, 7, 5), (3, 0, 2, 6), (1, 1, 1, 1), (-, -, -, -)] + * int* d_histogram[3]; // e.g., three device pointers to three device buffers, + * // each allocated with 256 integer counters + * int num_levels[3]; // e.g., {257, 257, 257}; + * unsigned int lower_level[3]; // e.g., {0, 0, 0}; + * unsigned int upper_level[3]; // e.g., {256, 256, 256}; + * ... + * + * // Determine temporary device storage requirements + * void* d_temp_storage = NULL; + * size_t temp_storage_bytes = 0; + * cub::DeviceHistogram::MultiHistogramEven<4, 3>( + * d_temp_storage, temp_storage_bytes, + * d_samples, d_histogram, num_levels, lower_level, upper_level, + * num_row_pixels, num_rows, row_stride_bytes); + * + * // Allocate temporary storage + * cudaMalloc(&d_temp_storage, temp_storage_bytes); + * + * // Compute histograms + * cub::DeviceHistogram::MultiHistogramEven<4, 3>( + * d_temp_storage, temp_storage_bytes, + * d_samples, d_histogram, num_levels, lower_level, upper_level, + * num_row_pixels, num_rows, row_stride_bytes); + * + * // d_histogram <-- [ [1, 1, 1, 2, 0, 0, 0, 1, 0, 0, 0, ..., 0], + * // [0, 4, 0, 0, 0, 0, 2, 0, 0, 0, 0, ..., 0], + * // [0, 1, 2, 0, 0, 0, 1, 2, 0, 0, 0, ..., 0] ] + * @endcode + * + * @tparam NUM_CHANNELS + * Number of channels interleaved in the input data (may be greater than + * the number of channels being actively histogrammed) + * + * @tparam NUM_ACTIVE_CHANNELS + * **[inferred]** Number of channels actively being histogrammed + * + * @tparam SampleIteratorT + * **[inferred]** Random-access input iterator type for reading input + * samples. \iterator + * + * @tparam CounterT + * **[inferred]** Integer type for histogram bin counters + * + * @tparam LevelT + * **[inferred]** Type for specifying boundaries (levels) + * + * @tparam OffsetT + * **[inferred]** Signed integer type for sequence offsets, list lengths, + * pointer differences, etc. \offset_size1 + * + * @param[in] d_temp_storage + * Device-accessible allocation of temporary storage. When `nullptr`, the + * required allocation size is written to `temp_storage_bytes` and no + * work is done. + * + * @param[in,out] temp_storage_bytes + * Reference to size in bytes of `d_temp_storage` allocation + * + * @param[in] d_samples + * The pointer to the multi-channel input sequence of data samples. The + * samples from different channels are assumed to be interleaved (e.g., + * an array of 32-bit pixels where each pixel consists of four + * *RGBA* 8-bit samples). + * + * @param[out] d_histogram + * The pointers to the histogram counter output arrays, one for each + * active channel. For channeli, the allocation length + * of `d_histogram[i]` should be `num_levels[i] - 1`. + * + * @param[in] num_levels + * The number of boundaries (levels) for delineating histogram samples in + * each active channel. Implies that the number of bins for + * channeli is `num_levels[i] - 1`. + * + * @param[in] lower_level + * The lower sample value bound (inclusive) for the lowest histogram bin in + * each active channel. + * + * @param[in] upper_level + * The upper sample value bound (exclusive) for the highest histogram bin + * in each active channel. + * + * @param[in] num_row_pixels + * The number of multi-channel pixels per row in the region of interest + * + * @param[in] num_rows + * The number of rows in the region of interest + * + * @param[in] row_stride_bytes + * The number of bytes between starts of consecutive rows in the region of + * interest + * + * @param[in] stream + * **[optional]** CUDA stream to launch kernels within. + * Default is stream0. + */ + template + CUB_RUNTIME_FUNCTION static cudaError_t + MultiHistogramEven(void *d_temp_storage, + size_t &temp_storage_bytes, + SampleIteratorT d_samples, + CounterT *d_histogram[NUM_ACTIVE_CHANNELS], + int num_levels[NUM_ACTIVE_CHANNELS], + LevelT lower_level[NUM_ACTIVE_CHANNELS], + LevelT upper_level[NUM_ACTIVE_CHANNELS], + OffsetT num_row_pixels, + OffsetT num_rows, + size_t row_stride_bytes, + cudaStream_t stream = 0) + { + /// The sample value type of the input iterator + using SampleT = cub::detail::value_t; + Int2Type is_byte_sample; + + if ((sizeof(OffsetT) > sizeof(int)) && + ((unsigned long long)(num_rows * row_stride_bytes) < + (unsigned long long)INT_MAX)) + { + // Down-convert OffsetT data type + return DispatchHistogram::DispatchEven(d_temp_storage, + temp_storage_bytes, + d_samples, + d_histogram, + num_levels, + lower_level, + upper_level, + (int)num_row_pixels, + (int)num_rows, + (int)(row_stride_bytes / + sizeof(SampleT)), + stream, + is_byte_sample); + } + + return DispatchHistogram::DispatchEven(d_temp_storage, + temp_storage_bytes, + d_samples, + d_histogram, + num_levels, + lower_level, + upper_level, + num_row_pixels, + num_rows, + (OffsetT)(row_stride_bytes / + sizeof(SampleT)), + stream, + is_byte_sample); + } + + template + CUB_DETAIL_RUNTIME_DEBUG_SYNC_IS_NOT_SUPPORTED + CUB_RUNTIME_FUNCTION static cudaError_t + MultiHistogramEven(void *d_temp_storage, + size_t &temp_storage_bytes, + SampleIteratorT d_samples, + CounterT *d_histogram[NUM_ACTIVE_CHANNELS], + int num_levels[NUM_ACTIVE_CHANNELS], + LevelT lower_level[NUM_ACTIVE_CHANNELS], + LevelT upper_level[NUM_ACTIVE_CHANNELS], + OffsetT num_row_pixels, + OffsetT num_rows, + size_t row_stride_bytes, + cudaStream_t stream, + bool debug_synchronous) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + + return MultiHistogramEven(d_temp_storage, + temp_storage_bytes, + d_samples, + d_histogram, + num_levels, + lower_level, + upper_level, + num_row_pixels, + num_rows, + row_stride_bytes, + stream); + } + + //@} end member group + /******************************************************************//** + * @name Custom bin ranges + *********************************************************************/ + //@{ + + /** + * @brief Computes an intensity histogram from a sequence of data samples + * using the specified bin boundary levels. + * + * @par + * - The number of histogram bins is (`num_levels - 1`) + * - The value range for bini is `[level[i], level[i+1])` + * - The range `[d_histogram, d_histogram + num_levels - 1)` shall not + * overlap `[d_samples, d_samples + num_samples)` nor + * `[d_levels, d_levels + num_levels)` in any way. The ranges + * `[d_levels, d_levels + num_levels)` and + * `[d_samples, d_samples + num_samples)` may overlap. + * - @devicestorage + * + * @par Snippet + * The code snippet below illustrates the computation of an six-bin histogram + * from a sequence of float samples + * + * @par + * @code + * #include // or equivalently + * + * // Declare, allocate, and initialize device-accessible pointers for input + * // samples and output histogram + * int num_samples; // e.g., 10 + * float* d_samples; // e.g., [2.2, 6.0, 7.1, 2.9, 3.5, 0.3, 2.9, 2.0, 6.1, 999.5] + * int* d_histogram; // e.g., [ -, -, -, -, -, -] + * int num_levels // e.g., 7 (seven level boundaries for six bins) + * float* d_levels; // e.g., [0.0, 2.0, 4.0, 6.0, 8.0, 12.0, 16.0] + * ... + * + * // Determine temporary device storage requirements + * void* d_temp_storage = NULL; + * size_t temp_storage_bytes = 0; + * cub::DeviceHistogram::HistogramRange( + * d_temp_storage, temp_storage_bytes, + * d_samples, d_histogram, num_levels, d_levels, num_samples); + * + * // Allocate temporary storage + * cudaMalloc(&d_temp_storage, temp_storage_bytes); + * + * // Compute histograms + * cub::DeviceHistogram::HistogramRange( + * d_temp_storage, temp_storage_bytes, + * d_samples, d_histogram, num_levels, d_levels, num_samples); + * + * // d_histogram <-- [1, 5, 0, 3, 0, 0]; + * + * @endcode + * + * @tparam SampleIteratorT + * **[inferred]** Random-access input iterator type for reading + * input samples.\iterator + * + * @tparam CounterT + * **[inferred]** Integer type for histogram bin counters + * + * @tparam LevelT + * **[inferred]** Type for specifying boundaries (levels) + * + * @tparam OffsetT + * **[inferred]** Signed integer type for sequence offsets, list lengths, + * pointer differences, etc. \offset_size1 + * + * @param[in] d_temp_storage + * Device-accessible allocation of temporary storage. When `nullptr`, the + * required allocation size is written to `temp_storage_bytes` and no work + * is done. + * + * @param[in,out] temp_storage_bytes + * Reference to size in bytes of `d_temp_storage` allocation + * + * @param[in] d_samples + * The pointer to the input sequence of data samples. + * + * @param[out] d_histogram + * The pointer to the histogram counter output array of length + * `num_levels - 1`. + * + * @param[in] num_levels + * The number of boundaries (levels) for delineating histogram samples. + * Implies that the number of bins is `num_levels - 1`. + * + * @param[in] d_levels + * The pointer to the array of boundaries (levels). Bin ranges are defined + * by consecutive boundary pairings: lower sample value boundaries are + * inclusive and upper sample value boundaries are exclusive. + * + * @param[in] num_samples + * The number of data samples per row in the region of interest + * + * @param[in] stream + * **[optional]** CUDA stream to launch kernels within. + * Default is stream0. + */ + template + CUB_RUNTIME_FUNCTION static cudaError_t + HistogramRange(void *d_temp_storage, + size_t &temp_storage_bytes, + SampleIteratorT d_samples, + CounterT *d_histogram, + int num_levels, + LevelT *d_levels, + OffsetT num_samples, + cudaStream_t stream = 0) + { + /// The sample value type of the input iterator + using SampleT = cub::detail::value_t; + + CounterT *d_histogram1[1] = {d_histogram}; + int num_levels1[1] = {num_levels}; + LevelT *d_levels1[1] = {d_levels}; + + return MultiHistogramRange<1, 1>(d_temp_storage, + temp_storage_bytes, + d_samples, + d_histogram1, + num_levels1, + d_levels1, + num_samples, + (OffsetT)1, + (size_t)(sizeof(SampleT) * num_samples), + stream); + } + + template + CUB_DETAIL_RUNTIME_DEBUG_SYNC_IS_NOT_SUPPORTED + CUB_RUNTIME_FUNCTION static cudaError_t + HistogramRange(void *d_temp_storage, + size_t &temp_storage_bytes, + SampleIteratorT d_samples, + CounterT *d_histogram, + int num_levels, + LevelT *d_levels, + OffsetT num_samples, + cudaStream_t stream, + bool debug_synchronous) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + + return HistogramRange(d_temp_storage, + temp_storage_bytes, + d_samples, + d_histogram, + num_levels, + d_levels, + num_samples, + stream); + } + + /** + * @brief Computes an intensity histogram from a sequence of data samples + * using the specified bin boundary levels. + * + * @par + * - A two-dimensional *region of interest* within `d_samples` can be + * specified using the `num_row_samples`, `num_rows`, and + * `row_stride_bytes` parameters. + * - The row stride must be a whole multiple of the sample data type + * size, i.e., `(row_stride_bytes % sizeof(SampleT)) == 0`. + * - The number of histogram bins is (`num_levels - 1`) + * - The value range for bini is `[level[i], level[i+1])` + * - For a given row `r` in `[0, num_rows)`, let + * `row_begin = d_samples + r * row_stride_bytes / sizeof(SampleT)` and + * `row_end = row_begin + num_row_samples`. The range + * `[d_histogram, d_histogram + num_levels - 1)` shall not overlap + * `[row_begin, row_end)` nor `[d_levels, d_levels + num_levels)`. + * The ranges `[d_levels, d_levels + num_levels)` and `[row_begin, row_end)` + * may overlap. + * - @devicestorage + * + * @par Snippet + * The code snippet below illustrates the computation of a six-bin histogram + * from a 2x5 region of interest within a flattened 2x7 array of float samples. + * + * @par + * @code + * #include // or equivalently + * + * // Declare, allocate, and initialize device-accessible pointers for input samples and + * // output histogram + * int num_row_samples; // e.g., 5 + * int num_rows; // e.g., 2; + * int row_stride_bytes; // e.g., 7 * sizeof(float) + * float* d_samples; // e.g., [2.2, 6.0, 7.1, 2.9, 3.5, -, -, + * // 0.3, 2.9, 2.0, 6.1, 999.5, -, -] + * int* d_histogram; // e.g., [ -, -, -, -, -, -] + * int num_levels // e.g., 7 (seven level boundaries for six bins) + * float *d_levels; // e.g., [0.0, 2.0, 4.0, 6.0, 8.0, 12.0, 16.0] + * ... + * + * // Determine temporary device storage requirements + * void* d_temp_storage = NULL; + * size_t temp_storage_bytes = 0; + * cub::DeviceHistogram::HistogramRange( + * d_temp_storage, temp_storage_bytes, + * d_samples, d_histogram, num_levels, d_levels, + * num_row_samples, num_rows, row_stride_bytes); + * + * // Allocate temporary storage + * cudaMalloc(&d_temp_storage, temp_storage_bytes); + * + * // Compute histograms + * cub::DeviceHistogram::HistogramRange( + * d_temp_storage, temp_storage_bytes, + * d_samples, d_histogram, num_levels, d_levels, + * num_row_samples, num_rows, row_stride_bytes); + * + * // d_histogram <-- [1, 5, 0, 3, 0, 0]; + * @endcode + * + * @tparam SampleIteratorT + * **[inferred]** Random-access input iterator type for reading + * input samples. \iterator + * + * @tparam CounterT + * **[inferred]** Integer type for histogram bin counters + * + * @tparam LevelT + * **[inferred]** Type for specifying boundaries (levels) + * + * @tparam OffsetT + * **[inferred]** Signed integer type for sequence offsets, list lengths, + * pointer differences, etc. \offset_size1 + * + * @param[in] d_temp_storage + * Device-accessible allocation of temporary storage. When `nullptr`, the + * required allocation size is written to `temp_storage_bytes` and no + * work is done. + * + * @param[in,out] temp_storage_bytes + * Reference to size in bytes of `d_temp_storage` allocation + * + * @param[in] d_samples + * The pointer to the input sequence of data samples. + * + * @param[out] d_histogram + * The pointer to the histogram counter output array of length + * `num_levels - 1`. + * + * @param[in] num_levels + * The number of boundaries (levels) for delineating histogram samples. + * Implies that the number of bins is `num_levels - 1`. + * + * @param[in] d_levels + * The pointer to the array of boundaries (levels). Bin ranges are defined + * by consecutive boundary pairings: lower sample value boundaries are + * inclusive and upper sample value boundaries are exclusive. + * + * @param[in] num_row_samples + * The number of data samples per row in the region of interest + * + * @param[in] num_rows + * The number of rows in the region of interest + * + * @param[in] row_stride_bytes + * The number of bytes between starts of consecutive rows in the region + * of interest + * + * @param[in] stream + * **[optional]** CUDA stream to launch kernels within. + * Default is stream0. + */ + template + CUB_RUNTIME_FUNCTION static cudaError_t + HistogramRange(void *d_temp_storage, + size_t &temp_storage_bytes, + SampleIteratorT d_samples, + CounterT *d_histogram, + int num_levels, + LevelT *d_levels, + OffsetT num_row_samples, + OffsetT num_rows, + size_t row_stride_bytes, + cudaStream_t stream = 0) + { + CounterT *d_histogram1[1] = {d_histogram}; + int num_levels1[1] = {num_levels}; + LevelT *d_levels1[1] = {d_levels}; + + return MultiHistogramRange<1, 1>(d_temp_storage, + temp_storage_bytes, + d_samples, + d_histogram1, + num_levels1, + d_levels1, + num_row_samples, + num_rows, + row_stride_bytes, + stream); + } + + template + CUB_DETAIL_RUNTIME_DEBUG_SYNC_IS_NOT_SUPPORTED + CUB_RUNTIME_FUNCTION static cudaError_t + HistogramRange(void *d_temp_storage, + size_t &temp_storage_bytes, + SampleIteratorT d_samples, + CounterT *d_histogram, + int num_levels, + LevelT *d_levels, + OffsetT num_row_samples, + OffsetT num_rows, + size_t row_stride_bytes, + cudaStream_t stream, + bool debug_synchronous) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + + return HistogramRange(d_temp_storage, + temp_storage_bytes, + d_samples, + d_histogram, + num_levels, + d_levels, + num_row_samples, + num_rows, + row_stride_bytes, + stream); + } + + /** + * @brief Computes per-channel intensity histograms from a sequence of + * multi-channel "pixel" data samples using the specified bin + * boundary levels. + * + * @par + * - The input is a sequence of *pixel* structures, where each pixel + * comprises a record of `NUM_CHANNELS` consecutive data samples + * (e.g., an *RGBA* pixel). + * - Of the `NUM_CHANNELS` specified, the function will only compute + * histograms for the first `NUM_ACTIVE_CHANNELS` (e.g., *RGB* histograms + * from *RGBA* pixel samples). + * - The number of histogram bins for channeli is + * `num_levels[i] - 1`. + * - For channeli, the range of values for all histogram + * bins have the same width: + * `(upper_level[i] - lower_level[i]) / (num_levels[i] - 1)` + * - For given channels `c1` and `c2` in `[0, NUM_ACTIVE_CHANNELS)`, the + * range `[d_histogram[c1], d_histogram[c1] + num_levels[c1] - 1)` shall + * not overlap `[d_samples, d_samples + NUM_CHANNELS * num_pixels)` nor + * `[d_levels[c2], d_levels[c2] + num_levels[c2])` in any way. + * The ranges `[d_levels[c2], d_levels[c2] + num_levels[c2])` and + * `[d_samples, d_samples + NUM_CHANNELS * num_pixels)` may overlap. + * - @devicestorage + * + * @par Snippet + * The code snippet below illustrates the computation of three 4-bin *RGB* + * histograms from a quad-channel sequence of *RGBA* pixels + * (8 bits per channel per pixel) + * + * @par + * @code + * #include // or equivalently + * + * // Declare, allocate, and initialize device-accessible pointers for + * // input samples and output histograms + * int num_pixels; // e.g., 5 + * unsigned char *d_samples; // e.g., [(2, 6, 7, 5),(3, 0, 2, 1),(7, 0, 6, 2), + * // (0, 6, 7, 5),(3, 0, 2, 6)] + * unsigned int *d_histogram[3]; // e.g., [[ -, -, -, -],[ -, -, -, -],[ -, -, -, -]]; + * int num_levels[3]; // e.g., {5, 5, 5}; + * unsigned int *d_levels[3]; // e.g., [ [0, 2, 4, 6, 8], + * // [0, 2, 4, 6, 8], + * // [0, 2, 4, 6, 8] ]; + * ... + * + * // Determine temporary device storage requirements + * void* d_temp_storage = NULL; + * size_t temp_storage_bytes = 0; + * cub::DeviceHistogram::MultiHistogramRange<4, 3>( + * d_temp_storage, temp_storage_bytes, + * d_samples, d_histogram, num_levels, d_levels, num_pixels); + * + * // Allocate temporary storage + * cudaMalloc(&d_temp_storage, temp_storage_bytes); + * + * // Compute histograms + * cub::DeviceHistogram::MultiHistogramRange<4, 3>( + * d_temp_storage, temp_storage_bytes, + * d_samples, d_histogram, num_levels, d_levels, num_pixels); + * + * // d_histogram <-- [ [1, 3, 0, 1], + * // [3, 0, 0, 2], + * // [0, 2, 0, 3] ] + * + * @endcode + * + * @tparam NUM_CHANNELS + * Number of channels interleaved in the input data (may be greater than + * the number of channels being actively histogrammed) + * + * @tparam NUM_ACTIVE_CHANNELS + * **[inferred]** Number of channels actively being histogrammed + * + * @tparam SampleIteratorT + * **[inferred]** Random-access input iterator type for reading + * input samples. \iterator + * + * @tparam CounterT + * **[inferred]** Integer type for histogram bin counters + * + * @tparam LevelT + * **[inferred]** Type for specifying boundaries (levels) + * + * @tparam OffsetT + * **[inferred]** Signed integer type for sequence offsets, list lengths, + * pointer differences, etc. \offset_size1 + * + * @param[in] d_temp_storage + * Device-accessible allocation of temporary storage. When `nullptr`, the + * required allocation size is written to `temp_storage_bytes` and no + * work is done. + * + * @param[in,out] temp_storage_bytes + * Reference to size in bytes of `d_temp_storage` allocation + * + * @param[in] d_samples + * The pointer to the multi-channel input sequence of data samples. + * The samples from different channels are assumed to be interleaved (e.g., + * an array of 32-bit pixels where each pixel consists of four *RGBA* + * 8-bit samples). + * + * @param[out] d_histogram + * The pointers to the histogram counter output arrays, one for each active + * channel. For channeli, the allocation length of + * `d_histogram[i]` should be `num_levels[i] - 1`. + * + * @param[in] num_levels + * The number of boundaries (levels) for delineating histogram samples in + * each active channel. Implies that the number of bins for + * channeli is `num_levels[i] - 1`. + * + * @param[in] d_levels + * The pointers to the arrays of boundaries (levels), one for each active + * channel. Bin ranges are defined by consecutive boundary pairings: lower + * sample value boundaries are inclusive and upper sample value boundaries + * are exclusive. + * + * @param[in] num_pixels + * The number of multi-channel pixels + * (i.e., the length of `d_samples / NUM_CHANNELS`) + * + * @param[in] stream + * **[optional]** CUDA stream to launch kernels within. + * Default is stream0. + */ + template + CUB_RUNTIME_FUNCTION static cudaError_t + MultiHistogramRange(void *d_temp_storage, + size_t &temp_storage_bytes, + SampleIteratorT d_samples, + CounterT *d_histogram[NUM_ACTIVE_CHANNELS], + int num_levels[NUM_ACTIVE_CHANNELS], + LevelT *d_levels[NUM_ACTIVE_CHANNELS], + OffsetT num_pixels, + cudaStream_t stream = 0) + { + /// The sample value type of the input iterator + using SampleT = cub::detail::value_t; + + return MultiHistogramRange( + d_temp_storage, + temp_storage_bytes, + d_samples, + d_histogram, + num_levels, + d_levels, + num_pixels, + (OffsetT)1, + (size_t)(sizeof(SampleT) * NUM_CHANNELS * num_pixels), + stream); + } + + template + CUB_DETAIL_RUNTIME_DEBUG_SYNC_IS_NOT_SUPPORTED + CUB_RUNTIME_FUNCTION static cudaError_t + MultiHistogramRange(void *d_temp_storage, + size_t &temp_storage_bytes, + SampleIteratorT d_samples, + CounterT *d_histogram[NUM_ACTIVE_CHANNELS], + int num_levels[NUM_ACTIVE_CHANNELS], + LevelT *d_levels[NUM_ACTIVE_CHANNELS], + OffsetT num_pixels, + cudaStream_t stream, + bool debug_synchronous) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + + return MultiHistogramRange(d_temp_storage, + temp_storage_bytes, + d_samples, + d_histogram, + num_levels, + d_levels, + num_pixels, + stream); + } + + /** + * @brief Computes per-channel intensity histograms from a sequence of + * multi-channel "pixel" data samples using the specified bin boundary + * levels. + * + * @par + * - The input is a sequence of *pixel* structures, where each pixel comprises + * a record of `NUM_CHANNELS` consecutive data samples + * (e.g., an *RGBA* pixel). + * - Of the `NUM_CHANNELS` specified, the function will only compute + * histograms for the first `NUM_ACTIVE_CHANNELS` (e.g., *RGB* histograms + * from *RGBA* pixel samples). + * - A two-dimensional *region of interest* within `d_samples` can be + * specified using the `num_row_samples`, `num_rows`, and `row_stride_bytes` + * parameters. + * - The row stride must be a whole multiple of the sample data type + * size, i.e., `(row_stride_bytes % sizeof(SampleT)) == 0`. + * - The number of histogram bins for channeli is + * `num_levels[i] - 1`. + * - For channeli, the range of values for all histogram + * bins have the same width: + * `(upper_level[i] - lower_level[i]) / (num_levels[i] - 1)` + * - For a given row `r` in `[0, num_rows)`, and sample `s` in + * `[0, num_row_pixels)`, let + * `row_begin = d_samples + r * row_stride_bytes / sizeof(SampleT)`, + * `sample_begin = row_begin + s * NUM_CHANNELS`, and + * `sample_end = sample_begin + NUM_ACTIVE_CHANNELS`. For given channels + * `c1` and `c2` in `[0, NUM_ACTIVE_CHANNELS)`, the range + * `[d_histogram[c1], d_histogram[c1] + num_levels[c1] - 1)` shall not + * overlap `[sample_begin, sample_end)` nor + * `[d_levels[c2], d_levels[c2] + num_levels[c2])` in any way. The ranges + * `[d_levels[c2], d_levels[c2] + num_levels[c2])` and + * `[sample_begin, sample_end)` may overlap. + * - @devicestorage + * + * @par Snippet + * The code snippet below illustrates the computation of three 4-bin *RGB* + * histograms from a 2x3 region of interest of within a flattened 2x4 array + * of quad-channel *RGBA* pixels (8 bits per channel per pixel). + * + * @par + * @code + * #include // or equivalently + * + * // Declare, allocate, and initialize device-accessible pointers for input + * // samples and output histograms + * int num_row_pixels; // e.g., 3 + * int num_rows; // e.g., 2 + * size_t row_stride_bytes; // e.g., 4 * sizeof(unsigned char) * NUM_CHANNELS + * unsigned char* d_samples; // e.g., [(2, 6, 7, 5),(3, 0, 2, 1),(1, 1, 1, 1),(-, -, -, -), + * // (7, 0, 6, 2),(0, 6, 7, 5),(3, 0, 2, 6),(-, -, -, -)] + * int* d_histogram[3]; // e.g., [[ -, -, -, -],[ -, -, -, -],[ -, -, -, -]]; + * int num_levels[3]; // e.g., {5, 5, 5}; + * unsigned int* d_levels[3]; // e.g., [ [0, 2, 4, 6, 8], + * // [0, 2, 4, 6, 8], + * // [0, 2, 4, 6, 8] ]; + * ... + * + * // Determine temporary device storage requirements + * void* d_temp_storage = NULL; + * size_t temp_storage_bytes = 0; + * cub::DeviceHistogram::MultiHistogramRange<4, 3>( + * d_temp_storage, temp_storage_bytes, + * d_samples, d_histogram, num_levels, d_levels, + * num_row_pixels, num_rows, row_stride_bytes); + * + * // Allocate temporary storage + * cudaMalloc(&d_temp_storage, temp_storage_bytes); + * + * // Compute histograms + * cub::DeviceHistogram::MultiHistogramRange<4, 3>( + * d_temp_storage, temp_storage_bytes, + * d_samples, d_histogram, num_levels, + * d_levels, num_row_pixels, num_rows, row_stride_bytes); + * + * // d_histogram <-- [ [2, 3, 0, 1], + * // [3, 0, 0, 2], + * // [1, 2, 0, 3] ] + * + * @endcode + * + * @tparam NUM_CHANNELS + * Number of channels interleaved in the input data (may be greater than + * the number of channels being actively histogrammed) + * + * @tparam NUM_ACTIVE_CHANNELS + * **[inferred]** Number of channels actively being histogrammed + * + * @tparam SampleIteratorT + * **[inferred]** Random-access input iterator type for reading input + * samples. \iterator + * + * @tparam CounterT + * **[inferred]** Integer type for histogram bin counters + * + * @tparam LevelT + * **[inferred]** Type for specifying boundaries (levels) + * + * @tparam OffsetT + * **[inferred]** Signed integer type for sequence offsets, list lengths, + * pointer differences, etc. \offset_size1 + * + * @param[in] d_temp_storage + * Device-accessible allocation of temporary storage. When `nullptr`, the + * required allocation size is written to \p temp_storage_bytes and no work is done. + * + * @param[in,out] temp_storage_bytes + * Reference to size in bytes of `d_temp_storage` allocation + * + * @param[in] d_samples + * The pointer to the multi-channel input sequence of data samples. The + * samples from different channels are assumed to be interleaved (e.g., an + * array of 32-bit pixels where each pixel consists of four + * *RGBA* 8-bit samples). + * + * @param[out] d_histogram + * The pointers to the histogram counter output arrays, one for each active + * channel. For channeli, the allocation length of + * `d_histogram[i]` should be `num_levels[i] - 1`. + * + * @param[in] num_levels + * The number of boundaries (levels) for delineating histogram samples in + * each active channel. Implies that the number of bins for + * channeli is `num_levels[i] - 1`. + * + * @param[in] d_levels + * The pointers to the arrays of boundaries (levels), one for each active + * channel. Bin ranges are defined by consecutive boundary pairings: lower + * sample value boundaries are inclusive and upper sample value boundaries + * are exclusive. + * + * @param[in] num_row_pixels + * The number of multi-channel pixels per row in the region of interest + * + * @param[in] num_rows + * The number of rows in the region of interest + * + * @param[in] row_stride_bytes + * The number of bytes between starts of consecutive rows in the + * region of interest + * + * @param[in] stream + * **[optional]** CUDA stream to launch kernels within. + * Default is stream0. + */ + template + CUB_RUNTIME_FUNCTION static cudaError_t + MultiHistogramRange(void *d_temp_storage, + size_t &temp_storage_bytes, + SampleIteratorT d_samples, + CounterT *d_histogram[NUM_ACTIVE_CHANNELS], + int num_levels[NUM_ACTIVE_CHANNELS], + LevelT *d_levels[NUM_ACTIVE_CHANNELS], + OffsetT num_row_pixels, + OffsetT num_rows, + size_t row_stride_bytes, + cudaStream_t stream = 0) + { + /// The sample value type of the input iterator + using SampleT = cub::detail::value_t; + Int2Type is_byte_sample; + + if ((sizeof(OffsetT) > sizeof(int)) && + ((unsigned long long)(num_rows * row_stride_bytes) < + (unsigned long long)INT_MAX)) + { + // Down-convert OffsetT data type + return DispatchHistogram::DispatchRange(d_temp_storage, + temp_storage_bytes, + d_samples, + d_histogram, + num_levels, + d_levels, + (int)num_row_pixels, + (int)num_rows, + (int)(row_stride_bytes / + sizeof(SampleT)), + stream, + is_byte_sample); + } + + return DispatchHistogram::DispatchRange(d_temp_storage, + temp_storage_bytes, + d_samples, + d_histogram, + num_levels, + d_levels, + num_row_pixels, + num_rows, + (OffsetT)(row_stride_bytes / + sizeof(SampleT)), + stream, + is_byte_sample); + } + + template + CUB_DETAIL_RUNTIME_DEBUG_SYNC_IS_NOT_SUPPORTED + CUB_RUNTIME_FUNCTION static cudaError_t + MultiHistogramRange(void *d_temp_storage, + size_t &temp_storage_bytes, + SampleIteratorT d_samples, + CounterT *d_histogram[NUM_ACTIVE_CHANNELS], + int num_levels[NUM_ACTIVE_CHANNELS], + LevelT *d_levels[NUM_ACTIVE_CHANNELS], + OffsetT num_row_pixels, + OffsetT num_rows, + size_t row_stride_bytes, + cudaStream_t stream, + bool debug_synchronous) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + + return MultiHistogramRange(d_temp_storage, + temp_storage_bytes, + d_samples, + d_histogram, + num_levels, + d_levels, + num_row_pixels, + num_rows, + row_stride_bytes, + stream); + } + + //@} end member group +}; + +CUB_NAMESPACE_END + + diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/device/device_memcpy.cuh b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/device/device_memcpy.cuh new file mode 100644 index 0000000000000000000000000000000000000000..a0f8fe5415f13b554a2fb5cc784e556a95e6bc53 --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/device/device_memcpy.cuh @@ -0,0 +1,179 @@ +/****************************************************************************** + * Copyright (c) 2011-2022, NVIDIA CORPORATION. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the NVIDIA CORPORATION nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ******************************************************************************/ + +/** + * \file + * cub::DeviceMemcpy provides device-wide, parallel operations for copying data. + */ + +#pragma once + +#include +#include + +#include +#include + +CUB_NAMESPACE_BEGIN + +/** + * @brief cub::DeviceMemcpy provides device-wide, parallel operations for copying data. + * \ingroup SingleModule + */ +struct DeviceMemcpy +{ + /** + * @brief Copies data from a batch of given source buffers to their corresponding destination + * buffer. + * @note If any input buffer aliases memory from any output buffer the behavior is undefined. If + * any output buffer aliases memory of another output buffer the behavior is undefined. Input + * buffers can alias one another. + * + * @par Snippet + * The code snippet below illustrates usage of DeviceMemcpy::Batched for mutating strings withing + * a single string buffer. + * @par + * @code + * struct GetPtrToStringItem + * { + * __host__ __device__ __forceinline__ void *operator()(uint32_t index) + * { + * return &d_string_data_in[d_string_offsets[index]]; + * } + * char *d_string_data_in; + * uint32_t *d_string_offsets; + * }; + * + * struct GetStringItemSize + * { + * __host__ __device__ __forceinline__ uint32_t operator()(uint32_t index) + * { + * return d_string_offsets[index + 1] - d_string_offsets[index]; + * } + * uint32_t *d_string_offsets; + * }; + * + * uint32_t num_strings = 5; + * char *d_string_data_in; // e.g., "TomatoesBananasApplesOrangesGrapes" + * char *d_string_data_out; // e.g., " ... " + * uint32_t *d_string_offsets_old; // e.g., [0, 8, 15, 21, 28, 34] + * uint32_t *d_string_offsets_new; // e.g., [0, 6, 13, 19, 26, 34] + * uint32_t *d_gather_index; // e.g., [2, 1, 4, 3, 0] + * + * // Initialize an iterator that returns d_gather_index[i] when the i-th item is dereferenced + * auto gather_iterator = thrust::make_permutation_iterator(thrust::make_counting_iterator(0), + * d_gather_index); + * + * // Returns pointers to the input buffer for each string + * auto str_ptrs_in = thrust::make_transform_iterator(gather_iterator, + * GetPtrToStringItem{d_string_data_in, + * d_string_offsets_old}); + * + * // Returns the string size of the i-th string + * auto str_sizes = thrust::make_transform_iterator(gather_iterator, + * GetStringItemSize{d_string_offsets_old}); + * + * // Returns pointers to the output buffer for each string + * auto str_ptrs_out = thrust::make_transform_iterator(thrust::make_counting_iterator(0), + * GetPtrToStringItem{d_string_data_out, + * d_string_offsets_new}); + * + * // Determine temporary device storage requirements + * void *d_temp_storage = nullptr; + * size_t temp_storage_bytes = 0; + * cub::DeviceMemcpy::Batched(d_temp_storage, temp_storage_bytes, str_ptrs_in, str_ptrs_out, + * str_sizes, num_strings); + * + * // Allocate temporary storage + * cudaMalloc(&d_temp_storage, temp_storage_bytes); + * + * // Run batched copy algorithm (used to permute strings) + * cub::DeviceMemcpy::Batched(d_temp_storage, temp_storage_bytes, str_ptrs_in, str_ptrs_out, + * str_sizes, num_strings); + * + * // d_string_data_out <-- "ApplesBananasGrapesOrangesTomatoe" + * @endcode + * @tparam InputBufferIt [inferred] Device-accessible random-access input iterator type + * providing the pointers to the source memory buffers + * @tparam OutputBufferIt [inferred] Device-accessible random-access input iterator type + * providing the pointers to the destination memory buffers + * @tparam BufferSizeIteratorT [inferred] Device-accessible random-access input iterator + * type providing the number of bytes to be copied for each pair of buffers + * @param d_temp_storage [in] Device-accessible allocation of temporary storage. When NULL, the + * required allocation size is written to \p temp_storage_bytes and no work is done. + * @param temp_storage_bytes [in,out] Reference to size in bytes of \p d_temp_storage allocation + * @param input_buffer_it [in] Device-accessible iterator providing the pointers to the source + * memory buffers + * @param output_buffer_it [in] Device-accessible iterator providing the pointers to the + * destination memory buffers + * @param buffer_sizes [in] Device-accessible iterator providing the number of bytes to be copied + * for each pair of buffers + * @param num_buffers [in] The total number of buffer pairs + * @param stream [in] [optional] CUDA stream to launch kernels within. Default is + * stream0. + */ + template + CUB_RUNTIME_FUNCTION static cudaError_t Batched(void *d_temp_storage, + size_t &temp_storage_bytes, + InputBufferIt input_buffer_it, + OutputBufferIt output_buffer_it, + BufferSizeIteratorT buffer_sizes, + uint32_t num_buffers, + cudaStream_t stream = 0) + { + static_assert(std::is_pointer>::value, + "DeviceMemcpy::Batched only supports copying of memory buffers." + "Please consider using DeviceCopy::Batched instead."); + static_assert(std::is_pointer>::value, + "DeviceMemcpy::Batched only supports copying of memory buffers." + "Please consider using DeviceCopy::Batched instead."); + + // Integer type large enough to hold any offset in [0, num_buffers) + using BufferOffsetT = uint32_t; + + // Integer type large enough to hold any offset in [0, num_thread_blocks_launched), where a safe + // uppper bound on num_thread_blocks_launched can be assumed to be given by + // IDIV_CEIL(num_buffers, 64) + using BlockOffsetT = uint32_t; + + return detail::DispatchBatchMemcpy, + true>::Dispatch(d_temp_storage, + temp_storage_bytes, + input_buffer_it, + output_buffer_it, + buffer_sizes, + num_buffers, + stream); + } +}; + +CUB_NAMESPACE_END diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/device/device_merge_sort.cuh b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/device/device_merge_sort.cuh new file mode 100644 index 0000000000000000000000000000000000000000..9b17ac391257d937b05fc00c2a9eec14411a8f2b --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/device/device_merge_sort.cuh @@ -0,0 +1,1118 @@ +/****************************************************************************** + * Copyright (c) 2011-2022, NVIDIA CORPORATION. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the NVIDIA CORPORATION nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ******************************************************************************/ + +#pragma once + +#include +#include +#include +#include + +CUB_NAMESPACE_BEGIN + + +/** + * @brief DeviceMergeSort provides device-wide, parallel operations for + * computing a merge sort across a sequence of data items residing within + * device-accessible memory. + * + * @ingroup SingleModule + * + * @par Overview + * - DeviceMergeSort arranges items into ascending order using a comparison + * functor with less-than semantics. Merge sort can handle arbitrary types (as + * long as a value of these types is a model of [LessThan Comparable]) and + * comparison functors, but is slower than DeviceRadixSort when sorting + * arithmetic types into ascending/descending order. + * - Another difference from RadixSort is the fact that DeviceMergeSort can + * handle arbitrary random-access iterators, as shown below. + * + * @par A Simple Example + * @par + * The code snippet below illustrates a thrust reverse iterator usage. + * @par + * @code + * #include // or equivalently + * + * struct CustomLess + * { + * template + * __device__ bool operator()(const DataType &lhs, const DataType &rhs) + * { + * return lhs < rhs; + * } + * }; + * + * // Declare, allocate, and initialize device-accessible pointers + * // for sorting data + * thrust::device_vector d_keys(num_items); + * thrust::device_vector d_values(num_items); + * // ... + * + * // Initialize iterator + * using KeyIterator = typename thrust::device_vector::iterator; + * thrust::reverse_iterator reverse_iter(d_keys.end()); + * + * // Determine temporary device storage requirements + * std::size_t temp_storage_bytes = 0; + * cub::DeviceMergeSort::SortPairs( + * nullptr, + * temp_storage_bytes, + * reverse_iter, + * thrust::raw_pointer_cast(d_values.data()), + * num_items, + * CustomLess()); + * + * // Allocate temporary storage + * cudaMalloc(&d_temp_storage, temp_storage_bytes); + * + * // Run sorting operation + * cub::DeviceMergeSort::SortPairs( + * d_temp_storage, + * temp_storage_bytes, + * reverse_iter, + * thrust::raw_pointer_cast(d_values.data()), + * num_items, + * CustomLess()); + * @endcode + * + * [LessThan Comparable]: https://en.cppreference.com/w/cpp/named_req/LessThanComparable + */ +struct DeviceMergeSort +{ + + /** + * @brief Sorts items using a merge sorting method. + * + * @par + * SortPairs is not guaranteed to be stable. That is, suppose that i and j are + * equivalent: neither one is less than the other. It is not guaranteed + * that the relative order of these two elements will be preserved by sort. + * + * @par Snippet + * The code snippet below illustrates the sorting of a device vector of `int` + * keys with associated vector of `int` values. + * @par + * @code + * #include + * // or equivalently + * + * // Declare, allocate, and initialize device-accessible pointers for + * // sorting data + * int num_items; // e.g., 7 + * int *d_keys; // e.g., [8, 6, 6, 5, 3, 0, 9] + * int *d_values; // e.g., [0, 1, 2, 3, 4, 5, 6] + * ... + * + * // Initialize comparator + * CustomOpT custom_op; + * + * // Determine temporary device storage requirements + * void *d_temp_storage = nullptr; + * std::size_t temp_storage_bytes = 0; + * cub::DeviceMergeSort::SortPairs( + * d_temp_storage, temp_storage_bytes, + * d_keys, d_values, num_items, custom_op); + * + * // Allocate temporary storage + * cudaMalloc(&d_temp_storage, temp_storage_bytes); + * + * // Run sorting operation + * cub::DeviceMergeSort::SortPairs( + * d_temp_storage, temp_storage_bytes, + * d_keys, d_values, num_items, custom_op); + * + * // d_keys <-- [0, 3, 5, 6, 6, 8, 9] + * // d_values <-- [5, 4, 3, 2, 1, 0, 6] + * + * @endcode + * + * @tparam KeyIteratorT + * is a model of [Random Access Iterator]. `KeyIteratorT` is mutable, and + * its `value_type` is a model of [LessThan Comparable]. This `value_type`'s + * ordering relation is a *strict weak ordering* as defined in + * the [LessThan Comparable] requirements. + * + * @tparam ValueIteratorT + * is a model of [Random Access Iterator], and `ValueIteratorT` is mutable. + * + * @tparam OffsetT + * is an integer type for global offsets. + * + * @tparam CompareOpT + * is a type of callable object with the signature + * `bool operator()(KeyT lhs, KeyT rhs)` that models + * the [Strict Weak Ordering] concept. + * + * @param[in] d_temp_storage + * Device-accessible allocation of temporary storage. When `nullptr`, the + * required allocation size is written to `temp_storage_bytes` and no work + * is done. + * + * @param[in,out] temp_storage_bytes + * Reference to size in bytes of `d_temp_storage` allocation + * + * @param[in,out] d_keys + * Pointer to the input sequence of unsorted input keys + * + * @param[in,out] d_items + * Pointer to the input sequence of unsorted input values + * + * @param[in] num_items + * Number of items to sort + * + * @param[in] compare_op + * Comparison function object which returns true if the first argument is + * ordered before the second + * + * @param[in] stream + * **[optional]** CUDA stream to launch kernels within. Default is + * stream0. + * + * [Random Access Iterator]: https://en.cppreference.com/w/cpp/iterator/random_access_iterator + * [Strict Weak Ordering]: https://en.cppreference.com/w/cpp/concepts/strict_weak_order + * [LessThan Comparable]: https://en.cppreference.com/w/cpp/named_req/LessThanComparable + */ + template + CUB_RUNTIME_FUNCTION static cudaError_t + SortPairs(void *d_temp_storage, + std::size_t &temp_storage_bytes, + KeyIteratorT d_keys, + ValueIteratorT d_items, + OffsetT num_items, + CompareOpT compare_op, + cudaStream_t stream = 0) + { + using DispatchMergeSortT = DispatchMergeSort; + + return DispatchMergeSortT::Dispatch(d_temp_storage, + temp_storage_bytes, + d_keys, + d_items, + d_keys, + d_items, + num_items, + compare_op, + stream); + } + + template + CUB_DETAIL_RUNTIME_DEBUG_SYNC_IS_NOT_SUPPORTED + CUB_RUNTIME_FUNCTION static cudaError_t + SortPairs(void *d_temp_storage, + std::size_t &temp_storage_bytes, + KeyIteratorT d_keys, + ValueIteratorT d_items, + OffsetT num_items, + CompareOpT compare_op, + cudaStream_t stream, + bool debug_synchronous) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + + return SortPairs( + d_temp_storage, + temp_storage_bytes, + d_keys, + d_items, + num_items, + compare_op, + stream); + } + + /** + * @brief Sorts items using a merge sorting method. + * + * @par + * - SortPairsCopy is not guaranteed to be stable. That is, suppose + * that `i` and `j` are equivalent: neither one is less than the + * other. It is not guaranteed that the relative order of these + * two elements will be preserved by sort. + * - Input arrays `d_input_keys` and `d_input_items` are not modified. + * - Note that the behavior is undefined if the input and output ranges + * overlap in any way. + * + * @par Snippet + * The code snippet below illustrates the sorting of a device vector of + * `int` keys with associated vector of `int` values. + * @par + * @code + * #include + * // or equivalently + * + * // Declare, allocate, and initialize device-accessible pointers + * // for sorting data + * int num_items; // e.g., 7 + * int *d_keys; // e.g., [8, 6, 6, 5, 3, 0, 9] + * int *d_values; // e.g., [0, 1, 2, 3, 4, 5, 6] + * ... + * + * // Initialize comparator + * CustomOpT custom_op; + * + * // Determine temporary device storage requirements + * void *d_temp_storage = nullptr; + * std::size_t temp_storage_bytes = 0; + * cub::DeviceMergeSort::SortPairsCopy( + * d_temp_storage, temp_storage_bytes, + * d_keys, d_values, num_items, custom_op); + * + * // Allocate temporary storage + * cudaMalloc(&d_temp_storage, temp_storage_bytes); + * + * // Run sorting operation + * cub::DeviceMergeSort::SortPairsCopy( + * d_temp_storage, temp_storage_bytes, + * d_keys, d_values, num_items, custom_op); + * + * // d_keys <-- [0, 3, 5, 6, 6, 8, 9] + * // d_values <-- [5, 4, 3, 2, 1, 0, 6] + * + * @endcode + * + * @tparam KeyInputIteratorT + * is a model of [Random Access Iterator]. Its `value_type` is a model of + * [LessThan Comparable]. This `value_type`'s ordering relation is a + * *strict weak ordering* as defined in the [LessThan Comparable] + * requirements. + * + * @tparam ValueInputIteratorT + * is a model of [Random Access Iterator]. + * + * @tparam KeyIteratorT + * is a model of [Random Access Iterator]. `KeyIteratorT` is mutable, and + * its `value_type` is a model of [LessThan Comparable]. This `value_type`'s + * ordering relation is a *strict weak ordering* as defined in + * the [LessThan Comparable] requirements. + * + * @tparam ValueIteratorT + * is a model of [Random Access Iterator], and `ValueIteratorT` is mutable. + * + * @tparam OffsetT + * is an integer type for global offsets. + * + * @tparam CompareOpT + * is a type of callable object with the signature + * `bool operator()(KeyT lhs, KeyT rhs)` that models + * the [Strict Weak Ordering] concept. + * + * @param[in] d_temp_storage + * Device-accessible allocation of temporary storage. When `nullptr`, the + * required allocation size is written to `temp_storage_bytes` and no work + * is done. + * + * @param[in,out] temp_storage_bytes + * Reference to size in bytes of `d_temp_storage` allocation + * + * @param[in] d_input_keys + * Pointer to the input sequence of unsorted input keys + * + * @param[in] d_input_items + * Pointer to the input sequence of unsorted input values + * + * @param[out] d_output_keys + * Pointer to the output sequence of sorted input keys + * + * @param[out] d_output_items + * Pointer to the output sequence of sorted input values + * + * @param[in] num_items + * Number of items to sort + * + * @param[in] compare_op + * Comparison function object which returns `true` if the first argument is + * ordered before the second + * + * @param[in] stream + * **[optional]** CUDA stream to launch kernels within. Default is + * stream0. + * + * [Random Access Iterator]: https://en.cppreference.com/w/cpp/iterator/random_access_iterator + * [Strict Weak Ordering]: https://en.cppreference.com/w/cpp/concepts/strict_weak_order + * [LessThan Comparable]: https://en.cppreference.com/w/cpp/named_req/LessThanComparable + */ + template + CUB_RUNTIME_FUNCTION static cudaError_t + SortPairsCopy(void *d_temp_storage, + std::size_t &temp_storage_bytes, + KeyInputIteratorT d_input_keys, + ValueInputIteratorT d_input_items, + KeyIteratorT d_output_keys, + ValueIteratorT d_output_items, + OffsetT num_items, + CompareOpT compare_op, + cudaStream_t stream = 0) + { + using DispatchMergeSortT = DispatchMergeSort; + + return DispatchMergeSortT::Dispatch(d_temp_storage, + temp_storage_bytes, + d_input_keys, + d_input_items, + d_output_keys, + d_output_items, + num_items, + compare_op, + stream); + } + + template + CUB_DETAIL_RUNTIME_DEBUG_SYNC_IS_NOT_SUPPORTED + CUB_RUNTIME_FUNCTION static cudaError_t + SortPairsCopy(void *d_temp_storage, + std::size_t &temp_storage_bytes, + KeyInputIteratorT d_input_keys, + ValueInputIteratorT d_input_items, + KeyIteratorT d_output_keys, + ValueIteratorT d_output_items, + OffsetT num_items, + CompareOpT compare_op, + cudaStream_t stream, + bool debug_synchronous) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + + return SortPairsCopy(d_temp_storage, + temp_storage_bytes, + d_input_keys, + d_input_items, + d_output_keys, + d_output_items, + num_items, + compare_op, + stream); + } + + /** + * @brief Sorts items using a merge sorting method. + * + * @par + * SortKeys is not guaranteed to be stable. That is, suppose that `i` and `j` + * are equivalent: neither one is less than the other. It is not guaranteed + * that the relative order of these two elements will be preserved by sort. + * + * @par Snippet + * The code snippet below illustrates the sorting of a device vector of `int` + * keys. + * @par + * @code + * #include + * // or equivalently + * + * // Declare, allocate, and initialize device-accessible pointers + * // for sorting data + * int num_items; // e.g., 7 + * int *d_keys; // e.g., [8, 6, 7, 5, 3, 0, 9] + * ... + * + * // Initialize comparator + * CustomOpT custom_op; + * + * // Determine temporary device storage requirements + * void *d_temp_storage = nullptr; + * std::size_t temp_storage_bytes = 0; + * cub::DeviceMergeSort::SortKeys( + * d_temp_storage, temp_storage_bytes, + * d_keys, num_items, custom_op); + * + * // Allocate temporary storage + * cudaMalloc(&d_temp_storage, temp_storage_bytes); + * + * // Run sorting operation + * cub::DeviceMergeSort::SortKeys( + * d_temp_storage, temp_storage_bytes, + * d_keys, num_items, custom_op); + * + * // d_keys <-- [0, 3, 5, 6, 7, 8, 9] + * @endcode + * + * @tparam KeyIteratorT + * is a model of [Random Access Iterator]. `KeyIteratorT` is mutable, and + * its `value_type` is a model of [LessThan Comparable]. This `value_type`'s + * ordering relation is a *strict weak ordering* as defined in + * the [LessThan Comparable] requirements. + * + * @tparam OffsetT + * is an integer type for global offsets. + * + * @tparam CompareOpT + * is a type of callable object with the signature + * `bool operator()(KeyT lhs, KeyT rhs)` that models + * the [Strict Weak Ordering] concept. + * + * @param[in] d_temp_storage + * Device-accessible allocation of temporary storage. When `nullptr`, the + * required allocation size is written to `temp_storage_bytes` and no work + * is done. + * + * @param[in,out] temp_storage_bytes + * Reference to size in bytes of `d_temp_storage` allocation + * + * @param[in,out] d_keys + * Pointer to the input sequence of unsorted input keys + * + * @param[in] num_items + * Number of items to sort + * + * @param[in] compare_op + * Comparison function object which returns true if the first argument is + * ordered before the second + * + * @param[in] stream + * **[optional]** CUDA stream to launch kernels within. Default is + * stream0. + * + * [Random Access Iterator]: https://en.cppreference.com/w/cpp/iterator/random_access_iterator + * [Strict Weak Ordering]: https://en.cppreference.com/w/cpp/concepts/strict_weak_order + * [LessThan Comparable]: https://en.cppreference.com/w/cpp/named_req/LessThanComparable + */ + template + CUB_RUNTIME_FUNCTION static cudaError_t + SortKeys(void *d_temp_storage, + std::size_t &temp_storage_bytes, + KeyIteratorT d_keys, + OffsetT num_items, + CompareOpT compare_op, + cudaStream_t stream = 0) + { + using DispatchMergeSortT = DispatchMergeSort; + + return DispatchMergeSortT::Dispatch(d_temp_storage, + temp_storage_bytes, + d_keys, + static_cast(nullptr), + d_keys, + static_cast(nullptr), + num_items, + compare_op, + stream); + } + + template + CUB_DETAIL_RUNTIME_DEBUG_SYNC_IS_NOT_SUPPORTED + CUB_RUNTIME_FUNCTION static cudaError_t + SortKeys(void *d_temp_storage, + std::size_t &temp_storage_bytes, + KeyIteratorT d_keys, + OffsetT num_items, + CompareOpT compare_op, + cudaStream_t stream, + bool debug_synchronous) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + + return SortKeys(d_temp_storage, + temp_storage_bytes, + d_keys, + num_items, + compare_op, + stream); + } + + /** + * @brief Sorts items using a merge sorting method. + * + * @par + * - SortKeysCopy is not guaranteed to be stable. That is, suppose that `i` + * and `j` are equivalent: neither one is less than the other. It is not + * guaranteed that the relative order of these two elements will be + * preserved by sort. + * - Input array d_input_keys is not modified. + * - Note that the behavior is undefined if the input and output ranges + * overlap in any way. + * + * @par Snippet + * The code snippet below illustrates the sorting of a device vector of + * `int` keys. + * @par + * @code + * #include + * // or equivalently + * + * // Declare, allocate, and initialize device-accessible pointers for + * // sorting data + * int num_items; // e.g., 7 + * int *d_keys; // e.g., [8, 6, 7, 5, 3, 0, 9] + * ... + * + * // Initialize comparator + * CustomOpT custom_op; + * + * // Determine temporary device storage requirements + * void *d_temp_storage = nullptr; + * std::size_t temp_storage_bytes = 0; + * cub::DeviceMergeSort::SortKeysCopy( + * d_temp_storage, temp_storage_bytes, + * d_keys, num_items, custom_op); + * + * // Allocate temporary storage + * cudaMalloc(&d_temp_storage, temp_storage_bytes); + * + * // Run sorting operation + * cub::DeviceMergeSort::SortKeysCopy( + * d_temp_storage, temp_storage_bytes, + * d_keys, num_items, custom_op); + * + * // d_keys <-- [0, 3, 5, 6, 7, 8, 9] + * @endcode + * + * @tparam KeyInputIteratorT + * is a model of [Random Access Iterator]. Its `value_type` is a model of + * [LessThan Comparable]. This `value_type`'s ordering relation is a + * *strict weak ordering* as defined in the [LessThan Comparable] + * requirements. + * + * @tparam KeyIteratorT + * is a model of [Random Access Iterator]. `KeyIteratorT` is mutable, and + * its `value_type` is a model of [LessThan Comparable]. This `value_type`'s + * ordering relation is a *strict weak ordering* as defined in + * the [LessThan Comparable] requirements. + * + * @tparam OffsetT + * is an integer type for global offsets. + * + * @tparam CompareOpT + * is a type of callable object with the signature + * `bool operator()(KeyT lhs, KeyT rhs)` that models + * the [Strict Weak Ordering] concept. + * + * @param[in] d_temp_storage + * Device-accessible allocation of temporary storage. When `nullptr`, the + * required allocation size is written to `temp_storage_bytes` and no work + * is done. + * + * @param[in,out] temp_storage_bytes + * Reference to size in bytes of `d_temp_storage` allocation + * + * @param[in] d_input_keys + * Pointer to the input sequence of unsorted input keys + * + * @param[out] d_output_keys + * Pointer to the output sequence of sorted input keys + * + * @param[in] num_items + * Number of items to sort + * + * @param[in] compare_op + * Comparison function object which returns true if the first argument is + * ordered before the second + * + * @param[in] stream + * **[optional]** CUDA stream to launch kernels within. Default is + * stream0. + * + * [Random Access Iterator]: https://en.cppreference.com/w/cpp/iterator/random_access_iterator + * [Strict Weak Ordering]: https://en.cppreference.com/w/cpp/concepts/strict_weak_order + * [LessThan Comparable]: https://en.cppreference.com/w/cpp/named_req/LessThanComparable + */ + template + CUB_RUNTIME_FUNCTION static cudaError_t + SortKeysCopy(void *d_temp_storage, + std::size_t &temp_storage_bytes, + KeyInputIteratorT d_input_keys, + KeyIteratorT d_output_keys, + OffsetT num_items, + CompareOpT compare_op, + cudaStream_t stream = 0) + { + using DispatchMergeSortT = DispatchMergeSort; + + return DispatchMergeSortT::Dispatch(d_temp_storage, + temp_storage_bytes, + d_input_keys, + static_cast(nullptr), + d_output_keys, + static_cast(nullptr), + num_items, + compare_op, + stream); + } + + template + CUB_DETAIL_RUNTIME_DEBUG_SYNC_IS_NOT_SUPPORTED + CUB_RUNTIME_FUNCTION static cudaError_t + SortKeysCopy(void *d_temp_storage, + std::size_t &temp_storage_bytes, + KeyInputIteratorT d_input_keys, + KeyIteratorT d_output_keys, + OffsetT num_items, + CompareOpT compare_op, + cudaStream_t stream, + bool debug_synchronous) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + + return SortKeysCopy( + d_temp_storage, + temp_storage_bytes, + d_input_keys, + d_output_keys, + num_items, + compare_op, + stream); + } + + /** + * @brief Sorts items using a merge sorting method. + * + * @par + * StableSortPairs is stable: it preserves the relative ordering of equivalent + * elements. That is, if x and y are elements such that x precedes y, + * and if the two elements are equivalent (neither x < y nor y < x) then + * a postcondition of stable_sort is that x still precedes y. + * + * @par Snippet + * The code snippet below illustrates the sorting of a device vector of `int` + * keys with associated vector of `int` values. + * @par + * @code + * #include + * // or equivalently + * + * // Declare, allocate, and initialize device-accessible pointers for + * // sorting data + * int num_items; // e.g., 7 + * int *d_keys; // e.g., [8, 6, 6, 5, 3, 0, 9] + * int *d_values; // e.g., [0, 1, 2, 3, 4, 5, 6] + * ... + * + * // Initialize comparator + * CustomOpT custom_op; + * + * // Determine temporary device storage requirements + * void *d_temp_storage = nullptr; + * std::size_t temp_storage_bytes = 0; + * cub::DeviceMergeSort::StableSortPairs( + * d_temp_storage, temp_storage_bytes, + * d_keys, d_values, num_items, custom_op); + * + * // Allocate temporary storage + * cudaMalloc(&d_temp_storage, temp_storage_bytes); + * + * // Run sorting operation + * cub::DeviceMergeSort::StableSortPairs( + * d_temp_storage, temp_storage_bytes, + * d_keys, d_values, num_items, custom_op); + * + * // d_keys <-- [0, 3, 5, 6, 6, 8, 9] + * // d_values <-- [5, 4, 3, 1, 2, 0, 6] + * @endcode + * + * @tparam KeyIteratorT + * is a model of [Random Access Iterator]. `KeyIteratorT` is mutable, and + * its `value_type` is a model of [LessThan Comparable]. This `value_type`'s + * ordering relation is a *strict weak ordering* as defined in + * the [LessThan Comparable] requirements. + * + * @tparam ValueIteratorT + * is a model of [Random Access Iterator], and `ValueIteratorT` is mutable. + * + * @tparam OffsetT + * is an integer type for global offsets. + * + * @tparam CompareOpT + * is a type of callable object with the signature + * `bool operator()(KeyT lhs, KeyT rhs)` that models + * the [Strict Weak Ordering] concept. + * + * @param[in] d_temp_storage + * Device-accessible allocation of temporary storage. When `nullptr`, the + * required allocation size is written to `temp_storage_bytes` and no work + * is done. + * + * @param[in,out] temp_storage_bytes + * Reference to size in bytes of `d_temp_storage` allocation + * + * @param[in,out] d_keys + * Pointer to the input sequence of unsorted input keys + * + * @param[in,out] d_items + * Pointer to the input sequence of unsorted input values + * + * @param[in] num_items + * Number of items to sort + * + * @param[in] compare_op + * Comparison function object which returns true if the first argument is + * ordered before the second + * + * @param[in] stream + * **[optional]** CUDA stream to launch kernels within. Default is + * stream0. + * + * [Random Access Iterator]: https://en.cppreference.com/w/cpp/iterator/random_access_iterator + * [Strict Weak Ordering]: https://en.cppreference.com/w/cpp/concepts/strict_weak_order + * [LessThan Comparable]: https://en.cppreference.com/w/cpp/named_req/LessThanComparable + */ + template + CUB_RUNTIME_FUNCTION static cudaError_t + StableSortPairs(void *d_temp_storage, + std::size_t &temp_storage_bytes, + KeyIteratorT d_keys, + ValueIteratorT d_items, + OffsetT num_items, + CompareOpT compare_op, + cudaStream_t stream = 0) + { + return SortPairs( + d_temp_storage, + temp_storage_bytes, + d_keys, + d_items, + num_items, + compare_op, + stream); + } + + template + CUB_DETAIL_RUNTIME_DEBUG_SYNC_IS_NOT_SUPPORTED + CUB_RUNTIME_FUNCTION static cudaError_t + StableSortPairs(void *d_temp_storage, + std::size_t &temp_storage_bytes, + KeyIteratorT d_keys, + ValueIteratorT d_items, + OffsetT num_items, + CompareOpT compare_op, + cudaStream_t stream, + bool debug_synchronous) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + + return StableSortPairs( + d_temp_storage, + temp_storage_bytes, + d_keys, + d_items, + num_items, + compare_op, + stream); + } + + /** + * @brief Sorts items using a merge sorting method. + * + * @par + * StableSortKeys is stable: it preserves the relative ordering of equivalent + * elements. That is, if `x` and `y` are elements such that `x` precedes `y`, + * and if the two elements are equivalent (neither `x < y` nor `y < x`) then + * a postcondition of stable_sort is that `x` still precedes `y`. + * + * @par Snippet + * The code snippet below illustrates the sorting of a device vector of `int` + * keys. + * \par + * \code + * #include + * // or equivalently + * + * // Declare, allocate, and initialize device-accessible pointers for + * // sorting data + * int num_items; // e.g., 7 + * int *d_keys; // e.g., [8, 6, 7, 5, 3, 0, 9] + * ... + * + * // Initialize comparator + * CustomOpT custom_op; + * + * // Determine temporary device storage requirements + * void *d_temp_storage = nullptr; + * std::size_t temp_storage_bytes = 0; + * cub::DeviceMergeSort::StableSortKeys( + * d_temp_storage, temp_storage_bytes, + * d_keys, num_items, custom_op); + * + * // Allocate temporary storage + * cudaMalloc(&d_temp_storage, temp_storage_bytes); + * + * // Run sorting operation + * cub::DeviceMergeSort::StableSortKeys( + * d_temp_storage, temp_storage_bytes, + * d_keys, num_items, custom_op); + * + * // d_keys <-- [0, 3, 5, 6, 7, 8, 9] + * @endcode + * + * @tparam KeyIteratorT + * is a model of [Random Access Iterator]. `KeyIteratorT` is mutable, and + * its `value_type` is a model of [LessThan Comparable]. This `value_type`'s + * ordering relation is a *strict weak ordering* as defined in + * the [LessThan Comparable] requirements. + * + * @tparam OffsetT + * is an integer type for global offsets. + * + * @tparam CompareOpT + * is a type of callable object with the signature + * `bool operator()(KeyT lhs, KeyT rhs)` that models + * the [Strict Weak Ordering] concept. + * + * @param[in] d_temp_storage + * Device-accessible allocation of temporary storage. When `nullptr`, the + * required allocation size is written to `temp_storage_bytes` and no work + * is done. + * + * @param[in,out] temp_storage_bytes + * Reference to size in bytes of `d_temp_storage` allocation + * + * @param[in,out] d_keys + * Pointer to the input sequence of unsorted input keys + * + * @param[in] num_items + * Number of items to sort + * + * @param[in] compare_op + * Comparison function object which returns true if the first argument is + * ordered before the second + * + * @param[in] stream + * **[optional]** CUDA stream to launch kernels within. Default is + * stream0. + * + * [Random Access Iterator]: https://en.cppreference.com/w/cpp/iterator/random_access_iterator + * [Strict Weak Ordering]: https://en.cppreference.com/w/cpp/concepts/strict_weak_order + * [LessThan Comparable]: https://en.cppreference.com/w/cpp/named_req/LessThanComparable + */ + template + CUB_RUNTIME_FUNCTION static cudaError_t + StableSortKeys(void *d_temp_storage, + std::size_t &temp_storage_bytes, + KeyIteratorT d_keys, + OffsetT num_items, + CompareOpT compare_op, + cudaStream_t stream = 0) + { + return SortKeys(d_temp_storage, + temp_storage_bytes, + d_keys, + num_items, + compare_op, + stream); + } + + template + CUB_DETAIL_RUNTIME_DEBUG_SYNC_IS_NOT_SUPPORTED + CUB_RUNTIME_FUNCTION static cudaError_t + StableSortKeys(void *d_temp_storage, + std::size_t &temp_storage_bytes, + KeyIteratorT d_keys, + OffsetT num_items, + CompareOpT compare_op, + cudaStream_t stream, + bool debug_synchronous) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + + return StableSortKeys(d_temp_storage, + temp_storage_bytes, + d_keys, + num_items, + compare_op, + stream); + } + + /** + * @brief Sorts items using a merge sorting method. + * + * @par + * - StableSortKeysCopy is stable: it preserves the relative ordering of equivalent + * elements. That is, if `x` and `y` are elements such that `x` precedes `y`, + * and if the two elements are equivalent (neither `x < y` nor `y < x`) then + * a postcondition of stable_sort is that `x` still precedes `y`. + * - Input array d_input_keys is not modified + * - Note that the behavior is undefined if the input and output ranges overlap + * in any way. + * + * @par Snippet + * The code snippet below illustrates the sorting of a device vector of `int` + * keys. + * \par + * \code + * #include + * // or equivalently + * + * // Declare, allocate, and initialize device-accessible pointers for + * // sorting data + * int num_items; // e.g., 7 + * int *d_input_keys; // e.g., [8, 6, 7, 5, 3, 0, 9] + * int *d_output_keys; // must hold at least num_items elements + * ... + * + * // Initialize comparator + * CustomOpT custom_op; + * + * // Determine temporary device storage requirements + * void *d_temp_storage = nullptr; + * std::size_t temp_storage_bytes = 0; + * cub::DeviceMergeSort::StableSortKeysCopy( + * d_temp_storage, temp_storage_bytes, + * d_input_keys, d_output_keys, num_items, custom_op); + * + * // Allocate temporary storage + * cudaMalloc(&d_temp_storage, temp_storage_bytes); + * + * // Run sorting operation + * cub::DeviceMergeSort::StableSortKeysCopy( + * d_temp_storage, temp_storage_bytes, + * d_input_keys, d_output_keys, num_items, custom_op); + * + * // d_output_keys <-- [0, 3, 5, 6, 7, 8, 9] + * @endcode + * + * @tparam KeyInputIteratorT + * is a model of [Random Access Iterator]. Its `value_type` is a model of + * [LessThan Comparable]. This `value_type`'s ordering relation is a + * *strict weak ordering* as defined in the [LessThan Comparable] + * requirements. + * + * @tparam KeyIteratorT + * is a model of [Random Access Iterator]. `KeyIteratorT` is mutable, and + * its `value_type` is a model of [LessThan Comparable]. This `value_type`'s + * ordering relation is a *strict weak ordering* as defined in + * the [LessThan Comparable] requirements. + * + * @tparam OffsetT + * is an integer type for global offsets. + * + * @tparam CompareOpT + * is a type of callable object with the signature + * `bool operator()(KeyT lhs, KeyT rhs)` that models + * the [Strict Weak Ordering] concept. + * + * @param[in] d_temp_storage + * Device-accessible allocation of temporary storage. When `nullptr`, the + * required allocation size is written to `temp_storage_bytes` and no work + * is done. + * + * @param[in,out] temp_storage_bytes + * Reference to size in bytes of `d_temp_storage` allocation + * + * @param[in] d_input_keys + * Pointer to the input sequence of unsorted input keys + * + * @param[out] d_output_keys + * Pointer to the output sequence of sorted input keys + * + * @param[in] num_items + * Number of elements in d_input_keys to sort + * + * @param[in] compare_op + * Comparison function object which returns true if the first argument is + * ordered before the second + * + * @param[in] stream + * **[optional]** CUDA stream to launch kernels within. Default is + * stream0. + * + * [Random Access Iterator]: https://en.cppreference.com/w/cpp/iterator/random_access_iterator + * [Strict Weak Ordering]: https://en.cppreference.com/w/cpp/concepts/strict_weak_order + * [LessThan Comparable]: https://en.cppreference.com/w/cpp/named_req/LessThanComparable + */ + template + CUB_RUNTIME_FUNCTION static cudaError_t + StableSortKeysCopy(void *d_temp_storage, + std::size_t &temp_storage_bytes, + KeyInputIteratorT d_input_keys, + KeyIteratorT d_output_keys, + OffsetT num_items, + CompareOpT compare_op, + cudaStream_t stream = 0) + { + return SortKeysCopy(d_temp_storage, + temp_storage_bytes, + d_input_keys, + d_output_keys, + num_items, + compare_op, + stream); + } +}; + +CUB_NAMESPACE_END diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/device/device_radix_sort.cuh b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/device/device_radix_sort.cuh new file mode 100644 index 0000000000000000000000000000000000000000..da40a6654c61b041d9e71b6c6c599f74488821e2 --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/device/device_radix_sort.cuh @@ -0,0 +1,3643 @@ +/****************************************************************************** + * Copyright (c) 2011, Duane Merrill. All rights reserved. + * Copyright (c) 2011-2023, NVIDIA CORPORATION. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the NVIDIA CORPORATION nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ******************************************************************************/ + +//! @file cub::DeviceRadixSort provides device-wide, parallel operations for +//! computing a radix sort across a sequence of data items residing within +//! device-accessible memory. + +#pragma once + +#include +#include +#include +#include + +#include + + +CUB_NAMESPACE_BEGIN + + +//! @brief DeviceRadixSort provides device-wide, parallel operations for +//! computing a radix sort across a sequence of data items residing +//! within device-accessible memory. ![](sorting_logo.png) +//! @ingroup SingleModule +//! +//! @par Overview +//! The [*radix sorting method*](http://en.wikipedia.org/wiki/Radix_sort) +//! arranges items into ascending (or descending) order. The algorithm relies +//! upon a positional representation for keys, i.e., each key is comprised of an +//! ordered sequence of symbols (e.g., digits, characters, etc.) specified from +//! least-significant to most-significant. For a given input sequence of keys +//! and a set of rules specifying a total ordering of the symbolic alphabet, the +//! radix sorting method produces a lexicographic ordering of those keys. +//! +//! @par Supported Types +//! DeviceRadixSort can sort all of the built-in C++ numeric primitive types +//! (`unsigned char`, `int`, `double`, etc.) as well as CUDA's `__half` +//! and `__nv_bfloat16` 16-bit floating-point types. User-defined types are +//! supported as long as decomposer object is provided. +//! +//! @par Floating-Point Special Cases +//! +//! - Positive and negative zeros are considered equivalent, and will be treated +//! as such in the output. +//! - No special handling is implemented for NaN values; these are sorted +//! according to their bit representations after any transformations. +//! +//! @par Transformations +//! Although the direct radix sorting method can only be applied to unsigned +//! integral types, DeviceRadixSort is able to sort signed and floating-point +//! types via simple bit-wise transformations that ensure lexicographic key +//! ordering. Additional transformations occur for descending sorts. These +//! transformations must be considered when restricting the +//! `[begin_bit, end_bit)` range, as the bitwise transformations will occur +//! before the bit-range truncation. +//! +//! Any transformations applied to the keys prior to sorting are reversed +//! while writing to the final output buffer. +//! +//! @par Type Specific Bitwise Transformations +//! To convert the input values into a radix-sortable bitwise representation, +//! the following transformations take place prior to sorting: +//! +//! - For unsigned integral values, the keys are used directly. +//! - For signed integral values, the sign bit is inverted. +//! - For positive floating point values, the sign bit is inverted. +//! - For negative floating point values, the full key is inverted. +//! +//! For floating point types, positive and negative zero are a special case and +//! will be considered equivalent during sorting. +//! +//! @par Descending Sort Bitwise Transformations +//! If descending sort is used, the keys are inverted after performing any +//! type-specific transformations, and the resulting keys are sorted in ascending +//! order. +//! +//! @par Stability +//! DeviceRadixSort is stable. For floating-point types, `-0.0` and `+0.0` are +//! considered equal and appear in the result in the same order as they appear in +//! the input. +//! +//! @par Usage Considerations +//! @cdp_class{DeviceRadixSort} +//! +//! @par Performance +//! @linear_performance{radix sort} The following chart illustrates +//! DeviceRadixSort::SortKeys performance across different CUDA architectures +//! for uniform-random `uint32` keys. +//! @plots_below +//! +//! @image html lsb_radix_sort_int32_keys.png +struct DeviceRadixSort +{ +private: + template + CUB_RUNTIME_FUNCTION static cudaError_t custom_radix_sort(::cuda::std::false_type, + void *d_temp_storage, + size_t &temp_storage_bytes, + bool is_overwrite_okay, + DoubleBuffer &d_keys, + DoubleBuffer &d_values, + NumItemsT num_items, + DecomposerT decomposer, + int begin_bit, + int end_bit, + cudaStream_t stream); + + template + CUB_RUNTIME_FUNCTION static cudaError_t custom_radix_sort(::cuda::std::true_type, + void *d_temp_storage, + size_t &temp_storage_bytes, + bool is_overwrite_okay, + DoubleBuffer &d_keys, + DoubleBuffer &d_values, + OffsetT num_items, + DecomposerT decomposer, + int begin_bit, + int end_bit, + cudaStream_t stream) + { + return DispatchRadixSort, + DecomposerT>::Dispatch(d_temp_storage, + temp_storage_bytes, + d_keys, + d_values, + static_cast(num_items), + begin_bit, + end_bit, + is_overwrite_okay, + stream, + decomposer); + } + + template + CUB_RUNTIME_FUNCTION static cudaError_t custom_radix_sort(::cuda::std::false_type, + void *d_temp_storage, + size_t &temp_storage_bytes, + bool is_overwrite_okay, + DoubleBuffer &d_keys, + DoubleBuffer &d_values, + NumItemsT num_items, + DecomposerT decomposer, + cudaStream_t stream); + + template + CUB_RUNTIME_FUNCTION static cudaError_t custom_radix_sort(::cuda::std::true_type, + void *d_temp_storage, + size_t &temp_storage_bytes, + bool is_overwrite_okay, + DoubleBuffer &d_keys, + DoubleBuffer &d_values, + OffsetT num_items, + DecomposerT decomposer, + cudaStream_t stream) + { + const int begin_bit = 0; + const int end_bit = detail::radix::traits_t::default_end_bit(decomposer); + + return DeviceRadixSort::custom_radix_sort(::cuda::std::true_type{}, + d_temp_storage, + temp_storage_bytes, + is_overwrite_okay, + d_keys, + d_values, + num_items, + decomposer, + begin_bit, + end_bit, + stream); + } + +public: + + //! @name KeyT-value pairs + //@{ + + //! @brief Sorts key-value pairs into ascending order. + //! (`~2N` auxiliary storage required) + //! + //! @par + //! - The contents of the input data are not altered by the sorting operation. + //! - Pointers to contiguous memory must be used; iterators are not currently + //! supported. + //! - In-place operations are not supported. There must be no overlap between + //! any of the provided ranges: + //! - `[d_keys_in, d_keys_in + num_items)` + //! - `[d_keys_out, d_keys_out + num_items)` + //! - `[d_values_in, d_values_in + num_items)` + //! - `[d_values_out, d_values_out + num_items)` + //! - An optional bit subrange `[begin_bit, end_bit)` of differentiating key + //! bits can be specified. This can reduce overall sorting overhead and + //! yield a corresponding performance improvement. + //! - @devicestorageNP For sorting using only `O(P)` temporary storage, see + //! the sorting interface using DoubleBuffer wrappers below. + //! - @devicestorage + //! + //! @par Performance + //! The following charts illustrate saturated sorting performance across + //! different CUDA architectures for uniform-random `uint32, uint32` and + //! `uint64, uint64` pairs, respectively. + //! + //! @image html lsb_radix_sort_int32_pairs.png + //! @image html lsb_radix_sort_int64_pairs.png + //! + //! @par Snippet + //! The code snippet below illustrates the sorting of a device vector of `int` + //! keys with associated vector of `int` values. + //! @par + //! @code + //! #include + //! // or equivalently + //! + //! // Declare, allocate, and initialize device-accessible pointers + //! // for sorting data + //! int num_items; // e.g., 7 + //! int *d_keys_in; // e.g., [8, 6, 7, 5, 3, 0, 9] + //! int *d_keys_out; // e.g., [ ... ] + //! int *d_values_in; // e.g., [0, 1, 2, 3, 4, 5, 6] + //! int *d_values_out; // e.g., [ ... ] + //! ... + //! + //! // Determine temporary device storage requirements + //! void *d_temp_storage = NULL; + //! size_t temp_storage_bytes = 0; + //! cub::DeviceRadixSort::SortPairs(d_temp_storage, temp_storage_bytes, + //! d_keys_in, d_keys_out, d_values_in, d_values_out, num_items); + //! + //! // Allocate temporary storage + //! cudaMalloc(&d_temp_storage, temp_storage_bytes); + //! + //! // Run sorting operation + //! cub::DeviceRadixSort::SortPairs(d_temp_storage, temp_storage_bytes, + //! d_keys_in, d_keys_out, d_values_in, d_values_out, num_items); + //! + //! // d_keys_out <-- [0, 3, 5, 6, 7, 8, 9] + //! // d_values_out <-- [5, 4, 3, 1, 2, 0, 6] + //! @endcode + //! + //! @tparam KeyT + //! **[inferred]** KeyT type + //! + //! @tparam ValueT + //! **[inferred]** ValueT type + //! + //! @tparam NumItemsT + //! **[inferred]** Type of num_items + //! + //! @param[in] d_temp_storage + //! Device-accessible allocation of temporary storage. When `nullptr`, the + //! required allocation size is written to `temp_storage_bytes` and no work + //! is done. + //! + //! @param[in,out] temp_storage_bytes + //! Reference to size in bytes of `d_temp_storage` allocation + //! + //! @param[in] d_keys_in + //! Pointer to the input data of key data to sort + //! + //! @param[out] d_keys_out + //! Pointer to the sorted output sequence of key data + //! + //! @param[in] d_values_in + //! Pointer to the corresponding input sequence of associated value items + //! + //! @param[out] d_values_out + //! Pointer to the correspondingly-reordered output sequence of associated + //! value items + //! + //! @param[in] num_items + //! Number of items to sort + //! + //! @param[in] begin_bit + //! **[optional]** The least-significant bit index (inclusive) needed for + //! key comparison + //! + //! @param[in] end_bit + //! **[optional]** The most-significant bit index (exclusive) needed for key + //! comparison (e.g., sizeof(unsigned int) * 8) + //! + //! @param[in] stream + //! **[optional]** CUDA stream to launch kernels within. + //! Default is stream0. + template + CUB_RUNTIME_FUNCTION static cudaError_t + SortPairs(void *d_temp_storage, + size_t &temp_storage_bytes, + const KeyT *d_keys_in, + KeyT *d_keys_out, + const ValueT *d_values_in, + ValueT *d_values_out, + NumItemsT num_items, + int begin_bit = 0, + int end_bit = sizeof(KeyT) * 8, + cudaStream_t stream = 0) + { + // Unsigned integer type for global offsets. + using OffsetT = typename detail::ChooseOffsetT::Type; + + // TODO API that doesn't accept decomposer should also contain a static + // assert that the key type is fundamental. + + // We cast away const-ness, but will *not* write to these arrays. + // `DispatchRadixSort::Dispatch` will allocate temporary storage and + // create a new double-buffer internally when the `is_overwrite_ok` flag + // is not set. + constexpr bool is_overwrite_okay = false; + DoubleBuffer d_keys(const_cast(d_keys_in), d_keys_out); + DoubleBuffer d_values(const_cast(d_values_in), + d_values_out); + + return DispatchRadixSort::Dispatch( + d_temp_storage, + temp_storage_bytes, + d_keys, + d_values, + static_cast(num_items), + begin_bit, + end_bit, + is_overwrite_okay, + stream); + } + + #ifndef DOXYGEN_SHOULD_SKIP_THIS // Do not document + template + CUB_DETAIL_RUNTIME_DEBUG_SYNC_IS_NOT_SUPPORTED + CUB_RUNTIME_FUNCTION static cudaError_t + SortPairs(void *d_temp_storage, + size_t &temp_storage_bytes, + const KeyT *d_keys_in, + KeyT *d_keys_out, + const ValueT *d_values_in, + ValueT *d_values_out, + NumItemsT num_items, + int begin_bit, + int end_bit, + cudaStream_t stream, + bool debug_synchronous) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + + return SortPairs(d_temp_storage, + temp_storage_bytes, + d_keys_in, + d_keys_out, + d_values_in, + d_values_out, + num_items, + begin_bit, + end_bit, + stream); + } + #endif + + //! @rst + //! Sorts key-value pairs into ascending order using :math:`\approx 2N` auxiliary storage. + //! + //! * The contents of the input data are not altered by the sorting operation. + //! * Pointers to contiguous memory must be used; iterators are not currently + //! supported. + //! * In-place operations are not supported. There must be no overlap between + //! any of the provided ranges: + //! + //! * ``[d_keys_in, d_keys_in + num_items)`` + //! * ``[d_keys_out, d_keys_out + num_items)`` + //! * ``[d_values_in, d_values_in + num_items)`` + //! * ``[d_values_out, d_values_out + num_items)`` + //! + //! * A bit subrange ``[begin_bit, end_bit)`` is provided to specify + //! differentiating key bits. This can reduce overall sorting overhead and + //! yield a corresponding performance improvement. + //! * @devicestorageNP For sorting using only :math:`O(P)` temporary storage, see + //! the sorting interface using DoubleBuffer wrappers below. + //! * @devicestorage + //! + //! Snippet + //! ========================================================================== + //! + //! Let's consider a user-defined ``custom_t`` type below. To sort an array of + //! ``custom_t`` objects, we have to tell CUB about relevant members of the + //! ``custom_t`` type. We do this by providing a decomposer that returns a + //! tuple of references to relevant members of the key. + //! + //! .. literalinclude:: ../../test/catch2_test_device_radix_sort_custom.cu + //! :language: c++ + //! :dedent: + //! :start-after: example-begin custom-type + //! :end-before: example-end custom-type + //! + //! The following snippet shows how to sort an array of ``custom_t`` objects + //! using ``cub::DeviceRadixSort::SortPairs``: + //! + //! .. literalinclude:: ../../test/catch2_test_device_radix_sort_custom.cu + //! :language: c++ + //! :dedent: + //! :start-after: example-begin pairs-bits + //! :end-before: example-end pairs-bits + //! + //! @endrst + //! + //! @tparam KeyT + //! **[inferred]** KeyT type + //! + //! @tparam ValueT + //! **[inferred]** ValueT type + //! + //! @tparam NumItemsT + //! **[inferred]** Type of num_items + //! + //! @tparam DecomposerT + //! **[inferred]** Type of a callable object responsible for decomposing a + //! ``KeyT`` into a tuple of references to its constituent arithmetic types: + //! ``::cuda::std::tuple operator()(KeyT &key)``. + //! The leftmost element of the tuple is considered the most significant. + //! The call operator must not modify members of the key. + //! + //! @param[in] d_temp_storage + //! Device-accessible allocation of temporary storage. When `nullptr`, the + //! required allocation size is written to `temp_storage_bytes` and no work + //! is done. + //! + //! @param[in,out] temp_storage_bytes + //! Reference to size in bytes of `d_temp_storage` allocation + //! + //! @param[in] d_keys_in + //! Pointer to the input data of key data to sort + //! + //! @param[out] d_keys_out + //! Pointer to the sorted output sequence of key data + //! + //! @param[in] d_values_in + //! Pointer to the corresponding input sequence of associated value items + //! + //! @param[out] d_values_out + //! Pointer to the correspondingly-reordered output sequence of associated + //! value items + //! + //! @param[in] num_items + //! Number of items to sort + //! + //! @param decomposer + //! Callable object responsible for decomposing a ``KeyT`` into a tuple of + //! references to its constituent arithmetic types. The leftmost element of + //! the tuple is considered the most significant. The call operator must not + //! modify members of the key. + //! + //! @param[in] begin_bit + //! **[optional]** The least-significant bit index (inclusive) needed for + //! key comparison + //! + //! @param[in] end_bit + //! **[optional]** The most-significant bit index (exclusive) needed for key + //! comparison (e.g., `(sizeof(float) + sizeof(long long int)) * 8`) + //! + //! @param[in] stream + //! **[optional]** CUDA stream to launch kernels within. + //! Default is stream0. + template + CUB_RUNTIME_FUNCTION static // + typename ::cuda::std::enable_if< // + !::cuda::std::is_convertible::value, // + cudaError_t>::type + SortPairs(void *d_temp_storage, + size_t &temp_storage_bytes, + const KeyT *d_keys_in, + KeyT *d_keys_out, + const ValueT *d_values_in, + ValueT *d_values_out, + NumItemsT num_items, + DecomposerT decomposer, + int begin_bit, + int end_bit, + cudaStream_t stream = 0) + { + // unsigned integer type for global offsets + using offset_t = typename detail::ChooseOffsetT::Type; + using decomposer_check_t = detail::radix::decomposer_check_t; + + static_assert(decomposer_check_t::value, + "DecomposerT must be a callable object returning a tuple of references to " + "arithmetic types"); + + // We cast away const-ness, but will *not* write to these arrays. + // `DispatchRadixSort::Dispatch` will allocate temporary storage and + // create a new double-buffer internally when the `is_overwrite_ok` flag + // is not set. + constexpr bool is_overwrite_okay = false; + constexpr bool is_descending = false; + DoubleBuffer d_keys(const_cast(d_keys_in), d_keys_out); + DoubleBuffer d_values(const_cast(d_values_in), d_values_out); + + return DeviceRadixSort::custom_radix_sort(decomposer_check_t{}, + d_temp_storage, + temp_storage_bytes, + is_overwrite_okay, + d_keys, + d_values, + static_cast(num_items), + decomposer, + begin_bit, + end_bit, + stream); + } + + //! @rst + //! Sorts key-value pairs into ascending order using :math:`\approx 2N` auxiliary storage. + //! + //! * The contents of the input data are not altered by the sorting operation. + //! * Pointers to contiguous memory must be used; iterators are not currently + //! supported. + //! * In-place operations are not supported. There must be no overlap between + //! any of the provided ranges: + //! + //! * ``[d_keys_in, d_keys_in + num_items)`` + //! * ``[d_keys_out, d_keys_out + num_items)`` + //! * ``[d_values_in, d_values_in + num_items)`` + //! * ``[d_values_out, d_values_out + num_items)`` + //! + //! * @devicestorageNP For sorting using only :math:`O(P)` temporary storage, see + //! the sorting interface using DoubleBuffer wrappers below. + //! * @devicestorage + //! + //! Snippet + //! ========================================================================== + //! + //! Let's consider a user-defined ``custom_t`` type below. To sort an array of + //! ``custom_t`` objects, we have to tell CUB about relevant members of the + //! ``custom_t`` type. We do this by providing a decomposer that returns a + //! tuple of references to relevant members of the key. + //! + //! .. literalinclude:: ../../test/catch2_test_device_radix_sort_custom.cu + //! :language: c++ + //! :dedent: + //! :start-after: example-begin custom-type + //! :end-before: example-end custom-type + //! + //! The following snippet shows how to sort an array of ``custom_t`` objects + //! using ``cub::DeviceRadixSort::SortPairs``: + //! + //! .. literalinclude:: ../../test/catch2_test_device_radix_sort_custom.cu + //! :language: c++ + //! :dedent: + //! :start-after: example-begin pairs + //! :end-before: example-end pairs + //! + //! @endrst + //! + //! @tparam KeyT + //! **[inferred]** KeyT type + //! + //! @tparam ValueT + //! **[inferred]** ValueT type + //! + //! @tparam NumItemsT + //! **[inferred]** Type of num_items + //! + //! @tparam DecomposerT + //! **[inferred]** Type of a callable object responsible for decomposing a + //! ``KeyT`` into a tuple of references to its constituent arithmetic types: + //! ``::cuda::std::tuple operator()(KeyT &key)``. + //! The leftmost element of the tuple is considered the most significant. + //! The call operator must not modify members of the key. + //! + //! @param[in] d_temp_storage + //! Device-accessible allocation of temporary storage. When `nullptr`, the + //! required allocation size is written to `temp_storage_bytes` and no work + //! is done. + //! + //! @param[in,out] temp_storage_bytes + //! Reference to size in bytes of `d_temp_storage` allocation + //! + //! @param[in] d_keys_in + //! Pointer to the input data of key data to sort + //! + //! @param[out] d_keys_out + //! Pointer to the sorted output sequence of key data + //! + //! @param[in] d_values_in + //! Pointer to the corresponding input sequence of associated value items + //! + //! @param[out] d_values_out + //! Pointer to the correspondingly-reordered output sequence of associated + //! value items + //! + //! @param[in] num_items + //! Number of items to sort + //! + //! @param decomposer + //! Callable object responsible for decomposing a ``KeyT`` into a tuple of + //! references to its constituent arithmetic types. The leftmost element of + //! the tuple is considered the most significant. The call operator must not + //! modify members of the key. + //! + //! @param[in] stream + //! **[optional]** CUDA stream to launch kernels within. + //! Default is stream0. + template + CUB_RUNTIME_FUNCTION static // + typename ::cuda::std::enable_if< // + !::cuda::std::is_convertible::value, // + cudaError_t>::type + SortPairs(void *d_temp_storage, + size_t &temp_storage_bytes, + const KeyT *d_keys_in, + KeyT *d_keys_out, + const ValueT *d_values_in, + ValueT *d_values_out, + NumItemsT num_items, + DecomposerT decomposer, + cudaStream_t stream = 0) + { + // unsigned integer type for global offsets + using offset_t = typename detail::ChooseOffsetT::Type; + using decomposer_check_t = detail::radix::decomposer_check_t; + + static_assert(decomposer_check_t::value, + "DecomposerT must be a callable object returning a tuple of references to " + "arithmetic types"); + + // We cast away const-ness, but will *not* write to these arrays. + // `DispatchRadixSort::Dispatch` will allocate temporary storage and + // create a new double-buffer internally when the `is_overwrite_ok` flag + // is not set. + constexpr bool is_overwrite_okay = false; + constexpr bool is_descending = false; + DoubleBuffer d_keys(const_cast(d_keys_in), d_keys_out); + DoubleBuffer d_values(const_cast(d_values_in), d_values_out); + + return DeviceRadixSort::custom_radix_sort(decomposer_check_t{}, + d_temp_storage, + temp_storage_bytes, + is_overwrite_okay, + d_keys, + d_values, + static_cast(num_items), + decomposer, + stream); + } + + //! @brief Sorts key-value pairs into ascending order. + //! (`~N` auxiliary storage required) + //! + //! @par + //! - The sorting operation is given a pair of key buffers and a corresponding + //! pair of associated value buffers. Each pair is managed by a DoubleBuffer + //! structure that indicates which of the two buffers is "current" (and thus + //! contains the input data to be sorted). + //! - The contents of both buffers within each pair may be altered by the + //! sorting operation. + //! - In-place operations are not supported. There must be no overlap between + //! any of the provided ranges: + //! - `[d_keys.Current(), d_keys.Current() + num_items)` + //! - `[d_keys.Alternate(), d_keys.Alternate() + num_items)` + //! - `[d_values.Current(), d_values.Current() + num_items)` + //! - `[d_values.Alternate(), d_values.Alternate() + num_items)` + //! - Upon completion, the sorting operation will update the "current" + //! indicator within each DoubleBuffer wrapper to reference which of the two + //! buffers now contains the sorted output sequence (a function of the + //! number of key bits specified and the targeted device architecture). + //! - An optional bit subrange `[begin_bit, end_bit)` of differentiating key + //! bits can be specified. This can reduce overall sorting overhead and + //! yield a corresponding performance improvement. + //! - @devicestorageP + //! - @devicestorage + //! + //! @par Performance + //! The following charts illustrate saturated sorting performance across + //! different CUDA architectures for uniform-random `uint32, uint32` and + //! `uint64, uint64` pairs, respectively. + //! + //! @image html lsb_radix_sort_int32_pairs.png + //! @image html lsb_radix_sort_int64_pairs.png + //! + //! @par Snippet + //! The code snippet below illustrates the sorting of a device vector of `int` + //! keys with associated vector of `int` values. + //! @par + //! @code + //! #include + //! // or equivalently + //! + //! // Declare, allocate, and initialize device-accessible pointers for + //! // sorting data + //! int num_items; // e.g., 7 + //! int *d_key_buf; // e.g., [8, 6, 7, 5, 3, 0, 9] + //! int *d_key_alt_buf; // e.g., [ ... ] + //! int *d_value_buf; // e.g., [0, 1, 2, 3, 4, 5, 6] + //! int *d_value_alt_buf; // e.g., [ ... ] + //! ... + //! + //! // Create a set of DoubleBuffers to wrap pairs of device pointers + //! cub::DoubleBuffer d_keys(d_key_buf, d_key_alt_buf); + //! cub::DoubleBuffer d_values(d_value_buf, d_value_alt_buf); + //! + //! // Determine temporary device storage requirements + //! void *d_temp_storage = NULL; + //! size_t temp_storage_bytes = 0; + //! cub::DeviceRadixSort::SortPairs( + //! d_temp_storage, temp_storage_bytes, d_keys, d_values, num_items); + //! + //! // Allocate temporary storage + //! cudaMalloc(&d_temp_storage, temp_storage_bytes); + //! + //! // Run sorting operation + //! cub::DeviceRadixSort::SortPairs( + //! d_temp_storage, temp_storage_bytes, d_keys, d_values, num_items); + //! + //! // d_keys.Current() <-- [0, 3, 5, 6, 7, 8, 9] + //! // d_values.Current() <-- [5, 4, 3, 1, 2, 0, 6] + //! + //! @endcode + //! + //! @tparam KeyT + //! **[inferred]** KeyT type + //! + //! @tparam ValueT + //! **[inferred]** ValueT type + //! + //! @tparam NumItemsT + //! **[inferred]** Type of num_items + //! + //! @param[in] d_temp_storage + //! Device-accessible allocation of temporary storage. When `nullptr`, the + //! required allocation size is written to @p temp_storage_bytes and no work is done. + //! + //! @param[in,out] temp_storage_bytes + //! Reference to size in bytes of `d_temp_storage` allocation + //! + //! @param[in,out] d_keys + //! Reference to the double-buffer of keys whose "current" device-accessible + //! buffer contains the unsorted input keys and, upon return, is updated to + //! point to the sorted output keys + //! + //! @param[in,out] d_values + //! Double-buffer of values whose "current" device-accessible buffer + //! contains the unsorted input values and, upon return, is updated to point + //! to the sorted output values + //! + //! @param[in] num_items + //! Number of items to sort + //! + //! @param[in] begin_bit + //! **[optional]** The least-significant bit index (inclusive) needed for + //! key comparison + //! + //! @param[in] end_bit + //! **[optional]** The most-significant bit index (exclusive) needed for key + //! comparison (e.g., `sizeof(unsigned int) * 8`) + //! + //! @param[in] stream + //! **[optional]** CUDA stream to launch kernels within. + //! Default is stream0. + template + CUB_RUNTIME_FUNCTION static cudaError_t + SortPairs(void *d_temp_storage, + size_t &temp_storage_bytes, + DoubleBuffer &d_keys, + DoubleBuffer &d_values, + NumItemsT num_items, + int begin_bit = 0, + int end_bit = sizeof(KeyT) * 8, + cudaStream_t stream = 0) + { + // Unsigned integer type for global offsets. + using OffsetT = typename detail::ChooseOffsetT::Type; + + constexpr bool is_overwrite_okay = true; + + return DispatchRadixSort::Dispatch( + d_temp_storage, + temp_storage_bytes, + d_keys, + d_values, + num_items, + begin_bit, + end_bit, + is_overwrite_okay, + stream); + } + + #ifndef DOXYGEN_SHOULD_SKIP_THIS // Do not document + template + CUB_DETAIL_RUNTIME_DEBUG_SYNC_IS_NOT_SUPPORTED + CUB_RUNTIME_FUNCTION static cudaError_t + SortPairs(void *d_temp_storage, + size_t &temp_storage_bytes, + DoubleBuffer &d_keys, + DoubleBuffer &d_values, + NumItemsT num_items, + int begin_bit, + int end_bit, + cudaStream_t stream, + bool debug_synchronous) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + + return SortPairs(d_temp_storage, + temp_storage_bytes, + d_keys, + d_values, + num_items, + begin_bit, + end_bit, + stream); + } + #endif + + //! @rst + //! Sorts key-value pairs into ascending order using :math:`\approx N` auxiliary storage. + //! + //! * The sorting operation is given a pair of key buffers and a corresponding + //! pair of associated value buffers. Each pair is managed by a DoubleBuffer + //! structure that indicates which of the two buffers is "current" (and thus + //! contains the input data to be sorted). + //! * The contents of both buffers within each pair may be altered by the + //! sorting operation. + //! * In-place operations are not supported. There must be no overlap between + //! any of the provided ranges: + //! + //! - ``[d_keys.Current(), d_keys.Current() + num_items)`` + //! - ``[d_keys.Alternate(), d_keys.Alternate() + num_items)`` + //! - ``[d_values.Current(), d_values.Current() + num_items)`` + //! - ``[d_values.Alternate(), d_values.Alternate() + num_items)`` + //! + //! - Upon completion, the sorting operation will update the "current" + //! indicator within each DoubleBuffer wrapper to reference which of the two + //! buffers now contains the sorted output sequence (a function of the + //! number of key bits specified and the targeted device architecture). + //! - @devicestorageP + //! - @devicestorage + //! + //! Snippet + //! ========================================================================== + //! + //! Let's consider a user-defined ``custom_t`` type below. To sort an array of + //! ``custom_t`` objects, we have to tell CUB about relevant members of the + //! ``custom_t`` type. We do this by providing a decomposer that returns a + //! tuple of references to relevant members of the key. + //! + //! .. literalinclude:: ../../test/catch2_test_device_radix_sort_custom.cu + //! :language: c++ + //! :dedent: + //! :start-after: example-begin custom-type + //! :end-before: example-end custom-type + //! + //! The following snippet shows how to sort an array of ``custom_t`` objects + //! using ``cub::DeviceRadixSort::SortPairs``: + //! + //! .. literalinclude:: ../../test/catch2_test_device_radix_sort_custom.cu + //! :language: c++ + //! :dedent: + //! :start-after: example-begin pairs-db + //! :end-before: example-end pairs-db + //! + //! @endrst + //! + //! @tparam KeyT + //! **[inferred]** KeyT type + //! + //! @tparam ValueT + //! **[inferred]** ValueT type + //! + //! @tparam NumItemsT + //! **[inferred]** Type of num_items + //! + //! @tparam DecomposerT + //! **[inferred]** Type of a callable object responsible for decomposing a + //! ``KeyT`` into a tuple of references to its constituent arithmetic types: + //! ``::cuda::std::tuple operator()(KeyT &key)``. + //! The leftmost element of the tuple is considered the most significant. + //! The call operator must not modify members of the key. + //! + //! @param[in] d_temp_storage + //! Device-accessible allocation of temporary storage. When `nullptr`, the + //! required allocation size is written to `temp_storage_bytes` and no work + //! is done. + //! + //! @param[in,out] temp_storage_bytes + //! Reference to size in bytes of `d_temp_storage` allocation + //! + //! @param[in,out] d_keys + //! Reference to the double-buffer of keys whose "current" device-accessible + //! buffer contains the unsorted input keys and, upon return, is updated to + //! point to the sorted output keys + //! + //! @param[in,out] d_values + //! Double-buffer of values whose "current" device-accessible buffer + //! contains the unsorted input values and, upon return, is updated to point + //! to the sorted output values + //! + //! @param[in] num_items + //! Number of items to sort + //! + //! @param decomposer + //! Callable object responsible for decomposing a ``KeyT`` into a tuple of + //! references to its constituent arithmetic types. The leftmost element of + //! the tuple is considered the most significant. The call operator must not + //! modify members of the key. + //! + //! @param[in] stream + //! **[optional]** CUDA stream to launch kernels within. + //! Default is stream0. + template + CUB_RUNTIME_FUNCTION static // + typename ::cuda::std::enable_if< // + !::cuda::std::is_convertible::value, // + cudaError_t>::type + SortPairs(void *d_temp_storage, + size_t &temp_storage_bytes, + DoubleBuffer &d_keys, + DoubleBuffer &d_values, + NumItemsT num_items, + DecomposerT decomposer, + cudaStream_t stream = 0) + { + // unsigned integer type for global offsets + using offset_t = typename detail::ChooseOffsetT::Type; + using decomposer_check_t = detail::radix::decomposer_check_t; + + static_assert(decomposer_check_t::value, + "DecomposerT must be a callable object returning a tuple of references to " + "arithmetic types"); + + constexpr bool is_overwrite_okay = true; + constexpr bool is_descending = false; + + return DeviceRadixSort::custom_radix_sort(decomposer_check_t{}, + d_temp_storage, + temp_storage_bytes, + is_overwrite_okay, + d_keys, + d_values, + static_cast(num_items), + decomposer, + stream); + } + + //! @rst + //! Sorts key-value pairs into ascending order using :math:`\approx N` auxiliary storage. + //! + //! * The sorting operation is given a pair of key buffers and a corresponding + //! pair of associated value buffers. Each pair is managed by a DoubleBuffer + //! structure that indicates which of the two buffers is "current" (and thus + //! contains the input data to be sorted). + //! * The contents of both buffers within each pair may be altered by the + //! sorting operation. + //! * In-place operations are not supported. There must be no overlap between + //! any of the provided ranges: + //! + //! - ``[d_keys.Current(), d_keys.Current() + num_items)`` + //! - ``[d_keys.Alternate(), d_keys.Alternate() + num_items)`` + //! - ``[d_values.Current(), d_values.Current() + num_items)`` + //! - ``[d_values.Alternate(), d_values.Alternate() + num_items)`` + //! + //! - Upon completion, the sorting operation will update the "current" + //! indicator within each DoubleBuffer wrapper to reference which of the two + //! buffers now contains the sorted output sequence (a function of the + //! number of key bits specified and the targeted device architecture). + //! - An optional bit subrange ``[begin_bit, end_bit)`` of differentiating key + //! bits can be specified. This can reduce overall sorting overhead and + //! yield a corresponding performance improvement. + //! - @devicestorageP + //! - @devicestorage + //! + //! Snippet + //! ========================================================================== + //! + //! Let's consider a user-defined ``custom_t`` type below. To sort an array of + //! ``custom_t`` objects, we have to tell CUB about relevant members of the + //! ``custom_t`` type. We do this by providing a decomposer that returns a + //! tuple of references to relevant members of the key. + //! + //! .. literalinclude:: ../../test/catch2_test_device_radix_sort_custom.cu + //! :language: c++ + //! :dedent: + //! :start-after: example-begin custom-type + //! :end-before: example-end custom-type + //! + //! The following snippet shows how to sort an array of ``custom_t`` objects + //! using ``cub::DeviceRadixSort::SortPairs``: + //! + //! .. literalinclude:: ../../test/catch2_test_device_radix_sort_custom.cu + //! :language: c++ + //! :dedent: + //! :start-after: example-begin pairs-bits-db + //! :end-before: example-end pairs-bits-db + //! + //! @endrst + //! + //! @tparam KeyT + //! **[inferred]** KeyT type + //! + //! @tparam ValueT + //! **[inferred]** ValueT type + //! + //! @tparam NumItemsT + //! **[inferred]** Type of num_items + //! + //! @tparam DecomposerT + //! **[inferred]** Type of a callable object responsible for decomposing a + //! ``KeyT`` into a tuple of references to its constituent arithmetic types: + //! ``::cuda::std::tuple operator()(KeyT &key)``. + //! The leftmost element of the tuple is considered the most significant. + //! The call operator must not modify members of the key. + //! + //! @param[in] d_temp_storage + //! Device-accessible allocation of temporary storage. When `nullptr`, the + //! required allocation size is written to `temp_storage_bytes` and no work + //! is done. + //! + //! @param[in,out] temp_storage_bytes + //! Reference to size in bytes of `d_temp_storage` allocation + //! + //! @param[in,out] d_keys + //! Reference to the double-buffer of keys whose "current" device-accessible + //! buffer contains the unsorted input keys and, upon return, is updated to + //! point to the sorted output keys + //! + //! @param[in,out] d_values + //! Double-buffer of values whose "current" device-accessible buffer + //! contains the unsorted input values and, upon return, is updated to point + //! to the sorted output values + //! + //! @param[in] num_items + //! Number of items to sort + //! + //! @param decomposer + //! Callable object responsible for decomposing a ``KeyT`` into a tuple of + //! references to its constituent arithmetic types. The leftmost element of + //! the tuple is considered the most significant. The call operator must not + //! modify members of the key. + //! + //! @param[in] begin_bit + //! **[optional]** The least-significant bit index (inclusive) needed for + //! key comparison + //! + //! @param[in] end_bit + //! **[optional]** The most-significant bit index (exclusive) needed for key + //! comparison (e.g., `(sizeof(float) + sizeof(long long int)) * 8`) + //! + //! @param[in] stream + //! **[optional]** CUDA stream to launch kernels within. + //! Default is stream0. + template + CUB_RUNTIME_FUNCTION static // + typename ::cuda::std::enable_if< // + !::cuda::std::is_convertible::value, // + cudaError_t>::type + SortPairs(void *d_temp_storage, + size_t &temp_storage_bytes, + DoubleBuffer &d_keys, + DoubleBuffer &d_values, + NumItemsT num_items, + DecomposerT decomposer, + int begin_bit, + int end_bit, + cudaStream_t stream = 0) + { + // unsigned integer type for global offsets + using offset_t = typename detail::ChooseOffsetT::Type; + using decomposer_check_t = detail::radix::decomposer_check_t; + + static_assert(decomposer_check_t::value, + "DecomposerT must be a callable object returning a tuple of references to " + "arithmetic types"); + + constexpr bool is_overwrite_okay = true; + constexpr bool is_descending = false; + + return DeviceRadixSort::custom_radix_sort(decomposer_check_t{}, + d_temp_storage, + temp_storage_bytes, + is_overwrite_okay, + d_keys, + d_values, + static_cast(num_items), + decomposer, + begin_bit, + end_bit, + stream); + } + + //! @brief Sorts key-value pairs into descending order. + //! (`~2N` auxiliary storage required). + //! + //! @par + //! - The contents of the input data are not altered by the sorting operation. + //! - Pointers to contiguous memory must be used; iterators are not currently + //! supported. + //! - In-place operations are not supported. There must be no overlap between + //! any of the provided ranges: + //! - `[d_keys_in, d_keys_in + num_items)` + //! - `[d_keys_out, d_keys_out + num_items)` + //! - `[d_values_in, d_values_in + num_items)` + //! - `[d_values_out, d_values_out + num_items)` + //! - An optional bit subrange `[begin_bit, end_bit)` of differentiating key + //! bits can be specified. This can reduce overall sorting overhead and + //! yield a corresponding performance improvement. + //! - @devicestorageNP For sorting using only `O(P)` temporary storage, see + //! the sorting interface using DoubleBuffer wrappers below. + //! - @devicestorage + //! + //! @par Performance + //! Performance is similar to DeviceRadixSort::SortPairs. + //! + //! @par Snippet + //! The code snippet below illustrates the sorting of a device vector of `int` + //! keys with associated vector of `int` values. + //! @par + //! @code + //! #include + //! // or equivalently + //! + //! // Declare, allocate, and initialize device-accessible pointers + //! // for sorting data + //! int num_items; // e.g., 7 + //! int *d_keys_in; // e.g., [8, 6, 7, 5, 3, 0, 9] + //! int *d_keys_out; // e.g., [ ... ] + //! int *d_values_in; // e.g., [0, 1, 2, 3, 4, 5, 6] + //! int *d_values_out; // e.g., [ ... ] + //! ... + //! + //! // Determine temporary device storage requirements + //! void *d_temp_storage = NULL; + //! size_t temp_storage_bytes = 0; + //! cub::DeviceRadixSort::SortPairsDescending( + //! d_temp_storage, temp_storage_bytes, + //! d_keys_in, d_keys_out, d_values_in, d_values_out, num_items); + //! + //! // Allocate temporary storage + //! cudaMalloc(&d_temp_storage, temp_storage_bytes); + //! + //! // Run sorting operation + //! cub::DeviceRadixSort::SortPairsDescending( + //! d_temp_storage, temp_storage_bytes, + //! d_keys_in, d_keys_out, d_values_in, d_values_out, num_items); + //! + //! // d_keys_out <-- [9, 8, 7, 6, 5, 3, 0] + //! // d_values_out <-- [6, 0, 2, 1, 3, 4, 5] + //! @endcode + //! + //! @tparam KeyT + //! **[inferred]** KeyT type + //! + //! @tparam ValueT + //! **[inferred]** ValueT type + //! + //! @tparam NumItemsT + //! **[inferred]** Type of num_items + //! + //! @param[in] d_temp_storage + //! Device-accessible allocation of temporary storage. When `nullptr`, the + //! required allocation size is written to `temp_storage_bytes` and no work + //! is done. + //! + //! @param[in,out] temp_storage_bytes + //! Reference to size in bytes of @p d_temp_storage allocation + //! + //! @param[in] d_keys_in + //! Pointer to the input data of key data to sort + //! + //! @param[out] d_keys_out + //! Pointer to the sorted output sequence of key data + //! + //! @param[in] d_values_in + //! Pointer to the corresponding input sequence of associated value items + //! + //! @param[out] d_values_out + //! Pointer to the correspondingly-reordered output sequence of associated + //! value items + //! + //! @param[in] num_items + //! Number of items to sort + //! + //! @param[in] begin_bit + //! **[optional]** The least-significant bit index (inclusive) needed for + //! key comparison + //! + //! @param[in] end_bit + //! **[optional]** The most-significant bit index (exclusive) needed for key + //! comparison (e.g., `sizeof(unsigned int) * 8`) + //! + //! @param[in] stream + //! **[optional]** CUDA stream to launch kernels within. + //! Default is stream0. + template + CUB_RUNTIME_FUNCTION static cudaError_t + SortPairsDescending(void *d_temp_storage, + size_t &temp_storage_bytes, + const KeyT *d_keys_in, + KeyT *d_keys_out, + const ValueT *d_values_in, + ValueT *d_values_out, + NumItemsT num_items, + int begin_bit = 0, + int end_bit = sizeof(KeyT) * 8, + cudaStream_t stream = 0) + { + // Unsigned integer type for global offsets. + using OffsetT = typename detail::ChooseOffsetT::Type; + + // We cast away const-ness, but will *not* write to these arrays. + // `DispatchRadixSort::Dispatch` will allocate temporary storage and + // create a new double-buffer internally when the `is_overwrite_ok` flag + // is not set. + constexpr bool is_overwrite_okay = false; + DoubleBuffer d_keys(const_cast(d_keys_in), d_keys_out); + DoubleBuffer d_values(const_cast(d_values_in), + d_values_out); + + return DispatchRadixSort::Dispatch( + d_temp_storage, + temp_storage_bytes, + d_keys, + d_values, + num_items, + begin_bit, + end_bit, + is_overwrite_okay, + stream); + } + + #ifndef DOXYGEN_SHOULD_SKIP_THIS // Do not document + template + CUB_DETAIL_RUNTIME_DEBUG_SYNC_IS_NOT_SUPPORTED + CUB_RUNTIME_FUNCTION static cudaError_t + SortPairsDescending(void *d_temp_storage, + size_t &temp_storage_bytes, + const KeyT *d_keys_in, + KeyT *d_keys_out, + const ValueT *d_values_in, + ValueT *d_values_out, + NumItemsT num_items, + int begin_bit, + int end_bit, + cudaStream_t stream, + bool debug_synchronous) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + + return SortPairsDescending(d_temp_storage, + temp_storage_bytes, + d_keys_in, + d_keys_out, + d_values_in, + d_values_out, + num_items, + begin_bit, + end_bit, + stream); + } + #endif + + //! @rst + //! Sorts key-value pairs into descending order using :math:`\approx 2N` auxiliary storage. + //! + //! * The contents of the input data are not altered by the sorting operation. + //! * Pointers to contiguous memory must be used; iterators are not currently + //! supported. + //! * In-place operations are not supported. There must be no overlap between + //! any of the provided ranges: + //! + //! * ``[d_keys_in, d_keys_in + num_items)`` + //! * ``[d_keys_out, d_keys_out + num_items)`` + //! * ``[d_values_in, d_values_in + num_items)`` + //! * ``[d_values_out, d_values_out + num_items)`` + //! + //! * A bit subrange ``[begin_bit, end_bit)`` is provided to specify + //! differentiating key bits. This can reduce overall sorting overhead and + //! yield a corresponding performance improvement. + //! * @devicestorageNP For sorting using only :math:`O(P)` temporary storage, see + //! the sorting interface using DoubleBuffer wrappers below. + //! * @devicestorage + //! + //! Snippet + //! ========================================================================== + //! + //! Let's consider a user-defined ``custom_t`` type below. To sort an array of + //! ``custom_t`` objects, we have to tell CUB about relevant members of the + //! ``custom_t`` type. We do this by providing a decomposer that returns a + //! tuple of references to relevant members of the key. + //! + //! .. literalinclude:: ../../test/catch2_test_device_radix_sort_custom.cu + //! :language: c++ + //! :dedent: + //! :start-after: example-begin custom-type + //! :end-before: example-end custom-type + //! + //! The following snippet shows how to sort an array of ``custom_t`` objects + //! using ``cub::DeviceRadixSort::SortPairsDescending``: + //! + //! .. literalinclude:: ../../test/catch2_test_device_radix_sort_custom.cu + //! :language: c++ + //! :dedent: + //! :start-after: example-begin pairs-descending-bits + //! :end-before: example-end pairs-descending-bits + //! + //! @endrst + //! + //! @tparam KeyT + //! **[inferred]** KeyT type + //! + //! @tparam ValueT + //! **[inferred]** ValueT type + //! + //! @tparam NumItemsT + //! **[inferred]** Type of num_items + //! + //! @tparam DecomposerT + //! **[inferred]** Type of a callable object responsible for decomposing a + //! ``KeyT`` into a tuple of references to its constituent arithmetic types: + //! ``::cuda::std::tuple operator()(KeyT &key)``. + //! The leftmost element of the tuple is considered the most significant. + //! The call operator must not modify members of the key. + //! + //! @param[in] d_temp_storage + //! Device-accessible allocation of temporary storage. When `nullptr`, the + //! required allocation size is written to `temp_storage_bytes` and no work + //! is done. + //! + //! @param[in,out] temp_storage_bytes + //! Reference to size in bytes of `d_temp_storage` allocation + //! + //! @param[in] d_keys_in + //! Pointer to the input data of key data to sort + //! + //! @param[out] d_keys_out + //! Pointer to the sorted output sequence of key data + //! + //! @param[in] d_values_in + //! Pointer to the corresponding input sequence of associated value items + //! + //! @param[out] d_values_out + //! Pointer to the correspondingly-reordered output sequence of associated + //! value items + //! + //! @param[in] num_items + //! Number of items to sort + //! + //! @param decomposer + //! Callable object responsible for decomposing a ``KeyT`` into a tuple of + //! references to its constituent arithmetic types. The leftmost element of + //! the tuple is considered the most significant. The call operator must not + //! modify members of the key. + //! + //! @param[in] begin_bit + //! **[optional]** The least-significant bit index (inclusive) needed for + //! key comparison + //! + //! @param[in] end_bit + //! **[optional]** The most-significant bit index (exclusive) needed for key + //! comparison (e.g., `(sizeof(float) + sizeof(long long int)) * 8`) + //! + //! @param[in] stream + //! **[optional]** CUDA stream to launch kernels within. + //! Default is stream0. + template + CUB_RUNTIME_FUNCTION static // + typename ::cuda::std::enable_if< // + !::cuda::std::is_convertible::value, // + cudaError_t>::type + SortPairsDescending(void *d_temp_storage, + size_t &temp_storage_bytes, + const KeyT *d_keys_in, + KeyT *d_keys_out, + const ValueT *d_values_in, + ValueT *d_values_out, + NumItemsT num_items, + DecomposerT decomposer, + int begin_bit, + int end_bit, + cudaStream_t stream = 0) + { + // unsigned integer type for global offsets + using offset_t = typename detail::ChooseOffsetT::Type; + using decomposer_check_t = detail::radix::decomposer_check_t; + + static_assert(decomposer_check_t::value, + "DecomposerT must be a callable object returning a tuple of references to " + "arithmetic types"); + + // We cast away const-ness, but will *not* write to these arrays. + // `DispatchRadixSort::Dispatch` will allocate temporary storage and + // create a new double-buffer internally when the `is_overwrite_ok` flag + // is not set. + constexpr bool is_overwrite_okay = false; + constexpr bool is_descending = true; + DoubleBuffer d_keys(const_cast(d_keys_in), d_keys_out); + DoubleBuffer d_values(const_cast(d_values_in), d_values_out); + + return DeviceRadixSort::custom_radix_sort(decomposer_check_t{}, + d_temp_storage, + temp_storage_bytes, + is_overwrite_okay, + d_keys, + d_values, + static_cast(num_items), + decomposer, + begin_bit, + end_bit, + stream); + } + + //! @rst + //! Sorts key-value pairs into descending order using :math:`\approx 2N` auxiliary storage. + //! + //! * The contents of the input data are not altered by the sorting operation. + //! * Pointers to contiguous memory must be used; iterators are not currently + //! supported. + //! * In-place operations are not supported. There must be no overlap between + //! any of the provided ranges: + //! + //! * ``[d_keys_in, d_keys_in + num_items)`` + //! * ``[d_keys_out, d_keys_out + num_items)`` + //! * ``[d_values_in, d_values_in + num_items)`` + //! * ``[d_values_out, d_values_out + num_items)`` + //! + //! * @devicestorageNP For sorting using only :math:`O(P)` temporary storage, see + //! the sorting interface using DoubleBuffer wrappers below. + //! * @devicestorage + //! + //! Snippet + //! ========================================================================== + //! + //! Let's consider a user-defined ``custom_t`` type below. To sort an array of + //! ``custom_t`` objects, we have to tell CUB about relevant members of the + //! ``custom_t`` type. We do this by providing a decomposer that returns a + //! tuple of references to relevant members of the key. + //! + //! .. literalinclude:: ../../test/catch2_test_device_radix_sort_custom.cu + //! :language: c++ + //! :dedent: + //! :start-after: example-begin custom-type + //! :end-before: example-end custom-type + //! + //! The following snippet shows how to sort an array of ``custom_t`` objects + //! using ``cub::DeviceRadixSort::SortPairsDescending``: + //! + //! .. literalinclude:: ../../test/catch2_test_device_radix_sort_custom.cu + //! :language: c++ + //! :dedent: + //! :start-after: example-begin pairs-descending + //! :end-before: example-end pairs-descending + //! + //! @endrst + //! + //! @tparam KeyT + //! **[inferred]** KeyT type + //! + //! @tparam ValueT + //! **[inferred]** ValueT type + //! + //! @tparam NumItemsT + //! **[inferred]** Type of num_items + //! + //! @tparam DecomposerT + //! **[inferred]** Type of a callable object responsible for decomposing a + //! ``KeyT`` into a tuple of references to its constituent arithmetic types: + //! ``::cuda::std::tuple operator()(KeyT &key)``. + //! The leftmost element of the tuple is considered the most significant. + //! The call operator must not modify members of the key. + //! + //! @param[in] d_temp_storage + //! Device-accessible allocation of temporary storage. When `nullptr`, the + //! required allocation size is written to `temp_storage_bytes` and no work + //! is done. + //! + //! @param[in,out] temp_storage_bytes + //! Reference to size in bytes of `d_temp_storage` allocation + //! + //! @param[in] d_keys_in + //! Pointer to the input data of key data to sort + //! + //! @param[out] d_keys_out + //! Pointer to the sorted output sequence of key data + //! + //! @param[in] d_values_in + //! Pointer to the corresponding input sequence of associated value items + //! + //! @param[out] d_values_out + //! Pointer to the correspondingly-reordered output sequence of associated + //! value items + //! + //! @param[in] num_items + //! Number of items to sort + //! + //! @param decomposer + //! Callable object responsible for decomposing a ``KeyT`` into a tuple of + //! references to its constituent arithmetic types. The leftmost element of + //! the tuple is considered the most significant. The call operator must not + //! modify members of the key. + //! + //! @param[in] stream + //! **[optional]** CUDA stream to launch kernels within. + //! Default is stream0. + template + CUB_RUNTIME_FUNCTION static // + typename ::cuda::std::enable_if< // + !::cuda::std::is_convertible::value, // + cudaError_t>::type + SortPairsDescending(void *d_temp_storage, + size_t &temp_storage_bytes, + const KeyT *d_keys_in, + KeyT *d_keys_out, + const ValueT *d_values_in, + ValueT *d_values_out, + NumItemsT num_items, + DecomposerT decomposer, + cudaStream_t stream = 0) + { + // unsigned integer type for global offsets + using offset_t = typename detail::ChooseOffsetT::Type; + using decomposer_check_t = detail::radix::decomposer_check_t; + + static_assert(decomposer_check_t::value, + "DecomposerT must be a callable object returning a tuple of references to " + "arithmetic types"); + + // We cast away const-ness, but will *not* write to these arrays. + // `DispatchRadixSort::Dispatch` will allocate temporary storage and + // create a new double-buffer internally when the `is_overwrite_ok` flag + // is not set. + constexpr bool is_overwrite_okay = false; + constexpr bool is_descending = true; + DoubleBuffer d_keys(const_cast(d_keys_in), d_keys_out); + DoubleBuffer d_values(const_cast(d_values_in), d_values_out); + + return DeviceRadixSort::custom_radix_sort(decomposer_check_t{}, + d_temp_storage, + temp_storage_bytes, + is_overwrite_okay, + d_keys, + d_values, + static_cast(num_items), + decomposer, + stream); + } + + //! @brief Sorts key-value pairs into descending order. + //! (`~N` auxiliary storage required). + //! + //! @par + //! - The sorting operation is given a pair of key buffers and a corresponding + //! pair of associated value buffers. Each pair is managed by a DoubleBuffer + //! structure that indicates which of the two buffers is "current" (and thus + //! contains the input data to be sorted). + //! - The contents of both buffers within each pair may be altered by the + //! sorting operation. + //! - In-place operations are not supported. There must be no overlap between + //! any of the provided ranges: + //! - `[d_keys.Current(), d_keys.Current() + num_items)` + //! - `[d_keys.Alternate(), d_keys.Alternate() + num_items)` + //! - `[d_values.Current(), d_values.Current() + num_items)` + //! - `[d_values.Alternate(), d_values.Alternate() + num_items)` + //! - Upon completion, the sorting operation will update the "current" + //! indicator within each DoubleBuffer wrapper to reference which of the two + //! buffers now contains the sorted output sequence (a function of the number + //! of key bits specified and the targeted device architecture). + //! - An optional bit subrange `[begin_bit, end_bit)` of differentiating key + //! bits can be specified. This can reduce overall sorting overhead and + //! yield a corresponding performance improvement. + //! - @devicestorageP + //! - @devicestorage + //! + //! @par Performance + //! Performance is similar to DeviceRadixSort::SortPairs. + //! + //! @par Snippet + //! The code snippet below illustrates the sorting of a device vector of `int` + //! keys with associated vector of `int` values. + //! @par + //! @code + //! #include + //! // or equivalently + //! + //! // Declare, allocate, and initialize device-accessible pointers + //! // for sorting data + //! int num_items; // e.g., 7 + //! int *d_key_buf; // e.g., [8, 6, 7, 5, 3, 0, 9] + //! int *d_key_alt_buf; // e.g., [ ... ] + //! int *d_value_buf; // e.g., [0, 1, 2, 3, 4, 5, 6] + //! int *d_value_alt_buf; // e.g., [ ... ] + //! ... + //! + //! // Create a set of DoubleBuffers to wrap pairs of device pointers + //! cub::DoubleBuffer d_keys(d_key_buf, d_key_alt_buf); + //! cub::DoubleBuffer d_values(d_value_buf, d_value_alt_buf); + //! + //! // Determine temporary device storage requirements + //! void *d_temp_storage = NULL; + //! size_t temp_storage_bytes = 0; + //! cub::DeviceRadixSort::SortPairsDescending( + //! d_temp_storage, temp_storage_bytes, d_keys, d_values, num_items); + //! + //! // Allocate temporary storage + //! cudaMalloc(&d_temp_storage, temp_storage_bytes); + //! + //! // Run sorting operation + //! cub::DeviceRadixSort::SortPairsDescending( + //! d_temp_storage, temp_storage_bytes, d_keys, d_values, num_items); + //! + //! // d_keys.Current() <-- [9, 8, 7, 6, 5, 3, 0] + //! // d_values.Current() <-- [6, 0, 2, 1, 3, 4, 5] + //! @endcode + //! + //! @tparam KeyT + //! **[inferred]** KeyT type + //! + //! @tparam ValueT + //! **[inferred]** ValueT type + //! + //! @tparam NumItemsT + //! **[inferred]** Type of num_items + //! + //! @param[in] d_temp_storage + //! Device-accessible allocation of temporary storage. When `nullptr`, the + //! required allocation size is written to `temp_storage_bytes` and no work + //! is done. + //! + //! @param[in,out] temp_storage_bytes + //! Reference to size in bytes of `d_temp_storage` allocation + //! + //! @param[in,out] d_keys + //! Reference to the double-buffer of keys whose "current" device-accessible + //! buffer contains the unsorted input keys and, upon return, is updated to + //! point to the sorted output keys + //! + //! @param[in,out] d_values + //! Double-buffer of values whose "current" device-accessible buffer + //! contains the unsorted input values and, upon return, is updated to point + //! to the sorted output values + //! + //! @param[in] num_items + //! Number of items to sort + //! + //! @param[in] begin_bit + //! **[optional]** The least-significant bit index (inclusive) needed for + //! key comparison + //! + //! @param[in] end_bit + //! **[optional]** The most-significant bit index (exclusive) needed for key + //! comparison (e.g., `sizeof(unsigned int) * 8`) + //! + //! @param[in] stream + //! **[optional]** CUDA stream to launch kernels within. + //! Default is stream0. + template + CUB_RUNTIME_FUNCTION static cudaError_t + SortPairsDescending(void *d_temp_storage, + size_t &temp_storage_bytes, + DoubleBuffer &d_keys, + DoubleBuffer &d_values, + NumItemsT num_items, + int begin_bit = 0, + int end_bit = sizeof(KeyT) * 8, + cudaStream_t stream = 0) + { + // Unsigned integer type for global offsets. + using OffsetT = typename detail::ChooseOffsetT::Type; + + constexpr bool is_overwrite_okay = true; + + return DispatchRadixSort::Dispatch( + d_temp_storage, + temp_storage_bytes, + d_keys, + d_values, + num_items, + begin_bit, + end_bit, + is_overwrite_okay, + stream); + } + + #ifndef DOXYGEN_SHOULD_SKIP_THIS // Do not document + template + CUB_DETAIL_RUNTIME_DEBUG_SYNC_IS_NOT_SUPPORTED + CUB_RUNTIME_FUNCTION static cudaError_t + SortPairsDescending(void *d_temp_storage, + size_t &temp_storage_bytes, + DoubleBuffer &d_keys, + DoubleBuffer &d_values, + NumItemsT num_items, + int begin_bit, + int end_bit, + cudaStream_t stream, + bool debug_synchronous) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + + return SortPairsDescending(d_temp_storage, + temp_storage_bytes, + d_keys, + d_values, + num_items, + begin_bit, + end_bit, + stream); + } + #endif + + //! @rst + //! Sorts key-value pairs into descending order using :math:`\approx N` auxiliary storage. + //! + //! * The sorting operation is given a pair of key buffers and a corresponding + //! pair of associated value buffers. Each pair is managed by a DoubleBuffer + //! structure that indicates which of the two buffers is "current" (and thus + //! contains the input data to be sorted). + //! * The contents of both buffers within each pair may be altered by the + //! sorting operation. + //! * In-place operations are not supported. There must be no overlap between + //! any of the provided ranges: + //! + //! - ``[d_keys.Current(), d_keys.Current() + num_items)`` + //! - ``[d_keys.Alternate(), d_keys.Alternate() + num_items)`` + //! - ``[d_values.Current(), d_values.Current() + num_items)`` + //! - ``[d_values.Alternate(), d_values.Alternate() + num_items)`` + //! + //! - Upon completion, the sorting operation will update the "current" + //! indicator within each DoubleBuffer wrapper to reference which of the two + //! buffers now contains the sorted output sequence (a function of the + //! number of key bits specified and the targeted device architecture). + //! - @devicestorageP + //! - @devicestorage + //! + //! Snippet + //! ========================================================================== + //! + //! Let's consider a user-defined ``custom_t`` type below. To sort an array of + //! ``custom_t`` objects, we have to tell CUB about relevant members of the + //! ``custom_t`` type. We do this by providing a decomposer that returns a + //! tuple of references to relevant members of the key. + //! + //! .. literalinclude:: ../../test/catch2_test_device_radix_sort_custom.cu + //! :language: c++ + //! :dedent: + //! :start-after: example-begin custom-type + //! :end-before: example-end custom-type + //! + //! The following snippet shows how to sort an array of ``custom_t`` objects + //! using ``cub::DeviceRadixSort::SortPairsDescending``: + //! + //! .. literalinclude:: ../../test/catch2_test_device_radix_sort_custom.cu + //! :language: c++ + //! :dedent: + //! :start-after: example-begin pairs-descending-db + //! :end-before: example-end pairs-descending-db + //! + //! @endrst + //! + //! @tparam KeyT + //! **[inferred]** KeyT type + //! + //! @tparam ValueT + //! **[inferred]** ValueT type + //! + //! @tparam NumItemsT + //! **[inferred]** Type of num_items + //! + //! @tparam DecomposerT + //! **[inferred]** Type of a callable object responsible for decomposing a + //! ``KeyT`` into a tuple of references to its constituent arithmetic types: + //! ``::cuda::std::tuple operator()(KeyT &key)``. + //! The leftmost element of the tuple is considered the most significant. + //! The call operator must not modify members of the key. + //! + //! @param[in] d_temp_storage + //! Device-accessible allocation of temporary storage. When `nullptr`, the + //! required allocation size is written to `temp_storage_bytes` and no work + //! is done. + //! + //! @param[in,out] temp_storage_bytes + //! Reference to size in bytes of `d_temp_storage` allocation + //! + //! @param[in,out] d_keys + //! Reference to the double-buffer of keys whose "current" device-accessible + //! buffer contains the unsorted input keys and, upon return, is updated to + //! point to the sorted output keys + //! + //! @param[in,out] d_values + //! Double-buffer of values whose "current" device-accessible buffer + //! contains the unsorted input values and, upon return, is updated to point + //! to the sorted output values + //! + //! @param[in] num_items + //! Number of items to sort + //! + //! @param decomposer + //! Callable object responsible for decomposing a ``KeyT`` into a tuple of + //! references to its constituent arithmetic types. The leftmost element of + //! the tuple is considered the most significant. The call operator must not + //! modify members of the key. + //! + //! @param[in] stream + //! **[optional]** CUDA stream to launch kernels within. + //! Default is stream0. + template + CUB_RUNTIME_FUNCTION static // + typename ::cuda::std::enable_if< // + !::cuda::std::is_convertible::value, // + cudaError_t>::type + SortPairsDescending(void *d_temp_storage, + size_t &temp_storage_bytes, + DoubleBuffer &d_keys, + DoubleBuffer &d_values, + NumItemsT num_items, + DecomposerT decomposer, + cudaStream_t stream = 0) + { + // unsigned integer type for global offsets + using offset_t = typename detail::ChooseOffsetT::Type; + using decomposer_check_t = detail::radix::decomposer_check_t; + + static_assert(decomposer_check_t::value, + "DecomposerT must be a callable object returning a tuple of references to " + "arithmetic types"); + + constexpr bool is_overwrite_okay = true; + constexpr bool is_descending = true; + + return DeviceRadixSort::custom_radix_sort(decomposer_check_t{}, + d_temp_storage, + temp_storage_bytes, + is_overwrite_okay, + d_keys, + d_values, + static_cast(num_items), + decomposer, + stream); + } + + //! @rst + //! Sorts key-value pairs into descending order using :math:`\approx N` auxiliary storage. + //! + //! * The sorting operation is given a pair of key buffers and a corresponding + //! pair of associated value buffers. Each pair is managed by a DoubleBuffer + //! structure that indicates which of the two buffers is "current" (and thus + //! contains the input data to be sorted). + //! * The contents of both buffers within each pair may be altered by the + //! sorting operation. + //! * In-place operations are not supported. There must be no overlap between + //! any of the provided ranges: + //! + //! - ``[d_keys.Current(), d_keys.Current() + num_items)`` + //! - ``[d_keys.Alternate(), d_keys.Alternate() + num_items)`` + //! - ``[d_values.Current(), d_values.Current() + num_items)`` + //! - ``[d_values.Alternate(), d_values.Alternate() + num_items)`` + //! + //! - Upon completion, the sorting operation will update the "current" + //! indicator within each DoubleBuffer wrapper to reference which of the two + //! buffers now contains the sorted output sequence (a function of the + //! number of key bits specified and the targeted device architecture). + //! - An optional bit subrange ``[begin_bit, end_bit)`` of differentiating key + //! bits can be specified. This can reduce overall sorting overhead and + //! yield a corresponding performance improvement. + //! - @devicestorageP + //! - @devicestorage + //! + //! Snippet + //! ========================================================================== + //! + //! Let's consider a user-defined ``custom_t`` type below. To sort an array of + //! ``custom_t`` objects, we have to tell CUB about relevant members of the + //! ``custom_t`` type. We do this by providing a decomposer that returns a + //! tuple of references to relevant members of the key. + //! + //! .. literalinclude:: ../../test/catch2_test_device_radix_sort_custom.cu + //! :language: c++ + //! :dedent: + //! :start-after: example-begin custom-type + //! :end-before: example-end custom-type + //! + //! The following snippet shows how to sort an array of ``custom_t`` objects + //! using ``cub::DeviceRadixSort::SortPairsDescending``: + //! + //! .. literalinclude:: ../../test/catch2_test_device_radix_sort_custom.cu + //! :language: c++ + //! :dedent: + //! :start-after: example-begin pairs-descending-bits-db + //! :end-before: example-end pairs-descending-bits-db + //! + //! @endrst + //! + //! @tparam KeyT + //! **[inferred]** KeyT type + //! + //! @tparam ValueT + //! **[inferred]** ValueT type + //! + //! @tparam NumItemsT + //! **[inferred]** Type of num_items + //! + //! @tparam DecomposerT + //! **[inferred]** Type of a callable object responsible for decomposing a + //! ``KeyT`` into a tuple of references to its constituent arithmetic types: + //! ``::cuda::std::tuple operator()(KeyT &key)``. + //! The leftmost element of the tuple is considered the most significant. + //! The call operator must not modify members of the key. + //! + //! @param[in] d_temp_storage + //! Device-accessible allocation of temporary storage. When `nullptr`, the + //! required allocation size is written to `temp_storage_bytes` and no work + //! is done. + //! + //! @param[in,out] temp_storage_bytes + //! Reference to size in bytes of `d_temp_storage` allocation + //! + //! @param[in,out] d_keys + //! Reference to the double-buffer of keys whose "current" device-accessible + //! buffer contains the unsorted input keys and, upon return, is updated to + //! point to the sorted output keys + //! + //! @param[in,out] d_values + //! Double-buffer of values whose "current" device-accessible buffer + //! contains the unsorted input values and, upon return, is updated to point + //! to the sorted output values + //! + //! @param[in] num_items + //! Number of items to sort + //! + //! @param decomposer + //! Callable object responsible for decomposing a ``KeyT`` into a tuple of + //! references to its constituent arithmetic types. The leftmost element of + //! the tuple is considered the most significant. The call operator must not + //! modify members of the key. + //! + //! @param[in] begin_bit + //! **[optional]** The least-significant bit index (inclusive) needed for + //! key comparison + //! + //! @param[in] end_bit + //! **[optional]** The most-significant bit index (exclusive) needed for key + //! comparison (e.g., `(sizeof(float) + sizeof(long long int)) * 8`) + //! + //! @param[in] stream + //! **[optional]** CUDA stream to launch kernels within. + //! Default is stream0. + template + CUB_RUNTIME_FUNCTION static // + typename ::cuda::std::enable_if< // + !::cuda::std::is_convertible::value, // + cudaError_t>::type + SortPairsDescending(void *d_temp_storage, + size_t &temp_storage_bytes, + DoubleBuffer &d_keys, + DoubleBuffer &d_values, + NumItemsT num_items, + DecomposerT decomposer, + int begin_bit, + int end_bit, + cudaStream_t stream = 0) + { + // unsigned integer type for global offsets + using offset_t = typename detail::ChooseOffsetT::Type; + using decomposer_check_t = detail::radix::decomposer_check_t; + + static_assert(decomposer_check_t::value, + "DecomposerT must be a callable object returning a tuple of references to " + "arithmetic types"); + + constexpr bool is_overwrite_okay = true; + constexpr bool is_descending = true; + + return DeviceRadixSort::custom_radix_sort(decomposer_check_t{}, + d_temp_storage, + temp_storage_bytes, + is_overwrite_okay, + d_keys, + d_values, + static_cast(num_items), + decomposer, + begin_bit, + end_bit, + stream); + } + + //@} end member group + /******************************************************************//** + * @name Keys-only + *********************************************************************/ + //@{ + + + //! @brief Sorts keys into ascending order. + //! (`~2N` auxiliary storage required) + //! + //! @par + //! - The contents of the input data are not altered by the sorting operation. + //! - Pointers to contiguous memory must be used; iterators are not currently + //! supported. + //! - In-place operations are not supported. There must be no overlap between + //! any of the provided ranges: + //! - `[d_keys_in, d_keys_in + num_items)` + //! - `[d_keys_out, d_keys_out + num_items)` + //! - An optional bit subrange `[begin_bit, end_bit)` of differentiating key + //! bits can be specified. This can reduce overall sorting overhead and + //! yield a corresponding performance improvement. + //! - @devicestorageNP For sorting using only `O(P)` temporary storage, see + //! the sorting interface using DoubleBuffer wrappers below. + //! - @devicestorage + //! + //! @par Performance + //! The following charts illustrate saturated sorting performance across + //! different CUDA architectures for uniform-random `uint32` and `uint64` + //! keys, respectively. + //! + //! @image html lsb_radix_sort_int32_keys.png + //! @image html lsb_radix_sort_int64_keys.png + //! + //! @par Snippet + //! The code snippet below illustrates the sorting of a device vector of + //! `int` keys. + //! @par + //! @code + //! #include + //! // or equivalently + //! + //! // Declare, allocate, and initialize device-accessible pointers + //! // for sorting data + //! int num_items; // e.g., 7 + //! int *d_keys_in; // e.g., [8, 6, 7, 5, 3, 0, 9] + //! int *d_keys_out; // e.g., [ ... ] + //! ... + //! + //! // Determine temporary device storage requirements + //! void *d_temp_storage = NULL; + //! size_t temp_storage_bytes = 0; + //! cub::DeviceRadixSort::SortKeys( + //! d_temp_storage, temp_storage_bytes, d_keys_in, d_keys_out, num_items); + //! + //! // Allocate temporary storage + //! cudaMalloc(&d_temp_storage, temp_storage_bytes); + //! + //! // Run sorting operation + //! cub::DeviceRadixSort::SortKeys( + //! d_temp_storage, temp_storage_bytes, d_keys_in, d_keys_out, num_items); + //! + //! // d_keys_out <-- [0, 3, 5, 6, 7, 8, 9] + //! @endcode + //! + //! @tparam KeyT + //! **[inferred]** KeyT type + //! + //! @tparam NumItemsT + //! **[inferred]** Type of num_items + //! + //! @tparam NumItemsT + //! **[inferred]** Type of num_items + //! + //! @param[in] d_temp_storage + //! Device-accessible allocation of temporary storage. When `nullptr`, the + //! required allocation size is written to `temp_storage_bytes` and no work + //! is done. + //! + //! @param[in,out] temp_storage_bytes + //! Reference to size in bytes of `d_temp_storage` allocation + //! + //! @param[in] d_keys_in + //! Pointer to the input data of key data to sort + //! + //! @param[out] d_keys_out + //! Pointer to the sorted output sequence of key data + //! + //! @param[in] num_items + //! Number of items to sort + //! + //! @param[in] begin_bit + //! **[optional]** The least-significant bit index (inclusive) needed for + //! key comparison + //! + //! @param[in] end_bit + //! **[optional]** The most-significant bit index (exclusive) needed for key + //! comparison (e.g., `sizeof(unsigned int) * 8`) + //! + //! @param[in] stream + //! **[optional]** CUDA stream to launch kernels within. + //! Default is stream0. + template + CUB_RUNTIME_FUNCTION static cudaError_t + SortKeys(void *d_temp_storage, + size_t &temp_storage_bytes, + const KeyT *d_keys_in, + KeyT *d_keys_out, + NumItemsT num_items, + int begin_bit = 0, + int end_bit = sizeof(KeyT) * 8, + cudaStream_t stream = 0) + { + // Unsigned integer type for global offsets. + using OffsetT = typename detail::ChooseOffsetT::Type; + + // We cast away const-ness, but will *not* write to these arrays. + // `DispatchRadixSort::Dispatch` will allocate temporary storage and + // create a new double-buffer internally when the `is_overwrite_ok` flag + // is not set. + constexpr bool is_overwrite_okay = false; + DoubleBuffer d_keys(const_cast(d_keys_in), d_keys_out); + // Null value type + DoubleBuffer d_values; + + return DispatchRadixSort::Dispatch( + d_temp_storage, + temp_storage_bytes, + d_keys, + d_values, + static_cast(num_items), + begin_bit, + end_bit, + is_overwrite_okay, + stream); + } + + //! @rst + //! Sorts keys into ascending order using :math:`\approx 2N` auxiliary storage. + //! + //! * The contents of the input data are not altered by the sorting operation. + //! * Pointers to contiguous memory must be used; iterators are not currently + //! supported. + //! * In-place operations are not supported. There must be no overlap between + //! any of the provided ranges: + //! + //! * ``[d_keys_in, d_keys_in + num_items)`` + //! * ``[d_keys_out, d_keys_out + num_items)`` + //! + //! * A bit subrange ``[begin_bit, end_bit)`` is provided to specify + //! differentiating key bits. This can reduce overall sorting overhead and + //! yield a corresponding performance improvement. + //! * @devicestorageNP For sorting using only :math:`O(P)` temporary storage, see + //! the sorting interface using DoubleBuffer wrappers below. + //! * @devicestorage + //! + //! Snippet + //! ========================================================================== + //! + //! Let's consider a user-defined ``custom_t`` type below. To sort an array of + //! ``custom_t`` objects, we have to tell CUB about relevant members of the + //! ``custom_t`` type. We do this by providing a decomposer that returns a + //! tuple of references to relevant members of the key. + //! + //! .. literalinclude:: ../../test/catch2_test_device_radix_sort_custom.cu + //! :language: c++ + //! :dedent: + //! :start-after: example-begin custom-type + //! :end-before: example-end custom-type + //! + //! The following snippet shows how to sort an array of ``custom_t`` objects + //! using ``cub::DeviceRadixSort::SortKeys``: + //! + //! .. literalinclude:: ../../test/catch2_test_device_radix_sort_custom.cu + //! :language: c++ + //! :dedent: + //! :start-after: example-begin keys-bits + //! :end-before: example-end keys-bits + //! + //! @endrst + //! + //! @tparam KeyT + //! **[inferred]** KeyT type + //! + //! @tparam NumItemsT + //! **[inferred]** Type of num_items + //! + //! @tparam DecomposerT + //! **[inferred]** Type of a callable object responsible for decomposing a + //! ``KeyT`` into a tuple of references to its constituent arithmetic types: + //! ``::cuda::std::tuple operator()(KeyT &key)``. + //! The leftmost element of the tuple is considered the most significant. + //! The call operator must not modify members of the key. + //! + //! @param[in] d_temp_storage + //! Device-accessible allocation of temporary storage. When `nullptr`, the + //! required allocation size is written to `temp_storage_bytes` and no work + //! is done. + //! + //! @param[in,out] temp_storage_bytes + //! Reference to size in bytes of `d_temp_storage` allocation + //! + //! @param[in] d_keys_in + //! Pointer to the input data of key data to sort + //! + //! @param[out] d_keys_out + //! Pointer to the sorted output sequence of key data + //! + //! @param[in] num_items + //! Number of items to sort + //! + //! @param decomposer + //! Callable object responsible for decomposing a ``KeyT`` into a tuple of + //! references to its constituent arithmetic types. The leftmost element of + //! the tuple is considered the most significant. The call operator must not + //! modify members of the key. + //! + //! @param[in] begin_bit + //! **[optional]** The least-significant bit index (inclusive) needed for + //! key comparison + //! + //! @param[in] end_bit + //! **[optional]** The most-significant bit index (exclusive) needed for key + //! comparison (e.g., `(sizeof(float) + sizeof(long long int)) * 8`) + //! + //! @param[in] stream + //! **[optional]** CUDA stream to launch kernels within. + //! Default is stream0. + template + CUB_RUNTIME_FUNCTION static // + typename ::cuda::std::enable_if< // + !::cuda::std::is_convertible::value, // + cudaError_t>::type + SortKeys(void *d_temp_storage, + size_t &temp_storage_bytes, + const KeyT *d_keys_in, + KeyT *d_keys_out, + NumItemsT num_items, + DecomposerT decomposer, + int begin_bit, + int end_bit, + cudaStream_t stream = 0) + { + // unsigned integer type for global offsets + using offset_t = typename detail::ChooseOffsetT::Type; + using decomposer_check_t = detail::radix::decomposer_check_t; + + static_assert(decomposer_check_t::value, + "DecomposerT must be a callable object returning a tuple of references to " + "arithmetic types"); + + // We cast away const-ness, but will *not* write to these arrays. + // `DispatchRadixSort::Dispatch` will allocate temporary storage and + // create a new double-buffer internally when the `is_overwrite_ok` flag + // is not set. + constexpr bool is_overwrite_okay = false; + constexpr bool is_descending = false; + DoubleBuffer d_keys(const_cast(d_keys_in), d_keys_out); + DoubleBuffer d_values; + + return DeviceRadixSort::custom_radix_sort(decomposer_check_t{}, + d_temp_storage, + temp_storage_bytes, + is_overwrite_okay, + d_keys, + d_values, + static_cast(num_items), + decomposer, + begin_bit, + end_bit, + stream); + } + + //! @rst + //! Sorts keys into ascending order using :math:`\approx 2N` auxiliary storage. + //! + //! * The contents of the input data are not altered by the sorting operation. + //! * Pointers to contiguous memory must be used; iterators are not currently + //! supported. + //! * In-place operations are not supported. There must be no overlap between + //! any of the provided ranges: + //! + //! * ``[d_keys_in, d_keys_in + num_items)`` + //! * ``[d_keys_out, d_keys_out + num_items)`` + //! + //! * An optional bit subrange ``[begin_bit, end_bit)`` of differentiating key + //! bits can be specified. This can reduce overall sorting overhead and + //! yield a corresponding performance improvement. + //! * @devicestorageNP For sorting using only :math:`O(P)` temporary storage, see + //! the sorting interface using DoubleBuffer wrappers below. + //! * @devicestorage + //! + //! Snippet + //! ========================================================================== + //! + //! Let's consider a user-defined ``custom_t`` type below. To sort an array of + //! ``custom_t`` objects, we have to tell CUB about relevant members of the + //! ``custom_t`` type. We do this by providing a decomposer that returns a + //! tuple of references to relevant members of the key. + //! + //! .. literalinclude:: ../../test/catch2_test_device_radix_sort_custom.cu + //! :language: c++ + //! :dedent: + //! :start-after: example-begin custom-type + //! :end-before: example-end custom-type + //! + //! The following snippet shows how to sort an array of ``custom_t`` objects + //! using ``cub::DeviceRadixSort::SortKeys``: + //! + //! .. literalinclude:: ../../test/catch2_test_device_radix_sort_custom.cu + //! :language: c++ + //! :dedent: + //! :start-after: example-begin keys + //! :end-before: example-end keys + //! + //! @endrst + //! + //! @tparam KeyT + //! **[inferred]** KeyT type + //! + //! @tparam NumItemsT + //! **[inferred]** Type of num_items + //! + //! @tparam DecomposerT + //! **[inferred]** Type of a callable object responsible for decomposing a + //! ``KeyT`` into a tuple of references to its constituent arithmetic types: + //! ``::cuda::std::tuple operator()(KeyT &key)``. + //! The leftmost element of the tuple is considered the most significant. + //! The call operator must not modify members of the key. + //! + //! @param[in] d_temp_storage + //! Device-accessible allocation of temporary storage. When `nullptr`, the + //! required allocation size is written to `temp_storage_bytes` and no work + //! is done. + //! + //! @param[in,out] temp_storage_bytes + //! Reference to size in bytes of `d_temp_storage` allocation + //! + //! @param[in] d_keys_in + //! Pointer to the input data of key data to sort + //! + //! @param[out] d_keys_out + //! Pointer to the sorted output sequence of key data + //! + //! @param[in] num_items + //! Number of items to sort + //! + //! @param decomposer + //! Callable object responsible for decomposing a ``KeyT`` into a tuple of + //! references to its constituent arithmetic types. The leftmost element of + //! the tuple is considered the most significant. The call operator must not + //! modify members of the key. + //! + //! @param[in] stream + //! **[optional]** CUDA stream to launch kernels within. + //! Default is stream0. + template + CUB_RUNTIME_FUNCTION static // + typename ::cuda::std::enable_if< // + !::cuda::std::is_convertible::value, // + cudaError_t>::type + SortKeys(void *d_temp_storage, + size_t &temp_storage_bytes, + const KeyT *d_keys_in, + KeyT *d_keys_out, + NumItemsT num_items, + DecomposerT decomposer, + cudaStream_t stream = 0) + { + // unsigned integer type for global offsets + using offset_t = typename detail::ChooseOffsetT::Type; + using decomposer_check_t = detail::radix::decomposer_check_t; + + static_assert(decomposer_check_t::value, + "DecomposerT must be a callable object returning a tuple of references to " + "arithmetic types"); + + // We cast away const-ness, but will *not* write to these arrays. + // `DispatchRadixSort::Dispatch` will allocate temporary storage and + // create a new double-buffer internally when the `is_overwrite_ok` flag + // is not set. + constexpr bool is_overwrite_okay = false; + constexpr bool is_descending = false; + DoubleBuffer d_keys(const_cast(d_keys_in), d_keys_out); + DoubleBuffer d_values; + + return DeviceRadixSort::custom_radix_sort(decomposer_check_t{}, + d_temp_storage, + temp_storage_bytes, + is_overwrite_okay, + d_keys, + d_values, + static_cast(num_items), + decomposer, + stream); + } + +#ifndef DOXYGEN_SHOULD_SKIP_THIS // Do not document + template + CUB_DETAIL_RUNTIME_DEBUG_SYNC_IS_NOT_SUPPORTED + CUB_RUNTIME_FUNCTION static cudaError_t + SortKeys(void *d_temp_storage, + size_t &temp_storage_bytes, + const KeyT *d_keys_in, + KeyT *d_keys_out, + NumItemsT num_items, + int begin_bit, + int end_bit, + cudaStream_t stream, + bool debug_synchronous) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + + return SortKeys(d_temp_storage, + temp_storage_bytes, + d_keys_in, + d_keys_out, + num_items, + begin_bit, + end_bit, + stream); + } + #endif + + + //! @brief Sorts keys into ascending order. (`~N` auxiliary storage required). + //! + //! @par + //! - The sorting operation is given a pair of key buffers managed by a + //! DoubleBuffer structure that indicates which of the two buffers is + //! "current" (and thus contains the input data to be sorted). + //! - The contents of both buffers may be altered by the sorting operation. + //! - In-place operations are not supported. There must be no overlap between + //! any of the provided ranges: + //! - `[d_keys.Current(), d_keys.Current() + num_items)` + //! - `[d_keys.Alternate(), d_keys.Alternate() + num_items)` + //! - Upon completion, the sorting operation will update the "current" + //! indicator within the DoubleBuffer wrapper to reference which of the two + //! buffers now contains the sorted output sequence (a function of the + //! number of key bits specified and the targeted device architecture). + //! - An optional bit subrange `[begin_bit, end_bit)` of differentiating key + //! bits can be specified. This can reduce overall sorting overhead and + //! yield a corresponding performance improvement. + //! - @devicestorageP + //! - @devicestorage + //! + //! @par Performance + //! The following charts illustrate saturated sorting performance across + //! different CUDA architectures for uniform-random `uint32` and `uint64` + //! keys, respectively. + //! + //! @image html lsb_radix_sort_int32_keys.png + //! @image html lsb_radix_sort_int64_keys.png + //! + //! @par Snippet + //! The code snippet below illustrates the sorting of a device vector of + //! `int` keys. + //! @par + //! @code + //! #include + //! // or equivalently + //! + //! // Declare, allocate, and initialize device-accessible pointers + //! // for sorting data + //! int num_items; // e.g., 7 + //! int *d_key_buf; // e.g., [8, 6, 7, 5, 3, 0, 9] + //! int *d_key_alt_buf; // e.g., [ ... ] + //! ... + //! + //! // Create a DoubleBuffer to wrap the pair of device pointers + //! cub::DoubleBuffer d_keys(d_key_buf, d_key_alt_buf); + //! + //! // Determine temporary device storage requirements + //! void *d_temp_storage = NULL; + //! size_t temp_storage_bytes = 0; + //! cub::DeviceRadixSort::SortKeys( + //! d_temp_storage, temp_storage_bytes, d_keys, num_items); + //! + //! // Allocate temporary storage + //! cudaMalloc(&d_temp_storage, temp_storage_bytes); + //! + //! // Run sorting operation + //! cub::DeviceRadixSort::SortKeys( + //! d_temp_storage, temp_storage_bytes, d_keys, num_items); + //! + //! // d_keys.Current() <-- [0, 3, 5, 6, 7, 8, 9] + //! @endcode + //! + //! @tparam KeyT + //! **[inferred]** KeyT type + //! + //! @tparam NumItemsT + //! **[inferred]** Type of num_items + //! + //! @param[in] d_temp_storage + //! Device-accessible allocation of temporary storage. When `nullptr`, the + //! required allocation size is written to `temp_storage_bytes` and no work + //! is done. + //! + //! @param[in,out] temp_storage_bytes + //! Reference to size in bytes of `d_temp_storage` allocation + //! + //! @param[in,out] d_keys + //! Reference to the double-buffer of keys whose "current" device-accessible + //! buffer contains the unsorted input keys and, upon return, is updated to + //! point to the sorted output keys + //! + //! @param[in] num_items + //! Number of items to sort + //! + //! @param[in] begin_bit + //! **[optional]** The least-significant bit index (inclusive) needed for + //! key comparison + //! + //! @param[in] end_bit + //! **[optional]** The most-significant bit index (exclusive) needed for key + //! comparison (e.g., `sizeof(unsigned int) * 8`) + //! + //! @param[in] stream + //! **[optional]** CUDA stream to launch kernels within. + //! Default is stream0. + template + CUB_RUNTIME_FUNCTION static cudaError_t + SortKeys(void *d_temp_storage, + size_t &temp_storage_bytes, + DoubleBuffer &d_keys, + NumItemsT num_items, + int begin_bit = 0, + int end_bit = sizeof(KeyT) * 8, + cudaStream_t stream = 0) + { + // Unsigned integer type for global offsets. + using OffsetT = typename detail::ChooseOffsetT::Type; + + constexpr bool is_overwrite_okay = true; + + // Null value type + DoubleBuffer d_values; + + return DispatchRadixSort::Dispatch( + d_temp_storage, + temp_storage_bytes, + d_keys, + d_values, + num_items, + begin_bit, + end_bit, + is_overwrite_okay, + stream); + } + + #ifndef DOXYGEN_SHOULD_SKIP_THIS // Do not document + template + CUB_DETAIL_RUNTIME_DEBUG_SYNC_IS_NOT_SUPPORTED + CUB_RUNTIME_FUNCTION static cudaError_t + SortKeys(void *d_temp_storage, + size_t &temp_storage_bytes, + DoubleBuffer &d_keys, + NumItemsT num_items, + int begin_bit, + int end_bit, + cudaStream_t stream, + bool debug_synchronous) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + + return SortKeys(d_temp_storage, + temp_storage_bytes, + d_keys, + num_items, + begin_bit, + end_bit, + stream); + } + #endif + + //! @rst + //! Sorts keys into ascending order using :math:`\approx N` auxiliary storage. + //! + //! * The sorting operation is given a pair of key buffers managed by a + //! DoubleBuffer structure that indicates which of the two buffers is + //! "current" (and thus contains the input data to be sorted). + //! * The contents of both buffers may be altered by the sorting operation. + //! * In-place operations are not supported. There must be no overlap between + //! any of the provided ranges: + //! + //! * ``[d_keys.Current(), d_keys.Current() + num_items)`` + //! * ``[d_keys.Alternate(), d_keys.Alternate() + num_items)` + //! + //! * Upon completion, the sorting operation will update the "current" + //! indicator within the DoubleBuffer wrapper to reference which of the two + //! buffers now contains the sorted output sequence (a function of the + //! number of key bits specified and the targeted device architecture). + //! * @devicestorageP + //! * @devicestorage + //! + //! Snippet + //! ========================================================================== + //! + //! Let's consider a user-defined ``custom_t`` type below. To sort an array of + //! ``custom_t`` objects, we have to tell CUB about relevant members of the + //! ``custom_t`` type. We do this by providing a decomposer that returns a + //! tuple of references to relevant members of the key. + //! + //! .. literalinclude:: ../../test/catch2_test_device_radix_sort_custom.cu + //! :language: c++ + //! :dedent: + //! :start-after: example-begin custom-type + //! :end-before: example-end custom-type + //! + //! The following snippet shows how to sort an array of ``custom_t`` objects + //! using ``cub::DeviceRadixSort::SortKeys``: + //! + //! .. literalinclude:: ../../test/catch2_test_device_radix_sort_custom.cu + //! :language: c++ + //! :dedent: + //! :start-after: example-begin keys-db + //! :end-before: example-end keys-db + //! + //! @endrst + //! + //! @tparam KeyT + //! **[inferred]** KeyT type + //! + //! @tparam NumItemsT + //! **[inferred]** Type of num_items + //! + //! @tparam DecomposerT + //! **[inferred]** Type of a callable object responsible for decomposing a + //! ``KeyT`` into a tuple of references to its constituent arithmetic types: + //! ``::cuda::std::tuple operator()(KeyT &key)``. + //! The leftmost element of the tuple is considered the most significant. + //! The call operator must not modify members of the key. + //! + //! @param[in] d_temp_storage + //! Device-accessible allocation of temporary storage. When `nullptr`, the + //! required allocation size is written to `temp_storage_bytes` and no work + //! is done. + //! + //! @param[in,out] temp_storage_bytes + //! Reference to size in bytes of `d_temp_storage` allocation + //! + //! @param[in,out] d_keys + //! Reference to the double-buffer of keys whose "current" device-accessible + //! buffer contains the unsorted input keys and, upon return, is updated to + //! point to the sorted output keys + //! + //! @param[in] num_items + //! Number of items to sort + //! + //! @param decomposer + //! Callable object responsible for decomposing a ``KeyT`` into a tuple of + //! references to its constituent arithmetic types. The leftmost element of + //! the tuple is considered the most significant. The call operator must not + //! modify members of the key. + //! + //! @param[in] stream + //! **[optional]** CUDA stream to launch kernels within. + //! Default is stream0. + template + CUB_RUNTIME_FUNCTION static // + typename ::cuda::std::enable_if< // + !::cuda::std::is_convertible::value, // + cudaError_t>::type + SortKeys(void *d_temp_storage, + size_t &temp_storage_bytes, + DoubleBuffer &d_keys, + NumItemsT num_items, + DecomposerT decomposer, + cudaStream_t stream = 0) + { + // unsigned integer type for global offsets + using offset_t = typename detail::ChooseOffsetT::Type; + using decomposer_check_t = detail::radix::decomposer_check_t; + + static_assert(decomposer_check_t::value, + "DecomposerT must be a callable object returning a tuple of references to " + "arithmetic types"); + + constexpr bool is_overwrite_okay = true; + constexpr bool is_descending = false; + DoubleBuffer d_values; + + return DeviceRadixSort::custom_radix_sort(decomposer_check_t{}, + d_temp_storage, + temp_storage_bytes, + is_overwrite_okay, + d_keys, + d_values, + static_cast(num_items), + decomposer, + stream); + } + + //! @rst + //! Sorts keys into ascending order using :math:`\approx N` auxiliary storage. + //! + //! * The sorting operation is given a pair of key buffers managed by a + //! DoubleBuffer structure that indicates which of the two buffers is + //! "current" (and thus contains the input data to be sorted). + //! * The contents of both buffers may be altered by the sorting operation. + //! * In-place operations are not supported. There must be no overlap between + //! any of the provided ranges: + //! + //! * ``[d_keys.Current(), d_keys.Current() + num_items)`` + //! * ``[d_keys.Alternate(), d_keys.Alternate() + num_items)` + //! + //! * A bit subrange ``[begin_bit, end_bit)`` is provided to specify + //! differentiating key bits. This can reduce overall sorting overhead and + //! yield a corresponding performance improvement. + //! * Upon completion, the sorting operation will update the "current" + //! indicator within the DoubleBuffer wrapper to reference which of the two + //! buffers now contains the sorted output sequence (a function of the + //! number of key bits specified and the targeted device architecture). + //! * @devicestorageP + //! * @devicestorage + //! + //! Snippet + //! ========================================================================== + //! + //! Let's consider a user-defined ``custom_t`` type below. To sort an array of + //! ``custom_t`` objects, we have to tell CUB about relevant members of the + //! ``custom_t`` type. We do this by providing a decomposer that returns a + //! tuple of references to relevant members of the key. + //! + //! .. literalinclude:: ../../test/catch2_test_device_radix_sort_custom.cu + //! :language: c++ + //! :dedent: + //! :start-after: example-begin custom-type + //! :end-before: example-end custom-type + //! + //! The following snippet shows how to sort an array of ``custom_t`` objects + //! using ``cub::DeviceRadixSort::SortKeys``: + //! + //! .. literalinclude:: ../../test/catch2_test_device_radix_sort_custom.cu + //! :language: c++ + //! :dedent: + //! :start-after: example-begin keys-bits-db + //! :end-before: example-end keys-bits-db + //! + //! @endrst + //! + //! @tparam KeyT + //! **[inferred]** KeyT type + //! + //! @tparam NumItemsT + //! **[inferred]** Type of num_items + //! + //! @tparam DecomposerT + //! **[inferred]** Type of a callable object responsible for decomposing a + //! ``KeyT`` into a tuple of references to its constituent arithmetic types: + //! ``::cuda::std::tuple operator()(KeyT &key)``. + //! The leftmost element of the tuple is considered the most significant. + //! The call operator must not modify members of the key. + //! + //! @param[in] d_temp_storage + //! Device-accessible allocation of temporary storage. When `nullptr`, the + //! required allocation size is written to `temp_storage_bytes` and no work + //! is done. + //! + //! @param[in,out] temp_storage_bytes + //! Reference to size in bytes of `d_temp_storage` allocation + //! + //! @param[in,out] d_keys + //! Reference to the double-buffer of keys whose "current" device-accessible + //! buffer contains the unsorted input keys and, upon return, is updated to + //! point to the sorted output keys + //! + //! @param[in] num_items + //! Number of items to sort + //! + //! @param decomposer + //! Callable object responsible for decomposing a ``KeyT`` into a tuple of + //! references to its constituent arithmetic types. The leftmost element of + //! the tuple is considered the most significant. The call operator must not + //! modify members of the key. + //! + //! @param[in] begin_bit + //! **[optional]** The least-significant bit index (inclusive) needed for + //! key comparison + //! + //! @param[in] end_bit + //! **[optional]** The most-significant bit index (exclusive) needed for key + //! comparison (e.g., `(sizeof(float) + sizeof(long long int)) * 8`) + //! + //! @param[in] stream + //! **[optional]** CUDA stream to launch kernels within. + //! Default is stream0. + template + CUB_RUNTIME_FUNCTION static // + typename ::cuda::std::enable_if< // + !::cuda::std::is_convertible::value, // + cudaError_t>::type + SortKeys(void *d_temp_storage, + size_t &temp_storage_bytes, + DoubleBuffer &d_keys, + NumItemsT num_items, + DecomposerT decomposer, + int begin_bit, + int end_bit, + cudaStream_t stream = 0) + { + // unsigned integer type for global offsets + using offset_t = typename detail::ChooseOffsetT::Type; + using decomposer_check_t = detail::radix::decomposer_check_t; + + static_assert(decomposer_check_t::value, + "DecomposerT must be a callable object returning a tuple of references to " + "arithmetic types"); + + constexpr bool is_overwrite_okay = true; + constexpr bool is_descending = false; + DoubleBuffer d_values; + + return DeviceRadixSort::custom_radix_sort(decomposer_check_t{}, + d_temp_storage, + temp_storage_bytes, + is_overwrite_okay, + d_keys, + d_values, + static_cast(num_items), + decomposer, + begin_bit, + end_bit, + stream); + } + + //! @brief Sorts keys into descending order. + //! (`~2N` auxiliary storage required). + //! + //! @par + //! - The contents of the input data are not altered by the sorting operation. + //! - Pointers to contiguous memory must be used; iterators are not currently + //! supported. + //! - In-place operations are not supported. There must be no overlap between + //! any of the provided ranges: + //! - `[d_keys_in, d_keys_in + num_items)` + //! - `[d_keys_out, d_keys_out + num_items)` + //! - An optional bit subrange `[begin_bit, end_bit)` of differentiating key + //! bits can be specified. This can reduce overall sorting overhead and + //! yield a corresponding performance improvement. + //! - @devicestorageNP For sorting using only `O(P)` temporary storage, see + //! the sorting interface using DoubleBuffer wrappers below. + //! - @devicestorage + //! + //! @par Performance + //! Performance is similar to DeviceRadixSort::SortKeys. + //! + //! @par Snippet + //! The code snippet below illustrates the sorting of a device vector of + //! `int` keys. + //! @par + //! @code + //! #include + //! // or equivalently + //! + //! // Declare, allocate, and initialize device-accessible pointers + //! // for sorting data + //! int num_items; // e.g., 7 + //! int *d_keys_in; // e.g., [8, 6, 7, 5, 3, 0, 9] + //! int *d_keys_out; // e.g., [ ... ] + //! ... + //! + //! // Create a DoubleBuffer to wrap the pair of device pointers + //! cub::DoubleBuffer d_keys(d_key_buf, d_key_alt_buf); + //! + //! // Determine temporary device storage requirements + //! void *d_temp_storage = NULL; + //! size_t temp_storage_bytes = 0; + //! cub::DeviceRadixSort::SortKeysDescending( + //! d_temp_storage, temp_storage_bytes, d_keys_in, d_keys_out, num_items); + //! + //! // Allocate temporary storage + //! cudaMalloc(&d_temp_storage, temp_storage_bytes); + //! + //! // Run sorting operation + //! cub::DeviceRadixSort::SortKeysDescending( + //! d_temp_storage, temp_storage_bytes, d_keys_in, d_keys_out, num_items); + //! + //! // d_keys_out <-- [9, 8, 7, 6, 5, 3, 0]s + //! + //! @endcode + //! + //! @tparam KeyT + //! **[inferred]** KeyT type + //! + //! @tparam NumItemsT + //! **[inferred]** Type of num_items + //! + //! @param[in] d_temp_storage + //! Device-accessible allocation of temporary storage. When `nullptr`, the + //! required allocation size is written to `temp_storage_bytes` and no work + //! is done. + //! + //! @param[in,out] temp_storage_bytes + //! Reference to size in bytes of `d_temp_storage` allocation + //! + //! @param[in] d_keys_in + //! Pointer to the input data of key data to sort + //! + //! @param[out] d_keys_out + //! Pointer to the sorted output sequence of key data + //! + //! @param[in] num_items + //! Number of items to sort + //! + //! @param[in] begin_bit + //! **[optional]** The least-significant bit index (inclusive) needed for + //! key comparison + //! + //! @param[in] end_bit + //! **[optional]** The most-significant bit index (exclusive) needed for key + //! comparison (e.g., `sizeof(unsigned int) * 8`) + //! + //! @param[in] stream + //! **[optional]** CUDA stream to launch kernels within. + //! Default is stream0. + template + CUB_RUNTIME_FUNCTION static cudaError_t + SortKeysDescending(void *d_temp_storage, + size_t &temp_storage_bytes, + const KeyT *d_keys_in, + KeyT *d_keys_out, + NumItemsT num_items, + int begin_bit = 0, + int end_bit = sizeof(KeyT) * 8, + cudaStream_t stream = 0) + { + // Unsigned integer type for global offsets. + using OffsetT = typename detail::ChooseOffsetT::Type; + + // We cast away const-ness, but will *not* write to these arrays. + // `DispatchRadixSort::Dispatch` will allocate temporary storage and + // create a new double-buffer internally when the `is_overwrite_ok` flag + // is not set. + constexpr bool is_overwrite_okay = false; + DoubleBuffer d_keys(const_cast(d_keys_in), d_keys_out); + DoubleBuffer d_values; + + return DispatchRadixSort::Dispatch( + d_temp_storage, + temp_storage_bytes, + d_keys, + d_values, + num_items, + begin_bit, + end_bit, + is_overwrite_okay, + stream); + } + + #ifndef DOXYGEN_SHOULD_SKIP_THIS // Do not document + template + CUB_DETAIL_RUNTIME_DEBUG_SYNC_IS_NOT_SUPPORTED + CUB_RUNTIME_FUNCTION static cudaError_t + SortKeysDescending(void *d_temp_storage, + size_t &temp_storage_bytes, + const KeyT *d_keys_in, + KeyT *d_keys_out, + NumItemsT num_items, + int begin_bit, + int end_bit, + cudaStream_t stream, + bool debug_synchronous) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + + return SortKeysDescending(d_temp_storage, + temp_storage_bytes, + d_keys_in, + d_keys_out, + num_items, + begin_bit, + end_bit, + stream); + } + #endif + + //! @rst + //! Sorts keys into descending order using :math:`\approx 2N` auxiliary storage. + //! + //! * The contents of the input data are not altered by the sorting operation. + //! * Pointers to contiguous memory must be used; iterators are not currently + //! supported. + //! * In-place operations are not supported. There must be no overlap between + //! any of the provided ranges: + //! + //! * ``[d_keys_in, d_keys_in + num_items)`` + //! * ``[d_keys_out, d_keys_out + num_items)`` + //! + //! * An optional bit subrange ``[begin_bit, end_bit)`` of differentiating key + //! bits can be specified. This can reduce overall sorting overhead and + //! yield a corresponding performance improvement. + //! * @devicestorageNP For sorting using only :math:`O(P)` temporary storage, see + //! the sorting interface using DoubleBuffer wrappers below. + //! * @devicestorage + //! + //! Snippet + //! ========================================================================== + //! + //! Let's consider a user-defined ``custom_t`` type below. To sort an array of + //! ``custom_t`` objects, we have to tell CUB about relevant members of the + //! ``custom_t`` type. We do this by providing a decomposer that returns a + //! tuple of references to relevant members of the key. + //! + //! .. literalinclude:: ../../test/catch2_test_device_radix_sort_custom.cu + //! :language: c++ + //! :dedent: + //! :start-after: example-begin custom-type + //! :end-before: example-end custom-type + //! + //! The following snippet shows how to sort an array of ``custom_t`` objects + //! using ``cub::DeviceRadixSort::SortKeysDescending``: + //! + //! .. literalinclude:: ../../test/catch2_test_device_radix_sort_custom.cu + //! :language: c++ + //! :dedent: + //! :start-after: example-begin keys-descending-bits + //! :end-before: example-end keys-descending-bits + //! + //! @endrst + //! + //! @tparam KeyT + //! **[inferred]** KeyT type + //! + //! @tparam NumItemsT + //! **[inferred]** Type of num_items + //! + //! @tparam DecomposerT + //! **[inferred]** Type of a callable object responsible for decomposing a + //! ``KeyT`` into a tuple of references to its constituent arithmetic types: + //! ``::cuda::std::tuple operator()(KeyT &key)``. + //! The leftmost element of the tuple is considered the most significant. + //! The call operator must not modify members of the key. + //! + //! @param[in] d_temp_storage + //! Device-accessible allocation of temporary storage. When `nullptr`, the + //! required allocation size is written to `temp_storage_bytes` and no work + //! is done. + //! + //! @param[in,out] temp_storage_bytes + //! Reference to size in bytes of `d_temp_storage` allocation + //! + //! @param[in] d_keys_in + //! Pointer to the input data of key data to sort + //! + //! @param[out] d_keys_out + //! Pointer to the sorted output sequence of key data + //! + //! @param[in] num_items + //! Number of items to sort + //! + //! @param decomposer + //! Callable object responsible for decomposing a ``KeyT`` into a tuple of + //! references to its constituent arithmetic types. The leftmost element of + //! the tuple is considered the most significant. The call operator must not + //! modify members of the key. + //! + //! @param[in] begin_bit + //! **[optional]** The least-significant bit index (inclusive) needed for + //! key comparison + //! + //! @param[in] end_bit + //! **[optional]** The most-significant bit index (exclusive) needed for key + //! comparison (e.g., `(sizeof(float) + sizeof(long long int)) * 8`) + //! + //! @param[in] stream + //! **[optional]** CUDA stream to launch kernels within. + //! Default is stream0. + template + CUB_RUNTIME_FUNCTION static // + typename ::cuda::std::enable_if< // + !::cuda::std::is_convertible::value, // + cudaError_t>::type + SortKeysDescending(void *d_temp_storage, + size_t &temp_storage_bytes, + const KeyT *d_keys_in, + KeyT *d_keys_out, + NumItemsT num_items, + DecomposerT decomposer, + int begin_bit, + int end_bit, + cudaStream_t stream = 0) + { + // unsigned integer type for global offsets + using offset_t = typename detail::ChooseOffsetT::Type; + using decomposer_check_t = detail::radix::decomposer_check_t; + + static_assert(decomposer_check_t::value, + "DecomposerT must be a callable object returning a tuple of references to " + "arithmetic types"); + + // We cast away const-ness, but will *not* write to these arrays. + // `DispatchRadixSort::Dispatch` will allocate temporary storage and + // create a new double-buffer internally when the `is_overwrite_ok` flag + // is not set. + constexpr bool is_overwrite_okay = false; + constexpr bool is_descending = true; + DoubleBuffer d_keys(const_cast(d_keys_in), d_keys_out); + DoubleBuffer d_values; + + return DeviceRadixSort::custom_radix_sort(decomposer_check_t{}, + d_temp_storage, + temp_storage_bytes, + is_overwrite_okay, + d_keys, + d_values, + static_cast(num_items), + decomposer, + begin_bit, + end_bit, + stream); + } + + //! @rst + //! Sorts keys into descending order using :math:`\approx 2N` auxiliary storage. + //! + //! * The contents of the input data are not altered by the sorting operation. + //! * Pointers to contiguous memory must be used; iterators are not currently + //! supported. + //! * In-place operations are not supported. There must be no overlap between + //! any of the provided ranges: + //! + //! * ``[d_keys_in, d_keys_in + num_items)`` + //! * ``[d_keys_out, d_keys_out + num_items)`` + //! + //! * @devicestorageNP For sorting using only :math:`O(P)` temporary storage, see + //! the sorting interface using DoubleBuffer wrappers below. + //! * @devicestorage + //! + //! Snippet + //! ========================================================================== + //! + //! Let's consider a user-defined ``custom_t`` type below. To sort an array of + //! ``custom_t`` objects, we have to tell CUB about relevant members of the + //! ``custom_t`` type. We do this by providing a decomposer that returns a + //! tuple of references to relevant members of the key. + //! + //! .. literalinclude:: ../../test/catch2_test_device_radix_sort_custom.cu + //! :language: c++ + //! :dedent: + //! :start-after: example-begin custom-type + //! :end-before: example-end custom-type + //! + //! The following snippet shows how to sort an array of ``custom_t`` objects + //! using ``cub::DeviceRadixSort::SortKeysDescending``: + //! + //! .. literalinclude:: ../../test/catch2_test_device_radix_sort_custom.cu + //! :language: c++ + //! :dedent: + //! :start-after: example-begin keys-descending + //! :end-before: example-end keys-descending + //! + //! @endrst + //! + //! @tparam KeyT + //! **[inferred]** KeyT type + //! + //! @tparam NumItemsT + //! **[inferred]** Type of num_items + //! + //! @tparam DecomposerT + //! **[inferred]** Type of a callable object responsible for decomposing a + //! ``KeyT`` into a tuple of references to its constituent arithmetic types: + //! ``::cuda::std::tuple operator()(KeyT &key)``. + //! The leftmost element of the tuple is considered the most significant. + //! The call operator must not modify members of the key. + //! + //! @param[in] d_temp_storage + //! Device-accessible allocation of temporary storage. When `nullptr`, the + //! required allocation size is written to `temp_storage_bytes` and no work + //! is done. + //! + //! @param[in,out] temp_storage_bytes + //! Reference to size in bytes of `d_temp_storage` allocation + //! + //! @param[in] d_keys_in + //! Pointer to the input data of key data to sort + //! + //! @param[out] d_keys_out + //! Pointer to the sorted output sequence of key data + //! + //! @param[in] num_items + //! Number of items to sort + //! + //! @param decomposer + //! Callable object responsible for decomposing a ``KeyT`` into a tuple of + //! references to its constituent arithmetic types. The leftmost element of + //! the tuple is considered the most significant. The call operator must not + //! modify members of the key. + //! + //! @param[in] stream + //! **[optional]** CUDA stream to launch kernels within. + //! Default is stream0. + template + CUB_RUNTIME_FUNCTION static // + typename ::cuda::std::enable_if< // + !::cuda::std::is_convertible::value, // + cudaError_t>::type + SortKeysDescending(void *d_temp_storage, + size_t &temp_storage_bytes, + const KeyT *d_keys_in, + KeyT *d_keys_out, + NumItemsT num_items, + DecomposerT decomposer, + cudaStream_t stream = 0) + { + // unsigned integer type for global offsets + using offset_t = typename detail::ChooseOffsetT::Type; + using decomposer_check_t = detail::radix::decomposer_check_t; + + static_assert(decomposer_check_t::value, + "DecomposerT must be a callable object returning a tuple of references to " + "arithmetic types"); + + // We cast away const-ness, but will *not* write to these arrays. + // `DispatchRadixSort::Dispatch` will allocate temporary storage and + // create a new double-buffer internally when the `is_overwrite_ok` flag + // is not set. + constexpr bool is_overwrite_okay = false; + constexpr bool is_descending = true; + DoubleBuffer d_keys(const_cast(d_keys_in), d_keys_out); + DoubleBuffer d_values; + + return DeviceRadixSort::custom_radix_sort(decomposer_check_t{}, + d_temp_storage, + temp_storage_bytes, + is_overwrite_okay, + d_keys, + d_values, + static_cast(num_items), + decomposer, + stream); + } + + //! @brief Sorts keys into descending order. + //! (`~N` auxiliary storage required). + //! + //! @par + //! - The sorting operation is given a pair of key buffers managed by a + //! DoubleBuffer structure that indicates which of the two buffers is + //! "current" (and thus contains the input data to be sorted). + //! - The contents of both buffers may be altered by the sorting operation. + //! - In-place operations are not supported. There must be no overlap between + //! any of the provided ranges: + //! - `[d_keys.Current(), d_keys.Current() + num_items)` + //! - `[d_keys.Alternate(), d_keys.Alternate() + num_items)` + //! - Upon completion, the sorting operation will update the "current" + //! indicator within the DoubleBuffer wrapper to reference which of the two + //! buffers now contains the sorted output sequence (a function of the + //! number of key bits specified and the targeted device architecture). + //! - An optional bit subrange `[begin_bit, end_bit)` of differentiating key + //! bits can be specified. This can reduce overall sorting overhead and + //! yield a corresponding performance improvement. + //! - @devicestorageP + //! - @devicestorage + //! + //! @par Performance + //! Performance is similar to DeviceRadixSort::SortKeys. + //! + //! @par Snippet + //! The code snippet below illustrates the sorting of a device vector of @p int keys. + //! @par + //! @code + //! #include + //! // or equivalently + //! + //! // Declare, allocate, and initialize device-accessible pointers + //! // for sorting data + //! int num_items; // e.g., 7 + //! int *d_key_buf; // e.g., [8, 6, 7, 5, 3, 0, 9] + //! int *d_key_alt_buf; // e.g., [ ... ] + //! ... + //! + //! // Create a DoubleBuffer to wrap the pair of device pointers + //! cub::DoubleBuffer d_keys(d_key_buf, d_key_alt_buf); + //! + //! // Determine temporary device storage requirements + //! void *d_temp_storage = NULL; + //! size_t temp_storage_bytes = 0; + //! cub::DeviceRadixSort::SortKeysDescending( + //! d_temp_storage, temp_storage_bytes, d_keys, num_items); + //! + //! // Allocate temporary storage + //! cudaMalloc(&d_temp_storage, temp_storage_bytes); + //! + //! // Run sorting operation + //! cub::DeviceRadixSort::SortKeysDescending( + //! d_temp_storage, temp_storage_bytes, d_keys, num_items); + //! + //! // d_keys.Current() <-- [9, 8, 7, 6, 5, 3, 0] + //! @endcode + //! + //! @tparam KeyT + //! **[inferred]** KeyT type + //! + //! @tparam NumItemsT + //! **[inferred]** Type of num_items + //! + //! @param[in] d_temp_storage + //! Device-accessible allocation of temporary storage. When `nullptr`, the + //! required allocation size is written to `temp_storage_bytes` and no work + //! is done. + //! + //! @param[in,out] temp_storage_bytes + //! Reference to size in bytes of `d_temp_storage` allocation + //! + //! @param[in,out] d_keys + //! Reference to the double-buffer of keys whose "current" device-accessible + //! buffer contains the unsorted input keys and, upon return, is updated to + //! point to the sorted output keys + //! + //! @param[in] num_items + //! Number of items to sort + //! + //! @param[in] begin_bit + //! **[optional]** The least-significant bit index (inclusive) needed for + //! key comparison + //! + //! @param[in] end_bit + //! **[optional]** The most-significant bit index (exclusive) needed for key + //! comparison (e.g., `sizeof(unsigned int) * 8`) + //! + //! @param[in] stream + //! **[optional]** CUDA stream to launch kernels within. + //! Default is stream0. + template + CUB_RUNTIME_FUNCTION static cudaError_t + SortKeysDescending(void *d_temp_storage, + size_t &temp_storage_bytes, + DoubleBuffer &d_keys, + NumItemsT num_items, + int begin_bit = 0, + int end_bit = sizeof(KeyT) * 8, + cudaStream_t stream = 0) + { + // Unsigned integer type for global offsets. + using OffsetT = typename detail::ChooseOffsetT::Type; + + constexpr bool is_overwrite_okay = true; + + // Null value type + DoubleBuffer d_values; + + return DispatchRadixSort::Dispatch( + d_temp_storage, + temp_storage_bytes, + d_keys, + d_values, + num_items, + begin_bit, + end_bit, + is_overwrite_okay, + stream); + } + + #ifndef DOXYGEN_SHOULD_SKIP_THIS // Do not document + template + CUB_DETAIL_RUNTIME_DEBUG_SYNC_IS_NOT_SUPPORTED + CUB_RUNTIME_FUNCTION static cudaError_t + SortKeysDescending(void *d_temp_storage, + size_t &temp_storage_bytes, + DoubleBuffer &d_keys, + NumItemsT num_items, + int begin_bit, + int end_bit, + cudaStream_t stream, + bool debug_synchronous) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + + return SortKeysDescending(d_temp_storage, + temp_storage_bytes, + d_keys, + num_items, + begin_bit, + end_bit, + stream); + } + #endif + + //! @rst + //! Sorts keys into descending order using :math:`\approx N` auxiliary storage. + //! + //! * The sorting operation is given a pair of key buffers managed by a + //! DoubleBuffer structure that indicates which of the two buffers is + //! "current" (and thus contains the input data to be sorted). + //! * The contents of both buffers may be altered by the sorting operation. + //! * In-place operations are not supported. There must be no overlap between + //! any of the provided ranges: + //! + //! * ``[d_keys.Current(), d_keys.Current() + num_items)`` + //! * ``[d_keys.Alternate(), d_keys.Alternate() + num_items)` + //! + //! * Upon completion, the sorting operation will update the "current" + //! indicator within the DoubleBuffer wrapper to reference which of the two + //! buffers now contains the sorted output sequence (a function of the + //! number of key bits specified and the targeted device architecture). + //! * @devicestorageP + //! * @devicestorage + //! + //! Snippet + //! ========================================================================== + //! + //! Let's consider a user-defined ``custom_t`` type below. To sort an array of + //! ``custom_t`` objects, we have to tell CUB about relevant members of the + //! ``custom_t`` type. We do this by providing a decomposer that returns a + //! tuple of references to relevant members of the key. + //! + //! .. literalinclude:: ../../test/catch2_test_device_radix_sort_custom.cu + //! :language: c++ + //! :dedent: + //! :start-after: example-begin custom-type + //! :end-before: example-end custom-type + //! + //! The following snippet shows how to sort an array of ``custom_t`` objects + //! using ``cub::DeviceRadixSort::SortKeysDescending``: + //! + //! .. literalinclude:: ../../test/catch2_test_device_radix_sort_custom.cu + //! :language: c++ + //! :dedent: + //! :start-after: example-begin keys-descending-db + //! :end-before: example-end keys-descending-db + //! + //! @endrst + //! + //! @tparam KeyT + //! **[inferred]** KeyT type + //! + //! @tparam NumItemsT + //! **[inferred]** Type of num_items + //! + //! @tparam DecomposerT + //! **[inferred]** Type of a callable object responsible for decomposing a + //! ``KeyT`` into a tuple of references to its constituent arithmetic types: + //! ``::cuda::std::tuple operator()(KeyT &key)``. + //! The leftmost element of the tuple is considered the most significant. + //! The call operator must not modify members of the key. + //! + //! @param[in] d_temp_storage + //! Device-accessible allocation of temporary storage. When `nullptr`, the + //! required allocation size is written to `temp_storage_bytes` and no work + //! is done. + //! + //! @param[in,out] temp_storage_bytes + //! Reference to size in bytes of `d_temp_storage` allocation + //! + //! @param[in,out] d_keys + //! Reference to the double-buffer of keys whose "current" device-accessible + //! buffer contains the unsorted input keys and, upon return, is updated to + //! point to the sorted output keys + //! + //! @param[in] num_items + //! Number of items to sort + //! + //! @param decomposer + //! Callable object responsible for decomposing a ``KeyT`` into a tuple of + //! references to its constituent arithmetic types. The leftmost element of + //! the tuple is considered the most significant. The call operator must not + //! modify members of the key. + //! + //! @param[in] stream + //! **[optional]** CUDA stream to launch kernels within. + //! Default is stream0. + template + CUB_RUNTIME_FUNCTION static // + typename ::cuda::std::enable_if< // + !::cuda::std::is_convertible::value, // + cudaError_t>::type + SortKeysDescending(void *d_temp_storage, + size_t &temp_storage_bytes, + DoubleBuffer &d_keys, + NumItemsT num_items, + DecomposerT decomposer, + cudaStream_t stream = 0) + { + // unsigned integer type for global offsets + using offset_t = typename detail::ChooseOffsetT::Type; + using decomposer_check_t = detail::radix::decomposer_check_t; + + static_assert(decomposer_check_t::value, + "DecomposerT must be a callable object returning a tuple of references to " + "arithmetic types"); + + constexpr bool is_overwrite_okay = true; + constexpr bool is_descending = true; + DoubleBuffer d_values; + + return DeviceRadixSort::custom_radix_sort(decomposer_check_t{}, + d_temp_storage, + temp_storage_bytes, + is_overwrite_okay, + d_keys, + d_values, + static_cast(num_items), + decomposer, + stream); + } + + //! @rst + //! Sorts keys into descending order using :math:`\approx N` auxiliary storage. + //! + //! * The sorting operation is given a pair of key buffers managed by a + //! DoubleBuffer structure that indicates which of the two buffers is + //! "current" (and thus contains the input data to be sorted). + //! * The contents of both buffers may be altered by the sorting operation. + //! * In-place operations are not supported. There must be no overlap between + //! any of the provided ranges: + //! + //! * ``[d_keys.Current(), d_keys.Current() + num_items)`` + //! * ``[d_keys.Alternate(), d_keys.Alternate() + num_items)` + //! + //! * A bit subrange ``[begin_bit, end_bit)`` is provided to specify + //! differentiating key bits. This can reduce overall sorting overhead and + //! yield a corresponding performance improvement. + //! * Upon completion, the sorting operation will update the "current" + //! indicator within the DoubleBuffer wrapper to reference which of the two + //! buffers now contains the sorted output sequence (a function of the + //! number of key bits specified and the targeted device architecture). + //! * @devicestorageP + //! * @devicestorage + //! + //! Snippet + //! ========================================================================== + //! + //! Let's consider a user-defined ``custom_t`` type below. To sort an array of + //! ``custom_t`` objects, we have to tell CUB about relevant members of the + //! ``custom_t`` type. We do this by providing a decomposer that returns a + //! tuple of references to relevant members of the key. + //! + //! .. literalinclude:: ../../test/catch2_test_device_radix_sort_custom.cu + //! :language: c++ + //! :dedent: + //! :start-after: example-begin custom-type + //! :end-before: example-end custom-type + //! + //! The following snippet shows how to sort an array of ``custom_t`` objects + //! using ``cub::DeviceRadixSort::SortKeysDescending``: + //! + //! .. literalinclude:: ../../test/catch2_test_device_radix_sort_custom.cu + //! :language: c++ + //! :dedent: + //! :start-after: example-begin keys-descending-bits-db + //! :end-before: example-end keys-descending-bits-db + //! + //! @endrst + //! + //! @tparam KeyT + //! **[inferred]** KeyT type + //! + //! @tparam NumItemsT + //! **[inferred]** Type of num_items + //! + //! @tparam DecomposerT + //! **[inferred]** Type of a callable object responsible for decomposing a + //! ``KeyT`` into a tuple of references to its constituent arithmetic types: + //! ``::cuda::std::tuple operator()(KeyT &key)``. + //! The leftmost element of the tuple is considered the most significant. + //! The call operator must not modify members of the key. + //! + //! @param[in] d_temp_storage + //! Device-accessible allocation of temporary storage. When `nullptr`, the + //! required allocation size is written to `temp_storage_bytes` and no work + //! is done. + //! + //! @param[in,out] temp_storage_bytes + //! Reference to size in bytes of `d_temp_storage` allocation + //! + //! @param[in,out] d_keys + //! Reference to the double-buffer of keys whose "current" device-accessible + //! buffer contains the unsorted input keys and, upon return, is updated to + //! point to the sorted output keys + //! + //! @param[in] num_items + //! Number of items to sort + //! + //! @param decomposer + //! Callable object responsible for decomposing a ``KeyT`` into a tuple of + //! references to its constituent arithmetic types. The leftmost element of + //! the tuple is considered the most significant. The call operator must not + //! modify members of the key. + //! + //! @param[in] begin_bit + //! **[optional]** The least-significant bit index (inclusive) needed for + //! key comparison + //! + //! @param[in] end_bit + //! **[optional]** The most-significant bit index (exclusive) needed for key + //! comparison (e.g., `(sizeof(float) + sizeof(long long int)) * 8`) + //! + //! @param[in] stream + //! **[optional]** CUDA stream to launch kernels within. + //! Default is stream0. + template + CUB_RUNTIME_FUNCTION static // + typename ::cuda::std::enable_if< // + !::cuda::std::is_convertible::value, // + cudaError_t>::type + SortKeysDescending(void *d_temp_storage, + size_t &temp_storage_bytes, + DoubleBuffer &d_keys, + NumItemsT num_items, + DecomposerT decomposer, + int begin_bit, + int end_bit, + cudaStream_t stream = 0) + { + // unsigned integer type for global offsets + using offset_t = typename detail::ChooseOffsetT::Type; + using decomposer_check_t = detail::radix::decomposer_check_t; + + static_assert(decomposer_check_t::value, + "DecomposerT must be a callable object returning a tuple of references to " + "arithmetic types"); + + constexpr bool is_overwrite_okay = true; + constexpr bool is_descending = true; + DoubleBuffer d_values; + + return DeviceRadixSort::custom_radix_sort(decomposer_check_t{}, + d_temp_storage, + temp_storage_bytes, + is_overwrite_okay, + d_keys, + d_values, + static_cast(num_items), + decomposer, + begin_bit, + end_bit, + stream); + } + + //@} end member group +}; + +/** + * @example example_device_radix_sort.cu + */ + +CUB_NAMESPACE_END diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/device/device_reduce.cuh b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/device/device_reduce.cuh new file mode 100644 index 0000000000000000000000000000000000000000..f2c4090f8b597be7503864f8e55b8c075c70333f --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/device/device_reduce.cuh @@ -0,0 +1,1213 @@ +/****************************************************************************** + * Copyright (c) 2011, Duane Merrill. All rights reserved. + * Copyright (c) 2011-2022, NVIDIA CORPORATION. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the NVIDIA CORPORATION nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ******************************************************************************/ + +/** + * @file cub::DeviceReduce provides device-wide, parallel operations for + * computing a reduction across a sequence of data items residing within + * device-accessible memory. + */ + +#pragma once + +#include +#include + +#include +#include +#include +#include +#include +#include + +CUB_NAMESPACE_BEGIN + + +//! @ingroup SingleModule +//! +//! @rst +//! DeviceReduce provides device-wide, parallel operations for computing +//! a reduction across a sequence of data items residing within +//! device-accessible memory. +//! +//! .. image:: ../img/reduce_logo.png +//! :align: center +//! +//! Overview +//! ==================================== +//! A `reduction `_ +//! (or *fold*) uses a binary combining operator to compute a single aggregate +//! from a sequence of input elements. +//! +//! Usage Considerations +//! ==================================== +//! @cdp_class{DeviceReduce} +//! +//! Performance +//! ==================================== +//! @linear_performance{reduction, reduce-by-key, and run-length encode} +//! +//! The following chart illustrates DeviceReduce::Sum +//! performance across different CUDA architectures for \p int32 keys. +//! +//! .. image:: ../img/reduce_int32.png +//! :align: center +//! +//! @par +//! The following chart illustrates DeviceReduce::ReduceByKey (summation) +//! performance across different CUDA architectures for `fp32` values. Segments +//! are identified by `int32` keys, and have lengths uniformly sampled +//! from `[1, 1000]`. +//! +//! .. image:: ../img/reduce_by_key_fp32_len_500.png +//! :align: center +//! +//! @endrst +struct DeviceReduce +{ + /** + * @brief Computes a device-wide reduction using the specified binary + * `reduction_op` functor and initial value `init`. + * + * @par + * - Does not support binary reduction operators that are non-commutative. + * - Provides "run-to-run" determinism for pseudo-associative reduction + * (e.g., addition of floating point types) on the same GPU device. + * However, results for pseudo-associative reduction may be inconsistent + * from one device to a another device of a different compute-capability + * because CUB can employ different tile-sizing for different architectures. + * - The range `[d_in, d_in + num_items)` shall not overlap `d_out`. + * - @devicestorage + * + * @par Snippet + * The code snippet below illustrates a user-defined min-reduction of a + * device vector of `int` data elements. + * @par + * @code + * #include + * // or equivalently + * + * // CustomMin functor + * struct CustomMin + * { + * template + * __device__ __forceinline__ + * T operator()(const T &a, const T &b) const { + * return (b < a) ? b : a; + * } + * }; + * + * // Declare, allocate, and initialize device-accessible pointers for + * // input and output + * int num_items; // e.g., 7 + * int *d_in; // e.g., [8, 6, 7, 5, 3, 0, 9] + * int *d_out; // e.g., [-] + * CustomMin min_op; + * int init; // e.g., INT_MAX + * ... + * + * // Determine temporary device storage requirements + * void *d_temp_storage = NULL; + * size_t temp_storage_bytes = 0; + * cub::DeviceReduce::Reduce( + * d_temp_storage, temp_storage_bytes, + * d_in, d_out, num_items, min_op, init); + * + * // Allocate temporary storage + * cudaMalloc(&d_temp_storage, temp_storage_bytes); + * + * // Run reduction + * cub::DeviceReduce::Reduce( + * d_temp_storage, temp_storage_bytes, + * d_in, d_out, num_items, min_op, init); + * + * // d_out <-- [0] + * @endcode + * + * @tparam InputIteratorT + * **[inferred]** Random-access input iterator type for reading input + * items \iterator + * + * @tparam OutputIteratorT + * **[inferred]** Output iterator type for recording the reduced + * aggregate \iterator + * + * @tparam ReductionOpT + * **[inferred]** Binary reduction functor type having member + * `T operator()(const T &a, const T &b)` + * + * @tparam T + * **[inferred]** Data element type that is convertible to the `value` type + * of `InputIteratorT` + * + * @tparam NumItemsT **[inferred]** Type of num_items + * + * @param[in] d_temp_storage + * Device-accessible allocation of temporary storage. When `nullptr`, the + * required allocation size is written to `temp_storage_bytes` and no work + * is done. + * + * @param[in,out] temp_storage_bytes + * Reference to size in bytes of `d_temp_storage` allocation + * + * @param d_in[in] + * Pointer to the input sequence of data items + * + * @param d_out[out] + * Pointer to the output aggregate + * + * @param num_items[in] + * Total number of input items (i.e., length of `d_in`) + * + * @param reduction_op[in] + * Binary reduction functor + * + * @param[in] init + * Initial value of the reduction + * + * @param[in] stream + * **[optional]** CUDA stream to launch kernels within. + * Default is stream0. + */ + template + CUB_RUNTIME_FUNCTION static cudaError_t Reduce(void *d_temp_storage, + size_t &temp_storage_bytes, + InputIteratorT d_in, + OutputIteratorT d_out, + NumItemsT num_items, + ReductionOpT reduction_op, + T init, + cudaStream_t stream = 0) + { + // Signed integer type for global offsets + using OffsetT = typename detail::ChooseOffsetT::Type; + + return DispatchReduce::Dispatch(d_temp_storage, + temp_storage_bytes, + d_in, + d_out, + static_cast(num_items), + reduction_op, + init, + stream); + } + + template + CUB_DETAIL_RUNTIME_DEBUG_SYNC_IS_NOT_SUPPORTED + CUB_RUNTIME_FUNCTION static cudaError_t Reduce(void *d_temp_storage, + size_t &temp_storage_bytes, + InputIteratorT d_in, + OutputIteratorT d_out, + int num_items, + ReductionOpT reduction_op, + T init, + cudaStream_t stream, + bool debug_synchronous) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + + return Reduce( + d_temp_storage, + temp_storage_bytes, + d_in, + d_out, + num_items, + reduction_op, + init, + stream); + } + + /** + * @brief Computes a device-wide sum using the addition (`+`) operator. + * + * @par + * - Uses `0` as the initial value of the reduction. + * - Does not support \p + operators that are non-commutative.. + * - Provides "run-to-run" determinism for pseudo-associative reduction + * (e.g., addition of floating point types) on the same GPU device. + * However, results for pseudo-associative reduction may be inconsistent + * from one device to a another device of a different compute-capability + * because CUB can employ different tile-sizing for different architectures. + * - The range `[d_in, d_in + num_items)` shall not overlap `d_out`. + * - @devicestorage + * + * @par Performance + * The following charts illustrate saturated sum-reduction performance across + * different CUDA architectures for `int32` and `int64` items, respectively. + * + * @image html reduce_int32.png + * @image html reduce_int64.png + * + * @par Snippet + * The code snippet below illustrates the sum-reduction of a device vector + * of `int` data elements. + * @par + * @code + * #include + * // or equivalently + * + * // Declare, allocate, and initialize device-accessible pointers + * // for input and output + * int num_items; // e.g., 7 + * int *d_in; // e.g., [8, 6, 7, 5, 3, 0, 9] + * int *d_out; // e.g., [-] + * ... + * + * // Determine temporary device storage requirements + * void *d_temp_storage = NULL; + * size_t temp_storage_bytes = 0; + * cub::DeviceReduce::Sum( + * d_temp_storage, temp_storage_bytes, d_in, d_out, num_items); + * + * // Allocate temporary storage + * cudaMalloc(&d_temp_storage, temp_storage_bytes); + * + * // Run sum-reduction + * cub::DeviceReduce::Sum( + * d_temp_storage, temp_storage_bytes, d_in, d_out, num_items); + * + * // d_out <-- [38] + * @endcode + * + * @tparam InputIteratorT + * **[inferred]** Random-access input iterator type for reading input + * items \iterator + * + * @tparam OutputIteratorT + * **[inferred]** Output iterator type for recording the reduced + * aggregate \iterator + * + * @tparam NumItemsT **[inferred]** Type of num_items + * + * @param[in] d_temp_storage + * Device-accessible allocation of temporary storage. When `nullptr`, the + * required allocation size is written to `temp_storage_bytes` and no work + * is done. + * + * @param[in,out] temp_storage_bytes + * Reference to size in bytes of `d_temp_storage` allocation + * + * @param[in] d_in + * Pointer to the input sequence of data items + * + * @param[out] d_out + * Pointer to the output aggregate + * + * @param[in] num_items + * Total number of input items (i.e., length of `d_in`) + * + * @param[in] stream + * **[optional]** CUDA stream to launch kernels within. + * Default is stream0. + */ + template + CUB_RUNTIME_FUNCTION static cudaError_t Sum(void *d_temp_storage, + size_t &temp_storage_bytes, + InputIteratorT d_in, + OutputIteratorT d_out, + NumItemsT num_items, + cudaStream_t stream = 0) + { + // Signed integer type for global offsets + using OffsetT = typename detail::ChooseOffsetT::Type; + + // The output value type + using OutputT = + cub::detail::non_void_value_t>; + + using InitT = OutputT; + + return DispatchReduce::Dispatch(d_temp_storage, + temp_storage_bytes, + d_in, + d_out, + static_cast(num_items), + cub::Sum(), + InitT{}, // zero-initialize + stream); + } + + template + CUB_DETAIL_RUNTIME_DEBUG_SYNC_IS_NOT_SUPPORTED + CUB_RUNTIME_FUNCTION static cudaError_t Sum(void *d_temp_storage, + size_t &temp_storage_bytes, + InputIteratorT d_in, + OutputIteratorT d_out, + int num_items, + cudaStream_t stream, + bool debug_synchronous) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + + return Sum(d_temp_storage, + temp_storage_bytes, + d_in, + d_out, + num_items, + stream); + } + + /** + * @brief Computes a device-wide minimum using the less-than ('<') operator. + * + * @par + * - Uses `std::numeric_limits::max()` as the initial value of the reduction. + * - Does not support `<` operators that are non-commutative. + * - Provides "run-to-run" determinism for pseudo-associative reduction + * (e.g., addition of floating point types) on the same GPU device. + * However, results for pseudo-associative reduction may be inconsistent + * from one device to a another device of a different compute-capability + * because CUB can employ different tile-sizing for different architectures. + * - The range `[d_in, d_in + num_items)` shall not overlap `d_out`. + * - @devicestorage + * + * @par Snippet + * The code snippet below illustrates the min-reduction of a device vector of + * `int` data elements. + * @par + * @code + * #include + * // or equivalently + * + * // Declare, allocate, and initialize device-accessible pointers + * // for input and output + * int num_items; // e.g., 7 + * int *d_in; // e.g., [8, 6, 7, 5, 3, 0, 9] + * int *d_out; // e.g., [-] + * ... + * + * // Determine temporary device storage requirements + * void *d_temp_storage = NULL; + * size_t temp_storage_bytes = 0; + * cub::DeviceReduce::Min( + * d_temp_storage, temp_storage_bytes, d_in, d_out, num_items); + * + * // Allocate temporary storage + * cudaMalloc(&d_temp_storage, temp_storage_bytes); + * + * // Run min-reduction + * cub::DeviceReduce::Min( + * d_temp_storage, temp_storage_bytes, d_in, d_out, num_items); + * + * // d_out <-- [0] + * @endcode + * + * @tparam InputIteratorT + * **[inferred]** Random-access input iterator type for reading input + * items \iterator + * + * @tparam OutputIteratorT + * **[inferred]** Output iterator type for recording the reduced + * aggregate \iterator + * + * @tparam NumItemsT **[inferred]** Type of num_items + * + * @param[in] d_temp_storage + * Device-accessible allocation of temporary storage. When `nullptr`, the + * required allocation size is written to `temp_storage_bytes` and no work + * is done. + * + * @param[in,out] temp_storage_bytes + * Reference to size in bytes of `d_temp_storage` allocation + * + * @param[in] d_in + * Pointer to the input sequence of data items + * + * @param[out] d_out + * Pointer to the output aggregate + * + * @param[in] num_items + * Total number of input items (i.e., length of `d_in`) + * + * @param[in] stream + * **[optional]** CUDA stream to launch kernels within. + * Default is stream0. + */ + template + CUB_RUNTIME_FUNCTION static cudaError_t Min(void *d_temp_storage, + size_t &temp_storage_bytes, + InputIteratorT d_in, + OutputIteratorT d_out, + NumItemsT num_items, + cudaStream_t stream = 0) + { + // Signed integer type for global offsets + using OffsetT = typename detail::ChooseOffsetT::Type; + + // The input value type + using InputT = cub::detail::value_t; + + using InitT = InputT; + + return DispatchReduce::Dispatch(d_temp_storage, + temp_storage_bytes, + d_in, + d_out, + static_cast(num_items), + cub::Min(), + // replace with + // std::numeric_limits::max() when + // C++11 support is more prevalent + Traits::Max(), + stream); + } + + template + CUB_DETAIL_RUNTIME_DEBUG_SYNC_IS_NOT_SUPPORTED + CUB_RUNTIME_FUNCTION static cudaError_t Min(void *d_temp_storage, + size_t &temp_storage_bytes, + InputIteratorT d_in, + OutputIteratorT d_out, + int num_items, + cudaStream_t stream, + bool debug_synchronous) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + + return Min(d_temp_storage, + temp_storage_bytes, + d_in, + d_out, + num_items, + stream); + } + + /** + * @brief Finds the first device-wide minimum using the less-than ('<') + * operator, also returning the index of that item. + * + * @par + * - The output value type of `d_out` is cub::KeyValuePair `` + * (assuming the value type of `d_in` is `T`) + * - The minimum is written to `d_out.value` and its offset in the input + * array is written to `d_out.key`. + * - The `{1, std::numeric_limits::max()}` tuple is produced for + * zero-length inputs + * - Does not support `<` operators that are non-commutative. + * - Provides "run-to-run" determinism for pseudo-associative reduction + * (e.g., addition of floating point types) on the same GPU device. + * However, results for pseudo-associative reduction may be inconsistent + * from one device to a another device of a different compute-capability + * because CUB can employ different tile-sizing for different architectures. + * - The range `[d_in, d_in + num_items)` shall not overlap `d_out`. + * - @devicestorage + * + * @par Snippet + * The code snippet below illustrates the argmin-reduction of a device vector + * of `int` data elements. + * @par + * @code + * #include + * // or equivalently + * + * // Declare, allocate, and initialize device-accessible pointers + * // for input and output + * int num_items; // e.g., 7 + * int *d_in; // e.g., [8, 6, 7, 5, 3, 0, 9] + * KeyValuePair *d_out; // e.g., [{-,-}] + * ... + * + * // Determine temporary device storage requirements + * void *d_temp_storage = NULL; + * size_t temp_storage_bytes = 0; + * cub::DeviceReduce::ArgMin( + * d_temp_storage, temp_storage_bytes, d_in, d_argmin, num_items); + * + * // Allocate temporary storage + * cudaMalloc(&d_temp_storage, temp_storage_bytes); + * + * // Run argmin-reduction + * cub::DeviceReduce::ArgMin( + * d_temp_storage, temp_storage_bytes, d_in, d_argmin, num_items); + * + * // d_out <-- [{5, 0}] + * + * @endcode + * + * @tparam InputIteratorT + * **[inferred]** Random-access input iterator type for reading input items + * (of some type `T`) \iterator + * + * @tparam OutputIteratorT + * **[inferred]** Output iterator type for recording the reduced aggregate + * (having value type `cub::KeyValuePair`) \iterator + * + * @param[in] d_temp_storage + * Device-accessible allocation of temporary storage. When `nullptr`, the + * required allocation size is written to \p temp_storage_bytes and no work is done. + * + * @param[in,out] temp_storage_bytes + * Reference to size in bytes of `d_temp_storage` allocation + * + * @param[in] d_in + * Pointer to the input sequence of data items + * + * @param[out] d_out + * Pointer to the output aggregate + * + * @param[in] num_items + * Total number of input items (i.e., length of `d_in`) + * + * @param[in] stream + * **[optional]** CUDA stream to launch kernels within. + * Default is stream0. + */ + template + CUB_RUNTIME_FUNCTION static cudaError_t ArgMin(void *d_temp_storage, + size_t &temp_storage_bytes, + InputIteratorT d_in, + OutputIteratorT d_out, + int num_items, + cudaStream_t stream = 0) + { + // Signed integer type for global offsets + using OffsetT = int; + + // The input type + using InputValueT = cub::detail::value_t; + + // The output tuple type + using OutputTupleT = + cub::detail::non_void_value_t>; + + using AccumT = OutputTupleT; + + using InitT = detail::reduce::empty_problem_init_t; + + // The output value type + using OutputValueT = typename OutputTupleT::Value; + + // Wrapped input iterator to produce index-value tuples + using ArgIndexInputIteratorT = + ArgIndexInputIterator; + + ArgIndexInputIteratorT d_indexed_in(d_in); + + // Initial value + // TODO Address https://github.com/NVIDIA/cub/issues/651 + InitT initial_value{AccumT(1, Traits::Max())}; + + return DispatchReduce::Dispatch(d_temp_storage, + temp_storage_bytes, + d_indexed_in, + d_out, + num_items, + cub::ArgMin(), + initial_value, + stream); + } + + template + CUB_DETAIL_RUNTIME_DEBUG_SYNC_IS_NOT_SUPPORTED + CUB_RUNTIME_FUNCTION static cudaError_t ArgMin(void *d_temp_storage, + size_t &temp_storage_bytes, + InputIteratorT d_in, + OutputIteratorT d_out, + int num_items, + cudaStream_t stream, + bool debug_synchronous) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + + return ArgMin(d_temp_storage, + temp_storage_bytes, + d_in, + d_out, + num_items, + stream); + } + + /** + * @brief Computes a device-wide maximum using the greater-than ('>') operator. + * + * @par + * - Uses `std::numeric_limits::lowest()` as the initial value of the + * reduction. + * - Does not support `>` operators that are non-commutative. + * - Provides "run-to-run" determinism for pseudo-associative reduction + * (e.g., addition of floating point types) on the same GPU device. + * However, results for pseudo-associative reduction may be inconsistent + * from one device to a another device of a different compute-capability + * because CUB can employ different tile-sizing for different architectures. + * - The range `[d_in, d_in + num_items)` shall not overlap `d_out`. + * - @devicestorage + * + * @par Snippet + * The code snippet below illustrates the max-reduction of a device vector of + * `int` data elements. + * @par + * @code + * #include + * // or equivalently + * + * // Declare, allocate, and initialize device-accessible pointers + * // for input and output + * int num_items; // e.g., 7 + * int *d_in; // e.g., [8, 6, 7, 5, 3, 0, 9] + * int *d_out; // e.g., [-] + * ... + * + * // Determine temporary device storage requirements + * void *d_temp_storage = NULL; + * size_t temp_storage_bytes = 0; + * cub::DeviceReduce::Max( + * d_temp_storage, temp_storage_bytes, d_in, d_max, num_items); + * + * // Allocate temporary storage + * cudaMalloc(&d_temp_storage, temp_storage_bytes); + * + * // Run max-reduction + * cub::DeviceReduce::Max( + * d_temp_storage, temp_storage_bytes, d_in, d_max, num_items); + * + * // d_out <-- [9] + * @endcode + * + * @tparam InputIteratorT + * **[inferred]** Random-access input iterator type for reading input + * items \iterator + * + * @tparam OutputIteratorT + * **[inferred]** Output iterator type for recording the reduced + * aggregate \iterator + * + * @tparam NumItemsT **[inferred]** Type of num_items + * + * @param[in] d_temp_storage + * Device-accessible allocation of temporary storage. When `nullptr`, the + * required allocation size is written to `temp_storage_bytes` and no work + * is done. + * + * @param[in,out] temp_storage_bytes + * Reference to size in bytes of `d_temp_storage` allocation + * + * @param[in] d_in + * Pointer to the input sequence of data items + * + * @param[out] d_out + * Pointer to the output aggregate + * + * @param[in] num_items + * Total number of input items (i.e., length of `d_in`) + * + * @param[in] stream + * **[optional]** CUDA stream to launch kernels within. + * Default is stream0. + */ + template + CUB_RUNTIME_FUNCTION static cudaError_t Max(void *d_temp_storage, + size_t &temp_storage_bytes, + InputIteratorT d_in, + OutputIteratorT d_out, + NumItemsT num_items, + cudaStream_t stream = 0) + { + // Signed integer type for global offsets + using OffsetT = typename detail::ChooseOffsetT::Type; + + // The input value type + using InputT = cub::detail::value_t; + + using InitT = InputT; + + return DispatchReduce::Dispatch(d_temp_storage, + temp_storage_bytes, + d_in, + d_out, + static_cast(num_items), + cub::Max(), + // replace with + // std::numeric_limits::lowest() + // when C++11 support is more + // prevalent + Traits::Lowest(), + stream); + } + + template + CUB_DETAIL_RUNTIME_DEBUG_SYNC_IS_NOT_SUPPORTED + CUB_RUNTIME_FUNCTION static cudaError_t Max(void *d_temp_storage, + size_t &temp_storage_bytes, + InputIteratorT d_in, + OutputIteratorT d_out, + int num_items, + cudaStream_t stream, + bool debug_synchronous) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + + return Max(d_temp_storage, + temp_storage_bytes, + d_in, + d_out, + num_items, + stream); + } + + /** + * @brief Finds the first device-wide maximum using the greater-than ('>') + * operator, also returning the index of that item + * + * @par + * - The output value type of `d_out` is cub::KeyValuePair `` + * (assuming the value type of `d_in` is `T`) + * - The maximum is written to `d_out.value` and its offset in the input + * array is written to `d_out.key`. + * - The `{1, std::numeric_limits::lowest()}` tuple is produced for + * zero-length inputs + * - Does not support `>` operators that are non-commutative. + * - Provides "run-to-run" determinism for pseudo-associative reduction + * (e.g., addition of floating point types) on the same GPU device. + * However, results for pseudo-associative reduction may be inconsistent + * from one device to a another device of a different compute-capability + * because CUB can employ different tile-sizing for different architectures. + * - The range `[d_in, d_in + num_items)` shall not overlap `d_out`. + * - @devicestorage + * + * @par Snippet + * The code snippet below illustrates the argmax-reduction of a device vector + * of `int` data elements. + * @par + * @code + * #include + * // or equivalently + * + * // Declare, allocate, and initialize device-accessible pointers + * // for input and output + * int num_items; // e.g., 7 + * int *d_in; // e.g., [8, 6, 7, 5, 3, 0, 9] + * KeyValuePair *d_out; // e.g., [{-,-}] + * ... + * + * // Determine temporary device storage requirements + * void *d_temp_storage = NULL; + * size_t temp_storage_bytes = 0; + * cub::DeviceReduce::ArgMax( + * d_temp_storage, temp_storage_bytes, d_in, d_argmax, num_items); + * + * // Allocate temporary storage + * cudaMalloc(&d_temp_storage, temp_storage_bytes); + * + * // Run argmax-reduction + * cub::DeviceReduce::ArgMax( + * d_temp_storage, temp_storage_bytes, d_in, d_argmax, num_items); + * + * // d_out <-- [{6, 9}] + * + * @endcode + * + * @tparam InputIteratorT + * **[inferred]** Random-access input iterator type for reading input items + * (of some type \p T) \iterator + * + * @tparam OutputIteratorT + * **[inferred]** Output iterator type for recording the reduced aggregate + * (having value type `cub::KeyValuePair`) \iterator + * + * @param[in] d_temp_storage + * Device-accessible allocation of temporary storage. When `nullptr`, the + * required allocation size is written to `temp_storage_bytes` and no work + * is done. + * + * @param[in,out] temp_storage_bytes + * Reference to size in bytes of `d_temp_storage` allocation + * + * @param[in] d_in + * Pointer to the input sequence of data items + * + * @param[out] d_out + * Pointer to the output aggregate + * + * @param[in] num_items + * Total number of input items (i.e., length of `d_in`) + * + * @param[in] stream + * **[optional]** CUDA stream to launch kernels within. + * Default is stream0. + */ + template + CUB_RUNTIME_FUNCTION static cudaError_t ArgMax(void *d_temp_storage, + size_t &temp_storage_bytes, + InputIteratorT d_in, + OutputIteratorT d_out, + int num_items, + cudaStream_t stream = 0) + { + // Signed integer type for global offsets + using OffsetT = int; + + // The input type + using InputValueT = cub::detail::value_t; + + // The output tuple type + using OutputTupleT = + cub::detail::non_void_value_t>; + + using AccumT = OutputTupleT; + + // The output value type + using OutputValueT = typename OutputTupleT::Value; + + using InitT = detail::reduce::empty_problem_init_t; + + // Wrapped input iterator to produce index-value tuples + using ArgIndexInputIteratorT = + ArgIndexInputIterator; + + ArgIndexInputIteratorT d_indexed_in(d_in); + + // Initial value + // TODO Address https://github.com/NVIDIA/cub/issues/651 + InitT initial_value{AccumT(1, Traits::Lowest())}; + + return DispatchReduce::Dispatch(d_temp_storage, + temp_storage_bytes, + d_indexed_in, + d_out, + num_items, + cub::ArgMax(), + initial_value, + stream); + } + + template + CUB_DETAIL_RUNTIME_DEBUG_SYNC_IS_NOT_SUPPORTED + CUB_RUNTIME_FUNCTION static cudaError_t ArgMax(void *d_temp_storage, + size_t &temp_storage_bytes, + InputIteratorT d_in, + OutputIteratorT d_out, + int num_items, + cudaStream_t stream, + bool debug_synchronous) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + + return ArgMax(d_temp_storage, + temp_storage_bytes, + d_in, + d_out, + num_items, + stream); + } + + /** + * @brief Reduces segments of values, where segments are demarcated by + * corresponding runs of identical keys. + * + * @par + * This operation computes segmented reductions within `d_values_in` using + * the specified binary `reduction_op` functor. The segments are identified + * by "runs" of corresponding keys in `d_keys_in`, where runs are maximal + * ranges of consecutive, identical keys. For the *i*th run + * encountered, the first key of the run and the corresponding value + * aggregate of that run are written to `d_unique_out[i] and + * `d_aggregates_out[i]`, respectively. The total number of runs encountered + * is written to `d_num_runs_out`. + * + * @par + * - The `==` equality operator is used to determine whether keys are + * equivalent + * - Provides "run-to-run" determinism for pseudo-associative reduction + * (e.g., addition of floating point types) on the same GPU device. + * However, results for pseudo-associative reduction may be inconsistent + * from one device to a another device of a different compute-capability + * because CUB can employ different tile-sizing for different architectures. + * - Let `out` be any of + * `[d_unique_out, d_unique_out + *d_num_runs_out)` + * `[d_aggregates_out, d_aggregates_out + *d_num_runs_out)` + * `d_num_runs_out`. The ranges represented by `out` shall not overlap + * `[d_keys_in, d_keys_in + num_items)`, + * `[d_values_in, d_values_in + num_items)` nor `out` in any way. + * - @devicestorage + * + * @par Performance + * The following chart illustrates reduction-by-key (sum) performance across + * different CUDA architectures for `fp32` and `fp64` values, respectively. + * Segments are identified by `int32` keys, and have lengths uniformly + * sampled from `[1, 1000]`. + * + * @image html reduce_by_key_fp32_len_500.png + * @image html reduce_by_key_fp64_len_500.png + * + * @par + * The following charts are similar, but with segment lengths uniformly + * sampled from [1,10]: + * + * @image html reduce_by_key_fp32_len_5.png + * @image html reduce_by_key_fp64_len_5.png + * + * @par Snippet + * The code snippet below illustrates the segmented reduction of `int` values + * grouped by runs of associated `int` keys. + * @par + * @code + * #include + * // or equivalently + * + * // CustomMin functor + * struct CustomMin + * { + * template + * CUB_RUNTIME_FUNCTION __forceinline__ + * T operator()(const T &a, const T &b) const { + * return (b < a) ? b : a; + * } + * }; + * + * // Declare, allocate, and initialize device-accessible pointers + * // for input and output + * int num_items; // e.g., 8 + * int *d_keys_in; // e.g., [0, 2, 2, 9, 5, 5, 5, 8] + * int *d_values_in; // e.g., [0, 7, 1, 6, 2, 5, 3, 4] + * int *d_unique_out; // e.g., [-, -, -, -, -, -, -, -] + * int *d_aggregates_out; // e.g., [-, -, -, -, -, -, -, -] + * int *d_num_runs_out; // e.g., [-] + * CustomMin reduction_op; + * ... + * + * // Determine temporary device storage requirements + * void *d_temp_storage = NULL; + * size_t temp_storage_bytes = 0; + * cub::DeviceReduce::ReduceByKey( + * d_temp_storage, temp_storage_bytes, + * d_keys_in, d_unique_out, d_values_in, + * d_aggregates_out, d_num_runs_out, reduction_op, num_items); + * + * // Allocate temporary storage + * cudaMalloc(&d_temp_storage, temp_storage_bytes); + * + * // Run reduce-by-key + * cub::DeviceReduce::ReduceByKey( + * d_temp_storage, temp_storage_bytes, + * d_keys_in, d_unique_out, d_values_in, + * d_aggregates_out, d_num_runs_out, reduction_op, num_items); + * + * // d_unique_out <-- [0, 2, 9, 5, 8] + * // d_aggregates_out <-- [0, 1, 6, 2, 4] + * // d_num_runs_out <-- [5] + * @endcode + * + * @tparam KeysInputIteratorT + * **[inferred]** Random-access input iterator type for reading input + * keys \iterator + * + * @tparam UniqueOutputIteratorT + * **[inferred]** Random-access output iterator type for writing unique + * output keys \iterator + * + * @tparam ValuesInputIteratorT + * **[inferred]** Random-access input iterator type for reading input + * values \iterator + * + * @tparam AggregatesOutputIterator + * **[inferred]** Random-access output iterator type for writing output + * value aggregates \iterator + * + * @tparam NumRunsOutputIteratorT + * **[inferred]** Output iterator type for recording the number of runs + * encountered \iterator + * + * @tparam ReductionOpT + * **[inferred]*8 Binary reduction functor type having member + * `T operator()(const T &a, const T &b)` + * + * @tparam NumItemsT **[inferred]** Type of num_items + * + * @param[in] d_temp_storage + * Device-accessible allocation of temporary storage. When `nullptr`, the + * required allocation size is written to `temp_storage_bytes` and no work + * is done. + * + * @param[in,out] temp_storage_bytes + * Reference to size in bytes of `d_temp_storage` allocation + * + * @param[in] d_keys_in + * Pointer to the input sequence of keys + * + * @param[out] d_unique_out + * Pointer to the output sequence of unique keys (one key per run) + * + * @param[in] d_values_in + * Pointer to the input sequence of corresponding values + * + * @param[out] d_aggregates_out + * Pointer to the output sequence of value aggregates + * (one aggregate per run) + * + * @param[out] d_num_runs_out + * Pointer to total number of runs encountered + * (i.e., the length of `d_unique_out`) + * + * @param[in] reduction_op + * Binary reduction functor + * + * @param[in] num_items + * Total number of associated key+value pairs + * (i.e., the length of `d_in_keys` and `d_in_values`) + * + * @param[in] stream + * **[optional]** CUDA stream to launch kernels within. + * Default is stream0. + */ + template + CUB_RUNTIME_FUNCTION __forceinline__ static cudaError_t + ReduceByKey(void *d_temp_storage, + size_t &temp_storage_bytes, + KeysInputIteratorT d_keys_in, + UniqueOutputIteratorT d_unique_out, + ValuesInputIteratorT d_values_in, + AggregatesOutputIteratorT d_aggregates_out, + NumRunsOutputIteratorT d_num_runs_out, + ReductionOpT reduction_op, + NumItemsT num_items, + cudaStream_t stream = 0) + { + // Signed integer type for global offsets + using OffsetT = typename detail::ChooseOffsetT::Type; + + // FlagT iterator type (not used) + + // Selection op (not used) + + // Default == operator + typedef Equality EqualityOp; + + return DispatchReduceByKey::Dispatch(d_temp_storage, + temp_storage_bytes, + d_keys_in, + d_unique_out, + d_values_in, + d_aggregates_out, + d_num_runs_out, + EqualityOp(), + reduction_op, + static_cast(num_items), + stream); + } + + template + CUB_DETAIL_RUNTIME_DEBUG_SYNC_IS_NOT_SUPPORTED + CUB_RUNTIME_FUNCTION __forceinline__ static cudaError_t + ReduceByKey(void *d_temp_storage, + size_t &temp_storage_bytes, + KeysInputIteratorT d_keys_in, + UniqueOutputIteratorT d_unique_out, + ValuesInputIteratorT d_values_in, + AggregatesOutputIteratorT d_aggregates_out, + NumRunsOutputIteratorT d_num_runs_out, + ReductionOpT reduction_op, + int num_items, + cudaStream_t stream, + bool debug_synchronous) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + + return ReduceByKey(d_temp_storage, + temp_storage_bytes, + d_keys_in, + d_unique_out, + d_values_in, + d_aggregates_out, + d_num_runs_out, + reduction_op, + num_items, + stream); + } +}; + +/** + * @example example_device_reduce.cu + */ + +CUB_NAMESPACE_END + diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/device/device_run_length_encode.cuh b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/device/device_run_length_encode.cuh new file mode 100644 index 0000000000000000000000000000000000000000..2a8a546bd3868959765600a2bc22c0d2263e6d20 --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/device/device_run_length_encode.cuh @@ -0,0 +1,451 @@ +/****************************************************************************** + * Copyright (c) 2011, Duane Merrill. All rights reserved. + * Copyright (c) 2011-2022, NVIDIA CORPORATION. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the NVIDIA CORPORATION nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ******************************************************************************/ + +/** + * @file cub::DeviceRunLengthEncode provides device-wide, parallel operations + * for computing a run-length encoding across a sequence of data items + * residing within device-accessible memory. + */ + +#pragma once + +#include +#include +#include +#include +#include + +#include + +#include + +CUB_NAMESPACE_BEGIN + + +/** + * @brief DeviceRunLengthEncode provides device-wide, parallel operations for + * demarcating "runs" of same-valued items within a sequence residing + * within device-accessible memory. ![](run_length_encode_logo.png) + * @ingroup SingleModule + * + * @par Overview + * A *run-length encoding* + * computes a simple compressed representation of a sequence of input elements + * such that each maximal "run" of consecutive same-valued data items is + * encoded as a single data value along with a count of the elements in that + * run. + * + * @par Usage Considerations + * @cdp_class{DeviceRunLengthEncode} + * + * @par Performance + * @linear_performance{run-length encode} + * + * @par + * The following chart illustrates DeviceRunLengthEncode::RunLengthEncode + * performance across different CUDA architectures for `int32` items. + * Segments have lengths uniformly sampled from `[1, 1000]`. + * + * @image html rle_int32_len_500.png + * + * @par + * @plots_below + */ +struct DeviceRunLengthEncode +{ + /** + * @brief Computes a run-length encoding of the sequence \p d_in. + * + * @par + * - For the *i*th run encountered, the first key of the run and + * its length are written to `d_unique_out[i]` and `d_counts_out[i]`, + * respectively. + * - The total number of runs encountered is written to `d_num_runs_out`. + * - The `==` equality operator is used to determine whether values are + * equivalent + * - In-place operations are not supported. There must be no overlap between + * any of the provided ranges: + * - `[d_unique_out, d_unique_out + *d_num_runs_out)` + * - `[d_counts_out, d_counts_out + *d_num_runs_out)` + * - `[d_num_runs_out, d_num_runs_out + 1)` + * - `[d_in, d_in + num_items)` + * - @devicestorage + * + * @par Performance + * The following charts illustrate saturated encode performance across + * different CUDA architectures for `int32` and `int64` items, respectively. + * Segments have lengths uniformly sampled from [1,1000]. + * + * @image html rle_int32_len_500.png + * @image html rle_int64_len_500.png + * + * @par + * The following charts are similar, but with segment lengths uniformly + * sampled from [1,10]: + * + * @image html rle_int32_len_5.png + * @image html rle_int64_len_5.png + * + * @par Snippet + * The code snippet below illustrates the run-length encoding of a sequence + * of `int` values. + * @par + * @code + * #include + * // or equivalently + * + * // Declare, allocate, and initialize device-accessible pointers for + * // input and output + * int num_items; // e.g., 8 + * int *d_in; // e.g., [0, 2, 2, 9, 5, 5, 5, 8] + * int *d_unique_out; // e.g., [ , , , , , , , ] + * int *d_counts_out; // e.g., [ , , , , , , , ] + * int *d_num_runs_out; // e.g., [ ] + * ... + * + * // Determine temporary device storage requirements + * void *d_temp_storage = NULL; + * size_t temp_storage_bytes = 0; + * cub::DeviceRunLengthEncode::Encode( + * d_temp_storage, temp_storage_bytes, + * d_in, d_unique_out, d_counts_out, d_num_runs_out, num_items); + * + * // Allocate temporary storage + * cudaMalloc(&d_temp_storage, temp_storage_bytes); + * + * // Run encoding + * cub::DeviceRunLengthEncode::Encode( + * d_temp_storage, temp_storage_bytes, + * d_in, d_unique_out, d_counts_out, d_num_runs_out, num_items); + * + * // d_unique_out <-- [0, 2, 9, 5, 8] + * // d_counts_out <-- [1, 2, 1, 3, 1] + * // d_num_runs_out <-- [5] + * @endcode + * + * @tparam InputIteratorT + * **[inferred]** Random-access input iterator type for reading input + * items \iterator + * + * @tparam UniqueOutputIteratorT + * **[inferred]** Random-access output iterator type for writing unique + * output items \iterator + * + * @tparam LengthsOutputIteratorT + * **[inferred]** Random-access output iterator type for writing output + * counts \iterator + * + * @tparam NumRunsOutputIteratorT + * **[inferred]** Output iterator type for recording the number of runs + * encountered \iterator + * + * @param[in] d_temp_storage + * Device-accessible allocation of temporary storage. When `nullptr`, the + * required allocation size is written to `temp_storage_bytes` and no work + * is done. + * + * @param[in,out] temp_storage_bytes + * Reference to size in bytes of `d_temp_storage` allocation + * + * @param[in] d_in + * Pointer to the input sequence of keys + * + * @param[out] d_unique_out + * Pointer to the output sequence of unique keys (one key per run) + * + * @param[out] d_counts_out + * Pointer to the output sequence of run-lengths (one count per run) + * + * @param[out] d_num_runs_out + * Pointer to total number of runs + * + * @param[in] num_items + * Total number of associated key+value pairs (i.e., the length of + * `d_in_keys` and `d_in_values`) + * + * @param[in] stream + * **[optional]** CUDA stream to launch kernels within. + * Default is stream0. + */ + template + CUB_RUNTIME_FUNCTION __forceinline__ static cudaError_t + Encode(void *d_temp_storage, + size_t &temp_storage_bytes, + InputIteratorT d_in, + UniqueOutputIteratorT d_unique_out, + LengthsOutputIteratorT d_counts_out, + NumRunsOutputIteratorT d_num_runs_out, + int num_items, + cudaStream_t stream = 0) + { + using offset_t = int; // Signed integer type for global offsets + using equality_op = Equality; // Default == operator + using reduction_op = cub::Sum; // Value reduction operator + + // The lengths output value type + using length_t = + cub::detail::non_void_value_t; + + // Generator type for providing 1s values for run-length reduction + using lengths_input_iterator_t = ConstantInputIterator; + + using accum_t = detail::accumulator_t; + + using key_t = + cub::detail::non_void_value_t>; + + using policy_t = detail::device_run_length_encode_policy_hub; + + return DispatchReduceByKey::Dispatch(d_temp_storage, + temp_storage_bytes, + d_in, + d_unique_out, + lengths_input_iterator_t((length_t)1), + d_counts_out, + d_num_runs_out, + equality_op(), + reduction_op(), + num_items, + stream); + } + + template + CUB_DETAIL_RUNTIME_DEBUG_SYNC_IS_NOT_SUPPORTED + CUB_RUNTIME_FUNCTION __forceinline__ static cudaError_t + Encode(void *d_temp_storage, + size_t &temp_storage_bytes, + InputIteratorT d_in, + UniqueOutputIteratorT d_unique_out, + LengthsOutputIteratorT d_counts_out, + NumRunsOutputIteratorT d_num_runs_out, + int num_items, + cudaStream_t stream, + bool debug_synchronous) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + + return Encode(d_temp_storage, + temp_storage_bytes, + d_in, + d_unique_out, + d_counts_out, + d_num_runs_out, + num_items, + stream); + } + + /** + * @brief Enumerates the starting offsets and lengths of all non-trivial runs + * (of `length > 1`) of same-valued keys in the sequence `d_in`. + * + * @par + * - For the *i*th non-trivial run, the run's starting offset and + * its length are written to `d_offsets_out[i]` and `d_lengths_out[i]`, + * respectively. + * - The total number of runs encountered is written to `d_num_runs_out`. + * - The `==` equality operator is used to determine whether values are + * equivalent + * - In-place operations are not supported. There must be no overlap between + * any of the provided ranges: + * - `[d_offsets_out, d_offsets_out + *d_num_runs_out)` + * - `[d_lengths_out, d_lengths_out + *d_num_runs_out)` + * - `[d_num_runs_out, d_num_runs_out + 1)` + * - `[d_in, d_in + num_items)` + * - @devicestorage + * + * @par Performance + * + * @par Snippet + * The code snippet below illustrates the identification of non-trivial runs + * within a sequence of `int` values. + * @par + * @code + * #include + * // or equivalently + * + * // Declare, allocate, and initialize device-accessible pointers + * // for input and output + * int num_items; // e.g., 8 + * int *d_in; // e.g., [0, 2, 2, 9, 5, 5, 5, 8] + * int *d_offsets_out; // e.g., [ , , , , , , , ] + * int *d_lengths_out; // e.g., [ , , , , , , , ] + * int *d_num_runs_out; // e.g., [ ] + * ... + * + * // Determine temporary device storage requirements + * void *d_temp_storage = NULL; + * size_t temp_storage_bytes = 0; + * cub::DeviceRunLengthEncode::NonTrivialRuns( + * d_temp_storage, temp_storage_bytes, + * d_in, d_offsets_out, d_lengths_out, d_num_runs_out, num_items); + * + * // Allocate temporary storage + * cudaMalloc(&d_temp_storage, temp_storage_bytes); + * + * // Run encoding + * cub::DeviceRunLengthEncode::NonTrivialRuns( + * d_temp_storage, temp_storage_bytes, + * d_in, d_offsets_out, d_lengths_out, d_num_runs_out, num_items); + * + * // d_offsets_out <-- [1, 4] + * // d_lengths_out <-- [2, 3] + * // d_num_runs_out <-- [2] + * @endcode + * + * @tparam InputIteratorT + * **[inferred]** Random-access input iterator type for reading input + * items \iterator + * + * @tparam OffsetsOutputIteratorT + * **[inferred]** Random-access output iterator type for writing run-offset + * values \iterator + * + * @tparam LengthsOutputIteratorT + * **[inferred]** Random-access output iterator type for writing run-length + * values \iterator + * + * @tparam NumRunsOutputIteratorT + * **[inferred]** Output iterator type for recording the number of runs + * encountered \iterator + * + * @param[in] d_temp_storage + * Device-accessible allocation of temporary storage. When `nullptr`, the + * required allocation size is written to `temp_storage_bytes` and no work + * is done. + * + * @param[in,out] temp_storage_bytes + * Reference to size in bytes of `d_temp_storage` allocation + * + * @param[in] d_in + * Pointer to input sequence of data items + * + * @param[out] d_offsets_out + * Pointer to output sequence of run-offsets + * (one offset per non-trivial run) + * + * @param[out] d_lengths_out + * Pointer to output sequence of run-lengths + * (one count per non-trivial run) + * + * @param[out] d_num_runs_out + * Pointer to total number of runs (i.e., length of `d_offsets_out`) + * + * @param[in] num_items + * Total number of associated key+value pairs (i.e., the length of + * `d_in_keys` and `d_in_values`) + * + * @param[in] stream + * **[optional]** CUDA stream to launch kernels within. + * Default is stream0. + */ + template + CUB_RUNTIME_FUNCTION __forceinline__ static cudaError_t + NonTrivialRuns(void *d_temp_storage, + size_t &temp_storage_bytes, + InputIteratorT d_in, + OffsetsOutputIteratorT d_offsets_out, + LengthsOutputIteratorT d_lengths_out, + NumRunsOutputIteratorT d_num_runs_out, + int num_items, + cudaStream_t stream = 0) + { + using OffsetT = int; // Signed integer type for global offsets + using EqualityOp = Equality; // Default == operator + + return DeviceRleDispatch::Dispatch(d_temp_storage, + temp_storage_bytes, + d_in, + d_offsets_out, + d_lengths_out, + d_num_runs_out, + EqualityOp(), + num_items, + stream); + } + + template + CUB_DETAIL_RUNTIME_DEBUG_SYNC_IS_NOT_SUPPORTED + CUB_RUNTIME_FUNCTION __forceinline__ static cudaError_t + NonTrivialRuns(void *d_temp_storage, + size_t &temp_storage_bytes, + InputIteratorT d_in, + OffsetsOutputIteratorT d_offsets_out, + LengthsOutputIteratorT d_lengths_out, + NumRunsOutputIteratorT d_num_runs_out, + int num_items, + cudaStream_t stream, + bool debug_synchronous) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + + return NonTrivialRuns(d_temp_storage, + temp_storage_bytes, + d_in, + d_offsets_out, + d_lengths_out, + d_num_runs_out, + num_items, + stream); + } +}; + +CUB_NAMESPACE_END + + diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/device/device_scan.cuh b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/device/device_scan.cuh new file mode 100644 index 0000000000000000000000000000000000000000..20cb8ba872fe4db1430236e35080961269736276 --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/device/device_scan.cuh @@ -0,0 +1,2268 @@ +/****************************************************************************** + * Copyright (c) 2011, Duane Merrill. All rights reserved. + * Copyright (c) 2011-2022, NVIDIA CORPORATION. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the NVIDIA CORPORATION nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ******************************************************************************/ + +/** + * @file cub::DeviceScan provides device-wide, parallel operations for + * computing a prefix scan across a sequence of data items residing + * within device-accessible memory. + */ + +#pragma once + +#include +#include +#include +#include +#include + +CUB_NAMESPACE_BEGIN + + +/** + * @brief DeviceScan provides device-wide, parallel operations for computing a + * prefix scan across a sequence of data items residing within + * device-accessible memory. ![](device_scan.png) + * + * @ingroup SingleModule + * + * @par Overview + * Given a sequence of input elements and a binary reduction operator, a + * [*prefix scan*](http://en.wikipedia.org/wiki/Prefix_sum) produces an output + * sequence where each element is computed to be the reduction of the elements + * occurring earlier in the input sequence. *Prefix sum* connotes a prefix scan + * with the addition operator. The term *inclusive* indicates that the + * *i*th output reduction incorporates the *i*th input. + * The term *exclusive* indicates the *i*th input is not + * incorporated into the *i*th output reduction. When the input and + * output sequences are the same, the scan is performed in-place. + * + * @par + * As of CUB 1.0.1 (2013), CUB's device-wide scan APIs have implemented our + * *"decoupled look-back"* algorithm for performing global prefix scan with + * only a single pass through the input data, as described in our 2016 technical + * report [1]. The central idea is to leverage a small, constant factor of + * redundant work in order to overlap the latencies of global prefix + * propagation with local computation. As such, our algorithm requires only + * ~2*n* data movement (*n* inputs are read, *n* outputs are written), and + * typically proceeds at "memcpy" speeds. Our algorithm supports inplace + * operations. + * + * @par + * [1] [Duane Merrill and Michael Garland. "Single-pass Parallel Prefix Scan with Decoupled Look-back", NVIDIA Technical Report NVR-2016-002, 2016.](https://research.nvidia.com/publication/single-pass-parallel-prefix-scan-decoupled-look-back) + * + * @par Usage Considerations + * @cdp_class{DeviceScan} + * + * @par Performance + * @linear_performance{prefix scan} + * + * @par + * The following chart illustrates DeviceScan::ExclusiveSum performance across + * different CUDA architectures for `int32` keys. + * @plots_below + * + * @image html scan_int32.png + * + */ +struct DeviceScan +{ + /******************************************************************//** + * \name Exclusive scans + *********************************************************************/ + //@{ + + /** + * @brief Computes a device-wide exclusive prefix sum. The value of `0` is + * applied as the initial value, and is assigned to `*d_out`. + * + * @par + * - Supports non-commutative sum operators. + * - Results are not deterministic for pseudo-associative operators (e.g., + * addition of floating-point types). Results for pseudo-associative + * operators may vary from run to run. Additional details can be found in + * the [decoupled look-back] description. + * - When `d_in` and `d_out` are equal, the scan is performed in-place. The + * range `[d_in, d_in + num_items)` and `[d_out, d_out + num_items)` + * shall not overlap in any other way. + * - @devicestorage + * + * @par Performance + * The following charts illustrate saturated exclusive sum performance across + * different CUDA architectures for `int32` and `int64` items, respectively. + * + * @image html scan_int32.png + * @image html scan_int64.png + * + * @par Snippet + * The code snippet below illustrates the exclusive prefix sum of an `int` + * device vector. + * @par + * @code + * #include // or equivalently + * + * // Declare, allocate, and initialize device-accessible pointers for + * // input and output + * int num_items; // e.g., 7 + * int *d_in; // e.g., [8, 6, 7, 5, 3, 0, 9] + * int *d_out; // e.g., [ , , , , , , ] + * ... + * + * // Determine temporary device storage requirements + * void *d_temp_storage = NULL; + * size_t temp_storage_bytes = 0; + * cub::DeviceScan::ExclusiveSum( + * d_temp_storage, temp_storage_bytes, + * d_in, d_out, num_items); + * + * // Allocate temporary storage + * cudaMalloc(&d_temp_storage, temp_storage_bytes); + * + * // Run exclusive prefix sum + * cub::DeviceScan::ExclusiveSum( + * d_temp_storage, temp_storage_bytes, + * d_in, d_out, num_items); + * + * // d_out <-- [0, 8, 14, 21, 26, 29, 29] + * + * @endcode + * + * @tparam InputIteratorT + * **[inferred]** Random-access input iterator type for reading scan + * inputs \iterator + * + * @tparam OutputIteratorT + * **[inferred]** Random-access output iterator type for writing scan + * outputs \iterator + * + * @param[in] d_temp_storage + * Device-accessible allocation of temporary storage. When `nullptr`, the + * required allocation size is written to `temp_storage_bytes` and no + * work is done. + * + * @param[in,out] temp_storage_bytes + * Reference to size in bytes of `d_temp_storage` allocation + * + * @param[in] d_in + * Random-access iterator to the input sequence of data items + * + * @param[out] d_out + * Random-access iterator to the output sequence of data items + * + * @param[in] num_items + * Total number of input items (i.e., the length of `d_in`) + * + * @param[in] stream + * **[optional]** CUDA stream to launch kernels within. + * Default is stream0. + * + * [decoupled look-back]: https://research.nvidia.com/publication/single-pass-parallel-prefix-scan-decoupled-look-back + */ + template + CUB_RUNTIME_FUNCTION static cudaError_t + ExclusiveSum(void *d_temp_storage, + size_t &temp_storage_bytes, + InputIteratorT d_in, + OutputIteratorT d_out, + int num_items, + cudaStream_t stream = 0) + { + // Signed integer type for global offsets + using OffsetT = int; + using InitT = cub::detail::value_t; + + // Initial value + InitT init_value{}; + + return DispatchScan< + InputIteratorT, OutputIteratorT, Sum, detail::InputValue, + OffsetT>::Dispatch(d_temp_storage, temp_storage_bytes, d_in, d_out, + Sum(), detail::InputValue(init_value), + num_items, stream); + } + + template + CUB_DETAIL_RUNTIME_DEBUG_SYNC_IS_NOT_SUPPORTED + CUB_RUNTIME_FUNCTION static cudaError_t + ExclusiveSum(void *d_temp_storage, + size_t &temp_storage_bytes, + InputIteratorT d_in, + OutputIteratorT d_out, + int num_items, + cudaStream_t stream, + bool debug_synchronous) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + + return ExclusiveSum(d_temp_storage, + temp_storage_bytes, + d_in, + d_out, + num_items, + stream); + } + + /** + * @brief Computes a device-wide exclusive prefix sum in-place. The value of + * `0` is applied as the initial value, and is assigned to `*d_data`. + * + * @par + * - Supports non-commutative sum operators. + * - Results are not deterministic for pseudo-associative operators (e.g., + * addition of floating-point types). Results for pseudo-associative + * operators may vary from run to run. Additional details can be found in + * the [decoupled look-back] description. + * - @devicestorage + * + * @par Performance + * The following charts illustrate saturated exclusive sum performance across + * different CUDA architectures for `int32` and `int64` items, respectively. + * + * @image html scan_int32.png + * @image html scan_int64.png + * + * @par Snippet + * The code snippet below illustrates the exclusive prefix sum of an `int` + * device vector. + * @par + * @code + * #include // or equivalently + * + * // Declare, allocate, and initialize device-accessible pointers for + * // input and output + * int num_items; // e.g., 7 + * int *d_data; // e.g., [8, 6, 7, 5, 3, 0, 9] + * ... + * + * // Determine temporary device storage requirements + * void *d_temp_storage = NULL; + * size_t temp_storage_bytes = 0; + * cub::DeviceScan::ExclusiveSum( + * d_temp_storage, temp_storage_bytes, + * d_data, num_items); + * + * // Allocate temporary storage + * cudaMalloc(&d_temp_storage, temp_storage_bytes); + * + * // Run exclusive prefix sum + * cub::DeviceScan::ExclusiveSum( + * d_temp_storage, temp_storage_bytes, + * d_data, num_items); + * + * // d_data <-- [0, 8, 14, 21, 26, 29, 29] + * + * @endcode + * + * @tparam IteratorT + * **[inferred]** Random-access iterator type for reading scan + * inputs and wrigin scan outputs + * + * @param[in] d_temp_storage + * Device-accessible allocation of temporary storage. When `nullptr`, the + * required allocation size is written to `temp_storage_bytes` and no + * work is done. + * + * @param[in,out] temp_storage_bytes + * Reference to size in bytes of `d_temp_storage` allocation + * + * @param[in,out] d_data + * Random-access iterator to the sequence of data items + * + * @param[in] num_items + * Total number of input items (i.e., the length of `d_in`) + * + * @param[in] stream + * **[optional]** CUDA stream to launch kernels within. + * Default is stream0. + * + * [decoupled look-back]: https://research.nvidia.com/publication/single-pass-parallel-prefix-scan-decoupled-look-back + */ + template + CUB_RUNTIME_FUNCTION static cudaError_t + ExclusiveSum(void *d_temp_storage, + size_t &temp_storage_bytes, + IteratorT d_data, + int num_items, + cudaStream_t stream = 0) + { + return ExclusiveSum(d_temp_storage, + temp_storage_bytes, + d_data, + d_data, + num_items, + stream); + } + + template + CUB_DETAIL_RUNTIME_DEBUG_SYNC_IS_NOT_SUPPORTED + CUB_RUNTIME_FUNCTION static cudaError_t + ExclusiveSum(void *d_temp_storage, + size_t &temp_storage_bytes, + IteratorT d_data, + int num_items, + cudaStream_t stream, + bool debug_synchronous) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + + return ExclusiveSum(d_temp_storage, + temp_storage_bytes, + d_data, + num_items, + stream); + } + + /** + * @brief Computes a device-wide exclusive prefix scan using the specified + * binary `scan_op` functor. The `init_value` value is applied as + * the initial value, and is assigned to `*d_out`. + * + * @par + * - Supports non-commutative scan operators. + * - Results are not deterministic for pseudo-associative operators (e.g., + * addition of floating-point types). Results for pseudo-associative + * operators may vary from run to run. Additional details can be found in + * the [decoupled look-back] description. + * - When `d_in` and `d_out` are equal, the scan is performed in-place. The + * range `[d_in, d_in + num_items)` and `[d_out, d_out + num_items)` + * shall not overlap in any other way. + * - @devicestorage + * + * @par Snippet + * The code snippet below illustrates the exclusive prefix min-scan of an + * `int` device vector + * @par + * @code + * #include // or equivalently + * #include // for INT_MAX + * + * // CustomMin functor + * struct CustomMin + * { + * template + * CUB_RUNTIME_FUNCTION __forceinline__ + * T operator()(const T &a, const T &b) const { + * return (b < a) ? b : a; + * } + * }; + * + * // Declare, allocate, and initialize device-accessible pointers for + * // input and output + * int num_items; // e.g., 7 + * int *d_in; // e.g., [8, 6, 7, 5, 3, 0, 9] + * int *d_out; // e.g., [ , , , , , , ] + * CustomMin min_op; + * ... + * + * // Determine temporary device storage requirements for exclusive + * // prefix scan + * void *d_temp_storage = NULL; + * size_t temp_storage_bytes = 0; + * cub::DeviceScan::ExclusiveScan( + * d_temp_storage, temp_storage_bytes, + * d_in, d_out, min_op, (int) INT_MAX, num_items); + * + * // Allocate temporary storage for exclusive prefix scan + * cudaMalloc(&d_temp_storage, temp_storage_bytes); + * + * // Run exclusive prefix min-scan + * cub::DeviceScan::ExclusiveScan( + * d_temp_storage, temp_storage_bytes, + * d_in, d_out, min_op, (int) INT_MAX, num_items); + * + * // d_out <-- [2147483647, 8, 6, 6, 5, 3, 0] + * + * @endcode + * + * @tparam InputIteratorT + * **[inferred]** Random-access input iterator type for reading scan + * inputs \iterator + * + * @tparam OutputIteratorT + * **[inferred]** Random-access output iterator type for writing scan + * outputs \iterator + * + * @tparam ScanOp + * **[inferred]** Binary scan functor type having member + * `T operator()(const T &a, const T &b)` + * + * @tparam InitValueT + * **[inferred]** Type of the `init_value` used Binary scan functor type + * having member `T operator()(const T &a, const T &b)` + * + * @param[in] d_temp_storage + * Device-accessible allocation of temporary storage. When `nullptr`, the + * required allocation size is written to `temp_storage_bytes` and no + * work is done. + * + * @param[in,out] temp_storage_bytes + * Reference to size in bytes of `d_temp_storage` allocation + * + * @param[in] d_in + * Random-access iterator to the input sequence of data items + * + * @param[out] d_out + * Random-access iterator to the output sequence of data items + * + * @param[in] scan_op + * Binary scan functor + * + * @param[in] init_value + * Initial value to seed the exclusive scan (and is assigned to *d_out) + * + * @param[in] num_items + * Total number of input items (i.e., the length of \p d_in) + * + * @param[in] stream + * **[optional]** CUDA stream to launch kernels within. Default is + * stream0. + * + * [decoupled look-back]: https://research.nvidia.com/publication/single-pass-parallel-prefix-scan-decoupled-look-back + */ + template + CUB_RUNTIME_FUNCTION static cudaError_t + ExclusiveScan(void *d_temp_storage, + size_t &temp_storage_bytes, + InputIteratorT d_in, + OutputIteratorT d_out, + ScanOpT scan_op, + InitValueT init_value, + int num_items, + cudaStream_t stream = 0) + { + // Signed integer type for global offsets + using OffsetT = int ; + + return DispatchScan, + OffsetT>::Dispatch(d_temp_storage, + temp_storage_bytes, + d_in, + d_out, + scan_op, + detail::InputValue( + init_value), + num_items, + stream); + } + + template + CUB_DETAIL_RUNTIME_DEBUG_SYNC_IS_NOT_SUPPORTED + CUB_RUNTIME_FUNCTION static cudaError_t + ExclusiveScan(void *d_temp_storage, + size_t &temp_storage_bytes, + InputIteratorT d_in, + OutputIteratorT d_out, + ScanOpT scan_op, + InitValueT init_value, + int num_items, + cudaStream_t stream, + bool debug_synchronous) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + + return ExclusiveScan( + d_temp_storage, + temp_storage_bytes, + d_in, + d_out, + scan_op, + init_value, + num_items, + stream); + } + + /** + * @brief Computes a device-wide exclusive prefix scan using the specified + * binary `scan_op` functor. The `init_value` value is applied as + * the initial value, and is assigned to `*d_data`. + * + * @par + * - Supports non-commutative scan operators. + * - Results are not deterministic for pseudo-associative operators (e.g., + * addition of floating-point types). Results for pseudo-associative + * operators may vary from run to run. Additional details can be found in + * the [decoupled look-back] description. + * - @devicestorage + * + * @par Snippet + * The code snippet below illustrates the exclusive prefix min-scan of an + * `int` device vector + * @par + * @code + * #include // or equivalently + * #include // for INT_MAX + * + * // CustomMin functor + * struct CustomMin + * { + * template + * CUB_RUNTIME_FUNCTION __forceinline__ + * T operator()(const T &a, const T &b) const { + * return (b < a) ? b : a; + * } + * }; + * + * // Declare, allocate, and initialize device-accessible pointers for + * // input and output + * int num_items; // e.g., 7 + * int *d_data; // e.g., [8, 6, 7, 5, 3, 0, 9] + * CustomMin min_op; + * ... + * + * // Determine temporary device storage requirements for exclusive + * // prefix scan + * void *d_temp_storage = NULL; + * size_t temp_storage_bytes = 0; + * cub::DeviceScan::ExclusiveScan( + * d_temp_storage, temp_storage_bytes, + * d_data, min_op, (int) INT_MAX, num_items); + * + * // Allocate temporary storage for exclusive prefix scan + * cudaMalloc(&d_temp_storage, temp_storage_bytes); + * + * // Run exclusive prefix min-scan + * cub::DeviceScan::ExclusiveScan( + * d_temp_storage, temp_storage_bytes, + * d_data, min_op, (int) INT_MAX, num_items); + * + * // d_data <-- [2147483647, 8, 6, 6, 5, 3, 0] + * + * @endcode + * + * @tparam IteratorT + * **[inferred]** Random-access input iterator type for reading scan + * inputs and writing scan outputs + * + * @tparam ScanOp + * **[inferred]** Binary scan functor type having member + * `T operator()(const T &a, const T &b)` + * + * @tparam InitValueT + * **[inferred]** Type of the `init_value` used Binary scan functor type + * having member `T operator()(const T &a, const T &b)` + * + * @param[in] d_temp_storage + * Device-accessible allocation of temporary storage. When `nullptr`, the + * required allocation size is written to `temp_storage_bytes` and no + * work is done. + * + * @param[in,out] temp_storage_bytes + * Reference to size in bytes of `d_temp_storage` allocation + * + * @param[in,out] d_data + * Random-access iterator to the sequence of data items + * + * @param[in] scan_op + * Binary scan functor + * + * @param[in] init_value + * Initial value to seed the exclusive scan (and is assigned to *d_out) + * + * @param[in] num_items + * Total number of input items (i.e., the length of \p d_in) + * + * @param[in] stream + * **[optional]** CUDA stream to launch kernels within. Default is + * stream0. + * + * [decoupled look-back]: https://research.nvidia.com/publication/single-pass-parallel-prefix-scan-decoupled-look-back + */ + template + CUB_RUNTIME_FUNCTION static cudaError_t + ExclusiveScan(void *d_temp_storage, + size_t &temp_storage_bytes, + IteratorT d_data, + ScanOpT scan_op, + InitValueT init_value, + int num_items, + cudaStream_t stream = 0) + { + return ExclusiveScan(d_temp_storage, + temp_storage_bytes, + d_data, + d_data, + scan_op, + init_value, + num_items, + stream); + } + + template + CUB_DETAIL_RUNTIME_DEBUG_SYNC_IS_NOT_SUPPORTED + CUB_RUNTIME_FUNCTION static cudaError_t + ExclusiveScan(void *d_temp_storage, + size_t &temp_storage_bytes, + IteratorT d_data, + ScanOpT scan_op, + InitValueT init_value, + int num_items, + cudaStream_t stream, + bool debug_synchronous) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + + return ExclusiveScan(d_temp_storage, + temp_storage_bytes, + d_data, + scan_op, + init_value, + num_items, + stream); + } + + /** + * @brief Computes a device-wide exclusive prefix scan using the specified + * binary `scan_op` functor. The `init_value` value is provided as + * a future value. + * + * @par + * - Supports non-commutative scan operators. + * - Results are not deterministic for pseudo-associative operators (e.g., + * addition of floating-point types). Results for pseudo-associative + * operators may vary from run to run. Additional details can be found in + * the [decoupled look-back] description. + * - When `d_in` and `d_out` are equal, the scan is performed in-place. The + * range `[d_in, d_in + num_items)` and `[d_out, d_out + num_items)` + * shall not overlap in any other way. + * - @devicestorage + * + * @par Snippet + * The code snippet below illustrates the exclusive prefix min-scan of an + * `int` device vector + * @par + * @code + * #include // or equivalently + * #include // for INT_MAX + * + * // CustomMin functor + * struct CustomMin + * { + * template + * CUB_RUNTIME_FUNCTION __forceinline__ + * T operator()(const T &a, const T &b) const { + * return (b < a) ? b : a; + * } + * }; + * + * // Declare, allocate, and initialize device-accessible pointers for + * // input and output + * int num_items; // e.g., 7 + * int *d_in; // e.g., [8, 6, 7, 5, 3, 0, 9] + * int *d_out; // e.g., [ , , , , , , ] + * int *d_init_iter; // e.g., INT_MAX + * CustomMin min_op; + * + * auto future_init_value = + * cub::FutureValue(d_init_iter); + * + * ... + * + * // Determine temporary device storage requirements for exclusive + * // prefix scan + * void *d_temp_storage = NULL; + * size_t temp_storage_bytes = 0; + * cub::DeviceScan::ExclusiveScan( + * d_temp_storage, temp_storage_bytes, + * d_in, d_out, min_op, future_init_value, num_items); + * + * // Allocate temporary storage for exclusive prefix scan + * cudaMalloc(&d_temp_storage, temp_storage_bytes); + * + * // Run exclusive prefix min-scan + * cub::DeviceScan::ExclusiveScan( + * d_temp_storage, temp_storage_bytes, + * d_in, d_out, min_op, future_init_value, num_items); + * + * // d_out <-- [2147483647, 8, 6, 6, 5, 3, 0] + * + * @endcode + * + * @tparam InputIteratorT + * **[inferred]** Random-access input iterator type for reading scan + * inputs \iterator + * + * @tparam OutputIteratorT + * **[inferred]** Random-access output iterator type for writing scan + * outputs \iterator + * + * @tparam ScanOp + * **[inferred]** Binary scan functor type having member + * `T operator()(const T &a, const T &b)` + * + * @tparam InitValueT + * **[inferred]** Type of the `init_value` used Binary scan functor type + * having member `T operator()(const T &a, const T &b)` + * + * @param[in] d_temp_storage + * Device-accessible allocation of temporary storage. When `nullptr`, the + * required allocation size is written to `temp_storage_bytes` and no work + * is done. + * + * @param[in,out] temp_storage_bytes + * Reference to size in bytes of \p d_temp_storage allocation + * + * @param[in] d_in + * Pointer to the input sequence of data items + * + * @param[out] d_out + * Pointer to the output sequence of data items + * + * @param[in] scan_op + * Binary scan functor + * + * @param[in] init_value + * Initial value to seed the exclusive scan (and is assigned to `*d_out`) + * + * @param[in] num_items + * Total number of input items (i.e., the length of `d_in`) + * + * @param[in] stream + * **[optional]** CUDA stream to launch kernels within. + * Default is stream0. + * + * [decoupled look-back]: https://research.nvidia.com/publication/single-pass-parallel-prefix-scan-decoupled-look-back + */ + template + CUB_RUNTIME_FUNCTION static cudaError_t + ExclusiveScan(void *d_temp_storage, + size_t &temp_storage_bytes, + InputIteratorT d_in, + OutputIteratorT d_out, + ScanOpT scan_op, + FutureValue init_value, + int num_items, + cudaStream_t stream = 0) + { + // Signed integer type for global offsets + using OffsetT = int; + + return DispatchScan, + OffsetT>::Dispatch(d_temp_storage, + temp_storage_bytes, + d_in, + d_out, + scan_op, + detail::InputValue( + init_value), + num_items, + stream); + } + + template + CUB_DETAIL_RUNTIME_DEBUG_SYNC_IS_NOT_SUPPORTED + CUB_RUNTIME_FUNCTION static cudaError_t + ExclusiveScan(void *d_temp_storage, + size_t &temp_storage_bytes, + InputIteratorT d_in, + OutputIteratorT d_out, + ScanOpT scan_op, + FutureValue init_value, + int num_items, + cudaStream_t stream, + bool debug_synchronous) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + + return ExclusiveScan(d_temp_storage, + temp_storage_bytes, + d_in, + d_out, + scan_op, + init_value, + num_items, + stream); + } + + /** + * @brief Computes a device-wide exclusive prefix scan using the specified + * binary `scan_op` functor. The `init_value` value is provided as + * a future value. + * + * @par + * - Supports non-commutative scan operators. + * - Results are not deterministic for pseudo-associative operators (e.g., + * addition of floating-point types). Results for pseudo-associative + * operators may vary from run to run. Additional details can be found in + * the [decoupled look-back] description. + * - @devicestorage + * + * @par Snippet + * The code snippet below illustrates the exclusive prefix min-scan of an + * `int` device vector + * @par + * @code + * #include // or equivalently + * #include // for INT_MAX + * + * // CustomMin functor + * struct CustomMin + * { + * template + * CUB_RUNTIME_FUNCTION __forceinline__ + * T operator()(const T &a, const T &b) const { + * return (b < a) ? b : a; + * } + * }; + * + * // Declare, allocate, and initialize device-accessible pointers for + * // input and output + * int num_items; // e.g., 7 + * int *d_data; // e.g., [8, 6, 7, 5, 3, 0, 9] + * int *d_init_iter; // e.g., INT_MAX + * CustomMin min_op; + * + * auto future_init_value = + * cub::FutureValue(d_init_iter); + * + * ... + * + * // Determine temporary device storage requirements for exclusive + * // prefix scan + * void *d_temp_storage = NULL; + * size_t temp_storage_bytes = 0; + * cub::DeviceScan::ExclusiveScan( + * d_temp_storage, temp_storage_bytes, + * d_data, min_op, future_init_value, num_items); + * + * // Allocate temporary storage for exclusive prefix scan + * cudaMalloc(&d_temp_storage, temp_storage_bytes); + * + * // Run exclusive prefix min-scan + * cub::DeviceScan::ExclusiveScan( + * d_temp_storage, temp_storage_bytes, + * d_data, min_op, future_init_value, num_items); + * + * // d_data <-- [2147483647, 8, 6, 6, 5, 3, 0] + * + * @endcode + * + * @tparam IteratorT + * **[inferred]** Random-access input iterator type for reading scan + * inputs and writing scan outputs + * + * @tparam ScanOp + * **[inferred]** Binary scan functor type having member + * `T operator()(const T &a, const T &b)` + * + * @tparam InitValueT + * **[inferred]** Type of the `init_value` used Binary scan functor type + * having member `T operator()(const T &a, const T &b)` + * + * @param[in] d_temp_storage + * Device-accessible allocation of temporary storage. When `nullptr`, the + * required allocation size is written to `temp_storage_bytes` and no work + * is done. + * + * @param[in,out] temp_storage_bytes + * Reference to size in bytes of \p d_temp_storage allocation + * + * @param[in,out] d_data + * Pointer to the sequence of data items + * + * @param[in] scan_op + * Binary scan functor + * + * @param[in] init_value + * Initial value to seed the exclusive scan (and is assigned to `*d_out`) + * + * @param[in] num_items + * Total number of input items (i.e., the length of `d_in`) + * + * @param[in] stream + * **[optional]** CUDA stream to launch kernels within. + * Default is stream0. + * + * [decoupled look-back]: https://research.nvidia.com/publication/single-pass-parallel-prefix-scan-decoupled-look-back + */ + template + CUB_RUNTIME_FUNCTION static cudaError_t + ExclusiveScan(void *d_temp_storage, + size_t &temp_storage_bytes, + IteratorT d_data, + ScanOpT scan_op, + FutureValue init_value, + int num_items, + cudaStream_t stream = 0) + { + return ExclusiveScan(d_temp_storage, + temp_storage_bytes, + d_data, + d_data, + scan_op, + init_value, + num_items, + stream); + } + + template + CUB_DETAIL_RUNTIME_DEBUG_SYNC_IS_NOT_SUPPORTED + CUB_RUNTIME_FUNCTION static cudaError_t + ExclusiveScan(void *d_temp_storage, + size_t &temp_storage_bytes, + IteratorT d_data, + ScanOpT scan_op, + FutureValue init_value, + int num_items, + cudaStream_t stream, + bool debug_synchronous) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + + return ExclusiveScan( + d_temp_storage, + temp_storage_bytes, + d_data, + scan_op, + init_value, + num_items, + stream); + } + + //@} end member group + /******************************************************************//** + * @name Inclusive scans + *********************************************************************/ + //@{ + + + /** + * @brief Computes a device-wide inclusive prefix sum. + * + * @par + * - Supports non-commutative sum operators. + * - Results are not deterministic for pseudo-associative operators (e.g., + * addition of floating-point types). Results for pseudo-associative + * operators may vary from run to run. Additional details can be found in + * the [decoupled look-back] description. + * - When `d_in` and `d_out` are equal, the scan is performed in-place. The + * range `[d_in, d_in + num_items)` and `[d_out, d_out + num_items)` + * shall not overlap in any other way. + * - @devicestorage + * + * @par Snippet + * The code snippet below illustrates the inclusive prefix sum of an `int` + * device vector. + * + * @par + * @code + * #include // or equivalently + * + * // Declare, allocate, and initialize device-accessible pointers for + * // input and output + * int num_items; // e.g., 7 + * int *d_in; // e.g., [8, 6, 7, 5, 3, 0, 9] + * int *d_out; // e.g., [ , , , , , , ] + * ... + * + * // Determine temporary device storage requirements for inclusive + * // prefix sum + * void *d_temp_storage = nullptr; + * size_t temp_storage_bytes = 0; + * cub::DeviceScan::InclusiveSum( + * d_temp_storage, temp_storage_bytes, + * d_in, d_out, num_items); + * + * // Allocate temporary storage for inclusive prefix sum + * cudaMalloc(&d_temp_storage, temp_storage_bytes); + * + * // Run inclusive prefix sum + * cub::DeviceScan::InclusiveSum( + * d_temp_storage, temp_storage_bytes, + * d_in, d_out, num_items); + * + * // d_out <-- [8, 14, 21, 26, 29, 29, 38] + * + * @endcode + * + * @tparam InputIteratorT + * **[inferred]** Random-access input iterator type for reading scan + * inputs \iterator + * + * @tparam OutputIteratorT + * **[inferred]** Random-access output iterator type for writing scan + * outputs \iterator + * + * @param[in] d_temp_storage + * Device-accessible allocation of temporary storage. When `nullptr`, the + * required allocation size is written to `temp_storage_bytes` and no + * work is done. + * + * @param[in,out] temp_storage_bytes + * Reference to size in bytes of `d_temp_storage` allocation + * + * @param[in] d_in + * Random-access iterator to the input sequence of data items + * + * @param[out] d_out + * Random-access iterator to the output sequence of data items + * + * @param[in] num_items + * Total number of input items (i.e., the length of `d_in`) + * + * @param[in] stream + * **[optional]** CUDA stream to launch kernels within. + * Default is stream0. + * + * [decoupled look-back]: https://research.nvidia.com/publication/single-pass-parallel-prefix-scan-decoupled-look-back + */ + template + CUB_RUNTIME_FUNCTION static cudaError_t + InclusiveSum(void *d_temp_storage, + size_t &temp_storage_bytes, + InputIteratorT d_in, + OutputIteratorT d_out, + int num_items, + cudaStream_t stream = 0) + { + // Signed integer type for global offsets + using OffsetT = int; + + return DispatchScan::Dispatch(d_temp_storage, + temp_storage_bytes, + d_in, + d_out, + Sum(), + NullType(), + num_items, + stream); + } + + template + CUB_DETAIL_RUNTIME_DEBUG_SYNC_IS_NOT_SUPPORTED + CUB_RUNTIME_FUNCTION static cudaError_t + InclusiveSum(void *d_temp_storage, + size_t &temp_storage_bytes, + InputIteratorT d_in, + OutputIteratorT d_out, + int num_items, + cudaStream_t stream, + bool debug_synchronous) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + + return InclusiveSum(d_temp_storage, + temp_storage_bytes, + d_in, + d_out, + num_items, + stream); + } + + /** + * @brief Computes a device-wide inclusive prefix sum in-place. + * + * @par + * - Supports non-commutative sum operators. + * - Results are not deterministic for pseudo-associative operators (e.g., + * addition of floating-point types). Results for pseudo-associative + * operators may vary from run to run. Additional details can be found in + * the [decoupled look-back] description. + * - @devicestorage + * + * @par Snippet + * The code snippet below illustrates the inclusive prefix sum of an `int` + * device vector. + * + * @par + * @code + * #include // or equivalently + * + * // Declare, allocate, and initialize device-accessible pointers for + * // input and output + * int num_items; // e.g., 7 + * int *d_data; // e.g., [8, 6, 7, 5, 3, 0, 9] + * ... + * + * // Determine temporary device storage requirements for inclusive + * // prefix sum + * void *d_temp_storage = nullptr; + * size_t temp_storage_bytes = 0; + * cub::DeviceScan::InclusiveSum( + * d_temp_storage, temp_storage_bytes, + * d_data, num_items); + * + * // Allocate temporary storage for inclusive prefix sum + * cudaMalloc(&d_temp_storage, temp_storage_bytes); + * + * // Run inclusive prefix sum + * cub::DeviceScan::InclusiveSum( + * d_temp_storage, temp_storage_bytes, + * d_data, num_items); + * + * // d_data <-- [8, 14, 21, 26, 29, 29, 38] + * + * @endcode + * + * @tparam IteratorT + * **[inferred]** Random-access input iterator type for reading scan + * inputs and writing scan outputs + * + * @param[in] d_temp_storage + * Device-accessible allocation of temporary storage. When `nullptr`, the + * required allocation size is written to `temp_storage_bytes` and no + * work is done. + * + * @param[in,out] temp_storage_bytes + * Reference to size in bytes of `d_temp_storage` allocation + * + * @param[in,out] d_data + * Random-access iterator to the sequence of data items + * + * @param[in] num_items + * Total number of input items (i.e., the length of `d_in`) + * + * @param[in] stream + * **[optional]** CUDA stream to launch kernels within. + * Default is stream0. + * + * [decoupled look-back]: https://research.nvidia.com/publication/single-pass-parallel-prefix-scan-decoupled-look-back + */ + template + CUB_RUNTIME_FUNCTION static cudaError_t + InclusiveSum(void *d_temp_storage, + size_t &temp_storage_bytes, + IteratorT d_data, + int num_items, + cudaStream_t stream = 0) + { + return InclusiveSum(d_temp_storage, + temp_storage_bytes, + d_data, + d_data, + num_items, + stream); + } + + template + CUB_DETAIL_RUNTIME_DEBUG_SYNC_IS_NOT_SUPPORTED + CUB_RUNTIME_FUNCTION static cudaError_t + InclusiveSum(void *d_temp_storage, + size_t &temp_storage_bytes, + IteratorT d_data, + int num_items, + cudaStream_t stream, + bool debug_synchronous) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + + return InclusiveSum(d_temp_storage, + temp_storage_bytes, + d_data, + num_items, + stream); + } + + /** + * @brief Computes a device-wide inclusive prefix scan using the specified + * binary `scan_op` functor. + * + * @par + * - Supports non-commutative scan operators. + * - Results are not deterministic for pseudo-associative operators (e.g., + * addition of floating-point types). Results for pseudo-associative + * operators may vary from run to run. Additional details can be found in + * the [decoupled look-back] description. + * - When `d_in` and `d_out` are equal, the scan is performed in-place. The + * range `[d_in, d_in + num_items)` and `[d_out, d_out + num_items)` + * shall not overlap in any other way. + * - @devicestorage + * + * @par Snippet + * The code snippet below illustrates the inclusive prefix min-scan of an + * `int` device vector. + * + * @par + * @code + * #include // or equivalently + * #include // for INT_MAX + * + * // CustomMin functor + * struct CustomMin + * { + * template + * CUB_RUNTIME_FUNCTION __forceinline__ + * T operator()(const T &a, const T &b) const { + * return (b < a) ? b : a; + * } + * }; + * + * // Declare, allocate, and initialize device-accessible pointers for + * // input and output + * int num_items; // e.g., 7 + * int *d_in; // e.g., [8, 6, 7, 5, 3, 0, 9] + * int *d_out; // e.g., [ , , , , , , ] + * CustomMin min_op; + * ... + * + * // Determine temporary device storage requirements for inclusive + * // prefix scan + * void *d_temp_storage = nullptr; + * size_t temp_storage_bytes = 0; + * cub::DeviceScan::InclusiveScan( + * d_temp_storage, temp_storage_bytes, + * d_in, d_out, min_op, num_items); + * + * // Allocate temporary storage for inclusive prefix scan + * cudaMalloc(&d_temp_storage, temp_storage_bytes); + * + * // Run inclusive prefix min-scan + * cub::DeviceScan::InclusiveScan( + * d_temp_storage, temp_storage_bytes, + * d_in, d_out, min_op, num_items); + * + * // d_out <-- [8, 6, 6, 5, 3, 0, 0] + * + * @endcode + * + * @tparam InputIteratorT + * **[inferred]** Random-access input iterator type for reading scan + * inputs \iterator + * + * @tparam OutputIteratorT + * **[inferred]** Random-access output iterator type for writing scan + * outputs \iterator + * + * @tparam ScanOp + * **[inferred]** Binary scan functor type having member + * `T operator()(const T &a, const T &b)` + * + * @param[in] + * d_temp_storage Device-accessible allocation of temporary storage. + * When `nullptr`, the required allocation size is written to + * `temp_storage_bytes` and no work is done. + * + * @param[in,out] temp_storage_bytes + * Reference to size in bytes of `d_temp_storage` allocation + * + * @param[in] d_in + * Random-access iterator to the input sequence of data items + * + * @param[out] d_out + * Random-access iterator to the output sequence of data items + * + * @param[in] scan_op + * Binary scan functor + * + * @param[in] num_items + * Total number of input items (i.e., the length of `d_in`) + * + * @param[in] stream + * **[optional]** CUDA stream to launch kernels within. + * Default is stream0. + * + * [decoupled look-back]: https://research.nvidia.com/publication/single-pass-parallel-prefix-scan-decoupled-look-back + */ + template + CUB_RUNTIME_FUNCTION static cudaError_t + InclusiveScan(void *d_temp_storage, + size_t &temp_storage_bytes, + InputIteratorT d_in, + OutputIteratorT d_out, + ScanOpT scan_op, + int num_items, + cudaStream_t stream = 0) + { + // Signed integer type for global offsets + using OffsetT = int; + + return DispatchScan::Dispatch(d_temp_storage, + temp_storage_bytes, + d_in, + d_out, + scan_op, + NullType(), + num_items, + stream); + } + + template + CUB_DETAIL_RUNTIME_DEBUG_SYNC_IS_NOT_SUPPORTED + CUB_RUNTIME_FUNCTION static cudaError_t + InclusiveScan(void *d_temp_storage, + size_t &temp_storage_bytes, + InputIteratorT d_in, + OutputIteratorT d_out, + ScanOpT scan_op, + int num_items, + cudaStream_t stream, + bool debug_synchronous) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + + return InclusiveScan( + d_temp_storage, + temp_storage_bytes, + d_in, + d_out, + scan_op, + num_items, + stream); + } + + /** + * @brief Computes a device-wide inclusive prefix scan using the specified + * binary `scan_op` functor. + * + * @par + * - Supports non-commutative scan operators. + * - Results are not deterministic for pseudo-associative operators (e.g., + * addition of floating-point types). Results for pseudo-associative + * operators may vary from run to run. Additional details can be found in + * the [decoupled look-back] description. + * - @devicestorage + * + * @par Snippet + * The code snippet below illustrates the inclusive prefix min-scan of an + * `int` device vector. + * + * @par + * @code + * #include // or equivalently + * #include // for INT_MAX + * + * // CustomMin functor + * struct CustomMin + * { + * template + * CUB_RUNTIME_FUNCTION __forceinline__ + * T operator()(const T &a, const T &b) const { + * return (b < a) ? b : a; + * } + * }; + * + * // Declare, allocate, and initialize device-accessible pointers for + * // input and output + * int num_items; // e.g., 7 + * int *d_data; // e.g., [8, 6, 7, 5, 3, 0, 9] + * CustomMin min_op; + * ... + * + * // Determine temporary device storage requirements for inclusive + * // prefix scan + * void *d_temp_storage = nullptr; + * size_t temp_storage_bytes = 0; + * cub::DeviceScan::InclusiveScan( + * d_temp_storage, temp_storage_bytes, + * d_data, min_op, num_items); + * + * // Allocate temporary storage for inclusive prefix scan + * cudaMalloc(&d_temp_storage, temp_storage_bytes); + * + * // Run inclusive prefix min-scan + * cub::DeviceScan::InclusiveScan( + * d_temp_storage, temp_storage_bytes, + * d_in, d_out, min_op, num_items); + * + * // d_data <-- [8, 6, 6, 5, 3, 0, 0] + * + * @endcode + * + * @tparam IteratorT + * **[inferred]** Random-access input iterator type for reading scan + * inputs and writing scan outputs + * + * @tparam ScanOp + * **[inferred]** Binary scan functor type having member + * `T operator()(const T &a, const T &b)` + * + * @param[in] + * d_temp_storage Device-accessible allocation of temporary storage. + * When `nullptr`, the required allocation size is written to + * `temp_storage_bytes` and no work is done. + * + * @param[in,out] temp_storage_bytes + * Reference to size in bytes of `d_temp_storage` allocation + * + * @param[in] d_data + * Random-access iterator to the sequence of data items + * + * @param[in] scan_op + * Binary scan functor + * + * @param[in] num_items + * Total number of input items (i.e., the length of `d_in`) + * + * @param[in] stream + * **[optional]** CUDA stream to launch kernels within. + * Default is stream0. + * + * [decoupled look-back]: https://research.nvidia.com/publication/single-pass-parallel-prefix-scan-decoupled-look-back + */ + template + CUB_RUNTIME_FUNCTION static cudaError_t + InclusiveScan(void *d_temp_storage, + size_t &temp_storage_bytes, + IteratorT d_data, + ScanOpT scan_op, + int num_items, + cudaStream_t stream = 0) + { + return InclusiveScan(d_temp_storage, + temp_storage_bytes, + d_data, + d_data, + scan_op, + num_items, + stream); + } + + template + CUB_DETAIL_RUNTIME_DEBUG_SYNC_IS_NOT_SUPPORTED + CUB_RUNTIME_FUNCTION static cudaError_t + InclusiveScan(void *d_temp_storage, + size_t &temp_storage_bytes, + IteratorT d_data, + ScanOpT scan_op, + int num_items, + cudaStream_t stream, + bool debug_synchronous) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + + return InclusiveScan(d_temp_storage, + temp_storage_bytes, + d_data, + scan_op, + num_items, + stream); + } + + /** + * @brief Computes a device-wide exclusive prefix sum-by-key with key equality + * defined by `equality_op`. The value of `0` is applied as the initial + * value, and is assigned to the beginning of each segment in + * `d_values_out`. + * + * @par + * - Supports non-commutative sum operators. + * - Results are not deterministic for pseudo-associative operators (e.g., + * addition of floating-point types). Results for pseudo-associative + * operators may vary from run to run. Additional details can be found in + * the [decoupled look-back] description. + * - `d_keys_in` may equal `d_values_out` but the range + * `[d_keys_in, d_keys_in + num_items)` and the range + * `[d_values_out, d_values_out + num_items)` shall not overlap otherwise. + * - `d_values_in` may equal `d_values_out` but the range + * `[d_values_in, d_values_in + num_items)` and the range + * `[d_values_out, d_values_out + num_items)` shall not overlap otherwise. + * - @devicestorage + * + * @par Snippet + * The code snippet below illustrates the exclusive prefix sum-by-key of an + * `int` device vector. + * @par + * @code + * #include // or equivalently + * + * // Declare, allocate, and initialize device-accessible pointers for + * // input and output + * int num_items; // e.g., 7 + * int *d_keys_in; // e.g., [0, 0, 1, 1, 1, 2, 2] + * int *d_values_in; // e.g., [8, 6, 7, 5, 3, 0, 9] + * int *d_values_out; // e.g., [ , , , , , , ] + * ... + * + * // Determine temporary device storage requirements + * void *d_temp_storage = nullptr; + * size_t temp_storage_bytes = 0; + * cub::DeviceScan::ExclusiveSumByKey( + * d_temp_storage, temp_storage_bytes, + * d_keys_in, d_values_in, d_values_out, num_items); + * + * // Allocate temporary storage + * cudaMalloc(&d_temp_storage, temp_storage_bytes); + * + * // Run exclusive prefix sum + * cub::DeviceScan::ExclusiveSumByKey( + * d_temp_storage, temp_storage_bytes, + * d_keys_in, d_values_in, d_values_out, num_items); + * + * // d_values_out <-- [0, 8, 0, 7, 12, 0, 0] + * + * @endcode + * + * @tparam KeysInputIteratorT + * **[inferred]** Random-access input iterator type for reading scan keys + * inputs \iterator + * + * @tparam ValuesInputIteratorT + * **[inferred]** Random-access input iterator type for reading scan + * values inputs \iterator + * + * @tparam ValuesOutputIteratorT + * **[inferred]** Random-access output iterator type for writing scan + * values outputs \iterator + * + * @tparam EqualityOpT + * **[inferred]** Functor type having member + * `T operator()(const T &a, const T &b)` for binary operations that + * defines the equality of keys + * + * @param[in] d_temp_storage + * Device-accessible allocation of temporary storage. When `nullptr`, the + * required allocation size is written to `temp_storage_bytes` and no + * work is done. + * + * @param[in,out] temp_storage_bytes + * Reference to size in bytes of `d_temp_storage` allocation + * + * @param[in] d_keys_in + * Random-access input iterator to the input sequence of key items + * + * @param[in] d_values_in + * Random-access input iterator to the input sequence of value items + * + * @param[out] d_values_out + * Random-access output iterator to the output sequence of value items + * + * @param[in] num_items + * Total number of input items (i.e., the length of `d_keys_in` and + * `d_values_in`) + * + * @param[in] equality_op + * Binary functor that defines the equality of keys. + * Default is cub::Equality(). + * + * @param[in] stream + * **[optional]** CUDA stream to launch kernels within. + * Default is stream0. + * + * [decoupled look-back]: https://research.nvidia.com/publication/single-pass-parallel-prefix-scan-decoupled-look-back + */ + template + CUB_RUNTIME_FUNCTION static cudaError_t + ExclusiveSumByKey(void *d_temp_storage, + size_t &temp_storage_bytes, + KeysInputIteratorT d_keys_in, + ValuesInputIteratorT d_values_in, + ValuesOutputIteratorT d_values_out, + int num_items, + EqualityOpT equality_op = EqualityOpT(), + cudaStream_t stream = 0) + { + // Signed integer type for global offsets + using OffsetT = int; + using InitT = cub::detail::value_t; + + // Initial value + InitT init_value{}; + + return DispatchScanByKey::Dispatch(d_temp_storage, + temp_storage_bytes, + d_keys_in, + d_values_in, + d_values_out, + equality_op, + Sum(), + init_value, + num_items, + stream); + } + + template + CUB_DETAIL_RUNTIME_DEBUG_SYNC_IS_NOT_SUPPORTED + CUB_RUNTIME_FUNCTION static cudaError_t + ExclusiveSumByKey(void *d_temp_storage, + size_t &temp_storage_bytes, + KeysInputIteratorT d_keys_in, + ValuesInputIteratorT d_values_in, + ValuesOutputIteratorT d_values_out, + int num_items, + EqualityOpT equality_op, + cudaStream_t stream, + bool debug_synchronous) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + + return ExclusiveSumByKey(d_temp_storage, + temp_storage_bytes, + d_keys_in, + d_values_in, + d_values_out, + num_items, + equality_op, + stream); + } + + /** + * @brief Computes a device-wide exclusive prefix scan-by-key using the + * specified binary `scan_op` functor. The key equality is defined by + * `equality_op`. The `init_value` value is applied as the initial + * value, and is assigned to the beginning of each segment in + * `d_values_out`. + * + * @par + * - Supports non-commutative scan operators. + * - Results are not deterministic for pseudo-associative operators (e.g., + * addition of floating-point types). Results for pseudo-associative + * operators may vary from run to run. Additional details can be found in + * the [decoupled look-back] description. + * - `d_keys_in` may equal `d_values_out` but the range + * `[d_keys_in, d_keys_in + num_items)` and the range + * `[d_values_out, d_values_out + num_items)` shall not overlap otherwise. + * - `d_values_in` may equal `d_values_out` but the range + * `[d_values_in, d_values_in + num_items)` and the range + * `[d_values_out, d_values_out + num_items)` shall not overlap otherwise. + * - @devicestorage + * + * @par Snippet + * The code snippet below illustrates the exclusive prefix min-scan-by-key of + * an `int` device vector + * @par + * @code + * #include // or equivalently + * #include // for INT_MAX + * + * // CustomMin functor + * struct CustomMin + * { + * template + * CUB_RUNTIME_FUNCTION __forceinline__ + * T operator()(const T &a, const T &b) const { + * return (b < a) ? b : a; + * } + * }; + * + * // CustomEqual functor + * struct CustomEqual + * { + * template + * CUB_RUNTIME_FUNCTION __forceinline__ + * T operator()(const T &a, const T &b) const { + * return a == b; + * } + * }; + * + * // Declare, allocate, and initialize device-accessible pointers for + * // input and output + * int num_items; // e.g., 7 + * int *d_keys_in; // e.g., [0, 0, 1, 1, 1, 2, 2] + * int *d_values_in; // e.g., [8, 6, 7, 5, 3, 0, 9] + * int *d_values_out; // e.g., [ , , , , , , ] + * CustomMin min_op; + * CustomEqual equality_op; + * ... + * + * // Determine temporary device storage requirements for exclusive + * // prefix scan + * void *d_temp_storage = NULL; + * size_t temp_storage_bytes = 0; + * cub::DeviceScan::ExclusiveScanByKey( + * d_temp_storage, temp_storage_bytes, + * d_keys_in, d_values_in, d_values_out, min_op, + * (int) INT_MAX, num_items, equality_op); + * + * // Allocate temporary storage for exclusive prefix scan + * cudaMalloc(&d_temp_storage, temp_storage_bytes); + * + * // Run exclusive prefix min-scan + * cub::DeviceScan::ExclusiveScanByKey( + * d_temp_storage, temp_storage_bytes, + * d_keys_in, d_values_in, d_values_out, min_op, + * (int) INT_MAX, num_items, equality_op); + * + * // d_values_out <-- [2147483647, 8, 2147483647, 7, 5, 2147483647, 0] + * + * @endcode + * + * @tparam KeysInputIteratorT + * **[inferred]** Random-access input iterator type for reading scan keys + * inputs \iterator + * + * @tparam ValuesInputIteratorT + * **[inferred]** Random-access input iterator type for reading scan values + * inputs \iterator + * + * @tparam ValuesOutputIteratorT + * **[inferred]** Random-access output iterator type for writing scan values + * outputs \iterator + * + * @tparam ScanOp + * **[inferred]** Binary scan functor type having member + * `T operator()(const T &a, const T &b)` + * + * @tparam InitValueT + * **[inferred]** Type of the `init_value` value used in Binary scan + * functor type having member `T operator()(const T &a, const T &b)` + * + * @tparam EqualityOpT + * **[inferred]** Functor type having member + * `T operator()(const T &a, const T &b)` for binary operations that + * defines the equality of keys + * + * @param[in] d_temp_storage + * Device-accessible allocation of temporary storage. When `nullptr`, the + * required allocation size is written to `temp_storage_bytes` and no work + * is done. + * + * @param[in,out] temp_storage_bytes + * Reference to size in bytes of `d_temp_storage` allocation + * + * @param[in] d_keys_in + * Random-access input iterator to the input sequence of key items + * + * @param[in] d_values_in + * Random-access input iterator to the input sequence of value items + * + * @param[out] d_values_out + * Random-access output iterator to the output sequence of value items + * + * @param[in] scan_op + * Binary scan functor + * + * @param[in] init_value + * Initial value to seed the exclusive scan (and is assigned to the + * beginning of each segment in `d_values_out`) + * + * @param[in] num_items + * Total number of input items (i.e., the length of `d_keys_in` and + * `d_values_in`) + * + * @param[in] equality_op + * Binary functor that defines the equality of keys. + * Default is cub::Equality(). + * + * @param[in] stream + * **[optional]** CUDA stream to launch kernels within. + * Default is stream0. + * + * [decoupled look-back]: https://research.nvidia.com/publication/single-pass-parallel-prefix-scan-decoupled-look-back + */ + template + CUB_RUNTIME_FUNCTION static cudaError_t + ExclusiveScanByKey(void *d_temp_storage, + size_t &temp_storage_bytes, + KeysInputIteratorT d_keys_in, + ValuesInputIteratorT d_values_in, + ValuesOutputIteratorT d_values_out, + ScanOpT scan_op, + InitValueT init_value, + int num_items, + EqualityOpT equality_op = EqualityOpT(), + cudaStream_t stream = 0) + { + // Signed integer type for global offsets + using OffsetT = int ; + + return DispatchScanByKey::Dispatch(d_temp_storage, + temp_storage_bytes, + d_keys_in, + d_values_in, + d_values_out, + equality_op, + scan_op, + init_value, + num_items, + stream); + } + + template + CUB_DETAIL_RUNTIME_DEBUG_SYNC_IS_NOT_SUPPORTED + CUB_RUNTIME_FUNCTION static cudaError_t + ExclusiveScanByKey(void *d_temp_storage, + size_t &temp_storage_bytes, + KeysInputIteratorT d_keys_in, + ValuesInputIteratorT d_values_in, + ValuesOutputIteratorT d_values_out, + ScanOpT scan_op, + InitValueT init_value, + int num_items, + EqualityOpT equality_op, + cudaStream_t stream, + bool debug_synchronous) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + + return ExclusiveScanByKey(d_temp_storage, + temp_storage_bytes, + d_keys_in, + d_values_in, + d_values_out, + scan_op, + init_value, + num_items, + equality_op, + stream); + } + + /** + * @brief Computes a device-wide inclusive prefix sum-by-key with key + * equality defined by `equality_op`. + * + * @par + * - Supports non-commutative sum operators. + * - Results are not deterministic for pseudo-associative operators (e.g., + * addition of floating-point types). Results for pseudo-associative + * operators may vary from run to run. Additional details can be found in + * the [decoupled look-back] description. + * - `d_keys_in` may equal `d_values_out` but the range + * `[d_keys_in, d_keys_in + num_items)` and the range + * `[d_values_out, d_values_out + num_items)` shall not overlap otherwise. + * - `d_values_in` may equal `d_values_out` but the range + * `[d_values_in, d_values_in + num_items)` and the range + * `[d_values_out, d_values_out + num_items)` shall not overlap otherwise. + * - @devicestorage + * + * @par Snippet + * The code snippet below illustrates the inclusive prefix sum-by-key of an + * `int` device vector. + * @par + * @code + * #include // or equivalently + * + * // Declare, allocate, and initialize device-accessible pointers for + * // input and output + * int num_items; // e.g., 7 + * int *d_keys_in; // e.g., [0, 0, 1, 1, 1, 2, 2] + * int *d_values_in; // e.g., [8, 6, 7, 5, 3, 0, 9] + * int *d_values_out; // e.g., [ , , , , , , ] + * ... + * + * // Determine temporary device storage requirements for inclusive prefix sum + * void *d_temp_storage = NULL; + * size_t temp_storage_bytes = 0; + * cub::DeviceScan::InclusiveSumByKey( + * d_temp_storage, temp_storage_bytes, + * d_keys_in, d_values_in, d_values_out, num_items); + * + * // Allocate temporary storage for inclusive prefix sum + * cudaMalloc(&d_temp_storage, temp_storage_bytes); + * + * // Run inclusive prefix sum + * cub::DeviceScan::InclusiveSumByKey( + * d_temp_storage, temp_storage_bytes, + * d_keys_in, d_values_in, d_values_out, num_items); + * + * // d_out <-- [8, 14, 7, 12, 15, 0, 9] + * + * @endcode + * + * @tparam KeysInputIteratorT + * **[inferred]** Random-access input iterator type for reading scan + * keys inputs \iterator + * + * @tparam ValuesInputIteratorT + * **[inferred]** Random-access input iterator type for reading scan + * values inputs \iterator + * + * @tparam ValuesOutputIteratorT + * **[inferred]** Random-access output iterator type for writing scan + * values outputs \iterator + * + * @tparam EqualityOpT + * **[inferred]** Functor type having member + * `T operator()(const T &a, const T &b)` for binary operations that + * defines the equality of keys + * + * @param[in] d_temp_storage + * Device-accessible allocation of temporary storage. + * When `nullptr`, the required allocation size is written to + * `temp_storage_bytes` and no work is done. + * + * @param[in,out] temp_storage_bytes + * Reference to size in bytes of `d_temp_storage` allocation + * + * @param[in] d_keys_in + * Random-access input iterator to the input sequence of key items + * + * @param[in] d_values_in + * Random-access input iterator to the input sequence of value items + * + * @param[out] d_values_out + * Random-access output iterator to the output sequence of value items + * + * @param[in] num_items + * Total number of input items (i.e., the length of `d_keys_in` and + * `d_values_in`) + * + * @param[in] equality_op + * Binary functor that defines the equality of keys. + * Default is cub::Equality(). + * + * @param[in] stream + * **[optional]** CUDA stream to launch kernels within. + * Default is stream0. + * + * [decoupled look-back]: https://research.nvidia.com/publication/single-pass-parallel-prefix-scan-decoupled-look-back + */ + template + CUB_RUNTIME_FUNCTION static cudaError_t + InclusiveSumByKey(void *d_temp_storage, + size_t &temp_storage_bytes, + KeysInputIteratorT d_keys_in, + ValuesInputIteratorT d_values_in, + ValuesOutputIteratorT d_values_out, + int num_items, + EqualityOpT equality_op = EqualityOpT(), + cudaStream_t stream = 0) + { + // Signed integer type for global offsets + using OffsetT = int ; + + return DispatchScanByKey::Dispatch(d_temp_storage, + temp_storage_bytes, + d_keys_in, + d_values_in, + d_values_out, + equality_op, + Sum(), + NullType(), + num_items, + stream); + } + + template + CUB_DETAIL_RUNTIME_DEBUG_SYNC_IS_NOT_SUPPORTED + CUB_RUNTIME_FUNCTION static cudaError_t + InclusiveSumByKey(void *d_temp_storage, + size_t &temp_storage_bytes, + KeysInputIteratorT d_keys_in, + ValuesInputIteratorT d_values_in, + ValuesOutputIteratorT d_values_out, + int num_items, + EqualityOpT equality_op, + cudaStream_t stream, + bool debug_synchronous) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + + return InclusiveSumByKey(d_temp_storage, + temp_storage_bytes, + d_keys_in, + d_values_in, + d_values_out, + num_items, + equality_op, + stream); + } + + /** + * @brief Computes a device-wide inclusive prefix scan-by-key using the + * specified binary `scan_op` functor. The key equality is defined + * by `equality_op`. + * + * @par + * - Supports non-commutative scan operators. + * - Results are not deterministic for pseudo-associative operators (e.g., + * addition of floating-point types). Results for pseudo-associative + * operators may vary from run to run. Additional details can be found in + * the [decoupled look-back] description. + * - `d_keys_in` may equal `d_values_out` but the range + * `[d_keys_in, d_keys_in + num_items)` and the range + * `[d_values_out, d_values_out + num_items)` shall not overlap otherwise. + * - `d_values_in` may equal `d_values_out` but the range + * `[d_values_in, d_values_in + num_items)` and the range + * `[d_values_out, d_values_out + num_items)` shall not overlap otherwise. + * - @devicestorage + * + * @par Snippet + * The code snippet below illustrates the inclusive prefix min-scan-by-key + * of an `int` device vector. + * @par + * @code + * #include // or equivalently + * #include // for INT_MAX + * + * // CustomMin functor + * struct CustomMin + * { + * template + * CUB_RUNTIME_FUNCTION __forceinline__ + * T operator()(const T &a, const T &b) const { + * return (b < a) ? b : a; + * } + * }; + * + * // CustomEqual functor + * struct CustomEqual + * { + * template + * CUB_RUNTIME_FUNCTION __forceinline__ + * T operator()(const T &a, const T &b) const { + * return a == b; + * } + * }; + * + * // Declare, allocate, and initialize device-accessible pointers for + * // input and output + * int num_items; // e.g., 7 + * int *d_keys_in; // e.g., [0, 0, 1, 1, 1, 2, 2] + * int *d_values_in; // e.g., [8, 6, 7, 5, 3, 0, 9] + * int *d_values_out; // e.g., [ , , , , , , ] + * CustomMin min_op; + * CustomEqual equality_op; + * ... + * + * // Determine temporary device storage requirements for inclusive prefix scan + * void *d_temp_storage = NULL; + * size_t temp_storage_bytes = 0; + * cub::DeviceScan::InclusiveScanByKey( + * d_temp_storage, temp_storage_bytes, + * d_keys_in, d_values_in, d_values_out, min_op, num_items, equality_op); + * + * // Allocate temporary storage for inclusive prefix scan + * cudaMalloc(&d_temp_storage, temp_storage_bytes); + * + * // Run inclusive prefix min-scan + * cub::DeviceScan::InclusiveScanByKey( + * d_temp_storage, temp_storage_bytes, + * d_keys_in, d_values_in, d_values_out, min_op, num_items, equality_op); + * + * // d_out <-- [8, 6, 7, 5, 3, 0, 0] + * + * @endcode + * + * @tparam KeysInputIteratorT + * **[inferred]** Random-access input iterator type for reading scan keys + * inputs \iterator + * + * @tparam ValuesInputIteratorT + * **[inferred]** Random-access input iterator type for reading scan + * values inputs \iterator + * + * @tparam ValuesOutputIteratorT + * **[inferred]** Random-access output iterator type for writing scan + * values outputs \iterator + * + * @tparam ScanOp + * **[inferred]** Binary scan functor type having member + * `T operator()(const T &a, const T &b)` + * + * @tparam EqualityOpT + * **[inferred]** Functor type having member + * `T operator()(const T &a, const T &b)` for binary operations that + * defines the equality of keys + * + * @param[in] d_temp_storage + * Device-accessible allocation of temporary storage. + * When `nullptr`, the required allocation size is written to + * `temp_storage_bytes` and no work is done. + * + * @param[in,out] temp_storage_bytes + * Reference to size in bytes of `d_temp_storage` allocation + * + * @param[in] d_keys_in + * Random-access input iterator to the input sequence of key items + * + * @param[in] d_values_in + * Random-access input iterator to the input sequence of value items + * + * @param[out] d_values_out + * Random-access output iterator to the output sequence of value items + * + * @param[in] scan_op + * Binary scan functor + * + * @param[in] num_items + * Total number of input items (i.e., the length of `d_keys_in` and + * `d_values_in`) + * + * @param[in] equality_op + * Binary functor that defines the equality of keys. + * Default is cub::Equality(). + * + * @param[in] stream + * **[optional]** CUDA stream to launch kernels within. + * Default is stream0. + * + * [decoupled look-back]: https://research.nvidia.com/publication/single-pass-parallel-prefix-scan-decoupled-look-back + */ + template + CUB_RUNTIME_FUNCTION static cudaError_t + InclusiveScanByKey(void *d_temp_storage, + size_t &temp_storage_bytes, + KeysInputIteratorT d_keys_in, + ValuesInputIteratorT d_values_in, + ValuesOutputIteratorT d_values_out, + ScanOpT scan_op, + int num_items, + EqualityOpT equality_op = EqualityOpT(), + cudaStream_t stream = 0) + { + // Signed integer type for global offsets + using OffsetT = int; + + return DispatchScanByKey::Dispatch(d_temp_storage, + temp_storage_bytes, + d_keys_in, + d_values_in, + d_values_out, + equality_op, + scan_op, + NullType(), + num_items, + stream); + } + + template + CUB_DETAIL_RUNTIME_DEBUG_SYNC_IS_NOT_SUPPORTED + CUB_RUNTIME_FUNCTION static cudaError_t + InclusiveScanByKey(void *d_temp_storage, + size_t &temp_storage_bytes, + KeysInputIteratorT d_keys_in, + ValuesInputIteratorT d_values_in, + ValuesOutputIteratorT d_values_out, + ScanOpT scan_op, + int num_items, + EqualityOpT equality_op, + cudaStream_t stream, + bool debug_synchronous) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + + return InclusiveScanByKey(d_temp_storage, + temp_storage_bytes, + d_keys_in, + d_values_in, + d_values_out, + scan_op, + num_items, + equality_op, + stream); + } + + //@} end member group +}; + +/** + * @example example_device_scan.cu + */ + +CUB_NAMESPACE_END + + diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/device/device_segmented_sort.cuh b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/device/device_segmented_sort.cuh new file mode 100644 index 0000000000000000000000000000000000000000..2b86da950781aecc235daa3076208dd0707a9f4b --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/device/device_segmented_sort.cuh @@ -0,0 +1,3098 @@ +/****************************************************************************** + * Copyright (c) 2011-2022, NVIDIA CORPORATION. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the NVIDIA CORPORATION nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ******************************************************************************/ + +/** + * @file + * cub::DeviceSegmentedSort provides device-wide, parallel operations for + * computing a batched sort across multiple, non-overlapping sequences of + * data items residing within device-accessible memory. + */ + +#pragma once + +#include +#include +#include +#include + +CUB_NAMESPACE_BEGIN + + +/** + * @brief DeviceSegmentedSort provides device-wide, parallel operations for + * computing a batched sort across multiple, non-overlapping sequences of + * data items residing within device-accessible memory. + * ![](segmented_sorting_logo.png) + * @ingroup SegmentedModule + * + * @par Overview + * The algorithm arranges items into ascending (or descending) order. + * The underlying sorting algorithm is undefined. Depending on the segment size, + * it might be radix sort, merge sort or something else. Therefore, no + * assumptions on the underlying implementation should be made. + * + * @par Differences from DeviceSegmentedRadixSort + * DeviceSegmentedRadixSort is optimized for significantly large segments (tens + * of thousands of items and more). Nevertheless, some domains produce a wide + * range of segment sizes. DeviceSegmentedSort partitions segments into size + * groups and specialize sorting algorithms for each group. This approach leads + * to better resource utilization in the presence of segment size imbalance or + * moderate segment sizes (up to thousands of items). + * This algorithm is more complex and consists of multiple kernels. This fact + * leads to longer compilation times as well as larger binaries sizes. + * + * @par Supported Types + * The algorithm has to satisfy the underlying algorithms restrictions. Radix + * sort usage restricts the list of supported types. Therefore, + * DeviceSegmentedSort can sort all of the built-in C++ numeric primitive types + * (`unsigned char`, `int`, `double`, etc.) as well as CUDA's `__half` and + * `__nv_bfloat16` 16-bit floating-point types. + * + * @par Segments are not required to be contiguous. Any element of input(s) or + * output(s) outside the specified segments will not be accessed nor modified. + * + * @par A simple example + * @code + * #include + * // or equivalently + * + * // Declare, allocate, and initialize device-accessible pointers + * // for sorting data + * int num_items; // e.g., 7 + * int num_segments; // e.g., 3 + * int *d_offsets; // e.g., [0, 3, 3, 7] + * int *d_keys_in; // e.g., [8, 6, 7, 5, 3, 0, 9] + * int *d_keys_out; // e.g., [-, -, -, -, -, -, -] + * int *d_values_in; // e.g., [0, 1, 2, 3, 4, 5, 6] + * int *d_values_out; // e.g., [-, -, -, -, -, -, -] + * ... + * + * // Determine temporary device storage requirements + * void *d_temp_storage = NULL; + * size_t temp_storage_bytes = 0; + * cub::DeviceSegmentedSort::SortPairs( + * d_temp_storage, temp_storage_bytes, + * d_keys_in, d_keys_out, d_values_in, d_values_out, + * num_items, num_segments, d_offsets, d_offsets + 1); + * + * // Allocate temporary storage + * cudaMalloc(&d_temp_storage, temp_storage_bytes); + * + * // Run sorting operation + * cub::DeviceSegmentedSort::SortPairs( + * d_temp_storage, temp_storage_bytes, + * d_keys_in, d_keys_out, d_values_in, d_values_out, + * num_items, num_segments, d_offsets, d_offsets + 1); + * + * // d_keys_out <-- [6, 7, 8, 0, 3, 5, 9] + * // d_values_out <-- [1, 2, 0, 5, 4, 3, 6] + * @endcode + */ +struct DeviceSegmentedSort +{ + + /*************************************************************************//** + * @name Keys-only + ****************************************************************************/ + //@{ + + /** + * @brief Sorts segments of keys into ascending order. Approximately + * `num_items + 2*num_segments` auxiliary storage required. + * + * @par + * - The contents of the input data are not altered by the sorting operation. + * - When the input is a contiguous sequence of segments, a single sequence + * @p segment_offsets (of length `num_segments+1`) can be aliased + * for both the @p d_begin_offsets and @p d_end_offsets parameters (where + * the latter is specified as `segment_offsets+1`). + * - SortKeys is not guaranteed to be stable. That is, suppose that @p i and + * @p j are equivalent: neither one is less than the other. It is not + * guaranteed that the relative order of these two elements will be + * preserved by sort. + * - The range `[d_keys_out, d_keys_out + num_items)` shall not overlap + * `[d_keys_in, d_keys_in + num_items)`, + * `[d_begin_offsets, d_begin_offsets + num_segments)` nor + * `[d_end_offsets, d_end_offsets + num_segments)` in any way. + * - Segments are not required to be contiguous. For all index values `i` + * outside the specified segments `d_keys_in[i]`, `d_keys_out[i]` will not + * be accessed nor modified. + * + * @par Snippet + * The code snippet below illustrates the batched sorting of three segments + * (with one zero-length segment) of @p int keys. + * + * @par + * @code + * #include + * // or equivalently + * + * // Declare, allocate, and initialize device-accessible + * // pointers for sorting data + * int num_items; // e.g., 7 + * int num_segments; // e.g., 3 + * int *d_offsets; // e.g., [0, 3, 3, 7] + * int *d_keys_in; // e.g., [8, 6, 7, 5, 3, 0, 9] + * int *d_keys_out; // e.g., [-, -, -, -, -, -, -] + * ... + * + * // Determine temporary device storage requirements + * void *d_temp_storage = NULL; + * size_t temp_storage_bytes = 0; + * cub::DeviceSegmentedSort::SortKeys( + * d_temp_storage, temp_storage_bytes, d_keys_in, d_keys_out, + * num_items, num_segments, d_offsets, d_offsets + 1); + * + * // Allocate temporary storage + * cudaMalloc(&d_temp_storage, temp_storage_bytes); + * + * // Run sorting operation + * cub::DeviceSegmentedSort::SortKeys( + * d_temp_storage, temp_storage_bytes, d_keys_in, d_keys_out, + * num_items, num_segments, d_offsets, d_offsets + 1); + * + * // d_keys_out <-- [6, 7, 8, 0, 3, 5, 9] + * @endcode + * + * @tparam KeyT + * [inferred] Key type + * + * @tparam BeginOffsetIteratorT + * [inferred] Random-access input iterator type for reading segment + * beginning offsets \iterator + * + * @tparam EndOffsetIteratorT + * [inferred] Random-access input iterator type for reading segment + * ending offsets \iterator + * + * @param[in] d_temp_storage + * Device-accessible allocation of temporary storage. When nullptr, the + * required allocation size is written to @p temp_storage_bytes and no work + * is done + * + * @param[in,out] temp_storage_bytes + * Reference to size in bytes of @p d_temp_storage allocation + * + * @param[in] d_keys_in + * Device-accessible pointer to the input data of key data to sort + * + * @param[out] d_keys_out + * Device-accessible pointer to the sorted output sequence of key data + * + * @param[in] num_items + * The total number of items to sort (across all segments) + * + * @param[in] num_segments + * The number of segments that comprise the sorting data + * + * @param[in] d_begin_offsets + * Random-access input iterator to the sequence of beginning offsets of + * length `num_segments`, such that `d_begin_offsets[i]` is the first + * element of the ith data segment in `d_keys_*` and + * `d_values_*` + * + * @param[in] d_end_offsets + * Random-access input iterator to the sequence of ending offsets of length + * `num_segments`, such that `d_end_offsets[i] - 1` is the last element of + * the ith data segment in `d_keys_*` and `d_values_*`. + * If `d_end_offsets[i] - 1 <= d_begin_offsets[i]`, the i-th segment is + * considered empty. + * + * @param[in] stream + * [optional] CUDA stream to launch kernels within. Default is + * stream0. + */ + template + CUB_RUNTIME_FUNCTION static cudaError_t + SortKeys(void *d_temp_storage, + std::size_t &temp_storage_bytes, + const KeyT *d_keys_in, + KeyT *d_keys_out, + int num_items, + int num_segments, + BeginOffsetIteratorT d_begin_offsets, + EndOffsetIteratorT d_end_offsets, + cudaStream_t stream = 0) + { + constexpr bool is_descending = false; + constexpr bool is_overwrite_okay = false; + using DispatchT = DispatchSegmentedSort; + + DoubleBuffer d_keys(const_cast(d_keys_in), d_keys_out); + DoubleBuffer d_values; + + return DispatchT::Dispatch(d_temp_storage, + temp_storage_bytes, + d_keys, + d_values, + num_items, + num_segments, + d_begin_offsets, + d_end_offsets, + is_overwrite_okay, + stream); + } + + template + CUB_DETAIL_RUNTIME_DEBUG_SYNC_IS_NOT_SUPPORTED + CUB_RUNTIME_FUNCTION static cudaError_t + SortKeys(void *d_temp_storage, + std::size_t &temp_storage_bytes, + const KeyT *d_keys_in, + KeyT *d_keys_out, + int num_items, + int num_segments, + BeginOffsetIteratorT d_begin_offsets, + EndOffsetIteratorT d_end_offsets, + cudaStream_t stream, + bool debug_synchronous) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + + return SortKeys( + d_temp_storage, + temp_storage_bytes, + d_keys_in, + d_keys_out, + num_items, + num_segments, + d_begin_offsets, + d_end_offsets, + stream); + } + + /** + * @brief Sorts segments of keys into descending order. Approximately + * `num_items + 2*num_segments` auxiliary storage required. + * + * @par + * - The contents of the input data are not altered by the sorting operation. + * - When the input is a contiguous sequence of segments, a single sequence + * @p segment_offsets (of length `num_segments + 1`) can be aliased + * for both the @p d_begin_offsets and @p d_end_offsets parameters (where + * the latter is specified as `segment_offsets + 1`). + * - SortKeysDescending is not guaranteed to be stable. That is, suppose that + * @p i and @p j are equivalent: neither one is less than the other. It is + * not guaranteed that the relative order of these two elements will be + * preserved by sort. + * - The range `[d_keys_out, d_keys_out + num_items)` shall not overlap + * `[d_keys_in, d_keys_in + num_items)`, + * `[d_begin_offsets, d_begin_offsets + num_segments)` nor + * `[d_end_offsets, d_end_offsets + num_segments)` in any way. + * - Segments are not required to be contiguous. For all index values `i` + * outside the specified segments `d_keys_in[i]`, `d_keys_out[i]` will not + * be accessed nor modified. + * + * @par Snippet + * The code snippet below illustrates the batched sorting of three segments + * (with one zero-length segment) of @p int keys. + * + * @par + * @code + * #include + * // or equivalently + * + * // Declare, allocate, and initialize device-accessible pointers + * // for sorting data + * int num_items; // e.g., 7 + * int num_segments; // e.g., 3 + * int *d_offsets; // e.g., [0, 3, 3, 7] + * int *d_keys_in; // e.g., [8, 6, 7, 5, 3, 0, 9] + * int *d_keys_out; // e.g., [-, -, -, -, -, -, -] + * ... + * + * // Determine temporary device storage requirements + * void *d_temp_storage = NULL; + * size_t temp_storage_bytes = 0; + * cub::DeviceSegmentedSort::SortKeysDescending( + * d_temp_storage, temp_storage_bytes, d_keys_in, d_keys_out, + * num_items, num_segments, d_offsets, d_offsets + 1); + * + * // Allocate temporary storage + * cudaMalloc(&d_temp_storage, temp_storage_bytes); + * + * // Run sorting operation + * cub::DeviceSegmentedSort::SortKeysDescending( + * d_temp_storage, temp_storage_bytes, d_keys_in, d_keys_out, + * num_items, num_segments, d_offsets, d_offsets + 1); + * + * // d_keys_out <-- [8, 7, 6, 9, 5, 3, 0] + * @endcode + * + * @tparam KeyT + * [inferred] Key type + * + * @tparam BeginOffsetIteratorT + * [inferred] Random-access input iterator type for reading segment + * beginning offsets \iterator + * + * @tparam EndOffsetIteratorT + * [inferred] Random-access input iterator type for reading segment + * ending offsets \iterator + * + * @param[in] d_temp_storage + * Device-accessible allocation of temporary storage. When nullptr, the + * required allocation size is written to @p temp_storage_bytes and no + * work is done + * + * @param[in,out] temp_storage_bytes + * Reference to size in bytes of @p d_temp_storage allocation + * + * @param[in] d_keys_in + * Device-accessible pointer to the input data of key data to sort + * + * @param[out] d_keys_out + * Device-accessible pointer to the sorted output sequence of key data + * + * @param[in] num_items + * The total number of items to sort (across all segments) + * + * @param[in] num_segments + * The number of segments that comprise the sorting data + * + * @param[in] d_begin_offsets + * Random-access input iterator to the sequence of beginning offsets of + * length @p num_segments, such that `d_begin_offsets[i]` is the first + * element of the ith data segment in `d_keys_*` and + * `d_values_*` + * + * @param[in] d_end_offsets + * Random-access input iterator to the sequence of ending offsets of length + * @p num_segments, such that `d_end_offsets[i] - 1` is the last element of + * the ith data segment in `d_keys_*` and `d_values_*`. + * If `d_end_offsets[i] - 1 <= d_begin_offsets[i]`, the i-th segment is + * considered empty. + * + * @param[in] stream + * [optional] CUDA stream to launch kernels within. Default is + * stream0. + */ + template + CUB_RUNTIME_FUNCTION static cudaError_t + SortKeysDescending(void *d_temp_storage, + std::size_t &temp_storage_bytes, + const KeyT *d_keys_in, + KeyT *d_keys_out, + int num_items, + int num_segments, + BeginOffsetIteratorT d_begin_offsets, + EndOffsetIteratorT d_end_offsets, + cudaStream_t stream = 0) + { + constexpr bool is_descending = true; + constexpr bool is_overwrite_okay = false; + using DispatchT = DispatchSegmentedSort; + + DoubleBuffer d_keys(const_cast(d_keys_in), d_keys_out); + DoubleBuffer d_values; + + return DispatchT::Dispatch(d_temp_storage, + temp_storage_bytes, + d_keys, + d_values, + num_items, + num_segments, + d_begin_offsets, + d_end_offsets, + is_overwrite_okay, + stream); + } + + template + CUB_DETAIL_RUNTIME_DEBUG_SYNC_IS_NOT_SUPPORTED + CUB_RUNTIME_FUNCTION static cudaError_t + SortKeysDescending(void *d_temp_storage, + std::size_t &temp_storage_bytes, + const KeyT *d_keys_in, + KeyT *d_keys_out, + int num_items, + int num_segments, + BeginOffsetIteratorT d_begin_offsets, + EndOffsetIteratorT d_end_offsets, + cudaStream_t stream, + bool debug_synchronous) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + + return SortKeysDescending( + d_temp_storage, + temp_storage_bytes, + d_keys_in, + d_keys_out, + num_items, + num_segments, + d_begin_offsets, + d_end_offsets, + stream); + } + + /** + * @brief Sorts segments of keys into ascending order. Approximately + * `2*num_segments` auxiliary storage required. + * + * @par + * - The sorting operation is given a pair of key buffers managed by a + * DoubleBuffer structure that indicates which of the two buffers is + * "current" (and thus contains the input data to be sorted). + * - The contents of both buffers may be altered by the sorting operation. + * - Upon completion, the sorting operation will update the "current" + * indicator within the DoubleBuffer wrapper to reference which of the two + * buffers now contains the sorted output sequence (a function of the number + * of key bits and the targeted device architecture). + * - When the input is a contiguous sequence of segments, a single sequence + * @p segment_offsets (of length `num_segments+1`) can be aliased + * for both the @p d_begin_offsets and @p d_end_offsets parameters (where + * the latter is specified as `segment_offsets+1`). + * - SortKeys is not guaranteed to be stable. That is, suppose that + * @p i and @p j are equivalent: neither one is less than the other. It is + * not guaranteed that the relative order of these two elements will be + * preserved by sort. + * - Let `cur = d_keys.Current()` and `alt = d_keys.Alternate()`. + * The range `[cur, cur + num_items)` shall not overlap + * `[alt, alt + num_items)`. Both ranges shall not overlap + * `[d_begin_offsets, d_begin_offsets + num_segments)` nor + * `[d_end_offsets, d_end_offsets + num_segments)` in any way. + * - Segments are not required to be contiguous. For all index values `i` + * outside the specified segments `d_keys.Current()[i]`, + * `d_keys[i].Alternate()[i]` will not be accessed nor modified. + * + * @par Snippet + * The code snippet below illustrates the batched sorting of three segments + * (with one zero-length segment) of @p int keys. + * + * @par + * @code + * #include + * // or equivalently + * + * // Declare, allocate, and initialize device-accessible + * // pointers for sorting data + * int num_items; // e.g., 7 + * int num_segments; // e.g., 3 + * int *d_offsets; // e.g., [0, 3, 3, 7] + * int *d_key_buf; // e.g., [8, 6, 7, 5, 3, 0, 9] + * int *d_key_alt_buf; // e.g., [-, -, -, -, -, -, -] + * ... + * + * // Create a DoubleBuffer to wrap the pair of device pointers + * cub::DoubleBuffer d_keys(d_key_buf, d_key_alt_buf); + * + * // Determine temporary device storage requirements + * void *d_temp_storage = NULL; + * size_t temp_storage_bytes = 0; + * cub::DeviceSegmentedSort::SortKeys( + * d_temp_storage, temp_storage_bytes, d_keys, + * num_items, num_segments, d_offsets, d_offsets + 1); + * + * // Allocate temporary storage + * cudaMalloc(&d_temp_storage, temp_storage_bytes); + * + * // Run sorting operation + * cub::DeviceSegmentedSort::SortKeys( + * d_temp_storage, temp_storage_bytes, d_keys, + * num_items, num_segments, d_offsets, d_offsets + 1); + * + * // d_keys.Current() <-- [6, 7, 8, 0, 3, 5, 9] + * @endcode + * + * @tparam KeyT + * [inferred] Key type + * + * @tparam BeginOffsetIteratorT + * [inferred] Random-access input iterator type for reading segment + * beginning offsets \iterator + * + * @tparam EndOffsetIteratorT + * [inferred] Random-access input iterator type for reading segment + * ending offsets \iterator + * + * @param[in] d_temp_storage + * Device-accessible allocation of temporary storage. When nullptr, the + * required allocation size is written to @p temp_storage_bytes and no + * work is done + * + * @param[in,out] temp_storage_bytes + * Reference to size in bytes of @p d_temp_storage allocation + * + * @param[in,out] d_keys + * Reference to the double-buffer of keys whose "current" device-accessible + * buffer contains the unsorted input keys and, upon return, is updated to + * point to the sorted output keys + * + * @param[in] num_items + * The total number of items to sort (across all segments) + * + * @param[in] num_segments + * The number of segments that comprise the sorting data + * + * @param[in] d_begin_offsets + * Random-access input iterator to the sequence of beginning offsets of + * length @p num_segments, such that `d_begin_offsets[i]` is the first + * element of the ith data segment in `d_keys_*` + * and `d_values_*` + * + * @param[in] d_end_offsets + * Random-access input iterator to the sequence of ending offsets of length + * @p num_segments, such that `d_end_offsets[i] - 1` is the last element of + * the ith data segment in `d_keys_*` and `d_values_*`. + * If `d_end_offsets[i] - 1 <= d_begin_offsets[i]`, the i-th segment is + * considered empty. + * + * @param[in] stream + * [optional] CUDA stream to launch kernels within. Default is + * stream0. + */ + template + CUB_RUNTIME_FUNCTION static cudaError_t + SortKeys(void *d_temp_storage, + std::size_t &temp_storage_bytes, + DoubleBuffer &d_keys, + int num_items, + int num_segments, + BeginOffsetIteratorT d_begin_offsets, + EndOffsetIteratorT d_end_offsets, + cudaStream_t stream = 0) + { + constexpr bool is_descending = false; + constexpr bool is_overwrite_okay = true; + + using DispatchT = DispatchSegmentedSort; + + DoubleBuffer d_values; + + return DispatchT::Dispatch(d_temp_storage, + temp_storage_bytes, + d_keys, + d_values, + num_items, + num_segments, + d_begin_offsets, + d_end_offsets, + is_overwrite_okay, + stream); + } + + template + CUB_DETAIL_RUNTIME_DEBUG_SYNC_IS_NOT_SUPPORTED + CUB_RUNTIME_FUNCTION static cudaError_t + SortKeys(void *d_temp_storage, + std::size_t &temp_storage_bytes, + DoubleBuffer &d_keys, + int num_items, + int num_segments, + BeginOffsetIteratorT d_begin_offsets, + EndOffsetIteratorT d_end_offsets, + cudaStream_t stream, + bool debug_synchronous) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + + return SortKeys( + d_temp_storage, + temp_storage_bytes, + d_keys, + num_items, + num_segments, + d_begin_offsets, + d_end_offsets, + stream); + } + + /** + * @brief Sorts segments of keys into descending order. Approximately + * `2*num_segments` auxiliary storage required. + * + * @par + * - The sorting operation is given a pair of key buffers managed by a + * DoubleBuffer structure that indicates which of the two buffers is + * "current" (and thus contains the input data to be sorted). + * - The contents of both buffers may be altered by the sorting operation. + * - Upon completion, the sorting operation will update the "current" + * indicator within the DoubleBuffer wrapper to reference which of the two + * buffers now contains the sorted output sequence (a function of the number + * of key bits and the targeted device architecture). + * - When the input is a contiguous sequence of segments, a single sequence + * @p segment_offsets (of length `num_segments + 1`) can be aliased + * for both the @p d_begin_offsets and @p d_end_offsets parameters (where + * the latter is specified as `segment_offsets + 1`). + * - SortKeysDescending is not guaranteed to be stable. That is, suppose that + * @p i and @p j are equivalent: neither one is less than the other. It is + * not guaranteed that the relative order of these two elements will be + * preserved by sort. + * - Let `cur = d_keys.Current()` and `alt = d_keys.Alternate()`. + * The range `[cur, cur + num_items)` shall not overlap + * `[alt, alt + num_items)`. Both ranges shall not overlap + * `[d_begin_offsets, d_begin_offsets + num_segments)` nor + * `[d_end_offsets, d_end_offsets + num_segments)` in any way. + * - Segments are not required to be contiguous. For all index values `i` + * outside the specified segments `d_keys.Current()[i]`, + * `d_keys[i].Alternate()[i]` will not be accessed nor modified. + * + * @par Snippet + * The code snippet below illustrates the batched sorting of three segments + * (with one zero-length segment) of @p int keys. + * + * @par + * @code + * #include + * // or equivalently + * + * // Declare, allocate, and initialize device-accessible pointers for + * // sorting data + * int num_items; // e.g., 7 + * int num_segments; // e.g., 3 + * int *d_offsets; // e.g., [0, 3, 3, 7] + * int *d_key_buf; // e.g., [8, 6, 7, 5, 3, 0, 9] + * int *d_key_alt_buf; // e.g., [-, -, -, -, -, -, -] + * ... + * + * // Create a DoubleBuffer to wrap the pair of device pointers + * cub::DoubleBuffer d_keys(d_key_buf, d_key_alt_buf); + * + * // Determine temporary device storage requirements + * void *d_temp_storage = NULL; + * size_t temp_storage_bytes = 0; + * cub::DeviceSegmentedSort::SortKeysDescending( + * d_temp_storage, temp_storage_bytes, d_keys, + * num_items, num_segments, d_offsets, d_offsets + 1); + * + * // Allocate temporary storage + * cudaMalloc(&d_temp_storage, temp_storage_bytes); + * + * // Run sorting operation + * cub::DeviceSegmentedSort::SortKeysDescending( + * d_temp_storage, temp_storage_bytes, d_keys, + * num_items, num_segments, d_offsets, d_offsets + 1); + * + * // d_keys.Current() <-- [8, 7, 6, 9, 5, 3, 0] + * @endcode + * + * @tparam KeyT + * [inferred] Key type + * + * @tparam BeginOffsetIteratorT + * [inferred] Random-access input iterator type for reading segment + * beginning offsets \iterator + * + * @tparam EndOffsetIteratorT + * [inferred] Random-access input iterator type for reading segment + * ending offsets \iterator + * + * @param[in] d_temp_storage + * Device-accessible allocation of temporary storage. When `nullptr`, the + * required allocation size is written to @p temp_storage_bytes and no work + * is done + * + * @param[in,out] temp_storage_bytes + * Reference to size in bytes of @p d_temp_storage allocation + * + * @param[in,out] d_keys + * Reference to the double-buffer of keys whose "current" device-accessible + * buffer contains the unsorted input keys and, upon return, is updated to + * point to the sorted output keys + * + * @param[in] num_items + * The total number of items to sort (across all segments) + * + * @param[in] num_segments + * The number of segments that comprise the sorting data + * + * @param[in] d_begin_offsets + * Random-access input iterator to the sequence of beginning offsets of + * length @p num_segments, such that `d_begin_offsets[i]` is the first + * element of the ith data segment in `d_keys_*` and + * `d_values_*` + * + * @param[in] d_end_offsets + * Random-access input iterator to the sequence of ending offsets of length + * @p num_segments, such that `d_end_offsets[i] - 1` is the last element of + * the ith data segment in `d_keys_*` and `d_values_*`. + * If `d_end_offsets[i] - 1<= d_begin_offsets[i]`, the i-th segment is + * considered empty. + * + * @param[in] stream + * [optional] CUDA stream to launch kernels within. Default is + * stream0. + */ + template + CUB_RUNTIME_FUNCTION static cudaError_t + SortKeysDescending(void *d_temp_storage, + std::size_t &temp_storage_bytes, + DoubleBuffer &d_keys, + int num_items, + int num_segments, + BeginOffsetIteratorT d_begin_offsets, + EndOffsetIteratorT d_end_offsets, + cudaStream_t stream = 0) + { + constexpr bool is_descending = true; + constexpr bool is_overwrite_okay = true; + + using DispatchT = DispatchSegmentedSort; + + DoubleBuffer d_values; + + return DispatchT::Dispatch(d_temp_storage, + temp_storage_bytes, + d_keys, + d_values, + num_items, + num_segments, + d_begin_offsets, + d_end_offsets, + is_overwrite_okay, + stream); + } + + template + CUB_DETAIL_RUNTIME_DEBUG_SYNC_IS_NOT_SUPPORTED + CUB_RUNTIME_FUNCTION static cudaError_t + SortKeysDescending(void *d_temp_storage, + std::size_t &temp_storage_bytes, + DoubleBuffer &d_keys, + int num_items, + int num_segments, + BeginOffsetIteratorT d_begin_offsets, + EndOffsetIteratorT d_end_offsets, + cudaStream_t stream, + bool debug_synchronous) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + + return SortKeysDescending( + d_temp_storage, + temp_storage_bytes, + d_keys, + num_items, + num_segments, + d_begin_offsets, + d_end_offsets, + stream); + } + + /** + * @brief Sorts segments of keys into ascending order. Approximately + * `num_items + 2*num_segments` auxiliary storage required. + * + * @par + * - The contents of the input data are not altered by the sorting operation. + * - When the input is a contiguous sequence of segments, a single sequence + * @p segment_offsets (of length `num_segments+1`) can be aliased + * for both the @p d_begin_offsets and @p d_end_offsets parameters (where + * the latter is specified as `segment_offsets+1`). + * - StableSortKeys is stable: it preserves the relative ordering of + * equivalent elements. That is, if @p x and @p y are elements such that + * @p x precedes @p y, and if the two elements are equivalent (neither + * @p x < @p y nor @p y < @p x) then a postcondition of stable sort is that + * @p x still precedes @p y. + * - The range `[d_keys_out, d_keys_out + num_items)` shall not overlap + * `[d_keys_in, d_keys_in + num_items)`, + * `[d_begin_offsets, d_begin_offsets + num_segments)` nor + * `[d_end_offsets, d_end_offsets + num_segments)` in any way. + * - Segments are not required to be contiguous. For all index values `i` + * outside the specified segments `d_keys_in[i]`, `d_keys_out[i]` will not + * be accessed nor modified. + * + * @par Snippet + * The code snippet below illustrates the batched sorting of three segments + * (with one zero-length segment) of @p int keys. + * + * @par + * @code + * #include + * // or equivalently + * + * // Declare, allocate, and initialize device-accessible pointers + * // for sorting data + * int num_items; // e.g., 7 + * int num_segments; // e.g., 3 + * int *d_offsets; // e.g., [0, 3, 3, 7] + * int *d_keys_in; // e.g., [8, 6, 7, 5, 3, 0, 9] + * int *d_keys_out; // e.g., [-, -, -, -, -, -, -] + * ... + * + * // Determine temporary device storage requirements + * void *d_temp_storage = NULL; + * size_t temp_storage_bytes = 0; + * cub::DeviceSegmentedSort::StableSortKeys( + * d_temp_storage, temp_storage_bytes, d_keys_in, d_keys_out, + * num_items, num_segments, d_offsets, d_offsets + 1); + * + * // Allocate temporary storage + * cudaMalloc(&d_temp_storage, temp_storage_bytes); + * + * // Run sorting operation + * cub::DeviceSegmentedSort::StableSortKeys( + * d_temp_storage, temp_storage_bytes, d_keys_in, d_keys_out, + * num_items, num_segments, d_offsets, d_offsets + 1); + * + * // d_keys_out <-- [6, 7, 8, 0, 3, 5, 9] + * @endcode + * + * @tparam KeyT + * [inferred] Key type + * + * @tparam BeginOffsetIteratorT + * [inferred] Random-access input iterator type for reading segment + * beginning offsets \iterator + * + * @tparam EndOffsetIteratorT + * [inferred] Random-access input iterator type for reading segment + * ending offsets \iterator + * + * @param[in] d_temp_storage + * Device-accessible allocation of temporary storage. When nullptr, the + * required allocation size is written to @p temp_storage_bytes and no work + * is done + * + * @param[in,out] temp_storage_bytes + * Reference to size in bytes of @p d_temp_storage allocation + * + * @param[in] d_keys_in + * Device-accessible pointer to the input data of key data to sort + * + * @param[out] d_keys_out + * Device-accessible pointer to the sorted output sequence of key data + * + * @param[in] num_items + * The total number of items to sort (across all segments) + * + * @param[in] num_segments + * The number of segments that comprise the sorting data + * + * @param[in] d_begin_offsets + * Random-access input iterator to the sequence of beginning offsets of + * length @p num_segments, such that `d_begin_offsets[i]` is the first + * element of the ith data segment in `d_keys_*` and + * `d_values_*` + * + * @param[in] d_end_offsets + * Random-access input iterator to the sequence of ending offsets of length + * @p num_segments, such that `d_end_offsets[i]-1` is the last element of + * the ith data segment in `d_keys_*` and `d_values_*`. + * If `d_end_offsets[i]-1 <= d_begin_offsets[i]`, the i-th segment is + * considered empty. + * + * @param[in] stream + * [optional] CUDA stream to launch kernels within. Default is + * stream0. + */ + template + CUB_RUNTIME_FUNCTION static cudaError_t + StableSortKeys(void *d_temp_storage, + std::size_t &temp_storage_bytes, + const KeyT *d_keys_in, + KeyT *d_keys_out, + int num_items, + int num_segments, + BeginOffsetIteratorT d_begin_offsets, + EndOffsetIteratorT d_end_offsets, + cudaStream_t stream = 0) + { + return SortKeys( + d_temp_storage, + temp_storage_bytes, + d_keys_in, + d_keys_out, + num_items, + num_segments, + d_begin_offsets, + d_end_offsets, + stream); + } + + template + CUB_DETAIL_RUNTIME_DEBUG_SYNC_IS_NOT_SUPPORTED + CUB_RUNTIME_FUNCTION static cudaError_t + StableSortKeys(void *d_temp_storage, + std::size_t &temp_storage_bytes, + const KeyT *d_keys_in, + KeyT *d_keys_out, + int num_items, + int num_segments, + BeginOffsetIteratorT d_begin_offsets, + EndOffsetIteratorT d_end_offsets, + cudaStream_t stream, + bool debug_synchronous) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + + return StableSortKeys( + d_temp_storage, + temp_storage_bytes, + d_keys_in, + d_keys_out, + num_items, + num_segments, + d_begin_offsets, + d_end_offsets, + stream); + } + + /** + * @brief Sorts segments of keys into descending order. Approximately + * `num_items + 2*num_segments` auxiliary storage required. + * + * @par + * - The contents of the input data are not altered by the sorting operation. + * - When the input is a contiguous sequence of segments, a single sequence + * @p segment_offsets (of length `num_segments+1`) can be aliased + * for both the @p d_begin_offsets and @p d_end_offsets parameters (where + * the latter is specified as `segment_offsets+1`). + * - StableSortKeysDescending is stable: it preserves the relative ordering of + * equivalent elements. That is, if @p x and @p y are elements such that + * @p x precedes @p y, and if the two elements are equivalent (neither + * @p x < @p y nor @p y < @p x) then a postcondition of stable sort is that + * @p x still precedes @p y. + * - The range `[d_keys_out, d_keys_out + num_items)` shall not overlap + * `[d_keys_in, d_keys_in + num_items)`, + * `[d_begin_offsets, d_begin_offsets + num_segments)` nor + * `[d_end_offsets, d_end_offsets + num_segments)` in any way. + * - Segments are not required to be contiguous. For all index values `i` + * outside the specified segments `d_keys_in[i]`, `d_keys_out[i]` will not + * be accessed nor modified. + * + * @par Snippet + * The code snippet below illustrates the batched sorting of three segments + * (with one zero-length segment) of @p int keys. + * + * @par + * @code + * #include + * // or equivalently + * + * // Declare, allocate, and initialize device-accessible pointers + * // for sorting data + * int num_items; // e.g., 7 + * int num_segments; // e.g., 3 + * int *d_offsets; // e.g., [0, 3, 3, 7] + * int *d_keys_in; // e.g., [8, 6, 7, 5, 3, 0, 9] + * int *d_keys_out; // e.g., [-, -, -, -, -, -, -] + * ... + * + * // Determine temporary device storage requirements + * void *d_temp_storage = NULL; + * size_t temp_storage_bytes = 0; + * cub::DeviceSegmentedSort::StableSortKeysDescending( + * d_temp_storage, temp_storage_bytes, d_keys_in, d_keys_out, + * num_items, num_segments, d_offsets, d_offsets + 1); + * + * // Allocate temporary storage + * cudaMalloc(&d_temp_storage, temp_storage_bytes); + * + * // Run sorting operation + * cub::DeviceSegmentedSort::StableSortKeysDescending( + * d_temp_storage, temp_storage_bytes, d_keys_in, d_keys_out, + * num_items, num_segments, d_offsets, d_offsets + 1); + * + * // d_keys_out <-- [8, 7, 6, 9, 5, 3, 0] + * @endcode + * + * @tparam KeyT + * [inferred] Key type + * + * @tparam BeginOffsetIteratorT + * [inferred] Random-access input iterator type for reading segment + * beginning offsets \iterator + * + * @tparam EndOffsetIteratorT + * [inferred] Random-access input iterator type for reading segment + * ending offsets \iterator + * + * @param[in] d_temp_storage + * Device-accessible allocation of temporary storage. When nullptr, the + * required allocation size is written to @p temp_storage_bytes and no work + * is done. + * + * @param[in,out] temp_storage_bytes + * Reference to size in bytes of @p d_temp_storage allocation + * + * @param[in] d_keys_in + * Device-accessible pointer to the input data of key data to sort + * + * @param[out] d_keys_out + * Device-accessible pointer to the sorted output sequence of key data + * + * @param[in] num_items + * The total number of items to sort (across all segments) + * + * @param[in] num_segments + * The number of segments that comprise the sorting data + * + * @param[in] d_begin_offsets + * Random-access input iterator to the sequence of beginning offsets of + * length @p num_segments, such that `d_begin_offsets[i]` is the first + * element of the ith data segment in `d_keys_*` and + * `d_values_*` + * + * @param[in] d_end_offsets + * Random-access input iterator to the sequence of ending offsets of length + * @p num_segments, such that `d_end_offsets[i]-1` is the last element of + * the ith data segment in `d_keys_*` and `d_values_*`. + * If `d_end_offsets[i]-1 <= d_begin_offsets[i]`, the i-th segment is + * considered empty. + * + * @param[in] stream + * [optional] CUDA stream to launch kernels within. Default is + * stream0. + */ + template + CUB_RUNTIME_FUNCTION static cudaError_t + StableSortKeysDescending(void *d_temp_storage, + std::size_t &temp_storage_bytes, + const KeyT *d_keys_in, + KeyT *d_keys_out, + int num_items, + int num_segments, + BeginOffsetIteratorT d_begin_offsets, + EndOffsetIteratorT d_end_offsets, + cudaStream_t stream = 0) + { + return SortKeysDescending(d_temp_storage, + temp_storage_bytes, + d_keys_in, + d_keys_out, + num_items, + num_segments, + d_begin_offsets, + d_end_offsets, + stream); + } + + template + CUB_DETAIL_RUNTIME_DEBUG_SYNC_IS_NOT_SUPPORTED + CUB_RUNTIME_FUNCTION static cudaError_t + StableSortKeysDescending(void *d_temp_storage, + std::size_t &temp_storage_bytes, + const KeyT *d_keys_in, + KeyT *d_keys_out, + int num_items, + int num_segments, + BeginOffsetIteratorT d_begin_offsets, + EndOffsetIteratorT d_end_offsets, + cudaStream_t stream, + bool debug_synchronous) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + + return StableSortKeysDescending(d_temp_storage, + temp_storage_bytes, + d_keys_in, + d_keys_out, + num_items, + num_segments, + d_begin_offsets, + d_end_offsets, + stream); + } + + /** + * @brief Sorts segments of keys into ascending order. Approximately + * `2*num_segments` auxiliary storage required. + * + * @par + * - The sorting operation is given a pair of key buffers managed by a + * DoubleBuffer structure that indicates which of the two buffers is + * "current" (and thus contains the input data to be sorted). + * - The contents of both buffers may be altered by the sorting operation. + * - Upon completion, the sorting operation will update the "current" + * indicator within the DoubleBuffer wrapper to reference which of the two + * buffers now contains the sorted output sequence (a function of the number + * of key bits and the targeted device architecture). + * - When the input is a contiguous sequence of segments, a single sequence + * @p segment_offsets (of length `num_segments+1`) can be aliased + * for both the @p d_begin_offsets and @p d_end_offsets parameters (where + * the latter is specified as `segment_offsets+1`). + * - StableSortKeys is stable: it preserves the relative ordering of + * equivalent elements. That is, if @p x and @p y are elements such that + * @p x precedes @p y, and if the two elements are equivalent (neither + * @p x < @p y nor @p y < @p x) then a postcondition of stable sort is that + * @p x still precedes @p y. + * - Let `cur = d_keys.Current()` and `alt = d_keys.Alternate()`. + * The range `[cur, cur + num_items)` shall not overlap + * `[alt, alt + num_items)`. Both ranges shall not overlap + * `[d_begin_offsets, d_begin_offsets + num_segments)` nor + * `[d_end_offsets, d_end_offsets + num_segments)` in any way. + * - Segments are not required to be contiguous. For all index values `i` + * outside the specified segments `d_keys.Current()[i]`, + * `d_keys[i].Alternate()[i]` will not be accessed nor modified. + * + * @par Snippet + * The code snippet below illustrates the batched sorting of three segments + * (with one zero-length segment) of @p int keys. + * + * @par + * @code + * #include + * // or equivalently + * + * // Declare, allocate, and initialize device-accessible pointers + * // for sorting data + * int num_items; // e.g., 7 + * int num_segments; // e.g., 3 + * int *d_offsets; // e.g., [0, 3, 3, 7] + * int *d_key_buf; // e.g., [8, 6, 7, 5, 3, 0, 9] + * int *d_key_alt_buf; // e.g., [-, -, -, -, -, -, -] + * ... + * + * // Create a DoubleBuffer to wrap the pair of device pointers + * cub::DoubleBuffer d_keys(d_key_buf, d_key_alt_buf); + * + * // Determine temporary device storage requirements + * void *d_temp_storage = NULL; + * size_t temp_storage_bytes = 0; + * cub::DeviceSegmentedSort::StableSortKeys( + * d_temp_storage, temp_storage_bytes, d_keys, + * num_items, num_segments, d_offsets, d_offsets + 1); + * + * // Allocate temporary storage + * cudaMalloc(&d_temp_storage, temp_storage_bytes); + * + * // Run sorting operation + * cub::DeviceSegmentedSort::StableSortKeys( + * d_temp_storage, temp_storage_bytes, d_keys, + * num_items, num_segments, d_offsets, d_offsets + 1); + * + * // d_keys.Current() <-- [6, 7, 8, 0, 3, 5, 9] + * @endcode + * + * @tparam KeyT + * [inferred] Key type + * + * @tparam BeginOffsetIteratorT + * [inferred] Random-access input iterator type for reading segment + * beginning offsets \iterator + * + * @tparam EndOffsetIteratorT + * [inferred] Random-access input iterator type for reading segment + * ending offsets \iterator + * + * @param[in] d_temp_storage + * Device-accessible allocation of temporary storage. When nullptr, the + * required allocation size is written to @p temp_storage_bytes and no work + * is done + * + * @param[in,out] temp_storage_bytes + * Reference to size in bytes of @p d_temp_storage allocation + * + * @param[in,out] d_keys + * Reference to the double-buffer of keys whose "current" device-accessible + * buffer contains the unsorted input keys and, upon return, is updated to + * point to the sorted output keys + * + * @param[in] num_items + * The total number of items to sort (across all segments) + * + * @param[in] num_segments + * The number of segments that comprise the sorting data + * + * @param[in] d_begin_offsets + * Random-access input iterator to the sequence of beginning offsets of + * length @p num_segments, such that `d_begin_offsets[i]` is the first + * element of the ith data segment in `d_keys_*` and + * `d_values_*` + * + * @param[in] d_end_offsets + * Random-access input iterator to the sequence of ending offsets of length + * @p num_segments, such that `d_end_offsets[i] - 1` is the last element of + * the ith data segment in `d_keys_*` and `d_values_*`. + * If `d_end_offsets[i] - 1 <= d_begin_offsets[i]`, the i-th segment is + * considered empty. + * + * @param[in] stream + * [optional] CUDA stream to launch kernels within. Default is + * stream0. + */ + template + CUB_RUNTIME_FUNCTION static cudaError_t + StableSortKeys(void *d_temp_storage, + std::size_t &temp_storage_bytes, + DoubleBuffer &d_keys, + int num_items, + int num_segments, + BeginOffsetIteratorT d_begin_offsets, + EndOffsetIteratorT d_end_offsets, + cudaStream_t stream = 0) + { + return SortKeys( + d_temp_storage, + temp_storage_bytes, + d_keys, + num_items, + num_segments, + d_begin_offsets, + d_end_offsets, + stream); + } + + template + CUB_DETAIL_RUNTIME_DEBUG_SYNC_IS_NOT_SUPPORTED + CUB_RUNTIME_FUNCTION static cudaError_t + StableSortKeys(void *d_temp_storage, + std::size_t &temp_storage_bytes, + DoubleBuffer &d_keys, + int num_items, + int num_segments, + BeginOffsetIteratorT d_begin_offsets, + EndOffsetIteratorT d_end_offsets, + cudaStream_t stream, + bool debug_synchronous) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + + return StableSortKeys( + d_temp_storage, + temp_storage_bytes, + d_keys, + num_items, + num_segments, + d_begin_offsets, + d_end_offsets, + stream); + } + + /** + * @brief Sorts segments of keys into descending order. Approximately + * `2*num_segments` auxiliary storage required. + * + * @par + * - The sorting operation is given a pair of key buffers managed by a + * DoubleBuffer structure that indicates which of the two buffers is + * "current" (and thus contains the input data to be sorted). + * - The contents of both buffers may be altered by the sorting operation. + * - Upon completion, the sorting operation will update the "current" + * indicator within the DoubleBuffer wrapper to reference which of the two + * buffers now contains the sorted output sequence (a function of the number + * of key bits and the targeted device architecture). + * - When the input is a contiguous sequence of segments, a single sequence + * @p segment_offsets (of length `num_segments+1`) can be aliased + * for both the @p d_begin_offsets and @p d_end_offsets parameters (where + * the latter is specified as `segment_offsets+1`). + * - StableSortKeysDescending is stable: it preserves the relative ordering of + * equivalent elements. That is, if @p x and @p y are elements such that + * @p x precedes @p y, and if the two elements are equivalent (neither + * @p x < @p y nor @p y < @p x) then a postcondition of stable sort is that + * @p x still precedes @p y. + * - Let `cur = d_keys.Current()` and `alt = d_keys.Alternate()`. + * The range `[cur, cur + num_items)` shall not overlap + * `[alt, alt + num_items)`. Both ranges shall not overlap + * `[d_begin_offsets, d_begin_offsets + num_segments)` nor + * `[d_end_offsets, d_end_offsets + num_segments)` in any way. + * - Segments are not required to be contiguous. For all index values `i` + * outside the specified segments `d_keys.Current()[i]`, + * `d_keys[i].Alternate()[i]` will not be accessed nor modified. + * + * @par Snippet + * The code snippet below illustrates the batched sorting of three segments + * (with one zero-length segment) of @p int keys. + * + * @par + * @code + * #include + * // or equivalently + * + * // Declare, allocate, and initialize device-accessible pointers + * // for sorting data + * int num_items; // e.g., 7 + * int num_segments; // e.g., 3 + * int *d_offsets; // e.g., [0, 3, 3, 7] + * int *d_key_buf; // e.g., [8, 6, 7, 5, 3, 0, 9] + * int *d_key_alt_buf; // e.g., [-, -, -, -, -, -, -] + * ... + * + * // Create a DoubleBuffer to wrap the pair of device pointers + * cub::DoubleBuffer d_keys(d_key_buf, d_key_alt_buf); + * + * // Determine temporary device storage requirements + * void *d_temp_storage = NULL; + * size_t temp_storage_bytes = 0; + * cub::DeviceSegmentedSort::StableSortKeysDescending( + * d_temp_storage, temp_storage_bytes, d_keys, + * num_items, num_segments, d_offsets, d_offsets + 1); + * + * // Allocate temporary storage + * cudaMalloc(&d_temp_storage, temp_storage_bytes); + * + * // Run sorting operation + * cub::DeviceSegmentedSort::StableSortKeysDescending( + * d_temp_storage, temp_storage_bytes, d_keys, + * num_items, num_segments, d_offsets, d_offsets + 1); + * + * // d_keys.Current() <-- [8, 7, 6, 9, 5, 3, 0] + * @endcode + * + * @tparam KeyT + * [inferred] Key type + * + * @tparam BeginOffsetIteratorT + * [inferred] Random-access input iterator type for reading segment + * beginning offsets \iterator + * + * @tparam EndOffsetIteratorT + * [inferred] Random-access input iterator type for reading segment + * ending offsets \iterator + * + * @param[in] d_temp_storage + * Device-accessible allocation of temporary storage. When nullptr, the + * required allocation size is written to @p temp_storage_bytes and no work + * is done. + * + * @param[in,out] temp_storage_bytes + * Reference to size in bytes of @p d_temp_storage allocation + * + * @param[in,out] d_keys + * Reference to the double-buffer of keys whose "current" device-accessible + * buffer contains the unsorted input keys and, upon return, is updated to + * point to the sorted output keys + * + * @param[in] num_items + * The total number of items to sort (across all segments) + * + * @param[in] num_segments + * The number of segments that comprise the sorting data + * + * @param[in] d_begin_offsets + * Random-access input iterator to the sequence of beginning offsets of + * length @p num_segments, such that `d_begin_offsets[i]` is the first + * element of the ith data segment in `d_keys_*` and + * `d_values_*` + * + * @param[in] d_end_offsets + * Random-access input iterator to the sequence of ending offsets of length + * @p num_segments, such that d_end_offsets[i]-1 is the last + * element of the ith data segment in `d_keys_*` and + * `d_values_*`. If `d_end_offsets[i]-1 <= d_begin_offsets[i]`, the + * i-th segment is considered empty. + * + * @param[in] stream + * [optional] CUDA stream to launch kernels within. Default is + * stream0. + */ + template + CUB_RUNTIME_FUNCTION static cudaError_t + StableSortKeysDescending(void *d_temp_storage, + std::size_t &temp_storage_bytes, + DoubleBuffer &d_keys, + int num_items, + int num_segments, + BeginOffsetIteratorT d_begin_offsets, + EndOffsetIteratorT d_end_offsets, + cudaStream_t stream = 0) + { + return SortKeysDescending(d_temp_storage, + temp_storage_bytes, + d_keys, + num_items, + num_segments, + d_begin_offsets, + d_end_offsets, + stream); + } + + template + CUB_DETAIL_RUNTIME_DEBUG_SYNC_IS_NOT_SUPPORTED + CUB_RUNTIME_FUNCTION static cudaError_t + StableSortKeysDescending(void *d_temp_storage, + std::size_t &temp_storage_bytes, + DoubleBuffer &d_keys, + int num_items, + int num_segments, + BeginOffsetIteratorT d_begin_offsets, + EndOffsetIteratorT d_end_offsets, + cudaStream_t stream, + bool debug_synchronous) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + + return StableSortKeysDescending(d_temp_storage, + temp_storage_bytes, + d_keys, + num_items, + num_segments, + d_begin_offsets, + d_end_offsets, + stream); + } + + //@} end member group + /*************************************************************************//** + * @name Key-value pairs + ****************************************************************************/ + //@{ + + /** + * @brief Sorts segments of key-value pairs into ascending order. + * Approximately `2*num_items + 2*num_segments` auxiliary storage + * required. + * + * @par + * - The contents of the input data are not altered by the sorting operation. + * - When the input is a contiguous sequence of segments, a single sequence + * @p segment_offsets (of length `num_segments+1`) can be aliased + * for both the @p d_begin_offsets and @p d_end_offsets parameters (where + * the latter is specified as `segment_offsets+1`). + * - SortPairs is not guaranteed to be stable. That is, suppose that @p i and + * @p j are equivalent: neither one is less than the other. It is not + * guaranteed that the relative order of these two elements will be + * preserved by sort. + * - Let `in` be one of `{d_keys_in, d_values_in}` and `out` be any of + * `{d_keys_out, d_values_out}`. The range `[out, out + num_items)` shall + * not overlap `[in, in + num_items)`, + * `[d_begin_offsets, d_begin_offsets + num_segments)` nor + * `[d_end_offsets, d_end_offsets + num_segments)` in any way. + * - Segments are not required to be contiguous. For all index values `i` + * outside the specified segments `d_keys_in[i]`, `d_values_in[i]`, + * `d_keys_out[i]`, `d_values_out[i]` will not be accessed nor modified. + * + * @par Snippet + * The code snippet below illustrates the batched sorting of three segments + * (with one zero-length segment) of @p int keys with associated vector of + * @p int values. + * + * @par + * @code + * #include + * // or equivalently + * + * // Declare, allocate, and initialize device-accessible pointers + * // for sorting data + * int num_items; // e.g., 7 + * int num_segments; // e.g., 3 + * int *d_offsets; // e.g., [0, 3, 3, 7] + * int *d_keys_in; // e.g., [8, 6, 7, 5, 3, 0, 9] + * int *d_keys_out; // e.g., [-, -, -, -, -, -, -] + * int *d_values_in; // e.g., [0, 1, 2, 3, 4, 5, 6] + * int *d_values_out; // e.g., [-, -, -, -, -, -, -] + * ... + * + * // Determine temporary device storage requirements + * void *d_temp_storage = NULL; + * size_t temp_storage_bytes = 0; + * cub::DeviceSegmentedSort::SortPairs( + * d_temp_storage, temp_storage_bytes, + * d_keys_in, d_keys_out, d_values_in, d_values_out, + * num_items, num_segments, d_offsets, d_offsets + 1); + * + * // Allocate temporary storage + * cudaMalloc(&d_temp_storage, temp_storage_bytes); + * + * // Run sorting operation + * cub::DeviceSegmentedSort::SortPairs( + * d_temp_storage, temp_storage_bytes, + * d_keys_in, d_keys_out, d_values_in, d_values_out, + * num_items, num_segments, d_offsets, d_offsets + 1); + * + * // d_keys_out <-- [6, 7, 8, 0, 3, 5, 9] + * // d_values_out <-- [1, 2, 0, 5, 4, 3, 6] + * @endcode + * + * @tparam KeyT + * [inferred] Key type + * + * @tparam ValueT + * [inferred] Value type + * + * @tparam BeginOffsetIteratorT + * [inferred] Random-access input iterator type for reading segment + * beginning offsets \iterator + * + * @tparam EndOffsetIteratorT + * [inferred] Random-access input iterator type for reading segment + * ending offsets \iterator + * + * @param[in] d_temp_storage + * Device-accessible allocation of temporary storage. When `nullptr`, the + * required allocation size is written to @p temp_storage_bytes and no work + * is done + * + * @param[in,out] temp_storage_bytes + * Reference to size in bytes of @p d_temp_storage allocation + * + * @param[in] d_keys_in + * Device-accessible pointer to the input data of key data to sort + * + * @param[out] d_keys_out + * Device-accessible pointer to the sorted output sequence of key data + * + * @param[in] d_values_in + * Device-accessible pointer to the corresponding input sequence of + * associated value items + * + * @param[out] d_values_out + * Device-accessible pointer to the correspondingly-reordered output + * sequence of associated value items + * + * @param[in] num_items + * The total number of items to sort (across all segments) + * + * @param[in] num_segments + * The number of segments that comprise the sorting data + * + * @param[in] d_begin_offsets + * Random-access input iterator to the sequence of beginning offsets of + * length @p num_segments, such that `d_begin_offsets[i]` is the first + * element of the ith data segment in `d_keys_*` and + * `d_values_*` + * + * @param[in] d_end_offsets + * Random-access input iterator to the sequence of ending offsets of length + * @p num_segments, such that `d_end_offsets[i]-1` is the last element of + * the ith data segment in `d_keys_*` and `d_values_*`. + * If `d_end_offsets[i]-1 <= d_begin_offsets[i]`, the i-th segment is + * considered empty. + * + * @param[in] stream + * [optional] CUDA stream to launch kernels within. Default is + * stream0. + */ + template + CUB_RUNTIME_FUNCTION static cudaError_t + SortPairs(void *d_temp_storage, + std::size_t &temp_storage_bytes, + const KeyT *d_keys_in, + KeyT *d_keys_out, + const ValueT *d_values_in, + ValueT *d_values_out, + int num_items, + int num_segments, + BeginOffsetIteratorT d_begin_offsets, + EndOffsetIteratorT d_end_offsets, + cudaStream_t stream = 0) + { + constexpr bool is_descending = false; + constexpr bool is_overwrite_okay = false; + using DispatchT = DispatchSegmentedSort; + + DoubleBuffer d_keys(const_cast(d_keys_in), d_keys_out); + DoubleBuffer d_values(const_cast(d_values_in), d_values_out); + + return DispatchT::Dispatch(d_temp_storage, + temp_storage_bytes, + d_keys, + d_values, + num_items, + num_segments, + d_begin_offsets, + d_end_offsets, + is_overwrite_okay, + stream); + } + + template + CUB_DETAIL_RUNTIME_DEBUG_SYNC_IS_NOT_SUPPORTED + CUB_RUNTIME_FUNCTION static cudaError_t + SortPairs(void *d_temp_storage, + std::size_t &temp_storage_bytes, + const KeyT *d_keys_in, + KeyT *d_keys_out, + const ValueT *d_values_in, + ValueT *d_values_out, + int num_items, + int num_segments, + BeginOffsetIteratorT d_begin_offsets, + EndOffsetIteratorT d_end_offsets, + cudaStream_t stream, + bool debug_synchronous) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + + return SortPairs( + d_temp_storage, + temp_storage_bytes, + d_keys_in, + d_keys_out, + d_values_in, + d_values_out, + num_items, + num_segments, + d_begin_offsets, + d_end_offsets, + stream); + } + + /** + * @brief Sorts segments of key-value pairs into descending order. Approximately + * `2*num_items + 2*num_segments` auxiliary storage required. + * + * @par + * - The contents of the input data are not altered by the sorting operation. + * - When the input is a contiguous sequence of segments, a single sequence + * @p segment_offsets (of length `num_segments+1`) can be aliased + * for both the @p d_begin_offsets and @p d_end_offsets parameters (where + * the latter is specified as `segment_offsets+1`). + * - SortPairs is not guaranteed to be stable. That is, suppose that @p i and + * @p j are equivalent: neither one is less than the other. It is not + * guaranteed that the relative order of these two elements will be + * preserved by sort. + * - Let `in` be one of `{d_keys_in, d_values_in}` and `out` be any of + * `{d_keys_out, d_values_out}`. The range `[out, out + num_items)` shall + * not overlap `[in, in + num_items)`, + * `[d_begin_offsets, d_begin_offsets + num_segments)` nor + * `[d_end_offsets, d_end_offsets + num_segments)` in any way. + * - Segments are not required to be contiguous. For all index values `i` + * outside the specified segments `d_keys_in[i]`, `d_values_in[i]`, + * `d_keys_out[i]`, `d_values_out[i]` will not be accessed nor modified. + * + * @par Snippet + * The code snippet below illustrates the batched sorting of three segments + * (with one zero-length segment) of @p int keys with associated vector of + * @p int values. + * + * @par + * @code + * #include + * // or equivalently + * + * // Declare, allocate, and initialize device-accessible pointers for + * // sorting data + * int num_items; // e.g., 7 + * int num_segments; // e.g., 3 + * int *d_offsets; // e.g., [0, 3, 3, 7] + * int *d_keys_in; // e.g., [8, 6, 7, 5, 3, 0, 9] + * int *d_keys_out; // e.g., [-, -, -, -, -, -, -] + * int *d_values_in; // e.g., [0, 1, 2, 3, 4, 5, 6] + * int *d_values_out; // e.g., [-, -, -, -, -, -, -] + * ... + * + * // Determine temporary device storage requirements + * void *d_temp_storage = NULL; + * size_t temp_storage_bytes = 0; + * cub::DeviceSegmentedSort::SortPairsDescending( + * d_temp_storage, temp_storage_bytes, + * d_keys_in, d_keys_out, d_values_in, d_values_out, + * num_items, num_segments, d_offsets, d_offsets + 1); + * + * // Allocate temporary storage + * cudaMalloc(&d_temp_storage, temp_storage_bytes); + * + * // Run sorting operation + * cub::DeviceSegmentedSort::SortPairsDescending( + * d_temp_storage, temp_storage_bytes, + * d_keys_in, d_keys_out, d_values_in, d_values_out, + * num_items, num_segments, d_offsets, d_offsets + 1); + * + * // d_keys_out <-- [8, 7, 6, 9, 5, 3, 0] + * // d_values_out <-- [0, 2, 1, 6, 3, 4, 5] + * @endcode + * + * @tparam KeyT + * [inferred] Key type + * + * @tparam ValueT + * [inferred] Value type + * + * @tparam BeginOffsetIteratorT + * [inferred] Random-access input iterator type for reading segment + * beginning offsets \iterator + * + * @tparam EndOffsetIteratorT + * [inferred] Random-access input iterator type for reading segment + * ending offsets \iterator + * + * @param[in] d_temp_storage + * Device-accessible allocation of temporary storage. When nullptr, the + * required allocation size is written to @p temp_storage_bytes and no work + * is done. + * + * @param[in,out] temp_storage_bytes + * Reference to size in bytes of @p d_temp_storage allocation + * + * @param[in] d_keys_in + * Device-accessible pointer to the input data of key data to sort + * + * @param[out] d_keys_out + * Device-accessible pointer to the sorted output sequence of key data + * + * @param[in] d_values_in + * Device-accessible pointer to the corresponding input sequence of + * associated value items + * + * @param[out] d_values_out + * Device-accessible pointer to the correspondingly-reordered output + * sequence of associated value items + * + * @param[in] num_items + * The total number of items to sort (across all segments) + * + * @param[in] num_segments + * The number of segments that comprise the sorting data + * + * @param[in] d_begin_offsets + * Random-access input iterator to the sequence of beginning offsets of + * length @p num_segments, such that `d_begin_offsets[i]` is the first + * element of the ith data segment in `d_keys_*` and + * `d_values_*` + * + * @param[in] d_end_offsets + * Random-access input iterator to the sequence of ending offsets of length + * @p num_segments, such that `d_end_offsets[i]-1` is the last element of + * the ith data segment in `d_keys_*` and `d_values_*`. + * If `d_end_offsets[i]-1 <= d_begin_offsets[i]`, the i-th segment is + * considered empty. + * + * @param[in] stream + * [optional] CUDA stream to launch kernels within. Default is + * stream0. + */ + template + CUB_RUNTIME_FUNCTION static cudaError_t + SortPairsDescending(void *d_temp_storage, + std::size_t &temp_storage_bytes, + const KeyT *d_keys_in, + KeyT *d_keys_out, + const ValueT *d_values_in, + ValueT *d_values_out, + int num_items, + int num_segments, + BeginOffsetIteratorT d_begin_offsets, + EndOffsetIteratorT d_end_offsets, + cudaStream_t stream = 0) + { + constexpr bool is_descending = true; + constexpr bool is_overwrite_okay = false; + using DispatchT = DispatchSegmentedSort; + + DoubleBuffer d_keys(const_cast(d_keys_in), d_keys_out); + DoubleBuffer d_values(const_cast(d_values_in), d_values_out); + + return DispatchT::Dispatch(d_temp_storage, + temp_storage_bytes, + d_keys, + d_values, + num_items, + num_segments, + d_begin_offsets, + d_end_offsets, + is_overwrite_okay, + stream); + } + + template + CUB_DETAIL_RUNTIME_DEBUG_SYNC_IS_NOT_SUPPORTED + CUB_RUNTIME_FUNCTION static cudaError_t + SortPairsDescending(void *d_temp_storage, + std::size_t &temp_storage_bytes, + const KeyT *d_keys_in, + KeyT *d_keys_out, + const ValueT *d_values_in, + ValueT *d_values_out, + int num_items, + int num_segments, + BeginOffsetIteratorT d_begin_offsets, + EndOffsetIteratorT d_end_offsets, + cudaStream_t stream, + bool debug_synchronous) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + + return SortPairsDescending(d_temp_storage, + temp_storage_bytes, + d_keys_in, + d_keys_out, + d_values_in, + d_values_out, + num_items, + num_segments, + d_begin_offsets, + d_end_offsets, + stream); + } + + /** + * @brief Sorts segments of key-value pairs into ascending order. + * Approximately `2*num_segments` auxiliary storage required. + * + * @par + * - The sorting operation is given a pair of key buffers and a corresponding + * pair of associated value buffers. Each pair is managed by a DoubleBuffer + * structure that indicates which of the two buffers is "current" (and thus + * contains the input data to be sorted). + * - The contents of both buffers within each pair may be altered by the sorting + * operation. + * - Upon completion, the sorting operation will update the "current" indicator + * within each DoubleBuffer wrapper to reference which of the two buffers + * now contains the sorted output sequence (a function of the number of key bits + * specified and the targeted device architecture). + * - When the input is a contiguous sequence of segments, a single sequence + * @p segment_offsets (of length `num_segments+1`) can be aliased + * for both the @p d_begin_offsets and @p d_end_offsets parameters (where + * the latter is specified as `segment_offsets+1`). + * - SortPairs is not guaranteed to be stable. That is, suppose that @p i and + * @p j are equivalent: neither one is less than the other. It is not + * guaranteed that the relative order of these two elements will be + * preserved by sort. + * - Let `cur` be one of `{d_keys.Current(), d_values.Current()}` and `alt` + * be any of `{d_keys.Alternate(), d_values.Alternate()}`. The range + * `[cur, cur + num_items)` shall not overlap + * `[alt, alt + num_items)`. Both ranges shall not overlap + * `[d_begin_offsets, d_begin_offsets + num_segments)` nor + * `[d_end_offsets, d_end_offsets + num_segments)` in any way. + * - Segments are not required to be contiguous. For all index values `i` + * outside the specified segments `d_keys.Current()[i]`, + * `d_values.Current()[i]`, `d_keys.Alternate()[i]`, + * `d_values.Alternate()[i]` will not be accessed nor modified. + * + * @par Snippet + * The code snippet below illustrates the batched sorting of three segments + * (with one zero-length segment) of @p int keys with associated vector of + * @p int values. + * + * @par + * @code + * #include + * // or equivalently + * + * // Declare, allocate, and initialize device-accessible pointers + * // for sorting data + * int num_items; // e.g., 7 + * int num_segments; // e.g., 3 + * int *d_offsets; // e.g., [0, 3, 3, 7] + * int *d_key_buf; // e.g., [8, 6, 7, 5, 3, 0, 9] + * int *d_key_alt_buf; // e.g., [-, -, -, -, -, -, -] + * int *d_value_buf; // e.g., [0, 1, 2, 3, 4, 5, 6] + * int *d_value_alt_buf; // e.g., [-, -, -, -, -, -, -] + * ... + * + * // Create a set of DoubleBuffers to wrap pairs of device pointers + * cub::DoubleBuffer d_keys(d_key_buf, d_key_alt_buf); + * cub::DoubleBuffer d_values(d_value_buf, d_value_alt_buf); + * + * // Determine temporary device storage requirements + * void *d_temp_storage = NULL; + * size_t temp_storage_bytes = 0; + * cub::DeviceSegmentedSort::SortPairs( + * d_temp_storage, temp_storage_bytes, d_keys, d_values, + * num_items, num_segments, d_offsets, d_offsets + 1); + * + * // Allocate temporary storage + * cudaMalloc(&d_temp_storage, temp_storage_bytes); + * + * // Run sorting operation + * cub::DeviceSegmentedSort::SortPairs( + * d_temp_storage, temp_storage_bytes, d_keys, d_values, + * num_items, num_segments, d_offsets, d_offsets + 1); + * + * // d_keys.Current() <-- [6, 7, 8, 0, 3, 5, 9] + * // d_values.Current() <-- [5, 4, 3, 1, 2, 0, 6] + * + * @endcode + * + * @tparam KeyT + * [inferred] Key type + * + * @tparam ValueT + * [inferred] Value type + * + * @tparam BeginOffsetIteratorT + * [inferred] Random-access input iterator type for reading segment + * beginning offsets \iterator + * + * @tparam EndOffsetIteratorT + * [inferred] Random-access input iterator type for reading segment + * ending offsets \iterator + * + * @param[in] d_temp_storage + * Device-accessible allocation of temporary storage. When `nullptr`, the + * required allocation size is written to @p temp_storage_bytes and no work + * is done. + * + * @param[in,out] temp_storage_bytes + * Reference to size in bytes of @p d_temp_storage allocation + * + * @param[in,out] d_keys + * Reference to the double-buffer of keys whose "current" device-accessible + * buffer contains the unsorted input keys and, upon return, is updated to + * point to the sorted output keys + * + * @param[in,out] d_values + * Double-buffer of values whose "current" device-accessible buffer contains + * the unsorted input values and, upon return, is updated to point to the + * sorted output values + * + * @param[in] num_items + * The total number of items to sort (across all segments) + * + * @param[in] num_segments + * The number of segments that comprise the sorting data + * + * @param[in] d_begin_offsets + * Random-access input iterator to the sequence of beginning offsets of + * length @p num_segments, such that `d_begin_offsets[i]` is the first + * element of the ith data segment in `d_keys_*` and + * `d_values_*` + * + * @param[in] d_end_offsets + * Random-access input iterator to the sequence of ending offsets of length + * @p num_segments, such that `d_end_offsets[i]-1` is the last element of + * the ith data segment in `d_keys_*` and `d_values_*`. + * If `d_end_offsets[i]-1 <= d_begin_offsets[i]`, the i-th segment is + * considered empty. + * + * @param[in] stream + * [optional] CUDA stream to launch kernels within. Default is + * stream0. + */ + template + CUB_RUNTIME_FUNCTION static cudaError_t + SortPairs(void *d_temp_storage, + std::size_t &temp_storage_bytes, + DoubleBuffer &d_keys, + DoubleBuffer &d_values, + int num_items, + int num_segments, + BeginOffsetIteratorT d_begin_offsets, + EndOffsetIteratorT d_end_offsets, + cudaStream_t stream = 0) + { + constexpr bool is_descending = false; + constexpr bool is_overwrite_okay = true; + using DispatchT = DispatchSegmentedSort; + + return DispatchT::Dispatch(d_temp_storage, + temp_storage_bytes, + d_keys, + d_values, + num_items, + num_segments, + d_begin_offsets, + d_end_offsets, + is_overwrite_okay, + stream); + } + + template + CUB_DETAIL_RUNTIME_DEBUG_SYNC_IS_NOT_SUPPORTED + CUB_RUNTIME_FUNCTION static cudaError_t + SortPairs(void *d_temp_storage, + std::size_t &temp_storage_bytes, + DoubleBuffer &d_keys, + DoubleBuffer &d_values, + int num_items, + int num_segments, + BeginOffsetIteratorT d_begin_offsets, + EndOffsetIteratorT d_end_offsets, + cudaStream_t stream, + bool debug_synchronous) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + + return SortPairs( + d_temp_storage, + temp_storage_bytes, + d_keys, + d_values, + num_items, + num_segments, + d_begin_offsets, + d_end_offsets, + stream); + } + + /** + * @brief Sorts segments of key-value pairs into descending order. + * Approximately `2*num_segments` auxiliary storage required. + * + * @par + * - The sorting operation is given a pair of key buffers and a corresponding + * pair of associated value buffers. Each pair is managed by a DoubleBuffer + * structure that indicates which of the two buffers is "current" (and thus + * contains the input data to be sorted). + * - The contents of both buffers within each pair may be altered by the + * sorting operation. + * - Upon completion, the sorting operation will update the "current" + * indicator within each DoubleBuffer wrapper to reference which of the two + * buffers now contains the sorted output sequence (a function of the number + * of key bits specified and the targeted device architecture). + * - When the input is a contiguous sequence of segments, a single sequence + * @p segment_offsets (of length num_segments+1) can be aliased + * for both the @p d_begin_offsets and @p d_end_offsets parameters (where + * the latter is specified as segment_offsets+1). + * - SortPairsDescending is not guaranteed to be stable. That is, suppose that + * @p i and @p j are equivalent: neither one is less than the other. It is + * not guaranteed that the relative order of these two elements will be + * preserved by sort. + * - Let `cur` be one of `{d_keys.Current(), d_values.Current()}` and `alt` + * be any of `{d_keys.Alternate(), d_values.Alternate()}`. The range + * `[cur, cur + num_items)` shall not overlap + * `[alt, alt + num_items)`. Both ranges shall not overlap + * `[d_begin_offsets, d_begin_offsets + num_segments)` nor + * `[d_end_offsets, d_end_offsets + num_segments)` in any way. + * - Segments are not required to be contiguous. For all index values `i` + * outside the specified segments `d_keys.Current()[i]`, + * `d_values.Current()[i]`, `d_keys.Alternate()[i]`, + * `d_values.Alternate()[i]` will not be accessed nor modified. + * + * @par Snippet + * The code snippet below illustrates the batched sorting of three segments + * (with one zero-length segment) of @p int keys with associated vector of + * @p int values. + * + * @par + * @code + * #include + * // or equivalently + * + * // Declare, allocate, and initialize device-accessible pointers for + * // sorting data + * int num_items; // e.g., 7 + * int num_segments; // e.g., 3 + * int *d_offsets; // e.g., [0, 3, 3, 7] + * int *d_key_buf; // e.g., [8, 6, 7, 5, 3, 0, 9] + * int *d_key_alt_buf; // e.g., [-, -, -, -, -, -, -] + * int *d_value_buf; // e.g., [0, 1, 2, 3, 4, 5, 6] + * int *d_value_alt_buf; // e.g., [-, -, -, -, -, -, -] + * ... + * + * // Create a set of DoubleBuffers to wrap pairs of device pointers + * cub::DoubleBuffer d_keys(d_key_buf, d_key_alt_buf); + * cub::DoubleBuffer d_values(d_value_buf, d_value_alt_buf); + * + * // Determine temporary device storage requirements + * void *d_temp_storage = NULL; + * size_t temp_storage_bytes = 0; + * cub::DeviceSegmentedSort::SortPairsDescending( + * d_temp_storage, temp_storage_bytes, d_keys, d_values, + * num_items, num_segments, d_offsets, d_offsets + 1); + * + * // Allocate temporary storage + * cudaMalloc(&d_temp_storage, temp_storage_bytes); + * + * // Run sorting operation + * cub::DeviceSegmentedSort::SortPairsDescending( + * d_temp_storage, temp_storage_bytes, d_keys, d_values, + * num_items, num_segments, d_offsets, d_offsets + 1); + * + * // d_keys.Current() <-- [8, 7, 6, 9, 5, 3, 0] + * // d_values.Current() <-- [0, 2, 1, 6, 3, 4, 5] + * + * @endcode + * + * @tparam KeyT + * [inferred] Key type + * + * @tparam ValueT + * [inferred] Value type + * + * @tparam BeginOffsetIteratorT + * [inferred] Random-access input iterator type for reading segment + * beginning offsets \iterator + * + * @tparam EndOffsetIteratorT + * [inferred] Random-access input iterator type for reading segment + * ending offsets \iterator + * + * @param[in] d_temp_storage + * Device-accessible allocation of temporary storage. When nullptr, the + * required allocation size is written to @p temp_storage_bytes and no work + * is done + * + * @param[in,out] temp_storage_bytes + * Reference to size in bytes of @p d_temp_storage allocation + * + * @param[in,out] d_keys + * Reference to the double-buffer of keys whose "current" device-accessible + * buffer contains the unsorted input keys and, upon return, is updated to + * point to the sorted output keys + * + * @param[in,out] d_values + * Double-buffer of values whose "current" device-accessible buffer contains + * the unsorted input values and, upon return, is updated to point to the + * sorted output values + * + * @param[in] num_items + * The total number of items to sort (across all segments) + * + * @param[in] num_segments + * The number of segments that comprise the sorting data + * + * @param[in] d_begin_offsets + * Random-access input iterator to the sequence of beginning offsets of + * length @p num_segments, such that `d_begin_offsets[i]` is the first + * element of the ith data segment in `d_keys_*` and + * `d_values_*` + * + * @param[in] d_end_offsets + * Random-access input iterator to the sequence of ending offsets of length + * @p num_segments, such that `d_end_offsets[i]-1` is the last element of + * the ith data segment in `d_keys_*` and `d_values_*`. + * If `d_end_offsets[i]-1 <= d_begin_offsets[i]`, the i-th segment is + * considered empty. + * + * @param[in] stream + * [optional] CUDA stream to launch kernels within. Default is + * stream0. + */ + template + CUB_RUNTIME_FUNCTION static cudaError_t + SortPairsDescending(void *d_temp_storage, + std::size_t &temp_storage_bytes, + DoubleBuffer &d_keys, + DoubleBuffer &d_values, + int num_items, + int num_segments, + BeginOffsetIteratorT d_begin_offsets, + EndOffsetIteratorT d_end_offsets, + cudaStream_t stream = 0) + { + constexpr bool is_descending = true; + constexpr bool is_overwrite_okay = true; + using DispatchT = DispatchSegmentedSort; + + return DispatchT::Dispatch(d_temp_storage, + temp_storage_bytes, + d_keys, + d_values, + num_items, + num_segments, + d_begin_offsets, + d_end_offsets, + is_overwrite_okay, + stream); + } + + template + CUB_DETAIL_RUNTIME_DEBUG_SYNC_IS_NOT_SUPPORTED + CUB_RUNTIME_FUNCTION static cudaError_t + SortPairsDescending(void *d_temp_storage, + std::size_t &temp_storage_bytes, + DoubleBuffer &d_keys, + DoubleBuffer &d_values, + int num_items, + int num_segments, + BeginOffsetIteratorT d_begin_offsets, + EndOffsetIteratorT d_end_offsets, + cudaStream_t stream, + bool debug_synchronous) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + + return SortPairsDescending(d_temp_storage, + temp_storage_bytes, + d_keys, + d_values, + num_items, + num_segments, + d_begin_offsets, + d_end_offsets, + stream); + } + + /** + * @brief Sorts segments of key-value pairs into ascending order. Approximately + * `2*num_items + 2*num_segments` auxiliary storage required. + * + * @par + * - The contents of the input data are not altered by the sorting operation. + * - When the input is a contiguous sequence of segments, a single sequence + * @p segment_offsets (of length `num_segments+1`) can be aliased + * for both the @p d_begin_offsets and @p d_end_offsets parameters (where + * the latter is specified as `segment_offsets+1`). + * - StableSortPairs is stable: it preserves the relative ordering of + * equivalent elements. That is, if @p x and @p y are elements such that + * @p x precedes @p y, and if the two elements are equivalent (neither + * @p x < @p y nor @p y < @p x) then a postcondition of stable sort is that + * @p x still precedes @p y. + * - Let `in` be one of `{d_keys_in, d_values_in}` and `out` be any of + * `{d_keys_out, d_values_out}`. The range `[out, out + num_items)` shall + * not overlap `[in, in + num_items)`, + * `[d_begin_offsets, d_begin_offsets + num_segments)` nor + * `[d_end_offsets, d_end_offsets + num_segments)` in any way. + * - Segments are not required to be contiguous. For all index values `i` + * outside the specified segments `d_keys_in[i]`, `d_values_in[i]`, + * `d_keys_out[i]`, `d_values_out[i]` will not be accessed nor modified. + * + * @par Snippet + * The code snippet below illustrates the batched sorting of three segments + * (with one zero-length segment) of @p int keys with associated vector of + * @p int values. + * + * @par + * @code + * #include + * // or equivalently + * + * // Declare, allocate, and initialize device-accessible pointers + * // for sorting data + * int num_items; // e.g., 7 + * int num_segments; // e.g., 3 + * int *d_offsets; // e.g., [0, 3, 3, 7] + * int *d_keys_in; // e.g., [8, 6, 7, 5, 3, 0, 9] + * int *d_keys_out; // e.g., [-, -, -, -, -, -, -] + * int *d_values_in; // e.g., [0, 1, 2, 3, 4, 5, 6] + * int *d_values_out; // e.g., [-, -, -, -, -, -, -] + * ... + * + * // Determine temporary device storage requirements + * void *d_temp_storage = NULL; + * size_t temp_storage_bytes = 0; + * cub::DeviceSegmentedSort::StableSortPairs( + * d_temp_storage, temp_storage_bytes, + * d_keys_in, d_keys_out, d_values_in, d_values_out, + * num_items, num_segments, d_offsets, d_offsets + 1); + * + * // Allocate temporary storage + * cudaMalloc(&d_temp_storage, temp_storage_bytes); + * + * // Run sorting operation + * cub::DeviceSegmentedSort::StableSortPairs( + * d_temp_storage, temp_storage_bytes, + * d_keys_in, d_keys_out, d_values_in, d_values_out, + * num_items, num_segments, d_offsets, d_offsets + 1); + * + * // d_keys_out <-- [6, 7, 8, 0, 3, 5, 9] + * // d_values_out <-- [1, 2, 0, 5, 4, 3, 6] + * @endcode + * + * @tparam KeyT + * [inferred] Key type + * + * @tparam ValueT + * [inferred] Value type + * + * @tparam BeginOffsetIteratorT + * [inferred] Random-access input iterator type for reading segment + * beginning offsets \iterator + * + * @tparam EndOffsetIteratorT + * [inferred] Random-access input iterator type for reading segment + * ending offsets \iterator + * + * @param[in] d_temp_storage + * Device-accessible allocation of temporary storage. When nullptr, the + * required allocation size is written to @p temp_storage_bytes and no work is done. + * + * @param[in,out] temp_storage_bytes + * Reference to size in bytes of @p d_temp_storage allocation + * + * @param[in] d_keys_in + * Device-accessible pointer to the input data of key data to sort + * + * @param[out] d_keys_out + * Device-accessible pointer to the sorted output sequence of key data + * + * @param[in] d_values_in + * Device-accessible pointer to the corresponding input sequence of + * associated value items + * + * @param[out] d_values_out + * Device-accessible pointer to the correspondingly-reordered output + * sequence of associated value items + * + * @param[in] num_items + * The total number of items to sort (across all segments) + * + * @param[in] num_segments + * The number of segments that comprise the sorting data + * + * @param[in] d_begin_offsets + * Random-access input iterator to the sequence of beginning offsets of + * length @p num_segments, such that `d_begin_offsets[i]` is the first + * element of the ith data segment in `d_keys_*` and + * `d_values_*` + * + * @param[in] d_end_offsets + * Random-access input iterator to the sequence of ending offsets of length + * @p num_segments, such that `d_end_offsets[i]-1` is the last element of + * the ith data segment in `d_keys_*` and `d_values_*`. + * If `d_end_offsets[i]-1 <= d_begin_offsets[i]`, the i-th segment is + * considered empty. + * + * @param[in] stream + * [optional] CUDA stream to launch kernels within. Default is + * stream0. + */ + template + CUB_RUNTIME_FUNCTION static cudaError_t + StableSortPairs(void *d_temp_storage, + std::size_t &temp_storage_bytes, + const KeyT *d_keys_in, + KeyT *d_keys_out, + const ValueT *d_values_in, + ValueT *d_values_out, + int num_items, + int num_segments, + BeginOffsetIteratorT d_begin_offsets, + EndOffsetIteratorT d_end_offsets, + cudaStream_t stream = 0) + { + return SortPairs(d_temp_storage, + temp_storage_bytes, + d_keys_in, + d_keys_out, + d_values_in, + d_values_out, + num_items, + num_segments, + d_begin_offsets, + d_end_offsets, + stream); + } + + template + CUB_DETAIL_RUNTIME_DEBUG_SYNC_IS_NOT_SUPPORTED + CUB_RUNTIME_FUNCTION static cudaError_t + StableSortPairs(void *d_temp_storage, + std::size_t &temp_storage_bytes, + const KeyT *d_keys_in, + KeyT *d_keys_out, + const ValueT *d_values_in, + ValueT *d_values_out, + int num_items, + int num_segments, + BeginOffsetIteratorT d_begin_offsets, + EndOffsetIteratorT d_end_offsets, + cudaStream_t stream, + bool debug_synchronous) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + + return StableSortPairs( + d_temp_storage, + temp_storage_bytes, + d_keys_in, + d_keys_out, + d_values_in, + d_values_out, + num_items, + num_segments, + d_begin_offsets, + d_end_offsets, + stream); + } + + /** + * @brief Sorts segments of key-value pairs into descending order. + * Approximately `2*num_items + 2*num_segments` auxiliary + * storage required. + * + * @par + * - The contents of the input data are not altered by the sorting operation. + * - When the input is a contiguous sequence of segments, a single sequence + * @p segment_offsets (of length `num_segments+1`) can be aliased + * for both the @p d_begin_offsets and @p d_end_offsets parameters (where + * the latter is specified as `segment_offsets+1`). + * - StableSortPairsDescending is stable: it preserves the relative ordering + * of equivalent elements. That is, if @p x and @p y are elements such that + * @p x precedes @p y, and if the two elements are equivalent (neither + * @p x < @p y nor @p y < @p x) then a postcondition of stable sort is that + * @p x still precedes @p y. + * - Let `in` be one of `{d_keys_in, d_values_in}` and `out` be any of + * `{d_keys_out, d_values_out}`. The range `[out, out + num_items)` shall + * not overlap `[in, in + num_items)`, + * `[d_begin_offsets, d_begin_offsets + num_segments)` nor + * `[d_end_offsets, d_end_offsets + num_segments)` in any way. + * - Segments are not required to be contiguous. For all index values `i` + * outside the specified segments `d_keys_in[i]`, `d_values_in[i]`, + * `d_keys_out[i]`, `d_values_out[i]` will not be accessed nor modified. + * + * @par Snippet + * The code snippet below illustrates the batched sorting of three segments + * (with one zero-length segment) of @p int keys with associated vector of + * @p int values. + * + * @par + * @code + * #include + * // or equivalently + * + * // Declare, allocate, and initialize device-accessible pointers + * // for sorting data + * int num_items; // e.g., 7 + * int num_segments; // e.g., 3 + * int *d_offsets; // e.g., [0, 3, 3, 7] + * int *d_keys_in; // e.g., [8, 6, 7, 5, 3, 0, 9] + * int *d_keys_out; // e.g., [-, -, -, -, -, -, -] + * int *d_values_in; // e.g., [0, 1, 2, 3, 4, 5, 6] + * int *d_values_out; // e.g., [-, -, -, -, -, -, -] + * ... + * + * // Determine temporary device storage requirements + * void *d_temp_storage = NULL; + * size_t temp_storage_bytes = 0; + * cub::DeviceSegmentedSort::StableSortPairsDescending( + * d_temp_storage, temp_storage_bytes, + * d_keys_in, d_keys_out, d_values_in, d_values_out, + * num_items, num_segments, d_offsets, d_offsets + 1); + * + * // Allocate temporary storage + * cudaMalloc(&d_temp_storage, temp_storage_bytes); + * + * // Run sorting operation + * cub::DeviceSegmentedSort::StableSortPairsDescending( + * d_temp_storage, temp_storage_bytes, + * d_keys_in, d_keys_out, d_values_in, d_values_out, + * num_items, num_segments, d_offsets, d_offsets + 1); + * + * // d_keys_out <-- [8, 7, 6, 9, 5, 3, 0] + * // d_values_out <-- [0, 2, 1, 6, 3, 4, 5] + * @endcode + * + * @tparam KeyT + * [inferred] Key type + * + * @tparam ValueT + * [inferred] Value type + * + * @tparam BeginOffsetIteratorT + * [inferred] Random-access input iterator type for reading segment + * beginning offsets \iterator + * + * @tparam EndOffsetIteratorT + * [inferred] Random-access input iterator type for reading segment + * ending offsets \iterator + * + * @param[in] d_temp_storage + * Device-accessible allocation of temporary storage. When `nullptr`, the + * required allocation size is written to @p temp_storage_bytes and no work + * is done + * + * @param[in,out] temp_storage_bytes + * Reference to size in bytes of @p d_temp_storage allocation + * + * @param[in] d_keys_in + * Device-accessible pointer to the input data of key data to sort + * + * @param[out] d_keys_out + * Device-accessible pointer to the sorted output sequence of key data + * + * @param[in] d_values_in + * Device-accessible pointer to the corresponding input sequence of + * associated value items + * + * @param[out] d_values_out + * Device-accessible pointer to the correspondingly-reordered output + * sequence of associated value items + * + * @param[in] num_items + * The total number of items to sort (across all segments) + * + * @param[in] num_segments + * The number of segments that comprise the sorting data + * + * @param[in] d_begin_offsets + * Random-access input iterator to the sequence of beginning offsets of + * length @p num_segments, such that `d_begin_offsets[i]` is the first + * element of the ith data segment in `d_keys_*` and + * `d_values_*` + * + * @param[in] d_end_offsets + * Random-access input iterator to the sequence of ending offsets of length + * @p num_segments, such that `d_end_offsets[i]-1` is the last element of + * the ith data segment in `d_keys_*` and `d_values_*`. + * If `d_end_offsets[i]-1 <= d_begin_offsets[i]`, the i-th segment is + * considered empty. + * + * @param[in] stream + * [optional] CUDA stream to launch kernels within. Default is + * stream0. + */ + template + CUB_RUNTIME_FUNCTION static cudaError_t + StableSortPairsDescending(void *d_temp_storage, + std::size_t &temp_storage_bytes, + const KeyT *d_keys_in, + KeyT *d_keys_out, + const ValueT *d_values_in, + ValueT *d_values_out, + int num_items, + int num_segments, + BeginOffsetIteratorT d_begin_offsets, + EndOffsetIteratorT d_end_offsets, + cudaStream_t stream = 0) + { + return SortPairsDescending(d_temp_storage, + temp_storage_bytes, + d_keys_in, + d_keys_out, + d_values_in, + d_values_out, + num_items, + num_segments, + d_begin_offsets, + d_end_offsets, + stream); + } + + template + CUB_DETAIL_RUNTIME_DEBUG_SYNC_IS_NOT_SUPPORTED + CUB_RUNTIME_FUNCTION static cudaError_t + StableSortPairsDescending(void *d_temp_storage, + std::size_t &temp_storage_bytes, + const KeyT *d_keys_in, + KeyT *d_keys_out, + const ValueT *d_values_in, + ValueT *d_values_out, + int num_items, + int num_segments, + BeginOffsetIteratorT d_begin_offsets, + EndOffsetIteratorT d_end_offsets, + cudaStream_t stream, + bool debug_synchronous) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + + return StableSortPairsDescending(d_temp_storage, + temp_storage_bytes, + d_keys_in, + d_keys_out, + d_values_in, + d_values_out, + num_items, + num_segments, + d_begin_offsets, + d_end_offsets, + stream); + } + + /** + * @brief Sorts segments of key-value pairs into ascending order. + * Approximately `2*num_segments` auxiliary storage required. + * + * @par + * - The sorting operation is given a pair of key buffers and a corresponding + * pair of associated value buffers. Each pair is managed by a DoubleBuffer + * structure that indicates which of the two buffers is "current" (and thus + * contains the input data to be sorted). + * - The contents of both buffers within each pair may be altered by the + * sorting operation. + * - Upon completion, the sorting operation will update the "current" + * indicator within each DoubleBuffer wrapper to reference which of the two + * buffers now contains the sorted output sequence (a function of the number + * of key bits specified and the targeted device architecture). + * - When the input is a contiguous sequence of segments, a single sequence + * @p segment_offsets (of length `num_segments+1`) can be aliased + * for both the @p d_begin_offsets and @p d_end_offsets parameters (where + * the latter is specified as `segment_offsets+1`). + * - StableSortPairs is stable: it preserves the relative ordering + * of equivalent elements. That is, if @p x and @p y are elements such that + * @p x precedes @p y, and if the two elements are equivalent (neither + * @p x < @p y nor @p y < @p x) then a postcondition of stable sort is that + * @p x still precedes @p y. + * - Let `cur` be one of `{d_keys.Current(), d_values.Current()}` and `alt` + * be any of `{d_keys.Alternate(), d_values.Alternate()}`. The range + * `[cur, cur + num_items)` shall not overlap + * `[alt, alt + num_items)`. Both ranges shall not overlap + * `[d_begin_offsets, d_begin_offsets + num_segments)` nor + * `[d_end_offsets, d_end_offsets + num_segments)` in any way. + * - Segments are not required to be contiguous. For all index values `i` + * outside the specified segments `d_keys.Current()[i]`, + * `d_values.Current()[i]`, `d_keys.Alternate()[i]`, + * `d_values.Alternate()[i]` will not be accessed nor modified. + * + * @par Snippet + * The code snippet below illustrates the batched sorting of three segments + * (with one zero-length segment) of @p int keys with associated vector of + * @p int values. + * + * @par + * @code + * #include + * // or equivalently + * + * // Declare, allocate, and initialize device-accessible pointers + * // for sorting data + * int num_items; // e.g., 7 + * int num_segments; // e.g., 3 + * int *d_offsets; // e.g., [0, 3, 3, 7] + * int *d_key_buf; // e.g., [8, 6, 7, 5, 3, 0, 9] + * int *d_key_alt_buf; // e.g., [-, -, -, -, -, -, -] + * int *d_value_buf; // e.g., [0, 1, 2, 3, 4, 5, 6] + * int *d_value_alt_buf; // e.g., [-, -, -, -, -, -, -] + * ... + * + * // Create a set of DoubleBuffers to wrap pairs of device pointers + * cub::DoubleBuffer d_keys(d_key_buf, d_key_alt_buf); + * cub::DoubleBuffer d_values(d_value_buf, d_value_alt_buf); + * + * // Determine temporary device storage requirements + * void *d_temp_storage = NULL; + * size_t temp_storage_bytes = 0; + * cub::DeviceSegmentedSort::StableSortPairs( + * d_temp_storage, temp_storage_bytes, d_keys, d_values, + * num_items, num_segments, d_offsets, d_offsets + 1); + * + * // Allocate temporary storage + * cudaMalloc(&d_temp_storage, temp_storage_bytes); + * + * // Run sorting operation + * cub::DeviceSegmentedSort::StableSortPairs( + * d_temp_storage, temp_storage_bytes, d_keys, d_values, + * num_items, num_segments, d_offsets, d_offsets + 1); + * + * // d_keys.Current() <-- [6, 7, 8, 0, 3, 5, 9] + * // d_values.Current() <-- [5, 4, 3, 1, 2, 0, 6] + * + * @endcode + * + * @tparam KeyT + * [inferred] Key type + * + * @tparam ValueT + * [inferred] Value type + * + * @tparam BeginOffsetIteratorT + * [inferred] Random-access input iterator type for reading segment + * beginning offsets \iterator + * + * @tparam EndOffsetIteratorT + * [inferred] Random-access input iterator type for reading segment + * ending offsets \iterator + * + * @param[in] d_temp_storage + * Device-accessible allocation of temporary storage. When `nullptr`, the + * required allocation size is written to @p temp_storage_bytes and no work + * is done + * + * @param[in,out] temp_storage_bytes + * Reference to size in bytes of @p d_temp_storage allocation + * + * @param[in,out] d_keys + * Reference to the double-buffer of keys whose "current" device-accessible + * buffer contains the unsorted input keys and, upon return, is updated to + * point to the sorted output keys + * + * @param[in,out] d_values + * Double-buffer of values whose "current" device-accessible buffer contains + * the unsorted input values and, upon return, is updated to point to the + * sorted output values + * + * @param[in] num_items + * The total number of items to sort (across all segments) + * + * @param[in] num_segments + * The number of segments that comprise the sorting data + * + * @param[in] d_begin_offsets + * Random-access input iterator to the sequence of beginning offsets of + * length @p num_segments, such that `d_begin_offsets[i]` is the first + * element of the ith data segment in `d_keys_*` and + * `d_values_*` + * + * @param[in] d_end_offsets + * Random-access input iterator to the sequence of ending offsets of length + * @p num_segments, such that `d_end_offsets[i]-1` is the last element of + * the ith data segment in `d_keys_*` and `d_values_*`. + * If `d_end_offsets[i]-1 <= d_begin_offsets[i]`, the i-th segment is + * considered empty. + * + * @param[in] stream + * [optional] CUDA stream to launch kernels within. Default is + * stream0. + */ + template + CUB_RUNTIME_FUNCTION static cudaError_t + StableSortPairs(void *d_temp_storage, + std::size_t &temp_storage_bytes, + DoubleBuffer &d_keys, + DoubleBuffer &d_values, + int num_items, + int num_segments, + BeginOffsetIteratorT d_begin_offsets, + EndOffsetIteratorT d_end_offsets, + cudaStream_t stream = 0) + { + return SortPairs(d_temp_storage, + temp_storage_bytes, + d_keys, + d_values, + num_items, + num_segments, + d_begin_offsets, + d_end_offsets, + stream); + } + + template + CUB_DETAIL_RUNTIME_DEBUG_SYNC_IS_NOT_SUPPORTED + CUB_RUNTIME_FUNCTION static cudaError_t + StableSortPairs(void *d_temp_storage, + std::size_t &temp_storage_bytes, + DoubleBuffer &d_keys, + DoubleBuffer &d_values, + int num_items, + int num_segments, + BeginOffsetIteratorT d_begin_offsets, + EndOffsetIteratorT d_end_offsets, + cudaStream_t stream, + bool debug_synchronous) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + + return StableSortPairs( + d_temp_storage, + temp_storage_bytes, + d_keys, + d_values, + num_items, + num_segments, + d_begin_offsets, + d_end_offsets, + stream); + } + + /** + * @brief Sorts segments of key-value pairs into descending order. + * Approximately `2*num_segments` auxiliary storage required. + * + * @par + * - The sorting operation is given a pair of key buffers and a corresponding + * pair of associated value buffers. Each pair is managed by a DoubleBuffer + * structure that indicates which of the two buffers is "current" (and thus + * contains the input data to be sorted). + * - The contents of both buffers within each pair may be altered by the sorting + * operation. + * - Upon completion, the sorting operation will update the "current" indicator + * within each DoubleBuffer wrapper to reference which of the two buffers + * now contains the sorted output sequence (a function of the number of key bits + * specified and the targeted device architecture). + * - When the input is a contiguous sequence of segments, a single sequence + * @p segment_offsets (of length `num_segments+1`) can be aliased + * for both the @p d_begin_offsets and @p d_end_offsets parameters (where + * the latter is specified as `segment_offsets+1`). + * - StableSortPairsDescending is stable: it preserves the relative ordering + * of equivalent elements. That is, if @p x and @p y are elements such that + * @p x precedes @p y, and if the two elements are equivalent (neither + * @p x < @p y nor @p y < @p x) then a postcondition of stable sort is that + * @p x still precedes @p y. + * - Let `cur` be one of `{d_keys.Current(), d_values.Current()}` and `alt` + * be any of `{d_keys.Alternate(), d_values.Alternate()}`. The range + * `[cur, cur + num_items)` shall not overlap + * `[alt, alt + num_items)`. Both ranges shall not overlap + * `[d_begin_offsets, d_begin_offsets + num_segments)` nor + * `[d_end_offsets, d_end_offsets + num_segments)` in any way. + * - Segments are not required to be contiguous. For all index values `i` + * outside the specified segments `d_keys.Current()[i]`, + * `d_values.Current()[i]`, `d_keys.Alternate()[i]`, + * `d_values.Alternate()[i]` will not be accessed nor modified. + * + * @par Snippet + * The code snippet below illustrates the batched sorting of three segments + * (with one zero-length segment) of @p int keys with associated vector of + * @p int values. + * + * @par + * @code + * #include + * // or equivalently + * + * // Declare, allocate, and initialize device-accessible pointers + * // for sorting data + * int num_items; // e.g., 7 + * int num_segments; // e.g., 3 + * int *d_offsets; // e.g., [0, 3, 3, 7] + * int *d_key_buf; // e.g., [8, 6, 7, 5, 3, 0, 9] + * int *d_key_alt_buf; // e.g., [-, -, -, -, -, -, -] + * int *d_value_buf; // e.g., [0, 1, 2, 3, 4, 5, 6] + * int *d_value_alt_buf; // e.g., [-, -, -, -, -, -, -] + * ... + * + * // Create a set of DoubleBuffers to wrap pairs of device pointers + * cub::DoubleBuffer d_keys(d_key_buf, d_key_alt_buf); + * cub::DoubleBuffer d_values(d_value_buf, d_value_alt_buf); + * + * // Determine temporary device storage requirements + * void *d_temp_storage = NULL; + * size_t temp_storage_bytes = 0; + * cub::DeviceSegmentedSort::StableSortPairsDescending( + * d_temp_storage, temp_storage_bytes, d_keys, d_values, + * num_items, num_segments, d_offsets, d_offsets + 1); + * + * // Allocate temporary storage + * cudaMalloc(&d_temp_storage, temp_storage_bytes); + * + * // Run sorting operation + * cub::DeviceSegmentedSort::StableSortPairsDescending( + * d_temp_storage, temp_storage_bytes, d_keys, d_values, + * num_items, num_segments, d_offsets, d_offsets + 1); + * + * // d_keys.Current() <-- [8, 7, 6, 9, 5, 3, 0] + * // d_values.Current() <-- [0, 2, 1, 6, 3, 4, 5] + * @endcode + * + * @tparam KeyT + * [inferred] Key type + * + * @tparam ValueT + * [inferred] Value type + * + * @tparam BeginOffsetIteratorT + * [inferred] Random-access input iterator type for reading segment + * beginning offsets \iterator + * + * @tparam EndOffsetIteratorT + * [inferred] Random-access input iterator type for reading segment + * ending offsets \iterator + * + * @param[in] d_temp_storage + * Device-accessible allocation of temporary storage. When `nullptr`, the + * required allocation size is written to @p temp_storage_bytes and no work + * is done + * + * @param[in,out] temp_storage_bytes + * Reference to size in bytes of @p d_temp_storage allocation + * + * @param[in,out] d_keys + * Reference to the double-buffer of keys whose "current" device-accessible + * buffer contains the unsorted input keys and, upon return, is updated to + * point to the sorted output keys + * + * @param[in,out] d_values + * Double-buffer of values whose "current" device-accessible buffer contains + * the unsorted input values and, upon return, is updated to point to the + * sorted output values + * + * @param[in] num_items + * The total number of items to sort (across all segments) + * + * @param[in] num_segments + * The number of segments that comprise the sorting data + * + * @param[in] d_begin_offsets + * Random-access input iterator to the sequence of beginning offsets of + * length @p num_segments, such that `d_begin_offsets[i]` is the first + * element of the ith data segment in `d_keys_*` and + * `d_values_*` + * + * @param[in] d_end_offsets + * Random-access input iterator to the sequence of ending offsets of length + * @p num_segments, such that `d_end_offsets[i]-1` is the last element of + * the ith data segment in `d_keys_*` and `d_values_*`. + * If `d_end_offsets[i]-1 <= d_begin_offsets[i]`, the i-th segment is + * considered empty. + * + * @param[in] stream + * [optional] CUDA stream to launch kernels within. Default is + * stream0. + */ + template + CUB_RUNTIME_FUNCTION static cudaError_t + StableSortPairsDescending(void *d_temp_storage, + std::size_t &temp_storage_bytes, + DoubleBuffer &d_keys, + DoubleBuffer &d_values, + int num_items, + int num_segments, + BeginOffsetIteratorT d_begin_offsets, + EndOffsetIteratorT d_end_offsets, + cudaStream_t stream = 0) + { + return SortPairsDescending(d_temp_storage, + temp_storage_bytes, + d_keys, + d_values, + num_items, + num_segments, + d_begin_offsets, + d_end_offsets, + stream); + } + + template + CUB_DETAIL_RUNTIME_DEBUG_SYNC_IS_NOT_SUPPORTED + CUB_RUNTIME_FUNCTION static cudaError_t + StableSortPairsDescending(void *d_temp_storage, + std::size_t &temp_storage_bytes, + DoubleBuffer &d_keys, + DoubleBuffer &d_values, + int num_items, + int num_segments, + BeginOffsetIteratorT d_begin_offsets, + EndOffsetIteratorT d_end_offsets, + cudaStream_t stream, + bool debug_synchronous) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + + return StableSortPairsDescending(d_temp_storage, + temp_storage_bytes, + d_keys, + d_values, + num_items, + num_segments, + d_begin_offsets, + d_end_offsets, + stream); + } + + //@} end member group + +}; + + +CUB_NAMESPACE_END diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/device/device_select.cuh b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/device/device_select.cuh new file mode 100644 index 0000000000000000000000000000000000000000..f21431391ab2885849367af7893be00d9656bb22 --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/device/device_select.cuh @@ -0,0 +1,1095 @@ +/****************************************************************************** + * Copyright (c) 2011, Duane Merrill. All rights reserved. + * Copyright (c) 2011-2022, NVIDIA CORPORATION. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the NVIDIA CORPORATION nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ******************************************************************************/ + +/** + * @file cub::DeviceSelect provides device-wide, parallel operations for + * compacting selected items from sequences of data items residing within + * device-accessible memory. + */ + +#pragma once + +#include +#include + +#include +#include +#include +#include + +CUB_NAMESPACE_BEGIN + + +/** + * @brief DeviceSelect provides device-wide, parallel operations for compacting + * selected items from sequences of data items residing within + * device-accessible memory. ![](select_logo.png) + * @ingroup SingleModule + * + * @par Overview + * These operations apply a selection criterion to selectively copy + * items from a specified input sequence to a compact output sequence. + * + * @par Usage Considerations + * @cdp_class{DeviceSelect} + * + * @par Performance + * @linear_performance{select-flagged, select-if, and select-unique} + * + * @par + * The following chart illustrates DeviceSelect::If performance across + * different CUDA architectures for `int32` items, where 50% of the items are + * randomly selected. + * + * @image html select_if_int32_50_percent.png + * + * @par + * The following chart illustrates DeviceSelect::Unique performance across + * different CUDA architectures for `int32` items where segments have lengths + * uniformly sampled from `[1, 1000]`. + * + * @image html select_unique_int32_len_500.png + * + * @par + * @plots_below + * + */ +struct DeviceSelect +{ + /** + * @brief Uses the `d_flags` sequence to selectively copy the corresponding + * items from `d_in` into `d_out`. The total number of items selected + * is written to `d_num_selected_out`. ![](select_flags_logo.png) + * + * @par + * - The value type of `d_flags` must be castable to `bool` (e.g., `bool`, + * `char`, `int`, etc.). + * - Copies of the selected items are compacted into `d_out` and maintain + * their original relative ordering. + * - The range `[d_out, d_out + *d_num_selected_out)` shall not overlap + * `[d_in, d_in + num_items)`, `[d_flags, d_flags + num_items)` nor + * `d_num_selected_out` in any way. + * - @devicestorage + * + * @par Snippet + * The code snippet below illustrates the compaction of items selected from + * an `int` device vector. + * @par + * @code + * #include // or equivalently + * + * // Declare, allocate, and initialize device-accessible pointers for input, + * // flags, and output + * int num_items; // e.g., 8 + * int *d_in; // e.g., [1, 2, 3, 4, 5, 6, 7, 8] + * char *d_flags; // e.g., [1, 0, 0, 1, 0, 1, 1, 0] + * int *d_out; // e.g., [ , , , , , , , ] + * int *d_num_selected_out; // e.g., [ ] + * ... + * + * // Determine temporary device storage requirements + * void *d_temp_storage = NULL; + * size_t temp_storage_bytes = 0; + * cub::DeviceSelect::Flagged( + * d_temp_storage, temp_storage_bytes, + * d_in, d_flags, d_out, d_num_selected_out, num_items); + * + * // Allocate temporary storage + * cudaMalloc(&d_temp_storage, temp_storage_bytes); + * + * // Run selection + * cub::DeviceSelect::Flagged( + * d_temp_storage, temp_storage_bytes, + * d_in, d_flags, d_out, d_num_selected_out, num_items); + * + * // d_out <-- [1, 4, 6, 7] + * // d_num_selected_out <-- [4] + * + * @endcode + * + * @tparam InputIteratorT + * **[inferred]** Random-access input iterator type for reading input + * items \iterator + * + * @tparam FlagIterator + * **[inferred]** Random-access input iterator type for reading selection + * flags \iterator + * + * @tparam OutputIteratorT + * **[inferred]** Random-access output iterator type for writing selected + * items \iterator + * + * @tparam NumSelectedIteratorT + * **[inferred]** Output iterator type for recording the number of items + * selected \iterator + * + * @param[in] d_temp_storage + * Device-accessible allocation of temporary storage. When `nullptr`, the + * required allocation size is written to `temp_storage_bytes` and no work + * is done. + * + * @param[in,out] temp_storage_bytes + * Reference to size in bytes of `d_temp_storage` allocation + * + * @param[in] d_in + * Pointer to the input sequence of data items + * + * @param[in] d_flags + * Pointer to the input sequence of selection flags + * + * @param[out] d_out + * Pointer to the output sequence of selected data items + * + * @param[out] d_num_selected_out + * Pointer to the output total number of items selected + * (i.e., length of `d_out`) + * + * @param[in] num_items + * Total number of input items (i.e., length of `d_in`) + * + * @param[in] stream + * **[optional]** CUDA stream to launch kernels within. + * Default is stream0. + */ + template + CUB_RUNTIME_FUNCTION __forceinline__ static cudaError_t + Flagged(void *d_temp_storage, + size_t &temp_storage_bytes, + InputIteratorT d_in, + FlagIterator d_flags, + OutputIteratorT d_out, + NumSelectedIteratorT d_num_selected_out, + int num_items, + cudaStream_t stream = 0) + { + using OffsetT = int; // Signed integer type for global offsets + using SelectOp = NullType; // Selection op (not used) + using EqualityOp = NullType; // Equality operator (not used) + + return DispatchSelectIf::Dispatch(d_temp_storage, + temp_storage_bytes, + d_in, + d_flags, + d_out, + d_num_selected_out, + SelectOp(), + EqualityOp(), + num_items, + stream); + } + + template + CUB_DETAIL_RUNTIME_DEBUG_SYNC_IS_NOT_SUPPORTED + CUB_RUNTIME_FUNCTION __forceinline__ static cudaError_t + Flagged(void *d_temp_storage, + size_t &temp_storage_bytes, + InputIteratorT d_in, + FlagIterator d_flags, + OutputIteratorT d_out, + NumSelectedIteratorT d_num_selected_out, + int num_items, + cudaStream_t stream, + bool debug_synchronous) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + + return Flagged(d_temp_storage, + temp_storage_bytes, + d_in, + d_flags, + d_out, + d_num_selected_out, + num_items, + stream); + } + + /** + * @brief Uses the `d_flags` sequence to selectively compact the items in + * `d_data`. The total number of items selected is written to + * `d_num_selected_out`. ![](select_flags_logo.png) + * + * @par + * - The value type of `d_flags` must be castable to `bool` (e.g., `bool`, + * `char`, `int`, etc.). + * - Copies of the selected items are compacted in-place and maintain + * their original relative ordering. + * - The `d_data` may equal `d_flags`. The range + * `[d_data, d_data + num_items)` shall not overlap + * `[d_flags, d_flags + num_items)` in any other way. + * - @devicestorage + * + * @par Snippet + * The code snippet below illustrates the compaction of items selected from + * an `int` device vector. + * @par + * @code + * #include // or equivalently + * + * // Declare, allocate, and initialize device-accessible pointers for input, + * // flags, and output + * int num_items; // e.g., 8 + * int *d_data; // e.g., [1, 2, 3, 4, 5, 6, 7, 8] + * char *d_flags; // e.g., [1, 0, 0, 1, 0, 1, 1, 0] + * int *d_num_selected_out; // e.g., [ ] + * ... + * + * // Determine temporary device storage requirements + * void *d_temp_storage = NULL; + * size_t temp_storage_bytes = 0; + * cub::DeviceSelect::Flagged( + * d_temp_storage, temp_storage_bytes, + * d_in, d_flags, d_num_selected_out, num_items); + * + * // Allocate temporary storage + * cudaMalloc(&d_temp_storage, temp_storage_bytes); + * + * // Run selection + * cub::DeviceSelect::Flagged( + * d_temp_storage, temp_storage_bytes, + * d_in, d_flags, d_num_selected_out, num_items); + * + * // d_data <-- [1, 4, 6, 7] + * // d_num_selected_out <-- [4] + * + * @endcode + * + * @tparam IteratorT + * **[inferred]** Random-access iterator type for reading and writing + * selected items \iterator + * + * @tparam FlagIterator + * **[inferred]** Random-access input iterator type for reading selection + * flags \iterator + * + * @tparam NumSelectedIteratorT + * **[inferred]** Output iterator type for recording the number of items + * selected \iterator + * + * @param[in] d_temp_storage + * Device-accessible allocation of temporary storage. When `nullptr`, the + * required allocation size is written to `temp_storage_bytes` and no work + * is done. + * + * @param[in,out] temp_storage_bytes + * Reference to size in bytes of `d_temp_storage` allocation + * + * @param[in,out] d_data + * Pointer to the sequence of data items + * + * @param[in] d_flags + * Pointer to the input sequence of selection flags + * + * @param[out] d_num_selected_out + * Pointer to the output total number of items selected + * + * @param[in] num_items + * Total number of input items (i.e., length of `d_data`) + * + * @param[in] stream + * **[optional]** CUDA stream to launch kernels within. + * Default is stream0. + */ + template + CUB_RUNTIME_FUNCTION __forceinline__ static cudaError_t + Flagged(void *d_temp_storage, + size_t &temp_storage_bytes, + IteratorT d_data, + FlagIterator d_flags, + NumSelectedIteratorT d_num_selected_out, + int num_items, + cudaStream_t stream = 0) + { + using OffsetT = int; // Signed integer type for global offsets + using SelectOp = NullType; // Selection op (not used) + using EqualityOp = NullType; // Equality operator (not used) + + constexpr bool may_alias = true; + + return DispatchSelectIf::Dispatch(d_temp_storage, + temp_storage_bytes, + d_data, // in + d_flags, + d_data, // out + d_num_selected_out, + SelectOp(), + EqualityOp(), + num_items, + stream); + } + + template + CUB_DETAIL_RUNTIME_DEBUG_SYNC_IS_NOT_SUPPORTED + CUB_RUNTIME_FUNCTION __forceinline__ static cudaError_t + Flagged(void *d_temp_storage, + size_t &temp_storage_bytes, + IteratorT d_data, + FlagIterator d_flags, + NumSelectedIteratorT d_num_selected_out, + int num_items, + cudaStream_t stream, + bool debug_synchronous) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + + return Flagged( + d_temp_storage, + temp_storage_bytes, + d_data, + d_flags, + d_num_selected_out, + num_items, + stream); + } + + /** + * @brief Uses the `select_op` functor to selectively copy items from `d_in` + * into `d_out`. The total number of items selected is written to + * `d_num_selected_out`. ![](select_logo.png) + * + * @par + * - Copies of the selected items are compacted into `d_out` and maintain + * their original relative ordering. + * - The range `[d_out, d_out + *d_num_selected_out)` shall not overlap + * `[d_in, d_in + num_items)` nor `d_num_selected_out` in any way. + * - @devicestorage + * + * @par Performance + * The following charts illustrate saturated select-if performance across + * different CUDA architectures for `int32` and `int64` items, respectively. + * Items are selected with 50% probability. + * + * @image html select_if_int32_50_percent.png + * @image html select_if_int64_50_percent.png + * + * @par + * The following charts are similar, but 5% selection probability: + * + * @image html select_if_int32_5_percent.png + * @image html select_if_int64_5_percent.png + * + * @par Snippet + * The code snippet below illustrates the compaction of items selected from + * an `int` device vector. + * @par + * @code + * #include // or equivalently + * + * // Functor type for selecting values less than some criteria + * struct LessThan + * { + * int compare; + * + * CUB_RUNTIME_FUNCTION __forceinline__ + * LessThan(int compare) : compare(compare) {} + * + * CUB_RUNTIME_FUNCTION __forceinline__ + * bool operator()(const int &a) const { + * return (a < compare); + * } + * }; + * + * // Declare, allocate, and initialize device-accessible pointers + * // for input and output + * int num_items; // e.g., 8 + * int *d_in; // e.g., [0, 2, 3, 9, 5, 2, 81, 8] + * int *d_out; // e.g., [ , , , , , , , ] + * int *d_num_selected_out; // e.g., [ ] + * LessThan select_op(7); + * ... + * + * // Determine temporary device storage requirements + * void *d_temp_storage = NULL; + * size_t temp_storage_bytes = 0; + * cub::DeviceSelect::If( + * d_temp_storage, temp_storage_bytes, + * d_in, d_out, d_num_selected_out, num_items, select_op); + * + * // Allocate temporary storage + * cudaMalloc(&d_temp_storage, temp_storage_bytes); + * + * // Run selection + * cub::DeviceSelect::If( + * d_temp_storage, temp_storage_bytes, + * d_in, d_out, d_num_selected_out, num_items, select_op); + * + * // d_out <-- [0, 2, 3, 5, 2] + * // d_num_selected_out <-- [5] + * @endcode + * + * @tparam InputIteratorT + * **[inferred]** Random-access input iterator type for reading input + * items \iterator + * + * @tparam OutputIteratorT + * **[inferred]** Random-access output iterator type for writing selected + * items \iterator + * + * @tparam NumSelectedIteratorT + * **[inferred]** Output iterator type for recording the number of items + * selected \iterator + * + * @tparam SelectOp + * **[inferred]** Selection operator type having member + * `bool operator()(const T &a)` + * + * @param[in] d_temp_storage + * Device-accessible allocation of temporary storage. When `nullptr`, the + * required allocation size is written to `temp_storage_bytes` and no work + * is done. + * + * @param[in,out] temp_storage_bytes + * Reference to size in bytes of `d_temp_storage` allocation + * + * @param[in] d_in + * Pointer to the input sequence of data items + * + * @param[out] d_out + * Pointer to the output sequence of selected data items + * + * @param[out] d_num_selected_out + * Pointer to the output total number of items selected + * (i.e., length of `d_out`) + * + * @param[in] num_items + * Total number of input items (i.e., length of `d_in`) + * + * @param[in] select_op + * Unary selection operator + * + * @param[in] stream + * **[optional]** CUDA stream to launch kernels within. + * Default is stream0. + */ + template + CUB_RUNTIME_FUNCTION __forceinline__ static cudaError_t + If(void *d_temp_storage, + size_t &temp_storage_bytes, + InputIteratorT d_in, + OutputIteratorT d_out, + NumSelectedIteratorT d_num_selected_out, + int num_items, + SelectOp select_op, + cudaStream_t stream = 0) + { + using OffsetT = int; // Signed integer type for global offsets + using FlagIterator = NullType *; // FlagT iterator type (not used) + using EqualityOp = NullType; // Equality operator (not used) + + return DispatchSelectIf::Dispatch(d_temp_storage, + temp_storage_bytes, + d_in, + NULL, + d_out, + d_num_selected_out, + select_op, + EqualityOp(), + num_items, + stream); + } + + template + CUB_DETAIL_RUNTIME_DEBUG_SYNC_IS_NOT_SUPPORTED + CUB_RUNTIME_FUNCTION __forceinline__ static cudaError_t + If(void *d_temp_storage, + size_t &temp_storage_bytes, + InputIteratorT d_in, + OutputIteratorT d_out, + NumSelectedIteratorT d_num_selected_out, + int num_items, + SelectOp select_op, + cudaStream_t stream, + bool debug_synchronous) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + + return If( + d_temp_storage, + temp_storage_bytes, + d_in, + d_out, + d_num_selected_out, + num_items, + select_op, + stream); + } + + /** + * @brief Uses the `select_op` functor to selectively compact items in + * `d_data`. The total number of items selected is written to + * `d_num_selected_out`. ![](select_logo.png) + * + * @par + * - Copies of the selected items are compacted in `d_data` and maintain + * their original relative ordering. + * - @devicestorage + * + * @par Snippet + * The code snippet below illustrates the compaction of items selected from + * an `int` device vector. + * @par + * @code + * #include // or equivalently + * + * // Functor type for selecting values less than some criteria + * struct LessThan + * { + * int compare; + * + * CUB_RUNTIME_FUNCTION __forceinline__ + * LessThan(int compare) : compare(compare) {} + * + * CUB_RUNTIME_FUNCTION __forceinline__ + * bool operator()(const int &a) const { + * return (a < compare); + * } + * }; + * + * // Declare, allocate, and initialize device-accessible pointers + * // for input and output + * int num_items; // e.g., 8 + * int *d_data; // e.g., [0, 2, 3, 9, 5, 2, 81, 8] + * int *d_num_selected_out; // e.g., [ ] + * LessThan select_op(7); + * ... + * + * // Determine temporary device storage requirements + * void *d_temp_storage = NULL; + * size_t temp_storage_bytes = 0; + * cub::DeviceSelect::If( + * d_temp_storage, temp_storage_bytes, + * d_data, d_num_selected_out, num_items, select_op); + * + * // Allocate temporary storage + * cudaMalloc(&d_temp_storage, temp_storage_bytes); + * + * // Run selection + * cub::DeviceSelect::If( + * d_temp_storage, temp_storage_bytes, + * d_data, d_num_selected_out, num_items, select_op); + * + * // d_data <-- [0, 2, 3, 5, 2] + * // d_num_selected_out <-- [5] + * @endcode + * + * @tparam IteratorT + * **[inferred]** Random-access input iterator type for reading and + * writing items \iterator + * + * @tparam NumSelectedIteratorT + * **[inferred]** Output iterator type for recording the number of items + * selected \iterator + * + * @tparam SelectOp + * **[inferred]** Selection operator type having member + * `bool operator()(const T &a)` + * + * @param[in] d_temp_storage + * Device-accessible allocation of temporary storage. When `nullptr`, the + * required allocation size is written to `temp_storage_bytes` and no work + * is done. + * + * @param[in,out] temp_storage_bytes + * Reference to size in bytes of `d_temp_storage` allocation + * + * @param[in,out] d_data + * Pointer to the sequence of data items + * + * @param[out] d_num_selected_out + * Pointer to the output total number of items selected + * + * @param[in] num_items + * Total number of input items (i.e., length of `d_data`) + * + * @param[in] select_op + * Unary selection operator + * + * @param[in] stream + * **[optional]** CUDA stream to launch kernels within. + * Default is stream0. + */ + template + CUB_RUNTIME_FUNCTION __forceinline__ static cudaError_t + If(void *d_temp_storage, + size_t &temp_storage_bytes, + IteratorT d_data, + NumSelectedIteratorT d_num_selected_out, + int num_items, + SelectOp select_op, + cudaStream_t stream = 0) + { + using OffsetT = int; // Signed integer type for global offsets + using FlagIterator = NullType *; // FlagT iterator type (not used) + using EqualityOp = NullType; // Equality operator (not used) + + constexpr bool may_alias = true; + + return DispatchSelectIf::Dispatch(d_temp_storage, + temp_storage_bytes, + d_data, // in + NULL, + d_data, // out + d_num_selected_out, + select_op, + EqualityOp(), + num_items, + stream); + } + + template + CUB_DETAIL_RUNTIME_DEBUG_SYNC_IS_NOT_SUPPORTED + CUB_RUNTIME_FUNCTION __forceinline__ static cudaError_t + If(void *d_temp_storage, + size_t &temp_storage_bytes, + IteratorT d_data, + NumSelectedIteratorT d_num_selected_out, + int num_items, + SelectOp select_op, + cudaStream_t stream, + bool debug_synchronous) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + + return If(d_temp_storage, + temp_storage_bytes, + d_data, + d_num_selected_out, + num_items, + select_op, + stream); + } + + /** + * @brief Given an input sequence `d_in` having runs of consecutive + * equal-valued keys, only the first key from each run is selectively + * copied to `d_out`. The total number of items selected is written to + * `d_num_selected_out`. ![](unique_logo.png) + * + * @par + * - The `==` equality operator is used to determine whether keys are + * equivalent + * - Copies of the selected items are compacted into `d_out` and maintain + * their original relative ordering. + * - The range `[d_out, d_out + *d_num_selected_out)` shall not overlap + * `[d_in, d_in + num_items)` nor `d_num_selected_out` in any way. + * - @devicestorage + * + * @par Performance + * The following charts illustrate saturated select-unique performance across different + * CUDA architectures for `int32` and `int64` items, respectively. Segments + * have lengths uniformly sampled from `[1, 1000]`. + * + * @image html select_unique_int32_len_500.png + * @image html select_unique_int64_len_500.png + * + * @par + * The following charts are similar, but with segment lengths uniformly + * sampled from `[1, 10]`: + * + * @image html select_unique_int32_len_5.png + * @image html select_unique_int64_len_5.png + * + * @par Snippet + * The code snippet below illustrates the compaction of items selected from + * an `int` device vector. + * @par + * @code + * #include // or equivalently + * + * // Declare, allocate, and initialize device-accessible pointers + * // for input and output + * int num_items; // e.g., 8 + * int *d_in; // e.g., [0, 2, 2, 9, 5, 5, 5, 8] + * int *d_out; // e.g., [ , , , , , , , ] + * int *d_num_selected_out; // e.g., [ ] + * ... + * + * // Determine temporary device storage requirements + * void *d_temp_storage = NULL; + * size_t temp_storage_bytes = 0; + * cub::DeviceSelect::Unique( + * d_temp_storage, temp_storage_bytes, + * d_in, d_out, d_num_selected_out, num_items); + * + * // Allocate temporary storage + * cudaMalloc(&d_temp_storage, temp_storage_bytes); + * + * // Run selection + * cub::DeviceSelect::Unique( + * d_temp_storage, temp_storage_bytes, + * d_in, d_out, d_num_selected_out, num_items); + * + * // d_out <-- [0, 2, 9, 5, 8] + * // d_num_selected_out <-- [5] + * @endcode + * + * @tparam InputIteratorT + * **[inferred]** Random-access input iterator type for reading input + * items \iterator + * + * @tparam OutputIteratorT + * **[inferred]** Random-access output iterator type for writing selected + * items \iterator + * + * @tparam NumSelectedIteratorT + * **[inferred]** Output iterator type for recording the number of items + * selected \iterator + * + * @param[in] d_temp_storage + * Device-accessible allocation of temporary storage. When `nullptr`, the + * required allocation size is written to `temp_storage_bytes` and no work + * is done. + * + * @param[in,out] temp_storage_bytes + * Reference to size in bytes of `d_temp_storage` allocation + * + * @param[in] d_in + * Pointer to the input sequence of data items + * + * @param[out] d_out + * Pointer to the output sequence of selected data items + * + * @param[out] d_num_selected_out + * Pointer to the output total number of items selected + * (i.e., length of `d_out`) + * + * @param[in] num_items + * Total number of input items (i.e., length of `d_in`) + * + * @param[in] stream + * **[optional]** CUDA stream to launch kernels within. + * Default is stream0. + */ + template + CUB_RUNTIME_FUNCTION __forceinline__ static cudaError_t + Unique(void *d_temp_storage, + size_t &temp_storage_bytes, + InputIteratorT d_in, + OutputIteratorT d_out, + NumSelectedIteratorT d_num_selected_out, + int num_items, + cudaStream_t stream = 0) + { + using OffsetT = int; // Signed integer type for global offsets + using FlagIterator = NullType *; // FlagT iterator type (not used) + using SelectOp = NullType; // Selection op (not used) + using EqualityOp = Equality; // Default == operator + + return DispatchSelectIf::Dispatch(d_temp_storage, + temp_storage_bytes, + d_in, + NULL, + d_out, + d_num_selected_out, + SelectOp(), + EqualityOp(), + num_items, + stream); + } + + template + CUB_DETAIL_RUNTIME_DEBUG_SYNC_IS_NOT_SUPPORTED + CUB_RUNTIME_FUNCTION __forceinline__ static cudaError_t + Unique(void *d_temp_storage, + size_t &temp_storage_bytes, + InputIteratorT d_in, + OutputIteratorT d_out, + NumSelectedIteratorT d_num_selected_out, + int num_items, + cudaStream_t stream, + bool debug_synchronous) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + + return Unique( + d_temp_storage, + temp_storage_bytes, + d_in, + d_out, + d_num_selected_out, + num_items, + stream); + } + + /** + * @brief Given an input sequence `d_keys_in` and `d_values_in` with runs of + * key-value pairs with consecutive equal-valued keys, only the first + * key and its value from each run is selectively copied to + * `d_keys_out` and `d_values_out`. The total number of items selected + * is written to `d_num_selected_out`. ![](unique_logo.png) + * + * @par + * - The `==` equality operator is used to determine whether keys are + * equivalent + * - Copies of the selected items are compacted into `d_out` and maintain + * their original relative ordering. + * - In-place operations are not supported. There must be no overlap between + * any of the provided ranges: + * - `[d_keys_in, d_keys_in + num_items)` + * - `[d_keys_out, d_keys_out + *d_num_selected_out)` + * - `[d_values_in, d_values_in + num_items)` + * - `[d_values_out, d_values_out + *d_num_selected_out)` + * - `[d_num_selected_out, d_num_selected_out + 1)` + * - @devicestorage + * + * @par Snippet + * The code snippet below illustrates the compaction of items selected from + * an `int` device vector. + * @par + * @code + * #include // or equivalently + * + * // Declare, allocate, and initialize device-accessible pointers + * // for input and output + * int num_items; // e.g., 8 + * int *d_keys_in; // e.g., [0, 2, 2, 9, 5, 5, 5, 8] + * int *d_values_in; // e.g., [1, 2, 3, 4, 5, 6, 7, 8] + * int *d_keys_out; // e.g., [ , , , , , , , ] + * int *d_values_out; // e.g., [ , , , , , , , ] + * int *d_num_selected_out; // e.g., [ ] + * ... + * + * // Determine temporary device storage requirements + * void *d_temp_storage = NULL; + * size_t temp_storage_bytes = 0; + * cub::DeviceSelect::UniqueByKey( + * d_temp_storage, temp_storage_bytes, + * d_keys_in, d_values_in, + * d_keys_out, d_values_out, d_num_selected_out, num_items); + * + * // Allocate temporary storage + * cudaMalloc(&d_temp_storage, temp_storage_bytes); + * + * // Run selection + * cub::DeviceSelect::UniqueByKey( + * d_temp_storage, temp_storage_bytes, + * d_keys_in, d_values_in, + * d_keys_out, d_values_out, d_num_selected_out, num_items); + * + * // d_keys_out <-- [0, 2, 9, 5, 8] + * // d_values_out <-- [1, 2, 4, 5, 8] + * // d_num_selected_out <-- [5] + * @endcode + * + * @tparam KeyInputIteratorT + * **[inferred]** Random-access input iterator type for reading input + * keys \iterator + * + * @tparam ValueInputIteratorT + * **[inferred]** Random-access input iterator type for reading input + * values \iterator + * + * @tparam KeyOutputIteratorT + * **[inferred]** Random-access output iterator type for writing selected + * keys \iterator + * + * @tparam ValueOutputIteratorT + * **[inferred]** Random-access output iterator type for writing selected + * values \iterator + * + * @tparam NumSelectedIteratorT + * **[inferred]** Output iterator type for recording the number of items + * selected \iterator + * + * @param[in] d_temp_storage + * Device-accessible allocation of temporary storage. When `nullptr`, the + * required allocation size is written to `temp_storage_bytes` and no work + * is done. + * + * @param[in,out] temp_storage_bytes + * Reference to size in bytes of `d_temp_storage` allocation + * + * @param[in] d_keys_in + * Pointer to the input sequence of keys + * + * @param[in] d_values_in + * Pointer to the input sequence of values + * + * @param[out] d_keys_out + * Pointer to the output sequence of selected keys + * + * @param[out] d_values_out + * Pointer to the output sequence of selected values + * + * @param[out] d_num_selected_out + * Pointer to the total number of items selected (i.e., length of + * `d_keys_out` or `d_values_out`) + * + * @param[in] num_items + * Total number of input items (i.e., length of `d_keys_in` or + * `d_values_in`) + * + * @param[in] stream + * **[optional]** CUDA stream to launch kernels within. + * Default is stream0. + */ + template + CUB_RUNTIME_FUNCTION __forceinline__ static cudaError_t + UniqueByKey(void *d_temp_storage, + size_t &temp_storage_bytes, + KeyInputIteratorT d_keys_in, + ValueInputIteratorT d_values_in, + KeyOutputIteratorT d_keys_out, + ValueOutputIteratorT d_values_out, + NumSelectedIteratorT d_num_selected_out, + int num_items, + cudaStream_t stream = 0) + { + using OffsetT = int; + using EqualityOp = Equality; + + return DispatchUniqueByKey::Dispatch(d_temp_storage, + temp_storage_bytes, + d_keys_in, + d_values_in, + d_keys_out, + d_values_out, + d_num_selected_out, + EqualityOp(), + num_items, + stream); + } + + template + CUB_DETAIL_RUNTIME_DEBUG_SYNC_IS_NOT_SUPPORTED + CUB_RUNTIME_FUNCTION __forceinline__ static cudaError_t + UniqueByKey(void *d_temp_storage, + size_t &temp_storage_bytes, + KeyInputIteratorT d_keys_in, + ValueInputIteratorT d_values_in, + KeyOutputIteratorT d_keys_out, + ValueOutputIteratorT d_values_out, + NumSelectedIteratorT d_num_selected_out, + int num_items, + cudaStream_t stream, + bool debug_synchronous) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + + return UniqueByKey(d_temp_storage, + temp_storage_bytes, + d_keys_in, + d_values_in, + d_keys_out, + d_values_out, + d_num_selected_out, + num_items, + stream); + } +}; + +/** + * @example example_device_select_flagged.cu + * @example example_device_select_if.cu + * @example example_device_select_unique.cu + */ + +CUB_NAMESPACE_END + + diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/device/device_spmv.cuh b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/device/device_spmv.cuh new file mode 100644 index 0000000000000000000000000000000000000000..22dcbe5fcf540934507bcdc5d6578200b2702a6d --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/device/device_spmv.cuh @@ -0,0 +1,197 @@ + +/****************************************************************************** + * Copyright (c) 2011, Duane Merrill. All rights reserved. + * Copyright (c) 2011-2022, NVIDIA CORPORATION. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the NVIDIA CORPORATION nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ******************************************************************************/ + +/** + * \file + * cub::DeviceSpmv provides device-wide parallel operations for performing sparse-matrix * vector multiplication (SpMV). + */ + +#pragma once + +#include +#include +#include + +#include +#include +#include + +CUB_NAMESPACE_BEGIN + + +/** + * \brief DeviceSpmv provides device-wide parallel operations for performing sparse-matrix * dense-vector multiplication (SpMV). + * \ingroup SingleModule + * + * \par Overview + * The [SpMV computation](http://en.wikipedia.org/wiki/Sparse_matrix-vector_multiplication) + * performs the matrix-vector operation + * y = A*x + y, + * where: + * - A is an mxn sparse matrix whose non-zero structure is specified in + * [compressed-storage-row (CSR) format](http://en.wikipedia.org/wiki/Sparse_matrix#Compressed_row_Storage_.28CRS_or_CSR.29) + * (i.e., three arrays: values, row_offsets, and column_indices) + * - x and y are dense vectors + * + * \par Usage Considerations + * \cdp_class{DeviceSpmv} + * + */ +struct DeviceSpmv +{ + /******************************************************************//** + * \name CSR matrix operations + *********************************************************************/ + //@{ + + /** + * \brief This function performs the matrix-vector operation y = A*x. + * + * \par Snippet + * The code snippet below illustrates SpMV upon a 9x9 CSR matrix A + * representing a 3x3 lattice (24 non-zeros). + * + * \par + * \code + * #include // or equivalently + * + * // Declare, allocate, and initialize device-accessible pointers for input matrix A, input vector x, + * // and output vector y + * int num_rows = 9; + * int num_cols = 9; + * int num_nonzeros = 24; + * + * float* d_values; // e.g., [1, 1, 1, 1, 1, 1, 1, 1, + * // 1, 1, 1, 1, 1, 1, 1, 1, + * // 1, 1, 1, 1, 1, 1, 1, 1] + * + * int* d_column_indices; // e.g., [1, 3, 0, 2, 4, 1, 5, 0, + * // 4, 6, 1, 3, 5, 7, 2, 4, + * // 8, 3, 7, 4, 6, 8, 5, 7] + * + * int* d_row_offsets; // e.g., [0, 2, 5, 7, 10, 14, 17, 19, 22, 24] + * + * float* d_vector_x; // e.g., [1, 1, 1, 1, 1, 1, 1, 1, 1] + * float* d_vector_y; // e.g., [ , , , , , , , , ] + * ... + * + * // Determine temporary device storage requirements + * void* d_temp_storage = NULL; + * size_t temp_storage_bytes = 0; + * cub::DeviceSpmv::CsrMV(d_temp_storage, temp_storage_bytes, d_values, + * d_row_offsets, d_column_indices, d_vector_x, d_vector_y, + * num_rows, num_cols, num_nonzeros); + * + * // Allocate temporary storage + * cudaMalloc(&d_temp_storage, temp_storage_bytes); + * + * // Run SpMV + * cub::DeviceSpmv::CsrMV(d_temp_storage, temp_storage_bytes, d_values, + * d_row_offsets, d_column_indices, d_vector_x, d_vector_y, + * num_rows, num_cols, num_nonzeros); + * + * // d_vector_y <-- [2, 3, 2, 3, 4, 3, 2, 3, 2] + * + * \endcode + * + * \tparam ValueT [inferred] Matrix and vector value type (e.g., /p float, /p double, etc.) + */ + template < + typename ValueT> + CUB_RUNTIME_FUNCTION + static cudaError_t CsrMV( + void* d_temp_storage, ///< [in] Device-accessible allocation of temporary storage. When NULL, the required allocation size is written to \p temp_storage_bytes and no work is done. + size_t& temp_storage_bytes, ///< [in,out] Reference to size in bytes of \p d_temp_storage allocation + const ValueT* d_values, ///< [in] Pointer to the array of \p num_nonzeros values of the corresponding nonzero elements of matrix A. + const int* d_row_offsets, ///< [in] Pointer to the array of \p m + 1 offsets demarcating the start of every row in \p d_column_indices and \p d_values (with the final entry being equal to \p num_nonzeros) + const int* d_column_indices, ///< [in] Pointer to the array of \p num_nonzeros column-indices of the corresponding nonzero elements of matrix A. (Indices are zero-valued.) + const ValueT* d_vector_x, ///< [in] Pointer to the array of \p num_cols values corresponding to the dense input vector x + ValueT* d_vector_y, ///< [out] Pointer to the array of \p num_rows values corresponding to the dense output vector y + int num_rows, ///< [in] number of rows of matrix A. + int num_cols, ///< [in] number of columns of matrix A. + int num_nonzeros, ///< [in] number of nonzero elements of matrix A. + cudaStream_t stream = 0) ///< [in] [optional] CUDA stream to launch kernels within. Default is stream0. + { + SpmvParams spmv_params; + spmv_params.d_values = d_values; + spmv_params.d_row_end_offsets = d_row_offsets + 1; + spmv_params.d_column_indices = d_column_indices; + spmv_params.d_vector_x = d_vector_x; + spmv_params.d_vector_y = d_vector_y; + spmv_params.num_rows = num_rows; + spmv_params.num_cols = num_cols; + spmv_params.num_nonzeros = num_nonzeros; + spmv_params.alpha = ValueT{1}; + spmv_params.beta = ValueT{0}; + + return DispatchSpmv::Dispatch( + d_temp_storage, + temp_storage_bytes, + spmv_params, + stream); + } + + template + CUB_DETAIL_RUNTIME_DEBUG_SYNC_IS_NOT_SUPPORTED + CUB_RUNTIME_FUNCTION static cudaError_t CsrMV(void *d_temp_storage, + size_t &temp_storage_bytes, + const ValueT *d_values, + const int *d_row_offsets, + const int *d_column_indices, + const ValueT *d_vector_x, + ValueT *d_vector_y, + int num_rows, + int num_cols, + int num_nonzeros, + cudaStream_t stream, + bool debug_synchronous) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + + return CsrMV(d_temp_storage, + temp_storage_bytes, + d_values, + d_row_offsets, + d_column_indices, + d_vector_x, + d_vector_y, + num_rows, + num_cols, + num_nonzeros, + stream); + } + + //@} end member group +}; + + + +CUB_NAMESPACE_END + + diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/device/dispatch/dispatch_adjacent_difference.cuh b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/device/dispatch/dispatch_adjacent_difference.cuh new file mode 100644 index 0000000000000000000000000000000000000000..39d58de242997220b9755df8eb9846c843df7234 --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/device/dispatch/dispatch_adjacent_difference.cuh @@ -0,0 +1,403 @@ +/****************************************************************************** + * Copyright (c) 2011-2021, NVIDIA CORPORATION. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the NVIDIA CORPORATION nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ******************************************************************************/ + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include + +CUB_NAMESPACE_BEGIN + + +template +void __global__ DeviceAdjacentDifferenceInitKernel(InputIteratorT first, + InputT *result, + OffsetT num_tiles, + int items_per_tile) +{ + const int tile_idx = static_cast(blockIdx.x * blockDim.x + threadIdx.x); + AgentDifferenceInitT::Process(tile_idx, + first, + result, + num_tiles, + items_per_tile); +} + +template +void __global__ +DeviceAdjacentDifferenceDifferenceKernel(InputIteratorT input, + InputT *first_tile_previous, + OutputIteratorT result, + DifferenceOpT difference_op, + OffsetT num_items) +{ + using ActivePolicyT = + typename ChainedPolicyT::ActivePolicy::AdjacentDifferencePolicy; + + // It is OK to introspect the return type or parameter types of the + // `operator()` function of `__device__` extended lambda within device code. + using OutputT = detail::invoke_result_t; + + using Agent = AgentDifference; + + __shared__ typename Agent::TempStorage storage; + + Agent agent(storage, + input, + first_tile_previous, + result, + difference_op, + num_items); + + int tile_idx = static_cast(blockIdx.x); + OffsetT tile_base = static_cast(tile_idx) + * ActivePolicyT::ITEMS_PER_TILE; + + agent.Process(tile_idx, tile_base); +} + +template +struct DeviceAdjacentDifferencePolicy +{ + using ValueT = typename std::iterator_traits::value_type; + + //------------------------------------------------------------------------------ + // Architecture-specific tuning policies + //------------------------------------------------------------------------------ + + struct Policy300 : ChainedPolicy<300, Policy300, Policy300> + { + using AdjacentDifferencePolicy = + AgentAdjacentDifferencePolicy<128, + Nominal8BItemsToItems(7), + BLOCK_LOAD_WARP_TRANSPOSE, + LOAD_DEFAULT, + BLOCK_STORE_WARP_TRANSPOSE>; + }; + + struct Policy350 : ChainedPolicy<350, Policy350, Policy300> + { + using AdjacentDifferencePolicy = + AgentAdjacentDifferencePolicy<128, + Nominal8BItemsToItems(7), + BLOCK_LOAD_WARP_TRANSPOSE, + MayAlias ? LOAD_CA : LOAD_LDG, + BLOCK_STORE_WARP_TRANSPOSE>; + }; + + using MaxPolicy = Policy350; +}; + +template > +struct DispatchAdjacentDifference : public SelectedPolicy +{ + using InputT = typename std::iterator_traits::value_type; + + void *d_temp_storage; + std::size_t &temp_storage_bytes; + InputIteratorT d_input; + OutputIteratorT d_output; + OffsetT num_items; + DifferenceOpT difference_op; + cudaStream_t stream; + + CUB_RUNTIME_FUNCTION __forceinline__ + DispatchAdjacentDifference(void *d_temp_storage, + std::size_t &temp_storage_bytes, + InputIteratorT d_input, + OutputIteratorT d_output, + OffsetT num_items, + DifferenceOpT difference_op, + cudaStream_t stream) + : d_temp_storage(d_temp_storage) + , temp_storage_bytes(temp_storage_bytes) + , d_input(d_input) + , d_output(d_output) + , num_items(num_items) + , difference_op(difference_op) + , stream(stream) + {} + + CUB_DETAIL_RUNTIME_DEBUG_SYNC_IS_NOT_SUPPORTED + CUB_DEPRECATED CUB_RUNTIME_FUNCTION __forceinline__ + DispatchAdjacentDifference(void *d_temp_storage, + std::size_t &temp_storage_bytes, + InputIteratorT d_input, + OutputIteratorT d_output, + OffsetT num_items, + DifferenceOpT difference_op, + cudaStream_t stream, + bool debug_synchronous) + : d_temp_storage(d_temp_storage) + , temp_storage_bytes(temp_storage_bytes) + , d_input(d_input) + , d_output(d_output) + , num_items(num_items) + , difference_op(difference_op) + , stream(stream) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + } + + /// Invocation + template + CUB_RUNTIME_FUNCTION __forceinline__ cudaError_t Invoke() + { + using AdjacentDifferencePolicyT = + typename ActivePolicyT::AdjacentDifferencePolicy; + + using MaxPolicyT = typename DispatchAdjacentDifference::MaxPolicy; + + cudaError error = cudaSuccess; + + do + { + const int tile_size = AdjacentDifferencePolicyT::ITEMS_PER_TILE; + const int num_tiles = + static_cast(DivideAndRoundUp(num_items, tile_size)); + + std::size_t first_tile_previous_size = MayAlias * num_tiles * + sizeof(InputT); + + void *allocations[1] = {nullptr}; + std::size_t allocation_sizes[1] = {MayAlias * first_tile_previous_size}; + + if (CubDebug(error = AliasTemporaries(d_temp_storage, + temp_storage_bytes, + allocations, + allocation_sizes))) + { + break; + } + + if (d_temp_storage == nullptr) + { + // Return if the caller is simply requesting the size of the storage + // allocation + + if (temp_storage_bytes == 0) + { + temp_storage_bytes = 1; + } + + break; + } + + if (num_items == OffsetT{}) + { + break; + } + + auto first_tile_previous = reinterpret_cast(allocations[0]); + + if (MayAlias) + { + using AgentDifferenceInitT = + AgentDifferenceInit; + + const int init_block_size = AgentDifferenceInitT::BLOCK_THREADS; + const int init_grid_size = DivideAndRoundUp(num_tiles, init_block_size); + + #ifdef CUB_DETAIL_DEBUG_ENABLE_LOG + _CubLog("Invoking DeviceAdjacentDifferenceInitKernel" + "<<<%d, %d, 0, %lld>>>()\n", + init_grid_size, + init_block_size, + reinterpret_cast(stream)); + #endif + + THRUST_NS_QUALIFIER::cuda_cub::launcher::triple_chevron(init_grid_size, + init_block_size, + 0, + stream) + .doit(DeviceAdjacentDifferenceInitKernel, + d_input, + first_tile_previous, + num_tiles, + tile_size); + + error = detail::DebugSyncStream(stream); + + if (CubDebug(error)) + { + break; + } + + // Check for failure to launch + if (CubDebug(error = cudaPeekAtLastError())) + { + break; + } + } + + #ifdef CUB_DETAIL_DEBUG_ENABLE_LOG + _CubLog("Invoking DeviceAdjacentDifferenceDifferenceKernel" + "<<<%d, %d, 0, %lld>>>()\n", + num_tiles, + AdjacentDifferencePolicyT::BLOCK_THREADS, + reinterpret_cast(stream)); + #endif + + THRUST_NS_QUALIFIER::cuda_cub::launcher::triple_chevron( + num_tiles, + AdjacentDifferencePolicyT::BLOCK_THREADS, + 0, + stream) + .doit(DeviceAdjacentDifferenceDifferenceKernel, + d_input, + first_tile_previous, + d_output, + difference_op, + num_items); + + error = detail::DebugSyncStream(stream); + + if (CubDebug(error)) + { + break; + } + + // Check for failure to launch + if (CubDebug(error = cudaPeekAtLastError())) + { + break; + } + } while (0); + + return error; + } + + CUB_RUNTIME_FUNCTION + static cudaError_t Dispatch(void *d_temp_storage, + std::size_t &temp_storage_bytes, + InputIteratorT d_input, + OutputIteratorT d_output, + OffsetT num_items, + DifferenceOpT difference_op, + cudaStream_t stream) + { + using MaxPolicyT = typename DispatchAdjacentDifference::MaxPolicy; + + cudaError error = cudaSuccess; + do + { + // Get PTX version + int ptx_version = 0; + if (CubDebug(error = PtxVersion(ptx_version))) + { + break; + } + + // Create dispatch functor + DispatchAdjacentDifference dispatch(d_temp_storage, + temp_storage_bytes, + d_input, + d_output, + num_items, + difference_op, + stream); + + // Dispatch to chained policy + if (CubDebug(error = MaxPolicyT::Invoke(ptx_version, dispatch))) + { + break; + } + } while (0); + + return error; + } + + CUB_DETAIL_RUNTIME_DEBUG_SYNC_IS_NOT_SUPPORTED + CUB_RUNTIME_FUNCTION + static cudaError_t Dispatch(void *d_temp_storage, + std::size_t &temp_storage_bytes, + InputIteratorT d_input, + OutputIteratorT d_output, + OffsetT num_items, + DifferenceOpT difference_op, + cudaStream_t stream, + bool debug_synchronous) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + + return Dispatch(d_temp_storage, + temp_storage_bytes, + d_input, + d_output, + num_items, + difference_op, + stream); + } +}; + + +CUB_NAMESPACE_END diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/device/dispatch/dispatch_batch_memcpy.cuh b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/device/dispatch/dispatch_batch_memcpy.cuh new file mode 100644 index 0000000000000000000000000000000000000000..a8b5a1f655002afcec3752a90e737edb5fb4b7be --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/device/dispatch/dispatch_batch_memcpy.cuh @@ -0,0 +1,746 @@ +/****************************************************************************** + * Copyright (c) 2011-2022, NVIDIA CORPORATION. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the NVIDIA CORPORATION nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ******************************************************************************/ + +/** + * \file + * cub::DispatchBatchMemcpy provides device-wide, parallel operations for copying data from a number + * of given source buffers to their corresponding destination buffer. + */ + +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +#include + +#include + +#include + +CUB_NAMESPACE_BEGIN + +namespace detail +{ + +/** + * Parameterizable tuning policy type for AgentBatchMemcpy + */ +template +struct AgentBatchMemcpyLargeBuffersPolicy +{ + /// Threads per thread block + static constexpr uint32_t BLOCK_THREADS = _BLOCK_THREADS; + /// The number of bytes each thread copies + static constexpr uint32_t BYTES_PER_THREAD = _BYTES_PER_THREAD; +}; + +/** + * Initialization kernel for tile status initialization (multi-block) + */ +template +__global__ void InitTileStateKernel(BufferOffsetScanTileStateT buffer_offset_scan_tile_state, + BlockOffsetScanTileStateT block_offset_scan_tile_state, + TileOffsetT num_tiles) +{ + // Initialize tile status + buffer_offset_scan_tile_state.InitializeStatus(num_tiles); + block_offset_scan_tile_state.InitializeStatus(num_tiles); +} + +/** + * Kernel that copies buffers that need to be copied by at least one (and potentially many) thread + * blocks. + */ +template +__launch_bounds__(int(ChainedPolicyT::ActivePolicy::AgentLargeBufferPolicyT::BLOCK_THREADS)) + __global__ void MultiBlockBatchMemcpyKernel(InputBufferIt input_buffer_it, + OutputBufferIt output_buffer_it, + BufferSizeIteratorT buffer_sizes, + BufferTileOffsetItT buffer_tile_offsets, + TileT buffer_offset_tile, + TileOffsetT last_tile_offset) +{ + using StatusWord = typename TileT::StatusWord; + using ActivePolicyT = typename ChainedPolicyT::ActivePolicy::AgentLargeBufferPolicyT; + using BufferSizeT = cub::detail::value_t; + /// Internal load/store type. For byte-wise memcpy, a single-byte type + using AliasT = typename ::cuda::std::conditional< + IsMemcpy, + std::iterator_traits, + std::iterator_traits>>::type::value_type; + /// Types of the input and output buffers + using InputBufferT = cub::detail::value_t; + using OutputBufferT = cub::detail::value_t; + + constexpr uint32_t BLOCK_THREADS = ActivePolicyT::BLOCK_THREADS; + constexpr uint32_t ITEMS_PER_THREAD = ActivePolicyT::BYTES_PER_THREAD; + constexpr BufferSizeT TILE_SIZE = static_cast(BLOCK_THREADS * ITEMS_PER_THREAD); + + BufferOffsetT num_blev_buffers = buffer_offset_tile.LoadValid(last_tile_offset); + + uint32_t tile_id = blockIdx.x; + + // No block-level buffers => we're done here + if (num_blev_buffers == 0) + { + return; + } + + // While there's still tiles of bytes from block-level buffers to copied + do + { + __shared__ BufferOffsetT block_buffer_id; + + // Make sure thread 0 does not overwrite the buffer id before other threads have finished with + // the prior iteration of the loop + CTA_SYNC(); + + // Binary search the buffer that this tile belongs to + if (threadIdx.x == 0) + block_buffer_id = UpperBound(buffer_tile_offsets, num_blev_buffers, tile_id) - 1; + + // Make sure thread 0 has written the buffer this thread block is assigned to + CTA_SYNC(); + + const BufferOffsetT buffer_id = block_buffer_id; + + // The relative offset of this tile within the buffer it's assigned to + BufferSizeT tile_offset_within_buffer = + static_cast(tile_id - buffer_tile_offsets[buffer_id]) * TILE_SIZE; + + // If the tile has already reached beyond the work of the end of the last buffer + if (buffer_id >= num_blev_buffers - 1 && tile_offset_within_buffer > buffer_sizes[buffer_id]) + { + return; + } + + // Tiny remainders are copied without vectorizing laods + if (buffer_sizes[buffer_id] - tile_offset_within_buffer <= 32) + { + BufferSizeT thread_offset = tile_offset_within_buffer + threadIdx.x; + for (int i = 0; i < ITEMS_PER_THREAD; i++) + { + if (thread_offset < buffer_sizes[buffer_id]) + { + const auto value = read_item(input_buffer_it[buffer_id], + thread_offset); + write_item(output_buffer_it[buffer_id], + thread_offset, + value); + } + thread_offset += BLOCK_THREADS; + } + } + else + { + copy_items( + input_buffer_it[buffer_id], + output_buffer_it[buffer_id], + (cub::min)(buffer_sizes[buffer_id] - tile_offset_within_buffer, TILE_SIZE), + tile_offset_within_buffer); + } + + tile_id += gridDim.x; + } while (true); +} + +/** + * @brief Kernel that copies data from a batch of given source buffers to their corresponding + * destination buffer. If a buffer's size is to large to be copied by a single thread block, that + * buffer is put into a queue of buffers that will get picked up later on, where multiple blocks + * collaborate on each of these buffers. All other buffers get copied straight away. + * + * @param input_buffer_it [in] Iterator providing the pointers to the source memory buffers + * @param output_buffer_it [in] Iterator providing the pointers to the destination memory buffers + * @param buffer_sizes [in] Iterator providing the number of bytes to be copied for each pair of + * buffers + * @param num_buffers [in] The total number of buffer pairs + * @param blev_buffer_srcs [out] The source pointers of buffers that require block-level + * collaboration + * @param blev_buffer_dsts [out] The destination pointers of buffers that require block-level + * collaboration + * @param blev_buffer_sizes [out] The sizes of buffers that require block-level collaboration + * @param blev_buffer_scan_state [in,out] Tile states for the prefix sum over the count of buffers + * requiring block-level collaboration (to "stream compact" (aka "select") BLEV-buffers) + * @param blev_block_scan_state [in,out] Tile states for the prefix sum over the number of thread + * blocks getting assigned to each buffer that requires block-level collaboration + */ +template +__launch_bounds__(int(ChainedPolicyT::ActivePolicy::AgentSmallBufferPolicyT::BLOCK_THREADS)) + __global__ void BatchMemcpyKernel(InputBufferIt input_buffer_it, + OutputBufferIt output_buffer_it, + BufferSizeIteratorT buffer_sizes, + BufferOffsetT num_buffers, + BlevBufferSrcsOutItT blev_buffer_srcs, + BlevBufferDstsOutItT blev_buffer_dsts, + BlevBufferSizesOutItT blev_buffer_sizes, + BlevBufferTileOffsetsOutItT blev_buffer_tile_offsets, + BLevBufferOffsetTileState blev_buffer_scan_state, + BLevBlockOffsetTileState blev_block_scan_state) +{ + // Internal type used for storing a buffer's size + using BufferSizeT = cub::detail::value_t; + + // Alias the correct tuning policy for the current compilation pass' architecture + using AgentBatchMemcpyPolicyT = typename ChainedPolicyT::ActivePolicy::AgentSmallBufferPolicyT; + + // Block-level specialization + using AgentBatchMemcpyT = AgentBatchMemcpy; + + // Shared memory for AgentBatchMemcpy + __shared__ typename AgentBatchMemcpyT::TempStorage temp_storage; + + // Process this block's tile of input&output buffer pairs + AgentBatchMemcpyT(temp_storage, + input_buffer_it, + output_buffer_it, + buffer_sizes, + num_buffers, + blev_buffer_srcs, + blev_buffer_dsts, + blev_buffer_sizes, + blev_buffer_tile_offsets, + blev_buffer_scan_state, + blev_block_scan_state) + .ConsumeTile(blockIdx.x); +} + +template +struct DeviceBatchMemcpyPolicy +{ + static constexpr uint32_t BLOCK_THREADS = 128U; + static constexpr uint32_t BUFFERS_PER_THREAD = 4U; + static constexpr uint32_t TLEV_BYTES_PER_THREAD = 8U; + + static constexpr uint32_t LARGE_BUFFER_BLOCK_THREADS = 256U; + static constexpr uint32_t LARGE_BUFFER_BYTES_PER_THREAD = 32U; + + static constexpr uint32_t WARP_LEVEL_THRESHOLD = 128; + static constexpr uint32_t BLOCK_LEVEL_THRESHOLD = 8 * 1024; + + using buff_delay_constructor_t = detail::default_delay_constructor_t; + using block_delay_constructor_t = detail::default_delay_constructor_t; + + /// SM35 + struct Policy350 : ChainedPolicy<350, Policy350, Policy350> + { + static constexpr bool PREFER_POW2_BITS = true; + using AgentSmallBufferPolicyT = + AgentBatchMemcpyPolicy; + + using AgentLargeBufferPolicyT = + AgentBatchMemcpyLargeBuffersPolicy; + }; + + /// SM70 + struct Policy700 : ChainedPolicy<700, Policy700, Policy350> + { + static constexpr bool PREFER_POW2_BITS = false; + using AgentSmallBufferPolicyT = + AgentBatchMemcpyPolicy; + + using AgentLargeBufferPolicyT = + AgentBatchMemcpyLargeBuffersPolicy; + }; + + using MaxPolicy = Policy700; +}; + +/** + * @tparam InputBufferIt [inferred] Random-access input iterator type providing the pointers + * to the source memory buffers + * @tparam OutputBufferIt [inferred] Random-access input iterator type providing the pointers + * to the destination memory buffers + * @tparam BufferSizeIteratorT [inferred] Random-access input iterator type providing the + * number of bytes to be copied for each pair of buffers + * @tparam BufferOffsetT Integer type large enough to hold any offset in [0, num_buffers) + * @tparam BlockOffsetT Integer type large enough to hold any offset in [0, + * num_thread_blocks_launched) + */ +template , + bool IsMemcpy = true> +struct DispatchBatchMemcpy : SelectedPolicy +{ + //------------------------------------------------------------------------------ + // TYPE ALIASES + //------------------------------------------------------------------------------ + // Tile state for the single-pass prefix scan to "stream compact" (aka "select") the buffers + // requiring block-level collaboration + using BufferPartitionScanTileStateT = typename cub::ScanTileState; + + // Tile state for the single-pass prefix scan to keep track of how many blocks are assigned to + // each of the buffers requiring block-level collaboration + using BufferTileOffsetScanStateT = typename cub::ScanTileState; + + // Internal type used to keep track of a buffer's size + using BufferSizeT = cub::detail::value_t; + + //------------------------------------------------------------------------------ + // Member Veriables + //------------------------------------------------------------------------------ + void *d_temp_storage; + size_t &temp_storage_bytes; + InputBufferIt input_buffer_it; + OutputBufferIt output_buffer_it; + BufferSizeIteratorT buffer_sizes; + BufferOffsetT num_buffers; + cudaStream_t stream; + + //------------------------------------------------------------------------------ + // Constructor + //------------------------------------------------------------------------------ + CUB_RUNTIME_FUNCTION __forceinline__ DispatchBatchMemcpy(void *d_temp_storage, + size_t &temp_storage_bytes, + InputBufferIt input_buffer_it, + OutputBufferIt output_buffer_it, + BufferSizeIteratorT buffer_sizes, + BufferOffsetT num_buffers, + cudaStream_t stream) + : d_temp_storage(d_temp_storage) + , temp_storage_bytes(temp_storage_bytes) + , input_buffer_it(input_buffer_it) + , output_buffer_it(output_buffer_it) + , buffer_sizes(buffer_sizes) + , num_buffers(num_buffers) + , stream(stream) + {} + + //------------------------------------------------------------------------------ + // Chained policy invocation + //------------------------------------------------------------------------------ + /** + * @brief Tuning policy invocation. This member function template is getting instantiated for all + * tuning policies in the tuning policy chain. It is, however, *invoked* for the correct tuning + * policy only. + */ + template + CUB_RUNTIME_FUNCTION __forceinline__ cudaError_t Invoke() + { + using MaxPolicyT = typename DispatchBatchMemcpy::MaxPolicy; + + // Single-pass prefix scan tile states for the prefix-sum over the number of block-level buffers + using BLevBufferOffsetTileState = cub::ScanTileState; + + // Single-pass prefix scan tile states for the prefix sum over the number of thread blocks + // assigned to each of the block-level buffers + using BLevBlockOffsetTileState = cub::ScanTileState; + + cudaError error = cudaSuccess; + + enum : uint32_t + { + // Memory for the source pointers of the buffers that require block-level collaboration + MEM_BLEV_BUFFER_SRCS = 0, + // Memory for the destination pointers of the buffers that require block-level collaboration + MEM_BLEV_BUFFER_DSTS, + // Memory for the block-level buffers' sizes + MEM_BLEV_BUFFER_SIZES, + // Memory to keep track of the assignment of thread blocks to block-level buffers + MEM_BLEV_BUFFER_TBLOCK, + // Memory for the tile states of the prefix sum over the number of buffers that require + // block-level collaboration + MEM_BLEV_BUFFER_SCAN_STATE, + // Memory for the scan tile states of the prefix sum over the number of thread block's + // assigned up to and including a certain block-level buffer + MEM_BLEV_BLOCK_SCAN_STATE, + // Total number of distinct memory allocations in the temporary storage memory BLOB + MEM_NUM_ALLOCATIONS + }; + + // Number of threads per block for initializing the grid states + constexpr BlockOffsetT INIT_KERNEL_THREADS = 128U; + + // The number of buffers that get processed per thread block + constexpr uint32_t TILE_SIZE = ActivePolicyT::AgentSmallBufferPolicyT::BLOCK_THREADS * + ActivePolicyT::AgentSmallBufferPolicyT::BUFFERS_PER_THREAD; + + // The number of thread blocks (or tiles) required to process all of the given buffers + BlockOffsetT num_tiles = DivideAndRoundUp(num_buffers, TILE_SIZE); + + using BlevBufferSrcsOutT = + cub::detail::conditional_t>; + using BlevBufferDstOutT = + cub::detail::conditional_t>; + using BlevBufferSrcsOutItT = BlevBufferSrcsOutT *; + using BlevBufferDstsOutItT = BlevBufferDstOutT *; + using BlevBufferSizesOutItT = BufferSizeT *; + using BlevBufferTileOffsetsOutItT = BlockOffsetT *; + + temporary_storage::layout temporary_storage_layout; + + auto blev_buffer_srcs_slot = temporary_storage_layout.get_slot(MEM_BLEV_BUFFER_SRCS); + auto blev_buffer_dsts_slot = temporary_storage_layout.get_slot(MEM_BLEV_BUFFER_DSTS); + auto blev_buffer_sizes_slot = temporary_storage_layout.get_slot(MEM_BLEV_BUFFER_SIZES); + auto blev_buffer_block_slot = temporary_storage_layout.get_slot(MEM_BLEV_BUFFER_TBLOCK); + auto blev_buffer_scan_slot = temporary_storage_layout.get_slot(MEM_BLEV_BUFFER_SCAN_STATE); + auto blev_buffer_block_scan_slot = temporary_storage_layout.get_slot(MEM_BLEV_BLOCK_SCAN_STATE); + + auto blev_buffer_srcs_alloc = + blev_buffer_srcs_slot->template create_alias(); + auto blev_buffer_dsts_alloc = blev_buffer_dsts_slot->template create_alias(); + auto blev_buffer_sizes_alloc = blev_buffer_sizes_slot->template create_alias(); + auto blev_buffer_block_alloc = blev_buffer_block_slot->template create_alias(); + auto blev_buffer_scan_alloc = blev_buffer_scan_slot->template create_alias(); + auto blev_block_scan_alloc = blev_buffer_block_scan_slot->template create_alias(); + + std::size_t buffer_offset_scan_storage = 0; + std::size_t blev_block_scan_storage = 0; + CubDebug(error = BLevBufferOffsetTileState::AllocationSize(static_cast(num_tiles), + buffer_offset_scan_storage)); + if (error) + { + return error; + } + CubDebug(error = BLevBlockOffsetTileState::AllocationSize(static_cast(num_tiles), + blev_block_scan_storage)); + if (error) + { + return error; + } + + blev_buffer_srcs_alloc.grow(num_buffers); + blev_buffer_dsts_alloc.grow(num_buffers); + blev_buffer_sizes_alloc.grow(num_buffers); + blev_buffer_block_alloc.grow(num_buffers); + blev_buffer_scan_alloc.grow(buffer_offset_scan_storage); + blev_block_scan_alloc.grow(blev_block_scan_storage); + + // Just return if no temporary storage is provided + if (d_temp_storage == nullptr) + { + temp_storage_bytes = temporary_storage_layout.get_size(); + return error; + } + + // Return if empty problem + if (num_buffers == 0) + { + return error; + } + + // Alias memory buffers into the storage blob + if (CubDebug( + error = temporary_storage_layout.map_to_buffer(d_temp_storage, temp_storage_bytes))) + { + return error; + } + + // Alias into temporary storage allocation + BlevBufferSrcsOutItT d_blev_src_buffers = blev_buffer_srcs_alloc.get(); + BlevBufferDstsOutItT d_blev_dst_buffers = blev_buffer_dsts_alloc.get(); + BlevBufferSizesOutItT d_blev_buffer_sizes = blev_buffer_sizes_alloc.get(); + BlevBufferTileOffsetsOutItT d_blev_block_offsets = blev_buffer_block_alloc.get(); + + // Kernels' grid sizes + BlockOffsetT init_grid_size = DivideAndRoundUp(num_tiles, INIT_KERNEL_THREADS); + BlockOffsetT batch_memcpy_grid_size = num_tiles; + + // Kernels + auto init_scan_states_kernel = + InitTileStateKernel; + auto batch_memcpy_non_blev_kernel = BatchMemcpyKernel; + + auto multi_block_memcpy_kernel = MultiBlockBatchMemcpyKernel; + + constexpr uint32_t BLEV_BLOCK_THREADS = ActivePolicyT::AgentLargeBufferPolicyT::BLOCK_THREADS; + + // Get device ordinal + int device_ordinal; + if (CubDebug(error = cudaGetDevice(&device_ordinal))) + { + return error; + } + + // Get SM count + int sm_count; + if (CubDebug(error = cudaDeviceGetAttribute(&sm_count, + cudaDevAttrMultiProcessorCount, + device_ordinal))) + { + return error; + } + + // Get SM occupancy for the batch memcpy block-level buffers kernel + int batch_memcpy_blev_occupancy; + if (CubDebug(error = MaxSmOccupancy(batch_memcpy_blev_occupancy, + multi_block_memcpy_kernel, + BLEV_BLOCK_THREADS))) + { + return error; + } + + int batch_memcpy_blev_grid_size = + static_cast(sm_count * batch_memcpy_blev_occupancy * CUB_SUBSCRIPTION_FACTOR(0)); + + // Construct the tile status for the buffer prefix sum + BLevBufferOffsetTileState buffer_scan_tile_state; + if (CubDebug(error = buffer_scan_tile_state.Init(static_cast(num_tiles), + blev_buffer_scan_alloc.get(), + buffer_offset_scan_storage))) + { + return error; + } + + // Construct the tile status for thread blocks-to-buffer-assignment prefix sum + BLevBlockOffsetTileState block_scan_tile_state; + if (CubDebug(error = block_scan_tile_state.Init(static_cast(num_tiles), + blev_block_scan_alloc.get(), + blev_block_scan_storage))) + { + return error; + } + +#ifdef CUB_DETAIL_DEBUG_ENABLE_LOG + _CubLog("Invoking " + "InitTileStateKernel<<<%d, %d, 0, %lld>>>()\n", + static_cast(init_grid_size), + INIT_KERNEL_THREADS, + (long long)stream); +#endif + + // Invoke init_kernel to initialize buffer prefix sum-tile descriptors + error = + THRUST_NS_QUALIFIER::cuda_cub::launcher::triple_chevron(init_grid_size, + INIT_KERNEL_THREADS, + 0, + stream) + .doit(init_scan_states_kernel, buffer_scan_tile_state, block_scan_tile_state, num_tiles); + + // Check for failure to launch + if (CubDebug(error)) + { + return error; + } + + // Sync the stream if specified to flush runtime errors + error = detail::DebugSyncStream(stream); + + // Check for failure to launch + if (CubDebug(error)) + { + return error; + } + +#ifdef CUB_DETAIL_DEBUG_ENABLE_LOG + _CubLog("Invoking " + "BatchMemcpyKernel<<<%d, %d, 0, %lld>>>()\n", + static_cast(batch_memcpy_grid_size), + ActivePolicyT::AgentSmallBufferPolicyT::BLOCK_THREADS, + (long long)stream); +#endif + + // Invoke kernel to copy small buffers and put the larger ones into a queue that will get picked + // up by next kernel + error = THRUST_NS_QUALIFIER::cuda_cub::launcher::triple_chevron( + batch_memcpy_grid_size, + ActivePolicyT::AgentSmallBufferPolicyT::BLOCK_THREADS, + 0, + stream) + .doit(batch_memcpy_non_blev_kernel, + input_buffer_it, + output_buffer_it, + buffer_sizes, + num_buffers, + d_blev_src_buffers, + d_blev_dst_buffers, + d_blev_buffer_sizes, + d_blev_block_offsets, + buffer_scan_tile_state, + block_scan_tile_state); + + // Check for failure to launch + if (CubDebug(error)) + { + return error; + } + + // Sync the stream if specified to flush runtime errors + error = detail::DebugSyncStream(stream); + if (CubDebug(error)) + { + return error; + } + +#ifdef CUB_DETAIL_DEBUG_ENABLE_LOG + _CubLog("Invoking " + "MultiBlockBatchMemcpyKernel<<<%d, %d, 0, %lld>>>()\n", + static_cast(batch_memcpy_blev_grid_size), + BLEV_BLOCK_THREADS, + (long long)stream); +#endif + + error = THRUST_NS_QUALIFIER::cuda_cub::launcher::triple_chevron(batch_memcpy_blev_grid_size, + BLEV_BLOCK_THREADS, + 0, + stream) + .doit(multi_block_memcpy_kernel, + d_blev_src_buffers, + d_blev_dst_buffers, + d_blev_buffer_sizes, + d_blev_block_offsets, + buffer_scan_tile_state, + batch_memcpy_grid_size - 1); + + // Check for failure to launch + if (CubDebug(error)) + { + return error; + } + + // Sync the stream if specified to flush runtime errors + error = detail::DebugSyncStream(stream); + + return error; + } + + //------------------------------------------------------------------------------ + // Dispatch entrypoints + //------------------------------------------------------------------------------ + /** + * Internal dispatch routine + */ + CUB_RUNTIME_FUNCTION __forceinline__ static cudaError_t Dispatch(void *d_temp_storage, + size_t &temp_storage_bytes, + InputBufferIt input_buffer_it, + OutputBufferIt output_buffer_it, + BufferSizeIteratorT buffer_sizes, + BufferOffsetT num_buffers, + cudaStream_t stream) + { + using MaxPolicyT = typename DispatchBatchMemcpy::MaxPolicy; + + cudaError_t error = cudaSuccess; + + // Get PTX version + int ptx_version = 0; + if (CubDebug(error = PtxVersion(ptx_version))) + { + return error; + } + + // Create dispatch functor + DispatchBatchMemcpy dispatch(d_temp_storage, + temp_storage_bytes, + input_buffer_it, + output_buffer_it, + buffer_sizes, + num_buffers, + stream); + + // Dispatch to chained policy + if (CubDebug(error = MaxPolicyT::Invoke(ptx_version, dispatch))) + { + return error; + } + return error; + } +}; + +} // namespace detail + +CUB_NAMESPACE_END diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/device/dispatch/dispatch_histogram.cuh b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/device/dispatch/dispatch_histogram.cuh new file mode 100644 index 0000000000000000000000000000000000000000..b393d3c82454389be192fe1557509b4d4f6755e3 --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/device/dispatch/dispatch_histogram.cuh @@ -0,0 +1,1623 @@ + +/****************************************************************************** + * Copyright (c) 2011, Duane Merrill. All rights reserved. + * Copyright (c) 2011-2018, NVIDIA CORPORATION. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the NVIDIA CORPORATION nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ******************************************************************************/ + +/** + * @file + * cub::DeviceHistogram provides device-wide parallel operations for constructing histogram(s) + * from a sequence of samples data residing within device-accessible memory. + */ + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include + +#include +#include +#include + +#include + +CUB_NAMESPACE_BEGIN + +/****************************************************************************** + * Histogram kernel entry points + *****************************************************************************/ + +/** + * Histogram initialization kernel entry point + * + * @tparam NUM_ACTIVE_CHANNELS + * Number of channels actively being histogrammed + * + * @tparam CounterT + * Integer type for counting sample occurrences per histogram bin + * + * @tparam OffsetT + * Signed integer type for global offsets + * + * @param num_output_bins_wrapper + * Number of output histogram bins per channel + * + * @param d_output_histograms_wrapper + * Histogram counter data having logical dimensions + * `CounterT[NUM_ACTIVE_CHANNELS][num_bins.array[CHANNEL]]` + * + * @param tile_queue + * Drain queue descriptor for dynamically mapping tile data onto thread blocks + */ +template +__global__ void +DeviceHistogramInitKernel(ArrayWrapper num_output_bins_wrapper, + ArrayWrapper d_output_histograms_wrapper, + GridQueue tile_queue) +{ + if ((threadIdx.x == 0) && (blockIdx.x == 0)) + { + tile_queue.ResetDrain(); + } + + int output_bin = (blockIdx.x * blockDim.x) + threadIdx.x; + +#pragma unroll + for (int CHANNEL = 0; CHANNEL < NUM_ACTIVE_CHANNELS; ++CHANNEL) + { + if (output_bin < num_output_bins_wrapper.array[CHANNEL]) + { + d_output_histograms_wrapper.array[CHANNEL][output_bin] = 0; + } + } +} + +/** + * Histogram privatized sweep kernel entry point (multi-block). + * Computes privatized histograms, one per thread block. + * + * + * @tparam AgentHistogramPolicyT + * Parameterized AgentHistogramPolicy tuning policy type + * + * @tparam PRIVATIZED_SMEM_BINS + * Maximum number of histogram bins per channel (e.g., up to 256) + * + * @tparam NUM_CHANNELS + * Number of channels interleaved in the input data (may be greater than the number of channels + * being actively histogrammed) + * + * @tparam NUM_ACTIVE_CHANNELS + * Number of channels actively being histogrammed + * + * @tparam SampleIteratorT + * The input iterator type. \iterator. + * + * @tparam CounterT + * Integer type for counting sample occurrences per histogram bin + * + * @tparam PrivatizedDecodeOpT + * The transform operator type for determining privatized counter indices from samples, + * one for each channel + * + * @tparam OutputDecodeOpT + * The transform operator type for determining output bin-ids from privatized counter indices, + * one for each channel + * + * @tparam OffsetT + * integer type for global offsets + * + * @param d_samples + * Input data to reduce + * + * @param num_output_bins_wrapper + * The number bins per final output histogram + * + * @param num_privatized_bins_wrapper + * The number bins per privatized histogram + * + * @param d_output_histograms_wrapper + * Reference to final output histograms + * + * @param d_privatized_histograms_wrapper + * Reference to privatized histograms + * + * @param output_decode_op_wrapper + * The transform operator for determining output bin-ids from privatized counter indices, + * one for each channel + * + * @param privatized_decode_op_wrapper + * The transform operator for determining privatized counter indices from samples, + * one for each channel + * + * @param num_row_pixels + * The number of multi-channel pixels per row in the region of interest + * + * @param num_rows + * The number of rows in the region of interest + * + * @param row_stride_samples + * The number of samples between starts of consecutive rows in the region of interest + * + * @param tiles_per_row + * Number of image tiles per row + * + * @param tile_queue + * Drain queue descriptor for dynamically mapping tile data onto thread blocks + */ +template +__launch_bounds__(int(ChainedPolicyT::ActivePolicy::AgentHistogramPolicyT::BLOCK_THREADS)) __global__ + void DeviceHistogramSweepKernel( + SampleIteratorT d_samples, + ArrayWrapper num_output_bins_wrapper, + ArrayWrapper num_privatized_bins_wrapper, + ArrayWrapper d_output_histograms_wrapper, + ArrayWrapper d_privatized_histograms_wrapper, + ArrayWrapper output_decode_op_wrapper, + ArrayWrapper privatized_decode_op_wrapper, + OffsetT num_row_pixels, + OffsetT num_rows, + OffsetT row_stride_samples, + int tiles_per_row, + GridQueue tile_queue) +{ + // Thread block type for compositing input tiles + using AgentHistogramPolicyT = typename ChainedPolicyT::ActivePolicy::AgentHistogramPolicyT; + using AgentHistogramT = AgentHistogram; + + // Shared memory for AgentHistogram + __shared__ typename AgentHistogramT::TempStorage temp_storage; + + AgentHistogramT agent(temp_storage, + d_samples, + num_output_bins_wrapper.array, + num_privatized_bins_wrapper.array, + d_output_histograms_wrapper.array, + d_privatized_histograms_wrapper.array, + output_decode_op_wrapper.array, + privatized_decode_op_wrapper.array); + + // Initialize counters + agent.InitBinCounters(); + + // Consume input tiles + agent.ConsumeTiles(num_row_pixels, num_rows, row_stride_samples, tiles_per_row, tile_queue); + + // Store output to global (if necessary) + agent.StoreOutput(); +} + +namespace detail +{ + +template +struct dispatch_histogram +{ + void *d_temp_storage; + size_t &temp_storage_bytes; + SampleIteratorT d_samples; + CounterT **d_output_histograms; + int *num_privatized_levels; + PrivatizedDecodeOpT *privatized_decode_op; + int *num_output_levels; + OutputDecodeOpT *output_decode_op; + int max_num_output_bins; + OffsetT num_row_pixels; + OffsetT num_rows; + OffsetT row_stride_samples; + cudaStream_t stream; + + CUB_RUNTIME_FUNCTION + dispatch_histogram(void *d_temp_storage, + size_t &temp_storage_bytes, + SampleIteratorT d_samples, + CounterT *d_output_histograms[NUM_ACTIVE_CHANNELS], + int num_privatized_levels[NUM_ACTIVE_CHANNELS], + PrivatizedDecodeOpT privatized_decode_op[NUM_ACTIVE_CHANNELS], + int num_output_levels[NUM_ACTIVE_CHANNELS], + OutputDecodeOpT output_decode_op[NUM_ACTIVE_CHANNELS], + int max_num_output_bins, + OffsetT num_row_pixels, + OffsetT num_rows, + OffsetT row_stride_samples, + cudaStream_t stream) + : d_temp_storage(d_temp_storage) + , temp_storage_bytes(temp_storage_bytes) + , d_samples(d_samples) + , d_output_histograms(d_output_histograms) + , num_privatized_levels(num_privatized_levels) + , privatized_decode_op(privatized_decode_op) + , num_output_levels(num_output_levels) + , output_decode_op(output_decode_op) + , max_num_output_bins(max_num_output_bins) + , num_row_pixels(num_row_pixels) + , num_rows(num_rows) + , row_stride_samples(row_stride_samples) + , stream(stream) + {} + + template + CUB_RUNTIME_FUNCTION __forceinline__ cudaError_t + Invoke(DeviceHistogramInitKernelT histogram_init_kernel, + DeviceHistogramSweepKernelT histogram_sweep_kernel) + { + cudaError error = cudaSuccess; + + const int block_threads = ActivePolicyT::AgentHistogramPolicyT::BLOCK_THREADS; + const int pixels_per_thread = ActivePolicyT::AgentHistogramPolicyT::PIXELS_PER_THREAD; + + do + { + // Get device ordinal + int device_ordinal; + if (CubDebug(error = cudaGetDevice(&device_ordinal))) + { + break; + } + + // Get SM count + int sm_count; + if (CubDebug(error = cudaDeviceGetAttribute(&sm_count, + cudaDevAttrMultiProcessorCount, + device_ordinal))) + { + break; + } + + // Get SM occupancy for histogram_sweep_kernel + int histogram_sweep_sm_occupancy; + if (CubDebug(error = MaxSmOccupancy(histogram_sweep_sm_occupancy, + histogram_sweep_kernel, + block_threads))) + { + break; + } + + // Get device occupancy for histogram_sweep_kernel + int histogram_sweep_occupancy = histogram_sweep_sm_occupancy * sm_count; + + if (num_row_pixels * NUM_CHANNELS == row_stride_samples) + { + // Treat as a single linear array of samples + num_row_pixels *= num_rows; + num_rows = 1; + row_stride_samples = num_row_pixels * NUM_CHANNELS; + } + + // Get grid dimensions, trying to keep total blocks ~histogram_sweep_occupancy + int pixels_per_tile = block_threads * pixels_per_thread; + int tiles_per_row = static_cast(cub::DivideAndRoundUp(num_row_pixels, pixels_per_tile)); + int blocks_per_row = CUB_MIN(histogram_sweep_occupancy, tiles_per_row); + int blocks_per_col = (blocks_per_row > 0) + ? int(CUB_MIN(histogram_sweep_occupancy / blocks_per_row, num_rows)) + : 0; + int num_thread_blocks = blocks_per_row * blocks_per_col; + + dim3 sweep_grid_dims; + sweep_grid_dims.x = (unsigned int)blocks_per_row; + sweep_grid_dims.y = (unsigned int)blocks_per_col; + sweep_grid_dims.z = 1; + + // Temporary storage allocation requirements + const int NUM_ALLOCATIONS = NUM_ACTIVE_CHANNELS + 1; + void *allocations[NUM_ALLOCATIONS] = {}; + size_t allocation_sizes[NUM_ALLOCATIONS]; + + for (int CHANNEL = 0; CHANNEL < NUM_ACTIVE_CHANNELS; ++CHANNEL) + { + allocation_sizes[CHANNEL] = size_t(num_thread_blocks) * + (num_privatized_levels[CHANNEL] - 1) * sizeof(CounterT); + } + + allocation_sizes[NUM_ALLOCATIONS - 1] = GridQueue::AllocationSize(); + + // Alias the temporary allocations from the single storage blob (or compute the + // necessary size of the blob) + if (CubDebug( + error = + AliasTemporaries(d_temp_storage, temp_storage_bytes, allocations, allocation_sizes))) + { + break; + } + + if (d_temp_storage == nullptr) + { + // Return if the caller is simply requesting the size of the storage allocation + break; + } + + // Construct the grid queue descriptor + GridQueue tile_queue(allocations[NUM_ALLOCATIONS - 1]); + + // Setup array wrapper for histogram channel output (because we can't pass static arrays + // as kernel parameters) + ArrayWrapper d_output_histograms_wrapper; + for (int CHANNEL = 0; CHANNEL < NUM_ACTIVE_CHANNELS; ++CHANNEL) + { + d_output_histograms_wrapper.array[CHANNEL] = d_output_histograms[CHANNEL]; + } + + // Setup array wrapper for privatized per-block histogram channel output (because we + // can't pass static arrays as kernel parameters) + ArrayWrapper d_privatized_histograms_wrapper; + for (int CHANNEL = 0; CHANNEL < NUM_ACTIVE_CHANNELS; ++CHANNEL) + { + d_privatized_histograms_wrapper.array[CHANNEL] = (CounterT *)allocations[CHANNEL]; + } + + // Setup array wrapper for sweep bin transforms (because we can't pass static arrays as + // kernel parameters) + ArrayWrapper privatized_decode_op_wrapper; + for (int CHANNEL = 0; CHANNEL < NUM_ACTIVE_CHANNELS; ++CHANNEL) + { + privatized_decode_op_wrapper.array[CHANNEL] = privatized_decode_op[CHANNEL]; + } + + // Setup array wrapper for aggregation bin transforms (because we can't pass static + // arrays as kernel parameters) + ArrayWrapper output_decode_op_wrapper; + for (int CHANNEL = 0; CHANNEL < NUM_ACTIVE_CHANNELS; ++CHANNEL) + { + output_decode_op_wrapper.array[CHANNEL] = output_decode_op[CHANNEL]; + } + + // Setup array wrapper for num privatized bins (because we can't pass static arrays as + // kernel parameters) + ArrayWrapper num_privatized_bins_wrapper; + for (int CHANNEL = 0; CHANNEL < NUM_ACTIVE_CHANNELS; ++CHANNEL) + { + num_privatized_bins_wrapper.array[CHANNEL] = num_privatized_levels[CHANNEL] - 1; + } + + // Setup array wrapper for num output bins (because we can't pass static arrays as + // kernel parameters) + ArrayWrapper num_output_bins_wrapper; + for (int CHANNEL = 0; CHANNEL < NUM_ACTIVE_CHANNELS; ++CHANNEL) + { + num_output_bins_wrapper.array[CHANNEL] = num_output_levels[CHANNEL] - 1; + } + + int histogram_init_block_threads = 256; + + int histogram_init_grid_dims = (max_num_output_bins + histogram_init_block_threads - 1) / + histogram_init_block_threads; + +// Log DeviceHistogramInitKernel configuration +#ifdef CUB_DETAIL_DEBUG_ENABLE_LOG + _CubLog("Invoking DeviceHistogramInitKernel<<<%d, %d, 0, %lld>>>()\n", + histogram_init_grid_dims, + histogram_init_block_threads, + (long long)stream); +#endif + + // Invoke histogram_init_kernel + THRUST_NS_QUALIFIER::cuda_cub::launcher::triple_chevron(histogram_init_grid_dims, + histogram_init_block_threads, + 0, + stream) + .doit(histogram_init_kernel, + num_output_bins_wrapper, + d_output_histograms_wrapper, + tile_queue); + + // Return if empty problem + if ((blocks_per_row == 0) || (blocks_per_col == 0)) + { + break; + } + +// Log histogram_sweep_kernel configuration +#ifdef CUB_DETAIL_DEBUG_ENABLE_LOG + _CubLog("Invoking histogram_sweep_kernel<<<{%d, %d, %d}, %d, 0, %lld>>>(), %d pixels " + "per thread, %d SM occupancy\n", + sweep_grid_dims.x, + sweep_grid_dims.y, + sweep_grid_dims.z, + block_threads, + (long long)stream, + pixels_per_thread, + histogram_sweep_sm_occupancy); +#endif + + // Invoke histogram_sweep_kernel + THRUST_NS_QUALIFIER::cuda_cub::launcher::triple_chevron(sweep_grid_dims, + block_threads, + 0, + stream) + .doit(histogram_sweep_kernel, + d_samples, + num_output_bins_wrapper, + num_privatized_bins_wrapper, + d_output_histograms_wrapper, + d_privatized_histograms_wrapper, + output_decode_op_wrapper, + privatized_decode_op_wrapper, + num_row_pixels, + num_rows, + row_stride_samples, + tiles_per_row, + tile_queue); + + // Check for failure to launch + if (CubDebug(error = cudaPeekAtLastError())) + { + break; + } + + // Sync the stream if specified to flush runtime errors + error = detail::DebugSyncStream(stream); + if (CubDebug(error)) + { + break; + } + } while (0); + + return error; + } + + template + CUB_RUNTIME_FUNCTION __forceinline__ cudaError_t Invoke() + { + return Invoke(DeviceHistogramInitKernel, + DeviceHistogramSweepKernel); + } +}; + +} // namespace detail + +/****************************************************************************** + * Dispatch + ******************************************************************************/ + +/** + * Utility class for dispatching the appropriately-tuned kernels for DeviceHistogram + * + * @tparam NUM_CHANNELS + * Number of channels interleaved in the input data (may be greater than the number of channels + * being actively histogrammed) + * + * @tparam NUM_ACTIVE_CHANNELS + * Number of channels actively being histogrammed + * + * @tparam SampleIteratorT + * Random-access input iterator type for reading input items \iterator + * + * @tparam CounterT + * Integer type for counting sample occurrences per histogram bin + * + * @tparam LevelT + * Type for specifying bin level boundaries + * + * @tparam OffsetT + * Signed integer type for global offsets + * + * @tparam SelectedPolicy + * Implementation detail, do not specify directly, requirements on the + * content of this type are subject to breaking change. + */ +template , + CounterT, + NUM_CHANNELS, + NUM_ACTIVE_CHANNELS>> +struct DispatchHistogram : SelectedPolicy +{ +public: + //--------------------------------------------------------------------- + // Types and constants + //--------------------------------------------------------------------- + + /// The sample value type of the input iterator + using SampleT = cub::detail::value_t; + + enum + { + // Maximum number of bins per channel for which we will use a privatized smem strategy + MAX_PRIVATIZED_SMEM_BINS = 256 + }; + + //--------------------------------------------------------------------- + // Transform functors for converting samples to bin-ids + //--------------------------------------------------------------------- + + // Searches for bin given a list of bin-boundary levels + template + struct SearchTransform + { + LevelIteratorT d_levels; // Pointer to levels array + int num_output_levels; // Number of levels in array + + /** + * @brief Initializer + * + * @param d_levels_ Pointer to levels array + * @param num_output_levels_ Number of levels in array + */ + __host__ __device__ __forceinline__ void Init(LevelIteratorT d_levels_, int num_output_levels_) + { + this->d_levels = d_levels_; + this->num_output_levels = num_output_levels_; + } + + // Method for converting samples to bin-ids + template + __host__ __device__ __forceinline__ void BinSelect(_SampleT sample, int &bin, bool valid) + { + /// Level iterator wrapper type + // Wrap the native input pointer with CacheModifiedInputIterator + // or Directly use the supplied input iterator type + using WrappedLevelIteratorT = + cub::detail::conditional_t::value, + CacheModifiedInputIterator, + LevelIteratorT>; + + WrappedLevelIteratorT wrapped_levels(d_levels); + + int num_bins = num_output_levels - 1; + if (valid) + { + bin = UpperBound(wrapped_levels, num_output_levels, (LevelT)sample) - 1; + if (bin >= num_bins) + bin = -1; + } + } + }; + + // Scales samples to evenly-spaced bins + struct ScaleTransform + { + private: + using CommonT = typename ::cuda::std::common_type::type; + static_assert(::cuda::std::is_convertible::value, + "The common type of `LevelT` and `SampleT` must be " + "convertible to `int`."); + static_assert(::cuda::std::is_trivially_copyable::value, + "The common type of `LevelT` and `SampleT` must be " + "trivially copyable."); + + // An arithmetic type that's used for bin computation of integral types, guaranteed to not + // overflow for (max_level - min_level) * scale.fraction.bins. Since we drop invalid samples + // of less than min_level, (sample - min_level) is guaranteed to be non-negative. We use the + // rule: 2^l * 2^r = 2^(l + r) to determine a sufficiently large type to hold the + // multiplication result. + // If CommonT used to be a 128-bit wide integral type already, we use CommonT's arithmetic + using IntArithmeticT = cub::detail::conditional_t< // + sizeof(SampleT) + sizeof(CommonT) <= sizeof(uint32_t), // + uint32_t, // +#if CUB_IS_INT128_ENABLED + cub::detail::conditional_t< // + (::cuda::std::is_same::value || // + ::cuda::std::is_same::value), // + CommonT, // + uint64_t> // +#else + uint64_t +#endif + >; + + // Alias template that excludes __[u]int128 from the integral types + template + using is_integral_excl_int128 = +#if CUB_IS_INT128_ENABLED + cub::detail::conditional_t< + ::cuda::std::is_same::value && ::cuda::std::is_same::value, + ::cuda::std::false_type, + ::cuda::std::is_integral>; +#else + ::cuda::std::is_integral; +#endif + + union ScaleT + { + // Used when CommonT is not floating-point to avoid intermediate + // rounding errors (see NVIDIA/cub#489). + struct FractionT + { + CommonT bins; + CommonT range; + } fraction; + + // Used when CommonT is floating-point as an optimization. + CommonT reciprocal; + }; + + CommonT m_max; // Max sample level (exclusive) + CommonT m_min; // Min sample level (inclusive) + ScaleT m_scale; // Bin scaling + + template + __host__ __device__ __forceinline__ ScaleT + ComputeScale(int num_levels, T max_level, T min_level, ::cuda::std::true_type /* is_fp */) + { + ScaleT result; + result.reciprocal = + static_cast(static_cast(num_levels - 1) / static_cast(max_level - min_level)); + return result; + } + + template + __host__ __device__ __forceinline__ ScaleT + ComputeScale(int num_levels, T max_level, T min_level, ::cuda::std::false_type /* is_fp */) + { + ScaleT result; + result.fraction.bins = static_cast(num_levels - 1); + result.fraction.range = static_cast(max_level - min_level); + return result; + } + + template + __host__ __device__ __forceinline__ ScaleT ComputeScale(int num_levels, + T max_level, + T min_level) + { + return this->ComputeScale(num_levels, + max_level, + min_level, + ::cuda::std::is_floating_point{}); + } + +#ifdef __CUDA_FP16_TYPES_EXIST__ + __host__ __device__ __forceinline__ ScaleT ComputeScale(int num_levels, + __half max_level, + __half min_level) + { + NV_IF_TARGET( + NV_PROVIDES_SM_53, + (return this->ComputeScale(num_levels, max_level, min_level, ::cuda::std::true_type{});), + (return this->ComputeScale(num_levels, + __half2float(max_level), + __half2float(min_level), + ::cuda::std::true_type{});)); + } +#endif + + // All types but __half: + template + __host__ __device__ __forceinline__ int SampleIsValid(T sample, T max_level, T min_level) + { + return sample >= min_level && sample < max_level; + } + +#ifdef __CUDA_FP16_TYPES_EXIST__ + __host__ __device__ __forceinline__ int SampleIsValid(__half sample, + __half max_level, + __half min_level) + { + NV_IF_TARGET(NV_PROVIDES_SM_53, + (return sample >= min_level && sample < max_level;), + (return this->SampleIsValid(__half2float(sample), + __half2float(max_level), + __half2float(min_level));)); + } +#endif + + /** + * @brief Bin computation for floating point (and extended floating point) types + */ + template + __host__ __device__ __forceinline__ int + ComputeBin(T sample, T min_level, ScaleT scale, ::cuda::std::true_type /* is_fp */) + { + return static_cast((sample - min_level) * scale.reciprocal); + } + + /** + * @brief Bin computation for custom types and __[u]int128 + */ + template + __host__ __device__ __forceinline__ int + ComputeBin(T sample, T min_level, ScaleT scale, ::cuda::std::false_type /* is_fp */) + { + return static_cast(((sample - min_level) * scale.fraction.bins) / scale.fraction.range); + } + + /** + * @brief Bin computation for integral types of up to 64-bit types + */ + template ::value, int>::type = 0> + __host__ __device__ __forceinline__ int ComputeBin(T sample, T min_level, ScaleT scale) + { + return static_cast((static_cast(sample - min_level) * + static_cast(scale.fraction.bins)) / + static_cast(scale.fraction.range)); + } + + template ::value, int>::type = 0> + __host__ __device__ __forceinline__ int ComputeBin(T sample, T min_level, ScaleT scale) + { + return this->ComputeBin(sample, min_level, scale, ::cuda::std::is_floating_point{}); + } + +#ifdef __CUDA_FP16_TYPES_EXIST__ + __host__ __device__ __forceinline__ int ComputeBin(__half sample, + __half min_level, + ScaleT scale) + { + NV_IF_TARGET(NV_PROVIDES_SM_53, + (return this->ComputeBin(sample, min_level, scale, ::cuda::std::true_type{});), + (return static_cast((__half2float(sample) - __half2float(min_level)) * + __half2float(scale.reciprocal));)); + } +#endif + + __host__ __device__ __forceinline__ bool MayOverflow(CommonT /* num_bins */, + ::cuda::std::false_type /* is_integral */) + { + return false; + } + + /** + * @brief Returns true if the bin computation for a given combination of range `(max_level - + * min_level)` and number of bins may overflow. + */ + __host__ __device__ __forceinline__ bool MayOverflow(CommonT num_bins, + ::cuda::std::true_type /* is_integral */) + { + return static_cast(m_max - m_min) > + (::cuda::std::numeric_limits::max() / + static_cast(num_bins)); + } + + public: + /** + * @brief Initializes the ScaleTransform for the given parameters + * @return cudaErrorInvalidValue if the ScaleTransform for the given values may overflow, + * cudaSuccess otherwise + */ + __host__ __device__ __forceinline__ cudaError_t Init(int num_levels, + LevelT max_level, + LevelT min_level) + { + m_max = static_cast(max_level); + m_min = static_cast(min_level); + + // Check whether accurate bin computation for an integral sample type may overflow + if (MayOverflow(static_cast(num_levels - 1), ::cuda::std::is_integral{})) + { + return cudaErrorInvalidValue; + } + + m_scale = this->ComputeScale(num_levels, m_max, m_min); + return cudaSuccess; + } + + // Method for converting samples to bin-ids + template + __host__ __device__ __forceinline__ void BinSelect(SampleT sample, int &bin, bool valid) + { + const CommonT common_sample = static_cast(sample); + + if (valid && this->SampleIsValid(common_sample, m_max, m_min)) + { + bin = this->ComputeBin(common_sample, m_min, m_scale); + } + } + }; + + // Pass-through bin transform operator + struct PassThruTransform + { + // Method for converting samples to bin-ids + template + __host__ __device__ __forceinline__ void BinSelect(_SampleT sample, int &bin, bool valid) + { + if (valid) + bin = (int)sample; + } + }; + + //--------------------------------------------------------------------- + // Dispatch entrypoints + //--------------------------------------------------------------------- + + /** + * Dispatch routine for HistogramRange, specialized for sample types larger than 8bit + * + * @param d_temp_storage + * Device-accessible allocation of temporary storage. + * When NULL, the required allocation size is written to `temp_storage_bytes` and + * no work is done. + * + * @param temp_storage_bytes + * Reference to size in bytes of `d_temp_storage` allocation + * + * @param d_samples + * The pointer to the multi-channel input sequence of data samples. + * The samples from different channels are assumed to be interleaved + * (e.g., an array of 32-bit pixels where each pixel consists of four RGBA 8-bit samples). + * + * @param d_output_histograms + * The pointers to the histogram counter output arrays, one for each active channel. + * For channeli, the allocation length of `d_histograms[i]` should be + * `num_output_levels[i] - 1`. + * + * @param num_output_levels + * The number of boundaries (levels) for delineating histogram samples in each active channel. + * Implies that the number of bins for channeli is + * `num_output_levels[i] - 1`. + * + * @param d_levels + * The pointers to the arrays of boundaries (levels), one for each active channel. + * Bin ranges are defined by consecutive boundary pairings: lower sample value boundaries are + * inclusive and upper sample value boundaries are exclusive. + * + * @param num_row_pixels + * The number of multi-channel pixels per row in the region of interest + * + * @param num_rows + * The number of rows in the region of interest + * + * @param row_stride_samples + * The number of samples between starts of consecutive rows in the region of interest + * + * @param stream + * CUDA stream to launch kernels within. Default is stream0. + * + * @param is_byte_sample + * type indicating whether or not SampleT is a 8b type + */ + CUB_RUNTIME_FUNCTION + static cudaError_t DispatchRange(void *d_temp_storage, + size_t &temp_storage_bytes, + SampleIteratorT d_samples, + CounterT *d_output_histograms[NUM_ACTIVE_CHANNELS], + int num_output_levels[NUM_ACTIVE_CHANNELS], + LevelT *d_levels[NUM_ACTIVE_CHANNELS], + OffsetT num_row_pixels, + OffsetT num_rows, + OffsetT row_stride_samples, + cudaStream_t stream, + Int2Type /*is_byte_sample*/) + { + using MaxPolicyT = typename SelectedPolicy::MaxPolicy; + cudaError error = cudaSuccess; + + do + { + // Get PTX version + int ptx_version = 0; + if (CubDebug(error = PtxVersion(ptx_version))) + { + break; + } + + // Use the search transform op for converting samples to privatized bins + typedef SearchTransform PrivatizedDecodeOpT; + + // Use the pass-thru transform op for converting privatized bins to output bins + typedef PassThruTransform OutputDecodeOpT; + + PrivatizedDecodeOpT privatized_decode_op[NUM_ACTIVE_CHANNELS]{}; + OutputDecodeOpT output_decode_op[NUM_ACTIVE_CHANNELS]{}; + int max_levels = num_output_levels[0]; + + for (int channel = 0; channel < NUM_ACTIVE_CHANNELS; ++channel) + { + privatized_decode_op[channel].Init(d_levels[channel], num_output_levels[channel]); + if (num_output_levels[channel] > max_levels) + { + max_levels = num_output_levels[channel]; + } + } + int max_num_output_bins = max_levels - 1; + + // Dispatch + if (max_num_output_bins > MAX_PRIVATIZED_SMEM_BINS) + { + // Too many bins to keep in shared memory. + const int PRIVATIZED_SMEM_BINS = 0; + + detail::dispatch_histogram + dispatch(d_temp_storage, + temp_storage_bytes, + d_samples, + d_output_histograms, + num_output_levels, + privatized_decode_op, + num_output_levels, + output_decode_op, + max_num_output_bins, + num_row_pixels, + num_rows, + row_stride_samples, + stream); + + if (CubDebug(error = MaxPolicyT::Invoke(ptx_version, dispatch))) + { + break; + } + } + else + { + // Dispatch shared-privatized approach + const int PRIVATIZED_SMEM_BINS = MAX_PRIVATIZED_SMEM_BINS; + + detail::dispatch_histogram + dispatch(d_temp_storage, + temp_storage_bytes, + d_samples, + d_output_histograms, + num_output_levels, + privatized_decode_op, + num_output_levels, + output_decode_op, + max_num_output_bins, + num_row_pixels, + num_rows, + row_stride_samples, + stream); + + if (CubDebug(error = MaxPolicyT::Invoke(ptx_version, dispatch))) + { + break; + } + } + } while (0); + + return error; + } + + CUB_DETAIL_RUNTIME_DEBUG_SYNC_IS_NOT_SUPPORTED + CUB_RUNTIME_FUNCTION + static cudaError_t DispatchRange(void *d_temp_storage, + size_t &temp_storage_bytes, + SampleIteratorT d_samples, + CounterT *d_output_histograms[NUM_ACTIVE_CHANNELS], + int num_output_levels[NUM_ACTIVE_CHANNELS], + LevelT *d_levels[NUM_ACTIVE_CHANNELS], + OffsetT num_row_pixels, + OffsetT num_rows, + OffsetT row_stride_samples, + cudaStream_t stream, + bool debug_synchronous, + Int2Type is_byte_sample) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + + return DispatchRange(d_temp_storage, + temp_storage_bytes, + d_samples, + d_output_histograms, + num_output_levels, + d_levels, + num_row_pixels, + num_rows, + row_stride_samples, + stream, + is_byte_sample); + } + + /** + * Dispatch routine for HistogramRange, specialized for 8-bit sample types + * (computes 256-bin privatized histograms and then reduces to user-specified levels) + * + * @param d_temp_storage + * Device-accessible allocation of temporary storage. + * When NULL, the required allocation size is written to `temp_storage_bytes` and + * no work is done. + * + * @param temp_storage_bytes + * Reference to size in bytes of `d_temp_storage` allocation + * + * @param d_samples + * The pointer to the multi-channel input sequence of data samples. + * The samples from different channels are assumed to be interleaved + * (e.g., an array of 32-bit pixels where each pixel consists of four RGBA 8-bit samples). + * + * @param d_output_histograms + * The pointers to the histogram counter output arrays, one for each active channel. + * For channeli, the allocation length of + * `d_histograms[i]` should be `num_output_levels[i] - 1`. + * + * @param num_output_levels + * The number of boundaries (levels) for delineating histogram samples in each active channel. + * Implies that the number of bins for channeli is + * `num_output_levels[i] - 1`. + * + * @param d_levels + * The pointers to the arrays of boundaries (levels), one for each active channel. + * Bin ranges are defined by consecutive boundary pairings: lower sample value boundaries are + * inclusive and upper sample value boundaries are exclusive. + * + * @param num_row_pixels + * The number of multi-channel pixels per row in the region of interest + * + * @param num_rows + * The number of rows in the region of interest + * + * @param row_stride_samples + * The number of samples between starts of consecutive rows in the region of interest + * + * @param stream + * CUDA stream to launch kernels within. Default is stream0. + * + * @param is_byte_sample + * Marker type indicating whether or not SampleT is a 8b type + */ + CUB_RUNTIME_FUNCTION + static cudaError_t DispatchRange(void *d_temp_storage, + size_t &temp_storage_bytes, + SampleIteratorT d_samples, + CounterT *d_output_histograms[NUM_ACTIVE_CHANNELS], + int num_output_levels[NUM_ACTIVE_CHANNELS], + LevelT *d_levels[NUM_ACTIVE_CHANNELS], + OffsetT num_row_pixels, + OffsetT num_rows, + OffsetT row_stride_samples, + cudaStream_t stream, + Int2Type /*is_byte_sample*/) + { + using MaxPolicyT = typename SelectedPolicy::MaxPolicy; + cudaError error = cudaSuccess; + + do + { + // Get PTX version + int ptx_version = 0; + if (CubDebug(error = PtxVersion(ptx_version))) + { + break; + } + + // Use the pass-thru transform op for converting samples to privatized bins + typedef PassThruTransform PrivatizedDecodeOpT; + + // Use the search transform op for converting privatized bins to output bins + typedef SearchTransform OutputDecodeOpT; + + int num_privatized_levels[NUM_ACTIVE_CHANNELS]; + PrivatizedDecodeOpT privatized_decode_op[NUM_ACTIVE_CHANNELS]{}; + OutputDecodeOpT output_decode_op[NUM_ACTIVE_CHANNELS]{}; + int max_levels = num_output_levels[0]; // Maximum number of levels in any channel + + for (int channel = 0; channel < NUM_ACTIVE_CHANNELS; ++channel) + { + num_privatized_levels[channel] = 257; + output_decode_op[channel].Init(d_levels[channel], num_output_levels[channel]); + + if (num_output_levels[channel] > max_levels) + { + max_levels = num_output_levels[channel]; + } + } + int max_num_output_bins = max_levels - 1; + + const int PRIVATIZED_SMEM_BINS = 256; + + detail::dispatch_histogram + dispatch(d_temp_storage, + temp_storage_bytes, + d_samples, + d_output_histograms, + num_privatized_levels, + privatized_decode_op, + num_output_levels, + output_decode_op, + max_num_output_bins, + num_row_pixels, + num_rows, + row_stride_samples, + stream); + + if (CubDebug(error = MaxPolicyT::Invoke(ptx_version, dispatch))) + { + break; + } + } while (0); + + return error; + } + + CUB_DETAIL_RUNTIME_DEBUG_SYNC_IS_NOT_SUPPORTED + CUB_RUNTIME_FUNCTION + static cudaError_t DispatchRange(void *d_temp_storage, + size_t &temp_storage_bytes, + SampleIteratorT d_samples, + CounterT *d_output_histograms[NUM_ACTIVE_CHANNELS], + int num_output_levels[NUM_ACTIVE_CHANNELS], + LevelT *d_levels[NUM_ACTIVE_CHANNELS], + OffsetT num_row_pixels, + OffsetT num_rows, + OffsetT row_stride_samples, + cudaStream_t stream, + bool debug_synchronous, + Int2Type is_byte_sample) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + + return DispatchRange(d_temp_storage, + temp_storage_bytes, + d_samples, + d_output_histograms, + num_output_levels, + d_levels, + num_row_pixels, + num_rows, + row_stride_samples, + stream, + is_byte_sample); + } + + /** + * Dispatch routine for HistogramEven, specialized for sample types larger than 8-bit + * + * @param d_temp_storage + * Device-accessible allocation of temporary storage. + * When NULL, the required allocation size is written to + * `temp_storage_bytes` and no work is done. + * + * @param temp_storage_bytes + * Reference to size in bytes of `d_temp_storage` allocation + * + * @param d_samples + * The pointer to the input sequence of sample items. + * The samples from different channels are assumed to be interleaved + * (e.g., an array of 32-bit pixels where each pixel consists of four RGBA 8-bit samples). + * + * @param d_output_histograms + * The pointers to the histogram counter output arrays, one for each active channel. + * For channeli, the allocation length of `d_histograms[i]` should be + * `num_output_levels[i] - 1`. + * + * @param num_output_levels + * The number of bin level boundaries for delineating histogram samples in each active channel. + * Implies that the number of bins for channeli is + * `num_output_levels[i] - 1`. + * + * @param lower_level + * The lower sample value bound (inclusive) for the lowest histogram bin in each active channel. + * + * @param upper_level + * The upper sample value bound (exclusive) for the highest histogram bin in each active + * channel. + * + * @param num_row_pixels + * The number of multi-channel pixels per row in the region of interest + * + * @param num_rows + * The number of rows in the region of interest + * + * @param row_stride_samples + * The number of samples between starts of consecutive rows in the region of interest + * + * @param stream + * CUDA stream to launch kernels within. Default is stream0. + * + * @param is_byte_sample + * Marker type indicating whether or not SampleT is a 8b type + */ + CUB_RUNTIME_FUNCTION __forceinline__ static cudaError_t + DispatchEven(void *d_temp_storage, + size_t &temp_storage_bytes, + SampleIteratorT d_samples, + CounterT *d_output_histograms[NUM_ACTIVE_CHANNELS], + int num_output_levels[NUM_ACTIVE_CHANNELS], + LevelT lower_level[NUM_ACTIVE_CHANNELS], + LevelT upper_level[NUM_ACTIVE_CHANNELS], + OffsetT num_row_pixels, + OffsetT num_rows, + OffsetT row_stride_samples, + cudaStream_t stream, + Int2Type /*is_byte_sample*/) + { + using MaxPolicyT = typename SelectedPolicy::MaxPolicy; + cudaError error = cudaSuccess; + + do + { + // Get PTX version + int ptx_version = 0; + if (CubDebug(error = PtxVersion(ptx_version))) + { + break; + } + + // Use the scale transform op for converting samples to privatized bins + typedef ScaleTransform PrivatizedDecodeOpT; + + // Use the pass-thru transform op for converting privatized bins to output bins + typedef PassThruTransform OutputDecodeOpT; + + PrivatizedDecodeOpT privatized_decode_op[NUM_ACTIVE_CHANNELS]{}; + OutputDecodeOpT output_decode_op[NUM_ACTIVE_CHANNELS]{}; + int max_levels = num_output_levels[0]; + + for (int channel = 0; channel < NUM_ACTIVE_CHANNELS; ++channel) + { + error = privatized_decode_op[channel].Init(num_output_levels[channel], + upper_level[channel], + lower_level[channel]); + if (CubDebug(error != cudaSuccess)) + { + // Make sure to also return a reasonable value for `temp_storage_bytes` in case of + // an overflow of the bin computation, in which case a subsequent algorithm + // invocation will also fail + if (!d_temp_storage) + { + temp_storage_bytes = 1U; + } + return error; + } + + if (num_output_levels[channel] > max_levels) + { + max_levels = num_output_levels[channel]; + } + } + int max_num_output_bins = max_levels - 1; + + if (max_num_output_bins > MAX_PRIVATIZED_SMEM_BINS) + { + // Dispatch shared-privatized approach + const int PRIVATIZED_SMEM_BINS = 0; + + detail::dispatch_histogram + dispatch(d_temp_storage, + temp_storage_bytes, + d_samples, + d_output_histograms, + num_output_levels, + privatized_decode_op, + num_output_levels, + output_decode_op, + max_num_output_bins, + num_row_pixels, + num_rows, + row_stride_samples, + stream); + + if (CubDebug(error = MaxPolicyT::Invoke(ptx_version, dispatch))) + { + break; + } + } + else + { + // Dispatch shared-privatized approach + const int PRIVATIZED_SMEM_BINS = MAX_PRIVATIZED_SMEM_BINS; + + detail::dispatch_histogram + dispatch(d_temp_storage, + temp_storage_bytes, + d_samples, + d_output_histograms, + num_output_levels, + privatized_decode_op, + num_output_levels, + output_decode_op, + max_num_output_bins, + num_row_pixels, + num_rows, + row_stride_samples, + stream); + + if (CubDebug(error = MaxPolicyT::Invoke(ptx_version, dispatch))) + { + break; + } + } + } while (0); + + return error; + } + + CUB_DETAIL_RUNTIME_DEBUG_SYNC_IS_NOT_SUPPORTED + CUB_RUNTIME_FUNCTION __forceinline__ static cudaError_t + DispatchEven(void *d_temp_storage, + size_t &temp_storage_bytes, + SampleIteratorT d_samples, + CounterT *d_output_histograms[NUM_ACTIVE_CHANNELS], + int num_output_levels[NUM_ACTIVE_CHANNELS], + LevelT lower_level[NUM_ACTIVE_CHANNELS], + LevelT upper_level[NUM_ACTIVE_CHANNELS], + OffsetT num_row_pixels, + OffsetT num_rows, + OffsetT row_stride_samples, + cudaStream_t stream, + bool debug_synchronous, + Int2Type is_byte_sample) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + + return DispatchEven(d_temp_storage, + temp_storage_bytes, + d_samples, + d_output_histograms, + num_output_levels, + lower_level, + upper_level, + num_row_pixels, + num_rows, + row_stride_samples, + stream, + is_byte_sample); + } + + /** + * Dispatch routine for HistogramEven, specialized for 8-bit sample types + * (computes 256-bin privatized histograms and then reduces to user-specified levels) + * + * @param d_temp_storage + * Device-accessible allocation of temporary storage. + * When NULL, the required allocation size is written to `temp_storage_bytes` and + * no work is done. + * + * @param temp_storage_bytes + * Reference to size in bytes of `d_temp_storage` allocation + * + * @param d_samples + * The pointer to the input sequence of sample items. The samples from different channels are + * assumed to be interleaved (e.g., an array of 32-bit pixels where each pixel consists of + * four RGBA 8-bit samples). + * + * @param d_output_histograms + * The pointers to the histogram counter output arrays, one for each active channel. + * For channeli, the allocation length of `d_histograms[i]` should be + * `num_output_levels[i] - 1`. + * + * @param num_output_levels + * The number of bin level boundaries for delineating histogram samples in each active channel. + * Implies that the number of bins for channeli is + * `num_output_levels[i] - 1`. + * + * @param lower_level + * The lower sample value bound (inclusive) for the lowest histogram bin in each active channel. + * + * @param upper_level + * The upper sample value bound (exclusive) for the highest histogram bin in each active + * channel. + * + * @param num_row_pixels + * The number of multi-channel pixels per row in the region of interest + * + * @param num_rows + * The number of rows in the region of interest + * + * @param row_stride_samples + * The number of samples between starts of consecutive rows in the region of interest + * + * @param stream + * CUDA stream to launch kernels within. Default is stream0. + * + * @param is_byte_sample + * type indicating whether or not SampleT is a 8b type + */ + CUB_RUNTIME_FUNCTION __forceinline__ static cudaError_t + DispatchEven(void *d_temp_storage, + size_t &temp_storage_bytes, + SampleIteratorT d_samples, + CounterT *d_output_histograms[NUM_ACTIVE_CHANNELS], + int num_output_levels[NUM_ACTIVE_CHANNELS], + LevelT lower_level[NUM_ACTIVE_CHANNELS], + LevelT upper_level[NUM_ACTIVE_CHANNELS], + OffsetT num_row_pixels, + OffsetT num_rows, + OffsetT row_stride_samples, + cudaStream_t stream, + Int2Type /*is_byte_sample*/) + { + using MaxPolicyT = typename SelectedPolicy::MaxPolicy; + cudaError error = cudaSuccess; + + do + { + // Get PTX version + int ptx_version = 0; + if (CubDebug(error = PtxVersion(ptx_version))) + { + break; + } + + // Use the pass-thru transform op for converting samples to privatized bins + typedef PassThruTransform PrivatizedDecodeOpT; + + // Use the scale transform op for converting privatized bins to output bins + typedef ScaleTransform OutputDecodeOpT; + + int num_privatized_levels[NUM_ACTIVE_CHANNELS]; + PrivatizedDecodeOpT privatized_decode_op[NUM_ACTIVE_CHANNELS]{}; + OutputDecodeOpT output_decode_op[NUM_ACTIVE_CHANNELS]{}; + int max_levels = num_output_levels[0]; + + for (int channel = 0; channel < NUM_ACTIVE_CHANNELS; ++channel) + { + num_privatized_levels[channel] = 257; + + output_decode_op[channel].Init(num_output_levels[channel], + upper_level[channel], + lower_level[channel]); + + if (num_output_levels[channel] > max_levels) + { + max_levels = num_output_levels[channel]; + } + } + int max_num_output_bins = max_levels - 1; + + const int PRIVATIZED_SMEM_BINS = 256; + + detail::dispatch_histogram + dispatch(d_temp_storage, + temp_storage_bytes, + d_samples, + d_output_histograms, + num_privatized_levels, + privatized_decode_op, + num_output_levels, + output_decode_op, + max_num_output_bins, + num_row_pixels, + num_rows, + row_stride_samples, + stream); + + if (CubDebug(error = MaxPolicyT::Invoke(ptx_version, dispatch))) + { + break; + } + } while (0); + + return error; + } + + CUB_RUNTIME_FUNCTION __forceinline__ static cudaError_t + DispatchEven(void *d_temp_storage, + size_t &temp_storage_bytes, + SampleIteratorT d_samples, + CounterT *d_output_histograms[NUM_ACTIVE_CHANNELS], + int num_output_levels[NUM_ACTIVE_CHANNELS], + LevelT lower_level[NUM_ACTIVE_CHANNELS], + LevelT upper_level[NUM_ACTIVE_CHANNELS], + OffsetT num_row_pixels, + OffsetT num_rows, + OffsetT row_stride_samples, + cudaStream_t stream, + bool debug_synchronous, + Int2Type is_byte_sample) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + + return DispatchEven(d_temp_storage, + temp_storage_bytes, + d_samples, + d_output_histograms, + num_output_levels, + lower_level, + upper_level, + num_row_pixels, + num_rows, + row_stride_samples, + stream, + is_byte_sample); + } +}; + +CUB_NAMESPACE_END diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/device/dispatch/dispatch_merge_sort.cuh b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/device/dispatch/dispatch_merge_sort.cuh new file mode 100644 index 0000000000000000000000000000000000000000..5bbd3dfdd781948573eff21c7e09e5e1838b50b6 --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/device/dispatch/dispatch_merge_sort.cuh @@ -0,0 +1,898 @@ +/****************************************************************************** + * Copyright (c) 2011-2021, NVIDIA CORPORATION. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the NVIDIA CORPORATION nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ******************************************************************************/ + +#pragma once + +#include +#include +#include +#include +#include + +#include +#include + +CUB_NAMESPACE_BEGIN + + +template +void __global__ __launch_bounds__(ChainedPolicyT::ActivePolicy::MergeSortPolicy::BLOCK_THREADS) +DeviceMergeSortBlockSortKernel(bool ping, + KeyInputIteratorT keys_in, + ValueInputIteratorT items_in, + KeyIteratorT keys_out, + ValueIteratorT items_out, + OffsetT keys_count, + KeyT *tmp_keys_out, + ValueT *tmp_items_out, + CompareOpT compare_op, + char *vshmem) +{ + extern __shared__ char shmem[]; + using ActivePolicyT = typename ChainedPolicyT::ActivePolicy::MergeSortPolicy; + + using AgentBlockSortT = AgentBlockSort; + + const OffsetT vshmem_offset = blockIdx.x * + AgentBlockSortT::SHARED_MEMORY_SIZE; + + typename AgentBlockSortT::TempStorage &storage = + *reinterpret_cast( + UseVShmem ? vshmem + vshmem_offset : shmem); + + AgentBlockSortT agent(ping, + storage, + THRUST_NS_QUALIFIER::cuda_cub::core::make_load_iterator(ActivePolicyT(), keys_in), + THRUST_NS_QUALIFIER::cuda_cub::core::make_load_iterator(ActivePolicyT(), items_in), + keys_count, + keys_out, + items_out, + tmp_keys_out, + tmp_items_out, + compare_op); + + agent.Process(); +} + +template +__global__ void DeviceMergeSortPartitionKernel(bool ping, + KeyIteratorT keys_ping, + KeyT *keys_pong, + OffsetT keys_count, + OffsetT num_partitions, + OffsetT *merge_partitions, + CompareOpT compare_op, + OffsetT target_merged_tiles_number, + int items_per_tile) +{ + OffsetT partition_idx = blockDim.x * blockIdx.x + threadIdx.x; + + if (partition_idx < num_partitions) + { + AgentPartition agent( + ping, + keys_ping, + keys_pong, + keys_count, + partition_idx, + merge_partitions, + compare_op, + target_merged_tiles_number, + items_per_tile); + + agent.Process(); + } +} + +template +void __global__ __launch_bounds__(ChainedPolicyT::ActivePolicy::MergeSortPolicy::BLOCK_THREADS) +DeviceMergeSortMergeKernel(bool ping, + KeyIteratorT keys_ping, + ValueIteratorT items_ping, + OffsetT keys_count, + KeyT *keys_pong, + ValueT *items_pong, + CompareOpT compare_op, + OffsetT *merge_partitions, + OffsetT target_merged_tiles_number, + char *vshmem) +{ + extern __shared__ char shmem[]; + + using ActivePolicyT = typename ChainedPolicyT::ActivePolicy::MergeSortPolicy; + using AgentMergeT = AgentMerge; + + const OffsetT vshmem_offset = blockIdx.x * AgentMergeT::SHARED_MEMORY_SIZE; + + typename AgentMergeT::TempStorage &storage = + *reinterpret_cast( + UseVShmem ? vshmem + vshmem_offset : shmem); + + AgentMergeT agent( + ping, + storage, + THRUST_NS_QUALIFIER::cuda_cub::core::make_load_iterator(ActivePolicyT(), keys_ping), + THRUST_NS_QUALIFIER::cuda_cub::core::make_load_iterator(ActivePolicyT(), items_ping), + THRUST_NS_QUALIFIER::cuda_cub::core::make_load_iterator(ActivePolicyT(), keys_pong), + THRUST_NS_QUALIFIER::cuda_cub::core::make_load_iterator(ActivePolicyT(), items_pong), + keys_count, + keys_pong, + items_pong, + keys_ping, + items_ping, + compare_op, + merge_partitions, + target_merged_tiles_number); + + agent.Process(); +} + +/******************************************************************************* + * Policy + ******************************************************************************/ + +template +struct DeviceMergeSortPolicy +{ + using KeyT = cub::detail::value_t; + + //---------------------------------------------------------------------------- + // Architecture-specific tuning policies + //---------------------------------------------------------------------------- + + struct Policy350 : ChainedPolicy<350, Policy350, Policy350> + { + using MergeSortPolicy = + AgentMergeSortPolicy<256, + Nominal4BItemsToItems(11), + cub::BLOCK_LOAD_WARP_TRANSPOSE, + cub::LOAD_LDG, + cub::BLOCK_STORE_WARP_TRANSPOSE>; + }; + +// NVBug 3384810 +#if defined(_NVHPC_CUDA) + using Policy520 = Policy350; +#else + struct Policy520 : ChainedPolicy<520, Policy520, Policy350> + { + using MergeSortPolicy = + AgentMergeSortPolicy<512, + Nominal4BItemsToItems(15), + cub::BLOCK_LOAD_WARP_TRANSPOSE, + cub::LOAD_LDG, + cub::BLOCK_STORE_WARP_TRANSPOSE>; + }; +#endif + + struct Policy600 : ChainedPolicy<600, Policy600, Policy520> + { + using MergeSortPolicy = + AgentMergeSortPolicy<256, + Nominal4BItemsToItems(17), + cub::BLOCK_LOAD_WARP_TRANSPOSE, + cub::LOAD_DEFAULT, + cub::BLOCK_STORE_WARP_TRANSPOSE>; + }; + + + /// MaxPolicy + using MaxPolicy = Policy600; +}; + +template +struct BlockSortLauncher +{ + int num_tiles; + std::size_t block_sort_shmem_size; + bool ping; + + KeyInputIteratorT d_input_keys; + ValueInputIteratorT d_input_items; + KeyIteratorT d_output_keys; + ValueIteratorT d_output_items; + OffsetT num_items; + CompareOpT compare_op; + cudaStream_t stream; + + KeyT *keys_buffer; + ValueT *items_buffer; + char* vshmem_ptr; + + CUB_RUNTIME_FUNCTION __forceinline__ + BlockSortLauncher(int num_tiles, + std::size_t block_sort_shmem_size, + bool ping, + KeyInputIteratorT d_input_keys, + ValueInputIteratorT d_input_items, + KeyIteratorT d_output_keys, + ValueIteratorT d_output_items, + OffsetT num_items, + CompareOpT compare_op, + cudaStream_t stream, + KeyT *keys_buffer, + ValueT *items_buffer, + char *vshmem_ptr) + : num_tiles(num_tiles) + , block_sort_shmem_size(block_sort_shmem_size) + , ping(ping) + , d_input_keys(d_input_keys) + , d_input_items(d_input_items) + , d_output_keys(d_output_keys) + , d_output_items(d_output_items) + , num_items(num_items) + , compare_op(compare_op) + , stream(stream) + , keys_buffer(keys_buffer) + , items_buffer(items_buffer) + , vshmem_ptr(vshmem_ptr) + {} + + CUB_RUNTIME_FUNCTION __forceinline__ + void launch() const + { + if (vshmem_ptr) + { + launch_impl(); + } + else + { + launch_impl(); + } + } + + template + CUB_RUNTIME_FUNCTION __forceinline__ void launch_impl() const + { + constexpr bool use_vshmem = (AgentFitsIntoDefaultShmemSize == false) && + UseVShmem; + + THRUST_NS_QUALIFIER::cuda_cub::launcher::triple_chevron( + num_tiles, + ActivePolicyT::MergeSortPolicy::BLOCK_THREADS, + use_vshmem ? 0 : block_sort_shmem_size, + stream) + .doit(DeviceMergeSortBlockSortKernel, + ping, + d_input_keys, + d_input_items, + d_output_keys, + d_output_items, + num_items, + keys_buffer, + items_buffer, + compare_op, + vshmem_ptr); + } +}; + +template +struct MergeLauncher +{ + int num_tiles; + std::size_t merge_shmem_size; + + KeyIteratorT d_keys; + ValueIteratorT d_items; + OffsetT num_items; + CompareOpT compare_op; + OffsetT *merge_partitions; + cudaStream_t stream; + + KeyT *keys_buffer; + ValueT *items_buffer; + char *vshmem_ptr; + + CUB_RUNTIME_FUNCTION __forceinline__ MergeLauncher(int num_tiles, + std::size_t merge_shmem_size, + KeyIteratorT d_keys, + ValueIteratorT d_items, + OffsetT num_items, + CompareOpT compare_op, + OffsetT *merge_partitions, + cudaStream_t stream, + KeyT *keys_buffer, + ValueT *items_buffer, + char *vshmem_ptr) + : num_tiles(num_tiles) + , merge_shmem_size(merge_shmem_size) + , d_keys(d_keys) + , d_items(d_items) + , num_items(num_items) + , compare_op(compare_op) + , merge_partitions(merge_partitions) + , stream(stream) + , keys_buffer(keys_buffer) + , items_buffer(items_buffer) + , vshmem_ptr(vshmem_ptr) + {} + + CUB_RUNTIME_FUNCTION __forceinline__ void + launch(bool ping, OffsetT target_merged_tiles_number) const + { + if (vshmem_ptr) + { + launch_impl(ping, target_merged_tiles_number); + } + else + { + launch_impl(ping, target_merged_tiles_number); + } + } + + template + CUB_RUNTIME_FUNCTION __forceinline__ void + launch_impl(bool ping, OffsetT target_merged_tiles_number) const + { + constexpr bool use_vshmem = (AgentFitsIntoDefaultShmemSize == false) && + UseVShmem; + + THRUST_NS_QUALIFIER::cuda_cub::launcher::triple_chevron( + num_tiles, + ActivePolicyT::MergeSortPolicy::BLOCK_THREADS, + use_vshmem ? 0 : merge_shmem_size, + stream) + .doit(DeviceMergeSortMergeKernel, + ping, + d_keys, + d_items, + num_items, + keys_buffer, + items_buffer, + compare_op, + merge_partitions, + target_merged_tiles_number, + vshmem_ptr); + } +}; + +template > +struct DispatchMergeSort : SelectedPolicy +{ + using KeyT = cub::detail::value_t; + using ValueT = cub::detail::value_t; + + /// Whether or not there are values to be trucked along with keys + static constexpr bool KEYS_ONLY = std::is_same::value; + + // Problem state + + /// Device-accessible allocation of temporary storage. When NULL, the required + /// allocation size is written to \p temp_storage_bytes and no work is done. + void *d_temp_storage; + + /// Reference to size in bytes of \p d_temp_storage allocation + std::size_t &temp_storage_bytes; + + /// Pointer to the input sequence of unsorted input keys + KeyInputIteratorT d_input_keys; + + /// Pointer to the input sequence of unsorted input values + ValueInputIteratorT d_input_items; + + /// Pointer to the output sequence of sorted input keys + KeyIteratorT d_output_keys; + + /// Pointer to the output sequence of sorted input values + ValueIteratorT d_output_items; + + /// Number of items to sort + OffsetT num_items; + + /// Comparison function object which returns true if the first argument is + /// ordered before the second + CompareOpT compare_op; + + /// CUDA stream to launch kernels within. Default is stream0. + cudaStream_t stream; + + int ptx_version; + + // Constructor + CUB_RUNTIME_FUNCTION __forceinline__ + DispatchMergeSort(void *d_temp_storage, + std::size_t &temp_storage_bytes, + KeyInputIteratorT d_input_keys, + ValueInputIteratorT d_input_items, + KeyIteratorT d_output_keys, + ValueIteratorT d_output_items, + OffsetT num_items, + CompareOpT compare_op, + cudaStream_t stream, + int ptx_version) + : d_temp_storage(d_temp_storage) + , temp_storage_bytes(temp_storage_bytes) + , d_input_keys(d_input_keys) + , d_input_items(d_input_items) + , d_output_keys(d_output_keys) + , d_output_items(d_output_items) + , num_items(num_items) + , compare_op(compare_op) + , stream(stream) + , ptx_version(ptx_version) + {} + + CUB_DETAIL_RUNTIME_DEBUG_SYNC_IS_NOT_SUPPORTED + CUB_RUNTIME_FUNCTION __forceinline__ + DispatchMergeSort(void *d_temp_storage, + std::size_t &temp_storage_bytes, + KeyInputIteratorT d_input_keys, + ValueInputIteratorT d_input_items, + KeyIteratorT d_output_keys, + ValueIteratorT d_output_items, + OffsetT num_items, + CompareOpT compare_op, + cudaStream_t stream, + bool debug_synchronous, + int ptx_version) + : d_temp_storage(d_temp_storage) + , temp_storage_bytes(temp_storage_bytes) + , d_input_keys(d_input_keys) + , d_input_items(d_input_items) + , d_output_keys(d_output_keys) + , d_output_items(d_output_items) + , num_items(num_items) + , compare_op(compare_op) + , stream(stream) + , ptx_version(ptx_version) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + } + + // Invocation + template + CUB_RUNTIME_FUNCTION __forceinline__ cudaError_t Invoke() + { + using MergePolicyT = typename ActivePolicyT::MergeSortPolicy; + using MaxPolicyT = typename DispatchMergeSort::MaxPolicy; + + using BlockSortAgentT = AgentBlockSort; + + using MergeAgentT = AgentMerge; + + cudaError error = cudaSuccess; + + if (num_items == 0) + return error; + + do + { + // Get device ordinal + int device_ordinal = 0; + if (CubDebug(error = cudaGetDevice(&device_ordinal))) + { + break; + } + + // Get shared memory size + const auto tile_size = MergePolicyT::ITEMS_PER_TILE; + const auto num_tiles = cub::DivideAndRoundUp(num_items, tile_size); + + /** + * Merge sort supports large types, which can lead to excessive shared + * memory size requirements. In these cases, merge sort allocates virtual + * shared memory that resides in global memory: + * ``` + * extern __shared__ char shmem[]; + * typename AgentT::TempStorage &storage = + * *reinterpret_cast( + * UseVShmem ? vshmem + vshmem_offset : shmem); + * ``` + * Having `UseVShmem` as a runtime variable leads to the generation of + * generic loads and stores, which causes a slowdown. Therefore, + * `UseVShmem` has to be known at compilation time. + * In the generic case, available shared memory size is queried at runtime + * to check if kernels requirements are satisfied. Since the query result + * is not known at compile-time, merge sort kernels are specialized for + * both cases. + * To address increased compilation time, the dispatch layer checks + * whether kernels requirements fit into default shared memory + * size (48KB). In this case, there's no need for virtual shared + * memory specialization. + */ + constexpr std::size_t default_shared_memory_size = 48 * 1024; + constexpr auto block_sort_shmem_size = + static_cast(BlockSortAgentT::SHARED_MEMORY_SIZE); + constexpr bool block_sort_fits_into_default_shmem = + block_sort_shmem_size < default_shared_memory_size; + + constexpr auto merge_shmem_size = + static_cast(MergeAgentT::SHARED_MEMORY_SIZE); + constexpr bool merge_fits_into_default_shmem = merge_shmem_size < + default_shared_memory_size; + constexpr bool runtime_shmem_size_check_is_required = + !(merge_fits_into_default_shmem && block_sort_fits_into_default_shmem); + + const auto merge_partitions_size = + static_cast(1 + num_tiles) * sizeof(OffsetT); + + const auto temporary_keys_storage_size = + static_cast(num_items * sizeof(KeyT)); + + const auto temporary_values_storage_size = + static_cast(num_items * sizeof(ValueT)) * !KEYS_ONLY; + + std::size_t virtual_shared_memory_size = 0; + bool block_sort_requires_vshmem = false; + bool merge_requires_vshmem = false; + + if (runtime_shmem_size_check_is_required) + { + int max_shmem = 0; + if (CubDebug( + error = cudaDeviceGetAttribute(&max_shmem, + cudaDevAttrMaxSharedMemoryPerBlock, + device_ordinal))) + { + break; + } + + block_sort_requires_vshmem = block_sort_shmem_size > + static_cast(max_shmem); + merge_requires_vshmem = merge_shmem_size > + static_cast(max_shmem); + + virtual_shared_memory_size = + detail::VshmemSize(static_cast(max_shmem), + (cub::max)(block_sort_shmem_size, merge_shmem_size), + static_cast(num_tiles)); + } + + + void *allocations[4] = {nullptr, nullptr, nullptr, nullptr}; + std::size_t allocation_sizes[4] = {merge_partitions_size, + temporary_keys_storage_size, + temporary_values_storage_size, + virtual_shared_memory_size}; + + if (CubDebug(error = AliasTemporaries(d_temp_storage, + temp_storage_bytes, + allocations, + allocation_sizes))) + { + break; + } + + if (d_temp_storage == nullptr) + { + // Return if the caller is simply requesting the size of the storage + // allocation + break; + } + + const int num_passes = + static_cast(THRUST_NS_QUALIFIER::detail::log2_ri(num_tiles)); + + /* + * The algorithm consists of stages. At each stage, there are input and + * output arrays. There are two pairs of arrays allocated (keys and items). + * One pair is from function arguments and another from temporary storage. + * Ping is a helper variable that controls which of these two pairs of + * arrays is an input and which is an output for a current stage. If the + * ping is true - the current stage stores its result in the temporary + * storage. The temporary storage acts as input data otherwise. + * + * Block sort is executed before the main loop. It stores its result in + * the pair of arrays that will be an input of the next stage. The initial + * value of the ping variable is selected so that the result of the final + * stage is stored in the input arrays. + */ + bool ping = num_passes % 2 == 0; + + auto merge_partitions = reinterpret_cast(allocations[0]); + auto keys_buffer = reinterpret_cast(allocations[1]); + auto items_buffer = reinterpret_cast(allocations[2]); + + char *vshmem_ptr = virtual_shared_memory_size > 0 + ? reinterpret_cast(allocations[3]) + : nullptr; + + // Invoke DeviceReduceKernel + BlockSortLauncher + block_sort_launcher(static_cast(num_tiles), + block_sort_shmem_size, + ping, + d_input_keys, + d_input_items, + d_output_keys, + d_output_items, + num_items, + compare_op, + stream, + keys_buffer, + items_buffer, + block_sort_requires_vshmem ? vshmem_ptr : nullptr); + + block_sort_launcher.launch(); + + error = detail::DebugSyncStream(stream); + if (CubDebug(error)) + { + break; + } + + // Check for failure to launch + if (CubDebug(error = cudaPeekAtLastError())) + { + break; + } + + const OffsetT num_partitions = num_tiles + 1; + const int threads_per_partition_block = 256; + + const int partition_grid_size = static_cast( + cub::DivideAndRoundUp(num_partitions, threads_per_partition_block)); + + MergeLauncher + merge_launcher(static_cast(num_tiles), + merge_shmem_size, + d_output_keys, + d_output_items, + num_items, + compare_op, + merge_partitions, + stream, + keys_buffer, + items_buffer, + merge_requires_vshmem ? vshmem_ptr : nullptr); + + for (int pass = 0; pass < num_passes; ++pass, ping = !ping) + { + OffsetT target_merged_tiles_number = OffsetT(2) << pass; + + // Partition + THRUST_NS_QUALIFIER::cuda_cub::launcher::triple_chevron( + partition_grid_size, + threads_per_partition_block, + 0, + stream) + .doit(DeviceMergeSortPartitionKernel, + ping, + d_output_keys, + keys_buffer, + num_items, + num_partitions, + merge_partitions, + compare_op, + target_merged_tiles_number, + tile_size); + + error = detail::DebugSyncStream(stream); + if (CubDebug(error)) + { + break; + } + + // Check for failure to launch + if (CubDebug(error = cudaPeekAtLastError())) + { + break; + } + + // Merge + merge_launcher.launch(ping, target_merged_tiles_number); + + error = detail::DebugSyncStream(stream); + if (CubDebug(error)) + { + break; + } + + // Check for failure to launch + if (CubDebug(error = cudaPeekAtLastError())) + { + break; + } + } + } + while (0); + + return error; + } + + CUB_RUNTIME_FUNCTION __forceinline__ static cudaError_t + Dispatch(void *d_temp_storage, + std::size_t &temp_storage_bytes, + KeyInputIteratorT d_input_keys, + ValueInputIteratorT d_input_items, + KeyIteratorT d_output_keys, + ValueIteratorT d_output_items, + OffsetT num_items, + CompareOpT compare_op, + cudaStream_t stream) + { + using MaxPolicyT = typename DispatchMergeSort::MaxPolicy; + + cudaError error = cudaSuccess; + do + { + // Get PTX version + int ptx_version = 0; + if (CubDebug(error = PtxVersion(ptx_version))) + { + break; + } + + // Create dispatch functor + DispatchMergeSort dispatch(d_temp_storage, + temp_storage_bytes, + d_input_keys, + d_input_items, + d_output_keys, + d_output_items, + num_items, + compare_op, + stream, + ptx_version); + + // Dispatch to chained policy + if (CubDebug(error = MaxPolicyT::Invoke(ptx_version, dispatch))) + { + break; + } + } while (0); + + return error; + } + + CUB_DETAIL_RUNTIME_DEBUG_SYNC_IS_NOT_SUPPORTED + CUB_RUNTIME_FUNCTION __forceinline__ static cudaError_t + Dispatch(void *d_temp_storage, + std::size_t &temp_storage_bytes, + KeyInputIteratorT d_input_keys, + ValueInputIteratorT d_input_items, + KeyIteratorT d_output_keys, + ValueIteratorT d_output_items, + OffsetT num_items, + CompareOpT compare_op, + cudaStream_t stream, + bool debug_synchronous) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + + return Dispatch(d_temp_storage, + temp_storage_bytes, + d_input_keys, + d_input_items, + d_output_keys, + d_output_items, + num_items, + compare_op, + stream); + } +}; + + +CUB_NAMESPACE_END diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/device/dispatch/dispatch_reduce_by_key.cuh b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/device/dispatch/dispatch_reduce_by_key.cuh new file mode 100644 index 0000000000000000000000000000000000000000..d56f4cb4d02160e60da0b18f63fb1648506f7d4e --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/device/dispatch/dispatch_reduce_by_key.cuh @@ -0,0 +1,578 @@ +/****************************************************************************** + * Copyright (c) 2011, Duane Merrill. All rights reserved. + * Copyright (c) 2011-2022, NVIDIA CORPORATION. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the NVIDIA CORPORATION nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ******************************************************************************/ + +/** + * @file cub::DeviceReduceByKey provides device-wide, parallel operations for + * reducing segments of values residing within device-accessible memory. + */ + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include + +#include + +CUB_NAMESPACE_BEGIN + +/****************************************************************************** + * Kernel entry points + *****************************************************************************/ + +/** + * @brief Multi-block reduce-by-key sweep kernel entry point + * + * @tparam AgentReduceByKeyPolicyT + * Parameterized AgentReduceByKeyPolicyT tuning policy type + * + * @tparam KeysInputIteratorT + * Random-access input iterator type for keys + * + * @tparam UniqueOutputIteratorT + * Random-access output iterator type for keys + * + * @tparam ValuesInputIteratorT + * Random-access input iterator type for values + * + * @tparam AggregatesOutputIteratorT + * Random-access output iterator type for values + * + * @tparam NumRunsOutputIteratorT + * Output iterator type for recording number of segments encountered + * + * @tparam ScanTileStateT + * Tile status interface type + * + * @tparam EqualityOpT + * KeyT equality operator type + * + * @tparam ReductionOpT + * ValueT reduction operator type + * + * @tparam OffsetT + * Signed integer type for global offsets + * + * @param d_keys_in + * Pointer to the input sequence of keys + * + * @param d_unique_out + * Pointer to the output sequence of unique keys (one key per run) + * + * @param d_values_in + * Pointer to the input sequence of corresponding values + * + * @param d_aggregates_out + * Pointer to the output sequence of value aggregates (one aggregate per run) + * + * @param d_num_runs_out + * Pointer to total number of runs encountered + * (i.e., the length of d_unique_out) + * + * @param tile_state + * Tile status interface + * + * @param start_tile + * The starting tile for the current grid + * + * @param equality_op + * KeyT equality operator + * + * @param reduction_op + * ValueT reduction operator + * + * @param num_items + * Total number of items to select from + */ +template +__launch_bounds__(int(ChainedPolicyT::ActivePolicy::ReduceByKeyPolicyT::BLOCK_THREADS)) __global__ + void DeviceReduceByKeyKernel(KeysInputIteratorT d_keys_in, + UniqueOutputIteratorT d_unique_out, + ValuesInputIteratorT d_values_in, + AggregatesOutputIteratorT d_aggregates_out, + NumRunsOutputIteratorT d_num_runs_out, + ScanTileStateT tile_state, + int start_tile, + EqualityOpT equality_op, + ReductionOpT reduction_op, + OffsetT num_items) +{ + using AgentReduceByKeyPolicyT = typename ChainedPolicyT::ActivePolicy::ReduceByKeyPolicyT; + + // Thread block type for reducing tiles of value segments + using AgentReduceByKeyT = AgentReduceByKey; + + // Shared memory for AgentReduceByKey + __shared__ typename AgentReduceByKeyT::TempStorage temp_storage; + + // Process tiles + AgentReduceByKeyT(temp_storage, + d_keys_in, + d_unique_out, + d_values_in, + d_aggregates_out, + d_num_runs_out, + equality_op, + reduction_op) + .ConsumeRange(num_items, tile_state, start_tile); +} + +/****************************************************************************** + * Dispatch + ******************************************************************************/ + +/** + * @brief Utility class for dispatching the appropriately-tuned kernels for + * DeviceReduceByKey + * + * @tparam KeysInputIteratorT + * Random-access input iterator type for keys + * + * @tparam UniqueOutputIteratorT + * Random-access output iterator type for keys + * + * @tparam ValuesInputIteratorT + * Random-access input iterator type for values + * + * @tparam AggregatesOutputIteratorT + * Random-access output iterator type for values + * + * @tparam NumRunsOutputIteratorT + * Output iterator type for recording number of segments encountered + * + * @tparam EqualityOpT + * KeyT equality operator type + * + * @tparam ReductionOpT + * ValueT reduction operator type + * + * @tparam OffsetT + * Signed integer type for global offsets + * + * @tparam SelectedPolicy + * Implementation detail, do not specify directly, requirements on the + * content of this type are subject to breaking change. + */ +template , + cub::detail::value_t>, + typename SelectedPolicy = // + detail::device_reduce_by_key_policy_hub< // + ReductionOpT, // + AccumT, // + cub::detail::non_void_value_t< // + UniqueOutputIteratorT, // + cub::detail::value_t>>> +struct DispatchReduceByKey +{ + //------------------------------------------------------------------------- + // Types and constants + //------------------------------------------------------------------------- + + // The input values type + using ValueInputT = cub::detail::value_t; + + static constexpr int INIT_KERNEL_THREADS = 128; + + // Tile status descriptor interface type + using ScanTileStateT = ReduceByKeyScanTileState; + + void *d_temp_storage; + size_t &temp_storage_bytes; + KeysInputIteratorT d_keys_in; + UniqueOutputIteratorT d_unique_out; + ValuesInputIteratorT d_values_in; + AggregatesOutputIteratorT d_aggregates_out; + NumRunsOutputIteratorT d_num_runs_out; + EqualityOpT equality_op; + ReductionOpT reduction_op; + OffsetT num_items; + cudaStream_t stream; + + CUB_RUNTIME_FUNCTION __forceinline__ + DispatchReduceByKey(void *d_temp_storage, + size_t &temp_storage_bytes, + KeysInputIteratorT d_keys_in, + UniqueOutputIteratorT d_unique_out, + ValuesInputIteratorT d_values_in, + AggregatesOutputIteratorT d_aggregates_out, + NumRunsOutputIteratorT d_num_runs_out, + EqualityOpT equality_op, + ReductionOpT reduction_op, + OffsetT num_items, + cudaStream_t stream) + : d_temp_storage(d_temp_storage) + , temp_storage_bytes(temp_storage_bytes) + , d_keys_in(d_keys_in) + , d_unique_out(d_unique_out) + , d_values_in(d_values_in) + , d_aggregates_out(d_aggregates_out) + , d_num_runs_out(d_num_runs_out) + , equality_op(equality_op) + , reduction_op(reduction_op) + , num_items(num_items) + , stream(stream) + {} + + //--------------------------------------------------------------------- + // Dispatch entrypoints + //--------------------------------------------------------------------- + + template + CUB_RUNTIME_FUNCTION __forceinline__ cudaError_t Invoke(ScanInitKernelT init_kernel, + ReduceByKeyKernelT reduce_by_key_kernel) + { + using AgentReduceByKeyPolicyT = typename ActivePolicyT::ReduceByKeyPolicyT; + const int block_threads = AgentReduceByKeyPolicyT::BLOCK_THREADS; + const int items_per_thread = AgentReduceByKeyPolicyT::ITEMS_PER_THREAD; + + cudaError error = cudaSuccess; + do + { + // Get device ordinal + int device_ordinal; + if (CubDebug(error = cudaGetDevice(&device_ordinal))) + { + break; + } + + // Number of input tiles + int tile_size = block_threads * items_per_thread; + int num_tiles = static_cast(cub::DivideAndRoundUp(num_items, tile_size)); + + // Specify temporary storage allocation requirements + size_t allocation_sizes[1]; + if (CubDebug(error = ScanTileStateT::AllocationSize(num_tiles, allocation_sizes[0]))) + { + break; // bytes needed for tile status descriptors + } + + // Compute allocation pointers into the single storage blob (or compute + // the necessary size of the blob) + void *allocations[1] = {}; + if (CubDebug( + error = + AliasTemporaries(d_temp_storage, temp_storage_bytes, allocations, allocation_sizes))) + { + break; + } + + if (d_temp_storage == nullptr) + { + // Return if the caller is simply requesting the size of the storage + // allocation + break; + } + + // Construct the tile status interface + ScanTileStateT tile_state; + if (CubDebug(error = tile_state.Init(num_tiles, allocations[0], allocation_sizes[0]))) + { + break; + } + + // Log init_kernel configuration + int init_grid_size = CUB_MAX(1, cub::DivideAndRoundUp(num_tiles, INIT_KERNEL_THREADS)); + +#ifdef CUB_DETAIL_DEBUG_ENABLE_LOG + _CubLog("Invoking init_kernel<<<%d, %d, 0, %lld>>>()\n", + init_grid_size, + INIT_KERNEL_THREADS, + (long long)stream); +#endif + + // Invoke init_kernel to initialize tile descriptors + THRUST_NS_QUALIFIER::cuda_cub::launcher::triple_chevron(init_grid_size, + INIT_KERNEL_THREADS, + 0, + stream) + .doit(init_kernel, tile_state, num_tiles, d_num_runs_out); + + // Check for failure to launch + if (CubDebug(error = cudaPeekAtLastError())) + { + break; + } + + // Sync the stream if specified to flush runtime errors + error = detail::DebugSyncStream(stream); + if (CubDebug(error)) + { + break; + } + + // Return if empty problem + if (num_items == 0) + { + break; + } + + // Get SM occupancy for reduce_by_key_kernel + int reduce_by_key_sm_occupancy; + if (CubDebug(error = MaxSmOccupancy(reduce_by_key_sm_occupancy, + reduce_by_key_kernel, + block_threads))) + { + break; + } + + // Get max x-dimension of grid + int max_dim_x; + if (CubDebug( + error = cudaDeviceGetAttribute(&max_dim_x, cudaDevAttrMaxGridDimX, device_ordinal))) + { + break; + } + + // Run grids in epochs (in case number of tiles exceeds max x-dimension + int scan_grid_size = CUB_MIN(num_tiles, max_dim_x); + for (int start_tile = 0; start_tile < num_tiles; start_tile += scan_grid_size) + { +// Log reduce_by_key_kernel configuration +#ifdef CUB_DETAIL_DEBUG_ENABLE_LOG + _CubLog("Invoking %d reduce_by_key_kernel<<<%d, %d, 0, %lld>>>(), %d " + "items per thread, %d SM occupancy\n", + start_tile, + scan_grid_size, + block_threads, + (long long)stream, + items_per_thread, + reduce_by_key_sm_occupancy); +#endif + + // Invoke reduce_by_key_kernel + THRUST_NS_QUALIFIER::cuda_cub::launcher::triple_chevron(scan_grid_size, + block_threads, + 0, + stream) + .doit(reduce_by_key_kernel, + d_keys_in, + d_unique_out, + d_values_in, + d_aggregates_out, + d_num_runs_out, + tile_state, + start_tile, + equality_op, + reduction_op, + num_items); + + // Check for failure to launch + if (CubDebug(error = cudaPeekAtLastError())) + { + break; + } + + // Sync the stream if specified to flush runtime errors + error = detail::DebugSyncStream(stream); + if (CubDebug(error)) + { + break; + } + } + } while (0); + + return error; + } + + template + CUB_RUNTIME_FUNCTION __forceinline__ cudaError_t Invoke() + { + using MaxPolicyT = typename SelectedPolicy::MaxPolicy; + return Invoke(DeviceCompactInitKernel, + DeviceReduceByKeyKernel); + } + + /** + * Internal dispatch routine + * @param[in] d_temp_storage + * Device-accessible allocation of temporary storage. When `nullptr`, the + * required allocation size is written to `temp_storage_bytes` and no + * work is done. + * + * @param[in,out] temp_storage_bytes + * Reference to size in bytes of `d_temp_storage` allocation + * + * @param[in] d_keys_in + * Pointer to the input sequence of keys + * + * @param[out] d_unique_out + * Pointer to the output sequence of unique keys (one key per run) + * + * @param[in] d_values_in + * Pointer to the input sequence of corresponding values + * + * @param[out] d_aggregates_out + * Pointer to the output sequence of value aggregates + * (one aggregate per run) + * + * @param[out] d_num_runs_out + * Pointer to total number of runs encountered + * (i.e., the length of d_unique_out) + * + * @param[in] equality_op + * KeyT equality operator + * + * @param[in] reduction_op + * ValueT reduction operator + * + * @param[in] num_items + * Total number of items to select from + * + * @param[in] stream + * CUDA stream to launch kernels within. Default is stream0. + */ + CUB_RUNTIME_FUNCTION __forceinline__ static cudaError_t + Dispatch(void *d_temp_storage, + size_t &temp_storage_bytes, + KeysInputIteratorT d_keys_in, + UniqueOutputIteratorT d_unique_out, + ValuesInputIteratorT d_values_in, + AggregatesOutputIteratorT d_aggregates_out, + NumRunsOutputIteratorT d_num_runs_out, + EqualityOpT equality_op, + ReductionOpT reduction_op, + OffsetT num_items, + cudaStream_t stream) + { + using MaxPolicyT = typename SelectedPolicy::MaxPolicy; + + cudaError error = cudaSuccess; + + do + { + // Get PTX version + int ptx_version = 0; + if (CubDebug(error = PtxVersion(ptx_version))) + { + break; + } + + DispatchReduceByKey dispatch(d_temp_storage, + temp_storage_bytes, + d_keys_in, + d_unique_out, + d_values_in, + d_aggregates_out, + d_num_runs_out, + equality_op, + reduction_op, + num_items, + stream); + + // Dispatch + if (CubDebug(error = MaxPolicyT::Invoke(ptx_version, dispatch))) + { + break; + } + } while (0); + + return error; + } + + CUB_DETAIL_RUNTIME_DEBUG_SYNC_IS_NOT_SUPPORTED + CUB_RUNTIME_FUNCTION __forceinline__ static cudaError_t + Dispatch(void *d_temp_storage, + size_t &temp_storage_bytes, + KeysInputIteratorT d_keys_in, + UniqueOutputIteratorT d_unique_out, + ValuesInputIteratorT d_values_in, + AggregatesOutputIteratorT d_aggregates_out, + NumRunsOutputIteratorT d_num_runs_out, + EqualityOpT equality_op, + ReductionOpT reduction_op, + OffsetT num_items, + cudaStream_t stream, + bool debug_synchronous) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + + return Dispatch(d_temp_storage, + temp_storage_bytes, + d_keys_in, + d_unique_out, + d_values_in, + d_aggregates_out, + d_num_runs_out, + equality_op, + reduction_op, + num_items, + stream); + } +}; + +CUB_NAMESPACE_END diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/device/dispatch/dispatch_rle.cuh b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/device/dispatch/dispatch_rle.cuh new file mode 100644 index 0000000000000000000000000000000000000000..6b978fa95fc8739439246fc541452ae742ff6ddb --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/device/dispatch/dispatch_rle.cuh @@ -0,0 +1,560 @@ +/****************************************************************************** + * Copyright (c) 2011, Duane Merrill. All rights reserved. + * Copyright (c) 2011-2018, NVIDIA CORPORATION. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the NVIDIA CORPORATION nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ******************************************************************************/ + +/** + * @file + * cub::DeviceRle provides device-wide, parallel operations for run-length-encoding sequences of + * data items residing within device-accessible memory. + */ + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include + +#include + +CUB_NAMESPACE_BEGIN + +/****************************************************************************** + * Kernel entry points + *****************************************************************************/ + +/** + * Select kernel entry point (multi-block) + * + * Performs functor-based selection if SelectOp functor type != NullType + * Otherwise performs flag-based selection if FlagIterator's value type != NullType + * Otherwise performs discontinuity selection (keep unique) + * + * @tparam AgentRlePolicyT + * Parameterized AgentRlePolicyT tuning policy type + * + * @tparam InputIteratorT + * Random-access input iterator type for reading input items \iterator + * + * @tparam OffsetsOutputIteratorT + * Random-access output iterator type for writing run-offset values \iterator + * + * @tparam LengthsOutputIteratorT + * Random-access output iterator type for writing run-length values \iterator + * + * @tparam NumRunsOutputIteratorT + * Output iterator type for recording the number of runs encountered \iterator + * + * @tparam ScanTileStateT + * Tile status interface type + * + * @tparam EqualityOpT + * T equality operator type + * + * @tparam OffsetT + * Signed integer type for global offsets + * + * @param d_in + * Pointer to input sequence of data items + * + * @param d_offsets_out + * Pointer to output sequence of run-offsets + * + * @param d_lengths_out + * Pointer to output sequence of run-lengths + * + * @param d_num_runs_out + * Pointer to total number of runs (i.e., length of `d_offsets_out`) + * + * @param tile_status + * Tile status interface + * + * @param equality_op + * Equality operator for input items + * + * @param num_items + * Total number of input items (i.e., length of `d_in`) + * + * @param num_tiles + * Total number of tiles for the entire problem + */ +template +__launch_bounds__(int(ChainedPolicyT::ActivePolicy::RleSweepPolicyT::BLOCK_THREADS)) __global__ + void DeviceRleSweepKernel(InputIteratorT d_in, + OffsetsOutputIteratorT d_offsets_out, + LengthsOutputIteratorT d_lengths_out, + NumRunsOutputIteratorT d_num_runs_out, + ScanTileStateT tile_status, + EqualityOpT equality_op, + OffsetT num_items, + int num_tiles) +{ + using AgentRlePolicyT = typename ChainedPolicyT::ActivePolicy::RleSweepPolicyT; + + // Thread block type for selecting data from input tiles + using AgentRleT = AgentRle; + + // Shared memory for AgentRle + __shared__ typename AgentRleT::TempStorage temp_storage; + + // Process tiles + AgentRleT(temp_storage, d_in, d_offsets_out, d_lengths_out, equality_op, num_items) + .ConsumeRange(num_tiles, tile_status, d_num_runs_out); +} + +/****************************************************************************** + * Dispatch + ******************************************************************************/ + +/** + * Utility class for dispatching the appropriately-tuned kernels for DeviceRle + * + * @tparam InputIteratorT + * Random-access input iterator type for reading input items \iterator + * + * @tparam OffsetsOutputIteratorT + * Random-access output iterator type for writing run-offset values \iterator + * + * @tparam LengthsOutputIteratorT + * Random-access output iterator type for writing run-length values \iterator + * + * @tparam NumRunsOutputIteratorT + * Output iterator type for recording the number of runs encountered \iterator + * + * @tparam EqualityOpT + * T equality operator type + * + * @tparam OffsetT + * Signed integer type for global offsets + * + * @tparam SelectedPolicy + * Implementation detail, do not specify directly, requirements on the + * content of this type are subject to breaking change. + */ +template , + cub::detail::value_t>> +struct DeviceRleDispatch +{ + /****************************************************************************** + * Types and constants + ******************************************************************************/ + + // The lengths output value type + using LengthT = cub::detail::non_void_value_t; + + enum + { + INIT_KERNEL_THREADS = 128, + }; + + // Tile status descriptor interface type + using ScanTileStateT = ReduceByKeyScanTileState; + + void *d_temp_storage; + size_t &temp_storage_bytes; + InputIteratorT d_in; + OffsetsOutputIteratorT d_offsets_out; + LengthsOutputIteratorT d_lengths_out; + NumRunsOutputIteratorT d_num_runs_out; + EqualityOpT equality_op; + OffsetT num_items; + cudaStream_t stream; + + CUB_RUNTIME_FUNCTION __forceinline__ DeviceRleDispatch(void *d_temp_storage, + size_t &temp_storage_bytes, + InputIteratorT d_in, + OffsetsOutputIteratorT d_offsets_out, + LengthsOutputIteratorT d_lengths_out, + NumRunsOutputIteratorT d_num_runs_out, + EqualityOpT equality_op, + OffsetT num_items, + cudaStream_t stream) + : d_temp_storage(d_temp_storage) + , temp_storage_bytes(temp_storage_bytes) + , d_in(d_in) + , d_offsets_out(d_offsets_out) + , d_lengths_out(d_lengths_out) + , d_num_runs_out(d_num_runs_out) + , equality_op(equality_op) + , num_items(num_items) + , stream(stream) + {} + + /****************************************************************************** + * Dispatch entrypoints + ******************************************************************************/ + + /** + * Internal dispatch routine for computing a device-wide run-length-encode using the + * specified kernel functions. + * + * @tparam DeviceScanInitKernelPtr + * Function type of cub::DeviceScanInitKernel + * + * @tparam DeviceRleSweepKernelPtr + * Function type of cub::DeviceRleSweepKernelPtr + * + * @param d_temp_storage + * Device-accessible allocation of temporary storage. + * When NULL, the required allocation size is written to + * `temp_storage_bytes` and no work is done. + * + * @param temp_storage_bytes + * Reference to size in bytes of `d_temp_storage` allocation + * + * @param d_in + * Pointer to the input sequence of data items + * + * @param d_offsets_out + * Pointer to the output sequence of run-offsets + * + * @param d_lengths_out + * Pointer to the output sequence of run-lengths + * + * @param d_num_runs_out + * Pointer to the total number of runs encountered (i.e., length of `d_offsets_out`) + * + * @param equality_op + * Equality operator for input items + * + * @param num_items + * Total number of input items (i.e., length of `d_in`) + * + * @param stream + * CUDA stream to launch kernels within. Default is stream0. + * + * @param ptx_version + * PTX version of dispatch kernels + * + * @param device_scan_init_kernel + * Kernel function pointer to parameterization of cub::DeviceScanInitKernel + * + * @param device_rle_sweep_kernel + * Kernel function pointer to parameterization of cub::DeviceRleSweepKernel + */ + template + CUB_RUNTIME_FUNCTION __forceinline__ cudaError_t + Invoke(DeviceScanInitKernelPtr device_scan_init_kernel, + DeviceRleSweepKernelPtr device_rle_sweep_kernel) + { + cudaError error = cudaSuccess; + + const int block_threads = ActivePolicyT::RleSweepPolicyT::BLOCK_THREADS; + const int items_per_thread = ActivePolicyT::RleSweepPolicyT::ITEMS_PER_THREAD; + + do + { + // Get device ordinal + int device_ordinal; + if (CubDebug(error = cudaGetDevice(&device_ordinal))) + break; + + // Number of input tiles + int tile_size = block_threads * items_per_thread; + int num_tiles = static_cast(cub::DivideAndRoundUp(num_items, tile_size)); + + // Specify temporary storage allocation requirements + size_t allocation_sizes[1]; + if (CubDebug(error = ScanTileStateT::AllocationSize(num_tiles, allocation_sizes[0]))) + { + break; // bytes needed for tile status descriptors + } + + // Compute allocation pointers into the single storage blob (or compute the necessary size of + // the blob) + void *allocations[1] = {}; + if (CubDebug( + error = + AliasTemporaries(d_temp_storage, temp_storage_bytes, allocations, allocation_sizes))) + { + break; + } + + if (d_temp_storage == nullptr) + { + // Return if the caller is simply requesting the size of the storage allocation + break; + } + + // Construct the tile status interface + ScanTileStateT tile_status; + if (CubDebug(error = tile_status.Init(num_tiles, allocations[0], allocation_sizes[0]))) + { + break; + } + + // Log device_scan_init_kernel configuration + int init_grid_size = CUB_MAX(1, cub::DivideAndRoundUp(num_tiles, INIT_KERNEL_THREADS)); + +#ifdef CUB_DETAIL_DEBUG_ENABLE_LOG + _CubLog("Invoking device_scan_init_kernel<<<%d, %d, 0, %lld>>>()\n", + init_grid_size, + INIT_KERNEL_THREADS, + (long long)stream); +#endif + + // Invoke device_scan_init_kernel to initialize tile descriptors and queue descriptors + THRUST_NS_QUALIFIER::cuda_cub::launcher::triple_chevron(init_grid_size, + INIT_KERNEL_THREADS, + 0, + stream) + .doit(device_scan_init_kernel, tile_status, num_tiles, d_num_runs_out); + + // Check for failure to launch + if (CubDebug(error = cudaPeekAtLastError())) + { + break; + } + + // Sync the stream if specified to flush runtime errors + error = detail::DebugSyncStream(stream); + if (CubDebug(error)) + { + break; + } + + // Return if empty problem + if (num_items == 0) + { + break; + } + + // Get SM occupancy for device_rle_sweep_kernel + int device_rle_kernel_sm_occupancy; + if (CubDebug(error = MaxSmOccupancy(device_rle_kernel_sm_occupancy, // out + device_rle_sweep_kernel, + block_threads))) + { + break; + } + + // Get max x-dimension of grid + int max_dim_x; + if (CubDebug( + error = cudaDeviceGetAttribute(&max_dim_x, cudaDevAttrMaxGridDimX, device_ordinal))) + { + break; + } + + // Get grid size for scanning tiles + dim3 scan_grid_size; + scan_grid_size.z = 1; + scan_grid_size.y = cub::DivideAndRoundUp(num_tiles, max_dim_x); + scan_grid_size.x = CUB_MIN(num_tiles, max_dim_x); + +// Log device_rle_sweep_kernel configuration +#ifdef CUB_DETAIL_DEBUG_ENABLE_LOG + _CubLog("Invoking device_rle_sweep_kernel<<<{%d,%d,%d}, %d, 0, %lld>>>(), %d items per " + "thread, %d SM occupancy\n", + scan_grid_size.x, + scan_grid_size.y, + scan_grid_size.z, + block_threads, + (long long)stream, + items_per_thread, + device_rle_kernel_sm_occupancy); +#endif + + // Invoke device_rle_sweep_kernel + THRUST_NS_QUALIFIER::cuda_cub::launcher::triple_chevron(scan_grid_size, + block_threads, + 0, + stream) + .doit(device_rle_sweep_kernel, + d_in, + d_offsets_out, + d_lengths_out, + d_num_runs_out, + tile_status, + equality_op, + num_items, + num_tiles); + + // Check for failure to launch + if (CubDebug(error = cudaPeekAtLastError())) + { + break; + } + + // Sync the stream if specified to flush runtime errors + error = detail::DebugSyncStream(stream); + if (CubDebug(error)) + { + break; + } + } while (0); + + return error; + } + + template + CUB_RUNTIME_FUNCTION __forceinline__ cudaError_t Invoke() + { + using MaxPolicyT = typename SelectedPolicy::MaxPolicy; + return Invoke(DeviceCompactInitKernel, + DeviceRleSweepKernel); + } + + /** + * Internal dispatch routine + * + * @param d_temp_storage + * Device-accessible allocation of temporary storage. + * When NULL, the required allocation size is written to + * `temp_storage_bytes` and no work is done. + * + * @param temp_storage_bytes + * Reference to size in bytes of `d_temp_storage` allocation + * + * @param d_in + * Pointer to input sequence of data items + * + * @param d_offsets_out + * Pointer to output sequence of run-offsets + * + * @param d_lengths_out + * Pointer to output sequence of run-lengths + * + * @param d_num_runs_out + * Pointer to total number of runs (i.e., length of `d_offsets_out`) + * + * @param equality_op + * Equality operator for input items + * + * @param num_items + * Total number of input items (i.e., length of `d_in`) + * + * @param stream + * [optional] CUDA stream to launch kernels within. + * Default is stream0. + */ + CUB_RUNTIME_FUNCTION __forceinline__ static cudaError_t + Dispatch(void *d_temp_storage, + size_t &temp_storage_bytes, + InputIteratorT d_in, + OffsetsOutputIteratorT d_offsets_out, + LengthsOutputIteratorT d_lengths_out, + NumRunsOutputIteratorT d_num_runs_out, + EqualityOpT equality_op, + OffsetT num_items, + cudaStream_t stream) + { + using MaxPolicyT = typename SelectedPolicy::MaxPolicy; + + cudaError error = cudaSuccess; + + do + { + // Get PTX version + int ptx_version = 0; + if (CubDebug(error = PtxVersion(ptx_version))) + { + break; + } + + DeviceRleDispatch dispatch(d_temp_storage, + temp_storage_bytes, + d_in, + d_offsets_out, + d_lengths_out, + d_num_runs_out, + equality_op, + num_items, + stream); + + // Dispatch + if (CubDebug(error = MaxPolicyT::Invoke(ptx_version, dispatch))) + { + break; + } + } while (0); + + return error; + } + + CUB_RUNTIME_FUNCTION __forceinline__ static cudaError_t + Dispatch(void *d_temp_storage, + size_t &temp_storage_bytes, + InputIteratorT d_in, + OffsetsOutputIteratorT d_offsets_out, + LengthsOutputIteratorT d_lengths_out, + NumRunsOutputIteratorT d_num_runs_out, + EqualityOpT equality_op, + OffsetT num_items, + cudaStream_t stream, + bool debug_synchronous) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + + return Dispatch(d_temp_storage, + temp_storage_bytes, + d_in, + d_offsets_out, + d_lengths_out, + d_num_runs_out, + equality_op, + num_items, + stream); + } +}; + +CUB_NAMESPACE_END diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/device/dispatch/dispatch_scan.cuh b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/device/dispatch/dispatch_scan.cuh new file mode 100644 index 0000000000000000000000000000000000000000..a4bf2eff5fa6a87ebb2cf185a20603f57cdacba7 --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/device/dispatch/dispatch_scan.cuh @@ -0,0 +1,636 @@ + +/****************************************************************************** + * Copyright (c) 2011, Duane Merrill. All rights reserved. + * Copyright (c) 2011-2022, NVIDIA CORPORATION. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the NVIDIA CORPORATION nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ******************************************************************************/ + +/** + * @file cub::DeviceScan provides device-wide, parallel operations for + * computing a prefix scan across a sequence of data items residing + * within device-accessible memory. + */ + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include + +CUB_NAMESPACE_BEGIN + +/****************************************************************************** + * Kernel entry points + *****************************************************************************/ + +/** + * @brief Initialization kernel for tile status initialization (multi-block) + * + * @tparam ScanTileStateT + * Tile status interface type + * + * @param[in] tile_state + * Tile status interface + * + * @param[in] num_tiles + * Number of tiles + */ +template +__global__ void DeviceScanInitKernel(ScanTileStateT tile_state, int num_tiles) +{ + // Initialize tile status + tile_state.InitializeStatus(num_tiles); +} + +/** + * Initialization kernel for tile status initialization (multi-block) + * + * @tparam ScanTileStateT + * Tile status interface type + * + * @tparam NumSelectedIteratorT + * Output iterator type for recording the number of items selected + * + * @param[in] tile_state + * Tile status interface + * + * @param[in] num_tiles + * Number of tiles + * + * @param[out] d_num_selected_out + * Pointer to the total number of items selected + * (i.e., length of `d_selected_out`) + */ +template +__global__ void DeviceCompactInitKernel(ScanTileStateT tile_state, + int num_tiles, + NumSelectedIteratorT d_num_selected_out) +{ + // Initialize tile status + tile_state.InitializeStatus(num_tiles); + + // Initialize d_num_selected_out + if ((blockIdx.x == 0) && (threadIdx.x == 0)) + { + *d_num_selected_out = 0; + } +} + +/** + * @brief Scan kernel entry point (multi-block) + * + * + * @tparam ChainedPolicyT + * Chained tuning policy + * + * @tparam InputIteratorT + * Random-access input iterator type for reading scan inputs \iterator + * + * @tparam OutputIteratorT + * Random-access output iterator type for writing scan outputs \iterator + * + * @tparam ScanTileStateT + * Tile status interface type + * + * @tparam ScanOpT + * Binary scan functor type having member + * `auto operator()(const T &a, const U &b)` + * + * @tparam InitValueT + * Initial value to seed the exclusive scan + * (cub::NullType for inclusive scans) + * + * @tparam OffsetT + * Signed integer type for global offsets + * + * @paramInput d_in + * data + * + * @paramOutput d_out + * data + * + * @paramTile tile_state + * status interface + * + * @paramThe start_tile + * starting tile for the current grid + * + * @paramBinary scan_op + * scan functor + * + * @paramInitial init_value + * value to seed the exclusive scan + * + * @paramTotal num_items + * number of scan items for the entire problem + */ +template +__launch_bounds__(int(ChainedPolicyT::ActivePolicy::ScanPolicyT::BLOCK_THREADS)) + __global__ void DeviceScanKernel(InputIteratorT d_in, + OutputIteratorT d_out, + ScanTileStateT tile_state, + int start_tile, + ScanOpT scan_op, + InitValueT init_value, + OffsetT num_items) +{ + using RealInitValueT = typename InitValueT::value_type; + typedef typename ChainedPolicyT::ActivePolicy::ScanPolicyT ScanPolicyT; + + // Thread block type for scanning input tiles + typedef AgentScan + AgentScanT; + + // Shared memory for AgentScan + __shared__ typename AgentScanT::TempStorage temp_storage; + + RealInitValueT real_init_value = init_value; + + // Process tiles + AgentScanT(temp_storage, d_in, d_out, scan_op, real_init_value) + .ConsumeRange(num_items, tile_state, start_tile); +} + +/****************************************************************************** + * Dispatch + ******************************************************************************/ + +/** + * @brief Utility class for dispatching the appropriately-tuned kernels for + * DeviceScan + * + * @tparam InputIteratorT + * Random-access input iterator type for reading scan inputs \iterator + * + * @tparam OutputIteratorT + * Random-access output iterator type for writing scan outputs \iterator + * + * @tparam ScanOpT + * Binary scan functor type having member + * `auto operator()(const T &a, const U &b)` + * + * @tparam InitValueT + * The init_value element type for ScanOpT (cub::NullType for inclusive scans) + * + * @tparam OffsetT + * Signed integer type for global offsets + * + */ +template ::value, + cub::detail::value_t, + typename InitValueT::value_type>, + cub::detail::value_t>, + typename SelectedPolicy = DeviceScanPolicy> +struct DispatchScan : SelectedPolicy +{ + //--------------------------------------------------------------------- + // Constants and Types + //--------------------------------------------------------------------- + + static constexpr int INIT_KERNEL_THREADS = 128; + + // The input value type + using InputT = cub::detail::value_t; + + /// Device-accessible allocation of temporary storage. When NULL, the + /// required allocation size is written to \p temp_storage_bytes and no work + /// is done. + void *d_temp_storage; + + /// Reference to size in bytes of \p d_temp_storage allocation + size_t &temp_storage_bytes; + + /// Iterator to the input sequence of data items + InputIteratorT d_in; + + /// Iterator to the output sequence of data items + OutputIteratorT d_out; + + /// Binary scan functor + ScanOpT scan_op; + + /// Initial value to seed the exclusive scan + InitValueT init_value; + + /// Total number of input items (i.e., the length of \p d_in) + OffsetT num_items; + + /// CUDA stream to launch kernels within. Default is stream0. + cudaStream_t stream; + + int ptx_version; + + /** + * + * @param[in] d_temp_storage + * Device-accessible allocation of temporary storage. When `nullptr`, the + * required allocation size is written to `temp_storage_bytes` and no + * work is done. + * + * @param[in,out] temp_storage_bytes + * Reference to size in bytes of `d_temp_storage` allocation + * + * @param[in] d_in + * Iterator to the input sequence of data items + * + * @param[out] d_out + * Iterator to the output sequence of data items + * + * @param[in] num_items + * Total number of input items (i.e., the length of `d_in`) + * + * @param[in] scan_op + * Binary scan functor + * + * @param[in] init_value + * Initial value to seed the exclusive scan + * + * @param[in] stream + * **[optional]** CUDA stream to launch kernels within. + * Default is stream0. + */ + CUB_RUNTIME_FUNCTION __forceinline__ DispatchScan(void *d_temp_storage, + size_t &temp_storage_bytes, + InputIteratorT d_in, + OutputIteratorT d_out, + OffsetT num_items, + ScanOpT scan_op, + InitValueT init_value, + cudaStream_t stream, + int ptx_version) + : d_temp_storage(d_temp_storage) + , temp_storage_bytes(temp_storage_bytes) + , d_in(d_in) + , d_out(d_out) + , scan_op(scan_op) + , init_value(init_value) + , num_items(num_items) + , stream(stream) + , ptx_version(ptx_version) + {} + + CUB_DETAIL_RUNTIME_DEBUG_SYNC_IS_NOT_SUPPORTED + CUB_RUNTIME_FUNCTION __forceinline__ DispatchScan(void *d_temp_storage, + size_t &temp_storage_bytes, + InputIteratorT d_in, + OutputIteratorT d_out, + OffsetT num_items, + ScanOpT scan_op, + InitValueT init_value, + cudaStream_t stream, + bool debug_synchronous, + int ptx_version) + : d_temp_storage(d_temp_storage) + , temp_storage_bytes(temp_storage_bytes) + , d_in(d_in) + , d_out(d_out) + , scan_op(scan_op) + , init_value(init_value) + , num_items(num_items) + , stream(stream) + , ptx_version(ptx_version) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + } + + template + CUB_RUNTIME_FUNCTION __host__ __forceinline__ cudaError_t + Invoke(InitKernel init_kernel, ScanKernel scan_kernel) + { + typedef typename ActivePolicyT::ScanPolicyT Policy; + typedef typename cub::ScanTileState ScanTileStateT; + + // `LOAD_LDG` makes in-place execution UB and doesn't lead to better + // performance. + static_assert(Policy::LOAD_MODIFIER != CacheLoadModifier::LOAD_LDG, + "The memory consistency model does not apply to texture " + "accesses"); + + cudaError error = cudaSuccess; + do + { + // Get device ordinal + int device_ordinal; + if (CubDebug(error = cudaGetDevice(&device_ordinal))) + { + break; + } + + // Number of input tiles + int tile_size = Policy::BLOCK_THREADS * Policy::ITEMS_PER_THREAD; + int num_tiles = + static_cast(cub::DivideAndRoundUp(num_items, tile_size)); + + // Specify temporary storage allocation requirements + size_t allocation_sizes[1]; + if (CubDebug(error = ScanTileStateT::AllocationSize(num_tiles, + allocation_sizes[0]))) + { + break; // bytes needed for tile status descriptors + } + + // Compute allocation pointers into the single storage blob (or compute + // the necessary size of the blob) + void *allocations[1] = {}; + if (CubDebug(error = AliasTemporaries(d_temp_storage, + temp_storage_bytes, + allocations, + allocation_sizes))) + { + break; + } + + if (d_temp_storage == NULL) + { + // Return if the caller is simply requesting the size of the storage + // allocation + break; + } + + // Return if empty problem + if (num_items == 0) + { + break; + } + + // Construct the tile status interface + ScanTileStateT tile_state; + if (CubDebug(error = tile_state.Init(num_tiles, + allocations[0], + allocation_sizes[0]))) + { + break; + } + + // Log init_kernel configuration + int init_grid_size = cub::DivideAndRoundUp(num_tiles, + INIT_KERNEL_THREADS); + + #ifdef CUB_DETAIL_DEBUG_ENABLE_LOG + _CubLog("Invoking init_kernel<<<%d, %d, 0, %lld>>>()\n", + init_grid_size, + INIT_KERNEL_THREADS, + (long long)stream); + #endif + + // Invoke init_kernel to initialize tile descriptors + THRUST_NS_QUALIFIER::cuda_cub::launcher::triple_chevron( + init_grid_size, + INIT_KERNEL_THREADS, + 0, + stream) + .doit(init_kernel, tile_state, num_tiles); + + // Check for failure to launch + if (CubDebug(error = cudaPeekAtLastError())) + { + break; + } + + // Sync the stream if specified to flush runtime errors + error = detail::DebugSyncStream(stream); + if (CubDebug(error)) + { + break; + } + + // Get SM occupancy for scan_kernel + int scan_sm_occupancy; + if (CubDebug(error = MaxSmOccupancy(scan_sm_occupancy, // out + scan_kernel, + Policy::BLOCK_THREADS))) + { + break; + } + + // Get max x-dimension of grid + int max_dim_x; + if (CubDebug(error = cudaDeviceGetAttribute(&max_dim_x, + cudaDevAttrMaxGridDimX, + device_ordinal))) + { + break; + } + + // Run grids in epochs (in case number of tiles exceeds max x-dimension + int scan_grid_size = CUB_MIN(num_tiles, max_dim_x); + for (int start_tile = 0; start_tile < num_tiles; + start_tile += scan_grid_size) + { + // Log scan_kernel configuration + #ifdef CUB_DETAIL_DEBUG_ENABLE_LOG + _CubLog("Invoking %d scan_kernel<<<%d, %d, 0, %lld>>>(), %d items " + "per thread, %d SM occupancy\n", + start_tile, + scan_grid_size, + Policy::BLOCK_THREADS, + (long long)stream, + Policy::ITEMS_PER_THREAD, + scan_sm_occupancy); + #endif + + // Invoke scan_kernel + THRUST_NS_QUALIFIER::cuda_cub::launcher::triple_chevron( + scan_grid_size, + Policy::BLOCK_THREADS, + 0, + stream) + .doit(scan_kernel, + d_in, + d_out, + tile_state, + start_tile, + scan_op, + init_value, + num_items); + + // Check for failure to launch + if (CubDebug(error = cudaPeekAtLastError())) + { + break; + } + + // Sync the stream if specified to flush runtime errors + error = detail::DebugSyncStream(stream); + if (CubDebug(error)) + { + break; + } + } + } while (0); + + return error; + } + + template + CUB_RUNTIME_FUNCTION __host__ __forceinline__ cudaError_t Invoke() + { + typedef typename DispatchScan::MaxPolicy MaxPolicyT; + typedef typename cub::ScanTileState ScanTileStateT; + // Ensure kernels are instantiated. + return Invoke(DeviceScanInitKernel, + DeviceScanKernel); + } + + /** + * @brief Internal dispatch routine + * + * @param[in] d_temp_storage + * Device-accessible allocation of temporary storage. When `nullptr`, the + * required allocation size is written to `temp_storage_bytes` and no + * work is done. + * + * @param[in,out] temp_storage_bytes + * Reference to size in bytes of `d_temp_storage` allocation + * + * @param[in] d_in + * Iterator to the input sequence of data items + * + * @param[out] d_out + * Iterator to the output sequence of data items + * + * @param[in] scan_op + * Binary scan functor + * + * @param[in] init_value + * Initial value to seed the exclusive scan + * + * @param[in] num_items + * Total number of input items (i.e., the length of `d_in`) + * + * @param[in] stream + * **[optional]** CUDA stream to launch kernels within. + * Default is stream0. + * + */ + CUB_RUNTIME_FUNCTION __forceinline__ static cudaError_t + Dispatch(void *d_temp_storage, + size_t &temp_storage_bytes, + InputIteratorT d_in, + OutputIteratorT d_out, + ScanOpT scan_op, + InitValueT init_value, + OffsetT num_items, + cudaStream_t stream) + { + typedef typename DispatchScan::MaxPolicy MaxPolicyT; + + cudaError_t error; + do + { + // Get PTX version + int ptx_version = 0; + if (CubDebug(error = PtxVersion(ptx_version))) + { + break; + } + + // Create dispatch functor + DispatchScan dispatch(d_temp_storage, + temp_storage_bytes, + d_in, + d_out, + num_items, + scan_op, + init_value, + stream, + ptx_version); + + // Dispatch to chained policy + if (CubDebug(error = MaxPolicyT::Invoke(ptx_version, dispatch))) + { + break; + } + } while (0); + + return error; + } + + CUB_DETAIL_RUNTIME_DEBUG_SYNC_IS_NOT_SUPPORTED + CUB_RUNTIME_FUNCTION __forceinline__ static cudaError_t + Dispatch(void *d_temp_storage, + size_t &temp_storage_bytes, + InputIteratorT d_in, + OutputIteratorT d_out, + ScanOpT scan_op, + InitValueT init_value, + OffsetT num_items, + cudaStream_t stream, + bool debug_synchronous) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + + return Dispatch(d_temp_storage, + temp_storage_bytes, + d_in, + d_out, + scan_op, + init_value, + num_items, + stream); + } +}; + +CUB_NAMESPACE_END + diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/device/dispatch/dispatch_segmented_sort.cuh b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/device/dispatch/dispatch_segmented_sort.cuh new file mode 100644 index 0000000000000000000000000000000000000000..d00e998f165f63833969c56fedd1cd3bcdcc5a08 --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/device/dispatch/dispatch_segmented_sort.cuh @@ -0,0 +1,1783 @@ +/****************************************************************************** + * Copyright (c) 2011-2021, NVIDIA CORPORATION. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the NVIDIA CORPORATION nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ******************************************************************************/ + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include + +#include + + +CUB_NAMESPACE_BEGIN + + +/** + * @brief Fallback kernel, in case there's not enough segments to + * take advantage of partitioning. + * + * In this case, the sorting method is still selected based on the segment size. + * If a single warp can sort the segment, the algorithm will use the sub-warp + * merge sort. Otherwise, the algorithm will use the in-shared-memory version of + * block radix sort. If data don't fit into shared memory, the algorithm will + * use in-global-memory radix sort. + * + * @param[in] d_keys_in_orig + * Input keys buffer + * + * @param[out] d_keys_out_orig + * Output keys buffer + * + * @param[in,out] d_keys_double_buffer + * Double keys buffer + * + * @param[in] d_values_in_orig + * Input values buffer + * + * @param[out] d_values_out_orig + * Output values buffer + * + * @param[in,out] d_values_double_buffer + * Double values buffer + * + * @param[in] d_begin_offsets + * Random-access input iterator to the sequence of beginning offsets of length + * @p num_segments, such that `d_begin_offsets[i]` is the first element of the + * i-th data segment in `d_keys_*` and `d_values_*` + * + * @param[in] d_end_offsets + * Random-access input iterator to the sequence of ending offsets of length + * @p num_segments, such that `d_end_offsets[i]-1` is the last element of the + * i-th data segment in `d_keys_*` and `d_values_*`. + * If `d_end_offsets[i]-1 <= d_begin_offsets[i]`, the i-th segment is + * considered empty. + */ +template +__launch_bounds__(ChainedPolicyT::ActivePolicy::LargeSegmentPolicy::BLOCK_THREADS) +__global__ void DeviceSegmentedSortFallbackKernel( + const KeyT *d_keys_in_orig, + KeyT *d_keys_out_orig, + cub::detail::device_double_buffer d_keys_double_buffer, + const ValueT *d_values_in_orig, + ValueT *d_values_out_orig, + cub::detail::device_double_buffer d_values_double_buffer, + BeginOffsetIteratorT d_begin_offsets, + EndOffsetIteratorT d_end_offsets) +{ + using ActivePolicyT = typename ChainedPolicyT::ActivePolicy; + using LargeSegmentPolicyT = typename ActivePolicyT::LargeSegmentPolicy; + using MediumPolicyT = + typename ActivePolicyT::SmallAndMediumSegmentedSortPolicyT::MediumPolicyT; + + const unsigned int segment_id = blockIdx.x; + OffsetT segment_begin = d_begin_offsets[segment_id]; + OffsetT segment_end = d_end_offsets[segment_id]; + OffsetT num_items = segment_end - segment_begin; + + if (num_items <= 0) + { + return; + } + + using AgentSegmentedRadixSortT = + cub::AgentSegmentedRadixSort; + + using WarpReduceT = cub::WarpReduce; + + using AgentWarpMergeSortT = + AgentSubWarpSort; + + __shared__ union + { + typename AgentSegmentedRadixSortT::TempStorage block_sort; + typename WarpReduceT::TempStorage warp_reduce; + typename AgentWarpMergeSortT::TempStorage medium_warp_sort; + } temp_storage; + + constexpr bool keys_only = std::is_same::value; + AgentSegmentedRadixSortT agent(num_items, temp_storage.block_sort); + + constexpr int begin_bit = 0; + constexpr int end_bit = sizeof(KeyT) * 8; + + constexpr int cacheable_tile_size = LargeSegmentPolicyT::BLOCK_THREADS * + LargeSegmentPolicyT::ITEMS_PER_THREAD; + + d_keys_in_orig += segment_begin; + d_keys_out_orig += segment_begin; + + if (!keys_only) + { + d_values_in_orig += segment_begin; + d_values_out_orig += segment_begin; + } + + if (num_items <= MediumPolicyT::ITEMS_PER_TILE) + { + // Sort by a single warp + if (threadIdx.x < MediumPolicyT::WARP_THREADS) + { + AgentWarpMergeSortT(temp_storage.medium_warp_sort) + .ProcessSegment(num_items, + d_keys_in_orig, + d_keys_out_orig, + d_values_in_orig, + d_values_out_orig); + } + } + else if (num_items < cacheable_tile_size) + { + // Sort by a CTA if data fits into shared memory + agent.ProcessSinglePass(begin_bit, + end_bit, + d_keys_in_orig, + d_values_in_orig, + d_keys_out_orig, + d_values_out_orig); + } + else + { + // Sort by a CTA with multiple reads from global memory + int current_bit = begin_bit; + int pass_bits = (cub::min)(int{LargeSegmentPolicyT::RADIX_BITS}, + (end_bit - current_bit)); + + d_keys_double_buffer = cub::detail::device_double_buffer( + d_keys_double_buffer.current() + segment_begin, + d_keys_double_buffer.alternate() + segment_begin); + + if (!keys_only) + { + d_values_double_buffer = cub::detail::device_double_buffer( + d_values_double_buffer.current() + segment_begin, + d_values_double_buffer.alternate() + segment_begin); + } + + agent.ProcessIterative(current_bit, + pass_bits, + d_keys_in_orig, + d_values_in_orig, + d_keys_double_buffer.current(), + d_values_double_buffer.current()); + current_bit += pass_bits; + + #pragma unroll 1 + while (current_bit < end_bit) + { + pass_bits = (cub::min)(int{LargeSegmentPolicyT::RADIX_BITS}, + (end_bit - current_bit)); + + CTA_SYNC(); + agent.ProcessIterative(current_bit, + pass_bits, + d_keys_double_buffer.current(), + d_values_double_buffer.current(), + d_keys_double_buffer.alternate(), + d_values_double_buffer.alternate()); + + d_keys_double_buffer.swap(); + d_values_double_buffer.swap(); + current_bit += pass_bits; + } + } +} + + +/** + * @brief Single kernel for moderate size (less than a few thousand items) + * segments. + * + * This kernel allocates a sub-warp per segment. Therefore, this kernel assigns + * a single thread block to multiple segments. Segments fall into two + * categories. An architectural warp usually sorts segments in the medium-size + * category, while a few threads sort segments in the small-size category. Since + * segments are partitioned, we know the last thread block index assigned to + * sort medium-size segments. A particular thread block can check this number to + * find out which category it was assigned to sort. In both cases, the + * merge sort is used. + * + * @param[in] small_segments + * Number of segments that can be sorted by a warp part + * + * @param[in] medium_segments + * Number of segments that can be sorted by a warp + * + * @param[in] medium_blocks + * Number of CTAs assigned to process medium segments + * + * @param[in] d_small_segments_indices + * Small segments mapping of length @p small_segments, such that + * `d_small_segments_indices[i]` is the input segment index + * + * @param[in] d_medium_segments_indices + * Medium segments mapping of length @p medium_segments, such that + * `d_medium_segments_indices[i]` is the input segment index + * + * @param[in] d_keys_in_orig + * Input keys buffer + * + * @param[out] d_keys_out_orig + * Output keys buffer + * + * @param[in] d_values_in_orig + * Input values buffer + * + * @param[out] d_values_out_orig + * Output values buffer + * + * @param[in] d_begin_offsets + * Random-access input iterator to the sequence of beginning offsets of length + * @p num_segments, such that `d_begin_offsets[i]` is the first element of the + * ith data segment in `d_keys_*` and `d_values_*` + * + * @param[in] d_end_offsets + * Random-access input iterator to the sequence of ending offsets of length + * @p num_segments, such that `d_end_offsets[i]-1` is the last element of the + * ith data segment in `d_keys_*` and `d_values_*`. If + * `d_end_offsets[i]-1 <= d_begin_offsets[i]`, the ith is + * considered empty. + */ +template +__launch_bounds__(ChainedPolicyT::ActivePolicy::SmallAndMediumSegmentedSortPolicyT::BLOCK_THREADS) +__global__ void DeviceSegmentedSortKernelSmall( + unsigned int small_segments, + unsigned int medium_segments, + unsigned int medium_blocks, + const unsigned int *d_small_segments_indices, + const unsigned int *d_medium_segments_indices, + const KeyT *d_keys_in, + KeyT *d_keys_out, + const ValueT *d_values_in, + ValueT *d_values_out, + BeginOffsetIteratorT d_begin_offsets, + EndOffsetIteratorT d_end_offsets) +{ + const unsigned int tid = threadIdx.x; + const unsigned int bid = blockIdx.x; + + using ActivePolicyT = typename ChainedPolicyT::ActivePolicy; + using SmallAndMediumPolicyT = + typename ActivePolicyT::SmallAndMediumSegmentedSortPolicyT; + using MediumPolicyT = typename SmallAndMediumPolicyT::MediumPolicyT; + using SmallPolicyT = typename SmallAndMediumPolicyT::SmallPolicyT; + + constexpr int threads_per_medium_segment = MediumPolicyT::WARP_THREADS; + constexpr int threads_per_small_segment = SmallPolicyT::WARP_THREADS; + + using MediumAgentWarpMergeSortT = + AgentSubWarpSort; + + using SmallAgentWarpMergeSortT = + AgentSubWarpSort; + + constexpr auto segments_per_medium_block = + static_cast(SmallAndMediumPolicyT::SEGMENTS_PER_MEDIUM_BLOCK); + + constexpr auto segments_per_small_block = + static_cast(SmallAndMediumPolicyT::SEGMENTS_PER_SMALL_BLOCK); + + __shared__ union + { + typename MediumAgentWarpMergeSortT::TempStorage + medium_storage[segments_per_medium_block]; + + typename SmallAgentWarpMergeSortT::TempStorage + small_storage[segments_per_small_block]; + } temp_storage; + + if (bid < medium_blocks) + { + const unsigned int sid_within_block = tid / threads_per_medium_segment; + const unsigned int medium_segment_id = bid * segments_per_medium_block + + sid_within_block; + + if (medium_segment_id < medium_segments) + { + const unsigned int global_segment_id = + d_medium_segments_indices[medium_segment_id]; + + const OffsetT segment_begin = d_begin_offsets[global_segment_id]; + const OffsetT segment_end = d_end_offsets[global_segment_id]; + const OffsetT num_items = segment_end - segment_begin; + + MediumAgentWarpMergeSortT(temp_storage.medium_storage[sid_within_block]) + .ProcessSegment(num_items, + d_keys_in + segment_begin, + d_keys_out + segment_begin, + d_values_in + segment_begin, + d_values_out + segment_begin); + } + } + else + { + const unsigned int sid_within_block = tid / threads_per_small_segment; + const unsigned int small_segment_id = + (bid - medium_blocks) * segments_per_small_block + sid_within_block; + + if (small_segment_id < small_segments) + { + const unsigned int global_segment_id = + d_small_segments_indices[small_segment_id]; + + const OffsetT segment_begin = d_begin_offsets[global_segment_id]; + const OffsetT segment_end = d_end_offsets[global_segment_id]; + const OffsetT num_items = segment_end - segment_begin; + + SmallAgentWarpMergeSortT(temp_storage.small_storage[sid_within_block]) + .ProcessSegment(num_items, + d_keys_in + segment_begin, + d_keys_out + segment_begin, + d_values_in + segment_begin, + d_values_out + segment_begin); + } + } +} + +/** + * @brief Single kernel for large size (more than a few thousand items) segments. + * + * @param[in] d_keys_in_orig + * Input keys buffer + * + * @param[out] d_keys_out_orig + * Output keys buffer + * + * @param[in] d_values_in_orig + * Input values buffer + * + * @param[out] d_values_out_orig + * Output values buffer + * + * @param[in] d_begin_offsets + * Random-access input iterator to the sequence of beginning offsets of length + * @p num_segments, such that `d_begin_offsets[i]` is the first element of the + * ith data segment in `d_keys_*` and `d_values_*` + * + * @param[in] d_end_offsets + * Random-access input iterator to the sequence of ending offsets of length + * @p num_segments, such that `d_end_offsets[i]-1` is the last element of the + * ith data segment in `d_keys_*` and `d_values_*`. If + * `d_end_offsets[i]-1 <= d_begin_offsets[i]`, the ith is + * considered empty. + */ +template +__launch_bounds__(ChainedPolicyT::ActivePolicy::LargeSegmentPolicy::BLOCK_THREADS) +__global__ void DeviceSegmentedSortKernelLarge( + const unsigned int *d_segments_indices, + const KeyT *d_keys_in_orig, + KeyT *d_keys_out_orig, + cub::detail::device_double_buffer d_keys_double_buffer, + const ValueT *d_values_in_orig, + ValueT *d_values_out_orig, + cub::detail::device_double_buffer d_values_double_buffer, + BeginOffsetIteratorT d_begin_offsets, + EndOffsetIteratorT d_end_offsets) +{ + using ActivePolicyT = typename ChainedPolicyT::ActivePolicy; + using LargeSegmentPolicyT = typename ActivePolicyT::LargeSegmentPolicy; + + constexpr int small_tile_size = LargeSegmentPolicyT::BLOCK_THREADS * + LargeSegmentPolicyT::ITEMS_PER_THREAD; + + using AgentSegmentedRadixSortT = + cub::AgentSegmentedRadixSort; + + __shared__ typename AgentSegmentedRadixSortT::TempStorage storage; + + const unsigned int bid = blockIdx.x; + + constexpr int begin_bit = 0; + constexpr int end_bit = sizeof(KeyT) * 8; + + const unsigned int global_segment_id = d_segments_indices[bid]; + const OffsetT segment_begin = d_begin_offsets[global_segment_id]; + const OffsetT segment_end = d_end_offsets[global_segment_id]; + const OffsetT num_items = segment_end - segment_begin; + + constexpr bool keys_only = std::is_same::value; + AgentSegmentedRadixSortT agent(num_items, storage); + + d_keys_in_orig += segment_begin; + d_keys_out_orig += segment_begin; + + if (!keys_only) + { + d_values_in_orig += segment_begin; + d_values_out_orig += segment_begin; + } + + if (num_items < small_tile_size) + { + // Sort in shared memory if the segment fits into it + agent.ProcessSinglePass(begin_bit, + end_bit, + d_keys_in_orig, + d_values_in_orig, + d_keys_out_orig, + d_values_out_orig); + } + else + { + // Sort reading global memory multiple times + int current_bit = begin_bit; + int pass_bits = (cub::min)(int{LargeSegmentPolicyT::RADIX_BITS}, + (end_bit - current_bit)); + + d_keys_double_buffer = cub::detail::device_double_buffer( + d_keys_double_buffer.current() + segment_begin, + d_keys_double_buffer.alternate() + segment_begin); + + if (!keys_only) + { + d_values_double_buffer = cub::detail::device_double_buffer( + d_values_double_buffer.current() + segment_begin, + d_values_double_buffer.alternate() + segment_begin); + } + + agent.ProcessIterative(current_bit, + pass_bits, + d_keys_in_orig, + d_values_in_orig, + d_keys_double_buffer.current(), + d_values_double_buffer.current()); + current_bit += pass_bits; + + #pragma unroll 1 + while (current_bit < end_bit) + { + pass_bits = (cub::min)(int{LargeSegmentPolicyT::RADIX_BITS}, + (end_bit - current_bit)); + + CTA_SYNC(); + agent.ProcessIterative(current_bit, + pass_bits, + d_keys_double_buffer.current(), + d_values_double_buffer.current(), + d_keys_double_buffer.alternate(), + d_values_double_buffer.alternate()); + + d_keys_double_buffer.swap(); + d_values_double_buffer.swap(); + current_bit += pass_bits; + } + } +} + +/* + * Continuation is called after the partitioning stage. It launches kernels + * to sort large and small segments using the partitioning results. Separation + * of this stage is required to eliminate device-side synchronization in + * the CDP mode. + */ +template +CUB_RUNTIME_FUNCTION cudaError_t +DeviceSegmentedSortContinuation( + LargeKernelT large_kernel, + SmallKernelT small_kernel, + int num_segments, + KeyT *d_current_keys, + KeyT *d_final_keys, + detail::device_double_buffer d_keys_double_buffer, + ValueT *d_current_values, + ValueT *d_final_values, + detail::device_double_buffer d_values_double_buffer, + BeginOffsetIteratorT d_begin_offsets, + EndOffsetIteratorT d_end_offsets, + unsigned int *group_sizes, + unsigned int *large_and_medium_segments_indices, + unsigned int *small_segments_indices, + cudaStream_t stream) +{ + cudaError error = cudaSuccess; + + const unsigned int large_segments = group_sizes[0]; + + if (large_segments > 0) + { + // One CTA per segment + const unsigned int blocks_in_grid = large_segments; + + #ifdef CUB_DETAIL_DEBUG_ENABLE_LOG + _CubLog("Invoking " + "DeviceSegmentedSortKernelLarge<<<%d, %d, 0, %lld>>>()\n", + static_cast(blocks_in_grid), + LargeSegmentPolicyT::BLOCK_THREADS, + (long long)stream); + #endif + + THRUST_NS_QUALIFIER::cuda_cub::launcher::triple_chevron( + blocks_in_grid, + LargeSegmentPolicyT::BLOCK_THREADS, + 0, + stream) + .doit(large_kernel, + large_and_medium_segments_indices, + d_current_keys, + d_final_keys, + d_keys_double_buffer, + d_current_values, + d_final_values, + d_values_double_buffer, + d_begin_offsets, + d_end_offsets); + + // Check for failure to launch + if (CubDebug(error = cudaPeekAtLastError())) + { + return error; + } + + // Sync the stream if specified to flush runtime errors + error = detail::DebugSyncStream(stream); + if (CubDebug(error)) + { + return error; + } + } + + const unsigned int small_segments = group_sizes[1]; + const unsigned int medium_segments = + static_cast(num_segments) - + (large_segments + small_segments); + + const unsigned int small_blocks = + DivideAndRoundUp(small_segments, + SmallAndMediumPolicyT::SEGMENTS_PER_SMALL_BLOCK); + + const unsigned int medium_blocks = + DivideAndRoundUp(medium_segments, + SmallAndMediumPolicyT::SEGMENTS_PER_MEDIUM_BLOCK); + + const unsigned int small_and_medium_blocks_in_grid = small_blocks + + medium_blocks; + + if (small_and_medium_blocks_in_grid) + { + #ifdef CUB_DETAIL_DEBUG_ENABLE_LOG + _CubLog("Invoking " + "DeviceSegmentedSortKernelSmall<<<%d, %d, 0, %lld>>>()\n", + static_cast(small_and_medium_blocks_in_grid), + SmallAndMediumPolicyT::BLOCK_THREADS, + (long long)stream); + #endif + + THRUST_NS_QUALIFIER::cuda_cub::launcher::triple_chevron( + small_and_medium_blocks_in_grid, + SmallAndMediumPolicyT::BLOCK_THREADS, + 0, + stream) + .doit(small_kernel, + small_segments, + medium_segments, + medium_blocks, + small_segments_indices, + large_and_medium_segments_indices + num_segments - medium_segments, + d_current_keys, + d_final_keys, + d_current_values, + d_final_values, + d_begin_offsets, + d_end_offsets); + + // Check for failure to launch + if (CubDebug(error = cudaPeekAtLastError())) + { + return error; + } + + // Sync the stream if specified to flush runtime errors + error = detail::DebugSyncStream(stream); + if (CubDebug(error)) + { + return error; + } + } + + return error; +} + +#ifdef CUB_RDC_ENABLED +/* + * Continuation kernel is used only in the CDP mode. It's used to + * launch DeviceSegmentedSortContinuation as a separate kernel. + */ +template +__launch_bounds__(1) __global__ void +DeviceSegmentedSortContinuationKernel( + LargeKernelT large_kernel, + SmallKernelT small_kernel, + int num_segments, + KeyT *d_current_keys, + KeyT *d_final_keys, + detail::device_double_buffer d_keys_double_buffer, + ValueT *d_current_values, + ValueT *d_final_values, + detail::device_double_buffer d_values_double_buffer, + BeginOffsetIteratorT d_begin_offsets, + EndOffsetIteratorT d_end_offsets, + unsigned int *group_sizes, + unsigned int *large_and_medium_segments_indices, + unsigned int *small_segments_indices) +{ + using ActivePolicyT = typename ChainedPolicyT::ActivePolicy; + using LargeSegmentPolicyT = typename ActivePolicyT::LargeSegmentPolicy; + using SmallAndMediumPolicyT = + typename ActivePolicyT::SmallAndMediumSegmentedSortPolicyT; + + // In case of CDP: + // 1. each CTA has a different main stream + // 2. all streams are non-blocking + // 3. child grid always completes before the parent grid + // 4. streams can be used only from the CTA in which they were created + // 5. streams created on the host cannot be used on the device + // + // Due to (4, 5), we can't pass the user-provided stream in the continuation. + // Due to (1, 2, 3) it's safe to pass the main stream. + cudaError_t error = + DeviceSegmentedSortContinuation( + large_kernel, + small_kernel, + num_segments, + d_current_keys, + d_final_keys, + d_keys_double_buffer, + d_current_values, + d_final_values, + d_values_double_buffer, + d_begin_offsets, + d_end_offsets, + group_sizes, + large_and_medium_segments_indices, + small_segments_indices, + 0); // always launching on the main stream (see motivation above) + + CubDebug(error); +} +#endif // CUB_RDC_ENABLED + +template +struct DeviceSegmentedSortPolicy +{ + using DominantT = + cub::detail::conditional_t<(sizeof(ValueT) > sizeof(KeyT)), ValueT, KeyT>; + + constexpr static int KEYS_ONLY = std::is_same::value; + + //---------------------------------------------------------------------------- + // Architecture-specific tuning policies + //---------------------------------------------------------------------------- + + struct Policy350 : ChainedPolicy<350, Policy350, Policy350> + { + constexpr static int BLOCK_THREADS = 128; + constexpr static int RADIX_BITS = sizeof(KeyT) > 1 ? 6 : 4; + constexpr static int PARTITIONING_THRESHOLD = 300; + + using LargeSegmentPolicy = + AgentRadixSortDownsweepPolicy; + + constexpr static int ITEMS_PER_SMALL_THREAD = + Nominal4BItemsToItems(5); + + constexpr static int ITEMS_PER_MEDIUM_THREAD = + Nominal4BItemsToItems(5); + + using SmallAndMediumSegmentedSortPolicyT = + AgentSmallAndMediumSegmentedSortPolicy< + + BLOCK_THREADS, + + // Small policy + cub::AgentSubWarpMergeSortPolicy<4, + ITEMS_PER_SMALL_THREAD, + WarpLoadAlgorithm::WARP_LOAD_DIRECT, + CacheLoadModifier::LOAD_DEFAULT>, + + // Medium policy + cub::AgentSubWarpMergeSortPolicy<32, + ITEMS_PER_MEDIUM_THREAD, + WarpLoadAlgorithm::WARP_LOAD_DIRECT, + CacheLoadModifier::LOAD_DEFAULT>>; + }; + + struct Policy500 : ChainedPolicy<500, Policy500, Policy350> + { + constexpr static int BLOCK_THREADS = 256; + constexpr static int RADIX_BITS = sizeof(KeyT) > 1 ? 6 : 4; + constexpr static int PARTITIONING_THRESHOLD = 300; + + using LargeSegmentPolicy = + AgentRadixSortDownsweepPolicy; + + constexpr static int ITEMS_PER_SMALL_THREAD = + Nominal4BItemsToItems(7); + + constexpr static int ITEMS_PER_MEDIUM_THREAD = + Nominal4BItemsToItems(7); + + using SmallAndMediumSegmentedSortPolicyT = + AgentSmallAndMediumSegmentedSortPolicy< + + BLOCK_THREADS, + + // Small policy + cub::AgentSubWarpMergeSortPolicy<4, // Threads per segment + ITEMS_PER_SMALL_THREAD, + WarpLoadAlgorithm::WARP_LOAD_DIRECT, + CacheLoadModifier::LOAD_DEFAULT>, + + // Medium policy + cub::AgentSubWarpMergeSortPolicy<32, // Threads per segment + ITEMS_PER_MEDIUM_THREAD, + WarpLoadAlgorithm::WARP_LOAD_DIRECT, + CacheLoadModifier::LOAD_DEFAULT>>; + }; + + struct Policy600 : ChainedPolicy<600, Policy600, Policy500> + { + constexpr static int BLOCK_THREADS = 256; + constexpr static int RADIX_BITS = sizeof(KeyT) > 1 ? 6 : 4; + constexpr static int PARTITIONING_THRESHOLD = 500; + + using LargeSegmentPolicy = + AgentRadixSortDownsweepPolicy; + + constexpr static int ITEMS_PER_SMALL_THREAD = + Nominal4BItemsToItems(9); + + constexpr static int ITEMS_PER_MEDIUM_THREAD = + Nominal4BItemsToItems(9); + + using SmallAndMediumSegmentedSortPolicyT = + AgentSmallAndMediumSegmentedSortPolicy< + + BLOCK_THREADS, + + // Small policy + cub::AgentSubWarpMergeSortPolicy<4, // Threads per segment + ITEMS_PER_SMALL_THREAD, + WarpLoadAlgorithm::WARP_LOAD_DIRECT, + CacheLoadModifier::LOAD_DEFAULT>, + + // Medium policy + cub::AgentSubWarpMergeSortPolicy<32, // Threads per segment + ITEMS_PER_MEDIUM_THREAD, + WarpLoadAlgorithm::WARP_LOAD_DIRECT, + CacheLoadModifier::LOAD_DEFAULT>>; + }; + + struct Policy610 : ChainedPolicy<610, Policy610, Policy600> + { + constexpr static int BLOCK_THREADS = 256; + constexpr static int RADIX_BITS = sizeof(KeyT) > 1 ? 6 : 4; + constexpr static int PARTITIONING_THRESHOLD = 500; + + using LargeSegmentPolicy = + AgentRadixSortDownsweepPolicy; + + constexpr static int ITEMS_PER_SMALL_THREAD = + Nominal4BItemsToItems(9); + + constexpr static int ITEMS_PER_MEDIUM_THREAD = + Nominal4BItemsToItems(9); + + using SmallAndMediumSegmentedSortPolicyT = + AgentSmallAndMediumSegmentedSortPolicy< + + BLOCK_THREADS, + + // Small policy + cub::AgentSubWarpMergeSortPolicy<4, // Threads per segment + ITEMS_PER_SMALL_THREAD, + WarpLoadAlgorithm::WARP_LOAD_DIRECT, + CacheLoadModifier::LOAD_DEFAULT>, + + // Medium policy + cub::AgentSubWarpMergeSortPolicy<32, // Threads per segment + ITEMS_PER_MEDIUM_THREAD, + WarpLoadAlgorithm::WARP_LOAD_DIRECT, + CacheLoadModifier::LOAD_DEFAULT>>; + }; + + struct Policy620 : ChainedPolicy<620, Policy620, Policy610> + { + constexpr static int BLOCK_THREADS = 256; + constexpr static int RADIX_BITS = sizeof(KeyT) > 1 ? 5 : 4; + constexpr static int PARTITIONING_THRESHOLD = 500; + + using LargeSegmentPolicy = + AgentRadixSortDownsweepPolicy; + + constexpr static int ITEMS_PER_SMALL_THREAD = + Nominal4BItemsToItems(9); + + constexpr static int ITEMS_PER_MEDIUM_THREAD = + Nominal4BItemsToItems(9); + + using SmallAndMediumSegmentedSortPolicyT = + AgentSmallAndMediumSegmentedSortPolicy< + + BLOCK_THREADS, + + // Small policy + cub::AgentSubWarpMergeSortPolicy<4, // Threads per segment + ITEMS_PER_SMALL_THREAD, + WarpLoadAlgorithm::WARP_LOAD_DIRECT, + CacheLoadModifier::LOAD_DEFAULT>, + + // Medium policy + cub::AgentSubWarpMergeSortPolicy<32, // Threads per segment + ITEMS_PER_MEDIUM_THREAD, + WarpLoadAlgorithm::WARP_LOAD_DIRECT, + CacheLoadModifier::LOAD_DEFAULT>>; + }; + + struct Policy700 : ChainedPolicy<700, Policy700, Policy620> + { + constexpr static int BLOCK_THREADS = 256; + constexpr static int RADIX_BITS = sizeof(KeyT) > 1 ? 6 : 4; + constexpr static int PARTITIONING_THRESHOLD = 500; + + using LargeSegmentPolicy = + AgentRadixSortDownsweepPolicy; + + constexpr static int ITEMS_PER_SMALL_THREAD = + Nominal4BItemsToItems(7); + + constexpr static int ITEMS_PER_MEDIUM_THREAD = + Nominal4BItemsToItems(KEYS_ONLY ? 11 : 7); + + using SmallAndMediumSegmentedSortPolicyT = + AgentSmallAndMediumSegmentedSortPolicy< + + BLOCK_THREADS, + + // Small policy + cub::AgentSubWarpMergeSortPolicy<(KEYS_ONLY ? 4 : 8), // Threads per segment + ITEMS_PER_SMALL_THREAD, + WarpLoadAlgorithm::WARP_LOAD_DIRECT, + CacheLoadModifier::LOAD_DEFAULT>, + + // Medium policy + cub::AgentSubWarpMergeSortPolicy<32, // Threads per segment + ITEMS_PER_MEDIUM_THREAD, + WarpLoadAlgorithm::WARP_LOAD_DIRECT, + CacheLoadModifier::LOAD_DEFAULT>>; + }; + + struct Policy800 : ChainedPolicy<800, Policy800, Policy700> + { + constexpr static int BLOCK_THREADS = 256; + constexpr static int PARTITIONING_THRESHOLD = 500; + + using LargeSegmentPolicy = + cub::AgentRadixSortDownsweepPolicy 1) ? 6 : 4>; + + constexpr static int ITEMS_PER_SMALL_THREAD = + Nominal4BItemsToItems(9); + + constexpr static int ITEMS_PER_MEDIUM_THREAD = + Nominal4BItemsToItems(KEYS_ONLY ? 7 : 11); + + using SmallAndMediumSegmentedSortPolicyT = + AgentSmallAndMediumSegmentedSortPolicy< + + BLOCK_THREADS, + + // Small policy + cub::AgentSubWarpMergeSortPolicy<(KEYS_ONLY ? 4 : 2), // Threads per segment + ITEMS_PER_SMALL_THREAD, + WarpLoadAlgorithm::WARP_LOAD_TRANSPOSE, + CacheLoadModifier::LOAD_DEFAULT>, + + // Medium policy + cub::AgentSubWarpMergeSortPolicy<32, // Threads per segment + ITEMS_PER_MEDIUM_THREAD, + WarpLoadAlgorithm::WARP_LOAD_TRANSPOSE, + CacheLoadModifier::LOAD_DEFAULT>>; + }; + + struct Policy860 : ChainedPolicy<860, Policy860, Policy800> + { + constexpr static int BLOCK_THREADS = 256; + constexpr static int PARTITIONING_THRESHOLD = 500; + + using LargeSegmentPolicy = + cub::AgentRadixSortDownsweepPolicy 1) ? 6 : 4>; + + constexpr static bool LARGE_ITEMS = sizeof(DominantT) > 4; + + constexpr static int ITEMS_PER_SMALL_THREAD = + Nominal4BItemsToItems(LARGE_ITEMS ? 7 : 9); + + constexpr static int ITEMS_PER_MEDIUM_THREAD = + Nominal4BItemsToItems(LARGE_ITEMS ? 9 : 7); + + using SmallAndMediumSegmentedSortPolicyT = + AgentSmallAndMediumSegmentedSortPolicy< + + BLOCK_THREADS, + + // Small policy + cub::AgentSubWarpMergeSortPolicy<(LARGE_ITEMS ? 8 : 2), // Threads per segment + ITEMS_PER_SMALL_THREAD, + WarpLoadAlgorithm::WARP_LOAD_TRANSPOSE, + CacheLoadModifier::LOAD_LDG>, + + // Medium policy + cub::AgentSubWarpMergeSortPolicy<16, // Threads per segment + ITEMS_PER_MEDIUM_THREAD, + WarpLoadAlgorithm::WARP_LOAD_TRANSPOSE, + CacheLoadModifier::LOAD_LDG>>; + }; + + /// MaxPolicy + using MaxPolicy = Policy860; +}; + +template > +struct DispatchSegmentedSort : SelectedPolicy +{ + static constexpr int KEYS_ONLY = std::is_same::value; + + struct LargeSegmentsSelectorT + { + OffsetT value{}; + BeginOffsetIteratorT d_offset_begin{}; + EndOffsetIteratorT d_offset_end{}; + + __host__ __device__ __forceinline__ + LargeSegmentsSelectorT(OffsetT value, + BeginOffsetIteratorT d_offset_begin, + EndOffsetIteratorT d_offset_end) + : value(value) + , d_offset_begin(d_offset_begin) + , d_offset_end(d_offset_end) + {} + + __host__ __device__ __forceinline__ bool + operator()(unsigned int segment_id) const + { + const OffsetT segment_size = d_offset_end[segment_id] - + d_offset_begin[segment_id]; + return segment_size > value; + } + }; + + struct SmallSegmentsSelectorT + { + OffsetT value{}; + BeginOffsetIteratorT d_offset_begin{}; + EndOffsetIteratorT d_offset_end{}; + + __host__ __device__ __forceinline__ + SmallSegmentsSelectorT(OffsetT value, + BeginOffsetIteratorT d_offset_begin, + EndOffsetIteratorT d_offset_end) + : value(value) + , d_offset_begin(d_offset_begin) + , d_offset_end(d_offset_end) + {} + + __host__ __device__ __forceinline__ bool + operator()(unsigned int segment_id) const + { + const OffsetT segment_size = d_offset_end[segment_id] - + d_offset_begin[segment_id]; + return segment_size < value; + } + }; + + // Partition selects large and small groups. The middle group is not selected. + constexpr static std::size_t num_selected_groups = 2; + + /** + * Device-accessible allocation of temporary storage. When `nullptr`, the + * required allocation size is written to @p temp_storage_bytes and no work + * is done. + */ + void *d_temp_storage; + + /// Reference to size in bytes of @p d_temp_storage allocation + std::size_t &temp_storage_bytes; + + /** + * Double-buffer whose current buffer contains the unsorted input keys and, + * upon return, is updated to point to the sorted output keys + */ + DoubleBuffer &d_keys; + + /** + * Double-buffer whose current buffer contains the unsorted input values and, + * upon return, is updated to point to the sorted output values + */ + DoubleBuffer &d_values; + + /// Number of items to sort + OffsetT num_items; + + /// The number of segments that comprise the sorting data + int num_segments; + + /** + * Random-access input iterator to the sequence of beginning offsets of length + * @p num_segments, such that `d_begin_offsets[i]` is the first element of the + * ith data segment in `d_keys_*` and `d_values_*` + */ + BeginOffsetIteratorT d_begin_offsets; + + /** + * Random-access input iterator to the sequence of ending offsets of length + * @p num_segments, such that d_end_offsets[i]-1 is the last element + * of the ith data segment in `d_keys_*` and + * `d_values_*`. If `d_end_offsets[i]-1 <= d_begin_offsets[i]`, + * the ith is considered empty. + */ + EndOffsetIteratorT d_end_offsets; + + /// Whether is okay to overwrite source buffers + bool is_overwrite_okay; + + /// CUDA stream to launch kernels within. + cudaStream_t stream; + + CUB_RUNTIME_FUNCTION __forceinline__ + DispatchSegmentedSort(void *d_temp_storage, + std::size_t &temp_storage_bytes, + DoubleBuffer &d_keys, + DoubleBuffer &d_values, + OffsetT num_items, + int num_segments, + BeginOffsetIteratorT d_begin_offsets, + EndOffsetIteratorT d_end_offsets, + bool is_overwrite_okay, + cudaStream_t stream) + : d_temp_storage(d_temp_storage) + , temp_storage_bytes(temp_storage_bytes) + , d_keys(d_keys) + , d_values(d_values) + , num_items(num_items) + , num_segments(num_segments) + , d_begin_offsets(d_begin_offsets) + , d_end_offsets(d_end_offsets) + , is_overwrite_okay(is_overwrite_okay) + , stream(stream) + {} + + CUB_DETAIL_RUNTIME_DEBUG_SYNC_IS_NOT_SUPPORTED + CUB_RUNTIME_FUNCTION __forceinline__ + DispatchSegmentedSort(void *d_temp_storage, + std::size_t &temp_storage_bytes, + DoubleBuffer &d_keys, + DoubleBuffer &d_values, + OffsetT num_items, + int num_segments, + BeginOffsetIteratorT d_begin_offsets, + EndOffsetIteratorT d_end_offsets, + bool is_overwrite_okay, + cudaStream_t stream, + bool debug_synchronous) + : d_temp_storage(d_temp_storage) + , temp_storage_bytes(temp_storage_bytes) + , d_keys(d_keys) + , d_values(d_values) + , num_items(num_items) + , num_segments(num_segments) + , d_begin_offsets(d_begin_offsets) + , d_end_offsets(d_end_offsets) + , is_overwrite_okay(is_overwrite_okay) + , stream(stream) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + } + + template + CUB_RUNTIME_FUNCTION __forceinline__ cudaError_t Invoke() + { + using MaxPolicyT = typename DispatchSegmentedSort::MaxPolicy; + using LargeSegmentPolicyT = typename ActivePolicyT::LargeSegmentPolicy; + using SmallAndMediumPolicyT = + typename ActivePolicyT::SmallAndMediumSegmentedSortPolicyT; + + static_assert( + LargeSegmentPolicyT::LOAD_MODIFIER != CacheLoadModifier::LOAD_LDG, + "The memory consistency model does not apply to texture accesses"); + + static_assert( + KEYS_ONLY + || LargeSegmentPolicyT::LOAD_ALGORITHM != BLOCK_LOAD_STRIPED + || SmallAndMediumPolicyT::MediumPolicyT::LOAD_ALGORITHM != WARP_LOAD_STRIPED + || SmallAndMediumPolicyT::SmallPolicyT::LOAD_ALGORITHM != WARP_LOAD_STRIPED, + "Striped load will make this algorithm unstable"); + + static_assert( + SmallAndMediumPolicyT::MediumPolicyT::STORE_ALGORITHM != WARP_STORE_STRIPED + || SmallAndMediumPolicyT::SmallPolicyT::STORE_ALGORITHM != WARP_STORE_STRIPED, + "Striped stores will produce unsorted results"); + + constexpr int radix_bits = LargeSegmentPolicyT::RADIX_BITS; + + cudaError error = cudaSuccess; + + do + { + //------------------------------------------------------------------------ + // Prepare temporary storage layout + //------------------------------------------------------------------------ + + const bool partition_segments = num_segments > + ActivePolicyT::PARTITIONING_THRESHOLD; + + cub::detail::temporary_storage::layout<5> temporary_storage_layout; + + auto keys_slot = temporary_storage_layout.get_slot(0); + auto values_slot = temporary_storage_layout.get_slot(1); + auto large_and_medium_partitioning_slot = temporary_storage_layout.get_slot(2); + auto small_partitioning_slot = temporary_storage_layout.get_slot(3); + auto group_sizes_slot = temporary_storage_layout.get_slot(4); + + auto keys_allocation = keys_slot->create_alias(); + auto values_allocation = values_slot->create_alias(); + + if (!is_overwrite_okay) + { + keys_allocation.grow(num_items); + + if (!KEYS_ONLY) + { + values_allocation.grow(num_items); + } + } + + auto large_and_medium_segments_indices = + large_and_medium_partitioning_slot->create_alias(); + auto small_segments_indices = + small_partitioning_slot->create_alias(); + auto group_sizes = group_sizes_slot->create_alias(); + + std::size_t three_way_partition_temp_storage_bytes {}; + + LargeSegmentsSelectorT large_segments_selector( + SmallAndMediumPolicyT::MediumPolicyT::ITEMS_PER_TILE, + d_begin_offsets, + d_end_offsets); + + SmallSegmentsSelectorT small_segments_selector( + SmallAndMediumPolicyT::SmallPolicyT::ITEMS_PER_TILE + 1, + d_begin_offsets, + d_end_offsets); + + auto device_partition_temp_storage = + keys_slot->create_alias(); + + if (partition_segments) + { + large_and_medium_segments_indices.grow(num_segments); + small_segments_indices.grow(num_segments); + group_sizes.grow(num_selected_groups); + + auto medium_indices_iterator = + THRUST_NS_QUALIFIER::make_reverse_iterator( + large_and_medium_segments_indices.get()); + + cub::DevicePartition::If( + nullptr, + three_way_partition_temp_storage_bytes, + THRUST_NS_QUALIFIER::counting_iterator(0), + large_and_medium_segments_indices.get(), + small_segments_indices.get(), + medium_indices_iterator, + group_sizes.get(), + num_segments, + large_segments_selector, + small_segments_selector, + stream); + + device_partition_temp_storage.grow( + three_way_partition_temp_storage_bytes); + } + + if (d_temp_storage == nullptr) + { + temp_storage_bytes = temporary_storage_layout.get_size(); + + // Return if the caller is simply requesting the size of the storage + // allocation + break; + } + + if (num_items == 0 || num_segments == 0) + { + break; + } + + if (CubDebug( + error = temporary_storage_layout.map_to_buffer(d_temp_storage, + temp_storage_bytes))) + { + break; + } + + //------------------------------------------------------------------------ + // Sort + //------------------------------------------------------------------------ + + const bool is_num_passes_odd = GetNumPasses(radix_bits) & 1; + + /** + * This algorithm sorts segments that don't fit into shared memory with + * the in-global-memory radix sort. Radix sort splits key representation + * into multiple "digits". Each digit is RADIX_BITS wide. The algorithm + * iterates over these digits. Each of these iterations consists of a + * couple of stages. The first stage computes a histogram for a current + * digit in each segment key. This histogram helps to determine the + * starting position of the keys group with a similar digit. + * For example: + * keys_digits = [ 1, 0, 0, 1 ] + * digit_prefix = [ 0, 2 ] + * The second stage checks the keys again and increments the prefix to + * determine the final position of the key: + * + * expression | key | idx | result + * ----------------------------------- | ----- | ------- | -------------- + * result[prefix[keys[0]]++] = keys[0] | 1 | 2 | [ ?, ?, 1, ? ] + * result[prefix[keys[1]]++] = keys[0] | 0 | 0 | [ 0, ?, 1, ? ] + * result[prefix[keys[2]]++] = keys[0] | 0 | 1 | [ 0, 0, 1, ? ] + * result[prefix[keys[3]]++] = keys[0] | 1 | 3 | [ 0, 0, 1, 1 ] + * + * If the resulting memory is aliased to the input one, we'll face the + * following issues: + * + * input | key | idx | result/input | issue + * -------------- | ----- | ------- | ---------------- | ---------------- + * [ 1, 0, 0, 1 ] | 1 | 2 | [ 1, 0, 1, 1 ] | overwrite keys[2] + * [ 1, 0, 1, 1 ] | 0 | 0 | [ 0, 0, 1, 1 ] | + * [ 0, 0, 1, 1 ] | 1 | 3 | [ 0, 0, 1, 1 ] | extra key + * [ 0, 0, 1, 1 ] | 1 | 4 | [ 0, 0, 1, 1 ] 1 | OOB access + * + * To avoid these issues, we have to use extra memory. The extra memory + * holds temporary storage for writing intermediate results of each stage. + * Since we iterate over digits in keys, we potentially need: + * `sizeof(KeyT) * num_items * DivideAndRoundUp(sizeof(KeyT),RADIX_BITS)` + * auxiliary memory bytes. To reduce the auxiliary memory storage + * requirements, the algorithm relies on a double buffer facility. The + * idea behind it is in swapping destination and source buffers at each + * iteration. This way, we can use only two buffers. One of these buffers + * can be the final algorithm output destination. Therefore, only one + * auxiliary array is needed. Depending on the number of iterations, we + * can initialize the double buffer so that the algorithm output array + * will match the double buffer result one at the final iteration. + * A user can provide this algorithm with a double buffer straightaway to + * further reduce the auxiliary memory requirements. `is_overwrite_okay` + * indicates this use case. + */ + detail::device_double_buffer d_keys_double_buffer( + (is_overwrite_okay || is_num_passes_odd) ? d_keys.Alternate() : keys_allocation.get(), + (is_overwrite_okay) ? d_keys.Current() : (is_num_passes_odd) ? keys_allocation.get() : d_keys.Alternate()); + + detail::device_double_buffer d_values_double_buffer( + (is_overwrite_okay || is_num_passes_odd) ? d_values.Alternate() : values_allocation.get(), + (is_overwrite_okay) ? d_values.Current() : (is_num_passes_odd) ? values_allocation.get() : d_values.Alternate()); + + if (partition_segments) + { + // Partition input segments into size groups and assign specialized + // kernels for each of them. + error = + SortWithPartitioning( + DeviceSegmentedSortKernelLarge, + DeviceSegmentedSortKernelSmall, + three_way_partition_temp_storage_bytes, + d_keys_double_buffer, + d_values_double_buffer, + large_segments_selector, + small_segments_selector, + device_partition_temp_storage, + large_and_medium_segments_indices, + small_segments_indices, + group_sizes); + } + else + { + // If there are not enough segments, there's no reason to spend time + // on extra partitioning steps. + + error = SortWithoutPartitioning( + DeviceSegmentedSortFallbackKernel, + d_keys_double_buffer, + d_values_double_buffer); + } + + d_keys.selector = GetFinalSelector(d_keys.selector, radix_bits); + d_values.selector = GetFinalSelector(d_values.selector, radix_bits); + + } while (false); + + return error; + } + + CUB_RUNTIME_FUNCTION __forceinline__ static cudaError_t + Dispatch(void *d_temp_storage, + std::size_t &temp_storage_bytes, + DoubleBuffer &d_keys, + DoubleBuffer &d_values, + OffsetT num_items, + int num_segments, + BeginOffsetIteratorT d_begin_offsets, + EndOffsetIteratorT d_end_offsets, + bool is_overwrite_okay, + cudaStream_t stream) + { + using MaxPolicyT = typename DispatchSegmentedSort::MaxPolicy; + + cudaError error = cudaSuccess; + + do + { + // Get PTX version + int ptx_version = 0; + if (CubDebug(error = PtxVersion(ptx_version))) + { + break; + } + + // Create dispatch functor + DispatchSegmentedSort dispatch(d_temp_storage, + temp_storage_bytes, + d_keys, + d_values, + num_items, + num_segments, + d_begin_offsets, + d_end_offsets, + is_overwrite_okay, + stream); + + // Dispatch to chained policy + if (CubDebug(error = MaxPolicyT::Invoke(ptx_version, dispatch))) + { + break; + } + } while (false); + + return error; + } + + CUB_DETAIL_RUNTIME_DEBUG_SYNC_IS_NOT_SUPPORTED + CUB_RUNTIME_FUNCTION __forceinline__ static cudaError_t + Dispatch(void *d_temp_storage, + std::size_t &temp_storage_bytes, + DoubleBuffer &d_keys, + DoubleBuffer &d_values, + OffsetT num_items, + int num_segments, + BeginOffsetIteratorT d_begin_offsets, + EndOffsetIteratorT d_end_offsets, + bool is_overwrite_okay, + cudaStream_t stream, + bool debug_synchronous) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + + return Dispatch(d_temp_storage, + temp_storage_bytes, + d_keys, + d_values, + num_items, + num_segments, + d_begin_offsets, + d_end_offsets, + is_overwrite_okay, + stream); + } + +private: + CUB_RUNTIME_FUNCTION __forceinline__ + int GetNumPasses(int radix_bits) + { + const int byte_size = 8; + const int num_bits = sizeof(KeyT) * byte_size; + const int num_passes = DivideAndRoundUp(num_bits, radix_bits); + return num_passes; + } + + CUB_RUNTIME_FUNCTION __forceinline__ + int GetFinalSelector(int selector, int radix_bits) + { + // Sorted data always ends up in the other vector + if (!is_overwrite_okay) + { + return (selector + 1) & 1; + } + + return (selector + GetNumPasses(radix_bits)) & 1; + } + + template + CUB_RUNTIME_FUNCTION __forceinline__ + T* GetFinalOutput(int radix_bits, + DoubleBuffer &buffer) + { + const int final_selector = GetFinalSelector(buffer.selector, radix_bits); + return buffer.d_buffers[final_selector]; + } + + template + CUB_RUNTIME_FUNCTION __forceinline__ cudaError_t + SortWithPartitioning( + LargeKernelT large_kernel, + SmallKernelT small_kernel, + std::size_t three_way_partition_temp_storage_bytes, + cub::detail::device_double_buffer &d_keys_double_buffer, + cub::detail::device_double_buffer &d_values_double_buffer, + LargeSegmentsSelectorT &large_segments_selector, + SmallSegmentsSelectorT &small_segments_selector, + cub::detail::temporary_storage::alias &device_partition_temp_storage, + cub::detail::temporary_storage::alias &large_and_medium_segments_indices, + cub::detail::temporary_storage::alias &small_segments_indices, + cub::detail::temporary_storage::alias &group_sizes) + { + cudaError_t error = cudaSuccess; + + auto medium_indices_iterator = + THRUST_NS_QUALIFIER::make_reverse_iterator( + large_and_medium_segments_indices.get() + num_segments); + + error = cub::DevicePartition::If( + device_partition_temp_storage.get(), + three_way_partition_temp_storage_bytes, + THRUST_NS_QUALIFIER::counting_iterator(0), + large_and_medium_segments_indices.get(), + small_segments_indices.get(), + medium_indices_iterator, + group_sizes.get(), + num_segments, + large_segments_selector, + small_segments_selector, + stream); + if (CubDebug(error)) + { + return error; + } + + // The device path is only used (and only compiles) when CDP is enabled. + // It's defined in a macro since we can't put `#ifdef`s inside of + // `NV_IF_TARGET`. +#ifndef CUB_RDC_ENABLED + +#define CUB_TEMP_DEVICE_CODE + +#else // CUB_RDC_ENABLED + +#define CUB_TEMP_DEVICE_CODE \ + using MaxPolicyT = typename DispatchSegmentedSort::MaxPolicy; \ + error = \ + THRUST_NS_QUALIFIER::cuda_cub::launcher::triple_chevron(1, 1, 0, stream) \ + .doit(DeviceSegmentedSortContinuationKernel, \ + large_kernel, \ + small_kernel, \ + num_segments, \ + d_keys.Current(), \ + GetFinalOutput(LargeSegmentPolicyT::RADIX_BITS, d_keys), \ + d_keys_double_buffer, \ + d_values.Current(), \ + GetFinalOutput(LargeSegmentPolicyT::RADIX_BITS, d_values), \ + d_values_double_buffer, \ + d_begin_offsets, \ + d_end_offsets, \ + group_sizes.get(), \ + large_and_medium_segments_indices.get(), \ + small_segments_indices.get()); \ + \ + if (CubDebug(error)) \ + { \ + return error; \ + } \ + \ + error = detail::DebugSyncStream(stream); \ + if (CubDebug(error)) \ + { \ + return error; \ + } + +#endif // CUB_RDC_ENABLED + + // Clang format mangles some of this NV_IF_TARGET block + // clang-format off + NV_IF_TARGET( + NV_IS_HOST, + ( + unsigned int h_group_sizes[num_selected_groups]; + + if (CubDebug(error = cudaMemcpyAsync(h_group_sizes, + group_sizes.get(), + num_selected_groups * + sizeof(unsigned int), + cudaMemcpyDeviceToHost, + stream))) + { + return error; + } + + if (CubDebug(error = SyncStream(stream))) + { + return error; + } + + error = DeviceSegmentedSortContinuation( + large_kernel, + small_kernel, + num_segments, + d_keys.Current(), + GetFinalOutput(LargeSegmentPolicyT::RADIX_BITS, d_keys), + d_keys_double_buffer, + d_values.Current(), + GetFinalOutput(LargeSegmentPolicyT::RADIX_BITS, d_values), + d_values_double_buffer, + d_begin_offsets, + d_end_offsets, + h_group_sizes, + large_and_medium_segments_indices.get(), + small_segments_indices.get(), + stream);), + // NV_IS_DEVICE: + (CUB_TEMP_DEVICE_CODE)); + // clang-format on + +#undef CUB_TEMP_DEVICE_CODE + + return error; + } + + template + CUB_RUNTIME_FUNCTION __forceinline__ cudaError_t SortWithoutPartitioning( + FallbackKernelT fallback_kernel, + cub::detail::device_double_buffer &d_keys_double_buffer, + cub::detail::device_double_buffer &d_values_double_buffer) + { + cudaError_t error = cudaSuccess; + + const auto blocks_in_grid = static_cast(num_segments); + const auto threads_in_block = + static_cast(LargeSegmentPolicyT::BLOCK_THREADS); + + // Log kernel configuration + #ifdef CUB_DETAIL_DEBUG_ENABLE_LOG + _CubLog("Invoking DeviceSegmentedSortFallbackKernel<<<%d, %d, " + "0, %lld>>>(), %d items per thread, bit_grain %d\n", + blocks_in_grid, + threads_in_block, + (long long)stream, + LargeSegmentPolicyT::ITEMS_PER_THREAD, + LargeSegmentPolicyT::RADIX_BITS); + #endif + + // Invoke fallback kernel + THRUST_NS_QUALIFIER::cuda_cub::launcher::triple_chevron(blocks_in_grid, + threads_in_block, + 0, + stream) + .doit(fallback_kernel, + d_keys.Current(), + GetFinalOutput(LargeSegmentPolicyT::RADIX_BITS, d_keys), + d_keys_double_buffer, + d_values.Current(), + GetFinalOutput(LargeSegmentPolicyT::RADIX_BITS, d_values), + d_values_double_buffer, + d_begin_offsets, + d_end_offsets); + + // Check for failure to launch + if (CubDebug(error = cudaPeekAtLastError())) + { + return error; + } + + // Sync the stream if specified to flush runtime errors + error = detail::DebugSyncStream(stream); + if (CubDebug(error)) + { + return error; + } + + return error; + } +}; + + +CUB_NAMESPACE_END diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/device/dispatch/dispatch_select_if.cuh b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/device/dispatch/dispatch_select_if.cuh new file mode 100644 index 0000000000000000000000000000000000000000..a2f3536ed2e8f48592d4c3782343f4ba3f5b25b7 --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/device/dispatch/dispatch_select_if.cuh @@ -0,0 +1,600 @@ +/****************************************************************************** + * Copyright (c) 2011, Duane Merrill. All rights reserved. + * Copyright (c) 2011-2018, NVIDIA CORPORATION. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the NVIDIA CORPORATION nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ******************************************************************************/ + +/** + * @file + * cub::DeviceSelect provides device-wide, parallel operations for selecting items from sequences + * of data items residing within device-accessible memory. + */ + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include + +#include + +CUB_NAMESPACE_BEGIN + +/****************************************************************************** + * Kernel entry points + *****************************************************************************/ + +/** + * Select kernel entry point (multi-block) + * + * Performs functor-based selection if SelectOpT functor type != NullType + * Otherwise performs flag-based selection if FlagsInputIterator's value type != NullType + * Otherwise performs discontinuity selection (keep unique) + * + * @tparam InputIteratorT + * Random-access input iterator type for reading input items + * + * @tparam FlagsInputIteratorT + * Random-access input iterator type for reading selection flags (NullType* if a selection functor + * or discontinuity flagging is to be used for selection) + * + * @tparam SelectedOutputIteratorT + * Random-access output iterator type for writing selected items + * + * @tparam NumSelectedIteratorT + * Output iterator type for recording the number of items selected + * + * @tparam ScanTileStateT + * Tile status interface type + * + * @tparam SelectOpT + * Selection operator type (NullType if selection flags or discontinuity flagging is + * to be used for selection) + * + * @tparam EqualityOpT + * Equality operator type (NullType if selection functor or selection flags is + * to be used for selection) + * + * @tparam OffsetT + * Signed integer type for global offsets + * + * @tparam KEEP_REJECTS + * Whether or not we push rejected items to the back of the output + * + * @param[in] d_in + * Pointer to the input sequence of data items + * + * @param[in] d_flags + * Pointer to the input sequence of selection flags (if applicable) + * + * @param[out] d_selected_out + * Pointer to the output sequence of selected data items + * + * @param[out] d_num_selected_out + * Pointer to the total number of items selected (i.e., length of \p d_selected_out) + * + * @param[in] tile_status + * Tile status interface + * + * @param[in] select_op + * Selection operator + * + * @param[in] equality_op + * Equality operator + * + * @param[in] num_items + * Total number of input items (i.e., length of \p d_in) + * + * @param[in] num_tiles + * Total number of tiles for the entire problem + */ +template +__launch_bounds__(int(ChainedPolicyT::ActivePolicy::SelectIfPolicyT::BLOCK_THREADS)) __global__ + void DeviceSelectSweepKernel(InputIteratorT d_in, + FlagsInputIteratorT d_flags, + SelectedOutputIteratorT d_selected_out, + NumSelectedIteratorT d_num_selected_out, + ScanTileStateT tile_status, + SelectOpT select_op, + EqualityOpT equality_op, + OffsetT num_items, + int num_tiles) +{ + using AgentSelectIfPolicyT = typename ChainedPolicyT::ActivePolicy::SelectIfPolicyT; + + // Thread block type for selecting data from input tiles + using AgentSelectIfT = AgentSelectIf; + + // Shared memory for AgentSelectIf + __shared__ typename AgentSelectIfT::TempStorage temp_storage; + + // Process tiles + AgentSelectIfT(temp_storage, d_in, d_flags, d_selected_out, select_op, equality_op, num_items).ConsumeRange( + num_tiles, + tile_status, + d_num_selected_out); +} + + +/****************************************************************************** + * Dispatch + ******************************************************************************/ + +/** + * Utility class for dispatching the appropriately-tuned kernels for DeviceSelect + * + * @tparam InputIteratorT + * Random-access input iterator type for reading input items + * + * @tparam FlagsInputIteratorT + * Random-access input iterator type for reading selection flags + * (NullType* if a selection functor or discontinuity flagging is to be used for selection) + * + * @tparam SelectedOutputIteratorT + * Random-access output iterator type for writing selected items + * + * @tparam NumSelectedIteratorT + * Output iterator type for recording the number of items selected + * + * @tparam SelectOpT + * Selection operator type (NullType if selection flags or discontinuity flagging is + * to be used for selection) + * + * @tparam EqualityOpT + * Equality operator type (NullType if selection functor or selection flags is to + * be used for selection) + * + * @tparam OffsetT + * Signed integer type for global offsets + * + * @tparam KEEP_REJECTS + * Whether or not we push rejected items to the back of the output + */ +template , + cub::detail::value_t, + OffsetT, + MayAlias, + KEEP_REJECTS>> +struct DispatchSelectIf : SelectedPolicy +{ + /****************************************************************************** + * Types and constants + ******************************************************************************/ + + // Tile status descriptor interface type + using ScanTileStateT = ScanTileState; + + static constexpr int INIT_KERNEL_THREADS = 128; + + /// Device-accessible allocation of temporary storage. + /// When `nullptr`, the required allocation size is written to `temp_storage_bytes` + /// and no work is done. + void* d_temp_storage; + + /// Reference to size in bytes of `d_temp_storage` allocation + size_t& temp_storage_bytes; + + /// Pointer to the input sequence of data items + InputIteratorT d_in; + + /// Pointer to the input sequence of selection flags (if applicable) + FlagsInputIteratorT d_flags; + + /// Pointer to the output sequence of selected data items + SelectedOutputIteratorT d_selected_out; + + /// Pointer to the total number of items selected (i.e., length of `d_selected_out`) + NumSelectedIteratorT d_num_selected_out; + + /// Selection operator + SelectOpT select_op; + + /// Equality operator + EqualityOpT equality_op; + + /// Total number of input items (i.e., length of `d_in`) + OffsetT num_items; + + /// CUDA stream to launch kernels within. Default is stream0. + cudaStream_t stream; + + int ptx_version; + + /** + * @param d_temp_storage + * Device-accessible allocation of temporary storage. + * When `nullptr`, the required allocation size is written to `temp_storage_bytes` + * and no work is done. + * + * @param temp_storage_bytes + * Reference to size in bytes of `d_temp_storage` allocation + * + * @param d_in + * Pointer to the input sequence of data items + * + * @param d_flags + * Pointer to the input sequence of selection flags (if applicable) + * + * @param d_selected_out + * Pointer to the output sequence of selected data items + * + * @param d_num_selected_out + * Pointer to the total number of items selected (i.e., length of `d_selected_out`) + * + * @param select_op + * Selection operator + * + * @param equality_op + * Equality operator + * + * @param num_items + * Total number of input items (i.e., length of `d_in`) + * + * @param stream + * CUDA stream to launch kernels within. Default is stream0. + */ + CUB_RUNTIME_FUNCTION __forceinline__ DispatchSelectIf(void *d_temp_storage, + size_t &temp_storage_bytes, + InputIteratorT d_in, + FlagsInputIteratorT d_flags, + SelectedOutputIteratorT d_selected_out, + NumSelectedIteratorT d_num_selected_out, + SelectOpT select_op, + EqualityOpT equality_op, + OffsetT num_items, + cudaStream_t stream, + int ptx_version) + : d_temp_storage(d_temp_storage) + , temp_storage_bytes(temp_storage_bytes) + , d_in(d_in) + , d_flags(d_flags) + , d_selected_out(d_selected_out) + , d_num_selected_out(d_num_selected_out) + , select_op(select_op) + , equality_op(equality_op) + , num_items(num_items) + , stream(stream) + , ptx_version(ptx_version) + {} + + /****************************************************************************** + * Dispatch entrypoints + ******************************************************************************/ + + /** + * Internal dispatch routine for computing a device-wide selection using the + * specified kernel functions. + */ + template + CUB_RUNTIME_FUNCTION __forceinline__ cudaError_t Invoke(ScanInitKernelPtrT scan_init_kernel, + SelectIfKernelPtrT select_if_kernel) + { + cudaError error = cudaSuccess; + + const int block_threads = ActivePolicyT::SelectIfPolicyT::BLOCK_THREADS; + const int items_per_thread = ActivePolicyT::SelectIfPolicyT::ITEMS_PER_THREAD; + const int tile_size = block_threads * items_per_thread; + + do + { + // Get device ordinal + int device_ordinal; + if (CubDebug(error = cudaGetDevice(&device_ordinal))) + { + break; + } + + // Number of input tiles + int num_tiles = static_cast(cub::DivideAndRoundUp(num_items, tile_size)); + + // Specify temporary storage allocation requirements + size_t allocation_sizes[1]; + + // bytes needed for tile status descriptors + if (CubDebug(error = ScanTileStateT::AllocationSize(num_tiles, allocation_sizes[0]))) + { + break; + } + + // Compute allocation pointers into the single storage blob (or compute the necessary size of the blob) + void* allocations[1] = {}; + if (CubDebug(error = AliasTemporaries(d_temp_storage, temp_storage_bytes, allocations, allocation_sizes))) + { + break; + } + + if (d_temp_storage == nullptr) + { + // Return if the caller is simply requesting the size of the storage allocation + break; + } + + // Construct the tile status interface + ScanTileStateT tile_status; + if (CubDebug(error = tile_status.Init(num_tiles, allocations[0], allocation_sizes[0]))) + { + break; + } + + // Log scan_init_kernel configuration + int init_grid_size = CUB_MAX(1, cub::DivideAndRoundUp(num_tiles, INIT_KERNEL_THREADS)); + + #ifdef CUB_DETAIL_DEBUG_ENABLE_LOG + _CubLog("Invoking scan_init_kernel<<<%d, %d, 0, %lld>>>()\n", init_grid_size, INIT_KERNEL_THREADS, (long long) stream); + #endif + + // Invoke scan_init_kernel to initialize tile descriptors + THRUST_NS_QUALIFIER::cuda_cub::launcher::triple_chevron( + init_grid_size, INIT_KERNEL_THREADS, 0, stream + ).doit(scan_init_kernel, + tile_status, + num_tiles, + d_num_selected_out); + + // Check for failure to launch + if (CubDebug(error = cudaPeekAtLastError())) + { + break; + } + + // Sync the stream if specified to flush runtime errors + error = detail::DebugSyncStream(stream); + if (CubDebug(error)) + { + break; + } + + // Return if empty problem + if (num_items == 0) + { + break; + } + + // Get max x-dimension of grid + int max_dim_x; + if (CubDebug(error = cudaDeviceGetAttribute(&max_dim_x, cudaDevAttrMaxGridDimX, device_ordinal))) + { + break; + } + + // Get grid size for scanning tiles + dim3 scan_grid_size; + scan_grid_size.z = 1; + scan_grid_size.y = cub::DivideAndRoundUp(num_tiles, max_dim_x); + scan_grid_size.x = CUB_MIN(num_tiles, max_dim_x); + + // Log select_if_kernel configuration + #ifdef CUB_DETAIL_DEBUG_ENABLE_LOG + { + // Get SM occupancy for select_if_kernel + int range_select_sm_occupancy; + if (CubDebug(error = MaxSmOccupancy(range_select_sm_occupancy, // out + select_if_kernel, + block_threads))) + { + break; + } + + _CubLog("Invoking select_if_kernel<<<{%d,%d,%d}, %d, 0, " + "%lld>>>(), %d items per thread, %d SM occupancy\n", + scan_grid_size.x, + scan_grid_size.y, + scan_grid_size.z, + block_threads, + (long long)stream, + items_per_thread, + range_select_sm_occupancy); + } + #endif + + // Invoke select_if_kernel + THRUST_NS_QUALIFIER::cuda_cub::launcher::triple_chevron( + scan_grid_size, block_threads, 0, stream + ).doit(select_if_kernel, + d_in, + d_flags, + d_selected_out, + d_num_selected_out, + tile_status, + select_op, + equality_op, + num_items, + num_tiles); + + // Check for failure to launch + if (CubDebug(error = cudaPeekAtLastError())) + { + break; + } + + // Sync the stream if specified to flush runtime errors + error = detail::DebugSyncStream(stream); + if (CubDebug(error)) + { + break; + } + } + while (0); + + return error; + } + + template + CUB_RUNTIME_FUNCTION __forceinline__ cudaError_t Invoke() + { + using MaxPolicyT = typename SelectedPolicy::MaxPolicy; + + return Invoke(DeviceCompactInitKernel, + DeviceSelectSweepKernel); + } + + /** + * Internal dispatch routine + * + * @param d_temp_storage + * Device-accessible allocation of temporary storage. + * When `nullptr`, the required allocation size is written to `temp_storage_bytes` + * and no work is done. + * + * @param temp_storage_bytes + * Reference to size in bytes of `d_temp_storage` allocation + * + * @param d_in + * Pointer to the input sequence of data items + * + * @param d_flags + * Pointer to the input sequence of selection flags (if applicable) + * + * @param d_selected_out + * Pointer to the output sequence of selected data items + * + * @param d_num_selected_out + * Pointer to the total number of items selected (i.e., length of `d_selected_out`) + * + * @param select_op + * Selection operator + * + * @param equality_op + * Equality operator + * + * @param num_items + * Total number of input items (i.e., length of `d_in`) + * + * @param stream + * CUDA stream to launch kernels within. Default is stream0. + */ + CUB_RUNTIME_FUNCTION __forceinline__ static cudaError_t + Dispatch(void *d_temp_storage, + size_t &temp_storage_bytes, + InputIteratorT d_in, + FlagsInputIteratorT d_flags, + SelectedOutputIteratorT d_selected_out, + NumSelectedIteratorT d_num_selected_out, + SelectOpT select_op, + EqualityOpT equality_op, + OffsetT num_items, + cudaStream_t stream) + { + using MaxPolicyT = typename SelectedPolicy::MaxPolicy; + + int ptx_version = 0; + if (cudaError_t error = CubDebug(PtxVersion(ptx_version))) + { + return error; + } + + DispatchSelectIf dispatch(d_temp_storage, + temp_storage_bytes, + d_in, + d_flags, + d_selected_out, + d_num_selected_out, + select_op, + equality_op, + num_items, + stream, + ptx_version); + + return CubDebug(MaxPolicyT::Invoke(ptx_version, dispatch)); + } + + CUB_DETAIL_RUNTIME_DEBUG_SYNC_IS_NOT_SUPPORTED + CUB_RUNTIME_FUNCTION __forceinline__ + static cudaError_t Dispatch( + void* d_temp_storage, + size_t& temp_storage_bytes, + InputIteratorT d_in, + FlagsInputIteratorT d_flags, + SelectedOutputIteratorT d_selected_out, + NumSelectedIteratorT d_num_selected_out, + SelectOpT select_op, + EqualityOpT equality_op, + OffsetT num_items, + cudaStream_t stream, + bool debug_synchronous) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + + return Dispatch(d_temp_storage, + temp_storage_bytes, + d_in, + d_flags, + d_selected_out, + d_num_selected_out, + select_op, + equality_op, + num_items, + stream); + } +}; + + +CUB_NAMESPACE_END diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/device/dispatch/dispatch_unique_by_key.cuh b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/device/dispatch/dispatch_unique_by_key.cuh new file mode 100644 index 0000000000000000000000000000000000000000..07aeb59526fde1ff703431341f055f9896f72f24 --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/device/dispatch/dispatch_unique_by_key.cuh @@ -0,0 +1,444 @@ + +/****************************************************************************** + * Copyright (c) NVIDIA CORPORATION. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the NVIDIA CORPORATION nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ******************************************************************************/ + +/** + * \file + * cub::DeviceSelect::UniqueByKey provides device-wide, parallel operations for selecting unique items by key from sequences of data items residing within device-accessible memory. + */ + +#include +#include +#include +#include +#include +#include + +#include + +CUB_NAMESPACE_BEGIN + +/****************************************************************************** + * Kernel entry points + *****************************************************************************/ + +/** + * Unique by key kernel entry point (multi-block) + */ +template < + typename ChainedPolicyT, + typename KeyInputIteratorT, ///< Random-access input iterator type for keys + typename ValueInputIteratorT, ///< Random-access input iterator type for values + typename KeyOutputIteratorT, ///< Random-access output iterator type for keys + typename ValueOutputIteratorT, ///< Random-access output iterator type for values + typename NumSelectedIteratorT, ///< Output iterator type for recording the number of items selected + typename ScanTileStateT, ///< Tile status interface type + typename EqualityOpT, ///< Equality operator type + typename OffsetT> ///< Signed integer type for global offsets +__launch_bounds__ (int(ChainedPolicyT::ActivePolicy::UniqueByKeyPolicyT::BLOCK_THREADS)) +__global__ void DeviceUniqueByKeySweepKernel( + KeyInputIteratorT d_keys_in, ///< [in] Pointer to the input sequence of keys + ValueInputIteratorT d_values_in, ///< [in] Pointer to the input sequence of values + KeyOutputIteratorT d_keys_out, ///< [out] Pointer to the output sequence of selected data items + ValueOutputIteratorT d_values_out, ///< [out] Pointer to the output sequence of selected data items + NumSelectedIteratorT d_num_selected_out, ///< [out] Pointer to the total number of items selected (i.e., length of \p d_keys_out or \p d_values_out) + ScanTileStateT tile_state, ///< [in] Tile status interface + EqualityOpT equality_op, ///< [in] Equality operator + OffsetT num_items, ///< [in] Total number of input items (i.e., length of \p d_keys_in or \p d_values_in) + int num_tiles) ///< [in] Total number of tiles for the entire problem +{ + using AgentUniqueByKeyPolicyT = typename ChainedPolicyT::ActivePolicy::UniqueByKeyPolicyT; + + // Thread block type for selecting data from input tiles + using AgentUniqueByKeyT = AgentUniqueByKey; + + // Shared memory for AgentUniqueByKey + __shared__ typename AgentUniqueByKeyT::TempStorage temp_storage; + + // Process tiles + AgentUniqueByKeyT(temp_storage, d_keys_in, d_values_in, d_keys_out, d_values_out, equality_op, num_items).ConsumeRange( + num_tiles, + tile_state, + d_num_selected_out); +} + + +/****************************************************************************** + * Dispatch + ******************************************************************************/ + +/** + * Utility class for dispatching the appropriately-tuned kernels for DeviceSelect + */ +template < + typename KeyInputIteratorT, ///< Random-access input iterator type for keys + typename ValueInputIteratorT, ///< Random-access input iterator type for values + typename KeyOutputIteratorT, ///< Random-access output iterator type for keys + typename ValueOutputIteratorT, ///< Random-access output iterator type for values + typename NumSelectedIteratorT, ///< Output iterator type for recording the number of items selected + typename EqualityOpT, ///< Equality operator type + typename OffsetT, ///< Signed integer type for global offsets + typename SelectedPolicy = DeviceUniqueByKeyPolicy> +struct DispatchUniqueByKey : SelectedPolicy +{ + /****************************************************************************** + * Types and constants + ******************************************************************************/ + + enum + { + INIT_KERNEL_THREADS = 128, + }; + + // The input key and value type + using KeyT = typename std::iterator_traits::value_type; + using ValueT = typename std::iterator_traits::value_type; + + // Tile status descriptor interface type + using ScanTileStateT = ScanTileState; + + + void* d_temp_storage; ///< [in] Device-accessible allocation of temporary storage. When NULL, the required allocation size is written to \p temp_storage_bytes and no work is done. + size_t& temp_storage_bytes; ///< [in,out] Reference to size in bytes of \p d_temp_storage allocation + KeyInputIteratorT d_keys_in; ///< [in] Pointer to the input sequence of keys + ValueInputIteratorT d_values_in; ///< [in] Pointer to the input sequence of values + KeyOutputIteratorT d_keys_out; ///< [out] Pointer to the output sequence of selected data items + ValueOutputIteratorT d_values_out; ///< [out] Pointer to the output sequence of selected data items + NumSelectedIteratorT d_num_selected_out; ///< [out] Pointer to the total number of items selected (i.e., length of \p d_keys_out or \p d_values_out) + EqualityOpT equality_op; ///< [in] Equality operator + OffsetT num_items; ///< [in] Total number of input items (i.e., length of \p d_keys_in or \p d_values_in) + cudaStream_t stream; ///< [in] [optional] CUDA stream to launch kernels within. Default is stream0. + + CUB_RUNTIME_FUNCTION __forceinline__ + DispatchUniqueByKey( + void* d_temp_storage, ///< [in] Device-accessible allocation of temporary storage. When NULL, the required allocation size is written to \p temp_storage_bytes and no work is done. + size_t& temp_storage_bytes, ///< [in,out] Reference to size in bytes of \p d_temp_storage allocation + KeyInputIteratorT d_keys_in, ///< [in] Pointer to the input sequence of keys + ValueInputIteratorT d_values_in, ///< [in] Pointer to the input sequence of values + KeyOutputIteratorT d_keys_out, ///< [out] Pointer to the output sequence of selected data items + ValueOutputIteratorT d_values_out, ///< [out] Pointer to the output sequence of selected data items + NumSelectedIteratorT d_num_selected_out, ///< [out] Pointer to the total number of items selected (i.e., length of \p d_keys_out or \p d_values_out) + EqualityOpT equality_op, ///< [in] Equality operator + OffsetT num_items, ///< [in] Total number of input items (i.e., length of \p d_keys_in or \p d_values_in) + cudaStream_t stream ///< [in] [optional] CUDA stream to launch kernels within. Default is stream0. + ): + d_temp_storage(d_temp_storage), + temp_storage_bytes(temp_storage_bytes), + d_keys_in(d_keys_in), + d_values_in(d_values_in), + d_keys_out(d_keys_out), + d_values_out(d_values_out), + d_num_selected_out(d_num_selected_out), + equality_op(equality_op), + num_items(num_items), + stream(stream) + {} + + CUB_DETAIL_RUNTIME_DEBUG_SYNC_IS_NOT_SUPPORTED + CUB_RUNTIME_FUNCTION __forceinline__ + DispatchUniqueByKey( + void* d_temp_storage, + size_t& temp_storage_bytes, + KeyInputIteratorT d_keys_in, + ValueInputIteratorT d_values_in, + KeyOutputIteratorT d_keys_out, + ValueOutputIteratorT d_values_out, + NumSelectedIteratorT d_num_selected_out, + EqualityOpT equality_op, + OffsetT num_items, + cudaStream_t stream, + bool debug_synchronous + ): + d_temp_storage(d_temp_storage), + temp_storage_bytes(temp_storage_bytes), + d_keys_in(d_keys_in), + d_values_in(d_values_in), + d_keys_out(d_keys_out), + d_values_out(d_values_out), + d_num_selected_out(d_num_selected_out), + equality_op(equality_op), + num_items(num_items), + stream(stream) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + } + + + /****************************************************************************** + * Dispatch entrypoints + ******************************************************************************/ + + template + CUB_RUNTIME_FUNCTION __host__ __forceinline__ + cudaError_t Invoke(InitKernel init_kernel, ScanKernel scan_kernel) + { + using Policy = typename ActivePolicyT::UniqueByKeyPolicyT; + using UniqueByKeyAgentT = AgentUniqueByKey; + + cudaError error = cudaSuccess; + do + { + // Get device ordinal + int device_ordinal; + if (CubDebug(error = cudaGetDevice(&device_ordinal))) break; + + // Number of input tiles + int tile_size = Policy::BLOCK_THREADS * Policy::ITEMS_PER_THREAD; + int num_tiles = static_cast(cub::DivideAndRoundUp(num_items, tile_size)); + + // Size of virtual shared memory + int max_shmem = 0; + if (CubDebug( + error = cudaDeviceGetAttribute(&max_shmem, + cudaDevAttrMaxSharedMemoryPerBlock, + device_ordinal))) + { + break; + } + std::size_t vshmem_size = detail::VshmemSize(max_shmem, sizeof(typename UniqueByKeyAgentT::TempStorage), num_tiles); + + // Specify temporary storage allocation requirements + size_t allocation_sizes[2] = {0, vshmem_size}; + if (CubDebug(error = ScanTileStateT::AllocationSize(num_tiles, allocation_sizes[0]))) break; // bytes needed for tile status descriptors + + // Compute allocation pointers into the single storage blob (or compute the necessary size of the blob) + void *allocations[2] = {NULL, NULL}; + if (CubDebug(error = AliasTemporaries(d_temp_storage, temp_storage_bytes, allocations, allocation_sizes))) break; + if (d_temp_storage == NULL) + { + // Return if the caller is simply requesting the size of the storage allocation + break; + } + + // Construct the tile status interface + ScanTileStateT tile_state; + if (CubDebug(error = tile_state.Init(num_tiles, allocations[0], allocation_sizes[0]))) break; + + // Log init_kernel configuration + num_tiles = CUB_MAX(1, num_tiles); + int init_grid_size = cub::DivideAndRoundUp(num_tiles, INIT_KERNEL_THREADS); + + #ifdef CUB_DETAIL_DEBUG_ENABLE_LOG + _CubLog("Invoking init_kernel<<<%d, %d, 0, %lld>>>()\n", init_grid_size, INIT_KERNEL_THREADS, (long long) stream); + #endif + + // Invoke init_kernel to initialize tile descriptors + THRUST_NS_QUALIFIER::cuda_cub::launcher::triple_chevron( + init_grid_size, INIT_KERNEL_THREADS, 0, stream + ).doit(init_kernel, tile_state, num_tiles, d_num_selected_out); + + // Check for failure to launch + if (CubDebug(error = cudaPeekAtLastError())) break; + + // Sync the stream if specified to flush runtime errors + error = detail::DebugSyncStream(stream); + if (CubDebug(error)) + { + break; + } + + // Return if empty problem + if (num_items == 0) break; + + // Get max x-dimension of grid + int max_dim_x; + if (CubDebug(error = cudaDeviceGetAttribute(&max_dim_x, cudaDevAttrMaxGridDimX, device_ordinal))) break; + + // Get grid size for scanning tiles + dim3 scan_grid_size; + scan_grid_size.z = 1; + scan_grid_size.y = cub::DivideAndRoundUp(num_tiles, max_dim_x); + scan_grid_size.x = CUB_MIN(num_tiles, max_dim_x); + + // Log select_if_kernel configuration + #ifdef CUB_DETAIL_DEBUG_ENABLE_LOG + { + // Get SM occupancy for unique_by_key_kernel + int scan_sm_occupancy; + if (CubDebug(error = MaxSmOccupancy(scan_sm_occupancy, // out + scan_kernel, + Policy::BLOCK_THREADS))) + { + break; + } + + _CubLog("Invoking unique_by_key_kernel<<<{%d,%d,%d}, %d, 0, " + "%lld>>>(), %d items per thread, %d SM occupancy\n", + scan_grid_size.x, + scan_grid_size.y, + scan_grid_size.z, + Policy::BLOCK_THREADS, + (long long)stream, + Policy::ITEMS_PER_THREAD, + scan_sm_occupancy); + } + #endif + + // Invoke select_if_kernel + error = THRUST_NS_QUALIFIER::cuda_cub::launcher::triple_chevron( + scan_grid_size, Policy::BLOCK_THREADS, 0, stream + ).doit(scan_kernel, + d_keys_in, + d_values_in, + d_keys_out, + d_values_out, + d_num_selected_out, + tile_state, + equality_op, + num_items, + num_tiles); + + // Check for failure to launch + if (CubDebug(error)) + { + break; + } + + // Sync the stream if specified to flush runtime errors + error = detail::DebugSyncStream(stream); + if (CubDebug(error)) + { + break; + } + } + while(0); + + return error; + } + + template + CUB_RUNTIME_FUNCTION __host__ __forceinline__ + cudaError_t Invoke() + { + using MaxPolicyT = typename DispatchUniqueByKey::MaxPolicy; + + // Ensure kernels are instantiated. + return Invoke( + DeviceCompactInitKernel, + DeviceUniqueByKeySweepKernel< + MaxPolicyT, + KeyInputIteratorT, + ValueInputIteratorT, + KeyOutputIteratorT, + ValueOutputIteratorT, + NumSelectedIteratorT, + ScanTileStateT, + EqualityOpT, + OffsetT> + ); + } + + + /** + * Internal dispatch routine + */ + CUB_RUNTIME_FUNCTION __forceinline__ + static cudaError_t Dispatch( + void* d_temp_storage, ///< [in] Device-accessible allocation of temporary storage. When NULL, the required allocation size is written to \p temp_storage_bytes and no work is done. + size_t &temp_storage_bytes, ///< [in,out] Reference to size in bytes of \p d_temp_storage allocation + KeyInputIteratorT d_keys_in, ///< [in] Pointer to the input sequence of keys + ValueInputIteratorT d_values_in, ///< [in] Pointer to the input sequence of values + KeyOutputIteratorT d_keys_out, ///< [out] Pointer to the output sequence of selected data items + ValueOutputIteratorT d_values_out, ///< [out] Pointer to the output sequence of selected data items + NumSelectedIteratorT d_num_selected_out, ///< [out] Pointer to the total number of items selected (i.e., length of \p d_keys_out or \p d_values_out) + EqualityOpT equality_op, ///< [in] Equality operator + OffsetT num_items, ///< [in] Total number of input items (i.e., the length of \p d_in) + cudaStream_t stream) ///< [in] [optional] CUDA stream to launch kernels within. Default is stream0. + { + using MaxPolicyT = typename DispatchUniqueByKey::MaxPolicy; + + cudaError_t error; + do + { + // Get PTX version + int ptx_version = 0; + if (CubDebug(error = PtxVersion(ptx_version))) break; + + // Create dispatch functor + DispatchUniqueByKey dispatch( + d_temp_storage, + temp_storage_bytes, + d_keys_in, + d_values_in, + d_keys_out, + d_values_out, + d_num_selected_out, + equality_op, + num_items, + stream); + + // Dispatch to chained policy + if (CubDebug(error = MaxPolicyT::Invoke(ptx_version, dispatch))) break; + } + while (0); + + return error; + } + + CUB_DETAIL_RUNTIME_DEBUG_SYNC_IS_NOT_SUPPORTED + CUB_RUNTIME_FUNCTION __forceinline__ + static cudaError_t Dispatch( + void* d_temp_storage, + size_t &temp_storage_bytes, + KeyInputIteratorT d_keys_in, + ValueInputIteratorT d_values_in, + KeyOutputIteratorT d_keys_out, + ValueOutputIteratorT d_values_out, + NumSelectedIteratorT d_num_selected_out, + EqualityOpT equality_op, + OffsetT num_items, + cudaStream_t stream, + bool debug_synchronous) + { + CUB_DETAIL_RUNTIME_DEBUG_SYNC_USAGE_LOG + + return Dispatch(d_temp_storage, + temp_storage_bytes, + d_keys_in, + d_values_in, + d_keys_out, + d_values_out, + d_num_selected_out, + equality_op, + num_items, + stream); + } +}; + +CUB_NAMESPACE_END diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/device/dispatch/tuning/tuning_reduce_by_key.cuh b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/device/dispatch/tuning/tuning_reduce_by_key.cuh new file mode 100644 index 0000000000000000000000000000000000000000..d06e2f7fb866419051c413d12ff30f777a23ce02 --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/device/dispatch/tuning/tuning_reduce_by_key.cuh @@ -0,0 +1,650 @@ +/****************************************************************************** + * Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the NVIDIA CORPORATION nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ******************************************************************************/ + +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +CUB_NAMESPACE_BEGIN + +namespace detail +{ + +namespace reduce_by_key +{ + +enum class primitive_key +{ + no, + yes +}; +enum class primitive_accum +{ + no, + yes +}; +enum class primitive_op +{ + no, + yes +}; +enum class key_size +{ + _1, + _2, + _4, + _8, + _16, + unknown +}; +enum class accum_size +{ + _1, + _2, + _4, + _8, + _16, + unknown +}; + +template +constexpr primitive_key is_primitive_key() +{ + return Traits::PRIMITIVE ? primitive_key::yes : primitive_key::no; +} + +template +constexpr primitive_accum is_primitive_accum() +{ + return Traits::PRIMITIVE ? primitive_accum::yes : primitive_accum::no; +} + +template +constexpr primitive_op is_primitive_op() +{ + return basic_binary_op_t::value ? primitive_op::yes : primitive_op::no; +} + +template +constexpr key_size classify_key_size() +{ + return sizeof(KeyT) == 1 ? key_size::_1 + : sizeof(KeyT) == 2 ? key_size::_2 + : sizeof(KeyT) == 4 ? key_size::_4 + : sizeof(KeyT) == 8 ? key_size::_8 + : sizeof(KeyT) == 16 ? key_size::_16 + : key_size::unknown; +} + +template +constexpr accum_size classify_accum_size() +{ + return sizeof(AccumT) == 1 ? accum_size::_1 + : sizeof(AccumT) == 2 ? accum_size::_2 + : sizeof(AccumT) == 4 ? accum_size::_4 + : sizeof(AccumT) == 8 ? accum_size::_8 + : sizeof(AccumT) == 16 ? accum_size::_16 + : accum_size::unknown; +} + +template (), + primitive_accum PrimitiveAccum = is_primitive_accum(), + key_size KeySize = classify_key_size(), + accum_size AccumSize = classify_accum_size()> +struct sm90_tuning +{ + static constexpr int max_input_bytes = CUB_MAX(sizeof(KeyT), sizeof(AccumT)); + static constexpr int combined_input_bytes = sizeof(KeyT) + sizeof(AccumT); + + static constexpr int threads = 128; + + static constexpr int nominal_4b_items_per_thread = 6; + static constexpr int items = + (max_input_bytes <= 8) + ? 6 + : CUB_MIN(nominal_4b_items_per_thread, + CUB_MAX(1, + ((nominal_4b_items_per_thread * 8) + combined_input_bytes - 1) / + combined_input_bytes)); + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_DIRECT; + + using delay_constructor = detail::default_reduce_by_key_delay_constructor_t; +}; + +// 8-bit key +template +struct sm90_tuning +{ + static constexpr int threads = 256; + + static constexpr int items = 13; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_DIRECT; + + using delay_constructor = detail::no_delay_constructor_t<720>; +}; + +template +struct sm90_tuning +{ + static constexpr int threads = 320; + + static constexpr int items = 23; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_DIRECT; + + using delay_constructor = detail::no_delay_constructor_t<865>; +}; + +template +struct sm90_tuning +{ + static constexpr int threads = 192; + + static constexpr int items = 14; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_WARP_TRANSPOSE; + + using delay_constructor = detail::no_delay_constructor_t<735>; +}; + +template +struct sm90_tuning +{ + static constexpr int threads = 128; + + static constexpr int items = 13; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_WARP_TRANSPOSE; + + using delay_constructor = detail::no_delay_constructor_t<580>; +}; + +template +struct sm90_tuning +{ + static constexpr int threads = 128; + + static constexpr int items = 11; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_WARP_TRANSPOSE; + + using delay_constructor = detail::no_delay_constructor_t<1100>; +}; + +// 16-bit key +template +struct sm90_tuning +{ + static constexpr int threads = 128; + + static constexpr int items = 23; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_DIRECT; + + using delay_constructor = detail::no_delay_constructor_t<985>; +}; + +template +struct sm90_tuning +{ + static constexpr int threads = 256; + + static constexpr int items = 11; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_DIRECT; + + using delay_constructor = detail::fixed_delay_constructor_t<276, 650>; +}; + +template +struct sm90_tuning +{ + static constexpr int threads = 256; + + static constexpr int items = 14; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_WARP_TRANSPOSE; + + using delay_constructor = detail::fixed_delay_constructor_t<240, 765>; +}; + +template +struct sm90_tuning +{ + static constexpr int threads = 128; + + static constexpr int items = 19; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_WARP_TRANSPOSE; + + using delay_constructor = detail::no_delay_constructor_t<1190>; +}; + +template +struct sm90_tuning +{ + static constexpr int threads = 128; + + static constexpr int items = 11; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_WARP_TRANSPOSE; + + using delay_constructor = detail::no_delay_constructor_t<1175>; +}; + +// 32-bit key +template +struct sm90_tuning +{ + static constexpr int threads = 256; + + static constexpr int items = 13; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_DIRECT; + + using delay_constructor = detail::fixed_delay_constructor_t<404, 645>; +}; + +template +struct sm90_tuning +{ + static constexpr int threads = 256; + + static constexpr int items = 18; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_WARP_TRANSPOSE; + + using delay_constructor = detail::no_delay_constructor_t<1160>; +}; + +template +struct sm90_tuning +{ + static constexpr int threads = 256; + + static constexpr int items = 18; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_WARP_TRANSPOSE; + + using delay_constructor = detail::no_delay_constructor_t<1170>; +}; + +template +struct sm90_tuning +{ + static constexpr int threads = 128; + + static constexpr int items = 13; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_WARP_TRANSPOSE; + + using delay_constructor = detail::no_delay_constructor_t<1055>; +}; + +template +struct sm90_tuning +{ + static constexpr int threads = 128; + + static constexpr int items = 11; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_WARP_TRANSPOSE; + + using delay_constructor = detail::no_delay_constructor_t<1195>; +}; + +// 64-bit key +template +struct sm90_tuning +{ + static constexpr int threads = 256; + + static constexpr int items = 10; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_DIRECT; + + using delay_constructor = detail::no_delay_constructor_t<1170>; +}; + +template +struct sm90_tuning +{ + static constexpr int threads = 256; + + static constexpr int items = 9; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_DIRECT; + + using delay_constructor = detail::fixed_delay_constructor_t<236, 1030>; +}; + +template +struct sm90_tuning +{ + static constexpr int threads = 128; + + static constexpr int items = 13; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_WARP_TRANSPOSE; + + using delay_constructor = detail::fixed_delay_constructor_t<152, 560>; +}; + +template +struct sm90_tuning +{ + static constexpr int threads = 128; + + static constexpr int items = 23; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_WARP_TRANSPOSE; + + using delay_constructor = detail::no_delay_constructor_t<1030>; +}; + +template +struct sm90_tuning +{ + static constexpr int threads = 128; + + static constexpr int items = 11; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_WARP_TRANSPOSE; + + using delay_constructor = detail::no_delay_constructor_t<1125>; +}; + +// 128-bit key +template +struct sm90_tuning +{ + static constexpr int threads = 128; + + static constexpr int items = 11; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_WARP_TRANSPOSE; + + using delay_constructor = detail::no_delay_constructor_t<1080>; +}; + +template +struct sm90_tuning +{ + static constexpr int threads = 128; + + static constexpr int items = 11; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_WARP_TRANSPOSE; + + using delay_constructor = detail::fixed_delay_constructor_t<320, 1005>; +}; + +template +struct sm90_tuning +{ + static constexpr int threads = 128; + + static constexpr int items = 11; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_WARP_TRANSPOSE; + + using delay_constructor = detail::fixed_delay_constructor_t<232, 1100>; +}; + +template +struct sm90_tuning +{ + static constexpr int threads = 128; + + static constexpr int items = 11; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_WARP_TRANSPOSE; + + using delay_constructor = detail::no_delay_constructor_t<1195>; +}; + +template +struct sm90_tuning +{ + static constexpr int threads = 128; + + static constexpr int items = 11; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_WARP_TRANSPOSE; + + using delay_constructor = detail::no_delay_constructor_t<1150>; +}; +} // namespace reduce_by_key + +template +struct device_reduce_by_key_policy_hub +{ + static constexpr int MAX_INPUT_BYTES = CUB_MAX(sizeof(KeyT), sizeof(AccumT)); + static constexpr int COMBINED_INPUT_BYTES = sizeof(KeyT) + sizeof(AccumT); + + /// SM35 + struct Policy350 : ChainedPolicy<350, Policy350, Policy350> + { + static constexpr int NOMINAL_4B_ITEMS_PER_THREAD = 6; + static constexpr int ITEMS_PER_THREAD = + (MAX_INPUT_BYTES <= 8) + ? 6 + : CUB_MIN(NOMINAL_4B_ITEMS_PER_THREAD, + CUB_MAX(1, + ((NOMINAL_4B_ITEMS_PER_THREAD * 8) + COMBINED_INPUT_BYTES - 1) / + COMBINED_INPUT_BYTES)); + + using ReduceByKeyPolicyT = + AgentReduceByKeyPolicy<128, + ITEMS_PER_THREAD, + BLOCK_LOAD_DIRECT, + LOAD_LDG, + BLOCK_SCAN_WARP_SCANS, + detail::default_reduce_by_key_delay_constructor_t>; + }; + + /// SM90 + struct Policy900 : ChainedPolicy<900, Policy900, Policy350> + { + using tuning = detail::reduce_by_key:: + sm90_tuning()>; + + using ReduceByKeyPolicyT = AgentReduceByKeyPolicy; + }; + + using MaxPolicy = Policy900; +}; + +} // namespace detail + +CUB_NAMESPACE_END diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/device/dispatch/tuning/tuning_run_length_encode.cuh b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/device/dispatch/tuning/tuning_run_length_encode.cuh new file mode 100644 index 0000000000000000000000000000000000000000..80282592915fbbf330c440f3ef6e7b5bea0d3b96 --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/device/dispatch/tuning/tuning_run_length_encode.cuh @@ -0,0 +1,652 @@ +/****************************************************************************** + * Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the NVIDIA CORPORATION nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ******************************************************************************/ + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +CUB_NAMESPACE_BEGIN + +namespace detail +{ + +namespace rle +{ + +enum class primitive_key { no, yes }; +enum class primitive_length { no, yes }; +enum class key_size { _1, _2, _4, _8, _16, unknown }; +enum class length_size { _4, unknown }; + +template +constexpr primitive_key is_primitive_key() +{ + return Traits::PRIMITIVE ? primitive_key::yes : primitive_key::no; +} + +template +constexpr primitive_length is_primitive_length() +{ + return Traits::PRIMITIVE ? primitive_length::yes : primitive_length::no; +} + +template +constexpr key_size classify_key_size() +{ + return sizeof(KeyT) == 1 ? key_size::_1 + : sizeof(KeyT) == 2 ? key_size::_2 + : sizeof(KeyT) == 4 ? key_size::_4 + : sizeof(KeyT) == 8 ? key_size::_8 + : sizeof(KeyT) == 16 ? key_size::_16 + : key_size::unknown; +} + +template +constexpr length_size classify_length_size() +{ + return sizeof(LengthT) == 4 ? length_size::_4 : length_size::unknown; +} + +namespace encode { + +template (), + primitive_key PrimitiveKey = is_primitive_key(), + length_size LengthSize = classify_length_size(), + key_size KeySize = classify_key_size()> +struct sm90_tuning +{ + static constexpr int max_input_bytes = CUB_MAX(sizeof(KeyT), sizeof(LengthT)); + static constexpr int combined_input_bytes = sizeof(KeyT) + sizeof(LengthT); + + static constexpr int threads = 128; + + static constexpr int nominal_4b_items_per_thread = 6; + + static constexpr int items = + (max_input_bytes <= 8) + ? 6 + : CUB_MIN(nominal_4b_items_per_thread, + CUB_MAX(1, + ((nominal_4b_items_per_thread * 8) + combined_input_bytes - 1) / + combined_input_bytes)); + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_DIRECT; + + using delay_constructor = detail::default_reduce_by_key_delay_constructor_t; +}; + +template +struct sm90_tuning +{ + static constexpr int threads = 256; + + static constexpr int items = 13; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_DIRECT; + + using delay_constructor = detail::no_delay_constructor_t<620>; +}; + +template +struct sm90_tuning +{ + static constexpr int threads = 128; + + static constexpr int items = 22; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_DIRECT; + + using delay_constructor = detail::no_delay_constructor_t<775>; +}; + +template +struct sm90_tuning +{ + static constexpr int threads = 192; + + static constexpr int items = 14; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_WARP_TRANSPOSE; + + using delay_constructor = detail::fixed_delay_constructor_t<284, 480>; +}; + +template +struct sm90_tuning +{ + static constexpr int threads = 128; + + static constexpr int items = 19; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_WARP_TRANSPOSE; + + using delay_constructor = detail::no_delay_constructor_t<515>; +}; + +#if CUB_IS_INT128_ENABLED +template +struct sm90_tuning +{ + static constexpr int threads = 128; + + static constexpr int items = 11; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_WARP_TRANSPOSE; + + using delay_constructor = detail::fixed_delay_constructor_t<428, 930>; +}; + +template +struct sm90_tuning +{ + static constexpr int threads = 128; + + static constexpr int items = 11; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_WARP_TRANSPOSE; + + using delay_constructor = detail::fixed_delay_constructor_t<428, 930>; +}; +#endif + +template (), + primitive_key PrimitiveKey = is_primitive_key(), + length_size LengthSize = classify_length_size(), + key_size KeySize = classify_key_size()> +struct sm80_tuning +{ + static constexpr int max_input_bytes = CUB_MAX(sizeof(KeyT), sizeof(LengthT)); + static constexpr int combined_input_bytes = sizeof(KeyT) + sizeof(LengthT); + + static constexpr int threads = 128; + + static constexpr int nominal_4b_items_per_thread = 6; + + static constexpr int items = + (max_input_bytes <= 8) + ? 6 + : CUB_MIN(nominal_4b_items_per_thread, + CUB_MAX(1, + ((nominal_4b_items_per_thread * 8) + combined_input_bytes - 1) / + combined_input_bytes)); + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_DIRECT; + + using delay_constructor = detail::default_reduce_by_key_delay_constructor_t; +}; + +template +struct sm80_tuning +{ + static constexpr int threads = 256; + + static constexpr int items = 14; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_DIRECT; + + using delay_constructor = detail::no_delay_constructor_t<640>; +}; + +template +struct sm80_tuning +{ + static constexpr int threads = 256; + + static constexpr int items = 13; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_DIRECT; + + using delay_constructor = detail::no_delay_constructor_t<900>; +}; + +template +struct sm80_tuning +{ + static constexpr int threads = 256; + + static constexpr int items = 13; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_DIRECT; + + using delay_constructor = detail::no_delay_constructor_t<1080>; +}; + +template +struct sm80_tuning +{ + static constexpr int threads = 224; + + static constexpr int items = 9; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_WARP_TRANSPOSE; + + using delay_constructor = detail::no_delay_constructor_t<1075>; +}; + +#if CUB_IS_INT128_ENABLED +template +struct sm80_tuning +{ + static constexpr int threads = 128; + + static constexpr int items = 7; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_WARP_TRANSPOSE; + + using delay_constructor = detail::no_delay_constructor_t<630>; +}; + +template +struct sm80_tuning +{ + static constexpr int threads = 128; + + static constexpr int items = 7; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_WARP_TRANSPOSE; + + using delay_constructor = detail::no_delay_constructor_t<630>; +}; +#endif + +} // namespace encode + +namespace non_trivial_runs +{ + +template (), + primitive_key PrimitiveKey = is_primitive_key(), + length_size LengthSize = classify_length_size(), + key_size KeySize = classify_key_size()> +struct sm90_tuning +{ + static constexpr int threads = 96; + + static constexpr int nominal_4b_items_per_thread = 15; + + static constexpr int items = CUB_MIN(nominal_4b_items_per_thread, + CUB_MAX(1, (nominal_4b_items_per_thread * 4 / sizeof(KeyT)))); + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_WARP_TRANSPOSE; + + static constexpr bool store_with_time_slicing = true; + + using delay_constructor = detail::default_reduce_by_key_delay_constructor_t; +}; + +template +struct sm90_tuning +{ + static constexpr int threads = 256; + + static constexpr int items = 18; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_DIRECT; + + static constexpr bool store_with_time_slicing = false; + + using delay_constructor = detail::no_delay_constructor_t<385>; +}; + +template +struct sm90_tuning +{ + static constexpr int threads = 224; + + static constexpr int items = 20; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_DIRECT; + + static constexpr bool store_with_time_slicing = false; + + using delay_constructor = detail::no_delay_constructor_t<675>; +}; + +template +struct sm90_tuning +{ + static constexpr int threads = 256; + + static constexpr int items = 18; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_DIRECT; + + static constexpr bool store_with_time_slicing = false; + + using delay_constructor = detail::no_delay_constructor_t<695>; +}; + +template +struct sm90_tuning +{ + static constexpr int threads = 224; + + static constexpr int items = 14; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_WARP_TRANSPOSE; + + static constexpr bool store_with_time_slicing = false; + + using delay_constructor = detail::no_delay_constructor_t<840>; +}; + +#if CUB_IS_INT128_ENABLED +template +struct sm90_tuning +{ + static constexpr int threads = 288; + + static constexpr int items = 9; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_WARP_TRANSPOSE; + + static constexpr bool store_with_time_slicing = false; + + using delay_constructor = detail::fixed_delay_constructor_t<484, 1150>; +}; + +template +struct sm90_tuning +{ + static constexpr int threads = 288; + + static constexpr int items = 9; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_WARP_TRANSPOSE; + + static constexpr bool store_with_time_slicing = false; + + using delay_constructor = detail::fixed_delay_constructor_t<484, 1150>; +}; +#endif + +template (), + primitive_key PrimitiveKey = is_primitive_key(), + length_size LengthSize = classify_length_size(), + key_size KeySize = classify_key_size()> +struct sm80_tuning +{ + static constexpr int threads = 96; + + static constexpr int nominal_4b_items_per_thread = 15; + + static constexpr int items = CUB_MIN(nominal_4b_items_per_thread, + CUB_MAX(1, (nominal_4b_items_per_thread * 4 / sizeof(KeyT)))); + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_WARP_TRANSPOSE; + + static constexpr bool store_with_time_slicing = true; + + using delay_constructor = detail::default_reduce_by_key_delay_constructor_t; +}; + +template +struct sm80_tuning +{ + static constexpr int threads = 192; + + static constexpr int items = 20; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_DIRECT; + + static constexpr bool store_with_time_slicing = false; + + using delay_constructor = detail::no_delay_constructor_t<630>; +}; + +template +struct sm80_tuning +{ + static constexpr int threads = 192; + + static constexpr int items = 20; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_WARP_TRANSPOSE; + + static constexpr bool store_with_time_slicing = false; + + using delay_constructor = detail::no_delay_constructor_t<1015>; +}; + +template +struct sm80_tuning +{ + static constexpr int threads = 224; + + static constexpr int items = 15; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_WARP_TRANSPOSE; + + static constexpr bool store_with_time_slicing = false; + + using delay_constructor = detail::no_delay_constructor_t<915>; +}; + +template +struct sm80_tuning +{ + static constexpr int threads = 256; + + static constexpr int items = 13; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_WARP_TRANSPOSE; + + static constexpr bool store_with_time_slicing = false; + + using delay_constructor = detail::no_delay_constructor_t<1065>; +}; + +#if CUB_IS_INT128_ENABLED +template +struct sm80_tuning +{ + static constexpr int threads = 192; + + static constexpr int items = 13; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_WARP_TRANSPOSE; + + static constexpr bool store_with_time_slicing = false; + + using delay_constructor = detail::no_delay_constructor_t<1050>; +}; + +template +struct sm80_tuning +{ + static constexpr int threads = 192; + + static constexpr int items = 13; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_WARP_TRANSPOSE; + + static constexpr bool store_with_time_slicing = false; + + using delay_constructor = detail::no_delay_constructor_t<1050>; +}; +#endif + +} // namespace non_trivial_runs + + +} // namespace rle + +template +struct device_run_length_encode_policy_hub +{ + static constexpr int MAX_INPUT_BYTES = CUB_MAX(sizeof(KeyT), sizeof(LengthT)); + static constexpr int COMBINED_INPUT_BYTES = sizeof(KeyT) + sizeof(LengthT); + + struct DefaultTuning + { + static constexpr int NOMINAL_4B_ITEMS_PER_THREAD = 6; + static constexpr int ITEMS_PER_THREAD = + (MAX_INPUT_BYTES <= 8) + ? 6 + : CUB_MIN(NOMINAL_4B_ITEMS_PER_THREAD, + CUB_MAX(1, + ((NOMINAL_4B_ITEMS_PER_THREAD * 8) + COMBINED_INPUT_BYTES - 1) / + COMBINED_INPUT_BYTES)); + + using ReduceByKeyPolicyT = + AgentReduceByKeyPolicy<128, + ITEMS_PER_THREAD, + BLOCK_LOAD_DIRECT, + LOAD_LDG, + BLOCK_SCAN_WARP_SCANS, + detail::default_reduce_by_key_delay_constructor_t>; + }; + + /// SM35 + struct Policy350 + : DefaultTuning + , ChainedPolicy<350, Policy350, Policy350> + {}; + + /// SM80 + struct Policy800 : ChainedPolicy<800, Policy800, Policy350> + { + using tuning = detail::rle::encode::sm80_tuning; + + using ReduceByKeyPolicyT = + AgentReduceByKeyPolicy; + }; + + // SM86 + struct Policy860 + : DefaultTuning + , ChainedPolicy<860, Policy860, Policy800> + {}; + + /// SM90 + struct Policy900 : ChainedPolicy<900, Policy900, Policy860> + { + using tuning = detail::rle::encode::sm90_tuning; + + using ReduceByKeyPolicyT = + AgentReduceByKeyPolicy; + }; + + using MaxPolicy = Policy900; +}; + +template +struct device_non_trivial_runs_policy_hub +{ + struct DefaultTuning + { + enum + { + NOMINAL_4B_ITEMS_PER_THREAD = 15, + + ITEMS_PER_THREAD = CUB_MIN(NOMINAL_4B_ITEMS_PER_THREAD, + CUB_MAX(1, (NOMINAL_4B_ITEMS_PER_THREAD * 4 / sizeof(KeyT)))), + }; + + using RleSweepPolicyT = + AgentRlePolicy<96, + ITEMS_PER_THREAD, + BLOCK_LOAD_DIRECT, + LOAD_LDG, + true, + BLOCK_SCAN_WARP_SCANS, + detail::default_reduce_by_key_delay_constructor_t>; + }; + + /// SM35 + struct Policy350 + : DefaultTuning + , ChainedPolicy<350, Policy350, Policy350> + {}; + + // SM80 + struct Policy800 : ChainedPolicy<800, Policy800, Policy350> + { + using tuning = detail::rle::non_trivial_runs::sm80_tuning; + + using RleSweepPolicyT = AgentRlePolicy; + }; + + // SM86 + struct Policy860 + : DefaultTuning + , ChainedPolicy<860, Policy860, Policy800> + {}; + + // SM90 + struct Policy900 : ChainedPolicy<900, Policy900, Policy860> + { + using tuning = detail::rle::non_trivial_runs::sm90_tuning; + + using RleSweepPolicyT = + AgentRlePolicy; + }; + + using MaxPolicy = Policy900; +}; + +} // namespace detail + + +CUB_NAMESPACE_END diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/device/dispatch/tuning/tuning_select_if.cuh b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/device/dispatch/tuning/tuning_select_if.cuh new file mode 100644 index 0000000000000000000000000000000000000000..27247ca70e5114e9aef7f409bf4c77ca974cfff5 --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/device/dispatch/tuning/tuning_select_if.cuh @@ -0,0 +1,749 @@ +/****************************************************************************** + * Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the NVIDIA CORPORATION nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ******************************************************************************/ + +#pragma once + +#include +#include +#include +#include +#include +#include + +CUB_NAMESPACE_BEGIN + +namespace detail +{ + +namespace select +{ + +enum class flagged { no, yes }; +enum class keep_rejects { no, yes }; +enum class primitive { no, yes }; +enum class offset_size { _4, _8, unknown }; +enum class input_size { _1, _2, _4, _8, _16, unknown }; + +template +constexpr primitive is_primitive() +{ + return Traits::PRIMITIVE ? primitive::yes : primitive::no; +} + +template +constexpr flagged is_flagged() +{ + return std::is_same::value ? flagged::no : flagged::yes; +} + +template +constexpr keep_rejects are_rejects_kept() +{ + return KeepRejects ? keep_rejects::yes : keep_rejects::no; +} + +template +constexpr input_size classify_input_size() +{ + return sizeof(InputT) == 1 ? input_size::_1 + : sizeof(InputT) == 2 ? input_size::_2 + : sizeof(InputT) == 4 ? input_size::_4 + : sizeof(InputT) == 8 ? input_size::_8 + : sizeof(InputT) == 16 ? input_size::_16 + : input_size::unknown; +} + +template +constexpr offset_size classify_offset_size() +{ + return sizeof(OffsetT) == 4 ? offset_size::_4 + : sizeof(OffsetT) == 8 ? offset_size::_8 + : offset_size::unknown; +} + +template (), + input_size InputSize = classify_input_size()> +struct sm90_tuning +{ + static constexpr int threads = 128; + + static constexpr int nominal_4b_items_per_thread = 10; + + static constexpr int items = + CUB_MIN(nominal_4b_items_per_thread, + CUB_MAX(1, (nominal_4b_items_per_thread * 4 / sizeof(InputT)))); + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_DIRECT; + + using delay_constructor = detail::fixed_delay_constructor_t<350, 450>; +}; + +// select::if +template +struct sm90_tuning +{ + static constexpr int threads = 256; + static constexpr int items = 22; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_DIRECT; + + using delay_constructor = detail::no_delay_constructor_t<580>; +}; + +template +struct sm90_tuning +{ + static constexpr int threads = 256; + static constexpr int items = 22; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_WARP_TRANSPOSE; + + using delay_constructor = detail::fixed_delay_constructor_t<320, 605>; +}; + +template +struct sm90_tuning +{ + static constexpr int threads = 384; + static constexpr int items = 17; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_WARP_TRANSPOSE; + + using delay_constructor = detail::fixed_delay_constructor_t<76, 1150>; +}; + +template +struct sm90_tuning +{ + static constexpr int threads = 384; + static constexpr int items = 11; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_WARP_TRANSPOSE; + + using delay_constructor = detail::fixed_delay_constructor_t<380, 1140>; +}; + +#if CUB_IS_INT128_ENABLED +template <> +struct sm90_tuning<__int128_t, flagged::no, keep_rejects::no, offset_size::_4, primitive::no, input_size::_16> +{ + static constexpr int threads = 512; + static constexpr int items = 5; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_DIRECT; + + using delay_constructor = detail::fixed_delay_constructor_t<460, 1145>; +}; + +template <> +struct sm90_tuning<__uint128_t, flagged::no, keep_rejects::no, offset_size::_4, primitive::no, input_size::_16> +{ + static constexpr int threads = 512; + static constexpr int items = 5; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_DIRECT; + + using delay_constructor = detail::fixed_delay_constructor_t<460, 1145>; +}; +#endif + +// select::flagged +template +struct sm90_tuning +{ + static constexpr int threads = 448; + static constexpr int items = 20; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_DIRECT; + + using delay_constructor = detail::no_delay_constructor_t<715>; +}; + +template +struct sm90_tuning +{ + static constexpr int threads = 448; + static constexpr int items = 20; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_DIRECT; + + using delay_constructor = detail::fixed_delay_constructor_t<504, 765>; +}; + +template +struct sm90_tuning +{ + static constexpr int threads = 384; + static constexpr int items = 15; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_DIRECT; + + using delay_constructor = detail::fixed_delay_constructor_t<415, 1125>; +}; + +template +struct sm90_tuning +{ + static constexpr int threads = 384; + static constexpr int items = 11; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_DIRECT; + + using delay_constructor = detail::fixed_delay_constructor_t<360, 1170>; +}; + +#if CUB_IS_INT128_ENABLED +template <> +struct sm90_tuning<__int128_t, flagged::yes, keep_rejects::no, offset_size::_4, primitive::no, input_size::_16> +{ + static constexpr int threads = 512; + static constexpr int items = 3; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_DIRECT; + + using delay_constructor = detail::fixed_delay_constructor_t<284, 1130>; +}; + +template <> +struct sm90_tuning<__uint128_t, flagged::yes, keep_rejects::no, offset_size::_4, primitive::no, input_size::_16> +{ + static constexpr int threads = 512; + static constexpr int items = 3; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_DIRECT; + + using delay_constructor = detail::fixed_delay_constructor_t<284, 1130>; +}; +#endif + +// partition::if +template +struct sm90_tuning +{ + static constexpr int threads = 384; + static constexpr int items = 20; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_DIRECT; + + using delay_constructor = detail::fixed_delay_constructor_t<908, 995>; +}; + +template +struct sm90_tuning +{ + static constexpr int threads = 320; + static constexpr int items = 14; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_DIRECT; + + using delay_constructor = detail::fixed_delay_constructor_t<500, 560>; +}; + +template +struct sm90_tuning +{ + static constexpr int threads = 256; + static constexpr int items = 14; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_DIRECT; + + using delay_constructor = detail::fixed_delay_constructor_t<536, 1055>; +}; + +template +struct sm90_tuning +{ + static constexpr int threads = 128; + static constexpr int items = 12; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_WARP_TRANSPOSE; + + using delay_constructor = detail::fixed_delay_constructor_t<512, 1075>; +}; + +#if CUB_IS_INT128_ENABLED +template <> +struct sm90_tuning<__int128_t, flagged::no, keep_rejects::yes, offset_size::_4, primitive::no, input_size::_16> +{ + static constexpr int threads = 192; + static constexpr int items = 5; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_WARP_TRANSPOSE; + + using delay_constructor = detail::fixed_delay_constructor_t<1616, 1115>; +}; + +template <> +struct sm90_tuning<__uint128_t, flagged::no, keep_rejects::yes, offset_size::_4, primitive::no, input_size::_16> +{ + static constexpr int threads = 192; + static constexpr int items = 5; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_WARP_TRANSPOSE; + + using delay_constructor = detail::fixed_delay_constructor_t<1616, 1115>; +}; +#endif + +// partition::flagged +template +struct sm90_tuning +{ + static constexpr int threads = 256; + static constexpr int items = 20; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_DIRECT; + + using delay_constructor = detail::fixed_delay_constructor_t<580, 850>; +}; + +template +struct sm90_tuning +{ + static constexpr int threads = 512; + static constexpr int items = 20; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_DIRECT; + + using delay_constructor = detail::fixed_delay_constructor_t<388, 1055>; +}; + +template +struct sm90_tuning +{ + static constexpr int threads = 256; + static constexpr int items = 20; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_DIRECT; + + using delay_constructor = detail::fixed_delay_constructor_t<72, 1165>; +}; + +template +struct sm90_tuning +{ + static constexpr int threads = 224; + static constexpr int items = 6; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_DIRECT; + + using delay_constructor = detail::fixed_delay_constructor_t<532, 1180>; +}; + +#if CUB_IS_INT128_ENABLED +template <> +struct sm90_tuning<__int128_t, flagged::yes, keep_rejects::yes, offset_size::_4, primitive::no, input_size::_16> +{ + static constexpr int threads = 160; + static constexpr int items = 5; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_DIRECT; + + using delay_constructor = detail::fixed_delay_constructor_t<720, 1105>; +}; + +template <> +struct sm90_tuning<__uint128_t, flagged::yes, keep_rejects::yes, offset_size::_4, primitive::no, input_size::_16> +{ + static constexpr int threads = 160; + static constexpr int items = 5; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_DIRECT; + + using delay_constructor = detail::fixed_delay_constructor_t<720, 1105>; +}; +#endif + + +template (), + input_size InputSize = classify_input_size()> +struct sm80_tuning +{ + static constexpr int threads = 128; + + static constexpr int nominal_4b_items_per_thread = 10; + + static constexpr int items = + CUB_MIN(nominal_4b_items_per_thread, + CUB_MAX(1, (nominal_4b_items_per_thread * 4 / sizeof(InputT)))); + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_DIRECT; + + using delay_constructor = detail::fixed_delay_constructor_t<350, 450>; +}; + +// select::if +template +struct sm80_tuning +{ + static constexpr int threads = 992; + static constexpr int items = 20; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_DIRECT; + + using delay_constructor = detail::no_delay_constructor_t<395>; +}; + +template +struct sm80_tuning +{ + static constexpr int threads = 576; + static constexpr int items = 14; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_DIRECT; + + using delay_constructor = detail::no_delay_constructor_t<870>; +}; + +template +struct sm80_tuning +{ + static constexpr int threads = 256; + static constexpr int items = 18; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_WARP_TRANSPOSE; + + using delay_constructor = detail::no_delay_constructor_t<1130>; +}; + +template +struct sm80_tuning +{ + static constexpr int threads = 192; + static constexpr int items = 10; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_WARP_TRANSPOSE; + + using delay_constructor = detail::fixed_delay_constructor_t<832, 1165>; +}; + +#if CUB_IS_INT128_ENABLED +template <> +struct sm80_tuning<__int128_t, flagged::no, keep_rejects::no, offset_size::_4, primitive::no, input_size::_16> +{ + static constexpr int threads = 384; + static constexpr int items = 4; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_DIRECT; + + using delay_constructor = detail::no_delay_constructor_t<1140>; +}; + +template <> +struct sm80_tuning<__uint128_t, flagged::no, keep_rejects::no, offset_size::_4, primitive::no, input_size::_16> +{ + static constexpr int threads = 384; + static constexpr int items = 4; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_DIRECT; + + using delay_constructor = detail::no_delay_constructor_t<1140>; +}; +#endif + +// select::flagged +template +struct sm80_tuning +{ + static constexpr int threads = 224; + static constexpr int items = 20; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_DIRECT; + + using delay_constructor = detail::no_delay_constructor_t<735>; +}; + +template +struct sm80_tuning +{ + static constexpr int threads = 256; + static constexpr int items = 20; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_WARP_TRANSPOSE; + + using delay_constructor = detail::no_delay_constructor_t<1155>; +}; + +template +struct sm80_tuning +{ + static constexpr int threads = 320; + static constexpr int items = 10; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_DIRECT; + + using delay_constructor = detail::fixed_delay_constructor_t<124, 1115>; +}; + +template +struct sm80_tuning +{ + static constexpr int threads = 384; + static constexpr int items = 6; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_DIRECT; + + using delay_constructor = detail::no_delay_constructor_t<1130>; +}; + +#if CUB_IS_INT128_ENABLED +template <> +struct sm80_tuning<__int128_t, flagged::yes, keep_rejects::no, offset_size::_4, primitive::no, input_size::_16> +{ + static constexpr int threads = 256; + static constexpr int items = 5; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_DIRECT; + + using delay_constructor = detail::fixed_delay_constructor_t<464, 1025>; +}; + +template <> +struct sm80_tuning<__uint128_t, flagged::yes, keep_rejects::no, offset_size::_4, primitive::no, input_size::_16> +{ + static constexpr int threads = 256; + static constexpr int items = 5; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_DIRECT; + + using delay_constructor = detail::fixed_delay_constructor_t<464, 1025>; +}; +#endif + +// partition::if +template +struct sm80_tuning +{ + static constexpr int threads = 512; + static constexpr int items = 20; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_DIRECT; + + using delay_constructor = detail::no_delay_constructor_t<510>; +}; + +template +struct sm80_tuning +{ + static constexpr int threads = 224; + static constexpr int items = 18; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_WARP_TRANSPOSE; + + using delay_constructor = detail::no_delay_constructor_t<1045>; +}; + +template +struct sm80_tuning +{ + static constexpr int threads = 192; + static constexpr int items = 15; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_DIRECT; + + using delay_constructor = detail::no_delay_constructor_t<1040>; +}; + +template +struct sm80_tuning +{ + static constexpr int threads = 192; + static constexpr int items = 10; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_WARP_TRANSPOSE; + + using delay_constructor = detail::fixed_delay_constructor_t<68, 1160>; +}; + +#if CUB_IS_INT128_ENABLED +template <> +struct sm80_tuning<__int128_t, flagged::no, keep_rejects::yes, offset_size::_4, primitive::no, input_size::_16> +{ + static constexpr int threads = 256; + static constexpr int items = 5; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_WARP_TRANSPOSE; + + using delay_constructor = detail::fixed_delay_constructor_t<400, 1090>; +}; + +template <> +struct sm80_tuning<__uint128_t, flagged::no, keep_rejects::yes, offset_size::_4, primitive::no, input_size::_16> +{ + static constexpr int threads = 256; + static constexpr int items = 5; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_WARP_TRANSPOSE; + + using delay_constructor = detail::fixed_delay_constructor_t<400, 1090>; +}; +#endif + +// partition::flagged +template +struct sm80_tuning +{ + static constexpr int threads = 512; + static constexpr int items = 20; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_DIRECT; + + using delay_constructor = detail::no_delay_constructor_t<595>; +}; + +template +struct sm80_tuning +{ + static constexpr int threads = 224; + static constexpr int items = 18; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_WARP_TRANSPOSE; + + using delay_constructor = detail::no_delay_constructor_t<1105>; +}; + +template +struct sm80_tuning +{ + static constexpr int threads = 192; + static constexpr int items = 12; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_DIRECT; + + using delay_constructor = detail::fixed_delay_constructor_t<912, 1025>; +}; + +template +struct sm80_tuning +{ + static constexpr int threads = 192; + static constexpr int items = 12; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_WARP_TRANSPOSE; + + using delay_constructor = detail::fixed_delay_constructor_t<884, 1130>; +}; + +#if CUB_IS_INT128_ENABLED +template <> +struct sm80_tuning<__int128_t, flagged::yes, keep_rejects::yes, offset_size::_4, primitive::no, input_size::_16> +{ + static constexpr int threads = 256; + static constexpr int items = 5; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_WARP_TRANSPOSE; + + using delay_constructor = detail::fixed_delay_constructor_t<400, 1090>; +}; + +template <> +struct sm80_tuning<__uint128_t, flagged::yes, keep_rejects::yes, offset_size::_4, primitive::no, input_size::_16> +{ + static constexpr int threads = 256; + static constexpr int items = 5; + + static constexpr BlockLoadAlgorithm load_algorithm = BLOCK_LOAD_WARP_TRANSPOSE; + + using delay_constructor = detail::fixed_delay_constructor_t<400, 1090>; +}; +#endif + +} // namespace select + +template +struct device_select_policy_hub +{ + struct DefaultTuning + { + static constexpr int NOMINAL_4B_ITEMS_PER_THREAD = 10; + + static constexpr int ITEMS_PER_THREAD = + CUB_MIN(NOMINAL_4B_ITEMS_PER_THREAD, + CUB_MAX(1, (NOMINAL_4B_ITEMS_PER_THREAD * 4 / sizeof(InputT)))); + + using SelectIfPolicyT = AgentSelectIfPolicy<128, + ITEMS_PER_THREAD, + BLOCK_LOAD_DIRECT, + MayAlias ? LOAD_CA : LOAD_LDG, + BLOCK_SCAN_WARP_SCANS, + detail::fixed_delay_constructor_t<350, 450>>; + }; + + struct Policy350 + : DefaultTuning + , ChainedPolicy<350, Policy350, Policy350> + {}; + + struct Policy800 : ChainedPolicy<800, Policy800, Policy350> + { + using tuning = detail::select::sm80_tuning(), + select::are_rejects_kept(), + select::classify_offset_size()>; + + using SelectIfPolicyT = AgentSelectIfPolicy; + }; + + struct Policy860 + : DefaultTuning + , ChainedPolicy<860, Policy860, Policy800> + {}; + + struct Policy900 : ChainedPolicy<900, Policy900, Policy860> + { + using tuning = detail::select::sm90_tuning(), + select::are_rejects_kept(), + select::classify_offset_size()>; + + using SelectIfPolicyT = AgentSelectIfPolicy; + }; + + using MaxPolicy = Policy900; +}; + +} // detail + +CUB_NAMESPACE_END diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/grid/grid_barrier.cuh b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/grid/grid_barrier.cuh new file mode 100644 index 0000000000000000000000000000000000000000..ca946f3cc84095ce9150160107a956e8cff9bd75 --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/grid/grid_barrier.cuh @@ -0,0 +1,206 @@ +/****************************************************************************** + * Copyright (c) 2011, Duane Merrill. All rights reserved. + * Copyright (c) 2011-2018, NVIDIA CORPORATION. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the NVIDIA CORPORATION nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ******************************************************************************/ + +/** + * \file + * cub::GridBarrier implements a software global barrier among thread blocks within a CUDA grid + */ + +#pragma once + +#include "../util_debug.cuh" +#include "../config.cuh" +#include "../thread/thread_load.cuh" + +CUB_NAMESPACE_BEGIN + + +/** + * \addtogroup GridModule + * @{ + */ + + +/** + * \brief GridBarrier implements a software global barrier among thread blocks within a CUDA grid + */ +class GridBarrier +{ +protected : + + typedef unsigned int SyncFlag; + + // Counters in global device memory + SyncFlag* d_sync; + +public: + + /** + * Constructor + */ + GridBarrier() : d_sync(NULL) {} + + + /** + * Synchronize + */ + __device__ __forceinline__ void Sync() const + { + volatile SyncFlag *d_vol_sync = d_sync; + + // Threadfence and syncthreads to make sure global writes are visible before + // thread-0 reports in with its sync counter + __threadfence(); + CTA_SYNC(); + + if (blockIdx.x == 0) + { + // Report in ourselves + if (threadIdx.x == 0) + { + d_vol_sync[blockIdx.x] = 1; + } + + CTA_SYNC(); + + // Wait for everyone else to report in + for (int peer_block = threadIdx.x; peer_block < gridDim.x; peer_block += blockDim.x) + { + while (ThreadLoad(d_sync + peer_block) == 0) + { + __threadfence_block(); + } + } + + CTA_SYNC(); + + // Let everyone know it's safe to proceed + for (int peer_block = threadIdx.x; peer_block < gridDim.x; peer_block += blockDim.x) + { + d_vol_sync[peer_block] = 0; + } + } + else + { + if (threadIdx.x == 0) + { + // Report in + d_vol_sync[blockIdx.x] = 1; + + // Wait for acknowledgment + while (ThreadLoad(d_sync + blockIdx.x) == 1) + { + __threadfence_block(); + } + } + + CTA_SYNC(); + } + } +}; + + +/** + * \brief GridBarrierLifetime extends GridBarrier to provide lifetime management of the temporary device storage needed for cooperation. + * + * Uses RAII for lifetime, i.e., device resources are reclaimed when + * the destructor is called. + */ +class GridBarrierLifetime : public GridBarrier +{ +protected: + + // Number of bytes backed by d_sync + size_t sync_bytes; + +public: + + /** + * Constructor + */ + GridBarrierLifetime() : GridBarrier(), sync_bytes(0) {} + + + /** + * DeviceFrees and resets the progress counters + */ + cudaError_t HostReset() + { + cudaError_t retval = cudaSuccess; + if (d_sync) + { + CubDebug(retval = cudaFree(d_sync)); + d_sync = NULL; + } + sync_bytes = 0; + return retval; + } + + + /** + * Destructor + */ + virtual ~GridBarrierLifetime() + { + HostReset(); + } + + + /** + * Sets up the progress counters for the next kernel launch (lazily + * allocating and initializing them if necessary) + */ + cudaError_t Setup(int sweep_grid_size) + { + cudaError_t retval = cudaSuccess; + do { + size_t new_sync_bytes = sweep_grid_size * sizeof(SyncFlag); + if (new_sync_bytes > sync_bytes) + { + if (d_sync) + { + if (CubDebug(retval = cudaFree(d_sync))) break; + } + + sync_bytes = new_sync_bytes; + + // Allocate and initialize to zero + if (CubDebug(retval = cudaMalloc((void**) &d_sync, sync_bytes))) break; + if (CubDebug(retval = cudaMemset(d_sync, 0, new_sync_bytes))) break; + } + } while (0); + + return retval; + } +}; + + +/** @} */ // end group GridModule + +CUB_NAMESPACE_END + diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/grid/grid_even_share.cuh b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/grid/grid_even_share.cuh new file mode 100644 index 0000000000000000000000000000000000000000..d2150511321c299680f42d49aefb86183fba0bb5 --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/grid/grid_even_share.cuh @@ -0,0 +1,222 @@ +/****************************************************************************** + * Copyright (c) 2011, Duane Merrill. All rights reserved. + * Copyright (c) 2011-2018, NVIDIA CORPORATION. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the NVIDIA CORPORATION nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ******************************************************************************/ + +/** + * \file + * cub::GridEvenShare is a descriptor utility for distributing input among CUDA thread blocks in an "even-share" fashion. Each thread block gets roughly the same number of fixed-size work units (grains). + */ + + +#pragma once + +#include "../config.cuh" +#include "../util_namespace.cuh" +#include "../util_macro.cuh" +#include "../util_math.cuh" +#include "../util_type.cuh" +#include "grid_mapping.cuh" + +CUB_NAMESPACE_BEGIN + + +/** + * \addtogroup GridModule + * @{ + */ + + +/** + * \brief GridEvenShare is a descriptor utility for distributing input among + * CUDA thread blocks in an "even-share" fashion. Each thread block gets roughly + * the same number of input tiles. + * + * \par Overview + * Each thread block is assigned a consecutive sequence of input tiles. To help + * preserve alignment and eliminate the overhead of guarded loads for all but the + * last thread block, to GridEvenShare assigns one of three different amounts of + * work to a given thread block: "big", "normal", or "last". The "big" workloads + * are one scheduling grain larger than "normal". The "last" work unit for the + * last thread block may be partially-full if the input is not an even multiple of + * the scheduling grain size. + * + * \par + * Before invoking a child grid, a parent thread will typically construct an + * instance of GridEvenShare. The instance can be passed to child thread blocks + * which can initialize their per-thread block offsets using \p BlockInit(). + */ +template +struct GridEvenShare +{ +private: + + int total_tiles; + int big_shares; + OffsetT big_share_items; + OffsetT normal_share_items; + OffsetT normal_base_offset; + +public: + + /// Total number of input items + OffsetT num_items; + + /// Grid size in thread blocks + int grid_size; + + /// OffsetT into input marking the beginning of the owning thread block's segment of input tiles + OffsetT block_offset; + + /// OffsetT into input of marking the end (one-past) of the owning thread block's segment of input tiles + OffsetT block_end; + + /// Stride between input tiles + OffsetT block_stride; + + + /** + * \brief Constructor. + */ + __host__ __device__ __forceinline__ GridEvenShare() : + total_tiles(0), + big_shares(0), + big_share_items(0), + normal_share_items(0), + normal_base_offset(0), + num_items(0), + grid_size(0), + block_offset(0), + block_end(0), + block_stride(0) + {} + + + /** + * \brief Dispatch initializer. To be called prior prior to kernel launch. + */ + __host__ __device__ __forceinline__ void DispatchInit( + OffsetT num_items_, ///< Total number of input items + int max_grid_size, ///< Maximum grid size allowable (actual grid size may be less if not warranted by the the number of input items) + int tile_items) ///< Number of data items per input tile + { + this->block_offset = num_items_; // Initialize past-the-end + this->block_end = num_items_; // Initialize past-the-end + this->num_items = num_items_; + this->total_tiles = static_cast(cub::DivideAndRoundUp(num_items_, tile_items)); + this->grid_size = CUB_MIN(total_tiles, max_grid_size); + int avg_tiles_per_block = total_tiles / grid_size; + // leftover grains go to big blocks: + this->big_shares = total_tiles - (avg_tiles_per_block * grid_size); + this->normal_share_items = avg_tiles_per_block * tile_items; + this->normal_base_offset = big_shares * tile_items; + this->big_share_items = normal_share_items + tile_items; + } + + + /** + * \brief Initializes ranges for the specified thread block index. Specialized + * for a "raking" access pattern in which each thread block is assigned a + * consecutive sequence of input tiles. + */ + template + __device__ __forceinline__ void BlockInit( + int block_id, + Int2Type /*strategy_tag*/) + { + block_stride = TILE_ITEMS; + if (block_id < big_shares) + { + // This thread block gets a big share of grains (avg_tiles_per_block + 1) + block_offset = (block_id * big_share_items); + block_end = block_offset + big_share_items; + } + else if (block_id < total_tiles) + { + // This thread block gets a normal share of grains (avg_tiles_per_block) + block_offset = normal_base_offset + (block_id * normal_share_items); + // Avoid generating values greater than num_items, as it may cause overflow + block_end = block_offset + CUB_MIN(num_items - block_offset, normal_share_items); + } + // Else default past-the-end + } + + + /** + * \brief Block-initialization, specialized for a "raking" access + * pattern in which each thread block is assigned a consecutive sequence + * of input tiles. + */ + template + __device__ __forceinline__ void BlockInit( + int block_id, + Int2Type /*strategy_tag*/) + { + block_stride = grid_size * TILE_ITEMS; + block_offset = (block_id * TILE_ITEMS); + block_end = num_items; + } + + + /** + * \brief Block-initialization, specialized for "strip mining" access + * pattern in which the input tiles assigned to each thread block are + * separated by a stride equal to the the extent of the grid. + */ + template < + int TILE_ITEMS, + GridMappingStrategy STRATEGY> + __device__ __forceinline__ void BlockInit() + { + BlockInit(blockIdx.x, Int2Type()); + } + + + /** + * \brief Block-initialization, specialized for a "raking" access + * pattern in which each thread block is assigned a consecutive sequence + * of input tiles. + */ + template + __device__ __forceinline__ void BlockInit( + OffsetT block_offset, ///< [in] Threadblock begin offset (inclusive) + OffsetT block_end) ///< [in] Threadblock end offset (exclusive) + { + this->block_offset = block_offset; + this->block_end = block_end; + this->block_stride = TILE_ITEMS; + } + + +}; + + + + + +/** @} */ // end group GridModule + +CUB_NAMESPACE_END diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/grid/grid_mapping.cuh b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/grid/grid_mapping.cuh new file mode 100644 index 0000000000000000000000000000000000000000..b57f193deb883f421076fc52bff75f23423251d6 --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/grid/grid_mapping.cuh @@ -0,0 +1,108 @@ +/****************************************************************************** + * Copyright (c) 2011, Duane Merrill. All rights reserved. + * Copyright (c) 2011-2018, NVIDIA CORPORATION. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the NVIDIA CORPORATION nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ******************************************************************************/ + +/** + * \file + * cub::GridMappingStrategy enumerates alternative strategies for mapping constant-sized tiles of device-wide data onto a grid of CUDA thread blocks. + */ + +#pragma once + +#include "../config.cuh" + +CUB_NAMESPACE_BEGIN + + +/** + * \addtogroup GridModule + * @{ + */ + + +/****************************************************************************** + * Mapping policies + *****************************************************************************/ + + +/** + * \brief cub::GridMappingStrategy enumerates alternative strategies for mapping constant-sized tiles of device-wide data onto a grid of CUDA thread blocks. + */ +enum GridMappingStrategy +{ + /** + * \brief An a "raking" access pattern in which each thread block is + * assigned a consecutive sequence of input tiles + * + * \par Overview + * The input is evenly partitioned into \p p segments, where \p p is + * constant and corresponds loosely to the number of thread blocks that may + * actively reside on the target device. Each segment is comprised of + * consecutive tiles, where a tile is a small, constant-sized unit of input + * to be processed to completion before the thread block terminates or + * obtains more work. The kernel invokes \p p thread blocks, each + * of which iteratively consumes a segment of n/p elements + * in tile-size increments. + */ + GRID_MAPPING_RAKE, + + /** + * \brief An a "strip mining" access pattern in which the input tiles assigned + * to each thread block are separated by a stride equal to the the extent of + * the grid. + * + * \par Overview + * The input is evenly partitioned into \p p sets, where \p p is + * constant and corresponds loosely to the number of thread blocks that may + * actively reside on the target device. Each set is comprised of + * data tiles separated by stride \p tiles, where a tile is a small, + * constant-sized unit of input to be processed to completion before the + * thread block terminates or obtains more work. The kernel invokes \p p + * thread blocks, each of which iteratively consumes a segment of + * n/p elements in tile-size increments. + */ + GRID_MAPPING_STRIP_MINE, + + /** + * \brief A dynamic "queue-based" strategy for assigning input tiles to thread blocks. + * + * \par Overview + * The input is treated as a queue to be dynamically consumed by a grid of + * thread blocks. Work is atomically dequeued in tiles, where a tile is a + * unit of input to be processed to completion before the thread block + * terminates or obtains more work. The grid size \p p is constant, + * loosely corresponding to the number of thread blocks that may actively + * reside on the target device. + */ + GRID_MAPPING_DYNAMIC, +}; + + +/** @} */ // end group GridModule + +CUB_NAMESPACE_END + diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/grid/grid_queue.cuh b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/grid/grid_queue.cuh new file mode 100644 index 0000000000000000000000000000000000000000..e1933e3d3819b0ad251857cb10312d0ccf93babd --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/grid/grid_queue.cuh @@ -0,0 +1,237 @@ +/****************************************************************************** + * Copyright (c) 2011, Duane Merrill. All rights reserved. + * Copyright (c) 2011-2018, NVIDIA CORPORATION. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the NVIDIA CORPORATION nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ******************************************************************************/ + +/** + * \file + * cub::GridQueue is a descriptor utility for dynamic queue management. + */ + +#pragma once + +#include +#include + +#include + +CUB_NAMESPACE_BEGIN + + +/** + * \addtogroup GridModule + * @{ + */ + + +/** + * \brief GridQueue is a descriptor utility for dynamic queue management. + * + * \par Overview + * GridQueue descriptors provides abstractions for "filling" or + * "draining" globally-shared vectors. + * + * \par + * A "filling" GridQueue works by atomically-adding to a zero-initialized counter, + * returning a unique offset for the calling thread to write its items. + * The GridQueue maintains the total "fill-size". The fill counter must be reset + * using GridQueue::ResetFill by the host or kernel instance prior to the kernel instance that + * will be filling. + * + * \par + * Similarly, a "draining" GridQueue works by works by atomically-incrementing a + * zero-initialized counter, returning a unique offset for the calling thread to + * read its items. Threads can safely drain until the array's logical fill-size is + * exceeded. The drain counter must be reset using GridQueue::ResetDrain or + * GridQueue::FillAndResetDrain by the host or kernel instance prior to the kernel instance that + * will be filling. (For dynamic work distribution of existing data, the corresponding fill-size + * is simply the number of elements in the array.) + * + * \par + * Iterative work management can be implemented simply with a pair of flip-flopping + * work buffers, each with an associated set of fill and drain GridQueue descriptors. + * + * \tparam OffsetT Signed integer type for global offsets + */ +template +class GridQueue +{ +private: + + /// Counter indices + enum + { + FILL = 0, + DRAIN = 1, + }; + + /// Pair of counters + OffsetT *d_counters; + +public: + + /// Returns the device allocation size in bytes needed to construct a GridQueue instance + __host__ __device__ __forceinline__ + static size_t AllocationSize() + { + return sizeof(OffsetT) * 2; + } + + + /// Constructs an invalid GridQueue descriptor + __host__ __device__ __forceinline__ GridQueue() + : + d_counters(NULL) + {} + + + /// Constructs a GridQueue descriptor around the device storage allocation + __host__ __device__ __forceinline__ GridQueue( + void *d_storage) ///< Device allocation to back the GridQueue. Must be at least as big as AllocationSize(). + : + d_counters((OffsetT*) d_storage) + {} + + + /// This operation sets the fill-size and resets the drain counter, preparing the GridQueue for draining in the next kernel instance. To be called by the host or by a kernel prior to that which will be draining. + __host__ __device__ __forceinline__ cudaError_t FillAndResetDrain( + OffsetT fill_size, + cudaStream_t stream = 0) + { + cudaError_t result = cudaErrorUnknown; + + NV_IF_TARGET(NV_IS_DEVICE, + ( + (void)stream; + d_counters[FILL] = fill_size; + d_counters[DRAIN] = 0; + result = cudaSuccess; + ), ( + OffsetT counters[2]; + counters[FILL] = fill_size; + counters[DRAIN] = 0; + result = CubDebug(cudaMemcpyAsync(d_counters, counters, sizeof(OffsetT) * 2, cudaMemcpyHostToDevice, stream)); + )); + + return result; + } + + + /// This operation resets the drain so that it may advance to meet the existing fill-size. To be called by the host or by a kernel prior to that which will be draining. + __host__ __device__ __forceinline__ cudaError_t ResetDrain(cudaStream_t stream = 0) + { + cudaError_t result = cudaErrorUnknown; + + NV_IF_TARGET(NV_IS_DEVICE, + ( + (void)stream; + d_counters[DRAIN] = 0; + result = cudaSuccess; + ), ( + result = CubDebug(cudaMemsetAsync(d_counters + DRAIN, 0, sizeof(OffsetT), stream)); + )); + + return result; + } + + + /// This operation resets the fill counter. To be called by the host or by a kernel prior to that which will be filling. + __host__ __device__ __forceinline__ cudaError_t ResetFill(cudaStream_t stream = 0) + { + cudaError_t result = cudaErrorUnknown; + + NV_IF_TARGET(NV_IS_DEVICE, + ( + (void)stream; + d_counters[FILL] = 0; + result = cudaSuccess; + ), ( + result = CubDebug(cudaMemsetAsync(d_counters + FILL, 0, sizeof(OffsetT), stream)); + )); + + return result; + } + + + /// Returns the fill-size established by the parent or by the previous kernel. + __host__ __device__ __forceinline__ cudaError_t FillSize( + OffsetT &fill_size, + cudaStream_t stream = 0) + { + cudaError_t result = cudaErrorUnknown; + + NV_IF_TARGET(NV_IS_DEVICE, + ( + (void)stream; + fill_size = d_counters[FILL]; + result = cudaSuccess; + ), ( + result = CubDebug(cudaMemcpyAsync(&fill_size, d_counters + FILL, sizeof(OffsetT), cudaMemcpyDeviceToHost, stream)); + )); + + return result; + } + + + /// Drain \p num_items from the queue. Returns offset from which to read items. To be called from CUDA kernel. + __device__ __forceinline__ OffsetT Drain(OffsetT num_items) + { + return atomicAdd(d_counters + DRAIN, num_items); + } + + + /// Fill \p num_items into the queue. Returns offset from which to write items. To be called from CUDA kernel. + __device__ __forceinline__ OffsetT Fill(OffsetT num_items) + { + return atomicAdd(d_counters + FILL, num_items); + } +}; + + +#ifndef DOXYGEN_SHOULD_SKIP_THIS // Do not document + + +/** + * Reset grid queue (call with 1 block of 1 thread) + */ +template +__global__ void FillAndResetDrainKernel( + GridQueue grid_queue, + OffsetT num_items) +{ + grid_queue.FillAndResetDrain(num_items); +} + + + +#endif // DOXYGEN_SHOULD_SKIP_THIS + + +/** @} */ // end group GridModule + +CUB_NAMESPACE_END + + diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/iterator/arg_index_input_iterator.cuh b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/iterator/arg_index_input_iterator.cuh new file mode 100644 index 0000000000000000000000000000000000000000..822869a5a54ef9d7aa79cdf223c6ffabfbc55496 --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/iterator/arg_index_input_iterator.cuh @@ -0,0 +1,254 @@ +/****************************************************************************** + * Copyright (c) 2011, Duane Merrill. All rights reserved. + * Copyright (c) 2011-2018, NVIDIA CORPORATION. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the NVIDIA CORPORATION nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ******************************************************************************/ + +/** + * \file + * Random-access iterator types + */ + +#pragma once + +#include +#include + +#include "../config.cuh" +#include "../thread/thread_load.cuh" +#include "../thread/thread_store.cuh" +#include "../util_device.cuh" + +#include + +#if (THRUST_VERSION >= 100700) + // This iterator is compatible with Thrust API 1.7 and newer + #include + #include +#endif // THRUST_VERSION + +CUB_NAMESPACE_BEGIN + +/** + * \addtogroup UtilIterator + * @{ + */ + + +/** + * \brief A random-access input wrapper for pairing dereferenced values with their corresponding indices (forming \p KeyValuePair tuples). + * + * \par Overview + * - ArgIndexInputIteratorTwraps a random access input iterator \p itr of type \p InputIteratorT. + * Dereferencing an ArgIndexInputIteratorTat offset \p i produces a \p KeyValuePair value whose + * \p key field is \p i and whose \p value field is itr[i]. + * - Can be used with any data type. + * - Can be constructed, manipulated, and exchanged within and between host and device + * functions. Wrapped host memory can only be dereferenced on the host, and wrapped + * device memory can only be dereferenced on the device. + * - Compatible with Thrust API v1.7 or newer. + * + * \par Snippet + * The code snippet below illustrates the use of \p ArgIndexInputIteratorTto + * dereference an array of doubles + * \par + * \code + * #include // or equivalently + * + * // Declare, allocate, and initialize a device array + * double *d_in; // e.g., [8.0, 6.0, 7.0, 5.0, 3.0, 0.0, 9.0] + * + * // Create an iterator wrapper + * cub::ArgIndexInputIterator itr(d_in); + * + * // Within device code: + * typedef typename cub::ArgIndexInputIterator::value_type Tuple; + * Tuple item_offset_pair.key = *itr; + * printf("%f @ %d\n", + * item_offset_pair.value, + * item_offset_pair.key); // 8.0 @ 0 + * + * itr = itr + 6; + * item_offset_pair.key = *itr; + * printf("%f @ %d\n", + * item_offset_pair.value, + * item_offset_pair.key); // 9.0 @ 6 + * + * \endcode + * + * \tparam InputIteratorT The value type of the wrapped input iterator + * \tparam OffsetT The difference type of this iterator (Default: \p ptrdiff_t) + * \tparam OutputValueT The paired value type of the tuple (Default: value type of input iterator) + */ +template < + typename InputIteratorT, + typename OffsetT = ptrdiff_t, + typename OutputValueT = cub::detail::value_t> +class ArgIndexInputIterator +{ +public: + + // Required iterator traits + typedef ArgIndexInputIterator self_type; ///< My own type + typedef OffsetT difference_type; ///< Type to express the result of subtracting one iterator from another + typedef KeyValuePair value_type; ///< The type of the element the iterator can point to + typedef value_type* pointer; ///< The type of a pointer to an element the iterator can point to + typedef value_type reference; ///< The type of a reference to an element the iterator can point to + +#if (THRUST_VERSION >= 100700) + // Use Thrust's iterator categories so we can use these iterators in Thrust 1.7 (or newer) methods + typedef typename THRUST_NS_QUALIFIER::detail::iterator_facade_category< + THRUST_NS_QUALIFIER::any_system_tag, + THRUST_NS_QUALIFIER::random_access_traversal_tag, + value_type, + reference + >::type iterator_category; ///< The iterator category +#else + typedef std::random_access_iterator_tag iterator_category; ///< The iterator category +#endif // THRUST_VERSION + +private: + + InputIteratorT itr; + difference_type offset; + +public: + + /// Constructor + __host__ __device__ __forceinline__ ArgIndexInputIterator( + InputIteratorT itr, ///< Input iterator to wrap + difference_type offset = 0) ///< OffsetT (in items) from \p itr denoting the position of the iterator + : + itr(itr), + offset(offset) + {} + + /// Postfix increment + __host__ __device__ __forceinline__ self_type operator++(int) + { + self_type retval = *this; + offset++; + return retval; + } + + /// Prefix increment + __host__ __device__ __forceinline__ self_type operator++() + { + offset++; + return *this; + } + + /// Indirection + __host__ __device__ __forceinline__ reference operator*() const + { + value_type retval; + retval.value = itr[offset]; + retval.key = offset; + return retval; + } + + /// Addition + template + __host__ __device__ __forceinline__ self_type operator+(Distance n) const + { + self_type retval(itr, offset + n); + return retval; + } + + /// Addition assignment + template + __host__ __device__ __forceinline__ self_type& operator+=(Distance n) + { + offset += n; + return *this; + } + + /// Subtraction + template + __host__ __device__ __forceinline__ self_type operator-(Distance n) const + { + self_type retval(itr, offset - n); + return retval; + } + + /// Subtraction assignment + template + __host__ __device__ __forceinline__ self_type& operator-=(Distance n) + { + offset -= n; + return *this; + } + + /// Distance + __host__ __device__ __forceinline__ difference_type operator-(self_type other) const + { + return offset - other.offset; + } + + /// Array subscript + template + __host__ __device__ __forceinline__ reference operator[](Distance n) const + { + self_type offset = (*this) + n; + return *offset; + } + + /// Structure dereference + __host__ __device__ __forceinline__ pointer operator->() + { + return &(*(*this)); + } + + /// Equal to + __host__ __device__ __forceinline__ bool operator==(const self_type& rhs) + { + return ((itr == rhs.itr) && (offset == rhs.offset)); + } + + /// Not equal to + __host__ __device__ __forceinline__ bool operator!=(const self_type& rhs) + { + return ((itr != rhs.itr) || (offset != rhs.offset)); + } + + /// Normalize + __host__ __device__ __forceinline__ void normalize() + { + itr += offset; + offset = 0; + } + + /// ostream operator + friend std::ostream& operator<<(std::ostream& os, const self_type& /*itr*/) + { + return os; + } +}; + + + +/** @} */ // end group UtilIterator + +CUB_NAMESPACE_END diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/iterator/counting_input_iterator.cuh b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/iterator/counting_input_iterator.cuh new file mode 100644 index 0000000000000000000000000000000000000000..0272543710e081fb3ecf3e90b7430e13b995e081 --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/iterator/counting_input_iterator.cuh @@ -0,0 +1,223 @@ +/****************************************************************************** + * Copyright (c) 2011, Duane Merrill. All rights reserved. + * Copyright (c) 2011-2018, NVIDIA CORPORATION. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the NVIDIA CORPORATION nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ******************************************************************************/ + +/** + * \file + * Random-access iterator types + */ + +#pragma once + +#include +#include + +#include "../thread/thread_load.cuh" +#include "../thread/thread_store.cuh" +#include "../config.cuh" +#include "../util_device.cuh" + +#if (THRUST_VERSION >= 100700) + // This iterator is compatible with Thrust API 1.7 and newer + #include + #include +#endif // THRUST_VERSION + + +CUB_NAMESPACE_BEGIN + +/** + * \addtogroup UtilIterator + * @{ + */ + +/** + * \brief A random-access input generator for dereferencing a sequence of incrementing integer values. + * + * \par Overview + * - After initializing a CountingInputIteratorTto a certain integer \p base, read references + * at \p offset will return the value \p base + \p offset. + * - Can be constructed, manipulated, dereferenced, and exchanged within and between host and device + * functions. + * - Compatible with Thrust API v1.7 or newer. + * + * \par Snippet + * The code snippet below illustrates the use of \p CountingInputIteratorTto + * dereference a sequence of incrementing integers. + * \par + * \code + * #include // or equivalently + * + * cub::CountingInputIterator itr(5); + * + * printf("%d\n", itr[0]); // 5 + * printf("%d\n", itr[1]); // 6 + * printf("%d\n", itr[2]); // 7 + * printf("%d\n", itr[50]); // 55 + * + * \endcode + * + * \tparam ValueType The value type of this iterator + * \tparam OffsetT The difference type of this iterator (Default: \p ptrdiff_t) + */ +template < + typename ValueType, + typename OffsetT = ptrdiff_t> +class CountingInputIterator +{ +public: + + // Required iterator traits + typedef CountingInputIterator self_type; ///< My own type + typedef OffsetT difference_type; ///< Type to express the result of subtracting one iterator from another + typedef ValueType value_type; ///< The type of the element the iterator can point to + typedef ValueType* pointer; ///< The type of a pointer to an element the iterator can point to + typedef ValueType reference; ///< The type of a reference to an element the iterator can point to + +#if (THRUST_VERSION >= 100700) + // Use Thrust's iterator categories so we can use these iterators in Thrust 1.7 (or newer) methods + typedef typename THRUST_NS_QUALIFIER::detail::iterator_facade_category< + THRUST_NS_QUALIFIER::any_system_tag, + THRUST_NS_QUALIFIER::random_access_traversal_tag, + value_type, + reference + >::type iterator_category; ///< The iterator category +#else + typedef std::random_access_iterator_tag iterator_category; ///< The iterator category +#endif // THRUST_VERSION + +private: + + ValueType val; + +public: + + /// Constructor + __host__ __device__ __forceinline__ CountingInputIterator( + const ValueType &val) ///< Starting value for the iterator instance to report + : + val(val) + {} + + /// Postfix increment + __host__ __device__ __forceinline__ self_type operator++(int) + { + self_type retval = *this; + val++; + return retval; + } + + /// Prefix increment + __host__ __device__ __forceinline__ self_type operator++() + { + val++; + return *this; + } + + /// Indirection + __host__ __device__ __forceinline__ reference operator*() const + { + return val; + } + + /// Addition + template + __host__ __device__ __forceinline__ self_type operator+(Distance n) const + { + self_type retval(val + (ValueType) n); + return retval; + } + + /// Addition assignment + template + __host__ __device__ __forceinline__ self_type& operator+=(Distance n) + { + val += (ValueType) n; + return *this; + } + + /// Subtraction + template + __host__ __device__ __forceinline__ self_type operator-(Distance n) const + { + self_type retval(val - (ValueType) n); + return retval; + } + + /// Subtraction assignment + template + __host__ __device__ __forceinline__ self_type& operator-=(Distance n) + { + val -= n; + return *this; + } + + /// Distance + __host__ __device__ __forceinline__ difference_type operator-(self_type other) const + { + return (difference_type) (val - other.val); + } + + /// Array subscript + template + __host__ __device__ __forceinline__ reference operator[](Distance n) const + { + return val + (ValueType) n; + } + + /// Structure dereference + __host__ __device__ __forceinline__ pointer operator->() + { + return &val; + } + + /// Equal to + __host__ __device__ __forceinline__ bool operator==(const self_type& rhs) const + { + return (val == rhs.val); + } + + /// Not equal to + __host__ __device__ __forceinline__ bool operator!=(const self_type& rhs) const + { + return (val != rhs.val); + } + + /// ostream operator + friend std::ostream& operator<<(std::ostream& os, const self_type& itr) + { + os << "[" << itr.val << "]"; + return os; + } + +}; + + + +/** @} */ // end group UtilIterator + +CUB_NAMESPACE_END diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/iterator/discard_output_iterator.cuh b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/iterator/discard_output_iterator.cuh new file mode 100644 index 0000000000000000000000000000000000000000..ac47a3ff344026bcf96c05e2981bd2adeccc43db --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/iterator/discard_output_iterator.cuh @@ -0,0 +1,208 @@ +/****************************************************************************** + * Copyright (c) 2011, Duane Merrill. All rights reserved. + * Copyright (c) 2011-2018, NVIDIA CORPORATION. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the NVIDIA CORPORATION nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ******************************************************************************/ + +/** + * \file + * Random-access iterator types + */ + +#pragma once + +#include +#include + +#include "../config.cuh" + +#if (THRUST_VERSION >= 100700) + // This iterator is compatible with Thrust API 1.7 and newer + #include + #include +#endif // THRUST_VERSION + + +CUB_NAMESPACE_BEGIN + + +/** + * \addtogroup UtilIterator + * @{ + */ + + +/** + * \brief A discard iterator + */ +template +class DiscardOutputIterator +{ +public: + + // Required iterator traits + typedef DiscardOutputIterator self_type; ///< My own type + typedef OffsetT difference_type; ///< Type to express the result of subtracting one iterator from another + typedef void value_type; ///< The type of the element the iterator can point to + typedef void pointer; ///< The type of a pointer to an element the iterator can point to + typedef void reference; ///< The type of a reference to an element the iterator can point to + +#if (THRUST_VERSION >= 100700) + // Use Thrust's iterator categories so we can use these iterators in Thrust 1.7 (or newer) methods + typedef typename THRUST_NS_QUALIFIER::detail::iterator_facade_category< + THRUST_NS_QUALIFIER::any_system_tag, + THRUST_NS_QUALIFIER::random_access_traversal_tag, + value_type, + reference + >::type iterator_category; ///< The iterator category +#else + typedef std::random_access_iterator_tag iterator_category; ///< The iterator category +#endif // THRUST_VERSION + +private: + + OffsetT offset; + +#if defined(_WIN32) || !defined(_WIN64) + // Workaround for win32 parameter-passing bug (ulonglong2 argmin DeviceReduce) + OffsetT pad[CUB_MAX(1, (16 / sizeof(OffsetT) - 1))] = {}; +#endif + +public: + + /// Constructor + __host__ __device__ __forceinline__ DiscardOutputIterator( + OffsetT offset = 0) ///< Base offset + : + offset(offset) + {} + + /// Postfix increment + __host__ __device__ __forceinline__ self_type operator++(int) + { + self_type retval = *this; + offset++; + return retval; + } + + /// Prefix increment + __host__ __device__ __forceinline__ self_type operator++() + { + offset++; + return *this; + } + + /// Indirection + __host__ __device__ __forceinline__ self_type& operator*() + { + // return self reference, which can be assigned to anything + return *this; + } + + /// Addition + template + __host__ __device__ __forceinline__ self_type operator+(Distance n) const + { + self_type retval(offset + n); + return retval; + } + + /// Addition assignment + template + __host__ __device__ __forceinline__ self_type& operator+=(Distance n) + { + offset += n; + return *this; + } + + /// Subtraction + template + __host__ __device__ __forceinline__ self_type operator-(Distance n) const + { + self_type retval(offset - n); + return retval; + } + + /// Subtraction assignment + template + __host__ __device__ __forceinline__ self_type& operator-=(Distance n) + { + offset -= n; + return *this; + } + + /// Distance + __host__ __device__ __forceinline__ difference_type operator-(self_type other) const + { + return offset - other.offset; + } + + /// Array subscript + template + __host__ __device__ __forceinline__ self_type& operator[](Distance n) + { + // return self reference, which can be assigned to anything + return *this; + } + + /// Structure dereference + __host__ __device__ __forceinline__ pointer operator->() + { + return; + } + + /// Assignment to anything else (no-op) + template + __host__ __device__ __forceinline__ void operator=(T const&) + {} + + /// Cast to void* operator + __host__ __device__ __forceinline__ operator void*() const { return NULL; } + + /// Equal to + __host__ __device__ __forceinline__ bool operator==(const self_type& rhs) + { + return (offset == rhs.offset); + } + + /// Not equal to + __host__ __device__ __forceinline__ bool operator!=(const self_type& rhs) + { + return (offset != rhs.offset); + } + + /// ostream operator + friend std::ostream& operator<<(std::ostream& os, const self_type& itr) + { + os << "[" << itr.offset << "]"; + return os; + } + +}; + + +/** @} */ // end group UtilIterator + +CUB_NAMESPACE_END diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/iterator/transform_input_iterator.cuh b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/iterator/transform_input_iterator.cuh new file mode 100644 index 0000000000000000000000000000000000000000..2ef7269c6760040d8d0ed9b9345f16c29b5fa9f0 --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/iterator/transform_input_iterator.cuh @@ -0,0 +1,241 @@ +/****************************************************************************** + * Copyright (c) 2011, Duane Merrill. All rights reserved. + * Copyright (c) 2011-2018, NVIDIA CORPORATION. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the NVIDIA CORPORATION nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ******************************************************************************/ + +/** + * \file + * Random-access iterator types + */ + +#pragma once + +#include +#include + +#include "../thread/thread_load.cuh" +#include "../thread/thread_store.cuh" +#include "../config.cuh" +#include "../util_device.cuh" + +#if (THRUST_VERSION >= 100700) + // This iterator is compatible with Thrust API 1.7 and newer + #include + #include +#endif // THRUST_VERSION + + +CUB_NAMESPACE_BEGIN + +/** + * \addtogroup UtilIterator + * @{ + */ + + +/** + * \brief A random-access input wrapper for transforming dereferenced values. + * + * \par Overview + * - TransformInputIteratorTwraps a unary conversion functor of type \p + * ConversionOp and a random-access input iterator of type InputIteratorT, + * using the former to produce references of type \p ValueType from the latter. + * - Can be used with any data type. + * - Can be constructed, manipulated, and exchanged within and between host and device + * functions. Wrapped host memory can only be dereferenced on the host, and wrapped + * device memory can only be dereferenced on the device. + * - Compatible with Thrust API v1.7 or newer. + * + * \par Snippet + * The code snippet below illustrates the use of \p TransformInputIteratorTto + * dereference an array of integers, tripling the values and converting them to doubles. + * \par + * \code + * #include // or equivalently + * + * // Functor for tripling integer values and converting to doubles + * struct TripleDoubler + * { + * __host__ __device__ __forceinline__ + * double operator()(const int &a) const { + * return double(a * 3); + * } + * }; + * + * // Declare, allocate, and initialize a device array + * int *d_in; // e.g., [8, 6, 7, 5, 3, 0, 9] + * TripleDoubler conversion_op; + * + * // Create an iterator wrapper + * cub::TransformInputIterator itr(d_in, conversion_op); + * + * // Within device code: + * printf("%f\n", itr[0]); // 24.0 + * printf("%f\n", itr[1]); // 18.0 + * printf("%f\n", itr[6]); // 27.0 + * + * \endcode + * + * \tparam ValueType The value type of this iterator + * \tparam ConversionOp Unary functor type for mapping objects of type \p InputType to type \p ValueType. Must have member ValueType operator()(const InputType &datum). + * \tparam InputIteratorT The type of the wrapped input iterator + * \tparam OffsetT The difference type of this iterator (Default: \p ptrdiff_t) + * + */ +template < + typename ValueType, + typename ConversionOp, + typename InputIteratorT, + typename OffsetT = ptrdiff_t> +class TransformInputIterator +{ +public: + + // Required iterator traits + typedef TransformInputIterator self_type; ///< My own type + typedef OffsetT difference_type; ///< Type to express the result of subtracting one iterator from another + typedef ValueType value_type; ///< The type of the element the iterator can point to + typedef ValueType* pointer; ///< The type of a pointer to an element the iterator can point to + typedef ValueType reference; ///< The type of a reference to an element the iterator can point to + +#if (THRUST_VERSION >= 100700) + // Use Thrust's iterator categories so we can use these iterators in Thrust 1.7 (or newer) methods + typedef typename THRUST_NS_QUALIFIER::detail::iterator_facade_category< + THRUST_NS_QUALIFIER::any_system_tag, + THRUST_NS_QUALIFIER::random_access_traversal_tag, + value_type, + reference + >::type iterator_category; ///< The iterator category +#else + typedef std::random_access_iterator_tag iterator_category; ///< The iterator category +#endif // THRUST_VERSION + +private: + + ConversionOp conversion_op; + InputIteratorT input_itr; + +public: + + /// Constructor + __host__ __device__ __forceinline__ TransformInputIterator( + InputIteratorT input_itr, ///< Input iterator to wrap + ConversionOp conversion_op) ///< Conversion functor to wrap + : + conversion_op(conversion_op), + input_itr(input_itr) + {} + + /// Postfix increment + __host__ __device__ __forceinline__ self_type operator++(int) + { + self_type retval = *this; + input_itr++; + return retval; + } + + /// Prefix increment + __host__ __device__ __forceinline__ self_type operator++() + { + input_itr++; + return *this; + } + + /// Indirection + __host__ __device__ __forceinline__ reference operator*() const + { + return conversion_op(*input_itr); + } + + /// Addition + template + __host__ __device__ __forceinline__ self_type operator+(Distance n) const + { + self_type retval(input_itr + n, conversion_op); + return retval; + } + + /// Addition assignment + template + __host__ __device__ __forceinline__ self_type& operator+=(Distance n) + { + input_itr += n; + return *this; + } + + /// Subtraction + template + __host__ __device__ __forceinline__ self_type operator-(Distance n) const + { + self_type retval(input_itr - n, conversion_op); + return retval; + } + + /// Subtraction assignment + template + __host__ __device__ __forceinline__ self_type& operator-=(Distance n) + { + input_itr -= n; + return *this; + } + + /// Distance + __host__ __device__ __forceinline__ difference_type operator-(self_type other) const + { + return input_itr - other.input_itr; + } + + /// Array subscript + template + __host__ __device__ __forceinline__ reference operator[](Distance n) const + { + return conversion_op(input_itr[n]); + } + + /// Equal to + __host__ __device__ __forceinline__ bool operator==(const self_type& rhs) const + { + return (input_itr == rhs.input_itr); + } + + /// Not equal to + __host__ __device__ __forceinline__ bool operator!=(const self_type& rhs) const + { + return (input_itr != rhs.input_itr); + } + + /// ostream operator + friend std::ostream& operator<<(std::ostream& os, const self_type& /* itr */) + { + return os; + } +}; + + + +/** @} */ // end group UtilIterator + +CUB_NAMESPACE_END diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/thread/thread_load.cuh b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/thread/thread_load.cuh new file mode 100644 index 0000000000000000000000000000000000000000..73d251c33168506e55b64f0e373ffa8a7a4c027d --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/thread/thread_load.cuh @@ -0,0 +1,409 @@ +/****************************************************************************** + * Copyright (c) 2011, Duane Merrill. All rights reserved. + * Copyright (c) 2011-2018, NVIDIA CORPORATION. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the NVIDIA CORPORATION nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ******************************************************************************/ + +/** + * \file + * Thread utilities for reading memory using PTX cache modifiers. + */ + +#pragma once + +#include + +#include "../config.cuh" +#include "../util_ptx.cuh" +#include "../util_type.cuh" + +CUB_NAMESPACE_BEGIN + +/** + * \addtogroup UtilIo + * @{ + */ + +//----------------------------------------------------------------------------- +// Tags and constants +//----------------------------------------------------------------------------- + +/** + * \brief Enumeration of cache modifiers for memory load operations. + */ +enum CacheLoadModifier +{ + LOAD_DEFAULT, ///< Default (no modifier) + LOAD_CA, ///< Cache at all levels + LOAD_CG, ///< Cache at global level + LOAD_CS, ///< Cache streaming (likely to be accessed once) + LOAD_CV, ///< Cache as volatile (including cached system lines) + LOAD_LDG, ///< Cache as texture + LOAD_VOLATILE, ///< Volatile (any memory space) +}; + + +/** + * \name Thread I/O (cache modified) + * @{ + */ + +/** + * \brief Thread utility for reading memory using cub::CacheLoadModifier cache modifiers. Can be used to load any data type. + * + * \par Example + * \code + * #include // or equivalently + * + * // 32-bit load using cache-global modifier: + * int *d_in; + * int val = cub::ThreadLoad(d_in + threadIdx.x); + * + * // 16-bit load using default modifier + * short *d_in; + * short val = cub::ThreadLoad(d_in + threadIdx.x); + * + * // 256-bit load using cache-volatile modifier + * double4 *d_in; + * double4 val = cub::ThreadLoad(d_in + threadIdx.x); + * + * // 96-bit load using cache-streaming modifier + * struct TestFoo { bool a; short b; }; + * TestFoo *d_struct; + * TestFoo val = cub::ThreadLoad(d_in + threadIdx.x); + * \endcode + * + * \tparam MODIFIER [inferred] CacheLoadModifier enumeration + * \tparam InputIteratorT [inferred] Input iterator type \iterator + */ +template +__device__ __forceinline__ cub::detail::value_t +ThreadLoad(InputIteratorT itr); + +//@} end member group + + +#ifndef DOXYGEN_SHOULD_SKIP_THIS // Do not document + + +/// Helper structure for templated load iteration (inductive case) +template +struct IterateThreadLoad +{ + template + static __device__ __forceinline__ void Load(T const *ptr, T *vals) + { + vals[COUNT] = ThreadLoad(ptr + COUNT); + IterateThreadLoad::template Load(ptr, vals); + } + + template + static __device__ __forceinline__ void Dereference(InputIteratorT itr, T *vals) + { + vals[COUNT] = itr[COUNT]; + IterateThreadLoad::Dereference(itr, vals); + } +}; + + +/// Helper structure for templated load iteration (termination case) +template +struct IterateThreadLoad +{ + template + static __device__ __forceinline__ void Load(T const * /*ptr*/, T * /*vals*/) {} + + template + static __device__ __forceinline__ void Dereference(InputIteratorT /*itr*/, T * /*vals*/) {} +}; + + +/** + * Define a uint4 (16B) ThreadLoad specialization for the given Cache load modifier + */ +#define _CUB_LOAD_16(cub_modifier, ptx_modifier) \ + template<> \ + __device__ __forceinline__ uint4 ThreadLoad(uint4 const *ptr) \ + { \ + uint4 retval; \ + asm volatile ("ld."#ptx_modifier".v4.u32 {%0, %1, %2, %3}, [%4];" : \ + "=r"(retval.x), \ + "=r"(retval.y), \ + "=r"(retval.z), \ + "=r"(retval.w) : \ + _CUB_ASM_PTR_(ptr)); \ + return retval; \ + } \ + template<> \ + __device__ __forceinline__ ulonglong2 ThreadLoad(ulonglong2 const *ptr) \ + { \ + ulonglong2 retval; \ + asm volatile ("ld."#ptx_modifier".v2.u64 {%0, %1}, [%2];" : \ + "=l"(retval.x), \ + "=l"(retval.y) : \ + _CUB_ASM_PTR_(ptr)); \ + return retval; \ + } + +/** + * Define a uint2 (8B) ThreadLoad specialization for the given Cache load modifier + */ +#define _CUB_LOAD_8(cub_modifier, ptx_modifier) \ + template<> \ + __device__ __forceinline__ ushort4 ThreadLoad(ushort4 const *ptr) \ + { \ + ushort4 retval; \ + asm volatile ("ld."#ptx_modifier".v4.u16 {%0, %1, %2, %3}, [%4];" : \ + "=h"(retval.x), \ + "=h"(retval.y), \ + "=h"(retval.z), \ + "=h"(retval.w) : \ + _CUB_ASM_PTR_(ptr)); \ + return retval; \ + } \ + template<> \ + __device__ __forceinline__ uint2 ThreadLoad(uint2 const *ptr) \ + { \ + uint2 retval; \ + asm volatile ("ld."#ptx_modifier".v2.u32 {%0, %1}, [%2];" : \ + "=r"(retval.x), \ + "=r"(retval.y) : \ + _CUB_ASM_PTR_(ptr)); \ + return retval; \ + } \ + template<> \ + __device__ __forceinline__ unsigned long long ThreadLoad(unsigned long long const *ptr) \ + { \ + unsigned long long retval; \ + asm volatile ("ld."#ptx_modifier".u64 %0, [%1];" : \ + "=l"(retval) : \ + _CUB_ASM_PTR_(ptr)); \ + return retval; \ + } + +/** + * Define a uint (4B) ThreadLoad specialization for the given Cache load modifier + */ +#define _CUB_LOAD_4(cub_modifier, ptx_modifier) \ + template<> \ + __device__ __forceinline__ unsigned int ThreadLoad(unsigned int const *ptr) \ + { \ + unsigned int retval; \ + asm volatile ("ld."#ptx_modifier".u32 %0, [%1];" : \ + "=r"(retval) : \ + _CUB_ASM_PTR_(ptr)); \ + return retval; \ + } + + +/** + * Define a unsigned short (2B) ThreadLoad specialization for the given Cache load modifier + */ +#define _CUB_LOAD_2(cub_modifier, ptx_modifier) \ + template<> \ + __device__ __forceinline__ unsigned short ThreadLoad(unsigned short const *ptr) \ + { \ + unsigned short retval; \ + asm volatile ("ld."#ptx_modifier".u16 %0, [%1];" : \ + "=h"(retval) : \ + _CUB_ASM_PTR_(ptr)); \ + return retval; \ + } + + +/** + * Define an unsigned char (1B) ThreadLoad specialization for the given Cache load modifier + */ +#define _CUB_LOAD_1(cub_modifier, ptx_modifier) \ + template<> \ + __device__ __forceinline__ unsigned char ThreadLoad(unsigned char const *ptr) \ + { \ + unsigned short retval; \ + asm volatile ( \ + "{" \ + " .reg .u8 datum;" \ + " ld."#ptx_modifier".u8 datum, [%1];" \ + " cvt.u16.u8 %0, datum;" \ + "}" : \ + "=h"(retval) : \ + _CUB_ASM_PTR_(ptr)); \ + return (unsigned char) retval; \ + } + + +/** + * Define powers-of-two ThreadLoad specializations for the given Cache load modifier + */ +#define _CUB_LOAD_ALL(cub_modifier, ptx_modifier) \ + _CUB_LOAD_16(cub_modifier, ptx_modifier) \ + _CUB_LOAD_8(cub_modifier, ptx_modifier) \ + _CUB_LOAD_4(cub_modifier, ptx_modifier) \ + _CUB_LOAD_2(cub_modifier, ptx_modifier) \ + _CUB_LOAD_1(cub_modifier, ptx_modifier) \ + + +/** + * Define powers-of-two ThreadLoad specializations for the various Cache load modifiers + */ +_CUB_LOAD_ALL(LOAD_CA, ca) +_CUB_LOAD_ALL(LOAD_CG, cg) +_CUB_LOAD_ALL(LOAD_CS, cs) +_CUB_LOAD_ALL(LOAD_CV, cv) +_CUB_LOAD_ALL(LOAD_LDG, global.nc) + + +// Macro cleanup +#undef _CUB_LOAD_ALL +#undef _CUB_LOAD_1 +#undef _CUB_LOAD_2 +#undef _CUB_LOAD_4 +#undef _CUB_LOAD_8 +#undef _CUB_LOAD_16 + + + +/** + * ThreadLoad definition for LOAD_DEFAULT modifier on iterator types + */ +template +__device__ __forceinline__ cub::detail::value_t +ThreadLoad(InputIteratorT itr, + Int2Type /*modifier*/, + Int2Type /*is_pointer*/) +{ + return *itr; +} + + +/** + * ThreadLoad definition for LOAD_DEFAULT modifier on pointer types + */ +template +__device__ __forceinline__ T ThreadLoad( + T *ptr, + Int2Type /*modifier*/, + Int2Type /*is_pointer*/) +{ + return *ptr; +} + + +/** + * ThreadLoad definition for LOAD_VOLATILE modifier on primitive pointer types + */ +template +__device__ __forceinline__ T ThreadLoadVolatilePointer( + T *ptr, + Int2Type /*is_primitive*/) +{ + T retval = *reinterpret_cast(ptr); + return retval; +} + + +/** + * ThreadLoad definition for LOAD_VOLATILE modifier on non-primitive pointer types + */ +template +__device__ __forceinline__ T ThreadLoadVolatilePointer( + T *ptr, + Int2Type /*is_primitive*/) +{ + typedef typename UnitWord::VolatileWord VolatileWord; // Word type for memcopying + + const int VOLATILE_MULTIPLE = sizeof(T) / sizeof(VolatileWord); + + T retval; + VolatileWord *words = reinterpret_cast(&retval); + IterateThreadLoad<0, VOLATILE_MULTIPLE>::Dereference( + reinterpret_cast(ptr), + words); + return retval; +} + + +/** + * ThreadLoad definition for LOAD_VOLATILE modifier on pointer types + */ +template +__device__ __forceinline__ T ThreadLoad( + T *ptr, + Int2Type /*modifier*/, + Int2Type /*is_pointer*/) +{ + // Apply tags for partial-specialization + return ThreadLoadVolatilePointer(ptr, Int2Type::PRIMITIVE>()); +} + + +/** + * ThreadLoad definition for generic modifiers on pointer types + */ +template +__device__ __forceinline__ T ThreadLoad( + T const *ptr, + Int2Type /*modifier*/, + Int2Type /*is_pointer*/) +{ + typedef typename UnitWord::DeviceWord DeviceWord; + + const int DEVICE_MULTIPLE = sizeof(T) / sizeof(DeviceWord); + + DeviceWord words[DEVICE_MULTIPLE]; + + IterateThreadLoad<0, DEVICE_MULTIPLE>::template Load( + reinterpret_cast(const_cast(ptr)), + words); + + return *reinterpret_cast(words); +} + + +/** + * ThreadLoad definition for generic modifiers + */ +template < + CacheLoadModifier MODIFIER, + typename InputIteratorT> +__device__ __forceinline__ cub::detail::value_t +ThreadLoad(InputIteratorT itr) +{ + // Apply tags for partial-specialization + return ThreadLoad( + itr, + Int2Type(), + Int2Type::value>()); +} + + + +#endif // DOXYGEN_SHOULD_SKIP_THIS + + +/** @} */ // end group UtilIo + + +CUB_NAMESPACE_END diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/thread/thread_search.cuh b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/thread/thread_search.cuh new file mode 100644 index 0000000000000000000000000000000000000000..62b3cdb4e5d499c4d6a8611ecf2aca06d964ecf5 --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/thread/thread_search.cuh @@ -0,0 +1,185 @@ +/****************************************************************************** + * Copyright (c) 2011, Duane Merrill. All rights reserved. + * Copyright (c) 2011-2018, NVIDIA CORPORATION. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the NVIDIA CORPORATION nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ******************************************************************************/ + +/** + * \file + * Thread utilities for sequential search + */ + +#pragma once + +#include +#include +#include +#include + +#include + +CUB_NAMESPACE_BEGIN + + +/** + * Computes the begin offsets into A and B for the specific diagonal + */ +template < + typename AIteratorT, + typename BIteratorT, + typename OffsetT, + typename CoordinateT> +__host__ __device__ __forceinline__ void MergePathSearch( + OffsetT diagonal, + AIteratorT a, + BIteratorT b, + OffsetT a_len, + OffsetT b_len, + CoordinateT& path_coordinate) +{ + /// The value type of the input iterator + using T = cub::detail::value_t; + + OffsetT split_min = CUB_MAX(diagonal - b_len, 0); + OffsetT split_max = CUB_MIN(diagonal, a_len); + + while (split_min < split_max) + { + OffsetT split_pivot = (split_min + split_max) >> 1; + if (a[split_pivot] <= b[diagonal - split_pivot - 1]) + { + // Move candidate split range up A, down B + split_min = split_pivot + 1; + } + else + { + // Move candidate split range up B, down A + split_max = split_pivot; + } + } + + path_coordinate.x = CUB_MIN(split_min, a_len); + path_coordinate.y = diagonal - split_min; +} + + + +/** + * \brief Returns the offset of the first value within \p input which does not compare less than \p val + */ +template < + typename InputIteratorT, + typename OffsetT, + typename T> +__device__ __forceinline__ OffsetT LowerBound( + InputIteratorT input, ///< [in] Input sequence + OffsetT num_items, ///< [in] Input sequence length + T val) ///< [in] Search key +{ + OffsetT retval = 0; + while (num_items > 0) + { + OffsetT half = num_items >> 1; + if (input[retval + half] < val) + { + retval = retval + (half + 1); + num_items = num_items - (half + 1); + } + else + { + num_items = half; + } + } + + return retval; +} + + +/** + * \brief Returns the offset of the first value within \p input which compares greater than \p val + */ +template < + typename InputIteratorT, + typename OffsetT, + typename T> +__device__ __forceinline__ OffsetT UpperBound( + InputIteratorT input, ///< [in] Input sequence + OffsetT num_items, ///< [in] Input sequence length + T val) ///< [in] Search key +{ + OffsetT retval = 0; + while (num_items > 0) + { + OffsetT half = num_items >> 1; + if (val < input[retval + half]) + { + num_items = half; + } + else + { + retval = retval + (half + 1); + num_items = num_items - (half + 1); + } + } + + return retval; +} + + +#if defined(__CUDA_FP16_TYPES_EXIST__) +template < + typename InputIteratorT, + typename OffsetT> +__device__ __forceinline__ OffsetT UpperBound( + InputIteratorT input, ///< [in] Input sequence + OffsetT num_items, ///< [in] Input sequence length + __half val) ///< [in] Search key +{ + OffsetT retval = 0; + while (num_items > 0) + { + OffsetT half = num_items >> 1; + + bool lt; + NV_IF_TARGET(NV_PROVIDES_SM_53, + (lt = val < input[retval + half];), + (lt = __half2float(val) < __half2float(input[retval + half]);)); + + if (lt) + { + num_items = half; + } + else + { + retval = retval + (half + 1); + num_items = num_items - (half + 1); + } + } + + return retval; +} +#endif + +CUB_NAMESPACE_END diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/thread/thread_sort.cuh b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/thread/thread_sort.cuh new file mode 100644 index 0000000000000000000000000000000000000000..5d486789684c3e1c2c59c6cfc7044398c0ce51da --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/thread/thread_sort.cuh @@ -0,0 +1,105 @@ +/****************************************************************************** + * Copyright (c) 2011-2021, NVIDIA CORPORATION. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the NVIDIA CORPORATION nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ******************************************************************************/ + +#pragma once + +#include "../config.cuh" +#include "../util_ptx.cuh" +#include "../util_type.cuh" + +CUB_NAMESPACE_BEGIN + + +template +__device__ __forceinline__ void Swap(T &lhs, T &rhs) +{ + T temp = lhs; + lhs = rhs; + rhs = temp; +} + + +/** + * @brief Sorts data using odd-even sort method + * + * The sorting method is stable. Further details can be found in: + * A. Nico Habermann. Parallel neighbor sort (or the glory of the induction + * principle). Technical Report AD-759 248, Carnegie Mellon University, 1972. + * + * @tparam KeyT + * Key type + * + * @tparam ValueT + * Value type. If `cub::NullType` is used as `ValueT`, only keys are sorted. + * + * @tparam CompareOp + * functor type having member `bool operator()(KeyT lhs, KeyT rhs)` + * + * @tparam ITEMS_PER_THREAD + * The number of items per thread + * + * @param[in,out] keys + * Keys to sort + * + * @param[in,out] items + * Values to sort + * + * @param[in] compare_op + * Comparison function object which returns true if the first argument is + * ordered before the second + */ +template +__device__ __forceinline__ void +StableOddEvenSort(KeyT (&keys)[ITEMS_PER_THREAD], + ValueT (&items)[ITEMS_PER_THREAD], + CompareOp compare_op) +{ + constexpr bool KEYS_ONLY = std::is_same::value; + + #pragma unroll + for (int i = 0; i < ITEMS_PER_THREAD; ++i) + { + #pragma unroll + for (int j = 1 & i; j < ITEMS_PER_THREAD - 1; j += 2) + { + if (compare_op(keys[j + 1], keys[j])) + { + Swap(keys[j], keys[j + 1]); + if (!KEYS_ONLY) + { + Swap(items[j], items[j + 1]); + } + } + } // inner loop + } // outer loop +} + + +CUB_NAMESPACE_END diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/warp/specializations/warp_exchange_shfl.cuh b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/warp/specializations/warp_exchange_shfl.cuh new file mode 100644 index 0000000000000000000000000000000000000000..38e2cd81b9789040e72f3b4ed95b2aaea3447cd8 --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/warp/specializations/warp_exchange_shfl.cuh @@ -0,0 +1,327 @@ +/****************************************************************************** + * Copyright (c) 2011-2023, NVIDIA CORPORATION. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the NVIDIA CORPORATION nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ******************************************************************************/ + +#pragma once + +#include +#include +#include + +CUB_NAMESPACE_BEGIN + +namespace detail +{ + +template +class WarpExchangeShfl +{ + static_assert(PowerOfTwo::VALUE, + "LOGICAL_WARP_THREADS must be a power of two"); + + static_assert(ITEMS_PER_THREAD == LOGICAL_WARP_THREADS, + "WARP_EXCHANGE_SHUFFLE currently only works when ITEMS_PER_THREAD == " + "LOGICAL_WARP_THREADS"); + + constexpr static bool IS_ARCH_WARP = LOGICAL_WARP_THREADS == CUB_WARP_THREADS(0); + + // concrete recursion class + template + class CompileTimeArray : protected CompileTimeArray + { + protected: + InputT val; + + template + __device__ void Foreach(const bool xor_bit_set, const unsigned mask) + { + // The implementation here is a recursive divide-and-conquer approach + // that takes inspiration from: + // https://forums.developer.nvidia.com/t/transposing-register-held-matrices-with-warp-shuffles-need-help/38652/2 + // + // At its core, the problem can be boiled down to transposing the matrix + // + // A B + // C D + // + // by swapping the off-diagonal elements/sub-matrices B and C recursively. + // + // This implementation requires power-of-two matrices. In order to avoid + // the use of local or shared memory, all index computation has to occur + // at compile-time, since registers cannot be indexed dynamically. + // Furthermore, using recursive templates reduces the mental load on the + // optimizer, since lowering for-loops into registers oftentimes requires + // finagling them with #pragma unroll, which leads to brittle code. + // + // To illustrate this algorithm, let's pretend we have warpSize = 8, + // where t0, ..., t7 denote the 8 threads, and thread i has an array of + // size 8 with data = [Ai, Bi, ..., Hi] (the columns in the schematics). + // + // In the first round, we exchange the largest 4x4 off-diagonal + // submatrix. Boxes illustrate the submatrices to be exchanged. + // + // ROUND 1 + // ======= + // t0 t1 t2 t3 t4 t5 t6 t7 + // ┌──────────────┐ + // A0 A1 A2 A3 │A4 A5 A6 A7│ NUM_ENTRIES == 4 tells us how many + // │ │ entries we have in a submatrix, + // │ │ in this case 4 and the size of + // B0 B1 B2 B3 │B4 B5 B6 B7│ the jumps between submatrices. + // │ │ + // │ │ 1. t[0,1,2,3] data[4] swap with t[4,5,6,7]'s data[0] + // C0 C1 C2 C3 │C4 C5 C6 C7│ 2. t[0,1,2,3] data[5] swap with t[4,5,6,7]'s data[1] + // │ │ 3. t[0,1,2,3] data[6] swap with t[4,5,6,7]'s data[2] + // │ │ 4. t[0,1,2,3] data[7] swap with t[4,5,6,7]'s data[3] + // D0 D1 D2 D3 │D4 D5 D6 D7│ + // └──────────────┘ + // ┌──────────────┐ + // │E0 E1 E2 E3│ E4 E5 E6 E7 + // │ │ + // │ │ + // │F0 F1 F2 F3│ F4 F5 F6 F7 + // │ │ + // │ │ + // │G0 G1 G2 G3│ G4 G5 G6 G7 + // │ │ + // │ │ + // │H0 H1 H2 H3│ H4 H5 H6 H7 + // └──────────────┘ + // + // ROUND 2 + // ======= + // t0 t1 t2 t3 t4 t5 t6 t7 + // ┌──────┐ ┌──────┐ + // A0 A1 │A2 A3│ E0 E1 │E2 E3│ NUM_ENTRIES == 2 so we have 2 + // │ │ │ │ submatrices per thread and there + // │ │ │ │ are 2 elements between these + // B0 B1 │B2 B3│ F0 F1 │F2 F3│ submatrices. + // └──────┘ └──────┘ + // ┌──────┐ ┌──────┐ 1. t[0,1,4,5] data[2] swap with t[2,3,6,7]'s data[0] + // │C0 C1│ C2 C3 │G0 G1│ G2 G3 2. t[0,1,4,5] data[3] swap with t[2,3,6,7]'s data[1] + // │ │ │ │ 3. t[0,1,4,5] data[6] swap with t[2,3,6,7]'s data[4] + // │ │ │ │ 4. t[0,1,4,5] data[7] swap with t[2,3,6,7]'s data[5] + // │D0 D1│ D2 D3 │H0 H1│ H2 H3 + // └──────┘ └──────┘ + // ┌──────┐ ┌──────┐ + // A4 A5 │A6 A7│ E4 E5 │E6 E7│ + // │ │ │ │ + // │ │ │ │ + // B4 B5 │B6 B7│ F4 F5 │F6 F7│ + // └──────┘ └──────┘ + // ┌──────┐ ┌──────┐ + // │C4 C5│ C6 C7 │G4 G5│ G6 G7 + // │ │ │ │ + // │ │ │ │ + // │D4 D5│ D6 D7 │H4 H5│ H6 H7 + // └──────┘ └──────┘ + // + // ROUND 3 + // ======= + // t0 t1 t2 t3 t4 t5 t6 t7 + // ┌──┐ ┌──┐ ┌──┐ ┌──┐ + // A0 │A1│ C0 │C1│ E0 │E1│ G0 │G1│ NUM_ENTRIES == 1 so we have 4 + // └──┘ └──┘ └──┘ └──┘ submatrices per thread and there + // ┌──┐ ┌──┐ ┌──┐ ┌──┐ is 1 element between these + // │B0│ B1 │D0│ D1 │F0│ F1 │H0│ H1 submatrices. + // └──┘ └──┘ └──┘ └──┘ + // ┌──┐ ┌──┐ ┌──┐ ┌──┐ 1. t[0,2,4,6] data[1] swap with t[1,3,5,7]'s data[0] + // A2 │A3│ C2 │C3│ E2 │E3│ G2 │G3│ 2. t[0,2,4,6] data[3] swap with t[1,3,5,7]'s data[2] + // └──┘ └──┘ └──┘ └──┘ 3. t[0,2,4,6] data[5] swap with t[1,3,5,7]'s data[4] + // ┌──┐ ┌──┐ ┌──┐ ┌──┐ 4. t[0,2,4,6] data[7] swap with t[1,3,5,7]'s data[6] + // │B2│ B3 │D2│ D3 │F2│ F3 │H2│ H3 + // └──┘ └──┘ └──┘ └──┘ + // ┌──┐ ┌──┐ ┌──┐ ┌──┐ + // A4 │A5│ C4 │C5│ E4 │E5│ G4 │G5│ + // └──┘ └──┘ └──┘ └──┘ + // ┌──┐ ┌──┐ ┌──┐ ┌──┐ + // │B4│ B5 │D4│ D5 │F4│ F5 │H4│ H5 + // └──┘ └──┘ └──┘ └──┘ + // ┌──┐ ┌──┐ ┌──┐ ┌──┐ + // A6 │A7│ C6 │C7│ E6 │E7│ G6 │G7│ + // └──┘ └──┘ └──┘ └──┘ + // ┌──┐ ┌──┐ ┌──┐ ┌──┐ + // │B6│ B7 │D6│ D7 │F6│ F7 │H6│ H7 + // └──┘ └──┘ └──┘ └──┘ + // + // RESULT + // ====== + // t0 t1 t2 t3 t4 t5 t6 t7 + // + // A0 B0 C0 D0 E0 F0 G0 H0 + // + // + // A1 B1 C1 D1 E1 F1 G1 H1 + // + // + // A2 B2 C2 D2 E2 F2 G2 H2 + // + // + // A3 B3 C3 D3 E3 F3 G3 H3 + // + // + // A4 B4 C4 D4 E4 F4 G4 H4 + // + // + // A5 B5 C5 D5 E5 F5 G5 H5 + // + // + // A6 B6 C6 D6 E6 F6 G6 H6 + // + // + // A7 B7 C7 D7 E7 F7 G7 H7 + // + + // NOTE: Do *NOT* try to refactor this code to use a reference, since nvcc + // tends to choke on it and then drop everything into local memory. + const InputT send_val = (xor_bit_set ? CompileTimeArray::val + : CompileTimeArray::val); + const InputT recv_val = __shfl_xor_sync(mask, send_val, NUM_ENTRIES, LOGICAL_WARP_THREADS); + (xor_bit_set ? CompileTimeArray::val + : CompileTimeArray::val) = recv_val; + + constexpr int next_idx = IDX + 1 + ((IDX + 1) % NUM_ENTRIES == 0) * NUM_ENTRIES; + CompileTimeArray::template Foreach(xor_bit_set, mask); + } + + // terminate recursion + __device__ void TransposeImpl(unsigned int, unsigned int, Int2Type<0>) {} + + template + __device__ void TransposeImpl(const unsigned int lane_id, + const unsigned int mask, + Int2Type) + { + const bool xor_bit_set = lane_id & NUM_ENTRIES; + Foreach(xor_bit_set, mask); + + TransposeImpl(lane_id, mask, Int2Type()); + } + + public: + __device__ CompileTimeArray(const InputT (&input_items)[ITEMS_PER_THREAD], + OutputT (&output_items)[ITEMS_PER_THREAD]) + : CompileTimeArray{input_items, output_items} + , val{input_items[IDX]} + {} + + __device__ ~CompileTimeArray() { this->output_items[IDX] = val; } + + __device__ void Transpose(const unsigned int lane_id, const unsigned int mask) + { + TransposeImpl(lane_id, mask, Int2Type()); + } + }; + + // terminating partial specialization + template + class CompileTimeArray + { + protected: + // used for dumping back the individual values after transposing + InputT (&output_items)[ITEMS_PER_THREAD]; + + template + __device__ void Foreach(bool, unsigned) + {} + + public: + __device__ CompileTimeArray(const InputT (&)[ITEMS_PER_THREAD], + OutputT (&output_items)[ITEMS_PER_THREAD]) + : output_items{output_items} + {} + }; + + + const unsigned int lane_id; + const unsigned int warp_id; + const unsigned int member_mask; + +public: + using TempStorage = NullType; + + WarpExchangeShfl() = delete; + + explicit __device__ __forceinline__ WarpExchangeShfl(TempStorage &) + : lane_id(IS_ARCH_WARP ? LaneId() : (LaneId() % LOGICAL_WARP_THREADS)) + , warp_id(IS_ARCH_WARP ? 0 : (LaneId() / LOGICAL_WARP_THREADS)) + , member_mask(WarpMask(warp_id)) + {} + + template + __device__ __forceinline__ void BlockedToStriped(const InputT (&input_items)[ITEMS_PER_THREAD], + OutputT (&output_items)[ITEMS_PER_THREAD]) + { + CompileTimeArray arr{input_items, output_items}; + arr.Transpose(lane_id, member_mask); + } + + template + __device__ __forceinline__ void StripedToBlocked(const InputT (&input_items)[ITEMS_PER_THREAD], + OutputT (&output_items)[ITEMS_PER_THREAD]) + { + BlockedToStriped(input_items, output_items); + } + + // Trick to keep the compiler from inferring that the + // condition in the static_assert is always false. + template + struct dependent_false + { + static constexpr bool value = false; + }; + + template + __device__ __forceinline__ void + ScatterToStriped(InputT (&)[ITEMS_PER_THREAD], + OffsetT (&)[ITEMS_PER_THREAD]) + { + static_assert(dependent_false::value, + "Shuffle specialization of warp exchange does not support\n" + "ScatterToStriped(InputT (&items)[ITEMS_PER_THREAD],\n" + " OffsetT (&ranks)[ITEMS_PER_THREAD])"); + } + + template + __device__ __forceinline__ void + ScatterToStriped(const InputT (&)[ITEMS_PER_THREAD], + OutputT (&)[ITEMS_PER_THREAD], + OffsetT (&)[ITEMS_PER_THREAD]) + { + static_assert(dependent_false::value, + "Shuffle specialization of warp exchange does not support\n" + "ScatterToStriped(const InputT (&input_items)[ITEMS_PER_THREAD],\n" + " OutputT (&output_items)[ITEMS_PER_THREAD],\n" + " OffsetT (&ranks)[ITEMS_PER_THREAD])"); + } +}; + +} // namespace detail + +CUB_NAMESPACE_END diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/warp/specializations/warp_exchange_smem.cuh b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/warp/specializations/warp_exchange_smem.cuh new file mode 100644 index 0000000000000000000000000000000000000000..1a377d8e68438107739de95bbe1174e49aae1b85 --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/warp/specializations/warp_exchange_smem.cuh @@ -0,0 +1,178 @@ +/****************************************************************************** + * Copyright (c) 2011-2023, NVIDIA CORPORATION. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the NVIDIA CORPORATION nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ******************************************************************************/ + +/** + * @file + * The cub::WarpExchangeSmem class provides [collective](index.html#sec0) + * methods for rearranging data partitioned across a CUDA warp. + */ + +#pragma once + +#include +#include +#include + +CUB_NAMESPACE_BEGIN + +namespace detail +{ + +template +class WarpExchangeSmem +{ + static_assert(PowerOfTwo::VALUE, + "LOGICAL_WARP_THREADS must be a power of two"); + + constexpr static int ITEMS_PER_TILE = + ITEMS_PER_THREAD * LOGICAL_WARP_THREADS + 1; + + constexpr static bool IS_ARCH_WARP = LOGICAL_WARP_THREADS == CUB_WARP_THREADS(0); + + constexpr static int LOG_SMEM_BANKS = CUB_LOG_SMEM_BANKS(0); + + // Insert padding if the number of items per thread is a power of two + // and > 4 (otherwise we can typically use 128b loads) + constexpr static bool INSERT_PADDING = (ITEMS_PER_THREAD > 4) && + (PowerOfTwo::VALUE); + + constexpr static int PADDING_ITEMS = INSERT_PADDING + ? (ITEMS_PER_TILE >> LOG_SMEM_BANKS) + : 0; + + union _TempStorage + { + InputT items_shared[ITEMS_PER_TILE + PADDING_ITEMS]; + }; // union TempStorage + + /// Shared storage reference + _TempStorage &temp_storage; + + const unsigned int lane_id; + const unsigned int warp_id; + const unsigned int member_mask; + +public: + + struct TempStorage : Uninitialized<_TempStorage> {}; + + WarpExchangeSmem() = delete; + + explicit __device__ __forceinline__ + WarpExchangeSmem(TempStorage &temp_storage) + : temp_storage(temp_storage.Alias()) + , lane_id(IS_ARCH_WARP ? LaneId() : (LaneId() % LOGICAL_WARP_THREADS)) + , warp_id(IS_ARCH_WARP ? 0 : (LaneId() / LOGICAL_WARP_THREADS)) + , member_mask(WarpMask(warp_id)) + {} + + template + __device__ __forceinline__ void + BlockedToStriped(const InputT (&input_items)[ITEMS_PER_THREAD], + OutputT (&output_items)[ITEMS_PER_THREAD]) + { + for (int item = 0; item < ITEMS_PER_THREAD; item++) + { + const int idx = ITEMS_PER_THREAD * lane_id + item; + temp_storage.items_shared[idx] = input_items[item]; + } + WARP_SYNC(member_mask); + + for (int item = 0; item < ITEMS_PER_THREAD; item++) + { + const int idx = LOGICAL_WARP_THREADS * item + lane_id; + output_items[item] = temp_storage.items_shared[idx]; + } + } + + template + __device__ __forceinline__ void + StripedToBlocked(const InputT (&input_items)[ITEMS_PER_THREAD], + OutputT (&output_items)[ITEMS_PER_THREAD]) + { + for (int item = 0; item < ITEMS_PER_THREAD; item++) + { + const int idx = LOGICAL_WARP_THREADS * item + lane_id; + temp_storage.items_shared[idx] = input_items[item]; + } + WARP_SYNC(member_mask); + + for (int item = 0; item < ITEMS_PER_THREAD; item++) + { + const int idx = ITEMS_PER_THREAD * lane_id + item; + output_items[item] = temp_storage.items_shared[idx]; + } + } + + template + __device__ __forceinline__ void + ScatterToStriped(InputT (&items)[ITEMS_PER_THREAD], + OffsetT (&ranks)[ITEMS_PER_THREAD]) + { + ScatterToStriped(items, items, ranks); + } + + template + __device__ __forceinline__ void + ScatterToStriped(const InputT (&input_items)[ITEMS_PER_THREAD], + OutputT (&output_items)[ITEMS_PER_THREAD], + OffsetT (&ranks)[ITEMS_PER_THREAD]) + { + #pragma unroll + for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ITEM++) + { + if (INSERT_PADDING) + { + ranks[ITEM] = SHR_ADD(ranks[ITEM], LOG_SMEM_BANKS, ranks[ITEM]); + } + + temp_storage.items_shared[ranks[ITEM]] = input_items[ITEM]; + } + + WARP_SYNC(member_mask); + + #pragma unroll + for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ITEM++) + { + int item_offset = (ITEM * LOGICAL_WARP_THREADS) + lane_id; + + if (INSERT_PADDING) + { + item_offset = SHR_ADD(item_offset, LOG_SMEM_BANKS, item_offset); + } + + output_items[ITEM] = temp_storage.items_shared[item_offset]; + } + } +}; + +} // namespace detail + +CUB_NAMESPACE_END diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/warp/specializations/warp_reduce_shfl.cuh b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/warp/specializations/warp_reduce_shfl.cuh new file mode 100644 index 0000000000000000000000000000000000000000..ad6d2512f92440e9f0a6f9eaf3e3202e62f11a4d --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/warp/specializations/warp_reduce_shfl.cuh @@ -0,0 +1,583 @@ +/****************************************************************************** + * Copyright (c) 2011, Duane Merrill. All rights reserved. + * Copyright (c) 2011-2018, NVIDIA CORPORATION. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the NVIDIA CORPORATION nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ******************************************************************************/ + +/** + * \file + * cub::WarpReduceShfl provides SHFL-based variants of parallel reduction of items partitioned across a CUDA thread warp. + */ + +#pragma once + +#include "../../config.cuh" +#include "../../thread/thread_operators.cuh" +#include "../../util_ptx.cuh" +#include "../../util_type.cuh" + +#include + +#include +#include + +CUB_NAMESPACE_BEGIN + + +namespace detail +{ + +template +struct reduce_add_exists : ::cuda::std::false_type +{}; + +template +struct reduce_add_exists : ::cuda::std::true_type +{}; + +template +struct reduce_min_exists : ::cuda::std::false_type +{}; + +template +struct reduce_min_exists : ::cuda::std::true_type +{}; + +template +struct reduce_max_exists : ::cuda::std::false_type +{}; + +template +struct reduce_max_exists : ::cuda::std::true_type +{}; + +} + + +/** + * \brief WarpReduceShfl provides SHFL-based variants of parallel reduction of items partitioned across a CUDA thread warp. + * + * LOGICAL_WARP_THREADS must be a power-of-two + */ +template < + typename T, ///< Data type being reduced + int LOGICAL_WARP_THREADS, ///< Number of threads per logical warp + int LEGACY_PTX_ARCH = 0> ///< The PTX compute capability for which to to specialize this collective +struct WarpReduceShfl +{ + static_assert(PowerOfTwo::VALUE, + "LOGICAL_WARP_THREADS must be a power of two"); + + //--------------------------------------------------------------------- + // Constants and type definitions + //--------------------------------------------------------------------- + + enum + { + /// Whether the logical warp size and the PTX warp size coincide + IS_ARCH_WARP = (LOGICAL_WARP_THREADS == CUB_WARP_THREADS(0)), + + /// The number of warp reduction steps + STEPS = Log2::VALUE, + + /// Number of logical warps in a PTX warp + LOGICAL_WARPS = CUB_WARP_THREADS(0) / LOGICAL_WARP_THREADS, + + /// The 5-bit SHFL mask for logically splitting warps into sub-segments starts 8-bits up + SHFL_C = (CUB_WARP_THREADS(0) - LOGICAL_WARP_THREADS) << 8 + + }; + + template + struct IsInteger + { + enum { + ///Whether the data type is a small (32b or less) integer for which we can use a single SFHL instruction per exchange + IS_SMALL_UNSIGNED = (Traits::CATEGORY == UNSIGNED_INTEGER) && (sizeof(S) <= sizeof(unsigned int)) + }; + }; + + + /// Shared memory storage layout type + typedef NullType TempStorage; + + + //--------------------------------------------------------------------- + // Thread fields + //--------------------------------------------------------------------- + + /// Lane index in logical warp + int lane_id; + + /// Logical warp index in 32-thread physical warp + int warp_id; + + /// 32-thread physical warp member mask of logical warp + uint32_t member_mask; + + + //--------------------------------------------------------------------- + // Construction + //--------------------------------------------------------------------- + + /// Constructor + __device__ __forceinline__ WarpReduceShfl( + TempStorage &/*temp_storage*/) + : lane_id(static_cast(LaneId())) + , warp_id(IS_ARCH_WARP ? 0 : (lane_id / LOGICAL_WARP_THREADS)) + , member_mask(WarpMask(warp_id)) + { + if (!IS_ARCH_WARP) + { + lane_id = lane_id % LOGICAL_WARP_THREADS; + } + } + + + //--------------------------------------------------------------------- + // Reduction steps + //--------------------------------------------------------------------- + + /// Reduction (specialized for summation across uint32 types) + __device__ __forceinline__ unsigned int ReduceStep( + unsigned int input, ///< [in] Calling thread's input item. + cub::Sum /*reduction_op*/, ///< [in] Binary reduction operator + int last_lane, ///< [in] Index of last lane in segment + int offset) ///< [in] Up-offset to pull from + { + unsigned int output; + int shfl_c = last_lane | SHFL_C; // Shuffle control (mask and last_lane) + + // Use predicate set from SHFL to guard against invalid peers + asm volatile( + "{" + " .reg .u32 r0;" + " .reg .pred p;" + " shfl.sync.down.b32 r0|p, %1, %2, %3, %5;" + " @p add.u32 r0, r0, %4;" + " mov.u32 %0, r0;" + "}" + : "=r"(output) : "r"(input), "r"(offset), "r"(shfl_c), "r"(input), "r"(member_mask)); + + return output; + } + + + /// Reduction (specialized for summation across fp32 types) + __device__ __forceinline__ float ReduceStep( + float input, ///< [in] Calling thread's input item. + cub::Sum /*reduction_op*/, ///< [in] Binary reduction operator + int last_lane, ///< [in] Index of last lane in segment + int offset) ///< [in] Up-offset to pull from + { + float output; + int shfl_c = last_lane | SHFL_C; // Shuffle control (mask and last_lane) + + // Use predicate set from SHFL to guard against invalid peers + asm volatile( + "{" + " .reg .f32 r0;" + " .reg .pred p;" + " shfl.sync.down.b32 r0|p, %1, %2, %3, %5;" + " @p add.f32 r0, r0, %4;" + " mov.f32 %0, r0;" + "}" + : "=f"(output) : "f"(input), "r"(offset), "r"(shfl_c), "f"(input), "r"(member_mask)); + + return output; + } + + + /// Reduction (specialized for summation across unsigned long long types) + __device__ __forceinline__ unsigned long long ReduceStep( + unsigned long long input, ///< [in] Calling thread's input item. + cub::Sum /*reduction_op*/, ///< [in] Binary reduction operator + int last_lane, ///< [in] Index of last lane in segment + int offset) ///< [in] Up-offset to pull from + { + unsigned long long output; + int shfl_c = last_lane | SHFL_C; // Shuffle control (mask and last_lane) + + asm volatile( + "{" + " .reg .u32 lo;" + " .reg .u32 hi;" + " .reg .pred p;" + " mov.b64 {lo, hi}, %1;" + " shfl.sync.down.b32 lo|p, lo, %2, %3, %4;" + " shfl.sync.down.b32 hi|p, hi, %2, %3, %4;" + " mov.b64 %0, {lo, hi};" + " @p add.u64 %0, %0, %1;" + "}" + : "=l"(output) : "l"(input), "r"(offset), "r"(shfl_c), "r"(member_mask)); + + return output; + } + + + /// Reduction (specialized for summation across long long types) + __device__ __forceinline__ long long ReduceStep( + long long input, ///< [in] Calling thread's input item. + cub::Sum /*reduction_op*/, ///< [in] Binary reduction operator + int last_lane, ///< [in] Index of last lane in segment + int offset) ///< [in] Up-offset to pull from + { + long long output; + int shfl_c = last_lane | SHFL_C; // Shuffle control (mask and last_lane) + + // Use predicate set from SHFL to guard against invalid peers + asm volatile( + "{" + " .reg .u32 lo;" + " .reg .u32 hi;" + " .reg .pred p;" + " mov.b64 {lo, hi}, %1;" + " shfl.sync.down.b32 lo|p, lo, %2, %3, %4;" + " shfl.sync.down.b32 hi|p, hi, %2, %3, %4;" + " mov.b64 %0, {lo, hi};" + " @p add.s64 %0, %0, %1;" + "}" + : "=l"(output) : "l"(input), "r"(offset), "r"(shfl_c), "r"(member_mask)); + + return output; + } + + + /// Reduction (specialized for summation across double types) + __device__ __forceinline__ double ReduceStep( + double input, ///< [in] Calling thread's input item. + cub::Sum /*reduction_op*/, ///< [in] Binary reduction operator + int last_lane, ///< [in] Index of last lane in segment + int offset) ///< [in] Up-offset to pull from + { + double output; + int shfl_c = last_lane | SHFL_C; // Shuffle control (mask and last_lane) + + // Use predicate set from SHFL to guard against invalid peers + asm volatile( + "{" + " .reg .u32 lo;" + " .reg .u32 hi;" + " .reg .pred p;" + " .reg .f64 r0;" + " mov.b64 %0, %1;" + " mov.b64 {lo, hi}, %1;" + " shfl.sync.down.b32 lo|p, lo, %2, %3, %4;" + " shfl.sync.down.b32 hi|p, hi, %2, %3, %4;" + " mov.b64 r0, {lo, hi};" + " @p add.f64 %0, %0, r0;" + "}" + : "=d"(output) : "d"(input), "r"(offset), "r"(shfl_c), "r"(member_mask)); + + return output; + } + + + /// Reduction (specialized for swizzled ReduceByKeyOp across KeyValuePair types) + template + __device__ __forceinline__ KeyValuePair ReduceStep( + KeyValuePair input, ///< [in] Calling thread's input item. + SwizzleScanOp > /*reduction_op*/, ///< [in] Binary reduction operator + int last_lane, ///< [in] Index of last lane in segment + int offset) ///< [in] Up-offset to pull from + { + KeyValuePair output; + + KeyT other_key = ShuffleDown(input.key, offset, last_lane, member_mask); + + output.key = input.key; + output.value = ReduceStep( + input.value, + cub::Sum(), + last_lane, + offset, + Int2Type::IS_SMALL_UNSIGNED>()); + + if (input.key != other_key) + output.value = input.value; + + return output; + } + + + + /// Reduction (specialized for swizzled ReduceBySegmentOp across KeyValuePair types) + template + __device__ __forceinline__ KeyValuePair ReduceStep( + KeyValuePair input, ///< [in] Calling thread's input item. + SwizzleScanOp > /*reduction_op*/, ///< [in] Binary reduction operator + int last_lane, ///< [in] Index of last lane in segment + int offset) ///< [in] Up-offset to pull from + { + KeyValuePair output; + + output.value = ReduceStep(input.value, cub::Sum(), last_lane, offset, Int2Type::IS_SMALL_UNSIGNED>()); + output.key = ReduceStep(input.key, cub::Sum(), last_lane, offset, Int2Type::IS_SMALL_UNSIGNED>()); + + if (input.key > 0) + output.value = input.value; + + return output; + } + + + /// Reduction step (generic) + template + __device__ __forceinline__ _T ReduceStep( + _T input, ///< [in] Calling thread's input item. + ReductionOp reduction_op, ///< [in] Binary reduction operator + int last_lane, ///< [in] Index of last lane in segment + int offset) ///< [in] Up-offset to pull from + { + _T output = input; + + _T temp = ShuffleDown(output, offset, last_lane, member_mask); + + // Perform reduction op if valid + if (offset + lane_id <= last_lane) + output = reduction_op(input, temp); + + return output; + } + + + /// Reduction step (specialized for small unsigned integers size 32b or less) + template + __device__ __forceinline__ _T ReduceStep( + _T input, ///< [in] Calling thread's input item. + ReductionOp reduction_op, ///< [in] Binary reduction operator + int last_lane, ///< [in] Index of last lane in segment + int offset, ///< [in] Up-offset to pull from + Int2Type /*is_small_unsigned*/) ///< [in] Marker type indicating whether T is a small unsigned integer + { + return ReduceStep(input, reduction_op, last_lane, offset); + } + + + /// Reduction step (specialized for types other than small unsigned integers size 32b or less) + template + __device__ __forceinline__ _T ReduceStep( + _T input, ///< [in] Calling thread's input item. + ReductionOp reduction_op, ///< [in] Binary reduction operator + int last_lane, ///< [in] Index of last lane in segment + int offset, ///< [in] Up-offset to pull from + Int2Type /*is_small_unsigned*/) ///< [in] Marker type indicating whether T is a small unsigned integer + { + return ReduceStep(input, reduction_op, last_lane, offset); + } + + + //--------------------------------------------------------------------- + // Templated reduction iteration + //--------------------------------------------------------------------- + + template + __device__ __forceinline__ void ReduceStep( + T& input, ///< [in] Calling thread's input item. + ReductionOp reduction_op, ///< [in] Binary reduction operator + int last_lane, ///< [in] Index of last lane in segment + Int2Type /*step*/) + { + input = ReduceStep(input, reduction_op, last_lane, 1 << STEP, Int2Type::IS_SMALL_UNSIGNED>()); + + ReduceStep(input, reduction_op, last_lane, Int2Type()); + } + + template + __device__ __forceinline__ void ReduceStep( + T& /*input*/, ///< [in] Calling thread's input item. + ReductionOp /*reduction_op*/, ///< [in] Binary reduction operator + int /*last_lane*/, ///< [in] Index of last lane in segment + Int2Type /*step*/) + {} + + + //--------------------------------------------------------------------- + // Reduction operations + //--------------------------------------------------------------------- + template + __device__ __forceinline__ T ReduceImpl( + Int2Type<0> /* all_lanes_valid */, + T input, ///< [in] Calling thread's input + int valid_items, ///< [in] Total number of valid items across the logical warp + ReductionOp reduction_op) ///< [in] Binary reduction operator + { + int last_lane = valid_items - 1; + + T output = input; + + // Template-iterate reduction steps + ReduceStep(output, reduction_op, last_lane, Int2Type<0>()); + + return output; + } + + template + __device__ __forceinline__ T ReduceImpl( + Int2Type<1> /* all_lanes_valid */, + T input, ///< [in] Calling thread's input + int /* valid_items */, ///< [in] Total number of valid items across the logical warp + ReductionOp reduction_op) ///< [in] Binary reduction operator + { + int last_lane = LOGICAL_WARP_THREADS - 1; + + T output = input; + + // Template-iterate reduction steps + ReduceStep(output, reduction_op, last_lane, Int2Type<0>()); + + return output; + } + + template + __device__ __forceinline__ + typename std::enable_if< + (std::is_same::value || std::is_same::value) + && detail::reduce_add_exists<>::value, T>::type + ReduceImpl(Int2Type<1> /* all_lanes_valid */, + T input, + int /* valid_items */, + cub::Sum /* reduction_op */) + { + T output = input; + + NV_IF_TARGET(NV_PROVIDES_SM_80, + (output = __reduce_add_sync(member_mask, input);), + (output = ReduceImpl(Int2Type<1>{}, + input, + LOGICAL_WARP_THREADS, + cub::Sum{});)); + + return output; + } + + template + __device__ __forceinline__ + typename std::enable_if< + (std::is_same::value || std::is_same::value) + && detail::reduce_min_exists<>::value, T>::type + ReduceImpl(Int2Type<1> /* all_lanes_valid */, + T input, + int /* valid_items */, + cub::Min /* reduction_op */) + { + T output = input; + + NV_IF_TARGET(NV_PROVIDES_SM_80, + (output = __reduce_min_sync(member_mask, input);), + (output = ReduceImpl(Int2Type<1>{}, + input, + LOGICAL_WARP_THREADS, + cub::Min{});)); + + return output; + } + + template + __device__ __forceinline__ + typename std::enable_if< + (std::is_same::value || std::is_same::value) + && detail::reduce_max_exists<>::value, T>::type + ReduceImpl(Int2Type<1> /* all_lanes_valid */, + T input, + int /* valid_items */, + cub::Max /* reduction_op */) + { + T output = input; + + NV_IF_TARGET(NV_PROVIDES_SM_80, + (output = __reduce_max_sync(member_mask, input);), + (output = ReduceImpl(Int2Type<1>{}, + input, + LOGICAL_WARP_THREADS, + cub::Max{});)); + + return output; + } + + /// Reduction + template < + bool ALL_LANES_VALID, ///< Whether all lanes in each warp are contributing a valid fold of items + typename ReductionOp> + __device__ __forceinline__ T Reduce( + T input, ///< [in] Calling thread's input + int valid_items, ///< [in] Total number of valid items across the logical warp + ReductionOp reduction_op) ///< [in] Binary reduction operator + { + return ReduceImpl( + Int2Type{}, input, valid_items, reduction_op); + } + + + /// Segmented reduction + template < + bool HEAD_SEGMENTED, ///< Whether flags indicate a segment-head or a segment-tail + typename FlagT, + typename ReductionOp> + __device__ __forceinline__ T SegmentedReduce( + T input, ///< [in] Calling thread's input + FlagT flag, ///< [in] Whether or not the current lane is a segment head/tail + ReductionOp reduction_op) ///< [in] Binary reduction operator + { + // Get the start flags for each thread in the warp. + int warp_flags = WARP_BALLOT(flag, member_mask); + + // Convert to tail-segmented + if (HEAD_SEGMENTED) + warp_flags >>= 1; + + // Mask out the bits below the current thread + warp_flags &= LaneMaskGe(); + + // Mask of physical lanes outside the logical warp and convert to logical lanemask + if (!IS_ARCH_WARP) + { + warp_flags = (warp_flags & member_mask) >> (warp_id * LOGICAL_WARP_THREADS); + } + + // Mask in the last lane of logical warp + warp_flags |= 1u << (LOGICAL_WARP_THREADS - 1); + + // Find the next set flag + int last_lane = __clz(__brev(warp_flags)); + + T output = input; + +// // Iterate reduction steps +// #pragma unroll +// for (int STEP = 0; STEP < STEPS; STEP++) +// { +// output = ReduceStep(output, reduction_op, last_lane, 1 << STEP, Int2Type::IS_SMALL_UNSIGNED>()); +// } + + // Template-iterate reduction steps + ReduceStep(output, reduction_op, last_lane, Int2Type<0>()); + + return output; + } +}; + + +CUB_NAMESPACE_END diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/warp/specializations/warp_reduce_smem.cuh b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/warp/specializations/warp_reduce_smem.cuh new file mode 100644 index 0000000000000000000000000000000000000000..bd083fccfc20b6d7c624b067999d6e867e79a4b7 --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/warp/specializations/warp_reduce_smem.cuh @@ -0,0 +1,360 @@ +/****************************************************************************** + * Copyright (c) 2011, Duane Merrill. All rights reserved. + * Copyright (c) 2011-2018, NVIDIA CORPORATION. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the NVIDIA CORPORATION nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ******************************************************************************/ + +/** + * \file + * cub::WarpReduceSmem provides smem-based variants of parallel reduction of items partitioned across a CUDA thread warp. + */ + +#pragma once + +#include "../../config.cuh" +#include "../../thread/thread_operators.cuh" +#include "../../thread/thread_load.cuh" +#include "../../thread/thread_store.cuh" +#include "../../util_type.cuh" + +CUB_NAMESPACE_BEGIN + +/** + * \brief WarpReduceSmem provides smem-based variants of parallel reduction of items partitioned across a CUDA thread warp. + */ +template < + typename T, ///< Data type being reduced + int LOGICAL_WARP_THREADS, ///< Number of threads per logical warp + int LEGACY_PTX_ARCH = 0> ///< The PTX compute capability for which to to specialize this collective +struct WarpReduceSmem +{ + /****************************************************************************** + * Constants and type definitions + ******************************************************************************/ + + enum + { + /// Whether the logical warp size and the PTX warp size coincide + IS_ARCH_WARP = (LOGICAL_WARP_THREADS == CUB_WARP_THREADS(0)), + + /// Whether the logical warp size is a power-of-two + IS_POW_OF_TWO = PowerOfTwo::VALUE, + + /// The number of warp reduction steps + STEPS = Log2::VALUE, + + /// The number of threads in half a warp + HALF_WARP_THREADS = 1 << (STEPS - 1), + + /// The number of shared memory elements per warp + WARP_SMEM_ELEMENTS = LOGICAL_WARP_THREADS + HALF_WARP_THREADS, + + /// FlagT status (when not using ballot) + UNSET = 0x0, // Is initially unset + SET = 0x1, // Is initially set + SEEN = 0x2, // Has seen another head flag from a successor peer + }; + + /// Shared memory flag type + typedef unsigned char SmemFlag; + + /// Shared memory storage layout type (1.5 warps-worth of elements for each warp) + struct _TempStorage + { + T reduce[WARP_SMEM_ELEMENTS]; + SmemFlag flags[WARP_SMEM_ELEMENTS]; + }; + + // Alias wrapper allowing storage to be unioned + struct TempStorage : Uninitialized<_TempStorage> {}; + + + /****************************************************************************** + * Thread fields + ******************************************************************************/ + + _TempStorage &temp_storage; + unsigned int lane_id; + unsigned int member_mask; + + + /****************************************************************************** + * Construction + ******************************************************************************/ + + /// Constructor + explicit __device__ __forceinline__ WarpReduceSmem(TempStorage &temp_storage) + : temp_storage(temp_storage.Alias()) + , lane_id(IS_ARCH_WARP ? LaneId() : LaneId() % LOGICAL_WARP_THREADS) + , member_mask( + WarpMask(LaneId() / LOGICAL_WARP_THREADS)) + {} + + /****************************************************************************** + * Utility methods + ******************************************************************************/ + + //--------------------------------------------------------------------- + // Regular reduction + //--------------------------------------------------------------------- + + /** + * Reduction step + */ + template < + bool ALL_LANES_VALID, ///< Whether all lanes in each warp are contributing a valid fold of items + typename ReductionOp, + int STEP> + __device__ __forceinline__ T ReduceStep( + T input, ///< [in] Calling thread's input + int valid_items, ///< [in] Total number of valid items across the logical warp + ReductionOp reduction_op, ///< [in] Reduction operator + Int2Type /*step*/) + { + const int OFFSET = 1 << STEP; + + // Share input through buffer + ThreadStore(&temp_storage.reduce[lane_id], input); + + WARP_SYNC(member_mask); + + // Update input if peer_addend is in range + if ((ALL_LANES_VALID && IS_POW_OF_TWO) || ((lane_id + OFFSET) < valid_items)) + { + T peer_addend = ThreadLoad(&temp_storage.reduce[lane_id + OFFSET]); + input = reduction_op(input, peer_addend); + } + + WARP_SYNC(member_mask); + + return ReduceStep(input, valid_items, reduction_op, Int2Type()); + } + + + /** + * Reduction step (terminate) + */ + template < + bool ALL_LANES_VALID, ///< Whether all lanes in each warp are contributing a valid fold of items + typename ReductionOp> + __device__ __forceinline__ T ReduceStep( + T input, ///< [in] Calling thread's input + int valid_items, ///< [in] Total number of valid items across the logical warp + ReductionOp /*reduction_op*/, ///< [in] Reduction operator + Int2Type /*step*/) + { + return input; + } + + + //--------------------------------------------------------------------- + // Segmented reduction + //--------------------------------------------------------------------- + + + /** + * Ballot-based segmented reduce + */ + template < + bool HEAD_SEGMENTED, ///< Whether flags indicate a segment-head or a segment-tail + typename FlagT, + typename ReductionOp> + __device__ __forceinline__ T SegmentedReduce( + T input, ///< [in] Calling thread's input + FlagT flag, ///< [in] Whether or not the current lane is a segment head/tail + ReductionOp reduction_op, ///< [in] Reduction operator + Int2Type /*has_ballot*/) ///< [in] Marker type for whether the target arch has ballot functionality + { + // Get the start flags for each thread in the warp. + int warp_flags = WARP_BALLOT(flag, member_mask); + + if (!HEAD_SEGMENTED) + warp_flags <<= 1; + + // Keep bits above the current thread. + warp_flags &= LaneMaskGt(); + + // Accommodate packing of multiple logical warps in a single physical warp + if (!IS_ARCH_WARP) + { + warp_flags >>= (LaneId() / LOGICAL_WARP_THREADS) * LOGICAL_WARP_THREADS; + } + + // Find next flag + int next_flag = __clz(__brev(warp_flags)); + + // Clip the next segment at the warp boundary if necessary + if (LOGICAL_WARP_THREADS != 32) + next_flag = CUB_MIN(next_flag, LOGICAL_WARP_THREADS); + + #pragma unroll + for (int STEP = 0; STEP < STEPS; STEP++) + { + const int OFFSET = 1 << STEP; + + // Share input into buffer + ThreadStore(&temp_storage.reduce[lane_id], input); + + WARP_SYNC(member_mask); + + // Update input if peer_addend is in range + if (OFFSET + lane_id < next_flag) + { + T peer_addend = ThreadLoad(&temp_storage.reduce[lane_id + OFFSET]); + input = reduction_op(input, peer_addend); + } + + WARP_SYNC(member_mask); + } + + return input; + } + + + /** + * Smem-based segmented reduce + */ + template < + bool HEAD_SEGMENTED, ///< Whether flags indicate a segment-head or a segment-tail + typename FlagT, + typename ReductionOp> + __device__ __forceinline__ T SegmentedReduce( + T input, ///< [in] Calling thread's input + FlagT flag, ///< [in] Whether or not the current lane is a segment head/tail + ReductionOp reduction_op, ///< [in] Reduction operator + Int2Type /*has_ballot*/) ///< [in] Marker type for whether the target arch has ballot functionality + { + enum + { + UNSET = 0x0, // Is initially unset + SET = 0x1, // Is initially set + SEEN = 0x2, // Has seen another head flag from a successor peer + }; + + // Alias flags onto shared data storage + volatile SmemFlag *flag_storage = temp_storage.flags; + + SmemFlag flag_status = (flag) ? SET : UNSET; + + for (int STEP = 0; STEP < STEPS; STEP++) + { + const int OFFSET = 1 << STEP; + + // Share input through buffer + ThreadStore(&temp_storage.reduce[lane_id], input); + + WARP_SYNC(member_mask); + + // Get peer from buffer + T peer_addend = ThreadLoad(&temp_storage.reduce[lane_id + OFFSET]); + + WARP_SYNC(member_mask); + + // Share flag through buffer + flag_storage[lane_id] = flag_status; + + // Get peer flag from buffer + SmemFlag peer_flag_status = flag_storage[lane_id + OFFSET]; + + // Update input if peer was in range + if (lane_id < LOGICAL_WARP_THREADS - OFFSET) + { + if (HEAD_SEGMENTED) + { + // Head-segmented + if ((flag_status & SEEN) == 0) + { + // Has not seen a more distant head flag + if (peer_flag_status & SET) + { + // Has now seen a head flag + flag_status |= SEEN; + } + else + { + // Peer is not a head flag: grab its count + input = reduction_op(input, peer_addend); + } + + // Update seen status to include that of peer + flag_status |= (peer_flag_status & SEEN); + } + } + else + { + // Tail-segmented. Simply propagate flag status + if (!flag_status) + { + input = reduction_op(input, peer_addend); + flag_status |= peer_flag_status; + } + + } + } + } + + return input; + } + + + /****************************************************************************** + * Interface + ******************************************************************************/ + + /** + * Reduction + */ + template < + bool ALL_LANES_VALID, ///< Whether all lanes in each warp are contributing a valid fold of items + typename ReductionOp> + __device__ __forceinline__ T Reduce( + T input, ///< [in] Calling thread's input + int valid_items, ///< [in] Total number of valid items across the logical warp + ReductionOp reduction_op) ///< [in] Reduction operator + { + return ReduceStep(input, valid_items, reduction_op, Int2Type<0>()); + } + + + /** + * Segmented reduction + */ + template < + bool HEAD_SEGMENTED, ///< Whether flags indicate a segment-head or a segment-tail + typename FlagT, + typename ReductionOp> + __device__ __forceinline__ T SegmentedReduce( + T input, ///< [in] Calling thread's input + FlagT flag, ///< [in] Whether or not the current lane is a segment head/tail + ReductionOp reduction_op) ///< [in] Reduction operator + { + return SegmentedReduce(input, flag, reduction_op, Int2Type()); + } + + +}; + + +CUB_NAMESPACE_END diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/warp/specializations/warp_scan_smem.cuh b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/warp/specializations/warp_scan_smem.cuh new file mode 100644 index 0000000000000000000000000000000000000000..bd17118e999617a99d5a9b7fdc4af588e3af73c1 --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/warp/specializations/warp_scan_smem.cuh @@ -0,0 +1,388 @@ +/****************************************************************************** + * Copyright (c) 2011, Duane Merrill. All rights reserved. + * Copyright (c) 2011-2018, NVIDIA CORPORATION. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the NVIDIA CORPORATION nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ******************************************************************************/ + +/** + * \file + * cub::WarpScanSmem provides smem-based variants of parallel prefix scan of items partitioned across a CUDA thread warp. + */ + +#pragma once + +#include "../../config.cuh" +#include "../../thread/thread_operators.cuh" +#include "../../thread/thread_load.cuh" +#include "../../thread/thread_store.cuh" +#include "../../util_type.cuh" + +CUB_NAMESPACE_BEGIN + +/** + * \brief WarpScanSmem provides smem-based variants of parallel prefix scan of items partitioned across a CUDA thread warp. + */ +template < + typename T, ///< Data type being scanned + int LOGICAL_WARP_THREADS, ///< Number of threads per logical warp + int LEGACY_PTX_ARCH = 0> ///< The PTX compute capability for which to to specialize this collective +struct WarpScanSmem +{ + /****************************************************************************** + * Constants and type definitions + ******************************************************************************/ + + enum + { + /// Whether the logical warp size and the PTX warp size coincide + IS_ARCH_WARP = (LOGICAL_WARP_THREADS == CUB_WARP_THREADS(0)), + + /// The number of warp scan steps + STEPS = Log2::VALUE, + + /// The number of threads in half a warp + HALF_WARP_THREADS = 1 << (STEPS - 1), + + /// The number of shared memory elements per warp + WARP_SMEM_ELEMENTS = LOGICAL_WARP_THREADS + HALF_WARP_THREADS, + }; + + /// Storage cell type (workaround for SM1x compiler bugs with custom-ops like Max() on signed chars) + using CellT = T; + + /// Shared memory storage layout type (1.5 warps-worth of elements for each warp) + typedef CellT _TempStorage[WARP_SMEM_ELEMENTS]; + + // Alias wrapper allowing storage to be unioned + struct TempStorage : Uninitialized<_TempStorage> {}; + + + /****************************************************************************** + * Thread fields + ******************************************************************************/ + + _TempStorage &temp_storage; + unsigned int lane_id; + unsigned int member_mask; + + + /****************************************************************************** + * Construction + ******************************************************************************/ + + /// Constructor + explicit __device__ __forceinline__ WarpScanSmem( + TempStorage &temp_storage) + : + temp_storage(temp_storage.Alias()), + + lane_id(IS_ARCH_WARP ? + LaneId() : + LaneId() % LOGICAL_WARP_THREADS), + + member_mask( + WarpMask(LaneId() / LOGICAL_WARP_THREADS)) + {} + + + /****************************************************************************** + * Utility methods + ******************************************************************************/ + + /// Basic inclusive scan iteration (template unrolled, inductive-case specialization) + template < + bool HAS_IDENTITY, + int STEP, + typename ScanOp> + __device__ __forceinline__ void ScanStep( + T &partial, + ScanOp scan_op, + Int2Type /*step*/) + { + const int OFFSET = 1 << STEP; + + // Share partial into buffer + ThreadStore(&temp_storage[HALF_WARP_THREADS + lane_id], (CellT) partial); + + WARP_SYNC(member_mask); + + // Update partial if addend is in range + if (HAS_IDENTITY || (lane_id >= OFFSET)) + { + T addend = (T) ThreadLoad(&temp_storage[HALF_WARP_THREADS + lane_id - OFFSET]); + partial = scan_op(addend, partial); + } + WARP_SYNC(member_mask); + + ScanStep(partial, scan_op, Int2Type()); + } + + + /// Basic inclusive scan iteration(template unrolled, base-case specialization) + template < + bool HAS_IDENTITY, + typename ScanOp> + __device__ __forceinline__ void ScanStep( + T &/*partial*/, + ScanOp /*scan_op*/, + Int2Type /*step*/) + {} + + + /// Inclusive prefix scan (specialized for summation across primitive types) + __device__ __forceinline__ void InclusiveScan( + T input, ///< [in] Calling thread's input item. + T &output, ///< [out] Calling thread's output item. May be aliased with \p input. + Sum scan_op, ///< [in] Binary scan operator + Int2Type /*is_primitive*/) ///< [in] Marker type indicating whether T is primitive type + { + T identity = 0; + ThreadStore(&temp_storage[lane_id], (CellT) identity); + + WARP_SYNC(member_mask); + + // Iterate scan steps + output = input; + ScanStep(output, scan_op, Int2Type<0>()); + } + + + /// Inclusive prefix scan + template + __device__ __forceinline__ void InclusiveScan( + T input, ///< [in] Calling thread's input item. + T &output, ///< [out] Calling thread's output item. May be aliased with \p input. + ScanOp scan_op, ///< [in] Binary scan operator + Int2Type /*is_primitive*/) ///< [in] Marker type indicating whether T is primitive type + { + // Iterate scan steps + output = input; + ScanStep(output, scan_op, Int2Type<0>()); + } + + + /****************************************************************************** + * Interface + ******************************************************************************/ + + //--------------------------------------------------------------------- + // Broadcast + //--------------------------------------------------------------------- + + /// Broadcast + __device__ __forceinline__ T Broadcast( + T input, ///< [in] The value to broadcast + unsigned int src_lane) ///< [in] Which warp lane is to do the broadcasting + { + if (lane_id == src_lane) + { + ThreadStore(temp_storage, (CellT) input); + } + + WARP_SYNC(member_mask); + + return (T)ThreadLoad(temp_storage); + } + + + //--------------------------------------------------------------------- + // Inclusive operations + //--------------------------------------------------------------------- + + /// Inclusive scan + template + __device__ __forceinline__ void InclusiveScan( + T input, ///< [in] Calling thread's input item. + T &inclusive_output, ///< [out] Calling thread's output item. May be aliased with \p input. + ScanOp scan_op) ///< [in] Binary scan operator + { + InclusiveScan(input, inclusive_output, scan_op, Int2Type::PRIMITIVE>()); + } + + + /// Inclusive scan with aggregate + template + __device__ __forceinline__ void InclusiveScan( + T input, ///< [in] Calling thread's input item. + T &inclusive_output, ///< [out] Calling thread's output item. May be aliased with \p input. + ScanOp scan_op, ///< [in] Binary scan operator + T &warp_aggregate) ///< [out] Warp-wide aggregate reduction of input items. + { + InclusiveScan(input, inclusive_output, scan_op); + + // Retrieve aggregate + ThreadStore(&temp_storage[HALF_WARP_THREADS + lane_id], (CellT) inclusive_output); + + WARP_SYNC(member_mask); + + warp_aggregate = (T) ThreadLoad(&temp_storage[WARP_SMEM_ELEMENTS - 1]); + + WARP_SYNC(member_mask); + } + + + //--------------------------------------------------------------------- + // Get exclusive from inclusive + //--------------------------------------------------------------------- + + /// Update inclusive and exclusive using input and inclusive + template + __device__ __forceinline__ void Update( + T /*input*/, ///< [in] + T &inclusive, ///< [in, out] + T &exclusive, ///< [out] + ScanOpT /*scan_op*/, ///< [in] + IsIntegerT /*is_integer*/) ///< [in] + { + // initial value unknown + ThreadStore(&temp_storage[HALF_WARP_THREADS + lane_id], (CellT) inclusive); + + WARP_SYNC(member_mask); + + exclusive = (T) ThreadLoad(&temp_storage[HALF_WARP_THREADS + lane_id - 1]); + } + + /// Update inclusive and exclusive using input and inclusive (specialized for summation of integer types) + __device__ __forceinline__ void Update( + T input, + T &inclusive, + T &exclusive, + cub::Sum /*scan_op*/, + Int2Type /*is_integer*/) + { + // initial value presumed 0 + exclusive = inclusive - input; + } + + /// Update inclusive and exclusive using initial value using input, inclusive, and initial value + template + __device__ __forceinline__ void Update ( + T /*input*/, + T &inclusive, + T &exclusive, + ScanOpT scan_op, + T initial_value, + IsIntegerT /*is_integer*/) + { + inclusive = scan_op(initial_value, inclusive); + ThreadStore(&temp_storage[HALF_WARP_THREADS + lane_id], (CellT) inclusive); + + WARP_SYNC(member_mask); + + exclusive = (T) ThreadLoad(&temp_storage[HALF_WARP_THREADS + lane_id - 1]); + if (lane_id == 0) + exclusive = initial_value; + } + + /// Update inclusive and exclusive using initial value using input and inclusive (specialized for summation of integer types) + __device__ __forceinline__ void Update ( + T input, + T &inclusive, + T &exclusive, + cub::Sum scan_op, + T initial_value, + Int2Type /*is_integer*/) + { + inclusive = scan_op(initial_value, inclusive); + exclusive = inclusive - input; + } + + + /// Update inclusive, exclusive, and warp aggregate using input and inclusive + template + __device__ __forceinline__ void Update ( + T /*input*/, + T &inclusive, + T &exclusive, + T &warp_aggregate, + ScanOpT /*scan_op*/, + IsIntegerT /*is_integer*/) + { + // Initial value presumed to be unknown or identity (either way our padding is correct) + ThreadStore(&temp_storage[HALF_WARP_THREADS + lane_id], (CellT) inclusive); + + WARP_SYNC(member_mask); + + exclusive = (T) ThreadLoad(&temp_storage[HALF_WARP_THREADS + lane_id - 1]); + warp_aggregate = (T) ThreadLoad(&temp_storage[WARP_SMEM_ELEMENTS - 1]); + } + + /// Update inclusive, exclusive, and warp aggregate using input and inclusive (specialized for summation of integer types) + __device__ __forceinline__ void Update ( + T input, + T &inclusive, + T &exclusive, + T &warp_aggregate, + cub::Sum /*scan_o*/, + Int2Type /*is_integer*/) + { + // Initial value presumed to be unknown or identity (either way our padding is correct) + ThreadStore(&temp_storage[HALF_WARP_THREADS + lane_id], (CellT) inclusive); + + WARP_SYNC(member_mask); + + warp_aggregate = (T) ThreadLoad(&temp_storage[WARP_SMEM_ELEMENTS - 1]); + exclusive = inclusive - input; + } + + /// Update inclusive, exclusive, and warp aggregate using input, inclusive, and initial value + template + __device__ __forceinline__ void Update ( + T /*input*/, + T &inclusive, + T &exclusive, + T &warp_aggregate, + ScanOpT scan_op, + T initial_value, + IsIntegerT /*is_integer*/) + { + // Broadcast warp aggregate + ThreadStore(&temp_storage[HALF_WARP_THREADS + lane_id], (CellT) inclusive); + + WARP_SYNC(member_mask); + + warp_aggregate = (T) ThreadLoad(&temp_storage[WARP_SMEM_ELEMENTS - 1]); + + WARP_SYNC(member_mask); + + // Update inclusive with initial value + inclusive = scan_op(initial_value, inclusive); + + // Get exclusive from exclusive + ThreadStore(&temp_storage[HALF_WARP_THREADS + lane_id - 1], (CellT) inclusive); + + WARP_SYNC(member_mask); + + exclusive = (T) ThreadLoad(&temp_storage[HALF_WARP_THREADS + lane_id - 2]); + + if (lane_id == 0) + exclusive = initial_value; + } + + +}; + + +CUB_NAMESPACE_END diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/warp/warp_exchange.cuh b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/warp/warp_exchange.cuh new file mode 100644 index 0000000000000000000000000000000000000000..e863f67b103a5e80e78215675c49ec0ac277afb4 --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/warp/warp_exchange.cuh @@ -0,0 +1,423 @@ +/****************************************************************************** + * Copyright (c) 2011-2021, NVIDIA CORPORATION. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the NVIDIA CORPORATION nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ******************************************************************************/ + +/** + * @file + * The cub::WarpExchange class provides [collective](index.html#sec0) + * methods for rearranging data partitioned across a CUDA warp. + */ + +#pragma once + +#include +#include +#include +#include +#include + + +CUB_NAMESPACE_BEGIN + + +enum WarpExchangeAlgorithm +{ + WARP_EXCHANGE_SMEM, + WARP_EXCHANGE_SHUFFLE, +}; + +namespace detail +{ +template +using InternalWarpExchangeImpl = + cub::detail::conditional_t, + WarpExchangeShfl>; +} // namespace detail + +/** + * @brief The WarpExchange class provides [collective](index.html#sec0) + * methods for rearranging data partitioned across a CUDA warp. + * @ingroup WarpModule + * + * @tparam T + * The data type to be exchanged. + * + * @tparam ITEMS_PER_THREAD + * The number of items partitioned onto each thread. + * + * @tparam LOGICAL_WARP_THREADS + * [optional] The number of threads per "logical" warp (may be less + * than the number of hardware warp threads). Default is the warp size of the + * targeted CUDA compute-capability (e.g., 32 threads for SM86). Must be a + * power of two. + * + * @tparam LEGACY_PTX_ARCH + * Unused. + * + * @par Overview + * - It is commonplace for a warp of threads to rearrange data items between + * threads. For example, the global memory accesses prefer patterns where + * data items are "striped" across threads (where consecutive threads access + * consecutive items), yet most warp-wide operations prefer a "blocked" + * partitioning of items across threads (where consecutive items belong to a + * single thread). + * - WarpExchange supports the following types of data exchanges: + * - Transposing between [blocked](index.html#sec5sec3) and + * [striped](index.html#sec5sec3) arrangements + * - Scattering ranked items to a + * [striped arrangement](index.html#sec5sec3) + * + * @par A Simple Example + * @par + * The code snippet below illustrates the conversion from a "blocked" to a + * "striped" arrangement of 64 integer items partitioned across 16 threads where + * each thread owns 4 items. + * @par + * @code + * #include // or equivalently + * + * __global__ void ExampleKernel(int *d_data, ...) + * { + * constexpr int warp_threads = 16; + * constexpr int block_threads = 256; + * constexpr int items_per_thread = 4; + * constexpr int warps_per_block = block_threads / warp_threads; + * const int warp_id = static_cast(threadIdx.x) / warp_threads; + * + * // Specialize WarpExchange for a virtual warp of 16 threads owning 4 integer items each + * using WarpExchangeT = + * cub::WarpExchange; + * + * // Allocate shared memory for WarpExchange + * __shared__ typename WarpExchangeT::TempStorage temp_storage[warps_per_block]; + * + * // Load a tile of data striped across threads + * int thread_data[items_per_thread]; + * // ... + * + * // Collectively exchange data into a blocked arrangement across threads + * WarpExchangeT(temp_storage[warp_id]).StripedToBlocked(thread_data, thread_data); + * @endcode + * @par + * Suppose the set of striped input @p thread_data across the block of threads + * is { [0,16,32,48], [1,17,33,49], ..., [15, 32, 47, 63] }. + * The corresponding output @p thread_data in those threads will be + * { [0,1,2,3], [4,5,6,7], [8,9,10,11], ..., [60,61,62,63] }. + */ +template +class WarpExchange : private detail::InternalWarpExchangeImpl< + InputT, + ITEMS_PER_THREAD, + LOGICAL_WARP_THREADS, + WARP_EXCHANGE_ALGORITHM> +{ + using InternalWarpExchange = detail::InternalWarpExchangeImpl< + InputT, + ITEMS_PER_THREAD, + LOGICAL_WARP_THREADS, + WARP_EXCHANGE_ALGORITHM>; + +public: + + /// \smemstorage{WarpExchange} + using TempStorage = typename InternalWarpExchange::TempStorage; + + /*************************************************************************//** + * @name Collective constructors + ****************************************************************************/ + //@{ + + WarpExchange() = delete; + + /** + * @brief Collective constructor using the specified memory allocation as + * temporary storage. + */ + explicit __device__ __forceinline__ + WarpExchange(TempStorage &temp_storage) + : InternalWarpExchange(temp_storage) + { + + } + + //@} end member group + /*************************************************************************//** + * @name Data movement + ****************************************************************************/ + //@{ + + /** + * @brief Transposes data items from blocked arrangement to + * striped arrangement. + * + * @par + * @smemwarpreuse + * + * @par Snippet + * The code snippet below illustrates the conversion from a "blocked" to a + * "striped" arrangement of 64 integer items partitioned across 16 threads + * where each thread owns 4 items. + * @par + * @code + * #include // or equivalently + * + * __global__ void ExampleKernel(int *d_data, ...) + * { + * constexpr int warp_threads = 16; + * constexpr int block_threads = 256; + * constexpr int items_per_thread = 4; + * constexpr int warps_per_block = block_threads / warp_threads; + * const int warp_id = static_cast(threadIdx.x) / warp_threads; + * + * // Specialize WarpExchange for a virtual warp of 16 threads owning 4 integer items each + * using WarpExchangeT = cub::WarpExchange; + * + * // Allocate shared memory for WarpExchange + * __shared__ typename WarpExchangeT::TempStorage temp_storage[warps_per_block]; + * + * // Obtain a segment of consecutive items that are blocked across threads + * int thread_data[items_per_thread]; + * // ... + * + * // Collectively exchange data into a striped arrangement across threads + * WarpExchangeT(temp_storage[warp_id]).BlockedToStriped(thread_data, thread_data); + * @endcode + * @par + * Suppose the set of striped input @p thread_data across the block of threads + * is { [0,1,2,3], [4,5,6,7], [8,9,10,11], ..., [60,61,62,63] }. + * The corresponding output @p thread_data in those threads will be + * { [0,16,32,48], [1,17,33,49], ..., [15, 32, 47, 63] }. + * + * @param[in] input_items + * Items to exchange, converting between blocked and + * striped arrangements. + * + * @param[out] output_items + * Items from exchange, converting between striped and + * blocked arrangements. May be aliased to @p input_items. + */ + template + __device__ __forceinline__ void + BlockedToStriped(const InputT (&input_items)[ITEMS_PER_THREAD], + OutputT (&output_items)[ITEMS_PER_THREAD]) + { + InternalWarpExchange::BlockedToStriped(input_items, output_items); + } + + /** + * @brief Transposes data items from striped arrangement to + * blocked arrangement. + * + * @par + * @smemwarpreuse + * + * @par Snippet + * The code snippet below illustrates the conversion from a "striped" to a + * "blocked" arrangement of 64 integer items partitioned across 16 threads + * where each thread owns 4 items. + * @par + * @code + * #include // or equivalently + * + * __global__ void ExampleKernel(int *d_data, ...) + * { + * constexpr int warp_threads = 16; + * constexpr int block_threads = 256; + * constexpr int items_per_thread = 4; + * constexpr int warps_per_block = block_threads / warp_threads; + * const int warp_id = static_cast(threadIdx.x) / warp_threads; + * + * // Specialize WarpExchange for a virtual warp of 16 threads owning 4 integer items each + * using WarpExchangeT = cub::WarpExchange; + * + * // Allocate shared memory for WarpExchange + * __shared__ typename WarpExchangeT::TempStorage temp_storage[warps_per_block]; + * + * // Load a tile of data striped across threads + * int thread_data[items_per_thread]; + * // ... + * + * // Collectively exchange data into a blocked arrangement across threads + * WarpExchangeT(temp_storage[warp_id]).StripedToBlocked(thread_data, thread_data); + * @endcode + * @par + * Suppose the set of striped input @p thread_data across the block of threads + * is { [0,16,32,48], [1,17,33,49], ..., [15, 32, 47, 63] }. + * The corresponding output @p thread_data in those threads will be + * { [0,1,2,3], [4,5,6,7], [8,9,10,11], ..., [60,61,62,63] }. + * + * @param[in] input_items + * Items to exchange + * + * @param[out] output_items + * Items from exchange. May be aliased to @p input_items. + */ + template + __device__ __forceinline__ void + StripedToBlocked(const InputT (&input_items)[ITEMS_PER_THREAD], + OutputT (&output_items)[ITEMS_PER_THREAD]) + { + InternalWarpExchange::StripedToBlocked(input_items, output_items); + } + + /** + * @brief Exchanges valid data items annotated by rank + * into striped arrangement. + * + * @par + * @smemwarpreuse + * + * @par Snippet + * The code snippet below illustrates the conversion from a "scatter" to a + * "striped" arrangement of 64 integer items partitioned across 16 threads + * where each thread owns 4 items. + * @par + * @code + * #include // or equivalently + * + * __global__ void ExampleKernel(int *d_data, ...) + * { + * constexpr int warp_threads = 16; + * constexpr int block_threads = 256; + * constexpr int items_per_thread = 4; + * constexpr int warps_per_block = block_threads / warp_threads; + * const int warp_id = static_cast(threadIdx.x) / warp_threads; + * + * // Specialize WarpExchange for a virtual warp of 16 threads owning 4 integer items each + * using WarpExchangeT = cub::WarpExchange; + * + * // Allocate shared memory for WarpExchange + * __shared__ typename WarpExchangeT::TempStorage temp_storage[warps_per_block]; + * + * // Obtain a segment of consecutive items that are blocked across threads + * int thread_data[items_per_thread]; + * int thread_ranks[items_per_thread]; + * // ... + * + * // Collectively exchange data into a striped arrangement across threads + * WarpExchangeT(temp_storage[warp_id]).ScatterToStriped( + * thread_data, thread_ranks); + * @endcode + * @par + * Suppose the set of input @p thread_data across the block of threads + * is `{ [0,1,2,3], [4,5,6,7], ..., [60,61,62,63] }`, and the set of + * @p thread_ranks is `{ [63,62,61,60], ..., [7,6,5,4], [3,2,1,0] }`. The + * corresponding output @p thread_data in those threads will be + * `{ [63, 47, 31, 15], [62, 46, 30, 14], ..., [48, 32, 16, 0] }`. + * + * @tparam OffsetT [inferred] Signed integer type for local offsets + * + * @param[in,out] items Items to exchange + * @param[in] ranks Corresponding scatter ranks + */ + template + __device__ __forceinline__ void + ScatterToStriped(InputT (&items)[ITEMS_PER_THREAD], + OffsetT (&ranks)[ITEMS_PER_THREAD]) + { + InternalWarpExchange::ScatterToStriped(items, ranks); + } + + /** + * @brief Exchanges valid data items annotated by rank + * into striped arrangement. + * + * @par + * @smemwarpreuse + * + * @par Snippet + * The code snippet below illustrates the conversion from a "scatter" to a + * "striped" arrangement of 64 integer items partitioned across 16 threads + * where each thread owns 4 items. + * @par + * @code + * #include // or equivalently + * + * __global__ void ExampleKernel(int *d_data, ...) + * { + * constexpr int warp_threads = 16; + * constexpr int block_threads = 256; + * constexpr int items_per_thread = 4; + * constexpr int warps_per_block = block_threads / warp_threads; + * const int warp_id = static_cast(threadIdx.x) / warp_threads; + * + * // Specialize WarpExchange for a virtual warp of 16 threads owning 4 integer items each + * using WarpExchangeT = cub::WarpExchange; + * + * // Allocate shared memory for WarpExchange + * __shared__ typename WarpExchangeT::TempStorage temp_storage[warps_per_block]; + * + * // Obtain a segment of consecutive items that are blocked across threads + * int thread_input[items_per_thread]; + * int thread_ranks[items_per_thread]; + * // ... + * + * // Collectively exchange data into a striped arrangement across threads + * int thread_output[items_per_thread]; + * WarpExchangeT(temp_storage[warp_id]).ScatterToStriped( + * thread_input, thread_output, thread_ranks); + * @endcode + * @par + * Suppose the set of input @p thread_input across the block of threads + * is `{ [0,1,2,3], [4,5,6,7], ..., [60,61,62,63] }`, and the set of + * @p thread_ranks is `{ [63,62,61,60], ..., [7,6,5,4], [3,2,1,0] }`. The + * corresponding @p thread_output in those threads will be + * `{ [63, 47, 31, 15], [62, 46, 30, 14], ..., [48, 32, 16, 0] }`. + * + * @tparam OffsetT [inferred] Signed integer type for local offsets + * + * @param[in] input_items + * Items to exchange + * + * @param[out] output_items + * Items from exchange. May be aliased to @p input_items. + * + * @param[in] ranks + * Corresponding scatter ranks + */ + template + __device__ __forceinline__ void + ScatterToStriped(const InputT (&input_items)[ITEMS_PER_THREAD], + OutputT (&output_items)[ITEMS_PER_THREAD], + OffsetT (&ranks)[ITEMS_PER_THREAD]) + { + InternalWarpExchange::ScatterToStriped(input_items, output_items, ranks); + } + + //@} end member group +}; + + +CUB_NAMESPACE_END diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/warp/warp_load.cuh b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/warp/warp_load.cuh new file mode 100644 index 0000000000000000000000000000000000000000..df4ea98fcced030cb285c93b015e18abf7b39388 --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/warp/warp_load.cuh @@ -0,0 +1,638 @@ +/****************************************************************************** + * Copyright (c) 2011-2021, NVIDIA CORPORATION. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the NVIDIA CORPORATION nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ******************************************************************************/ + +//! @file Operations for reading linear tiles of data into the CUDA warp. + +#pragma once + +#include +#include +#include +#include +#include +#include + +#include +#include + +CUB_NAMESPACE_BEGIN + +//! @rst +//! ``cub::WarpLoadAlgorithm`` enumerates alternative algorithms for :cpp:struct:`cub::WarpLoad` to +//! read a linear segment of data from memory into a CUDA warp. +//! @endrst +enum WarpLoadAlgorithm +{ + //! @rst + //! Overview + //! ++++++++++++++++++++++++++ + //! + //! A :ref:`blocked arrangement ` of data is read directly from memory. + //! + //! Performance Considerations + //! ++++++++++++++++++++++++++ + //! + //! The utilization of memory transactions (coalescing) decreases as the + //! access stride between threads increases (i.e., the number items per thread). + //! @endrst + WARP_LOAD_DIRECT, + + //! @rst + //! Overview + //! ++++++++++++++++++++++++++ + //! + //! A :ref:`striped arrangement ` of data is read directly from memory. + //! + //! Performance Considerations + //! ++++++++++++++++++++++++++ + //! + //! The utilization of memory transactions (coalescing) doesn't depend on + //! the number of items per thread. + //! @endrst + WARP_LOAD_STRIPED, + + //! @rst + //! Overview + //! ++++++++++++++++++++++++++ + //! + //! A :ref:`blocked arrangement ` of data is read from memory using + //! CUDA's built-in vectorized loads as a coalescing optimization. + //! For example, ``ld.global.v4.s32`` instructions will be generated when ``T = int`` and + //! ``ITEMS_PER_THREAD % 4 == 0``. + //! + //! Performance Considerations + //! ++++++++++++++++++++++++++ + //! + //! - The utilization of memory transactions (coalescing) remains high until the the + //! access stride between threads (i.e., the number items per thread) exceeds the + //! maximum vector load width (typically 4 items or 64B, whichever is lower). + //! - The following conditions will prevent vectorization and loading will fall + //! back to cub::WARP_LOAD_DIRECT: + //! + //! - ``ITEMS_PER_THREAD`` is odd + //! - The ``InputIteratorT`` is not a simple pointer type + //! - The block input offset is not quadword-aligned + //! - The data type ``T`` is not a built-in primitive or CUDA vector type + //! (e.g., ``short``, ``int2``, ``double``, ``float2``, etc.) + //! @endrst + WARP_LOAD_VECTORIZE, + + //! @rst + //! Overview + //! ++++++++++++++++++++++++++ + //! + //! A :ref:`striped arrangement ` of data is read efficiently from + //! memory and then locally transposed into a + //! :ref:`blocked arrangement `. + //! + //! Performance Considerations + //! ++++++++++++++++++++++++++ + //! + //! - The utilization of memory transactions (coalescing) remains high + //! regardless of items loaded per thread. + //! - The local reordering incurs slightly longer latencies and throughput than the direct + //! ``cub::WARP_LOAD_DIRECT`` and ``cub::WARP_LOAD_VECTORIZE`` alternatives. + //! @endrst + WARP_LOAD_TRANSPOSE +}; + +//! @rst +//! The WarpLoad class provides :ref:`collective ` data movement methods for +//! loading a linear segment of items from memory into a +//! :ref:`blocked arrangement ` across a CUDA thread warp. +//! +//! Overview +//! ++++++++++++++++ +//! +//! - The WarpLoad class provides a single data movement abstraction that can be +//! specialized to implement different cub::WarpLoadAlgorithm strategies. This +//! facilitates different performance policies for different architectures, data +//! types, granularity sizes, etc. +//! - WarpLoad can be optionally specialized by different data movement strategies: +//! +//! #. :cpp:enumerator:`cub::WARP_LOAD_DIRECT`: +//! a :ref:`blocked arrangement ` of data is read directly from +//! memory. +//! #. :cpp:enumerator:`cub::WARP_LOAD_STRIPED`: +//! a :ref:`striped arrangement ` of data is read directly from +//! memory. +//! #. :cpp:enumerator:`cub::WARP_LOAD_VECTORIZE`: +//! a :ref:`blocked arrangement ` of data is read directly from +//! memory using CUDA's built-in vectorized loads as a coalescing optimization. +//! #. :cpp:enumerator:`cub::WARP_LOAD_TRANSPOSE`: +//! a :ref:`striped arrangement ` of data is read directly from +//! memory and is then locally transposed into a +//! :ref:`blocked arrangement `. +//! +//! A Simple Example +//! ++++++++++++++++ +//! +//! The code snippet below illustrates the loading of a linear segment of 64 +//! integers into a "blocked" arrangement across 16 threads where each thread +//! owns 4 consecutive items. The load is specialized for ``WARP_LOAD_TRANSPOSE``, +//! meaning memory references are efficiently coalesced using a warp-striped access +//! pattern (after which items are locally reordered among threads). +//! +//! .. code-block:: c++ +//! +//! #include // or equivalently +//! +//! __global__ void ExampleKernel(int *d_data, ...) +//! { +//! constexpr int warp_threads = 16; +//! constexpr int block_threads = 256; +//! constexpr int items_per_thread = 4; +//! +//! // Specialize WarpLoad for a warp of 16 threads owning 4 integer items each +//! using WarpLoadT = WarpLoad; +//! +//! constexpr int warps_in_block = block_threads / warp_threads; +//! constexpr int tile_size = items_per_thread * warp_threads; +//! const int warp_id = static_cast(threadIdx.x) / warp_threads; +//! +//! // Allocate shared memory for WarpLoad +//! __shared__ typename WarpLoadT::TempStorage temp_storage[warps_in_block]; +//! +//! // Load a segment of consecutive items that are blocked across threads +//! int thread_data[items_per_thread]; +//! WarpLoadT(temp_storage[warp_id]).Load(d_data + warp_id * tile_size, +//! thread_data); +//! +//! Suppose the input ``d_data`` is ``0, 1, 2, 3, 4, 5, ...``. +//! The set of ``thread_data`` across the first logical warp of threads in those +//! threads will be: ``{ [0,1,2,3], [4,5,6,7], ..., [60,61,62,63] }``. +//! @endrst +//! +//! @tparam InputT +//! The data type to read into (which must be convertible from the input +//! iterator's value type). +//! +//! @tparam ITEMS_PER_THREAD +//! The number of consecutive items partitioned onto each thread. +//! +//! @tparam ALGORITHM +//! [optional] cub::WarpLoadAlgorithm tuning policy. +//! default: cub::WARP_LOAD_DIRECT. +//! +//! @tparam LOGICAL_WARP_THREADS +//! [optional] The number of threads per "logical" warp (may be less +//! than the number of hardware warp threads). Default is the warp size of the +//! targeted CUDA compute-capability (e.g., 32 threads for SM86). Must be a +//! power of two. +//! +//! @tparam LEGACY_PTX_ARCH +//! Unused. +template +class WarpLoad +{ + constexpr static bool IS_ARCH_WARP = LOGICAL_WARP_THREADS == CUB_WARP_THREADS(0); + + static_assert(PowerOfTwo::VALUE, + "LOGICAL_WARP_THREADS must be a power of two"); + +private: + /***************************************************************************** + * Algorithmic variants + ****************************************************************************/ + + /// Load helper + template + struct LoadInternal; + + template + struct LoadInternal + { + using TempStorage = NullType; + + int linear_tid; + + __device__ __forceinline__ LoadInternal(TempStorage & /*temp_storage*/, int linear_tid) + : linear_tid(linear_tid) + {} + + template + __device__ __forceinline__ void Load(InputIteratorT block_itr, + InputT (&items)[ITEMS_PER_THREAD]) + { + LoadDirectBlocked(linear_tid, block_itr, items); + } + + template + __device__ __forceinline__ void Load(InputIteratorT block_itr, + InputT (&items)[ITEMS_PER_THREAD], + int valid_items) + { + LoadDirectBlocked(linear_tid, block_itr, items, valid_items); + } + + template + __device__ __forceinline__ void Load(InputIteratorT block_itr, + InputT (&items)[ITEMS_PER_THREAD], + int valid_items, + DefaultT oob_default) + { + LoadDirectBlocked(linear_tid, block_itr, items, valid_items, oob_default); + } + }; + + template + struct LoadInternal + { + using TempStorage = NullType; + + int linear_tid; + + __device__ __forceinline__ LoadInternal(TempStorage & /*temp_storage*/, int linear_tid) + : linear_tid(linear_tid) + {} + + template + __device__ __forceinline__ void Load(InputIteratorT block_itr, + InputT (&items)[ITEMS_PER_THREAD]) + { + LoadDirectStriped(linear_tid, block_itr, items); + } + + template + __device__ __forceinline__ void Load(InputIteratorT block_itr, + InputT (&items)[ITEMS_PER_THREAD], + int valid_items) + { + LoadDirectStriped(linear_tid, block_itr, items, valid_items); + } + + template + __device__ __forceinline__ void Load(InputIteratorT block_itr, + InputT (&items)[ITEMS_PER_THREAD], + int valid_items, + DefaultT oob_default) + { + LoadDirectStriped(linear_tid, + block_itr, + items, + valid_items, + oob_default); + } + }; + + template + struct LoadInternal + { + using TempStorage = NullType; + + int linear_tid; + + __device__ __forceinline__ LoadInternal(TempStorage & /*temp_storage*/, int linear_tid) + : linear_tid(linear_tid) + {} + + template + __device__ __forceinline__ void Load(InputT *block_ptr, InputT (&items)[ITEMS_PER_THREAD]) + { + InternalLoadDirectBlockedVectorized(linear_tid, block_ptr, items); + } + + template + __device__ __forceinline__ void Load(const InputT *block_ptr, InputT (&items)[ITEMS_PER_THREAD]) + { + InternalLoadDirectBlockedVectorized(linear_tid, block_ptr, items); + } + + template + __device__ __forceinline__ void + Load(CacheModifiedInputIterator block_itr, + InputT (&items)[ITEMS_PER_THREAD]) + { + InternalLoadDirectBlockedVectorized(linear_tid, block_itr.ptr, items); + } + + template + __device__ __forceinline__ void Load(_InputIteratorT block_itr, + InputT (&items)[ITEMS_PER_THREAD]) + { + LoadDirectBlocked(linear_tid, block_itr, items); + } + + template + __device__ __forceinline__ void Load(InputIteratorT block_itr, + InputT (&items)[ITEMS_PER_THREAD], + int valid_items) + { + LoadDirectBlocked(linear_tid, block_itr, items, valid_items); + } + + template + __device__ __forceinline__ void Load(InputIteratorT block_itr, + InputT (&items)[ITEMS_PER_THREAD], + int valid_items, + DefaultT oob_default) + { + LoadDirectBlocked(linear_tid, block_itr, items, valid_items, oob_default); + } + }; + + template + struct LoadInternal + { + using WarpExchangeT = WarpExchange; + + struct _TempStorage : WarpExchangeT::TempStorage + {}; + + struct TempStorage : Uninitialized<_TempStorage> + {}; + + _TempStorage &temp_storage; + + int linear_tid; + + __device__ __forceinline__ LoadInternal(TempStorage &temp_storage, int linear_tid) + : temp_storage(temp_storage.Alias()) + , linear_tid(linear_tid) + {} + + template + __device__ __forceinline__ void Load(InputIteratorT block_itr, + InputT (&items)[ITEMS_PER_THREAD]) + { + LoadDirectStriped(linear_tid, block_itr, items); + WarpExchangeT(temp_storage).StripedToBlocked(items, items); + } + + template + __device__ __forceinline__ void Load(InputIteratorT block_itr, + InputT (&items)[ITEMS_PER_THREAD], + int valid_items) + { + LoadDirectStriped(linear_tid, block_itr, items, valid_items); + WarpExchangeT(temp_storage).StripedToBlocked(items, items); + } + + template + __device__ __forceinline__ void Load(InputIteratorT block_itr, + InputT (&items)[ITEMS_PER_THREAD], + int valid_items, + DefaultT oob_default) + { + LoadDirectStriped(linear_tid, + block_itr, + items, + valid_items, + oob_default); + WarpExchangeT(temp_storage).StripedToBlocked(items, items); + } + }; + + /***************************************************************************** + * Type definitions + ****************************************************************************/ + + /// Internal load implementation to use + using InternalLoad = LoadInternal; + + /// Shared memory storage layout type + using _TempStorage = typename InternalLoad::TempStorage; + + /***************************************************************************** + * Utility methods + ****************************************************************************/ + + /// Internal storage allocator + __device__ __forceinline__ _TempStorage &PrivateStorage() + { + __shared__ _TempStorage private_storage; + return private_storage; + } + + /***************************************************************************** + * Thread fields + ****************************************************************************/ + + /// Thread reference to shared storage + _TempStorage &temp_storage; + + /// Linear thread-id + int linear_tid; + +public: + /// @smemstorage{WarpLoad} + struct TempStorage : Uninitialized<_TempStorage> + {}; + + //! @name Collective constructors + //! @{ + + //! @brief Collective constructor using a private static allocation of + //! shared memory as temporary storage. + __device__ __forceinline__ WarpLoad() + : temp_storage(PrivateStorage()) + , linear_tid(IS_ARCH_WARP ? LaneId() : (LaneId() % LOGICAL_WARP_THREADS)) + {} + + //! @brief Collective constructor using the specified memory allocation as + //! temporary storage. + __device__ __forceinline__ WarpLoad(TempStorage &temp_storage) + : temp_storage(temp_storage.Alias()) + , linear_tid(IS_ARCH_WARP ? LaneId() : (LaneId() % LOGICAL_WARP_THREADS)) + {} + + //! @} end member group + //! @name Data movement + //! @{ + + //! @rst + //! Load a linear segment of items from memory. + //! + //! @smemwarpreuse + //! + //! Snippet + //! +++++++ + //! + //! .. code-block:: c++ + //! + //! #include // or equivalently + //! + //! __global__ void ExampleKernel(int *d_data, ...) + //! { + //! constexpr int warp_threads = 16; + //! constexpr int block_threads = 256; + //! constexpr int items_per_thread = 4; + //! + //! // Specialize WarpLoad for a warp of 16 threads owning 4 integer items each + //! using WarpLoadT = WarpLoad; + //! + //! constexpr int warps_in_block = block_threads / warp_threads; + //! constexpr int tile_size = items_per_thread * warp_threads; + //! const int warp_id = static_cast(threadIdx.x) / warp_threads; + //! + //! // Allocate shared memory for WarpLoad + //! __shared__ typename WarpLoadT::TempStorage temp_storage[warps_in_block]; + //! + //! // Load a segment of consecutive items that are blocked across threads + //! int thread_data[items_per_thread]; + //! WarpLoadT(temp_storage[warp_id]).Load(d_data + warp_id * tile_size, + //! thread_data); + //! + //! Suppose the input ``d_data`` is ``0, 1, 2, 3, 4, 5, ...``, + //! The set of ``thread_data`` across the first logical warp of threads in those + //! threads will be: ``{ [0,1,2,3], [4,5,6,7], ..., [60,61,62,63] }``. + //! @endrst + //! + //! @param[in] block_itr The thread block's base input iterator for loading from + //! @param[out] items Data to load + template + __device__ __forceinline__ void Load(InputIteratorT block_itr, InputT (&items)[ITEMS_PER_THREAD]) + { + InternalLoad(temp_storage, linear_tid).Load(block_itr, items); + } + + //! @rst + //! Load a linear segment of items from memory, guarded by range. + //! + //! @smemwarpreuse + //! + //! Snippet + //! +++++++ + //! + //! .. code-block:: c++ + //! + //! #include // or equivalently + //! + //! __global__ void ExampleKernel(int *d_data, int valid_items, ...) + //! { + //! constexpr int warp_threads = 16; + //! constexpr int block_threads = 256; + //! constexpr int items_per_thread = 4; + //! + //! // Specialize WarpLoad for a warp of 16 threads owning 4 integer items each + //! using WarpLoadT = WarpLoad; + //! + //! constexpr int warps_in_block = block_threads / warp_threads; + //! constexpr int tile_size = items_per_thread * warp_threads; + //! const int warp_id = static_cast(threadIdx.x) / warp_threads; + //! + //! // Allocate shared memory for WarpLoad + //! __shared__ typename WarpLoadT::TempStorage temp_storage[warps_in_block]; + //! + //! // Load a segment of consecutive items that are blocked across threads + //! int thread_data[items_per_thread]; + //! WarpLoadT(temp_storage[warp_id]).Load(d_data + warp_id * tile_size, + //! thread_data, + //! valid_items); + //! + //! Suppose the input ``d_data`` is ``0, 1, 2, 3, 4, 5, ...`` and ``valid_items`` is ``5``. + //! The set of ``thread_data`` across the first logical warp of threads in those threads will be: + //! ``{ [0,1,2,3], [4,?,?,?], ..., [?,?,?,?] }`` with only the first two threads being unmasked to + //! load portions of valid data (and other items remaining unassigned). + //! @endrst + //! + //! @param[in] block_itr The thread block's base input iterator for loading from + //! @param[out] items Data to load + //! @param[in] valid_items Number of valid items to load + template + __device__ __forceinline__ void Load(InputIteratorT block_itr, + InputT (&items)[ITEMS_PER_THREAD], + int valid_items) + { + InternalLoad(temp_storage, linear_tid).Load(block_itr, items, valid_items); + } + + //! @rst + //! Load a linear segment of items from memory, guarded by range. + //! + //! @smemwarpreuse + //! + //! Snippet + //! +++++++ + //! + //! .. code-block:: c++ + //! + //! #include // or equivalently + //! + //! __global__ void ExampleKernel(int *d_data, int valid_items, ...) + //! { + //! constexpr int warp_threads = 16; + //! constexpr int block_threads = 256; + //! constexpr int items_per_thread = 4; + //! + //! // Specialize WarpLoad for a warp of 16 threads owning 4 integer items each + //! using WarpLoadT = WarpLoad; + //! + //! constexpr int warps_in_block = block_threads / warp_threads; + //! constexpr int tile_size = items_per_thread * warp_threads; + //! const int warp_id = static_cast(threadIdx.x) / warp_threads; + //! + //! // Allocate shared memory for WarpLoad + //! __shared__ typename WarpLoadT::TempStorage temp_storage[warps_in_block]; + //! + //! // Load a segment of consecutive items that are blocked across threads + //! int thread_data[items_per_thread]; + //! WarpLoadT(temp_storage[warp_id]).Load(d_data + warp_id * tile_size, + //! thread_data, + //! valid_items, + //! -1); + //! + //! Suppose the input ``d_data`` is ``0, 1, 2, 3, 4, 5, ...``, ``valid_items`` is ``5``, and the + //! out-of-bounds default is ``-1``. The set of ``thread_data`` across the first logical warp of + //! threads in those threads will be: ``{ [0,1,2,3], [4,-1,-1,-1], ..., [-1,-1,-1,-1] }`` with + //! only the first two threads being unmasked to load portions of valid data (and other items + //! are assigned ``-1``). + //! @endrst + //! + //! @param[in] block_itr The thread block's base input iterator for loading from + //! @param[out] items Data to load + //! @param[in] valid_items Number of valid items to load + //! @param[in] oob_default Default value to assign out-of-bound items + template + __device__ __forceinline__ void Load(InputIteratorT block_itr, + InputT (&items)[ITEMS_PER_THREAD], + int valid_items, + DefaultT oob_default) + { + InternalLoad(temp_storage, linear_tid).Load(block_itr, items, valid_items, oob_default); + } + + //! @} end member group +}; + +CUB_NAMESPACE_END diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/warp/warp_merge_sort.cuh b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/warp/warp_merge_sort.cuh new file mode 100644 index 0000000000000000000000000000000000000000..59892e925276f74534105dd47a35016f18650175 --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/warp/warp_merge_sort.cuh @@ -0,0 +1,159 @@ +/****************************************************************************** + * Copyright (c) 2011-2021, NVIDIA CORPORATION. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the NVIDIA CORPORATION nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ******************************************************************************/ + +#pragma once + +#include +#include +#include +#include + +CUB_NAMESPACE_BEGIN + +//! @rst +//! The WarpMergeSort class provides methods for sorting items partitioned across a CUDA warp +//! using a merge sorting method. +//! +//! Overview +//! ++++++++++++++++ +//! +//! WarpMergeSort arranges items into ascending order using a comparison +//! functor with less-than semantics. Merge sort can handle arbitrary types +//! and comparison functors. +//! +//! A Simple Example +//! ++++++++++++++++ +//! +//! The code snippet below illustrates a sort of 64 integer keys that are +//! partitioned across 16 threads where each thread owns 4 consecutive items. +//! +//! .. code-block:: c++ +//! +//! #include // or equivalently +//! +//! struct CustomLess +//! { +//! template +//! __device__ bool operator()(const DataType &lhs, const DataType &rhs) +//! { +//! return lhs < rhs; +//! } +//! }; +//! +//! __global__ void ExampleKernel(...) +//! { +//! constexpr int warp_threads = 16; +//! constexpr int block_threads = 256; +//! constexpr int items_per_thread = 4; +//! constexpr int warps_per_block = block_threads / warp_threads; +//! const int warp_id = static_cast(threadIdx.x) / warp_threads; +//! +//! // Specialize WarpMergeSort for a virtual warp of 16 threads +//! // owning 4 integer items each +//! using WarpMergeSortT = +//! cub::WarpMergeSort; +//! +//! // Allocate shared memory for WarpMergeSort +//! __shared__ typename WarpMergeSortT::TempStorage temp_storage[warps_per_block]; +//! +//! // Obtain a segment of consecutive items that are blocked across threads +//! int thread_keys[items_per_thread]; +//! // ... +//! +//! WarpMergeSortT(temp_storage[warp_id]).Sort(thread_keys, CustomLess()); +//! // ... +//! } +//! +//! Suppose the set of input ``thread_keys`` across a warp of threads is +//! ``{ [0,64,1,63], [2,62,3,61], [4,60,5,59], ..., [31,34,32,33] }``. +//! The corresponding output ``thread_keys`` in those threads will be +//! ``{ [0,1,2,3], [4,5,6,7], [8,9,10,11], ..., [31,32,33,34] }``. +//! @endrst +//! +//! @tparam KeyT +//! Key type +//! +//! @tparam ITEMS_PER_THREAD +//! The number of items per thread +//! +//! @tparam LOGICAL_WARP_THREADS +//! [optional] The number of threads per "logical" warp (may be less +//! than the number of hardware warp threads). Default is the warp size of the +//! targeted CUDA compute-capability (e.g., 32 threads for SM86). Must be a +//! power of two. +//! +//! @tparam ValueT +//! [optional] Value type (default: cub::NullType, which indicates a +//! keys-only sort) +//! +//! @tparam LEGACY_PTX_ARCH +//! Unused. +//! +template +class WarpMergeSort + : public BlockMergeSortStrategy< + KeyT, + ValueT, + LOGICAL_WARP_THREADS, + ITEMS_PER_THREAD, + WarpMergeSort> +{ +private: + constexpr static bool IS_ARCH_WARP = LOGICAL_WARP_THREADS == CUB_WARP_THREADS(0); + constexpr static bool KEYS_ONLY = std::is_same::value; + constexpr static int TILE_SIZE = ITEMS_PER_THREAD * LOGICAL_WARP_THREADS; + + using BlockMergeSortStrategyT = + BlockMergeSortStrategy; + + const unsigned int warp_id; + const unsigned int member_mask; + +public: + WarpMergeSort() = delete; + + __device__ __forceinline__ + WarpMergeSort(typename BlockMergeSortStrategyT::TempStorage &temp_storage) + : BlockMergeSortStrategyT(temp_storage, + IS_ARCH_WARP ? LaneId() : (LaneId() % LOGICAL_WARP_THREADS)) + , warp_id(IS_ARCH_WARP ? 0 : (LaneId() / LOGICAL_WARP_THREADS)) + , member_mask(WarpMask(warp_id)) + {} + + __device__ __forceinline__ unsigned int get_member_mask() const { return member_mask; } + +private: + __device__ __forceinline__ void SyncImplementation() const { WARP_SYNC(member_mask); } + + friend BlockMergeSortStrategyT; +}; + +CUB_NAMESPACE_END diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/warp/warp_reduce.cuh b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/warp/warp_reduce.cuh new file mode 100644 index 0000000000000000000000000000000000000000..2901f56bbcc4c6fc4fba561d92ffb1a5f4571064 --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/warp/warp_reduce.cuh @@ -0,0 +1,747 @@ +/****************************************************************************** + * Copyright (c) 2011, Duane Merrill. All rights reserved. + * Copyright (c) 2011-2018, NVIDIA CORPORATION. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the NVIDIA CORPORATION nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ******************************************************************************/ + +//! @file +//! @rst +//! The ``cub::WarpReduce`` class provides :ref:`collective ` methods for +//! computing a parallel reduction of items partitioned across a CUDA thread warp. +//! @endrst + +#pragma once + +#include +#include +#include +#include +#include + +CUB_NAMESPACE_BEGIN + +//! @rst +//! The ``WarpReduce`` class provides :ref:`collective ` methods for +//! computing a parallel reduction of items partitioned across a CUDA thread warp. +//! +//! .. image:: ../img/warp_reduce_logo.png +//! :align: center +//! +//! Overview +//! ++++++++++++++++++++++++++ +//! +//! - A `reduction `__ (or *fold*) +//! uses a binary combining operator to compute a single aggregate from a list of input elements. +//! - Supports "logical" warps smaller than the physical warp size (e.g., logical warps of 8 +//! threads) +//! - The number of entrant threads must be an multiple of ``LOGICAL_WARP_THREADS`` +//! +//! Performance Considerations +//! ++++++++++++++++++++++++++ +//! +//! - Uses special instructions when applicable (e.g., warp ``SHFL`` instructions) +//! - Uses synchronization-free communication between warp lanes when applicable +//! - Incurs zero bank conflicts for most types +//! - Computation is slightly more efficient (i.e., having lower instruction overhead) for: +//! +//! - Summation (**vs.** generic reduction) +//! - The architecture's warp size is a whole multiple of ``LOGICAL_WARP_THREADS`` +//! +//! Simple Examples +//! ++++++++++++++++++++++++++ +//! +//! @warpcollective{WarpReduce} +//! +//! The code snippet below illustrates four concurrent warp sum reductions within a block of +//! 128 threads (one per each of the 32-thread warps). +//! +//! .. code-block:: c++ +//! +//! #include +//! +//! __global__ void ExampleKernel(...) +//! { +//! // Specialize WarpReduce for type int +//! typedef cub::WarpReduce WarpReduce; +//! +//! // Allocate WarpReduce shared memory for 4 warps +//! __shared__ typename WarpReduce::TempStorage temp_storage[4]; +//! +//! // Obtain one input item per thread +//! int thread_data = ... +//! +//! // Return the warp-wide sums to each lane0 (threads 0, 32, 64, and 96) +//! int warp_id = threadIdx.x / 32; +//! int aggregate = WarpReduce(temp_storage[warp_id]).Sum(thread_data); +//! +//! Suppose the set of input ``thread_data`` across the block of threads is +//! ``{0, 1, 2, 3, ..., 127}``. The corresponding output ``aggregate`` in threads 0, 32, 64, and 96 +//! will be ``496``, ``1520``, ``2544``, and ``3568``, respectively +//! (and is undefined in other threads). +//! +//! The code snippet below illustrates a single warp sum reduction within a block of +//! 128 threads. +//! +//! .. code-block:: c++ +//! +//! #include +//! +//! __global__ void ExampleKernel(...) +//! { +//! // Specialize WarpReduce for type int +//! typedef cub::WarpReduce WarpReduce; +//! +//! // Allocate WarpReduce shared memory for one warp +//! __shared__ typename WarpReduce::TempStorage temp_storage; +//! ... +//! +//! // Only the first warp performs a reduction +//! if (threadIdx.x < 32) +//! { +//! // Obtain one input item per thread +//! int thread_data = ... +//! +//! // Return the warp-wide sum to lane0 +//! int aggregate = WarpReduce(temp_storage).Sum(thread_data); +//! +//! Suppose the set of input ``thread_data`` across the warp of threads is +//! ``{0, 1, 2, 3, ..., 31}``. The corresponding output ``aggregate`` in thread0 will be ``496`` +//! (and is undefined in other threads). +//! @endrst +//! +//! @tparam T +//! The reduction input/output element type +//! +//! @tparam LOGICAL_WARP_THREADS +//! [optional] The number of threads per "logical" warp (may be less than the number of +//! hardware warp threads). Default is the warp size of the targeted CUDA compute-capability +//! (e.g., 32 threads for SM20). +//! +//! @tparam LEGACY_PTX_ARCH +//! [optional] Unused. +template +class WarpReduce +{ +private: + /****************************************************************************** + * Constants and type definitions + ******************************************************************************/ + + enum + { + /// Whether the logical warp size and the PTX warp size coincide + IS_ARCH_WARP = (LOGICAL_WARP_THREADS == CUB_WARP_THREADS(0)), + + /// Whether the logical warp size is a power-of-two + IS_POW_OF_TWO = PowerOfTwo::VALUE, + }; + +public: +#ifndef DOXYGEN_SHOULD_SKIP_THIS // Do not document + + /// Internal specialization. + /// Use SHFL-based reduction if LOGICAL_WARP_THREADS is a power-of-two + using InternalWarpReduce = cub::detail::conditional_t, + WarpReduceSmem>; + +#endif // DOXYGEN_SHOULD_SKIP_THIS + +private: + /// Shared memory storage layout type for WarpReduce + using _TempStorage = typename InternalWarpReduce::TempStorage; + + /****************************************************************************** + * Thread fields + ******************************************************************************/ + + /// Shared storage reference + _TempStorage &temp_storage; + + /****************************************************************************** + * Utility methods + ******************************************************************************/ + +public: + /// \smemstorage{WarpReduce} + struct TempStorage : Uninitialized<_TempStorage> + {}; + + //! @name Collective constructors + //! @{ + + //! @rst + //! Collective constructor using the specified memory allocation as temporary storage. + //! Logical warp and lane identifiers are constructed from ``threadIdx.x``. + //! @endrst + //! + //! @param[in] temp_storage Reference to memory allocation having layout type TempStorage + __device__ __forceinline__ WarpReduce(TempStorage &temp_storage) + : temp_storage(temp_storage.Alias()) + {} + + //! @} end member group + //! @name Summation reductions + //! @{ + + //! @rst + //! Computes a warp-wide sum in the calling warp. + //! The output is valid in warp *lane*\ :sub:`0`. + //! + //! @smemwarpreuse + //! + //! Snippet + //! +++++++ + //! + //! The code snippet below illustrates four concurrent warp sum reductions within a block of + //! 128 threads (one per each of the 32-thread warps). + //! + //! .. code-block:: c++ + //! + //! #include + //! + //! __global__ void ExampleKernel(...) + //! { + //! // Specialize WarpReduce for type int + //! typedef cub::WarpReduce WarpReduce; + //! + //! // Allocate WarpReduce shared memory for 4 warps + //! __shared__ typename WarpReduce::TempStorage temp_storage[4]; + //! + //! // Obtain one input item per thread + //! int thread_data = ... + //! + //! // Return the warp-wide sums to each lane0 + //! int warp_id = threadIdx.x / 32; + //! int aggregate = WarpReduce(temp_storage[warp_id]).Sum(thread_data); + //! + //! Suppose the set of input ``thread_data`` across the block of threads is + //! ``{0, 1, 2, 3, ..., 127}``. + //! The corresponding output ``aggregate`` in threads 0, 32, 64, and 96 will ``496``, ``1520``, + //! ``2544``, and ``3568``, respectively (and is undefined in other threads). + //! @endrst + //! + //! @param[in] input Calling thread's input + __device__ __forceinline__ T Sum(T input) + { + return InternalWarpReduce(temp_storage) + .template Reduce(input, LOGICAL_WARP_THREADS, cub::Sum()); + } + + //! @rst + //! Computes a partially-full warp-wide sum in the calling warp. + //! The output is valid in warp *lane*\ :sub:`0`. + //! + //! All threads across the calling warp must agree on the same value for ``valid_items``. + //! Otherwise the result is undefined. + //! + //! @smemwarpreuse + //! + //! Snippet + //! +++++++ + //! + //! The code snippet below illustrates a sum reduction within a single, partially-full + //! block of 32 threads (one warp). + //! + //! .. code-block:: c++ + //! + //! #include + //! + //! __global__ void ExampleKernel(int *d_data, int valid_items) + //! { + //! // Specialize WarpReduce for type int + //! typedef cub::WarpReduce WarpReduce; + //! + //! // Allocate WarpReduce shared memory for one warp + //! __shared__ typename WarpReduce::TempStorage temp_storage; + //! + //! // Obtain one input item per thread if in range + //! int thread_data; + //! if (threadIdx.x < valid_items) + //! thread_data = d_data[threadIdx.x]; + //! + //! // Return the warp-wide sums to each lane0 + //! int aggregate = WarpReduce(temp_storage).Sum( + //! thread_data, valid_items); + //! + //! Suppose the input ``d_data`` is ``{0, 1, 2, 3, 4, ...`` and ``valid_items`` is ``4``. + //! The corresponding output ``aggregate`` in *lane*\ :sub:`0` is ``6`` + //! (and is undefined in other threads). + //! @endrst + //! + //! @param[in] input + //! Calling thread's input + //! + //! @param[in] valid_items + //! Total number of valid items in the calling thread's logical warp + //! (may be less than ``LOGICAL_WARP_THREADS``) + __device__ __forceinline__ T Sum(T input, int valid_items) + { + // Determine if we don't need bounds checking + return InternalWarpReduce(temp_storage).template Reduce(input, valid_items, cub::Sum()); + } + + //! @rst + //! Computes a segmented sum in the calling warp where segments are defined by head-flags. + //! The sum of each segment is returned to the first lane in that segment + //! (which always includes *lane*\ :sub:`0`). + //! + //! @smemwarpreuse + //! + //! Snippet + //! +++++++ + //! + //! The code snippet below illustrates a head-segmented warp sum + //! reduction within a block of 32 threads (one warp). + //! + //! .. code-block:: c++ + //! + //! #include + //! + //! __global__ void ExampleKernel(...) + //! { + //! // Specialize WarpReduce for type int + //! typedef cub::WarpReduce WarpReduce; + //! + //! // Allocate WarpReduce shared memory for one warp + //! __shared__ typename WarpReduce::TempStorage temp_storage; + //! + //! // Obtain one input item and flag per thread + //! int thread_data = ... + //! int head_flag = ... + //! + //! // Return the warp-wide sums to each lane0 + //! int aggregate = WarpReduce(temp_storage).HeadSegmentedSum( + //! thread_data, head_flag); + //! + //! Suppose the set of input ``thread_data`` and ``head_flag`` across the block of threads + //! is ``{0, 1, 2, 3, ..., 31`` and is ``{1, 0, 0, 0, 1, 0, 0, 0, ..., 1, 0, 0, 0``, + //! respectively. The corresponding output ``aggregate`` in threads 0, 4, 8, etc. will be + //! ``6``, ``22``, ``38``, etc. (and is undefined in other threads). + //! @endrst + //! + //! @tparam ReductionOp + //! **[inferred]** Binary reduction operator type having member + //! `T operator()(const T &a, const T &b)` + //! + //! @param[in] input + //! Calling thread's input + //! + //! @param[in] head_flag + //! Head flag denoting whether or not `input` is the start of a new segment + template + __device__ __forceinline__ T HeadSegmentedSum(T input, FlagT head_flag) + { + return HeadSegmentedReduce(input, head_flag, cub::Sum()); + } + + //! @rst + //! Computes a segmented sum in the calling warp where segments are defined by tail-flags. + //! The sum of each segment is returned to the first lane in that segment + //! (which always includes *lane*\ :sub:`0`). + //! + //! @smemwarpreuse + //! + //! Snippet + //! +++++++ + //! + //! The code snippet below illustrates a tail-segmented warp sum reduction within a block of 32 + //! threads (one warp). + //! + //! .. code-block:: c++ + //! + //! #include + //! + //! __global__ void ExampleKernel(...) + //! { + //! // Specialize WarpReduce for type int + //! typedef cub::WarpReduce WarpReduce; + //! + //! // Allocate WarpReduce shared memory for one warp + //! __shared__ typename WarpReduce::TempStorage temp_storage; + //! + //! // Obtain one input item and flag per thread + //! int thread_data = ... + //! int tail_flag = ... + //! + //! // Return the warp-wide sums to each lane0 + //! int aggregate = WarpReduce(temp_storage).TailSegmentedSum( + //! thread_data, tail_flag); + //! + //! Suppose the set of input ``thread_data`` and ``tail_flag`` across the block of threads + //! is ``{0, 1, 2, 3, ..., 31}`` and is ``{0, 0, 0, 1, 0, 0, 0, 1, ..., 0, 0, 0, 1}``, + //! respectively. The corresponding output ``aggregate`` in threads 0, 4, 8, etc. will be + //! ``6``, ``22``, ``38``, etc. (and is undefined in other threads). + //! @endrst + //! + //! @tparam ReductionOp + //! **[inferred]** Binary reduction operator type having member + //! `T operator()(const T &a, const T &b)` + //! + //! @param[in] input + //! Calling thread's input + //! + //! @param[in] tail_flag + //! Head flag denoting whether or not `input` is the start of a new segment + template + __device__ __forceinline__ T TailSegmentedSum(T input, FlagT tail_flag) + { + return TailSegmentedReduce(input, tail_flag, cub::Sum()); + } + + //! @} end member group + //! @name Generic reductions + //! @{ + + //! @rst + //! Computes a warp-wide reduction in the calling warp using the specified binary reduction + //! functor. The output is valid in warp *lane*\ :sub:`0`. + //! + //! Supports non-commutative reduction operators + //! + //! @smemwarpreuse + //! + //! Snippet + //! +++++++ + //! + //! The code snippet below illustrates four concurrent warp max reductions within a block of + //! 128 threads (one per each of the 32-thread warps). + //! + //! .. code-block:: c++ + //! + //! #include + //! + //! __global__ void ExampleKernel(...) + //! { + //! // Specialize WarpReduce for type int + //! typedef cub::WarpReduce WarpReduce; + //! + //! // Allocate WarpReduce shared memory for 4 warps + //! __shared__ typename WarpReduce::TempStorage temp_storage[4]; + //! + //! // Obtain one input item per thread + //! int thread_data = ... + //! + //! // Return the warp-wide reductions to each lane0 + //! int warp_id = threadIdx.x / 32; + //! int aggregate = WarpReduce(temp_storage[warp_id]).Reduce( + //! thread_data, cub::Max()); + //! + //! Suppose the set of input ``thread_data`` across the block of threads is + //! ``{0, 1, 2, 3, ..., 127}``. The corresponding output ``aggregate`` in threads 0, 32, 64, and + //! 96 will be ``31``, ``63``, ``95``, and ``127``, respectively + //! (and is undefined in other threads). + //! @endrst + //! + //! @tparam ReductionOp + //! **[inferred]** Binary reduction operator type having member + //! `T operator()(const T &a, const T &b)` + //! + //! @param[in] input + //! Calling thread's input + //! + //! @param[in] reduction_op + //! Binary reduction operator + template + __device__ __forceinline__ T Reduce(T input, ReductionOp reduction_op) + { + return InternalWarpReduce(temp_storage) + .template Reduce(input, LOGICAL_WARP_THREADS, reduction_op); + } + + //! @rst + //! Computes a partially-full warp-wide reduction in the calling warp using the specified binary + //! reduction functor. The output is valid in warp *lane*\ :sub:`0`. + //! + //! All threads across the calling warp must agree on the same value for ``valid_items``. + //! Otherwise the result is undefined. + //! + //! Supports non-commutative reduction operators + //! + //! @smemwarpreuse + //! + //! Snippet + //! +++++++ + //! + //! The code snippet below illustrates a max reduction within a single, partially-full + //! block of 32 threads (one warp). + //! + //! .. code-block:: c++ + //! + //! #include + //! + //! __global__ void ExampleKernel(int *d_data, int valid_items) + //! { + //! // Specialize WarpReduce for type int + //! typedef cub::WarpReduce WarpReduce; + //! + //! // Allocate WarpReduce shared memory for one warp + //! __shared__ typename WarpReduce::TempStorage temp_storage; + //! + //! // Obtain one input item per thread if in range + //! int thread_data; + //! if (threadIdx.x < valid_items) + //! thread_data = d_data[threadIdx.x]; + //! + //! // Return the warp-wide reductions to each lane0 + //! int aggregate = WarpReduce(temp_storage).Reduce( + //! thread_data, cub::Max(), valid_items); + //! + //! Suppose the input ``d_data`` is ``{0, 1, 2, 3, 4, ... }`` and ``valid_items`` + //! is ``4``. The corresponding output ``aggregate`` in thread0 is ``3`` (and is + //! undefined in other threads). + //! @endrst + //! + //! @tparam ReductionOp + //! **[inferred]** Binary reduction operator type having member + //! `T operator()(const T &a, const T &b)` + //! + //! @param[in] input + //! Calling thread's input + //! + //! @param[in] reduction_op + //! Binary reduction operator + //! + //! @param[in] valid_items + //! Total number of valid items in the calling thread's logical warp + //! (may be less than ``LOGICAL_WARP_THREADS``) + template + __device__ __forceinline__ T Reduce(T input, ReductionOp reduction_op, int valid_items) + { + return InternalWarpReduce(temp_storage).template Reduce(input, valid_items, reduction_op); + } + + //! @rst + //! Computes a segmented reduction in the calling warp where segments are defined by head-flags. + //! The reduction of each segment is returned to the first lane in that segment + //! (which always includes *lane*\ :sub:`0`). + //! + //! Supports non-commutative reduction operators + //! + //! @smemwarpreuse + //! + //! Snippet + //! +++++++ + //! + //! The code snippet below illustrates a head-segmented warp max + //! reduction within a block of 32 threads (one warp). + //! + //! .. code-block:: c++ + //! + //! #include + //! + //! __global__ void ExampleKernel(...) + //! { + //! // Specialize WarpReduce for type int + //! typedef cub::WarpReduce WarpReduce; + //! + //! // Allocate WarpReduce shared memory for one warp + //! __shared__ typename WarpReduce::TempStorage temp_storage; + //! + //! // Obtain one input item and flag per thread + //! int thread_data = ... + //! int head_flag = ... + //! + //! // Return the warp-wide reductions to each lane0 + //! int aggregate = WarpReduce(temp_storage).HeadSegmentedReduce( + //! thread_data, head_flag, cub::Max()); + //! + //! Suppose the set of input ``thread_data`` and ``head_flag`` across the block of threads + //! is ``{0, 1, 2, 3, ..., 31}`` and is ``{1, 0, 0, 0, 1, 0, 0, 0, ..., 1, 0, 0, 0}``, + //! respectively. The corresponding output ``aggregate`` in threads 0, 4, 8, etc. will be + //! ``3``, ``7``, ``11``, etc. (and is undefined in other threads). + //! @endrst + //! + //! @tparam ReductionOp + //! **[inferred]** Binary reduction operator type having member + //! `T operator()(const T &a, const T &b)` + //! + //! @param[in] input + //! Calling thread's input + //! + //! @param[in] head_flag + //! Head flag denoting whether or not `input` is the start of a new segment + //! + //! @param[in] reduction_op + //! Reduction operator + template + __device__ __forceinline__ T HeadSegmentedReduce(T input, + FlagT head_flag, + ReductionOp reduction_op) + { + return InternalWarpReduce(temp_storage) + .template SegmentedReduce(input, head_flag, reduction_op); + } + + //! @rst + //! Computes a segmented reduction in the calling warp where segments are defined by tail-flags. + //! The reduction of each segment is returned to the first lane in that segment + //! (which always includes *lane*\ :sub:`0`). + //! + //! Supports non-commutative reduction operators + //! + //! @smemwarpreuse + //! + //! Snippet + //! +++++++ + //! + //! The code snippet below illustrates a tail-segmented warp max + //! reduction within a block of 32 threads (one warp). + //! + //! .. code-block:: c++ + //! + //! #include + //! + //! __global__ void ExampleKernel(...) + //! { + //! // Specialize WarpReduce for type int + //! typedef cub::WarpReduce WarpReduce; + //! + //! // Allocate WarpReduce shared memory for one warp + //! __shared__ typename WarpReduce::TempStorage temp_storage; + //! + //! // Obtain one input item and flag per thread + //! int thread_data = ... + //! int tail_flag = ... + //! + //! // Return the warp-wide reductions to each lane0 + //! int aggregate = WarpReduce(temp_storage).TailSegmentedReduce( + //! thread_data, tail_flag, cub::Max()); + //! + //! Suppose the set of input ``thread_data`` and ``tail_flag`` across the block of threads + //! is ``{0, 1, 2, 3, ..., 31}`` and is ``{0, 0, 0, 1, 0, 0, 0, 1, ..., 0, 0, 0, 1}``, + //! respectively. The corresponding output ``aggregate`` in threads 0, 4, 8, etc. will be + //! ``3``, ``7``, ``11``, etc. (and is undefined in other threads). + //! @endrst + //! + //! @tparam ReductionOp + //! **[inferred]** Binary reduction operator type having member + //! `T operator()(const T &a, const T &b)` + //! + //! @param[in] input + //! Calling thread's input + //! + //! @param[in] tail_flag + //! Tail flag denoting whether or not \p input is the end of the current segment + //! + //! @param[in] reduction_op + //! Reduction operator + template + __device__ __forceinline__ T TailSegmentedReduce(T input, + FlagT tail_flag, + ReductionOp reduction_op) + { + return InternalWarpReduce(temp_storage) + .template SegmentedReduce(input, tail_flag, reduction_op); + } + + //! @} end member group +}; + +#ifndef DOXYGEN_SHOULD_SKIP_THIS // Do not document +template +class WarpReduce +{ +private: + using _TempStorage = cub::NullType; + +public: + struct InternalWarpReduce + { + struct TempStorage : Uninitialized<_TempStorage> + {}; + + __device__ __forceinline__ InternalWarpReduce(TempStorage & /*temp_storage */) {} + + template + __device__ __forceinline__ T Reduce(T input, + int /* valid_items */, + ReductionOp /* reduction_op */) + { + return input; + } + + template + __device__ __forceinline__ T SegmentedReduce(T input, + FlagT /* flag */, + ReductionOp /* reduction_op */) + { + return input; + } + }; + + using TempStorage = typename InternalWarpReduce::TempStorage; + + __device__ __forceinline__ WarpReduce(TempStorage & /*temp_storage */) {} + + __device__ __forceinline__ T Sum(T input) { return input; } + + __device__ __forceinline__ T Sum(T input, int /* valid_items */) { return input; } + + template + __device__ __forceinline__ T HeadSegmentedSum(T input, FlagT /* head_flag */) + { + return input; + } + + template + __device__ __forceinline__ T TailSegmentedSum(T input, FlagT /* tail_flag */) + { + return input; + } + + template + __device__ __forceinline__ T Reduce(T input, ReductionOp /* reduction_op */) + { + return input; + } + + template + __device__ __forceinline__ T Reduce(T input, + ReductionOp /* reduction_op */, + int /* valid_items */) + { + return input; + } + + template + __device__ __forceinline__ T HeadSegmentedReduce(T input, + FlagT /* head_flag */, + ReductionOp /* reduction_op */) + { + return input; + } + + template + __device__ __forceinline__ T TailSegmentedReduce(T input, + FlagT /* tail_flag */, + ReductionOp /* reduction_op */) + { + return input; + } +}; +#endif // DOXYGEN_SHOULD_SKIP_THIS + +CUB_NAMESPACE_END diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/warp/warp_scan.cuh b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/warp/warp_scan.cuh new file mode 100644 index 0000000000000000000000000000000000000000..feff7ffe69d812590be8bf557b0287ea6d0b5690 --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/warp/warp_scan.cuh @@ -0,0 +1,1043 @@ +/****************************************************************************** + * Copyright (c) 2011, Duane Merrill. All rights reserved. + * Copyright (c) 2011-2018, NVIDIA CORPORATION. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the NVIDIA CORPORATION nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ******************************************************************************/ + +//! @file +//! @rst +//! The ``cub::WarpScan`` class provides :ref:`collective ` methods for +//! computing a parallel prefix scan of items partitioned across a CUDA thread warp. +//! @endrst + +#pragma once + +#include +#include +#include +#include +#include + +CUB_NAMESPACE_BEGIN + +//! @rst +//! The WarpScan class provides :ref:`collective ` methods for computing a +//! parallel prefix scan of items partitioned across a CUDA thread warp. +//! +//! .. image:: ../img/warp_scan_logo.png +//! :align: center +//! +//! Overview +//! ++++++++++++++++++++++++++ +//! +//! * Given a list of input elements and a binary reduction operator, a +//! `prefix scan `__ produces an output list where each +//! element is computed to be the reduction of the elements occurring earlier in the input list. +//! *Prefix sum* connotes a prefix scan with the addition operator. The term *inclusive* +//! indicates that the *i*\ :sup:`th` output reduction incorporates the *i*\ :sup:`th` input. +//! The term *exclusive* indicates the *i*\ :sup:`th` input is not incorporated into +//! the *i*\ :sup:`th` output reduction. +//! * Supports non-commutative scan operators +//! * Supports "logical" warps smaller than the physical warp size +//! (e.g., a logical warp of 8 threads) +//! * The number of entrant threads must be an multiple of ``LOGICAL_WARP_THREADS`` +//! +//! Performance Considerations +//! ++++++++++++++++++++++++++ +//! +//! * Uses special instructions when applicable (e.g., warp ``SHFL``) +//! * Uses synchronization-free communication between warp lanes when applicable +//! * Incurs zero bank conflicts for most types +//! * Computation is slightly more efficient (i.e., having lower instruction overhead) for: +//! +//! * Summation (**vs.** generic scan) +//! * The architecture's warp size is a whole multiple of ``LOGICAL_WARP_THREADS`` +//! +//! Simple Examples +//! ++++++++++++++++++++++++++ +//! +//! @warpcollective{WarpScan} +//! +//! The code snippet below illustrates four concurrent warp prefix sums within a block of +//! 128 threads (one per each of the 32-thread warps). +//! +//! .. code-block:: c++ +//! +//! #include +//! +//! __global__ void ExampleKernel(...) +//! { +//! // Specialize WarpScan for type int +//! typedef cub::WarpScan WarpScan; +//! +//! // Allocate WarpScan shared memory for 4 warps +//! __shared__ typename WarpScan::TempStorage temp_storage[4]; +//! +//! // Obtain one input item per thread +//! int thread_data = ... +//! +//! // Compute warp-wide prefix sums +//! int warp_id = threadIdx.x / 32; +//! WarpScan(temp_storage[warp_id]).ExclusiveSum(thread_data, thread_data); +//! +//! Suppose the set of input ``thread_data`` across the block of threads is +//! ``{1, 1, 1, 1, ...}``. The corresponding output ``thread_data`` in each of the four warps of +//! threads will be ``0, 1, 2, 3, ..., 31}``. +//! +//! The code snippet below illustrates a single warp prefix sum within a block of +//! 128 threads. +//! +//! .. code-block:: c++ +//! +//! #include +//! +//! __global__ void ExampleKernel(...) +//! { +//! // Specialize WarpScan for type int +//! typedef cub::WarpScan WarpScan; +//! +//! // Allocate WarpScan shared memory for one warp +//! __shared__ typename WarpScan::TempStorage temp_storage; +//! ... +//! +//! // Only the first warp performs a prefix sum +//! if (threadIdx.x < 32) +//! { +//! // Obtain one input item per thread +//! int thread_data = ... +//! +//! // Compute warp-wide prefix sums +//! WarpScan(temp_storage).ExclusiveSum(thread_data, thread_data); +//! +//! Suppose the set of input ``thread_data`` across the warp of threads is +//! ``{1, 1, 1, 1, ...}``. The corresponding output ``thread_data`` will be +//! ``{0, 1, 2, 3, ..., 31}``. +//! @endrst +//! +//! @tparam T +//! The scan input/output element type +//! +//! @tparam LOGICAL_WARP_THREADS +//! **[optional]** The number of threads per "logical" warp (may be less than the number of +//! hardware warp threads). Default is the warp size associated with the CUDA Compute Capability +//! targeted by the compiler (e.g., 32 threads for SM20). +//! +//! @tparam LEGACY_PTX_ARCH +//! **[optional]** Unused. +template +class WarpScan +{ +private: + /****************************************************************************** + * Constants and type definitions + ******************************************************************************/ + + enum + { + /// Whether the logical warp size and the PTX warp size coincide + IS_ARCH_WARP = (LOGICAL_WARP_THREADS == CUB_WARP_THREADS(0)), + + /// Whether the logical warp size is a power-of-two + IS_POW_OF_TWO = ((LOGICAL_WARP_THREADS & (LOGICAL_WARP_THREADS - 1)) == 0), + + /// Whether the data type is an integer (which has fully-associative addition) + IS_INTEGER = ((Traits::CATEGORY == SIGNED_INTEGER) || + (Traits::CATEGORY == UNSIGNED_INTEGER)) + }; + + /// Internal specialization. + /// Use SHFL-based scan if LOGICAL_WARP_THREADS is a power-of-two + using InternalWarpScan = cub::detail::conditional_t, + WarpScanSmem>; + + /// Shared memory storage layout type for WarpScan + using _TempStorage = typename InternalWarpScan::TempStorage; + + /****************************************************************************** + * Thread fields + ******************************************************************************/ + + /// Shared storage reference + _TempStorage &temp_storage; + unsigned int lane_id; + + /****************************************************************************** + * Public types + ******************************************************************************/ + +public: + /// @smemstorage{WarpScan} + struct TempStorage : Uninitialized<_TempStorage> + {}; + + //! @name Collective constructors + //! @{ + + //! @brief Collective constructor using the specified memory allocation as temporary storage. + //! Logical warp and lane identifiers are constructed from `threadIdx.x`. + //! + //! @param[in] temp_storage + //! Reference to memory allocation having layout type TempStorage + __device__ __forceinline__ WarpScan(TempStorage &temp_storage) + : temp_storage(temp_storage.Alias()) + , lane_id(IS_ARCH_WARP ? LaneId() : LaneId() % LOGICAL_WARP_THREADS) + {} + + //! @} end member group + //! @name Inclusive prefix sums + //! @{ + + //! @rst + //! Computes an inclusive prefix sum across the calling warp. + //! + //! * @smemwarpreuse + //! + //! Snippet + //! +++++++ + //! + //! The code snippet below illustrates four concurrent warp-wide inclusive prefix sums within a + //! block of 128 threads (one per each of the 32-thread warps). + //! + //! .. code-block:: c++ + //! + //! #include + //! + //! __global__ void ExampleKernel(...) + //! { + //! // Specialize WarpScan for type int + //! typedef cub::WarpScan WarpScan; + //! + //! // Allocate WarpScan shared memory for 4 warps + //! __shared__ typename WarpScan::TempStorage temp_storage[4]; + //! + //! // Obtain one input item per thread + //! int thread_data = ... + //! + //! // Compute inclusive warp-wide prefix sums + //! int warp_id = threadIdx.x / 32; + //! WarpScan(temp_storage[warp_id]).InclusiveSum(thread_data, thread_data); + //! + //! Suppose the set of input ``thread_data`` across the block of threads is + //! ``{1, 1, 1, 1, ...}``. The corresponding output ``thread_data`` in each of the four warps + //! of threads will be ``1, 2, 3, ..., 32}``. + //! @endrst + //! + //! @param[in] input + //! Calling thread's input item. + //! + //! @param[out] inclusive_output + //! Calling thread's output item. May be aliased with `input`. + __device__ __forceinline__ void InclusiveSum(T input, T &inclusive_output) + { + InclusiveScan(input, inclusive_output, cub::Sum()); + } + + //! @rst + //! Computes an inclusive prefix sum across the calling warp. + //! Also provides every thread with the warp-wide ``warp_aggregate`` of all inputs. + //! + //! * @smemwarpreuse + //! + //! Snippet + //! +++++++ + //! + //! The code snippet below illustrates four concurrent warp-wide inclusive prefix sums within a + //! block of 128 threads (one per each of the 32-thread warps). + //! + //! .. code-block:: c++ + //! + //! #include + //! + //! __global__ void ExampleKernel(...) + //! { + //! // Specialize WarpScan for type int + //! typedef cub::WarpScan WarpScan; + //! + //! // Allocate WarpScan shared memory for 4 warps + //! __shared__ typename WarpScan::TempStorage temp_storage[4]; + //! + //! // Obtain one input item per thread + //! int thread_data = ... + //! + //! // Compute inclusive warp-wide prefix sums + //! int warp_aggregate; + //! int warp_id = threadIdx.x / 32; + //! WarpScan(temp_storage[warp_id]).InclusiveSum(thread_data, + //! thread_data, + //! warp_aggregate); + //! + //! Suppose the set of input ``thread_data`` across the block of threads is + //! ``{1, 1, 1, 1, ...}``. The corresponding output ``thread_data`` in each of the four warps + //! of threads will be ``1, 2, 3, ..., 32}``. Furthermore, ``warp_aggregate`` for all threads + //! in all warps will be ``32``. + //! @endrst + //! + //! @param[in] input + //! Calling thread's input item + //! + //! @param[out] inclusive_output + //! Calling thread's output item. May be aliased with `input` + //! + //! @param[out] warp_aggregate + //! Warp-wide aggregate reduction of input items + __device__ __forceinline__ void InclusiveSum(T input, T &inclusive_output, T &warp_aggregate) + { + InclusiveScan(input, inclusive_output, cub::Sum(), warp_aggregate); + } + + //! @} end member group + //! @name Exclusive prefix sums + //! @{ + + //! @rst + //! Computes an exclusive prefix sum across the calling warp. The value of 0 is applied as the + //! initial value, and is assigned to ``exclusive_output`` in *lane*\ :sub:`0`. + //! + //! * @identityzero + //! * @smemwarpreuse + //! + //! Snippet + //! +++++++ + //! + //! The code snippet below illustrates four concurrent warp-wide exclusive prefix sums within a + //! block of 128 threads (one per each of the 32-thread warps). + //! + //! .. code-block:: c++ + //! + //! #include + //! + //! __global__ void ExampleKernel(...) + //! { + //! // Specialize WarpScan for type int + //! typedef cub::WarpScan WarpScan; + //! + //! // Allocate WarpScan shared memory for 4 warps + //! __shared__ typename WarpScan::TempStorage temp_storage[4]; + //! + //! // Obtain one input item per thread + //! int thread_data = ... + //! + //! // Compute exclusive warp-wide prefix sums + //! int warp_id = threadIdx.x / 32; + //! WarpScan(temp_storage[warp_id]).ExclusiveSum(thread_data, thread_data); + //! + //! Suppose the set of input ``thread_data`` across the block of threads is + //! ``{1, 1, 1, 1, ...}``. The corresponding output ``thread_data`` in each of the four warps + //! of threads will be ``0, 1, 2, ..., 31}``. + //! @endrst + //! + //! @param[in] input + //! Calling thread's input item. + //! + //! @param[out] exclusive_output + //! Calling thread's output item. May be aliased with `input`. + __device__ __forceinline__ void ExclusiveSum(T input, T &exclusive_output) + { + T initial_value{}; + ExclusiveScan(input, exclusive_output, initial_value, cub::Sum()); + } + + //! @rst + //! Computes an exclusive prefix sum across the calling warp. The value of 0 is applied as the + //! initial value, and is assigned to ``exclusive_output`` in *lane*\ :sub:`0`. + //! Also provides every thread with the warp-wide ``warp_aggregate`` of all inputs. + //! + //! * @identityzero + //! * @smemwarpreuse + //! + //! Snippet + //! +++++++ + //! + //! The code snippet below illustrates four concurrent warp-wide exclusive prefix sums within a + //! block of 128 threads (one per each of the 32-thread warps). + //! + //! .. code-block:: c++ + //! + //! #include + //! + //! __global__ void ExampleKernel(...) + //! { + //! // Specialize WarpScan for type int + //! typedef cub::WarpScan WarpScan; + //! + //! // Allocate WarpScan shared memory for 4 warps + //! __shared__ typename WarpScan::TempStorage temp_storage[4]; + //! + //! // Obtain one input item per thread + //! int thread_data = ... + //! + //! // Compute exclusive warp-wide prefix sums + //! int warp_aggregate; + //! int warp_id = threadIdx.x / 32; + //! WarpScan(temp_storage[warp_id]).ExclusiveSum(thread_data, + //! thread_data, + //! warp_aggregate); + //! + //! Suppose the set of input ``thread_data`` across the block of threads is + //! ``{1, 1, 1, 1, ...}``. The corresponding output ``thread_data`` in each of the four warps + //! of threads will be ``0, 1, 2, ..., 31}``. Furthermore, ``warp_aggregate`` for all threads + //! in all warps will be ``32``. + //! @endrst + //! + //! + //! @param[in] input + //! Calling thread's input item + //! + //! @param[out] exclusive_output + //! Calling thread's output item. May be aliased with `input` + //! + //! @param[out] warp_aggregate + //! Warp-wide aggregate reduction of input items + __device__ __forceinline__ void ExclusiveSum(T input, T &exclusive_output, T &warp_aggregate) + { + T initial_value{}; + ExclusiveScan(input, exclusive_output, initial_value, cub::Sum(), warp_aggregate); + } + + //! @} end member group + //! @name Inclusive prefix scans + //! @{ + + //! @rst + //! Computes an inclusive prefix scan using the specified binary scan functor across the + //! calling warp. + //! + //! * @smemwarpreuse + //! + //! Snippet + //! +++++++ + //! + //! The code snippet below illustrates four concurrent warp-wide inclusive prefix max scans + //! within a block of 128 threads (one per each of the 32-thread warps). + //! + //! .. code-block:: c++ + //! + //! #include + //! + //! __global__ void ExampleKernel(...) + //! { + //! // Specialize WarpScan for type int + //! typedef cub::WarpScan WarpScan; + //! + //! // Allocate WarpScan shared memory for 4 warps + //! __shared__ typename WarpScan::TempStorage temp_storage[4]; + //! + //! // Obtain one input item per thread + //! int thread_data = ... + //! + //! // Compute inclusive warp-wide prefix max scans + //! int warp_id = threadIdx.x / 32; + //! WarpScan(temp_storage[warp_id]).InclusiveScan(thread_data, thread_data, cub::Max()); + //! + //! Suppose the set of input ``thread_data`` across the block of threads is + //! ``{0, -1, 2, -3, ..., 126, -127}``. The corresponding output ``thread_data`` in the first + //! warp would be ``0, 0, 2, 2, ..., 30, 30``, the output for the second warp would be + //! ``32, 32, 34, 34, ..., 62, 62``, etc. + //! @endrst + //! + //! @tparam ScanOp + //! **[inferred]** Binary scan operator type having member + //! `T operator()(const T &a, const T &b)` + //! + //! @param[in] input + //! Calling thread's input item + //! + //! @param[out] inclusive_output + //! Calling thread's output item. May be aliased with `input` + //! + //! @param[in] can_op + //! Binary scan operator + template + __device__ __forceinline__ void InclusiveScan(T input, T &inclusive_output, ScanOp scan_op) + { + InternalWarpScan(temp_storage).InclusiveScan(input, inclusive_output, scan_op); + } + + //! @rst + //! Computes an inclusive prefix scan using the specified binary scan functor across the + //! calling warp. Also provides every thread with the warp-wide ``warp_aggregate`` of + //! all inputs. + //! + //! * @smemwarpreuse + //! + //! Snippet + //! +++++++ + //! + //! The code snippet below illustrates four concurrent warp-wide inclusive prefix max scans + //! within a block of 128 threads (one per each of the 32-thread warps). + //! + //! .. code-block:: c++ + //! + //! #include + //! + //! __global__ void ExampleKernel(...) + //! { + //! // Specialize WarpScan for type int + //! typedef cub::WarpScan WarpScan; + //! + //! // Allocate WarpScan shared memory for 4 warps + //! __shared__ typename WarpScan::TempStorage temp_storage[4]; + //! + //! // Obtain one input item per thread + //! int thread_data = ... + //! + //! // Compute inclusive warp-wide prefix max scans + //! int warp_aggregate; + //! int warp_id = threadIdx.x / 32; + //! WarpScan(temp_storage[warp_id]).InclusiveScan( + //! thread_data, thread_data, cub::Max(), warp_aggregate); + //! + //! Suppose the set of input ``thread_data`` across the block of threads is + //! ``{0, -1, 2, -3, ..., 126, -127}``. The corresponding output ``thread_data`` in the first + //! warp would be ``0, 0, 2, 2, ..., 30, 30``, the output for the second warp would be + //! ``32, 32, 34, 34, ..., 62, 62``, etc. Furthermore, ``warp_aggregate`` would be assigned + //! ``30`` for threads in the first warp, ``62`` for threads in the second warp, etc. + //! @endrst + //! + //! @tparam ScanOp + //! **[inferred]** Binary scan operator type having member + //! `T operator()(const T &a, const T &b)` + //! @param[in] input + //! Calling thread's input item + //! + //! @param[out] inclusive_output + //! Calling thread's output item. May be aliased with ``input`` + //! + //! @param[in] scan_op + //! Binary scan operator + //! + //! @param[out] warp_aggregate + //! Warp-wide aggregate reduction of input items. + template + __device__ __forceinline__ void + InclusiveScan(T input, T &inclusive_output, ScanOp scan_op, T &warp_aggregate) + { + InternalWarpScan(temp_storage).InclusiveScan(input, inclusive_output, scan_op, warp_aggregate); + } + + //! @} end member group + //! @name Exclusive prefix scans + //! @{ + + //! @rst + //! Computes an exclusive prefix scan using the specified binary scan functor across the + //! calling warp. Because no initial value is supplied, the ``output`` computed for + //! *lane*\ :sub:`0` is undefined. + //! + //! * @smemwarpreuse + //! + //! Snippet + //! +++++++ + //! + //! The code snippet below illustrates four concurrent warp-wide exclusive prefix max scans + //! within a block of 128 threads (one per each of the 32-thread warps). + //! + //! .. code-block:: c++ + //! + //! #include + //! + //! __global__ void ExampleKernel(...) + //! { + //! // Specialize WarpScan for type int + //! typedef cub::WarpScan WarpScan; + //! + //! // Allocate WarpScan shared memory for 4 warps + //! __shared__ typename WarpScan::TempStorage temp_storage[4]; + //! + //! // Obtain one input item per thread + //! int thread_data = ... + //! + //! // Compute exclusive warp-wide prefix max scans + //! int warp_id = threadIdx.x / 32; + //! WarpScan(temp_storage[warp_id]).ExclusiveScan(thread_data, thread_data, cub::Max()); + //! + //! Suppose the set of input ``thread_data`` across the block of threads is + //! ``{0, -1, 2, -3, ..., 126, -127}``. The corresponding output ``thread_data`` in the first + //! warp would be ``?, 0, 0, 2, ..., 28, 30``, the output for the second warp would be + //! ``?, 32, 32, 34, ..., 60, 62``, etc. + //! (The output ``thread_data`` in warp *lane*\ :sub:`0` is undefined.) + //! @endrst + //! + //! @tparam ScanOp + //! **[inferred]** Binary scan operator type having member + //! `T operator()(const T &a, const T &b)` + //! + //! @param[in] input + //! Calling thread's input item + //! + //! @param[out] exclusive_output + //! Calling thread's output item. May be aliased with `input` + //! + //! @param[in] scan_op + //! Binary scan operator + template + __device__ __forceinline__ void ExclusiveScan(T input, T &exclusive_output, ScanOp scan_op) + { + InternalWarpScan internal(temp_storage); + + T inclusive_output; + internal.InclusiveScan(input, inclusive_output, scan_op); + + internal.Update(input, inclusive_output, exclusive_output, scan_op, Int2Type()); + } + + //! @rst + //! Computes an exclusive prefix scan using the specified binary scan functor across the + //! calling warp. + //! + //! * @smemwarpreuse + //! + //! Snippet + //! +++++++ + //! + //! The code snippet below illustrates four concurrent warp-wide exclusive prefix max scans + //! within a block of 128 threads (one per each of the 32-thread warps). + //! + //! .. code-block:: c++ + //! + //! #include + //! + //! __global__ void ExampleKernel(...) + //! { + //! // Specialize WarpScan for type int + //! typedef cub::WarpScan WarpScan; + //! + //! // Allocate WarpScan shared memory for 4 warps + //! __shared__ typename WarpScan::TempStorage temp_storage[4]; + //! + //! // Obtain one input item per thread + //! int thread_data = ... + //! + //! // Compute exclusive warp-wide prefix max scans + //! int warp_id = threadIdx.x / 32; + //! WarpScan(temp_storage[warp_id]).ExclusiveScan(thread_data, + //! thread_data, + //! INT_MIN, + //! cub::Max()); + //! + //! Suppose the set of input ``thread_data`` across the block of threads is + //! ``{0, -1, 2, -3, ..., 126, -127}``. The corresponding output ``thread_data`` in the first + //! warp would be ``INT_MIN, 0, 0, 2, ..., 28, 30``, the output for the second warp would be + //! ``30, 32, 32, 34, ..., 60, 62``, etc. + //! @endrst + //! + //! @tparam ScanOp + //! **[inferred]** Binary scan operator type having member + //! `T operator()(const T &a, const T &b)` + //! + //! @param[in] input + //! Calling thread's input item + //! + //! @param[out] exclusive_output + //! Calling thread's output item. May be aliased with `input` + //! + //! @param[in] initial_value + //! Initial value to seed the exclusive scan + //! + //! @param[in] scan_op + //! Binary scan operator + template + __device__ __forceinline__ void + ExclusiveScan(T input, T &exclusive_output, T initial_value, ScanOp scan_op) + { + InternalWarpScan internal(temp_storage); + + T inclusive_output; + internal.InclusiveScan(input, inclusive_output, scan_op); + + internal.Update(input, + inclusive_output, + exclusive_output, + scan_op, + initial_value, + Int2Type()); + } + + //! @rst + //! Computes an exclusive prefix scan using the specified binary scan functor across the + //! calling warp. Because no initial value is supplied, the ``output`` computed for + //! *lane*\ :sub:`0` is undefined. Also provides every thread with the warp-wide + //! ``warp_aggregate`` of all inputs. + //! + //! * @smemwarpreuse + //! + //! Snippet + //! +++++++ + //! + //! The code snippet below illustrates four concurrent warp-wide exclusive prefix max scans + //! within a block of 128 threads (one per each of the 32-thread warps). + //! + //! .. code-block:: c++ + //! + //! #include + //! + //! __global__ void ExampleKernel(...) + //! { + //! // Specialize WarpScan for type int + //! typedef cub::WarpScan WarpScan; + //! + //! // Allocate WarpScan shared memory for 4 warps + //! __shared__ typename WarpScan::TempStorage temp_storage[4]; + //! + //! // Obtain one input item per thread + //! int thread_data = ... + //! + //! // Compute exclusive warp-wide prefix max scans + //! int warp_aggregate; + //! int warp_id = threadIdx.x / 32; + //! WarpScan(temp_storage[warp_id]).ExclusiveScan(thread_data, + //! thread_data, + //! cub::Max(), + //! warp_aggregate); + //! + //! Suppose the set of input ``thread_data`` across the block of threads is + //! ``{0, -1, 2, -3, ..., 126, -127}``. The corresponding output ``thread_data`` in the first + //! warp would be ``?, 0, 0, 2, ..., 28, 30``, the output for the second warp would be + //! ``?, 32, 32, 34, ..., 60, 62``, etc. (The output ``thread_data`` in warp *lane*\ :sub:`0` + //! is undefined). Furthermore, ``warp_aggregate`` would be assigned ``30`` for threads in the + //! first warp, \p 62 for threads in the second warp, etc. + //! @endrst + //! + //! @tparam ScanOp + //! **[inferred]** Binary scan operator type having member + //! `T operator()(const T &a, const T &b)` + //! + //! @param[in] input + //! Calling thread's input item + //! + //! @param[out] exclusive_output + //! Calling thread's output item. May be aliased with `input` + //! + //! @param[in] scan_op + //! Binary scan operator + //! + //! @param[out] warp_aggregate + //! Warp-wide aggregate reduction of input items + template + __device__ __forceinline__ void + ExclusiveScan(T input, T &exclusive_output, ScanOp scan_op, T &warp_aggregate) + { + InternalWarpScan internal(temp_storage); + + T inclusive_output; + internal.InclusiveScan(input, inclusive_output, scan_op); + + internal.Update(input, + inclusive_output, + exclusive_output, + warp_aggregate, + scan_op, + Int2Type()); + } + + //! @rst + //! Computes an exclusive prefix scan using the specified binary scan functor across the + //! calling warp. Also provides every thread with the warp-wide ``warp_aggregate`` of + //! all inputs. + //! + //! * @smemwarpreuse + //! + //! Snippet + //! +++++++ + //! + //! The code snippet below illustrates four concurrent warp-wide exclusive prefix max scans + //! within a block of 128 threads (one per each of the 32-thread warps). + //! + //! .. code-block:: c++ + //! + //! #include + //! + //! __global__ void ExampleKernel(...) + //! { + //! // Specialize WarpScan for type int + //! typedef cub::WarpScan WarpScan; + //! + //! // Allocate WarpScan shared memory for 4 warps + //! __shared__ typename WarpScan::TempStorage temp_storage[4]; + //! + //! // Obtain one input item per thread + //! int thread_data = ... + //! + //! // Compute exclusive warp-wide prefix max scans + //! int warp_aggregate; + //! int warp_id = threadIdx.x / 32; + //! WarpScan(temp_storage[warp_id]).ExclusiveScan(thread_data, + //! thread_data, + //! INT_MIN, + //! cub::Max(), + //! warp_aggregate); + //! + //! Suppose the set of input ``thread_data`` across the block of threads is + //! ``{0, -1, 2, -3, ..., 126, -127}``. The corresponding output ``thread_data`` in the first + //! warp would be ``INT_MIN, 0, 0, 2, ..., 28, 30``, the output for the second warp would be + //! ``30, 32, 32, 34, ..., 60, 62``, etc. Furthermore, ``warp_aggregate`` would be assigned + //! ``30`` for threads in the first warp, ``62`` for threads in the second warp, etc. + //! @endrst + //! + //! @tparam ScanOp + //! **[inferred]** Binary scan operator type having member + //! `T operator()(const T &a, const T &b)` + //! + //! @param[in] input + //! Calling thread's input item + //! + //! @param[out] exclusive_output + //! Calling thread's output item. May be aliased with `input` + //! + //! @param[in] initial_value + //! Initial value to seed the exclusive scan + //! + //! @param[in] scan_op + //! Binary scan operator + //! + //! @param[out] warp_aggregate + //! Warp-wide aggregate reduction of input items + //! + template + __device__ __forceinline__ void + ExclusiveScan(T input, T &exclusive_output, T initial_value, ScanOp scan_op, T &warp_aggregate) + { + InternalWarpScan internal(temp_storage); + + T inclusive_output; + internal.InclusiveScan(input, inclusive_output, scan_op); + + internal.Update(input, + inclusive_output, + exclusive_output, + warp_aggregate, + scan_op, + initial_value, + Int2Type()); + } + + //! @} end member group + //! @name Combination (inclusive & exclusive) prefix scans + //! @{ + + //! @rst + //! Computes both inclusive and exclusive prefix scans using the specified binary scan functor + //! across the calling warp. Because no initial value is supplied, the ``exclusive_output`` + //! computed for *lane*\ :sub:`0` is undefined. + //! + //! * @smemwarpreuse + //! + //! Snippet + //! +++++++ + //! + //! The code snippet below illustrates four concurrent warp-wide exclusive prefix max scans + //! within a block of 128 threads (one per each of the 32-thread warps). + //! + //! .. code-block:: c++ + //! + //! #include + //! + //! __global__ void ExampleKernel(...) + //! { + //! // Specialize WarpScan for type int + //! typedef cub::WarpScan WarpScan; + //! + //! // Allocate WarpScan shared memory for 4 warps + //! __shared__ typename WarpScan::TempStorage temp_storage[4]; + //! + //! // Obtain one input item per thread + //! int thread_data = ... + //! + //! // Compute exclusive warp-wide prefix max scans + //! int inclusive_partial, exclusive_partial; + //! WarpScan(temp_storage[warp_id]).Scan(thread_data, + //! inclusive_partial, + //! exclusive_partial, + //! cub::Max()); + //! + //! Suppose the set of input ``thread_data`` across the block of threads is + //! ``{0, -1, 2, -3, ..., 126, -127}``. The corresponding output ``inclusive_partial`` in the + //! first warp would be ``0, 0, 2, 2, ..., 30, 30``, the output for the second warp would be + //! ``32, 32, 34, 34, ..., 62, 62``, etc. The corresponding output ``exclusive_partial`` in the + //! first warp would be ``?, 0, 0, 2, ..., 28, 30``, the output for the second warp would be + //! ``?, 32, 32, 34, ..., 60, 62``, etc. + //! (The output ``thread_data`` in warp *lane*\ :sub:`0` is undefined.) + //! @endrst + //! + //! @tparam ScanOp + //! **[inferred]** Binary scan operator type having member + //! `T operator()(const T &a, const T &b)` + //! + //! @param[in] input + //! Calling thread's input item + //! + //! @param[out] inclusive_output + //! Calling thread's inclusive-scan output item + //! + //! @param[out] exclusive_output + //! Calling thread's exclusive-scan output item + //! + //! @param[in] scan_op + //! Binary scan operator + template + __device__ __forceinline__ void + Scan(T input, T &inclusive_output, T &exclusive_output, ScanOp scan_op) + { + InternalWarpScan internal(temp_storage); + + internal.InclusiveScan(input, inclusive_output, scan_op); + + internal.Update(input, inclusive_output, exclusive_output, scan_op, Int2Type()); + } + + //! @rst + //! Computes both inclusive and exclusive prefix scans using the specified binary scan functor + //! across the calling warp. + //! + //! * @smemwarpreuse + //! + //! Snippet + //! +++++++ + //! + //! The code snippet below illustrates four concurrent warp-wide prefix max scans within a + //! block of 128 threads (one per each of the 32-thread warps). + //! + //! .. code-block:: c++ + //! + //! #include + //! + //! __global__ void ExampleKernel(...) + //! { + //! // Specialize WarpScan for type int + //! typedef cub::WarpScan WarpScan; + //! + //! // Allocate WarpScan shared memory for 4 warps + //! __shared__ typename WarpScan::TempStorage temp_storage[4]; + //! + //! // Obtain one input item per thread + //! int thread_data = ... + //! + //! // Compute inclusive warp-wide prefix max scans + //! int warp_id = threadIdx.x / 32; + //! int inclusive_partial, exclusive_partial; + //! WarpScan(temp_storage[warp_id]).Scan(thread_data, + //! inclusive_partial, + //! exclusive_partial, + //! INT_MIN, + //! cub::Max()); + //! + //! Suppose the set of input ``thread_data`` across the block of threads is + //! ``{0, -1, 2, -3, ..., 126, -127}``. The corresponding output ``inclusive_partial`` in the + //! first warp would be ``0, 0, 2, 2, ..., 30, 30``, the output for the second warp would be + //! ``32, 32, 34, 34, ..., 62, 62``, etc. The corresponding output ``exclusive_partial`` in the + //! first warp would be ``INT_MIN, 0, 0, 2, ..., 28, 30``, the output for the second warp would + //! be ``30, 32, 32, 34, ..., 60, 62``, etc. + //! @endrst + //! + //! @tparam ScanOp + //! **[inferred]** Binary scan operator type having member + //! `T operator()(const T &a, const T &b)` + //! + //! @param[in] input + //! Calling thread's input item + //! + //! @param[out] inclusive_output + //! Calling thread's inclusive-scan output item + //! + //! @param[out] exclusive_output + //! Calling thread's exclusive-scan output item + //! + //! @param[in] initial_value + //! Initial value to seed the exclusive scan + //! + //! @param[in] scan_op + //! Binary scan operator + template + __device__ __forceinline__ void + Scan(T input, T &inclusive_output, T &exclusive_output, T initial_value, ScanOp scan_op) + { + InternalWarpScan internal(temp_storage); + + internal.InclusiveScan(input, inclusive_output, scan_op); + + internal.Update(input, + inclusive_output, + exclusive_output, + scan_op, + initial_value, + Int2Type()); + } + + //! @} end member group + //! @name Data exchange + //! @{ + + //! @rst + //! Broadcast the value ``input`` from *lane*\ :sub:`src_lane` to all lanes in the warp + //! + //! * @smemwarpreuse + //! + //! Snippet + //! +++++++ + //! + //! The code snippet below illustrates the warp-wide broadcasts of values from *lane*\ :sub:`0` + //! in each of four warps to all other threads in those warps. + //! + //! .. code-block:: c++ + //! + //! #include + //! + //! __global__ void ExampleKernel(...) + //! { + //! // Specialize WarpScan for type int + //! typedef cub::WarpScan WarpScan; + //! + //! // Allocate WarpScan shared memory for 4 warps + //! __shared__ typename WarpScan::TempStorage temp_storage[4]; + //! + //! // Obtain one input item per thread + //! int thread_data = ... + //! + //! // Broadcast from lane0 in each warp to all other threads in the warp + //! int warp_id = threadIdx.x / 32; + //! thread_data = WarpScan(temp_storage[warp_id]).Broadcast(thread_data, 0); + //! + //! Suppose the set of input ``thread_data`` across the block of threads is + //! ``{0, 1, 2, 3, ..., 127}``. The corresponding output ``thread_data`` will be + //! ``{0, 0, ..., 0}`` in warp\ :sub:`0`, + //! ``{32, 32, ..., 32}`` in warp\ :sub:`1`, + //! ``{64, 64, ..., 64}`` in warp\ :sub:`2`, etc. + //! @endrst + //! + //! @param[in] input + //! The value to broadcast + //! + //! @param[in] src_lane + //! Which warp lane is to do the broadcasting + __device__ __forceinline__ T Broadcast(T input, unsigned int src_lane) + { + return InternalWarpScan(temp_storage).Broadcast(input, src_lane); + } + + //@} end member group +}; + +CUB_NAMESPACE_END diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/warp/warp_store.cuh b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/warp/warp_store.cuh new file mode 100644 index 0000000000000000000000000000000000000000..37a9d6519f7f8fddc59f70b576b714deb769f201 --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cub/warp/warp_store.cuh @@ -0,0 +1,523 @@ +/****************************************************************************** + * Copyright (c) 2011-2021, NVIDIA CORPORATION. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the NVIDIA CORPORATION nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ******************************************************************************/ + +//! @file Operations for writing linear segments of data from the CUDA warp + +#pragma once + +#include +#include +#include +#include +#include + +#include +#include + +CUB_NAMESPACE_BEGIN + +//! @rst +//! ``cub::WarpStoreAlgorithm`` enumerates alternative algorithms for :cpp:struct:`cub::WarpStore` +//! to write a blocked arrangement of items across a CUDA warp to a linear segment of memory. +//! @endrst +enum WarpStoreAlgorithm +{ + //! @rst + //! Overview + //! ++++++++++++++++++++++++++ + //! + //! A :ref:`blocked arrangement ` of data is written directly + //! to memory. + //! + //! Performance Considerations + //! ++++++++++++++++++++++++++ + //! + //! The utilization of memory transactions (coalescing) decreases as the + //! access stride between threads increases (i.e., the number items per thread). + //! @endrst + WARP_STORE_DIRECT, + + //! @rst + //! Overview + //! ++++++++++++++++++++++++++ + //! + //! A :ref:`striped arrangement ` of data is written + //! directly to memory. + //! + //! Performance Considerations + //! ++++++++++++++++++++++++++ + //! + //! The utilization of memory transactions (coalescing) remains high regardless + //! of items written per thread. + //! @endrst + WARP_STORE_STRIPED, + + //! @rst + //! Overview + //! ++++++++++++++++++++++++++ + //! + //! A :ref:`blocked arrangement ` of data is written + //! directly to memory using CUDA's built-in vectorized stores as a coalescing + //! optimization. For example, ``st.global.v4.s32`` instructions will be + //! generated when ``T = int`` and ``ITEMS_PER_THREAD % 4 == 0``. + //! + //! Performance Considerations + //! ++++++++++++++++++++++++++ + //! + //! * The utilization of memory transactions (coalescing) remains high until + //! the the access stride between threads (i.e., the number items per thread) + //! exceeds the maximum vector store width (typically 4 items or 64B, + //! whichever is lower). + //! * The following conditions will prevent vectorization and writing will fall + //! back to ``cub::WARP_STORE_DIRECT``: + //! + //! * ``ITEMS_PER_THREAD`` is odd + //! * The ``OutputIteratorT`` is not a simple pointer type + //! * The block output offset is not quadword-aligned + //! * The data type ``T`` is not a built-in primitive or CUDA vector type + //! (e.g., ``short``, ``int2``, ``double``, ``float2``, etc.) + //! + //! @endrst + WARP_STORE_VECTORIZE, + + //! @rst + //! Overview + //! ++++++++++++++++++++++++++ + //! + //! A :ref:`blocked arrangement ` is locally + //! transposed and then efficiently written to memory as a + //! :ref:`striped arrangement `. + //! + //! Performance Considerations + //! ++++++++++++++++++++++++++ + //! + //! * The utilization of memory transactions (coalescing) remains high + //! regardless of items written per thread. + //! * The local reordering incurs slightly longer latencies and throughput than the + //! direct ``cub::WARP_STORE_DIRECT`` and ``cub::WARP_STORE_VECTORIZE`` alternatives. + //! + //! @endrst + WARP_STORE_TRANSPOSE +}; + +//! @rst +//! The WarpStore class provides :ref:`collective ` +//! data movement methods for writing a :ref:`blocked arrangement ` +//! of items partitioned across a CUDA warp to a linear segment of memory. +//! +//! Overview +//! ++++++++++++++++ +//! +//! * The WarpStore class provides a single data movement abstraction that can be +//! specialized to implement different cub::WarpStoreAlgorithm strategies. This +//! facilitates different performance policies for different architectures, +//! data types, granularity sizes, etc. +//! * WarpStore can be optionally specialized by different data movement strategies: +//! +//! #. :cpp:enumerator:`cub::WARP_STORE_DIRECT`: +//! a :ref:`blocked arrangement ` of data is written directly to +//! memory. +//! #. :cpp:enumerator:`cub::WARP_STORE_STRIPED`: +//! a :ref:`striped arrangement ` of data is written directly to +//! memory. +//! #. :cpp:enumerator:`cub::WARP_STORE_VECTORIZE`: +//! a :ref:`blocked arrangement ` of data is written directly to +//! memory using CUDA's built-in vectorized stores as a coalescing optimization. +//! #. :cpp:enumerator:`cub::WARP_STORE_TRANSPOSE`: +//! a :ref:`blocked arrangement ` is locally transposed into a +//! :ref:`striped arrangement ` which is then written to memory. +//! +//! * @rowmajor +//! +//! A Simple Example +//! ++++++++++++++++ +//! +//! The code snippet below illustrates the storing of a "blocked" arrangement +//! of 64 integers across 16 threads (where each thread owns 4 consecutive items) +//! into a linear segment of memory. The store is specialized for +//! ``WARP_STORE_TRANSPOSE``, meaning items are locally reordered among threads so +//! that memory references will be efficiently coalesced using a warp-striped +//! access pattern. +//! +//! .. code-block:: c++ +//! +//! #include // or equivalently +//! +//! __global__ void ExampleKernel(int *d_data, ...) +//! { +//! constexpr int warp_threads = 16; +//! constexpr int block_threads = 256; +//! constexpr int items_per_thread = 4; +//! +//! // Specialize WarpStore for a virtual warp of 16 threads owning 4 integer items each +//! using WarpStoreT = WarpStore; +//! +//! constexpr int warps_in_block = block_threads / warp_threads; +//! constexpr int tile_size = items_per_thread * warp_threads; +//! const int warp_id = static_cast(threadIdx.x) / warp_threads; +//! +//! // Allocate shared memory for WarpStore +//! __shared__ typename WarpStoreT::TempStorage temp_storage[warps_in_block]; +//! +//! // Obtain a segment of consecutive items that are blocked across threads +//! int thread_data[4]; +//! ... +//! +//! // Store items to linear memory +//! WarpStoreT(temp_storage[warp_id]).Store(d_data + warp_id * tile_size, thread_data); +//! +//! Suppose the set of ``thread_data`` across the warp threads is +//! ``{ [0,1,2,3], [4,5,6,7], ..., [60,61,62,63] }``. +//! The output ``d_data`` will be ``0, 1, 2, 3, 4, 5, ...``. +//! @endrst +//! +//! @tparam T +//! The type of data to be written. +//! +//! @tparam ITEMS_PER_THREAD +//! The number of consecutive items partitioned onto each thread. +//! +//! @tparam ALGORITHM +//! [optional] cub::WarpStoreAlgorithm tuning policy enumeration. +//! default: cub::WARP_STORE_DIRECT. +//! +//! @tparam LOGICAL_WARP_THREADS +//! [optional] The number of threads per "logical" warp (may be less +//! than the number of hardware warp threads). Default is the warp size of the +//! targeted CUDA compute-capability (e.g., 32 threads for SM86). Must be a +//! power of two. +//! +//! @tparam LEGACY_PTX_ARCH +//! Unused. +template +class WarpStore +{ + static_assert(PowerOfTwo::VALUE, + "LOGICAL_WARP_THREADS must be a power of two"); + + constexpr static bool IS_ARCH_WARP = LOGICAL_WARP_THREADS == CUB_WARP_THREADS(0); + +private: + /// Store helper + template + struct StoreInternal; + + template + struct StoreInternal + { + using TempStorage = NullType; + + int linear_tid; + + __device__ __forceinline__ StoreInternal(TempStorage & /*temp_storage*/, int linear_tid) + : linear_tid(linear_tid) + {} + + template + __device__ __forceinline__ void Store(OutputIteratorT block_itr, T (&items)[ITEMS_PER_THREAD]) + { + StoreDirectBlocked(linear_tid, block_itr, items); + } + + template + __device__ __forceinline__ void Store(OutputIteratorT block_itr, + T (&items)[ITEMS_PER_THREAD], + int valid_items) + { + StoreDirectBlocked(linear_tid, block_itr, items, valid_items); + } + }; + + template + struct StoreInternal + { + using TempStorage = NullType; + + int linear_tid; + + __device__ __forceinline__ StoreInternal(TempStorage & /*temp_storage*/, int linear_tid) + : linear_tid(linear_tid) + {} + + template + __device__ __forceinline__ void Store(OutputIteratorT block_itr, T (&items)[ITEMS_PER_THREAD]) + { + StoreDirectStriped(linear_tid, block_itr, items); + } + + template + __device__ __forceinline__ void Store(OutputIteratorT block_itr, + T (&items)[ITEMS_PER_THREAD], + int valid_items) + { + StoreDirectStriped(linear_tid, block_itr, items, valid_items); + } + }; + + template + struct StoreInternal + { + using TempStorage = NullType; + + int linear_tid; + + __device__ __forceinline__ StoreInternal(TempStorage & /*temp_storage*/, int linear_tid) + : linear_tid(linear_tid) + {} + + __device__ __forceinline__ void Store(T *block_ptr, T (&items)[ITEMS_PER_THREAD]) + { + StoreDirectBlockedVectorized(linear_tid, block_ptr, items); + } + + template + __device__ __forceinline__ void Store(OutputIteratorT block_itr, T (&items)[ITEMS_PER_THREAD]) + { + StoreDirectBlocked(linear_tid, block_itr, items); + } + + template + __device__ __forceinline__ void Store(OutputIteratorT block_itr, + T (&items)[ITEMS_PER_THREAD], + int valid_items) + { + StoreDirectBlocked(linear_tid, block_itr, items, valid_items); + } + }; + + template + struct StoreInternal + { + using WarpExchangeT = WarpExchange; + + struct _TempStorage : WarpExchangeT::TempStorage + {}; + + struct TempStorage : Uninitialized<_TempStorage> + {}; + + _TempStorage &temp_storage; + + int linear_tid; + + __device__ __forceinline__ StoreInternal(TempStorage &temp_storage, int linear_tid) + : temp_storage(temp_storage.Alias()) + , linear_tid(linear_tid) + {} + + template + __device__ __forceinline__ void Store(OutputIteratorT block_itr, T (&items)[ITEMS_PER_THREAD]) + { + WarpExchangeT(temp_storage).BlockedToStriped(items, items); + StoreDirectStriped(linear_tid, block_itr, items); + } + + template + __device__ __forceinline__ void Store(OutputIteratorT block_itr, + T (&items)[ITEMS_PER_THREAD], + int valid_items) + { + WarpExchangeT(temp_storage).BlockedToStriped(items, items); + StoreDirectStriped(linear_tid, block_itr, items, valid_items); + } + }; + + /// Internal load implementation to use + using InternalStore = StoreInternal; + + /// Shared memory storage layout type + using _TempStorage = typename InternalStore::TempStorage; + + __device__ __forceinline__ _TempStorage &PrivateStorage() + { + __shared__ _TempStorage private_storage; + return private_storage; + } + + _TempStorage &temp_storage; + + int linear_tid; + +public: + struct TempStorage : Uninitialized<_TempStorage> + {}; + + //! @name Collective constructors + //! @{ + + //! @brief Collective constructor using a private static allocation of shared + //! memory as temporary storage. + __device__ __forceinline__ WarpStore() + : temp_storage(PrivateStorage()) + , linear_tid(IS_ARCH_WARP ? LaneId() : (LaneId() % LOGICAL_WARP_THREADS)) + {} + + //! @brief Collective constructor using the specified memory allocation as + //! temporary storage. + __device__ __forceinline__ WarpStore(TempStorage &temp_storage) + : temp_storage(temp_storage.Alias()) + , linear_tid(IS_ARCH_WARP ? LaneId() : (LaneId() % LOGICAL_WARP_THREADS)) + {} + + //! @} end member group + //! @name Data movement + //! @{ + + //! @rst + //! Store items into a linear segment of memory. + //! + //! @smemwarpreuse + //! + //! Snippet + //! +++++++ + //! + //! The code snippet below illustrates the storing of a "blocked" arrangement + //! of 64 integers across 16 threads (where each thread owns 4 consecutive items) + //! into a linear segment of memory. The store is specialized for + //! ``WARP_STORE_TRANSPOSE``, meaning items are locally reordered among threads so + //! that memory references will be efficiently coalesced using a warp-striped + //! access pattern. + //! + //! .. code-block:: c++ + //! + //! #include // or equivalently + //! + //! __global__ void ExampleKernel(int *d_data, ...) + //! { + //! constexpr int warp_threads = 16; + //! constexpr int block_threads = 256; + //! constexpr int items_per_thread = 4; + //! + //! // Specialize WarpStore for a virtual warp of 16 threads owning 4 integer items each + //! using WarpStoreT = WarpStore; + //! + //! constexpr int warps_in_block = block_threads / warp_threads; + //! constexpr int tile_size = items_per_thread * warp_threads; + //! const int warp_id = static_cast(threadIdx.x) / warp_threads; + //! + //! // Allocate shared memory for WarpStore + //! __shared__ typename WarpStoreT::TempStorage temp_storage[warps_in_block]; + //! + //! // Obtain a segment of consecutive items that are blocked across threads + //! int thread_data[4]; + //! ... + //! + //! // Store items to linear memory + //! WarpStoreT(temp_storage[warp_id]).Store(d_data + warp_id * tile_size, thread_data); + //! + //! Suppose the set of ``thread_data`` across the warp threads is + //! ``{ [0,1,2,3], [4,5,6,7], ..., [60,61,62,63] }``. + //! The output ``d_data`` will be ``0, 1, 2, 3, 4, 5, ...``. + //! @endrst + //! + //! @param[out] block_itr The thread block's base output iterator for storing to + //! @param[in] items Data to store + template + __device__ __forceinline__ void Store(OutputIteratorT block_itr, T (&items)[ITEMS_PER_THREAD]) + { + InternalStore(temp_storage, linear_tid).Store(block_itr, items); + } + + //! @rst + //! Store items into a linear segment of memory, guarded by range. + //! + //! @smemwarpreuse + //! + //! Snippet + //! +++++++ + //! + //! The code snippet below illustrates the storing of a "blocked" arrangement + //! of 64 integers across 16 threads (where each thread owns 4 consecutive items) + //! into a linear segment of memory. The store is specialized for + //! ``WARP_STORE_TRANSPOSE``, meaning items are locally reordered among threads so + //! that memory references will be efficiently coalesced using a warp-striped + //! access pattern. + //! + //! .. code-block:: c++ + //! + //! #include // or equivalently + //! + //! __global__ void ExampleKernel(int *d_data, int valid_items ...) + //! { + //! constexpr int warp_threads = 16; + //! constexpr int block_threads = 256; + //! constexpr int items_per_thread = 4; + //! + //! // Specialize WarpStore for a virtual warp of 16 threads owning 4 integer items each + //! using WarpStoreT = WarpStore; + //! + //! constexpr int warps_in_block = block_threads / warp_threads; + //! constexpr int tile_size = items_per_thread * warp_threads; + //! const int warp_id = static_cast(threadIdx.x) / warp_threads; + //! + //! // Allocate shared memory for WarpStore + //! __shared__ typename WarpStoreT::TempStorage temp_storage[warps_in_block]; + //! + //! // Obtain a segment of consecutive items that are blocked across threads + //! int thread_data[4]; + //! ... + //! + //! // Store items to linear memory + //! WarpStoreT(temp_storage[warp_id]).Store( + //! d_data + warp_id * tile_size, thread_data, valid_items); + //! + //! Suppose the set of ``thread_data`` across the warp threads is + //! ``{ [0,1,2,3], [4,5,6,7], ..., [60,61,62,63] }`` and ``valid_items`` + //! is ``5``. The output ``d_data`` will be ``0, 1, 2, 3, 4, ?, ?, ...``, + //! with only the first two threads being unmasked to store portions of valid + //! data. + //! @endrst + //! + //! @param[out] block_itr The thread block's base output iterator for storing to + //! @param[in] items Data to store + //! @param[in] valid_items Number of valid items to write + //! + template + __device__ __forceinline__ void Store(OutputIteratorT block_itr, + T (&items)[ITEMS_PER_THREAD], + int valid_items) + { + InternalStore(temp_storage, linear_tid).Store(block_itr, items, valid_items); + } + + //! @} end member group +}; + +CUB_NAMESPACE_END diff --git a/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cuda/semaphore b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cuda/semaphore new file mode 100644 index 0000000000000000000000000000000000000000..e2d06d15c3198d0f7f63727856bea84ad463c9f4 --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/tensorflow/include/external/local_config_cuda/cuda/cuda/nvml/include/cuda/semaphore @@ -0,0 +1,16 @@ +//===----------------------------------------------------------------------===// +// +// Part of libcu++, the C++ Standard Library for your entire system, +// under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. +// +//===----------------------------------------------------------------------===// + +#ifndef _CUDA_SEMAPHORE +#define _CUDA_SEMAPHORE + +#include "std/semaphore" + +#endif // _CUDA_SEMAPHORE