You are viewing a plain text version of this content. The canonical link for it is here.
Posted to discuss-archive@tvm.apache.org by "junrushao (via GitHub)" <gi...@apache.org> on 2026/02/06 10:31:38 UTC
[PR] doc: Update Kernel Library Guide [tvm-ffi]
junrushao opened a new pull request, #431:
URL: https://github.com/apache/tvm-ffi/pull/431
(no comment)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org
Re: [PR] doc: Update Kernel Library Guide [tvm-ffi]
Posted by "junrushao (via GitHub)" <gi...@apache.org>.
junrushao commented on PR #431:
URL: https://github.com/apache/tvm-ffi/pull/431#issuecomment-3861807966
/gemini review
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org
Re: [PR] doc: Update Kernel Library Guide [tvm-ffi]
Posted by "gemini-code-assist[bot] (via GitHub)" <gi...@apache.org>.
gemini-code-assist[bot] commented on code in PR #431:
URL: https://github.com/apache/tvm-ffi/pull/431#discussion_r2775345098
##########
docs/conf.py:
##########
@@ -92,11 +92,8 @@
TVM_FFI_EXTRA_CXX_API= TVM_FFI_WEAK= TVM_FFI_DOXYGEN_MODE \
__cplusplus=201703
EXCLUDE_SYMBOLS += *details* *TypeTraits* std \
- *use_default_type_traits_v* *is_optional_type_v* *operator* \
- TVM_FFI_LOG_EXCEPTION_CALL_BEGIN TVM_FFI_LOG_EXCEPTION_CALL_END \
- TVM_FFI_CLEAR_PTR_PADDING_IN_FFI_ANY TVM_FFI_STATIC_INIT_BLOCK \
- TVM_FFI_STATIC_INIT_BLOCK_DEF_ TVM_FFI_DEFINE_DEFAULT_COPY_MOVE_AND_ASSIGN
-EXCLUDE_PATTERNS += *details.h *internal*
+ *use_default_type_traits_v* *is_optional_type_v* *operator*
Review Comment:

This change removes several internal macros like `TVM_FFI_LOG_EXCEPTION_CALL_BEGIN`, `TVM_FFI_STATIC_INIT_BLOCK_DEF_`, etc., from the `EXCLUDE_SYMBOLS` list. These macros are defined in `base_details.h` and seem to be internal implementation details, some of which are suppressed from Doxygen. Exposing them in the public API documentation could be confusing. It seems only `TVM_FFI_STATIC_INIT_BLOCK` is intended to be documented. I'd suggest keeping the other internal macros excluded to avoid cluttering the public API docs.
##########
include/tvm/ffi/base_details.h:
##########
@@ -101,12 +99,14 @@
* }
* \endcode
*/
+#define TVM_FFI_STATIC_INIT_BLOCK()
+#elif defined(__GNUC__)
+// gcc and clang: attribute constructor
+#define TVM_FFI_STATIC_INIT_BLOCK_DEF_(FnName) __attribute__((constructor)) static void FnName()
#define TVM_FFI_STATIC_INIT_BLOCK() \
TVM_FFI_STATIC_INIT_BLOCK_DEF_(TVM_FFI_STR_CONCAT(__TVMFFIStaticInitFunc, __COUNTER__))
-
#else
Review Comment:

