yum-mirror/VkFFT

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

Tolmachev DmitriiVkFFT v1.3.3 released6f7ded

develop
138.7 KiB2625 linesraw
1%% LyX 2.3.4.3 created this file.  For more info, see http://www.lyx.org/.
2%% Do not edit unless you really know what you are doing.
3\documentclass[12pt,english]{article}
4\usepackage{amsmath}
5\usepackage{amssymb}
6\usepackage{fontspec}
7\usepackage{geometry}
8\geometry{verbose,tmargin=2.5cm,bmargin=2.5cm,lmargin=2.5cm,rmargin=2.5cm}
9\usepackage{stackrel}
10\usepackage[unicode=true]
11 {hyperref}
12
13\makeatletter
14%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% User specified LaTeX commands.
15\usepackage{sourcecodepro}
16\usepackage[parfill]{parskip}
17\usepackage{enumitem}
18\setlist[itemize]{leftmargin=*}
19\usepackage{minted}
20\usepackage{mdframed}
21\definecolor{bg}{rgb}{0.95,0.95,0.95}
22\usepackage{hyperref}
23\hypersetup{
24    colorlinks,
25    citecolor=black,
26    filecolor=black,
27    linkcolor=black,
28    urlcolor=black
29}
30
31\makeatother
32
33\usepackage{polyglossia}
34\setdefaultlanguage[variant=american]{english}
35\begin{document}
36\UseRawInputEncoding
37\begin{titlepage} 	
38\centering 	
39\vspace{1cm} 	
40{\scshape\LARGE VkFFT - Vulkan/CUDA/HIP/OpenCL/Level Zero/Metal Fast Fourier Transform library \par} 		
41\vspace{1.5cm} 	
42{\huge\bfseries API guide with examples\par} 	
43\vspace{2cm} 	
44{\Large Dmitrii Tolmachev\par} 	
45	
46\vspace{1cm} 	
47{\large January 2024, version 1.3.3\par} 
48\end{titlepage}
49
50\newpage{}
51
52\tableofcontents{}
53
54\newpage{}
55
56\section{Introduction}
57
58This document describes VkFFT - Vulkan/CUDA/HIP/OpenCL/Level Zero/Metal
59Fast Fourier Transform library. It describes the features and current
60limitations of VkFFT, explains the API and compares it to other FFT
61libraries (like FFTW and cuFFT) on the set of examples. It is by no
62means the final version, so if there is something unclear - feel free
63to contact me (dtolm96@gmail.com), so I can update it. 
64
65\newpage{}
66
67\section{Using the VkFFT API}
68
69This chapter will cover the basics of VkFFT. Fourier transform of
70a sequence is called Discrete Fourier Transform (DFT). It is defined
71by the following formula:
72\begin{equation}
73X_{k}=\stackrel[n=0]{N-1}{\sum}x_{n}e^{-\frac{2\pi i}{N}nk}=\mathrm{DFT}{}_{N}(x_{n},k),\label{eq:dft}
74\end{equation}
75
76where $x_{n}$is the input sequence, $N$ is the length of the input
77sequence and $k\in[0,N-1],k\in\mathbb{Z}$is the output index, corresponding
78to frequency in Fourier space. Corresponding to that, inverse DFT
79is defined as following:
80\begin{equation}
81x_{n}=\stackrel[k=0]{\mathrm{N-1}}{\sum}X_{k}e^{\frac{2\pi i}{N}nk}=\mathrm{IDFT}{}_{N}(X_{k},n)
82\end{equation}
83
84VkFFT follows the same definitions as FFTW and cuFFT - forward FFT
85has the exponent sign $-1$, while the inverse has the exponent sign
86$1$. Note, that inverse transform by default is unnormalized, so
87to get the input sequence after FFT + iFFT, the user has to divide
88the result by $N$.
89
90\subsection{Installing VkFFT}
91
92VkFFT is distributed as a header-only library (strating from the version
931.3, it is no longer a single header). The installation process consists
94of the following steps:
95\begin{enumerate}
96\item \begin{flushleft}
97Copy vkFFT.h file and vkFFT directory into one of the directories
98included in the user's project.
99\par\end{flushleft}
100\item Define VKFFT\_BACKEND as a number corresponding to the API used in
101the user's project: 0 - Vulkan, 1 - CUDA, 2 - HIP, 3 - OpenCL, 4 -
102Level Zero, 5 - Metal. Definition is done like:\begin{mdframed}[backgroundcolor=bg]
103\begin{minted}[tabsize=4,obeytabs,breaklines]{make}
104-DVKFFT_BACKEND=X
105\end{minted}
106\end{mdframed} in GCC or as \begin{mdframed}[backgroundcolor=bg]
107\begin{minted}[tabsize=4,obeytabs,breaklines]{cmake}
108set(VKFFT_BACKEND 1 CACHE STRING "0 - Vulkan, 1 - CUDA, 2 - HIP, 3 - OpenCL, 4 - Level Zero, 5 - Metal")
109\end{minted}
110\end{mdframed}in CMake.
111\item Define VKFFT\_MAX\_FFT\_DIMENSIONS as the number of max dimensions
112to be supported by VkFFT. Default is 4.
113\item Depending on the API backend, the project must use additional libraries
114for run-time compilation:
115\begin{enumerate}
116\item Vulkan API: SPIRV, glslang and Vulkan. Define VK\_API\_VERSION to
117the available Vulkan version. Sample CMakeLists can look like this:\begin{mdframed}[backgroundcolor=bg]
118\begin{minted}[tabsize=4,obeytabs,breaklines]{cmake}
119find_package(Vulkan REQUIRED)
120target_compile_definitions(${PROJECT_NAME} PUBLIC -DVK_API_VERSION=11)#10 - Vulkan 1.0, 11 - Vulkan 1.1, 12 - Vulkan 1.2 
121target_include_directories(${PROJECT_NAME} PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/glslang-main/glslang/Include/) 
122add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/glslang-main)
123
124target_include_directories(${PROJECT_NAME} PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/vkFFT/)
125add_library(VkFFT INTERFACE)
126target_compile_definitions(VkFFT INTERFACE -DVKFFT_BACKEND=0)
127
128target_link_libraries(${PROJECT_NAME} PUBLIC SPIRV glslang Vulkan::Vulkan VkFFT)
129\end{minted}
130\end{mdframed}
131\item CUDA API: CUDA and NVRTC. Sample CMakeLists can look like this: \begin{mdframed}[backgroundcolor=bg]
132\begin{minted}[tabsize=4,obeytabs,breaklines]{cmake}
133find_package(CUDA 9.0 REQUIRED) 	
134enable_language(CUDA) 	
135set_property(TARGET ${PROJECT_NAME} PROPERTY CUDA_ARCHITECTURESs 60 70 75 80 86) 	
136target_compile_options(${PROJECT_NAME} PUBLIC "$<$<COMPILE_LANGUAGE:CUDA>:SHELL: 	
137	-DVKFFT_BACKEND=${VKFFT_BACKEND} 	
138	-gencode arch=compute_60,code=compute_60
139	-gencode arch=compute_70,code=compute_70
140	-gencode arch=compute_75,code=compute_75
141	-gencode arch=compute_80,code=compute_80
142	-gencode arch=compute_86,code=compute_86>")
143set_target_properties(${PROJECT_NAME} PROPERTIES CUDA_SEPARABLE_COMPILATION ON)
144set_target_properties(${PROJECT_NAME} PROPERTIES CUDA_RESOLVE_DEVICE_SYMBOLS ON)
145
146find_library(CUDA_NVRTC_LIB libnvrtc nvrtc HINTS "${CUDA_TOOLKIT_ROOT_DIR}/lib64" "${LIBNVRTC_LIBRARY_DIR}" "${CUDA_TOOLKIT_ROOT_DIR}/lib/x64" /usr/lib64 /usr/local/cuda/lib64)
147add_definitions(-DCUDA_TOOLKIT_ROOT_DIR="${CUDA_TOOLKIT_ROOT_DIR}")
148
149target_include_directories(${PROJECT_NAME} PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/vkFFT/)
150add_library(VkFFT INTERFACE)
151target_compile_definitions(VkFFT INTERFACE -DVKFFT_BACKEND=1)
152
153target_link_libraries(${PROJECT_NAME} PUBLIC ${CUDA_LIBRARIES} cuda ${CUDA_NVRTC_LIB} VkFFT)
154\end{minted}
155\end{mdframed}
156\item HIP API: HIP and HIPRTC. Sample CMakeLists can look like this:\begin{mdframed}[backgroundcolor=bg]
157\begin{minted}[tabsize=4,obeytabs,breaklines]{cmake}
158list(APPEND CMAKE_PREFIX_PATH /opt/rocm/hip /opt/rocm)
159find_package(hip)
160
161target_include_directories(${PROJECT_NAME} PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/vkFFT/)
162add_library(VkFFT INTERFACE)
163target_compile_definitions(VkFFT INTERFACE -DVKFFT_BACKEND=2)
164#target_compile_definitions(${PROJECT_NAME} PUBLIC -DVKFFT_OLD_ROCM) #ROCm versions before 4.5 needed kernel include of hiprtc
165
166target_link_libraries(${PROJECT_NAME} PUBLIC hip::host VkFFT)
167\end{minted}
168\end{mdframed}
169\item OpenCL API: OpenCL. Sample CMakeLists can look like this:\begin{mdframed}[backgroundcolor=bg]
170\begin{minted}[tabsize=4,obeytabs,breaklines]{cmake}
171find_package(OpenCL REQUIRED)
172
173target_include_directories(${PROJECT_NAME} PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/vkFFT/)
174add_library(VkFFT INTERFACE)
175target_compile_definitions(VkFFT INTERFACE -DVKFFT_BACKEND=3)
176
177target_link_libraries(${PROJECT_NAME} PUBLIC OpenCL::OpenCL VkFFT)
178\end{minted}
179\end{mdframed}
180\item Level Zero API: Level Zero; Clang and llvm-spirv must be in the system
181path (for kernel compilation). Sample CMakeLists can look like this:\begin{mdframed}[backgroundcolor=bg]
182\begin{minted}[tabsize=4,obeytabs,breaklines]{cmake}
183set(LevelZero_LIBRARY "/usr/lib/x86_64-linux-gnu/")
184set(LevelZero_INCLUDE_DIR "/usr/include/")
185find_library(
186	LevelZero_LIB
187	NAMES "ze_loader"
188	PATHS ${LevelZero_LIBRARY}
189	PATH_SUFFIXES "lib" "lib64"
190	NO_DEFAULT_PATH
191  )
192find_path(
193	LevelZero_INCLUDES
194	NAMES "ze_api.h"
195	PATHS ${LevelZero_INCLUDE_DIR}
196	PATH_SUFFIXES "include" "level_zero"
197	NO_DEFAULT_PATH
198  )
199target_include_directories(${PROJECT_NAME} PUBLIC ${LevelZero_INCLUDES})
200add_library(VkFFT INTERFACE)
201target_compile_definitions(VkFFT INTERFACE -DVKFFT_BACKEND=4)
202
203target_link_libraries(${PROJECT_NAME} PUBLIC LevelZero VkFFT)
204\end{minted}
205\end{mdframed}
206\item Metal API: Metal. Sample CMakeLists can look like this:\begin{mdframed}[backgroundcolor=bg]
207\begin{minted}[tabsize=4,obeytabs,breaklines]{cmake}
208add_compile_options(-WMTL_IGNORE_WARNINGS)
209find_library(FOUNDATION_LIB Foundation REQUIRED)
210find_library(QUARTZ_CORE_LIB QuartzCore REQUIRED)	
211find_library(METAL_LIB Metal REQUIRED)
212target_include_directories(${PROJECT_NAME} PUBLIC "metal-cpp/")
213
214target_include_directories(${PROJECT_NAME} PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/vkFFT/)
215add_library(VkFFT INTERFACE)
216target_compile_definitions(VkFFT INTERFACE -DVKFFT_BACKEND=5)
217
218target_link_libraries(${PROJECT_NAME} PUBLIC ${FOUNDATION_LIB} ${QUARTZ_CORE_LIB} ${METAL_LIB} VkFFT)
219\end{minted}
220\end{mdframed}
221\end{enumerate}
222\end{enumerate}
223
224\subsection{Fourier Transform Setup}
225
226VkFFT follows a plan structure like FFTW/cuFFT with a notable difference
227- there is a unified interface to all transforms. This means that
228there are no separate functions like fftPlan1D/fftPlan2D/fftPlanMany/etc.
229The initialization is done through a single configuration struct -
230VkFFTConfiguration. Each parameter of it will be covered in detail
231in this document. Plans in VkFFT are called VkFFTApplication and they
232are created with a unified initializeVkFFT call. 
233
234As the code is written in C, don't forget to zero-initialize used
235structs!
236
237During the initializeVkFFT(VkFFTApplication{*} app, VkFFTConfiguration
238inputLaunchConfiguration) call VkFFT performs kernel generation and
239compilation from scratch (kernel reuse may be added later). The overall
240process of initialization looks like this:
241\begin{enumerate}
242\item Get device parameters, perform default initialization of internal
243copy of configuration struct inside the VkFFTApplication, then fill
244in user-defined parameters from inputLaunchConfiguration.~VkFFTApplication
245is passed as a pointer, so initializeVkFFT modifies the user-provided
246application.
247\item By default, there are two internal FFT plans created - inverse and
248forward. Multidimensional FFT is done as a combination of 1D FFTs
249in each axis direction. For each axis, the VkFFTPlanAxis function
250is called.
251\item VkFFTPlanAxis configures parameters for each axis. It may perform
252additional memory allocations (see: memory allocated by VkFFT).
253\item shaderGenVkFFT generates corresponding to the axis code in a char
254buffer (each axis may require more than one kernel: see Four-step
255FFT, Bluestein's algorithm for FFT). 
256\item Code is then compiled with the run-time compiler of the specified
257backend.
258\end{enumerate}
259Once the plan is no longer need, a call to the deleteVkFFT function
260frees all the allocated resources. There are no processes launched
261that continue to work outside of the VkFFT related function calls.
262
263\subsection{Fourier Transform types and their definitions}
264
265VkFFT supports commonly used Complex to complex (C2C), real to complex
266(R2C), complex to real (C2R) transformations and real to real (R2R)
267Discrete Cosine/Sine Transformations of types I, II, III and IV. VkFFT
268uses the same definitions as FFTW, except for the multidimensional
269FFT axis ordering: in FFTW dimensions are ordered with the decrease
270in consecutive elements stride, while VkFFT does the opposite - the
271first axis is the non-strided axis (the one that has elements located
272consecutively in memory with no gaps, usually named as the X-axis).
273So, in FFTW dimensions are specified as ZYX and in VkFFT as XYZ. This
274felt more logical to me - no matter if there are 1, 2, 3 or more dimensions,
275the user can always find the axis with the same stride at the same
276position. This choice doesn't require any modification in the user's
277data management - just provide the FFT dimensions in the reverse order
278to VkFFT. 
279
280The 1.3 version of VkFFT supports arbitrary number of dimensions,
281defined as VKFFT\_MAX\_FFT\_DIMENSIONS compile constant. VkFFT also
282supports two forms of batching: the number of coordinates and the
283number of systems. The choice of two distinct batching ways is made
284to support matrix-vector convolutions, where the kernel is presented
285as a matrix. Overall, the layout of VkFFT can be described as WHD+CN
286- width, height, depth, other dimensions, coordinate and number of
287systems (in order of increasing strides, starting with 1 for width).
288Often, the coordinate part of the layout is not used, so the main
289batching is done by specifying N.
290
291VkFFT assumes that complex numbers are stored consecutively in memory:
292RIRIRI... where R denotes the real part of the complex number and
293I denotes the imaginary part. There is no difference between using
294a float2/double2/half2 container or access memory as float/double/half/double-double
295as long as the byte order remains the same.
296
297This section and the next one will cover the basics of VkFFT data
298layouts and memory management. 
299
300\subsubsection{C2C transforms}
301
302The base FFT algorithm - C2C in VkFFT has the same definition as FFTW.
303Forward FFT has the exponent sign $-1$, while the inverse has the
304exponent sign $1$. By default, the inverse transform is unnormalized.
305$N_{x}N_{y}N_{z}$ complex numbers map to $N_{x}N_{y}N_{z}$ complex
306numbers and no additional padding is required. The resulting data
307order will be the same as in FFTW/cuFFT, unless special parameters
308are provided in configuration (see: advanced memory management)
309
310\subsubsection{R2C/C2R transforms}
311
312R2C/C2R transforms can be explained as C2C transforms with imaginary
313part set to zero. They exploit Hermitian symmetry of the result: $X_{k}=X_{N-k}^{*}$
314on the non-strided axis (the one that has elements located consecutively
315in memory with no gaps). This results in s reduction of required memory
316to store the complex result - we may only store $floor(\frac{N_{x}}{2})+1$
317complex numbers instead of $N_{x}$. However, this results in memory
318requirements mismatch between input and output in R2C: $floor(\frac{N_{x}}{2})+1$
319complex elements will require $N_{x}+2$ real numbers worth of memory
320for even $N_{x}$ and $N_{x}+1$ real numbers worth of memory for
321odd $N_{x}$. For C2R the situation is reversed. There are two approaches
322to this problem: pad each sequence of the non-strided axis with zeros
323to the required length or use out-of-place mode. More information
324on how to do this will be given in the next section.
325
326\subsubsection{R2R (DCT) transforms}
327
328R2R transforms in VkFFT are implemented in the form of Discrete cosine
329transforms and Discrete sine transforms of types I, II, III and IV.
330Their definitions and transforms results match FFTW:
331\begin{enumerate}
332\item DCT-I: $X_{k}=x_{0}+(-1)^{k}x_{N-1}+2\stackrel[n=1]{N-2}{\sum}x_{n}cos(\frac{\pi}{N-1}nk)$,
333inverse of DCT-I (itself)
334\item DCT-II: $X_{k}=2\stackrel[n=0]{N-1}{\sum}x_{n}cos(\frac{\pi}{N}(n+\frac{1}{2})k)$,
335inverse of DCT-III
336\item DCT-III: $X_{k}=x_{0}+2\stackrel[n=1]{N-1}{\sum}x_{n}cos(\frac{\pi}{N}n(k+\frac{1}{2}))$,
337inverse of DCT-II
338\item DCT-IV: $X_{k}=2\stackrel[n=0]{N-1}{\sum}x_{n}cos(\frac{\pi}{N}(n+\frac{1}{2})(k+\frac{1}{2}))$,
339inverse of DCT-IV (itself)
340\item DST-I: $X_{k}=2\stackrel[n=0]{N-1}{\sum}x_{n}sin(\frac{\pi}{N+1}(n+1)(k+1))$,
341inverse of DST-I (itself)
342\item DST-II: $X_{k}=2\stackrel[n=0]{N-1}{\sum}x_{n}sin(\frac{\pi}{N}(n+\frac{1}{2})(k+1))$,
343inverse of DST-III
344\item DST-III: $X_{k}=(-1)^{k}x_{N-1}+2\stackrel[n=0]{N-2}{\sum}x_{n}sin(\frac{\pi}{N}(n+1)(k+\frac{1}{2}))$,
345inverse of DST-II
346\item DST-IV: $X_{k}=2\stackrel[n=0]{N-1}{\sum}x_{n}sin(\frac{\pi}{N}(n+\frac{1}{2})(k+\frac{1}{2}))$,
347inverse of DST-IV (itself)
348\end{enumerate}
349R2R transforms are performed by redefinition of them to the C2C transforms
350(internal C2C sequence length can be different from the input R2R
351sequence length). R2R transform performs a one-to-one mapping between
352real numbers, so they don't require stride management, unlike R2C/C2R.
353
354\subsection{Memory management, data layouts for different transforms}
355
356\subsubsection{VkFFT buffers}
357
358VkFFT allows for explicit control over the data flow, which makes
359both in-place and out-of-place transforms possible. Buffers are passed
360to VkFFT as VkBuffer pointer in Vulkan, as double void pointers in
361CUDA/HIP/Level Zero, as cl\_mem pointer in OpenCL and as MTL::Buffer
362pointer in Metal. This is done to maintain a uniform data pattern
363because some of the buffers can be allocated automatically. 
364
365The main buffer is called buffer and it always has to be provided,
366either during the plan creation or when the plan is executed. All
367calculations are performed in this buffer and it is always overwritten.
368To do calculations out-of-place, VkFFT provides an option to specify
369inputBuffer/outputBuffer buffer. The logic behind their usage is fairly
370simple - the user specifies inputBuffer if the input data has to be
371read from a buffer, different from the main buffer. As the data is
372read only once and nothing is written back to the inputBuffer, this
373allows doing truly out-of-place transformations. The same logic applies
374to outputBuffer with the difference that it is responsible for the
375absolute last write of the VkFFT. It is possible to use all three
376buffers to create complex data management paths.
377
378It must be noted, that sometimes FFT can not be done inside one buffer
379(see: Four-Step FFT algorithm, Bluestein's algorithm). To compute
380FFT in these cases, there exists tempBuffer buffer and data is transferred
381between the main buffer and tempBuffer during the FFT execution. The
382ordering of transfers between the main buffer and tempBuffer is done
383in such a way, so the initial data read and final data write are obeying
384the configuration from the previous paragraph. Users can allocate
385tempBuffer themselves of some memory that does not have any useful
386information at the time of FFT execution (the tempBuffer size can
387depend on the configuration, so this is a rather advanced operation
388- read more in the advanced memory management section) or allow VkFFT
389to manage tempBuffer allocation itself (tempBuffer will be freed at
390the deleteVkFFT call).
391
392To compute convolutions and cross-correlations, a kernel buffer has
393to be specified. It must have the same layout as the result of the
394FFT transform.
395
396\subsubsection{VkFFT buffers strides. A special case of R2C/C2R transforms}
397
398To have better control of memory, the user can specify the strides
399between consecutive elements of different axes. The W (width) stride
400is fixed to be 1, so to achieve innermost batching, user needs to
401initialize an N+1 dimension FFT and omit the innermost dimension using
402omitDimension{[}0{]} = 1 parameter. N (number of systems) stride will
403be consecutive of C in memory if C is used, otherwise N will propagate
404the previous non-uniform stride multiplied by the corresponding axis
405length). Strides are specified not in bytes, but in the element type
406used - similar to the way how the user would access the corresponding
407element in the array. If all elements are consecutive in C2C, stride
408for H will be equal to the FFT length of W axis, stride for D will
409be multiplication of first two FFT axis lengths and so on, stride
410for C will be multiplication of all FFT axes lengths, etc. These are
411the default values of C2C and R2R strides if they are not explicitly
412specified.
413
414One of the main use-cases of strides comes to solve the R2C/C2R Hermitian
415symmetry H stride mismatch - for real space, it is equal to $N_{x}$
416real elements and for the frequency space it is equal to $floor(\frac{N_{x}}{2})+1$
417complex numbers. So, with strides it is possible to use a buffer,
418padded to $2\cdot(floor(\frac{N_{x}}{2})+1)$ real elements in H stride
419(all elements between $N_{x}$ and $2\cdot(floor(\frac{N_{x}}{2})+1)$
420will not be read so it does not matter what data is there before the
421write stage). All other strides are done as a multiplication between
422the previous stride and the number of elements in the previous axis.
423These are the default values of R2C/C2R strides if they are not explicitly
424specified.
425
426It is possible to specify separate sets of strides for all user-defined
427buffers: bufferStride for the main buffer, inputStride for input buffer,
428outputStride for output buffer (kernel stride is assumed to be the
429same as bufferStride, tempBuffer strides are configured automatically). 
430
431For an out-of-place R2C FFT, there is no need to pad buffer with real
432numbers, but user must specify H stride there (as it differs to default
433one) - $N_{x}$ real elements for real space and $floor(\frac{N_{x}}{2})+1$
434complex numbers for the frequency space. 
435
436An out-of-place C2R FFT is a more tricky transform. In the multidimensional
437case, the main buffer will be written to and read from multiple times.
438The intermediate stores have a complex layout, which requires more
439space than the output real layout, so in order not to modify the input
440data, there exist two options. First, pad the real data layout has
441to $2\cdot(floor(\frac{N_{x}}{2})+1)$ real elements in H stride (complex
442buffer will be used as inputBuffer, real buffer as buffer). Second,
443use the third buffer, so both input and output buffers have their
444original layouts (complex buffer will be used as inputBuffer, the
445main buffer for calculations is buffer and output real buffer as outputBuffer).
446If you use inverseReturnToInputBuffer option, where R2C is configured
447to read from input buffer and C2R is configured to write to the input
448buffer; C2R will modify the buffer it reads from in some cases (see
449issue \href{https://github.com/DTolm/VkFFT/issues/58\#issuecomment-1007205682}{\#58})
450
451By default, R2C/C2R will assume the complex-padded real strides in
452the in-place mode and non-padded real strides in out-of-place mode.
453
454\subsection{VkFFT algorithms}
455
456VkFFT implements a wide range of algorithms to compute different types
457of FFTs but all of them can be reduced to a mixed-radix Cooley-Tukey
458FFT algorithm in the Stockham autosort form. The main idea behind
459it is to decompose the sequence as a set of primes, for each of which
460FFT can be written down exactly. As of now, VkFFT has radix implementations
461for primes up to 13, so all C2C sequences decomposable into a multiplication
462of such primes will be done purely with the Stockham algorithm. Below
463additional algorithms and their use-cases are described.
464
465\subsubsection{Bluestein's algorithm}
466
467A complex algorithm that is used in cases where the sequence is not
468decomposable with implemented radix butterflies (currently - primes
469up to 13). It is derived by replacing $nk=\left(n^{2}+k^{2}-(n-k)^{2}\right)/2$
470in \ref{eq:dft}:
471
472\begin{align}
473X_{k} & =\left(e^{-\pi i\frac{k^{2}}{N}}\right)\stackrel[n=0]{N-1}{\sum}\left(x_{n}e^{-\pi i\frac{n^{2}}{N}}\right)\left(e^{\pi i\frac{\left(k-n\right)^{2}}{N}}\right)=b_{k}^{\ast}\stackrel[n=0]{N-1}{\sum}a_{n}b_{k-n}\label{eq:dft-1}\\
474a_{n} & =x_{n}b_{n}^{\ast}\\
475b_{n} & =e^{\pi i\frac{n^{2}}{N}}
476\end{align}
477
478Here FFT is represented as a convolution between two sequences: $a_{n}$
479and $b_{n}$, which can be performed by the means of convolution theorem:
480
481\begin{equation}
482F\{a\ast b\}=F\{a\}\cdot F\{b\}
483\end{equation}
484
485By padding $a_{n}$ and $b_{n}$ to a sequence length decomposable
486with implemented radix butterflies with a size of at least $2N-1$
487(because the length of $b_{n}$ is $2N-1$), we can perform FFT of
488any length. FFT of $b_{n}$ can be precomputed, so overall this algorithm
489requires at least 4x the computations and more memory transfers. This
490algorithm can be combined with all other algorithms implemented in
491VkFFT. If an FFT can not be done in a single upload, a tempBuffer
492has to be allocated (because the logical FFT buffer size is bigger
493than the original system).
494
495\subsubsection{The Four-Step FFT algorithm}
496
497GPUs and CPUs have a hierarchical memory model - the closer memory
498to the unit that performs the computations, the faster its speed and
499the lower the size. So it is advantageous to split FFTs, not to the
500lowest primes, but to some bigger multiplication of those primes,
501then upload this subsequence to the closest cache level to the cores
502and do the final prime split there. The absolute lowest level is the
503register file, however, it does not allow for thread communications
504outside the warp. For this purpose, modern GPUs employ shared memory
505- a fast memory with a bank structure that is visible to all threads
506in a thread block. The usual sizes of it change on a scale from 16KB
507to 192KB and it is often beneficial to use it fully. However, if the
508full sequence can not fit inside the shared memory, FFT has to be
509done in multiple uploads - with the Four Step FFT algorithm. The main
510idea behind it is to represent a big 1D sequence as a 2D (or 3D for
511the three-upload scheme) FFT - we first do FFT along the columns,
512then the rows, then transpose the result and multiply by a special
513set of phase vectors. Similar decomposition idea as the main Cooley-Tukey
514algorithm. However, performing transpositions in-place is a complicated
515task - especially for a non-trivial ratio between dimensions. It will
516also require an additional read/write stage, as it can not be merged
517with the last write of the FFT algorithm. The easiest and the most
518performant solution is to use a tempBuffer (it is the main reason
519for having this functionality, actually) and store intermediate FFT
520results out-of-place. This way the last transposition step can be
521merged with the write step, as we can overwrite the output buffer
522without losing data.
523
524To estimate if your sequence size is single upload or not, divide
525the amount of available shared memory (48KB - Nvidia GPUs with Vulkan/OpenCL
526API, 64KB - AMD GPUs, 100KB - Nvidia GPUs in CUDA API) by the complex
527size used for calculations (4 byte - half precision, 8 byte - single
528precision, 16 byte - double precision, 32 byte - double-double). For
52964KB of shared memory, we get 8192 as max single upload single-precision
530non-strided FFT, 4096 for double precision. For strided axes (H and
531D parts of the layout) these numbers have to be divided by 4 and 2
532respectively to achieve coalescing, resulting in 2048 length for single
533upload in both precisions. For more information on coalescing see:
534coalescing API reference.
535
536In the case of the Four-Step FFT algorithm, tempBuffer size has to
537be at least the same as the default main buffer size. It does not
538matter how many uploads are in the Four Step FFT algorithm - only
539a single tempBuffer is required. In this document, all systems that
540can fit in the shared memory entirely and be done without the Four
541Step FFT algorithm (and multiple uploads) are called single upload
542systems.
543
544If the last transposition is not required (the output data is allowed
545to be in not unshuffled form) it can be disabled during the configuration
546phase. This way tempBuffer will not be needed and all computations
547will be done in-place (unless Bluestein's algorithm is used). An example
548use-case of this is convolutions - if the kernel is computed with
549the same operation ordering, point-wise multiplication in the frequency
550domain is not dependent on the correct data ordering and the inverse
551FFT will restore the original layout.
552
553\subsubsection{R2C/C2R FFTs}
554
555A typical approach to a single upload R2C/C2R system is to just set
556the imaginary part to zero inside the shared memory and do a simple
557C2C transform. This doesn't affect the amount of memory transferred
558from VRAM and is not a bad approach as FFT is a memory-bound algorithm,
559however, this can be improved in multidimensional (in HDCN part of
560the layout) case by the composition of a single C2C sequence from
561two real sequences and some write for R2C/read for C2R post-processing.
562Both of these algorithms are implemented in VkFFT. Note, that R2C/C2R
563only affects the non-strided axis (W). All strided axes are still
564done as C2C.
565
566\subsubsection{R2C/C2R multi-upload FFT algorithm}
567
568For even sequences there exists an easy mapping between R2C/C2R FFTs
569and the C2C of half the size. In this case, all even indices (starting
570from 0) are read as the real values of a complex number and all odd
571indices are read as the imaginary values. This C2C sequence can be
572done with the help of the Four-Step FFT algorithm. When FFT is done,
573separate post-processing for R2C/pre-processing for C2R is applied.
574
575VkFFt also implements a general R2C/C2R algorithm that computes R2C
576as a C2C of the same length with imaginary part set to zero. The memory
577layout of it is optimized to reduce memory footprint.
578
579\subsubsection{R2R Discrete Cosine/Sine Transforms}
580
581There exist many different mappings between DCT and FFT. DSTs are
582reformulated as DCTs inside the VkFFT, so they use the same algorithms.
583As of now, VkFFT has the following algorithms implemented (both single
584and multiple uploads):
585\begin{itemize}
586\item DCT-I - mapping between R2R and C2C of the $2N-2$ length. For non-strided
587axis can use an optimization similar to the R2C/C2R multidimensional
588case (setting the imaginary part to the next FFT sequence).
589\item DCT-II/DCT-III - mapping between R2R and C2C of the same length. For
590non-strided axis can use an optimization similar to the R2C/C2R multidimensional
591case (setting the imaginary part to the next FFT sequence).
592\item DCT-IV - for even sizes, mapping between R2R and C2C sequence of half-length.
593For odd sizes mapping to the FFT of the same length (for non-strided
594axis can use an optimization similar to the R2C/C2R multidimensional
595case (setting the imaginary part to the next FFT sequence)).
596\end{itemize}
597The single upload versions (that can fit in shared memory) of these
598algorithms have all mappings done in shared memory of the compute
599unit. For multiple upload sequence sizes, special callback versions
600of these algorithms are created that work similar to callbacks in
601CUDA (though more sophisticated as these algorithms can use multiple
602input values). The callback functionality has not been yet exposed
603to the user for general applications and its design is open to discussion.
604
605\subsubsection{Register overutilization}
606
607Not an FFT algorithm by itself, but an optimization to do bigger sequences
608in a single upload instead of switching to the Four Step FFT algorithm.
609The main idea behind it is to use a register file (which is often
610bigger than the amount of shared memory) to store the sequence and
611use shared memory only as a communication buffer. This is useful in
612Vulkan and OpenCL APIs on Nvidia GPU, as they are only allowed to
613allocate 48KB of shared memory with a register file having the size
614of 256KB.
615
616\subsubsection{Zero padding}
617
618Not an FFT algorithm by itself, but a memory management optimization.
619If the user's system has parts that are known to be zero - for example,
620when an open system is modeled, to avoid a circular part of the FFT
621system has to be padded with zeros up to 2x in each direction. VkFFT
622can omit sequences full of zeros and don't perform the corresponding
623memory transfers and computations, as the output result will be zero.
624This way it is possible to get up to two times speed increase in the
6252D case and up to 3x increase in the 3D case. 
626
627\subsubsection{Convolution and cross-correlation support}
628
629With the help of the Convolution theorem, which states that the Fourier
630transform of a convolution is the pointwise product of signals Fourier
631transforms, it is possible to perform convolution with $NlogN$ complexity,
632compared to $N^{2}$ complexity of the simple multiplication approach.
633This is extremely useful for kernels spanning more than 50 elements
634in size. VkFFT can merge the last step FFT, kernel multiplication
635in the Fourier domain and the first step of inverse FFT to provide
636substantial memory transfer savings. Moreover, FFTs of big sequences
637can be performed without data reordering, which results in a better
638locality. 
639
640\subsection{VkFFT accuracy}
641
642To measure how VkFFT (single/double/half/double-double precision)
643results compare to cuFFT/rocFFT (single/double/half precision) and
644FFTW (double/quad precision), multiple sets of systems covering full
645supported C2C/R2C+C2R/R2R FFT range are filled with random complex
646data on the scale of {[}-1,1{]} and one transform was performed on
647each system. Samples 11(single), 12(double), 13(half), 14(non-power
648of 2 C2C, single), 15(R2C+C2R, single), 16(DCT-I/II/III/IV, single),
64917(DCT-I/II/III/IV, double), 18(non-power of 2 C2C, double), 19(double-double
650emulation of quad precision, C2C) are available in VkFFT Benchmark
651Suite to perform VkFFT verification on any of the target platforms.
652Overall, the Cooley-Tukey algorithm (Stockham autosort) exhibits logarithmic
653relative error scaling, similar to those of other GPU FFT libraries.
654Typically, the more computationally expensive algorithm is - the worse
655its precision is. So, Bluestein's algorithm has lower accuracy than
656Stockham autosort algorithm.
657
658Single precision in VkFFT supports two modes of calculation - by using
659the on-chip Special Function Units that can compute sines and cosines
660on the go or by using the precomputed on CPU look-up tables. For Nvidia
661and AMD GPUs, SFU provide great precision, while Intel iGPUs and mobile
662GPUs must use LUT to perform FFTs correctly.
663
664Double precision in VkFFT also supports two modes of calculation -
665by using polynomial sincos approximation and computing them on-chip
666or by using precomputed LUT as well. The second option is the better
667one, as polynomial sincos approximation is too compute-heavy for modern
668GPUs. It is selected by default on all devices.
669
670Half precision is supported in all backends. Half precision is implemented
671only as a memory trick - all on-chip computations are done in single
672precision. Half precision can use SFU or LUT as well.
673
674Double-double emulation of quad precision uses precomputed on CPU
675in quad precision twiddle factors and implements only additions and
676multiplications on GPU (for now).
677
678VkFFT also supports mixed-precision operations, where memory storing
679is done at lower precision, compared to the on-chip calculations.
680For example, it is possible to read data in single precision, do calculations
681in double and store data back in single precision. 
682
683\subsection{VkFFT additional memory allocations}
684
685In this section, all GPU memory allocations that are done by VkFFT
686are described. There are up to three situations when VkFFT allocates
687memory. All of the VkFFT allocated memory is freed at the deleteVkFFT
688call.
689
690\subsubsection{LUT allocations}
691
692This memory is used to store precomputed twiddle factors and phase
693vectors used during the computation. This buffer can have:
694\begin{itemize}
695\item twiddle factors for each radix stage of Stockham FFT calculation
696\item phase vectors used in the Four Step FFT algorithm between stages
697\item phase vectors used in DCT/DST-II/III/IV to perform a mapping between
698R2R and C2C
699\item phase vectors used in post-processing for R2C/pre-processing for C2R
700for even length sequences as C2C of half size
701\end{itemize}
702VkFFT manages LUT allocations by itself and they are performed during
703the initializeVkFFT call. LUT are allocated per axis, though some
704of them can be reused if the axes have the same LUT. Inverse and forward
705FFT plans share the same LUT (conjugation is performed on-chip).
706
707\subsubsection{The Four-Step FFT algorithm - tempBuffer allocation}
708
709To perform the merging of the transposition with the last upload of
710an axis, VkFFT requires additional memory to mimic an out-of-place
711execution. This memory is located in tempBuffer and has to be of at
712least the same size as the main buffer. It is possible for the users
713to allocate it themselves, though if this is not done, VkFFT can do
714the allocation automatically (the size of the tempBuffer will be the
715same as the main buffer, unless the logical dimensions of FFT are
716bigger than user-defined - then, it will allocate the system with
717the minimal size, that can cover maximal logical system size used
718in any of the axes - see next subsection).
719
720\subsubsection{Bluestein's buffers allocation}
721
722To do Bluestein's FFT algorithm, precomputed sequences $b_{n}=e^{\pi i\frac{n^{2}}{N}}$,
723$FFT(b_{n})$ and $iFFT(b_{n})$ are required. For each axis, they
724can be different and are computed separately (unless VkFFT can determine
725that they match, then the buffers are allocated only once). Notably,
726as Bluestein's algorithm pads the sequence length to at least $2N-1$,
727if it can not be done in a single upload and the Four Step algorithm
728has to be used, the intermediate storage required will be bigger than
729the main buffer size. In this case, tempBuffer must always be allocated.
730As the padded sequence can be different for each of the dimensions,
731the required size of the tempBuffer will also vary. VkFFT determines
732the biggest size needed among axes and allocated tempBuffer of this
733size.
734
735\subsection{VkFFT support for double-double emulation of quad precision}
736
737Since VkFFT 1.3.2 experimental support for double-double emulation
738of quad precision has been added. Double-double number is defined
739as an unevaluated sum of two double numbers, second one being on the
740order of \textasciitilde 1 ULP of the first one (like 1 and 1e-16).
741This boosts the significand from 53 to 106 bits and leaves the exponent
742the same (11bits). For example, true quad precision would have 15
743bits of exponent and 113 bits significand. The range of double-double
744stays the same as in double precision (1e308 vs 1e4932), while precision
745boosts from \textasciitilde 1e-16 to \textasciitilde 1e-32 (vs \textasciitilde 1e-34
746of true quad precision). The double-double format of VkFFT is equivalent
747to \_\_ibm128 type in gcc. VkFFT uses quadmath library to precompute
748twiddle factors and initialize kernels for double-double in the true
749quad precision. Currently, conversion between quad and double-double
750is only possible on CPU in true quad (GPU can only do operations on
751data in double-double format). This will be changed later.
752
753To enable double-double support, link against quadmath and set VkFFT\_use\_FP128\_double\_double
754compile flag to true.
755
756The performance impact is rather harsh - the code becomes compute-bound
757even on modern HPC clusters. The simple radix algorithms work well
758and are usable (\textasciitilde 2x impact compared to double precision),
759while Bluestein and big primes Rader algorithms incur a high toll
760on operations count. This can be improved in the future, but probably
761not to the extent of being VRAM bandwidth-bound on modern accelerators.
762
763The main usage for the double-double precision should be mixed-precision
764calculations, where most of the time is spent in regular FP64 and
765only some parts that hit precision boundaries are calculated in double-double.
766For example, in VkFFT it is possible to perform a double precision
767FFT with all on-chip calculations done in double-double. This way
768the final errors should be on the scale of 1 ULP.
769
770\newpage{}
771
772\section{Runtime code optimization platform\label{sec:Modern-GPU-architecture.}}
773
774\subsection{Platform for GPU code generation}
775
776While GPUs show extraordinary performance, they are harder to program
777for compared to regular CPUs. Firstly, the algorithms must be optimized
778for SIMT (single instruction, multiple threads) execution, which is
779the soul of the GPU model. Secondly, rapid GPU development makes all
780vendor architectures (Nvidia, AMD, Intel) largely different. Below
781we will list some examples:
782\begin{itemize}
783\item Shared memory size. If your code uses the full 64KB of shared memory
784on AMD MI250X, it won't be optimal on Nvidia H100 which has 256KB
785of it. The same goes for L2/L3 cache size.
786\item Warp size. If your code uses 32 core warps (usual on Nvidia), it will
787not work or work inefficiently for 64 core warps of AMD CDNA.
788\item Coalesced memory. For Nvidia and AMD we have to coalesce 32-byte memory
789requests, for Intel, it is equal to 64 bytes. Multiple of these requests
790are then combined into 128-byte transactions to the chip. However,
791this is a big simplification. There exist undocumented issues for
792Nvidia and AMD, when bandwidth drops when code tries to do distant,
793but coalesced memory accesses, i.e. data are still grouped in 32-byte
794transactions but target addresses with > 2\textasciicircum 18 bytes
795between them (and the bigger the distance - the bigger the drop).
796The load-store unit (LSU) can not group 32-byte transactions. It is
797possible to regain full bandwidth by switching to 128-byte memory
798coalescing on Nvidia, while on AMD memory management follows different
799rules and these requests just happen to hit the same physical memory
800pin and thus be serialized. All this information is usually never
801shared by vendors, so programmers have to find solutions by trial
802and error.
803\item Compute unit composition. Some compute units have special function
804units that can evaluate single precision sines and cosines in one
805cycle (AMD and Nvidia). On Intel GPUs, they are often imprecise. The
806ratio between FP32 and FP64 units also imposes limitations on the
807algorithm - compute units with low FP64 core count will benefit from
808data precomputation in the lookup tables more. Some compute units
809have tensor cores for accelerated matrix products.
810\item There are many other nuanced differences (like the number of supported
811by hardware queues/streams, support for CUDA MPS execution model,
812register spilling control) which result in some complicated kernels
813being unpredictable in performance before you try. So having an option
814to tweak some of its parameters loosely related to hardware is a huge
815benefit. 
816\end{itemize}
817This brings us to a big obstacle: all vendors have their own computing
818platforms. CUDA for Nvidia, HIP for AMD, Level Zero for Intel, Metal
819for Apple. To facilitate the development of code for all these different
820in details but similar in SIMD nature GPUs, I used all the knowledge
821obtained via numerous experiments with VkFFT to generalize GPU programming
822as much as possible - and create a unified platform for GPU code generation. 
823
824\subsection{Platform structure}
825
826The project structure is split into four main parts:
827\begin{itemize}
828\item Application manager. We use a container-based model of management
829- the user fills out the configuration struct and then initializes
830the application with only one initializer function. So this part of
831the platform performs initial configuration management, pass of the
832parameters to the corresponding to the particular subprogram plan
833initializer, binary load/store for future reuse and resources deallocation.
834Here we have application dispatch handlers, which abstract the actual
835application-dependent code dispatch handlers in the same way as we
836have one function for initialization.
837\item Plan manager. After configuration propagation, the plan manager performs
838extensive configuration of parameters for a particular task code generation.
839It also performs general API-dependent parameter initialization for
840supported backends. The plan manager also performs code compilation
841using supported by the target API runtime compiler (NVRTC by Nvidia
842CUDA, HIPRTC by AMD HIP, glslang by Vulkan, native OpenCL, clang and
843llvm-spirv for Intel Level Zero). It manages additional memory allocations
844and backend-specific memory management. Finally, it has plan-specific
845dispatch routines and a plan resource deallocation manager.
846\item Code manager. This part of the platform is solely responsible for
847GPU code generation. It takes a special input configuration structure
848created from user configuration and API-derived parameters and produces
849a char array containing code to be executed. The code manager has
850a block structure that developers can use. This allows reusing parts
851of code between kernels. The block structure has the following designations:
852\begin{itemize}
853\item Level 2 kernels: problem-specific kernels and layout configuration.
854These functions are called by the plan manager and they are intended
855to have a clear description of what is going on in the function. There
856is no pure code here - only calls to append lower-level functions
857code to the kernel code and additional inlining constants configuration
858that can be performed by the propagated from the plan manager information.
859This kernel also performs calls to additional kernel configuration
860routines like shared memory and register inlining inside a kernel
861and overall kernel decoration (like calls to inlining structure definitions,
862calls to kernel name inlining) - these routines are defined in lower
863kernels levels.
864\item Level 1 kernels: less abstract simple routine kernels, like matrix-vector
865products, copy kernels, radix components of FFT, read/write managers.
866All of them must have a specified structure so they can be reused,
867for example, considering all input data to be in shared memory with
868a specific layout - then level 2 kernels will have a simple job of
869providing data to level 1 kernels in a specified manner and get the
870output in an also specified manner.
871\item Level 0 kernels: memory management kernels. Here we have the absolute
872simplest kernel blocks, like memory data transfer request calls, synchronization,
873inlining of register/shared memory initialization code, etc. Many
874APIs have their own definitions for particular math operations, so
875we can define functions for inlining additions multiplications and
876other basic arithmetics here as well. The target of this level is
877to provide level 1 and 2 kernels with an easy way to reuse things
878that can be generalized between the widest range of math algorithms. 
879\end{itemize}
880All of the different level kernels have full access to the target
881GPU hardware parameters - hence (depending on the quality of implemented
882kernels) it is possible to autotune the algorithm at run-time and
883simplify the compiler job as much as possible. This involves loop
884unrolling, constants inlining, etc. Having an additional level (level
8851) dedicated to the simple algorithms allows for kernel merging. 
886\item Structs definitions. Here we define all structs used by the platform.
887It also contains some helper structs that can be used to manage GPU
888with different APIs and collect generated applications in a library
889struct for easier access through a map key (if the user's code uses
890many applications, this turns out to be extremely helpful).
891\end{itemize}
892
893\subsection{Container abstractions}
894
895The main design improvement that enables the platform functionality
896and greatly expands its usability are container abstractions. The
897code generator now operates on special data containers (implemented
898as C-unions), that can hold integer/float/complex numbers either as
899known during the plan creation values or as strings of variable names
900- no more sprintf calls with big chunks of unreadable code. 
901
902An example operation that uses containers is a MUL operation that
903performs a multiplication A equals B multiplied by C. If all containers
904have known values, A can be precomputed during plan creation. If A
905, B and C are, for example, register names, we print to the kernel
906an operation of multiplication. Each operation like MUL has its own
907representation for all supported APIs in the vkFFT\_MathUtils.h file.
908An important distinction is that it is not a full compiler, but a
909simple tool that unifies syntaxis of different APIs and supports JIT
910optimizations. However, as the code manager outputs code that resembles
911binary, one of the future exploration possibilities it may be interesting
912to try to make level 0 and 1 kernels output assembly without additional
913compilation by the plan manager. 
914
915Usage of container abstractions brings exciting opportunities to code
916creation. Behaving as multi-API templates it will be possible to implement
917double-double FP128 mathematics support on GPU without modifying any
918of the already written algorithm code. Another big benefit is automatic
919type casting between precisions and option to perform precomputation
920in higher precision than the GPU code executes in. 
921
922I have also explored other ways to implement these container abstractions
923- including switching to C++ from C99 and using templates and operator
924overloading, however this turned out to be just a syntactic sugar,
925as if it did not reduce number of lines of code and did not increase
926readibility. So the code is still C with almost instant compilations
927as a bonus. All this is subject to change in the future if people
928present convincing arguments. 
929
930VkFFT supports two base number modes (used for all FP calculations
931on CPU) - long double or quad (\_\_float128). The latter is needed
932to calculate the twiddle factors in double-double emulation of quad
933precision.
934
935\newpage{}
936
937\section{VkFFT API Reference}
938
939This section covers error codes, API functions that can be used by
940the user and configuration parameters.
941
942\subsection{Return value VkFFTResult}
943
944All VkFFT Library return values except for VKFFT\_SUCCESS are used
945in case of a failure and provide information on what has gone wrong.
946VkFFTResult is unified among different backends, though some of its
947values may not be used in specific backends. Possible return values
948of VkFFTResult are defined as following:
949
950\begin{mdframed}[backgroundcolor=bg]
951\begin{minted}[tabsize=4,obeytabs,breaklines]{C}
952typedef enum VkFFTResult { 	
953VKFFT_SUCCESS = 0,	// The VkFFT operation was successful
954VKFFT_ERROR_MALLOC_FAILED = 1,	// Some malloc call inside VkFFT has failed. Report this to the GitHub repo
955VKFFT_ERROR_INSUFFICIENT_CODE_BUFFER = 2,	// Generated kernel is bigger than default kernel array. Increase it with maxCodeLength parameter of configuration.
956VKFFT_ERROR_INSUFFICIENT_TEMP_BUFFER = 3,	// Temporary string used in kernel generation is bigger than default temporary string array. Increase it with maxTempLength parameter of configuration.
957VKFFT_ERROR_PLAN_NOT_INITIALIZED = 4,	// Code attempts to use uninitialized plan (it is zero inside VkFFTApplication)		
958VKFFT_ERROR_NULL_TEMP_PASSED = 5,	// Internal kernel generation error
959VKFFT_ERROR_MATH_FAILED = 6,	// Math instruction in code generator failed     
960VKFFT_ERROR_FFTdim_GT_MAX_FFT_DIMENSIONS = 7,	// User specified a number of dimensions higher than the code is compiled to handle with VKFFT_MAX_FFT_DIMENSIONS
961VKFFT_ERROR_NONZERO_APP_INITIALIZATION = 8,	// The app pointer is not pointing to the zero-filled memory block
962VKFFT_ERROR_INVALID_PHYSICAL_DEVICE = 1001,	// No physical device is provided (Vulkan API)
963VKFFT_ERROR_INVALID_DEVICE = 1002,	// No device is provided (All APIs)
964VKFFT_ERROR_INVALID_QUEUE = 1003,	// No queue is provided (Vulkan API)
965VKFFT_ERROR_INVALID_COMMAND_POOL = 1004,	// No command pool is provided (Vulkan API)
966VKFFT_ERROR_INVALID_FENCE = 1005,	// No fence is provided (Vulkan API)
967VKFFT_ERROR_ONLY_FORWARD_FFT_INITIALIZED = 1006,	// VkFFT tries to access inverse FFT plan, when appliction is created with makeForwardPlanOnly flag
968VKFFT_ERROR_ONLY_INVERSE_FFT_INITIALIZED = 1007,	// VkFFT tries to access forward FFT plan, when appliction is created with makeInversePlanOnly flag
969VKFFT_ERROR_INVALID_CONTEXT = 1008,	// No context is provided (OpenCL API)
970VKFFT_ERROR_INVALID_PLATFORM = 1009,	// No platform is provided (OpenCL API)
971VKFFT_ERROR_EMPTY_FILE = 1011,
972VKFFT_ERROR_EMPTY_FFTdim = 2001,	// Number of dimensions is not provided in the configuration
973VKFFT_ERROR_EMPTY_size = 2002,	// Array of dimensions is not provided in the configuration
974VKFFT_ERROR_EMPTY_bufferSize = 2003,	// Buffer size has to be provided during the application creation
975VKFFT_ERROR_EMPTY_buffer = 2004,	// Buffer has te be specified either at the application creation stage or during launch through VkFFTLaunchParams struct
976VKFFT_ERROR_EMPTY_tempBufferSize = 2005,	// Same error as VKFFT_ERROR_EMPTY_bufferSize if userTempBuffer is enabled
977VKFFT_ERROR_EMPTY_tempBuffer = 2006,	// Same error as VKFFT_ERROR_EMPTY_buffer if userTempBuffer is enabled
978VKFFT_ERROR_EMPTY_inputBufferSize = 2007,	// Same error as VKFFT_ERROR_EMPTY_bufferSize if isInputFormatted is enabled
979VKFFT_ERROR_EMPTY_inputBuffer = 2008,	// Same error as VKFFT_ERROR_EMPTY_buffer if isInputFormatted is enabled
980VKFFT_ERROR_EMPTY_outputBufferSize = 2009,	// Same error as VKFFT_ERROR_EMPTY_bufferSize if isOutputFormatted is enabled
981VKFFT_ERROR_EMPTY_outputBuffer = 2010,	// Same error as VKFFT_ERROR_EMPTY_buffer if isOutputFormatted is enabled
982VKFFT_ERROR_EMPTY_kernelSize = 2011,	// Same error as VKFFT_ERROR_EMPTY_bufferSize if performConvolution is enabled
983VKFFT_ERROR_EMPTY_kernel = 2012,	// Same error as VKFFT_ERROR_EMPTY_buffer if performConvolution is enabled
984VKFFT_ERROR_EMPTY_applicationString = 2013,	// loadApplicationString is zero when loadApplicationFromString is enabled
985VKFFT_ERROR_EMPRY_useCustomBluesteinPaddingPattern_arrays = 2014,	// pointers to primeSizes or paddedSizes arrays are zero when useCustomBluesteinPaddingPattern is enabled	
986VKFFT_ERROR_EMPTY_app = 2015,	// app pointer is zero
987VKFFT_ERROR_INVALID_user_tempBuffer_too_small = 2016,	// user provided tempBuffer is not sufficient for VkFFT intermediate calculations
988VKFFT_ERROR_UNSUPPORTED_RADIX = 3001,	// VkFFT has encountered unsupported radix (more than 13) during decomposition and Bluestein's FFT fallback did not work
989VKFFT_ERROR_UNSUPPORTED_FFT_LENGTH = 3002,	// VkFFT can not do this sequence length currently - it requires mor than three-upload Four step FFT
990VKFFT_ERROR_UNSUPPORTED_FFT_LENGTH_R2C = 3003,	// VkFFT can not do this sequence length currently - should no longer be thrown
991VKFFT_ERROR_UNSUPPORTED_FFT_LENGTH_R2R = 3004,	// VkFFT can not do this sequence length currently - should no longer be thrown
992VKFFT_ERROR_UNSUPPORTED_FFT_OMIT = 3005,	// VkFFT can not omit sequences in convolution calculations and R2C/C2R case
993VKFFT_ERROR_FAILED_TO_ALLOCATE = 4001,	// VkFFT failed to allocate GPU memory
994VKFFT_ERROR_FAILED_TO_MAP_MEMORY = 4002,	// 4002-4052 are handlers for errors of used backend APIs. They may indicate a driver failure. If they are thrown - report to the GitHub repo
995VKFFT_ERROR_FAILED_TO_ALLOCATE_COMMAND_BUFFERS = 4003,
996VKFFT_ERROR_FAILED_TO_BEGIN_COMMAND_BUFFER = 4004,
997VKFFT_ERROR_FAILED_TO_END_COMMAND_BUFFER = 4005,
998VKFFT_ERROR_FAILED_TO_SUBMIT_QUEUE = 4006,
999VKFFT_ERROR_FAILED_TO_WAIT_FOR_FENCES = 4007,
1000VKFFT_ERROR_FAILED_TO_RESET_FENCES = 4008,
1001VKFFT_ERROR_FAILED_TO_CREATE_DESCRIPTOR_POOL = 4009,
1002VKFFT_ERROR_FAILED_TO_CREATE_DESCRIPTOR_SET_LAYOUT = 4010,
1003VKFFT_ERROR_FAILED_TO_ALLOCATE_DESCRIPTOR_SETS = 4011,
1004VKFFT_ERROR_FAILED_TO_CREATE_PIPELINE_LAYOUT = 4012,
1005VKFFT_ERROR_FAILED_SHADER_PREPROCESS = 4013,
1006VKFFT_ERROR_FAILED_SHADER_PARSE = 4014,
1007VKFFT_ERROR_FAILED_SHADER_LINK = 4015,
1008VKFFT_ERROR_FAILED_SPIRV_GENERATE = 4016,
1009VKFFT_ERROR_FAILED_TO_CREATE_SHADER_MODULE = 4017,
1010VKFFT_ERROR_FAILED_TO_CREATE_INSTANCE = 4018,
1011VKFFT_ERROR_FAILED_TO_SETUP_DEBUG_MESSENGER = 4019,
1012VKFFT_ERROR_FAILED_TO_FIND_PHYSICAL_DEVICE = 4020,
1013VKFFT_ERROR_FAILED_TO_CREATE_DEVICE = 4021,
1014VKFFT_ERROR_FAILED_TO_CREATE_FENCE = 4022,
1015VKFFT_ERROR_FAILED_TO_CREATE_COMMAND_POOL = 4023,
1016VKFFT_ERROR_FAILED_TO_CREATE_BUFFER = 4024,
1017VKFFT_ERROR_FAILED_TO_ALLOCATE_MEMORY = 4025,
1018VKFFT_ERROR_FAILED_TO_BIND_BUFFER_MEMORY = 4026,
1019VKFFT_ERROR_FAILED_TO_FIND_MEMORY = 4027,
1020VKFFT_ERROR_FAILED_TO_SYNCHRONIZE = 4028,
1021VKFFT_ERROR_FAILED_TO_COPY = 4029,
1022VKFFT_ERROR_FAILED_TO_CREATE_PROGRAM = 4030,
1023VKFFT_ERROR_FAILED_TO_COMPILE_PROGRAM = 4031, 
1024VKFFT_ERROR_FAILED_TO_GET_CODE_SIZE = 4032,
1025VKFFT_ERROR_FAILED_TO_GET_CODE = 4033,
1026VKFFT_ERROR_FAILED_TO_DESTROY_PROGRAM = 4034,
1027VKFFT_ERROR_FAILED_TO_LOAD_MODULE = 4035,
1028VKFFT_ERROR_FAILED_TO_GET_FUNCTION = 4036,
1029VKFFT_ERROR_FAILED_TO_SET_DYNAMIC_SHARED_MEMORY = 4037,
1030VKFFT_ERROR_FAILED_TO_MODULE_GET_GLOBAL = 4038,
1031VKFFT_ERROR_FAILED_TO_LAUNCH_KERNEL = 4039,
1032VKFFT_ERROR_FAILED_TO_EVENT_RECORD = 4040,
1033VKFFT_ERROR_FAILED_TO_ADD_NAME_EXPRESSION = 4041,
1034VKFFT_ERROR_FAILED_TO_INITIALIZE = 4042,
1035VKFFT_ERROR_FAILED_TO_SET_DEVICE_ID = 4043,
1036VKFFT_ERROR_FAILED_TO_GET_DEVICE = 4044,
1037VKFFT_ERROR_FAILED_TO_CREATE_CONTEXT = 4045,
1038VKFFT_ERROR_FAILED_TO_CREATE_PIPELINE = 4046,
1039VKFFT_ERROR_FAILED_TO_SET_KERNEL_ARG = 4047,
1040VKFFT_ERROR_FAILED_TO_CREATE_COMMAND_QUEUE = 4048,
1041VKFFT_ERROR_FAILED_TO_RELEASE_COMMAND_QUEUE = 4049,
1042VKFFT_ERROR_FAILED_TO_ENUMERATE_DEVICES = 4050,
1043VKFFT_ERROR_FAILED_TO_GET_ATTRIBUTE = 4051,
1044VKFFT_ERROR_FAILED_TO_CREATE_EVENT = 4052,
1045VKFFT_ERROR_FAILED_TO_CREATE_COMMAND_LIST = 4053,
1046VKFFT_ERROR_FAILED_TO_DESTROY_COMMAND_LIST = 4054,
1047VKFFT_ERROR_FAILED_TO_SUBMIT_BARRIER = 4055
1048} VkFFTResult;
1049\end{minted}
1050\end{mdframed}
1051
1052\subsection{VkFFT application management functions}
1053
1054VkFFT has a unified plan management model - all different transform
1055types/ dimensionalities/ precision use the same calls with configuration
1056done through VkFFTConfiguration struct. This section shows how to
1057initialize/use/free VkFFT with this unified model, while the next
1058one will go into how to configure VkFFTConfiguration correctly. All
1059of the functions operate on VkFFTApplication and VkFFTConfiguration
1060assuming they have been zero-initialized before usage, so do not forget
1061to do this when initializing (otherwise VkFFT will throw an error):
1062
1063\begin{mdframed}[backgroundcolor=bg]
1064\begin{minted}[tabsize=4,obeytabs,breaklines]{C}
1065VkFFTConfiguration configuration = {};
1066VkFFTApplication app = {};
1067\end{minted}
1068\end{mdframed}
1069
1070\subsubsection{Function initializeVkFFT()}
1071
1072\begin{mdframed}[backgroundcolor=bg]
1073\begin{minted}[tabsize=4,obeytabs,breaklines]{C}
1074VkFFTResult initializeVkFFT(VkFFTApplication* app, VkFFTConfiguration inputLaunchConfiguration)
1075\end{minted}
1076\end{mdframed}
1077
1078Creates an FFT application (collection of forward and inverse plans).
1079As forward and inverse FFTs may have different memory layouts, can
1080have different normalizations - they are done as separate internal
1081plans inside VkFFTApplication. This call assumes the application to
1082be zero-initialized, so can be only done once on a particular application,
1083until it is deleted.
1084
1085If the initializeVkFFT call fails, it frees all allocated by VkFFT
1086CPU/GPU resources and sets the application to zero. VkFFTResult is
1087returned with an error code corresponding to what went wrong.
1088
1089In case of success, VkFFTApplication will contain initialized plans
1090with compiled kernels ready for execution with VKFFT\_SUCCESS returned.
1091
1092\subsubsection{Function VkFFTAppend()}
1093
1094\begin{mdframed}[backgroundcolor=bg]
1095\begin{minted}[tabsize=4,obeytabs,breaklines]{C}
1096VkFFTResult VkFFTAppend(VkFFTApplication* app, int inverse, VkFFTLaunchParams* launchParams)
1097\end{minted}
1098\end{mdframed}
1099
1100Performs FFT in the int inverse direction (-1 for forward FFT, 1 for
1101inverse FFT). FFT plans are selected from the VkFFTApplication collection
1102automatically. VkFFTApplication must be initialized with initializeVkFFT
1103call before. VkFFTLaunchParams struct allows for pre-launch configuration
1104of some parameters, namely:
1105\begin{itemize}
1106\item buffer - similar to how FFTW/cuFFT expects input/output data pointers
1107in {*}execC2C (and other) function calls, VkFFT allows specifying
1108memory used for computations at launch. It must have the same size/layout/strides
1109as defined during the application creation.
1110\item inputBuffer/outputBuffer/tempBuffer/kernel - other buffers can also
1111be specified at launch. In addition to them having the same size/layout/strides
1112as defined during the application creation, the application must be
1113created with flags enabling the corresponding buffer usage: isInputFormatted/isOutputFormatted/userTempBuffer/performConvolution
1114respectively.
1115\item bufferOffset/tempBufferOffset/inputBufferOffset/outputBufferOffset/kernelOffset
1116- specify if VkFFT has to offset the first element position inside
1117the corresponding buffer. In bytes. Default 0. specifyOffsetsAtLaunch
1118parameter must be enabled during the initializeVkFFT call before. 
1119\end{itemize}
1120Depending on the API, the execution model may vary and require additional
1121information at launch:
1122\begin{itemize}
1123\item Vulkan API: VkFFT appends a sequence of vkCmdDispatch calls to the
1124user-defined VkCommandBuffer (with respective push constants/descriptor
1125sets/pipelines/memory barriers bindings). VkCommandBuffer must be
1126provided as a pointer in VkFFTLaunchParams. VkCommandBuffer must be
1127in the writing stage, started with vkBeginCommandBuffer call. After
1128VkFFTAppend has finished, provided VkCommandBuffer will contain a
1129sequence of operations performing FFT. The first call of the sequence
1130has no input memory barrier, the last call has one, ensuring FFT has
1131finished execution.
1132\item CUDA/HIP API: if the user wants to use streams, they have to be provided
1133during the application configuration stage. VkFFTAppend performs a
1134series of cuLaunchKernel, which are sequential if appended to one
1135stream and synchronized if appended to multiple streams.
1136\item OpenCL API: similar to Vulkan, VkFFT appends a sequence of clEnqueueNDRangeKernel
1137calls to user-defined cl\_command\_queue. Currently, they are all
1138assumed to be sequential. cl\_command\_queue must be provided as a
1139pointer in VkFFTLaunchParams. 
1140\item Level Zero API: similar to Vulkan, VkFFT appends a sequence of zeCommandListAppendLaunchKernel
1141calls to user-defined command list ze\_command\_list\_handle\_t. They
1142have execution barriers between. ze\_command\_list\_handle\_t must
1143be provided as a pointer in VkFFTLaunchParams. 
1144\item Metal API: similar to Vulkan, VkFFT appends a sequence of dispatchThreads
1145calls to user-defined command encoder MTL::ComputeCommandEncoder.
1146MTL::ComputeCommandEncoder and its MTL::CommandBuffer must be provided
1147as a pointer in VkFFTLaunchParams. 
1148\end{itemize}
1149If VkFFT fails during the VkFFTAppend call, it will not free the application
1150and allocated there resources - use a separate call for that.
1151
1152\subsubsection{Function deleteVkFFT()}
1153
1154\begin{mdframed}[backgroundcolor=bg]
1155\begin{minted}[tabsize=4,obeytabs,breaklines]{C}
1156void deleteVkFFT(VkFFTApplication* app)
1157\end{minted}
1158\end{mdframed}
1159
1160Performs deallocation of resources used in the provided application.
1161Returns application to the zero-initialized state.
1162
1163\subsubsection{Function VkFFTGetVersion()}
1164
1165\begin{mdframed}[backgroundcolor=bg]
1166\begin{minted}[tabsize=4,obeytabs,breaklines]{C}
1167int VkFFTGetVersion()
1168\end{minted}
1169\end{mdframed}
1170
1171Returns the version of the VkFFT library in the X.XX.XX format (without
1172dots).
1173
1174\subsection{VkFFT configuration}
1175
1176This section will cover all the parameters that can be specified in
1177the VkFFTConfiguration struct. It will start with a short description
1178of the struct (intended to be used as a cheat sheet), then go for
1179each field in detail. Here pfUINT and pfINT are defined as uint64\_t
1180and int64\_t respectively.
1181
1182\begin{mdframed}[backgroundcolor=bg]
1183\begin{minted}[tabsize=4,obeytabs,breaklines]{C}
1184typedef struct {
1185// Required parameters: 	
1186pfUINT FFTdim;	// FFT dimensionality (1, 2 or 3)
1187pfUINT size[VKFFT_MAX_FFT_DIMENSIONS];	// WHD+ - system dimensions
1188#if(VKFFT_BACKEND==0) //Vulkan API
1189VkPhysicalDevice* physicalDevice;	// Pointer to Vulkan physical device, obtained from vkEnumeratePhysicalDevices
1190VkDevice* device;	// Pointer to Vulkan device, created with vkCreateDevice
1191VkQueue* queue;	// Pointer to Vulkan queue, created with vkGetDeviceQueue
1192VkCommandPool* commandPool;	// Pointer to Vulkan command pool, created with vkCreateCommandPool
1193VkFence* fence;	// Pointer to Vulkan fence, created with vkCreateFence
1194pfUINT isCompilerInitialized;	// Specify if glslang compiler has been intialized before (0 - off, 1 - on). Default 0 
1195#elif(VKFFT_BACKEND==1) //CUDA API
1196CUdevice* device;	// Pointer to CUDA device, obtained from cuDeviceGet
1197cudaStream_t* stream;	// Pointer to streams (can be more than 1), where to execute the kernels. Deafult 0
1198pfUINT num_streams;	// Try to submit CUDA kernels in multiple streams for asynchronous execution. Default 0, set to >=1 if you pass values in the stream pointer.  
1199#elif(VKFFT_BACKEND==2) //HIP API
1200hipDevice_t* device;	// Pointer to HIP device, obtained from hipDeviceGet
1201hipStream_t* stream;	// Pointer to streams (can be more than 1), where to execute the kernels. Deafult 0
1202pfUINT num_streams;	// Try to submit HIP kernels in multiple streams for asynchronous execution. Default 0, set to >=1 if you pass values in the stream pointer.
1203#elif(VKFFT_BACKEND==3) //OpenCL API
1204cl_platform_id* platform;	// NOT REQUIRED
1205cl_device_id* device;	// Pointer to OpenCL device, obtained from clGetDeviceIDs
1206cl_context* context;	// Pointer to OpenCL context, obtained from clCreateContext
1207#elif(VKFFT_BACKEND==4) //Level Zero API
1208ze_device_handle_t* device;	// Pointer to Level Zero device, obtained from zeDeviceGet
1209ze_context_handle_t* context;	// Pointer to Level Zero context, obtained from zeContextCreate
1210ze_command_queue_handle_t* commandQueue;	// Pointer to Level Zero command queue with compute and copy capabilities, obtained from zeCommandQueueCreate
1211uint32_t commandQueueID;	// ID of the commandQueue with compute and copy capabilities
1212#elif(VKFFT_BACKEND==5)
1213MTL::Device* device;	// Pointer to Metal device, obtained from MTL::CopyAllDevices
1214MTL::CommandQueue* queue;	// Pointer to Metal queue, obtained from device->newCommandQueue()
1215#endif
1216
1217// Data parameters (buffers can be specified at launch):
1218pfUINT userTempBuffer;	// Buffer allocated by app automatically if needed to reorder Four step algorithm. Setting to non zero value enables manual user allocation (0 - off, 1 - on)
1219pfUINT bufferNum;	// Multiple buffer sequence storage is Vulkan only. Default 1
1220pfUINT tempBufferNum;	// Multiple buffer sequence storage is Vulkan only. Default 1, buffer allocated by app automatically if needed to reorder Four step algorithm. Setting to non zero value enables manual user allocation 	
1221pfUINT inputBufferNum;	// Multiple buffer sequence storage is Vulkan only. Default 1, if isInputFormatted is enabled 
1222pfUINT outputBufferNum;	// Multiple buffer sequence storage is Vulkan only. Default 1, if isOutputFormatted is enabled 
1223pfUINT kernelNum;	// Multiple buffer sequence storage is Vulkan only. Default 1, if performConvolution is enabled
1224pfUINT* bufferSize;	// Array of buffers sizes in bytes
1225pfUINT* tempBufferSize;	// Array of temp buffers sizes in bytes. Default set to bufferSize sum, buffer allocated by app automatically if needed to reorder Four step algorithm. Setting to non zero value enables manual user allocation 
1226pfUINT* inputBufferSize;	// Array of input buffers sizes in bytes, if isInputFormatted is enabled
1227pfUINT* outputBufferSize;	// Array of output buffers sizes in bytes, if isOutputFormatted is enabled
1228pfUINT* kernelSize;	// Array of kernel buffers sizes in bytes, if performConvolution is enabled
1229#if(VKFFT_BACKEND==0) //Vulkan API
1230VkBuffer* buffer;	// Pointer to array of buffers (or one buffer) used for computations
1231VkBuffer* tempBuffer;	// Needed if reorderFourStep is enabled to transpose the array. Same sum size or bigger as buffer (can be split in multiple). Default 0. Setting to non zero value enables manual user allocation
1232VkBuffer* inputBuffer;	// Pointer to array of input buffers (or one buffer) used to read data from if isInputFormatted is enabled
1233VkBuffer* outputBuffer;	// Pointer to array of output buffers (or one buffer) used to write data to if isOutputFormatted is enabled
1234VkBuffer* kernel;	// Pointer to array of kernel buffers (or one buffer) used to read kernel data from if performConvolution is enabled
1235#elif(VKFFT_BACKEND==1) //CUDA API
1236void** buffer;	// Pointer to device buffer used for computations
1237void** tempBuffer;	// Needed if reorderFourStep is enabled to transpose the array. Same size as buffer. Default 0. Setting to non zero value enables manual user allocation 
1238void** inputBuffer;	// Pointer to device buffer used to read data from if isInputFormatted is enabled
1239void** outputBuffer;	// Pointer to device buffer used to write data to if isOutputFormatted is enabled
1240void** kernel;	// Pointer to device buffer used to read kernel data from if performConvolution is enabled 
1241#elif(VKFFT_BACKEND==2) //HIP API
1242void** buffer;	// Pointer to device buffer used for computations
1243void** tempBuffer;	// Needed if reorderFourStep is enabled to transpose the array. Same size as buffer. Default 0. Setting to non zero value enables manual user allocation
1244void** inputBuffer;	// Pointer to device buffer used to read data from if isInputFormatted is enabled
1245void** outputBuffer;	// Pointer to device buffer used to write data to if isOutputFormatted is enabled
1246void** kernel;	// Pointer to device buffer used to read kernel data from if performConvolution is enabled 
1247#elif(VKFFT_BACKEND==3) //OpenCL API
1248cl_mem* buffer;	// Pointer to device buffer used for computations
1249cl_mem* tempBuffer;	// Needed if reorderFourStep is enabled to transpose the array. Same size as buffer. Default 0. Setting to non zero value enables manual user allocation
1250cl_mem* inputBuffer;	// Pointer to device buffer used to read data from if isInputFormatted is enabled
1251cl_mem* outputBuffer;	// Pointer to device buffer used to write data to if isOutputFormatted is enabled
1252cl_mem* kernel;	// Pointer to device buffer used to read kernel data from if performConvolution is enabled
1253#elif(VKFFT_BACKEND==4)
1254void** buffer;	// Pointer to device buffer used for computations
1255void** tempBuffer;	// Needed if reorderFourStep is enabled to transpose the array. Same size as buffer. Default 0. Setting to non zero value enables manual user allocation
1256void** inputBuffer;	// Pointer to device buffer used to read data from if isInputFormatted is enabled
1257void** outputBuffer;	// Pointer to device buffer used to read data from if isOutputFormatted is enabled
1258void** kernel;	// Pointer to device buffer used to read kernel data from if performConvolution is enabled
1259#elif(VKFFT_BACKEND==5)
1260MTL::Buffer** buffer;	// Pointer to device buffer used for computations
1261MTL::Buffer** tempBuffer;	// Needed if reorderFourStep is enabled to transpose the array. Same size as buffer. Default 0. Setting to non zero value enables manual user allocation
1262MTL::Buffer** inputBuffer;	// Pointer to device buffer used to read data from if isInputFormatted is enabled
1263MTL::Buffer** outputBuffer;	// Pointer to device buffer used to read data from if isOutputFormatted is enabled
1264MTL::Buffer** kernel;	// Pointer to device buffer used to read kernel data from if performConvolution is enabled
1265#endif
1266pfUINT bufferOffset;	// Specify if VkFFT has to offset the first element position inside the buffer. In bytes. Default 0
1267pfUINT tempBufferOffset;	// Specify if VkFFT has to offset the first element position inside the temp buffer. In bytes. Default 0
1268pfUINT inputBufferOffset;	// Specify if VkFFT has to offset the first element position inside the input buffer. In bytes. Default 0
1269pfUINT outputBufferOffset;	// Specify if VkFFT has to offset the first element position inside the output buffer. In bytes. Default 0
1270pfUINT kernelOffset;	// Specify if VkFFT has to offset the first element position inside the kernel. In bytes. Default 0
1271pfUINT specifyOffsetsAtLaunch;	// Specify if offsets will be selected with launch parameters VkFFTLaunchParams (0 - off, 1 - on). Default 0
1272
1273// Optional: (default 0 if not stated otherwise)
1274pfUINT coalescedMemory;	// In bytes, for Nvidia and AMD is equal to 32, Intel is equal 64, scaled for half precision. Going to work regardless, but if specified by user correctly, the performance will be higher.
1275pfUINT aimThreads;	// Aim at this many threads per block. Default 128
1276pfUINT numSharedBanks;	// How many banks shared memory has. Default 32
1277pfUINT inverseReturnToInputBuffer;	// return data to the input buffer in inverse transform (0 - off, 1 - on). isInputFormatted must be enabled
1278pfUINT numberBatches;	// N - used to perform multiple batches of initial data. Default 1
1279pfUINT useUint64;	// Use 64-bit addressing mode in generated kernels
1280pfUINT omitDimension[VKFFT_MAX_FFT_DIMENSIONS];	// Disable FFT for this dimension (0 - FFT enabled, 1 - FFT disabled). Default 0. Doesn't work for R2C first axis for now. Doesn't work with convolutions.
1281int performBandwidthBoost; // Try to reduce coalsesced number by a factor of X to get bigger sequence in one upload for strided axes. Default: -1 for DCT/DST, 2 for Bluestein's algorithm (or -1 if DCT/DST), 0 otherwise  
1282
1283pfUINT doublePrecision;	// Perform calculations in double precision (0 - off, 1 - on).
1284pfUINT quadDoubleDoublePrecision; // Perform calculations in double-double emulation of quad precision (0 - off, 1 - on).
1285pfUINT quadDoubleDoublePrecisionDoubleMemory; // Perform calculations in double-double emulation of quad precision, while all memory storage is done in FP64.
1286pfUINT halfPrecision;	// Perform calculations in half precision (0 - off, 1 - on)
1287pfUINT halfPrecisionMemoryOnly;	// Use half precision only as input/output buffer. Input/Output have to be allocated as half, buffer/tempBuffer have to be allocated as float (out-of-place mode only). Specify isInputFormatted and isOutputFormatted to use (0 - off, 1 - on)
1288pfUINT doublePrecisionFloatMemory;	// Use FP64 precision for all calculations, while all memory storage is done in FP32.
1289
1290pfUINT performR2C;	// Perform R2C/C2R decomposition (0 - off, 1 - on)
1291pfUINT performDCT;	// Perform DCT transformation (X - DCT type, 1-4)
1292pfUINT performDST;	// Perform DST transformation (X - DST type, 1-4)
1293pfUINT disableMergeSequencesR2C;	// Disable merging of two real sequences to reduce calculations (0 - off, 1 - on)
1294pfUINT forceCallbackVersionRealTransforms;	// Force callback version of R2C and R2R algorithms for all usecases (0 - off, 1 - on) 
1295
1296pfUINT normalize;	// Normalize inverse transform (0 - off, 1 - on)
1297pfUINT disableReorderFourStep;	// Disables unshuffling of Four step algorithm. Requires tempbuffer allocation (0 - off, 1 - on)
1298pfINT useLUT;	// Switches from calculating sincos to using precomputed LUT tables (0 - off, 1 - on). Configured by initialization routine
1299pfINT useLUT_4step; // Switches from calculating sincos to using precomputed LUT tables for intermediate roots of 1 in the Four-step FFT algorithm. (-1 - off, 0 - auto, 1 - on). Configured by initialization routine
1300pfUINT makeForwardPlanOnly;	// Generate code only for forward FFT (0 - off, 1 - on)
1301pfUINT makeInversePlanOnly;	// Generate code only for inverse FFT (0 - off, 1 - on)
1302pfUINT bufferStride[VKFFT_MAX_FFT_DIMENSIONS];	// Buffer strides - default set to x - x*y - x*y*z values
1303pfUINT isInputFormatted;	// Specify if input buffer is padded - 0 - padded, 1 - not padded. For example if it is not padded for R2C if out-of-place mode is selected (only if numberBatches==1 and numberKernels==1)
1304pfUINT isOutputFormatted;	// Specify if output buffer is padded - 0 - padded, 1 - not padded. For example if it is not padded for R2C if out-of-place mode is selected (only if numberBatches==1 and numberKernels==1)
1305pfUINT inputBufferStride[VKFFT_MAX_FFT_DIMENSIONS];	// Input buffer strides. Used if isInputFormatted is enabled. Default set to bufferStride values
1306pfUINT outputBufferStride[VKFFT_MAX_FFT_DIMENSIONS];	// Output buffer strides. Used if isInputFormatted is enabled. Default set to bufferStride values
1307pfUINT swapTo2Stage4Step; // Specify at which number to switch from 1 upload to 2 upload 4-step FFT, in case if making max sequence size lower than coalesced sequence helps to combat TLB misses. Default 0 - disabled. 	
1308pfUINT swapTo3Stage4Step;	// Specify at which power of 2 to switch from 2 upload to 3 upload 4-step FFT, in case if making max sequence size lower than coalesced sequence helps to combat TLB misses. Default 0 - disabled. Must be at least 17
1309pfUINT considerAllAxesStrided;	// Will create plan for non-strided axis similar as a strided axis - used with disableReorderFourStep to get the same layout for Bluestein kernel (0 - off, 1 - on)
1310
1311pfUINT keepShaderCode;	// Will keep shader code and print all executed shaders during the plan execution in order (0 - off, 1 - on)
1312pfUINT printMemoryLayout;	// Will print order of buffers used in shaders (0 - off, 1 - on) 
1313
1314pfUINT saveApplicationToString;	// Will save all compiled binaries to VkFFTApplication.saveApplicationString (will be allocated by VkFFT, deallocated with deleteVkFFT call). VkFFTApplication.applicationStringSize will contain size of binary in bytes. Currently disabled in Metal backend. (0 - off, 1 - on)
1315pfUINT loadApplicationFromString;	// Will load all binaries from loadApplicationString instead of recompiling them (must be allocated by user, must contain what saveApplicationToString call generated previously in VkFFTApplication.saveApplicationString). Currently disabled in Metal backend. (0 - off, 1 - on). Mutually exclusive with saveApplicationToString
1316void* loadApplicationString;	// Memory binary array through which user can load VkFFT binaries, must be provided by user if loadApplicationFromString = 1. Use rb/wb flags to load/save.
1317
1318pfUINT disableSetLocale;	// disables all VkFFT attempts to set locale to C - user must ensure that VkFFT has C locale during the plan initialization. This option is needed for multithreading. Default 0. 
1319
1320// Optional Bluestein optimizations: (default 0 if not stated otherwise)
1321pfUINT fixMaxRadixBluestein;	// controls the padding of sequences in Bluestein convolution. If specified, padded sequence will be made of up to fixMaxRadixBluestein primes. Default: 2 for CUDA and Vulkan/OpenCL/HIP up to 1048576 combined dimension FFT system, 7 for Vulkan/OpenCL/HIP past after. Min = 2, Max = 13.
1322pfUINT forceBluesteinSequenceSize;	// force the sequence size to pad to in Bluestein's algorithm. Must be at least 2*N-1 and decomposable with primes 2-13.
1323pfUINT useCustomBluesteinPaddingPattern;	// force the sequence sizes to pad to in Bluestein's algorithm, but on a range. This number specifies the number of elements in primeSizes and in paddedSizes arrays. primeSizes - array of non-decomposable as radix scheme sizes - 17, 23, 31 etc. paddedSizes - array of lengths to pad to. paddedSizes[i] will be the padding size for all non-decomposable sequences from primeSizes[i] to primeSizes[i+1] (will use default scheme after last one) - 42, 60, 64 for primeSizes before and 37+ will use default scheme (for example). Default is vendor and API-based specified in autoCustomBluesteinPaddingPattern.
1324pfUINT* primeSizes;	// described in useCustomBluesteinPaddingPattern
1325pfUINT* paddedSizes;	// described in useCustomBluesteinPaddingPattern
1326
1327pfUINT fixMinRaderPrimeMult;	// start direct multiplication Rader's algorithm for radix primes from this number. This means that VkFFT will inline custom Rader kernels if sequence is divisible by these primes. Default is 17, as VkFFT has kernels for 2-13. If you make it less than 13, VkFFT will switch from these kernels to Rader.
1328pfUINT fixMaxRaderPrimeMult;	// switch from Mult Rader's algorithm for radix primes from this number. Current limitation for Rader is maxThreadNum/2+1, realistically you would want to switch somewhere on 30-100 range. Default is vendor-specific (currently ~40)
1329
1330pfUINT fixMinRaderPrimeFFT;	// start FFT convolution version of Rader for radix primes from this number. Better than direct multiplication version for almost all primes (except small ones, like 17-23 on some GPUs). Must be bigger or equal to fixMinRaderPrimeMult. Deafult 29 on AMD and 17 on other GPUs. 
1331pfUINT fixMaxRaderPrimeFFT;	// switch to Bluestein's algorithm for radix primes from this number. Switch may happen earlier if prime can't fit in shared memory. Default is 16384, which is bigger than most current GPU's shared memory.
1332
1333// Optional zero padding control parameters: (default 0 if not stated otherwise)
1334pfUINT performZeropadding[VKFFT_MAX_FFT_DIMENSIONS];	// Don't read some data/perform computations if some input sequences are zeropadded for each axis (0 - off, 1 - on)
1335pfUINT fft_zeropad_left[VKFFT_MAX_FFT_DIMENSIONS];	// Specify start boundary of zero block in the system for each axis
1336pfUINT fft_zeropad_right[VKFFT_MAX_FFT_DIMENSIONS];	// Specify end boundary of zero block in the system for each axis
1337pfUINT frequencyZeroPadding;	// Set to 1 if zeropadding of frequency domain, default 0 - spatial zeropadding
1338
1339// Optional convolution control parameters: (default 0 if not stated otherwise)
1340pfUINT performConvolution;	// Perform convolution in this application (0 - off, 1 - on). Disables reorderFourStep parameter
1341pfUINT coordinateFeatures;	// C - coordinate, or dimension of features vector. In matrix convolution - size of a vector
1342pfUINT matrixConvolution;	// If equal to 2 perform 2x2, if equal to 3 perform 3x3 matrix-vector convolution. Overrides coordinateFeatures
1343pfUINT symmetricKernel;	// Specify if kernel in 2x2 or 3x3 matrix convolution is symmetric
1344pfUINT numberKernels;	// N - only used in convolution step - specify how many kernels were initialized before. Expands one input to multiple (batched) output
1345pfUINT kernelConvolution;	// Specify if this application is used to create kernel for convolution, so it has the same properties. performConvolution has to be set to 0 for kernel creation
1346
1347// Register overutilization (experimental): (default 0 if not stated otherwise)
1348pfUINT registerBoost;	// Specify if register file size is bigger than shared memory and can be used to extend it X times (on Nvidia 256KB register file can be used instead of 32KB of shared memory, set this constant to 4 to emulate 128KB of shared memory). Defaults: Nvidia - 4 in Vulkan/OpenCL, 1 in CUDA backend; AMD - 2 if shared memory >= 64KB, else 4 in Vulkan/OpenCL backend, 1 in HIP backend; Intel - 1 if shared memory >= 64KB, else 2 in Vulkan/OpenCL/Level Zero backends, 1 in Metal; Default 1
1349pfUINT registerBoostNonPow2;	// Specify if register overutilization should be used on non power of 2 sequences (0 - off, 1 - on)
1350pfUINT registerBoost4Step;	// Specify if register file overutilization should be used in big sequences (>2^14), same definition as registerBoost. Default 1
1351
1352//not used techniques:
1353pfUINT devicePageSize;	// In KB, the size of a page on the GPU. Setting to 0 disables local buffer split in pages
1354pfUINT localPageSize;	// In KB, the size to split page into if sequence spans multiple devicePageSize pages
1355
1356// Automatically filled based on device info (still can be reconfigured by user):
1357pfUINT computeCapabilityMajor;	// CUDA/HIP compute capability of the device
1358pfUINT computeCapabilityMinor;	// CUDA/HIP compute capability of the device 	
1359pfUINT maxComputeWorkGroupCount[VKFFT_MAX_FFT_DIMENSIONS];	// maxComputeWorkGroupCount from VkPhysicalDeviceLimits
1360pfUINT maxComputeWorkGroupSize[VKFFT_MAX_FFT_DIMENSIONS];	// maxComputeWorkGroupCount from VkPhysicalDeviceLimits
1361pfUINT maxThreadsNum;	// Max number of threads from VkPhysicalDeviceLimits
1362pfUINT sharedMemorySizeStatic;	// Available for static allocation shared memory size, in bytes
1363pfUINT sharedMemorySize;	// Available for allocation shared memory size, in bytes
1364pfUINT sharedMemorySizePow2;	// Power of 2 which is less or equal to sharedMemorySize, in bytes
1365pfUINT warpSize;	// Number of threads per warp/wavefront.
1366pfUINT halfThreads;	// Intel fix
1367pfUINT allocateTempBuffer;	// Buffer allocated by app automatically if needed to reorder Four step algorithm. Parameter to check if it has been allocated
1368pfUINT reorderFourStep;	// Unshuffle Four step algorithm. Requires tempbuffer allocation (0 - off, 1 - on). Default 1.
1369pfINT maxCodeLength;	// Specify how big can be buffer used for code generation (in char). Default 1000000 chars. 
1370pfINT maxTempLength;	// Specify how big can be buffer used for intermediate string sprintfs be (in char). Default 5000 chars. If code segfaults for some reason - try increasing this number.
1371pfUINT autoCustomBluesteinPaddingPattern; // default value for useCustomBluesteinPaddingPattern
1372pfUINT useRaderUintLUT; // allocate additional LUT to store g_pow
1373pfUINT vendorID; // vendorID 0x10DE - NVIDIA, 0x8086 - Intel, 0x1002 - AMD, etc
1374#if(VKFFT_BACKEND==0) //Vulkan API
1375VkDeviceMemory tempBufferDeviceMemory;	// Filled at app creation
1376VkCommandBuffer* commandBuffer;	// Filled at app execution
1377VkMemoryBarrier* memory_barrier;	// Filled at app creation
1378#elif(VKFFT_BACKEND==1) //CUDA API
1379cudaEvent_t* stream_event;	// Filled at app creation
1380pfUINT streamCounter;	// Filled at app creation
1381pfUINT streamID;	// Filled at app creation
1382#elif(VKFFT_BACKEND==2) //HIP API
1383hipEvent_t* stream_event;	// Filled at app creation
1384pfUINT streamCounter;	// Filled at app creation
1385pfUINT streamID;	// Filled at app creation
1386#elif(VKFFT_BACKEND==3) //OpenCL API
1387cl_command_queue* commandQueue;	// Filled at app creation
1388#elif(VKFFT_BACKEND==4)
1389ze_command_list_handle_t* commandList;	// Filled at app creation
1390#elif(VKFFT_BACKEND==5)
1391MTL::CommandBuffer* commandBuffer;	// Filled at app execution
1392MTL::ComputeCommandEncoder* commandEncoder;	// Filled at app execution
1393#endif
1394} VkFFTConfiguration;
1395\end{minted}
1396\end{mdframed}
1397
1398\subsubsection{Driver API parameters}
1399
1400In order to work, VkFFT needs some structures that are provided by
1401the driver. They are backend API-dependent. VkFFT will return corresponding
1402VkFFTResult if one of these structures are not provided (value equal
1403to zero) unless it is stated that there is a default value assigned.
1404VkFFT will not modify provided values directly.
1405
1406Vulkan API will need the following information:
1407\begin{itemize}
1408\item VkPhysicalDevice{*} physicalDevice - Pointer to Vulkan physical device,
1409obtained from vkEnumeratePhysicalDevices()
1410\item VkDevice{*} device - Pointer to Vulkan device, created with vkCreateDevice()
1411\item VkQueue{*} queue - Pointer to Vulkan queue, created with vkGetDeviceQueue()
1412\item VkCommandPool{*} commandPool - Pointer to Vulkan command pool, created
1413with vkCreateCommandPool()
1414\item VkFence{*} fence - Pointer to Vulkan fence, created with vkCreateFence()
1415\item uint64\_t isCompilerInitialized - Specify if glslang compiler has
1416been intialized before (0 - off, 1 - on). Default 0 - VkFFT will call
1417glslang\_initialize\_process() at initializeVkFFT() and glslang\_finialize\_process()
1418at deleteVkFFT() calls.
1419\end{itemize}
1420CUDA API will need the following information:
1421\begin{itemize}
1422\item CUdevice{*} device - Pointer to CUDA device, obtained from cuDeviceGet()
1423\item cudaStream\_t{*} stream - Pointer to streams (can be more than 1),
1424where to execute the kernels. Default 0. Streams must be associated
1425with the provided device. There is no real benefit in having more
1426than one, however. 
1427\item uint64\_t num\_streams - Try to submit CUDA kernels in multiple streams
1428for asynchronous execution. Default 0, set to >=1 if you pass values
1429in the stream pointer. 
1430\end{itemize}
1431HIP API will need the following information:
1432\begin{itemize}
1433\item hipDevice\_t{*} device - Pointer to HIP device, obtained from hipDeviceGet()
1434\item hipStream\_t{*} stream - Pointer to streams (can be more than 1),
1435where to execute the kernels. Default 0. Streams must be associated
1436with the provided device. There is no real benefit in having more
1437than one, however. 
1438\item uint64\_t num\_streams - Try to submit HIP kernels in multiple streams
1439for asynchronous execution. Default 0, set to >=1 if you pass values
1440in the stream pointer.  
1441\end{itemize}
1442OpenCL API will need the following information:
1443\begin{itemize}
1444\item cl\_device\_id{*} device - Pointer to OpenCL device, obtained from
1445clGetDeviceIDs()
1446\item cl\_context{*} context - Pointer to OpenCL context, obtained from
1447clCreateContext()
1448\end{itemize}
1449Level Zero API will need the following information:
1450\begin{itemize}
1451\item ze\_device\_handle\_t{*} device - Pointer to Level Zero device, obtained
1452from zeDeviceGet()
1453\item ze\_context\_handle\_t{*} context - Pointer to Level Zero context,
1454obtained from zeContextGet()
1455\item ze\_command\_queue\_handle\_t{*} commandQueue - Pointer to Level Zero
1456command queuewith compute and copy capabilities, obtained from zeCommandQueueCreate()
1457\item uint32\_t commandQueueID - ID of the commandQueue with compute and
1458copy capabilities
1459\end{itemize}
1460Metal API will need the following information:
1461\begin{itemize}
1462\item MTL::Device{*} device - Pointer to Metal device, obtained from MTL::CopyAllDevices
1463\item MTL::CommandQueue{*} queue - Pointer to Metal queue, obtained from
1464device->newCommandQueue()
1465\end{itemize}
1466
1467\subsubsection{Memory management parameters}
1468
1469There are five buffer types user can provide to VkFFT: 
1470\begin{itemize}
1471\item the main buffer (buffer)
1472\item temporary buffer used for calculations requiring out-of-place writes
1473(tempBuffer)
1474\item separate input buffer, from which initial read is performed (inputBuffer)
1475\item separate output buffer, to which final write is performed (outputBuffer)
1476\item kernel buffer, used for calculation of convolutions and cross-correlations
1477(kernel)
1478\end{itemize}
1479These buffers must be passed by a pointer: in Vulkan API they are
1480provided as VkBuffer{*}, in CUDA, HIP and Level Zero they are provided
1481as void{*}{*}, in OpenCL they are provided as cl\_mem{*}, in Metal
1482they are provided as MTL::Buffer{*}. Even though the underlying structure
1483(VkBuffer, void{*}, cl\_mem, MTL::Buffer{*}) is not a memory but just
1484a number that the driver can use to access corresponding allocated
1485memory on the GPU, passing them by a pointer allows for the user to
1486query multiple GPU allocated buffers for VkFFT to use. Currently,
1487it is only supported in Vulkan API - each of five buffer types can
1488be made out of multiple separate memory allocations. For example,
1489it is possible to combine multiple small unused at the point of FFT
1490calculation buffers to form a tempBuffer. This option also allows
1491Vulkan API to overcome the limit of 4GB for a single memory allocation
1492- due to the fact that Vulkan can only use 32-bit numbers for addressing
1493(other APIs support 64-bit addressing). 
1494
1495To use the buffers other than the main buffer, the user has to specify
1496this in configuration at the application creation stage (set to zero
1497by default, optional parameters): 
1498\begin{itemize}
1499\item uint64\_t userTempBuffer - enables manual temporary buffer allocation
1500(otherwise it is managed by VkFFT)
1501\item uint64\_t isInputFormatted - specifies that initial read is performed
1502from a separate buffer (inputBuffer)
1503\item uint64\_t isOutputFormatted - specifies that final write is performed
1504to a separate buffer (outputBuffer)
1505\item uint64\_t performConvolution - enables convolution calculations, which
1506requires precomputed kernel (kernel)
1507\end{itemize}
1508Buffer sizes (bufferSize/tempBufferSize/inputBufferSize/outputBufferSize/kernelSize)
1509are provided as a uint64\_t pointer to an array, where each element
1510corresponds to the buffer size of the buffer with the same placement
1511in the buffer array. Buffer sizes have to be provided in Vulkan API
1512(due to the stricter memory management model and multiple buffer support)
1513and are optional in other backends (they can be useful to determine
1514when to switch for 64-bit addressing).
1515
1516Buffer number (bufferNum/tempBufferNum/inputBufferNum/outputBufferNum/kernelNum)
1517corresponds to how many elements are in the buffer and buffer size
1518array. By default it is set to 1 and is not required to be provided
1519by the user. Non-Vulkan backends currently don't support values other
1520than default. Optional parameter.
1521
1522Buffer offset (bufferOffset/ tempBufferOffset/ inputBufferOffset/
1523outputBufferOffset/ kernelOffset) specifies offset from the start
1524of the buffer sequence. It must be specified in bytes and must be
1525divisible by the number type size used in the corresponding array
1526(otherwise, the offset will be truncated). It is provided as a single
1527uint64\_t value. Can be provided at launch time, if specifyOffsetsAtLaunch
1528parameter is enabled during initialization call. Optional parameters.
1529
1530User can provide custom dimension strides for buffer/inputBuffer/outputBuffer
1531buffers - uint64\_t{[}VKFFT\_MAX\_FFT\_DIMENSIONS{]} array. Strides
1532are specified in elements used in the array (not bytes). The first
1533element corresponds to the stride between elements in the H direction,
1534the second corresponds to the D direction and the third to C (or N,
1535if the number of elements in C is 1). The first axis is assumed to
1536be non-strided. Must be at least of the same size as default strides,
1537otherwise the behavior is undefined. Optional parameters.
1538
1539uint64\_t inverseReturnToInputBuffer - an option that allows setting
1540the final output buffer of the inverse transform to the same buffer,
1541initial read of forward transform is performed from (inputBuffer,
1542if isInputFormatted enabled). Optional parameter.
1543
1544\subsubsection{General FFT parameters }
1545
1546This section describes part of the configuration structure responsible
1547for FFT specification. 
1548
1549uint64\_t FFTdim - dimensionality of the transform (up to VKFFT\_MAX\_FFT\_DIMENSIONS).
1550Required parameter.
1551
1552uint64\_t size{[}VKFFT\_MAX\_FFT\_DIMENSIONS{]} - WHD+ dimensions
1553of the transform. Required parameter.
1554
1555uint64\_t numberBatches - N parameter of the transform. By default,
1556it is set to 1. Optional parameter.
1557
1558uint64\_t performR2C - perform R2C/C2R decomposition. performDCT and
1559performDST must be set to 0. Default 0, set to 1 to enable. Optional
1560parameter.
1561
1562uint64\_t performDCT - perform DCT transformation. performR2C and
1563performDST must be set to 0. Default 0, set to X for DCT-X (currently
1564supported X: 1, 2, 3 and 4). Optional parameter.
1565
1566uint64\_t performDST - perform DST transformation. performR2C and
1567performDCT must be set to 0. Default 0, set to X for DST-X (currently
1568supported X: 1, 2, 3 and 4). Optional parameter.
1569
1570uint64\_t normalize - enabling this parameter will make the inverse
1571transform divide the result by the FFT length. Default 0, set to 1
1572to enable. Optional parameter.
1573
1574\subsubsection{Precision parameters (and some things that can affect it):}
1575
1576uint64\_t doublePrecision - perform calculations in double precision.
1577Default 0, set to 1 to enable. In Vulkan/OpenCL/Level Zero your device
1578must support double precision functionality. Metal API does not support
1579double precision. Optional parameter.
1580
1581uint64\_t doublePrecisionFloatMemory - perform calculations in double
1582precision, but all intermediate and final storage in float. Input/Output/main
1583buffers must have single-precision layout. doublePrecision must be
1584set to 0. This option increases precision, but not that much to be
1585recommended for actual use. Default 0, set to 1 to enable. In Vulkan/OpenCL/Level
1586Zero your device must support double precision functionality. Metal
1587API does not support double precision. Optional parameter.
1588
1589uint64\_t quadDoubleDoublePrecision - perform calculations in double-double
1590emulation of quad precision (0 - off, 1 - on). Optional parameter.
1591Requires quadmath library (for now).
1592
1593uint64\_t quadDoubleDoublePrecisionDoubleMemory - perform calculations
1594in double-double emulation of quad precision, while all memory storage
1595is done in FP64. Optional parameter. Requires quadmath library (for
1596now).
1597
1598uint64\_t halfPrecision - half-precision in VkFFT is implemented only
1599as memory optimization. All calculations are done in single precision
1600(similar way as doublePrecisionFloatMemory works for double and single
1601precision). Default 0, set to 1 to enable. Optional parameter.
1602
1603uint64\_t halfPrecisionMemoryOnly - another way of performing half-precision
1604in VkFFT, it will use half-precision only for initial and final memory
1605storage in input/output buffer. Input/Output have to be allocated
1606as half, buffer/tempBuffer have to be allocated as float (out-of-place
1607mode only). Specify isInputFormatted and isOutputFormatted to use.
1608So, for example, intermediate storage between axes FFTs in the multidimensional
1609case will be done in single precision, as opposed to half-precision
1610in the base halfPrecision case. halfPrecision must be set to 1. Default
16110, set to 1 to enable. Optional parameter.
1612
1613int64\_t useLUT - switches from calculating sines and cosines (via
1614special function units in single precision or as a polynomial approximation
1615in double precision) to using precomputed Look-Up Tables. -1 - off,
16160 - auto, 1 - on. Default 0 in single precision, 1 in double precision.
1617Set to 1 by default for Intel GPUs. If you have issues with single-precision
1618accuracy on your GPU, try enabling this parameter (mobile GPUs may
1619be affected). Optional parameter.
1620
1621int64\_t useLUT\_4step - switches from calculating sincos to using
1622precomputed LUT tables for intermediate roots of 1 in the Four-step
1623FFT algorithm. (-1 - off, 0 - auto, 1 - on). Configured by initialization
1624routine. Optional parameter. 
1625
1626\subsubsection{Advanced parameters (code will work fine without using them)}
1627
1628uint64\_t omitDimension{[}VKFFT\_MAX\_FFT\_DIMENSIONS{]} - parameter,
1629that disables the FFT calculation for a particular axis (WHD). Note,
1630that omitted dimensions still need to be included in FFTdim and size.
1631This parameter simply works as a switch during execution - by not
1632executing the particular dimension code. It doesn't work with the
1633non-strided axis (W) of R2C/C2R mode. It doesn't work with convolution
1634calculations. Default 0, set to 1 to enable. Optional parameter.
1635
1636uint64\_t useUint64 - forces VkFFT to use 64-bit addressing in generated
1637kernels. It is automatically enabled if the estimated buffer size
1638is more than 4GB. Doesn't work with the Vulkan backend. By default,
1639it is set to 0. Optional parameter.
1640
1641uint64\_t coalescedMemory - number of bytes to coalesce per one transaction.
1642For Nvidia and AMD is equal to 32, Intel is equal to 64. Going to
1643work regardless, but if specified by the user correctly, the performance
1644will be higher. Default 64 for other GPUs. For half-precision should
1645be multiplied by two. Should be a power of two. Optional parameter.
1646
1647uint64\_t numSharedBanks - configure the number of shared banks on
1648the target GPU. Default 32. Minor performance boost as it solves shared
1649memory conflicts for the power of two systems. Optional parameter.
1650
1651uint64\_t aimThreads - try to aim all kernels at this amount of threads.
1652Gains/losses are not predictable, just a parameter to play with (it
1653is not guaranteed that the target kernel will use that many threads).
1654Default 128. Optional parameter.
1655
1656uint64\_t useUint64 - forces 64-bit addressing in generated kernels.
1657Should be enabled automatically for systems spanning more than 4GB,
1658but it is better to have an option to force it as a failsafe. Doesn't
1659work in Vulkan API (use multiple buffer binding). Default 0, set to
16601 to enable. Optional parameter.
1661
1662int performBandwidthBoost - try to reduce coalsesced number by a factor
1663of X to get bigger sequence in one upload for strided axes. Default:
1664-1(inf) for DCT and DST, 2 for Bluestein's algorithm (or -1 if DCT
1665and DST), 0 otherwise 
1666
1667uint64\_t disableMergeSequencesR2C - disable the optimization that
1668performs merging of two real sequences to reduce calculations (in
1669R2C/C2R and R2R). If enabled, calculations will be performed by simply
1670setting the imaginary component to zero. Default 0, set to 1 to enable.
1671Optional parameter.
1672
1673uint64\_t forceCallbackVersionRealTransforms - force callback version
1674of R2C and R2R algorithms for all usecases (0 - off, 1 - on) 
1675
1676uint64\_t disableReorderFourStep - disables unshuffling of the Four
1677Step FFT algorithm (last transposition of data). With this option
1678enabled, tempBuffer will not be needed (unless it is required by Bluestein's
1679multi-upload FFT algorithm). Default 0, set to 1 to enable. Automatically
1680enabled for convolution calculations and Bluestein's algorithm. Optional
1681parameter.
1682
1683uint64\_t makeForwardPlanOnly - generate code only for forward FFT.
1684Default 0, set to 1 to enable. Mutually exclusive with makeInversePlanOnly.
1685Optional parameter.
1686
1687uint64\_t makeInversePlanOnly - generate code only for inverse FFT.
1688Default 0, set to 1 to enable. Mutually exclusive with makeForwardPlan.
1689Optional parameter.
1690
1691uint64\_t considerAllAxesStrided - will create a plan for a non-strided
1692axis similar to a strided axis (used with disableReorderFourStep to
1693get the same layout for Bluestein kernel). Default 0, set to 1 to
1694enable. Optional parameter.
1695
1696uint64\_t keepShaderCode - debugging option, will keep shader code
1697and print all executed shaders during the plan execution in order.
1698Default 0, set to 1 to enable. Optional parameter.
1699
1700uint64\_t printMemoryLayout - debugging option, will print order of
1701buffers used in kernels. Default 0, set to 1 to enable. Optional parameter. 
1702
1703uint64\_t saveApplicationToString - will save all compiled binaries
1704to VkFFTApplication.saveApplicationString (will be allocated by VkFFT,
1705deallocated with deleteVkFFT call). VkFFTApplication.applicationStringSize
1706will contain size of binary in bytes. Currently disabled in Metal
1707backend. Default 0, set to 1 to enable. Optional parameter.
1708
1709uint64\_t loadApplicationFromString - will load all binaries from
1710loadApplicationString instead of recompiling them (loadApplicationString
1711must be allocated by user, must contain what saveApplicationToString
1712call generated previously in VkFFTApplication.saveApplicationString).
1713Currently disabled in Metal backend. Default 0, set to 1 to enable.
1714Optional parameter. Mutually exclusive with saveApplicationToString 
1715
1716void{*} loadApplicationString - memory binary array through which
1717user can load VkFFT binaries, must be provided by user if loadApplicationFromString
1718= 1. Use rb/wb flags to load/save.
1719
1720uint64\_t disableSetLocale - disables all VkFFT attempts to set locale
1721to C - user must ensure that VkFFT has C locale during the plan initialization.
1722This option is needed for multithreading. Default 0.
1723
1724uint64\_t groupedBatch{[}VKFFT\_MAX\_FFT\_DIMENSIONS{]} - try to force
1725this many FFTs to be perfromed by one threadblock for each dimension.
1726Optional parameter. 
1727
1728\subsubsection{Rader control parameters}
1729
1730uint64\_t fixMinRaderPrimeMult - start direct multiplication Rader's
1731algorithm for radix primes from this number. This means that VkFFT
1732will inline custom Rader kernels if sequence is divisible by these
1733primes. Default is 17, as VkFFT has kernels for 2-13. If you make
1734it less than 13, VkFFT will switch from these kernels to Rader.
1735
1736uint64\_t fixMaxRaderPrimeMult - switch from Mult Rader's algorithm
1737for radix primes from this number. Current limitation for Rader is
1738maxThreadNum/2+1, realistically you would want to switch somewhere
1739on 30-100 range. Default is vendor-specific (currently \textasciitilde 40)
1740
1741uint64\_t fixMinRaderPrimeFFT - start FFT convolution version of Rader
1742for radix primes from this number. Better than direct multiplication
1743version for almost all primes (except small ones, like 17-23 on some
1744GPUs). Must be bigger or equal to fixMinRaderPrimeMult. Deafult 29
1745on AMD and 17 on other GPUs. 
1746
1747uint64\_t fixMaxRaderPrimeFFT - switch to Bluestein's algorithm for
1748radix primes from this number. Switch may happen earlier if prime
1749can't fit in shared memory. Default is 16384, which is bigger than
1750most current GPU's shared memory.
1751
1752\subsubsection{Bluestein control parameters}
1753
1754If the sequence can not be decomposed as a multiplication of primes
1755up to 13, FFT is performed as a convolution. The sequence to pad to
1756with the best performance is usually device-dependent. VkFFT uses
1757parameters manually tuned for all sequences between 2 and 4096 for
1758both double and single precision on Nvidia A100 (Nvidia profile) and
1759AMD MI250 (default profile). To control this process, VkFFT allows
1760for the following parameters specification:
1761
1762uint64\_t fixMaxRadixBluestein - controls the padding of sequences
1763in Bluestein convolution. If specified, padded sequence will be made
1764of up to fixMaxRadixBluestein primes. Default: 2 for CUDA and Vulkan/OpenCL/HIP
1765up to 1048576 combined dimension FFT system, 7 for Vulkan/OpenCL/HIP
1766past after. Min = 2, Max = 13.
1767
1768uint64\_t forceBluesteinSequenceSize - force the sequence size to
1769pad to in Bluestein's algorithm. Must be at least 2{*}N-1 and decomposable
1770with primes 2-13.
1771
1772uint64\_t useCustomBluesteinPaddingPattern - force the sequence sizes
1773to pad to in Bluestein's algorithm, but on a range. This number specifies
1774the number of elements in primeSizes and in paddedSizes arrays. primeSizes
1775- array of non-decomposable as radix scheme sizes - 17, 23, 31 etc.
1776paddedSizes - array of lengths to pad to. paddedSizes{[}i{]} will
1777be the padding size for all non-decomposable sequences from primeSizes{[}i{]}
1778to primeSizes{[}i+1{]} (will use default scheme after last one) -
177942, 60, 64 for primeSizes before and 37+ will use default scheme (for
1780example). Default is vendor and API-based specified in autoCustomBluesteinPaddingPattern.
1781
1782uint64\_t{*} primeSizes - described in useCustomBluesteinPaddingPattern
1783
1784uint64\_t{*} paddedSizes - described in useCustomBluesteinPaddingPattern
1785
1786\subsubsection{Zero padding parameters}
1787
1788uint64\_t performZeropadding{[}VKFFT\_MAX\_FFT\_DIMENSIONS{]} - do
1789not read/write some data/perform computations if some part of the
1790sequence is known to have zeros. Set separately for each axis (WHD).
1791If enabled, all 1D sequences in this direction will be considered
1792padded (independent of other zero-padded axes). Default 0, set to
17931 to enable. Optional parameter. 
1794
1795uint64\_t fft\_zeropad\_left{[}VKFFT\_MAX\_FFT\_DIMENSIONS{]} - specify
1796start boundary of zero block in the system for each axis. Default
17970, set to the value between 0 and size{[}X{]}-1. Optional parameter.
1798
1799uint64\_t fft\_zeropad\_right{[}VKFFT\_MAX\_FFT\_DIMENSIONS{]} - specify
1800end boundary of zero block in the system for each axis. Default 0,
1801set to the value between fft\_zeropad\_left{[}X{]} and size{[}X{]}-1.
1802Optional parameter.
1803
1804uint64\_t frequencyZeroPadding - enables zero padding of the frequency
1805domain, so the first read of inverse FFT will consider the parts of
1806the system from fft\_zeropad\_left to fft\_zeropad\_right as zero.
1807Default 0 - spatial zero padding, set to 1 to enable. Optional parameter. 
1808
1809\subsubsection{Convolution parameters}
1810
1811uint64\_t performConvolution - main parameter that enables convolutions
1812in the application. If enabled, you must specify kernel buffer, number
1813of kernel buffers and kernel sizes (in Vulkan API). Disables reordering
1814of the Four Step FFT algorithm. Default 0, set to 1 to enable. Optional
1815parameter. 
1816
1817uint64\_t conjugateConvolution - default 0, set to 1 to enable enables
1818conjugation of the sequence FFT is currently done on, 2 to enable
1819conjugation of the convolution kernel. Optional parameter. 
1820
1821uint64\_t crossPowerSpectrumNormalization - normalize the FFT {*}
1822kernel multiplication in frequency domain. Default 0, set to 1 to
1823enable. Optional parameter. 
1824
1825uint64\_t coordinateFeatures - max coordinate (C), or dimension of
1826the features vector. In matrix convolution - the size of the vector.
1827The main purpose is to support Matrix-Vector convolutions. Use numberBatches
1828parameter in tasks, not requiring two separate coordinate-like enumerations
1829of data. Default 1. Optional parameter.
1830
1831uint64\_t matrixConvolution - set to 2 to perform 2x2, set to 3 to
1832perform 3x3 matrix-vector convolution. Matrix-vector convolution is
1833a form of point-wise multiplication in the Fourier space, used by
1834the convolution theorem, where multiplication takes the form of Matrix-vector
1835multiplication. Overrides coordinateFeatures during execution. Default
18360. Optional parameter. 
1837
1838uint64\_t symmetricKernel - specify if kernel in 2x2 or 3x3 matrix
1839convolution is symmetric. You need to store data as xx, xy, yy (upper-triangular)
1840if enabled and as xx, xy, yx, yy (along rows then along columns, from
1841left to right) if disabled. Default 0, set to 1 to enable. Optional
1842parameter. 
1843
1844uint64\_t numberKernels - specify how many kernels were initialized
1845before performing one input/multiple output convolutions. Overwrites
1846numberBatches (N). Only used in convolution step and the following
1847inverse transforms. Default 1. Optional parameter. 
1848
1849uint64\_t kernelConvolution - specify if this application is used
1850to create kernel for convolution, so it has the same properties/memory
1851layout. performConvolution has to be set to 0 for the kernel creation.
1852Default 0, set to 1 to enable. Optional parameter, but it is a required
1853parameter for kernel generation.
1854
1855\subsubsection{Register overutilization}
1856
1857Only works in C2C mode, without convolution support. Enabled in Vulkan,
1858OpenCL and Level Zero APIs only (it works in other APIs, but worse,
1859does not work in Metal). Experimental feature.
1860
1861uint64\_t registerBoost - specify if the register file size is bigger
1862than shared memory and can be used to extend it X times (on Nvidia
1863256KB register file can be used instead of 32KB of shared memory,
1864set this constant to 4 to emulate 128KB of shared memory). Default
18651 - no overutilization. In Vulkan, OpenCL and Level Zero it is set
1866to 4 on Nvidia GPUs, to 2 if the driver shows 64KB or more of shared
1867memory on AMD, to 2 if the driver shows less than 64KB of shared memory
1868on AMD, to 1 if the driver shows 64KB or more of shared memory on
1869Intel, to 2 if the driver shows less than 64KB of shared memory on
1870Intel. Optional parameter.
1871
1872uint64\_t registerBoostNonPow2 - specify if register overutilization
1873should be used on non-power of 2 sequences. Default 0, set to 1 to
1874enable. Optional parameter.
1875
1876uint64\_t registerBoost4Step - specify if register file overutilization
1877should be used in big sequences (>2\textasciicircum 14), same definition
1878as registerBoost. Default 1. Optional parameter.
1879
1880\subsubsection{Extra advanced parameters (filled automatically)}
1881
1882uint64\_t computeCapabilityMajor - CUDA/HIP compute capability of
1883the device
1884
1885uint64\_t computeCapabilityMinor - CUDA/HIP compute capability of
1886the device 
1887
1888uint64\_t maxComputeWorkGroupCount{[}3{]} - how many workgroups can
1889be launched at one dispatch. Automatically derived from the driver,
1890can be artificially lowered. Then VkFFT will perform a logical split
1891and extension of the number of workgroups to cover the required range.
1892
1893uint64\_t maxComputeWorkGroupSize{[}3{]} - max dimensions of the workgroup.
1894Automatically derived from the driver. Can be modified if there are
1895some issues with the driver (as there were with ROCm 4.0, when it
1896returned 1024 for maxComputeWorkGroupSize and actually supported only
1897up to 256 threads).
1898
1899uint64\_t maxThreadsNum - max number of threads per block. Similar
1900to maxComputeWorkGroupSize, but aggregated. Automatically derived
1901from the driver.
1902
1903uint64\_t sharedMemorySizeStatic - available for static allocation
1904shared memory size, in bytes. Automatically derived from the driver.
1905Can be controlled by the user, if desired.
1906
1907uint64\_t sharedMemorySize - available for allocation shared memory
1908size, in bytes. VkFFT uses dynamic shared memory in CUDA/HIP as it
1909allows for bigger allocations. Automatically derived from the driver.
1910Can be controlled by the user, if desired.
1911
1912uint64\_t sharedMemorySizePow2 - the power of 2 which is less or equal
1913to sharedMemorySize, in bytes. Automatically computed.
1914
1915uint64\_t warpSize - number of threads per warp/wavefront. Automatically
1916derived from the driver, but can be modified (can increase performance,
1917though unpredictable as defaults have good values). Must be a power
1918of two.
1919
1920uint64\_t halfThreads - Intel GPU fix, tries to reduce the amount
1921of dispatched threads in half to solve performance degradation in
1922the Four Step FFT algorithm. Default 0 for other GPUs, try enabling
1923it if performance degrades in the Four Step FFT algorithm for your
1924GPU as well. 
1925
1926int64\_t maxCodeLength - specify how big can the buffer used for code
1927generation be (in char). Default 1000000 chars. 
1928
1929int64\_t maxTempLength - specify how big can the buffer used for intermediate
1930string sprintf's be (in char). Default 5000 chars. If code segfaults
1931for some reason - try increasing this number.
1932
1933uint64\_t autoCustomBluesteinPaddingPattern - default value for useCustomBluesteinPaddingPattern
1934
1935uint64\_t useRaderUintLUT - allocate additional LUT to store g\_pow 
1936
1937uint64\_t vendorID - vendorID 0x10DE - NVIDIA, 0x8086 - Intel, 0x1002
1938- AMD, etc.
1939
1940\newpage{}
1941
1942\section{VkFFT Benchmark/Precision Suite and utils\_VkFFT helper routines}
1943
1944The only licensed (MIT) part of the VkFFT repository is the VkFFT
1945header file - core library. Other files are either external helper
1946libraries (half, glslang, with their respective licenses) or unlicensed
1947code that is intended for simple copy-pasting (benchmark\_scripts,
1948utils\_VkFFT.h). It is the easiest way to understand how to use VkFFT
1949by taking the provided scripts and tinker them to the particular task.
1950The current version of the benchmark and precision verification suite
1951has the following codes available:
1952\begin{itemize}
1953\item user\_benchmark\_VkFFT - generalization of the main configuration
1954parameters that can be used to launch simplest in-place transforms
1955for the most important supported functionality
1956\item Sample 0 - FFT + iFFT C2C benchmark 1D batched in single precision
1957\item Sample 1 - FFT + iFFT C2C benchmark 1D batched in double precision
1958\item Sample 2 - FFT + iFFT C2C benchmark 1D batched in half precision
1959\item Sample 3 - FFT + iFFT C2C multidimensional benchmark in single precision
1960\item Sample 4 - FFT + iFFT C2C multidimensional benchmark in single precision,
1961native zeropadding
1962\item Sample 5 - FFT + iFFT C2C benchmark 1D batched in single precision,
1963no reshuffling
1964\item Sample 6 - FFT + iFFT R2C / C2R benchmark, in-place.
1965\item Sample 7 - FFT + iFFT C2C Bluestein benchmark in single precision
1966\item Sample 8 - FFT + iFFT C2C Bluestein benchmark in double precision
1967\item Sample 9 - FFT + iFFT C2C benchmark 1D batched in double-double emulation
1968of quad precision
1969\item Sample 10 - multiple buffers (4 by default) split version of benchmark
19700
1971\item Sample 11 - VkFFT / xFFT / FFTW C2C precision test in single precision
1972(xFFT can be cuFFT or rocFFT)
1973\item Sample 12 - VkFFT / xFFT / FFTW C2C precision test in double precision
1974(xFFT can be cuFFT or rocFFT)
1975\item Sample 13 - VkFFT / cuFFT / FFTW C2C precision test in half precision
1976\item Sample 14 - VkFFT / FFTW C2C radix 3 / 5 / 7 / 11 / 13 / Bluestein
1977precision test in single precision
1978\item Sample 15 - VkFFT / xFFT / FFTW R2C+C2R precision test in single precision,
1979out-of-place. (xFFT can be cuFFT or rocFFT)
1980\item Sample 16 - VkFFT / FFTW R2R DCT-I, II, III and IV precision test
1981in single precision
1982\item Sample 17 - VkFFT / FFTW R2R DCT-I, II, III and IV precision test
1983in double precision
1984\item Sample 18 - VkFFT / FFTW C2C radix 3 / 5 / 7 / 11 / 13 / Bluestein
1985precision test in double precision
1986\item Sample 19 - VkFFT / FFTW C2C precision test in double-double emulation
1987of quad precision
1988\item Sample 50 - convolution example with identity kernel
1989\item Sample 51 - zero padding convolution example with identity kernel
1990\item Sample 52 - batched convolution example with identity kernel
1991\item Sample 100 - VkFFT FFT + iFFT R2R DCT multidimensional benchmark in
1992single precision
1993\item Sample 101 - VkFFT FFT + iFFT R2R DCT multidimensional benchmark in
1994double precision
1995\item Sample 1000 - FFT + iFFT C2C benchmark 1D batched in single precision:
1996all supported systems from 2 to 4096
1997\item Sample 1001 - FFT + iFFT C2C benchmark 1D batched in double precision:
1998all supported systems from 2 to 4096
1999\item Sample 1002 - FFT + iFFT C2C benchmark 1D batched in half precision:
2000all supported systems from 2 to 4096
2001\item Sample 1003 - FFT + iFFT C2C benchmark 1D batched in single precision:
2002all supported systems from 2 to 4096
2003\item Sample 1004 - FFT + iFFT C2C benchmark 1D batched in double-double
2004emulation of quad precision: all supported systems from 2 to 4096
2005\end{itemize}
2006
2007\subsection{utils\_VkFFT helper routines}
2008
2009Launching even the simplest Vulkan application can be a non-trivial
2010task. To help with this, utils\_VkFFT contains the routines that can
2011help to create the simplest Vulkan application, allocate memory, record
2012command buffers and launch them. Code has some comments explaining
2013what is going on at each step. It also has some useful struct defines
2014(like vkGPU) that keep the most important handles used in Vulkan Compute.
2015This section may be expanded in the future to the proper step-by-step
2016guide on Vulkan Compute simple application creation. I also encourage
2017to check https://github.com/DTolm/VulkanComputeSamples-Transposition
2018repository for another example of a compute algorithm (matrix transposition)
2019implemented with Vulkan API.
2020
2021utils\_VkFFT also has a routine that prints the list of available
2022devices.
2023
2024vkGPU struct has the following definition:
2025
2026\begin{mdframed}[backgroundcolor=bg]
2027\begin{minted}[tabsize=4,obeytabs,breaklines]{C}
2028typedef struct {
2029#if(VKFFT_BACKEND==0) //Vulkan API
2030VkInstance instance; //a connection between the application and the Vulkan library
2031VkPhysicalDevice physicalDevice; //a handle for the graphics card used in the application
2032VkPhysicalDeviceProperties physicalDeviceProperties; //bastic device properties
2033VkPhysicalDeviceMemoryProperties physicalDeviceMemoryProperties; //basic memory properties of the device
2034VkDevice device; //a logical device, interacting with physical device
2035VkDebugUtilsMessengerEXT debugMessenger; //extension for debugging
2036uint64_t queueFamilyIndex; //if multiple queues are available, specify the used one
2037VkQueue queue; //a place, where all operations are submitted
2038VkCommandPool commandPool; //an opaque objects that command buffer memory is allocated from
2039VkFence fence; //a vkGPU->fence used to synchronize dispatches
2040std::vector<const char*> enabledDeviceExtensions;
2041uint64_t enableValidationLayers;
2042#elif(VKFFT_BACKEND==1) //CUDA API
2043CUdevice device;
2044CUcontext context;
2045#elif(VKFFT_BACKEND==2) //HIP API
2046hipDevice_t device;
2047hipCtx_t context;
2048#elif(VKFFT_BACKEND==3) //OpenCL API
2049cl_platform_id platform;
2050cl_device_id device;
2051cl_context context;
2052cl_command_queue commandQueue;
2053#elif(VKFFT_BACKEND==4) //Level Zero API
2054ze_driver_handle_t driver;
2055ze_device_handle_t device;
2056ze_context_handle_t context;
2057ze_command_queue_handle_t commandQueue;
2058uint32_t commandQueueID;
2059#elif(VKFFT_BACKEND==5) //Metal API
2060MTL::Device* device;
2061MTL::CommandQueue* queue;
2062#endif
2063uint64_t device_id; //an id of a device, reported by devices_list call
2064} VkGPU;
2065\end{minted}
2066\end{mdframed}\newpage{}
2067
2068\section{VkFFT Code Examples}
2069
2070This section will provide some simple pseudocode for VkFFT usage,
2071which will once again outline important steps required to launch FFT
2072with VkFFT. More information (and fully working code) can be found
2073in this folder of the VkFFT repository:
2074
2075/benchmark\_samples/vkFFT\_scripts/src/
2076
2077\subsection{Driver initializations}
2078
2079Before launching VkFFT, do not forget to do all necessary driver initializations.
2080The following code specifies them for all the supported backends,
2081though the final implementation may be different depending on the
2082particular user's configuration.
2083
2084\begin{mdframed}[backgroundcolor=bg]
2085\begin{minted}[tabsize=4,obeytabs,breaklines]{C}
2086#if(VKFFT_BACKEND==0) //Vulkan API
2087VkResult res = VK_SUCCESS;
2088//create instance - a connection between the application and the Vulkan library
2089res = createInstance(vkGPU, sample_id);
2090if (res != 0) {
2091	//printf("Instance creation failed, error code: %" PRIu64 "\n", res);
2092	return VKFFT_ERROR_FAILED_TO_CREATE_INSTANCE;
2093} 	
2094//set up the debugging messenger
2095res = setupDebugMessenger(vkGPU);
2096if (res != 0) {
2097//printf("Debug messenger creation failed, error code: %" PRIu64 "\n", res);
2098	return VKFFT_ERROR_FAILED_TO_SETUP_DEBUG_MESSENGER;
2099}
2100//check if there are GPUs that support Vulkan and select one
2101res = findPhysicalDevice(vkGPU);
2102if (res != 0) {
2103//printf("Physical device not found, error code: %" PRIu64 "\n", res);
2104	return VKFFT_ERROR_FAILED_TO_FIND_PHYSICAL_DEVICE;
2105}
2106//create logical device representation
2107res = createDevice(vkGPU, sample_id);
2108if (res != 0) {
2109//printf("Device creation failed, error code: %" PRIu64 "\n", res);
2110	return VKFFT_ERROR_FAILED_TO_CREATE_DEVICE;
2111}
2112//create fence for synchronization
2113res = createFence(vkGPU);
2114if (res != 0) {
2115//printf("Fence creation failed, error code: %" PRIu64 "\n", res);
2116	return VKFFT_ERROR_FAILED_TO_CREATE_FENCE;
2117}
2118//create a place, command buffer memory is allocated from
2119res = createCommandPool(vkGPU);
2120if (res != 0) {
2121	//printf("Fence creation failed, error code: %" PRIu64 "\n", res);
2122	return VKFFT_ERROR_FAILED_TO_CREATE_COMMAND_POOL;
2123}
2124vkGetPhysicalDeviceProperties(vkGPU->physicalDevice, &vkGPU->physicalDeviceProperties);
2125vkGetPhysicalDeviceMemoryProperties(vkGPU->physicalDevice, &vkGPU->physicalDeviceMemoryProperties);
2126glslang_initialize_process();
2127//compiler can be initialized before VkFFT
2128
2129#elif(VKFFT_BACKEND==1) //CUDA API
2130CUresult res = CUDA_SUCCESS;
2131cudaError_t res2 = cudaSuccess;
2132res = cuInit(0);
2133if (res != CUDA_SUCCESS) return VKFFT_ERROR_FAILED_TO_INITIALIZE;
2134res2 = cudaSetDevice((int)vkGPU->device_id);
2135if (res2 != cudaSuccess) return VKFFT_ERROR_FAILED_TO_SET_DEVICE_ID;
2136res = cuDeviceGet(&vkGPU->device, (int)vkGPU->device_id);
2137if (res != CUDA_SUCCESS) return VKFFT_ERROR_FAILED_TO_GET_DEVICE;
2138res = cuCtxCreate(&vkGPU->context, 0, (int)vkGPU->device);
2139if (res != CUDA_SUCCESS) return VKFFT_ERROR_FAILED_TO_CREATE_CONTEXT;
2140#elif(VKFFT_BACKEND==2) //HIP API
2141hipError_t res = hipSuccess;
2142res = hipInit(0);
2143if (res != hipSuccess) return VKFFT_ERROR_FAILED_TO_INITIALIZE;
2144res = hipSetDevice((int)vkGPU->device_id);
2145if (res != hipSuccess) return VKFFT_ERROR_FAILED_TO_SET_DEVICE_ID;
2146res = hipDeviceGet(&vkGPU->device, (int)vkGPU->device_id);
2147if (res != hipSuccess) return VKFFT_ERROR_FAILED_TO_GET_DEVICE; 
2148res = hipCtxCreate(&vkGPU->context, 0, (int)vkGPU->device);
2149if (res != hipSuccess) return VKFFT_ERROR_FAILED_TO_CREATE_CONTEXT;
2150#elif(VKFFT_BACKEND==3) //OpenCL API
2151cl_int res = CL_SUCCESS;
2152cl_uint numPlatforms;
2153res = clGetPlatformIDs(0, 0, &numPlatforms);
2154if (res != CL_SUCCESS) return VKFFT_ERROR_FAILED_TO_INITIALIZE;
2155cl_platform_id* platforms = (cl_platform_id*)malloc(sizeof(cl_platform_id) * numPlatforms);
2156if (!platforms) return VKFFT_ERROR_MALLOC_FAILED;
2157res = clGetPlatformIDs(numPlatforms, platforms, 0);
2158if (res != CL_SUCCESS) return VKFFT_ERROR_FAILED_TO_INITIALIZE;
2159uint64_t k = 0;
2160for (uint64_t j = 0; j < numPlatforms; j++) {
2161	cl_uint numDevices;
2162	res = clGetDeviceIDs(platforms[j], CL_DEVICE_TYPE_ALL, 0, 0, &numDevices);
2163	cl_device_id* deviceList = (cl_device_id*)malloc(sizeof(cl_device_id) * numDevices);
2164	if (!deviceList) return VKFFT_ERROR_MALLOC_FAILED;
2165	res = clGetDeviceIDs(platforms[j], CL_DEVICE_TYPE_ALL, numDevices, deviceList, 0);
2166	if (res != CL_SUCCESS) return VKFFT_ERROR_FAILED_TO_GET_DEVICE;
2167	for (uint64_t i = 0; i < numDevices; i++) {
2168		if (k == vkGPU->device_id) {
2169			vkGPU->platform = platforms[j];
2170			vkGPU->device = deviceList[i];
2171			vkGPU->context = clCreateContext(NULL, 1, &vkGPU->device, NULL, NULL, &res);
2172			if (res != CL_SUCCESS) return VKFFT_ERROR_FAILED_TO_CREATE_CONTEXT;
2173			cl_command_queue commandQueue = clCreateCommandQueue(vkGPU->context, vkGPU->device, 0, &res);
2174			if (res != CL_SUCCESS) return VKFFT_ERROR_FAILED_TO_CREATE_COMMAND_QUEUE;
2175			vkGPU->commandQueue = commandQueue;
2176			i=numDevices; 		
2177			j=numPlatforms;
2178		}
2179		else {
2180			k++;
2181		}
2182	}
2183	free(deviceList);
2184}
2185free(platforms);
2186#elif(VKFFT_BACKEND==4)
2187	ze_result_t res = ZE_RESULT_SUCCESS;
2188	res = zeInit(0);
2189	if (res != ZE_RESULT_SUCCESS) return VKFFT_ERROR_FAILED_TO_INITIALIZE;
2190	uint32_t numDrivers = 0;
2191	res = zeDriverGet(&numDrivers, 0);
2192	if (res != ZE_RESULT_SUCCESS) return VKFFT_ERROR_FAILED_TO_INITIALIZE;
2193	ze_driver_handle_t* drivers = (ze_driver_handle_t*)malloc(numDrivers * sizeof(ze_driver_handle_t));
2194	if (!drivers) return VKFFT_ERROR_MALLOC_FAILED;
2195	res = zeDriverGet(&numDrivers, drivers);
2196	if (res != ZE_RESULT_SUCCESS) return VKFFT_ERROR_FAILED_TO_INITIALIZE;
2197	uint64_t k = 0;
2198	for (uint64_t j = 0; j < numDrivers; j++) {
2199		uint32_t numDevices = 0;
2200		res = zeDeviceGet(drivers[j], &numDevices, nullptr);
2201		if (res != ZE_RESULT_SUCCESS) return VKFFT_ERROR_FAILED_TO_GET_DEVICE;
2202		ze_device_handle_t* deviceList = (ze_device_handle_t*)malloc(numDevices * sizeof(ze_device_handle_t));
2203		if (!deviceList) return VKFFT_ERROR_MALLOC_FAILED;
2204		res = zeDeviceGet(drivers[j], &numDevices, deviceList);
2205		if (res != ZE_RESULT_SUCCESS) return VKFFT_ERROR_FAILED_TO_GET_DEVICE;
2206		for (uint64_t i = 0; i < numDevices; i++) {
2207			if (k == vkGPU->device_id) {
2208				vkGPU->driver = drivers[j];
2209				vkGPU->device = deviceList[i];
2210				ze_context_desc_t contextDescription = {};
2211				contextDescription.stype = ZE_STRUCTURE_TYPE_CONTEXT_DESC;
2212				res = zeContextCreate(vkGPU->driver, &contextDescription, &vkGPU->context);
2213				if (res != ZE_RESULT_SUCCESS) return VKFFT_ERROR_FAILED_TO_CREATE_CONTEXT;
2214
2215				uint32_t queueGroupCount = 0;
2216				res = zeDeviceGetCommandQueueGroupProperties(vkGPU->device, &queueGroupCount, 0);
2217				if (res != ZE_RESULT_SUCCESS) return VKFFT_ERROR_FAILED_TO_CREATE_COMMAND_QUEUE;
2218
2219				ze_command_queue_group_properties_t* cmdqueueGroupProperties = (ze_command_queue_group_properties_t*) malloc(queueGroupCount * sizeof(ze_command_queue_group_properties_t));
2220				if (!cmdqueueGroupProperties) return VKFFT_ERROR_MALLOC_FAILED;
2221				res = zeDeviceGetCommandQueueGroupProperties(vkGPU->device, &queueGroupCount, cmdqueueGroupProperties);
2222				if (res != ZE_RESULT_SUCCESS) return VKFFT_ERROR_FAILED_TO_CREATE_COMMAND_QUEUE;
2223
2224				uint32_t commandQueueID = -1;
2225				for (uint32_t i = 0; i < queueGroupCount; ++i) {
2226					if ((cmdqueueGroupProperties[i].flags && ZE_COMMAND_QUEUE_GROUP_PROPERTY_FLAG_COMPUTE) && (cmdqueueGroupProperties[i].flags && ZE_COMMAND_QUEUE_GROUP_PROPERTY_FLAG_COPY)) {
2227						commandQueueID = i;
2228						break;
2229					}
2230				}
2231				if (commandQueueID == -1) return VKFFT_ERROR_FAILED_TO_CREATE_COMMAND_QUEUE;
2232				vkGPU->commandQueueID = commandQueueID;
2233				ze_command_queue_desc_t commandQueueDescription = {};
2234				commandQueueDescription.stype = ZE_STRUCTURE_TYPE_COMMAND_QUEUE_DESC;
2235				commandQueueDescription.ordinal = commandQueueID;
2236				commandQueueDescription.priority = ZE_COMMAND_QUEUE_PRIORITY_NORMAL;
2237				commandQueueDescription.mode = ZE_COMMAND_QUEUE_MODE_DEFAULT;
2238				res = zeCommandQueueCreate(vkGPU->context, vkGPU->device, &commandQueueDescription, &vkGPU->commandQueue);
2239				if (res != ZE_RESULT_SUCCESS) return VKFFT_ERROR_FAILED_TO_CREATE_COMMAND_QUEUE;
2240				free(cmdqueueGroupProperties);
2241				i=numDevices; 		
2242				j=numPlatforms;
2243			}
2244			else {
2245				k++;
2246			}
2247		}
2248
2249		free(deviceList);
2250	}
2251	free(drivers);
2252#elif(VKFFT_BACKEND==5)
2253    NS::Array* devices = MTL::CopyAllDevices();
2254    MTL::Device* device = (MTL::Device*)devices->object(vkGPU->device_id);
2255    vkGPU->device = device;
2256    MTL::CommandQueue* queue = device->newCommandQueue();
2257    vkGPU->queue = queue;
2258#endif
2259\end{minted}
2260\end{mdframed}
2261
2262\subsection{Simple FFT application example: 1D (one dimensional) C2C (complex
2263to complex) FP32 (single precision) FFT}
2264
2265This example performs the simplest case of FFT. It shows all the necessary
2266fields that the user must fill during the configuration and the submission
2267process. Other samples will build on this one, as driver parameters
2268initialization and code execution commands are the same for all configurations
2269(except for the launch parameters that can be configured after application
2270creation).
2271
2272\begin{mdframed}[backgroundcolor=bg]
2273\begin{minted}[tabsize=4,obeytabs,breaklines]{C}
2274//zero-initialize configuration + FFT application
2275VkFFTConfiguration configuration = {};
2276VkFFTApplication app = {};
2277
2278configuration.FFTdim = 1; //FFT dimension
2279configuration.size[0] = Nx; //FFT size
2280uint64_t bufferSize = (uint64_t)sizeof(float) * 2 * configuration.size[0];
2281
2282//Device management + code submission
2283#if(VKFFT_BACKEND==5)
2284configuration.device = vkGPU->device;
2285#else
2286configuration.device = &vkGPU->device;
2287#endif
2288
2289#if(VKFFT_BACKEND==0) //Vulkan API		
2290configuration.queue = &vkGPU->queue;
2291configuration.fence = &vkGPU->fence; 			
2292configuration.commandPool = &vkGPU->commandPool; 			
2293configuration.physicalDevice = &vkGPU->physicalDevice; 			
2294configuration.isCompilerInitialized = isCompilerInitialized; //glslang compiler can be initialized before VkFFT plan creation. if not, VkFFT will create and destroy one after initialization 
2295#elif(VKFFT_BACKEND==3) //OpenCL API		
2296configuration.context = &vkGPU->context; 
2297#elif(VKFFT_BACKEND==4)
2298configuration.context = &vkGPU->context;
2299configuration.commandQueue = &vkGPU->commandQueue;
2300configuration.commandQueueID = vkGPU->commandQueueID;
2301#elif(VKFFT_BACKEND==5)             
2302configuration.queue = vkGPU->queue;
2303#endif
2304
2305allocateBuffer(buffer, bufferSize); //Pseudocode for buffer allocation, differs between APIs
2306transferDataFromCPU(buffer, cpu_buffer); //Pseudocode for data transfer from CPU to GPU, differs between APIs
2307
2308#if(VKFFT_BACKEND==0) //Vulkan API needs bufferSize at initialization	
2309configuration.bufferSize = &bufferSize; 
2310#endif
2311
2312VkFFTResult resFFT = initializeVkFFT(&app, configuration);
2313
2314VkFFTLaunchParams launchParams = {};
2315launchParams.buffer = &buffer;
2316#if(VKFFT_BACKEND==0) //Vulkan API 
2317launchParams.commandBuffer = &commandBuffer;
2318#elif(VKFFT_BACKEND==3) //OpenCL API
2319launchParams.commandQueue = &commandQueue;
2320#elif(VKFFT_BACKEND==4) //Level Zero API
2321launchParams->commandList = &commandList;
2322#elif(VKFFT_BACKEND==5) //Metal API
2323launchParams->commandBuffer = commandBuffer;
2324launchParams->commandEncoder = commandEncoder;
2325#endif
2326resFFT = VkFFTAppend(app, -1, &launchParams);
2327
2328//add synchronization relevant to your API - vkWaitForFences/cudaDeviceSynchronize/hipDeviceSynchronize/clFinish
2329transferDataToCPU(cpu_buffer, buffer); //Pseudocode for data transfer from GPU to CPU, differs between APIs
2330
2331freeBuffer(buffer, bufferSize); //Pseudocode for buffer deallocation, differs between APIs
2332
2333deleteVkFFT(&app);
2334\end{minted}
2335\end{mdframed} 
2336
2337\subsection{Advanced FFT application example: ND, C2C/R2C/R2R, different precisions,
2338batched FFT}
2339
2340This example shows how to configure the main parameters of interest
2341in the VkFFT library: multidimensional case, different types of transforms,
2342different precision, perform batched transforms.
2343
2344In the code below X, Y and Z are the dimensions of FFT, B - number
2345of batches, R2C - real to complex mode 0 or 1 (on/off), DCT - 0, 1,
23462, 3 or 4 (off/DCT type), P - precision (0 - single, 1 - double, 2
2347- half).
2348
2349\begin{mdframed}[backgroundcolor=bg]
2350\begin{minted}[tabsize=4,obeytabs,breaklines]{C}
2351//zero-initialize configuration + FFT application
2352VkFFTConfiguration configuration = {};
2353VkFFTApplication app = {};
2354
2355configuration.FFTdim = 1; //FFT dimension
2356configuration.size[0] = X;
2357configuration.size[1] = Y;
2358configuration.size[2] = Z;
2359if (Y > 1) configuration.FFTdim++;
2360if (Z > 1) configuration.FFTdim++;
2361configuration.numberBatches = B;
2362configuration.performR2C = R2C;
2363configuration.performDCT = DCT;
2364if (P == 1) configuration.doublePrecision = 1; 
2365if (P == 2) configuration.halfPrecision = 1;
2366if (P == 3) configuration.quadDoubleDoublePrecision = 1;
2367
2368uint64_t bufferSize = 0;
2369
2370if (R2C) {
2371	bufferSize = (uint64_t)(storageComplexSize / 2) * (configuration.size[0] + 2) * configuration.size[1] * configuration.size[2] * configuration.numberBatches;
2372}
2373else {
2374	if (DCT) {
2375		bufferSize = (uint64_t)(storageComplexSize / 2) * configuration.size[0] * configuration.size[1] * configuration.size[2] * configuration.numberBatches;
2376	}
2377	else {
2378		bufferSize = (uint64_t)storageComplexSize * configuration.size[0] * configuration.size[1] * configuration.size[2] * configuration.numberBatches;
2379	}
2380} // storageComplexSize - 4/8/16 for FP16/FP32/FP64 respectively.
2381
2382//Device management + code submission - code is identical to the previous example
2383\end{minted}
2384\end{mdframed}
2385
2386\subsection{Advanced FFT application example: out-of-place R2C FFT with custom
2387strides}
2388
2389In this example, VkFFT is configured to calculate a 3D out-of-place
2390R2C FFT of a system with custom strides. VkFFT reads data from the
2391inputBuffer and produces the result in the buffer. 
2392
2393\begin{mdframed}[backgroundcolor=bg]
2394\begin{minted}[tabsize=4,obeytabs,breaklines]{C}
2395//zero-initialize configuration + FFT application
2396VkFFTConfiguration configuration = {};
2397VkFFTApplication app = {};
2398
2399configuration.FFTdim = 3; //FFT dimension
2400configuration.size[0] = Nx;
2401configuration.size[1] = Ny;
2402configuration.size[2] = Nz;
2403
2404configuration.performR2C = 1;
2405
2406//out-of-place - we need to specify that input buffer is separate from the main buffer
2407configuration.isInputFormatted = 1;
2408configuration.inputBufferStride[0] = configuration.size[0];
2409configuration.inputBufferStride[1] = configuration.inputBufferStride[0] * configuration.size[1];
2410configuration.inputBufferStride[2] = configuration.inputBufferStride[1] * configuration.size[2];
2411			
2412configuration.bufferStride[0] = (uint64_t) (configuration.size[0] / 2) + 1;
2413configuration.bufferStride[1] = configuration.bufferStride[0] * configuration.size[1];
2414configuration.bufferStride[2] = configuration.bufferStride[1]* configuration.size[2];
2415
2416uint64_t inputBufferSize = (uint64_t)sizeof(float) * configuration.size[0] * configuration.size[1] * configuration.size[2];
2417
2418uint64_t bufferSize = (uint64_t)sizeof(float) * 2 * (configuration.size[0]/2+1) * configuration.size[1] * configuration.size[2];
2419
2420//Device management + code submission - code is identical to the first example, except that you need to allocate two buffers (and provide them in the launch configuration).
2421
2422\end{minted}
2423\end{mdframed}
2424
2425\subsection{Advanced FFT application example: 3D FFT with innermost batching}
2426
2427In this example, VkFFT is configured to calculate a 3D in-place C2C
2428FFT of a system with innermost (fast axis) batching. 
2429
2430\begin{mdframed}[backgroundcolor=bg]
2431\begin{minted}[tabsize=4,obeytabs,breaklines]{C}
2432//zero-initialize configuration + FFT application
2433VkFFTConfiguration configuration = {};
2434VkFFTApplication app = {};
2435
2436configuration.FFTdim = 4; //FFT dimension, 3+1
2437configuration.size[0] = Nbatch;
2438configuration.size[1] = Nx;
2439configuration.size[2] = Ny;
2440configuration.size[3] = Nz;
2441
2442configuration.omitDimension[0] = 1; // disable FFT over the batching dimension
2443
2444uint64_t bufferSize = (uint64_t)sizeof(float) * configuration.size[0] * configuration.size[1] * configuration.size[2] * configuration.size[3];
2445
2446//Device management + code submission - code is identical to the first example, except that you need to allocate two buffers (and provide them in the launch configuration).
2447
2448\end{minted}
2449\end{mdframed}
2450
2451\subsection{Advanced FFT application example: 3D zero-padded FFT}
2452
2453In this example, VkFFT is configured to calculate a 3D FFT of a system.
2454The meaningful data is located in the first octant of the buffer,
2455the rest is padded with zeros. This configuration removes the circular
2456part of the convolution and allows modelling of open systems.
2457
2458\begin{mdframed}[backgroundcolor=bg]
2459\begin{minted}[tabsize=4,obeytabs,breaklines]{C}
2460//zero-initialize configuration + FFT application
2461VkFFTConfiguration configuration = {};
2462VkFFTApplication app = {};
2463
2464configuration.FFTdim = 3; //FFT dimension
2465configuration.size[0] = Nx;
2466configuration.size[1] = Ny;
2467configuration.size[2] = Nz;
2468
2469configuration.performZeropadding[0] = 1; //Perform padding with zeros on GPU. Still need to properly align input data (no need to fill padding area with meaningful data) but this will increase performance due to the lower amount of the memory reads/writes and omitting sequences only consisting of zeros.
2470configuration.performZeropadding[1] = 1;
2471configuration.performZeropadding[2] = 1;
2472configuration.fft_zeropad_left[0] = (uint64_t)ceil(configuration.size[0] / 2.0);
2473configuration.fft_zeropad_right[0] = configuration.size[0];
2474configuration.fft_zeropad_left[1] = (uint64_t)ceil(configuration.size[1] / 2.0);
2475configuration.fft_zeropad_right[1] = configuration.size[1];
2476configuration.fft_zeropad_left[2] = (uint64_t)ceil(configuration.size[2] / 2.0);
2477configuration.fft_zeropad_right[2] = configuration.size[2];
2478
2479uint64_t bufferSize = (uint64_t)storageComplexSize * configuration.size[0] * configuration.size[1] * configuration.size[2];
2480
2481
2482//Device management + code submission - code is identical to the first example
2483
2484\end{minted}
2485\end{mdframed}
2486
2487\subsection{Convolution application example: 3x3 matrix-vector convolution in
24881D}
2489
2490In this example, VkFFT is configured to calculate a kernel, represented
2491by a 3x3 matrix and a system, represented by a 3D vector. Their convolution
2492is a matrix-vector multiplication in the frequency domain.
2493
2494\begin{mdframed}[backgroundcolor=bg]
2495\begin{minted}[tabsize=4,obeytabs,breaklines]{C}
2496//zero-initialize configuration + FFT application, we need two - one for kernel calculation
2497VkFFTConfiguration kernel_configuration = {};
2498VkFFTConfiguration convolution_configuration = {};
2499VkFFTApplication app_kernel = {};
2500VkFFTApplication app_convolution = {};
2501
2502
2503kernel_configuration.FFTdim = 1; //FFT dimension
2504kernel_configuration.size[0] = Nx; //FFT size
2505
2506uint64_t bufferSize = (uint64_t)sizeof(float) * 2 * kernel_configuration.size[0];
2507
2508//configure kernel 
2509kernel_configuration.kernelConvolution = 1; //specify if this plan is used to create kernel for convolution
2510kernel_configuration.coordinateFeatures = 9; //Specify dimensionality of the input feature vector (default 1). Each component is stored not as a vector, but as a separate system and padded on it's own according to other options (i.e. for x*y system of 3-vector, first x*y elements correspond to the first dimension, then goes x*y for the second, etc).
2511//coordinateFeatures number is an important constant for convolution. If we perform 1x1 convolution, it is equal to number of features, but matrixConvolution should be equal to 1. For matrix convolution, it must be equal to matrixConvolution parameter. If we perform 2x2 convolution, it is equal to 3 for symmetric kernel (stored as xx, xy, yy) and 4 for nonsymmetric (stored as xx, xy, yx, yy). Similarly, 6 (stored as xx, xy, xz, yy, yz, zz) and 9 (stored as xx, xy, xz, yx, yy, yz, zx, zy, zz) for 3x3 convolutions. 
2512kernel_configuration.normalize = 1;
2513
2514//Initialize app_kernel and perform a single forward FFT like in examples before. You pass kernel as a buffer for the preparation stage.
2515
2516convolution_configuration = kernel_configuration;
2517convolution_configuration.kernelConvolution = 0;
2518convolution_configuration.performConvolution = 1;
2519convolution_configuration.symmetricKernel = 0;//Specify if convolution kernel is symmetric. In this case we only pass upper triangle part of it in the form of: (xx, xy, yy) for 2d and (xx, xy, xz, yy, yz, zz) for 3d.
2520convolution_configuration.matrixConvolution = 3;//we do matrix convolution, so kernel is 9 numbers (3x3), but vector dimension is 3
2521convolution_configuration.coordinateFeatures = 3;//equal to matrixConvolution size
2522
2523//Initialize app_convolution and perform a single forward FFT like in examples before. You pass kernel as kernel and system to be convolved with it as buffer
2524
2525\end{minted}
2526\end{mdframed}
2527
2528\subsection{Convolution application example: R2C cross-correlation between two
2529sets of N images}
2530
2531In this example, VkFFT is configured to calculate a kernel, represented
2532by three 2D vectors (RGB values of a pixel) and a system, also represented
2533by three 2D vectors. There are N kernels and N systems. Their cross-correlation
2534is a conjugate convolution in the frequency domain. Images are usually
2535stored as real, not complex numbers, so code uses R2C optimization
2536as well.
2537
2538\begin{mdframed}[backgroundcolor=bg]
2539\begin{minted}[tabsize=4,obeytabs,breaklines]{C}
2540//zero-initialize configuration + FFT application, we need two - one for kernel calculation
2541VkFFTConfiguration kernel_configuration = {};
2542VkFFTConfiguration convolution_configuration = {};
2543VkFFTApplication app_kernel = {};
2544VkFFTApplication app_convolution = {};
2545
2546
2547kernel_configuration.FFTdim = 2; //FFT dimension
2548kernel_configuration.size[0] = Nx;
2549kernel_configuration.size[1] = Ny; 
2550kernel_configuration.coordinateFeatures = 3;
2551kernel_configuration.numberBatches = N;
2552kernel_configuration.performR2C = 1;
2553kernel_configuration.normalize = 1;
2554
2555uint64_t bufferSize = (uint64_t)sizeof(float) * 2 * (kernel_configuration.size[0]/2+1) * kernel_configuration.size[1] * kernel_configuration.coordinateFeatures * kernel_configuration.numberBatches; 
2556	
2557kernel_configuration.kernelConvolution = 1; //specify if this plan is used to create kernel for convolution
2558
2559//Initialize app_kernel and perform a single forward FFT like in examples before. Pad in-place R2C system like this:
2560
2561for (uint64_t n = 0; n < kernel_configuration.numberBatches; n++) {
2562	for (uint64_t c = 0; c < kernel_configuration.coordinateFeatures; c++) {
2563		for (uint64_t j = 0; j < kernel_configuration.size[1]; j++) {
2564			for (uint64_t i = 0; i < kernel_configuration.size[0]; i++) {
2565				kernel_padded_GPU[i + j * 2 * (kernel_configuration.size[0]/2 + 1) + c * 2 * (kernel_configuration.size[0]/2 + 1) * kernel_configuration.size[1] + n * 2 * (kernel_configuration.size[0]/2 + 1) * kernel_configuration.size[1] * kernel_configuration.coordinateFeatures] = kernel_input[i + j * kernel_configuration.size[0] + c * kernel_configuration.size[0] * kernel_configuration.size[1] + n * kernel_configuration.size[0] * kernel_configuration.size[1] * kernel_configuration.coordinateFeatures];
2566			}
2567		}
2568	}
2569}
2570convolution_configuration = kernel_configuration;
2571convolution_configuration.kernelConvolution = 0;
2572convolution_configuration.performConvolution = 1;
2573convolution_configuration.conjugateConvolution = 1;
2574
2575//Initialize app_convolution and perform a single forward FFT like in examples before. Pad the system in the same way as the kernel
2576
2577\end{minted}
2578\end{mdframed}
2579
2580\subsection{Simple FFT application binary reuse application}
2581
2582This example shows how to save/load binaries generated by VkFFT. This
2583can reduce time taken by initializeVkFFT call by removing RTC components
2584from it. Be sure that rest of the configuration stays the same to
2585reuse the binary. Use rb/wb flags to load/save. This does not currently
2586work in Metal backend.
2587
2588\begin{mdframed}[backgroundcolor=bg]
2589\begin{minted}[tabsize=4,obeytabs,breaklines]{C}
2590VkFFTConfiguration configuration = {};
2591VkFFTApplication app = {};
2592
2593//configuration is initialized like in other examples
2594configuration.saveApplicationToString = 1;
2595//configuration.loadApplicationFromString = 1; //choose one to save/load binary file
2596
2597if (configuration.loadApplicationFromString) {
2598	FILE* kernelCache;
2599	uint64_t str_len;
2600	kernelCache = fopen("VkFFT_binary", "rb");
2601	fseek(kernelCache, 0, SEEK_END);
2602	str_len = ftell(kernelCache);
2603	fseek(kernelCache, 0, SEEK_SET);
2604	configuration.loadApplicationString = malloc(str_len);
2605	fread(configuration.loadApplicationString, str_len, 1, kernelCache);
2606	fclose(kernelCache);
2607}
2608
2609resFFT = initializeVkFFT(&app, configuration);
2610if (resFFT != VKFFT_SUCCESS) return resFFT;
2611
2612if (configuration.loadApplicationFromString)
2613	free(configuration.loadApplicationString);
2614
2615if (configuration.saveApplicationToString) {
2616	FILE* kernelCache;
2617	kernelCache = fopen("VkFFT_binary", "wb");
2618	fwrite(app.saveApplicationString, app.applicationStringSize, 1, kernelCache);
2619	fclose(kernelCache);
2620}
2621
2622//application is launched like in other examples
2623\end{minted}
2624\end{mdframed} 
2625\end{document}