Skip to content

Commit c1daeaa

Browse files
authored
Fix BF16 vision encoder: keep OneHot values as float32 (#252)
## Summary ONNX OneHot op does not support bfloat16 for the values tensor. When building Gemma4 with `--dtype bf16`, the vision encoder fails to load because `CastLike` casts the OneHot values to bf16 before the op. ## Fix Keep OneHot values as float32 and cast the output to model dtype afterward for the subsequent MatMul. ## Testing - 13 gemma4 tests pass - BF16 build succeeds: `mobius build --model google/gemma-4-e2b-it --dtype bf16 --no-weights` Signed-off-by: Justin Chu <[email protected]>
1 parent 798d363 commit c1daeaa

1 file changed

Lines changed: 5 additions & 2 deletions

File tree

‎src/mobius/models/gemma4.py‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -445,9 +445,12 @@ def forward(
445445
# --- 5. One-hot weight matrix ----------------------------------------
446446
# weights[b, t, j] = 1/k² if patch t maps to bucket j, else 0
447447
# ONNX OneHot: (indices [B,T], depth scalar, values [off, on])
448+
# Keep values as float32 — OneHot doesn't support bfloat16.
448449
on_val = 1.0 / float(k2)
449-
one_hot_vals = op.CastLike(op.Constant(value_floats=[0.0, on_val]), vision_features)
450-
weights = op.OneHot(kernel_idxs, valid_depth, one_hot_vals) # [B, T, valid_depth]
450+
one_hot_vals = op.Constant(value_floats=[0.0, on_val])
451+
weights = op.OneHot(kernel_idxs, valid_depth, one_hot_vals) # [B, T, valid_depth] f32
452+
# Cast to model dtype for the subsequent MatMul
453+
weights = op.CastLike(weights, vision_features)
451454

452455
# --- 6. Weighted sum: [B, valid_depth, T] @ [B, T, D] ---------------
453456
weights_t = op.Transpose(weights, perm=[0, 2, 1]) # [B, valid_depth, T]

0 commit comments

Comments
 (0)