8000 Add Qwen3.5 model support (config, weights, and hybrid Gated DeltaNet) by janpfeifer · Pull Request #87 · gomlx/go-huggingface · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .agents/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ Manages downloading and access to HuggingFace repositories.
- `config_sentence_transformers.json` (sentence transformer pipeline settings)
- `modules.json` (execution pipeline: Transformer -> Pooling -> Normalize)
- `1_Pooling/config.json` (pooling strategy: mean, CLS, last-token; defaults to last-token for causal decoders and mean for bidirectional encoders when absent)
- Supports native quantized GGUF execution (`LoadStore` attaches `model.Quantization` metadata so GoMLX dispatches `nn.QuantizedDense` and `nn.QuantizedGather`), `WithGGUFFile(filename)`, `WithApproximateGelu(approx)`, RoPE positional embeddings, layer normalization, RMSNorm, multi-head/grouped-query attention, and task prompts (`task_prompts.json`).
- Supports native quantized GGUF execution (`LoadStore` attaches `model.Quantization` metadata so GoMLX dispatches `nn.QuantizedDense` and `nn.QuantizedGather`), `WithGGUFFile(filename)`, `WithApproximateGelu(approx)`, RoPE positional embeddings (including partial RoPE and flat or per-layer-type `rope_parameters`), layer normalization, RMSNorm (including zero-centered `1 + weight`), multi-head/grouped-query attention (including gated attention outputs), hybrid Gated DeltaNet linear attention layers (e.g., Qwen3.5), and task prompts (`task_prompts.json`).

### 3.6. `models/sam2`
- Implements Facebook's Segment Anything 2 (SAM2) image architecture in GoMLX:
Expand Down
8 changes: 8 additions & 0 deletions docs/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,14 @@

## Unreleased

- 2026/11/25:
- `models/transformer`:
- Added Qwen3.5 (`model_type: "qwen3_5"` / `"qwen3_5_text"`) model support for both sentence embedding and autoregressive text generation:
- Extended `Config` with Qwen3.5 hybrid Gated DeltaNet parameters (`attn_output_gate`, `full_attention_interval`, `linear_conv_kernel_dim`, `linear_key_head_dim`, `linear_value_head_dim`, `linear_num_key_heads`, `linear_num_value_heads`, `mamba_ssm_dtype`, `tie_word_embeddings`) and updated `Config.UnmarshalJSON` to parse both flat `rope_parameters` objects (Qwen3.5) and per-layer-type `rope_parameters` maps (Gemma 4).
- Mapped `layers.{N}.linear_attn.*` safetensors weights (`in_proj_qkv`, `in_proj_z`, `in_proj_b`, `in_proj_a`, `out_proj`, `conv1d.weight`, `A_log`, `dt_bias`, `norm.weight`) and untied `lm_head.weight`, while cleanly skipping `model.visual.*` and `mtp.*` tensors.
- Configured `mltransformer.ArchitectureQwen35`, `mltransformer.LinearLayer` layer types, zero-centered RMSNorm (`RMSNormOffset = 1.0`), gated attention output, and standard partial RoPE (`partial_rotary_factor`) in `CreateGoMLXModel`, and added `qwen3_5` / `qwen3_5_text` to `detectCausalMask`.
- Added unit tests (`TestQwen35ConfigAndTensorMapping`) verifying Qwen3.5 config/tensor mapping and Gemma 4 nested `rope_parameters` backwards compatibility.

