yum-mirror/VkFFT

git clone https://git.yummers.dev/yum-mirror/VkFFT

Tolmachev DmitriiMetal support in VkFFTba7001c

v1.2.30
11.4 KiB275 linesraw
1//general parts
2#include <stdio.h>
3#include <vector>
4#include <memory>
5#include <string.h>
6#include <chrono>
7#include <thread>
8#include <iostream>
9#ifndef __STDC_FORMAT_MACROS
10#define __STDC_FORMAT_MACROS
11#endif
12#include <inttypes.h>
13
14#if(VKFFT_BACKEND==0)
15#include "vulkan/vulkan.h"
16#include "glslang_c_interface.h"
17#elif(VKFFT_BACKEND==1)
18#include <cuda.h>
19#include <cuda_runtime.h>
20#include <nvrtc.h>
21#include <cuda_runtime_api.h>
22#include <cuComplex.h>
23#elif(VKFFT_BACKEND==2)
24#ifndef __HIP_PLATFORM_HCC__
25#define __HIP_PLATFORM_HCC__
26#endif
27#include <hip/hip_runtime.h>
28#include <hip/hiprtc.h>
29#include <hip/hip_runtime_api.h>
30#include <hip/hip_complex.h>
31#elif(VKFFT_BACKEND==3)
32#ifndef CL_USE_DEPRECATED_OPENCL_1_2_APIS
33#define CL_USE_DEPRECATED_OPENCL_1_2_APIS
34#endif
35#ifdef __APPLE__
36#include <OpenCL/opencl.h>
37#else
38#include <CL/cl.h>
39#endif 
40#elif(VKFFT_BACKEND==4)
41#include <ze_api.h>
42#elif(VKFFT_BACKEND==5)
43#include "Foundation/Foundation.hpp"
44#include "QuartzCore/QuartzCore.hpp"
45#include "Metal/Metal.hpp"
46#endif
47#include "vkFFT.h"
48#include "utils_VkFFT.h"
49#include "half.hpp"
50
51VkFFTResult user_benchmark_VkFFT(VkGPU* vkGPU, uint64_t file_output, FILE* output, uint64_t isCompilerInitialized, VkFFTUserSystemParameters* userParams)
52{
53	VkFFTResult resFFT = VKFFT_SUCCESS;
54#if(VKFFT_BACKEND==0)
55	VkResult res = VK_SUCCESS;
56#elif(VKFFT_BACKEND==1)
57	cudaError_t res = cudaSuccess;
58#elif(VKFFT_BACKEND==2)
59	hipError_t res = hipSuccess;
60#elif(VKFFT_BACKEND==3)
61	cl_int res = CL_SUCCESS;
62#elif(VKFFT_BACKEND==4)
63	ze_result_t res = ZE_RESULT_SUCCESS;
64#elif(VKFFT_BACKEND==5)
65#endif
66	const int num_runs = 3;
67	double benchmark_result = 0;//averaged result = sum(system_size/iteration_time)/num_benchmark_samples
68	//memory allocated on the CPU once, makes benchmark completion faster + avoids performance issues connected to frequent allocation/deallocation.
69	uint64_t storageComplexSize=8;
70	switch (userParams->P) {
71	case 0:
72		storageComplexSize = (2 * sizeof(float));
73		break;
74	case 1:
75		storageComplexSize = (2 * sizeof(double));
76		break;
77	case 2:
78		storageComplexSize = (2 * 2);
79		break;
80	default:
81		storageComplexSize = (2 * sizeof(float));
82		break;
83	}
84    uint64_t bufferSize = 0;
85    if (userParams->R2C) {
86        bufferSize = (uint64_t)(storageComplexSize / 2) * (userParams->X + 2) * userParams->Y * userParams->Z * userParams->B;
87    }
88    else {
89        if (userParams->DCT) {
90            bufferSize = (uint64_t)(storageComplexSize / 2) * userParams->X * userParams->Y * userParams->Z * userParams->B;
91        }
92        else {
93            bufferSize = (uint64_t)storageComplexSize * userParams->X * userParams->Y * userParams->Z * userParams->B;
94        }
95    }
96    
97    float* buffer_input = (float*)malloc(bufferSize);
98    if (!buffer_input) return VKFFT_ERROR_MALLOC_FAILED;
99    for (uint64_t i = 0; i < bufferSize/sizeof(float); i++) {
100        buffer_input[i] = (float)(2 * ((float)rand()) / RAND_MAX - 1.0);
101    }
102	for (uint64_t n = 0; n < 2; n++) {
103		double run_time[num_runs];
104		for (uint64_t r = 0; r < num_runs; r++) {
105			//Configuration + FFT application .
106			VkFFTConfiguration configuration = {};
107			VkFFTApplication app = {};
108			//FFT + iFFT sample code.
109			//Setting up FFT configuration for forward and inverse FFT.
110			configuration.FFTdim = 1; //FFT dimension, 1D, 2D or 3D (default 1).
111			//if (n == 1) configuration.keepShaderCode = 1;
112
113			configuration.size[0] = userParams->X;
114			configuration.size[1] = userParams->Y;
115			configuration.size[2] = userParams->Z;
116			if (userParams->Y > 1) configuration.FFTdim++;
117			if (userParams->Z > 1) configuration.FFTdim++;
118			configuration.numberBatches = userParams->B;
119			configuration.performR2C = userParams->R2C;
120			configuration.performDCT = userParams->DCT;
121			if (userParams->P == 1) configuration.doublePrecision = 1;
122			if (userParams->P == 2) configuration.halfPrecision = 1;
123#if(VKFFT_BACKEND!=5)
124			if (userParams->saveApplicationToString && (n==0) && (r==0)) configuration.saveApplicationToString = 1;
125			if (userParams->loadApplicationFromString || (userParams->saveApplicationToString && ((n != 0) || (r != 0)))) configuration.loadApplicationFromString = 1;
126#endif
127			//After this, configuration file contains pointers to Vulkan objects needed to work with the GPU: VkDevice* device - created device, [uint64_t *bufferSize, VkBuffer *buffer, VkDeviceMemory* bufferDeviceMemory] - allocated GPU memory FFT is performed on. [uint64_t *kernelSize, VkBuffer *kernel, VkDeviceMemory* kernelDeviceMemory] - allocated GPU memory, where kernel for convolution is stored.
128#if(VKFFT_BACKEND==5)
129			configuration.device = vkGPU->device;
130#else
131            configuration.device = &vkGPU->device;
132#endif
133#if(VKFFT_BACKEND==0)
134			configuration.queue = &vkGPU->queue; //to allocate memory for LUT, we have to pass a queue, vkGPU->fence, commandPool and physicalDevice pointers 
135			configuration.fence = &vkGPU->fence;
136			configuration.commandPool = &vkGPU->commandPool;
137			configuration.physicalDevice = &vkGPU->physicalDevice;
138			configuration.isCompilerInitialized = isCompilerInitialized;//compiler can be initialized before VkFFT plan creation. if not, VkFFT will create and destroy one after initialization
139#elif(VKFFT_BACKEND==3)
140			configuration.context = &vkGPU->context;
141#elif(VKFFT_BACKEND==4)
142			configuration.context = &vkGPU->context;
143			configuration.commandQueue = &vkGPU->commandQueue;
144			configuration.commandQueueID = vkGPU->commandQueueID;
145#elif(VKFFT_BACKEND==5)
146            configuration.queue = vkGPU->queue;
147#endif
148			//Allocate buffer for the input data.
149#if(VKFFT_BACKEND==0)
150			VkBuffer buffer = {};
151			VkDeviceMemory bufferDeviceMemory = {};
152			resFFT = allocateBuffer(vkGPU, &buffer, &bufferDeviceMemory, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, VK_MEMORY_HEAP_DEVICE_LOCAL_BIT, bufferSize);
153			if (resFFT != VKFFT_SUCCESS) return resFFT;
154			configuration.buffer = &buffer;
155#elif(VKFFT_BACKEND==1)
156			cuFloatComplex* buffer = 0;
157			res = cudaMalloc((void**)&buffer, bufferSize);
158			if (res != cudaSuccess) return VKFFT_ERROR_FAILED_TO_ALLOCATE;
159			configuration.buffer = (void**)&buffer;
160#elif(VKFFT_BACKEND==2)
161			hipFloatComplex* buffer = 0;
162			res = hipMalloc((void**)&buffer, bufferSize);
163			if (res != hipSuccess) return VKFFT_ERROR_FAILED_TO_ALLOCATE;
164			configuration.buffer = (void**)&buffer;
165#elif(VKFFT_BACKEND==3)
166			cl_mem buffer = 0;
167			buffer = clCreateBuffer(vkGPU->context, CL_MEM_READ_WRITE, bufferSize, 0, &res);
168			if (res != CL_SUCCESS) return VKFFT_ERROR_FAILED_TO_ALLOCATE;
169			configuration.buffer = &buffer;
170#elif(VKFFT_BACKEND==4)
171			void* buffer = 0;
172			ze_device_mem_alloc_desc_t device_desc = {};
173			device_desc.stype = ZE_STRUCTURE_TYPE_DEVICE_MEM_ALLOC_DESC;
174			res = zeMemAllocDevice(vkGPU->context, &device_desc, bufferSize, sizeof(float), vkGPU->device, &buffer);
175			if (res != ZE_RESULT_SUCCESS) return VKFFT_ERROR_FAILED_TO_ALLOCATE;
176			configuration.buffer = &buffer;
177#elif(VKFFT_BACKEND==5)
178            MTL::Buffer* buffer = 0;
179            buffer = vkGPU->device->newBuffer(bufferSize, MTL::ResourceStorageModePrivate);
180            configuration.buffer = &buffer;
181#endif
182
183			configuration.bufferSize = &bufferSize;
184            
185            resFFT = transferDataFromCPU(vkGPU, buffer_input, &buffer, bufferSize);
186            if (resFFT != VKFFT_SUCCESS) return resFFT;
187            
188			if (configuration.loadApplicationFromString) {
189				FILE* kernelCache;
190				uint64_t str_len;
191				char fname[500];
192				int VkFFT_version = VkFFTGetVersion();
193				sprintf(fname, "VkFFT_binary_X%" PRIu64 "_Y%" PRIu64 "_Z%" PRIu64 "_P%" PRIu64 "_B%" PRIu64 "_N%" PRIu64 "_R2C%" PRIu64 "_DCT%" PRIu64 "_ver%d", userParams->X, userParams->Y, userParams->Z, userParams->P, userParams->B, userParams->N, userParams->R2C, userParams->DCT, VkFFT_version);
194				kernelCache = fopen(fname, "rb");
195				if (!kernelCache) return VKFFT_ERROR_EMPTY_FILE;
196				fseek(kernelCache, 0, SEEK_END);
197				str_len = ftell(kernelCache);
198				fseek(kernelCache, 0, SEEK_SET);
199				configuration.loadApplicationString = malloc(str_len);
200				fread(configuration.loadApplicationString, str_len, 1, kernelCache);
201				fclose(kernelCache);
202			}
203			//Initialize applications. This function loads shaders, creates pipeline and configures FFT based on configuration file. No buffer allocations inside VkFFT library.  
204			resFFT = initializeVkFFT(&app, configuration);
205			if (resFFT != VKFFT_SUCCESS) return resFFT;
206
207			if (configuration.loadApplicationFromString)
208				free(configuration.loadApplicationString);
209
210			if (configuration.saveApplicationToString) {
211				FILE* kernelCache;
212				char fname[500];
213				int VkFFT_version = VkFFTGetVersion();
214				sprintf(fname, "VkFFT_binary_X%" PRIu64 "_Y%" PRIu64 "_Z%" PRIu64 "_P%" PRIu64 "_B%" PRIu64 "_N%" PRIu64 "_R2C%" PRIu64 "_DCT%" PRIu64 "_ver%d", userParams->X, userParams->Y, userParams->Z, userParams->P, userParams->B, userParams->N, userParams->R2C, userParams->DCT, VkFFT_version);
215				kernelCache = fopen(fname, "wb");
216				fwrite(app.saveApplicationString, app.applicationStringSize, 1, kernelCache);
217				fclose(kernelCache);
218			}
219
220			//Submit FFT+iFFT.
221			
222			double totTime = 0;
223
224			VkFFTLaunchParams launchParams = {};
225			resFFT = performVulkanFFTiFFT(vkGPU, &app, &launchParams, userParams->N, &totTime);
226			if (resFFT != VKFFT_SUCCESS) return resFFT;
227			run_time[r] = totTime;
228			if (n > 0) {
229				if (r == num_runs - 1) {
230					double std_error = 0;
231					double avg_time = 0;
232					for (uint64_t t = 0; t < num_runs; t++) {
233						avg_time += run_time[t];
234					}
235					avg_time /= num_runs;
236					for (uint64_t t = 0; t < num_runs; t++) {
237						std_error += (run_time[t] - avg_time) * (run_time[t] - avg_time);
238					}
239					std_error = sqrt(std_error / num_runs);
240					uint64_t num_tot_transfers = 0;
241					for (uint64_t i = 0; i < configuration.FFTdim; i++)
242						num_tot_transfers += app.localFFTPlan->numAxisUploads[i];
243					num_tot_transfers *= 4;
244					if (file_output)
245						fprintf(output, "VkFFT System: %" PRIu64 "x%" PRIu64 "x%" PRIu64 " Batch: %" PRIu64 " Buffer: %" PRIu64 " MB avg_time_per_step: %0.3f ms std_error: %0.3f num_iter: %" PRIu64 " benchmark: %" PRIu64 " scaled bandwidth: %0.1f bandwidth: %0.1f\n", configuration.size[0], configuration.size[1], configuration.size[2], userParams->B, bufferSize / 1024 / 1024, avg_time, std_error, userParams->N, (uint64_t)(((double)bufferSize / 1024) / avg_time), bufferSize / 1024.0 / 1024.0 / 1.024 * 4 * configuration.FFTdim / avg_time, bufferSize / 1024.0 / 1024.0 / 1.024 * num_tot_transfers / avg_time);
246
247					printf("VkFFT System: %" PRIu64 "x%" PRIu64 "x%" PRIu64 " Batch: %" PRIu64 " Buffer: %" PRIu64 " MB avg_time_per_step: %0.3f ms std_error: %0.3f num_iter: %" PRIu64 " benchmark: %" PRIu64 " scaled bandwidth: %0.1f real bandwidth: %0.1f\n", configuration.size[0], configuration.size[1], configuration.size[2], userParams->B, bufferSize / 1024 / 1024, avg_time, std_error, userParams->N, (uint64_t)(((double)bufferSize / 1024) / avg_time), bufferSize / 1024.0 / 1024.0 / 1.024 * 4 * configuration.FFTdim / avg_time, bufferSize / 1024.0 / 1024.0 / 1.024 * num_tot_transfers / avg_time);
248					benchmark_result += ((double)bufferSize / 1024) / avg_time;
249				}
250
251
252			}
253
254#if(VKFFT_BACKEND==0)
255			vkDestroyBuffer(vkGPU->device, buffer, NULL);
256			vkFreeMemory(vkGPU->device, bufferDeviceMemory, NULL);
257#elif(VKFFT_BACKEND==1)
258			cudaFree(buffer);
259#elif(VKFFT_BACKEND==2)
260			hipFree(buffer);
261#elif(VKFFT_BACKEND==3)
262			clReleaseMemObject(buffer);
263#elif(VKFFT_BACKEND==4)
264			zeMemFree(vkGPU->context, buffer);
265#elif(VKFFT_BACKEND==5)
266            buffer->release();
267#endif
268
269			deleteVkFFT(&app);
270
271		}
272	}
273    free(buffer_input);
274	return resFFT;
275}