diff --git a/CMakeLists.txt b/CMakeLists.txt index ca569cd..a08eaa8 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -15,11 +15,13 @@ set(GGML_BUILD_EXAMPLES OFF CACHE BOOL "" FORCE) set(GGML_OPENMP ON CACHE BOOL "" FORCE) add_subdirectory(ggml) -# ── Core library ──────────────────────────────────────────────── +# ── Core library (diffusion + autoregressive) ───────────────── add_library(diffuse src/diffuse-model.cpp src/diffuse-graph.cpp src/diffuse-sampler.cpp + src/ar-graph.cpp + src/ar-sampler.cpp ) target_include_directories(diffuse PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include @@ -29,9 +31,14 @@ target_link_libraries(diffuse PUBLIC ggml) # ── CLI tools ─────────────────────────────────────────────────── if(DIFFUSE_BUILD_TOOLS) + # Diffusion CLI (LLaDA, Dream) add_executable(diffuse-cli tools/main-cli.cpp) target_link_libraries(diffuse-cli PRIVATE diffuse) + # Autoregressive CLI (Qwen2.5, Llama, etc.) + add_executable(diffuse-ar tools/ar-cli.cpp) + target_link_libraries(diffuse-ar PRIVATE diffuse) + add_executable(diffuse-bench tools/main-bench.cpp) target_link_libraries(diffuse-bench PRIVATE diffuse) diff --git a/include/diffuse.h b/include/diffuse.h index 681504b..c3fce1a 100644 --- a/include/diffuse.h +++ b/include/diffuse.h @@ -90,4 +90,29 @@ std::vector diffuse_generate( const diffuse_sampler_params & params, diffuse_step_callback callback = nullptr); +// ═══════════════════════════════════════════════════════════════ +// ── Autoregressive API ──────────────────────────────────────── +// ═══════════════════════════════════════════════════════════════ + +// ── AR sampler parameters ───────────────────────────────────── +struct ar_sampler_params { + float temperature = 0.0f; // 0 = greedy/argmax + float top_p = 0.9f; // nucleus sampling + int top_k = 40; // top-k (0 = disabled) + float repeat_penalty = 1.1f; // repetition penalty + int repeat_last_n = 64; // window for repeat penalty + uint32_t seed = 42; +}; + +// ── AR token callback (return false to stop) ────────────────── +using ar_token_callback = std::function; + +// ── AR generation ───────────────────────────────────────────── +std::vector ar_generate( + diffuse_context * ctx, + const std::vector & prompt_tokens, + int max_tokens, + const ar_sampler_params & params, + ar_token_callback callback = nullptr); + // end of diffuse.h diff --git a/src/ar-cache.h b/src/ar-cache.h new file mode 100644 index 0000000..a5487a6 --- /dev/null +++ b/src/ar-cache.h @@ -0,0 +1,117 @@ +#pragma once + +#include "diffuse-common.h" +#include +#include + +// ── Autoregressive KV cache (append-only) ──────────────────────── +// +// Standard autoregressive KV cache: appends new K,V after each token. +// Layout per layer: [n_ctx_max][n_head_kv * n_embd_head] flattened. +// +// For Qwen2.5-32B: 64 layers, 8 KV heads, 128 dim, 4096 ctx max +// = 64 * 2 * 4096 * 8 * 128 * 4 bytes = ~2 GB +// +// K and V are stored BEFORE GQA expansion (n_head_kv, not n_head) +// to save memory. GQA repeat happens in the graph at attention time. + +struct ar_kv_cache { + bool initialized = false; + int n_ctx_max = 0; // max context length + int n_past = 0; // tokens currently in cache + int n_layer = 0; + int n_embd_head = 0; + int n_head_kv = 0; // KV heads (8 for Qwen2.5-32B, not expanded) + + // 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] + std::vector> K; // K[layer] + std::vector> V; // V[layer] + + // ── Lifecycle ──────────────────────────────────────────────── + + void init(int ctx_max, int n_lay, int n_eh, int n_hkv) { + n_ctx_max = ctx_max; + n_layer = n_lay; + n_embd_head = n_eh; + n_head_kv = n_hkv; + n_past = 0; + + size_t kv_size = (size_t)n_ctx_max * n_head_kv * n_embd_head; + K.resize(n_layer); + V.resize(n_layer); + for (int il = 0; il < n_layer; il++) { + K[il].resize(kv_size, 0.0f); + V[il].resize(kv_size, 0.0f); + } + + initialized = true; + DIFFUSE_LOG("ar_kv_cache: %d layers, %d kv_heads, %d head_dim, %d ctx_max (%.1f MB)", + n_layer, n_head_kv, n_embd_head, n_ctx_max, + (float)(2 * n_layer * kv_size * sizeof(float)) / (1024 * 1024)); + } + + void clear() { + K.clear(); + V.clear(); + n_past = 0; + initialized = false; + } + + // Reset to empty (keep allocation) + void reset() { + n_past = 0; + } + + // Floats per position per layer: n_head_kv * n_embd_head + size_t pos_stride() const { + return (size_t)n_head_kv * n_embd_head; + } + + // Total bytes of the cache + size_t total_bytes() const { + return (size_t)2 * n_layer * n_ctx_max * pos_stride() * sizeof(float); + } + + // ── Append new K,V for n_new tokens at positions [n_past, n_past+n_new) ── + // + // K_new, V_new: [n_embd_head, n_head_kv, n_new] (GGML layout, pre-GQA) + // This matches the output shape from QKV projection + reshape_3d. + + void append(int layer, const float * K_new, const float * V_new, int n_new) { + if (n_past + n_new > n_ctx_max) { + DIFFUSE_LOG("WARNING: KV cache overflow (%d + %d > %d), wrapping", + n_past, n_new, n_ctx_max); + // Simple sliding window: shift left by n_new + size_t stride = pos_stride(); + size_t shift_bytes = (size_t)(n_ctx_max - n_new) * stride * sizeof(float); + size_t new_bytes = (size_t)n_new * stride * sizeof(float); + memmove(K[layer].data(), K[layer].data() + n_new * stride, shift_bytes); + memmove(V[layer].data(), V[layer].data() + n_new * stride, shift_bytes); + memcpy(K[layer].data() + (n_ctx_max - n_new) * stride, K_new, new_bytes); + memcpy(V[layer].data() + (n_ctx_max - n_new) * stride, V_new, new_bytes); + // n_past stays at n_ctx_max (updated by caller only once after all layers) + return; + } + + size_t stride = pos_stride(); + size_t offset = (size_t)n_past * stride; + size_t bytes = (size_t)n_new * stride * sizeof(float); + memcpy(K[layer].data() + offset, K_new, bytes); + memcpy(V[layer].data() + offset, V_new, bytes); + } + + // Advance the position counter (call once after appending to all layers) + void advance(int n_new) { + n_past = std::min(n_past + n_new, n_ctx_max); + } + + // ── Access cached K,V for attention ────────────────────────── + // + // Returns pointer to layer's K or V data starting at position 0. + // Caller uses n_past to know how many positions are valid. + + const float * k_data(int layer) const { return K[layer].data(); } + const float * v_data(int layer) const { return V[layer].data(); } +}; diff --git a/src/ar-graph.cpp b/src/ar-graph.cpp new file mode 100644 index 0000000..7848381 --- /dev/null +++ b/src/ar-graph.cpp @@ -0,0 +1,354 @@ +#include "ar-graph.h" + +// ── 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; + if (t->type != GGML_TYPE_F32) return ggml_cast(ctx, t, GGML_TYPE_F32); + return t; +} + +// ── Build autoregressive forward graph ────────────────────────── +// +// Standard transformer with causal attention and KV cache. +// Uses the same GGML ops as diffuse-graph.cpp but with: +// 1. Causal mask via ggml_soft_max_ext +// 2. KV cache append (only compute new tokens' K,V) +// 3. RoPE with absolute positions (n_past + i) +// +// n_new: number of NEW tokens (full prompt for prefill, 1 for decode) +// n_past: number of tokens already in KV cache + +static struct ggml_cgraph * ar_build_graph( + diffuse_context * dctx, + struct ggml_context * ctx, + const int32_t * tokens, + int n_new, + int n_past, + ar_kv_cache * cache) { + + const auto & model = *dctx->model; + const auto & hp = model.hparams; + const int n_embd = (int)hp.n_embd; + const int n_head = (int)hp.n_head; + const int n_head_kv = (int)hp.n_head_kv; + const int n_embd_head = (int)hp.n_embd_head(); + const int n_layer = (int)hp.n_layer; + const int n_kv = n_past + n_new; // total KV length + + struct ggml_cgraph * gf = ggml_new_graph_custom(ctx, + (size_t)(4096 * n_layer + n_layer * 4 + 256), false); + + // ── Input tokens ───────────────────────────────────────────── + struct ggml_tensor * inp_tokens = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, n_new); + ggml_set_name(inp_tokens, "inp_tokens"); + ggml_set_input(inp_tokens); + memcpy(inp_tokens->data, tokens, n_new * sizeof(int32_t)); + + // ── Position indices for new tokens ────────────────────────── + struct ggml_tensor * inp_pos = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, n_new); + ggml_set_name(inp_pos, "inp_pos"); + ggml_set_input(inp_pos); + { + int32_t * pos_data = (int32_t *)inp_pos->data; + for (int i = 0; i < n_new; i++) { + pos_data[i] = n_past + i; + } + } + + // ── Causal attention mask ──────────────────────────────────── + // Shape for ggml_soft_max_ext: [n_kv, n_new] + // mask[k, q] = 0.0 if position k can be attended by query q, else -inf + // For causal: q at absolute position (n_past+q) can see positions 0..(n_past+q) + struct ggml_tensor * attn_mask = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_kv, n_new); + ggml_set_name(attn_mask, "attn_mask"); + ggml_set_input(attn_mask); + { + float * mask_data = (float *)attn_mask->data; + 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) ? 0.0f : -INFINITY; + } + } + } + + // ── Embedding lookup ───────────────────────────────────────── + struct ggml_tensor * cur = ggml_get_rows(ctx, model.tok_embd, inp_tokens); + + // ── Transformer layers ─────────────────────────────────────── + for (int il = 0; il < n_layer; il++) { + const auto & layer = model.layers[il]; + struct ggml_tensor * residual = cur; + + // Pre-attention RMSNorm + cur = ggml_rms_norm(ctx, cur, hp.rms_norm_eps); + { + struct ggml_tensor * norm_w = layer.attn_norm; + if (norm_w->type != GGML_TYPE_F32) { + norm_w = ggml_cast(ctx, norm_w, GGML_TYPE_F32); + } + cur = ggml_mul(ctx, cur, norm_w); + } + + // QKV projections for new tokens only + struct ggml_tensor * Q = ggml_mul_mat(ctx, layer.wq, cur); + struct ggml_tensor * K_new = ggml_mul_mat(ctx, layer.wk, cur); + struct ggml_tensor * V_new = ggml_mul_mat(ctx, layer.wv, cur); + + // Add QKV biases if present (Qwen2.5) + if (layer.bq) Q = ggml_add(ctx, Q, ensure_f32(ctx, layer.bq)); + if (layer.bk) K_new = ggml_add(ctx, K_new, ensure_f32(ctx, layer.bk)); + if (layer.bv) V_new = ggml_add(ctx, V_new, ensure_f32(ctx, layer.bv)); + + // Reshape: [n_embd, n_new] → [n_embd_head, n_head(_kv), n_new] + Q = ggml_reshape_3d(ctx, Q, n_embd_head, n_head, n_new); + K_new = ggml_reshape_3d(ctx, K_new, n_embd_head, n_head_kv, n_new); + V_new = ggml_reshape_3d(ctx, V_new, n_embd_head, n_head_kv, n_new); + + // RoPE on Q and K_new with absolute positions + Q = ggml_rope_ext(ctx, Q, inp_pos, nullptr, n_embd_head, + GGML_ROPE_TYPE_NEOX, 0, hp.rope_theta, + 1.0f, 0.0f, 1.0f, 0.0f, 0.0f); + K_new = ggml_rope_ext(ctx, K_new, inp_pos, nullptr, n_embd_head, + GGML_ROPE_TYPE_NEOX, 0, hp.rope_theta, + 1.0f, 0.0f, 1.0f, 0.0f, 0.0f); + + // Mark K_new, V_new as outputs for cache extraction + { + char name_buf[32]; + snprintf(name_buf, sizeof(name_buf), "Kn.%02d", il); + ggml_set_name(K_new, name_buf); + ggml_set_output(K_new); + + snprintf(name_buf, sizeof(name_buf), "Vn.%02d", il); + ggml_set_name(V_new, name_buf); + ggml_set_output(V_new); + } + + // ── Build full K,V: concat cached + new ───────────────── + struct ggml_tensor * K_full; + struct ggml_tensor * V_full; + + if (n_past > 0) { + // Load cached K,V as input tensors + // Shape: [n_embd_head, n_head_kv, n_past] + struct ggml_tensor * K_cached = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, + n_embd_head, n_head_kv, n_past); + ggml_set_input(K_cached); + memcpy(K_cached->data, cache->k_data(il), + (size_t)n_past * cache->pos_stride() * sizeof(float)); + + struct ggml_tensor * V_cached = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, + n_embd_head, n_head_kv, n_past); + ggml_set_input(V_cached); + memcpy(V_cached->data, cache->v_data(il), + (size_t)n_past * cache->pos_stride() * sizeof(float)); + + K_full = ggml_concat(ctx, K_cached, K_new, 2); + V_full = ggml_concat(ctx, V_cached, V_new, 2); + } else { + K_full = K_new; + V_full = V_new; + } + // K_full, V_full: [n_embd_head, n_head_kv, n_kv] + + // ── GQA: expand KV heads to match Q heads ─────────────── + if (n_head_kv < n_head) { + const int n_rep = n_head / n_head_kv; + K_full = ggml_reshape_4d(ctx, K_full, n_embd_head, 1, n_head_kv, n_kv); + K_full = ggml_repeat(ctx, K_full, + ggml_new_tensor_4d(ctx, K_full->type, n_embd_head, n_rep, n_head_kv, n_kv)); + K_full = ggml_reshape_3d(ctx, K_full, n_embd_head, n_head, n_kv); + + V_full = ggml_reshape_4d(ctx, V_full, n_embd_head, 1, n_head_kv, n_kv); + V_full = ggml_repeat(ctx, V_full, + ggml_new_tensor_4d(ctx, V_full->type, n_embd_head, n_rep, n_head_kv, n_kv)); + V_full = ggml_reshape_3d(ctx, V_full, n_embd_head, n_head, n_kv); + } + + // ── Attention (same pattern as diffuse-graph.cpp) ──────── + // Q: [n_embd_head, n_head, n_new] → [n_embd_head, n_new, n_head] + Q = ggml_permute(ctx, Q, 0, 2, 1, 3); + // K: [n_embd_head, n_head, n_kv] → [n_embd_head, n_kv, n_head] + K_full = ggml_permute(ctx, K_full, 0, 2, 1, 3); + // V: [n_embd_head, n_head, n_kv] → [n_kv, n_embd_head, n_head] (contiguous) + V_full = ggml_cont(ctx, ggml_permute(ctx, V_full, 1, 2, 0, 3)); + + // K^T @ Q → [n_kv, n_new, n_head] + struct ggml_tensor * attn = ggml_mul_mat(ctx, K_full, Q); + + // Scale + causal mask + softmax (fused) + float scale = 1.0f / sqrtf((float)n_embd_head); + attn = ggml_soft_max_ext(ctx, attn, attn_mask, scale, 0.0f); + + // V^T @ attn → [n_embd_head, n_new, n_head] + struct ggml_tensor * attn_out = ggml_mul_mat(ctx, V_full, attn); + + // Merge heads: [n_embd_head, n_new, n_head] → [n_embd_head, n_head, n_new] → [n_embd, n_new] + attn_out = ggml_permute(ctx, attn_out, 0, 2, 1, 3); + attn_out = ggml_cont(ctx, attn_out); + attn_out = ggml_reshape_2d(ctx, attn_out, n_embd, n_new); + + // Output projection + cur = ggml_mul_mat(ctx, layer.wo, attn_out); + cur = ggml_add(ctx, cur, residual); + + // ── FFN (SwiGLU) ───────────────────────────────────────── + residual = cur; + cur = ggml_rms_norm(ctx, cur, hp.rms_norm_eps); + { + struct ggml_tensor * norm_w = layer.ffn_norm; + if (norm_w->type != GGML_TYPE_F32) { + norm_w = ggml_cast(ctx, norm_w, GGML_TYPE_F32); + } + cur = ggml_mul(ctx, cur, norm_w); + } + + struct ggml_tensor * gate = ggml_mul_mat(ctx, layer.ffn_gate, cur); + struct ggml_tensor * up = ggml_mul_mat(ctx, layer.ffn_up, cur); + gate = ggml_silu(ctx, gate); + cur = ggml_mul(ctx, gate, up); + cur = ggml_mul_mat(ctx, layer.ffn_down, cur); + + cur = ggml_add(ctx, cur, residual); + } + + // ── Final norm + logits ────────────────────────────────────── + cur = ggml_rms_norm(ctx, cur, hp.rms_norm_eps); + { + struct ggml_tensor * norm_w = model.output_norm; + if (norm_w->type != GGML_TYPE_F32) { + norm_w = ggml_cast(ctx, norm_w, GGML_TYPE_F32); + } + cur = ggml_mul(ctx, cur, norm_w); + } + cur = ggml_mul_mat(ctx, model.output, cur); + ggml_set_name(cur, "logits"); + ggml_set_output(cur); + + ggml_build_forward_expand(gf, cur); + return gf; +} + +// ── Execute forward pass and extract K,V into cache ────────────── +static bool ar_forward_impl( + diffuse_context * ctx, + const int32_t * tokens, + int n_new, + ar_kv_cache * cache, + float * logits_out) { + + const auto & hp = ctx->model->hparams; + const int n_past = cache->n_past; + const int n_kv = n_past + n_new; + const int n_head = (int)hp.n_head; + + // ── Compute buffer sizing ──────────────────────────────────── + size_t per_layer = (size_t)n_new * hp.n_embd * sizeof(float) * 10 + + (size_t)n_new * hp.n_ff * sizeof(float) * 3 + // Attention matrix: [n_kv, n_new, n_head] after GQA expansion + + (size_t)n_kv * n_new * n_head * sizeof(float) * 2 + // Cached K,V input: [n_embd_head, n_head_kv, n_past] × 2 + + (size_t)n_past * hp.n_embd_head() * hp.n_head_kv * sizeof(float) * 2 + // Expanded K,V: [n_embd_head, n_head, n_kv] × 2 + + (size_t)n_kv * hp.n_embd_head() * n_head * sizeof(float) * 4 + + hp.n_embd * sizeof(float) * 2; + size_t buf_size = per_layer * hp.n_layer; + + // Logits buffer + buf_size += (size_t)n_new * hp.n_vocab * sizeof(float) * 2; + + // Mask tensor + positions + buf_size += (size_t)n_kv * n_new * sizeof(float); + buf_size += n_new * sizeof(int32_t) * 2; + + // Overhead + buf_size += 256ull * 1024 * 1024; + buf_size = (size_t)(buf_size * 1.3); + + struct ggml_init_params cparams = { + /*.mem_size = */ buf_size, + /*.mem_buffer = */ nullptr, + /*.no_alloc = */ false, + }; + struct ggml_context * ctx_compute = ggml_init(cparams); + if (!ctx_compute) { + DIFFUSE_LOG("ar_forward: failed to allocate compute context (%zu MB)", + buf_size / (1024 * 1024)); + return false; + } + + struct ggml_cgraph * gf = ar_build_graph(ctx, ctx_compute, tokens, + n_new, n_past, cache); + + enum ggml_status status = ggml_graph_compute_with_ctx(ctx_compute, gf, ctx->n_threads); + if (status != GGML_STATUS_SUCCESS) { + DIFFUSE_LOG("ar_forward: graph compute failed with status %d", (int)status); + ggml_free(ctx_compute); + return false; + } + + // Extract logits + struct ggml_tensor * logits = ggml_graph_get_tensor(gf, "logits"); + if (!logits) { + DIFFUSE_LOG("ar_forward: logits tensor not found"); + ggml_free(ctx_compute); + return false; + } + memcpy(logits_out, logits->data, (size_t)n_new * hp.n_vocab * sizeof(float)); + + // Extract K_new, V_new and append to cache + { + char name_buf[32]; + for (int il = 0; il < (int)hp.n_layer; il++) { + snprintf(name_buf, sizeof(name_buf), "Kn.%02d", il); + struct ggml_tensor * K_t = ggml_graph_get_tensor(gf, name_buf); + snprintf(name_buf, sizeof(name_buf), "Vn.%02d", il); + struct ggml_tensor * V_t = ggml_graph_get_tensor(gf, name_buf); + + if (K_t && V_t) { + cache->append(il, (const float *)K_t->data, + (const float *)V_t->data, n_new); + } else { + DIFFUSE_LOG("WARNING: could not extract K/V for layer %d", il); + } + } + } + cache->advance(n_new); + + ggml_free(ctx_compute); + return true; +} + +// ── Public API: Prefill ────────────────────────────────────────── +bool ar_forward_prefill( + diffuse_context * ctx, + const int32_t * tokens, + int n_tokens, + ar_kv_cache * cache, + float * logits_out) { + + if (!cache || !cache->initialized) { + DIFFUSE_LOG("ar_forward_prefill: cache not initialized"); + return false; + } + + cache->reset(); + DIFFUSE_LOG("ar_forward_prefill: %d tokens", n_tokens); + return ar_forward_impl(ctx, tokens, n_tokens, cache, logits_out); +} + +// ── Public API: Decode one token ───────────────────────────────── +bool ar_forward_decode( + diffuse_context * ctx, + int32_t token, + ar_kv_cache * cache, + float * logits_out) { + + if (!cache || !cache->initialized) { + DIFFUSE_LOG("ar_forward_decode: cache not initialized"); + return false; + } + + return ar_forward_impl(ctx, &token, 1, cache, logits_out); +} diff --git a/src/ar-graph.h b/src/ar-graph.h new file mode 100644 index 0000000..4431121 --- /dev/null +++ b/src/ar-graph.h @@ -0,0 +1,29 @@ +#pragma once + +#include "diffuse-common.h" +#include "ar-cache.h" + +// ── Autoregressive forward pass ───────────────────────────────── +// +// Two modes: +// 1. Prefill: process N prompt tokens in batch, populate KV cache +// 2. Decode: process 1 token, read from KV cache +// +// Both modes return logits only for the NEW tokens (not the full ctx). + +// Prefill: process prompt tokens, fill KV cache, return logits for all positions. +// tokens: [n_tokens], logits_out: [n_tokens * n_vocab] +bool ar_forward_prefill( + diffuse_context * ctx, + const int32_t * tokens, + int n_tokens, + ar_kv_cache * cache, + float * logits_out); + +// Decode: process a single new token, append to KV cache, return logits. +// token: single token ID, logits_out: [n_vocab] +bool ar_forward_decode( + diffuse_context * ctx, + int32_t token, + ar_kv_cache * cache, + float * logits_out); diff --git a/src/ar-sampler.cpp b/src/ar-sampler.cpp new file mode 100644 index 0000000..d4ebe60 --- /dev/null +++ b/src/ar-sampler.cpp @@ -0,0 +1,286 @@ +#include "ar-sampler.h" +#include "ar-graph.h" + +#include +#include +#include +#include +#include + +// ── Top-K filtering ───────────────────────────────────────────── +// Keep only the top_k highest logits, set rest to -inf. +static void apply_top_k(float * logits, int n_vocab, int top_k) { + if (top_k <= 0 || top_k >= n_vocab) return; + + // Partial sort to find the k-th largest value + std::vector tmp(logits, logits + n_vocab); + std::nth_element(tmp.begin(), tmp.begin() + top_k, tmp.end(), + std::greater()); + float threshold = tmp[top_k - 1]; + + // Zero out anything below threshold + // (keep ties, so count how many are >= threshold) + for (int i = 0; i < n_vocab; i++) { + if (logits[i] < threshold) { + logits[i] = -INFINITY; + } + } +} + +// ── Top-P (nucleus) filtering ─────────────────────────────────── +// Sort by probability, keep tokens until cumulative prob >= top_p. +static void apply_top_p(float * logits, int n_vocab, float top_p) { + if (top_p >= 1.0f) return; + + // Softmax to get probabilities + float max_val = *std::max_element(logits, logits + n_vocab); + float sum = 0.0f; + for (int i = 0; i < n_vocab; i++) { + logits[i] = expf(logits[i] - max_val); + sum += logits[i]; + } + for (int i = 0; i < n_vocab; i++) { + logits[i] /= sum; + } + + // Sort indices by probability (descending) + std::vector idx(n_vocab); + std::iota(idx.begin(), idx.end(), 0); + std::sort(idx.begin(), idx.end(), [&](int a, int b) { + return logits[a] > logits[b]; + }); + + // Accumulate until we hit top_p + float cum = 0.0f; + int cutoff = n_vocab; + for (int i = 0; i < n_vocab; i++) { + cum += logits[idx[i]]; + if (cum >= top_p) { + cutoff = i + 1; + break; + } + } + + // Zero out everything beyond cutoff + for (int i = cutoff; i < n_vocab; i++) { + logits[idx[i]] = 0.0f; + } + + // Convert back to log-space for temperature application + for (int i = 0; i < n_vocab; i++) { + logits[i] = (logits[i] > 0.0f) ? logf(logits[i]) : -INFINITY; + } +} + +// ── Repetition penalty ────────────────────────────────────────── +static void apply_repeat_penalty(float * logits, int n_vocab, + const std::vector & recent_tokens, + float penalty) { + if (penalty <= 1.0f) return; + + for (int32_t tok : recent_tokens) { + if (tok >= 0 && tok < n_vocab) { + if (logits[tok] > 0.0f) { + logits[tok] /= penalty; + } else { + logits[tok] *= penalty; + } + } + } +} + +// ── Sample from logits ────────────────────────────────────────── +static int32_t sample_token(float * logits, int n_vocab, + const ar_sampler_params & params, + const std::vector & recent_tokens, + std::mt19937 & rng) { + + // Apply repetition penalty + apply_repeat_penalty(logits, n_vocab, recent_tokens, params.repeat_penalty); + + // Greedy (temperature == 0) + if (params.temperature <= 0.0f) { + int best = 0; + float best_val = logits[0]; + for (int i = 1; i < n_vocab; i++) { + if (logits[i] > best_val) { + best_val = logits[i]; + best = i; + } + } + return best; + } + + // Apply temperature + for (int i = 0; i < n_vocab; i++) { + logits[i] /= params.temperature; + } + + // Apply top-k + apply_top_k(logits, n_vocab, params.top_k); + + // Apply top-p + apply_top_p(logits, n_vocab, params.top_p); + + // Softmax → sample + float max_val = *std::max_element(logits, logits + n_vocab); + float sum = 0.0f; + std::vector probs(n_vocab); + for (int i = 0; i < n_vocab; i++) { + probs[i] = expf(logits[i] - max_val); + sum += probs[i]; + } + for (int i = 0; i < n_vocab; i++) { + probs[i] /= sum; + } + + std::discrete_distribution dist(probs.begin(), probs.end()); + return dist(rng); +} + +// ── Main autoregressive generation loop ───────────────────────── +std::vector ar_generate( + diffuse_context * ctx, + const std::vector & prompt_tokens, + int max_tokens, + const ar_sampler_params & params, + ar_token_callback callback) { + + const auto & hp = ctx->model->hparams; + const int n_vocab = hp.n_vocab; + const int prompt_len = (int)prompt_tokens.size(); + const int total_ctx = prompt_len + max_tokens; + + DIFFUSE_LOG("ar_generate: prompt=%d tokens, max_generate=%d, ctx=%d", + prompt_len, max_tokens, total_ctx); + + // Initialize KV cache + ar_kv_cache cache; + cache.init(total_ctx, (int)hp.n_layer, (int)hp.n_embd_head(), + (int)hp.n_head_kv); + + // RNG + std::mt19937 rng(params.seed); + + // Logits buffer + std::vector logits; + + // Timing + using clk = std::chrono::steady_clock; + auto gen_start = clk::now(); + double prefill_ms = 0.0; + double decode_ms = 0.0; + int n_decoded = 0; + + // ── 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"); + } + + auto t1 = clk::now(); + prefill_ms = std::chrono::duration(t1 - t0).count(); + DIFFUSE_LOG(" prefill: %d tokens in %.1f ms (%.1f tok/s)", + prompt_len, prefill_ms, + 1000.0 * prompt_len / prefill_ms); + } + + // ── Phase 2: Decode (token by token) ───────────────────────── + std::vector generated; + generated.reserve(max_tokens); + + // Recent tokens for repeat penalty (start with prompt tail) + std::vector recent; + { + int start = std::max(0, prompt_len - params.repeat_last_n); + for (int i = start; i < prompt_len; i++) { + recent.push_back(prompt_tokens[i]); + } + } + + // Get the first token from prefill logits (last position) + { + float * last_logits = logits.data() + (size_t)(prompt_len - 1) * n_vocab; + std::vector logit_copy(last_logits, last_logits + n_vocab); + int32_t first_token = sample_token(logit_copy.data(), n_vocab, + params, recent, rng); + generated.push_back(first_token); + recent.push_back(first_token); + if ((int)recent.size() > params.repeat_last_n) { + recent.erase(recent.begin()); + } + + if (callback && !callback(first_token, prompt_len)) { + goto done; + } + } + + // Decode remaining tokens + logits.resize(n_vocab); // Reuse for single-token decode + + { + auto decode_start = clk::now(); + + for (int i = 1; i < max_tokens; i++) { + int32_t last_token = generated.back(); + + // Check for EOS + // Common EOS tokens: Qwen2.5 uses 151643 (<|im_end|>), 151645 (<|endoftext|>) + // We check via the model's hparams if available, otherwise use hardcoded + // For now, stop on any of the common Qwen2.5 stop tokens + if (last_token == 151643 || last_token == 151645 || + last_token == 151644) { // <|im_start|> shouldn't appear in generation + DIFFUSE_LOG(" EOS token %d at position %d", last_token, + prompt_len + i - 1); + break; + } + + if (!ar_forward_decode(ctx, last_token, &cache, logits.data())) { + DIFFUSE_LOG("ar_generate: decode failed at token %d", i); + break; + } + + std::vector logit_copy(logits.begin(), logits.end()); + int32_t new_token = sample_token(logit_copy.data(), n_vocab, + params, recent, rng); + generated.push_back(new_token); + recent.push_back(new_token); + if ((int)recent.size() > params.repeat_last_n) { + recent.erase(recent.begin()); + } + n_decoded++; + + if (callback && !callback(new_token, prompt_len + i)) { + break; + } + } + + auto decode_end = clk::now(); + decode_ms = std::chrono::duration(decode_end - decode_start).count(); + } + +done: + // ── Timing summary ─────────────────────────────────────────── + auto gen_end = clk::now(); + double total_ms = std::chrono::duration(gen_end - gen_start).count(); + + DIFFUSE_LOG("=== AR GENERATION COMPLETE ==="); + DIFFUSE_LOG(" prefill: %6.1f ms (%d tokens, %.1f tok/s)", + prefill_ms, prompt_len, + 1000.0 * prompt_len / std::max(prefill_ms, 0.1)); + DIFFUSE_LOG(" decode: %6.1f ms (%d tokens, %.2f tok/s)", + decode_ms, n_decoded, + n_decoded > 0 ? 1000.0 * n_decoded / decode_ms : 0.0); + DIFFUSE_LOG(" total: %6.1f ms (%d generated)", + total_ms, (int)generated.size()); + DIFFUSE_LOG(" KV cache: %d / %d positions used (%.1f MB)", + cache.n_past, cache.n_ctx_max, + (float)cache.total_bytes() / (1024 * 1024)); + + cache.clear(); + return generated; +} diff --git a/src/ar-sampler.h b/src/ar-sampler.h new file mode 100644 index 0000000..2c27ec1 --- /dev/null +++ b/src/ar-sampler.h @@ -0,0 +1,8 @@ +#pragma once + +#include "diffuse-common.h" +#include "diffuse.h" // ar_sampler_params, ar_token_callback +#include "ar-cache.h" + +// ar_generate is declared in diffuse.h (public API). +// This header is for internal use by ar-sampler.cpp. diff --git a/src/diffuse-model.cpp b/src/diffuse-model.cpp index e2a88d9..9bfaa56 100644 --- a/src/diffuse-model.cpp +++ b/src/diffuse-model.cpp @@ -19,6 +19,54 @@ static float get_f32(const struct gguf_context * gctx, const char * key, float d return gguf_get_val_f32(gctx, id); } +// ── Multi-arch key resolution ──────────────────────────────────── +// Try diffuse.*, then qwen2.*, then llama.* prefixes. +// This allows loading GGUF files produced by llama.cpp's converter. +static uint32_t get_u32_multi(const struct gguf_context * gctx, + const char * suffix, uint32_t def = 0) { + // Try prefixes in order of priority + static const char * prefixes[] = { "diffuse", "qwen2", "llama", nullptr }; + char buf[128]; + for (int i = 0; prefixes[i]; i++) { + snprintf(buf, sizeof(buf), "%s.%s", prefixes[i], suffix); + int64_t id = gguf_find_key(gctx, buf); + if (id >= 0) { + return gguf_get_val_u32(gctx, id); + } + } + if (def != 0) return def; + DIFFUSE_DIE("missing GGUF metadata key: *.%s (tried diffuse/qwen2/llama)", suffix); + return 0; // unreachable +} + +static float get_f32_multi(const struct gguf_context * gctx, + const char * suffix, float def) { + static const char * prefixes[] = { "diffuse", "qwen2", "llama", nullptr }; + char buf[128]; + for (int i = 0; prefixes[i]; i++) { + snprintf(buf, sizeof(buf), "%s.%s", prefixes[i], suffix); + int64_t id = gguf_find_key(gctx, buf); + if (id >= 0) { + return gguf_get_val_f32(gctx, id); + } + } + return def; +} + +// Detect the architecture prefix used in this GGUF file +static std::string detect_arch_prefix(const struct gguf_context * gctx) { + // Check general.architecture first (standard llama.cpp key) + int64_t id = gguf_find_key(gctx, "general.architecture"); + if (id >= 0) { + return gguf_get_val_str(gctx, id); + } + // Fallback: check which prefix has block_count + if (gguf_find_key(gctx, "diffuse.block_count") >= 0) return "diffuse"; + if (gguf_find_key(gctx, "qwen2.block_count") >= 0) return "qwen2"; + if (gguf_find_key(gctx, "llama.block_count") >= 0) return "llama"; + return "unknown"; +} + // ── Tensor lookup helper ─────────────────────────────────────── static struct ggml_tensor * get_tensor(struct ggml_context * ctx, const char * name) { struct ggml_tensor * t = ggml_get_tensor(ctx, name); @@ -43,40 +91,50 @@ diffuse_model * diffuse_model_load_impl(const std::string & path, int n_threads) DIFFUSE_DIE("failed to open GGUF file: %s", path.c_str()); } - // Parse hyperparameters (standard GGUF key names) + // Parse hyperparameters — supports diffuse.*, qwen2.*, llama.* prefixes auto * model = new diffuse_model(); auto & hp = model->hparams; - hp.n_layer = get_u32(gctx, "diffuse.block_count"); - hp.n_head = get_u32(gctx, "diffuse.attention.head_count"); - hp.n_head_kv = get_u32(gctx, "diffuse.attention.head_count_kv"); - hp.n_embd = get_u32(gctx, "diffuse.embedding_length"); - hp.n_ff = get_u32(gctx, "diffuse.feed_forward_length"); - hp.n_ctx_max = get_u32(gctx, "diffuse.context_length"); - hp.n_vocab = get_u32(gctx, "diffuse.vocab_size"); - hp.mask_token_id = get_u32(gctx, "diffuse.mask_token_id"); - hp.rope_theta = get_f32(gctx, "diffuse.rope.freq_base", 500000.0f); - hp.rms_norm_eps = get_f32(gctx, "diffuse.attention.layer_norm_rms_epsilon", 1e-5f); + // Detect architecture + std::string arch = detect_arch_prefix(gctx); + DIFFUSE_LOG(" detected arch prefix: %s", arch.c_str()); - // Read model type (llada, dream, etc.) + hp.n_layer = get_u32_multi(gctx, "block_count"); + hp.n_head = get_u32_multi(gctx, "attention.head_count"); + hp.n_head_kv = get_u32_multi(gctx, "attention.head_count_kv"); + hp.n_embd = get_u32_multi(gctx, "embedding_length"); + hp.n_ff = get_u32_multi(gctx, "feed_forward_length"); + hp.n_ctx_max = get_u32_multi(gctx, "context_length", 4096); + hp.n_vocab = get_u32_multi(gctx, "vocab_size"); + hp.mask_token_id = get_u32_multi(gctx, "mask_token_id", 0); // 0 = no mask token (AR models) + hp.rope_theta = get_f32_multi(gctx, "rope.freq_base", 500000.0f); + hp.rms_norm_eps = get_f32_multi(gctx, "attention.layer_norm_rms_epsilon", 1e-5f); + + // Read model type { int64_t id = gguf_find_key(gctx, "diffuse.model_type"); if (id >= 0) { model->model_type = gguf_get_val_str(gctx, id); + } else if (arch == "qwen2") { + model->model_type = "qwen2"; // autoregressive Qwen2.5 + } else if (arch == "llama") { + model->model_type = "llama"; // autoregressive Llama } else { - model->model_type = "llada"; // default for older GGUF files + model->model_type = "llada"; // default for older diffuse GGUF files } } const char * arch_name = "unknown"; - if (model->model_type == "llada") arch_name = "LLaDA (Llama backbone)"; - else if (model->model_type == "dream") arch_name = "Dream (Qwen2.5 backbone, GQA)"; + if (model->model_type == "llada") arch_name = "LLaDA (Llama backbone, diffusion)"; + else if (model->model_type == "dream") arch_name = "Dream (Qwen2.5 backbone, diffusion)"; + else if (model->model_type == "qwen2") arch_name = "Qwen2.5 (autoregressive)"; + else if (model->model_type == "llama") arch_name = "Llama (autoregressive)"; DIFFUSE_LOG(" arch: %s", arch_name); DIFFUSE_LOG(" n_vocab=%u, n_embd=%u, n_head=%u/%u(kv), n_layer=%u, n_ff=%u", hp.n_vocab, hp.n_embd, hp.n_head, hp.n_head_kv, hp.n_layer, hp.n_ff); - DIFFUSE_LOG(" mask_token_id=%u, rope_theta=%.0f, rms_norm_eps=%.1e", - hp.mask_token_id, hp.rope_theta, hp.rms_norm_eps); + DIFFUSE_LOG(" rope_theta=%.0f, rms_norm_eps=%.1e, mask_token=%u", + hp.rope_theta, hp.rms_norm_eps, hp.mask_token_id); // The weight context is the one that gguf_init populated model->ctx = meta_ctx; diff --git a/tools/ar-cli.cpp b/tools/ar-cli.cpp new file mode 100644 index 0000000..fdbad24 --- /dev/null +++ b/tools/ar-cli.cpp @@ -0,0 +1,161 @@ +#include "diffuse.h" + +#include +#include +#include +#include +#include + +static void print_usage(const char * prog) { + fprintf(stderr, "Usage: %s [options]\n", prog); + fprintf(stderr, "\ndiffuse-cpp autoregressive inference engine\n"); + fprintf(stderr, "\nOptions:\n"); + fprintf(stderr, " -m PATH Model file (GGUF, llama.cpp or diffuse-cpp format)\n"); + fprintf(stderr, " -p TEXT Prompt text (requires external tokenization)\n"); + fprintf(stderr, " -n INT Max tokens to generate (default: 256)\n"); + fprintf(stderr, " -t INT Threads (default: 4)\n"); + fprintf(stderr, " --temp F Temperature (default: 0 = greedy)\n"); + fprintf(stderr, " --top-p F Nucleus sampling threshold (default: 0.9)\n"); + fprintf(stderr, " --top-k INT Top-K sampling (default: 40, 0 = disabled)\n"); + fprintf(stderr, " --repeat-penalty F Repetition penalty (default: 1.1)\n"); + fprintf(stderr, " --repeat-last-n INT Repeat penalty window (default: 64)\n"); + fprintf(stderr, " --seed INT Random seed (default: 42)\n"); + fprintf(stderr, " --tokens IDs Comma-separated pre-tokenized input\n"); + fprintf(stderr, "\nExample:\n"); + fprintf(stderr, " %s -m thrombia-32b-q4.gguf --tokens 151644,8948,198,... -n 512 -t 12\n", prog); +} + +static std::vector parse_tokens(const char * str) { + std::vector tokens; + const char * p = str; + while (*p) { + tokens.push_back(atoi(p)); + while (*p && *p != ',') p++; + if (*p == ',') p++; + } + return tokens; +} + +int main(int argc, char ** argv) { + std::string model_path; + std::string prompt; + std::vector input_tokens; + int max_tokens = 256; + int n_threads = 4; + float temperature = 0.0f; + float top_p = 0.9f; + int top_k = 40; + float repeat_penalty = 1.1f; + int repeat_last_n = 64; + uint32_t seed = 42; + + for (int i = 1; i < argc; i++) { + if (strcmp(argv[i], "-m") == 0 && i + 1 < argc) { + model_path = argv[++i]; + } else if (strcmp(argv[i], "-p") == 0 && i + 1 < argc) { + prompt = argv[++i]; + } else if (strcmp(argv[i], "-n") == 0 && i + 1 < argc) { + max_tokens = atoi(argv[++i]); + } else if (strcmp(argv[i], "-t") == 0 && i + 1 < argc) { + n_threads = atoi(argv[++i]); + } else if (strcmp(argv[i], "--temp") == 0 && i + 1 < argc) { + temperature = atof(argv[++i]); + } else if (strcmp(argv[i], "--top-p") == 0 && i + 1 < argc) { + top_p = atof(argv[++i]); + } else if (strcmp(argv[i], "--top-k") == 0 && i + 1 < argc) { + top_k = atoi(argv[++i]); + } else if (strcmp(argv[i], "--repeat-penalty") == 0 && i + 1 < argc) { + repeat_penalty = atof(argv[++i]); + } else if (strcmp(argv[i], "--repeat-last-n") == 0 && i + 1 < argc) { + repeat_last_n = atoi(argv[++i]); + } else if (strcmp(argv[i], "--seed") == 0 && i + 1 < argc) { + 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], "-h") == 0 || strcmp(argv[i], "--help") == 0) { + print_usage(argv[0]); + return 0; + } else { + fprintf(stderr, "Unknown option: %s\n", argv[i]); + print_usage(argv[0]); + return 1; + } + } + + if (model_path.empty()) { + fprintf(stderr, "Error: model path required (-m)\n"); + print_usage(argv[0]); + return 1; + } + if (input_tokens.empty() && prompt.empty()) { + fprintf(stderr, "Error: prompt (-p) or tokens (--tokens) required\n"); + return 1; + } + + // Native tokenizer not integrated — use --tokens + if (input_tokens.empty()) { + fprintf(stderr, "Warning: native tokenizer not yet integrated. " + "Use --tokens with pre-tokenized input.\n"); + fprintf(stderr, "Example: python3 -c \"\n" + "from transformers import AutoTokenizer\n" + "t = AutoTokenizer.from_pretrained('Qwen/Qwen2.5-32B-Instruct')\n" + "ids = t.apply_chat_template([{'role':'user','content':'%s'}], " + "tokenize=True, add_generation_prompt=True)\n" + "print(','.join(map(str, ids)))\"\n", prompt.c_str()); + return 1; + } + + // Load model + fprintf(stderr, "Loading model...\n"); + diffuse_model * model = diffuse_model_load(model_path, n_threads); + if (!model) { + fprintf(stderr, "Failed to load model\n"); + return 1; + } + + const auto & hp = diffuse_model_hparams(model); + int n_ctx = (int)input_tokens.size() + max_tokens; + fprintf(stderr, "Prompt: %d tokens, max_generate: %d, ctx: %d\n", + (int)input_tokens.size(), max_tokens, n_ctx); + + diffuse_context * ctx = diffuse_context_new(model, n_ctx, n_threads); + + // Setup AR sampler params + ar_sampler_params sparams; + sparams.temperature = temperature; + sparams.top_p = top_p; + sparams.top_k = top_k; + sparams.repeat_penalty = repeat_penalty; + sparams.repeat_last_n = repeat_last_n; + sparams.seed = seed; + + // Generate with streaming output + fprintf(stderr, "Generating (greedy=%s, temp=%.2f, top_p=%.2f, top_k=%d)...\n", + temperature <= 0.0f ? "yes" : "no", temperature, top_p, top_k); + + auto result = ar_generate(ctx, input_tokens, max_tokens, sparams, + [](int32_t token, int pos) -> bool { + // Streaming: print token IDs as they come + // (decode externally with tokenizer) + fprintf(stderr, "\r generating... %d tokens", pos); + return true; // continue + }); + + fprintf(stderr, "\n\nGenerated %d token IDs:\n", (int)result.size()); + for (size_t i = 0; i < result.size(); i++) { + if (i > 0) printf(","); + printf("%d", result[i]); + } + printf("\n"); + + fprintf(stderr, "\nDecode with:\n" + " python3 -c \"from transformers import AutoTokenizer; " + "t=AutoTokenizer.from_pretrained('Qwen/Qwen2.5-32B-Instruct'); " + "print(t.decode([...]))\"\n"); + + // Cleanup + diffuse_context_free(ctx); + diffuse_model_free(model); + + return 0; +}