Исходный код СУБД 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
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
# --------------------------------------------------------------------------
 
"""
Accuracy and latency harness for the CUDA MatMulBlockQuantizedFp8Weight and
MatMulBlockQuantizedFp4Weight contrib ops.
 
The script builds a single-node com.microsoft contrib-op model, binds CUDA tensors with
I/O binding, compares the output with an FP32 dequantized reference, and prints one JSON
record per case. It is intended for opt-in CUDA profiling, not for normal CI.
 
Examples:
  python profile_matmul_block_scaled.py --suite smoke
  python profile_matmul_block_scaled.py --op fp8 --activation-dtype bf16 --m 1 --n 4096 --k 4096 --bias
  python profile_matmul_block_scaled.py --op fp8 --m 16 --n 11008 --k 4096 --repeat 200 --w8a8
  python profile_matmul_block_scaled.py --op fp4 --activation-dtype bf16 --m 1 --n 4096 --k 4096 --bias
  python profile_matmul_block_scaled.py --op fp4 --m 16 --n 11008 --k 4096 --repeat 200
 
For kernel-level evidence, wrap a representative case with nsys:
  nsys profile -t cuda,nvtx -o block_scaled --export=sqlite \
      python profile_matmul_block_scaled.py --op fp4 --m 16 --n 4096 --k 4096
"""
 
from __future__ import annotations
 
import argparse
import json
import math
import os
import statistics
import sys
import time
from contextlib import nullcontext
from dataclasses import dataclass
from pathlib import Path
from typing import Any
 
import numpy as np
import torch
from onnx import TensorProto, helper
 
import onnxruntime
from onnxruntime.capi.onnxruntime_pybind11_state import Fail as OrtFail
 
_TRANSFORMERS_TEST_DIR = Path(__file__).resolve().parents[1] / "transformers"
sys.path.insert(0, str(_TRANSFORMERS_TEST_DIR))
try:
    from env_var_helper import scoped_env_var
finally:
    sys.path.pop(0)
 
try:
    import nvtx
 
    _HAS_NVTX = True
except ImportError:
    nvtx = None
    _HAS_NVTX = False
 
 
RESULT_PREFIX = "MATMUL_BLOCK_SCALED_RESULT "
 
_TORCH_TO_ONNX = {
    torch.float16: TensorProto.FLOAT16,
    torch.bfloat16: TensorProto.BFLOAT16,
}
_FP4_POS_VALUES = torch.tensor([0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0], dtype=torch.float32)
_FP8_E4M3_MAX = 448.0
 
 
@dataclass(frozen=True)
class Case:
    op: str
    m: int
    n: int
    k: int
    activation_dtype: str
    block_size: int | None = None
    bias: bool = False
    w8a8: bool = False
    seed: int = 0
 
 
def _nvtx_range(name: str, color: str = "green"):
    if not _HAS_NVTX:
        return nullcontext()
    return nvtx.annotate(name, color=color)
 
 
def _require_cuda() -> None:
    if not torch.cuda.is_available():
        raise RuntimeError("CUDA is required for this harness.")
    if "CUDAExecutionProvider" not in onnxruntime.get_available_providers():
        raise RuntimeError("CUDAExecutionProvider is not available in this onnxruntime build.")
 
 
def _torch_dtype(name: str) -> torch.dtype:
    if name == "fp16":
        return torch.float16
    if name == "bf16":
        return torch.bfloat16
    raise ValueError(f"Unsupported dtype: {name}")
 
 
def _onnx_dtype(name: str) -> int:
    return _TORCH_TO_ONNX[_torch_dtype(name)]
 
 
def _raw_uint8(tensor: torch.Tensor) -> bytes:
    return np.ascontiguousarray(tensor.detach().view(torch.uint8).cpu().numpy()).tobytes()
 
 
