Phase 4: Layer skip with VSIDS-inspired profiling + sliding window

- Profile per-layer importance during prefill (||delta||² metric)
- Skip N least important layers during decode (saves bandwidth)
- Protect first/last 2 layers from being skipped
- Sliding window attention mask (--sliding-window W)
- CLI: --layer-skip N, --sliding-window W
- Integrated in both standard AR and speculative paths

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
Carmen EstebanandClaude Opus 4.6 committed 2026-04-05 19:07:02 +02:00
1 parent 04065aa1ce
commit 46e9dc1fbe
7 files changed
+195 -12

No files matched your search

+5 -1
View File
@@ -102,6 +102,8 @@ struct ar_sampler_params {
float repeat_penalty = 1.1f; // repetition penalty
int repeat_last_n = 64; // window for repeat penalty
uint32_t seed = 42;
int layer_skip = 0; // skip N least important layers (0 = disabled)
int sliding_window = 0; // attend last W positions only (0 = full)
};
// ── AR token callback (return false to stop) ──────────────────
@@ -120,7 +122,9 @@ std::vector<int32_t> ar_generate(
// ═══════════════════════════════════════════════════════════════
struct ar_spec_params {
int K = 5; // speculative lookahead (draft tokens per round)
int K = 5; // speculative lookahead (draft tokens per round)
int layer_skip = 0; // skip N least important target layers (0 = disabled)
int sliding_window = 0; // attend last W positions only (0 = full)
};
struct ar_spec_stats {
+8
View File
@@ -28,6 +28,11 @@ struct ar_kv_cache {
int n_embd_head = 0;
int n_head_kv = 0; // KV heads (8 for Qwen2.5-32B, not expanded)
// ── Layer skip / optimization (VSIDS-inspired) ──────────────
std::vector<bool> skip_layers; // [n_layer] true = skip during decode
std::vector<float> layer_impact; // [n_layer] profiled impact scores
int sliding_window = 0; // 0 = full context, >0 = attend last W positions
// Per-layer K and V arrays
// Shape per layer: [n_ctx_max * n_head_kv * n_embd_head]
// Access pattern: cache[layer][pos * stride ... (pos+1) * stride]
@@ -67,7 +72,10 @@ struct ar_kv_cache {
void clear() {
K.clear();
V.clear();
skip_layers.clear();
layer_impact.clear();
n_past = 0;
sliding_window = 0;
initialized = false;
free_compute_resources();
}
+128 -5
View File
@@ -1,5 +1,9 @@
#include "ar-graph.h"
#include <algorithm>
#include <vector>
#include <utility>
// ── Helper: ensure tensor is F32 (for bias add after quantization) ──
static struct ggml_tensor * ensure_f32(struct ggml_context * ctx, struct ggml_tensor * t) {
if (!t) return nullptr;
@@ -25,7 +29,8 @@ static struct ggml_cgraph * ar_build_graph(
const int32_t * tokens,
int n_new,
int n_past,
ar_kv_cache * cache) {
ar_kv_cache * cache,
bool profile = false) {
const auto & model = *dctx->model;
const auto & hp = model.hparams;
@@ -67,10 +72,13 @@ static struct ggml_cgraph * ar_build_graph(
ggml_fp16_t * mask_data = (ggml_fp16_t *)attn_mask->data;
const ggml_fp16_t zero_f16 = ggml_fp32_to_fp16(0.0f);
const ggml_fp16_t ninf_f16 = ggml_fp32_to_fp16(-INFINITY);
const int sw = (cache && cache->sliding_window > 0) ? cache->sliding_window : 0;
for (int q = 0; q < n_new; q++) {
int q_abs = n_past + q;
for (int k = 0; k < n_kv; k++) {
mask_data[q * n_kv + k] = (k <= q_abs) ? zero_f16 : ninf_f16;
bool visible = (k <= q_abs);
if (sw > 0 && q_abs - k >= sw) visible = false;
mask_data[q * n_kv + k] = visible ? zero_f16 : ninf_f16;
}
}
}
@@ -80,6 +88,14 @@ static struct ggml_cgraph * ar_build_graph(
// ── Transformer layers ───────────────────────────────────────
for (int il = 0; il < n_layer; il++) {
// Layer skip (VSIDS-inspired): skip least important layers during decode
if (cache && !cache->skip_layers.empty() &&
(size_t)il < cache->skip_layers.size() && cache->skip_layers[il]) {
continue;
}
struct ggml_tensor * layer_input = profile ? cur : nullptr;
const auto & layer = model.layers[il];
struct ggml_tensor * residual = cur;
@@ -200,6 +216,17 @@ static struct ggml_cgraph * ar_build_graph(
cur = ggml_mul_mat(ctx, layer.ffn_down, cur);
cur = ggml_add(ctx, cur, residual);
// Layer importance profiling: ||layer_output - layer_input||²
// Used to identify least important layers for skip during decode
if (profile && layer_input) {
struct ggml_tensor * delta = ggml_sub(ctx, cur, layer_input);
struct ggml_tensor * dsq = ggml_sum(ctx, ggml_sqr(ctx, delta));
char name_buf[32];
snprintf(name_buf, sizeof(name_buf), "limp.%02d", il);
ggml_set_name(dsq, name_buf);
ggml_set_output(dsq);
}
}
// ── Final norm + logits ──────────────────────────────────────
@@ -225,7 +252,8 @@ static bool ar_forward_impl(
const int32_t * tokens,
int n_new,
ar_kv_cache * cache,
float * logits_out) {
float * logits_out,
bool profile = false) {
const auto & hp = ctx->model->hparams;
const int n_past = cache->n_past;
@@ -252,6 +280,11 @@ static bool ar_forward_impl(
buf_size += (size_t)n_kv * n_new * sizeof(ggml_fp16_t);
buf_size += n_new * sizeof(int32_t) * 2;
// Profile mode: extra tensors (sub + sqr per layer, ~2 * n_embd * n_new each)
if (profile) {
buf_size += (size_t)hp.n_layer * hp.n_embd * n_new * sizeof(float) * 2;
}
// Graph metadata overhead
buf_size += 256ull * 1024 * 1024;
buf_size = (size_t)(buf_size * 1.2);
@@ -272,7 +305,7 @@ static bool ar_forward_impl(
}
struct ggml_cgraph * gf = ar_build_graph(ctx, ctx_compute, tokens,
n_new, n_past, cache);
n_new, n_past, cache, profile);
// Use persistent threadpool + work buffer for graph compute
struct ggml_cplan plan = ggml_graph_plan(gf, ctx->n_threads, cache->threadpool);
@@ -310,13 +343,28 @@ static bool ar_forward_impl(
if (K_t && V_t) {
cache->append(il, (const float *)K_t->data,
(const float *)V_t->data, n_new);
} else {
} else if (cache->skip_layers.empty() ||
(size_t)il >= cache->skip_layers.size() ||
!cache->skip_layers[il]) {
DIFFUSE_LOG("WARNING: could not extract K/V for layer %d", il);
}
// Skipped layers produce no K/V — expected
}
}
cache->advance(n_new);
// Extract layer impact scores if profiling
if (profile) {
const int n_lay = (int)hp.n_layer;
cache->layer_impact.resize(n_lay, 0.0f);
char name_buf[32];
for (int il = 0; il < n_lay; il++) {
snprintf(name_buf, sizeof(name_buf), "limp.%02d", il);
struct ggml_tensor * imp_t = ggml_graph_get_tensor(gf, name_buf);
cache->layer_impact[il] = imp_t ? *(float *)imp_t->data : 0.0f;
}
}
ggml_free(ctx_compute);
return true;
}
@@ -371,3 +419,78 @@ bool ar_forward_batch(
DIFFUSE_LOG("ar_forward_batch: %d tokens, n_past=%d", n_tokens, cache->n_past);
return ar_forward_impl(ctx, tokens, n_tokens, cache, logits_out);
}
// ── Public API: Profile layers and configure skip mask ──────────
//
// VSIDS-inspired optimization: profile per-layer importance during prefill,
// then skip the N least important layers during decode to save bandwidth.
//
// For Qwen2.5-32B (64 layers, ~244 MB/layer): skipping 6 layers saves
// ~1.5 GB of weight reads per decode step (~5% bandwidth reduction).
//
// Importance metric: ||layer_output - layer_input||² (sum of squared delta).
// Layers with smallest delta contribute least to the representation.
// First and last 2 layers are always protected (never skipped).
//
bool ar_profile_layers(
diffuse_context * ctx,
const int32_t * tokens,
int n_tokens,
ar_kv_cache * cache,
float * logits_out,
int n_skip) {
if (!cache || !cache->initialized) {
DIFFUSE_LOG("ar_profile_layers: cache not initialized");
return false;
}
const int n_layer = (int)ctx->model->hparams.n_layer;
// Clear any existing skip mask (profile with all layers active)
cache->skip_layers.clear();
cache->reset();
DIFFUSE_LOG("ar_profile_layers: %d tokens, target skip=%d/%d layers",
n_tokens, n_skip, n_layer);
// Run prefill with profiling enabled
if (!ar_forward_impl(ctx, tokens, n_tokens, cache, logits_out, /*profile=*/true)) {
DIFFUSE_LOG("ar_profile_layers: prefill failed");
return false;
}
// Select layers to skip based on impact scores
if (n_skip > 0 && !cache->layer_impact.empty()) {
// Rank layers by impact (ascending = least important first)
std::vector<std::pair<float, int>> ranked;
ranked.reserve(n_layer);
for (int il = 0; il < n_layer; il++) {
ranked.push_back({cache->layer_impact[il], il});
}
std::sort(ranked.begin(), ranked.end());
// Report top/bottom layer impacts
DIFFUSE_LOG(" lowest impact layers:");
for (int i = 0; i < std::min(n_skip + 4, n_layer); i++) {
DIFFUSE_LOG(" layer %2d: impact = %.2f%s",
ranked[i].second, ranked[i].first,
(ranked[i].second < 2 || ranked[i].second >= n_layer - 2)
? " [PROTECTED]" : "");
}
// Skip the N least impactful, protecting first/last 2 layers
cache->skip_layers.resize(n_layer, false);
int skipped = 0;
for (auto & [imp, il] : ranked) {
if (skipped >= n_skip) break;
if (il < 2 || il >= n_layer - 2) continue;
cache->skip_layers[il] = true;
skipped++;
}
DIFFUSE_LOG(" layer-skip: %d/%d layers skipped during decode", skipped, n_layer);
}
return true;
}
+11
View File
@@ -37,3 +37,14 @@ bool ar_forward_batch(
int n_tokens,
ar_kv_cache * cache,
float * logits_out);
// Profile layer importance and configure skip mask (VSIDS-inspired).
// Runs prefill with profiling, selects n_skip least important layers to skip.
// Results stored in cache->skip_layers (used by all subsequent forward calls).
bool ar_profile_layers(
diffuse_context * ctx,
const int32_t * tokens,
int n_tokens,
ar_kv_cache * cache,
float * logits_out,
int n_skip);
+13 -3
View File
@@ -185,14 +185,24 @@ std::vector<int32_t> ar_generate(
double decode_ms = 0.0;
int n_decoded = 0;
// Set sliding window if configured
cache.sliding_window = params.sliding_window;
// ── Phase 1: Prefill (process all prompt tokens) ─────────────
{
auto t0 = clk::now();
logits.resize((size_t)prompt_len * n_vocab);
if (!ar_forward_prefill(ctx, prompt_tokens.data(), prompt_len,
&cache, logits.data())) {
DIFFUSE_DIE("ar_generate: prefill failed");
if (params.layer_skip > 0) {
if (!ar_profile_layers(ctx, prompt_tokens.data(), prompt_len,
&cache, logits.data(), params.layer_skip)) {
DIFFUSE_DIE("ar_generate: profile prefill failed");
}
} else {
if (!ar_forward_prefill(ctx, prompt_tokens.data(), prompt_len,
&cache, logits.data())) {
DIFFUSE_DIE("ar_generate: prefill failed");
}
}
auto t1 = clk::now();
+17 -3
View File
@@ -97,16 +97,30 @@ std::vector<int32_t> ar_speculative_generate(
using clk = std::chrono::steady_clock;
auto gen_start = clk::now();
// Set sliding window on target cache if configured
target_cache.sliding_window = params.sliding_window;
// ── Prefill both models ─────────────────────────────────────
std::vector<float> t_prefill_logits((size_t)prompt_len * t_vocab);
{
std::vector<float> d_prefill_logits((size_t)prompt_len * d_vocab);
auto t0 = clk::now();
if (!ar_forward_prefill(target_ctx, prompt_tokens.data(), prompt_len,
&target_cache, t_prefill_logits.data())) {
DIFFUSE_DIE("speculative: target prefill failed");
// Target prefill: optionally profile and set layer skip mask
if (params.layer_skip > 0) {
if (!ar_profile_layers(target_ctx, prompt_tokens.data(), prompt_len,
&target_cache, t_prefill_logits.data(),
params.layer_skip)) {
DIFFUSE_DIE("speculative: target profile prefill failed");
}
} else {
if (!ar_forward_prefill(target_ctx, prompt_tokens.data(), prompt_len,
&target_cache, t_prefill_logits.data())) {
DIFFUSE_DIE("speculative: target prefill failed");
}
}
if (!ar_forward_prefill(draft_ctx, prompt_tokens.data(), prompt_len,
&draft_cache, d_prefill_logits.data())) {
DIFFUSE_DIE("speculative: draft prefill failed");
+13
View File
@@ -30,6 +30,9 @@ static void print_usage(const char * prog) {
fprintf(stderr, " --draft PATH Draft model GGUF (enables speculative decoding)\n");
fprintf(stderr, " --spec-k INT Speculative lookahead (default: 4)\n");
fprintf(stderr, " --draft-threads INT Threads for draft model (default: 4)\n");
fprintf(stderr, "\nOptimizations:\n");
fprintf(stderr, " --layer-skip INT Skip N least important layers during decode (default: 0)\n");
fprintf(stderr, " --sliding-window INT Attend only last W tokens (default: 0 = full context)\n");
fprintf(stderr, "\nExample:\n");
fprintf(stderr, " %s -m thrombia-32b-q4.gguf --tokens 151644,8948,198,... -n 512 -t 12\n", prog);
fprintf(stderr, " %s -m thrombia-32b-q4.gguf --draft qwen2.5-0.5b-q4.gguf --spec-k 5 -t 12\n", prog);
@@ -55,6 +58,8 @@ int main(int argc, char ** argv) {
int n_threads = 4;
int draft_threads = 4;
int spec_k = 4;
int layer_skip = 0;
int sliding_window = 0;
float temperature = 0.0f;
float top_p = 0.9f;
int top_k = 40;
@@ -92,6 +97,10 @@ int main(int argc, char ** argv) {
seed = atoi(argv[++i]);
} else if (strcmp(argv[i], "--tokens") == 0 && i + 1 < argc) {
input_tokens = parse_tokens(argv[++i]);
} else if (strcmp(argv[i], "--layer-skip") == 0 && i + 1 < argc) {
layer_skip = atoi(argv[++i]);
} else if (strcmp(argv[i], "--sliding-window") == 0 && i + 1 < argc) {
sliding_window = atoi(argv[++i]);
} else if (strcmp(argv[i], "--bind-cores") == 0) {
bind_cores = true;
} else if (strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "--help") == 0) {
@@ -172,6 +181,8 @@ int main(int argc, char ** argv) {
ar_spec_params sparams;
sparams.K = spec_k;
sparams.layer_skip = layer_skip;
sparams.sliding_window = sliding_window;
ar_spec_stats stats;
@@ -228,6 +239,8 @@ int main(int argc, char ** argv) {
sparams.repeat_penalty = repeat_penalty;
sparams.repeat_last_n = repeat_last_n;
sparams.seed = seed;
sparams.layer_skip = layer_skip;
sparams.sliding_window = sliding_window;
// Generate with streaming output
fprintf(stderr, "Generating (greedy=%s, temp=%.2f, top_p=%.2f, top_k=%d)...\n",