Merged
fixup: examples: Fix bad type hints #13
lidongshengAdd on Dec 26, 2025
fixup: examples: Fix bad type hints #13
Merged
Merged fromtsungl4/pypto-openfixup/typesintocann/pyptomaster
Total: 13 files changed+548-544
| @@ -45,13 +45,13 @@ def get_device_id(): | |||
| 45 | 45 | ||
| 46 | 46 | ||
| 47 | @pypto.jit | 47 | @pypto.jit |
| 48 | -def add_direct_kernel_npu(x: torch.Tensor, y: torch.Tensor, z: torch.Tensor) -> None: | 48 | +def add_direct_kernel_npu(x: pypto.Tensor, y: pypto.Tensor, z: pypto.Tensor) -> None: |
| 49 | pypto.set_vec_tile_shapes(1, 4, 1, 64) | 49 | pypto.set_vec_tile_shapes(1, 4, 1, 64) |
| 50 | z[:] = x + y | 50 | z[:] = x + y |
| 51 | 51 | ||
| 52 | 52 | ||
| 53 | @pypto.jit(runtime_options={"run_mode": 1}) | 53 | @pypto.jit(runtime_options={"run_mode": 1}) |
| 54 | -def add_direct_kernel_sim(x: torch.Tensor, y: torch.Tensor, z: torch.Tensor) -> None: | 54 | +def add_direct_kernel_sim(x: pypto.Tensor, y: pypto.Tensor, z: pypto.Tensor) -> None: |
| 55 | pypto.set_vec_tile_shapes(1, 4, 1, 64) | 55 | pypto.set_vec_tile_shapes(1, 4, 1, 64) |
| 56 | z[:] = x + y | 56 | z[:] = x + y |
| 57 | 57 | ||
| @@ -198,4 +198,4 @@ Examples: | |||
| 198 | 198 | ||
| 199 | 199 | ||
| 200 | if __name__ == "__main__": | 200 | if __name__ == "__main__": |
| 201 | - main() | 201 | + main() |
| @@ -25,7 +25,7 @@ from numpy.testing import assert_allclose | |||
| 25 | def get_device_id(): | 25 | def get_device_id(): |
| 26 | """ | 26 | """ |
| 27 | Get and validate TILE_FWK_DEVICE_ID from environment variable. | 27 | Get and validate TILE_FWK_DEVICE_ID from environment variable. |
| 28 | - | 28 | + |
| 29 | Returns: | 29 | Returns: |
| 30 | int: The device ID if valid, None otherwise. | 30 | int: The device ID if valid, None otherwise. |
| 31 | """ | 31 | """ |
| @@ -34,7 +34,7 @@ def get_device_id(): | |||
| 34 | print("Please set it before running this example:") | 34 | print("Please set it before running this example:") |
| 35 | print(" export TILE_FWK_DEVICE_ID=0") | 35 | print(" export TILE_FWK_DEVICE_ID=0") |
| 36 | return None | 36 | return None |
| 37 | - | 37 | + |
| 38 | try: | 38 | try: |
| 39 | device_id = int(os.environ['TILE_FWK_DEVICE_ID']) | 39 | device_id = int(os.environ['TILE_FWK_DEVICE_ID']) |
| 40 | return device_id | 40 | return device_id |
| @@ -44,7 +44,9 @@ def get_device_id(): | |||
| 44 | 44 | ||
| 45 | 45 | ||
| 46 | @pypto.jit | 46 | @pypto.jit |
| 47 | -def add_scalar_loop_dynamic_axis_kernel_npu(input0: torch.Tensor, input1: torch.Tensor, output: torch.Tensor, val: int) -> None: | 47 | +def add_scalar_loop_dynamic_axis_kernel_npu(input0: pypto.Tensor, |
| 48 | + input1: pypto.Tensor, | ||
| 49 | + output: pypto.Tensor, val: int) -> None: | ||
| 48 | tensor_shape = input0.shape | 50 | tensor_shape = input0.shape |
| 49 | pypto.set_vec_tile_shapes(1, 4, 1, 64) | 51 | pypto.set_vec_tile_shapes(1, 4, 1, 64) |
| 50 | 52 | ||
| @@ -63,7 +65,9 @@ def add_scalar_loop_dynamic_axis_kernel_npu(input0: torch.Tensor, input1: torch. | |||
| 63 | 65 | ||
| 64 | 66 | ||
| 65 | @pypto.jit(runtime_options={"run_mode": 1}) | 67 | @pypto.jit(runtime_options={"run_mode": 1}) |
| 66 | -def add_scalar_loop_dynamic_axis_kernel_sim(input0: torch.Tensor, input1: torch.Tensor, output: torch.Tensor, val: int) -> None: | 68 | +def add_scalar_loop_dynamic_axis_kernel_sim(input0: pypto.Tensor, |
| 69 | + input1: pypto.Tensor, | ||
| 70 | + output: pypto.Tensor, val: int) -> None: | ||
| 67 | tensor_shape = input0.shape | 71 | tensor_shape = input0.shape |
| 68 | pypto.set_vec_tile_shapes(1, 4, 1, 64) | 72 | pypto.set_vec_tile_shapes(1, 4, 1, 64) |
| 69 | 73 | ||
| @@ -119,7 +123,7 @@ def test_add_scalar_loop_dyn_axis(device_id = None, run_mode: str = "npu") -> No | |||
| 119 | 123 | ||
| 120 | def main(): | 124 | def main(): |
| 121 | """Run add_scalar_loop_dyn_axis example. | 125 | """Run add_scalar_loop_dyn_axis example. |
| 122 | - | 126 | + |
| 123 | Usage: | 127 | Usage: |
| 124 | python add_scalar_loop_dyn_axis.py # Run example | 128 | python add_scalar_loop_dyn_axis.py # Run example |
| 125 | python add_scalar_loop_dyn_axis.py --list # List available examples | 129 | python add_scalar_loop_dyn_axis.py --list # List available examples |
| @@ -153,9 +157,9 @@ Examples: | |||
| 153 | choices=["npu", "sim"], | 157 | choices=["npu", "sim"], |
| 154 | help='Run mode, such as npu/sim etc.' | 158 | help='Run mode, such as npu/sim etc.' |
| 155 | ) | 159 | ) |
| 156 | - | 160 | + |
| 157 | args = parser.parse_args() | 161 | args = parser.parse_args() |
| 158 | - | 162 | + |
| 159 | # Define available examples | 163 | # Define available examples |
| 160 | examples = { | 164 | examples = { |
| 161 | "add_scalar_loop_dyn_axis::test_add_scalar_loop_dyn_axis": { | 165 | "add_scalar_loop_dyn_axis::test_add_scalar_loop_dyn_axis": { |
| @@ -164,7 +168,7 @@ Examples: | |||
| 164 | 'function': test_add_scalar_loop_dyn_axis | 168 | 'function': test_add_scalar_loop_dyn_axis |
| 165 | } | 169 | } |
| 166 | } | 170 | } |
| 167 | - | 171 | + |
| 168 | # List examples if requested | 172 | # List examples if requested |
| 169 | if args.list: | 173 | if args.list: |
| 170 | print("\n" + "=" * 60) | 174 | print("\n" + "=" * 60) |
| @@ -175,7 +179,7 @@ Examples: | |||
| 175 | print(f" name: {ex_info['name']}") | 179 | print(f" name: {ex_info['name']}") |
| 176 | print(f" description: {ex_info['description']}\n") | 180 | print(f" description: {ex_info['description']}\n") |
| 177 | return | 181 | return |
| 178 | - | 182 | + |
| 179 | # Validate example ID if provided | 183 | # Validate example ID if provided |
| 180 | if args.example_id is not None: | 184 | if args.example_id is not None: |
| 181 | if args.example_id not in examples: | 185 | if args.example_id not in examples: |
| @@ -183,22 +187,22 @@ Examples: | |||
| 183 | print(f"Valid example IDs are: {', '.join(map(str, sorted(examples.keys())))}") | 187 | print(f"Valid example IDs are: {', '.join(map(str, sorted(examples.keys())))}") |
| 184 | print("\nUse --list to see all available examples.") | 188 | print("\nUse --list to see all available examples.") |
| 185 | sys.exit(1) | 189 | sys.exit(1) |
| 186 | - | 190 | + |
| 187 | print("\n" + "=" * 60) | 191 | print("\n" + "=" * 60) |
| 188 | print("PyPTO add_scalar_loop_dyn_axis Example") | 192 | print("PyPTO add_scalar_loop_dyn_axis Example") |
| 189 | print("=" * 60 + "\n") | 193 | print("=" * 60 + "\n") |
| 190 | - | 194 | + |
| 191 | # Get and validate device ID (needed for NPU examples) | 195 | # Get and validate device ID (needed for NPU examples) |
| 192 | device_id = None | 196 | device_id = None |
| 193 | examples_to_run = [] | 197 | examples_to_run = [] |
| 194 | - | 198 | + |
| 195 | if args.example_id is not None: | 199 | if args.example_id is not None: |
| 196 | # Run single example | 200 | # Run single example |
| 197 | examples_to_run = [(args.example_id, examples[args.example_id])] | 201 | examples_to_run = [(args.example_id, examples[args.example_id])] |
| 198 | else: | 202 | else: |
| 199 | # Run all examples | 203 | # Run all examples |
| 200 | examples_to_run = list(examples.items()) | 204 | examples_to_run = list(examples.items()) |
| 201 | - | 205 | + |
| 202 | if args.run_mode == "npu": | 206 | if args.run_mode == "npu": |
| 203 | device_id = get_device_id() | 207 | device_id = get_device_id() |
| 204 | if device_id is None: | 208 | if device_id is None: |
| @@ -207,21 +211,21 @@ Examples: | |||
| 207 | torch.npu.set_device(device_id) | 211 | torch.npu.set_device(device_id) |
| 208 | print("Running examples that require NPU hardware...") | 212 | print("Running examples that require NPU hardware...") |
| 209 | print("(Make sure CANN environment is configured and NPU is available)\n") | 213 | print("(Make sure CANN environment is configured and NPU is available)\n") |
| 210 | - | 214 | + |
| 211 | try: | 215 | try: |
| 212 | for ex_id, ex_info in examples_to_run: | 216 | for ex_id, ex_info in examples_to_run: |
| 213 | print(f"Running Example {ex_id}: {ex_info['name']}") | 217 | print(f"Running Example {ex_id}: {ex_info['name']}") |
| 214 | ex_info['function'](device_id, args.run_mode) | 218 | ex_info['function'](device_id, args.run_mode) |
| 215 | - | 219 | + |
| 216 | if len(examples_to_run) > 1: | 220 | if len(examples_to_run) > 1: |
| 217 | print("=" * 60) | 221 | print("=" * 60) |
| 218 | print("All add_scalar_loop_dyn_axis tests passed!") | 222 | print("All add_scalar_loop_dyn_axis tests passed!") |
| 219 | print("=" * 60) | 223 | print("=" * 60) |
| 220 | - | 224 | + |
| 221 | except Exception as e: | 225 | except Exception as e: |
| 222 | print(f"\nError: {e}") | 226 | print(f"\nError: {e}") |
| 223 | raise | 227 | raise |
| 224 | 228 | ||
| 225 | 229 | ||
| 226 | if __name__ == "__main__": | 230 | if __name__ == "__main__": |
| 227 | - main() | 231 | + main() |
| @@ -29,7 +29,7 @@ from typing import Optional | |||
| 29 | def get_device_id(): | 29 | def get_device_id(): |
| 30 | """ | 30 | """ |
| 31 | Get and validate TILE_FWK_DEVICE_ID from environment variable. | 31 | Get and validate TILE_FWK_DEVICE_ID from environment variable. |
| 32 | - | 32 | + |
| 33 | Returns: | 33 | Returns: |
| 34 | int: The device ID if valid, None otherwise. | 34 | int: The device ID if valid, None otherwise. |
| 35 | """ | 35 | """ |
| @@ -39,7 +39,7 @@ def get_device_id(): | |||
| 39 | print("Please set it before running this example:") | 39 | print("Please set it before running this example:") |
| 40 | print(" export TILE_FWK_DEVICE_ID=0") | 40 | print(" export TILE_FWK_DEVICE_ID=0") |
| 41 | return None | 41 | return None |
| 42 | - | 42 | + |
| 43 | try: | 43 | try: |
| 44 | device_id = int(os.environ['TILE_FWK_DEVICE_ID']) | 44 | device_id = int(os.environ['TILE_FWK_DEVICE_ID']) |
| 45 | return device_id | 45 | return device_id |
| @@ -77,7 +77,7 @@ def scaled_dot_product_attention_golden( | |||
| 77 | return output | 77 | return output |
| 78 | 78 | ||
| 79 | 79 | ||
| 80 | -def scaled_dot_product_attention_core(q: pypto.Tensor, k: pypto.Tensor, v: pypto.Tensor, | 80 | +def scaled_dot_product_attention_core(q: pypto.Tensor, k: pypto.Tensor, v: pypto.Tensor, |
| 81 | scale: float, dtype: pypto.DataType) -> pypto.Tensor: | 81 | scale: float, dtype: pypto.DataType) -> pypto.Tensor: |
| 82 | k_t = pypto.transpose(k, 2, 3) | 82 | k_t = pypto.transpose(k, 2, 3) |
| 83 | scores = pypto.matmul(q, k_t, out_dtype=dtype) | 83 | scores = pypto.matmul(q, k_t, out_dtype=dtype) |
| @@ -90,10 +90,10 @@ def scaled_dot_product_attention_core(q: pypto.Tensor, k: pypto.Tensor, v: pypto | |||
| 90 | @pypto.jit( | 90 | @pypto.jit( |
| 91 | host_options={"only_codegen": True}, | 91 | host_options={"only_codegen": True}, |
| 92 | ) | 92 | ) |
| 93 | -def scaled_dot_product_attention_kernel_npu(q: torch.Tensor, k: torch.Tensor, | 93 | +def scaled_dot_product_attention_kernel_npu(q: pypto.Tensor, k: pypto.Tensor, |
| 94 | - v: torch.Tensor, y: torch.Tensor, params: torch.Size, | 94 | + v: pypto.Tensor, y: pypto.Tensor, params: torch.Size, |
| 95 | config: AttentionConfig): | 95 | config: AttentionConfig): |
| 96 | - """Scaled dot-product attention with dynamic batch and sequence lengths.""" | 96 | + """Scaled dot-product attention with dynamic batch and sequence lengths.""" |
| 97 | batch_size, num_heads, seq_len, head_dim = params | 97 | batch_size, num_heads, seq_len, head_dim = params |
| 98 | 98 | ||
| 99 | # Calculate scale | 99 | # Calculate scale |
| @@ -106,7 +106,7 @@ def scaled_dot_product_attention_kernel_npu(q: torch.Tensor, k: torch.Tensor, | |||
| 106 | q_view = q[bs_idx * view_shape[0]:(bs_idx+1) * view_shape[0], ...] | 106 | q_view = q[bs_idx * view_shape[0]:(bs_idx+1) * view_shape[0], ...] |
| 107 | k_view = k[bs_idx * view_shape[0]:(bs_idx+1) * view_shape[0], ...] | 107 | k_view = k[bs_idx * view_shape[0]:(bs_idx+1) * view_shape[0], ...] |
| 108 | v_view = v[bs_idx * view_shape[0]:(bs_idx+1) * view_shape[0], ...] | 108 | v_view = v[bs_idx * view_shape[0]:(bs_idx+1) * view_shape[0], ...] |
| 109 | - pypto.set_vec_tile_shapes(1, 8, 16, 64) | 109 | + pypto.set_vec_tile_shapes(1, 8, 16, 64) |
| 110 | res = scaled_dot_product_attention_core(q_view, k_view, v_view, scale, config.dtype) | 110 | res = scaled_dot_product_attention_core(q_view, k_view, v_view, scale, config.dtype) |
| 111 | y[bs_idx * view_shape[0]:, ...] = res | 111 | y[bs_idx * view_shape[0]:, ...] = res |
| 112 | 112 | ||
| @@ -115,10 +115,10 @@ def scaled_dot_product_attention_kernel_npu(q: torch.Tensor, k: torch.Tensor, | |||
| 115 | host_options={"only_codegen": True}, | 115 | host_options={"only_codegen": True}, |
| 116 | runtime_options={"run_mode": 1} | 116 | runtime_options={"run_mode": 1} |
| 117 | ) | 117 | ) |
| 118 | -def scaled_dot_product_attention_kernel_sim(q: torch.Tensor, k: torch.Tensor, | 118 | +def scaled_dot_product_attention_kernel_sim(q: pypto.Tensor, k: pypto.Tensor, |
| 119 | - v: torch.Tensor, y: torch.Tensor, params: torch.Size, | 119 | + v: pypto.Tensor, y: pypto.Tensor, params: torch.Size, |
| 120 | config: AttentionConfig): | 120 | config: AttentionConfig): |
| 121 | - """Scaled dot-product attention with dynamic batch and sequence lengths.""" | 121 | + """Scaled dot-product attention with dynamic batch and sequence lengths.""" |
| 122 | batch_size, num_heads, seq_len, head_dim = params | 122 | batch_size, num_heads, seq_len, head_dim = params |
| 123 | 123 | ||
| 124 | # Calculate scale | 124 | # Calculate scale |
| @@ -131,14 +131,14 @@ def scaled_dot_product_attention_kernel_sim(q: torch.Tensor, k: torch.Tensor, | |||
| 131 | q_view = q[bs_idx * view_shape[0]:(bs_idx+1) * view_shape[0], ...] | 131 | q_view = q[bs_idx * view_shape[0]:(bs_idx+1) * view_shape[0], ...] |
| 132 | k_view = k[bs_idx * view_shape[0]:(bs_idx+1) * view_shape[0], ...] | 132 | k_view = k[bs_idx * view_shape[0]:(bs_idx+1) * view_shape[0], ...] |
| 133 | v_view = v[bs_idx * view_shape[0]:(bs_idx+1) * view_shape[0], ...] | 133 | v_view = v[bs_idx * view_shape[0]:(bs_idx+1) * view_shape[0], ...] |
| 134 | - pypto.set_vec_tile_shapes(1, 8, 16, 64) | 134 | + pypto.set_vec_tile_shapes(1, 8, 16, 64) |
| 135 | res = scaled_dot_product_attention_core(q_view, k_view, v_view, scale, config.dtype) | 135 | res = scaled_dot_product_attention_core(q_view, k_view, v_view, scale, config.dtype) |
| 136 | y[bs_idx * view_shape[0]:, ...] = res | 136 | y[bs_idx * view_shape[0]:, ...] = res |
| 137 | print("finish kernel") | 137 | print("finish kernel") |
| 138 | - | 138 | + |
| 139 | - | 139 | + |
| 140 | -def scaled_dot_product_attention(q: torch.Tensor, k: torch.Tensor, | 140 | +def scaled_dot_product_attention(q: torch.Tensor, k: torch.Tensor, |
| 141 | - v: torch.Tensor, params: torch.Size, | 141 | + v: torch.Tensor, params: torch.Size, |
| 142 | config: AttentionConfig, run_mode: str = "npu", | 142 | config: AttentionConfig, run_mode: str = "npu", |
| 143 | dynamic: bool = True) -> torch.Tensor: | 143 | dynamic: bool = True) -> torch.Tensor: |
| 144 | y = torch.empty_like(q) | 144 | y = torch.empty_like(q) |
| @@ -167,11 +167,11 @@ def test_dynamic_shape(device_id = None, run_mode: str = "npu", dynamic: bool = | |||
| 167 | print("=" * 60) | 167 | print("=" * 60) |
| 168 | print("Test: Dynamic Scaled Dot-Product Attention") | 168 | print("Test: Dynamic Scaled Dot-Product Attention") |
| 169 | print("=" * 60) | 169 | print("=" * 60) |
| 170 | - | 170 | + |
| 171 | device = f'npu:{device_id}' if (run_mode == "npu" and device_id is not None) else 'cpu' | 171 | device = f'npu:{device_id}' if (run_mode == "npu" and device_id is not None) else 'cpu' |
| 172 | - | 172 | + |
| 173 | num_heads, head_dim = 8, 64 | 173 | num_heads, head_dim = 8, 64 |
| 174 | - | 174 | + |
| 175 | # Test with different batch sizes and sequence lengths (dynamic shapes) | 175 | # Test with different batch sizes and sequence lengths (dynamic shapes) |
| 176 | test_cases = [ | 176 | test_cases = [ |
| 177 | (2, 16, 16), | 177 | (2, 16, 16), |
| @@ -180,13 +180,13 @@ def test_dynamic_shape(device_id = None, run_mode: str = "npu", dynamic: bool = | |||
| 180 | ] | 180 | ] |
| 181 | for batch_size, seq_len_q, seq_len_kv in test_cases: | 181 | for batch_size, seq_len_q, seq_len_kv in test_cases: |
| 182 | dtype = torch.float32 | 182 | dtype = torch.float32 |
| 183 | - q_torch = torch.randn(batch_size, num_heads, seq_len_q, head_dim, | 183 | + q_torch = torch.randn(batch_size, num_heads, seq_len_q, head_dim, |
| 184 | dtype=dtype, device=device) | 184 | dtype=dtype, device=device) |
| 185 | - k_torch = torch.randn(batch_size, num_heads, seq_len_kv, head_dim, | 185 | + k_torch = torch.randn(batch_size, num_heads, seq_len_kv, head_dim, |
| 186 | dtype=dtype, device=device) | 186 | dtype=dtype, device=device) |
| 187 | - v_torch = torch.randn(batch_size, num_heads, seq_len_kv, head_dim, | 187 | + v_torch = torch.randn(batch_size, num_heads, seq_len_kv, head_dim, |
| 188 | dtype=dtype, device=device) | 188 | dtype=dtype, device=device) |
| 189 | - config = AttentionConfig(num_heads=num_heads, head_dim=head_dim, | 189 | + config = AttentionConfig(num_heads=num_heads, head_dim=head_dim, |
| 190 | dtype=pypto.DT_FP32, use_dynamic_shape=True) | 190 | dtype=pypto.DT_FP32, use_dynamic_shape=True) |
| 191 | params = q_torch.shape | 191 | params = q_torch.shape |
| 192 | # Execute | 192 | # Execute |
| @@ -197,21 +197,21 @@ def test_dynamic_shape(device_id = None, run_mode: str = "npu", dynamic: bool = | |||
| 197 | # Verify | 197 | # Verify |
| 198 | scale = 1.0 / (head_dim ** 0.5) | 198 | scale = 1.0 / (head_dim ** 0.5) |
| 199 | golden = scaled_dot_product_attention_golden(q_torch, k_torch, v_torch, scale).cpu() | 199 | golden = scaled_dot_product_attention_golden(q_torch, k_torch, v_torch, scale).cpu() |
| 200 | - | 200 | + |
| 201 | max_diff = (out_torch - golden).abs().max().item() | 201 | max_diff = (out_torch - golden).abs().max().item() |
| 202 | if run_mode == "npu": | 202 | if run_mode == "npu": |
| 203 | print(f"Batch={batch_size}, SeqQ={seq_len_q}, SeqKV={seq_len_kv}, Max diff: {max_diff:.6f}") | 203 | print(f"Batch={batch_size}, SeqQ={seq_len_q}, SeqKV={seq_len_kv}, Max diff: {max_diff:.6f}") |
| 204 | assert_allclose(np.array(out_torch), np.array(golden), rtol=3e-3, atol=3e-3) | 204 | assert_allclose(np.array(out_torch), np.array(golden), rtol=3e-3, atol=3e-3) |
| 205 | print(f"Input shape: {q_torch.shape}") | 205 | print(f"Input shape: {q_torch.shape}") |
| 206 | print(f"Output shape: {out_torch.shape}") | 206 | print(f"Output shape: {out_torch.shape}") |
| 207 | - | 207 | + |
| 208 | print("✓ Attention (dynamic) passed for the test case") | 208 | print("✓ Attention (dynamic) passed for the test case") |
| 209 | print() | 209 | print() |
| 210 | 210 | ||
| 211 | 211 | ||
| 212 | def main(): | 212 | def main(): |
| 213 | """Run dynamic examples. | 213 | """Run dynamic examples. |
| 214 | - | 214 | + |
| 215 | Usage: | 215 | Usage: |
| 216 | python dynamic.py # Run all examples | 216 | python dynamic.py # Run all examples |
| 217 | python dynamic.py 1 # Run example 1 only | 217 | python dynamic.py 1 # Run example 1 only |
| @@ -247,9 +247,9 @@ Examples: | |||
| 247 | choices=["npu", "sim"], | 247 | choices=["npu", "sim"], |
| 248 | help='Run mode, such as npu/sim etc.' | 248 | help='Run mode, such as npu/sim etc.' |
| 249 | ) | 249 | ) |
| 250 | - | 250 | + |
| 251 | args = parser.parse_args() | 251 | args = parser.parse_args() |
| 252 | - | 252 | + |
| 253 | # Define available examples | 253 | # Define available examples |
| 254 | examples = { | 254 | examples = { |
| 255 | 'dynamic_shape::test_dynamic_shape': { | 255 | 'dynamic_shape::test_dynamic_shape': { |
| @@ -258,7 +258,7 @@ Examples: | |||
| 258 | 'function': test_dynamic_shape, | 258 | 'function': test_dynamic_shape, |
| 259 | } | 259 | } |
| 260 | } | 260 | } |
| 261 | - | 261 | + |
| 262 | # List examples if requested | 262 | # List examples if requested |
| 263 | if args.list: | 263 | if args.list: |
| 264 | print("\n" + "=" * 60) | 264 | print("\n" + "=" * 60) |
| @@ -269,7 +269,7 @@ Examples: | |||
| 269 | print(f" name: {ex_info['name']}") | 269 | print(f" name: {ex_info['name']}") |
| 270 | print(f" description: {ex_info['description']}\n") | 270 | print(f" description: {ex_info['description']}\n") |
| 271 | return | 271 | return |
| 272 | - | 272 | + |
| 273 | # Validate example ID if provided | 273 | # Validate example ID if provided |
| 274 | if args.example_id is not None: | 274 | if args.example_id is not None: |
| 275 | if args.example_id not in examples: | 275 | if args.example_id not in examples: |
| @@ -277,22 +277,22 @@ Examples: | |||
| 277 | print(f"Valid example IDs are: {', '.join(map(str, sorted(examples.keys())))}") | 277 | print(f"Valid example IDs are: {', '.join(map(str, sorted(examples.keys())))}") |
| 278 | print("\nUse --list to see all available examples.") | 278 | print("\nUse --list to see all available examples.") |
| 279 | sys.exit(1) | 279 | sys.exit(1) |
| 280 | - | 280 | + |
| 281 | print("\n" + "=" * 60) | 281 | print("\n" + "=" * 60) |
| 282 | print("PyPTO Dynamic Function Examples") | 282 | print("PyPTO Dynamic Function Examples") |
| 283 | print("=" * 60 + "\n") | 283 | print("=" * 60 + "\n") |
| 284 | - | 284 | + |
| 285 | # Get and validate device ID (needed for NPU examples) | 285 | # Get and validate device ID (needed for NPU examples) |
| 286 | device_id = None | 286 | device_id = None |
| 287 | examples_to_run = [] | 287 | examples_to_run = [] |
| 288 | - | 288 | + |
| 289 | if args.example_id is not None: | 289 | if args.example_id is not None: |
| 290 | # Run single example | 290 | # Run single example |
| 291 | examples_to_run = [(args.example_id, examples[args.example_id])] | 291 | examples_to_run = [(args.example_id, examples[args.example_id])] |
| 292 | else: | 292 | else: |
| 293 | # Run all examples | 293 | # Run all examples |
| 294 | examples_to_run = list(examples.items()) | 294 | examples_to_run = list(examples.items()) |
| 295 | - | 295 | + |
| 296 | if args.run_mode == "npu": | 296 | if args.run_mode == "npu": |
| 297 | device_id = get_device_id() | 297 | device_id = get_device_id() |
| 298 | if device_id is None: | 298 | if device_id is None: |
| @@ -301,21 +301,21 @@ Examples: | |||
| 301 | torch.npu.set_device(device_id) | 301 | torch.npu.set_device(device_id) |
| 302 | print("Running examples that require NPU hardware...") | 302 | print("Running examples that require NPU hardware...") |
| 303 | print("(Make sure CANN environment is configured and NPU is available)\n") | 303 | print("(Make sure CANN environment is configured and NPU is available)\n") |
| 304 | - | 304 | + |
| 305 | try: | 305 | try: |
| 306 | for ex_id, ex_info in examples_to_run: | 306 | for ex_id, ex_info in examples_to_run: |
| 307 | print(f"Running Example {ex_id}: {ex_info['name']}") | 307 | print(f"Running Example {ex_id}: {ex_info['name']}") |
| 308 | ex_info['function'](device_id, args.run_mode) | 308 | ex_info['function'](device_id, args.run_mode) |
| 309 | - | 309 | + |
| 310 | if len(examples_to_run) > 1: | 310 | if len(examples_to_run) > 1: |
| 311 | print("=" * 60) | 311 | print("=" * 60) |
| 312 | print("All dynamic tests passed!") | 312 | print("All dynamic tests passed!") |
| 313 | print("=" * 60) | 313 | print("=" * 60) |
| 314 | - | 314 | + |
| 315 | except Exception as e: | 315 | except Exception as e: |
| 316 | print(f"\nError: {e}") | 316 | print(f"\nError: {e}") |
| 317 | raise | 317 | raise |
| 318 | 318 | ||
| 319 | 319 | ||
| 320 | if __name__ == "__main__": | 320 | if __name__ == "__main__": |
| 321 | - main() | 321 | + main() |
| @@ -29,7 +29,7 @@ from typing import Optional, Tuple | |||
| 29 | def get_device_id(): | 29 | def get_device_id(): |
| 30 | """ | 30 | """ |
| 31 | Get and validate TILE_FWK_DEVICE_ID from environment variable. | 31 | Get and validate TILE_FWK_DEVICE_ID from environment variable. |
| 32 | - | 32 | + |
| 33 | Returns: | 33 | Returns: |
| 34 | int: The device ID if valid, None otherwise. | 34 | int: The device ID if valid, None otherwise. |
| 35 | """ | 35 | """ |
| @@ -39,7 +39,7 @@ def get_device_id(): | |||
| 39 | print("Please set it before running this example:") | 39 | print("Please set it before running this example:") |
| 40 | print(" export TILE_FWK_DEVICE_ID=0") | 40 | print(" export TILE_FWK_DEVICE_ID=0") |
| 41 | return None | 41 | return None |
| 42 | - | 42 | + |
| 43 | try: | 43 | try: |
| 44 | device_id = int(os.environ['TILE_FWK_DEVICE_ID']) | 44 | device_id = int(os.environ['TILE_FWK_DEVICE_ID']) |
| 45 | return device_id | 45 | return device_id |
| @@ -89,10 +89,10 @@ def scaled_dot_product_attention_core(q: pypto.Tensor, k: pypto.Tensor, v: pypto | |||
| 89 | @pypto.jit( | 89 | @pypto.jit( |
| 90 | host_options={"only_codegen": True}, | 90 | host_options={"only_codegen": True}, |
| 91 | ) | 91 | ) |
| 92 | -def scaled_dot_product_attention_kernel_npu(q: torch.Tensor, y: torch.Tensor, k: torch.Tensor, | 92 | +def scaled_dot_product_attention_kernel_npu(q: pypto.Tensor, y: pypto.Tensor, k: pypto.Tensor, |
| 93 | - v: torch.Tensor, params: torch.Size, | 93 | + v: pypto.Tensor, params: torch.Size, |
| 94 | config: AttentionConfig) -> None: | 94 | config: AttentionConfig) -> None: |
| 95 | - """Scaled dot-product attention with dynamic batch and sequence lengths.""" | 95 | + """Scaled dot-product attention with dynamic batch and sequence lengths.""" |
| 96 | batch_size, num_heads, seq_len, head_dim = params | 96 | batch_size, num_heads, seq_len, head_dim = params |
| 97 | 97 | ||
| 98 | # Calculate scale | 98 | # Calculate scale |
| @@ -107,7 +107,7 @@ def scaled_dot_product_attention_kernel_npu(q: torch.Tensor, y: torch.Tensor, k: | |||
| 107 | q_view = q[bs_idx * view_shape[0]:(bs_idx+1) * view_shape[0], ...] | 107 | q_view = q[bs_idx * view_shape[0]:(bs_idx+1) * view_shape[0], ...] |
| 108 | k_view = k[bs_idx * view_shape[0]:(bs_idx+1) * view_shape[0], ...] | 108 | k_view = k[bs_idx * view_shape[0]:(bs_idx+1) * view_shape[0], ...] |
| 109 | v_view = v[bs_idx * view_shape[0]:(bs_idx+1) * view_shape[0], ...] | 109 | v_view = v[bs_idx * view_shape[0]:(bs_idx+1) * view_shape[0], ...] |
| 110 | - pypto.set_vec_tile_shapes(1, 8, 16, 64) | 110 | + pypto.set_vec_tile_shapes(1, 8, 16, 64) |
| 111 | res = scaled_dot_product_attention_core(q_view, k_view, v_view) | 111 | res = scaled_dot_product_attention_core(q_view, k_view, v_view) |
| 112 | y[bs_idx * view_shape[0]:, ...] = res | 112 | y[bs_idx * view_shape[0]:, ...] = res |
| 113 | 113 | ||
| @@ -116,10 +116,10 @@ def scaled_dot_product_attention_kernel_npu(q: torch.Tensor, y: torch.Tensor, k: | |||
| 116 | host_options={"only_codegen": True}, | 116 | host_options={"only_codegen": True}, |
| 117 | runtime_options={"run_mode": 1} | 117 | runtime_options={"run_mode": 1} |
| 118 | ) | 118 | ) |
| 119 | -def scaled_dot_product_attention_kernel_sim(q: torch.Tensor, y: torch.Tensor, k: torch.Tensor, | 119 | +def scaled_dot_product_attention_kernel_sim(q: pypto.Tensor, y: pypto.Tensor, k: pypto.Tensor, |
| 120 | - v: torch.Tensor, params: torch.Size, | 120 | + v: pypto.Tensor, params: torch.Size, |
| 121 | config: AttentionConfig) -> None: | 121 | config: AttentionConfig) -> None: |
| 122 | - """Scaled dot-product attention with dynamic batch and sequence lengths.""" | 122 | + """Scaled dot-product attention with dynamic batch and sequence lengths.""" |
| 123 | batch_size, num_heads, seq_len, head_dim = params | 123 | batch_size, num_heads, seq_len, head_dim = params |
| 124 | 124 | ||
| 125 | # Calculate scale | 125 | # Calculate scale |
| @@ -134,13 +134,13 @@ def scaled_dot_product_attention_kernel_sim(q: torch.Tensor, y: torch.Tensor, k: | |||
| 134 | q_view = q[bs_idx * view_shape[0]:(bs_idx+1) * view_shape[0], ...] | 134 | q_view = q[bs_idx * view_shape[0]:(bs_idx+1) * view_shape[0], ...] |
| 135 | k_view = k[bs_idx * view_shape[0]:(bs_idx+1) * view_shape[0], ...] | 135 | k_view = k[bs_idx * view_shape[0]:(bs_idx+1) * view_shape[0], ...] |
| 136 | v_view = v[bs_idx * view_shape[0]:(bs_idx+1) * view_shape[0], ...] | 136 | v_view = v[bs_idx * view_shape[0]:(bs_idx+1) * view_shape[0], ...] |
| 137 | - pypto.set_vec_tile_shapes(1, 8, 16, 64) | 137 | + pypto.set_vec_tile_shapes(1, 8, 16, 64) |
| 138 | res = scaled_dot_product_attention_core(q_view, k_view, v_view) | 138 | res = scaled_dot_product_attention_core(q_view, k_view, v_view) |
| 139 | y[bs_idx * view_shape[0]:, ...] = res | 139 | y[bs_idx * view_shape[0]:, ...] = res |
| 140 | 140 | ||
| 141 | 141 | ||
| 142 | -def scaled_dot_product_attention(q: torch.Tensor, k: torch.Tensor, | 142 | +def scaled_dot_product_attention(q: torch.Tensor, k: torch.Tensor, |
| 143 | - v: torch.Tensor, params: torch.Size, | 143 | + v: torch.Tensor, params: torch.Size, |
| 144 | config: AttentionConfig, run_mode: str = "npu", | 144 | config: AttentionConfig, run_mode: str = "npu", |
| 145 | dynamic: bool = True) -> torch.Tensor: | 145 | dynamic: bool = True) -> torch.Tensor: |
| 146 | y = torch.empty_like(q) | 146 | y = torch.empty_like(q) |
| @@ -170,48 +170,48 @@ def test_unordered_input_attention(device_id = None, run_mode: str = "npu", dyna | |||
| 170 | print("=" * 60) | 170 | print("=" * 60) |
| 171 | print("Test: kenel_unordered_input Scaled Dot-Product Attention") | 171 | print("Test: kenel_unordered_input Scaled Dot-Product Attention") |
| 172 | print("=" * 60) | 172 | print("=" * 60) |
| 173 | - | 173 | + |
| 174 | device = f'npu:{device_id}' if (run_mode == "npu" and device_id is not None) else 'cpu' | 174 | device = f'npu:{device_id}' if (run_mode == "npu" and device_id is not None) else 'cpu' |
| 175 | - | 175 | + |
| 176 | num_heads, head_dim = 8, 64 | 176 | num_heads, head_dim = 8, 64 |
| 177 | - | 177 | + |
| 178 | batch_size, seq_len_q, seq_len_kv = 8, 64, 64 | 178 | batch_size, seq_len_q, seq_len_kv = 8, 64, 64 |
| 179 | dtype = torch.float32 | 179 | dtype = torch.float32 |
| 180 | - q_torch = torch.randn(batch_size, num_heads, seq_len_q, head_dim, | 180 | + q_torch = torch.randn(batch_size, num_heads, seq_len_q, head_dim, |
| 181 | dtype=dtype, device=device) | 181 | dtype=dtype, device=device) |
| 182 | - k_torch = torch.randn(batch_size, num_heads, seq_len_kv, head_dim, | 182 | + k_torch = torch.randn(batch_size, num_heads, seq_len_kv, head_dim, |
| 183 | dtype=dtype, device=device) | 183 | dtype=dtype, device=device) |
| 184 | - v_torch = torch.randn(batch_size, num_heads, seq_len_kv, head_dim, | 184 | + v_torch = torch.randn(batch_size, num_heads, seq_len_kv, head_dim, |
| 185 | dtype=dtype, device=device) | 185 | dtype=dtype, device=device) |
| 186 | - config = AttentionConfig(num_heads=num_heads, head_dim=head_dim, | 186 | + config = AttentionConfig(num_heads=num_heads, head_dim=head_dim, |
| 187 | dtype=pypto.DT_FP32, use_dynamic_shape=True) | 187 | dtype=pypto.DT_FP32, use_dynamic_shape=True) |
| 188 | params = q_torch.shape | 188 | params = q_torch.shape |
| 189 | # Execute | 189 | # Execute |
| 190 | out_torch = scaled_dot_product_attention(q_torch, k_torch, v_torch, params, config, run_mode, dynamic).cpu() | 190 | out_torch = scaled_dot_product_attention(q_torch, k_torch, v_torch, params, config, run_mode, dynamic).cpu() |
| 191 | - | 191 | + |
| 192 | # Verify | 192 | # Verify |
| 193 | scale = 1.0 / (head_dim ** 0.5) | 193 | scale = 1.0 / (head_dim ** 0.5) |
| 194 | golden = scaled_dot_product_attention_golden(q_torch, k_torch, v_torch, scale).cpu() | 194 | golden = scaled_dot_product_attention_golden(q_torch, k_torch, v_torch, scale).cpu() |
| 195 | - | 195 | + |
| 196 | print(f"Batch={batch_size}, SeqQ={seq_len_q}, SeqKV={seq_len_kv}") | 196 | print(f"Batch={batch_size}, SeqQ={seq_len_q}, SeqKV={seq_len_kv}") |
| 197 | print(f"Input shape: {q_torch.shape}") | 197 | print(f"Input shape: {q_torch.shape}") |
| 198 | print(f"Output shape: {out_torch.shape}") | 198 | print(f"Output shape: {out_torch.shape}") |
| 199 | if run_mode == "npu": | 199 | if run_mode == "npu": |
| 200 | assert_allclose(np.array(out_torch), np.array(golden), rtol=3e-3, atol=3e-3) | 200 | assert_allclose(np.array(out_torch), np.array(golden), rtol=3e-3, atol=3e-3) |
| 201 | - | 201 | + |
| 202 | print("✓ Attention (kenel_unordered_input) passed for the test case") | 202 | print("✓ Attention (kenel_unordered_input) passed for the test case") |
| 203 | print() | 203 | print() |
| 204 | 204 | ||
| 205 | 205 | ||
| 206 | @pypto.jit | 206 | @pypto.jit |
| 207 | -def op_unordered_input_kernel_npu(a: torch.Tensor, y1: torch.Tensor, y2: torch.Tensor, b: torch.Tensor) -> None: | 207 | +def op_unordered_input_kernel_npu(a: pypto.Tensor, y1: pypto.Tensor, y2: pypto.Tensor, b: pypto.Tensor) -> None: |
| 208 | pypto.set_vec_tile_shapes(16, 16) | 208 | pypto.set_vec_tile_shapes(16, 16) |
| 209 | y1[:] = a + b | 209 | y1[:] = a + b |
| 210 | y2[:] = a * b | 210 | y2[:] = a * b |
| 211 | 211 | ||
| 212 | 212 | ||
| 213 | @pypto.jit(runtime_options={"run_mode": 1}) | 213 | @pypto.jit(runtime_options={"run_mode": 1}) |
| 214 | -def op_unordered_input_kernel_sim(a: torch.Tensor, y1: torch.Tensor, y2: torch.Tensor, b: torch.Tensor) -> None: | 214 | +def op_unordered_input_kernel_sim(a: pypto.Tensor, y1: pypto.Tensor, y2: pypto.Tensor, b: pypto.Tensor) -> None: |
| 215 | pypto.set_vec_tile_shapes(16, 16) | 215 | pypto.set_vec_tile_shapes(16, 16) |
| 216 | y1[:] = a + b | 216 | y1[:] = a + b |
| 217 | y2[:] = a * b | 217 | y2[:] = a * b |
| @@ -246,9 +246,9 @@ def test_unordered_input_op(device_id = None, run_mode: str = "npu", dynamic: bo | |||
| 246 | print("=" * 60) | 246 | print("=" * 60) |
| 247 | print("Test: OP with kenel_unordered_input") | 247 | print("Test: OP with kenel_unordered_input") |
| 248 | print("=" * 60) | 248 | print("=" * 60) |
| 249 | - | 249 | + |
| 250 | device = f'npu:{device_id}' if (run_mode == "npu" and device_id is not None) else 'cpu' | 250 | device = f'npu:{device_id}' if (run_mode == "npu" and device_id is not None) else 'cpu' |
| 251 | - | 251 | + |
| 252 | shape = (3, 2) | 252 | shape = (3, 2) |
| 253 | dtype = torch.float | 253 | dtype = torch.float |
| 254 | a = torch.rand(shape, dtype=dtype, device=device) | 254 | a = torch.rand(shape, dtype=dtype, device=device) |
| @@ -259,22 +259,22 @@ def test_unordered_input_op(device_id = None, run_mode: str = "npu", dynamic: bo | |||
| 259 | # Verify | 259 | # Verify |
| 260 | golden1 = torch.add(a, b).cpu() | 260 | golden1 = torch.add(a, b).cpu() |
| 261 | golden2 = torch.mul(a, b).cpu() | 261 | golden2 = torch.mul(a, b).cpu() |
| 262 | - | 262 | + |
| 263 | if run_mode == "npu": | 263 | if run_mode == "npu": |
| 264 | assert_allclose(np.array(y1), np.array(golden1), rtol=1e-3, atol=1e-3) | 264 | assert_allclose(np.array(y1), np.array(golden1), rtol=1e-3, atol=1e-3) |
| 265 | assert_allclose(np.array(y2), np.array(golden2), rtol=1e-3, atol=1e-3) | 265 | assert_allclose(np.array(y2), np.array(golden2), rtol=1e-3, atol=1e-3) |
| 266 | print(f"Output1: {y1}") | 266 | print(f"Output1: {y1}") |
| 267 | print(f"Expected1: {golden1}") | 267 | print(f"Expected1: {golden1}") |
| 268 | print(f"Output2: {y2}") | 268 | print(f"Output2: {y2}") |
| 269 | - print(f"Expected2: {golden2}") | 269 | + print(f"Expected2: {golden2}") |
| 270 | - | 270 | + |
| 271 | print("✓ OP with kenel_unordered_input passed for the test case") | 271 | print("✓ OP with kenel_unordered_input passed for the test case") |
| 272 | print() | 272 | print() |
| 273 | 273 | ||
| 274 | 274 | ||
| 275 | def main(): | 275 | def main(): |
| 276 | """Run dynamic examples. | 276 | """Run dynamic examples. |
| 277 | - | 277 | + |
| 278 | Usage: | 278 | Usage: |
| 279 | python dynamic.py # Run all examples | 279 | python dynamic.py # Run all examples |
| 280 | python dynamic.py 1 # Run example 1 only | 280 | python dynamic.py 1 # Run example 1 only |
| @@ -310,9 +310,9 @@ Examples: | |||
| 310 | choices=["npu", "sim"], | 310 | choices=["npu", "sim"], |
| 311 | help='Run mode, such as npu/sim etc.' | 311 | help='Run mode, such as npu/sim etc.' |
| 312 | ) | 312 | ) |
| 313 | - | 313 | + |
| 314 | args = parser.parse_args() | 314 | args = parser.parse_args() |
| 315 | - | 315 | + |
| 316 | # Define available examples | 316 | # Define available examples |
| 317 | examples = { | 317 | examples = { |
| 318 | 'unordered_input_attention::test_unordered_input_attention': { | 318 | 'unordered_input_attention::test_unordered_input_attention': { |
| @@ -328,7 +328,7 @@ Examples: | |||
| 328 | 'requires_npu': True | 328 | 'requires_npu': True |
| 329 | } | 329 | } |
| 330 | } | 330 | } |
| 331 | - | 331 | + |
| 332 | # List examples if requested | 332 | # List examples if requested |
| 333 | if args.list: | 333 | if args.list: |
| 334 | print("\n" + "=" * 60) | 334 | print("\n" + "=" * 60) |
| @@ -339,7 +339,7 @@ Examples: | |||
| 339 | print(f" name: {ex_info['name']}") | 339 | print(f" name: {ex_info['name']}") |
| 340 | print(f" description: {ex_info['description']}\n") | 340 | print(f" description: {ex_info['description']}\n") |
| 341 | return | 341 | return |
| 342 | - | 342 | + |
| 343 | # Validate example ID if provided | 343 | # Validate example ID if provided |
| 344 | if args.example_id is not None: | 344 | if args.example_id is not None: |
| 345 | if args.example_id not in examples: | 345 | if args.example_id not in examples: |
| @@ -347,22 +347,22 @@ Examples: | |||
| 347 | print(f"Valid example IDs are: {', '.join(map(str, sorted(examples.keys())))}") | 347 | print(f"Valid example IDs are: {', '.join(map(str, sorted(examples.keys())))}") |
| 348 | print("\nUse --list to see all available examples.") | 348 | print("\nUse --list to see all available examples.") |
| 349 | sys.exit(1) | 349 | sys.exit(1) |
| 350 | - | 350 | + |
| 351 | print("\n" + "=" * 60) | 351 | print("\n" + "=" * 60) |
| 352 | print("PyPTO Dynamic Function Examples") | 352 | print("PyPTO Dynamic Function Examples") |
| 353 | print("=" * 60 + "\n") | 353 | print("=" * 60 + "\n") |
| 354 | - | 354 | + |
| 355 | # Get and validate device ID (needed for NPU examples) | 355 | # Get and validate device ID (needed for NPU examples) |
| 356 | device_id = None | 356 | device_id = None |
| 357 | examples_to_run = [] | 357 | examples_to_run = [] |
| 358 | - | 358 | + |
| 359 | if args.example_id is not None: | 359 | if args.example_id is not None: |
| 360 | # Run single example | 360 | # Run single example |
| 361 | examples_to_run = [(args.example_id, examples[args.example_id])] | 361 | examples_to_run = [(args.example_id, examples[args.example_id])] |
| 362 | else: | 362 | else: |
| 363 | # Run all examples | 363 | # Run all examples |
| 364 | examples_to_run = list(examples.items()) | 364 | examples_to_run = list(examples.items()) |
| 365 | - | 365 | + |
| 366 | if args.run_mode == "npu": | 366 | if args.run_mode == "npu": |
| 367 | device_id = get_device_id() | 367 | device_id = get_device_id() |
| 368 | if device_id is None: | 368 | if device_id is None: |
| @@ -371,21 +371,21 @@ Examples: | |||
| 371 | torch.npu.set_device(device_id) | 371 | torch.npu.set_device(device_id) |
| 372 | print("Running examples that require NPU hardware...") | 372 | print("Running examples that require NPU hardware...") |
| 373 | print("(Make sure CANN environment is configured and NPU is available)\n") | 373 | print("(Make sure CANN environment is configured and NPU is available)\n") |
| 374 | - | 374 | + |
| 375 | try: | 375 | try: |
| 376 | for ex_id, ex_info in examples_to_run: | 376 | for ex_id, ex_info in examples_to_run: |
| 377 | print(f"Running Example {ex_id}: {ex_info['name']}") | 377 | print(f"Running Example {ex_id}: {ex_info['name']}") |
| 378 | ex_info['function'](device_id, args.run_mode) | 378 | ex_info['function'](device_id, args.run_mode) |
| 379 | - | 379 | + |
| 380 | if len(examples_to_run) > 1: | 380 | if len(examples_to_run) > 1: |
| 381 | print("=" * 60) | 381 | print("=" * 60) |
| 382 | print("All kenel_unordered_input tests passed!") | 382 | print("All kenel_unordered_input tests passed!") |
| 383 | print("=" * 60) | 383 | print("=" * 60) |
| 384 | - | 384 | + |
| 385 | except Exception as e: | 385 | except Exception as e: |
| 386 | print(f"\nError: {e}") | 386 | print(f"\nError: {e}") |
| 387 | raise | 387 | raise |
| 388 | 388 | ||
| 389 | 389 | ||
| 390 | if __name__ == "__main__": | 390 | if __name__ == "__main__": |
| 391 | - main() | 391 | + main() |
| @@ -47,7 +47,7 @@ def ceil_div(a, b): | |||
| 47 | return (a + b - 1) // b | 47 | return (a + b - 1) // b |
| 48 | 48 | ||
| 49 | 49 | ||
| 50 | -def gelu_activation_core(x: pypto.tensor) -> pypto.tensor: | 50 | +def gelu_activation_core(x: pypto.Tensor) -> pypto.Tensor: |
| 51 | """ | 51 | """ |
| 52 | GELU activation function: x * 0.5 * (1 + erf(x / sqrt(2))) | 52 | GELU activation function: x * 0.5 * (1 + erf(x / sqrt(2))) |
| 53 | 53 | ||
| @@ -55,12 +55,12 @@ def gelu_activation_core(x: pypto.tensor) -> pypto.tensor: | |||
| 55 | 55 | ||
| 56 | Parameters | 56 | Parameters |
| 57 | ---------- | 57 | ---------- |
| 58 | - x : pypto.tensor | 58 | + x : pypto.Tensor |
| 59 | Input tensor | 59 | Input tensor |
| 60 | 60 | ||
| 61 | Returns | 61 | Returns |
| 62 | ------- | 62 | ------- |
| 63 | - pypto.tensor | 63 | + pypto.Tensor |
| 64 | GELU activated tensor | 64 | GELU activated tensor |
| 65 | """ | 65 | """ |
| 66 | pypto.set_vec_tile_shapes(*x.shape[:2] if len(x.shape) >= 2 else (32, 128)) | 66 | pypto.set_vec_tile_shapes(*x.shape[:2] if len(x.shape) >= 2 else (32, 128)) |
| @@ -79,16 +79,16 @@ def gelu_activation_core(x: pypto.tensor) -> pypto.tensor: | |||
| 79 | return pypto.mul(x, sigmoid) | 79 | return pypto.mul(x, sigmoid) |
| 80 | 80 | ||
| 81 | 81 | ||
| 82 | -def swiglu_activation_core(gate: pypto.tensor, up: pypto.tensor) -> pypto.tensor: | 82 | +def swiglu_activation_core(gate: pypto.Tensor, up: pypto.Tensor) -> pypto.Tensor: |
| 83 | """ | 83 | """ |
| 84 | SwiGLU activation function: Swish(gate) * up | 84 | SwiGLU activation function: Swish(gate) * up |
| 85 | where Swish(x) = x * sigmoid(x) | 85 | where Swish(x) = x * sigmoid(x) |
| 86 | 86 | ||
| 87 | Parameters | 87 | Parameters |
| 88 | ---------- | 88 | ---------- |
| 89 | - gate : pypto.tensor | 89 | + gate : pypto.Tensor |
| 90 | Gate tensor | 90 | Gate tensor |
| 91 | - up : pypto.tensor | 91 | + up : pypto.Tensor |
| 92 | Up projection tensor | 92 | Up projection tensor |
| 93 | 93 | ||
| 94 | Returns | 94 | Returns |
| @@ -110,13 +110,13 @@ def swiglu_activation_core(gate: pypto.tensor, up: pypto.tensor) -> pypto.tensor | |||
| 110 | return pypto.mul(swish, up) | 110 | return pypto.mul(swish, up) |
| 111 | 111 | ||
| 112 | 112 | ||
| 113 | -def relu_activation_core(x: pypto.tensor) -> pypto.tensor: | 113 | +def relu_activation_core(x: pypto.Tensor) -> pypto.Tensor: |
| 114 | """ | 114 | """ |
| 115 | ReLU activation function: max(0, x) | 115 | ReLU activation function: max(0, x) |
| 116 | 116 | ||
| 117 | Parameters | 117 | Parameters |
| 118 | ---------- | 118 | ---------- |
| 119 | - x : pypto.tensor | 119 | + x : pypto.Tensor |
| 120 | Input tensor | 120 | Input tensor |
| 121 | 121 | ||
| 122 | Returns | 122 | Returns |
| @@ -131,11 +131,11 @@ def relu_activation_core(x: pypto.tensor) -> pypto.tensor: | |||
| 131 | 131 | ||
| 132 | @pypto.jit | 132 | @pypto.jit |
| 133 | def ffn_static_swiglu_kernel_npu( | 133 | def ffn_static_swiglu_kernel_npu( |
| 134 | - hidden_states: pypto.tensor, | 134 | + hidden_states: pypto.Tensor, |
| 135 | - gate_proj_weight: pypto.tensor, | 135 | + gate_proj_weight: pypto.Tensor, |
| 136 | - up_proj_weight: pypto.tensor, | 136 | + up_proj_weight: pypto.Tensor, |
| 137 | - down_proj_weight: pypto.tensor, | 137 | + down_proj_weight: pypto.Tensor, |
| 138 | - output: pypto.tensor, | 138 | + output: pypto.Tensor, |
| 139 | config: FFNConfig | 139 | config: FFNConfig |
| 140 | ): | 140 | ): |
| 141 | """ | 141 | """ |
| @@ -147,15 +147,15 @@ def ffn_static_swiglu_kernel_npu( | |||
| 147 | 147 | ||
| 148 | Parameters | 148 | Parameters |
| 149 | ---------- | 149 | ---------- |
| 150 | - hidden_states : pypto.tensor | 150 | + hidden_states : pypto.Tensor |
| 151 | Input tensor of shape [batch_size, hidden_size] | 151 | Input tensor of shape [batch_size, hidden_size] |
| 152 | - gate_proj_weight : pypto.tensor | 152 | + gate_proj_weight : pypto.Tensor |
| 153 | Gate projection weight of shape [hidden_size, intermediate_size] | 153 | Gate projection weight of shape [hidden_size, intermediate_size] |
| 154 | - up_proj_weight : pypto.tensor | 154 | + up_proj_weight : pypto.Tensor |
| 155 | Up projection weight of shape [hidden_size, intermediate_size] (for SwiGLU) | 155 | Up projection weight of shape [hidden_size, intermediate_size] (for SwiGLU) |
| 156 | - down_proj_weight : pypto.tensor | 156 | + down_proj_weight : pypto.Tensor |
| 157 | Down projection weight of shape [intermediate_size, hidden_size] | 157 | Down projection weight of shape [intermediate_size, hidden_size] |
| 158 | - output : pypto.tensor | 158 | + output : pypto.Tensor |
| 159 | Output tensor of shape [batch_size, hidden_size] | 159 | Output tensor of shape [batch_size, hidden_size] |
| 160 | config : FFNConfig | 160 | config : FFNConfig |
| 161 | FFN configuration | 161 | FFN configuration |
| @@ -195,11 +195,11 @@ def ffn_static_swiglu_kernel_npu( | |||
| 195 | 195 | ||
| 196 | @pypto.jit(runtime_options={"run_mode" : 1}) | 196 | @pypto.jit(runtime_options={"run_mode" : 1}) |
| 197 | def ffn_static_swiglu_kernel_sim( | 197 | def ffn_static_swiglu_kernel_sim( |
| 198 | - hidden_states: pypto.tensor, | 198 | + hidden_states: pypto.Tensor, |
| 199 | - gate_proj_weight: pypto.tensor, | 199 | + gate_proj_weight: pypto.Tensor, |
| 200 | - up_proj_weight: pypto.tensor, | 200 | + up_proj_weight: pypto.Tensor, |
| 201 | - down_proj_weight: pypto.tensor, | 201 | + down_proj_weight: pypto.Tensor, |
| 202 | - output: pypto.tensor, | 202 | + output: pypto.Tensor, |
| 203 | config: FFNConfig | 203 | config: FFNConfig |
| 204 | ): | 204 | ): |
| 205 | """ | 205 | """ |
| @@ -211,15 +211,15 @@ def ffn_static_swiglu_kernel_sim( | |||
| 211 | 211 | ||
| 212 | Parameters | 212 | Parameters |
| 213 | ---------- | 213 | ---------- |
| 214 | - hidden_states : pypto.tensor | 214 | + hidden_states : pypto.Tensor |
| 215 | Input tensor of shape [batch_size, hidden_size] | 215 | Input tensor of shape [batch_size, hidden_size] |
| 216 | - gate_proj_weight : pypto.tensor | 216 | + gate_proj_weight : pypto.Tensor |
| 217 | Gate projection weight of shape [hidden_size, intermediate_size] | 217 | Gate projection weight of shape [hidden_size, intermediate_size] |
| 218 | - up_proj_weight : pypto.tensor | 218 | + up_proj_weight : pypto.Tensor |
| 219 | Up projection weight of shape [hidden_size, intermediate_size] (for SwiGLU) | 219 | Up projection weight of shape [hidden_size, intermediate_size] (for SwiGLU) |
| 220 | - down_proj_weight : pypto.tensor | 220 | + down_proj_weight : pypto.Tensor |
| 221 | Down projection weight of shape [intermediate_size, hidden_size] | 221 | Down projection weight of shape [intermediate_size, hidden_size] |
| 222 | - output : pypto.tensor | 222 | + output : pypto.Tensor |
| 223 | Output tensor of shape [batch_size, hidden_size] | 223 | Output tensor of shape [batch_size, hidden_size] |
| 224 | config : FFNConfig | 224 | config : FFNConfig |
| 225 | FFN configuration | 225 | FFN configuration |
| @@ -255,15 +255,14 @@ def ffn_static_swiglu_kernel_sim( | |||
| 255 | [config.cube_tile_shape[2], config.cube_tile_shape[2]] | 255 | [config.cube_tile_shape[2], config.cube_tile_shape[2]] |
| 256 | ) | 256 | ) |
| 257 | pypto.set_matrix_size({batch_size, intermediate_size, hidden_size}) | 257 | pypto.set_matrix_size({batch_size, intermediate_size, hidden_size}) |
| 258 | - output[:] = pypto.matmul(activated, down_proj_weight, output.dtype, b_trans=False) | 258 | + output[:] = pypto.matmul(activated, down_proj_weight, output.dtype, b_trans=False) |
| 259 | 259 | ||
| 260 | @pypto.jit | 260 | @pypto.jit |
| 261 | def ffn_static_gule_kernel_npu( | 261 | def ffn_static_gule_kernel_npu( |
| 262 | - hidden_states: pypto.tensor, | 262 | + hidden_states: pypto.Tensor, |
| 263 | - gate_proj_weight: pypto.tensor, | 263 | + gate_proj_weight: pypto.Tensor, |
| 264 | - # up_proj_weight: pypto.tensor, | 264 | + down_proj_weight: pypto.Tensor, |
| 265 | - down_proj_weight: pypto.tensor, | 265 | + output: pypto.Tensor, |
| 266 | - output: pypto.tensor, | ||
| 267 | config: FFNConfig | 266 | config: FFNConfig |
| 268 | ): | 267 | ): |
| 269 | """ | 268 | """ |
| @@ -275,15 +274,13 @@ def ffn_static_gule_kernel_npu( | |||
| 275 | 274 | ||
| 276 | Parameters | 275 | Parameters |
| 277 | ---------- | 276 | ---------- |
| 278 | - hidden_states : pypto.tensor | 277 | + hidden_states : pypto.Tensor |
| 279 | Input tensor of shape [batch_size, hidden_size] | 278 | Input tensor of shape [batch_size, hidden_size] |
| 280 | - gate_proj_weight : pypto.tensor | 279 | + gate_proj_weight : pypto.Tensor |
| 281 | Gate projection weight of shape [hidden_size, intermediate_size] | 280 | Gate projection weight of shape [hidden_size, intermediate_size] |
| 282 | - up_proj_weight : pypto.tensor | 281 | + down_proj_weight : pypto.Tensor |
| 283 | - Up projection weight of shape [hidden_size, intermediate_size] (for SwiGLU) | ||
| 284 | - down_proj_weight : pypto.tensor | ||
| 285 | Down projection weight of shape [intermediate_size, hidden_size] | 282 | Down projection weight of shape [intermediate_size, hidden_size] |
| 286 | - output : pypto.tensor | 283 | + output : pypto.Tensor |
| 287 | Output tensor of shape [batch_size, hidden_size] | 284 | Output tensor of shape [batch_size, hidden_size] |
| 288 | config : FFNConfig | 285 | config : FFNConfig |
| 289 | FFN configuration | 286 | FFN configuration |
| @@ -303,7 +300,7 @@ def ffn_static_gule_kernel_npu( | |||
| 303 | 300 | ||
| 304 | # Gate projection: [batch_size, hidden_size] @ [hidden_size, intermediate_size] | 301 | # Gate projection: [batch_size, hidden_size] @ [hidden_size, intermediate_size] |
| 305 | gate = pypto.matmul(hidden_states, gate_proj_weight, config.dtype) | 302 | gate = pypto.matmul(hidden_states, gate_proj_weight, config.dtype) |
| 306 | - | 303 | + |
| 307 | if config.activation == "gelu": | 304 | if config.activation == "gelu": |
| 308 | # GELU activation | 305 | # GELU activation |
| 309 | pypto.set_vec_tile_shapes(*config.vec_tile_shape) | 306 | pypto.set_vec_tile_shapes(*config.vec_tile_shape) |
| @@ -322,11 +319,10 @@ def ffn_static_gule_kernel_npu( | |||
| 322 | 319 | ||
| 323 | @pypto.jit(runtime_options={"run_mode" : 1}) | 320 | @pypto.jit(runtime_options={"run_mode" : 1}) |
| 324 | def ffn_static_gule_kernel_sim( | 321 | def ffn_static_gule_kernel_sim( |
| 325 | - hidden_states: pypto.tensor, | 322 | + hidden_states: pypto.Tensor, |
| 326 | - gate_proj_weight: pypto.tensor, | 323 | + gate_proj_weight: pypto.Tensor, |
| 327 | - # up_proj_weight: pypto.tensor, | 324 | + down_proj_weight: pypto.Tensor, |
| 328 | - down_proj_weight: pypto.tensor, | 325 | + output: pypto.Tensor, |
| 329 | - output: pypto.tensor, | ||
| 330 | config: FFNConfig | 326 | config: FFNConfig |
| 331 | ): | 327 | ): |
| 332 | """ | 328 | """ |
| @@ -338,15 +334,13 @@ def ffn_static_gule_kernel_sim( | |||
| 338 | 334 | ||
| 339 | Parameters | 335 | Parameters |
| 340 | ---------- | 336 | ---------- |
| 341 | - hidden_states : pypto.tensor | 337 | + hidden_states : pypto.Tensor |
| 342 | Input tensor of shape [batch_size, hidden_size] | 338 | Input tensor of shape [batch_size, hidden_size] |
| 343 | - gate_proj_weight : pypto.tensor | 339 | + gate_proj_weight : pypto.Tensor |
| 344 | Gate projection weight of shape [hidden_size, intermediate_size] | 340 | Gate projection weight of shape [hidden_size, intermediate_size] |
| 345 | - up_proj_weight : pypto.tensor | 341 | + down_proj_weight : pypto.Tensor |
| 346 | - Up projection weight of shape [hidden_size, intermediate_size] (for SwiGLU) | ||
| 347 | - down_proj_weight : pypto.tensor | ||
| 348 | Down projection weight of shape [intermediate_size, hidden_size] | 342 | Down projection weight of shape [intermediate_size, hidden_size] |
| 349 | - output : pypto.tensor | 343 | + output : pypto.Tensor |
| 350 | Output tensor of shape [batch_size, hidden_size] | 344 | Output tensor of shape [batch_size, hidden_size] |
| 351 | config : FFNConfig | 345 | config : FFNConfig |
| 352 | FFN configuration | 346 | FFN configuration |
| @@ -366,7 +360,7 @@ def ffn_static_gule_kernel_sim( | |||
| 366 | 360 | ||
| 367 | # Gate projection: [batch_size, hidden_size] @ [hidden_size, intermediate_size] | 361 | # Gate projection: [batch_size, hidden_size] @ [hidden_size, intermediate_size] |
| 368 | gate = pypto.matmul(hidden_states, gate_proj_weight, config.dtype) | 362 | gate = pypto.matmul(hidden_states, gate_proj_weight, config.dtype) |
| 369 | - | 363 | + |
| 370 | if config.activation == "gelu": | 364 | if config.activation == "gelu": |
| 371 | # GELU activation | 365 | # GELU activation |
| 372 | pypto.set_vec_tile_shapes(*config.vec_tile_shape) | 366 | pypto.set_vec_tile_shapes(*config.vec_tile_shape) |
| @@ -385,10 +379,10 @@ def ffn_static_gule_kernel_sim( | |||
| 385 | 379 | ||
| 386 | @pypto.jit | 380 | @pypto.jit |
| 387 | def ffn_static_relu_kernel_npu( | 381 | def ffn_static_relu_kernel_npu( |
| 388 | - hidden_states: pypto.tensor, | 382 | + hidden_states: pypto.Tensor, |
| 389 | - gate_proj_weight: pypto.tensor, | 383 | + gate_proj_weight: pypto.Tensor, |
| 390 | - down_proj_weight: pypto.tensor, | 384 | + down_proj_weight: pypto.Tensor, |
| 391 | - output: pypto.tensor, | 385 | + output: pypto.Tensor, |
| 392 | config: FFNConfig | 386 | config: FFNConfig |
| 393 | ): | 387 | ): |
| 394 | """ | 388 | """ |
| @@ -400,15 +394,15 @@ def ffn_static_relu_kernel_npu( | |||
| 400 | 394 | ||
| 401 | Parameters | 395 | Parameters |
| 402 | ---------- | 396 | ---------- |
| 403 | - hidden_states : pypto.tensor | 397 | + hidden_states : pypto.Tensor |
| 404 | Input tensor of shape [batch_size, hidden_size] | 398 | Input tensor of shape [batch_size, hidden_size] |
| 405 | - gate_proj_weight : pypto.tensor | 399 | + gate_proj_weight : pypto.Tensor |
| 406 | Gate projection weight of shape [hidden_size, intermediate_size] | 400 | Gate projection weight of shape [hidden_size, intermediate_size] |
| 407 | - up_proj_weight : pypto.tensor | 401 | + up_proj_weight : pypto.Tensor |
| 408 | Up projection weight of shape [hidden_size, intermediate_size] (for SwiGLU) | 402 | Up projection weight of shape [hidden_size, intermediate_size] (for SwiGLU) |
| 409 | - down_proj_weight : pypto.tensor | 403 | + down_proj_weight : pypto.Tensor |
| 410 | Down projection weight of shape [intermediate_size, hidden_size] | 404 | Down projection weight of shape [intermediate_size, hidden_size] |
| 411 | - output : pypto.tensor | 405 | + output : pypto.Tensor |
| 412 | Output tensor of shape [batch_size, hidden_size] | 406 | Output tensor of shape [batch_size, hidden_size] |
| 413 | config : FFNConfig | 407 | config : FFNConfig |
| 414 | FFN configuration | 408 | FFN configuration |
| @@ -444,13 +438,13 @@ def ffn_static_relu_kernel_npu( | |||
| 444 | ) | 438 | ) |
| 445 | pypto.set_matrix_size({batch_size, intermediate_size, hidden_size}) | 439 | pypto.set_matrix_size({batch_size, intermediate_size, hidden_size}) |
| 446 | output[:] = pypto.matmul(activated, down_proj_weight, output.dtype, b_trans=False) | 440 | output[:] = pypto.matmul(activated, down_proj_weight, output.dtype, b_trans=False) |
| 447 | - | 441 | + |
| 448 | @pypto.jit(runtime_options={"run_mode" : 1}) | 442 | @pypto.jit(runtime_options={"run_mode" : 1}) |
| 449 | def ffn_static_relu_kernel_sim( | 443 | def ffn_static_relu_kernel_sim( |
| 450 | - hidden_states: pypto.tensor, | 444 | + hidden_states: pypto.Tensor, |
| 451 | - gate_proj_weight: pypto.tensor, | 445 | + gate_proj_weight: pypto.Tensor, |
| 452 | - down_proj_weight: pypto.tensor, | 446 | + down_proj_weight: pypto.Tensor, |
| 453 | - output: pypto.tensor, | 447 | + output: pypto.Tensor, |
| 454 | config: FFNConfig | 448 | config: FFNConfig |
| 455 | ): | 449 | ): |
| 456 | """ | 450 | """ |
| @@ -462,15 +456,15 @@ def ffn_static_relu_kernel_sim( | |||
| 462 | 456 | ||
| 463 | Parameters | 457 | Parameters |
| 464 | ---------- | 458 | ---------- |
| 465 | - hidden_states : pypto.tensor | 459 | + hidden_states : pypto.Tensor |
| 466 | Input tensor of shape [batch_size, hidden_size] | 460 | Input tensor of shape [batch_size, hidden_size] |
| 467 | - gate_proj_weight : pypto.tensor | 461 | + gate_proj_weight : pypto.Tensor |
| 468 | Gate projection weight of shape [hidden_size, intermediate_size] | 462 | Gate projection weight of shape [hidden_size, intermediate_size] |
| 469 | - up_proj_weight : pypto.tensor | 463 | + up_proj_weight : pypto.Tensor |
| 470 | Up projection weight of shape [hidden_size, intermediate_size] (for SwiGLU) | 464 | Up projection weight of shape [hidden_size, intermediate_size] (for SwiGLU) |
| 471 | - down_proj_weight : pypto.tensor | 465 | + down_proj_weight : pypto.Tensor |
| 472 | Down projection weight of shape [intermediate_size, hidden_size] | 466 | Down projection weight of shape [intermediate_size, hidden_size] |
| 473 | - output : pypto.tensor | 467 | + output : pypto.Tensor |
| 474 | Output tensor of shape [batch_size, hidden_size] | 468 | Output tensor of shape [batch_size, hidden_size] |
| 475 | config : FFNConfig | 469 | config : FFNConfig |
| 476 | FFN configuration | 470 | FFN configuration |
| @@ -509,10 +503,10 @@ def ffn_static_relu_kernel_sim( | |||
| 509 | 503 | ||
| 510 | @pypto.jit | 504 | @pypto.jit |
| 511 | def ffn_dynamic_gelu_kernel_npu( | 505 | def ffn_dynamic_gelu_kernel_npu( |
| 512 | - hidden_states: pypto.tensor, | 506 | + hidden_states: pypto.Tensor, |
| 513 | - gate_proj_weight: pypto.tensor, | 507 | + gate_proj_weight: pypto.Tensor, |
| 514 | - down_proj_weight: pypto.tensor, | 508 | + down_proj_weight: pypto.Tensor, |
| 515 | - output: pypto.tensor, | 509 | + output: pypto.Tensor, |
| 516 | config: FFNConfig | 510 | config: FFNConfig |
| 517 | ): | 511 | ): |
| 518 | """ | 512 | """ |
| @@ -522,15 +516,15 @@ def ffn_dynamic_gelu_kernel_npu( | |||
| 522 | 516 | ||
| 523 | Parameters | 517 | Parameters |
| 524 | ---------- | 518 | ---------- |
| 525 | - hidden_states : pypto.tensor | 519 | + hidden_states : pypto.Tensor |
| 526 | Input tensor with dynamic first dimension [batch_size, hidden_size] | 520 | Input tensor with dynamic first dimension [batch_size, hidden_size] |
| 527 | - gate_proj_weight : pypto.tensor | 521 | + gate_proj_weight : pypto.Tensor |
| 528 | Gate projection weight of shape [hidden_size, intermediate_size] | 522 | Gate projection weight of shape [hidden_size, intermediate_size] |
| 529 | - up_proj_weight : pypto.tensor | 523 | + up_proj_weight : pypto.Tensor |
| 530 | Up projection weight of shape [hidden_size, intermediate_size] (for SwiGLU) | 524 | Up projection weight of shape [hidden_size, intermediate_size] (for SwiGLU) |
| 531 | - down_proj_weight : pypto.tensor | 525 | + down_proj_weight : pypto.Tensor |
| 532 | Down projection weight of shape [intermediate_size, hidden_size] | 526 | Down projection weight of shape [intermediate_size, hidden_size] |
| 533 | - output : pypto.tensor | 527 | + output : pypto.Tensor |
| 534 | Output tensor with dynamic first dimension [batch_size, hidden_size] | 528 | Output tensor with dynamic first dimension [batch_size, hidden_size] |
| 535 | config : FFNConfig | 529 | config : FFNConfig |
| 536 | FFN configuration | 530 | FFN configuration |
| @@ -549,7 +543,7 @@ def ffn_dynamic_gelu_kernel_npu( | |||
| 549 | 543 | ||
| 550 | # Process in chunks | 544 | # Process in chunks |
| 551 | for idx in pypto.loop(0, num_iterations, 1, name="LOOP_FFN_BATCH", idx_name="idx"): | 545 | for idx in pypto.loop(0, num_iterations, 1, name="LOOP_FFN_BATCH", idx_name="idx"): |
| 552 | - | 546 | + |
| 553 | batch_offset = idx * basic_batch | 547 | batch_offset = idx * basic_batch |
| 554 | 548 | ||
| 555 | # View current batch chunk | 549 | # View current batch chunk |
| @@ -589,13 +583,13 @@ def ffn_dynamic_gelu_kernel_npu( | |||
| 589 | 583 | ||
| 590 | # Assemble result back to output | 584 | # Assemble result back to output |
| 591 | pypto.assemble(output_chunk, [batch_offset, 0], output) | 585 | pypto.assemble(output_chunk, [batch_offset, 0], output) |
| 592 | - | 586 | + |
| 593 | @pypto.jit(runtime_options={"run_mode" : 1}) | 587 | @pypto.jit(runtime_options={"run_mode" : 1}) |
| 594 | def ffn_dynamic_gelu_kernel_sim( | 588 | def ffn_dynamic_gelu_kernel_sim( |
| 595 | - hidden_states: pypto.tensor, | 589 | + hidden_states: pypto.Tensor, |
| 596 | - gate_proj_weight: pypto.tensor, | 590 | + gate_proj_weight: pypto.Tensor, |
| 597 | - down_proj_weight: pypto.tensor, | 591 | + down_proj_weight: pypto.Tensor, |
| 598 | - output: pypto.tensor, | 592 | + output: pypto.Tensor, |
| 599 | config: FFNConfig | 593 | config: FFNConfig |
| 600 | ): | 594 | ): |
| 601 | """ | 595 | """ |
| @@ -605,15 +599,15 @@ def ffn_dynamic_gelu_kernel_sim( | |||
| 605 | 599 | ||
| 606 | Parameters | 600 | Parameters |
| 607 | ---------- | 601 | ---------- |
| 608 | - hidden_states : pypto.tensor | 602 | + hidden_states : pypto.Tensor |
| 609 | Input tensor with dynamic first dimension [batch_size, hidden_size] | 603 | Input tensor with dynamic first dimension [batch_size, hidden_size] |
| 610 | - gate_proj_weight : pypto.tensor | 604 | + gate_proj_weight : pypto.Tensor |
| 611 | Gate projection weight of shape [hidden_size, intermediate_size] | 605 | Gate projection weight of shape [hidden_size, intermediate_size] |
| 612 | - up_proj_weight : pypto.tensor | 606 | + up_proj_weight : pypto.Tensor |
| 613 | Up projection weight of shape [hidden_size, intermediate_size] (for SwiGLU) | 607 | Up projection weight of shape [hidden_size, intermediate_size] (for SwiGLU) |
| 614 | - down_proj_weight : pypto.tensor | 608 | + down_proj_weight : pypto.Tensor |
| 615 | Down projection weight of shape [intermediate_size, hidden_size] | 609 | Down projection weight of shape [intermediate_size, hidden_size] |
| 616 | - output : pypto.tensor | 610 | + output : pypto.Tensor |
| 617 | Output tensor with dynamic first dimension [batch_size, hidden_size] | 611 | Output tensor with dynamic first dimension [batch_size, hidden_size] |
| 618 | config : FFNConfig | 612 | config : FFNConfig |
| 619 | FFN configuration | 613 | FFN configuration |
| @@ -632,7 +626,7 @@ def ffn_dynamic_gelu_kernel_sim( | |||
| 632 | 626 | ||
| 633 | # Process in chunks | 627 | # Process in chunks |
| 634 | for idx in pypto.loop(0, num_iterations, 1, name="LOOP_FFN_BATCH", idx_name="idx"): | 628 | for idx in pypto.loop(0, num_iterations, 1, name="LOOP_FFN_BATCH", idx_name="idx"): |
| 635 | - | 629 | + |
| 636 | batch_offset = idx * basic_batch | 630 | batch_offset = idx * basic_batch |
| 637 | 631 | ||
| 638 | # View current batch chunk | 632 | # View current batch chunk |
| @@ -671,4 +665,4 @@ def ffn_dynamic_gelu_kernel_sim( | |||
| 671 | output_chunk = pypto.matmul(activated, down_proj_weight, config.dtype, b_trans=False) | 665 | output_chunk = pypto.matmul(activated, down_proj_weight, config.dtype, b_trans=False) |
| 672 | 666 | ||
| 673 | # Assemble result back to output | 667 | # Assemble result back to output |
| 674 | - pypto.assemble(output_chunk, [batch_offset, 0], output) | 668 | + pypto.assemble(output_chunk, [batch_offset, 0], output) |
| @@ -81,7 +81,7 @@ def geglu_golden(gate: torch.Tensor, up: torch.Tensor) -> torch.Tensor: | |||
| 81 | 81 | ||
| 82 | 82 | ||
| 83 | @pypto.jit | 83 | @pypto.jit |
| 84 | -def silu_activation_kernel_npu(x: pypto.tensor, y: pypto.tensor) -> None: | 84 | +def silu_activation_kernel_npu(x: pypto.Tensor, y: pypto.Tensor) -> None: |
| 85 | """ | 85 | """ |
| 86 | SiLU (Swish) activation function: x * sigmoid(x) | 86 | SiLU (Swish) activation function: x * sigmoid(x) |
| 87 | 87 | ||
| @@ -92,12 +92,12 @@ def silu_activation_kernel_npu(x: pypto.tensor, y: pypto.tensor) -> None: | |||
| 92 | 92 | ||
| 93 | Parameters | 93 | Parameters |
| 94 | ---------- | 94 | ---------- |
| 95 | - x : pypto.tensor | 95 | + x : pypto.Tensor |
| 96 | Input tensor | 96 | Input tensor |
| 97 | 97 | ||
| 98 | Returns | 98 | Returns |
| 99 | ------- | 99 | ------- |
| 100 | - pypto.tensor | 100 | + pypto.Tensor |
| 101 | SiLU activated tensor | 101 | SiLU activated tensor |
| 102 | """ | 102 | """ |
| 103 | # Configure tiling based on input shape | 103 | # Configure tiling based on input shape |
| @@ -114,7 +114,7 @@ def silu_activation_kernel_npu(x: pypto.tensor, y: pypto.tensor) -> None: | |||
| 114 | 114 | ||
| 115 | 115 | ||
| 116 | @pypto.jit(runtime_options={"run_mode": 1}) | 116 | @pypto.jit(runtime_options={"run_mode": 1}) |
| 117 | -def silu_activation_kernel_sim(x: pypto.tensor, y: pypto.tensor) -> None: | 117 | +def silu_activation_kernel_sim(x: pypto.Tensor, y: pypto.Tensor) -> None: |
| 118 | """ | 118 | """ |
| 119 | SiLU (Swish) activation function: x * sigmoid(x) | 119 | SiLU (Swish) activation function: x * sigmoid(x) |
| 120 | 120 | ||
| @@ -125,12 +125,12 @@ def silu_activation_kernel_sim(x: pypto.tensor, y: pypto.tensor) -> None: | |||
| 125 | 125 | ||
| 126 | Parameters | 126 | Parameters |
| 127 | ---------- | 127 | ---------- |
| 128 | - x : pypto.tensor | 128 | + x : pypto.Tensor |
| 129 | Input tensor | 129 | Input tensor |
| 130 | 130 | ||
| 131 | Returns | 131 | Returns |
| 132 | ------- | 132 | ------- |
| 133 | - pypto.tensor | 133 | + pypto.Tensor |
| 134 | SiLU activated tensor | 134 | SiLU activated tensor |
| 135 | """ | 135 | """ |
| 136 | # Configure tiling based on input shape | 136 | # Configure tiling based on input shape |
| @@ -192,7 +192,7 @@ def test_silu(device_id = None, run_mode: str = "npu", dynamic: bool = False) -> | |||
| 192 | 192 | ||
| 193 | 193 | ||
| 194 | @pypto.jit | 194 | @pypto.jit |
| 195 | -def gelu_activation_kernel_npu(x: pypto.tensor, y: pypto.tensor) -> None: | 195 | +def gelu_activation_kernel_npu(x: pypto.Tensor, y: pypto.Tensor) -> None: |
| 196 | """ | 196 | """ |
| 197 | GELU (Gaussian Error Linear Unit) activation function. | 197 | GELU (Gaussian Error Linear Unit) activation function. |
| 198 | 198 | ||
| @@ -201,12 +201,12 @@ def gelu_activation_kernel_npu(x: pypto.tensor, y: pypto.tensor) -> None: | |||
| 201 | 201 | ||
| 202 | Parameters | 202 | Parameters |
| 203 | ---------- | 203 | ---------- |
| 204 | - x : pypto.tensor | 204 | + x : pypto.Tensor |
| 205 | Input tensor | 205 | Input tensor |
| 206 | 206 | ||
| 207 | Returns | 207 | Returns |
| 208 | ------- | 208 | ------- |
| 209 | - pypto.tensor | 209 | + pypto.Tensor |
| 210 | GELU activated tensor | 210 | GELU activated tensor |
| 211 | """ | 211 | """ |
| 212 | # Configure tiling | 212 | # Configure tiling |
| @@ -226,7 +226,7 @@ def gelu_activation_kernel_npu(x: pypto.tensor, y: pypto.tensor) -> None: | |||
| 226 | 226 | ||
| 227 | 227 | ||
| 228 | @pypto.jit(runtime_options={"run_mode": 1}) | 228 | @pypto.jit(runtime_options={"run_mode": 1}) |
| 229 | -def gelu_activation_kernel_sim(x: pypto.tensor, y: pypto.tensor) -> None: | 229 | +def gelu_activation_kernel_sim(x: pypto.Tensor, y: pypto.Tensor) -> None: |
| 230 | """ | 230 | """ |
| 231 | GELU (Gaussian Error Linear Unit) activation function. | 231 | GELU (Gaussian Error Linear Unit) activation function. |
| 232 | 232 | ||
| @@ -235,12 +235,12 @@ def gelu_activation_kernel_sim(x: pypto.tensor, y: pypto.tensor) -> None: | |||
| 235 | 235 | ||
| 236 | Parameters | 236 | Parameters |
| 237 | ---------- | 237 | ---------- |
| 238 | - x : pypto.tensor | 238 | + x : pypto.Tensor |
| 239 | Input tensor | 239 | Input tensor |
| 240 | 240 | ||
| 241 | Returns | 241 | Returns |
| 242 | ------- | 242 | ------- |
| 243 | - pypto.tensor | 243 | + pypto.Tensor |
| 244 | GELU activated tensor | 244 | GELU activated tensor |
| 245 | """ | 245 | """ |
| 246 | # Configure tiling | 246 | # Configure tiling |
| @@ -303,10 +303,10 @@ def test_gelu(device_id = None, run_mode: str = "npu", dynamic: bool = False) -> | |||
| 303 | assert max_diff < 1e-1, "Result mismatch!" | 303 | assert max_diff < 1e-1, "Result mismatch!" |
| 304 | print("✓ GELU passed") | 304 | print("✓ GELU passed") |
| 305 | print() | 305 | print() |
| 306 | - | 306 | + |
| 307 | 307 | ||
| 308 | @pypto.jit | 308 | @pypto.jit |
| 309 | -def swiglu_activation_kernel_npu(gate: pypto.tensor, up: pypto.tensor, y: pypto.tensor) -> None: | 309 | +def swiglu_activation_kernel_npu(gate: pypto.Tensor, up: pypto.Tensor, y: pypto.Tensor) -> None: |
| 310 | """ | 310 | """ |
| 311 | SwiGLU activation function: Swish(gate) * up | 311 | SwiGLU activation function: Swish(gate) * up |
| 312 | 312 | ||
| @@ -317,14 +317,14 @@ def swiglu_activation_kernel_npu(gate: pypto.tensor, up: pypto.tensor, y: pypto. | |||
| 317 | 317 | ||
| 318 | Parameters | 318 | Parameters |
| 319 | ---------- | 319 | ---------- |
| 320 | - gate : pypto.tensor | 320 | + gate : pypto.Tensor |
| 321 | Gate tensor | 321 | Gate tensor |
| 322 | - up : pypto.tensor | 322 | + up : pypto.Tensor |
| 323 | Up projection tensor | 323 | Up projection tensor |
| 324 | 324 | ||
| 325 | Returns | 325 | Returns |
| 326 | ------- | 326 | ------- |
| 327 | - pypto.tensor | 327 | + pypto.Tensor |
| 328 | SwiGLU activated tensor | 328 | SwiGLU activated tensor |
| 329 | """ | 329 | """ |
| 330 | # Configure tiling | 330 | # Configure tiling |
| @@ -344,7 +344,7 @@ def swiglu_activation_kernel_npu(gate: pypto.tensor, up: pypto.tensor, y: pypto. | |||
| 344 | 344 | ||
| 345 | 345 | ||
| 346 | @pypto.jit(runtime_options={"run_mode": 1}) | 346 | @pypto.jit(runtime_options={"run_mode": 1}) |
| 347 | -def swiglu_activation_kernel_sim(gate: pypto.tensor, up: pypto.tensor, y: pypto.tensor) -> None: | 347 | +def swiglu_activation_kernel_sim(gate: pypto.Tensor, up: pypto.Tensor, y: pypto.Tensor) -> None: |
| 348 | """ | 348 | """ |
| 349 | SwiGLU activation function: Swish(gate) * up | 349 | SwiGLU activation function: Swish(gate) * up |
| 350 | 350 | ||
| @@ -355,9 +355,9 @@ def swiglu_activation_kernel_sim(gate: pypto.tensor, up: pypto.tensor, y: pypto. | |||
| 355 | 355 | ||
| 356 | Parameters | 356 | Parameters |
| 357 | ---------- | 357 | ---------- |
| 358 | - gate : pypto.tensor | 358 | + gate : pypto.Tensor |
| 359 | Gate tensor | 359 | Gate tensor |
| 360 | - up : pypto.tensor | 360 | + up : pypto.Tensor |
| 361 | Up projection tensor | 361 | Up projection tensor |
| 362 | 362 | ||
| 363 | Returns | 363 | Returns |
| @@ -381,7 +381,8 @@ def swiglu_activation_kernel_sim(gate: pypto.tensor, up: pypto.tensor, y: pypto. | |||
| 381 | y[:] = swish * up | 381 | y[:] = swish * up |
| 382 | 382 | ||
| 383 | 383 | ||
| 384 | -def swiglu_activation(gate: pypto.tensor, up: pypto.tensor, run_mode: str = "npu", dynamic: bool = False) -> torch.Tensor: | 384 | +def swiglu_activation(gate: torch.Tensor, up: torch.Tensor, |
| 385 | + run_mode: str = "npu", dynamic: bool = False) -> torch.Tensor: | ||
| 385 | y = torch.empty_like(gate) | 386 | y = torch.empty_like(gate) |
| 386 | 387 | ||
| 387 | if dynamic: | 388 | if dynamic: |
| @@ -432,7 +433,7 @@ def test_swiglu(device_id = None, run_mode: str = "npu", dynamic: bool = False) | |||
| 432 | 433 | ||
| 433 | 434 | ||
| 434 | @pypto.jit | 435 | @pypto.jit |
| 435 | -def geglu_activation_kernel_npu(gate: pypto.tensor, up: pypto.tensor, y: pypto.tensor) -> None: | 436 | +def geglu_activation_kernel_npu(gate: pypto.Tensor, up: pypto.Tensor, y: pypto.Tensor) -> None: |
| 436 | """ | 437 | """ |
| 437 | GeGLU activation function: GELU(gate) * up | 438 | GeGLU activation function: GELU(gate) * up |
| 438 | 439 | ||
| @@ -443,14 +444,14 @@ def geglu_activation_kernel_npu(gate: pypto.tensor, up: pypto.tensor, y: pypto.t | |||
| 443 | 444 | ||
| 444 | Parameters | 445 | Parameters |
| 445 | ---------- | 446 | ---------- |
| 446 | - gate : pypto.tensor | 447 | + gate : pypto.Tensor |
| 447 | Gate tensor | 448 | Gate tensor |
| 448 | - up : pypto.tensor | 449 | + up : pypto.Tensor |
| 449 | Up projection tensor | 450 | Up projection tensor |
| 450 | 451 | ||
| 451 | Returns | 452 | Returns |
| 452 | ------- | 453 | ------- |
| 453 | - pypto.tensor | 454 | + pypto.Tensor |
| 454 | GeGLU activated tensor | 455 | GeGLU activated tensor |
| 455 | """ | 456 | """ |
| 456 | # Configure tiling | 457 | # Configure tiling |
| @@ -473,7 +474,7 @@ def geglu_activation_kernel_npu(gate: pypto.tensor, up: pypto.tensor, y: pypto.t | |||
| 473 | 474 | ||
| 474 | 475 | ||
| 475 | @pypto.jit(runtime_options={"run_mode": 1}) | 476 | @pypto.jit(runtime_options={"run_mode": 1}) |
| 476 | -def geglu_activation_kernel_sim(gate: pypto.tensor, up: pypto.tensor, y: pypto.tensor) -> None: | 477 | +def geglu_activation_kernel_sim(gate: pypto.Tensor, up: pypto.Tensor, y: pypto.Tensor) -> None: |
| 477 | """ | 478 | """ |
| 478 | GeGLU activation function: GELU(gate) * up | 479 | GeGLU activation function: GELU(gate) * up |
| 479 | 480 | ||
| @@ -484,9 +485,9 @@ def geglu_activation_kernel_sim(gate: pypto.tensor, up: pypto.tensor, y: pypto.t | |||
| 484 | 485 | ||
| 485 | Parameters | 486 | Parameters |
| 486 | ---------- | 487 | ---------- |
| 487 | - gate : pypto.tensor | 488 | + gate : pypto.Tensor |
| 488 | Gate tensor | 489 | Gate tensor |
| 489 | - up : pypto.tensor | 490 | + up : pypto.Tensor |
| 490 | Up projection tensor | 491 | Up projection tensor |
| 491 | 492 | ||
| 492 | Returns | 493 | Returns |
| @@ -513,7 +514,8 @@ def geglu_activation_kernel_sim(gate: pypto.tensor, up: pypto.tensor, y: pypto.t | |||
| 513 | y[:] = gelu_gate * up | 514 | y[:] = gelu_gate * up |
| 514 | 515 | ||
| 515 | 516 | ||
| 516 | -def geglu_activation(gate: pypto.tensor, up: pypto.tensor, run_mode: str = "npu", dynamic: bool = False) -> torch.Tensor: | 517 | +def geglu_activation(gate: torch.Tensor, up: torch.Tensor, |
| 518 | + run_mode: str = "npu", dynamic: bool = False) -> torch.Tensor: | ||
| 517 | y = torch.empty_like(gate) | 519 | y = torch.empty_like(gate) |
| 518 | 520 | ||
| 519 | if dynamic: | 521 | if dynamic: |
| @@ -31,7 +31,7 @@ from numpy.testing import assert_allclose | |||
| 31 | def get_device_id(): | 31 | def get_device_id(): |
| 32 | """ | 32 | """ |
| 33 | Get and validate TILE_FWK_DEVICE_ID from environment variable. | 33 | Get and validate TILE_FWK_DEVICE_ID from environment variable. |
| 34 | - | 34 | + |
| 35 | Returns: | 35 | Returns: |
| 36 | int: The device ID if valid, None otherwise. | 36 | int: The device ID if valid, None otherwise. |
| 37 | """ | 37 | """ |
| @@ -41,7 +41,7 @@ def get_device_id(): | |||
| 41 | print("Please set it before running this example:") | 41 | print("Please set it before running this example:") |
| 42 | print(" export TILE_FWK_DEVICE_ID=0") | 42 | print(" export TILE_FWK_DEVICE_ID=0") |
| 43 | return None | 43 | return None |
| 44 | - | 44 | + |
| 45 | try: | 45 | try: |
| 46 | device_id = int(os.environ['TILE_FWK_DEVICE_ID']) | 46 | device_id = int(os.environ['TILE_FWK_DEVICE_ID']) |
| 47 | return device_id | 47 | return device_id |
| @@ -53,12 +53,12 @@ def get_device_id(): | |||
| 53 | def softmax_core(x: pypto.Tensor) -> pypto.Tensor: | 53 | def softmax_core(x: pypto.Tensor) -> pypto.Tensor: |
| 54 | """ | 54 | """ |
| 55 | Core softmax computation: exp(x - max(x)) / sum(exp(x - max(x))). | 55 | Core softmax computation: exp(x - max(x)) / sum(exp(x - max(x))). |
| 56 | - | 56 | + |
| 57 | Parameters | 57 | Parameters |
| 58 | ---------- | 58 | ---------- |
| 59 | - input_tensor : pypto.tensor | 59 | + input_tensor : pypto.Tensor |
| 60 | Input tensor to apply softmax to | 60 | Input tensor to apply softmax to |
| 61 | - | 61 | + |
| 62 | Returns | 62 | Returns |
| 63 | ------- | 63 | ------- |
| 64 | pypto.tensor | 64 | pypto.tensor |
| @@ -151,7 +151,7 @@ def test_softmax(device_id = None, run_mode: str = "npu", dynamic: bool = True) | |||
| 151 | 151 | ||
| 152 | def main(): | 152 | def main(): |
| 153 | """Run softmax example. | 153 | """Run softmax example. |
| 154 | - | 154 | + |
| 155 | Usage: | 155 | Usage: |
| 156 | python softmax.py # Run example | 156 | python softmax.py # Run example |
| 157 | python softmax.py --list # List available examples | 157 | python softmax.py --list # List available examples |
| @@ -185,9 +185,9 @@ Examples: | |||
| 185 | choices=["npu", "sim"], | 185 | choices=["npu", "sim"], |
| 186 | help='Run mode, such as npu/sim etc.' | 186 | help='Run mode, such as npu/sim etc.' |
| 187 | ) | 187 | ) |
| 188 | - | 188 | + |
| 189 | args = parser.parse_args() | 189 | args = parser.parse_args() |
| 190 | - | 190 | + |
| 191 | # Define available examples | 191 | # Define available examples |
| 192 | examples = { | 192 | examples = { |
| 193 | "softmax::test_softmax": { | 193 | "softmax::test_softmax": { |
| @@ -196,7 +196,7 @@ Examples: | |||
| 196 | 'function': test_softmax | 196 | 'function': test_softmax |
| 197 | } | 197 | } |
| 198 | } | 198 | } |
| 199 | - | 199 | + |
| 200 | # List examples if requested | 200 | # List examples if requested |
| 201 | if args.list: | 201 | if args.list: |
| 202 | print("\n" + "=" * 60) | 202 | print("\n" + "=" * 60) |
| @@ -207,7 +207,7 @@ Examples: | |||
| 207 | print(f" name: {ex_info['name']}") | 207 | print(f" name: {ex_info['name']}") |
| 208 | print(f" description: {ex_info['description']}\n") | 208 | print(f" description: {ex_info['description']}\n") |
| 209 | return | 209 | return |
| 210 | - | 210 | + |
| 211 | # Validate example ID if provided | 211 | # Validate example ID if provided |
| 212 | if args.example_id is not None: | 212 | if args.example_id is not None: |
| 213 | if args.example_id not in examples: | 213 | if args.example_id not in examples: |
| @@ -215,7 +215,7 @@ Examples: | |||
| 215 | print(f"Valid example IDs are: {', '.join(map(str, sorted(examples.keys())))}") | 215 | print(f"Valid example IDs are: {', '.join(map(str, sorted(examples.keys())))}") |
| 216 | print("\nUse --list to see all available examples.") | 216 | print("\nUse --list to see all available examples.") |
| 217 | sys.exit(1) | 217 | sys.exit(1) |
| 218 | - | 218 | + |
| 219 | print("\n" + "=" * 60) | 219 | print("\n" + "=" * 60) |
| 220 | print("PyPTO Softmax Example") | 220 | print("PyPTO Softmax Example") |
| 221 | print("=" * 60 + "\n") | 221 | print("=" * 60 + "\n") |
| @@ -239,21 +239,21 @@ Examples: | |||
| 239 | torch.npu.set_device(device_id) | 239 | torch.npu.set_device(device_id) |
| 240 | print("Running examples that require NPU hardware...") | 240 | print("Running examples that require NPU hardware...") |
| 241 | print("(Make sure CANN environment is configured and NPU is available)\n") | 241 | print("(Make sure CANN environment is configured and NPU is available)\n") |
| 242 | - | 242 | + |
| 243 | try: | 243 | try: |
| 244 | for ex_id, ex_info in examples_to_run: | 244 | for ex_id, ex_info in examples_to_run: |
| 245 | print(f"Running Example {ex_id}: {ex_info['name']}") | 245 | print(f"Running Example {ex_id}: {ex_info['name']}") |
| 246 | ex_info['function'](device_id, args.run_mode) | 246 | ex_info['function'](device_id, args.run_mode) |
| 247 | - | 247 | + |
| 248 | if len(examples_to_run) > 1: | 248 | if len(examples_to_run) > 1: |
| 249 | print("=" * 60) | 249 | print("=" * 60) |
| 250 | print("All softmax tests passed!") | 250 | print("All softmax tests passed!") |
| 251 | print("=" * 60) | 251 | print("=" * 60) |
| 252 | - | 252 | + |
| 253 | except Exception as e: | 253 | except Exception as e: |
| 254 | print(f"\nError: {e}") | 254 | print(f"\nError: {e}") |
| 255 | raise | 255 | raise |
| 256 | 256 | ||
| 257 | 257 | ||
| 258 | if __name__ == "__main__": | 258 | if __name__ == "__main__": |
| 259 | - main() | 259 | + main() |
| @@ -34,7 +34,7 @@ from torch._subclasses.fake_tensor import FakeTensor | |||
| 34 | def get_device_id(): | 34 | def get_device_id(): |
| 35 | """ | 35 | """ |
| 36 | Get and validate TILE_FWK_DEVICE_ID from environment variable. | 36 | Get and validate TILE_FWK_DEVICE_ID from environment variable. |
| 37 | - | 37 | + |
| 38 | Returns: | 38 | Returns: |
| 39 | int: The device ID if valid, None otherwise. | 39 | int: The device ID if valid, None otherwise. |
| 40 | """ | 40 | """ |
| @@ -44,7 +44,7 @@ def get_device_id(): | |||
| 44 | print("Please set it before running this example:") | 44 | print("Please set it before running this example:") |
| 45 | print(" export TILE_FWK_DEVICE_ID=0") | 45 | print(" export TILE_FWK_DEVICE_ID=0") |
| 46 | return None | 46 | return None |
| 47 | - | 47 | + |
| 48 | try: | 48 | try: |
| 49 | device_id = int(os.environ['TILE_FWK_DEVICE_ID']) | 49 | device_id = int(os.environ['TILE_FWK_DEVICE_ID']) |
| 50 | return device_id | 50 | return device_id |
| @@ -56,12 +56,12 @@ def get_device_id(): | |||
| 56 | def softmax_core(x: pypto.Tensor) -> pypto.Tensor: | 56 | def softmax_core(x: pypto.Tensor) -> pypto.Tensor: |
| 57 | """ | 57 | """ |
| 58 | Core softmax computation: exp(x - max(x)) / sum(exp(x - max(x))). | 58 | Core softmax computation: exp(x - max(x)) / sum(exp(x - max(x))). |
| 59 | - | 59 | + |
| 60 | Parameters | 60 | Parameters |
| 61 | ---------- | 61 | ---------- |
| 62 | - input_tensor : pypto.tensor | 62 | + input_tensor : pypto.Tensor |
| 63 | Input tensor to apply softmax to | 63 | Input tensor to apply softmax to |
| 64 | - | 64 | + |
| 65 | Returns | 65 | Returns |
| 66 | ------- | 66 | ------- |
| 67 | pypto.tensor | 67 | pypto.tensor |
| @@ -134,7 +134,7 @@ def test_softmax_capture(device_id=None, dynamic: bool = True) -> None: | |||
| 134 | g = torch.npu.NPUGraph() | 134 | g = torch.npu.NPUGraph() |
| 135 | with torch.npu.graph(g): | 135 | with torch.npu.graph(g): |
| 136 | y = model(x, dynamic) | 136 | y = model(x, dynamic) |
| 137 | - | 137 | + |
| 138 | #execute graph | 138 | #execute graph |
| 139 | g.replay() | 139 | g.replay() |
| 140 | torch.npu.synchronize() | 140 | torch.npu.synchronize() |
| @@ -149,7 +149,7 @@ def test_softmax_capture(device_id=None, dynamic: bool = True) -> None: | |||
| 149 | 149 | ||
| 150 | def main(): | 150 | def main(): |
| 151 | """Run softmax example. | 151 | """Run softmax example. |
| 152 | - | 152 | + |
| 153 | Usage: | 153 | Usage: |
| 154 | python softmax.py # Run example | 154 | python softmax.py # Run example |
| 155 | python softmax.py --list # List available examples | 155 | python softmax.py --list # List available examples |
| @@ -174,9 +174,9 @@ Examples: | |||
| 174 | action='store_true', | 174 | action='store_true', |
| 175 | help='List all available examples and exit' | 175 | help='List all available examples and exit' |
| 176 | ) | 176 | ) |
| 177 | - | 177 | + |
| 178 | args = parser.parse_args() | 178 | args = parser.parse_args() |
| 179 | - | 179 | + |
| 180 | # Define available examples | 180 | # Define available examples |
| 181 | examples = { | 181 | examples = { |
| 182 | "aclgraph::test_aclgraph": { | 182 | "aclgraph::test_aclgraph": { |
| @@ -186,7 +186,7 @@ Examples: | |||
| 186 | 'requires_npu': True | 186 | 'requires_npu': True |
| 187 | } | 187 | } |
| 188 | } | 188 | } |
| 189 | - | 189 | + |
| 190 | # List examples if requested | 190 | # List examples if requested |
| 191 | if args.list: | 191 | if args.list: |
| 192 | print("\n" + "=" * 60) | 192 | print("\n" + "=" * 60) |
| @@ -197,7 +197,7 @@ Examples: | |||
| 197 | print(f" {ex_id}. {ex_info['name']}{npu_req}") | 197 | print(f" {ex_id}. {ex_info['name']}{npu_req}") |
| 198 | print(f" {ex_info['description']}\n") | 198 | print(f" {ex_info['description']}\n") |
| 199 | return | 199 | return |
| 200 | - | 200 | + |
| 201 | # Validate example ID if provided | 201 | # Validate example ID if provided |
| 202 | if args.example_id is not None: | 202 | if args.example_id is not None: |
| 203 | if args.example_id not in examples: | 203 | if args.example_id not in examples: |
| @@ -205,50 +205,50 @@ Examples: | |||
| 205 | print(f"Valid example IDs are: {', '.join(map(str, sorted(examples.keys())))}") | 205 | print(f"Valid example IDs are: {', '.join(map(str, sorted(examples.keys())))}") |
| 206 | print("\nUse --list to see all available examples.") | 206 | print("\nUse --list to see all available examples.") |
| 207 | sys.exit(1) | 207 | sys.exit(1) |
| 208 | - | 208 | + |
| 209 | print("\n" + "=" * 60) | 209 | print("\n" + "=" * 60) |
| 210 | print("PyPTO Softmax Example") | 210 | print("PyPTO Softmax Example") |
| 211 | print("=" * 60 + "\n") | 211 | print("=" * 60 + "\n") |
| 212 | - | 212 | + |
| 213 | # Get and validate device ID (needed for NPU examples) | 213 | # Get and validate device ID (needed for NPU examples) |
| 214 | device_id = None | 214 | device_id = None |
| 215 | examples_to_run = [] | 215 | examples_to_run = [] |
| 216 | - | 216 | + |
| 217 | if args.example_id is not None: | 217 | if args.example_id is not None: |
| 218 | # Run single example | 218 | # Run single example |
| 219 | examples_to_run = [(args.example_id, examples[args.example_id])] | 219 | examples_to_run = [(args.example_id, examples[args.example_id])] |
| 220 | else: | 220 | else: |
| 221 | # Run all examples | 221 | # Run all examples |
| 222 | examples_to_run = list(examples.items()) | 222 | examples_to_run = list(examples.items()) |
| 223 | - | 223 | + |
| 224 | # Check if any example requires NPU | 224 | # Check if any example requires NPU |
| 225 | requires_npu = any(ex_info['requires_npu'] for _, ex_info in examples_to_run) | 225 | requires_npu = any(ex_info['requires_npu'] for _, ex_info in examples_to_run) |
| 226 | - | 226 | + |
| 227 | if requires_npu: | 227 | if requires_npu: |
| 228 | device_id = get_device_id() | 228 | device_id = get_device_id() |
| 229 | if device_id is None: | 229 | if device_id is None: |
| 230 | return | 230 | return |
| 231 | # Set the device once for all examples | 231 | # Set the device once for all examples |
| 232 | torch.npu.set_device(device_id) | 232 | torch.npu.set_device(device_id) |
| 233 | - | 233 | + |
| 234 | try: | 234 | try: |
| 235 | for ex_id, ex_info in examples_to_run: | 235 | for ex_id, ex_info in examples_to_run: |
| 236 | if ex_info['requires_npu'] and device_id is None: | 236 | if ex_info['requires_npu'] and device_id is None: |
| 237 | print(f"Skipping example {ex_id} ({ex_info['name']}): NPU device not configured") | 237 | print(f"Skipping example {ex_id} ({ex_info['name']}): NPU device not configured") |
| 238 | continue | 238 | continue |
| 239 | - | 239 | + |
| 240 | print(f"Running Example {ex_id}: {ex_info['name']}") | 240 | print(f"Running Example {ex_id}: {ex_info['name']}") |
| 241 | ex_info['function']() | 241 | ex_info['function']() |
| 242 | - | 242 | + |
| 243 | if len(examples_to_run) > 1: | 243 | if len(examples_to_run) > 1: |
| 244 | print("=" * 60) | 244 | print("=" * 60) |
| 245 | print("All softmax tests passed!") | 245 | print("All softmax tests passed!") |
| 246 | print("=" * 60) | 246 | print("=" * 60) |
| 247 | - | 247 | + |
| 248 | except Exception as e: | 248 | except Exception as e: |
| 249 | print(f"\nError: {e}") | 249 | print(f"\nError: {e}") |
| 250 | raise | 250 | raise |
| 251 | 251 | ||
| 252 | 252 | ||
| 253 | if __name__ == "__main__": | 253 | if __name__ == "__main__": |
| 254 | - main() | 254 | + main() |
| @@ -9,7 +9,7 @@ | |||
| 9 | # See LICENSE in the root of the software repository for the full text of the License. | 9 | # See LICENSE in the root of the software repository for the full text of the License. |
| 10 | # ----------------------------------------------------------------------------------------------------------- | 10 | # ----------------------------------------------------------------------------------------------------------- |
| 11 | """ | 11 | """ |
| 12 | -This test case verifies that the swimlane diagram generation for the costmodel works correctly | 12 | +This test case verifies that the swimlane diagram generation for the costmodel works correctly |
| 13 | regardless of whether the CANN is installed in the environment or not. | 13 | regardless of whether the CANN is installed in the environment or not. |
| 14 | """ | 14 | """ |
| 15 | 15 | ||
| @@ -26,7 +26,7 @@ from numpy.testing import assert_allclose | |||
| 26 | PyPTO Cost Model Simulation Example | 26 | PyPTO Cost Model Simulation Example |
| 27 | 27 | ||
| 28 | This example demonstrates how to enable swimlane diagram generation in PyPTO's cost model mode. | 28 | This example demonstrates how to enable swimlane diagram generation in PyPTO's cost model mode. |
| 29 | -The test validates that the cost analysis and swimlane visualization work correctly in | 29 | +The test validates that the cost analysis and swimlane visualization work correctly in |
| 30 | simulation environment, independent of actual NPU hardware availability. | 30 | simulation environment, independent of actual NPU hardware availability. |
| 31 | """ | 31 | """ |
| 32 | 32 | ||
| @@ -48,15 +48,15 @@ def safe_json_load(file_path): | |||
| 48 | def get_out_put_path(): | 48 | def get_out_put_path(): |
| 49 | out_path = "./output" | 49 | out_path = "./output" |
| 50 | if os.path.exists(out_path): | 50 | if os.path.exists(out_path): |
| 51 | - subdirs = [os.path.join(out_path, d) for d in os.listdir(out_path) | 51 | + subdirs = [os.path.join(out_path, d) for d in os.listdir(out_path) |
| 52 | - if os.path.isdir(os.path.join(out_path, d))] | 52 | + if os.path.isdir(os.path.join(out_path, d))] |
| 53 | if subdirs: | 53 | if subdirs: |
| 54 | latest_dir = max(subdirs, key=os.path.getctime) | 54 | latest_dir = max(subdirs, key=os.path.getctime) |
| 55 | return latest_dir | 55 | return latest_dir |
| 56 | return None | 56 | return None |
| 57 | 57 | ||
| 58 | 58 | ||
| 59 | -def softmax_core(input_tensor: pypto.tensor) -> pypto.tensor: | 59 | +def softmax_core(input_tensor: pypto.Tensor) -> pypto.Tensor: |
| 60 | row_max = pypto.amax(input_tensor, dim=-1, keepdim=True) | 60 | row_max = pypto.amax(input_tensor, dim=-1, keepdim=True) |
| 61 | sub = pypto.sub(input_tensor, row_max) | 61 | sub = pypto.sub(input_tensor, row_max) |
| 62 | exp = pypto.exp(sub) | 62 | exp = pypto.exp(sub) |
| @@ -83,13 +83,13 @@ def softmax(input_tensor, output_tensor, cost_model_enable): | |||
| 83 | for idx in pypto.loop(0, b_loop, 1, name="LOOP_L0_bIdx", idx_name="idx"): | 83 | for idx in pypto.loop(0, b_loop, 1, name="LOOP_L0_bIdx", idx_name="idx"): |
| 84 | b_offset = idx * tile_b | 84 | b_offset = idx * tile_b |
| 85 | b_offset_end = (idx + 1) * tile_b | 85 | b_offset_end = (idx + 1) * tile_b |
| 86 | - | 86 | + |
| 87 | # Extract batch slice | 87 | # Extract batch slice |
| 88 | input_view = input_tensor[b_offset:b_offset_end, :n1, :n2, :dim] | 88 | input_view = input_tensor[b_offset:b_offset_end, :n1, :n2, :dim] |
| 89 | - | 89 | + |
| 90 | # Apply softmax to batch slice | 90 | # Apply softmax to batch slice |
| 91 | softmax_out = softmax_core(input_view) | 91 | softmax_out = softmax_core(input_view) |
| 92 | - | 92 | + |
| 93 | # Assemble result back to output tensor | 93 | # Assemble result back to output tensor |
| 94 | pypto.assemble(softmax_out, [b_offset, 0, 0, 0], output_tensor) | 94 | pypto.assemble(softmax_out, [b_offset, 0, 0, 0], output_tensor) |
| 95 | 95 | ||
| @@ -100,9 +100,9 @@ def test_softmax(cost_model_enable=True): | |||
| 100 | 100 | ||
| 101 | When cost_model_enable=True, PyPTO generates simulated execution | 101 | When cost_model_enable=True, PyPTO generates simulated execution |
| 102 | outputs (e.g. swimlane JSON) for analysis. | 102 | outputs (e.g. swimlane JSON) for analysis. |
| 103 | - """ | 103 | + """ |
| 104 | cann_is_configed: bool = bool(os.environ.get("ASCEND_HOME_PATH")) | 104 | cann_is_configed: bool = bool(os.environ.get("ASCEND_HOME_PATH")) |
| 105 | - | 105 | + |
| 106 | # Shape for verification: NCHW format, N can be any integer number as it is defined as dynamic axis | 106 | # Shape for verification: NCHW format, N can be any integer number as it is defined as dynamic axis |
| 107 | shape = (32, 32, 1, 256) | 107 | shape = (32, 32, 1, 256) |
| 108 | 108 | ||
| @@ -130,10 +130,10 @@ def test_softmax(cost_model_enable=True): | |||
| 130 | torch_data = torch_softmax.cpu() | 130 | torch_data = torch_softmax.cpu() |
| 131 | 131 | ||
| 132 | max_diff = np.abs(npu_data.numpy() - torch_data.numpy()).max() | 132 | max_diff = np.abs(npu_data.numpy() - torch_data.numpy()).max() |
| 133 | - | 133 | + |
| 134 | output_path = get_out_put_path() | 134 | output_path = get_out_put_path() |
| 135 | assert output_path | 135 | assert output_path |
| 136 | - | 136 | + |
| 137 | if cost_model_enable: | 137 | if cost_model_enable: |
| 138 | merged_swimlane, error = safe_json_load(os.path.join(output_path, 'CostModelSimulationOutput/merged_swimlane.json')) | 138 | merged_swimlane, error = safe_json_load(os.path.join(output_path, 'CostModelSimulationOutput/merged_swimlane.json')) |
| 139 | assert not error | 139 | assert not error |
| @@ -142,13 +142,13 @@ def test_softmax(cost_model_enable=True): | |||
| 142 | print(f"Output shape: {output_data.shape}") | 142 | print(f"Output shape: {output_data.shape}") |
| 143 | print("✓ Cost model test passed\n") | 143 | print("✓ Cost model test passed\n") |
| 144 | print() | 144 | print() |
| 145 | - | 145 | + |
| 146 | 146 | ||
| 147 | if __name__ == "__main__": | 147 | if __name__ == "__main__": |
| 148 | # Always execute through build_ci.py | 148 | # Always execute through build_ci.py |
| 149 | script_path = os.path.abspath(__file__) | 149 | script_path = os.path.abspath(__file__) |
| 150 | cmd = f"python3 build_ci.py -s={script_path}" | 150 | cmd = f"python3 build_ci.py -s={script_path}" |
| 151 | - | 151 | + |
| 152 | # Execute and Exit | 152 | # Execute and Exit |
| 153 | os.system(cmd) | 153 | os.system(cmd) |
| 154 | sys.exit(0) | 154 | sys.exit(0) |
| @@ -92,7 +92,7 @@ def scaled_dot_product_attention_golden( | |||
| 92 | return output | 92 | return output |
| 93 | 93 | ||
| 94 | 94 | ||
| 95 | -def scaled_dot_product_attention_core(q: pypto.Tensor, k: pypto.Tensor, v: pypto.Tensor, | 95 | +def scaled_dot_product_attention_core(q: pypto.Tensor, k: pypto.Tensor, v: pypto.Tensor, |
| 96 | scale: float, dtype: pypto.DataType) -> pypto.Tensor: | 96 | scale: float, dtype: pypto.DataType) -> pypto.Tensor: |
| 97 | k_t = pypto.transpose(k, 2, 3) | 97 | k_t = pypto.transpose(k, 2, 3) |
| 98 | scores = pypto.matmul(q, k_t, out_dtype=dtype) | 98 | scores = pypto.matmul(q, k_t, out_dtype=dtype) |
| @@ -105,10 +105,10 @@ def scaled_dot_product_attention_core(q: pypto.Tensor, k: pypto.Tensor, v: pypto | |||
| 105 | @pypto.jit( | 105 | @pypto.jit( |
| 106 | host_options={"only_codegen": True}, | 106 | host_options={"only_codegen": True}, |
| 107 | ) | 107 | ) |
| 108 | -def scaled_dot_product_attention_kernel_npu(q: torch.Tensor, k: torch.Tensor, | 108 | +def scaled_dot_product_attention_kernel_npu(q: pypto.Tensor, k: pypto.Tensor, |
| 109 | - v: torch.Tensor, y: torch.Tensor, params: torch.Size, | 109 | + v: pypto.Tensor, y: pypto.Tensor, params: torch.Size, |
| 110 | config: AttentionConfig): | 110 | config: AttentionConfig): |
| 111 | - """Scaled dot-product attention with dynamic batch and sequence lengths.""" | 111 | + """Scaled dot-product attention with dynamic batch and sequence lengths.""" |
| 112 | batch_size, num_heads, seq_len, head_dim = params | 112 | batch_size, num_heads, seq_len, head_dim = params |
| 113 | 113 | ||
| 114 | # Calculate scale | 114 | # Calculate scale |
| @@ -121,18 +121,18 @@ def scaled_dot_product_attention_kernel_npu(q: torch.Tensor, k: torch.Tensor, | |||
| 121 | q_view = q[bs_idx * view_shape[0]:(bs_idx+1) * view_shape[0], ...] | 121 | q_view = q[bs_idx * view_shape[0]:(bs_idx+1) * view_shape[0], ...] |
| 122 | k_view = k[bs_idx * view_shape[0]:(bs_idx+1) * view_shape[0], ...] | 122 | k_view = k[bs_idx * view_shape[0]:(bs_idx+1) * view_shape[0], ...] |
| 123 | v_view = v[bs_idx * view_shape[0]:(bs_idx+1) * view_shape[0], ...] | 123 | v_view = v[bs_idx * view_shape[0]:(bs_idx+1) * view_shape[0], ...] |
| 124 | - pypto.set_vec_tile_shapes(1, 8, 16, 64) | 124 | + pypto.set_vec_tile_shapes(1, 8, 16, 64) |
| 125 | res = scaled_dot_product_attention_core(q_view, k_view, v_view, scale, config.dtype) | 125 | res = scaled_dot_product_attention_core(q_view, k_view, v_view, scale, config.dtype) |
| 126 | y[bs_idx * view_shape[0]:, ...] = res | 126 | y[bs_idx * view_shape[0]:, ...] = res |
| 127 | - | 127 | + |
| 128 | @pypto.jit( | 128 | @pypto.jit( |
| 129 | host_options={"only_codegen": True}, | 129 | host_options={"only_codegen": True}, |
| 130 | runtime_options={"run_mode" : 1} | 130 | runtime_options={"run_mode" : 1} |
| 131 | ) | 131 | ) |
| 132 | -def scaled_dot_product_attention_kernel_sim(q: torch.Tensor, k: torch.Tensor, | 132 | +def scaled_dot_product_attention_kernel_sim(q: pypto.Tensor, k: pypto.Tensor, |
| 133 | - v: torch.Tensor, y: torch.Tensor, params: torch.Size, | 133 | + v: pypto.Tensor, y: pypto.Tensor, params: torch.Size, |
| 134 | config: AttentionConfig): | 134 | config: AttentionConfig): |
| 135 | - """Scaled dot-product attention with dynamic batch and sequence lengths.""" | 135 | + """Scaled dot-product attention with dynamic batch and sequence lengths.""" |
| 136 | batch_size, num_heads, seq_len, head_dim = params | 136 | batch_size, num_heads, seq_len, head_dim = params |
| 137 | 137 | ||
| 138 | # Calculate scale | 138 | # Calculate scale |
| @@ -145,13 +145,15 @@ def scaled_dot_product_attention_kernel_sim(q: torch.Tensor, k: torch.Tensor, | |||
| 145 | q_view = q[bs_idx * view_shape[0]:(bs_idx+1) * view_shape[0], ...] | 145 | q_view = q[bs_idx * view_shape[0]:(bs_idx+1) * view_shape[0], ...] |
| 146 | k_view = k[bs_idx * view_shape[0]:(bs_idx+1) * view_shape[0], ...] | 146 | k_view = k[bs_idx * view_shape[0]:(bs_idx+1) * view_shape[0], ...] |
| 147 | v_view = v[bs_idx * view_shape[0]:(bs_idx+1) * view_shape[0], ...] | 147 | v_view = v[bs_idx * view_shape[0]:(bs_idx+1) * view_shape[0], ...] |
| 148 | - pypto.set_vec_tile_shapes(1, 8, 16, 64) | 148 | + pypto.set_vec_tile_shapes(1, 8, 16, 64) |
| 149 | res = scaled_dot_product_attention_core(q_view, k_view, v_view, scale, config.dtype) | 149 | res = scaled_dot_product_attention_core(q_view, k_view, v_view, scale, config.dtype) |
| 150 | y[bs_idx * view_shape[0]:, ...] = res | 150 | y[bs_idx * view_shape[0]:, ...] = res |
| 151 | 151 | ||
| 152 | -def scaled_dot_product_attention(q: torch.Tensor, k: torch.Tensor, | 152 | + |
| 153 | - v: torch.Tensor, params: torch.Size, | 153 | +def scaled_dot_product_attention(q: torch.Tensor, k: torch.Tensor, |
| 154 | - config: AttentionConfig, run_mode: str = "npu", dynamic: bool = True) -> torch.Tensor: | 154 | + v: torch.Tensor, params: torch.Size, |
| 155 | + config: AttentionConfig, run_mode: str = "npu", | ||
| 156 | + dynamic: bool = True) -> torch.Tensor: | ||
| 155 | y = torch.empty_like(q) | 157 | y = torch.empty_like(q) |
| 156 | 158 | ||
| 157 | if dynamic: | 159 | if dynamic: |
| @@ -177,11 +179,11 @@ def test_attention_dynamic(device_id = None, run_mode: str = "npu", dynamic: boo | |||
| 177 | print("=" * 60) | 179 | print("=" * 60) |
| 178 | print("Test: Dynamic Scaled Dot-Product Attention") | 180 | print("Test: Dynamic Scaled Dot-Product Attention") |
| 179 | print("=" * 60) | 181 | print("=" * 60) |
| 180 | - | 182 | + |
| 181 | device = f'npu:{device_id}' if (run_mode == "npu" and device_id is not None) else 'cpu' | 183 | device = f'npu:{device_id}' if (run_mode == "npu" and device_id is not None) else 'cpu' |
| 182 | - | 184 | + |
| 183 | num_heads, head_dim = 8, 64 | 185 | num_heads, head_dim = 8, 64 |
| 184 | - | 186 | + |
| 185 | # Test with different batch sizes and sequence lengths (dynamic shapes) | 187 | # Test with different batch sizes and sequence lengths (dynamic shapes) |
| 186 | test_cases = [ | 188 | test_cases = [ |
| 187 | (2, 16, 16), | 189 | (2, 16, 16), |
| @@ -190,22 +192,22 @@ def test_attention_dynamic(device_id = None, run_mode: str = "npu", dynamic: boo | |||
| 190 | ] | 192 | ] |
| 191 | for batch_size, seq_len_q, seq_len_kv in test_cases: | 193 | for batch_size, seq_len_q, seq_len_kv in test_cases: |
| 192 | dtype = torch.float32 | 194 | dtype = torch.float32 |
| 193 | - q_torch = torch.randn(batch_size, num_heads, seq_len_q, head_dim, | 195 | + q_torch = torch.randn(batch_size, num_heads, seq_len_q, head_dim, |
| 194 | dtype=dtype, device=device) | 196 | dtype=dtype, device=device) |
| 195 | - k_torch = torch.randn(batch_size, num_heads, seq_len_kv, head_dim, | 197 | + k_torch = torch.randn(batch_size, num_heads, seq_len_kv, head_dim, |
| 196 | dtype=dtype, device=device) | 198 | dtype=dtype, device=device) |
| 197 | - v_torch = torch.randn(batch_size, num_heads, seq_len_kv, head_dim, | 199 | + v_torch = torch.randn(batch_size, num_heads, seq_len_kv, head_dim, |
| 198 | dtype=dtype, device=device) | 200 | dtype=dtype, device=device) |
| 199 | - config = AttentionConfig(num_heads=num_heads, head_dim=head_dim, | 201 | + config = AttentionConfig(num_heads=num_heads, head_dim=head_dim, |
| 200 | dtype=pypto.DT_FP32, use_dynamic_shape=True) | 202 | dtype=pypto.DT_FP32, use_dynamic_shape=True) |
| 201 | params = q_torch.shape | 203 | params = q_torch.shape |
| 202 | # Execute | 204 | # Execute |
| 203 | out_torch = scaled_dot_product_attention(q_torch, k_torch, v_torch, params, config, run_mode, dynamic).cpu() | 205 | out_torch = scaled_dot_product_attention(q_torch, k_torch, v_torch, params, config, run_mode, dynamic).cpu() |
| 204 | - | 206 | + |
| 205 | # Verify | 207 | # Verify |
| 206 | scale = 1.0 / (head_dim ** 0.5) | 208 | scale = 1.0 / (head_dim ** 0.5) |
| 207 | golden = scaled_dot_product_attention_golden(q_torch, k_torch, v_torch, scale).cpu() | 209 | golden = scaled_dot_product_attention_golden(q_torch, k_torch, v_torch, scale).cpu() |
| 208 | - | 210 | + |
| 209 | max_diff = (out_torch - golden).abs().max().item() | 211 | max_diff = (out_torch - golden).abs().max().item() |
| 210 | print(f"Batch={batch_size}, SeqQ={seq_len_q}, SeqKV={seq_len_kv}") | 212 | print(f"Batch={batch_size}, SeqQ={seq_len_q}, SeqKV={seq_len_kv}") |
| 211 | print(f"Input shape: {q_torch.shape}") | 213 | print(f"Input shape: {q_torch.shape}") |
| @@ -213,12 +215,12 @@ def test_attention_dynamic(device_id = None, run_mode: str = "npu", dynamic: boo | |||
| 213 | if run_mode == "npu": | 215 | if run_mode == "npu": |
| 214 | print(f"Batch={batch_size}, SeqQ={seq_len_q}, SeqKV={seq_len_kv}, Max diff: {max_diff:.6f}") | 216 | print(f"Batch={batch_size}, SeqQ={seq_len_q}, SeqKV={seq_len_kv}, Max diff: {max_diff:.6f}") |
| 215 | assert_allclose(np.array(out_torch), np.array(golden), rtol=3e-3, atol=3e-3) | 217 | assert_allclose(np.array(out_torch), np.array(golden), rtol=3e-3, atol=3e-3) |
| 216 | - | 218 | + |
| 217 | print("✓ Attention (dynamic) passed for the test case") | 219 | print("✓ Attention (dynamic) passed for the test case") |
| 218 | print() | 220 | print() |
| 219 | 221 | ||
| 220 | 222 | ||
| 221 | -def attention_with_projection_core(q_view: pypto.Tensor, k_view: pypto.Tensor, | 223 | +def attention_with_projection_core(q_view: pypto.Tensor, k_view: pypto.Tensor, |
| 222 | v_view: pypto.Tensor, out_weight: pypto.Tensor, | 224 | v_view: pypto.Tensor, out_weight: pypto.Tensor, |
| 223 | scale: float, dtype: pypto.DataType) -> pypto.Tensor: | 225 | scale: float, dtype: pypto.DataType) -> pypto.Tensor: |
| 224 | batch = q_view.shape[0] | 226 | batch = q_view.shape[0] |
| @@ -241,7 +243,7 @@ def attention_with_projection_core(q_view: pypto.Tensor, k_view: pypto.Tensor, | |||
| 241 | 243 | ||
| 242 | 244 | ||
| 243 | @pypto.jit | 245 | @pypto.jit |
| 244 | -def attention_with_projection_kernel_npu(hidden_states, q_weight, k_weight, v_weight, | 246 | +def attention_with_projection_kernel_npu(hidden_states, q_weight, k_weight, v_weight, |
| 245 | out_weight, out, config: AttentionConfig): | 247 | out_weight, out, config: AttentionConfig): |
| 246 | """Complete attention with input projection (Q, K, V from hidden states).""" | 248 | """Complete attention with input projection (Q, K, V from hidden states).""" |
| 247 | batch_size = hidden_states.shape[0] | 249 | batch_size = hidden_states.shape[0] |
| @@ -263,7 +265,7 @@ def attention_with_projection_kernel_npu(hidden_states, q_weight, k_weight, v_we | |||
| 263 | q = pypto.reshape(q_flat, [batch_size, seq_len, config.num_heads, config.head_dim]) | 265 | q = pypto.reshape(q_flat, [batch_size, seq_len, config.num_heads, config.head_dim]) |
| 264 | k = pypto.reshape(k_flat, [batch_size, seq_len, config.num_heads, config.head_dim]) | 266 | k = pypto.reshape(k_flat, [batch_size, seq_len, config.num_heads, config.head_dim]) |
| 265 | v = pypto.reshape(v_flat, [batch_size, seq_len, config.num_heads, config.head_dim]) | 267 | v = pypto.reshape(v_flat, [batch_size, seq_len, config.num_heads, config.head_dim]) |
| 266 | - | 268 | + |
| 267 | # Transpose for attention: [batch, num_heads, seq_len, head_dim] | 269 | # Transpose for attention: [batch, num_heads, seq_len, head_dim] |
| 268 | q = pypto.transpose(q, 1, 2) | 270 | q = pypto.transpose(q, 1, 2) |
| 269 | k = pypto.transpose(k, 1, 2) | 271 | k = pypto.transpose(k, 1, 2) |
| @@ -279,8 +281,9 @@ def attention_with_projection_kernel_npu(hidden_states, q_weight, k_weight, v_we | |||
| 279 | v_view, out_weight, | 281 | v_view, out_weight, |
| 280 | scale, config.dtype) | 282 | scale, config.dtype) |
| 281 | 283 | ||
| 284 | + | ||
| 282 | @pypto.jit(runtime_options={"run_mode" : 1}) | 285 | @pypto.jit(runtime_options={"run_mode" : 1}) |
| 283 | -def attention_with_projection_kernel_sim(hidden_states, q_weight, k_weight, v_weight, | 286 | +def attention_with_projection_kernel_sim(hidden_states, q_weight, k_weight, v_weight, |
| 284 | out_weight, out, config: AttentionConfig): | 287 | out_weight, out, config: AttentionConfig): |
| 285 | """Complete attention with input projection (Q, K, V from hidden states).""" | 288 | """Complete attention with input projection (Q, K, V from hidden states).""" |
| 286 | batch_size = hidden_states.shape[0] | 289 | batch_size = hidden_states.shape[0] |
| @@ -302,7 +305,7 @@ def attention_with_projection_kernel_sim(hidden_states, q_weight, k_weight, v_we | |||
| 302 | q = pypto.reshape(q_flat, [batch_size, seq_len, config.num_heads, config.head_dim]) | 305 | q = pypto.reshape(q_flat, [batch_size, seq_len, config.num_heads, config.head_dim]) |
| 303 | k = pypto.reshape(k_flat, [batch_size, seq_len, config.num_heads, config.head_dim]) | 306 | k = pypto.reshape(k_flat, [batch_size, seq_len, config.num_heads, config.head_dim]) |
| 304 | v = pypto.reshape(v_flat, [batch_size, seq_len, config.num_heads, config.head_dim]) | 307 | v = pypto.reshape(v_flat, [batch_size, seq_len, config.num_heads, config.head_dim]) |
| 305 | - | 308 | + |
| 306 | # Transpose for attention: [batch, num_heads, seq_len, head_dim] | 309 | # Transpose for attention: [batch, num_heads, seq_len, head_dim] |
| 307 | q = pypto.transpose(q, 1, 2) | 310 | q = pypto.transpose(q, 1, 2) |
| 308 | k = pypto.transpose(k, 1, 2) | 311 | k = pypto.transpose(k, 1, 2) |
| @@ -318,9 +321,10 @@ def attention_with_projection_kernel_sim(hidden_states, q_weight, k_weight, v_we | |||
| 318 | v_view, out_weight, | 321 | v_view, out_weight, |
| 319 | scale, config.dtype) | 322 | scale, config.dtype) |
| 320 | 323 | ||
| 321 | -def attention_with_projection(hidden_states: torch.Tensor, q_weight: torch.Tensor, | 324 | + |
| 322 | - k_weight: torch.Tensor, v_weight: torch.Tensor, | 325 | +def attention_with_projection(hidden_states: torch.Tensor, q_weight: torch.Tensor, |
| 323 | - out_weight: torch.Tensor, config: AttentionConfig, | 326 | + k_weight: torch.Tensor, v_weight: torch.Tensor, |
| 327 | + out_weight: torch.Tensor, config: AttentionConfig, | ||
| 324 | run_mode: str = "npu", dynamic: bool = True) -> torch.Tensor: | 328 | run_mode: str = "npu", dynamic: bool = True) -> torch.Tensor: |
| 325 | y = torch.empty_like(hidden_states) | 329 | y = torch.empty_like(hidden_states) |
| 326 | 330 | ||
| @@ -112,7 +112,7 @@ def layer_norm_kernel_sim(x: pypto.Tensor, gamma: pypto.Tensor, beta: pypto.Tens | |||
| 112 | pypto.set_vec_tile_shapes(64, 128) | 112 | pypto.set_vec_tile_shapes(64, 128) |
| 113 | 113 | ||
| 114 | out[:] = layernorm_core(x, gamma, beta) | 114 | out[:] = layernorm_core(x, gamma, beta) |
| 115 | - | 115 | + |
| 116 | 116 | ||
| 117 | def layer_norm(x: torch.Tensor, gamma: torch.Tensor, beta: torch.Tensor, run_mode: str = "npu", dynamic: bool = False) -> torch.Tensor: | 117 | def layer_norm(x: torch.Tensor, gamma: torch.Tensor, beta: torch.Tensor, run_mode: str = "npu", dynamic: bool = False) -> torch.Tensor: |
| 118 | y = torch.empty_like(x) | 118 | y = torch.empty_like(x) |
| @@ -186,7 +186,7 @@ def linear_projection(x: pypto.Tensor, weight: pypto.Tensor, run_mode: str = "np | |||
| 186 | 186 | ||
| 187 | # Function 3: GELU Activation | 187 | # Function 3: GELU Activation |
| 188 | @pypto.jit | 188 | @pypto.jit |
| 189 | -def gelu_activation_kernel_npu(x: pypto.tensor, y: pypto.tensor) -> None: | 189 | +def gelu_activation_kernel_npu(x: pypto.Tensor, y: pypto.Tensor) -> None: |
| 190 | """ | 190 | """ |
| 191 | GELU (Gaussian Error Linear Unit) activation function. | 191 | GELU (Gaussian Error Linear Unit) activation function. |
| 192 | 192 | ||
| @@ -195,12 +195,12 @@ def gelu_activation_kernel_npu(x: pypto.tensor, y: pypto.tensor) -> None: | |||
| 195 | 195 | ||
| 196 | Parameters | 196 | Parameters |
| 197 | ---------- | 197 | ---------- |
| 198 | - x : pypto.tensor | 198 | + x : pypto.Tensor |
| 199 | Input tensor | 199 | Input tensor |
| 200 | 200 | ||
| 201 | Returns | 201 | Returns |
| 202 | ------- | 202 | ------- |
| 203 | - pypto.tensor | 203 | + pypto.Tensor |
| 204 | GELU activated tensor | 204 | GELU activated tensor |
| 205 | """ | 205 | """ |
| 206 | # Configure tiling | 206 | # Configure tiling |
| @@ -220,7 +220,7 @@ def gelu_activation_kernel_npu(x: pypto.tensor, y: pypto.tensor) -> None: | |||
| 220 | 220 | ||
| 221 | 221 | ||
| 222 | @pypto.jit(runtime_options={"run_mode": 1}) | 222 | @pypto.jit(runtime_options={"run_mode": 1}) |
| 223 | -def gelu_activation_kernel_sim(x: pypto.tensor, y: pypto.tensor) -> None: | 223 | +def gelu_activation_kernel_sim(x: pypto.Tensor, y: pypto.Tensor) -> None: |
| 224 | """ | 224 | """ |
| 225 | GELU (Gaussian Error Linear Unit) activation function. | 225 | GELU (Gaussian Error Linear Unit) activation function. |
| 226 | 226 | ||
| @@ -229,12 +229,12 @@ def gelu_activation_kernel_sim(x: pypto.tensor, y: pypto.tensor) -> None: | |||
| 229 | 229 | ||
| 230 | Parameters | 230 | Parameters |
| 231 | ---------- | 231 | ---------- |
| 232 | - x : pypto.tensor | 232 | + x : pypto.Tensor |
| 233 | Input tensor | 233 | Input tensor |
| 234 | 234 | ||
| 235 | Returns | 235 | Returns |
| 236 | ------- | 236 | ------- |
| 237 | - pypto.tensor | 237 | + pypto.Tensor |
| 238 | GELU activated tensor | 238 | GELU activated tensor |
| 239 | """ | 239 | """ |
| 240 | # Configure tiling | 240 | # Configure tiling |
| @@ -274,7 +274,7 @@ def gelu_activation(x: torch.Tensor, run_mode: str = "npu", dynamic: bool = Fals | |||
| 274 | 274 | ||
| 275 | # Function 4: Residual Connection | 275 | # Function 4: Residual Connection |
| 276 | @pypto.jit | 276 | @pypto.jit |
| 277 | -def residual_add_kernel_npu(x: pypto.tensor, residual: pypto.tensor, out: pypto.tensor) -> None: | 277 | +def residual_add_kernel_npu(x: pypto.Tensor, residual: pypto.Tensor, out: pypto.Tensor) -> None: |
| 278 | """Add residual connection: out = x + residual""" | 278 | """Add residual connection: out = x + residual""" |
| 279 | pypto.set_vec_tile_shapes(64, 128) | 279 | pypto.set_vec_tile_shapes(64, 128) |
| 280 | 280 | ||
| @@ -282,7 +282,7 @@ def residual_add_kernel_npu(x: pypto.tensor, residual: pypto.tensor, out: pypto. | |||
| 282 | 282 | ||
| 283 | 283 | ||
| 284 | @pypto.jit(runtime_options={"run_mode": 1}) | 284 | @pypto.jit(runtime_options={"run_mode": 1}) |
| 285 | -def residual_add_kernel_sim(x: pypto.tensor, residual: pypto.tensor, out: pypto.tensor) -> None: | 285 | +def residual_add_kernel_sim(x: pypto.Tensor, residual: pypto.Tensor, out: pypto.Tensor) -> None: |
| 286 | """Add residual connection: out = x + residual""" | 286 | """Add residual connection: out = x + residual""" |
| 287 | pypto.set_vec_tile_shapes(64, 128) | 287 | pypto.set_vec_tile_shapes(64, 128) |
| 288 | 288 | ||
| @@ -312,7 +312,7 @@ def residual_add(x: pypto.Tensor, residual: pypto.Tensor, run_mode: str = "npu", | |||
| 312 | 312 | ||
| 313 | # Function 5: Attention (simplified) | 313 | # Function 5: Attention (simplified) |
| 314 | @pypto.jit | 314 | @pypto.jit |
| 315 | -def attention_kernel_npu(q: pypto.tensor, k: pypto.tensor, v: pypto.tensor, out: pypto.tensor, scale: float) -> None: | 315 | +def attention_kernel_npu(q: pypto.Tensor, k: pypto.Tensor, v: pypto.Tensor, out: pypto.Tensor, scale: float) -> None: |
| 316 | """Simplified attention mechanism.""" | 316 | """Simplified attention mechanism.""" |
| 317 | pypto.set_cube_tile_shapes([64, 64], [64, 64], [64, 64]) | 317 | pypto.set_cube_tile_shapes([64, 64], [64, 64], [64, 64]) |
| 318 | 318 | ||
| @@ -331,7 +331,7 @@ def attention_kernel_npu(q: pypto.tensor, k: pypto.tensor, v: pypto.tensor, out: | |||
| 331 | 331 | ||
| 332 | 332 | ||
| 333 | @pypto.jit(runtime_options={"run_mode": 1}) | 333 | @pypto.jit(runtime_options={"run_mode": 1}) |
| 334 | -def attention_kernel_sim(q: pypto.tensor, k: pypto.tensor, v: pypto.tensor, out: pypto.tensor, scale: float) -> None: | 334 | +def attention_kernel_sim(q: pypto.Tensor, k: pypto.Tensor, v: pypto.Tensor, out: pypto.Tensor, scale: float) -> None: |
| 335 | """Simplified attention mechanism.""" | 335 | """Simplified attention mechanism.""" |
| 336 | pypto.set_cube_tile_shapes([64, 64], [64, 64], [64, 64]) | 336 | pypto.set_cube_tile_shapes([64, 64], [64, 64], [64, 64]) |
| 337 | 337 | ||
| @@ -349,7 +349,7 @@ def attention_kernel_sim(q: pypto.tensor, k: pypto.tensor, v: pypto.tensor, out: | |||
| 349 | out[:] = pypto.matmul(attn_weights, v, out_dtype=out.dtype) | 349 | out[:] = pypto.matmul(attn_weights, v, out_dtype=out.dtype) |
| 350 | 350 | ||
| 351 | 351 | ||
| 352 | -def attention(q: torch.Tensor, k: torch.Tensor, | 352 | +def attention(q: torch.Tensor, k: torch.Tensor, |
| 353 | v: torch.Tensor, scale: float, | 353 | v: torch.Tensor, scale: float, |
| 354 | run_mode: str = "npu", dynamic: bool = False) -> torch.Tensor: | 354 | run_mode: str = "npu", dynamic: bool = False) -> torch.Tensor: |
| 355 | y = torch.empty_like(q) | 355 | y = torch.empty_like(q) |
| @@ -546,7 +546,7 @@ def test_function_reuse(device_id = None, run_mode: str = "npu", dynamic: bool = | |||
| 546 | out3 = layer_norm(x3, gamma, beta, run_mode, dynamic) | 546 | out3 = layer_norm(x3, gamma, beta, run_mode, dynamic) |
| 547 | if run_mode == "npu": | 547 | if run_mode == "npu": |
| 548 | torch.npu.synchronize() | 548 | torch.npu.synchronize() |
| 549 | - | 549 | + |
| 550 | 550 | ||
| 551 | # Verify | 551 | # Verify |
| 552 | expected1 = layer_norm_golden(x1, gamma, beta, 1e-6) | 552 | expected1 = layer_norm_golden(x1, gamma, beta, 1e-6) |
| @@ -119,7 +119,7 @@ class IndexerPrologQuantConfigs: | |||
| 119 | vec_nbuffer_mode: int | 119 | vec_nbuffer_mode: int |
| 120 | 120 | ||
| 121 | 121 | ||
| 122 | -def quant_layer_norm(x: pypto.tensor, gamma: pypto.tensor, beta: pypto.tensor, dim: int, epsilon: float): | 122 | +def quant_layer_norm(x: pypto.Tensor, gamma: pypto.Tensor, beta: pypto.Tensor, dim: int, epsilon: float): |
| 123 | """Compute quantized LayerNorm operation. | 123 | """Compute quantized LayerNorm operation. |
| 124 | 124 | ||
| 125 | Applies Layer Normalization with quantization support. The function normalizes | 125 | Applies Layer Normalization with quantization support. The function normalizes |
| @@ -165,7 +165,7 @@ def quant_layer_norm(x: pypto.tensor, gamma: pypto.tensor, beta: pypto.tensor, d | |||
| 165 | return pypto.cast((res32 * gamma32) + beta32, x_dtype) | 165 | return pypto.cast((res32 * gamma32) + beta32, x_dtype) |
| 166 | 166 | ||
| 167 | 167 | ||
| 168 | -def quant_rope_2d(x: pypto.tensor, cos: pypto.tensor, sin: pypto.tensor): | 168 | +def quant_rope_2d(x: pypto.Tensor, cos: pypto.Tensor, sin: pypto.Tensor): |
| 169 | """Apply 2D Rotary Position Embedding (RoPE) to input tensor. | 169 | """Apply 2D Rotary Position Embedding (RoPE) to input tensor. |
| 170 | 170 | ||
| 171 | Implements RoPE transformation for 2D tensors. RoPE encodes positional | 171 | Implements RoPE transformation for 2D tensors. RoPE encodes positional |
| @@ -202,7 +202,7 @@ def quant_rope_2d(x: pypto.tensor, cos: pypto.tensor, sin: pypto.tensor): | |||
| 202 | return res | 202 | return res |
| 203 | 203 | ||
| 204 | 204 | ||
| 205 | -def prolog_quant(input: pypto.tensor): | 205 | +def prolog_quant(x: pypto.Tensor): |
| 206 | """Perform per-token quantization to INT8. | 206 | """Perform per-token quantization to INT8. |
| 207 | 207 | ||
| 208 | Quantizes the input tensor to INT8 format using dynamic quantization. | 208 | Quantizes the input tensor to INT8 format using dynamic quantization. |
| @@ -229,7 +229,7 @@ def prolog_quant(input: pypto.tensor): | |||
| 229 | pypto.set_semantic_label("Prolog-Quant") | 229 | pypto.set_semantic_label("Prolog-Quant") |
| 230 | s8_max_value = 127.0 | 230 | s8_max_value = 127.0 |
| 231 | s8_one_value = 1.0 | 231 | s8_one_value = 1.0 |
| 232 | - input_fp32 = pypto.cast(input, pypto.DT_FP32, pypto.CastMode.CAST_NONE) | 232 | + input_fp32 = pypto.cast(x, pypto.DT_FP32, pypto.CastMode.CAST_NONE) |
| 233 | 233 | ||
| 234 | abs_res = pypto.abs(input_fp32) | 234 | abs_res = pypto.abs(input_fp32) |
| 235 | max_value = pypto.amax(abs_res, dim=-1, keepdim=True) | 235 | max_value = pypto.amax(abs_res, dim=-1, keepdim=True) |
| @@ -245,7 +245,7 @@ def prolog_quant(input: pypto.tensor): | |||
| 245 | return (out_int8, scale_dequant) | 245 | return (out_int8, scale_dequant) |
| 246 | 246 | ||
| 247 | 247 | ||
| 248 | -def rotate_half(input_tensor: pypto.tensor) -> pypto.tensor: | 248 | +def rotate_half(input_tensor: pypto.Tensor) -> pypto.Tensor: |
| 249 | """Rotate half of the tensor dimensions for RoPE computation. | 249 | """Rotate half of the tensor dimensions for RoPE computation. |
| 250 | 250 | ||
| 251 | Splits the last dimension in half and applies rotation transformation: | 251 | Splits the last dimension in half and applies rotation transformation: |
| @@ -279,7 +279,7 @@ def rotate_half(input_tensor: pypto.tensor) -> pypto.tensor: | |||
| 279 | return pypto.concat([x2 * (-1.0), x1 + 0.0], -1) | 279 | return pypto.concat([x2 * (-1.0), x1 + 0.0], -1) |
| 280 | 280 | ||
| 281 | 281 | ||
| 282 | -def rope_3d(x: pypto.tensor, cos: pypto.tensor, sin: pypto.tensor, configs: IndexerPrologQuantConfigs) -> pypto.tensor: | 282 | +def rope_3d(x: pypto.Tensor, cos: pypto.Tensor, sin: pypto.Tensor, configs: IndexerPrologQuantConfigs) -> pypto.Tensor: |
| 283 | """Apply 3D Rotary Position Embedding (RoPE) to input tensor. | 283 | """Apply 3D Rotary Position Embedding (RoPE) to input tensor. |
| 284 | 284 | ||
| 285 | Implements RoPE transformation for 3D tensors with shape (t_tile, head_num, rope_dim). | 285 | Implements RoPE transformation for 3D tensors with shape (t_tile, head_num, rope_dim). |