Исходный код СУБД RuDB — свободной СУБД с открытым исходным кодом на базе PostgreSQL
rudb
3 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
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation.  All rights reserved.
# Licensed under the MIT License.  See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
# Copyright 2020 The HuggingFace Inc. team
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
# -------------------------------------------------------------------------
 
"""
Shared utilities for ONNX Attention op (opset 23/24) tests.
 
Contains configuration, ONNX graph builders, reference implementation,
and parity check helpers used by both GQA and MHA test modules.
"""
 
import math
import os
from dataclasses import dataclass
 
import torch
from einops import rearrange, repeat
from onnx import TensorProto, helper
 
from onnxruntime import (
    InferenceSession,
    SessionOptions,
    get_available_providers,
    get_build_info,
)
 
# Set seed for reproducibility
torch.manual_seed(0)
 
# Reduces number of tests to run for faster pipeline checks
pipeline_mode = os.getenv("PIPELINE_MODE", "1") == "1"
 
# When quick build is used, flash attention only supports head_size=128
quick_build = ", quick-build=" in get_build_info()
 
enable_debug_print = quick_build
 
# #################################################################################################
#  Configuration and Helper Classes
# #################################################################################################
 
 
# --- ONNX and Torch/Numpy Dtype Mappings ---
ONNX_TENSOR_TYPE_MAP = {
    "float32": TensorProto.FLOAT,
    "float16": TensorProto.FLOAT16,
    "bfloat16": TensorProto.BFLOAT16,
    "int32": TensorProto.INT32,
    "int8": TensorProto.INT8,
    "int4": TensorProto.UINT8,
}
 
TORCH_DTYPE_TO_ONNX_MAP = {
    torch.float32: TensorProto.FLOAT,
    torch.float16: TensorProto.FLOAT16,
    torch.bfloat16: TensorProto.BFLOAT16,
    torch.int32: TensorProto.INT32,
    torch.int8: TensorProto.INT8,
}
 
 
@dataclass
class AttentionConfig:
    batch_size: int
    q_sequence_length: int
    kv_sequence_length: int
    q_num_heads: int
    kv_num_heads: int
    head_size: int
    v_head_size: int = 0  # 0 means same as head_size; set explicitly for asymmetric Q/V head sizes
    is_causal: int = 0
    past_kv_sequence_length: int = 0
    softcap: float = 0.0
    kv_cache_type: str = ""
    has_attn_mask: bool = False
    attn_mask_dims: int = 2  # 2D, 3D, or 4D boolean mask
    attn_mask_type: str = "bool"  # "bool" for GQA path, "additive" for MHA path
    has_nonpad_kv_seqlen: bool = False  # Opset 24: nonpad_kv_seqlen input
    use_4d_bnsh: bool = False  # Use 4D [B, num_heads, seq, head_size] inputs instead of 3D
    broadcast_mask_batch: bool = False  # Use batch dim 1 in 4D mask for broadcasting
    broadcast_mask_heads: bool = False  # Use heads dim 1 in 4D mask for broadcasting
 
 
# #################################################################################################
#  ONNX Graph Creation
# #################################################################################################
 
 
def create_attention_node_and_io(
    config: AttentionConfig,
    ort_type,
    is_past=False,
    output_qk: int | None = None,
):
    """
    Create ONNX Attention op node and I/O definitions for testing.
 
    output_qk: when set to an int in {0, 1, 2, 3}, enables the optional 4th
    output `output_qk` and sets the `qk_matmul_output_mode` attribute to that
    value. The numbering uses the post-onnx#7913 spec semantics that this PR
    establishes:
        0 = kQK            (raw scale*QK pre-softcap)
        1 = kPostSoftCap   (post-softcap, pre-mask/bias)
        2 = kPostMaskBias  (post-mask/bias, pre-softmax)
        3 = kPostSoftMax   (post-softmax)
    When None (the default), the 4th output is not emitted and the attribute
    defaults to 0. Any other int value (negative, or >= 4) raises an
    AssertionError.
 
    NOTE: API contract — `output_qk=None` (the default) DISABLES the 4th
    output. `output_qk=k` for k in {0, 1, 2, 3} ENABLES it and selects the
    corresponding mode (`output_qk=0` is raw-QK). Passing anything else —
    including the C++ `kNone = -1` sentinel from attention_parameters.h, or
    any unknown mode like `4`/`5` — raises immediately rather than silently
    binding the 4th output (the unfused CUDA kernel would populate it as
    raw-QK regardless of an out-of-range mode).
 
    ONNX Attention op (opset 23/24) inputs:
    - 0: Q (query) - required
    - 1: K (key) - required
    - 2: V (value) - required
    - 3: attn_mask - optional
    - 4: past_key - optional
    - 5: past_value - optional
 
    ONNX Attention op outputs:
    - 0: Y (output)
    - 1: present_key (optional)
    - 2: present_value (optional)
    - 3: output_qk (optional)
    """
    # For ONNX Attention op, present KV cache grows (not fixed buffer like GQA)
    if is_past:
        present_kv_seqlen = config.past_kv_sequence_length + config.kv_sequence_length
    else:  # Prompt (no past KV cache)
        present_kv_seqlen = config.kv_sequence_length
 
    # Effective v_head_size: defaults to head_size when not explicitly set
    effective_v_head_size = config.v_head_size or config.head_size
 
    if not config.kv_cache_type:
        config.kv_cache_type = {
            TensorProto.FLOAT16: "float16",
            TensorProto.BFLOAT16: "bfloat16",
            TensorProto.FLOAT: "float32",
        }.get(ort_type, "float16")
 
    # --- Node Definition ---
    outputs = [
        "output",
        "present_key",
        "present_value",
    ]
 
    # Strict validation: only None or one of the known QKMatMulOutputMode values
    # {0, 1, 2, 3} is accepted. Anything else (including the C++ `kNone = -1`
    # sentinel, or unknown modes like 4/5) raises immediately, so callers can't
    # silently bind a 4th output the unfused CUDA kernel would populate as raw-QK.
    if output_qk is not None:
        assert output_qk in (0, 1, 2, 3), f"output_qk must be one of {{0, 1, 2, 3}} or None, got {output_qk!r}"
        enable_output_qk = True
    else:
        enable_output_qk = False
    if enable_output_qk:
        outputs.append("output_qk")
 
    # ONNX Attention op inputs: Q, K, V, attn_mask, past_key, past_value
    # attn_mask is used as padding mask (additive bias: 0.0 for valid, -inf for masked)
    inputs = [
        "query",
        "key",
        "value",
        "attn_mask" if config.has_attn_mask else "",
        "past_key" if is_past else "",
        "past_value" if is_past else "",
        "nonpad_kv_seqlen" if config.has_nonpad_kv_seqlen else "",
    ]
 
    # Remove trailing empty strings
    while inputs and inputs[-1] == "":
        inputs.pop()
 
    # ONNX Attention op attributes (opset 23/24)
    node = helper.make_node(
        op_type="Attention",
        inputs=inputs,
        outputs=outputs,
        name="Attention_0",
        is_causal=config.is_causal,
        kv_num_heads=config.kv_num_heads,
        q_num_heads=config.q_num_heads,
        softcap=config.softcap,
        qk_matmul_output_mode=output_qk if enable_output_qk else 0,
        domain="",  # ai.onnx domain
    )
 
    # --- Graph Inputs ---
    if config.use_4d_bnsh:
        # 4D BNSH inputs: [batch, num_heads, seq_len, head_size]
        graph_input = [
            helper.make_tensor_value_info(
                "query",
                ort_type,
                [config.batch_size, config.q_num_heads, config.q_sequence_length, config.head_size],
            ),
            helper.make_tensor_value_info(
                "key",
                ort_type,
                [config.batch_size, config.kv_num_heads, config.kv_sequence_length, config.head_size],
            ),
            helper.make_tensor_value_info(
                "value",
                ort_type,
                [config.batch_size, config.kv_num_heads, config.kv_sequence_length, effective_v_head_size],
            ),
        ]
    else:
        # 3D inputs: [batch, seq_len, hidden_size]
        q_hidden_size = config.q_num_heads * config.head_size
        kv_hidden_size = config.kv_num_heads * config.head_size
        v_hidden_size = config.kv_num_heads * effective_v_head_size
        graph_input = [
            helper.make_tensor_value_info(
                "query", ort_type, [config.batch_size, config.q_sequence_length, q_hidden_size]
            ),
            helper.make_tensor_value_info(
                "key", ort_type, [config.batch_size, config.kv_sequence_length, kv_hidden_size]
            ),
            helper.make_tensor_value_info(
                "value", ort_type, [config.batch_size, config.kv_sequence_length, v_hidden_size]
            ),
        ]
 
    if isinstance(config.kv_cache_type, torch.dtype):
        cache_ort_type = TORCH_DTYPE_TO_ONNX_MAP[config.kv_cache_type]
    else:
        cache_ort_type = ONNX_TENSOR_TYPE_MAP[config.kv_cache_type]
 
    # attn_mask for ONNX Attention op
    if config.has_attn_mask:
        mask_seq_len = present_kv_seqlen
 
        # Determine mask ONNX type
        if config.attn_mask_type == "bool":
            mask_ort_type = TensorProto.BOOL
        else:
            mask_ort_type = ort_type  # additive mask uses same type as Q/K/V
 
        # Mask shapes differ between GQA (bool) and MHA (additive/bool) paths:
        # Per ONNX spec, 2D mask is [q_seq, total_seq] for all paths.
        # 3D and 4D are the same for both paths.
        # ONNX broadcasting aligns from the right: 3D [A, B, C] → [_, A, B, C] where A=heads
        is_gqa = config.kv_num_heads != config.q_num_heads
        if config.attn_mask_type == "bool" and is_gqa:
            if config.attn_mask_dims == 2:
                mask_shape = [config.q_sequence_length, mask_seq_len]
            elif config.attn_mask_dims == 3:
                mask_shape = [config.q_num_heads, config.q_sequence_length, mask_seq_len]
            else:  # 4D
                mask_batch = 1 if config.broadcast_mask_batch else config.batch_size
                mask_heads = 1 if config.broadcast_mask_heads else config.q_num_heads
                mask_shape = [mask_batch, mask_heads, config.q_sequence_length, mask_seq_len]
        else:  # additive, or bool on MHA path
            if config.attn_mask_dims == 2:
                mask_shape = [config.q_sequence_length, mask_seq_len]
            elif config.attn_mask_dims == 3:
                # 3D aligns to [_, heads, q_seq, total_seq] — dim 0 must be 1 or num_heads
                mask_shape = [config.q_num_heads, config.q_sequence_length, mask_seq_len]
            else:  # 4D
                mask_batch = 1 if config.broadcast_mask_batch else config.batch_size
                mask_heads = 1 if config.broadcast_mask_heads else config.q_num_heads
                mask_shape = [mask_batch, mask_heads, config.q_sequence_length, mask_seq_len]
        graph_input.append(helper.make_tensor_value_info("attn_mask", mask_ort_type, mask_shape))
 
    # past_key and past_value for ONNX Attention op
    # Shape: [batch, num_heads, past_seq_len, head_size] (4D BNSH format)
    if is_past:
        past_k_shape = [config.batch_size, config.kv_num_heads, config.past_kv_sequence_length, config.head_size]
        past_v_shape = [config.batch_size, config.kv_num_heads, config.past_kv_sequence_length, effective_v_head_size]
        graph_input.extend(
            [
                helper.make_tensor_value_info("past_key", cache_ort_type, past_k_shape),
                helper.make_tensor_value_info("past_value", cache_ort_type, past_v_shape),
            ]
        )
 
    # nonpad_kv_seqlen for Opset 24: int64 tensor [batch_size]
    if config.has_nonpad_kv_seqlen:
        graph_input.append(helper.make_tensor_value_info("nonpad_kv_seqlen", TensorProto.INT64, [config.batch_size]))
 
    # --- Graph Outputs ---
    output_k_shape = [config.batch_size, config.kv_num_heads, present_kv_seqlen, config.head_size]
    output_v_shape = [config.batch_size, config.kv_num_heads, present_kv_seqlen, effective_v_head_size]
 
    if config.use_4d_bnsh:
        output_shape = [config.batch_size, config.q_num_heads, config.q_sequence_length, effective_v_head_size]
    else:
        output_shape = [config.batch_size, config.q_sequence_length, config.q_num_heads * effective_v_head_size]
 
    graph_output = [
        helper.make_tensor_value_info("output", ort_type, output_shape),
        helper.make_tensor_value_info("present_key", cache_ort_type, output_k_shape),
        helper.make_tensor_value_info("present_value", cache_ort_type, output_v_shape),
    ]
 
    if output_qk is not None:
        graph_output.append(
            helper.make_tensor_value_info(
                "output_qk",
                ort_type,
                [config.batch_size, config.q_num_heads, config.q_sequence_length, present_kv_seqlen],
            )
        )
 
    return node, graph_input, graph_output
 
 
