Commit Graph
8 Commits
Author SHA1 Message Date
Xuyang LiandClaude Opus 4.8 3953e4b5fc [BugFix] Reject T.alloc_barrier() on pre-Hopper targets with a clear error (#2345)
LowerSharedBarrier lowers T.alloc_barrier() to hardware mbarrier code (the
cutlass Barrier type, tl::tl_shuffle_elect, tl::fence_barrier_init), all of
which only exist on sm_90+. On pre-Hopper targets (e.g. sm_86) the frontend
accepted the call silently and nvcc later failed with cryptic
"identifier 'Barrier' is undefined" / "namespace 'tl' has no member ..."
errors.

Add a static compute-capability guard in CUDAPassPipelineBody, before
LowerSharedBarrier: if the target is < sm_90 and the module uses a shared
barrier, raise a clear ValueError naming the offending primitives and pointing
to __syncthreads()/named barriers as the pre-Hopper alternative.

Fixes the sm_86 alloc_barrier compile crash.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-07 23:07:22 +08:00
Zhang JasonandLeiWang1999 3d95d65000 [AMD][RDNA4] Fix gfx12 (RDNA 4 / Wave32) related CI issues (#2313)
* [AMD][RDNA4] Fix RDNA4 (gfx1201 / Wave32) CI failures

- reduce.h: Replace hardcoded wave64 assumptions with runtime
  __builtin_amdgcn_wavefrontsize() in SharedReduceWarp and AllReduce
- scan.h: Add SEG=32 support in InclusiveScan/CumSum/CumMax for RDNA wave32
- finalize_reducer.cc: Use TargetGetWarpSize() instead of hardcoded 64
- carver/arch/__init__.py + rdna.py: Add gfx12 (RDNA4) support alongside gfx11
- wmma_macro_generator.py: Fix k_pack indexing in ldmatrix_a/b for k_pack > 1

These changes correspond to PR #2210 (Fix RDNA4 gfx1201/Wave32 CI Failures),
rebased cleanly onto upstream main (a8d93798).

* [AMD][HIP] Fix HIPMath dispatch for vector dtype in T.Parallel

When BLOCK_M > threads, TileLang generates vector types (e.g. float32x4)
for T.Parallel loops. HIPMath::operator() only handled scalar types, so
vector dtypes fell through to return  causing Unresolved call errors
in codegen for math intrinsics like tirx.exp2.

Fix: add a vector-type early-return that recurses on element_of(), so
float32xN correctly resolves to exp2f the same as scalar float32.

This complements the tirx.* registration fixes in #2282 and enables
Online Softmax on gfx1151 with BM > threads (e.g. BM=1024, TH=256).

* [Review] Fix 3 issues found in code review

1. tilelang/carver/arch/__init__.py: error message was not updated
   when gfx12 support was added — still said gfx11 only. Now says
   gfx11/gfx12 targets only, consistent with rdna.py.

2. src/tl_templates/hip/reduce.h: the static_assert(Threads % kWarpSize == 0)
   was removed when kWarpSize became a runtime value, leaving no safety
   check. Added equivalent runtime assert().

3. src/tl_templates/hip/scan.h: run_auto() else branch silently fell
   through to SEG=64 for any non-32 wavefront size. Added assert to
   catch unsupported wavefront sizes early.

* update codes for format checking

* [Review] Address review feedback and rebase on upstream main

- intrin_rule_hip.cc: remove redundant HIPMath scalar recursion; upstream
  PR #2286 already handles vector dtypes via DispatchPureExternScalarized
  at the IR level (correct for HIP packed carrier types)
- wmma_macro_generator.py: rename l/r to row_off/col_off to fix Ruff E741
  ambiguous variable name warnings
- scan.h: guard run_auto() branches with threads>=32 / threads>=64 so a
  threads==32 kernel on Wave64 doesn't compute TILE=0 and divide by zero
- reduce.h: replace assert (stripped in Release) with unconditional early
  return when Threads % kWarpSize != 0, preventing silent num_warps==0

* update codes for format checking

* fix

---------

Co-authored-by: LeiWang1999 <leiwang1999@outlook.com>
2026-06-03 11:20:30 +08:00
Lei Wang 146a1d3bef [TileOP] Add scan operators (#2262)
Add TileLang scan operators
2026-05-25 17:41:10 +08:00
a84c9b1433 [CuTeDSL] Integrate host codegen call sites (#2221)
[CuTeDSL] Integrate host codegen call sites

Drive CuTeDSL launcher generation from lowered host tvm_call_packed call sites so multi-kernel wrappers preserve host IR order and repeated launches can be represented.

Expose separate device, host, and generated module sources through the CuTeDSL adapter and persist them separately in the kernel/autotune caches.

Normalize bare cutedsl targets through TileLang CUDA arch detection so Hopper runners use sm_90a for CuTeDSL compilation instead of the generic sm_90 Target("cuda") result.

Add CuTeDSL host-codegen integration tests covering multi-call launcher ordering, source accessors, cache restore behavior, and bare target architecture normalization.

Co-authored-by: Jayce <jayce.su@enflame-tech.com>
Co-authored-by: LeiWang1999 <leiwang1999@outlook.com>
2026-05-21 20:28:41 +08:00
b939fa0137 [TIR][IR] Update to use tirx (#2216)
* [Feature] Implement Hoist Loop-Invariant If Pass

- Added a new pass to hoist loop-invariant if statements out of loops, improving optimization opportunities.
- Introduced classes for collecting and checking conditions, as well as for rewriting statements.
- Integrated the new pass into the optimization pipeline and provided a corresponding API for usage.

* Add tilelang semantics guide to programming guides (#1740)

* Add CallNodeChecker to Loop Unswitching Pass and integrate tilelang cache disabling in benchmark script

- Introduced CallNodeChecker class to identify CallNode expressions in loop conditions, enhancing loop-invariant checks.
- Updated IsLoopInvariant function to reject conditions containing CallNodes, preventing potential side effects.
- Added tilelang.disable_cache() in benchmark_mha_sink_fwd.py to optimize performance during benchmarking.

* lint fix

* lint fix

* Enhance Loop Unswitching Pass with Let Binding Support

- Added support for Let-bound variables in the WrittenBufferReadChecker to improve buffer read checks.
- Introduced UsesLoopVarThroughLetBindings function to check if conditions depend on loop variables through Let bindings.
- Updated IsLoopInvariant function to account for Let bindings when determining loop invariance.
- Enhanced HoistableIfFinder to track Let bindings for variables bound to BufferLoad expressions.
- Added debug print statements in the OptimizeForTarget function to visualize the module state before and after loop unswitching.

* fix

* lint fix

* Enhance Loop Unswitching with CallNode Exclusion Check

- Added CallCheckerExcludingIf class to ensure function calls outside of hoisted if statements are identified, preventing potential synchronization issues during loop unswitching.
- Updated loop unswitching logic to incorporate the new call checker, enhancing safety and correctness.
- Integrated debug print statements in OptimizeForTarget to visualize module state before and after loop unswitching.
- Disabled tilelang cache in the benchmark script for improved performance.

* Update TVM subproject to latest commit and remove debug print statements in OptimizeForTarget function

* Add support for disabling loop unswitching optimization

- Introduced a new configuration option `tl.disable_loop_unswitching` to allow users to disable the loop unswitching optimization.
- Updated the Loop Unswitching pass to check this configuration and return the original function if the option is enabled.
- Added relevant documentation in the PassConfigKey enumeration for clarity.

* update tvm

* Refactor: Update TileLang to use tirx instead of tir

- Removed references to `tvm.tir` and replaced them with `tvm.tirx` across various files, including examples and backend operations.
- Updated target configuration in documentation to reflect the new usage of target config dictionaries instead of CLI-style strings.
- Cleaned up `pyproject.toml` and `load_tvm.cmake` by removing obsolete paths.
- Enhanced examples for dequantization and GEMM operations to utilize the new `tirx` constructs.
- Adjusted various backend operations to ensure compatibility with the new `tirx` namespace.

* pass fix

* Update submodule 'tvm' to latest commit f24c7b19

* Apply formatting fixes

* Update CMakeLists.txt to set HIDE_PRIVATE_SYMBOLS for TileLang and modify target_host initialization in lower.py for compatibility with TVM's target handling.

* Refactor CMakeLists.txt and kernel_cache.py to update target names and library dependencies for TVM integration. Adjusted output targets and library names for better compatibility across platforms.

* Update repair-wheel-command in pyproject.toml to exclude libz3.so with wildcard for better compatibility with dependency packages.

* Fix macOS Z3 dylib lookup

* Move macOS Z3 install-name fix to install step

* Update TVM submodule for runtime import fix

* Update ROCm backend for TVM module factory changes

* Fix build-tree Z3 runtime lookup

* Fix macOS build-tree Z3 lookup

* Support legacy target option strings

* Normalize CUDA target in transform test

* Qualify Metal stream FFI lookup

* Fix PyPI Z3 packaging links

* Update TVM for Windows DLL lookup

* Register Windows dependency DLL directories

* Bump tvm-ffi to match tirx

* tvm update

* Apply lint fixes

* Enhance reduction operations with support for nan propagation and vectorization. Introduce new functions for preferred vectorized size and update existing reduction logic to handle packed operations for bfloat16 and float16 types. Add nan-aware min and max operations in CUDA and ROCm backends, and update related tests to validate functionality.

* Refactor ReduceLowerer: Remove unnecessary buffer allocation logic for packed operations in reduce.h

* Normalize PyPI Z3 dylib before linking

* Drop legacy target option string support

* Fix type reference for barrier annotations in CUDA copy operations. Updated `BufferLoadNode` to `tirx::BufferLoadNode` in `GetBarrier` and `LowerCluster` methods to ensure compatibility with recent changes in the TIR API.

---------

Co-authored-by: Yu Cheng <yu.cheng@pku.edu.cn>
Co-authored-by: Yichen Yan <oraluben@outlook.com>
2026-05-20 15:38:13 +08:00
Leonard c2a9d9872d [Fix][AMD] Fix Roller autotuner for RDNA3 WMMA targets (#2208)
* Tune RDNA WMMA Roller defaults

* Fix matmul Roller benchmark callback

* lint fix
2026-05-18 18:08:41 +08:00
Leonard d863f1d89d Add RDNA gfx1151 ROCm target support (#2127)
* Add RDNA gfx1151 ROCm target support

* Fix optional annotation handling for gfx1100

* Address CodeRabbit ROCm cleanup feedback

* Scope MFMA tests to CDNA targets

* Scope gfx950 copy async GEMM test

* Reject non-divisible warp layouts

* Skip CUDA/CDNA GEMM dtype tests on RDNA

* Scope RDNA device model to gfx11

* Use RDNA arch helper in block scoring

* Make RDNA tensor intrinsics generation-aware

* Exclude gfx1010 from SDOT4 guard

* Store RDNA tensor instructions as list

* Reject unsupported RDNA carver targets
2026-05-12 13:34:25 +08:00
Lei Wang 4929ad89cc [Refactor] Improve cp.async lowering and add async_copy op (#1887)
* Add CPAsync copy selection/lowering and vectorized ptx_cp_async folding

* [transform] Rename SimplifyCPAsyncSync to OptimizeCPAsyncSync

* ThreadSync: treat ptx_cp_async as async-copy

* Implement async_copy operator and enhance cp.async handling

- Introduced the async_copy operator for explicit asynchronous global-to-shared memory copies, ensuring no automatic waits are inserted.
- Updated the copy operator to normalize copy regions and handle both synchronous and asynchronous copy semantics.
- Enhanced pipeline planning to recognize explicit cp.async calls and bind commit and wait operations to the appropriate stages.
- Added tests to validate the behavior of async_copy and its integration with pipeline planning.

This commit improves the handling of asynchronous memory operations and clarifies the semantics of copy operations in the context of the new async_copy functionality.

* docs: clarify T.copy vs T.async_copy

* style: apply format.sh fixes

* async_copy: improve errors and defer cp.async check

* test: check T.copy vs T.async_copy codegen equivalence on SM80

* copy: allow predicated cp.async for OOB global->shared

* pipeline: schedule cp.async commits with cp.async groups

* lower: preserve manual pipeline statement arity

* pipeline: skip commit-order check when fused with cp.async

* pipeline: enforce cp.async ordering in PipelinePlanning

PipelinePlanning may float pure control intrinsics like ptx_commit_group earlier because they have no buffer regions, which can generate commit-before-cp_async.\n\nAdd an order-repair step that models cp.async group semantics (cp_async* -> commit, commit(group_i) -> cp_async(group_{i+1})) and wait->consumer constraints, then applies a stable topological sort to produce a valid software_pipeline_order.\n\nAlso adds a regression test to assert cp.async is ordered before commit when split into separate blocks.

* Enhance cp.async synchronization handling in pipeline planning

- Introduced logic to relax loop wait conditions and split epilogue waits for cp.async operations, improving overlap between consumer phases.
- Added a new method to identify and manage consumer phases based on async memory reads, ensuring correct synchronization.
- Updated tests to validate the new behavior, confirming that wait groups are correctly relaxed and inserted as needed in the optimized pipeline.

This commit refines the handling of cp.async synchronization, enhancing performance and correctness in the generated code.

* lint fix

* Refactor cp.async copy handling and improve vectorization logic

- Removed the unused IsCPAsyncElementBytes function to streamline the code.
- Enhanced the CPAsyncStoreRewriter class with a new method to track vectorized lanes during statement rewriting.
- Updated CheckCPAsyncCopy to remove the buffer_oob parameter, simplifying its signature.
- Added logging for vectorized loop iterations to aid in debugging and performance analysis.
- Improved error handling in LowerCPAsyncCopy to provide clearer warnings when cp.async rewrites fail.

These changes aim to optimize the cp.async copy process and improve code maintainability.

* lint fix

* Update cp.async copy handling to improve rewrite success tracking

- Set the successfully_rewritten_ flag to true when a copy operation is successfully rewritten.
- Adjust the flag to false in cases where the load is not global-like or the buffer is not shared.
- Removed logging for vectorized loop iterations to streamline the code.

These changes enhance the tracking of rewrite success in the cp.async copy process, contributing to better error handling and maintainability.

* fix

* test: cover commit-merge + wait relax

* fix: skip wait relaxation under conditional async copy

* test fix

* Implement async copy support in TileLang

- Introduced a new configuration option `tl.enable_async_copy` to control the lowering of global to shared memory copies to PTX `cp.async`.
- Updated the `CopyNode::LowerCPAsyncCopy` method to handle async copy semantics based on the new configuration.
- Enhanced the `InjectPTXAsyncCopy` pass to rewrite eligible global->shared copies into `cp.async`, including necessary commit and wait statements.
- Added tests to verify the correct behavior of async copy lowering and the impact of the configuration option.

These changes improve the flexibility and performance of memory copy operations in TileLang.

* lint fix

* Refactor async copy handling in TileLang

- Renamed `InjectPTXAsyncCopy` to `LowerPTXAsyncCopy` to better reflect its functionality.
- Updated the `OptimizeForTarget` function to use `LowerPTXAsyncCopy` instead of the deprecated `InjectPTXAsyncCopy`.
- Added a deprecated alias for `InjectPTXAsyncCopy` to maintain backward compatibility.
- Adjusted documentation to clarify the purpose of the new function name.

These changes enhance clarity and maintainability in the async copy transformation process.

* fix

* lint fix

* test fix

* Enhance PTX async copy integration in TileLang

- Added the `InjectPTXAsyncCopy` function to facilitate the injection of PTX `cp.async` operations into the lowering process.
- Updated the `LowerTileOp` function to conditionally apply `InjectPTXAsyncCopy` during parallel loop lowering when async copy is enabled.
- Removed deprecated calls to `LowerPTXAsyncCopy` in the `OptimizeForTarget` function to streamline the optimization process.

These changes improve the handling of async copy operations, ensuring better performance and compatibility with CUDA targets.

* lint fix

* fix

* fix

* fix

* set parallisim to 1 to test the ci

* fix

* Refactor async copy handling in PTX lowering

- Improved the `PrepareCopyIndexInfo` function to clarify the calculation of transfer bytes and ensure valid async copy operations.
- Updated synchronization state management for injected `cp.async` transfers, enhancing clarity and consistency in handling open copy regions and uncommitted transfers.
- Added helper functions for zero value checks and linear offset flattening to streamline index processing.

These changes enhance the robustness and readability of the async copy implementation.

* Refactor nested pipeline functions and update test cases

- Removed unused parameters `order` and `stage` from several functions, simplifying their signatures.
- Updated nested pipeline implementations to use `num_stages=2` for better clarity and performance.
- Adjusted test cases to reflect the changes in function signatures, ensuring they run correctly without the removed parameters.

These modifications enhance code readability and maintainability while ensuring the tests remain functional.

* Refactor async copy statement generation in PTX lowering

- Updated the `MakeCPAsyncStmt` function to `MakeCPAsyncStmtFromLoads`, improving the handling of base indices for vectorized accesses.
- Introduced `ExtractVectorBaseIndices` to streamline the extraction of base indices from vectorized loads and stores.
- Enhanced error handling for predicated async copy operations when base indices cannot be extracted.

These changes improve the clarity and robustness of async copy statement generation in the PTX lowering process.

* lint fix

* Enhance async copy operation handling in CodeGenTileLangCuTeDSL

- Added support for conditional async copy operations in the `VisitExpr_` method, allowing for an optional predicate argument.
- Improved error checking to ensure the correct number of arguments for `tl::ptx_cp_async`.
- Streamlined the generation of async copy statements for both standard and conditional cases.

These updates improve the flexibility and robustness of async copy operations in the code generation process.ix

* lint fix

* disable auto cp async without pipeline.

* lint fix

* Enhance cp.async synchronization handling in TileLang

- Introduced `ThreadSyncAfterWaitGroupInserter` to ensure correct insertion of storage synchronization after `ptx_wait_group` statements, addressing potential visibility issues in shared memory.
- Updated `WarpSpecialized` to utilize `tl.ptx_cp_async_barrier_noinc` for releasing producer-consumer dependencies, preventing incomplete memory observations.
- Added tests to verify the correct insertion of synchronization and the handling of cp.async barriers under warp specialization.

These changes improve the correctness and reliability of async copy operations in the TileLang transformation pipeline.

* fix

* fix

* test fix

* Refactor sparse_mla_fwd_pipelined.py and enhance phase.py synchronization

- Removed unused post-processing function and related code from `sparse_mla_fwd_pipelined.py` to streamline the implementation.
- Added debug print statements in `phase.py` to log the state of the module before and after thread synchronization, aiding in troubleshooting and verification of synchronization behavior.

* Enhance async copy handling and loop synchronization in TileLang

- Introduced new loop annotations for async copy operations, including `parallel_prefer_async` and `parallel_async_without_async_commit_wait`, to improve control over async behavior in parallel loops.
- Updated the `InjectPTXAsyncCopy` function to accommodate the new annotations, ensuring correct async copy injection based on user-defined preferences.
- Enhanced the pipeline planning logic to prioritize cp.async groups by their earliest consumers, improving scheduling efficiency and reducing wait times.
- Added tests to validate the new async copy behaviors and ensure correct synchronization in pipelined loops.

These changes enhance the flexibility and performance of async copy operations in the TileLang transformation pipeline.

* lint fix

* Add Regression Perf for mhc

* clean

* clean

* lint fix

* lint fix
2026-03-06 17:35:16 +08:00