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 "tqchen (via GitHub)" <gi...@apache.org> on 2026/04/20 15:10:40 UTC
[PR] [FEAT] Optimize map_dataclass_to_tuple with JIT unpack_dataclass_to_tuple [tvm-ffi]
tqchen opened a new pull request, #563:
URL: https://github.com/apache/tvm-ffi/pull/563
This PR introduces an optimized unpack_dataclass_to_tuple util and update `dataclasses.astuple` in `map_dataclass_to_tuple` with `unpack_dataclass_to_tuple`, a JIT-compiled per-class unpacker that brings 5-11x speedup and does not deep-copy leaf values.
Not deep-copying leaf is important for runtime use-cases, when dataclass fields contain tensor objects or other large resources that must not be copied -- leaf values are passed through by reference, not duplicated.
## Design
`unpack_dataclass_to_tuple(x)` recursively converts dataclass instances to tuples via JIT-compiled inline attribute access:
- `_extract_dataclass_to_tuple_schema(cls)` -- inspect type annotations
- `_validate_dataclass_to_tuple_schema(schema)` -- codegen security
- `_compile_dataclass_to_tuple_schema(prefix, schema)` -- inline code
Cached per-thread (TLS) for thread safety. Conservative field classification: only marks as leaf when certain (known primitives, containers of known primitives). Unknown types use dynamic dispatch.
## Performance (vs dataclasses.astuple)
| Case | unpack | astuple | speedup |
|-------------------|--------|---------|---------|
| Config (2 flat) | 144 ns | 769 ns | 5.3x |
| Nested (int + dc) | 152 ns | 1386 ns | 9.1x |
| Wide (5 flat) | 170 ns | 1268 ns | 7.5x |
| Deep (2 levels) | 200 ns | 2305 ns | 11.5x |
| WithAny (dynamic) | 254 ns | 1644 ns | 6.5x |
--
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] [FEAT] Enhance map_dataclass_to_tuple with JIT unpack_dataclass_to_tuple [tvm-ffi]
Posted by "tqchen (via GitHub)" <gi...@apache.org>.
tqchen commented on PR #563:
URL: https://github.com/apache/tvm-ffi/pull/563#issuecomment-4282064832
/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] [FEAT] Enhance map_dataclass_to_tuple with JIT unpack_dataclass_to_tuple [tvm-ffi]
Posted by "gemini-code-assist[bot] (via GitHub)" <gi...@apache.org>.
gemini-code-assist[bot] commented on code in PR #563:
URL: https://github.com/apache/tvm-ffi/pull/563#discussion_r3112762809
##########
python/tvm_ffi/utils/unpack_dataclass.py:
##########
@@ -0,0 +1,263 @@
+# 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.
+"""Fast dataclass-to-tuple conversion via JIT-compiled unpacking.
+
+This module provides ``unpack_dataclass_to_tuple``, a function that recursively
+converts dataclass instances to tuples. It JIT-compiles a per-class unpacker
+on first call and caches it per-thread for ~5-11x speedup over
+``dataclasses.astuple`` with no deep-copy of leaf values.
+"""
+
+from __future__ import annotations
+
+import dataclasses
+import keyword
+import sys
+import threading
+import typing
+from typing import Any
+
+# Support both typing.Union and types.UnionType (PEP 604, Python 3.10+)
+if sys.version_info >= (3, 10):
+ import types
+
+ _LEAF_CONTAINER_ORIGINS = (tuple, dict, set, frozenset, typing.Union, types.UnionType)
+else:
+ _LEAF_CONTAINER_ORIGINS = (tuple, dict, set, frozenset, typing.Union)
+
+# Type alias for dataclass-to-tuple schema (internal).
+# Schema values:
+# None -> leaf, direct attribute access (zero cost)
+# "unpack" -> dynamic dispatch via unpack_dataclass_to_tuple at runtime
+# dict -> nested struct, recurse inline
+# Example: {"x": None, "y": None} -> (__x.x, __x.y,)
+# Example: {"cfg": {"x": None, "y": None}, "data": "unpack"}
+# -> ((__x.cfg.x, __x.cfg.y,), __dispatch(__x.data),)
+DataclassToTupleSchema = dict # dict[str, None | str | DataclassToTupleSchema]
+
+# Sentinel value in schema: field should be dynamically dispatched
+UNPACK = "unpack"
+
+# Thread-local cache for JIT-compiled per-class unpack functions
+_tls = threading.local()
+
+# Types known to be safe leaves (never contain dataclass instances)
+_KNOWN_LEAF_TYPES: set[type] = {int, float, str, bool, bytes, complex, type(None)}
+
+
+def _is_known_leaf_type(tp: Any) -> bool:
+ """Check if a type is definitely a leaf (no dataclass content or conversion needed).
+
+ Note: list is NOT a leaf because it must be converted to a tuple per the
+ unpack contract (matching dataclasses.astuple behavior).
+ """
+ if isinstance(tp, type):
+ return tp in _KNOWN_LEAF_TYPES
+ if tp is Ellipsis:
+ return True
+ origin = typing.get_origin(tp)
+ if origin is not None:
+ # list is NOT a leaf — must be converted to tuple
+ # tuple/dict/set/frozenset/Union are leaves if all args are leaves
+ if origin in _LEAF_CONTAINER_ORIGINS:
+ args = typing.get_args(tp)
+ return bool(args) and all(_is_known_leaf_type(a) for a in args)
+ return False
+
+
+def _classify_field_type(
+ field_type: Any, memo: set[type] | None = None
+) -> None | str | DataclassToTupleSchema:
+ """Classify a resolved field type into a schema entry.
+
+ Conservative: only returns None (leaf) when we are certain the type
+ cannot contain a dataclass. Otherwise returns UNPACK (dynamic dispatch).
+ """
+ if isinstance(field_type, str) or field_type is Any or field_type is object:
+ return UNPACK
+ if dataclasses.is_dataclass(field_type) and isinstance(field_type, type):
+ # Guard against infinite recursion for self-referential dataclasses
+ if memo is not None and field_type in memo:
+ return UNPACK
+ return _extract_dataclass_to_tuple_schema(field_type, memo=memo)
+ # Known primitive types -> leaf
+ if isinstance(field_type, type) and field_type in _KNOWN_LEAF_TYPES:
+ return None
+ # Generic containers: check element types
+ # list always needs UNPACK (must be converted to tuple)
+ # tuple/dict/set/frozenset/Union are leaves if all args are known leaves
+ # Generic containers: list always UNPACK (must convert to tuple).
+ # tuple/dict/set/frozenset/Union are leaves only if all args are known leaves.
+ # Everything else (unknown type) -> UNPACK (conservative).
+ origin = typing.get_origin(field_type)
+ if origin in _LEAF_CONTAINER_ORIGINS:
+ args = typing.get_args(field_type)
+ if args and all(_is_known_leaf_type(a) for a in args):
+ return None
Review Comment:

This optimization deviates from `dataclasses.astuple` behavior. `astuple` always creates new container instances (dicts, lists, tuples) even if they only contain primitive values. By returning `None` (which leads to direct attribute access in the JIT code), you are passing these containers by reference. If the caller modifies a mutable container (like a `dict`) in the resulting tuple, it will modify the original dataclass instance. While this is a performance win, it introduces potential side effects that users of `astuple` would not expect.
##########
python/tvm_ffi/utils/unpack_dataclass.py:
##########
@@ -0,0 +1,263 @@
+# 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.
+"""Fast dataclass-to-tuple conversion via JIT-compiled unpacking.
+
+This module provides ``unpack_dataclass_to_tuple``, a function that recursively
+converts dataclass instances to tuples. It JIT-compiles a per-class unpacker
+on first call and caches it per-thread for ~5-11x speedup over
+``dataclasses.astuple`` with no deep-copy of leaf values.
+"""
+
+from __future__ import annotations
+
+import dataclasses
+import keyword
+import sys
+import threading
+import typing
+from typing import Any
+
+# Support both typing.Union and types.UnionType (PEP 604, Python 3.10+)
+if sys.version_info >= (3, 10):
+ import types
+
+ _LEAF_CONTAINER_ORIGINS = (tuple, dict, set, frozenset, typing.Union, types.UnionType)
+else:
+ _LEAF_CONTAINER_ORIGINS = (tuple, dict, set, frozenset, typing.Union)
+
+# Type alias for dataclass-to-tuple schema (internal).
+# Schema values:
+# None -> leaf, direct attribute access (zero cost)
+# "unpack" -> dynamic dispatch via unpack_dataclass_to_tuple at runtime
+# dict -> nested struct, recurse inline
+# Example: {"x": None, "y": None} -> (__x.x, __x.y,)
+# Example: {"cfg": {"x": None, "y": None}, "data": "unpack"}
+# -> ((__x.cfg.x, __x.cfg.y,), __dispatch(__x.data),)
+DataclassToTupleSchema = dict # dict[str, None | str | DataclassToTupleSchema]
+
+# Sentinel value in schema: field should be dynamically dispatched
+UNPACK = "unpack"
+
+# Thread-local cache for JIT-compiled per-class unpack functions
+_tls = threading.local()
+
+# Types known to be safe leaves (never contain dataclass instances)
+_KNOWN_LEAF_TYPES: set[type] = {int, float, str, bool, bytes, complex, type(None)}
+
+
+def _is_known_leaf_type(tp: Any) -> bool:
+ """Check if a type is definitely a leaf (no dataclass content or conversion needed).
+
+ Note: list is NOT a leaf because it must be converted to a tuple per the
+ unpack contract (matching dataclasses.astuple behavior).
+ """
+ if isinstance(tp, type):
+ return tp in _KNOWN_LEAF_TYPES
+ if tp is Ellipsis:
+ return True
+ origin = typing.get_origin(tp)
+ if origin is not None:
+ # list is NOT a leaf — must be converted to tuple
+ # tuple/dict/set/frozenset/Union are leaves if all args are leaves
+ if origin in _LEAF_CONTAINER_ORIGINS:
+ args = typing.get_args(tp)
+ return bool(args) and all(_is_known_leaf_type(a) for a in args)
+ return False
+
+
+def _classify_field_type(
+ field_type: Any, memo: set[type] | None = None
+) -> None | str | DataclassToTupleSchema:
+ """Classify a resolved field type into a schema entry.
+
+ Conservative: only returns None (leaf) when we are certain the type
+ cannot contain a dataclass. Otherwise returns UNPACK (dynamic dispatch).
+ """
+ if isinstance(field_type, str) or field_type is Any or field_type is object:
+ return UNPACK
+ if dataclasses.is_dataclass(field_type) and isinstance(field_type, type):
+ # Guard against infinite recursion for self-referential dataclasses
+ if memo is not None and field_type in memo:
+ return UNPACK
+ return _extract_dataclass_to_tuple_schema(field_type, memo=memo)
+ # Known primitive types -> leaf
+ if isinstance(field_type, type) and field_type in _KNOWN_LEAF_TYPES:
+ return None
+ # Generic containers: check element types
+ # list always needs UNPACK (must be converted to tuple)
+ # tuple/dict/set/frozenset/Union are leaves if all args are known leaves
+ # Generic containers: list always UNPACK (must convert to tuple).
+ # tuple/dict/set/frozenset/Union are leaves only if all args are known leaves.
+ # Everything else (unknown type) -> UNPACK (conservative).
+ origin = typing.get_origin(field_type)
+ if origin in _LEAF_CONTAINER_ORIGINS:
+ args = typing.get_args(field_type)
+ if args and all(_is_known_leaf_type(a) for a in args):
+ return None
+ return UNPACK
+
+
+def _compile_dataclass_to_tuple_schema(prefix: str, schema: DataclassToTupleSchema) -> str:
+ """Compile a DataclassToTupleSchema into an inline tuple expression.
+
+ Parameters
+ ----------
+ prefix
+ The variable expression to unpack (e.g. "__x" or "__x.field").
+ schema
+ The schema dict mapping field names to:
+ - None: leaf, direct attribute access
+ - "unpack": dynamic dispatch via __dispatch() at runtime
+ - nested dict: recurse inline
+
+ Returns
+ -------
+ A string expression that evaluates to a tuple of the unpacked fields.
+
+ """
+ parts: list[str] = []
+ for field_name, sub_schema in schema.items():
+ field_expr = f"{prefix}.{field_name}"
+ if sub_schema is None:
+ parts.append(field_expr)
+ elif sub_schema == UNPACK:
+ parts.append(f"__dispatch({field_expr})")
+ else:
+ parts.append(_compile_dataclass_to_tuple_schema(field_expr, sub_schema))
+ return "(" + ", ".join(parts) + (",)" if parts else ")")
+
+
+def _validate_dataclass_to_tuple_schema(schema: DataclassToTupleSchema) -> None:
+ """Validate that a DataclassToTupleSchema contains only safe identifiers.
+
+ This is critical for security since field names are embedded directly
+ in generated code via exec(). The validation ensures:
+ - Keys are strings (type check)
+ - Keys pass str.isidentifier() — rejects any non-identifier characters
+ - Keys are not Python keywords — rejects control flow injection
+ - Values are only None, "unpack", or recursively-validated dicts
+
+ Combined with the hardcoded prefix ("__x") and restricted exec_globals,
+ this prevents any code injection through crafted field names.
+
+ """
+ if not isinstance(schema, dict):
+ raise TypeError(f"DataclassToTupleSchema must be a dict, got {type(schema).__name__}")
+ for field_name, sub_schema in schema.items():
+ if not isinstance(field_name, str):
+ raise TypeError(f"Schema field name must be a string, got {type(field_name).__name__}")
+ if not field_name.isidentifier():
+ raise ValueError(f"Schema field name {field_name!r} is not a valid Python identifier")
+ if keyword.iskeyword(field_name):
+ raise ValueError(f"Schema field name {field_name!r} is a Python keyword")
+ if sub_schema is not None and sub_schema != UNPACK:
+ _validate_dataclass_to_tuple_schema(sub_schema)
+
+
+def _extract_dataclass_to_tuple_schema(
+ cls: type, *, memo: set[type] | None = None
+) -> DataclassToTupleSchema:
+ """Extract a DataclassToTupleSchema from a dataclass class using type annotations.
+
+ Classification per field (conservative: only leaf when certain):
+ - Known dataclass type -> nested schema (recurse inline)
+ - Known primitive type (int, float, str, bool, bytes, complex) -> None (leaf)
+ - Container with only known-leaf args (list[int], dict[str, float]) -> None (leaf)
+ - Container with dataclass/unknown args (list[Config]) -> "unpack" (dynamic dispatch)
+ - Any, object, unresolved string annotation -> "unpack" (dynamic dispatch)
+ - Unknown class -> "unpack" (dynamic dispatch)
+
+ Uses typing.get_type_hints() to resolve PEP 563 string annotations.
+ Uses memo set to prevent infinite recursion on self-referential dataclasses.
+
+ """
+ if not dataclasses.is_dataclass(cls) or not isinstance(cls, type):
+ raise TypeError(f"Expected a dataclass class, got {cls!r}")
+ if memo is None:
+ memo = set()
+ memo.add(cls)
+ try:
+ type_hints = typing.get_type_hints(cls)
+ except (NameError, TypeError, AttributeError):
+ type_hints = {}
+ schema: DataclassToTupleSchema = {}
+ for f in dataclasses.fields(cls):
+ field_type = type_hints.get(f.name, f.type)
+ schema[f.name] = _classify_field_type(field_type, memo=memo)
+ return schema
+
+
+def unpack_dataclass_to_tuple(x: Any) -> Any:
+ """Fast recursively unpack a dataclass value to tuple representation.
+
+ - Dataclass instances are unpacked to tuples of their field values.
+ - Lists and tuples are recursed element-wise, returning a tuple.
+ - Dicts are recursed on values, returning a new dict.
+ - All other values are returned as-is (leaf passthrough).
+
+ This function optimizes speed via JIT-compiling the conversion per dataclass
+ class and caching it per-thread. It brings about 5-11x speedup vs
+ ``dataclasses.astuple`` and does not deep-copy leaf values.
+
+ Parameters
+ ----------
+ x
+ The value to unpack.
+
+ Returns
+ -------
+ The unpacked tuple representation, or ``x`` unchanged if it's a leaf.
+
+ """
+ try:
+ cache = _tls.cache
+ except AttributeError:
+ cache = _tls.cache = {}
+
+ cls = type(x)
+ fn = cache.get(cls)
+ if fn is not None:
+ return fn(x)
+
+ # Cache miss — classify the type
+ if dataclasses.is_dataclass(cls) and isinstance(cls, type):
+ schema = _extract_dataclass_to_tuple_schema(cls)
+ # Validate that all field names in the schema are safe Python identifiers.
+ # This is critical: field names are embedded directly in the generated code string.
+ # _validate_dataclass_to_tuple_schema ensures no code injection is possible via
+ # crafted field names (isidentifier + iskeyword checks).
+ _validate_dataclass_to_tuple_schema(schema)
+ code_expr = _compile_dataclass_to_tuple_schema("__x", schema)
+ code = f"def __unpack(__x): return {code_expr}"
+ namespace: dict[str, Any] = {}
+ # exec_globals only exposes __dispatch (our own function), no other capabilities.
+ exec(code, {"__dispatch": unpack_dataclass_to_tuple}, namespace)
+ fn = namespace["__unpack"]
+ cache[cls] = fn
+ return fn(x)
+ if isinstance(x, (list, tuple)):
+ return tuple(unpack_dataclass_to_tuple(e) for e in x)
Review Comment:

This implementation converts all `list` objects to `tuple` objects. `dataclasses.astuple` preserves the container type (i.e., it returns a new `list` for a `list` field). If the target function or downstream code expects a `list` (e.g., for mutation or specific type checks), this change will cause a `TypeError` or logic error. Consider using `type(x)(...)` to preserve the container type if strict compatibility with `astuple` is desired, or clearly document this conversion.
```suggestion
if isinstance(x, (list, tuple)):
return type(x)(unpack_dataclass_to_tuple(e) for e in x)
```
--
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] [FEAT] Enhance map_dataclass_to_tuple with JIT unpack_dataclass_to_tuple [tvm-ffi]
Posted by "tqchen (via GitHub)" <gi...@apache.org>.
tqchen merged PR #563:
URL: https://github.com/apache/tvm-ffi/pull/563
--
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] [FEAT] Enhance map_dataclass_to_tuple with JIT unpack_dataclass_to_tuple [tvm-ffi]
Posted by "gemini-code-assist[bot] (via GitHub)" <gi...@apache.org>.
gemini-code-assist[bot] commented on code in PR #563:
URL: https://github.com/apache/tvm-ffi/pull/563#discussion_r3111803525
##########
python/tvm_ffi/utils/unpack_dataclass.py:
##########
@@ -0,0 +1,252 @@
+# 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.
+"""Fast dataclass-to-tuple conversion via JIT-compiled unpacking.
+
+This module provides ``unpack_dataclass_to_tuple``, a function that recursively
+converts dataclass instances to tuples. It JIT-compiles a per-class unpacker
+on first call and caches it per-thread for ~5-11x speedup over
+``dataclasses.astuple`` with no deep-copy of leaf values.
+"""
+
+from __future__ import annotations
+
+import dataclasses
+import keyword
+import sys
+import threading
+import typing
+from typing import Any
+
+# Support both typing.Union and types.UnionType (PEP 604, Python 3.10+)
+if sys.version_info >= (3, 10):
+ import types
+
+ _LEAF_CONTAINER_ORIGINS = (tuple, dict, set, frozenset, typing.Union, types.UnionType)
+else:
+ _LEAF_CONTAINER_ORIGINS = (tuple, dict, set, frozenset, typing.Union)
+
+# Type alias for dataclass-to-tuple schema (internal).
+# Schema values:
+# None -> leaf, direct attribute access (zero cost)
+# "unpack" -> dynamic dispatch via unpack_dataclass_to_tuple at runtime
+# dict -> nested struct, recurse inline
+# Example: {"x": None, "y": None} -> (__x.x, __x.y,)
+# Example: {"cfg": {"x": None, "y": None}, "data": "unpack"}
+# -> ((__x.cfg.x, __x.cfg.y,), __dispatch(__x.data),)
+DataclassToTupleSchema = dict # dict[str, None | str | DataclassToTupleSchema]
+
+# Sentinel value in schema: field should be dynamically dispatched
+UNPACK = "unpack"
+
+# Thread-local cache for JIT-compiled per-class unpack functions
+_tls = threading.local()
+
+# Types known to be safe leaves (never contain dataclass instances)
+_KNOWN_LEAF_TYPES: set[type] = {int, float, str, bool, bytes, complex, type(None)}
+
+
+def _is_known_leaf_type(tp: Any) -> bool:
+ """Check if a type is definitely a leaf (no dataclass content or conversion needed).
+
+ Note: list is NOT a leaf because it must be converted to a tuple per the
+ unpack contract (matching dataclasses.astuple behavior).
+ """
+ if isinstance(tp, type):
+ return tp in _KNOWN_LEAF_TYPES
+ if tp is Ellipsis:
+ return True
+ origin = typing.get_origin(tp)
+ if origin is not None:
+ # list is NOT a leaf — must be converted to tuple
+ # tuple/dict/set/frozenset/Union are leaves if all args are leaves
+ if origin in _LEAF_CONTAINER_ORIGINS:
+ args = typing.get_args(tp)
+ return all(_is_known_leaf_type(a) for a in args)
+ return False
+
+
+def _classify_field_type(field_type: Any) -> None | str | DataclassToTupleSchema:
+ """Classify a resolved field type into a schema entry.
+
+ Conservative: only returns None (leaf) when we are certain the type
+ cannot contain a dataclass. Otherwise returns UNPACK (dynamic dispatch).
+ """
+ if isinstance(field_type, str) or field_type is Any or field_type is object:
+ return UNPACK
+ if dataclasses.is_dataclass(field_type) and isinstance(field_type, type):
+ return _extract_dataclass_to_tuple_schema(field_type)
Review Comment:

The current implementation will enter an infinite recursion during schema extraction if a dataclass has a field that references itself (directly or indirectly) without being wrapped in a container that breaks the JIT recursion (like `List` or `Optional`). For example, a linked list node defined as `next: Node` (valid with `from __future__ import annotations`) or a circular dependency between two dataclasses `A -> B -> A` will crash the process.
To fix this, you should track the classes currently being processed in a `memo` set passed through `_extract_dataclass_to_tuple_schema` and `_classify_field_type`. If a class is encountered that is already in the `memo`, `_classify_field_type` should return `UNPACK` to break the JIT recursion and fall back to dynamic dispatch at runtime.
##########
python/tvm_ffi/utils/unpack_dataclass.py:
##########
@@ -0,0 +1,252 @@
+# 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.
+"""Fast dataclass-to-tuple conversion via JIT-compiled unpacking.
+
+This module provides ``unpack_dataclass_to_tuple``, a function that recursively
+converts dataclass instances to tuples. It JIT-compiles a per-class unpacker
+on first call and caches it per-thread for ~5-11x speedup over
+``dataclasses.astuple`` with no deep-copy of leaf values.
+"""
+
+from __future__ import annotations
+
+import dataclasses
+import keyword
+import sys
+import threading
+import typing
+from typing import Any
+
+# Support both typing.Union and types.UnionType (PEP 604, Python 3.10+)
+if sys.version_info >= (3, 10):
+ import types
+
+ _LEAF_CONTAINER_ORIGINS = (tuple, dict, set, frozenset, typing.Union, types.UnionType)
+else:
+ _LEAF_CONTAINER_ORIGINS = (tuple, dict, set, frozenset, typing.Union)
+
+# Type alias for dataclass-to-tuple schema (internal).
+# Schema values:
+# None -> leaf, direct attribute access (zero cost)
+# "unpack" -> dynamic dispatch via unpack_dataclass_to_tuple at runtime
+# dict -> nested struct, recurse inline
+# Example: {"x": None, "y": None} -> (__x.x, __x.y,)
+# Example: {"cfg": {"x": None, "y": None}, "data": "unpack"}
+# -> ((__x.cfg.x, __x.cfg.y,), __dispatch(__x.data),)
+DataclassToTupleSchema = dict # dict[str, None | str | DataclassToTupleSchema]
+
+# Sentinel value in schema: field should be dynamically dispatched
+UNPACK = "unpack"
+
+# Thread-local cache for JIT-compiled per-class unpack functions
+_tls = threading.local()
+
+# Types known to be safe leaves (never contain dataclass instances)
+_KNOWN_LEAF_TYPES: set[type] = {int, float, str, bool, bytes, complex, type(None)}
+
+
+def _is_known_leaf_type(tp: Any) -> bool:
+ """Check if a type is definitely a leaf (no dataclass content or conversion needed).
+
+ Note: list is NOT a leaf because it must be converted to a tuple per the
+ unpack contract (matching dataclasses.astuple behavior).
+ """
+ if isinstance(tp, type):
+ return tp in _KNOWN_LEAF_TYPES
+ if tp is Ellipsis:
+ return True
+ origin = typing.get_origin(tp)
+ if origin is not None:
+ # list is NOT a leaf — must be converted to tuple
+ # tuple/dict/set/frozenset/Union are leaves if all args are leaves
+ if origin in _LEAF_CONTAINER_ORIGINS:
+ args = typing.get_args(tp)
+ return all(_is_known_leaf_type(a) for a in args)
Review Comment:

