Compare commits

...
5 Commits
Author SHA1 Message Date
George Burton f6d944f6d5 mtmd: fix qwen3omni deepstack allow audio and video (#33041)
* fix: qwen3omni deepstack allow audio and video

* fix: mmproj audio broken/zero-width audio gets its own error line
2026-11-29 19:54:32 +01:00
Zuhal Karadavut 6c83d2ea39 convert : warn when per-channel FP8 weights are dequantized (#33312)
Assisted-by: Claude Code (Claude Opus 5.5)
2026-11-29 19:36:44 +01:00
Francisco Javier 84250b88ee hip: fix CU_CHECK macro shadowing causing infinite loop with VMM (#33227)
* hip: fix CU_CHECK macro shadowing causing infinite loop with VMM

* hip: fix CU_CHECK macro to prevent infinite loop
2026-11-29 19:19:13 +01:00
Alessandro de Oliveira Faria (A.K.A.CABELO) 5a18afaf7c vendor : update cpp-httplib-0.69.0 (#33310)
[no ci]
2026-11-29 19:18:41 +01:00
cyxu0401andxuchengyang e18d1b2150 models : add MiniCPM5 MoE support (#32644)
* models: add MiniCPM5 MoE support

Assisted-by: Codex
(cherry picked from commit 7f63c7e3e3258dd3c769c7cc9dfa03ae9a23a1f4)

* docs: clarify MiniCPM5 MoE DSpark startup options

Assisted-by: Codex

* models: preserve MiniCPM5 MoE HF BOS setting

* convert: use the released MiniCPM5 MoE tokenizer settings

Assisted-by: Codex

* tests: remove MiniCPM5 MoE conversion tests

Assisted-by: Codex

* models: address MiniCPM5 MoE converter and graph review

Assisted-by: Codex

* models: default unset MiniCPM5 MoE gating to sigmoid

Assisted-by: Codex

* tests: update the MiniCPM5 MoE Metal fusion baseline

Drop the model and speculative decoding documentation changes from this PR.

Assisted-by: Codex

---------

Co-authored-by: xuchengyang <xuchengyang@modelbest.cn>
2026-11-29 18:38:42 +01:00
21 changed files with 578 additions and 119 deletions
+1
View File
@@ -215,6 +215,7 @@ TEXT_MODEL_MAP: dict[str, str] = {
"MiMoV2FlashForCausalLM": "mimo",
"MiMoV2ForCausalLM": "mimo",
"MiniCPM3ForCausalLM": "minicpm",
"MiniCPM5MoEForCausalLM": "minicpm",
"MiniCPMForCausalLM": "minicpm",
"MiniCPMV4_6ForConditionalGeneration": "minicpm",
"MiniCPMV4_7ForConditionalGeneration": "minicpm",
+5
View File
@@ -719,6 +719,7 @@ class ModelBase:
channel_scales: dict[str, tuple[Tensor, ...]] = {}
weight_dtypes: dict[str, torch.dtype] = {}
scaled_weights: set[str] = set()
channel_scale_fallback: list[str] = []
expert_pattern = re.compile(r"(\.[^.]*experts)\.(\d+)\.")
scale_types = {
gguf.MODEL_TENSOR.ATTN_Q, gguf.MODEL_TENSOR.ATTN_K, gguf.MODEL_TENSOR.ATTN_V,
@@ -778,10 +779,14 @@ class ModelBase:
transformed = self._transform_fp8_scale(weight_name, scale.reshape(-1, 1)) if weight.ndim == 2 else None
if transformed is None or len(transformed) != len(new_names):
self._fp8_e4m3_preserved.discard(weight_name)
channel_scale_fallback.append(weight_name)
continue
channel_scales[weight_name] = transformed
candidates[weight_name] = (scale_name, scale, new_names, weight.shape)
if channel_scale_fallback:
logger.warning(f"{len(channel_scale_fallback)} FP8 weights will be dequantized, {type(self).__name__} cannot keep their per-channel scales (first: {channel_scale_fallback[0]})")
expert_groups: dict[str, list[str]] = {}
for name in self.model_tensors:
if (match := expert_pattern.search(name)) and name.endswith(".weight"):
+50
View File
@@ -61,6 +61,56 @@ class MiniCPMModel(TextModel):
yield from super().modify_tensors(data_torch, name, bid)
@ModelBase.register("MiniCPM5MoEForCausalLM")
class MiniCPM5MoEModel(TextModel):
model_arch = gguf.MODEL_ARCH.MINICPM5_MOE
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if not self.hparams.get("use_gated_attention", False):
raise ValueError("MiniCPM5 MoE requires gated attention")
self._experts: list[dict[str, Tensor]] = [{} for _ in range(self.block_count)]
def set_gguf_parameters(self):
super().set_gguf_parameters()
self.gguf_writer.add_vocab_size(self.hparams["vocab_size"])
head_dim = self.hparams.get("head_dim", self.hparams["hidden_size"] // self.hparams["num_attention_heads"])
self.gguf_writer.add_rope_dimension_count(head_dim)
self.gguf_writer.add_expert_feed_forward_length(self.hparams["moe_intermediate_size"])
self.gguf_writer.add_expert_shared_count(self.hparams["n_shared_experts"])
self.gguf_writer.add_leading_dense_block_count(self.hparams["first_k_dense_replace"])
self.gguf_writer.add_expert_weights_norm(self.hparams.get("norm_topk_prob", True))
self.gguf_writer.add_expert_weights_scale(self.hparams["routed_scaling_factor"])
def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]:
if name.endswith("self_attn.q_proj.weight"):
n_head = self.hparams["num_attention_heads"]
head_dim = self.hparams.get("head_dim", self.hparams["hidden_size"] // n_head)
# Each HF head stores its query rows followed by its gate rows.
query, gate = data_torch.reshape(n_head, 2 * head_dim, -1).chunk(2, dim=1)
query = query.reshape(n_head * head_dim, -1)
gate = gate.reshape(n_head * head_dim, -1)
yield self.format_tensor_name(gguf.MODEL_TENSOR.ATTN_Q, bid), query
yield self.format_tensor_name(gguf.MODEL_TENSOR.ATTN_GATE, bid), gate
return
if ".mlp.experts." in name:
n_experts = self.hparams["n_routed_experts"]
assert bid is not None
self._experts[bid][name] = data_torch
if len(self._experts[bid]) == n_experts * 3:
for projection in ("gate_proj", "up_proj", "down_proj"):
tensors = [
self._experts[bid].pop(f"model.layers.{bid}.mlp.experts.{eid}.{projection}.weight")
for eid in range(n_experts)
]
merged = torch.stack(tensors, dim=0)
yield from super().modify_tensors(merged, f"model.layers.{bid}.mlp.experts.{projection}.weight", bid)
return
yield from super().modify_tensors(data_torch, name, bid)
@ModelBase.register("MiniCPM3ForCausalLM")
@ModelBase.example("openbmb/MiniCPM3-4B")
class MiniCPM3Model(TextModel):
+9 -11
View File
@@ -14,6 +14,13 @@ from .qwen import Qwen3Model, Qwen3MoeModel
from .qwenvl import Qwen25AudioModel
def _vision_config(hparams: dict[str, Any]) -> dict[str, Any]:
# the vision config lives under thinker_config for omni models, at top level for plain VL
if "thinker_config" in hparams:
return hparams["thinker_config"].get("vision_config", {})
return hparams.get("vision_config", {})
@ModelBase.register("Qwen3VLForConditionalGeneration", "Qwen3VLMoeForConditionalGeneration", "Qwen3_5ForConditionalGeneration", "Qwen3_5MoeForConditionalGeneration", "OpenJevModel")
@ModelBase.example("Qwen/Qwen3-VL-4B-Instruct", "Qwen/Qwen3-VL-30B-A3B-Instruct", "Qwen/Qwen3.5-9B", "Qwen/Qwen3.5-35B-A3B")
class Qwen3VLVisionModel(MmprojModel):
@@ -295,11 +302,7 @@ class Qwen3VLTextModel(Qwen3Model):
def set_gguf_parameters(self):
super().set_gguf_parameters()
if "thinker_config" in self.hparams:
vision_config = self.hparams["thinker_config"].get("vision_config", {})
else:
vision_config = self.hparams.get("vision_config", {})
deepstack_layer_num = len(vision_config.get("deepstack_visual_indexes", []))
deepstack_layer_num = len(_vision_config(self.hparams).get("deepstack_visual_indexes", []))
self.gguf_writer.add_num_deepstack_layers(deepstack_layer_num)
@classmethod
@@ -318,8 +321,7 @@ class Qwen3VLMoeTextModel(Qwen3MoeModel):
def set_gguf_parameters(self):
super().set_gguf_parameters()
vision_config = self.hparams.get("vision_config", {})
deepstack_layer_num = len(vision_config.get("deepstack_visual_indexes", []))
deepstack_layer_num = len(_vision_config(self.hparams).get("deepstack_visual_indexes", []))
self.gguf_writer.add_num_deepstack_layers(deepstack_layer_num)
@classmethod
@@ -378,10 +380,6 @@ class Qwen3OmniMoeTextModel(Qwen3VLMoeTextModel):
self.gguf_writer.add_eos_token_id(int(token_id))
break
def set_gguf_parameters(self):
super().set_gguf_parameters()
self.gguf_writer.add_num_deepstack_layers(0)
@ModelBase.register("Qwen3ASRForConditionalGeneration")
@ModelBase.example("Qwen/Qwen3-ASR-0.6B-hf")
+1 -1
View File
@@ -31,7 +31,7 @@ typedef uint64_t ggml_cuda_thread_mask_t;
#define CU_MEM_ALLOCATION_TYPE_PINNED hipMemAllocationTypePinned
#define CU_MEM_LOCATION_TYPE_DEVICE hipMemLocationTypeDevice
#define CU_MEM_ACCESS_FLAGS_PROT_READWRITE hipMemAccessFlagsProtReadWrite
#define CU_CHECK(fn) {hipError_t err = fn; if(err != hipSuccess) { GGML_ABORT("HipVMM Failure: %s\n", hipGetErrorString(err)); }}
#define CU_CHECK(fn) do { hipError_t err_ = (fn); if (err_ != hipSuccess) { GGML_ABORT("HipVMM Failure: %s\n", hipGetErrorString(err_)); } } while (0)
#define cublasStrsmBatched hipblasStrsmBatched
#define cublasCreate hipblasCreate
#define cublasDestroy hipblasDestroy
+26
View File
@@ -733,6 +733,7 @@ class MODEL_ARCH(IntEnum):
DOTS3NOTE = auto()
ARCEE = auto()
AFMOE = auto()
MINICPM5_MOE = auto()
LAGUNA = auto()
RICURSIVE = auto()
ERNIE4_5 = auto()
@@ -1763,6 +1764,7 @@ MODEL_ARCH_NAMES: dict[MODEL_ARCH, str] = {
MODEL_ARCH.DOTS3NOTE: "dots3note",
MODEL_ARCH.ARCEE: "arcee",
MODEL_ARCH.AFMOE: "afmoe",
MODEL_ARCH.MINICPM5_MOE: "minicpm5_moe",
MODEL_ARCH.LAGUNA: "laguna",
MODEL_ARCH.RICURSIVE: "ricursive",
MODEL_ARCH.ERNIE4_5: "ernie4_5",
@@ -5901,6 +5903,30 @@ MODEL_TENSORS: dict[MODEL_ARCH, list[MODEL_TENSOR]] = {
MODEL_TENSOR.FFN_UP,
MODEL_TENSOR.FFN_POST_NORM,
],
MODEL_ARCH.MINICPM5_MOE: [
MODEL_TENSOR.TOKEN_EMBD,
MODEL_TENSOR.OUTPUT_NORM,
MODEL_TENSOR.OUTPUT,
MODEL_TENSOR.ATTN_NORM,
MODEL_TENSOR.ATTN_QKV,
MODEL_TENSOR.ATTN_Q,
MODEL_TENSOR.ATTN_K,
MODEL_TENSOR.ATTN_V,
MODEL_TENSOR.ATTN_OUT,
MODEL_TENSOR.ATTN_GATE,
MODEL_TENSOR.FFN_GATE,
MODEL_TENSOR.FFN_DOWN,
MODEL_TENSOR.FFN_UP,
MODEL_TENSOR.FFN_GATE_INP,
MODEL_TENSOR.FFN_GATE_EXP,
MODEL_TENSOR.FFN_DOWN_EXP,
MODEL_TENSOR.FFN_UP_EXP,
MODEL_TENSOR.FFN_GATE_SHEXP,
MODEL_TENSOR.FFN_UP_SHEXP,
MODEL_TENSOR.FFN_DOWN_SHEXP,
MODEL_TENSOR.FFN_NORM,
MODEL_TENSOR.FFN_EXP_PROBS_B,
],
MODEL_ARCH.LAGUNA: [
MODEL_TENSOR.TOKEN_EMBD,
MODEL_TENSOR.OUTPUT_NORM,
+1 -1
View File
@@ -5,7 +5,7 @@ import os
import sys
import subprocess
HTTPLIB_VERSION = "refs/tags/v0.68.0"
HTTPLIB_VERSION = "refs/tags/v0.69.0"
JSON_VERSION = "v3.12.0"
# stb has no release tag, so we pin a commit (stb_image v2.32)
+1
View File
@@ -126,6 +126,7 @@ static const std::map<llm_arch, const char *> LLM_ARCH_NAMES = {
{ LLM_ARCH_DOTS3NOTE, "dots3note" },
{ LLM_ARCH_ARCEE, "arcee" },
{ LLM_ARCH_AFMOE, "afmoe" },
{ LLM_ARCH_MINICPM5_MOE, "minicpm5_moe" },
{ LLM_ARCH_LAGUNA, "laguna" },
{ LLM_ARCH_ERNIE4_5, "ernie4_5" },
{ LLM_ARCH_ERNIE4_5_MOE, "ernie4_5-moe" },
+1
View File
@@ -130,6 +130,7 @@ enum llm_arch {
LLM_ARCH_DOTS3NOTE,
LLM_ARCH_ARCEE,
LLM_ARCH_AFMOE,
LLM_ARCH_MINICPM5_MOE,
LLM_ARCH_LAGUNA,
LLM_ARCH_ERNIE4_5,
LLM_ARCH_ERNIE4_5_MOE,
+3
View File
@@ -301,6 +301,8 @@ static llama_model * llama_model_mapping(llm_arch arch, const llama_model_params
return new llama_model_arcee(params);
case LLM_ARCH_AFMOE:
return new llama_model_afmoe(params);
case LLM_ARCH_MINICPM5_MOE:
return new llama_model_minicpm5_moe(params);
case LLM_ARCH_LAGUNA:
return new llama_model_laguna(params);
case LLM_ARCH_RICURSIVE:
@@ -3908,6 +3910,7 @@ llama_rope_type llama_model_rope_type(const llama_model * model) {
case LLM_ARCH_COGVLM:
case LLM_ARCH_PANGU_EMBED:
case LLM_ARCH_AFMOE:
case LLM_ARCH_MINICPM5_MOE:
case LLM_ARCH_LAGUNA:
case LLM_ARCH_QWEN3NEXT:
case LLM_ARCH_CLOVER_MOE:
+221
View File
@@ -0,0 +1,221 @@
#include "models.h"
void llama_model_minicpm5_moe::load_arch_hparams(llama_model_loader & ml) {
if (hparams.n_embd_head_k_full != hparams.n_embd_head_v_full) {
throw std::runtime_error("MiniCPM5 MoE requires equal key and value head sizes");
}
ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
ml.get_key(LLM_KV_LEADING_DENSE_BLOCK_COUNT, hparams.n_layer_dense_lead);
ml.get_key_or_arr(LLM_KV_EXPERT_FEED_FORWARD_LENGTH, hparams.n_ff_exp_arr, hparams.n_layer_all);
ml.get_key(LLM_KV_EXPERT_SHARED_COUNT, hparams.n_expert_shared);
ml.get_key(LLM_KV_EXPERT_WEIGHTS_SCALE, hparams.expert_weights_scale);
ml.get_key(LLM_KV_EXPERT_WEIGHTS_NORM, hparams.expert_weights_norm);
ml.get_key(LLM_KV_EXPERT_GATING_FUNC, hparams.expert_gating_func, false);
if (hparams.expert_gating_func == LLAMA_EXPERT_GATING_FUNC_TYPE_NONE) {
hparams.expert_gating_func = LLAMA_EXPERT_GATING_FUNC_TYPE_SIGMOID;
}
type = LLM_TYPE_UNKNOWN;
}
void llama_model_minicpm5_moe::load_arch_tensors(llama_model_loader &) {
LLAMA_LOAD_LOCALS;
const int64_t n_expert_shared = hparams.n_expert_shared;
tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);
// output
output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);
output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, TENSOR_NOT_REQUIRED);
// if output is NULL, init from the input tok embed
if (output == NULL) {
output = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, TENSOR_DUPLICATED);
}
const int64_t n_ff_exp = hparams.n_ff_exp();
for (int i = 0; i < n_layer; ++i) {
auto & layer = layers[i];
// attention pre-normalization
layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);
// attention projections
create_tensor_qkv(layer, i, n_embd, n_embd_head_k * n_head, n_embd_k_gqa, n_embd_v_gqa, 0);
layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_head_k * n_head, n_embd}, 0);
// attention gating
layer.wqkv_gate = create_tensor(tn(LLM_TENSOR_ATTN_GATE, "weight", i), {n_embd, n_embd_head_k * n_head}, 0);
// FFN pre-normalization
layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
if (static_cast<uint32_t>(i) >= hparams.n_layer_dense_lead) {
// MoE layers
layer.ffn_gate_inp = create_tensor(tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert}, 0);
layer.ffn_exp_probs_b = create_tensor(tn(LLM_TENSOR_FFN_EXP_PROBS_B, "bias", i), {n_expert}, 0);
// grouped expert weights
layer.ffn_gate_exps = create_tensor(tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i), {n_embd, n_ff_exp, n_expert}, 0);
layer.ffn_down_exps = create_tensor(tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), {n_ff_exp, n_embd, n_expert}, 0);
layer.ffn_up_exps = create_tensor(tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), {n_embd, n_ff_exp, n_expert}, 0);
// shared expert
if (n_expert_shared > 0) {
const int64_t n_ff_shexp = n_ff_exp * n_expert_shared;
layer.ffn_gate_shexp = create_tensor(tn(LLM_TENSOR_FFN_GATE_SHEXP, "weight", i), {n_embd, n_ff_shexp}, 0);
layer.ffn_down_shexp = create_tensor(tn(LLM_TENSOR_FFN_DOWN_SHEXP, "weight", i), {n_ff_shexp, n_embd}, 0);
layer.ffn_up_shexp = create_tensor(tn(LLM_TENSOR_FFN_UP_SHEXP, "weight", i), {n_embd, n_ff_shexp}, 0);
}
} else {
// Dense layers
layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0);
layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd}, 0);
layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
}
}
}
std::unique_ptr<llm_graph_context> llama_model_minicpm5_moe::build_arch_graph(const llm_graph_params & params) const {
return std::make_unique<graph>(params);
}
llama_model_minicpm5_moe::graph::graph(const llm_graph_params & params) : llm_graph_context(params) {
const int64_t n_embd_head = hparams.n_embd_head_v();
ggml_tensor * cur;
ggml_tensor * inpL;
inpL = build_inp_embd(model.tok_embd);
// inp_pos - contains the positions
ggml_tensor * inp_pos = build_inp_pos();
auto * inp_attn = build_attn_inp_kv();
ggml_tensor * inp_out_ids = build_inp_out_ids();
const float kq_scale = 1.0f/sqrtf(float(n_embd_head));
for (int il = 0; il < n_layer; ++il) {
res->t_layer_inp[il] = inpL;
ggml_tensor * inpSA = inpL;
// attention pre-normalization (pre)
cur = build_norm(inpL,
model.layers[il].attn_norm, NULL,
LLM_NORM_RMS, il);
cb(cur, "attn_norm", il);
// self-attention
{
ggml_tensor * attn_inp = cur; // save input for gate computation
auto [Qcur, Kcur, Vcur] = build_qkv(model.layers[il], cur,
n_embd_head, n_head, n_head_kv, il);
// compute gate from input
ggml_tensor * gate = build_lora_mm(model.layers[il].wqkv_gate, attn_inp);
cb(gate, "attn_gate_proj", il);
Qcur = build_rope(Qcur, inp_pos, il);
cb(Qcur, "Qcur_rope", il);
Kcur = build_rope(Kcur, inp_pos, il);
cb(Kcur, "Kcur_rope", il);
cur = build_attn(inp_attn,
NULL, NULL, // wo will be applied after gating
Qcur, Kcur, Vcur, nullptr, nullptr, nullptr, kq_scale, il);
cb(cur, "attn_out", il);
// attention gating: attn_out * sigmoid(gate) BEFORE o_proj
gate = ggml_sigmoid(ctx0, gate);
cb(gate, "attn_gate_sig", il);
cur = ggml_mul(ctx0, cur, gate);
cb(cur, "attn_gated", il);
// now apply output projection
cur = build_lora_mm(model.layers[il].wo, cur);
cb(cur, "attn_o_proj", il);
}
if (il == n_layer - 1 && inp_out_ids) {
cur = ggml_get_rows(ctx0, cur, inp_out_ids);
inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
}
ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
cb(ffn_inp, "ffn_inp", il);
// FFN pre-normalization (pre)
cur = build_norm(ffn_inp,
model.layers[il].ffn_norm, NULL,
LLM_NORM_RMS, il);
cb(cur, "ffn_norm", il);
// MoE or dense FFN
if ((uint32_t)il >= hparams.n_layer_dense_lead) {
ggml_tensor * moe_out = build_moe_ffn(cur,
model.layers[il].ffn_gate_inp,
model.layers[il].ffn_up_exps,
model.layers[il].ffn_gate_exps,
model.layers[il].ffn_down_exps,
model.layers[il].ffn_exp_probs_b,
n_expert, n_expert_used,
LLM_FFN_SILU,
hparams.expert_weights_norm,
hparams.expert_weights_scale,
(llama_expert_gating_func_type) hparams.expert_gating_func,
il);
cb(moe_out, "ffn_moe_out", il);
// shared expert
if (hparams.n_expert_shared > 0) {
ggml_tensor * ffn_shexp = build_ffn(cur,
model.layers[il].ffn_up_shexp, NULL,
model.layers[il].ffn_gate_shexp, NULL,
model.layers[il].ffn_down_shexp, NULL,
NULL,
LLM_FFN_SILU, LLM_FFN_PAR, il);
cb(ffn_shexp, "ffn_shexp", il);
cur = ggml_add(ctx0, moe_out, ffn_shexp);
cb(cur, "ffn_out", il);
} else {
cur = moe_out;
}
} else {
// dense layer
cur = build_ffn(cur,
model.layers[il].ffn_up, NULL,
model.layers[il].ffn_gate, NULL,
model.layers[il].ffn_down, NULL,
NULL,
LLM_FFN_SILU, LLM_FFN_PAR, il);
cb(cur, "ffn_out", il);
}
cur = ggml_add(ctx0, cur, ffn_inp);
cur = build_cvec(cur, il);
cb(cur, "l_out", il);
// input for next layer
inpL = cur;
}
cur = inpL;
cur = build_norm(cur,
model.output_norm, NULL,
LLM_NORM_RMS, -1);
cb(cur, "result_norm", -1);
res->t_embd = cur;
// lm_head
cur = build_lora_mm(model.output, cur);
cb(cur, "result_output", -1);
res->t_logits = cur;
}
+12
View File
@@ -2311,6 +2311,18 @@ struct llama_model_afmoe : public llama_model_base {
std::unique_ptr<llm_graph_context> build_arch_graph(const llm_graph_params & params) const override;
};
struct llama_model_minicpm5_moe : public llama_model_base {
llama_model_minicpm5_moe(const struct llama_model_params & params) : llama_model_base(params) {}
void load_arch_hparams(llama_model_loader & ml) override;
void load_arch_tensors(llama_model_loader & ml) override;
struct graph : public llm_graph_context {
graph(const llm_graph_params & params);
};
std::unique_ptr<llm_graph_context> build_arch_graph(const llm_graph_params & params) const override;
};
struct llama_model_beam : public llama_model_base {
llama_model_beam(const struct llama_model_params & params) : llama_model_base(params) {}
void load_arch_hparams(llama_model_loader & ml) override;
+4
View File
@@ -241,6 +241,10 @@ minicpm ,1 ,any ,MUL+ADD , 4
minicpm ,1 ,any ,RMS_NORM+MUL , 5
minicpm ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
minicpm3 ,0 ,any ,RMS_NORM+MUL , 9
minicpm5_moe ,1 ,any ,ADD+ADD , 1
minicpm5_moe ,1 ,any ,MUL+ADD , 2
minicpm5_moe ,1 ,any ,RMS_NORM+MUL , 5
minicpm5_moe ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV+SCALE, 1
minimax-01 ,1 ,any ,MUL+ADD , 4
minimax-01 ,1 ,any ,RMS_NORM+MUL , 6
minimax-01 ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
1 # test-fusion baseline for device MTL
241 minicpm ,1 ,any ,RMS_NORM+MUL , 5
242 minicpm ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
243 minicpm3 ,0 ,any ,RMS_NORM+MUL , 9
244 minicpm5_moe ,1 ,any ,ADD+ADD , 1
245 minicpm5_moe ,1 ,any ,MUL+ADD , 2
246 minicpm5_moe ,1 ,any ,RMS_NORM+MUL , 5
247 minicpm5_moe ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV+SCALE, 1
248 minimax-01 ,1 ,any ,MUL+ADD , 4
249 minimax-01 ,1 ,any ,RMS_NORM+MUL , 6
250 minimax-01 ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
+9 -3
View File
@@ -289,7 +289,7 @@ static gguf_context_ptr get_gguf_ctx(const llm_arch arch, const bool moe, const
n_layer = 6;
} else if (arch == LLM_ARCH_STEP35 || arch == LLM_ARCH_LAGUNA) {
n_embd = 160; // exercise per-head tensor split granularity with head size 80
} else if (arch == LLM_ARCH_QWEN3 || arch == LLM_ARCH_MUSE_GLIMMER || arch == LLM_ARCH_AFMOE || arch == LLM_ARCH_RICURSIVE) {
} else if (arch == LLM_ARCH_QWEN3 || arch == LLM_ARCH_MUSE_GLIMMER || arch == LLM_ARCH_AFMOE || arch == LLM_ARCH_MINICPM5_MOE || arch == LLM_ARCH_RICURSIVE) {
n_head = 4;
} else if (arch == LLM_ARCH_LIMITE) {
n_head = 4;
@@ -345,7 +345,7 @@ static gguf_context_ptr get_gguf_ctx(const llm_arch arch, const bool moe, const
n_head_kv = 1; // MQA coverage
} else if (arch == LLM_ARCH_MUSE_GLIMMER || arch == LLM_ARCH_MUSE_SPARK || arch == LLM_ARCH_AFMOE || arch == LLM_ARCH_MAION_CODER ||
arch == LLM_ARCH_KOLIBRI1 || arch == LLM_ARCH_LIMITE || arch == LLM_ARCH_GEMMA4 || arch == LLM_ARCH_RICURSIVE ||
arch == LLM_ARCH_ZAYA1) {
arch == LLM_ARCH_ZAYA1 || arch == LLM_ARCH_MINICPM5_MOE) {
n_head_kv = 2; // GQA coverage
}
if (arch == LLM_ARCH_BEAM) {
@@ -354,7 +354,7 @@ static gguf_context_ptr get_gguf_ctx(const llm_arch arch, const bool moe, const
n_layer = 4;
}
n_layer = std::max(n_layer, n_layer_min);
const uint32_t n_embd_head = n_embd / n_head;
const uint32_t n_embd_head = (arch == LLM_ARCH_MINICPM5_MOE ? 2 : 1) * n_embd / n_head;
ms.add_kv(LLM_KV_GENERAL_ARCHITECTURE, llama_arch_name(arch));
ms.add_kv(LLM_KV_VOCAB_SIZE, n_vocab);
@@ -866,6 +866,11 @@ static gguf_context_ptr get_gguf_ctx(const llm_arch arch, const bool moe, const
}
}
if (arch == LLM_ARCH_MINICPM5_MOE) {
ms.add_kv(LLM_KV_EXPERT_WEIGHTS_SCALE, 3.66f);
ms.add_kv(LLM_KV_EXPERT_WEIGHTS_NORM, true);
}
if (arch == LLM_ARCH_BEAM) {
ms.add_kv(LLM_KV_EXPERT_COUNT, uint32_t(8));
ms.add_kv(LLM_KV_EXPERT_GROUP_COUNT, uint32_t(4));
@@ -1201,6 +1206,7 @@ static bool moe_mandatory(const llm_arch arch) {
case LLM_ARCH_BAILINGMOE3:
case LLM_ARCH_DOTS1:
case LLM_ARCH_AFMOE:
case LLM_ARCH_MINICPM5_MOE:
case LLM_ARCH_BEAM:
case LLM_ARCH_ERNIE4_5:
case LLM_ARCH_ERNIE4_5_MOE:
+47
View File
@@ -653,6 +653,53 @@ MAKE_TEST(test_audio_preprocessor_qwen3a_tail) {
}
}
// audio rows are zero-padded to the (deepstack) vision width, e.g. Qwen3-Omni
MAKE_TEST(test_audio_embd_pad_rows) {
{
// one row, 2 -> 8
std::vector<float> embd = {1.f, 2.f};
mtmd_audio_embd_pad_rows(embd, 1, 2, 8);
t.assert_equal("one row size", (size_t) 8, embd.size());
const std::vector<float> want = {1.f, 2.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f};
bool content = embd.size() == want.size();
for (size_t i = 0; i < embd.size() && i < want.size(); ++i) {
content = content && embd[i] == want[i];
}
t.assert_true("one row zero-padded", content);
}
{
// three rows, 4 -> 8: rows must keep their order and never leak into each other
const size_t n_tokens = 3, n_embd_row = 4, n_embd_out = 8;
std::vector<float> embd;
for (size_t i = 0; i < n_tokens * n_embd_row; ++i) {
embd.push_back((float) i);
}
mtmd_audio_embd_pad_rows(embd, n_tokens, n_embd_row, n_embd_out);
t.assert_equal("three rows size", n_tokens * n_embd_out, embd.size());
bool content = embd.size() == n_tokens * n_embd_out;
for (size_t i = 0; i < n_tokens && content; ++i) {
for (size_t j = 0; content && j < n_embd_out; ++j) {
const float want = j < n_embd_row ? (float) (i * n_embd_row + j) : 0.0f;
content = content && embd[i * n_embd_out + j] == want;
}
}
t.assert_true("three rows content", content);
}
{
// no-op when the widths match
std::vector<float> embd = {1.f, 2.f, 3.f, 4.f};
mtmd_audio_embd_pad_rows(embd, 2, 2, 2);
t.assert_equal("identity size", (size_t) 4, embd.size());
t.assert_true("identity content", embd == std::vector<float>({1.f, 2.f, 3.f, 4.f}));
}
{
// no rows: nothing to pad, and the row 0 fill must not touch out-of-bounds memory
std::vector<float> embd;
mtmd_audio_embd_pad_rows(embd, 0, 2, 8);
t.assert_equal("zero rows size", (size_t) 0, embd.size());
}
}
MAKE_TEST(test_audio_preprocessor_conformer) {
mtmd_hparams hparams;
hparams.n_mel_bins = 128;
+3 -1
View File
@@ -229,7 +229,9 @@ class TestFP8Conversion(unittest.TestCase):
scales = torch.tensor([0.125, 0.25, 0.5, 1.]).reshape(4, 1)
for eager in (False, True):
with self.subTest(eager=eager):
result = self.convert(ReorderedRowsModel, {name: weight, name + "_scale": scales}, eager=eager, check_lazy=not eager)
with self.assertLogs("hf-to-gguf", level="WARNING") as logs:
result = self.convert(ReorderedRowsModel, {name: weight, name + "_scale": scales}, eager=eager, check_lazy=not eager)
self.assertIn(f"1 FP8 weights will be dequantized, ReorderedRowsModel cannot keep their per-channel scales (first: {name})", "\n".join(logs.output))
dtype, data = result["blk.0.attn_q.weight"]
self.assertEqual(dtype, gguf.GGMLQuantizationType.F16)
np.testing.assert_array_equal(data, (weight.float() * scales).flip(0).numpy())
+22
View File
@@ -14,6 +14,28 @@
constexpr bool DEBUG = false;
void mtmd_audio_embd_pad_rows(std::vector<float> & embd, size_t n_tokens, size_t n_embd_row, size_t n_embd_out) {
GGML_ASSERT(n_embd_row > 0 && n_embd_out >= n_embd_row);
GGML_ASSERT(n_embd_out % n_embd_row == 0);
GGML_ASSERT(embd.size() == n_tokens * n_embd_row);
if (n_tokens == 0 || n_embd_out == n_embd_row) {
return;
}
embd.resize(n_tokens * n_embd_out);
// last to first: a row's source must be read before its slot is overwritten
for (size_t i = n_tokens; i-- > 1;) {
auto row = embd.begin() + (i * n_embd_out);
std::copy_backward(embd.begin() + i * n_embd_row, embd.begin() + (i + 1) * n_embd_row, row + n_embd_row);
std::fill(row + n_embd_row, embd.begin() + (i + 1) * n_embd_out, 0.0f);
}
// row 0 is already in place, only its padding is zeroed
std::fill(embd.begin() + n_embd_row, embd.begin() + n_embd_out, 0.0f);
}
void mtmd_audio_cache::fill_sin_cos_table(uint32_t n) {
sin_vals.resize(n);
cos_vals.resize(n);
+4
View File
@@ -10,6 +10,10 @@
#define MTMD_INTERNAL_HEADER
// zero-pad each row of embd from n_embd_row to n_embd_out values. No-op when equal.
// e.g. the audio rows of Qwen3-Omni are padded to the deepstack vision width.
void mtmd_audio_embd_pad_rows(std::vector<float> & embd, size_t n_tokens, size_t n_embd_row, size_t n_embd_out);
struct mtmd_audio_mel {
int64_t n_len;
int64_t n_len_org;
+19 -5
View File
@@ -1001,18 +1001,23 @@ struct mtmd_context {
}
// if both vision and audio mmproj are present, we need to validate their n_embd
// deepstack vision rows are wider (e.g. Qwen3-Omni); the audio rows are zero-padded to that width
if (ctx_v && ctx_a) {
int n_embd_v = ctx_v->model.n_mmproj_embd();
int n_embd_a = ctx_a->model.n_mmproj_embd();
if (n_embd_v != n_embd_a) {
if (n_embd_a <= 0) {
throw std::runtime_error(mtmd_format(
"mismatch between vision and audio mmproj (n_embd_v = %d, n_embd_a = %d)\n",
"invalid audio mmproj, its width is %d\n", n_embd_a));
}
if (n_embd_v != (int64_t) n_embd_a * (1 + ctx_v->model.n_deepstack_layers)) {
throw std::runtime_error(mtmd_format(
"mismatch between vision and audio mmproj (n_embd_v = %d, n_embd_a = %d),"
" the vision width must be the audio width times (1 + deepstack layers of the vision model)\n",
n_embd_v, n_embd_a));
}
}
// since we already validate n_embd of vision and audio mmproj,
// we can safely assume that they are the same
// the vision width is the row width of the context, the audio rows are padded to it
// a gen-only mmproj is validated below
int n_embd_mmproj = ctx_v || ctx_a ? (ctx_v ? ctx_v : ctx_a)->model.n_mmproj_embd() : n_embd_text;
if (n_embd_text > 0 && n_embd_text != n_embd_mmproj) {
@@ -2753,6 +2758,8 @@ static int32_t mtmd_encode_chunk_impl(mtmd_context * ctx, const mtmd_input_chunk
}
if (track) {
if (track->embd.empty()) {
// no padding here: this path requires n_embd_out() to equal the audio width
// (soundtrack tracks are LFM3-only today, models without deepstack vision)
track->embd.resize((size_t) track->n_tokens * ctx->n_embd_out());
if (!mtmd_audio_batch_encode(ctx, track->batch_f32, track->source.get(), 0, track->embd)) {
track->embd.clear();
@@ -2780,8 +2787,15 @@ static int32_t mtmd_encode_chunk_impl(mtmd_context * ctx, const mtmd_input_chunk
if (ctx->ctx_a->model.proj_type == PROJECTOR_TYPE_QWEN3TTS_SPKENC && chunk->tokens_audio->batch_f32.entries.size() == 2) {
return mtmd_qwen3tts_ref_encode(ctx, chunk->tokens_audio.get(), out_embd);
}
out_embd.resize((size_t)chunk->tokens_audio->n_tokens * ctx->n_embd_out());
// the audio graph writes rows of the audio width; pad to the vision width if wider
const size_t n_tokens = chunk->tokens_audio->n_tokens;
const size_t n_embd_a = ctx->ctx_a->model.n_mmproj_embd();
const size_t n_embd_out = ctx->n_embd_out();
out_embd.resize(n_tokens * n_embd_a);
bool ok = mtmd_audio_batch_encode(ctx, chunk->tokens_audio->batch_f32, chunk->tokens_audio->source.get(), chunk->tokens_audio->source_idx, out_embd);
if (ok && n_embd_out != n_embd_a) {
mtmd_audio_embd_pad_rows(out_embd, n_tokens, n_embd_a, n_embd_out);
}
return ok ? 0 : 1;
}
+130 -95
View File
@@ -5986,75 +5986,6 @@ std::string escape_quoted_pairs(const std::string &s) {
return out;
}
// RFC 9110 Section 11.6.1 defines a challenge list as
// WWW-Authenticate = #challenge
// challenge = auth-scheme [ 1*SP ( token68 / [ #auth-param ] ) ]
// auth-param = token BWS "=" BWS ( token / quoted-string )
// so a server may offer several schemes, each with its own comma-separated
// auth-param list, in either order and either as separate field lines or
// packed into one. Splitting on every comma would break apart a challenge's
// own param list; splitting only on the first space would miss a Digest
// challenge that isn't first. Split on commas that aren't inside a
// quoted-string instead (split_unquoted), then track which scheme each
// resulting segment belongs to: a segment whose text before "=" contains
// whitespace (or that has no "=" at all) starts a new challenge named by its
// leading token.
bool parse_www_authenticate(const Response &res,
std::map<std::string, std::string> &auth,
bool is_proxy) {
auto auth_key = is_proxy ? "Proxy-Authenticate" : "WWW-Authenticate";
auto combined = get_combined_header_value(res.headers, auth_key);
if (combined.empty()) { return false; }
auto found_digest = false;
auto in_digest_challenge = false;
split_unquoted(
combined.data(), combined.data() + combined.size(), ',',
[&](const char *b, const char *e) {
std::string segment(b, e);
auto eq_pos = segment.find('=');
// BWS is allowed on both sides of "=", so the text naming the key (or,
// for the first segment of a challenge, "<scheme> <key>") must be
// trimmed before its boundaries are inspected.
auto key_part = trim_copy(
eq_pos == std::string::npos ? segment : segment.substr(0, eq_pos));
auto space_pos = key_part.find_last_of(" \t");
if (space_pos != std::string::npos || eq_pos == std::string::npos) {
// "<scheme>[ <key>]" starts a new challenge.
auto scheme_end =
space_pos == std::string::npos ? key_part.size() : space_pos;
// RFC 7616 Section 3.7: a server may offer more than one Digest
// challenge (e.g. SHA-256 and MD5); keep only the first so a nonce
// from one challenge is never paired with another's algorithm.
in_digest_challenge =
!found_digest &&
case_ignore::equal(key_part.substr(0, scheme_end), "Digest");
if (in_digest_challenge) { found_digest = true; }
if (space_pos == std::string::npos) {
// Bare scheme (or a token68), no auth-param on this segment.
return;
}
key_part = key_part.substr(space_pos + 1);
}
if (!in_digest_challenge) { return; }
auto val = trim_copy(segment.substr(eq_pos + 1));
auto unquoted = trim_double_quotes_copy(val);
if (unquoted.size() != val.size()) {
unquoted = unescape_quoted_pairs(unquoted);
}
auth[std::move(key_part)] = std::move(unquoted);
});
// RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge;
// make_digest_authentication_header() dereferences both unconditionally, so
// a challenge missing either can't produce a usable Authorization header.
// Treat it the same as no Digest challenge at all.
return found_digest && auth.find("realm") != auth.end() &&
auth.find("nonce") != auth.end();
}
class ContentProviderAdapter {
public:
explicit ContentProviderAdapter(
@@ -6523,6 +6454,121 @@ bool process_client_socket_ssl(
return callback(strm);
}
using DigestHash = std::string (*)(const std::string &);
// The Digest algorithms the client implements, matched case-insensitively;
// nullptr for any other.
DigestHash digest_hash(const std::string &algorithm) {
if (case_ignore::equal(algorithm, "MD5")) { return detail::MD5; }
if (case_ignore::equal(algorithm, "SHA-256")) { return detail::SHA_256; }
if (case_ignore::equal(algorithm, "SHA-512")) { return detail::SHA_512; }
return nullptr;
}
// Picks auth over auth-int from the qop options a server offers, as curl does:
// auth-int hashes req.body, which is empty when a content provider streams the
// body. Empty when it offers neither.
std::string select_digest_qop(const std::string &options) {
std::string qop;
split(options.data(), options.data() + options.size(), ',',
[&](const char *b, const char *e) {
std::string option(b, e);
if (case_ignore::equal(option, "auth")) {
qop = "auth";
} else if (qop.empty() && case_ignore::equal(option, "auth-int")) {
qop = "auth-int";
}
});
return qop;
}
// RFC 9110 Section 11.6.1 defines a challenge list as
// WWW-Authenticate = #challenge
// challenge = auth-scheme [ 1*SP ( token68 / [ #auth-param ] ) ]
// auth-param = token BWS "=" BWS ( token / quoted-string )
// so a server may offer several schemes, each with its own comma-separated
// auth-param list, in either order and either as separate field lines or
// packed into one. Splitting on every comma would break apart a challenge's
// own param list; splitting only on the first space would miss a Digest
// challenge that isn't first. Split on commas that aren't inside a
// quoted-string instead (split_unquoted), then track which scheme each
// resulting segment belongs to: a segment whose text before "=" contains
// whitespace (or that has no "=" at all) starts a new challenge named by its
// leading token.
bool parse_www_authenticate(const Response &res,
std::map<std::string, std::string> &auth,
bool is_proxy) {
auto auth_key = is_proxy ? "Proxy-Authenticate" : "WWW-Authenticate";
auto combined = get_combined_header_value(res.headers, auth_key);
if (combined.empty()) { return false; }
// RFC 7616 Section 3.7: a server may offer more than one Digest challenge
// (e.g. SHA-256 and MD5), and the client uses the first one it supports.
// A challenge whose algorithm the client doesn't implement is ignored
// (Section 3.3), as is one whose qop offers neither auth nor auth-int, and
// one without realm and nonce can't be answered. Params are collected per
// challenge, so a nonce from one is never paired with another's algorithm.
auto answerable = [](const std::map<std::string, std::string> &c) {
if (c.find("realm") == c.end() || c.find("nonce") == c.end()) {
return false;
}
auto algo_it = c.find("algorithm");
if (algo_it != c.end() && !digest_hash(algo_it->second)) { return false; }
auto qop_it = c.find("qop");
return qop_it == c.end() || !select_digest_qop(qop_it->second).empty();
};
auto found = false;
auto in_digest_challenge = false;
std::map<std::string, std::string> challenge;
auto take_challenge_if_answerable = [&] {
if (!found && in_digest_challenge && answerable(challenge)) {
auth = std::move(challenge);
found = true;
}
challenge.clear();
};
split_unquoted(
combined.data(), combined.data() + combined.size(), ',',
[&](const char *b, const char *e) {
std::string segment(b, e);
auto eq_pos = segment.find('=');
// BWS is allowed on both sides of "=", so the text naming the key (or,
// for the first segment of a challenge, "<scheme> <key>") must be
// trimmed before its boundaries are inspected.
auto key_part = trim_copy(
eq_pos == std::string::npos ? segment : segment.substr(0, eq_pos));
auto space_pos = key_part.find_first_of(" \t");
if (space_pos != std::string::npos || eq_pos == std::string::npos) {
// "<scheme>[ <key>]" starts a new challenge.
take_challenge_if_answerable();
auto scheme_end =
space_pos == std::string::npos ? key_part.size() : space_pos;
in_digest_challenge =
case_ignore::equal(key_part.substr(0, scheme_end), "Digest");
if (space_pos == std::string::npos) {
// Bare scheme (or a token68), no auth-param on this segment.
return;
}
key_part = trim_copy(key_part.substr(space_pos + 1));
}
if (!in_digest_challenge) { return; }
auto val = trim_copy(segment.substr(eq_pos + 1));
auto unquoted = trim_double_quotes_copy(val);
if (unquoted.size() != val.size()) {
unquoted = unescape_quoted_pairs(unquoted);
}
// auth-param names are case-insensitive (RFC 9110 Section 11.2)
challenge[case_ignore::to_lower(key_part)] = std::move(unquoted);
});
take_challenge_if_answerable();
return found;
}
// `uri` is req's request-target in origin form, as curl sends it, also when
// the request line carries the absolute form for a proxy.
std::pair<std::string, std::string> make_digest_authentication_header(
@@ -6537,33 +6583,21 @@ std::pair<std::string, std::string> make_digest_authentication_header(
nc = ss.str();
}
std::string qop;
if (auth.find("qop") != auth.end()) {
qop = auth.at("qop");
if (qop.find("auth-int") != std::string::npos) {
qop = "auth-int";
} else if (qop.find("auth") != std::string::npos) {
qop = "auth";
} else {
qop.clear();
}
}
// Without qop, the RFC 2069 form is used.
auto qop_it = auth.find("qop");
auto qop =
qop_it == auth.end() ? std::string() : select_digest_qop(qop_it->second);
assert(qop_it == auth.end() || !qop.empty());
std::string algo = "MD5";
if (auth.find("algorithm") != auth.end()) {
// algorithm is an unquoted token (RFC 7616 §3.4). A server value that is
// not a token would otherwise be emitted verbatim and could carry commas
// or quotes that inject further auth-params into the header below.
const auto &a = auth.at("algorithm");
if (fields::is_token(a)) { algo = a; }
}
// Sent back as the server wrote it (RFC 7616 Section 3.4).
// parse_www_authenticate() accepts only one digest_hash() knows.
auto algo_it = auth.find("algorithm");
auto algo = algo_it == auth.end() ? std::string("MD5") : algo_it->second;
auto H = digest_hash(algo);
assert(H);
std::string response;
{
auto H = algo == "SHA-256" ? detail::SHA_256
: algo == "SHA-512" ? detail::SHA_512
: detail::MD5;
auto A1 = username + ":" + auth.at("realm") + ":" + password;
auto A2 = req.method + ":" + uri;
@@ -7058,15 +7092,16 @@ bool set_socket_opt(socket_t sock, int level, int optname, int optval) {
}
std::string get_bearer_token_auth(const Request &req) {
// The auth scheme is case-insensitive (RFC 9110 11.1), and a value shorter
// than the prefix carries no token.
// The auth scheme is case-insensitive (RFC 9110 11.1) and followed by 1*SP,
// and a value shorter than the prefix carries no token.
constexpr const char bearer_prefix[] = "Bearer ";
constexpr auto bearer_prefix_len = detail::str_len(bearer_prefix);
auto value = req.get_header_value("Authorization");
if (value.size() >= bearer_prefix_len &&
detail::case_ignore::equal(value.substr(0, bearer_prefix_len),
bearer_prefix)) {
return value.substr(bearer_prefix_len);
auto pos = value.find_first_not_of(' ', bearer_prefix_len);
if (pos != std::string::npos) { return value.substr(pos); }
}
return "";
}
+9 -2
View File
@@ -8,8 +8,8 @@
#ifndef CPPHTTPLIB_HTTPLIB_H
#define CPPHTTPLIB_HTTPLIB_H
#define CPPHTTPLIB_VERSION "0.68.0"
#define CPPHTTPLIB_VERSION_NUM "0x004400"
#define CPPHTTPLIB_VERSION "0.69.0"
#define CPPHTTPLIB_VERSION_NUM "0x004500"
#ifdef _WIN32
#if defined(_WIN32_WINNT) && _WIN32_WINNT < 0x0A00
@@ -565,6 +565,13 @@ using socket_t = int;
#define CPPHTTPLIB_MBEDTLS_V3
#endif
// SSLServer (and SSLClients on several threads) use Mbed TLS concurrently.
#if !defined(MBEDTLS_THREADING_C) && \
!defined(CPPHTTPLIB_MBEDTLS_SINGLE_THREADED)
#error \
"Mbed TLS must be built with MBEDTLS_THREADING_C. Define CPPHTTPLIB_MBEDTLS_SINGLE_THREADED if it is only ever used from one thread."
#endif
#endif // CPPHTTPLIB_MBEDTLS_SUPPORT
#ifdef CPPHTTPLIB_WOLFSSL_SUPPORT