1 
2 // =================================================================================================
3 // This file is part of the CLBlast project. The project is licensed under Apache Version 2.0. This
4 // project loosely follows the Google C++ styleguide and uses a tab-size of two spaces and a max-
5 // width of 100 characters per line.
6 //
7 // Author(s):
8 //   Cedric Nugteren <www.cedricnugteren.nl>
9 //
10 // This file implements the Routine base class (see the header for information about the class).
11 //
12 // =================================================================================================
13 
14 #include <string>
15 #include <vector>
16 #include <chrono>
17 #include <cstdlib>
18 
19 #include "routine.hpp"
20 
21 namespace clblast {
22 // =================================================================================================
23 
24 // For each kernel this map contains a list of routines it is used in
25 const std::vector<std::string> Routine::routines_axpy = {"AXPY", "COPY", "SCAL", "SWAP"};
26 const std::vector<std::string> Routine::routines_dot = {"AMAX", "ASUM", "DOT", "DOTC", "DOTU", "MAX", "MIN", "NRM2", "SUM"};
27 const std::vector<std::string> Routine::routines_ger = {"GER", "GERC", "GERU", "HER", "HER2", "HPR", "HPR2", "SPR", "SPR2", "SYR", "SYR2"};
28 const std::vector<std::string> Routine::routines_gemv = {"GBMV", "GEMV", "HBMV", "HEMV", "HPMV", "SBMV", "SPMV", "SYMV", "TMBV", "TPMV", "TRMV", "TRSV"};
29 const std::vector<std::string> Routine::routines_gemm = {"GEMM", "HEMM", "SYMM", "TRMM"};
30 const std::vector<std::string> Routine::routines_gemm_syrk = {"GEMM", "HEMM", "HER2K", "HERK", "SYMM", "SYR2K", "SYRK", "TRMM", "TRSM"};
31 const std::vector<std::string> Routine::routines_trsm = {"TRSM"};
32 const std::unordered_map<std::string, const std::vector<std::string>> Routine::routines_by_kernel = {
33   {"Xaxpy", routines_axpy},
34   {"Xdot", routines_dot},
35   {"Xgemv", routines_gemv},
36   {"XgemvFast", routines_gemv},
37   {"XgemvFastRot", routines_gemv},
38   {"Xtrsv", routines_gemv},
39   {"Xger", routines_ger},
40   {"Copy", routines_gemm_syrk},
41   {"Pad", routines_gemm_syrk},
42   {"Transpose", routines_gemm_syrk},
43   {"Padtranspose", routines_gemm_syrk},
44   {"Xgemm", routines_gemm_syrk},
45   {"XgemmDirect", routines_gemm},
46   {"KernelSelection", routines_gemm},
47   {"Invert", routines_trsm},
48 };
49 // =================================================================================================
50 
51 // The constructor does all heavy work, errors are returned as exceptions
Routine(Queue & queue,EventPointer event,const std::string & name,const std::vector<std::string> & kernel_names,const Precision precision,const std::vector<database::DatabaseEntry> & userDatabase,std::initializer_list<const char * > source)52 Routine::Routine(Queue &queue, EventPointer event, const std::string &name,
53                  const std::vector<std::string> &kernel_names, const Precision precision,
54                  const std::vector<database::DatabaseEntry> &userDatabase,
55                  std::initializer_list<const char *> source):
56     precision_(precision),
57     routine_name_(name),
58     kernel_names_(kernel_names),
59     queue_(queue),
60     event_(event),
61     context_(queue_.GetContext()),
62     device_(queue_.GetDevice()),
63     platform_(device_.Platform()),
64     db_(kernel_names) {
65 
66   InitDatabase(userDatabase);
67   InitProgram(source);
68 }
69 
InitDatabase(const std::vector<database::DatabaseEntry> & userDatabase)70 void Routine::InitDatabase(const std::vector<database::DatabaseEntry> &userDatabase) {
71   for (const auto &kernel_name : kernel_names_) {
72 
73     // Queries the cache to see whether or not the kernel parameter database is already there
74     bool has_db;
75     db_(kernel_name) = DatabaseCache::Instance().Get(DatabaseKeyRef{ platform_, device_(), precision_, kernel_name },
76                                                      &has_db);
77     if (has_db) { continue; }
78 
79     // Builds the parameter database for this device and routine set and stores it in the cache
80     db_(kernel_name) = Database(device_, kernel_name, precision_, userDatabase);
81     DatabaseCache::Instance().Store(DatabaseKey{ platform_, device_(), precision_, kernel_name },
82                                     Database{ db_(kernel_name) });
83   }
84 }
85 
InitProgram(std::initializer_list<const char * > source)86 void Routine::InitProgram(std::initializer_list<const char *> source) {
87 
88   // Queries the cache to see whether or not the program (context-specific) is already there
89   bool has_program;
90   program_ = ProgramCache::Instance().Get(ProgramKeyRef{ context_(), device_(), precision_, routine_name_ },
91                                           &has_program);
92   if (has_program) { return; }
93 
94   // Sets the build options from an environmental variable (if set)
95   auto options = std::vector<std::string>();
96   const auto environment_variable = std::getenv("CLBLAST_BUILD_OPTIONS");
97   if (environment_variable != nullptr) {
98     options.push_back(std::string(environment_variable));
99   }
100 
101   // Queries the cache to see whether or not the binary (device-specific) is already there. If it
102   // is, a program is created and stored in the cache
103   const auto device_name = GetDeviceName(device_);
104   bool has_binary;
105   auto binary = BinaryCache::Instance().Get(BinaryKeyRef{ precision_, routine_name_, device_name },
106                                             &has_binary);
107   if (has_binary) {
108     program_ = Program(device_, context_, binary);
109     program_.Build(device_, options);
110     ProgramCache::Instance().Store(ProgramKey{ context_(), device_(), precision_, routine_name_ },
111                                    Program{ program_ });
112     return;
113   }
114 
115   // Otherwise, the kernel will be compiled and program will be built. Both the binary and the
116   // program will be added to the cache.
117 
118   // Inspects whether or not cl_khr_fp64 is supported in case of double precision
119   if ((precision_ == Precision::kDouble && !PrecisionSupported<double>(device_)) ||
120       (precision_ == Precision::kComplexDouble && !PrecisionSupported<double2>(device_))) {
121     throw RuntimeErrorCode(StatusCode::kNoDoublePrecision);
122   }
123 
124   // As above, but for cl_khr_fp16 (half precision)
125   if (precision_ == Precision::kHalf && !PrecisionSupported<half>(device_)) {
126     throw RuntimeErrorCode(StatusCode::kNoHalfPrecision);
127   }
128 
129   // Collects the parameters for this device in the form of defines, and adds the precision
130   auto source_string = std::string{""};
131   for (const auto &kernel_name : kernel_names_) {
132     source_string += db_(kernel_name).GetDefines();
133   }
134   source_string += "#define PRECISION "+ToString(static_cast<int>(precision_))+"\n";
135 
136   // Adds the name of the routine as a define
137   source_string += "#define ROUTINE_"+routine_name_+"\n";
138 
139   // Not all OpenCL compilers support the 'inline' keyword. The keyword is only used for devices on
140   // which it is known to work with all OpenCL platforms.
141   if (device_.IsNVIDIA() || device_.IsARM()) {
142     source_string += "#define USE_INLINE_KEYWORD 1\n";
143   }
144 
145   // For specific devices, use the non-IEE754 compliant OpenCL mad() instruction. This can improve
146   // performance, but might result in a reduced accuracy.
147   if (device_.IsAMD() && device_.IsGPU()) {
148     source_string += "#define USE_CL_MAD 1\n";
149   }
150 
151   // For specific devices, use staggered/shuffled workgroup indices.
152   if (device_.IsAMD() && device_.IsGPU()) {
153     source_string += "#define USE_STAGGERED_INDICES 1\n";
154   }
155 
156   // For specific devices add a global synchronisation barrier to the GEMM kernel to optimize
157   // performance through better cache behaviour
158   if (device_.IsARM() && device_.IsGPU()) {
159     source_string += "#define GLOBAL_MEM_FENCE 1\n";
160   }
161 
162   // Loads the common header (typedefs and defines and such)
163   source_string +=
164     #include "kernels/common.opencl"
165   ;
166 
167   // Adds routine-specific code to the constructed source string
168   for (const char *s: source) {
169     source_string += s;
170   }
171 
172   // Prints details of the routine to compile in case of debugging in verbose mode
173   #ifdef VERBOSE
174     printf("[DEBUG] Compiling routine '%s-%s' for device '%s'\n",
175            routine_name_.c_str(), ToString(precision_).c_str(), device_name.c_str());
176     const auto start_time = std::chrono::steady_clock::now();
177   #endif
178 
179   // Compiles the kernel
180   program_ = Program(context_, source_string);
181   try {
182     program_.Build(device_, options);
183   } catch (const CLError &e) {
184     if (e.status() == CL_BUILD_PROGRAM_FAILURE) {
185       fprintf(stdout, "OpenCL compiler error/warning: %s\n",
186               program_.GetBuildInfo(device_).c_str());
187     }
188     throw;
189   }
190 
191   // Store the compiled binary and program in the cache
192   BinaryCache::Instance().Store(BinaryKey{ precision_, routine_name_, device_name },
193                                 program_.GetIR());
194 
195   ProgramCache::Instance().Store(ProgramKey{ context_(), device_(), precision_, routine_name_ },
196                                  Program{ program_ });
197 
198   // Prints the elapsed compilation time in case of debugging in verbose mode
199   #ifdef VERBOSE
200     const auto elapsed_time = std::chrono::steady_clock::now() - start_time;
201     const auto timing = std::chrono::duration<double,std::milli>(elapsed_time).count();
202     printf("[DEBUG] Completed compilation in %.2lf ms\n", timing);
203   #endif
204 }
205 
206 // =================================================================================================
207 } // namespace clblast
208