This is an automated email from the ASF dual-hosted git repository.

tqchen pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/tvm-ffi.git


The following commit(s) were added to refs/heads/main by this push:
     new d74a25dc [PERF] Speed up Object instance and subclass checks (#976)
d74a25dc is described below

commit d74a25dc893c969752d622a158f6af47ecb067b3
Author: Yaxing Cai <[email protected]>
AuthorDate: Sat Nov 14 23:42:49 2026 +0800

    [PERF] Speed up Object instance and subclass checks (#976)
    
    Object instance and subclass checks incur ABCMeta overhead even when no
    virtual subclasses are registered. Negative subclass checks can
    recursively traverse large class hierarchies.
    
    Use MRO checks for Object instance and subclass checks, falling back to
    ABCMeta when virtual subclasses are registered or a subclass hook is
    defined. Add coverage for non-Object values, collection ABCs, virtual
    subclasses, and subclass hooks.
    
    ---------
    
    Co-authored-by: Zihao Ye <[email protected]>
    Co-authored-by: tqchen <[email protected]>
---
 include/tvm/ffi/c_api.h          |  2 +-
 python/tvm_ffi/cython/object.pxi | 37 ++++++++++++++++++++++++++++++++++++
 tests/python/test_object.py      | 41 ++++++++++++++++++++++++++++++++++++++++
 3 files changed, 79 insertions(+), 1 deletion(-)

diff --git a/include/tvm/ffi/c_api.h b/include/tvm/ffi/c_api.h
index 0deb498a..4d8a2f72 100644
--- a/include/tvm/ffi/c_api.h
+++ b/include/tvm/ffi/c_api.h
@@ -70,7 +70,7 @@
 /*! \brief TVM FFI minor version. */
 #define TVM_FFI_VERSION_MINOR 1
 /*! \brief TVM FFI patch version. */
-#define TVM_FFI_VERSION_PATCH 16
+#define TVM_FFI_VERSION_PATCH 17
 // NOLINTEND(modernize-macro-to-enum)
 
 #ifdef __cplusplus
diff --git a/python/tvm_ffi/cython/object.pxi b/python/tvm_ffi/cython/object.pxi
index 3219158f..6ea548d1 100644
--- a/python/tvm_ffi/cython/object.pxi
+++ b/python/tvm_ffi/cython/object.pxi
@@ -16,6 +16,7 @@
 # under the License.
 import json
 from abc import ABCMeta
+from cpython.type cimport PyType_Check, PyType_IsSubtype
 from typing import Any
 
 
@@ -221,15 +222,51 @@ cdef class CContainerBase(CObject):
         self._dlpack_exchange_api = NULL
 
 
+# Whether Object checks require ABCMeta's extended subclass machinery.
+# Most Object classes use ordinary inheritance, so Python's faster MRO-based
+# subtype checks suffice. Registering a virtual subclass or defining a custom
+# __subclasshook__ enables ABCMeta checks for all Object classes thereafter.
+cdef bint _OBJECT_USE_ABC_CHECKS = False
+
+
 class _ObjectSlotsMeta(ABCMeta):
     def __new__(mcls, name: str, bases: tuple[type, ...], ns: dict[str, Any], 
**kwargs: Any):
+        # Creates the class, defaulting to no additional instance slots.
+        global _OBJECT_USE_ABC_CHECKS
         if "__slots__" not in ns:
             ns["__slots__"] = ()
+        # ABCMeta calls __subclasshook__ to customize subclass recognition:
+        # True/False decides the result; NotImplemented defers to normal ABC 
checks.
+        if "__subclasshook__" in ns:
+            _OBJECT_USE_ABC_CHECKS = True
         return super().__new__(mcls, name, bases, ns, **kwargs)
 
     def __init__(cls, name: str, bases: tuple[type, ...], ns: dict[str, Any], 
**kwargs: Any):
+        # Initializes the newly created class through ABCMeta.
         super().__init__(name, bases, ns, **kwargs)
 
+    def register(cls, subclass):
+        # Registers a virtual subclass without changing its inheritance or MRO.
+        global _OBJECT_USE_ABC_CHECKS
+        _OBJECT_USE_ABC_CHECKS = True
+        return ABCMeta.register(cls, subclass)
+
+    def __instancecheck__(cls, instance):
+        # Implements isinstance(instance, cls).
+        if _OBJECT_USE_ABC_CHECKS:
+            return ABCMeta.__instancecheck__(cls, instance)
+        if PyType_IsSubtype(type(instance), <type>cls):
+            return True
+        return type.__instancecheck__(cls, instance)  # a ``__class__`` other 
than the type
+
+    def __subclasscheck__(cls, subclass):
+        # Implements issubclass(subclass, cls).
+        if _OBJECT_USE_ABC_CHECKS:
+            return ABCMeta.__subclasscheck__(cls, subclass)
+        if PyType_Check(subclass):
+            return PyType_IsSubtype(<type>subclass, <type>cls)
+        return type.__subclasscheck__(cls, subclass)
+
 
 class Object(CObject, metaclass=_ObjectSlotsMeta):
     """Base class of all TVM FFI objects.
diff --git a/tests/python/test_object.py b/tests/python/test_object.py
index 23df2d5c..d38a71c5 100644
--- a/tests/python/test_object.py
+++ b/tests/python/test_object.py
@@ -16,6 +16,7 @@
 # under the License.
 from __future__ import annotations
 
+import subprocess
 import sys
 from collections.abc import Sequence
 from typing import Any
@@ -477,6 +478,46 @@ class TestIsinstanceIssubclass:
         assert issubclass(tvm_ffi.testing.TestObjectBase, tvm_ffi.Object)
         assert issubclass(tvm_ffi.testing.TestObjectDerived, tvm_ffi.Object)
 
+    def test_non_object_values(self) -> None:
+        """Values and classes outside the hierarchy are no Object, and a 
non-class is refused."""
+        for value in (1, "a", None, [1], object()):
+            assert not isinstance(value, tvm_ffi.Object)
+            assert not isinstance(value, tvm_ffi.testing.TestObjectBase)
+        assert not issubclass(int, tvm_ffi.Object)
+        with pytest.raises(TypeError):
+            issubclass(1, tvm_ffi.Object)  # type: ignore[arg-type]
+
+    def test_containers_keep_their_collection_abcs(self) -> None:
+        """The collections.abc bases of a container answer as before."""
+        assert isinstance(tvm_ffi.Array([1]), Sequence)
+        assert not isinstance(tvm_ffi.Map({"a": 1}), Sequence)
+
+    def test_virtual_subclass_after_register(self) -> None:
+        """``register`` and ``__subclasshook__`` keep ABCMeta's meaning, from 
the first one on.
+
+        Each runs in its own process: it switches the checks of every Object 
class there to ABCMeta's.
+        """
+        register = (
+            "import tvm_ffi.testing as t\n"
+            "class Virtual: pass\n"
+            "assert not isinstance(Virtual(), t.TestObjectBase)\n"
+            "t.TestObjectBase.register(Virtual)\n"
+            "assert isinstance(Virtual(), t.TestObjectBase) and 
issubclass(Virtual, t.TestObjectBase)\n"
+            "assert not isinstance(Virtual(), t.TestObjectDerived)\n"
+            "assert isinstance(t.TestObjectBase(), t.TestObjectBase)\n"
+        )
+        hook = (
+            "import tvm_ffi\n"
+            "class Hooked(tvm_ffi.Object):\n"
+            "    @classmethod\n"
+            "    def __subclasshook__(cls, other):\n"
+            "        return True if other is int else NotImplemented\n"
+            "assert issubclass(int, Hooked) and isinstance(1, Hooked)\n"
+            "assert not issubclass(str, Hooked)\n"
+        )
+        for code in (register, hook):
+            subprocess.run([sys.executable, "-c", code], check=True)
+
     def test_issubclass_sibling_containers(self) -> None:
         """Sibling container types should not be subclasses of each other."""
         assert not issubclass(tvm_ffi.List, tvm_ffi.Array)

Reply via email to