Skip to content

Commit 3777c18

Browse files
gramalingamCopilot
andauthored
Replace op.Constant(value_float=...) with Python float literals, use autocast (#166)
Continuation of PR #58 which established this pattern. Replace all 68 instances of op.Constant(value_float=X) across 30 files with plain Python float literals or float() expressions. This leverages onnxscript's auto-casting of Python scalars to match the dtype of the other operand in binary ops, which fixes dtype mismatches when models use bfloat16 or float16. Patterns replaced: - op.Constant(value_float=X) -> X (plain literal) - op.Constant(value_float=float(expr)) -> float(expr) - op.Constant(value_float=self.attr) -> self.attr - op.CastLike(op.Constant(value_float=X), ref) -> op.CastLike(X, ref) Note: This is part 1. (A similar change can be done for int/ints/floats, but will do that in separate PRs.) --------- Signed-off-by: G Ramalingam <grama@microsoft.com> Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
1 parent 2024747 commit 3777c18

28 files changed

Lines changed: 79 additions & 73 deletions

src/mobius/components/_ecapa_tdnn.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -313,7 +313,7 @@ def forward(self, op: builder.OpBuilder, hidden_states: ir.Value):
313313
op.ReduceSum(op.Mul(diff, diff), [2], keepdims=True),
314314
seq_length_float,
315315
)
316-
eps_const = op.Constant(value_float=self._eps)
316+
eps_const = self._eps
317317
std = op.Sqrt(op.Add(variance, eps_const))
318318

319319
# Expand mean and std to (batch, channels, time) for concatenation

src/mobius/components/_multimodal.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -182,7 +182,7 @@ def forward(
182182
axis=0,
183183
)
184184
zero_pad = op.Expand(
185-
op.CastLike(op.Constant(value_float=0.0), vision_embeddings),
185+
op.CastLike(0.0, vision_embeddings),
186186
pad_shape,
187187
)
188188
# [batch, vision_seq + 1, hidden]

src/mobius/components/_qwen25_vl_vision.py

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -252,7 +252,7 @@ def _emit_standard_attention(self, op, q, k, v, cu_seqlens, seq_len_val):
252252
v = op.Unsqueeze(v, [0])
253253

254254
# Build block-diagonal attention bias from cu_seqlens
255-
attn_bias = self._build_block_diagonal_bias(op, cu_seqlens, seq_len_val)
255+
attn_bias = self._build_block_diagonal_bias(op, cu_seqlens, seq_len_val, q)
256256
attn_bias = op.Unsqueeze(attn_bias, [0, 1]) # (1, 1, N, N)
257257

258258
# Scaled dot-product attention
@@ -301,11 +301,14 @@ def _apply_rotary(self, op, x, cos, sin):
301301

302302
return op.Concat(rot_x1, rot_x2, axis=-1)
303303

304-
def _build_block_diagonal_bias(self, op, cu_seqlens, seq_len):
304+
def _build_block_diagonal_bias(self, op, cu_seqlens, seq_len, dtype_ref):
305305
"""Build block-diagonal attention bias from cu_seqlens.
306306
307307
Creates a matrix where positions in the same sub-sequence have 0
308308
and positions in different sub-sequences have -inf.
309+
310+
Args:
311+
dtype_ref: reference tensor whose dtype the bias should match.
309312
"""
310313
# Create range indices
311314
indices = op.Range(
@@ -337,8 +340,9 @@ def _build_block_diagonal_bias(self, op, cu_seqlens, seq_len):
337340
same_segment = op.Equal(seg_row, seg_col)
338341

339342
# Convert to attention bias: 0 where same segment, -inf where different
340-
neg_inf = op.Constant(value_float=-1e9)
341-
zero = op.Constant(value_float=0.0)
343+
# CastLike before Where so only the scalar is cast (cheaper than post-broadcast)
344+
neg_inf = op.CastLike(-1e9, dtype_ref)
345+
zero = op.CastLike(0.0, dtype_ref)
342346
return op.Where(same_segment, zero, neg_inf)
343347

344348

src/mobius/components/_qwen3_vl_vision.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -292,8 +292,8 @@ def _emit_standard_attention(self, op, query, key, value, cu_seqlens, hidden_sta
292292
same_segment = op.Equal(segment_row, segment_column) # (total_seq, total_seq)
293293
attn_bias = op.Where(
294294
same_segment,
295-
op.Constant(value_float=0.0),
296-
op.Constant(value_float=-10000.0),
295+
op.CastLike(0.0, query),
296+
op.CastLike(-10000.0, query),
297297
)
298298
# Reshape for Attention: (1, 1, total_seq, total_seq)
299299
attn_bias = op.Unsqueeze(attn_bias, [0, 1])
@@ -609,12 +609,12 @@ def _interpolate_pos_embed(self, op, grid_thw):
609609
)
610610

611611
h_idxs = body_op.Div(
612-
body_op.Mul(h_range, body_op.Constant(value_float=n_minus_1)),
613-
body_op.Sub(H_f, body_op.Constant(value_float=1.0)),
612+
body_op.Mul(h_range, n_minus_1),
613+
body_op.Sub(H_f, 1.0),
614614
)
615615
w_idxs = body_op.Div(
616-
body_op.Mul(w_range, body_op.Constant(value_float=n_minus_1)),
617-
body_op.Sub(W_f, body_op.Constant(value_float=1.0)),
616+
body_op.Mul(w_range, n_minus_1),
617+
body_op.Sub(W_f, 1.0),
618618
)
619619

620620
# Floor/ceil indices
@@ -648,8 +648,8 @@ def _interpolate_pos_embed(self, op, grid_thw):
648648
idx_10 = body_op.Reshape(body_op.Add(bh_c2, wf2), [-1])
649649
idx_11 = body_op.Reshape(body_op.Add(bh_c2, wc2), [-1])
650650

651-
one_minus_dh = body_op.Sub(body_op.Constant(value_float=1.0), dh)
652-
one_minus_dw = body_op.Sub(body_op.Constant(value_float=1.0), dw)
651+
one_minus_dh = body_op.Sub(1.0, dh)
652+
one_minus_dw = body_op.Sub(1.0, dw)
653653
dh2 = body_op.Unsqueeze(dh, [1])
654654
omdh2 = body_op.Unsqueeze(one_minus_dh, [1])
655655
dw2 = body_op.Unsqueeze(dw, [0])
@@ -704,7 +704,7 @@ def _interpolate_pos_embed(self, op, grid_thw):
704704
body_op.Constant(value_ints=[0]),
705705
axis=0,
706706
)
707-
padded = body_op.Pad(pos_embeds, pads, body_op.Constant(value_float=0.0))
707+
padded = body_op.Pad(pos_embeds, pads, 0.0)
708708
padded.name = "padded_pos_embed"
709709
body_graph.outputs.append(padded)
710710

