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>
This commit is contained in:
iafiscal1212andClaude Opus 4.6 committed 2026-03-22 13:03:30 +01:00
1 parent 9b76ba9bc3
commit 3f6aa5597a
9 files changed
+376 -18

No files matched your search

+21 -6
View File
@@ -21,10 +21,17 @@ High-performance C++ inference engine for Diffusion Language Models, built on GG
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.
### 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
All benchmarks: LLaDA-8B-Instruct, AMD EPYC 4465P 12-Core (24 threads), 125GB RAM, steps=16, 3 reps + 1 warmup.
@@ -103,9 +110,15 @@ print(",".join(map(str, tokens)))
Convert a model from HuggingFace to GGUF F16:
```bash
# LLaDA
python tools/convert-llada.py \
--input /path/to/LLaDA-8B-Instruct \
--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):
@@ -118,9 +131,9 @@ Quantize to Q4_K_M (recommended for best performance):
```
Available quantization formats:
- `Q4_K_M`: 4-bit mixed precision (recommended, 5.1 GB)
- `Q8_0`: 8-bit (8.4 GB, higher quality)
- `F16`: 16-bit float (14.9 GB, reference quality)
- `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 / ~7.6 GB)
- `F16`: 16-bit float (14.9 GB / ~15.2 GB)
## Supported Models
@@ -256,7 +269,9 @@ See `include/diffuse.h` for full API documentation.
## 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.
Dream adds Grouped Query Attention (GQA) and additional remasking strategies (`maskgit_plus`, `topk_margin`) from the [Dream paper](https://arxiv.org/abs/2508.15487).
Current limitations:
- No integrated tokenizer (use transformers)
@@ -267,7 +282,7 @@ Current limitations:
## Contributing
Contributions welcome. Areas of interest:
- Additional model architectures (SEDD, MDLM)
- Additional model architectures
- Improved scheduling heuristics
- Tokenizer integration
- Multi-query batching
+2
View File
@@ -38,6 +38,8 @@ enum class diffuse_remasking {
LOW_CONFIDENCE,
RANDOM,
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 {
+1
View File
@@ -46,6 +46,7 @@ struct diffuse_layer {
// ── Full model struct ──────────────────────────────────────────
struct diffuse_model {
diffuse_hparams hparams;
std::string model_type; // "llada", "dream", etc. (from GGUF metadata)
// Embeddings
struct ggml_tensor * tok_embd; // token embeddings
+19 -4
View File
@@ -58,10 +58,25 @@ diffuse_model * diffuse_model_load_impl(const std::string & path, int n_threads)
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)");
DIFFUSE_LOG(" n_vocab=%u, n_embd=%u, n_head=%u, n_layer=%u, n_ff=%u",
hp.n_vocab, hp.n_embd, hp.n_head, hp.n_layer, hp.n_ff);
DIFFUSE_LOG(" mask_token_id=%u, rope_theta=%.0f", hp.mask_token_id, hp.rope_theta);
// Read model type (llada, dream, etc.)
{
int64_t id = gguf_find_key(gctx, "diffuse.model_type");
if (id >= 0) {
model->model_type = gguf_get_val_str(gctx, id);
} else {
model->model_type = "llada"; // default for older GGUF files
}
}
const char * arch_name = "unknown";
if (model->model_type == "llada") arch_name = "LLaDA (Llama backbone)";
else if (model->model_type == "dream") arch_name = "Dream (Qwen2.5 backbone, GQA)";
DIFFUSE_LOG(" arch: %s", arch_name);
DIFFUSE_LOG(" n_vocab=%u, n_embd=%u, n_head=%u/%u(kv), n_layer=%u, n_ff=%u",
hp.n_vocab, hp.n_embd, hp.n_head, hp.n_head_kv, hp.n_layer, hp.n_ff);
DIFFUSE_LOG(" mask_token_id=%u, rope_theta=%.0f, rms_norm_eps=%.1e",
hp.mask_token_id, hp.rope_theta, hp.rms_norm_eps);
// The weight context is the one that gguf_init populated
model->ctx = meta_ctx;
+24 -5
View File
@@ -98,11 +98,15 @@ std::vector<int32_t> diffuse_sample(
const int cache_refresh = params.cache_refresh;
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",
params.n_steps, n_generate,
params.remasking == diffuse_remasking::ENTROPY_EXIT ? "entropy_exit" :
params.remasking == diffuse_remasking::LOW_CONFIDENCE ? "low_confidence" :
"random",
remasking_name,
use_cache ? "ON" : "OFF",
cache_refresh, cache_keep_active);
@@ -226,15 +230,22 @@ std::vector<int32_t> diffuse_sample(
float ent = compute_entropy(logit_row, n_vocab);
if (params.temperature <= 0.0f) {
// Find top-1 (and top-2 for TOPK_MARGIN)
int best = 0;
float best_val = logit_row[0];
float second_val = -1e30f;
for (int v = 1; v < n_vocab; v++) {
if (logit_row[v] > best_val) {
second_val = best_val;
best_val = logit_row[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 {
float max_logit = *std::max_element(logit_row, logit_row + n_vocab);
std::vector<float> probs(n_vocab);
@@ -272,11 +283,19 @@ std::vector<int32_t> diffuse_sample(
n_unmask = std::max(n_unmask, n_easy);
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(),
[](const candidate & a, const candidate & b) {
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 {
std::shuffle(candidates.begin(), candidates.end(), rng);
}
+301
View File
@@ -0,0 +1,301 @@
#!/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.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_k.weight": (512, 3584), # 4 KV heads * 128
"blk.*.attn_v.weight": (512, 3584), # 4 KV heads * 128
"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 * 9 # 3 global + 9 per layer
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",
choices=["cosine", "linear"])
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,
help="Entropy threshold for entropy_exit scheduler")
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[] = {
{"low_confidence", diffuse_remasking::LOW_CONFIDENCE},
{"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
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, " --seed INT Random seed (default: 42)\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, " --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");
@@ -79,6 +79,8 @@ int main(int argc, char ** argv) {
i++;
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], "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) {
use_cache = false;
} else if (strcmp(argv[i], "--cache-refresh") == 0 && i + 1 < argc) {