mirror of
https://github.com/ggml-org/llama.cpp.git
synced 2026-11-26 23:29:34 +00:00
DFlash2: support Inkling-2-Mini DFlash2 (#33073)
* support inkling2 DFlash2 * address review comments Assisted-by: Claude Opus 5.5 Co-authored-by: Nikita Belokopytov <belokopytov.n@gmail.com> --------- Co-authored-by: Nikita Belokopytov <belokopytov.n@gmail.com>
This commit is contained in:
parent
7365e4793c
commit
55d482814b
8 changed files with 66 additions and 21 deletions
|
|
@ -868,6 +868,22 @@ class Qwen3_5MoeTextModel(_Qwen35MRopeMixin, _LinearAttentionVReorderBase):
|
|||
class DFlashModel(Qwen3Model):
|
||||
model_arch = gguf.MODEL_ARCH.DFLASH
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self._target_is_inkling2 = False
|
||||
if self.target_model_dir is not None:
|
||||
target_hparams = ModelBase.load_hparams(self.target_model_dir, False)
|
||||
self._target_is_inkling2 = get_model_architecture(target_hparams, ModelType.TEXT).startswith("Inkling2")
|
||||
if self._target_is_inkling2:
|
||||
# the target GGUF keeps only the tokenizer rows of the padded vocab
|
||||
target_hparams = {**target_hparams, **target_hparams.get("text_config", {})}
|
||||
self.hparams["vocab_size"] = target_hparams["unpadded_vocab_size"]
|
||||
self.hparams["eos_token_id"] = target_hparams["eos_token_id"]
|
||||
# the loop core runs num_passes times, other looping targets need their own visit count
|
||||
self._target_n_visits = target_hparams["num_hidden_layers"]
|
||||
if (loop := target_hparams.get("loop_config")) is not None:
|
||||
self._target_n_visits += (loop["num_passes"] - 1) * (loop["core_end"] - loop["core_start"])
|
||||
|
||||
def set_vocab(self):
|
||||
if self.target_model_dir is None:
|
||||
raise ValueError(
|
||||
|
|
@ -917,6 +933,11 @@ class DFlashModel(Qwen3Model):
|
|||
self.gguf_writer.add_conv_group_size(int(dflash_config["conv_group_size"]))
|
||||
self.gguf_writer.add_selector_rank(int(dflash_config["selector_rank"]))
|
||||
self.gguf_writer.add_selector_top_k(int(dflash_config["selector_top_k"]))
|
||||
softcap_mode = dflash_config.get("selector_softcap_mode", "before_correction")
|
||||
if softcap_mode not in ("before_correction", "after_correction"):
|
||||
raise ValueError(f"DFlash2: unknown selector_softcap_mode {softcap_mode!r}")
|
||||
if softcap_mode == "after_correction":
|
||||
self.gguf_writer.add_selector_softcap_after_correction(True)
|
||||
|
||||
output_multiplier = dflash_config.get(
|
||||
"output_multiplier", self.hparams.get("output_multiplier")
|
||||
|
|
@ -942,7 +963,10 @@ class DFlashModel(Qwen3Model):
|
|||
|
||||
target_layer_ids = dflash_config.get("target_layer_ids", self.hparams.get("target_layer_ids", []))
|
||||
if target_layer_ids:
|
||||
extract_layer_ids = [i + 1 for i in target_layer_ids]
|
||||
# Inkling ids count loop visits, the last one is the final norm output
|
||||
if self._target_is_inkling2 and target_layer_ids[-1] != self._target_n_visits:
|
||||
raise ValueError(f"Inkling2 DFlash2: target_layer_ids {target_layer_ids} must end at the Inkling final norm ({self._target_n_visits})")
|
||||
extract_layer_ids = target_layer_ids if self._target_is_inkling2 else [i + 1 for i in target_layer_ids]
|
||||
self.gguf_writer.add_target_layers(extract_layer_ids)
|
||||
|
||||
use_sliding_window = self.hparams.get("use_sliding_window", False) or dflash_config.get("use_swa", False)
|
||||
|
|
@ -969,19 +993,6 @@ class DFlashModel(Qwen3Model):
|
|||
def generate_extra_tensors(self) -> Iterable[tuple[str, Tensor]]:
|
||||
yield from super().generate_extra_tensors()
|
||||
|
||||
mask_path = self.dir_model / "mask_embedding.pt"
|
||||
if not mask_path.is_file():
|
||||
return
|
||||
|
||||
mask = torch.load(mask_path, map_location="cpu", weights_only=True)
|
||||
mask_id = self.hparams.get("dflash_config", {}).get("mask_token_id")
|
||||
if mask_id is None or mask["mask_token_id"] != mask_id:
|
||||
raise ValueError("mask_embedding.pt mask_token_id does not match dflash_config")
|
||||
if tuple(mask["embedding"].shape) != (self.hparams["hidden_size"],):
|
||||
raise ValueError("mask_embedding.pt has an unexpected embedding shape")
|
||||
if not 0 <= mask_id < self.hparams["vocab_size"]:
|
||||
raise ValueError("mask_embedding.pt mask_token_id is outside the vocabulary")
|
||||
|
||||
def target_tensor(name: str) -> Tensor:
|
||||
if self.target_model_dir is None:
|
||||
raise ValueError("mask_embedding.pt requires --target-model-dir with the target embeddings and output head")
|
||||
|
|
@ -999,6 +1010,23 @@ class DFlashModel(Qwen3Model):
|
|||
return LazyTorchTensor.from_local_tensor(part[name])
|
||||
raise ValueError(f"Target tensor {name!r} was not found in safetensors")
|
||||
|
||||
if self._target_is_inkling2:
|
||||
# the draft borrows the raw target embeddings, Inkling norms them before its first layer
|
||||
yield "model.embed_norm.weight", target_tensor("model.llm.embed_norm.weight")
|
||||
|
||||
mask_path = self.dir_model / "mask_embedding.pt"
|
||||
if not mask_path.is_file():
|
||||
return
|
||||
|
||||
mask = torch.load(mask_path, map_location="cpu", weights_only=True)
|
||||
mask_id = self.hparams.get("dflash_config", {}).get("mask_token_id")
|
||||
if mask_id is None or mask["mask_token_id"] != mask_id:
|
||||
raise ValueError("mask_embedding.pt mask_token_id does not match dflash_config")
|
||||
if tuple(mask["embedding"].shape) != (self.hparams["hidden_size"],):
|
||||
raise ValueError("mask_embedding.pt has an unexpected embedding shape")
|
||||
if not 0 <= mask_id < self.hparams["vocab_size"]:
|
||||
raise ValueError("mask_embedding.pt mask_token_id is outside the vocabulary")
|
||||
|
||||
embedding_name = "model.embed_tokens.weight"
|
||||
if embedding_name in self.model_tensors:
|
||||
embeddings = self.model_tensors.pop(embedding_name)()
|
||||
|
|
@ -1061,6 +1089,8 @@ class DFlashModel(Qwen3Model):
|
|||
"model.candidate_selector.predecessor_codebook",
|
||||
"model.candidate_selector.successor_codebook",
|
||||
):
|
||||
# padded vocabs (Inkling): the selector only indexes the draft vocab
|
||||
data_torch = data_torch[:self.hparams["vocab_size"]]
|
||||
name += ".weight"
|
||||
|
||||
yield from super().modify_tensors(data_torch, name, bid)
|
||||
|
|
|
|||
|
|
@ -175,6 +175,7 @@ class Keys:
|
|||
CONV_GROUP_SIZE = "{arch}.conv_group_size"
|
||||
SELECTOR_RANK = "{arch}.selector_rank"
|
||||
SELECTOR_TOP_K = "{arch}.selector_top_k"
|
||||
SELECTOR_SOFTCAP_AFTER_CORRECTION = "{arch}.selector_softcap_after_correction"
|
||||
SAMPLE_FROM_ANCHOR = "{arch}.sample_from_anchor"
|
||||
HAS_CONFIDENCE_HEAD = "{arch}.has_confidence_head"
|
||||
HAS_MARKOV_CONTEXT = "{arch}.has_markov_context"
|
||||
|
|
|
|||
|
|
@ -1107,6 +1107,9 @@ class GGUFWriter:
|
|||
def add_selector_top_k(self, value: int) -> None:
|
||||
self.add_uint32(Keys.LLM.SELECTOR_TOP_K.format(arch=self.arch), value)
|
||||
|
||||
def add_selector_softcap_after_correction(self, value: bool) -> None:
|
||||
self.add_bool(Keys.LLM.SELECTOR_SOFTCAP_AFTER_CORRECTION.format(arch=self.arch), value)
|
||||
|
||||
def add_sample_from_anchor(self, value: bool) -> None:
|
||||
self.add_bool(Keys.LLM.SAMPLE_FROM_ANCHOR.format(arch=self.arch), value)
|
||||
|
||||
|
|
|
|||
|
|
@ -450,12 +450,13 @@ static const std::map<llm_kv, const char *> LLM_KV_NAMES = {
|
|||
{ LLM_KV_NORM_BEFORE_RESIDUAL, "%s.norm_before_residual" },
|
||||
{ LLM_KV_NORM_BEFORE_FC, "%s.norm_before_fc" },
|
||||
|
||||
{ LLM_KV_DFLASH_BLOCK_SIZE, "%s.block_size" },
|
||||
{ LLM_KV_DFLASH_CONV_KERNEL_SIZE, "%s.conv_kernel_size" },
|
||||
{ LLM_KV_DFLASH_CONV_GROUP_SIZE, "%s.conv_group_size" },
|
||||
{ LLM_KV_DFLASH_SELECTOR_RANK, "%s.selector_rank" },
|
||||
{ LLM_KV_DFLASH_SELECTOR_TOP_K, "%s.selector_top_k" },
|
||||
{ LLM_KV_DFLASH_HAS_MARKOV_CONTEXT, "%s.has_markov_context" },
|
||||
{ LLM_KV_DFLASH_BLOCK_SIZE, "%s.block_size" },
|
||||
{ LLM_KV_DFLASH_CONV_KERNEL_SIZE, "%s.conv_kernel_size" },
|
||||
{ LLM_KV_DFLASH_CONV_GROUP_SIZE, "%s.conv_group_size" },
|
||||
{ LLM_KV_DFLASH_SELECTOR_RANK, "%s.selector_rank" },
|
||||
{ LLM_KV_DFLASH_SELECTOR_TOP_K, "%s.selector_top_k" },
|
||||
{ LLM_KV_DFLASH_SELECTOR_SOFTCAP_AFTER_CORRECTION, "%s.selector_softcap_after_correction" },
|
||||
{ LLM_KV_DFLASH_HAS_MARKOV_CONTEXT, "%s.has_markov_context" },
|
||||
|
||||
{ LLM_KV_LILICORR_HIDDEN_SIZE, "lilicorr.hidden_size" },
|
||||
{ LLM_KV_LILICORR_CANDIDATE_TOPK, "lilicorr.candidate_topk" },
|
||||
|
|
|
|||
|
|
@ -501,6 +501,7 @@ enum llm_kv {
|
|||
LLM_KV_DFLASH_CONV_GROUP_SIZE,
|
||||
LLM_KV_DFLASH_SELECTOR_RANK,
|
||||
LLM_KV_DFLASH_SELECTOR_TOP_K,
|
||||
LLM_KV_DFLASH_SELECTOR_SOFTCAP_AFTER_CORRECTION,
|
||||
LLM_KV_DFLASH_HAS_MARKOV_CONTEXT,
|
||||
LLM_KV_LILICORR_HIDDEN_SIZE,
|
||||
LLM_KV_LILICORR_CANDIDATE_TOPK,
|
||||
|
|
|
|||
|
|
@ -305,6 +305,7 @@ struct llama_hparams {
|
|||
uint32_t dflash_conv_group_size = 0;
|
||||
uint32_t dflash_selector_rank = 0;
|
||||
uint32_t dflash_selector_top_k = 0;
|
||||
bool dflash_softcap_post = false; // DFlash2 softcaps the selector scores instead of the logits
|
||||
bool dspark_f_rnn = false; // rnn markov head reads f_rnn from embd_state
|
||||
uint32_t lilicorr_hidden_size = 0;
|
||||
uint32_t lilicorr_candidate_topk = 0;
|
||||
|
|
|
|||
|
|
@ -47,6 +47,7 @@ void llama_model_dflash::load_arch_hparams(llama_model_loader & ml) {
|
|||
}
|
||||
} else if (has_selector) {
|
||||
variant = VARIANT_DFLASH2;
|
||||
ml.get_key(LLM_KV_DFLASH_SELECTOR_SOFTCAP_AFTER_CORRECTION, hparams.dflash_softcap_post, false);
|
||||
} else if (has_lilicorr) {
|
||||
variant = VARIANT_LILICORR;
|
||||
load_hparams_lilicorr(ml);
|
||||
|
|
@ -447,6 +448,9 @@ ggml_tensor * llama_model_dflash::graph_base::build_layers(ggml_tensor * inp_tok
|
|||
ggml_tensor * inpL = model.dspark_mask_embd
|
||||
? build_dspark_inp_block(*this, model, inp_tokens)
|
||||
: ggml_get_rows(ctx0, get_tok_embd(*this, model), inp_tokens);
|
||||
if (model.tok_norm && !model.dspark_mask_embd) {
|
||||
inpL = build_norm(inpL, model.tok_norm, nullptr, LLM_NORM_RMS, -1);
|
||||
}
|
||||
if (hparams.f_embedding_scale != 0.0f) {
|
||||
inpL = ggml_scale(ctx0, inpL, hparams.f_embedding_scale);
|
||||
}
|
||||
|
|
@ -569,7 +573,7 @@ ggml_tensor * llama_model_dflash::graph_base::build_logits(ggml_tensor * cur) {
|
|||
if (hparams.f_logit_scale != 0.0f) {
|
||||
cur = ggml_scale(ctx0, cur, hparams.f_logit_scale);
|
||||
}
|
||||
if (hparams.f_final_logit_softcapping > 0.0f) {
|
||||
if (hparams.f_final_logit_softcapping > 0.0f && !hparams.dflash_softcap_post) {
|
||||
cur = ggml_scale(ctx0, cur, 1.0f / hparams.f_final_logit_softcapping);
|
||||
cur = ggml_tanh(ctx0, cur);
|
||||
cur = ggml_scale(ctx0, cur, hparams.f_final_logit_softcapping);
|
||||
|
|
|
|||
|
|
@ -177,6 +177,10 @@ static void build_dflash2_selector(llm_graph_context & g, const llama_model & mo
|
|||
}
|
||||
ggml_tensor * unary_bcast = ggml_reshape_4d(ctx0, unary_run, top_k, 1, n_pos, n_blocks);
|
||||
score = ggml_add(ctx0, score, ggml_repeat(ctx0, unary_bcast, score));
|
||||
if (hparams.dflash_softcap_post && hparams.f_final_logit_softcapping > 0.0f) {
|
||||
const float cap = hparams.f_final_logit_softcapping;
|
||||
score = ggml_scale(ctx0, ggml_tanh(ctx0, ggml_scale(ctx0, score, 1.0f / cap)), cap);
|
||||
}
|
||||
|
||||
ggml_tensor * row = ggml_concat(ctx0,
|
||||
ggml_cast(ctx0, cand_run, GGML_TYPE_F32),
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue