[Bug] Gradient rejects a function that returns a tuple bound to a Var, regardless of target_index
Expected behavior
relax.transform.Gradient("main", target_index=k) should accept a function whose return value is a Var of tuple type and differentiate with respect to the k-th field of that tuple.
This should behave the same way as when the function directly returns a tuple literal.
The following two forms describe the same return value:
return (lv1, lv2, lv3)and:
res = (lv1, lv2, lv3)
return resActual behavior
When the tuple is first bound to a Var, every target_index is rejected.
Two different internal checks are triggered.
For target_index=1:
InternalError: Check failed: target_index == 0 (1 vs. 0):
When the function has only one return value, target_index can only be 0.For target_index=2:
InternalError: Check failed: target_index == 0 (2 vs. 0):
When the function has only one return value, target_index can only be 0.For target_index=0:
InternalError: Check failed: (IsScalarTensor(target_ty) && IsFloatTensorType(target_ty)) is false:
The differentiation target must be a float scalar (0-dim Tensor), but the Type of
the given target res is T.Tuple(R.Tensor((3, 3), dtype="float32"),
R.Tensor((), dtype="float32"), R.Tensor((), dtype="float32"))The function returns three values, but the error messages for target_index=1 and target_index=2 state that it has only one return value.
Both checks come from:
src/relax/transform/gradient.cc:731
src/relax/transform/gradient.cc:753
GradientMutator::CheckAndSetTargetEnvironment
TVM version:
0.26.dev0Commit:
8312a17f8734ddfd56e5f3977cd5df25b83ec49fOS: Linux x86_64, Ubuntu
Kernel:
5.15Python:
3.11Device: CPU only
Reproduces with:
relax.transform.Gradientalone
Steps to reproduce
import tvm
from tvm import relax
from tvm.script import ir as I, relax as R
@I.ir_module
class Module:
@R.function
def main(
x: R.Tensor((3, 3), "float32"),
y: R.Tensor((3, 3), "float32"),
):
with R.dataflow():
lv1 = x
lv2 = R.sum(x)
lv3 = R.sum(y)
res: R.Tuple(
R.Tensor((3, 3), "float32"),
R.Tensor((), "float32"),
R.Tensor((), "float32"),
) = (lv1, lv2, lv3)
R.output(res)
return res
relax.transform.Gradient(
"main",
target_index=1,
)(Module)Difference from a passing case
If the last part of the function is changed from:
res = (lv1, lv2, lv3)
return resto a direct tuple return:
return (lv1, lv2, lv3)then target_index=1 and target_index=2 succeed.
Therefore, the behavior of Gradient depends on whether an equivalent tuple return value is represented directly as a tuple literal or indirectly through a Var.
Triage
needs-triagebug
Source: apache/tvm