forked from ggml-org/llama.cpp
-
Notifications
You must be signed in to change notification settings - Fork 44
Carry ggml-org#24423 (DiffusionGemma) onto b10775, and make the arch testable #177
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
danielhanchen
wants to merge
30
commits into
base/upstream-de8656bd9
from
diffusiongemma-24423-b10775
Closed
Changes from all commits
Commits
Show all changes
30 commits
Select commit
Hold shift + click to select a range
c5fe75b
diffusion-visual updates
danielhanchen c84e85a
diffusion: fix Windows build, skip diffusion-gemma in test-llama-arch…
danielhanchen 7c200dd
diffusion-cli: note that --fit is not applied by the diffusion runner
danielhanchen 9b4beb7
diffusion-cli: honor -ot / --n-cpu-moe (copy tensor_buft_overrides in…
danielhanchen 15ad8f4
diffusion: device-resident self-conditioning + cli throughput, /help,…
danielhanchen d6cf0b2
diffusion: device-side sampling reductions (default on, ~1.4x/step)
danielhanchen 53752ad
ggml-cuda: fix diffusion sampler build on HIP/MUSA
danielhanchen f53de16
diffusion: add gemma visual server for streaming canvas frames
danielhanchen 7ea238c
diffusion: self-tokenize in gemma visual server
danielhanchen 10a2613
diffusion: stop per-step device-sample fallback spam
danielhanchen e00da06
diffusion-gemma-visual-server: emit STATS, auto-size MAXTOK, report t…
danielhanchen 7a6ddc5
diffusion-gemma-visual-server: split decode time from visualization o…
danielhanchen 1153c4a
Load dynamic ggml backends so the diffusion-gemma servers offload to GPU
danielhanchen 4a6735f
diffusion: drop the DG_SC_CHECK / DG_DEVSAMPLE_CHECK debug verification
danielhanchen 49fc372
diffusion-gemma-visual-server: emit channel markers + low-VRAM auto-s…
danielhanchen 9b4dae8
diffusion-gemma-visual-server: size context by RAM when the model spi…
danielhanchen ef5e2dc
diffusion-gemma: chunked causal prefill + cap encode outputs to the c…
danielhanchen 1be9bcc
Merge remote-tracking branch 'origin/master' into diffusion-visual-up…
danielhanchen 73d820a
diffusion-gemma: enable device sampler on ROCm and MUSA backends
danielhanchen 1d2faac
Fix merge conflicts
danielhanchen c3fb972
Add tool calling
danielhanchen 1d87a1b
Fix merge conflicts
danielhanchen daca807
Fix merge conflicts
danielhanchen a15ca5b
Merge b10630 into the DiffusionGemma pin
danielhanchen 74acc40
diffusion-gemma : port the visual server to common_json
danielhanchen ba18cd5
Merge b10775 into the DiffusionGemma carry
6851db7
diffusion-gemma: give canvas_length an llm_kv id, and a test fixture
47073df
diffusion-gemma: keep the fixture out of save_models
ea0cdfd
Merge b10786: n_ff_exp is per-layer now
4137a7d
diffusion-gemma: run the arch, the fixture was the blocker
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,122 @@ | ||
| from __future__ import annotations | ||
|
|
||
| import json | ||
| from typing import Iterable | ||
|
|
||
| from torch import Tensor | ||
|
|
||
| from .base import ModelBase, SentencePieceTokenTypes | ||
| from .gemma import Gemma4Model | ||
| import gguf | ||
|
|
||
|
|
||
| @ModelBase.register("DiffusionGemma4ModelForBlockDiffusion", "DiffusionGemmaForBlockDiffusion") | ||
| class DiffusionGemmaModel(Gemma4Model): | ||
| """Block text-diffusion MoE on a Gemma-4 backbone. | ||
|
|
||
| Encoder (causal prefill) and decoder (bidirectional canvas denoising) share all weights except a | ||
| per-layer layer_scalar; the backbone lives under model.decoder.*. Strategy: rewrite model.decoder.<x> | ||
| -> model.<x> so the inherited Gemma4 tensor map handles it, then export the encoder layer_scalars | ||
| (ENC_LAYER_OUT_SCALE) and the self_conditioning gated MLP (SC_*) explicitly. Vision tower ignored; | ||
| lm_head tied to model.decoder.embed_tokens. | ||
| """ | ||
|
|
||
| model_arch = gguf.MODEL_ARCH.DIFFUSION_GEMMA | ||
|
|
||
| # TextModel.__init__ merges text_config into root hparams; root-only keys (canvas_length) are preserved. | ||
|
|
||
| def _create_vocab_sentencepiece(self): | ||
| tokens, scores, toktypes = super()._create_vocab_sentencepiece() | ||
| # Some Gemma special tokens ship non-control ('</s>', and tool/channel tokens with asymmetric | ||
| # '<|...>' / '<...|>' brackets the generic heuristic misses); tag them control so the vocab is correct. | ||
|
|
||
| def looks_control(s: str) -> bool: | ||
| return (s in ("<s>", "</s>") | ||
| or (s.startswith("<|") and s.endswith(">")) # <|tool_response>, <|...|> | ||
| or (s.startswith("<") and s.endswith("|>"))) # <tool_response|>, <turn|> | ||
| for i, tok in enumerate(tokens): | ||
| s = tok.decode("utf-8", "ignore") if isinstance(tok, (bytes, bytearray)) else str(tok) | ||
| if toktypes[i] in (SentencePieceTokenTypes.NORMAL, SentencePieceTokenTypes.USER_DEFINED) and looks_control(s): | ||
| toktypes[i] = SentencePieceTokenTypes.CONTROL | ||
| return tokens, scores, toktypes | ||
|
|
||
| def set_gguf_parameters(self): | ||
| # plain Gemma-4 MoE: disable gemma3n-only features (per-layer-input embeddings, KV-sharing) | ||
| self.hparams.setdefault("num_kv_shared_layers", 0) | ||
| self.hparams.setdefault("hidden_size_per_layer_input", 0) | ||
|
|
||
| super().set_gguf_parameters() | ||
|
|
||
| # bidirectional decoder; the forward fills its own region-aware mask | ||
| self.gguf_writer.add_causal_attention(False) | ||
|
|
||
| # canvas_length is required (the runtime splits [prompt | canvas] on it) | ||
| canvas_length = self.find_hparam(["canvas_length"], optional=False) | ||
| if canvas_length is None or int(canvas_length) <= 0: | ||
| raise ValueError("DiffusionGemma conversion requires a positive root canvas_length") | ||
| self.gguf_writer.add_diffusion_canvas_length(int(canvas_length)) | ||
|
|
||
| # entropy-bound sampler defaults (the real decoder) from generation_config; missing keys fall back to | ||
| # the runtime's reference defaults, so older configs still convert. | ||
| gen_cfg_path = self.dir_model / "generation_config.json" | ||
| if gen_cfg_path.is_file(): | ||
| with open(gen_cfg_path, encoding="utf-8") as f: | ||
| gen_cfg = json.load(f) | ||
| sampler_cfg = gen_cfg.get("sampler_config", {}) | ||
| if "max_denoising_steps" in gen_cfg: | ||
| self.gguf_writer.add_diffusion_eb_max_steps(int(gen_cfg["max_denoising_steps"])) | ||
| if "t_min" in gen_cfg: | ||
| self.gguf_writer.add_diffusion_eb_t_min(float(gen_cfg["t_min"])) | ||
| if "t_max" in gen_cfg: | ||
| self.gguf_writer.add_diffusion_eb_t_max(float(gen_cfg["t_max"])) | ||
| if "entropy_bound" in sampler_cfg: | ||
| self.gguf_writer.add_diffusion_eb_entropy_bound(float(sampler_cfg["entropy_bound"])) | ||
| if "stability_threshold" in gen_cfg: | ||
| self.gguf_writer.add_diffusion_eb_stability_threshold(int(gen_cfg["stability_threshold"])) | ||
| if "confidence_threshold" in gen_cfg: | ||
| self.gguf_writer.add_diffusion_eb_confidence_threshold(float(gen_cfg["confidence_threshold"])) | ||
|
|
||
| @classmethod | ||
| def filter_tensors(cls, item): | ||
| name, gen = item | ||
|
|
||
| # encoder contributes only layer_scalar buffers; suffix them like decoder scalars (raw 1-D) | ||
| if name.endswith("layer_scalar"): | ||
| name = name + ".weight" | ||
|
|
||
| return super().filter_tensors((name, gen)) | ||
|
|
||
| def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]: | ||
| # base filter_tensors strips "language_model.", so encoder tensors arrive as "model.encoder.layers.N.*" | ||
|
|
||
| # drop vision tower entirely (diffusion path is text-only) | ||
| if "vision" in name or "embed_vision" in name: | ||
| return | ||
|
|
||
| # encoder-mode per-layer scalar -> dedicated ENC_LAYER_OUT_SCALE tensor | ||
| if name.startswith("model.encoder.layers.") and "layer_scalar" in name: | ||
| yield (self.format_tensor_name(gguf.MODEL_TENSOR.ENC_LAYER_OUT_SCALE, bid), data_torch) | ||
| return | ||
|
|
||
| # ignore any other encoder-only tensors (its backbone weights are tied to the decoder) | ||
| if name.startswith("model.encoder."): | ||
| return | ||
|
|
||
| # decoder-only self-conditioning gated MLP | ||
| if name.startswith("model.decoder.self_conditioning."): | ||
| sub = name[len("model.decoder.self_conditioning."):] | ||
| sc_map = { | ||
| "pre_norm.weight": gguf.MODEL_TENSOR.SC_PRE_NORM, | ||
| "gate_proj.weight": gguf.MODEL_TENSOR.SC_GATE, | ||
| "up_proj.weight": gguf.MODEL_TENSOR.SC_UP, | ||
| "down_proj.weight": gguf.MODEL_TENSOR.SC_DOWN, | ||
| } | ||
| if sub in sc_map: | ||
| yield (self.format_tensor_name(sc_map[sub]), data_torch) | ||
| return | ||
|
|
||
| # remap the backbone (everything else under model.decoder.*) to model.<x> for Gemma4Model | ||
| if name.startswith("model.decoder."): | ||
| name = "model." + name[len("model.decoder."):] | ||
|
|
||
| yield from super().modify_tensors(data_torch, name, bid) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| set(TARGET llama-diffusion-gemma-eval) | ||
| add_executable(${TARGET} diffusion-gemma-eval.cpp) | ||
| install(TARGETS ${TARGET} RUNTIME) | ||
| target_link_libraries(${TARGET} PRIVATE llama ${CMAKE_THREAD_LIBS_INIT}) | ||
| target_compile_features(${TARGET} PRIVATE cxx_std_17) |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This override is never called because
DiffusionGemmaModelinheritsGemma4Model.set_vocab(), which constructsLlamaHfVocabdirectly rather than calling_create_vocab_sentencepiece(). Checkpoints needing the stated control-token correction therefore retain the original token types in the converted GGUF, affecting special-token parsing and rendering. Override the vocabulary path that Gemma4 actually uses.Useful? React with 👍 / 👎.