def _make_float_initializer(name: str, tensor: torch.Tensor, onnx_dtype: int):
    if onnx_dtype == TensorProto.FLOAT:
        values = np.ascontiguousarray(tensor.detach().cpu().numpy().astype(np.float32))
        return helper.make_tensor(name, onnx_dtype, list(tensor.shape), values.tobytes(), raw=True)
    if onnx_dtype == TensorProto.FLOAT16:
        values = np.ascontiguousarray(tensor.detach().cpu().numpy().astype(np.float16))
        return helper.make_tensor(name, onnx_dtype, list(tensor.shape), values.tobytes(), raw=True)
    if onnx_dtype == TensorProto.BFLOAT16:
        values = tensor.detach().to(torch.float32).flatten().cpu().tolist()
        return helper.make_tensor(name, onnx_dtype, list(tensor.shape), values, raw=False)
    raise ValueError(f"Unsupported initializer dtype: {onnx_dtype}")
 
 
def _make_session(model: bytes, cuda_graph: bool = False) -> onnxruntime.InferenceSession:
    session_options = onnxruntime.SessionOptions()
    session_options.intra_op_num_threads = 1
    session_options.graph_optimization_level = onnxruntime.GraphOptimizationLevel.ORT_DISABLE_ALL
    session_options.log_severity_level = 3
    try:
        provider_options = {}
        if cuda_graph:
            provider_options = {
                "user_compute_stream": str(torch.cuda.current_stream().cuda_stream),
            }
        return onnxruntime.InferenceSession(
            model, session_options, providers=[("CUDAExecutionProvider", provider_options)]
        )
    except OrtFail as error:
        if "MatMulBlockQuantized" in str(error) and "not a registered" in str(error):
            raise RuntimeError(
                "The active onnxruntime package does not register the MatMulBlockQuantized contrib ops. "
                "Build and install this branch's CUDA wheel before running the harness."
            ) from error
        raise
 
 
def _model_bytes(nodes, graph_inputs, graph_outputs, initializers, name: str) -> bytes:
    graph = helper.make_graph(nodes, name, graph_inputs, graph_outputs, initializers)
    model = helper.make_model(
        graph,
        opset_imports=[helper.make_opsetid("com.microsoft", 1), helper.make_opsetid("", 17)],
    )
    return model.SerializeToString()
 
 
def _quantize_fp4(weight: torch.Tensor, block_size: int) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
    if weight.shape[1] % 2 != 0:
        raise ValueError("FP4 packed weight requires even K.")
 
    n, k = weight.shape
    k_blocks = math.ceil(k / block_size)
    padded_k = k_blocks * block_size
    padded = torch.nn.functional.pad(weight.float(), (0, padded_k - k))
    blocks = padded.reshape(n, k_blocks, block_size)
    max_abs = blocks.abs().amax(dim=-1)
    scale = torch.clamp(max_abs / 6.0, min=1.0 / 1024.0).to(torch.float8_e4m3fn)
    scale_f32 = scale.float()
 
    scaled = blocks / scale_f32.unsqueeze(-1)
    values = _FP4_POS_VALUES.to(device=weight.device)
    flat_abs = scaled.abs().reshape(-1, 1).clamp(max=6.0)
    nearest = torch.abs(flat_abs - values.reshape(1, -1)).argmin(dim=1).reshape_as(scaled).to(torch.uint8)
    codes = nearest | ((scaled < 0).to(torch.uint8) << 3)
    codes = codes.reshape(n, padded_k)[:, :k].contiguous()
 
    low = codes[:, 0::2]
    high = codes[:, 1::2]
    packed = (low | (high << 4)).contiguous()
 
    quantized_values = values[nearest.long()].reshape_as(scaled) * torch.where(scaled < 0, -1.0, 1.0)
    dequantized = (quantized_values * scale_f32.unsqueeze(-1)).reshape(n, padded_k)[:, :k].contiguous()
    return packed, scale.view(torch.uint8).contiguous(), dequantized
 
 
