Skip to content

Conversation

@tlopex
Copy link
Member

@tlopex tlopex commented Sep 20, 2025

This PR implements the R.call_py_func operator that allows compiled TVM Relax modules to call Python functions at runtime. This enables integration between TVM's compiled code and Python through a robust VM backend implementation.

Simple Usage with BasePyModule

@I.ir_module
class MyModule(BasePyModule):
    @I.pyfunc
    def torch_relu(self, x):
        return torch.relu(x)
    
    @R.function
    def forward(x: R.Tensor((10,), "float32")) -> R.Tensor((10,), "float32"):
        return R.call_py_func("torch_relu", (x,), out_sinfo=R.Tensor((10,), "float32"))

Direct VM Backend Usage (Manual)

# Manually register Python function with VM backend
register_func = tvm.get_global_func("vm.builtin.register_py_func")
register_func("my_func", my_python_function)

# Use in Relax function (compiled to VM backend)
@R.function
def test(x: R.Tensor((5,), "float32")) -> R.Tensor((5,), "float32"):
    return R.call_py_func("my_func", (x,), out_sinfo=R.Tensor((5,), "float32"))

# Manual cleanup (required for direct VM backend usage)
clear_func = tvm.get_global_func("vm.builtin.clear_py_func_registry")
clear_func()

@tlopex
Copy link
Member Author

tlopex commented Sep 20, 2025

cc @MasterJH5574

Copy link
Contributor

@MasterJH5574 MasterJH5574 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks great, thank you @tlopex!

@MasterJH5574 MasterJH5574 merged commit a54af64 into apache:main Sep 22, 2025
13 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants