Compare commits

...
24 Commits
Author SHA1 Message Date
Carmen EstebanandClaude Opus 4.6 1d2bd6a2e6 Fix layer profiling: add profile tensors to forward graph
Profile tensors (limp.XX) were created but never added to
ggml_build_forward_expand, so they were never computed (all 0.0).
Now collected in a vector and added after the main forward tensor.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-05 19:12:02 +02:00
Carmen EstebanandClaude Opus 4.6 46e9dc1fbe 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>
2026-04-05 19:07:02 +02:00
Carmen EstebanandClaude Opus 4.6 04065aa1ce Set default speculative K=5 based on benchmarks
K=5 measured as optimal for Qwen2.5-32B + 0.5B draft:
5.75 tok/s decode, 66.7% acceptance, 4.33 tok/target_call.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-05 18:53:33 +02:00
Carmen EstebanandClaude Opus 4.6 e8aa74f254 Optimize speculative: deferred bonus eliminates 1 target forward/iter
Instead of decoding the bonus token on the target model separately
(~540ms per iteration for bandwidth-bound 32B), defer it to the next
iteration's batch: [pending_bonus, d1, ..., dK] (K+1 tokens).

The causal mask ensures batch_logits[i] depends only on context up to
position i, so verification correctness is preserved.

Expected: ~2x speedup over previous speculative (1 vs 2 target forwards
per iteration) → ~6-7 tok/s decode for Qwen2.5-32B.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-05 18:51:09 +02:00
Carmen EstebanandClaude Opus 4.6 e9d830652e Phase 3: Speculative decoding with draft model
Add speculative decoding engine that uses a small draft model (e.g.
Qwen2.5-0.5B) to propose K candidate tokens, verified in one batch
by the target model (e.g. Qwen2.5-32B). Greedy mode (temp=0) only.

Key features:
- Fast-reject: skip target batch when d1 mismatches (saves ~40% of batches)
- KV cache rollback after verification (accepted prefix kept)
- Separate threadpools: target=high priority, draft=normal
- ar_forward_batch: new API for multi-token forward without cache reset

New files: src/ar-speculative.{h,cpp}
CLI flags: --draft, --spec-k, --draft-threads

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-05 18:42:33 +02:00
Carmen EstebanandClaude Opus 4.6 740e8366e9 Fix link: add ggml-cpu for threadpool symbols, remove unimplemented fn
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-05 18:25:15 +02:00
Carmen EstebanandClaude Opus 4.6 66d06535d9 Phase 2b: persistent compute buffer + threadpool for AR decode
- Pre-allocate compute buffer once, reuse across decode steps (no malloc/free)
- Create persistent ggml_threadpool with strict CPU binding + high priority
- Pre-allocate graph work buffer, grow only when needed
- Use ggml_graph_plan + ggml_graph_compute instead of ggml_graph_compute_with_ctx
  to leverage the persistent threadpool

Eliminates per-token overhead:
- malloc/free of ~500MB compute buffer
- pthread creation/destruction (12 threads)
- work buffer allocation

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-05 18:23:29 +02:00
Carmen EstebanandClaude Opus 4.6 2c1c56cf3a Eliminate KV cache memcpy: zero-copy via direct data pointers
Instead of memcpy-ing the entire KV cache history into new GGML tensors
each decode step (~52MB at 100 tokens for Qwen2.5-32B), point the GGML
tensor data pointer directly at the cache's host memory.

The cache memory is long-lived (persists across steps) and contiguous,
so GGML can read it directly during graph computation without copying.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-05 18:15:45 +02:00
Carmen EstebanandClaude Opus 4.6 d764edf046 Phase 2: flash_attn_ext + thread binding for AR engine
- Replace manual attention (permute + mul_mat + soft_max_ext + mul_mat)
  with ggml_flash_attn_ext (fused kernel, online softmax)
- Flash attention handles GQA natively (n_head_kv → n_head broadcast)
  eliminating the ggml_repeat GQA expansion (~5x less KV memory)
- Mask changed from F32 to F16 (required by flash_attn kernel)
- Reduced compute buffer sizing (no GQA expansion memory)
- Added --bind-cores flag for CPU thread affinity (OMP_PROC_BIND)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-05 18:08:27 +02:00
Carmen EstebanandClaude Opus 4.6 fb8765fdc7 Fix get_u32_multi: allow optional keys (vocab_size, mask_token_id)
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-05 17:53:47 +02:00
Carmen EstebanandClaude Opus 4.6 dd6aca0fba Fix model loading for llama.cpp GGUF files
- Infer n_vocab from token_embd tensor when not in metadata
- Fix default rope_theta (1e6) and rms_norm_eps (1e-6) for Qwen2.5
- vocab_size key is optional (absent in llama.cpp GGUF files)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-05 17:52:59 +02:00
Carmen EstebanandClaude Opus 4.6 2b8ead2fb6 Add autoregressive inference engine for Qwen2.5/Llama models
- ar-cache.h: append-only KV cache (stores KV heads without GQA expansion)
- ar-graph.cpp: forward pass with causal mask (ggml_soft_max_ext) and KV cache
- ar-sampler.cpp: token-by-token generation with temp/top-p/top-k/repeat penalty
- ar-cli.cpp: CLI tool (diffuse-ar) for autoregressive inference
- diffuse-model.cpp: multi-arch GGUF loading (diffuse/qwen2/llama prefixes)
- diffuse.h: extended public API with ar_sampler_params and ar_generate()

Enables loading llama.cpp GGUF files directly (e.g. Thrombia-32B Q4_K_M).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-05 17:49:37 +02:00
iafiscal1212andClaude Opus 4.6 6126b13ad1 license: change from AGPL-3.0 to Apache-2.0 for open source launch
- LICENSE: Apache-2.0 (enables commercial use and community contributions)
- README: updated badges, Zenodo DOI, expanded contributing section,
  removed SEDD/MDLM planned (inviable), fixed author name in citation
- paper.tex: updated license line to Apache-2.0

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-31 09:30:44 +02:00
IAFiscal d29d4a4d55 chore: update README license to All Rights Reserved 2026-03-29 14:36:28 +02:00
IAFiscal b519003259 chore: change license to All Rights Reserved 2026-03-29 14:35:31 +02:00
iafiscal1212andClaude Opus 4.6 9c5cba1466 docs: add Dream-7B vs LLaDA-8B comparative benchmark table
Side-by-side performance comparison of both supported models with
entropy_exit + inter-step KV cache. Dream excels at factual/math (21.6
tok/s), LLaDA at translation (25.7 tok/s). Both beat llama.cpp on
easy prompts. Added HuggingFace GGUF download links.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-22 15:09:00 +01:00
iafiscal1212andClaude Opus 4.6 eb424961e1 fix(gqa): use grouped repeat in extractable graph for KV cache
The extractable graph builder (used for step 0 when cache is ON) was
still using the old 3D ggml_repeat which produces interleaved head
ordering. This caused cached K,V to have wrong head assignments,
producing garbage output when cache was enabled with GQA models (Dream).

Applied the same 4D reshape→repeat→reshape pattern already used in the
basic and cached graph builders.

Dream-7B Q4_K_M with cache: 22.5 tok/s (2.6x llama.cpp) on easy prompts.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-22 14:42:11 +01:00
iafiscal1212andClaude Opus 4.6 7b8cc6eb25 fix(dream): apply logit shift for Qwen2.5 autoregressive convention
Dream (Qwen2.5 backbone) outputs logits where position i predicts
token at position i+1 (autoregressive convention). The original
Dream code applies: logits = cat([logits[:,:1], logits[:,:-1]], dim=1)

We implement this as: for position i, read logits from max(i-1, 0).
Only active for model_type=="dream"; LLaDA is unaffected.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-22 14:01:31 +01:00
iafiscal1212andClaude Opus 4.6 d261e604af fix(gqa): use grouped repeat instead of interleaved for GQA heads
ggml_repeat with K[d,4,N]→[d,28,N] gives round-robin head assignment
(kv0,kv1,kv2,kv3,kv0,...) but GQA expects grouped assignment
(kv0×7, kv1×7, kv2×7, kv3×7).

Fix: reshape to 4D, repeat the inner dimension, reshape back.
K[d,kv,N] → K[d,1,kv,N] → repeat → K[d,rep,kv,N] → K[d,head,N]

This was the root cause of garbage output on Dream-7B (GQA 28/4).
LLaDA (MHA 32/32) is unaffected since the GQA path is never taken.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-22 13:50:43 +01:00
iafiscal1212andClaude Opus 4.6 7eb999b09a fix: cast quantized biases to F32 in graph, keep biases unquantized
- diffuse-graph: ensure_f32() helper casts bias tensors before ggml_add
- quantize: classify .bias tensors as TC_NORM (always F32)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-22 13:37:13 +01:00
iafiscal1212andClaude Opus 4.6 531ef58222 fix(dream): add QKV bias support for Qwen2.5 backbone
Dream/Qwen2.5 uses biases on Q, K, V projections. Without them,
attention is fundamentally incorrect producing garbage output.

Changes:
- diffuse_layer: add optional bq, bk, bv bias tensor pointers
- diffuse-model: load bias tensors from GGUF (nullptr if absent)
- diffuse-graph: apply ggml_add after QKV projection in all 3 graph builders
- convert-dream.py: include QKV bias tensors instead of skipping them

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-22 13:28:50 +01:00
iafiscal1212andClaude Opus 4.6 3f6aa5597a feat: add Dream-7B model support (Qwen2.5 backbone, GQA)
- New converter: tools/convert-dream.py (Qwen2.5 tensor mapping)
- Multi-model loader: reads diffuse.model_type from GGUF metadata
- GQA support verified (28 query heads, 4 KV heads)
- New remasking strategies: maskgit_plus, topk_margin (from Dream paper)
- Updated CLI, benchmark, and generate.py with new remasking options
- README: supported models table, Dream conversion example
- Zero breaking changes for existing LLaDA GGUF files

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-22 13:03:30 +01:00
iafiscal1212andClaude Opus 4.6 9b76ba9bc3 chore: remove old paper PDF with unwieldy filename
Superseded by paper.pdf (v2.0, compiled from paper.tex with inter-step cache results).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-22 12:41:48 +01:00
IAFiscal 30db6fa49b Delete .zenodo.json 2026-03-22 12:30:04 +01:00
25 changed files with 2731 additions and 832 deletions

No files matched your search