def _get_opset_version(config: AttentionConfig):
    """Return 24 when nonpad_kv_seqlen is used, otherwise 23."""
    return 24 if config.has_nonpad_kv_seqlen else 23
 
 
def create_attention_graph_prompt(config: AttentionConfig, ort_type, output_qk: int | None = None):
    """Create ONNX graph for prompt phase (no past KV cache)."""
    node, graph_input, graph_output = create_attention_node_and_io(config, ort_type, is_past=False, output_qk=output_qk)
    graph = helper.make_graph([node], "Attention_Graph", graph_input, graph_output)
    opset = _get_opset_version(config)
    model = helper.make_model(graph, opset_imports=[helper.make_opsetid("", opset)])
    return model.SerializeToString()
 
 
def create_attention_graph_past(config: AttentionConfig, ort_type):
    """Create ONNX graph for decoding phase (with past KV cache)."""
    node, graph_input, graph_output = create_attention_node_and_io(config, ort_type, is_past=True)
    graph = helper.make_graph([node], "Attention_Graph", graph_input, graph_output)
    opset = _get_opset_version(config)
    model = helper.make_model(graph, opset_imports=[helper.make_opsetid("", opset)])
    return model.SerializeToString()
 
 
# #################################################################################################
#  ONNX Runtime Execution Functions
# #################################################################################################
 
 
def bind_tensor(io_binding, name, tensor, device, ort_type):
    # Helper to bind a tensor to ONNX Runtime based on its device and type
    if tensor is None:
        return
    # Assuming tensor is a torch tensor. This works for both CPU and GPU tensors.
    io_binding.bind_input(
        name,
        tensor.device.type,
        0,
        ort_type,
        tuple(tensor.shape),
        tensor.data_ptr(),
    )
 
 
def bind_output_tensor(io_binding, name, tensor, device, ort_type):
    if tensor is None:
        return
    io_binding.bind_output(
        name,
        tensor.device.type,
        0,
        ort_type,
        tuple(tensor.shape),
        tensor.data_ptr(),
    )
 
 
def _get_out_dtype(ort_type):
    """Get the torch dtype for output tensors given an ORT type."""
    if ort_type == TensorProto.BFLOAT16:
        return torch.bfloat16
    elif ort_type == TensorProto.FLOAT16:
        return torch.float16
    else:
        return torch.float32
 
 
def _get_mask_ort_type(config: AttentionConfig, ort_type):
    """Get the ORT type for the attention mask."""
    if config.attn_mask_type == "bool":
        return TensorProto.BOOL
    else:
        return ort_type
 
 
def attention_prompt_func(
    q,
    k,
    v,
    config: AttentionConfig,
    attn_mask,
    ep,
    device,
    ort_type=TensorProto.FLOAT16,
    nonpad_kv_seqlen=None,
    output_qk: int | None = None,
):
    """
    Run ONNX Attention op for prompt phase (no past KV cache).
 
    Args:
        q: Query tensor [batch, q_seq_len, q_num_heads, head_size]
        k: Key tensor [batch, kv_seq_len, kv_num_heads, head_size]
        v: Value tensor [batch, kv_seq_len, kv_num_heads, head_size]
        config: AttentionConfig with model parameters
        attn_mask: Optional attention mask tensor
        ep: Execution provider (e.g., "CUDAExecutionProvider")
        device: Device string (e.g., "cuda")
        ort_type: ONNX tensor type
        nonpad_kv_seqlen: Optional int64 tensor [batch_size] for opset 24
        output_qk: When set to an int in {0, 1, 2, 3}, enables the optional
            4th output `output_qk` and sets the `qk_matmul_output_mode`
            attribute to that value. The numbering is the post-onnx#7913
            spec semantics established by this PR:
                0 = kQK            (raw scale*QK pre-softcap)
                1 = kPostSoftCap   (post-softcap, pre-mask/bias)
                2 = kPostMaskBias  (post-mask/bias, pre-softmax)
                3 = kPostSoftMax   (post-softmax)
            The function then returns a 4-tuple
            (out, present_k, present_v, qk) instead of the usual 3-tuple.
            Pass None (the default) to DISABLE. Any other int value
            (negative, or >= 4) raises an AssertionError; do NOT pass the
            C++ `kNone = -1` sentinel — use Python `None`.
    """
    if not config.kv_cache_type:
        config.kv_cache_type = {
            TensorProto.FLOAT16: "float16",
            TensorProto.BFLOAT16: "bfloat16",
            TensorProto.FLOAT: "float32",
        }.get(ort_type, "float16")
 
    onnx_model_str = create_attention_graph_prompt(
        config=config,
        ort_type=ort_type,
        output_qk=output_qk,
    )
 
    # Reshape inputs for ONNX graph
    if config.use_4d_bnsh:
        # 4D BNSH: [batch, num_heads, seq_len, head_size]
        q_input = q.transpose(1, 2).contiguous()  # BSNH → BNSH
        k_input = k.transpose(1, 2).contiguous()
        v_input = v.transpose(1, 2).contiguous()
    else:
        # 3D: [batch, seq_len, hidden_size]
        q_input = torch.reshape(q, (config.batch_size, config.q_sequence_length, -1))
        k_input = torch.reshape(k, (config.batch_size, config.kv_sequence_length, -1))
        v_input = torch.reshape(v, (config.batch_size, config.kv_sequence_length, -1))
 
    sess_options = SessionOptions()
    ort_session = InferenceSession(onnx_model_str, sess_options, providers=[ep])
    io_binding = ort_session.io_binding()
 
    # Bind inputs
    bind_tensor(io_binding, "query", q_input, device, ort_type)
    bind_tensor(io_binding, "key", k_input, device, ort_type)
    bind_tensor(io_binding, "value", v_input, device, ort_type)
 
    # Bind optional attention mask
    if config.has_attn_mask and attn_mask is not None:
        mask_ort_type = _get_mask_ort_type(config, ort_type)
        bind_tensor(io_binding, "attn_mask", attn_mask, device, mask_ort_type)
 
    # Bind optional nonpad_kv_seqlen (opset 24+)
    if config.has_nonpad_kv_seqlen:
        if nonpad_kv_seqlen is None:
            raise ValueError(
                "Invariant violated: config.has_nonpad_kv_seqlen=True but the nonpad_kv_seqlen "
                "tensor is None. Either provide the tensor or set has_nonpad_kv_seqlen=False."
            )
        bind_tensor(io_binding, "nonpad_kv_seqlen", nonpad_kv_seqlen, device, TensorProto.INT64)
 
    # Bind Outputs
    effective_v_head_size = config.v_head_size or config.head_size
    output_hidden_size = config.q_num_heads * effective_v_head_size
    out_dtype = _get_out_dtype(ort_type)
 
    if config.use_4d_bnsh:
        out_torch = torch.zeros(
            (config.batch_size, config.q_num_heads, config.q_sequence_length, effective_v_head_size),
            dtype=out_dtype,
            device=device,
        )
    else:
        out_torch = torch.zeros(
            (config.batch_size, config.q_sequence_length, output_hidden_size), dtype=out_dtype, device=device
        )
    bind_output_tensor(io_binding, "output", out_torch, device, ort_type)
 
    # present KV shape for prompt (no past)
    present_seqlen = config.kv_sequence_length
    present_k_dims = [config.batch_size, config.kv_num_heads, present_seqlen, config.head_size]
    present_v_dims = [config.batch_size, config.kv_num_heads, present_seqlen, effective_v_head_size]
 
    # Determine dtype for cache tensors
    cache_dtype = out_dtype
    if isinstance(config.kv_cache_type, torch.dtype):
        cache_ort_type = TORCH_DTYPE_TO_ONNX_MAP[config.kv_cache_type]
    else:
        cache_ort_type = ONNX_TENSOR_TYPE_MAP[config.kv_cache_type]
 
    present_k = torch.zeros(tuple(present_k_dims), dtype=cache_dtype, device=device)
    present_v = torch.zeros(tuple(present_v_dims), dtype=cache_dtype, device=device)
    bind_output_tensor(io_binding, "present_key", present_k, device, cache_ort_type)
    bind_output_tensor(io_binding, "present_value", present_v, device, cache_ort_type)
 
    output_qk_tensor = None
    # `create_attention_node_and_io` (called above via `create_attention_graph_prompt`)
    # has already validated `output_qk in {0, 1, 2, 3}` or None. Just gate on `is not None`.
    output_qk_enabled = output_qk is not None
    if output_qk_enabled:
        output_qk_tensor = torch.zeros(
            (config.batch_size, config.q_num_heads, config.q_sequence_length, config.kv_sequence_length),
            dtype=out_dtype,
            device=device,
        )
        bind_output_tensor(io_binding, "output_qk", output_qk_tensor, device, ort_type)
 
    ort_session.run_with_iobinding(io_binding)
    # run_with_iobinding() is asynchronous on CUDA: ORT submits work to its own
    # CUDA stream and returns. The torch tensors we hand back live on torch's
    # default stream, so reading them without an explicit cross-stream sync can
    # observe partially-written GPU memory under load (e.g., full-suite runs).
    # synchronize_outputs() blocks until ORT's stream is done writing the bound
    # output tensors, eliminating that read-before-write race.
    io_binding.synchronize_outputs()
 
    if output_qk_enabled:
        return out_torch, present_k, present_v, output_qk_tensor
    return out_torch, present_k, present_v
 
 
