Cómo persistir pipelines Vulkan compiladas con VkPipelineCache

Example: VulkanExamples/p22-pipelinecache

La creación de pipelines es la llamada más cara de un frame de Vulkan — SPIR-V → ISA nativa más fusión de estado de función fija. Un VkPipelineCache permite al driver acumular sus artefactos de compilación y te permite a ti serializarlos entre ejecuciones, convirtiendo los tirones de arranque en una lectura de archivo.

Los tres puntos de la API

  1. Crear: vkCreatePipelineCache — opcionalmente con initialData = un blob de una ejecución anterior.
  2. Usar: pasa la caché como primer arg de vkCreateGraphicsPipelines/vkCreateComputePipelines — los hits se saltan la compilación. (Los misses añaden a la caché.)
  3. Persistir: vkGetPipelineCacheData → blob de bytes → archivo. La siguiente ejecución lo alimenta de vuelta como initialData.
example.cpp
auto data = device->getPipelineCacheData(cache);   // -> file
// next run:
ci.setInitialDataSize(blob.size()).setPInitialData(blob.data());
auto cache = device->createPipelineCacheUnique(ci);
auto pipe  = device->createGraphicsPipelineUnique(cache, gi);

Qué es el blob (y qué no)

Un blob opaco y versionado por driver — el contenido de RADV difiere del de NVIDIA, y los drivers incrustan sus propios marcadores de versión/GPU: una caché escrita por el driver X es ignorada por el driver Y (de forma segura — obtienes una compilación en frío, no un crash). Así que: distribuye cachés por GPU solo como optimización de arranque, nunca como mecanismo de corrección.

La ganancia mayor: merge

vkMergePipelineCaches(dst, srcs) fusiona varias cachés en una — el patrón estándar para un thread de compilación de pipelines en background:

example.txt
main thread:   render with cache A
worker thread: compile new pipelines into empty cache B
periodically:  merge B into A, save A to disk

Las variantes nuevas se construyen sin estancar el bucle de render.

Cómo NO usarlo

  • No compartas un archivo de caché entre combinaciones driver/GPU — en el peor caso se ignora, pero indexa el nombre del archivo por VkPhysicalDeviceProperties::pipelineCacheUUID de todos modos: para eso existe exactamente el campo.
  • No esperes dedup entre procesos — los datos de caché son aditivos por proceso; fusionar blobs de dos ejecuciones que empezaron vacías es donde entra vkMergePipelineCaches.
  • Una caché no valida tu pipeline — un blob obsoleto más shaders cambiados sigue compilando correctamente (el driver detecta el desajuste internamente); la corrección nunca depende de ello.

Compilar y ejecutar

build.sh
g++ -std=c++23 -O2 main.cpp -o app -lvulkan -lglfw -lshaderc
./app --headless out.ppm   # run twice: cold, then warm
python3 check.py           # drives both runs + verifies render

El check

check.py borra pipeline.cache, corre la app dos veces, y verifica: la ejecución en frío loguea starting cold + escribe un blob no vacío; la ejecución en caliente loguea loaded N bytes; ambos renders producen el triángulo válido.

check.py
#!/usr/bin/env python3
# SPDX-License-Identifier: CC0-1.0
# check.py — verify the pipeline cache lifecycle:
#   run 1 (cold): no cache file -> "starting cold", writes cache
#   run 2 (warm): "loaded N bytes", renders identically
# Also verifies the rendered triangle in both outputs.
import os
import subprocess
import sys


def load_ppm(path):
    d = open(path, "rb").read()
    hdr, data = d.split(b"255\n", 1)
    parts = hdr.split()
    w, h = int(parts[1]), int(parts[2])
    return w, h, data


def triangle_ok(path):
    w, h, data = load_ppm(path)

    def px(x, y):
        i = (y * w + x) * 3
        return data[i], data[i + 1], data[i + 2]
    # blue apex top, colored bottom band, dark bg corner
    apex = px(w // 2, int(h * 0.12))
    assert apex[2] > 120, f"apex {apex}"
    bl = px(int(w * 0.2), int(h * 0.82))
    assert bl[0] > 120, f"bl {bl}"
    bg = px(5, 5)
    assert all(v < 60 for v in bg), f"bg {bg}"
    return True


def run():
    r = subprocess.run(["./app", "--headless", "out.ppm"],
                       capture_output=True, text=True, timeout=60)
    out = r.stdout + r.stderr
    print(out, end="")
    assert r.returncode == 0, f"exit {r.returncode}"
    return out


def main():
    if os.path.exists("pipeline.cache"):
        os.remove("pipeline.cache")

    out1 = run()
    assert "starting cold" in out1, out1
    assert os.path.exists("pipeline.cache"), \
        "cache file was not written"
    sz1 = os.path.getsize("pipeline.cache")
    assert sz1 > 100, f"cache file suspiciously small: {sz1}"
    triangle_ok("out.ppm")
    print(f"run1: cold build, cache saved ({sz1} B), render OK")

    out2 = run()
    assert "loaded" in out2, out2
    triangle_ok("out.ppm")
    print("run2: warm — cache blob loaded, render identical")
    print("OK: pipeline cache round-trips across runs")


if __name__ == "__main__":
    main()
output.txt
[cache] starting cold
wrote out.ppm
[cache] saved 2232 bytes to pipeline.cache
run1: cold build, cache saved (2232 B), render OK
[cache] loaded 2232 bytes from pipeline.cache
run2: warm — cache blob loaded, render identical
OK: pipeline cache round-trips across runs

Fuente completa

main.cpp
// SPDX-License-Identifier: CC0-1.0
//
// Pipeline cache: vkCreateGraphicsPipelines is expensive — driver
// compiles SPIR-V to native ISA and merges fixed-function state.
// VkPipelineCache lets you persist that work across runs:
// vkGetPipelineCacheData -> file -> VkPipelineCacheCreateInfo.
//
// First run:  builds pipelines cold, writes pipeline.cache
// Second run: loads the blob, pipelines hit the cache
//
//   ./app --headless o.ppm     one frame -> PPM
//   python3 check.py           runs it twice, verifies cache reuse
//
// Build:  g++ -std=c++23 -O2 main.cpp -o app -lvulkan -lglfw -lshaderc

#include "vkmini.hpp"

#include <GLFW/glfw3.h>

static const char* kVert = R"GLSL(
#version 460
layout(location = 0) out vec3 vColor;
void main() {
    vec2 p[3] = vec2[](vec2(-0.8, 0.7), vec2(0.8, 0.7),
                       vec2(0.0, -0.8));
    vec3 c[3] = vec3[](vec3(1, 0, 0), vec3(0, 1, 0),
                       vec3(0, 0, 1));
    gl_Position = vec4(p[gl_VertexIndex], 0.0, 1.0);
    vColor = c[gl_VertexIndex];
}
)GLSL";

static const char* kFrag = R"GLSL(
#version 460
layout(location = 0) in vec3 vColor;
layout(location = 0) out vec4 outColor;
void main() { outColor = vec4(vColor, 1.0); }
)GLSL";

/// Load an existing cache blob if present, else start empty.
static vk::UniquePipelineCache makeCache(vkmini::Vk& vk,
                                         const char* path) {
    std::vector<char> blob;
    if (std::ifstream f{path, std::ios::binary | std::ios::ate}) {
        auto n = f.tellg();
        blob.resize(size_t(n));
        f.seekg(0);
        f.read(blob.data(), n);
    }
    vk::PipelineCacheCreateInfo ci{};
    if (!blob.empty()) {
        ci.setInitialDataSize(blob.size())
            .setPInitialData(blob.data());
        printf("[cache] loaded %zu bytes from %s\n", blob.size(),
               path);
    } else {
        printf("[cache] starting cold\n");
    }
    return vk.device->createPipelineCacheUnique(ci);
}

/// Persist whatever the driver accumulated in the cache.
static void saveCache(vkmini::Vk& vk, vk::PipelineCache cache,
                      const char* path) {
    auto data = vk.device->getPipelineCacheData(cache);
    std::ofstream f{path, std::ios::binary};
    f.write(reinterpret_cast<const char*>(data.data()),
            std::streamsize(data.size()));
    printf("[cache] saved %zu bytes to %s\n", data.size(), path);
}

