Brunobkr commited on
Commit
a7caa93
·
verified ·
1 Parent(s): 653ecac

Upload 2 files

Browse files

diffusion-gemma-http.cpp

Files changed (2) hide show
  1. README.md +144 -0
  2. diffusion-gemma-http.cpp +541 -0
README.md ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: mit
3
+ language:
4
+ - en
5
+ - pt
6
+ tags:
7
+ - llama.cpp
8
+ - gguf
9
+ - text-diffusion
10
+ - block-diffusion
11
+ - diffusion-language-model
12
+ - gemma
13
+ - openai-api
14
+ - server
15
+ - cpu-inference
16
+ - offline
17
+ pipeline_tag: text-generation
18
+ ---
19
+
20
+ <img src="https://huggingface.co/Brunobkr/REPO_NAME/resolve/main/capa.png" alt="ΩFFΣLLIα diffusion-gemma-http" width="100%"/>
21
+
22
+ # ΩFFΣLLIα — diffusion-gemma-http
23
+
24
+ **A native, single-file, OpenAI-compatible HTTP server for DiffusionGemma block text-diffusion models (GGUF / llama.cpp).**
25
+
26
+ `diffusion-gemma-http.cpp` makes a block text-diffusion model behave like a regular `llama-server`: load the GGUF once, listen on a port, answer `/v1/chat/completions`. Everything — tokenization, chat template, the block-diffusion denoising loop, and the HTTP API — runs in a single C++ process on top of the llama.cpp diffusion fork. No Python, no external tokenizer files, no per-step IPC.
27
+
28
+ Validated end-to-end on **CPU-only consumer hardware** (AMD Ryzen 5 5625U, 8 GB shared UMA, Kali Linux), serving a **DiffusionGemma 26B-A4B MoE (NVFP4 GGUF)** to a local chat UI over `:8080`.
29
+
30
+ ---
31
+
32
+ ## Why this exists
33
+
34
+ Diffusion language models cannot be served by the standard `llama-server`: generation is not autoregressive token-by-token decoding, but iterative **denoising of a fixed-length canvas** (`[prompt | canvas]` bidirectional forwards, region-aware masks, self-conditioning). Until now the options were a raw logits server driven by an external Python loop, or a one-shot CLI. This tool closes the gap: a persistent HTTP server speaking the OpenAI Chat Completions protocol, with the entire diffusion decode loop in-process.
35
+
36
+ ## Features
37
+
38
+ - **OpenAI-compatible API**: `POST /v1/chat/completions` (streaming via SSE and non-streaming), `GET /v1/models`, `GET /health`, `GET /`
39
+ - **Native tokenization** from the GGUF vocabulary (control tokens parsed atomically; no tokenizer.json needed)
40
+ - **Model chat template built in**: `<|turn>role\n … <turn|>` turns with `<|channel>thought … <channel|>` reasoning channels; thinking can be disabled per request (`"enable_thinking": false`, the default) by pre-filling an empty thought channel, or enabled globally with `--thinking`
41
+ - **Entropy-bound block-diffusion sampler** (see below), with all parameters read from GGUF metadata
42
+ - **Prompt-KV caching** (`DG_KVCACHE=1` / `--kvcache`): the prompt is prefilled once per block; each denoising step forwards only the canvas
43
+ - **Self-conditioning** across denoising steps (previous-step logits fed back from step 2 onward)
44
+ - **Multi-block generation**: when a block fills without an end-of-turn, it is appended to the prompt and a new canvas is denoised, until `max_tokens` or end of content
45
+ - **Streaming per block** with correct `finish_reason` (`stop` vs `length`)
46
+ - Memory-conscious: per-position statistics are computed in streaming passes over the logits — the probability matrix (`canvas × 262k vocab`) is never materialized
47
+
48
+ ## Requirements
49
+
50
+ 1. A **llama.cpp fork with the `diffusion-gemma` architecture** (the `DIFFUSION_GEMMA` model class providing `llama_diffusion_set_phase` / `llama_diffusion_set_sc`).
51
+ 2. A **DiffusionGemma GGUF** carrying the diffusion metadata:
52
+
53
+ | GGUF key | Meaning |
54
+ |---|---|
55
+ | `diffusion.canvas_length` | Canvas size per block (required; the C++ graph splits `[prompt \| canvas]` on it) |
56
+ | `diffusion.eb_max_steps` | Max denoising steps per block |
57
+ | `diffusion.eb_t_min` / `diffusion.eb_t_max` | Temperature schedule (linear, `t_max → t_min`) |
58
+ | `diffusion.eb_entropy_bound` | Per-position entropy bound for locking |
59
+ | `diffusion.eb_stability_threshold` | Consecutive stable-argmax steps required to lock |
60
+ | `diffusion.eb_confidence_threshold` | Reference-decoder parameter (read, reported, not used by this sampler — see Limitations) |
61
+
62
+ 3. The vendored headers already shipped with the llama.cpp tree: `vendor/cpp-httplib/httplib.h` (+ `httplib.cpp`) and `vendor/nlohmann/json.hpp`.
63
+
64
+ ## Build
65
+
66
+ Place the file at `tools/diffusion-gemma-http/diffusion-gemma-http.cpp` inside the fork, then:
67
+
68
+ ```cmake
69
+ # tools/diffusion-gemma-http/CMakeLists.txt
70
+ set(TARGET llama-diffusion-gemma-http)
71
+ add_executable(${TARGET}
72
+ diffusion-gemma-http.cpp
73
+ ${CMAKE_SOURCE_DIR}/vendor/cpp-httplib/httplib.cpp)
74
+ target_include_directories(${TARGET} PRIVATE
75
+ ${CMAKE_SOURCE_DIR}/vendor/cpp-httplib
76
+ ${CMAKE_SOURCE_DIR}/vendor)
77
+ target_link_libraries(${TARGET} PRIVATE llama Threads::Threads)
78
+ target_compile_features(${TARGET} PRIVATE cxx_std_17)
79
+ install(TARGETS ${TARGET} RUNTIME)
80
+ ```
81
+
82
+ ```bash
83
+ echo 'add_subdirectory(diffusion-gemma-http)' >> tools/CMakeLists.txt
84
+ cmake -B build
85
+ cmake --build build --target llama-diffusion-gemma-http -j4
86
+ ```
87
+
88
+ ## Usage
89
+
90
+ ```bash
91
+ DG_KVCACHE=1 ./build/bin/llama-diffusion-gemma-http \
92
+ -m model.gguf --port 8080 [--host 0.0.0.0] [-ngl N] [-c MAXTOK] [--thinking]
93
+ ```
94
+
95
+ | Flag / env | Default | Description |
96
+ |---|---|---|
97
+ | `-m, --model` | — | GGUF path (positional also accepted) |
98
+ | `--port` / `--host` | `8080` / `0.0.0.0` | Bind address |
99
+ | `-c, --ctx` / `MAXTOK` | `2304` | Context budget = prompt + accumulated blocks. Non-causal forwards require the whole sequence in one ubatch, so the compute buffer scales with this — raise gradually on small-RAM machines |
100
+ | `-ngl` / `NGL` | `0` | GPU layers |
101
+ | `--kvcache` / `DG_KVCACHE=1` | off | Prompt-KV caching (strongly recommended on CPU) |
102
+ | `--thinking` / `DG_THINKING=1` | off | Enable the reasoning channel by default |
103
+ | `DG_MASK_ID` | auto (`<mask>`) | Override the canvas mask token id |
104
+ | `FA=1` | off | Flash attention |
105
+
106
+ ### API
107
+
108
+ ```bash
109
+ curl -s http://127.0.0.1:8080/v1/chat/completions -H 'Content-Type: application/json' -d '{
110
+ "messages": [{"role": "user", "content": "Explique em duas frases o que é um número primo."}],
111
+ "max_tokens": 200,
112
+ "stream": false
113
+ }'
114
+ ```
115
+
116
+ Any OpenAI-compatible client or front-end pointed at `http://host:8080` works unchanged. Per-request fields: `messages` (system merged into the first user turn), `max_tokens` / `max_completion_tokens`, `stream`, `enable_thinking`.
117
+
118
+ ## The sampler
119
+
120
+ The decode loop implements an **entropy-bound block-diffusion sampler**:
121
+
122
+ 1. The canvas starts fully masked. Each step runs one bidirectional forward and computes, per position, the best **real** token (mask excluded), its confidence, and the entropy of the mask-excluded distribution — in streaming passes, without materializing probabilities.
123
+ 2. A position **locks** when its argmax has been stable for `stability_threshold` consecutive steps **and** its entropy is below `entropy_bound`.
124
+ 3. A prediction of `<mask>` never locks: it means "not ready yet / end of content". Positions still masked when the model proposes nothing new for 2 consecutive steps signal **end of content** (the model's native length control).
125
+ 4. Minimum progress per step is guaranteed by confidence ranking; **adjacent positions never lock in the same step**, and an **anti-echo guard** defers locking a token identical to an already-locked neighbor (legitimate repetition persists and passes; denoising echoes dissolve).
126
+ 5. Temperature follows a linear `t_max → t_min` schedule; self-conditioning on the previous step's logits is active from step 2.
127
+
128
+ ### Honest limitations
129
+
130
+ - This sampler is a **validated approximation**, not a byte-exact port of the reference entropy-bound decoder: in particular, `diffusion.eb_confidence_threshold` is read and reported but plays no role in the locking rule, whose reference semantics differ from a naive confidence cutoff. Residual artifacts of parallel unmasking (rare token echoes) are mitigated by the guards above but not formally eliminated.
131
+ - Single-flight inference: concurrent requests are serialized by a mutex.
132
+ - Diffusion on CPU is compute-heavy: every denoising step is a dense forward over the canvas (plus the prompt without KV caching). Expect minutes, not seconds, for long answers on laptop-class CPUs.
133
+
134
+ ## Provenance
135
+
136
+ Developed iteratively against a live DiffusionGemma 26B-A4B (MoE, 30 layers, 262k vocab, canvas 256, Harmony-style `<|turn>`/`<|channel>` template) quantized to NVFP4 GGUF, debugged end-to-end from raw logits to a working chat UI. Part of the **ΩFFΣLLIα** local-first, zero-telemetry tooling line.
137
+
138
+ - Author: **Bruno Becker** — [huggingface.co/Brunobkr](https://huggingface.co/Brunobkr)
139
+ - Research: [doi.org/10.5281/zenodo.20026837](https://doi.org/10.5281/zenodo.20026837)
140
+ - Built on [llama.cpp](https://github.com/ggml-org/llama.cpp) (MIT) with a diffusion-gemma architecture fork; HTTP via [cpp-httplib](https://github.com/yhirose/cpp-httplib), JSON via [nlohmann/json](https://github.com/nlohmann/json).
141
+
142
+ ## License
143
+
144
+ MIT, following the llama.cpp ecosystem it extends.
diffusion-gemma-http.cpp ADDED
@@ -0,0 +1,541 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // diffusion-gemma-http.cpp — servidor HTTP OpenAI-compativel nativo para DiffusionGemma.
2
+ // Substitui a ponte Python: tokenizacao (vocab do GGUF), template <|turn>/<|channel>,
3
+ // loop block-diffusion entropy-bound e API /v1/chat/completions, tudo em C++ no mesmo processo.
4
+ //
5
+ // Endpoints: GET /health, GET /v1/models, POST /v1/chat/completions (stream e nao-stream).
6
+ //
7
+ // Uso:
8
+ // llama-diffusion-gemma-http -m model.gguf [--port 8080] [--host 0.0.0.0] [-ngl N] [-c MAXTOK]
9
+ // env: DG_KVCACHE=1 (prompt-KV cache), DG_THINKING=1, DG_MASK_ID, MAXTOK, NGL, FA
10
+ //
11
+ // Sampler (mesma semantica validada na ponte dg-bridge.py):
12
+ // - predicao de <mask> nunca trava (posicao fica aberta); mask remanescente = fim de conteudo
13
+ // - trava: argmax estavel >= stability E entropia (dist. sem mask) <= entropy_bound
14
+ // - progresso minimo por confianca; sem travar posicoes adjacentes no mesmo passo
15
+ // - schedule t_max -> t_min em max_steps; self-conditioning a partir do passo 2
16
+ // - parametros lidos dos metadados do GGUF (diffusion.canvas_length, diffusion.eb_*)
17
+
18
+ #include "llama.h"
19
+ #include "httplib.h"
20
+ #include <nlohmann/json.hpp>
21
+
22
+ #include <algorithm>
23
+ #include <cmath>
24
+ #include <cstdio>
25
+ #include <cstdlib>
26
+ #include <cstring>
27
+ #include <functional>
28
+ #include <mutex>
29
+ #include <string>
30
+ #include <vector>
31
+
32
+ using json = nlohmann::json;
33
+
34
+ // ------------------------------------------------------------------ estado global
35
+ struct EBParams {
36
+ int max_steps = 48;
37
+ float t_min = 0.4f;
38
+ float t_max = 0.8f;
39
+ float entropy_bound = 0.1f;
40
+ int stability = 1;
41
+ float confidence = 0.005f; // lido do GGUF; semantica do decoder de referencia (nao usado no lock)
42
+ };
43
+
44
+ struct DG {
45
+ llama_model * model = nullptr;
46
+ llama_context * ctx = nullptr;
47
+ const llama_vocab * vocab = nullptr;
48
+ llama_batch batch{};
49
+ std::string model_name;
50
+
51
+ int n_vocab = 0;
52
+ int maxtok = 2304;
53
+ int canvas = 0;
54
+ bool kvcache = false;
55
+ bool thinking_default = false;
56
+ EBParams eb;
57
+
58
+ llama_token id_mask = -1, id_turn_close = -1, id_channel_close = -1, id_eos = -1, id_bos = -1;
59
+
60
+ // estado do forward (single-flight; protegido por mtx)
61
+ std::vector<float> sc_cache; // logits do passo anterior (self-conditioning)
62
+ float prev_temp = 1.0f;
63
+ std::vector<llama_token> cur_prompt; // prompt atualmente no K,V store (DG_KVCACHE)
64
+ std::vector<float> logits; // scratch [C, n_vocab] do passo corrente
65
+
66
+ std::mutex mtx;
67
+ };
68
+ static DG G;
69
+
70
+ // ------------------------------------------------------------------ helpers
71
+ static bool meta_str(const char * key, std::string & out) {
72
+ char buf[512];
73
+ const int n = llama_model_meta_val_str(G.model, key, buf, sizeof(buf));
74
+ if (n < 0) return false;
75
+ out.assign(buf);
76
+ return true;
77
+ }
78
+ static bool meta_f(const char * key, float & v) { std::string s; if (!meta_str(key, s)) return false; v = strtof(s.c_str(), nullptr); return true; }
79
+ static bool meta_i(const char * key, int & v) { std::string s; if (!meta_str(key, s)) return false; v = (int) strtol(s.c_str(), nullptr, 10); return true; }
80
+
81
+ static std::vector<llama_token> tokenize(const std::string & text, bool parse_special) {
82
+ int n = -llama_tokenize(G.vocab, text.c_str(), (int) text.size(), nullptr, 0, false, parse_special);
83
+ std::vector<llama_token> ids(std::max(n, 0));
84
+ if (n > 0) {
85
+ llama_tokenize(G.vocab, text.c_str(), (int) text.size(), ids.data(), n, false, parse_special);
86
+ }
87
+ return ids;
88
+ }
89
+
90
+ static std::string detok(const std::vector<llama_token> & ids, bool remove_special) {
91
+ if (ids.empty()) return "";
92
+ std::string out(ids.size() * 8 + 32, '\0');
93
+ int n = llama_detokenize(G.vocab, ids.data(), (int) ids.size(), out.data(), (int) out.size(),
94
+ remove_special, /*unparse_special=*/false);
95
+ if (n < 0) {
96
+ out.resize(-n);
97
+ n = llama_detokenize(G.vocab, ids.data(), (int) ids.size(), out.data(), (int) out.size(),
98
+ remove_special, false);
99
+ }
100
+ out.resize(std::max(n, 0));
101
+ return out;
102
+ }
103
+
104
+ static llama_token token_id(const char * s) {
105
+ auto ids = tokenize(s, /*parse_special=*/true);
106
+ return ids.size() == 1 ? ids[0] : -1;
107
+ }
108
+
109
+ static std::string trim(std::string s) {
110
+ const char * ws = " \t\r\n";
111
+ const auto a = s.find_first_not_of(ws);
112
+ if (a == std::string::npos) return "";
113
+ const auto b = s.find_last_not_of(ws);
114
+ return s.substr(a, b - a + 1);
115
+ }
116
+
117
+ // ------------------------------------------------------------------ forward [prompt | canvas]
118
+ // Preenche G.logits [C, n_vocab] e atualiza o cache de self-conditioning. UNIFIED por padrao;
119
+ // com DG_KVCACHE=1, PREFILL do prompt uma vez por bloco e DECODE so do canvas por passo.
120
+ static bool dg_forward(const std::vector<llama_token> & prompt,
121
+ const std::vector<llama_token> & canvas, bool use_sc, float temp) {
122
+ const int P = (int) prompt.size();
123
+ const int C = (int) canvas.size();
124
+ const int N = P + C;
125
+ if (N <= 0 || N > G.maxtok) return false;
126
+
127
+ if ((int) G.sc_cache.size() != C * G.n_vocab) G.sc_cache.assign((size_t) C * G.n_vocab, 0.0f);
128
+ if ((int) G.logits.size() != C * G.n_vocab) G.logits.assign((size_t) C * G.n_vocab, 0.0f);
129
+
130
+ int row_base = P;
131
+ const bool use_kv = G.kvcache && P > 0;
132
+
133
+ if (!use_kv) {
134
+ llama_diffusion_set_phase(G.model, /*PKV_UNIFIED=*/0, 0);
135
+ G.batch.n_tokens = N;
136
+ for (int i = 0; i < N; ++i) {
137
+ G.batch.token[i] = (i < P) ? prompt[i] : canvas[i - P];
138
+ G.batch.pos[i] = i;
139
+ G.batch.n_seq_id[i] = 1;
140
+ G.batch.seq_id[i][0] = 0;
141
+ G.batch.logits[i] = (i >= P);
142
+ }
143
+ llama_diffusion_set_sc(G.model, G.sc_cache.data(), use_sc ? 1.0f : 0.0f,
144
+ use_sc ? 1.0f / G.prev_temp : 1.0f, true);
145
+ if (llama_decode(G.ctx, G.batch) != 0) return false;
146
+ row_base = P;
147
+ } else {
148
+ bool new_block = ((int) G.cur_prompt.size() != P);
149
+ for (int i = 0; !new_block && i < P; ++i) new_block = (G.cur_prompt[i] != prompt[i]);
150
+ if (new_block) {
151
+ llama_diffusion_set_phase(G.model, /*PKV_PREFILL=*/1, P);
152
+ llama_diffusion_set_sc(G.model, G.sc_cache.data(), 0.0f, 1.0f, false);
153
+ G.batch.n_tokens = P;
154
+ for (int i = 0; i < P; ++i) {
155
+ G.batch.token[i] = prompt[i];
156
+ G.batch.pos[i] = i;
157
+ G.batch.n_seq_id[i] = 1;
158
+ G.batch.seq_id[i][0] = 0;
159
+ G.batch.logits[i] = (i == P - 1);
160
+ }
161
+ if (llama_decode(G.ctx, G.batch) != 0) { G.cur_prompt.clear(); return false; }
162
+ G.cur_prompt = prompt;
163
+ }
164
+ llama_diffusion_set_phase(G.model, /*PKV_DECODE=*/2, P);
165
+ llama_diffusion_set_sc(G.model, G.sc_cache.data(), use_sc ? 1.0f : 0.0f,
166
+ use_sc ? 1.0f / G.prev_temp : 1.0f, true);
167
+ G.batch.n_tokens = C;
168
+ for (int i = 0; i < C; ++i) {
169
+ G.batch.token[i] = canvas[i];
170
+ G.batch.pos[i] = P + i;
171
+ G.batch.n_seq_id[i] = 1;
172
+ G.batch.seq_id[i][0] = 0;
173
+ G.batch.logits[i] = 1;
174
+ }
175
+ if (llama_decode(G.ctx, G.batch) != 0) return false;
176
+ row_base = 0;
177
+ }
178
+
179
+ for (int j = 0; j < C; ++j) {
180
+ const float * row = llama_get_logits_ith(G.ctx, row_base + j);
181
+ if (!row) return false;
182
+ memcpy(&G.logits[(size_t) j * G.n_vocab], row, (size_t) G.n_vocab * sizeof(float));
183
+ memcpy(&G.sc_cache[(size_t) j * G.n_vocab], row, (size_t) G.n_vocab * sizeof(float));
184
+ }
185
+ G.prev_temp = temp;
186
+ return true;
187
+ }
188
+
189
+ // ------------------------------------------------------------------ denoise de um bloco
190
+ static std::vector<llama_token> denoise_block(const std::vector<llama_token> & prompt) {
191
+ const int C = G.canvas;
192
+ const int V = G.n_vocab;
193
+ std::vector<llama_token> canvas(C, G.id_mask);
194
+ std::vector<uint8_t> masked(C, 1);
195
+ std::vector<int> stable(C, 0);
196
+ std::vector<llama_token> last(C, -1);
197
+ std::vector<llama_token> arg(C);
198
+ std::vector<float> conf(C), ent(C);
199
+ std::vector<uint8_t> pm(C); // prefers_mask
200
+ int mask_stall = 0;
201
+ const int steps = G.eb.max_steps;
202
+
203
+ for (int step = 0; step < steps; ++step) {
204
+ const float t = G.eb.t_max + (G.eb.t_min - G.eb.t_max) * (float) step / (float) std::max(1, steps - 1);
205
+ if (!dg_forward(prompt, canvas, step > 0, t)) break;
206
+ const float s = 1.0f / std::max(t, 1e-4f);
207
+
208
+ // estatisticas por posicao em duas passadas, sem materializar a matriz de probs
209
+ for (int j = 0; j < C; ++j) {
210
+ const float * l = &G.logits[(size_t) j * V];
211
+ float m = -INFINITY; int amax = -1;
212
+ for (int v = 0; v < V; ++v) { const float x = s * l[v]; if (x > m) { m = x; amax = v; } }
213
+ double Z = 0.0, S1 = 0.0, zm = 0.0, s1m = 0.0;
214
+ float bx = -INFINITY; int bi = -1;
215
+ for (int v = 0; v < V; ++v) {
216
+ const float x = s * l[v] - m;
217
+ const double e = exp((double) x);
218
+ Z += e; S1 += (double) x * e;
219
+ if (v == G.id_mask) { zm = e; s1m = (double) x * e; }
220
+ else if (x > bx) { bx = x; bi = v; }
221
+ }
222
+ const double Zx = std::max(Z - zm, 1e-300);
223
+ const double S1x = S1 - s1m;
224
+ pm[j] = (amax == G.id_mask); // "deixa para depois / fim de conteudo"
225
+ arg[j] = bi; // melhor token real (mask excluido)
226
+ conf[j] = (float) (exp((double) bx) / Zx);
227
+ ent[j] = (float) (log(Zx) - S1x / Zx);
228
+ }
229
+
230
+ for (int j = 0; j < C; ++j) {
231
+ stable[j] = (arg[j] == last[j]) ? stable[j] + 1 : 0;
232
+ last[j] = arg[j];
233
+ }
234
+
235
+ bool any_locked = false;
236
+ for (int j = 0; j < C; ++j) if (!masked[j]) { any_locked = true; break; }
237
+ std::vector<int> cand;
238
+ for (int j = 0; j < C; ++j) if (masked[j] && !pm[j]) cand.push_back(j);
239
+ if (cand.empty()) {
240
+ if (!any_locked) {
241
+ for (int j = 0; j < C; ++j) if (masked[j]) cand.push_back(j); // passo frio: forca o inicio
242
+ } else {
243
+ if (++mask_stall >= 2) break; // persistiu por 2 passos com conteudo: fim
244
+ continue; // mais um passo; contexto novo pode destravar
245
+ }
246
+ } else {
247
+ mask_stall = 0;
248
+ }
249
+
250
+ std::vector<uint8_t> lock(C, 0);
251
+ int nlock = 0;
252
+ for (int j : cand) {
253
+ if (ent[j] <= G.eb.entropy_bound && stable[j] >= G.eb.stability) { lock[j] = 1; ++nlock; }
254
+ }
255
+ const int need = (int) std::ceil((double) cand.size() / (double) std::max(1, steps - step));
256
+ if (nlock < need) {
257
+ std::vector<int> byconf = cand;
258
+ std::sort(byconf.begin(), byconf.end(), [&](int a, int b) { return conf[a] > conf[b]; });
259
+ for (int j : byconf) {
260
+ if (nlock >= need) break;
261
+ if (!lock[j]) { lock[j] = 1; ++nlock; }
262
+ }
263
+ }
264
+ // nao trava adjacentes no mesmo passo (evita duplicacao); mantem as de maior confianca
265
+ if (nlock > 1) {
266
+ std::vector<int> locked;
267
+ for (int j = 0; j < C; ++j) if (lock[j]) locked.push_back(j);
268
+ std::sort(locked.begin(), locked.end(), [&](int a, int b) { return conf[a] > conf[b]; });
269
+ std::vector<uint8_t> keep(C, 0);
270
+ for (int j : locked) {
271
+ if ((j > 0 && keep[j - 1]) || (j + 1 < C && keep[j + 1])) continue;
272
+ keep[j] = 1;
273
+ }
274
+ lock.swap(keep);
275
+ }
276
+
277
+ bool all_done = true;
278
+ for (int j = 0; j < C; ++j) {
279
+ if (lock[j]) { canvas[j] = arg[j]; masked[j] = 0; }
280
+ else if (masked[j]) canvas[j] = G.id_mask;
281
+ if (masked[j]) all_done = false;
282
+ }
283
+ if (all_done) break;
284
+ }
285
+ return canvas; // posicoes ainda em mask = fim de conteudo
286
+ }
287
+
288
+ // ------------------------------------------------------------------ geracao multi-bloco
289
+ struct GenResult { std::vector<llama_token> ids; bool stopped = false; };
290
+
291
+ static GenResult dg_generate(std::vector<llama_token> cur, int max_new,
292
+ const std::function<void(const std::vector<llama_token> &, bool)> & on_block) {
293
+ GenResult r;
294
+ int produced = 0;
295
+ while (produced < max_new) {
296
+ if ((int) cur.size() + G.canvas > G.maxtok) { r.stopped = true; break; }
297
+ auto block = denoise_block(cur);
298
+ int cut = -1;
299
+ for (int i = 0; i < (int) block.size(); ++i) {
300
+ const llama_token t = block[i];
301
+ if (t == G.id_turn_close || t == G.id_eos || t == G.id_mask) { cut = i; break; }
302
+ }
303
+ if (cut >= 0) {
304
+ r.ids.insert(r.ids.end(), block.begin(), block.begin() + cut);
305
+ r.stopped = true;
306
+ on_block(r.ids, true);
307
+ break;
308
+ }
309
+ const int keep = std::min((int) block.size(), max_new - produced);
310
+ r.ids.insert(r.ids.end(), block.begin(), block.begin() + keep);
311
+ produced += keep;
312
+ cur.insert(cur.end(), block.begin(), block.end());
313
+ on_block(r.ids, produced >= max_new);
314
+ }
315
+ return r;
316
+ }
317
+
318
+ // resposta final = ids depois do ultimo <channel|>, cortados no primeiro stop; specials removidos no detok
319
+ static std::string extract_text(const std::vector<llama_token> & ids) {
320
+ size_t start = 0;
321
+ for (size_t i = 0; i < ids.size(); ++i) if (ids[i] == G.id_channel_close) start = i + 1;
322
+ std::vector<llama_token> body;
323
+ for (size_t i = start; i < ids.size(); ++i) {
324
+ const llama_token t = ids[i];
325
+ if (t == G.id_turn_close || t == G.id_eos || t == G.id_mask) break;
326
+ body.push_back(t);
327
+ }
328
+ return trim(detok(body, /*remove_special=*/true));
329
+ }
330
+
331
+ // ------------------------------------------------------------------ template de chat
332
+ static std::string build_prompt(const json & messages, bool thinking) {
333
+ std::string out, sysbuf;
334
+ for (const auto & m : messages) {
335
+ const std::string role = m.value("role", "user");
336
+ std::string content;
337
+ if (m.contains("content")) {
338
+ if (m["content"].is_string()) content = m["content"].get<std::string>();
339
+ else if (m["content"].is_array()) {
340
+ for (const auto & p : m["content"]) {
341
+ if (p.value("type", "") == "text") content += p.value("text", "");
342
+ }
343
+ }
344
+ }
345
+ if (role == "system") {
346
+ if (!sysbuf.empty()) sysbuf += "\n";
347
+ sysbuf += content;
348
+ continue;
349
+ }
350
+ const std::string r = (role == "assistant") ? "model" : "user";
351
+ if (!sysbuf.empty() && r == "user") { content = sysbuf + "\n\n" + content; sysbuf.clear(); }
352
+ out += "<|turn>" + r + "\n" + trim(content) + "<turn|>\n";
353
+ }
354
+ out += "<|turn>model\n";
355
+ if (!thinking) out += "<|channel>thought\n<channel|>"; // enable_thinking=false do chat_template
356
+ return out;
357
+ }
358
+
359
+ static std::vector<llama_token> prompt_ids_for(const json & messages, bool thinking) {
360
+ auto ids = tokenize(build_prompt(messages, thinking), /*parse_special=*/true);
361
+ ids.insert(ids.begin(), G.id_bos);
362
+ if ((int) ids.size() + G.canvas > G.maxtok) { // mantem o fim do prompt (trim pela esquerda)
363
+ ids.erase(ids.begin(), ids.end() - (G.maxtok - G.canvas));
364
+ }
365
+ return ids;
366
+ }
367
+
368
+ // ------------------------------------------------------------------ HTTP
369
+ static json chunk_json(const std::string & rid, long created, const json & delta, const json & finish) {
370
+ return json{{"id", rid}, {"object", "chat.completion.chunk"}, {"created", created},
371
+ {"model", G.model_name},
372
+ {"choices", json::array({json{{"index", 0}, {"delta", delta}, {"finish_reason", finish}}})}};
373
+ }
374
+
375
+ int main(int argc, char ** argv) {
376
+ std::string model_path, host = "0.0.0.0";
377
+ int port = 8080;
378
+ int ngl = atoi(getenv("NGL") ? getenv("NGL") : "0");
379
+ G.maxtok = atoi(getenv("MAXTOK") ? getenv("MAXTOK") : "2304");
380
+ G.kvcache = getenv("DG_KVCACHE") && atoi(getenv("DG_KVCACHE"));
381
+ G.thinking_default = getenv("DG_THINKING") && atoi(getenv("DG_THINKING"));
382
+
383
+ for (int i = 1; i < argc; ++i) {
384
+ const std::string a = argv[i];
385
+ if ((a == "-m" || a == "--model") && i + 1 < argc) model_path = argv[++i];
386
+ else if (a == "--port" && i + 1 < argc) port = atoi(argv[++i]);
387
+ else if (a == "--host" && i + 1 < argc) host = argv[++i];
388
+ else if ((a == "-ngl" || a == "--gpu-layers") && i + 1 < argc) ngl = atoi(argv[++i]);
389
+ else if ((a == "-c" || a == "--ctx") && i + 1 < argc) G.maxtok = atoi(argv[++i]);
390
+ else if (a == "--kvcache") G.kvcache = true;
391
+ else if (a == "--thinking") G.thinking_default = true;
392
+ else if (a[0] != '-' && model_path.empty()) model_path = a; // posicional
393
+ }
394
+ if (model_path.empty()) {
395
+ fprintf(stderr, "usage: %s -m <model.gguf> [--port 8080] [--host 0.0.0.0] [-ngl N] [-c MAXTOK] [--kvcache] [--thinking]\n", argv[0]);
396
+ return 1;
397
+ }
398
+
399
+ llama_backend_init();
400
+ llama_model_params mparams = llama_model_default_params();
401
+ mparams.n_gpu_layers = ngl;
402
+ G.model = llama_model_load_from_file(model_path.c_str(), mparams);
403
+ if (!G.model) { fprintf(stderr, "failed to load model\n"); return 1; }
404
+ G.vocab = llama_model_get_vocab(G.model);
405
+ G.n_vocab = llama_vocab_n_tokens(G.vocab);
406
+ { const auto p = model_path.find_last_of("/\\");
407
+ G.model_name = model_path.substr(p == std::string::npos ? 0 : p + 1);
408
+ const auto d = G.model_name.rfind(".gguf");
409
+ if (d != std::string::npos) G.model_name.resize(d); }
410
+
411
+ // metadados de diffusion
412
+ if (!meta_i("diffusion.canvas_length", G.canvas) || G.canvas <= 0) {
413
+ fprintf(stderr, "GGUF sem diffusion.canvas_length valido\n"); return 1;
414
+ }
415
+ meta_i("diffusion.eb_max_steps", G.eb.max_steps);
416
+ meta_f("diffusion.eb_t_min", G.eb.t_min);
417
+ meta_f("diffusion.eb_t_max", G.eb.t_max);
418
+ meta_f("diffusion.eb_entropy_bound", G.eb.entropy_bound);
419
+ meta_i("diffusion.eb_stability_threshold", G.eb.stability);
420
+ meta_f("diffusion.eb_confidence_threshold", G.eb.confidence);
421
+
422
+ llama_context_params cparams = llama_context_default_params();
423
+ cparams.n_ctx = G.maxtok;
424
+ cparams.n_batch = G.maxtok;
425
+ cparams.n_ubatch = G.maxtok; // non-causal: sequencia inteira em um ubatch
426
+ cparams.no_perf = true;
427
+ cparams.flash_attn_type = getenv("FA") && atoi(getenv("FA"))
428
+ ? LLAMA_FLASH_ATTN_TYPE_ENABLED : LLAMA_FLASH_ATTN_TYPE_DISABLED;
429
+ G.ctx = llama_init_from_model(G.model, cparams);
430
+ if (!G.ctx) { fprintf(stderr, "failed to create context\n"); return 1; }
431
+ llama_set_causal_attn(G.ctx, false);
432
+ G.batch = llama_batch_init(G.maxtok, 0, 1);
433
+
434
+ // ids de controle
435
+ G.id_bos = llama_vocab_bos(G.vocab);
436
+ G.id_eos = llama_vocab_eos(G.vocab);
437
+ G.id_turn_close = token_id("<turn|>");
438
+ G.id_channel_close = token_id("<channel|>");
439
+ G.id_mask = getenv("DG_MASK_ID") ? atoi(getenv("DG_MASK_ID")) : token_id("<mask>");
440
+ if (G.id_mask < 0 || G.id_turn_close < 0) {
441
+ fprintf(stderr, "tokens de controle ausentes: mask=%d turn_close=%d (defina DG_MASK_ID se preciso)\n",
442
+ G.id_mask, G.id_turn_close);
443
+ return 1;
444
+ }
445
+
446
+ fprintf(stderr, "diffusion-gemma-http: n_vocab=%d canvas=%d maxtok=%d kvcache=%d "
447
+ "eb{steps=%d t=[%.2f,%.2f] ent=%.3f stab=%d conf=%.4f} mask=%d turn|=%d channel|=%d\n",
448
+ G.n_vocab, G.canvas, G.maxtok, (int) G.kvcache,
449
+ G.eb.max_steps, G.eb.t_min, G.eb.t_max, G.eb.entropy_bound, G.eb.stability, G.eb.confidence,
450
+ G.id_mask, G.id_turn_close, G.id_channel_close);
451
+
452
+ httplib::Server svr;
453
+
454
+ svr.Get("/", [](const httplib::Request &, httplib::Response & res) {
455
+ json j = {{"server", "diffusion-gemma-http"}, {"model", G.model_name},
456
+ {"endpoints", json::array({"/health", "/v1/models", "/v1/chat/completions (POST)"})}};
457
+ res.set_content(j.dump(), "application/json");
458
+ });
459
+
460
+ svr.Get("/health", [](const httplib::Request &, httplib::Response & res) {
461
+ res.set_content("{\"status\":\"ok\"}", "application/json");
462
+ });
463
+
464
+ svr.Get("/v1/models", [](const httplib::Request &, httplib::Response & res) {
465
+ json j = {{"object", "list"},
466
+ {"data", json::array({json{{"id", G.model_name}, {"object", "model"}, {"owned_by", "local"}}})}};
467
+ res.set_content(j.dump(), "application/json");
468
+ });
469
+
470
+ svr.Post("/v1/chat/completions", [](const httplib::Request & req, httplib::Response & res) {
471
+ json body = json::parse(req.body, nullptr, false);
472
+ if (body.is_discarded() || !body.contains("messages")) {
473
+ res.status = 400;
474
+ res.set_content("{\"error\":\"json invalido ou sem messages\"}", "application/json");
475
+ return;
476
+ }
477
+ int max_new = 0;
478
+ if (body.contains("max_tokens") && body["max_tokens"].is_number()) max_new = body["max_tokens"];
479
+ else if (body.contains("max_completion_tokens") && body["max_completion_tokens"].is_number())
480
+ max_new = body["max_completion_tokens"];
481
+ if (max_new <= 0) max_new = 512;
482
+ const bool stream = body.value("stream", false);
483
+ const bool thinking = body.value("enable_thinking", G.thinking_default);
484
+
485
+ const auto p_ids = prompt_ids_for(body["messages"], thinking);
486
+ char ridbuf[40]; snprintf(ridbuf, sizeof(ridbuf), "chatcmpl-%08x%08x", rand(), rand());
487
+ const std::string rid = ridbuf;
488
+ const long created = (long) time(nullptr);
489
+
490
+ if (!stream) {
491
+ std::lock_guard<std::mutex> lk(G.mtx);
492
+ auto r = dg_generate(p_ids, max_new, [](const std::vector<llama_token> &, bool) {});
493
+ const std::string text = extract_text(r.ids);
494
+ json j = {{"id", rid}, {"object", "chat.completion"}, {"created", created},
495
+ {"model", G.model_name},
496
+ {"choices", json::array({json{
497
+ {"index", 0},
498
+ {"message", json{{"role", "assistant"}, {"content", text}}},
499
+ {"finish_reason", r.stopped ? "stop" : "length"}}})},
500
+ {"usage", json{{"prompt_tokens", (int) p_ids.size()},
501
+ {"completion_tokens", (int) r.ids.size()},
502
+ {"total_tokens", (int) (p_ids.size() + r.ids.size())}}}};
503
+ res.set_content(j.dump(), "application/json");
504
+ return;
505
+ }
506
+
507
+ res.set_chunked_content_provider("text/event-stream",
508
+ [p_ids, max_new, rid, created](size_t, httplib::DataSink & sink) -> bool {
509
+ std::lock_guard<std::mutex> lk(G.mtx);
510
+ auto send = [&](const json & j) {
511
+ const std::string s = "data: " + j.dump() + "\n\n";
512
+ sink.write(s.data(), s.size());
513
+ };
514
+ send(chunk_json(rid, created, json{{"role", "assistant"}, {"content", ""}}, nullptr));
515
+ std::string sent;
516
+ auto r = dg_generate(p_ids, max_new,
517
+ [&](const std::vector<llama_token> & acc, bool) {
518
+ const std::string full = extract_text(acc);
519
+ if (full.size() > sent.size()) {
520
+ send(chunk_json(rid, created, json{{"content", full.substr(sent.size())}}, nullptr));
521
+ sent = full;
522
+ }
523
+ });
524
+ send(chunk_json(rid, created, json::object(), r.stopped ? "stop" : "length"));
525
+ const std::string done = "data: [DONE]\n\n";
526
+ sink.write(done.data(), done.size());
527
+ sink.done();
528
+ return true;
529
+ });
530
+ });
531
+
532
+ fprintf(stderr, "diffusion-gemma-http escutando em http://%s:%d\n", host.c_str(), port);
533
+ printf("READY %d\n", G.n_vocab); fflush(stdout);
534
+ svr.listen(host, port);
535
+
536
+ llama_batch_free(G.batch);
537
+ llama_free(G.ctx);
538
+ llama_model_free(G.model);
539
+ llama_backend_free();
540
+ return 0;
541
+ }