src/mobius/models/base.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -126,7 +126,7 @@ def forward(
126126
to=ir.DataType.INT32,
127127
) # [batch] INT32
128128
total_seq_len = op.Cast(
129-
op.Gather(op.Shape(attention_mask), op.Constant(value_int=1)),
129+
op.Gather(op.Shape(attention_mask), 1),
130130
to=ir.DataType.INT32,
131131
) # scalar INT32
132132

src/mobius/models/blip2.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -166,7 +166,7 @@ def forward(self, op: builder.OpBuilder, input_ids: ir.Value, image_features: ir
166166

167167
# Build indices to scatter image features into text positions
168168
mask_int = op.Cast(image_mask, to=7)
169-
cumsum = op.CumSum(mask_int, op.Constant(value_int=1))
169+
cumsum = op.CumSum(mask_int, 1)
170170
indices = op.Sub(cumsum, op.Constant(value_int=1))
171171
indices = op.Clip(indices, op.Constant(value_int=0))
172172

src/mobius/models/clip.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -294,18 +294,20 @@ def forward(
294294
hidden_states = self.embeddings(op, input_ids)
295295

296296
# Build causal attention bias (lower-triangular)
297+
# CastLike ensures the bias dtype matches hidden_states (fp16/bf16/fp32)
298+
# Cast the scalar *before* Expand so only a single element is cast
297299
seq_len = op.Shape(input_ids, start=1, end=2)
298300
_causal_mask = op.Trilu(
299301
op.Expand(
300-
op.Constant(value_float=0.0),
302+
op.CastLike(0.0, hidden_states),
301303
op.Concat(seq_len, seq_len, axis=0),
302304
),
303305
upper=0,
304306
)
305307
# Fill upper triangle with -inf
306308
neg_inf_mask = op.Trilu(
307309
op.Expand(
308-
op.Constant(value_float=-10000.0),
310+
op.CastLike(-10000.0, hidden_states),
309311
op.Concat(seq_len, seq_len, axis=0),
310312
),
311313
upper=1,

src/mobius/models/cogvideox.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -157,7 +157,7 @@ def forward(
157157
emb, num_outputs=6, axis=-1, _outputs=6
158158
)
159159

160-
one = op.Constant(value_float=1.0)
160+
one = 1.0
161161

162162
# Modulate video stream
163163
normed_h = self.norm(op, hidden_states)
@@ -197,7 +197,7 @@ def forward(self, op: builder.OpBuilder, hidden_states: ir.Value, temb: ir.Value
197197
emb = self.linear(op, emb)
198198
# CogVideoX shift-first order
199199
shift, scale = op.Split(emb, num_outputs=2, axis=-1, _outputs=2)
200-
one = op.Constant(value_float=1.0)
200+
one = 1.0
201201
hidden_states = self.norm(op, hidden_states)
202202
hidden_states = op.Mul(hidden_states, op.Add(one, op.Unsqueeze(scale, [1])))
203203
hidden_states = op.Add(hidden_states, op.Unsqueeze(shift, [1]))

src/mobius/models/cohere.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -127,7 +127,5 @@ def forward(
127127
# Scale logits by the model's configured logit_scale scalar
128128
# (HF default: 0.0625 = 1/16 for all Cohere models).
129129
# CastLike ensures the constant matches logits dtype (fp16/bf16/fp32).
130-
logits = op.Mul(
131-
logits, op.CastLike(op.Constant(value_float=float(self.logit_scale)), logits)
132-
)
130+
logits = op.Mul(logits, op.CastLike(float(self.logit_scale), logits))
133131
return logits, present_key_values

src/mobius/models/deepseek.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,7 @@ def forward(self, op: builder.OpBuilder, hidden_states: ir.Value):
9696
# Normalize weights (V3 with norm_topk_prob=True)
9797
if self.norm_topk_prob:
9898
weight_sum = op.ReduceSum(routing_weights, [-1], keepdims=True)
99-
eps = op.Constant(value_float=1e-20)
99+
eps = 1e-20
100100
routing_weights = op.Div(routing_weights, op.Add(weight_sum, eps))
101101

102102
# Apply routing scale

0 commit comments

Comments
 (0)