int main() {
    vkmini::Vk vk;
    vk.createInstance({});
    vk.pickPhysicalDevice();
    vk.createDevice({});

    auto cache = makeCache(vk, "pipeline.cache");

    auto vs = vk.shader(kVert, shaderc_vertex_shader, "t.vert");
    auto fs = vk.shader(kFrag, shaderc_fragment_shader, "t.frag");
    vk::PipelineShaderStageCreateInfo stages[2];
    stages[0].setStage(vk::ShaderStageFlagBits::eVertex)
        .setModule(vs.get())
        .setPName("main");
    stages[1].setStage(vk::ShaderStageFlagBits::eFragment)
        .setModule(fs.get())
        .setPName("main");
    vk::PipelineVertexInputStateCreateInfo vin{};
    vk::PipelineInputAssemblyStateCreateInfo ia{};
    ia.setTopology(vk::PrimitiveTopology::eTriangleList);
    vk::PipelineViewportStateCreateInfo vp{};
    vp.setViewportCount(1).setScissorCount(1);
    std::array dynStates{vk::DynamicState::eViewport,
                         vk::DynamicState::eScissor};
    vk::PipelineDynamicStateCreateInfo dyn{};
    dyn.setDynamicStates(dynStates);
    vk::PipelineRasterizationStateCreateInfo rs{};
    rs.setPolygonMode(vk::PolygonMode::eFill)
        .setCullMode(vk::CullModeFlagBits::eNone)
        .setFrontFace(vk::FrontFace::eCounterClockwise)
        .setLineWidth(1.0f);
    vk::PipelineMultisampleStateCreateInfo ms{};
    ms.setRasterizationSamples(vk::SampleCountFlagBits::e1);
    vk::PipelineColorBlendAttachmentState cb{};
    cb.setColorWriteMask(
        vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG |
        vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA);
    vk::PipelineColorBlendStateCreateInfo blend{};
    blend.setAttachments(cb);
    auto layout = vk.device->createPipelineLayoutUnique({});
    vk::PipelineRenderingCreateInfo rendering{};
    vk::Format cfmt = vk::Format::eR8G8B8A8Unorm;
    rendering.setColorAttachmentFormats(cfmt);
    vk::GraphicsPipelineCreateInfo gi{};
    gi.setStages(stages)
        .setPVertexInputState(&vin)
        .setPInputAssemblyState(&ia)
        .setPViewportState(&vp)
        .setPDynamicState(&dyn)
        .setPRasterizationState(&rs)
        .setPMultisampleState(&ms)
        .setPColorBlendState(&blend)
        .setLayout(layout.get())
        .setPNext(&rendering);
    // createGraphicsPipelineUnique takes the cache as first arg —
    // hits avoid the ISA compile inside the driver
    auto res = vk.device->createGraphicsPipelineUnique(
        cache.get(), gi);
    if (res.result != vk::Result::eSuccess)
        throw std::runtime_error("pipeline failed");
    auto pipe = std::move(res.value);

    // render one frame headless to prove the cached pipeline works
    vkmini::Headless hl;
    hl.init(vk, 256, 256);
    hl.render(vk::ImageLayout::eColorAttachmentOptimal,
              [&](vk::CommandBuffer c) {
                  vk::RenderingAttachmentInfo att{};
                  att.setImageView(hl.color.view.get())
                      .setImageLayout(
                          vk::ImageLayout::eColorAttachmentOptimal)
                      .setLoadOp(vk::AttachmentLoadOp::eClear)
                      .setStoreOp(vk::AttachmentStoreOp::eStore)
                      .setClearValue(vk::ClearValue{
                          vk::ClearColorValue{
                              std::array{0.05f, 0.05f, 0.08f,
                                         1.f}}});
                  vk::RenderingInfo ri{};
                  ri.setRenderArea({{0, 0}, hl.extent})
                      .setLayerCount(1)
                      .setColorAttachments(att);
                  c.beginRendering(ri);
                  c.bindPipeline(vk::PipelineBindPoint::eGraphics,
                                 pipe.get());
                  vk::Viewport vp{0, 0, 256, 256, 0.f, 1.f};
                  c.setViewport(0, vp);
                  vk::Rect2D sc{{0, 0}, hl.extent};
                  c.setScissor(0, sc);
                  c.draw(3, 1, 0, 0);
                  c.endRendering();
              });
    hl.savePpm("out.ppm");
    printf("wrote out.ppm\n");

    saveCache(vk, cache.get(), "pipeline.cache");
    return 0;
}

Todo el código fuente de esta serie se publica bajo CC0 1.0 Universal (CC0-1.0) — dedicación al dominio público, sin atribución requerida.


Echa un vistazo a artículos similares por categoría: C++ Vulkan