Skip to content

Get up and running with Kimi, GLM, MiniMax, DeepSeek, gpt-oss, Qwen, Gemma and other models.

New model... (#19030)

Daniel Hiltgen00bef57a9f5b
diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml
index 7404905a5..460f211c7 100644
--- a/.github/workflows/test.yaml
+++ b/.github/workflows/test.yaml
@@ -216,7 +216,7 @@ jobs:
- preset: Vulkan
install: https://sdk.lunarg.com/sdk/download/1.4.321.1/windows/vulkansdk-windows-X64-1.4.321.1.exe
superbuild_target: ollama-llama-server-vulkan
- superbuild_dir: build\local-superbuild-vulkan
+ superbuild_dir: build\vk
superbuild_args: '-DOLLAMA_LLAMA_BACKENDS=vulkan'
expected_payload: lib\ollama\vulkan\ggml-vulkan.dll
- preset: 'MLX CUDA 13'
diff --git a/create/create.go b/create/create.go
index 7cf2efc2f..fa7e1cae0 100644
--- a/create/create.go
+++ b/create/create.go
@@ -449,6 +449,7 @@ var tensorImportTransformRegistry = map[string]tensorImportTransformFactory{
"gemma4_unified_assistant": newGemma4ImportTransform,
"NemotronH_Nano_VL_V2": newNemotronHImportTransform,
"NemotronH_Nano_Omni_Reasoning_V3": newNemotronHImportTransform,
+ "NemotronH_Omni_Reasoning_V3": newNemotronHImportTransform,
"NemotronHForCausalLM": newNemotronHImportTransform,
"EmbeddingGemma2Model": newGemma4EmbeddingImportTransform,
}
@@ -469,6 +470,24 @@ func buildSourceFP8Reader(weightTD, scaleTD *safetensors.TensorData) io.Reader {
}
func validateScalarFloat32TensorData(td *safetensors.TensorData, name string) (*safetensors.TensorData, error) {
+ validated, err := validateFloat32TensorData(td, name)
+ if err != nil || validated == nil {
+ if err != nil && td != nil && strings.EqualFold(td.Dtype, "F32") {
+ return nil, fmt.Errorf("expected scalar F32 tensor, got shape %v", td.Shape)
+ }
+ return validated, err
+ }
+ n := int64(1)
+ for _, dim := range validated.Shape {
+ n *= int64(dim)
+ }
+ if n != 1 {
+ return nil, fmt.Errorf("expected scalar F32 tensor, got shape %v", validated.Shape)
+ }
+ return validated, nil
+}
+
+func validateFloat32TensorData(td *safetensors.TensorData, name string) (*safetensors.TensorData, error) {
if td == nil {
return nil, nil
}
@@ -478,35 +497,36 @@ func validateScalarFloat32TensorData(td *safetensors.TensorData, name string) (*
n := int64(1)
for _, dim := range td.Shape {
if dim <= 0 || n > math.MaxInt64/int64(dim) {
- return nil, fmt.Errorf("expected scalar F32 tensor, got shape %v", td.Shape)
+ return nil, fmt.Errorf("expected non-empty F32 tensor, got shape %v", td.Shape)
}
n *= int64(dim)
}
- if n != 1 || td.Size != 4 {
- return nil, fmt.Errorf("expected scalar F32 tensor, got shape %v", td.Shape)
+ if n > math.MaxInt64/4 || td.Size != n*4 {
+ return nil, fmt.Errorf("expected non-empty F32 tensor, got shape %v", td.Shape)
}
return td.WithName(name), nil
}
-func invertScalarFloat32TensorData(td *safetensors.TensorData, name string) (*safetensors.TensorData, error) {
- td, err := validateScalarFloat32TensorData(td, name)
- if err != nil {
- return nil, err
+func invertFloat32TensorData(td *safetensors.TensorData, name string) (*safetensors.TensorData, error) {
+ td, err := validateFloat32TensorData(td, name)
+ if err != nil || td == nil {
+ return td, err
}
raw, err := io.ReadAll(td.Reader())
if err != nil {
return nil, err
}
- if len(raw)%4 != 0 {
- return nil, fmt.Errorf("invalid F32 tensor byte length %d", len(raw))
+ if int64(len(raw)) != td.Size {
+ return nil, fmt.Errorf("invalid F32 tensor byte length %d, expected %d", len(raw), td.Size)
}
out := make([]byte, len(raw))
for i := 0; i < len(raw); i += 4 {
v := math.Float32frombits(binary.LittleEndian.Uint32(raw[i : i+4]))
- if v == 0 {
- return nil, fmt.Errorf("cannot invert zero F32 scale")
+ inverse := 1 / v
+ if !(v > 0) || math.IsInf(float64(v), 0) || math.IsInf(float64(inverse), 0) {
+ return nil, fmt.Errorf("cannot invert F32 scale %v: expected a finite positive scale with a finite reciprocal", v)
}
- binary.LittleEndian.PutUint32(out[i:i+4], math.Float32bits(1/v))
+ binary.LittleEndian.PutUint32(out[i:i+4], math.Float32bits(inverse))
}
return safetensors.NewTensorDataFromBytes(name, td.Dtype, td.Shape, out), nil
}
diff --git a/create/create_test.go b/create/create_test.go
index 993b812a9..950da64d9 100644
--- a/create/create_test.go
+++ b/create/create_test.go
@@ -63,12 +63,21 @@ func TestValidateScalarFloat32TensorDataRejectsShapeOverflow(t *testing.T) {
}
}
-func TestInvertScalarFloat32TensorDataRejectsNonF32(t *testing.T) {
+func TestInvertFloat32TensorDataRejectsNonF32(t *testing.T) {
td := st.NewTensorDataFromBytes("linear.weight_global_scale", "BF16", []int32{}, []byte{0, 0})
- _, err := invertScalarFloat32TensorData(td, "linear.weight.global_scale")
+ _, err := invertFloat32TensorData(td, "linear.weight.global_scale")
if err == nil || !strings.Contains(err.Error(), "expected F32 tensor") {
- t.Fatalf("invertScalarFloat32TensorData error = %v, want dtype failure", err)
+ t.Fatalf("invertFloat32TensorData error = %v, want dtype failure", err)
+ }
+}
+
+func TestInvertFloat32TensorDataRejectsInvalidScales(t *testing.T) {
+ for _, value := range []float32{0, -1, float32(math.NaN()), float32(math.Inf(1)), math.SmallestNonzeroFloat32} {
+ td := st.NewTensorDataFromBytes("experts.weight_global_scale", "F32", []int32{2}, encodeFloat32s(2, value))
+ if _, err := invertFloat32TensorData(td, "experts.weight.global_scale"); err == nil {
+ t.Errorf("inverting scale bank [2, %v] succeeded, want invalid-scale error", value)
+ }
}
}
diff --git a/create/metadata.go b/create/metadata.go
index e8729e4c9..acf2ff7c9 100644
--- a/create/metadata.go
+++ b/create/metadata.go
@@ -195,7 +195,11 @@ func lagunaRendererParserNameFromTemplate(modelDir, chatTemplate string) (string
return "laguna", nil
}
-func nemotronRendererParserNameFromTemplate(modelDir, chatTemplate string) (string, error) {
+// Nemotron 3.5 replaces inline /think toggles with request-controlled thinking
+// and adds a reasoning-effort marker. The architecture names do not distinguish
+// these prompt formats, but both use the same thinking/tool-call output syntax
+// and therefore the nemotron-3-nano parser.
+func nemotronRendererNameFromTemplate(modelDir, chatTemplate string) (string, error) {
const v35Marker = "{reasoning effort: efficient}"
chatTemplatePath := filepath.Join(modelDir, "chat_template.jinja")
@@ -250,7 +254,7 @@ func parserNameForIdentifier(modelDir, s, chatTemplate string) (string, error) {
case strings.Contains(s, "qwen3"):
return "qwen3", nil
case strings.Contains(s, "nemotronh") || strings.Contains(s, "nemotron_h"):
- return nemotronRendererParserNameFromTemplate(modelDir, chatTemplate)
+ return "nemotron-3-nano", nil
default:
return "", nil
}
@@ -293,8 +297,10 @@ func rendererNameForIdentifier(modelDir, s, chatTemplate string) (string, error)
return qwen35RendererNameFromTemplate(chatTemplate), nil
case strings.Contains(s, "qwen3"):
return "qwen3-coder", nil
+ case s == "nemotronh_omni_reasoning_v3":
+ return "nemotron-3.5-super", nil
case strings.Contains(s, "nemotronh") || strings.Contains(s, "nemotron_h"):
- return nemotronRendererParserNameFromTemplate(modelDir, chatTemplate)
+ return nemotronRendererNameFromTemplate(modelDir, chatTemplate)
default:
return "", nil
}
diff --git a/create/metadata_test.go b/create/metadata_test.go
index a93c3e12b..36f90cf88 100644
--- a/create/metadata_test.go
+++ b/create/metadata_test.go
@@ -182,7 +182,7 @@ func TestInferSafetensorsConfigFamilies(t *testing.T) {
config: `{"architectures":["NemotronHForCausalLM"],"model_type":"nemotron_h"}`,
chatTemplate: "{reasoning effort: efficient}",
standalone: true,
- wantParser: "nemotron-3.5-nano",
+ wantParser: "nemotron-3-nano",
wantRenderer: "nemotron-3.5-nano",
},
{
@@ -192,6 +192,13 @@ func TestInferSafetensorsConfigFamilies(t *testing.T) {
wantRenderer: "nemotron-3-nano",
wantCaps: []string{"completion", "vision", "audio", "tools", "thinking"},
},
+ {
+ name: "nemotron super published architecture",
+ config: `{"architectures":["NemotronH_Omni_Reasoning_V3"],"model_type":"nemotron_h_omni","vision_config":{},"sound_config":null,"llm_config":{"model_type":"nemotron_h"}}`,
+ wantParser: "nemotron-3-nano",
+ wantRenderer: "nemotron-3.5-super",
+ wantCaps: []string{"completion", "vision", "tools", "thinking"},
+ },
{
name: "deepseek",
config: `{"architectures":["DeepseekV3ForCausalLM"]}`,
diff --git a/create/nemotron_h.go b/create/nemotron_h.go
index 0fc60edcf..a9d9f6ed2 100644
--- a/create/nemotron_h.go
+++ b/create/nemotron_h.go
@@ -12,9 +12,11 @@ type nemotronHImportTransform struct {
func newNemotronHImportTransform(rawConfig json.RawMessage) (quantizePolicy, error) {
var cfg struct {
- NumHiddenLayers int `json:"num_hidden_layers"`
+ NumHiddenLayers int `json:"num_hidden_layers"`
+ LayersBlockType []string `json:"layers_block_type"`
LLMConfig struct {
- NumHiddenLayers int `json:"num_hidden_layers"`
+ NumHiddenLayers int `json:"num_hidden_layers"`
+ LayersBlockType []string `json:"layers_block_type"`
} `json:"llm_config"`
}
if err := json.Unmarshal(rawConfig, &cfg); err != nil {
@@ -24,12 +26,19 @@ func newNemotronHImportTransform(rawConfig json.RawMessage) (quantizePolicy, err
if numLayers == 0 {
numLayers = cfg.LLMConfig.NumHiddenLayers
}
+ if numLayers == 0 {
+ numLayers = len(cfg.LayersBlockType)
+ }
+ if numLayers == 0 {
+ numLayers = len(cfg.LLMConfig.LayersBlockType)
+ }
return nemotronHImportTransform{numLayers: numLayers}, nil
}
// Nemotron's modality tower names do not match the shared predicates.
func nemotronHIsVisionTower(name string) bool {
return strings.HasPrefix(name, "vision_model.") ||
+ strings.HasPrefix(name, "vision_projector.") ||
strings.HasPrefix(name, "mlp1.")
}
@@ -44,6 +53,8 @@ func nemotronHShouldKeepBF16ForDirectNonAffine(name string) bool {
return true
case strings.HasSuffix(name, ".mixer.conv1d.weight"):
return true
+ case strings.HasSuffix(name, ".mixer.fc1_latent_proj.weight"), strings.HasSuffix(name, ".mixer.fc2_latent_proj.weight"):
+ return true
default:
return false
}
@@ -64,6 +75,12 @@ func (t nemotronHImportTransform) promoteSensitive(name string) bool {
if nemotronHIsAttentionProjection(name) {
return true
}
+ // The detached MTP module is a one-layer assistant, not layer zero of the
+ // target stack. Do not apply the target's early/late promotion schedule to
+ // its expert projections.
+ if strings.HasPrefix(name, "mtp.") || strings.HasPrefix(name, "language_model.mtp.") {
+ return false
+ }
layerIdx := layerIndex(name)
return layerIdx < 0 || useMoreBits(layerIdx, t.numLayers)
}
diff --git a/create/nemotron_h_test.go b/create/nemotron_h_test.go
index bebd68feb..58a91ace8 100644
--- a/create/nemotron_h_test.go
+++ b/create/nemotron_h_test.go
@@ -7,21 +7,55 @@ import (
)
func TestNemotronHImportTransformRegistration(t *testing.T) {
- inv := Inventory{
- Config: sourceModelConfig{Architectures: []string{"NemotronH_Nano_Omni_Reasoning_V3"}},
- RawConfig: json.RawMessage(`{"architectures":["NemotronH_Nano_Omni_Reasoning_V3"],"llm_config":{"num_hidden_layers":52}}`),
- }
+ for _, tt := range []struct {
+ name string
+ rawConfig string
+ want int
+ }{
+ {"nested layer count", `{"architectures":["NemotronH_Nano_Omni_Reasoning_V3"],"llm_config":{"num_hidden_layers":52}}`, 52},
+ {"layer block types", `{"architectures":["NemotronHForCausalLM"],"layers_block_type":["linear_attention","moe","linear_attention"]}`, 3},
+ {"published super config", `{"architectures":["NemotronH_Omni_Reasoning_V3"],"llm_config":{"layers_block_type":["mamba","moe","attention"]}}`, 3},
+ } {
+ t.Run(tt.name, func(t *testing.T) {
+ inv := Inventory{
+ RawConfig: json.RawMessage(tt.rawConfig),
+ }
+ if err := json.Unmarshal(inv.RawConfig, &inv.Config); err != nil {
+ t.Fatal(err)
+ }
- policy, err := newTensorImportTransform(inv)
- if err != nil {
- t.Fatalf("newTensorImportTransform() error = %v", err)
- }
- transform, ok := policy.(nemotronHImportTransform)
- if !ok {
- t.Fatalf("newTensorImportTransform() = %T, want nemotronHImportTransform", policy)
+ policy, err := newTensorImportTransform(inv)
+ if err != nil {
+ t.Fatalf("newTensorImportTransform() error = %v", err)
+ }
+ transform, ok := policy.(nemotronHImportTransform)
+ if !ok {
+ t.Fatalf("newTensorImportTransform() = %T, want nemotronHImportTransform", policy)
+ }
+ if transform.numLayers != tt.want {
+ t.Fatalf("numLayers = %d, want %d", transform.numLayers, tt.want)
+ }
+ })
}
- if transform.numLayers != 52 {
- t.Fatalf("numLayers = %d, want 52", transform.numLayers)
+}
+
+func TestNemotronHImportTransformDoesNotApplyTargetLayerScheduleToMTP(t *testing.T) {
+ policy := nemotronHImportTransform{numLayers: 52}
+ shape := []int32{128, 128}
+
+ for _, tt := range []struct {
+ name string
+ want string
+ }{
+ {"language_model.backbone.layers.0.mixer.experts.down_proj.weight", "mxfp8"},
+ {"mtp.layers.0.mixer.experts.down_proj.weight", "nvfp4"},
+ {"mtp.layers.0.mixer.q_proj.weight", "mxfp8"},
+ {"language_model.mtp.layers.1.mixer.experts.down_proj.weight", "nvfp4"},
+ {"language_model.mtp.layers.0.mixer.q_proj.weight", "mxfp8"},
+ } {
+ if got := policy.quantizationType(tt.name, shape, "nvfp4"); got != tt.want {
+ t.Errorf("quantizationType(%q) = %q, want %q", tt.name, got, tt.want)
+ }
}
}
@@ -93,6 +127,9 @@ func TestNemotronHImportTransformQuantizationPolicy(t *testing.T) {
{"middle dense down_proj stays nvfp4", "language_model.backbone.layers.16.mixer.down_proj.weight", []int32{32, 32}, "nvfp4", "nvfp4"},
{"router gate kept bf16", "language_model.backbone.layers.2.mixer.gate.weight", []int32{8, 32}, "nvfp4", ""},
{"conv kept bf16", "language_model.backbone.layers.0.mixer.conv1d.weight", []int32{96, 32}, "nvfp4", ""},
+ {"latent input kept bf16", "language_model.backbone.layers.1.mixer.fc1_latent_proj.weight", []int32{1024, 4096}, "nvfp4", ""},
+ {"latent output kept bf16", "language_model.backbone.layers.1.mixer.fc2_latent_proj.weight", []int32{4096, 1024}, "mxfp8", ""},
+ {"draft latent input kept bf16", "language_model.mtp.layers.1.mixer.fc1_latent_proj.weight", []int32{1024, 4096}, "int4", ""},
{"embedding promoted to mxfp8", "language_model.backbone.embeddings.weight", []int32{4096, 32}, "mxfp8", "mxfp8"},
{"embedding promoted to mxfp8 from nvfp4", "language_model.backbone.embeddings.weight", []int32{4096, 32}, "nvfp4", "mxfp8"},
{"embedding promoted to int8 from int4", "language_model.backbone.embeddings.weight", []int32{4096, 64}, "int4", "int8"},
@@ -104,6 +141,7 @@ func TestNemotronHImportTransformQuantizationPolicy(t *testing.T) {
{"lm head unaligned kept bf16", "language_model.lm_head.weight", []int32{4096, 31}, "nvfp4", ""},
{"vision kept bf16", "vision_model.radio_model.model.patch_generator.proj.weight", []int32{32, 32}, "nvfp4", ""},
{"vision projector kept bf16", "mlp1.0.weight", []int32{32, 32}, "nvfp4", ""},
+ {"vision final norm kept bf16", "vision_projector.vision_final_layernorm.weight", []int32{1280}, "nvfp4", ""},
{"sound encoder kept bf16", "sound_encoder.encoder.layers.0.self_attn.q_proj.weight", []int32{32, 32}, "nvfp4", ""},
{"sound projector kept bf16", "sound_projection.adapter.weight", []int32{32, 32}, "nvfp4", ""},
}
diff --git a/create/plan.go b/create/plan.go
index f9a024669..7d4e6fbb6 100644
--- a/create/plan.go
+++ b/create/plan.go
@@ -28,8 +28,11 @@ const (
// it through (a global scale stored as-is).
TransformScalarF32 Transform = "scalar_f32"
- // TransformReciprocalF32 validates a scalar F32 and stores its reciprocal
- // (a global scale the producer stored inverted).
+ // TransformF32 preserves an F32 vector scale bank with one value per expert.
+ TransformF32 Transform = "f32"
+
+ // TransformReciprocalF32 validates an F32 scale tensor and stores each
+ // element's reciprocal (global scales the producer stored inverted).
TransformReciprocalF32 Transform = "reciprocal_f32"
// TransformStackExperts concatenates N per-expert source tensors (in
diff --git a/create/prequant.go b/create/prequant.go
index ec782c081..25146e259 100644
--- a/create/prequant.go
+++ b/create/prequant.go
@@ -25,9 +25,9 @@ type prequantPattern struct {
biasSuffix string // optional bias / zero-point companion ("" if none)
globalSuffix string // optional global-scale companion ("" if none)
- globalReciprocal bool // store the global scale as its reciprocal
+ globalReciprocal bool // producer stores the weight global scale inverted
- ignoreSuffixes []string // companions consumed but not written (e.g. activation scales)
+ ignoreSuffixes []string // activation scales unused by weight-only inference
forceQuantType string // override the blob's quant_type metadata
defaultGroupSize string // set group_size metadata only when the config did not
@@ -147,7 +147,8 @@ func matchPrequant(name string, inv Inventory) (BlobSpec, []string, bool) {
if p.globalSuffix != "" {
if gSrc := base + p.globalSuffix; inv.Has(gSrc) {
- global := TensorSpec{Name: outWeight + ".global_scale", Sources: []SourceTensor{inv.Tensors[gSrc]}, Transform: TransformScalarF32}
+ globalSource := inv.Tensors[gSrc]
+ global := TensorSpec{Name: outWeight + ".global_scale", Sources: []SourceTensor{globalSource}, Transform: f32ScaleTransform(globalSource)}
if p.globalReciprocal {
global.Transform = TransformReciprocalF32
}
@@ -156,9 +157,9 @@ func matchPrequant(name string, inv Inventory) (BlobSpec, []string, bool) {
}
}
- for _, suf := range p.ignoreSuffixes {
- if s := base + suf; inv.Has(s) {
- consumed = append(consumed, s)
+ for _, suffix := range p.ignoreSuffixes {
+ if source := base + suffix; inv.Has(source) {
+ consumed = append(consumed, source)
}
}
@@ -167,6 +168,15 @@ func matchPrequant(name string, inv Inventory) (BlobSpec, []string, bool) {
return BlobSpec{}, nil, false
}
+func f32ScaleTransform(t SourceTensor) Transform {
+ for _, dim := range t.Shape {
+ if dim != 1 {
+ return TransformF32
+ }
+ }
+ return TransformScalarF32
+}
+
// prequantMetadata builds the fused blob's metadata: the source config's quant
// metadata, with the pattern's quant_type override and group_size default
// applied. Returns nil when there is nothing to record.
diff --git a/create/prequant_test.go b/create/prequant_test.go
index 15f352b41..50051a8a8 100644
--- a/create/prequant_test.go
+++ b/create/prequant_test.go
@@ -84,6 +84,9 @@ func TestPlanPrequantizedModelOptNVFP4(t *testing.T) {
"l.weight_scale": "F8_E4M3",
"l.weight_scale_2": "F32",
})
+ global := inv.Tensors["l.weight_scale_2"]
+ global.Shape = nil
+ inv.Tensors[global.Name] = global
specs, err := Plan(inv, Classification{Kind: SourcePrequantized}, defaultQuantPolicy{})
if err != nil {
@@ -117,52 +120,26 @@ func TestPlanPrequantizedModelOptNVFP4(t *testing.T) {
}
}
-func TestPlanPrequantizedModelOptDropsActivationScale(t *testing.T) {
- // ModelOpt ships per-weight activation scales (.input_scale and, in some
- // variants, .input_global_scale) that are unused for weight-only
- // inference. They must be consumed, not emitted as their own blobs.
- inv := newInventory(sourceModelConfig{}, map[string]string{
- "l.weight": "U8",
- "l.weight_scale": "F8_E4M3",
- "l.weight_scale_2": "F32",
- "l.input_scale": "F32",
- "l.input_global_scale": "F32",
- })
-
- specs, err := Plan(inv, Classification{Kind: SourcePrequantized}, defaultQuantPolicy{})
- if err != nil {
- t.Fatalf("Plan() error = %v", err)
- }
- if len(specs) != 1 {
- t.Fatalf("got %d specs %v, want 1 (activation scales must not become blobs)", len(specs), specNames(specs))
- }
- w := specs[0]
- for _, act := range []string{"l.input_scale", "l.input_global_scale"} {
- if _, leaked := inputByOutput(w, act); leaked {
- t.Errorf("activation scale %s leaked into the fused blob", act)
- }
- for _, s := range specs {
- if s.Name == act {
- t.Errorf("activation scale %s emitted as its own blob", act)
- }
- }
- }
-}
-
func TestPlanPrequantizedCompressedNVFP4(t *testing.T) {
inv := newInventory(sourceModelConfig{}, map[string]string{
"l.weight_packed": "U8",
"l.weight_scale": "F8_E4M3",
"l.weight_global_scale": "F32",
"l.input_global_scale": "F32",
+ "l.input_scale": "F32",
})
+ for _, name := range []string{"l.weight_global_scale", "l.input_global_scale", "l.input_scale"} {
+ scale := inv.Tensors[name]
+ scale.Shape = nil
+ inv.Tensors[name] = scale
+ }
specs, err := Plan(inv, Classification{Kind: SourcePrequantized}, defaultQuantPolicy{})
if err != nil {
t.Fatalf("Plan() error = %v", err)
}
if len(specs) != 1 {
- t.Fatalf("got %d specs %v, want 1 (input_global_scale must be consumed)", len(specs), specNames(specs))
+ t.Fatalf("got %d specs %v, want 1", len(specs), specNames(specs))
}
w := specs[0]
if w.Name != "l.weight" {
@@ -177,7 +154,62 @@ func TestPlanPrequantizedCompressedNVFP4(t *testing.T) {
if !ok || globalIn.Transform != TransformReciprocalF32 {
t.Errorf("global_scale input = %+v ok=%v, want reciprocal_f32", globalIn, ok)
}
+ if len(w.Tensors) != 3 {
+ t.Errorf("fused tensors = %v, want only weight, block scale and global scale", w.Tensors)
+ }
if w.Metadata["quant_type"] != "nvfp4" || w.Metadata["group_size"] != "16" {
t.Errorf("metadata = %v, want quant_type=nvfp4 group_size=16", w.Metadata)
}
}
+
+func TestPlanPrequantizedModelOptRetainsExpertScaleBanks(t *testing.T) {
+ inv := newInventory(sourceModelConfig{}, map[string]string{
+ "l.weight": "U32",
+ "l.weight_scale": "U8",
+ "l.weight_scale_2": "F32",
+ "l.input_scale": "F32",
+ })
+ for _, name := range []string{"l.weight_scale_2", "l.input_scale"} {
+ scale := inv.Tensors[name]
+ scale.Shape = []int32{128}
+ inv.Tensors[name] = scale
+ }
+
+ specs, err := Plan(inv, Classification{Kind: SourcePrequantized}, defaultQuantPolicy{})
+ if err != nil {
+ t.Fatalf("Plan() error = %v", err)
+ }
+ w, ok := specByName(specs, "l.weight")
+ if !ok {
+ t.Fatal("missing l.weight blob")
+ }
+ scale, ok := inputByOutput(w, "l.weight.global_scale")
+ if !ok || scale.Transform != TransformF32 || !slices.Equal(scale.Sources[0].Shape, []int32{128}) {
+ t.Errorf("global scale = %+v ok=%v, want F32 expert scale bank", scale, ok)
+ }
+ if len(specs) != 1 || len(w.Tensors) != 3 {
+ t.Errorf("specs = %v, want only fused weight, block scale and global scale", specs)
+ }
+}
+
+func TestPlanPrequantizedRetainsKVCacheScales(t *testing.T) {
+ inv := newInventory(sourceModelConfig{}, map[string]string{
+ "l.k_proj.weight": "U8",
+ "l.k_proj.weight_scale": "F8_E4M3",
+ "l.k_proj.k_scale": "F32",
+ "l.v_proj.weight": "U8",
+ "l.v_proj.weight_scale": "F8_E4M3",
+ "l.v_proj.v_scale": "F32",
+ })
+
+ specs, err := Plan(inv, Classification{Kind: SourcePrequantized}, defaultQuantPolicy{})
+ if err != nil {
+ t.Fatalf("Plan() error = %v", err)
+ }
+ for _, name := range []string{"l.k_proj.k_scale", "l.v_proj.v_scale"} {
+ spec, ok := specByName(specs, name)
+ if !ok || len(spec.Tensors) != 1 || sourceName(spec.Tensors[0]) != name {
+ t.Errorf("%s = %+v ok=%v, want unchanged standalone tensor", name, spec, ok)
+ }
+ }
+}
diff --git a/create/transform.go b/create/transform.go
index 99847011f..9eb30fa49 100644
--- a/create/transform.go
+++ b/create/transform.go
@@ -40,11 +40,17 @@ func applyByteTransform(ts TensorSpec, sources []*safetensors.TensorData) (*safe
}
return validateScalarFloat32TensorData(sources[0], ts.Name)
+ case TransformF32:
+ if len(sources) != 1 {
+ return nil, fmt.Errorf("transform f32 expects 1 source, got %d", len(sources))
+ }
+ return validateFloat32TensorData(sources[0], ts.Name)
+
case TransformReciprocalF32:
if len(sources) != 1 {
return nil, fmt.Errorf("transform reciprocal_f32 expects 1 source, got %d", len(sources))
}
- return invertScalarFloat32TensorData(sources[0], ts.Name)
+ return invertFloat32TensorData(sources[0], ts.Name)
case TransformStackExperts:
return stackExpertTensors(ts.Name, ts.OutDtype, ts.OutShape, sources)
diff --git a/create/writer_test.go b/create/writer_test.go
index 5b82b7ab9..bd1f86b56 100644
--- a/create/writer_test.go
+++ b/create/writer_test.go
@@ -1,6 +1,7 @@
package create
import (
+ "bytes"
"context"
"encoding/binary"
"encoding/json"
@@ -97,6 +98,8 @@ func TestWriteBlobsCompressedNVFP4(t *testing.T) {
st.NewTensorDataFromBytes("linear.weight_packed", "U8", []int32{16, 8}, make([]byte, 16*8)),
st.NewTensorDataFromBytes("linear.weight_scale", "F8_E4M3", []int32{16, 1}, make([]byte, 16)),
st.NewTensorDataFromBytes("linear.weight_global_scale", "F32", []int32{}, f32le(4.0)),
+ st.NewTensorDataFromBytes("linear.input_global_scale", "F32", []int32{}, f32le(8.0)),
+ st.NewTensorDataFromBytes("linear.input_scale", "F32", []int32{}, f32le(2.0)),
st.NewTensorDataFromBytes("norm.weight", "BF16", []int32{16}, make([]byte, 32)),
})
@@ -134,6 +137,12 @@ func TestWriteBlobsCompressedNVFP4(t *testing.T) {
if got := math.Float32frombits(binary.LittleEndian.Uint32(gs)); got != 0.25 {
t.Errorf("global_scale = %v, want 0.25 (reciprocal of 4.0)", got)
}
+ if len(hdr) != 3 {
+ t.Errorf("fused tensors = %v, want only weight, block scale and global scale", hdr)
+ }
+ if got := store.names(); !slices.Equal(got, []string{"linear.weight", "norm.weight"}) {
+ t.Errorf("blob names = %v, want only fused weight and norm", got)
+ }
// the scale companion is folded in, not its own blob.
if _, leaked := store.blobs["linear.weight_scale"]; leaked {
@@ -150,6 +159,96 @@ func TestWriteBlobsCompressedNVFP4(t *testing.T) {
}
}
+func TestWriteBlobsModelOptSkipsActivationScale(t *testing.T) {
+ dir := t.TempDir()
+ writeConfigJSON(t, dir, `{"architectures":["TestModel"]}`)
+ createTestSafetensors(t, filepath.Join(dir, "model.safetensors"), []*st.TensorData{
+ st.NewTensorDataFromBytes("linear.weight", "U8", []int32{16, 8}, make([]byte, 16*8)),
+ st.NewTensorDataFromBytes("linear.weight_scale", "F8_E4M3", []int32{16, 1}, make([]byte, 16)),
+ st.NewTensorDataFromBytes("linear.weight_scale_2", "F32", []int32{}, f32le(4.0)),
+ st.NewTensorDataFromBytes("linear.input_scale", "BF16", []int32{}, make([]byte, 2)),
+ st.NewTensorDataFromBytes("attention.k_scale", "F32", []int32{}, f32le(0.25)),
+ st.NewTensorDataFromBytes("attention.v_scale", "F32", []int32{}, f32le(0.5)),
+ })
+
+ inv, err := ReadInventory(dir)
+ if err != nil {
+ t.Fatalf("ReadInventory() error = %v", err)
+ }
+ specs, err := Plan(inv, Classification{Kind: SourcePrequantized}, defaultQuantPolicy{})
+ if err != nil {
+ t.Fatalf("Plan() error = %v", err)
+ }
+ store := newCaptureStore()
+ if _, err := WriteBlobs(context.Background(), specs, dir, store); err != nil {
+ t.Fatalf("WriteBlobs() error = %v", err)
+ }
+
+ fused := store.blobs["linear.weight"]
+ hdr := blobHeader(t, fused)
+ if len(hdr) != 3 {
+ t.Errorf("fused tensors = %v, want only weight, block scale and global scale", hdr)
+ }
+ if _, ok := store.blobs["linear.input_scale"]; ok {
+ t.Error("unused activation scale should not be emitted")
+ }
+ for name, want := range map[string]float32{
+ "attention.k_scale": 0.25,
+ "attention.v_scale": 0.5,
+ } {
+ raw := readPackedTensorRaw(t, store.blobs[name], name)
+ if got := math.Float32frombits(binary.LittleEndian.Uint32(raw)); got != want {
+ t.Errorf("%s = %v, want %v (stored as-is)", name, got, want)
+ }
+ }
+}
+
+func TestWriteBlobsNVFP4ExpertScaleBanks(t *testing.T) {
+ for _, tc := range []struct {
+ name, weight, global, input string
+ wantGlobal []float32
+ }{
+ {"modelopt", ".weight", ".weight_scale_2", ".input_scale", []float32{2, 4}},
+ {"compressed-tensors", ".weight_packed", ".weight_global_scale", ".input_global_scale", []float32{0.5, 0.25}},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ dir := t.TempDir()
+ writeConfigJSON(t, dir, `{"architectures":["TestModel"]}`)
+ createTestSafetensors(t, filepath.Join(dir, "model.safetensors"), []*st.TensorData{
+ st.NewTensorDataFromBytes("experts"+tc.weight, "U32", []int32{2, 16, 2}, make([]byte, 2*16*2*4)),
+ st.NewTensorDataFromBytes("experts.weight_scale", "U8", []int32{2, 16, 1}, make([]byte, 2*16)),
+ st.NewTensorDataFromBytes("experts"+tc.global, "F32", []int32{2}, append(f32le(2.0), f32le(4.0)...)),
+ st.NewTensorDataFromBytes("experts"+tc.input, "F32", []int32{2}, append(f32le(8.0), f32le(16.0)...)),
+ })
+
+ inv, err := ReadInventory(dir)
+ if err != nil {
+ t.Fatalf("ReadInventory() error = %v", err)
+ }
+ specs, err := Plan(inv, Classification{Kind: SourcePrequantized}, defaultQuantPolicy{})
+ if err != nil {
+ t.Fatalf("Plan() error = %v", err)
+ }
+ store := newCaptureStore()
+ if _, err := WriteBlobs(context.Background(), specs, dir, store); err != nil {
+ t.Fatalf("WriteBlobs() error = %v", err)
+ }
+
+ hdr := blobHeader(t, store.blobs["experts.weight"])
+ name := "experts.weight.global_scale"
+ if scale, ok := hdr[name]; !ok || scale.Dtype != "F32" || !slices.Equal(scale.Shape, []int32{2}) {
+ t.Errorf("%s = %+v ok=%v, want F32 [2]", name, scale, ok)
+ }
+ if got, want := readPackedTensorRaw(t, store.blobs["experts.weight"], name), encodeFloat32s(tc.wantGlobal...); !bytes.Equal(got, want) {
+ t.Errorf("%s bytes = %v, want %v", name, got, want)
+ }
+ if len(hdr) != 3 || len(store.blobs) != 1 {
+ t.Errorf("tensors = %v, blobs = %v, want only fused weight, block scale and global scale", hdr, store.names())
+ }
+ })
+ }
+}
+
func TestWriteBlobsQuantizeFloat(t *testing.T) {
mlxtest.SkipIfUnavailable(t)
for _, quantize := range []string{"int4", "nvfp4", "mxfp8"} {
diff --git a/mlx/mamba2_scan.go b/mlx/mamba2_scan.go
index c5b387d57..ea4b4f5dc 100644
--- a/mlx/mamba2_scan.go
+++ b/mlx/mamba2_scan.go
@@ -67,7 +67,8 @@ for (int i = 0; i < n_per_t; ++i) {
for (int t = 0; t < T; ++t) {
auto bth = (b_idx * T + t) * H + h_idx;
float dt_raw = static_cast<float>(dt[bth]) + static_cast<float>(dt_bias[h_idx]);
- float dt_val = log(1.0f + exp(dt_raw));
+ // Stable softplus: large trained timesteps must not overflow exp().
+ float dt_val = max(dt_raw, 0.0f) + log1p(exp(-abs(dt_raw)));
float decay = exp(dt_val * static_cast<float>(a[h_idx]));
float x_val = static_cast<float>(hidden[bth * D + d_idx]);
@@ -263,7 +264,7 @@ func mamba2ScanGraph(hidden, bState, cState, dt, state, a, d, dtBias *Array, cap
ct := sliceMambaTime(cState, t)
dtt := Add(sliceMambaTime(dt, t), bias2)
- dtt = Log(AddScalar(Exp(dtt), 1))
+ dtt = Softplus(dtt)
dA := Exp(Mul(Reshape(dtt, B, H, 1, 1), a4))
dB := Mul(Reshape(dtt, B, H, 1), bt)
diff --git a/mlx/mamba_kernels_test.go b/mlx/mamba_kernels_test.go
index 5df9a34ad..17d1a511b 100644
--- a/mlx/mamba_kernels_test.go
+++ b/mlx/mamba_kernels_test.go
@@ -24,6 +24,48 @@ func TestMamba2ScanMatchesReference(t *testing.T) {
})
}
+func TestMamba2ScanSoftplusExtremes(t *testing.T) {
+ for _, size := range []int{31, 32} { // graph fallback and GPU kernel
+ t.Run(fmt.Sprintf("state=%d", size), func(t *testing.T) {
+ withMLXThread(t, func(t *mlxthreadtest.T) {
+ if size == 32 {
+ requireGPUKernel(t)
+ }
+ // With zero decay coefficient and initial state, unit B/C/x and no
+ // skip connection, every state element is softplus(dt + bias).
+ for _, raw := range []float32{-100, -20, 0, 20, 100} {
+ in := mamba2TestInputs{
+ hidden: onesTest(DTypeFloat32, 1, 1, 1, 1),
+ bState: onesTest(DTypeFloat32, 1, 1, 1, size),
+ cState: onesTest(DTypeFloat32, 1, 1, 1, size),
+ dt: FromValues([]float32{raw - 1}, 1, 1, 1),
+ state: Zeros(DTypeFloat32, 1, 1, 1, size),
+ a: Zeros(DTypeFloat32, 1),
+ d: Zeros(DTypeFloat32, 1),
+ dtBias: onesTest(DTypeFloat32, 1),
+ }
+ y, state, _ := Mamba2Scan(in.hidden, in.bState, in.cState, in.dt, in.state, in.a, in.d, in.dtBias, nil, false)
+ Eval(y, state)
+ softplus := math.Max(float64(raw), 0) + math.Log1p(math.Exp(-math.Abs(float64(raw))))
+ for name, output := range map[string]*Array{"output": y, "state": state} {
+ want := softplus
+ if name == "output" {
+ want *= float64(size)
+ }
+ for i, value := range output.Floats() {
+ got := float64(value)
+ if math.IsNaN(got) || math.IsInf(got, 0) || math.Abs(got-want) > max(1e-37, math.Abs(want)*1e-5) {
+ t.Errorf("S=%d dt=%g %s[%d]=%g, want %g", size, raw, name, i, got, want)
+ break
+ }
+ }
+ }
+ }
+ })
+ })
+ }
+}
+
// Every interior state must match, not just one boundary.
func TestMamba2ScanCaptureAllMatchesPerTokenReference(t *testing.T) {
withMLXThread(t, func(t *mlxthreadtest.T) {
@@ -216,7 +258,7 @@ func appendArrayCloseError(failures []error, name string, got, want *Array, tol
return append(failures, fmt.Errorf("%s length = %d, want %d", name, len(gotF), len(wantF)))
}
for i := range gotF {
- if math.Abs(float64(gotF[i]-wantF[i])) > tol {
+ if math.IsNaN(float64(gotF[i])) || math.IsInf(float64(gotF[i]), 0) || math.Abs(float64(gotF[i]-wantF[i])) > tol {
return append(failures, fmt.Errorf("%s[%d] = %v, want %v", name, i, gotF[i], wantF[i]))
}
}
@@ -244,7 +286,7 @@ func mamba2ScanReference(hidden, bState, cState, dt, state, a, d, dtBias *Array)
bt := sliceTimeForTest(bState, t).AsType(DTypeFloat32)
ct := sliceTimeForTest(cState, t).AsType(DTypeFloat32)
dtt := Add(sliceTimeForTest(dt, t).AsType(DTypeFloat32), dtBias)
- dtt = Log(AddScalar(Exp(dtt), 1))
+ dtt = Softplus(dtt)
dA := Exp(Mul(Reshape(dtt, B, H, 1, 1), a))
dB := Mul(Reshape(dtt, B, H, 1), bt)
state = Add(Mul(state, dA), Mul(ExpandDims(xt, -1), ExpandDims(dB, 2)))
diff --git a/mlx/weighted_sum.go b/mlx/weighted_sum.go
new file mode 100644
index 000000000..404490aeb
--- /dev/null
+++ b/mlx/weighted_sum.go
@@ -0,0 +1,83 @@
+package mlx
+
+const (
+ weightedSumValues = iota
+ weightedSumScores
+ weightedSumIndices
+)
+
+const (
+ weightedSumWidth = iota
+ weightedSumExperts
+ weightedSumGather
+)
+
+var gatherWeightedSum = &gpuKernel{
+ name: "gather_weighted_sum",
+ inputs: []string{weightedSumValues: "values", weightedSumScores: "scores", weightedSumIndices: "indices"},
+ outputs: []string{"out"},
+ metal: gpuSource{source: `
+auto col = thread_position_in_grid.x;
+auto row = thread_position_in_grid.y;
+if (col >= D) return;
+float sum = 0;
+for (int k = 0; k < K; ++k) {
+ auto slot = row * K + k;
+ auto source = GATHER ? indices[slot] : slot;
+ sum += float(values[source * D + col]) * scores[slot];
+}
+out[row * D + col] = static_cast<T>(sum);
+`},
+ fallback: func(launch gpuLaunch) []*Array {
+ in := launch.inputs
+ indices := in[weightedSumIndices]
+ if launch.ints[weightedSumGather].value == 0 {
+ indices = nil
+ }
+ return []*Array{gatherWeightedSumGraph(in[weightedSumValues], in[weightedSumScores], indices)}
+ },
+}
+
+func gatherWeightedSumGraph(values, scores, indices *Array) *Array {
+ if indices != nil {
+ values = Take(values, Flatten(indices), 0)
+ }
+ values = Reshape(values, int32(scores.Dim(0)), int32(scores.Dim(1)), int32(values.Dim(1)))
+ return Sum(Mul(values.AsType(DTypeFloat32), ExpandDims(scores, -1)), 1, false).AsType(values.DType())
+}
+
+// GatherWeightedSum reduces K expert rows per token in FP32, then rounds to
+// values' dtype. values is [N*K, D], scores is [N, K], and optional indices
+// maps each token/expert slot to a row in values. Fusing the gather and reduction
+// avoids materializing reordered expert outputs and their FP32 weighted product.
+func GatherWeightedSum(values, scores, indices *Array) *Array {
+ if values.NumDims() != 2 || scores.NumDims() != 2 || values.Dim(0) != scores.Size() {
+ panic("mlx: GatherWeightedSum requires values [N*K, D] and scores [N, K]")
+ }
+ if indices != nil && indices.Size() != scores.Size() {
+ panic("mlx: GatherWeightedSum indices must have N*K entries")
+ }
+ scores = scores.AsType(DTypeFloat32)
+ if values.DType() != DTypeFloat32 && values.DType() != DTypeBFloat16 && values.DType() != DTypeFloat16 {
+ return gatherWeightedSumGraph(values, scores, indices)
+ }
+ N, K, D := scores.Dim(0), scores.Dim(1), values.Dim(1)
+ if N == 0 || K == 0 || D == 0 {
+ return gatherWeightedSumGraph(values, scores, indices)
+ }
+ gather := 0
+ if indices == nil {
+ indices = FromValues([]int32{0}, 1)
+ } else {
+ indices = indices.AsType(DTypeInt32)
+ gather = 1
+ }
+ return gatherWeightedSum.run(gpuLaunch{
+ dtypes: []gpuDTypeArg{{"T", values.DType()}},
+ ints: []gpuIntArg{weightedSumWidth: {"D", D}, weightedSumExperts: {"K", K}, weightedSumGather: {"GATHER", gather}},
+ outputs: []gpuOutputSpec{{"WEIGHTED_SUM", []int32{int32(N), int32(D)}, values.DType()}},
+ grid: [3]int{D, N, 1},
+ threadGroup: [3]int{min(D, 256), 1, 1},
+ inputs: []*Array{weightedSumValues: values, weightedSumScores: scores, weightedSumIndices: indices},
+ })[0]
+}
diff --git a/mlx/weighted_sum_test.go b/mlx/weighted_sum_test.go
new file mode 100644
index 000000000..863fa7cad
--- /dev/null
+++ b/mlx/weighted_sum_test.go
@@ -0,0 +1,100 @@
+package mlx
+
+import (
+ "fmt"
+ "math"
+ "testing"
+
+ "github.com/ollama/ollama/mlx/mlxthread/mlxthreadtest"
+)
+
+func TestGatherWeightedSum(t *testing.T) {
+ withMLXThread(t, func(t *mlxthreadtest.T) {
+ for _, dtype := range []DType{DTypeFloat32, DTypeBFloat16, DTypeFloat16} {
+ for _, shape := range [][3]int{{1, 3, 17}, {8, 22, 64}, {32, 22, 33}} {
+ for _, gather := range []bool{false, true} {
+ Scoped(func() {
+ N, K, D := shape[0], shape[1], shape[2]
+ data := make([]float32, N*K*D)
+ for i := range data {
+ data[i] = float32(math.Sin(float64(i) * 0.17))
+ }
+ // Exercise the kernel's contiguous-input conversion too.
+ values := Transpose(FromValues(data, D, N*K), 1, 0).AsType(dtype)
+ weights := make([]float32, N*K)
+ permutation := make([]int32, N*K)
+ for i := range weights {
+ weights[i] = float32(0.2 + 0.1*math.Cos(float64(i)*0.23))
+ permutation[i] = int32(N*K - 1 - i)
+ }
+ scores := FromValues(weights, N, K)
+ var indices *Array
+ if gather {
+ indices = FromValues(permutation, N, K)
+ }
+ got := GatherWeightedSum(values, scores, indices)
+ if MetalIsAvailable() && got.name != "WEIGHTED_SUM" {
+ t.Fatal("Metal weighted-sum kernel was skipped")
+ }
+ if got.DType() != dtype || got.Dim(0) != N || got.Dim(1) != D {
+ t.Fatalf("unexpected output dtype/shape: %v %v", got.DType(), got.Dims())
+ }
+ fp32 := Contiguous(values.AsType(DTypeFloat32), false)
+ Eval(fp32)
+ v := fp32.Floats()
+ want := make([]float32, N*D)
+ for n := range N {
+ for d := range D {
+ var sum float64
+ for k := range K {
+ slot := n*K + k
+ row := slot
+ if gather {
+ row = int(permutation[slot])
+ }
+ sum += float64(v[row*D+d]) * float64(weights[slot])
+ }
+ want[n*D+d] = float32(sum)
+ }
+ }
+ expected := FromValues(want, N, D).AsType(dtype).AsType(DTypeFloat32)
+ actual := got.AsType(DTypeFloat32)
+ graph := gatherWeightedSumGraph(values, scores, indices).AsType(DTypeFloat32)
+ Eval(actual, expected, graph)
+ label := fmt.Sprintf("dtype=%v shape=%v gather=%v", dtype, shape, gather)
+ gotValues := actual.Floats()
+ for name, reference := range map[string]*Array{"oracle": expected, "fallback": graph} {
+ for i, want := range reference.Floats() {
+ tolerance := 2e-6 * math.Max(1, math.Abs(float64(want)))
+ // Permit one final output ULP when FP32 accumulation
+ // straddles a low-precision rounding boundary.
+ if dtype != DTypeFloat32 {
+ bits := 7
+ if dtype == DTypeFloat16 {
+ bits = 10
+ }
+ tolerance = math.Max(2e-6, math.Ldexp(1, math.Ilogb(math.Abs(float64(want)))-bits))
+ }
+ got := gotValues[i]
+ if math.IsNaN(float64(got)) || math.Abs(float64(got-want)) > tolerance {
+ t.Errorf("%s %s[%d]=%g, want %g (tolerance %g)", label, name, i, got, want, tolerance)
+ break
+ }
+ }
+ }
+ })
+ }
+ }
+ }
+ })
+}
+
+func TestGatherWeightedSumPreservesFP32Scores(t *testing.T) {
+ withMLXThread(t, func(t *mlxthreadtest.T) {
+ values := FromValues([]float32{1024, -1024}, 2, 1).AsType(DTypeBFloat16)
+ scores := FromValues([]float32{0.5001, 0.5}, 1, 2)
+ got := GatherWeightedSum(values, scores, nil).AsType(DTypeFloat32)
+ want := FromValues([]float32{(float32(0.5001) - 0.5) * 1024}, 1, 1).AsType(DTypeBFloat16).AsType(DTypeFloat32)
+ reportMamba2Failures(t, appendArrayCloseError(nil, "FP32 scores", got, want, 0))
+ })
+}
diff --git a/mlxrunner/model/globalscale.go b/mlxrunner/model/globalscale.go
index ab704fa75..c0c428ecc 100644
--- a/mlxrunner/model/globalscale.go
+++ b/mlxrunner/model/globalscale.go
@@ -6,7 +6,8 @@ import "github.com/ollama/ollama/mlx"
// ModelOpt's own name, reached when a checkpoint skips import.
var globalScaleSuffixes = []string{".global_scale", "_scale_2"}
-// These scale the activations, never the weight, but are freed alongside it.
+// Older imports and raw checkpoints may include activation scales. Release
+// them with the weight's companions; weight-only inference does not use them.
var activationScaleSuffixes = []string{".input_global_scale", ".input_scale"}
// ReadGlobalScale returns a weight's NVFP4 global scale in MLX's
diff --git a/mlxrunner/model/globalscale_test.go b/mlxrunner/model/globalscale_test.go
index 72c9424fa..6c80a1872 100644
--- a/mlxrunner/model/globalscale_test.go
+++ b/mlxrunner/model/globalscale_test.go
@@ -170,7 +170,8 @@ func TestGatherQMMGlobalScaleMatchesDequantized(t *testing.T) {
// One key policy for every model. The canonical name import writes wins;
// ModelOpt's own name is the fallback for un-imported checkpoints; and an
-// activation scale is consumed but never mistaken for a weight scale.
+// activation scale is reported as a companion but never mistaken for a weight
+// scale.
func TestReadGlobalScale(t *testing.T) {
mlxtest.Run(t, func(t *mlxtest.T) {
scale := func(v float32) *mlx.Array { return mlx.FromValues([]float32{v}, 1) }
@@ -211,6 +212,12 @@ func TestReadGlobalScale(t *testing.T) {
want: 0,
consumed: []string{"w.weight.input_global_scale"},
},
+ {
+ name: "modelopt activation scale is never the weight scale",
+ tensors: map[string]*mlx.Array{"w.weight.input_scale": scale(8)},
+ want: 0,
+ consumed: []string{"w.weight.input_scale"},
+ },
{
name: "activation scale alongside a weight scale",
tensors: map[string]*mlx.Array{
diff --git a/mlxrunner/model/nemotron_h/mamba_compile_test.go b/mlxrunner/model/nemotron_h/mamba_compile_test.go
new file mode 100644
index 000000000..164522c85
--- /dev/null
+++ b/mlxrunner/model/nemotron_h/mamba_compile_test.go
@@ -0,0 +1,60 @@
+package nemotron_h
+
+import (
+ "fmt"
+ "math"
+ "testing"
+
+ "github.com/ollama/ollama/mlx"
+ "github.com/ollama/ollama/mlx/mlxtest"
+)
+
+func mambaGateEager(y, gate *mlx.Array) *mlx.Array {
+ return mlx.Mul(y, mlx.SiLU(gate.AsType(y.DType())))
+}
+
+func mambaNormScaleEager(y, weight *mlx.Array) *mlx.Array {
+ return mlx.Mul(y.AsType(weight.DType()), weight)
+}
+
+func mambaCompileInputs(tokens int, norm bool) (*mlx.Array, *mlx.Array) {
+ const width = 4096
+ values := make([]float32, tokens*width)
+ for i := range values {
+ values[i] = float32(math.Sin(float64(i) * 0.17))
+ }
+ y := mlx.FromValues(values, 1, tokens, width)
+ if norm {
+ weight := mlx.FromValues(values[:width], 1, 1, 8, width/8)
+ return mlx.Reshape(y, 1, int32(tokens), 8, width/8), weight
+ }
+ // The recurrent scan returns FP32; the projection supplies BF16 gates.
+ return y, mlx.FromValues(values, 1, tokens, width).AsType(mlx.DTypeBFloat16)
+}
+
+func TestMambaCompiledMatchesEager(t *testing.T) {
+ for _, op := range []struct {
+ name string
+ norm bool
+ eager func(*mlx.Array, *mlx.Array) *mlx.Array
+ compiled func(*mlx.Array, *mlx.Array) *mlx.Array
+ }{
+ {"gate", false, mambaGateEager, mambaGate},
+ {"norm_scale", true, mambaNormScaleEager, mambaNormScale},
+ } {
+ for _, tokens := range []int{1, 128} {
+ mlxtest.RunSubtest(t, fmt.Sprintf("%s/%d", op.name, tokens), func(t *mlxtest.T) {
+ mlx.EnableCompile()
+ mlx.Scoped(func() {
+ y, arg := mambaCompileInputs(tokens, op.norm)
+ got, want := op.compiled(y, arg), op.eager(y, arg)
+ if got.DType() != want.DType() {
+ t.Fatalf("dtype = %v, want %v", got.DType(), want.DType())
+ }
+ mlx.Eval(got, want)
+ assertAllClose(t, op.name, got.Floats(), want.Floats(), 1e-6)
+ })
+ })
+ }
+ }
+}
diff --git a/mlxrunner/model/nemotron_h/nemotron_h.go b/mlxrunner/model/nemotron_h/nemotron_h.go
index 1e8cacab9..5a91ce1b8 100644
--- a/mlxrunner/model/nemotron_h/nemotron_h.go
+++ b/mlxrunner/model/nemotron_h/nemotron_h.go
@@ -20,6 +20,7 @@ import (
func init() {
model.Register("NemotronH_Nano_VL_V2", newModel)
model.Register("NemotronH_Nano_Omni_Reasoning_V3", newModel)
+ model.Register("NemotronH_Omni_Reasoning_V3", newModel)
model.Register("NemotronHForCausalLM", newModel)
}
@@ -48,6 +49,7 @@ type Config struct {
AttentionBias bool `json:"attention_bias"`
MLPBias bool `json:"mlp_bias"`
UseBias bool `json:"use_bias"`
+ NumNextNPredictLayers int32 `json:"num_nextn_predict_layers"`
ConvKernel int32 `json:"conv_kernel"`
SSMStateSize int32 `json:"ssm_state_size"`
@@ -56,10 +58,15 @@ type Config struct {
NGroups int32 `json:"n_groups"`
MambaChunkSize int32 `json:"chunk_size"`
+ // Round scan output before gating and normalized activations before scaling.
+ // The first cast intentionally discards precision before resuming in FP32.
+ MambaRoundIntermediates bool `json:"-"`
+
NRoutedExperts int32 `json:"n_routed_experts"`
NSharedExperts int32 `json:"n_shared_experts"`
NumExpertsPerTok int32 `json:"num_experts_per_tok"`
MoEIntermediateSize int32 `json:"moe_intermediate_size"`
+ MoELatentSize int32 `json:"moe_latent_size"`
MoESharedExpertIntermediateSize int32 `json:"moe_shared_expert_intermediate_size"`
RoutedScalingFactor float32 `json:"routed_scaling_factor"`
ExpertGroupCount int32 `json:"n_group"`
@@ -165,6 +172,8 @@ type SparseMoE struct {
SharedUp nn.LinearLayer
SharedDown nn.LinearLayer
+ LatentIn nn.LinearLayer
+ LatentOut nn.LinearLayer
FoldedSharedExperts int32
}
@@ -180,7 +189,8 @@ type stackedExpertWeights struct {
}
type configEnvelope struct {
- LLMConfig *Config `json:"llm_config"`
+ Architectures []string `json:"architectures"`
+ LLMConfig *Config `json:"llm_config"`
}
func parseConfig(data []byte) (Config, error) {
@@ -196,16 +206,25 @@ func parseConfig(data []byte) (Config, error) {
if env.LLMConfig != nil {
cfg = *env.LLMConfig
}
+ for _, architecture := range env.Architectures {
+ if architecture == "NemotronH_Omni_Reasoning_V3" {
+ cfg.MambaRoundIntermediates = true
+ }
+ }
if cfg.HybridOverridePattern == "" && len(cfg.LayersBlockType) > 0 {
pattern := make([]byte, len(cfg.LayersBlockType))
for i, layerType := range cfg.LayersBlockType {
+ // linear_attention and full_attention are legacy aliases retained
+ // for models published before the upstream names were supported.
switch layerType {
- case "linear_attention":
+ case "mamba", "linear_attention":
pattern[i] = 'M'
- case "full_attention":
+ case "attention", "full_attention":
pattern[i] = '*'
case "moe":
pattern[i] = 'E'
+ case "mlp":
+ pattern[i] = '-'
default:
return Config{}, fmt.Errorf("unsupported layers_block_type %q at layer %d", layerType, i)
}
@@ -264,6 +283,12 @@ func parseConfig(data []byte) (Config, error) {
if cfg.RoutedScalingFactor == 0 {
cfg.RoutedScalingFactor = 1
}
+ if cfg.MoELatentSize < 0 {
+ return Config{}, fmt.Errorf("invalid moe_latent_size: %d", cfg.MoELatentSize)
+ }
+ if cfg.NumNextNPredictLayers < 0 || cfg.NumNextNPredictLayers > 1 {
+ return Config{}, fmt.Errorf("unsupported num_nextn_predict_layers: %d (at most one MTP stage is supported)", cfg.NumNextNPredictLayers)
+ }
if cfg.ExpertGroupCount <= 0 {
cfg.ExpertGroupCount = 1
}
@@ -497,7 +522,7 @@ func stackSlicesAndClone(slices []*mlx.Array) *mlx.Array {
}
func foldSharedExperts(m *SparseMoE, cfg *Config) bool {
- if m == nil || cfg == nil || cfg.NSharedExperts != 1 {
+ if m == nil || cfg == nil || cfg.NSharedExperts != 1 || cfg.MoELatentSize > 0 {
return false
}
if cfg.MoEIntermediateSize <= 0 || cfg.MoESharedExpertIntermediateSize <= 0 {
@@ -866,12 +891,12 @@ func hasTensorByBase(tensors map[string]*mlx.Array, base string) bool {
return t != nil
}
-func hasMTPHeadTensors(tensors map[string]*mlx.Array) bool {
- if hasTensorByBase(tensors, "mtp.fc") {
+func hasMTPHeadTensors(tensors map[string]*mlx.Array, prefix string) bool {
+ if hasTensorByBase(tensors, prefix+"fc") {
return true
}
for name, tensor := range tensors {
- if tensor != nil && strings.HasPrefix(name, "mtp.layers.") && strings.HasSuffix(name, ".eh_proj.weight") {
+ if tensor != nil && strings.HasPrefix(name, prefix+"layers.") && strings.HasSuffix(name, ".eh_proj.weight") {
return true
}
}
@@ -901,8 +926,8 @@ func detectMTPLayerType(tensors map[string]*mlx.Array, layerPrefix string) (byte
}
}
-func mtpLayerPrefixes(tensors map[string]*mlx.Array) ([]string, error) {
- const prefix = "mtp.layers."
+func mtpLayerPrefixes(tensors map[string]*mlx.Array, mtpPrefix string) ([]string, error) {
+ prefix := mtpPrefix + "layers."
indices := map[int]struct{}{}
for name, tensor := range tensors {
@@ -932,7 +957,7 @@ func mtpLayerPrefixes(tensors map[string]*mlx.Array) ([]string, error) {
prefixes := make([]string, len(sorted))
for i, index := range sorted {
- prefixes[i] = fmt.Sprintf("mtp.layers.%d", index)
+ prefixes[i] = fmt.Sprintf("%s%d", prefix, index)
}
return prefixes, nil
}
@@ -1009,6 +1034,34 @@ func loadLayer(linears model.LinearFactory, tensors map[string]*mlx.Array, cfg *
if cfg.NRoutedExperts <= 0 || cfg.NumExpertsPerTok <= 0 {
return nil, fmt.Errorf("invalid moe config")
}
+ if cfg.MoELatentSize > 0 {
+ moe.LatentIn = linears.Make(mixerPrefix + ".fc1_latent_proj")
+ moe.LatentOut = linears.Make(mixerPrefix + ".fc2_latent_proj")
+ if moe.LatentIn == nil || moe.LatentOut == nil {
+ return nil, fmt.Errorf("missing moe latent projections")
+ }
+ for _, projection := range []struct {
+ name string
+ input, output int32
+ }{
+ {"fc1_latent_proj", cfg.HiddenSize, cfg.MoELatentSize},
+ {"fc2_latent_proj", cfg.MoELatentSize, cfg.HiddenSize},
+ } {
+ key := mixerPrefix + "." + projection.name + ".weight"
+ weight := tensors[key]
+ if weight.NumDims() != 2 || weight.Dim(0) != int(projection.output) {
+ return nil, fmt.Errorf("invalid %s dimensions: %v", projection.name, weight.Dims())
+ }
+ input := weight.Dim(1)
+ if scales := tensors[key+"_scale"]; scales != nil {
+ groupSize, _, _ := model.ResolveLinearQuantParams(cfg.QuantGroupSize, cfg.QuantBits, cfg.QuantMode, cfg.TensorQuant, key, weight, scales)
+ input = scales.Dim(1) * groupSize
+ }
+ if input != int(projection.input) {
+ return nil, fmt.Errorf("%s input width = %d, want %d", projection.name, input, projection.input)
+ }
+ }
+ }
up := loadStackedExpertProjection(tensors, cfg, useQuantizedExperts, layerPrefix, "up_proj")
if up == nil {
up = collectExpertProjection(tensors, cfg, useQuantizedExperts, layerPrefix, "up_proj", cfg.NRoutedExperts)
@@ -1020,6 +1073,28 @@ func loadLayer(linears model.LinearFactory, tensors map[string]*mlx.Array, cfg *
if up == nil || down == nil {
return nil, fmt.Errorf("missing routed expert weights")
}
+ if cfg.MoELatentSize > 0 {
+ for _, projection := range []struct {
+ name string
+ bank *stackedExpertWeights
+ input, output int32
+ }{
+ {"up_proj", up, cfg.MoELatentSize, cfg.MoEIntermediateSize},
+ {"down_proj", down, cfg.MoEIntermediateSize, cfg.MoELatentSize},
+ } {
+ bank := projection.bank
+ if bank.Weight.NumDims() != 3 || bank.Weight.Dim(0) != int(cfg.NRoutedExperts) || bank.Weight.Dim(1) != int(projection.output) {
+ return nil, fmt.Errorf("invalid latent expert %s dimensions: %v", projection.name, bank.Weight.Dims())
+ }
+ input := bank.Weight.Dim(2)
+ if bank.Scales != nil {
+ input = bank.Scales.Dim(2) * bank.GroupSize
+ }
+ if input != int(projection.input) {
+ return nil, fmt.Errorf("latent expert %s input width = %d, want %d", projection.name, input, projection.input)
+ }
+ }
+ }
if up.Scales != nil {
moe.UpWeightQ = up.Weight
moe.UpScales = up.Scales
@@ -1054,9 +1129,9 @@ func loadLayer(linears model.LinearFactory, tensors map[string]*mlx.Array, cfg *
return layer, nil
}
-func (m *Model) loadMTPHead(linears model.LinearFactory, tensors map[string]*mlx.Array, useQuantizedExperts bool) error {
+func (m *Model) loadMTPHead(linears model.LinearFactory, tensors map[string]*mlx.Array, prefix string, useQuantizedExperts bool) error {
cfg := m.Config
- layerPrefixes, err := mtpLayerPrefixes(tensors)
+ layerPrefixes, err := mtpLayerPrefixes(tensors, prefix)
if err != nil {
return fmt.Errorf("mtp head: %w", err)
}
@@ -1065,20 +1140,20 @@ func (m *Model) loadMTPHead(linears model.LinearFactory, tensors map[string]*mlx
head := &MTPHead{
Enorm: loadRMSNormAny(tensors, cfg.LayerNormEpsilon,
- "mtp.pre_fc_norm_embedding.weight",
+ prefix+"pre_fc_norm_embedding.weight",
firstPrefix+".enorm.weight",
),
Hnorm: loadRMSNormAny(tensors, cfg.LayerNormEpsilon,
- "mtp.pre_fc_norm_hidden.weight",
+ prefix+"pre_fc_norm_hidden.weight",
firstPrefix+".hnorm.weight",
),
FC: makeLinearAny(linears,
- "mtp.fc",
+ prefix+"fc",
firstPrefix+".eh_proj",
),
Norm: loadRMSNormAny(tensors, cfg.LayerNormEpsilon,
- "mtp.norm.weight",
- "mtp.shared_head.norm.weight",
+ prefix+"norm.weight",
+ prefix+"shared_head.norm.weight",
lastPrefix+".final_layernorm.weight",
),
}
@@ -1157,11 +1232,17 @@ func (m *Model) LoadWeights(tensors map[string]*mlx.Array) error {
}
m.Layers[i] = layer
}
- if hasMTPHeadTensors(tensors) {
- if err := m.loadMTPHead(linears, tensors, useQuantizedExperts); err != nil {
- return err
+ for _, prefix := range []string{layout.containerPrefix + "mtp.", "mtp."} {
+ if hasMTPHeadTensors(tensors, prefix) {
+ if err := m.loadMTPHead(linears, tensors, prefix, useQuantizedExperts); err != nil {
+ return err
+ }
+ break
}
}
+ if cfg.NumNextNPredictLayers > 0 && m.MTP == nil {
+ return fmt.Errorf("config declares MTP but its head tensors are missing")
+ }
return nil
}
@@ -1219,6 +1300,20 @@ func (m *Mamba2) Forward(x *mlx.Array, b *batch.Batch, c cache.Cache, B, L int32
return out
}
+var mambaGate = mlx.Compile2("NemotronMambaGate", func(y, gate *mlx.Array) *mlx.Array {
+ return mlx.Mul(y, mlx.SiLU(gate.AsType(y.DType())))
+}, mlx.Shapeless())
+
+var mambaRoundedGate = mlx.Compile2("NemotronMambaRoundedGate", func(y, gate *mlx.Array) *mlx.Array {
+ // Super rounds the scan to the projection dtype before gating in FP32.
+ y = y.AsType(gate.DType()).AsType(mlx.DTypeFloat32)
+ return mlx.Mul(y, mlx.SiLU(gate.AsType(y.DType())))
+}, mlx.Shapeless())
+
+var mambaNormScale = mlx.Compile2("NemotronMambaNormScale", func(y, weight *mlx.Array) *mlx.Array {
+ return mlx.Mul(y.AsType(weight.DType()), weight)
+}, mlx.Shapeless())
+
// gatedGroupRMSNorm computes RMSNorm(y * SiLU(gate), groups) * weight. The
// weight varies across groups while the norm reduces within one, so it is a
// separate multiply rather than the norm's own weight argument.
@@ -1228,9 +1323,17 @@ func gatedGroupRMSNorm(y, gate, weight *mlx.Array, cfg *Config, dtype mlx.DType)
B, L := int32(dims[0]), int32(dims[1])
groupSize := inner / cfg.NGroups
- y = mlx.Mul(y, mlx.SiLU(gate.AsType(y.DType())))
+ if cfg.MambaRoundIntermediates {
+ y = mambaRoundedGate(y, gate)
+ } else {
+ y = mambaGate(y, gate)
+ }
y = mlx.RMSNormFn(mlx.Reshape(y, B, L, cfg.NGroups, groupSize), nil, cfg.LayerNormEpsilon)
- y = mlx.Mul(y, mlx.Reshape(weight.AsType(y.DType()), 1, 1, cfg.NGroups, groupSize))
+ scaleType := y.DType()
+ if cfg.MambaRoundIntermediates {
+ scaleType = dtype
+ }
+ y = mambaNormScale(y, mlx.Reshape(weight.AsType(scaleType), 1, 1, cfg.NGroups, groupSize))
return mlx.Reshape(y, B, L, inner).AsType(dtype)
}
@@ -1312,13 +1415,16 @@ func (m *SparseMoE) gatherExpertDown(hidden, idxFlat *mlx.Array, doSort bool) *m
return mlx.GatherMM(hidden, m.DownWeight, nil, idxFlat, doSort)
}
-func (m *SparseMoE) expertForward(x *mlx.Array, indices *mlx.Array, cfg *Config) *mlx.Array {
+// expertForward returns individual expert outputs unless scores is supplied,
+// in which case it gathers and accumulates the latent outputs in FP32.
+func (m *SparseMoE) expertForward(x, indices, scores *mlx.Array) *mlx.Array {
dims := x.Dims()
B, L := int32(dims[0]), int32(dims[1])
+ width := int32(dims[2])
topK := int32(indices.Dim(2))
xExpanded := mlx.ExpandDims(mlx.ExpandDims(x, -2), -2)
- xFlat := mlx.Reshape(xExpanded, B*L, 1, 1, cfg.HiddenSize)
+ xFlat := mlx.Reshape(xExpanded, B*L, 1, 1, width)
idxFlat := mlx.Reshape(indices, B*L, topK)
doSort := shouldSortMoEExperts(B * L)
@@ -1343,12 +1449,16 @@ func (m *SparseMoE) expertForward(x *mlx.Array, indices *mlx.Array, cfg *Config)
}
down := m.gatherExpertDown(hidden, idxFlat, doSort)
+ if scores != nil {
+ y := mlx.GatherWeightedSum(mlx.Reshape(down, n, width), mlx.Reshape(scores, B*L, topK), invOrder)
+ return mlx.Reshape(y, B, L, width)
+ }
if doSort {
- down = mlx.Reshape(mlx.Take(mlx.Squeeze(mlx.Squeeze(down, 2), 1), invOrder, 0), B*L, topK, cfg.HiddenSize)
+ down = mlx.Reshape(mlx.Take(mlx.Squeeze(mlx.Squeeze(down, 2), 1), invOrder, 0), B*L, topK, width)
} else {
down = mlx.Squeeze(down, 2)
}
- return mlx.Reshape(down, B, L, topK, cfg.HiddenSize)
+ return mlx.Reshape(down, B, L, topK, width)
}
func appendFoldedSharedExperts(inds, scores *mlx.Array, cfg *Config, folded int32) (*mlx.Array, *mlx.Array) {
@@ -1381,8 +1491,19 @@ func (m *SparseMoE) Forward(x *mlx.Array, cfg *Config) *mlx.Array {
inds, scores := m.route(x, cfg, B, L)
inds, scores = appendFoldedSharedExperts(inds, scores, cfg, m.FoldedSharedExperts)
- expertOut := m.expertForward(x, inds, cfg)
- y := moeWeightedSum(expertOut, scores, x.DType())
+ routed := x
+ if m.LatentIn != nil {
+ routed = m.LatentIn.Forward(routed)
+ }
+ var y *mlx.Array
+ if m.LatentIn != nil {
+ // The latent reference weights and accumulates expert outputs in FP32,
+ // then casts back before projecting to the model's hidden width.
+ y = m.expertForward(routed, inds, scores).AsType(routed.DType())
+ y = m.LatentOut.Forward(y)
+ } else {
+ y = moeWeightedSum(m.expertForward(routed, inds, nil), scores, x.DType())
+ }
if m.FoldedSharedExperts > 0 {
return mlx.Reshape(y, B, L, cfg.HiddenSize)
}
diff --git a/mlxrunner/model/nemotron_h/nemotron_h_test.go b/mlxrunner/model/nemotron_h/nemotron_h_test.go
index 7a8ce3a7f..05460fe1b 100644
--- a/mlxrunner/model/nemotron_h/nemotron_h_test.go
+++ b/mlxrunner/model/nemotron_h/nemotron_h_test.go
@@ -2,6 +2,7 @@ package nemotron_h
import (
"fmt"
+ "image"
"math"
"slices"
"strings"
@@ -53,27 +54,41 @@ func TestParseConfigNestedWrapper(t *testing.T) {
if got, want := cfg.RoutedScalingFactor, float32(2.5); got != want {
t.Fatalf("RoutedScalingFactor = %v, want %v", got, want)
}
+ if cfg.MambaRoundIntermediates {
+ t.Fatal("legacy architecture unexpectedly changed Mamba precision")
+ }
}
func TestParseConfigLayersBlockType(t *testing.T) {
- cfg, err := parseConfig([]byte(`{
- "model_type": "nemotron_h",
- "hidden_size": 8,
- "num_attention_heads": 2,
- "layers_block_type": ["linear_attention", "moe", "full_attention"]
- }`))
- if err != nil {
- t.Fatalf("parseConfig returned error: %v", err)
- }
+ for _, tt := range []struct {
+ name string
+ layerTypes string
+ want string
+ }{
+ {"publisher names", `["mamba", "moe", "attention", "mlp"]`, "ME*-"},
+ {"legacy aliases", `["linear_attention", "moe", "full_attention"]`, "ME*"},
+ } {
+ t.Run(tt.name, func(t *testing.T) {
+ cfg, err := parseConfig([]byte(fmt.Sprintf(`{
+ "model_type": "nemotron_h",
+ "hidden_size": 8,
+ "num_attention_heads": 2,
+ "layers_block_type": %s
+ }`, tt.layerTypes)))
+ if err != nil {
+ t.Fatalf("parseConfig returned error: %v", err)
+ }
- if got, want := cfg.NumHiddenLayers, int32(3); got != want {
- t.Fatalf("NumHiddenLayers = %d, want %d", got, want)
- }
- if got, want := cfg.HybridOverridePattern, "ME*"; got != want {
- t.Fatalf("HybridOverridePattern = %q, want %q", got, want)
- }
- if got, want := string(cfg.LayerTypes), "ME*"; got != want {
- t.Fatalf("LayerTypes = %q, want %q", got, want)
+ if got, want := cfg.NumHiddenLayers, int32(len(tt.want)); got != want {
+ t.Fatalf("NumHiddenLayers = %d, want %d", got, want)
+ }
+ if got, want := cfg.HybridOverridePattern, tt.want; got != want {
+ t.Fatalf("HybridOverridePattern = %q, want %q", got, want)
+ }
+ if got, want := string(cfg.LayerTypes), tt.want; got != want {
+ t.Fatalf("LayerTypes = %q, want %q", got, want)
+ }
+ })
}
}
@@ -88,6 +103,46 @@ func TestParseConfigRejectsUnknownLayerBlockType(t *testing.T) {
}
}
+func TestParseSuperConfig(t *testing.T) {
+ cfg, err := parseConfig([]byte(`{
+ "architectures": ["NemotronH_Omni_Reasoning_V3"],
+ "llm_config": {
+ "hidden_size": 4096,
+ "num_attention_heads": 32,
+ "num_key_value_heads": 2,
+ "moe_latent_size": 1024,
+ "layers_block_type": ["mamba", "moe", "attention"]
+ }
+ }`))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if cfg.MoELatentSize != 1024 || cfg.NumHiddenLayers != 3 || string(cfg.LayerTypes) != "ME*" || !cfg.MambaRoundIntermediates {
+ t.Fatalf("unexpected super config: %+v", cfg)
+ }
+}
+
+func TestNestedMTPPaths(t *testing.T) {
+ present := &mlx.Array{}
+ tensors := map[string]*mlx.Array{
+ "language_model.mtp.layers.0.eh_proj.weight": present,
+ "language_model.mtp.layers.0.mixer.q_proj.weight": present,
+ "language_model.mtp.layers.1.mixer.experts.0.up_proj.weight": present,
+ "mtp.layers.99.mixer.q_proj.weight": present,
+ }
+ const prefix = "language_model.mtp."
+ if !hasMTPHeadTensors(tensors, prefix) {
+ t.Fatal("nested MTP fusion not detected")
+ }
+ got, err := mtpLayerPrefixes(tensors, prefix)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if want := []string{prefix + "layers.0", prefix + "layers.1"}; !slices.Equal(got, want) {
+ t.Fatalf("prefixes = %v, want %v", got, want)
+ }
+}
+
func TestParseConfigRejectsBadPattern(t *testing.T) {
_, err := parseConfig([]byte(`{
"hidden_size": 4,
@@ -291,7 +346,7 @@ func TestMTPLayerPrefixes(t *testing.T) {
},
} {
t.Run(tt.name, func(t *testing.T) {
- got, err := mtpLayerPrefixes(tt.tensors)
+ got, err := mtpLayerPrefixes(tt.tensors, "mtp.")
if tt.wantErr != "" {
if err == nil || !strings.Contains(err.Error(), tt.wantErr) {
t.Fatalf("mtpLayerPrefixes error = %v, want %q", err, tt.wantErr)
@@ -332,7 +387,7 @@ func TestHasMTPHeadTensors(t *testing.T) {
},
} {
t.Run(tt.name, func(t *testing.T) {
- if got := hasMTPHeadTensors(tt.tensors); got != tt.want {
+ if got := hasMTPHeadTensors(tt.tensors, "mtp."); got != tt.want {
t.Fatalf("hasMTPHeadTensors() = %v, want %v", got, tt.want)
}
})
@@ -408,6 +463,41 @@ func TestGatedGroupRMSNormMatchesElementwiseReference(t *testing.T) {
})
}
+func TestMambaIntermediateRounding(t *testing.T) {
+ mlxtest.Run(t, func(t *mlxtest.T) {
+ mlx.EnableCompile()
+ cfg := &Config{MambaNumHeads: 1, MambaHeadDim: 2, NGroups: 1, MambaRoundIntermediates: true}
+ scan := mlx.FromValues([]float32{1.004, 2}, 1, 1, 2)
+ gate := mlx.FromValues([]float32{1, 1}, 1, 1, 2).AsType(mlx.DTypeBFloat16)
+ weight := mlx.FromValues([]float32{1.015625, 1.015625}, 2).AsType(mlx.DTypeBFloat16)
+ got := gatedGroupRMSNorm(scan, gate, weight, cfg, mlx.DTypeBFloat16).AsType(mlx.DTypeFloat32)
+ mlx.Eval(got)
+ // Scan rounds to [129/128, 2]. Equal gates cancel in RMS normalization
+ // with epsilon zero, giving BF16 [163/256, 81/64] before scaling by 65/64.
+ assertAllClose(t, "intermediate rounding", got.Floats(), []float32{166.0 / 256, 165.0 / 128}, 0)
+ })
+}
+
+func TestLatentMoEKeepsSharedExpertAtHiddenWidth(t *testing.T) {
+ mlxtest.Run(t, func(t *mlxtest.T) {
+ cfg := &Config{HiddenSize: 2, MoELatentSize: 1, NRoutedExperts: 2, NumExpertsPerTok: 2, NormTopKProb: true, RoutedScalingFactor: 1}
+ m := &SparseMoE{
+ RouterWeight: mlx.Zeros(mlx.DTypeFloat32, 2, 2),
+ LatentIn: nn.NewLinear(mlx.FromValues([]float32{1, 0}, 1, 2), nil),
+ LatentOut: nn.NewLinear(mlx.FromValues([]float32{1, 3}, 2, 1), nil),
+ UpWeight: mlx.FromValues([]float32{1, 2}, 2, 1, 1),
+ DownWeight: mlx.FromValues([]float32{1, 1}, 2, 1, 1),
+ SharedUp: nn.NewLinear(mlx.FromValues([]float32{0, 1}, 1, 2), nil),
+ SharedDown: nn.NewLinear(mlx.FromValues([]float32{1, 2}, 2, 1), nil),
+ }
+ got := m.Forward(mlx.FromValues([]float32{2, 3}, 1, 1, 2), cfg)
+ mlx.Eval(got)
+ // Routed: (2² + 4²)/2 = 10, projected to [10, 30].
+ // Shared: 3² = 9, projected to [9, 18].
+ assertAllClose(t, "latent and shared experts", got.Floats(), []float32{19, 48}, 0)
+ })
+}
+
func testGatedValues(seed float32, shape ...int) *mlx.Array {
n := 1
for _, d := range shape {
@@ -426,7 +516,7 @@ func assertAllClose(t *mlxtest.T, name string, got, want []float32, tol float64)
t.Fatalf("%s length = %d, want %d", name, len(got), len(want))
}
for i := range got {
- if math.Abs(float64(got[i]-want[i])) > tol {
+ if math.IsNaN(float64(got[i])) || math.IsInf(float64(got[i]), 0) || math.Abs(float64(got[i]-want[i])) > tol {
t.Fatalf("%s[%d] = %v, want %v", name, i, got[i], want[i])
}
}
@@ -537,6 +627,11 @@ func TestFoldSharedExpertsExtendsGlobalScales(t *testing.T) {
if dims := m.UpWeightQ.Dims(); dims[0] != routed {
t.Fatalf("skipped fold mutated the weight bank: dims = %v", dims)
}
+
+ cfg.MoELatentSize = hidden / 2
+ if foldSharedExperts(newMoE(nil, nil), cfg) {
+ t.Fatal("foldSharedExperts accepted different routed and shared widths")
+ }
})
}
@@ -757,6 +852,23 @@ func TestLoadVisionWeightsRejectsNonSquarePositionGrid(t *testing.T) {
})
}
+func TestResizeRadioImagePreservesFloatRange(t *testing.T) {
+ src := image.NewNRGBA(image.Rect(0, 0, 2, 1))
+ copy(src.Pix, []byte{0, 0, 0, 255, 255, 255, 255, 255})
+ got := resizeRadioImage(src, 1, 4)
+ // The half-pixel bicubic filter overshoots at the ends and produces
+ // fractional interior values; neither may be clamped or rounded to uint8.
+ want := []float32{-22.5, 255 * 29.0 / 140, 255 * 111.0 / 140, 277.5}
+ if len(got) != 3*len(want) {
+ t.Fatalf("pixel count = %d, want %d", len(got), 3*len(want))
+ }
+ for i, v := range got {
+ if math.IsNaN(float64(v)) || math.Abs(float64(v-want[i%len(want)])) > 3e-5 {
+ t.Fatalf("pixel[%d] = %v, want %v", i, v, want[i%len(want)])
+ }
+ }
+}
+
func TestResizeGrid2DPreservesSourceDType(t *testing.T) {
mlxtest.Run(t, func(t *mlxtest.T) {
x := mlx.FromValues([]float32{0, 1, 2, 3}, 1, 2, 2, 1).AsType(mlx.DTypeBFloat16)
@@ -768,6 +880,63 @@ func TestResizeGrid2DPreservesSourceDType(t *testing.T) {
})
}
+func TestResizeRadioImageChannels(t *testing.T) {
+ src := image.NewNRGBA(image.Rect(3, 5, 5, 7))
+ copy(src.Pix, []byte{0, 10, 20, 255, 40, 50, 60, 255, 80, 90, 100, 255, 120, 130, 140, 255})
+ for _, tt := range []struct {
+ height, width int
+ want []float32
+ }{
+ {1, 1, []float32{60, 70, 80}},
+ {1, 2, []float32{40, 80, 50, 90, 60, 100}},
+ {2, 2, []float32{0, 40, 80, 120, 10, 50, 90, 130, 20, 60, 100, 140}},
+ } {
+ t.Run(fmt.Sprintf("%dx%d", tt.width, tt.height), func(t *testing.T) {
+ if got := resizeRadioImage(src, tt.height, tt.width); !slices.Equal(got, tt.want) {
+ t.Errorf("pixels = %v, want %v", got, tt.want)
+ }
+ })
+ }
+}
+
+func TestResizeRadioImagePixelAccess(t *testing.T) {
+ bounds := image.Rect(3, 5, 12, 13)
+ crop := image.Rect(5, 7, 10, 11)
+ nrgba := image.NewNRGBA(bounds)
+ for i := range nrgba.Pix {
+ nrgba.Pix[i] = byte(i * 31)
+ }
+ for i := 3; i < len(nrgba.Pix); i += 4 {
+ nrgba.Pix[i] = [4]byte{0, 1, 127, 255}[(i/4)%4]
+ }
+ images := []image.Image{nrgba.SubImage(crop)}
+ for _, ratio := range []image.YCbCrSubsampleRatio{
+ image.YCbCrSubsampleRatio444, image.YCbCrSubsampleRatio422,
+ image.YCbCrSubsampleRatio420, image.YCbCrSubsampleRatio440,
+ image.YCbCrSubsampleRatio411, image.YCbCrSubsampleRatio410,
+ } {
+ src := image.NewYCbCr(bounds, ratio)
+ for i := range src.Y {
+ src.Y[i] = byte(i * 31)
+ }
+ for i := range src.Cb {
+ src.Cb[i], src.Cr[i] = byte(i*17), byte(i*43)
+ }
+ images = append(images, src.SubImage(crop))
+ }
+ for _, src := range images {
+ // Hiding the concrete image type exercises the generic color conversion.
+ generic := struct{ image.Image }{src}
+ for _, size := range [][2]int{{2, 3}, {4, 5}, {7, 9}} {
+ got := resizeRadioImage(src, size[0], size[1])
+ want := resizeRadioImage(generic, size[0], size[1])
+ if !slices.Equal(got, want) {
+ t.Errorf("%T resize to %v differs from generic pixel access", src, size)
+ }
+ }
+ }
+}
+
func TestNemotronImagePatchBudget(t *testing.T) {
cfg := &VisionConfig{
DownsampleFactor: 2,
@@ -802,13 +971,25 @@ func TestNemotronImagePatchGrid(t *testing.T) {
wantMax int
wantMin int
wantFactor int
+ wantErr bool
}{
{name: "square minimum", height: 512, width: 512, budget: 1024, wantMax: 1024, wantMin: 1024, wantFactor: 2},
{name: "large square capped", height: 2048, width: 2048, budget: 13312, wantMax: 13312, wantMin: 1024, wantFactor: 2},
{name: "wide image capped", height: 512, width: 2048, budget: 4096, wantMax: 4096, wantMin: 1024, wantFactor: 2},
+ {name: "extremely wide image", height: 16, width: 131072, budget: 13312, wantErr: true},
+ {name: "extremely tall image", height: 131072, width: 16, budget: 13312, wantErr: true},
} {
t.Run(tt.name, func(t *testing.T) {
- patchH, patchW := nemotronImagePatchGrid(tt.height, tt.width, tt.budget, cfg)
+ patchH, patchW, err := nemotronImagePatchGrid(tt.height, tt.width, tt.budget, cfg)
+ if tt.wantErr {
+ if err == nil || !strings.Contains(err.Error(), "exceeds the patch budget") {
+ t.Fatalf("error = %v, want patch budget error", err)
+ }
+ return
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
if got := patchH * patchW; got > tt.wantMax || got < tt.wantMin {
t.Fatalf("patches = %d (%dx%d), want within [%d,%d]", got, patchH, patchW, tt.wantMin, tt.wantMax)
}
diff --git a/mlxrunner/model/nemotron_h/vision.go b/mlxrunner/model/nemotron_h/vision.go
index 8c60a1e1a..10d379394 100644
--- a/mlxrunner/model/nemotron_h/vision.go
+++ b/mlxrunner/model/nemotron_h/vision.go
@@ -45,6 +45,8 @@ type VisionConfig struct {
HeadDim int32
LayerNormEps float32
ProjectorNormEps float32
+ FinalLayerNorm bool
+ FloatImageResize bool
DownsampleFactor int32
MinNumPatches int
MaxNumPatches int
@@ -79,22 +81,28 @@ type RadioVisionLayer struct {
}
type VisionProjector struct {
- Norm *nn.RMSNorm
- FC1 nn.LinearLayer
- FC2 nn.LinearLayer
+ FinalNorm *nn.LayerNorm
+ Norm *nn.RMSNorm
+ FC1 nn.LinearLayer
+ FC2 nn.LinearLayer
}
func parseVisionConfig(configData, preprocessorData []byte) (*VisionConfig, error) {
var env struct {
+ Architectures []string `json:"architectures"`
+ LLMConfig struct {
+ NumNextNPredictLayers int `json:"num_nextn_predict_layers"`
+ } `json:"llm_config"`
PSVersion string `json:"ps_version"`
VisionConfig *struct {
- Version string `json:"version"`
- PatchSize int32 `json:"patch_size"`
- MinNumPatches int `json:"min_num_patches"`
- MaxNumPatches int `json:"max_num_patches"`
- HiddenSize int32 `json:"hidden_size"`
- NumHiddenLayers int32 `json:"num_hidden_layers"`
- NumHeads int32 `json:"num_attention_heads"`
+ Version string `json:"version"`
+ PatchSize int32 `json:"patch_size"`
+ MinNumPatches int `json:"min_num_patches"`
+ MaxNumPatches int `json:"max_num_patches"`
+ HiddenSize int32 `json:"hidden_size"`
+ NumHiddenLayers int32 `json:"num_hidden_layers"`
+ NumHeads int32 `json:"num_attention_heads"`
+ LayerNormEps float32 `json:"layer_norm_eps"`
Args struct {
Model string `json:"model"`
MinNumPatches int `json:"min_num_patches"`
@@ -153,6 +161,17 @@ func parseVisionConfig(configData, preprocessorData []byte) (*VisionConfig, erro
if env.DownsampleRatio > 0 {
cfg.DownsampleFactor = int32(math.Round(float64(1 / env.DownsampleRatio)))
}
+ if env.VisionConfig.LayerNormEps > 0 {
+ cfg.LayerNormEps = env.VisionConfig.LayerNormEps
+ }
+ for _, architecture := range env.Architectures {
+ if architecture == "NemotronH_Omni_Reasoning_V3" {
+ // The publisher's Megatron vision block inherits the MTP config,
+ // which adds a final layer norm when prediction layers are enabled.
+ cfg.FinalLayerNorm = env.LLMConfig.NumNextNPredictLayers > 0
+ cfg.FloatImageResize = true
+ }
+ }
if cfg.DownsampleFactor <= 0 {
cfg.DownsampleFactor = 2
}
@@ -326,6 +345,16 @@ func (m *Model) loadVisionWeights(tensors map[string]*mlx.Array, linears model.L
}
projector := m.Projector
+ projector.FinalNorm = newLayerNorm(tensors, "vision_projector.vision_final_layernorm", cfg.LayerNormEps)
+ if cfg.FinalLayerNorm && projector.FinalNorm == nil {
+ return fmt.Errorf("missing final vision layer norm weights")
+ }
+ if norm := projector.FinalNorm; norm != nil {
+ if norm.Weight.NumDims() != 1 || norm.Weight.Dim(0) != int(cfg.HiddenSize) ||
+ norm.Bias == nil || norm.Bias.NumDims() != 1 || norm.Bias.Dim(0) != int(cfg.HiddenSize) {
+ return fmt.Errorf("invalid final vision layer norm dimensions")
+ }
+ }
normWeight := tensors["mlp1.0.weight"]
projector.FC1 = linears.Make("mlp1.1")
projector.FC2 = linears.Make("mlp1.3")
@@ -494,14 +523,18 @@ func (m *Model) forwardVision(pixelValues *mlx.Array) *mlx.Array {
[]int32{0, clsTokens, 0},
[]int32{B, clsTokens + patchH*patchW, cfg.HiddenSize},
)
- h = mlx.Reshape(h, B, patchH, patchW, cfg.HiddenSize)
- h = radioPixelShuffle(h, cfg.DownsampleFactor)
- h = mlx.Reshape(h, B, (patchH/cfg.DownsampleFactor)*(patchW/cfg.DownsampleFactor), cfg.HiddenSize*cfg.DownsampleFactor*cfg.DownsampleFactor)
- return m.Projector.Forward(h)
+ return m.Projector.Forward(h, patchH, patchW, cfg.DownsampleFactor)
}
-func (p *VisionProjector) Forward(x *mlx.Array) *mlx.Array {
- x = p.Norm.Forward(x, 0)
+func (p *VisionProjector) Forward(x *mlx.Array, patchH, patchW, factor int32) *mlx.Array {
+ B, hidden := int32(x.Dim(0)), int32(x.Dim(2))
+ if p.FinalNorm != nil {
+ x = radioLayerNorm(p.FinalNorm, x)
+ }
+ x = mlx.Reshape(x, B, patchH, patchW, hidden)
+ x = radioPixelShuffle(x, factor)
+ x = mlx.Reshape(x, B, (patchH/factor)*(patchW/factor), hidden*factor*factor)
+ x = p.Norm.Forward(x.AsType(mlx.DTypeFloat32), 0).AsType(x.DType())
x = p.FC1.Forward(x)
x = mlx.ReLUSquared(x)
return p.FC2.Forward(x)
@@ -509,16 +542,21 @@ func (p *VisionProjector) Forward(x *mlx.Array) *mlx.Array {
func radioVisionLayerForward(layer *RadioVisionLayer, x *mlx.Array, B int32, cfg *VisionConfig) *mlx.Array {
S := int32(x.Dim(1))
- normed := layer.Norm1.Forward(x)
+ normed := radioLayerNorm(layer.Norm1, x)
attn := radioAttentionForward(layer, normed, B, S, cfg)
h := mlx.Add(x, attn)
- mlp := layer.FC1.Forward(layer.Norm2.Forward(h))
+ mlp := layer.FC1.Forward(radioLayerNorm(layer.Norm2, h))
mlpDType := mlp.DType()
mlp = mlx.GELU(mlp.AsType(mlx.DTypeFloat32)).AsType(mlpDType)
mlp = layer.FC2.Forward(mlp)
return mlx.Add(h, mlp)
}
+func radioLayerNorm(norm *nn.LayerNorm, x *mlx.Array) *mlx.Array {
+ // Avoid BF16 rounding between normalization and the affine transform.
+ return norm.Forward(x.AsType(mlx.DTypeFloat32)).AsType(x.DType())
+}
+
func radioAttentionForward(layer *RadioVisionLayer, x *mlx.Array, B, S int32, cfg *VisionConfig) *mlx.Array {
qkv := layer.QKV.Forward(x)
q := sliceAxis(qkv, 2, 0, cfg.HiddenSize)
diff --git a/mlxrunner/model/nemotron_h/vision_prompt.go b/mlxrunner/model/nemotron_h/vision_prompt.go
index 29c13457c..eba78a9c4 100644
--- a/mlxrunner/model/nemotron_h/vision_prompt.go
+++ b/mlxrunner/model/nemotron_h/vision_prompt.go
@@ -116,9 +116,22 @@ func (m *Model) preprocessImage(data []byte, maxPatches int) (pixels []float32,
return nil, 0, 0, fmt.Errorf("invalid image dimensions %dx%d", srcW, srcH)
}
- patchH, patchW := nemotronImagePatchGrid(srcH, srcW, maxPatches, cfg)
+ patchH, patchW, err := nemotronImagePatchGrid(srcH, srcW, maxPatches, cfg)
+ if err != nil {
+ return nil, 0, 0, err
+ }
targetH := patchH * int(cfg.PatchSize)
targetW := patchW * int(cfg.PatchSize)
+ if cfg.FloatImageResize {
+ pixels = resizeRadioImage(src, targetH, targetW)
+ plane := targetH * targetW
+ for c := range 3 {
+ for i := range plane {
+ pixels[c*plane+i] = (pixels[c*plane+i]/255 - cfg.Mean[c]) / cfg.Std[c]
+ }
+ }
+ return pixels, targetH, targetW, nil
+ }
dst := image.NewRGBA(image.Rect(0, 0, targetW, targetH))
draw.CatmullRom.Scale(dst, dst.Bounds(), src, bounds, draw.Src, nil)
@@ -141,7 +154,7 @@ func nemotronImagePatchBudget(cfg *VisionConfig) int {
return max(cfg.MinNumPatches, min(cfg.MaxNumPatches, (cfg.MaxModelLen-nemotronVisionReservedTokens)*int(cfg.DownsampleFactor)*int(cfg.DownsampleFactor)))
}
-func nemotronImagePatchGrid(srcH, srcW, maxPatches int, cfg *VisionConfig) (int, int) {
+func nemotronImagePatchGrid(srcH, srcW, maxPatches int, cfg *VisionConfig) (int, int, error) {
patchSize := float64(cfg.PatchSize)
closestH := max(1, int(math.RoundToEven(float64(srcH)/patchSize+0.5)))
closestW := max(1, int(math.RoundToEven(float64(srcW)/patchSize+0.5)))
@@ -175,5 +188,8 @@ func nemotronImagePatchGrid(srcH, srcW, maxPatches int, cfg *VisionConfig) (int,
}
}
- return targetH, targetW
+ if targetH > budget/targetW {
+ return 0, 0, fmt.Errorf("image %dx%d exceeds the patch budget after resize", srcW, srcH)
+ }
+ return targetH, targetW, nil
}
diff --git a/mlxrunner/model/nemotron_h/vision_resize.go b/mlxrunner/model/nemotron_h/vision_resize.go
new file mode 100644
index 000000000..eeeaa4964
--- /dev/null
+++ b/mlxrunner/model/nemotron_h/vision_resize.go
@@ -0,0 +1,118 @@
+package nemotron_h
+
+import (
+ "image"
+ "image/color"
+)
+
+// resizeRadioImage matches the reference's float32 bicubic interpolation with
+// antialiasing and align_corners=false. Keeping both passes in floating point
+// preserves overshoot and avoids rounding/clamping to uint8 before normalization.
+// The result is planar RGB in the source's 0..255 scale.
+func resizeRadioImage(src image.Image, height, width int) []float32 {
+ bounds := src.Bounds()
+ srcH, srcW := bounds.Dy(), bounds.Dx()
+ pixels := make([]float32, 3*srcH*width)
+ row := make([]float32, 3*srcW)
+ var horizontal []radioResizeFilter
+ if srcW != width {
+ horizontal = radioResizeWeights(srcW, width)
+ }
+ for y := range srcH {
+ switch src := src.(type) {
+ case *image.NRGBA:
+ offset := src.PixOffset(bounds.Min.X, bounds.Min.Y+y)
+ pixels := src.Pix[offset : offset+4*srcW]
+ for x := range srcW {
+ row[x] = float32(pixels[4*x])
+ row[srcW+x] = float32(pixels[4*x+1])
+ row[2*srcW+x] = float32(pixels[4*x+2])
+ }
+ case *image.YCbCr:
+ offset := src.YOffset(bounds.Min.X, bounds.Min.Y+y)
+ for x := range srcW {
+ chroma := src.COffset(bounds.Min.X+x, bounds.Min.Y+y)
+ r, g, b := color.YCbCrToRGB(src.Y[offset+x], src.Cb[chroma], src.Cr[chroma])
+ row[x] = float32(r)
+ row[srcW+x] = float32(g)
+ row[2*srcW+x] = float32(b)
+ }
+ default:
+ for x := range srcW {
+ c := color.NRGBAModel.Convert(src.At(bounds.Min.X+x, bounds.Min.Y+y)).(color.NRGBA)
+ row[x] = float32(c.R)
+ row[srcW+x] = float32(c.G)
+ row[2*srcW+x] = float32(c.B)
+ }
+ }
+ for c := range 3 {
+ srcRow := row[c*srcW : (c+1)*srcW]
+ dstRow := pixels[(c*srcH+y)*width : (c*srcH+y+1)*width]
+ if srcW == width {
+ copy(dstRow, srcRow)
+ continue
+ }
+ for x, filter := range horizontal {
+ var sum float32
+ for j, w := range filter.weights {
+ sum += srcRow[filter.start+j] * w
+ }
+ dstRow[x] = sum
+ }
+ }
+ }
+ if srcH != height {
+ weights := radioResizeWeights(srcH, height)
+ out := make([]float32, 3*height*width)
+ for c := range 3 {
+ for y, filter := range weights {
+ for x := range width {
+ var sum float32
+ for j, w := range filter.weights {
+ sum += pixels[(c*srcH+filter.start+j)*width+x] * w
+ }
+ out[(c*height+y)*width+x] = sum
+ }
+ }
+ }
+ pixels = out
+ }
+ return pixels
+}
+
+type radioResizeFilter struct {
+ start int
+ weights []float32
+}
+
+func radioResizeWeights(source, target int) []radioResizeFilter {
+ scale := float32(source) / float32(target)
+ filterScale := max(scale, 1)
+ support := 2 * filterScale
+ filters := make([]radioResizeFilter, target)
+ for i := range target {
+ center := (float32(i) + 0.5) * scale
+ start := max(int(center-support+0.5), 0)
+ end := min(int(center+support+0.5), source)
+ weights := make([]float32, end-start)
+ var sum float32
+ for j := range weights {
+ x := (float32(start+j) - center + 0.5) / filterScale
+ if x < 0 {
+ x = -x
+ }
+ // Cubic convolution with a=-0.5.
+ if x < 1 {
+ weights[j] = ((1.5*x-2.5)*x)*x + 1
+ } else if x < 2 {
+ weights[j] = ((-0.5*x+2.5)*x-4)*x + 2
+ }
+ sum += weights[j]
+ }
+ for j := range weights {
+ weights[j] /= sum
+ }
+ filters[i] = radioResizeFilter{start: start, weights: weights}
+ }
+ return filters
+}
diff --git a/model/renderers/nemotron35_reference_test.go b/model/renderers/nemotron35_reference_test.go
index 286ecd75b..6af4451be 100644
--- a/model/renderers/nemotron35_reference_test.go
+++ b/model/renderers/nemotron35_reference_test.go
@@ -136,6 +136,13 @@ func TestNemotron35RendererMatchesReference(t *testing.T) {
t.Fatalf("3.5 template mismatch (-want +got):\n%s", diff)
}
}
+ gotSuper, err := RenderWithRenderer("nemotron-3.5-super", tc.messages, tc.tools, tc.think)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if diff := cmp.Diff(want, gotSuper); diff != "" {
+ t.Fatalf("super renderer mismatch (-want +got):\n%s", diff)
+ }
})
}
}
diff --git a/model/renderers/nemotron35_super_test.go b/model/renderers/nemotron35_super_test.go
new file mode 100644
index 000000000..45211002b
--- /dev/null
+++ b/model/renderers/nemotron35_super_test.go
@@ -0,0 +1,33 @@
+package renderers
+
+import (
+ "testing"
+
+ "github.com/google/go-cmp/cmp"
+ "github.com/ollama/ollama/api"
+)
+
+func TestNemotronSuperImageLabels(t *testing.T) {
+ for _, tc := range []struct {
+ name, content string
+ count int
+ want string
+ }{
+ {"one", "Describe.", 1, "[img-0]Describe."},
+ {"two", "Compare.", 2, "<image 1>[img-0]<image 2>[img-1]Compare."},
+ {"interleaved", "First [img] then [img] end.", 2, "First <image 1>[img-0] then <image 2>[img-1] end."},
+ {"explicit source placeholders", "First <image> then <image> end.", 2, "First [img-0] then [img-1] end."},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ messages := []api.Message{{Role: "user", Content: tc.content, Images: make([]api.ImageData, tc.count)}}
+ got, err := RenderWithRenderer("nemotron-3.5-super", messages, nil, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ want := "<|im_start|>system\n<|im_end|>\n<|im_start|>user\n" + tc.want + "<|im_end|>\n<|im_start|>assistant\n<think>\n"
+ if diff := cmp.Diff(want, got); diff != "" {
+ t.Fatalf("render mismatch (-want +got):\n%s", diff)
+ }
+ })
+ }
+}
diff --git a/model/renderers/nemotron3nano.go b/model/renderers/nemotron3nano.go
index 5280d4aeb..a81430174 100644
--- a/model/renderers/nemotron3nano.go
+++ b/model/renderers/nemotron3nano.go
@@ -14,7 +14,8 @@ import (
type Nemotron3NanoRenderer struct {
// v35 renders the Nemotron 3.5 prompt layout.
- v35 bool
+ v35 bool
+ imageLabels bool
}
func (r *Nemotron3NanoRenderer) LeadingBOS() string {
@@ -277,11 +278,42 @@ func (r *Nemotron3NanoRenderer) renderMessageContent(message api.Message, imageO
if len(message.Images) == 0 {
return content
}
+ if r.imageLabels {
+ return nemotronSuperImageContent(content, len(message.Images), imageOffset)
+ }
content, _ = renderContentWithImageTags(content, len(message.Images), imageOffset)
return content
}
+// The Super template numbers multiple images within each message. Explicit
+// <image> placeholders suppress automatic labels and retain their positions.
+func nemotronSuperImageContent(content string, count, offset int) string {
+ if strings.Contains(content, "<image>") {
+ for i := range count {
+ content = strings.Replace(content, "<image>", fmt.Sprintf("[img-%d]", offset+i), 1)
+ }
+ return content
+ }
+ var prefix strings.Builder
+ for i := range count {
+ tag := fmt.Sprintf("[img-%d]", offset+i)
+ label := ""
+ if count > 1 {
+ label = fmt.Sprintf("<image %d>", i+1)
+ }
+ switch {
+ case strings.Contains(content, tag):
+ content = strings.Replace(content, tag, label+tag, 1)
+ case strings.Contains(content, "[img]"):
+ content = strings.Replace(content, "[img]", label+tag, 1)
+ default:
+ prefix.WriteString(label + tag)
+ }
+ }
+ return prefix.String() + content
+}
+
func nemotron3NanoRenderContent(content any) string {
switch v := content.(type) {
case string:
diff --git a/model/renderers/renderer.go b/model/renderers/renderer.go
index f344b3291..33e106b45 100644
--- a/model/renderers/renderer.go
+++ b/model/renderers/renderer.go
@@ -99,6 +99,8 @@ func rendererForName(name string) Renderer {
return &Nemotron3NanoRenderer{}
case "nemotron-3.5-nano":
return &Nemotron3NanoRenderer{v35: true}
+ case "nemotron-3.5-super":
+ return &Nemotron3NanoRenderer{v35: true, imageLabels: true}
case "gemma4", "gemma4-small":
return &Gemma4Renderer{useImgTags: RenderImgTags}
case "gemma4-large":