Skip to content

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

qwen3_5: image input support

Jesse Gross1e85fe8e9a1e
diff --git a/x/mlxrunner/mlx/ops_extra.go b/x/mlxrunner/mlx/ops_extra.go
index 31170ea06..b37322023 100644
--- a/x/mlxrunner/mlx/ops_extra.go
+++ b/x/mlxrunner/mlx/ops_extra.go
@@ -461,6 +461,12 @@ func Sigmoid(a *Array) *Array {
return a.Sigmoid()
}
+func Erf(a *Array) *Array {
+ out := New("ERF")
+ C.mlx_erf(&out.ctx, a.ctx, DefaultStream().ctx)
+ return out
+}
+
func Exp(a *Array) *Array {
out := New("EXP")
C.mlx_exp(&out.ctx, a.ctx, DefaultStream().ctx)
diff --git a/x/models/qwen3_5/process_image.go b/x/models/qwen3_5/process_image.go
new file mode 100644
index 000000000..2796441f8
--- /dev/null
+++ b/x/models/qwen3_5/process_image.go
@@ -0,0 +1,183 @@
+package qwen3_5
+
+import (
+ "bytes"
+ "fmt"
+ "image"
+ "math"
+
+ "golang.org/x/image/draw"
+)
+
+// Processor bounds from the family's preprocessor config: total pixels are
+// clamped to [shortest_edge, longest_edge] with both sides rounded to
+// multiples of patch_size * spatial_merge_size.
+const (
+ visionMinPixels = 65536
+ visionMaxPixels = 16777216
+)
+
+// preparedImage is the model-private state for one image: the pre-merge
+// patch grid and the CPU-computed lookups the encoder consumes, all in the
+// block-major merge order the pixel rows use.
+type preparedImage struct {
+ gridH, gridW int32
+ // ropePos is (h, w) per patch for the tower's 2D rotary tables.
+ ropePos []int32
+ // posIdx/posWt are the four bilinear corners per patch into the learned
+ // position table, with their interpolation weights.
+ posIdx []int32
+ posWt []float32
+}
+
+func (p preparedImage) numPatches() int32 { return p.gridH * p.gridW }
+
+func (p preparedImage) numTokens(merge int32) int32 {
+ return p.gridH * p.gridW / (merge * merge)
+}
+
+// smartResize ports the reference resize rule: round each side to the patch
+// factor, then scale into the pixel budget, preserving aspect ratio.
+func smartResize(height, width, factor int32) (int32, int32, error) {
+ if height <= 0 || width <= 0 {
+ return 0, 0, fmt.Errorf("invalid image size %dx%d", width, height)
+ }
+ longer, shorter := float64(max(height, width)), float64(min(height, width))
+ if longer/shorter > 200 {
+ return 0, 0, fmt.Errorf("image aspect ratio %.0f exceeds 200", longer/shorter)
+ }
+
+ f := float64(factor)
+ // The reference uses Python round (half to even).
+ hBar := math.RoundToEven(float64(height)/f) * f
+ wBar := math.RoundToEven(float64(width)/f) * f
+ if hBar*wBar > visionMaxPixels {
+ beta := math.Sqrt(float64(height) * float64(width) / visionMaxPixels)
+ hBar = math.Max(f, math.Floor(float64(height)/beta/f)*f)
+ wBar = math.Max(f, math.Floor(float64(width)/beta/f)*f)
+ } else if hBar*wBar < visionMinPixels {
+ beta := math.Sqrt(visionMinPixels / (float64(height) * float64(width)))
+ hBar = math.Ceil(float64(height)*beta/f) * f
+ wBar = math.Ceil(float64(width)*beta/f) * f
+ }
+ return int32(hBar), int32(wBar), nil
+}
+
+// preprocessImage decodes and prepares one image: aspect-preserving resize,
+// (x/255-0.5)/0.5 normalization, and patchification into the tower's
+// block-major row layout.
+func (m *Model) preprocessImage(data []byte) (pixels []float32, prep preparedImage, err error) {
+ img, _, err := image.Decode(bytes.NewReader(data))
+ if err != nil {
+ return nil, preparedImage{}, fmt.Errorf("decode image: %w", err)
+ }
+
+ v := m.Vision
+ patch, merge, temporal := v.PatchSize, v.SpatialMergeSize, v.TemporalPatchSize
+ bounds := img.Bounds()
+ img = dropAlpha(img, bounds)
+ targetH, targetW, err := smartResize(int32(bounds.Dy()), int32(bounds.Dx()), patch*merge)
+ if err != nil {
+ return nil, preparedImage{}, err
+ }
+
+ resized := image.NewRGBA(image.Rect(0, 0, int(targetW), int(targetH)))
+ draw.CatmullRom.Scale(resized, resized.Bounds(), img, bounds, draw.Src, nil)
+ gridH, gridW := targetH/patch, targetW/patch
+ prep = preparedImage{gridH: gridH, gridW: gridW}
+ pixels = patchifyImage(resized, gridH, gridW, patch, merge, temporal)
+ prep.ropePos, prep.posIdx, prep.posWt = visionPatchLookups(gridH, gridW, merge, v.NumPositionEmbeddings)
+ return pixels, prep, nil
+}
+
+// patchifyImage converts the resized image to the tower's row layout:
+// block-major over merge blocks, each row [channel][temporal duplicate]
+// [pixel row][pixel column].
+func patchifyImage(resized *image.RGBA, gridH, gridW, patch, merge, temporal int32) []float32 {
+ n := int(gridH * gridW)
+ rowLen := int(3 * temporal * patch * patch)
+ pixels := make([]float32, n*rowLen)
+
+ p, t := int(patch), int(temporal)
+ patchArea := p * p
+ row := 0
+ for bh := range gridH / merge {
+ for bw := range gridW / merge {
+ for mh := range merge {
+ for mw := range merge {
+ gh, gw := bh*merge+mh, bw*merge+mw
+ out := pixels[row*rowLen:]
+ baseX, baseY := int(gw)*p, int(gh)*p
+ for py := range p {
+ px0 := resized.PixOffset(baseX, baseY+py)
+ for px := range p {
+ pix := resized.Pix[px0+px*4:]
+ o := py*p + px
+ for c := range 3 {
+ val := float32(pix[c])/127.5 - 1
+ for ti := range t {
+ out[(c*t+ti)*patchArea+o] = val
+ }
+ }
+ }
+ }
+ row++
+ }
+ }
+ }
+ }
+ return pixels
+}
+
+// visionPatchLookups computes, in the block-major token order, each patch's
+// (h, w) rotary position and its four bilinear corners into the learned
+// side*side position grid with their weights.
+func visionPatchLookups(gridH, gridW, merge, numPosEmbeddings int32) (ropePos, posIdx []int32, posWt []float32) {
+ side := int32(math.Sqrt(float64(numPosEmbeddings)))
+ n := int(gridH * gridW)
+ ropePos = make([]int32, 0, 2*n)
+ posIdx = make([]int32, 0, 4*n)
+ posWt = make([]float32, 0, 4*n)
+
+ // linspace(0, side-1, g) per axis over the pre-merge grid.
+ coord := func(i, g int32) float64 {
+ if g == 1 {
+ return 0
+ }
+ return float64(i) * float64(side-1) / float64(g-1)
+ }
+
+ for bh := range gridH / merge {
+ for bw := range gridW / merge {
+ for mh := range merge {
+ for mw := range merge {
+ gh, gw := bh*merge+mh, bw*merge+mw
+ ropePos = append(ropePos, gh, gw)
+
+ hg, wg := coord(gh, gridH), coord(gw, gridW)
+ hf, wf := int32(hg), int32(wg)
+ hc, wc := min(hf+1, side-1), min(wf+1, side-1)
+ hFrac, wFrac := float32(hg-float64(hf)), float32(wg-float64(wf))
+ posIdx = append(posIdx, hf*side+wf, hf*side+wc, hc*side+wf, hc*side+wc)
+ posWt = append(posWt,
+ (1-hFrac)*(1-wFrac), (1-hFrac)*wFrac, hFrac*(1-wFrac), hFrac*wFrac)
+ }
+ }
+ }
+ }
+ return ropePos, posIdx, posWt
+}
+
+// dropAlpha flattens a non-opaque image to straight RGB: the reference
+// drops alpha via RGB conversion before resizing, not by compositing.
+func dropAlpha(img image.Image, bounds image.Rectangle) image.Image {
+ if o, ok := img.(interface{ Opaque() bool }); ok && o.Opaque() {
+ return img
+ }
+ flat := image.NewNRGBA(bounds)
+ draw.Draw(flat, bounds, img, bounds.Min, draw.Src)
+ for i := 3; i < len(flat.Pix); i += 4 {
+ flat.Pix[i] = 0xff
+ }
+ return flat
+}
diff --git a/x/models/qwen3_5/qwen3_5.go b/x/models/qwen3_5/qwen3_5.go
index f36a5e66c..dda85db44 100644
--- a/x/models/qwen3_5/qwen3_5.go
+++ b/x/models/qwen3_5/qwen3_5.go
@@ -28,6 +28,7 @@ var (
_ base.Model = (*Model)(nil)
_ base.SelfDraft = (*Model)(nil)
_ base.DraftModel = (*mtpDraft)(nil)
+ _ base.MediaModel = (*Model)(nil)
)
// RopeParameters carries optional rope metadata embedded under rope_parameters.
@@ -36,6 +37,7 @@ type RopeParameters struct {
RopeType string `json:"rope_type"`
RopeTheta float32 `json:"rope_theta"`
PartialRotaryFactor float32 `json:"partial_rotary_factor"`
+ MropeSection []int32 `json:"mrope_section"`
}
// Config holds Qwen 3.5 text config (top-level or nested text_config).
@@ -76,6 +78,8 @@ type Config struct {
RopeScaling map[string]any `json:"rope_scaling"`
RopeParameters *RopeParameters `json:"rope_parameters"`
+ MropeSection []int32 `json:"-"`
+
// Quantization metadata.
QuantGroupSize int `json:"-"`
QuantBits int `json:"-"`
@@ -96,6 +100,11 @@ type Model struct {
MTP *MTPHead
+ // Vision components; nil for text-only checkpoints.
+ Vision *VisionConfig
+ VisionTower *VisionTower
+ MM multimodalConfig
+
tok *tokenizer.Tokenizer
*Config
@@ -276,6 +285,10 @@ func parseConfig(configData []byte) (Config, error) {
ropeDim = cfg.HeadDim
}
cfg.RopeDim = ropeDim
+ cfg.MropeSection = []int32{11, 11, 10}
+ if cfg.RopeParameters != nil && len(cfg.RopeParameters.MropeSection) == 3 {
+ cfg.MropeSection = cfg.RopeParameters.MropeSection
+ }
if cfg.FullAttentionInterval <= 0 {
for i, lt := range cfg.LayerTypes {
@@ -405,9 +418,16 @@ func NewModel(root *model.Root) (base.Model, error) {
return nil, fmt.Errorf("parse tokenizer: %w", err)
}
+ mm, err := parseMultimodalConfig(configData)
+ if err != nil {
+ return nil, err
+ }
+
m := &Model{
Layers: make([]*Layer, cfg.NumHiddenLayers),
Config: &cfg,
+ MM: mm,
+ Vision: mm.VisionConfig,
tok: tok,
}
@@ -870,7 +890,7 @@ func (m *Model) LoadWeights(tensors map[string]*mlx.Array) error {
}
}
- return nil
+ return m.loadVisionWeights(tensors, linears)
}
// loadLayer builds a decoder layer from tensors at layerPrefix. It serves both
@@ -1021,7 +1041,7 @@ func (m *Model) loadMTPHead(linears model.LinearFactory, tensors map[string]*mlx
return nil
}
-func (a *FullAttention) Forward(x *mlx.Array, b *batch.Batch, c cache.Cache, positions *mlx.Array, B, L int32, cfg *Config) *mlx.Array {
+func (a *FullAttention) Forward(x *mlx.Array, b *batch.Batch, c cache.Cache, positions *mlx.Array, B, L int32, cfg *Config, mropeCos, mropeSin *mlx.Array) *mlx.Array {
qg := a.QProj.Forward(x)
qg = mlx.Reshape(qg, B, L, cfg.NumAttentionHeads, cfg.HeadDim*2)
q := mlx.SliceStartStop(qg, []int32{0, 0, 0, 0}, []int32{B, L, cfg.NumAttentionHeads, cfg.HeadDim})
@@ -1040,8 +1060,13 @@ func (a *FullAttention) Forward(x *mlx.Array, b *batch.Batch, c cache.Cache, pos
k = mlx.Transpose(k, 0, 2, 1, 3)
v = mlx.Transpose(v, 0, 2, 1, 3)
- q = mlx.RoPEWithBase(q, int(cfg.RopeDim), false, cfg.RopeTheta, 1.0, positions)
- k = mlx.RoPEWithBase(k, int(cfg.RopeDim), false, cfg.RopeTheta, 1.0, positions)
+ if mropeCos != nil {
+ q = applyMRoPE(q, mropeCos, mropeSin, cfg.RopeDim)
+ k = applyMRoPE(k, mropeCos, mropeSin, cfg.RopeDim)
+ } else {
+ q = mlx.RoPEWithBase(q, int(cfg.RopeDim), false, cfg.RopeTheta, 1.0, positions)
+ k = mlx.RoPEWithBase(k, int(cfg.RopeDim), false, cfg.RopeTheta, 1.0, positions)
+ }
var kv nn.SDPAOption
if c != nil {
@@ -1181,13 +1206,13 @@ func (m *SparseMoE) Forward(x *mlx.Array, cfg *Config) *mlx.Array {
return mlx.Reshape(y, B, L, cfg.HiddenSize)
}
-func (l *Layer) Forward(x *mlx.Array, b *batch.Batch, c cache.Cache, positions *mlx.Array, B, L int32, cfg *Config) *mlx.Array {
+func (l *Layer) Forward(x *mlx.Array, b *batch.Batch, c cache.Cache, positions *mlx.Array, B, L int32, cfg *Config, mropeCos, mropeSin *mlx.Array) *mlx.Array {
var r *mlx.Array
normed := l.InputNorm.Forward(x, cfg.RMSNormEps)
if l.IsLinear {
r = l.Linear.Forward(normed, b, c, B, L, cfg)
} else {
- r = l.FullAttn.Forward(normed, b, c, positions, B, L, cfg)
+ r = l.FullAttn.Forward(normed, b, c, positions, B, L, cfg, mropeCos, mropeSin)
}
h := mlx.Add(x, r)
r = l.MLP.Forward(l.PostAttentionNorm.Forward(h, cfg.RMSNormEps), cfg)
@@ -1200,12 +1225,23 @@ func (m *Model) Forward(b *batch.Batch, caches []cache.Cache) (hidden, auxHidden
positions := mlx.FromValues(b.SeqOffsets, len(b.SeqOffsets))
h := m.EmbedTokens.Forward(b.InputIDs)
+ if len(b.Media) > 0 {
+ h = m.scatterMedia(h, b, 0)
+ }
+
+ // One shared table pair per forward: every full-attention layer applies
+ // the same chunk positions.
+ var mropeCos, mropeSin *mlx.Array
+ if mp := ropePositions(b, L); mp != nil {
+ mropeCos, mropeSin = mropeCosSin(m.Config, mp, L)
+ }
+
for i, layer := range m.Layers {
var c cache.Cache
if caches != nil && i < len(caches) {
c = caches[i]
}
- h = layer.Forward(h, b, c, positions, B, L, m.Config)
+ h = layer.Forward(h, b, c, positions, B, L, m.Config, mropeCos, mropeSin)
}
out := m.Norm.Forward(h, m.RMSNormEps)
return out, out
@@ -1248,11 +1284,22 @@ func (m *mtpDraft) Forward(b *batch.Batch, _, draftCaches []cache.Cache) (hidden
B, L := int32(dims[0]), int32(dims[1])
positions := mlx.FromValues(b.SeqOffsets, len(b.SeqOffsets))
- emb := m.MTP.Enorm.Forward(m.EmbedTokens.Forward(b.InputIDs), m.RMSNormEps)
+ raw := m.EmbedTokens.Forward(b.InputIDs)
+ if len(b.Media) > 0 {
+ // The pair at slot S embeds the look-ahead token S+1, so each row's
+ // column 0 holds the prompt token one past its offset.
+ raw = (*Model)(m).scatterMedia(raw, b, 1)
+ }
+ emb := m.MTP.Enorm.Forward(raw, m.RMSNormEps)
h := m.MTP.Hnorm.Forward(b.Hidden, m.RMSNormEps)
fused := m.MTP.FC.Forward(emb.Concatenate(-1, h))
- out := m.MTP.Layer.Forward(fused, b, draftCaches[0], positions, B, L, m.Config)
+ var mropeCos, mropeSin *mlx.Array
+ if mp := ropePositions(b, L); mp != nil {
+ mropeCos, mropeSin = mropeCosSin(m.Config, mp, L)
+ }
+
+ out := m.MTP.Layer.Forward(fused, b, draftCaches[0], positions, B, L, m.Config, mropeCos, mropeSin)
hidden = m.MTP.Norm.Forward(out, m.RMSNormEps)
return hidden, hidden
}
diff --git a/x/models/qwen3_5/vision.go b/x/models/qwen3_5/vision.go
new file mode 100644
index 000000000..bc8107134
--- /dev/null
+++ b/x/models/qwen3_5/vision.go
@@ -0,0 +1,512 @@
+package qwen3_5
+
+import (
+ "encoding/json"
+ "fmt"
+ "math"
+
+ "github.com/ollama/ollama/x/mlxrunner/batch"
+ "github.com/ollama/ollama/x/mlxrunner/mlx"
+ "github.com/ollama/ollama/x/mlxrunner/model"
+ "github.com/ollama/ollama/x/mlxrunner/model/base"
+ "github.com/ollama/ollama/x/models/nn"
+)
+
+// VisionConfig holds the qwen3.5 vision tower configuration.
+type VisionConfig struct {
+ Depth int32 `json:"depth"`
+ HiddenSize int32 `json:"hidden_size"`
+ NumHeads int32 `json:"num_heads"`
+ InChannels int32 `json:"in_channels"`
+ PatchSize int32 `json:"patch_size"`
+ SpatialMergeSize int32 `json:"spatial_merge_size"`
+ TemporalPatchSize int32 `json:"temporal_patch_size"`
+ NumPositionEmbeddings int32 `json:"num_position_embeddings"`
+
+ // DeepstackVisualIndexes is rejected at load when non-empty: the
+ // family ships it empty, and serving it would need per-layer feature
+ // injection the tower does not implement.
+ DeepstackVisualIndexes []int32 `json:"deepstack_visual_indexes"`
+}
+
+// multimodalConfig carries the top-level fields the text_config unwrap
+// discards.
+type multimodalConfig struct {
+ VisionConfig *VisionConfig `json:"vision_config"`
+ ImageTokenID int32 `json:"image_token_id"`
+ VisionStartTokenID int32 `json:"vision_start_token_id"`
+ VisionEndTokenID int32 `json:"vision_end_token_id"`
+}
+
+func parseMultimodalConfig(configData []byte) (multimodalConfig, error) {
+ var mm multimodalConfig
+ if err := json.Unmarshal(configData, &mm); err != nil {
+ return multimodalConfig{}, fmt.Errorf("parse multimodal config: %w", err)
+ }
+ if v := mm.VisionConfig; v != nil {
+ if len(v.DeepstackVisualIndexes) > 0 {
+ return multimodalConfig{}, fmt.Errorf("unsupported deepstack_visual_indexes %v", v.DeepstackVisualIndexes)
+ }
+ if v.PatchSize == 0 {
+ v.PatchSize = 16
+ }
+ if v.SpatialMergeSize == 0 {
+ v.SpatialMergeSize = 2
+ }
+ if v.TemporalPatchSize == 0 {
+ v.TemporalPatchSize = 2
+ }
+ if v.NumHeads == 0 {
+ v.NumHeads = 16
+ }
+ }
+ return mm, nil
+}
+
+// VisionTower is the qwen3.5 image encoder: a bidirectional transformer over
+// patch embeddings with interpolated learned positions and 2D rotary
+// attention, merged 2x2 into LM-space tokens.
+type VisionTower struct {
+ PatchEmbed nn.LinearLayer
+ PosEmbed *mlx.Array // [num_position_embeddings, hidden]
+ Blocks []*VisionBlock
+ MergerNorm *nn.LayerNorm
+ MergerFC1 nn.LinearLayer
+ MergerFC2 nn.LinearLayer
+}
+
+type VisionBlock struct {
+ Norm1 *nn.LayerNorm
+ Norm2 *nn.LayerNorm
+ QKV nn.LinearLayer
+ Proj nn.LinearLayer
+ FC1 nn.LinearLayer
+ FC2 nn.LinearLayer
+}
+
+// visionLayout is the request's Batch.Layout value: the prompt's 3-channel
+// rope positions and the delta that continues them past the prompt.
+type visionLayout struct {
+ positions []int32 // flattened [3][promptLen]
+ promptLen int32
+ delta int32
+}
+
+// visionWeightRoot locates the tower's tensor prefix: the import pipeline
+// renames the reference's model.visual to vision_tower.
+func visionWeightRoot(tensors map[string]*mlx.Array) string {
+ for _, root := range []string{"vision_tower.", "model.visual.", "visual."} {
+ if tensors[root+"patch_embed.proj.bias"] != nil {
+ return root
+ }
+ }
+ return ""
+}
+
+func (m *Model) loadVisionWeights(tensors map[string]*mlx.Array, linears model.LinearFactory) error {
+ root := visionWeightRoot(tensors)
+ v := m.Vision
+ if root == "" {
+ if v != nil {
+ return fmt.Errorf("config declares a vision tower but vision weights are missing from the manifest")
+ }
+ return nil
+ }
+ if v == nil {
+ return fmt.Errorf("vision tower tensors present but config has no vision_config")
+ }
+
+ required := func(name string) (*mlx.Array, error) {
+ w := tensors[root+name]
+ if w == nil {
+ return nil, fmt.Errorf("missing vision weight: %s%s", root, name)
+ }
+ return w, nil
+ }
+ requiredLinear := func(name string) (nn.LinearLayer, error) {
+ l := linears.Make(root + name)
+ if l == nil {
+ return nil, fmt.Errorf("missing vision weight: %s%s", root, name)
+ }
+ return l, nil
+ }
+ layerNorm := func(name string) (*nn.LayerNorm, error) {
+ w, err := required(name + ".weight")
+ if err != nil {
+ return nil, err
+ }
+ b, err := required(name + ".bias")
+ if err != nil {
+ return nil, err
+ }
+ return &nn.LayerNorm{Weight: w, Bias: b, Eps: 1e-6}, nil
+ }
+
+ tower := &VisionTower{Blocks: make([]*VisionBlock, v.Depth)}
+
+ // The reference patch embed is a Conv3d whose stride equals its kernel:
+ // a linear over the flattened patch row.
+ convW, err := required("patch_embed.proj.weight")
+ if err != nil {
+ return err
+ }
+ convB, err := required("patch_embed.proj.bias")
+ if err != nil {
+ return err
+ }
+ rowLen := v.InChannels * v.TemporalPatchSize * v.PatchSize * v.PatchSize
+ tower.PatchEmbed = nn.NewLinear(mlx.Reshape(convW, v.HiddenSize, rowLen), convB)
+
+ if tower.PosEmbed, err = required("pos_embed.weight"); err != nil {
+ return err
+ }
+
+ for i := range tower.Blocks {
+ bp := fmt.Sprintf("blocks.%d.", i)
+ blk := &VisionBlock{}
+ if blk.Norm1, err = layerNorm(bp + "norm1"); err != nil {
+ return err
+ }
+ if blk.Norm2, err = layerNorm(bp + "norm2"); err != nil {
+ return err
+ }
+ if blk.QKV, err = requiredLinear(bp + "attn.qkv"); err != nil {
+ return err
+ }
+ if blk.Proj, err = requiredLinear(bp + "attn.proj"); err != nil {
+ return err
+ }
+ if blk.FC1, err = requiredLinear(bp + "mlp.linear_fc1"); err != nil {
+ return err
+ }
+ if blk.FC2, err = requiredLinear(bp + "mlp.linear_fc2"); err != nil {
+ return err
+ }
+ tower.Blocks[i] = blk
+ }
+
+ if tower.MergerNorm, err = layerNorm("merger.norm"); err != nil {
+ return err
+ }
+ if tower.MergerFC1, err = requiredLinear("merger.linear_fc1"); err != nil {
+ return err
+ }
+ if tower.MergerFC2, err = requiredLinear("merger.linear_fc2"); err != nil {
+ return err
+ }
+
+ m.VisionTower = tower
+ return nil
+}
+
+func (m *Model) visionLoaded() bool { return m.VisionTower != nil }
+
+// PrepareMedia implements base.MediaModel: preprocess each image segment,
+// splice its vision_start + pads + vision_end expansion, and precompute the
+// request's 3-channel rope positions.
+func (m *Model) PrepareMedia(segments []base.Segment) (*base.PreparedRequest, error) {
+ prepared := &base.PreparedRequest{}
+
+ // pos walks the reference's multimodal position rule: text advances one
+ // per token on all channels; an image spans a merged grid anchored at
+ // the current position and advances it by the grid's longer side.
+ var positions []int32
+ cur := int32(0)
+ maxPos := int32(-1)
+ text := func(n int) {
+ for range n {
+ positions = append(positions, cur, cur, cur)
+ maxPos = max(maxPos, cur)
+ cur++
+ }
+ }
+
+ for s, seg := range segments {
+ if seg.Data == nil {
+ prepared.Tokens = append(prepared.Tokens, seg.Tokens...)
+ text(len(seg.Tokens))
+ continue
+ }
+ if !m.visionLoaded() {
+ return nil, fmt.Errorf("this model does not support %s input", seg.Kind)
+ }
+ if seg.Kind != "image" {
+ return nil, fmt.Errorf("qwen3.5 does not support %s input", seg.Kind)
+ }
+
+ pixels, prep, err := m.preprocessImage(seg.Data)
+ if err != nil {
+ return nil, err
+ }
+
+ start := len(prepared.Tokens)
+ prepared.Tokens = append(prepared.Tokens, m.MM.VisionStartTokenID)
+ text(1)
+ merge := m.Vision.SpatialMergeSize
+ mh, mw := prep.gridH/merge, prep.gridW/merge
+ for bh := range mh {
+ for bw := range mw {
+ prepared.Tokens = append(prepared.Tokens, m.MM.ImageTokenID)
+ positions = append(positions, cur, cur+bh, cur+bw)
+ maxPos = max(maxPos, max(cur+bh, cur+bw))
+ }
+ }
+ cur += max(mh, mw)
+ prepared.Tokens = append(prepared.Tokens, m.MM.VisionEndTokenID)
+ text(1)
+
+ n := int(prep.numPatches())
+ prepared.Items = append(prepared.Items, base.PreparedItem{
+ Range: [2]int{start, len(prepared.Tokens)},
+ Source: s,
+ MediaData: pixels,
+ Dims: []int{n, len(pixels) / n},
+ Opaque: prep,
+ Causal: true,
+ })
+ }
+
+ if len(prepared.Items) > 0 {
+ // positions accumulated as (t,h,w) triples per token; the layout
+ // stores three channel rows.
+ L := int32(len(prepared.Tokens))
+ table := make([]int32, 3*L)
+ for i := range L {
+ table[i] = positions[3*i]
+ table[L+i] = positions[3*i+1]
+ table[2*L+i] = positions[3*i+2]
+ }
+ prepared.Layout = &visionLayout{positions: table, promptLen: L, delta: maxPos + 1 - L}
+ }
+ return prepared, nil
+}
+
+// EncodeMedia implements base.MediaModel: run the tower over one whole
+// image, returning the lazy [numTokens, hidden] features.
+func (m *Model) EncodeMedia(item *base.PreparedItem, data *mlx.Array) *mlx.Array {
+ prep := item.Opaque.(preparedImage)
+ v := m.Vision
+ t := m.VisionTower
+ n := prep.numPatches()
+
+ h := t.PatchEmbed.Forward(data.AsType(t.PosEmbed.DType()))
+
+ // Bilinear position interpolation: four corner rows summed with their
+ // weights, in fp32 like the reference.
+ pos := mlx.Zeros(mlx.DTypeFloat32, int(n), int(v.HiddenSize))
+ for c := range 4 {
+ idx := make([]int32, n)
+ wt := make([]float32, n)
+ for i := range int(n) {
+ idx[i] = prep.posIdx[4*i+c]
+ wt[i] = prep.posWt[4*i+c]
+ }
+ rows := mlx.Take(t.PosEmbed, mlx.FromValues(idx, int(n)), 0).AsType(mlx.DTypeFloat32)
+ pos = mlx.Add(pos, mlx.Mul(rows, mlx.FromValues(wt, int(n), 1)))
+ }
+ h = mlx.Add(h, pos.AsType(h.DType()))
+ h = mlx.Reshape(h, 1, n, v.HiddenSize)
+
+ headDim := v.HiddenSize / v.NumHeads
+ cos, sin := visionRopeTables(prep.ropePos, n, headDim)
+ scale := float32(1.0 / math.Sqrt(float64(headDim)))
+
+ for _, blk := range t.Blocks {
+ x := blk.Norm1.Forward(h)
+ qkv := mlx.Reshape(blk.QKV.Forward(x), 1, n, 3, v.NumHeads, headDim)
+ split := func(i int32) *mlx.Array {
+ s := mlx.SliceStartStop(qkv, []int32{0, 0, i, 0, 0}, []int32{1, n, i + 1, v.NumHeads, headDim})
+ return mlx.Transpose(mlx.Squeeze(s, 2), 0, 2, 1, 3)
+ }
+ q, k, val := split(0), split(1), split(2)
+ q = applyVisionRoPE(q, cos, sin)
+ k = applyVisionRoPE(k, cos, sin)
+
+ // Fully bidirectional over the single image.
+ out := mlx.FastScaledDotProductAttention(q, k, val, scale, "", nil)
+ out = mlx.Reshape(mlx.Transpose(out, 0, 2, 1, 3), 1, n, v.HiddenSize)
+ h = mlx.Add(h, blk.Proj.Forward(out))
+
+ x = blk.Norm2.Forward(h)
+ h = mlx.Add(h, blk.FC2.Forward(mlx.GELUApprox(blk.FC1.Forward(x))))
+ }
+
+ // Block-major token order makes the merge reshape a plain grouping of
+ // consecutive rows; the activation is the exact erf GELU in fp32, like
+ // the reference.
+ merged := t.MergerNorm.Forward(mlx.Squeeze(h, 0))
+ unit := v.SpatialMergeSize * v.SpatialMergeSize
+ merged = mlx.Reshape(merged, n/unit, v.HiddenSize*unit)
+ f := t.MergerFC1.Forward(merged).AsType(mlx.DTypeFloat32)
+ f = mlx.Mul(mlx.MulScalar(f, 0.5),
+ mlx.AddScalar(mlx.Erf(mlx.MulScalar(f, float32(1/math.Sqrt2))), 1))
+ out := t.MergerFC2.Forward(f.AsType(merged.DType()))
+ return out
+}
+
+// visionRopeTables builds the tower's rotary tables: 2D positions, half the
+// head dim per axis, in fp32.
+func visionRopeTables(ropePos []int32, n, headDim int32) (cos, sin *mlx.Array) {
+ half := int(headDim) / 2
+ nFreq := half / 2
+ invFreq := make([]float32, nFreq)
+ for i := range invFreq {
+ invFreq[i] = float32(1 / math.Pow(10000, float64(2*i)/float64(half)))
+ }
+
+ // Per token: h-axis freqs then w-axis freqs, duplicated across the two
+ // rotation halves.
+ emb := make([]float32, int(n)*int(headDim))
+ for i := range n {
+ hp, wp := float32(ropePos[2*i]), float32(ropePos[2*i+1])
+ row := emb[int(i)*int(headDim):]
+ for j := range nFreq {
+ row[j] = hp * invFreq[j]
+ row[nFreq+j] = wp * invFreq[j]
+ }
+ copy(row[half:], row[:half])
+ }
+ e := mlx.FromValues(emb, 1, int(n), 1, int(headDim))
+ return mlx.Cos(e), mlx.Sin(e)
+}
+
+// applyVisionRoPE applies full-dim rotate-half rotary in fp32, matching the
+// reference's float application.
+func applyVisionRoPE(t, cos, sin *mlx.Array) *mlx.Array {
+ dt := t.DType()
+ tf := t.AsType(mlx.DTypeFloat32)
+ dims := tf.Dims()
+ headDim := int32(dims[3])
+ half := headDim / 2
+ t1 := tf.Slice(mlx.Slice(), mlx.Slice(), mlx.Slice(), mlx.Slice(0, int(half)))
+ t2 := tf.Slice(mlx.Slice(), mlx.Slice(), mlx.Slice(), mlx.Slice(int(half), int(headDim)))
+ rot := mlx.Concatenate([]*mlx.Array{mlx.Neg(t2), t1}, -1)
+ // cos/sin are [1, n, 1, headDim]; broadcast over heads on axis 1 needs
+ // the transpose-matched layout [1, 1, n, headDim].
+ c := mlx.Transpose(cos, 0, 2, 1, 3)
+ s := mlx.Transpose(sin, 0, 2, 1, 3)
+ return mlx.Add(mlx.Mul(tf, c), mlx.Mul(rot, s)).AsType(dt)
+}
+
+// softRun returns an item's image-token range: the expansion is
+// vision_start + pads + vision_end.
+func softRun(item batch.MediaItem, merge int32) (start, end int) {
+ prep := item.Opaque.(preparedImage)
+ return item.Pos + 1, item.Pos + 1 + int(prep.numTokens(merge))
+}
+
+// scatterMedia overwrites the image-token rows this chunk covers with the
+// item's encoded features. delta shifts each row's offset to the sequence
+// position of batch column 0.
+func (m *Model) scatterMedia(h *mlx.Array, b *batch.Batch, delta int) *mlx.Array {
+ merge := m.Vision.SpatialMergeSize
+ for _, item := range b.Media {
+ if item.Features == nil {
+ continue
+ }
+ start, end := softRun(item, merge)
+ base := int(b.SeqOffsets[item.Seq]) + delta
+ qLo := max(start, base)
+ qHi := min(end, base+int(b.SeqQueryLens[item.Seq]))
+ if qHi <= qLo {
+ continue
+ }
+ feat := item.Features.Slice(mlx.Slice(qLo-start, qHi-start), mlx.Slice())
+ feat = mlx.Reshape(feat.AsType(h.DType()), 1, int32(qHi-qLo), m.HiddenSize)
+ h = h.SliceUpdate(feat, mlx.Slice(item.Seq, item.Seq+1), mlx.Slice(qLo-base, qHi-base), mlx.Slice())
+ }
+ return h
+}
+
+// ropePositions returns each row's 3-channel positions, flattened [B][3][L],
+// from its layout: table rows inside the prompt, the uniform text
+// continuation past it. Rows without a layout advance uniformly on all
+// channels. Nil when no row carries a layout (plain 1D positions).
+func ropePositions(b *batch.Batch, L int32) []int32 {
+ carried := false
+ for _, l := range b.Layout {
+ carried = carried || l != nil
+ }
+ if !carried {
+ return nil
+ }
+ out := make([]int32, 3*L*int32(len(b.SeqOffsets)))
+ for r, base := range b.SeqOffsets {
+ row := out[r*3*int(L):]
+ var layout *visionLayout
+ if b.Layout[r] != nil {
+ layout = b.Layout[r].(*visionLayout)
+ }
+ for i := range L {
+ p := base + i
+ switch {
+ case layout == nil:
+ row[i], row[L+i], row[2*L+i] = p, p, p
+ case p < layout.promptLen:
+ row[i] = layout.positions[p]
+ row[L+i] = layout.positions[layout.promptLen+p]
+ row[2*L+i] = layout.positions[2*layout.promptLen+p]
+ default:
+ row[i], row[L+i], row[2*L+i] = p+layout.delta, p+layout.delta, p+layout.delta
+ }
+ }
+ }
+ return out
+}
+
+// mropeCosSin builds the interleaved 3-channel rotary tables for one chunk:
+// each channel's frequencies laid out round-robin T,H,W across the rotary
+// half-dims, matching the reference's interleaved M-RoPE. positions is
+// ropePositions' per-row [3][L] blocks.
+func mropeCosSin(cfg *Config, positions []int32, L int32) (cos, sin *mlx.Array) {
+ half := int(cfg.RopeDim) / 2
+ invFreq := make([]float32, half)
+ for i := range invFreq {
+ invFreq[i] = float32(1 / math.Pow(float64(cfg.RopeTheta), float64(2*i)/float64(cfg.RopeDim)))
+ }
+
+ // Interleave: start from T, then overwrite H at 1,4,7,... and W at
+ // 2,5,8,..., each bounded by its section's 3x length like the reference.
+ sel := make([]int32, half)
+ for c := int32(1); c <= 2; c++ {
+ limit := min(int(cfg.MropeSection[c])*3, half)
+ for j := int(c); j < limit; j += 3 {
+ sel[j] = c
+ }
+ }
+
+ B := len(positions) / (3 * int(L))
+ emb := make([]float32, B*int(L)*int(cfg.RopeDim))
+ for r := range B {
+ rowPos := positions[r*3*int(L):]
+ for i := range int(L) {
+ row := emb[(r*int(L)+i)*int(cfg.RopeDim):]
+ for j, c := range sel {
+ row[j] = float32(rowPos[int(c)*int(L)+i]) * invFreq[j]
+ }
+ copy(row[half:], row[:half])
+ }
+ }
+ e := mlx.FromValues(emb, B, 1, int(L), int(cfg.RopeDim))
+ return mlx.Cos(e), mlx.Sin(e)
+}
+
+// applyMRoPE rotates the leading RopeDim dims with the chunk's tables,
+// passing the rest through, in the tensor's own dtype like the reference.
+func applyMRoPE(t, cos, sin *mlx.Array, ropeDim int32) *mlx.Array {
+ dims := t.Dims()
+ headDim := int32(dims[3])
+ rot := t.Slice(mlx.Slice(), mlx.Slice(), mlx.Slice(), mlx.Slice(0, int(ropeDim)))
+ half := ropeDim / 2
+ r1 := rot.Slice(mlx.Slice(), mlx.Slice(), mlx.Slice(), mlx.Slice(0, int(half)))
+ r2 := rot.Slice(mlx.Slice(), mlx.Slice(), mlx.Slice(), mlx.Slice(int(half), int(ropeDim)))
+ rotated := mlx.Concatenate([]*mlx.Array{mlx.Neg(r2), r1}, -1)
+ c := cos.AsType(t.DType())
+ s := sin.AsType(t.DType())
+ out := mlx.Add(mlx.Mul(rot, c), mlx.Mul(rotated, s))
+ if ropeDim == headDim {
+ return out
+ }
+ pass := t.Slice(mlx.Slice(), mlx.Slice(), mlx.Slice(), mlx.Slice(int(ropeDim), int(headDim)))
+ return mlx.Concatenate([]*mlx.Array{out, pass}, -1)
+}
diff --git a/x/models/qwen3_5/vision_test.go b/x/models/qwen3_5/vision_test.go
new file mode 100644
index 000000000..b1d3938e8
--- /dev/null
+++ b/x/models/qwen3_5/vision_test.go
@@ -0,0 +1,167 @@
+package qwen3_5
+
+import (
+ "bytes"
+ "image"
+ "image/png"
+ "strings"
+ "testing"
+
+ "github.com/ollama/ollama/x/mlxrunner/model/base"
+)
+
+func TestSmartResize(t *testing.T) {
+ // Goldens from the reference smart_resize at the family's processor
+ // bounds (factor 32, pixels in [65536, 16777216]).
+ cases := []struct{ h, w, wantH, wantW int32 }{
+ {480, 640, 480, 640},
+ {1080, 1920, 1088, 1920},
+ {3024, 4032, 3008, 4032},
+ {100, 100, 256, 256},
+ {37, 5000, 32, 4992},
+ }
+ for _, c := range cases {
+ h, w, err := smartResize(c.h, c.w, 32)
+ if err != nil {
+ t.Fatalf("smartResize(%d, %d): %v", c.h, c.w, err)
+ }
+ if h != c.wantH || w != c.wantW {
+ t.Errorf("smartResize(%d, %d) = (%d, %d), want (%d, %d)", c.h, c.w, h, w, c.wantH, c.wantW)
+ }
+ }
+ if _, _, err := smartResize(10, 5000, 32); err == nil {
+ t.Error("aspect ratio over 200 should error")
+ }
+}
+
+func TestParseMultimodalConfig(t *testing.T) {
+ mm, err := parseMultimodalConfig([]byte(`{
+ "image_token_id": 248056, "vision_start_token_id": 248053, "vision_end_token_id": 248054,
+ "vision_config": {"depth": 27, "hidden_size": 1152, "deepstack_visual_indexes": []}}`))
+ if err != nil {
+ t.Fatal(err)
+ }
+ v := mm.VisionConfig
+ if v == nil || v.PatchSize != 16 || v.SpatialMergeSize != 2 || v.TemporalPatchSize != 2 || v.NumHeads != 16 {
+ t.Fatalf("defaults not applied: %+v", v)
+ }
+
+ // Deepstack injection is not implemented; a config requesting it must
+ // fail the load rather than silently skip the injections.
+ _, err = parseMultimodalConfig([]byte(`{
+ "vision_config": {"depth": 27, "deepstack_visual_indexes": [8, 16, 24]}}`))
+ if err == nil || !strings.Contains(err.Error(), "deepstack") {
+ t.Fatalf("deepstack config accepted: %v", err)
+ }
+}
+
+// TestMRopePositionRule drives a real image through PrepareMedia and checks
+// the reference position rule: text advances all channels one per token; an
+// image grid anchors T at the current position, offsets H/W by row/column,
+// and advances the position by the grid's longer side.
+func TestMRopePositionRule(t *testing.T) {
+ cfg := &VisionConfig{PatchSize: 16, SpatialMergeSize: 2, TemporalPatchSize: 2, InChannels: 3, NumPositionEmbeddings: 2304}
+ m := &Model{
+ Config: &Config{},
+ VisionTower: &VisionTower{},
+ Vision: cfg,
+ MM: multimodalConfig{
+ ImageTokenID: 9,
+ VisionStartTokenID: 7,
+ VisionEndTokenID: 8,
+ VisionConfig: cfg,
+ },
+ }
+
+ prepared, err := m.PrepareMedia([]base.Segment{{Tokens: []int32{1, 2, 3}}})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if prepared.Layout != nil {
+ t.Fatal("text-only stream must carry no layout")
+ }
+
+ // A 64x64 PNG resizes to the 256x256 minimum-pixel floor: a 16x16 patch
+ // grid, merged 8x8.
+ var buf bytes.Buffer
+ if err := png.Encode(&buf, image.NewRGBA(image.Rect(0, 0, 64, 64))); err != nil {
+ t.Fatal(err)
+ }
+ prepared, err = m.PrepareMedia([]base.Segment{
+ {Tokens: []int32{1, 2, 3}},
+ {Kind: "image", Data: buf.Bytes()},
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ // Three text tokens, vision_start, 64 pads, vision_end.
+ const L = 69
+ if len(prepared.Tokens) != L {
+ t.Fatalf("tokens = %d, want %d", len(prepared.Tokens), L)
+ }
+ if len(prepared.Items) != 1 || prepared.Items[0].Range != [2]int{3, L} || !prepared.Items[0].Causal {
+ t.Fatalf("items = %+v", prepared.Items)
+ }
+
+ layout := prepared.Layout.(*visionLayout)
+ if layout.promptLen != L {
+ t.Fatalf("promptLen = %d, want %d", layout.promptLen, L)
+ }
+ // The image anchors at position 4 and advances the cursor by its longer
+ // side: vision_end lands at 12 and decode continues from maxPos+1.
+ if want := int32(12 + 1 - L); layout.delta != want {
+ t.Fatalf("delta = %d, want %d", layout.delta, want)
+ }
+ pos := func(i int32) [3]int32 {
+ return [3]int32{layout.positions[i], layout.positions[L+i], layout.positions[2*L+i]}
+ }
+ checks := []struct {
+ i int32
+ want [3]int32
+ }{
+ {0, [3]int32{0, 0, 0}}, // text
+ {2, [3]int32{2, 2, 2}}, // text
+ {3, [3]int32{3, 3, 3}}, // vision_start
+ {4, [3]int32{4, 4, 4}}, // image row 0, col 0
+ {5, [3]int32{4, 4, 5}}, // image row 0, col 1
+ {12, [3]int32{4, 5, 4}}, // image row 1, col 0
+ {67, [3]int32{4, 11, 11}}, // image row 7, col 7
+ {68, [3]int32{12, 12, 12}}, // vision_end
+ }
+ for _, c := range checks {
+ if got := pos(c.i); got != c.want {
+ t.Errorf("positions[%d] = %v, want %v", c.i, got, c.want)
+ }
+ }
+}
+
+func TestVisionPatchLookups(t *testing.T) {
+ // 4x6 pre-merge grid, merge 2: token order is block-major; rope
+ // positions are the pre-merge (h, w) indices.
+ ropePos, posIdx, posWt := visionPatchLookups(4, 6, 2, 2304)
+ if len(ropePos) != 2*24 || len(posIdx) != 4*24 || len(posWt) != 4*24 {
+ t.Fatalf("lengths %d %d %d", len(ropePos), len(posIdx), len(posWt))
+ }
+ // First merge block covers (0,0) (0,1) (1,0) (1,1) in that order.
+ want := []int32{0, 0, 0, 1, 1, 0, 1, 1}
+ for i, w := range want {
+ if ropePos[i] != w {
+ t.Fatalf("ropePos[:8] = %v, want %v", ropePos[:8], want)
+ }
+ }
+ // Second block continues at (0,2).
+ if ropePos[8] != 0 || ropePos[9] != 2 {
+ t.Fatalf("second block starts at (%d, %d), want (0, 2)", ropePos[8], ropePos[9])
+ }
+ // Bilinear weights sum to one per patch.
+ for i := range 24 {
+ var sum float32
+ for c := range 4 {
+ sum += posWt[4*i+c]
+ }
+ if sum < 0.999 || sum > 1.001 {
+ t.Fatalf("patch %d weights sum %f", i, sum)
+ }
+ }
+}