This is an automated email from the ASF dual-hosted git repository.
junrushao pushed a commit to branch unity
in repository https://gitbox.apache.org/repos/asf/tvm.git
The following commit(s) were added to refs/heads/unity by this push:
new 4ad3f3389c [Unity][Frontend][NN] Add nn.MultiLinear (#15662)
4ad3f3389c is described below
commit 4ad3f3389c07b3e15d4a76096c3d34471f4300d8
Author: Junru Shao <[email protected]>
AuthorDate: Mon Sep 4 10:35:58 2023 -0700
[Unity][Frontend][NN] Add nn.MultiLinear (#15662)
This PR introduces `nn.MultiLinear` as an extension to `nn.Linear`
which is arithmetically equivalent to applying multiple `nn.Linear` to
the same input.
For example, QKV projection in attention, represented in `nn.Linear`
being:
```python
q_proj = nn.Linear(hidden_dim, ...)
k_proj = nn.Linear(hidden_dim, ...)
v_proj = nn.Linear(hidden_dim, ...)
q = q_proj(x)
k = k_proj(x)
v = v_proj(x)
```
could be simplified using `nn.MultiLinear` as:
```python
qkv_proj = nn.MultiLinear((hidden_dim, hidden_dim, hidden_dim), ...)
q, k, v = qkv_proj(x)
```
The underlying implementation, by default, will fuse all the projection
matrices into a single one, to allow potentially larger room for
optimization.
---
python/tvm/relax/frontend/nn/modules.py | 54 +++++++++++++++++++++++++-
python/tvm/relax/frontend/nn/op.py | 30 +++++++++++++-
tests/python/relax/test_frontend_nn_modules.py | 50 ++++++++++++++++++++++++
3 files changed, 132 insertions(+), 2 deletions(-)
diff --git a/python/tvm/relax/frontend/nn/modules.py
b/python/tvm/relax/frontend/nn/modules.py
index 3eb3c569dc..f07bcb1ce3 100644
--- a/python/tvm/relax/frontend/nn/modules.py
+++ b/python/tvm/relax/frontend/nn/modules.py
@@ -18,13 +18,15 @@
"""Builtin Modules."""
from typing import List, Optional, Sequence, Union
+import numpy as np
+
from tvm import relax as rx
from tvm import tir
from tvm._ffi import register_func
from tvm.runtime import NDArray
from . import op
-from .core import Effect, Module, Parameter, Tensor, get_default_dtype,
ModuleList
+from .core import Effect, Module, ModuleList, Parameter, Tensor,
get_default_dtype
class IOEffect(Effect):
@@ -143,6 +145,56 @@ class Linear(Module):
return x
+class MultiLinear(Module):
+ """A layer that applies multiple linear transformations to the input."""
+
+ def __init__(
+ self,
+ in_features: int,
+ out_features: Sequence[int],
+ bias: bool = True,
+ dtype: Optional[str] = None,
+ out_dtype: Optional[str] = None,
+ ):
+ assert len(out_features) > 0
+ total_out_features = sum(out_features)
+
+ super().__init__()
+ self.in_features = in_features
+ self.out_features = out_features
+ self.out_dtype = out_dtype
+ self.weight = Parameter((total_out_features, in_features), dtype)
+ if bias:
+ self.bias = Parameter((total_out_features,), dtype)
+ else:
+ self.bias = None
+
+ def forward(self, x: Tensor) -> Tensor:
+ """
+ Forward method for linear layer.
+
+ Parameters
+ ----------
+ x : Tensor
+ The input tensor.
+
+ Returns
+ -------
+ ret : Tensor
+ The output tensor for the linear layer.
+ """
+ sections = list(np.cumsum(self.out_features)[:-1])
+ # x: [*B, in_features]
+ # w: [in_features, out_features]
+ w = op.permute_dims(self.weight)
+ # x: [*B, out_features]
+ x = op.matmul(x, w, out_dtype=self.out_dtype)
+ if self.bias is not None:
+ x = x + self.bias
+ results = op.split(x, sections, axis=-1)
+ return results
+
+
class Conv1D(Module):
"""
Module for conv1d layer.
diff --git a/python/tvm/relax/frontend/nn/op.py
b/python/tvm/relax/frontend/nn/op.py
index 66bf0e44b5..1f00eb058a 100644
--- a/python/tvm/relax/frontend/nn/op.py
+++ b/python/tvm/relax/frontend/nn/op.py
@@ -20,6 +20,7 @@ import math
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union
import numpy as np
+
from tvm import tir as _tir
from ... import expr as rx
@@ -32,7 +33,7 @@ from .spec import SpecBuilder
IntExpr = Union[int, _tir.PrimExpr]
-def _wrap_nested(expr: rx.Expr, name: str) -> Union[Tensor, Tuple[Tensor]]:
+def _wrap_nested(expr: rx.Expr, name: str) -> Union[Tensor, Tuple[Tensor,
...]]:
"""Wrap the given relax.Expr, emit it using the current BlockBuilder,
and automatically handle nested cases if the expr represents a Tuple.
@@ -1044,6 +1045,33 @@ def zeros(
return _wrap_nested(_op.zeros(shape, dtype), name)
+def split(
+ ary: Tensor,
+ indices_or_sections: Union[int, Sequence[int]],
+ axis: int = 0,
+ name: str = "split",
+) -> Tuple[Tensor, ...]:
+ """Split an array into multiple sub-arrays.
+
+ Parameters
+ ----------
+ ary : Tensor
+ Input tensor to be split.
+ indices_or_sections : Union[int, Sequence[int]]
+ Indices or sections to split into.
+ axis : int = 0
+ The axis along which to split, default is 0.
+ name : str
+ Name hint.
+
+ Returns
+ -------
+ result : Tuple[Tensor, ...]
+ A list of sub-arrays as the outcome of splitting.
+ """
+ return _wrap_nested(_op.split(ary._expr, indices_or_sections, axis), name)
+
+
def pad(
x: Tensor,
pad: List[int],
diff --git a/tests/python/relax/test_frontend_nn_modules.py
b/tests/python/relax/test_frontend_nn_modules.py
index dc69e2c51e..9d10a84f55 100644
--- a/tests/python/relax/test_frontend_nn_modules.py
+++ b/tests/python/relax/test_frontend_nn_modules.py
@@ -83,6 +83,56 @@ def test_linear():
assert_structural_equal(tvm_mod["forward"], forward, True)
+def test_multi_linear():
+ @R.function
+ def forward(
+ x: R.Tensor((3, 5, 4), dtype="float32"),
+ weight: R.Tensor((60, 4), dtype="float32"),
+ ) -> R.Tuple(
+ R.Tensor((3, 5, 4), dtype="float32"),
+ R.Tensor((3, 5, 8), dtype="float32"),
+ R.Tensor((3, 5, 16), dtype="float32"),
+ R.Tensor((3, 5, 32), dtype="float32"),
+ ):
+ R.func_attr({"num_input": 1})
+ with R.dataflow():
+ permute_dims: R.Tensor((4, 60), dtype="float32") =
R.permute_dims(weight, axes=None)
+ matmul: R.Tensor((3, 5, 60), dtype="float32") = R.matmul(
+ x, permute_dims, out_dtype="void"
+ )
+ split: R.Tuple(
+ R.Tensor((3, 5, 4), dtype="float32"),
+ R.Tensor((3, 5, 8), dtype="float32"),
+ R.Tensor((3, 5, 16), dtype="float32"),
+ R.Tensor((3, 5, 32), dtype="float32"),
+ ) = R.split(matmul, indices_or_sections=[4, 12, 28], axis=-1)
+ split_0: R.Tensor((3, 5, 4), dtype="float32") = split[0]
+ split_1: R.Tensor((3, 5, 8), dtype="float32") = split[1]
+ split_2: R.Tensor((3, 5, 16), dtype="float32") = split[2]
+ split_3: R.Tensor((3, 5, 32), dtype="float32") = split[3]
+ gv: R.Tuple(
+ R.Tensor((3, 5, 4), dtype="float32"),
+ R.Tensor((3, 5, 8), dtype="float32"),
+ R.Tensor((3, 5, 16), dtype="float32"),
+ R.Tensor((3, 5, 32), dtype="float32"),
+ ) = (split_0, split_1, split_2, split_3)
+ R.output(gv)
+ return gv
+
+ mod = modules.MultiLinear(
+ in_features=4,
+ out_features=[4, 8, 16, 32],
+ bias=False,
+ )
+ tvm_mod, _ = mod.export_tvm(
+ spec={
+ "forward": {"x": spec.Tensor((3, 5, 4), "float32")},
+ },
+ debug=False,
+ )
+ assert_structural_equal(tvm_mod["forward"], forward, True)
+
+
def test_conv1d():
@R.function
def forward(