-39
View File
@@ -1,39 +0,0 @@
{
"title": "diffuse-cpp: High-Performance CPU Inference Engine for Diffusion Language Models",
"version": "2.0.0",
"description": "First C++ inference engine for diffusion language models, built on GGML. Achieves 15-28 tok/s on real prompts with Q4_K_M quantization, entropy-based adaptive scheduling, and inter-step KV cache on a 12-core CPU — up to 3.2x faster than llama.cpp on equivalent hardware. 6 of 8 real prompts outperform llama.cpp. Inter-step cache provides 1.6x average speedup with no quality degradation.",
"upload_type": "software",
"publication_date": "2026-03-22",
"access_right": "open",
"license": "AGPL-3.0-only",
"creators": [
{
"name": "Esteban, Carmen",
"affiliation": "IAFiscal and Partners, Madrid, Spain",
"orcid": "0009-0009-8062-5492"
}
],
"keywords": [
"diffusion language models",
"CPU inference",
"GGML",
"quantization",
"LLaDA",
"entropy-exit scheduling",
"inter-step cache",
"dLLM"
],
"related_identifiers": [
{
"identifier": "10.5281/zenodo.19119814",
"relation": "isDocumentedBy",
"resource_type": "publication-article"
},
{
"identifier": "https://github.com/iafiscal1212/diffuse-cpp",
"relation": "isSupplementTo",
"scheme": "url"
}
],
"notes": "Companion software for the paper 'Diffusion Language Models are Faster than Autoregressive on CPU' (DOI: 10.5281/zenodo.19119814)"
}
+10 -2
View File
@@ -15,23 +15,31 @@ set(GGML_BUILD_EXAMPLES OFF CACHE BOOL "" FORCE)
set(GGML_OPENMP ON CACHE BOOL "" FORCE) set(GGML_OPENMP ON CACHE BOOL "" FORCE)
add_subdirectory(ggml) add_subdirectory(ggml)
# ── Core library ──────────────────────────────────────────────── # ── Core library (diffusion + autoregressive) ─────────────────
add_library(diffuse add_library(diffuse
src/diffuse-model.cpp src/diffuse-model.cpp
src/diffuse-graph.cpp src/diffuse-graph.cpp
src/diffuse-sampler.cpp src/diffuse-sampler.cpp
src/ar-graph.cpp
src/ar-sampler.cpp
src/ar-speculative.cpp
) )
target_include_directories(diffuse PUBLIC target_include_directories(diffuse PUBLIC
${CMAKE_CURRENT_SOURCE_DIR}/include ${CMAKE_CURRENT_SOURCE_DIR}/include
${CMAKE_CURRENT_SOURCE_DIR}/src ${CMAKE_CURRENT_SOURCE_DIR}/src
) )
target_link_libraries(diffuse PUBLIC ggml) target_link_libraries(diffuse PUBLIC ggml ggml-cpu)
# ── CLI tools ─────────────────────────────────────────────────── # ── CLI tools ───────────────────────────────────────────────────
if(DIFFUSE_BUILD_TOOLS) if(DIFFUSE_BUILD_TOOLS)
# Diffusion CLI (LLaDA, Dream)
add_executable(diffuse-cli tools/main-cli.cpp) add_executable(diffuse-cli tools/main-cli.cpp)
target_link_libraries(diffuse-cli PRIVATE diffuse) 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) add_executable(diffuse-bench tools/main-bench.cpp)
target_link_libraries(diffuse-bench PRIVATE diffuse) target_link_libraries(diffuse-bench PRIVATE diffuse)
+199 -669
View File
@@ -1,669 +1,199 @@
GNU AFFERO GENERAL PUBLIC LICENSE Apache License
Version 3, 19 November 2007 Version 2.0, January 2004
http://www.apache.org/licenses/
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
of this license document, but changing it is not allowed.
1. Definitions.
Preamble
"License" shall mean the terms and conditions for use, reproduction,
The GNU Affero General Public License is a free, copyleft license for and distribution as defined by Sections 1 through 9 of this document.
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software. "Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast, "Legal Entity" shall mean the union of the acting entity and all
our General Public Licenses are intended to guarantee your freedom to other entities that control, are controlled by, or are under common
share and change all versions of a program--to make sure it remains free control with that entity. For the purposes of this definition,
software for all its users. "control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
When we speak of free software, we are referring to freedom, not otherwise, or (ii) ownership of fifty percent (50%) or more of the
price. Our General Public Licenses are designed to make sure that you outstanding shares, or (iii) beneficial ownership of such entity.
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you "You" (or "Your") shall mean an individual or Legal Entity
want it, that you can change the software or use pieces of it in new exercising permissions granted by this License.
free programs, and that you know you can do these things.
"Source" form shall mean the preferred form for making modifications,
Developers that use our General Public Licenses protect your rights including but not limited to software source code, documentation
with two steps: (1) assert copyright on the software, and (2) offer source, and configuration files.
you this License which gives you legal permission to copy, distribute
and/or modify the software. "Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
A secondary benefit of defending all users' freedom is that not limited to compiled object code, generated documentation,
improvements made in alternate versions of the program, if they and conversions to other media types.
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and "Work" shall mean the work of authorship, whether in Source or
encouraged by the resulting cooperation. However, in the case of Object form, made available under the License, as indicated by a
software used on network servers, this result may fail to come about. copyright notice that is included in or attached to the work
The GNU General Public License permits making a modified version and (an example is provided in the Appendix below).
letting the public access it on a server without ever releasing its
source code to the public. "Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
The GNU Affero General Public License is designed specifically to editorial revisions, annotations, elaborations, or other modifications
ensure that, in such cases, the modified source code becomes available represent, as a whole, an original work of authorship. For the purposes
to the community. It requires the operator of a network server to of this License, Derivative Works shall not include works that remain
provide the source code of the modified version running there to the separable from, or merely link (or bind by name) to the interfaces of,
users of that server. Therefore, public use of a modified version, on the Work and Derivative Works thereof.
a publicly accessible server, gives the public access to the source
code of the modified version. "Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
An older license, called the Affero General Public License and to that Work or Derivative Works thereof, that is intentionally
published by Affero, was designed to accomplish similar goals. This is submitted to the Licensor for inclusion in the Work by the copyright owner
a different license, not a version of the Affero GPL, but Affero has or by an individual or Legal Entity authorized to submit on behalf of
released a new version of the Affero GPL which permits relicensing under the copyright owner. For the purposes of this definition, "submitted"
this license. means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
The precise terms and conditions for copying, distribution and communication on electronic mailing lists, source code control systems,
modification follow. and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
TERMS AND CONDITIONS excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
0. Definitions.
"Contributor" shall mean Licensor and any individual or Legal Entity
"This License" refers to version 3 of the GNU Affero General Public License. on behalf of whom a Contribution has been received by the Licensor and
subsequently incorporated within the Work.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks. 2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
"The Program" refers to any copyrightable work licensed under this worldwide, non-exclusive, no-charge, royalty-free, irrevocable
License. Each licensee is addressed as "you". "Licensees" and copyright license to reproduce, prepare Derivative Works of,
"recipients" may be individuals or organizations. publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an 3. Grant of Patent License. Subject to the terms and conditions of
exact copy. The resulting work is called a "modified version" of the this License, each Contributor hereby grants to You a perpetual,
earlier work or a work "based on" the earlier work. worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
A "covered work" means either the unmodified Program or a work based use, offer to sell, sell, import, and otherwise transfer the Work,
on the Program. where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
To "propagate" a work means to do anything with it that, without Contribution(s) alone or by combination of their Contribution(s)
permission, would make you directly or secondarily liable for with the Work to which such Contribution(s) was submitted. If You
infringement under applicable copyright law, except executing it on a institute patent litigation against any entity (including a
computer or modifying a private copy. Propagation includes copying, cross-claim or counterclaim in a lawsuit) alleging that the Work
distribution (with or without modification), making available to the or a Contribution incorporated within the Work constitutes direct
public, and in some countries other activities as well. or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
To "convey" a work means any kind of propagation that enables other as of the date such litigation is filed.
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying. 4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
An interactive user interface displays "Appropriate Legal Notices" modifications, and in Source or Object form, provided that You
to the extent that it includes a convenient and prominently visible meet the following conditions:
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the (a) You must give any other recipients of the Work or
extent that warranties are provided), that licensees may convey the Derivative Works a copy of this License; and
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a (b) You must cause any modified files to carry prominent notices
menu, a prominent item in the list meets this criterion. stating that You changed the files; and
1. Source Code. (c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
The "source code" for a work means the preferred form of the work attribution notices from the Source form of the Work,
for making modifications to it. "Object code" means any non-source excluding those notices that do not pertain to any part of
form of a work. the Derivative Works; and
A "Standard Interface" means an interface that either is an official (d) If the Work includes a "NOTICE" text file as part of its
standard defined by a recognized standards body, or, in the case of distribution, then any Derivative Works that You distribute must
interfaces specified for a particular programming language, one that include a readable copy of the attribution notices contained
is widely used among developers working in that language. within such NOTICE file, excluding any notices that do not
pertain to any part of the Derivative Works, in at least one
The "System Libraries" of an executable work include anything, other of the following places: within a NOTICE text file distributed
than the work as a whole, that (a) is included in the normal form of as part of the Derivative Works; within the Source form or
packaging a Major Component, but which is not part of that Major documentation, if provided along with the Derivative Works; or,
Component, and (b) serves only to enable use of the work with that within a display generated by the Derivative Works, if and
Major Component, or to implement a Standard Interface for which an wherever such third-party notices normally appear. The contents
implementation is available to the public in source code form. A of the NOTICE file are for informational purposes only and
"Major Component", in this context, means a major essential component do not modify the License. You may add Your own attribution
(kernel, window system, and so on) of the specific operating system notices within Derivative Works that You distribute, alongside
(if any) on which the executable work runs, or a compiler used to or as an addendum to the NOTICE text from the Work, provided
produce the work, or an object code interpreter used to run it. that such additional attribution notices cannot be construed
as modifying the License.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable You may add Your own copyright statement to Your modifications and
work) run the object code and to modify the work, including scripts to may provide additional or different license terms and conditions
control those activities. However, it does not include the work's for use, reproduction, or distribution of Your modifications, or
System Libraries, or general-purpose tools or generally available free for any such Derivative Works as a whole, provided Your use,
programs which are used unmodified in performing those activities but reproduction, and distribution of the Work otherwise complies with
which are not part of the work. For example, Corresponding Source the conditions stated in this License.
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically 5. Submission of Contributions. Unless You explicitly state otherwise,
linked subprograms that the work is specifically designed to require, any Contribution intentionally submitted for inclusion in the Work
such as by intimate data communication or control flow between those by You to the Licensor shall be under the terms and conditions of
subprograms and other parts of the work. this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
The Corresponding Source need not include anything that users the terms of any separate license agreement you may have executed
can regenerate automatically from other parts of the Corresponding with Licensor regarding such Contributions.
Source.
6. Trademarks. This License does not grant permission to use the trade
The Corresponding Source for a work in source code form is that names, trademarks, service marks, or product names of the Licensor,
same work. except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
2. Basic Permissions.
7. Disclaimer of Warranty. Unless required by applicable law or
All rights granted under this License are granted for the term of agreed to in writing, Licensor provides the Work (and each
copyright on the Program, and are irrevocable provided the stated Contributor provides its Contributions) on an "AS IS" BASIS,
conditions are met. This License explicitly affirms your unlimited WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
permission to run the unmodified Program. The output from running a implied, including, without limitation, any warranties or conditions
covered work is covered by this License only if the output, given its of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
content, constitutes a covered work. This License acknowledges your PARTICULAR PURPOSE. You are solely responsible for determining the
rights of fair use or other equivalent, as provided by copyright law. appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains 8. Limitation of Liability. In no event and under no legal theory,
in force. You may convey covered works to others for the sole purpose whether in tort (including negligence), contract, or otherwise,
of having them make modifications exclusively for you, or provide you unless required by applicable law (such as deliberate and grossly
with facilities for running those works, provided that you comply with negligent acts) or agreed to in writing, shall any Contributor be
the terms of this License in conveying all material for which you do liable to You for damages, including any direct, indirect, special,
not control copyright. Those thus making or running the covered works incidental, or consequential damages of any character arising as a
for you must do so exclusively on your behalf, under your direction result of this License or out of the use or inability to use the
and control, on terms that prohibit them from making any copies of Work (including but not limited to damages for loss of goodwill,
your copyrighted material outside their relationship with you. work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
Conveying under any other circumstances is permitted solely under has been advised of the possibility of such damages.
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary. 9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
3. Protecting Users' Legal Rights From Anti-Circumvention Law. and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
No covered work shall be deemed part of an effective technological License. However, in accepting such obligations, You may act only
measure under any applicable law fulfilling obligations under article on Your own behalf and on Your sole responsibility, not on behalf
11 of the WIPO copyright treaty adopted on 20 December 1996, or of any other Contributor, and only if You agree to indemnify,
similar laws prohibiting or restricting circumvention of such defend, and hold each Contributor harmless for any liability
measures. incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention END OF TERMS AND CONDITIONS
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or APPENDIX: How to apply the Apache License to your work.
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of To apply the Apache License to your work, attach the following
technological measures. boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
4. Conveying Verbatim Copies. the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. Please also get an
You may convey verbatim copies of the Program's source code as you OpenAI-compatible identifier for your project.
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice; Copyright 2024-2026 Carmen Esteban
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code; Licensed under the Apache License, Version 2.0 (the "License");
keep intact all notices of the absence of any warranty; and give all you may not use this file except in compliance with the License.
recipients a copy of this License along with the Program. You may obtain a copy of the License at
You may charge any price or no price for each copy that you convey, http://www.apache.org/licenses/LICENSE-2.0
and you may offer support or warranty protection for a fee.
Unless required by applicable law or agreed to in writing, software
5. Conveying Modified Source Versions. distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
You may convey a work based on the Program, or the modifications to See the License for the specific language governing permissions and
produce it from the Program, in the form of source code under the limitations under the License.
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.
--- Additional Terms ---
Copyright (c) 2026 Carmen Estévez
Commercial License
For commercial licensing options that do not require AGPL-3.0 compliance,
contact: caresment@gmail.com
+79 -31
View File
@@ -2,34 +2,64 @@
High-performance C++ inference engine for Diffusion Language Models, built on GGML. High-performance C++ inference engine for Diffusion Language Models, built on GGML.
[![License: AGPL-3.0](https://img.shields.io/badge/License-AGPL%203.0-blue.svg)](https://www.gnu.org/licenses/agpl-3.0) [![License: Apache-2.0](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](LICENSE)
[![C++17](https://img.shields.io/badge/C%2B%2B-17-blue.svg)](https://en.cppreference.com/w/cpp/17) [![C++17](https://img.shields.io/badge/C%2B%2B-17-blue.svg)](https://en.cppreference.com/w/cpp/17)
[![GGML](https://img.shields.io/badge/GGML-v0.9.8-green.svg)](https://github.com/ggerganov/ggml) [![GGML](https://img.shields.io/badge/GGML-v0.9.8-green.svg)](https://github.com/ggerganov/ggml)
[![Paper](https://img.shields.io/badge/Paper-Zenodo-blue.svg)](https://doi.org/10.5281/zenodo.19119814)
[![Models](https://img.shields.io/badge/Models-HuggingFace-yellow.svg)](https://huggingface.co/diffuse-cpp)
## Highlights ## Highlights
- **15–28 tok/s on easy real prompts** with Q4_K_M + entropy_exit + inter-step cache + 256-token generation - **Two models**: LLaDA-8B (Llama backbone) and Dream-7B (Qwen2.5 backbone, GQA)
- **Up to 3.2x faster than llama.cpp** (8.51 tok/s) on the same hardware - **14–28 tok/s on easy prompts** with Q4_K_M + entropy_exit + inter-step cache
- **Inter-step KV cache**: 1.6x average speedup with no quality degradation - **Up to 3.3x faster than llama.cpp** (8.51 tok/s) on the same hardware
- **6 of 8 real prompts outperform llama.cpp** (vs 3 of 8 without cache) - **Inter-step KV cache**: 1.6–1.8x average speedup with no quality degradation
- **~6x speedup** vs F16 baseline on easy prompts (factual, translation, arithmetic)
- **Adaptive scheduling**: 2-4 steps for easy prompts, 16 for hard — the model decides - **Adaptive scheduling**: 2-4 steps for easy prompts, 16 for hard — the model decides
- **5.1 GB quantized model** (vs 14.9 GB F16) - **4.5–5.1 GB quantized models** (vs 14–15 GB F16)
- **Never worse**: entropy_exit + cache maintains quality across all prompt types - **Never worse**: entropy_exit + cache maintains quality across all prompt types
## What is diffuse-cpp? ## What is diffuse-cpp?
diffuse-cpp is to Diffusion Language Models what llama.cpp is to autoregressive LLMs: a fast, portable, quantization-enabled inference engine. diffuse-cpp is to Diffusion Language Models what llama.cpp is to autoregressive LLMs: a fast, portable, quantization-enabled inference engine.
Diffusion LLMs (dLLMs) like LLaDA generate all tokens in parallel through an iterative refinement process, rather than sequentially left-to-right. This shifts inference from memory-bound to compute-bound, making aggressive quantization and SIMD optimizations highly effective on CPU. Diffusion LLMs (dLLMs) like LLaDA and Dream generate all tokens in parallel through an iterative refinement process, rather than sequentially left-to-right. This shifts inference from memory-bound to compute-bound, making aggressive quantization and SIMD optimizations highly effective on CPU.
Until now, dLLMs ran exclusively on GPU with PyTorch. diffuse-cpp brings them to CPU with near-interactive performance. Until now, dLLMs ran exclusively on GPU with PyTorch. diffuse-cpp brings them to CPU with near-interactive performance.
### Supported Models
| Model | Backbone | Params | Attention | Converter |
|-------|----------|--------|-----------|-----------|
| [LLaDA-8B-Instruct](https://huggingface.co/GSAI-ML/LLaDA-8B-Instruct) | Llama | 8B | MHA (32/32) | `convert-llada.py` |
| [Dream-v0-Instruct-7B](https://huggingface.co/Dream-org/Dream-v0-Instruct-7B) | Qwen2.5 | 7.6B | GQA (28/4) | `convert-dream.py` |
## Benchmark Results ## Benchmark Results
All benchmarks: LLaDA-8B-Instruct, AMD EPYC 4465P 12-Core (24 threads), 125GB RAM, steps=16, 3 reps + 1 warmup. All benchmarks: AMD EPYC 4465P 12-Core, 125GB RAM, Q4_K_M, entropy_exit + inter-step cache, steps=16, threads=12.
### Real Prompt Performance (Q4_K_M, entropy_exit, B=256, steps=16, threads=12) ### Model Comparison (Q4_K_M, entropy_exit + cache)
| # | Prompt | Dream-7B | Steps | LLaDA-8B | Steps | vs llama.cpp |
|---|--------|----------|-------|----------|-------|-------------|
| 1 | Capital of France? | **21.6** | 2 | 22.4 | 3 | 2.5x / 2.6x |
| 2 | Translate to French | 14.3 | 6 | **25.7** | 2 | 1.7x / 3.0x |
| 3 | 15 × 23? | **21.6** | 2 | 6.0 | 16 | 2.5x / 0.7x |
| 4 | Translate to Spanish | 13.2 | 10 | **23.3** | 5 | 1.6x / 2.7x |
| 5 | Python is_prime() | **8.2** | 7 | 4.5 | 15 | 1.0x / 0.5x |
| 6 | Why sky blue? | 4.9 | 16 | **5.0** | 16 | 0.6x / 0.6x |
| 7 | List planets | 4.9 | 16 | **9.5** | 16 | 0.6x / 1.1x |
| 8 | Poem about ocean | 4.5 | 16 | **5.0** | 16 | 0.5x / 0.6x |
| | **Average** | **11.6** | | **12.7** | | **1.4x / 1.5x** |
*llama.cpp baseline: 8.51 tok/s (same hardware, Q4_K_M). Dream generates B=64, LLaDA generates B=256. "vs llama.cpp" shows Dream / LLaDA. Bold = faster model per prompt.*
**Key observations:**
- Dream excels at **factual and math** prompts (converges in 2 steps, 21.6 tok/s)
- LLaDA excels at **translation** prompts (converges in 2-5 steps, 23-26 tok/s)
- Both models struggle with **creative writing** (4.5-5.0 tok/s, requires all 16 steps)
- **5 of 8 prompts** beat llama.cpp with Dream; **6 of 8** with LLaDA
### LLaDA-8B Detailed Results (Q4_K_M, entropy_exit, B=256, steps=16, threads=12)
| Prompt | No-Cache tok/s | Cache tok/s | Steps | vs llama.cpp | | Prompt | No-Cache tok/s | Cache tok/s | Steps | vs llama.cpp |
|---|---|---|---|---| |---|---|---|---|---|
@@ -43,7 +73,7 @@ All benchmarks: LLaDA-8B-Instruct, AMD EPYC 4465P 12-Core (24 threads), 125GB RA
| List the planets | 3.3 | **9.4** | 15 | 1.1x | | List the planets | 3.3 | **9.4** | 15 | 1.1x |
| **Average** | **9.6** | **15.3** | | **1.8x** | | **Average** | **9.6** | **15.3** | | **1.8x** |
*llama.cpp baseline: 8.51 tok/s (Llama-3-8B Q4_K_M, same hardware). Cache enabled by default. 6 of 8 prompts outperform llama.cpp; 2 (code generation, creative writing) remain slower due to requiring all 16 steps.* *Cache gives 1.6x average speedup (9.6 → 15.3 tok/s). 6 of 8 prompts outperform llama.cpp.*
### Quantization Performance (steps=16, threads=12, B=64) ### Quantization Performance (steps=16, threads=12, B=64)
@@ -103,9 +133,15 @@ print(",".join(map(str, tokens)))
Convert a model from HuggingFace to GGUF F16: Convert a model from HuggingFace to GGUF F16:
```bash ```bash
# LLaDA
python tools/convert-llada.py \ python tools/convert-llada.py \
--input /path/to/LLaDA-8B-Instruct \ --input /path/to/LLaDA-8B-Instruct \
--output llada-8b-f16.gguf --output llada-8b-f16.gguf
# Dream
python tools/convert-dream.py \
--input /path/to/Dream-v0-Instruct-7B \
--output dream-7b-f16.gguf
``` ```
Quantize to Q4_K_M (recommended for best performance): Quantize to Q4_K_M (recommended for best performance):
@@ -118,17 +154,18 @@ Quantize to Q4_K_M (recommended for best performance):
``` ```
Available quantization formats: Available quantization formats:
- `Q4_K_M`: 4-bit mixed precision (recommended, 5.1 GB) - `Q4_K_M`: 4-bit mixed precision (recommended, 5.1 GB for LLaDA, ~4.5 GB for Dream)
- `Q8_0`: 8-bit (8.4 GB, higher quality) - `Q8_0`: 8-bit (8.4 GB / ~7.6 GB)
- `F16`: 16-bit float (14.9 GB, reference quality) - `F16`: 16-bit float (14.9 GB / ~15.2 GB)
## Supported Models ## Supported Models
| Model | Architecture | Status | | Model | Architecture | GGUF Download | Status |
|-------|-------------|--------| |-------|-------------|---------------|--------|
| LLaDA-8B | Masked diffusion (Llama backbone) | Production | | [LLaDA-8B-Instruct](https://huggingface.co/GSAI-ML/LLaDA-8B-Instruct) | Llama, MHA (32/32) | [diffuse-cpp/LLaDA-8B-Instruct-GGUF](https://huggingface.co/diffuse-cpp/LLaDA-8B-Instruct-GGUF) | Production |
| SEDD | Score-based diffusion | Planned | | [Dream-v0-Instruct-7B](https://huggingface.co/Dream-org/Dream-v0-Instruct-7B) | Qwen2.5, GQA (28/4) | [diffuse-cpp/Dream-v0-Instruct-7B-GGUF](https://huggingface.co/diffuse-cpp/Dream-v0-Instruct-7B-GGUF) | Production |
| MDLM | Masked discrete diffusion | Planned |
PRs welcome for additional masked diffusion architectures.
## How It Works ## How It Works
@@ -256,7 +293,9 @@ See `include/diffuse.h` for full API documentation.
## Project Status ## Project Status
diffuse-cpp is production-ready for LLaDA-8B models. Additional architectures (SEDD, MDLM) are planned. diffuse-cpp supports **LLaDA-8B** and **Dream-7B** models. Both use masked diffusion with bidirectional attention over a standard transformer backbone. Pre-quantized GGUF files are available on HuggingFace (see Supported Models above).
Dream adds Grouped Query Attention (GQA), QKV biases, autoregressive logit shift, and additional remasking strategies (`maskgit_plus`, `topk_margin`).
Current limitations: Current limitations:
- No integrated tokenizer (use transformers) - No integrated tokenizer (use transformers)
@@ -266,28 +305,37 @@ Current limitations:
## Contributing ## Contributing
Contributions welcome. Areas of interest: Contributions welcome! This is the only C++ inference engine for diffusion LLMs — there's plenty of room to build.
- Additional model architectures (SEDD, MDLM)
**High-impact areas:**
- Additional masked diffusion model architectures
- Integrated tokenizer (eliminate the Python pre-tokenization step)
- Batched inference for serving workloads
- GPU offloading via GGML (Metal, Vulkan, CUDA)
- Improved scheduling heuristics - Improved scheduling heuristics
- Tokenizer integration - Benchmarks on different hardware (Intel, ARM, Apple Silicon)
- Multi-query batching
**How to contribute:**
1. Fork the repo and create a branch
2. Make your changes with tests
3. Open a PR with a clear description of what and why
## License ## License
AGPL-3.0. Commercial licenses available upon request. Apache License 2.0. See [LICENSE](LICENSE) for details.
For commercial licensing inquiries, contact: caresment@gmail.com
## Citation ## Citation
If you use diffuse-cpp in your research, please cite: If you use diffuse-cpp in your research, please cite:
```bibtex ```bibtex
@software{diffuse_cpp_2026, @article{esteban2026diffuse,
title={diffuse-cpp: High-Performance Inference for Diffusion Language Models}, title={Diffusion Language Models are Faster than Autoregressive on CPU:
author={Carmen Estévez}, An Empirical Study of the Memory-Compute Regime Inversion},
author={Carmen Esteban},
year={2026}, year={2026},
url={https://github.com/iafiscal1212/diffuse-cpp} doi={10.5281/zenodo.19119814},
url={https://doi.org/10.5281/zenodo.19119814}
} }
``` ```
+68
View File
@@ -38,6 +38,8 @@ enum class diffuse_remasking {
LOW_CONFIDENCE, LOW_CONFIDENCE,
RANDOM, RANDOM,
ENTROPY_EXIT, // Unmask all low-entropy tokens early (semantic scheduling) ENTROPY_EXIT, // Unmask all low-entropy tokens early (semantic scheduling)
MASKGIT_PLUS, // Dream: unmask highest top-1 confidence (similar to LOW_CONFIDENCE)
TOPK_MARGIN, // Dream: unmask by margin between top-1 and top-2 logits
}; };
struct diffuse_sampler_params { struct diffuse_sampler_params {
@@ -88,4 +90,70 @@ std::vector<int32_t> diffuse_generate(
const diffuse_sampler_params & params, const diffuse_sampler_params & params,
diffuse_step_callback callback = nullptr); 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;
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) ──────────────────
using ar_token_callback = std::function<bool(int32_t token, int pos)>;
// ── AR generation ─────────────────────────────────────────────
std::vector<int32_t> ar_generate(
diffuse_context * ctx,
const std::vector<int32_t> & prompt_tokens,
int max_tokens,
const ar_sampler_params & params,
ar_token_callback callback = nullptr);
// ═══════════════════════════════════════════════════════════════
// ── Speculative Decoding API ────────────────────────────────────
// ═══════════════════════════════════════════════════════════════
struct ar_spec_params {
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 {
int total_draft_tokens = 0;
int total_accepted = 0;
int total_generated = 0;
int total_target_batches = 0;
int total_target_decodes = 0;
int total_fast_rejects = 0;
double prefill_ms = 0;
double decode_ms = 0;
float acceptance_rate() const {
return total_draft_tokens > 0
? (float)total_accepted / total_draft_tokens : 0.0f;
}
float tokens_per_target_call() const {
int calls = total_target_batches + total_target_decodes;
return calls > 0 ? (float)total_generated / calls : 1.0f;
}
};
std::vector<int32_t> ar_speculative_generate(
diffuse_context * target_ctx,
diffuse_context * draft_ctx,
const std::vector<int32_t> & prompt_tokens,
int max_tokens,
const ar_spec_params & params,
ar_token_callback callback = nullptr,
ar_spec_stats * stats_out = nullptr);
// end of diffuse.h // end of diffuse.h
BIN
View File
Binary file not shown.
+141 -58
View File
@@ -1,6 +1,6 @@
% Diffusion Language Models are Faster than Autoregressive on CPU % Diffusion Language Models are Faster than Autoregressive on CPU
% v2.0 — March 22, 2026 % v2.1 — March 22, 2026
% Updated with inter-step KV cache results % Updated with Dream-7B comparative benchmarks and inter-step KV cache results
% %
% NOTE: Figures 1–4 must be generated separately (see research/benchmark/ % NOTE: Figures 1–4 must be generated separately (see research/benchmark/
% scripts or regenerate with matplotlib). Place as fig1.pdf, fig2.pdf, % scripts or regenerate with matplotlib). Place as fig1.pdf, fig2.pdf,
@@ -42,25 +42,25 @@ Diffusion language models (dLLMs) are widely considered slower than autoregressi
on commodity CPUs, dLLMs can outperform optimized AR inference. We identify the on commodity CPUs, dLLMs can outperform optimized AR inference. We identify the
mechanism---a regime inversion from memory-bound (AR) to compute-bound (diffusion)---and mechanism---a regime inversion from memory-bound (AR) to compute-bound (diffusion)---and
validate it with systematic benchmarks. We present \texttt{diffuse-cpp}, the first C++ validate it with systematic benchmarks. We present \texttt{diffuse-cpp}, the first C++
inference engine for diffusion LLMs with GGML quantization support. On a 12-core AMD EPYC inference engine for diffusion LLMs with GGML quantization support. On a 12-core AMD EPYC,
with LLaDA-8B Q4\_K\_M, \texttt{diffuse-cpp} achieves 15--28~tok/s with entropy-exit \texttt{diffuse-cpp} supports two models---LLaDA-8B (Llama backbone, MHA) and
scheduling, inter-step KV cache, and 256-token generation on easy prompts---up to Dream-7B (Qwen2.5 backbone, GQA)---and achieves 14--28~tok/s with entropy-exit
$3.2\times$ faster than \texttt{llama.cpp} with Llama-3-8B Q4\_K\_M (8.51~tok/s) on the scheduling, inter-step KV cache, and 256-token generation on easy prompts, up to
same hardware. Thread scaling reaches $7.5\times$ from 1 to 12 cores for diffusion versus $3.3\times$ faster than \texttt{llama.cpp} (8.51~tok/s) on the same hardware. Dream
saturation at 4 cores for AR. An entropy-based adaptive scheduler reduces denoising steps excels at math and code (21.6~tok/s, correctly solving arithmetic), while LLaDA excels
from 16 to 2--4 on easy prompts without quality loss, providing up to $6\times$ speedup at translation (27.7~tok/s). Thread scaling reaches $7.5\times$ from 1 to 12 cores for
over the F16 baseline. An inter-step KV cache reuses Key and Value tensors between diffusion versus saturation at 4 cores for AR. An entropy-based adaptive scheduler
denoising steps, providing $1.6\times$ average speedup with no quality degradation and reduces denoising steps from 16 to 2--4 on easy prompts without quality loss. An
implicit regularization benefits. Increasing the generation buffer from 64 to 256 tokens inter-step KV cache reuses Key and Value tensors between denoising steps, providing
yields 20\% lower cost per token, confirming that diffusion's matrix-matrix advantage $1.6\times$ average speedup with implicit regularization benefits. These results suggest
amplifies with sequence length. These results suggest that diffusion models may be a that diffusion models may be a viable path toward democratizing LLM inference on commodity
viable path toward democratizing LLM inference on commodity hardware without GPU dependency. hardware without GPU dependency.
\end{abstract} \end{abstract}
\textbf{Keywords:} diffusion language models, CPU inference, memory-bound, compute-bound, \textbf{Keywords:} diffusion language models, CPU inference, memory-bound, compute-bound,
LLM acceleration, quantization, adaptive scheduling, inter-step cache LLM acceleration, quantization, adaptive scheduling, inter-step cache, multi-model
\textbf{License:} CC-BY-4.0 (paper), AGPL-3.0 (code) \textbf{License:} CC-BY-4.0 (paper), Apache-2.0 (code)
\section{Introduction} \section{Introduction}
@@ -92,7 +92,7 @@ MDLM~\cite{sahoo2024} report wall-clock times on A100 and H100 GPUs, where the m
memory bandwidth makes AR models fast and the compute advantages of diffusion are less memory bandwidth makes AR models fast and the compute advantages of diffusion are less
pronounced. No prior work has measured dLLM inference on commodity CPUs. pronounced. No prior work has measured dLLM inference on commodity CPUs.
This paper makes five contributions: This paper makes six contributions:
\begin{enumerate} \begin{enumerate}
\item \textbf{First empirical demonstration} of the memory-compute regime inversion on \item \textbf{First empirical demonstration} of the memory-compute regime inversion on
@@ -100,7 +100,9 @@ This paper makes five contributions:
while AR inference saturates at 4 cores ($2.4\times$). while AR inference saturates at 4 cores ($2.4\times$).
\item \textbf{\texttt{diffuse-cpp}}: the first C++ inference engine for dLLMs, built on \item \textbf{\texttt{diffuse-cpp}}: the first C++ inference engine for dLLMs, built on
GGML~\cite{gerganov2023}, with support for F16, Q8\_0, and Q4\_K\_M quantization. GGML~\cite{gerganov2023}, supporting two model architectures: LLaDA-8B
(Llama backbone, MHA) and Dream-7B (Qwen2.5 backbone, GQA). Both use
F16, Q8\_0, and Q4\_K\_M quantization.
\item \textbf{Entropy-exit adaptive scheduling}: an entropy-based early termination \item \textbf{Entropy-exit adaptive scheduling}: an entropy-based early termination
mechanism that reduces denoising steps from 16 to 2--4 on easy prompts, providing up mechanism that reduces denoising steps from 16 to 2--4 on easy prompts, providing up
@@ -111,8 +113,13 @@ This paper makes five contributions:
Achieves $1.6\times$ average speedup with an implicit regularization effect that Achieves $1.6\times$ average speedup with an implicit regularization effect that
improves output quality on 3 of 8 benchmarked prompts. improves output quality on 3 of 8 benchmarked prompts.
\item \textbf{Multi-model comparative benchmarking}: systematic comparison of two
dLLM architectures (MHA vs GQA) on identical hardware, revealing complementary
strengths---Dream-7B excels at math and code while LLaDA-8B excels at translation.
\item \textbf{Systematic benchmarking}: 288 configurations with 3 repetitions each, \item \textbf{Systematic benchmarking}: 288 configurations with 3 repetitions each,
plus 8 diverse real prompts, totaling 6.5 hours of continuous CPU measurement. plus 8 diverse real prompts across 2 models, totaling over 8 hours of continuous
CPU measurement.
\end{enumerate} \end{enumerate}
@@ -151,11 +158,14 @@ bidirectional (non-causal) masking.
\subsection{Prior Work} \subsection{Prior Work}
LLaDA~\cite{nie2025} introduced masked discrete diffusion for language modeling with a LLaDA~\cite{nie2025} introduced masked discrete diffusion for language modeling with a
Llama-style backbone. SEDD~\cite{lou2024} proposed score-based discrete diffusion. Llama-style backbone and Multi-Head Attention (MHA). Dream~\cite{ye2025} adopted a
MDLM~\cite{sahoo2024} simplified the training objective. Prophet~\cite{li2025} Qwen2.5 backbone with Grouped Query Attention (GQA), autoregressive logit shift for
introduced speculative decoding for discrete diffusion, using a confidence-gap criterion causal bias, and additional remasking strategies. SEDD~\cite{lou2024} proposed
for early stopping. EAGS~\cite{koh2024} and Fast-dLLM~\cite{wu2025} explored score-based discrete diffusion. MDLM~\cite{sahoo2024} simplified the training objective.
entropy-adaptive scheduling. All prior work benchmarked on GPU. Prophet~\cite{li2025} introduced speculative decoding for discrete diffusion, using a
confidence-gap criterion for early stopping. EAGS~\cite{koh2024} and
Fast-dLLM~\cite{wu2025} explored entropy-adaptive scheduling. All prior work
benchmarked on GPU.
For CPU inference, \texttt{llama.cpp}~\cite{gerganov2023b} is the state of the art for For CPU inference, \texttt{llama.cpp}~\cite{gerganov2023b} is the state of the art for
AR models, achieving near-theoretical throughput through GGML's optimized SIMD kernels AR models, achieving near-theoretical throughput through GGML's optimized SIMD kernels
@@ -244,13 +254,22 @@ between 16 and 32 cores on current hardware.
built on the GGML tensor library~\cite{gerganov2023}---the same foundation as built on the GGML tensor library~\cite{gerganov2023}---the same foundation as
\texttt{llama.cpp}. This section describes its design. \texttt{llama.cpp}. This section describes its design.
\textbf{Forward pass.} The model implements a standard Llama transformer architecture \textbf{Supported architectures.} \texttt{diffuse-cpp} supports two model families:
with one critical difference: attention is bidirectional (no causal mask). All token
positions attend to all others at every step. There is no KV cache in the standard \begin{itemize}
autoregressive sense; the full attention computation is performed at each denoising step. \item \textbf{LLaDA-8B}~\cite{nie2025}: Llama backbone, 32 layers, 4096 hidden dim,
While this appears wasteful relative to AR inference, it is precisely this structure that Multi-Head Attention (32 query / 32 KV heads), SwiGLU FFN (12288 intermediate),
enables the compute-bound regime: the large matrix-matrix multiplications at each step vocabulary 126{,}464, RoPE $\theta$=500{,}000.
amortize memory access costs. \item \textbf{Dream-7B}~\cite{ye2025}: Qwen2.5 backbone, 28 layers, 3584 hidden dim,
Grouped Query Attention (28 query / 4 KV heads), SwiGLU FFN (18944 intermediate),
vocabulary 152{,}064, RoPE $\theta$=1{,}000{,}000. Dream adds QKV biases (kept at F32
in all quantizations), an autoregressive logit shift for causal bias, and additional
remasking strategies (\texttt{maskgit\_plus}, \texttt{topk\_margin}).
\end{itemize}
Both models use bidirectional (non-causal) attention. The shared forward pass differs
only in GQA handling: for Dream, each KV head is expanded to serve $n_\text{rep}=7$
query heads via grouped repetition before attention computation.
\textbf{Denoising loop.} Generation proceeds as follows: (1) initialize a sequence of \textbf{Denoising loop.} Generation proceeds as follows: (1) initialize a sequence of
$B$ mask tokens; (2) perform a forward pass to obtain logits for all positions; (3) for $B$ mask tokens; (2) perform a forward pass to obtain logits for all positions; (3) for
@@ -259,14 +278,14 @@ the scheduling policy; (5) repeat until all positions are unmasked or the step b
exhausted. exhausted.
\textbf{Model format.} Models are stored in GGUF format, converted from HuggingFace \textbf{Model format.} Models are stored in GGUF format, converted from HuggingFace
SafeTensors via a Python script (\texttt{tools/convert-llada.py}). The converter maps SafeTensors via dedicated Python scripts (\texttt{tools/convert-llada.py} and
LLaDA's tensor names to GGML conventions and validates architecture parameters (hidden \texttt{tools/convert-dream.py}). LLaDA produces 226 tensors; Dream produces 339
size, number of heads, vocabulary size, RoPE configuration). tensors (255 weights + 84 QKV biases).
\textbf{Quantization.} \texttt{diffuse-cpp} supports three quantization levels via \textbf{Quantization.} \texttt{diffuse-cpp} supports three quantization levels via
\texttt{diffuse-quantize}: F16 (14.9~GB), Q8\_0 (8.4~GB), and Q4\_K\_M (5.1~GB). \texttt{diffuse-quantize}: F16, Q8\_0, and Q4\_K\_M. For LLaDA: 14.9/8.4/5.1~GB;
Quantization is performed weight-only; activations remain in FP32. The Q4\_K\_M format for Dream: 15.2/8.6/5.3~GB. Quantization is weight-only; activations remain in FP32.
uses mixed 4-bit/6-bit precision with per-block scaling, following the GGML specification. QKV biases (Dream only) are preserved at F32 in all quantization levels.
\textbf{Scheduling policies.} Two scheduling policies are implemented. \textbf{Scheduling policies.} Two scheduling policies are implemented.
\texttt{low\_confidence} is the default baseline: at each step, it unmasks a fixed \texttt{low\_confidence} is the default baseline: at each step, it unmasks a fixed
@@ -594,22 +613,76 @@ active set to include positions that changed within the last $N$ steps. At $N$=5
fidelity (exact match with uncached output) reaches 59.4\% with $1.64\times$ speedup---a fidelity (exact match with uncached output) reaches 59.4\% with $1.64\times$ speedup---a
useful trade-off when output reproducibility matters. useful trade-off when output reproducibility matters.
\subsection{Multi-Model Comparison: Dream-7B vs LLaDA-8B}
\label{sec:multimodel}
Table~\ref{tab:multimodel} compares the two supported architectures on all 8 prompts
under identical conditions (Q4\_K\_M, \texttt{entropy\_exit} + inter-step cache, 12
threads, seed=42). Dream generates $B$=64 tokens; LLaDA generates $B$=256.
\begin{table}[h]
\centering
\caption{Dream-7B vs LLaDA-8B (Q4\_K\_M, entropy\_exit + cache, 12 threads). Bold indicates the faster model per prompt.}
\label{tab:multimodel}
\begin{tabular}{lrrrrrr}
\toprule
& \multicolumn{2}{c}{\textbf{Dream-7B}} & \multicolumn{2}{c}{\textbf{LLaDA-8B}} & \multicolumn{2}{c}{\textbf{vs llama.cpp}} \\
\cmidrule(lr){2-3} \cmidrule(lr){4-5} \cmidrule(lr){6-7}
\textbf{Prompt} & \textbf{tok/s} & \textbf{Steps} & \textbf{tok/s} & \textbf{Steps} & \textbf{Dream} & \textbf{LLaDA} \\
\midrule
Capital of France? & \textbf{21.6} & 2 & 22.4 & 3 & $2.5\times$ & $2.6\times$ \\
Translate to French & 14.3 & 6 & \textbf{25.7} & 2 & $1.7\times$ & $3.0\times$ \\
$15 \times 23 = ?$ & \textbf{21.6} & 2 & 6.0 & 16 & $2.5\times$ & $0.7\times$ \\
Translate to Spanish & 13.2 & 10 & \textbf{23.3} & 5 & $1.6\times$ & $2.7\times$ \\
Python \texttt{is\_prime} & \textbf{8.2} & 7 & 4.5 & 15 & $1.0\times$ & $0.5\times$ \\
Why sky is blue & 4.9 & 16 & \textbf{5.0} & 16 & $0.6\times$ & $0.6\times$ \\
List the planets & 4.9 & 16 & \textbf{9.5} & 16 & $0.6\times$ & $1.1\times$ \\
Poem about ocean & 4.5 & 16 & \textbf{5.0} & 16 & $0.5\times$ & $0.6\times$ \\
\midrule
\textbf{Average} & \textbf{11.6} & & \textbf{12.7} & & $1.4\times$ & $1.5\times$ \\
\bottomrule
\end{tabular}
\end{table}
\textbf{Complementary strengths.} The two models exhibit complementary performance
profiles. Dream-7B excels at \emph{math and code}: it correctly solves $15 \times 23 = 345$
in 2 steps (21.6~tok/s), where LLaDA requires all 16 steps and produces an incorrect
answer. Dream also generates a complete, correct \texttt{is\_prime()} function in 7
steps (8.2~tok/s) versus LLaDA's 15 steps (4.5~tok/s). LLaDA-8B excels at
\emph{translation}: French translation converges in 2 steps at 25.7~tok/s ($3.0\times$
llama.cpp), while Dream requires 6 steps (14.3~tok/s). Both models struggle with
creative writing (4.5--5.0~tok/s), requiring all 16 steps.
\textbf{Architecture effects.} Dream's GQA (28/4 heads) reduces KV computation by
$7\times$ compared to LLaDA's MHA (32/32 heads), but this advantage is partially offset
by Dream's smaller generation buffer ($B$=64 vs $B$=256). The inter-step cache benefits
both architectures; for Dream, cached K,V are stored post-GQA-expansion (at full
$n_\text{head}$ dimensionality) to avoid recomputing the grouped repetition on each step.
\textbf{Practical recommendation.} Users should select the model based on their primary
use case: Dream for math, code, and factual queries; LLaDA for translation and
conversational tasks. Both outperform \texttt{llama.cpp} on 5--6 of 8 prompts.
\section{Limitations} \section{Limitations}
We are transparent about the limitations of this work. We are transparent about the limitations of this work.
\textbf{Model quality.} LLaDA-8B produces noticeably lower-quality outputs than \textbf{Model quality.} Both LLaDA-8B and Dream-7B produce lower-quality outputs than
Llama-3-8B. We observed repetitions (``the and and molecules''), incomplete outputs on their AR counterparts (Llama-3-8B, Qwen2.5-7B). LLaDA shows occasional repetitions and
code prompts, and mediocre translations. The throughput comparison is between paradigms, incomplete code; Dream produces higher-quality math and code but sometimes generates
not quality-equivalent models. A fair comparison would require a diffusion model trained hallucinated content. The throughput comparison is between paradigms, not
to match Llama-3-8B quality, which does not yet exist. quality-equivalent models.
\textbf{Different models.} We compare LLaDA-8B (diffusion) against Llama-3-8B \textbf{Different models.} We compare dLLMs (LLaDA-8B, Dream-7B) against AR models
(autoregressive). These share the same parameter count and Llama backbone architecture (Llama-3-8B). These share similar parameter counts and backbone architectures but differ
but differ in training procedure, data, and generation mechanism. The comparison in training procedure, data, and generation mechanism. The comparison demonstrates the
demonstrates the \emph{computational} regime inversion, not a head-to-head model quality \emph{computational} regime inversion, not a head-to-head model quality contest.
contest.
\textbf{Generation buffer asymmetry.} Dream benchmarks use $B$=64 tokens while LLaDA
uses $B$=256. This reflects practical constraints (Dream's Qwen2.5 tokenizer produces
shorter outputs) but means the per-token throughput comparison is not perfectly
controlled. Dream would likely achieve higher throughput at $B$=256.
\textbf{Prior art on scheduling.} Entropy-based scheduling is not novel. \textbf{Prior art on scheduling.} Entropy-based scheduling is not novel.
Prophet~\cite{li2025}, EAGS~\cite{koh2024}, and Fast-dLLM~\cite{wu2025} proposed Prophet~\cite{li2025}, EAGS~\cite{koh2024}, and Fast-dLLM~\cite{wu2025} proposed
@@ -656,7 +729,9 @@ demonstrates that significant speedups are achievable through caching strategies
Further optimizations remain unexplored: bidirectional Flash Attention~\cite{dao2022} Further optimizations remain unexplored: bidirectional Flash Attention~\cite{dao2022}
adapted for non-causal masks, delta attention (recomputing only changed hidden state adapted for non-causal masks, delta attention (recomputing only changed hidden state
contributions), batched inference for serving workloads, generation buffers beyond 256 contributions), batched inference for serving workloads, generation buffers beyond 256
tokens, and support for additional architectures (SEDD, MDLM). tokens, and support for additional architectures (SEDD, MDLM). Dream-7B's GQA
architecture also opens the possibility of a more memory-efficient inter-step cache
that stores K,V at the reduced KV-head dimensionality rather than post-expansion.
\textbf{Better diffusion models.} The regime inversion becomes practically relevant when \textbf{Better diffusion models.} The regime inversion becomes practically relevant when
dLLM quality matches AR models. Investment in larger, better-trained diffusion models dLLM quality matches AR models. Investment in larger, better-trained diffusion models
@@ -673,15 +748,15 @@ CPUs, however, the computational regime inverts: AR inference hits a hard bandwi
ceiling while diffusion inference scales with available compute. ceiling while diffusion inference scales with available compute.
We demonstrated this empirically with \texttt{diffuse-cpp}, the first C++ inference We demonstrated this empirically with \texttt{diffuse-cpp}, the first C++ inference
engine for diffusion LLMs. On an AMD EPYC 12-core CPU, thread scaling reaches engine for diffusion LLMs, supporting two architectures: LLaDA-8B (Llama/MHA) and
Dream-7B (Qwen2.5/GQA). On an AMD EPYC 12-core CPU, thread scaling reaches
$7.4\times$ for diffusion versus $2.4\times$ for AR. With Q4\_K\_M quantization, $7.4\times$ for diffusion versus $2.4\times$ for AR. With Q4\_K\_M quantization,
entropy-exit scheduling, inter-step KV cache, and 256-token generation, entropy-exit scheduling, and inter-step KV cache, \texttt{diffuse-cpp} achieves
\texttt{diffuse-cpp} achieves 15--28~tok/s on real prompts---up to $3.2\times$ faster 14--28~tok/s on easy prompts---up to $3.3\times$ faster than \texttt{llama.cpp}'s
than \texttt{llama.cpp}'s 8.51~tok/s on the same hardware, with 6 of 8 prompts 8.51~tok/s on the same hardware. The two models exhibit complementary strengths:
outperforming the AR baseline. The inter-step cache provides $1.6\times$ average Dream excels at math and code (21.6~tok/s), while LLaDA excels at translation
speedup with no quality degradation. Increasing the generation buffer from 64 to 256 (27.7~tok/s). The inter-step cache provides $1.6\times$ average speedup with no quality
tokens reduces per-token cost by 20\%, confirming that diffusion's advantage amplifies degradation.
with sequence length.
The contribution is not a claim that diffusion is universally faster. It is the The contribution is not a claim that diffusion is universally faster. It is the
identification and empirical validation of a hardware-dependent regime inversion, and the identification and empirical validation of a hardware-dependent regime inversion, and the
@@ -695,7 +770,8 @@ The code, models, benchmark data, and this paper are publicly available under op
This work was inspired by the GGML library and llama.cpp~\cite{gerganov2023b}. The This work was inspired by the GGML library and llama.cpp~\cite{gerganov2023b}. The
entropy-exit scheduler builds on ideas from Prophet~\cite{li2025} and the entropy-exit scheduler builds on ideas from Prophet~\cite{li2025} and the
entropy-adaptive scheduling literature~\cite{koh2024,wu2025}. Figures~1--3 were entropy-adaptive scheduling literature~\cite{koh2024,wu2025}. Dream support was
developed using the architecture specifications from~\cite{ye2025}. Figures~1--3 were
generated with Matplotlib. generated with Matplotlib.
@@ -766,6 +842,13 @@ Chengyue Wu, Hao Zhang, Shuchen Xue, Zhijian Liu, Shizhe Diao, Ligeng Zhu,
cache and parallel decoding. cache and parallel decoding.
\newblock \emph{arXiv preprint arXiv:2505.22618}, 2025. \newblock \emph{arXiv preprint arXiv:2505.22618}, 2025.
\bibitem[Ye et~al.(2025)]{ye2025}
Jiacheng Ye, Shansan Gong, Liheng Chen, Lin Zheng, Mukai Li, Thong Nguyen,
Kaiyan Zhang, Shuicheng Yan, Silvio Savarese, Caiming Xiong, and Yingbo Zhou.
\newblock Dream 7B -- Scalable generation of structured and unstructured content
from diffusion language modeling.
\newblock \emph{arXiv preprint arXiv:2504.16915}, 2025.
\end{thebibliography} \end{thebibliography}
+168
View File
@@ -0,0 +1,168 @@
#pragma once
#include "diffuse-common.h"
#include <vector>
#include <cstring>
// ── 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.
//
// Also holds persistent compute resources (buffer, threadpool, work data)
// to avoid malloc/free and thread creation overhead each decode step.
struct ggml_threadpool; // forward declaration
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)
// ── 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]
std::vector<std::vector<float>> K; // K[layer]
std::vector<std::vector<float>> V; // V[layer]
// ── Persistent compute resources (avoid malloc/free per step) ──
void * compute_buf = nullptr; // pre-allocated GGML context buffer
size_t compute_buf_size = 0;
uint8_t * work_buf = nullptr; // pre-allocated graph work buffer
size_t work_buf_size = 0;
struct ggml_threadpool * threadpool = nullptr; // persistent thread pool
// ── 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();
skip_layers.clear();
layer_impact.clear();
n_past = 0;
sliding_window = 0;
initialized = false;
free_compute_resources();
}
void free_compute_resources() {
if (compute_buf) { free(compute_buf); compute_buf = nullptr; compute_buf_size = 0; }
if (work_buf) { free(work_buf); work_buf = nullptr; work_buf_size = 0; }
// threadpool freed externally (owned by caller who created it)
threadpool = nullptr;
}
// 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);
}
// ── Ensure compute buffer is large enough ─────────────────────
void ensure_compute_buf(size_t needed) {
if (needed <= compute_buf_size) return;
free(compute_buf);
compute_buf_size = needed;
compute_buf = malloc(compute_buf_size);
if (!compute_buf) {
DIFFUSE_DIE("ar_kv_cache: failed to allocate compute buffer (%zu MB)",
compute_buf_size / (1024 * 1024));
}
}
// ── Ensure work buffer is large enough ────────────────────────
void ensure_work_buf(size_t needed) {
if (needed <= work_buf_size) return;
free(work_buf);
work_buf_size = needed;
work_buf = (uint8_t *)malloc(work_buf_size);
if (!work_buf) {
DIFFUSE_DIE("ar_kv_cache: failed to allocate work buffer (%zu MB)",
work_buf_size / (1024 * 1024));
}
}
// ── 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);
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(); }
};
+507
View File
@@ -0,0 +1,507 @@
#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;
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 ggml_flash_attn_ext for fused attention (handles GQA natively).
// 1. Causal mask via F16 mask tensor + flash attention kernel
// 2. KV cache append (only compute new tokens' K,V)
// 3. RoPE with absolute positions (n_past + i)
// 4. No GQA expansion needed (flash_attn broadcasts n_head_kv → n_head)
//
// 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,
bool profile = false) {
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 (F16 for ggml_flash_attn_ext) ──────
// Shape: [n_kv, n_new] — broadcasts over heads and batch dims
// 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_F16, n_kv, n_new);
ggml_set_name(attn_mask, "attn_mask");
ggml_set_input(attn_mask);
{
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++) {
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;
}
}
}
// ── Embedding lookup ─────────────────────────────────────────
struct ggml_tensor * cur = ggml_get_rows(ctx, model.tok_embd, inp_tokens);
// Profile tensors collected here, added to graph after main forward
std::vector<struct ggml_tensor *> profile_tensors;
// ── 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;
// 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) {
// Zero-copy: point GGML tensor directly at cache memory
// 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);
K_cached->data = (void *)cache->k_data(il);
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);
V_cached->data = (void *)cache->v_data(il);
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]
// ── Flash Attention (fused, handles GQA natively) ─────────
// ggml_flash_attn_ext expects:
// Q: [n_embd_head, n_new, n_head, 1]
// K: [n_embd_head, n_kv, n_head_kv, 1]
// V: [n_embd_head, n_kv, n_head_kv, 1] (NOT transposed, contiguous)
// mask: [n_kv, n_new, 1, 1] (F16)
// result: [n_embd_head, n_head, n_new, 1] (already permuted)
//
// GQA broadcast: n_head % n_head_kv == 0 → handled by kernel
// 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_kv, n_kv] → [n_embd_head, n_kv, n_head_kv]
K_full = ggml_permute(ctx, K_full, 0, 2, 1, 3);
// V: same permutation, must be contiguous
V_full = ggml_cont(ctx, ggml_permute(ctx, V_full, 0, 2, 1, 3));
float scale = 1.0f / sqrtf((float)n_embd_head);
struct ggml_tensor * attn_out = ggml_flash_attn_ext(
ctx, Q, K_full, V_full, attn_mask,
scale, 0.0f, 0.0f);
// Result: [n_embd_head, n_head, n_new, 1] → [n_embd, n_new]
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);
// 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);
profile_tensors.push_back(dsq);
}
}
// ── 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);
// Add profiling tensors to forward graph (they depend on layer outputs
// already in the graph, so only sub/sqr/sum nodes get added)
for (auto * pt : profile_tensors) {
ggml_build_forward_expand(gf, pt);
}
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,
bool profile = false) {
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 ────────────────────────────────────
// flash_attn_ext: no GQA expansion, no full attention matrix materialization
size_t per_layer = (size_t)n_new * hp.n_embd * sizeof(float) * 10 // QKV proj + norms
+ (size_t)n_new * hp.n_ff * sizeof(float) * 3 // FFN (gate, up, down)
// 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
// K,V full (with new): [n_embd_head, n_head_kv, n_kv] × 2 (permuted + cont)
+ (size_t)n_kv * hp.n_embd_head() * hp.n_head_kv * sizeof(float) * 4
// flash_attn working memory (per-thread)
+ (size_t)hp.n_embd_head() * sizeof(float) * 4 * ctx->n_threads
+ 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 (F16) + positions
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);
// Use persistent compute buffer if available (avoids malloc/free each step)
cache->ensure_compute_buf(buf_size);
struct ggml_init_params cparams = {
/*.mem_size = */ cache->compute_buf_size,
/*.mem_buffer = */ cache->compute_buf,
/*.no_alloc = */ false,
};
struct ggml_context * ctx_compute = ggml_init(cparams);
if (!ctx_compute) {
DIFFUSE_LOG("ar_forward: failed to init 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, profile);
// Use persistent threadpool + work buffer for graph compute
struct ggml_cplan plan = ggml_graph_plan(gf, ctx->n_threads, cache->threadpool);
if (plan.work_size > 0) {
cache->ensure_work_buf(plan.work_size);
plan.work_data = cache->work_buf;
}
enum ggml_status status = ggml_graph_compute(gf, &plan);
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 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;
}
// ── 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);
}
// ── Public API: Batch forward (no cache reset) ──────────────────
// Used by speculative decoding to verify K candidate tokens at once.
bool ar_forward_batch(
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_batch: cache not initialized");
return false;
}
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 = %.6e%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;
}
+50
View File
@@ -0,0 +1,50 @@
#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);
// Batch: process N tokens with existing KV cache (no reset).
// Used for speculative decoding verification: target verifies K draft tokens at once.
// tokens: [n_tokens], logits_out: [n_tokens * n_vocab]
bool ar_forward_batch(
diffuse_context * ctx,
const int32_t * tokens,
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);
+314
View File
@@ -0,0 +1,314 @@
#include "ar-sampler.h"
#include "ar-graph.h"
#include "ggml-cpu.h"
#include <algorithm>
#include <numeric>
#include <random>
#include <cmath>
#include <chrono>
// ── 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<float> tmp(logits, logits + n_vocab);
std::nth_element(tmp.begin(), tmp.begin() + top_k, tmp.end(),
std::greater<float>());
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<int> 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<int32_t> & 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<int32_t> & 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<float> 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<int> dist(probs.begin(), probs.end());
return dist(rng);
}
// ── Main autoregressive generation loop ─────────────────────────
std::vector<int32_t> ar_generate(
diffuse_context * ctx,
const std::vector<int32_t> & 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);
// Create persistent threadpool (reused across all decode steps)
{
struct ggml_threadpool_params tparams = ggml_threadpool_params_default(ctx->n_threads);
tparams.strict_cpu = true; // bind threads to cores
tparams.prio = GGML_SCHED_PRIO_HIGH;
cache.threadpool = ggml_threadpool_new(&tparams);
if (cache.threadpool) {
DIFFUSE_LOG(" threadpool: %d threads (persistent, high priority)",
ctx->n_threads);
}
}
// RNG
std::mt19937 rng(params.seed);
// Logits buffer
std::vector<float> 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;
// 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 (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();
prefill_ms = std::chrono::duration<double, std::milli>(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<int32_t> generated;
generated.reserve(max_tokens);
// Recent tokens for repeat penalty (start with prompt tail)
std::vector<int32_t> 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<float> 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<float> 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<double, std::milli>(decode_end - decode_start).count();
}
done:
// ── Timing summary ───────────────────────────────────────────
auto gen_end = clk::now();
double total_ms = std::chrono::duration<double, std::milli>(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));
// Free threadpool before clearing cache
if (cache.threadpool) {
ggml_threadpool_free(cache.threadpool);
cache.threadpool = nullptr;
}
cache.clear();
return generated;
}
+8
View File
@@ -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.
+397
View File
@@ -0,0 +1,397 @@
#include "ar-speculative.h"
#include "ar-graph.h"
#include "diffuse.h"
#include "ggml-cpu.h"
#include <algorithm>
#include <chrono>
#include <cmath>
#include <vector>
// ── Helpers ─────────────────────────────────────────────────────
static int32_t argmax(const float * logits, int n) {
int best = 0;
float best_val = logits[0];
for (int i = 1; i < n; i++) {
if (logits[i] > best_val) {
best_val = logits[i];
best = i;
}
}
return best;
}
// Qwen2.5 family EOS tokens
static bool is_eos_token(int32_t token) {
return token == 151643 || token == 151645 || token == 151644;
}
// ── Speculative Generation with Deferred Bonus ──────────────────
//
// Key optimization: instead of decoding the bonus token on the target
// as a separate forward pass (~540ms for bandwidth-bound 32B model),
// we defer it to the NEXT iteration's batch. Each batch is:
//
// [pending_bonus, draft_d1, draft_d2, ..., draft_dK] (K+1 tokens)
//
// The causal mask ensures batch_logits[0] depends only on context +
// pending (not on d1..dK), so verification is correct.
//
// This eliminates 1 target forward per iteration:
// Before: 1 batch + 1 decode = 2 forwards per iteration
// After: 1 batch = 1 forward per iteration
//
// The target and draft caches stay 1 position apart (draft has the
// pending token decoded, target doesn't until the next batch).
std::vector<int32_t> ar_speculative_generate(
diffuse_context * target_ctx,
diffuse_context * draft_ctx,
const std::vector<int32_t> & prompt_tokens,
int max_tokens,
const ar_spec_params & params,
ar_token_callback callback,
ar_spec_stats * stats_out) {
const auto & t_hp = target_ctx->model->hparams;
const auto & d_hp = draft_ctx->model->hparams;
const int t_vocab = (int)t_hp.n_vocab;
const int d_vocab = (int)d_hp.n_vocab;
const int prompt_len = (int)prompt_tokens.size();
const int total_ctx = prompt_len + max_tokens + params.K + 4;
const int K = std::max(params.K, 1);
DIFFUSE_LOG("speculative: target=%dL/%dH/%dKV vocab=%d, draft=%dL/%dH/%dKV vocab=%d, K=%d",
(int)t_hp.n_layer, (int)t_hp.n_head, (int)t_hp.n_head_kv, t_vocab,
(int)d_hp.n_layer, (int)d_hp.n_head, (int)d_hp.n_head_kv, d_vocab, K);
// ── Init KV caches ──────────────────────────────────────────
ar_kv_cache target_cache, draft_cache;
target_cache.init(total_ctx, (int)t_hp.n_layer,
(int)t_hp.n_embd_head(), (int)t_hp.n_head_kv);
draft_cache.init(total_ctx, (int)d_hp.n_layer,
(int)d_hp.n_embd_head(), (int)d_hp.n_head_kv);
// ── Persistent threadpools ──────────────────────────────────
{
auto tp = ggml_threadpool_params_default(target_ctx->n_threads);
tp.strict_cpu = true;
tp.prio = GGML_SCHED_PRIO_HIGH;
target_cache.threadpool = ggml_threadpool_new(&tp);
DIFFUSE_LOG(" target: %d threads, %dL, %d KV heads, %d dim",
target_ctx->n_threads, (int)t_hp.n_layer,
(int)t_hp.n_head_kv, (int)t_hp.n_embd_head());
}
{
auto tp = ggml_threadpool_params_default(draft_ctx->n_threads);
tp.strict_cpu = true;
tp.prio = GGML_SCHED_PRIO_NORMAL;
draft_cache.threadpool = ggml_threadpool_new(&tp);
DIFFUSE_LOG(" draft: %d threads, %dL, %d KV heads, %d dim",
draft_ctx->n_threads, (int)d_hp.n_layer,
(int)d_hp.n_head_kv, (int)d_hp.n_embd_head());
}
ar_spec_stats stats = {};
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();
// 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");
}
auto t1 = clk::now();
stats.prefill_ms = std::chrono::duration<double, std::milli>(t1 - t0).count();
DIFFUSE_LOG(" prefill: %d tokens in %.1f ms (%.1f tok/s)",
prompt_len, stats.prefill_ms,
1000.0 * prompt_len / std::max(stats.prefill_ms, 0.1));
}
// ── Sample first token from target prefill logits ───────────
std::vector<int32_t> generated;
generated.reserve(max_tokens);
int32_t first_token = argmax(
t_prefill_logits.data() + (size_t)(prompt_len - 1) * t_vocab, t_vocab);
// Free prefill buffer
t_prefill_logits.clear();
t_prefill_logits.shrink_to_fit();
generated.push_back(first_token);
stats.total_generated++;
if (callback && !callback(first_token, prompt_len)) {
goto cleanup;
}
if (is_eos_token(first_token)) {
DIFFUSE_LOG(" EOS at first token (%d)", first_token);
goto cleanup;
}
// ── Deferred bonus: DON'T decode first_token on target ──────
// Instead, set it as pending and include it in the first batch.
// This saves one target forward (~540ms for 32B).
//
// Only decode on draft (fast, ~12ms) to get prev_draft_logits.
{
std::vector<float> prev_draft_logits(d_vocab);
if (!ar_forward_decode(draft_ctx, first_token,
&draft_cache, prev_draft_logits.data())) {
DIFFUSE_DIE("speculative: draft decode first token failed");
}
// State:
// target_cache.n_past = prompt_len (first_token NOT decoded)
// draft_cache.n_past = prompt_len + 1 (first_token decoded)
// pending = first_token
int32_t pending = first_token;
// ── Main speculative loop ───────────────────────────────
auto decode_start = clk::now();
std::vector<float> draft_logits_buf(d_vocab);
std::vector<float> target_batch_logits;
std::vector<int32_t> candidates;
std::vector<int32_t> batch_tokens;
candidates.reserve(K);
batch_tokens.reserve(K + 1);
while ((int)generated.size() < max_tokens) {
int remaining = max_tokens - (int)generated.size();
int k = std::min(K, remaining);
int target_P = target_cache.n_past;
// Invariant: draft_cache.n_past == target_P + 1
// ── Phase 1: Draft generates k candidates ───────────
candidates.clear();
{
// First candidate from prev_draft_logits
candidates.push_back(argmax(prev_draft_logits.data(), d_vocab));
// Remaining: decode on draft and sample
for (int i = 1; i < k; i++) {
if (!ar_forward_decode(draft_ctx, candidates[i - 1],
&draft_cache, draft_logits_buf.data())) {
DIFFUSE_LOG("speculative: draft decode failed at candidate %d", i);
goto loop_done;
}
candidates.push_back(argmax(draft_logits_buf.data(), d_vocab));
}
stats.total_draft_tokens += k;
}
// draft_cache.n_past = (target_P + 1) + (k - 1) = target_P + k
// ── Phase 2: Target batch [pending, d1..dk] ─────────
//
// K+1 tokens total. Logits layout:
// batch_logits[0]: after pending → verify d1
// batch_logits[1]: after d1 → verify d2
// ...
// batch_logits[k]: after dk → bonus if all accepted
//
// Causal mask ensures batch_logits[i] depends only on
// context + pending + d1..di (not future draft tokens).
{
batch_tokens.clear();
batch_tokens.push_back(pending);
batch_tokens.insert(batch_tokens.end(),
candidates.begin(), candidates.end());
int batch_size = 1 + k;
target_batch_logits.resize((size_t)batch_size * t_vocab);
if (!ar_forward_batch(target_ctx, batch_tokens.data(), batch_size,
&target_cache, target_batch_logits.data())) {
DIFFUSE_LOG("speculative: target batch failed");
goto loop_done;
}
stats.total_target_batches++;
// target_cache.n_past = target_P + batch_size = target_P + 1 + k
}
// ── Phase 3: Verify candidates ──────────────────────
{
int n_accepted = 0;
// Verify d_i against batch_logits[i-1]
// batch_logits[0] = after pending → predicts d1
// batch_logits[1] = after d1 → predicts d2
// ...
for (int i = 0; i < k; i++) {
float * bl = target_batch_logits.data()
+ (size_t)i * t_vocab;
if (argmax(bl, t_vocab) == candidates[i]) {
n_accepted++;
} else {
break;
}
}
// Bonus: target's prediction after the last accepted token
// n_accepted=0 → bonus from batch_logits[0] (after pending)
// n_accepted=J → bonus from batch_logits[J] (after d_J)
// n_accepted=k → bonus from batch_logits[k] (after d_k)
int32_t bonus = argmax(
target_batch_logits.data() + (size_t)n_accepted * t_vocab,
t_vocab);
stats.total_accepted += n_accepted;
if (n_accepted == 0) stats.total_fast_rejects++;
// Rollback target: keep pending + accepted candidates
// target was at target_P + 1 + k, we want target_P + 1 + n_accepted
target_cache.n_past = target_P + 1 + n_accepted;
// ── Output accepted tokens ──────────────────────
for (int i = 0; i < n_accepted; i++) {
if ((int)generated.size() >= max_tokens) goto loop_done;
generated.push_back(candidates[i]);
stats.total_generated++;
if (callback && !callback(candidates[i],
prompt_len + (int)generated.size() - 1)) {
goto loop_done;
}
if (is_eos_token(candidates[i])) {
goto loop_done;
}
}
// ── Output bonus ────────────────────────────────
if ((int)generated.size() < max_tokens) {
generated.push_back(bonus);
stats.total_generated++;
if (callback && !callback(bonus,
prompt_len + (int)generated.size() - 1)) {
goto loop_done;
}
if (is_eos_token(bonus)) {
goto loop_done;
}
}
// ── Sync draft: rollback + decode bonus ─────────
//
// draft was at target_P + k (from generating k-1 decodes)
// target is now at target_P + 1 + n_accepted
// We need draft at target_P + 1 + n_accepted,
// then decode bonus → draft at target_P + 2 + n_accepted
//
// delta = (target_P + k) - (target_P + 1 + n_accepted)
// = k - 1 - n_accepted
//
// k-1-n > 0: rollback draft
// k-1-n = 0: nothing
// k-1-n < 0: advance (decode candidates[k-1])
{
int draft_current = target_P + k;
int draft_target = target_P + 1 + n_accepted;
if (draft_current > draft_target) {
draft_cache.n_past = draft_target;
} else if (draft_current < draft_target) {
// n_accepted == k: decode the last candidate
if (!ar_forward_decode(draft_ctx, candidates[k - 1],
&draft_cache,
draft_logits_buf.data())) {
DIFFUSE_LOG("speculative: draft decode last candidate failed");
goto loop_done;
}
}
// Decode bonus on draft → get prev_draft_logits
if (!ar_forward_decode(draft_ctx, bonus,
&draft_cache,
prev_draft_logits.data())) {
DIFFUSE_LOG("speculative: draft decode bonus failed");
goto loop_done;
}
}
// Set pending for next iteration (deferred bonus)
pending = bonus;
DIFFUSE_LOG(" spec: k=%d accepted=%d bonus=%d (%.0f%%) [deferred]",
k, n_accepted, bonus,
k > 0 ? 100.0f * n_accepted / k : 0.0f);
}
}
loop_done:
auto decode_end = clk::now();
stats.decode_ms = std::chrono::duration<double, std::milli>(
decode_end - decode_start).count();
}
// ── Report ──────────────────────────────────────────────────
{
auto gen_end = clk::now();
double total_ms = std::chrono::duration<double, std::milli>(
gen_end - gen_start).count();
int total_target = stats.total_target_batches + stats.total_target_decodes;
DIFFUSE_LOG("=== SPECULATIVE GENERATION COMPLETE ===");
DIFFUSE_LOG(" prefill: %.1f ms (%d tok, %.1f tok/s)",
stats.prefill_ms, prompt_len,
1000.0 * prompt_len / std::max(stats.prefill_ms, 0.1));
DIFFUSE_LOG(" decode: %.1f ms (%d tok, %.2f tok/s)",
stats.decode_ms, stats.total_generated,
stats.total_generated > 0
? 1000.0 * stats.total_generated / stats.decode_ms
: 0.0);
DIFFUSE_LOG(" acceptance: %d/%d (%.1f%%)",
stats.total_accepted, stats.total_draft_tokens,
100.0f * stats.acceptance_rate());
DIFFUSE_LOG(" d1 rejects: %d (no bonus saved — deferred mode)",
stats.total_fast_rejects);
DIFFUSE_LOG(" target calls: %d batches + %d decodes = %d total",
stats.total_target_batches, stats.total_target_decodes,
total_target);
DIFFUSE_LOG(" effective: %.2f tok/target_call (deferred bonus)",
stats.tokens_per_target_call());
DIFFUSE_LOG(" total: %.1f ms", total_ms);
}
cleanup:
if (stats_out) *stats_out = stats;
if (target_cache.threadpool) {
ggml_threadpool_free(target_cache.threadpool);
target_cache.threadpool = nullptr;
}
if (draft_cache.threadpool) {
ggml_threadpool_free(draft_cache.threadpool);
draft_cache.threadpool = nullptr;
}
target_cache.clear();
draft_cache.clear();
return generated;
}
+9
View File
@@ -0,0 +1,9 @@
#pragma once
// Speculative decoding implementation header.
// Public types (ar_spec_params, ar_spec_stats, ar_speculative_generate)
// are declared in include/diffuse.h.
// This header adds internal includes needed by the implementation.
#include "diffuse-common.h"
#include "ar-cache.h"
+6
View File
@@ -36,6 +36,11 @@ struct diffuse_layer {
struct ggml_tensor * wv; // V projection struct ggml_tensor * wv; // V projection
struct ggml_tensor * wo; // output projection struct ggml_tensor * wo; // output projection
// QKV biases (optional, nullptr for models without them e.g. LLaDA)
struct ggml_tensor * bq = nullptr; // Q bias (Dream/Qwen2.5)
struct ggml_tensor * bk = nullptr; // K bias
struct ggml_tensor * bv = nullptr; // V bias
// FFN (SwiGLU) // FFN (SwiGLU)
struct ggml_tensor * ffn_norm; // RMSNorm weight struct ggml_tensor * ffn_norm; // RMSNorm weight
struct ggml_tensor * ffn_gate; // gate projection (w1) struct ggml_tensor * ffn_gate; // gate projection (w1)
@@ -46,6 +51,7 @@ struct diffuse_layer {
// ── Full model struct ────────────────────────────────────────── // ── Full model struct ──────────────────────────────────────────
struct diffuse_model { struct diffuse_model {
diffuse_hparams hparams; diffuse_hparams hparams;
std::string model_type; // "llada", "dream", etc. (from GGUF metadata)
// Embeddings // Embeddings
struct ggml_tensor * tok_embd; // token embeddings struct ggml_tensor * tok_embd; // token embeddings
+51 -8
View File
@@ -1,5 +1,12 @@
#include "diffuse-graph.h" #include "diffuse-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 transformer forward graph ──────────────────────────── // ── Build transformer forward graph ────────────────────────────
struct ggml_cgraph * diffuse_build_graph( struct ggml_cgraph * diffuse_build_graph(
diffuse_context * dctx, diffuse_context * dctx,
@@ -55,6 +62,11 @@ struct ggml_cgraph * diffuse_build_graph(
struct ggml_tensor * K = ggml_mul_mat(ctx, layer.wk, cur); struct ggml_tensor * K = ggml_mul_mat(ctx, layer.wk, cur);
struct ggml_tensor * V = ggml_mul_mat(ctx, layer.wv, cur); struct ggml_tensor * V = ggml_mul_mat(ctx, layer.wv, cur);
// Add QKV biases if present (Dream/Qwen2.5)
if (layer.bq) Q = ggml_add(ctx, Q, ensure_f32(ctx, layer.bq));
if (layer.bk) K = ggml_add(ctx, K, ensure_f32(ctx, layer.bk));
if (layer.bv) V = ggml_add(ctx, V, ensure_f32(ctx, layer.bv));
// Reshape for multi-head: [n_embd_head, n_head, N] // Reshape for multi-head: [n_embd_head, n_head, N]
Q = ggml_reshape_3d(ctx, Q, n_embd_head, n_head, N); Q = ggml_reshape_3d(ctx, Q, n_embd_head, n_head, N);
K = ggml_reshape_3d(ctx, K, n_embd_head, n_head_kv, N); K = ggml_reshape_3d(ctx, K, n_embd_head, n_head_kv, N);
@@ -66,12 +78,20 @@ struct ggml_cgraph * diffuse_build_graph(
K = ggml_rope_ext(ctx, K, inp_pos, nullptr, n_embd_head, K = ggml_rope_ext(ctx, K, inp_pos, nullptr, n_embd_head,
GGML_ROPE_TYPE_NEOX, 0, hp.rope_theta, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f); GGML_ROPE_TYPE_NEOX, 0, hp.rope_theta, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f);
// GQA: repeat K, V heads if n_head_kv < n_head // GQA: repeat each KV head n_rep times (grouped, not interleaved)
// Reshape 3D→4D so ggml_repeat expands the right axis, then flatten back.
// K[d, n_kv, N] → K[d, 1, n_kv, N] → repeat → K[d, n_rep, n_kv, N] → K[d, n_head, N]
if (n_head_kv < n_head) { if (n_head_kv < n_head) {
const int n_rep = n_head / n_head_kv;
K = ggml_reshape_4d(ctx, K, n_embd_head, 1, n_head_kv, N);
K = ggml_repeat(ctx, K, K = ggml_repeat(ctx, K,
ggml_new_tensor_3d(ctx, K->type, n_embd_head, n_head, N)); ggml_new_tensor_4d(ctx, K->type, n_embd_head, n_rep, n_head_kv, N));
K = ggml_reshape_3d(ctx, K, n_embd_head, n_head, N);
V = ggml_reshape_4d(ctx, V, n_embd_head, 1, n_head_kv, N);
V = ggml_repeat(ctx, V, V = ggml_repeat(ctx, V,
ggml_new_tensor_3d(ctx, V->type, n_embd_head, n_head, N)); ggml_new_tensor_4d(ctx, V->type, n_embd_head, n_rep, n_head_kv, N));
V = ggml_reshape_3d(ctx, V, n_embd_head, n_head, N);
} }
// Permute Q, K: [n_embd_head, n_head, N] → [n_embd_head, N, n_head] // Permute Q, K: [n_embd_head, n_head, N] → [n_embd_head, N, n_head]
@@ -193,6 +213,11 @@ static struct ggml_cgraph * diffuse_build_graph_extractable(
struct ggml_tensor * K = ggml_mul_mat(ctx, layer.wk, cur); struct ggml_tensor * K = ggml_mul_mat(ctx, layer.wk, cur);
struct ggml_tensor * V = ggml_mul_mat(ctx, layer.wv, cur); struct ggml_tensor * V = ggml_mul_mat(ctx, layer.wv, cur);
// Add QKV biases if present (Dream/Qwen2.5)
if (layer.bq) Q = ggml_add(ctx, Q, ensure_f32(ctx, layer.bq));
if (layer.bk) K = ggml_add(ctx, K, ensure_f32(ctx, layer.bk));
if (layer.bv) V = ggml_add(ctx, V, ensure_f32(ctx, layer.bv));
Q = ggml_reshape_3d(ctx, Q, n_embd_head, n_head, N); Q = ggml_reshape_3d(ctx, Q, n_embd_head, n_head, N);
K = ggml_reshape_3d(ctx, K, n_embd_head, n_head_kv, N); K = ggml_reshape_3d(ctx, K, n_embd_head, n_head_kv, N);
V = ggml_reshape_3d(ctx, V, n_embd_head, n_head_kv, N); V = ggml_reshape_3d(ctx, V, n_embd_head, n_head_kv, N);
@@ -202,11 +227,18 @@ static struct ggml_cgraph * diffuse_build_graph_extractable(
K = ggml_rope_ext(ctx, K, inp_pos, nullptr, n_embd_head, K = ggml_rope_ext(ctx, K, inp_pos, nullptr, n_embd_head,
GGML_ROPE_TYPE_NEOX, 0, hp.rope_theta, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f); GGML_ROPE_TYPE_NEOX, 0, hp.rope_theta, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f);
// GQA: repeat each KV head n_rep times (grouped, not interleaved)
if (n_head_kv < n_head) { if (n_head_kv < n_head) {
const int n_rep = n_head / n_head_kv;
K = ggml_reshape_4d(ctx, K, n_embd_head, 1, n_head_kv, N);
K = ggml_repeat(ctx, K, K = ggml_repeat(ctx, K,
ggml_new_tensor_3d(ctx, K->type, n_embd_head, n_head, N)); ggml_new_tensor_4d(ctx, K->type, n_embd_head, n_rep, n_head_kv, N));
K = ggml_reshape_3d(ctx, K, n_embd_head, n_head, N);
V = ggml_reshape_4d(ctx, V, n_embd_head, 1, n_head_kv, N);
V = ggml_repeat(ctx, V, V = ggml_repeat(ctx, V,
ggml_new_tensor_3d(ctx, V->type, n_embd_head, n_head, N)); ggml_new_tensor_4d(ctx, V->type, n_embd_head, n_rep, n_head_kv, N));
V = ggml_reshape_3d(ctx, V, n_embd_head, n_head, N);
} }
// ── Name K,V for cache extraction (BEFORE permute) ────── // ── Name K,V for cache extraction (BEFORE permute) ──────
@@ -420,6 +452,11 @@ struct ggml_cgraph * diffuse_build_graph_cached(
struct ggml_tensor * K_active = ggml_mul_mat(ctx, layer.wk, cur); struct ggml_tensor * K_active = ggml_mul_mat(ctx, layer.wk, cur);
struct ggml_tensor * V_active = ggml_mul_mat(ctx, layer.wv, cur); struct ggml_tensor * V_active = ggml_mul_mat(ctx, layer.wv, cur);
// Add QKV biases if present (Dream/Qwen2.5)
if (layer.bq) Q_active = ggml_add(ctx, Q_active, ensure_f32(ctx, layer.bq));
if (layer.bk) K_active = ggml_add(ctx, K_active, ensure_f32(ctx, layer.bk));
if (layer.bv) V_active = ggml_add(ctx, V_active, ensure_f32(ctx, layer.bv));
// Reshape: [n_embd, n_active] → [n_embd_head, n_head(_kv), n_active] // Reshape: [n_embd, n_active] → [n_embd_head, n_head(_kv), n_active]
Q_active = ggml_reshape_3d(ctx, Q_active, n_embd_head, n_head, n_active); Q_active = ggml_reshape_3d(ctx, Q_active, n_embd_head, n_head, n_active);
K_active = ggml_reshape_3d(ctx, K_active, n_embd_head, n_head_kv, n_active); K_active = ggml_reshape_3d(ctx, K_active, n_embd_head, n_head_kv, n_active);
@@ -431,12 +468,18 @@ struct ggml_cgraph * diffuse_build_graph_cached(
K_active = ggml_rope_ext(ctx, K_active, inp_pos, nullptr, n_embd_head, K_active = ggml_rope_ext(ctx, K_active, inp_pos, nullptr, n_embd_head,
GGML_ROPE_TYPE_NEOX, 0, hp.rope_theta, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f); GGML_ROPE_TYPE_NEOX, 0, hp.rope_theta, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f);
// GQA expansion // GQA: repeat each KV head n_rep times (grouped, not interleaved)
if (n_head_kv < n_head) { if (n_head_kv < n_head) {
const int n_rep = n_head / n_head_kv;
K_active = ggml_reshape_4d(ctx, K_active, n_embd_head, 1, n_head_kv, n_active);
K_active = ggml_repeat(ctx, K_active, K_active = ggml_repeat(ctx, K_active,
ggml_new_tensor_3d(ctx, K_active->type, n_embd_head, n_head, n_active)); ggml_new_tensor_4d(ctx, K_active->type, n_embd_head, n_rep, n_head_kv, n_active));
K_active = ggml_reshape_3d(ctx, K_active, n_embd_head, n_head, n_active);
V_active = ggml_reshape_4d(ctx, V_active, n_embd_head, 1, n_head_kv, n_active);
V_active = ggml_repeat(ctx, V_active, V_active = ggml_repeat(ctx, V_active,
ggml_new_tensor_3d(ctx, V_active->type, n_embd_head, n_head, n_active)); ggml_new_tensor_4d(ctx, V_active->type, n_embd_head, n_rep, n_head_kv, n_active));
V_active = ggml_reshape_3d(ctx, V_active, n_embd_head, n_head, n_active);
} }
// ── Name K_active, V_active for extraction ────────────── // ── Name K_active, V_active for extraction ──────────────
+103 -15
View File
@@ -19,6 +19,57 @@ static float get_f32(const struct gguf_context * gctx, const char * key, float d
return gguf_get_val_f32(gctx, id); 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.
// required = true: die if not found and no default
// required = false: return def if not found
static uint32_t get_u32_multi(const struct gguf_context * gctx,
const char * suffix,
uint32_t def = 0,
bool required = true) {
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 (!required) 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 ─────────────────────────────────────── // ── Tensor lookup helper ───────────────────────────────────────
static struct ggml_tensor * get_tensor(struct ggml_context * ctx, const char * name) { static struct ggml_tensor * get_tensor(struct ggml_context * ctx, const char * name) {
struct ggml_tensor * t = ggml_get_tensor(ctx, name); struct ggml_tensor * t = ggml_get_tensor(ctx, name);
@@ -43,25 +94,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()); 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 * model = new diffuse_model();
auto & hp = model->hparams; auto & hp = model->hparams;
hp.n_layer = get_u32(gctx, "diffuse.block_count"); // Detect architecture
hp.n_head = get_u32(gctx, "diffuse.attention.head_count"); std::string arch = detect_arch_prefix(gctx);
hp.n_head_kv = get_u32(gctx, "diffuse.attention.head_count_kv"); DIFFUSE_LOG(" detected arch prefix: %s", arch.c_str());
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);
DIFFUSE_LOG(" arch: LLaDA (Llama backbone)"); hp.n_layer = get_u32_multi(gctx, "block_count");
DIFFUSE_LOG(" n_vocab=%u, n_embd=%u, n_head=%u, n_layer=%u, n_ff=%u", hp.n_head = get_u32_multi(gctx, "attention.head_count");
hp.n_vocab, hp.n_embd, hp.n_head, hp.n_layer, hp.n_ff); hp.n_head_kv = get_u32_multi(gctx, "attention.head_count_kv");
DIFFUSE_LOG(" mask_token_id=%u, rope_theta=%.0f", hp.mask_token_id, hp.rope_theta); 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", 0, false); // inferred from tensor if absent
hp.mask_token_id = get_u32_multi(gctx, "mask_token_id", 0, false); // 0 = no mask token (AR models)
hp.rope_theta = get_f32_multi(gctx, "rope.freq_base", 1000000.0f);
hp.rms_norm_eps = get_f32_multi(gctx, "attention.layer_norm_rms_epsilon", 1e-6f);
// 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 diffuse GGUF files
}
}
const char * arch_name = "unknown";
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(" 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 // The weight context is the one that gguf_init populated
model->ctx = meta_ctx; model->ctx = meta_ctx;
@@ -70,6 +146,13 @@ diffuse_model * diffuse_model_load_impl(const std::string & path, int n_threads)
model->tok_embd = get_tensor(meta_ctx, "token_embd.weight"); model->tok_embd = get_tensor(meta_ctx, "token_embd.weight");
model->output_norm = get_tensor(meta_ctx, "output_norm.weight"); model->output_norm = get_tensor(meta_ctx, "output_norm.weight");
// Infer n_vocab from token_embd if not in metadata
// In GGML: token_embd.weight has shape [n_embd, n_vocab] (ne[0]=n_embd, ne[1]=n_vocab)
if (hp.n_vocab == 0) {
hp.n_vocab = (uint32_t)model->tok_embd->ne[1];
DIFFUSE_LOG(" n_vocab inferred from token_embd: %u", hp.n_vocab);
}
// lm_head — may or may not be present (tied embeddings) // lm_head — may or may not be present (tied embeddings)
struct ggml_tensor * lm_head = ggml_get_tensor(meta_ctx, "output.weight"); struct ggml_tensor * lm_head = ggml_get_tensor(meta_ctx, "output.weight");
model->output = lm_head ? lm_head : model->tok_embd; model->output = lm_head ? lm_head : model->tok_embd;
@@ -87,6 +170,11 @@ diffuse_model * diffuse_model_load_impl(const std::string & path, int n_threads)
l.ffn_gate = get_tensor(meta_ctx, fmt_layer("blk.%d.ffn_gate.weight", i).c_str()); l.ffn_gate = get_tensor(meta_ctx, fmt_layer("blk.%d.ffn_gate.weight", i).c_str());
l.ffn_up = get_tensor(meta_ctx, fmt_layer("blk.%d.ffn_up.weight", i).c_str()); l.ffn_up = get_tensor(meta_ctx, fmt_layer("blk.%d.ffn_up.weight", i).c_str());
l.ffn_down = get_tensor(meta_ctx, fmt_layer("blk.%d.ffn_down.weight", i).c_str()); l.ffn_down = get_tensor(meta_ctx, fmt_layer("blk.%d.ffn_down.weight", i).c_str());
// Optional QKV biases (Dream/Qwen2.5 has them, LLaDA does not)
l.bq = ggml_get_tensor(meta_ctx, fmt_layer("blk.%d.attn_q.bias", i).c_str());
l.bk = ggml_get_tensor(meta_ctx, fmt_layer("blk.%d.attn_k.bias", i).c_str());
l.bv = ggml_get_tensor(meta_ctx, fmt_layer("blk.%d.attn_v.bias", i).c_str());
} }
DIFFUSE_LOG("model loaded: %lld tensors", DIFFUSE_LOG("model loaded: %lld tensors",
+32 -6
View File
@@ -68,6 +68,11 @@ std::vector<int32_t> diffuse_sample(
const int mask_id = hp.mask_token_id; const int mask_id = hp.mask_token_id;
const int n_vocab = hp.n_vocab; const int n_vocab = hp.n_vocab;
// Dream (Qwen2.5 backbone) uses shifted logits: output at position i
// predicts token at position i+1 (autoregressive convention).
// To get logits for position i, read from position max(i-1, 0).
const bool shift_logits = (ctx->model->model_type == "dream");
// Build initial sequence: prompt + MASK tokens // Build initial sequence: prompt + MASK tokens
std::vector<int32_t> seq = prompt_tokens; std::vector<int32_t> seq = prompt_tokens;
int prompt_len = (int)prompt_tokens.size(); int prompt_len = (int)prompt_tokens.size();
@@ -98,11 +103,15 @@ std::vector<int32_t> diffuse_sample(
const int cache_refresh = params.cache_refresh; const int cache_refresh = params.cache_refresh;
const int cache_keep_active = params.cache_keep_active; const int cache_keep_active = params.cache_keep_active;
const char * remasking_name =
params.remasking == diffuse_remasking::ENTROPY_EXIT ? "entropy_exit" :
params.remasking == diffuse_remasking::LOW_CONFIDENCE ? "low_confidence" :
params.remasking == diffuse_remasking::MASKGIT_PLUS ? "maskgit_plus" :
params.remasking == diffuse_remasking::TOPK_MARGIN ? "topk_margin" :
"random";
DIFFUSE_LOG("diffusion: %d steps, %d tokens to generate, scheduler=%s, cache=%s, refresh=%d, keep_active=%d", DIFFUSE_LOG("diffusion: %d steps, %d tokens to generate, scheduler=%s, cache=%s, refresh=%d, keep_active=%d",
params.n_steps, n_generate, params.n_steps, n_generate,
params.remasking == diffuse_remasking::ENTROPY_EXIT ? "entropy_exit" : remasking_name,
params.remasking == diffuse_remasking::LOW_CONFIDENCE ? "low_confidence" :
"random",
use_cache ? "ON" : "OFF", use_cache ? "ON" : "OFF",
cache_refresh, cache_keep_active); cache_refresh, cache_keep_active);
@@ -222,19 +231,28 @@ std::vector<int32_t> diffuse_sample(
for (int i = 0; i < total_len; i++) { for (int i = 0; i < total_len; i++) {
if (!is_masked[i]) continue; if (!is_masked[i]) continue;
const float * logit_row = logit_source + (size_t)i * n_vocab; // Dream: shifted logits (position i uses logits from position max(i-1, 0))
int logit_pos = shift_logits ? std::max(i - 1, 0) : i;
const float * logit_row = logit_source + (size_t)logit_pos * n_vocab;
float ent = compute_entropy(logit_row, n_vocab); float ent = compute_entropy(logit_row, n_vocab);
if (params.temperature <= 0.0f) { if (params.temperature <= 0.0f) {
// Find top-1 (and top-2 for TOPK_MARGIN)
int best = 0; int best = 0;
float best_val = logit_row[0]; float best_val = logit_row[0];
float second_val = -1e30f;
for (int v = 1; v < n_vocab; v++) { for (int v = 1; v < n_vocab; v++) {
if (logit_row[v] > best_val) { if (logit_row[v] > best_val) {
second_val = best_val;
best_val = logit_row[v]; best_val = logit_row[v];
best = v; best = v;
} else if (logit_row[v] > second_val) {
second_val = logit_row[v];
} }
} }
candidates.push_back({i, best, best_val, ent}); float conf = (params.remasking == diffuse_remasking::TOPK_MARGIN)
? (best_val - second_val) : best_val;
candidates.push_back({i, best, conf, ent});
} else { } else {
float max_logit = *std::max_element(logit_row, logit_row + n_vocab); float max_logit = *std::max_element(logit_row, logit_row + n_vocab);
std::vector<float> probs(n_vocab); std::vector<float> probs(n_vocab);
@@ -272,11 +290,19 @@ std::vector<int32_t> diffuse_sample(
n_unmask = std::max(n_unmask, n_easy); n_unmask = std::max(n_unmask, n_easy);
n_unmask = std::min(n_unmask, (int)candidates.size()); n_unmask = std::min(n_unmask, (int)candidates.size());
} else if (params.remasking == diffuse_remasking::LOW_CONFIDENCE) { } else if (params.remasking == diffuse_remasking::LOW_CONFIDENCE ||
params.remasking == diffuse_remasking::MASKGIT_PLUS) {
// Both sort by highest confidence (top-1 logit value)
std::sort(candidates.begin(), candidates.end(), std::sort(candidates.begin(), candidates.end(),
[](const candidate & a, const candidate & b) { [](const candidate & a, const candidate & b) {
return a.confidence > b.confidence; return a.confidence > b.confidence;
}); });
} else if (params.remasking == diffuse_remasking::TOPK_MARGIN) {
// Sort by margin between top-1 and top-2 logits (highest margin first)
std::sort(candidates.begin(), candidates.end(),
[](const candidate & a, const candidate & b) {
return a.confidence > b.confidence; // margin stored in confidence field
});
} else { } else {
std::shuffle(candidates.begin(), candidates.end(), rng); std::shuffle(candidates.begin(), candidates.end(), rng);
} }
+272
View File
@@ -0,0 +1,272 @@
#include "diffuse.h"
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <vector>
#ifdef _OPENMP
#include <omp.h>
#endif
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, " --bind-cores Bind threads to CPU cores (reduces jitter)\n");
fprintf(stderr, "\nSpeculative decoding:\n");
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);
}
static std::vector<int32_t> parse_tokens(const char * str) {
std::vector<int32_t> 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 draft_path;
std::string prompt;
std::vector<int32_t> input_tokens;
int max_tokens = 256;
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;
float repeat_penalty = 1.1f;
int repeat_last_n = 64;
uint32_t seed = 42;
bool bind_cores = false;
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], "--draft") == 0 && i + 1 < argc) {
draft_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], "--draft-threads") == 0 && i + 1 < argc) {
draft_threads = atoi(argv[++i]);
} else if (strcmp(argv[i], "--spec-k") == 0 && i + 1 < argc) {
spec_k = 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], "--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) {
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;
}
// Thread binding for reduced scheduling jitter
if (bind_cores) {
#ifdef _OPENMP
omp_set_num_threads(n_threads);
#endif
setenv("OMP_PROC_BIND", "close", 0);
setenv("OMP_PLACES", "cores", 0);
setenv("GOMP_CPU_AFFINITY", "0-1023", 0);
fprintf(stderr, "Thread binding: enabled (%d threads, close/cores)\n", n_threads);
}
// ── Speculative decoding path ───────────────────────────────
if (!draft_path.empty()) {
fprintf(stderr, "=== SPECULATIVE DECODING MODE ===\n");
fprintf(stderr, "Loading target model: %s\n", model_path.c_str());
diffuse_model * target_model = diffuse_model_load(model_path, n_threads);
if (!target_model) {
fprintf(stderr, "Failed to load target model\n");
return 1;
}
fprintf(stderr, "Loading draft model: %s\n", draft_path.c_str());
diffuse_model * draft_model = diffuse_model_load(draft_path, draft_threads);
if (!draft_model) {
fprintf(stderr, "Failed to load draft model\n");
diffuse_model_free(target_model);
return 1;
}
const auto & t_hp = diffuse_model_hparams(target_model);
const auto & d_hp = diffuse_model_hparams(draft_model);
int n_ctx = (int)input_tokens.size() + max_tokens + spec_k + 4;
fprintf(stderr, "Target: %dL, %d heads, vocab=%d\n",
(int)t_hp.n_layer, (int)t_hp.n_head, (int)t_hp.n_vocab);
fprintf(stderr, "Draft: %dL, %d heads, vocab=%d\n",
(int)d_hp.n_layer, (int)d_hp.n_head, (int)d_hp.n_vocab);
fprintf(stderr, "Prompt: %d tokens, max_generate: %d, K=%d\n",
(int)input_tokens.size(), max_tokens, spec_k);
diffuse_context * target_ctx = diffuse_context_new(target_model, n_ctx, n_threads);
diffuse_context * draft_ctx = diffuse_context_new(draft_model, n_ctx, draft_threads);
ar_spec_params sparams;
sparams.K = spec_k;
sparams.layer_skip = layer_skip;
sparams.sliding_window = sliding_window;
ar_spec_stats stats;
auto result = ar_speculative_generate(
target_ctx, draft_ctx, input_tokens, max_tokens, sparams,
[](int32_t token, int pos) -> bool {
fprintf(stderr, "\r generating... %d tokens", pos);
return true;
},
&stats);
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, "\nSpeculative stats:\n");
fprintf(stderr, " Acceptance rate: %.1f%% (%d/%d)\n",
100.0f * stats.acceptance_rate(),
stats.total_accepted, stats.total_draft_tokens);
fprintf(stderr, " Tokens/target_call: %.2f\n",
stats.tokens_per_target_call());
fprintf(stderr, " Fast rejects: %d\n", stats.total_fast_rejects);
diffuse_context_free(target_ctx);
diffuse_context_free(draft_ctx);
diffuse_model_free(target_model);
diffuse_model_free(draft_model);
return 0;
}
// ── Standard AR decoding path ───────────────────────────────
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;
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",
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 {
fprintf(stderr, "\r generating... %d tokens", pos);
return true;
});
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;
}
+307
View File
@@ -0,0 +1,307 @@
#!/usr/bin/env python3
"""Convert Dream SafeTensors model to GGUF format for diffuse-cpp.
Dream-7B uses a Qwen2.5 backbone with bidirectional attention and GQA.
Tensor names follow the HuggingFace Qwen2 convention (model.layers.{i}.*).
Usage:
python convert-dream.py --input /path/to/Dream-v0-Instruct-7B --output dream-7b-f16.gguf
python convert-dream.py --input /path/to/Dream-v0-Instruct-7B --output dream-7b-f16.gguf --type f16
"""
import argparse
import json
import os
import struct
import sys
from pathlib import Path
import numpy as np
try:
import torch
except ImportError:
print("ERROR: torch not installed. Run: pip install torch", file=sys.stderr)
sys.exit(1)
try:
from safetensors import safe_open
except ImportError:
print("ERROR: safetensors not installed. Run: pip install safetensors", file=sys.stderr)
sys.exit(1)
try:
import gguf
except ImportError:
print("ERROR: gguf not installed. Run: pip install gguf", file=sys.stderr)
sys.exit(1)
# ── Tensor name mapping ────────────────────────────────────────
# Dream (Qwen2.5) SafeTensors → diffuse-cpp GGUF
GLOBAL_TENSOR_MAP = {
"model.embed_tokens.weight": "token_embd.weight",
"model.norm.weight": "output_norm.weight",
"lm_head.weight": "output.weight",
}
# Per-layer: model.layers.{i}.X → blk.{i}.Y
LAYER_TENSOR_MAP = {
"self_attn.q_proj.weight": "attn_q.weight",
"self_attn.k_proj.weight": "attn_k.weight",
"self_attn.v_proj.weight": "attn_v.weight",
"self_attn.q_proj.bias": "attn_q.bias",
"self_attn.k_proj.bias": "attn_k.bias",
"self_attn.v_proj.bias": "attn_v.bias",
"self_attn.o_proj.weight": "attn_output.weight",
"mlp.gate_proj.weight": "ffn_gate.weight", # SwiGLU gate (w1)
"mlp.up_proj.weight": "ffn_up.weight", # SwiGLU up (w3)
"mlp.down_proj.weight": "ffn_down.weight", # SwiGLU down (w2)
"input_layernorm.weight": "attn_norm.weight",
"post_attention_layernorm.weight": "ffn_norm.weight",
}
# Expected tensor shapes for Dream-7B (for validation)
EXPECTED_SHAPES_7B = {
"token_embd.weight": (152064, 3584),
"output_norm.weight": (3584,),
"output.weight": (152064, 3584),
"blk.*.attn_norm.weight": (3584,),
"blk.*.attn_q.weight": (3584, 3584), # 28 heads * 128
"blk.*.attn_q.bias": (3584,),
"blk.*.attn_k.weight": (512, 3584), # 4 KV heads * 128
"blk.*.attn_k.bias": (512,),
"blk.*.attn_v.weight": (512, 3584), # 4 KV heads * 128
"blk.*.attn_v.bias": (512,),
"blk.*.attn_output.weight": (3584, 3584),
"blk.*.ffn_norm.weight": (3584,),
"blk.*.ffn_gate.weight": (18944, 3584),
"blk.*.ffn_up.weight": (18944, 3584),
"blk.*.ffn_down.weight": (3584, 18944),
}
def map_tensor_name(name: str) -> str:
"""Map Dream tensor name to GGUF tensor name. Returns None if unmapped."""
if name in GLOBAL_TENSOR_MAP:
return GLOBAL_TENSOR_MAP[name]
prefix = "model.layers."
if name.startswith(prefix):
rest = name[len(prefix):]
dot_idx = rest.index(".")
layer_id = rest[:dot_idx]
component = rest[dot_idx + 1:]
if component in LAYER_TENSOR_MAP:
return f"blk.{layer_id}.{LAYER_TENSOR_MAP[component]}"
return None
def load_config(model_dir: str) -> dict:
"""Load config.json from model directory."""
config_path = os.path.join(model_dir, "config.json")
if not os.path.exists(config_path):
raise FileNotFoundError(f"config.json not found in {model_dir}")
with open(config_path) as f:
return json.load(f)
def find_shard_files(model_dir: str) -> list:
"""Find all SafeTensors shard files, sorted."""
files = sorted(Path(model_dir).glob("model*.safetensors"))
if not files:
single = Path(model_dir) / "model.safetensors"
if single.exists():
return [str(single)]
raise FileNotFoundError(f"No .safetensors files found in {model_dir}")
return [str(f) for f in files]
def validate_shape(gguf_name: str, shape: tuple, n_layers: int):
"""Validate tensor shape against expected shapes."""
if gguf_name in EXPECTED_SHAPES_7B:
expected = EXPECTED_SHAPES_7B[gguf_name]
if shape != expected:
print(f" WARNING: {gguf_name} shape {shape} != expected {expected}")
return False
return True
for pattern, expected in EXPECTED_SHAPES_7B.items():
if "*" in pattern:
prefix, suffix = pattern.split("*")
if gguf_name.startswith(prefix) and gguf_name.endswith(suffix):
if shape != expected:
print(f" WARNING: {gguf_name} shape {shape} != expected {expected}")
return False
return True
return True
def convert(args):
"""Main conversion logic."""
config = load_config(args.input)
shard_files = find_shard_files(args.input)
print(f"Model directory: {args.input}")
print(f"Shard files: {len(shard_files)}")
print(f"Output: {args.output}")
print(f"Output type: {args.type}")
# ── Extract hyperparameters from config.json ────────────────
hidden_size = config.get("hidden_size", 3584)
n_heads = config.get("num_attention_heads", 28)
n_kv_heads = config.get("num_key_value_heads", 4)
n_layers = config.get("num_hidden_layers", 28)
intermediate = config.get("intermediate_size", 18944)
vocab_size = config.get("vocab_size", 152064)
max_pos = config.get("max_position_embeddings", 131072)
rope_theta = float(config.get("rope_theta", 1000000.0))
rms_norm_eps = float(config.get("rms_norm_eps", 1e-6))
mask_token_id = config.get("mask_token_id", 151666)
tie_embeddings = config.get("tie_word_embeddings", False)
print(f"\nHyperparameters (from config.json):")
print(f" hidden_size = {hidden_size}")
print(f" n_heads = {n_heads}")
print(f" n_kv_heads = {n_kv_heads}")
print(f" n_layers = {n_layers}")
print(f" intermediate = {intermediate}")
print(f" vocab_size = {vocab_size}")
print(f" max_pos = {max_pos}")
print(f" rope_theta = {rope_theta}")
print(f" rms_norm_eps = {rms_norm_eps}")
print(f" mask_token_id = {mask_token_id}")
print(f" tie_embeddings = {tie_embeddings}")
# ── Create GGUF writer ──────────────────────────────────────
writer = gguf.GGUFWriter(args.output, arch="diffuse")
writer.add_name("Dream-7B")
writer.add_block_count(n_layers)
writer.add_head_count(n_heads)
writer.add_head_count_kv(n_kv_heads)
writer.add_embedding_length(hidden_size)
writer.add_feed_forward_length(intermediate)
writer.add_context_length(max_pos)
writer.add_vocab_size(vocab_size)
writer.add_rope_freq_base(rope_theta)
writer.add_layer_norm_rms_eps(rms_norm_eps)
# Custom diffusion-specific keys
writer.add_uint32("diffuse.mask_token_id", mask_token_id)
writer.add_string("diffuse.model_type", "dream")
# ── Process tensors ─────────────────────────────────────────
n_converted = 0
n_skipped = 0
total_params = 0
checksums = {}
has_lm_head = False
for shard_path in shard_files:
shard_name = os.path.basename(shard_path)
print(f"\n── {shard_name} ──")
with safe_open(shard_path, framework="pt") as f:
for name in sorted(f.keys()):
gguf_name = map_tensor_name(name)
if gguf_name is None:
print(f" SKIP {name}")
n_skipped += 1
continue
if gguf_name == "output.weight":
has_lm_head = True
pt_tensor = f.get_tensor(name)
orig_dtype_str = str(pt_tensor.dtype).replace("torch.", "")
orig_shape = tuple(pt_tensor.shape)
tensor = pt_tensor.float().numpy()
if args.type == "f32":
tensor = tensor.astype(np.float32)
elif args.type == "f16":
tensor = tensor.astype(np.float16)
validate_shape(gguf_name, orig_shape, n_layers)
if args.validate:
f32_data = tensor.astype(np.float32) if tensor.dtype != np.float32 else tensor
checksum = float(np.sum(f32_data ** 2))
checksums[gguf_name] = checksum
n_params = int(np.prod(orig_shape))
total_params += n_params
print(f" OK {name}")
print(f" → {gguf_name} {list(orig_shape)} "
f"{orig_dtype_str} → {args.type} ({n_params:,} params)")
writer.add_tensor(gguf_name, tensor)
n_converted += 1
# Warn if lm_head not found and tie_embeddings is False
if not has_lm_head and not tie_embeddings:
print("WARNING: lm_head.weight not found and tie_word_embeddings=False")
print(" The model will use token_embd.weight as output projection")
# ── Summary ─────────────────────────────────────────────────
print(f"\n{'='*60}")
print(f"Tensors converted: {n_converted}")
print(f"Tensors skipped: {n_skipped}")
print(f"Total parameters: {total_params:,} ({total_params/1e9:.2f}B)")
expected_tensors = 3 + n_layers * 12 # 3 global + 12 per layer (9 weights + 3 QKV biases)
if not has_lm_head:
expected_tensors -= 1 # No separate lm_head
if n_converted != expected_tensors:
print(f"WARNING: expected {expected_tensors} tensors, got {n_converted}")
# ── Write GGUF ──────────────────────────────────────────────
print(f"\nWriting GGUF file...")
writer.write_header_to_file()
writer.write_kv_data_to_file()
writer.write_tensors_to_file()
writer.close()
size_bytes = os.path.getsize(args.output)
size_gb = size_bytes / (1024 ** 3)
print(f"Output: {args.output} ({size_gb:.2f} GB)")
if args.validate:
cksum_path = args.output + ".checksums.json"
with open(cksum_path, "w") as f:
json.dump(checksums, f, indent=2)
print(f"Checksums written to: {cksum_path}")
print("\nDone!")
def main():
parser = argparse.ArgumentParser(
description="Convert Dream SafeTensors model to GGUF format for diffuse-cpp")
parser.add_argument("--input", "-i", required=True,
help="Path to Dream model directory "
"(containing config.json and .safetensors files)")
parser.add_argument("--output", "-o", required=True,
help="Output GGUF file path")
parser.add_argument("--type", "-t", default="f32",
choices=["f32", "f16"],
help="Output tensor type (default: f32)")
parser.add_argument("--validate", action="store_true",
help="Write tensor checksums for cross-validation with PyTorch")
args = parser.parse_args()
if not os.path.isdir(args.input):
print(f"ERROR: {args.input} is not a directory", file=sys.stderr)
sys.exit(1)
convert(args)
if __name__ == "__main__":
main()
+2 -1
View File
@@ -37,7 +37,8 @@ def main():
parser.add_argument("--schedule", default="cosine", parser.add_argument("--schedule", default="cosine",
choices=["cosine", "linear"]) choices=["cosine", "linear"])
parser.add_argument("--remasking", default="low_confidence", parser.add_argument("--remasking", default="low_confidence",
choices=["low_confidence", "random", "entropy_exit"]) choices=["low_confidence", "random", "entropy_exit",
"maskgit_plus", "topk_margin"])
parser.add_argument("--entropy-threshold", type=float, default=1.5, parser.add_argument("--entropy-threshold", type=float, default=1.5,
help="Entropy threshold for entropy_exit scheduler") help="Entropy threshold for entropy_exit scheduler")
parser.add_argument("--no-cache", action="store_true", parser.add_argument("--no-cache", action="store_true",
+3 -1
View File
@@ -113,8 +113,10 @@ int main(int argc, char ** argv) {
sched_config schedulers[] = { sched_config schedulers[] = {
{"low_confidence", diffuse_remasking::LOW_CONFIDENCE}, {"low_confidence", diffuse_remasking::LOW_CONFIDENCE},
{"entropy_exit", diffuse_remasking::ENTROPY_EXIT}, {"entropy_exit", diffuse_remasking::ENTROPY_EXIT},
{"maskgit_plus", diffuse_remasking::MASKGIT_PLUS},
{"topk_margin", diffuse_remasking::TOPK_MARGIN},
}; };
int n_schedulers = 2; int n_schedulers = 4;
// Load model // Load model
int max_threads = *std::max_element(threads_list.begin(), threads_list.end()); int max_threads = *std::max_element(threads_list.begin(), threads_list.end());
+3 -1
View File
@@ -17,7 +17,7 @@ static void print_usage(const char * prog) {
fprintf(stderr, " --temp F Temperature (default: 0 = argmax)\n"); fprintf(stderr, " --temp F Temperature (default: 0 = argmax)\n");
fprintf(stderr, " --seed INT Random seed (default: 42)\n"); fprintf(stderr, " --seed INT Random seed (default: 42)\n");
fprintf(stderr, " --schedule cosine|linear (default: cosine)\n"); fprintf(stderr, " --schedule cosine|linear (default: cosine)\n");
fprintf(stderr, " --remasking low_confidence|random|entropy_exit (default: low_confidence)\n"); fprintf(stderr, " --remasking low_confidence|random|entropy_exit|maskgit_plus|topk_margin (default: low_confidence)\n");
fprintf(stderr, " --entropy-threshold F Entropy threshold for entropy_exit (default: 1.5)\n"); fprintf(stderr, " --entropy-threshold F Entropy threshold for entropy_exit (default: 1.5)\n");
fprintf(stderr, " --cache-refresh INT Force full forward every N steps (default: 0 = never)\n"); fprintf(stderr, " --cache-refresh INT Force full forward every N steps (default: 0 = never)\n");
fprintf(stderr, " --cache-keep-active INT Keep recently-changed positions active N extra steps (default: 0)\n"); fprintf(stderr, " --cache-keep-active INT Keep recently-changed positions active N extra steps (default: 0)\n");
@@ -79,6 +79,8 @@ int main(int argc, char ** argv) {
i++; i++;
if (strcmp(argv[i], "random") == 0) remasking = diffuse_remasking::RANDOM; if (strcmp(argv[i], "random") == 0) remasking = diffuse_remasking::RANDOM;
else if (strcmp(argv[i], "entropy_exit") == 0) remasking = diffuse_remasking::ENTROPY_EXIT; else if (strcmp(argv[i], "entropy_exit") == 0) remasking = diffuse_remasking::ENTROPY_EXIT;
else if (strcmp(argv[i], "maskgit_plus") == 0) remasking = diffuse_remasking::MASKGIT_PLUS;
else if (strcmp(argv[i], "topk_margin") == 0) remasking = diffuse_remasking::TOPK_MARGIN;
} else if (strcmp(argv[i], "--no-cache") == 0) { } else if (strcmp(argv[i], "--no-cache") == 0) {
use_cache = false; use_cache = false;
} else if (strcmp(argv[i], "--cache-refresh") == 0 && i + 1 < argc) { } else if (strcmp(argv[i], "--cache-refresh") == 0 && i + 1 < argc) {
+2 -1
View File
@@ -29,8 +29,9 @@ enum tensor_class {
}; };
static tensor_class classify_tensor(const char * name, int n_layers) { static tensor_class classify_tensor(const char * name, int n_layers) {
// Norms are always kept in F32 // Norms and biases are always kept in F32
if (strstr(name, "_norm") || strstr(name, "norm.")) return TC_NORM; if (strstr(name, "_norm") || strstr(name, "norm.")) return TC_NORM;
if (strstr(name, ".bias")) return TC_NORM;
// Token embeddings // Token embeddings
if (strstr(name, "token_embd") || strstr(name, "embed")) return TC_EMBED; if (strstr(name, "token_embd") || strstr(name, "embed")) return TC_EMBED;