diff --git a/CMakeLists.txt b/CMakeLists.txt index 6c208aaa15..26338f5b16 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1943,6 +1943,11 @@ endif() if(LLVM_VERSION_MAJOR GREATER_EQUAL 23) set(HOST_DEVICE_SPV_EXTENSIONS "${HOST_DEVICE_SPV_EXTENSIONS},+SPV_KHR_float_controls2") endif() +# SPV_KHR_bfloat16: a bfloat16 type for loads, stores and conversions to and +# from other floating-point types. The translator maps it to LLVM's bfloat. +if(HAVE_LLVM_SPIRV_KHR_BFLOAT16) + set(HOST_DEVICE_SPV_EXTENSIONS "${HOST_DEVICE_SPV_EXTENSIONS},+SPV_KHR_bfloat16") +endif() # The SPIR-V side of cl_intel_subgroups: shuffles (also of vectors) and buffer block # reads/writes. cl_intel_spirv_subgroups is not advertised, as it also requires the # image block reads/writes. diff --git a/cmake/SetupLLVMSPIRV.cmake b/cmake/SetupLLVMSPIRV.cmake index ea0e770cea..6423a75d28 100644 --- a/cmake/SetupLLVMSPIRV.cmake +++ b/cmake/SetupLLVMSPIRV.cmake @@ -94,6 +94,18 @@ if(HAVE_LLVM_SPIRV_LIB) set(LLVM_SPIRV_LIB_HAS_ERROR_HANDLING 0 CACHE BOOL "libLLVMSPIRV has TranslatorOpts::setErrorHandlingKind") endif() endif() + + # The translator reads SPV_KHR_bfloat16 since LLVM 21, and since 18.1.14, + # 19.1.8 and 20.1.3 on the older release branches. Not cached, so that it + # follows changes of the translator. + file(READ "${LLVM_SPIRV_INCLUDEDIR}/LLVMSPIRVExtensions.inc" LLVMSPIRVEXTENSIONS_CONTENT) + if(LLVMSPIRVEXTENSIONS_CONTENT MATCHES "EXT\\(SPV_KHR_bfloat16\\)") + message(STATUS "libLLVMSPIRV supports SPV_KHR_bfloat16") + set(LLVM_SPIRV_LIB_HAS_KHR_BFLOAT16 1) + else() + message(STATUS "libLLVMSPIRV is too old for SPV_KHR_bfloat16") + set(LLVM_SPIRV_LIB_HAS_KHR_BFLOAT16 0) + endif() else() message(STATUS "LLVMSPIRV library NOT found: ${LLVM_SPIRV_INCLUDEDIR} | ${LLVM_SPIRV_LIB}") endif() @@ -105,6 +117,15 @@ set_expr(HAVE_SPIRV_LINK TARGET_SPIRV_LINK) set_expr(HAVE_LLVM_SPIRV TARGET_LLVM_SPIRV) set_expr(HAVE_LLVM_OPT TARGET_LLVM_OPT) +# Without the library, the llvm-spirv binary is used, whose extensions can't be +# queried; every translator release for LLVM 21 and later reads SPV_KHR_bfloat16. +if(HAVE_LLVM_SPIRV_LIB) + set_expr(HAVE_LLVM_SPIRV_KHR_BFLOAT16 LLVM_SPIRV_LIB_HAS_KHR_BFLOAT16) +else() + set_expr(HAVE_LLVM_SPIRV_KHR_BFLOAT16 + HAVE_LLVM_SPIRV AND (LLVM_VERSION_MAJOR GREATER_EQUAL 21)) +endif() + if(HAVE_SPIRV_LINK AND (NOT DEFINED SPIRV_LINK_HAS_USE_HIGHEST_VERSION) AND NOT CMAKE_CROSSCOMPILING) # TODO crosscompiling diff --git a/lib/CL/devices/spirv.hh b/lib/CL/devices/spirv.hh index 000d711590..fe0076ba5b 100644 --- a/lib/CL/devices/spirv.hh +++ b/lib/CL/devices/spirv.hh @@ -713,6 +713,9 @@ enum class Capability : unsigned { ShaderClockKHR = 5055, ShaderEnqueueAMDX = 5067, QuadControlKHR = 5087, + BFloat16TypeKHR = 5116, + BFloat16DotProductKHR = 5117, + BFloat16CooperativeMatrixKHR = 5118, SampleMaskOverrideCoverageNV = 5249, GeometryShaderPassthroughNV = 5251, ShaderViewportIndexLayerEXT = 5254, diff --git a/lib/CL/devices/spirv_queries.cc b/lib/CL/devices/spirv_queries.cc index 9514b77213..216b074362 100644 --- a/lib/CL/devices/spirv_queries.cc +++ b/lib/CL/devices/spirv_queries.cc @@ -254,6 +254,13 @@ void pocl_setup_spirv_queries(cl_device_id dev) { static_cast(spv::Capability::FloatControls2)); } + if (dev->supported_spirv_extensions && + strstr(dev->supported_spirv_extensions, "SPV_KHR_bfloat16")) { + SpirvExtensions.push_back("SPV_KHR_bfloat16"); + SpirvCapabilities.push_back( + static_cast(spv::Capability::BFloat16TypeKHR)); + } + if (strstr(dev->extensions, "cl_intel_spirv_subgroups")) { SpirvExtensions.push_back("SPV_INTEL_subgroups"); SpirvCapabilities.push_back( diff --git a/lib/CL/pocl_llvm_orc.cc b/lib/CL/pocl_llvm_orc.cc index 133902842d..f2ed0b1e8a 100644 --- a/lib/CL/pocl_llvm_orc.cc +++ b/lib/CL/pocl_llvm_orc.cc @@ -129,6 +129,44 @@ static double poclExtendHFDF2(_Float16 A) { } #endif +#if defined(__x86_64__) || defined(_M_X64) +/* On x86-64 CPUs without native bfloat16 conversions, codegen calls + __truncsfbf2 and __truncdfbf2 for float/double -> bfloat. libgcc only has + them since GCC 13, and on Windows they have the problems of the FP16 helpers + above, so hand kernels our own. A bfloat16 is returned in the low 16 bits of + XMM0, like a float whose low half holds its bits, which spares us from + needing __bf16 support in the compiler that builds PoCL. */ +static float poclBF16Result(uint32_t H) { + float R; + __builtin_memcpy(&R, &H, sizeof R); + return R; +} +/* Rounds the bits of a float to the bits of a bfloat16, to nearest even. */ +static uint32_t poclFloatBitsToBF16(uint32_t U) { + if ((U & 0x7fffffffu) > 0x7f800000u) // NaN: keep it, but quiet + return (U >> 16) | 0x40u; + return (U + 0x7fffu + ((U >> 16) & 1u)) >> 16; +} +static float poclTruncSFBF2(float A) { + uint32_t U; + __builtin_memcpy(&U, &A, sizeof U); + return poclBF16Result(poclFloatBitsToBF16(U)); +} +static float poclTruncDFBF2(double A) { + /* Round to float with round-to-odd first, so that rounding that to + bfloat16 gives the correctly rounded result. */ + float F = (float)A; + uint32_t U; + __builtin_memcpy(&U, &F, sizeof U); + if (F == F && (double)F != A) { + if (__builtin_fabs((double)F) > __builtin_fabs(A)) + U -= 1; + U |= 1; + } + return poclBF16Result(poclFloatBitsToBF16(U)); +} +#endif + namespace { /* Process-global JIT shared by all CPU host devices, created on the first @@ -436,8 +474,9 @@ static bool addLazySVMLGenerator(const char *IRCPath, const char *SVMLPath) { } /* Inject symbols that kernel objects reference but that are linked into libpocl - rather than exported by a process library: PoCL's own host callbacks and, on - Windows, the libgcc/compiler-rt stack probe. Defining them as absolute + rather than exported by a process library: PoCL's own host callbacks, the + bfloat16 conversions on x86-64 and, on Windows, the libgcc/compiler-rt stack + probe and FP16 conversions. Defining them as absolute symbols makes resolution independent of libpocl's (deliberately hidden) dynamic-symbol visibility. They are constant for the process, so this is done once at init into the process-symbols JITDylib that every kernel JITDylib @@ -467,6 +506,14 @@ void defineHostSymbols(JITDylib &JD) { Syms[TheJIT->mangleAndIntern("__extendhfdf2")] = { ExecutorAddr::fromPtr(&poclExtendHFDF2), JITSymbolFlags::Exported | JITSymbolFlags::Callable}; +#endif +#if defined(__x86_64__) || defined(_M_X64) + Syms[TheJIT->mangleAndIntern("__truncsfbf2")] = { + ExecutorAddr::fromPtr(&poclTruncSFBF2), + JITSymbolFlags::Exported | JITSymbolFlags::Callable}; + Syms[TheJIT->mangleAndIntern("__truncdfbf2")] = { + ExecutorAddr::fromPtr(&poclTruncDFBF2), + JITSymbolFlags::Exported | JITSymbolFlags::Callable}; #endif if (Syms.empty()) return; diff --git a/tests/regression/CMakeLists.txt b/tests/regression/CMakeLists.txt index a17a518440..e5913ce263 100644 --- a/tests/regression/CMakeLists.txt +++ b/tests/regression/CMakeLists.txt @@ -40,6 +40,7 @@ set(C_PROGRAMS_TO_BUILD test_assign_loop_variable_to_privvar_makes_it_local test_localmem_load_across_barrier test_replicated_wi_subgroup_alloca test_spirv_intel_subgroups + test_spirv_bfloat16 test_indirect_ptrs test_usm_indirect_ptrs test_usm_free_realloc @@ -57,6 +58,10 @@ endforeach() target_include_directories(test_indirect_ptrs PRIVATE $) +if(HAVE_LLVM_SPIRV_KHR_BFLOAT16) + target_compile_definitions(test_spirv_bfloat16 PRIVATE EXPECT_CPU_SPV_KHR_BFLOAT16) +endif() + set(PROGRAMS_TO_BUILD test_barrier_between_for_loops test_early_return test_for_with_var_iteration_count test_id_dependent_computation test_locals test_multi_level_loops_with_barriers @@ -203,6 +208,8 @@ add_test_pocl(NAME "regression/multi_exit_barrier_region" WORKITEM_HANDLER "loop add_test_pocl(NAME "regression/spirv_intel_subgroups" WORKITEM_HANDLER "loops;loopvec;cbs;" COMMAND "test_spirv_intel_subgroups" LABELS ${SPIRV_LABELS}) +add_test_pocl(NAME "regression/spirv_bfloat16" WORKITEM_HANDLER "loops;loopvec;cbs;" COMMAND "test_spirv_bfloat16" LABELS ${SPIRV_LABELS}) + add_test_pocl(NAME "regression/divergent_implicit_barrier_entry" WORKITEM_HANDLER "loops;loopvec;cbs;" COMMAND "test_divergent_implicit_barrier_entry") add_test_pocl(NAME "regression/uniform_implicit_barrier_entry" WORKITEM_HANDLER "loops;loopvec;cbs;" COMMAND "test_uniform_implicit_barrier_entry") diff --git a/tests/regression/test_spirv_bfloat16.c b/tests/regression/test_spirv_bfloat16.c new file mode 100644 index 0000000000..f52a1c0d13 --- /dev/null +++ b/tests/regression/test_spirv_bfloat16.c @@ -0,0 +1,294 @@ +// Copyright (c) 2026 PoCL developers +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +/* + A kernel using SPV_KHR_bfloat16 to store, load and convert bfloat16 values, + including a bfloat16 kernel argument. The SPIR-V reader rejects modules using + extensions that are not enabled through --spirv-ext, so before the extension + was enabled, building the program failed. Float to bfloat16 conversions + round to nearest even. Test source (test_spirv_bfloat16.spv, assembled with + spirv-as --target-env spv1.0): + + OpCapability Addresses + OpCapability Kernel + OpCapability Int64 + OpCapability BFloat16TypeKHR + OpExtension "SPV_KHR_bfloat16" + OpMemoryModel Physical64 OpenCL + OpEntryPoint Kernel %kernel "convert" %gid + OpDecorate %gid BuiltIn GlobalInvocationId + OpDecorate %gid Constant + %ulong = OpTypeInt 64 0 + %v3ulong = OpTypeVector %ulong 3 + %ptr_input = OpTypePointer Input %v3ulong + %void = OpTypeVoid + %float = OpTypeFloat 32 + %bf16 = OpTypeFloat 16 BFloat16KHR + %ptr_f32 = OpTypePointer CrossWorkgroup %float + %ptr_bf16 = OpTypePointer CrossWorkgroup %bf16 + %fn = OpTypeFunction %void %ptr_bf16 %ptr_f32 %ptr_f32 %ptr_bf16 %bf16 + %gid = OpVariable %ptr_input Input + %kernel = OpFunction %void None %fn + %out_bf = OpFunctionParameter %ptr_bf16 + %out_f = OpFunctionParameter %ptr_f32 + %in_f = OpFunctionParameter %ptr_f32 + %in_bf = OpFunctionParameter %ptr_bf16 + %scale = OpFunctionParameter %bf16 + %entry = OpLabel + %gid3 = OpLoad %v3ulong %gid Aligned 32 + %i = OpCompositeExtract %ulong %gid3 0 + %in_f_ptr = OpInBoundsPtrAccessChain %ptr_f32 %in_f %i + %in_bf_ptr = OpInBoundsPtrAccessChain %ptr_bf16 %in_bf %i + %out_bf_ptr = OpInBoundsPtrAccessChain %ptr_bf16 %out_bf %i + %out_f_ptr = OpInBoundsPtrAccessChain %ptr_f32 %out_f %i + %f = OpLoad %float %in_f_ptr Aligned 4 + %narrow = OpFConvert %bf16 %f + OpStore %out_bf_ptr %narrow Aligned 2 + %b = OpLoad %bf16 %in_bf_ptr Aligned 2 + %wide = OpFConvert %float %b + %scale_f = OpFConvert %float %scale + %scaled = OpFMul %float %wide %scale_f + OpStore %out_f_ptr %scaled Aligned 4 + OpReturn + OpFunctionEnd +*/ + +#include "pocl_opencl.h" + +#include +#include +#include +#include +#ifndef _WIN32 +#include +#endif + +#define CHECK_ERROR(err) \ + if (err != CL_SUCCESS) { \ + printf("OpenCL Error %d at %s:%d\n", err, __FILE__, __LINE__); \ + return 1; \ + } + +#define N 16 + +static float bits_to_float(uint32_t u) { + float f; + memcpy(&f, &u, sizeof f); + return f; +} + +int main(int argc, char **argv) { + cl_uint platform_index = argc > 1 ? (cl_uint)atoi(argv[1]) : 0; + cl_int err; + +#ifndef _WIN32 + // Fail quickly instead of tripping the much larger ctest timeout in case + // a regressed build hangs. + alarm(300); +#endif + + cl_uint num_platforms; + CHECK_ERROR(clGetPlatformIDs(0, NULL, &num_platforms)); + if (platform_index >= num_platforms) { + printf("Platform index %u out of range\n", platform_index); + return 1; + } + cl_platform_id *platforms = malloc(sizeof(cl_platform_id) * num_platforms); + CHECK_ERROR(clGetPlatformIDs(num_platforms, platforms, NULL)); + cl_platform_id platform = platforms[platform_index]; + free(platforms); + + cl_device_id device; + CHECK_ERROR(clGetDeviceIDs(platform, CL_DEVICE_TYPE_ALL, 1, &device, NULL)); + + if (!poclu_device_supports_il(device, "SPIR-V_1.0")) { + printf("SKIP: The test requires support for SPIR-V 1.0\n"); + return 77; + } + + size_t extensions_size; + CHECK_ERROR(clGetDeviceInfo(device, CL_DEVICE_SPIRV_EXTENSIONS_KHR, 0, NULL, + &extensions_size)); + const char **extensions = malloc(extensions_size); + CHECK_ERROR(clGetDeviceInfo(device, CL_DEVICE_SPIRV_EXTENSIONS_KHR, + extensions_size, extensions, NULL)); + int supported = 0; + for (size_t i = 0; i < extensions_size / sizeof(const char *); i++) + if (strcmp(extensions[i], "SPV_KHR_bfloat16") == 0) + supported = 1; + free(extensions); + if (!supported) { +#ifdef EXPECT_CPU_SPV_KHR_BFLOAT16 + // The CPU devices accept it whenever the translator does. + cl_device_type type; + CHECK_ERROR( + clGetDeviceInfo(device, CL_DEVICE_TYPE, sizeof(type), &type, NULL)); + if (type & CL_DEVICE_TYPE_CPU) { + printf("The CPU device does not report SPV_KHR_bfloat16\n"); + return 1; + } +#endif + printf("SKIP: The test requires SPV_KHR_bfloat16\n"); + return 77; + } + + size_t capabilities_size; + CHECK_ERROR(clGetDeviceInfo(device, CL_DEVICE_SPIRV_CAPABILITIES_KHR, 0, NULL, + &capabilities_size)); + cl_uint *capabilities = malloc(capabilities_size); + CHECK_ERROR(clGetDeviceInfo(device, CL_DEVICE_SPIRV_CAPABILITIES_KHR, + capabilities_size, capabilities, NULL)); + int has_capability = 0; + for (size_t i = 0; i < capabilities_size / sizeof(cl_uint); i++) + if (capabilities[i] == 5116) // BFloat16TypeKHR + has_capability = 1; + free(capabilities); + if (!has_capability) { + printf("SPV_KHR_bfloat16 is reported without BFloat16TypeKHR\n"); + return 1; + } + + cl_context context = clCreateContext(NULL, 1, &device, NULL, NULL, &err); + CHECK_ERROR(err); + cl_queue_properties props[] = {0}; + cl_command_queue queue = + clCreateCommandQueueWithProperties(context, device, props, &err); + CHECK_ERROR(err); + + FILE *f = fopen(SRCDIR "/test_spirv_bfloat16.spv", "rb"); + if (!f) { + printf("Failed to open test_spirv_bfloat16.spv\n"); + return 1; + } + fseek(f, 0, SEEK_END); + size_t size = ftell(f); + fseek(f, 0, SEEK_SET); + unsigned char *binary = malloc(size); + if (fread(binary, 1, size, f) != size) { + printf("Failed to read SPIR-V\n"); + free(binary); + fclose(f); + return 1; + } + fclose(f); + + cl_program program = clCreateProgramWithIL(context, binary, size, &err); + CHECK_ERROR(err); + CHECK_ERROR(clBuildProgram(program, 1, &device, NULL, NULL, NULL)); + + cl_kernel kernel = clCreateKernel(program, "convert", &err); + CHECK_ERROR(err); + + // Float inputs and their bfloat16 bits, rounded to nearest even. + static const uint32_t in_f_bits[N] = { + 0x3f800000, // 1.0 + 0x3f808000, // halfway between 1.0 and its successor: to even, down + 0x3f818000, // halfway, odd below: to even, up + 0x3f808001, // just above halfway: up + 0x3f807fff, // just below halfway: down + 0xc0200000, // -2.5 + 0xbf808000, // -(halfway): to even, down in magnitude + 0x7f7fffff, // FLT_MAX: overflows to infinity + 0x7f800000, // infinity + 0xff800000, // -infinity + 0x00000000, // 0.0 + 0x80000000, // -0.0 + 0x40490fdb, // pi + 0x3dcccccd, // 0.1 + 0x477fe000, // 65504 + 0x3f7fffff, // just below 1.0: up to 1.0 + }; + static const uint16_t expected_bf_bits[N] = { + 0x3f80, 0x3f80, 0x3f82, 0x3f81, 0x3f80, 0xc020, 0xbf80, 0x7f80, + 0x7f80, 0xff80, 0x0000, 0x8000, 0x4049, 0x3dcd, 0x4780, 0x3f80, + }; + + float in_f[N]; + uint16_t in_bf[N]; + for (int i = 0; i < N; i++) { + in_f[i] = bits_to_float(in_f_bits[i]); + // Widening is exact: the bfloat16 bits are the float's upper half. + in_bf[i] = (uint16_t)(in_f_bits[i] >> 16); + } + uint16_t scale = 0xc000; // -2.0 + + uint16_t out_bf[N]; + float out_f[N]; + memset(out_bf, 0xff, sizeof(out_bf)); + memset(out_f, 0xff, sizeof(out_f)); + + cl_mem out_bf_buf = + clCreateBuffer(context, CL_MEM_WRITE_ONLY, sizeof(out_bf), NULL, &err); + CHECK_ERROR(err); + cl_mem out_f_buf = + clCreateBuffer(context, CL_MEM_WRITE_ONLY, sizeof(out_f), NULL, &err); + CHECK_ERROR(err); + cl_mem in_f_buf = + clCreateBuffer(context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, + sizeof(in_f), in_f, &err); + CHECK_ERROR(err); + cl_mem in_bf_buf = + clCreateBuffer(context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, + sizeof(in_bf), in_bf, &err); + CHECK_ERROR(err); + CHECK_ERROR(clSetKernelArg(kernel, 0, sizeof(cl_mem), &out_bf_buf)); + CHECK_ERROR(clSetKernelArg(kernel, 1, sizeof(cl_mem), &out_f_buf)); + CHECK_ERROR(clSetKernelArg(kernel, 2, sizeof(cl_mem), &in_f_buf)); + CHECK_ERROR(clSetKernelArg(kernel, 3, sizeof(cl_mem), &in_bf_buf)); + CHECK_ERROR(clSetKernelArg(kernel, 4, sizeof(scale), &scale)); + + size_t global_size = N, local_size = 8; + CHECK_ERROR(clEnqueueNDRangeKernel(queue, kernel, 1, NULL, &global_size, + &local_size, 0, NULL, NULL)); + CHECK_ERROR(clEnqueueReadBuffer(queue, out_bf_buf, CL_TRUE, 0, sizeof(out_bf), + out_bf, 0, NULL, NULL)); + CHECK_ERROR(clEnqueueReadBuffer(queue, out_f_buf, CL_TRUE, 0, sizeof(out_f), + out_f, 0, NULL, NULL)); + + int failed = 0; + for (int i = 0; i < N; i++) { + if (out_bf[i] != expected_bf_bits[i]) { + printf("bfloat16(%a) = 0x%04x, expected 0x%04x\n", in_f[i], out_bf[i], + expected_bf_bits[i]); + failed = 1; + } + float expected = bits_to_float((uint32_t)in_bf[i] << 16) * -2.0f; + if (memcmp(&out_f[i], &expected, sizeof(float)) != 0) { + printf("float(bfloat16 0x%04x) * -2 = %a, expected %a\n", in_bf[i], + out_f[i], expected); + failed = 1; + } + } + + clReleaseMemObject(out_bf_buf); + clReleaseMemObject(out_f_buf); + clReleaseMemObject(in_f_buf); + clReleaseMemObject(in_bf_buf); + clReleaseKernel(kernel); + clReleaseProgram(program); + clReleaseCommandQueue(queue); + clReleaseContext(context); + free(binary); + + if (failed) + return 1; + printf("OK\n"); + return 0; +} diff --git a/tests/regression/test_spirv_bfloat16.spv b/tests/regression/test_spirv_bfloat16.spv new file mode 100644 index 0000000000..0fe25f76cf Binary files /dev/null and b/tests/regression/test_spirv_bfloat16.spv differ