1# Licensed to the Apache Software Foundation (ASF) under one
2# or more contributor license agreements.  See the NOTICE file
3# distributed with this work for additional information
4# regarding copyright ownership.  The ASF licenses this file
5# to you under the Apache License, Version 2.0 (the
6# "License"); you may not use this file except in compliance
7# with the License.  You may obtain a copy of the License at
8#
9#   http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing,
12# software distributed under the License is distributed on an
13# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14# KIND, either express or implied.  See the License for the
15# specific language governing permissions and limitations
16# under the License.
17"""Wrapping functions to bridge frameworks with DLPack support to TVM"""
18from .. import ndarray
19
20def convert_func(tvm_func, tensor_type, to_dlpack_func):
21    """Convert a tvm function into one that accepts a tensor from another
22       framework, provided the other framework supports DLPACK
23
24    Parameters
25    ----------
26    tvm_func: Function
27        Built tvm function operating on arrays
28
29    tensor_type: Type
30        Type of the tensors of the target framework
31
32    to_dlpack_func: Function
33        Function to convert the source tensors to DLPACK
34    """
35    assert callable(tvm_func)
36
37    def _wrapper(*args):
38        args = tuple(ndarray.from_dlpack(to_dlpack_func(arg))\
39            if isinstance(arg, tensor_type) else arg for arg in args)
40        return tvm_func(*args)
41
42    return _wrapper
43
44def to_pytorch_func(tvm_func):
45    """Convert a tvm function into one that accepts PyTorch tensors
46
47    Parameters
48    ----------
49    tvm_func: Function
50        Built tvm function operating on arrays
51
52    Returns
53    -------
54    wrapped_func: Function
55        Wrapped tvm function that operates on PyTorch tensors
56    """
57    import torch
58    import torch.utils.dlpack
59    return convert_func(tvm_func, torch.Tensor, torch.utils.dlpack.to_dlpack)
60