- 2026/11/24:
- `tokenizers/hftokenizer`:
- Unigram tokenization picks the best-scoring split with Viterbi over the vocab scores, matching HuggingFace `tokenizers` (e.g. `Munich` → `▁`+`Munich` with deberta-v3 / GLiNER, previously greedy `▁Munic`+`h`).
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ require (
github.com/eliben/go-sentencepiece v0.7.0
github.com/gofrs/flock v0.13.0
github.com/gomlx/compute v0.1.34
github.com/gomlx/gomlx v0.28.40
github.com/gomlx/gomlx v0.28.41-0.20261125134254-cce1c9501d0b
github.com/google/uuid v1.6.0
github.com/parquet-go/parquet-go v0.29.0
github.com/pkg/errors v0.9.1
Expand Down
4 changes: 2 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,8 @@ github.com/gomlx/go-darwinml v0.1.11 h1:97F3Ki1aQekxopCkypzDFI4LyosniX5AuK8vcr0N
github.com/gomlx/go-darwinml v0.1.11/go.mod h1:XKlwSErj4TwHBpBm4k42lKqsDM9Zr+m2BLJXCeDcHX8=
github.com/gomlx/go-xla v0.4.34 h1:MiIBBYwQNF6gUupZ40X7ZMo7RgkSVjbjDbOhuxYQzdY=
github.com/gomlx/go-xla v0.4.34/go.mod h1:ZelbdzYVHVDlPszUwYnV1mw8kbtOvp0/OlEz+aECiKM=
github.com/gomlx/gomlx v0.28.40 h1:FsYu1sGIvKMpULfGcNCGcQzl5naHmjyoMLruszLW74E=
github.com/gomlx/gomlx v0.28.40/go.mod h1:oH8s8hvpzYNDYUNiw5km0AscX4UJvM/r0CZo1KDzc3E=
github.com/gomlx/gomlx v0.28.41-0.20261125134254-cce1c9501d0b h1:KWCOehW7rOlijKOT4EwfmdMsgyrbMWxARsjrbP8Baz0=
github.com/gomlx/gomlx v0.28.41-0.20261125134254-cce1c9501d0b/go.mod h1:oH8s8hvpzYNDYUNiw5km0AscX4UJvM/r0CZo1KDzc3E=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
Expand Down
53 changes: 47 additions & 6 deletions models/transformer/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,21 @@ type Config struct {
// SlidingWindow is the size of the sliding window for sliding attention layers.
SlidingWindow int `json:"sliding_window"`

// LayerTypes: known values are "full_attention", "sliding_attention"
LayerTypes []string `json:"layer_types"`
Extra map[string]any `json:"-"`
// LayerTypes: known values are "full_attention", "sliding_attention", "linear_attention"
LayerTypes []string `json:"layer_types"`

// Qwen3.5 / Hybrid Linear Attention (Gated DeltaNet) configuration.
AttnOutputGate bool `json:"attn_output_gate"`
FullAttentionInterval int `json:"full_attention_interval"`
LinearConvKernelDim int `json:"linear_conv_kernel_dim"`
LinearKeyHeadDim int `json:"linear_key_head_dim"`
LinearValueHeadDim int `json:"linear_value_head_dim"`
LinearNumKeyHeads int `json:"linear_num_key_heads"`
LinearNumValueHeads int `json:"linear_num_value_heads"`
MambaSSMDType string `json:"mamba_ssm_dtype"`
TieWordEmbeddings *bool `json:"tie_word_embeddings"`

Extra map[string]any `json:"-"`
}

type RoPEScaling struct {
Expand All @@ -64,9 +76,38 @@ type RoPEParams struct {
PartialRotaryFactor float64 `json:"partial_rotary_factor"`
}

func (c *Config) UnmarshalJSON(data []byte) error {
func (c *Config) unmarshalSection(data []byte) error {
// Parse rope_parameters separately because HuggingFace configs use either:
// - a per-layer-type map {"full_attention": {...}, "sliding_attention": {...}} (e.g. Gemma 4), or
// - a flat object {"rope_theta": ..., "partial_rotary_factor": ..., "rope_type": ...} (e.g. Qwen3.5).
type wrapper Config
if err := json.Unmarshal(data, (*wrapper)(c)); err != nil {
type rawConfig struct {
*wrapper
RawRoPEParameters json.RawMessage `json:"rope_parameters"`
}
rc := rawConfig{wrapper: (*wrapper)(c)}
if err := json.Unmarshal(data, &rc); err != nil {
return err
}
if len(rc.RawRoPEParameters) > 0 && string(rc.RawRoPEParameters) != "null" {
var perLayer map[string]RoPEParams
if err := json.Unmarshal(rc.RawRoPEParameters, &perLayer); err == nil && len(perLayer) > 0 {
c.RoPEParameters = perLayer
} else {
var flat RoPEParams
if err := json.Unmarshal(rc.RawRoPEParameters, &flat); err == nil {
c.RoPEParameters = map[string]RoPEParams{"default": flat}
if c.RoPETheta == 0 && flat.RopeTheta > 0 {
c.RoPETheta = flat.RopeTheta
}
}
}
}
return nil
}

func (c *Config) UnmarshalJSON(data []byte) error {
if err := c.unmarshalSection(data); err != nil {
return err
}
if err := json.Unmarshal(data, &c.Extra); err != nil {
Expand All @@ -75,7 +116,7 @@ func (c *Config) UnmarshalJSON(data []byte) error {
if textConfigRaw, ok := c.Extra["text_config"]; ok {
textConfigBytes, err := json.Marshal(textConfigRaw)
if err == nil {
_ = json.Unmarshal(textConfigBytes, (*wrapper)(c))
_ = c.unmarshalSection(textConfigBytes)
}
}
return nil
Expand Down
34 changes: 32 additions & 2 deletions models/transformer/model.go
Original file line number Diff line number Diff line change
Expand Up @@ -252,8 +252,8 @@ func (m *Model) detectCausalMask() bool {
// 3. Known decoder types:
switch modelType {
case "gemma", "gemma2", "gemma3", "gemma3_text", "gemma4", "gemma4_text",
"llama", "mistral", "qwen", "qwen2", "qwen3", "gpt2", "gpt_neox", "opt",
"phi", "phi3", "starcoder", "starcoder2", "falcon", "deepseek":
"llama", "mistral", "qwen", "qwen2", "qwen3", "qwen3_5", "qwen3_5_text",
"gpt2", "gpt_neox", "opt", "phi", "phi3", "starcoder", "starcoder2", "falcon", "deepseek":
return true
}

Expand Down Expand Up @@ -380,6 +380,8 @@ func (m *Model) LoadStoreFiltered(backend compute.Backend, store *model.Store, f
tieEmbeddings := false
if m.Config.ModelType == "gemma" || m.Config.ModelType == "gemma2" || m.Config.ModelType == "gemma3" || m.Config.ModelType == "gemma4" || m.Config.ModelType == "llama" {
tieEmbeddings = true
} else if m.Config.TieWordEmbeddings != nil {
tieEmbeddings = *m.Config.TieWordEmbeddings
} else if tieVal, ok := m.Config.Extra["tie_word_embeddings"]; ok {
if b, ok := tieVal.(bool); ok {
tieEmbeddings = b
Expand Down Expand Up @@ -581,6 +583,9 @@ func mapTensorName(safetensorsName string) (scopePath []string, varName string,
if safetensorsName == "norm.weight" {
return []string{"final_norm", "rms_norm"}, "scale", true
}
if safetensorsName == "lm_head.weight" {
return []string{"output", "dense"}, "weights", true
}

var layerNum int
var component, sub1, sub2 string
Expand Down Expand Up @@ -628,6 +633,31 @@ func mapTensorName(safetensorsName string) (scopePath []string, varName string,
}
}

// Parse linear attention blocks (e.g., Qwen3.5 Gated DeltaNet)
if n, err := fmt.Sscanf(safetensorsName, "layers.%d.linear_attn.%s", &layerNum, &sub1); n == 2 && err == nil {
layerScope := fmt.Sprintf("layer_%d", layerNum)
switch sub1 {
case "in_proj_qkv.weight":
return []string{layerScope, "linear_attn", "in_proj_qkv", "dense"}, "weights", true
case "in_proj_z.weight":
return []string{layerScope, "linear_attn", "in_proj_z", "dense"}, "weights", true
case "in_proj_b.weight":
return []string{layerScope, "linear_attn", "in_proj_b", "dense"}, "weights", true
case "in_proj_a.weight":
return []string{layerScope, "linear_attn", "in_proj_a", "dense"}, "weights", true
case "out_proj.weight":
return []string{layerScope, "linear_attn", "out_proj", "dense"}, "weights", true
case "conv1d.weight":
return []string{layerScope, "linear_attn"}, "conv1d_weight", true
case "A_log":
return []string{layerScope, "linear_attn"}, "A_log", true
case "dt_bias":
return []string{layerScope, "linear_attn"}, "dt_bias", true
case "norm.weight":
return []string{layerScope, "linear_attn", "norm"}, "weight", true
}
}

// Parse MLP blocks
if n, err := fmt.Sscanf(safetensorsName, "layers.%d.mlp.%s", &layerNum, &sub2); n == 2 && err == nil {
layerScope := fmt.Sprintf("layer_%d", layerNum)
Expand Down
80 changes: 78 additions & 2 deletions models/transformer/transformer.go
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,8 @@ func (m *Model) CreateGoMLXModel(scope *model.Scope) *mltransformer.Model {
arch = mltransformer.ArchitectureGemma4
case "gemma2", "gemma":
arch = mltransformer.ArchitectureGemma
case "qwen3_5", "qwen3_5_text":
arch = mltransformer.ArchitectureQwen35
default:
arch = mltransformer.ArchitectureGemma3
}
Expand All @@ -131,6 +133,43 @@ func (m *Model) CreateGoMLXModel(scope *model.Scope) *mltransformer.Model {
tm.WithRMSNormOffset(0.0)
tm.WithQueryKeyScale(1.0)
}
if arch == mltransformer.ArchitectureQwen35 {
tm.WithRMSNormOffset(1.0)
// Qwen3_5Attention always fuses an output gate into q_proj.
tm.WithAttnOutputGate(true)
convKernelDim := m.Config.LinearConvKernelDim
if convKernelDim == 0 {
convKernelDim = 4
}
keyHeadDim := m.Config.LinearKeyHeadDim
if keyHeadDim == 0 {
keyHeadDim = 128
}
valueHeadDim := m.Config.LinearValueHeadDim
if valueHeadDim == 0 {
valueHeadDim = 128
}
numKeyHeads := m.Config.LinearNumKeyHeads
if numKeyHeads == 0 {
numKeyHeads = 16
}
numValueHeads := m.Config.LinearNumValueHeads
if numValueHeads == 0 {
numValueHeads = 32
}
stateDType := dtypes.Float32
if m.Config.MambaSSMDType == "bfloat16" {
stateDType = dtypes.BFloat16
} else if m.Config.MambaSSMDType == "float16" {
stateDType = dtypes.Float16
}
tm.WithLinearConvKernelDim(convKernelDim).
WithLinearKeyHeadDim(keyHeadDim).
WithLinearValueHeadDim(valueHeadDim).
WithLinearNumKeyHeads(numKeyHeads).
WithLinearNumValueHeads(numValueHeads).
WithLinearStateDType(stateDType)
}
if m.Config.QueryPreAttnScalar > 0 {
tm.WithQueryKeyScale(1.0 / math.Sqrt(m.Config.QueryPreAttnScalar))
}
Expand All @@ -143,10 +182,27 @@ func (m *Model) CreateGoMLXModel(scope *model.Scope) *mltransformer.Model {
if len(m.Config.LayerTypes) > 0 {
layerTypes := make([]mltransformer.LayerType, m.Config.NumHiddenLayers)
for i, lt := range m.Config.LayerTypes {
if lt == "sliding_attention" {
switch lt {
case "sliding_attention":
layerTypes[i] = mltransformer.LocalLayer
} else {
case "linear_attention":
layerTypes[i] = mltransformer.LinearLayer
default:
layerTypes[i] = mltransformer.GlobalLayer
}
}
tm.WithLayerTypes(layerTypes)
} else if arch == mltransformer.ArchitectureQwen35 && m.Config.NumHiddenLayers > 0 {
interval := m.Config.FullAttentionInterval
if interval <= 0 {
interval = 4
}
layerTypes := make([]mltransformer.LayerType, m.Config.NumHiddenLayers)
for i := range layerTypes {
if (i+1)%interval == 0 {
layerTypes[i] = mltransformer.GlobalLayer
} else {
layerTypes[i] = mltransformer.LinearLayer
}
}
tm.WithLayerTypes(layerTypes)
Expand Down Expand Up @@ -180,6 +236,26 @@ func (m *Model) CreateGoMLXModel(scope *model.Scope) *mltransformer.Model {
} else {
fullRope = pos.NewRoPE(fp.RopeTheta)
}
} else if dp, ok := m.Config.RoPEParameters["default"]; ok {
theta := dp.RopeTheta
if theta == 0 {
theta = ropeTheta
}
partialFactor := dp.PartialRotaryFactor
if partialFactor == 0 && arch == mltransformer.ArchitectureQwen35 {
partialFactor = 0.25
}
if partialFactor > 0 && partialFactor < 1.0 {
if dp.RopeType == "proportional" {
fullRope = pos.NewRoPE(theta).WithPartialRotaryFactor(partialFactor)
} else {
rotatedDims := int(partialFactor * float64(headDim))
// Standard partial RoPE (e.g. Qwen3.5) computes inv_freq over rotatedDims (FrequencyDivisor=0).
fullRope = pos.NewRoPEWithDimRange(theta, 0, rotatedDims)
}
} else {
fullRope = pos.NewRoPE(theta)
}
}
if sp, ok := m.Config.RoPEParameters["sliding_attention"]; ok && sp.RopeTheta > 0 {
if sp.PartialRotaryFactor > 0 && sp.PartialRotaryFactor < 1.0 {
Expand Down
Loading
0