Исходный код СУБД RuDB — свободной СУБД с открытым исходным кодом на базе PostgreSQL
rudb
2 days ago bd039d1e92813358c5c5a1e346b49074baf513f2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation.  All rights reserved.
# Licensed under the MIT License.  See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
 
import os
import tempfile
import unittest
 
import numpy as np
import onnx
from bart_model_generator import create_bart_attention_sdpa
from bert_model_generator import create_bert_attention, create_bert_attention_pre_ln, create_tf2onnx_attention_3d
from dit_model_generator import create_dit_attention, create_dit_attention_no_k_transpose
from gpt2_model_generator import create_gpt2_attention, create_gpt2_attention_no_past
from model_loader import get_test_data_path
from onnx import numpy_helper
from parity_utilities import find_transformers_source
from qwen3_model_generator import create_qwen3_decoder_layer
 
if find_transformers_source():
    from fusion_options import FusionOptions
    from onnx_model import OnnxModel
    from optimizer import optimize_by_fusion, optimize_model
else:
    from onnxruntime.transformers.fusion_options import FusionOptions
    from onnxruntime.transformers.onnx_model import OnnxModel
    from onnxruntime.transformers.optimizer import optimize_by_fusion, optimize_model
 
 
class TestFusion(unittest.TestCase):
    def _validate_mha_input_types(self, optimized_model):
        """Verify all MultiHeadAttention inputs share the same element type.
 
        MHA's type parameter T binds Q, K, V to a single type. A mismatch
        (e.g., Q=float32, V=float16) produces a graph that ORT rejects at load time.
 
        Runs ONNX shape inference first to populate type info for intermediate
        tensors — without this, get_dtype returns None for outputs of internal
        nodes and the check would pass vacuously even if types are mismatched.
        """
        # Run shape inference to propagate types through standard ONNX ops
        # so that MHA inputs (from Reshape, Transpose, etc.) have type info.
        try:
            inferred = onnx.shape_inference.infer_shapes(optimized_model.model, check_type=True, strict_mode=False)
            optimized_model.model.CopyFrom(inferred)
            # Reset cached dtype dict so get_dtype picks up inferred types
            optimized_model._dtype_dict = None
        except Exception:
            pass  # Custom ops (com.microsoft) may cause warnings; proceed with available info
 
        for node in optimized_model.model.graph.node:
            if node.op_type == "MultiHeadAttention":
                input_types = []
                for inp_name in node.input[:3]:  # Q, K, V
                    if not inp_name:
                        continue
                    dtype = optimized_model.get_dtype(inp_name)
                    if dtype is not None:
                        input_types.append((inp_name, dtype))
                if len(input_types) >= 2:
                    first_name, first_dtype = input_types[0]
                    for inp_name, dtype in input_types[1:]:
                        self.assertEqual(
                            dtype,
                            first_dtype,
                            f"MHA input type mismatch: {first_name} has type {first_dtype} "
                            f"but {inp_name} has type {dtype}",
                        )
 
    def verify_fusion(self, optimized_model, expected_model_filename):
        optimized_model.topological_sort(is_deterministic=True)
 
        expected_model_path = os.path.join(os.path.dirname(__file__), "test_data", "models", expected_model_filename)
        expected_model = OnnxModel(onnx.load(expected_model_path))
        expected_model.topological_sort(is_deterministic=True)
 
        nodes = optimized_model.model.graph.node
        self.assertEqual(len(nodes), len(expected_model.model.graph.node))
 
        for i in range(len(nodes)):
            self.assertEqual(nodes[i], expected_model.model.graph.node[i])
 
        for expected_initializer in expected_model.model.graph.initializer:
            self.assertTrue(
                OnnxModel.has_same_value(
                    optimized_model.get_initializer(expected_initializer.name), expected_initializer
                )
            )
 
    def test_multi_head_attention_fusion(self):
        model = create_bert_attention()
        dir = "."
        model_path = os.path.join(dir, "attention.onnx")
        onnx.save(model, model_path)
        options = FusionOptions("bert")
        options.use_multi_head_attention = True
        options.use_raw_attention_mask(True)
        optimized_model = optimize_model(model_path, optimization_options=options)
        os.remove(model_path)
        self.verify_fusion(optimized_model, "attention_mha.onnx")
 
    def test_attention_fusion(self):
        model = create_bert_attention()
        dir = "."
        model_path = os.path.join(dir, "attention.onnx")
        onnx.save(model, model_path)
        options = FusionOptions("bert")
        options.use_raw_attention_mask(True)
        optimized_model = optimize_model(model_path, optimization_options=options)
        os.remove(model_path)
 
        self.verify_fusion(optimized_model, "attention_opt.onnx")
 
    def test_attention_fusion_pruned_model(self):
        model = create_bert_attention(
            input_hidden_size=16,
            num_heads=2,
            pruned_qk_hidden_size=8,
            pruned_v_hidden_size=8,
        )
        dir = "."
        model_path = os.path.join(dir, "pruned_attention.onnx")
        onnx.save(model, model_path)
        options = FusionOptions("bert")
        options.use_raw_attention_mask(True)
        optimized_model = optimize_model(model_path, optimization_options=options)
        os.remove(model_path)
 
        self.verify_fusion(optimized_model, "pruned_attention_opt.onnx")
 
    def test_attention_fusion_reverse_add_order(self):
        model = create_bert_attention(
            input_hidden_size=16,
            num_heads=2,
            pruned_qk_hidden_size=8,
            pruned_v_hidden_size=8,
            switch_add_inputs=True,
        )
        dir = "."
        model_path = os.path.join(dir, "bert_attention_reverse_add_order.onnx")
        onnx.save(model, model_path)
        options = FusionOptions("bert")
        options.use_raw_attention_mask(True)
        optimized_model = optimize_model(model_path, optimization_options=options)
        os.remove(model_path)
 
        # reverse add input order will get same optimized model
        self.verify_fusion(optimized_model, "pruned_attention_opt.onnx")
 
    def test_attention_fusion_for_varied_qkv_dimensions(self):
        model = create_bert_attention(
            input_hidden_size=16,
            num_heads=2,
            pruned_qk_hidden_size=24,
            pruned_v_hidden_size=16,
        )
        dir = "."
        model_path = os.path.join(dir, "attention_with_varied_qkv.onnx")
        onnx.save(model, model_path)
        options = FusionOptions("bert")
        options.use_raw_attention_mask(True)
        optimized_model = optimize_model(model_path, optimization_options=options)
        os.remove(model_path)
 
        self.verify_fusion(optimized_model, "attention_with_varied_qkv_opt.onnx")
 
    def test_attention_fusion_for_varied_qkv_dimensions_with_wrong_opt_parameters(self):
        model = create_bert_attention(
            input_hidden_size=16,
            num_heads=2,
            pruned_qk_hidden_size=24,
            pruned_v_hidden_size=16,
        )
        dir = "."
        model_path = os.path.join(dir, "attention_with_varied_qkv.onnx")
        onnx.save(model, model_path)
 
        # wrong num_heads and hidden_size
        options = FusionOptions("bert")
        options.use_raw_attention_mask(True)
        optimized_model = optimize_model(model_path, "bert", num_heads=8, hidden_size=8, optimization_options=options)
 
        os.remove(model_path)
 
        self.verify_fusion(optimized_model, "attention_with_varied_qkv_opt.onnx")
 
    def test_3d_attention_fusion_tf2onnx_model(self):
        model = create_tf2onnx_attention_3d()
        dir = "."
        model_path = os.path.join(dir, "bert_3d_attention.onnx")
        onnx.save(model, model_path)
        optimized_model = optimize_model(model_path, model_type="bert_tf", num_heads=4, hidden_size=16)
        os.remove(model_path)
 
        self.verify_fusion(optimized_model, "bert_3d_attention_opt.onnx")
 
    def test_attention_fusion_pre_ln(self):
        """Test attention fusion for pre-layer-norm first block.
 
        In a pre-LN model the first block has no Add before the first
        LayerNormalization — the graph input feeds LN directly.
        """
        model = create_bert_attention_pre_ln()
        dir = tempfile.mkdtemp()
        model_path = os.path.join(dir, "pre_ln_attention.onnx")
        onnx.save(model, model_path)
        options = FusionOptions("bert")
        options.use_raw_attention_mask(True)
        optimized_model = optimize_model(model_path, opt_level=0, optimization_options=options)
        os.remove(model_path)
 
        attention_nodes = [n for n in optimized_model.model.graph.node if n.op_type == "Attention"]
        self.assertEqual(len(attention_nodes), 1, "Expected exactly 1 fused Attention node")
        num_heads_attr = next((a for a in attention_nodes[0].attribute if a.name == "num_heads"), None)
        self.assertIsNotNone(num_heads_attr)
        self.assertEqual(num_heads_attr.i, 2)
 
    def test_attention_fusion_pre_ln_reverse_add_order(self):
        """Pre-LN fusion with reversed Add input ordering."""
        model = create_bert_attention_pre_ln(switch_add_inputs=True)
        dir = tempfile.mkdtemp()
        model_path = os.path.join(dir, "pre_ln_attention_reverse.onnx")
        onnx.save(model, model_path)
        options = FusionOptions("bert")
        options.use_raw_attention_mask(True)
        optimized_model = optimize_model(model_path, opt_level=0, optimization_options=options)
        os.remove(model_path)
 
        attention_nodes = [n for n in optimized_model.model.graph.node if n.op_type == "Attention"]
        self.assertEqual(len(attention_nodes), 1, "Expected exactly 1 fused Attention node")
        num_heads_attr = next((a for a in attention_nodes[0].attribute if a.name == "num_heads"), None)
        self.assertIsNotNone(num_heads_attr)
        self.assertEqual(num_heads_attr.i, 2)
 
    def test_attention_fusion_pre_ln_with_skiplayernorm(self):
        """Pre-LN fusion when SkipLayerNorm fusion runs first (exercises Change 3).
 
        The optimizer runs fuse_skip_layer_norm before fuse_attention.  When enabled,
        the Add + LayerNorm after the residual becomes a SkipLayerNormalization node,
        and attention fusion must handle that anchor type.
        """
        model = create_bert_attention_pre_ln()
        dir = tempfile.mkdtemp()
        model_path = os.path.join(dir, "pre_ln_attention_skiplayernorm.onnx")
        onnx.save(model, model_path)
        options = FusionOptions("bert")
        options.use_raw_attention_mask(True)
        options.enable_skip_layer_norm = True
        optimized_model = optimize_model(model_path, opt_level=0, optimization_options=options)
        os.remove(model_path)
 
        attention_nodes = [n for n in optimized_model.model.graph.node if n.op_type == "Attention"]
        self.assertEqual(len(attention_nodes), 1, "Expected exactly 1 fused Attention node with SkipLN anchor")
        num_heads_attr = next((a for a in attention_nodes[0].attribute if a.name == "num_heads"), None)
        self.assertIsNotNone(num_heads_attr)
        self.assertEqual(num_heads_attr.i, 2)
 
    def test_gpt2_attention_fusion(self):
        hidden_size = 64
        num_heads = 4
        for add_order in [False, True]:
            for enable_skip_layer_norm_fusion in [False, True]:
                model = create_gpt2_attention(
                    hidden_size=hidden_size,
                    num_heads=num_heads,
                    switch_add_inputs=add_order,
                )
                dir = "."
                model_path = os.path.join(dir, "gpt2_attention.onnx")
                onnx.save(model, model_path)
 
                options = FusionOptions("gpt2")
                options.enable_skip_layer_norm = enable_skip_layer_norm_fusion
 
                optimized_model = optimize_model(
                    model_path,
                    model_type="gpt2",
                    num_heads=num_heads,
                    hidden_size=hidden_size,
                    optimization_options=options,
                )
 
                optimized_model.topological_sort()
                os.remove(model_path)
 
                model_suffix = ""
                if add_order and enable_skip_layer_norm_fusion:
                    model_suffix = "add_opt_skiplayernorm"
                elif add_order and not enable_skip_layer_norm_fusion:
                    model_suffix = "add_opt_no_skiplayernorm"
                elif not add_order and enable_skip_layer_norm_fusion:
                    model_suffix = "opt_skiplayernorm"
                else:
                    model_suffix = "opt_no_skiplayernorm"
 
                model_name = f"gpt2_attention_{model_suffix}.onnx"
                self.verify_fusion(optimized_model, model_name)
 
    def test_bart_attention_sdpa_fusion(self):
        hidden_size = 16
        num_heads = 4
        for with_mask in [True, False]:
            model = create_bart_attention_sdpa(
                hidden_size=hidden_size,
                num_heads=num_heads,
                with_mask=with_mask,
            )
 
            options = FusionOptions("bart")
            # Disable SkipLayerNorm fusion to match real SDPA BART behaviour,
            # where symbolic shape inference fails and the attention fusion
            # anchor is a plain LayerNormalization node.
            options.enable_skip_layer_norm = False
 
            optimized_model = optimize_by_fusion(
                model,
                model_type="bart",
                num_heads=num_heads,
                hidden_size=hidden_size,
                optimization_options=options,
            )
 
            attn_nodes = [n for n in optimized_model.model.graph.node if n.op_type == "Attention"]
            self.assertEqual(
                len(attn_nodes),
                1,
                f"Expected 1 Attention node for with_mask={with_mask}, got {len(attn_nodes)}",
            )
 
            attn = attn_nodes[0]
            num_heads_attr = next((a for a in attn.attribute if a.name == "num_heads"), None)
            self.assertIsNotNone(num_heads_attr)
            self.assertEqual(num_heads_attr.i, num_heads)
 
            unidirectional_attr = next((a for a in attn.attribute if a.name == "unidirectional"), None)
            if with_mask:
                # With mask → decoder self-attention → unidirectional=1
                self.assertIsNotNone(unidirectional_attr)
                self.assertEqual(unidirectional_attr.i, 1)
            else:
                # No mask → encoder attention → unidirectional=0
                if unidirectional_attr is not None:
                    self.assertEqual(unidirectional_attr.i, 0)
 
    def test_gpt2_attention_no_past_fusion(self):
        hidden_size = 64
        num_heads = 4
        for add_cast in [True, False]:
            for switch_add_inputs in [False, True]:
                model = create_gpt2_attention_no_past(
                    hidden_size=hidden_size,
                    num_heads=num_heads,
                    switch_add_inputs=switch_add_inputs,
                    add_cast=add_cast,
                )
                dir = "."
                model_path = os.path.join(dir, "gpt2_attention_no_past.onnx")
                onnx.save(model, model_path)
 
                options = FusionOptions("gpt2")
 
                optimized_model = optimize_model(
                    model_path,
                    model_type="gpt2",
                    num_heads=num_heads,
                    hidden_size=hidden_size,
                    optimization_options=options,
                )
 
                os.remove(model_path)
 
                model_suffix = "add_opt" if switch_add_inputs else "opt"
                model_name = f"gpt2_attention_no_past_{model_suffix}.onnx"
                self.verify_fusion(optimized_model, model_name)
 
    def test_megatron_gpt2_attention_fusion(self):
        for enable_skip_layer_norm_fusion in [False, True]:
            path = get_test_data_path("models", "gpt2_megatron.onnx")
            model = onnx.load(path)
 
            options = FusionOptions("gpt2")
            options.enable_skip_layer_norm = enable_skip_layer_norm_fusion
 
            optimized_model = optimize_by_fusion(
                model,
                model_type="gpt2",
                num_heads=0,
                hidden_size=0,
                optimization_options=options,
            )
 
            model_suffix = ""
            if enable_skip_layer_norm_fusion:
                model_suffix = "opt_skiplayernorm"
            else:
                model_suffix = "opt_no_skiplayernorm"
 
            model_name = f"gpt2_megatron_{model_suffix}.onnx"
            self.verify_fusion(optimized_model, model_name)
 
    def test_qwen3_normalization_fusion(self):
        """Test Qwen3 decoder layer optimization.
 
        Verifies that the optimizer fuses RMSNorm patterns into SimplifiedLayerNormalization.
        """
        hidden_size = 64
        num_heads = 8
        num_kv_heads = 2
 
        model = create_qwen3_decoder_layer(
            hidden_size=hidden_size,
            num_heads=num_heads,
            num_kv_heads=num_kv_heads,
        )
 
        dir = tempfile.mkdtemp()
        model_path = os.path.join(dir, "qwen3_decoder.onnx")
        onnx.save(model, model_path)
 
        options = FusionOptions("qwen3")
        optimized_model = optimize_model(
            model_path,
            model_type="qwen3",
            num_heads=num_heads,
            hidden_size=hidden_size,
            optimization_options=options,
        )
 
        os.remove(model_path)
 
        nodes = optimized_model.model.graph.node
        sln_count = sum(1 for n in nodes if n.op_type == "SimplifiedLayerNormalization")
 
        # 4 RMSNorm patterns all fuse into SimplifiedLayerNormalization:
        # pre-attn, Q-norm, K-norm, post-attn.
        self.assertEqual(
            sln_count,
            4,
            f"Expected 4 SimplifiedLayerNormalization, got {sln_count}",
        )
 
    def test_qwen3_rotary_embedding_fusion(self):
        """Test Qwen3 RotaryEmbedding fusion for on-the-fly RoPE with dynamic Slice indices.
 
        Verifies that the optimizer fuses:
          - On-the-fly RoPE (MatMul → Cos/Sin → Mul(scaling)) into RotaryEmbedding nodes
          - Both Q and K paths get RotaryEmbedding fusion (2 total)
        """
        hidden_size = 64
        num_heads = 8
        num_kv_heads = 2
 
        model = create_qwen3_decoder_layer(
            hidden_size=hidden_size,
            num_heads=num_heads,
            num_kv_heads=num_kv_heads,
            include_rope=True,
        )
 
        dir = tempfile.mkdtemp()
        model_path = os.path.join(dir, "qwen3_decoder_rope.onnx")
        onnx.save(model, model_path)
 
        options = FusionOptions("qwen3")
        optimized_model = optimize_model(
            model_path,
            model_type="qwen3",
            num_heads=num_heads,
            hidden_size=hidden_size,
            optimization_options=options,
        )
 
        os.remove(model_path)
 
        nodes = optimized_model.model.graph.node
        rope_count = sum(1 for n in nodes if n.op_type == "RotaryEmbedding")
        sln_count = sum(1 for n in nodes if n.op_type == "SimplifiedLayerNormalization")
 
        self.assertEqual(
            rope_count,
            2,
            f"Expected 2 RotaryEmbedding (Q + K), got {rope_count}",
        )
        self.assertEqual(
            sln_count,
            4,
            f"Expected 4 SimplifiedLayerNormalization, got {sln_count}",
        )
 
    def test_qwen3_rotary_embedding_fusion_with_expand(self):
        """Test RotaryEmbedding fusion when inv_freq path includes Cast → Expand → Where nodes."""
        hidden_size = 64
        num_heads = 8
        num_kv_heads = 2
 
        model = create_qwen3_decoder_layer(
            hidden_size=hidden_size,
            num_heads=num_heads,
            num_kv_heads=num_kv_heads,
            include_rope=True,
            include_expand_in_inv_freq=True,
        )
 
        dir = tempfile.mkdtemp()
        model_path = os.path.join(dir, "qwen3_decoder_rope_expand.onnx")
        onnx.save(model, model_path)
 
        options = FusionOptions("qwen3")
        optimized_model = optimize_model(
            model_path,
            model_type="qwen3",
            num_heads=num_heads,
            hidden_size=hidden_size,
            optimization_options=options,
        )
 
        os.remove(model_path)
 
        nodes = optimized_model.model.graph.node
        rope_count = sum(1 for n in nodes if n.op_type == "RotaryEmbedding")
 
        self.assertEqual(
            rope_count,
            2,
            f"Expected 2 RotaryEmbedding (Q + K) with Expand in inv_freq path, got {rope_count}",
        )
 
    def test_qwen3_rotary_embedding_fusion_negative_dynamic_inv_freq(self):
        """Test that RotaryEmbedding fusion gracefully falls back when inv_freq is a dynamic graph input.
 
        When inv_freq is not a constant initializer (e.g., computed dynamically), the fusion cannot
        extract the values at optimization time and should skip fusion without crashing.
        """
        hidden_size = 64
        num_heads = 8
        num_kv_heads = 2
 
        model = create_qwen3_decoder_layer(
            hidden_size=hidden_size,
            num_heads=num_heads,
            num_kv_heads=num_kv_heads,
            include_rope=True,
            inv_freq_as_graph_input=True,
        )
 
        dir = tempfile.mkdtemp()
        model_path = os.path.join(dir, "qwen3_decoder_rope_dynamic_inv_freq.onnx")
        onnx.save(model, model_path)
 
        options = FusionOptions("qwen3")
        optimized_model = optimize_model(
            model_path,
            model_type="qwen3",
            num_heads=num_heads,
            hidden_size=hidden_size,
            optimization_options=options,
        )
 
        os.remove(model_path)
 
        nodes = optimized_model.model.graph.node
        rope_count = sum(1 for n in nodes if n.op_type == "RotaryEmbedding")
 
        # Fusion should gracefully skip — 0 RotaryEmbedding nodes, no crash
        self.assertEqual(
            rope_count,
            0,
            f"Expected 0 RotaryEmbedding when inv_freq is dynamic, got {rope_count}",
        )
 
    def test_qwen3_rotary_embedding_fusion_cache_numerical_validation(self):
        """Test that the generated cos/sin caches have correct values.
 
        Verifies the mathematical correctness of the precomputed caches:
            freqs[pos, i] = pos * inv_freq[i]
            cos_cache[pos, i] = cos(freqs[pos, i]) * scaling
            sin_cache[pos, i] = sin(freqs[pos, i]) * scaling
        """
        hidden_size = 64
        num_heads = 8
        num_kv_heads = 2
        head_dim = hidden_size // num_heads  # 8
        half_dim = head_dim // 2  # 4
 
        model = create_qwen3_decoder_layer(
            hidden_size=hidden_size,
            num_heads=num_heads,
            num_kv_heads=num_kv_heads,
            include_rope=True,
        )
 
        dir = tempfile.mkdtemp()
        model_path = os.path.join(dir, "qwen3_decoder_rope_numerical.onnx")
        onnx.save(model, model_path)
 
        options = FusionOptions("qwen3")
        optimized_model = optimize_model(
            model_path,
            model_type="qwen3",
            num_heads=num_heads,
            hidden_size=hidden_size,
            optimization_options=options,
        )
 
        os.remove(model_path)
 
        # Verify cos/sin cache initializers exist
        cos_init = optimized_model.get_initializer("cos_cache")
        sin_init = optimized_model.get_initializer("sin_cache")
        self.assertIsNotNone(cos_init, "cos_cache initializer not found after fusion")
        self.assertIsNotNone(sin_init, "sin_cache initializer not found after fusion")
 
        cos_data = numpy_helper.to_array(cos_init)
        sin_data = numpy_helper.to_array(sin_init)
 
        # Verify shape: (max_seq_len, head_dim // 2)
        self.assertEqual(cos_data.shape[1], half_dim, f"cos_cache dim 1 should be {half_dim}")
        self.assertEqual(sin_data.shape[1], half_dim, f"sin_cache dim 1 should be {half_dim}")
        self.assertEqual(cos_data.shape, sin_data.shape, "cos_cache and sin_cache shapes should match")
 
        # Recompute expected values from inv_freq (must match the generator's formula)
        inv_freq = 1.0 / (10000.0 ** (np.arange(0, head_dim, 2, dtype=np.float32) / head_dim))
        scaling = 1.0  # attention_scaling in the test generator
 
        # Spot-check at several positions
        for pos in [0, 1, 7, 100, 1000]:
            expected_freqs = pos * inv_freq
            expected_cos = np.cos(expected_freqs) * scaling
            expected_sin = np.sin(expected_freqs) * scaling
            np.testing.assert_allclose(
                cos_data[pos],
                expected_cos,
                rtol=1e-6,
                err_msg=f"cos_cache mismatch at position {pos}",
            )
            np.testing.assert_allclose(
                sin_data[pos],
                expected_sin,
                rtol=1e-6,
                err_msg=f"sin_cache mismatch at position {pos}",
            )
 
    def test_dit_attention_fusion(self):
        """Test DiT attention fusion for F5-TTS-style pattern (FP32, with K pre-transpose)."""
        model = create_dit_attention(
            batch_size=2,
            seq_len=4,
            num_heads=4,
            head_dim=8,
            scale=100.0,
            use_fp16_casts=False,
        )
        dir = tempfile.mkdtemp()
        model_path = os.path.join(dir, "dit_attention.onnx")
        onnx.save(model, model_path)
 
        optimized_model = optimize_model(model_path, model_type="mmdit", opt_level=0)
        os.remove(model_path)
 
        # Validate the optimized model produces a type-consistent fused graph.
        self._validate_mha_input_types(optimized_model)
 
        mha_nodes = [n for n in optimized_model.model.graph.node if n.op_type == "MultiHeadAttention"]
        self.assertEqual(len(mha_nodes), 1, "Expected exactly 1 fused MultiHeadAttention node")
 
        # Verify num_heads attribute
        num_heads_attr = next((a for a in mha_nodes[0].attribute if a.name == "num_heads"), None)
        self.assertIsNotNone(num_heads_attr)
        self.assertEqual(num_heads_attr.i, 4)
 
        # Verify scale attribute
        scale_attr = next((a for a in mha_nodes[0].attribute if a.name == "scale"), None)
        self.assertIsNotNone(scale_attr)
        self.assertAlmostEqual(scale_attr.f, 100.0, places=5)
 
        # Verify no Softmax remains (it should be absorbed into MHA)
        softmax_count = sum(1 for n in optimized_model.model.graph.node if n.op_type == "Softmax")
        self.assertEqual(softmax_count, 0, "Softmax should be fused into MultiHeadAttention")
 
    def test_dit_attention_fusion_with_fp16_casts(self):
        """Test DiT attention fusion with FP16 Cast nodes around Softmax."""
        model = create_dit_attention(
            batch_size=2,
            seq_len=4,
            num_heads=4,
            head_dim=8,
            scale=100.0,
            use_fp16_casts=True,
        )
        dir = tempfile.mkdtemp()
        model_path = os.path.join(dir, "dit_attention_fp16.onnx")
        onnx.save(model, model_path)
 
        optimized_model = optimize_model(model_path, model_type="mmdit", opt_level=0)
        os.remove(model_path)
 
        # Validate MHA input types — catches mixed-dtype fused graphs (e.g.,
        # Q=float32 but V=float16) that pass structural assertions but fail at ORT load.
        self._validate_mha_input_types(optimized_model)
 
        mha_nodes = [n for n in optimized_model.model.graph.node if n.op_type == "MultiHeadAttention"]
        self.assertEqual(len(mha_nodes), 1, "Expected exactly 1 fused MultiHeadAttention node")
 
        # Verify num_heads and scale
        num_heads_attr = next((a for a in mha_nodes[0].attribute if a.name == "num_heads"), None)
        self.assertIsNotNone(num_heads_attr)
        self.assertEqual(num_heads_attr.i, 4)
 
        scale_attr = next((a for a in mha_nodes[0].attribute if a.name == "scale"), None)
        self.assertIsNotNone(scale_attr)
        self.assertAlmostEqual(scale_attr.f, 100.0, places=5)
 
        # Verify no Softmax remains (it should be absorbed into MHA)
        softmax_count = sum(1 for n in optimized_model.model.graph.node if n.op_type == "Softmax")
        self.assertEqual(softmax_count, 0, "Softmax should be fused into MultiHeadAttention")
 
    def test_dit_attention_fusion_custom_scale(self):
        """Test DiT attention fusion with standard 1/sqrt(d_k) scale."""
        head_dim = 8
        standard_scale = 1.0 / (head_dim**0.5)
        model = create_dit_attention(
            batch_size=1,
            seq_len=4,
            num_heads=4,
            head_dim=head_dim,
            scale=standard_scale,
            use_fp16_casts=False,
        )
        dir = tempfile.mkdtemp()
        model_path = os.path.join(dir, "dit_attention_standard_scale.onnx")
        onnx.save(model, model_path)
 
        optimized_model = optimize_model(model_path, model_type="mmdit", opt_level=0)
        os.remove(model_path)
 
        self._validate_mha_input_types(optimized_model)
 
        mha_nodes = [n for n in optimized_model.model.graph.node if n.op_type == "MultiHeadAttention"]
        self.assertEqual(len(mha_nodes), 1, "Expected exactly 1 fused MultiHeadAttention node")
 
        scale_attr = next((a for a in mha_nodes[0].attribute if a.name == "scale"), None)
        self.assertIsNotNone(scale_attr)
        self.assertAlmostEqual(scale_attr.f, standard_scale, places=5)
 
        # Verify no Softmax remains (it should be absorbed into MHA)
        softmax_count = sum(1 for n in optimized_model.model.graph.node if n.op_type == "Softmax")
        self.assertEqual(softmax_count, 0, "Softmax should be fused into MultiHeadAttention")
 
    def test_dit_attention_fusion_no_k_transpose(self):
        """Test DiT attention fusion when K is natively BNHS (no explicit Transpose node)."""
        model = create_dit_attention_no_k_transpose(
            batch_size=2,
            seq_len=4,
            num_heads=4,
            head_dim=8,
            scale=100.0,
        )
        dir = tempfile.mkdtemp()
        model_path = os.path.join(dir, "dit_attention_no_k_transpose.onnx")
        onnx.save(model, model_path)
 
        optimized_model = optimize_model(model_path, model_type="mmdit", opt_level=0)
        os.remove(model_path)
 
        self._validate_mha_input_types(optimized_model)
 
        mha_nodes = [n for n in optimized_model.model.graph.node if n.op_type == "MultiHeadAttention"]
        self.assertEqual(len(mha_nodes), 1, "Expected exactly 1 fused MultiHeadAttention node")
 
        # Verify scale attribute
        scale_attr = next((a for a in mha_nodes[0].attribute if a.name == "scale"), None)
        self.assertIsNotNone(scale_attr)
        self.assertAlmostEqual(scale_attr.f, 100.0, places=5)
 
        # Verify no Softmax remains
        softmax_count = sum(1 for n in optimized_model.model.graph.node if n.op_type == "Softmax")
        self.assertEqual(softmax_count, 0, "Softmax should be fused into MultiHeadAttention")
 
        # Verify the fusion added a Transpose for K (BNHS -> BNSH)
        transpose_nodes = [n for n in optimized_model.model.graph.node if n.op_type == "Transpose"]
        has_bnhs_to_bnsh = any(OnnxModel.get_node_attribute(t, "perm") == [0, 1, 3, 2] for t in transpose_nodes)
        self.assertTrue(has_bnhs_to_bnsh, "Fusion should add Transpose(BNHS->BNSH) for K")
 
 
if __name__ == "__main__":
    unittest.main()