def _make_fp4_model(case: Case, b_packed: torch.Tensor, weight_scale: torch.Tensor, bias: torch.Tensor | None) -> bytes:
    activation_onnx_type = _onnx_dtype(case.activation_dtype)
    block_size = case.block_size or 16
    inputs = ["A", "B", "weight_scale", "weight_scale_2"]
    initializers = [
        helper.make_tensor("B", TensorProto.UINT8, [case.n, case.k // 2], _raw_uint8(b_packed), raw=True),
        helper.make_tensor(
            "weight_scale",
            TensorProto.UINT8,
            [case.n, math.ceil(case.k / block_size)],
            _raw_uint8(weight_scale),
            raw=True,
        ),
        helper.make_tensor("weight_scale_2", TensorProto.FLOAT, [1], [1.0], raw=False),
    ]
    if bias is not None:
        inputs.extend(["", "bias"])
        initializers.append(_make_float_initializer("bias", bias, activation_onnx_type))
 
    node = helper.make_node(
        "MatMulBlockQuantizedFp4Weight",
        inputs,
        ["Y"],
        domain="com.microsoft",
        block_size=block_size,
    )
    graph_inputs = [helper.make_tensor_value_info("A", activation_onnx_type, [case.m, case.k])]
    graph_outputs = [helper.make_tensor_value_info("Y", activation_onnx_type, [case.m, case.n])]
    return _model_bytes([node], graph_inputs, graph_outputs, initializers, "MatMulBlockQuantizedFp4Weight_Profile")
 
 
def _fp4_reference(a: torch.Tensor, b_dequantized: torch.Tensor, bias: torch.Tensor | None) -> torch.Tensor:
    result = a.float() @ b_dequantized.float().T
    if bias is not None:
        result += bias.float().reshape(1, -1)
    return result.to(a.dtype).float()
 
 
def _fp4_native_sm120_enabled() -> bool:
    return os.environ.get("ORT_MATMUL_BLOCK_SCALED_FP4_NATIVE_SM120", "").lower() in {"1", "true", "yes", "on"}
 
 
def _env_enabled(name: str, default: bool) -> bool:
    value = os.environ.get(name)
    return default if value is None else value.lower() in {"1", "true", "yes", "on"}
 
 
def _fp4_native_sm120_supported(case: Case) -> bool:
    block_size = case.block_size or 16
    return (
        _fp4_native_sm120_enabled()
        and case.m > 8
        and block_size == 16
        and case.k % 32 == 0
        and case.n % 32 == 0
        and case.activation_dtype in {"fp16", "bf16"}
    )
 
 
def _fp4_expected_path(case: Case) -> str:
    block_size = case.block_size or 16
    gemv_max_m = 8
    if torch.cuda.get_device_capability()[0] >= 8 and case.k % 128 == 0 and _env_enabled("ORT_FP4_GEMV_MMA", True):
        gemv_max_m = int(os.environ.get("ORT_FP4_GEMV_MAX_M", "32"))
    if case.m > 0 and case.m <= gemv_max_m and block_size == 16 and case.k % 32 == 0:
        return "fp4_gemv"
    if _fp4_native_sm120_supported(case):
        return "sm120_native_fp4_gemm"
    return "fp4_dequant_cublas"
 
 
def _quantize_fp8(weight: torch.Tensor, block_size: int) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
    """Block-scaled FP8 E4M3 weight quantization.
 
    Returns (b_fp8 [N, K] float8_e4m3fn, b_scale [N, ceil(K/block_size)] fp32, dequantized [N, K] fp32).
    """
    n, k = weight.shape
    k_blocks = math.ceil(k / block_size)
    padded_k = k_blocks * block_size
    padded = torch.nn.functional.pad(weight.float(), (0, padded_k - k))
    blocks = padded.reshape(n, k_blocks, block_size)
    max_abs = blocks.abs().amax(dim=-1)
    scale_f32 = torch.clamp(max_abs / _FP8_E4M3_MAX, min=1.0 / 65504.0).float()
    q = (blocks / scale_f32.unsqueeze(-1)).to(torch.float8_e4m3fn)
    b_fp8 = q.reshape(n, padded_k)[:, :k].contiguous()
    dequantized = (q.float() * scale_f32.unsqueeze(-1)).reshape(n, padded_k)[:, :k].contiguous()
    return b_fp8, scale_f32.contiguous(), dequantized
 
 
def _quantize_dequantize_activation_fp8(a: torch.Tensor) -> tuple[torch.Tensor, float]:
    """Static per-tensor W8A8 activation QDQ: a_deq = fp8_e4m3(a / a_scale) * a_scale."""
    max_abs = a.float().abs().amax()
    a_scale = float(torch.clamp(max_abs / _FP8_E4M3_MAX, min=1.0 / 65504.0).item())
    a_deq = ((a.float() / a_scale).to(torch.float8_e4m3fn).float() * a_scale).to(a.dtype)
    return a_deq.contiguous(), a_scale
 
 
def _make_fp8_model(
    case: Case,
    b_fp8: torch.Tensor,
    b_scale: torch.Tensor,
    a_scale: float | None,
    bias: torch.Tensor | None,
) -> bytes:
    activation_onnx_type = _onnx_dtype(case.activation_dtype)
    block_size = case.block_size or 128
    inputs = ["A", "B", "b_scale"]
    initializers = [
        helper.make_tensor("B", TensorProto.FLOAT8E4M3FN, [case.n, case.k], _raw_uint8(b_fp8), raw=True),
        _make_float_initializer("b_scale", b_scale, TensorProto.FLOAT),
    ]
    if a_scale is not None:
        inputs.append("a_scale")
        initializers.append(helper.make_tensor("a_scale", TensorProto.FLOAT, [], [float(a_scale)], raw=False))
    elif bias is not None:
        inputs.append("")  # optional a_scale skipped, keep positional slot for bias
    if bias is not None:
        inputs.append("bias")
        initializers.append(_make_float_initializer("bias", bias, activation_onnx_type))
 
    node = helper.make_node(
        "MatMulBlockQuantizedFp8Weight",
        inputs,
        ["Y"],
        domain="com.microsoft",
        block_size=block_size,
    )
    graph_inputs = [helper.make_tensor_value_info("A", activation_onnx_type, [case.m, case.k])]
    graph_outputs = [helper.make_tensor_value_info("Y", activation_onnx_type, [case.m, case.n])]
    return _model_bytes([node], graph_inputs, graph_outputs, initializers, "MatMulBlockQuantizedFp8Weight_Profile")
 
 
def _fp8_reference(a: torch.Tensor, b_dequantized: torch.Tensor, bias: torch.Tensor | None) -> torch.Tensor:
    result = a.float() @ b_dequantized.float().T
    if bias is not None:
        result += bias.float().reshape(1, -1)
    return result.to(a.dtype).float()
 
 
def _fp8_expected_path(case: Case) -> str:
    block_size = case.block_size or 128
    gemv_max_m = 8
    if (
        torch.cuda.get_device_capability()[0] >= 8
        and case.k % 64 == 0
        and case.k >= 256
        and block_size % 64 == 0
        and _env_enabled("ORT_FP8_GEMV_MMA", True)
    ):
        gemv_max_m = int(os.environ.get("ORT_FP8_GEMV_MAX_M", "32"))
    if case.m > 0 and case.m <= gemv_max_m and case.k % 16 == 0 and block_size % 16 == 0:
        return "fp8_gemv"
    if (
        _env_enabled("ORT_FP8_MATMUL_DEEPGEMM", False)
        and case.w8a8
        and block_size == 128
        and case.k > 0
        and case.k % 128 == 0
        and case.n % 64 == 0
        and case.m <= 128
        and case.n >= 2048
        and case.n * case.k >= 8 * 1024 * 1024
        and torch.cuda.get_device_capability() == (9, 0)
    ):
        return "fp8_deepgemm_candidate"  # Verify build support and actual dispatch with a CUDA trace.
    return "fp8_dequant_cublas"
 
 
def _make_fp8_inputs(case: Case) -> tuple[bytes, torch.Tensor, torch.Tensor, str]:
    generator = torch.Generator(device="cuda")
    generator.manual_seed(case.seed)
    block_size = case.block_size or 128
 
    activation_dtype = _torch_dtype(case.activation_dtype)
    a = (torch.randn((case.m, case.k), generator=generator, device="cuda") * 0.75).to(activation_dtype).contiguous()
    weight = torch.randn((case.n, case.k), generator=generator, device="cuda", dtype=torch.float32) * 0.75
    b_fp8, b_scale, b_dequantized = _quantize_fp8(weight, block_size)
    bias = None
    if case.bias:
        bias = (torch.randn((case.n,), generator=generator, device="cuda") * 0.25).to(activation_dtype).contiguous()
 
    a_scale = None
    a_effective = a
    if case.w8a8:
        a_effective, a_scale = _quantize_dequantize_activation_fp8(a)
 
    model = _make_fp8_model(case, b_fp8, b_scale, a_scale, bias)
    reference = _fp8_reference(a_effective, b_dequantized, bias)
    return model, a, reference, _fp8_expected_path(case)
 
 
def _make_inputs(case: Case) -> tuple[bytes, torch.Tensor, torch.Tensor, str]:
    if case.op == "fp8":
        return _make_fp8_inputs(case)
 
    generator = torch.Generator(device="cuda")
    generator.manual_seed(case.seed)
    block_size = case.block_size or 16
 
    activation_dtype = _torch_dtype(case.activation_dtype)
    a = (torch.randn((case.m, case.k), generator=generator, device="cuda") * 0.75).to(activation_dtype).contiguous()
    weight = torch.randn((case.n, case.k), generator=generator, device="cuda", dtype=torch.float32) * 0.75
    b_packed, weight_scale, b_dequantized = _quantize_fp4(weight, block_size)
    bias = None
    if case.bias:
        bias = (torch.randn((case.n,), generator=generator, device="cuda") * 0.25).to(activation_dtype).contiguous()
    model = _make_fp4_model(case, b_packed, weight_scale, bias)
    if _fp4_native_sm120_supported(case):
        _, _, a_dequantized = _quantize_fp4(a.float(), block_size)
        reference = _fp4_reference(a_dequantized.to(activation_dtype), b_dequantized, bias)
    else:
        reference = _fp4_reference(a, b_dequantized, bias)
    return model, a, reference, _fp4_expected_path(case)
 
 
def _error_metrics(actual: torch.Tensor, expected: torch.Tensor) -> dict[str, float]:
    diff = actual.float() - expected.float()
    abs_diff = diff.abs()
    rel_diff = abs_diff / torch.clamp(expected.float().abs(), min=1.0e-6)
    return {
        "max_abs_error": float(abs_diff.max().item()) if abs_diff.numel() else 0.0,
        "max_rel_error": float(rel_diff.max().item()) if rel_diff.numel() else 0.0,
        "rmse": float(torch.sqrt(torch.mean(diff * diff)).item()) if diff.numel() else 0.0,
        "max_expected_abs": float(expected.float().abs().max().item()) if expected.numel() else 0.0,
    }
 
 
def _run_timed(
    session: onnxruntime.InferenceSession,
    a: torch.Tensor,
    y: torch.Tensor,
    warmup: int,
    repeat: int,
    cuda_graph: bool = False,
) -> list[float]:
    io_binding = session.io_binding()
    io_binding.bind_input("A", "cuda", 0, _TORCH_TO_ONNX[a.dtype], list(a.shape), a.data_ptr())
    io_binding.bind_output("Y", "cuda", 0, _TORCH_TO_ONNX[y.dtype], list(y.shape), y.data_ptr())
    run_options = onnxruntime.RunOptions()
    if cuda_graph:
        run_options.add_run_config_entry("disable_synchronize_execution_providers", "1")
 
    with _nvtx_range("warmup", "yellow"):
        for _ in range(warmup):
            session.run_with_iobinding(io_binding, run_options)
    torch.cuda.synchronize()
 
    if cuda_graph:
        # Capture fixed-shape operator calls on the user stream after allocator warmup.
        # Batching amortizes Python launch overhead without nesting cudaGraphLaunch
        # inside capture. Events include quantization and output conversion.
        batch_size = 16
        batch = torch.cuda.CUDAGraph()
        with torch.cuda.graph(batch, stream=torch.cuda.current_stream()):
            for _ in range(batch_size):
                session.run_with_iobinding(io_binding, run_options)
        batch.replay()
        torch.cuda.synchronize()
        start = torch.cuda.Event(enable_timing=True)
        end = torch.cuda.Event(enable_timing=True)
        times_ms = []
        for _ in range(repeat):
            start.record()
            batch.replay()
            end.record()
            end.synchronize()
            times_ms.append(start.elapsed_time(end) / batch_size)
        return times_ms
 
    times_ms = []
    with _nvtx_range("benchmark", "green"):
        for _ in range(repeat):
            start = time.perf_counter()
            session.run_with_iobinding(io_binding)
            torch.cuda.synchronize()
            times_ms.append((time.perf_counter() - start) * 1000.0)
    return times_ms
 
 
def _summarize_times(times_ms: list[float]) -> dict[str, float]:
    sorted_times = sorted(times_ms)
    p90_index = min(len(sorted_times) - 1, math.ceil(0.90 * len(sorted_times)) - 1)
    p99_index = min(len(sorted_times) - 1, math.ceil(0.99 * len(sorted_times)) - 1)
    return {
        "mean_ms": statistics.fmean(times_ms),
        "p50_ms": statistics.median(times_ms),
        "p90_ms": sorted_times[p90_index],
        "p99_ms": sorted_times[p99_index],
        "min_ms": sorted_times[0],
    }
 
 
def run_case(
    case: Case, warmup: int, repeat: int, atol: float, rtol: float, cuda_graph: bool = False
) -> dict[str, Any]:
    model, a, reference, expected_path = _make_inputs(case)
    output_dtype = _torch_dtype(case.activation_dtype)
    y = torch.empty((case.m, case.n), dtype=output_dtype, device="cuda")
    torch.cuda.synchronize()
    stream_scope = torch.cuda.stream(torch.cuda.Stream()) if cuda_graph else nullcontext()
    with stream_scope:
        session = _make_session(model, cuda_graph)
        times_ms = _run_timed(session, a, y, warmup, repeat, cuda_graph)
 
    metrics = _error_metrics(y, reference)
    threshold = atol + rtol * metrics["max_expected_abs"]
    passed = metrics["max_abs_error"] <= threshold
    flops = 2.0 * case.m * case.n * case.k
    timing = _summarize_times(times_ms)
    result = {
        "op": case.op,
        "m": case.m,
        "n": case.n,
        "k": case.k,
        "block_size": case.block_size or (128 if case.op == "fp8" else 16),
        "activation_dtype": case.activation_dtype,
        "bias": case.bias,
        "w8a8": case.w8a8,
        "timing": "cuda_graph_gpu_events" if cuda_graph else "host_wall_time",
        "expected_path": expected_path,
        "passed": passed,
        "atol": atol,
        "rtol": rtol,
        "tflops": flops / (timing["mean_ms"] * 1.0e-3) / 1.0e12,
        **timing,
        **metrics,
    }
    print(RESULT_PREFIX + json.dumps(result, sort_keys=True))
    return result
 
 
def _default_cases(args) -> list[Case]:
    if args.m is not None and args.n is not None and args.k is not None:
        return [
            Case(
                op=args.op,
                m=args.m,
                n=args.n,
                k=args.k,
                activation_dtype=args.activation_dtype,
                block_size=args.block_size,
                bias=args.bias,
                w8a8=args.w8a8,
                seed=args.seed,
            )
        ]
 
    cases = []
    if args.suite == "smoke":
        cases.extend(
            [
                Case(args.op, 1, 80, 256, "fp16", bias=True, seed=args.seed + 3),
                Case(args.op, 32, 128, 256, "bf16", bias=False, seed=args.seed + 4),
            ]
        )
        return cases
 
    matrix_ms = [1, 2, 4, 8] if args.suite == "decode" else [16, 32, 64, 128]
    matrix_shapes = [(4096, 4096), (4096, 11008)]
    for k, n in matrix_shapes:
        cases.extend(
            Case(args.op, m, n, k, args.activation_dtype, bias=args.bias, w8a8=args.w8a8, seed=args.seed + 100 + m)
            for m in matrix_ms
        )
    return cases
 
 
def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description="Profile the CUDA block-scaled FP8/FP4 MatMul contrib ops")
    parser.add_argument("--op", choices=["fp8", "fp4"], default="fp8")
    parser.add_argument("--suite", choices=["smoke", "decode", "prefill"], default="smoke")
    parser.add_argument("--m", type=int, help="M rows for single-case mode")
    parser.add_argument("--n", type=int, help="N columns for single-case mode")
    parser.add_argument("--k", type=int, help="K reduction dimension for single-case mode")
    parser.add_argument("--block-size", type=int, help="Override block_size attribute")
    parser.add_argument("--activation-dtype", choices=["fp16", "bf16"], default="fp16")
    parser.add_argument("--bias", action="store_true", help="Enable bias input")
    parser.add_argument("--w8a8", action="store_true", help="FP8 only: statically quantize A to FP8 (a_scale)")
    parser.add_argument("--cuda-graph", action="store_true", help="Time batched CUDA graph replays with GPU events")
    parser.add_argument("--gemv-max-m", type=int, help="Temporarily override the selected format's GEMV M limit")
    parser.add_argument("--warmup", type=int, default=10)
    parser.add_argument("--repeat", type=int, default=50)
    parser.add_argument("--seed", type=int, default=0)
    parser.add_argument("--atol", type=float, default=2.0)
    parser.add_argument("--rtol", type=float, default=0.02)
    return parser.parse_args()
 
 
def main() -> None:
    args = parse_args()
    _require_cuda()
    if args.warmup < 0 or args.repeat < 1:
        raise ValueError("Use nonnegative warmup calls and at least one measured repeat.")
    if args.cuda_graph and args.warmup < 2:
        raise ValueError("CUDA graph timing requires at least two warmup calls.")
    if args.gemv_max_m is not None and not 1 <= args.gemv_max_m <= 64:
        raise ValueError("--gemv-max-m must be in [1, 64].")
    single_case_args = [args.m is not None, args.n is not None, args.k is not None]
    if any(single_case_args) and not all(single_case_args):
        raise ValueError("Single-case mode requires all of --m, --n and --k.")
 
    env_name = f"ORT_{args.op.upper()}_GEMV_MAX_M"
    env_scope = scoped_env_var(env_name, str(args.gemv_max_m)) if args.gemv_max_m is not None else nullcontext()
    with env_scope:
        results = [
            run_case(case, args.warmup, args.repeat, args.atol, args.rtol, args.cuda_graph)
            for case in _default_cases(args)
        ]
    failures = [result for result in results if not result["passed"]]
    if failures:
        raise SystemExit(f"{len(failures)} case(s) failed accuracy checks")
 
 
if __name__ == "__main__":
    main()