`all()` returns `True` for an empty iterable. This causes `_is_known_leaf_type` to return `True` for unparameterized generic containers like `typing.Tuple` or `typing.Dict` (where `typing.get_args` returns an empty tuple). Since these containers can contain dataclasses at runtime, they should not be considered "known leaves". This can lead to nested dataclasses being passed through by reference instead of being unpacked when they are inside unparameterized generics.
```suggestion
return bool(args) and all(_is_known_leaf_type(a) for a in args)
```
--
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] [FEAT] Enhance map_dataclass_to_tuple with JIT unpack_dataclass_to_tuple [tvm-ffi]
Posted by "tqchen (via GitHub)" <gi...@apache.org>.
tqchen commented on PR #563:
URL: https://github.com/apache/tvm-ffi/pull/563#issuecomment-4283218934
/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] [FEAT] Enhance map_dataclass_to_tuple with JIT unpack_dataclass_to_tuple [tvm-ffi]
Posted by "gemini-code-assist[bot] (via GitHub)" <gi...@apache.org>.
gemini-code-assist[bot] commented on code in PR #563:
URL: https://github.com/apache/tvm-ffi/pull/563#discussion_r3111744834
##########
python/tvm_ffi/utils/unpack_dataclass.py:
##########
@@ -0,0 +1,233 @@
+# 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.
+"""Fast dataclass-to-tuple conversion via JIT-compiled unpacking.
+
+This module provides ``unpack_dataclass_to_tuple``, a function that recursively
+converts dataclass instances to tuples. It JIT-compiles a per-class unpacker
+on first call and caches it per-thread for ~5-11x speedup over
+``dataclasses.astuple`` with no deep-copy of leaf values.
+"""
+
+from __future__ import annotations
+
+import dataclasses
+import keyword
+import threading
+import typing
+from typing import Any
+
+# Type alias for dataclass-to-tuple schema (internal).
+# Schema values:
+# None -> leaf, direct attribute access (zero cost)
+# "unpack" -> dynamic dispatch via unpack_dataclass_to_tuple at runtime
+# dict -> nested struct, recurse inline
+# Example: {"x": None, "y": None} -> (__x.x, __x.y,)
+# Example: {"cfg": {"x": None, "y": None}, "data": "unpack"}
+# -> ((__x.cfg.x, __x.cfg.y,), __dispatch(__x.data),)
+DataclassToTupleSchema = dict # dict[str, None | str | DataclassToTupleSchema]
+
+# Sentinel value in schema: field should be dynamically dispatched
+UNPACK = "unpack"
+
+# Thread-local cache for JIT-compiled per-class unpack functions
+_tls = threading.local()
+
+# Types known to be safe leaves (never contain dataclass instances)
+_KNOWN_LEAF_TYPES: set[type] = {int, float, str, bool, bytes, complex, type(None)}
+
+
+def _is_known_leaf_type(tp: Any) -> bool:
+ """Check if a type is definitely a leaf (no dataclass content possible)."""
+ if isinstance(tp, type):
+ return tp in _KNOWN_LEAF_TYPES
+ if tp is Ellipsis:
+ return True
+ origin = typing.get_origin(tp)
+ if origin is not None:
+ args = typing.get_args(tp)
+ return all(_is_known_leaf_type(a) for a in args)
+ return False
Review Comment:

The current implementation of `_is_known_leaf_type` considers `list` types as leaves if their arguments are leaves (e.g., `list[int]`). However, `dataclasses.astuple` (and the docstring for `unpack_dataclass_to_tuple` at line 178) specifies that lists should be converted to tuples.
By classifying `list[int]` as a leaf, the JIT-compiled code will return the list by reference instead of converting it to a tuple, leading to inconsistent return types compared to the dynamic path and `dataclasses.astuple`. Additionally, this function currently misses an optimization opportunity for `Union` and `Optional` types.
```python
def _is_known_leaf_type(tp: Any) -> bool:
"""Check if a type is definitely a leaf (no dataclass content or conversion needed)."""
if isinstance(tp, type):
return tp in _KNOWN_LEAF_TYPES
if tp is Ellipsis:
return True
origin = typing.get_origin(tp)
if origin is not None:
# Union/Optional are leaves if all their arguments are leaves.
# list is NOT a leaf because it must be converted to a tuple per astuple contract.
# dict/set/frozenset are leaves if their arguments are leaves (astuple doesn't convert them).
if origin in (tuple, dict, set, frozenset, typing.Union):
args = typing.get_args(tp)
return all(_is_known_leaf_type(a) for a in args)
return False
```
##########
python/tvm_ffi/utils/unpack_dataclass.py:
##########
@@ -0,0 +1,233 @@
+# 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.
+"""Fast dataclass-to-tuple conversion via JIT-compiled unpacking.
+
+This module provides ``unpack_dataclass_to_tuple``, a function that recursively
+converts dataclass instances to tuples. It JIT-compiles a per-class unpacker
+on first call and caches it per-thread for ~5-11x speedup over
+``dataclasses.astuple`` with no deep-copy of leaf values.
+"""
+
+from __future__ import annotations
+
+import dataclasses
+import keyword
+import threading
+import typing
+from typing import Any
+
+# Type alias for dataclass-to-tuple schema (internal).
+# Schema values:
+# None -> leaf, direct attribute access (zero cost)
+# "unpack" -> dynamic dispatch via unpack_dataclass_to_tuple at runtime
+# dict -> nested struct, recurse inline
+# Example: {"x": None, "y": None} -> (__x.x, __x.y,)
+# Example: {"cfg": {"x": None, "y": None}, "data": "unpack"}
+# -> ((__x.cfg.x, __x.cfg.y,), __dispatch(__x.data),)
+DataclassToTupleSchema = dict # dict[str, None | str | DataclassToTupleSchema]
+
+# Sentinel value in schema: field should be dynamically dispatched
+UNPACK = "unpack"
+
+# Thread-local cache for JIT-compiled per-class unpack functions
+_tls = threading.local()
+
+# Types known to be safe leaves (never contain dataclass instances)
+_KNOWN_LEAF_TYPES: set[type] = {int, float, str, bool, bytes, complex, type(None)}
+
+
+def _is_known_leaf_type(tp: Any) -> bool:
+ """Check if a type is definitely a leaf (no dataclass content possible)."""
+ if isinstance(tp, type):
+ return tp in _KNOWN_LEAF_TYPES
+ if tp is Ellipsis:
+ return True
+ origin = typing.get_origin(tp)
+ if origin is not None:
+ args = typing.get_args(tp)
+ return all(_is_known_leaf_type(a) for a in args)
+ return False
+
+
+def _classify_field_type(field_type: Any) -> None | str | DataclassToTupleSchema:
+ """Classify a resolved field type into a schema entry.
+
+ Conservative: only returns None (leaf) when we are certain the type
+ cannot contain a dataclass. Otherwise returns UNPACK (dynamic dispatch).
+ """
+ if isinstance(field_type, str) or field_type is Any or field_type is object:
+ return UNPACK
+ if dataclasses.is_dataclass(field_type) and isinstance(field_type, type):
+ return _extract_dataclass_to_tuple_schema(field_type)
+ # Known primitive types -> leaf
+ if isinstance(field_type, type) and field_type in _KNOWN_LEAF_TYPES:
+ return None
+ # Generic containers: check element types
+ origin = typing.get_origin(field_type)
+ if origin in (list, tuple, dict, set, frozenset):
+ args = typing.get_args(field_type)
+ if args and all(_is_known_leaf_type(a) for a in args):
+ return None
+ return UNPACK
Review Comment:

As noted in the feedback for `_is_known_leaf_type`, including `list` in the optimization that returns `None` (leaf) will cause the JIT-compiled code to return lists by reference, violating the contract that sequences are converted to tuples.
Also, adding `typing.Union` here would allow `Optional[int]` or `Union[int, str]` fields to be optimized as leaves when they contain no dataclasses.
```suggestion
# Generic containers: check element types
origin = typing.get_origin(field_type)
if origin in (tuple, dict, set, frozenset, typing.Union):
args = typing.get_args(field_type)
if args and all(_is_known_leaf_type(a) for a in args):
return None
return UNPACK
```
##########
python/tvm_ffi/utils/unpack_dataclass.py:
##########
@@ -0,0 +1,233 @@
+# 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.
+"""Fast dataclass-to-tuple conversion via JIT-compiled unpacking.
+
+This module provides ``unpack_dataclass_to_tuple``, a function that recursively
+converts dataclass instances to tuples. It JIT-compiles a per-class unpacker
+on first call and caches it per-thread for ~5-11x speedup over
+``dataclasses.astuple`` with no deep-copy of leaf values.
+"""
+
+from __future__ import annotations
+
+import dataclasses
+import keyword
+import threading
+import typing
+from typing import Any
+
+# Type alias for dataclass-to-tuple schema (internal).
+# Schema values:
+# None -> leaf, direct attribute access (zero cost)
+# "unpack" -> dynamic dispatch via unpack_dataclass_to_tuple at runtime
+# dict -> nested struct, recurse inline
+# Example: {"x": None, "y": None} -> (__x.x, __x.y,)
+# Example: {"cfg": {"x": None, "y": None}, "data": "unpack"}
+# -> ((__x.cfg.x, __x.cfg.y,), __dispatch(__x.data),)
+DataclassToTupleSchema = dict # dict[str, None | str | DataclassToTupleSchema]
+
+# Sentinel value in schema: field should be dynamically dispatched
+UNPACK = "unpack"
+
+# Thread-local cache for JIT-compiled per-class unpack functions
+_tls = threading.local()
+
+# Types known to be safe leaves (never contain dataclass instances)
+_KNOWN_LEAF_TYPES: set[type] = {int, float, str, bool, bytes, complex, type(None)}
+
+
+def _is_known_leaf_type(tp: Any) -> bool:
+ """Check if a type is definitely a leaf (no dataclass content possible)."""
+ if isinstance(tp, type):
+ return tp in _KNOWN_LEAF_TYPES
+ if tp is Ellipsis:
+ return True
+ origin = typing.get_origin(tp)
+ if origin is not None:
+ args = typing.get_args(tp)
+ return all(_is_known_leaf_type(a) for a in args)
+ return False
+
+
+def _classify_field_type(field_type: Any) -> None | str | DataclassToTupleSchema:
+ """Classify a resolved field type into a schema entry.
+
+ Conservative: only returns None (leaf) when we are certain the type
+ cannot contain a dataclass. Otherwise returns UNPACK (dynamic dispatch).
+ """
+ if isinstance(field_type, str) or field_type is Any or field_type is object:
+ return UNPACK
+ if dataclasses.is_dataclass(field_type) and isinstance(field_type, type):
+ return _extract_dataclass_to_tuple_schema(field_type)
+ # Known primitive types -> leaf
+ if isinstance(field_type, type) and field_type in _KNOWN_LEAF_TYPES:
+ return None
+ # Generic containers: check element types
+ origin = typing.get_origin(field_type)
+ if origin in (list, tuple, dict, set, frozenset):
+ args = typing.get_args(field_type)
+ if args and all(_is_known_leaf_type(a) for a in args):
+ return None
+ return UNPACK
+ # Unknown type — conservative: use dynamic dispatch
+ return UNPACK
+
+
+def _compile_dataclass_to_tuple_schema(prefix: str, schema: DataclassToTupleSchema) -> str:
+ """Compile a DataclassToTupleSchema into an inline tuple expression.
+
+ Parameters
+ ----------
+ prefix
+ The variable expression to unpack (e.g. "__x" or "__x.field").
+ schema
+ The schema dict mapping field names to:
+ - None: leaf, direct attribute access
+ - "unpack": dynamic dispatch via __dispatch() at runtime
+ - nested dict: recurse inline
+
+ Returns
+ -------
+ A string expression that evaluates to a tuple of the unpacked fields.
+
+ """
+ parts: list[str] = []
+ for field_name, sub_schema in schema.items():
+ field_expr = f"{prefix}.{field_name}"
+ if sub_schema is None:
+ parts.append(field_expr)
+ elif sub_schema == UNPACK:
+ parts.append(f"__dispatch({field_expr})")
+ else:
+ parts.append(_compile_dataclass_to_tuple_schema(field_expr, sub_schema))
+ return "(" + ", ".join(parts) + (",)" if parts else ")")
+
+
+def _validate_dataclass_to_tuple_schema(schema: DataclassToTupleSchema) -> None:
+ """Validate that a DataclassToTupleSchema contains only safe identifiers.
+
+ This is critical for security since field names are embedded directly
+ in generated code via exec(). The validation ensures:
+ - Keys are strings (type check)
+ - Keys pass str.isidentifier() — rejects any non-identifier characters
+ - Keys are not Python keywords — rejects control flow injection
+ - Values are only None, "unpack", or recursively-validated dicts
+
+ Combined with the hardcoded prefix ("__x") and restricted exec_globals,
+ this prevents any code injection through crafted field names.
+
+ """
+ if not isinstance(schema, dict):
+ raise TypeError(f"DataclassToTupleSchema must be a dict, got {type(schema).__name__}")
+ for field_name, sub_schema in schema.items():
+ if not isinstance(field_name, str):
+ raise TypeError(f"Schema field name must be a string, got {type(field_name).__name__}")
+ if not field_name.isidentifier():
+ raise ValueError(f"Schema field name {field_name!r} is not a valid Python identifier")
+ if keyword.iskeyword(field_name):
+ raise ValueError(f"Schema field name {field_name!r} is a Python keyword")
+ if sub_schema is not None and sub_schema != UNPACK:
+ _validate_dataclass_to_tuple_schema(sub_schema)
+
+
+def _extract_dataclass_to_tuple_schema(cls: type) -> DataclassToTupleSchema:
+ """Extract a DataclassToTupleSchema from a dataclass class using type annotations.
+
+ Classification per field (conservative: only leaf when certain):
+ - Known dataclass type -> nested schema (recurse inline)
+ - Known primitive type (int, float, str, bool, bytes, complex) -> None (leaf)
+ - Container with only known-leaf args (list[int], dict[str, float]) -> None (leaf)
+ - Container with dataclass/unknown args (list[Config]) -> "unpack" (dynamic dispatch)
+ - Any, object, unresolved string annotation -> "unpack" (dynamic dispatch)
+ - Unknown class -> "unpack" (dynamic dispatch)
+
+ Uses typing.get_type_hints() to resolve PEP 563 string annotations.
+
+ """
+ if not dataclasses.is_dataclass(cls) or not isinstance(cls, type):
+ raise TypeError(f"Expected a dataclass class, got {cls!r}")
+ try:
+ type_hints = typing.get_type_hints(cls)
+ except (NameError, TypeError):
+ type_hints = {}
+ schema: DataclassToTupleSchema = {}
+ for f in dataclasses.fields(cls):
+ field_type = type_hints.get(f.name, f.type)
+ schema[f.name] = _classify_field_type(field_type)
+ return schema
+
+
+def unpack_dataclass_to_tuple(x: Any) -> Any:
+ """Fast recursively unpack a dataclass value to tuple representation.
+
+ - Dataclass instances are unpacked to tuples of their field values.
+ - Lists and tuples are recursed element-wise, returning a tuple.
Review Comment:

The docstring states that lists and tuples are recursed and return a tuple. However, the JIT optimization in `_classify_field_type` (as currently implemented) allows fields typed as `list[int]` to be passed through as lists. This creates an inconsistency where the return type of a list depends on whether it is the root object being unpacked or a field within a dataclass.
If the intention is to strictly follow the `astuple` contract (always returning tuples for sequences), the optimization for `list` types should be removed from the leaf classification logic.
--
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] [FEAT] Enhance map_dataclass_to_tuple with JIT unpack_dataclass_to_tuple [tvm-ffi]
Posted by "gemini-code-assist[bot] (via GitHub)" <gi...@apache.org>.
gemini-code-assist[bot] commented on code in PR #563:
URL: https://github.com/apache/tvm-ffi/pull/563#discussion_r3112031110
##########
python/tvm_ffi/utils/unpack_dataclass.py:
##########
@@ -0,0 +1,263 @@
+# 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.
+"""Fast dataclass-to-tuple conversion via JIT-compiled unpacking.
+
+This module provides ``unpack_dataclass_to_tuple``, a function that recursively
+converts dataclass instances to tuples. It JIT-compiles a per-class unpacker
+on first call and caches it per-thread for ~5-11x speedup over
+``dataclasses.astuple`` with no deep-copy of leaf values.
+"""
+
+from __future__ import annotations
+
+import dataclasses
+import keyword
+import sys
+import threading
+import typing
+from typing import Any
+
+# Support both typing.Union and types.UnionType (PEP 604, Python 3.10+)
+if sys.version_info >= (3, 10):
+ import types
+
+ _LEAF_CONTAINER_ORIGINS = (tuple, dict, set, frozenset, typing.Union, types.UnionType)
+else:
+ _LEAF_CONTAINER_ORIGINS = (tuple, dict, set, frozenset, typing.Union)
+
+# Type alias for dataclass-to-tuple schema (internal).
+# Schema values:
+# None -> leaf, direct attribute access (zero cost)
+# "unpack" -> dynamic dispatch via unpack_dataclass_to_tuple at runtime
+# dict -> nested struct, recurse inline
+# Example: {"x": None, "y": None} -> (__x.x, __x.y,)
+# Example: {"cfg": {"x": None, "y": None}, "data": "unpack"}
+# -> ((__x.cfg.x, __x.cfg.y,), __dispatch(__x.data),)
+DataclassToTupleSchema = dict # dict[str, None | str | DataclassToTupleSchema]
+
+# Sentinel value in schema: field should be dynamically dispatched
+UNPACK = "unpack"
+
+# Thread-local cache for JIT-compiled per-class unpack functions
+_tls = threading.local()
+
+# Types known to be safe leaves (never contain dataclass instances)
+_KNOWN_LEAF_TYPES: set[type] = {int, float, str, bool, bytes, complex, type(None)}
+
+
+def _is_known_leaf_type(tp: Any) -> bool:
+ """Check if a type is definitely a leaf (no dataclass content or conversion needed).
+
+ Note: list is NOT a leaf because it must be converted to a tuple per the
+ unpack contract (matching dataclasses.astuple behavior).
+ """
+ if isinstance(tp, type):
+ return tp in _KNOWN_LEAF_TYPES
+ if tp is Ellipsis:
+ return True
+ origin = typing.get_origin(tp)
+ if origin is not None:
+ # list is NOT a leaf — must be converted to tuple
+ # tuple/dict/set/frozenset/Union are leaves if all args are leaves
+ if origin in _LEAF_CONTAINER_ORIGINS:
+ args = typing.get_args(tp)
+ return bool(args) and all(_is_known_leaf_type(a) for a in args)
+ return False
+
+
+def _classify_field_type(
+ field_type: Any, memo: set[type] | None = None
+) -> None | str | DataclassToTupleSchema:
+ """Classify a resolved field type into a schema entry.
+
+ Conservative: only returns None (leaf) when we are certain the type
+ cannot contain a dataclass. Otherwise returns UNPACK (dynamic dispatch).
+ """
+ if isinstance(field_type, str) or field_type is Any or field_type is object:
+ return UNPACK
+ if dataclasses.is_dataclass(field_type) and isinstance(field_type, type):
+ # Guard against infinite recursion for self-referential dataclasses
+ if memo is not None and field_type in memo:
+ return UNPACK
+ return _extract_dataclass_to_tuple_schema(field_type, memo=memo)
+ # Known primitive types -> leaf
+ if isinstance(field_type, type) and field_type in _KNOWN_LEAF_TYPES:
+ return None
+ # Generic containers: check element types
+ # list always needs UNPACK (must be converted to tuple)
+ # tuple/dict/set/frozenset/Union are leaves if all args are known leaves
+ # Generic containers: list always UNPACK (must convert to tuple).
+ # tuple/dict/set/frozenset/Union are leaves only if all args are known leaves.
+ # Everything else (unknown type) -> UNPACK (conservative).
+ origin = typing.get_origin(field_type)
+ if origin in _LEAF_CONTAINER_ORIGINS:
+ args = typing.get_args(field_type)
+ if args and all(_is_known_leaf_type(a) for a in args):
+ return None
+ return UNPACK
+
+
+def _compile_dataclass_to_tuple_schema(prefix: str, schema: DataclassToTupleSchema) -> str:
+ """Compile a DataclassToTupleSchema into an inline tuple expression.
+
+ Parameters
+ ----------
+ prefix
+ The variable expression to unpack (e.g. "__x" or "__x.field").
+ schema
+ The schema dict mapping field names to:
+ - None: leaf, direct attribute access
+ - "unpack": dynamic dispatch via __dispatch() at runtime
+ - nested dict: recurse inline
+
+ Returns
+ -------
+ A string expression that evaluates to a tuple of the unpacked fields.
+
+ """
+ parts: list[str] = []
+ for field_name, sub_schema in schema.items():
+ field_expr = f"{prefix}.{field_name}"
+ if sub_schema is None:
+ parts.append(field_expr)
+ elif sub_schema == UNPACK:
+ parts.append(f"__dispatch({field_expr})")
+ else:
+ parts.append(_compile_dataclass_to_tuple_schema(field_expr, sub_schema))
+ return "(" + ", ".join(parts) + (",)" if parts else ")")
+
+
+def _validate_dataclass_to_tuple_schema(schema: DataclassToTupleSchema) -> None:
+ """Validate that a DataclassToTupleSchema contains only safe identifiers.
+
+ This is critical for security since field names are embedded directly
+ in generated code via exec(). The validation ensures:
+ - Keys are strings (type check)
+ - Keys pass str.isidentifier() — rejects any non-identifier characters
+ - Keys are not Python keywords — rejects control flow injection
+ - Values are only None, "unpack", or recursively-validated dicts
+
+ Combined with the hardcoded prefix ("__x") and restricted exec_globals,
+ this prevents any code injection through crafted field names.
+
+ """
+ if not isinstance(schema, dict):
+ raise TypeError(f"DataclassToTupleSchema must be a dict, got {type(schema).__name__}")
+ for field_name, sub_schema in schema.items():
+ if not isinstance(field_name, str):
+ raise TypeError(f"Schema field name must be a string, got {type(field_name).__name__}")
+ if not field_name.isidentifier():
+ raise ValueError(f"Schema field name {field_name!r} is not a valid Python identifier")
+ if keyword.iskeyword(field_name):
+ raise ValueError(f"Schema field name {field_name!r} is a Python keyword")
+ if sub_schema is not None and sub_schema != UNPACK:
+ _validate_dataclass_to_tuple_schema(sub_schema)
+
+
+def _extract_dataclass_to_tuple_schema(
+ cls: type, *, memo: set[type] | None = None
+) -> DataclassToTupleSchema:
+ """Extract a DataclassToTupleSchema from a dataclass class using type annotations.
+
+ Classification per field (conservative: only leaf when certain):
+ - Known dataclass type -> nested schema (recurse inline)
+ - Known primitive type (int, float, str, bool, bytes, complex) -> None (leaf)
+ - Container with only known-leaf args (list[int], dict[str, float]) -> None (leaf)
+ - Container with dataclass/unknown args (list[Config]) -> "unpack" (dynamic dispatch)
+ - Any, object, unresolved string annotation -> "unpack" (dynamic dispatch)
+ - Unknown class -> "unpack" (dynamic dispatch)
+
+ Uses typing.get_type_hints() to resolve PEP 563 string annotations.
+ Uses memo set to prevent infinite recursion on self-referential dataclasses.
+
+ """
+ if not dataclasses.is_dataclass(cls) or not isinstance(cls, type):
+ raise TypeError(f"Expected a dataclass class, got {cls!r}")
+ if memo is None:
+ memo = set()
+ memo.add(cls)
+ try:
+ type_hints = typing.get_type_hints(cls)
+ except (NameError, TypeError):
Review Comment:

While `NameError` and `TypeError` are the most common exceptions raised by `typing.get_type_hints` (typically due to forward references that cannot be resolved), it can also raise `AttributeError` in certain edge cases, such as when a class's module cannot be found or when dealing with complex nested types in some Python versions. Adding `AttributeError` to the caught exceptions would make the schema extraction more robust.
```suggestion
except (NameError, TypeError, AttributeError):
```
##########
python/tvm_ffi/utils/unpack_dataclass.py:
##########
@@ -0,0 +1,263 @@
+# 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.
+"""Fast dataclass-to-tuple conversion via JIT-compiled unpacking.
+
+This module provides ``unpack_dataclass_to_tuple``, a function that recursively
+converts dataclass instances to tuples. It JIT-compiles a per-class unpacker
+on first call and caches it per-thread for ~5-11x speedup over
+``dataclasses.astuple`` with no deep-copy of leaf values.
+"""
+
+from __future__ import annotations
+
+import dataclasses
+import keyword
+import sys
+import threading
+import typing
+from typing import Any
+
+# Support both typing.Union and types.UnionType (PEP 604, Python 3.10+)
+if sys.version_info >= (3, 10):
+ import types
+
+ _LEAF_CONTAINER_ORIGINS = (tuple, dict, set, frozenset, typing.Union, types.UnionType)
+else:
+ _LEAF_CONTAINER_ORIGINS = (tuple, dict, set, frozenset, typing.Union)
+
+# Type alias for dataclass-to-tuple schema (internal).
+# Schema values:
+# None -> leaf, direct attribute access (zero cost)
+# "unpack" -> dynamic dispatch via unpack_dataclass_to_tuple at runtime
+# dict -> nested struct, recurse inline
+# Example: {"x": None, "y": None} -> (__x.x, __x.y,)
+# Example: {"cfg": {"x": None, "y": None}, "data": "unpack"}
+# -> ((__x.cfg.x, __x.cfg.y,), __dispatch(__x.data),)
+DataclassToTupleSchema = dict # dict[str, None | str | DataclassToTupleSchema]
+
+# Sentinel value in schema: field should be dynamically dispatched
+UNPACK = "unpack"
+
+# Thread-local cache for JIT-compiled per-class unpack functions
+_tls = threading.local()
+
+# Types known to be safe leaves (never contain dataclass instances)
+_KNOWN_LEAF_TYPES: set[type] = {int, float, str, bool, bytes, complex, type(None)}
+
+
+def _is_known_leaf_type(tp: Any) -> bool:
+ """Check if a type is definitely a leaf (no dataclass content or conversion needed).
+
+ Note: list is NOT a leaf because it must be converted to a tuple per the
+ unpack contract (matching dataclasses.astuple behavior).
+ """
+ if isinstance(tp, type):
+ return tp in _KNOWN_LEAF_TYPES
+ if tp is Ellipsis:
+ return True
+ origin = typing.get_origin(tp)
+ if origin is not None:
+ # list is NOT a leaf — must be converted to tuple
+ # tuple/dict/set/frozenset/Union are leaves if all args are leaves
+ if origin in _LEAF_CONTAINER_ORIGINS:
+ args = typing.get_args(tp)
+ return bool(args) and all(_is_known_leaf_type(a) for a in args)
+ return False
+
+
+def _classify_field_type(
+ field_type: Any, memo: set[type] | None = None
+) -> None | str | DataclassToTupleSchema:
+ """Classify a resolved field type into a schema entry.
+
+ Conservative: only returns None (leaf) when we are certain the type
+ cannot contain a dataclass. Otherwise returns UNPACK (dynamic dispatch).
+ """
+ if isinstance(field_type, str) or field_type is Any or field_type is object:
+ return UNPACK
+ if dataclasses.is_dataclass(field_type) and isinstance(field_type, type):
+ # Guard against infinite recursion for self-referential dataclasses
+ if memo is not None and field_type in memo:
+ return UNPACK
+ return _extract_dataclass_to_tuple_schema(field_type, memo=memo)
+ # Known primitive types -> leaf
+ if isinstance(field_type, type) and field_type in _KNOWN_LEAF_TYPES:
+ return None
+ # Generic containers: check element types
+ # list always needs UNPACK (must be converted to tuple)
+ # tuple/dict/set/frozenset/Union are leaves if all args are known leaves
+ # Generic containers: list always UNPACK (must convert to tuple).
+ # tuple/dict/set/frozenset/Union are leaves only if all args are known leaves.
+ # Everything else (unknown type) -> UNPACK (conservative).
+ origin = typing.get_origin(field_type)
+ if origin in _LEAF_CONTAINER_ORIGINS:
+ args = typing.get_args(field_type)
+ if args and all(_is_known_leaf_type(a) for a in args):
+ return None
+ return UNPACK
+
+
+def _compile_dataclass_to_tuple_schema(prefix: str, schema: DataclassToTupleSchema) -> str:
+ """Compile a DataclassToTupleSchema into an inline tuple expression.
+
+ Parameters
+ ----------
+ prefix
+ The variable expression to unpack (e.g. "__x" or "__x.field").
+ schema
+ The schema dict mapping field names to:
+ - None: leaf, direct attribute access
+ - "unpack": dynamic dispatch via __dispatch() at runtime
+ - nested dict: recurse inline
+
+ Returns
+ -------
+ A string expression that evaluates to a tuple of the unpacked fields.
+
+ """
+ parts: list[str] = []
+ for field_name, sub_schema in schema.items():
+ field_expr = f"{prefix}.{field_name}"
+ if sub_schema is None:
+ parts.append(field_expr)
+ elif sub_schema == UNPACK:
+ parts.append(f"__dispatch({field_expr})")
+ else:
+ parts.append(_compile_dataclass_to_tuple_schema(field_expr, sub_schema))
+ return "(" + ", ".join(parts) + (",)" if parts else ")")
+
+
+def _validate_dataclass_to_tuple_schema(schema: DataclassToTupleSchema) -> None:
+ """Validate that a DataclassToTupleSchema contains only safe identifiers.
+
+ This is critical for security since field names are embedded directly
+ in generated code via exec(). The validation ensures:
+ - Keys are strings (type check)
+ - Keys pass str.isidentifier() — rejects any non-identifier characters
+ - Keys are not Python keywords — rejects control flow injection
+ - Values are only None, "unpack", or recursively-validated dicts
+
+ Combined with the hardcoded prefix ("__x") and restricted exec_globals,
+ this prevents any code injection through crafted field names.
+
+ """
+ if not isinstance(schema, dict):
+ raise TypeError(f"DataclassToTupleSchema must be a dict, got {type(schema).__name__}")
+ for field_name, sub_schema in schema.items():
+ if not isinstance(field_name, str):
+ raise TypeError(f"Schema field name must be a string, got {type(field_name).__name__}")
+ if not field_name.isidentifier():
+ raise ValueError(f"Schema field name {field_name!r} is not a valid Python identifier")
+ if keyword.iskeyword(field_name):
+ raise ValueError(f"Schema field name {field_name!r} is a Python keyword")
+ if sub_schema is not None and sub_schema != UNPACK:
+ _validate_dataclass_to_tuple_schema(sub_schema)
+
+
+def _extract_dataclass_to_tuple_schema(
+ cls: type, *, memo: set[type] | None = None
+) -> DataclassToTupleSchema:
+ """Extract a DataclassToTupleSchema from a dataclass class using type annotations.
+
+ Classification per field (conservative: only leaf when certain):
+ - Known dataclass type -> nested schema (recurse inline)
+ - Known primitive type (int, float, str, bool, bytes, complex) -> None (leaf)
+ - Container with only known-leaf args (list[int], dict[str, float]) -> None (leaf)
+ - Container with dataclass/unknown args (list[Config]) -> "unpack" (dynamic dispatch)
+ - Any, object, unresolved string annotation -> "unpack" (dynamic dispatch)
+ - Unknown class -> "unpack" (dynamic dispatch)
+
+ Uses typing.get_type_hints() to resolve PEP 563 string annotations.
+ Uses memo set to prevent infinite recursion on self-referential dataclasses.
+
+ """
+ if not dataclasses.is_dataclass(cls) or not isinstance(cls, type):
+ raise TypeError(f"Expected a dataclass class, got {cls!r}")
+ if memo is None:
+ memo = set()
+ memo.add(cls)
+ try:
+ type_hints = typing.get_type_hints(cls)
+ except (NameError, TypeError):
+ type_hints = {}
+ schema: DataclassToTupleSchema = {}
+ for f in dataclasses.fields(cls):
+ field_type = type_hints.get(f.name, f.type)
+ schema[f.name] = _classify_field_type(field_type, memo=memo)
+ return schema
+
+
+def unpack_dataclass_to_tuple(x: Any) -> Any:
+ """Fast recursively unpack a dataclass value to tuple representation.
+
+ - Dataclass instances are unpacked to tuples of their field values.
+ - Lists and tuples are recursed element-wise, returning a tuple.
+ - Dicts are recursed on values, returning a new dict.
Review Comment:

The docstring states that dicts are recursed on values, returning a new dict. However, the JIT optimization in `_classify_field_type` (line 107) and `_is_known_leaf_type` (line 78) will mark a `dict` as a leaf if all its type arguments are known leaf types (e.g., `dict[str, int]`). In such cases, the JIT-compiled code will pass the dictionary through by reference rather than creating a new one. While this aligns with the performance goal of avoiding deep copies, it slightly contradicts this specific line in the docstring for 'leaf' dictionaries. Consider clarifying that recursion only occurs if the dictionary is not identified as a leaf at compile-time.
--
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] [FEAT] Enhance map_dataclass_to_tuple with JIT unpack_dataclass_to_tuple [tvm-ffi]
Posted by "tqchen (via GitHub)" <gi...@apache.org>.
tqchen commented on PR #563:
URL: https://github.com/apache/tvm-ffi/pull/563#issuecomment-4282133266
/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] [FEAT] Enhance map_dataclass_to_tuple with JIT unpack_dataclass_to_tuple [tvm-ffi]
Posted by "gemini-code-assist[bot] (via GitHub)" <gi...@apache.org>.
gemini-code-assist[bot] commented on code in PR #563:
URL: https://github.com/apache/tvm-ffi/pull/563#discussion_r3111708059
##########
python/tvm_ffi/utils/unpack_dataclass.py:
##########
@@ -0,0 +1,233 @@
+# 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.
+"""Fast dataclass-to-tuple conversion via JIT-compiled unpacking.
+
+This module provides ``unpack_dataclass_to_tuple``, a function that recursively
+converts dataclass instances to tuples. It JIT-compiles a per-class unpacker
+on first call and caches it per-thread for ~5-11x speedup over
+``dataclasses.astuple`` with no deep-copy of leaf values.
+"""
+
+from __future__ import annotations
+
+import dataclasses
+import keyword
+import threading
+import typing
+from typing import Any
+
+# Type alias for dataclass-to-tuple schema (internal).
+# Schema values:
+# None -> leaf, direct attribute access (zero cost)
+# "unpack" -> dynamic dispatch via unpack_dataclass_to_tuple at runtime
+# dict -> nested struct, recurse inline
+# Example: {"x": None, "y": None} -> (__x.x, __x.y,)
+# Example: {"cfg": {"x": None, "y": None}, "data": "unpack"}
+# -> ((__x.cfg.x, __x.cfg.y,), __dispatch(__x.data),)
+DataclassToTupleSchema = dict[str, "None | str | DataclassToTupleSchema"]
+
+# Sentinel value in schema: field should be dynamically dispatched
+UNPACK = "unpack"
+
+# Thread-local cache for JIT-compiled per-class unpack functions
+_tls = threading.local()
+
+# Types known to be safe leaves (never contain dataclass instances)
+_KNOWN_LEAF_TYPES: set[type] = {int, float, str, bool, bytes, complex, type(None)}
+
+
+def _is_known_leaf_type(tp: Any) -> bool:
+ """Check if a type is definitely a leaf (no dataclass content possible)."""
+ if isinstance(tp, type):
+ return tp in _KNOWN_LEAF_TYPES
+ if tp is Ellipsis:
+ return True
+ origin = typing.get_origin(tp)
+ if origin is not None:
+ args = typing.get_args(tp)
+ return all(_is_known_leaf_type(a) for a in args)
+ return False
+
+
+def _classify_field_type(field_type: Any) -> None | str | DataclassToTupleSchema:
+ """Classify a resolved field type into a schema entry.
+
+ Conservative: only returns None (leaf) when we are certain the type
+ cannot contain a dataclass. Otherwise returns UNPACK (dynamic dispatch).
+ """
+ if isinstance(field_type, str) or field_type is Any or field_type is object:
+ return UNPACK
+ if dataclasses.is_dataclass(field_type) and isinstance(field_type, type):
+ return _extract_dataclass_to_tuple_schema(field_type)
+ # Known primitive types -> leaf
+ if isinstance(field_type, type) and field_type in _KNOWN_LEAF_TYPES:
+ return None
+ # Generic containers: check element types
+ origin = typing.get_origin(field_type)
+ if origin in (list, tuple, dict, set, frozenset):
+ args = typing.get_args(field_type)
+ if args and all(_is_known_leaf_type(a) for a in args):
+ return None
+ return UNPACK
+ # Unknown type — conservative: use dynamic dispatch
+ return UNPACK
+
+
+def _compile_dataclass_to_tuple_schema(prefix: str, schema: DataclassToTupleSchema) -> str:
+ """Compile a DataclassToTupleSchema into an inline tuple expression.
+
+ Parameters
+ ----------
+ prefix
+ The variable expression to unpack (e.g. "__x" or "__x.field").
+ schema
+ The schema dict mapping field names to:
+ - None: leaf, direct attribute access
+ - "unpack": dynamic dispatch via __dispatch() at runtime
+ - nested dict: recurse inline
+
+ Returns
+ -------
+ A string expression that evaluates to a tuple of the unpacked fields.
+
+ """
+ parts: list[str] = []
+ for field_name, sub_schema in schema.items():
+ field_expr = f"{prefix}.{field_name}"
+ if sub_schema is None:
+ parts.append(field_expr)
+ elif sub_schema == UNPACK:
+ parts.append(f"__dispatch({field_expr})")
+ else:
+ parts.append(_compile_dataclass_to_tuple_schema(field_expr, sub_schema))
+ return "(" + ", ".join(parts) + ",)"
+
+
+def _validate_dataclass_to_tuple_schema(schema: DataclassToTupleSchema) -> None:
+ """Validate that a DataclassToTupleSchema contains only safe identifiers.
+
+ This is critical for security since field names are embedded directly
+ in generated code via exec(). The validation ensures:
+ - Keys are strings (type check)
+ - Keys pass str.isidentifier() — rejects any non-identifier characters
+ - Keys are not Python keywords — rejects control flow injection
+ - Values are only None, "unpack", or recursively-validated dicts
+
+ Combined with the hardcoded prefix ("__x") and restricted exec_globals,
+ this prevents any code injection through crafted field names.
+
+ """
+ if not isinstance(schema, dict):
+ raise TypeError(f"DataclassToTupleSchema must be a dict, got {type(schema).__name__}")
+ for field_name, sub_schema in schema.items():
+ if not isinstance(field_name, str):
+ raise TypeError(f"Schema field name must be a string, got {type(field_name).__name__}")
+ if not field_name.isidentifier():
+ raise ValueError(f"Schema field name {field_name!r} is not a valid Python identifier")
+ if keyword.iskeyword(field_name):
+ raise ValueError(f"Schema field name {field_name!r} is a Python keyword")
+ if sub_schema is not None and sub_schema != UNPACK:
+ _validate_dataclass_to_tuple_schema(sub_schema)
+
+
+def _extract_dataclass_to_tuple_schema(cls: type) -> DataclassToTupleSchema:
+ """Extract a DataclassToTupleSchema from a dataclass class using type annotations.
+
+ Classification per field (conservative: only leaf when certain):
+ - Known dataclass type -> nested schema (recurse inline)
+ - Known primitive type (int, float, str, bool, bytes, complex) -> None (leaf)
+ - Container with only known-leaf args (list[int], dict[str, float]) -> None (leaf)
+ - Container with dataclass/unknown args (list[Config]) -> "unpack" (dynamic dispatch)
+ - Any, object, unresolved string annotation -> "unpack" (dynamic dispatch)
+ - Unknown class -> "unpack" (dynamic dispatch)
+
+ Uses typing.get_type_hints() to resolve PEP 563 string annotations.
+
+ """
+ if not dataclasses.is_dataclass(cls) or not isinstance(cls, type):
+ raise TypeError(f"Expected a dataclass class, got {cls!r}")
+ try:
+ type_hints = typing.get_type_hints(cls)
+ except Exception:
Review Comment:

Catching all exceptions from `typing.get_type_hints` might mask unexpected issues. While it's used here as a fallback, it's generally better to catch specific exceptions like `NameError` or `TypeError` that are expected when type hints cannot be resolved.
```suggestion
except (NameError, TypeError):
```
##########
python/tvm_ffi/utils/unpack_dataclass.py:
##########
@@ -0,0 +1,233 @@
+# 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.
+"""Fast dataclass-to-tuple conversion via JIT-compiled unpacking.
+
+This module provides ``unpack_dataclass_to_tuple``, a function that recursively
+converts dataclass instances to tuples. It JIT-compiles a per-class unpacker
+on first call and caches it per-thread for ~5-11x speedup over
+``dataclasses.astuple`` with no deep-copy of leaf values.
+"""
+
+from __future__ import annotations
+
+import dataclasses
+import keyword
+import threading
+import typing
+from typing import Any
+
+# Type alias for dataclass-to-tuple schema (internal).
+# Schema values:
+# None -> leaf, direct attribute access (zero cost)
+# "unpack" -> dynamic dispatch via unpack_dataclass_to_tuple at runtime
+# dict -> nested struct, recurse inline
+# Example: {"x": None, "y": None} -> (__x.x, __x.y,)
+# Example: {"cfg": {"x": None, "y": None}, "data": "unpack"}
+# -> ((__x.cfg.x, __x.cfg.y,), __dispatch(__x.data),)
+DataclassToTupleSchema = dict[str, "None | str | DataclassToTupleSchema"]
+
+# Sentinel value in schema: field should be dynamically dispatched
+UNPACK = "unpack"
+
+# Thread-local cache for JIT-compiled per-class unpack functions
+_tls = threading.local()
+
+# Types known to be safe leaves (never contain dataclass instances)
+_KNOWN_LEAF_TYPES: set[type] = {int, float, str, bool, bytes, complex, type(None)}
+
+
+def _is_known_leaf_type(tp: Any) -> bool:
+ """Check if a type is definitely a leaf (no dataclass content possible)."""
+ if isinstance(tp, type):
+ return tp in _KNOWN_LEAF_TYPES
+ if tp is Ellipsis:
+ return True
+ origin = typing.get_origin(tp)
+ if origin is not None:
+ args = typing.get_args(tp)
+ return all(_is_known_leaf_type(a) for a in args)
+ return False
+
+
+def _classify_field_type(field_type: Any) -> None | str | DataclassToTupleSchema:
+ """Classify a resolved field type into a schema entry.
+
+ Conservative: only returns None (leaf) when we are certain the type
+ cannot contain a dataclass. Otherwise returns UNPACK (dynamic dispatch).
+ """
+ if isinstance(field_type, str) or field_type is Any or field_type is object:
+ return UNPACK
+ if dataclasses.is_dataclass(field_type) and isinstance(field_type, type):
+ return _extract_dataclass_to_tuple_schema(field_type)
+ # Known primitive types -> leaf
+ if isinstance(field_type, type) and field_type in _KNOWN_LEAF_TYPES:
+ return None
+ # Generic containers: check element types
+ origin = typing.get_origin(field_type)
+ if origin in (list, tuple, dict, set, frozenset):
+ args = typing.get_args(field_type)
+ if args and all(_is_known_leaf_type(a) for a in args):
+ return None
+ return UNPACK
+ # Unknown type — conservative: use dynamic dispatch
+ return UNPACK
+
+
+def _compile_dataclass_to_tuple_schema(prefix: str, schema: DataclassToTupleSchema) -> str:
+ """Compile a DataclassToTupleSchema into an inline tuple expression.
+
+ Parameters
+ ----------
+ prefix
+ The variable expression to unpack (e.g. "__x" or "__x.field").
+ schema
+ The schema dict mapping field names to:
+ - None: leaf, direct attribute access
+ - "unpack": dynamic dispatch via __dispatch() at runtime
+ - nested dict: recurse inline
+
+ Returns
+ -------
+ A string expression that evaluates to a tuple of the unpacked fields.
+
+ """
+ parts: list[str] = []
+ for field_name, sub_schema in schema.items():
+ field_expr = f"{prefix}.{field_name}"
+ if sub_schema is None:
+ parts.append(field_expr)
+ elif sub_schema == UNPACK:
+ parts.append(f"__dispatch({field_expr})")
+ else:
+ parts.append(_compile_dataclass_to_tuple_schema(field_expr, sub_schema))
+ return "(" + ", ".join(parts) + ",)"
Review Comment:

The current implementation generates `(,)` for a dataclass with no fields, which is invalid Python syntax. It should generate `()` instead.
```suggestion
return "(" + ", ".join(parts) + ("," if parts else "") + ")"
```
--
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] [FEAT] Enhance map_dataclass_to_tuple with JIT unpack_dataclass_to_tuple [tvm-ffi]
Posted by "tqchen (via GitHub)" <gi...@apache.org>.
tqchen commented on PR #563:
URL: https://github.com/apache/tvm-ffi/pull/563#issuecomment-4282377019
/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