This refactoring seems to have unintentionally exposed internal implementation macros to Doxygen. Specifically, `TVM_FFI_STATIC_INIT_BLOCK_DEF_` for both GCC and other compilers are now outside of a `\cond Doxygen_Suppress` block. These are internal details and should not be part of the public documentation. Please consider wrapping the implementation part (from `#elif` to `#endif`) in a suppression block.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org
Re: [PR] doc: Update Kernel Library Guide [tvm-ffi]
Posted by "tqchen (via GitHub)" <gi...@apache.org>.
tqchen commented on code in PR #431:
URL: https://github.com/apache/tvm-ffi/pull/431#discussion_r2773955916
##########
docs/guides/kernel_library_guide.rst:
##########
@@ -15,180 +15,343 @@
.. specific language governing permissions and limitations
.. under the License.
-====================
Kernel Library Guide
====================
-This guide serves as a quick start for shipping kernel libraries with TVM FFI. The shipped kernel libraries are of python version and ML framework agnostic. With the help of TVM FFI, we can connect the kernel libraries to multiple ML framework, such as PyTorch, XLA, JAX, together with the minimal efforts.
+This guide covers shipping C++/CUDA kernel libraries with TVM-FFI. The resulting
+libraries are agnostic to Python version and ML framework — a single ``.so`` works
+with PyTorch, JAX, PaddlePaddle, NumPy, and more.
-Tensor
-======
+.. seealso::
-Almost all kernel libraries are about tensor computation and manipulation. For better adaptation to different ML frameworks, TVM FFI provides a minimal set of data structures to represent tensors from ML frameworks, including the tensor basic attributes and storage pointer.
-To be specific, in TVM FFI, two types of tensor constructs, :cpp:class:`~tvm::ffi::Tensor` and :cpp:class:`~tvm::ffi::TensorView`, can be used to represent a tensor from ML frameworks.
+ - :doc:`../get_started/quickstart`: End-to-end walkthrough of a simpler ``add_one`` kernel
+ - :doc:`../packaging/cpp_tooling`: Build toolchain, CMake integration, and library distribution
+ - All example code in this guide is under
+ `examples/kernel_library/ <https://github.com/apache/tvm-ffi/tree/main/examples/kernel_library>`_.
-Tensor and TensorView
----------------------
-Both :cpp:class:`~tvm::ffi::Tensor` and :cpp:class:`~tvm::ffi::TensorView` are designed to represent tensors from ML frameworks that interact with the TVM FFI ABI. They are backed by the `DLTensor` in DLPack in practice. The main difference is whether it is an owning tensor structure.
+Anatomy of a Kernel Function
+-----------------------------
-:cpp:class:`tvm::ffi::Tensor`
- :cpp:class:`~tvm::ffi::Tensor` is a completely owning tensor with reference counting. It can be created on either C++ or Python side and passed between either side. And TVM FFI internally keeps a reference count to track lifetime of the tensors. When the reference count goes to zero, its underlying deleter function will be called to free the tensor storage.
+Every TVM-FFI CUDA kernel follows the same sequence:
-:cpp:class:`tvm::ffi::TensorView`
- :cpp:class:`~tvm::ffi::TensorView` is a non-owning view of an existing tensor, pointing to an existing tensor (e.g., a tensor allocated by PyTorch).
+1. **Validate** inputs (device, dtype, shape, contiguity)
+2. **Set device guard** to match the tensor's device
+3. **Acquire stream** from the host framework
+4. **Dispatch** on dtype and **launch** the kernel
-It is **recommended** to use :cpp:class:`~tvm::ffi::TensorView` when possible, that helps us to support more cases, including cases where only view but not strong reference are passed, like XLA buffer. It is also more lightweight. However, since :cpp:class:`~tvm::ffi::TensorView` is a non-owning view, it is the user's responsibility to ensure the lifetime of underlying tensor.
+Here is a complete ``Scale`` kernel that computes ``y = x * factor``:
-Tensor Attributes
------------------
+.. literalinclude:: ../../examples/kernel_library/scale_kernel.cu
+ :language: cpp
+ :start-after: [function.begin]
+ :end-before: [function.end]
-For convenience, :cpp:class:`~tvm::ffi::TensorView` and :cpp:class:`~tvm::ffi::Tensor` align the following attributes retrieval mehtods to :cpp:class:`at::Tensor` interface, to obtain tensor basic attributes and storage pointer:
-``dim``, ``dtype``, ``sizes``, ``size``, ``strides``, ``stride``, ``numel``, ``data_ptr``, ``device``, ``is_contiguous``
+The CUDA kernel itself is a standard ``__global__`` function:
-Please refer to the documentation of both tensor classes for their details. Here highlight some non-primitive attributes:
+.. literalinclude:: ../../examples/kernel_library/scale_kernel.cu
+ :language: cpp
+ :start-after: [cuda_kernel.begin]
+ :end-before: [cuda_kernel.end]
-:c:struct:`DLDataType`
- The ``dtype`` of the tensor. It's represented by a struct with three fields: code, bits, and lanes, defined by DLPack protocol.
+The following subsections break down each step.
-:c:struct:`DLDevice`
- The ``device`` where the tensor is stored. It is represented by a struct with two fields: device_type and device_id, defined by DLPack protocol.
-:cpp:class:`tvm::ffi::ShapeView`
- The ``sizes`` and ``strides`` attributes retrieval are returned as :cpp:class:`~tvm::ffi::ShapeView`. It is an iterate-able data structure storing the shapes or strides data as ``int64_t`` array.
+Input Validation
+~~~~~~~~~~~~~~~~
-Tensor Allocation
------------------
+Kernel functions should validate inputs early and fail with clear error messages.
+A common pattern is to define reusable ``CHECK_*`` macros on top of
+:c:macro:`TVM_FFI_CHECK` (see :doc:`../concepts/exception_handling`):
+
+.. literalinclude:: ../../examples/kernel_library/tvm_ffi_utils.h
+ :language: cpp
+ :start-after: [check_macros.begin]
+ :end-before: [check_macros.end]
+
+For **user-facing errors** (bad arguments, unsupported dtypes, shape mismatches),
+use :c:macro:`TVM_FFI_THROW` or :c:macro:`TVM_FFI_CHECK` with a specific error kind
+so that callers receive an actionable message:
+
+.. code-block:: cpp
+
+ TVM_FFI_THROW(TypeError) << "Unsupported dtype: " << input.dtype();
+ TVM_FFI_CHECK(input.numel() > 0, ValueError) << "input must be non-empty";
+ TVM_FFI_CHECK(input.numel() == output.numel(), ValueError) << "size mismatch";
+
+For **internal invariants** that indicate bugs in the kernel itself, use
+:c:macro:`TVM_FFI_ICHECK`:
+
+.. code-block:: cpp
+
+ TVM_FFI_ICHECK_GE(n, 0) << "element count must be non-negative";
+
+
+Device Guard and Stream
+~~~~~~~~~~~~~~~~~~~~~~~
+
+Before launching a CUDA kernel, two things must happen:
+
+1. **Set the CUDA device** to match the tensor's device. :cpp:class:`tvm::ffi::CUDADeviceGuard`
+ is an RAII guard that calls ``cudaSetDevice`` on construction and restores the
+ original device on destruction.
+
+2. **Acquire the stream** from the host framework via :cpp:func:`TVMFFIEnvGetStream`.
+ When Python code calls a kernel with PyTorch tensors, TVM-FFI automatically
+ captures PyTorch's current stream for the tensor's device.
+
+A small helper keeps this concise:
+
+.. literalinclude:: ../../examples/kernel_library/tvm_ffi_utils.h
+ :language: cpp
+ :start-after: [get_stream.begin]
+ :end-before: [get_stream.end]
+
+Every kernel function then follows the same two-line pattern:
+
+.. code-block:: cpp
+
+ ffi::CUDADeviceGuard guard(input.device().device_id);
+ cudaStream_t stream = get_cuda_stream(input.device());
+
+See :doc:`../concepts/tensor` for details on stream handling and automatic stream
+context updates.
-TVM FFI provides several methods to create or allocate tensors at C++ runtime. Generally, there are two types of tensor creation methods:
-* Allocate a tensor with new storage from scratch, i.e. :cpp:func:`~tvm::ffi::Tensor::FromEnvAlloc` and :cpp:func:`~tvm::ffi::Tensor::FromNDAlloc`. By this types of methods, the shapes, strides, data types, devices and other attributes are required for the allocation.
-* Create a tensor with existing storage following DLPack protocol, i.e. :cpp:func:`~tvm::ffi::Tensor::FromDLPack` and :cpp:func:`~tvm::ffi::Tensor::FromDLPackVersioned`. By this types of methods, the shapes, data types, devices and other attributes can be inferred from the DLPack attributes.
+Dtype Dispatch
+~~~~~~~~~~~~~~
-FromEnvAlloc
-^^^^^^^^^^^^
+Kernels typically support multiple dtypes. Dispatch on :c:struct:`DLDataType` at
+runtime while instantiating templates at compile time:
-To better adapt to the ML framework, it is **recommended** to reuse the framework tensor allocator anyway, instead of directly allocating the tensors via CUDA runtime API, like ``cudaMalloc``. Since reusing the framework tensor allocator:
+.. code-block:: cpp
-* Benefit from the framework's native caching allocator or related allocation mechanism.
-* Help framework tracking memory usage and planning globally.
+ constexpr DLDataType dl_float32 = DLDataType{kDLFloat, 32, 1};
+ constexpr DLDataType dl_float16 = DLDataType{kDLFloat, 16, 1};
-TVM FFI provides :cpp:func:`tvm::ffi::Tensor::FromEnvAlloc` to allocate a tensor with the framework tensor allocator. To determine which framework tensor allocator, TVM FFI infers it from the passed-in framework tensors. For example, when calling the kernel library at Python side, there is an input framework tensor if of type ``torch.Tensor``, TVM FFI will automatically bind the :cpp:func:`at::empty` as the current framework tensor allocator by ``TVMFFIEnvTensorAlloc``. And then the :cpp:func:`~tvm::ffi::Tensor::FromEnvAlloc` is calling the :cpp:class:`at::empty` actually:
+ if (input.dtype() == dl_float32) {
+ ScaleKernel<<<blocks, threads, 0, stream>>>(
+ static_cast<float*>(output.data_ptr()), ...);
+ } else if (input.dtype() == dl_float16) {
+ ScaleKernel<<<blocks, threads, 0, stream>>>(
+ static_cast<half*>(output.data_ptr()), ...);
+ } else {
+ TVM_FFI_THROW(TypeError) << "Unsupported dtype: " << input.dtype();
+ }
-.. code-block:: c++
+For libraries that support many dtypes, define dispatch macros
+(see `FlashInfer's tvm_ffi_utils.h <https://github.com/flashinfer-ai/flashinfer/blob/main/csrc/tvm_ffi_utils.h>`_
+for a production example).
- ffi::Tensor tensor = ffi::Tensor::FromEnvAlloc(TVMFFIEnvTensorAlloc, ...);
-which is equivalent to:
+Export and Load
+---------------
-.. code-block:: c++
+Export and Build
+~~~~~~~~~~~~~~~~
- at::Tensor tensor = at::empty(...);
+**Export.** Use :c:macro:`TVM_FFI_DLL_EXPORT_TYPED_FUNC` to create a C symbol
+that follows the :doc:`TVM-FFI calling convention <../concepts/func_module>`:
-FromNDAlloc
-^^^^^^^^^^^
+.. literalinclude:: ../../examples/kernel_library/scale_kernel.cu
+ :language: cpp
+ :start-after: [export.begin]
+ :end-before: [export.end]
-:cpp:func:`tvm::ffi::Tensor::FromNDAlloc` can be used to create a tensor with custom memory allocator. It is of simple usage by providing a custom memory allocator and deleter for tensor allocation and free each, rather than relying on any framework tensor allocator.
+This creates a symbol ``__tvm_ffi_scale`` in the shared library. For larger
+projects, a common pattern is to keep kernel implementations and export
+declarations in **separate files** — an implementation file and a binding file:
Review Comment:
generally we don't need declarations, not sure where this guideline is useful
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org
Re: [PR] doc: Update Kernel Library Guide [tvm-ffi]
Posted by "junrushao (via GitHub)" <gi...@apache.org>.
junrushao merged PR #431:
URL: https://github.com/apache/tvm-ffi/pull/431
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org
Re: [PR] doc: Update Kernel Library Guide [tvm-ffi]
Posted by "gemini-code-assist[bot] (via GitHub)" <gi...@apache.org>.
gemini-code-assist[bot] commented on PR #431:
URL: https://github.com/apache/tvm-ffi/pull/431#issuecomment-3859522809
## Summary of Changes
Hello @junrushao, I'm Gemini Code Assist[^1]! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!
This pull request significantly enhances the TVM-FFI documentation by overhauling the Kernel Library Guide. The guide has been transformed into a practical, step-by-step tutorial, complete with new, concrete C++/CUDA kernel examples and helper utilities. These changes aim to provide developers with clearer instructions and best practices for integrating custom kernels, making the process more accessible and robust.
### Highlights
* **Kernel Library Guide Overhaul**: The `Kernel Library Guide` has been completely rewritten to provide a more practical, example-driven tutorial for developing C++/CUDA kernels with TVM-FFI. It now covers the anatomy of a kernel function, best practices for input validation, device and stream management, dtype dispatch, and tensor handling.
* **New Example Kernel and Utilities**: A new comprehensive `Scale` kernel example (`scale_kernel.cu`) has been added, demonstrating the concepts discussed in the updated guide. This is complemented by a new utility header (`tvm_ffi_utils.h`) providing reusable macros for input validation, stream handling, and tensor allocation.
* **Improved Documentation Generation**: Doxygen configuration has been updated in `docs/conf.py` to refine symbol and pattern exclusions, leading to cleaner and more focused generated documentation. Minor adjustments were also made to static initialization block macros in `base_details.h`.
🧠 **New Feature in Public Preview:** You can now enable **Memory** to help **Gemini Code Assist** learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. **Click [here](https://codeassist.google/code-review/login) to enable Memory in your admin console.**
<details>
<summary><b>Changelog</b></summary>
* **docs/conf.py**
* Updated `EXCLUDE_SYMBOLS` to remove specific FFI-related macros from Doxygen documentation.
* Modified `EXCLUDE_PATTERNS` to target specific detail headers (`function_details.h`, `container_details.h`) for exclusion.
* **docs/guides/kernel_library_guide.rst**
* Rewrote the entire guide to focus on practical kernel development, including sections on input validation, device/stream management, dtype dispatch, and tensor handling.
* Added `seealso` links to related documentation and example code.
* Incorporated detailed code examples and best practices for `TensorView` vs `Tensor` usage and tensor allocation strategies.
* Introduced a 'Further Reading' section with links to other core TVM-FFI concepts.
* **examples/kernel_library/load_scale.py**
* Added a new Python script demonstrating how to load a compiled kernel library and call a `Scale` function with PyTorch tensors.
* **examples/kernel_library/scale_kernel.cu**
* Added a new C++/CUDA file implementing a `Scale` kernel, showcasing input validation, device guard, stream acquisition, dtype dispatch, and FFI export.
* **examples/kernel_library/tvm_ffi_utils.h**
* Added a new utility header containing reusable macros for input validation (`CHECK_CUDA`, `CHECK_CONTIGUOUS`, `CHECK_DIM`, `CHECK_DEVICE`).
* Included helper functions for CUDA stream acquisition (`get_cuda_stream`) and framework-aware tensor allocation (`alloc_tensor`).
* Defined common DLPack `DLDataType` constants for convenience.
* **include/tvm/ffi/base_details.h**
* Refactored the `TVM_FFI_STATIC_INIT_BLOCK` macro definitions, potentially improving documentation generation or compiler compatibility.
</details>
<details>
<summary><b>Activity</b></summary>
* The pull request introduces significant documentation and example code changes.
* New example files for a 'Scale' kernel and associated utilities have been added.
* The core kernel library guide has been completely rewritten for improved clarity and practicality.
</details>
<details>
<summary><b>Using Gemini Code Assist</b></summary>
<br>
The full guide for Gemini Code Assist can be found on our [documentation page](https://developers.google.com/gemini-code-assist/docs/review-github-code), here are some quick tips.
<b>Invoking Gemini</b>
You can request assistance from Gemini at any point by creating a comment using either `/gemini <command>` or `@gemini-code-assist <command>`. Below is a summary of the supported commands on the current page.
Feature | Command | Description
--- | --- | ---
Code Review | `/gemini review` | Performs a code review for the current pull request in its current state.
Pull Request Summary | `/gemini summary` | Provides a summary of the current pull request in its current state.
Comment | @gemini-code-assist | Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help | `/gemini help` | Displays a list of available commands.
<b>Customization</b>
To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a `.gemini/` folder in the base of the repository. Detailed instructions can be found [here](https://developers.google.com/gemini-code-assist/docs/customize-gemini-behavior-github).
<b>Limitations & Feedback</b>
Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with :thumbsup: and :thumbsdown: on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up [here](https://google.qualtrics.com/jfe/form/SV_2cyuGuTWsEw84yG).
<b>You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the [Gemini Code Assist IDE Extension](https://cloud.google.com/products/gemini/code-assist).</b>
</details>
[^1]: Review the [Privacy Notices](https://policies.google.com/privacy), [Generative AI Prohibited Use Policy](https://policies.google.com/terms/generative-ai/use-policy), [Terms of Service](https://policies.google.com/terms), and learn how to configure Gemini Code Assist in GitHub [here](https://developers.google.com/gemini-code-assist/docs/customize-gemini-behavior-github). Gemini can make mistakes, so double check it and [use code with caution](https://support.google.com/legal/answer/13505487).
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org
Re: [PR] doc: Update Kernel Library Guide [tvm-ffi]
Posted by "junrushao (via GitHub)" <gi...@apache.org>.
junrushao commented on code in PR #431:
URL: https://github.com/apache/tvm-ffi/pull/431#discussion_r2775066389
##########
docs/guides/kernel_library_guide.rst:
##########
@@ -15,180 +15,343 @@
.. specific language governing permissions and limitations
.. under the License.
-====================
Kernel Library Guide
====================
-This guide serves as a quick start for shipping kernel libraries with TVM FFI. The shipped kernel libraries are of python version and ML framework agnostic. With the help of TVM FFI, we can connect the kernel libraries to multiple ML framework, such as PyTorch, XLA, JAX, together with the minimal efforts.
+This guide covers shipping C++/CUDA kernel libraries with TVM-FFI. The resulting
+libraries are agnostic to Python version and ML framework — a single ``.so`` works
+with PyTorch, JAX, PaddlePaddle, NumPy, and more.
-Tensor
-======
+.. seealso::
-Almost all kernel libraries are about tensor computation and manipulation. For better adaptation to different ML frameworks, TVM FFI provides a minimal set of data structures to represent tensors from ML frameworks, including the tensor basic attributes and storage pointer.
-To be specific, in TVM FFI, two types of tensor constructs, :cpp:class:`~tvm::ffi::Tensor` and :cpp:class:`~tvm::ffi::TensorView`, can be used to represent a tensor from ML frameworks.
+ - :doc:`../get_started/quickstart`: End-to-end walkthrough of a simpler ``add_one`` kernel
+ - :doc:`../packaging/cpp_tooling`: Build toolchain, CMake integration, and library distribution
+ - All example code in this guide is under
+ `examples/kernel_library/ <https://github.com/apache/tvm-ffi/tree/main/examples/kernel_library>`_.
-Tensor and TensorView
----------------------
-Both :cpp:class:`~tvm::ffi::Tensor` and :cpp:class:`~tvm::ffi::TensorView` are designed to represent tensors from ML frameworks that interact with the TVM FFI ABI. They are backed by the `DLTensor` in DLPack in practice. The main difference is whether it is an owning tensor structure.
+Anatomy of a Kernel Function
+-----------------------------
-:cpp:class:`tvm::ffi::Tensor`
- :cpp:class:`~tvm::ffi::Tensor` is a completely owning tensor with reference counting. It can be created on either C++ or Python side and passed between either side. And TVM FFI internally keeps a reference count to track lifetime of the tensors. When the reference count goes to zero, its underlying deleter function will be called to free the tensor storage.
+Every TVM-FFI CUDA kernel follows the same sequence:
-:cpp:class:`tvm::ffi::TensorView`
- :cpp:class:`~tvm::ffi::TensorView` is a non-owning view of an existing tensor, pointing to an existing tensor (e.g., a tensor allocated by PyTorch).
+1. **Validate** inputs (device, dtype, shape, contiguity)
+2. **Set device guard** to match the tensor's device
+3. **Acquire stream** from the host framework
+4. **Dispatch** on dtype and **launch** the kernel
-It is **recommended** to use :cpp:class:`~tvm::ffi::TensorView` when possible, that helps us to support more cases, including cases where only view but not strong reference are passed, like XLA buffer. It is also more lightweight. However, since :cpp:class:`~tvm::ffi::TensorView` is a non-owning view, it is the user's responsibility to ensure the lifetime of underlying tensor.
+Here is a complete ``Scale`` kernel that computes ``y = x * factor``:
-Tensor Attributes
------------------
+.. literalinclude:: ../../examples/kernel_library/scale_kernel.cu
+ :language: cpp
+ :start-after: [function.begin]
+ :end-before: [function.end]
-For convenience, :cpp:class:`~tvm::ffi::TensorView` and :cpp:class:`~tvm::ffi::Tensor` align the following attributes retrieval mehtods to :cpp:class:`at::Tensor` interface, to obtain tensor basic attributes and storage pointer:
-``dim``, ``dtype``, ``sizes``, ``size``, ``strides``, ``stride``, ``numel``, ``data_ptr``, ``device``, ``is_contiguous``
+The CUDA kernel itself is a standard ``__global__`` function:
-Please refer to the documentation of both tensor classes for their details. Here highlight some non-primitive attributes:
+.. literalinclude:: ../../examples/kernel_library/scale_kernel.cu
+ :language: cpp
+ :start-after: [cuda_kernel.begin]
+ :end-before: [cuda_kernel.end]
-:c:struct:`DLDataType`
- The ``dtype`` of the tensor. It's represented by a struct with three fields: code, bits, and lanes, defined by DLPack protocol.
+The following subsections break down each step.
-:c:struct:`DLDevice`
- The ``device`` where the tensor is stored. It is represented by a struct with two fields: device_type and device_id, defined by DLPack protocol.
-:cpp:class:`tvm::ffi::ShapeView`
- The ``sizes`` and ``strides`` attributes retrieval are returned as :cpp:class:`~tvm::ffi::ShapeView`. It is an iterate-able data structure storing the shapes or strides data as ``int64_t`` array.
+Input Validation
+~~~~~~~~~~~~~~~~
-Tensor Allocation
------------------
+Kernel functions should validate inputs early and fail with clear error messages.
+A common pattern is to define reusable ``CHECK_*`` macros on top of
+:c:macro:`TVM_FFI_CHECK` (see :doc:`../concepts/exception_handling`):
+
+.. literalinclude:: ../../examples/kernel_library/tvm_ffi_utils.h
+ :language: cpp
+ :start-after: [check_macros.begin]
+ :end-before: [check_macros.end]
+
+For **user-facing errors** (bad arguments, unsupported dtypes, shape mismatches),
+use :c:macro:`TVM_FFI_THROW` or :c:macro:`TVM_FFI_CHECK` with a specific error kind
+so that callers receive an actionable message:
+
+.. code-block:: cpp
+
+ TVM_FFI_THROW(TypeError) << "Unsupported dtype: " << input.dtype();
+ TVM_FFI_CHECK(input.numel() > 0, ValueError) << "input must be non-empty";
+ TVM_FFI_CHECK(input.numel() == output.numel(), ValueError) << "size mismatch";
+
+For **internal invariants** that indicate bugs in the kernel itself, use
+:c:macro:`TVM_FFI_ICHECK`:
+
+.. code-block:: cpp
+
+ TVM_FFI_ICHECK_GE(n, 0) << "element count must be non-negative";
+
+
+Device Guard and Stream
+~~~~~~~~~~~~~~~~~~~~~~~
+
+Before launching a CUDA kernel, two things must happen:
+
+1. **Set the CUDA device** to match the tensor's device. :cpp:class:`tvm::ffi::CUDADeviceGuard`
+ is an RAII guard that calls ``cudaSetDevice`` on construction and restores the
+ original device on destruction.
+
+2. **Acquire the stream** from the host framework via :cpp:func:`TVMFFIEnvGetStream`.
+ When Python code calls a kernel with PyTorch tensors, TVM-FFI automatically
+ captures PyTorch's current stream for the tensor's device.
+
+A small helper keeps this concise:
+
+.. literalinclude:: ../../examples/kernel_library/tvm_ffi_utils.h
+ :language: cpp
+ :start-after: [get_stream.begin]
+ :end-before: [get_stream.end]
+
+Every kernel function then follows the same two-line pattern:
+
+.. code-block:: cpp
+
+ ffi::CUDADeviceGuard guard(input.device().device_id);
+ cudaStream_t stream = get_cuda_stream(input.device());
+
+See :doc:`../concepts/tensor` for details on stream handling and automatic stream
+context updates.
-TVM FFI provides several methods to create or allocate tensors at C++ runtime. Generally, there are two types of tensor creation methods:
-* Allocate a tensor with new storage from scratch, i.e. :cpp:func:`~tvm::ffi::Tensor::FromEnvAlloc` and :cpp:func:`~tvm::ffi::Tensor::FromNDAlloc`. By this types of methods, the shapes, strides, data types, devices and other attributes are required for the allocation.
-* Create a tensor with existing storage following DLPack protocol, i.e. :cpp:func:`~tvm::ffi::Tensor::FromDLPack` and :cpp:func:`~tvm::ffi::Tensor::FromDLPackVersioned`. By this types of methods, the shapes, data types, devices and other attributes can be inferred from the DLPack attributes.
+Dtype Dispatch
+~~~~~~~~~~~~~~
-FromEnvAlloc
-^^^^^^^^^^^^
+Kernels typically support multiple dtypes. Dispatch on :c:struct:`DLDataType` at
+runtime while instantiating templates at compile time:
-To better adapt to the ML framework, it is **recommended** to reuse the framework tensor allocator anyway, instead of directly allocating the tensors via CUDA runtime API, like ``cudaMalloc``. Since reusing the framework tensor allocator:
+.. code-block:: cpp
-* Benefit from the framework's native caching allocator or related allocation mechanism.
-* Help framework tracking memory usage and planning globally.
+ constexpr DLDataType dl_float32 = DLDataType{kDLFloat, 32, 1};
+ constexpr DLDataType dl_float16 = DLDataType{kDLFloat, 16, 1};
-TVM FFI provides :cpp:func:`tvm::ffi::Tensor::FromEnvAlloc` to allocate a tensor with the framework tensor allocator. To determine which framework tensor allocator, TVM FFI infers it from the passed-in framework tensors. For example, when calling the kernel library at Python side, there is an input framework tensor if of type ``torch.Tensor``, TVM FFI will automatically bind the :cpp:func:`at::empty` as the current framework tensor allocator by ``TVMFFIEnvTensorAlloc``. And then the :cpp:func:`~tvm::ffi::Tensor::FromEnvAlloc` is calling the :cpp:class:`at::empty` actually:
+ if (input.dtype() == dl_float32) {
+ ScaleKernel<<<blocks, threads, 0, stream>>>(
+ static_cast<float*>(output.data_ptr()), ...);
+ } else if (input.dtype() == dl_float16) {
+ ScaleKernel<<<blocks, threads, 0, stream>>>(
+ static_cast<half*>(output.data_ptr()), ...);
+ } else {
+ TVM_FFI_THROW(TypeError) << "Unsupported dtype: " << input.dtype();
+ }
-.. code-block:: c++
+For libraries that support many dtypes, define dispatch macros
+(see `FlashInfer's tvm_ffi_utils.h <https://github.com/flashinfer-ai/flashinfer/blob/main/csrc/tvm_ffi_utils.h>`_
+for a production example).
- ffi::Tensor tensor = ffi::Tensor::FromEnvAlloc(TVMFFIEnvTensorAlloc, ...);
-which is equivalent to:
+Export and Load
+---------------
-.. code-block:: c++
+Export and Build
+~~~~~~~~~~~~~~~~
- at::Tensor tensor = at::empty(...);
+**Export.** Use :c:macro:`TVM_FFI_DLL_EXPORT_TYPED_FUNC` to create a C symbol
+that follows the :doc:`TVM-FFI calling convention <../concepts/func_module>`:
-FromNDAlloc
-^^^^^^^^^^^
+.. literalinclude:: ../../examples/kernel_library/scale_kernel.cu
+ :language: cpp
+ :start-after: [export.begin]
+ :end-before: [export.end]
-:cpp:func:`tvm::ffi::Tensor::FromNDAlloc` can be used to create a tensor with custom memory allocator. It is of simple usage by providing a custom memory allocator and deleter for tensor allocation and free each, rather than relying on any framework tensor allocator.
+This creates a symbol ``__tvm_ffi_scale`` in the shared library. For larger
+projects, a common pattern is to keep kernel implementations and export
+declarations in **separate files** — an implementation file and a binding file:
Review Comment:
Opus 4.6 hallucinates 🫠
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org
Re: [PR] doc: Update Kernel Library Guide [tvm-ffi]
Posted by "gemini-code-assist[bot] (via GitHub)" <gi...@apache.org>.
gemini-code-assist[bot] commented on code in PR #431:
URL: https://github.com/apache/tvm-ffi/pull/431#discussion_r2773467241
##########
examples/kernel_library/scale_kernel.cu:
##########
@@ -0,0 +1,65 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+#include "tvm_ffi_utils.h"
+
+// [cuda_kernel.begin]
+template <typename T>
+__global__ void ScaleKernel(T* out, const T* in, T factor, int64_t n) {
+ int64_t i = blockIdx.x * blockDim.x + threadIdx.x;
+ if (i < n) {
+ out[i] = in[i] * factor;
+ }
+}
+// [cuda_kernel.end]
+
+// [function.begin]
+void Scale(TensorView output, TensorView input, double factor) {
+ // --- 1. Validate inputs ---
+ CHECK_INPUT(input);
+ CHECK_INPUT(output);
+ CHECK_DIM(1, input);
+ CHECK_DEVICE(input, output);
+ TVM_FFI_CHECK(input.numel() == output.numel(), ValueError) << "input/output size mismatch";
Review Comment:

The validation logic checks that the input and output tensors are on the same device and have the same number of elements, but it doesn't verify that they have the same `dtype`. Since the `ScaleKernel` is templated on a single type `T` for both input and output, a `dtype` mismatch would lead to incorrect behavior or memory corruption. It's important to add a check to ensure `input.dtype() == output.dtype()`.
```
CHECK_DEVICE(input, output);
TVM_FFI_CHECK(input.dtype() == output.dtype(), ValueError) << "input/output dtype mismatch";
TVM_FFI_CHECK(input.numel() == output.numel(), ValueError) << "input/output size mismatch";
```
##########
examples/kernel_library/tvm_ffi_utils.h:
##########
@@ -0,0 +1,71 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+#ifndef KERNEL_LIBRARY_TVM_FFI_UTILS_H_
+#define KERNEL_LIBRARY_TVM_FFI_UTILS_H_
+
+#include <tvm/ffi/extra/c_env_api.h>
+#include <tvm/ffi/extra/cuda/device_guard.h>
+#include <tvm/ffi/tvm_ffi.h>
+
+namespace ffi = tvm::ffi;
+using ffi::Optional;
+using ffi::Tensor;
+using ffi::TensorView;
+
+// [check_macros.begin]
+// --- Reusable validation macros ---
+#define CHECK_CUDA(x) \
+ TVM_FFI_CHECK((x).device().device_type == kDLCUDA, ValueError) << #x " must be a CUDA tensor"
+#define CHECK_CONTIGUOUS(x) \
+ TVM_FFI_CHECK((x).IsContiguous(), ValueError) << #x " must be contiguous"
+#define CHECK_INPUT(x) \
+ CHECK_CUDA(x); \
+ CHECK_CONTIGUOUS(x)
Review Comment:

This macro expands to two separate statements. This can lead to unexpected behavior when used in control flow statements without braces, like `if (condition) CHECK_INPUT(x);`. In this case, only the first check (`CHECK_CUDA`) would be conditional. To make the macro robust, it's a standard C++ practice to wrap multi-statement macros in a `do { ... } while(0)` block, which turns them into a single statement.
```suggestion
#define CHECK_INPUT(x) \
do { \
CHECK_CUDA(x); \
CHECK_CONTIGUOUS(x); \
} while (0)
```
##########
examples/kernel_library/tvm_ffi_utils.h:
##########
@@ -0,0 +1,71 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+#ifndef KERNEL_LIBRARY_TVM_FFI_UTILS_H_
+#define KERNEL_LIBRARY_TVM_FFI_UTILS_H_
+
+#include <tvm/ffi/extra/c_env_api.h>
+#include <tvm/ffi/extra/cuda/device_guard.h>
+#include <tvm/ffi/tvm_ffi.h>
+
+namespace ffi = tvm::ffi;
+using ffi::Optional;
+using ffi::Tensor;
+using ffi::TensorView;
+
+// [check_macros.begin]
+// --- Reusable validation macros ---
+#define CHECK_CUDA(x) \
+ TVM_FFI_CHECK((x).device().device_type == kDLCUDA, ValueError) << #x " must be a CUDA tensor"
+#define CHECK_CONTIGUOUS(x) \
+ TVM_FFI_CHECK((x).IsContiguous(), ValueError) << #x " must be contiguous"
+#define CHECK_INPUT(x) \
+ CHECK_CUDA(x); \
+ CHECK_CONTIGUOUS(x)
+#define CHECK_DIM(d, x) \
+ TVM_FFI_CHECK((x).ndim() == (d), ValueError) << #x " must be a " #d "D tensor"
+#define CHECK_DEVICE(a, b) \
+ TVM_FFI_CHECK((a).device().device_type == (b).device().device_type, ValueError) \
+ << #a " and " #b " must be on the same device type"; \
+ TVM_FFI_CHECK((a).device().device_id == (b).device().device_id, ValueError) \
+ << #a " and " #b " must be on the same device"
Review Comment:

Similar to `CHECK_INPUT`, this macro expands to multiple statements, which can be problematic inside control structures without braces (e.g., `if`). Additionally, there's an inconsistent use of semicolons within the macro definition. To ensure it behaves as a single, safe statement, it should be wrapped in a `do { ... } while(0)` block, and the internal semicolon should be removed for consistency.
```suggestion
#define CHECK_DEVICE(a, b) \
do { \
TVM_FFI_CHECK((a).device().device_type == (b).device().device_type, ValueError) \
<< #a " and " #b " must be on the same device type"; \
TVM_FFI_CHECK((a).device().device_id == (b).device_id, ValueError) \
<< #a " and " #b " must be on the same device"; \
} while (0)
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org