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
15 changes: 15 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -126,9 +126,24 @@ in the [GitHub releases](https://github.com/FluxML/Metalhead.jl/releases).
`vit_base_patch32_clip_quickgelu_224` (`laion400m_e32`, was `metaclip_400m`). The weights
of 0.9 are `timm/resnet50.tv2_in1k` and `timm/wide_resnet50_2.tv2_in1k`, as in the
[migration guide](https://fluxml.ai/Metalhead.jl/dev/migration/) (#391).
- The `A_log` of the Qwen3.5 linear-attention layers stays `Float32` under `eltype =
Float16`/`BFloat16` and `Flux.f16`/`bf16`, as in the checkpoints and in vLLM, instead of
being rounded to 16 bits. transformers rounds it, so half-precision outputs differ from
transformers' by far less than the half-precision noise itself (#342).

### Fixed

- A sequence of a batch that is all padding (a column of zeros in the `attention_mask`) no
longer gives NaN outputs in the language models, the BERT-like encoders and the CLIP and
SigLIP text encoders: its attention output is zero, as in transformers' `sdpa` (#342).
- Granite's `residual_multiplier`, `embedding_multiplier` and `logits_scaling` are no longer
rounded to the element type in `Float16`/`BFloat16`; as in PyTorch, the product is rounded,
not the scalar. A `residual_multiplier` of 0.22 had scaled every residual branch by 0.2197
in `BFloat16` (#342).
- A ViT with `init_values = 0` builds no layer scale, as in timm, where `0` is falsy; it built
a `LayerScale` of zeros that silenced every residual branch (#342).
- The convolutions of the multi-query attention of the MobileNetV4 hybrid models start from
`xavier_uniform`, as in timm, when they are initialized randomly (#342).
- Llama-2-era checkpoints (`NousResearch/Llama-2-7b-hf`), which store the
`rotary_emb.inv_freq` of each attention layer, load into the language models (Llama,
Qwen2, Qwen3, Gemma 3, Granite, and their mixtures of experts): transformers drops those
Expand Down
4 changes: 3 additions & 1 deletion docs/src/tutorials/language_models.md
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,9 @@ and the other decoding strategies of transformers are left to your loop (see the
The `i`-th is transformers' `output_hidden_states[i]`, and [`feature_info`](@ref) gives
the size and the module of each layer.
- The weights are converted to `eltype` (`Float32` by default) when they are loaded, whatever
their type on the Hub (often `bfloat16`).
their type on the Hub (often `bfloat16`). In `Float16` and `BFloat16` the weights of the
norms stay `Float32`, and so does the `A_log` of the linear attention of Qwen3.5, as in
its checkpoints.

## Configuration

Expand Down
18 changes: 14 additions & 4 deletions skills/port-hf-model/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,8 @@ Metalhead before it checks anything. Run Julia in one persistent session instead
without random initialization. Normalization constructors use it too.
- Allocate a custom parameter through `init_array(init, dims...)`, where `init(dims...)`
gives its normal Float32 initialization. Pass `norm = true` for a normalization
parameter that stays Float32 under `f16`/`bf16`. Wrap the whole initialization in the
parameter, or another one that the checkpoint keeps in float32 (Qwen3.5's `A_log`), that
stays Float32 under `f16`/`bf16`. Wrap the whole initialization in the
function, so that pretrained construction skips its random draws and temporaries.
An initializer applied after layer construction uses `init_parameter!(array, init)`.
These helpers preserve random initialization with `pretrained = false`.
Expand Down Expand Up @@ -327,6 +328,12 @@ normalization layers keep their parameters and statistics in `Float32` and norma
`NNlib.layernorm(g, b, x; dims, eps)` with `g` and `b` reshaped to broadcast against `x`.
These return the eltype of `x`, and throw on 16-bit parameters with 16-bit input. Don't
multiply by the weight yourself: a `Float32` weight times `Float16` data is `Float32`.
- **A parameter of another layer that the checkpoint keeps in float32** (Qwen3.5's `A_log`,
whose exponential is the decay rate of the linear attention) stays `Float32` too, though
the rest of its layer converts: give the layer `Flux.f16`/`Flux.bf16` methods that
convert each field (`f32(m.A_log, cx)`, `convert(field, cx)` for the others; see
`convert_except_A_log`), allocate it with `init_array(...; norm = true)`, and list it in
`partial` of `check_half_precision`.
- Other parameters (layer scale `gamma`, ResMLP's `Affine`) convert like any weight.
- **Constants built in the forward pass** (blur filters, pooling matrices, rotary tables,
masks) take `eltype(x)`, and scalars `oftype(x, c)` or `eltype(x)(c)`: a `Float32` array
Expand Down Expand Up @@ -474,9 +481,12 @@ first. The workflow is the one above, with these differences.
`window = attention_window(n, sliding_window)` to `NNlib.scaled_dot_product_attention`; no
mask is needed, and NNlib only goes through the keys of the windows. In a batch padded on
the right, a padding query whose window holds only padding attends to nothing: PyTorch
returns zeros there, and NNlib NaNs unless `sliding_window_q_lengths` gives it the
matching `q_lengths`. Give a padded fixture such queries (Gemma 3's `lengths = [9, 7, 2]`
with a window of 4).
returns zeros there, and NNlib NaNs unless `query_lengths(kv_lengths, n, sliding_window)`
gives it the matching `q_lengths`. Give a padded fixture such queries (Gemma 3's
`lengths = [9, 7, 2]` with a window of 4). The same goes for a sequence of all padding
(`kv_lengths` of 0), whose every query attends to nothing: pass
`q_lengths = query_lengths(kv_lengths, n)` wherever `kv_lengths` goes to NNlib's attention
(`test/models/all_padding.jl`).
- **Key-value cache** (`kvcache.jl`, `LayerCache` and `attend` in `layers.jl`). A decoder
whose layers are all full attention takes a `KVCache` if its attention layers and decoder
layers accept a fourth argument `cache = nothing`: rotate the queries and keys with
Expand Down
8 changes: 8 additions & 0 deletions src/Timm/efficientnet_builder.jl
Original file line number Diff line number Diff line change
Expand Up @@ -340,6 +340,14 @@ function efficientnet_init_weights!(model)
m.bias isa AbstractArray && fill!(m.bias, 0)
end
end
# timm calls `init_weights()` after the pass above: the convs of the multi-query
# attention (MobileNetV4 hybrids) start from xavier_uniform, not _init_weight_goog
for m in Flux.modules(model)
m isa MultiQueryAttention2d || continue
for conv in Flux.modules(m)
conv isa Conv && init_parameter!(conv.weight, Flux.glorot_uniform)
end
end
# CondConv routing layers: fan-in plus fan-out (CondConv2d inits itself)
for m in Flux.modules(model)
m isa CondConvResidual || continue
Expand Down
4 changes: 3 additions & 1 deletion src/Timm/vit.jl
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,9 @@ function vit_block(dim, num_heads; mlp_ratio, qkv_bias, proj_bias, init_values,
num_heads, vit_dense(dim => 3dim; bias = qkv_bias), dropout_or_identity(attn_drop),
vit_dense(dim => dim; bias = proj_bias), dropout_or_identity(proj_drop))
mlp = Mlp(dim, hidden; act_layer, bias = proj_bias, drop = proj_drop)
ls() = init_values === nothing ? identity : layer_scale(dim, init_values)
# timm tests `if init_values`: 0 builds an identity too
ls() = init_values === nothing || iszero(init_values) ? identity :
layer_scale(dim, init_values)
return ViTBlock(
init_layer(LayerNorm, dim; eps = norm_eps), attn, ls(), token_drop_path(drop_path),
init_layer(LayerNorm, dim; eps = norm_eps), mlp, ls(), token_drop_path(drop_path))
Expand Down
2 changes: 1 addition & 1 deletion src/Transformers/bert.jl
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@ function (m::BertSelfAttention)(x, kv_lengths)
heads(p) = reshape(p(x), :, m.num_attention_heads, n, b)
q, k, v = heads(m.query), heads(m.key), heads(m.value)
y = NNlib.scaled_dot_product_attention(q, k, v; kv_lengths,
fdrop = attention_fdrop(m.dropout, q))
q_lengths = query_lengths(kv_lengths, n), fdrop = attention_fdrop(m.dropout, q))
return reshape(y, :, n, b)
end

Expand Down
2 changes: 1 addition & 1 deletion src/Transformers/clip.jl
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ function (m::CLIPAttention)(x, kv_lengths = nothing; is_causal::Bool = false)
heads(p) = reshape(p(x), :, m.num_heads, n, b)
q, k, v = heads(m.q_proj), heads(m.k_proj), heads(m.v_proj)
y = NNlib.scaled_dot_product_attention(q, k, v; is_causal, kv_lengths,
fdrop = attention_fdrop(m.dropout, q))
q_lengths = query_lengths(kv_lengths, n), fdrop = attention_fdrop(m.dropout, q))
return m.out_proj(reshape(y, :, n, b))
end

Expand Down
2 changes: 1 addition & 1 deletion src/Transformers/gemma3.jl
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ function (m::Gemma3Attention)(x, position_embeddings, kv_lengths = nothing)
fdrop = attention_fdrop(m.attention_dropout, q),
scale = m.scaling, is_causal = true, kv_lengths,
window = attention_window(n, m.sliding_window),
q_lengths = sliding_window_q_lengths(kv_lengths, n, m.sliding_window))
q_lengths = query_lengths(kv_lengths, n, m.sliding_window))
return m.o_proj(reshape(y, :, n, b))
end

Expand Down
21 changes: 15 additions & 6 deletions src/Transformers/granite.jl
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,15 @@ function (m::GraniteAttention)(x, position_embeddings, kv_lengths = nothing,
return m.o_proj(reshape(y, :, n, b))
end

# The multipliers of Granite are Python floats, which torch applies to a half-precision
# tensor in Float32 and rounds only the result of, not the float: `T(0.22)` would be 0.2197
# in BFloat16. The residual's addition is a second rounding, as in torch.
mul_scalar(x::AbstractArray{T}, s) where {T} = T.(x .* promote_type(T, Float32)(s))
div_scalar(x::AbstractArray{T}, s) where {T} = T.(x ./ promote_type(T, Float32)(s))
function add_scaled(x, y::AbstractArray{T}, s) where {T}
return x .+ T.(y .* promote_type(T, Float32)(s))
end

# `LlamaDecoderLayer` whose attention and MLP outputs are multiplied by `residual_multiplier`.
@concrete struct GraniteDecoderLayer
self_attn
Expand All @@ -44,9 +53,10 @@ Flux.@layer GraniteDecoderLayer

function (m::GraniteDecoderLayer)(x, position_embeddings, kv_lengths = nothing,
cache = nothing)
r = eltype(x)(m.residual_multiplier)
x = x .+ m.self_attn(m.input_layernorm(x), position_embeddings, kv_lengths, cache) .* r
return x .+ m.mlp(m.post_attention_layernorm(x)) .* r
r = m.residual_multiplier
x = add_scaled(x,
m.self_attn(m.input_layernorm(x), position_embeddings, kv_lengths, cache), r)
return add_scaled(x, m.mlp(m.post_attention_layernorm(x)), r)
end

# `LlamaModel` whose token embeddings are multiplied by `embedding_multiplier`, and whose
Expand All @@ -62,7 +72,7 @@ Flux.@layer GraniteModel

function input_embeddings(m::GraniteModel, input_ids)
x = m.embed_tokens(input_ids)
return x .* eltype(x)(m.embedding_multiplier)
return mul_scalar(x, m.embedding_multiplier)
end

# The causal language models of Granite, whose logits are divided by `logits_scaling`.
Expand All @@ -76,8 +86,7 @@ Flux.@layer GraniteForCausalLM

function forward_head(m::GraniteForCausalLM, x; pre_logits::Bool = false)
pre_logits && return x
logits = m.lm_head(x)
return logits ./ eltype(logits)(m.logits_scaling)
return div_scalar(m.lm_head(x), m.logits_scaling)
end

"""
Expand Down
7 changes: 4 additions & 3 deletions src/Transformers/granitemoe.jl
Original file line number Diff line number Diff line change
Expand Up @@ -70,9 +70,10 @@ Flux.@layer GraniteMoeDecoderLayer

function (m::GraniteMoeDecoderLayer)(x, position_embeddings, kv_lengths = nothing,
cache = nothing)
r = eltype(x)(m.residual_multiplier)
x = x .+ m.self_attn(m.input_layernorm(x), position_embeddings, kv_lengths, cache) .* r
return x .+ feedforward(m, m.post_attention_layernorm(x)) .* r
r = m.residual_multiplier
x = add_scaled(x,
m.self_attn(m.input_layernorm(x), position_embeddings, kv_lengths, cache), r)
return add_scaled(x, feedforward(m, m.post_attention_layernorm(x)), r)
end

function feedforward(m::GraniteMoeDecoderLayer, x)
Expand Down
23 changes: 13 additions & 10 deletions src/Transformers/layers.jl
Original file line number Diff line number Diff line change
Expand Up @@ -99,16 +99,19 @@ rotary_tables(::Nothing, x, n) = nothing
attention_window(n, sliding_window) =
sliding_window === nothing || sliding_window >= n ? nothing : sliding_window

# In a batch padded on the right, the queries past `kv_lengths + sliding_window - 1` have
# only padding in their window. PyTorch's attention gives them zeros, as
# `NNlib.scaled_dot_product_attention` does to the queries past its `q_lengths`, rather
# than NaNs.
function sliding_window_q_lengths(kv_lengths, n, sliding_window)
(kv_lengths === nothing || sliding_window === nothing || sliding_window >= n) &&
return nothing
return min.(kv_lengths .+ (sliding_window - 1), n)
# The `q_lengths` of `NNlib.scaled_dot_product_attention` for `n` queries over the first
# `kv_lengths` keys of each sequence of a batch padded on the right, or `nothing` if no
# query needs them. A query with no key to attend to has NaNs in NNlib and zeros in
# PyTorch's attention, which `q_lengths` gives it too: every query of a sequence of all
# padding, and with a sliding window those past `kv_lengths + sliding_window - 1`.
function query_lengths(kv_lengths, n, sliding_window = nothing)
kv_lengths === nothing && return nothing
windowed = sliding_window !== nothing && sliding_window < n
(windowed || any(iszero, kv_lengths)) || return nothing
lengths = windowed ? min.(kv_lengths .+ (sliding_window - 1), n) : n
return ifelse.(iszero.(kv_lengths), 0, lengths)
end
ChainRulesCore.@non_differentiable sliding_window_q_lengths(::Any...)
ChainRulesCore.@non_differentiable query_lengths(::Any...)

to_device_of(x, a) = copyto!(similar(x, size(a)), a)
device_indices(x, index) = copyto!(similar(x, Int, size(index)), index)
Expand Down Expand Up @@ -174,7 +177,7 @@ end
# call without one: it attends to the new keys, not to the whole buffer.
function attend(q, k, v, kv_lengths, ::Nothing; kwargs...)
return NNlib.scaled_dot_product_attention(q, k, v; is_causal = true, kv_lengths,
kwargs...)
q_lengths = query_lengths(kv_lengths, size(q, 3)), kwargs...)
end

function attend(q, k, v, kv_lengths, cache::LayerCache; kwargs...)
Expand Down
2 changes: 1 addition & 1 deletion src/Transformers/modernbert.jl
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ function (m::ModernBertAttention)(x, position_embeddings, kv_lengths = nothing)
y = NNlib.scaled_dot_product_attention(q, k, v;
fdrop = attention_fdrop(m.out_drop, q), kv_lengths,
window = attention_window(n, m.sliding_window),
q_lengths = sliding_window_q_lengths(kv_lengths, n, m.sliding_window))
q_lengths = query_lengths(kv_lengths, n, m.sliding_window))
return m.out_drop(m.Wo(reshape(y, :, n, b)))
end

Expand Down
15 changes: 13 additions & 2 deletions src/Transformers/qwen3_5.jl
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ function (m::Qwen3_5Attention)(x, position_embeddings, kv_lengths = nothing)
k = apply_partial_rotary(k, cos, sin)
y = NNlib.scaled_dot_product_attention(q, k, v;
fdrop = attention_fdrop(m.attention_dropout, q),
is_causal = true, kv_lengths)
is_causal = true, kv_lengths, q_lengths = query_lengths(kv_lengths, n))
return m.o_proj(reshape(y, :, n, b) .* sigmoid.(gate))
end

Expand Down Expand Up @@ -122,6 +122,8 @@ keys and values of `in_proj_qkv`, after a causal depthwise convolution `conv1d`.
recurrent state, `(head_v_dim, head_k_dim)` per value head, decays by
`exp(-exp(A_log) * softplus(in_proj_a(x) + dt_bias))` at each token and is written with
the rate `sigmoid(in_proj_b(x))`. The output is normed and gated by `in_proj_z(x)`.
Under `f16`/`bf16` its `A_log` stays `Float32`, as in the checkpoints: in `BFloat16` it
would err by up to 1.5% on the decay rate `exp(A_log)`.
"""
@concrete struct Qwen3_5GatedDeltaNet
num_k_heads
Expand All @@ -141,6 +143,15 @@ the rate `sigmoid(in_proj_b(x))`. The output is normed and gated by `in_proj_z(x
end
Flux.@layer Qwen3_5GatedDeltaNet

# Unlike the norms, which stay Float32 whole, only `A_log` does here: the rest converts.
function convert_except_A_log(convert, m::Qwen3_5GatedDeltaNet, cx)
fields, rebuild = Functors.functor(m)
cast(k, c) = k === :A_log ? f32(c, cx) : convert(c, cx)
return rebuild(NamedTuple{keys(fields)}(map(cast, keys(fields), values(fields))))
end
Flux.f16(m::Qwen3_5GatedDeltaNet, cx) = convert_except_A_log(f16, m, cx)
Flux.bf16(m::Qwen3_5GatedDeltaNet, cx) = convert_except_A_log(bf16, m, cx)

function (m::Qwen3_5GatedDeltaNet)(x, kv_lengths = nothing)
x = mask_padding(x, kv_lengths)
_, n, b = size(x)
Expand Down Expand Up @@ -522,7 +533,7 @@ function qwen3_5_text_like(mlp; vocab_size, hidden_size, num_hidden_layers,
kernel = linear_conv_kernel_dim
conv1d = init_layer(Conv, (kernel,), conv_dim => conv_dim; groups = conv_dim,
pad = (kernel - 1, 0), bias = false, init)
A_log = init_array(linear_num_value_heads) do n
A_log = init_array(linear_num_value_heads; norm = true) do n
A = 0.01f0 .+ (16 - 0.01f0) .* rand(Float32, n)
return log.(A)
end
Expand Down
5 changes: 3 additions & 2 deletions src/Transformers/siglip.jl
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ function (m::SiglipAttention)(x, kv_lengths)
heads(p) = reshape(p(x), :, m.num_heads, n, b)
q, k, v = heads(m.q_proj), heads(m.k_proj), heads(m.v_proj)
y = NNlib.scaled_dot_product_attention(q, k, v; kv_lengths,
fdrop = attention_fdrop(m.dropout, q))
q_lengths = query_lengths(kv_lengths, n), fdrop = attention_fdrop(m.dropout, q))
return m.out_proj(reshape(y, :, n, b))
end

Expand Down Expand Up @@ -135,7 +135,8 @@ end

function (m::MultiheadAttention)(query, key, value; kv_lengths = nothing)
y = NNlib.scaled_dot_product_attention(in_projection(m, query, 1),
in_projection(m, key, 2), in_projection(m, value, 3); kv_lengths)
in_projection(m, key, 2), in_projection(m, value, 3); kv_lengths,
q_lengths = query_lengths(kv_lengths, size(query, 2)))
return m.out_proj(reshape(y, size(query))), nothing
end

Expand Down
4 changes: 2 additions & 2 deletions test/hub/initialization.jl
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ using .TestData: fixture
@testset "pretrained precision and weights" begin
# Cover Flux layers, custom parameters, normalization, stacked experts and tied weights.
for name in ("resnet_basic", "convnext_linear_mlp", "vit_dinov2_reg", "resmlp",
"gmlp", "efficientnet_cc_tf_same", "llama_options", "gemma3_tiny",
"granitemoe_tiny", "qwen3_5_tiny", "sam3_tiny", "vae_flux2_options",
"gmlp", "efficientnet_cc_tf_same", "mobilenetv4_hybrid_medium", "llama_options",
"gemma3_tiny", "granitemoe_tiny", "qwen3_5_tiny", "sam3_tiny", "vae_flux2_options",
"transformer_flux2_options", "autoencoder_kl_tiny", "autoencoder_kl_options",
"transformer_z_image_tiny", "transformer_z_image_options")
dir = fixture(name)
Expand Down
Loading
Loading