assassinlike commited on
Commit
554aa12
·
verified ·
1 Parent(s): 6256be4

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/__pycache__/__init__.cpython-310.pyc +0 -0
  2. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/__pycache__/api.cpython-310.pyc +0 -0
  3. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/__pycache__/utils.cpython-310.pyc +0 -0
  4. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/fp8_fa3/__init__.py +21 -0
  5. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/fp8_fa3/__pycache__/__init__.cpython-310.pyc +0 -0
  6. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/fp8_fa3/__pycache__/attention.cpython-310.pyc +0 -0
  7. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/fp8_fa3/__pycache__/setup.cpython-310.pyc +0 -0
  8. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/fp8_fa3/attention.py +44 -0
  9. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/fp8_fa3/setup.py +27 -0
  10. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/quantization/__init__.py +17 -0
  11. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/quantization/__pycache__/__init__.cpython-310.pyc +0 -0
  12. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/quantization/__pycache__/quantization.cpython-310.pyc +0 -0
  13. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/quantization/__pycache__/triton_qkv_quantization.cpython-310.pyc +0 -0
  14. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/quantization/__pycache__/triton_rope_qkv_quantization.cpython-310.pyc +0 -0
  15. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/quantization/quantization.py +50 -0
  16. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/quantization/triton_qkv_quantization.py +474 -0
  17. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/quantization/triton_rope_qkv_quantization.py +745 -0
  18. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/shared_utils/__init__.py +5 -0
  19. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/shared_utils/__pycache__/__init__.cpython-310.pyc +0 -0
  20. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/shared_utils/__pycache__/attention.cpython-310.pyc +0 -0
  21. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/shared_utils/__pycache__/custom_ops.cpython-310.pyc +0 -0
  22. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/shared_utils/__pycache__/fusion_utils.cpython-310.pyc +0 -0
  23. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/shared_utils/__pycache__/setup.cpython-310.pyc +0 -0
  24. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/shared_utils/__pycache__/wrapper.cpython-310.pyc +0 -0
  25. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/shared_utils/attention.py +135 -0
  26. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/shared_utils/custom_ops.py +112 -0
  27. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/shared_utils/fusion_utils.py +908 -0
  28. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/shared_utils/setup.py +44 -0
  29. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/shared_utils/wrapper.py +90 -0
  30. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/blockwise_fp8_training/__pycache__/__init__.cpython-310.pyc +0 -0
  31. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/blockwise_fp8_training/__pycache__/kernels.cpython-310.pyc +0 -0
  32. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/blockwise_fp8_training/__pycache__/linear.cpython-310.pyc +0 -0
  33. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/float8nocompile/__pycache__/__init__.cpython-310.pyc +0 -0
  34. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/float8nocompile/__pycache__/float8nocompile_linear.cpython-310.pyc +0 -0
  35. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/float8nocompile/__pycache__/float8nocompile_linear_test.cpython-310.pyc +0 -0
  36. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/float8nocompile/__pycache__/float8nocompile_linear_utils.cpython-310.pyc +0 -0
  37. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/float8nocompile/__pycache__/float8nocompile_scaling_utils.cpython-310.pyc +0 -0
  38. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/float8nocompile/kernels/__init__.py +0 -0
  39. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/float8nocompile/kernels/__pycache__/__init__.cpython-310.pyc +0 -0
  40. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/float8nocompile/kernels/__pycache__/fp8_dynamic_tensorwise.cpython-310.pyc +0 -0
  41. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/float8nocompile/kernels/__pycache__/fp8_dynamic_tensorwise_test.cpython-310.pyc +0 -0
  42. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/float8nocompile/kernels/fp8_dynamic_tensorwise.py +1090 -0
  43. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/float8nocompile/kernels/fp8_dynamic_tensorwise_test.py +493 -0
  44. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/moe_training/ep/__pycache__/__init__.cpython-310.pyc +0 -0
  45. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/moe_training/ep/__pycache__/a2a_combine.cpython-310.pyc +0 -0
  46. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/moe_training/ep/__pycache__/a2a_dispatch.cpython-310.pyc +0 -0
  47. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/moe_training/ep/__pycache__/kernels.cpython-310.pyc +0 -0
  48. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/moe_training/ep/__pycache__/permute.cpython-310.pyc +0 -0
  49. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/moe_training/ep/__pycache__/unpermute.cpython-310.pyc +0 -0
  50. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/moe_training/kernels/mxfp8/__pycache__/__init__.cpython-310.pyc +0 -0
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (492 Bytes). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/__pycache__/api.cpython-310.pyc ADDED
Binary file (3.05 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/__pycache__/utils.cpython-310.pyc ADDED
Binary file (936 Bytes). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/fp8_fa3/__init__.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD 3-Clause license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ """
8
+ FP8 attention using FA3 backend.
9
+ """
10
+
11
+ from torchao.prototype.attention.fp8_fa3.attention import (
12
+ fp8_fa3_rope_sdpa,
13
+ fp8_fa3_sdpa,
14
+ )
15
+ from torchao.prototype.attention.quantization import _fp8_sdpa_quantize
16
+
17
+ __all__ = [
18
+ "fp8_fa3_sdpa",
19
+ "fp8_fa3_rope_sdpa",
20
+ "_fp8_sdpa_quantize",
21
+ ]
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/fp8_fa3/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (489 Bytes). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/fp8_fa3/__pycache__/attention.cpython-310.pyc ADDED
Binary file (1.01 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/fp8_fa3/__pycache__/setup.cpython-310.pyc ADDED
Binary file (821 Bytes). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/fp8_fa3/attention.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD 3-Clause license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ """
8
+ FP8 SDPA using FA3 backend.
9
+
10
+ When using these functions directly (not through apply_low_precision_attention),
11
+ you must activate FA3 yourself::
12
+
13
+ activate_flash_attention_impl("FA3")
14
+ try:
15
+ out = fp8_fa3_sdpa(q, k, v, is_causal=True)
16
+ finally:
17
+ restore_flash_attention_impl()
18
+ """
19
+
20
+ from functools import partial
21
+
22
+ from torchao.prototype.attention.shared_utils.attention import (
23
+ _fp8_rope_sdpa,
24
+ _fp8_sdpa,
25
+ )
26
+ from torchao.prototype.attention.shared_utils.custom_ops import (
27
+ register_fp8_attention_ops,
28
+ )
29
+
30
+ fp8_fa3_sdpa = partial(_fp8_sdpa, backend_name="FA3")
31
+ fp8_fa3_sdpa.__doc__ = _fp8_sdpa.__doc__
32
+ fp8_fa3_sdpa.__name__ = "fp8_fa3_sdpa"
33
+ fp8_fa3_sdpa.__qualname__ = "fp8_fa3_sdpa"
34
+
35
+ fp8_fa3_rope_sdpa = partial(_fp8_rope_sdpa, backend_name="FA3")
36
+ fp8_fa3_rope_sdpa.__doc__ = _fp8_rope_sdpa.__doc__
37
+ fp8_fa3_rope_sdpa.__name__ = "fp8_fa3_rope_sdpa"
38
+ fp8_fa3_rope_sdpa.__qualname__ = "fp8_fa3_rope_sdpa"
39
+
40
+ _ops = register_fp8_attention_ops(
41
+ backend_name="fa3",
42
+ rope_sdpa_fn=fp8_fa3_rope_sdpa,
43
+ sdpa_fn=fp8_fa3_sdpa,
44
+ )
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/fp8_fa3/setup.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD 3-Clause license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ """FP8 FA3 backend setup."""
8
+
9
+ import torch.nn as nn
10
+
11
+ from torchao.prototype.attention.config import LowPrecisionAttentionConfig
12
+ from torchao.prototype.attention.shared_utils.setup import setup_fp8_backend
13
+
14
+
15
+ def setup_fp8_fa3(
16
+ model: nn.Module,
17
+ config: LowPrecisionAttentionConfig,
18
+ ) -> nn.Module:
19
+ """Set up FP8 FA3 attention on *model* and wrap it."""
20
+ from torchao.prototype.attention.fp8_fa3.attention import fp8_fa3_sdpa
21
+
22
+ return setup_fp8_backend(
23
+ model,
24
+ config,
25
+ flash_impl_name="FA3",
26
+ sdpa_fn=fp8_fa3_sdpa,
27
+ )
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/quantization/__init__.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD 3-Clause license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ from torchao.prototype.attention.quantization.triton_qkv_quantization import (
8
+ triton_fp8_sdpa_quantize as _fp8_sdpa_quantize,
9
+ )
10
+ from torchao.prototype.attention.quantization.triton_rope_qkv_quantization import (
11
+ triton_fp8_rope_sdpa_quantize as _fp8_rope_sdpa_quantize,
12
+ )
13
+
14
+ __all__ = [
15
+ "_fp8_sdpa_quantize",
16
+ "_fp8_rope_sdpa_quantize",
17
+ ]
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/quantization/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (528 Bytes). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/quantization/__pycache__/quantization.cpython-310.pyc ADDED
Binary file (1.34 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/quantization/__pycache__/triton_qkv_quantization.cpython-310.pyc ADDED
Binary file (7.87 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/quantization/__pycache__/triton_rope_qkv_quantization.cpython-310.pyc ADDED
Binary file (11.9 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/quantization/quantization.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD 3-Clause license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ """
8
+ FP8 quantization for attention inputs.
9
+ """
10
+
11
+ from typing import Tuple
12
+
13
+ import torch
14
+
15
+
16
+ def _fp8_sdpa_quantize(
17
+ q: torch.Tensor,
18
+ k: torch.Tensor,
19
+ v: torch.Tensor,
20
+ ) -> Tuple[
21
+ torch.Tensor,
22
+ torch.Tensor,
23
+ torch.Tensor,
24
+ torch.Tensor,
25
+ torch.Tensor,
26
+ torch.Tensor,
27
+ ]:
28
+ """Quantize Q, K, V to FP8 with per-head scaling."""
29
+ if q.dim() != 4:
30
+ raise ValueError(f"Expected 4D tensor for q, got {q.dim()}D")
31
+ if k.dim() != 4:
32
+ raise ValueError(f"Expected 4D tensor for k, got {k.dim()}D")
33
+ if v.dim() != 4:
34
+ raise ValueError(f"Expected 4D tensor for v, got {v.dim()}D")
35
+ if k.shape != v.shape:
36
+ raise ValueError(f"K and V shape mismatch: {k.shape} vs {v.shape}")
37
+ if q.shape[0] != k.shape[0]:
38
+ raise ValueError(f"Batch size mismatch: {q.shape[0]} vs {k.shape[0]}")
39
+ if q.shape[1] % k.shape[1] != 0:
40
+ raise ValueError(
41
+ f"Q head count ({q.shape[1]}) must be a multiple of K head count ({k.shape[1]})"
42
+ )
43
+ if q.shape[3] != k.shape[3]:
44
+ raise ValueError(f"Head dim mismatch: {q.shape[3]} vs {k.shape[3]}")
45
+
46
+ from torchao.prototype.attention.quantization.triton_qkv_quantization import (
47
+ triton_fp8_sdpa_quantize,
48
+ )
49
+
50
+ return triton_fp8_sdpa_quantize(q, k, v)
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/quantization/triton_qkv_quantization.py ADDED
@@ -0,0 +1,474 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD 3-Clause license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ """
8
+ FP8 quantization kernels for Q, K, V.
9
+
10
+ Input/output format: [B, H, S, D].
11
+ Supports GQA (different head counts for Q vs K/V).
12
+ """
13
+
14
+ from typing import Optional, Tuple
15
+
16
+ import torch
17
+ import triton
18
+ import triton.language as tl
19
+
20
+
21
+ def _compute_num_chunks(tensor: torch.Tensor, S: int) -> int:
22
+ """Compute optimal number of chunks based on GPU properties."""
23
+ props = torch.cuda.get_device_properties(tensor.device)
24
+ num_sms = props.multi_processor_count
25
+ B, H = tensor.shape[:2] # [B, H, S, D]
26
+ base_parallelism = B * H
27
+ # Target 2-4x SMs for good occupancy/latency hiding
28
+ target_blocks = num_sms * 4
29
+ num_chunks = max(1, target_blocks // base_parallelism)
30
+ # Ensure each chunk has at least 32 S positions for efficiency
31
+ num_chunks = min(num_chunks, S // 32) if S >= 32 else 1
32
+ # Cap at reasonable maximum
33
+ num_chunks = min(num_chunks, 64)
34
+ # Adjust if S is small
35
+ num_chunks = min(num_chunks, S)
36
+ return num_chunks
37
+
38
+
39
+ @triton.autotune(
40
+ configs=[
41
+ triton.Config({"BLOCK_SIZE": 512}, num_warps=4),
42
+ triton.Config({"BLOCK_SIZE": 1024}, num_warps=4),
43
+ triton.Config({"BLOCK_SIZE": 2048}, num_warps=8),
44
+ triton.Config({"BLOCK_SIZE": 4096}, num_warps=8),
45
+ ],
46
+ key=["chunk_size", "D"],
47
+ )
48
+ @triton.jit
49
+ def single_phase1_kernel(
50
+ # Input tensor [B, H, S, D]
51
+ x_ptr,
52
+ # Output: partial max values [B * H * num_chunks]
53
+ partial_max_ptr,
54
+ # Input strides (for [B, H, S, D] layout)
55
+ stride_b,
56
+ stride_h,
57
+ stride_s,
58
+ stride_d,
59
+ # Dimensions
60
+ S,
61
+ D,
62
+ H,
63
+ chunk_size,
64
+ num_chunks,
65
+ # Block size
66
+ BLOCK_SIZE: tl.constexpr,
67
+ ):
68
+ """
69
+ Phase 1 for a single tensor: Compute partial absmax.
70
+
71
+ Grid: (B, H, num_chunks)
72
+
73
+ Uses linearized iteration over chunk_size * D elements.
74
+ """
75
+ pid_b = tl.program_id(axis=0)
76
+ pid_h = tl.program_id(axis=1)
77
+ pid_chunk = tl.program_id(axis=2)
78
+
79
+ # Compute the S range for this chunk
80
+ s_start = pid_chunk * chunk_size
81
+ s_end = tl.minimum(s_start + chunk_size, S)
82
+ chunk_elements = (s_end - s_start) * D
83
+
84
+ # Base pointer for input [B, H, S, D]
85
+ base_offset = pid_b * stride_b + pid_h * stride_h
86
+
87
+ # Initialize max accumulator
88
+ x_max = 0.0
89
+
90
+ # Linearized iteration over chunk_size * D elements
91
+ for block_start in range(0, chunk_elements, BLOCK_SIZE):
92
+ offs = block_start + tl.arange(0, BLOCK_SIZE)
93
+ mask = offs < chunk_elements
94
+
95
+ # Convert linear offset to (s, d) coordinates
96
+ local_s = offs // D
97
+ d_idx = offs % D
98
+ s_idx = s_start + local_s
99
+
100
+ # Input offset [B, H, S, D]
101
+ ptr_offset = s_idx * stride_s + d_idx * stride_d
102
+
103
+ x_val = tl.load(x_ptr + base_offset + ptr_offset, mask=mask, other=0.0).to(
104
+ tl.float32
105
+ )
106
+ x_max = tl.maximum(x_max, tl.max(tl.abs(x_val)))
107
+
108
+ # Store partial max
109
+ chunk_idx = pid_b * (H * num_chunks) + pid_h * num_chunks + pid_chunk
110
+ tl.store(partial_max_ptr + chunk_idx, x_max)
111
+
112
+
113
+ @triton.jit
114
+ def single_reduce_kernel(
115
+ partial_max_ptr, # [B * H * num_chunks]
116
+ scale_ptr,
117
+ descale_ptr,
118
+ H,
119
+ num_chunks,
120
+ ):
121
+ """
122
+ Reduce partial maxes and compute scale/descale for a single tensor.
123
+
124
+ Grid: (B, H)
125
+ """
126
+ pid_b = tl.program_id(axis=0)
127
+ pid_h = tl.program_id(axis=1)
128
+
129
+ # Reduce across chunks for this (batch, head)
130
+ x_max = 0.0
131
+
132
+ base_idx = (pid_b * H + pid_h) * num_chunks
133
+ for c in range(num_chunks):
134
+ x_max = tl.maximum(x_max, tl.load(partial_max_ptr + base_idx + c))
135
+
136
+ # Compute scale and descale
137
+ # FP8 E4M3 max value is 448.0
138
+ FP8_MAX = 448.0
139
+ eps = 1e-12
140
+ scale_idx = pid_b * H + pid_h
141
+
142
+ tl.store(scale_ptr + scale_idx, tl.where(x_max > eps, FP8_MAX / x_max, 1.0))
143
+ tl.store(descale_ptr + scale_idx, tl.where(x_max > eps, x_max / FP8_MAX, 1.0))
144
+
145
+
146
+ @triton.jit
147
+ def group_reduce_kernel(
148
+ partial_max_ptr, # [B * H_q * num_chunks]
149
+ scale_ptr, # [B, H_kv]
150
+ descale_ptr, # [B, H_kv]
151
+ H_q,
152
+ H_kv,
153
+ groups, # H_q // H_kv
154
+ num_chunks,
155
+ ):
156
+ """
157
+ Reduce partial maxes across head groups for GQA Q tensor.
158
+
159
+ For each KV group, reduces the max across all Q heads in that group
160
+ and all chunks, producing one scale per (batch, kv_head).
161
+
162
+ Grid: (B, H_kv)
163
+ """
164
+ pid_b = tl.program_id(axis=0)
165
+ pid_hkv = tl.program_id(axis=1)
166
+
167
+ x_max = 0.0
168
+
169
+ for g in range(groups):
170
+ h_q = pid_hkv * groups + g
171
+ base_idx = (pid_b * H_q + h_q) * num_chunks
172
+ for c in range(num_chunks):
173
+ x_max = tl.maximum(x_max, tl.load(partial_max_ptr + base_idx + c))
174
+
175
+ FP8_MAX = 448.0
176
+ eps = 1e-12
177
+ scale_idx = pid_b * H_kv + pid_hkv
178
+
179
+ tl.store(scale_ptr + scale_idx, tl.where(x_max > eps, FP8_MAX / x_max, 1.0))
180
+ tl.store(descale_ptr + scale_idx, tl.where(x_max > eps, x_max / FP8_MAX, 1.0))
181
+
182
+
183
+ @triton.autotune(
184
+ configs=[
185
+ triton.Config({"BLOCK_SIZE": 512}, num_warps=4),
186
+ triton.Config({"BLOCK_SIZE": 1024}, num_warps=4),
187
+ triton.Config({"BLOCK_SIZE": 2048}, num_warps=8),
188
+ triton.Config({"BLOCK_SIZE": 4096}, num_warps=8),
189
+ ],
190
+ key=["chunk_size", "D"],
191
+ )
192
+ @triton.jit
193
+ def single_phase2_kernel(
194
+ # Input tensor [B, H, S, D]
195
+ x_ptr,
196
+ # Output tensor [B, H, S, D] - FP8 quantized
197
+ x_out_ptr,
198
+ # Precomputed scale [B, H_scale]
199
+ scale_ptr,
200
+ # Strides (for [B, H, S, D] layout)
201
+ stride_b,
202
+ stride_h,
203
+ stride_s,
204
+ stride_d,
205
+ # Dimensions
206
+ S,
207
+ D,
208
+ H,
209
+ chunk_size,
210
+ # Scale indexing for GQA: scale has H_scale entries per batch,
211
+ # and each group of `groups` heads shares one scale.
212
+ # For non-GQA: H_scale = H, groups = 1.
213
+ H_scale,
214
+ groups,
215
+ # Block size
216
+ BLOCK_SIZE: tl.constexpr,
217
+ ):
218
+ """
219
+ Phase 2 for a single tensor: Quantize to FP8 using precomputed scale.
220
+
221
+ Grid: (B, H, num_chunks)
222
+ """
223
+ pid_b = tl.program_id(axis=0)
224
+ pid_h = tl.program_id(axis=1)
225
+ pid_chunk = tl.program_id(axis=2)
226
+
227
+ # Load scale for this head (or head group for GQA)
228
+ scale = tl.load(scale_ptr + pid_b * H_scale + pid_h // groups)
229
+
230
+ # Compute the S range for this chunk
231
+ s_start = pid_chunk * chunk_size
232
+ s_end = tl.minimum(s_start + chunk_size, S)
233
+ chunk_elements = (s_end - s_start) * D
234
+
235
+ # Base pointer
236
+ base_offset = pid_b * stride_b + pid_h * stride_h
237
+
238
+ # Linearized iteration over chunk_size * D elements
239
+ for block_start in range(0, chunk_elements, BLOCK_SIZE):
240
+ offs = block_start + tl.arange(0, BLOCK_SIZE)
241
+ mask = offs < chunk_elements
242
+
243
+ # Convert linear offset to (s, d) coordinates
244
+ local_s = offs // D
245
+ d_idx = offs % D
246
+ s_idx = s_start + local_s
247
+
248
+ ptr_offset = base_offset + s_idx * stride_s + d_idx * stride_d
249
+
250
+ # Load input value
251
+ x_val = tl.load(x_ptr + ptr_offset, mask=mask, other=0.0).to(tl.float32)
252
+
253
+ # Quantize to FP8
254
+ x_fp8 = (x_val * scale).to(tl.float8e4nv)
255
+
256
+ # Store to output
257
+ tl.store(x_out_ptr + ptr_offset, x_fp8, mask=mask)
258
+
259
+
260
+ def triton_fp8_sdpa_quantize(
261
+ q: torch.Tensor,
262
+ k: torch.Tensor,
263
+ v: torch.Tensor,
264
+ num_chunks: Optional[int] = None,
265
+ ) -> Tuple[
266
+ torch.Tensor,
267
+ torch.Tensor,
268
+ torch.Tensor,
269
+ torch.Tensor,
270
+ torch.Tensor,
271
+ torch.Tensor,
272
+ ]:
273
+ """
274
+ Separated FP8 quantization for Q, K, V tensors.
275
+
276
+ Quantizes all tensors to FP8 with per-head scaling.
277
+ Each of Q, K, V is processed with independent kernel launches,
278
+ supporting GQA where Q has more heads than K/V (H_q = groups * H_kv)
279
+ and cross-attention where Q and K/V have different sequence lengths.
280
+
281
+ For GQA, Q is quantized with per-KV-group scaling so that q_descale
282
+ has shape [B, H_kv] as required by FA3.
283
+
284
+ Args:
285
+ q: Query tensor of shape [B, H_q, S_q, D] in bf16/fp16
286
+ k: Key tensor of shape [B, H_kv, S_kv, D] in bf16/fp16
287
+ v: Value tensor of shape [B, H_kv, S_kv, D] in bf16/fp16
288
+ num_chunks: Number of chunks to split the S dimension into.
289
+ If None, automatically selects based on GPU SM count.
290
+
291
+ Returns:
292
+ q_fp8: Quantized query, shape [B, H_q, S_q, D] in fp8
293
+ k_fp8: Quantized key, shape [B, H_kv, S_kv, D] in fp8
294
+ v_fp8: Quantized value, shape [B, H_kv, S_kv, D] in fp8
295
+ q_descale: Query descale factors, shape [B, H_kv] in fp32
296
+ k_descale: Key descale factors, shape [B, H_kv] in fp32
297
+ v_descale: Value descale factors, shape [B, H_kv] in fp32
298
+ """
299
+ assert q.dim() == 4, f"Expected 4D tensor [B, H, S, D], got {q.dim()}D"
300
+ assert k.dim() == 4, f"Expected 4D tensor [B, H, S, D], got {k.dim()}D"
301
+ assert v.dim() == 4, f"Expected 4D tensor [B, H, S, D], got {v.dim()}D"
302
+ assert k.shape == v.shape, (
303
+ f"K and V must have the same shape, got {k.shape} vs {v.shape}"
304
+ )
305
+ assert q.shape[0] == k.shape[0], (
306
+ f"Batch size mismatch: {q.shape[0]} vs {k.shape[0]}"
307
+ )
308
+ assert q.shape[3] == k.shape[3], f"Head dim mismatch: {q.shape[3]} vs {k.shape[3]}"
309
+ assert q.shape[1] % k.shape[1] == 0, (
310
+ f"Q heads ({q.shape[1]}) must be a multiple of K heads ({k.shape[1]})"
311
+ )
312
+
313
+ B, H_q, S_q, D = q.shape
314
+ H_kv = k.shape[1]
315
+ S_kv = k.shape[2]
316
+ groups = H_q // H_kv
317
+
318
+ # Make tensors contiguous if needed
319
+ q = q.contiguous()
320
+ k = k.contiguous()
321
+ v = v.contiguous()
322
+
323
+ # Compute number of chunks independently for Q and KV
324
+ if num_chunks is None:
325
+ q_num_chunks = _compute_num_chunks(q, S_q)
326
+ kv_num_chunks = _compute_num_chunks(k, S_kv)
327
+ else:
328
+ q_num_chunks = num_chunks
329
+ kv_num_chunks = num_chunks
330
+ q_chunk_size = (S_q + q_num_chunks - 1) // q_num_chunks
331
+ kv_chunk_size = (S_kv + kv_num_chunks - 1) // kv_num_chunks
332
+
333
+ # Allocate output tensors
334
+ q_fp8 = torch.empty_like(q, dtype=torch.float8_e4m3fn)
335
+ k_fp8 = torch.empty_like(k, dtype=torch.float8_e4m3fn)
336
+ v_fp8 = torch.empty_like(v, dtype=torch.float8_e4m3fn)
337
+
338
+ # Allocate partial max buffers (one per tensor)
339
+ q_partial_max = torch.empty(
340
+ B * H_q * q_num_chunks, dtype=torch.float32, device=q.device
341
+ )
342
+ k_partial_max = torch.empty(
343
+ B * H_kv * kv_num_chunks, dtype=torch.float32, device=q.device
344
+ )
345
+ v_partial_max = torch.empty(
346
+ B * H_kv * kv_num_chunks, dtype=torch.float32, device=q.device
347
+ )
348
+
349
+ # Allocate scale/descale tensors.
350
+ # For GQA, Q scale/descale are [B, H_kv] (per KV group).
351
+ # K and V are always [B, H_kv] (per head).
352
+ q_scale = torch.empty(B, H_kv, dtype=torch.float32, device=q.device)
353
+ k_scale = torch.empty(B, H_kv, dtype=torch.float32, device=q.device)
354
+ v_scale = torch.empty(B, H_kv, dtype=torch.float32, device=q.device)
355
+ q_descale = torch.empty(B, H_kv, dtype=torch.float32, device=q.device)
356
+ k_descale = torch.empty(B, H_kv, dtype=torch.float32, device=q.device)
357
+ v_descale = torch.empty(B, H_kv, dtype=torch.float32, device=q.device)
358
+
359
+ q_grid_chunked = (B, H_q, q_num_chunks)
360
+ kv_grid_chunked = (B, H_kv, kv_num_chunks)
361
+
362
+ # ---- Phase 1: Max for Q ----
363
+ single_phase1_kernel[q_grid_chunked](
364
+ q,
365
+ q_partial_max,
366
+ q.stride(0),
367
+ q.stride(1),
368
+ q.stride(2),
369
+ q.stride(3),
370
+ S_q,
371
+ D,
372
+ H_q,
373
+ q_chunk_size,
374
+ q_num_chunks,
375
+ )
376
+
377
+ # ---- Phase 1: Max for K ----
378
+ single_phase1_kernel[kv_grid_chunked](
379
+ k,
380
+ k_partial_max,
381
+ k.stride(0),
382
+ k.stride(1),
383
+ k.stride(2),
384
+ k.stride(3),
385
+ S_kv,
386
+ D,
387
+ H_kv,
388
+ kv_chunk_size,
389
+ kv_num_chunks,
390
+ )
391
+
392
+ # ---- Phase 1: Max for V ----
393
+ single_phase1_kernel[kv_grid_chunked](
394
+ v,
395
+ v_partial_max,
396
+ v.stride(0),
397
+ v.stride(1),
398
+ v.stride(2),
399
+ v.stride(3),
400
+ S_kv,
401
+ D,
402
+ H_kv,
403
+ kv_chunk_size,
404
+ kv_num_chunks,
405
+ )
406
+
407
+ # ---- Reduce ----
408
+ # Q: group reduce across `groups` Q heads per KV head
409
+ group_reduce_kernel[(B, H_kv)](
410
+ q_partial_max, q_scale, q_descale, H_q, H_kv, groups, q_num_chunks
411
+ )
412
+ # K, V: per-head reduce
413
+ single_reduce_kernel[(B, H_kv)](
414
+ k_partial_max, k_scale, k_descale, H_kv, kv_num_chunks
415
+ )
416
+ single_reduce_kernel[(B, H_kv)](
417
+ v_partial_max, v_scale, v_descale, H_kv, kv_num_chunks
418
+ )
419
+
420
+ # ---- Phase 2: Quantize Q ----
421
+ # Q scale is [B, H_kv]; each group of `groups` Q heads shares one scale.
422
+ single_phase2_kernel[q_grid_chunked](
423
+ q,
424
+ q_fp8,
425
+ q_scale,
426
+ q.stride(0),
427
+ q.stride(1),
428
+ q.stride(2),
429
+ q.stride(3),
430
+ S_q,
431
+ D,
432
+ H_q,
433
+ q_chunk_size,
434
+ H_kv,
435
+ groups,
436
+ )
437
+
438
+ # ---- Phase 2: Quantize K ----
439
+ # K scale is [B, H_kv]; groups=1 (per-head).
440
+ single_phase2_kernel[kv_grid_chunked](
441
+ k,
442
+ k_fp8,
443
+ k_scale,
444
+ k.stride(0),
445
+ k.stride(1),
446
+ k.stride(2),
447
+ k.stride(3),
448
+ S_kv,
449
+ D,
450
+ H_kv,
451
+ kv_chunk_size,
452
+ H_kv,
453
+ 1,
454
+ )
455
+
456
+ # ---- Phase 2: Quantize V ----
457
+ # V scale is [B, H_kv]; groups=1 (per-head).
458
+ single_phase2_kernel[kv_grid_chunked](
459
+ v,
460
+ v_fp8,
461
+ v_scale,
462
+ v.stride(0),
463
+ v.stride(1),
464
+ v.stride(2),
465
+ v.stride(3),
466
+ S_kv,
467
+ D,
468
+ H_kv,
469
+ kv_chunk_size,
470
+ H_kv,
471
+ 1,
472
+ )
473
+
474
+ return q_fp8, k_fp8, v_fp8, q_descale, k_descale, v_descale
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/quantization/triton_rope_qkv_quantization.py ADDED
@@ -0,0 +1,745 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD 3-Clause license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ """
8
+ Fused RoPE + FP8 quantization kernels for Q, K, V.
9
+
10
+ Input: [B, S, H, D], output: [B, H, S, D].
11
+ Supports GQA (different head counts for Q vs K/V).
12
+ """
13
+
14
+ from typing import Optional, Tuple
15
+
16
+ import torch
17
+ import triton
18
+ import triton.language as tl
19
+
20
+
21
+ def _compute_num_chunks(tensor: torch.Tensor, S: int) -> int:
22
+ """Compute optimal number of chunks based on GPU properties."""
23
+ props = torch.cuda.get_device_properties(tensor.device)
24
+ num_sms = props.multi_processor_count
25
+ B, _, H, _ = tensor.shape # [B, S, H, D]
26
+ base_parallelism = B * H
27
+ # Target 2-4x SMs for good occupancy/latency hiding
28
+ target_blocks = num_sms * 4
29
+ num_chunks = max(1, target_blocks // base_parallelism)
30
+ # Ensure each chunk has at least 32 S positions for efficiency
31
+ num_chunks = min(num_chunks, S // 32) if S >= 32 else 1
32
+ # Cap at reasonable maximum
33
+ num_chunks = min(num_chunks, 64)
34
+ # Adjust if S is small
35
+ num_chunks = min(num_chunks, S)
36
+ return num_chunks
37
+
38
+
39
+ @triton.autotune(
40
+ configs=[
41
+ triton.Config({"BLOCK_SIZE": 256}, num_warps=4),
42
+ triton.Config({"BLOCK_SIZE": 512}, num_warps=4),
43
+ triton.Config({"BLOCK_SIZE": 1024}, num_warps=8),
44
+ triton.Config({"BLOCK_SIZE": 2048}, num_warps=8),
45
+ ],
46
+ key=["chunk_size", "D_HALF"],
47
+ )
48
+ @triton.jit
49
+ def rope_single_phase1_kernel(
50
+ # Input tensor [B, S, H, D]
51
+ x_ptr,
52
+ # RoPE frequency tensors [S, D]
53
+ cos_ptr,
54
+ sin_ptr,
55
+ # Intermediate output tensor [B, H, S, D] - stores RoPE'd result
56
+ x_rope_ptr,
57
+ # Output: partial max values [B * H * num_chunks]
58
+ partial_max_ptr,
59
+ # Input strides (for [B, S, H, D] layout)
60
+ stride_in_b,
61
+ stride_in_s,
62
+ stride_in_h,
63
+ stride_in_d,
64
+ # Output strides (for [B, H, S, D] layout)
65
+ stride_out_b,
66
+ stride_out_h,
67
+ stride_out_s,
68
+ stride_out_d,
69
+ # Dimensions
70
+ S,
71
+ D,
72
+ D_HALF,
73
+ H,
74
+ chunk_size,
75
+ num_chunks,
76
+ # Block size
77
+ BLOCK_SIZE: tl.constexpr,
78
+ ROPE_INTERLEAVED: tl.constexpr,
79
+ ):
80
+ """
81
+ Phase 1 for a single tensor (Q or K): Apply RoPE, store to intermediate,
82
+ compute partial max.
83
+
84
+ Grid: (B, H, num_chunks)
85
+
86
+ Supports two RoPE pairing variants (selected by ROPE_INTERLEAVED constexpr):
87
+ - NeoX half-split (ROPE_INTERLEAVED=False): pairs (j, j+D/2) for j in [0, D/2)
88
+ - Interleaved (ROPE_INTERLEAVED=True): pairs (2i, 2i+1) for i in [0, D/2)
89
+
90
+ Each pair shares the same rotation angle and the 2D rotation formula is:
91
+ out[first] = x[first]*cos - x[second]*sin
92
+ out[second] = x[second]*cos + x[first]*sin
93
+ """
94
+ pid_b = tl.program_id(axis=0)
95
+ pid_h = tl.program_id(axis=1)
96
+ pid_chunk = tl.program_id(axis=2)
97
+
98
+ # Compute the S range for this chunk
99
+ s_start = pid_chunk * chunk_size
100
+ s_end = tl.minimum(s_start + chunk_size, S)
101
+ actual_chunk_size = s_end - s_start
102
+
103
+ # Number of pairs to process in this chunk
104
+ chunk_pairs = actual_chunk_size * D_HALF
105
+
106
+ # Base pointers for input [B, S, H, D]
107
+ in_base_b = pid_b * stride_in_b
108
+ in_base_h = pid_h * stride_in_h
109
+
110
+ # Base pointers for output [B, H, S, D]
111
+ out_base_b = pid_b * stride_out_b
112
+ out_base_h = pid_h * stride_out_h
113
+
114
+ # Initialize max accumulator
115
+ x_max = 0.0
116
+
117
+ # Linearized iteration over chunk_size * D_HALF pairs
118
+ for block_start in range(0, chunk_pairs, BLOCK_SIZE):
119
+ offs = block_start + tl.arange(0, BLOCK_SIZE)
120
+ mask = offs < chunk_pairs
121
+
122
+ # Convert linear offset to (s, pair_idx) coordinates
123
+ local_s = offs // D_HALF
124
+ pair_idx = offs % D_HALF
125
+ s_idx = s_start + local_s
126
+
127
+ # Compute element indices for this pair based on RoPE variant
128
+ if ROPE_INTERLEAVED:
129
+ # FLUX/GPT-J interleaved: pair (2i, 2i+1)
130
+ d_first = pair_idx * 2
131
+ d_second = pair_idx * 2 + 1
132
+ else:
133
+ # NeoX/LLaMA half-split: pair (j, j+D/2)
134
+ d_first = pair_idx
135
+ d_second = pair_idx + D_HALF
136
+
137
+ # Input offsets [B, S, H, D]
138
+ in_offset_first = (
139
+ in_base_b + s_idx * stride_in_s + in_base_h + d_first * stride_in_d
140
+ )
141
+ in_offset_second = (
142
+ in_base_b + s_idx * stride_in_s + in_base_h + d_second * stride_in_d
143
+ )
144
+
145
+ # Output offsets [B, H, S, D]
146
+ out_offset_first = (
147
+ out_base_b + out_base_h + s_idx * stride_out_s + d_first * stride_out_d
148
+ )
149
+ out_offset_second = (
150
+ out_base_b + out_base_h + s_idx * stride_out_s + d_second * stride_out_d
151
+ )
152
+
153
+ # Load input pairs (each element loaded exactly once)
154
+ x_first = tl.load(x_ptr + in_offset_first, mask=mask, other=0.0).to(tl.float32)
155
+ x_second = tl.load(x_ptr + in_offset_second, mask=mask, other=0.0).to(
156
+ tl.float32
157
+ )
158
+
159
+ # Load cos/sin — both elements in a NeoX pair share the same
160
+ # rotation angle. cos[j] == cos[j+D/2] in LLaMA's frequency
161
+ # layout, so we only need one load per pair.
162
+ cos_offset = s_idx * D + d_first
163
+ cos_val = tl.load(cos_ptr + cos_offset, mask=mask, other=1.0).to(tl.float32)
164
+ sin_val = tl.load(sin_ptr + cos_offset, mask=mask, other=0.0).to(tl.float32)
165
+
166
+ # Apply NeoX RoPE rotation:
167
+ # out[j] = x[j] * cos - x[j+D/2] * sin
168
+ # out[j+D/2] = x[j+D/2] * cos + x[j] * sin
169
+ x_rope_first = tl.math.fma(x_first, cos_val, -(x_second * sin_val))
170
+ x_rope_second = tl.math.fma(x_second, cos_val, x_first * sin_val)
171
+
172
+ # Store RoPE'd result to intermediate buffer [B, H, S, D]
173
+ tl.store(
174
+ x_rope_ptr + out_offset_first, x_rope_first.to(x_first.dtype), mask=mask
175
+ )
176
+ tl.store(
177
+ x_rope_ptr + out_offset_second, x_rope_second.to(x_first.dtype), mask=mask
178
+ )
179
+
180
+ # Update max values (from RoPE'd values)
181
+ x_max = tl.maximum(x_max, tl.max(tl.abs(x_rope_first)))
182
+ x_max = tl.maximum(x_max, tl.max(tl.abs(x_rope_second)))
183
+
184
+ # Store partial max
185
+ chunk_idx = pid_b * (H * num_chunks) + pid_h * num_chunks + pid_chunk
186
+ tl.store(partial_max_ptr + chunk_idx, x_max)
187
+
188
+
189
+ @triton.autotune(
190
+ configs=[
191
+ triton.Config({"BLOCK_SIZE": 512}, num_warps=4),
192
+ triton.Config({"BLOCK_SIZE": 1024}, num_warps=4),
193
+ triton.Config({"BLOCK_SIZE": 2048}, num_warps=8),
194
+ triton.Config({"BLOCK_SIZE": 4096}, num_warps=8),
195
+ ],
196
+ key=["chunk_size", "D"],
197
+ )
198
+ @triton.jit
199
+ def v_phase1_kernel(
200
+ # Input tensor [B, S, H, D]
201
+ v_ptr,
202
+ # Output: partial max values [B * H * num_chunks]
203
+ partial_max_ptr,
204
+ # Input strides (for [B, S, H, D] layout)
205
+ stride_in_b,
206
+ stride_in_s,
207
+ stride_in_h,
208
+ stride_in_d,
209
+ # Dimensions
210
+ S,
211
+ D,
212
+ H,
213
+ chunk_size,
214
+ num_chunks,
215
+ # Block size
216
+ BLOCK_SIZE: tl.constexpr,
217
+ ):
218
+ """
219
+ Phase 1 for V: Compute partial absmax (no RoPE applied).
220
+
221
+ Grid: (B, H, num_chunks)
222
+
223
+ Uses linearized iteration over chunk_size * D elements.
224
+ """
225
+ pid_b = tl.program_id(axis=0)
226
+ pid_h = tl.program_id(axis=1)
227
+ pid_chunk = tl.program_id(axis=2)
228
+
229
+ # Compute the S range for this chunk
230
+ s_start = pid_chunk * chunk_size
231
+ s_end = tl.minimum(s_start + chunk_size, S)
232
+ chunk_elements = (s_end - s_start) * D
233
+
234
+ # Base pointers for input [B, S, H, D]
235
+ in_base_b = pid_b * stride_in_b
236
+ in_base_h = pid_h * stride_in_h
237
+
238
+ # Initialize max accumulator
239
+ v_max = 0.0
240
+
241
+ # Linearized iteration over chunk_size * D elements
242
+ for block_start in range(0, chunk_elements, BLOCK_SIZE):
243
+ offs = block_start + tl.arange(0, BLOCK_SIZE)
244
+ mask = offs < chunk_elements
245
+
246
+ # Convert linear offset to (s, d) coordinates
247
+ local_s = offs // D
248
+ d_idx = offs % D
249
+ s_idx = s_start + local_s
250
+
251
+ # Input offset [B, S, H, D]
252
+ in_offset = in_base_b + s_idx * stride_in_s + in_base_h + d_idx * stride_in_d
253
+
254
+ v_val = tl.load(v_ptr + in_offset, mask=mask, other=0.0).to(tl.float32)
255
+ v_max = tl.maximum(v_max, tl.max(tl.abs(v_val)))
256
+
257
+ # Store partial max
258
+ chunk_idx = pid_b * (H * num_chunks) + pid_h * num_chunks + pid_chunk
259
+ tl.store(partial_max_ptr + chunk_idx, v_max)
260
+
261
+
262
+ @triton.jit
263
+ def single_reduce_kernel(
264
+ partial_max_ptr, # [B * H * num_chunks]
265
+ scale_ptr,
266
+ descale_ptr,
267
+ H,
268
+ num_chunks,
269
+ ):
270
+ """
271
+ Reduce partial maxes and compute scale/descale for a single tensor.
272
+
273
+ Grid: (B, H)
274
+ """
275
+ pid_b = tl.program_id(axis=0)
276
+ pid_h = tl.program_id(axis=1)
277
+
278
+ # Reduce across chunks for this (batch, head)
279
+ x_max = 0.0
280
+
281
+ base_idx = (pid_b * H + pid_h) * num_chunks
282
+ for c in range(num_chunks):
283
+ x_max = tl.maximum(x_max, tl.load(partial_max_ptr + base_idx + c))
284
+
285
+ # Compute scale and descale
286
+ # FP8 E4M3 max value is 448.0
287
+ FP8_MAX = 448.0
288
+ eps = 1e-12
289
+ scale_idx = pid_b * H + pid_h
290
+
291
+ tl.store(scale_ptr + scale_idx, tl.where(x_max > eps, FP8_MAX / x_max, 1.0))
292
+ tl.store(descale_ptr + scale_idx, tl.where(x_max > eps, x_max / FP8_MAX, 1.0))
293
+
294
+
295
+ @triton.jit
296
+ def group_reduce_kernel(
297
+ partial_max_ptr, # [B * H_q * num_chunks]
298
+ scale_ptr, # [B, H_kv]
299
+ descale_ptr, # [B, H_kv]
300
+ H_q,
301
+ H_kv,
302
+ groups, # H_q // H_kv
303
+ num_chunks,
304
+ ):
305
+ """
306
+ Reduce partial maxes across head groups for GQA Q tensor.
307
+
308
+ For each KV group, reduces the max across all Q heads in that group
309
+ and all chunks, producing one scale per (batch, kv_head).
310
+
311
+ Grid: (B, H_kv)
312
+ """
313
+ pid_b = tl.program_id(axis=0)
314
+ pid_hkv = tl.program_id(axis=1)
315
+
316
+ x_max = 0.0
317
+
318
+ for g in range(groups):
319
+ h_q = pid_hkv * groups + g
320
+ base_idx = (pid_b * H_q + h_q) * num_chunks
321
+ for c in range(num_chunks):
322
+ x_max = tl.maximum(x_max, tl.load(partial_max_ptr + base_idx + c))
323
+
324
+ FP8_MAX = 448.0
325
+ eps = 1e-12
326
+ scale_idx = pid_b * H_kv + pid_hkv
327
+
328
+ tl.store(scale_ptr + scale_idx, tl.where(x_max > eps, FP8_MAX / x_max, 1.0))
329
+ tl.store(descale_ptr + scale_idx, tl.where(x_max > eps, x_max / FP8_MAX, 1.0))
330
+
331
+
332
+ @triton.autotune(
333
+ configs=[
334
+ triton.Config({"BLOCK_SIZE": 512}, num_warps=4),
335
+ triton.Config({"BLOCK_SIZE": 1024}, num_warps=4),
336
+ triton.Config({"BLOCK_SIZE": 2048}, num_warps=8),
337
+ triton.Config({"BLOCK_SIZE": 4096}, num_warps=8),
338
+ ],
339
+ key=["chunk_size", "D"],
340
+ )
341
+ @triton.jit
342
+ def rope_single_phase2_kernel(
343
+ # Intermediate tensor [B, H, S, D] - already RoPE'd
344
+ x_rope_ptr,
345
+ # Output tensor [B, H, S, D] - FP8 quantized
346
+ x_out_ptr,
347
+ # Precomputed scale [B, H_scale]
348
+ scale_ptr,
349
+ # Strides (for [B, H, S, D] layout) - same for intermediate and output
350
+ stride_b,
351
+ stride_h,
352
+ stride_s,
353
+ stride_d,
354
+ # Dimensions
355
+ S,
356
+ D,
357
+ H,
358
+ chunk_size,
359
+ # Scale indexing for GQA: scale has H_scale entries per batch,
360
+ # and each group of `groups` heads shares one scale.
361
+ # For non-GQA: H_scale = H, groups = 1.
362
+ H_scale,
363
+ groups,
364
+ # Block size
365
+ BLOCK_SIZE: tl.constexpr,
366
+ ):
367
+ """
368
+ Phase 2 for a single tensor (Q or K): Quantize pre-computed RoPE'd values to FP8.
369
+
370
+ Grid: (B, H, num_chunks)
371
+ """
372
+ pid_b = tl.program_id(axis=0)
373
+ pid_h = tl.program_id(axis=1)
374
+ pid_chunk = tl.program_id(axis=2)
375
+
376
+ # Load scale for this head (or head group for GQA)
377
+ scale = tl.load(scale_ptr + pid_b * H_scale + pid_h // groups)
378
+
379
+ # Compute the S range for this chunk
380
+ s_start = pid_chunk * chunk_size
381
+ s_end = tl.minimum(s_start + chunk_size, S)
382
+ chunk_elements = (s_end - s_start) * D
383
+
384
+ # Base pointer
385
+ base_offset = pid_b * stride_b + pid_h * stride_h
386
+
387
+ # Linearized iteration over chunk_size * D elements
388
+ for block_start in range(0, chunk_elements, BLOCK_SIZE):
389
+ offs = block_start + tl.arange(0, BLOCK_SIZE)
390
+ mask = offs < chunk_elements
391
+
392
+ # Convert linear offset to (s, d) coordinates
393
+ local_s = offs // D
394
+ d_idx = offs % D
395
+ s_idx = s_start + local_s
396
+
397
+ ptr_offset = base_offset + s_idx * stride_s + d_idx * stride_d
398
+
399
+ # Load pre-computed RoPE'd value from intermediate buffer
400
+ x_val = tl.load(x_rope_ptr + ptr_offset, mask=mask, other=0.0).to(tl.float32)
401
+
402
+ # Quantize to FP8
403
+ x_fp8 = (x_val * scale).to(tl.float8e4nv)
404
+
405
+ # Store to output
406
+ tl.store(x_out_ptr + ptr_offset, x_fp8, mask=mask)
407
+
408
+
409
+ @triton.autotune(
410
+ configs=[
411
+ triton.Config({"BLOCK_SIZE": 512}, num_warps=4),
412
+ triton.Config({"BLOCK_SIZE": 1024}, num_warps=4),
413
+ triton.Config({"BLOCK_SIZE": 2048}, num_warps=8),
414
+ triton.Config({"BLOCK_SIZE": 4096}, num_warps=8),
415
+ ],
416
+ key=["chunk_size", "D"],
417
+ )
418
+ @triton.jit
419
+ def v_phase2_kernel(
420
+ # Original V tensor [B, S, H, D] - needs transpose only
421
+ v_ptr,
422
+ # Output tensor [B, H, S, D] - FP8 quantized
423
+ v_out_ptr,
424
+ # Precomputed scale [B, H]
425
+ scale_ptr,
426
+ # V input strides (for [B, S, H, D] layout)
427
+ stride_v_in_b,
428
+ stride_v_in_s,
429
+ stride_v_in_h,
430
+ stride_v_in_d,
431
+ # Output strides (for [B, H, S, D] layout)
432
+ stride_out_b,
433
+ stride_out_h,
434
+ stride_out_s,
435
+ stride_out_d,
436
+ # Dimensions
437
+ S,
438
+ D,
439
+ H,
440
+ chunk_size,
441
+ # Block size
442
+ BLOCK_SIZE: tl.constexpr,
443
+ ):
444
+ """
445
+ Phase 2 for V: Transpose from [B,S,H,D] to [B,H,S,D] and quantize to FP8.
446
+
447
+ Grid: (B, H, num_chunks)
448
+ """
449
+ pid_b = tl.program_id(axis=0)
450
+ pid_h = tl.program_id(axis=1)
451
+ pid_chunk = tl.program_id(axis=2)
452
+
453
+ # Load scale for this head
454
+ scale = tl.load(scale_ptr + pid_b * H + pid_h)
455
+
456
+ # Compute the S range for this chunk
457
+ s_start = pid_chunk * chunk_size
458
+ s_end = tl.minimum(s_start + chunk_size, S)
459
+ chunk_elements = (s_end - s_start) * D
460
+
461
+ # Base pointers
462
+ v_in_base = pid_b * stride_v_in_b + pid_h * stride_v_in_h
463
+ out_base = pid_b * stride_out_b + pid_h * stride_out_h
464
+
465
+ # Linearized iteration over chunk_size * D elements
466
+ for block_start in range(0, chunk_elements, BLOCK_SIZE):
467
+ offs = block_start + tl.arange(0, BLOCK_SIZE)
468
+ mask = offs < chunk_elements
469
+
470
+ # Convert linear offset to (s, d) coordinates
471
+ local_s = offs // D
472
+ d_idx = offs % D
473
+ s_idx = s_start + local_s
474
+
475
+ # V input offset [B, S, H, D]
476
+ v_in_offset = v_in_base + s_idx * stride_v_in_s + d_idx * stride_v_in_d
477
+
478
+ # Output offset [B, H, S, D]
479
+ out_offset = out_base + s_idx * stride_out_s + d_idx * stride_out_d
480
+
481
+ # Load V from original input (no RoPE, just transpose)
482
+ v_val = tl.load(v_ptr + v_in_offset, mask=mask, other=0.0).to(tl.float32)
483
+
484
+ # Quantize to FP8
485
+ v_fp8 = (v_val * scale).to(tl.float8e4nv)
486
+
487
+ # Store to output
488
+ tl.store(v_out_ptr + out_offset, v_fp8, mask=mask)
489
+
490
+
491
+ def triton_fp8_rope_sdpa_quantize(
492
+ q: torch.Tensor,
493
+ k: torch.Tensor,
494
+ v: torch.Tensor,
495
+ cos: torch.Tensor,
496
+ sin: torch.Tensor,
497
+ num_chunks: Optional[int] = None,
498
+ rope_interleaved: bool = False,
499
+ ) -> Tuple[
500
+ torch.Tensor,
501
+ torch.Tensor,
502
+ torch.Tensor,
503
+ torch.Tensor,
504
+ torch.Tensor,
505
+ torch.Tensor,
506
+ ]:
507
+ """
508
+ Separated RoPE + FP8 quantization for Q, K, V tensors.
509
+
510
+ Applies RoPE to Q and K, then quantizes all tensors to FP8 with per-head scaling.
511
+ Also performs layout transformation from [B, S, H, D] to [B, H, S, D].
512
+ Each of Q, K, V is processed with independent kernel launches.
513
+
514
+ Supports GQA where Q has more heads than K/V (H_q = groups * H_kv).
515
+ For GQA, Q is quantized with per-KV-group scaling so that q_descale
516
+ has shape [B, H_kv] as required by FA3.
517
+
518
+ Args:
519
+ q: Query tensor of shape [B, S, H_q, D] in bf16/fp16
520
+ k: Key tensor of shape [B, S, H_kv, D] in bf16/fp16
521
+ v: Value tensor of shape [B, S, H_kv, D] in bf16/fp16
522
+ cos: Cosine frequencies for RoPE, shape [S, D]
523
+ sin: Sine frequencies for RoPE, shape [S, D]
524
+ num_chunks: Number of chunks to split S dimension into.
525
+ If None, automatically selects based on GPU SM count.
526
+
527
+ Returns:
528
+ q_fp8: Quantized query with RoPE, shape [B, H_q, S, D] in fp8
529
+ k_fp8: Quantized key with RoPE, shape [B, H_kv, S, D] in fp8
530
+ v_fp8: Quantized value, shape [B, H_kv, S, D] in fp8
531
+ q_descale: Query descale factors, shape [B, H_kv] in fp32
532
+ k_descale: Key descale factors, shape [B, H_kv] in fp32
533
+ v_descale: Value descale factors, shape [B, H_kv] in fp32
534
+ """
535
+ assert q.dim() == 4, f"Expected 4D tensor [B, S, H, D], got {q.dim()}D"
536
+ assert k.dim() == 4, f"Expected 4D tensor [B, S, H, D], got {k.dim()}D"
537
+ assert v.dim() == 4, f"Expected 4D tensor [B, S, H, D], got {v.dim()}D"
538
+ assert k.shape == v.shape, (
539
+ f"K and V must have the same shape, got {k.shape} vs {v.shape}"
540
+ )
541
+ assert q.shape[0] == k.shape[0], (
542
+ f"Batch size mismatch: {q.shape[0]} vs {k.shape[0]}"
543
+ )
544
+ assert q.shape[1] == k.shape[1], (
545
+ f"Sequence length mismatch: {q.shape[1]} vs {k.shape[1]}"
546
+ )
547
+ assert q.shape[3] == k.shape[3], f"Head dim mismatch: {q.shape[3]} vs {k.shape[3]}"
548
+ assert q.shape[2] % k.shape[2] == 0, (
549
+ f"Q heads ({q.shape[2]}) must be a multiple of K heads ({k.shape[2]})"
550
+ )
551
+ assert cos.dim() == 2, f"Expected 2D cos tensor [S, D], got {cos.dim()}D"
552
+ assert sin.dim() == 2, f"Expected 2D sin tensor [S, D], got {sin.dim()}D"
553
+
554
+ B, S, H_q, D = q.shape
555
+ H_kv = k.shape[2]
556
+ groups = H_q // H_kv
557
+
558
+ assert D % 2 == 0, f"Head dimension D must be even for RoPE, got D={D}"
559
+ assert cos.shape == (S, D), f"Expected cos shape [{S}, {D}], got {cos.shape}"
560
+ assert sin.shape == (S, D), f"Expected sin shape [{S}, {D}], got {sin.shape}"
561
+
562
+ D_HALF = D // 2
563
+
564
+ # Make tensors contiguous if needed
565
+ q = q.contiguous()
566
+ k = k.contiguous()
567
+ v = v.contiguous()
568
+ cos = cos.contiguous()
569
+ sin = sin.contiguous()
570
+
571
+ # Compute number of chunks
572
+ if num_chunks is None:
573
+ num_chunks = _compute_num_chunks(q, S)
574
+ chunk_size = (S + num_chunks - 1) // num_chunks
575
+
576
+ # Allocate output tensors in [B, H, S, D] layout for SDPA
577
+ q_fp8 = torch.empty(B, H_q, S, D, dtype=torch.float8_e4m3fn, device=q.device)
578
+ k_fp8 = torch.empty(B, H_kv, S, D, dtype=torch.float8_e4m3fn, device=q.device)
579
+ v_fp8 = torch.empty(B, H_kv, S, D, dtype=torch.float8_e4m3fn, device=q.device)
580
+
581
+ # Allocate intermediate buffers for RoPE'd Q, K in [B, H, S, D] layout
582
+ q_rope_intermediate = torch.empty(B, H_q, S, D, dtype=q.dtype, device=q.device)
583
+ k_rope_intermediate = torch.empty(B, H_kv, S, D, dtype=k.dtype, device=q.device)
584
+
585
+ # Allocate partial max buffers (one per tensor)
586
+ q_partial_max = torch.empty(
587
+ B * H_q * num_chunks, dtype=torch.float32, device=q.device
588
+ )
589
+ k_partial_max = torch.empty(
590
+ B * H_kv * num_chunks, dtype=torch.float32, device=q.device
591
+ )
592
+ v_partial_max = torch.empty(
593
+ B * H_kv * num_chunks, dtype=torch.float32, device=q.device
594
+ )
595
+
596
+ # Allocate scale/descale tensors.
597
+ # For GQA, Q scale/descale are [B, H_kv] (per KV group).
598
+ # K and V are always [B, H_kv] (per head).
599
+ q_scale = torch.empty(B, H_kv, dtype=torch.float32, device=q.device)
600
+ k_scale = torch.empty(B, H_kv, dtype=torch.float32, device=q.device)
601
+ v_scale = torch.empty(B, H_kv, dtype=torch.float32, device=q.device)
602
+ q_descale = torch.empty(B, H_kv, dtype=torch.float32, device=q.device)
603
+ k_descale = torch.empty(B, H_kv, dtype=torch.float32, device=q.device)
604
+ v_descale = torch.empty(B, H_kv, dtype=torch.float32, device=q.device)
605
+
606
+ q_grid_chunked = (B, H_q, num_chunks)
607
+ kv_grid_chunked = (B, H_kv, num_chunks)
608
+
609
+ # ---- Phase 1: RoPE + max for Q ----
610
+ rope_single_phase1_kernel[q_grid_chunked](
611
+ q,
612
+ cos,
613
+ sin,
614
+ q_rope_intermediate,
615
+ q_partial_max,
616
+ # Input strides [B, S, H_q, D]
617
+ q.stride(0),
618
+ q.stride(1),
619
+ q.stride(2),
620
+ q.stride(3),
621
+ # Output strides [B, H_q, S, D]
622
+ q_rope_intermediate.stride(0),
623
+ q_rope_intermediate.stride(1),
624
+ q_rope_intermediate.stride(2),
625
+ q_rope_intermediate.stride(3),
626
+ S,
627
+ D,
628
+ D_HALF,
629
+ H_q,
630
+ chunk_size,
631
+ num_chunks,
632
+ ROPE_INTERLEAVED=rope_interleaved,
633
+ )
634
+
635
+ # ---- Phase 1: RoPE + max for K ----
636
+ rope_single_phase1_kernel[kv_grid_chunked](
637
+ k,
638
+ cos,
639
+ sin,
640
+ k_rope_intermediate,
641
+ k_partial_max,
642
+ # Input strides [B, S, H_kv, D]
643
+ k.stride(0),
644
+ k.stride(1),
645
+ k.stride(2),
646
+ k.stride(3),
647
+ # Output strides [B, H_kv, S, D]
648
+ k_rope_intermediate.stride(0),
649
+ k_rope_intermediate.stride(1),
650
+ k_rope_intermediate.stride(2),
651
+ k_rope_intermediate.stride(3),
652
+ S,
653
+ D,
654
+ D_HALF,
655
+ H_kv,
656
+ chunk_size,
657
+ num_chunks,
658
+ ROPE_INTERLEAVED=rope_interleaved,
659
+ )
660
+
661
+ # ---- Phase 1: Max for V (no RoPE) ----
662
+ v_phase1_kernel[kv_grid_chunked](
663
+ v,
664
+ v_partial_max,
665
+ # Input strides [B, S, H_kv, D]
666
+ v.stride(0),
667
+ v.stride(1),
668
+ v.stride(2),
669
+ v.stride(3),
670
+ S,
671
+ D,
672
+ H_kv,
673
+ chunk_size,
674
+ num_chunks,
675
+ )
676
+
677
+ # ---- Reduce ----
678
+ # Q: group reduce across `groups` Q heads per KV head
679
+ group_reduce_kernel[(B, H_kv)](
680
+ q_partial_max, q_scale, q_descale, H_q, H_kv, groups, num_chunks
681
+ )
682
+ # K, V: per-head reduce
683
+ single_reduce_kernel[(B, H_kv)](k_partial_max, k_scale, k_descale, H_kv, num_chunks)
684
+ single_reduce_kernel[(B, H_kv)](v_partial_max, v_scale, v_descale, H_kv, num_chunks)
685
+
686
+ # ---- Phase 2: Quantize Q from intermediate ----
687
+ # Q scale is [B, H_kv]; each group of `groups` Q heads shares one scale.
688
+ rope_single_phase2_kernel[q_grid_chunked](
689
+ q_rope_intermediate,
690
+ q_fp8,
691
+ q_scale,
692
+ # Strides [B, H_q, S, D]
693
+ q_fp8.stride(0),
694
+ q_fp8.stride(1),
695
+ q_fp8.stride(2),
696
+ q_fp8.stride(3),
697
+ S,
698
+ D,
699
+ H_q,
700
+ chunk_size,
701
+ H_kv,
702
+ groups,
703
+ )
704
+
705
+ # ---- Phase 2: Quantize K from intermediate ----
706
+ # K scale is [B, H_kv]; groups=1 (per-head).
707
+ rope_single_phase2_kernel[kv_grid_chunked](
708
+ k_rope_intermediate,
709
+ k_fp8,
710
+ k_scale,
711
+ # Strides [B, H_kv, S, D]
712
+ k_fp8.stride(0),
713
+ k_fp8.stride(1),
714
+ k_fp8.stride(2),
715
+ k_fp8.stride(3),
716
+ S,
717
+ D,
718
+ H_kv,
719
+ chunk_size,
720
+ H_kv,
721
+ 1,
722
+ )
723
+
724
+ # ---- Phase 2: Transpose + quantize V ----
725
+ v_phase2_kernel[kv_grid_chunked](
726
+ v,
727
+ v_fp8,
728
+ v_scale,
729
+ # V input strides [B, S, H_kv, D]
730
+ v.stride(0),
731
+ v.stride(1),
732
+ v.stride(2),
733
+ v.stride(3),
734
+ # Output strides [B, H_kv, S, D]
735
+ v_fp8.stride(0),
736
+ v_fp8.stride(1),
737
+ v_fp8.stride(2),
738
+ v_fp8.stride(3),
739
+ S,
740
+ D,
741
+ H_kv,
742
+ chunk_size,
743
+ )
744
+
745
+ return q_fp8, k_fp8, v_fp8, q_descale, k_descale, v_descale
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/shared_utils/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD 3-Clause license found in the
5
+ # LICENSE file in the root directory of this source tree.
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/shared_utils/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (214 Bytes). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/shared_utils/__pycache__/attention.cpython-310.pyc ADDED
Binary file (3.13 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/shared_utils/__pycache__/custom_ops.cpython-310.pyc ADDED
Binary file (3.1 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/shared_utils/__pycache__/fusion_utils.cpython-310.pyc ADDED
Binary file (18.9 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/shared_utils/__pycache__/setup.cpython-310.pyc ADDED
Binary file (1.21 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/shared_utils/__pycache__/wrapper.cpython-310.pyc ADDED
Binary file (3.02 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/shared_utils/attention.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD 3-Clause license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ """
8
+ Shared FP8 scaled dot-product attention implementation.
9
+
10
+ Backend-specific modules (``fp8_fa3/attention.py``, etc.) provide thin
11
+ named wrappers around these functions via ``functools.partial``.
12
+ """
13
+
14
+ from typing import Optional
15
+
16
+ import torch
17
+
18
+ from torchao.utils import torch_version_at_least
19
+
20
+ _TORCH_VERSION_AT_LEAST_2_11 = torch_version_at_least("2.11.0")
21
+
22
+ if _TORCH_VERSION_AT_LEAST_2_11:
23
+ from torch.nn.attention import SDPBackend, sdpa_kernel
24
+ from torch.nn.attention.experimental._scaled_dot_product_attention_quantized import (
25
+ _scaled_dot_product_attention_quantized,
26
+ )
27
+
28
+ from torchao.prototype.attention.quantization import (
29
+ _fp8_rope_sdpa_quantize,
30
+ _fp8_sdpa_quantize,
31
+ )
32
+
33
+
34
+ def _fp8_sdpa(
35
+ query: torch.Tensor,
36
+ key: torch.Tensor,
37
+ value: torch.Tensor,
38
+ attn_mask: Optional[torch.Tensor] = None,
39
+ dropout_p: float = 0.0,
40
+ is_causal: bool = False,
41
+ scale: Optional[float] = None,
42
+ enable_gqa: bool = False,
43
+ *,
44
+ backend_name: str = "FP8",
45
+ ) -> torch.Tensor:
46
+ """FP8 SDPA shared by all backends.
47
+
48
+ The correct flash attention implementation (e.g. FA3) must be
49
+ activated before calling this function. The high-level
50
+ ``apply_low_precision_attention`` API handles this automatically.
51
+
52
+ Input/output layout: [B, H, S, D].
53
+ """
54
+ if not _TORCH_VERSION_AT_LEAST_2_11:
55
+ raise RuntimeError("Low-precision attention requires PyTorch 2.11+.")
56
+ if attn_mask is not None:
57
+ raise ValueError(f"attn_mask not supported for FP8 {backend_name}")
58
+ if dropout_p != 0.0:
59
+ raise ValueError(
60
+ f"dropout_p must be 0.0 for FP8 {backend_name}, got {dropout_p}"
61
+ )
62
+
63
+ input_dtype = query.dtype
64
+
65
+ q_fp8, k_fp8, v_fp8, descale_q, descale_k, descale_v = _fp8_sdpa_quantize(
66
+ query, key, value
67
+ )
68
+
69
+ with sdpa_kernel(SDPBackend.FLASH_ATTENTION):
70
+ out = _scaled_dot_product_attention_quantized(
71
+ q_fp8,
72
+ k_fp8,
73
+ v_fp8,
74
+ is_causal=is_causal,
75
+ scale=scale,
76
+ q_descale=descale_q,
77
+ k_descale=descale_k,
78
+ v_descale=descale_v,
79
+ )
80
+
81
+ return out.to(input_dtype)
82
+
83
+
84
+ def _fp8_rope_sdpa(
85
+ query: torch.Tensor,
86
+ key: torch.Tensor,
87
+ value: torch.Tensor,
88
+ cos: torch.Tensor,
89
+ sin: torch.Tensor,
90
+ attn_mask: Optional[torch.Tensor] = None,
91
+ dropout_p: float = 0.0,
92
+ is_causal: bool = False,
93
+ scale: Optional[float] = None,
94
+ enable_gqa: bool = False,
95
+ rope_interleaved: bool = False,
96
+ *,
97
+ backend_name: str = "FP8",
98
+ ) -> torch.Tensor:
99
+ """Fused RoPE + FP8 SDPA shared by all backends.
100
+
101
+ Input layout: [B, S, H, D] (pre-transpose). The fused quantization
102
+ kernel handles the transpose to [B, H, S, D] internally.
103
+ Output layout: [B, H, S, D].
104
+ """
105
+ if not _TORCH_VERSION_AT_LEAST_2_11:
106
+ raise RuntimeError("Low-precision attention requires PyTorch 2.11+.")
107
+ if attn_mask is not None:
108
+ raise ValueError(f"attn_mask not supported for FP8 {backend_name}")
109
+ if dropout_p != 0.0:
110
+ raise ValueError(
111
+ f"dropout_p must be 0.0 for FP8 {backend_name}, got {dropout_p}"
112
+ )
113
+
114
+ input_dtype = query.dtype
115
+
116
+ cos = cos.to(query.device)
117
+ sin = sin.to(query.device)
118
+
119
+ q_fp8, k_fp8, v_fp8, descale_q, descale_k, descale_v = _fp8_rope_sdpa_quantize(
120
+ query, key, value, cos, sin, rope_interleaved=rope_interleaved
121
+ )
122
+
123
+ with sdpa_kernel(SDPBackend.FLASH_ATTENTION):
124
+ out = _scaled_dot_product_attention_quantized(
125
+ q_fp8,
126
+ k_fp8,
127
+ v_fp8,
128
+ is_causal=is_causal,
129
+ scale=scale,
130
+ q_descale=descale_q,
131
+ k_descale=descale_k,
132
+ v_descale=descale_v,
133
+ )
134
+
135
+ return out.to(input_dtype)
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/shared_utils/custom_ops.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD 3-Clause license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ """
8
+ Shared custom op registration and compile helpers for FP8 attention backends.
9
+
10
+ Custom ops are needed because our FP8 SDPA functions call Triton kernels
11
+ that are not traceable by torch.compile. Registering them as custom_ops
12
+ tells the compiler to treat them as opaque nodes with known shapes/dtypes.
13
+ """
14
+
15
+ from typing import Callable, NamedTuple
16
+
17
+ import torch
18
+
19
+
20
+ class RegisteredOps(NamedTuple):
21
+ rope_sdpa_op: object
22
+ fp8_sdpa_op: object
23
+
24
+
25
+ def register_fp8_attention_ops(
26
+ backend_name: str,
27
+ rope_sdpa_fn: Callable,
28
+ sdpa_fn: Callable,
29
+ ) -> RegisteredOps:
30
+ """Register the RoPE+SDPA and plain SDPA custom ops for a backend."""
31
+ backend = backend_name.lower()
32
+
33
+ rope_op_name = f"torchao::fp8_{backend}_rope_sdpa"
34
+
35
+ @torch.library.custom_op(rope_op_name, mutates_args=())
36
+ def _rope_sdpa_custom_op(
37
+ q: torch.Tensor,
38
+ k: torch.Tensor,
39
+ v: torch.Tensor,
40
+ cos: torch.Tensor,
41
+ sin: torch.Tensor,
42
+ is_causal: bool = False,
43
+ scale: float = 0.0,
44
+ enable_gqa: bool = False,
45
+ rope_interleaved: bool = False,
46
+ ) -> torch.Tensor:
47
+ actual_scale = scale if scale != 0.0 else None
48
+ return rope_sdpa_fn(
49
+ q,
50
+ k,
51
+ v,
52
+ cos,
53
+ sin,
54
+ is_causal=is_causal,
55
+ scale=actual_scale,
56
+ enable_gqa=enable_gqa,
57
+ rope_interleaved=rope_interleaved,
58
+ )
59
+
60
+ @_rope_sdpa_custom_op.register_fake
61
+ def _rope_sdpa_fake(
62
+ q: torch.Tensor,
63
+ k: torch.Tensor,
64
+ v: torch.Tensor,
65
+ cos: torch.Tensor,
66
+ sin: torch.Tensor,
67
+ is_causal: bool = False,
68
+ scale: float = 0.0,
69
+ enable_gqa: bool = False,
70
+ rope_interleaved: bool = False,
71
+ ) -> torch.Tensor:
72
+ B, S, H, D = q.shape
73
+ return torch.empty(B, H, S, D, dtype=q.dtype, device=q.device)
74
+
75
+ sdpa_op_name = f"torchao::fp8_{backend}_sdpa"
76
+
77
+ @torch.library.custom_op(sdpa_op_name, mutates_args=())
78
+ def _sdpa_custom_op(
79
+ q: torch.Tensor,
80
+ k: torch.Tensor,
81
+ v: torch.Tensor,
82
+ is_causal: bool = False,
83
+ scale: float = 0.0,
84
+ enable_gqa: bool = False,
85
+ ) -> torch.Tensor:
86
+ actual_scale = scale if scale != 0.0 else None
87
+ return sdpa_fn(
88
+ q,
89
+ k,
90
+ v,
91
+ is_causal=is_causal,
92
+ scale=actual_scale,
93
+ enable_gqa=enable_gqa,
94
+ )
95
+
96
+ @_sdpa_custom_op.register_fake
97
+ def _sdpa_fake(
98
+ q: torch.Tensor,
99
+ k: torch.Tensor,
100
+ v: torch.Tensor,
101
+ is_causal: bool = False,
102
+ scale: float = 0.0,
103
+ enable_gqa: bool = False,
104
+ ) -> torch.Tensor:
105
+ return torch.empty(q.shape, dtype=q.dtype, device=q.device)
106
+
107
+ rope_sdpa_op = getattr(
108
+ getattr(torch.ops, "torchao"), f"fp8_{backend}_rope_sdpa"
109
+ ).default
110
+ fp8_sdpa_op = getattr(getattr(torch.ops, "torchao"), f"fp8_{backend}_sdpa").default
111
+
112
+ return RegisteredOps(rope_sdpa_op=rope_sdpa_op, fp8_sdpa_op=fp8_sdpa_op)
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/shared_utils/fusion_utils.py ADDED
@@ -0,0 +1,908 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD 3-Clause license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ """
8
+ Shared FX graph pattern detection and fusion utilities for low-precision attention.
9
+ """
10
+
11
+ import logging
12
+ import operator
13
+ from dataclasses import dataclass
14
+ from typing import Optional, Tuple
15
+
16
+ import torch
17
+ import torch.nn as nn
18
+ import torch.nn.functional as F
19
+ from torch.fx import Graph, Node
20
+
21
+ logger = logging.getLogger(__name__)
22
+
23
+
24
+ @dataclass
25
+ class RoPEMatch:
26
+ """Result of detecting a RoPE pattern on a tensor."""
27
+
28
+ pre_rope_input: Node # tensor before RoPE: "x" in "x * cos + rotate_half(x) * sin"
29
+ cos_node: Node # cosine frequencies, traced back to [S, D] source
30
+ sin_node: Node # sine frequencies, traced back to [S, D] source
31
+ rope_interleaved: bool # True = FLUX interleaved, False = NeoX half-split
32
+
33
+
34
+ # FX Node Utilities
35
+
36
+
37
+ def _is_op(node: Node, *targets) -> bool:
38
+ """Check if an FX node matches one of the given targets."""
39
+ if node.op in ("call_function", "call_method"):
40
+ return node.target in targets
41
+ return False
42
+
43
+
44
+ def _get_fake_tensor(node: Node) -> Optional[torch.Tensor]:
45
+ """Get the FakeTensor metadata from a node (pre-grad or post-grad)."""
46
+ for key in ("val", "example_value"):
47
+ if key in node.meta:
48
+ val = node.meta[key]
49
+ if isinstance(val, torch.Tensor):
50
+ return val
51
+ return None
52
+
53
+
54
+ def _get_node_shape(node: Node) -> Optional[Tuple[int, ...]]:
55
+ fake = _get_fake_tensor(node)
56
+ if fake is not None:
57
+ return tuple(fake.shape)
58
+ return None
59
+
60
+
61
+ def _reshape_cos_sin_to_2d(
62
+ graph: Graph,
63
+ cos_node: Node,
64
+ sin_node: Node,
65
+ insert_before: Node,
66
+ ) -> Optional[Tuple[Node, Node]]:
67
+ """Reshape cos/sin nodes to 2D [S, D] if they have leading size-1 dims.
68
+
69
+ HuggingFace models produce cos/sin with shape [B, S, D] or [1, 1, S, D].
70
+ """
71
+ cos_shape = _get_node_shape(cos_node)
72
+ sin_shape = _get_node_shape(sin_node)
73
+
74
+ if cos_shape is None or sin_shape is None:
75
+ return cos_node, sin_node
76
+
77
+ if len(cos_shape) == 2 and len(sin_shape) == 2:
78
+ return cos_node, sin_node
79
+
80
+ for name, shape in [("cos", cos_shape), ("sin", sin_shape)]:
81
+ if len(shape) < 2:
82
+ logger.debug("RoPE %s has fewer than 2 dims: shape=%s", name, shape)
83
+ return None
84
+ for dim in shape[:-2]:
85
+ if dim != 1:
86
+ logger.debug(
87
+ "RoPE %s has non-unit leading dim: shape=%s",
88
+ name,
89
+ shape,
90
+ )
91
+ return None
92
+
93
+ s, d = cos_shape[-2], cos_shape[-1]
94
+ with graph.inserting_before(insert_before):
95
+ cos_2d = graph.call_function(
96
+ torch.ops.aten.view.default,
97
+ args=(cos_node, [s, d]),
98
+ )
99
+ sin_2d = graph.call_function(
100
+ torch.ops.aten.view.default,
101
+ args=(sin_node, [s, d]),
102
+ )
103
+ return cos_2d, sin_2d
104
+
105
+
106
+ def _trace_through_views(node: Node) -> Node:
107
+ """Trace backward through view-like ops (unsqueeze, expand, clone, to.dtype, etc.)."""
108
+ current = node
109
+ while isinstance(current, Node):
110
+ if current.op == "call_function" and current.target in (
111
+ torch.ops.aten.unsqueeze.default,
112
+ torch.ops.aten.clone.default,
113
+ torch.ops.aten.contiguous.default,
114
+ torch.ops.aten.expand.default,
115
+ torch.ops.aten.to.dtype,
116
+ torch.ops.aten._to_copy.default,
117
+ ):
118
+ current = current.args[0]
119
+ elif current.op == "call_method" and current.target in (
120
+ "unsqueeze",
121
+ "clone",
122
+ "contiguous",
123
+ "expand",
124
+ "to",
125
+ "float",
126
+ "half",
127
+ "bfloat16",
128
+ ):
129
+ current = current.args[0]
130
+ elif (
131
+ current.op == "call_function"
132
+ and current.target is operator.getitem
133
+ and len(current.args) >= 2
134
+ and isinstance(current.args[1], tuple)
135
+ and all(i is None or i == slice(None) for i in current.args[1])
136
+ ):
137
+ current = current.args[0]
138
+ else:
139
+ break
140
+ return current
141
+
142
+
143
+ # Transpose Detection
144
+
145
+
146
+ def _unwrap_transpose(node: Node) -> Optional[Node]:
147
+ """If node is transpose(1,2) or permute([0,2,1,3]), return its input.
148
+
149
+ Also looks through contiguous()/clone() wrappers.
150
+ """
151
+ if not isinstance(node, Node):
152
+ return None
153
+
154
+ current = node
155
+ while isinstance(current, Node) and _is_op(
156
+ current,
157
+ torch.ops.aten.contiguous.default,
158
+ torch.ops.aten.clone.default,
159
+ "contiguous",
160
+ "clone",
161
+ ):
162
+ current = current.args[0]
163
+
164
+ if not isinstance(current, Node):
165
+ return None
166
+
167
+ # aten.transpose.int(tensor, 1, 2)
168
+ if _is_op(current, torch.ops.aten.transpose.int):
169
+ if len(current.args) >= 3:
170
+ dim0, dim1 = current.args[1], current.args[2]
171
+ if (dim0 == 1 and dim1 == 2) or (dim0 == 2 and dim1 == 1):
172
+ return current.args[0]
173
+
174
+ # aten.permute.default(tensor, [0, 2, 1, 3])
175
+ if _is_op(current, torch.ops.aten.permute.default):
176
+ if len(current.args) >= 2:
177
+ perm = current.args[1]
178
+ if list(perm) == [0, 2, 1, 3]:
179
+ return current.args[0]
180
+
181
+ # call_method transpose(1, 2)
182
+ if _is_op(current, "transpose"):
183
+ if len(current.args) >= 3:
184
+ dim0, dim1 = current.args[1], current.args[2]
185
+ if (dim0 == 1 and dim1 == 2) or (dim0 == 2 and dim1 == 1):
186
+ return current.args[0]
187
+
188
+ # call_method permute(0, 2, 1, 3)
189
+ if _is_op(current, "permute"):
190
+ if len(current.args) >= 5:
191
+ perm = list(current.args[1:5])
192
+ if perm == [0, 2, 1, 3]:
193
+ return current.args[0]
194
+ elif len(current.args) >= 2 and isinstance(current.args[1], (list, tuple)):
195
+ perm = current.args[1]
196
+ if list(perm) == [0, 2, 1, 3]:
197
+ return current.args[0]
198
+
199
+ return None
200
+
201
+
202
+ def _unwrap_repeat_kv(node: Node) -> Optional[Node]:
203
+ """Unwrap HuggingFace's repeat_kv (GQA head repetition) pattern.
204
+
205
+ Pattern: reshape <- expand <- getitem(unsqueeze).
206
+ Returns the pre-repetition tensor, or None.
207
+ """
208
+ if not isinstance(node, Node):
209
+ return None
210
+
211
+ if not _is_op(
212
+ node,
213
+ torch.ops.aten.reshape.default,
214
+ torch.ops.aten.view.default,
215
+ "reshape",
216
+ "view",
217
+ ):
218
+ return None
219
+
220
+ inner = node.args[0] if node.args else None
221
+ if not isinstance(inner, Node):
222
+ return None
223
+
224
+ if not _is_op(inner, torch.ops.aten.expand.default, "expand"):
225
+ return None
226
+
227
+ inner2 = inner.args[0] if inner.args else None
228
+ if not isinstance(inner2, Node):
229
+ return None
230
+
231
+ if _is_op(inner2, torch.ops.aten.unsqueeze.default, "unsqueeze"):
232
+ return inner2.args[0] if inner2.args else None
233
+
234
+ if inner2.op == "call_function" and inner2.target is operator.getitem:
235
+ if len(inner2.args) >= 2 and isinstance(inner2.args[1], tuple):
236
+ if any(i is None for i in inner2.args[1]):
237
+ return inner2.args[0] if inner2.args else None
238
+
239
+ return None
240
+
241
+
242
+ # SDPA Detection and Parameter Extraction
243
+
244
+
245
+ def _is_fp8_sdpa_node(node: Node, fp8_sdpa_op) -> bool:
246
+ """Check if an FX node is our FP8 SDPA custom op."""
247
+ return node.op == "call_function" and node.target is fp8_sdpa_op
248
+
249
+
250
+ def _is_sdpa_node(node: Node) -> bool:
251
+ """Check if an FX node is ``aten.scaled_dot_product_attention``."""
252
+ return _is_op(
253
+ node,
254
+ torch.ops.aten.scaled_dot_product_attention.default,
255
+ torch._C._nn.scaled_dot_product_attention,
256
+ )
257
+
258
+
259
+ def _sdpa_is_fusible(node: Node, strip_causal_mask: bool = False) -> Tuple[bool, bool]:
260
+ """Check if an aten SDPA node is compatible with our FP8 fused kernel.
261
+
262
+ Returns (is_fusible, needs_mask_strip).
263
+ """
264
+ args = node.args
265
+ kwargs = node.kwargs
266
+
267
+ attn_mask = args[3] if len(args) > 3 else kwargs.get("attn_mask", None)
268
+ is_causal = args[5] if len(args) > 5 else kwargs.get("is_causal", False)
269
+
270
+ needs_mask_strip = False
271
+ if attn_mask is not None:
272
+ if not is_causal and strip_causal_mask and isinstance(attn_mask, Node):
273
+ needs_mask_strip = True
274
+ else:
275
+ return False, False
276
+
277
+ dropout_p = args[4] if len(args) > 4 else kwargs.get("dropout_p", 0.0)
278
+ if dropout_p != 0.0:
279
+ return False, False
280
+
281
+ return True, needs_mask_strip
282
+
283
+
284
+ def _strip_causal_mask(node: Node) -> None:
285
+ """Strip a materialized causal mask from an aten SDPA node."""
286
+ args = list(node.args)
287
+ kwargs = dict(node.kwargs)
288
+
289
+ if len(args) > 3:
290
+ args[3] = None
291
+ elif "attn_mask" in kwargs:
292
+ kwargs["attn_mask"] = None
293
+
294
+ if len(args) > 5:
295
+ args[5] = True
296
+ elif "is_causal" in kwargs:
297
+ kwargs["is_causal"] = True
298
+ else:
299
+ kwargs["is_causal"] = True
300
+
301
+ node.args = tuple(args)
302
+ node.kwargs = kwargs
303
+
304
+ logger.info("Stripped causal mask from SDPA node: %s", node.name)
305
+
306
+
307
+ def _is_lower_triangular_bool_mask(mask: torch.Tensor) -> bool:
308
+ """Check if a tensor is a bool, square lower-triangular (causal) mask."""
309
+ if mask.dtype != torch.bool or mask.ndim < 2:
310
+ return False
311
+ q_len, kv_len = mask.shape[-2], mask.shape[-1]
312
+ if q_len != kv_len:
313
+ return False
314
+ ref = torch.tril(torch.ones(q_len, kv_len, dtype=torch.bool, device=mask.device))
315
+ return torch.equal(mask.broadcast_to(mask.shape), ref.expand_as(mask))
316
+
317
+
318
+ def detect_causal_mask(
319
+ model: nn.Module,
320
+ sample_input_ids=None,
321
+ flash_impl_name: str | None = None,
322
+ ) -> bool:
323
+ """Run one forward pass to detect whether the model uses causal masks.
324
+
325
+ Returns True when every SDPA call used causal attention (either via
326
+ a materialized lower-triangular bool mask, or via is_causal=True).
327
+ """
328
+ from torch.nn.attention import (
329
+ activate_flash_attention_impl,
330
+ restore_flash_attention_impl,
331
+ )
332
+
333
+ try:
334
+ device = next(model.parameters()).device
335
+ except StopIteration:
336
+ return False
337
+
338
+ if sample_input_ids is None:
339
+ vocab_size = getattr(getattr(model, "config", None), "vocab_size", None)
340
+ if vocab_size is None:
341
+ return False
342
+ sample_input_ids = torch.randint(0, vocab_size, (1, 16), device=device)
343
+
344
+ all_causal: list[bool] = []
345
+ saw_any_sdpa = False
346
+
347
+ original_sdpa = F.scaled_dot_product_attention
348
+
349
+ def _hook(*args, **kwargs):
350
+ nonlocal saw_any_sdpa
351
+ saw_any_sdpa = True
352
+ attn_mask = args[3] if len(args) > 3 else kwargs.get("attn_mask", None)
353
+ is_causal = kwargs.get("is_causal", False) if len(args) <= 5 else args[5]
354
+
355
+ if attn_mask is not None and not is_causal:
356
+ all_causal.append(_is_lower_triangular_bool_mask(attn_mask))
357
+ elif attn_mask is None and is_causal:
358
+ all_causal.append(True)
359
+
360
+ return original_sdpa(*args, **kwargs)
361
+
362
+ F.scaled_dot_product_attention = _hook
363
+ if flash_impl_name is not None:
364
+ activate_flash_attention_impl(flash_impl_name)
365
+ try:
366
+ with torch.no_grad():
367
+ model(sample_input_ids)
368
+ except Exception:
369
+ logger.debug("detect_causal_mask: forward pass failed", exc_info=True)
370
+ return False
371
+ finally:
372
+ F.scaled_dot_product_attention = original_sdpa
373
+ if flash_impl_name is not None:
374
+ restore_flash_attention_impl()
375
+
376
+ if not saw_any_sdpa:
377
+ return False
378
+
379
+ return all(all_causal)
380
+
381
+
382
+ def _get_fp8_sdpa_params(node: Node) -> Tuple[bool, float, bool]:
383
+ """Extract is_causal, scale, and enable_gqa from an FP8 SDPA custom op node.
384
+
385
+ Custom op signature: (q, k, v, is_causal=False, scale=0.0, enable_gqa=False)
386
+ Scale uses 0.0 as sentinel for "default" (1/sqrt(D)).
387
+ """
388
+ args = node.args
389
+ kwargs = node.kwargs
390
+
391
+ is_causal = args[3] if len(args) > 3 else kwargs.get("is_causal", False)
392
+ scale = args[4] if len(args) > 4 else kwargs.get("scale", 0.0)
393
+ enable_gqa = args[5] if len(args) > 5 else kwargs.get("enable_gqa", False)
394
+
395
+ return is_causal, scale, enable_gqa
396
+
397
+
398
+ def _get_fp8_sdpa_qkv(node: Node) -> Optional[Tuple[Node, Node, Node]]:
399
+ """Extract Q, K, V input nodes from an FP8 SDPA custom op node."""
400
+ args = node.args
401
+ kwargs = node.kwargs
402
+
403
+ q = args[0] if len(args) > 0 else kwargs.get("q", None)
404
+ k = args[1] if len(args) > 1 else kwargs.get("k", None)
405
+ v = args[2] if len(args) > 2 else kwargs.get("v", None)
406
+
407
+ if not all(isinstance(n, Node) for n in (q, k, v)):
408
+ return None
409
+
410
+ return q, k, v
411
+
412
+
413
+ # NeoX/LLaMA RoPE Pattern Detection
414
+ #
415
+ # NeoX/LLaMA RoPE:
416
+ # rotate_half(x) = cat(-x[..., D//2:], x[..., :D//2], dim=-1)
417
+ # apply_rope(x, cos, sin) = x * cos + rotate_half(x) * sin
418
+
419
+
420
+ def _detect_rotate_half(cat_node: Node) -> Optional[Node]:
421
+ """Detect rotate_half(x) = cat(-x[..., D//2:], x[..., :D//2], dim=-1).
422
+
423
+ Returns the source tensor x, or None.
424
+ """
425
+ if not _is_op(cat_node, torch.ops.aten.cat.default, torch.cat):
426
+ return None
427
+
428
+ if len(cat_node.args) < 1:
429
+ return None
430
+
431
+ tensors_list = cat_node.args[0]
432
+
433
+ if len(cat_node.args) >= 2:
434
+ cat_dim = cat_node.args[1]
435
+ else:
436
+ cat_dim = cat_node.kwargs.get("dim", 0)
437
+
438
+ if cat_dim not in (-1, 3):
439
+ return None
440
+
441
+ if not isinstance(tensors_list, (list, tuple)) or len(tensors_list) != 2:
442
+ return None
443
+
444
+ neg_part = tensors_list[0]
445
+ pos_part = tensors_list[1]
446
+
447
+ if not isinstance(neg_part, Node) or not isinstance(pos_part, Node):
448
+ return None
449
+
450
+ if not _is_op(neg_part, torch.ops.aten.neg.default, operator.neg, torch.neg):
451
+ return None
452
+
453
+ neg_input = neg_part.args[0]
454
+ if not isinstance(neg_input, Node):
455
+ return None
456
+
457
+ return _match_rotate_half_slices(neg_input, pos_part)
458
+
459
+
460
+ def _match_rotate_half_slices(neg_input: Node, pos_part: Node) -> Optional[Node]:
461
+ """Match the slice patterns in rotate_half. Returns the source tensor x, or None."""
462
+ # ATen slice pattern
463
+ if _is_op(neg_input, torch.ops.aten.slice.Tensor) and _is_op(
464
+ pos_part, torch.ops.aten.slice.Tensor
465
+ ):
466
+ slice_neg_source = neg_input.args[0]
467
+ slice_pos_source = pos_part.args[0]
468
+
469
+ if slice_neg_source is not slice_pos_source:
470
+ return None
471
+
472
+ slice_neg_dim = neg_input.args[1] if len(neg_input.args) > 1 else 0
473
+ slice_pos_dim = pos_part.args[1] if len(pos_part.args) > 1 else 0
474
+
475
+ if slice_neg_dim not in (-1, 3) or slice_pos_dim not in (-1, 3):
476
+ return None
477
+
478
+ pos_start = pos_part.args[2] if len(pos_part.args) > 2 else None
479
+ pos_end = pos_part.args[3] if len(pos_part.args) > 3 else None
480
+ neg_start = neg_input.args[2] if len(neg_input.args) > 2 else None
481
+
482
+ if pos_start != 0:
483
+ return None
484
+ if neg_start is None or pos_end is None:
485
+ return None
486
+ if neg_start != pos_end:
487
+ return None
488
+
489
+ return slice_neg_source
490
+
491
+ # Dynamo getitem pattern
492
+ if _is_op(neg_input, operator.getitem) and _is_op(pos_part, operator.getitem):
493
+ slice_neg_source = neg_input.args[0]
494
+ slice_pos_source = pos_part.args[0]
495
+
496
+ if slice_neg_source is not slice_pos_source:
497
+ return None
498
+
499
+ neg_idx = neg_input.args[1]
500
+ pos_idx = pos_part.args[1]
501
+
502
+ neg_slice = _extract_last_dim_slice(neg_idx)
503
+ pos_slice = _extract_last_dim_slice(pos_idx)
504
+
505
+ if neg_slice is None or pos_slice is None:
506
+ return None
507
+
508
+ if pos_slice.start not in (0, None):
509
+ return None
510
+ if pos_slice.stop is None:
511
+ return None
512
+ if neg_slice.start is None:
513
+ return None
514
+ if neg_slice.start != pos_slice.stop:
515
+ return None
516
+
517
+ return slice_neg_source
518
+
519
+ return None
520
+
521
+
522
+ def _extract_last_dim_slice(idx) -> Optional[slice]:
523
+ """Extract the slice on the last dimension from a getitem index."""
524
+ if isinstance(idx, tuple):
525
+ if len(idx) >= 2 and idx[0] is Ellipsis and isinstance(idx[1], slice):
526
+ return idx[1]
527
+ if len(idx) >= 1 and isinstance(idx[-1], slice):
528
+ for i in range(len(idx) - 1):
529
+ if idx[i] is not Ellipsis and idx[i] != slice(None):
530
+ return None
531
+ return idx[-1]
532
+ elif isinstance(idx, slice):
533
+ return idx
534
+ return None
535
+
536
+
537
+ def _detect_interleaved_rotation(node: Node) -> Optional[Node]:
538
+ """Detect the FLUX-style interleaved rotation pattern.
539
+
540
+ Pattern: x.reshape(..., -1, 2).unbind(-1) -> stack([-x_imag, x_real], dim=-1).flatten(3)
541
+ Returns the source tensor x, or None.
542
+ """
543
+ if not _is_op(node, torch.ops.aten.flatten.using_ints, "flatten"):
544
+ return None
545
+ if len(node.args) < 1:
546
+ return None
547
+
548
+ stack_node = node.args[0]
549
+ if not isinstance(stack_node, Node):
550
+ return None
551
+
552
+ if not _is_op(stack_node, torch.ops.aten.stack.default, torch.stack):
553
+ return None
554
+ if len(stack_node.args) < 1:
555
+ return None
556
+
557
+ tensors_list = stack_node.args[0]
558
+ if len(stack_node.args) >= 2:
559
+ stack_dim = stack_node.args[1]
560
+ else:
561
+ stack_dim = stack_node.kwargs.get("dim", 0)
562
+ if stack_dim != -1:
563
+ return None
564
+
565
+ if not isinstance(tensors_list, (list, tuple)) or len(tensors_list) != 2:
566
+ return None
567
+
568
+ neg_part = tensors_list[0]
569
+ pos_part = tensors_list[1]
570
+ if not isinstance(neg_part, Node) or not isinstance(pos_part, Node):
571
+ return None
572
+
573
+ if not _is_op(neg_part, torch.ops.aten.neg.default, operator.neg, torch.neg):
574
+ return None
575
+
576
+ x_imag = neg_part.args[0]
577
+ if not isinstance(x_imag, Node):
578
+ return None
579
+
580
+ if not _is_op(pos_part, operator.getitem) or not _is_op(x_imag, operator.getitem):
581
+ return None
582
+
583
+ real_source = pos_part.args[0]
584
+ imag_source = x_imag.args[0]
585
+ if real_source is not imag_source:
586
+ return None
587
+ if pos_part.args[1] != 0 or x_imag.args[1] != 1:
588
+ return None
589
+
590
+ unbind_node = real_source
591
+ if not isinstance(unbind_node, Node):
592
+ return None
593
+ if not _is_op(unbind_node, torch.ops.aten.unbind.int, "unbind"):
594
+ return None
595
+
596
+ if len(unbind_node.args) >= 2:
597
+ unbind_dim = unbind_node.args[1]
598
+ else:
599
+ unbind_dim = unbind_node.kwargs.get("dim", 0)
600
+ if unbind_dim != -1:
601
+ return None
602
+
603
+ reshape_node = unbind_node.args[0]
604
+ if not isinstance(reshape_node, Node):
605
+ return None
606
+ if not _is_op(
607
+ reshape_node,
608
+ torch.ops.aten.reshape.default,
609
+ torch.ops.aten.view.default,
610
+ "reshape",
611
+ "view",
612
+ ):
613
+ return None
614
+
615
+ source_x = reshape_node.args[0]
616
+ return source_x if isinstance(source_x, Node) else None
617
+
618
+
619
+ def _detect_rotation(node: Node) -> Optional[Tuple[Node, bool]]:
620
+ """Detect any supported rotation pattern.
621
+
622
+ Returns (source_tensor, is_interleaved) or None.
623
+ """
624
+ result = _detect_rotate_half(node)
625
+ if result is not None:
626
+ return result, False
627
+
628
+ result = _detect_interleaved_rotation(node)
629
+ if result is not None:
630
+ return result, True
631
+
632
+ return None
633
+
634
+
635
+ def _detect_neox_rope(node: Node) -> Optional[RoPEMatch]:
636
+ """Detect the NeoX/LLaMA RoPE pattern: add(mul(x, cos), mul(rotate_half(x), sin))."""
637
+ if not _is_op(node, torch.ops.aten.add.Tensor, operator.add):
638
+ return None
639
+ if len(node.args) < 2:
640
+ return None
641
+
642
+ left = node.args[0]
643
+ right = node.args[1]
644
+ if not isinstance(left, Node) or not isinstance(right, Node):
645
+ return None
646
+
647
+ if not _is_op(left, torch.ops.aten.mul.Tensor, operator.mul):
648
+ return None
649
+ if not _is_op(right, torch.ops.aten.mul.Tensor, operator.mul):
650
+ return None
651
+
652
+ def _try_match(x_mul: Node, rot_mul: Node) -> Optional[RoPEMatch]:
653
+ rot_a, rot_b = rot_mul.args[0], rot_mul.args[1]
654
+
655
+ for rot_candidate, sin_candidate in [(rot_a, rot_b), (rot_b, rot_a)]:
656
+ if not isinstance(rot_candidate, Node):
657
+ continue
658
+
659
+ rot_unwrapped = _trace_through_views(rot_candidate)
660
+ rotation_result = _detect_rotation(rot_unwrapped)
661
+ if rotation_result is None:
662
+ continue
663
+ x_from_rotate, is_interleaved = rotation_result
664
+
665
+ x_a, x_b = x_mul.args[0], x_mul.args[1]
666
+ for x_candidate, cos_candidate in [(x_a, x_b), (x_b, x_a)]:
667
+ if not isinstance(x_candidate, Node):
668
+ continue
669
+
670
+ x_traced = _trace_through_views(x_candidate)
671
+ if x_traced is not x_from_rotate:
672
+ continue
673
+
674
+ cos_source = _trace_through_views(cos_candidate)
675
+ sin_source = _trace_through_views(sin_candidate)
676
+
677
+ return RoPEMatch(
678
+ pre_rope_input=x_from_rotate,
679
+ cos_node=cos_source,
680
+ sin_node=sin_source,
681
+ rope_interleaved=is_interleaved,
682
+ )
683
+
684
+ return None
685
+
686
+ # Try both orderings of the add (commutative).
687
+ result = _try_match(left, right)
688
+ if result is not None:
689
+ return result
690
+ return _try_match(right, left)
691
+
692
+
693
+ def _detect_rope(node: Node) -> Optional[RoPEMatch]:
694
+ """Detect any supported RoPE variant at a given node."""
695
+ return _detect_neox_rope(node)
696
+
697
+
698
+ # Graph Surgery
699
+
700
+
701
+ def _replace_with_fused_op(
702
+ graph: Graph,
703
+ sdpa_node: Node,
704
+ pre_rope_q: Node,
705
+ pre_rope_k: Node,
706
+ v_input: Node,
707
+ cos_node: Node,
708
+ sin_node: Node,
709
+ is_causal: bool,
710
+ scale: float,
711
+ enable_gqa: bool,
712
+ rope_interleaved: bool,
713
+ rope_sdpa_op,
714
+ ) -> None:
715
+ """Replace an SDPA node with a fused RoPE+SDPA custom op."""
716
+ with graph.inserting_before(sdpa_node):
717
+ fused_node = graph.call_function(
718
+ rope_sdpa_op,
719
+ args=(pre_rope_q, pre_rope_k, v_input, cos_node, sin_node),
720
+ kwargs={
721
+ "is_causal": is_causal,
722
+ "scale": scale,
723
+ "enable_gqa": enable_gqa,
724
+ "rope_interleaved": rope_interleaved,
725
+ },
726
+ )
727
+
728
+ fused_node.meta = sdpa_node.meta.copy()
729
+ sdpa_node.replace_all_uses_with(fused_node)
730
+
731
+ logger.info(
732
+ "Fused RoPE + SDPA: replaced %s with %s",
733
+ sdpa_node.name,
734
+ fused_node.name,
735
+ )
736
+
737
+
738
+ # Main Fusion Pass
739
+
740
+
741
+ def rope_sdpa_fusion_pass(
742
+ graph: Graph,
743
+ rope_sdpa_op,
744
+ fp8_sdpa_op,
745
+ backend_name: str = "FP8",
746
+ ) -> None:
747
+ """Detect RoPE patterns preceding FP8 SDPA nodes and fuse them.
748
+
749
+ Scans the FX graph for FP8 SDPA custom op nodes (placed by the
750
+ monkey-patch). For each one where RoPE is detected on Q and K,
751
+ replaces it with the fused RoPE+SDPA custom op. Nodes without
752
+ RoPE are left as-is — they are already low-precision from the
753
+ monkey-patch.
754
+
755
+ Supported patterns:
756
+ - Pattern A (RoPE -> transpose -> FP8 SDPA): FLUX-style
757
+ - Pattern B (transpose -> RoPE -> FP8 SDPA): HuggingFace-style
758
+
759
+ Note: KV caching must be disabled before compilation.
760
+ DynamicCache.update() inserts torch.cat nodes that break pattern matching.
761
+ """
762
+ fp8_sdpa_nodes = [n for n in graph.nodes if _is_fp8_sdpa_node(n, fp8_sdpa_op)]
763
+
764
+ if not fp8_sdpa_nodes:
765
+ print(
766
+ f"[low_precision_attention] RoPE fusion pass ({backend_name}): "
767
+ f"found 0 FP8 SDPA nodes in graph"
768
+ )
769
+ return
770
+
771
+ fused_count = 0
772
+
773
+ for sdpa_node in fp8_sdpa_nodes:
774
+ is_causal, scale, enable_gqa = _get_fp8_sdpa_params(sdpa_node)
775
+
776
+ qkv = _get_fp8_sdpa_qkv(sdpa_node)
777
+ if qkv is None:
778
+ continue
779
+ q_node, k_node, v_node = qkv
780
+
781
+ v_pre_transpose = _unwrap_transpose(v_node)
782
+
783
+ # Pattern A: RoPE -> transpose -> FP8 SDPA (FLUX-style)
784
+ q_pre_transpose = _unwrap_transpose(q_node)
785
+ k_pre_transpose = _unwrap_transpose(k_node)
786
+
787
+ if q_pre_transpose is not None and k_pre_transpose is not None:
788
+ q_pre_cast = _trace_through_views(q_pre_transpose)
789
+ k_pre_cast = _trace_through_views(k_pre_transpose)
790
+
791
+ q_rope = _detect_rope(q_pre_cast)
792
+ k_rope = _detect_rope(k_pre_cast)
793
+
794
+ if q_rope is not None and k_rope is not None:
795
+ pre_rope_q = _trace_through_views(q_rope.pre_rope_input)
796
+ pre_rope_k = _trace_through_views(k_rope.pre_rope_input)
797
+
798
+ if v_pre_transpose is None:
799
+ logger.debug(
800
+ "Pattern A: V has no transpose, skipping: %s",
801
+ sdpa_node.name,
802
+ )
803
+ continue
804
+
805
+ cos_sin = _reshape_cos_sin_to_2d(
806
+ graph,
807
+ q_rope.cos_node,
808
+ q_rope.sin_node,
809
+ sdpa_node,
810
+ )
811
+ if cos_sin is None:
812
+ logger.debug(
813
+ "Pattern A: cos/sin shape incompatible, skipping: %s",
814
+ sdpa_node.name,
815
+ )
816
+ continue
817
+ cos_2d, sin_2d = cos_sin
818
+
819
+ _replace_with_fused_op(
820
+ graph=graph,
821
+ sdpa_node=sdpa_node,
822
+ pre_rope_q=pre_rope_q,
823
+ pre_rope_k=pre_rope_k,
824
+ v_input=v_pre_transpose,
825
+ cos_node=cos_2d,
826
+ sin_node=sin_2d,
827
+ is_causal=is_causal,
828
+ scale=scale,
829
+ enable_gqa=enable_gqa,
830
+ rope_interleaved=q_rope.rope_interleaved,
831
+ rope_sdpa_op=rope_sdpa_op,
832
+ )
833
+ fused_count += 1
834
+ continue
835
+
836
+ # Pattern B: transpose -> RoPE -> FP8 SDPA (HuggingFace-style)
837
+ # For GQA, K may go through repeat_kv after RoPE.
838
+ q_rope = _detect_rope(_trace_through_views(q_node))
839
+
840
+ k_rope = _detect_rope(_trace_through_views(k_node))
841
+ gqa_unwrapped = False
842
+ if k_rope is None:
843
+ k_pre_repeat = _unwrap_repeat_kv(k_node)
844
+ if k_pre_repeat is not None:
845
+ k_rope = _detect_rope(_trace_through_views(k_pre_repeat))
846
+ if k_rope is not None:
847
+ gqa_unwrapped = True
848
+
849
+ if q_rope is not None and k_rope is not None:
850
+ q_bshd = _unwrap_transpose(_trace_through_views(q_rope.pre_rope_input))
851
+ k_bshd = _unwrap_transpose(_trace_through_views(k_rope.pre_rope_input))
852
+
853
+ if q_bshd is not None and k_bshd is not None:
854
+ v_for_fusion = v_node
855
+ if gqa_unwrapped:
856
+ v_pre_repeat = _unwrap_repeat_kv(v_node)
857
+ if v_pre_repeat is not None:
858
+ v_for_fusion = v_pre_repeat
859
+
860
+ v_bshd = _unwrap_transpose(v_for_fusion)
861
+ if v_bshd is None:
862
+ logger.debug(
863
+ "Pattern B: V has no transpose, skipping: %s",
864
+ sdpa_node.name,
865
+ )
866
+ continue
867
+
868
+ cos_sin = _reshape_cos_sin_to_2d(
869
+ graph,
870
+ q_rope.cos_node,
871
+ q_rope.sin_node,
872
+ sdpa_node,
873
+ )
874
+ if cos_sin is None:
875
+ logger.debug(
876
+ "Pattern B: cos/sin shape incompatible, skipping: %s",
877
+ sdpa_node.name,
878
+ )
879
+ continue
880
+ cos_2d, sin_2d = cos_sin
881
+
882
+ fused_enable_gqa = True if gqa_unwrapped else enable_gqa
883
+
884
+ _replace_with_fused_op(
885
+ graph=graph,
886
+ sdpa_node=sdpa_node,
887
+ pre_rope_q=q_bshd,
888
+ pre_rope_k=k_bshd,
889
+ v_input=v_bshd,
890
+ cos_node=cos_2d,
891
+ sin_node=sin_2d,
892
+ is_causal=is_causal,
893
+ scale=scale,
894
+ enable_gqa=fused_enable_gqa,
895
+ rope_interleaved=q_rope.rope_interleaved,
896
+ rope_sdpa_op=rope_sdpa_op,
897
+ )
898
+ fused_count += 1
899
+ continue
900
+
901
+ print(
902
+ f"[low_precision_attention] RoPE fusion pass ({backend_name}): "
903
+ f"found {len(fp8_sdpa_nodes)} FP8 SDPA node(s), "
904
+ f"{fused_count} fused with RoPE"
905
+ )
906
+
907
+ if fused_count > 0:
908
+ graph.eliminate_dead_code()
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/shared_utils/setup.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD 3-Clause license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ from functools import partial
8
+
9
+ import torch._inductor.config as inductor_config
10
+ import torch.nn as nn
11
+
12
+ from torchao.prototype.attention.shared_utils.fusion_utils import (
13
+ detect_causal_mask,
14
+ rope_sdpa_fusion_pass,
15
+ )
16
+ from torchao.prototype.attention.shared_utils.wrapper import (
17
+ _FP8FlashAttentionMonkeyPatchWrapper,
18
+ _make_causal_aware_sdpa,
19
+ )
20
+
21
+
22
+ def setup_fp8_backend(
23
+ model: nn.Module,
24
+ flash_impl_name: str,
25
+ ) -> nn.Module:
26
+ if flash_impl_name == "FA3":
27
+ from torchao.prototype.attention.fp8_fa3.attention import _ops
28
+ else:
29
+ raise ValueError(f"Unknown flash_impl_name: {flash_impl_name}")
30
+
31
+ strip_causal_mask = detect_causal_mask(model, flash_impl_name=flash_impl_name)
32
+
33
+ inductor_config.pre_grad_custom_pass = partial(
34
+ rope_sdpa_fusion_pass,
35
+ rope_sdpa_op=_ops.rope_sdpa_op,
36
+ fp8_sdpa_op=_ops.fp8_sdpa_op,
37
+ backend_name=flash_impl_name,
38
+ )
39
+
40
+ return _FP8FlashAttentionMonkeyPatchWrapper(
41
+ model,
42
+ flash_impl_name=flash_impl_name,
43
+ sdpa_patch_fn=_make_causal_aware_sdpa(_ops.fp8_sdpa_op, strip_causal_mask),
44
+ )
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/attention/shared_utils/wrapper.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD 3-Clause license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ from typing import Callable
8
+
9
+ import torch.nn as nn
10
+ import torch.nn.functional as F
11
+ from torch.nn.attention import (
12
+ activate_flash_attention_impl,
13
+ restore_flash_attention_impl,
14
+ )
15
+
16
+
17
+ class _LowPrecisionAttentionWrapper(nn.Module):
18
+ """Base wrapper. Proxies attribute access to the original module."""
19
+
20
+ def __init__(self, orig_mod: nn.Module):
21
+ super().__init__()
22
+ self._orig_mod = orig_mod
23
+
24
+ def __getattr__(self, name: str):
25
+ try:
26
+ return super().__getattr__(name)
27
+ except AttributeError:
28
+ return getattr(self._orig_mod, name)
29
+
30
+
31
+ class _FP8FlashAttentionMonkeyPatchWrapper(_LowPrecisionAttentionWrapper):
32
+ """Monkey-patch path wrapper. Replaces ``F.scaled_dot_product_attention``
33
+ with the FP8 backend for the duration of each forward call.
34
+ """
35
+
36
+ def __init__(
37
+ self, orig_mod: nn.Module, flash_impl_name: str, sdpa_patch_fn: Callable
38
+ ):
39
+ super().__init__(orig_mod)
40
+ self._flash_impl_name = flash_impl_name
41
+ self._sdpa_patch_fn = sdpa_patch_fn
42
+
43
+ def forward(self, *args, **kwargs):
44
+ activate_flash_attention_impl(self._flash_impl_name)
45
+ try:
46
+ original_sdpa = F.scaled_dot_product_attention
47
+ F.scaled_dot_product_attention = self._sdpa_patch_fn
48
+ try:
49
+ return self._orig_mod(*args, **kwargs)
50
+ finally:
51
+ F.scaled_dot_product_attention = original_sdpa
52
+ finally:
53
+ restore_flash_attention_impl()
54
+
55
+
56
+ def _make_causal_aware_sdpa(fp8_sdpa_custom_op, strip_causal_mask: bool) -> Callable:
57
+ """Bridge F.sdpa signature to the FP8 SDPA custom op.
58
+
59
+ Calls the custom op so torch.compile sees an opaque node in the FX graph.
60
+ """
61
+
62
+ def _patched(
63
+ query,
64
+ key,
65
+ value,
66
+ attn_mask=None,
67
+ dropout_p=0.0,
68
+ is_causal=False,
69
+ scale=None,
70
+ enable_gqa=False,
71
+ ):
72
+ if strip_causal_mask and attn_mask is not None:
73
+ attn_mask = None
74
+ is_causal = True
75
+ if attn_mask is not None:
76
+ raise ValueError("attn_mask not supported for FP8 attention")
77
+ if dropout_p != 0.0:
78
+ raise ValueError(
79
+ f"dropout_p must be 0.0 for FP8 attention, got {dropout_p}"
80
+ )
81
+ return fp8_sdpa_custom_op(
82
+ query,
83
+ key,
84
+ value,
85
+ is_causal=is_causal,
86
+ scale=scale if scale is not None else 0.0,
87
+ enable_gqa=enable_gqa,
88
+ )
89
+
90
+ return _patched
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/blockwise_fp8_training/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (214 Bytes). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/blockwise_fp8_training/__pycache__/kernels.cpython-310.pyc ADDED
Binary file (18.7 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/blockwise_fp8_training/__pycache__/linear.cpython-310.pyc ADDED
Binary file (4.79 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/float8nocompile/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (207 Bytes). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/float8nocompile/__pycache__/float8nocompile_linear.cpython-310.pyc ADDED
Binary file (6.43 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/float8nocompile/__pycache__/float8nocompile_linear_test.cpython-310.pyc ADDED
Binary file (1.95 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/float8nocompile/__pycache__/float8nocompile_linear_utils.cpython-310.pyc ADDED
Binary file (1.91 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/float8nocompile/__pycache__/float8nocompile_scaling_utils.cpython-310.pyc ADDED
Binary file (4.84 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/float8nocompile/kernels/__init__.py ADDED
File without changes
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/float8nocompile/kernels/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (215 Bytes). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/float8nocompile/kernels/__pycache__/fp8_dynamic_tensorwise.cpython-310.pyc ADDED
Binary file (16.8 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/float8nocompile/kernels/__pycache__/fp8_dynamic_tensorwise_test.cpython-310.pyc ADDED
Binary file (7.23 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/float8nocompile/kernels/fp8_dynamic_tensorwise.py ADDED
@@ -0,0 +1,1090 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD 3-Clause license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ """
8
+ Triton kernels for scaling high precision tensors to float8.
9
+ """
10
+
11
+ from enum import Enum
12
+
13
+ import torch
14
+ import triton
15
+ import triton.language as tl
16
+
17
+ from torchao.float8.float8_training_tensor import (
18
+ Float8TrainingTensor,
19
+ GemmInputRole,
20
+ LinearMMConfig,
21
+ )
22
+
23
+ EPS = 1e-12
24
+
25
+ FP8_DTYPE_MAP = {
26
+ torch.int8: tl.int8,
27
+ torch.int16: tl.int16,
28
+ torch.int32: tl.int32,
29
+ torch.int64: tl.int64,
30
+ torch.float8_e4m3fn: tl.float8e4nv,
31
+ torch.float8_e5m2: tl.float8e5,
32
+ torch.float16: tl.float16,
33
+ torch.bfloat16: tl.bfloat16,
34
+ torch.float32: tl.float32,
35
+ torch.float64: tl.float64,
36
+ }
37
+
38
+
39
+ kernel_configs_1D = [
40
+ triton.Config({"BLOCK_SIZE": 128}, num_warps=1),
41
+ triton.Config({"BLOCK_SIZE": 256}, num_warps=2),
42
+ triton.Config({"BLOCK_SIZE": 512}, num_warps=4),
43
+ triton.Config({"BLOCK_SIZE": 1024}, num_warps=4),
44
+ triton.Config({"BLOCK_SIZE": 2048}, num_warps=8),
45
+ triton.Config({"BLOCK_SIZE": 4096}, num_warps=8),
46
+ ]
47
+
48
+ kernel_configs_2D = [
49
+ triton.Config({"BLOCK_SIZE_ROWS": 32, "BLOCK_SIZE_COLS": 32}, num_warps=1),
50
+ triton.Config({"BLOCK_SIZE_ROWS": 64, "BLOCK_SIZE_COLS": 64}, num_warps=8),
51
+ triton.Config({"BLOCK_SIZE_ROWS": 128, "BLOCK_SIZE_COLS": 128}, num_warps=4),
52
+ ]
53
+
54
+
55
+ class KernelAlgorithm(Enum):
56
+ """Enum for FP8 conversion strategy."""
57
+
58
+ # use atomic max to compute global amax between blocks
59
+ ATOMIC_MAX = "atomic_max"
60
+
61
+ # reduce shared buffer containing local block amaxes to find global amax
62
+ REDUCTION = "reduction"
63
+
64
+
65
+ @triton.autotune(configs=kernel_configs_1D, key=["num_elements"])
66
+ @triton.jit
67
+ def _to_fp8_row_major(
68
+ input_ptr,
69
+ out_ptr,
70
+ scale_ptr,
71
+ num_elements: int,
72
+ fp8_dtype_min: float,
73
+ fp8_dtype_max: float,
74
+ input_dtype: tl.constexpr,
75
+ output_dtype: tl.constexpr,
76
+ BLOCK_SIZE: tl.constexpr,
77
+ EPS: tl.constexpr,
78
+ ):
79
+ block_id = tl.program_id(axis=0)
80
+
81
+ # load scaling factor
82
+ scale = tl.load(scale_ptr).to(tl.float32)
83
+
84
+ # load block of input tensor
85
+ block_start = block_id * BLOCK_SIZE
86
+ block_offs = block_start + tl.arange(0, BLOCK_SIZE)
87
+ mask = block_offs < num_elements
88
+ vals = tl.load(input_ptr + block_offs, mask=mask).to(input_dtype)
89
+
90
+ # perform conversion
91
+ vals = vals * scale
92
+ fp8_vals = tl.clamp(vals, min=fp8_dtype_min, max=fp8_dtype_max).to(output_dtype)
93
+ tl.store(out_ptr + block_offs, fp8_vals, mask=mask)
94
+
95
+
96
+ @triton.autotune(
97
+ configs=kernel_configs_2D,
98
+ key=["num_elements"],
99
+ )
100
+ @triton.jit
101
+ def _to_fp8_row_major_t(
102
+ input_ptr,
103
+ out_ptr,
104
+ scale_ptr,
105
+ num_elements: int,
106
+ fp8_dtype_min: float,
107
+ fp8_dtype_max: float,
108
+ input_num_rows: int,
109
+ input_num_cols: int,
110
+ output_num_rows: int,
111
+ output_num_cols: int,
112
+ input_stride_row: int,
113
+ input_stride_col: int,
114
+ output_stride_row: int,
115
+ output_stride_col: int,
116
+ input_dtype: tl.constexpr,
117
+ output_dtype: tl.constexpr,
118
+ BLOCK_SIZE_ROWS: tl.constexpr,
119
+ BLOCK_SIZE_COLS: tl.constexpr,
120
+ EPS: tl.constexpr,
121
+ ):
122
+ block_row_id = tl.program_id(axis=0)
123
+ block_col_id = tl.program_id(axis=1)
124
+
125
+ # load scaling factor
126
+ scale = tl.load(scale_ptr).to(tl.float32)
127
+
128
+ # load block of input tensor
129
+ block_row_start = block_row_id * BLOCK_SIZE_ROWS
130
+ block_col_start = block_col_id * BLOCK_SIZE_COLS
131
+ block_row_offs = block_row_start + tl.arange(0, BLOCK_SIZE_ROWS)
132
+ block_col_offs = block_col_start + tl.arange(0, BLOCK_SIZE_COLS)
133
+ input_offs = (
134
+ block_row_offs[:, None] * input_stride_row
135
+ + block_col_offs[None, :] * input_stride_col
136
+ )
137
+ input_mask = (block_row_offs[:, None] < input_num_rows) & (
138
+ block_col_offs[None, :] < input_num_cols
139
+ )
140
+ vals = tl.load(input_ptr + input_offs, mask=input_mask).to(input_dtype)
141
+
142
+ # perform conversion
143
+ vals = vals * scale
144
+ fp8_vals = tl.clamp(vals, min=fp8_dtype_min, max=fp8_dtype_max).to(output_dtype)
145
+
146
+ # write back in tranposed output tensor
147
+ out_offs = (
148
+ block_col_offs[:, None] * output_stride_row
149
+ + block_row_offs[None, :] * output_stride_col
150
+ )
151
+ out_mask = (block_row_offs[:, None] < output_num_rows) & (
152
+ block_col_offs[None, :] < output_num_cols
153
+ )
154
+ tl.store(out_ptr + out_offs, fp8_vals.trans(1, 0), mask=out_mask)
155
+
156
+
157
+ @triton.autotune(
158
+ configs=kernel_configs_2D,
159
+ key=["num_elements"],
160
+ )
161
+ @triton.jit
162
+ def _to_fp8_col_major(
163
+ input_ptr,
164
+ out_ptr,
165
+ scale_ptr,
166
+ num_elements: int,
167
+ fp8_dtype_min: float,
168
+ fp8_dtype_max: float,
169
+ num_rows: int,
170
+ num_cols: int,
171
+ out_stride_row: int,
172
+ out_stride_col: int,
173
+ input_dtype: tl.constexpr,
174
+ output_dtype: tl.constexpr,
175
+ BLOCK_SIZE_ROWS: tl.constexpr,
176
+ BLOCK_SIZE_COLS: tl.constexpr,
177
+ EPS: tl.constexpr,
178
+ ):
179
+ block_row_id = tl.program_id(axis=0)
180
+ block_col_id = tl.program_id(axis=1)
181
+
182
+ # load scaling factor
183
+ scale = tl.load(scale_ptr).to(tl.float32)
184
+
185
+ # load block of input tensor
186
+ block_row_start = block_row_id * BLOCK_SIZE_ROWS
187
+ block_col_start = block_col_id * BLOCK_SIZE_COLS
188
+ block_row_offs = block_row_start + tl.arange(0, BLOCK_SIZE_ROWS)
189
+ block_col_offs = block_col_start + tl.arange(0, BLOCK_SIZE_COLS)
190
+ block_offs = block_row_offs[:, None] * num_cols + block_col_offs[None, :]
191
+ mask = (block_row_offs[:, None] < num_rows) & (block_col_offs[None, :] < num_cols)
192
+ vals = tl.load(input_ptr + block_offs, mask=mask).to(input_dtype)
193
+
194
+ # perform conversion
195
+ vals = vals * scale
196
+ fp8_vals = tl.clamp(vals, min=fp8_dtype_min, max=fp8_dtype_max).to(output_dtype)
197
+ out_offs = block_col_offs[None, :] * num_rows + block_row_offs[:, None]
198
+ tl.store(out_ptr + out_offs, fp8_vals, mask=mask)
199
+
200
+
201
+ @triton.autotune(
202
+ configs=kernel_configs_2D,
203
+ key=["num_elements"],
204
+ )
205
+ @triton.jit
206
+ def to_fp8_col_major_t(
207
+ input_ptr,
208
+ out_ptr,
209
+ scale_ptr,
210
+ num_elements: int,
211
+ fp8_dtype_min: float,
212
+ fp8_dtype_max: float,
213
+ input_num_rows: int,
214
+ input_num_cols: int,
215
+ output_num_rows: int,
216
+ output_num_cols: int,
217
+ input_stride_row: int,
218
+ input_stride_col: int,
219
+ output_stride_row: int,
220
+ output_stride_col: int,
221
+ input_dtype: tl.constexpr,
222
+ output_dtype: tl.constexpr,
223
+ BLOCK_SIZE_ROWS: tl.constexpr,
224
+ BLOCK_SIZE_COLS: tl.constexpr,
225
+ EPS: tl.constexpr,
226
+ ):
227
+ block_row_id = tl.program_id(axis=0)
228
+ block_col_id = tl.program_id(axis=1)
229
+
230
+ # load scaling factor
231
+ scale = tl.load(scale_ptr).to(tl.float32)
232
+
233
+ # load block of input tensor
234
+ block_row_start = block_row_id * BLOCK_SIZE_ROWS
235
+ block_col_start = block_col_id * BLOCK_SIZE_COLS
236
+ block_row_offs = block_row_start + tl.arange(0, BLOCK_SIZE_ROWS)
237
+ block_col_offs = block_col_start + tl.arange(0, BLOCK_SIZE_COLS)
238
+ input_offs = (
239
+ block_row_offs[:, None] * input_stride_row
240
+ + block_col_offs[None, :] * input_stride_col
241
+ )
242
+ input_mask = (block_row_offs[:, None] < input_num_rows) & (
243
+ block_col_offs[None, :] < input_num_cols
244
+ )
245
+ vals = tl.load(input_ptr + input_offs, mask=input_mask).to(input_dtype)
246
+
247
+ # perform conversion
248
+ vals = vals * scale
249
+ fp8_vals = tl.clamp(vals, min=fp8_dtype_min, max=fp8_dtype_max).to(output_dtype)
250
+ fp8_vals = fp8_vals.trans(1, 0)
251
+
252
+ # write back in tranposed output tensor
253
+ out_offs = (
254
+ block_col_offs[:, None] * output_stride_row
255
+ + block_row_offs[None, :] * output_stride_col
256
+ )
257
+ out_mask = (block_col_offs[:, None] < output_num_rows) & (
258
+ block_row_offs[None, :] < output_num_cols
259
+ )
260
+ tl.store(out_ptr + out_offs, fp8_vals, mask=out_mask)
261
+
262
+
263
+ @triton.autotune(
264
+ configs=kernel_configs_2D,
265
+ key=["num_elements"],
266
+ )
267
+ @triton.jit
268
+ def _to_fp8_row_and_col_major(
269
+ input_ptr,
270
+ row_major_out_ptr,
271
+ col_major_out_ptr,
272
+ scale_ptr,
273
+ num_elements: int,
274
+ fp8_dtype_min: float,
275
+ fp8_dtype_max: float,
276
+ num_rows: int,
277
+ num_cols: int,
278
+ input_dtype: tl.constexpr,
279
+ output_dtype: tl.constexpr,
280
+ BLOCK_SIZE_ROWS: tl.constexpr,
281
+ BLOCK_SIZE_COLS: tl.constexpr,
282
+ EPS: tl.constexpr,
283
+ ):
284
+ block_row_id = tl.program_id(axis=0)
285
+ block_col_id = tl.program_id(axis=1)
286
+
287
+ # load scaling factor
288
+ scale = tl.load(scale_ptr).to(tl.float32)
289
+
290
+ # load block of input tensor
291
+ block_row_start = block_row_id * BLOCK_SIZE_ROWS
292
+ block_col_start = block_col_id * BLOCK_SIZE_COLS
293
+ block_row_offs = block_row_start + tl.arange(0, BLOCK_SIZE_ROWS)
294
+ block_col_offs = block_col_start + tl.arange(0, BLOCK_SIZE_COLS)
295
+ block_offs = block_row_offs[:, None] * num_cols + block_col_offs[None, :]
296
+ mask = (block_row_offs[:, None] < num_rows) & (block_col_offs[None, :] < num_cols)
297
+ vals = tl.load(input_ptr + block_offs, mask=mask).to(input_dtype)
298
+
299
+ # perform conversion
300
+ vals = vals * scale
301
+ fp8_vals = tl.clamp(vals, min=fp8_dtype_min, max=fp8_dtype_max).to(output_dtype)
302
+
303
+ # write row major output
304
+ row_major_offs = block_row_offs[:, None] * num_cols + block_col_offs[None, :]
305
+ tl.store(row_major_out_ptr + row_major_offs, fp8_vals, mask=mask)
306
+
307
+ # write column major output
308
+ col_major_offs = block_col_offs[None, :] * num_rows + block_row_offs[:, None]
309
+ tl.store(col_major_out_ptr + col_major_offs, fp8_vals, mask=mask)
310
+
311
+
312
+ @triton.autotune(
313
+ configs=kernel_configs_2D,
314
+ key=["num_elements"],
315
+ )
316
+ @triton.jit
317
+ def _to_fp8_row_major_t_and_non_t(
318
+ input_ptr,
319
+ row_major_out_ptr,
320
+ row_major_t_out_ptr,
321
+ scale_ptr,
322
+ num_elements: int,
323
+ fp8_dtype_min: float,
324
+ fp8_dtype_max: float,
325
+ input_num_rows: int,
326
+ input_num_cols: int,
327
+ input_stride_row: int,
328
+ input_stride_col: int,
329
+ row_major_out_stride_row: int,
330
+ row_major_out_stride_col: int,
331
+ row_major_t_out_stride_row: int,
332
+ row_major_t_out_stride_col: int,
333
+ input_dtype: tl.constexpr,
334
+ output_dtype: tl.constexpr,
335
+ BLOCK_SIZE_ROWS: tl.constexpr,
336
+ BLOCK_SIZE_COLS: tl.constexpr,
337
+ EPS: tl.constexpr,
338
+ ):
339
+ """
340
+ Reads a row-major, high precision input tensor and writes 2 output tensors:
341
+ 1) fp8 row major tensor (transposed)
342
+ 2) fp8 row major tensor
343
+ """
344
+ block_row_id = tl.program_id(axis=0)
345
+ block_col_id = tl.program_id(axis=1)
346
+
347
+ # load scaling factor
348
+ scale = tl.load(scale_ptr).to(tl.float32)
349
+
350
+ # load block of input tensor
351
+ block_row_start = block_row_id * BLOCK_SIZE_ROWS
352
+ block_col_start = block_col_id * BLOCK_SIZE_COLS
353
+ block_row_offs = block_row_start + tl.arange(0, BLOCK_SIZE_ROWS)
354
+ block_col_offs = block_col_start + tl.arange(0, BLOCK_SIZE_COLS)
355
+ input_offs = (
356
+ block_row_offs[:, None] * input_stride_row
357
+ + block_col_offs[None, :] * input_stride_col
358
+ )
359
+ mask = (block_row_offs[:, None] < input_num_rows) & (
360
+ block_col_offs[None, :] < input_num_cols
361
+ )
362
+ vals = tl.load(input_ptr + input_offs, mask=mask).to(input_dtype)
363
+
364
+ # perform conversion
365
+ vals = vals * scale
366
+ fp8_vals = tl.clamp(vals, min=fp8_dtype_min, max=fp8_dtype_max).to(output_dtype)
367
+
368
+ # write row-major output
369
+ row_major_offs = (
370
+ block_row_offs[:, None] * row_major_out_stride_row
371
+ + block_col_offs[None, :] * row_major_out_stride_col
372
+ )
373
+ tl.store(row_major_out_ptr + row_major_offs, fp8_vals, mask=mask)
374
+
375
+ # write tranposed row-major output
376
+ row_major_t_num_rows = input_num_cols
377
+ row_major_t_num_cols = input_num_rows
378
+ row_major_t_offs = (
379
+ block_col_offs[:, None] * row_major_t_out_stride_row
380
+ + block_row_offs[None, :] * row_major_t_out_stride_col
381
+ )
382
+ mask = (block_col_offs[:, None] < row_major_t_num_rows) & (
383
+ block_row_offs[None, :] < row_major_t_num_cols
384
+ )
385
+ tl.store(row_major_t_out_ptr + row_major_t_offs, fp8_vals.trans(1, 0), mask=mask)
386
+
387
+
388
+ @triton.autotune(configs=kernel_configs_2D, key=["num_elements"])
389
+ @triton.jit
390
+ def _to_fp8_col_major_t_and_non_t(
391
+ input_ptr,
392
+ col_major_out_ptr,
393
+ col_major_t_out_ptr,
394
+ scale_ptr,
395
+ num_elements: int,
396
+ fp8_dtype_min: float,
397
+ fp8_dtype_max: float,
398
+ input_num_rows: int,
399
+ input_num_cols: int,
400
+ input_stride_row: int,
401
+ input_stride_col: int,
402
+ col_major_out_stride_row: int,
403
+ col_major_out_stride_col: int,
404
+ col_major_t_out_stride_row: int,
405
+ col_major_t_out_stride_col: int,
406
+ input_dtype: tl.constexpr,
407
+ output_dtype: tl.constexpr,
408
+ BLOCK_SIZE_ROWS: tl.constexpr,
409
+ BLOCK_SIZE_COLS: tl.constexpr,
410
+ EPS: tl.constexpr,
411
+ ):
412
+ """
413
+ Reads a row-major, high precision input tensor and writes 2 output tensors:
414
+ 1) fp8 col major tensor (transposed)
415
+ 2) fp8 col major tensor
416
+ """
417
+ # col major tranposed
418
+ block_row_id = tl.program_id(axis=0)
419
+ block_col_id = tl.program_id(axis=1)
420
+
421
+ # load scaling factor
422
+ scale = tl.load(scale_ptr).to(tl.float32)
423
+
424
+ # load block of input tensor
425
+ block_row_start = block_row_id * BLOCK_SIZE_ROWS
426
+ block_col_start = block_col_id * BLOCK_SIZE_COLS
427
+ block_row_offs = block_row_start + tl.arange(0, BLOCK_SIZE_ROWS)
428
+ block_col_offs = block_col_start + tl.arange(0, BLOCK_SIZE_COLS)
429
+ input_offs = (
430
+ block_row_offs[:, None] * input_stride_row
431
+ + block_col_offs[None, :] * input_stride_col
432
+ )
433
+ mask = (block_row_offs[:, None] < input_num_rows) & (
434
+ block_col_offs[None, :] < input_num_cols
435
+ )
436
+ vals = tl.load(input_ptr + input_offs, mask=mask).to(input_dtype)
437
+
438
+ # perform conversion
439
+ vals = vals * scale
440
+ fp8_vals = tl.clamp(vals, min=fp8_dtype_min, max=fp8_dtype_max).to(output_dtype)
441
+
442
+ # 1. write col-major output
443
+ out_offs = block_row_offs[:, None] + block_col_offs[None, :] * input_num_rows
444
+ tl.store(col_major_out_ptr + out_offs, fp8_vals, mask=mask)
445
+
446
+ # 2. write tranposed col-major output
447
+ col_major_t_num_rows = input_num_cols
448
+ col_major_t_num_cols = input_num_rows
449
+ out_offs = (
450
+ block_col_offs[:, None] * col_major_t_out_stride_row
451
+ + block_row_offs[None, :] * col_major_t_out_stride_col
452
+ )
453
+ out_mask = (block_col_offs[:, None] < col_major_t_num_rows) & (
454
+ block_row_offs[None, :] < col_major_t_num_cols
455
+ )
456
+ tl.store(col_major_t_out_ptr + out_offs, fp8_vals.trans(1, 0), mask=out_mask)
457
+
458
+
459
+ @triton.autotune(configs=kernel_configs_1D, key=["num_elements"])
460
+ @triton.jit
461
+ def _amax_atomic(
462
+ input_ptr,
463
+ amax_ptr,
464
+ num_elements,
465
+ input_dtype: tl.constexpr,
466
+ BLOCK_SIZE: tl.constexpr,
467
+ EPS: tl.constexpr,
468
+ ):
469
+ # compute local amax for each block
470
+ block_id = tl.program_id(axis=0)
471
+ block_start = block_id * BLOCK_SIZE
472
+ block_offs = block_start + tl.arange(0, BLOCK_SIZE)
473
+ block_mask = block_offs < num_elements
474
+ vals = tl.load(input_ptr + block_offs, mask=block_mask).to(input_dtype)
475
+ block_amax = tl.max(tl.abs(vals))
476
+ # AMD GPUs need relaxed semantics for better performance
477
+ if tl.constexpr(torch.version.hip is not None):
478
+ tl.atomic_max(amax_ptr, block_amax, sem="relaxed")
479
+ else:
480
+ tl.atomic_max(amax_ptr, block_amax)
481
+
482
+
483
+ @triton.jit
484
+ def _scale_atomic(
485
+ amax_ptr,
486
+ scale_out_ptr,
487
+ fp8_dtype_max,
488
+ EPS: tl.constexpr,
489
+ ):
490
+ # load previously computed global amax
491
+ global_amax = tl.load(amax_ptr).to(tl.float64)
492
+
493
+ # compute scale, must be fp32
494
+ scale = (fp8_dtype_max / tl.clamp(global_amax, min=EPS, max=float("inf"))).to(
495
+ tl.float32
496
+ )
497
+
498
+ # store scale for use in Float8TrainingTensor constructor
499
+ scale_off = tl.arange(0, 1)
500
+ tl.store(scale_out_ptr + scale_off, scale)
501
+
502
+
503
+ @triton.jit
504
+ def _amax_reduction(
505
+ input_ptr,
506
+ block_amaxes_ptr,
507
+ num_elements,
508
+ input_dtype: tl.constexpr,
509
+ BLOCK_SIZE: tl.constexpr,
510
+ EPS: tl.constexpr,
511
+ ):
512
+ # compute local amax for each block
513
+ block_id = tl.program_id(axis=0)
514
+ block_start = block_id * BLOCK_SIZE
515
+ block_offs = block_start + tl.arange(0, BLOCK_SIZE)
516
+ block_mask = block_offs < num_elements
517
+ vals = tl.load(input_ptr + block_offs, mask=block_mask).to(input_dtype)
518
+ block_amax = tl.max(tl.abs(vals))
519
+ tl.store(block_amaxes_ptr + block_id, block_amax)
520
+
521
+
522
+ @triton.jit
523
+ def _scale_reduction(
524
+ block_amaxes_ptr,
525
+ scale_out_ptr,
526
+ num_elements,
527
+ fp8_dtype_max,
528
+ BLOCK_SIZE: tl.constexpr,
529
+ EPS: tl.constexpr,
530
+ ):
531
+ # calculate global amax across all blocks
532
+ global_amax = tl.zeros([1], dtype=tl.float64)
533
+ num_blocks = tl.cdiv(num_elements, BLOCK_SIZE)
534
+ for i in range(num_blocks):
535
+ block_max = tl.load(block_amaxes_ptr + i)
536
+ global_amax = tl.maximum(global_amax, block_max)
537
+
538
+ # compute scale, must be fp32
539
+ scale = (fp8_dtype_max / tl.clamp(global_amax, min=EPS, max=float("inf"))).to(
540
+ tl.float32
541
+ )
542
+ scale_off = tl.arange(0, 1)
543
+ tl.store(scale_out_ptr + scale_off, scale)
544
+
545
+
546
+ def hp_to_fp8_row_major(
547
+ hp_tensor: torch.Tensor,
548
+ fp8_dtype: torch.dtype,
549
+ linear_mm_config: LinearMMConfig,
550
+ gemm_input_role: GemmInputRole = GemmInputRole.INPUT,
551
+ algo: KernelAlgorithm = KernelAlgorithm.ATOMIC_MAX,
552
+ ) -> Float8TrainingTensor:
553
+ assert hp_tensor.is_contiguous(), "input tensor must be contiguous"
554
+
555
+ num_elements = hp_tensor.numel()
556
+ tl_input_dtype = FP8_DTYPE_MAP[hp_tensor.dtype]
557
+ tl_output_dtype = FP8_DTYPE_MAP[fp8_dtype]
558
+
559
+ fp8_dtype_min = torch.finfo(fp8_dtype).min
560
+ fp8_dtype_max = torch.finfo(fp8_dtype).max
561
+
562
+ # compute scaling factor for tensor
563
+ scale = _hp_tensor_to_scale(
564
+ hp_tensor,
565
+ tl_input_dtype,
566
+ fp8_dtype_max,
567
+ algo,
568
+ )
569
+
570
+ # perform fp8 conversion
571
+ output_buffer = torch.empty_like(
572
+ hp_tensor, dtype=fp8_dtype, device=hp_tensor.device
573
+ )
574
+ grid = lambda meta: (triton.cdiv(num_elements, meta["BLOCK_SIZE"]),)
575
+ _to_fp8_row_major[grid](
576
+ hp_tensor,
577
+ output_buffer,
578
+ scale,
579
+ num_elements,
580
+ fp8_dtype_min,
581
+ fp8_dtype_max,
582
+ tl_input_dtype,
583
+ tl_output_dtype,
584
+ EPS=EPS,
585
+ )
586
+
587
+ # wrap output tensor in Float8TrainingTensor
588
+ fp8_tensor_row_major = Float8TrainingTensor(
589
+ output_buffer,
590
+ scale,
591
+ orig_dtype=hp_tensor.dtype,
592
+ linear_mm_config=linear_mm_config,
593
+ gemm_input_role=gemm_input_role,
594
+ )
595
+ return fp8_tensor_row_major
596
+
597
+
598
+ def hp_to_fp8_row_major_t(
599
+ hp_tensor: torch.Tensor,
600
+ fp8_dtype: torch.dtype,
601
+ linear_mm_config: LinearMMConfig,
602
+ gemm_input_role: GemmInputRole = GemmInputRole.INPUT,
603
+ algo: KernelAlgorithm = KernelAlgorithm.ATOMIC_MAX,
604
+ ) -> Float8TrainingTensor:
605
+ assert hp_tensor.is_contiguous(), "input tensor must be contiguous"
606
+
607
+ num_elements = hp_tensor.numel()
608
+ input_num_rows, input_num_cols = hp_tensor.shape
609
+ output_num_rows, output_num_cols = input_num_cols, input_num_rows
610
+ tl_input_dtype = FP8_DTYPE_MAP[hp_tensor.dtype]
611
+ tl_output_dtype = FP8_DTYPE_MAP[fp8_dtype]
612
+
613
+ fp8_dtype_min = torch.finfo(fp8_dtype).min
614
+ fp8_dtype_max = torch.finfo(fp8_dtype).max
615
+
616
+ # compute scaling factor for tensor
617
+ scale = _hp_tensor_to_scale(
618
+ hp_tensor,
619
+ tl_input_dtype,
620
+ fp8_dtype_max,
621
+ algo,
622
+ )
623
+
624
+ # perform conversion
625
+ output_buffer = torch.empty(
626
+ (output_num_rows, output_num_cols), dtype=fp8_dtype, device=hp_tensor.device
627
+ )
628
+ grid = lambda meta: (
629
+ triton.cdiv(input_num_rows, meta["BLOCK_SIZE_ROWS"]),
630
+ triton.cdiv(input_num_cols, meta["BLOCK_SIZE_COLS"]),
631
+ )
632
+ _to_fp8_row_major_t[grid](
633
+ hp_tensor,
634
+ output_buffer,
635
+ scale,
636
+ num_elements,
637
+ fp8_dtype_min,
638
+ fp8_dtype_max,
639
+ input_num_rows,
640
+ input_num_cols,
641
+ output_num_rows,
642
+ output_num_cols,
643
+ hp_tensor.stride(0),
644
+ hp_tensor.stride(1),
645
+ output_buffer.stride(0),
646
+ output_buffer.stride(1),
647
+ input_dtype=tl_input_dtype,
648
+ output_dtype=tl_output_dtype,
649
+ EPS=EPS,
650
+ )
651
+
652
+ # wrap output tensor in Float8TrainingTensor
653
+ fp8_tensor_row_major_t = Float8TrainingTensor(
654
+ output_buffer,
655
+ scale,
656
+ orig_dtype=hp_tensor.dtype,
657
+ linear_mm_config=linear_mm_config,
658
+ gemm_input_role=gemm_input_role,
659
+ )
660
+ return fp8_tensor_row_major_t
661
+
662
+
663
+ def hp_to_fp8_col_major(
664
+ hp_tensor: torch.Tensor,
665
+ fp8_dtype: torch.dtype,
666
+ linear_mm_config: LinearMMConfig,
667
+ gemm_input_role: GemmInputRole = GemmInputRole.INPUT,
668
+ algo: KernelAlgorithm = KernelAlgorithm.ATOMIC_MAX,
669
+ ) -> Float8TrainingTensor:
670
+ assert hp_tensor.is_contiguous(), "input tensor must be contiguous"
671
+
672
+ num_elements = hp_tensor.numel()
673
+ num_rows, num_cols = hp_tensor.shape
674
+ tl_input_dtype = FP8_DTYPE_MAP[hp_tensor.dtype]
675
+ tl_output_dtype = FP8_DTYPE_MAP[fp8_dtype]
676
+
677
+ fp8_dtype_min = torch.finfo(fp8_dtype).min
678
+ fp8_dtype_max = torch.finfo(fp8_dtype).max
679
+
680
+ # compute scaling factor for tensor
681
+ scale = _hp_tensor_to_scale(
682
+ hp_tensor,
683
+ tl_input_dtype,
684
+ fp8_dtype_max,
685
+ algo,
686
+ )
687
+
688
+ # perform fp8 conversion
689
+ output_buffer = torch.empty_like(
690
+ hp_tensor, dtype=fp8_dtype, device=hp_tensor.device
691
+ )
692
+ grid = lambda meta: (
693
+ triton.cdiv(num_rows, meta["BLOCK_SIZE_ROWS"]),
694
+ triton.cdiv(num_cols, meta["BLOCK_SIZE_COLS"]),
695
+ )
696
+ _to_fp8_col_major[grid](
697
+ hp_tensor,
698
+ output_buffer,
699
+ scale,
700
+ num_elements,
701
+ fp8_dtype_min,
702
+ fp8_dtype_max,
703
+ num_rows,
704
+ num_cols,
705
+ output_buffer.stride(0),
706
+ output_buffer.stride(1),
707
+ input_dtype=tl_input_dtype,
708
+ output_dtype=tl_output_dtype,
709
+ EPS=EPS,
710
+ )
711
+
712
+ # for col major we need to update the strides to reflect the new memory layout
713
+ col_major_strides = (1, num_rows)
714
+ output_buffer = output_buffer.as_strided(output_buffer.size(), col_major_strides)
715
+
716
+ # wrap output tensor in Float8TrainingTensor
717
+ fp8_tensor_col_major = Float8TrainingTensor(
718
+ output_buffer,
719
+ scale,
720
+ orig_dtype=hp_tensor.dtype,
721
+ linear_mm_config=linear_mm_config,
722
+ gemm_input_role=gemm_input_role,
723
+ )
724
+ return fp8_tensor_col_major
725
+
726
+
727
+ def hp_to_fp8_col_major_t(
728
+ hp_tensor: torch.Tensor,
729
+ fp8_dtype: torch.dtype,
730
+ linear_mm_config: LinearMMConfig,
731
+ gemm_input_role: GemmInputRole = GemmInputRole.INPUT,
732
+ algo: KernelAlgorithm = KernelAlgorithm.ATOMIC_MAX,
733
+ ) -> Float8TrainingTensor:
734
+ assert hp_tensor.is_contiguous(), "input tensor must be contiguous"
735
+
736
+ num_elements = hp_tensor.numel()
737
+ tl_input_dtype = FP8_DTYPE_MAP[hp_tensor.dtype]
738
+ tl_output_dtype = FP8_DTYPE_MAP[fp8_dtype]
739
+
740
+ fp8_dtype_min = torch.finfo(fp8_dtype).min
741
+ fp8_dtype_max = torch.finfo(fp8_dtype).max
742
+
743
+ # compute scaling factor for tensor
744
+ scale = _hp_tensor_to_scale(
745
+ hp_tensor,
746
+ tl_input_dtype,
747
+ fp8_dtype_max,
748
+ algo,
749
+ )
750
+
751
+ # perform conversion
752
+ output_buffer = torch.empty_like(
753
+ hp_tensor.t(), dtype=fp8_dtype, device=hp_tensor.device
754
+ )
755
+ grid = lambda meta: (triton.cdiv(num_elements, meta["BLOCK_SIZE"]),)
756
+ _to_fp8_row_major[grid](
757
+ hp_tensor,
758
+ output_buffer,
759
+ scale,
760
+ num_elements,
761
+ fp8_dtype_min,
762
+ fp8_dtype_max,
763
+ tl_input_dtype,
764
+ tl_output_dtype,
765
+ EPS=EPS,
766
+ )
767
+
768
+ # wrap output tensor in Float8TrainingTensor
769
+ fp8_tensor_col_major_t = Float8TrainingTensor(
770
+ output_buffer,
771
+ scale,
772
+ orig_dtype=hp_tensor.dtype,
773
+ linear_mm_config=linear_mm_config,
774
+ gemm_input_role=gemm_input_role,
775
+ )
776
+ return fp8_tensor_col_major_t
777
+
778
+
779
+ def hp_to_fp8_row_and_col_major(
780
+ hp_tensor: torch.Tensor,
781
+ fp8_dtype: torch.dtype,
782
+ linear_mm_config: LinearMMConfig,
783
+ gemm_input_role: GemmInputRole = GemmInputRole.INPUT,
784
+ algo: KernelAlgorithm = KernelAlgorithm.ATOMIC_MAX,
785
+ ) -> Float8TrainingTensor:
786
+ assert hp_tensor.is_contiguous(), "input tensor must be contiguous"
787
+
788
+ tl_input_dtype = FP8_DTYPE_MAP[hp_tensor.dtype]
789
+ tl_output_dtype = FP8_DTYPE_MAP[fp8_dtype]
790
+
791
+ fp8_dtype_min = torch.finfo(fp8_dtype).min
792
+ fp8_dtype_max = torch.finfo(fp8_dtype).max
793
+
794
+ # compute scaling factor for tensor
795
+ scale = _hp_tensor_to_scale(
796
+ hp_tensor,
797
+ tl_input_dtype,
798
+ fp8_dtype_max,
799
+ algo,
800
+ )
801
+
802
+ # perform fp8 conversion
803
+ orig_shape = hp_tensor.shape
804
+ num_elements = hp_tensor.numel()
805
+
806
+ # preallocate necessary output tensors
807
+ fp8_output_row_major = torch.empty(
808
+ orig_shape, dtype=fp8_dtype, device=hp_tensor.device
809
+ )
810
+ fp8_output_col_major = torch.empty(
811
+ orig_shape, dtype=fp8_dtype, device=hp_tensor.device
812
+ )
813
+
814
+ # launch triton kernel to perform conversion
815
+ num_rows, num_cols = orig_shape
816
+ grid = lambda meta: (
817
+ triton.cdiv(num_rows, meta["BLOCK_SIZE_ROWS"]),
818
+ triton.cdiv(num_cols, meta["BLOCK_SIZE_COLS"]),
819
+ )
820
+ _to_fp8_row_and_col_major[grid](
821
+ hp_tensor,
822
+ fp8_output_row_major,
823
+ fp8_output_col_major,
824
+ scale,
825
+ num_elements,
826
+ fp8_dtype_min,
827
+ fp8_dtype_max,
828
+ num_rows,
829
+ num_cols,
830
+ input_dtype=tl_input_dtype,
831
+ output_dtype=tl_output_dtype,
832
+ EPS=EPS,
833
+ )
834
+
835
+ # for col major we need to update the strides to reflect the new memory layout
836
+ col_major_strides = (1, num_rows)
837
+ fp8_output_col_major = fp8_output_col_major.as_strided(
838
+ fp8_output_col_major.size(), col_major_strides
839
+ )
840
+
841
+ # wrap outputs in Float8TrainingTensors
842
+ fp8_tensor_row_major = Float8TrainingTensor(
843
+ fp8_output_row_major,
844
+ scale,
845
+ orig_dtype=hp_tensor.dtype,
846
+ linear_mm_config=linear_mm_config,
847
+ gemm_input_role=gemm_input_role,
848
+ )
849
+ fp8_tensor_col_major = Float8TrainingTensor(
850
+ fp8_output_col_major,
851
+ scale,
852
+ orig_dtype=hp_tensor.dtype,
853
+ linear_mm_config=linear_mm_config,
854
+ gemm_input_role=gemm_input_role,
855
+ )
856
+ return fp8_tensor_row_major, fp8_tensor_col_major
857
+
858
+
859
+ def hp_to_fp8_row_major_t_and_non_t(
860
+ hp_tensor: torch.Tensor,
861
+ fp8_dtype: torch.dtype,
862
+ linear_mm_config: LinearMMConfig,
863
+ gemm_input_role: GemmInputRole = GemmInputRole.INPUT,
864
+ algo: KernelAlgorithm = KernelAlgorithm.ATOMIC_MAX,
865
+ ) -> Float8TrainingTensor:
866
+ assert hp_tensor.is_contiguous(), "input tensor must be contiguous"
867
+
868
+ tl_input_dtype = FP8_DTYPE_MAP[hp_tensor.dtype]
869
+ tl_output_dtype = FP8_DTYPE_MAP[fp8_dtype]
870
+
871
+ fp8_dtype_min = torch.finfo(fp8_dtype).min
872
+ fp8_dtype_max = torch.finfo(fp8_dtype).max
873
+
874
+ # compute scaling factor for tensor
875
+ scale = _hp_tensor_to_scale(
876
+ hp_tensor,
877
+ tl_input_dtype,
878
+ fp8_dtype_max,
879
+ algo,
880
+ )
881
+
882
+ # perform fp8 conversion
883
+ input_num_rows, input_num_cols = hp_tensor.shape
884
+ transposed_num_rows, transposed_num_cols = input_num_cols, input_num_rows
885
+ num_elements = hp_tensor.numel()
886
+
887
+ # preallocate necessary output tensors
888
+ fp8_output_row_major = torch.empty(
889
+ (input_num_rows, input_num_cols), dtype=fp8_dtype, device=hp_tensor.device
890
+ )
891
+ fp8_output_row_major_t = torch.empty(
892
+ (transposed_num_rows, transposed_num_cols),
893
+ dtype=fp8_dtype,
894
+ device=hp_tensor.device,
895
+ )
896
+
897
+ # launch triton kernel to perform conversion
898
+ grid = lambda meta: (
899
+ triton.cdiv(input_num_rows, meta["BLOCK_SIZE_ROWS"]),
900
+ triton.cdiv(input_num_cols, meta["BLOCK_SIZE_COLS"]),
901
+ )
902
+ _to_fp8_row_major_t_and_non_t[grid](
903
+ hp_tensor,
904
+ fp8_output_row_major,
905
+ fp8_output_row_major_t,
906
+ scale,
907
+ num_elements,
908
+ fp8_dtype_min,
909
+ fp8_dtype_max,
910
+ input_num_rows,
911
+ input_num_cols,
912
+ hp_tensor.stride(0),
913
+ hp_tensor.stride(1),
914
+ fp8_output_row_major.stride(0),
915
+ fp8_output_row_major.stride(1),
916
+ fp8_output_row_major_t.stride(0),
917
+ fp8_output_row_major_t.stride(1),
918
+ input_dtype=tl_input_dtype,
919
+ output_dtype=tl_output_dtype,
920
+ EPS=EPS,
921
+ )
922
+
923
+ # wrap outputs in Float8TrainingTensors
924
+ fp8_tensor_row_major = Float8TrainingTensor(
925
+ fp8_output_row_major,
926
+ scale,
927
+ orig_dtype=hp_tensor.dtype,
928
+ linear_mm_config=linear_mm_config,
929
+ gemm_input_role=gemm_input_role,
930
+ )
931
+ fp8_tensor_row_major_t = Float8TrainingTensor(
932
+ fp8_output_row_major_t,
933
+ scale,
934
+ orig_dtype=hp_tensor.dtype,
935
+ linear_mm_config=linear_mm_config,
936
+ gemm_input_role=gemm_input_role,
937
+ )
938
+ return fp8_tensor_row_major, fp8_tensor_row_major_t
939
+
940
+
941
+ def hp_to_fp8_col_major_t_and_non_t(
942
+ hp_tensor: torch.Tensor,
943
+ fp8_dtype: torch.dtype,
944
+ linear_mm_config: LinearMMConfig,
945
+ gemm_input_role: GemmInputRole = GemmInputRole.INPUT,
946
+ algo: KernelAlgorithm = KernelAlgorithm.ATOMIC_MAX,
947
+ ) -> Float8TrainingTensor:
948
+ assert hp_tensor.is_contiguous(), "input tensor must be contiguous"
949
+
950
+ tl_input_dtype = FP8_DTYPE_MAP[hp_tensor.dtype]
951
+ tl_output_dtype = FP8_DTYPE_MAP[fp8_dtype]
952
+
953
+ fp8_dtype_min = torch.finfo(fp8_dtype).min
954
+ fp8_dtype_max = torch.finfo(fp8_dtype).max
955
+
956
+ # compute scaling factor for tensor
957
+ scale = _hp_tensor_to_scale(
958
+ hp_tensor,
959
+ tl_input_dtype,
960
+ fp8_dtype_max,
961
+ algo,
962
+ )
963
+
964
+ # perform fp8 conversion
965
+ input_num_rows, input_num_cols = hp_tensor.shape
966
+ num_elements = hp_tensor.numel()
967
+
968
+ # preallocate necessary output tensors
969
+ fp8_output_col_major = torch.empty(
970
+ (input_num_rows, input_num_cols), dtype=fp8_dtype, device=hp_tensor.device
971
+ )
972
+ fp8_output_col_major_t = torch.empty_like(
973
+ hp_tensor.t(),
974
+ dtype=fp8_dtype,
975
+ device=hp_tensor.device,
976
+ )
977
+
978
+ # launch triton kernel to perform conversion
979
+ grid = lambda meta: (
980
+ triton.cdiv(input_num_rows, meta["BLOCK_SIZE_ROWS"]),
981
+ triton.cdiv(input_num_cols, meta["BLOCK_SIZE_COLS"]),
982
+ )
983
+ _to_fp8_col_major_t_and_non_t[grid](
984
+ hp_tensor,
985
+ fp8_output_col_major,
986
+ fp8_output_col_major_t,
987
+ scale,
988
+ num_elements,
989
+ fp8_dtype_min,
990
+ fp8_dtype_max,
991
+ input_num_rows,
992
+ input_num_cols,
993
+ hp_tensor.stride(0),
994
+ hp_tensor.stride(1),
995
+ fp8_output_col_major.stride(0),
996
+ fp8_output_col_major.stride(1),
997
+ fp8_output_col_major_t.stride(0),
998
+ fp8_output_col_major_t.stride(1),
999
+ input_dtype=tl_input_dtype,
1000
+ output_dtype=tl_output_dtype,
1001
+ EPS=EPS,
1002
+ )
1003
+
1004
+ # for col major we need to update the strides to reflect the new memory layout
1005
+ col_major_strides = (1, input_num_rows)
1006
+ fp8_output_col_major = fp8_output_col_major.as_strided(
1007
+ fp8_output_col_major.size(), col_major_strides
1008
+ )
1009
+
1010
+ # wrap outputs in Float8TrainingTensors
1011
+ fp8_tensor_col_major = Float8TrainingTensor(
1012
+ fp8_output_col_major,
1013
+ scale,
1014
+ orig_dtype=hp_tensor.dtype,
1015
+ linear_mm_config=linear_mm_config,
1016
+ gemm_input_role=gemm_input_role,
1017
+ )
1018
+ fp8_tensor_col_major_t = Float8TrainingTensor(
1019
+ fp8_output_col_major_t,
1020
+ scale,
1021
+ orig_dtype=hp_tensor.dtype,
1022
+ linear_mm_config=linear_mm_config,
1023
+ gemm_input_role=gemm_input_role,
1024
+ )
1025
+ return fp8_tensor_col_major, fp8_tensor_col_major_t
1026
+
1027
+
1028
+ def _hp_tensor_to_scale(
1029
+ hp_tensor: torch.Tensor,
1030
+ tl_input_dtype: tl.core.dtype,
1031
+ fp8_dtype_max: float,
1032
+ algo: KernelAlgorithm,
1033
+ ) -> torch.Tensor:
1034
+ num_elements = hp_tensor.numel()
1035
+ scale_out = torch.empty((), dtype=torch.float32, device=hp_tensor.device)
1036
+ grid = lambda meta: (triton.cdiv(num_elements, meta["BLOCK_SIZE"]),)
1037
+
1038
+ # compute the fp8 scale using the given algorithm
1039
+ if algo == KernelAlgorithm.ATOMIC_MAX:
1040
+ global_amax = torch.zeros((1,), dtype=torch.float32, device=hp_tensor.device)
1041
+ # compute global amax to be used for scaling
1042
+ _amax_atomic[grid](
1043
+ hp_tensor,
1044
+ global_amax,
1045
+ num_elements,
1046
+ input_dtype=tl_input_dtype,
1047
+ EPS=EPS,
1048
+ )
1049
+
1050
+ # compute scale for fp8 conversion
1051
+ _scale_atomic[1, 1, 1](
1052
+ global_amax,
1053
+ scale_out,
1054
+ fp8_dtype_max,
1055
+ EPS=EPS,
1056
+ )
1057
+
1058
+ elif algo == KernelAlgorithm.REDUCTION:
1059
+ # max block size and num warps values determined via manual tuning
1060
+ max_block_size = 4096
1061
+ num_warps = 8
1062
+ block_size = triton.next_power_of_2(min(max_block_size, num_elements))
1063
+ amax_buffer_size = triton.cdiv(num_elements, block_size)
1064
+ block_amaxes = torch.zeros(
1065
+ (amax_buffer_size,), dtype=torch.float32, device=hp_tensor.device
1066
+ )
1067
+ # compute local amax for each block
1068
+ _amax_reduction[grid](
1069
+ hp_tensor,
1070
+ block_amaxes,
1071
+ num_elements,
1072
+ input_dtype=tl_input_dtype,
1073
+ BLOCK_SIZE=block_size,
1074
+ EPS=EPS,
1075
+ num_warps=num_warps,
1076
+ )
1077
+
1078
+ # calculate global amax across all blocks and use it to compute scale
1079
+ _scale_reduction[(1, 1, 1)](
1080
+ block_amaxes,
1081
+ scale_out,
1082
+ num_elements,
1083
+ fp8_dtype_max,
1084
+ BLOCK_SIZE=block_size,
1085
+ EPS=EPS,
1086
+ )
1087
+ else:
1088
+ raise ValueError(f"Unsupported kernel algorithm: {algo}")
1089
+
1090
+ return scale_out
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/float8nocompile/kernels/fp8_dynamic_tensorwise_test.py ADDED
@@ -0,0 +1,493 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD 3-Clause license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+ import pytest
7
+ import torch
8
+
9
+ from torchao.float8.float8_scaling_utils import hp_tensor_to_float8_dynamic
10
+ from torchao.float8.float8_training_tensor import LinearMMConfig
11
+ from torchao.float8.float8_utils import is_row_major
12
+ from torchao.prototype.float8nocompile.kernels.fp8_dynamic_tensorwise import (
13
+ KernelAlgorithm,
14
+ hp_to_fp8_col_major,
15
+ hp_to_fp8_col_major_t,
16
+ hp_to_fp8_col_major_t_and_non_t,
17
+ hp_to_fp8_row_and_col_major,
18
+ hp_to_fp8_row_major,
19
+ hp_to_fp8_row_major_t,
20
+ hp_to_fp8_row_major_t_and_non_t,
21
+ )
22
+
23
+
24
+ @pytest.mark.parametrize(
25
+ "algo",
26
+ [KernelAlgorithm.REDUCTION, KernelAlgorithm.ATOMIC_MAX],
27
+ )
28
+ @pytest.mark.parametrize(
29
+ "input_shape",
30
+ [(2, 4), (32, 16), (512, 512)],
31
+ )
32
+ def test_fp8_hp_to_fp8_row_major(input_shape: tuple[int, int], algo: KernelAlgorithm):
33
+ assert torch.cuda.is_available()
34
+ device = "cuda"
35
+ input_bf16 = torch.randn(input_shape, dtype=torch.bfloat16, device=device)
36
+ x_bf16 = input_bf16.clone().detach().to(device)
37
+ y_bf16 = input_bf16.clone().detach().to(device)
38
+
39
+ # production implementation
40
+ x_fp8_row_major = hp_tensor_to_float8_dynamic(
41
+ x_bf16,
42
+ torch.float8_e4m3fn,
43
+ LinearMMConfig(),
44
+ )
45
+
46
+ # float8nocompile triton implementation
47
+ y_fp8_row_major = hp_to_fp8_row_major(
48
+ y_bf16,
49
+ torch.float8_e4m3fn,
50
+ LinearMMConfig(),
51
+ algo=algo,
52
+ )
53
+
54
+ # check scales
55
+ assert torch.eq(x_fp8_row_major._scale, y_fp8_row_major._scale)
56
+
57
+ # check data
58
+ assert torch.all(torch.eq(x_fp8_row_major._data, y_fp8_row_major._data))
59
+
60
+ # check shapes
61
+ assert x_fp8_row_major.shape == y_fp8_row_major.shape
62
+
63
+ # check strides
64
+ assert x_fp8_row_major.stride() == y_fp8_row_major.stride()
65
+
66
+ # check memory layout
67
+ assert is_row_major(x_fp8_row_major.stride())
68
+ assert is_row_major(y_fp8_row_major.stride())
69
+
70
+ # check underlying memory layout
71
+ assert (
72
+ x_fp8_row_major._data.storage().tolist()
73
+ == y_fp8_row_major._data.storage().tolist()
74
+ )
75
+
76
+ # assert that error is raised when input tensor is not contiguous
77
+ with pytest.raises(AssertionError, match="tensor must be contiguous"):
78
+ hp_to_fp8_row_major(
79
+ y_bf16.t(), # transpose so tensor memory layout is no longer contiguous
80
+ torch.float8_e4m3fn,
81
+ LinearMMConfig(),
82
+ )
83
+
84
+
85
+ @pytest.mark.parametrize(
86
+ "algo",
87
+ [KernelAlgorithm.REDUCTION, KernelAlgorithm.ATOMIC_MAX],
88
+ )
89
+ @pytest.mark.parametrize(
90
+ "input_shape",
91
+ [(2, 4), (32, 16), (512, 512)],
92
+ )
93
+ def test_fp8_hp_to_fp8_row_major_t(input_shape: tuple[int, int], algo: KernelAlgorithm):
94
+ assert torch.cuda.is_available()
95
+ device = "cuda"
96
+ input_bf16 = torch.tensor(
97
+ [[1, 2, 3], [4, 5, 6]], dtype=torch.bfloat16, device=device
98
+ )
99
+ x_bf16 = input_bf16.clone().detach().to(device)
100
+ y_bf16 = input_bf16.clone().detach().to(device)
101
+
102
+ # production implementation
103
+ x_fp8_row_major = hp_tensor_to_float8_dynamic(
104
+ x_bf16,
105
+ torch.float8_e4m3fn,
106
+ LinearMMConfig(),
107
+ )
108
+ x_fp8_row_major_t = x_fp8_row_major.t().contiguous()
109
+
110
+ # float8nocompile triton implementation
111
+ y_fp8_row_major_t = hp_to_fp8_row_major_t(
112
+ y_bf16,
113
+ torch.float8_e4m3fn,
114
+ LinearMMConfig(),
115
+ algo=algo,
116
+ )
117
+
118
+ # check scales
119
+ assert torch.eq(x_fp8_row_major_t._scale, y_fp8_row_major_t._scale)
120
+
121
+ # check data
122
+ assert torch.all(torch.eq(x_fp8_row_major_t._data, y_fp8_row_major_t._data))
123
+
124
+ # check shapes
125
+ assert x_fp8_row_major_t.shape == y_fp8_row_major_t.shape
126
+
127
+ # check strides
128
+ assert x_fp8_row_major_t.stride() == y_fp8_row_major_t.stride()
129
+
130
+ # check memory layout
131
+ assert is_row_major(x_fp8_row_major_t.stride())
132
+ assert is_row_major(y_fp8_row_major_t.stride())
133
+
134
+ # check underlying memory layout
135
+ assert (
136
+ x_fp8_row_major_t._data.storage().tolist()
137
+ == y_fp8_row_major_t._data.storage().tolist()
138
+ )
139
+
140
+ # assert that error is raised when input tensor is not contiguous
141
+ with pytest.raises(AssertionError, match="tensor must be contiguous"):
142
+ hp_to_fp8_row_major(
143
+ y_bf16.t(), # transpose so tensor memory layout is no longer contiguous
144
+ torch.float8_e4m3fn,
145
+ LinearMMConfig(),
146
+ )
147
+
148
+
149
+ @pytest.mark.parametrize(
150
+ "algo",
151
+ [KernelAlgorithm.REDUCTION, KernelAlgorithm.ATOMIC_MAX],
152
+ )
153
+ @pytest.mark.parametrize(
154
+ "input_shape",
155
+ [(2, 4), (32, 16), (512, 512)],
156
+ )
157
+ def test_fp8_hp_to_fp8_col_major(input_shape: tuple[int, int], algo: KernelAlgorithm):
158
+ assert torch.cuda.is_available()
159
+ device = "cuda"
160
+ input_bf16 = torch.randn(input_shape, dtype=torch.bfloat16, device=device)
161
+ x_bf16 = input_bf16.clone().detach().to(device)
162
+ y_bf16 = input_bf16.clone().detach().to(device)
163
+
164
+ # production implementation
165
+ x_fp8_row_major = hp_tensor_to_float8_dynamic(
166
+ x_bf16,
167
+ torch.float8_e4m3fn,
168
+ LinearMMConfig(),
169
+ )
170
+ x_fp8_col_major = x_fp8_row_major.t().contiguous().t()
171
+
172
+ # float8nocompile triton implementation
173
+ y_fp8_col_major = hp_to_fp8_col_major(
174
+ y_bf16,
175
+ torch.float8_e4m3fn,
176
+ LinearMMConfig(),
177
+ algo=algo,
178
+ )
179
+
180
+ # check scales
181
+ assert torch.eq(x_fp8_col_major._scale, y_fp8_col_major._scale)
182
+
183
+ # check data
184
+ assert torch.all(torch.eq(x_fp8_col_major._data, y_fp8_col_major._data))
185
+
186
+ # check shapes
187
+ assert x_fp8_col_major.shape == y_fp8_col_major.shape
188
+
189
+ # check strides
190
+ assert x_fp8_col_major.stride() == y_fp8_col_major.stride()
191
+
192
+ # check memory layout
193
+ assert not is_row_major(x_fp8_col_major.stride())
194
+ assert not is_row_major(y_fp8_col_major.stride())
195
+
196
+ # check underlying memory layout
197
+ assert (
198
+ x_fp8_col_major._data.storage().tolist()
199
+ == y_fp8_col_major._data.storage().tolist()
200
+ )
201
+
202
+ # assert that error is raised when input tensor is not contiguous
203
+ with pytest.raises(AssertionError, match="tensor must be contiguous"):
204
+ hp_to_fp8_col_major(
205
+ y_bf16.t(), # transpose so tensor memory layout is no longer contiguous
206
+ torch.float8_e4m3fn,
207
+ LinearMMConfig(),
208
+ )
209
+
210
+
211
+ @pytest.mark.parametrize(
212
+ "algo",
213
+ [KernelAlgorithm.REDUCTION, KernelAlgorithm.ATOMIC_MAX],
214
+ )
215
+ @pytest.mark.parametrize(
216
+ "input_shape",
217
+ [(2, 4), (32, 16), (512, 512)],
218
+ )
219
+ def test_fp8_hp_to_fp8_col_major_t(input_shape: tuple[int, int], algo: KernelAlgorithm):
220
+ assert torch.cuda.is_available()
221
+ device = "cuda"
222
+ input_bf16 = torch.randn(input_shape, dtype=torch.bfloat16, device=device)
223
+ x_bf16 = input_bf16.clone().detach().to(device)
224
+ y_bf16 = input_bf16.clone().detach().to(device)
225
+
226
+ # production implementation
227
+ x_fp8_row_major = hp_tensor_to_float8_dynamic(
228
+ x_bf16,
229
+ torch.float8_e4m3fn,
230
+ LinearMMConfig(),
231
+ )
232
+ x_fp8_col_major_t = x_fp8_row_major.contiguous().t()
233
+
234
+ # float8nocompile triton implementation
235
+ y_fp8_col_major_t = hp_to_fp8_col_major_t(
236
+ y_bf16,
237
+ torch.float8_e4m3fn,
238
+ LinearMMConfig(),
239
+ algo=algo,
240
+ )
241
+
242
+ # check scales
243
+ assert torch.eq(x_fp8_col_major_t._scale, y_fp8_col_major_t._scale)
244
+
245
+ # check data
246
+ assert torch.all(torch.eq(x_fp8_col_major_t._data, y_fp8_col_major_t._data))
247
+
248
+ # check shapes
249
+ assert x_fp8_col_major_t.shape == y_fp8_col_major_t.shape
250
+
251
+ # check strides
252
+ assert x_fp8_col_major_t.stride() == y_fp8_col_major_t.stride()
253
+
254
+ # check memory layout
255
+ assert not is_row_major(x_fp8_col_major_t.stride())
256
+ assert not is_row_major(y_fp8_col_major_t.stride())
257
+
258
+ # check underlying memory layout
259
+ assert (
260
+ x_fp8_col_major_t._data.storage().tolist()
261
+ == y_fp8_col_major_t._data.storage().tolist()
262
+ )
263
+
264
+ # assert that error is raised when input tensor is not contiguous
265
+ with pytest.raises(AssertionError, match="tensor must be contiguous"):
266
+ hp_to_fp8_col_major(
267
+ y_bf16.t(), # transpose so tensor memory layout is no longer contiguous
268
+ torch.float8_e4m3fn,
269
+ LinearMMConfig(),
270
+ )
271
+
272
+
273
+ @pytest.mark.parametrize(
274
+ "algo",
275
+ [KernelAlgorithm.REDUCTION, KernelAlgorithm.ATOMIC_MAX],
276
+ )
277
+ @pytest.mark.parametrize(
278
+ "input_shape",
279
+ [(2, 4), (32, 16), (512, 512)],
280
+ )
281
+ def test_fp8_hp_to_fp8_row_and_col_major(
282
+ input_shape: tuple[int, int], algo: KernelAlgorithm
283
+ ):
284
+ assert torch.cuda.is_available()
285
+ device = "cuda"
286
+ input_bf16 = torch.randn(input_shape, dtype=torch.bfloat16, device=device)
287
+ x_bf16 = input_bf16.clone().detach().to(device)
288
+ y_bf16 = input_bf16.clone().detach().to(device)
289
+
290
+ # production implementation
291
+ x_fp8_row_major = hp_tensor_to_float8_dynamic(
292
+ x_bf16,
293
+ torch.float8_e4m3fn,
294
+ LinearMMConfig(),
295
+ )
296
+ x_fp8_col_major = x_fp8_row_major.t().contiguous().t()
297
+
298
+ # float8nocompile triton implementation
299
+ y_fp8_row_major, y_fp8_col_major = hp_to_fp8_row_and_col_major(
300
+ y_bf16,
301
+ torch.float8_e4m3fn,
302
+ LinearMMConfig(),
303
+ algo=algo,
304
+ )
305
+
306
+ # check scales
307
+ assert torch.eq(x_fp8_row_major._scale, y_fp8_row_major._scale)
308
+ assert torch.eq(x_fp8_col_major._scale, y_fp8_col_major._scale)
309
+
310
+ # check data
311
+ assert torch.all(torch.eq(x_fp8_row_major._data, y_fp8_row_major._data))
312
+ assert torch.all(torch.eq(x_fp8_col_major._data, y_fp8_col_major._data))
313
+
314
+ # check shapes
315
+ assert x_fp8_row_major.shape == y_fp8_row_major.shape
316
+ assert x_fp8_col_major.shape == y_fp8_col_major.shape
317
+
318
+ # check strides
319
+ assert x_fp8_row_major.stride() == y_fp8_row_major.stride()
320
+ assert x_fp8_col_major.stride() == y_fp8_col_major.stride()
321
+
322
+ # check memory layout
323
+ assert is_row_major(x_fp8_row_major.stride())
324
+ assert is_row_major(y_fp8_row_major.stride())
325
+ assert not is_row_major(x_fp8_col_major.stride())
326
+ assert not is_row_major(y_fp8_col_major.stride())
327
+
328
+ # check underlying memory layout
329
+ assert (
330
+ x_fp8_row_major._data.storage().tolist()
331
+ == y_fp8_row_major._data.storage().tolist()
332
+ )
333
+ assert (
334
+ x_fp8_col_major._data.storage().tolist()
335
+ == y_fp8_col_major._data.storage().tolist()
336
+ )
337
+
338
+ # assert that error is raised when input tensor is not contiguous
339
+ with pytest.raises(AssertionError, match="tensor must be contiguous"):
340
+ hp_to_fp8_row_and_col_major(
341
+ y_bf16.t(), # transpose so tensor memory layout is no longer contiguous
342
+ torch.float8_e4m3fn,
343
+ LinearMMConfig(),
344
+ )
345
+
346
+
347
+ @pytest.mark.parametrize(
348
+ "algo",
349
+ [KernelAlgorithm.REDUCTION, KernelAlgorithm.ATOMIC_MAX],
350
+ )
351
+ @pytest.mark.parametrize(
352
+ "input_shape",
353
+ [(2, 4), (32, 16), (512, 512)],
354
+ )
355
+ def test_fp8_hp_to_fp8_row_major_t_and_non_t(
356
+ input_shape: tuple[int, int], algo: KernelAlgorithm
357
+ ):
358
+ assert torch.cuda.is_available()
359
+ device = "cuda"
360
+ input_bf16 = torch.randn(input_shape, dtype=torch.bfloat16, device=device)
361
+ x_bf16 = input_bf16.clone().detach().to(device)
362
+ y_bf16 = input_bf16.clone().detach().to(device)
363
+
364
+ # production implementation
365
+ x_fp8_row_major = hp_tensor_to_float8_dynamic(
366
+ x_bf16,
367
+ torch.float8_e4m3fn,
368
+ LinearMMConfig(),
369
+ )
370
+ x_fp8_row_major_t = x_fp8_row_major.t().contiguous()
371
+
372
+ # float8nocompile triton implementation
373
+ y_fp8_row_major, y_fp8_row_major_t = hp_to_fp8_row_major_t_and_non_t(
374
+ y_bf16,
375
+ torch.float8_e4m3fn,
376
+ LinearMMConfig(),
377
+ algo=algo,
378
+ )
379
+
380
+ # check scales
381
+ assert torch.eq(x_fp8_row_major._scale, y_fp8_row_major._scale)
382
+ assert torch.eq(x_fp8_row_major_t._scale, y_fp8_row_major_t._scale)
383
+
384
+ # check data
385
+ assert torch.all(torch.eq(x_fp8_row_major._data, y_fp8_row_major._data))
386
+ assert torch.all(torch.eq(x_fp8_row_major_t._data, y_fp8_row_major_t._data))
387
+
388
+ # check shapes
389
+ assert x_fp8_row_major.shape == y_fp8_row_major.shape
390
+ assert x_fp8_row_major_t.shape == y_fp8_row_major_t.shape
391
+
392
+ # check strides
393
+ assert x_fp8_row_major.stride() == y_fp8_row_major.stride()
394
+ assert x_fp8_row_major_t.stride() == y_fp8_row_major_t.stride()
395
+
396
+ # check memory layout
397
+ assert is_row_major(x_fp8_row_major.stride())
398
+ assert is_row_major(y_fp8_row_major.stride())
399
+ assert is_row_major(x_fp8_row_major_t.stride())
400
+ assert is_row_major(y_fp8_row_major_t.stride())
401
+
402
+ # check underlying memory layout
403
+ assert (
404
+ x_fp8_row_major._data.storage().tolist()
405
+ == y_fp8_row_major._data.storage().tolist()
406
+ )
407
+ assert (
408
+ x_fp8_row_major_t._data.storage().tolist()
409
+ == y_fp8_row_major_t._data.storage().tolist()
410
+ )
411
+
412
+ # assert that error is raised when input tensor is not contiguous
413
+ with pytest.raises(AssertionError, match="tensor must be contiguous"):
414
+ hp_to_fp8_row_major_t_and_non_t(
415
+ y_bf16.t(), # transpose so tensor memory layout is no longer contiguous
416
+ torch.float8_e4m3fn,
417
+ LinearMMConfig(),
418
+ )
419
+
420
+
421
+ @pytest.mark.parametrize(
422
+ "algo",
423
+ [KernelAlgorithm.REDUCTION, KernelAlgorithm.ATOMIC_MAX],
424
+ )
425
+ @pytest.mark.parametrize(
426
+ "input_shape",
427
+ [(2, 4), (32, 16), (512, 512)],
428
+ )
429
+ def test_fp8_hp_to_fp8_col_major_t_and_non_t(
430
+ input_shape: tuple[int, int], algo: KernelAlgorithm
431
+ ):
432
+ assert torch.cuda.is_available()
433
+ device = "cuda"
434
+ input_bf16 = torch.randn(input_shape, dtype=torch.bfloat16, device=device)
435
+ x_bf16 = input_bf16.clone().detach().to(device)
436
+ y_bf16 = input_bf16.clone().detach().to(device)
437
+
438
+ # production implementation
439
+ x_fp8_row_major = hp_tensor_to_float8_dynamic(
440
+ x_bf16,
441
+ torch.float8_e4m3fn,
442
+ LinearMMConfig(),
443
+ )
444
+ x_fp8_col_major = x_fp8_row_major.t().contiguous().t()
445
+ x_fp8_col_major_t = x_fp8_row_major.t()
446
+
447
+ # float8nocompile triton implementation
448
+ y_fp8_col_major, y_fp8_col_major_t = hp_to_fp8_col_major_t_and_non_t(
449
+ y_bf16,
450
+ torch.float8_e4m3fn,
451
+ LinearMMConfig(),
452
+ algo=algo,
453
+ )
454
+
455
+ # check scales
456
+ assert torch.eq(x_fp8_col_major._scale, y_fp8_col_major._scale)
457
+ assert torch.eq(x_fp8_col_major_t._scale, y_fp8_col_major_t._scale)
458
+
459
+ # check data
460
+ assert torch.all(torch.eq(x_fp8_col_major._data, y_fp8_col_major._data))
461
+ assert torch.all(torch.eq(x_fp8_col_major_t._data, y_fp8_col_major_t._data))
462
+
463
+ # check shapes
464
+ assert x_fp8_col_major.shape == y_fp8_col_major.shape
465
+ assert x_fp8_col_major_t.shape == y_fp8_col_major_t.shape
466
+
467
+ # check strides
468
+ assert x_fp8_col_major.stride() == y_fp8_col_major.stride()
469
+ assert x_fp8_col_major_t.stride() == y_fp8_col_major_t.stride()
470
+
471
+ # check memory layout
472
+ assert not is_row_major(x_fp8_col_major.stride())
473
+ assert not is_row_major(y_fp8_col_major.stride())
474
+ assert not is_row_major(x_fp8_col_major_t.stride())
475
+ assert not is_row_major(y_fp8_col_major_t.stride())
476
+
477
+ # check underlying memory layout
478
+ assert (
479
+ x_fp8_col_major._data.storage().tolist()
480
+ == y_fp8_col_major._data.storage().tolist()
481
+ )
482
+ assert (
483
+ x_fp8_col_major_t._data.storage().tolist()
484
+ == y_fp8_col_major_t._data.storage().tolist()
485
+ )
486
+
487
+ # assert that error is raised when input tensor is not contiguous
488
+ with pytest.raises(AssertionError, match="tensor must be contiguous"):
489
+ hp_to_fp8_col_major_t_and_non_t(
490
+ y_bf16.t(), # transpose so tensor memory layout is no longer contiguous
491
+ torch.float8_e4m3fn,
492
+ LinearMMConfig(),
493
+ )
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/moe_training/ep/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.09 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/moe_training/ep/__pycache__/a2a_combine.cpython-310.pyc ADDED
Binary file (4.96 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/moe_training/ep/__pycache__/a2a_dispatch.cpython-310.pyc ADDED
Binary file (4.42 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/moe_training/ep/__pycache__/kernels.cpython-310.pyc ADDED
Binary file (3.9 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/moe_training/ep/__pycache__/permute.cpython-310.pyc ADDED
Binary file (8.04 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/moe_training/ep/__pycache__/unpermute.cpython-310.pyc ADDED
Binary file (3.78 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/torchao/prototype/moe_training/kernels/mxfp8/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (843 Bytes). View file