2450 lines
112 KiB
C++
2450 lines
112 KiB
C++
// vk_backend.cpp — Vulkan-бэкенд вычислений (архитектура v2).
|
||
//
|
||
// ─────────────────────────────────────────────────────────────────────────────
|
||
// СТАТУС: компилируется с Vulkan SDK; числовая корректность ядер проверяется
|
||
// `xenith gradcheck --backend vulkan` (порог min_gemm_flops для gradcheck
|
||
// обнуляется, поэтому тестируются именно GPU-ядра). Перед эксплуатацией на
|
||
// новой машине прогоните gradcheck и сравните loss 100 шагов cpu vs vulkan.
|
||
// ─────────────────────────────────────────────────────────────────────────────
|
||
//
|
||
// ЧТО ИЗМЕНЕНО ОТНОСИТЕЛЬНО v1 («закачал → dispatch → вычитал» на каждое ядро):
|
||
//
|
||
// 1. БАТЧИ. Все ядра шага обучения (forward + backward + adam) записываются в
|
||
// ОДИН command buffer и уходят ОДНИМ submit. Между dispatch — лёгкие
|
||
// глобальные барьеры COMPUTE→COMPUTE вместо submit+fence-wait на ядро
|
||
// (экономия ~90% оверхеда: fence-wait стоит десятки мкс, барьер — единицы).
|
||
//
|
||
// 2. ГРЯЗНЫЕ ФЛАГИ вместо закачки/вычитки всего подряд. Каждый device-буфер
|
||
// знает, где свежая копия (host_dirty/dev_dirty). Веса, градиенты и m/v
|
||
// ЖИВУТ НА GPU между шагами и ядрами: закачка — один раз за сессию,
|
||
// активации не покидают видеокарту ВООБЩЕ (кроме тех, что реально читает
|
||
// host-код — loss_row, клип-норма, логиты при сэмплинге).
|
||
//
|
||
// 3. НИКАКИХ аллокаций на операцию.Device-буфер создаётся один раз на
|
||
// (host_ptr,size) и переиспользуется (кэш с эпохами); staging и readback —
|
||
// постоянно отображённые кольца (mapped один раз на init, без
|
||
// vkMapMemory/vkUnmapMemory на каждую копию); descriptor sets освобождаются
|
||
// пачкой на flush.
|
||
//
|
||
// 4. КЛИП НОРМЫ ГРАДИЕНТА НА GPU: два новых ядра (reduce_sumsq + reduce_final)
|
||
// считают сумму квадратов и счётчик nan/inf, не вычитывая градиенты на
|
||
// хост. Хост получает ~200 байт итога через постоянно отображённый буфер.
|
||
//
|
||
// 5. ГОТОВЫЕ ТОКЕНЫ ЧЕРЕЗ SHARED MEMORY: жадный сэмплинг считает argmax НА
|
||
// GPU (ядро argmax) и пишет id токена в host-visible буфер, отображённый
|
||
// процессу (shared memory между GPU и CPU). Процессор читает 4 байта
|
||
// ответа вместо вычитывания всего вектора логитов.
|
||
//
|
||
// 6. ПАЙПЛАЙНИНГ: после шага оптимизатора батч уходит на GPU БЕЗ ожидания
|
||
// (launch) — видеокарта считает, пока хост готовит данные следующего шага.
|
||
// Ожидание — ровно одно на шаг (в точке, где хосту нужен loss).
|
||
//
|
||
// Корректность host-доступа: ядро (model/backward/generate/gradcheck) сообщает
|
||
// бэкенду о host-чтениях/записях тензоров через Backend::materialize() /
|
||
// host_written() (см. backend.h). На CPU-бэкенде это no-op.
|
||
//
|
||
// Портируемость: по-прежнему без float-атомиков; scatter_add (градиент
|
||
// эмбеддингов) детерминированно считается на CPU (материализуя gwte/dx —
|
||
// один round-trip vocab×d за шаг, плата за детерминизм).
|
||
#include "backend.h"
|
||
#include "../core/tensor.h" // полное определение Tensor
|
||
#include "../core/config.h" // engine_log/engine_warn — никакого stderr в библиотечном режиме
|
||
#include "../core/platform.h" // path_from_utf8/path_to_utf8
|
||
|
||
#include <cstdio>
|
||
#include <cstring>
|
||
|
||
#ifndef XENITH_VULKAN
|
||
|
||
namespace xt {
|
||
bool vulkan_available() { return false; }
|
||
std::string vulkan_loader_error() { return "Xenith собран без Vulkan"; }
|
||
bool vulkan_init(const VulkanOptions&, std::string& err) {
|
||
err = "Xenith собран без Vulkan: пересобери с -DXENITH_VULKAN=ON "
|
||
"(нужны Vulkan SDK и libvulkan-dev)";
|
||
return false;
|
||
}
|
||
void vulkan_shutdown() {}
|
||
void vulkan_begin_step() {}
|
||
std::vector<std::string> vulkan_list_devices() { return {}; }
|
||
std::string vulkan_shader_dir() { return {}; }
|
||
bool vulkan_rebuild_shaders(std::string& err, const std::string&) {
|
||
err = "Xenith собран без Vulkan: шейдеры не используются";
|
||
return false;
|
||
}
|
||
} // namespace xt
|
||
|
||
#else // XENITH_VULKAN
|
||
|
||
#include "vk_loader.h"
|
||
|
||
// Имена Vulkan-функций — указатели, которые заполняет vk_loader_load().
|
||
#define vkAllocateCommandBuffers p_vkAllocateCommandBuffers
|
||
#define vkAllocateDescriptorSets p_vkAllocateDescriptorSets
|
||
#define vkAllocateMemory p_vkAllocateMemory
|
||
#define vkBeginCommandBuffer p_vkBeginCommandBuffer
|
||
#define vkBindBufferMemory p_vkBindBufferMemory
|
||
#define vkCmdBindDescriptorSets p_vkCmdBindDescriptorSets
|
||
#define vkCmdBindPipeline p_vkCmdBindPipeline
|
||
#define vkCmdCopyBuffer p_vkCmdCopyBuffer
|
||
#define vkCmdDispatch p_vkCmdDispatch
|
||
#define vkCmdFillBuffer p_vkCmdFillBuffer
|
||
#define vkCmdPipelineBarrier p_vkCmdPipelineBarrier
|
||
#define vkCmdPushConstants p_vkCmdPushConstants
|
||
#define vkCreateBuffer p_vkCreateBuffer
|
||
#define vkCreateCommandPool p_vkCreateCommandPool
|
||
#define vkCreateComputePipelines p_vkCreateComputePipelines
|
||
#define vkCreateDescriptorPool p_vkCreateDescriptorPool
|
||
#define vkCreateDescriptorSetLayout p_vkCreateDescriptorSetLayout
|
||
#define vkCreateDevice p_vkCreateDevice
|
||
#define vkCreateFence p_vkCreateFence
|
||
#define vkCreateInstance p_vkCreateInstance
|
||
#define vkCreatePipelineLayout p_vkCreatePipelineLayout
|
||
#define vkCreateShaderModule p_vkCreateShaderModule
|
||
#define vkDestroyBuffer p_vkDestroyBuffer
|
||
#define vkDestroyCommandPool p_vkDestroyCommandPool
|
||
#define vkDestroyDescriptorPool p_vkDestroyDescriptorPool
|
||
#define vkDestroyDescriptorSetLayout p_vkDestroyDescriptorSetLayout
|
||
#define vkDestroyDevice p_vkDestroyDevice
|
||
#define vkDestroyFence p_vkDestroyFence
|
||
#define vkDestroyInstance p_vkDestroyInstance
|
||
#define vkDestroyPipeline p_vkDestroyPipeline
|
||
#define vkDestroyPipelineLayout p_vkDestroyPipelineLayout
|
||
#define vkDestroyShaderModule p_vkDestroyShaderModule
|
||
#define vkDeviceWaitIdle p_vkDeviceWaitIdle
|
||
#define vkEndCommandBuffer p_vkEndCommandBuffer
|
||
#define vkEnumerateInstanceLayerProperties p_vkEnumerateInstanceLayerProperties
|
||
#define vkEnumeratePhysicalDevices p_vkEnumeratePhysicalDevices
|
||
#define vkFreeDescriptorSets p_vkFreeDescriptorSets
|
||
#define vkFreeMemory p_vkFreeMemory
|
||
#define vkGetBufferMemoryRequirements p_vkGetBufferMemoryRequirements
|
||
#define vkGetDeviceQueue p_vkGetDeviceQueue
|
||
#define vkGetPhysicalDeviceMemoryProperties p_vkGetPhysicalDeviceMemoryProperties
|
||
#define vkGetPhysicalDeviceProperties p_vkGetPhysicalDeviceProperties
|
||
#define vkGetPhysicalDeviceQueueFamilyProperties p_vkGetPhysicalDeviceQueueFamilyProperties
|
||
#define vkMapMemory p_vkMapMemory
|
||
#define vkQueueSubmit p_vkQueueSubmit
|
||
#define vkResetCommandBuffer p_vkResetCommandBuffer
|
||
#define vkResetDescriptorPool p_vkResetDescriptorPool
|
||
#define vkResetFences p_vkResetFences
|
||
#define vkUnmapMemory p_vkUnmapMemory
|
||
#define vkUpdateDescriptorSets p_vkUpdateDescriptorSets
|
||
#define vkWaitForFences p_vkWaitForFences
|
||
|
||
|
||
#if !defined(__has_include)
|
||
# error "нужен компилятор с __has_include"
|
||
#elif !__has_include("shaders_bin.h")
|
||
# error "Не найден xenith/backend/shaders_bin.h. Сначала выполни: python3 tools/build_shaders.py (нужен glslc или glslangValidator), либо собери без Vulkan: cmake -DXENITH_VULKAN=OFF"
|
||
#else
|
||
# include "shaders_bin.h"
|
||
#endif
|
||
|
||
#include <algorithm>
|
||
#include <array>
|
||
#include <cmath>
|
||
#include <cstdlib>
|
||
#include <filesystem>
|
||
#include <fstream>
|
||
#include <map>
|
||
#include <memory>
|
||
#include <mutex>
|
||
#include <set>
|
||
#include <sstream>
|
||
#include <string>
|
||
#include <system_error>
|
||
#include <unordered_map>
|
||
#include <vector>
|
||
|
||
namespace fs = std::filesystem;
|
||
|
||
namespace xt {
|
||
|
||
|
||
namespace {
|
||
|
||
// Должно совпадать с #define WG в shaders/common.glsl.
|
||
constexpr uint32_t kWorkGroupSize = 64;
|
||
constexpr size_t kStagingDefault = 256ull * 1024 * 1024;
|
||
constexpr size_t kReadbackDefault = 64ull * 1024 * 1024;
|
||
constexpr int kMaxSets = 8192;
|
||
constexpr int kMaxBindings = 8;
|
||
// Сколько эпох (шагов обучения) device-буфер может не использоваться, прежде
|
||
// чем его освободит sweep. Веса/градиенты трогают каждый шаг — они вечны;
|
||
// записи умерших (реаллоцированных) тензоров подчищаются.
|
||
constexpr uint64_t kCacheTtlEpochs = 48;
|
||
// Предохранитель: если записей стало неприлично много — чистим агрессивнее.
|
||
constexpr size_t kMaxCacheEntries = 3072;
|
||
constexpr int kCmdBuffers = 4;
|
||
|
||
// Push-константы: ровно то, что объявлено в shaders/common.glsl.
|
||
struct PushData {
|
||
int32_t P[8];
|
||
float F[8];
|
||
};
|
||
static_assert(sizeof(PushData) == 64, "PushData должен совпадать с блоком push_constant в common.glsl");
|
||
|
||
#define VK_TRY(expr, msg) \
|
||
do { \
|
||
VkResult r_ = (expr); \
|
||
if (r_ != VK_SUCCESS) { \
|
||
char b_[256]; \
|
||
snprintf(b_, sizeof b_, "%s: VkResult %d", (msg), (int)r_); \
|
||
err = b_; \
|
||
return false; \
|
||
} \
|
||
} while (0)
|
||
|
||
// ---------------------------------------------------------------------------
|
||
enum class Kernel {
|
||
GemmNN, GemmNT, GemmTN,
|
||
RmsNormFwd, RmsNormBwd, RmsNormDw,
|
||
SwigluFwd, SwigluBwd,
|
||
RopeFwd, RopeBwd,
|
||
SoftmaxCE, SoftmaxLoss,
|
||
AttnFwd, AttnBwdA, AttnBwdB, AttnDV,
|
||
AdamStep, Elementwise, EmbedGather,
|
||
ReduceSumSq, ReduceFinal, Argmax,
|
||
COUNT
|
||
};
|
||
|
||
const char* kernel_name(Kernel k) {
|
||
switch (k) {
|
||
case Kernel::GemmNN: return "gemm_nn";
|
||
case Kernel::GemmNT: return "gemm_nt";
|
||
case Kernel::GemmTN: return "gemm_tn";
|
||
case Kernel::RmsNormFwd: return "rmsnorm_fwd";
|
||
case Kernel::RmsNormBwd: return "rmsnorm_bwd";
|
||
case Kernel::RmsNormDw: return "rmsnorm_dw";
|
||
case Kernel::SwigluFwd: return "swiglu_fwd";
|
||
case Kernel::SwigluBwd: return "swiglu_bwd";
|
||
case Kernel::RopeFwd: return "rope_fwd";
|
||
case Kernel::RopeBwd: return "rope_bwd";
|
||
case Kernel::SoftmaxCE: return "softmax_ce";
|
||
case Kernel::SoftmaxLoss: return "softmax_loss";
|
||
case Kernel::AttnFwd: return "attn_fwd";
|
||
case Kernel::AttnBwdA: return "attn_bwd_a";
|
||
case Kernel::AttnBwdB: return "attn_bwd_b";
|
||
case Kernel::AttnDV: return "attn_dv";
|
||
case Kernel::AdamStep: return "adam_step";
|
||
case Kernel::Elementwise: return "elementwise";
|
||
case Kernel::EmbedGather: return "embed_gather";
|
||
case Kernel::ReduceSumSq: return "reduce_sumsq";
|
||
case Kernel::ReduceFinal: return "reduce_final";
|
||
case Kernel::Argmax: return "argmax";
|
||
default: return "?";
|
||
}
|
||
}
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// SPIR-V: сначала диск (bin/shaders/*.spv), потом компиляция из .comp,
|
||
// и только в крайнем случае — встроенный в бинарник shaders_bin.h.
|
||
//
|
||
// Зачем: папка bin/ должна быть самодостаточной и переносимой. Рядом с
|
||
// бинарником лежат исходники шейдеров; если драйвер/оптимизатор их
|
||
// перекомпилирует — бинарник не нужно пересобирать. Встроенная копия — это
|
||
// страховка: без shaders/ всё всё равно работает.
|
||
// ---------------------------------------------------------------------------
|
||
const uint32_t* embedded_spv(Kernel k, size_t& words) {
|
||
switch (k) {
|
||
case Kernel::GemmNN: words = xenith_spv_gemm_nn_len; return xenith_spv_gemm_nn;
|
||
case Kernel::GemmNT: words = xenith_spv_gemm_nt_len; return xenith_spv_gemm_nt;
|
||
case Kernel::GemmTN: words = xenith_spv_gemm_tn_len; return xenith_spv_gemm_tn;
|
||
case Kernel::RmsNormFwd: words = xenith_spv_rmsnorm_fwd_len; return xenith_spv_rmsnorm_fwd;
|
||
case Kernel::RmsNormBwd: words = xenith_spv_rmsnorm_bwd_len; return xenith_spv_rmsnorm_bwd;
|
||
case Kernel::RmsNormDw: words = xenith_spv_rmsnorm_dw_len; return xenith_spv_rmsnorm_dw;
|
||
case Kernel::SwigluFwd: words = xenith_spv_swiglu_fwd_len; return xenith_spv_swiglu_fwd;
|
||
case Kernel::SwigluBwd: words = xenith_spv_swiglu_bwd_len; return xenith_spv_swiglu_bwd;
|
||
case Kernel::RopeFwd: words = xenith_spv_rope_fwd_len; return xenith_spv_rope_fwd;
|
||
case Kernel::RopeBwd: words = xenith_spv_rope_bwd_len; return xenith_spv_rope_bwd;
|
||
case Kernel::SoftmaxCE: words = xenith_spv_softmax_ce_len; return xenith_spv_softmax_ce;
|
||
case Kernel::SoftmaxLoss: words = xenith_spv_softmax_loss_len; return xenith_spv_softmax_loss;
|
||
case Kernel::AttnFwd: words = xenith_spv_attn_fwd_len; return xenith_spv_attn_fwd;
|
||
case Kernel::AttnBwdA: words = xenith_spv_attn_bwd_a_len; return xenith_spv_attn_bwd_a;
|
||
case Kernel::AttnBwdB: words = xenith_spv_attn_bwd_b_len; return xenith_spv_attn_bwd_b;
|
||
case Kernel::AttnDV: words = xenith_spv_attn_dv_len; return xenith_spv_attn_dv;
|
||
case Kernel::AdamStep: words = xenith_spv_adam_step_len; return xenith_spv_adam_step;
|
||
case Kernel::Elementwise: words = xenith_spv_elementwise_len; return xenith_spv_elementwise;
|
||
case Kernel::EmbedGather: words = xenith_spv_embed_gather_len; return xenith_spv_embed_gather;
|
||
case Kernel::ReduceSumSq: words = xenith_spv_reduce_sumsq_len; return xenith_spv_reduce_sumsq;
|
||
case Kernel::ReduceFinal: words = xenith_spv_reduce_final_len; return xenith_spv_reduce_final;
|
||
case Kernel::Argmax: words = xenith_spv_argmax_len; return xenith_spv_argmax;
|
||
default: words = 0; return nullptr;
|
||
}
|
||
}
|
||
|
||
std::vector<std::string> shader_dirs() {
|
||
std::vector<std::string> dirs;
|
||
if (const char* e = std::getenv("XENITH_SHADER_DIR"); e && *e) dirs.push_back(e);
|
||
const std::string exe = executable_dir();
|
||
if (!exe.empty()) {
|
||
dirs.push_back(exe + "/shaders");
|
||
dirs.push_back(exe + "/../share/xenith/shaders");
|
||
}
|
||
dirs.push_back("shaders");
|
||
dirs.push_back("../shaders");
|
||
return dirs;
|
||
}
|
||
|
||
std::string shell_quote_local(const std::string& s) {
|
||
#ifdef _WIN32
|
||
// cmd.exe понимает двойные кавычки, а не POSIX-одинарные.
|
||
std::string out = "\"";
|
||
for (char c : s) {
|
||
if (c == '"') out += "\\\"";
|
||
else out += c;
|
||
}
|
||
out += "\"";
|
||
return out;
|
||
#else
|
||
std::string out = "'";
|
||
for (char c : s) { if (c == '\'') out += "'\\''"; else out += c; }
|
||
out += "'";
|
||
return out;
|
||
#endif
|
||
}
|
||
|
||
#ifdef _WIN32
|
||
# define XENITH_NULL_REDIRECT " >NUL 2>&1"
|
||
#else
|
||
# define XENITH_NULL_REDIRECT " >/dev/null 2>&1"
|
||
#endif
|
||
|
||
bool read_spv_file(const std::string& path, std::vector<uint32_t>& out, std::string& err) {
|
||
std::ifstream f(path_from_utf8(path), std::ios::binary | std::ios::ate);
|
||
if (!f) { err = "не открывается " + path; return false; }
|
||
const std::streamoff sz = f.tellg();
|
||
if (sz <= 0 || (sz % 4) != 0) { err = "пустой/некратный 4 SPIR-V: " + path; return false; }
|
||
out.resize((size_t)sz / 4);
|
||
f.seekg(0);
|
||
f.read(reinterpret_cast<char*>(out.data()), sz);
|
||
if (!f) { err = "ошибка чтения " + path; return false; }
|
||
if (out.empty() || out[0] != 0x07230203u) { err = "не SPIR-V (magic): " + path; return false; }
|
||
return true;
|
||
}
|
||
|
||
int run_cmd(const std::string& cmd) {
|
||
#ifdef _WIN32
|
||
// cmd.exe /c, если команда начинается с кавычки, срезает первую и
|
||
// последнюю кавычку ВСЕЙ строки. Из-за этого `"C:\...\glslangValidator.exe"
|
||
// -I"..." ...` превращался в мусор («не является командой»). Оборачиваем
|
||
// всю команду в дополнительную пару кавычек — классический обход.
|
||
std::string c = cmd;
|
||
if (!c.empty() && c.front() == '"') c = "\"" + c + "\"";
|
||
return std::system(c.c_str());
|
||
#else
|
||
return std::system(cmd.c_str());
|
||
#endif
|
||
}
|
||
|
||
bool run_quiet(const std::string& cmd) { return run_cmd(cmd) == 0; }
|
||
|
||
bool compile_spv(const std::string& comp, const std::string& out, std::string& err) {
|
||
std::error_code ec;
|
||
fs::path comp_p = path_from_utf8(comp);
|
||
fs::path out_p = path_from_utf8(out);
|
||
if (!fs::exists(comp_p, ec)) { err = "нет исходника " + comp; return false; }
|
||
const std::string dir = path_to_utf8(comp_p.parent_path());
|
||
|
||
// Кандидаты: env → рядом с exe → PATH.
|
||
std::vector<std::string> cands;
|
||
if (const char* e = std::getenv("XENITH_SHADER_COMPILER"); e && *e) cands.push_back(e);
|
||
const std::string exe = executable_dir();
|
||
for (const char* n : {"glslc", "glslangValidator"}) {
|
||
if (!exe.empty()) {
|
||
cands.push_back(exe + "/" + n);
|
||
cands.push_back(exe + "/" + n + ".exe");
|
||
}
|
||
cands.push_back(n);
|
||
}
|
||
|
||
std::string last;
|
||
for (const auto& c : cands) {
|
||
const bool is_glslc = c.find("glslc") != std::string::npos;
|
||
const std::string base = c.substr(c.find_last_of("/\\") == std::string::npos
|
||
? 0 : c.find_last_of("/\\") + 1);
|
||
// Путь-кандидат должен существовать; имена без пути проверяем через
|
||
// «--version» (если бинаря нет, system вернёт ненулевой код).
|
||
if (c.find('/') != std::string::npos || c.find('\\') != std::string::npos) {
|
||
std::error_code ec2;
|
||
if (!fs::exists(path_from_utf8(c), ec2)) continue;
|
||
} else {
|
||
if (!run_quiet(shell_quote_local(c) + " --version" XENITH_NULL_REDIRECT)) {
|
||
#ifdef _WIN32
|
||
if (!run_quiet("where " + shell_quote_local(c) + " >NUL 2>&1")) continue;
|
||
#else
|
||
if (!run_quiet("command -v " + shell_quote_local(c) + " >/dev/null 2>&1")) continue;
|
||
#endif
|
||
}
|
||
}
|
||
fs::remove(out_p, ec);
|
||
std::string cmd;
|
||
if (is_glslc) {
|
||
cmd = shell_quote_local(c) + " -I " + shell_quote_local(dir) +
|
||
" -O --target-env=vulkan1.1 -o " + shell_quote_local(out) +
|
||
" " + shell_quote_local(comp);
|
||
} else {
|
||
cmd = shell_quote_local(c) + " -I" + shell_quote_local(dir) +
|
||
" -V -o " + shell_quote_local(out) + " " + shell_quote_local(comp);
|
||
}
|
||
if (std::getenv("XENITH_SHADER_DEBUG")) {
|
||
fprintf(stderr, "[shader] %s\n", cmd.c_str());
|
||
run_cmd(cmd);
|
||
} else {
|
||
cmd += XENITH_NULL_REDIRECT;
|
||
}
|
||
if (run_quiet(cmd) && fs::exists(out_p, ec)) {
|
||
(void)base;
|
||
return true;
|
||
}
|
||
last = c;
|
||
}
|
||
err = "не удалось скомпилировать " + comp +
|
||
(last.empty() ? " (компилятор шейдеров не найден)" : " (пробовал " + last + ")");
|
||
return false;
|
||
}
|
||
|
||
const std::vector<uint32_t>& spv_for(Kernel k) {
|
||
static std::mutex mtx;
|
||
static std::map<int, std::vector<uint32_t>> cache;
|
||
std::lock_guard<std::mutex> lk(mtx);
|
||
auto it = cache.find((int)k);
|
||
if (it != cache.end()) return it->second;
|
||
|
||
std::vector<uint32_t> words;
|
||
const std::string name = kernel_name(k);
|
||
for (const auto& d : shader_dirs()) {
|
||
std::error_code ec;
|
||
const fs::path spv = path_from_utf8(d) / (name + ".spv");
|
||
std::string err;
|
||
if (fs::exists(spv, ec) && read_spv_file(path_to_utf8(spv), words, err)) break;
|
||
const fs::path comp = path_from_utf8(d) / (name + ".comp");
|
||
if (fs::exists(comp, ec)) {
|
||
std::string cerr;
|
||
if (compile_spv(path_to_utf8(comp), path_to_utf8(spv), cerr) &&
|
||
read_spv_file(path_to_utf8(spv), words, cerr))
|
||
break;
|
||
engine_warn("shader " + name + ": " + cerr);
|
||
}
|
||
words.clear();
|
||
}
|
||
if (words.empty()) {
|
||
size_t n = 0;
|
||
const uint32_t* data = embedded_spv(k, n);
|
||
if (data && n) words.assign(data, data + n);
|
||
}
|
||
return cache.emplace((int)k, std::move(words)).first->second;
|
||
}
|
||
|
||
// Номера binding'ов каждого ядра — ДОЛЖНЫ совпадать с шейдером.
|
||
std::vector<uint32_t> bindings_for(Kernel k) {
|
||
auto seq = [](uint32_t n) {
|
||
std::vector<uint32_t> v;
|
||
for (uint32_t i = 0; i < n; ++i) v.push_back(i);
|
||
return v;
|
||
};
|
||
switch (k) {
|
||
case Kernel::GemmNN: case Kernel::GemmNT: case Kernel::GemmTN: return seq(3);
|
||
case Kernel::RmsNormFwd: return seq(4);
|
||
case Kernel::RmsNormBwd: return seq(5); // x, w, r, dy -> dx
|
||
case Kernel::RmsNormDw: return seq(4); // dy, x, r -> dw
|
||
case Kernel::SwigluFwd: return seq(3);
|
||
case Kernel::SwigluBwd: return seq(5);
|
||
case Kernel::RopeFwd: case Kernel::RopeBwd: return seq(4);
|
||
case Kernel::SoftmaxCE: return seq(4);
|
||
case Kernel::SoftmaxLoss: return seq(3);
|
||
case Kernel::AttnFwd: return seq(5);
|
||
case Kernel::AttnBwdA: return seq(7);
|
||
case Kernel::AttnBwdB: return seq(3);
|
||
case Kernel::AttnDV: return seq(3);
|
||
case Kernel::AdamStep: return seq(4);
|
||
case Kernel::Elementwise: return {0u, 12u};
|
||
case Kernel::EmbedGather: return seq(3);
|
||
case Kernel::ReduceSumSq: return seq(2);
|
||
case Kernel::ReduceFinal: return seq(2);
|
||
case Kernel::Argmax: return seq(2);
|
||
default: return {};
|
||
}
|
||
}
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// Device-буфер с флагами «где свежая копия».
|
||
// host_dirty — на хосте данные новее (или устройство не инициализировано):
|
||
// перед device-использованием нужна закачка.
|
||
// dev_dirty — устройство изменило буфер, host-копия устарела: перед
|
||
// host-чтением нужна вычитка (materialize).
|
||
// Оба false — копии синхронны.
|
||
struct GpuBuf {
|
||
VkBuffer buffer = VK_NULL_HANDLE;
|
||
VkDeviceMemory mem = VK_NULL_HANDLE;
|
||
VkDeviceSize size = 0;
|
||
bool host_dirty = true;
|
||
bool dev_dirty = false;
|
||
uint64_t epoch = 0;
|
||
};
|
||
|
||
// Флаги BufSpec (v2):
|
||
enum BufFlags : uint32_t {
|
||
BF_NONE = 0,
|
||
BF_UPLOAD = 1u << 0, // вход: закачать, ЕСЛИ host_dirty
|
||
BF_FORCE_UPLOAD = 1u << 1, // вход: закачивать ВСЕГДА (данные вызова: id токенов, таблицы)
|
||
BF_OUTPUT = 1u << 2, // ядро полностью перезаписывает буфер
|
||
BF_ACCUM = 1u << 3, // ядро читает И пишет (inout/accumulate)
|
||
BF_ZERO = 1u << 4, // перед dispatch обнулить на устройстве (vkCmdFillBuffer)
|
||
BF_HOST = 1u << 5, // результат нужен хосту: запланировать вычитку на flush
|
||
BF_DIRECT = 1u << 6, // использовать spec.direct (выделенный host-visible буфер), мимо кэша
|
||
};
|
||
|
||
struct BufSpec {
|
||
const void* host = nullptr;
|
||
size_t bytes = 0;
|
||
uint32_t flags = BF_NONE;
|
||
GpuBuf* direct = nullptr; // BF_DIRECT: готовый буфер (token_out_, adam_out_)
|
||
};
|
||
|
||
// Вход, закачивается только когда хост новее устройства (веса между шагами).
|
||
inline BufSpec rd_buf(const void* p, size_t b) { return BufSpec{p, b, BF_UPLOAD}; }
|
||
// Вход с данными КАЖДОГО вызова (токены батча, цели, таблицы RoPE) — всегда качаем.
|
||
inline BufSpec tmp_buf(const void* p, size_t b) { return BufSpec{p, b, BF_UPLOAD | BF_FORCE_UPLOAD}; }
|
||
// Выход: ядро пишет целиком.
|
||
inline BufSpec out_buf(void* p, size_t b) { return BufSpec{p, b, BF_OUTPUT}; }
|
||
// Inout/накопление: закачать если host_dirty, ядро читает+пишет.
|
||
// BF_UPLOAD обязателен: после host-записи (host_written) данные должны уйти
|
||
// на устройство; когда host_dirty=false закачки не будет (см. run()).
|
||
inline BufSpec acc_buf(void* p, size_t b) { return BufSpec{p, b, BF_ACCUM | BF_UPLOAD}; }
|
||
// Накопление с предварительным обнулением на устройстве (gemm_nn: C=0; C+=A·B).
|
||
inline BufSpec zero_buf(void* p, size_t b) { return BufSpec{p, b, BF_ZERO | BF_ACCUM}; }
|
||
// Выход, который хост читает в этом же шаге (loss_row): запланировать вычитку.
|
||
inline BufSpec host_out(void* p, size_t b) { return BufSpec{p, b, BF_OUTPUT | BF_HOST}; }
|
||
// Заглушка биндинга (elementwise binding 12 для op=1): ничего не качаем.
|
||
inline BufSpec bind_only(const void* p, size_t b){ return BufSpec{p, b, BF_NONE}; }
|
||
// Прямой буфер (host-visible, минует кэш): token_out_, adam_out_.
|
||
inline BufSpec direct_buf(GpuBuf* g, size_t b) { return BufSpec{nullptr, b, BF_DIRECT, g}; }
|
||
|
||
struct BufKey {
|
||
const void* p;
|
||
size_t bytes;
|
||
bool operator==(const BufKey& o) const { return p == o.p && bytes == o.bytes; }
|
||
};
|
||
struct BufKeyHash {
|
||
size_t operator()(const BufKey& k) const {
|
||
return std::hash<const void*>()(k.p) * 1315423911u ^ std::hash<size_t>()(k.bytes);
|
||
}
|
||
};
|
||
|
||
// Очередь отложенных вычиток (исполняется на flush).
|
||
struct PendingDownload {
|
||
BufKey key;
|
||
void* host = nullptr;
|
||
size_t bytes = 0;
|
||
size_t done = 0; // частичное исполнение (чанки readback-кольца)
|
||
};
|
||
|
||
// Отправленный, но не дожиданный батч.
|
||
struct Inflight {
|
||
bool valid = false;
|
||
VkCommandBuffer cb = VK_NULL_HANDLE;
|
||
VkFence fence = VK_NULL_HANDLE;
|
||
std::vector<VkDescriptorSet> sets;
|
||
};
|
||
|
||
// Стадия, после которой нужен барьер перед следующей операцией.
|
||
enum class Stage { None, Transfer, Compute };
|
||
|
||
} // namespace
|
||
|
||
// ===========================================================================
|
||
class VkBackend : public Backend {
|
||
public:
|
||
~VkBackend() override { shutdown(); }
|
||
|
||
const char* name() const override { return "vulkan"; }
|
||
std::string describe() const override { return device_name_; }
|
||
|
||
bool init(const VulkanOptions& opt, std::string& err);
|
||
void shutdown();
|
||
|
||
// v2: НЕ уничтожает кэш (веса device-resident между шагами!). Только
|
||
// двигает эпоху и подчищает записи давно умерших тензоров.
|
||
void begin_step();
|
||
|
||
// --- Backend API ---
|
||
void gemm_nn(const Tensor& A, const Tensor& B, Tensor& C) override;
|
||
void gemm_nt(const Tensor& A, const Tensor& B, Tensor& C) override;
|
||
void gemm_tn(const Tensor& A, const Tensor& B, Tensor& C, bool accumulate) override;
|
||
void rmsnorm_forward (const Tensor& x, const Tensor& w, float eps, Tensor& y, Tensor& inv_rms) override;
|
||
void rmsnorm_backward(const Tensor& x, const Tensor& w, const Tensor& inv_rms,
|
||
const Tensor& dy, Tensor& dx, Tensor& dw) override;
|
||
void swiglu_forward (const Tensor& h1, const Tensor& h3, Tensor& ha) override;
|
||
void swiglu_backward(const Tensor& h1, const Tensor& h3, const Tensor& dha,
|
||
Tensor& dh1, Tensor& dh3) override;
|
||
void rope_forward (Tensor& q, Tensor& k, int n_seq, int S, int H, int hd,
|
||
const float* cs, const float* sn) override;
|
||
void rope_backward(Tensor& dq, Tensor& dk, int n_seq, int S, int H, int hd,
|
||
const float* cs, const float* sn) override;
|
||
void softmax_ce(const Tensor& logits, const int* targets, int B, int V,
|
||
Tensor& dlogits, Tensor& loss_row) override;
|
||
float softmax_ce_loss(const Tensor& logits, const int* targets, int B, int V,
|
||
Tensor& loss_row) override;
|
||
void attention_forward(const Tensor& q, const Tensor& k, const Tensor& v,
|
||
int n_seq, int S, int H, int hd, float scale,
|
||
Tensor& att, Tensor& attout) override;
|
||
void attention_backward(const Tensor& q, const Tensor& k, const Tensor& v,
|
||
const Tensor& att, const Tensor& dattout,
|
||
int n_seq, int S, int H, int hd, float scale,
|
||
Tensor& dq, Tensor& dk, Tensor& dv) override;
|
||
void zero(Tensor& t) override;
|
||
void add_into(Tensor& dst, const Tensor& src) override;
|
||
void scale(Tensor& t, float k) override;
|
||
void copy(Tensor& dst, const Tensor& src) override;
|
||
void scatter_add_rows(Tensor& x, const int* row_ids, int n_rows, const Tensor& src) override;
|
||
void embed_gather(Tensor& x, const Tensor& wte, const int* row_ids, int n_rows) override;
|
||
void adam(std::vector<Tensor*>& params, std::vector<Tensor*>& grads,
|
||
std::vector<Tensor*>& m, std::vector<Tensor*>& v,
|
||
float lr, float b1, float b2, float eps, float wd,
|
||
int step, float clip, bool* had_nonfinite) override;
|
||
|
||
// --- отложенная синхронизация host/device (см. backend.h) ---
|
||
void materialize(Tensor& t) override;
|
||
void materialize(const std::vector<Tensor*>& ts) override;
|
||
void host_written(Tensor& t) override;
|
||
void host_written(const std::vector<Tensor*>& ts) override;
|
||
void invalidate(const Tensor& t) override;
|
||
void invalidate_all() override;
|
||
void flush() override;
|
||
void sync() override;
|
||
bool sample_argmax(const Tensor& logits, int& out_id) override;
|
||
|
||
size_t device_memory_used() const override { return bytes_allocated_; }
|
||
bool supports(const char* k) const override;
|
||
|
||
private:
|
||
// --- инициализация ---
|
||
bool create_instance(std::string& err);
|
||
bool pick_device(std::string& err);
|
||
bool create_logical_device(std::string& err);
|
||
bool create_pools_and_pipelines(std::string& err);
|
||
bool create_rings(std::string& err);
|
||
bool alloc_host_visible(GpuBuf& b, size_t bytes, void** mapped, std::string& err);
|
||
uint32_t find_memory_type(uint32_t bits, VkMemoryPropertyFlags want) const;
|
||
|
||
// --- буферы ---
|
||
bool alloc_device_buf(GpuBuf& b, size_t bytes, std::string& err);
|
||
void free_device_buf(GpuBuf& b);
|
||
GpuBuf* resolve(const BufSpec& sp, std::string& err); // запись кэша (или direct)
|
||
void sweep_locked(bool aggressive);
|
||
|
||
// --- батчи ---
|
||
bool begin_batch_locked(std::string& err);
|
||
void barrier_to_compute_locked();
|
||
void barrier_compute_locked();
|
||
void barrier_to_transfer_locked();
|
||
bool launch_locked(std::string& err); // submit БЕЗ ожидания
|
||
void wait_inflight_locked();
|
||
void flush_locked(); // submit + wait + вычитки
|
||
bool ensure_ring_space(size_t need);
|
||
bool record_upload_locked(GpuBuf& b, const void* host, size_t bytes, std::string& err);
|
||
void schedule_download_locked(const BufKey& key, void* host, size_t bytes);
|
||
bool alloc_set_locked(const std::vector<uint32_t>& bk, VkDescriptorSet& out, std::string& err);
|
||
|
||
// Главный вход: подготовить буферы, записать fill/upload/dispatch в батч.
|
||
bool run(Kernel k, const std::vector<BufSpec>& bufs,
|
||
const int32_t P[8], const float F[8], uint32_t work_items,
|
||
std::string& err);
|
||
|
||
// Синхронизация для CPU-фолбэка: вычитать все dev_dirty входы на хост.
|
||
void sync_host_for_fallback(const std::vector<BufSpec>& bufs);
|
||
// После CPU-фолбэка: выходы помечаются «хост новее».
|
||
void mark_host_outputs(const std::vector<BufSpec>& bufs);
|
||
|
||
bool small_enough_for_cpu(int64_t flops) const { return flops < (int64_t)opt_.min_gemm_flops; }
|
||
|
||
// --- adam-хелперы ---
|
||
bool ensure_adam_out(size_t n_floats, std::string& err);
|
||
GpuBuf* ensure_partials(const void* owner, size_t n, std::string& err);
|
||
|
||
// --- nolock-варианты синхронизации (вызываются УЖЕ под mtx_) ---
|
||
void materialize_nolock(Tensor& t);
|
||
void materialize_nolock(const Tensor& t) { materialize_nolock(const_cast<Tensor&>(t)); }
|
||
void materialize_nolock(const std::vector<Tensor*>& ts);
|
||
void host_written_nolock(Tensor& t);
|
||
void host_written_nolock(const Tensor& t) { host_written_nolock(const_cast<Tensor&>(t)); }
|
||
void host_written_nolock(const std::vector<Tensor*>& ts);
|
||
// Аварийный режим: устройство потеряно/ошиблось — до конца процесса все
|
||
// операции идут через CPU-фолбэк, vk не трогаем.
|
||
void degraded_enter();
|
||
|
||
VulkanOptions opt_;
|
||
std::string device_name_ = "vulkan";
|
||
bool inited_ = false;
|
||
bool degraded_ = false; // device lost: всё на CPU, vk не трогаем
|
||
|
||
VkInstance instance_ = VK_NULL_HANDLE;
|
||
VkPhysicalDevice phys_ = VK_NULL_HANDLE;
|
||
VkDevice dev_ = VK_NULL_HANDLE;
|
||
VkQueue queue_ = VK_NULL_HANDLE;
|
||
uint32_t queue_family_ = 0;
|
||
VkCommandPool cmd_pool_ = VK_NULL_HANDLE;
|
||
VkDescriptorPool desc_pool_ = VK_NULL_HANDLE;
|
||
VkPhysicalDeviceProperties props_{};
|
||
|
||
using BindKey = std::vector<uint32_t>;
|
||
struct BindKeyHash {
|
||
size_t operator()(const BindKey& v) const {
|
||
size_t h = 1469598103934665603ull;
|
||
for (uint32_t x : v) { h ^= x; h *= 1099511628211ull; }
|
||
return h;
|
||
}
|
||
};
|
||
std::unordered_map<BindKey, VkDescriptorSetLayout, BindKeyHash> ds_layout_;
|
||
std::unordered_map<BindKey, VkPipelineLayout, BindKeyHash> pl_layout_;
|
||
std::array<VkPipeline, (size_t)Kernel::COUNT> pipelines_{};
|
||
|
||
// command buffers / fences — пул на kCmdBuffers штук (ротация)
|
||
VkCommandBuffer cbs_[kCmdBuffers] = {};
|
||
VkFence fences_[kCmdBuffers] = {};
|
||
int cb_idx_ = 0, fence_idx_ = 0;
|
||
|
||
// текущий открытый батч
|
||
bool batch_open_ = false;
|
||
VkCommandBuffer cur_cb_ = VK_NULL_HANDLE;
|
||
std::vector<VkDescriptorSet> cur_sets_;
|
||
Stage stage_ = Stage::None; // последняя записанная стадия (для барьеров)
|
||
uint32_t dispatches_in_cb_ = 0;
|
||
|
||
Inflight inflight_;
|
||
|
||
// staging-кольцо (закачка): host-visible, отображено ОДИН раз
|
||
GpuBuf staging_{};
|
||
void* staging_map_ = nullptr;
|
||
VkDeviceSize ring_off_ = 0;
|
||
|
||
// readback-кольцо (вычитка): host-visible, отображено один раз
|
||
GpuBuf readback_{};
|
||
void* readback_map_ = nullptr;
|
||
VkDeviceSize rb_off_ = 0;
|
||
|
||
// SHARED MEMORY каналы GPU→CPU (host-visible, постоянно отображены):
|
||
GpuBuf token_out_{}; // argmax: готовый id токена (int[16])
|
||
int32_t* token_map_ = nullptr;
|
||
GpuBuf adam_out_{}; // reduce_final: [sumsq, nonfinite] на тензор
|
||
float* adam_map_ = nullptr;
|
||
size_t adam_out_floats_ = 0;
|
||
|
||
// кэш device-буферов: (host_ptr,bytes) → буфер с dirty-флагами.
|
||
// unique_ptr: указатели на записи стабильны при реhash'е.
|
||
std::unordered_map<BufKey, std::unique_ptr<GpuBuf>, BufKeyHash> cache_;
|
||
// device-only скретч (частичные суммы редукции) — ключ = владелец
|
||
std::unordered_map<const void*, std::unique_ptr<GpuBuf>> scratch_;
|
||
uint64_t epoch_ = 1;
|
||
VkDeviceSize bytes_allocated_ = 0;
|
||
VkDeviceSize ring_align_ = 256;
|
||
|
||
std::vector<PendingDownload> pending_downloads_;
|
||
|
||
float dummy_y_[16] = {0.f}; // заглушка binding 12 (elementwise op=1)
|
||
|
||
std::mutex mtx_;
|
||
CpuBackend cpu_; // фолбэк: мелкие задачи, ошибки, scatter_add
|
||
};
|
||
|
||
// ===========================================================================
|
||
// Инициализация
|
||
// ===========================================================================
|
||
uint32_t VkBackend::find_memory_type(uint32_t bits, VkMemoryPropertyFlags want) const {
|
||
VkPhysicalDeviceMemoryProperties mp;
|
||
vkGetPhysicalDeviceMemoryProperties(phys_, &mp);
|
||
for (uint32_t i = 0; i < mp.memoryTypeCount; ++i)
|
||
if ((bits & (1u << i)) && (mp.memoryTypes[i].propertyFlags & want) == want) return i;
|
||
for (uint32_t i = 0; i < mp.memoryTypeCount; ++i)
|
||
if ((bits & (1u << i)) && (mp.memoryTypes[i].propertyFlags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT)) return i;
|
||
for (uint32_t i = 0; i < mp.memoryTypeCount; ++i)
|
||
if (bits & (1u << i)) return i;
|
||
return UINT32_MAX;
|
||
}
|
||
|
||
bool VkBackend::create_instance(std::string& err) {
|
||
VkApplicationInfo app{};
|
||
app.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
|
||
app.pApplicationName = "Xenith";
|
||
app.pEngineName = "Xenith";
|
||
app.apiVersion = VK_API_VERSION_1_1;
|
||
|
||
VkInstanceCreateInfo ci{};
|
||
ci.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
|
||
ci.pApplicationInfo = &app;
|
||
|
||
const char* layers[] = {"VK_LAYER_KHRONOS_validation"};
|
||
if (opt_.validation_layers) {
|
||
uint32_t n = 0;
|
||
vkEnumerateInstanceLayerProperties(&n, nullptr);
|
||
std::vector<VkLayerProperties> avail((size_t)n);
|
||
if (n) vkEnumerateInstanceLayerProperties(&n, avail.data());
|
||
for (const auto& l : avail)
|
||
if (!strcmp(l.layerName, layers[0])) { ci.enabledLayerCount = 1; ci.ppEnabledLayerNames = layers; break; }
|
||
if (!ci.enabledLayerCount)
|
||
engine_warn("[vulkan] validation layers запрошены, но не установлены");
|
||
}
|
||
VK_TRY(vkCreateInstance(&ci, nullptr, &instance_), "vkCreateInstance");
|
||
return true;
|
||
}
|
||
|
||
bool VkBackend::pick_device(std::string& err) {
|
||
uint32_t n = 0;
|
||
VK_TRY(vkEnumeratePhysicalDevices(instance_, &n, nullptr), "vkEnumeratePhysicalDevices");
|
||
if (n == 0) { err = "не найдено ни одного Vulkan-устройства"; return false; }
|
||
std::vector<VkPhysicalDevice> devs((size_t)n);
|
||
VK_TRY(vkEnumeratePhysicalDevices(instance_, &n, devs.data()), "vkEnumeratePhysicalDevices(2)");
|
||
|
||
int chosen = -1;
|
||
if (opt_.device_index >= 0 && opt_.device_index < (int)n) {
|
||
chosen = opt_.device_index;
|
||
} else {
|
||
int best = -1;
|
||
for (uint32_t i = 0; i < n; ++i) {
|
||
VkPhysicalDeviceProperties p; vkGetPhysicalDeviceProperties(devs[(size_t)i], &p);
|
||
const bool discrete = p.deviceType == VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU;
|
||
const bool integrated = p.deviceType == VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU;
|
||
if (integrated && !opt_.allow_integrated) continue;
|
||
if (p.deviceType == VK_PHYSICAL_DEVICE_TYPE_CPU) continue;
|
||
int score = discrete ? 100000 : (integrated ? 10000 : 100);
|
||
score += (int)(p.limits.maxComputeWorkGroupCount[0] / 16);
|
||
score += (int)(p.limits.maxComputeWorkGroupInvocations / 8);
|
||
if (score > best) { best = score; chosen = (int)i; }
|
||
}
|
||
if (chosen < 0) chosen = 0;
|
||
}
|
||
|
||
phys_ = devs[(size_t)chosen];
|
||
vkGetPhysicalDeviceProperties(phys_, &props_);
|
||
{
|
||
char b[512];
|
||
snprintf(b, sizeof b, "%s (Vulkan %u.%u, max invocations %u, max wg %u)",
|
||
props_.deviceName,
|
||
VK_VERSION_MAJOR(props_.apiVersion), VK_VERSION_MINOR(props_.apiVersion),
|
||
props_.limits.maxComputeWorkGroupInvocations,
|
||
props_.limits.maxComputeWorkGroupSize[0]);
|
||
device_name_ = b;
|
||
}
|
||
|
||
uint32_t qn = 0;
|
||
vkGetPhysicalDeviceQueueFamilyProperties(phys_, &qn, nullptr);
|
||
std::vector<VkQueueFamilyProperties> qf((size_t)qn);
|
||
vkGetPhysicalDeviceQueueFamilyProperties(phys_, &qn, qf.data());
|
||
bool found = false;
|
||
for (uint32_t i = 0; i < qn; ++i)
|
||
if (qf[(size_t)i].queueFlags & VK_QUEUE_COMPUTE_BIT) { queue_family_ = i; found = true; break; }
|
||
if (!found) { err = "у устройства нет compute-очереди"; return false; }
|
||
|
||
if (kWorkGroupSize > props_.limits.maxComputeWorkGroupInvocations) {
|
||
err = "устройство поддерживает только " +
|
||
std::to_string(props_.limits.maxComputeWorkGroupInvocations) +
|
||
" invocations, а шейдеры собраны под WG=64";
|
||
return false;
|
||
}
|
||
ring_align_ = std::max<VkDeviceSize>(256, props_.limits.minStorageBufferOffsetAlignment);
|
||
return true;
|
||
}
|
||
|
||
bool VkBackend::create_logical_device(std::string& err) {
|
||
const float prio = 1.0f;
|
||
VkDeviceQueueCreateInfo qi{};
|
||
qi.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
|
||
qi.queueFamilyIndex = queue_family_;
|
||
qi.queueCount = 1;
|
||
qi.pQueuePriorities = &prio;
|
||
|
||
VkPhysicalDeviceFeatures feats{};
|
||
VkDeviceCreateInfo ci{};
|
||
ci.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
|
||
ci.queueCreateInfoCount = 1;
|
||
ci.pQueueCreateInfos = &qi;
|
||
ci.pEnabledFeatures = &feats;
|
||
|
||
VK_TRY(vkCreateDevice(phys_, &ci, nullptr, &dev_), "vkCreateDevice");
|
||
vkGetDeviceQueue(dev_, queue_family_, 0, &queue_);
|
||
|
||
VkCommandPoolCreateInfo pc{};
|
||
pc.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
|
||
pc.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
|
||
pc.queueFamilyIndex = queue_family_;
|
||
VK_TRY(vkCreateCommandPool(dev_, &pc, nullptr, &cmd_pool_), "vkCreateCommandPool");
|
||
|
||
// command buffers + fences — пул, ротация на каждый батч
|
||
VkCommandBufferAllocateInfo ai{};
|
||
ai.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
|
||
ai.commandPool = cmd_pool_;
|
||
ai.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
|
||
ai.commandBufferCount = kCmdBuffers;
|
||
VK_TRY(vkAllocateCommandBuffers(dev_, &ai, cbs_), "vkAllocateCommandBuffers");
|
||
|
||
VkFenceCreateInfo fci{};
|
||
fci.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
|
||
fci.flags = VK_FENCE_CREATE_SIGNALED_BIT;
|
||
for (int i = 0; i < kCmdBuffers; ++i)
|
||
VK_TRY(vkCreateFence(dev_, &fci, nullptr, &fences_[i]), "vkCreateFence");
|
||
return true;
|
||
}
|
||
|
||
bool VkBackend::alloc_host_visible(GpuBuf& b, size_t bytes, void** mapped, std::string& err) {
|
||
VkBufferCreateInfo bi{};
|
||
bi.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
|
||
bi.size = (VkDeviceSize)bytes;
|
||
bi.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT |
|
||
VK_BUFFER_USAGE_TRANSFER_DST_BIT;
|
||
VK_TRY(vkCreateBuffer(dev_, &bi, nullptr, &b.buffer), "vkCreateBuffer(host-visible)");
|
||
|
||
VkMemoryRequirements mr;
|
||
vkGetBufferMemoryRequirements(dev_, b.buffer, &mr);
|
||
VkMemoryAllocateInfo ai{};
|
||
ai.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
|
||
ai.allocationSize = mr.size;
|
||
ai.memoryTypeIndex = find_memory_type(mr.memoryTypeBits,
|
||
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
|
||
if (ai.memoryTypeIndex == UINT32_MAX) { err = "нет host-visible памяти"; return false; }
|
||
VK_TRY(vkAllocateMemory(dev_, &ai, nullptr, &b.mem), "vkAllocateMemory(host-visible)");
|
||
VK_TRY(vkBindBufferMemory(dev_, b.buffer, b.mem, 0), "vkBindBufferMemory(host-visible)");
|
||
VK_TRY(vkMapMemory(dev_, b.mem, 0, (VkDeviceSize)bytes, 0, mapped), "vkMapMemory");
|
||
b.size = (VkDeviceSize)bytes;
|
||
b.host_dirty = false; b.dev_dirty = false;
|
||
bytes_allocated_ += b.size;
|
||
return true;
|
||
}
|
||
|
||
bool VkBackend::create_rings(std::string& err) {
|
||
// staging-кольцо закачки
|
||
VkDeviceSize want = opt_.staging_mb ? (VkDeviceSize)opt_.staging_mb * 1024 * 1024
|
||
: (VkDeviceSize)kStagingDefault;
|
||
for (int attempt = 0; attempt < 4; ++attempt) {
|
||
std::string e2;
|
||
if (alloc_host_visible(staging_, (size_t)want, &staging_map_, e2)) break;
|
||
want /= 4;
|
||
if (want < 4 * 1024 * 1024) { err = "не удалось выделить staging-кольцо: " + e2; return false; }
|
||
}
|
||
// readback-кольцо вычитки
|
||
VkDeviceSize rb = (VkDeviceSize)kReadbackDefault;
|
||
for (int attempt = 0; attempt < 4; ++attempt) {
|
||
std::string e2;
|
||
if (alloc_host_visible(readback_, (size_t)rb, &readback_map_, e2)) break;
|
||
rb /= 4;
|
||
if (rb < 1024 * 1024) { err = "не удалось выделить readback-кольцо: " + e2; return false; }
|
||
}
|
||
// shm-канал готовых токенов (argmax)
|
||
if (!alloc_host_visible(token_out_, 64 * sizeof(int32_t), (void**)&token_map_, err)) return false;
|
||
return true;
|
||
}
|
||
|
||
bool VkBackend::create_pools_and_pipelines(std::string& err) {
|
||
VkDescriptorPoolSize sz{};
|
||
sz.type = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
|
||
sz.descriptorCount = (uint32_t)(kMaxSets * kMaxBindings);
|
||
|
||
VkDescriptorPoolCreateInfo pi{};
|
||
pi.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
|
||
pi.flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT;
|
||
pi.maxSets = (uint32_t)kMaxSets;
|
||
pi.poolSizeCount = 1;
|
||
pi.pPoolSizes = &sz;
|
||
VK_TRY(vkCreateDescriptorPool(dev_, &pi, nullptr, &desc_pool_), "vkCreateDescriptorPool");
|
||
|
||
std::vector<BindKey> unique_sets;
|
||
for (int i = 0; i < (int)Kernel::COUNT; ++i) {
|
||
BindKey bk = bindings_for((Kernel)i);
|
||
if (bk.empty()) continue;
|
||
bool dup = false;
|
||
for (const auto& u : unique_sets) if (u == bk) { dup = true; break; }
|
||
if (!dup) unique_sets.push_back(bk);
|
||
}
|
||
for (const auto& bk : unique_sets) {
|
||
std::vector<VkDescriptorSetLayoutBinding> b(bk.size());
|
||
for (size_t i = 0; i < bk.size(); ++i) {
|
||
b[i].binding = bk[i];
|
||
b[i].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
|
||
b[i].descriptorCount = 1;
|
||
b[i].stageFlags = VK_SHADER_STAGE_COMPUTE_BIT;
|
||
}
|
||
VkDescriptorSetLayoutCreateInfo li{};
|
||
li.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
|
||
li.bindingCount = (uint32_t)bk.size();
|
||
li.pBindings = b.data();
|
||
VkDescriptorSetLayout dsl = VK_NULL_HANDLE;
|
||
VK_TRY(vkCreateDescriptorSetLayout(dev_, &li, nullptr, &dsl), "ds layout");
|
||
|
||
VkPushConstantRange pcr{};
|
||
pcr.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT;
|
||
pcr.offset = 0;
|
||
pcr.size = (uint32_t)sizeof(PushData);
|
||
|
||
VkPipelineLayoutCreateInfo pl{};
|
||
pl.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
|
||
pl.setLayoutCount = 1;
|
||
pl.pSetLayouts = &dsl;
|
||
pl.pushConstantRangeCount = 1;
|
||
pl.pPushConstantRanges = &pcr;
|
||
VkPipelineLayout pll = VK_NULL_HANDLE;
|
||
VK_TRY(vkCreatePipelineLayout(dev_, &pl, nullptr, &pll), "pipeline layout");
|
||
|
||
ds_layout_[bk] = dsl;
|
||
pl_layout_[bk] = pll;
|
||
}
|
||
|
||
for (int i = 0; i < (int)Kernel::COUNT; ++i) {
|
||
const Kernel k = (Kernel)i;
|
||
const std::vector<uint32_t>& spv = spv_for(k);
|
||
if (spv.empty()) continue;
|
||
|
||
VkShaderModuleCreateInfo sm{};
|
||
sm.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
|
||
sm.codeSize = spv.size() * sizeof(uint32_t);
|
||
sm.pCode = spv.data();
|
||
VkShaderModule mod = VK_NULL_HANDLE;
|
||
VK_TRY(vkCreateShaderModule(dev_, &sm, nullptr, &mod), "vkCreateShaderModule");
|
||
|
||
const BindKey bk = bindings_for(k);
|
||
auto itl = pl_layout_.find(bk);
|
||
if (itl == pl_layout_.end()) {
|
||
vkDestroyShaderModule(dev_, mod, nullptr);
|
||
err = std::string("нет pipeline layout для ядра ") + kernel_name(k);
|
||
return false;
|
||
}
|
||
VkComputePipelineCreateInfo ci{};
|
||
ci.sType = VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO;
|
||
ci.stage.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
|
||
ci.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT;
|
||
ci.stage.module = mod;
|
||
ci.stage.pName = "main";
|
||
ci.layout = itl->second;
|
||
|
||
VkPipeline pipe = VK_NULL_HANDLE;
|
||
const VkResult r = vkCreateComputePipelines(dev_, VK_NULL_HANDLE, 1, &ci, nullptr, &pipe);
|
||
vkDestroyShaderModule(dev_, mod, nullptr);
|
||
if (r != VK_SUCCESS) {
|
||
char b[256];
|
||
snprintf(b, sizeof b, "vkCreateComputePipelines(%s): VkResult %d", kernel_name(k), (int)r);
|
||
err = b;
|
||
return false;
|
||
}
|
||
pipelines_[(size_t)i] = pipe;
|
||
}
|
||
return true;
|
||
}
|
||
|
||
bool VkBackend::init(const VulkanOptions& opt, std::string& err) {
|
||
opt_ = opt;
|
||
if (!create_instance(err)) { shutdown(); return false; }
|
||
if (!pick_device(err)) { shutdown(); return false; }
|
||
if (!create_logical_device(err)) { shutdown(); return false; }
|
||
if (!create_rings(err)) { shutdown(); return false; }
|
||
if (!create_pools_and_pipelines(err)) { shutdown(); return false; }
|
||
inited_ = true;
|
||
|
||
char ib[512];
|
||
snprintf(ib, sizeof ib,
|
||
"[vulkan] устройство: %s | compute queue family %u | staging %llu МиБ | "
|
||
"readback %llu МиБ | порог CPU/GPU %d FLOP | батчи: один submit на шаг",
|
||
device_name_.c_str(), queue_family_,
|
||
(unsigned long long)(staging_.size / (1024 * 1024)),
|
||
(unsigned long long)(readback_.size / (1024 * 1024)),
|
||
opt_.min_gemm_flops);
|
||
engine_info(ib);
|
||
return true;
|
||
}
|
||
|
||
void VkBackend::shutdown() {
|
||
if (dev_ != VK_NULL_HANDLE) {
|
||
vkDeviceWaitIdle(dev_);
|
||
for (auto& kv : cache_) free_device_buf(*kv.second);
|
||
cache_.clear();
|
||
for (auto& kv : scratch_) free_device_buf(*kv.second);
|
||
scratch_.clear();
|
||
free_device_buf(token_out_);
|
||
free_device_buf(adam_out_);
|
||
// staging_/readback_ отображены — освобождаем как обычные буферы
|
||
if (staging_.buffer) { vkDestroyBuffer(dev_, staging_.buffer, nullptr); }
|
||
if (staging_.mem) { vkFreeMemory(dev_, staging_.mem, nullptr); }
|
||
if (readback_.buffer) { vkDestroyBuffer(dev_, readback_.buffer, nullptr); }
|
||
if (readback_.mem) { vkFreeMemory(dev_, readback_.mem, nullptr); }
|
||
staging_ = GpuBuf{}; readback_ = GpuBuf{};
|
||
staging_map_ = nullptr; readback_map_ = nullptr; token_map_ = nullptr; adam_map_ = nullptr;
|
||
|
||
for (auto& p : pipelines_) if (p) { vkDestroyPipeline(dev_, p, nullptr); p = VK_NULL_HANDLE; }
|
||
for (auto& kv : pl_layout_) if (kv.second) vkDestroyPipelineLayout(dev_, kv.second, nullptr);
|
||
for (auto& kv : ds_layout_) if (kv.second) vkDestroyDescriptorSetLayout(dev_, kv.second, nullptr);
|
||
pl_layout_.clear();
|
||
ds_layout_.clear();
|
||
if (desc_pool_) { vkDestroyDescriptorPool(dev_, desc_pool_, nullptr); desc_pool_ = VK_NULL_HANDLE; }
|
||
for (int i = 0; i < kCmdBuffers; ++i)
|
||
if (fences_[i]) { vkDestroyFence(dev_, fences_[i], nullptr); fences_[i] = VK_NULL_HANDLE; }
|
||
if (cmd_pool_) { vkDestroyCommandPool(dev_, cmd_pool_, nullptr); cmd_pool_ = VK_NULL_HANDLE; }
|
||
vkDestroyDevice(dev_, nullptr);
|
||
dev_ = VK_NULL_HANDLE;
|
||
}
|
||
if (instance_) { vkDestroyInstance(instance_, nullptr); instance_ = VK_NULL_HANDLE; }
|
||
inited_ = false;
|
||
degraded_ = false;
|
||
bytes_allocated_ = 0;
|
||
batch_open_ = false;
|
||
inflight_ = Inflight{};
|
||
pending_downloads_.clear();
|
||
}
|
||
|
||
void VkBackend::begin_step() {
|
||
std::lock_guard<std::mutex> lk(mtx_);
|
||
if (dev_ == VK_NULL_HANDLE || degraded_) return;
|
||
++epoch_;
|
||
// Подчистка записей умерших тензоров (реаллокации между шагами).
|
||
// Записи текущего/предыдущего шага НЕ трогаем: их могут ссылаться
|
||
// открытый батч и inflight.
|
||
if (cache_.size() > 64) sweep_locked(cache_.size() > kMaxCacheEntries);
|
||
if (scratch_.size() > 64) {
|
||
for (auto it = scratch_.begin(); it != scratch_.end();) {
|
||
if (epoch_ - it->second->epoch > kCacheTtlEpochs) {
|
||
free_device_buf(*it->second);
|
||
it = scratch_.erase(it);
|
||
} else ++it;
|
||
}
|
||
}
|
||
}
|
||
|
||
void VkBackend::sweep_locked(bool aggressive) {
|
||
const uint64_t ttl = aggressive ? 1 : kCacheTtlEpochs;
|
||
for (auto it = cache_.begin(); it != cache_.end();) {
|
||
if (epoch_ - it->second->epoch > ttl) {
|
||
free_device_buf(*it->second);
|
||
it = cache_.erase(it);
|
||
} else ++it;
|
||
}
|
||
}
|
||
|
||
// ===========================================================================
|
||
// Буферы
|
||
// ===========================================================================
|
||
void VkBackend::free_device_buf(GpuBuf& b) {
|
||
if (!dev_) return;
|
||
if (b.buffer) { vkDestroyBuffer(dev_, b.buffer, nullptr); b.buffer = VK_NULL_HANDLE; }
|
||
if (b.mem) { vkFreeMemory(dev_, b.mem, nullptr); b.mem = VK_NULL_HANDLE; }
|
||
bytes_allocated_ = (b.size > bytes_allocated_) ? bytes_allocated_ - b.size : 0;
|
||
b.size = 0; b.host_dirty = true; b.dev_dirty = false;
|
||
}
|
||
|
||
bool VkBackend::alloc_device_buf(GpuBuf& b, size_t bytes, std::string& err) {
|
||
if (bytes == 0) bytes = sizeof(float);
|
||
VkBufferCreateInfo bi{};
|
||
bi.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
|
||
bi.size = (VkDeviceSize)bytes;
|
||
bi.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT |
|
||
VK_BUFFER_USAGE_TRANSFER_DST_BIT;
|
||
VK_TRY(vkCreateBuffer(dev_, &bi, nullptr, &b.buffer), "vkCreateBuffer");
|
||
|
||
VkMemoryRequirements mr;
|
||
vkGetBufferMemoryRequirements(dev_, b.buffer, &mr);
|
||
VkMemoryAllocateInfo ai{};
|
||
ai.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
|
||
ai.allocationSize = mr.size;
|
||
ai.memoryTypeIndex = find_memory_type(mr.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
|
||
if (ai.memoryTypeIndex == UINT32_MAX)
|
||
ai.memoryTypeIndex = find_memory_type(mr.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT);
|
||
if (ai.memoryTypeIndex == UINT32_MAX) {
|
||
vkDestroyBuffer(dev_, b.buffer, nullptr); b.buffer = VK_NULL_HANDLE;
|
||
err = "нет подходящего типа памяти";
|
||
return false;
|
||
}
|
||
if (vkAllocateMemory(dev_, &ai, nullptr, &b.mem) != VK_SUCCESS) {
|
||
// лимит аллокаций драйвера: чистим кэш и пробуем ещё раз
|
||
vkDestroyBuffer(dev_, b.buffer, nullptr); b.buffer = VK_NULL_HANDLE;
|
||
sweep_locked(true);
|
||
VK_TRY(vkAllocateMemory(dev_, &ai, nullptr, &b.mem), "vkAllocateMemory (после sweep)");
|
||
}
|
||
VK_TRY(vkBindBufferMemory(dev_, b.buffer, b.mem, 0), "vkBindBufferMemory");
|
||
b.size = (VkDeviceSize)bytes;
|
||
b.host_dirty = true; // содержимое устройства не определено
|
||
b.dev_dirty = false;
|
||
b.epoch = epoch_;
|
||
bytes_allocated_ += b.size;
|
||
return true;
|
||
}
|
||
|
||
GpuBuf* VkBackend::resolve(const BufSpec& sp, std::string& err) {
|
||
if (sp.flags & BF_DIRECT) return sp.direct;
|
||
if (!sp.host || sp.bytes == 0) { err = "пустой буфер"; return nullptr; }
|
||
const BufKey key{sp.host, sp.bytes};
|
||
auto it = cache_.find(key);
|
||
if (it == cache_.end()) {
|
||
if (cache_.size() >= kMaxCacheEntries) sweep_locked(true);
|
||
auto nb = std::make_unique<GpuBuf>();
|
||
if (!alloc_device_buf(*nb, sp.bytes, err)) return nullptr;
|
||
it = cache_.emplace(key, std::move(nb)).first;
|
||
}
|
||
GpuBuf* b = it->second.get();
|
||
b->epoch = epoch_;
|
||
return b;
|
||
}
|
||
|
||
// ===========================================================================
|
||
// Батчи: запись, барьеры, submit, wait, flush
|
||
// ===========================================================================
|
||
bool VkBackend::begin_batch_locked(std::string& err) {
|
||
if (batch_open_) return true;
|
||
// ротация: cb не должен быть в inflight (inflight ≤ 1, cb'ов 4)
|
||
cur_cb_ = cbs_[cb_idx_];
|
||
cb_idx_ = (cb_idx_ + 1) % kCmdBuffers;
|
||
if (vkResetCommandBuffer(cur_cb_, 0) != VK_SUCCESS) { err = "vkResetCommandBuffer"; return false; }
|
||
VkCommandBufferBeginInfo bb{};
|
||
bb.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
|
||
bb.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
|
||
if (vkBeginCommandBuffer(cur_cb_, &bb) != VK_SUCCESS) { err = "vkBeginCommandBuffer"; return false; }
|
||
batch_open_ = true;
|
||
stage_ = Stage::None;
|
||
dispatches_in_cb_ = 0;
|
||
return true;
|
||
}
|
||
|
||
void VkBackend::barrier_to_compute_locked() {
|
||
// барьер нужен, если до этого были transfer-записи (copy/fill)
|
||
if (stage_ != Stage::Transfer) { if (stage_ == Stage::None) stage_ = Stage::Compute; return; }
|
||
VkMemoryBarrier mb{};
|
||
mb.sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER;
|
||
mb.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
|
||
mb.dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
|
||
vkCmdPipelineBarrier(cur_cb_, VK_PIPELINE_STAGE_TRANSFER_BIT,
|
||
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
|
||
0, 1, &mb, 0, nullptr, 0, nullptr);
|
||
stage_ = Stage::Compute;
|
||
}
|
||
|
||
void VkBackend::barrier_compute_locked() {
|
||
// между зависимыми dispatch: запись шейдера → чтение шейдера
|
||
if (stage_ == Stage::Transfer) { barrier_to_compute_locked(); return; }
|
||
VkMemoryBarrier mb{};
|
||
mb.sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER;
|
||
mb.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT;
|
||
mb.dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
|
||
vkCmdPipelineBarrier(cur_cb_, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
|
||
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
|
||
0, 1, &mb, 0, nullptr, 0, nullptr);
|
||
stage_ = Stage::Compute;
|
||
}
|
||
|
||
void VkBackend::barrier_to_transfer_locked() {
|
||
if (stage_ != Stage::Compute) { stage_ = Stage::Transfer; return; }
|
||
VkMemoryBarrier mb{};
|
||
mb.sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER;
|
||
mb.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT;
|
||
mb.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
|
||
vkCmdPipelineBarrier(cur_cb_, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
|
||
VK_PIPELINE_STAGE_TRANSFER_BIT,
|
||
0, 1, &mb, 0, nullptr, 0, nullptr);
|
||
stage_ = Stage::Transfer;
|
||
}
|
||
|
||
bool VkBackend::ensure_ring_space(size_t need) {
|
||
const VkDeviceSize aligned = (VkDeviceSize)((need + ring_align_ - 1) / ring_align_) * ring_align_;
|
||
if (ring_off_ + aligned <= staging_.size) return true;
|
||
// кольцо занято: синхронизируем всё (submit+wait), кольца сбрасываются
|
||
flush_locked();
|
||
return ring_off_ + aligned <= staging_.size;
|
||
}
|
||
|
||
bool VkBackend::record_upload_locked(GpuBuf& b, const void* host, size_t bytes, std::string& err) {
|
||
const char* src = (const char*)host;
|
||
size_t done = 0;
|
||
while (done < bytes) {
|
||
size_t chunk = std::min(bytes - done, (size_t)staging_.size);
|
||
if (!ensure_ring_space(chunk)) { err = "staging-кольцо мало для закачки"; return false; }
|
||
// ensure_ring мог сделать flush (батч закрыт) — открываем снова
|
||
if (!begin_batch_locked(err)) return false;
|
||
memcpy((char*)staging_map_ + ring_off_, src + done, chunk);
|
||
VkBufferCopy cp{};
|
||
cp.srcOffset = ring_off_;
|
||
cp.dstOffset = (VkDeviceSize)done;
|
||
cp.size = (VkDeviceSize)chunk;
|
||
vkCmdCopyBuffer(cur_cb_, staging_.buffer, b.buffer, 1, &cp);
|
||
stage_ = Stage::Transfer;
|
||
ring_off_ += (VkDeviceSize)((chunk + ring_align_ - 1) / ring_align_) * ring_align_;
|
||
done += chunk;
|
||
}
|
||
return true;
|
||
}
|
||
|
||
void VkBackend::schedule_download_locked(const BufKey& key, void* host, size_t bytes) {
|
||
for (const auto& pd : pending_downloads_)
|
||
if (pd.key == key && pd.host == host) return; // уже в очереди
|
||
PendingDownload pd;
|
||
pd.key = key; pd.host = host; pd.bytes = bytes; pd.done = 0;
|
||
pending_downloads_.push_back(pd);
|
||
}
|
||
|
||
bool VkBackend::alloc_set_locked(const BindKey& bk, VkDescriptorSet& out, std::string& err) {
|
||
auto itl = ds_layout_.find(bk);
|
||
if (itl == ds_layout_.end()) { err = "нет descriptor layout"; return false; }
|
||
VkDescriptorSetAllocateInfo dsi{};
|
||
dsi.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
|
||
dsi.descriptorPool = desc_pool_;
|
||
dsi.descriptorSetCount = 1;
|
||
dsi.pSetLayouts = &itl->second;
|
||
if (vkAllocateDescriptorSets(dev_, &dsi, &out) == VK_SUCCESS) return true;
|
||
// пул исчерпан: сбрасываем всё (flush освобождает sets предыдущих батчей)
|
||
flush_locked();
|
||
vkResetDescriptorPool(dev_, desc_pool_, 0);
|
||
if (!begin_batch_locked(err)) return false;
|
||
if (vkAllocateDescriptorSets(dev_, &dsi, &out) != VK_SUCCESS) {
|
||
err = "не удалось выделить descriptor set (пул исчерпан)";
|
||
return false;
|
||
}
|
||
return true;
|
||
}
|
||
|
||
bool VkBackend::launch_locked(std::string& err) {
|
||
if (degraded_) return false;
|
||
if (inflight_.valid) wait_inflight_locked(); // больше одного в полёте не держим
|
||
if (!batch_open_) return true; // нечего отправлять
|
||
if (vkEndCommandBuffer(cur_cb_) != VK_SUCCESS) {
|
||
batch_open_ = false;
|
||
err = "vkEndCommandBuffer";
|
||
degraded_enter();
|
||
return false;
|
||
}
|
||
// сбрасываем предыдущий сигнал fence'а
|
||
vkResetFences(dev_, 1, &fences_[fence_idx_]);
|
||
VkSubmitInfo si{};
|
||
si.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
|
||
si.commandBufferCount = 1;
|
||
si.pCommandBuffers = &cur_cb_;
|
||
const VkFence f = fences_[fence_idx_];
|
||
fence_idx_ = (fence_idx_ + 1) % kCmdBuffers;
|
||
if (vkQueueSubmit(queue_, 1, &si, f) != VK_SUCCESS) {
|
||
batch_open_ = false;
|
||
err = "vkQueueSubmit";
|
||
degraded_enter();
|
||
return false;
|
||
}
|
||
inflight_ = Inflight{true, cur_cb_, f, std::move(cur_sets_)};
|
||
cur_sets_.clear();
|
||
batch_open_ = false;
|
||
stage_ = Stage::None;
|
||
dispatches_in_cb_ = 0;
|
||
return true;
|
||
}
|
||
|
||
void VkBackend::wait_inflight_locked() {
|
||
if (!inflight_.valid) return;
|
||
vkWaitForFences(dev_, 1, &inflight_.fence, VK_TRUE, UINT64_MAX);
|
||
if (!inflight_.sets.empty())
|
||
vkFreeDescriptorSets(dev_, desc_pool_, (uint32_t)inflight_.sets.size(), inflight_.sets.data());
|
||
inflight_ = Inflight{};
|
||
}
|
||
|
||
void VkBackend::flush_locked() {
|
||
if (degraded_) { pending_downloads_.clear(); return; }
|
||
|
||
// 1) Исполняем отложенные вычитки (возможно, несколькими submit'ами:
|
||
// readback-кольцо ограничено).
|
||
while (!pending_downloads_.empty()) {
|
||
std::string err;
|
||
if (!begin_batch_locked(err)) { pending_downloads_.clear(); break; }
|
||
if (dispatches_in_cb_ > 0 || stage_ == Stage::Compute) barrier_to_transfer_locked();
|
||
|
||
// сколько вычиток влезает в readback-кольцо (за один submit)
|
||
struct Copy { PendingDownload* pd; VkDeviceSize rb_off; VkDeviceSize bytes; };
|
||
std::vector<Copy> copies;
|
||
copies.reserve(64);
|
||
VkDeviceSize used = 0;
|
||
for (auto& pd : pending_downloads_) {
|
||
if (copies.size() >= 64) break;
|
||
const size_t remain = pd.bytes - pd.done;
|
||
if (remain == 0) continue;
|
||
const size_t fit = std::min(remain, (size_t)(readback_.size - used));
|
||
if (fit == 0) break;
|
||
auto it = cache_.find(pd.key);
|
||
if (it == cache_.end()) { pd.done = pd.bytes; continue; } // запись умерла — отдавать нечего
|
||
VkBufferCopy cp{};
|
||
cp.srcOffset = (VkDeviceSize)pd.done;
|
||
cp.dstOffset = used;
|
||
cp.size = (VkDeviceSize)fit;
|
||
vkCmdCopyBuffer(cur_cb_, it->second->buffer, readback_.buffer, 1, &cp);
|
||
copies.push_back(Copy{&pd, used, (VkDeviceSize)fit});
|
||
used += (VkDeviceSize)((fit + ring_align_ - 1) / ring_align_) * ring_align_;
|
||
pd.done += fit;
|
||
}
|
||
if (copies.empty()) {
|
||
// все записи умерли — чистим очередь и выходим
|
||
pending_downloads_.clear();
|
||
batch_open_ = false; // пустой батч выбрасываем (cb переиспользуется после reset)
|
||
stage_ = Stage::None;
|
||
break;
|
||
}
|
||
stage_ = Stage::Transfer;
|
||
|
||
if (vkEndCommandBuffer(cur_cb_) != VK_SUCCESS) { pending_downloads_.clear(); batch_open_ = false; break; }
|
||
vkResetFences(dev_, 1, &fences_[fence_idx_]);
|
||
VkSubmitInfo si{};
|
||
si.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
|
||
si.commandBufferCount = 1;
|
||
si.pCommandBuffers = &cur_cb_;
|
||
const VkFence f = fences_[fence_idx_];
|
||
fence_idx_ = (fence_idx_ + 1) % kCmdBuffers;
|
||
if (vkQueueSubmit(queue_, 1, &si, f) != VK_SUCCESS) {
|
||
pending_downloads_.clear();
|
||
batch_open_ = false;
|
||
degraded_enter();
|
||
break;
|
||
}
|
||
vkWaitForFences(dev_, 1, &f, VK_TRUE, UINT64_MAX);
|
||
|
||
// разносим по host-указателям: readback отображён ПОСТОЯННО (shared
|
||
// memory GPU↔CPU) — никакого vkMapMemory, обычный memcpy.
|
||
for (const Copy& c : copies)
|
||
memcpy((char*)c.pd->host + (c.pd->done - (size_t)c.bytes),
|
||
(const char*)readback_map_ + c.rb_off, (size_t)c.bytes);
|
||
|
||
if (!cur_sets_.empty()) {
|
||
vkFreeDescriptorSets(dev_, desc_pool_, (uint32_t)cur_sets_.size(), cur_sets_.data());
|
||
cur_sets_.clear();
|
||
}
|
||
batch_open_ = false;
|
||
stage_ = Stage::None;
|
||
dispatches_in_cb_ = 0;
|
||
|
||
pending_downloads_.erase(
|
||
std::remove_if(pending_downloads_.begin(), pending_downloads_.end(),
|
||
[this](const PendingDownload& p) {
|
||
if (p.done >= p.bytes) {
|
||
auto it = cache_.find(p.key);
|
||
if (it != cache_.end()) {
|
||
it->second->dev_dirty = false;
|
||
it->second->host_dirty = false; // копии синхронны
|
||
}
|
||
return true;
|
||
}
|
||
return false;
|
||
}),
|
||
pending_downloads_.end());
|
||
}
|
||
|
||
// 2) батч без вычиток (или остатки) — отправить и дождаться
|
||
if (batch_open_) {
|
||
std::string err;
|
||
launch_locked(err); // при ошибке degraded_enter взведётся внутри submit-ветки
|
||
if (!degraded_ && !err.empty()) { /* launch сам обработал */ }
|
||
}
|
||
wait_inflight_locked();
|
||
|
||
// 3) кольца свободны — сброс
|
||
ring_off_ = 0;
|
||
rb_off_ = 0;
|
||
}
|
||
|
||
void VkBackend::degraded_enter() {
|
||
if (degraded_) return;
|
||
degraded_ = true;
|
||
engine_error("[vulkan] ошибка устройства — до конца процесса работаю через CPU-фолбэк");
|
||
// Состояние батчей выбрасываем БЕЗ ожидания (устройство может быть потеряно).
|
||
batch_open_ = false;
|
||
inflight_ = Inflight{};
|
||
pending_downloads_.clear();
|
||
cur_sets_.clear();
|
||
// Все device-копии больше не достоверны: помечаем «хост — источник истины»,
|
||
// последующие CPU-фолбэки работают с host-данными и перекачивают их заново.
|
||
for (auto& kv : cache_) { kv.second->host_dirty = true; kv.second->dev_dirty = false; }
|
||
}
|
||
|
||
// --- nolock-хелперы (вызываются под захваченным mtx_) ---
|
||
void VkBackend::materialize_nolock(Tensor& t) {
|
||
if (degraded_ || t.n() == 0) return;
|
||
const BufKey key{t.ptr(), t.n() * sizeof(float)};
|
||
auto it = cache_.find(key);
|
||
if (it == cache_.end() || !it->second->dev_dirty) return;
|
||
schedule_download_locked(key, t.ptr(), (size_t)key.bytes);
|
||
flush_locked();
|
||
}
|
||
|
||
void VkBackend::materialize_nolock(const std::vector<Tensor*>& ts) {
|
||
if (degraded_) return;
|
||
bool any = false;
|
||
for (Tensor* t : ts) {
|
||
if (!t || t->n() == 0) continue;
|
||
const BufKey key{t->ptr(), t->n() * sizeof(float)};
|
||
auto it = cache_.find(key);
|
||
if (it == cache_.end() || !it->second->dev_dirty) continue;
|
||
schedule_download_locked(key, t->ptr(), (size_t)key.bytes);
|
||
any = true;
|
||
}
|
||
if (any) flush_locked();
|
||
}
|
||
|
||
void VkBackend::host_written_nolock(Tensor& t) {
|
||
if (degraded_ || t.n() == 0) return;
|
||
auto it = cache_.find(BufKey{t.ptr(), t.n() * sizeof(float)});
|
||
if (it == cache_.end()) return;
|
||
it->second->host_dirty = true;
|
||
it->second->dev_dirty = false;
|
||
}
|
||
|
||
void VkBackend::host_written_nolock(const std::vector<Tensor*>& ts) {
|
||
if (degraded_) return;
|
||
for (Tensor* t : ts) {
|
||
if (!t || t->n() == 0) continue;
|
||
auto it = cache_.find(BufKey{t->ptr(), t->n() * sizeof(float)});
|
||
if (it == cache_.end()) continue;
|
||
it->second->host_dirty = true;
|
||
it->second->dev_dirty = false;
|
||
}
|
||
}
|
||
|
||
// ===========================================================================
|
||
// run — запись одной операции в текущий батч
|
||
// ===========================================================================
|
||
bool VkBackend::run(Kernel k, const std::vector<BufSpec>& bufs,
|
||
const int32_t P[8], const float F[8], uint32_t work_items,
|
||
std::string& err) {
|
||
if (degraded_) { err = "vulkan degraded"; return false; }
|
||
const BindKey bk = bindings_for(k);
|
||
const int nb = (int)bufs.size();
|
||
if ((size_t)nb != bk.size()) {
|
||
char b[192];
|
||
snprintf(b, sizeof b, "%s: передано %d буферов, шейдер ждёт %zu",
|
||
kernel_name(k), nb, bk.size());
|
||
err = b;
|
||
return false;
|
||
}
|
||
if (!pipelines_[(size_t)k]) { err = std::string("pipeline не создан: ") + kernel_name(k); return false; }
|
||
if (work_items == 0) return true;
|
||
if (!begin_batch_locked(err)) return false;
|
||
|
||
std::vector<GpuBuf*> live((size_t)nb, nullptr);
|
||
for (int i = 0; i < nb; ++i) {
|
||
const BufSpec& sp = bufs[(size_t)i];
|
||
GpuBuf* b = resolve(sp, err);
|
||
if (!b) return false;
|
||
live[(size_t)i] = b;
|
||
|
||
if ((sp.flags & BF_DIRECT) || !(sp.flags & (BF_UPLOAD | BF_ZERO))) continue;
|
||
|
||
if (sp.flags & BF_ZERO) {
|
||
// обнуление на устройстве (fill), хост-копия устаревает
|
||
vkCmdFillBuffer(cur_cb_, b->buffer, 0, b->size, 0u);
|
||
stage_ = Stage::Transfer;
|
||
b->dev_dirty = true;
|
||
b->host_dirty = false;
|
||
continue;
|
||
}
|
||
const bool force = (sp.flags & BF_FORCE_UPLOAD) != 0;
|
||
if (force || b->host_dirty) {
|
||
if (!record_upload_locked(*b, sp.host, sp.bytes, err)) return false;
|
||
// record_upload мог переоткрыть батч — cur_cb_ тот же (begin_batch
|
||
// берёт следующий cb только если батч был закрыт flush'ем)
|
||
if (!batch_open_) { if (!begin_batch_locked(err)) return false; }
|
||
b->host_dirty = false;
|
||
b->dev_dirty = false; // копии синхронны
|
||
}
|
||
}
|
||
|
||
// барьеры: transfer (uploads/fills) → compute; либо compute → compute
|
||
if (stage_ == Stage::Transfer) barrier_to_compute_locked();
|
||
else if (dispatches_in_cb_ > 0) barrier_compute_locked();
|
||
|
||
// --- descriptor set ---
|
||
VkDescriptorSet set = VK_NULL_HANDLE;
|
||
if (!alloc_set_locked(bk, set, err)) return false;
|
||
|
||
std::vector<VkDescriptorBufferInfo> bi((size_t)nb);
|
||
std::vector<VkWriteDescriptorSet> w((size_t)nb);
|
||
for (int i = 0; i < nb; ++i) {
|
||
bi[(size_t)i].buffer = live[(size_t)i]->buffer;
|
||
bi[(size_t)i].offset = 0;
|
||
bi[(size_t)i].range = live[(size_t)i]->size;
|
||
w[(size_t)i].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
|
||
w[(size_t)i].dstSet = set;
|
||
w[(size_t)i].dstBinding = bk[(size_t)i];
|
||
w[(size_t)i].descriptorCount = 1;
|
||
w[(size_t)i].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
|
||
w[(size_t)i].pBufferInfo = &bi[(size_t)i];
|
||
}
|
||
vkUpdateDescriptorSets(dev_, (uint32_t)nb, w.data(), 0, nullptr);
|
||
cur_sets_.push_back(set);
|
||
|
||
// --- push + dispatch ---
|
||
PushData pd{};
|
||
for (int i = 0; i < 8; ++i) { pd.P[i] = P[i]; pd.F[i] = F[i]; }
|
||
auto itp = pl_layout_.find(bk);
|
||
if (itp == pl_layout_.end()) { err = "нет pipeline layout"; return false; }
|
||
|
||
vkCmdBindPipeline(cur_cb_, VK_PIPELINE_BIND_POINT_COMPUTE, pipelines_[(size_t)k]);
|
||
vkCmdBindDescriptorSets(cur_cb_, VK_PIPELINE_BIND_POINT_COMPUTE, itp->second,
|
||
0, 1, &set, 0, nullptr);
|
||
vkCmdPushConstants(cur_cb_, itp->second, VK_SHADER_STAGE_COMPUTE_BIT,
|
||
0, (uint32_t)sizeof(pd), &pd);
|
||
const uint32_t groups = (work_items + kWorkGroupSize - 1) / kWorkGroupSize;
|
||
vkCmdDispatch(cur_cb_, groups, 1, 1);
|
||
++dispatches_in_cb_;
|
||
stage_ = Stage::Compute;
|
||
|
||
// выходы: устройство новее хоста. host_dirty ОБЯЗАТЕЛЬНО сбрасывается:
|
||
// иначе следующий rd_buf закачает поверх свежих device-данных устаревший
|
||
// (или мусорный) host-буфер — именно так обнулялся весь forward.
|
||
for (int i = 0; i < nb; ++i) {
|
||
const BufSpec& sp = bufs[(size_t)i];
|
||
if (sp.flags & (BF_OUTPUT | BF_ACCUM)) {
|
||
live[(size_t)i]->dev_dirty = true;
|
||
live[(size_t)i]->host_dirty = false;
|
||
}
|
||
if (sp.flags & BF_HOST) {
|
||
schedule_download_locked(BufKey{sp.host, sp.bytes}, const_cast<void*>(sp.host), sp.bytes);
|
||
}
|
||
}
|
||
return true;
|
||
}
|
||
|
||
void VkBackend::sync_host_for_fallback(const std::vector<BufSpec>& bufs) {
|
||
if (degraded_) return;
|
||
bool any = false;
|
||
for (const BufSpec& sp : bufs) {
|
||
if ((sp.flags & BF_DIRECT) || !sp.host || sp.bytes == 0) continue;
|
||
const BufKey key{sp.host, sp.bytes};
|
||
auto it = cache_.find(key);
|
||
if (it == cache_.end() || !it->second->dev_dirty) continue;
|
||
schedule_download_locked(key, const_cast<void*>(sp.host), sp.bytes);
|
||
any = true;
|
||
}
|
||
if (any) flush_locked();
|
||
}
|
||
|
||
void VkBackend::mark_host_outputs(const std::vector<BufSpec>& bufs) {
|
||
for (const BufSpec& sp : bufs) {
|
||
if ((sp.flags & BF_DIRECT) || !sp.host || sp.bytes == 0) continue;
|
||
if (!(sp.flags & (BF_OUTPUT | BF_ACCUM | BF_ZERO | BF_HOST))) continue;
|
||
const BufKey key{sp.host, sp.bytes};
|
||
auto it = cache_.find(key);
|
||
if (it == cache_.end()) continue;
|
||
it->second->host_dirty = true; // CPU-фолбэк записал хост
|
||
it->second->dev_dirty = false;
|
||
}
|
||
}
|
||
|
||
// ===========================================================================
|
||
// Отложенная синхронизация (публичные Backend-методы)
|
||
// ===========================================================================
|
||
void VkBackend::materialize(Tensor& t) {
|
||
std::lock_guard<std::mutex> lk(mtx_);
|
||
materialize_nolock(t);
|
||
}
|
||
|
||
void VkBackend::materialize(const std::vector<Tensor*>& ts) {
|
||
std::lock_guard<std::mutex> lk(mtx_);
|
||
materialize_nolock(ts);
|
||
}
|
||
|
||
void VkBackend::host_written(Tensor& t) {
|
||
std::lock_guard<std::mutex> lk(mtx_);
|
||
host_written_nolock(t);
|
||
}
|
||
|
||
void VkBackend::host_written(const std::vector<Tensor*>& ts) {
|
||
std::lock_guard<std::mutex> lk(mtx_);
|
||
host_written_nolock(ts);
|
||
}
|
||
|
||
void VkBackend::invalidate(const Tensor& t) {
|
||
std::lock_guard<std::mutex> lk(mtx_);
|
||
if (degraded_ || t.n() == 0) return;
|
||
auto it = cache_.find(BufKey{t.ptr(), t.n() * sizeof(float)});
|
||
if (it == cache_.end()) return;
|
||
it->second->host_dirty = true;
|
||
it->second->dev_dirty = false;
|
||
}
|
||
|
||
void VkBackend::invalidate_all() {
|
||
std::lock_guard<std::mutex> lk(mtx_);
|
||
for (auto& kv : cache_) { kv.second->host_dirty = true; kv.second->dev_dirty = false; }
|
||
}
|
||
|
||
void VkBackend::flush() {
|
||
std::lock_guard<std::mutex> lk(mtx_);
|
||
if (degraded_) return;
|
||
flush_locked();
|
||
}
|
||
|
||
void VkBackend::sync() { flush(); }
|
||
|
||
bool VkBackend::supports(const char* k) const {
|
||
if (!k) return false;
|
||
return inited_ && !degraded_;
|
||
}
|
||
|
||
// ===========================================================================
|
||
// Ядра (обёртки). Ошибка записи → вычитать входы → CPU-фолбэк → пометить выходы.
|
||
// ===========================================================================
|
||
namespace {
|
||
// Предупреждение об откате на CPU печатается ОДИН раз на ядро.
|
||
inline void fallback_warn(const char* what, const std::string& err) {
|
||
static std::mutex warn_mtx;
|
||
static std::set<std::string> warned;
|
||
std::lock_guard<std::mutex> lk(warn_mtx);
|
||
if (!warned.insert(what).second) return;
|
||
engine_warn(std::string("[vulkan] ") + what + ": " + err + " — откат на CPU (предупреждаю один раз)");
|
||
}
|
||
void fillP(int32_t out[8], std::initializer_list<int32_t> v) {
|
||
for (int i = 0; i < 8; ++i) out[i] = 0;
|
||
int i = 0; for (int32_t x : v) { if (i < 8) out[i++] = x; }
|
||
}
|
||
void fillF(float out[8], std::initializer_list<float> v) {
|
||
for (int i = 0; i < 8; ++i) out[i] = 0.0f;
|
||
int i = 0; for (float x : v) { if (i < 8) out[i++] = x; }
|
||
}
|
||
} // namespace
|
||
|
||
// Единый шаблон вызова ядра с CPU-фолбэком:
|
||
// VK_CALL(имя, kernel, bufs, P, F, work_items, cpu_fallback_expr)
|
||
#define VK_CALL(what, kern, bufs, P, F, wi, fallback_expr) \
|
||
do { \
|
||
std::lock_guard<std::mutex> lk(mtx_); \
|
||
if (degraded_) { fallback_expr; return; } \
|
||
std::string err; \
|
||
if (!run(kern, bufs, P, F, wi, err)) { \
|
||
fallback_warn(what, err); \
|
||
sync_host_for_fallback(bufs); \
|
||
fallback_expr; \
|
||
mark_host_outputs(bufs); \
|
||
return; \
|
||
} \
|
||
} while (0)
|
||
|
||
void VkBackend::gemm_nn(const Tensor& A, const Tensor& B, Tensor& C) {
|
||
const int N = A.R(), K = A.C(), M = B.C();
|
||
if (N <= 0 || K <= 0 || M <= 0) return;
|
||
if (C.R() != N || C.C() != M) C.resize(N, M); // resize обнуляет хост-копию
|
||
if (small_enough_for_cpu((int64_t)N * M * K)) {
|
||
std::lock_guard<std::mutex> lk(mtx_);
|
||
materialize_nolock(A); materialize_nolock(B);
|
||
cpu_.gemm_nn(A, B, C);
|
||
host_written_nolock(C);
|
||
return;
|
||
}
|
||
int32_t P[8]; float F[8];
|
||
fillP(P, {N, K, M}); fillF(F, {});
|
||
// Шейдер стартует аккумулятор с C[i] → C обнуляется fill'ом НА УСТРОЙСТВЕ
|
||
// (host-нули из resize закачивать не нужно).
|
||
std::vector<BufSpec> bufs = {
|
||
rd_buf(A.ptr(), A.n() * sizeof(float)),
|
||
rd_buf(B.ptr(), B.n() * sizeof(float)),
|
||
zero_buf(C.ptr(), C.n() * sizeof(float)),
|
||
};
|
||
VK_CALL("gemm_nn", Kernel::GemmNN, bufs, P, F, (uint32_t)((int64_t)N * M),
|
||
cpu_.gemm_nn(A, B, C));
|
||
}
|
||
|
||
void VkBackend::gemm_nt(const Tensor& A, const Tensor& B, Tensor& C) {
|
||
const int N = A.R(), K = A.C(), M = B.R();
|
||
if (N <= 0 || K <= 0 || M <= 0) return;
|
||
C.resize(N, M);
|
||
if (small_enough_for_cpu((int64_t)N * M * K)) {
|
||
std::lock_guard<std::mutex> lk(mtx_);
|
||
materialize_nolock(A); materialize_nolock(B);
|
||
cpu_.gemm_nt(A, B, C);
|
||
host_written_nolock(C);
|
||
return;
|
||
}
|
||
int32_t P[8]; float F[8];
|
||
fillP(P, {N, K, M}); fillF(F, {});
|
||
std::vector<BufSpec> bufs = {
|
||
rd_buf(A.ptr(), A.n() * sizeof(float)),
|
||
rd_buf(B.ptr(), B.n() * sizeof(float)),
|
||
out_buf(C.ptr(), C.n() * sizeof(float)),
|
||
};
|
||
VK_CALL("gemm_nt", Kernel::GemmNT, bufs, P, F, (uint32_t)((int64_t)N * M),
|
||
cpu_.gemm_nt(A, B, C));
|
||
}
|
||
|
||
void VkBackend::gemm_tn(const Tensor& A, const Tensor& B, Tensor& C, bool accumulate) {
|
||
const int N = A.R(), K = A.C(), M = B.C();
|
||
if (N <= 0 || K <= 0 || M <= 0) return;
|
||
if (!accumulate) C.resize(K, M);
|
||
else if (C.R() != K || C.C() != M) {
|
||
engine_error("gemm_tn: форма C " + std::to_string(C.R()) + "x" + std::to_string(C.C()) +
|
||
" != ожидаемой " + std::to_string(K) + "x" + std::to_string(M));
|
||
abort();
|
||
}
|
||
if (small_enough_for_cpu((int64_t)N * M * K)) {
|
||
std::lock_guard<std::mutex> lk(mtx_);
|
||
materialize_nolock(A); materialize_nolock(B);
|
||
if (accumulate) materialize_nolock(C);
|
||
cpu_.gemm_tn(A, B, C, accumulate);
|
||
host_written_nolock(C);
|
||
return;
|
||
}
|
||
int32_t P[8]; float F[8];
|
||
fillP(P, {N, K, M, accumulate ? 1 : 0}); fillF(F, {});
|
||
std::vector<BufSpec> bufs = {
|
||
rd_buf(A.ptr(), A.n() * sizeof(float)),
|
||
rd_buf(B.ptr(), B.n() * sizeof(float)),
|
||
accumulate ? acc_buf(C.ptr(), C.n() * sizeof(float))
|
||
: out_buf(C.ptr(), C.n() * sizeof(float)),
|
||
};
|
||
VK_CALL("gemm_tn", Kernel::GemmTN, bufs, P, F, (uint32_t)((int64_t)K * M),
|
||
cpu_.gemm_tn(A, B, C, accumulate));
|
||
}
|
||
|
||
void VkBackend::rmsnorm_forward(const Tensor& x, const Tensor& w, float eps, Tensor& y, Tensor& inv_rms) {
|
||
const int N = x.R(), D = x.C();
|
||
y.resize(N, D);
|
||
inv_rms.resize(N, 1);
|
||
int32_t P[8]; float F[8];
|
||
fillP(P, {N, D}); fillF(F, {eps});
|
||
std::vector<BufSpec> bufs = {
|
||
rd_buf(x.ptr(), x.n() * sizeof(float)),
|
||
rd_buf(w.ptr(), w.n() * sizeof(float)),
|
||
out_buf(y.ptr(), y.n() * sizeof(float)),
|
||
out_buf(inv_rms.ptr(), inv_rms.n() * sizeof(float)),
|
||
};
|
||
VK_CALL("rmsnorm_fwd", Kernel::RmsNormFwd, bufs, P, F, (uint32_t)N,
|
||
cpu_.rmsnorm_forward(x, w, eps, y, inv_rms));
|
||
}
|
||
|
||
void VkBackend::rmsnorm_backward(const Tensor& x, const Tensor& w, const Tensor& inv_rms,
|
||
const Tensor& dy, Tensor& dx, Tensor& dw) {
|
||
const int N = x.R(), D = x.C();
|
||
dx.resize(N, D);
|
||
dw.resize(1, D);
|
||
dw.zero();
|
||
if (D > 4096) { // MAX_D в шейдере
|
||
std::lock_guard<std::mutex> lk(mtx_);
|
||
materialize_nolock(x); materialize_nolock(w);
|
||
materialize_nolock(inv_rms); materialize_nolock(dy);
|
||
cpu_.rmsnorm_backward(x, w, inv_rms, dy, dx, dw);
|
||
host_written_nolock(dx); host_written_nolock(dw);
|
||
return;
|
||
}
|
||
int32_t P[8]; float F[8];
|
||
fillP(P, {N, D}); fillF(F, {});
|
||
// Два независимых прохода: dx по строкам, dw по столбцам.
|
||
std::vector<BufSpec> bufs_dx = {
|
||
rd_buf(x.ptr(), x.n() * sizeof(float)),
|
||
rd_buf(w.ptr(), w.n() * sizeof(float)),
|
||
rd_buf(inv_rms.ptr(), inv_rms.n() * sizeof(float)),
|
||
rd_buf(dy.ptr(), dy.n() * sizeof(float)),
|
||
out_buf(dx.ptr(), dx.n() * sizeof(float)),
|
||
};
|
||
std::vector<BufSpec> bufs_dw = {
|
||
rd_buf(dy.ptr(), dy.n() * sizeof(float)),
|
||
rd_buf(x.ptr(), x.n() * sizeof(float)),
|
||
rd_buf(inv_rms.ptr(), inv_rms.n() * sizeof(float)),
|
||
out_buf(dw.ptr(), dw.n() * sizeof(float)),
|
||
};
|
||
{
|
||
std::lock_guard<std::mutex> lk(mtx_);
|
||
if (degraded_) {
|
||
cpu_.rmsnorm_backward(x, w, inv_rms, dy, dx, dw);
|
||
return;
|
||
}
|
||
std::string err;
|
||
if (!run(Kernel::RmsNormBwd, bufs_dx, P, F, (uint32_t)N, err) ||
|
||
!run(Kernel::RmsNormDw, bufs_dw, P, F, (uint32_t)D, err)) {
|
||
fallback_warn("rmsnorm_bwd", err);
|
||
sync_host_for_fallback(bufs_dx);
|
||
sync_host_for_fallback(bufs_dw);
|
||
cpu_.rmsnorm_backward(x, w, inv_rms, dy, dx, dw);
|
||
mark_host_outputs(bufs_dx);
|
||
mark_host_outputs(bufs_dw);
|
||
}
|
||
}
|
||
}
|
||
|
||
void VkBackend::swiglu_forward(const Tensor& h1, const Tensor& h3, Tensor& ha) {
|
||
ha.resize(h1.R(), h1.C());
|
||
int32_t P[8]; float F[8];
|
||
fillP(P, {(int32_t)ha.n()}); fillF(F, {});
|
||
std::vector<BufSpec> bufs = {
|
||
rd_buf(h1.ptr(), h1.n() * sizeof(float)),
|
||
rd_buf(h3.ptr(), h3.n() * sizeof(float)),
|
||
out_buf(ha.ptr(), ha.n() * sizeof(float)),
|
||
};
|
||
VK_CALL("swiglu_fwd", Kernel::SwigluFwd, bufs, P, F, (uint32_t)ha.n(),
|
||
cpu_.swiglu_forward(h1, h3, ha));
|
||
}
|
||
|
||
void VkBackend::swiglu_backward(const Tensor& h1, const Tensor& h3, const Tensor& dha,
|
||
Tensor& dh1, Tensor& dh3) {
|
||
dh1.resize(h1.R(), h1.C());
|
||
dh3.resize(h3.R(), h3.C());
|
||
int32_t P[8]; float F[8];
|
||
fillP(P, {(int32_t)dh1.n()}); fillF(F, {});
|
||
std::vector<BufSpec> bufs = {
|
||
rd_buf(h1.ptr(), h1.n() * sizeof(float)),
|
||
rd_buf(h3.ptr(), h3.n() * sizeof(float)),
|
||
rd_buf(dha.ptr(), dha.n() * sizeof(float)),
|
||
out_buf(dh1.ptr(), dh1.n() * sizeof(float)),
|
||
out_buf(dh3.ptr(), dh3.n() * sizeof(float)),
|
||
};
|
||
VK_CALL("swiglu_bwd", Kernel::SwigluBwd, bufs, P, F, (uint32_t)dh1.n(),
|
||
cpu_.swiglu_backward(h1, h3, dha, dh1, dh3));
|
||
}
|
||
|
||
void VkBackend::rope_forward(Tensor& q, Tensor& k, int n_seq, int S, int H, int hd,
|
||
const float* cs, const float* sn) {
|
||
const size_t tbl = (size_t)S * (size_t)(hd / 2) * sizeof(float);
|
||
int32_t P[8]; float F[8];
|
||
fillP(P, {n_seq, S, H, hd}); fillF(F, {});
|
||
std::vector<BufSpec> bufs = {
|
||
acc_buf(q.ptr(), q.n() * sizeof(float)),
|
||
acc_buf(k.ptr(), k.n() * sizeof(float)),
|
||
tmp_buf(cs, tbl),
|
||
tmp_buf(sn, tbl),
|
||
};
|
||
VK_CALL("rope_fwd", Kernel::RopeFwd, bufs, P, F, (uint32_t)((int64_t)n_seq * S * H),
|
||
cpu_.rope_forward(q, k, n_seq, S, H, hd, cs, sn));
|
||
}
|
||
|
||
void VkBackend::rope_backward(Tensor& dq, Tensor& dk, int n_seq, int S, int H, int hd,
|
||
const float* cs, const float* sn) {
|
||
const size_t tbl = (size_t)S * (size_t)(hd / 2) * sizeof(float);
|
||
int32_t P[8]; float F[8];
|
||
fillP(P, {n_seq, S, H, hd}); fillF(F, {});
|
||
std::vector<BufSpec> bufs = {
|
||
acc_buf(dq.ptr(), dq.n() * sizeof(float)),
|
||
acc_buf(dk.ptr(), dk.n() * sizeof(float)),
|
||
tmp_buf(cs, tbl),
|
||
tmp_buf(sn, tbl),
|
||
};
|
||
VK_CALL("rope_bwd", Kernel::RopeBwd, bufs, P, F, (uint32_t)((int64_t)n_seq * S * H),
|
||
cpu_.rope_backward(dq, dk, n_seq, S, H, hd, cs, sn));
|
||
}
|
||
|
||
void VkBackend::softmax_ce(const Tensor& logits, const int* targets, int B, int V,
|
||
Tensor& dlogits, Tensor& loss_row) {
|
||
dlogits.resize(B, V);
|
||
loss_row.resize(B, 1);
|
||
int32_t P[8]; float F[8];
|
||
fillP(P, {B, V}); fillF(F, {});
|
||
std::vector<BufSpec> bufs = {
|
||
rd_buf(logits.ptr(), logits.n() * sizeof(float)),
|
||
tmp_buf(targets, (size_t)B * sizeof(int)),
|
||
out_buf(dlogits.ptr(), dlogits.n() * sizeof(float)),
|
||
// loss нужен хосту КАЖДЫЙ шаг: вычитка планируется на flush
|
||
// ( backward() дёрнет materialize(loss_row) в конце шага — один
|
||
// submit+wait на весь шаг, а не на каждое ядро ).
|
||
host_out(loss_row.ptr(), loss_row.n() * sizeof(float)),
|
||
};
|
||
VK_CALL("softmax_ce", Kernel::SoftmaxCE, bufs, P, F, (uint32_t)B,
|
||
cpu_.softmax_ce(logits, targets, B, V, dlogits, loss_row));
|
||
}
|
||
|
||
float VkBackend::softmax_ce_loss(const Tensor& logits, const int* targets, int B, int V,
|
||
Tensor& loss_row) {
|
||
loss_row.resize(B, 1);
|
||
int32_t P[8]; float F[8];
|
||
fillP(P, {B, V}); fillF(F, {});
|
||
std::vector<BufSpec> bufs = {
|
||
rd_buf(logits.ptr(), logits.n() * sizeof(float)),
|
||
tmp_buf(targets, (size_t)B * sizeof(int)),
|
||
host_out(loss_row.ptr(), loss_row.n() * sizeof(float)),
|
||
};
|
||
{
|
||
std::lock_guard<std::mutex> lk(mtx_);
|
||
if (!degraded_) {
|
||
std::string err;
|
||
if (run(Kernel::SoftmaxLoss, bufs, P, F, (uint32_t)B, err)) {
|
||
flush_locked(); // host_out уже в очереди вычитки
|
||
} else {
|
||
fallback_warn("softmax_loss", err);
|
||
sync_host_for_fallback(bufs);
|
||
float l = cpu_.softmax_ce_loss(logits, targets, B, V, loss_row);
|
||
mark_host_outputs(bufs);
|
||
return l;
|
||
}
|
||
} else {
|
||
return cpu_.softmax_ce_loss(logits, targets, B, V, loss_row);
|
||
}
|
||
}
|
||
double s = 0.0;
|
||
for (int i = 0; i < B; ++i) s += loss_row.at(i);
|
||
return B > 0 ? (float)(s / (double)B) : 0.0f;
|
||
}
|
||
|
||
void VkBackend::attention_forward(const Tensor& q, const Tensor& k, const Tensor& v,
|
||
int n_seq, int S, int H, int hd, float scale,
|
||
Tensor& att, Tensor& attout) {
|
||
att.resize3d(n_seq * H, S, S);
|
||
attout.resize(n_seq * S, H * hd);
|
||
attout.zero(); // нужно только CPU-фолбэку; GPU-ядро пишет attout целиком
|
||
if (S > 1024 || hd > 256 ||
|
||
small_enough_for_cpu((int64_t)n_seq * H * S * S * hd)) {
|
||
std::lock_guard<std::mutex> lk(mtx_);
|
||
materialize_nolock(q); materialize_nolock(k); materialize_nolock(v);
|
||
cpu_.attention_forward(q, k, v, n_seq, S, H, hd, scale, att, attout);
|
||
host_written_nolock(att); host_written_nolock(attout);
|
||
return;
|
||
}
|
||
int32_t P[8]; float F[8];
|
||
fillP(P, {n_seq, S, H, hd}); fillF(F, {scale});
|
||
std::vector<BufSpec> bufs = {
|
||
rd_buf(q.ptr(), q.n() * sizeof(float)),
|
||
rd_buf(k.ptr(), k.n() * sizeof(float)),
|
||
rd_buf(v.ptr(), v.n() * sizeof(float)),
|
||
out_buf(att.ptr(), att.n() * sizeof(float)),
|
||
out_buf(attout.ptr(), attout.n() * sizeof(float)),
|
||
};
|
||
VK_CALL("attn_fwd", Kernel::AttnFwd, bufs, P, F, (uint32_t)((int64_t)n_seq * H * S),
|
||
cpu_.attention_forward(q, k, v, n_seq, S, H, hd, scale, att, attout));
|
||
}
|
||
|
||
void VkBackend::attention_backward(const Tensor& q, const Tensor& k, const Tensor& v,
|
||
const Tensor& att, const Tensor& dattout,
|
||
int n_seq, int S, int H, int hd, float scale,
|
||
Tensor& dq, Tensor& dk, Tensor& dv) {
|
||
const int d = H * hd;
|
||
dq.resize(n_seq * S, d); dq.zero();
|
||
dk.resize(n_seq * S, d); dk.zero();
|
||
dv.resize(n_seq * S, d); dv.zero();
|
||
|
||
if (S > 2048 || hd > 256 ||
|
||
small_enough_for_cpu((int64_t)n_seq * H * S * S * hd)) {
|
||
std::lock_guard<std::mutex> lk(mtx_);
|
||
materialize_nolock(q); materialize_nolock(k); materialize_nolock(v);
|
||
materialize_nolock(att); materialize_nolock(dattout);
|
||
cpu_.attention_backward(q, k, v, att, dattout, n_seq, S, H, hd, scale, dq, dk, dv);
|
||
host_written_nolock(dq); host_written_nolock(dk); host_written_nolock(dv);
|
||
return;
|
||
}
|
||
|
||
Tensor ds((int)((int64_t)n_seq * H * S), S); // промежуточные dScore
|
||
const uint32_t wi = (uint32_t)((int64_t)n_seq * H * S);
|
||
const size_t fA = sizeof(float);
|
||
int32_t P[8]; float F[8];
|
||
fillP(P, {n_seq, S, H, hd}); fillF(F, {scale});
|
||
|
||
std::vector<BufSpec> bufs_a = {
|
||
rd_buf(q.ptr(), q.n() * fA),
|
||
rd_buf(k.ptr(), k.n() * fA),
|
||
rd_buf(v.ptr(), v.n() * fA),
|
||
rd_buf(att.ptr(), att.n() * fA),
|
||
rd_buf(dattout.ptr(), dattout.n() * fA),
|
||
zero_buf(dq.ptr(), dq.n() * fA),
|
||
out_buf(ds.ptr(), ds.n() * fA),
|
||
};
|
||
std::vector<BufSpec> bufs_b = {
|
||
rd_buf(q.ptr(), q.n() * fA),
|
||
rd_buf(ds.ptr(), ds.n() * fA),
|
||
zero_buf(dk.ptr(), dk.n() * fA),
|
||
};
|
||
std::vector<BufSpec> bufs_v = {
|
||
rd_buf(att.ptr(), att.n() * fA),
|
||
rd_buf(dattout.ptr(), dattout.n() * fA),
|
||
zero_buf(dv.ptr(), dv.n() * fA),
|
||
};
|
||
{
|
||
std::lock_guard<std::mutex> lk(mtx_);
|
||
if (degraded_) {
|
||
cpu_.attention_backward(q, k, v, att, dattout, n_seq, S, H, hd, scale, dq, dk, dv);
|
||
return;
|
||
}
|
||
std::string err;
|
||
fillF(F, {scale});
|
||
bool ok = run(Kernel::AttnBwdA, bufs_a, P, F, wi, err);
|
||
if (ok) { fillF(F, {}); ok = run(Kernel::AttnBwdB, bufs_b, P, F, wi, err); }
|
||
if (ok) { ok = run(Kernel::AttnDV, bufs_v, P, F, wi, err); }
|
||
if (!ok) {
|
||
fallback_warn("attn_bwd", err);
|
||
sync_host_for_fallback(bufs_a);
|
||
cpu_.attention_backward(q, k, v, att, dattout, n_seq, S, H, hd, scale, dq, dk, dv);
|
||
mark_host_outputs(bufs_a);
|
||
}
|
||
}
|
||
}
|
||
|
||
void VkBackend::zero(Tensor& t) {
|
||
if (t.n() == 0) return;
|
||
// Обнуление — vkCmdFillBuffer (без dispatch): device-копия становится
|
||
// нулевой, host-копия устаревает до materialize().
|
||
std::lock_guard<std::mutex> lk(mtx_);
|
||
if (degraded_) { cpu_.zero(t); return; }
|
||
std::string err;
|
||
if (!begin_batch_locked(err)) { cpu_.zero(t); return; }
|
||
GpuBuf* b = resolve(out_buf(t.ptr(), t.n() * sizeof(float)), err);
|
||
if (!b) { cpu_.zero(t); host_written_nolock(t); return; }
|
||
vkCmdFillBuffer(cur_cb_, b->buffer, 0, b->size, 0u);
|
||
stage_ = Stage::Transfer;
|
||
b->dev_dirty = true;
|
||
b->host_dirty = false;
|
||
}
|
||
|
||
void VkBackend::add_into(Tensor& dst, const Tensor& src) {
|
||
const size_t n = std::min(dst.n(), src.n());
|
||
if (n == 0) return;
|
||
int32_t P[8]; float F[8];
|
||
fillP(P, {2, (int32_t)n}); fillF(F, {});
|
||
std::vector<BufSpec> bufs = {
|
||
acc_buf(dst.ptr(), n * sizeof(float)),
|
||
rd_buf(src.ptr(), n * sizeof(float)),
|
||
};
|
||
VK_CALL("add_into", Kernel::Elementwise, bufs, P, F, (uint32_t)n,
|
||
cpu_.add_into(dst, src));
|
||
}
|
||
|
||
void VkBackend::scale(Tensor& t, float k) {
|
||
if (t.n() == 0) return;
|
||
int32_t P[8]; float F[8];
|
||
fillP(P, {1, (int32_t)t.n()}); fillF(F, {k});
|
||
std::vector<BufSpec> bufs = {
|
||
acc_buf(t.ptr(), t.n() * sizeof(float)),
|
||
bind_only(dummy_y_, sizeof(dummy_y_)),
|
||
};
|
||
VK_CALL("scale", Kernel::Elementwise, bufs, P, F, (uint32_t)t.n(),
|
||
cpu_.scale(t, k));
|
||
}
|
||
|
||
void VkBackend::copy(Tensor& dst, const Tensor& src) {
|
||
dst.resize(src.R(), src.C());
|
||
int32_t P[8]; float F[8];
|
||
fillP(P, {3, (int32_t)src.n()}); fillF(F, {});
|
||
std::vector<BufSpec> bufs = {
|
||
out_buf(dst.ptr(), dst.n() * sizeof(float)),
|
||
rd_buf(src.ptr(), src.n() * sizeof(float)),
|
||
};
|
||
VK_CALL("copy", Kernel::Elementwise, bufs, P, F, (uint32_t)src.n(),
|
||
cpu_.copy(dst, src));
|
||
}
|
||
|
||
void VkBackend::embed_gather(Tensor& x, const Tensor& wte, const int* row_ids, int n_rows) {
|
||
const int d = wte.C();
|
||
x.resize(n_rows, d);
|
||
int32_t P[8]; float F[8];
|
||
fillP(P, {n_rows, d, wte.R()}); fillF(F, {});
|
||
std::vector<BufSpec> bufs = {
|
||
rd_buf(wte.ptr(), wte.n() * sizeof(float)),
|
||
tmp_buf(row_ids, (size_t)n_rows * sizeof(int)),
|
||
out_buf(x.ptr(), x.n() * sizeof(float)),
|
||
};
|
||
VK_CALL("embed_gather", Kernel::EmbedGather, bufs, P, F, (uint32_t)((int64_t)n_rows * d),
|
||
cpu_.embed_gather(x, wte, row_ids, n_rows));
|
||
}
|
||
|
||
void VkBackend::scatter_add_rows(Tensor& x, const int* row_ids, int n_rows, const Tensor& src) {
|
||
// ВСЕГДА на CPU (детерминизм: неатомарный += на GPU терял бы обновления
|
||
// при повторяющихся токенах). Цена — один round-trip x/src за шаг.
|
||
std::lock_guard<std::mutex> lk(mtx_);
|
||
materialize_nolock(x);
|
||
materialize_nolock(const_cast<Tensor&>(src));
|
||
cpu_.scatter_add_rows(x, row_ids, n_rows, src);
|
||
host_written_nolock(x);
|
||
}
|
||
|
||
// ===========================================================================
|
||
// Adam: клип глобальной нормы НА GPU + device-resident веса/m/v
|
||
// ===========================================================================
|
||
bool VkBackend::ensure_adam_out(size_t n_floats, std::string& err) {
|
||
if (adam_out_.buffer && adam_out_floats_ >= n_floats) return true;
|
||
if (adam_out_.buffer) {
|
||
bytes_allocated_ -= adam_out_.size;
|
||
vkDestroyBuffer(dev_, adam_out_.buffer, nullptr);
|
||
vkFreeMemory(dev_, adam_out_.mem, nullptr);
|
||
adam_out_ = GpuBuf{};
|
||
adam_map_ = nullptr;
|
||
}
|
||
size_t cap = std::max<size_t>(n_floats, 256);
|
||
if (!alloc_host_visible(adam_out_, cap * sizeof(float), (void**)&adam_map_, err)) return false;
|
||
adam_out_floats_ = cap;
|
||
return true;
|
||
}
|
||
|
||
GpuBuf* VkBackend::ensure_partials(const void* owner, size_t n, std::string& err) {
|
||
const uint32_t max_wg = std::min<uint32_t>(props_.limits.maxComputeWorkGroupCount[0], 1u << 20);
|
||
uint32_t nwg = (uint32_t)((n + kWorkGroupSize - 1) / kWorkGroupSize);
|
||
if (nwg > max_wg) nwg = max_wg;
|
||
if (nwg == 0) nwg = 1;
|
||
const size_t bytes = (size_t)nwg * 2 * sizeof(float);
|
||
auto it = scratch_.find(owner);
|
||
if (it != scratch_.end()) {
|
||
it->second->epoch = epoch_;
|
||
if (it->second->size >= (VkDeviceSize)bytes) return it->second.get();
|
||
free_device_buf(*it->second);
|
||
}
|
||
auto nb = std::make_unique<GpuBuf>();
|
||
if (!alloc_device_buf(*nb, bytes, err)) return nullptr;
|
||
GpuBuf* p = nb.get();
|
||
scratch_[owner] = std::move(nb);
|
||
return p;
|
||
}
|
||
|
||
void VkBackend::adam(std::vector<Tensor*>& params, std::vector<Tensor*>& grads,
|
||
std::vector<Tensor*>& m, std::vector<Tensor*>& v,
|
||
float lr, float b1, float b2, float eps, float wd,
|
||
int step, float clip, bool* had_nonfinite) {
|
||
if (had_nonfinite) *had_nonfinite = false;
|
||
if (params.size() != grads.size() || params.size() != m.size() || params.size() != v.size()) {
|
||
std::lock_guard<std::mutex> lk(mtx_);
|
||
materialize_nolock(params); materialize_nolock(grads);
|
||
materialize_nolock(m); materialize_nolock(v);
|
||
cpu_.adam(params, grads, m, v, lr, b1, b2, eps, wd, step, clip, had_nonfinite);
|
||
host_written_nolock(params); host_written_nolock(m); host_written_nolock(v);
|
||
return;
|
||
}
|
||
|
||
std::lock_guard<std::mutex> lk(mtx_);
|
||
if (degraded_) {
|
||
materialize_nolock(params); materialize_nolock(grads);
|
||
materialize_nolock(m); materialize_nolock(v);
|
||
cpu_.adam(params, grads, m, v, lr, b1, b2, eps, wd, step, clip, had_nonfinite);
|
||
host_written_nolock(params); host_written_nolock(m); host_written_nolock(v);
|
||
return;
|
||
}
|
||
|
||
std::string err;
|
||
const size_t nt = params.size();
|
||
const float bc1 = 1.0f - std::pow(b1, (float)step);
|
||
const float bc2 = 1.0f - std::pow(b2, (float)step);
|
||
const float inv1 = 1.0f / std::max(bc1, 1e-12f);
|
||
const float inv2 = 1.0f / std::max(bc2, 1e-12f);
|
||
|
||
// ------------------------------------------------------------------
|
||
// Клип глобальной нормы — ДВУМПРОХОДНОЙ РЕДУКЦИЕЙ НА GPU.
|
||
// Градиенты НЕ вычитываются на хост: на каждый тензор два dispatch
|
||
// (частичные суммы → итог), хост читает 2 float на тензор из постоянно
|
||
// отображённого буфера adam_out_ (shared memory GPU↔CPU).
|
||
// ------------------------------------------------------------------
|
||
float gscale = 1.0f;
|
||
if (clip > 0.0f) {
|
||
if (!ensure_adam_out(2 * nt + 2, err)) {
|
||
fallback_warn("adam/clip", err);
|
||
degraded_enter();
|
||
cpu_.adam(params, grads, m, v, lr, b1, b2, eps, wd, step, clip, had_nonfinite);
|
||
return;
|
||
}
|
||
const uint32_t max_wg = std::min<uint32_t>(props_.limits.maxComputeWorkGroupCount[0], 1u << 20);
|
||
bool ok = true;
|
||
for (size_t i = 0; i < nt && ok; ++i) {
|
||
const size_t n = grads[i]->n();
|
||
if (n == 0) continue;
|
||
GpuBuf* part = ensure_partials(grads[i]->ptr(), n, err);
|
||
if (!part) { ok = false; break; }
|
||
uint32_t nwg = (uint32_t)((n + kWorkGroupSize - 1) / kWorkGroupSize);
|
||
if (nwg > max_wg) nwg = max_wg;
|
||
|
||
int32_t P[8]; float F[8];
|
||
fillP(P, {(int32_t)n, (int32_t)(nwg * kWorkGroupSize)}); fillF(F, {});
|
||
std::vector<BufSpec> b1s = {
|
||
rd_buf(grads[i]->ptr(), n * sizeof(float)),
|
||
direct_buf(part, (size_t)part->size),
|
||
};
|
||
ok = run(Kernel::ReduceSumSq, b1s, P, F, nwg * kWorkGroupSize, err);
|
||
if (!ok) break;
|
||
|
||
fillP(P, {(int32_t)nwg, (int32_t)i}); fillF(F, {});
|
||
std::vector<BufSpec> b2s = {
|
||
direct_buf(part, (size_t)part->size),
|
||
direct_buf(&adam_out_, 2 * sizeof(float)),
|
||
};
|
||
ok = run(Kernel::ReduceFinal, b2s, P, F, kWorkGroupSize, err);
|
||
}
|
||
if (ok) {
|
||
flush_locked(); // submit+wait; adam_out_ — host-visible, читаем напрямую
|
||
double sq = 0.0;
|
||
double nf = 0.0;
|
||
for (size_t i = 0; i < nt; ++i) {
|
||
sq += (double)adam_map_[2 * i];
|
||
nf += (double)adam_map_[2 * i + 1];
|
||
}
|
||
if (nf > 0.0 && had_nonfinite) *had_nonfinite = true;
|
||
const float nrm = (float)std::sqrt(sq);
|
||
if (std::isfinite(nrm) && nrm > clip) gscale = clip / (nrm + 1e-6f);
|
||
} else {
|
||
fallback_warn("adam/clip", err);
|
||
degraded_enter();
|
||
cpu_.adam(params, grads, m, v, lr, b1, b2, eps, wd, step, clip, had_nonfinite);
|
||
return;
|
||
}
|
||
}
|
||
|
||
// ------------------------------------------------------------------
|
||
// Шаг Adam — одним батчем на все тензоры (без submit на тензор!).
|
||
// Веса/m/v остаются на устройстве (dev_dirty) — на хост не вычитываются.
|
||
// ------------------------------------------------------------------
|
||
bool ok = true;
|
||
for (size_t i = 0; i < nt && ok; ++i) {
|
||
Tensor& Pt = *params[i]; Tensor& G = *grads[i];
|
||
Tensor& M = *m[i]; Tensor& V = *v[i];
|
||
if (Pt.n() == 0) continue;
|
||
|
||
int32_t P[8]; float F[8];
|
||
fillP(P, {(int32_t)Pt.n()});
|
||
fillF(F, {lr, b1, b2, eps, wd, gscale, inv1, inv2});
|
||
const size_t fA = sizeof(float);
|
||
std::vector<BufSpec> bufs = {
|
||
acc_buf(Pt.ptr(), Pt.n() * fA),
|
||
rd_buf(G.ptr(), G.n() * fA),
|
||
acc_buf(M.ptr(), M.n() * fA),
|
||
acc_buf(V.ptr(), V.n() * fA),
|
||
};
|
||
ok = run(Kernel::AdamStep, bufs, P, F, (uint32_t)Pt.n(), err);
|
||
if (!ok) {
|
||
fallback_warn("adam_step", err);
|
||
sync_host_for_fallback(bufs);
|
||
mark_host_outputs(bufs);
|
||
}
|
||
}
|
||
if (!ok) {
|
||
// часть тензоров уже обновлена на GPU — вычитываем всё и домешиваем
|
||
// остаток на CPU (редкая аварийная ветка).
|
||
materialize_nolock(params); materialize_nolock(grads);
|
||
materialize_nolock(m); materialize_nolock(v);
|
||
for (size_t i = 0; i < nt; ++i) {
|
||
if (params[i]->n() == 0) continue;
|
||
std::vector<Tensor*> pp{params[i]}, gg{grads[i]}, mm{m[i]}, vv{v[i]};
|
||
cpu_.adam(pp, gg, mm, vv, lr, b1, b2, eps, wd, step, 0.0f, nullptr);
|
||
}
|
||
host_written_nolock(params); host_written_nolock(m); host_written_nolock(v);
|
||
return;
|
||
}
|
||
|
||
// Пайплайнинг: отправляем батч на GPU БЕЗ ожидания — видеокарта считает
|
||
// adam, пока хост готовит данные следующего шага.
|
||
if (!launch_locked(err)) {
|
||
fallback_warn("adam/launch", err);
|
||
degraded_enter();
|
||
materialize_nolock(params); materialize_nolock(grads);
|
||
materialize_nolock(m); materialize_nolock(v);
|
||
cpu_.adam(params, grads, m, v, lr, b1, b2, eps, wd, step, clip, had_nonfinite);
|
||
host_written_nolock(params); host_written_nolock(m); host_written_nolock(v);
|
||
}
|
||
}
|
||
|
||
// ===========================================================================
|
||
// Жадный сэмплинг НА GPU: готовый токен через shared memory
|
||
// ===========================================================================
|
||
bool VkBackend::sample_argmax(const Tensor& logits, int& out_id) {
|
||
const int V = logits.C();
|
||
if (V <= 0 || logits.n() < (size_t)V) return false;
|
||
std::lock_guard<std::mutex> lk(mtx_);
|
||
if (degraded_) return false;
|
||
|
||
int32_t P[8]; float F[8];
|
||
fillP(P, {V}); fillF(F, {});
|
||
std::vector<BufSpec> bufs = {
|
||
rd_buf(logits.ptr(), logits.n() * sizeof(float)),
|
||
direct_buf(&token_out_, 16 * sizeof(int32_t)),
|
||
};
|
||
std::string err;
|
||
if (!run(Kernel::Argmax, bufs, P, F, kWorkGroupSize, err)) {
|
||
fallback_warn("argmax", err);
|
||
return false; // вызывающий сэмплирует на CPU
|
||
}
|
||
flush_locked(); // submit+wait — токен уже в отображённой памяти
|
||
out_id = (int)token_map_[0];
|
||
return out_id >= 0 && out_id < V;
|
||
}
|
||
|
||
// ===========================================================================
|
||
// Глобальный экземпляр
|
||
// ===========================================================================
|
||
namespace {
|
||
std::unique_ptr<VkBackend> g_vk;
|
||
}
|
||
|
||
bool vulkan_available() { return true; }
|
||
std::string vulkan_loader_error() { return vk_loader_error(); }
|
||
|
||
bool vulkan_init(const VulkanOptions& opt, std::string& err) {
|
||
std::string lerr;
|
||
if (!vk_loader_load(lerr)) { err = lerr; return false; }
|
||
if (g_vk) { set_backend(g_vk.get()); return true; }
|
||
auto b = std::make_unique<VkBackend>();
|
||
if (!b->init(opt, err)) { b.reset(); return false; }
|
||
g_vk = std::move(b);
|
||
set_backend(g_vk.get());
|
||
return true;
|
||
}
|
||
|
||
void vulkan_shutdown() {
|
||
if (g_vk) { set_backend(nullptr); g_vk->shutdown(); g_vk.reset(); }
|
||
}
|
||
|
||
void vulkan_begin_step() { if (g_vk) g_vk->begin_step(); }
|
||
|
||
std::vector<std::string> vulkan_list_devices() {
|
||
std::vector<std::string> out;
|
||
std::string lerr;
|
||
if (!vk_loader_load(lerr)) return out;
|
||
VkApplicationInfo app{};
|
||
app.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
|
||
app.apiVersion = VK_API_VERSION_1_1;
|
||
VkInstanceCreateInfo ci{};
|
||
ci.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
|
||
ci.pApplicationInfo = &app;
|
||
VkInstance inst = VK_NULL_HANDLE;
|
||
if (vkCreateInstance(&ci, nullptr, &inst) != VK_SUCCESS) return out;
|
||
|
||
uint32_t n = 0;
|
||
vkEnumeratePhysicalDevices(inst, &n, nullptr);
|
||
std::vector<VkPhysicalDevice> devs((size_t)n);
|
||
if (n) vkEnumeratePhysicalDevices(inst, &n, devs.data());
|
||
for (uint32_t i = 0; i < n; ++i) {
|
||
VkPhysicalDeviceProperties p;
|
||
vkGetPhysicalDeviceProperties(devs[(size_t)i], &p);
|
||
const char* t = p.deviceType == VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU ? "discrete"
|
||
: p.deviceType == VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU ? "integrated"
|
||
: p.deviceType == VK_PHYSICAL_DEVICE_TYPE_VIRTUAL_GPU ? "virtual"
|
||
: p.deviceType == VK_PHYSICAL_DEVICE_TYPE_CPU ? "cpu" : "other";
|
||
char buf[640];
|
||
snprintf(buf, sizeof buf,
|
||
"[%u] %s %s API %u.%u maxComputeWorkGroupInvocations=%u maxStorageBufferRange=%u",
|
||
i, p.deviceName, t,
|
||
VK_VERSION_MAJOR(p.apiVersion), VK_VERSION_MINOR(p.apiVersion),
|
||
p.limits.maxComputeWorkGroupInvocations, p.limits.maxStorageBufferRange);
|
||
out.push_back(buf);
|
||
}
|
||
vkDestroyInstance(inst, nullptr);
|
||
return out;
|
||
}
|
||
|
||
std::string vulkan_shader_dir() {
|
||
for (const auto& d : shader_dirs()) {
|
||
std::error_code ec;
|
||
if (fs::is_directory(path_from_utf8(d), ec)) return d;
|
||
}
|
||
return {};
|
||
}
|
||
|
||
bool vulkan_rebuild_shaders(std::string& err, const std::string& dir) {
|
||
const std::string d = dir.empty() ? vulkan_shader_dir() : dir;
|
||
if (d.empty()) {
|
||
err = "каталог shaders/ не найден. Положи рядом с бинарником shaders/*.comp "
|
||
"или задай XENITH_SHADER_DIR=<каталог>";
|
||
return false;
|
||
}
|
||
int ok = 0, fail = 0;
|
||
std::ostringstream errs;
|
||
std::error_code ec;
|
||
for (auto& e : fs::directory_iterator(path_from_utf8(d), ec)) {
|
||
if (e.path().extension() != ".comp") continue;
|
||
std::string out = path_to_utf8(e.path());
|
||
out.replace(out.size() - 5, 5, ".spv");
|
||
std::string e1;
|
||
if (compile_spv(path_to_utf8(e.path()), out, e1)) {
|
||
++ok;
|
||
} else {
|
||
++fail;
|
||
errs << " - " << e.path().filename().string() << ": " << e1 << "\n";
|
||
}
|
||
}
|
||
if (ok == 0 && fail == 0) { err = "в " + d + " нет ни одного .comp"; return false; }
|
||
err = errs.str();
|
||
return fail == 0;
|
||
}
|
||
|
||
} // namespace xt
|
||
|
||
// ===========================================================================
|
||
// Что осталось на следующий апгрейд (когда понадобится ещё быстрее):
|
||
// 1. Tiling в GEMM через shared memory (сейчас 1 invokation = 1 элемент C,
|
||
// memory-bound); specialization constants для D/hd/S.
|
||
// 2. fp16/bf16 хранение весов при fp32-аккумуляторах (opt_.fp16 пока игнорируется).
|
||
// 3. GPU-resident KV-кэш для генерации (сейчас decode-внимание на хосте —
|
||
// на больших моделях узкое место; prefill/обучение — полностью на GPU).
|
||
// 4. scatter_add на GPU через атомики (GL_EXT_shader_atomic_float_add) с
|
||
// фолбэком — убирает последний round-trip обучения (gwte).
|
||
// 5. Несколько command buffer параллельно (multi-queue) на независимых ветвях.
|
||
// Каждый шаг проверять: xenith gradcheck --backend vulkan
|
||
// и сравнением loss на 100 шагах при одинаковом seed между cpu и vulkan.
|
||
// ===========================================================================
|
||
|
||
#endif // XENITH_VULKAN
|