Skip to content

Commit ea209db

Browse files
authored
perf: cache CPU position embeddings across DiT runners (#2211)
1 parent a85db96 commit ea209db

31 files changed

Lines changed: 858 additions & 613 deletions

‎docs/pe_cache.md‎

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
# Position embedding cache
2+
3+
`sd::PECache` stores CPU-side `sd::Tensor<float>` data. Each model runner owns
4+
its cache and calls the existing `make_input()` on every graph build. Cache
5+
hits skip PE generation; allocation and upload remain ordinary graph-input
6+
operations. `GGMLRunner` has no PE-specific code or resource hooks.
7+
8+
The cache keeps the most recent key and tensor for each named PE input. A
9+
matching key returns the existing tensor by reference. Changing its parameters
10+
replaces that input's cached result. Different named inputs have independent
11+
storage. Alternating two layouts under the same name recomputes their PE;
12+
there is no LRU, device-buffer cache, memory budget, or graph lifecycle callback.
13+
CPU data lives with the model runner, including across `runner_end()` calls,
14+
and is released when its named entry is replaced or the cache is destroyed.
15+
16+
## Adding a model
17+
18+
Include `core/pe_cache.h` and declare a member:
19+
20+
```cpp
21+
sd::PECache pe_cache_;
22+
```
23+
24+
Construct the key before generating PE and place the generation code in the
25+
lazy callback:
26+
27+
```cpp
28+
sd::PECacheKey key("model.image_pe");
29+
key.add(height).add(width).add(head_dim).add(theta)
30+
.add(circular_x_enabled).add(circular_y_enabled);
31+
auto pe = make_input(pe_cache_.get_or_create(key, [&]() {
32+
auto values = generate_position_embedding(/* existing arguments */);
33+
return sd::Tensor<float>({2, 2, head_dim / 2, token_count}, std::move(values));
34+
}));
35+
```
36+
37+
Keys must cover every variable affecting PE values or shape: geometry, text
38+
length, frequency settings, reference-image ordering and offsets, circular
39+
settings, and video/audio positions or frame rates as applicable.
40+
`add_shape()` records all four ggml dimensions, including trailing singleton
41+
dimensions. `add_shapes()` records an ordered list of reference shapes.
42+
`add(sd::Tensor<T>)` records both shape and values for explicit position inputs.
43+
Keys compare their complete encoded fields rather than a data pointer or hash.
44+
45+
Use distinct names for PE inputs that coexist in a graph, such as Anima's
46+
adapter query and key PE. `make_input()` defers reading the CPU data until graph
47+
execution: do not replace a named entry while an unfinished graph references
48+
it. Adding or updating other named entries does not invalidate its storage.
49+
Return tensor shapes with the contiguous dimension first, and preserve each
50+
model's existing F32 values, layout, and final transformations.
51+
52+
## Current integrations
53+
54+
The cache is used by MiniT2I, the Flux runner and its variants, Flux3, Qwen Image,
55+
Qwen Image 2.1, Z-Image and L2P, Anima, Boogu, ERNIE Image, Fibo2, Ideogram4,
56+
Iris, Krea2, Lens, LLaDA Image, MAGE Flow, Ming Image, MOSS Image, PiD, PixArt,
57+
Wan, Hunyuan Video, LingBot Video, and LTX audio/video.
58+
59+
Position embeddings stored as model weights and graph-side RoPE operations
60+
remain on their existing paths, including MiniMax H3 and SenseNova U1.

‎src/core/pe_cache.cpp‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
#include "core/pe_cache.h"
2+
3+
namespace sd {
4+
PECacheKey& PECacheKey::add_shape(const ggml_tensor* tensor) {
5+
add(tensor != nullptr);
6+
if (tensor != nullptr) {
7+
for (int i = 0; i < GGML_MAX_DIMS; ++i) {
8+
add(tensor->ne[i]);
9+
}
10+
}
11+
return *this;
12+
}
13+
14+
PECacheKey& PECacheKey::add_shapes(const std::vector<ggml_tensor*>& tensors) {
15+
add(tensors.size());
16+
for (const auto* tensor : tensors) {
17+
add_shape(tensor);
18+
}
19+
return *this;
20+
}
21+
22+
const Tensor<float>& PECache::get_or_create(const PECacheKey& key, const std::function<Tensor<float>()>& build) {
23+
auto entry = entries_.find(key.name());
24+
if (entry != entries_.end() && entry->second.key == key) {
25+
return entry->second.value;
26+
}
27+
auto value = build();
28+
return entries_.insert_or_assign(key.name(), Entry{key, std::move(value)}).first->second.value;
29+
}
30+
}

‎src/core/pe_cache.h‎

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
#ifndef __SD_CORE_PE_CACHE_H__
2+
#define __SD_CORE_PE_CACHE_H__
3+
4+
#include <functional>
5+
#include <map>
6+
#include <set>
7+
#include <type_traits>
8+
9+
#include "core/tensor.hpp"
10+
#include "ggml.h"
11+
12+
namespace sd {
13+
class PECacheKey {
14+
std::string name_;
15+
std::string fields_;
16+
17+
public:
18+
explicit PECacheKey(std::string name)
19+
: name_(std::move(name)) {}
20+
const std::string& name() const { return name_; }
21+
22+
template <typename T, std::enable_if_t<std::is_arithmetic_v<T> || std::is_enum_v<T>, int> = 0>
23+
PECacheKey& add(T value) {
24+
if constexpr (std::is_floating_point_v<T>) {
25+
const double field = static_cast<double>(value);
26+
fields_.push_back('f');
27+
fields_.append(reinterpret_cast<const char*>(&field), sizeof(field));
28+
} else {
29+
const uint64_t field = static_cast<uint64_t>(value);
30+
fields_.push_back('i');
31+
fields_.append(reinterpret_cast<const char*>(&field), sizeof(field));
32+
}
33+
return *this;
34+
}
35+
36+
template <typename T>
37+
PECacheKey& add(const std::vector<T>& values) {
38+
fields_.push_back('v');
39+
add(values.size());
40+
for (const auto& value : values) {
41+
add(value);
42+
}
43+
return *this;
44+
}
45+
46+
template <typename T>
47+
PECacheKey& add(const std::set<T>& values) {
48+
return add(std::vector<T>(values.begin(), values.end()));
49+
}
50+
51+
template <typename T>
52+
PECacheKey& add(const Tensor<T>& values) {
53+
add(values.shape());
54+
for (int64_t i = 0; i < values.numel(); ++i) {
55+
add(values.data()[i]);
56+
}
57+
return *this;
58+
}
59+
60+
PECacheKey& add_shape(const ggml_tensor* tensor);
61+
PECacheKey& add_shapes(const std::vector<ggml_tensor*>& tensors);
62+
63+
bool operator==(const PECacheKey& other) const {
64+
return name_ == other.name_ && fields_ == other.fields_;
65+
}
66+
};
67+
68+
class PECache {
69+
struct Entry {
70+
PECacheKey key;
71+
Tensor<float> value;
72+
};
73+
74+
std::map<std::string, Entry> entries_;
75+
76+
public:
77+
const Tensor<float>& get_or_create(const PECacheKey& key, const std::function<Tensor<float>()>& build);
78+
};
79+
80+
}
81+
82+
#endif // __SD_CORE_PE_CACHE_H__

‎src/model/diffusion/anima.hpp‎

Lines changed: 30 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
#include <memory>
88
#include <utility>
99
#include <vector>
10+
#include "core/pe_cache.h"
1011

1112
#include "model/common/block.hpp"
1213
#include "model/common/rope.hpp"
@@ -562,10 +563,9 @@ namespace Anima {
562563
};
563564

564565
struct AnimaRunner : public DiffusionModelRunner {
566+
sd::PECache pe_cache_;
567+
565568
public:
566-
std::vector<float> image_pe_vec;
567-
std::vector<float> adapter_q_pe_vec;
568-
std::vector<float> adapter_k_pe_vec;
569569
AnimaConfig config;
570570
AnimaNet net;
571571

@@ -660,36 +660,40 @@ namespace Anima {
660660
int64_t h_pad = x->ne[1] + pad_h;
661661
int64_t w_pad = x->ne[0] + pad_w;
662662

663-
image_pe_vec = finish_rope_pe(gen_anima_image_pe_vec(1,
664-
static_cast<int>(h_pad),
665-
static_cast<int>(w_pad),
666-
static_cast<int>(config.patch_size),
667-
config.theta,
668-
config.axes_dim,
669-
4.0f,
670-
4.0f,
671-
1.0f,
672-
ref_latents));
673-
int64_t image_pos_len = static_cast<int64_t>(image_pe_vec.size()) / (2 * 2 * (config.head_dim / 2));
674-
auto image_pe = ggml_new_tensor_4d(compute_ctx, GGML_TYPE_F32, 2, 2, config.head_dim / 2, image_pos_len);
675-
set_backend_tensor_data(image_pe, image_pe_vec.data());
663+
sd::PECacheKey image_pe_key("anima.image_pe");
664+
image_pe_key.add(h_pad).add(w_pad).add(config.patch_size).add(config.theta).add(config.axes_dim).add(config.head_dim);
665+
image_pe_key.add_shapes(ref_latents).add(circular_x_enabled).add(circular_y_enabled);
666+
auto image_pe = make_input(pe_cache_.get_or_create(image_pe_key, [&]() {
667+
auto image_pe_vec = finish_rope_pe(gen_anima_image_pe_vec(1,
668+
static_cast<int>(h_pad),
669+
static_cast<int>(w_pad),
670+
static_cast<int>(config.patch_size),
671+
config.theta,
672+
config.axes_dim,
673+
4.0f,
674+
4.0f,
675+
1.0f,
676+
ref_latents));
677+
int64_t image_pos_len = static_cast<int64_t>(image_pe_vec.size()) / (2 * 2 * (config.head_dim / 2));
678+
return sd::Tensor<float>({2, 2, config.head_dim / 2, image_pos_len}, std::move(image_pe_vec));
679+
}));
676680

677681
ggml_tensor* adapter_q_pe = nullptr;
678682
ggml_tensor* adapter_k_pe = nullptr;
679683
if (t5_ids != nullptr) {
680684
int64_t target_len = t5_ids->ne[0];
681685
int64_t source_len = context->ne[1];
682686

683-
adapter_q_pe_vec = gen_1d_rope_pe_vec(target_len, 64, 10000.f);
684-
adapter_k_pe_vec = gen_1d_rope_pe_vec(source_len, 64, 10000.f);
685-
686-
int64_t target_pos_len = static_cast<int64_t>(adapter_q_pe_vec.size()) / (2 * 2 * 32);
687-
int64_t source_pos_len = static_cast<int64_t>(adapter_k_pe_vec.size()) / (2 * 2 * 32);
688-
689-
adapter_q_pe = ggml_new_tensor_4d(compute_ctx, GGML_TYPE_F32, 2, 2, 32, target_pos_len);
690-
adapter_k_pe = ggml_new_tensor_4d(compute_ctx, GGML_TYPE_F32, 2, 2, 32, source_pos_len);
691-
set_backend_tensor_data(adapter_q_pe, adapter_q_pe_vec.data());
692-
set_backend_tensor_data(adapter_k_pe, adapter_k_pe_vec.data());
687+
sd::PECacheKey q_key("anima.adapter_q_pe");
688+
q_key.add(target_len);
689+
adapter_q_pe = make_input(pe_cache_.get_or_create(q_key, [&]() {
690+
return sd::Tensor<float>({2, 2, 32, target_len}, gen_1d_rope_pe_vec(target_len, 64, 10000.f));
691+
}));
692+
sd::PECacheKey k_key("anima.adapter_k_pe");
693+
k_key.add(source_len);
694+
adapter_k_pe = make_input(pe_cache_.get_or_create(k_key, [&]() {
695+
return sd::Tensor<float>({2, 2, 32, source_len}, gen_1d_rope_pe_vec(source_len, 64, 10000.f));
696+
}));
693697
}
694698

695699
auto runner_ctx = get_context();

‎src/model/diffusion/boogu.hpp‎

Lines changed: 17 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
#include <cmath>
77
#include <tuple>
88
#include <vector>
9+
#include "core/pe_cache.h"
910

1011
#include "core/ggml_extend.h"
1112
#include "core/ggml_runner.h"
@@ -759,9 +760,9 @@ namespace Boogu {
759760
}
760761

761762
struct BooguImageRunner : public DiffusionModelRunner {
763+
sd::PECache pe_cache_;
762764
BooguConfig config;
763765
BooguImageModel boogu;
764-
std::vector<float> pe_vec;
765766

766767
BooguImageRunner(ggml_backend_t backend,
767768
const String2TensorStorage& tensor_storage_map = {},
@@ -799,17 +800,21 @@ namespace Boogu {
799800
ref_latents.push_back(make_input(ref_latent_tensor));
800801
}
801802

802-
pe_vec = finish_rope_pe(gen_boogu_pe(static_cast<int>(x->ne[1]),
803-
static_cast<int>(x->ne[0]),
804-
config.patch_size,
805-
static_cast<int>(x->ne[3]),
806-
static_cast<int>(context->ne[1]),
807-
ref_latents,
808-
config.theta,
809-
config.axes_dim));
810-
int pos_len = static_cast<int>(pe_vec.size() / config.axes_dim_sum / 2);
811-
auto pe = ggml_new_tensor_4d(compute_ctx, GGML_TYPE_F32, 2, 2, config.axes_dim_sum / 2, pos_len);
812-
set_backend_tensor_data(pe, pe_vec.data());
803+
sd::PECacheKey pe_key("boogu.pe");
804+
pe_key.add_shape(x).add_shape(context).add(config.theta).add(config.axes_dim).add(config.axes_dim_sum);
805+
pe_key.add(circular_x_enabled).add(circular_y_enabled).add(config.patch_size).add_shapes(ref_latents);
806+
auto pe = make_input(pe_cache_.get_or_create(pe_key, [&]() {
807+
auto pe_vec = finish_rope_pe(gen_boogu_pe(static_cast<int>(x->ne[1]),
808+
static_cast<int>(x->ne[0]),
809+
config.patch_size,
810+
static_cast<int>(x->ne[3]),
811+
static_cast<int>(context->ne[1]),
812+
ref_latents,
813+
config.theta,
814+
config.axes_dim));
815+
int pos_len = static_cast<int>(pe_vec.size() / config.axes_dim_sum / 2);
816+
return sd::Tensor<float>({2, 2, config.axes_dim_sum / 2, pos_len}, std::move(pe_vec));
817+
}));
813818

814819
auto runner_ctx = get_context();
815820
ggml_tensor* out = boogu.forward(&runner_ctx, x, timesteps, context, pe, ref_latents);

‎src/model/diffusion/ernie_image.hpp‎

Lines changed: 16 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
#include <cinttypes>
55
#include <memory>
66
#include <vector>
7+
#include "core/pe_cache.h"
78

89
#include "model/common/rope.hpp"
910
#include "model/diffusion/dit.hpp"
@@ -383,9 +384,9 @@ namespace ErnieImage {
383384
};
384385

385386
struct ErnieImageRunner : public DiffusionModelRunner {
387+
sd::PECache pe_cache_;
386388
ErnieImageConfig config;
387389
ErnieImageModel ernie_image;
388-
std::vector<float> pe_vec;
389390

390391
ErnieImageRunner(ggml_backend_t backend,
391392
const String2TensorStorage& tensor_storage_map = {},
@@ -415,16 +416,20 @@ namespace ErnieImage {
415416
GGML_ASSERT(!context_tensor.empty());
416417
ggml_tensor* context = make_input(context_tensor);
417418

418-
pe_vec = finish_rope_pe(Rope::gen_ernie_image_pe(static_cast<int>(x->ne[1]),
419-
static_cast<int>(x->ne[0]),
420-
config.patch_size,
421-
static_cast<int>(x->ne[3]),
422-
static_cast<int>(context->ne[1]),
423-
config.theta,
424-
config.axes_dim));
425-
int pos_len = static_cast<int>(pe_vec.size() / config.axes_dim_sum / 2);
426-
auto pe = ggml_new_tensor_4d(compute_ctx, GGML_TYPE_F32, config.axes_dim_sum, 1, pos_len, 2);
427-
set_backend_tensor_data(pe, pe_vec.data());
419+
sd::PECacheKey pe_key("ernie_image.pe");
420+
pe_key.add_shape(x).add_shape(context).add(config.theta).add(config.axes_dim).add(config.axes_dim_sum);
421+
pe_key.add(circular_x_enabled).add(circular_y_enabled).add(config.patch_size);
422+
auto pe = make_input(pe_cache_.get_or_create(pe_key, [&]() {
423+
auto pe_vec = finish_rope_pe(Rope::gen_ernie_image_pe(static_cast<int>(x->ne[1]),
424+
static_cast<int>(x->ne[0]),
425+
config.patch_size,
426+
static_cast<int>(x->ne[3]),
427+
static_cast<int>(context->ne[1]),
428+
config.theta,
429+
config.axes_dim));
430+
int pos_len = static_cast<int>(pe_vec.size() / config.axes_dim_sum / 2);
431+
return sd::Tensor<float>({config.axes_dim_sum, 1, pos_len, 2}, std::move(pe_vec));
432+
}));
428433

429434
auto runner_ctx = get_context();
430435
ggml_tensor* out = ernie_image.forward(&runner_ctx, x, timesteps, context, pe);

0 commit comments

Comments
 (0)