From 71b9f54dffd512f23cb74f20189e924d0f5141b5 Mon Sep 17 00:00:00 2001 From: Prabhsimran Singh Date: Wed, 18 Nov 2026 19:20:09 +0530 Subject: [PATCH 01/10] feat(convert): SALM GGUFs from a ModelOpt NVFP4 checkpoint - convert_model.py --architecture salm accepts a ModelOpt checkpoint (hf_quant_config.json, NVFP4 and FP8 layers) in the Hugging Face NemotronH layout, with --outtype nvfp4 only - the decoder comes straight from llama.cpp's converter: NVFP4 tensors keep their blocks and scales, FP8 tensors their E4M3 values in BF16 and a .scale tensor; the MTP layer's FP8 tensors are written dequantized, as BF16 - the encoder file defaults to F32, which holds the FP8 encoder weights; --salm-encoder f32 for any checkpoint - converter contract tests; model-conversion.md and salm/models.md Signed-off-by: Prabhsimran Singh --- conversion/pee.py | 26 +++- conversion/salm.py | 124 +++++++++++++++----- conversion/salm_decoder_hf.py | 69 ++++++++++- convert_model.py | 7 +- docs/model-conversion.md | 8 ++ docs/salm/models.md | 5 +- tests/conversion/converter_contract_test.py | 91 ++++++++++++++ 7 files changed, 288 insertions(+), 42 deletions(-) diff --git a/conversion/pee.py b/conversion/pee.py index 1e21853..9f4558c 100644 --- a/conversion/pee.py +++ b/conversion/pee.py @@ -212,7 +212,10 @@ def _add_branch(gw: GGUFWriter, branch: str, hp: dict) -> None: def _load_salm_perception(path: Path) -> tuple[dict, dict]: - """PEE config and ``perception.*`` tensors (prefix stripped) from a SALM checkpoint dir.""" + """PEE config and ``perception.*`` tensors (prefix stripped) from a SALM checkpoint dir. ModelOpt FP8 linears + (E4M3 weight and a per-tensor ``weight_scale``) are dequantized to F32, which holds the product exactly; their + scale tensors are dropped.""" + import torch from safetensors import safe_open with (path / "config.json").open("r", encoding="utf-8") as f: @@ -220,9 +223,24 @@ def _load_salm_perception(path: Path) -> tuple[dict, dict]: sd: dict = {} for shard in sorted(path.glob("*.safetensors")): with safe_open(str(shard), framework="pt", device="cpu") as f: - for key in f.keys(): - if key.startswith(_SALM_PREFIX) and "_extra_state" not in key: - sd[key[len(_SALM_PREFIX) :]] = f.get_tensor(key) + keys = set(f.keys()) + for key in sorted(keys): + if not key.startswith(_SALM_PREFIX) or "_extra_state" in key: + continue + if key.endswith((".weight_scale", ".input_scale", ".weight_scale_2")): + continue # applied to their weight below + tensor = f.get_tensor(key) + scale_key = key.removesuffix(".weight") + ".weight_scale" + if tensor.dtype == torch.float8_e4m3fn: + scale = f.get_tensor(scale_key) if scale_key in keys else None + if scale is None or scale.numel() != 1: + raise RuntimeError(f"{key}: an FP8 weight needs one per-tensor {scale_key}") + tensor = tensor.float() * scale.float() + elif scale_key in keys: + raise RuntimeError( + f"{key}: unsupported quantized encoder weight ({tensor.dtype})" + ) + sd[key[len(_SALM_PREFIX) :]] = tensor if not sd: raise RuntimeError(f"no perception.* tensors found in {path}") return cfg, sd diff --git a/conversion/salm.py b/conversion/salm.py index b4a152e..0f4b78f 100644 --- a/conversion/salm.py +++ b/conversion/salm.py @@ -21,6 +21,11 @@ The speech encoder (conversion/pee.py) is F16 ("none" writes the decoder alone, for a second profile of a checkpoint whose encoder file exists) and the CTC timestamp head (conversion/ctc_timestamp.py) comes from the checkpoint when it carries one (ctc_timestamp.*). + +A checkpoint quantized with ModelOpt (hf_quant_config.json; NVFP4 and FP8 layers, Hugging Face NemotronH tensor +names) keeps its weights: it converts to `nvfp4` only, the decoder straight from llama.cpp's converter without +llama-quantize. NVFP4 tensors keep their blocks and scales, FP8 tensors become their BF16 values and a per-tensor +scale (salm_decoder_hf.py), and the encoder file defaults to F32, which holds the FP8 encoder linears exactly. """ from __future__ import annotations @@ -49,8 +54,10 @@ } # the dense linears of each profile Q2_KEPT_MOE_LAYERS = 5 # q2_0: the last MoE layers whose routed experts stay IQ4_NL Q2_0_BLOCK_BYTES = 18 # FP16 scale and 64 2-bit codes -ENCODER_TYPES = ("f16", "none") +ENCODER_TYPES = ("f16", "f32", "none") DEFAULT_ENCODER = "f16" +QUANTIZED_ENCODER = "f32" # the default for a ModelOpt checkpoint: its FP8 encoder linears exactly +MODELOPT_ALGOS = {"NVFP4", "FP8"} # the ModelOpt layer formats a checkpoint may use ENCODER_FILE_KEY = "nemo_speech.speech_model" # the encoder file the decoder names CHECKPOINT_ID_KEY = "nemo_speech.checkpoint_id" EXPERT_TENSORS = "ffn_(up|down|gate)_exps" @@ -76,6 +83,30 @@ def backbone_config(source: Path) -> dict: raise RuntimeError(f"{source}: no llm_backbone/config.json and no llm_config in config.json") +def modelopt_quantization(source: Path) -> dict | None: + """The `quantization` section of a ModelOpt checkpoint's hf_quant_config.json, or None for an unquantized one. + Raises for layer formats other than NVFP4 and FP8 or a quantized KV cache.""" + path = source / "hf_quant_config.json" + if not path.is_file(): + return None + config = json.loads(path.read_text(encoding="utf-8")) + if (config.get("producer") or {}).get("name", "").lower() != "modelopt": + raise RuntimeError(f"{path}: not a ModelOpt quantization config") + quantization = config.get("quantization") or {} + algos = { + layer.get("quant_algo") + for layer in (quantization.get("quantized_layers") or {}).values() + if isinstance(layer, dict) + } or {quantization.get("quant_algo")} + if not algos <= MODELOPT_ALGOS: + raise RuntimeError( + f"{path}: unsupported ModelOpt formats {sorted(str(a) for a in algos - MODELOPT_ALGOS)}" + ) + if quantization.get("kv_cache_quant_algo"): + raise RuntimeError(f"{path}: a quantized KV cache is not supported") + return quantization + + def kept_expert_layers(profile: str, config: dict) -> list[int]: """The decoder blocks whose routed experts stay IQ4_NL: for q2_0 the last MoE layers of the main stack.""" if profile != "q2_0": @@ -116,8 +147,12 @@ def stage(source: Path, staging: Path, weights: bool = True) -> None: (staging / "tokenizer_config.json").write_text( json.dumps(tokenizer_config, indent=2, ensure_ascii=False), encoding="utf-8" ) - if (source / "generation_config.json").is_file(): - shutil.copyfile(source / "generation_config.json", staging / "generation_config.json") + for name in ( + "generation_config.json", + "hf_quant_config.json", + ): # the converter reads ModelOpt's config + if (source / name).is_file(): + shutil.copyfile(source / name, staging / name) if not weights: return @@ -141,14 +176,22 @@ def convert( ) -> None: profile = normalize_profile(profile) dense = DENSE_TYPE[profile] - encoder = encoder_type(profile, encoder) + quantized = modelopt_quantization(source) is not None + if quantized and profile != "nvfp4": + raise ValueError( + f"{source} is quantized with ModelOpt and converts to --outtype nvfp4 only, keeping its weights; " + f"convert {profile} from the BF16 checkpoint" + ) + encoder = encoder_type(profile, encoder, quantized) if encoder not in ENCODER_TYPES: - raise ValueError("salm encoder type must be " + " or ".join(ENCODER_TYPES)) + raise ValueError("salm encoder type must be " + ", ".join(ENCODER_TYPES)) name = checkpoint_name or source.name repository = Path(__file__).resolve().parent.parent llama = ensure_llama_checkout(llama_cpp or repository / "llama.cpp", repository) quantize = None - if not dry_run: # before the long conversion, so a missing quantizer fails fast + if ( + not dry_run and not quantized + ): # before the long conversion, so a missing quantizer fails fast quantize = ensure_quantizer( llama, quantizer, profile=profile, repo_root=repository, auto_build=auto_build_quantizer ) @@ -186,31 +229,46 @@ def convert( staging = work / "hf" print(f"[convert-salm] staging the decoder of {source}") stage(source, staging) - bf16 = work / "decoder-bf16.gguf" - print(f"[convert-salm] decoder -> BF16 GGUF {bf16}") - keys = decoder_keys(name, identity) - subprocess.run( - [ - sys.executable, - str(Path(__file__).with_name("salm_decoder_hf.py")), - str(llama), - str(staging), - "--outfile", - str(bf16), - "--outtype", - "bf16", - "--model-name", - f"{name} {profile.upper()}", - *[arg for key in keys for arg in ("--nemo-speech-key", key)], - *(["--dry-run"] if dry_run else []), - ], - check=True, + # a ModelOpt checkpoint's decoder comes straight from the converter (its weights are already quantized) + decoder = ( + outfile.with_name(outfile.name + ".writing") if quantized else work / "decoder-bf16.gguf" + ) + print( + f"[convert-salm] decoder -> {'GGUF with the checkpoint weights' if quantized else 'BF16 GGUF'} {decoder}" ) + paired = encoder if encoder != "none" else (QUANTIZED_ENCODER if quantized else DEFAULT_ENCODER) + keys = decoder_keys(name, identity, paired) + command = [ + sys.executable, + str(Path(__file__).with_name("salm_decoder_hf.py")), + str(llama), + str(staging), + "--outfile", + str(decoder), + "--outtype", + "bf16", + "--model-name", + f"{name} {profile.upper()}", + *[arg for key in keys for arg in ("--nemo-speech-key", key)], + *(["--dry-run"] if dry_run else []), + ] + try: + subprocess.run(command, check=True) + except BaseException: + if quantized: + decoder.unlink(missing_ok=True) + raise if dry_run: # tensor mapping checked, nothing written shutil.rmtree(work, ignore_errors=True) return + if quantized: + decoder.replace(outfile) + shutil.rmtree(work, ignore_errors=True) + if speech: + print(f"[convert-salm] {outfile.name} and its encoder file {speech.name}") + return quantize_decoder( - bf16, + decoder, outfile, profile, quantize, @@ -228,10 +286,13 @@ def encoder_file_name(name: str, encoder: str = DEFAULT_ENCODER) -> str: return f"{name}-Encoder-{encoder.upper()}.gguf" -def decoder_keys(name: str, identity: str) -> list[str]: +def decoder_keys(name: str, identity: str, encoder: str = DEFAULT_ENCODER) -> list[str]: """The decoder's nemo_speech keys: the checkpoint id and the encoder file it pairs with, also when this run writes no encoder file (--salm-encoder none reuses the checkpoint's existing one).""" - return [f"{CHECKPOINT_ID_KEY}={identity}", f"{ENCODER_FILE_KEY}={encoder_file_name(name)}"] + return [ + f"{CHECKPOINT_ID_KEY}={identity}", + f"{ENCODER_FILE_KEY}={encoder_file_name(name, encoder)}", + ] def checkpoint_id(source: Path) -> str: @@ -264,10 +325,11 @@ def ctc_checkpoint(source: Path) -> Path | None: return None -def encoder_type(profile: str, encoder: str | None = None) -> str: - """The encoder's type: F16 (every profile shares one encoder file), or "none".""" +def encoder_type(profile: str, encoder: str | None = None, quantized: bool = False) -> str: + """The encoder's type: F16 (every profile shares one encoder file), F32 by default for a ModelOpt checkpoint + (its FP8 encoder linears exactly), or "none".""" normalize_profile(profile) - return (encoder or DEFAULT_ENCODER).lower() + return (encoder or (QUANTIZED_ENCODER if quantized else DEFAULT_ENCODER)).lower() def tensor_rules( diff --git a/conversion/salm_decoder_hf.py b/conversion/salm_decoder_hf.py index 1403dab..a58f4c2 100644 --- a/conversion/salm_decoder_hf.py +++ b/conversion/salm_decoder_hf.py @@ -15,6 +15,13 @@ and the grouped expert weights are un-fused: Automodel stores `gate_and_up_projs [E, hidden, inter]` and `down_projs [E, inter, hidden]` as [in, out]; GGUF wants per-expert [out, in]. +A ModelOpt checkpoint (the NVFP4 checkpoint: `backbone.*` and `lm_head.*` already in the HF layout, the MTP layer as +`llm.mtp.*` with per-expert weights) keeps its weights. llama.cpp's converter writes its NVFP4 tensors as they are; +its FP8 tensors (E4M3 weight and a per-tensor `weight_scale`) become their values, exact in BF16, and a `.scale` +tensor that llama.cpp multiplies in after the matmul, instead of the dequantized product. The MTP layer's FP8 tensors +are the exception: they are written as the dequantized product in BF16, without `.scale` tensors, because llama.cpp +does not skip those when it loads the model without the MTP head. + `--nemo-speech-key KEY=VALUE` (repeatable) adds string keys this project's runtime reads (the encoder file the decoder pairs with and the checkpoint id, conversion/salm.py); llama-quantize carries them to the quantized file. @@ -38,8 +45,9 @@ import convert_hf_to_gguf # noqa: E402 import gguf # noqa: E402 +import torch # noqa: E402 -from conversion.base import ModelBase # noqa: E402 +from conversion.base import LazyTorchTensor, ModelBase # noqa: E402 from conversion.nemotron import NemotronHModel # noqa: E402 _PREFIX = "llm." @@ -49,6 +57,8 @@ ("llm.lm_head.weight", "lm_head.weight"), ) _FUSED = {"gate_and_up_projs": "up_proj", "down_projs": "down_proj"} +_HF_LAYOUT = ("backbone.", "lm_head.") # a checkpoint already in the HF NemotronH layout +_MTP = "mtp." # the MTP layer's tensors, after the re-keying @ModelBase.register("NemotronHForCausalLM") @@ -64,11 +74,19 @@ def set_gguf_parameters(self): for key, value in _KEYS: self.gguf_writer.add_string(key, value) + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self._fp8_scales = {} # FP8 weight name -> its per-tensor scale + @classmethod def filter_tensors(cls, item): name, gen = item - if not name.startswith(_PREFIX) or "_extra_state" in name: - return None # perception encoder and projection, TE extra-state blobs + if "_extra_state" in name: + return None # TE extra-state blobs + if name.startswith(_HF_LAYOUT): + return super().filter_tensors(item) + if not name.startswith(_PREFIX): + return None # perception encoder and projection, CTC timestamp head for src, dst in _RENAMES: if name == src: name = dst @@ -83,7 +101,52 @@ def filter_tensors(cls, item): name = name.replace("._fp32_params.", ".") return super().filter_tensors((name, gen)) + def dequant_model(self): + """ModelOpt FP8 weights: keep their E4M3 values (written as BF16, exact) and their per-tensor scale for a + `.scale` tensor, instead of llama.cpp's dequantized product. The MTP layer's are dequantized here (the + product, written as BF16; no `.scale`). NVFP4 tensors were written before this. + """ + quantization = self.hparams.get("quantization_config") or {} + if quantization.get("quant_method") == "modelopt": + for scale_name in [n for n in self.model_tensors if n.endswith(".weight_scale")]: + weight_name = scale_name.removesuffix("_scale") + weight = self.model_tensors.get(weight_name) + if weight is None or weight().dtype != torch.float8_e4m3fn: + continue + scale = LazyTorchTensor.to_eager(self.model_tensors.pop(scale_name)()).float() + if scale.numel() != 1: + raise ValueError( + f"{scale_name}: expected one FP8 scale per tensor, got {list(scale.shape)}" + ) + if weight_name.startswith(_MTP): + self.model_tensors[weight_name] = ( + lambda w=weight, s=scale.item(): w().float() * s + ) + else: + self._fp8_scales[weight_name] = scale.reshape(1) + self.model_tensors[weight_name] = lambda w=weight: w().float() + self.model_tensors.pop(weight_name.removesuffix(".weight") + ".input_scale", None) + super().dequant_model() + def modify_tensors(self, data_torch, name, bid): + written = [] + for new_name, data in self._modify_tensors(data_torch, name, bid): + written.append(new_name) + yield new_name, data + scale = self._fp8_scales.pop(name, None) + if scale is not None: + if len(written) != 1: # stacked experts would need one scale per expert + raise ValueError( + f"{name}: an FP8 weight outside the MTP layer that is not written as one tensor" + ) + self._write_scale_tensor(written[0].removesuffix(".weight") + ".scale", scale) + + def prepare_tensors(self): + super().prepare_tensors() + if self._fp8_scales: + raise ValueError(f"FP8 scales without their weights: {list(self._fp8_scales)}") + + def _modify_tensors(self, data_torch, name, bid): leaf = name.rsplit(".", 1)[-1] if ".mixer.experts." in name and leaf in _FUSED: if name.startswith("mtp.layers."): diff --git a/convert_model.py b/convert_model.py index 4f4d6cb..6e389f8 100644 --- a/convert_model.py +++ b/convert_model.py @@ -65,9 +65,10 @@ def parse_args() -> argparse.Namespace: ) parser.add_argument( "--salm-encoder", - choices=("f16", "none"), - help="speech-LLM: f16 (default) writes the encoder file next to the decoder " - "(-Encoder-F16.gguf); none: the decoder only (its encoder file exists)", + choices=("f16", "f32", "none"), + help="speech-LLM: the encoder file next to the decoder (-Encoder-F16.gguf): f16 (default), f32 " + "(the default for a ModelOpt checkpoint, its FP8 encoder weights exactly); none: the decoder only (its " + "encoder file exists)", ) parser.add_argument( "--salm-target", diff --git a/docs/model-conversion.md b/docs/model-conversion.md index 73297b3..37f18d6 100644 --- a/docs/model-conversion.md +++ b/docs/model-conversion.md @@ -80,6 +80,14 @@ The encoder file is the same for every `--outtype` (F16 encoder and F32 CTC head checkpoint, so decoders of several types share one. `--salm-encoder none` writes only the decoder, for a second `--outtype` of a checkpoint whose encoder file exists; `--architecture pee` converts only the speech encoder. +A checkpoint quantized with ModelOpt (it carries `hf_quant_config.json`, with NVFP4 and FP8 layers) keeps its +weights: it converts to `--outtype nvfp4` only, and the other types convert from the BF16 checkpoint. The decoder's +NVFP4 tensors keep their 4-bit values and scales, and each FP8 tensor keeps its 8-bit values (stored as BF16, which +holds them exactly) with its scale, which the runtime applies after the matrix multiply; the MTP head's FP8 tensors are +written dequantized, as BF16. The encoder file defaults to +F32 (`-Encoder-F32.gguf`), which holds the FP8 encoder weights exactly; `--salm-encoder f16` writes the +smaller F16 one. + The conversion stages the checkpoint's decoder for llama.cpp's NemotronH converter (the pinned `llama.cpp` submodule), writes a BF16 intermediate next to the output (the size of the BF16 decoder) and then quantizes it with the patched `llama-quantize`, built once on first use like the S2S converter's. `--dry-run` checks the tensor diff --git a/docs/salm/models.md b/docs/salm/models.md index dcfdd8d..d85748e 100644 --- a/docs/salm/models.md +++ b/docs/salm/models.md @@ -21,7 +21,10 @@ python3 convert_model.py checkpoints/NVIDIA-Nemotron-3.5-Transcribe-30B-A4B --ar --outtype nvfp4 --outfile models/NVIDIA-Nemotron-3.5-Transcribe-30B-A4B-NVFP4.gguf ``` -The example writes the NVFP4 decoder; for another precision, change `--outtype` and the file name. Every entrypoint +The example writes the NVFP4 decoder; for another precision, change `--outtype` and the file name. The +[NVFP4 checkpoint](https://huggingface.co/nvidia/NVIDIA-Nemotron-3.5-Transcribe-30B-A4B-NVFP4) also converts, with +`--outtype nvfp4` only: its decoder and encoder keep the checkpoint's own quantized weights +([Model conversion](../model-conversion.md#speech-llm-salm)). Every entrypoint takes the path of the decoder you converted: ```bash diff --git a/tests/conversion/converter_contract_test.py b/tests/conversion/converter_contract_test.py index 1092204..22b5614 100644 --- a/tests/conversion/converter_contract_test.py +++ b/tests/conversion/converter_contract_test.py @@ -54,10 +54,12 @@ ) from conversion.salm import DENSE_TYPE as SALM_DENSE_TYPE from conversion.salm import checkpoint_id as salm_checkpoint_id +from conversion.salm import convert as convert_salm from conversion.salm import decoder_keys as salm_decoder_keys from conversion.salm import encoder_file_name as salm_encoder_file_name from conversion.salm import encoder_type as salm_encoder_type from conversion.salm import kept_expert_layers as salm_kept_expert_layers +from conversion.salm import modelopt_quantization as salm_modelopt_quantization from conversion.salm import q2_0_uses_top_level as salm_q2_0_uses_top_level from conversion.salm import stage as stage_salm from conversion.salm import tensor_rules as salm_tensor_rules @@ -340,6 +342,9 @@ def test_salm_quantization_rules(self) -> None: self.assertEqual(salm_encoder_type("nvfp4"), "f16") self.assertEqual(salm_encoder_type("iq4_nl"), "f16") self.assertEqual(salm_encoder_type("iq4_nl", "none"), "none") + # a ModelOpt checkpoint's encoder file defaults to F32 (its FP8 linears exactly) + self.assertEqual(salm_encoder_type("nvfp4", quantized=True), "f32") + self.assertEqual(salm_encoder_type("nvfp4", "f16", quantized=True), "f16") self.assertEqual( salm_encoder_file_name("example-salm", "f16"), "example-salm-Encoder-F16.gguf", @@ -353,6 +358,87 @@ def test_salm_quantization_rules(self) -> None: ], ) + def test_salm_modelopt_checkpoint(self) -> None: + def quant_config(root, layers, producer="modelopt", kv=None): + (root / "hf_quant_config.json").write_text( + json.dumps( + { + "producer": {"name": producer}, + "quantization": { + "quant_algo": "MIXED_PRECISION", + "kv_cache_quant_algo": kv, + "quantized_layers": { + name: {"quant_algo": algo} for name, algo in layers.items() + }, + }, + } + ) + ) + + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + self.assertIsNone(salm_modelopt_quantization(root)) # BF16 checkpoint + quant_config( + root, + { + "backbone.layers.1.mixer.experts": "NVFP4", + "backbone.layers.0.mixer.in_proj": "FP8", + }, + ) + self.assertEqual( + salm_modelopt_quantization(root)["quantized_layers"][ + "backbone.layers.0.mixer.in_proj" + ], + {"quant_algo": "FP8"}, + ) + # it keeps its weights: --outtype nvfp4 only (checked before any conversion work) + with self.assertRaisesRegex(ValueError, "nvfp4 only"): + convert_salm(root, root / "out.gguf", "iq4_nl") + quant_config(root, {"backbone.layers.1.mixer.experts": "W4A8_AWQ"}) + with self.assertRaisesRegex(RuntimeError, "W4A8_AWQ"): + salm_modelopt_quantization(root) + quant_config(root, {"backbone.layers.1.mixer.experts": "NVFP4"}, kv="FP8") + with self.assertRaisesRegex(RuntimeError, "KV cache"): + salm_modelopt_quantization(root) + quant_config(root, {}, producer="other") + with self.assertRaises(RuntimeError): + salm_modelopt_quantization(root) + # the decoder names the encoder file it pairs with + self.assertEqual( + salm_decoder_keys("example-salm", "0123", "f32")[1], + "nemo_speech.speech_model=example-salm-Encoder-F32.gguf", + ) + + def test_salm_encoder_fp8_weights(self) -> None: + from conversion.pee import _load_salm_perception + + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + (root / "config.json").write_text(json.dumps({"pe_encoder_config": {"d_model": 4}})) + values = torch.tensor([[0.5, -1.25, 448.0, 0.0], [-0.0, 2.0**-9, 3.0, -6.5]]) + weight = values.to(torch.float8_e4m3fn) + prefix = "perception.encoder.asr_encoder.layers.0.attn.out_proj" + tensors = { + f"{prefix}.weight": weight, + f"{prefix}.weight_scale": torch.tensor(0.0071), + f"{prefix}.input_scale": torch.tensor(0.5), + "perception.proj.weight": torch.ones(2, 2, dtype=torch.bfloat16), + } + save_file(tensors, str(root / "perception.safetensors")) + cfg, sd = _load_salm_perception(root) + self.assertEqual(cfg, {"d_model": 4}) + self.assertEqual( + sorted(sd), ["encoder.asr_encoder.layers.0.attn.out_proj.weight", "proj.weight"] + ) + fp8 = sd["encoder.asr_encoder.layers.0.attn.out_proj.weight"] + self.assertEqual(fp8.dtype, torch.float32) + self.assertTrue(torch.equal(fp8, weight.float() * torch.tensor(0.0071))) + # an FP8 weight without its scale is refused + del tensors[f"{prefix}.weight_scale"] + save_file(tensors, str(root / "perception.safetensors")) + with self.assertRaisesRegex(RuntimeError, "weight_scale"): + _load_salm_perception(root) + def test_salm_checkpoint_id(self) -> None: import numpy as np @@ -458,9 +544,14 @@ def test_salm_decoder_staging(self) -> None: ) ) (source / "model.safetensors").write_bytes(b"weights") + (source / "hf_quant_config.json").write_text('{"producer": {"name": "modelopt"}}') staging = root / "staged" stage_salm(source, staging) self.assertEqual(json.loads((staging / "config.json").read_text()), backbone) + # llama.cpp's converter reads a ModelOpt checkpoint's quantization from the staged dir + self.assertEqual( + (staging / "hf_quant_config.json").read_text(), '{"producer": {"name": "modelopt"}}' + ) tokens = json.loads((staging / "tokenizer.json").read_text())["added_tokens"] self.assertEqual([t["content"] for t in tokens], ["<|im_end|>"]) tokenizer_config = json.loads((staging / "tokenizer_config.json").read_text()) From 9f02d3bc7844cd6ab36295096ef115b5e5a13d6a Mon Sep 17 00:00:00 2001 From: Prabhsimran Singh Date: Wed, 18 Nov 2026 19:20:09 +0530 Subject: [PATCH 02/10] feat(salm): greedy picks at the checkpoint's BF16 output precision - greedy decoding compares the logits rounded to BF16 and takes the lowest token id among equal values, as the reference implementation's BF16 logits give - patches: ggml_argmax_bf16 (CPU, CUDA); llama_serving_params.bf16_argmax for the batched path's greedy picks and MTP drafts - the upstream llama.cpp path picks greedy tokens on the host - tests: salm_policy cases; argmax_bf16 checks the op against the host pick Signed-off-by: Prabhsimran Singh --- ...ggml-argmax-over-bf16-rounded-values.patch | 136 ++++++++++++++++++ ...nded-argmax-for-batched-greedy-picks.patch | 53 +++++++ patches/series | 2 + src/speechlm/salm_engine.cpp | 50 +++---- src/speechlm/salm_policy.cpp | 19 +++ src/speechlm/salm_policy.h | 5 + tests/cpp/speechlm/CMakeLists.txt | 12 ++ tests/cpp/speechlm/test_argmax_bf16.cpp | 131 +++++++++++++++++ tests/cpp/speechlm/test_salm_policy.cpp | 29 ++++ 9 files changed, 413 insertions(+), 24 deletions(-) create mode 100644 patches/ggml-argmax-over-bf16-rounded-values.patch create mode 100644 patches/llama-bf16-rounded-argmax-for-batched-greedy-picks.patch create mode 100644 tests/cpp/speechlm/test_argmax_bf16.cpp diff --git a/patches/ggml-argmax-over-bf16-rounded-values.patch b/patches/ggml-argmax-over-bf16-rounded-values.patch new file mode 100644 index 0000000..bc285c6 --- /dev/null +++ b/patches/ggml-argmax-over-bf16-rounded-values.patch @@ -0,0 +1,136 @@ +From: Prabhsimran Singh +Subject: ggml: argmax over BF16-rounded values + +ggml_argmax_bf16 takes the argmax of each row after rounding the values to +BF16 (round to nearest even), and the lowest index among equal values: the +result of an argmax over the same values held in a BF16 tensor. A decoder +whose reference implementation computes its logits in BF16 picks the same +tokens with it as that implementation. The CPU and CUDA backends implement +it; ggml_argmax is unchanged. + +Upstream: stays here (greedy decoding of BF16 speech-LLM checkpoints). + +diff --git a/ggml/include/ggml.h b/ggml/include/ggml.h +index c13b47c54be26e5f8d04de165022121e943bbafe..2c5cabbe65678985be0d81531d0649ed550c72c2 100644 +--- a/ggml/include/ggml.h ++++ b/ggml/include/ggml.h +@@ -1085,6 +1085,11 @@ extern "C" { + struct ggml_context * ctx, + struct ggml_tensor * a); + ++ // argmax along rows of the values rounded to BF16 (round to nearest even); equal values give the lowest index ++ GGML_API struct ggml_tensor * ggml_argmax_bf16( ++ struct ggml_context * ctx, ++ struct ggml_tensor * a); ++ + // count number of equal elements in a and b + GGML_API struct ggml_tensor * ggml_count_equal( + struct ggml_context * ctx, +diff --git a/ggml/src/ggml-cpu/ops.cpp b/ggml/src/ggml-cpu/ops.cpp +index 53555e3cede08cef22792219657ba5bc00731d42..83c61c6f89bf9fbec834fef1efd31f69255f8751 100644 +--- a/ggml/src/ggml-cpu/ops.cpp ++++ b/ggml/src/ggml-cpu/ops.cpp +@@ -1586,11 +1586,24 @@ static void ggml_compute_forward_argmax_f32( + const size_t nb01 = src0->nb[1]; + const size_t nb0 = dst->nb[0]; + ++ const bool bf16 = ggml_get_op_params_i32(dst, 0) != 0; // ggml_argmax_bf16 ++ + for (int64_t i1 = 0; i1 < ne01; i1++) { + float * src = (float *) ((char *) src0->data + i1*nb01); + int32_t * dst_ = (int32_t *) ((char *) dst->data + i1*nb0); + int v = 0; +- ggml_vec_argmax_f32(ne00, &v, src); ++ if (bf16) { ++ float max = -INFINITY; ++ for (int64_t i0 = 0; i0 < ne00; i0++) { ++ const float x = GGML_BF16_TO_FP32(GGML_FP32_TO_BF16(src[i0])); ++ if (x > max) { // the first of equal values stays ++ max = x; ++ v = (int) i0; ++ } ++ } ++ } else { ++ ggml_vec_argmax_f32(ne00, &v, src); ++ } + dst_[0] = v; + } + } +diff --git a/ggml/src/ggml-cuda/argmax.cu b/ggml/src/ggml-cuda/argmax.cu +index 51967c667cfd88a8d9d81ddbf827bce402d65761..678b9fed47bad2b484c32b8930002af67b6ad834 100644 +--- a/ggml/src/ggml-cuda/argmax.cu ++++ b/ggml/src/ggml-cuda/argmax.cu +@@ -5,6 +5,14 @@ + #include "common.cuh" + #include "sum.cuh" + ++// x rounded to BF16, round to nearest even (the bits of a float that a BF16 holds exactly) ++static __device__ __forceinline__ float argmax_round_bf16(const float x) { ++ const uint32_t u = __float_as_uint(x); ++ return __uint_as_float((u + 0x7FFF + ((u >> 16) & 1)) & 0xFFFF0000u); ++} ++ ++// bf16 (ggml_argmax_bf16): the values are compared after rounding to BF16, and equal values give the lowest column ++template + static __global__ void argmax_f32(const float * __restrict__ x, int32_t * __restrict__ dst, const int64_t ncols) { + const int64_t row = blockIdx.x; + +@@ -13,7 +21,7 @@ static __global__ void argmax_f32(const float * __restrict__ x, int32_t * __rest + const float * rowx = x + row * ncols; + + for (int32_t col = threadIdx.x; col < ncols; col += blockDim.x) { +- const float val = rowx[col]; ++ const float val = bf16 ? argmax_round_bf16(rowx[col]) : rowx[col]; + if (val > maxval) { + maxval = val; + argmax = col; +@@ -24,7 +32,7 @@ static __global__ void argmax_f32(const float * __restrict__ x, int32_t * __rest + for (int offset = WARP_SIZE/2; offset > 0; offset >>= 1) { + const float val = __shfl_xor_sync(0xFFFFFFFF, maxval, offset, WARP_SIZE); + const int col = __shfl_xor_sync(0xFFFFFFFF, argmax, offset, WARP_SIZE); +- if (val > maxval) { ++ if (val > maxval || (bf16 && val == maxval && col < argmax)) { + maxval = val; + argmax = col; + } +@@ -53,7 +61,7 @@ static __global__ void argmax_f32(const float * __restrict__ x, int32_t * __rest + for (int offset = WARP_SIZE/2; offset > 0; offset >>= 1) { + const float val = __shfl_xor_sync(0xFFFFFFFF, maxval, offset, WARP_SIZE); + const int col = __shfl_xor_sync(0xFFFFFFFF, argmax, offset, WARP_SIZE); +- if (val > maxval) { ++ if (val > maxval || (bf16 && val == maxval && col < argmax)) { + maxval = val; + argmax = col; + } +@@ -87,5 +95,9 @@ void ggml_cuda_argmax(ggml_backend_cuda_context & ctx, ggml_tensor * dst) { + const dim3 blocks_dim(num_threads, 1, 1); + const dim3 blocks_num(num_blocks, 1, 1); + +- argmax_f32<<>>(src0_d, dst_d, ne00); ++ if (ggml_get_op_params_i32(dst, 0) != 0) { ++ argmax_f32<<>>(src0_d, dst_d, ne00); ++ } else { ++ argmax_f32<<>>(src0_d, dst_d, ne00); ++ } + } +diff --git a/ggml/src/ggml.c b/ggml/src/ggml.c +index a2c11d254728236205cec60d2092d9849e43a7fc..d08015cfbbad955d712e8476dff4c711d89ad0ac 100644 +--- a/ggml/src/ggml.c ++++ b/ggml/src/ggml.c +@@ -2561,6 +2561,16 @@ struct ggml_tensor * ggml_argmax( + return result; + } + ++struct ggml_tensor * ggml_argmax_bf16( ++ struct ggml_context * ctx, ++ struct ggml_tensor * a) { ++ struct ggml_tensor * result = ggml_argmax(ctx, a); ++ ++ ggml_set_op_params_i32(result, 0, 1); // the backends read it: values rounded to BF16, lowest index among equals ++ ++ return result; ++} ++ + // ggml_count_equal + + struct ggml_tensor * ggml_count_equal( diff --git a/patches/llama-bf16-rounded-argmax-for-batched-greedy-picks.patch b/patches/llama-bf16-rounded-argmax-for-batched-greedy-picks.patch new file mode 100644 index 0000000..c8de87d --- /dev/null +++ b/patches/llama-bf16-rounded-argmax-for-batched-greedy-picks.patch @@ -0,0 +1,53 @@ +From: Prabhsimran Singh +Subject: llama: BF16-rounded argmax for batched greedy picks + +llama_serving_params.bf16_argmax makes the batched greedy argmax and the +chained MTP drafts use ggml_argmax_bf16: the logits are compared after +rounding to BF16, and the lowest token id wins among equal values. +NeMo-Speech.cpp's speech-LLM engine sets it, so that greedy decoding picks +the tokens of the checkpoint's reference implementation, which computes its +logits in BF16. Off (the default) keeps ggml_argmax. + +Upstream: not planned (batched serving path). + +diff --git a/include/llama.h b/include/llama.h +index 8dd80e0187a02fff196b1c6826031d195024ee5a..90012121a36894266dba5bc38958c35422f34e43 100644 +--- a/include/llama.h ++++ b/include/llama.h +@@ -375,6 +375,10 @@ extern "C" { + uint32_t kv_reserve_cells; + // struct ggml_backend_cuda_serving (ggml-cuda.h) applied to the context's CUDA backends, or NULL. + const void * cuda_serving; ++ // Greedy sequences and chained MTP drafts take the argmax of the logits rounded to BF16, the lowest token id ++ // among equal values (ggml_argmax_bf16): the tokens a reference implementation with BF16 logits picks. Needs ++ // batched. ++ bool bf16_argmax; + }; + + // NOTE: changing the default values of parameters marked as [EXPERIMENTAL] may cause crashes or incorrect results in certain configurations +diff --git a/src/llama-graph.cpp b/src/llama-graph.cpp +index 885879cfce6b79530c3d7bef33b09c1e201e3b25..45c95a19484fc254ac64a5e3a5c2d5b171e48168 100644 +--- a/src/llama-graph.cpp ++++ b/src/llama-graph.cpp +@@ -4123,7 +4123,7 @@ void llm_graph_context::build_sampling() const { + if (name[0] == '+') ++name; + return std::strcmp(name, "greedy") == 0; + }; +- auto * ids = ggml_argmax(ctx0, logits); ++ auto * ids = cparams.serving.bf16_argmax ? ggml_argmax_bf16(ctx0, logits) : ggml_argmax(ctx0, logits); + ggml_set_name(ids, "batched_greedy_argmax"); + ggml_set_output(ids); + ggml_build_forward_expand(gf, ids); +diff --git a/src/models/nemotron-h-moe.cpp b/src/models/nemotron-h-moe.cpp +index f3b9656df3c53003329dde25470df708d95ef199..da3b9fd2331e8885a703b9e1f9a8cdad61b66f12 100644 +--- a/src/models/nemotron-h-moe.cpp ++++ b/src/models/nemotron-h-moe.cpp +@@ -206,7 +206,7 @@ llama_model_nemotron_h_moe::graph_mtp::graph_mtp(const llama_model & model, cons + if (cparams.mtp_tok && cparams.mtp_tok_out >= 0) { + // chained drafting: argmax ids and the head's hidden rows stay on the device for the next draft; nothing is + // extracted to the host +- ggml_tensor * am = ggml_argmax(ctx0, cur); ++ ggml_tensor * am = cparams.serving.bf16_argmax ? ggml_argmax_bf16(ctx0, cur) : ggml_argmax(ctx0, cur); + ggml_build_forward_expand(gf, ggml_cpy(ctx0, am, + ggml_view_1d(ctx0, cparams.mtp_tok, am->ne[0], cparams.mtp_tok_out*ggml_element_size(cparams.mtp_tok)))); + if (cparams.mtp_h_out) { diff --git a/patches/series b/patches/series index a9e994e..3309813 100644 --- a/patches/series +++ b/patches/series @@ -41,3 +41,5 @@ llama-dflash2-drafting-in-the-batched-serving-path.patch llama-mtp-verify-steps-flagged-by-the-caller.patch ggml-fit-q2_0-block-scales-to-the-weights-and-the-importance-matrix.patch ggml-cuda-re-instantiate-cuda-graphs-that-sat-idle-on-integrated-gpus.patch +ggml-argmax-over-bf16-rounded-values.patch +llama-bf16-rounded-argmax-for-batched-greedy-picks.patch diff --git a/src/speechlm/salm_engine.cpp b/src/speechlm/salm_engine.cpp index 4d4d389..d8d8f66 100644 --- a/src/speechlm/salm_engine.cpp +++ b/src/speechlm/salm_engine.cpp @@ -147,17 +147,6 @@ piece(const llama_vocab* vocab, llama_token t) { return s; } -int -argmax(const float* logits, int n) { - int best = 0; - float bv = logits[0]; - for (int i = 1; i < n; i++) - if (logits[i] > bv) { - bv = logits[i]; - best = i; - } - return best; -} // Scheduling constants of the batched path. // Distinct prompt prefixes kept computed in extra sequences; admitted requests copy their prefix. @@ -263,9 +252,10 @@ struct SalmEngine::Impl { int emb_dev_turn = 0; std::vector dft_pos; // tok_batch positions shifted per slot for the MTP draft context - std::vector - seq_samplers; // chain attached to each slot: greedy (GPU argmax) or temperature sampling - std::vector seq_greedy; // seq_samplers[i] is a greedy chain + // chain attached to each slot: greedy (GPU argmax) or temperature sampling; null for a greedy + // slot of the upstream path (the host picks) + std::vector seq_samplers; + std::vector seq_greedy; // slot i decodes greedily std::vector seq_sampler_cfg; // Word-timestamp evidence of one request: the CTC head's output for its frames (on the @@ -529,6 +519,7 @@ struct SalmEngine::Impl { if (fast) { cuda_decoder.fused = true; cp.serving.batched = true; + cp.serving.bf16_argmax = true; // the device argmax follows policy::greedy_pick // rejected drafts roll back natively (pinned cells + ReplaySSM), no state snapshots cp.serving.mtp_replay = cfg.mtp_draft > 0 ? cfg.mtp_draft + 1 : 0; // the KV length is padded to multiples of 4096 cells so decode graphs are reused; the @@ -542,13 +533,16 @@ struct SalmEngine::Impl { // Reserve every verification output for backend sampling, including MTP. cp.n_outputs_max_per_seq = std::max(1, cfg.mtp_draft + 1); cp.n_outputs_max = cp.n_seq_max * cp.n_outputs_max_per_seq; - // Sample on the backend through per-slot sampler chains (greedy: GPU argmax) instead of - // copying every sequence's logits to the host each step. + // The batched path samples on the backend through per-slot sampler chains (greedy: GPU + // argmax) instead of copying every sequence's logits to the host each step. On the + // upstream path a greedy sequence has no chain: the host picks its tokens from the logits + // (policy::greedy_pick), and only temperature sampling runs on the backend. for (int i = 0; i < cfg.max_sequences; i++) { - llama_sampler* chain = sampler_chain(0, std::nullopt); + llama_sampler* chain = fast ? sampler_chain(0, std::nullopt) : nullptr; seq_samplers.push_back(chain); seq_greedy.push_back(1); - seq_sampler_cfg.push_back({i, chain}); + if (chain) + seq_sampler_cfg.push_back({i, chain}); } cp.samplers = seq_sampler_cfg.data(); cp.n_samplers = seq_sampler_cfg.size(); @@ -1502,7 +1496,8 @@ struct SalmEngine::Impl { } // Attach `chain` to sequence `seq`, owning it, and free the chain it replaces (an attached - // chain cannot be attached again, so every change builds a new one). + // chain cannot be attached again, so every change builds a new one). A null chain detaches: + // the sequence's logits go to the host. void attach_sampler(int seq, llama_sampler* chain, bool greedy) { if (!llama_set_sampler(ctx, seq, chain)) { llama_sampler_free(chain); @@ -1519,7 +1514,8 @@ struct SalmEngine::Impl { const bool greedy = s->temperature < policy::kGreedyTemperature; if (greedy && seq_greedy[s->seq_id]) return; - attach_sampler(s->seq_id, sampler_chain(s->temperature, s->seed), greedy); + attach_sampler( + s->seq_id, greedy && !fast ? nullptr : sampler_chain(s->temperature, s->seed), greedy); } // Greedy-pick the next token for each slot whose logits were requested. @@ -1530,8 +1526,9 @@ struct SalmEngine::Impl { int32_t batch_idx; }; // Tokens of several batch rows: pick_rows() reads the backend-sampled ids of `pick_idx` after - // one wait for the step; picked_at(i) is the token of pick_idx[i]. Upstream llama.cpp may leave - // a row unsampled (a sampler chain it could not offload): its logits are decoded on the host. + // one wait for the step; picked_at(i) is the token of pick_idx[i]. A row the backend did not + // sample (a greedy sequence of the upstream path, or a sampler chain upstream llama.cpp could + // not offload) is picked on the host from its logits. std::vector pick_idx; std::vector picked; void pick_rows() { @@ -1553,7 +1550,7 @@ struct SalmEngine::Impl { if (!logits) throw std::runtime_error( "missing logits for batch entry " + std::to_string(pick_idx[i])); - picked[i] = argmax(logits, n_vocab); + picked[i] = policy::greedy_pick(logits, n_vocab); } return picked[i]; } @@ -1564,7 +1561,12 @@ struct SalmEngine::Impl { pick_idx.resize(n); for (size_t i = 0; i < n; ++i) pick_idx[i] = flagged[i].batch_idx; pick_rows(); - for (size_t i = 0; i < n; ++i) flagged[i].slot->last = picked_at(i); + for (size_t i = 0; i < n; ++i) { + // a greedy sequence of the upstream path has no chain: the row holds no id of this step + if (!fast && seq_greedy[flagged[i].slot->seq_id]) + picked[i] = LLAMA_TOKEN_NULL; + flagged[i].slot->last = picked_at(i); + } } // Commit the sampled token(s) of each slot in `sampled`: append text, detect end diff --git a/src/speechlm/salm_policy.cpp b/src/speechlm/salm_policy.cpp index 1180f7a..d264d5e 100644 --- a/src/speechlm/salm_policy.cpp +++ b/src/speechlm/salm_policy.cpp @@ -6,6 +6,7 @@ #include #include #include +#include namespace nemo_speech::speechlm::policy { @@ -352,6 +353,24 @@ duration_limit_error(double seconds, double limit) { return std::string(buffer); } +int +greedy_pick(const float* logits, int n) { + int best = 0; + float top = -INFINITY; + for (int i = 0; i < n; i++) { + uint32_t bits; + std::memcpy(&bits, &logits[i], sizeof(bits)); + bits = (bits + 0x7FFF + ((bits >> 16) & 1)) & 0xFFFF0000u; // to BF16, nearest even + float value; + std::memcpy(&value, &bits, sizeof(value)); + if (value > top) { // the first of equal values stays + top = value; + best = i; + } + } + return best; +} + bool near_silent(const float* samples, size_t n) { double sum = 0.0; diff --git a/src/speechlm/salm_policy.h b/src/speechlm/salm_policy.h index 207fda7..c0bffe0 100644 --- a/src/speechlm/salm_policy.h +++ b/src/speechlm/salm_policy.h @@ -39,6 +39,11 @@ inline constexpr int kMaxOutputTokens = 21664; // largest output budget inline constexpr double kMaxDurationSeconds = 3600; // longest accepted audio inline constexpr double kGreedyTemperature = 1e-5; // temperatures below this decode greedily +// The token greedy decoding picks: the largest logit after rounding the logits to BF16 (round to +// nearest even), and the lowest token id among equal values. The checkpoint's reference +// implementation computes its logits in BF16, so this is the token its argmax gives. +int greedy_pick(const float* logits, int n); + // An invalid request (HTTP 400). `param` names the offending public field (chat route), or is // empty. class PolicyError : public std::invalid_argument { diff --git a/tests/cpp/speechlm/CMakeLists.txt b/tests/cpp/speechlm/CMakeLists.txt index 4cb94d3..a3d2f4f 100644 --- a/tests/cpp/speechlm/CMakeLists.txt +++ b/tests/cpp/speechlm/CMakeLists.txt @@ -16,3 +16,15 @@ add_test(NAME salm_guards COMMAND test_salm_guards) add_executable(test_salm_policy test_salm_policy.cpp) target_link_libraries(test_salm_policy PRIVATE nemo_speech_speechlm llama) add_test(NAME salm_policy COMMAND test_salm_policy) +# ggml_argmax_bf16 (the ggml patch: the batched path's greedy pick on the device) against policy::greedy_pick (the host's), +# on the CPU backend and, with one, the GPU backend. +if(NEMO_SPEECH_GGML_PATCHED) + add_executable(test_argmax_bf16 test_argmax_bf16.cpp) + target_link_libraries(test_argmax_bf16 PRIVATE nemo_speech_speechlm ggml) + if(GGML_CUDA) + # Links ggml directly: the stub resolves libggml-cuda's libcuda.so.1 NEEDED entry. + target_link_libraries(test_argmax_bf16 PRIVATE CUDA::cuda_driver) + endif() + add_test(NAME argmax_bf16 COMMAND test_argmax_bf16) + set_tests_properties(argmax_bf16 PROPERTIES TIMEOUT 120) +endif() diff --git a/tests/cpp/speechlm/test_argmax_bf16.cpp b/tests/cpp/speechlm/test_argmax_bf16.cpp new file mode 100644 index 0000000..c59840f --- /dev/null +++ b/tests/cpp/speechlm/test_argmax_bf16.cpp @@ -0,0 +1,131 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +// +// ggml_argmax_bf16 (the ggml patch) against policy::greedy_pick: the batched path picks greedy +// tokens with the op on the device, the upstream path with greedy_pick on the host, and both must +// give the same token. Rows of vocabulary width and narrower, with equal values after the BF16 +// rounding placed so that a plain argmax, or an argmax that does not take the lowest index, gives +// another column. Runs on the CPU backend and, when there is one, the GPU backend. +#include +#include +#include +#include + +#include "ggml-alloc.h" +#include "ggml-backend.h" +#include "ggml-cpu.h" +#include "ggml.h" +#include "salm_policy.h" + +namespace { + +using nemo_speech::speechlm::policy::greedy_pick; + +// rows x cols logits in [100, 230) (BF16 steps of 0.5 and 1), then per row a group of columns +// that round to the same largest value +std::vector +make_rows(int64_t cols, int64_t rows) { + std::vector x((size_t)(cols * rows)); + uint32_t state = 12345u + (uint32_t)cols; + for (float& v : x) { + state = state * 1664525u + 1013904223u; + v = 100.0f + 130.0f * (float)(state >> 8) / 16777216.0f; + } + const float inf = std::numeric_limits::infinity(); + for (int64_t r = 0; r < rows; ++r) { + float* row = x.data() + r * cols; + const int64_t lo = (7 + 13 * r) % cols, mid = cols / 2 + r, hi = cols - 1 - r; + switch (r % 4) { + case 0: // the largest logit is the highest column; all three round to 250 + row[lo] = 249.6f; + row[mid] = 250.2f; + row[hi] = 250.4f; + break; + case 1: // ties to even: 250.5 rounds to 250 and loses to 251 further on + row[lo] = 250.5f; + row[hi] = 250.6f; + break; + case 2: // masked columns, and equal values in neighbouring columns + row[0] = -inf; + row[mid] = 240.3f; + row[mid + 1] = 240.4f; + row[hi] = -inf; + break; + default: // no tie at the top + row[mid] = 245.0f; + break; + } + } + return x; +} + +std::vector +run(ggml_backend_t backend, const std::vector& x, int64_t cols, int64_t rows, bool bf16) { + ggml_init_params params{ggml_tensor_overhead() * 4 + ggml_graph_overhead(), nullptr, true}; + ggml_context* ctx = ggml_init(params); + ggml_tensor* in = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, cols, rows); + ggml_tensor* ids = bf16 ? ggml_argmax_bf16(ctx, in) : ggml_argmax(ctx, in); + ggml_cgraph* gf = ggml_new_graph(ctx); + ggml_build_forward_expand(gf, ids); + ggml_gallocr_t allocr = ggml_gallocr_new(ggml_backend_get_default_buffer_type(backend)); + ggml_gallocr_alloc_graph(allocr, gf); + ggml_backend_tensor_set(in, x.data(), 0, x.size() * sizeof(float)); + ggml_backend_graph_compute(backend, gf); + std::vector out((size_t)rows); + ggml_backend_tensor_get(ids, out.data(), 0, out.size() * sizeof(int32_t)); + ggml_gallocr_free(allocr); + ggml_free(ctx); + return out; +} + +} // namespace + +int +main() { + ggml_backend_t backends[2] = { + ggml_backend_cpu_init(), ggml_backend_init_by_type(GGML_BACKEND_DEVICE_TYPE_GPU, nullptr)}; + const char* names[2] = {"CPU", "GPU"}; + if (!backends[1]) + std::fprintf(stderr, "no GPU backend available; CPU only\n"); + + int failures = 0; + const int64_t widths[] = {131072, 4097, 1000, 70, 3}; // the vocabulary, and under one block + for (int64_t cols : widths) { + const int64_t rows = cols >= 70 ? 9 : 2; + const std::vector x = make_rows(cols, rows); + std::vector want((size_t)rows); + for (int64_t r = 0; r < rows; ++r) + want[(size_t)r] = greedy_pick(x.data() + r * cols, (int)cols); + for (int b = 0; b < 2; ++b) { + if (!backends[b]) + continue; + const std::vector got = run(backends[b], x, cols, rows, true); + for (int64_t r = 0; r < rows; ++r) { + if (got[(size_t)r] != want[(size_t)r]) { + std::fprintf( + stderr, + "FAIL: %s, %lld columns, row %lld: ggml_argmax_bf16 %d, greedy_pick %d\n", + names[b], (long long)cols, (long long)r, got[(size_t)r], want[(size_t)r]); + ++failures; + } + } + } + if (cols >= 70) { // row 0 does tell the two rules apart + const std::vector plain = run(backends[0], x, cols, rows, false); + if (plain[0] == want[0]) { + std::fprintf( + stderr, "FAIL: %lld columns: row 0 does not need the rounding\n", + (long long)cols); + ++failures; + } + } + } + + for (ggml_backend_t backend : backends) + if (backend) + ggml_backend_free(backend); + if (failures) + return 1; + std::fprintf(stderr, "OK: ggml_argmax_bf16 picks the greedy_pick column on every backend\n"); + return 0; +} diff --git a/tests/cpp/speechlm/test_salm_policy.cpp b/tests/cpp/speechlm/test_salm_policy.cpp index d65d12b..2e8dd38 100644 --- a/tests/cpp/speechlm/test_salm_policy.cpp +++ b/tests/cpp/speechlm/test_salm_policy.cpp @@ -230,6 +230,35 @@ test_budget() { expect(near_silent(sparse.data(), sparse.size()), "near_silent(one 32-LSB sample)"); expect(!near_silent(loud.data(), loud.size()), "near_silent(one 33-LSB sample)"); } + // greedy pick: logits compared after rounding to BF16 (steps of 1 between 128 and 256, ties to + // even), the lowest token id among equal values + { + const float inf = std::numeric_limits::infinity(); + struct Case { + std::vector logits; + int want; + }; + const Case cases[] = { + {{199.6f, 200.4f}, 0}, // both 200: the lower id, not the larger logit + {{200.4f, 200.6f}, 1}, // 200 and 201 + {{200.4f, 3.0f, 199.6f}, 0}, // equal values apart + {{201.0f, 200.5f}, 0}, // 200.5 is a tie between 200 and 201: to even, 200 + {{201.4f, 201.5f}, 1}, // 201.5 to even: 202 + {{202.0f, 201.5f, 202.4f}, 0}, // all 202 + {{-200.4f, -199.6f}, 0}, // both -200 + {{1.0f, 1.001f}, 0}, // steps of 1/128 near 1: both 1.0 + {{1.0f, 1.004f}, 1}, // 1.004 rounds to 1 + 1/128 + {{-inf, 3.0f, -inf, 3.0f}, 1}, // masked tokens + {{-inf, -inf}, 0}, + }; + for (const Case& c : cases) { + const int got = greedy_pick(c.logits.data(), static_cast(c.logits.size())); + expect( + got == c.want, "greedy_pick case of " + std::to_string(c.logits.size()) + + " logits starting " + std::to_string(c.logits[0]) + ": got " + + std::to_string(got) + ", want " + std::to_string(c.want)); + } + } } void From 0e1e8d6de85d0db434efa50964f184ec0cd6c0d5 Mon Sep 17 00:00:00 2001 From: Prabhsimran Singh Date: Wed, 18 Nov 2026 20:56:37 +0530 Subject: [PATCH 03/10] feat(model-store): speech-LLM decoders, encoder files and draft models - Index entries may share a repository: its ID selects the first entry, and aliases select each one - asr_encoder artifacts download with their decoder, into the same directory, so the decoders of one repository share one encoder file - draft role: asr.salm.dflash_path takes an indexed name in transcribe, bench and serve - model list shows decoders as decoder + encoder and lists draft models - cli_model_store covers shared entries, the encoder file and the draft model Signed-off-by: Prabhsimran Singh --- app/bench_asr.cpp | 4 ++ app/model_store.cpp | 70 ++++++++++++++++--------- app/serve.cpp | 5 ++ app/transcribe.cpp | 4 ++ tests/cli/model_store_test.py | 99 +++++++++++++++++++++++++++++++++++ 5 files changed, 157 insertions(+), 25 deletions(-) diff --git a/app/bench_asr.cpp b/app/bench_asr.cpp index cdbf550..15b010f 100644 --- a/app/bench_asr.cpp +++ b/app/bench_asr.cpp @@ -103,6 +103,10 @@ class AsrWorkload : public Workload { const std::string reference = model_.empty() ? config_.model.path : model_; if (config_.salm.encoder_path.empty() || !reference.empty()) config_.model.path = resolve_model_file(reference, "asr", "ASR model").string(); + if (!config_.salm.dflash_path.empty()) + config_.salm.dflash_path = + resolve_model_file(config_.salm.dflash_path, "draft", "DFlash2 draft model") + .string(); config_.batching.enabled = max_concurrency > 1; config_.batching.max_batch_size = std::max(config_.batching.max_batch_size, max_concurrency); diff --git a/app/model_store.cpp b/app/model_store.cpp index 744ba8f..7a2ce5b 100644 --- a/app/model_store.cpp +++ b/app/model_store.cpp @@ -306,6 +306,17 @@ looks_like_repo(const std::string& reference) { } } +const Model& +find_model(const Index& index, const std::string& repo) { + for (const auto& model : index.models) { + if (model.repo == repo || + std::find(model.aliases.begin(), model.aliases.end(), repo) != model.aliases.end()) + return model; + } + throw MissingModelError( + "unknown model repository: " + repo + " (run 'nemo-speech model list')"); +} + Index load_index() { Value root = Value::parse(read_text_file(index_path())); @@ -349,8 +360,10 @@ load_index() { artifact.range_end = artifact_value.find("range_end") ? integer(artifact_value, "range_end") : 0; artifact.stop_before = artifact_value.string_or("stop_before"); + // asr_encoder: a speech-LLM decoder's encoder file, downloaded next to it; draft: a + // speech-LLM draft model (asr.salm.dflash_path). static const std::set allowed_roles = { - "asr", "diarization", "tts", "codec", "tokenizer"}; + "asr", "asr_encoder", "draft", "diarization", "tts", "codec", "tokenizer"}; if (allowed_roles.find(artifact.role) == allowed_roles.end()) throw std::runtime_error("unsupported artifact role in model index"); if (!artifact.revision.empty()) @@ -432,9 +445,13 @@ load_index() { throw std::runtime_error("model has no artifacts in model index: " + model.repo); index.models.push_back(std::move(model)); } + // Entries may share a repository (the decoders of one GGUF repository): its ID selects the + // first entry, and each later one is selected by aliases of its own. std::set identifiers; + std::set repos; for (const auto& model : index.models) { - if (!identifiers.insert(model.repo).second) + if (repos.insert(model.repo).second ? !identifiers.insert(model.repo).second + : model.aliases.empty()) throw std::runtime_error("duplicate repository in model index: " + model.repo); for (const auto& alias : model.aliases) if (!identifiers.insert(alias).second) @@ -444,12 +461,7 @@ load_index() { if (identifiers.find(item.second) == identifiers.end()) throw std::runtime_error( "model index default references an unknown model: " + item.second); - const Model* model = nullptr; - for (const auto& candidate : index.models) - if (candidate.repo == item.second || - std::find(candidate.aliases.begin(), candidate.aliases.end(), item.second) != - candidate.aliases.end()) - model = &candidate; + const Model* model = &find_model(index, item.second); const bool provides_role = std::any_of( model->artifacts.begin(), model->artifacts.end(), [&](const Artifact& artifact) { return artifact.role == item.first; }); @@ -464,17 +476,6 @@ load_index() { return index; } -const Model& -find_model(const Index& index, const std::string& repo) { - for (const auto& model : index.models) { - if (model.repo == repo || - std::find(model.aliases.begin(), model.aliases.end(), repo) != model.aliases.end()) - return model; - } - throw MissingModelError( - "unknown model repository: " + repo + " (run 'nemo-speech model list')"); -} - const Artifact& find_artifact(const Model& model, const std::string& role, bool directory) { for (const auto& artifact : model.artifacts) { @@ -498,6 +499,10 @@ commands_for(const Model& model) { add("transcribe"); add("bench"); add("serve"); + } else if (artifact.role == "draft") { + add("transcribe --asr.salm.dflash_path"); + add("bench --asr.salm.dflash_path"); + add("serve --asr.salm.dflash_path"); } else if (artifact.role == "diarization") { add("diarize"); add("transcribe --diarize"); @@ -1306,9 +1311,9 @@ resolve( } const Model* model = nullptr; for (const auto& candidate : index.models) - if (candidate.repo == repo || - std::find(candidate.aliases.begin(), candidate.aliases.end(), repo) != - candidate.aliases.end()) + if (!model && (candidate.repo == repo || + std::find(candidate.aliases.begin(), candidate.aliases.end(), repo) != + candidate.aliases.end())) model = &candidate; if (!model) { if (reference.empty() || looks_like_repo(reference)) @@ -1319,7 +1324,13 @@ resolve( description + (directory ? " directory does not exist: " : " file does not exist: ") + reference); } - return materialize(*model, find_artifact(*model, role, directory)).path; + const Artifact& artifact = find_artifact(*model, role, directory); + // A speech-LLM decoder loads the encoder file it names from its own directory. + if (role == "asr") + for (const auto& encoder : model->artifacts) + if (encoder.role == "asr_encoder") + materialize(*model, encoder); + return materialize(*model, artifact).path; } } // namespace @@ -1340,10 +1351,10 @@ std::vector pull_indexed_model(const std::string& repo) { const Index index = load_index(); std::vector result; - std::set visited; + std::set visited; std::function pull = [&](const std::string& current_repo) { const Model& model = find_model(index, current_repo); - if (!visited.insert(model.repo).second) + if (!visited.insert(&model).second) return; for (const auto& artifact : model.artifacts) result.push_back(materialize(model, artifact)); for (const auto& companion : model.companions) pull(companion); @@ -1432,7 +1443,16 @@ indexed_models_text() { << "ASR — transcribe, bench, serve\n"; for (const auto& model : index.models) if (has_role(model, "asr")) + print_model(model, has_role(model, "asr_encoder") ? "decoder + encoder" : ""); + + bool drafts = false; + for (const auto& model : index.models) + if (has_role(model, "draft")) { + if (!drafts) + output << "\nSpeech-LLM draft models — --asr.salm.dflash_path\n"; + drafts = true; print_model(model, ""); + } output << "\nDiarization — diarize, transcribe --diarize, serve\n"; for (const auto& model : index.models) diff --git a/app/serve.cpp b/app/serve.cpp index ecdc3d1..5b0edb3 100644 --- a/app/serve.cpp +++ b/app/serve.cpp @@ -445,6 +445,11 @@ run_server(int argc, char** argv) { nemo_speech::asr::resolve_salm_encoder(asr_config); return asr_config.salm.encoder_path; }).empty(); + if (start_asr && !asr_config.salm.dflash_path.empty()) + asr_config.salm.dflash_path = resolve("DFlash2 draft model", [&] { + return optional_model( + asr_config.salm.dflash_path, "draft", "DFlash2 draft model", true); + }); if (asr_enabled != 0 && (asr_requested || !asr_path.empty())) { asr_config.vad.model_path = resolve("VAD model", [&] { return optional_model( diff --git a/app/transcribe.cpp b/app/transcribe.cpp index eef82c5..a185ad6 100644 --- a/app/transcribe.cpp +++ b/app/transcribe.cpp @@ -745,6 +745,10 @@ command_transcribe(int argc, char** argv) { // speaker branch. asr::resolve_salm_encoder(config); const bool speech_llm = !config.salm.encoder_path.empty(); + if (!config.salm.dflash_path.empty()) + config.salm.dflash_path = + resolve_model_file(config.salm.dflash_path, "draft", "DFlash2 draft model") + .string(); if (!options.instruction.empty() && !speech_llm) throw std::invalid_argument("--instruction needs a speech-LLM (SALM) model"); // --translate-to: a speech-LLM translates the speech itself unless an NMT model is named. diff --git a/tests/cli/model_store_test.py b/tests/cli/model_store_test.py index cd66fac..4fda099 100644 --- a/tests/cli/model_store_test.py +++ b/tests/cli/model_store_test.py @@ -19,6 +19,11 @@ PAYLOAD = b"NeMo-Speech.cpp model-store fixture\n" CODEC_PAYLOAD = b"NeMo-Speech.cpp codec fixture\n" TTS_PAYLOAD = b"NeMo-Speech.cpp TTS fixture\n" +SALM_PAYLOAD = b"NeMo-Speech.cpp speech-LLM decoder fixture\n" +SALM_SMALL_PAYLOAD = b"NeMo-Speech.cpp smaller speech-LLM decoder fixture\n" +SALM_ENCODER_PAYLOAD = b"NeMo-Speech.cpp speech-LLM encoder fixture\n" +SALM_DRAFT_PAYLOAD = b"NeMo-Speech.cpp speech-LLM draft fixture\n" +SALM_REVISION = "6" * 40 TOKENIZER_PAYLOAD = b"tokenizer configuration\n" UPDATED_TOKENIZER_PAYLOAD = b"updated tokenizer configuration\n" TTS_REVISION = "1" * 40 @@ -134,6 +139,17 @@ def file_artifact(role: str, filename: str, payload: bytes, sha256: str | None = } +def salm_entry(alias: str, *artifacts: dict) -> dict: + return { + "repo": "acme/tiny-salm", + "aliases": [alias], + "revision": SALM_REVISION, + "license": "Test only", + "license_url": "https://example.invalid/license", + "artifacts": list(artifacts), + } + + def write_index( path: pathlib.Path, asr_sha256: str, @@ -196,6 +212,26 @@ def write_index( "license_url": "https://example.invalid/license", "artifacts": [file_artifact("codec", "tiny-codec.gguf", CODEC_PAYLOAD)], }, + # Three entries of one repository: two decoders that share an encoder file, + # and a draft model. + salm_entry( + "tiny-salm", + file_artifact("asr", "tiny-salm.gguf", SALM_PAYLOAD), + file_artifact( + "asr_encoder", "tiny-salm-encoder.gguf", SALM_ENCODER_PAYLOAD + ), + ), + salm_entry( + "tiny-salm-small", + file_artifact("asr", "tiny-salm-small.gguf", SALM_SMALL_PAYLOAD), + file_artifact( + "asr_encoder", "tiny-salm-encoder.gguf", SALM_ENCODER_PAYLOAD + ), + ), + salm_entry( + "tiny-salm-draft", + file_artifact("draft", "tiny-salm-draft.gguf", SALM_DRAFT_PAYLOAD), + ), ], } ), @@ -228,6 +264,10 @@ def main() -> None: "tiny-tts.gguf": TTS_PAYLOAD, "tiny-tts.nemo": tokenizer_tar, "tiny-codec.gguf": CODEC_PAYLOAD, + "tiny-salm.gguf": SALM_PAYLOAD, + "tiny-salm-small.gguf": SALM_SMALL_PAYLOAD, + "tiny-salm-encoder.gguf": SALM_ENCODER_PAYLOAD, + "tiny-salm-draft.gguf": SALM_DRAFT_PAYLOAD, } server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), ArtifactHandler) thread = threading.Thread(target=server.serve_forever, daemon=True) @@ -248,6 +288,9 @@ def main() -> None: assert "TTS — synthesize, serve" in plain_listing.stdout assert "* tiny-asr" in plain_listing.stdout assert "repo: acme/tiny-asr" in plain_listing.stdout + assert "tiny-salm (decoder + encoder)" in plain_listing.stdout + assert "tiny-salm-small (decoder + encoder)" in plain_listing.stdout + assert "Speech-LLM draft models — --asr.salm.dflash_path" in plain_listing.stdout listed = run(binary, environment, "--json", "model", "list") assert listed.returncode == 0, listed.stderr @@ -258,6 +301,13 @@ def main() -> None: assert listing["models"][0]["default_for"] == ["asr"] assert listing["models"][1]["commands"] == ["synthesize", "serve"] assert listing["models"][1]["default_for"] == ["tokenizer", "tts"] + assert listing["models"][3]["roles"] == ["asr", "asr_encoder"] + assert listing["models"][3]["commands"] == ["transcribe", "bench", "serve"] + assert listing["models"][5]["commands"] == [ + "transcribe --asr.salm.dflash_path", + "bench --asr.salm.dflash_path", + "serve --asr.salm.dflash_path", + ] pulled = run(binary, environment, "--json", "pull", "tiny-asr") assert pulled.returncode == 0, pulled.stderr @@ -329,6 +379,55 @@ def main() -> None: assert ArtifactHandler.request_counts["tiny-tts.nemo"] == 2 assert ArtifactHandler.request_counts["tiny-codec.gguf"] == 1 + def salm_pull(name: str) -> list[tuple[str, str, bool]]: + result = run(binary, environment, "--json", "pull", name) + assert result.returncode == 0, result.stderr + return [ + (item["role"], pathlib.Path(item["path"]).name, item["cached"]) + for item in json.loads(result.stdout)["artifacts"] + ] + + # Each alias selects its own decoder; the encoder file they share downloads once, into + # the repository's directory, and the repository ID selects the first entry. + assert salm_pull("tiny-salm-small") == [ + ("asr", "tiny-salm-small.gguf", False), + ("asr_encoder", "tiny-salm-encoder.gguf", False), + ] + assert salm_pull("acme/tiny-salm") == [ + ("asr", "tiny-salm.gguf", False), + ("asr_encoder", "tiny-salm-encoder.gguf", True), + ] + assert salm_pull("tiny-salm-draft") == [("draft", "tiny-salm-draft.gguf", False)] + assert ArtifactHandler.request_counts["tiny-salm-encoder.gguf"] == 1 + salm_directory = cache / "acme" / "tiny-salm" / SALM_REVISION + assert (salm_directory / "tiny-salm-small.gguf").read_bytes() == SALM_SMALL_PAYLOAD + + # Resolving the decoder for a command also brings its encoder file. + audio = pathlib.Path(__file__).resolve().parents[2] / "test_files/asr/wav/test/jfk.wav" + resolve_cache = root / "resolve-cache" + resolved = run( + binary, + {**environment, "NEMO_SPEECH_MODEL_DIR": str(resolve_cache)}, + "transcribe", + str(audio), + "--model", + "tiny-salm", + ) + if "unknown command" not in resolved.stderr: + resolved_directory = resolve_cache / "acme" / "tiny-salm" / SALM_REVISION + assert (resolved_directory / "tiny-salm.gguf").read_bytes() == SALM_PAYLOAD + assert ( + resolved_directory / "tiny-salm-encoder.gguf" + ).read_bytes() == SALM_ENCODER_PAYLOAD + + # A later entry of a repository needs an alias. + shared_index = json.loads(index.read_text(encoding="utf-8")) + del shared_index["models"][4]["aliases"] + index.write_text(json.dumps(shared_index), encoding="utf-8") + shared = expect_json_error(run(binary, environment, "--json", "model", "list"), 1) + assert "duplicate repository in model index: acme/tiny-salm" in shared["message"] + write_index(index, hashlib.sha256(PAYLOAD).hexdigest(), tokenizer_tar) + ranged_archive, ranges, selected = ranged_tokenizer_archive() ranged_index = json.loads(index.read_text(encoding="utf-8")) ranged_artifact = ranged_index["models"][1]["artifacts"][1] From f8a0e54b290fec3f0d7af4e509b2c5a3d895dc14 Mon Sep 17 00:00:00 2001 From: Prabhsimran Singh Date: Wed, 18 Nov 2026 20:56:45 +0530 Subject: [PATCH 04/10] feat(models): index the SALM decoders, encoder file and DFlash2 drafter - nemotron-transcribe: the IQ4_NL decoder and the encoder file - nemotron-transcribe-nvfp4: the NVFP4 decoder and the same encoder file - nemotron-transcribe-dflash2: the DFlash2 draft model - All from nvidia/NVIDIA-Nemotron-3.5-Transcribe-30B-A4B-GGUF at 6a0b402 Signed-off-by: Prabhsimran Singh --- models/index.json | 62 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) diff --git a/models/index.json b/models/index.json index a1f7e9d..5ac7f96 100644 --- a/models/index.json +++ b/models/index.json @@ -72,6 +72,68 @@ } ] }, + { + "repo": "nvidia/NVIDIA-Nemotron-3.5-Transcribe-30B-A4B-GGUF", + "aliases": ["nemotron-transcribe"], + "revision": "6a0b4021f8a4d09d2cbc48ef27193564b0c21510", + "license": "OpenMDW-1.1", + "license_url": "https://huggingface.co/nvidia/NVIDIA-Nemotron-3.5-Transcribe-30B-A4B-GGUF", + "artifacts": [ + { + "role": "asr", + "type": "file", + "filename": "NVIDIA-Nemotron-3.5-Transcribe-30B-A4B-IQ4_NL.gguf", + "size": 20352805856, + "sha256": "001bea92194596abe971528cf903efe2970f766ac809e4b46381d8567e2dfa30" + }, + { + "role": "asr_encoder", + "type": "file", + "filename": "NVIDIA-Nemotron-3.5-Transcribe-30B-A4B-Encoder-F16.gguf", + "size": 1670410080, + "sha256": "98b97e3b591a268229762fed39b7cbb26a322aa89a15f0bbee49d340bbdf6fe1" + } + ] + }, + { + "repo": "nvidia/NVIDIA-Nemotron-3.5-Transcribe-30B-A4B-GGUF", + "aliases": ["nemotron-transcribe-nvfp4"], + "revision": "6a0b4021f8a4d09d2cbc48ef27193564b0c21510", + "license": "OpenMDW-1.1", + "license_url": "https://huggingface.co/nvidia/NVIDIA-Nemotron-3.5-Transcribe-30B-A4B-GGUF", + "artifacts": [ + { + "role": "asr", + "type": "file", + "filename": "NVIDIA-Nemotron-3.5-Transcribe-30B-A4B-NVFP4.gguf", + "size": 22765076480, + "sha256": "eb8c9b338003347b527fbe2e249d4ca6fe9bccac289b6105e55b6a6b08a9c4c6" + }, + { + "role": "asr_encoder", + "type": "file", + "filename": "NVIDIA-Nemotron-3.5-Transcribe-30B-A4B-Encoder-F16.gguf", + "size": 1670410080, + "sha256": "98b97e3b591a268229762fed39b7cbb26a322aa89a15f0bbee49d340bbdf6fe1" + } + ] + }, + { + "repo": "nvidia/NVIDIA-Nemotron-3.5-Transcribe-30B-A4B-GGUF", + "aliases": ["nemotron-transcribe-dflash2"], + "revision": "6a0b4021f8a4d09d2cbc48ef27193564b0c21510", + "license": "OpenMDW-1.1", + "license_url": "https://huggingface.co/nvidia/NVIDIA-Nemotron-3.5-Transcribe-30B-A4B-GGUF", + "artifacts": [ + { + "role": "draft", + "type": "file", + "filename": "NVIDIA-Nemotron-3.5-Transcribe-30B-A4B-DFlash2-BF16.gguf", + "size": 1149497536, + "sha256": "a08e8da4053111d9743fe5c8a137e60d0fd743e84e0793cef65fd2588da8c5ce" + } + ] + }, { "repo": "nvidia/Nemotron-3-Diarization", "aliases": ["nemotron-3-diarization", "nemotron-diar"], From 06ef3cb14c3a03540c96bd5a831f357a33c92852 Mon Sep 17 00:00:00 2001 From: Prabhsimran Singh Date: Sun, 22 Nov 2026 12:25:49 +0530 Subject: [PATCH 05/10] fix(salm): BF16 argmax on Vulkan and Metal, FP8 scales across shards, reused encoder name - Vulkan and Metal reject ggml_argmax_bf16 in supports_op, so it runs on the CPU there instead of as a plain argmax; argmax_bf16 skips a GPU backend that rejects it - ModelOpt encoder conversion finds an FP8 weight's scale in any shard - --salm-encoder none names the encoder file next to the output (F16 or F32), else the checkpoint's default - docs: the BF16 intermediate and llama-quantize apply to BF16 checkpoints only; a ModelOpt checkpoint's encoder file defaults to F32 Signed-off-by: Prabhsimran Singh --- conversion/pee.py | 42 ++++++++++--------- conversion/salm.py | 24 +++++++++-- docs/model-conversion.md | 17 ++++---- docs/salm/models.md | 3 +- ...ggml-argmax-over-bf16-rounded-values.patch | 32 +++++++++++++- tests/conversion/converter_contract_test.py | 29 +++++++++++++ tests/cpp/speechlm/test_argmax_bf16.cpp | 26 +++++++++++- 7 files changed, 139 insertions(+), 34 deletions(-) diff --git a/conversion/pee.py b/conversion/pee.py index 9f4558c..3d5863c 100644 --- a/conversion/pee.py +++ b/conversion/pee.py @@ -29,6 +29,7 @@ from __future__ import annotations +import contextlib import json import math import re @@ -221,26 +222,27 @@ def _load_salm_perception(path: Path) -> tuple[dict, dict]: with (path / "config.json").open("r", encoding="utf-8") as f: cfg = dict(json.load(f)["pe_encoder_config"]) sd: dict = {} - for shard in sorted(path.glob("*.safetensors")): - with safe_open(str(shard), framework="pt", device="cpu") as f: - keys = set(f.keys()) - for key in sorted(keys): - if not key.startswith(_SALM_PREFIX) or "_extra_state" in key: - continue - if key.endswith((".weight_scale", ".input_scale", ".weight_scale_2")): - continue # applied to their weight below - tensor = f.get_tensor(key) - scale_key = key.removesuffix(".weight") + ".weight_scale" - if tensor.dtype == torch.float8_e4m3fn: - scale = f.get_tensor(scale_key) if scale_key in keys else None - if scale is None or scale.numel() != 1: - raise RuntimeError(f"{key}: an FP8 weight needs one per-tensor {scale_key}") - tensor = tensor.float() * scale.float() - elif scale_key in keys: - raise RuntimeError( - f"{key}: unsupported quantized encoder weight ({tensor.dtype})" - ) - sd[key[len(_SALM_PREFIX) :]] = tensor + with contextlib.ExitStack() as stack: + # every shard open at once: a weight's scale may be stored in another shard + files = {} + for shard in sorted(path.glob("*.safetensors")): + f = stack.enter_context(safe_open(str(shard), framework="pt", device="cpu")) + files.update((key, f) for key in f.keys()) + for key in sorted(files): + if not key.startswith(_SALM_PREFIX) or "_extra_state" in key: + continue + if key.endswith((".weight_scale", ".input_scale", ".weight_scale_2")): + continue # applied to their weight below + tensor = files[key].get_tensor(key) + scale_key = key.removesuffix(".weight") + ".weight_scale" + if tensor.dtype == torch.float8_e4m3fn: + scale = files[scale_key].get_tensor(scale_key) if scale_key in files else None + if scale is None or scale.numel() != 1: + raise RuntimeError(f"{key}: an FP8 weight needs one per-tensor {scale_key}") + tensor = tensor.float() * scale.float() + elif scale_key in files: + raise RuntimeError(f"{key}: unsupported quantized encoder weight ({tensor.dtype})") + sd[key[len(_SALM_PREFIX) :]] = tensor if not sd: raise RuntimeError(f"no perception.* tensors found in {path}") return cfg, sd diff --git a/conversion/salm.py b/conversion/salm.py index 0f4b78f..3716f3d 100644 --- a/conversion/salm.py +++ b/conversion/salm.py @@ -19,8 +19,8 @@ llama.cpp rounds every block to three of its four levels, so the converter checks its output for the fourth. The speech encoder (conversion/pee.py) is F16 ("none" writes the decoder alone, for a second profile of a checkpoint -whose encoder file exists) and the CTC timestamp head (conversion/ctc_timestamp.py) comes from the checkpoint when it -carries one (ctc_timestamp.*). +whose encoder file exists, and names that file) and the CTC timestamp head (conversion/ctc_timestamp.py) comes from +the checkpoint when it carries one (ctc_timestamp.*). A checkpoint quantized with ModelOpt (hf_quant_config.json; NVFP4 and FP8 layers, Hugging Face NemotronH tensor names) keeps its weights: it converts to `nvfp4` only, the decoder straight from llama.cpp's converter without @@ -236,7 +236,13 @@ def convert( print( f"[convert-salm] decoder -> {'GGUF with the checkpoint weights' if quantized else 'BF16 GGUF'} {decoder}" ) - paired = encoder if encoder != "none" else (QUANTIZED_ENCODER if quantized else DEFAULT_ENCODER) + paired = encoder if encoder != "none" else reused_encoder(outfile.parent, name, quantized) + if encoder == "none": + reused = outfile.with_name(encoder_file_name(name, paired)) + print( + f"[convert-salm] the decoder names the encoder file {reused.name}" + + ("" if reused.is_file() else " (not next to the output yet)") + ) keys = decoder_keys(name, identity, paired) command = [ sys.executable, @@ -286,6 +292,18 @@ def encoder_file_name(name: str, encoder: str = DEFAULT_ENCODER) -> str: return f"{name}-Encoder-{encoder.upper()}.gguf" +def reused_encoder(directory: Path, name: str, quantized: bool = False) -> str: + """--salm-encoder none: the type of the encoder file the decoder pairs with, the checkpoint's encoder file in + directory when there is one of a single type, otherwise the checkpoint's default (F32 for a ModelOpt checkpoint, + F16 for the others).""" + found = [ + kind for kind in ("f16", "f32") if (directory / encoder_file_name(name, kind)).is_file() + ] + if len(found) == 1: + return found[0] + return QUANTIZED_ENCODER if quantized else DEFAULT_ENCODER + + def decoder_keys(name: str, identity: str, encoder: str = DEFAULT_ENCODER) -> list[str]: """The decoder's nemo_speech keys: the checkpoint id and the encoder file it pairs with, also when this run writes no encoder file (--salm-encoder none reuses the checkpoint's existing one).""" diff --git a/docs/model-conversion.md b/docs/model-conversion.md index 37f18d6..1337937 100644 --- a/docs/model-conversion.md +++ b/docs/model-conversion.md @@ -76,9 +76,10 @@ experts); embeddings, the output head and the norms stay BF16/F32: | `iq4_nl` | IQ4_NL | Q8_0 | GPUs without NVFP4 (Ampere, Ada), CPU, Vulkan | | `q2_0` | Q2_0, IQ4_NL in the last five MoE layers | Q8_0 (also the embeddings and output head) | the smallest file, for smaller GPUs | -The encoder file is the same for every `--outtype` (F16 encoder and F32 CTC head), named after the -checkpoint, so decoders of several types share one. `--salm-encoder none` writes only the decoder, for a second -`--outtype` of a checkpoint whose encoder file exists; `--architecture pee` converts only the speech encoder. +The encoder file is the same for every `--outtype` (F16 encoder and F32 CTC head), named after the checkpoint, so +decoders of several types share one. `--salm-encoder none` writes only the decoder, for a second `--outtype` of a +checkpoint whose encoder file exists, and the decoder names the encoder file next to it; `--architecture pee` +converts only the speech encoder. A checkpoint quantized with ModelOpt (it carries `hf_quant_config.json`, with NVFP4 and FP8 layers) keeps its weights: it converts to `--outtype nvfp4` only, and the other types convert from the BF16 checkpoint. The decoder's @@ -89,10 +90,12 @@ F32 (`-Encoder-F32.gguf`), which holds the FP8 encoder weights exact smaller F16 one. The conversion stages the checkpoint's decoder for llama.cpp's NemotronH converter (the pinned `llama.cpp` -submodule), writes a BF16 intermediate next to the output (the size of the BF16 decoder) and then quantizes it -with the patched `llama-quantize`, built once on first use like the S2S converter's. `--dry-run` checks the tensor -mapping without writing. `q2_0` needs the Q2_0 scale fitting in `patches/`: the converter builds `llama-quantize` -for it from this repository's patched `llama.cpp` (not a `--llama-cpp` checkout) and checks its output. +submodule). From a BF16 checkpoint it writes a BF16 intermediate next to the output (the size of the BF16 decoder) +and then quantizes it with the patched `llama-quantize`, built once on first use like the S2S converter's; a +ModelOpt checkpoint's decoder is written directly, without the intermediate or `llama-quantize`. `--dry-run` checks +the tensor mapping without writing. `q2_0` needs the Q2_0 scale fitting in `patches/`: the converter builds +`llama-quantize` for it from this repository's patched `llama.cpp` (not a `--llama-cpp` checkout) and checks its +output. ### DFlash2 draft model diff --git a/docs/salm/models.md b/docs/salm/models.md index d85748e..5394953 100644 --- a/docs/salm/models.md +++ b/docs/salm/models.md @@ -48,7 +48,8 @@ nemo-speech serve --asr-model $MODEL \ ## What the files are A model is two GGUF files in one directory: the language-model decoder, which is the model you pass, and the encoder -file it names (`-Encoder-F16.gguf`): the speech encoder with its speaker branch, and the CTC timestamp head +file it names (`-Encoder-F16.gguf`, or `-Encoder-F32.gguf` by default from a ModelOpt checkpoint; +`--salm-encoder` at conversion sets it): the speech encoder with its speaker branch, and the CTC timestamp head (word timestamps and speaker labels). Decoders of every precision share one encoder file, and a decoder refuses an encoder file of another checkpoint. The DFlash2 draft model is a separate optional file. [Model conversion](../model-conversion.md#speech-llm-salm) makes the files from a checkpoint. `--salm-encoder` (or diff --git a/patches/ggml-argmax-over-bf16-rounded-values.patch b/patches/ggml-argmax-over-bf16-rounded-values.patch index bc285c6..5f20d24 100644 --- a/patches/ggml-argmax-over-bf16-rounded-values.patch +++ b/patches/ggml-argmax-over-bf16-rounded-values.patch @@ -6,7 +6,8 @@ BF16 (round to nearest even), and the lowest index among equal values: the result of an argmax over the same values held in a BF16 tensor. A decoder whose reference implementation computes its logits in BF16 picks the same tokens with it as that implementation. The CPU and CUDA backends implement -it; ggml_argmax is unchanged. +it; Vulkan and Metal reject it in supports_op, so it runs on the CPU there. +ggml_argmax is unchanged. Upstream: stays here (greedy decoding of BF16 speech-LLM checkpoints). @@ -113,6 +114,35 @@ index 51967c667cfd88a8d9d81ddbf827bce402d65761..678b9fed47bad2b484c32b8930002af6 + argmax_f32<<>>(src0_d, dst_d, ne00); + } } +diff --git a/ggml/src/ggml-metal/ggml-metal-device.m b/ggml/src/ggml-metal/ggml-metal-device.m +index 81ea7f9d7a97f10456c5427a18cb261b1315a7d9..8327c9aadf2dc2a4c4d1cc406a741b09616a6e92 100644 +--- a/ggml/src/ggml-metal/ggml-metal-device.m ++++ b/ggml/src/ggml-metal/ggml-metal-device.m +@@ -1674,7 +1674,8 @@ bool ggml_metal_device_supports_op(ggml_metal_device_t dev, const struct ggml_te + op->src[1]->type == GGML_TYPE_I32 && + op->type == GGML_TYPE_I64; + case GGML_OP_ARGMAX: +- return has_simdgroup_reduction; ++ // ggml_argmax_bf16 (op_params[0]) is not implemented here; it runs on the CPU ++ return has_simdgroup_reduction && ggml_get_op_params_i32(op, 0) == 0; + case GGML_OP_NORM: + case GGML_OP_RMS_NORM: + return has_simdgroup_reduction && (ggml_is_contiguous_rows(op->src[0])); +diff --git a/ggml/src/ggml-vulkan/ggml-vulkan.cpp b/ggml/src/ggml-vulkan/ggml-vulkan.cpp +index 1720657cf46c40f9b802bbae8d2d3095dc3489d1..f5d4a9746cd0c06570f0f1af58c00a4e0a92fb1e 100644 +--- a/ggml/src/ggml-vulkan/ggml-vulkan.cpp ++++ b/ggml/src/ggml-vulkan/ggml-vulkan.cpp +@@ -15513,7 +15513,9 @@ static bool ggml_backend_vk_device_supports_op(ggml_backend_dev_t dev, const ggm + return true; + } + case GGML_OP_ARGMAX: +- return ggml_is_contiguous(op->src[0]) && op->src[0]->type == GGML_TYPE_F32; ++ // ggml_argmax_bf16 (op_params[0]) is not implemented here; it runs on the CPU ++ return ggml_is_contiguous(op->src[0]) && op->src[0]->type == GGML_TYPE_F32 ++ && ggml_get_op_params_i32(op, 0) == 0; + case GGML_OP_CROSS_ENTROPY_LOSS: + return ggml_is_contiguous(op->src[0]) && op->src[0]->type == GGML_TYPE_F32 + && ggml_is_contiguous(op->src[1]) && op->src[1]->type == GGML_TYPE_F32 diff --git a/ggml/src/ggml.c b/ggml/src/ggml.c index a2c11d254728236205cec60d2092d9849e43a7fc..d08015cfbbad955d712e8476dff4c711d89ad0ac 100644 --- a/ggml/src/ggml.c diff --git a/tests/conversion/converter_contract_test.py b/tests/conversion/converter_contract_test.py index 22b5614..f20529e 100644 --- a/tests/conversion/converter_contract_test.py +++ b/tests/conversion/converter_contract_test.py @@ -61,6 +61,7 @@ from conversion.salm import kept_expert_layers as salm_kept_expert_layers from conversion.salm import modelopt_quantization as salm_modelopt_quantization from conversion.salm import q2_0_uses_top_level as salm_q2_0_uses_top_level +from conversion.salm import reused_encoder as salm_reused_encoder from conversion.salm import stage as stage_salm from conversion.salm import tensor_rules as salm_tensor_rules from conversion.source import extract_archive @@ -349,6 +350,18 @@ def test_salm_quantization_rules(self) -> None: salm_encoder_file_name("example-salm", "f16"), "example-salm-Encoder-F16.gguf", ) + # --salm-encoder none names the encoder file next to the output: the one there, or else the default + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + self.assertEqual(salm_reused_encoder(root, "example-salm"), "f16") + self.assertEqual(salm_reused_encoder(root, "example-salm", quantized=True), "f32") + (root / "example-salm-Encoder-F32.gguf").touch() + self.assertEqual(salm_reused_encoder(root, "example-salm"), "f32") + (root / "example-salm-Encoder-F16.gguf").touch() + self.assertEqual(salm_reused_encoder(root, "example-salm"), "f16") + self.assertEqual(salm_reused_encoder(root, "example-salm", quantized=True), "f32") + (root / "example-salm-Encoder-F32.gguf").unlink() + self.assertEqual(salm_reused_encoder(root, "example-salm", quantized=True), "f16") # every decoder names its encoder file, also one converted with --salm-encoder none self.assertEqual( salm_decoder_keys("example-salm", "0123"), @@ -433,6 +446,22 @@ def test_salm_encoder_fp8_weights(self) -> None: fp8 = sd["encoder.asr_encoder.layers.0.attn.out_proj.weight"] self.assertEqual(fp8.dtype, torch.float32) self.assertTrue(torch.equal(fp8, weight.float() * torch.tensor(0.0071))) + # the scale may sit in another shard than its weight + (root / "perception.safetensors").unlink() + save_file( + {k: v for k, v in tensors.items() if not k.endswith("_scale")}, + str(root / "model-00001-of-00002.safetensors"), + ) + save_file( + {k: v for k, v in tensors.items() if k.endswith("_scale")}, + str(root / "model-00002-of-00002.safetensors"), + ) + _, sharded = _load_salm_perception(root) + self.assertEqual(sorted(sharded), sorted(sd)) + for key, tensor in sd.items(): + self.assertTrue(torch.equal(sharded[key], tensor)) + for shard in root.glob("*.safetensors"): + shard.unlink() # an FP8 weight without its scale is refused del tensors[f"{prefix}.weight_scale"] save_file(tensors, str(root / "perception.safetensors")) diff --git a/tests/cpp/speechlm/test_argmax_bf16.cpp b/tests/cpp/speechlm/test_argmax_bf16.cpp index c59840f..1cec161 100644 --- a/tests/cpp/speechlm/test_argmax_bf16.cpp +++ b/tests/cpp/speechlm/test_argmax_bf16.cpp @@ -5,7 +5,8 @@ // tokens with the op on the device, the upstream path with greedy_pick on the host, and both must // give the same token. Rows of vocabulary width and narrower, with equal values after the BF16 // rounding placed so that a plain argmax, or an argmax that does not take the lowest index, gives -// another column. Runs on the CPU backend and, when there is one, the GPU backend. +// another column. Runs on the CPU backend and on the GPU backend when there is one that supports +// the op (CUDA; Vulkan and Metal reject it, so the scheduler runs it on the CPU there). #include #include #include @@ -78,6 +79,16 @@ run(ggml_backend_t backend, const std::vector& x, int64_t cols, int64_t r return out; } +bool +supports_argmax_bf16(ggml_backend_t backend) { + ggml_init_params params{ggml_tensor_overhead() * 2, nullptr, true}; + ggml_context* ctx = ggml_init(params); + const bool ok = ggml_backend_supports_op( + backend, ggml_argmax_bf16(ctx, ggml_new_tensor_2d(ctx, GGML_TYPE_F32, 8, 1))); + ggml_free(ctx); + return ok; +} + } // namespace int @@ -85,8 +96,19 @@ main() { ggml_backend_t backends[2] = { ggml_backend_cpu_init(), ggml_backend_init_by_type(GGML_BACKEND_DEVICE_TYPE_GPU, nullptr)}; const char* names[2] = {"CPU", "GPU"}; - if (!backends[1]) + if (!backends[1]) { std::fprintf(stderr, "no GPU backend available; CPU only\n"); + } else if (!supports_argmax_bf16(backends[1])) { + std::fprintf( + stderr, "%s does not support ggml_argmax_bf16 (it runs on the CPU there); CPU only\n", + ggml_backend_name(backends[1])); + ggml_backend_free(backends[1]); + backends[1] = nullptr; + } + if (!supports_argmax_bf16(backends[0])) { + std::fprintf(stderr, "FAIL: the CPU backend does not support ggml_argmax_bf16\n"); + return 1; + } int failures = 0; const int64_t widths[] = {131072, 4097, 1000, 70, 3}; // the vocabulary, and under one block From 0f91e8d96e8048885b8544d44b66f01e37ef0ed6 Mon Sep 17 00:00:00 2001 From: Prabhsimran Singh Date: Sun, 22 Nov 2026 12:25:50 +0530 Subject: [PATCH 06/10] fix(model-store): resolve the draft model only when it drafts - transcribe, bench and serve resolve asr.salm.dflash_path only with mtp_draft > 0 (transcribe and serve: for a speech-LLM model) - transcribe resolves it after the option checks, so a rejected command downloads nothing - cli_model_store: a GGUF decoder fixture; --stream and mtp_draft 0 download no draft, the default does Signed-off-by: Prabhsimran Singh --- app/bench_asr.cpp | 3 +- app/serve.cpp | 4 ++- app/transcribe.cpp | 10 +++--- tests/cli/model_store_test.py | 65 ++++++++++++++++++++++++++++++++++- 4 files changed, 75 insertions(+), 7 deletions(-) diff --git a/app/bench_asr.cpp b/app/bench_asr.cpp index 15b010f..063643c 100644 --- a/app/bench_asr.cpp +++ b/app/bench_asr.cpp @@ -103,7 +103,8 @@ class AsrWorkload : public Workload { const std::string reference = model_.empty() ? config_.model.path : model_; if (config_.salm.encoder_path.empty() || !reference.empty()) config_.model.path = resolve_model_file(reference, "asr", "ASR model").string(); - if (!config_.salm.dflash_path.empty()) + // the engine loads a draft model only for speculative decoding (mtp_draft > 0) + if (config_.salm.mtp_draft > 0 && !config_.salm.dflash_path.empty()) config_.salm.dflash_path = resolve_model_file(config_.salm.dflash_path, "draft", "DFlash2 draft model") .string(); diff --git a/app/serve.cpp b/app/serve.cpp index 5b0edb3..f023e1e 100644 --- a/app/serve.cpp +++ b/app/serve.cpp @@ -445,7 +445,9 @@ run_server(int argc, char** argv) { nemo_speech::asr::resolve_salm_encoder(asr_config); return asr_config.salm.encoder_path; }).empty(); - if (start_asr && !asr_config.salm.dflash_path.empty()) + // the engine loads a draft model only for speculative decoding (mtp_draft > 0) + if (start_asr && speech_llm && asr_config.salm.mtp_draft > 0 && + !asr_config.salm.dflash_path.empty()) asr_config.salm.dflash_path = resolve("DFlash2 draft model", [&] { return optional_model( asr_config.salm.dflash_path, "draft", "DFlash2 draft model", true); diff --git a/app/transcribe.cpp b/app/transcribe.cpp index a185ad6..d302389 100644 --- a/app/transcribe.cpp +++ b/app/transcribe.cpp @@ -745,10 +745,6 @@ command_transcribe(int argc, char** argv) { // speaker branch. asr::resolve_salm_encoder(config); const bool speech_llm = !config.salm.encoder_path.empty(); - if (!config.salm.dflash_path.empty()) - config.salm.dflash_path = - resolve_model_file(config.salm.dflash_path, "draft", "DFlash2 draft model") - .string(); if (!options.instruction.empty() && !speech_llm) throw std::invalid_argument("--instruction needs a speech-LLM (SALM) model"); // --translate-to: a speech-LLM translates the speech itself unless an NMT model is named. @@ -775,6 +771,12 @@ command_transcribe(int argc, char** argv) { throw std::invalid_argument( std::string("SALM supports complete audio only; ") + (options.live ? "--live" : "--stream") + " streaming recognition is unavailable"); + // after the checks above, so a rejected command downloads nothing; the engine loads a draft + // model only for speculative decoding (mtp_draft > 0) + if (speech_llm && config.salm.mtp_draft > 0 && !config.salm.dflash_path.empty()) + config.salm.dflash_path = + resolve_model_file(config.salm.dflash_path, "draft", "DFlash2 draft model") + .string(); if (!options.vad_model.empty() || !config.vad.model_path.empty()) config.vad.model_path = require_model_file( diff --git a/tests/cli/model_store_test.py b/tests/cli/model_store_test.py index 4fda099..0fc24db 100644 --- a/tests/cli/model_store_test.py +++ b/tests/cli/model_store_test.py @@ -8,6 +8,7 @@ import json import os import pathlib +import struct import subprocess import sys import tarfile @@ -19,7 +20,20 @@ PAYLOAD = b"NeMo-Speech.cpp model-store fixture\n" CODEC_PAYLOAD = b"NeMo-Speech.cpp codec fixture\n" TTS_PAYLOAD = b"NeMo-Speech.cpp TTS fixture\n" -SALM_PAYLOAD = b"NeMo-Speech.cpp speech-LLM decoder fixture\n" + + +def gguf_naming(key: str, value: str) -> bytes: + """A GGUF v3 file with no tensors and one string key: a speech-LLM decoder header for key + nemo_speech.speech_model, which names the encoder file.""" + + def text(item: str) -> bytes: + return struct.pack(" list[tuple[str, str, bool]]: resolved_directory / "tiny-salm-encoder.gguf" ).read_bytes() == SALM_ENCODER_PAYLOAD + # A draft model downloads only when the command can run and drafts: not for streaming, + # which a speech-LLM rejects, and not with mtp_draft 0. + if "unknown command" not in resolved.stderr: + draft_cache = root / "draft-cache" + draft_environment = {**environment, "NEMO_SPEECH_MODEL_DIR": str(draft_cache)} + drafts_before = ArtifactHandler.request_counts.get("tiny-salm-draft.gguf", 0) + rejected = run( + binary, + draft_environment, + "transcribe", + str(audio), + "--model", + "tiny-salm", + "--stream", + "--asr.salm.dflash_path", + "tiny-salm-draft", + ) + assert rejected.returncode != 0 + assert "SALM supports complete audio only" in rejected.stderr, rejected.stderr + undrafted = run( + binary, + draft_environment, + "transcribe", + str(audio), + "--model", + "tiny-salm", + "--asr.salm.mtp_draft", + "0", + "--asr.salm.dflash_path", + "tiny-salm-draft", + ) + assert "DFlash2 draft model" not in undrafted.stderr, undrafted.stderr + assert ( + ArtifactHandler.request_counts.get("tiny-salm-draft.gguf", 0) == drafts_before + ) + assert not list(draft_cache.rglob("tiny-salm-draft.gguf")) + drafted = run( + binary, + draft_environment, + "transcribe", + str(audio), + "--model", + "tiny-salm", + "--asr.salm.dflash_path", + "tiny-salm-draft", + ) + assert drafted.returncode != 0 # the fixture decoder has no weights + assert list(draft_cache.rglob("tiny-salm-draft.gguf")), drafted.stderr + # A later entry of a repository needs an alias. shared_index = json.loads(index.read_text(encoding="utf-8")) del shared_index["models"][4]["aliases"] From d15aa02490aa1d469538ce94588ca17e15508442 Mon Sep 17 00:00:00 2001 From: Prabhsimran Singh Date: Sun, 22 Nov 2026 12:39:18 +0530 Subject: [PATCH 07/10] fix(build): link with a static llama.cpp (GGML_STATIC) - the runtime's global format() is weak on GCC and Clang, so a library that also links llama.cpp statically takes llama-impl.cpp's identical definition instead of failing on a duplicate symbol (#102) Signed-off-by: Prabhsimran Singh --- src/runtime/ggml/logging.cpp | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/runtime/ggml/logging.cpp b/src/runtime/ggml/logging.cpp index 036d73a..84637d9 100644 --- a/src/runtime/ggml/logging.cpp +++ b/src/runtime/ggml/logging.cpp @@ -50,7 +50,12 @@ log_internal( } // namespace ggml_runtime -// Global-namespace; called from llama_file and other global helpers. +// Global-namespace; called from llama_file and other global helpers. Weak: a library that also +// links llama.cpp statically (GGML_STATIC) takes llama-impl.cpp's identical format() instead of +// failing on a duplicate definition. +#if defined(__GNUC__) || defined(__clang__) +__attribute__((weak)) +#endif std::string format(const char* fmt, ...) { va_list ap; From 8090c0b0363691d29d2f5e2426739ee061ffe657 Mon Sep 17 00:00:00 2001 From: Prabhsimran Singh Date: Sun, 22 Nov 2026 12:39:23 +0530 Subject: [PATCH 08/10] fix(http): accept the ASR model's names in a request's model field - the ASR model id drops the leading dot that some published GGUFs carry in general.name - /v1/audio/transcriptions and /v1/audio/translations also accept the name serve loaded the model by (indexed name, its repository ID and aliases, or a path), its file name with or without the extension, and an id with a leading dot (#94) Signed-off-by: Prabhsimran Singh --- app/model_store.cpp | 14 ++++++++++++++ app/model_store.h | 3 +++ app/serve.cpp | 11 +++++++++++ docs/api.md | 2 +- server/http/http_server.cpp | 25 ++++++++++++++++++++----- server/http/http_server.h | 4 ++++ src/asr/model.cpp | 4 ++++ 7 files changed, 57 insertions(+), 6 deletions(-) diff --git a/app/model_store.cpp b/app/model_store.cpp index 7a2ce5b..10a8401 100644 --- a/app/model_store.cpp +++ b/app/model_store.cpp @@ -1347,6 +1347,20 @@ resolve_indexed_model_directory( return resolve(reference, role, description, true); } +std::vector +indexed_model_names(const std::string& reference) { + try { + const Index index = load_index(); + const Model& model = find_model(index, reference); + std::vector names{model.repo}; + names.insert(names.end(), model.aliases.begin(), model.aliases.end()); + return names; + } + catch (const std::exception&) { + return {}; + } +} + std::vector pull_indexed_model(const std::string& repo) { const Index index = load_index(); diff --git a/app/model_store.h b/app/model_store.h index 3800130..d611b67 100644 --- a/app/model_store.h +++ b/app/model_store.h @@ -19,6 +19,9 @@ std::filesystem::path resolve_indexed_model_directory( const std::string& reference, const std::string& role, const std::string& description); std::vector pull_indexed_model(const std::string& repo); +// The repository ID and aliases of the index entry `reference` names; none when it names no entry +// (a local path) or there is no index. +std::vector indexed_model_names(const std::string& reference); std::string indexed_models_json(); std::string indexed_models_text(); std::filesystem::path model_downloader_executable(); diff --git a/app/serve.cpp b/app/serve.cpp index f023e1e..b57840d 100644 --- a/app/serve.cpp +++ b/app/serve.cpp @@ -21,6 +21,7 @@ #include "engine_registry.h" #include "http_server.h" #include "json.h" +#include "model_store.h" #include "model_utils.h" #include "parameter_parser.h" #if defined(NEMO_SPEECH_CLI_TTS) @@ -436,6 +437,16 @@ run_server(int argc, char** argv) { if (device_set) asr_config.backend.gpu = gpu; asr_config.model.path = asr_path; + // a request's `model` may also name the model as it was started (path, or indexed name and + // then also its repository ID and other aliases) or by its file name, with or without the + // extension + if (!asr_path.empty()) { + const std::filesystem::path file(asr_path); + server_config.asr_model_names = indexed_model_names(asr_reference); + server_config.asr_model_names.insert( + server_config.asr_model_names.end(), + {asr_reference, file.filename().string(), file.stem().string()}); + } } // A speech-LLM decoder names its encoder file (GGUF headers only), so SALM is known here, // before any model load, also from the decoder alone. diff --git a/docs/api.md b/docs/api.md index faf1735..66362be 100644 --- a/docs/api.md +++ b/docs/api.md @@ -42,7 +42,7 @@ uses the `/v1/audio/transcriptions/realtime` WebSocket described below. | Field | Type | Default | Description | |---|---|---|---| -| `model` | string | loaded ASR model | omitted or empty: the loaded ASR model; otherwise its id from `GET /v1/models` (or the chat API's served id), and any other id is a 404 `unknown_model` | +| `model` | string | loaded ASR model | omitted or empty: the loaded ASR model; otherwise its id from `GET /v1/models`, the chat API's served id, or the name `serve` loaded it by (indexed name, repository ID or path) or its file name; any other id is a 404 `unknown_model` | | `file` | WAV upload | required | audio to transcribe | | `language` | string | model default | language code; prompt-conditioned models select their language prompt | | `response_format` | string | `json` | `json`, `verbose_json` (adds words/timestamps), `text`, `srt`, or `vtt` | diff --git a/server/http/http_server.cpp b/server/http/http_server.cpp index 810dea2..4a06199 100644 --- a/server/http/http_server.cpp +++ b/server/http/http_server.cpp @@ -141,14 +141,19 @@ form_value( } // `model` of the ASR upload routes, as the chat API takes it: omitted or empty is the loaded -// model, otherwise one of `served` (the ids GET /v1/models lists for the route and the chat API's -// served id); any other id answers 404 unknown_model. True when the request was refused. +// model, otherwise one of `served` (the ids GET /v1/models lists for the route, the chat API's +// served id and the names the ASR model was started with); any other id answers 404 +// unknown_model. An id with leading dots also matches without them (0.3.0 listed some ASR ids +// with one). True when the request was refused. bool refuse_unknown_model( const httplib::Request& request, httplib::Response& response, const std::vector& served) { const std::string model = form_value(request, "model"); - if (model.empty() || std::find(served.begin(), served.end(), model) != served.end()) + const size_t first = model.find_first_not_of('.'); + const std::string undotted = first == std::string::npos ? model : model.substr(first); + if (model.empty() || std::find(served.begin(), served.end(), model) != served.end() || + std::find(served.begin(), served.end(), undotted) != served.end()) return false; Value root(Value::Object{}); Value error(Value::Object{}); @@ -386,6 +391,15 @@ struct Server::Impl { std::atomic request_id{1}; TtsPreemptionCoordinator tts_preemption; + // `served` and the ids a request's `model` may use for the ASR model: its listed id and the + // names it was started with + std::vector asr_ids( + const std::string& model_name, std::vector served) const { + served.push_back(model_name); + served.insert(served.end(), config.asr_model_names.begin(), config.asr_model_names.end()); + return served; + } + Impl(EngineRegistry& engines, ServerConfig config) : models(engines), config(std::move(config)) { if (this->config.preempt_tts && this->config.threads < 2) { @@ -705,7 +719,8 @@ struct Server::Impl { auto recognizer = this->models.asr(); if (refuse_unknown_model( request, response, - {recognizer->model_name(), this->config.chat.limits.model_name})) + this->asr_ids( + recognizer->model_name(), {this->config.chat.limits.model_name}))) return; const auto result = recognizer->recognize( audio.samples.data(), audio.samples.size(), options, language, @@ -830,7 +845,7 @@ struct Server::Impl { std::vector served = { "speech-translation", this->config.chat.limits.model_name}; try { - served.push_back(this->models.asr()->model_name()); + served = this->asr_ids(this->models.asr()->model_name(), served); } catch (const std::exception&) { } diff --git a/server/http/http_server.h b/server/http/http_server.h index d3445bf..be93b52 100644 --- a/server/http/http_server.h +++ b/server/http/http_server.h @@ -5,6 +5,7 @@ #include #include #include +#include #include "chat_api.h" @@ -35,6 +36,9 @@ struct ServerConfig { bool realtime_s2s_output_text_events = false; // Chat API limits (http.chat.*). chat::ApiConfig chat; + // Names a request's `model` may also use for the ASR model besides its listed id: the name + // or path it was started with and its file name (serve fills them in). + std::vector asr_model_names; }; class Server { diff --git a/src/asr/model.cpp b/src/asr/model.cpp index 07e14ac..989c304 100644 --- a/src/asr/model.cpp +++ b/src/asr/model.cpp @@ -1364,7 +1364,11 @@ AsrModel::load( } else { throw std::runtime_error("Unknown asr.head_type='" + h + "'"); } + // some published GGUFs carry a leading dot in general.name (".nemotron-...gguf") c.model_name = loader.get_str("general.name", "asr"); + c.model_name.erase(0, c.model_name.find_first_not_of('.')); + if (c.model_name.empty()) + c.model_name = "asr"; } else if (arch == "parakeet-ctc" || arch.empty()) { head = HeadKind::Ctc; c.ns = "parakeet-ctc"; From c79650d38b0402dd1b600b91a889b9fac3f625c6 Mon Sep 17 00:00:00 2001 From: Prabhsimran Singh Date: Sun, 22 Nov 2026 13:10:16 +0530 Subject: [PATCH 09/10] fix(http): accept the ASR model's names on the chat route and for the default model - /v1/chat/completions accepts the same names as the upload routes, through one shared check: the listed id with or without leading dots and the names serve loaded the model by - serve without --asr-model also accepts the default model's indexed name and repository ID - chat_api test: the listed, dotted and extra names are served, others are not Signed-off-by: Prabhsimran Singh --- app/model_store.cpp | 11 +++++++++-- app/model_store.h | 7 ++++--- app/serve.cpp | 2 +- docs/api.md | 2 +- server/http/chat_api.cpp | 14 +++++++++++++- server/http/chat_api.h | 10 +++++++++- server/http/http_server.cpp | 9 ++++----- tests/cpp/common/test_chat_api.cpp | 10 ++++++++++ 8 files changed, 51 insertions(+), 14 deletions(-) diff --git a/app/model_store.cpp b/app/model_store.cpp index 10a8401..dc3fa43 100644 --- a/app/model_store.cpp +++ b/app/model_store.cpp @@ -1348,10 +1348,17 @@ resolve_indexed_model_directory( } std::vector -indexed_model_names(const std::string& reference) { +indexed_model_names(const std::string& reference, const std::string& role) { try { const Index index = load_index(); - const Model& model = find_model(index, reference); + std::string repo = reference; + if (repo.empty()) { + const auto found = index.defaults.find(role); + if (found == index.defaults.end()) + return {}; + repo = found->second; + } + const Model& model = find_model(index, repo); std::vector names{model.repo}; names.insert(names.end(), model.aliases.begin(), model.aliases.end()); return names; diff --git a/app/model_store.h b/app/model_store.h index d611b67..fc59561 100644 --- a/app/model_store.h +++ b/app/model_store.h @@ -19,9 +19,10 @@ std::filesystem::path resolve_indexed_model_directory( const std::string& reference, const std::string& role, const std::string& description); std::vector pull_indexed_model(const std::string& repo); -// The repository ID and aliases of the index entry `reference` names; none when it names no entry -// (a local path) or there is no index. -std::vector indexed_model_names(const std::string& reference); +// The repository ID and aliases of the index entry `reference` names, or of the index's default +// model for `role` when `reference` is empty; none when it names no entry (a local path) or there +// is no index. +std::vector indexed_model_names(const std::string& reference, const std::string& role); std::string indexed_models_json(); std::string indexed_models_text(); std::filesystem::path model_downloader_executable(); diff --git a/app/serve.cpp b/app/serve.cpp index b57840d..4ebf1e7 100644 --- a/app/serve.cpp +++ b/app/serve.cpp @@ -442,7 +442,7 @@ run_server(int argc, char** argv) { // extension if (!asr_path.empty()) { const std::filesystem::path file(asr_path); - server_config.asr_model_names = indexed_model_names(asr_reference); + server_config.asr_model_names = indexed_model_names(asr_reference, "asr"); server_config.asr_model_names.insert( server_config.asr_model_names.end(), {asr_reference, file.filename().string(), file.stem().string()}); diff --git a/docs/api.md b/docs/api.md index 66362be..3b47180 100644 --- a/docs/api.md +++ b/docs/api.md @@ -79,7 +79,7 @@ optional instruction travel as one user message: | Field | Type | Default | Description | |---|---|---|---| -| `model` | string | required | the id listed by `GET /v1/models` | +| `model` | string | required | the id listed by `GET /v1/models`, `http.chat.model-name`, or the name `serve` loaded the model by (indexed name, repository ID or path) or its file name | | `messages` | array | required | exactly one `user` message whose `content` holds one `input_audio` part and at most one `text` part (the instruction) | | `language` | string | none | language hint, added to the default instruction as "The speech is in ." for the codes the model knows (`en`, `fr`, `zh`, `tl`, ...); a `text` instruction is used as written. Echoed in the response (`und` when omitted) | | `timestamp_granularities` | array | none | `"word"` and/or `"segment"`: word timestamps, subtitle cues and speakers in the response, in any language (Chinese, Japanese and Thai per character, see transcriptions); needs the CTC timestamp adapter | diff --git a/server/http/chat_api.cpp b/server/http/chat_api.cpp index e553fd1..a7914aa 100644 --- a/server/http/chat_api.cpp +++ b/server/http/chat_api.cpp @@ -46,6 +46,14 @@ namespace nemo_speech::http::chat { +bool +names_model(const std::vector& names, const std::string& requested) { + const size_t first = requested.find_first_not_of('.'); + const std::string undotted = first == std::string::npos ? requested : requested.substr(first); + return std::find(names.begin(), names.end(), requested) != names.end() || + std::find(names.begin(), names.end(), undotted) != names.end(); +} + #if defined(NEMO_SPEECH_REGISTRY_ASR) namespace { @@ -1902,9 +1910,12 @@ Api::post(const HeaderLookup& headers, const BodyReader& read_body, const Client if ((*text)->size() > 262144) throw bad_request(what + " exceeds the configured limit of 262144 bytes", param); } + std::vector names = s.backend.model_names; + if (s.backend.model_alias) + names.push_back(s.backend.model_alias()); const bool served = (!s.limits.model_name.empty() && request.model == s.limits.model_name) || - (s.backend.model_alias && request.model == s.backend.model_alias()); + names_model(names, request.model); if (!served || !s.backend.recognize) throw ApiError{404, "unknown_model", "requested model is not available", {}}; if (deferred) @@ -2126,6 +2137,7 @@ install(httplib::Server& server, EngineRegistry& engines, const ApiConfig& confi return std::string(); } }; + backend.model_names = config.model_names; auto api = std::make_shared(config.limits, std::move(backend)); const auto send = [](const HttpResponse& from, httplib::Response& to) { diff --git a/server/http/chat_api.h b/server/http/chat_api.h index d72ded5..8c8c01e 100644 --- a/server/http/chat_api.h +++ b/server/http/chat_api.h @@ -42,8 +42,15 @@ struct Limits { } }; +// Whether a request's `model` is one of `names`, exactly or without leading dots (0.3.0 listed +// some ASR model ids with one). +bool names_model(const std::vector& names, const std::string& requested); + struct ApiConfig { Limits limits; + // Other names of the loaded ASR model a request may use (serve: the name it was started by and + // its file name); not a setting. + std::vector model_names; void Register(common::ParameterParser& p) { p.Register("chat", limits); } }; @@ -83,8 +90,9 @@ struct Backend { std::function supports_instructions; std::function request_id; // default "asr___" std::function unix_seconds; // default the wall clock - // The `model` accepted: the recognizer's id, which GET /v1/models lists. + // The `model` accepted: the recognizer's id, which GET /v1/models lists, and its other names. std::function model_alias; + std::vector model_names; }; class Api { diff --git a/server/http/http_server.cpp b/server/http/http_server.cpp index 4a06199..e61af5f 100644 --- a/server/http/http_server.cpp +++ b/server/http/http_server.cpp @@ -150,10 +150,7 @@ refuse_unknown_model( const httplib::Request& request, httplib::Response& response, const std::vector& served) { const std::string model = form_value(request, "model"); - const size_t first = model.find_first_not_of('.'); - const std::string undotted = first == std::string::npos ? model : model.substr(first); - if (model.empty() || std::find(served.begin(), served.end(), model) != served.end() || - std::find(served.begin(), served.end(), undotted) != served.end()) + if (model.empty() || chat::names_model(served, model)) return false; Value root(Value::Object{}); Value error(Value::Object{}); @@ -1349,7 +1346,9 @@ struct Server::Impl { server->WebSocket("/realtime", std::move(realtime_s2s), select_s2s_subprotocol); } #endif - chat::install(*server, models, this->config.chat); + chat::ApiConfig chat_config = this->config.chat; + chat_config.model_names = this->config.asr_model_names; + chat::install(*server, models, chat_config); } }; diff --git a/tests/cpp/common/test_chat_api.cpp b/tests/cpp/common/test_chat_api.cpp index 0563677..7831baf 100644 --- a/tests/cpp/common/test_chat_api.cpp +++ b/tests/cpp/common/test_chat_api.cpp @@ -647,6 +647,16 @@ test_validation() { CHECK( post(aliased, body).response.status == 200, "the recognizer's /v1/models id is served"); CHECK(post(aliased, chat_body()).response.status == 200, "the configured name also is"); + b.model_names = {"asr-short-name"}; + chat::Api renamed(limits(), b); + for (const char* name : {"asr-model-id", ".asr-model-id", "asr-short-name"}) { + body = chat_body(); + body.replace(body.find(kModel), kModel.size(), name); + CHECK(post(renamed, body).response.status == 200, name); + } + body = chat_body(); + body.replace(body.find(kModel), kModel.size(), "asr-other"); + CHECK(post(renamed, body).response.status == 404, "an unknown name"); } EXPECT_ERROR( post(api, chat_body("", with_text("Transcribe <|audio|> now."))), 400, "invalid_request", From 47ced7aeafd8da7bdc206dbe5375f9c8d09c4c5c Mon Sep 17 00:00:00 2001 From: Prabhsimran Singh Date: Fri, 20 Nov 2026 17:52:35 +0530 Subject: [PATCH 10/10] release: bump version to 0.3.1 Signed-off-by: Prabhsimran Singh --- VERSION | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/VERSION b/VERSION index 95f41e3..932e409 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -NEMO_SPEECH_VERSION: 0.3.0 +NEMO_SPEECH_VERSION: 0.3.1