vulkan-shaders-gen.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646
  1. #include <iostream>
  2. #include <fstream>
  3. #include <sstream>
  4. #include <string>
  5. #include <stdexcept>
  6. #include <array>
  7. #include <vector>
  8. #include <map>
  9. #include <thread>
  10. #include <mutex>
  11. #include <future>
  12. #include <queue>
  13. #include <condition_variable>
  14. #include <cstdio>
  15. #include <cstring>
  16. #include <cstdlib>
  17. #include <cassert>
  18. #include <algorithm>
  19. #include <sys/stat.h>
  20. #include <sys/types.h>
  21. #ifdef _WIN32
  22. #include <windows.h>
  23. #include <direct.h> // For _mkdir on Windows
  24. #else
  25. #include <unistd.h>
  26. #include <sys/wait.h>
  27. #include <fcntl.h>
  28. #endif
  29. #define ASYNCIO_CONCURRENCY 64
  30. std::mutex lock;
  31. std::vector<std::pair<std::string, std::string>> shader_fnames;
  32. std::string GLSLC = "glslc";
  33. std::string input_dir = "vulkan-shaders";
  34. std::string output_dir = "/tmp";
  35. std::string target_hpp = "ggml-vulkan-shaders.hpp";
  36. std::string target_cpp = "ggml-vulkan-shaders.cpp";
  37. bool no_clean = false;
  38. const std::vector<std::string> type_names = {
  39. "f32",
  40. "f16",
  41. "q4_0",
  42. "q4_1",
  43. "q5_0",
  44. "q5_1",
  45. "q8_0",
  46. "q2_k",
  47. "q3_k",
  48. "q4_k",
  49. "q5_k",
  50. "q6_k",
  51. "iq1_s",
  52. "iq1_m",
  53. "iq2_xxs",
  54. "iq2_xs",
  55. "iq2_s",
  56. "iq3_xxs",
  57. "iq3_s",
  58. "iq4_xs",
  59. "iq4_nl"
  60. };
  61. namespace {
  62. void execute_command(const std::string& command, std::string& stdout_str, std::string& stderr_str) {
  63. #ifdef _WIN32
  64. HANDLE stdout_read, stdout_write;
  65. HANDLE stderr_read, stderr_write;
  66. SECURITY_ATTRIBUTES sa = { sizeof(SECURITY_ATTRIBUTES), NULL, TRUE };
  67. if (!CreatePipe(&stdout_read, &stdout_write, &sa, 0) ||
  68. !SetHandleInformation(stdout_read, HANDLE_FLAG_INHERIT, 0)) {
  69. throw std::runtime_error("Failed to create stdout pipe");
  70. }
  71. if (!CreatePipe(&stderr_read, &stderr_write, &sa, 0) ||
  72. !SetHandleInformation(stderr_read, HANDLE_FLAG_INHERIT, 0)) {
  73. throw std::runtime_error("Failed to create stderr pipe");
  74. }
  75. PROCESS_INFORMATION pi;
  76. STARTUPINFOA si = {};
  77. si.cb = sizeof(STARTUPINFOA);
  78. si.dwFlags = STARTF_USESTDHANDLES;
  79. si.hStdOutput = stdout_write;
  80. si.hStdError = stderr_write;
  81. std::vector<char> cmd(command.begin(), command.end());
  82. cmd.push_back('\0');
  83. if (!CreateProcessA(NULL, cmd.data(), NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi)) {
  84. throw std::runtime_error("Failed to create process");
  85. }
  86. CloseHandle(stdout_write);
  87. CloseHandle(stderr_write);
  88. std::array<char, 128> buffer;
  89. DWORD bytes_read;
  90. while (ReadFile(stdout_read, buffer.data(), (DWORD)buffer.size(), &bytes_read, NULL) && bytes_read > 0) {
  91. stdout_str.append(buffer.data(), bytes_read);
  92. }
  93. while (ReadFile(stderr_read, buffer.data(), (DWORD)buffer.size(), &bytes_read, NULL) && bytes_read > 0) {
  94. stderr_str.append(buffer.data(), bytes_read);
  95. }
  96. CloseHandle(stdout_read);
  97. CloseHandle(stderr_read);
  98. WaitForSingleObject(pi.hProcess, INFINITE);
  99. CloseHandle(pi.hProcess);
  100. CloseHandle(pi.hThread);
  101. #else
  102. int stdout_pipe[2];
  103. int stderr_pipe[2];
  104. if (pipe(stdout_pipe) != 0 || pipe(stderr_pipe) != 0) {
  105. throw std::runtime_error("Failed to create pipes");
  106. }
  107. pid_t pid = fork();
  108. if (pid < 0) {
  109. throw std::runtime_error("Failed to fork process");
  110. }
  111. if (pid == 0) {
  112. close(stdout_pipe[0]);
  113. close(stderr_pipe[0]);
  114. dup2(stdout_pipe[1], STDOUT_FILENO);
  115. dup2(stderr_pipe[1], STDERR_FILENO);
  116. close(stdout_pipe[1]);
  117. close(stderr_pipe[1]);
  118. execl("/bin/sh", "sh", "-c", command.c_str(), (char*) nullptr);
  119. _exit(EXIT_FAILURE);
  120. } else {
  121. close(stdout_pipe[1]);
  122. close(stderr_pipe[1]);
  123. std::array<char, 128> buffer;
  124. ssize_t bytes_read;
  125. while ((bytes_read = read(stdout_pipe[0], buffer.data(), buffer.size())) > 0) {
  126. stdout_str.append(buffer.data(), bytes_read);
  127. }
  128. while ((bytes_read = read(stderr_pipe[0], buffer.data(), buffer.size())) > 0) {
  129. stderr_str.append(buffer.data(), bytes_read);
  130. }
  131. close(stdout_pipe[0]);
  132. close(stderr_pipe[0]);
  133. waitpid(pid, nullptr, 0);
  134. }
  135. #endif
  136. }
  137. bool directory_exists(const std::string& path) {
  138. struct stat info;
  139. if (stat(path.c_str(), &info) != 0) {
  140. return false; // Path doesn't exist or can't be accessed
  141. }
  142. return (info.st_mode & S_IFDIR) != 0; // Check if it is a directory
  143. }
  144. bool create_directory(const std::string& path) {
  145. #ifdef _WIN32
  146. return _mkdir(path.c_str()) == 0 || errno == EEXIST; // EEXIST means the directory already exists
  147. #else
  148. return mkdir(path.c_str(), 0755) == 0 || errno == EEXIST; // 0755 is the directory permissions
  149. #endif
  150. }
  151. std::string to_uppercase(const std::string& input) {
  152. std::string result = input;
  153. for (char& c : result) {
  154. c = std::toupper(c);
  155. }
  156. return result;
  157. }
  158. bool string_starts_with(const std::string& str, const std::string& prefix) {
  159. if (prefix.size() > str.size()) {
  160. return false;
  161. }
  162. return std::equal(prefix.begin(), prefix.end(), str.begin());
  163. }
  164. bool string_ends_with(const std::string& str, const std::string& suffix) {
  165. if (suffix.size() > str.size()) {
  166. return false;
  167. }
  168. return std::equal(suffix.rbegin(), suffix.rend(), str.rbegin());
  169. }
  170. static const char path_separator = '/';
  171. std::string join_paths(const std::string& path1, const std::string& path2) {
  172. return path1 + path_separator + path2;
  173. }
  174. std::string basename(const std::string &path) {
  175. return path.substr(path.find_last_of("/\\") + 1);
  176. }
  177. // variables to track number of compiles in progress
  178. static uint32_t compile_count = 0;
  179. static std::mutex compile_count_mutex;
  180. static std::condition_variable compile_count_cond;
  181. void string_to_spv_func(const std::string& _name, const std::string& in_fname, const std::map<std::string, std::string>& defines, bool fp16 = true, bool coopmat = false, bool coopmat2 = false, bool f16acc = false) {
  182. std::string name = _name + (f16acc ? "_f16acc" : "") + (coopmat ? "_coopmat" : "") + (coopmat2 ? "_cm2" : (fp16 ? "" : "_fp32"));
  183. std::string out_fname = join_paths(output_dir, name + ".spv");
  184. std::string in_path = join_paths(input_dir, in_fname);
  185. std::string target_env = (name.find("_cm2") != std::string::npos) ? "--target-env=vulkan1.3" : "--target-env=vulkan1.2";
  186. // disable spirv-opt for coopmat shaders for https://github.com/ggerganov/llama.cpp/issues/10734
  187. std::string opt_level = coopmat ? "" : "-O";
  188. #ifdef _WIN32
  189. std::vector<std::string> cmd = {GLSLC, "-fshader-stage=compute", target_env, opt_level, "\"" + in_path + "\"", "-o", "\"" + out_fname + "\""};
  190. #else
  191. std::vector<std::string> cmd = {GLSLC, "-fshader-stage=compute", target_env, opt_level, in_path, "-o", out_fname};
  192. #endif
  193. #ifdef GGML_VULKAN_SHADER_DEBUG_INFO
  194. cmd.push_back("-g");
  195. #endif
  196. for (const auto& define : defines) {
  197. cmd.push_back("-D" + define.first + "=" + define.second);
  198. }
  199. std::string command;
  200. for (const auto& part : cmd) {
  201. command += part + " ";
  202. }
  203. std::string stdout_str, stderr_str;
  204. try {
  205. // std::cout << "Executing command: ";
  206. // for (const auto& part : cmd) {
  207. // std::cout << part << " ";
  208. // }
  209. // std::cout << std::endl;
  210. execute_command(command, stdout_str, stderr_str);
  211. if (!stderr_str.empty()) {
  212. std::cerr << "cannot compile " << name << "\n\n" << command << "\n\n" << stderr_str << std::endl;
  213. return;
  214. }
  215. std::lock_guard<std::mutex> guard(lock);
  216. shader_fnames.push_back(std::make_pair(name, out_fname));
  217. } catch (const std::exception& e) {
  218. std::cerr << "Error executing command for " << name << ": " << e.what() << std::endl;
  219. }
  220. {
  221. std::lock_guard<std::mutex> guard(compile_count_mutex);
  222. assert(compile_count > 0);
  223. compile_count--;
  224. }
  225. compile_count_cond.notify_all();
  226. }
  227. std::map<std::string, std::string> merge_maps(const std::map<std::string, std::string>& a, const std::map<std::string, std::string>& b) {
  228. std::map<std::string, std::string> result = a;
  229. result.insert(b.begin(), b.end());
  230. return result;
  231. }
  232. static std::vector<std::future<void>> compiles;
  233. void string_to_spv(const std::string& _name, const std::string& in_fname, const std::map<std::string, std::string>& defines, bool fp16 = true, bool coopmat = false, bool coopmat2 = false, bool f16acc = false) {
  234. {
  235. // wait until fewer than N compiles are in progress.
  236. // 16 is an arbitrary limit, the goal is to avoid "failed to create pipe" errors.
  237. uint32_t N = 16;
  238. std::unique_lock<std::mutex> guard(compile_count_mutex);
  239. while (compile_count >= N) {
  240. compile_count_cond.wait(guard);
  241. }
  242. compile_count++;
  243. }
  244. compiles.push_back(std::async(string_to_spv_func, _name, in_fname, defines, fp16, coopmat, coopmat2, f16acc));
  245. }
  246. void matmul_shaders(bool fp16, bool matmul_id, bool coopmat, bool coopmat2, bool f16acc) {
  247. std::string load_vec = coopmat2 ? "1" : fp16 ? "8" : "4";
  248. std::string aligned_b_type_f32 = coopmat2 ? "float" : fp16 ? "mat2x4" : "vec4";
  249. std::string aligned_b_type_f16 = coopmat2 ? "float16_t" : fp16 ? "f16mat2x4" : "f16vec4";
  250. std::map<std::string, std::string> base_dict = {{"FLOAT_TYPE", (coopmat2 || fp16) ? "float16_t" : "float"}};
  251. std::string shader_name = "matmul";
  252. if (matmul_id) {
  253. base_dict["MUL_MAT_ID"] = "1";
  254. shader_name = "matmul_id";
  255. }
  256. if (fp16) {
  257. base_dict["FLOAT16"] = "1";
  258. }
  259. base_dict["ACC_TYPE"] = f16acc ? "float16_t" : "float";
  260. if (coopmat) {
  261. base_dict["COOPMAT"] = "1";
  262. }
  263. base_dict["ACC_TYPE"] = f16acc ? "float16_t" : "float";
  264. std::string source_name = coopmat2 ? "mul_mm_cm2.comp" : "mul_mm.comp";
  265. // Shaders with f16 B_TYPE
  266. string_to_spv(shader_name + "_f32_f16", source_name, merge_maps(base_dict, {{"DATA_A_F32", "1"}, {"B_TYPE", "float16_t"}, {"D_TYPE", "float"}, }), fp16, coopmat, coopmat2, f16acc);
  267. string_to_spv(shader_name + "_f32_f16_aligned", source_name, merge_maps(base_dict, {{"DATA_A_F32", "1"}, {"LOAD_VEC_A", load_vec}, {"LOAD_VEC_B", load_vec}, {"B_TYPE", aligned_b_type_f16}, {"D_TYPE", "float"}, {"ALIGNED", "1"}}), fp16, coopmat, coopmat2, f16acc);
  268. string_to_spv(shader_name + "_f16_aligned", source_name, merge_maps(base_dict, {{"DATA_A_F16", "1"}, {"LOAD_VEC_A", load_vec}, {"LOAD_VEC_B", load_vec}, {"B_TYPE", aligned_b_type_f16}, {"D_TYPE", "float"}, {"ALIGNED", "1"}}), fp16, coopmat, coopmat2, f16acc);
  269. string_to_spv(shader_name + "_f16", source_name, merge_maps(base_dict, {{"DATA_A_F16", "1"}, {"B_TYPE", "float16_t"}, {"D_TYPE", "float"}}), fp16, coopmat, coopmat2, f16acc);
  270. for (const auto& tname : type_names) {
  271. std::string load_vec_quant = "2";
  272. if ((tname == "q4_0") || (tname == "q4_1"))
  273. load_vec_quant = "8";
  274. else if ((tname == "q5_0") || (tname == "q5_1") || (tname == "q8_0") || (tname == "iq4_nl"))
  275. load_vec_quant = "4";
  276. std::string data_a_key = "DATA_A_" + to_uppercase(tname);
  277. // For unaligned, load one at a time for f32/f16, or two at a time for quants
  278. std::string load_vec_a_unaligned = (coopmat2 || tname == "f32" || tname == "f16") ? "1" : load_vec_quant;
  279. // For aligned matmul loads
  280. std::string load_vec_a = (coopmat2 || tname == "f32" || tname == "f16") ? load_vec : load_vec_quant;
  281. // don't generate f32 variants for coopmat2
  282. if (!coopmat2) {
  283. string_to_spv(shader_name + "_" + tname + "_f32", source_name, merge_maps(base_dict, {{data_a_key, "1"}, {"LOAD_VEC_A", load_vec_a_unaligned}, {"B_TYPE", "float"}, {"D_TYPE", "float"}, {"B_IS_FLOAT", "1"}}), fp16, coopmat, coopmat2, f16acc);
  284. string_to_spv(shader_name + "_" + tname + "_f32_aligned", source_name, merge_maps(base_dict, {{data_a_key, "1"}, {"LOAD_VEC_A", load_vec_a}, {"LOAD_VEC_B", load_vec}, {"B_TYPE", aligned_b_type_f32}, {"D_TYPE", "float"}, {"B_IS_FLOAT", "1"}, {"ALIGNED", "1"}}), fp16, coopmat, coopmat2, f16acc);
  285. }
  286. if (tname != "f16" && tname != "f32") {
  287. string_to_spv(shader_name + "_" + tname + "_f16", source_name, merge_maps(base_dict, {{data_a_key, "1"}, {"LOAD_VEC_A", load_vec_a_unaligned}, {"B_TYPE", "float16_t"}, {"D_TYPE", "float"}, {"B_IS_FLOAT", "1"}}), fp16, coopmat, coopmat2, f16acc);
  288. string_to_spv(shader_name + "_" + tname + "_f16_aligned", source_name, merge_maps(base_dict, {{data_a_key, "1"}, {"LOAD_VEC_A", load_vec_a}, {"LOAD_VEC_B", load_vec}, {"B_TYPE", aligned_b_type_f16}, {"D_TYPE", "float"}, {"B_IS_FLOAT", "1"}, {"ALIGNED", "1"}}), fp16, coopmat, coopmat2, f16acc);
  289. }
  290. }
  291. }
  292. void process_shaders() {
  293. std::cout << "ggml_vulkan: Generating and compiling shaders to SPIR-V" << std::endl;
  294. std::map<std::string, std::string> base_dict = {{"FLOAT_TYPE", "float"}};
  295. // matmul
  296. for (const auto& matmul_id : {false, true}) {
  297. // No coopmats
  298. // fp32
  299. matmul_shaders(false, matmul_id, false, false, false);
  300. // fp16, fp32acc and fp16acc
  301. matmul_shaders(true, matmul_id, false, false, false);
  302. matmul_shaders(true, matmul_id, false, false, true);
  303. #if defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  304. // Coopmat, fp32acc and fp16acc
  305. matmul_shaders(true, matmul_id, true, false, false);
  306. matmul_shaders(true, matmul_id, true, false, true);
  307. #endif
  308. #if defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  309. // Coopmat2, fp32acc and fp16acc
  310. matmul_shaders(true, matmul_id, false, true, false);
  311. matmul_shaders(true, matmul_id, false, true, true);
  312. #endif
  313. }
  314. #if defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  315. // flash attention
  316. for (const auto& f16acc : {false, true}) {
  317. std::string acctype = f16acc ? "float16_t" : "float";
  318. for (const auto& tname : type_names) {
  319. if (tname == "f32") {
  320. continue;
  321. }
  322. if (tname == "f16") {
  323. string_to_spv("flash_attn_f32_f16_" + tname, "flash_attn_cm2.comp",
  324. merge_maps(base_dict, {{"Q_TYPE", "float"}, {"D_TYPE", "float"}, {"ACC_TYPE", acctype}}), true, false, true, f16acc);
  325. } else {
  326. std::string data_a_key = "DATA_A_" + to_uppercase(tname);
  327. string_to_spv("flash_attn_f32_f16_" + tname, "flash_attn_cm2.comp",
  328. merge_maps(base_dict, {{data_a_key, "1"}, {"Q_TYPE", "float"}, {"D_TYPE", "float"}, {"ACC_TYPE", acctype}, {"DEQUANTFUNC", "dequantFunc"+to_uppercase(tname) }, {"BLOCK_SIZE", "QUANT_K_"+to_uppercase(tname) }}), true, false, true, f16acc);
  329. }
  330. }
  331. }
  332. #endif
  333. for (const auto& tname : type_names) {
  334. // mul mat vec
  335. std::string data_a_key = "DATA_A_" + to_uppercase(tname);
  336. std::string shader = (string_ends_with(tname, "_k") || string_starts_with(tname, "iq1_") || string_starts_with(tname, "iq2_") || string_starts_with(tname, "iq3_")) ? "mul_mat_vec_" + tname + ".comp" : "mul_mat_vec.comp";
  337. string_to_spv("mul_mat_vec_" + tname + "_f32_f32", shader, merge_maps(base_dict, {{data_a_key, "1"}, {"B_TYPE", "float"}, {"B_TYPE_VEC2", "vec2"}, {"B_TYPE_VEC4", "vec4"}, {"D_TYPE", "float"}}));
  338. string_to_spv("mul_mat_vec_" + tname + "_f16_f32", shader, merge_maps(base_dict, {{data_a_key, "1"}, {"B_TYPE", "float16_t"}, {"B_TYPE_VEC2", "f16vec2"}, {"B_TYPE_VEC4", "f16vec4"}, {"D_TYPE", "float"}}));
  339. string_to_spv("mul_mat_vec_id_" + tname + "_f32", shader, merge_maps(base_dict, {{"MUL_MAT_ID", "1"}, {data_a_key, "1"}, {"B_TYPE", "float"}, {"B_TYPE_VEC2", "vec2"}, {"B_TYPE_VEC4", "vec4"}, {"D_TYPE", "float"}}));
  340. // Dequant shaders
  341. if (tname != "f16") {
  342. string_to_spv("dequant_" + tname, "dequant_" + tname + ".comp", merge_maps(base_dict, {{data_a_key, "1"}, {"D_TYPE", "float16_t"}}));
  343. }
  344. if (!string_ends_with(tname, "_k")) {
  345. shader = (tname == "f32" || tname == "f16") ? "get_rows.comp" : "get_rows_quant.comp";
  346. if (tname == "f16") {
  347. string_to_spv("get_rows_" + tname, shader, merge_maps(base_dict, {{data_a_key, "1"}, {"B_TYPE", "int"}, {"D_TYPE", "float16_t"}, {"OPTIMIZATION_ERROR_WORKAROUND", "1"}}));
  348. } else {
  349. string_to_spv("get_rows_" + tname, shader, merge_maps(base_dict, {{data_a_key, "1"}, {"B_TYPE", "int"}, {"D_TYPE", "float16_t"}}));
  350. }
  351. string_to_spv("get_rows_" + tname + "_f32", shader, merge_maps(base_dict, {{data_a_key, "1"}, {"B_TYPE", "int"}, {"D_TYPE", "float"}}));
  352. }
  353. }
  354. string_to_spv("mul_mat_vec_p021_f16_f32", "mul_mat_vec_p021.comp", {{"A_TYPE", "float16_t"}, {"B_TYPE", "float"}, {"D_TYPE", "float"}});
  355. string_to_spv("mul_mat_vec_nc_f16_f32", "mul_mat_vec_nc.comp", {{"A_TYPE", "float16_t"}, {"B_TYPE", "float"}, {"D_TYPE", "float"}});
  356. // Norms
  357. string_to_spv("norm_f32", "norm.comp", merge_maps(base_dict, {{"A_TYPE", "float"}, {"D_TYPE", "float"}}));
  358. string_to_spv("group_norm_f32", "group_norm.comp", merge_maps(base_dict, {{"A_TYPE", "float"}, {"D_TYPE", "float"}}));
  359. string_to_spv("rms_norm_f32", "rms_norm.comp", merge_maps(base_dict, {{"A_TYPE", "float"}, {"D_TYPE", "float"}}));
  360. string_to_spv("rms_norm_back_f32", "rms_norm_back.comp", merge_maps(base_dict, {{"A_TYPE", "float"}, {"B_TYPE", "float"}, {"D_TYPE", "float"}}));
  361. string_to_spv("l2_norm_f32", "l2_norm.comp", merge_maps(base_dict, {{"A_TYPE", "float"}, {"D_TYPE", "float"}}));
  362. string_to_spv("cpy_f32_f32", "copy.comp", {{"A_TYPE", "float"}, {"D_TYPE", "float"}});
  363. string_to_spv("cpy_f32_f16", "copy.comp", {{"A_TYPE", "float"}, {"D_TYPE", "float16_t"}});
  364. string_to_spv("cpy_f16_f16", "copy.comp", {{"A_TYPE", "float16_t"}, {"D_TYPE", "float16_t"}, {"OPTIMIZATION_ERROR_WORKAROUND", "1"}});
  365. string_to_spv("contig_cpy_f32_f32", "contig_copy.comp", {{"A_TYPE", "float"}, {"D_TYPE", "float"}});
  366. string_to_spv("contig_cpy_f32_f16", "contig_copy.comp", {{"A_TYPE", "float"}, {"D_TYPE", "float16_t"}});
  367. string_to_spv("contig_cpy_f16_f16", "contig_copy.comp", {{"A_TYPE", "float16_t"}, {"D_TYPE", "float16_t"}, {"OPTIMIZATION_ERROR_WORKAROUND", "1"}});
  368. for (std::string t : {"q4_0", "q4_1", "q5_0", "q5_1", "q8_0", "iq4_nl"}) {
  369. string_to_spv("cpy_f32_" + t, "copy_to_quant.comp", {{"DATA_A_" + to_uppercase(t), "1"}, {"D_TYPE", "float"}, {"FLOAT_TYPE", "float"}});
  370. string_to_spv("cpy_" + t + "_f32", "copy_from_quant.comp", {{"DATA_A_" + to_uppercase(t), "1"}, {"D_TYPE", "float"}, {"FLOAT_TYPE", "float"}});
  371. }
  372. string_to_spv("add_f32", "add.comp", {{"A_TYPE", "float"}, {"B_TYPE", "float"}, {"D_TYPE", "float"}, {"FLOAT_TYPE", "float"}});
  373. string_to_spv("add_f16_f32_f16", "add.comp", {{"A_TYPE", "float16_t"}, {"B_TYPE", "float"}, {"D_TYPE", "float16_t"}, {"FLOAT_TYPE", "float"}});
  374. string_to_spv("sub_f32", "sub.comp", {{"A_TYPE", "float"}, {"B_TYPE", "float"}, {"D_TYPE", "float"}, {"FLOAT_TYPE", "float"}});
  375. string_to_spv("acc_f32", "acc.comp", {{"A_TYPE", "float"}, {"B_TYPE", "float"}, {"D_TYPE", "float"}, {"FLOAT_TYPE", "float"}});
  376. string_to_spv("split_k_reduce", "mul_mat_split_k_reduce.comp", {});
  377. string_to_spv("mul_f32", "mul.comp", {{"A_TYPE", "float"}, {"B_TYPE", "float"}, {"D_TYPE", "float"}, {"FLOAT_TYPE", "float"}});
  378. string_to_spv("div_f32", "div.comp", {{"A_TYPE", "float"}, {"B_TYPE", "float"}, {"D_TYPE", "float"}, {"FLOAT_TYPE", "float"}});
  379. string_to_spv("repeat_f32", "repeat.comp", {{"A_TYPE", "float"}, {"D_TYPE", "float"}});
  380. string_to_spv("repeat_back_f32", "repeat_back.comp", {{"A_TYPE", "float"}, {"D_TYPE", "float"}});
  381. string_to_spv("scale_f32", "scale.comp", {{"A_TYPE", "float"}, {"D_TYPE", "float"}, {"FLOAT_TYPE", "float"}});
  382. string_to_spv("sqr_f32", "square.comp", {{"A_TYPE", "float"}, {"D_TYPE", "float"}, {"FLOAT_TYPE", "float"}});
  383. string_to_spv("sin_f32", "sin.comp", {{"A_TYPE", "float"}, {"D_TYPE", "float"}, {"FLOAT_TYPE", "float"}});
  384. string_to_spv("cos_f32", "cos.comp", {{"A_TYPE", "float"}, {"D_TYPE", "float"}, {"FLOAT_TYPE", "float"}});
  385. string_to_spv("clamp_f32", "clamp.comp", {{"A_TYPE", "float"}, {"D_TYPE", "float"}, {"FLOAT_TYPE", "float"}});
  386. string_to_spv("pad_f32", "pad.comp", {{"A_TYPE", "float"}, {"D_TYPE", "float"}});
  387. string_to_spv("concat_f32", "concat.comp", {{"A_TYPE", "float"}, {"B_TYPE", "float"}, {"D_TYPE", "float"}});
  388. string_to_spv("concat_f16", "concat.comp", {{"A_TYPE", "float16_t"}, {"B_TYPE", "float16_t"}, {"D_TYPE", "float16_t"}, {"OPTIMIZATION_ERROR_WORKAROUND", "1"}});
  389. string_to_spv("concat_i32", "concat.comp", {{"A_TYPE", "int"}, {"B_TYPE", "int"}, {"D_TYPE", "int"}});
  390. string_to_spv("upscale_f32", "upscale.comp", {{"A_TYPE", "float"}, {"B_TYPE", "float"}, {"D_TYPE", "float"}});
  391. string_to_spv("gelu_f32", "gelu.comp", {{"A_TYPE", "float"}, {"D_TYPE", "float"}});
  392. string_to_spv("gelu_quick_f32", "gelu_quick.comp", {{"A_TYPE", "float"}, {"D_TYPE", "float"}});
  393. string_to_spv("silu_f32", "silu.comp", {{"A_TYPE", "float"}, {"D_TYPE", "float"}});
  394. string_to_spv("silu_back_f32", "silu_back.comp", {{"A_TYPE", "float"}, {"B_TYPE", "float"}, {"D_TYPE", "float"}});
  395. string_to_spv("relu_f32", "relu.comp", {{"A_TYPE", "float"}, {"D_TYPE", "float"}});
  396. string_to_spv("leaky_relu_f32", "leaky_relu.comp", {{"A_TYPE", "float"}, {"D_TYPE", "float"}});
  397. string_to_spv("tanh_f32", "tanh.comp", {{"A_TYPE", "float"}, {"D_TYPE", "float"}});
  398. string_to_spv("sigmoid_f32", "sigmoid.comp", {{"A_TYPE", "float"}, {"D_TYPE", "float"}});
  399. string_to_spv("diag_mask_inf_f32", "diag_mask_inf.comp", {{"A_TYPE", "float"}, {"D_TYPE", "float"}});
  400. string_to_spv("soft_max_f32", "soft_max.comp", merge_maps(base_dict, {{"A_TYPE", "float"}, {"B_TYPE", "float"}, {"D_TYPE", "float"}}));
  401. string_to_spv("soft_max_f32_f16", "soft_max.comp", merge_maps(base_dict, {{"A_TYPE", "float"}, {"B_TYPE", "float16_t"}, {"D_TYPE", "float"}}));
  402. string_to_spv("soft_max_back_f32", "soft_max_back.comp", merge_maps(base_dict, {{"A_TYPE", "float"}, {"B_TYPE", "float"}, {"D_TYPE", "float"}}));
  403. string_to_spv("rope_norm_f32", "rope_norm.comp", {{"A_TYPE", "float"}, {"D_TYPE", "float"}});
  404. string_to_spv("rope_norm_f16", "rope_norm.comp", {{"A_TYPE", "float16_t"}, {"D_TYPE", "float16_t"}});
  405. string_to_spv("rope_norm_f16_rte", "rope_norm.comp", {{"A_TYPE", "float16_t"}, {"D_TYPE", "float16_t"}, {"RTE16", "1"}});
  406. string_to_spv("rope_neox_f32", "rope_neox.comp", {{"A_TYPE", "float"}, {"D_TYPE", "float"}});
  407. string_to_spv("rope_neox_f16", "rope_neox.comp", {{"A_TYPE", "float16_t"}, {"D_TYPE", "float16_t"}});
  408. string_to_spv("rope_neox_f16_rte", "rope_neox.comp", {{"A_TYPE", "float16_t"}, {"D_TYPE", "float16_t"}, {"RTE16", "1"}});
  409. string_to_spv("rope_multi_f32", "rope_multi.comp", {{"A_TYPE", "float"}, {"D_TYPE", "float"}});
  410. string_to_spv("rope_multi_f16", "rope_multi.comp", {{"A_TYPE", "float16_t"}, {"D_TYPE", "float16_t"}});
  411. string_to_spv("rope_multi_f16_rte", "rope_multi.comp", {{"A_TYPE", "float16_t"}, {"D_TYPE", "float16_t"}, {"RTE16", "1"}});
  412. string_to_spv("rope_vision_f32", "rope_vision.comp", {{"A_TYPE", "float"}, {"D_TYPE", "float"}});
  413. string_to_spv("rope_vision_f16", "rope_vision.comp", {{"A_TYPE", "float16_t"}, {"D_TYPE", "float16_t"}});
  414. string_to_spv("rope_vision_f16_rte", "rope_vision.comp", {{"A_TYPE", "float16_t"}, {"D_TYPE", "float16_t"}, {"RTE16", "1"}});
  415. string_to_spv("argsort_f32", "argsort.comp", {{"A_TYPE", "float"}});
  416. string_to_spv("argmax_f32", "argmax.comp", merge_maps(base_dict, {{"A_TYPE", "float"}, {"D_TYPE", "int"}}));
  417. string_to_spv("sum_rows_f32", "sum_rows.comp", merge_maps(base_dict, {{"A_TYPE", "float"}, {"D_TYPE", "float"}}));
  418. string_to_spv("count_equal_i32", "count_equal.comp", merge_maps(base_dict, {{"A_TYPE", "int"}, {"B_TYPE", "int"}, {"D_TYPE", "int"}}));
  419. string_to_spv("im2col_f32", "im2col.comp", merge_maps(base_dict, {{"A_TYPE", "float"}, {"D_TYPE", "float"}}));
  420. string_to_spv("im2col_f32_f16", "im2col.comp", merge_maps(base_dict, {{"A_TYPE", "float"}, {"D_TYPE", "float16_t"}}));
  421. string_to_spv("im2col_f32_f16_rte", "im2col.comp", merge_maps(base_dict, {{"A_TYPE", "float"}, {"D_TYPE", "float16_t"}, {"RTE16", "1"}}));
  422. string_to_spv("timestep_embedding_f32", "timestep_embedding.comp", merge_maps(base_dict, {{"A_TYPE", "float"}, {"D_TYPE", "float"}}));
  423. string_to_spv("pool2d_f32", "pool2d.comp", merge_maps(base_dict, {{"A_TYPE", "float"}, {"D_TYPE", "float"}}));
  424. string_to_spv("rwkv_wkv6_f32", "wkv6.comp", merge_maps(base_dict, {{"A_TYPE", "float"}}));
  425. string_to_spv("rwkv_wkv7_f32", "wkv7.comp", merge_maps(base_dict, {{"A_TYPE", "float"}}));
  426. string_to_spv("opt_step_adamw_f32", "opt_step_adamw.comp", merge_maps(base_dict, {{"A_TYPE", "float"}}));
  427. for (auto &c : compiles) {
  428. c.wait();
  429. }
  430. }
  431. void write_output_files() {
  432. FILE* hdr = fopen(target_hpp.c_str(), "w");
  433. FILE* src = fopen(target_cpp.c_str(), "w");
  434. fprintf(hdr, "#include <cstdint>\n\n");
  435. fprintf(src, "#include \"%s\"\n\n", basename(target_hpp).c_str());
  436. std::sort(shader_fnames.begin(), shader_fnames.end());
  437. for (const auto& pair : shader_fnames) {
  438. const std::string& name = pair.first;
  439. #ifdef _WIN32
  440. std::string path = pair.second;
  441. std::replace(path.begin(), path.end(), '/', '\\' );
  442. #else
  443. const std::string& path = pair.second;
  444. #endif
  445. FILE* spv = fopen(path.c_str(), "rb");
  446. if (!spv) {
  447. std::cerr << "Error opening SPIR-V file: " << path << " (" << strerror(errno) << ")\n";
  448. continue;
  449. }
  450. fseek(spv, 0, SEEK_END);
  451. size_t size = ftell(spv);
  452. fseek(spv, 0, SEEK_SET);
  453. std::vector<unsigned char> data(size);
  454. size_t read_size = fread(data.data(), 1, size, spv);
  455. fclose(spv);
  456. if (read_size != size) {
  457. std::cerr << "Error reading SPIR-V file: " << path << " (" << strerror(errno) << ")\n";
  458. continue;
  459. }
  460. fprintf(hdr, "extern unsigned char %s_data[%zu];\n", name.c_str(), size);
  461. fprintf(hdr, "const uint64_t %s_len = %zu;\n\n", name.c_str(), size);
  462. fprintf(src, "unsigned char %s_data[%zu] = {\n", name.c_str(), size);
  463. for (size_t i = 0; i < size; ++i) {
  464. fprintf(src, "0x%02x,", data[i]);
  465. if ((i + 1) % 12 == 0) fprintf(src, "\n");
  466. }
  467. fprintf(src, "\n};\n\n");
  468. if (!no_clean) {
  469. std::remove(path.c_str());
  470. }
  471. }
  472. fclose(hdr);
  473. fclose(src);
  474. }
  475. }
  476. int main(int argc, char** argv) {
  477. std::map<std::string, std::string> args;
  478. for (int i = 1; i < argc; ++i) {
  479. std::string arg = argv[i];
  480. if (arg.rfind("--", 0) == 0) {
  481. if (i + 1 < argc && argv[i + 1][0] != '-') {
  482. args[arg] = argv[i + 1];
  483. ++i;
  484. } else {
  485. args[arg] = "";
  486. }
  487. }
  488. }
  489. if (args.find("--glslc") != args.end()) {
  490. GLSLC = args["--glslc"]; // Path to glslc
  491. }
  492. if (args.find("--input-dir") != args.end()) {
  493. input_dir = args["--input-dir"]; // Directory containing shader sources
  494. }
  495. if (args.find("--output-dir") != args.end()) {
  496. output_dir = args["--output-dir"]; // Directory for containing SPIR-V output
  497. }
  498. if (args.find("--target-hpp") != args.end()) {
  499. target_hpp = args["--target-hpp"]; // Path to generated header file
  500. }
  501. if (args.find("--target-cpp") != args.end()) {
  502. target_cpp = args["--target-cpp"]; // Path to generated cpp file
  503. }
  504. if (args.find("--no-clean") != args.end()) {
  505. no_clean = true; // Keep temporary SPIR-V files in output-dir after build
  506. }
  507. if (!directory_exists(input_dir)) {
  508. std::cerr << "\"" << input_dir << "\" must be a valid directory containing shader sources" << std::endl;
  509. return EXIT_FAILURE;
  510. }
  511. if (!directory_exists(output_dir)) {
  512. if (!create_directory(output_dir)) {
  513. std::cerr << "Error creating output directory: " << output_dir << "\n";
  514. return EXIT_FAILURE;
  515. }
  516. }
  517. process_shaders();
  518. write_output_files();
  519. return EXIT_SUCCESS;
  520. }