[Bug][Relax] RemoveUnusedOutputs drops impure calls when tuple outputs are unused
Description
RemoveUnusedOutputs removes a call to an impure private function when none of its tuple fields are read. The returned values are unused, but evaluating the call is observable and must be preserved.
Environment
- TVM
0.26.dev0, executed ate269315c90e3a061c9e1c77b370ce883b1b223f4 - Ubuntu 24.04 x86-64, LLVM 18.1.3 CPU target
- Current upstream
mainchecked atd55759ec1ebed554d9782a52e43e5730b8a96656 src/relax/transform/remove_unused_outputs.ccis byte-identical at both revisions (SHA-2565b07b27de645d2e398cc7ccc5fe7d0308dc6a238542e47b516f4aa89e559b47c)- I did not have a binary built from current
main, so the runtime reproduction below is from the executed revision
Minimal reproduction
from tvm import relax
from tvm.script import ir as I
from tvm.script import relax as R
@I.ir_module
class Module:
@R.function(pure=False)
def main(x: R.Tensor((2,), "float32")):
ignored = Module.effect(x)
return x
@R.function(private=True, pure=False)
def effect(x: R.Tensor((2,), "float32")) -> R.Tuple(
R.Tensor((2,), "float32"), R.Tensor((2,), "float32")
):
R.print(format="observable effect")
return (x, R.add(x, x))
assert relax.analysis.check_well_formed(Module, check_ty=True)
after = relax.transform.RemoveUnusedOutputs()(Module)
assert relax.analysis.check_well_formed(after, check_ty=True)
print(after.script())
Expected behavior
The pass may remove unused tuple values, but it must retain evaluation of the impure call.
Actual behavior
The transformed main contains only return x; both the call and R.print disappear. Running the source prints once per invocation, while the target prints nothing. Both modules otherwise return the same tensor.
A control that observes outputs[0] preserves the call and matches the source across six deterministic input regimes.
Likely cause
When the output-usage mask is entirely false, the callsite updater creates a new call but does not place it in any returned field. Later canonicalization removes it without accounting for the callee's purity.
Duplicate check
I searched open and closed TVM issues and PRs for RemoveUnusedOutputs deleting an impure call when all tuple fields are unused. I did not find the same cause. #17247/#17253 concern an observed tuple value and a different analysis path.
I can send a fix PR and help with follow-up testing if this diagnosis looks right.
Triage
- needs-triage
- type: bug
I'd like to work on this issue. I have reproduced the lost side effect on current main: an unused impure tuple-returning call prints once before RemoveUnusedOutputs and zero times afterwards, while the observed-output control preserves the effect. I plan a scoped fix that retains evaluation when all tuple outputs are unused, with regression coverage for purity, partially used outputs and repeated calls. Please let me know if an implementation is already in progress.