def attention_past_func(
    q,
    past_k,
    past_v,
    new_k,
    new_v,
    config: AttentionConfig,
    attn_mask,
    ep,
    device,
    ort_type=TensorProto.FLOAT16,
):
    """
    Run ONNX Attention op for decoding phase (with past KV cache).
 
    Args:
        q: Query tensor [batch, q_seq_len, q_num_heads, head_size]
        past_k: Past key tensor [batch, kv_num_heads, past_seq_len, head_size]
        past_v: Past value tensor [batch, kv_num_heads, past_seq_len, head_size]
        new_k: New key tensor [batch, kv_seq_len, kv_num_heads, head_size]
        new_v: New value tensor [batch, kv_seq_len, kv_num_heads, head_size]
        config: AttentionConfig with model parameters
        attn_mask: Optional attention mask tensor
        ep: Execution provider (e.g., "CUDAExecutionProvider")
        device: Device string (e.g., "cuda")
        ort_type: ONNX tensor type
    """
    if not config.kv_cache_type:
        config.kv_cache_type = {
            TensorProto.FLOAT16: "float16",
            TensorProto.BFLOAT16: "bfloat16",
            TensorProto.FLOAT: "float32",
        }.get(ort_type, "float16")
 
    onnx_model_str = create_attention_graph_past(
        config=config,
        ort_type=ort_type,
    )
 
    # Reshape inputs for ONNX graph
    if config.use_4d_bnsh:
        # 4D BNSH: [batch, num_heads, seq_len, head_size]
        q_input = q.transpose(1, 2).contiguous()  # BSNH → BNSH
        new_k_input = new_k.transpose(1, 2).contiguous()
        new_v_input = new_v.transpose(1, 2).contiguous()
    else:
        # 3D: [batch, seq_len, hidden_size]
        q_input = torch.reshape(q, (config.batch_size, config.q_sequence_length, -1))
        new_k_input = torch.reshape(new_k, (config.batch_size, config.kv_sequence_length, -1))
        new_v_input = torch.reshape(new_v, (config.batch_size, config.kv_sequence_length, -1))
 
    sess_options = SessionOptions()
    ort_session = InferenceSession(onnx_model_str, sess_options, providers=[ep])
    io_binding = ort_session.io_binding()
 
    # Total sequence length for present KV
    total_seq_len = config.past_kv_sequence_length + config.kv_sequence_length
 
    # Bind inputs
    bind_tensor(io_binding, "query", q_input, device, ort_type)
    bind_tensor(io_binding, "key", new_k_input, device, ort_type)
    bind_tensor(io_binding, "value", new_v_input, device, ort_type)
 
    # Bind optional attention mask
    if config.has_attn_mask and attn_mask is not None:
        mask_ort_type = _get_mask_ort_type(config, ort_type)
        bind_tensor(io_binding, "attn_mask", attn_mask, device, mask_ort_type)
 
    # Bind past_key and past_value
    if isinstance(config.kv_cache_type, torch.dtype):
        cache_ort_type = TORCH_DTYPE_TO_ONNX_MAP[config.kv_cache_type]
    else:
        cache_ort_type = ONNX_TENSOR_TYPE_MAP[config.kv_cache_type]
 
    # past_k and past_v should be sliced to actual past length
    past_len = config.past_kv_sequence_length
    past_k_sliced = past_k[:, :, :past_len, :].contiguous()
    past_v_sliced = past_v[:, :, :past_len, :].contiguous()
    bind_tensor(io_binding, "past_key", past_k_sliced, device, cache_ort_type)
    bind_tensor(io_binding, "past_value", past_v_sliced, device, cache_ort_type)
 
    # Bind Outputs
    effective_v_head_size = config.v_head_size or config.head_size
    output_hidden_size = config.q_num_heads * effective_v_head_size
    out_dtype = _get_out_dtype(ort_type)
 
    if config.use_4d_bnsh:
        out_torch = torch.zeros(
            (config.batch_size, config.q_num_heads, config.q_sequence_length, effective_v_head_size),
            dtype=out_dtype,
            device=device,
        )
    else:
        out_torch = torch.zeros(
            (config.batch_size, config.q_sequence_length, output_hidden_size), dtype=out_dtype, device=device
        )
    bind_output_tensor(io_binding, "output", out_torch, device, ort_type)
 
    # present KV shape (past + new)
    present_seqlen = total_seq_len
    present_k_dims = [config.batch_size, config.kv_num_heads, present_seqlen, config.head_size]
    present_v_dims = [config.batch_size, config.kv_num_heads, present_seqlen, effective_v_head_size]
 
    cache_dtype = out_dtype
    present_k = torch.zeros(tuple(present_k_dims), dtype=cache_dtype, device=device)
    present_v = torch.zeros(tuple(present_v_dims), dtype=cache_dtype, device=device)
    bind_output_tensor(io_binding, "present_key", present_k, device, cache_ort_type)
    bind_output_tensor(io_binding, "present_value", present_v, device, cache_ort_type)
 
    ort_session.run_with_iobinding(io_binding)
    # See note above attention_prompt_func's run_with_iobinding call: this sync
    # is required to avoid a read-before-write race on torch's default stream.
    io_binding.synchronize_outputs()
 
    return out_torch, present_k, present_v
 
 
