Get up and running with Kimi, GLM, MiniMax, DeepSeek, gpt-oss, Qwen, Gemma and other models.
mlx: x/create rewrite (#16919)
Patrick Devine964ea42c098c
diff --git a/x/create/blockfp8.go b/x/create/blockfp8.gonew file mode 100644index 000000000..359423e9e--- /dev/null+++ b/x/create/blockfp8.go@@ -0,0 +1,173 @@+package create++import (+ "fmt"+ "slices"+ "sort"+ "strings"+)++// planBlockFP8 plans an HF block-FP8 source. MLX has no FP8 tensor type, so+// every FP8 weight is decoded to BF16 using its block scale and then quantized+// to the target (mxfp8); a weight the policy declines is still decoded and kept+// at BF16 (it is never stored as FP8). Everything else passes through at source+// precision.+func planBlockFP8(inv Inventory, target string, policy quantizePolicy) ([]BlobSpec, error) {+ // The scale companion of each FP8 weight is folded into that weight's+ // blob, so it is not emitted on its own.+ consumed := make(map[string]bool)+ for _, name := range sortedTensorNames(inv) {+ if isFP8Weight(inv, name) {+ if scale, ok := fp8ScaleFor(inv, name); ok {+ consumed[scale] = true+ }+ }+ }++ groups := make(map[string][]SourceTensor)+ fp8Groups := make(map[string][]SourceTensor)+ specs := make([]BlobSpec, 0, len(inv.Tensors))+ for _, name := range sortedTensorNames(inv) {+ if consumed[name] {+ continue+ }+ t := inv.Tensors[name]++ if isFP8Weight(inv, name) {+ // Disjoint per-expert FP8 weights are stacked, decoded, and+ // quantized together by planFP8ExpertGroup; an already-stacked (3D)+ // FP8 expert tensor falls through to the single-tensor decode below.+ if gp, perExpert := perExpertGroup(name); perExpert {+ fp8Groups[gp] = append(fp8Groups[gp], t)+ continue+ }+ scaleName, ok := fp8ScaleFor(inv, name)+ if !ok {+ return nil, fmt.Errorf("fp8 weight %q has no scale companion", name)+ }+ specs = append(specs, BlobSpec{+ Name: name,+ Tensors: []TensorSpec{{+ Name: name,+ Sources: []SourceTensor{t, inv.Tensors[scaleName]},+ Transform: TransformDecodeFP8,+ Quantize: policy.quantizationType(name, t.Shape, target),+ OutDtype: "BF16",+ OutShape: t.Shape,+ }},+ })+ continue+ }++ if gp, ok := perExpertGroup(name); ok {+ groups[gp] = append(groups[gp], t)+ continue+ }++ specs = append(specs, BlobSpec{+ Name: name,+ Tensors: []TensorSpec{{Name: name, Sources: []SourceTensor{t}}},+ })+ }++ for _, gp := range sortedKeys(groups) {+ spec, err := planExpertGroup(gp, groups[gp], "", policy)+ if err != nil {+ return nil, err+ }+ specs = append(specs, spec)+ }+ for _, gp := range sortedKeys(fp8Groups) {+ spec, err := planFP8ExpertGroup(gp, fp8Groups[gp], inv, target, policy)+ if err != nil {+ return nil, err+ }+ specs = append(specs, spec)+ }+ return specs, nil+}++// planFP8ExpertGroup packs a layer's disjoint per-expert block-FP8 weights into+// one blob: the experts of each projection are stacked into [experts, out, in],+// dequantized from FP8 with their block scales, and quantized per the policy.+// The stacking, decode, and quantize all run on the MLX writer thread; the+// planner only groups and orders the source weights and their scale companions.+func planFP8ExpertGroup(groupPrefix string, tensors []SourceTensor, inv Inventory, target string, policy quantizePolicy) (BlobSpec, error) {+ type expert struct {+ idx int+ weight SourceTensor+ scale SourceTensor+ }+ byProj := make(map[string][]expert)+ for _, t := range tensors {+ idx, proj, err := parseExpertTensor(groupPrefix, t.Name)+ if err != nil {+ return BlobSpec{}, err+ }+ scaleName, ok := fp8ScaleFor(inv, t.Name)+ if !ok {+ return BlobSpec{}, fmt.Errorf("fp8 expert weight %q has no scale companion", t.Name)+ }+ byProj[proj] = append(byProj[proj], expert{idx: idx, weight: t, scale: inv.Tensors[scaleName]})+ }++ spec := BlobSpec{Name: groupPrefix}+ for _, proj := range sortedKeys(byProj) {+ experts := byProj[proj]+ sort.Slice(experts, func(i, j int) bool { return experts[i].idx < experts[j].idx })++ base := experts[0].weight+ baseScale := experts[0].scale+ // Sources are the N weights followed by the N scales, in expert order,+ // matching what TransformDecodeStackFP8 expects.+ sources := make([]SourceTensor, 0, 2*len(experts))+ scales := make([]SourceTensor, 0, len(experts))+ for _, e := range experts {+ if e.weight.Dtype != base.Dtype || !slices.Equal(e.weight.Shape, base.Shape) {+ return BlobSpec{}, fmt.Errorf("fp8 expert group %s projection %s has mismatched weight layout (%s %v vs %s %v)",+ groupPrefix, proj, base.Dtype, base.Shape, e.weight.Dtype, e.weight.Shape)+ }+ if e.scale.Dtype != baseScale.Dtype || !slices.Equal(e.scale.Shape, baseScale.Shape) {+ return BlobSpec{}, fmt.Errorf("fp8 expert group %s projection %s has mismatched scale layout (%s %v vs %s %v)",+ groupPrefix, proj, baseScale.Dtype, baseScale.Shape, e.scale.Dtype, e.scale.Shape)+ }+ sources = append(sources, e.weight)+ scales = append(scales, e.scale)+ }+ sources = append(sources, scales...)++ stackedName := groupPrefix + "." + proj + ".weight"+ stackedShape := append([]int32{int32(len(experts))}, base.Shape...)+ spec.Tensors = append(spec.Tensors, TensorSpec{+ Name: stackedName,+ Sources: sources,+ Transform: TransformDecodeStackFP8,+ Quantize: policy.quantizationType(stackedName, stackedShape, target),+ OutDtype: base.Dtype,+ OutShape: stackedShape,+ })+ }+ return spec, nil+}++// isFP8Weight reports whether name is an F8_E4M3 weight with a block-scale+// companion (the form that must be decoded before use).+func isFP8Weight(inv Inventory, name string) bool {+ t, ok := inv.Tensors[name]+ if !ok || !strings.HasSuffix(name, ".weight") || !isE4M3Dtype(t.Dtype) {+ return false+ }+ _, ok = fp8ScaleFor(inv, name)+ return ok+}++// fp8ScaleFor returns the block-scale companion name for an FP8 weight,+// preferring "_scale_inv" over "_scale" (matching the source conventions).+func fp8ScaleFor(inv Inventory, weightName string) (string, bool) {+ for _, suffix := range []string{"_scale_inv", "_scale"} {+ if s := weightName + suffix; inv.Has(s) {+ return s, true+ }+ }+ return "", false+}diff --git a/x/create/blockfp8_test.go b/x/create/blockfp8_test.gonew file mode 100644index 000000000..4a75c3781--- /dev/null+++ b/x/create/blockfp8_test.go@@ -0,0 +1,132 @@+package create++import (+ "slices"+ "testing"+)++func blockFP8(tensors map[string]string) Inventory {+ // Block-fp8 sources are routed to planBlockFP8 by kind; the config is not+ // needed once classified, so build the inventory directly with realistic+ // shapes for the quantize policy.+ m := make(map[string]SourceTensor)+ for name, dtype := range tensors {+ shape := []int32{256, 256}+ if dtype != "F8_E4M3" && dtype != "BF16" {+ shape = []int32{1} // scale companions are small+ }+ m[name] = SourceTensor{Name: name, Dtype: dtype, Shape: shape}+ }+ return Inventory{Dir: "test", Tensors: m}+}++func TestPlanBlockFP8(t *testing.T) {+ inv := blockFP8(map[string]string{+ "model.layers.0.self_attn.q_proj.weight": "F8_E4M3",+ "model.layers.0.self_attn.q_proj.weight_scale_inv": "F32",+ "model.layers.0.mlp.down_proj.weight": "F8_E4M3",+ "model.layers.0.mlp.down_proj.weight_scale_inv": "F32",+ "model.layers.0.input_layernorm.weight": "F32", // norm stays as-is+ "model.embed_tokens.weight": "BF16",+ "lm_head.weight": "BF16",+ })++ specs, err := Plan(inv, Classification{Kind: SourceBlockFP8, Quantize: "mxfp8"}, defaultQuantPolicy{})+ if err != nil {+ t.Fatalf("Plan() error = %v", err)+ }++ // FP8 weight: decode + quantize to mxfp8, scale folded in (not its own blob).+ q, ok := specByName(specs, "model.layers.0.self_attn.q_proj.weight")+ if !ok {+ t.Fatal("missing q_proj blob")+ }+ ts := q.Tensors[0]+ if ts.Transform != TransformDecodeFP8 || ts.Quantize != "mxfp8" || ts.OutDtype != "BF16" {+ t.Errorf("q_proj = %+v, want decode_fp8 + mxfp8 + BF16", ts)+ }+ if len(ts.Sources) != 2 || ts.Sources[0].Name != "model.layers.0.self_attn.q_proj.weight" ||+ ts.Sources[1].Name != "model.layers.0.self_attn.q_proj.weight_scale_inv" {+ t.Errorf("q_proj sources = %v, want [weight, scale_inv]", ts.Sources)+ }+ if _, leaked := specByName(specs, "model.layers.0.self_attn.q_proj.weight_scale_inv"); leaked {+ t.Error("scale companion must not be its own blob")+ }++ // Norm stays at source precision (F32), not quantized, not cast.+ norm, _ := specByName(specs, "model.layers.0.input_layernorm.weight")+ if norm.Tensors[0].Quantize != "" || norm.Tensors[0].Transform != TransformNone || norm.Tensors[0].OutDtype != "" {+ t.Errorf("norm = %+v, want kept at source precision", norm.Tensors[0])+ }++ // BF16 weights pass through untouched.+ lmHead, _ := specByName(specs, "lm_head.weight")+ if lmHead.Tensors[0].Quantize != "" || lmHead.Tensors[0].Transform != TransformNone {+ t.Errorf("lm_head = %+v, want kept at source precision", lmHead.Tensors[0])+ }+}++func TestPlanBlockFP8PrestackedExperts(t *testing.T) {+ // A pre-stacked fp8 expert tensor (one [E, out, in] tensor + one scale)+ // decodes + quantizes as an ordinary tensor — no per-expert stacking.+ inv := Inventory{Dir: "test", Tensors: map[string]SourceTensor{+ "model.layers.0.mlp.experts.gate_up_proj.weight": {Name: "model.layers.0.mlp.experts.gate_up_proj.weight", Dtype: "F8_E4M3", Shape: []int32{8, 512, 256}},+ "model.layers.0.mlp.experts.gate_up_proj.weight_scale_inv": {Name: "model.layers.0.mlp.experts.gate_up_proj.weight_scale_inv", Dtype: "F32", Shape: []int32{8, 4, 2}},+ }}+ specs, err := Plan(inv, Classification{Kind: SourceBlockFP8, Quantize: "mxfp8"}, defaultQuantPolicy{})+ if err != nil {+ t.Fatalf("Plan() error = %v", err)+ }+ w, ok := specByName(specs, "model.layers.0.mlp.experts.gate_up_proj.weight")+ if !ok || len(specs) != 1 {+ t.Fatalf("want single decode blob; got %v", specNames(specs))+ }+ ts := w.Tensors[0]+ if ts.Transform != TransformDecodeFP8 || ts.Quantize != "mxfp8" || !slices.Equal(ts.OutShape, []int32{8, 512, 256}) {+ t.Errorf("pre-stacked fp8 expert = %+v, want decode_fp8 + mxfp8 + 3D shape", ts)+ }+}++func TestPlanBlockFP8PerExpertStacked(t *testing.T) {+ // Disjoint per-expert fp8 weights are grouped by projection, stacked into one+ // [experts, out, in] tensor, and decoded+quantized together. Sources are the+ // N weights followed by the N scales, in expert-index order.+ inv := Inventory{Dir: "test", Tensors: map[string]SourceTensor{+ "model.layers.0.mlp.experts.0.gate_proj.weight": {Name: "model.layers.0.mlp.experts.0.gate_proj.weight", Dtype: "F8_E4M3", Shape: []int32{256, 256}},+ "model.layers.0.mlp.experts.0.gate_proj.weight_scale": {Name: "model.layers.0.mlp.experts.0.gate_proj.weight_scale", Dtype: "BF16", Shape: []int32{2, 2}},+ "model.layers.0.mlp.experts.1.gate_proj.weight": {Name: "model.layers.0.mlp.experts.1.gate_proj.weight", Dtype: "F8_E4M3", Shape: []int32{256, 256}},+ "model.layers.0.mlp.experts.1.gate_proj.weight_scale": {Name: "model.layers.0.mlp.experts.1.gate_proj.weight_scale", Dtype: "BF16", Shape: []int32{2, 2}},+ }}+ specs, err := Plan(inv, Classification{Kind: SourceBlockFP8, Quantize: "mxfp8"}, defaultQuantPolicy{})+ if err != nil {+ t.Fatalf("Plan() error = %v", err)+ }+ if len(specs) != 1 {+ t.Fatalf("want single stacked blob; got %v", specNames(specs))+ }+ spec, ok := specByName(specs, "model.layers.0.mlp.experts")+ if !ok || len(spec.Tensors) != 1 {+ t.Fatalf("want one stacked expert group; got %v", specNames(specs))+ }+ ts := spec.Tensors[0]+ if ts.Name != "model.layers.0.mlp.experts.gate_proj.weight" {+ t.Errorf("stacked name = %q, want model.layers.0.mlp.experts.gate_proj.weight", ts.Name)+ }+ if ts.Transform != TransformDecodeStackFP8 || ts.Quantize != "mxfp8" || ts.OutDtype != "F8_E4M3" || !slices.Equal(ts.OutShape, []int32{2, 256, 256}) {+ t.Errorf("stacked fp8 expert = %+v, want decode_stack_fp8 + mxfp8 + F8_E4M3 + [2 256 256]", ts)+ }+ wantSources := []string{+ "model.layers.0.mlp.experts.0.gate_proj.weight",+ "model.layers.0.mlp.experts.1.gate_proj.weight",+ "model.layers.0.mlp.experts.0.gate_proj.weight_scale",+ "model.layers.0.mlp.experts.1.gate_proj.weight_scale",+ }+ if len(ts.Sources) != len(wantSources) {+ t.Fatalf("sources = %d, want %d (N weights then N scales)", len(ts.Sources), len(wantSources))+ }+ for i, want := range wantSources {+ if ts.Sources[i].Name != want {+ t.Errorf("source[%d] = %q, want %q", i, ts.Sources[i].Name, want)+ }+ }+}diff --git a/x/create/classify.go b/x/create/classify.gonew file mode 100644index 000000000..92507d497--- /dev/null+++ b/x/create/classify.go@@ -0,0 +1,166 @@+package create++import (+ "fmt"+ "strings"++ "github.com/ollama/ollama/x/quant"+)++// SourceKind is the overarching dtype for a given safetensors model+type SourceKind int++const (+ SourceFloat SourceKind = iota // bf16/fp16/fp32 — quantizable on request+ SourceBlockFP8 // HF block-FP8 — auto-converted to mxfp8+ SourcePrequantized // already quantized — copied through+)++func (k SourceKind) String() string {+ switch k {+ case SourceFloat:+ return "float"+ case SourceBlockFP8:+ return "block-fp8"+ case SourcePrequantized:+ return "prequantized"+ default:+ return "unknown"+ }+}++// Classification is the decision about a source model: its kind and the+// quantization that will actually be applied. An empty Quantize means the+// tensors are stored at source precision (no quantization).+type Classification struct {+ Kind SourceKind+ Quantize string+}++// Classify decides a source model's kind and resolves the effective+// quantization from the user's requested type, rejecting requests that are not+// allowed for the kind.+func Classify(inv Inventory, requested string) (Classification, error) {+ requested, err := normalizeRequested(requested)+ if err != nil {+ return Classification{}, err+ }++ if name, ok := firstUnsupportedFP8(inv); ok {+ return Classification{}, fmt.Errorf("unsupported fp8 source: tensor %s is F8_E5M2; only F8_E4M3 block-FP8 sources are supported", name)+ }++ switch detectKind(inv) {+ case SourceFloat:+ return Classification{Kind: SourceFloat, Quantize: requested}, nil++ case SourcePrequantized:+ if requested != "" {+ return Classification{}, fmt.Errorf("cannot requantize an already-quantized source model (requested %q): only bf16/fp16/fp32 sources can be quantized", requested)+ }+ return Classification{Kind: SourcePrequantized}, nil++ case SourceBlockFP8:+ rows, cols, ok := inv.Config.HFFP8WeightBlockSize()+ if !ok {+ return Classification{}, fmt.Errorf("fp8 source model is missing weight_block_size metadata")+ }+ if rows != 128 || cols != 128 {+ return Classification{}, fmt.Errorf("unsupported fp8 source block size %dx%d (only 128x128 is supported)", rows, cols)+ }+ if requested != "" {+ return Classification{}, fmt.Errorf("cannot quantize an fp8 source model (requested %q): fp8 sources are converted to mxfp8 automatically; only bf16/fp16/fp32 sources can be quantized", requested)+ }+ return Classification{Kind: SourceBlockFP8, Quantize: "mxfp8"}, nil+ }++ return Classification{}, fmt.Errorf("could not classify source model in %s", inv.Dir)+}++// normalizeRequested validates the user's quantize value and returns its+// canonical form ("" for no quantization).+func normalizeRequested(requested string) (string, error) {+ if strings.TrimSpace(requested) == "" {+ return "", nil+ }+ c := quant.Canonical(requested)+ if c == "" {+ return "", fmt.Errorf("unsupported quantize type %q: supported types are int4, int8, nvfp4, mxfp4, mxfp8", requested)+ }+ return c, nil+}++// detectKind sorts a source into Float, BlockFP8, or Prequantized using only+// the inventory's tensor names, dtypes, and config. Prequantized is detected+// from the tensors themselves, so a model whose quantization config sidecar is+// missing (e.g. a ModelOpt checkpoint without hf_quant_config.json) is still+// recognized as already-quantized and not mistaken for a float model.+func detectKind(inv Inventory) SourceKind {+ var hasMLXScales, hasPacked, hasNVFP4Scale, hasFP8Weight bool+ for name, t := range inv.Tensors {+ switch {+ case strings.HasSuffix(name, ".scales"):+ hasMLXScales = true+ case strings.HasSuffix(name, ".weight_packed"):+ hasPacked = true+ case strings.HasSuffix(name, ".weight_scale"):+ // An NVFP4 per-block scale sits on a packed (U8) weight. A+ // block-FP8 source also has a scale companion, but its weight is+ // F8_E4M3 — so the base weight's dtype disambiguates the two.+ if bt, ok := inv.Tensors[strings.TrimSuffix(name, "_scale")]; ok && isPackedDtype(bt.Dtype) {+ hasNVFP4Scale = true+ }+ }+ if strings.HasSuffix(name, ".weight") && isE4M3Dtype(t.Dtype) {+ hasFP8Weight = true+ }+ }++ switch {+ case hasMLXScales || hasPacked || hasNVFP4Scale:+ return SourcePrequantized+ case hasFP8Weight:+ return SourceBlockFP8+ default:+ return SourceFloat+ }+}++// firstUnsupportedFP8 returns the name of the first F8_E5M2 weight in the+// source, if any. We decode only E4M3, so an E5M2 source must be rejected+// explicitly rather than silently mishandled.+func firstUnsupportedFP8(inv Inventory) (string, bool) {+ for name, t := range inv.Tensors {+ if strings.HasSuffix(name, ".weight") && isE5M2Dtype(t.Dtype) {+ return name, true+ }+ }+ return "", false+}++func isPackedDtype(dtype string) bool {+ switch strings.ToUpper(dtype) {+ case "U8", "U32": // current .weight_scale producers ship U8; U32 covers a future word-packed source+ return true+ default:+ return false+ }+}++func isE4M3Dtype(dtype string) bool {+ switch strings.ToUpper(dtype) {+ case "F8_E4M3", "F8_E4M3FN":+ return true+ default:+ return false+ }+}++func isE5M2Dtype(dtype string) bool {+ switch strings.ToUpper(dtype) {+ case "F8_E5M2", "F8_E5M2FNUZ":+ return true+ default:+ return false+ }+}diff --git a/x/create/classify_test.go b/x/create/classify_test.gonew file mode 100644index 000000000..84e696cc4--- /dev/null+++ b/x/create/classify_test.go@@ -0,0 +1,149 @@+package create++import (+ "strings"+ "testing"+)++func newInventory(cfg sourceModelConfig, tensors map[string]string) Inventory {+ m := make(map[string]SourceTensor)+ for name, dtype := range tensors {+ m[name] = SourceTensor{Name: name, Dtype: dtype, Shape: []int32{128, 128}, File: "model.safetensors"}+ }+ return Inventory{Dir: "test", Config: cfg, Tensors: m}+}++func fp8BlockConfig(rows, cols int32) sourceModelConfig {+ return sourceModelConfig{+ QuantizationConfig: sourceQuantization{QuantMethod: "fp8", WeightBlockSize: []int32{rows, cols}},+ }+}++func TestClassify(t *testing.T) {+ tests := []struct {+ name string+ cfg sourceModelConfig+ tensors map[string]string+ requested string+ wantKind SourceKind+ wantQuant string+ }{+ {+ name: "float, no quantize",+ tensors: map[string]string{"model.embed.weight": "BF16", "model.layers.0.weight": "BF16"},+ wantKind: SourceFloat,+ },+ {+ name: "float, quantize int4",+ tensors: map[string]string{"model.layers.0.weight": "BF16"},+ requested: "int4",+ wantKind: SourceFloat,+ wantQuant: "int4",+ },+ {+ name: "float, quantize alias fp8 resolves to int8",+ tensors: map[string]string{"model.layers.0.weight": "F32"},+ requested: "fp8",+ wantKind: SourceFloat,+ wantQuant: "int8",+ },+ {+ name: "mlx prequantized (.scales)",+ tensors: map[string]string{"model.layers.0.weight": "U32", "model.layers.0.scales": "BF16"},+ wantKind: SourcePrequantized,+ },+ {+ // ModelOpt NVFP4 whose hf_quant_config.json sidecar is absent:+ // recognized from the packed weight + scale companion (finding #7).+ name: "modelopt nvfp4 without config sidecar",+ tensors: map[string]string{"model.layers.0.weight": "U8", "model.layers.0.weight_scale": "F8_E4M3"},+ wantKind: SourcePrequantized,+ },+ {+ name: "compressed-tensors nvfp4 (.weight_packed)",+ tensors: map[string]string{"model.layers.0.weight_packed": "U8", "model.layers.0.weight_scale": "F8_E4M3"},+ wantKind: SourcePrequantized,+ },+ {+ name: "block-fp8 auto-converts to mxfp8",+ cfg: fp8BlockConfig(128, 128),+ tensors: map[string]string{"model.layers.0.weight": "F8_E4M3", "model.layers.0.weight_scale_inv": "F32"},+ wantKind: SourceBlockFP8,+ wantQuant: "mxfp8",+ },+ }+ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ got, err := Classify(newInventory(tt.cfg, tt.tensors), tt.requested)+ if err != nil {+ t.Fatalf("Classify() error = %v", err)+ }+ if got.Kind != tt.wantKind {+ t.Errorf("Kind = %v, want %v", got.Kind, tt.wantKind)+ }+ if got.Quantize != tt.wantQuant {+ t.Errorf("Quantize = %q, want %q", got.Quantize, tt.wantQuant)+ }+ })+ }+}++func TestClassifyErrors(t *testing.T) {+ tests := []struct {+ name string+ cfg sourceModelConfig+ tensors map[string]string+ requested string+ wantErr string+ }{+ {+ name: "invalid quantize type",+ tensors: map[string]string{"model.layers.0.weight": "BF16"},+ requested: "int3",+ wantErr: "unsupported quantize type",+ },+ {+ name: "mlx prequantized rejects requantize",+ tensors: map[string]string{"model.layers.0.weight": "U32", "model.layers.0.scales": "BF16"},+ requested: "int4",+ wantErr: "cannot requantize",+ },+ {+ name: "modelopt nvfp4 rejects requantize",+ tensors: map[string]string{"model.layers.0.weight": "U8", "model.layers.0.weight_scale": "F8_E4M3"},+ requested: "nvfp4",+ wantErr: "cannot requantize",+ },+ {+ name: "block-fp8 rejects quantize flag",+ cfg: fp8BlockConfig(128, 128),+ tensors: map[string]string{"model.layers.0.weight": "F8_E4M3", "model.layers.0.weight_scale_inv": "F32"},+ requested: "nvfp4",+ wantErr: "cannot quantize an fp8 source",+ },+ {+ name: "block-fp8 missing block size",+ tensors: map[string]string{"model.layers.0.weight": "F8_E4M3", "model.layers.0.weight_scale_inv": "F32"},+ wantErr: "missing weight_block_size",+ },+ {+ name: "block-fp8 unsupported block size",+ cfg: fp8BlockConfig(64, 64),+ tensors: map[string]string{"model.layers.0.weight": "F8_E4M3", "model.layers.0.weight_scale_inv": "F32"},+ wantErr: "unsupported fp8 source block size",+ },+ {+ name: "e5m2 fp8 unsupported",+ tensors: map[string]string{"model.layers.0.weight": "F8_E5M2"},+ wantErr: "F8_E5M2",+ },+ }+ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ _, err := Classify(newInventory(tt.cfg, tt.tensors), tt.requested)+ if err == nil || !strings.Contains(err.Error(), tt.wantErr) {+ t.Fatalf("Classify() error = %v, want substring %q", err, tt.wantErr)+ }+ })+ }+}diff --git a/x/create/client/create.go b/x/create/client/create.goindex 01a6b4d1d..bc00be5de 100644--- a/x/create/client/create.go+++ b/x/create/client/create.go@@ -26,7 +26,7 @@ import ("github.com/ollama/ollama/types/model""github.com/ollama/ollama/x/create"imagemanifest "github.com/ollama/ollama/x/imagegen/manifest"- "github.com/ollama/ollama/x/safetensors"+ "github.com/ollama/ollama/x/quant")// MinOllamaVersion is the minimum Ollama version required for safetensors models.@@ -142,43 +142,34 @@ type CreateOptions struct {func CreateModel(opts CreateOptions, p *progress.Progress) error {// Detect model typeisSafetensors := create.IsSafetensorsModelDir(opts.ModelDir)- isImageGen := create.IsTensorModelDir(opts.ModelDir)hasDraft := opts.Modelfile != nil && opts.Modelfile.Draft != ""isBaseModelWithDraft := hasDraft && !isSafetensors && create.IsSafetensorsLLMModel(opts.ModelDir)if opts.DraftQuantize != "" && !hasDraft {return fmt.Errorf("--draft-quantize requires a DRAFT model")}+ if opts.Quantize != "" && quant.Canonical(opts.Quantize) == "" {+ return fmt.Errorf("unsupported --quantize %q: supported types are int4, int8, nvfp4, mxfp4, mxfp8", opts.Quantize)+ }+ if opts.DraftQuantize != "" && quant.Canonical(opts.DraftQuantize) == "" {+ return fmt.Errorf("unsupported --draft-quantize %q: supported types are int4, int8, nvfp4, mxfp4, mxfp8", opts.DraftQuantize)+ }- if !isSafetensors && !isImageGen && !isBaseModelWithDraft {- return fmt.Errorf("%s is not a supported model directory (needs config.json + *.safetensors or model_index.json)", opts.ModelDir)+ if !isSafetensors && !isBaseModelWithDraft {+ return fmt.Errorf("%s is not a supported safetensors model directory (needs config.json + *.safetensors)", opts.ModelDir)}if hasDraft && !create.IsSafetensorsModelDir(opts.Modelfile.Draft) {return fmt.Errorf("draft %s is not a supported safetensors model directory", opts.Modelfile.Draft)}- if hasDraft && isImageGen {- return fmt.Errorf("draft models are only supported for safetensors LLM models")- }- // Determine model type settings- var modelType, spinnerKey string+ modelType := "safetensors model"+ spinnerKey := "create"var capabilities []stringvar parserName, rendererName stringif isSafetensors {- modelType = "safetensors model"- spinnerKey = "create"-- // Set parser and renderer name based on architectureparserName = getParserName(opts.ModelDir)rendererName = getRendererName(opts.ModelDir)capabilities = inferSafetensorsCapabilities(opts.ModelDir, resolveParserName(opts.Modelfile, parserName))- } else if isBaseModelWithDraft {- modelType = "safetensors model"- spinnerKey = "create"- } else {- modelType = "image generation model"- spinnerKey = "imagegen"- capabilities = []string{"image"}}// Set up progress spinner@@ -196,13 +187,12 @@ func CreateModel(opts CreateOptions, p *progress.Progress) error {var draftLayers []create.LayerInfovar err errorif hasDraft {- draftLayers, err = create.CreateDraftSafetensorsLayers(+ draftLayers, err = create.CreateDraftLayers(opts.Modelfile.Draft,"draft.",- "draft",+ "draft/",opts.DraftQuantize,- newLayerCreator(),- newTensorLayerCreator(),+ create.StoreFromLayerCreator(newLayerCreator()),progressFn,)if err != nil {@@ -221,27 +211,18 @@ func CreateModel(opts CreateOptions, p *progress.Progress) error {return nil}- // Create the model using shared callbacks- if isSafetensors {- writer := newManifestWriter(opts, capabilities, parserName, rendererName)- if len(draftLayers) > 0 {- writer = appendLayersManifestWriter(writer, draftLayers)- }- err = create.CreateSafetensorsModel(- opts.ModelName, opts.ModelDir, opts.Quantize,- newLayerCreator(), newTensorLayerCreator(),- writer,- progressFn,- newPackedTensorLayerCreator(),- )- } else {- err = create.CreateImageGenModel(- opts.ModelName, opts.ModelDir, opts.Quantize,- newLayerCreator(), newTensorLayerCreator(),- newManifestWriter(opts, capabilities, "", ""),- progressFn,- )+ // Create the model through the x/create pipeline (read → classify → plan+ // → write), supplying blob storage and manifest assembly.+ writer := newManifestWriter(opts, capabilities, parserName, rendererName)+ if len(draftLayers) > 0 {+ writer = appendLayersManifestWriter(writer, draftLayers)}+ err = create.Create(+ opts.ModelName, opts.ModelDir, opts.Quantize,+ create.StoreFromLayerCreator(newLayerCreator()),+ writer,+ progressFn,+ )spinner.Stop()if err != nil {@@ -351,12 +332,12 @@ func readConfigV2(m *imagemanifest.ModelManifest) (*model.ConfigV2, error) {func inferSafetensorsCapabilities(modelDir, parserName string) []string {capabilities := []string{"completion"}- // Qwen3.5 multimodal checkpoints use ConditionalGeneration architectures.- if supportsVision(modelDir) {+ caps := detectCapabilities(modelDir)+ if caps.vision {capabilities = append(capabilities, "vision")}- if supportsAudio(modelDir) {+ if caps.audio {capabilities = append(capabilities, "audio")}@@ -369,7 +350,7 @@ func inferSafetensorsCapabilities(modelDir, parserName string) []string {capabilities = append(capabilities, "tools")}- if supportsThinking(modelDir) || (builtinParser != nil && builtinParser.HasThinkingSupport()) {+ if caps.thinking || (builtinParser != nil && builtinParser.HasThinkingSupport()) {capabilities = append(capabilities, "thinking")}@@ -393,115 +374,6 @@ func newLayerCreator() create.LayerCreator {}}-// newTensorLayerCreator returns a QuantizingTensorLayerCreator callback for creating tensor layers.-// When quantize is non-empty, returns multiple layers (weight + scales + optional qbias).-func newTensorLayerCreator() create.QuantizingTensorLayerCreator {- return func(r io.Reader, name, dtype string, shape []int32, quantize string) ([]create.LayerInfo, error) {- if quantize != "" {- return createQuantizedLayers(r, name, dtype, shape, quantize)- }- return createUnquantizedLayer(r, name)- }-}--// createQuantizedLayers quantizes a tensor and returns a single combined layer.-// The combined blob contains data, scale, and optional bias tensors with metadata.-func createQuantizedLayers(r io.Reader, name, dtype string, shape []int32, quantize string) ([]create.LayerInfo, error) {- if !QuantizeSupported() {- return nil, fmt.Errorf("quantization requires MLX support")- }-- // Quantize the tensor into a single combined blob- blobData, err := quantizeTensor(r, name, dtype, shape, quantize)- if err != nil {- return nil, fmt.Errorf("failed to quantize %s: %w", name, err)- }-- // Create single layer for the combined blob- layer, err := manifest.NewLayer(bytes.NewReader(blobData), manifest.MediaTypeImageTensor)- if err != nil {- return nil, err- }-- return []create.LayerInfo{- {- Digest: layer.Digest,- Size: layer.Size,- MediaType: layer.MediaType,- Name: name,- },- }, nil-}--// createUnquantizedLayer creates a single tensor layer without quantization.-func createUnquantizedLayer(r io.Reader, name string) ([]create.LayerInfo, error) {- layer, err := manifest.NewLayer(r, manifest.MediaTypeImageTensor)- if err != nil {- return nil, err- }-- return []create.LayerInfo{- {- Digest: layer.Digest,- Size: layer.Size,- MediaType: layer.MediaType,- Name: name,- },- }, nil-}--// newPackedTensorLayerCreator returns a PackedTensorLayerCreator callback for-// creating packed multi-tensor blob layers (used for expert groups).-func newPackedTensorLayerCreator() create.PackedTensorLayerCreator {- return func(groupName string, tensors []create.PackedTensorInput) (create.LayerInfo, error) {- // Check if any tensor in the group needs quantization- hasQuantize := false- for _, t := range tensors {- if t.Quantize != "" {- hasQuantize = true- break- }- }-- var blobReader io.Reader- if hasQuantize {- if !QuantizeSupported() {- return create.LayerInfo{}, fmt.Errorf("quantization requires MLX support")- }- blobData, err := quantizePackedGroup(groupName, tensors)- if err != nil {- return create.LayerInfo{}, fmt.Errorf("failed to quantize packed group %s: %w", groupName, err)- }- blobReader = bytes.NewReader(blobData)- } else {- // Build unquantized packed blob using streaming reader- // Extract raw tensor data from safetensors-wrapped readers- var tds []*safetensors.TensorData- for _, t := range tensors {- rawData, err := safetensors.ExtractRawFromSafetensors(t.Reader)- if err != nil {- return create.LayerInfo{}, fmt.Errorf("failed to extract tensor %s: %w", t.Name, err)- }- td := safetensors.NewTensorDataFromBytes(t.Name, t.Dtype, t.Shape, rawData)- tds = append(tds, td)- }- blobReader = safetensors.BuildPackedSafetensorsReader(tds)- }-- layer, err := manifest.NewLayer(blobReader, manifest.MediaTypeImageTensor)- if err != nil {- return create.LayerInfo{}, err- }-- return create.LayerInfo{- Digest: layer.Digest,- Size: layer.Size,- MediaType: layer.MediaType,- Name: groupName,- }, nil- }-}-// newManifestWriter returns a ManifestWriter callback for writing the model manifest.func newManifestWriter(opts CreateOptions, capabilities []string, parserName, rendererName string) create.ManifestWriter {return func(modelName string, config create.LayerInfo, layers []create.LayerInfo) error {@@ -641,85 +513,84 @@ func createModelfileLayers(mf *ModelfileConfig) ([]manifest.Layer, error) {return layers, nil}-// supportsThinking checks if the model supports thinking mode based on known-// architectures that do not expose a cleaner signal in their local metadata.-func supportsThinking(modelDir string) bool {- configPath := filepath.Join(modelDir, "config.json")- data, err := os.ReadFile(configPath)- if err != nil {- return false- }+// modelCapabilities holds the input-modality and reasoning capabilities a model+// advertises, inferred from its source metadata.+type modelCapabilities struct {+ vision bool+ audio bool+ thinking bool+}+// detectCapabilities reads the model directory once and reports the vision,+// audio, and thinking capabilities it can infer.+func detectCapabilities(modelDir string) modelCapabilities {var cfg struct {- Architectures []string `json:"architectures"`- ModelType string `json:"model_type"`+ Architectures []string `json:"architectures"`+ ModelType string `json:"model_type"`+ VisionConfig *map[string]any `json:"vision_config"`+ AudioConfig *map[string]any `json:"audio_config"`}- if err := json.Unmarshal(data, &cfg); err != nil {- return false+ if data, err := os.ReadFile(filepath.Join(modelDir, "config.json")); err == nil {+ _ = json.Unmarshal(data, &cfg)}- // Check architectures that support thinking- thinkingArchitectures := []string{- "glm4moe", // GLM-4 MoE models- "deepseek", // DeepSeek models- "qwen3", // Qwen3 models+ return modelCapabilities{+ vision: cfg.VisionConfig != nil,+ audio: cfg.AudioConfig != nil,+ thinking: chatTemplateHasThinkingSupport(readChatTemplate(modelDir)) ||+ alwaysSupportsThinking(cfg.Architectures, cfg.ModelType),}+}- // Check the architecture list- for _, arch := range cfg.Architectures {- archLower := strings.ToLower(arch)- for _, thinkArch := range thinkingArchitectures {- if strings.Contains(archLower, thinkArch) {- return true- }+// readChatTemplate returns the model's chat template, preferring the+// chat_template field of tokenizer_config.json and falling back to a standalone+// chat_template.jinja. It returns "" when neither is present.+func readChatTemplate(modelDir string) string {+ if data, err := os.ReadFile(filepath.Join(modelDir, "tokenizer_config.json")); err == nil {+ var cfg struct {+ ChatTemplate string `json:"chat_template"`}- }-- // Also check model_type- if cfg.ModelType != "" {- typeLower := strings.ToLower(cfg.ModelType)- for _, thinkArch := range thinkingArchitectures {- if strings.Contains(typeLower, thinkArch) {- return true- }+ if json.Unmarshal(data, &cfg) == nil && cfg.ChatTemplate != "" {+ return cfg.ChatTemplate}}-- return false-}--// supportsVision checks if the model has a vision encoder by looking for-// vision_config in config.json.-func supportsVision(modelDir string) bool {- data, err := os.ReadFile(filepath.Join(modelDir, "config.json"))- if err != nil {- return false+ if data, err := os.ReadFile(filepath.Join(modelDir, "chat_template.jinja")); err == nil {+ return string(data)}+ return ""+}- var cfg struct {- VisionConfig *map[string]any `json:"vision_config"`- }- if err := json.Unmarshal(data, &cfg); err != nil {- return false+// chatTemplateHasThinkingSupport reports whether a chat template emits thinking+// blocks. Copied from server.chatTemplateHasThinkingSupport so this package need+// not depend on the server package for an eight-line string check.+func chatTemplateHasThinkingSupport(chatTemplate string) bool {+ if strings.Contains(chatTemplate, "<think>") && strings.Contains(chatTemplate, "</think>") {+ return true}- return cfg.VisionConfig != nil+ // Some Qwen/DeepSeek templates strip prior reasoning by splitting assistant+ // content at </think>; llama.cpp can still extract reasoning from them.+ return (strings.Contains(chatTemplate, "content.split('</think>')") ||+ strings.Contains(chatTemplate, `content.split("</think>")`)) &&+ !strings.Contains(chatTemplate, "reasoning_content") &&+ !strings.Contains(chatTemplate, "<SPECIAL_12>")}-func supportsAudio(modelDir string) bool {- data, err := os.ReadFile(filepath.Join(modelDir, "config.json"))- if err != nil {- return false- }-- var cfg struct {- AudioConfig *map[string]any `json:"audio_config"`+func alwaysSupportsThinking(architectures []string, modelType string) bool {+ if isQwen35Family(modelType) {+ return true}- if err := json.Unmarshal(data, &cfg); err != nil {- return false+ for _, arch := range architectures {+ if isQwen35Family(arch) {+ return true+ }}+ return false+}- return cfg.AudioConfig != nil+func isQwen35Family(s string) bool {+ s = strings.ToLower(s)+ return strings.Contains(s, "qwen3_5") || strings.Contains(s, "qwen3next")}// getParserName returns the parser name for a model based on its architecture.diff --git a/x/create/client/create_test.go b/x/create/client/create_test.goindex e1a9fd2f1..774d1840d 100644--- a/x/create/client/create_test.go+++ b/x/create/client/create_test.go@@ -423,84 +423,6 @@ func TestInferSafetensorsCapabilities(t *testing.T) {}}-func TestParsePerExpertInputs(t *testing.T) {- makeInput := func(name, quantize string) create.PackedTensorInput {- return create.PackedTensorInput{Name: name, Quantize: quantize}- }-- t.Run("uniform quant across projections", func(t *testing.T) {- inputs := []create.PackedTensorInput{- makeInput("layer.moe.experts.0.gate_proj.weight", "int4"),- makeInput("layer.moe.experts.1.gate_proj.weight", "int4"),- makeInput("layer.moe.experts.0.down_proj.weight", "int4"),- makeInput("layer.moe.experts.1.down_proj.weight", "int4"),- }- groups, projQ := parsePerExpertInputs("layer.moe.experts", inputs)- if groups == nil {- t.Fatal("expected non-nil groups")- }- if len(groups) != 2 {- t.Fatalf("expected 2 projection groups, got %d", len(groups))- }- if projQ["gate_proj.weight"] != "int4" {- t.Errorf("gate_proj quant = %q, want int4", projQ["gate_proj.weight"])- }- if projQ["down_proj.weight"] != "int4" {- t.Errorf("down_proj quant = %q, want int4", projQ["down_proj.weight"])- }- })-- t.Run("mixed quant across projections", func(t *testing.T) {- inputs := []create.PackedTensorInput{- makeInput("layer.moe.experts.0.gate_proj.weight", "int4"),- makeInput("layer.moe.experts.1.gate_proj.weight", "int4"),- makeInput("layer.moe.experts.0.down_proj.weight", "int8"),- makeInput("layer.moe.experts.1.down_proj.weight", "int8"),- }- groups, projQ := parsePerExpertInputs("layer.moe.experts", inputs)- if groups == nil {- t.Fatal("expected non-nil groups for mixed cross-projection quant")- }- if projQ["gate_proj.weight"] != "int4" {- t.Errorf("gate_proj quant = %q, want int4", projQ["gate_proj.weight"])- }- if projQ["down_proj.weight"] != "int8" {- t.Errorf("down_proj quant = %q, want int8", projQ["down_proj.weight"])- }- })-- t.Run("mixed quant within same projection rejected", func(t *testing.T) {- inputs := []create.PackedTensorInput{- makeInput("layer.moe.experts.0.down_proj.weight", "int4"),- makeInput("layer.moe.experts.1.down_proj.weight", "int8"),- }- groups, _ := parsePerExpertInputs("layer.moe.experts", inputs)- if groups != nil {- t.Fatal("expected nil for mixed quant within same projection")- }- })-- t.Run("non-experts group rejected", func(t *testing.T) {- inputs := []create.PackedTensorInput{- makeInput("layer.mlp.gate_proj.weight", "int4"),- }- groups, _ := parsePerExpertInputs("layer.mlp", inputs)- if groups != nil {- t.Fatal("expected nil for non-experts group")- }- })-}--func TestQuantizeSupported(t *testing.T) {- // This just verifies the function exists and returns a boolean- // The actual value depends on build tags (mlx vs non-mlx)- supported := QuantizeSupported()-- // In non-mlx builds, this should be false- // We can't easily test both cases, so just verify it returns something- _ = supported-}-func TestCreateModelfileLayersIncludesParameters(t *testing.T) {t.Setenv("OLLAMA_MODELS", t.TempDir())@@ -632,77 +554,91 @@ func TestNewManifestWriter_PopulatesDraftMetadata(t *testing.T) {}}-func TestSupportsThinking(t *testing.T) {+func TestDetectCapabilities(t *testing.T) {+ const thinkingTemplate = `{"chat_template": "{%- if '</think>' in content %}{{ content.split('</think>')[-1] }}{%- endif %}<think>\n</think>"}`+ const instructTemplate = `{"chat_template": "{{ '<|im_start|>assistant\n' }}"}`+tests := []struct {- name string- configJSON string- want bool+ name string+ configJSON string+ tokenizerJSON string+ want modelCapabilities}{{- name: "qwen3 architecture",- configJSON: `{"architectures": ["Qwen3ForCausalLM"], "model_type": "qwen3"}`,- want: true,+ name: "thinking from chat template",+ configJSON: `{"architectures": ["Qwen3ForCausalLM"], "model_type": "qwen3"}`,+ tokenizerJSON: thinkingTemplate,+ want: modelCapabilities{thinking: true},},{- name: "deepseek architecture",- configJSON: `{"architectures": ["DeepseekV3ForCausalLM"]}`,- want: true,+ name: "instruct template has no thinking",+ configJSON: `{"architectures": ["Qwen3ForCausalLM"], "model_type": "qwen3"}`,+ tokenizerJSON: instructTemplate,+ want: modelCapabilities{thinking: false},},{- name: "glm4moe architecture",- configJSON: `{"architectures": ["GLM4MoeForCausalLM"]}`,- want: true,+ name: "plain qwen3 without template has no thinking",+ configJSON: `{"architectures": ["Qwen3ForCausalLM"], "model_type": "qwen3"}`,+ want: modelCapabilities{thinking: false},},{- name: "llama architecture (no thinking)",- configJSON: `{"architectures": ["LlamaForCausalLM"], "model_type": "llama"}`,- want: false,+ name: "qwen3.5 moe always thinks without a thinking template",+ configJSON: `{"architectures": ["Qwen3_5MoeForConditionalGeneration"], "model_type": "qwen3_5_moe"}`,+ tokenizerJSON: instructTemplate,+ want: modelCapabilities{thinking: true},},{- name: "gemma architecture (no thinking)",- configJSON: `{"architectures": ["Gemma3ForCausalLM"], "model_type": "gemma3"}`,- want: false,+ name: "qwen3-next always thinks",+ configJSON: `{"architectures": ["Qwen3NextForCausalLM"]}`,+ want: modelCapabilities{thinking: true},},{- name: "model_type only",- configJSON: `{"model_type": "deepseek"}`,- want: true,+ name: "vision config",+ configJSON: `{"architectures": ["Gemma4ForConditionalGeneration"], "vision_config": {}}`,+ want: modelCapabilities{vision: true},},{- name: "laguna architecture without template",- configJSON: `{"architectures": ["LagunaForCausalLM"], "model_type": "laguna"}`,- want: false,+ name: "audio config",+ configJSON: `{"architectures": ["Qwen3OmniForConditionalGeneration"], "audio_config": {}}`,+ want: modelCapabilities{audio: true},},{- name: "empty config",- configJSON: `{}`,- want: false,+ name: "llama has no extra capabilities",+ configJSON: `{"architectures": ["LlamaForCausalLM"], "model_type": "llama"}`,+ want: modelCapabilities{},},{- name: "invalid json",+ name: "invalid config json",configJSON: `not json`,- want: false,+ want: modelCapabilities{},+ },+ {+ name: "missing files",+ want: modelCapabilities{},},}for _, tt := range tests {t.Run(tt.name, func(t *testing.T) {dir := t.TempDir()- os.WriteFile(filepath.Join(dir, "config.json"), []byte(tt.configJSON), 0o644)+ if tt.configJSON != "" {+ if err := os.WriteFile(filepath.Join(dir, "config.json"), []byte(tt.configJSON), 0o644); err != nil {+ t.Fatal(err)+ }+ }+ if tt.tokenizerJSON != "" {+ if err := os.WriteFile(filepath.Join(dir, "tokenizer_config.json"), []byte(tt.tokenizerJSON), 0o644); err != nil {+ t.Fatal(err)+ }+ }- if got := supportsThinking(dir); got != tt.want {- t.Errorf("supportsThinking() = %v, want %v", got, tt.want)+ if got := detectCapabilities(dir); got != tt.want {+ t.Errorf("detectCapabilities() = %+v, want %+v", got, tt.want)}})}}-func TestSupportsThinking_NoConfig(t *testing.T) {- if supportsThinking(t.TempDir()) {- t.Error("supportsThinking should return false for missing config.json")- }-}-func TestInferSafetensorsCapabilitiesFromParser(t *testing.T) {tests := []struct {name stringdiff --git a/x/create/client/quantize.go b/x/create/client/quantize.godeleted file mode 100644index 0836e8412..000000000--- a/x/create/client/quantize.go+++ /dev/null@@ -1,610 +0,0 @@-package client--import (- "encoding/binary"- "encoding/json"- "fmt"- "io"- "os"- "path/filepath"- "regexp"- "sort"- "strconv"- "strings"-- "github.com/ollama/ollama/x/create"- "github.com/ollama/ollama/x/mlxrunner/mlx"- "github.com/ollama/ollama/x/mlxrunner/model"-)--// loadAndQuantizeArray writes a safetensors reader to a temp file, loads it with MLX,-// quantizes the tensor, and appends the resulting arrays (weight, scale, optional bias)-// to the provided maps. If quantize is empty, the tensor is kept as-is.-// Returns any temp file paths created (caller must clean up) and arrays needing eval.-func loadAndQuantizeArray(r io.Reader, name, quantize string, arrays map[string]*mlx.Array) (tmpPath string, toEval []*mlx.Array, nativeHandle *mlx.SafetensorsFile, err error) {- if quantize != "" {- if gs, _, _ := model.QuantizationParams(quantize); gs == 0 {- return "", nil, nil, fmt.Errorf("unsupported quantization type: %s", quantize)- }- }-- tmpDir := ensureTempDir()-- tmpFile, err := os.CreateTemp(tmpDir, "quant-*.safetensors")- if err != nil {- return "", nil, nil, fmt.Errorf("failed to create temp file: %w", err)- }- tmpPath = tmpFile.Name()-- if _, err := io.Copy(tmpFile, r); err != nil {- tmpFile.Close()- return tmpPath, nil, nil, fmt.Errorf("failed to write temp file for %s: %w", name, err)- }- tmpFile.Close()-- st, err := mlx.LoadSafetensorsNative(tmpPath)- if err != nil {- return tmpPath, nil, nil, fmt.Errorf("failed to load safetensors for %s: %w", name, err)- }-- // Find the tensor key (may differ from name for single-tensor blobs)- header, err := readSafetensorsHeader(tmpPath)- if err != nil {- st.Free()- return tmpPath, nil, nil, fmt.Errorf("failed to read blob header for %s: %w", name, err)- }- inputKey, err := safetensorsKey(name, header)- if err != nil {- st.Free()- return tmpPath, nil, nil, fmt.Errorf("failed to resolve tensor key for %s: %w", name, err)- }-- arr := st.Get(inputKey)- if arr == nil {- st.Free()- return tmpPath, nil, nil, fmt.Errorf("tensor %q not found in safetensors", inputKey)- }-- // Decode FP8 source encoding before checking quantize, so that callers- // requesting decode-only (quantize="") receive usable float data.- if info, ok := header[inputKey]; ok && info.Dtype == "F8_E4M3" {- scaleKey := inputKey + ".scale_inv"- scaleInv := st.Get(scaleKey)- if scaleInv == nil {- scaleKey = inputKey + ".scale"- scaleInv = st.Get(scaleKey)- }- if scaleInv == nil {- st.Free()- return tmpPath, nil, nil, fmt.Errorf("missing companion tensor %q or %q for fp8 source tensor %q", inputKey+".scale_inv", inputKey+".scale", inputKey)- }- arr, err = decodeSourceFP8Tensor(arr, scaleInv)- if err != nil {- st.Free()- return tmpPath, nil, nil, fmt.Errorf("failed to decode fp8 tensor %s: %w", inputKey, err)- }- mlx.Eval(arr)- }-- if quantize == "" {- arr = mlx.Contiguous(arr, false)- arrays[name] = arr- return tmpPath, []*mlx.Array{arr}, st, nil- }-- if arr.DType() != mlx.DTypeBFloat16 && arr.DType() != mlx.DTypeFloat32 && arr.DType() != mlx.DTypeFloat16 {- // Convert to float type if needed (quantize expects float)- arr = arr.AsType(mlx.DTypeBFloat16)- mlx.Eval(arr)- }-- groupSize, bits, mode := model.QuantizationParams(quantize)- qweight, scales, qbiases := mlx.Quantize(arr, groupSize, bits, mode)-- // Validate quantization produced non-empty output. MLX quantize may return- // empty arrays for unsupported mode/bits combinations without raising an error.- mlx.Eval(qweight, scales)- if len(qweight.Dims()) == 0 || qweight.Dims()[0] == 0 {- st.Free()- return tmpPath, nil, nil, fmt.Errorf("mlx.Quantize produced empty weight for %s (quantize=%s, groupSize=%d, bits=%d, mode=%s)",- name, quantize, groupSize, bits, mode)- }- if len(scales.Dims()) == 0 || scales.Dims()[0] == 0 {- st.Free()- return tmpPath, nil, nil, fmt.Errorf("mlx.Quantize produced empty scales for %s (quantize=%s, groupSize=%d, bits=%d, mode=%s)",- name, quantize, groupSize, bits, mode)- }-- qweight = mlx.Contiguous(qweight, false)- scales = mlx.Contiguous(scales, false)- arrays[name] = qweight- arrays[name+".scale"] = scales- toEval = append(toEval, qweight, scales)-- if qbiases != nil {- qbiases = mlx.Contiguous(qbiases, false)- arrays[name+".bias"] = qbiases- toEval = append(toEval, qbiases)- }-- return tmpPath, toEval, st, nil-}--// quantizeTensor loads a tensor from safetensors format, quantizes it,-// and returns a single combined safetensors blob with the quantized weight, scale, and optional bias.-// Tensor keys use the original tensor name: name, name.scale, name.bias.-// The blob includes __metadata__ with quant_type and group_size.-// Supported quantization types: "int4", "nvfp4", "mxfp4", "int8", "mxfp8".-func quantizeTensor(r io.Reader, tensorName, dtype string, shape []int32, quantize string) (blobData []byte, err error) {- arrays := make(map[string]*mlx.Array)- tmpPath, toEval, st, err := loadAndQuantizeArray(r, tensorName, quantize, arrays)- if tmpPath != "" {- defer os.Remove(tmpPath)- }- if err != nil {- return nil, err- }-- finalArrays := make([]*mlx.Array, 0, len(arrays))- for _, arr := range arrays {- if arr != nil {- finalArrays = append(finalArrays, arr)- }- }- mlx.Pin(finalArrays...)- defer func() {- if st != nil {- st.Free()- }- mlx.Unpin(finalArrays...)- mlx.Sweep()- }()-- mlx.Eval(toEval...)- mlx.Sweep()- // Free early to release mmap; defer guard handles error paths- if st != nil {- st.Free()- st = nil- }-- // Build metadata for single-tensor blobs- groupSize, _, _ := model.QuantizationParams(quantize)- metadata := map[string]string{- "quant_type": quantize,- "group_size": strconv.Itoa(groupSize),- }-- tmpDir := ensureTempDir()- outPath := filepath.Join(tmpDir, "combined.safetensors")- defer os.Remove(outPath)- if err := mlx.SaveSafetensorsWithMetadata(outPath, arrays, metadata); err != nil {- return nil, fmt.Errorf("failed to save combined blob: %w", err)- }- return os.ReadFile(outPath)-}--// quantizePackedGroup quantizes multiple tensors and saves them all into a single-// combined safetensors blob. Used for packing expert groups.-// When the inputs are per-expert 2D tensors (e.g., experts.0.gate_proj.weight),-// they are stacked into 3D switch_mlp tensors before quantization.-// Each tensor may have a different quantization type (mixed-precision).-// Returns the blob bytes.-func quantizePackedGroup(groupName string, inputs []create.PackedTensorInput) ([]byte, error) {- // Check if inputs are per-expert tensors that should be stacked into 3D- if projGroups, projQuantize := parsePerExpertInputs(groupName, inputs); projGroups != nil {- return stackAndQuantizeExpertGroup(groupName, projGroups, projQuantize)- }-- allArrays := make(map[string]*mlx.Array)- var pinned []*mlx.Array-- var metadata map[string]string- uniformQuantize := ""- hasQuantized := false- mixedQuantize := false- for _, input := range inputs {- if input.Quantize == "" {- if hasQuantized {- mixedQuantize = true- }- continue- }- if !hasQuantized {- hasQuantized = true- uniformQuantize = input.Quantize- continue- }- if input.Quantize != uniformQuantize {- mixedQuantize = true- }- }- if hasQuantized && !mixedQuantize {- if groupSize, _, _ := model.QuantizationParams(uniformQuantize); groupSize > 0 {- metadata = map[string]string{- "quant_type": uniformQuantize,- "group_size": strconv.Itoa(groupSize),- }- }- }-- for _, input := range inputs {- tmpPath, toEval, st, err := loadAndQuantizeArray(input.Reader, input.Name, input.Quantize, allArrays)- if err != nil {- mlx.Unpin(pinned...)- mlx.Sweep()- return nil, err- }-- mlx.Eval(toEval...)-- finalArrays := arraysForPackedInput(allArrays, input)- mlx.Pin(finalArrays...)- pinned = append(pinned, finalArrays...)-- // Record per-tensor quant type so the model can resolve params at load time.- if input.Quantize != "" {- if groupSize, _, _ := model.QuantizationParams(input.Quantize); groupSize > 0 {- if metadata == nil {- metadata = make(map[string]string)- }- metadata[input.Name+".quant_type"] = input.Quantize- metadata[input.Name+".group_size"] = strconv.Itoa(groupSize)- }- }-- if st != nil {- st.Free()- }- if tmpPath != "" {- os.Remove(tmpPath)- }- mlx.Sweep()- }- defer func() {- mlx.Unpin(pinned...)- mlx.Sweep()- }()-- // Save combined blob. Add global metadata only when every packed tensor uses- // the same quantization mode and group size.- tmpDir := ensureTempDir()- outPath := filepath.Join(tmpDir, "packed-combined.safetensors")- defer os.Remove(outPath)- if err := mlx.SaveSafetensorsWithMetadata(outPath, allArrays, metadata); err != nil {- return nil, fmt.Errorf("failed to save packed blob: %w", err)- }-- blobData, err := os.ReadFile(outPath)- if err != nil {- return nil, fmt.Errorf("failed to read packed blob: %w", err)- }-- return blobData, nil-}--func arraysForPackedInput(allArrays map[string]*mlx.Array, input create.PackedTensorInput) []*mlx.Array {- keys := []string{input.Name}- if input.Quantize != "" {- keys = append(keys, input.Name+".scale", input.Name+".bias")- }-- out := make([]*mlx.Array, 0, len(keys))- for _, key := range keys {- if arr := allArrays[key]; arr != nil {- out = append(out, arr)- }- }- return out-}--// perExpertSuffix matches ".{index}.{proj_and_suffix}" after the group prefix.-var perExpertSuffix = regexp.MustCompile(`^\.(\d+)\.(.+)$`)--type expertTensorInfo struct {- index int- proj string // e.g., "gate_proj.weight"- input create.PackedTensorInput-}--// parsePerExpertInputs groups per-expert 2D tensor inputs by projection type-// and returns per-projection quantization types. Different projections may use-// different quant types (e.g., gate_up=int4, down=int8) but all experts within-// a projection must share the same type.-// Returns nil if the inputs are not per-expert tensors (e.g., already stacked 3D).-// Only handles ".experts" groups; ".shared_experts" groups are left unpacked.-func parsePerExpertInputs(groupName string, inputs []create.PackedTensorInput) (map[string][]expertTensorInfo, map[string]string) {- if !strings.HasSuffix(groupName, ".experts") {- return nil, nil- }-- groups := make(map[string][]expertTensorInfo)- projQuantize := make(map[string]string) // projection -> quant type- for _, input := range inputs {- suffix := strings.TrimPrefix(input.Name, groupName)- m := perExpertSuffix.FindStringSubmatch(suffix)- if m == nil {- return nil, nil // not a per-expert pattern- }- index, err := strconv.Atoi(m[1])- if err != nil {- return nil, nil- }- proj := m[2]- if existing, ok := projQuantize[proj]; ok {- if input.Quantize != existing {- return nil, nil // mixed quant within same projection- }- } else {- projQuantize[proj] = input.Quantize- }- groups[proj] = append(groups[proj], expertTensorInfo{- index: index,- proj: proj,- input: input,- })- }- if len(groups) == 0 {- return nil, nil- }- return groups, projQuantize-}--// stackAndQuantizeExpertGroup decodes per-expert tensors, stacks them into 3D-// switch_mlp tensors, quantizes, and returns the combined safetensors blob.-// projQuantize maps projection name to its quantization type (may differ per projection).-func stackAndQuantizeExpertGroup(groupName string, projGroups map[string][]expertTensorInfo, projQuantize map[string]string) ([]byte, error) {- groupBase := strings.TrimSuffix(groupName, ".experts")-- allArrays := make(map[string]*mlx.Array)- var pinned []*mlx.Array-- // Build metadata: if all projections use the same quant type, set global metadata.- // Otherwise record per-tensor quant info.- metadata := make(map[string]string)-- // Sort projection names for deterministic output- projNames := make([]string, 0, len(projGroups))- for proj := range projGroups {- projNames = append(projNames, proj)- }- sort.Strings(projNames)-- cleanup := func() {- for _, p := range pinned {- if p != nil {- mlx.Unpin(p)- }- }- mlx.Sweep()- }-- for _, proj := range projNames {- experts := projGroups[proj]-- // Sort by expert index- sort.Slice(experts, func(i, j int) bool {- return experts[i].index < experts[j].index- })-- // Load and decode each expert tensor- var decoded []*mlx.Array- for _, expert := range experts {- dummyArrays := make(map[string]*mlx.Array)- tmpPath, toEval, st, err := loadAndQuantizeArray(expert.input.Reader, expert.input.Name, "", dummyArrays)- if err != nil {- cleanup()- return nil, fmt.Errorf("failed to decode expert tensor %s: %w", expert.input.Name, err)- }- mlx.Eval(toEval...)-- arr := dummyArrays[expert.input.Name]- mlx.Pin(arr)- pinned = append(pinned, arr)- decoded = append(decoded, arr)-- if st != nil {- st.Free()- }- if tmpPath != "" {- os.Remove(tmpPath)- }- mlx.Sweep()- }-- // Stack into 3D along axis 0: [numExperts, rows, cols]- stacked := mlx.Stack(decoded, 0)- mlx.Eval(stacked)- mlx.Pin(stacked)- pinned = append(pinned, stacked)-- // Free individual decoded arrays (remove from pinned to avoid double-unpin in cleanup)- for i, p := range pinned {- for _, d := range decoded {- if p == d {- pinned[i] = nil- }- }- }- mlx.Unpin(decoded...)- mlx.Sweep()-- stackedName := groupBase + ".switch_mlp." + proj- quantize := projQuantize[proj]-- // Record per-tensor quant metadata so the model can resolve params at load time.- if quantize != "" {- if groupSize, _, _ := model.QuantizationParams(quantize); groupSize > 0 {- metadata[stackedName+".quant_type"] = quantize- metadata[stackedName+".group_size"] = strconv.Itoa(groupSize)- }- }-- // Quantize the stacked tensor- if quantize != "" {- groupSize, bits, mode := model.QuantizationParams(quantize)-- qweight, scales, qbiases := mlx.Quantize(stacked, groupSize, bits, mode)-- // Validate quantization produced non-empty output.- mlx.Eval(qweight, scales)- if len(qweight.Dims()) == 0 || qweight.Dims()[0] == 0 {- cleanup()- return nil, fmt.Errorf("mlx.Quantize produced empty weight for %s (quantize=%s, groupSize=%d, bits=%d, mode=%s)",- stackedName, quantize, groupSize, bits, mode)- }-- qweight = mlx.Contiguous(qweight, false)- scales = mlx.Contiguous(scales, false)- allArrays[stackedName] = qweight- allArrays[stackedName+".scale"] = scales-- toEval := []*mlx.Array{qweight, scales}- if qbiases != nil {- qbiases = mlx.Contiguous(qbiases, false)- allArrays[stackedName+".bias"] = qbiases- toEval = append(toEval, qbiases)- }- mlx.Eval(toEval...)- mlx.Pin(toEval...)- pinned = append(pinned, toEval...)-- // Free stacked source array (remove from pinned to avoid double-unpin in cleanup)- for i, p := range pinned {- if p == stacked {- pinned[i] = nil- }- }- mlx.Unpin(stacked)- mlx.Sweep()- } else {- stacked = mlx.Contiguous(stacked, false)- mlx.Eval(stacked)- mlx.Pin(stacked)- pinned = append(pinned, stacked)- allArrays[stackedName] = stacked- }- }-- defer cleanup()-- tmpDir := ensureTempDir()- outPath := filepath.Join(tmpDir, "stacked-combined.safetensors")- defer os.Remove(outPath)- if err := mlx.SaveSafetensorsWithMetadata(outPath, allArrays, metadata); err != nil {- return nil, fmt.Errorf("failed to save stacked blob: %w", err)- }-- blobData, err := os.ReadFile(outPath)- if err != nil {- return nil, fmt.Errorf("failed to read stacked blob: %w", err)- }- return blobData, nil-}--// QuantizeSupported returns true if quantization is supported (MLX library available)-func QuantizeSupported() bool {- return mlx.CheckInit() == nil-}--// ensureTempDir creates the temp directory for quantization if it doesn't exist-func ensureTempDir() string {- tmpDir := filepath.Join(os.TempDir(), "ollama-quantize")- os.MkdirAll(tmpDir, 0o755)- return tmpDir-}--type safetensorsHeaderEntry struct {- Dtype string `json:"dtype"`- Shape []int32 `json:"shape"`-}--func readSafetensorsHeader(path string) (map[string]safetensorsHeaderEntry, error) {- f, err := os.Open(path)- if err != nil {- return nil, err- }- defer f.Close()-- var headerSize uint64- if err := binary.Read(f, binary.LittleEndian, &headerSize); err != nil {- return nil, err- }- headerBytes := make([]byte, headerSize)- if _, err := io.ReadFull(f, headerBytes); err != nil {- return nil, err- }-- var header map[string]safetensorsHeaderEntry- if err := json.Unmarshal(headerBytes, &header); err != nil {- return nil, err- }- return header, nil-}--// safetensorsKey resolves the primary tensor key from a header.-func safetensorsKey(preferred string, header map[string]safetensorsHeaderEntry) (string, error) {- if preferred != "" {- if _, ok := header[preferred]; ok {- return preferred, nil- }- }-- keys := make([]string, 0, len(header))- for k := range header {- if k == "__metadata__" || strings.HasSuffix(k, ".scale_inv") {- continue- }- keys = append(keys, k)- }- sort.Strings(keys)- if len(keys) == 0 {- return "", fmt.Errorf("no tensor found in safetensors header")- }- return keys[0], nil-}--func decodeSourceFP8Tensor(weight, scale *mlx.Array) (*mlx.Array, error) {- if weight == nil || scale == nil {- return nil, fmt.Errorf("fp8 weight and scale tensors are required")- }-- weightShape := weight.Dims()- scaleShape := scale.Dims()- if len(weightShape) != 2 || len(scaleShape) != 2 {- return nil, fmt.Errorf("expected 2D fp8 weight and scale tensors, got %v and %v", weightShape, scaleShape)- }-- // These must match the block size validated by resolveEffectiveQuantization- // in create.go, which rejects any source model with a different block size.- const blockRows = 128- const blockCols = 128- rows, cols := weightShape[0], weightShape[1]- expectedScaleRows := (rows + blockRows - 1) / blockRows- expectedScaleCols := (cols + blockCols - 1) / blockCols- if scaleShape[0] != expectedScaleRows || scaleShape[1] != expectedScaleCols {- return nil, fmt.Errorf(- "unexpected fp8 scale shape %v for weight shape %v; want [%d %d]",- scaleShape,- weightShape,- expectedScaleRows,- expectedScaleCols,- )- }-- decoded := mlx.FromFP8(weight, mlx.DTypeBFloat16)- padBottom := blockRows*scaleShape[0] - rows- padSide := blockCols*scaleShape[1] - cols- if padBottom > 0 || padSide > 0 {- decoded = mlx.PadConstant(decoded, []int{0, 1}, []int{0, 0}, []int{padBottom, padSide})- }-- decoded = mlx.Reshape(decoded, int32(scaleShape[0]), int32(blockRows), int32(scaleShape[1]), int32(blockCols))- decoded = mlx.Mul(decoded, mlx.ExpandDims(mlx.ExpandDims(scale, 1), 3))- decoded = mlx.Reshape(decoded, int32(rows+padBottom), int32(cols+padSide))- if padBottom > 0 || padSide > 0 {- decoded = mlx.SliceStartStop(decoded, []int32{0, 0}, []int32{int32(rows), int32(cols)})- }-- return decoded, nil-}diff --git a/x/create/client/quantize_test.go b/x/create/client/quantize_test.godeleted file mode 100644index 3e4a5f8bb..000000000--- a/x/create/client/quantize_test.go+++ /dev/null@@ -1,24 +0,0 @@-package client--import (- "testing"-- "github.com/ollama/ollama/x/mlxrunner/mlx"-)--func TestDecodeSourceFP8TensorAcceptsWeightScale(t *testing.T) {- if err := mlx.CheckInit(); err != nil {- t.Skipf("MLX unavailable: %v", err)- }-- weight := mlx.FromValues([]uint8{0, 1, 2, 3}, 2, 2)- scale := mlx.FromValues([]float32{1}, 1, 1).AsType(mlx.DTypeBFloat16)- got, err := decodeSourceFP8Tensor(weight, scale)- if err != nil {- t.Fatal(err)- }- mlx.Eval(got)- if dims := got.Dims(); len(dims) != 2 || dims[0] != 2 || dims[1] != 2 {- t.Fatalf("decoded dims = %v, want [2 2]", dims)- }-}diff --git a/x/create/cohere2moe.go b/x/create/cohere2moe.goindex c111eed03..8c1ecf60d 100644--- a/x/create/cohere2moe.go+++ b/x/create/cohere2moe.go@@ -2,13 +2,8 @@ package createimport ("encoding/json"- "os"- "path/filepath"- "regexp"- "strconv"+ "fmt""strings"-- "github.com/ollama/ollama/x/safetensors")// cohere2MoeImportTransform adjusts quantization for Cohere2 MoE imports@@ -17,47 +12,26 @@ type cohere2MoeImportTransform struct {numLayers int}-func newCohere2MoeImportTransform(modelDir string, _ sourceModelConfig) (tensorImportTransform, error) {- data, err := os.ReadFile(filepath.Join(modelDir, "config.json"))- if err != nil {- return cohere2MoeImportTransform{}, nil //nolint:nilerr // fallback to no heuristic- }+func newCohere2MoeImportTransform(rawConfig json.RawMessage) (quantizePolicy, error) {var cfg struct {NumHiddenLayers int `json:"num_hidden_layers"`}- if err := json.Unmarshal(data, &cfg); err != nil {- return cohere2MoeImportTransform{}, nil //nolint:nilerr // fallback to no heuristic+ if err := json.Unmarshal(rawConfig, &cfg); err != nil {+ return nil, fmt.Errorf("cohere2moe: parse config.json: %w", err)}return cohere2MoeImportTransform{numLayers: cfg.NumHiddenLayers}, nil}-func (cohere2MoeImportTransform) skipTensor(string) bool { return false }--func (cohere2MoeImportTransform) transformTensor(td *safetensors.TensorData) ([]*safetensors.TensorData, error) {- return []*safetensors.TensorData{td}, nil-}--var cohere2MoeLayerIndexRe = regexp.MustCompile(`\.layers\.(\d+)\.`)-func (t cohere2MoeImportTransform) quantizationType(name string, shape []int32, quantize string) string {- quantNorm := normalizeQuantType(quantize)+ base := normalizeQuantType(quantize)// The embedding serves double duty: lookup (via QuantizedEmbedding) and the// tied lm_head projection (via AsLinear). With a 262k vocab the bf16// embedding dominates decode bandwidth through the lm_head matmul, so- // quantize it to the 8-bit variant of the requested mode.- if strings.HasSuffix(name, "embed_tokens.weight") && len(shape) == 2 {- switch quantNorm {- case "int4", "int8":- if isAligned(shape, "int8") {- return "int8"- }- case "mxfp4", "nvfp4", "mxfp8":- if isAligned(shape, "mxfp8") {- return "mxfp8"- }- }- return ""+ // quantize it to the 8-bit variant of the requested mode, or keep source+ // precision when that does not fit.+ if isEmbedTokensWeight(name) && len(shape) == 2 {+ return promoteEmbedding(shape, base)}// The MoE router picks the top-k expert set; quantization noise there can@@ -69,36 +43,17 @@ func (t cohere2MoeImportTransform) quantizationType(name string, shape []int32,}// Sensitive tensors (v_proj, k_proj, down_proj) get higher precision only- // at quantization-sensitive layer positions (gemma4's useMoreBits- // heuristic) instead of the default policy's blanket promotion. The- // blanket int8 down_proj costs ~25% of decode bandwidth on a top-8 MoE;- // the layer-position heuristic keeps the early/late layers (and every- // third in between) at 8 bits where residual-stream error matters most.- promote := ""- switch quantNorm {- case "int4":- promote = "int8"- case "mxfp4", "nvfp4":- promote = "mxfp8"- }+ // at quantization-sensitive layer positions (useMoreBits) instead of the+ // default policy's blanket promotion. The blanket int8 down_proj costs+ // ~25% of decode bandwidth on a top-8 MoE; the layer-position heuristic+ // keeps the early/late layers (and every third in between) at 8 bits where+ // residual-stream error matters most.isSensitive := strings.Contains(name, ".v_proj") || strings.Contains(name, ".k_proj") || strings.Contains(name, "down_proj")- if promote != "" && isSensitive && t.numLayers > 0 {- layerIdx := -1- if m := cohere2MoeLayerIndexRe.FindStringSubmatch(name); m != nil {- if idx, err := strconv.Atoi(m[1]); err == nil {- layerIdx = idx- }- }- if layerIdx >= 0 {- if useMoreBits(layerIdx, t.numLayers) && isAligned(shape, promote) {- return promote- }- if !isAligned(shape, quantNorm) {- return ""- }+ if isSensitive && eightBit(base) != base && t.numLayers > 0 {+ if idx := layerIndex(name); idx >= 0 {// Bypass GetTensorQuantization's blanket promotion — the// layer-position heuristic is authoritative here.- return quantNorm+ return sensitiveType(useMoreBits(idx, t.numLayers), shape, base)}}diff --git a/x/create/create.go b/x/create/create.goindex acf2d2446..f1ef4feca 100644--- a/x/create/create.go+++ b/x/create/create.go@@ -7,11 +7,9 @@ import ("io""math""os"- "path""path/filepath""regexp""slices"- "sort""strconv""strings"@@ -118,16 +116,6 @@ func loadModelConfig(modelName string) (*ModelConfig, error) {return &config, nil}-// IsSafetensorsModel checks if a model was created with the experimental-// safetensors builder by checking the model format in the config.-func IsSafetensorsModel(modelName string) bool {- config, err := loadModelConfig(modelName)- if err != nil {- return false- }- return config.ModelFormat == "safetensors"-}-// IsSafetensorsLLMModel checks if a model is a safetensors LLM model// (has completion capability, not image generation).func IsSafetensorsLLMModel(modelName string) bool {@@ -138,55 +126,6 @@ func IsSafetensorsLLMModel(modelName string) bool {return config.ModelFormat == "safetensors" && slices.Contains(config.Capabilities, "completion")}-// IsImageGenModel checks if a model is an image generation model-// (has image capability).-func IsImageGenModel(modelName string) bool {- config, err := loadModelConfig(modelName)- if err != nil {- return false- }- return config.ModelFormat == "safetensors" && slices.Contains(config.Capabilities, "image")-}--// GetModelArchitecture returns the architecture from the model's config.json layer.-func GetModelArchitecture(modelName string) (string, error) {- manifest, err := loadManifest(modelName)- if err != nil {- return "", err- }-- // Find the config.json layer- for _, layer := range manifest.Layers {- if layer.Name == "config.json" && layer.MediaType == "application/vnd.ollama.image.json" {- blobName := strings.Replace(layer.Digest, ":", "-", 1)- blobPath := filepath.Join(defaultBlobDir(), blobName)-- data, err := os.ReadFile(blobPath)- if err != nil {- return "", err- }-- var cfg struct {- Architectures []string `json:"architectures"`- ModelType string `json:"model_type"`- }- if err := json.Unmarshal(data, &cfg); err != nil {- return "", err- }-- // Prefer model_type, fall back to first architecture- if cfg.ModelType != "" {- return cfg.ModelType, nil- }- if len(cfg.Architectures) > 0 {- return cfg.Architectures[0], nil- }- }- }-- return "", fmt.Errorf("architecture not found in model config")-}-// IsTensorModelDir checks if the directory contains a diffusers-style tensor model// by looking for model_index.json, which is the standard diffusers pipeline config.func IsTensorModelDir(dir string) bool {@@ -229,14 +168,6 @@ type LayerInfo struct {// name is the path-style name (e.g., "tokenizer/tokenizer.json")type LayerCreator func(r io.Reader, mediaType, name string) (LayerInfo, error)-// TensorLayerCreator creates a tensor blob layer with metadata.-// name is the path-style name including component (e.g., "text_encoder/model.embed_tokens.weight")-type TensorLayerCreator func(r io.Reader, name, dtype string, shape []int32) (LayerInfo, error)--// QuantizingTensorLayerCreator creates tensor layers with optional quantization.-// When quantize is non-empty (e.g., "int8"), returns multiple layers (weight + scales + biases).-type QuantizingTensorLayerCreator func(r io.Reader, name, dtype string, shape []int32, quantize string) ([]LayerInfo, error)-// ManifestWriter writes the manifest file.type ManifestWriter func(modelName string, config LayerInfo, layers []LayerInfo) error@@ -273,13 +204,6 @@ func ShouldQuantize(name, component string) bool {return strings.HasSuffix(name, ".weight")}-// ShouldQuantizeTensor returns true if a tensor should be quantized based on name, shape, and quantize type.-// This is a more detailed check that also considers tensor dimensions.-// The quantize parameter specifies the quantization type (e.g., "int4", "nvfp4", "mxfp4", "int8", "mxfp8").-func ShouldQuantizeTensor(name string, shape []int32, quantize string) bool {- return GetTensorQuantization(name, shape, quantize) != ""-}-// normalizeQuantType converts various quantization type aliases to canonical forms.// Supports: q4/Q4/int4/INT4/fp4/FP4 -> int4, q8/Q8/int8/INT8/fp8/FP8 -> int8, nvfp4/NVFP4, mxfp4/MXFP4, mxfp8/MXFP8func normalizeQuantType(quantize string) string {@@ -322,89 +246,24 @@ func isStackedExpertWeight(name string) bool {return false}- return strings.Contains(name, ".mlp.switch_mlp.") ||- strings.Contains(name, ".mlp.experts.") ||- strings.Contains(name, ".mlp.shared_experts.") ||- strings.Contains(name, ".moe.experts.")-}--func sourceFP8BF16PromotionQuantization(name string, shape []int32, requested string) string {- quantNorm := normalizeQuantType(requested)- if quantNorm == "" {- return ""- }-- switch quantNorm {- case "nvfp4", "mxfp4", "mxfp8":- default:- return ""- }-- if !sourceFP8CanPromoteBF16Weight(name, shape) {- return ""- }-- return "mxfp8"-}--func sourceFP8TensorQuantization(name string, shape []int32, requested string, fallback string) string {- quantNorm := normalizeQuantType(requested)- switch quantNorm {- case "nvfp4", "mxfp4":- if sourceFP8ShouldPromoteLowBitTensor(name, shape) {- return "mxfp8"- }- }- return fallback-}--func sourceFP8ShouldPromoteLowBitTensor(name string, shape []int32) bool {- if len(shape) != 2 || !isAligned(shape, "mxfp8") {- return false- }-- return strings.Contains(name, "down_proj") ||- strings.Contains(name, ".v_proj") ||- strings.Contains(name, ".k_proj")+ // ".experts." covers the common case (.mlp.experts., .moe.experts.) as well+ // as gemma's bare "...layers.N.experts.gate_up_proj" (no .mlp/.moe prefix).+ return strings.Contains(name, ".experts.") ||+ strings.Contains(name, ".mlp.switch_mlp.") ||+ strings.Contains(name, ".mlp.shared_experts.")}-func sourceFP8CanPromoteBF16Weight(name string, shape []int32) bool {- if !strings.HasSuffix(name, ".weight") || len(shape) != 2 {- return false- }-- var elems int64 = 1- for _, d := range shape {- elems *= int64(d)- }- if elems < 1024 {- return false- }-- if !isAligned(shape, "mxfp8") {- return false- }-- switch {- case strings.Contains(name, "audio_tower") || strings.Contains(name, "embed_audio"):- return false- case strings.Contains(name, "norm") || strings.Contains(name, "ln_") || strings.Contains(name, "layernorm"):- return false- case strings.Contains(name, "router") || strings.Contains(name, "score_correction"):- return false- case strings.Contains(name, "mlp.gate.weight") && !strings.Contains(name, "_proj"):- return false- default:- return true- }+// isRoutingGate reports the small MoE routing/gate weights that select the+// active experts. Quantization noise there can flip expert selection, so they+// are kept at source precision regardless of architecture.+func isRoutingGate(name string) bool {+ return strings.HasSuffix(name, ".mlp.gate.weight") ||+ strings.HasSuffix(name, ".shared_expert_gate.weight") ||+ strings.HasSuffix(name, ".router.proj.weight")}// GetTensorQuantization returns the appropriate quantization type for a tensor.// Returns "" if the tensor should not be quantized.-// This implements mixed-precision quantization:-// - v_proj, k_proj, down_proj: promoted to INT8 when base is INT4-// - Norms, embeddings, biases, routing gates: no quantization-// - All other eligible weights: use requested quantization typefunc GetTensorQuantization(name string, shape []int32, quantize string) string {stackedExpert := isStackedExpertWeight(name)@@ -431,31 +290,26 @@ func GetTensorQuantization(name string, shape []int32, quantize string) string {// Normalize quantization type to canonical formquantNorm := normalizeQuantType(quantize)- // Skip routing gate weights (should stay high precision)- // In safetensors these are: mlp.gate.weight (not mlp.gate_proj.weight)- if strings.Contains(name, "mlp.gate.weight") && !strings.Contains(name, "_proj") {+ // Routing gates are tiny and selection-sensitive — keep them at source precision.+ if isRoutingGate(name) {return ""}- // MLX quantization requires last dimension to be divisible by group size.- if !isAligned(shape, quantNorm) {+ // lm_head is too sensitive for the fp quant modes; keep it at source precision.+ if strings.HasSuffix(name, "lm_head.weight") && (quantNorm == "nvfp4" || quantNorm == "mxfp4" || quantNorm == "mxfp8") {return ""}- // For non-affine modes, use the same quantization for all eligible tensors.- if quantNorm == "nvfp4" || quantNorm == "mxfp4" || quantNorm == "mxfp8" {- return quantNorm+ // MLX quantization requires last dimension to be divisible by group size.+ if !isAligned(shape, quantNorm) {+ return ""}- // Value projection weights directly determine attention output quality.- // Down projection weights feed directly into the residual stream where- // errors accumulate across layers. Both benefit from higher precision.- // Promote to INT8 when base is INT4 (same affine mode, compatible with- // GatherQMM for MoE expert tensors).- if quantNorm == "int4" {+ // Promote sensitive projections to 8-bit; fp4 skips experts since their kernels take a single mode.+ if quantNorm == "int4" || ((quantNorm == "nvfp4" || quantNorm == "mxfp4") && !stackedExpert) {if strings.Contains(name, ".v_proj") || strings.Contains(name, ".k_proj") || strings.Contains(name, "down_proj") {- if isAligned(shape, "int8") {- return "int8"+ if e := eightBit(quantNorm); isAligned(shape, e) {+ return e}}}@@ -464,8 +318,7 @@ func GetTensorQuantization(name string, shape []int32, quantize string) string {}var (- expertLayerPrefixRegexp = regexp.MustCompile(`^(?:model\.language_model\.|language_model(?:\.model)?\.|model\.)?layers\.\d+$`)- prequantizedExpertSuffixRegexp = regexp.MustCompile(`^\.(\d+)\.(.+)$`)+ expertLayerPrefixRegexp = regexp.MustCompile(`^(?:model\.language_model\.|language_model(?:\.model)?\.|model\.)?layers\.\d+$`))// ExpertGroupPrefix returns the group prefix for expert tensors that should be packed together.@@ -502,19 +355,6 @@ func ExpertGroupPrefix(tensorName string) string {return ""}-// PackedTensorInput holds metadata for a tensor that will be packed into a multi-tensor blob.-type PackedTensorInput struct {- Name string- Dtype string- Shape []int32- Quantize string // per-tensor quantization type (may differ within group)- Reader io.Reader // safetensors-wrapped tensor data-}--// PackedTensorLayerCreator creates a single blob layer containing multiple packed tensors.-// groupName is the group prefix (e.g., "model.layers.1.mlp.experts").-type PackedTensorLayerCreator func(groupName string, tensors []PackedTensorInput) (LayerInfo, error)-type sourceQuantization struct {Bits int `json:"bits"`GroupSize int `json:"group_size"`@@ -546,19 +386,23 @@ type sourceModelConfig struct {} `json:"text_config"`}-func readSourceModelConfig(modelDir string) (sourceModelConfig, error) {+// readSourceModelConfig parses config.json into the shared sourceModelConfig+// and returns the raw bytes alongside it. The raw bytes are retained on the+// Inventory so architecture-specific factories can parse their own fields+// without re-opening the file.+func readSourceModelConfig(modelDir string) (sourceModelConfig, json.RawMessage, error) {configPath := filepath.Join(modelDir, "config.json")data, err := os.ReadFile(configPath)if err != nil {- return sourceModelConfig{}, err+ return sourceModelConfig{}, nil, err}var cfg sourceModelConfigif err := json.Unmarshal(data, &cfg); err != nil {- return sourceModelConfig{}, err+ return sourceModelConfig{}, nil, err}- return cfg, nil+ return cfg, data, nil}func (cfg sourceModelConfig) Architecture() string {@@ -574,14 +418,7 @@ func (cfg sourceModelConfig) Architecture() string {func (cfg sourceModelConfig) QuantMetadata() map[string]string {// Use the first non-empty quantization config foundvar q sourceQuantization- for _, candidate := range []sourceQuantization{- cfg.Quantization,- cfg.QuantizationConfig,- cfg.CompressionConfig,- cfg.TextConfig.Quantization,- cfg.TextConfig.QuantizationConfig,- cfg.TextConfig.CompressionConfig,- } {+ for _, candidate := range cfg.quantizationConfigs() {if candidate.Bits != 0 {q = candidatebreak@@ -600,14 +437,6 @@ func (cfg sourceModelConfig) QuantMetadata() map[string]string {return metadata}-type sourceQuantizedKind string--const (- sourceQuantizedKindNone sourceQuantizedKind = ""- sourceQuantizedKindPrequantized sourceQuantizedKind = "prequantized"- sourceQuantizedKindSourceFP8 sourceQuantizedKind = "source_fp8"-)-func (cfg sourceModelConfig) quantizationConfigs() []sourceQuantization {return []sourceQuantization{cfg.Quantization,@@ -638,172 +467,7 @@ func (cfg sourceModelConfig) HFFP8WeightBlockSize() (rows, cols int32, ok bool)return 0, 0, false}-func (cfg sourceModelConfig) hasPackedNVFP4Format() bool {- for _, q := range cfg.quantizationConfigs() {- if strings.EqualFold(q.Format, "nvfp4-pack-quantized") {- return true- }- }- return false-}--func inspectSourceQuantization(modelDir string, cfg sourceModelConfig) (sourceQuantizedKind, error) {- // Check for NVIDIA ModelOpt hf_quant_config.json (NVFP4)- if detectModelOptQuantization(modelDir) {- return sourceQuantizedKindPrequantized, nil- }-- entries, err := os.ReadDir(modelDir)- if err != nil {- return sourceQuantizedKindNone, err- }-- hasFP8Scale := false- hasPackedNVFP4 := false- for _, entry := range entries {- if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".safetensors") {- continue- }-- extractor, err := safetensors.OpenForExtraction(filepath.Join(modelDir, entry.Name()))- if err != nil {- return sourceQuantizedKindNone, err- }-- for _, name := range extractor.ListTensors() {- switch {- case strings.HasSuffix(name, ".scales"):- extractor.Close()- return sourceQuantizedKindPrequantized, nil- case strings.HasSuffix(name, ".weight_packed"):- hasPackedNVFP4 = true- case strings.HasSuffix(name, ".weight_scale_inv"):- hasFP8Scale = true- case strings.HasSuffix(name, ".weight_scale"):- hasFP8Scale = true- }- }-- extractor.Close()- }-- if hasPackedNVFP4 && cfg.hasPackedNVFP4Format() {- return sourceQuantizedKindPrequantized, nil- }-- if hasFP8Scale {- if _, _, ok := cfg.HFFP8WeightBlockSize(); ok {- return sourceQuantizedKindSourceFP8, nil- }- }-- return sourceQuantizedKindNone, nil-}--// modelOptQuantConfig represents the hf_quant_config.json format from-// NVIDIA ModelOpt (TensorRT Model Optimizer).-type modelOptQuantConfig struct {- Producer struct {- Name string `json:"name"`- Version string `json:"version"`- } `json:"producer"`- Quantization struct {- QuantAlgo string `json:"quant_algo"`- GroupSize int `json:"group_size"`- ExcludeModules []string `json:"exclude_modules"`- } `json:"quantization"`-}--func detectModelOptQuantization(modelDir string) bool {- data, err := os.ReadFile(filepath.Join(modelDir, "hf_quant_config.json"))- if err != nil {- return false- }- var cfg modelOptQuantConfig- if err := json.Unmarshal(data, &cfg); err != nil {- return false- }- return strings.ToUpper(cfg.Quantization.QuantAlgo) == "NVFP4"-}--func resolveEffectiveQuantization(cfg sourceModelConfig, sourceKind sourceQuantizedKind, requested string) (string, error) {- return resolveEffectiveQuantizationForFlag(cfg, sourceKind, requested, "--quantize")-}--func resolveEffectiveQuantizationForFlag(cfg sourceModelConfig, sourceKind sourceQuantizedKind, requested, flagName string) (string, error) {- switch sourceKind {- case sourceQuantizedKindNone:- return requested, nil- case sourceQuantizedKindPrequantized:- if requested != "" {- return "", fmt.Errorf("cannot requantize already-quantized source model with %s %q", flagName, requested)- }- return "", nil- case sourceQuantizedKindSourceFP8:- rows, cols, ok := cfg.HFFP8WeightBlockSize()- if !ok {- return "", fmt.Errorf("fp8 source model missing weight_block_size metadata")- }- if rows != 128 || cols != 128 {- return "", fmt.Errorf("unsupported fp8 source block size %dx%d", rows, cols)- }- if requested != "" {- requested = normalizeQuantType(requested)- switch requested {- case "nvfp4", "mxfp4", "mxfp8":- return requested, nil- default:- return "", fmt.Errorf("cannot convert already-quantized fp8 source model with %s %q", flagName, requested)- }- }- return "mxfp8", nil- default:- return "", fmt.Errorf("unsupported source quantization kind %q", sourceKind)- }-}--func importQuantizationStatus(sourceKind sourceQuantizedKind, effectiveQuantize string) string {- if effectiveQuantize == "" {- if sourceKind == sourceQuantizedKindPrequantized {- return ", preserving source quantization"- }- return ""- }- switch sourceKind {- case sourceQuantizedKindSourceFP8:- return fmt.Sprintf(", converting source E4M3 block-FP8 to MLX %s", effectiveQuantize)- default:- return fmt.Sprintf(", quantizing to %s", effectiveQuantize)- }-}--type tensorImportTransform interface {- skipTensor(name string) bool- transformTensor(td *safetensors.TensorData) ([]*safetensors.TensorData, error)- quantizationType(name string, shape []int32, quantize string) string-}--type sourceFP8TensorImportTransform interface {- sourceFP8TensorQuantization(name string, shape []int32, requested string, fallback string) string- sourceFP8BF16Quantization(name string, shape []int32, requested string) string-}--type noopImportTransform struct{}--func (noopImportTransform) skipTensor(string) bool { return false }--func (noopImportTransform) transformTensor(td *safetensors.TensorData) ([]*safetensors.TensorData, error) {- if td == nil {- return nil, nil- }- return []*safetensors.TensorData{td}, nil-}--func (noopImportTransform) quantizationType(name string, shape []int32, quantize string) string {- return GetTensorQuantization(name, shape, quantize)-}--type tensorImportTransformFactory func(modelDir string, cfg sourceModelConfig) (tensorImportTransform, error)+type tensorImportTransformFactory func(rawConfig json.RawMessage) (quantizePolicy, error)var tensorImportTransformRegistry = map[string]tensorImportTransformFactory{"Qwen3_5ForCausalLM": newQwen35ImportTransform,@@ -827,558 +491,11 @@ var tensorImportTransformRegistry = map[string]tensorImportTransformFactory{"gemma4_unified_assistant": newGemma4ImportTransform,}-func newTensorImportTransform(modelDir string, cfg sourceModelConfig) (tensorImportTransform, error) {- if factory, ok := tensorImportTransformRegistry[cfg.Architecture()]; ok {- return factory(modelDir, cfg)- }- return noopImportTransform{}, nil-}--// CreateSafetensorsModel imports a standard safetensors model from a directory.-// This handles Hugging Face style models with config.json and *.safetensors files.-// Stores each tensor as a separate blob for fine-grained deduplication.-// Expert tensors are packed into per-layer blobs when createPackedLayer is non-nil.-// If quantize is non-empty (e.g., "int8"), eligible tensors will be quantized.-func CreateSafetensorsModel(modelName, modelDir, quantize string, createLayer LayerCreator, createTensorLayer QuantizingTensorLayerCreator, writeManifest ManifestWriter, fn func(status string), createPackedLayer ...PackedTensorLayerCreator) error {- var layers []LayerInfo- var configLayer LayerInfo- sourceConfig, err := readSourceModelConfig(modelDir)- if err != nil {- return fmt.Errorf("failed to read source config.json: %w", err)- }- sourceQuantKind, err := inspectSourceQuantization(modelDir, sourceConfig)- if err != nil {- return fmt.Errorf("failed to inspect source quantization: %w", err)- }- effectiveQuantize, err := resolveEffectiveQuantization(sourceConfig, sourceQuantKind, quantize)- if err != nil {- return err- }- sourceQuantMetadata := sourceConfig.QuantMetadata()- sourceTensorFiles, err := readSourceTensorFiles(modelDir)- if err != nil {- return fmt.Errorf("failed to read source tensor index: %w", err)- }- importTransform, err := newTensorImportTransform(modelDir, sourceConfig)- if err != nil {- return fmt.Errorf("failed to construct import transform for architecture %q: %w", sourceConfig.Architecture(), err)- }- sourceFP8Transform, _ := importTransform.(sourceFP8TensorImportTransform)-- // Resolve the optional packed layer creator- var packedCreator PackedTensorLayerCreator- if len(createPackedLayer) > 0 {- packedCreator = createPackedLayer[0]- }- // Accumulate expert tensors by group prefix for packing.- // Readers reference file-backed SectionReaders, so we keep extractors- // open until each group is flushed to avoid buffering tensor data in memory.- expertGroups := make(map[string][]PackedTensorInput)- prequantizedExpertGroups := make(map[string][]*safetensors.TensorData)- var expertGroupOrder []string-- // Track open extractors so we can close them after flushing groups- var openExtractors []*safetensors.TensorExtractor- crossFileExtractors := make(map[string]*safetensors.TensorExtractor)-- closeExtractors := func() {- for _, ext := range openExtractors {- ext.Close()- }- openExtractors = nil- for _, ext := range crossFileExtractors {- ext.Close()- }- clear(crossFileExtractors)- }-- entries, err := os.ReadDir(modelDir)- if err != nil {- return fmt.Errorf("failed to read directory: %w", err)- }-- // Process all safetensors files- for _, entry := range entries {- if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".safetensors") {- continue- }-- stPath := filepath.Join(modelDir, entry.Name())-- // Extract individual tensors from safetensors file- extractor, err := safetensors.OpenForExtraction(stPath)- if err != nil {- closeExtractors()- return fmt.Errorf("failed to open %s: %w", stPath, err)- }-- tensorNames := extractor.ListTensors()- tensorSet := make(map[string]struct{}, len(tensorNames))- for _, name := range tensorNames {- tensorSet[name] = struct{}{}- }- fn(fmt.Sprintf("importing %s (%d tensors%s)", entry.Name(), len(tensorNames), importQuantizationStatus(sourceQuantKind, effectiveQuantize)))-- // Track whether this extractor has expert tensors that need to stay open- hasExpertTensors := false-- for _, tensorName := range tensorNames {- if importTransform.skipTensor(tensorName) {- continue- }- if shouldSkipSourceCompanion(tensorName, tensorSet, sourceTensorFiles) {- continue- }- sourceFP8ScaleName, hasSourceFP8Scale := sourceFP8Companion(tensorName, tensorSet, sourceTensorFiles)-- td, err := extractor.GetTensor(tensorName)- if err != nil {- extractor.Close()- closeExtractors()- return fmt.Errorf("failed to get tensor %s: %w", tensorName, err)- }-- if packedCreator != nil {- if packedWeightName := strings.TrimSuffix(tensorName, "_packed"); packedWeightName != tensorName {- groupPrefix := ExpertGroupPrefix(packedWeightName)- if groupPrefix != "" {- packedTensors, ok, err := packedNVFP4TensorData(modelDir, extractor, crossFileExtractors, td, tensorName, tensorSet, sourceTensorFiles)- if err != nil {- extractor.Close()- closeExtractors()- return err- }- if ok {- hasExpertTensors = true- if _, exists := prequantizedExpertGroups[groupPrefix]; !exists {- expertGroupOrder = append(expertGroupOrder, groupPrefix)- }- prequantizedExpertGroups[groupPrefix] = append(prequantizedExpertGroups[groupPrefix], packedTensors...)- continue- }- }- }- }-- if effectiveQuantize == "" {- layer, ok, err := createPrequantizedLayer(extractor, td, tensorName, tensorSet, sourceQuantMetadata, createLayer)- if err != nil {- extractor.Close()- closeExtractors()- return err- }- if ok {- layers = append(layers, layer)- continue- }- layer, ok, err = createPackedNVFP4Layer(modelDir, extractor, crossFileExtractors, td, tensorName, tensorSet, sourceTensorFiles, sourceQuantMetadata, createLayer)- if err != nil {- extractor.Close()- closeExtractors()- return err- }- if ok {- layers = append(layers, layer)- continue- }- // Try ModelOpt NVFP4 format (weight_scale + weight_scale_2)- layer, ok, err = createModelOptFP4Layer(extractor, td, tensorName, tensorSet, sourceQuantMetadata, createLayer)- if err != nil {- extractor.Close()- closeExtractors()- return err- }- if ok {- layers = append(layers, layer)- continue- }- }-- outputTensors, err := importTransform.transformTensor(td)- if err != nil {- extractor.Close()- closeExtractors()- return fmt.Errorf("failed to transform tensor %s: %w", tensorName, err)- }-- for _, outTD := range outputTensors {- // Determine quantization type for this tensor (empty string if not quantizing)- // GetTensorQuantization handles mixed-precision (e.g., Q8 for attention, Q4 for FFN)- quantizeType := ""- switch {- case sourceQuantKind == sourceQuantizedKindSourceFP8 && hasSourceFP8Scale:- quantizeType = importTransform.quantizationType(outTD.Name, outTD.Shape, effectiveQuantize)- if quantizeType == "" && effectiveQuantize == "mxfp8" {- // Source FP8 tensors are already quantized weights and small- // synthetic tests may not pass the generic import size filter.- quantizeType = "mxfp8"- }- if sourceFP8Transform != nil {- quantizeType = sourceFP8Transform.sourceFP8TensorQuantization(outTD.Name, outTD.Shape, quantize, quantizeType)- } else {- quantizeType = sourceFP8TensorQuantization(outTD.Name, outTD.Shape, quantize, quantizeType)- }- case sourceQuantKind == sourceQuantizedKindSourceFP8:- if sourceFP8Transform != nil {- quantizeType = sourceFP8Transform.sourceFP8BF16Quantization(outTD.Name, outTD.Shape, quantize)- } else {- quantizeType = sourceFP8BF16PromotionQuantization(outTD.Name, outTD.Shape, quantize)- }- case effectiveQuantize != "":- quantizeType = importTransform.quantizationType(outTD.Name, outTD.Shape, effectiveQuantize)- }- reader := outTD.SafetensorsReader()- if hasSourceFP8Scale {- if len(outputTensors) != 1 {- extractor.Close()- closeExtractors()- return fmt.Errorf("source fp8 tensor %s rewrote into %d tensors; only 1:1 rewrites are supported", tensorName, len(outputTensors))- }- if quantizeType == "" {- extractor.Close()- closeExtractors()- return fmt.Errorf("source fp8 tensor %s was not scheduled for %s conversion", tensorName, effectiveQuantize)- }- scaleTD, err := getTensorFromSource(modelDir, extractor, crossFileExtractors, sourceTensorFiles, sourceFP8ScaleName)- if err != nil {- extractor.Close()- closeExtractors()- return fmt.Errorf("failed to get fp8 scale tensor %s: %w", sourceFP8ScaleName, err)- }- reader = buildSourceFP8Reader(outTD, scaleTD)- }-- // Check if this tensor belongs to an expert group for packing- groupPrefix := ""- if packedCreator != nil {- groupPrefix = ExpertGroupPrefix(outTD.Name)- }-- if groupPrefix != "" {- // Accumulate expert tensor for packed blob.- // The Reader uses a file-backed SectionReader, so we must- // keep the extractor open until this group is flushed.- hasExpertTensors = true- if _, exists := expertGroups[groupPrefix]; !exists {- expertGroupOrder = append(expertGroupOrder, groupPrefix)- }- expertGroups[groupPrefix] = append(expertGroups[groupPrefix], PackedTensorInput{- Name: outTD.Name,- Dtype: outTD.Dtype,- Shape: outTD.Shape,- Quantize: quantizeType,- Reader: reader,- })- } else {- // Store as minimal safetensors format (88 bytes header overhead)- // This enables native mmap loading via mlx_load_safetensors- // createTensorLayer returns multiple layers if quantizing (weight + scales)- newLayers, err := createTensorLayer(reader, outTD.Name, outTD.Dtype, outTD.Shape, quantizeType)- if err != nil {- extractor.Close()- closeExtractors()- return fmt.Errorf("failed to create layer for %s: %w", outTD.Name, err)- }- layers = append(layers, newLayers...)- }- }- }-- if hasExpertTensors {- // Keep extractor open - readers still reference its file handle- openExtractors = append(openExtractors, extractor)- } else {- extractor.Close()- }- }-- // Process accumulated expert groups into packed blobs, then close extractors- if packedCreator != nil {- sort.Strings(expertGroupOrder)- for _, groupName := range expertGroupOrder {- if tensors := prequantizedExpertGroups[groupName]; len(tensors) > 0 {- layer, ok, err := createPackedNVFP4ExpertGroupLayer(groupName, tensors, createLayer)- if err != nil {- closeExtractors()- return fmt.Errorf("failed to create packed prequantized layer for %s: %w", groupName, err)- }- if ok {- layers = append(layers, layer)- continue- }- layer, err = createLayer(- safetensors.BuildPackedSafetensorsReaderWithMetadata(tensors, map[string]string{- "quant_type": "nvfp4",- "group_size": "16",- }),- "application/vnd.ollama.image.tensor",- groupName,- )- if err != nil {- closeExtractors()- return fmt.Errorf("failed to create packed prequantized layer for %s: %w", groupName, err)- }- layers = append(layers, layer)- continue- }- tensors := expertGroups[groupName]- fn(fmt.Sprintf("packing %s (%d tensors)", groupName, len(tensors)))- layer, err := packedCreator(groupName, tensors)- if err != nil {- closeExtractors()- return fmt.Errorf("failed to create packed layer for %s: %w", groupName, err)- }- layers = append(layers, layer)- }- }- closeExtractors()-- // Process all JSON config files- for _, entry := range entries {- if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".json") {- continue- }-- // Skip the index file as we don't need it after extraction- if entry.Name() == "model.safetensors.index.json" {- continue- }-- cfgPath := entry.Name()- fullPath := filepath.Join(modelDir, cfgPath)-- fn(fmt.Sprintf("importing config %s", cfgPath))-- f, err := os.Open(fullPath)- if err != nil {- return fmt.Errorf("failed to open %s: %w", cfgPath, err)- }-- layer, err := createLayer(f, "application/vnd.ollama.image.json", cfgPath)- f.Close()- if err != nil {- return fmt.Errorf("failed to create layer for %s: %w", cfgPath, err)- }-- // Use config.json as the config layer- if cfgPath == "config.json" {- configLayer = layer- }-- layers = append(layers, layer)- }-- if configLayer.Digest == "" {- return fmt.Errorf("config.json not found in %s", modelDir)- }-- fn(fmt.Sprintf("writing manifest for %s", modelName))-- if err := writeManifest(modelName, configLayer, layers); err != nil {- return fmt.Errorf("failed to write manifest: %w", err)- }-- fn(fmt.Sprintf("successfully imported %s with %d layers", modelName, len(layers)))- return nil-}--func normalizeRequestedQuantization(flagName, quantize string) (string, error) {- q := normalizeQuantType(strings.TrimSpace(quantize))- switch q {- case "", "int4", "int8", "nvfp4", "mxfp4", "mxfp8":- return q, nil- default:- return "", fmt.Errorf("unsupported %s %q: supported types are int4, int8, nvfp4, mxfp4, mxfp8", flagName, quantize)- }-}--// CreateDraftSafetensorsLayers imports an assistant/draft safetensors model-// into prefixed tensor and config layers. When draftQuantize is non-empty,-// eligible draft tensors are quantized with the same per-architecture policy-// used by target safetensors imports.-func CreateDraftSafetensorsLayers(modelDir, tensorPrefix, configPrefix, draftQuantize string, createLayer LayerCreator, createTensorLayer QuantizingTensorLayerCreator, fn func(status string)) ([]LayerInfo, error) {- if tensorPrefix == "" {- return nil, fmt.Errorf("draft tensor prefix must not be empty")- }- if configPrefix == "" {- return nil, fmt.Errorf("draft config prefix must not be empty")- }- effectiveQuantize, err := normalizeRequestedQuantization("--draft-quantize", draftQuantize)- if err != nil {- return nil, err- }-- var importTransform tensorImportTransform = noopImportTransform{}- if effectiveQuantize != "" {- sourceConfig, err := readSourceModelConfig(modelDir)- if err != nil {- return nil, fmt.Errorf("failed to read draft config.json: %w", err)- }- sourceQuantKind, err := inspectSourceQuantization(modelDir, sourceConfig)- if err != nil {- return nil, fmt.Errorf("failed to inspect draft quantization: %w", err)- }- effectiveQuantize, err = resolveEffectiveQuantizationForFlag(sourceConfig, sourceQuantKind, effectiveQuantize, "--draft-quantize")- if err != nil {- return nil, err- }- importTransform, err = newTensorImportTransform(modelDir, sourceConfig)- if err != nil {- return nil, fmt.Errorf("failed to construct draft import transform for architecture %q: %w", sourceConfig.Architecture(), err)- }- }-- entries, err := os.ReadDir(modelDir)- if err != nil {- return nil, fmt.Errorf("failed to read draft directory: %w", err)- }-- var layers []LayerInfo- for _, entry := range entries {- if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".safetensors") {- continue- }-- stPath := filepath.Join(modelDir, entry.Name())- extractor, err := safetensors.OpenForExtraction(stPath)- if err != nil {- return nil, fmt.Errorf("failed to open draft %s: %w", stPath, err)- }-- tensorNames := extractor.ListTensors()- fn(fmt.Sprintf("importing draft %s (%d tensors%s)", entry.Name(), len(tensorNames), importQuantizationStatus(sourceQuantizedKindNone, effectiveQuantize)))- for _, tensorName := range tensorNames {- if importTransform.skipTensor(tensorName) {- continue- }- td, err := extractor.GetTensor(tensorName)- if err != nil {- extractor.Close()- return nil, fmt.Errorf("failed to get draft tensor %s: %w", tensorName, err)- }-- outTDs, err := importTransform.transformTensor(td)- if err != nil {- extractor.Close()- return nil, fmt.Errorf("failed to transform draft tensor %s: %w", tensorName, err)- }- for _, transformedTD := range outTDs {- if transformedTD == nil {- continue- }- outTD := transformedTD.WithName(tensorPrefix + transformedTD.Name)- quantizeType := ""- if effectiveQuantize != "" {- quantizeType = importTransform.quantizationType(outTD.Name, outTD.Shape, effectiveQuantize)- if isEmbedTokensWeight(outTD.Name) {- quantizeType = ""- }- }- newLayers, err := createTensorLayer(outTD.SafetensorsReader(), outTD.Name, outTD.Dtype, outTD.Shape, quantizeType)- if err != nil {- extractor.Close()- return nil, fmt.Errorf("failed to create draft layer for %s: %w", tensorName, err)- }- layers = append(layers, newLayers...)- }- }- extractor.Close()- }-- for _, entry := range entries {- if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".json") {- continue- }- if entry.Name() == "model.safetensors.index.json" {- continue- }-- cfgPath := entry.Name()- fullPath := filepath.Join(modelDir, cfgPath)- fn(fmt.Sprintf("importing draft config %s", cfgPath))-- f, err := os.Open(fullPath)- if err != nil {- return nil, fmt.Errorf("failed to open draft %s: %w", cfgPath, err)- }- layer, err := createLayer(f, "application/vnd.ollama.image.json", path.Join(configPrefix, cfgPath))- f.Close()- if err != nil {- return nil, fmt.Errorf("failed to create draft config layer for %s: %w", cfgPath, err)- }- layers = append(layers, layer)- }-- return layers, nil-}--func shouldSkipSourceCompanion(name string, tensorSet map[string]struct{}, sourceTensorFiles map[string]string) bool {- switch {- case strings.HasSuffix(name, ".scales"):- _, ok := tensorSet[strings.TrimSuffix(name, ".scales")+".weight"]- return ok- case strings.HasSuffix(name, ".biases"):- _, ok := tensorSet[strings.TrimSuffix(name, ".biases")+".weight"]- return ok- case strings.HasSuffix(name, ".weight_scale_inv"):- _, ok := tensorSet[strings.TrimSuffix(name, "_scale_inv")]- return ok- case strings.HasSuffix(name, ".weight_scale"):- base := strings.TrimSuffix(name, "_scale")- if _, ok := tensorSet[base]; ok {- return true- }- if _, ok := sourceTensorFiles[base+"_packed"]; ok {- return true- }- _, ok := tensorSet[base+"_packed"]- return ok- // ModelOpt NVFP4 companion tensors- case strings.HasSuffix(name, ".weight_scale_2"):- _, ok := tensorSet[strings.TrimSuffix(name, "_scale_2")]- return ok- case strings.HasSuffix(name, ".input_scale"):- // Activation scale for ModelOpt — not needed for weight-only inference- base := strings.TrimSuffix(name, ".input_scale")- _, ok := tensorSet[base+".weight"]- return ok- case strings.HasSuffix(name, ".weight_global_scale"):- base := strings.TrimSuffix(name, ".weight_global_scale")- if _, ok := sourceTensorFiles[base+".weight_packed"]; ok {- return true- }- _, ok := tensorSet[base+".weight_packed"]- return ok- case strings.HasSuffix(name, ".input_global_scale"):- base := strings.TrimSuffix(name, ".input_global_scale")- if _, ok := sourceTensorFiles[base+".weight_packed"]; ok {- return true- }- _, ok := tensorSet[base+".weight_packed"]- return ok- default:- return false- }-}--func sourceFP8Companion(weightName string, tensorSet map[string]struct{}, sourceTensorFiles map[string]string) (scaleName string, ok bool) {- if !strings.HasSuffix(weightName, ".weight") {- return "", false- }-- scaleName = weightName + "_scale_inv"- if _, ok = tensorSet[scaleName]; ok {- return scaleName, true- }- if _, ok = sourceTensorFiles[scaleName]; ok {- return scaleName, true+func newTensorImportTransform(inv Inventory) (quantizePolicy, error) {+ if factory, ok := tensorImportTransformRegistry[inv.Config.Architecture()]; ok {+ return factory(inv.RawConfig)}- scaleName = weightName + "_scale"- if _, ok = tensorSet[scaleName]; ok {- return scaleName, true- }- _, ok = sourceTensorFiles[scaleName]- return scaleName, ok+ return defaultQuantPolicy{}, nil}func buildSourceFP8Reader(weightTD, scaleTD *safetensors.TensorData) io.Reader {@@ -1389,404 +506,6 @@ func buildSourceFP8Reader(weightTD, scaleTD *safetensors.TensorData) io.Reader {return safetensors.BuildPackedSafetensorsReader([]*safetensors.TensorData{weightTD, scaleTD.WithName(scaleName)})}-func createPrequantizedLayer(- extractor *safetensors.TensorExtractor,- td *safetensors.TensorData,- tensorName string,- tensorSet map[string]struct{},- metadata map[string]string,- createLayer LayerCreator,-) (LayerInfo, bool, error) {- scaleName, biasName, ok := prequantizedCompanions(tensorName, tensorSet)- if !ok {- return LayerInfo{}, false, nil- }-- tensors := []*safetensors.TensorData{td.WithName(tensorName)}-- scaleTD, err := extractor.GetTensor(scaleName)- if err != nil {- return LayerInfo{}, false, fmt.Errorf("failed to get tensor %s: %w", scaleName, err)- }- tensors = append(tensors, scaleTD.WithName(tensorName+".scale"))-- if biasName != "" {- biasTD, err := extractor.GetTensor(biasName)- if err != nil {- return LayerInfo{}, false, fmt.Errorf("failed to get tensor %s: %w", biasName, err)- }- tensors = append(tensors, biasTD.WithName(tensorName+".bias"))- }-- layer, err := createLayer(- safetensors.BuildPackedSafetensorsReaderWithMetadata(tensors, metadata),- "application/vnd.ollama.image.tensor",- tensorName,- )- if err != nil {- return LayerInfo{}, false, fmt.Errorf("failed to create prequantized layer for %s: %w", tensorName, err)- }- return layer, true, nil-}--func prequantizedCompanions(weightName string, tensorSet map[string]struct{}) (scaleName, biasName string, ok bool) {- if !strings.HasSuffix(weightName, ".weight") {- return "", "", false- }-- base := strings.TrimSuffix(weightName, ".weight")- scaleName = base + ".scales"- if _, ok := tensorSet[scaleName]; !ok {- return "", "", false- }-- biasName = base + ".biases"- if _, ok := tensorSet[biasName]; !ok {- biasName = ""- }- return scaleName, biasName, true-}--// createModelOptFP4Layer creates a pre-quantized layer from NVIDIA ModelOpt-// NVFP4 tensors. The weight (U8) and scale (F8_E4M3 stored as uint8) are-// packed with the per-tensor global scale (weight_scale_2) into a single-// safetensors blob. The tensor names are mapped to our standard format:-// - source.weight → tensorName (weight data, kept as-is)-// - source.weight_scale → tensorName.scale (FP8 E4M3 bytes as uint8)-// - source.weight_scale_2 → tensorName.global_scale (F32 scalar)-func createModelOptFP4Layer(- extractor *safetensors.TensorExtractor,- td *safetensors.TensorData,- tensorName string,- tensorSet map[string]struct{},- metadata map[string]string,- createLayer LayerCreator,-) (LayerInfo, bool, error) {- scaleName, globalScaleName, ok := modelOptFP4Companions(tensorName, tensorSet)- if !ok {- return LayerInfo{}, false, nil- }-- // NVIDIA packs FP4 as U8 (2 values/byte), MLX expects U32 (8 values/uint32).- // Repack: view the U8 data as U32 (4 consecutive bytes → 1 uint32) and- // adjust the shape from [out, in/2] to [out, in/8].- weightTD := td.WithName(tensorName)- if strings.ToUpper(weightTD.Dtype) == "U8" && len(weightTD.Shape) == 2 {- weightTD.Dtype = "U32"- weightTD.Shape = []int32{weightTD.Shape[0], weightTD.Shape[1] / 4}- }- tensors := []*safetensors.TensorData{weightTD}-- scaleTD, err := extractor.GetTensor(scaleName)- if err != nil {- return LayerInfo{}, false, fmt.Errorf("failed to get tensor %s: %w", scaleName, err)- }- // F8_E4M3 scales stored as uint8 — fix the dtype for our loader- scaleRenamed := scaleTD.WithName(tensorName + ".scale")- if strings.ToUpper(scaleRenamed.Dtype) == "F8_E4M3" {- scaleRenamed.Dtype = "U8"- }- tensors = append(tensors, scaleRenamed)-- if globalScaleName != "" {- gsTD, err := extractor.GetTensor(globalScaleName)- if err != nil {- return LayerInfo{}, false, fmt.Errorf("failed to get tensor %s: %w", globalScaleName, err)- }- gsTD, err = validateScalarFloat32TensorData(gsTD, tensorName+".global_scale")- if err != nil {- return LayerInfo{}, false, fmt.Errorf("failed to normalize tensor %s: %w", globalScaleName, err)- }- tensors = append(tensors, gsTD)- }-- // Add nvfp4 quant metadata- md := make(map[string]string)- for k, v := range metadata {- md[k] = v- }- md["quant_type"] = "nvfp4"-- layer, err := createLayer(- safetensors.BuildPackedSafetensorsReaderWithMetadata(tensors, md),- "application/vnd.ollama.image.tensor",- tensorName,- )- if err != nil {- return LayerInfo{}, false, fmt.Errorf("failed to create ModelOpt FP4 layer for %s: %w", tensorName, err)- }- return layer, true, nil-}--// createPackedNVFP4Layer creates a pre-quantized layer from packed NVFP4-// tensors that use the newer source layout:-// - source.weight_packed -> tensorName (U32 repacked weight)-// - source.weight_scale -> tensorName.scale-// - source.weight_global_scale -> reciprocal stored as tensorName.global_scale-// - source.input_global_scale -> ignored for weight-only inference-func createPackedNVFP4Layer(- modelDir string,- extractor *safetensors.TensorExtractor,- crossFileExtractors map[string]*safetensors.TensorExtractor,- td *safetensors.TensorData,- tensorName string,- tensorSet map[string]struct{},- sourceTensorFiles map[string]string,- metadata map[string]string,- createLayer LayerCreator,-) (LayerInfo, bool, error) {- weightName, scaleName, weightGlobalScaleName, _, ok := packedNVFP4Companions(tensorName, tensorSet, sourceTensorFiles)- if !ok {- return LayerInfo{}, false, nil- }-- weightTD := td.WithName(weightName)- if strings.ToUpper(weightTD.Dtype) == "U8" && len(weightTD.Shape) == 2 {- weightTD.Dtype = "U32"- weightTD.Shape = []int32{weightTD.Shape[0], weightTD.Shape[1] / 4}- }- tensors := []*safetensors.TensorData{weightTD}-- scaleTD, err := getTensorFromSource(modelDir, extractor, crossFileExtractors, sourceTensorFiles, scaleName)- if err != nil {- return LayerInfo{}, false, fmt.Errorf("failed to get tensor %s: %w", scaleName, err)- }- scaleRenamed := scaleTD.WithName(weightName + ".scale")- if strings.ToUpper(scaleRenamed.Dtype) == "F8_E4M3" {- scaleRenamed.Dtype = "U8"- }- tensors = append(tensors, scaleRenamed)-- if weightGlobalScaleName != "" {- gsTD, err := getTensorFromSource(modelDir, extractor, crossFileExtractors, sourceTensorFiles, weightGlobalScaleName)- if err != nil {- return LayerInfo{}, false, fmt.Errorf("failed to get tensor %s: %w", weightGlobalScaleName, err)- }- gsTD, err = invertScalarFloat32TensorData(gsTD, weightName+".global_scale")- if err != nil {- return LayerInfo{}, false, fmt.Errorf("failed to normalize tensor %s: %w", weightGlobalScaleName, err)- }- tensors = append(tensors, gsTD)- }-- md := make(map[string]string)- for k, v := range metadata {- md[k] = v- }- md["quant_type"] = "nvfp4"- if _, ok := md["group_size"]; !ok {- md["group_size"] = "16"- }-- layer, err := createLayer(- safetensors.BuildPackedSafetensorsReaderWithMetadata(tensors, md),- "application/vnd.ollama.image.tensor",- weightName,- )- if err != nil {- return LayerInfo{}, false, fmt.Errorf("failed to create packed NVFP4 layer for %s: %w", tensorName, err)- }- return layer, true, nil-}--type stackedTempTensor struct {- tensor *safetensors.TensorData- file *os.File- path string-}--func createPackedNVFP4ExpertGroupLayer(groupName string, tensors []*safetensors.TensorData, createLayer LayerCreator) (LayerInfo, bool, error) {- stacked, metadata, ok, err := stackPackedNVFP4ExpertGroup(groupName, tensors)- if err != nil || !ok {- return LayerInfo{}, ok, err- }- defer func() {- for _, td := range stacked {- if td.file != nil {- td.file.Close()- }- if td.path != "" {- os.Remove(td.path)- }- }- }()-- packed := make([]*safetensors.TensorData, 0, len(stacked))- for _, td := range stacked {- packed = append(packed, td.tensor)- }- layer, err := createLayer(- safetensors.BuildPackedSafetensorsReaderWithMetadata(packed, metadata),- "application/vnd.ollama.image.tensor",- groupName,- )- if err != nil {- return LayerInfo{}, true, err- }- return layer, true, nil-}--func stackPackedNVFP4ExpertGroup(groupName string, tensors []*safetensors.TensorData) ([]stackedTempTensor, map[string]string, bool, error) {- if !strings.HasSuffix(groupName, ".experts") {- return nil, nil, false, nil- }-- type namedExpertTensor struct {- expert int- name string- td *safetensors.TensorData- }-- grouped := make(map[string][]namedExpertTensor)- for _, td := range tensors {- suffix := strings.TrimPrefix(td.Name, groupName)- m := prequantizedExpertSuffixRegexp.FindStringSubmatch(suffix)- if m == nil {- return nil, nil, false, nil- }- expert, err := strconv.Atoi(m[1])- if err != nil {- return nil, nil, false, fmt.Errorf("invalid expert index in %q: %w", td.Name, err)- }- grouped[m[2]] = append(grouped[m[2]], namedExpertTensor{- expert: expert,- name: td.Name,- td: td,- })- }- if len(grouped) == 0 {- return nil, nil, false, nil- }-- groupBase := strings.TrimSuffix(groupName, ".experts") + ".switch_mlp."- names := make([]string, 0, len(grouped))- for name := range grouped {- names = append(names, name)- }- sort.Strings(names)-- var stacked []stackedTempTensor- metadata := map[string]string{- "quant_type": "nvfp4",- "group_size": "16",- }- cleanup := func() {- for _, td := range stacked {- if td.file != nil {- td.file.Close()- }- if td.path != "" {- os.Remove(td.path)- }- }- }-- for _, name := range names {- if strings.HasSuffix(name, ".input_global_scale") {- continue- }- experts := grouped[name]- sort.Slice(experts, func(i, j int) bool { return experts[i].expert < experts[j].expert })- if len(experts) == 0 {- continue- }-- stackedName := groupBase + name- baseShape := append([]int32(nil), experts[0].td.Shape...)- stackedShape := make([]int32, 0, len(baseShape)+1)- stackedShape = append(stackedShape, int32(len(experts)))- switch {- case strings.HasSuffix(name, ".global_scale"), strings.HasSuffix(name, ".input_global_scale"):- stackedShape = append(stackedShape, 1, 1)- default:- stackedShape = append(stackedShape, baseShape...)- }-- f, err := os.CreateTemp("", "ollama-packed-nvfp4-*.bin")- if err != nil {- cleanup()- return nil, nil, false, fmt.Errorf("create temp tensor for %s: %w", stackedName, err)- }-- var size int64- for _, expert := range experts {- if expert.td.Dtype != experts[0].td.Dtype || !slices.Equal(expert.td.Shape, experts[0].td.Shape) {- f.Close()- os.Remove(f.Name())- cleanup()- return nil, nil, false, fmt.Errorf("mismatched expert tensor layout in %s", stackedName)- }- written, err := io.Copy(f, expert.td.Reader())- if err != nil {- f.Close()- os.Remove(f.Name())- cleanup()- return nil, nil, false, fmt.Errorf("stack tensor %s: %w", expert.name, err)- }- size += written- }-- stacked = append(stacked, stackedTempTensor{- tensor: safetensors.NewTensorDataFromReaderAt(stackedName, experts[0].td.Dtype, stackedShape, f, size),- file: f,- path: f.Name(),- })-- if strings.HasSuffix(name, ".weight") {- metadata[stackedName+".quant_type"] = "nvfp4"- metadata[stackedName+".group_size"] = "16"- }- }-- return stacked, metadata, true, nil-}--func packedNVFP4TensorData(- modelDir string,- extractor *safetensors.TensorExtractor,- crossFileExtractors map[string]*safetensors.TensorExtractor,- td *safetensors.TensorData,- tensorName string,- tensorSet map[string]struct{},- sourceTensorFiles map[string]string,-) ([]*safetensors.TensorData, bool, error) {- weightName, scaleName, weightGlobalScaleName, _, ok := packedNVFP4Companions(tensorName, tensorSet, sourceTensorFiles)- if !ok {- return nil, false, nil- }-- weightTD := td.WithName(weightName)- if strings.ToUpper(weightTD.Dtype) == "U8" && len(weightTD.Shape) == 2 {- weightTD.Dtype = "U32"- weightTD.Shape = []int32{weightTD.Shape[0], weightTD.Shape[1] / 4}- }- tensors := []*safetensors.TensorData{weightTD}-- scaleTD, err := getTensorFromSource(modelDir, extractor, crossFileExtractors, sourceTensorFiles, scaleName)- if err != nil {- return nil, false, fmt.Errorf("failed to get tensor %s: %w", scaleName, err)- }- scaleRenamed := scaleTD.WithName(weightName + ".scale")- if strings.ToUpper(scaleRenamed.Dtype) == "F8_E4M3" {- scaleRenamed.Dtype = "U8"- }- tensors = append(tensors, scaleRenamed)-- if weightGlobalScaleName != "" {- gsTD, err := getTensorFromSource(modelDir, extractor, crossFileExtractors, sourceTensorFiles, weightGlobalScaleName)- if err != nil {- return nil, false, fmt.Errorf("failed to get tensor %s: %w", weightGlobalScaleName, err)- }- gsTD, err = invertScalarFloat32TensorData(gsTD, weightName+".global_scale")- if err != nil {- return nil, false, fmt.Errorf("failed to normalize tensor %s: %w", weightGlobalScaleName, err)- }- tensors = append(tensors, gsTD)- }-- return tensors, true, nil-}-func validateScalarFloat32TensorData(td *safetensors.TensorData, name string) (*safetensors.TensorData, error) {if td == nil {return nil, nil@@ -1827,56 +546,6 @@ func invertScalarFloat32TensorData(td *safetensors.TensorData, name string) (*sareturn safetensors.NewTensorDataFromBytes(name, td.Dtype, td.Shape, out), nil}-// modelOptFP4Companions finds the companion tensors for a ModelOpt NVFP4-// quantized weight: weight_scale (per-group FP8 E4M3 scales) and optional-// weight_scale_2 (per-tensor global scale).-func modelOptFP4Companions(weightName string, tensorSet map[string]struct{}) (scaleName, globalScaleName string, ok bool) {- if !strings.HasSuffix(weightName, ".weight") {- return "", "", false- }-- scaleName = weightName + "_scale"- if _, ok := tensorSet[scaleName]; !ok {- return "", "", false- }-- globalScaleName = weightName + "_scale_2"- if _, ok := tensorSet[globalScaleName]; !ok {- globalScaleName = ""- }- return scaleName, globalScaleName, true-}--func packedNVFP4Companions(weightPackedName string, tensorSet map[string]struct{}, sourceTensorFiles map[string]string) (weightName, scaleName, weightGlobalScaleName, inputGlobalScaleName string, ok bool) {- if !strings.HasSuffix(weightPackedName, ".weight_packed") {- return "", "", "", "", false- }-- weightName = strings.TrimSuffix(weightPackedName, "_packed")- scaleName = strings.TrimSuffix(weightPackedName, "_packed") + "_scale"- if _, ok := tensorSet[scaleName]; !ok {- if _, ok := sourceTensorFiles[scaleName]; !ok {- return "", "", "", "", false- }- }-- weightGlobalScaleName = strings.TrimSuffix(weightPackedName, "_packed") + "_global_scale"- if _, ok := tensorSet[weightGlobalScaleName]; !ok {- if _, ok := sourceTensorFiles[weightGlobalScaleName]; !ok {- weightGlobalScaleName = ""- }- }-- inputGlobalScaleName = strings.TrimSuffix(weightPackedName, ".weight_packed") + ".input_global_scale"- if _, ok := tensorSet[inputGlobalScaleName]; !ok {- if _, ok := sourceTensorFiles[inputGlobalScaleName]; !ok {- inputGlobalScaleName = ""- }- }-- return weightName, scaleName, weightGlobalScaleName, inputGlobalScaleName, true-}-func readSourceTensorFiles(modelDir string) (map[string]string, error) {indexPath := filepath.Join(modelDir, "model.safetensors.index.json")data, err := os.ReadFile(indexPath)@@ -1894,27 +563,3 @@ func readSourceTensorFiles(modelDir string) (map[string]string, error) {}return index.WeightMap, nil}--func getTensorFromSource(modelDir string, current *safetensors.TensorExtractor, cache map[string]*safetensors.TensorExtractor, sourceTensorFiles map[string]string, name string) (*safetensors.TensorData, error) {- if td, err := current.GetTensor(name); err == nil {- return td, nil- }- if sourceTensorFiles == nil {- return nil, fmt.Errorf("tensor %s not found in current shard and no source index available", name)- }- fileName, ok := sourceTensorFiles[name]- if !ok {- return nil, fmt.Errorf("tensor %s not found in source index", name)- }- ext := cache[fileName]- if ext == nil {- path := filepath.Join(modelDir, fileName)- var err error- ext, err = safetensors.OpenForExtraction(path)- if err != nil {- return nil, err- }- cache[fileName] = ext- }- return ext.GetTensor(name)-}diff --git a/x/create/create_test.go b/x/create/create_test.goindex 0c195b371..ddd996487 100644--- a/x/create/create_test.go+++ b/x/create/create_test.go@@ -4,7 +4,6 @@ import ("bytes""encoding/binary""encoding/json"- "fmt""io""math""os"@@ -13,7 +12,6 @@ import ("strings""testing"- "github.com/d4l3k/go-bfloat16"st "github.com/ollama/ollama/x/safetensors")@@ -172,1586 +170,75 @@ func TestIsSafetensorsModelDir_NonexistentDir(t *testing.T) {}}-// createMinimalSafetensors creates a minimal valid safetensors file with one tensor-func createMinimalSafetensors(t *testing.T, path string) {- t.Helper()-- // Create a minimal safetensors file with a single float32 tensor- header := map[string]interface{}{- "test_tensor": map[string]interface{}{- "dtype": "F32",- "shape": []int{2, 2},- "data_offsets": []int{0, 16}, // 4 float32 values = 16 bytes- },- }- headerJSON, err := json.Marshal(header)- if err != nil {- t.Fatalf("failed to marshal header: %v", err)- }-- // Pad header to 8-byte alignment- padding := (8 - len(headerJSON)%8) % 8- headerJSON = append(headerJSON, bytes.Repeat([]byte(" "), padding)...)-- // Write file- f, err := os.Create(path)- if err != nil {- t.Fatalf("failed to create file: %v", err)- }- defer f.Close()-- // Write header size (8 bytes, little endian)- if err := binary.Write(f, binary.LittleEndian, uint64(len(headerJSON))); err != nil {- t.Fatalf("failed to write header size: %v", err)- }-- // Write header- if _, err := f.Write(headerJSON); err != nil {- t.Fatalf("failed to write header: %v", err)- }-- // Write tensor data (16 bytes of zeros for 4 float32 values)- if _, err := f.Write(make([]byte, 16)); err != nil {- t.Fatalf("failed to write tensor data: %v", err)- }-}--func createTestSafetensors(t *testing.T, path string, tensors []*st.TensorData) {- t.Helper()-- data, err := io.ReadAll(st.BuildPackedSafetensorsReader(tensors))- if err != nil {- t.Fatalf("failed to build packed safetensors: %v", err)- }- if err := os.WriteFile(path, data, 0o644); err != nil {- t.Fatalf("failed to write safetensors: %v", err)- }-}--func readSingleTensorHeader(t *testing.T, data []byte) (string, []int32) {- t.Helper()-- var headerSize uint64- if err := binary.Read(bytes.NewReader(data[:8]), binary.LittleEndian, &headerSize); err != nil {- t.Fatalf("failed to read header size: %v", err)- }-- var header map[string]struct {- Dtype string `json:"dtype"`- Shape []int32 `json:"shape"`- }- if err := json.Unmarshal(data[8:8+headerSize], &header); err != nil {- t.Fatalf("failed to parse header: %v", err)- }-- for name, info := range header {- if name == "__metadata__" {- continue- }- return info.Dtype, info.Shape- }-- t.Fatal("no tensor entry found in header")- return "", nil-}--func readSingleTensorRaw(t *testing.T, data []byte) []byte {- t.Helper()-- var headerSize uint64- if err := binary.Read(bytes.NewReader(data[:8]), binary.LittleEndian, &headerSize); err != nil {- t.Fatalf("failed to read header size: %v", err)- }-- var header map[string]struct {- Dtype string `json:"dtype"`- Shape []int32 `json:"shape"`- DataOffsets [2]int `json:"data_offsets"`- }- if err := json.Unmarshal(data[8:8+headerSize], &header); err != nil {- t.Fatalf("failed to parse header: %v", err)- }-- for name, info := range header {- if name == "__metadata__" {- continue- }- start := 8 + int(headerSize) + info.DataOffsets[0]- end := 8 + int(headerSize) + info.DataOffsets[1]- return data[start:end]- }-- t.Fatal("no tensor entry found in header")- return nil-}--func encodeFloat32s(vals ...float32) []byte {- raw := make([]byte, 4*len(vals))- for i, v := range vals {- binary.LittleEndian.PutUint32(raw[i*4:(i+1)*4], math.Float32bits(v))- }- return raw-}--func readPackedTensorRaw(t *testing.T, data []byte, tensorName string) []byte {- t.Helper()-- var headerSize uint64- if err := binary.Read(bytes.NewReader(data[:8]), binary.LittleEndian, &headerSize); err != nil {- t.Fatalf("failed to read header size: %v", err)- }-- var header map[string]struct {- Dtype string `json:"dtype"`- Shape []int32 `json:"shape"`- DataOffsets [2]int `json:"data_offsets"`- }- if err := json.Unmarshal(data[8:8+headerSize], &header); err != nil {- t.Fatalf("failed to parse header: %v", err)- }-- info, ok := header[tensorName]- if !ok {- t.Fatalf("tensor %q not found in header", tensorName)- }-- start := 8 + int(headerSize) + info.DataOffsets[0]- end := 8 + int(headerSize) + info.DataOffsets[1]- return data[start:end]-}--func readSafetensorsHeaderNames(t *testing.T, data []byte) []string {- t.Helper()-- var headerSize uint64- if err := binary.Read(bytes.NewReader(data[:8]), binary.LittleEndian, &headerSize); err != nil {- t.Fatalf("failed to read header size: %v", err)- }-- var header map[string]json.RawMessage- if err := json.Unmarshal(data[8:8+headerSize], &header); err != nil {- t.Fatalf("failed to parse header: %v", err)- }-- names := make([]string, 0, len(header))- for name := range header {- if name == "__metadata__" {- continue- }- names = append(names, name)- }- slices.Sort(names)- return names-}--func TestCreateSafetensorsModel(t *testing.T) {- dir := t.TempDir()-- // Create config.json- configJSON := `{"model_type": "test", "architectures": ["TestModel"]}`- if err := os.WriteFile(filepath.Join(dir, "config.json"), []byte(configJSON), 0o644); err != nil {- t.Fatalf("failed to write config.json: %v", err)- }-- // Create a minimal safetensors file- createMinimalSafetensors(t, filepath.Join(dir, "model.safetensors"))-- // Track what was created- var createdLayers []LayerInfo- var manifestWritten bool- var manifestModelName string- var manifestConfigLayer LayerInfo- var manifestLayers []LayerInfo- var statusMessages []string-- // Mock callbacks- createLayer := func(r io.Reader, mediaType, name string) (LayerInfo, error) {- data, err := io.ReadAll(r)- if err != nil {- return LayerInfo{}, err- }- layer := LayerInfo{- Digest: "sha256:test",- Size: int64(len(data)),- MediaType: mediaType,- Name: name,- }- createdLayers = append(createdLayers, layer)- return layer, nil- }-- createTensorLayer := func(r io.Reader, name, dtype string, shape []int32, quantize string) ([]LayerInfo, error) {- data, err := io.ReadAll(r)- if err != nil {- return nil, err- }- layer := LayerInfo{- Digest: "sha256:tensor_" + name,- Size: int64(len(data)),- MediaType: "application/vnd.ollama.image.tensor",- Name: name,- }- createdLayers = append(createdLayers, layer)- return []LayerInfo{layer}, nil- }-- writeManifest := func(modelName string, config LayerInfo, layers []LayerInfo) error {- manifestWritten = true- manifestModelName = modelName- manifestConfigLayer = config- manifestLayers = layers- return nil- }-- progressFn := func(status string) {- statusMessages = append(statusMessages, status)- }-- // Run CreateSafetensorsModel- err := CreateSafetensorsModel("test-model", dir, "", createLayer, createTensorLayer, writeManifest, progressFn)- if err != nil {- t.Fatalf("CreateSafetensorsModel failed: %v", err)- }-- // Verify manifest was written- if !manifestWritten {- t.Error("manifest was not written")- }-- if manifestModelName != "test-model" {- t.Errorf("manifest model name = %q, want %q", manifestModelName, "test-model")- }-- // Verify config layer was set- if manifestConfigLayer.Name != "config.json" {- t.Errorf("config layer name = %q, want %q", manifestConfigLayer.Name, "config.json")- }-- // Verify we have at least one tensor and one config layer- hasTensor := false- hasConfig := false- for _, layer := range manifestLayers {- if layer.Name == "test_tensor" {- hasTensor = true- }- if layer.Name == "config.json" {- hasConfig = true- }- }-- if !hasTensor {- t.Error("no tensor layer found in manifest")- }- if !hasConfig {- t.Error("no config layer found in manifest")- }-- // Verify status messages were sent- if len(statusMessages) == 0 {- t.Error("no status messages received")- }-}--func TestCreateDraftSafetensorsLayersPrefixesTensorsAndConfigs(t *testing.T) {- dir := t.TempDir()- if err := os.WriteFile(filepath.Join(dir, "config.json"), []byte(`{"model_type":"gemma4_assistant"}`), 0o644); err != nil {- t.Fatal(err)- }- createTestSafetensors(t, filepath.Join(dir, "model.safetensors"), []*st.TensorData{- st.NewTensorDataFromBytes("model.layers.0.self_attn.q_proj.weight", "BF16", []int32{2, 2}, make([]byte, 8)),- })-- var tensorNames []string- createLayer := func(r io.Reader, mediaType, name string) (LayerInfo, error) {- data, err := io.ReadAll(r)- if err != nil {- return LayerInfo{}, err- }- return LayerInfo{Digest: "sha256:json_" + name, Size: int64(len(data)), MediaType: mediaType, Name: name}, nil- }- createTensorLayer := func(r io.Reader, name, dtype string, shape []int32, quantize string) ([]LayerInfo, error) {- data, err := io.ReadAll(r)- if err != nil {- return nil, err- }- tensorNames = append(tensorNames, name)- tensorName, tensorShape := readSingleTensorNameAndShape(t, data)- if tensorName != name {- t.Fatalf("safetensors key = %q, want %q", tensorName, name)- }- if !slices.Equal(tensorShape, shape) {- t.Fatalf("shape = %v, want %v", tensorShape, shape)- }- if quantize != "" {- t.Fatalf("draft quantize = %q, want empty", quantize)- }- return []LayerInfo{{Digest: "sha256:tensor_" + name, Size: int64(len(data)), MediaType: "application/vnd.ollama.image.tensor", Name: name}}, nil- }-- layers, err := CreateDraftSafetensorsLayers(dir, "draft.", "draft", "", createLayer, createTensorLayer, func(string) {})- if err != nil {- t.Fatal(err)- }-- if !slices.Contains(tensorNames, "draft.model.layers.0.self_attn.q_proj.weight") {- t.Fatalf("draft tensor was not prefixed: %v", tensorNames)- }- var hasDraftConfig bool- for _, layer := range layers {- if layer.Name == "draft/config.json" && layer.MediaType == "application/vnd.ollama.image.json" {- hasDraftConfig = true- }- }- if !hasDraftConfig {- t.Fatalf("draft/config.json layer missing: %#v", layers)- }-}--func TestCreateDraftSafetensorsLayersQuantizesEligibleTensors(t *testing.T) {- dir := t.TempDir()- if err := os.WriteFile(filepath.Join(dir, "config.json"), []byte(`{- "architectures":["Gemma4AssistantForCausalLM"],- "num_hidden_layers":8- }`), 0o644); err != nil {- t.Fatal(err)- }- createTestSafetensors(t, filepath.Join(dir, "model.safetensors"), []*st.TensorData{- st.NewTensorDataFromBytes("model.embed_tokens.weight", "BF16", []int32{64, 64}, make([]byte, 64*64*2)),- st.NewTensorDataFromBytes("model.layers.0.self_attn.q_proj.weight", "BF16", []int32{64, 64}, make([]byte, 64*64*2)),- st.NewTensorDataFromBytes("model.layers.0.input_layernorm.weight", "BF16", []int32{64}, make([]byte, 64*2)),- })-- createLayer := func(r io.Reader, mediaType, name string) (LayerInfo, error) {- data, err := io.ReadAll(r)- if err != nil {- return LayerInfo{}, err- }- return LayerInfo{Digest: "sha256:json_" + name, Size: int64(len(data)), MediaType: mediaType, Name: name}, nil- }- quantizeByName := make(map[string]string)- createTensorLayer := func(r io.Reader, name, dtype string, shape []int32, quantize string) ([]LayerInfo, error) {- data, err := io.ReadAll(r)- if err != nil {- return nil, err- }- quantizeByName[name] = quantize- return []LayerInfo{{Digest: "sha256:tensor_" + name, Size: int64(len(data)), MediaType: "application/vnd.ollama.image.tensor", Name: name}}, nil- }-- if _, err := CreateDraftSafetensorsLayers(dir, "draft.", "draft", "MXFP8", createLayer, createTensorLayer, func(string) {}); err != nil {- t.Fatal(err)- }-- if got := quantizeByName["draft.model.layers.0.self_attn.q_proj.weight"]; got != "mxfp8" {- t.Fatalf("q_proj draft quantize = %q, want mxfp8", got)- }- if got := quantizeByName["draft.model.layers.0.input_layernorm.weight"]; got != "" {- t.Fatalf("norm draft quantize = %q, want empty", got)- }- if got := quantizeByName["draft.model.embed_tokens.weight"]; got != "" {- t.Fatalf("embed_tokens draft quantize = %q, want empty", got)- }-}--func TestCreateDraftSafetensorsLayersRejectsUnsupportedDraftQuantize(t *testing.T) {- _, err := CreateDraftSafetensorsLayers(t.TempDir(), "draft.", "draft", "bogus", nil, nil, func(string) {})- if err == nil || !strings.Contains(err.Error(), "unsupported --draft-quantize") {- t.Fatalf("error = %v, want unsupported --draft-quantize", err)- }-}--func readSingleTensorNameAndShape(t *testing.T, data []byte) (string, []int32) {- t.Helper()-- var headerSize uint64- if err := binary.Read(bytes.NewReader(data[:8]), binary.LittleEndian, &headerSize); err != nil {- t.Fatalf("failed to read header size: %v", err)- }-- var header map[string]struct {- Shape []int32 `json:"shape"`- }- if err := json.Unmarshal(data[8:8+headerSize], &header); err != nil {- t.Fatalf("failed to parse header: %v", err)- }- for name, info := range header {- if name != "__metadata__" {- return name, info.Shape- }- }- t.Fatal("no tensor entry found in header")- return "", nil-}--func TestCreateSafetensorsModel_NoConfigJson(t *testing.T) {- dir := t.TempDir()-- // Create only a safetensors file, no config.json- createMinimalSafetensors(t, filepath.Join(dir, "model.safetensors"))-- // Mock callbacks (minimal)- createLayer := func(r io.Reader, mediaType, name string) (LayerInfo, error) {- io.ReadAll(r)- return LayerInfo{Name: name}, nil- }- createTensorLayer := func(r io.Reader, name, dtype string, shape []int32, quantize string) ([]LayerInfo, error) {- io.ReadAll(r)- return []LayerInfo{{Name: name}}, nil- }- writeManifest := func(modelName string, config LayerInfo, layers []LayerInfo) error {- return nil- }- progressFn := func(status string) {}-- err := CreateSafetensorsModel("test-model", dir, "", createLayer, createTensorLayer, writeManifest, progressFn)- if err == nil {- t.Error("expected error for missing config.json, got nil")- }-}--func TestCreateSafetensorsModel_EmptyDir(t *testing.T) {- dir := t.TempDir()-- // Mock callbacks- createLayer := func(r io.Reader, mediaType, name string) (LayerInfo, error) {- return LayerInfo{}, nil- }- createTensorLayer := func(r io.Reader, name, dtype string, shape []int32, quantize string) ([]LayerInfo, error) {- return []LayerInfo{{}}, nil- }- writeManifest := func(modelName string, config LayerInfo, layers []LayerInfo) error {- return nil- }- progressFn := func(status string) {}-- err := CreateSafetensorsModel("test-model", dir, "", createLayer, createTensorLayer, writeManifest, progressFn)- if err == nil {- t.Error("expected error for empty directory, got nil")- }-}--func TestCreateSafetensorsModel_SkipsIndexJson(t *testing.T) {- dir := t.TempDir()-- // Create config.json- if err := os.WriteFile(filepath.Join(dir, "config.json"), []byte(`{}`), 0o644); err != nil {- t.Fatalf("failed to write config.json: %v", err)- }-- // Create model.safetensors.index.json (should be skipped)- indexJSON := `{"metadata": {"total_size": 100}, "weight_map": {}}`- if err := os.WriteFile(filepath.Join(dir, "model.safetensors.index.json"), []byte(indexJSON), 0o644); err != nil {- t.Fatalf("failed to write index.json: %v", err)- }-- // Create a minimal safetensors file- createMinimalSafetensors(t, filepath.Join(dir, "model.safetensors"))-- var configNames []string-- createLayer := func(r io.Reader, mediaType, name string) (LayerInfo, error) {- io.ReadAll(r)- configNames = append(configNames, name)- return LayerInfo{Name: name, Digest: "sha256:test"}, nil- }- createTensorLayer := func(r io.Reader, name, dtype string, shape []int32, quantize string) ([]LayerInfo, error) {- io.ReadAll(r)- return []LayerInfo{{Name: name}}, nil- }- writeManifest := func(modelName string, config LayerInfo, layers []LayerInfo) error {- return nil- }- progressFn := func(status string) {}-- err := CreateSafetensorsModel("test-model", dir, "", createLayer, createTensorLayer, writeManifest, progressFn)- if err != nil {- t.Fatalf("CreateSafetensorsModel failed: %v", err)- }-- // Verify model.safetensors.index.json was not included- for _, name := range configNames {- if name == "model.safetensors.index.json" {- t.Error("model.safetensors.index.json should have been skipped")- }- }-}--func TestCreateSafetensorsModel_PacksPrequantizedTensorTriplets(t *testing.T) {- dir := t.TempDir()-- configJSON := `{- "model_type": "test",- "architectures": ["TestModel"],- "quantization": {"group_size": 64, "bits": 4, "mode": "affine"}- }`- if err := os.WriteFile(filepath.Join(dir, "config.json"), []byte(configJSON), 0o644); err != nil {- t.Fatalf("failed to write config.json: %v", err)- }-- createTestSafetensors(t, filepath.Join(dir, "model.safetensors"), []*st.TensorData{- st.NewTensorDataFromBytes("linear.weight", "U32", []int32{4, 4}, make([]byte, 16)),- st.NewTensorDataFromBytes("linear.scales", "BF16", []int32{4, 1}, make([]byte, 8)),- st.NewTensorDataFromBytes("linear.biases", "BF16", []int32{4, 1}, make([]byte, 8)),- st.NewTensorDataFromBytes("plain.weight", "F32", []int32{2, 2}, make([]byte, 16)),- })-- var packedHeader map[string]json.RawMessage- var tensorLayerNames []string- var createTensorLayerNames []string-- createLayer := func(r io.Reader, mediaType, name string) (LayerInfo, error) {- data, err := io.ReadAll(r)- if err != nil {- return LayerInfo{}, err- }- if mediaType == "application/vnd.ollama.image.tensor" && name == "linear.weight" {- var headerSize uint64- if err := binary.Read(bytes.NewReader(data[:8]), binary.LittleEndian, &headerSize); err != nil {- return LayerInfo{}, err- }- if err := json.Unmarshal(data[8:8+headerSize], &packedHeader); err != nil {- return LayerInfo{}, err- }- }- tensorLayerNames = append(tensorLayerNames, name)- return LayerInfo{Name: name, Digest: "sha256:" + name, MediaType: mediaType, Size: int64(len(data))}, nil- }-- createTensorLayer := func(r io.Reader, name, dtype string, shape []int32, quantize string) ([]LayerInfo, error) {- if _, err := io.ReadAll(r); err != nil {- return nil, err- }- createTensorLayerNames = append(createTensorLayerNames, name)- return []LayerInfo{{Name: name, Digest: "sha256:tensor_" + name, MediaType: "application/vnd.ollama.image.tensor"}}, nil- }-- writeManifest := func(modelName string, config LayerInfo, layers []LayerInfo) error {- return nil- }-- progressFn := func(status string) {}-- if err := CreateSafetensorsModel("test-model", dir, "", createLayer, createTensorLayer, writeManifest, progressFn); err != nil {- t.Fatalf("CreateSafetensorsModel failed: %v", err)- }-- if packedHeader == nil {- t.Fatal("expected packed quantized header for linear.weight")- }- if _, ok := packedHeader["linear.weight"]; !ok {- t.Fatalf("packed header missing linear.weight: %v", packedHeader)- }- if _, ok := packedHeader["linear.weight.scale"]; !ok {- t.Fatalf("packed header missing linear.weight.scale: %v", packedHeader)- }- if _, ok := packedHeader["linear.weight.bias"]; !ok {- t.Fatalf("packed header missing linear.weight.bias: %v", packedHeader)- }-- var metadata map[string]string- if metaRaw, ok := packedHeader["__metadata__"]; ok {- if err := json.Unmarshal(metaRaw, &metadata); err != nil {- t.Fatalf("failed to parse packed metadata: %v", err)- }- }- if metadata["quant_type"] != "int4" {- t.Fatalf("quant_type = %q, want %q", metadata["quant_type"], "int4")- }- if metadata["group_size"] != "64" {- t.Fatalf("group_size = %q, want %q", metadata["group_size"], "64")- }-- if slices.Contains(createTensorLayerNames, "linear.weight") {- t.Fatalf("linear.weight unexpectedly handled by createTensorLayer: %v", createTensorLayerNames)- }- if slices.Contains(createTensorLayerNames, "linear.scales") || slices.Contains(createTensorLayerNames, "linear.biases") {- t.Fatalf("quantized companions unexpectedly handled separately: %v", createTensorLayerNames)- }- if !slices.Contains(createTensorLayerNames, "plain.weight") {- t.Fatalf("plain.weight missing from createTensorLayer calls: %v", createTensorLayerNames)- }- if slices.Contains(tensorLayerNames, "linear.scales") || slices.Contains(tensorLayerNames, "linear.biases") {- t.Fatalf("quantized companions unexpectedly emitted as layers: %v", tensorLayerNames)- }-}--func TestCreateSafetensorsModel_HFFP8AutoConvertsToMXFP8(t *testing.T) {- dir := t.TempDir()-- configJSON := `{- "model_type": "test",- "architectures": ["TestModel"],- "quantization_config": {"quant_method": "fp8", "weight_block_size": [128, 128]}- }`- if err := os.WriteFile(filepath.Join(dir, "config.json"), []byte(configJSON), 0o644); err != nil {- t.Fatalf("failed to write config.json: %v", err)- }-- createTestSafetensors(t, filepath.Join(dir, "model.safetensors"), []*st.TensorData{- st.NewTensorDataFromBytes("linear.weight", "F8_E4M3", []int32{2, 2}, []byte{1, 2, 3, 4}),- st.NewTensorDataFromBytes("linear.weight_scale_inv", "BF16", []int32{1, 1}, make([]byte, 2)),- st.NewTensorDataFromBytes("dense.weight", "BF16", []int32{128, 128}, make([]byte, 128*128*2)),- st.NewTensorDataFromBytes("norm.weight", "BF16", []int32{2}, make([]byte, 4)),- })-- quantizeByName := make(map[string]string)- headerNamesByName := make(map[string][]string)-- createLayer := func(r io.Reader, mediaType, name string) (LayerInfo, error) {- _, err := io.ReadAll(r)- if err != nil {- return LayerInfo{}, err- }- return LayerInfo{Name: name, Digest: "sha256:" + name, MediaType: mediaType}, nil- }-- createTensorLayer := func(r io.Reader, name, dtype string, shape []int32, quantize string) ([]LayerInfo, error) {- data, err := io.ReadAll(r)- if err != nil {- return nil, err- }- quantizeByName[name] = quantize- headerNamesByName[name] = readSafetensorsHeaderNames(t, data)- return []LayerInfo{{Name: name, Digest: "sha256:tensor_" + name, MediaType: "application/vnd.ollama.image.tensor"}}, nil- }-- writeManifest := func(modelName string, config LayerInfo, layers []LayerInfo) error { return nil }-- var statusMessages []string- progressFn := func(status string) {- statusMessages = append(statusMessages, status)- }-- if err := CreateSafetensorsModel("test-model", dir, "", createLayer, createTensorLayer, writeManifest, progressFn); err != nil {- t.Fatalf("CreateSafetensorsModel failed: %v", err)- }-- if len(statusMessages) == 0 {- t.Fatal("no status messages received")- }- if got, want := statusMessages[0], "importing model.safetensors (4 tensors, converting source E4M3 block-FP8 to MLX mxfp8)"; got != want {- t.Fatalf("status = %q, want %q", got, want)- }-- if got := quantizeByName["linear.weight"]; got != "mxfp8" {- t.Fatalf("linear.weight quantization = %q, want %q", got, "mxfp8")- }-- if got := quantizeByName["norm.weight"]; got != "" {- t.Fatalf("norm.weight quantization = %q, want empty", got)- }- if got := quantizeByName["dense.weight"]; got != "" {- t.Fatalf("dense.weight quantization = %q, want empty", got)- }-- if _, ok := quantizeByName["linear.weight_scale_inv"]; ok {- t.Fatal("linear.weight_scale_inv should not be imported as a standalone tensor")- }-- if got := headerNamesByName["linear.weight"]; !slices.Equal(got, []string{"linear.weight", "linear.weight.scale_inv"}) {- t.Fatalf("linear.weight blob tensors = %v, want %v", got, []string{"linear.weight", "linear.weight.scale_inv"})- }-- if got := headerNamesByName["norm.weight"]; !slices.Equal(got, []string{"norm.weight"}) {- t.Fatalf("norm.weight blob tensors = %v, want %v", got, []string{"norm.weight"})- }- if got := headerNamesByName["dense.weight"]; !slices.Equal(got, []string{"dense.weight"}) {- t.Fatalf("dense.weight blob tensors = %v, want %v", got, []string{"dense.weight"})- }-}--func TestCreateSafetensorsModel_CompressedTensorsFP8WeightScale(t *testing.T) {- dir := t.TempDir()-- configJSON := `{- "model_type": "test",- "architectures": ["TestModel"],- "compression_config": {- "quant_method": "compressed-tensors",- "format": "float-quantized",- "config_groups": {- "group_0": {- "format": "float-quantized",- "weights": {- "type": "float",- "num_bits": 8,- "block_structure": [128, 128]- }- }- }- }- }`- if err := os.WriteFile(filepath.Join(dir, "config.json"), []byte(configJSON), 0o644); err != nil {- t.Fatalf("failed to write config.json: %v", err)- }-- createTestSafetensors(t, filepath.Join(dir, "model.safetensors"), []*st.TensorData{- st.NewTensorDataFromBytes("linear.weight", "F8_E4M3", []int32{2, 2}, []byte{1, 2, 3, 4}),- st.NewTensorDataFromBytes("linear.weight_scale", "BF16", []int32{1, 1}, make([]byte, 2)),- st.NewTensorDataFromBytes("norm.weight", "BF16", []int32{2}, make([]byte, 4)),- })-- quantizeByName := make(map[string]string)- headerNamesByName := make(map[string][]string)-- createLayer := func(r io.Reader, mediaType, name string) (LayerInfo, error) {- if _, err := io.ReadAll(r); err != nil {- return LayerInfo{}, err- }- return LayerInfo{Name: name, Digest: "sha256:" + name, MediaType: mediaType}, nil- }- createTensorLayer := func(r io.Reader, name, dtype string, shape []int32, quantize string) ([]LayerInfo, error) {- data, err := io.ReadAll(r)- if err != nil {- return nil, err- }- quantizeByName[name] = quantize- headerNamesByName[name] = readSafetensorsHeaderNames(t, data)- return []LayerInfo{{Name: name, Digest: "sha256:tensor_" + name, MediaType: "application/vnd.ollama.image.tensor"}}, nil- }- writeManifest := func(modelName string, config LayerInfo, layers []LayerInfo) error { return nil }-- var statusMessages []string- progressFn := func(status string) {- statusMessages = append(statusMessages, status)- }-- if err := CreateSafetensorsModel("test-model", dir, "", createLayer, createTensorLayer, writeManifest, progressFn); err != nil {- t.Fatalf("CreateSafetensorsModel failed: %v", err)- }- if len(statusMessages) == 0 {- t.Fatal("no status messages received")- }- if got, want := statusMessages[0], "importing model.safetensors (3 tensors, converting source E4M3 block-FP8 to MLX mxfp8)"; got != want {- t.Fatalf("status = %q, want %q", got, want)- }- if got := quantizeByName["linear.weight"]; got != "mxfp8" {- t.Fatalf("linear.weight quantization = %q, want mxfp8", got)- }- if _, ok := quantizeByName["linear.weight_scale"]; ok {- t.Fatal("linear.weight_scale should not be imported as a standalone tensor")- }- if got := headerNamesByName["linear.weight"]; !slices.Equal(got, []string{"linear.weight", "linear.weight.scale"}) {- t.Fatalf("linear.weight blob tensors = %v, want %v", got, []string{"linear.weight", "linear.weight.scale"})- }-}--func TestCreateSafetensorsModel_HFFP8SourceCanConvertToNVFP4(t *testing.T) {- dir := t.TempDir()-- configJSON := `{- "model_type": "test",- "architectures": ["TestModel"],- "quantization_config": {"quant_method": "fp8", "weight_block_size": [128, 128]}- }`- if err := os.WriteFile(filepath.Join(dir, "config.json"), []byte(configJSON), 0o644); err != nil {- t.Fatalf("failed to write config.json: %v", err)- }-- createTestSafetensors(t, filepath.Join(dir, "model.safetensors"), []*st.TensorData{- st.NewTensorDataFromBytes("linear.weight", "F8_E4M3", []int32{128, 128}, make([]byte, 128*128)),- st.NewTensorDataFromBytes("linear.weight_scale_inv", "BF16", []int32{1, 1}, make([]byte, 2)),- st.NewTensorDataFromBytes("model.layers.0.mlp.experts.0.down_proj.weight", "F8_E4M3", []int32{128, 128}, make([]byte, 128*128)),- st.NewTensorDataFromBytes("model.layers.0.mlp.experts.0.down_proj.weight_scale_inv", "BF16", []int32{1, 1}, make([]byte, 2)),- st.NewTensorDataFromBytes("model.layers.0.self_attn.q_proj.weight", "BF16", []int32{128, 128}, make([]byte, 128*128*2)),- st.NewTensorDataFromBytes("model.embed_tokens.weight", "BF16", []int32{128, 128}, make([]byte, 128*128*2)),- st.NewTensorDataFromBytes("lm_head.weight", "BF16", []int32{128, 128}, make([]byte, 128*128*2)),- st.NewTensorDataFromBytes("model.layers.0.mlp.gate.weight", "BF16", []int32{128, 128}, make([]byte, 128*128*2)),- st.NewTensorDataFromBytes("norm.weight", "BF16", []int32{128}, make([]byte, 256)),- })-- quantizeByName := make(map[string]string)- headerNamesByName := make(map[string][]string)-- createLayer := func(r io.Reader, mediaType, name string) (LayerInfo, error) {- if _, err := io.ReadAll(r); err != nil {- return LayerInfo{}, err- }- return LayerInfo{Name: name, Digest: "sha256:" + name, MediaType: mediaType}, nil- }- createTensorLayer := func(r io.Reader, name, dtype string, shape []int32, quantize string) ([]LayerInfo, error) {- data, err := io.ReadAll(r)- if err != nil {- return nil, err- }- quantizeByName[name] = quantize- headerNamesByName[name] = readSafetensorsHeaderNames(t, data)- return []LayerInfo{{Name: name, Digest: "sha256:tensor_" + name, MediaType: "application/vnd.ollama.image.tensor"}}, nil- }- writeManifest := func(modelName string, config LayerInfo, layers []LayerInfo) error { return nil }-- var statusMessages []string- progressFn := func(status string) {- statusMessages = append(statusMessages, status)- }-- if err := CreateSafetensorsModel("test-model", dir, "nvfp4", createLayer, createTensorLayer, writeManifest, progressFn); err != nil {- t.Fatalf("CreateSafetensorsModel failed: %v", err)- }- if len(statusMessages) == 0 {- t.Fatal("no status messages received")- }- if got, want := statusMessages[0], "importing model.safetensors (9 tensors, converting source E4M3 block-FP8 to MLX nvfp4)"; got != want {- t.Fatalf("status = %q, want %q", got, want)- }- if got := quantizeByName["linear.weight"]; got != "nvfp4" {- t.Fatalf("linear.weight quantization = %q, want nvfp4", got)- }- if got := quantizeByName["model.layers.0.mlp.experts.0.down_proj.weight"]; got != "mxfp8" {- t.Fatalf("source fp8 down_proj quantization = %q, want mxfp8", got)- }- for _, name := range []string{- "model.layers.0.self_attn.q_proj.weight",- "model.embed_tokens.weight",- "lm_head.weight",- } {- if got := quantizeByName[name]; got != "mxfp8" {- t.Fatalf("%s quantization = %q, want mxfp8", name, got)- }- }- if got := quantizeByName["model.layers.0.mlp.gate.weight"]; got != "" {- t.Fatalf("router gate quantization = %q, want empty", got)- }- if got := quantizeByName["norm.weight"]; got != "" {- t.Fatalf("norm.weight quantization = %q, want empty", got)- }- if got := headerNamesByName["linear.weight"]; !slices.Equal(got, []string{"linear.weight", "linear.weight.scale_inv"}) {- t.Fatalf("linear.weight blob tensors = %v, want %v", got, []string{"linear.weight", "linear.weight.scale_inv"})- }-}--func TestCreateSafetensorsModel_RejectsRequantizingQuantizedSources(t *testing.T) {- tests := []struct {- name string- configJSON string- tensors []*st.TensorData- wantErr string- }{- {- name: "prequantized affine",- configJSON: `{"model_type": "test", "architectures": ["TestModel"]}`,- tensors: []*st.TensorData{- st.NewTensorDataFromBytes("linear.weight", "U32", []int32{4, 4}, make([]byte, 16)),- st.NewTensorDataFromBytes("linear.scales", "BF16", []int32{4, 1}, make([]byte, 8)),- },- wantErr: `cannot requantize already-quantized source model with --quantize "int4"`,- },- {- name: "hf fp8 source",- configJSON: `{- "model_type": "test",- "architectures": ["TestModel"],- "quantization_config": {"quant_method": "fp8", "weight_block_size": [128, 128]}- }`,- tensors: []*st.TensorData{- st.NewTensorDataFromBytes("linear.weight", "F8_E4M3", []int32{2, 2}, []byte{1, 2, 3, 4}),- st.NewTensorDataFromBytes("linear.weight_scale_inv", "BF16", []int32{1, 1}, make([]byte, 2)),- },- wantErr: `cannot convert already-quantized fp8 source model with --quantize "int4"`,- },- {- name: "packed nvfp4 source",- configJSON: `{- "model_type": "test",- "architectures": ["TestModel"],- "compression_config": {"format": "nvfp4-pack-quantized"}- }`,- tensors: []*st.TensorData{- st.NewTensorDataFromBytes("linear.weight_packed", "U8", []int32{16, 8}, make([]byte, 128)),- st.NewTensorDataFromBytes("linear.weight_scale", "F8_E4M3", []int32{16, 1}, make([]byte, 16)),- },- wantErr: `cannot requantize already-quantized source model with --quantize "int4"`,- },- }-- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- dir := t.TempDir()- if err := os.WriteFile(filepath.Join(dir, "config.json"), []byte(tt.configJSON), 0o644); err != nil {- t.Fatalf("failed to write config.json: %v", err)- }- createTestSafetensors(t, filepath.Join(dir, "model.safetensors"), tt.tensors)-- createLayer := func(r io.Reader, mediaType, name string) (LayerInfo, error) {- return LayerInfo{}, nil- }- createTensorLayer := func(r io.Reader, name, dtype string, shape []int32, quantize string) ([]LayerInfo, error) {- return nil, nil- }- writeManifest := func(modelName string, config LayerInfo, layers []LayerInfo) error { return nil }-- err := CreateSafetensorsModel("test-model", dir, "int4", createLayer, createTensorLayer, writeManifest, func(string) {})- if err == nil {- t.Fatal("expected error, got nil")- }- if !strings.Contains(err.Error(), tt.wantErr) {- t.Fatalf("error = %q, want substring %q", err, tt.wantErr)- }- })- }-}--func TestCreateSafetensorsModel_PackedNVFP4PreservesSourceLayout(t *testing.T) {- dir := t.TempDir()-- configJSON := `{- "model_type": "test",- "architectures": ["TestModel"],- "compression_config": {"format": "nvfp4-pack-quantized"}- }`- if err := os.WriteFile(filepath.Join(dir, "config.json"), []byte(configJSON), 0o644); err != nil {- t.Fatalf("failed to write config.json: %v", err)- }-- createTestSafetensors(t, filepath.Join(dir, "model.safetensors"), []*st.TensorData{- st.NewTensorDataFromBytes("linear.weight_packed", "U8", []int32{16, 8}, make([]byte, 128)),- st.NewTensorDataFromBytes("linear.weight_scale", "F8_E4M3", []int32{16, 1}, make([]byte, 16)),- st.NewTensorDataFromBytes("linear.weight_global_scale", "F32", []int32{}, encodeFloat32s(4)),- st.NewTensorDataFromBytes("linear.input_global_scale", "F32", []int32{}, encodeFloat32s(8)),- st.NewTensorDataFromBytes("norm.weight", "BF16", []int32{16}, make([]byte, 32)),- })-- var statusMessages []string- layerHeaders := make(map[string]map[string]json.RawMessage)- layerData := make(map[string][]byte)- var tensorLayerNames []string-- createLayer := func(r io.Reader, mediaType, name string) (LayerInfo, error) {- data, err := io.ReadAll(r)- if err != nil {- return LayerInfo{}, err- }- if mediaType == "application/vnd.ollama.image.tensor" {- if len(data) < 8 {- return LayerInfo{}, io.ErrUnexpectedEOF- }- var headerSize uint64- if err := binary.Read(bytes.NewReader(data[:8]), binary.LittleEndian, &headerSize); err != nil {- return LayerInfo{}, err- }- var header map[string]json.RawMessage- if err := json.Unmarshal(data[8:8+headerSize], &header); err != nil {- return LayerInfo{}, err- }- layerHeaders[name] = header- layerData[name] = data- }- return LayerInfo{Name: name, Digest: "sha256:" + name, MediaType: mediaType}, nil- }- createTensorLayer := func(r io.Reader, name, dtype string, shape []int32, quantize string) ([]LayerInfo, error) {- if _, err := io.ReadAll(r); err != nil {- return nil, err- }- tensorLayerNames = append(tensorLayerNames, name)- return []LayerInfo{{Name: name, Digest: "sha256:tensor_" + name, MediaType: "application/vnd.ollama.image.tensor"}}, nil- }- writeManifest := func(modelName string, config LayerInfo, layers []LayerInfo) error { return nil }- progressFn := func(status string) { statusMessages = append(statusMessages, status) }-- if err := CreateSafetensorsModel("test-model", dir, "", createLayer, createTensorLayer, writeManifest, progressFn); err != nil {- t.Fatalf("CreateSafetensorsModel failed: %v", err)- }-- if len(statusMessages) == 0 {- t.Fatal("no status messages received")- }- if got, want := statusMessages[0], "importing model.safetensors (5 tensors, preserving source quantization)"; got != want {- t.Fatalf("status = %q, want %q", got, want)- }-- if slices.Contains(tensorLayerNames, "linear.weight_scale") || slices.Contains(tensorLayerNames, "linear.weight_global_scale") || slices.Contains(tensorLayerNames, "linear.input_global_scale") {- t.Fatalf("packed nvfp4 companions unexpectedly emitted as standalone tensor layers: %v", tensorLayerNames)- }-- packedHeader := layerHeaders["linear.weight"]- if packedHeader == nil {- t.Fatalf("missing packed layer header for linear.weight")- }- for _, key := range []string{- "linear.weight",- "linear.weight.scale",- "linear.weight.global_scale",- } {- if _, ok := packedHeader[key]; !ok {- t.Fatalf("packed header missing %s: %v", key, packedHeader)- }- }- if _, ok := packedHeader["linear.weight.input_global_scale"]; ok {- t.Fatalf("packed header unexpectedly includes input_global_scale: %v", packedHeader)- }- globalRaw := readPackedTensorRaw(t, layerData["linear.weight"], "linear.weight.global_scale")- if got := math.Float32frombits(binary.LittleEndian.Uint32(globalRaw)); got != 0.25 {- t.Fatalf("linear.weight.global_scale = %v, want 0.25", got)- }-- var metadata map[string]string- if metaRaw, ok := packedHeader["__metadata__"]; ok {- if err := json.Unmarshal(metaRaw, &metadata); err != nil {- t.Fatalf("failed to parse metadata: %v", err)- }- }- if metadata["quant_type"] != "nvfp4" {- t.Fatalf("quant_type = %q, want %q", metadata["quant_type"], "nvfp4")- }- if metadata["group_size"] != "16" {- t.Fatalf("group_size = %q, want %q", metadata["group_size"], "16")- }-}--func TestCreateSafetensorsModel_PackedNVFP4CrossShardCompanions(t *testing.T) {- dir := t.TempDir()-- configJSON := `{- "model_type": "test",- "architectures": ["TestModel"],- "compression_config": {"format": "nvfp4-pack-quantized"}- }`- if err := os.WriteFile(filepath.Join(dir, "config.json"), []byte(configJSON), 0o644); err != nil {- t.Fatalf("failed to write config.json: %v", err)- }-- createTestSafetensors(t, filepath.Join(dir, "model-00001-of-00002.safetensors"), []*st.TensorData{- st.NewTensorDataFromBytes("linear.weight_packed", "U8", []int32{16, 8}, make([]byte, 128)),- st.NewTensorDataFromBytes("norm.weight", "BF16", []int32{16}, make([]byte, 32)),- })- createTestSafetensors(t, filepath.Join(dir, "model-00002-of-00002.safetensors"), []*st.TensorData{- st.NewTensorDataFromBytes("linear.weight_scale", "F8_E4M3", []int32{16, 1}, make([]byte, 16)),- st.NewTensorDataFromBytes("linear.weight_global_scale", "F32", []int32{}, encodeFloat32s(2)),- st.NewTensorDataFromBytes("linear.input_global_scale", "F32", []int32{}, encodeFloat32s(8)),- })- indexJSON := `{- "metadata": {"total_size": 152},- "weight_map": {- "linear.weight_packed": "model-00001-of-00002.safetensors",- "norm.weight": "model-00001-of-00002.safetensors",- "linear.weight_scale": "model-00002-of-00002.safetensors",- "linear.weight_global_scale": "model-00002-of-00002.safetensors",- "linear.input_global_scale": "model-00002-of-00002.safetensors"- }- }`- if err := os.WriteFile(filepath.Join(dir, "model.safetensors.index.json"), []byte(indexJSON), 0o644); err != nil {- t.Fatalf("failed to write index: %v", err)- }-- layerHeaders := make(map[string]map[string]json.RawMessage)- var tensorLayerNames []string-- createLayer := func(r io.Reader, mediaType, name string) (LayerInfo, error) {- data, err := io.ReadAll(r)- if err != nil {- return LayerInfo{}, err- }- if mediaType == "application/vnd.ollama.image.tensor" {- var headerSize uint64- if err := binary.Read(bytes.NewReader(data[:8]), binary.LittleEndian, &headerSize); err != nil {- return LayerInfo{}, err- }- var header map[string]json.RawMessage- if err := json.Unmarshal(data[8:8+headerSize], &header); err != nil {- return LayerInfo{}, err- }- layerHeaders[name] = header- }- return LayerInfo{Name: name, Digest: "sha256:" + name, MediaType: mediaType}, nil- }- createTensorLayer := func(r io.Reader, name, dtype string, shape []int32, quantize string) ([]LayerInfo, error) {- if _, err := io.ReadAll(r); err != nil {- return nil, err- }- tensorLayerNames = append(tensorLayerNames, name)- return []LayerInfo{{Name: name, Digest: "sha256:tensor_" + name, MediaType: "application/vnd.ollama.image.tensor"}}, nil- }- writeManifest := func(modelName string, config LayerInfo, layers []LayerInfo) error { return nil }-- packedCreator := func(groupName string, tensors []PackedTensorInput) (LayerInfo, error) {- return LayerInfo{}, fmt.Errorf("unexpected packedCreator call for %s", groupName)- }- if err := CreateSafetensorsModel("test-model", dir, "", createLayer, createTensorLayer, writeManifest, func(string) {}, packedCreator); err != nil {- t.Fatalf("CreateSafetensorsModel failed: %v", err)- }-- if slices.Contains(tensorLayerNames, "linear.weight_packed") || slices.Contains(tensorLayerNames, "linear.weight_scale") || slices.Contains(tensorLayerNames, "linear.weight_global_scale") || slices.Contains(tensorLayerNames, "linear.input_global_scale") {- t.Fatalf("packed nvfp4 tensors unexpectedly emitted as standalone tensor layers: %v", tensorLayerNames)- }-- packedHeader := layerHeaders["linear.weight"]- if packedHeader == nil {- t.Fatalf("missing packed layer header for linear.weight")- }- for _, key := range []string{- "linear.weight",- "linear.weight.scale",- "linear.weight.global_scale",- } {- if _, ok := packedHeader[key]; !ok {- t.Fatalf("packed header missing %s: %v", key, packedHeader)- }- }- if _, ok := packedHeader["linear.weight.input_global_scale"]; ok {- t.Fatalf("packed header unexpectedly includes input_global_scale: %v", packedHeader)- }-}--func TestCreateSafetensorsModel_PackedNVFP4StacksExperts(t *testing.T) {- dir := t.TempDir()-- configJSON := `{- "model_type": "test",- "architectures": ["TestModel"],- "compression_config": {"format": "nvfp4-pack-quantized"}- }`- if err := os.WriteFile(filepath.Join(dir, "config.json"), []byte(configJSON), 0o644); err != nil {- t.Fatalf("failed to write config.json: %v", err)- }-- createTestSafetensors(t, filepath.Join(dir, "model.safetensors"), []*st.TensorData{- st.NewTensorDataFromBytes("model.layers.1.mlp.experts.0.gate_proj.weight_packed", "U8", []int32{2, 8}, make([]byte, 16)),- st.NewTensorDataFromBytes("model.layers.1.mlp.experts.0.gate_proj.weight_scale", "F8_E4M3", []int32{2, 1}, make([]byte, 2)),- st.NewTensorDataFromBytes("model.layers.1.mlp.experts.0.gate_proj.weight_global_scale", "F32", []int32{1}, encodeFloat32s(2)),- st.NewTensorDataFromBytes("model.layers.1.mlp.experts.0.gate_proj.input_global_scale", "F32", []int32{1}, encodeFloat32s(32)),- st.NewTensorDataFromBytes("model.layers.1.mlp.experts.1.gate_proj.weight_packed", "U8", []int32{2, 8}, make([]byte, 16)),- st.NewTensorDataFromBytes("model.layers.1.mlp.experts.1.gate_proj.weight_scale", "F8_E4M3", []int32{2, 1}, make([]byte, 2)),- st.NewTensorDataFromBytes("model.layers.1.mlp.experts.1.gate_proj.weight_global_scale", "F32", []int32{1}, encodeFloat32s(4)),- st.NewTensorDataFromBytes("model.layers.1.mlp.experts.1.gate_proj.input_global_scale", "F32", []int32{1}, encodeFloat32s(64)),- st.NewTensorDataFromBytes("norm.weight", "BF16", []int32{2}, make([]byte, 4)),- })-- layerHeaders := make(map[string]map[string]json.RawMessage)- layerData := make(map[string][]byte)- createLayer := func(r io.Reader, mediaType, name string) (LayerInfo, error) {- data, err := io.ReadAll(r)- if err != nil {- return LayerInfo{}, err- }- if mediaType == "application/vnd.ollama.image.tensor" {- var headerSize uint64- if err := binary.Read(bytes.NewReader(data[:8]), binary.LittleEndian, &headerSize); err != nil {- return LayerInfo{}, err- }- var header map[string]json.RawMessage- if err := json.Unmarshal(data[8:8+headerSize], &header); err != nil {- return LayerInfo{}, err- }- layerHeaders[name] = header- layerData[name] = data- }- return LayerInfo{Name: name, Digest: "sha256:" + name, MediaType: mediaType}, nil- }- createTensorLayer := func(r io.Reader, name, dtype string, shape []int32, quantize string) ([]LayerInfo, error) {- if _, err := io.ReadAll(r); err != nil {- return nil, err- }- return []LayerInfo{{Name: name, Digest: "sha256:tensor_" + name, MediaType: "application/vnd.ollama.image.tensor"}}, nil- }- writeManifest := func(modelName string, config LayerInfo, layers []LayerInfo) error { return nil }- packedCreator := func(groupName string, tensors []PackedTensorInput) (LayerInfo, error) {- return LayerInfo{}, fmt.Errorf("unexpected packedCreator call for %s", groupName)- }-- if err := CreateSafetensorsModel("test-model", dir, "", createLayer, createTensorLayer, writeManifest, func(string) {}, packedCreator); err != nil {- t.Fatalf("CreateSafetensorsModel failed: %v", err)- }-- header := layerHeaders["model.layers.1.mlp.experts"]- if header == nil {- t.Fatalf("missing packed expert layer header")- }- for _, key := range []string{- "model.layers.1.mlp.switch_mlp.gate_proj.weight",- "model.layers.1.mlp.switch_mlp.gate_proj.weight.scale",- "model.layers.1.mlp.switch_mlp.gate_proj.weight.global_scale",- } {- if _, ok := header[key]; !ok {- t.Fatalf("stacked header missing %s: %v", key, header)- }- }- if _, ok := header["model.layers.1.mlp.switch_mlp.gate_proj.weight.input_global_scale"]; ok {- t.Fatalf("stacked header unexpectedly includes input_global_scale: %v", header)- }- if _, ok := header["model.layers.1.mlp.experts.0.gate_proj.weight"]; ok {- t.Fatalf("unexpected per-expert tensor left in packed header: %v", header)- }-- var weightInfo struct {- Dtype string `json:"dtype"`- Shape []int32 `json:"shape"`- }- if err := json.Unmarshal(header["model.layers.1.mlp.switch_mlp.gate_proj.weight"], &weightInfo); err != nil {- t.Fatalf("failed to unmarshal stacked weight info: %v", err)- }- if weightInfo.Dtype != "U32" || !slices.Equal(weightInfo.Shape, []int32{2, 2, 2}) {- t.Fatalf("stacked weight = dtype %s shape %v, want U32 [2 2 2]", weightInfo.Dtype, weightInfo.Shape)- }-- var globalInfo struct {- Dtype string `json:"dtype"`- Shape []int32 `json:"shape"`- }- if err := json.Unmarshal(header["model.layers.1.mlp.switch_mlp.gate_proj.weight.global_scale"], &globalInfo); err != nil {- t.Fatalf("failed to unmarshal stacked global scale info: %v", err)- }- if globalInfo.Dtype != "F32" || !slices.Equal(globalInfo.Shape, []int32{2, 1, 1}) {- t.Fatalf("stacked global scale = dtype %s shape %v, want F32 [2 1 1]", globalInfo.Dtype, globalInfo.Shape)- }- globalRaw := readPackedTensorRaw(t, layerData["model.layers.1.mlp.experts"], "model.layers.1.mlp.switch_mlp.gate_proj.weight.global_scale")- if got0 := math.Float32frombits(binary.LittleEndian.Uint32(globalRaw[0:4])); got0 != 0.5 {- t.Fatalf("stacked global scale[0] = %v, want 0.5", got0)- }- if got1 := math.Float32frombits(binary.LittleEndian.Uint32(globalRaw[4:8])); got1 != 0.25 {- t.Fatalf("stacked global scale[1] = %v, want 0.25", got1)- }-}--func TestCreateSafetensorsModel_HFFP8PacksExperts(t *testing.T) {- dir := t.TempDir()-- configJSON := `{- "model_type": "test",- "architectures": ["Qwen3_5MoeForConditionalGeneration"],- "quantization_config": {"quant_method": "fp8", "weight_block_size": [128, 128]}- }`- if err := os.WriteFile(filepath.Join(dir, "config.json"), []byte(configJSON), 0o644); err != nil {- t.Fatalf("failed to write config.json: %v", err)- }-- // Create 2 experts so stacking produces a [2, 128, 128] tensor- createTestSafetensors(t, filepath.Join(dir, "model.safetensors"), []*st.TensorData{- st.NewTensorDataFromBytes("model.language_model.layers.0.mlp.experts.0.gate_proj.weight", "F8_E4M3", []int32{128, 128}, make([]byte, 128*128)),- st.NewTensorDataFromBytes("model.language_model.layers.0.mlp.experts.0.gate_proj.weight_scale_inv", "BF16", []int32{1, 1}, make([]byte, 2)),- st.NewTensorDataFromBytes("model.language_model.layers.0.mlp.experts.0.up_proj.weight", "F8_E4M3", []int32{128, 128}, make([]byte, 128*128)),- st.NewTensorDataFromBytes("model.language_model.layers.0.mlp.experts.0.up_proj.weight_scale_inv", "BF16", []int32{1, 1}, make([]byte, 2)),- st.NewTensorDataFromBytes("model.language_model.layers.0.mlp.experts.0.down_proj.weight", "F8_E4M3", []int32{128, 128}, make([]byte, 128*128)),- st.NewTensorDataFromBytes("model.language_model.layers.0.mlp.experts.0.down_proj.weight_scale_inv", "BF16", []int32{1, 1}, make([]byte, 2)),- st.NewTensorDataFromBytes("model.language_model.layers.0.mlp.experts.1.gate_proj.weight", "F8_E4M3", []int32{128, 128}, make([]byte, 128*128)),- st.NewTensorDataFromBytes("model.language_model.layers.0.mlp.experts.1.gate_proj.weight_scale_inv", "BF16", []int32{1, 1}, make([]byte, 2)),- st.NewTensorDataFromBytes("model.language_model.layers.0.mlp.experts.1.up_proj.weight", "F8_E4M3", []int32{128, 128}, make([]byte, 128*128)),- st.NewTensorDataFromBytes("model.language_model.layers.0.mlp.experts.1.up_proj.weight_scale_inv", "BF16", []int32{1, 1}, make([]byte, 2)),- st.NewTensorDataFromBytes("model.language_model.layers.0.mlp.experts.1.down_proj.weight", "F8_E4M3", []int32{128, 128}, make([]byte, 128*128)),- st.NewTensorDataFromBytes("model.language_model.layers.0.mlp.experts.1.down_proj.weight_scale_inv", "BF16", []int32{1, 1}, make([]byte, 2)),- })-- var packedLayerNames []string- var packedLayerTensors [][]PackedTensorInput-- createLayer := func(r io.Reader, mediaType, name string) (LayerInfo, error) {- if _, err := io.ReadAll(r); err != nil {- return LayerInfo{}, err- }- return LayerInfo{Name: name, Digest: "sha256:" + name, MediaType: mediaType}, nil- }-- createTensorLayer := func(r io.Reader, name, dtype string, shape []int32, quantize string) ([]LayerInfo, error) {- if _, err := io.ReadAll(r); err != nil {- return nil, err- }- return []LayerInfo{{Name: name, Digest: "sha256:tensor_" + name, MediaType: "application/vnd.ollama.image.tensor"}}, nil- }-- createPackedLayer := func(groupName string, tensors []PackedTensorInput) (LayerInfo, error) {- packedLayerNames = append(packedLayerNames, groupName)- packedLayerTensors = append(packedLayerTensors, tensors)- return LayerInfo{Name: groupName, Digest: "sha256:packed_" + groupName, MediaType: "application/vnd.ollama.image.tensor"}, nil- }-- writeManifest := func(modelName string, config LayerInfo, layers []LayerInfo) error { return nil }-- if err := CreateSafetensorsModel("test-model", dir, "", createLayer, createTensorLayer, writeManifest, func(string) {}, createPackedLayer); err != nil {- t.Fatalf("CreateSafetensorsModel failed: %v", err)- }-- if len(packedLayerNames) != 1 {- t.Fatalf("expected 1 packed layer, got %d: %v", len(packedLayerNames), packedLayerNames)- }- if packedLayerNames[0] != "language_model.model.layers.0.mlp.experts" {- t.Fatalf("unexpected packed layer name: %s", packedLayerNames[0])- }-- // Verify all 6 expert tensors (2 experts × 3 proj types) were accumulated- tensors := packedLayerTensors[0]- if len(tensors) != 6 {- t.Fatalf("expected 6 tensors in packed group, got %d", len(tensors))- }-- // All should be marked for mxfp8 quantization- for _, tensor := range tensors {- if tensor.Quantize != "mxfp8" {- t.Fatalf("expected mxfp8 quantize for %s, got %q", tensor.Name, tensor.Quantize)- }- }-- packedLayerNames = nil- packedLayerTensors = nil- if err := CreateSafetensorsModel("test-model", dir, "nvfp4", createLayer, createTensorLayer, writeManifest, func(string) {}, createPackedLayer); err != nil {- t.Fatalf("CreateSafetensorsModel nvfp4 failed: %v", err)- }+func createTestSafetensors(t *testing.T, path string, tensors []*st.TensorData) {+ t.Helper()- if len(packedLayerNames) != 1 {- t.Fatalf("expected 1 packed layer for nvfp4, got %d: %v", len(packedLayerNames), packedLayerNames)+ data, err := io.ReadAll(st.BuildPackedSafetensorsReader(tensors))+ if err != nil {+ t.Fatalf("failed to build packed safetensors: %v", err)}-- for _, tensor := range packedLayerTensors[0] {- want := "nvfp4"- if strings.Contains(tensor.Name, "down_proj") {- want = "mxfp8"- }- if tensor.Quantize != want {- t.Fatalf("nvfp4 packed tensor %s quantize = %q, want %q", tensor.Name, tensor.Quantize, want)- }+ if err := os.WriteFile(path, data, 0o644); err != nil {+ t.Fatalf("failed to write safetensors: %v", err)}}-func TestCreateSafetensorsModel_Qwen35Transforms(t *testing.T) {- dir := t.TempDir()-- configJSON := `{- "model_type": "test",- "architectures": ["Qwen3_5MoeForConditionalGeneration"],- "text_config": {"dtype": "bfloat16"}- }`- if err := os.WriteFile(filepath.Join(dir, "config.json"), []byte(configJSON), 0o644); err != nil {- t.Fatalf("failed to write config.json: %v", err)+func encodeFloat32s(vals ...float32) []byte {+ raw := make([]byte, 4*len(vals))+ for i, v := range vals {+ binary.LittleEndian.PutUint32(raw[i*4:(i+1)*4], math.Float32bits(v))}+ return raw+}- gateUpValues := make([]float32, 2*128*64)- for expert := range 2 {- base := expert * 128 * 64- for i := range 64 * 64 {- gateUpValues[base+i] = 1- gateUpValues[base+64*64+i] = 2- }- }+func readSafetensorsHeaderNames(t *testing.T, data []byte) []string {+ t.Helper()- createTestSafetensors(t, filepath.Join(dir, "model.safetensors"), []*st.TensorData{- st.NewTensorDataFromBytes("model.language_model.embed_tokens.weight", "BF16", []int32{64, 64}, make([]byte, 64*64*2)),- st.NewTensorDataFromBytes("model.language_model.layers.0.input_layernorm.weight", "F32", []int32{64}, make([]byte, 64*4)),- st.NewTensorDataFromBytes("model.language_model.layers.0.linear_attn.A_log", "F32", []int32{32}, make([]byte, 32*4)),- st.NewTensorDataFromBytes("model.language_model.layers.0.linear_attn.conv1d.weight", "BF16", []int32{64, 1, 4}, make([]byte, 64*1*4*2)),- st.NewTensorDataFromBytes("model.language_model.layers.0.mlp.gate.weight", "BF16", []int32{64, 64}, make([]byte, 64*64*2)),- st.NewTensorDataFromBytes("model.language_model.layers.0.mlp.experts.gate_up_proj", "BF16", []int32{2, 128, 64}, bfloat16.EncodeFloat32(gateUpValues)),- st.NewTensorDataFromBytes("model.language_model.layers.0.mlp.experts.down_proj", "BF16", []int32{2, 64, 64}, bfloat16.EncodeFloat32(make([]float32, 2*64*64))),- st.NewTensorDataFromBytes("model.language_model.layers.0.mlp.shared_expert.down_proj.weight", "BF16", []int32{64, 64}, make([]byte, 64*64*2)),- st.NewTensorDataFromBytes("model.visual.blocks.0.attn.proj.weight", "BF16", []int32{64, 64}, make([]byte, 64*64*2)),- st.NewTensorDataFromBytes("mtp.layers.0.foo.weight", "F32", []int32{64, 64}, make([]byte, 64*64*4)),- })-- type tensorCall struct {- dtype string- shape []int32- quantize string- raw []byte+ var headerSize uint64+ if err := binary.Read(bytes.NewReader(data[:8]), binary.LittleEndian, &headerSize); err != nil {+ t.Fatalf("failed to read header size: %v", err)}- calls := make(map[string]tensorCall)- createLayer := func(r io.Reader, mediaType, name string) (LayerInfo, error) {- _, _ = io.ReadAll(r)- return LayerInfo{Name: name, Digest: "sha256:" + name, MediaType: mediaType}, nil+ var header map[string]json.RawMessage+ if err := json.Unmarshal(data[8:8+headerSize], &header); err != nil {+ t.Fatalf("failed to parse header: %v", err)}- createTensorLayer := func(r io.Reader, name, dtype string, shape []int32, quantize string) ([]LayerInfo, error) {- data, err := io.ReadAll(r)- if err != nil {- return nil, err- }- headerDType, headerShape := readSingleTensorHeader(t, data)- calls[name] = tensorCall{- dtype: headerDType,- shape: headerShape,- quantize: quantize,- raw: readSingleTensorRaw(t, data),+ names := make([]string, 0, len(header))+ for name := range header {+ if name == "__metadata__" {+ continue}- return []LayerInfo{{Name: name, Digest: "sha256:" + name, MediaType: "application/vnd.ollama.image.tensor"}}, nil- }-- writeManifest := func(modelName string, config LayerInfo, layers []LayerInfo) error {- return nil- }-- if err := CreateSafetensorsModel("test-model", dir, "int4", createLayer, createTensorLayer, writeManifest, func(string) {}); err != nil {- t.Fatalf("CreateSafetensorsModel failed: %v", err)- }-- if _, ok := calls["mtp.layers.0.foo.weight"]; !ok {- t.Fatal("mtp tensor should have been preserved")- }-- layerNorm := calls["language_model.model.layers.0.input_layernorm.weight"]- if layerNorm.dtype != "BF16" {- t.Fatalf("input_layernorm dtype = %q, want %q", layerNorm.dtype, "BF16")- }- if layerNorm.quantize != "" {- t.Fatalf("input_layernorm quantize = %q, want empty", layerNorm.quantize)- }- layerNormValues := bfloat16.DecodeFloat32(layerNorm.raw)- if len(layerNormValues) == 0 || layerNormValues[0] != 1.0 {- t.Fatalf("input_layernorm first value = %v, want 1.0 after +1 shift", layerNormValues[0])- }-- alog := calls["language_model.model.layers.0.linear_attn.A_log"]- if alog.dtype != "F32" {- t.Fatalf("A_log dtype = %q, want %q", alog.dtype, "F32")- }-- conv := calls["language_model.model.layers.0.linear_attn.conv1d.weight"]- if !slices.Equal(conv.shape, []int32{64, 4, 1}) {- t.Fatalf("conv1d shape = %v, want %v", conv.shape, []int32{64, 4, 1})- }-- if got := calls["language_model.model.embed_tokens.weight"].quantize; got != "int4" {- t.Fatalf("embed_tokens quantize = %q, want %q", got, "int4")- }- if got := calls["language_model.model.layers.0.mlp.gate.weight"].quantize; got != "int4" {- t.Fatalf("mlp.gate quantize = %q, want %q", got, "int4")- }- if got := calls["language_model.model.layers.0.mlp.shared_expert.down_proj.weight"].quantize; got != "int4" {- t.Fatalf("down_proj quantize = %q, want %q", got, "int4")+ names = append(names, name)}+ slices.Sort(names)+ return names+}- if _, ok := calls["language_model.model.layers.0.mlp.experts.gate_up_proj"]; ok {- t.Fatal("combined gate_up_proj tensor should have been rewritten")- }- if _, ok := calls["language_model.model.layers.0.mlp.experts.down_proj"]; ok {- t.Fatal("combined down_proj tensor should have been rewritten")- }+func readPackedTensorRaw(t *testing.T, data []byte, tensorName string) []byte {+ t.Helper()- gateProj := calls["language_model.model.layers.0.mlp.switch_mlp.gate_proj.weight"]- if !slices.Equal(gateProj.shape, []int32{2, 64, 64}) {- t.Fatalf("gate_proj shape = %v, want %v", gateProj.shape, []int32{2, 64, 64})- }- gateProjValues := bfloat16.DecodeFloat32(gateProj.raw)- if len(gateProjValues) == 0 || gateProjValues[0] != 1.0 {- t.Fatalf("gate_proj first value = %v, want 1.0", gateProjValues[0])+ var headerSize uint64+ if err := binary.Read(bytes.NewReader(data[:8]), binary.LittleEndian, &headerSize); err != nil {+ t.Fatalf("failed to read header size: %v", err)}- upProj := calls["language_model.model.layers.0.mlp.switch_mlp.up_proj.weight"]- if !slices.Equal(upProj.shape, []int32{2, 64, 64}) {- t.Fatalf("up_proj shape = %v, want %v", upProj.shape, []int32{2, 64, 64})- }- upProjValues := bfloat16.DecodeFloat32(upProj.raw)- if len(upProjValues) == 0 || upProjValues[0] != 2.0 {- t.Fatalf("up_proj first value = %v, want 2.0", upProjValues[0])+ var header map[string]struct {+ Dtype string `json:"dtype"`+ Shape []int32 `json:"shape"`+ DataOffsets [2]int `json:"data_offsets"`}-- if got := calls["language_model.model.layers.0.mlp.switch_mlp.down_proj.weight"].quantize; got != "int4" {- t.Fatalf("switch_mlp down_proj quantize = %q, want %q", got, "int4")+ if err := json.Unmarshal(data[8:8+headerSize], &header); err != nil {+ t.Fatalf("failed to parse header: %v", err)}- vision := calls["vision_tower.blocks.0.attn.proj.weight"]- if vision.dtype != "BF16" {- t.Fatalf("vision weight dtype = %q, want %q", vision.dtype, "BF16")- }- if vision.quantize != "" {- t.Fatalf("vision weight quantize = %q, want empty", vision.quantize)- }- if _, ok := calls["language_model.model.visual.blocks.0.attn.proj.weight"]; ok {- t.Fatal("vision tensor should have been rewritten to vision_tower.*")+ info, ok := header[tensorName]+ if !ok {+ t.Fatalf("tensor %q not found in header", tensorName)}-}--func TestCreateSafetensorsModel_Qwen35DirectNonAffineKeepsSensitiveWeightsBF16(t *testing.T) {- for _, quantize := range []string{"nvfp4", "mxfp8", "mxfp4"} {- t.Run(quantize, func(t *testing.T) {- dir := t.TempDir()-- configJSON := `{- "model_type": "test",- "architectures": ["Qwen3_5MoeForConditionalGeneration"],- "text_config": {"dtype": "bfloat16"}- }`- if err := os.WriteFile(filepath.Join(dir, "config.json"), []byte(configJSON), 0o644); err != nil {- t.Fatalf("failed to write config.json: %v", err)- }-- gateUpValues := make([]float32, 2*128*64)- for expert := range 2 {- base := expert * 128 * 64- for i := range 64 * 64 {- gateUpValues[base+i] = 1- gateUpValues[base+64*64+i] = 2- }- }-- createTestSafetensors(t, filepath.Join(dir, "model.safetensors"), []*st.TensorData{- st.NewTensorDataFromBytes("model.language_model.embed_tokens.weight", "BF16", []int32{64, 64}, make([]byte, 64*64*2)),- st.NewTensorDataFromBytes("lm_head.weight", "BF16", []int32{64, 64}, make([]byte, 64*64*2)),- st.NewTensorDataFromBytes("model.language_model.layers.0.linear_attn.in_proj_a.weight", "BF16", []int32{32, 64}, make([]byte, 32*64*2)),- st.NewTensorDataFromBytes("model.language_model.layers.0.linear_attn.in_proj_b.weight", "BF16", []int32{32, 64}, make([]byte, 32*64*2)),- st.NewTensorDataFromBytes("model.language_model.layers.0.mlp.gate.weight", "BF16", []int32{64, 64}, make([]byte, 64*64*2)),- st.NewTensorDataFromBytes("model.language_model.layers.0.mlp.shared_expert_gate.weight", "BF16", []int32{1, 64}, make([]byte, 64*2)),- st.NewTensorDataFromBytes("model.language_model.layers.0.self_attn.q_proj.weight", "BF16", []int32{64, 64}, make([]byte, 64*64*2)),- st.NewTensorDataFromBytes("model.language_model.layers.0.mlp.experts.gate_up_proj", "BF16", []int32{2, 128, 64}, bfloat16.EncodeFloat32(gateUpValues)),- st.NewTensorDataFromBytes("model.language_model.layers.0.mlp.experts.down_proj", "BF16", []int32{2, 64, 64}, bfloat16.EncodeFloat32(make([]float32, 2*64*64))),- })-- type tensorCall struct {- quantize string- }- type packedTensorCall struct {- Name string- Quantize string- }-- tensorCalls := make(map[string]tensorCall)- packedCalls := make(map[string][]packedTensorCall)-- createLayer := func(r io.Reader, mediaType, name string) (LayerInfo, error) {- _, _ = io.ReadAll(r)- return LayerInfo{Name: name, Digest: "sha256:" + name, MediaType: mediaType}, nil- }-- createTensorLayer := func(r io.Reader, name, dtype string, shape []int32, quantizeType string) ([]LayerInfo, error) {- _, _ = io.ReadAll(r)- tensorCalls[name] = tensorCall{quantize: quantizeType}- return []LayerInfo{{Name: name, Digest: "sha256:" + name, MediaType: "application/vnd.ollama.image.tensor"}}, nil- }-- createPackedLayer := func(groupName string, tensors []PackedTensorInput) (LayerInfo, error) {- group := make([]packedTensorCall, 0, len(tensors))- for _, tensor := range tensors {- group = append(group, packedTensorCall{- Name: tensor.Name,- Quantize: tensor.Quantize,- })- }- packedCalls[groupName] = group- return LayerInfo{Name: groupName, Digest: "sha256:" + groupName, MediaType: "application/vnd.ollama.image.tensor"}, nil- }-- writeManifest := func(modelName string, config LayerInfo, layers []LayerInfo) error {- return nil- }-- if err := CreateSafetensorsModel("test-model", dir, quantize, createLayer, createTensorLayer, writeManifest, func(string) {}, createPackedLayer); err != nil {- t.Fatalf("CreateSafetensorsModel failed: %v", err)- }-- for _, name := range []string{- "language_model.model.embed_tokens.weight",- "language_model.lm_head.weight",- "language_model.model.layers.0.linear_attn.in_proj_a.weight",- "language_model.model.layers.0.linear_attn.in_proj_b.weight",- "language_model.model.layers.0.mlp.gate.weight",- "language_model.model.layers.0.mlp.shared_expert_gate.weight",- } {- if got := tensorCalls[name].quantize; got != "" {- t.Fatalf("%s quantize = %q, want empty", name, got)- }- }-- if got := tensorCalls["language_model.model.layers.0.self_attn.q_proj.weight"].quantize; got != quantize {- t.Fatalf("q_proj quantize = %q, want %q", got, quantize)- }- group := packedCalls["language_model.model.layers.0.mlp.switch_mlp"]- if len(group) != 3 {- t.Fatalf("packed switch_mlp tensor count = %d, want 3", len(group))- }- for _, tensor := range group {- if tensor.Quantize != quantize {- t.Fatalf("packed tensor %q quantize = %q, want %q", tensor.Name, tensor.Quantize, quantize)- }- }- })- }+ start := 8 + int(headerSize) + info.DataOffsets[0]+ end := 8 + int(headerSize) + info.DataOffsets[1]+ return data[start:end]}func TestResolveManifestPath(t *testing.T) {@@ -1919,65 +406,6 @@ func TestShouldQuantize(t *testing.T) {}}-func TestShouldQuantizeTensor(t *testing.T) {- tests := []struct {- name string- tensor string- shape []int32- quantize string- want bool- }{- // 2D tensors with sufficient size should be quantized- {"large 2D weight fp8", "q_proj.weight", []int32{4096, 4096}, "fp8", true},- {"medium 2D weight fp8", "small_proj.weight", []int32{128, 128}, "fp8", true},- {"large 2D weight nvfp4", "q_proj.weight", []int32{4096, 4096}, "nvfp4", true},- {"large 2D weight mxfp4", "q_proj.weight", []int32{4096, 4096}, "mxfp4", true},-- // Small tensors should not be quantized (< 1024 elements)- {"tiny 2D weight", "tiny.weight", []int32{16, 16}, "fp8", false},- {"small 2D weight", "small.weight", []int32{31, 31}, "fp8", false},-- // 1D tensors should not be quantized- {"1D tensor", "layer_norm.weight", []int32{4096}, "fp8", false},-- // 3D+ tensors should not be quantized- {"3D tensor", "conv.weight", []int32{64, 64, 3}, "fp8", false},- {"4D tensor", "conv2d.weight", []int32{64, 64, 3, 3}, "fp8", false},- {"stacked expert switch_mlp gate_up 3D int8", "model.layers.1.mlp.switch_mlp.gate_up_proj.weight", []int32{64, 22016, 4096}, "int8", true},- {"stacked expert experts down_proj 3D int8", "model.layers.1.mlp.experts.down_proj.weight", []int32{64, 4096, 14336}, "int8", true},- {"stacked expert combined gate_up 3D int8", "model.language_model.layers.0.mlp.experts.gate_up_proj", []int32{256, 1024, 2048}, "int8", true},- {"stacked expert combined down_proj 3D int8", "model.language_model.layers.0.mlp.experts.down_proj", []int32{256, 2048, 512}, "int8", true},-- // Embeddings should not be quantized regardless of shape- {"embedding 2D", "embed_tokens.weight", []int32{32000, 4096}, "fp8", false},-- // Norms should not be quantized regardless of shape- {"norm 2D", "layer_norm.weight", []int32{4096, 1}, "fp8", false},-- // Biases should not be quantized- {"bias 2D", "proj.bias", []int32{4096, 1}, "fp8", false},-- // Group size divisibility tests- // FP8/FP4/MXFP4 require divisible by 32- {"not divisible by 32 fp8", "proj.weight", []int32{128, 48}, "fp8", false},- {"divisible by 32 fp8", "proj.weight", []int32{128, 64}, "fp8", true},- {"not divisible by 32 mxfp4", "proj.weight", []int32{128, 48}, "mxfp4", false},- {"divisible by 32 mxfp4", "proj.weight", []int32{128, 64}, "mxfp4", true},- // NVFP4 requires divisible by 16- {"not divisible by 16 nvfp4", "proj.weight", []int32{128, 24}, "nvfp4", false},- {"divisible by 16 nvfp4", "proj.weight", []int32{128, 48}, "nvfp4", true},- }-- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- got := ShouldQuantizeTensor(tt.tensor, tt.shape, tt.quantize)- if got != tt.want {- t.Errorf("ShouldQuantizeTensor(%q, %v, %q) = %v, want %v", tt.tensor, tt.shape, tt.quantize, got, tt.want)- }- })- }-}-func TestExpertGroupPrefix(t *testing.T) {tests := []struct {name string@@ -2161,14 +589,20 @@ func TestGetTensorQuantization_MixedPrecisionPromotion(t *testing.T) {{"gate_proj int4 stays", "model.layers.0.mlp.gate_proj.weight", aligned, "int4", "int4"},{"up_proj int4 stays", "model.layers.0.mlp.up_proj.weight", aligned, "int4", "int4"},- // nvfp4/mxfp4/mxfp8: no promotion (uniform quantization)- {"v_proj nvfp4 uniform", "model.layers.0.self_attn.v_proj.weight", aligned, "nvfp4", "nvfp4"},- {"down_proj mxfp4 uniform", "model.layers.0.mlp.down_proj.weight", aligned, "mxfp4", "mxfp4"},+ // nvfp4/mxfp4 → mxfp8 promotion for sensitive tensors; mxfp8 stays uniform+ {"v_proj nvfp4 promoted", "model.layers.0.self_attn.v_proj.weight", aligned, "nvfp4", "mxfp8"},+ {"down_proj mxfp4 promoted", "model.layers.0.mlp.down_proj.weight", aligned, "mxfp4", "mxfp8"},+ {"q_proj nvfp4 stays", "model.layers.0.self_attn.q_proj.weight", aligned, "nvfp4", "nvfp4"},{"v_proj mxfp8 uniform", "model.layers.0.self_attn.v_proj.weight", aligned, "mxfp8", "mxfp8"},// int8: already 8-bit, no promotion{"v_proj int8 stays", "model.layers.0.self_attn.v_proj.weight", aligned, "int8", "int8"},+ // lm_head stays at source precision for fp modes, quantizes for affine+ {"lm_head nvfp4 kept", "lm_head.weight", aligned, "nvfp4", ""},+ {"lm_head mxfp8 kept", "lm_head.weight", aligned, "mxfp8", ""},+ {"lm_head int4 stays", "lm_head.weight", aligned, "int4", "int4"},+// Expert tensors: down_proj also promoted for int4{"expert down_proj int4", "model.layers.0.mlp.experts.down_proj.weight", []int32{128, 4096, 2816}, "int4", "int8"},{"moe expert down_proj int4", "model.layers.0.moe.experts.down_proj.weight", []int32{128, 4096, 2816}, "int4", "int8"},@@ -2187,297 +621,3 @@ func TestGetTensorQuantization_MixedPrecisionPromotion(t *testing.T) {})}}--func TestCreateSafetensorsModel_Qwen35NVFP4PacksSwitchMLPExperts(t *testing.T) {- dir := t.TempDir()-- configJSON := `{- "model_type": "test",- "architectures": ["Qwen3_5MoeForConditionalGeneration"],- "text_config": {"dtype": "bfloat16"}- }`- if err := os.WriteFile(filepath.Join(dir, "config.json"), []byte(configJSON), 0o644); err != nil {- t.Fatalf("failed to write config.json: %v", err)- }-- gateUpValues := make([]float32, 2*128*64)- for expert := range 2 {- base := expert * 128 * 64- for i := range 64 * 64 {- gateUpValues[base+i] = 1- gateUpValues[base+64*64+i] = 2- }- }-- createTestSafetensors(t, filepath.Join(dir, "model.safetensors"), []*st.TensorData{- st.NewTensorDataFromBytes("model.language_model.embed_tokens.weight", "BF16", []int32{64, 64}, make([]byte, 64*64*2)),- st.NewTensorDataFromBytes("model.language_model.layers.0.mlp.gate.weight", "BF16", []int32{64, 64}, make([]byte, 64*64*2)),- st.NewTensorDataFromBytes("model.language_model.layers.0.mlp.experts.gate_up_proj", "BF16", []int32{2, 128, 64}, bfloat16.EncodeFloat32(gateUpValues)),- st.NewTensorDataFromBytes("model.language_model.layers.0.mlp.experts.down_proj", "BF16", []int32{2, 64, 64}, bfloat16.EncodeFloat32(make([]float32, 2*64*64))),- })-- type tensorCall struct {- quantize string- }- type packedTensorCall struct {- Name string- Dtype string- Shape []int32- Quantize string- }-- tensorCalls := make(map[string]tensorCall)- packedCalls := make(map[string][]packedTensorCall)-- createLayer := func(r io.Reader, mediaType, name string) (LayerInfo, error) {- _, _ = io.ReadAll(r)- return LayerInfo{Name: name, Digest: "sha256:" + name, MediaType: mediaType}, nil- }-- createTensorLayer := func(r io.Reader, name, dtype string, shape []int32, quantize string) ([]LayerInfo, error) {- _, _ = io.ReadAll(r)- tensorCalls[name] = tensorCall{quantize: quantize}- return []LayerInfo{{Name: name, Digest: "sha256:" + name, MediaType: "application/vnd.ollama.image.tensor"}}, nil- }-- createPackedLayer := func(groupName string, tensors []PackedTensorInput) (LayerInfo, error) {- group := make([]packedTensorCall, 0, len(tensors))- for _, tensor := range tensors {- group = append(group, packedTensorCall{- Name: tensor.Name,- Dtype: tensor.Dtype,- Shape: append([]int32(nil), tensor.Shape...),- Quantize: tensor.Quantize,- })- }- packedCalls[groupName] = group- return LayerInfo{Name: groupName, Digest: "sha256:" + groupName, MediaType: "application/vnd.ollama.image.tensor"}, nil- }-- writeManifest := func(modelName string, config LayerInfo, layers []LayerInfo) error {- return nil- }-- if err := CreateSafetensorsModel("test-model", dir, "nvfp4", createLayer, createTensorLayer, writeManifest, func(string) {}, createPackedLayer); err != nil {- t.Fatalf("CreateSafetensorsModel failed: %v", err)- }-- groupName := "language_model.model.layers.0.mlp.switch_mlp"- group, ok := packedCalls[groupName]- if !ok {- t.Fatalf("missing packed group %q: %v", groupName, packedCalls)- }-- if len(group) != 3 {- t.Fatalf("packed group %q has %d tensors, want 3", groupName, len(group))- }-- gotNames := make([]string, 0, len(group))- for _, tensor := range group {- gotNames = append(gotNames, tensor.Name)- if tensor.Quantize != "nvfp4" {- t.Fatalf("packed tensor %q quantize = %q, want %q", tensor.Name, tensor.Quantize, "nvfp4")- }- if tensor.Dtype != "BF16" {- t.Fatalf("packed tensor %q dtype = %q, want %q", tensor.Name, tensor.Dtype, "BF16")- }- }- slices.Sort(gotNames)-- wantNames := []string{- "language_model.model.layers.0.mlp.switch_mlp.down_proj.weight",- "language_model.model.layers.0.mlp.switch_mlp.gate_proj.weight",- "language_model.model.layers.0.mlp.switch_mlp.up_proj.weight",- }- if !slices.Equal(gotNames, wantNames) {- t.Fatalf("packed tensor names = %v, want %v", gotNames, wantNames)- }-- for _, name := range wantNames {- if _, ok := tensorCalls[name]; ok {- t.Fatalf("packed expert tensor %q unexpectedly handled by createTensorLayer", name)- }- }-- if got := tensorCalls["language_model.model.embed_tokens.weight"].quantize; got != "" {- t.Fatalf("embed_tokens quantize = %q, want empty", got)- }- if got := tensorCalls["language_model.model.layers.0.mlp.gate.weight"].quantize; got != "" {- t.Fatalf("mlp.gate quantize = %q, want empty", got)- }-}--func TestCreateSafetensorsModel_WithQuantize(t *testing.T) {- dir := t.TempDir()-- // Create config.json- configJSON := `{"model_type": "test", "architectures": ["TestModel"]}`- if err := os.WriteFile(filepath.Join(dir, "config.json"), []byte(configJSON), 0o644); err != nil {- t.Fatalf("failed to write config.json: %v", err)- }-- // Create a minimal safetensors file- createMinimalSafetensors(t, filepath.Join(dir, "model.safetensors"))-- var quantizeRequested []string-- createLayer := func(r io.Reader, mediaType, name string) (LayerInfo, error) {- io.ReadAll(r)- return LayerInfo{Name: name, Digest: "sha256:test"}, nil- }-- createTensorLayer := func(r io.Reader, name, dtype string, shape []int32, quantize string) ([]LayerInfo, error) {- io.ReadAll(r)- quantizeRequested = append(quantizeRequested, quantize)- return []LayerInfo{{Name: name}}, nil- }-- writeManifest := func(modelName string, config LayerInfo, layers []LayerInfo) error {- return nil- }-- progressFn := func(status string) {}-- // Run with quantize enabled- err := CreateSafetensorsModel("test-model", dir, "fp8", createLayer, createTensorLayer, writeManifest, progressFn)- if err != nil {- t.Fatalf("CreateSafetensorsModel failed: %v", err)- }-- // Verify quantize was passed to callback (will be false for small test tensor)- if len(quantizeRequested) == 0 {- t.Error("no tensors processed")- }-}--// createMinimalImageGenModel creates a minimal diffusers-style model directory-func createMinimalImageGenModel(t *testing.T, dir string) {- t.Helper()-- // Create model_index.json- modelIndex := `{"_class_name": "FluxPipeline", "_diffusers_version": "0.30.0"}`- if err := os.WriteFile(filepath.Join(dir, "model_index.json"), []byte(modelIndex), 0o644); err != nil {- t.Fatalf("failed to write model_index.json: %v", err)- }-- // Create transformer directory with a safetensors file- transformerDir := filepath.Join(dir, "transformer")- if err := os.MkdirAll(transformerDir, 0o755); err != nil {- t.Fatalf("failed to create transformer dir: %v", err)- }- createMinimalSafetensors(t, filepath.Join(transformerDir, "model.safetensors"))-- // Create transformer config- transformerConfig := `{"hidden_size": 3072}`- if err := os.WriteFile(filepath.Join(transformerDir, "config.json"), []byte(transformerConfig), 0o644); err != nil {- t.Fatalf("failed to write transformer config: %v", err)- }-}--func TestCreateImageGenModel(t *testing.T) {- dir := t.TempDir()- createMinimalImageGenModel(t, dir)-- var manifestWritten bool- var manifestModelName string- var statusMessages []string-- createLayer := func(r io.Reader, mediaType, name string) (LayerInfo, error) {- io.ReadAll(r)- return LayerInfo{Name: name, Digest: "sha256:test"}, nil- }-- createTensorLayer := func(r io.Reader, name, dtype string, shape []int32, quantize string) ([]LayerInfo, error) {- io.ReadAll(r)- return []LayerInfo{{Name: name, Digest: "sha256:tensor"}}, nil- }-- writeManifest := func(modelName string, config LayerInfo, layers []LayerInfo) error {- manifestWritten = true- manifestModelName = modelName- return nil- }-- progressFn := func(status string) {- statusMessages = append(statusMessages, status)- }-- err := CreateImageGenModel("test-imagegen", dir, "", createLayer, createTensorLayer, writeManifest, progressFn)- if err != nil {- t.Fatalf("CreateImageGenModel failed: %v", err)- }-- if !manifestWritten {- t.Error("manifest was not written")- }-- if manifestModelName != "test-imagegen" {- t.Errorf("manifest model name = %q, want %q", manifestModelName, "test-imagegen")- }-- if len(statusMessages) == 0 {- t.Error("no status messages received")- }-}--func TestCreateImageGenModel_NoModelIndex(t *testing.T) {- dir := t.TempDir()-- // Create only transformer without model_index.json- transformerDir := filepath.Join(dir, "transformer")- if err := os.MkdirAll(transformerDir, 0o755); err != nil {- t.Fatalf("failed to create transformer dir: %v", err)- }- createMinimalSafetensors(t, filepath.Join(transformerDir, "model.safetensors"))-- createLayer := func(r io.Reader, mediaType, name string) (LayerInfo, error) {- io.ReadAll(r)- return LayerInfo{Name: name}, nil- }- createTensorLayer := func(r io.Reader, name, dtype string, shape []int32, quantize string) ([]LayerInfo, error) {- io.ReadAll(r)- return []LayerInfo{{Name: name}}, nil- }- writeManifest := func(modelName string, config LayerInfo, layers []LayerInfo) error {- return nil- }- progressFn := func(status string) {}-- err := CreateImageGenModel("test-imagegen", dir, "", createLayer, createTensorLayer, writeManifest, progressFn)- if err == nil {- t.Error("expected error for missing model_index.json, got nil")- }-}--func TestCreateImageGenModel_WithQuantize(t *testing.T) {- dir := t.TempDir()- createMinimalImageGenModel(t, dir)-- var quantizeRequested []string-- createLayer := func(r io.Reader, mediaType, name string) (LayerInfo, error) {- io.ReadAll(r)- return LayerInfo{Name: name, Digest: "sha256:test"}, nil- }-- createTensorLayer := func(r io.Reader, name, dtype string, shape []int32, quantize string) ([]LayerInfo, error) {- io.ReadAll(r)- quantizeRequested = append(quantizeRequested, quantize)- return []LayerInfo{{Name: name}}, nil- }-- writeManifest := func(modelName string, config LayerInfo, layers []LayerInfo) error {- return nil- }-- progressFn := func(status string) {}-- err := CreateImageGenModel("test-imagegen", dir, "int8", createLayer, createTensorLayer, writeManifest, progressFn)- if err != nil {- t.Fatalf("CreateImageGenModel failed: %v", err)- }-- if len(quantizeRequested) == 0 {- t.Error("no tensors processed")- }-}diff --git a/x/create/draft.go b/x/create/draft.gonew file mode 100644index 000000000..b6e3d9f51--- /dev/null+++ b/x/create/draft.go@@ -0,0 +1,83 @@+package create++import "fmt"++// CreateDraftLayers imports a draft (speculative-decoding / MTP assistant)+// safetensors model into prefixed tensor and config blobs and returns the+// layers WITHOUT writing a manifest — the caller folds them into the target+// model's manifest. A draft never stands alone; it always accompanies a target+// model named on the Modelfile's FROM line.+//+// It runs the same read → classify → plan → write pipeline as Create. Output+// tensor names keep their source form, namespaced by tensorPrefix (e.g.+// "draft.") so they cannot collide with the target's tensors; config blobs are+// named under configPrefix (e.g. "draft/").+func CreateDraftLayers(modelDir, tensorPrefix, configPrefix, quantize string, store BlobStore, fn func(status string)) ([]LayerInfo, error) {+ if tensorPrefix == "" {+ return nil, fmt.Errorf("draft tensor prefix must not be empty")+ }+ if configPrefix == "" {+ return nil, fmt.Errorf("draft config prefix must not be empty")+ }+ defer sweepMLX()++ inv, err := ReadInventory(modelDir)+ if err != nil {+ return nil, fmt.Errorf("read draft model: %w", err)+ }+ class, err := Classify(inv, quantize)+ if err != nil {+ return nil, err+ }+ policy, err := newTensorImportTransform(inv)+ if err != nil {+ return nil, fmt.Errorf("build draft quantization policy for %q: %w", inv.Config.Architecture(), err)+ }+ specs, err := Plan(inv, class, draftPolicy{policy})+ if err != nil {+ return nil, fmt.Errorf("plan draft model: %w", err)+ }+ specs = prefixSpecs(specs, tensorPrefix)++ fn(fmt.Sprintf("importing draft (%d tensors%s)", len(inv.Tensors), quantizeStatus(class)))+ layers, err := WriteBlobs(specs, modelDir, store)+ if err != nil {+ return nil, err+ }++ configLayers, _, err := importConfigBlobs(modelDir, configPrefix, store, fn)+ if err != nil {+ return nil, err+ }+ return append(layers, configLayers...), nil+}++// prefixSpecs returns specs with prefix prepended to every output blob name and+// output tensor name, leaving the source references (which point at the source+// files) untouched. Scale/bias keys derive from the tensor name, so they inherit+// the prefix automatically.+func prefixSpecs(specs []BlobSpec, prefix string) []BlobSpec {+ out := make([]BlobSpec, len(specs))+ for i, spec := range specs {+ tensors := make([]TensorSpec, len(spec.Tensors))+ for j, ts := range spec.Tensors {+ ts.Name = prefix + ts.Name+ tensors[j] = ts+ }+ out[i] = BlobSpec{Name: prefix + spec.Name, Tensors: tensors, Metadata: spec.Metadata}+ }+ return out+}++// draftPolicy wraps an architecture policy to keep a draft model's token+// embedding at source precision (drafts start with unquantized embeddings; this+// may change later). Every other tensor follows the wrapped policy. It is given+// unprefixed source names, since planning runs before prefixSpecs.+type draftPolicy struct{ inner quantizePolicy }++func (p draftPolicy) quantizationType(name string, shape []int32, requested string) string {+ if isEmbedTokensWeight(name) {+ return ""+ }+ return p.inner.quantizationType(name, shape, requested)+}diff --git a/x/create/draft_test.go b/x/create/draft_test.gonew file mode 100644index 000000000..6bf9ff67f--- /dev/null+++ b/x/create/draft_test.go@@ -0,0 +1,121 @@+package create++import (+ "io"+ "os"+ "path/filepath"+ "slices"+ "testing"++ st "github.com/ollama/ollama/x/safetensors"+)++// recordingStore captures the blobs a pipeline run produces so tests can assert+// on their names and contents.+type recordingStore struct {+ names []string+ blobs map[string][]byte+}++func (s *recordingStore) WriteBlob(r io.Reader, mediaType, name string) (LayerInfo, error) {+ data, err := io.ReadAll(r)+ if err != nil {+ return LayerInfo{}, err+ }+ if s.blobs == nil {+ s.blobs = map[string][]byte{}+ }+ s.blobs[name] = data+ s.names = append(s.names, name)+ return LayerInfo{Digest: "sha256:" + name, Size: int64(len(data)), MediaType: mediaType, Name: name}, nil+}++func TestPrefixSpecs(t *testing.T) {+ specs := []BlobSpec{+ {+ Name: "model.layers.0.mlp.experts",+ Tensors: []TensorSpec{{+ Name: "model.layers.0.mlp.experts.gate_proj.weight",+ Sources: []SourceTensor{{Name: "model.layers.0.mlp.experts.0.gate_proj.weight", File: "a.safetensors"}},+ Quantize: "int8",+ }},+ },+ }+ got := prefixSpecs(specs, "draft.")++ if got[0].Name != "draft.model.layers.0.mlp.experts" {+ t.Errorf("blob name = %q, want draft.-prefixed", got[0].Name)+ }+ if got[0].Tensors[0].Name != "draft.model.layers.0.mlp.experts.gate_proj.weight" {+ t.Errorf("tensor name = %q, want draft.-prefixed", got[0].Tensors[0].Name)+ }+ if got[0].Tensors[0].Quantize != "int8" {+ t.Errorf("quantize = %q, want it preserved", got[0].Tensors[0].Quantize)+ }+ // Sources point at the source files and must not be prefixed.+ if got[0].Tensors[0].Sources[0].Name != "model.layers.0.mlp.experts.0.gate_proj.weight" {+ t.Errorf("source name = %q, want unchanged", got[0].Tensors[0].Sources[0].Name)+ }+ // The input must not be mutated.+ if specs[0].Name != "model.layers.0.mlp.experts" || specs[0].Tensors[0].Name != "model.layers.0.mlp.experts.gate_proj.weight" {+ t.Errorf("prefixSpecs mutated its input: %+v", specs[0])+ }+}++func TestDraftPolicyKeepsEmbeddingsUnquantized(t *testing.T) {+ p := draftPolicy{defaultQuantPolicy{}}++ // Draft token embeddings start unquantized regardless of the request.+ if got := p.quantizationType("model.embed_tokens.weight", []int32{4096, 2048}, "int8"); got != "" {+ t.Errorf("draft embed_tokens quant = %q, want \"\"", got)+ }+ // Other eligible weights still follow the wrapped policy.+ if got := p.quantizationType("model.layers.0.mlp.down_proj.weight", []int32{2048, 2048}, "int8"); got == "" {+ t.Errorf("draft down_proj quant = \"\", want it quantized via the inner policy")+ }+}++func TestCreateDraftLayersPrefixesNamesAndConfig(t *testing.T) {+ dir := t.TempDir()+ if err := os.WriteFile(filepath.Join(dir, "config.json"), []byte(`{"architectures":["LlamaForCausalLM"]}`), 0o644); err != nil {+ t.Fatal(err)+ }+ createTestSafetensors(t, filepath.Join(dir, "model.safetensors"), []*st.TensorData{+ st.NewTensorDataFromBytes("model.embed_tokens.weight", "BF16", []int32{4, 8}, make([]byte, 4*8*2)),+ st.NewTensorDataFromBytes("model.norm.weight", "BF16", []int32{8}, make([]byte, 8*2)),+ })++ store := &recordingStore{}+ layers, err := CreateDraftLayers(dir, "draft.", "draft/", "", store, func(string) {})+ if err != nil {+ t.Fatalf("CreateDraftLayers: %v", err)+ }+ if len(layers) == 0 {+ t.Fatal("CreateDraftLayers returned no layers")+ }++ // Tensor blobs are namespaced under draft.; the config under draft/.+ if !slices.Contains(store.names, "draft.model.embed_tokens.weight") {+ t.Errorf("missing draft.-prefixed tensor blob; got %v", store.names)+ }+ if !slices.Contains(store.names, "draft/config.json") {+ t.Errorf("missing draft/config.json; got %v", store.names)+ }++ // The prefix must also land inside the blob, since the runtime resolves+ // draft tensors by the "draft." name prefix.+ names := readSafetensorsHeaderNames(t, store.blobs["draft.model.embed_tokens.weight"])+ if !slices.Contains(names, "draft.model.embed_tokens.weight") {+ t.Errorf("in-blob tensor name not prefixed; got %v", names)+ }+}++func TestCreateDraftLayersRejectsEmptyPrefixes(t *testing.T) {+ store := &recordingStore{}+ if _, err := CreateDraftLayers(t.TempDir(), "", "draft/", "", store, func(string) {}); err == nil {+ t.Error("expected an error for an empty tensor prefix")+ }+ if _, err := CreateDraftLayers(t.TempDir(), "draft.", "", "", store, func(string) {}); err == nil {+ t.Error("expected an error for an empty config prefix")+ }+}diff --git a/x/create/gemma4.go b/x/create/gemma4.goindex 2bb493db3..3c79be27c 100644--- a/x/create/gemma4.go+++ b/x/create/gemma4.go@@ -3,14 +3,7 @@ package createimport ("encoding/json""fmt"- "io"- "os"- "path/filepath"- "regexp"- "strconv""strings"-- "github.com/ollama/ollama/x/safetensors")type gemma4ImportTransform struct {@@ -28,14 +21,10 @@ type gemma4Config struct {} `json:"text_config"`}-func newGemma4ImportTransform(modelDir string, _ sourceModelConfig) (tensorImportTransform, error) {- data, err := os.ReadFile(filepath.Join(modelDir, "config.json"))- if err != nil {- return gemma4ImportTransform{}, nil //nolint:nilerr // fallback to no heuristic- }+func newGemma4ImportTransform(rawConfig json.RawMessage) (quantizePolicy, error) {var cfg gemma4Config- if err := json.Unmarshal(data, &cfg); err != nil {- return gemma4ImportTransform{}, nil //nolint:nilerr // fallback to no heuristic+ if err := json.Unmarshal(rawConfig, &cfg); err != nil {+ return nil, fmt.Errorf("gemma4: parse config.json: %w", err)}numLayers := cfg.NumHiddenLayers@@ -50,228 +39,57 @@ func newGemma4ImportTransform(modelDir string, _ sourceModelConfig) (tensorImporreturn gemma4ImportTransform{numLayers: numLayers, numExperts: numExperts}, nil}-func (t gemma4ImportTransform) skipTensor(name string) bool {- return false-}--// layerIndexRe extracts the layer index from tensor names like-// "model.language_model.layers.5.self_attn.v_proj.weight" or-// "model.language_model.layers.5.moe.experts.42.down_proj.weight"-var layerIndexRe = regexp.MustCompile(`\.layers\.(\d+)\.`)--// useMoreBits returns true for layers where quantization-sensitive tensors-// should use higher precision: the first and last 1/8 of layers (which handle-// input grounding and final output refinement), plus every 3rd layer in between-// to limit error accumulation through the residual stream.-func useMoreBits(layerIdx, numLayers int) bool {- return layerIdx < numLayers/8 ||- layerIdx >= 7*numLayers/8 ||- (layerIdx-numLayers/8)%3 == 2-}-func (t gemma4ImportTransform) quantizationType(name string, shape []int32, quantize string) string {- quantNorm := normalizeQuantType(quantize)-- // Embedding: quantize to 8-bit variant for bandwidth efficiency.- // The embedding serves double duty: lookup (via QuantizedEmbedding) and- // lm_head projection (via AsLinear). Using 8-bit matches GGUF Q6_K quality- // (strictly higher at 8 bpw vs 6.5 bpw) while saving ~2.8 GB on 31B vs bf16.- if isEmbedTokensWeight(name) {- switch quantNorm {- case "int4", "int8":- if isAligned(shape, "int8") {- return "int8"- }- case "mxfp4", "nvfp4", "mxfp8":- if isAligned(shape, "mxfp8") {- return "mxfp8"- }+ base := normalizeQuantType(quantize)+ switch {+ case isEmbedTokensWeight(name):+ // The embedding doubles as the lm_head projection; an 8-bit type keeps+ // quality close to bf16 (matching GGUF Q6_K) while saving bandwidth.+ // Fall back to the base type when 8-bit does not fit the vocab shape.+ if e := promoteEmbedding(shape, base); e != "" {+ return e}- if isAligned(shape, quantNorm) {- return quantNorm+ if isAligned(shape, base) {+ return base}return ""+ case t.isSensitiveProjection(name) && eightBit(base) != base:+ return sensitiveType(t.promoteSensitive(name), shape, base)+ default:+ // Routing gates, norms, embeddings, etc. are handled by the generic+ // policy; everything else quantizes at the requested type.+ return GetTensorQuantization(name, shape, quantize)}-- // MoE router logits choose the top-k expert set. Quantization noise here- // can flip expert selection, after which downstream activations diverge- // sharply. The tensor is small, so leave it in source precision.- if isGemma4RouterProjection(name) {- return ""- }-- // Mixed-precision quantization: sensitive tensors get higher precision.- //- // Value projections (v_proj) directly determine attention output quality.- // Down projections (down_proj) are the final MLP output and errors there- // propagate directly to the residual stream. Both benefit from higher- // precision at early layers, late layers, and periodically in between- // (the "useMoreBits" heuristic).- //- // For int4: promote → int8 (same affine family, GatherQMM compatible).- // For mxfp4/nvfp4: promote → mxfp8. MLX quantized_matmul handles mixed- // nvfp4+mxfp8 modes within the same model — each tensor carries its own- // quant metadata and the kernel dispatches per-tensor.- if t.numLayers > 0 {- layerIdx := -1- if m := layerIndexRe.FindStringSubmatch(name); m != nil {- if idx, err := strconv.Atoi(m[1]); err == nil {- layerIdx = idx- }- }-- // Determine promotion target for sensitive tensors.- // "int8" = int4 base → int8 (affine family)- // "mxfp8" = mxfp4/nvfp4 base → mxfp8- // "" = no promotion (int8/mxfp8, already 8-bit)- promote := ""- switch quantNorm {- case "int4":- promote = "int8"- case "mxfp4", "nvfp4":- promote = "mxfp8"- }-- // Only apply to language model tensors — audio/vision tower tensors- // should pass through to GetTensorQuantization which skips them.- isModelTensor := !strings.Contains(name, "audio_tower") &&- !strings.Contains(name, "vision_tower")- isSensitive := isModelTensor &&- (strings.Contains(name, ".v_proj") || strings.Contains(name, "down_proj"))- isSensitiveK := isModelTensor && strings.Contains(name, "k_proj")-- if promote != "" && (isSensitive || isSensitiveK) {- shouldPromote := false-- // 8-expert models: v_proj and k_proj share very few KV heads,- // so quantization errors are amplified. Always promote.- if t.numExperts == 8 && (strings.Contains(name, ".v_proj") || isSensitiveK) {- shouldPromote = true- }-- // Layer-position heuristic for v_proj and down_proj.- if isSensitive && layerIdx >= 0 && useMoreBits(layerIdx, t.numLayers) {- shouldPromote = true- }-- if shouldPromote && isAligned(shape, promote) {- return promote- }-- // Sensitive tensor at a non-promoted layer: use base quant type.- // Return directly to bypass GetTensorQuantization's uniform- // promotion — the layer-position heuristic is authoritative here.- if !isAligned(shape, quantNorm) {- return ""- }- return quantNorm- }- }-- return GetTensorQuantization(name, shape, quantize)}-// isEmbedTokensWeight returns true for the main token embedding weight.-func isEmbedTokensWeight(name string) bool {- return strings.HasSuffix(name, "embed_tokens.weight") &&- !strings.Contains(name, "per_layer")-}--func isGemma4RouterProjection(name string) bool {- return strings.HasSuffix(name, ".router.proj.weight") &&- !strings.Contains(name, "audio_tower") &&- !strings.Contains(name, "vision_tower")-}--func (t gemma4ImportTransform) transformTensor(td *safetensors.TensorData) ([]*safetensors.TensorData, error) {- if td == nil {- return nil, nil- }-- // Split pre-stacked MoE expert tensors [N, out, in] into per-expert- // [out, in] tensors so they go through the standard expert packing and- // quantization flow (ExpertGroupPrefix matching, per-expert quantize).- if isGemma4StackedMoETensor(td.Name, td.Shape) {- return splitStackedMoETensor(td)- }-- return []*safetensors.TensorData{td}, nil-}--// isGemma4StackedMoETensor checks if this is a pre-stacked MoE expert weight.-// Gemma 4 HF weights come in two layouts depending on the model version:-// - Older: model.language_model.layers.N.moe.{gate,up,down}_proj [experts, dim1, dim2]-// - Newer: model.language_model.layers.N.experts.{gate_up,down}_proj [experts, dim1, dim2]-//-// The newer layout has gate+up already fused. We keep it fused (no splitting)-// so the tensors flow through the standard expert packing and quantization path.-func isGemma4StackedMoETensor(name string, shape []int32) bool {- if len(shape) != 3 {+// isSensitiveProjection reports the value/key/down projections whose precision+// most affects quality — attention output (v/k) and the residual stream+// (down). Audio and vision tower tensors are excluded and follow the generic+// policy.+func (t gemma4ImportTransform) isSensitiveProjection(name string) bool {+ if isVisionTower(name) || isAudioTower(name) {return false}- if strings.Contains(name, ".moe.") || strings.Contains(name, ".experts.") {- return strings.HasSuffix(name, "_proj") || strings.HasSuffix(name, "_proj.weight")- }- return false+ return strings.Contains(name, ".v_proj") ||+ strings.Contains(name, ".k_proj") ||+ strings.Contains(name, "down_proj")}-// splitStackedMoETensor splits a [N, out, in] stacked expert tensor into-// N individual [out, in] tensors named with the per-expert convention that-// ExpertGroupPrefix expects: prefix.moe.experts.{E}.{proj}.weight-func splitStackedMoETensor(td *safetensors.TensorData) ([]*safetensors.TensorData, error) {- raw, err := io.ReadAll(td.Reader())- if err != nil {- return nil, fmt.Errorf("failed to read tensor %s: %w", td.Name, err)- }-- numExperts := int(td.Shape[0])- rows := int(td.Shape[1]) // out_features in HF layout- cols := int(td.Shape[2]) // in_features in HF layout-- elemSize, err := DTypeSize(td.Dtype)- if err != nil {- return nil, fmt.Errorf("failed to get dtype size for %s: %w", td.Dtype, err)- }-- perExpertBytes := rows * cols * elemSize- if len(raw) != numExperts*perExpertBytes {- return nil, fmt.Errorf("tensor %s: raw byte length %d does not match shape %v and dtype %s",- td.Name, len(raw), td.Shape, td.Dtype)- }-- // Determine the per-expert name pattern.- // Two source layouts:- // Old: model.language_model.layers.N.moe.gate_proj- // -> model.language_model.layers.N.moe.experts.E.gate_proj.weight- // New: model.language_model.layers.N.experts.gate_up_proj- // -> model.language_model.layers.N.moe.experts.E.gate_up_proj.weight- baseName := td.Name- baseName = strings.TrimSuffix(baseName, ".weight")- lastDot := strings.LastIndex(baseName, ".")- if lastDot < 0 {- return nil, fmt.Errorf("tensor %s: unexpected name format", td.Name)+// promoteSensitive decides whether a sensitive projection uses 8-bit precision.+// 8-expert models share very few KV heads, so their k/v projections are always+// promoted; otherwise v/down projections are promoted at the input and output+// layers and periodically between (useMoreBits), where residual-stream error+// accumulates most.+func (t gemma4ImportTransform) promoteSensitive(name string) bool {+ if t.numLayers == 0 {+ return false}- parentPrefix := baseName[:lastDot] // "...layers.N.moe" or "...layers.N.experts"- projName := baseName[lastDot+1:] // "gate_proj" or "gate_up_proj"-- // Normalize: if parent already ends with ".experts", use the grandparent + ".moe"- // so we get a consistent "layers.N.moe.experts.E" pattern.- var moePrefix string- if cut, ok := strings.CutSuffix(parentPrefix, ".experts"); ok {- moePrefix = cut + ".moe"- } else {- moePrefix = parentPrefix+ if t.numExperts == 8 && (strings.Contains(name, ".v_proj") || strings.Contains(name, ".k_proj")) {+ return true}-- transposedShape := []int32{td.Shape[1], td.Shape[2]}-- results := make([]*safetensors.TensorData, numExperts)- for e := range numExperts {- expertName := fmt.Sprintf("%s.experts.%d.%s.weight", moePrefix, e, projName)- start := e * perExpertBytes- end := start + perExpertBytes- results[e] = safetensors.NewTensorDataFromBytes(expertName, td.Dtype, transposedShape, raw[start:end])+ if strings.Contains(name, ".k_proj") {+ return false // k_proj is promoted only via the 8-expert path}-- return results, nil+ layer := layerIndex(name)+ return layer >= 0 && useMoreBits(layer, t.numLayers)}diff --git a/x/create/gemma4_test.go b/x/create/gemma4_test.goindex de7b53b98..622abb8c5 100644--- a/x/create/gemma4_test.go+++ b/x/create/gemma4_test.go@@ -1,8 +1,7 @@package createimport (- "os"- "path/filepath"+ "encoding/json""testing")@@ -11,27 +10,40 @@ func TestGemma4UnifiedImportTransformRegistration(t *testing.T) {name stringconfigJSON stringcfg sourceModelConfig+ wantErr bool+ wantLayers int}{{name: "unified conditional generation architecture",configJSON: `{"architectures":["Gemma4UnifiedForConditionalGeneration"],"text_config":{"num_hidden_layers":48}}`,cfg: sourceModelConfig{Architectures: []string{"Gemma4UnifiedForConditionalGeneration"}},+ wantLayers: 48,},{name: "unified model type fallback",configJSON: `{"model_type":"gemma4_unified","text_config":{"num_hidden_layers":48}}`,cfg: sourceModelConfig{ModelType: "gemma4_unified"},+ wantLayers: 48,+ },+ {+ name: "malformed config is a hard error",+ configJSON: `{"architectures":["Gemma4UnifiedForConditionalGeneration"],"num_hidden_layers":"oops"}`,+ cfg: sourceModelConfig{Architectures: []string{"Gemma4UnifiedForConditionalGeneration"}},+ wantErr: true,},}for _, tt := range tests {t.Run(tt.name, func(t *testing.T) {- dir := t.TempDir()- if err := os.WriteFile(filepath.Join(dir, "config.json"), []byte(tt.configJSON), 0o644); err != nil {- t.Fatal(err)+ inv := Inventory{Config: tt.cfg, RawConfig: json.RawMessage(tt.configJSON)}++ transform, err := newTensorImportTransform(inv)+ if tt.wantErr {+ if err == nil {+ t.Fatalf("newTensorImportTransform() error = nil, want error")+ }+ return}-- transform, err := newTensorImportTransform(dir, tt.cfg)if err != nil {t.Fatalf("newTensorImportTransform() error = %v", err)}@@ -40,8 +52,8 @@ func TestGemma4UnifiedImportTransformRegistration(t *testing.T) {if !ok {t.Fatalf("newTensorImportTransform() = %T, want gemma4ImportTransform", transform)}- if gemmaTransform.numLayers != 48 {- t.Fatalf("numLayers = %d, want 48", gemmaTransform.numLayers)+ if gemmaTransform.numLayers != tt.wantLayers {+ t.Fatalf("numLayers = %d, want %d", gemmaTransform.numLayers, tt.wantLayers)}})}@@ -151,7 +163,7 @@ func TestGemma4QuantizationType(t *testing.T) {// but not intercepted by gemma4's layer-position heuristic.// Falls through to GetTensorQuantization which applies uniform promotion.{"vision v_proj int4", transform26B, "model.vision_tower.encoder.layers.0.self_attn.v_proj.linear.weight", aligned, "int4", "int8"},- {"vision v_proj nvfp4", transform26B, "model.vision_tower.encoder.layers.0.self_attn.v_proj.linear.weight", aligned, "nvfp4", "nvfp4"},+ {"vision v_proj nvfp4", transform26B, "model.vision_tower.encoder.layers.0.self_attn.v_proj.linear.weight", aligned, "nvfp4", "mxfp8"},// Audio tower down_proj{"audio down_proj int4", transform26B, "model.audio_tower.layers.0.mlp.down_proj.linear.weight", aligned, "int4", ""},{"audio down_proj nvfp4", transform26B, "model.audio_tower.layers.0.mlp.down_proj.linear.weight", aligned, "nvfp4", ""},@@ -205,35 +217,3 @@ func TestUseMoreBits(t *testing.T) {t.Errorf("layer 5 should be promoted (periodic)")}}--func TestIsGemma4StackedMoETensor(t *testing.T) {- tests := []struct {- label string- tensorName string- shape []int32- want bool- }{- // New-style: .experts.gate_up_proj- {"experts gate_up_proj 3D", "model.layers.0.experts.gate_up_proj", []int32{128, 1408, 2816}, true},- {"experts down_proj 3D", "model.layers.0.experts.down_proj", []int32{128, 2816, 704}, true},- // Old-style: .moe.gate_proj- {"moe gate_proj 3D", "model.layers.0.moe.gate_proj", []int32{128, 2112, 2816}, true},- {"moe down_proj 3D", "model.layers.0.moe.down_proj.weight", []int32{128, 2816, 2112}, true},- // Not stacked: 2D- {"2D weight", "model.layers.0.experts.gate_up_proj", []int32{1408, 2816}, false},- // Not expert- {"non-expert 3D", "model.layers.0.mlp.gate_proj", []int32{3, 2816, 2816}, false},- // Not a projection- {"expert non-proj", "model.layers.0.experts.scale", []int32{128, 1, 1}, false},- }-- for _, tt := range tests {- t.Run(tt.label, func(t *testing.T) {- got := isGemma4StackedMoETensor(tt.tensorName, tt.shape)- if got != tt.want {- t.Errorf("isGemma4StackedMoETensor(%q, %v) = %v, want %v",- tt.tensorName, tt.shape, got, tt.want)- }- })- }-}diff --git a/x/create/imagegen.go b/x/create/imagegen.godeleted file mode 100644index 09c832137..000000000--- a/x/create/imagegen.go+++ /dev/null@@ -1,230 +0,0 @@-package create--import (- "bytes"- "encoding/json"- "fmt"- "io"- "os"- "path/filepath"- "strings"-- "github.com/ollama/ollama/x/safetensors"-)--// CreateImageGenModel imports an image generation model from a directory.-// Stores each tensor as a separate blob for fine-grained deduplication.-// If quantize is specified, linear weights in transformer/text_encoder are quantized.-// Supported quantization types: int4, int8, nvfp4, mxfp8 (or empty for no quantization).-// Layer creation and manifest writing are done via callbacks to avoid import cycles.-func CreateImageGenModel(modelName, modelDir, quantize string, createLayer LayerCreator, createTensorLayer QuantizingTensorLayerCreator, writeManifest ManifestWriter, fn func(status string)) error {- // Validate quantization type- switch quantize {- case "", "int4", "int8", "nvfp4", "mxfp8":- // valid- default:- return fmt.Errorf("unsupported quantization type %q: supported types are int4, int8, nvfp4, mxfp8", quantize)- }-- var layers []LayerInfo- var configLayer LayerInfo- var totalParams int64 // Count parameters from original tensor shapes- var torchDtype string // Read from component config for quantization display-- // Components to process - extract individual tensors from each- components := []string{"text_encoder", "transformer", "vae"}-- for _, component := range components {- componentDir := filepath.Join(modelDir, component)- if _, err := os.Stat(componentDir); os.IsNotExist(err) {- continue- }-- // Find all safetensors files in this component- entries, err := os.ReadDir(componentDir)- if err != nil {- return fmt.Errorf("failed to read %s: %w", component, err)- }-- for _, entry := range entries {- if !strings.HasSuffix(entry.Name(), ".safetensors") {- continue- }-- stPath := filepath.Join(componentDir, entry.Name())-- // Extract individual tensors from safetensors file- extractor, err := safetensors.OpenForExtraction(stPath)- if err != nil {- return fmt.Errorf("failed to open %s: %w", stPath, err)- }-- tensorNames := extractor.ListTensors()- quantizeMsg := ""- if quantize != "" && component != "vae" {- quantizeMsg = ", quantizing to " + quantize- }- fn(fmt.Sprintf("importing %s/%s (%d tensors%s)", component, entry.Name(), len(tensorNames), quantizeMsg))-- for _, tensorName := range tensorNames {- td, err := extractor.GetTensor(tensorName)- if err != nil {- extractor.Close()- return fmt.Errorf("failed to get tensor %s: %w", tensorName, err)- }-- // Count parameters from original tensor shape- if len(td.Shape) > 0 {- numElements := int64(1)- for _, dim := range td.Shape {- numElements *= int64(dim)- }- totalParams += numElements- }-- // Store as minimal safetensors format (88 bytes header overhead)- // This enables native mmap loading via mlx_load_safetensors- // Use path-style name: "component/tensor_name"- fullName := component + "/" + tensorName-- // Determine quantization type for this tensor (empty string if not quantizing)- quantizeType := ""- if quantize != "" && ShouldQuantize(tensorName, component) && canQuantizeShape(td.Shape, quantize) {- quantizeType = quantize- }-- // createTensorLayer returns multiple layers if quantizing (weight + scales)- newLayers, err := createTensorLayer(td.SafetensorsReader(), fullName, td.Dtype, td.Shape, quantizeType)- if err != nil {- extractor.Close()- return fmt.Errorf("failed to create layer for %s: %w", fullName, err)- }- layers = append(layers, newLayers...)- }-- extractor.Close()- }- }-- // Read torch_dtype from text_encoder config for quantization display- if torchDtype == "" {- textEncoderConfig := filepath.Join(modelDir, "text_encoder/config.json")- if data, err := os.ReadFile(textEncoderConfig); err == nil {- var cfg struct {- TorchDtype string `json:"torch_dtype"`- }- if json.Unmarshal(data, &cfg) == nil && cfg.TorchDtype != "" {- torchDtype = cfg.TorchDtype- }- }- }-- // Import config files- configFiles := []string{- "model_index.json",- "text_encoder/config.json",- "text_encoder/generation_config.json",- "transformer/config.json",- "vae/config.json",- "scheduler/scheduler_config.json",- "tokenizer/tokenizer.json",- "tokenizer/tokenizer_config.json",- "tokenizer/vocab.json",- }-- for _, cfgPath := range configFiles {- fullPath := filepath.Join(modelDir, cfgPath)- if _, err := os.Stat(fullPath); os.IsNotExist(err) {- continue- }-- fn(fmt.Sprintf("importing config %s", cfgPath))-- var r io.Reader-- // For model_index.json, normalize to Ollama format and add metadata- if cfgPath == "model_index.json" {- data, err := os.ReadFile(fullPath)- if err != nil {- return fmt.Errorf("failed to read %s: %w", cfgPath, err)- }-- var cfg map[string]any- if err := json.Unmarshal(data, &cfg); err != nil {- return fmt.Errorf("failed to parse %s: %w", cfgPath, err)- }-- // Rename _class_name to architecture, remove diffusers-specific fields- if className, ok := cfg["_class_name"]; ok {- cfg["architecture"] = className- delete(cfg, "_class_name")- }- delete(cfg, "_diffusers_version")-- // Add parameter count (counted from tensor shapes during import)- cfg["parameter_count"] = totalParams-- // Add quantization info - use quantize type if set, otherwise torch_dtype- if quantize != "" {- cfg["quantization"] = strings.ToUpper(quantize)- } else {- cfg["quantization"] = torchDtype- }-- data, err = json.MarshalIndent(cfg, "", " ")- if err != nil {- return fmt.Errorf("failed to marshal %s: %w", cfgPath, err)- }- r = bytes.NewReader(data)- } else {- f, err := os.Open(fullPath)- if err != nil {- return fmt.Errorf("failed to open %s: %w", cfgPath, err)- }- defer f.Close()- r = f- }-- layer, err := createLayer(r, "application/vnd.ollama.image.json", cfgPath)- if err != nil {- return fmt.Errorf("failed to create layer for %s: %w", cfgPath, err)- }-- // Use model_index.json as the config layer- if cfgPath == "model_index.json" {- configLayer = layer- }-- layers = append(layers, layer)- }-- if configLayer.Digest == "" {- return fmt.Errorf("model_index.json not found in %s", modelDir)- }-- fn(fmt.Sprintf("writing manifest for %s", modelName))-- if err := writeManifest(modelName, configLayer, layers); err != nil {- return fmt.Errorf("failed to write manifest: %w", err)- }-- fn(fmt.Sprintf("successfully imported %s with %d layers", modelName, len(layers)))- return nil-}--// canQuantizeShape returns true if a tensor shape is compatible with MLX quantization.-// MLX requires the last dimension to be divisible by the group size.-// nvfp4: 16, int4/mxfp8: 32, int8: 64-func canQuantizeShape(shape []int32, quantize string) bool {- if len(shape) < 2 {- return false- }- groupSize := int32(32)- switch strings.ToUpper(quantize) {- case "NVFP4":- groupSize = 16- case "INT8":- groupSize = 64- }- return shape[len(shape)-1]%groupSize == 0-}diff --git a/x/create/inventory.go b/x/create/inventory.gonew file mode 100644index 000000000..6a3995dc7--- /dev/null+++ b/x/create/inventory.go@@ -0,0 +1,124 @@+package create++import (+ "encoding/json"+ "fmt"+ "os"+ "path/filepath"+ "strings"++ "github.com/ollama/ollama/x/safetensors"+)++// SourceTensor describes one tensor found in a source model: its on-disk type+// and shape and which safetensors file holds it. It carries no weight data —+// only what the header and shard index reveal.+type SourceTensor struct {+ Name string+ Dtype string+ Shape []int32+ File string // safetensors file basename, relative to the model directory+}++// Inventory is the immutable result of reading a source model: every tensor+// indexed by name, plus the parsed config and the model directory. Reading+// source headers happens only here; the classify, plan, and write steps work+// entirely from this listing and never re-open a source header to make a+// decision. RawConfig holds the config.json bytes so architecture-specific+// factories can parse their own fields without re-opening the file.+type Inventory struct {+ Dir string+ Config sourceModelConfig+ RawConfig json.RawMessage+ Tensors map[string]SourceTensor+}++// Has reports whether a tensor with the given name exists in the source.+func (inv Inventory) Has(name string) bool {+ _, ok := inv.Tensors[name]+ return ok+}++// ReadInventory reads a source model directory into an Inventory: the config,+// the shard index, and every tensor's header. It reads no weight data. If the+// shard index references a tensor that cannot be found (a missing or truncated+// shard, e.g. a partial download), it fails rather than silently producing an+// incomplete model.+func ReadInventory(dir string) (Inventory, error) {+ cfg, rawConfig, err := readSourceModelConfig(dir)+ if err != nil {+ return Inventory{}, fmt.Errorf("read config: %w", err)+ }++ index, err := readSourceTensorFiles(dir)+ if err != nil {+ return Inventory{}, fmt.Errorf("read tensor index: %w", err)+ }++ entries, err := os.ReadDir(dir)+ if err != nil {+ return Inventory{}, err+ }++ // Only the standard HF weights - a monolithic model.safetensors or the+ // sharded model-*.safetensors set - are imported. Other safetensors in the+ // same repo - notably Mistral's consolidated-*.safetensors - use a layout+ // we don't support, and are skipped so they can't shadow or pollute the+ // model tensors.+ var monolithic bool+ var files []string+ for _, entry := range entries {+ if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".safetensors") || !strings.HasPrefix(entry.Name(), "model") {+ continue+ }+ if entry.Name() == "model.safetensors" {+ monolithic = true+ }+ files = append(files, entry.Name())+ }+ if monolithic && len(files) > 1 {+ return Inventory{}, fmt.Errorf("found both model.safetensors and sharded model-*.safetensors weights in %s: ambiguous source", dir)+ }++ tensors := make(map[string]SourceTensor)+ for _, file := range files {+ ext, err := safetensors.OpenForExtraction(filepath.Join(dir, file))+ if err != nil {+ return Inventory{}, fmt.Errorf("open %s: %w", file, err)+ }+ for _, name := range ext.ListTensors() {+ td, err := ext.GetTensor(name)+ if err != nil {+ ext.Close()+ return Inventory{}, fmt.Errorf("read tensor %s from %s: %w", name, file, err)+ }+ if prev, ok := tensors[name]; ok {+ ext.Close()+ return Inventory{}, fmt.Errorf("duplicate tensor %s: found in both %s and %s", name, prev.File, file)+ }+ tensors[name] = SourceTensor{+ Name: name,+ Dtype: td.Dtype,+ Shape: td.Shape,+ File: file,+ }+ }+ ext.Close()+ }++ // Completeness: every tensor named in the shard index must actually be+ // present. A missing shard (or an index entry whose shard lacks the+ // tensor) means missing weights, which must fail loudly here rather than+ // silently importing an incomplete model.+ for name, file := range index {+ if _, ok := tensors[name]; !ok {+ return Inventory{}, fmt.Errorf("source model is incomplete: tensor %s (indexed in %q) was not found", name, file)+ }+ }++ if len(tensors) == 0 {+ return Inventory{}, fmt.Errorf("no model.safetensors or model-*.safetensors weights found in %s", dir)+ }++ return Inventory{Dir: dir, Config: cfg, RawConfig: rawConfig, Tensors: tensors}, nil+}diff --git a/x/create/inventory_test.go b/x/create/inventory_test.gonew file mode 100644index 000000000..cad766ae4--- /dev/null+++ b/x/create/inventory_test.go@@ -0,0 +1,134 @@+package create++import (+ "os"+ "path/filepath"+ "slices"+ "strings"+ "testing"++ st "github.com/ollama/ollama/x/safetensors"+)++func writeConfigJSON(t *testing.T, dir, content string) {+ t.Helper()+ if err := os.WriteFile(filepath.Join(dir, "config.json"), []byte(content), 0o644); err != nil {+ t.Fatal(err)+ }+}++func TestReadInventory(t *testing.T) {+ dir := t.TempDir()+ writeConfigJSON(t, dir, `{"architectures":["TestModel"]}`)+ createTestSafetensors(t, filepath.Join(dir, "model.safetensors"), []*st.TensorData{+ st.NewTensorDataFromBytes("model.embed.weight", "BF16", []int32{4, 8}, make([]byte, 4*8*2)),+ st.NewTensorDataFromBytes("model.layers.0.weight", "BF16", []int32{8, 8}, make([]byte, 8*8*2)),+ })++ inv, err := ReadInventory(dir)+ if err != nil {+ t.Fatalf("ReadInventory() error = %v", err)+ }+ if len(inv.Tensors) != 2 {+ t.Fatalf("got %d tensors, want 2", len(inv.Tensors))+ }+ embed, ok := inv.Tensors["model.embed.weight"]+ if !ok {+ t.Fatal("missing model.embed.weight")+ }+ if embed.Dtype != "BF16" || !slices.Equal(embed.Shape, []int32{4, 8}) || embed.File != "model.safetensors" {+ t.Errorf("embed tensor = %+v", embed)+ }+ if !inv.Has("model.layers.0.weight") {+ t.Error("Has(model.layers.0.weight) = false, want true")+ }+}++func TestReadInventoryIncomplete(t *testing.T) {+ dir := t.TempDir()+ writeConfigJSON(t, dir, `{"architectures":["TestModel"]}`)+ createTestSafetensors(t, filepath.Join(dir, "model-00001-of-00002.safetensors"), []*st.TensorData{+ st.NewTensorDataFromBytes("model.a.weight", "BF16", []int32{4, 4}, make([]byte, 4*4*2)),+ })+ // The index references a second shard that is not present on disk.+ index := `{"weight_map":{"model.a.weight":"model-00001-of-00002.safetensors","model.b.weight":"model-00002-of-00002.safetensors"}}`+ if err := os.WriteFile(filepath.Join(dir, "model.safetensors.index.json"), []byte(index), 0o644); err != nil {+ t.Fatal(err)+ }++ _, err := ReadInventory(dir)+ if err == nil || !strings.Contains(err.Error(), "incomplete") {+ t.Fatalf("ReadInventory() error = %v, want substring %q", err, "incomplete")+ }+}++func TestReadInventorySkipsConsolidated(t *testing.T) {+ dir := t.TempDir()+ writeConfigJSON(t, dir, `{"architectures":["TestModel"]}`)+ // Standard HF weights — imported.+ createTestSafetensors(t, filepath.Join(dir, "model.safetensors"), []*st.TensorData{+ st.NewTensorDataFromBytes("model.layers.0.weight", "BF16", []int32{8, 8}, make([]byte, 8*8*2)),+ })+ // Mistral consolidated weights shipped in the same repo — must be ignored so+ // they can't shadow or pollute the model tensors.+ createTestSafetensors(t, filepath.Join(dir, "consolidated-00001-of-00001.safetensors"), []*st.TensorData{+ st.NewTensorDataFromBytes("layers.0.attention.wq.weight", "BF16", []int32{8, 8}, make([]byte, 8*8*2)),+ })++ inv, err := ReadInventory(dir)+ if err != nil {+ t.Fatalf("ReadInventory() error = %v", err)+ }+ if len(inv.Tensors) != 1 || !inv.Has("model.layers.0.weight") {+ t.Errorf("tensors = %v, want only model.layers.0.weight", inv.Tensors)+ }+ if inv.Has("layers.0.attention.wq.weight") {+ t.Error("consolidated tensor was imported; consolidated-*.safetensors must be skipped")+ }+}++func TestReadInventoryRejectsMonolithicPlusShards(t *testing.T) {+ dir := t.TempDir()+ writeConfigJSON(t, dir, `{"architectures":["TestModel"]}`)+ createTestSafetensors(t, filepath.Join(dir, "model.safetensors"), []*st.TensorData{+ st.NewTensorDataFromBytes("model.a.weight", "BF16", []int32{4, 4}, make([]byte, 4*4*2)),+ })+ createTestSafetensors(t, filepath.Join(dir, "model-00001-of-00001.safetensors"), []*st.TensorData{+ st.NewTensorDataFromBytes("model.a.weight", "BF16", []int32{4, 4}, make([]byte, 4*4*2)),+ })++ _, err := ReadInventory(dir)+ if err == nil || !strings.Contains(err.Error(), "ambiguous") {+ t.Fatalf("ReadInventory() error = %v, want an 'ambiguous source' error", err)+ }+}++func TestReadInventoryRejectsDuplicateTensorAcrossShards(t *testing.T) {+ dir := t.TempDir()+ writeConfigJSON(t, dir, `{"architectures":["TestModel"]}`)+ createTestSafetensors(t, filepath.Join(dir, "model-00001-of-00002.safetensors"), []*st.TensorData{+ st.NewTensorDataFromBytes("model.a.weight", "BF16", []int32{4, 4}, make([]byte, 4*4*2)),+ })+ createTestSafetensors(t, filepath.Join(dir, "model-00002-of-00002.safetensors"), []*st.TensorData{+ st.NewTensorDataFromBytes("model.a.weight", "BF16", []int32{4, 4}, make([]byte, 4*4*2)),+ })++ _, err := ReadInventory(dir)+ if err == nil || !strings.Contains(err.Error(), "duplicate tensor") {+ t.Fatalf("ReadInventory() error = %v, want a 'duplicate tensor' error", err)+ }+}++func TestReadInventoryNoModelWeights(t *testing.T) {+ dir := t.TempDir()+ writeConfigJSON(t, dir, `{"architectures":["TestModel"]}`)+ // Only consolidated weights present — nothing importable.+ createTestSafetensors(t, filepath.Join(dir, "consolidated.safetensors"), []*st.TensorData{+ st.NewTensorDataFromBytes("layers.0.attention.wq.weight", "BF16", []int32{8, 8}, make([]byte, 8*8*2)),+ })++ _, err := ReadInventory(dir)+ if err == nil || !strings.Contains(err.Error(), "no model") {+ t.Fatalf("ReadInventory() error = %v, want a 'no model ... weights' error", err)+ }+}diff --git a/x/create/laguna.go b/x/create/laguna.goindex 8355c9dba..0e5b4de61 100644--- a/x/create/laguna.go+++ b/x/create/laguna.go@@ -1,26 +1,16 @@package createimport (+ "encoding/json""strings"-- "github.com/ollama/ollama/x/safetensors")type lagunaImportTransform struct{}-func newLagunaImportTransform(string, sourceModelConfig) (tensorImportTransform, error) {+func newLagunaImportTransform(json.RawMessage) (quantizePolicy, error) {return lagunaImportTransform{}, nil}-func (lagunaImportTransform) skipTensor(string) bool { return false }--func (lagunaImportTransform) transformTensor(td *safetensors.TensorData) ([]*safetensors.TensorData, error) {- if td == nil {- return nil, nil- }- return []*safetensors.TensorData{td}, nil-}-func (lagunaImportTransform) quantizationType(name string, shape []int32, quantize string) string {if !lagunaIsHFRoutedExpertWeight(name) {return ""@@ -28,32 +18,6 @@ func (lagunaImportTransform) quantizationType(name string, shape []int32, quantireturn GetTensorQuantization(name, shape, quantize)}-func (lagunaImportTransform) sourceFP8TensorQuantization(name string, shape []int32, requested string, fallback string) string {- if !lagunaIsHFRoutedExpertWeight(name) {- return ""- }-- switch normalizeQuantType(requested) {- case "nvfp4", "mxfp4":- if lagunaKeepSourceFP8TensorAtMXFP8(name, shape) {- return "mxfp8"- }- }- return fallback-}--func (lagunaImportTransform) sourceFP8BF16Quantization(string, []int32, string) string {- return ""-}--func lagunaKeepSourceFP8TensorAtMXFP8(name string, shape []int32) bool {- if len(shape) != 2 || !isAligned(shape, "mxfp8") {- return false- }-- return strings.Contains(name, "down_proj")-}-func lagunaIsHFRoutedExpertWeight(name string) bool {return strings.HasSuffix(name, ".weight") && strings.Contains(name, ".mlp.experts.")}diff --git a/x/create/laguna_test.go b/x/create/laguna_test.godeleted file mode 100644index 7e122366e..000000000--- a/x/create/laguna_test.go+++ /dev/null@@ -1,200 +0,0 @@-package create--import (- "io"- "os"- "path/filepath"- "testing"-- st "github.com/ollama/ollama/x/safetensors"-)--func TestCreateSafetensorsModel_LagunaHFFP8RespectsSourceTensorPrecision(t *testing.T) {- tests := []struct {- name string- requested string- wantFP8Gate string- wantFP8Up string- wantFP8Down string- wantBF16QProj string- }{- {- name: "default mxfp8 import keeps source bf16 tensors",- requested: "",- wantFP8Gate: "mxfp8",- wantFP8Up: "mxfp8",- wantFP8Down: "mxfp8",- wantBF16QProj: "",- },- {- name: "nvfp4 import keeps source bf16 tensors and preserves down_proj at mxfp8",- requested: "nvfp4",- wantFP8Gate: "nvfp4",- wantFP8Up: "nvfp4",- wantFP8Down: "mxfp8",- wantBF16QProj: "",- },- }-- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- dir := t.TempDir()- configJSON := `{- "model_type": "laguna",- "architectures": ["LagunaForCausalLM"],- "quantization_config": {"quant_method": "fp8", "weight_block_size": [128, 128]}- }`- if err := os.WriteFile(filepath.Join(dir, "config.json"), []byte(configJSON), 0o644); err != nil {- t.Fatalf("failed to write config.json: %v", err)- }-- createTestSafetensors(t, filepath.Join(dir, "model.safetensors"), []*st.TensorData{- st.NewTensorDataFromBytes("model.layers.0.mlp.experts.0.gate_proj.weight", "F8_E4M3", []int32{128, 128}, make([]byte, 128*128)),- st.NewTensorDataFromBytes("model.layers.0.mlp.experts.0.gate_proj.weight_scale_inv", "BF16", []int32{1, 1}, make([]byte, 2)),- st.NewTensorDataFromBytes("model.layers.0.mlp.experts.0.up_proj.weight", "F8_E4M3", []int32{128, 128}, make([]byte, 128*128)),- st.NewTensorDataFromBytes("model.layers.0.mlp.experts.0.up_proj.weight_scale_inv", "BF16", []int32{1, 1}, make([]byte, 2)),- st.NewTensorDataFromBytes("model.layers.0.mlp.experts.0.down_proj.weight", "F8_E4M3", []int32{128, 128}, make([]byte, 128*128)),- st.NewTensorDataFromBytes("model.layers.0.mlp.experts.0.down_proj.weight_scale_inv", "BF16", []int32{1, 1}, make([]byte, 2)),- st.NewTensorDataFromBytes("model.layers.0.self_attn.q_proj.weight", "BF16", []int32{128, 128}, make([]byte, 128*128*2)),- st.NewTensorDataFromBytes("model.embed_tokens.weight", "BF16", []int32{128, 128}, make([]byte, 128*128*2)),- st.NewTensorDataFromBytes("lm_head.weight", "BF16", []int32{128, 128}, make([]byte, 128*128*2)),- st.NewTensorDataFromBytes("model.layers.0.mlp.gate.weight", "BF16", []int32{128, 128}, make([]byte, 128*128*2)),- })-- quantizeByName := make(map[string]string)-- createLayer := func(r io.Reader, mediaType, name string) (LayerInfo, error) {- if _, err := io.ReadAll(r); err != nil {- return LayerInfo{}, err- }- return LayerInfo{Name: name, Digest: "sha256:" + name, MediaType: mediaType}, nil- }- createTensorLayer := func(r io.Reader, name, dtype string, shape []int32, quantize string) ([]LayerInfo, error) {- if _, err := io.ReadAll(r); err != nil {- return nil, err- }- quantizeByName[name] = quantize- return []LayerInfo{{Name: name, Digest: "sha256:tensor_" + name, MediaType: "application/vnd.ollama.image.tensor"}}, nil- }- writeManifest := func(modelName string, config LayerInfo, layers []LayerInfo) error { return nil }-- if err := CreateSafetensorsModel("test-model", dir, tt.requested, createLayer, createTensorLayer, writeManifest, func(string) {}); err != nil {- t.Fatalf("CreateSafetensorsModel failed: %v", err)- }-- if got := quantizeByName["model.layers.0.mlp.experts.0.gate_proj.weight"]; got != tt.wantFP8Gate {- t.Fatalf("gate_proj quantization = %q, want %q", got, tt.wantFP8Gate)- }- if got := quantizeByName["model.layers.0.mlp.experts.0.up_proj.weight"]; got != tt.wantFP8Up {- t.Fatalf("up_proj quantization = %q, want %q", got, tt.wantFP8Up)- }- if got := quantizeByName["model.layers.0.mlp.experts.0.down_proj.weight"]; got != tt.wantFP8Down {- t.Fatalf("down_proj quantization = %q, want %q", got, tt.wantFP8Down)- }- for _, name := range []string{- "model.layers.0.self_attn.q_proj.weight",- "model.embed_tokens.weight",- "lm_head.weight",- "model.layers.0.mlp.gate.weight",- } {- if got := quantizeByName[name]; got != tt.wantBF16QProj {- t.Fatalf("%s quantization = %q, want %q", name, got, tt.wantBF16QProj)- }- }- })- }-}--func TestCreateSafetensorsModel_LagunaBF16QuantizesOnlyRoutedExperts(t *testing.T) {- tests := []struct {- name string- requested string- want map[string]string- }{- {- name: "int8 quantizes only routed experts",- requested: "int8",- want: map[string]string{- "model.layers.0.mlp.experts.0.gate_proj.weight": "int8",- "model.layers.0.mlp.experts.0.up_proj.weight": "int8",- "model.layers.0.mlp.experts.0.down_proj.weight": "int8",- "model.layers.0.mlp.shared_experts.gate_proj.weight": "",- "model.layers.0.mlp.shared_experts.down_proj.weight": "",- "model.layers.0.self_attn.q_proj.weight": "",- "model.layers.0.mlp.down_proj.weight": "",- "model.embed_tokens.weight": "",- "lm_head.weight": "",- "model.layers.0.mlp.gate.weight": "",- },- },- {- name: "int4 keeps routed down_proj at int8 and leaves others bf16",- requested: "int4",- want: map[string]string{- "model.layers.0.mlp.experts.0.gate_proj.weight": "int4",- "model.layers.0.mlp.experts.0.up_proj.weight": "int4",- "model.layers.0.mlp.experts.0.down_proj.weight": "int8",- "model.layers.0.mlp.shared_experts.gate_proj.weight": "",- "model.layers.0.mlp.shared_experts.down_proj.weight": "",- "model.layers.0.self_attn.q_proj.weight": "",- "model.layers.0.mlp.down_proj.weight": "",- "model.embed_tokens.weight": "",- "lm_head.weight": "",- "model.layers.0.mlp.gate.weight": "",- },- },- }-- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- dir := t.TempDir()- configJSON := `{- "model_type": "laguna",- "architectures": ["LagunaForCausalLM"]- }`- if err := os.WriteFile(filepath.Join(dir, "config.json"), []byte(configJSON), 0o644); err != nil {- t.Fatalf("failed to write config.json: %v", err)- }-- createTestSafetensors(t, filepath.Join(dir, "model.safetensors"), []*st.TensorData{- st.NewTensorDataFromBytes("model.layers.0.mlp.experts.0.gate_proj.weight", "BF16", []int32{128, 128}, make([]byte, 128*128*2)),- st.NewTensorDataFromBytes("model.layers.0.mlp.experts.0.up_proj.weight", "BF16", []int32{128, 128}, make([]byte, 128*128*2)),- st.NewTensorDataFromBytes("model.layers.0.mlp.experts.0.down_proj.weight", "BF16", []int32{128, 128}, make([]byte, 128*128*2)),- st.NewTensorDataFromBytes("model.layers.0.mlp.shared_experts.gate_proj.weight", "BF16", []int32{128, 128}, make([]byte, 128*128*2)),- st.NewTensorDataFromBytes("model.layers.0.mlp.shared_experts.down_proj.weight", "BF16", []int32{128, 128}, make([]byte, 128*128*2)),- st.NewTensorDataFromBytes("model.layers.0.self_attn.q_proj.weight", "BF16", []int32{128, 128}, make([]byte, 128*128*2)),- st.NewTensorDataFromBytes("model.layers.0.mlp.down_proj.weight", "BF16", []int32{128, 128}, make([]byte, 128*128*2)),- st.NewTensorDataFromBytes("model.embed_tokens.weight", "BF16", []int32{128, 128}, make([]byte, 128*128*2)),- st.NewTensorDataFromBytes("lm_head.weight", "BF16", []int32{128, 128}, make([]byte, 128*128*2)),- st.NewTensorDataFromBytes("model.layers.0.mlp.gate.weight", "BF16", []int32{128, 128}, make([]byte, 128*128*2)),- })-- quantizeByName := make(map[string]string)-- createLayer := func(r io.Reader, mediaType, name string) (LayerInfo, error) {- if _, err := io.ReadAll(r); err != nil {- return LayerInfo{}, err- }- return LayerInfo{Name: name, Digest: "sha256:" + name, MediaType: mediaType}, nil- }- createTensorLayer := func(r io.Reader, name, dtype string, shape []int32, quantize string) ([]LayerInfo, error) {- if _, err := io.ReadAll(r); err != nil {- return nil, err- }- quantizeByName[name] = quantize- return []LayerInfo{{Name: name, Digest: "sha256:tensor_" + name, MediaType: "application/vnd.ollama.image.tensor"}}, nil- }- writeManifest := func(modelName string, config LayerInfo, layers []LayerInfo) error { return nil }-- if err := CreateSafetensorsModel("test-model", dir, tt.requested, createLayer, createTensorLayer, writeManifest, func(string) {}); err != nil {- t.Fatalf("CreateSafetensorsModel failed: %v", err)- }-- for name, want := range tt.want {- if got := quantizeByName[name]; got != want {- t.Fatalf("%s quantization = %q, want %q", name, got, want)- }- }- })- }-}diff --git a/x/create/mlxthread.go b/x/create/mlxthread.gonew file mode 100644index 000000000..590a15dfb--- /dev/null+++ b/x/create/mlxthread.go@@ -0,0 +1,72 @@+package create++import (+ "fmt"+ "runtime"+ "sync"+ "sync/atomic"++ "github.com/ollama/ollama/x/mlxrunner/mlx"+)++var (+ mlxThreadOnce sync.Once+ mlxThreadStarted atomic.Bool+ mlxWork chan func()+ mlxInitErr error+)++// runOnMLXThread runs f on the MLX thread and returns its error. The thread is+// started (and MLX initialized) on first use. A panic in f is recovered and+// returned as an error so a kernel failure cannot kill the pinned thread.+//+// TODO(pdevine): This method should be revisited when the `ollama create` is+// instead run on the ollama server process instead of the client.+func runOnMLXThread(f func() error) error {+ mlxThreadOnce.Do(func() {+ mlxWork = make(chan func())+ ready := make(chan error)+ go func() {+ runtime.LockOSThread() // pinned for the process lifetime; never unlocked+ err := mlx.CheckInit()+ if err == nil && mlx.GPUIsAvailable() {+ mlx.SetDefaultDeviceGPU()+ }+ ready <- err+ if err != nil {+ return+ }+ for work := range mlxWork {+ work()+ }+ }()+ mlxInitErr = <-ready+ mlxThreadStarted.Store(mlxInitErr == nil)+ })+ if mlxInitErr != nil {+ return fmt.Errorf("MLX init failed: %w", mlxInitErr)+ }++ done := make(chan error, 1)+ mlxWork <- func() {+ defer func() {+ if r := recover(); r != nil {+ done <- fmt.Errorf("mlx: %v", r)+ }+ }()+ done <- f()+ }+ return <-done+}++// sweepMLX releases the MLX buffer cache. It is a no-op if no MLX work has run.+func sweepMLX() {+ if !mlxThreadStarted.Load() {+ return+ }+ _ = runOnMLXThread(func() error {+ mlx.ClearCache()+ mlx.Sweep()+ return nil+ })+}diff --git a/x/create/pipeline.go b/x/create/pipeline.gonew file mode 100644index 000000000..6794382ad--- /dev/null+++ b/x/create/pipeline.go@@ -0,0 +1,121 @@+package create++import (+ "fmt"+ "io"+ "os"+ "path/filepath"+ "strings"+)++// Create imports a safetensors model through the full pipeline: read the+// source into an inventory, classify it, plan the output blobs, write them+// through store, import the config files, and write the manifest. It is the+// server-side entry point — the caller supplies blob storage (store) and+// manifest assembly (writeManifest).+func Create(modelName, modelDir, quantize string, store BlobStore, writeManifest ManifestWriter, fn func(status string)) error {+ defer sweepMLX()++ inv, err := ReadInventory(modelDir)+ if err != nil {+ return fmt.Errorf("read model: %w", err)+ }+ class, err := Classify(inv, quantize)+ if err != nil {+ return err+ }+ policy, err := newTensorImportTransform(inv)+ if err != nil {+ return fmt.Errorf("build quantization policy for %q: %w", inv.Config.Architecture(), err)+ }+ specs, err := Plan(inv, class, policy)+ if err != nil {+ return fmt.Errorf("plan model: %w", err)+ }++ fn(fmt.Sprintf("importing %s (%d tensors%s)", modelName, len(inv.Tensors), quantizeStatus(class)))+ layers, err := WriteBlobs(specs, modelDir, store)+ if err != nil {+ return err+ }++ // Import config files (config.json, tokenizer, etc.) as JSON blobs.+ configLayers, configLayer, err := importConfigBlobs(modelDir, "", store, fn)+ if err != nil {+ return err+ }+ layers = append(layers, configLayers...)+ if configLayer.Digest == "" {+ return fmt.Errorf("config.json not found in %s", modelDir)+ }++ fn(fmt.Sprintf("writing manifest for %s", modelName))+ if err := writeManifest(modelName, configLayer, layers); err != nil {+ return fmt.Errorf("write manifest: %w", err)+ }+ fn(fmt.Sprintf("successfully imported %s with %d layers", modelName, len(layers)))+ return nil+}++const mediaTypeImageJSON = "application/vnd.ollama.image.json"++// importConfigBlobs writes every .json in modelDir (except the shard index) as an+// image.json blob, prefixing each blob name with namePrefix, and returns the+// resulting layers along with the config.json layer (zero value if absent). The+// target import passes "" for namePrefix; a draft import passes "draft/" so its+// config sits beside the target's.+func importConfigBlobs(modelDir, namePrefix string, store BlobStore, fn func(status string)) ([]LayerInfo, LayerInfo, error) {+ entries, err := os.ReadDir(modelDir)+ if err != nil {+ return nil, LayerInfo{}, err+ }+ var layers []LayerInfo+ var configLayer LayerInfo+ for _, entry := range entries {+ if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".json") || entry.Name() == "model.safetensors.index.json" {+ continue+ }+ name := entry.Name()+ fn(fmt.Sprintf("importing config %s", name))+ f, err := os.Open(filepath.Join(modelDir, name))+ if err != nil {+ return nil, LayerInfo{}, fmt.Errorf("open %s: %w", name, err)+ }+ layer, err := store.WriteBlob(f, mediaTypeImageJSON, namePrefix+name)+ f.Close()+ if err != nil {+ return nil, LayerInfo{}, fmt.Errorf("write config %s: %w", name, err)+ }+ if name == "config.json" {+ configLayer = layer+ }+ layers = append(layers, layer)+ }+ return layers, configLayer, nil+}++func quantizeStatus(c Classification) string {+ switch c.Kind {+ case SourceBlockFP8:+ return ", converting fp8 to mxfp8"+ case SourcePrequantized:+ return ", preserving source quantization"+ default:+ if c.Quantize != "" {+ return ", quantizing to " + c.Quantize+ }+ return ""+ }+}++// StoreFromLayerCreator adapts a LayerCreator-style function to a BlobStore, so+// a caller that already has a blob-writing callback can drive the pipeline.+func StoreFromLayerCreator(fn LayerCreator) BlobStore {+ return layerCreatorStore{fn}+}++type layerCreatorStore struct{ fn LayerCreator }++func (s layerCreatorStore) WriteBlob(r io.Reader, mediaType, name string) (LayerInfo, error) {+ return s.fn(r, mediaType, name)+}diff --git a/x/create/pipeline_test.go b/x/create/pipeline_test.gonew file mode 100644index 000000000..ba0122d68--- /dev/null+++ b/x/create/pipeline_test.go@@ -0,0 +1,45 @@+package create++import (+ "path/filepath"+ "testing"++ st "github.com/ollama/ollama/x/safetensors"+)++func TestCreatePipeline(t *testing.T) {+ dir := t.TempDir()+ writeConfigJSON(t, dir, `{"architectures":["TestModel"]}`)+ createTestSafetensors(t, filepath.Join(dir, "model.safetensors"), []*st.TensorData{+ st.NewTensorDataFromBytes("model.embed_tokens.weight", "BF16", []int32{8, 8}, make([]byte, 8*8*2)),+ st.NewTensorDataFromBytes("model.norm.weight", "BF16", []int32{8}, make([]byte, 8*2)),+ })++ store := newCaptureStore()+ var gotName string+ var gotConfig LayerInfo+ var gotLayers []LayerInfo+ writeManifest := func(name string, config LayerInfo, layers []LayerInfo) error {+ gotName, gotConfig, gotLayers = name, config, layers+ return nil+ }++ if err := Create("mymodel", dir, "", store, writeManifest, func(string) {}); err != nil {+ t.Fatalf("Create() error = %v", err)+ }++ if gotName != "mymodel" {+ t.Errorf("manifest name = %q, want mymodel", gotName)+ }+ if gotConfig.Name != "config.json" {+ t.Errorf("config layer = %q, want config.json", gotConfig.Name)+ }+ if len(gotLayers) != 3 {+ t.Fatalf("manifest layers = %d, want 3 (2 tensors + config.json)", len(gotLayers))+ }+ for _, n := range []string{"model.embed_tokens.weight", "model.norm.weight", "config.json"} {+ if _, ok := store.blobs[n]; !ok {+ t.Errorf("missing written blob %q (have %v)", n, store.names())+ }+ }+}diff --git a/x/create/plan.go b/x/create/plan.gonew file mode 100644index 000000000..d61dcb394--- /dev/null+++ b/x/create/plan.go@@ -0,0 +1,282 @@+package create++import (+ "fmt"+ "slices"+ "sort"+ "strconv"+ "strings"+)++// Transform names how a tensor's source(s) are turned into the output tensor.+// The zero value, TransformNone, copies a single source through unchanged.+type Transform string++const (+ TransformNone Transform = ""++ // TransformRepackFP4 reinterprets a U8 fp4-packed weight (2 values/byte)+ // as U32 words (8 values/word): the bytes are unchanged, only the dtype+ // and last dimension are relabeled.+ TransformRepackFP4 Transform = "repack_fp4"++ // TransformRelabelU8 relabels an F8_E4M3 scale as U8 so the loader reads+ // its raw bytes; the bytes themselves are unchanged.+ TransformRelabelU8 Transform = "relabel_u8"++ // TransformScalarF32 validates that the source is a scalar F32 and copies+ // 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).+ TransformReciprocalF32 Transform = "reciprocal_f32"++ // TransformStackExperts concatenates N per-expert source tensors (in+ // expert-index order) into one [experts, ...] tensor.+ TransformStackExperts Transform = "stack_experts"++ // TransformDecodeFP8 dequantizes a block-FP8 weight using its block scale.+ // Its two sources are the F8_E4M3 weight and its scale companion; the+ // result is a BF16 tensor, which Quantize (if set) then re-quantizes.+ TransformDecodeFP8 Transform = "decode_fp8"++ // TransformDecodeStackFP8 stacks N per-expert block-FP8 weights (and their N+ // block scales) into one [experts, out, in] tensor and dequantizes it. Its+ // sources are the N weights followed by the N scales, in expert-index order;+ // the result is a BF16 tensor, which Quantize (if set) then re-quantizes.+ TransformDecodeStackFP8 Transform = "decode_stack_fp8"+)++// TensorSpec describes one output tensor within a blob: the source tensor(s)+// it is built from, the transform that combines or converts them, the name it+// takes in the blob, and an optional quantization to apply. When Quantize is+// set the writer runs MLX quantization, which generates the tensor's scale and+// bias sub-tensors; otherwise the (transformed) bytes are stored as-is.+type TensorSpec struct {+ Name string+ Sources []SourceTensor+ Transform Transform+ Quantize string+ OutDtype string // dtype after the transform; "" means same as the single source+ OutShape []int32 // shape after the transform; nil means same as the single source+}++// BlobSpec describes one output blob: its layer name, the tensors it contains,+// and its safetensors metadata. The planner builds these purely from the+// inventory and classification; the writer executes them and makes no+// decisions of its own.+type BlobSpec struct {+ Name string+ Tensors []TensorSpec+ Metadata map[string]string+}++// quantizePolicy decides the quantization type for each tensor of a model,+// returning "" to keep it at source precision. A policy may return a higher-+// precision type than requested for sensitive tensors. The per-architecture+// import transforms implement it; defaultQuantPolicy provides the generic+// default (GetTensorQuantization).+type quantizePolicy interface {+ quantizationType(name string, shape []int32, requested string) string+}++// Plan turns an inventory and its classification into the ordered list of+// blobs to write. It reads no weight data and makes every decision here, so+// the writer that follows has nothing left to decide. The policy decides which+// weights are quantized and to what; pass defaultQuantPolicy{} for the generic+// policy.+func Plan(inv Inventory, class Classification, policy quantizePolicy) ([]BlobSpec, error) {+ var (+ specs []BlobSpec+ err error+ )+ switch class.Kind {+ case SourceFloat:+ specs, err = planFloat(inv, class.Quantize, policy)+ case SourcePrequantized:+ specs, err = planPrequantized(inv)+ case SourceBlockFP8:+ specs, err = planBlockFP8(inv, class.Quantize, policy)+ default:+ return nil, fmt.Errorf("plan: source kind %q is not yet supported", class.Kind)+ }+ if err != nil {+ return nil, err+ }+ if err := checkOutputCollisions(specs); err != nil {+ return nil, err+ }+ return specs, nil+}++// checkOutputCollisions rejects a plan in which two source tensors normalized+// to the same output name — for example a source shipping both foo.weight and+// foo.weight_packed, which would both fuse to foo.weight. Writing such a plan+// would produce blobs that silently shadow each other at load time.+func checkOutputCollisions(specs []BlobSpec) error {+ blobs := make(map[string]bool, len(specs))+ tensors := make(map[string]string)+ for _, spec := range specs {+ if blobs[spec.Name] {+ return fmt.Errorf("plan: two blobs named %s (source tensors normalize to a clashing name)", spec.Name)+ }+ blobs[spec.Name] = true+ for _, ts := range spec.Tensors {+ if prev, ok := tensors[ts.Name]; ok {+ return fmt.Errorf("plan: output tensor %s planned in both blob %s and blob %s (source tensors normalize to a clashing name)", ts.Name, prev, spec.Name)+ }+ tensors[ts.Name] = spec.Name+ }+ }+ return nil+}++// planFloat plans a float model: per-expert tensors are packed into one blob+// per layer's expert group; every other tensor becomes its own blob, with the+// quantization policy deciding which weights are quantized and to what.+func planFloat(inv Inventory, quantize string, policy quantizePolicy) ([]BlobSpec, error) {+ groups := make(map[string][]SourceTensor)+ var plain []string+ for _, name := range sortedTensorNames(inv) {+ if gp, ok := perExpertGroup(name); ok {+ groups[gp] = append(groups[gp], inv.Tensors[name])+ } else {+ plain = append(plain, name)+ }+ }++ specs := make([]BlobSpec, 0, len(plain)+len(groups))+ for _, name := range plain {+ t := inv.Tensors[name]+ q := ""+ if quantize != "" {+ q = policy.quantizationType(name, t.Shape, quantize)+ }+ specs = append(specs, BlobSpec{+ Name: name,+ Tensors: []TensorSpec{{Name: name, Sources: []SourceTensor{t}, Quantize: q}},+ })+ }++ for _, gp := range sortedKeys(groups) {+ spec, err := planExpertGroup(gp, groups[gp], quantize, policy)+ if err != nil {+ return nil, err+ }+ specs = append(specs, spec)+ }+ return specs, nil+}++// planExpertGroup packs a layer's per-expert weights into one blob: the experts+// of each projection are stacked into a single [experts, out, in] tensor and+// quantized per the policy. Output tensor names keep the source's ".experts."+// path; only the per-expert index is dropped.+func planExpertGroup(groupPrefix string, tensors []SourceTensor, quantize string, policy quantizePolicy) (BlobSpec, error) {+ type expert struct {+ idx int+ t SourceTensor+ }+ byProj := make(map[string][]expert)+ for _, t := range tensors {+ idx, proj, err := parseExpertTensor(groupPrefix, t.Name)+ if err != nil {+ return BlobSpec{}, err+ }+ byProj[proj] = append(byProj[proj], expert{idx: idx, t: t})+ }++ spec := BlobSpec{Name: groupPrefix}+ for _, proj := range sortedKeys(byProj) {+ experts := byProj[proj]+ sort.Slice(experts, func(i, j int) bool { return experts[i].idx < experts[j].idx })++ base := experts[0].t+ sources := make([]SourceTensor, len(experts))+ for i, e := range experts {+ if e.t.Dtype != base.Dtype || !slices.Equal(e.t.Shape, base.Shape) {+ return BlobSpec{}, fmt.Errorf("expert group %s projection %s has mismatched expert layout (%s %v vs %s %v)",+ groupPrefix, proj, base.Dtype, base.Shape, e.t.Dtype, e.t.Shape)+ }+ sources[i] = e.t+ }++ stackedName := groupPrefix + "." + proj + ".weight"+ stackedShape := append([]int32{int32(len(experts))}, base.Shape...)+ q := ""+ if quantize != "" {+ q = policy.quantizationType(stackedName, stackedShape, quantize)+ }+ spec.Tensors = append(spec.Tensors, TensorSpec{+ Name: stackedName,+ Sources: sources,+ Transform: TransformStackExperts,+ Quantize: q,+ OutDtype: base.Dtype,+ OutShape: stackedShape,+ })+ }+ return spec, nil+}++// parseExpertTensor splits a per-expert weight name of the form+// "<groupPrefix>.<index>.<projection>.weight" into its expert index and+// projection name.+func parseExpertTensor(groupPrefix, name string) (idx int, proj string, err error) {+ rest, ok := strings.CutPrefix(name, groupPrefix+".")+ if !ok {+ return 0, "", fmt.Errorf("expert tensor %q is not under group %q", name, groupPrefix)+ }+ rest, ok = strings.CutSuffix(rest, ".weight")+ if !ok {+ return 0, "", fmt.Errorf("expert tensor %q does not end in .weight", name)+ }+ idxStr, proj, ok := strings.Cut(rest, ".")+ if !ok {+ return 0, "", fmt.Errorf("expert tensor %q is not <index>.<projection>.weight", name)+ }+ idx, err = strconv.Atoi(idxStr)+ if err != nil {+ return 0, "", fmt.Errorf("expert tensor %q has a non-numeric expert index %q", name, idxStr)+ }+ return idx, proj, nil+}++// perExpertGroup reports whether name is a per-expert weight that must be+// stacked — e.g. "<layer>.mlp.experts.3.gate_proj.weight" — and returns its+// group prefix. An already-stacked expert tensor (one tensor covering all+// experts, e.g. "<layer>.mlp.experts.gate_up_proj.weight" as qwen3.5 and+// gemma4 ship it) is not per-expert: it is quantized as an ordinary 3D tensor+// and the runtime splits/uses it directly.+func perExpertGroup(name string) (string, bool) {+ gp := ExpertGroupPrefix(name)+ if gp == "" {+ return "", false+ }+ rest, ok := strings.CutPrefix(name, gp+".")+ if !ok {+ return "", false+ }+ idx, _, ok := strings.Cut(rest, ".")+ if !ok {+ return "", false+ }+ if _, err := strconv.Atoi(idx); err != nil {+ return "", false+ }+ return gp, true+}++func sortedTensorNames(inv Inventory) []string {+ return sortedKeys(inv.Tensors)+}++func sortedKeys[V any](m map[string]V) []string {+ keys := make([]string, 0, len(m))+ for k := range m {+ keys = append(keys, k)+ }+ sort.Strings(keys)+ return keys+}diff --git a/x/create/plan_test.go b/x/create/plan_test.gonew file mode 100644index 000000000..ccc2cab2d--- /dev/null+++ b/x/create/plan_test.go@@ -0,0 +1,208 @@+package create++import (+ "slices"+ "sort"+ "strings"+ "testing"+)++func TestPlanRejectsOutputNameCollision(t *testing.T) {+ // A source shipping both an MLX-pattern weight (foo.weight + foo.scales)+ // and a compressed-tensors weight (foo.weight_packed + foo.weight_scale)+ // fuses both to the output name foo.weight.+ inv := newInventory(sourceModelConfig{}, map[string]string{+ "model.a.weight": "U32",+ "model.a.scales": "BF16",+ "model.a.weight_packed": "U8",+ "model.a.weight_scale": "F8_E4M3",+ })+ _, err := Plan(inv, Classification{Kind: SourcePrequantized}, defaultQuantPolicy{})+ if err == nil || !strings.Contains(err.Error(), "clashing name") {+ t.Fatalf("Plan() error = %v, want a clashing-name error", err)+ }+}++func TestPlanFloat(t *testing.T) {+ inv := newInventory(sourceModelConfig{}, map[string]string{+ "model.embed_tokens.weight": "BF16",+ "model.layers.0.input_layernorm.weight": "BF16",+ "model.layers.0.self_attn.q_proj.weight": "BF16",+ "model.layers.0.self_attn.v_proj.weight": "BF16",+ "model.layers.0.mlp.down_proj.weight": "BF16",+ })++ t.Run("no quantize", func(t *testing.T) {+ specs, err := Plan(inv, Classification{Kind: SourceFloat}, defaultQuantPolicy{})+ if err != nil {+ t.Fatalf("Plan() error = %v", err)+ }+ if len(specs) != len(inv.Tensors) {+ t.Fatalf("got %d specs, want %d", len(specs), len(inv.Tensors))+ }+ if !sort.SliceIsSorted(specs, func(i, j int) bool { return specs[i].Name < specs[j].Name }) {+ t.Error("specs are not sorted by name")+ }+ for _, s := range specs {+ if len(s.Tensors) != 1 || s.Tensors[0].Name != s.Name || sourceName(s.Tensors[0]) != s.Name {+ t.Errorf("%s: unexpected tensors %+v", s.Name, s.Tensors)+ }+ if s.Tensors[0].Quantize != "" {+ t.Errorf("%s: quantize = %q, want empty when no --quantize", s.Name, s.Tensors[0].Quantize)+ }+ }+ })++ t.Run("4-bit fp promotes sensitive tensors to mxfp8", func(t *testing.T) {+ for _, quant := range []string{"nvfp4", "mxfp4"} {+ specs, err := Plan(inv, Classification{Kind: SourceFloat, Quantize: quant}, defaultQuantPolicy{})+ if err != nil {+ t.Fatalf("Plan(%s) error = %v", quant, err)+ }+ got := make(map[string]string)+ for _, s := range specs {+ got[s.Name] = s.Tensors[0].Quantize+ }+ want := map[string]string{+ "model.embed_tokens.weight": "",+ "model.layers.0.input_layernorm.weight": "",+ "model.layers.0.self_attn.q_proj.weight": quant,+ "model.layers.0.self_attn.v_proj.weight": "mxfp8",+ "model.layers.0.mlp.down_proj.weight": "mxfp8",+ }+ for name, w := range want {+ if got[name] != w {+ t.Errorf("%s: %s quantize = %q, want %q", quant, name, got[name], w)+ }+ }+ }+ })++ t.Run("int4 applies the mixed-precision policy", func(t *testing.T) {+ specs, err := Plan(inv, Classification{Kind: SourceFloat, Quantize: "int4"}, defaultQuantPolicy{})+ if err != nil {+ t.Fatalf("Plan() error = %v", err)+ }+ got := make(map[string]string)+ for _, s := range specs {+ got[s.Name] = s.Tensors[0].Quantize+ }+ want := map[string]string{+ "model.embed_tokens.weight": "", // embeddings stay full precision+ "model.layers.0.input_layernorm.weight": "", // norms stay full precision+ "model.layers.0.self_attn.q_proj.weight": "int4", // standard linear+ "model.layers.0.self_attn.v_proj.weight": "int8", // promoted for quality+ "model.layers.0.mlp.down_proj.weight": "int8", // promoted for quality+ }+ for name, w := range want {+ if got[name] != w {+ t.Errorf("%s: quantize = %q, want %q", name, got[name], w)+ }+ }+ })+}++func TestPlanFloatExpertGroup(t *testing.T) {+ // A float MoE layer that ships per-expert tensors: two experts, two+ // projections. Each projection is stacked into one [experts, out, in]+ // tensor in a single packed blob; the routing gate and norm stay plain.+ inv := newInventory(sourceModelConfig{}, map[string]string{+ "model.layers.0.mlp.experts.0.gate_proj.weight": "BF16",+ "model.layers.0.mlp.experts.1.gate_proj.weight": "BF16",+ "model.layers.0.mlp.experts.0.down_proj.weight": "BF16",+ "model.layers.0.mlp.experts.1.down_proj.weight": "BF16",+ "model.layers.0.mlp.gate.weight": "BF16",+ "model.layers.0.input_layernorm.weight": "BF16",+ })++ specs, err := Plan(inv, Classification{Kind: SourceFloat, Quantize: "int4"}, defaultQuantPolicy{})+ if err != nil {+ t.Fatalf("Plan() error = %v", err)+ }++ group, ok := specByName(specs, "model.layers.0.mlp.experts")+ if !ok {+ t.Fatalf("missing packed expert blob; got %v", specNames(specs))+ }+ if len(group.Tensors) != 2 {+ t.Fatalf("packed blob has %d tensors, want 2 (gate_proj, down_proj)", len(group.Tensors))+ }++ gate, ok := inputByOutput(group, "model.layers.0.mlp.experts.gate_proj.weight")+ if !ok {+ t.Fatal("packed blob missing stacked gate_proj")+ }+ if gate.Transform != TransformStackExperts || len(gate.Sources) != 2 {+ t.Errorf("gate_proj = %+v, want stack of 2 experts", gate)+ }+ if !slices.Equal(gate.OutShape, []int32{2, 128, 128}) {+ t.Errorf("gate_proj stacked shape = %v, want [2 128 128]", gate.OutShape)+ }+ if gate.Sources[0].Name != "model.layers.0.mlp.experts.0.gate_proj.weight" ||+ gate.Sources[1].Name != "model.layers.0.mlp.experts.1.gate_proj.weight" {+ t.Errorf("gate_proj sources out of order: %v", gate.Sources)+ }+ if gate.Quantize != "int4" {+ t.Errorf("gate_proj quantize = %q, want int4", gate.Quantize)+ }++ down, _ := inputByOutput(group, "model.layers.0.mlp.experts.down_proj.weight")+ if down.Quantize != "int8" {+ t.Errorf("down_proj quantize = %q, want int8 (promoted)", down.Quantize)+ }++ // Routing gate and norm are not expert tensors; they stay as their own blobs.+ for _, name := range []string{"model.layers.0.mlp.gate.weight", "model.layers.0.input_layernorm.weight"} {+ if _, ok := specByName(specs, name); !ok {+ t.Errorf("%s should be its own blob", name)+ }+ }+}++func TestPlanFloatPrestackedExperts(t *testing.T) {+ // qwen3.5 / gemma4 ship experts pre-stacked and fused: one tensor per+ // projection covering all experts. These are quantized as ordinary 3D+ // stacked tensors (each its own blob, no per-expert stacking); the runtime+ // splits the fused gate_up at load. Names are kept exactly.+ inv := Inventory{Dir: "test", Tensors: map[string]SourceTensor{+ "model.layers.0.mlp.experts.gate_up_proj.weight": {Name: "model.layers.0.mlp.experts.gate_up_proj.weight", Dtype: "BF16", Shape: []int32{8, 256, 128}},+ "model.layers.0.mlp.experts.down_proj.weight": {Name: "model.layers.0.mlp.experts.down_proj.weight", Dtype: "BF16", Shape: []int32{8, 128, 128}},+ "model.layers.0.mlp.gate.weight": {Name: "model.layers.0.mlp.gate.weight", Dtype: "BF16", Shape: []int32{8, 128}},+ }}++ specs, err := Plan(inv, Classification{Kind: SourceFloat, Quantize: "int4"}, defaultQuantPolicy{})+ if err != nil {+ t.Fatalf("Plan() error = %v", err)+ }++ // Each tensor is its own blob; nothing is grouped/stacked.+ gateUp, ok := specByName(specs, "model.layers.0.mlp.experts.gate_up_proj.weight")+ if !ok {+ t.Fatalf("fused gate_up should be its own blob; got %v", specNames(specs))+ }+ if len(gateUp.Tensors) != 1 || gateUp.Tensors[0].Transform != TransformNone || len(gateUp.Tensors[0].Sources) != 1 {+ t.Errorf("gate_up should pass through unstacked: %+v", gateUp.Tensors)+ }+ if gateUp.Tensors[0].Quantize != "int4" {+ t.Errorf("gate_up quantize = %q, want int4", gateUp.Tensors[0].Quantize)+ }+ down, _ := specByName(specs, "model.layers.0.mlp.experts.down_proj.weight")+ if down.Tensors[0].Quantize != "int8" {+ t.Errorf("down_proj quantize = %q, want int8 (promoted)", down.Tensors[0].Quantize)+ }+ // No packed group blob should have been produced.+ if _, ok := specByName(specs, "model.layers.0.mlp.experts"); ok {+ t.Error("pre-stacked experts must not be re-grouped into a packed blob")+ }+}++func TestPlanExpertGroupMismatchedLayout(t *testing.T) {+ // Experts in the same projection with different shapes cannot be stacked.+ inv := Inventory{Dir: "test", Tensors: map[string]SourceTensor{+ "model.layers.0.mlp.experts.0.gate_proj.weight": {Name: "model.layers.0.mlp.experts.0.gate_proj.weight", Dtype: "BF16", Shape: []int32{128, 128}},+ "model.layers.0.mlp.experts.1.gate_proj.weight": {Name: "model.layers.0.mlp.experts.1.gate_proj.weight", Dtype: "BF16", Shape: []int32{128, 64}},+ }}+ if _, err := Plan(inv, Classification{Kind: SourceFloat, Quantize: "int4"}, defaultQuantPolicy{}); err == nil {+ t.Fatal("Plan() error = nil, want mismatched expert layout error")+ }+}diff --git a/x/create/prequant.go b/x/create/prequant.gonew file mode 100644index 000000000..ec782c081--- /dev/null+++ b/x/create/prequant.go@@ -0,0 +1,190 @@+package create++import "strings"++// prequantPattern describes how one producer packs an already-quantized weight+// and its scale companions into safetensors files, and how to fuse them into+// the single blob our loader reads. Producers differ only in tensor names and a+// few per-field transforms; expressing them as table rows keeps those+// differences visible and prevents the per-producer drift the old separate code+// paths suffered (for example the global scale being stored as-is by one+// producer and inverted by another).+//+// All suffixes are relative to the base — the source weight name minus its+// weight suffix. The fused blob is always named "<base>.weight", with+// companions "<base>.weight.scale", ".bias", and ".global_scale".+type prequantPattern struct {+ name string++ weightSuffix string // source suffix identifying the weight (".weight" or ".weight_packed")+ repackWeight bool // repack a U8 fp4 weight into U32 words++ scaleSuffix string // required per-block / affine scale companion+ scaleRelabelU8 bool // relabel an F8_E4M3 scale as U8 for the loader++ 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++ ignoreSuffixes []string // companions consumed but not written (e.g. activation scales)++ forceQuantType string // override the blob's quant_type metadata+ defaultGroupSize string // set group_size metadata only when the config did not+}++// prequantPatterns is consulted in order; the first whose weight suffix matches+// and whose required scale companion is present wins. MLX and ModelOpt both use+// a ".weight" weight, but their scale companions (".scales" vs ".weight_scale")+// are mutually exclusive, so the order between them does not matter.+var prequantPatterns = []prequantPattern{+ {+ name: "mlx",+ weightSuffix: ".weight",+ scaleSuffix: ".scales",+ biasSuffix: ".biases",+ },+ {+ name: "compressed-tensors-nvfp4",+ weightSuffix: ".weight_packed",+ repackWeight: true,+ scaleSuffix: ".weight_scale",+ scaleRelabelU8: true,+ globalSuffix: ".weight_global_scale",+ globalReciprocal: true,+ ignoreSuffixes: []string{".input_scale", ".input_global_scale"},+ forceQuantType: "nvfp4",+ defaultGroupSize: "16",+ },+ {+ name: "modelopt-nvfp4",+ weightSuffix: ".weight",+ repackWeight: true,+ scaleSuffix: ".weight_scale",+ scaleRelabelU8: true,+ globalSuffix: ".weight_scale_2",+ ignoreSuffixes: []string{".input_scale", ".input_global_scale"},+ forceQuantType: "nvfp4",+ },+}++// planPrequantized plans an already-quantized source: each weight is fused with+// its scale companions into one blob, companions are not emitted on their own,+// and any remaining tensors (norms, embeddings) pass through at source+// precision.+func planPrequantized(inv Inventory) ([]BlobSpec, error) {+ fused := make(map[string]BlobSpec)+ consumed := make(map[string]bool)+ for _, name := range sortedTensorNames(inv) {+ spec, sources, ok := matchPrequant(name, inv)+ if !ok {+ continue+ }+ fused[name] = spec+ for _, s := range sources {+ consumed[s] = true+ }+ }++ specs := make([]BlobSpec, 0, len(inv.Tensors))+ for _, name := range sortedTensorNames(inv) {+ if spec, ok := fused[name]; ok {+ specs = append(specs, spec)+ continue+ }+ if consumed[name] {+ continue+ }+ t := inv.Tensors[name]+ specs = append(specs, BlobSpec{Name: name, Tensors: []TensorSpec{{Name: name, Sources: []SourceTensor{t}}}})+ }+ return specs, nil+}++// matchPrequant returns the fused blob for a weight tensor if it matches a+// prequantized producer, along with the source names it consumes. It returns+// ok=false when name is not a prequantized weight (a companion or a plain+// tensor).+func matchPrequant(name string, inv Inventory) (BlobSpec, []string, bool) {+ for _, p := range prequantPatterns {+ base, ok := strings.CutSuffix(name, p.weightSuffix)+ if !ok {+ continue+ }+ scaleSrc := base + p.scaleSuffix+ if !inv.Has(scaleSrc) {+ continue+ }++ outWeight := base + ".weight"+ weight := inv.Tensors[name]+ var tensors []TensorSpec+ var consumed []string++ weightTensor := TensorSpec{Name: outWeight, Sources: []SourceTensor{weight}}+ if p.repackWeight && strings.EqualFold(weight.Dtype, "U8") && len(weight.Shape) == 2 {+ weightTensor.Transform = TransformRepackFP4+ weightTensor.OutDtype = "U32"+ weightTensor.OutShape = []int32{weight.Shape[0], weight.Shape[1] / 4}+ }+ tensors = append(tensors, weightTensor)++ scale := inv.Tensors[scaleSrc]+ scaleTensor := TensorSpec{Name: outWeight + ".scale", Sources: []SourceTensor{scale}}+ if p.scaleRelabelU8 && isE4M3Dtype(scale.Dtype) {+ scaleTensor.Transform = TransformRelabelU8+ scaleTensor.OutDtype = "U8"+ }+ tensors = append(tensors, scaleTensor)+ consumed = append(consumed, scaleSrc)++ if p.biasSuffix != "" {+ if biasSrc := base + p.biasSuffix; inv.Has(biasSrc) {+ tensors = append(tensors, TensorSpec{Name: outWeight + ".bias", Sources: []SourceTensor{inv.Tensors[biasSrc]}})+ consumed = append(consumed, biasSrc)+ }+ }++ if p.globalSuffix != "" {+ if gSrc := base + p.globalSuffix; inv.Has(gSrc) {+ global := TensorSpec{Name: outWeight + ".global_scale", Sources: []SourceTensor{inv.Tensors[gSrc]}, Transform: TransformScalarF32}+ if p.globalReciprocal {+ global.Transform = TransformReciprocalF32+ }+ tensors = append(tensors, global)+ consumed = append(consumed, gSrc)+ }+ }++ for _, suf := range p.ignoreSuffixes {+ if s := base + suf; inv.Has(s) {+ consumed = append(consumed, s)+ }+ }++ return BlobSpec{Name: outWeight, Tensors: tensors, Metadata: prequantMetadata(inv, p)}, consumed, true+ }+ return BlobSpec{}, nil, false+}++// 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.+func prequantMetadata(inv Inventory, p prequantPattern) map[string]string {+ md := make(map[string]string)+ for k, v := range inv.Config.QuantMetadata() {+ md[k] = v+ }+ if p.forceQuantType != "" {+ md["quant_type"] = p.forceQuantType+ }+ if p.defaultGroupSize != "" {+ if _, ok := md["group_size"]; !ok {+ md["group_size"] = p.defaultGroupSize+ }+ }+ if len(md) == 0 {+ return nil+ }+ return md+}diff --git a/x/create/prequant_test.go b/x/create/prequant_test.gonew file mode 100644index 000000000..15f352b41--- /dev/null+++ b/x/create/prequant_test.go@@ -0,0 +1,183 @@+package create++import (+ "slices"+ "testing"+)++func specByName(specs []BlobSpec, name string) (BlobSpec, bool) {+ for _, s := range specs {+ if s.Name == name {+ return s, true+ }+ }+ return BlobSpec{}, false+}++func inputByOutput(spec BlobSpec, outputName string) (TensorSpec, bool) {+ for _, ts := range spec.Tensors {+ if ts.Name == outputName {+ return ts, true+ }+ }+ return TensorSpec{}, false+}++// sourceName returns the (single) source tensor name for a TensorSpec.+func sourceName(ts TensorSpec) string {+ if len(ts.Sources) == 0 {+ return ""+ }+ return ts.Sources[0].Name+}++func specNames(specs []BlobSpec) []string {+ names := make([]string, len(specs))+ for i, s := range specs {+ names[i] = s.Name+ }+ return names+}++func TestPlanPrequantizedMLX(t *testing.T) {+ cfg := sourceModelConfig{Quantization: sourceQuantization{Bits: 4, Mode: "affine", GroupSize: 32}}+ inv := newInventory(cfg, map[string]string{+ "l.weight": "U32",+ "l.scales": "BF16",+ "l.biases": "BF16",+ "norm.weight": "BF16",+ })++ specs, err := Plan(inv, Classification{Kind: SourcePrequantized}, defaultQuantPolicy{})+ if err != nil {+ t.Fatalf("Plan() error = %v", err)+ }+ // l.weight (fused with scales+biases) and norm.weight (pass-through).+ if len(specs) != 2 {+ t.Fatalf("got %d specs %v, want 2", len(specs), specNames(specs))+ }++ w, ok := specByName(specs, "l.weight")+ if !ok {+ t.Fatal("missing l.weight blob")+ }+ for _, want := range []string{"l.weight", "l.weight.scale", "l.weight.bias"} {+ in, ok := inputByOutput(w, want)+ if !ok {+ t.Fatalf("l.weight blob missing input %q", want)+ }+ if in.Transform != TransformNone {+ t.Errorf("%s transform = %q, want none", want, in.Transform)+ }+ }+ if w.Metadata["quant_type"] != "int4" || w.Metadata["group_size"] != "32" {+ t.Errorf("metadata = %v, want quant_type=int4 group_size=32 from config", w.Metadata)+ }+ if _, ok := specByName(specs, "norm.weight"); !ok {+ t.Error("norm.weight should pass through as its own blob")+ }+}++func TestPlanPrequantizedModelOptNVFP4(t *testing.T) {+ inv := newInventory(sourceModelConfig{}, map[string]string{+ "l.weight": "U8",+ "l.weight_scale": "F8_E4M3",+ "l.weight_scale_2": "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", len(specs), specNames(specs))+ }+ w := specs[0]+ if w.Name != "l.weight" {+ t.Fatalf("blob name = %q, want l.weight", w.Name)+ }++ weightIn, _ := inputByOutput(w, "l.weight")+ if weightIn.Transform != TransformRepackFP4 || weightIn.OutDtype != "U32" || !slices.Equal(weightIn.OutShape, []int32{128, 32}) {+ t.Errorf("weight input = %+v, want repack to U32 [128 32]", weightIn)+ }+ scaleIn, _ := inputByOutput(w, "l.weight.scale")+ if scaleIn.Transform != TransformRelabelU8 || scaleIn.OutDtype != "U8" {+ t.Errorf("scale input = %+v, want relabel to U8", scaleIn)+ }+ globalIn, ok := inputByOutput(w, "l.weight.global_scale")+ if !ok || globalIn.Transform != TransformScalarF32 {+ t.Errorf("global_scale input = %+v ok=%v, want scalar_f32 (stored as-is)", globalIn, ok)+ }+ if w.Metadata["quant_type"] != "nvfp4" {+ t.Errorf("quant_type = %q, want nvfp4", w.Metadata["quant_type"])+ }+ if _, ok := w.Metadata["group_size"]; ok {+ t.Errorf("ModelOpt should not default group_size: %v", w.Metadata)+ }+}++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",+ })++ 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))+ }+ w := specs[0]+ if w.Name != "l.weight" {+ t.Fatalf("blob name = %q, want l.weight", w.Name)+ }++ weightIn, _ := inputByOutput(w, "l.weight")+ if sourceName(weightIn) != "l.weight_packed" || weightIn.Transform != TransformRepackFP4 {+ t.Errorf("weight input = %+v, want source l.weight_packed repacked", weightIn)+ }+ globalIn, ok := inputByOutput(w, "l.weight.global_scale")+ if !ok || globalIn.Transform != TransformReciprocalF32 {+ t.Errorf("global_scale input = %+v ok=%v, want reciprocal_f32", globalIn, ok)+ }+ if w.Metadata["quant_type"] != "nvfp4" || w.Metadata["group_size"] != "16" {+ t.Errorf("metadata = %v, want quant_type=nvfp4 group_size=16", w.Metadata)+ }+}diff --git a/x/create/quantize.go b/x/create/quantize.gonew file mode 100644index 000000000..b91a356bd--- /dev/null+++ b/x/create/quantize.go@@ -0,0 +1,289 @@+package create++import (+ "fmt"+ "io"+ "os"+ "path/filepath"+ "slices"+ "strconv"++ "github.com/ollama/ollama/x/mlxrunner/mlx"+ "github.com/ollama/ollama/x/quant"+)++// QuantizeSupported reports whether MLX (and thus quantization) is available.+func QuantizeSupported() bool {+ return mlx.CheckInit() == nil+}++// quantizeItem is one tensor going into a (possibly multi-tensor) quantized+// blob: its output name, the quantization to apply (or "" to decode/keep at+// source precision), a safetensors-wrapped reader for its input bytes (keyed by+// name), and whether the input is a block-FP8 weight to decode before use.+type quantizeItem struct {+ name string+ quantize string+ reader io.Reader+ decodeFP8 bool+}++// quantizeBlob loads, optionally quantizes, and packs the given tensors into a+// single safetensors blob (weight + scale + optional bias per quantized+// tensor). All MLX work runs on the pinned MLX thread.+func quantizeBlob(items []quantizeItem) ([]byte, error) {+ var blob []byte+ err := runOnMLXThread(func() error {+ var err error+ blob, err = quantizeBlobLocked(items)+ return err+ })+ return blob, err+}++func quantizeBlobLocked(items []quantizeItem) ([]byte, error) {+ allArrays := make(map[string]*mlx.Array)+ var pinned []*mlx.Array+ defer func() {+ mlx.Unpin(pinned...)+ mlx.Sweep()+ }()++ tmpDir, err := os.MkdirTemp("", "ollama-quantize-*")+ if err != nil {+ return nil, fmt.Errorf("failed to create temp dir: %w", err)+ }+ defer os.RemoveAll(tmpDir)++ // Blob metadata: a single quant_type/group_size when every quantized+ // tensor matches, otherwise per-tensor entries.+ uniform, mixed, hasQuant := "", false, false+ for _, it := range items {+ if it.quantize == "" {+ if hasQuant {+ mixed = true+ }+ continue+ }+ if !hasQuant {+ hasQuant, uniform = true, it.quantize+ continue+ }+ if it.quantize != uniform {+ mixed = true+ }+ }+ var metadata map[string]string+ if hasQuant && !mixed {+ if gs, _, _ := quant.Params(uniform); gs > 0 {+ metadata = map[string]string{"quant_type": uniform, "group_size": strconv.Itoa(gs)}+ }+ }++ for _, it := range items {+ if err := func() error {+ defer mlx.Sweep()+ tmpPath, toEval, st, err := loadAndQuantizeArray(it.reader, it.name, it.quantize, it.decodeFP8, allArrays, tmpDir)+ if tmpPath != "" {+ defer os.Remove(tmpPath)+ }+ if err != nil {+ return err+ }+ if st != nil {+ defer st.Free()+ }+ mlx.Eval(toEval...)+ final := arraysForItem(allArrays, it)+ mlx.Pin(final...)+ pinned = append(pinned, final...)++ if mixed && it.quantize != "" {+ if gs, _, _ := quant.Params(it.quantize); gs > 0 {+ if metadata == nil {+ metadata = make(map[string]string)+ }+ metadata[it.name+".quant_type"] = it.quantize+ metadata[it.name+".group_size"] = strconv.Itoa(gs)+ }+ }+ return nil+ }(); err != nil {+ return nil, err+ }+ }++ outPath := filepath.Join(tmpDir, "blob.safetensors")+ if err := mlx.SaveSafetensorsWithMetadata(outPath, allArrays, metadata); err != nil {+ return nil, fmt.Errorf("failed to save blob: %w", err)+ }+ return os.ReadFile(outPath)+}++func arraysForItem(all map[string]*mlx.Array, it quantizeItem) []*mlx.Array {+ keys := []string{it.name}+ if it.quantize != "" {+ keys = append(keys, it.name+".scale", it.name+".bias")+ }+ out := make([]*mlx.Array, 0, len(keys))+ for _, k := range keys {+ if a := all[k]; a != nil {+ out = append(out, a)+ }+ }+ return out+}++// loadAndQuantizeArray writes a safetensors reader to a temp file, loads it+// with MLX, decodes a block-FP8 source tensor if present, optionally+// quantizes, and adds the resulting arrays (weight, scale, optional bias) to+// arrays keyed by name. With quantize == "" the (decoded) tensor is kept as-is.+// It must be called on the MLX thread.+//+// TODO: MLX's safetensors loader takes a file path, so we spill each tensor to a+// temp file. Wiring a streaming mlx_load_safetensors_reader into the CGO wrapper+// would let us load from the reader directly and drop the temp files.+func loadAndQuantizeArray(r io.Reader, name, quantize string, decodeFP8 bool, arrays map[string]*mlx.Array, tmpDir string) (tmpPath string, toEval []*mlx.Array, nativeHandle *mlx.SafetensorsFile, err error) {+ if quantize != "" && quant.Canonical(quantize) == "" {+ return "", nil, nil, fmt.Errorf("unsupported quantization type: %s", quantize)+ }++ tmpFile, err := os.CreateTemp(tmpDir, "quant-*.safetensors")+ if err != nil {+ return "", nil, nil, fmt.Errorf("failed to create temp file: %w", err)+ }+ tmpPath = tmpFile.Name()+ if _, err := io.Copy(tmpFile, r); err != nil {+ tmpFile.Close()+ return tmpPath, nil, nil, fmt.Errorf("failed to write temp file for %s: %w", name, err)+ }+ tmpFile.Close()++ st, err := mlx.LoadSafetensorsNative(tmpPath)+ if err != nil {+ return tmpPath, nil, nil, fmt.Errorf("failed to load safetensors for %s: %w", name, err)+ }++ arr := st.Get(name)+ if arr == nil {+ st.Free()+ return tmpPath, nil, nil, fmt.Errorf("tensor %q not found in safetensors", name)+ }++ // Decode an FP8 source tensor (using its block scale) before quantizing,+ // so a decode-only request (quantize == "") still yields usable float data.+ if decodeFP8 {+ scaleKey := name + ".scale_inv"+ scaleInv := st.Get(scaleKey)+ if scaleInv == nil {+ scaleKey = name + ".scale"+ scaleInv = st.Get(scaleKey)+ }+ if scaleInv == nil {+ st.Free()+ return tmpPath, nil, nil, fmt.Errorf("missing companion tensor %q or %q for fp8 source tensor %q", name+".scale_inv", name+".scale", name)+ }+ arr, err = decodeSourceFP8Tensor(arr, scaleInv)+ if err != nil {+ st.Free()+ return tmpPath, nil, nil, fmt.Errorf("failed to decode fp8 tensor %s: %w", name, err)+ }+ mlx.Eval(arr)+ }++ if quantize == "" {+ arr = mlx.Contiguous(arr, false)+ arrays[name] = arr+ return tmpPath, []*mlx.Array{arr}, st, nil+ }++ if arr.DType() != mlx.DTypeBFloat16 && arr.DType() != mlx.DTypeFloat32 && arr.DType() != mlx.DTypeFloat16 {+ arr = arr.AsType(mlx.DTypeBFloat16)+ mlx.Eval(arr)+ }++ groupSize, bits, mode := quant.Params(quantize)+ qweight, scales, qbiases := mlx.Quantize(arr, groupSize, bits, mode)+ mlx.Eval(qweight, scales)+ if len(qweight.Dims()) == 0 || qweight.Dims()[0] == 0 {+ st.Free()+ return tmpPath, nil, nil, fmt.Errorf("mlx.Quantize produced empty weight for %s (quantize=%s, groupSize=%d, bits=%d, mode=%s)", name, quantize, groupSize, bits, mode)+ }+ if len(scales.Dims()) == 0 || scales.Dims()[0] == 0 {+ st.Free()+ return tmpPath, nil, nil, fmt.Errorf("mlx.Quantize produced empty scales for %s (quantize=%s, groupSize=%d, bits=%d, mode=%s)", name, quantize, groupSize, bits, mode)+ }++ qweight = mlx.Contiguous(qweight, false)+ scales = mlx.Contiguous(scales, false)+ arrays[name] = qweight+ arrays[name+".scale"] = scales+ toEval = append(toEval, qweight, scales)+ if qbiases != nil {+ qbiases = mlx.Contiguous(qbiases, false)+ arrays[name+".bias"] = qbiases+ toEval = append(toEval, qbiases)+ }+ return tmpPath, toEval, st, nil+}++// decodeSourceFP8Tensor dequantizes a 128x128 block-FP8 weight using its block+// scale, returning a BF16 tensor. The weight is either 2D [rows, cols] with a 2D+// scale [ceil(rows/128), ceil(cols/128)], or a stacked 3D expert tensor+// [experts, rows, cols] with a 3D scale [experts, ceil(rows/128), ceil(cols/128)];+// the leading expert axis (if present) is decoded block-wise per expert.+func decodeSourceFP8Tensor(weight, scale *mlx.Array) (*mlx.Array, error) {+ if weight == nil || scale == nil {+ return nil, fmt.Errorf("fp8 weight and scale tensors are required")+ }+ weightShape := weight.Dims()+ scaleShape := scale.Dims()+ rank := len(weightShape)+ if (rank != 2 && rank != 3) || len(scaleShape) != rank {+ return nil, fmt.Errorf("expected matching 2D or 3D fp8 weight and scale tensors, got %v and %v", weightShape, scaleShape)+ }++ const blockRows = 128+ const blockCols = 128++ // The 128x128 blocks tile the trailing [rows, cols]; a 3D weight carries a+ // leading expert axis that broadcasts over those blocks one expert at a time.+ lead := weightShape[:rank-2]+ rows, cols := weightShape[rank-2], weightShape[rank-1]+ sr := (rows + blockRows - 1) / blockRows+ sc := (cols + blockCols - 1) / blockCols+ wantScale := append(append([]int(nil), lead...), sr, sc)+ if !slices.Equal(scaleShape, wantScale) {+ return nil, fmt.Errorf("unexpected fp8 scale shape %v for weight shape %v; want %v", scaleShape, weightShape, wantScale)+ }++ leadI32 := make([]int32, len(lead))+ for i, d := range lead {+ leadI32[i] = int32(d)+ }++ decoded := mlx.FromFP8(weight, mlx.DTypeBFloat16)+ dtype := decoded.DType()+ padBottom := blockRows*sr - rows+ padSide := blockCols*sc - cols+ if padBottom > 0 || padSide > 0 {+ // Pad the bottom/right of the trailing [rows, cols] only.+ decoded = mlx.PadConstant(decoded, []int{rank - 2, rank - 1}, []int{0, 0}, []int{padBottom, padSide})+ }++ // Split each 128x128 block into its own axis pair, scale every block by its+ // per-block factor (broadcast across the block interior), then restore.+ blocked := append(append([]int32(nil), leadI32...), int32(sr), blockRows, int32(sc), blockCols)+ decoded = mlx.Reshape(decoded, blocked...)+ // scale [..., sr, sc] -> [..., sr, 1, sc, 1]+ scaleB := mlx.ExpandDims(mlx.ExpandDims(scale, len(lead)+1), len(lead)+3)+ // Multiplying by an F32 scale promotes the result; keep the decoded dtype.+ decoded = mlx.Mul(decoded, scaleB).AsType(dtype)+ padded := append(append([]int32(nil), leadI32...), int32(rows+padBottom), int32(cols+padSide))+ decoded = mlx.Reshape(decoded, padded...)+ if padBottom > 0 || padSide > 0 {+ stops := append(append([]int32(nil), leadI32...), int32(rows), int32(cols))+ decoded = mlx.SliceStartStop(decoded, make([]int32, rank), stops)+ }+ return decoded, nil+}diff --git a/x/create/quantpolicy.go b/x/create/quantpolicy.gonew file mode 100644index 000000000..2fc000663--- /dev/null+++ b/x/create/quantpolicy.go@@ -0,0 +1,96 @@+package create++import (+ "regexp"+ "strconv"+ "strings"+)++// defaultQuantPolicy is the quantize policy for any architecture without a+// registered override: the shared GetTensorQuantization decision with no+// architecture-specific adjustments.+type defaultQuantPolicy struct{}++func (defaultQuantPolicy) quantizationType(name string, shape []int32, quantize string) string {+ return GetTensorQuantization(name, shape, quantize)+}++// layerIndexRe extracts the layer index from tensor names like+// "model.language_model.layers.5.self_attn.v_proj.weight" or+// "model.language_model.layers.5.moe.experts.42.down_proj.weight"+var layerIndexRe = regexp.MustCompile(`\.layers\.(\d+)\.`)++// layerIndex returns the transformer layer index encoded in name, or -1.+func layerIndex(name string) int {+ m := layerIndexRe.FindStringSubmatch(name)+ if m == nil {+ return -1+ }+ idx, err := strconv.Atoi(m[1])+ if err != nil {+ return -1+ }+ return idx+}++// useMoreBits returns true for layers where quantization-sensitive tensors+// should use higher precision: the first and last 1/8 of layers (which handle+// input grounding and final output refinement), plus every 3rd layer in between+// to limit error accumulation through the residual stream.+func useMoreBits(layerIdx, numLayers int) bool {+ return layerIdx < numLayers/8 ||+ layerIdx >= 7*numLayers/8 ||+ (layerIdx-numLayers/8)%3 == 2+}++// eightBit returns the 8-bit quantization type in base's family: int8 for the+// affine family, mxfp8 for the fp4 family.+func eightBit(base string) string {+ if base == "int4" || base == "int8" {+ return "int8"+ }+ return "mxfp8"+}++// promoteEmbedding returns the 8-bit type in base's family when the embedding+// shape fits it, or "" when it does not. Token embeddings often double as the+// lm_head projection, where an 8-bit type keeps quality close to bf16 while+// saving decode bandwidth; the caller decides the fallback when 8-bit does not+// fit (the base type, or source precision).+func promoteEmbedding(shape []int32, base string) string {+ if e := eightBit(base); isAligned(shape, e) {+ return e+ }+ return ""+}++// sensitiveType resolves a quantization-sensitive projection (v/k/down): the+// 8-bit type in base's family when promote is set and fits the shape,+// otherwise the base type when it fits, otherwise source precision.+func sensitiveType(promote bool, shape []int32, base string) string {+ if promote {+ if e := eightBit(base); isAligned(shape, e) {+ return e+ }+ }+ if isAligned(shape, base) {+ return base+ }+ return ""+}++// isEmbedTokensWeight returns true for the main token embedding weight.+func isEmbedTokensWeight(name string) bool {+ return strings.HasSuffix(name, "embed_tokens.weight") &&+ !strings.Contains(name, "per_layer")+}++// isVisionTower reports tensors under a model's vision tower.+func isVisionTower(name string) bool {+ return strings.Contains(name, "vision_tower") || strings.Contains(name, ".visual.")+}++// isAudioTower reports tensors under a model's audio tower or audio embedding.+func isAudioTower(name string) bool {+ return strings.Contains(name, "audio_tower") || strings.Contains(name, "embed_audio")+}diff --git a/x/create/qwen35.go b/x/create/qwen35.goindex ea72e83b3..b7206fe0a 100644--- a/x/create/qwen35.go+++ b/x/create/qwen35.go@@ -1,354 +1,29 @@package createimport (- "fmt"- "io"- "os"- "path/filepath"+ "encoding/json""strings"-- "github.com/ollama/ollama/x/safetensors")-type qwen35ImportTransform struct {- shouldShiftNormWeights bool- rewriteLanguageModel bool-}--type qwen35SourceInfo struct {- hasPrequantizedWeights bool- shouldShiftNormWeights bool-}--func newQwen35ImportTransform(modelDir string, cfg sourceModelConfig) (tensorImportTransform, error) {- sourceInfo, err := qwen35InspectSource(modelDir)- if err != nil {- return qwen35ImportTransform{}, err- }- if sourceInfo.hasPrequantizedWeights {- return noopImportTransform{}, nil- }-- return qwen35ImportTransform{- shouldShiftNormWeights: sourceInfo.shouldShiftNormWeights,- rewriteLanguageModel: strings.Contains(cfg.Architecture(), "ConditionalGeneration"),- }, nil-}--func qwen35InspectSource(modelDir string) (qwen35SourceInfo, error) {- entries, err := os.ReadDir(modelDir)- if err != nil {- return qwen35SourceInfo{}, err- }-- var info qwen35SourceInfo- for _, entry := range entries {- if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".safetensors") {- continue- }+type qwen35ImportTransform struct{}- extractor, err := safetensors.OpenForExtraction(filepath.Join(modelDir, entry.Name()))- if err != nil {- return qwen35SourceInfo{}, err- }-- for _, name := range extractor.ListTensors() {- if strings.HasSuffix(name, ".scales") {- extractor.Close()- info.hasPrequantizedWeights = true- return info, nil- }- if strings.Contains(name, "mtp.") {- info.shouldShiftNormWeights = true- continue- }- if info.shouldShiftNormWeights || !strings.Contains(name, "conv1d.weight") {- continue- }-- td, err := extractor.GetTensor(name)- if err != nil {- extractor.Close()- return qwen35SourceInfo{}, err- }- if len(td.Shape) == 3 && td.Shape[2] != 1 {- info.shouldShiftNormWeights = true- }- }-- extractor.Close()- }-- return info, nil-}--func (t qwen35ImportTransform) skipTensor(name string) bool {- return false-}--func qwen35ShouldKeepBF16ForDirectNonAffine(name string) bool {- switch {- case strings.HasSuffix(name, "embed_tokens.weight"):- return true- case strings.HasSuffix(name, "lm_head.weight"):- return true- case strings.HasSuffix(name, ".linear_attn.in_proj_a.weight"):- return true- case strings.HasSuffix(name, ".linear_attn.in_proj_b.weight"):- return true- case strings.HasSuffix(name, ".linear_attn.in_proj_ba.weight"):- return true- case strings.HasSuffix(name, ".mlp.gate.weight") && !strings.Contains(name, "_proj"):- return true- case strings.HasSuffix(name, ".mlp.shared_expert_gate.weight"):- return true- default:- return false- }+func newQwen35ImportTransform(json.RawMessage) (quantizePolicy, error) {+ return qwen35ImportTransform{}, nil}-func (t qwen35ImportTransform) quantizationType(name string, shape []int32, quantize string) string {- if strings.HasPrefix(name, "vision_tower.") {- return ""- }-- stackedExpert := isStackedExpertWeight(name)- if strings.HasSuffix(name, ".bias") || strings.HasSuffix(name, ".scale") || strings.HasSuffix(name, ".qbias") ||- strings.HasSuffix(name, ".biases") || strings.HasSuffix(name, ".scales") {- return ""- }- if !stackedExpert && !strings.HasSuffix(name, ".weight") {- return ""- }- if strings.Contains(name, "norm") || strings.Contains(name, "ln_") || strings.Contains(name, "layernorm") {- return ""- }- if len(shape) != 2 && !(len(shape) == 3 && stackedExpert) {- return ""- }-- var elems int64 = 1- for _, d := range shape {- elems *= int64(d)- }- if elems < 1024 {- return ""- }-- quantNorm := normalizeQuantType(quantize)- groupSize := int32(32)- switch quantNorm {- case "nvfp4":- groupSize = 16- case "int4", "int8":- groupSize = 64- }- if shape[len(shape)-1]%groupSize != 0 {- return ""- }-- // Match the working HF-FP8 import policy for direct NVFP4/MXFP4/MXFP8 imports:- // keep embeddings, LM head, low-rank linear_attn projections, and routing- // gates in BF16 rather than forcing them into a non-affine quantized format.- if (quantNorm == "nvfp4" || quantNorm == "mxfp4" || quantNorm == "mxfp8") && qwen35ShouldKeepBF16ForDirectNonAffine(name) {+func (qwen35ImportTransform) quantizationType(name string, shape []int32, quantize string) string {+ // The vision tower is not yet supported and the low-rank linear-attention+ // projections are sensitive; keep both at source precision. Everything else+ // follows the generic policy, which already keeps embeddings, norms, biases,+ // and routing gates unquantized.+ if isVisionTower(name) || qwen35IsLowRankProjection(name) {return ""}-- return quantNorm-}--func (t qwen35ImportTransform) rewriteTensorData(td *safetensors.TensorData) (*safetensors.TensorData, error) {- if td == nil {- return td, nil- }-- shiftNorm := t.shouldShiftNormWeights && qwen35ShouldShiftNormKey(td.Name)- transposeConv := strings.Contains(td.Name, "conv1d.weight") && len(td.Shape) == 3 && td.Shape[2] != 1- castToBF16 := qwen35NeedsCastToBF16(td.Name, td.Dtype)- if !shiftNorm && !transposeConv && !castToBF16 {- return td, nil- }-- raw, err := io.ReadAll(td.Reader())- if err != nil {- return nil, fmt.Errorf("failed to read tensor %s: %w", td.Name, err)- }-- values, err := DecodeFloatTensor(td.Dtype, raw)- if err != nil {- return nil, fmt.Errorf("failed to decode tensor %s: %w", td.Name, err)- }-- shape := append([]int32(nil), td.Shape...)- if transposeConv {- values, shape = qwen35TransposeConv1D(values, shape)- }- if shiftNorm {- for i := range values {- values[i] += 1.0- }- }-- targetDtype := td.Dtype- if castToBF16 {- targetDtype = "BF16"- }-- out, err := EncodeFloatTensor(targetDtype, values)- if err != nil {- return nil, fmt.Errorf("failed to encode tensor %s: %w", td.Name, err)- }-- return safetensors.NewTensorDataFromBytes(td.Name, targetDtype, shape, out), nil-}--func (t qwen35ImportTransform) transformTensor(td *safetensors.TensorData) ([]*safetensors.TensorData, error) {- if td == nil {- return nil, nil- }-- name := t.canonicalTensorName(td.Name)-- // Phase 1: rename/split into intermediate tensors- var intermediates []*safetensors.TensorData- stripped := strings.TrimSuffix(name, ".weight")- switch {- case strings.HasSuffix(stripped, ".mlp.experts.gate_up_proj"):- prefix := strings.TrimSuffix(stripped, ".mlp.experts.gate_up_proj")- raw, err := io.ReadAll(td.Reader())- if err != nil {- return nil, fmt.Errorf("failed to read tensor %s: %w", td.Name, err)- }- gateRaw, upRaw, splitShape, err := qwen35SplitAxis1Raw(raw, td.Dtype, td.Shape)- if err != nil {- return nil, fmt.Errorf("failed to split tensor %s: %w", td.Name, err)- }- intermediates = []*safetensors.TensorData{- safetensors.NewTensorDataFromBytes(prefix+".mlp.switch_mlp.gate_proj.weight", td.Dtype, splitShape, gateRaw),- safetensors.NewTensorDataFromBytes(prefix+".mlp.switch_mlp.up_proj.weight", td.Dtype, splitShape, upRaw),- }- case strings.HasSuffix(stripped, ".mlp.experts.down_proj"):- newName := strings.TrimSuffix(stripped, ".mlp.experts.down_proj") + ".mlp.switch_mlp.down_proj.weight"- intermediates = []*safetensors.TensorData{td.WithName(newName)}- default:- intermediates = []*safetensors.TensorData{td.WithName(name)}- }-- // Phase 2: rewrite all intermediates- results := make([]*safetensors.TensorData, 0, len(intermediates))- for _, inter := range intermediates {- rewritten, err := t.rewriteTensorData(inter)- if err != nil {- return nil, err- }- results = append(results, rewritten)- }- return results, nil-}--func (t qwen35ImportTransform) canonicalTensorName(name string) string {- // Vision tensors: normalize to vision_tower.* prefix- switch {- case strings.HasPrefix(name, "model.visual."):- return "vision_tower." + strings.TrimPrefix(name, "model.visual.")- case strings.HasPrefix(name, "vision_tower."):- return name- case strings.HasPrefix(name, "mtp."):- return name- }-- // Language model tensors: normalize to language_model.model.* prefix- if !t.rewriteLanguageModel {- return name- }- switch {- case strings.HasPrefix(name, "model.language_model"):- return "language_model.model" + strings.TrimPrefix(name, "model.language_model")- case strings.HasPrefix(name, "language_model."):- return name- default:- return "language_model." + name- }-}--func qwen35ShouldShiftNormKey(key string) bool {- for _, suffix := range []string{- ".input_layernorm.weight",- ".post_attention_layernorm.weight",- "mtp.pre_fc_norm_embedding.weight",- "mtp.pre_fc_norm_hidden.weight",- "model.norm.weight",- ".q_norm.weight",- ".k_norm.weight",- } {- if strings.HasSuffix(key, suffix) {- return true- }- }- return false-}--func qwen35NeedsCastToBF16(name, dtype string) bool {- if strings.HasSuffix(name, "A_log") {- return false- }- switch strings.ToUpper(dtype) {- case "F16", "F32", "F64":- return true- default:- return false- }-}--func qwen35TransposeConv1D(values []float32, shape []int32) ([]float32, []int32) {- if len(shape) != 3 {- return values, shape- }-- d0, d1, d2 := int(shape[0]), int(shape[1]), int(shape[2])- out := make([]float32, len(values))- for i := range d0 {- for j := range d1 {- for k := range d2 {- inIdx := (i*d1+j)*d2 + k- outIdx := (i*d2+k)*d1 + j- out[outIdx] = values[inIdx]- }- }- }-- return out, []int32{shape[0], shape[2], shape[1]}+ return GetTensorQuantization(name, shape, quantize)}-func qwen35SplitAxis1Raw(raw []byte, dtype string, shape []int32) ([]byte, []byte, []int32, error) {- if len(shape) != 3 {- return nil, nil, nil, fmt.Errorf("expected 3D tensor, got shape %v", shape)- }- if shape[1]%2 != 0 {- return nil, nil, nil, fmt.Errorf("axis 1 dim %d is not even", shape[1])- }-- elemSize, err := DTypeSize(dtype)- if err != nil {- return nil, nil, nil, err- }-- d0, d1, d2 := int(shape[0]), int(shape[1]), int(shape[2])- perExpertBytes := d1 * d2 * elemSize- if len(raw) != d0*perExpertBytes {- return nil, nil, nil, fmt.Errorf("raw byte length %d does not match shape %v and dtype %s", len(raw), shape, dtype)- }-- halfD1 := d1 / 2- halfExpertBytes := halfD1 * d2 * elemSize- gateRaw := make([]byte, d0*halfExpertBytes)- upRaw := make([]byte, d0*halfExpertBytes)- for e := range d0 {- src := e * perExpertBytes- dst := e * halfExpertBytes- copy(gateRaw[dst:dst+halfExpertBytes], raw[src:src+halfExpertBytes])- copy(upRaw[dst:dst+halfExpertBytes], raw[src+halfExpertBytes:src+perExpertBytes])- }-- return gateRaw, upRaw, []int32{shape[0], int32(halfD1), shape[2]}, nil+func qwen35IsLowRankProjection(name string) bool {+ return strings.HasSuffix(name, ".linear_attn.in_proj_a.weight") ||+ strings.HasSuffix(name, ".linear_attn.in_proj_b.weight") ||+ strings.HasSuffix(name, ".linear_attn.in_proj_ba.weight")}diff --git a/x/create/transform.go b/x/create/transform.gonew file mode 100644index 000000000..ceb761cc8--- /dev/null+++ b/x/create/transform.go@@ -0,0 +1,74 @@+package create++import (+ "bytes"+ "fmt"+ "io"++ "github.com/ollama/ollama/x/safetensors"+)++// applyByteTransform produces a TensorSpec's output tensor from its resolved+// source tensors using only byte-level (non-MLX) operations. The MLX transform+// (decode_fp8) and quantization are handled separately by the MLX writer path.+func applyByteTransform(ts TensorSpec, sources []*safetensors.TensorData) (*safetensors.TensorData, error) {+ switch ts.Transform {+ case TransformNone:+ if len(sources) != 1 {+ return nil, fmt.Errorf("transform none expects 1 source, got %d", len(sources))+ }+ return sources[0].WithName(ts.Name), nil++ case TransformRepackFP4, TransformRelabelU8:+ // Both relabel the header (dtype, and for the fp4 repack the last+ // dimension); the bytes are unchanged, so the reader is reused.+ if len(sources) != 1 {+ return nil, fmt.Errorf("transform %s expects 1 source, got %d", ts.Transform, len(sources))+ }+ td := sources[0].WithName(ts.Name)+ if ts.OutDtype != "" {+ td.Dtype = ts.OutDtype+ }+ if ts.OutShape != nil {+ td.Shape = append([]int32(nil), ts.OutShape...)+ }+ return td, nil++ case TransformScalarF32:+ if len(sources) != 1 {+ return nil, fmt.Errorf("transform scalar_f32 expects 1 source, got %d", len(sources))+ }+ return validateScalarFloat32TensorData(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)++ case TransformStackExperts:+ return stackExpertTensors(ts.Name, ts.OutDtype, ts.OutShape, sources)++ default:+ return nil, fmt.Errorf("transform %q requires the MLX writer path", ts.Transform)+ }+}++// stackExpertTensors concatenates per-expert tensors (in the given order) into+// one [experts, ...] tensor. Row-major layout means the stacked bytes are+// exactly the per-expert byte blocks back to back.+func stackExpertTensors(name, dtype string, shape []int32, sources []*safetensors.TensorData) (*safetensors.TensorData, error) {+ if len(sources) == 0 {+ return nil, fmt.Errorf("stack_experts expects at least one source")+ }+ var buf bytes.Buffer+ for i, s := range sources {+ if s.Dtype != sources[0].Dtype {+ return nil, fmt.Errorf("stack_experts source %d dtype %s != %s", i, s.Dtype, sources[0].Dtype)+ }+ if _, err := io.Copy(&buf, s.Reader()); err != nil {+ return nil, fmt.Errorf("stack_experts read source %d (%s): %w", i, s.Name, err)+ }+ }+ return safetensors.NewTensorDataFromBytes(name, dtype, append([]int32(nil), shape...), buf.Bytes()), nil+}diff --git a/x/create/writer.go b/x/create/writer.gonew file mode 100644index 000000000..bce27a34f--- /dev/null+++ b/x/create/writer.go@@ -0,0 +1,190 @@+package create++import (+ "bytes"+ "fmt"+ "io"+ "path/filepath"++ "github.com/ollama/ollama/x/safetensors"+)++const mediaTypeImageTensor = "application/vnd.ollama.image.tensor"++// BlobStore stores a finished blob and returns its layer info. The writer+// produces the blob bytes; where they are stored — the local model store, or a+// remote target in a future networked create — is the store's concern.+type BlobStore interface {+ WriteBlob(r io.Reader, mediaType, name string) (LayerInfo, error)+}++// WriteBlobs executes a plan's blobs: for each blob it resolves the tensors'+// sources, produces the blob bytes, and stores the result.+func WriteBlobs(specs []BlobSpec, modelDir string, store BlobStore) ([]LayerInfo, error) {+ src := newSourceFiles(modelDir)+ defer src.close()++ layers := make([]LayerInfo, 0, len(specs))+ for _, spec := range specs {+ layer, err := writeBlob(spec, src, store)+ if err != nil {+ return nil, err+ }+ layers = append(layers, layer)+ }+ return layers, nil+}++// writeBlob resolves each tensor's sources and produces the blob.+func writeBlob(spec BlobSpec, src *sourceFiles, store BlobStore) (LayerInfo, error) {+ needsMLX := blobNeedsMLX(spec)+ var (+ tensors []*safetensors.TensorData+ items []quantizeItem+ )+ for _, ts := range spec.Tensors {+ sources, err := src.resolve(ts.Sources)+ if err != nil {+ return LayerInfo{}, err+ }+ if needsMLX {+ reader, err := quantizeInputReader(ts, sources)+ if err != nil {+ return LayerInfo{}, fmt.Errorf("blob %s: tensor %s: %w", spec.Name, ts.Name, err)+ }+ items = append(items, quantizeItem{name: ts.Name, quantize: ts.Quantize, reader: reader, decodeFP8: needsFP8Decode(ts.Transform)})+ } else {+ td, err := applyByteTransform(ts, sources)+ if err != nil {+ return LayerInfo{}, fmt.Errorf("blob %s: tensor %s: %w", spec.Name, ts.Name, err)+ }+ tensors = append(tensors, td)+ }+ }++ // The quantizer computes the blob's quant metadata itself and ignores+ // spec.Metadata; today only prequant blobs carry Metadata and they never+ // take the MLX path.+ var r io.Reader+ if needsMLX {+ blobData, err := quantizeBlob(items)+ if err != nil {+ return LayerInfo{}, fmt.Errorf("quantize blob %s: %w", spec.Name, err)+ }+ r = bytes.NewReader(blobData)+ } else {+ r = safetensors.BuildPackedSafetensorsReaderWithMetadata(tensors, spec.Metadata)+ }++ layer, err := store.WriteBlob(r, mediaTypeImageTensor, spec.Name)+ if err != nil {+ return LayerInfo{}, fmt.Errorf("write blob %s: %w", spec.Name, err)+ }+ return layer, nil+}++// quantizeInputReader builds the safetensors-wrapped reader the quantizer+// consumes for one tensor: a paired weight+scale for FP8 decode, a byte-stacked+// 3D tensor for experts, or the tensor itself. The output tensor is always+// keyed by ts.Name so the quantizer can look it up by name.+func quantizeInputReader(ts TensorSpec, sources []*safetensors.TensorData) (io.Reader, error) {+ switch ts.Transform {+ case TransformNone:+ if len(sources) != 1 {+ return nil, fmt.Errorf("transform none expects 1 source, got %d", len(sources))+ }+ return sources[0].WithName(ts.Name).SafetensorsReader(), nil+ case TransformDecodeFP8:+ if len(sources) != 2 {+ return nil, fmt.Errorf("transform decode_fp8 expects weight+scale, got %d sources", len(sources))+ }+ return buildSourceFP8Reader(sources[0].WithName(ts.Name), sources[1]), nil+ case TransformDecodeStackFP8:+ if len(sources) == 0 || len(sources)%2 != 0 {+ return nil, fmt.Errorf("transform decode_stack_fp8 expects N weights followed by N scales, got %d sources", len(sources))+ }+ n := len(sources) / 2+ weights, scales := sources[:n], sources[n:]+ stackedWeight, err := stackExpertTensors(ts.Name, ts.OutDtype, ts.OutShape, weights)+ if err != nil {+ return nil, err+ }+ scaleShape := append([]int32{int32(n)}, scales[0].Shape...)+ stackedScale, err := stackExpertTensors(ts.Name+".scale_inv", scales[0].Dtype, scaleShape, scales)+ if err != nil {+ return nil, err+ }+ return safetensors.BuildPackedSafetensorsReader([]*safetensors.TensorData{stackedWeight, stackedScale}), nil+ case TransformStackExperts:+ stacked, err := stackExpertTensors(ts.Name, ts.OutDtype, ts.OutShape, sources)+ if err != nil {+ return nil, err+ }+ return stacked.SafetensorsReader(), nil+ default:+ return nil, fmt.Errorf("transform %q is not supported for a quantized tensor", ts.Transform)+ }+}++// needsFP8Decode reports whether a transform dequantizes block-FP8 weights on+// the MLX thread (a single tensor or a stacked per-expert group).+func needsFP8Decode(t Transform) bool {+ return t == TransformDecodeFP8 || t == TransformDecodeStackFP8+}++// blobNeedsMLX reports whether any of the blob's tensors require the MLX path+// — either a quantization target or an FP8 decode (which cannot be done with+// byte operations alone).+func blobNeedsMLX(spec BlobSpec) bool {+ for _, ts := range spec.Tensors {+ if ts.Quantize != "" || needsFP8Decode(ts.Transform) {+ return true+ }+ }+ return false+}++// sourceFiles opens and caches the source safetensors files so each shard is+// opened once across all the blobs that read from it.+type sourceFiles struct {+ dir string+ cache map[string]*safetensors.TensorExtractor+}++func newSourceFiles(dir string) *sourceFiles {+ return &sourceFiles{dir: dir, cache: make(map[string]*safetensors.TensorExtractor)}+}++func (s *sourceFiles) resolve(sources []SourceTensor) ([]*safetensors.TensorData, error) {+ out := make([]*safetensors.TensorData, len(sources))+ for i, st := range sources {+ ext, err := s.extractor(st.File)+ if err != nil {+ return nil, err+ }+ td, err := ext.GetTensor(st.Name)+ if err != nil {+ return nil, fmt.Errorf("read %s from %s: %w", st.Name, st.File, err)+ }+ out[i] = td+ }+ return out, nil+}++func (s *sourceFiles) extractor(file string) (*safetensors.TensorExtractor, error) {+ if ext, ok := s.cache[file]; ok {+ return ext, nil+ }+ ext, err := safetensors.OpenForExtraction(filepath.Join(s.dir, file))+ if err != nil {+ return nil, fmt.Errorf("open %s: %w", file, err)+ }+ s.cache[file] = ext+ return ext, nil+}++func (s *sourceFiles) close() {+ for _, ext := range s.cache {+ ext.Close()+ }+}diff --git a/x/create/writer_test.go b/x/create/writer_test.gonew file mode 100644index 000000000..1d9df0049--- /dev/null+++ b/x/create/writer_test.go@@ -0,0 +1,216 @@+package create++import (+ "encoding/binary"+ "encoding/json"+ "io"+ "math"+ "path/filepath"+ "slices"+ "sort"+ "testing"++ st "github.com/ollama/ollama/x/safetensors"+)++type captureStore struct{ blobs map[string][]byte }++func newCaptureStore() *captureStore { return &captureStore{blobs: make(map[string][]byte)} }++func (c *captureStore) WriteBlob(r io.Reader, mediaType, name string) (LayerInfo, error) {+ data, err := io.ReadAll(r)+ if err != nil {+ return LayerInfo{}, err+ }+ c.blobs[name] = data+ return LayerInfo{Name: name, MediaType: mediaType, Digest: "sha256:" + name, Size: int64(len(data))}, nil+}++func (c *captureStore) names() []string {+ out := make([]string, 0, len(c.blobs))+ for k := range c.blobs {+ out = append(out, k)+ }+ sort.Strings(out)+ return out+}++type headerEntry struct {+ Dtype string `json:"dtype"`+ Shape []int32 `json:"shape"`+}++func blobHeader(t *testing.T, data []byte) map[string]headerEntry {+ t.Helper()+ if len(data) < 8 {+ t.Fatalf("blob too small: %d bytes", len(data))+ }+ n := binary.LittleEndian.Uint64(data[:8])+ var raw map[string]json.RawMessage+ if err := json.Unmarshal(data[8:8+n], &raw); err != nil {+ t.Fatalf("parse header: %v", err)+ }+ out := make(map[string]headerEntry)+ for k, v := range raw {+ if k == "__metadata__" {+ continue+ }+ var e headerEntry+ if err := json.Unmarshal(v, &e); err != nil {+ t.Fatalf("parse header entry %q: %v", k, err)+ }+ out[k] = e+ }+ return out+}++func f32le(v float32) []byte {+ b := make([]byte, 4)+ binary.LittleEndian.PutUint32(b, math.Float32bits(v))+ return b+}++func TestWriteBlobsCompressedNVFP4(t *testing.T) {+ dir := t.TempDir()+ writeConfigJSON(t, dir, `{"architectures":["TestModel"],"compression_config":{"format":"nvfp4-pack-quantized"}}`)+ createTestSafetensors(t, filepath.Join(dir, "model.safetensors"), []*st.TensorData{+ 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("norm.weight", "BF16", []int32{16}, make([]byte, 32)),+ })++ 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(specs, dir, store); err != nil {+ t.Fatalf("WriteBlobs() error = %v", err)+ }++ fused, ok := store.blobs["linear.weight"]+ if !ok {+ t.Fatalf("missing fused blob; got %v", store.names())+ }+ hdr := blobHeader(t, fused)++ if w := hdr["linear.weight"]; w.Dtype != "U32" || !slices.Equal(w.Shape, []int32{16, 2}) {+ t.Errorf("fused weight = %+v, want U32 [16 2] (repacked)", w)+ }+ if s := hdr["linear.weight.scale"]; s.Dtype != "U8" {+ t.Errorf("fused scale dtype = %q, want U8 (relabeled from F8_E4M3)", s.Dtype)+ }+ if g, ok := hdr["linear.weight.global_scale"]; !ok || g.Dtype != "F32" {+ t.Errorf("fused global_scale = %+v ok=%v, want F32", g, ok)+ }+ // compressed-tensors stores the global scale inverted.+ gs := readPackedTensorRaw(t, fused, "linear.weight.global_scale")+ if got := math.Float32frombits(binary.LittleEndian.Uint32(gs)); got != 0.25 {+ t.Errorf("global_scale = %v, want 0.25 (reciprocal of 4.0)", got)+ }++ // the scale companion is folded in, not its own blob.+ if _, leaked := store.blobs["linear.weight_scale"]; leaked {+ t.Error("scale companion leaked as its own blob")+ }++ // the norm passes through unchanged as its own blob.+ norm, ok := store.blobs["norm.weight"]+ if !ok {+ t.Fatalf("missing norm blob; got %v", store.names())+ }+ if nh := blobHeader(t, norm)["norm.weight"]; nh.Dtype != "BF16" || !slices.Equal(nh.Shape, []int32{16}) {+ t.Errorf("norm = %+v, want BF16 [16]", nh)+ }+}++func TestWriteBlobsQuantizeFloat(t *testing.T) {+ if !QuantizeSupported() {+ t.Skip("MLX unavailable")+ }+ dir := t.TempDir()+ writeConfigJSON(t, dir, `{"architectures":["TestModel"]}`)+ createTestSafetensors(t, filepath.Join(dir, "model.safetensors"), []*st.TensorData{+ st.NewTensorDataFromBytes("model.layers.0.self_attn.q_proj.weight", "BF16", []int32{128, 128}, make([]byte, 128*128*2)),+ st.NewTensorDataFromBytes("model.norm.weight", "BF16", []int32{128}, make([]byte, 128*2)),+ })++ inv, err := ReadInventory(dir)+ if err != nil {+ t.Fatalf("ReadInventory() error = %v", err)+ }+ specs, err := Plan(inv, Classification{Kind: SourceFloat, Quantize: "int4"}, defaultQuantPolicy{})+ if err != nil {+ t.Fatalf("Plan() error = %v", err)+ }+ store := newCaptureStore()+ if _, err := WriteBlobs(specs, dir, store); err != nil {+ t.Fatalf("WriteBlobs() error = %v", err)+ }++ q, ok := store.blobs["model.layers.0.self_attn.q_proj.weight"]+ if !ok {+ t.Fatalf("missing q_proj blob; got %v", store.names())+ }+ hdr := blobHeader(t, q)+ if w := hdr["model.layers.0.self_attn.q_proj.weight"]; w.Dtype != "U32" {+ t.Errorf("quantized weight dtype = %q, want U32 (packed int4)", w.Dtype)+ }+ if _, ok := hdr["model.layers.0.self_attn.q_proj.weight.scale"]; !ok {+ t.Error("quantized blob missing scale")+ }++ norm, ok := store.blobs["model.norm.weight"]+ if !ok {+ t.Fatalf("missing norm blob; got %v", store.names())+ }+ if nh := blobHeader(t, norm)["model.norm.weight"]; nh.Dtype != "BF16" {+ t.Errorf("norm dtype = %q, want BF16 (kept, not quantized)", nh.Dtype)+ }+}++func TestWriteBlobsBlockFP8Decode(t *testing.T) {+ if !QuantizeSupported() {+ t.Skip("MLX unavailable")+ }+ dir := t.TempDir()+ writeConfigJSON(t, dir, `{"architectures":["TestModel"]}`)+ createTestSafetensors(t, filepath.Join(dir, "model.safetensors"), []*st.TensorData{+ st.NewTensorDataFromBytes("model.layers.0.mlp.down_proj.weight", "F8_E4M3", []int32{128, 128}, make([]byte, 128*128)),+ st.NewTensorDataFromBytes("model.layers.0.mlp.down_proj.weight_scale_inv", "F32", []int32{1, 1}, f32le(1.0)),+ })++ inv, err := ReadInventory(dir)+ if err != nil {+ t.Fatalf("ReadInventory() error = %v", err)+ }+ specs, err := Plan(inv, Classification{Kind: SourceBlockFP8, Quantize: "mxfp8"}, defaultQuantPolicy{})+ if err != nil {+ t.Fatalf("Plan() error = %v", err)+ }+ store := newCaptureStore()+ if _, err := WriteBlobs(specs, dir, store); err != nil {+ t.Fatalf("WriteBlobs() error = %v", err)+ }++ b, ok := store.blobs["model.layers.0.mlp.down_proj.weight"]+ if !ok {+ t.Fatalf("missing decoded blob; got %v", store.names())+ }+ hdr := blobHeader(t, b)+ if w := hdr["model.layers.0.mlp.down_proj.weight"]; w.Dtype != "U32" {+ t.Errorf("decoded+quantized weight dtype = %q, want U32 (packed mxfp8)", w.Dtype)+ }+ if _, ok := hdr["model.layers.0.mlp.down_proj.weight.scale"]; !ok {+ t.Error("mxfp8 blob missing scale")+ }+ if _, leaked := store.blobs["model.layers.0.mlp.down_proj.weight_scale_inv"]; leaked {+ t.Error("fp8 scale companion leaked as its own blob")+ }+}diff --git a/x/mlxrunner/model/quant.go b/x/mlxrunner/model/quant.goindex fa6eae1b0..c027424a4 100644--- a/x/mlxrunner/model/quant.go+++ b/x/mlxrunner/model/quant.go@@ -1,29 +1,15 @@package modelimport (- "strings"-"github.com/ollama/ollama/x/mlxrunner/mlx"+ "github.com/ollama/ollama/x/quant")-// QuantizationParams returns default groupSize, bits, and mode for a quantization type.+// QuantizationParams returns default groupSize, bits, and mode for a+// quantization type. The values live in the shared x/quant package so the+// importer, the runtime loader, and `ollama show` agree on them.func QuantizationParams(quantization string) (groupSize, bits int, mode string) {- switch strings.ToUpper(quantization) {- case "NVFP4":- return 16, 4, "nvfp4"- case "MXFP4":- return 32, 4, "mxfp4"- case "FP4", "Q4", "INT4":- return 64, 4, "affine"- case "MXFP8":- return 32, 8, "mxfp8"- case "FP8", "Q8", "INT8":- return 64, 8, "affine"- case "":- return 0, 0, ""- default:- return 32, 8, "affine"- }+ return quant.Params(quantization)}// TensorQuantParams resolves quant params for a tensor using per-tensor metadatadiff --git a/x/models/cohere2_moe/cohere2_moe.go b/x/models/cohere2_moe/cohere2_moe.goindex 5b14b13b5..5565f9b1f 100644--- a/x/models/cohere2_moe/cohere2_moe.go+++ b/x/models/cohere2_moe/cohere2_moe.go@@ -446,6 +446,16 @@ func loadStackedProjection(tensors map[string]*mlx.Array, cfg *Config, useQuanti}}+// loadStackedExperts resolves a stacked expert projection by its close-to-source+// name (layers.N.mlp.experts.<proj>, which `ollama create` now writes) and falls+// back to the legacy switch_mlp name that older imports produced.+func loadStackedExperts(tensors map[string]*mlx.Array, cfg *Config, useQuantized bool, layerPrefix, proj string) *stackedExpertWeights {+ if w := loadStackedProjection(tensors, cfg, useQuantized, layerPrefix+".mlp.experts."+proj); w != nil {+ return w+ }+ return loadStackedProjection(tensors, cfg, useQuantized, layerPrefix+".mlp.switch_mlp."+proj)+}+// LoadWeights assigns tensors to model fields.func (m *Model) LoadWeights(tensors map[string]*mlx.Array) error {cfg := m.Config@@ -527,11 +537,11 @@ func (m *Model) LoadWeights(tensors map[string]*mlx.Array) error {return fmt.Errorf("layer %d: missing moe router gate", i)}- gateW := loadStackedProjection(tensors, cfg, useQuantizedExperts, layerPrefix+".mlp.switch_mlp.gate_proj")- upW := loadStackedProjection(tensors, cfg, useQuantizedExperts, layerPrefix+".mlp.switch_mlp.up_proj")- downW := loadStackedProjection(tensors, cfg, useQuantizedExperts, layerPrefix+".mlp.switch_mlp.down_proj")+ gateW := loadStackedExperts(tensors, cfg, useQuantizedExperts, layerPrefix, "gate_proj")+ upW := loadStackedExperts(tensors, cfg, useQuantizedExperts, layerPrefix, "up_proj")+ downW := loadStackedExperts(tensors, cfg, useQuantizedExperts, layerPrefix, "down_proj")if gateW == nil || upW == nil || downW == nil {- return fmt.Errorf("layer %d: missing stacked switch_mlp expert weights (import the model with `ollama create`)", i)+ return fmt.Errorf("layer %d: missing stacked expert weights (import the model with `ollama create`)", i)}switchMLP := &SwitchMLP{}diff --git a/x/models/gemma4/gemma4.go b/x/models/gemma4/gemma4.goindex ff77864d0..515c4a5d7 100644--- a/x/models/gemma4/gemma4.go+++ b/x/models/gemma4/gemma4.go@@ -5,6 +5,7 @@ import ("encoding/json""fmt""math"+ "strings""github.com/ollama/ollama/x/mlxrunner/batch""github.com/ollama/ollama/x/mlxrunner/cache"@@ -154,6 +155,17 @@ func firstNonNil(tensors map[string]*mlx.Array, keys ...string) *mlx.Array {return nil}+// firstTensorKey returns the first key present in tensors along with its+// tensor, or "", nil if none of the keys are present.+func firstTensorKey(tensors map[string]*mlx.Array, keys ...string) (string, *mlx.Array) {+ for _, k := range keys {+ if t := tensors[k]; t != nil {+ return k, t+ }+ }+ return "", nil+}+// sliceAxis1 slices a tensor along axis 1: a[:, start:stop, ...].func sliceAxis1(a *mlx.Array, start, stop int32) *mlx.Array {dims := a.Dims()@@ -243,44 +255,36 @@ func collectExpertProjection(tensors map[string]*mlx.Array, cfg *TextConfig, prereturn out}-// loadFusedExperts populates moe with a stacked-3D fused gate_up + down expert-// pair, choosing the quantized GatherQMM path when scale sidecars are present-// and the dense GatherMM path otherwise. gateUpW/downW are the stacked tensors-// and gateUpKey/downKey are their map keys, used to locate the _scale/_qbias-// sidecars and per-tensor quant metadata. Shared by the .experts./.moe.-// pre-stacked names and the .moe.switch_mlp. names so all fused layouts load-// identically.-func loadFusedExperts(tensors map[string]*mlx.Array, cfg *TextConfig, moe *MoEBlock, gateUpW *mlx.Array, gateUpKey string, downW *mlx.Array, downKey string) {+// loadFusedExperts configures an MoE block from a fused, pre-stacked gate_up+// projection and its down projection. It keeps the fused gate_up as a single+// tensor and chooses GatherQMM (one quantized call) when scale companions are+// present, or GatherMM otherwise. It is name-agnostic: callers resolve the+// tensor keys, which may or may not carry a ".weight" suffix.+func (m *Model) loadFusedExperts(moe *MoEBlock, tensors map[string]*mlx.Array, gateUpKey string, gateUp *mlx.Array, downKey string, down *mlx.Array) {moe.UseFusedGateUp = truegateUpScales := firstNonNil(tensors, gateUpKey+"_scale", gateUpKey+".scale")downScales := firstNonNil(tensors, downKey+"_scale", downKey+".scale")if gateUpScales == nil || downScales == nil {- // Unquantized: keep fused and transpose for GatherMM ([experts, in, out]).- moe.GateUpWeight = transposeForGatherMM(gateUpW)- moe.DownWeight = transposeForGatherMM(downW)+ // Dense: keep gate_up fused and transpose for GatherMM.+ moe.GateUpWeight = transposeForGatherMM(gateUp)+ moe.DownWeight = transposeForGatherMM(down)return}- // Quantized (affine/nvfp4/mxfp8): keep fused as a single tensor for one- // GatherQMM call instead of two. No transpose. nvfp4/mxfp8 carry no qbias,- // and this path does not apply nvfp4's optional double-scale global_scale.+ // Quantized: keep the fused gate_up packed for a single GatherQMM call.moe.UseQuantized = true- moe.GateUpWeightQ = gateUpW+ moe.GateUpWeightQ = gateUpmoe.GateUpScales = gateUpScalesmoe.GateUpBiases = firstNonNil(tensors, gateUpKey+"_qbias", gateUpKey+".bias")- moe.DownWeightQ = downW+ moe.DownWeightQ = downmoe.DownScales = downScalesmoe.DownBiases = firstNonNil(tensors, downKey+"_qbias", downKey+".bias")moe.GateUpGroupSize, moe.GateUpBits, moe.QuantMode = model.ResolveLinearQuantParams(- cfg.QuantGroupSize, cfg.QuantBits, cfg.QuantMode,- cfg.TensorQuant, gateUpKey, gateUpW, gateUpScales,- )+ m.QuantGroupSize, m.QuantBits, m.QuantMode, m.TensorQuant, gateUpKey, gateUp, gateUpScales)moe.DownGroupSize, moe.DownBits, moe.DownQuantMode = model.ResolveLinearQuantParams(- cfg.QuantGroupSize, cfg.QuantBits, cfg.QuantMode,- cfg.TensorQuant, downKey, downW, downScales,- )+ m.QuantGroupSize, m.QuantBits, m.QuantMode, m.TensorQuant, downKey, down, downScales)}// Router implements Gemma 4's expert routing mechanism.@@ -801,70 +805,34 @@ func (m *Model) LoadWeights(tensors map[string]*mlx.Array) error {moe := &MoEBlock{PerExpertScale: perExpertScale}- // Check for pre-stacked tensors (BF16 or quantized HF format).- // Try .experts. first (new weight drop), fall back to .moe. (old- // format). Track the matched key so loadFusedExperts can find the- // quant sidecars.- gateUpKey := layerPrefix + ".experts.gate_up_proj"- gateUpW := tensors[gateUpKey]- if gateUpW == nil {- gateUpKey = layerPrefix + ".moe.gate_up_proj"- gateUpW = tensors[gateUpKey]- }- gateW := tensors[layerPrefix+".experts.gate_proj"]- if gateW == nil {- gateW = tensors[layerPrefix+".moe.gate_proj"]- }- if gateUpW != nil {- // Fused gate+up (dense or quantized): split happens at matmul time.- downKey := layerPrefix + ".experts.down_proj"- downW := tensors[downKey]- if downW == nil {- downKey = layerPrefix + ".moe.down_proj"- downW = tensors[downKey]- }- if downW == nil {- return fmt.Errorf("layer %d: missing MoE down_proj with fused gate_up_proj", i)+ // Experts ship with gate+up fused into one pre-stacked tensor under+ // a few different names: HF (.experts./.moe.) and the create+ // pipeline (.moe.switch_mlp.), each with or without a ".weight"+ // suffix. Resolve the gate_up projection once, then let+ // loadFusedExperts decide quantized vs dense from its scales.+ if gateUpKey, gateUp := firstTensorKey(tensors,+ layerPrefix+".experts.gate_up_proj.weight", layerPrefix+".experts.gate_up_proj",+ layerPrefix+".moe.gate_up_proj.weight", layerPrefix+".moe.gate_up_proj",+ layerPrefix+".moe.switch_mlp.gate_up_proj.weight", layerPrefix+".moe.switch_mlp.gate_up_proj",+ ); gateUp != nil {+ downKey := strings.Replace(gateUpKey, "gate_up_proj", "down_proj", 1)+ down := tensors[downKey]+ if down == nil {+ return fmt.Errorf("layer %d: missing MoE down_proj for fused gate_up_proj %q", i, gateUpKey)}- loadFusedExperts(tensors, m.TextConfig, moe, gateUpW, gateUpKey, downW, downKey)- } else if gateW != nil {- // Separate gate_proj and up_proj (older format). Transpose for GatherMM.+ m.loadFusedExperts(moe, tensors, gateUpKey, gateUp, downKey, down)+ } else if gateW := firstNonNil(tensors,+ layerPrefix+".experts.gate_proj", layerPrefix+".moe.gate_proj"); gateW != nil {+ // Separate (non-fused) pre-stacked gate/up projections (older HF+ // layout, dense only). Transpose for GatherMM.moe.GateWeight = transposeForGatherMM(gateW)- upW := tensors[layerPrefix+".experts.up_proj"]- if upW == nil {- upW = tensors[layerPrefix+".moe.up_proj"]- }- downW := tensors[layerPrefix+".experts.down_proj"]- if downW == nil {- downW = tensors[layerPrefix+".moe.down_proj"]- }- moe.UpWeight = transposeForGatherMM(upW)- moe.DownWeight = transposeForGatherMM(downW)+ moe.UpWeight = transposeForGatherMM(firstNonNil(tensors,+ layerPrefix+".experts.up_proj", layerPrefix+".moe.up_proj"))+ moe.DownWeight = transposeForGatherMM(firstNonNil(tensors,+ layerPrefix+".experts.down_proj", layerPrefix+".moe.down_proj"))if moe.UpWeight == nil || moe.DownWeight == nil {return fmt.Errorf("layer %d: incomplete pre-stacked MoE weights", i)}- } else if switchGateUp := firstNonNil(tensors,- layerPrefix+".moe.switch_mlp.gate_up_proj.weight",- layerPrefix+".moe.switch_mlp.gate_up_proj"); switchGateUp != nil {- // Stacked switch_mlp format (from create pipeline with expert packing).- switchDown := firstNonNil(tensors,- layerPrefix+".moe.switch_mlp.down_proj.weight",- layerPrefix+".moe.switch_mlp.down_proj")- if switchDown == nil {- return fmt.Errorf("layer %d: missing switch_mlp down_proj", i)- }-- // Resolve base keys: the scale/bias suffix attaches to whichever- // of .weight / bare matched the weight tensor.- gateUpKey := layerPrefix + ".moe.switch_mlp.gate_up_proj.weight"- if tensors[gateUpKey] == nil {- gateUpKey = layerPrefix + ".moe.switch_mlp.gate_up_proj"- }- downKey := layerPrefix + ".moe.switch_mlp.down_proj.weight"- if tensors[downKey] == nil {- downKey = layerPrefix + ".moe.switch_mlp.down_proj"- }- loadFusedExperts(tensors, m.TextConfig, moe, switchGateUp, gateUpKey, switchDown, downKey)} else {// Per-expert tensors (from create path).// Try separate gate_proj/up_proj first, then fused gate_up_proj.diff --git a/x/models/gemma4/gemma4_moe_test.go b/x/models/gemma4/gemma4_moe_test.goindex e7ea5cc28..4fae76067 100644--- a/x/models/gemma4/gemma4_moe_test.go+++ b/x/models/gemma4/gemma4_moe_test.go@@ -141,6 +141,88 @@ func TestMoEBlockSortedForward(t *testing.T) {}}+// TestLoadFusedExpertsQuantized verifies that a quantized, fused gate_up+// projection is loaded onto the GatherQMM path under every name the experts+// ship as — including gemma's bare ".experts." name, which previously fell+// through to the dense branch and was loaded unquantized (the memory bloat+// bug this fix addresses).+func TestLoadFusedExpertsQuantized(t *testing.T) {+ skipIfNoMLX(t)++ const E, I, H = 4, 8, 16+ m := &Model{TextConfig: &TextConfig{QuantGroupSize: 16, QuantBits: 4, QuantMode: "nvfp4"}}++ for _, prefix := range []string{+ "model.language_model.layers.0.experts", // gemma HF (bare .experts.)+ "model.language_model.layers.0.moe.switch_mlp", // create pipeline+ } {+ t.Run(prefix, func(t *testing.T) {+ gateUpKey := prefix + ".gate_up_proj"+ downKey := prefix + ".down_proj"+ tensors := map[string]*mlx.Array{+ gateUpKey: onesLike(E, 2*I, H),+ gateUpKey + "_scale": onesLike(E, 2*I, H/16),+ gateUpKey + "_qbias": onesLike(E, 2*I, H/16),+ downKey: onesLike(E, H, I),+ downKey + "_scale": onesLike(E, H, I/16),+ downKey + "_qbias": onesLike(E, H, I/16),+ }++ moe := &MoEBlock{}+ m.loadFusedExperts(moe, tensors, gateUpKey, tensors[gateUpKey], downKey, tensors[downKey])++ if !moe.UseQuantized {+ t.Error("UseQuantized = false, want true")+ }+ if !moe.UseFusedGateUp {+ t.Error("UseFusedGateUp = false, want true")+ }+ if moe.GateUpWeightQ == nil || moe.GateUpScales == nil || moe.GateUpBiases == nil {+ t.Error("quantized gate_up weight/scale/bias not all set")+ }+ if moe.DownWeightQ == nil || moe.DownScales == nil || moe.DownBiases == nil {+ t.Error("quantized down weight/scale/bias not all set")+ }+ // Dense fields must stay nil so Forward takes the GatherQMM path.+ if moe.GateUpWeight != nil || moe.DownWeight != nil {+ t.Error("dense weights set on a quantized block")+ }+ })+ }+}++// TestLoadFusedExpertsDense verifies that a fused gate_up projection with no+// scale companions is loaded onto the dense GatherMM path, kept fused.+func TestLoadFusedExpertsDense(t *testing.T) {+ skipIfNoMLX(t)++ const E, I, H = 4, 8, 16+ m := &Model{TextConfig: &TextConfig{}}++ gateUpKey := "model.language_model.layers.0.experts.gate_up_proj"+ downKey := "model.language_model.layers.0.experts.down_proj"+ tensors := map[string]*mlx.Array{+ gateUpKey: onesLike(E, 2*I, H),+ downKey: onesLike(E, I, H),+ }++ moe := &MoEBlock{}+ m.loadFusedExperts(moe, tensors, gateUpKey, tensors[gateUpKey], downKey, tensors[downKey])++ if moe.UseQuantized {+ t.Error("UseQuantized = true, want false (no scales present)")+ }+ if !moe.UseFusedGateUp {+ t.Error("UseFusedGateUp = false, want true")+ }+ if moe.GateUpWeight == nil || moe.DownWeight == nil {+ t.Error("dense fused weights not set")+ }+ if moe.GateUpWeightQ != nil || moe.DownWeightQ != nil {+ t.Error("quantized weights set on a dense block")+ }+}+// TestRouterForwardMatchesLegacy verifies the optimized Router.Forward —// which takes the top-k of the raw logits and softmaxes only the selected// values — produces the same indices and (within tolerance) the samediff --git a/x/models/glm4_moe_lite/glm4_moe_lite.go b/x/models/glm4_moe_lite/glm4_moe_lite.goindex 76494185a..65f84e439 100644--- a/x/models/glm4_moe_lite/glm4_moe_lite.go+++ b/x/models/glm4_moe_lite/glm4_moe_lite.go@@ -418,6 +418,41 @@ type StackedExpertWeights struct {GroupSize int}+// loadStackedProjection loads an expert projection stored as a single stacked+// 3D tensor, or nil if base isn't present.+func loadStackedProjection(tensors map[string]*mlx.Array, base string, useQuantized bool, cfg *Config) *StackedExpertWeights {+ key := base + ".weight"+ w := tensors[key]+ if w == nil {+ return nil+ }++ scales := tensors[key+"_scale"]+ if scales == nil {+ return &StackedExpertWeights{Weight: w}+ }++ qbiases := tensors[key+"_qbias"]+ groupSize, bits, mode := model.ResolveLinearQuantParams(+ cfg.QuantGroupSize, cfg.QuantBits, cfg.QuantMode, cfg.TensorQuant,+ key, w, scales,+ )+ if useQuantized && supportsGatherQMM(mode, bits) {+ return &StackedExpertWeights{Weight: w, Scales: scales, Biases: qbiases, Bits: bits, GroupSize: groupSize}+ }++ return &StackedExpertWeights{Weight: mlx.Dequantize(w, scales, qbiases, groupSize, bits, mode)}+}++// loadStackedExperts loads a stacked expert projection by its .experts name,+// falling back to the switch_mlp name older imports use.+func loadStackedExperts(tensors map[string]*mlx.Array, prefix, projName string, useQuantized bool, cfg *Config) *StackedExpertWeights {+ if w := loadStackedProjection(tensors, prefix+".mlp.experts."+projName, useQuantized, cfg); w != nil {+ return w+ }+ return loadStackedProjection(tensors, prefix+".mlp.switch_mlp."+projName, useQuantized, cfg)+}+// collectAndStackExpertWeights loads and stacks expert weights for one projection type.func collectAndStackExpertWeights(tensors map[string]*mlx.Array,@@ -462,8 +497,15 @@ func collectAndStackExpertWeights(return result}-// sanitizeExpertWeights stacks individual expert weights into tensors.+// sanitizeExpertWeights resolves the three MoE projections, preferring the+// stacked on-disk layout and falling back to per-expert tensors.func sanitizeExpertWeights(tensors map[string]*mlx.Array, prefix string, numExperts int32, useQuantized bool, cfg *Config) (gate, up, down *StackedExpertWeights) {+ gate = loadStackedExperts(tensors, prefix, "gate_proj", useQuantized, cfg)+ up = loadStackedExperts(tensors, prefix, "up_proj", useQuantized, cfg)+ down = loadStackedExperts(tensors, prefix, "down_proj", useQuantized, cfg)+ if gate != nil && up != nil && down != nil {+ return gate, up, down+ }gate = collectAndStackExpertWeights(tensors, prefix, "gate_proj", numExperts, useQuantized, cfg)up = collectAndStackExpertWeights(tensors, prefix, "up_proj", numExperts, useQuantized, cfg)down = collectAndStackExpertWeights(tensors, prefix, "down_proj", numExperts, useQuantized, cfg)diff --git a/x/quant/quant.go b/x/quant/quant.gonew file mode 100644index 000000000..5564b2a04--- /dev/null+++ b/x/quant/quant.go@@ -0,0 +1,79 @@+// Package quant holds the quantization format facts shared by the model+// importer, the runtime loader, and `ollama show`. It deliberately has no+// dependency on the MLX C library, so any package can use it without pulling+// in cgo — which is what keeps these facts from drifting between separate+// hand-maintained copies.+package quant++import "strings"++type params struct {+ groupSize int+ bits int+ mode string+}++// byType maps each canonical quantization type to its parameters. Aliases are+// resolved to a canonical name by Canonical before lookup.+var byType = map[string]params{+ "nvfp4": {groupSize: 16, bits: 4, mode: "nvfp4"},+ "mxfp4": {groupSize: 32, bits: 4, mode: "mxfp4"},+ "int4": {groupSize: 64, bits: 4, mode: "affine"},+ "mxfp8": {groupSize: 32, bits: 8, mode: "mxfp8"},+ "int8": {groupSize: 64, bits: 8, mode: "affine"},+}++// Canonical returns the canonical name for a quantization type, resolving+// aliases (for example "FP8" and "Q8" both map to "int8"). It returns "" for+// the empty string and for any type it does not recognize.+func Canonical(quantType string) string {+ switch strings.ToUpper(strings.TrimSpace(quantType)) {+ case "NVFP4":+ return "nvfp4"+ case "MXFP4":+ return "mxfp4"+ case "MXFP8":+ return "mxfp8"+ case "INT4", "FP4", "Q4":+ return "int4"+ case "INT8", "FP8", "Q8":+ return "int8"+ default:+ return ""+ }+}++// Params returns the default group size, bit width, and mode for a+// quantization type. The empty string returns zeros. An unrecognized+// non-empty type falls back to 8-bit affine, matching the runtime loader's+// historical leniency toward unexpected metadata.+func Params(quantType string) (groupSize, bits int, mode string) {+ if strings.TrimSpace(quantType) == "" {+ return 0, 0, ""+ }+ if p, ok := byType[Canonical(quantType)]; ok {+ return p.groupSize, p.bits, p.mode+ }+ return 32, 8, "affine"+}++// Bits returns the bit width of a recognized quantization type, or 0 if the+// type is empty or unrecognized. Unlike Params it applies no fallback, so+// callers that size or display tensors never act on an unknown type.+func Bits(quantType string) int {+ if p, ok := byType[Canonical(quantType)]; ok {+ return p.bits+ }+ return 0+}++// PackFactor returns how many quantized values are packed into one 32-bit+// word, or 0 for an empty or unrecognized type. MLX stores quantized weights+// packed into U32 words, so a tensor's logical last dimension is its stored+// last dimension times this factor.+func PackFactor(quantType string) int {+ if b := Bits(quantType); b > 0 {+ return 32 / b+ }+ return 0+}diff --git a/x/quant/quant_test.go b/x/quant/quant_test.gonew file mode 100644index 000000000..81a9d3e74--- /dev/null+++ b/x/quant/quant_test.go@@ -0,0 +1,58 @@+package quant++import "testing"++func TestParams(t *testing.T) {+ tests := []struct {+ in string+ groupSize int+ bits int+ mode string+ }{+ {"nvfp4", 16, 4, "nvfp4"},+ {"NVFP4", 16, 4, "nvfp4"},+ {"mxfp4", 32, 4, "mxfp4"},+ {"mxfp8", 32, 8, "mxfp8"},+ {"int4", 64, 4, "affine"},+ {"int8", 64, 8, "affine"},+ {"fp4", 64, 4, "affine"},+ {"q4", 64, 4, "affine"},+ {"fp8", 64, 8, "affine"},+ {"q8", 64, 8, "affine"},+ {"", 0, 0, ""},+ // Unknown non-empty types fall back to 8-bit affine, matching the+ // runtime loader's historical behavior.+ {"something-else", 32, 8, "affine"},+ }+ for _, tt := range tests {+ gs, bits, mode := Params(tt.in)+ if gs != tt.groupSize || bits != tt.bits || mode != tt.mode {+ t.Errorf("Params(%q) = (%d, %d, %q), want (%d, %d, %q)", tt.in, gs, bits, mode, tt.groupSize, tt.bits, tt.mode)+ }+ }+}++func TestBitsAndPackFactor(t *testing.T) {+ tests := []struct {+ in string+ bits int+ packFactor int+ }{+ {"int4", 4, 8},+ {"nvfp4", 4, 8},+ {"mxfp4", 4, 8}, // regression: mxfp4 was missing from the old show.go switch+ {"int8", 8, 4},+ {"mxfp8", 8, 4},+ {"FP8", 8, 4},+ {"", 0, 0},+ {"unknown", 0, 0}, // strict: no fallback for sizing/display+ }+ for _, tt := range tests {+ if got := Bits(tt.in); got != tt.bits {+ t.Errorf("Bits(%q) = %d, want %d", tt.in, got, tt.bits)+ }+ if got := PackFactor(tt.in); got != tt.packFactor {+ t.Errorf("PackFactor(%q) = %d, want %d", tt.in, got, tt.packFactor)+ }+ }+}diff --git a/x/server/show.go b/x/server/show.goindex a8781b37b..f1985e3f2 100644--- a/x/server/show.go+++ b/x/server/show.go@@ -13,6 +13,7 @@ import ("github.com/ollama/ollama/api""github.com/ollama/ollama/manifest""github.com/ollama/ollama/types/model"+ "github.com/ollama/ollama/x/quant")func canonicalQuantType(quantType string) string {@@ -267,13 +268,10 @@ func getTensorInfoFromManifest(mf *manifest.Manifest) ([]api.Tensor, error) {shape[i] = uint64(s)}- var packFactor int64- switch strings.ToLower(info.QuantType) {- case "int4", "nvfp4":- packFactor = 8- case "int8", "mxfp8":- packFactor = 4- }+ // Quantized weights are packed into U32 words; report the+ // logical unpacked shape. PackFactor covers every quant type+ // the engine produces (including mxfp4) from one table.+ packFactor := int64(quant.PackFactor(info.QuantType))if packFactor > 0 && len(shape) >= 2 {shape[len(shape)-1] = uint64(info.Shape[len(info.Shape)-1] * packFactor)}@@ -363,14 +361,7 @@ func GetSafetensorsDtype(name model.Name) (string, error) {}func quantTypePrecision(quantType string) int {- switch canonicalQuantType(quantType) {- case "int4", "nvfp4", "mxfp4":- return 4- case "int8", "mxfp8":- return 8- default:- return 0- }+ return quant.Bits(quantType)}// safetensorsTensorInfo holds metadata about a tensor from a safetensors header