# #################################################################################################
#  Reference Attention Implementation
# #################################################################################################
 
 
def construct_causal_mask(seqlen_q, seqlen_k, device, past_seqlen=0):
    """Construct a causal mask for ONNX Attention upper-left alignment."""
    row_idx = rearrange(torch.arange(seqlen_q, device=device, dtype=torch.long), "s -> s 1")
    col_idx = torch.arange(seqlen_k, device=device, dtype=torch.long)
    return col_idx > row_idx + past_seqlen
 
 
def attention_ref(
    q,
    k,
    v,
    key_padding_mask=None,
    attn_bias=None,
    causal=False,
    softcap=0.0,
    past_seqlen=0,
):
    """
    Reference implementation of scaled dot-product attention with GQA support.
 
    Args:
        q: Query tensor [batch, seq_q, num_heads, head_size]
        k: Key tensor [batch, seq_k, kv_num_heads, head_size]
        v: Value tensor [batch, seq_k, kv_num_heads, head_size]
        key_padding_mask: Boolean mask [batch, seq_k] - True for valid, False for masked
        attn_bias: Additive attention bias [broadcastable to batch, num_heads, seq_q, seq_k]
        causal: Whether to apply causal masking
        softcap: Softcap value for attention scores (0.0 = disabled)
        past_seqlen: Number of past K/V tokens before q[0] for causal masking.
 
    Returns:
        output: Attention output [batch, seq_q, num_heads, head_size]
        attention: Attention weights [batch, num_heads, seq_q, seq_k]
    """
    dtype_og = q.dtype
    q, k, v = q.float(), k.float(), v.float()
    seqlen_q, seqlen_k = q.shape[1], k.shape[1]
 
    # Repeat K/V heads for Grouped-Query Attention
    if k.shape[2] != q.shape[2]:
        k = repeat(k, "b s h d -> b s (h g) d", g=q.shape[2] // k.shape[2])
    if v.shape[2] != q.shape[2]:
        v = repeat(v, "b s h d -> b s (h g) d", g=q.shape[2] // v.shape[2])
 
    scores = torch.einsum("bthd,bshd->bhts", q, k) / math.sqrt(q.shape[-1])
 
    # Corrected ordering per onnx/onnx#7867: QK → softcap → add bias/mask → softmax
    # Softcap must be applied before mask so that -inf mask values are not
    # squashed to finite -softcap, which would leak probability to masked positions.
    if softcap > 0:
        scores = (scores / softcap).tanh() * softcap
 
    if attn_bias is not None:
        scores = scores + attn_bias.float()
 
    if key_padding_mask is not None:
        scores.masked_fill_(rearrange(~key_padding_mask, "b s -> b 1 1 s"), float("-inf"))
 
    if causal:
        causal_mask = construct_causal_mask(seqlen_q, seqlen_k, q.device, past_seqlen=past_seqlen)
        scores.masked_fill_(causal_mask, float("-inf"))
 
    attention = torch.softmax(scores, dim=-1)
 
    output = torch.einsum("bhts,bshd->bthd", attention, v)
 
    return output.to(dtype=dtype_og), attention.to(dtype=dtype_og)
 
 
# #################################################################################################
#  Test Utilities
# #################################################################################################
 
 
def print_diff_statistics(diff_tensor: torch.Tensor, prefix: str = ""):
    """
    Print percentile statistics (75%, 95%, 99%) for a difference tensor.
    This helps assess parity quality beyond just max difference.
 
    Args:
        diff_tensor: Tensor containing absolute differences between expected and actual outputs.
        prefix: Optional prefix string for the output message.
    """
    if not enable_debug_print:
        return
 
    diff_flat = diff_tensor.flatten().float()
    if diff_flat.numel() == 0:
        print(f"{prefix}Diff statistics: empty tensor")
        return
 
    # Compute percentiles
    sorted_diff, _ = torch.sort(diff_flat)
    n = sorted_diff.numel()
 
    p75_idx = min(int(n * 0.75), n - 1)
    p90_idx = min(int(n * 0.90), n - 1)
    p95_idx = min(int(n * 0.95), n - 1)
    p99_idx = min(int(n * 0.99), n - 1)
    p999_idx = min(int(n * 0.999), n - 1)
 
    p75 = sorted_diff[p75_idx].item()
    p90 = sorted_diff[p90_idx].item()
    p95 = sorted_diff[p95_idx].item()
    p99 = sorted_diff[p99_idx].item()
    p999 = sorted_diff[p999_idx].item()
    max_val = sorted_diff[-1].item()
    mean_val = diff_flat.mean().item()
 
    print(
        f"{prefix} Diff stats - mean: {mean_val:.6f}, p75: {p75:.6f}, p90: {p90:.6f}, p95: {p95:.6f}, p99: {p99:.6f}, p999: {p999:.6f}, max: {max_val:.6f}"
    )
 
 
# #################################################################################################
#  Attention Mask Helper Functions
# #################################################################################################
 
 
def create_boolean_mask_from_seqlens(
    seqlens: torch.Tensor,
    total_seq_len: int,
    mask_dims: int,
    q_seq_len: int = 1,
    num_heads: int = 1,
    device: str = "cuda",
) -> torch.Tensor:
    """
    Create a boolean attention mask from sequence lengths.
 
    ONNX broadcasting aligns dimensions from the right (trailing dimensions).
    Target broadcast shape: (batch_size, q_num_heads, q_seq_len, total_seq_len)
 
    Args:
        seqlens: Tensor of shape [batch_size] containing the valid sequence length for each batch.
        total_seq_len: The total sequence length (last dimension of the mask).
        mask_dims: Number of dimensions for the mask (2, 3, or 4).
        q_seq_len: Query sequence length (for 3D/4D masks).
        num_heads: Number of q_heads (for 3D/4D masks).
        device: Device for the tensor.
 
    Returns:
        Boolean mask where True = valid, False = padding.
        - 2D: [q_seq_len, total_seq_len] - broadcasts to [batch, heads, q_seq, total_seq]
        - 3D: [num_heads, q_seq_len, total_seq_len] - broadcasts to [1, num_heads, q_seq, total_seq]
        - 4D: [batch_size, num_heads, q_seq_len, total_seq_len] - no broadcasting
    """
    batch_size = seqlens.shape[0]
 
    # Create base 2D mask [batch_size, total_seq_len]
    # mask[b, i] = True if i < seqlens[b]
    arange = torch.arange(total_seq_len, device=device).unsqueeze(0)  # [1, total_seq_len]
    seqlens_expanded = seqlens.unsqueeze(1)  # [batch_size, 1]
    mask_2d = arange < seqlens_expanded  # [batch_size, total_seq_len]
 
    if mask_dims == 2:
        # 2D: [q_seq_len, total_seq_len] per ONNX spec. Broadcasts across batch and heads.
        # Since 2D masks can't vary per batch, use the first batch's pattern.
        mask_1d = mask_2d[0:1, :]  # [1, total_seq_len]
        return mask_1d.expand(q_seq_len, total_seq_len).contiguous()
    elif mask_dims == 3:
        # 3D mask: [num_heads, q_seq_len, total_seq_len]
        # For right-padding tests, all batches should have the same mask pattern per position.
        # Since seqlens can vary per batch, we use the first batch's pattern and expand across heads.
        # This is valid for testing because the 3D mask broadcasts across batches (dim 0 becomes 1).
        # For a more general case, 3D masks would need uniform seqlens across batches.
        mask_1d = mask_2d[0:1, :]  # Take first batch pattern [1, total_seq_len]
        mask_3d = mask_1d.unsqueeze(0).expand(num_heads, q_seq_len, total_seq_len).contiguous()
        return mask_3d
    else:  # 4D
        # Expand to [batch_size, num_heads, q_seq_len, total_seq_len]
        # The mask is the same for all heads and query positions
        return mask_2d.unsqueeze(1).unsqueeze(1).expand(batch_size, num_heads, q_seq_len, total_seq_len).contiguous()
 
 
def create_additive_mask_from_seqlens(
    seqlens: torch.Tensor,
    total_seq_len: int,
    mask_dims: int,
    q_seq_len: int = 1,
    num_heads: int = 1,
    device: str = "cuda",
    dtype: torch.dtype = torch.float16,
) -> torch.Tensor:
    """
    Create an additive attention mask from sequence lengths.
 
    Valid positions get 0.0, masked positions get -inf.
    This is used for the MHA path which expects additive bias.
 
    Args:
        seqlens: Tensor of shape [batch_size] containing the valid sequence length for each batch.
        total_seq_len: The total sequence length (last dimension of the mask).
        mask_dims: Number of dimensions for the mask (2, 3, or 4).
        q_seq_len: Query sequence length (for 3D/4D masks).
        num_heads: Number of heads (for 3D/4D masks).
        device: Device for the tensor.
        dtype: Torch dtype for the mask.
 
    Returns:
        Additive mask where 0.0 = valid, -inf = masked.
        - 2D: [q_seq_len, total_seq_len]
        - 3D: [num_heads, q_seq_len, total_seq_len]
        - 4D: [batch_size, num_heads, q_seq_len, total_seq_len]
    """
    batch_size = seqlens.shape[0]
 
    # Create base boolean mask [batch_size, total_seq_len]
    arange = torch.arange(total_seq_len, device=device).unsqueeze(0)
    seqlens_expanded = seqlens.unsqueeze(1)
    bool_mask = arange < seqlens_expanded  # True for valid
 
    # Convert to additive: 0.0 for valid, -inf for masked
    additive_4d = torch.zeros(batch_size, num_heads, q_seq_len, total_seq_len, device=device, dtype=dtype)
    # Expand bool mask to 4D [batch, 1, 1, total_seq] and apply
    additive_4d.masked_fill_(~bool_mask.unsqueeze(1).unsqueeze(1), float("-inf"))
 
    if mask_dims == 2:
        # 2D: [q_seq_len, total_seq_len] — only works when all batches have same seqlens
        return additive_4d[0, 0, :, :]
    elif mask_dims == 3:
        # 3D: [heads, q_seq_len, total_seq_len] — batch always broadcasts, use first batch
        return additive_4d[0, :, :, :]
    else:  # 4D
        return additive_4d
 
 
# #################################################################################################
#  Hardware / Provider Helpers
# #################################################################################################
 
 
def has_cuda_provider():
    return "CUDAExecutionProvider" in get_available_providers()
 
 
def has_cuda_device(min_capability: int = 80):
    if not has_cuda_provider() or not torch.cuda.is_available():
        return False
    major, minor = torch.cuda.get_device_capability()
    return major * 10 + minor >= min_capability
 
 
def has_flash_attention():
    return has_cuda_device(80)
 
 
# Default tolerances
# Note: fp32 tolerances are relaxed because TF32 is enabled by default on Ampere+ GPUs
# (see attention.cc: use_tf32 = UseTF32()), giving roughly fp16-level matmul precision.
rtol = {"fp16": 5e-3, "fp32": 5e-3, "bf16": 5e-2}
atol = {"fp16": 5e-3, "fp32": 5e-3, "bf16": 1e-2}