Skip to content

Conversation

@tlopex
Copy link
Member

@tlopex tlopex commented Sep 26, 2025

This pr supports lstm.input for ExportedProgram importer.
This links to issue #18340

@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @tlopex, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request significantly enhances the PyTorch ExportedProgram importer by adding robust support for nn.LSTM operations, enabling more complex recurrent neural networks to be translated into TVM Relax. It also refines tensor indexing logic and expands matrix multiplication support, improving the overall compatibility and functionality of the importer.

Highlights

  • LSTM Operator Support: Introduced support for the lstm.input operator within the PyTorch ExportedProgram importer, allowing nn.LSTM models to be translated to Relax.
  • LSTM Implementation Details: The new _lstm method in exported_program_translator.py provides a Relax-based implementation of the LSTM forward pass, handling input, hidden/cell states, and parameters, including batch_first configuration. It currently supports single-layer, non-bidirectional LSTMs.
  • Tensor Indexing Improvement: Enhanced the _getitem method in base_fx_graph_translator.py to correctly process tensor indexing when the index is a simple integer or a list/tuple of indices.
  • Matrix Multiplication Support: Added a mapping for torch.mm to relax.op.linear_algebra.matmul for improved compatibility.
  • Comprehensive Testing: Included new test cases for both torch.mm and nn.LSTM (covering batch_first variations) to validate the newly added functionalities.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request adds support for the lstm.input operator from PyTorch's ExportedProgram format. The implementation includes a new _lstm method in the ExportedProgramImporter and corresponding tests. While the core LSTM logic is present, there are several areas for improvement regarding correctness, robustness, and code quality.

My review highlights a critical bug in the _getitem implementation, several high-severity issues in the _lstm implementation related to incomplete functionality and lack of robustness, and some medium-severity suggestions for code refactoring to improve maintainability and efficiency. Addressing these points will make the LSTM support more robust and reliable.

Comment on lines +2002 to +2005
if not isinstance(node.args[1], (list, tuple)):
indices = [node.args[1]]
else:
indices = node.args[1]
Copy link
Contributor

Choose a reason for hiding this comment

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

critical

The new logic for handling integer indexing on tensors is incorrect. It returns the tensor itself, which breaks the semantics of tensor indexing. For a tensor x, x[0] should return the first slice along axis 0, which has a reduced rank. The current implementation returns x unmodified. Since _getitem is a general-purpose function, this change can cause incorrect behavior for other operators that rely on it.

This seems to be a workaround for an incomplete _lstm implementation. The correct fix should be in the _lstm operator implementation to return a proper tuple output, and this logic should be removed from _getitem.

Comment on lines +274 to +276
else:
# Fallback to a default hidden size
hidden_size = 16
Copy link
Contributor

Choose a reason for hiding this comment

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

high

The fallback logic for when LSTM parameters are not provided is problematic. It defaults to hidden_size = 16. This can lead to silent correctness issues and hard-to-debug errors. It would be better to raise a ValueError if the parameters are not available to determine hidden_size, as a valid LSTM layer must have weights.

Suggested change
else:
# Fallback to a default hidden size
hidden_size = 16
else:
raise ValueError("Cannot determine hidden_size. LSTM params (weights) are required.")

Comment on lines +291 to +300
else:
# Fallback: create zero weights
weight_ih = self.block_builder.emit(
relax.op.zeros(relax.ShapeExpr((4 * hidden_size, input_size)), dtype)
)
weight_hh = self.block_builder.emit(
relax.op.zeros(relax.ShapeExpr((4 * hidden_size, hidden_size)), dtype)
)
bias_ih = None
bias_hh = None
Copy link
Contributor

Choose a reason for hiding this comment

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

high

Creating zero-tensors for weights as a fallback is problematic. This can lead to silent correctness issues where the model compiles but produces incorrect (zero) outputs. It's better to raise an error if weights are not provided, as they are essential for a functional LSTM layer.

Suggested change
else:
# Fallback: create zero weights
weight_ih = self.block_builder.emit(
relax.op.zeros(relax.ShapeExpr((4 * hidden_size, input_size)), dtype)
)
weight_hh = self.block_builder.emit(
relax.op.zeros(relax.ShapeExpr((4 * hidden_size, hidden_size)), dtype)
)
bias_ih = None
bias_hh = None
else:
raise ValueError("LSTM params (weights) are required.")

if batch_first:
# (seq_len, batch_size, hidden_size) -> (batch_size, seq_len, hidden_size)
output = self.block_builder.emit(relax.op.permute_dims(output, axes=[1, 0, 2]))
return output
Copy link
Contributor

Choose a reason for hiding this comment

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

high

The _lstm implementation is incomplete. It only returns the output sequence but not the final hidden and cell states, which are part of the standard torch.nn.LSTM output (output, (h_n, c_n)). This will lead to incorrect behavior for models that use these states. The function should be updated to return a tuple containing the output sequence and the final hidden/cell states to fully match the PyTorch operator's behavior.

Comment on lines +342 to +355
if bias_ih is not None and bias_hh is not None:
gates = self.block_builder.emit(
relax.op.add(relax.op.add(relax.op.add(ih_gates, bias_ih), hh_gates), bias_hh)
)
elif bias_ih is not None:
gates = self.block_builder.emit(
relax.op.add(relax.op.add(ih_gates, bias_ih), hh_gates)
)
elif bias_hh is not None:
gates = self.block_builder.emit(
relax.op.add(relax.op.add(ih_gates, hh_gates), bias_hh)
)
else:
gates = self.block_builder.emit(relax.op.add(ih_gates, hh_gates))
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

The logic for adding biases is quite verbose with multiple if/elif/else branches. This can be simplified for better readability and maintainability. You can calculate the total gates first, and then conditionally add the biases.

Suggested change
if bias_ih is not None and bias_hh is not None:
gates = self.block_builder.emit(
relax.op.add(relax.op.add(relax.op.add(ih_gates, bias_ih), hh_gates), bias_hh)
)
elif bias_ih is not None:
gates = self.block_builder.emit(
relax.op.add(relax.op.add(ih_gates, bias_ih), hh_gates)
)
elif bias_hh is not None:
gates = self.block_builder.emit(
relax.op.add(relax.op.add(ih_gates, hh_gates), bias_hh)
)
else:
gates = self.block_builder.emit(relax.op.add(ih_gates, hh_gates))
gates = self.block_builder.emit(relax.op.add(ih_gates, hh_gates))
if bias_ih is not None:
gates = self.block_builder.emit(relax.op.add(gates, bias_ih))
if bias_hh is not None:
gates = self.block_builder.emit(relax.op.add(gates, bias_hh))

Comment on lines +358 to +369
i_gate = self.block_builder.emit(
relax.op.strided_slice(gates, axes=[1], begin=[0], end=[gate_size])
)
f_gate = self.block_builder.emit(
relax.op.strided_slice(gates, axes=[1], begin=[gate_size], end=[2 * gate_size])
)
g_gate = self.block_builder.emit(
relax.op.strided_slice(gates, axes=[1], begin=[2 * gate_size], end=[3 * gate_size])
)
o_gate = self.block_builder.emit(
relax.op.strided_slice(gates, axes=[1], begin=[3 * gate_size], end=[4 * gate_size])
)
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

The four gates (input, forget, cell, output) are split from the concatenated gates tensor using four separate strided_slice operations. This can be done more efficiently and concisely using a single relax.op.split operation, which would also improve readability.

            gate_tuple = self.block_builder.emit(relax.op.split(gates, 4, axis=1))
            i_gate = self.block_builder.emit(relax.TupleGetItem(gate_tuple, 0))
            f_gate = self.block_builder.emit(relax.TupleGetItem(gate_tuple, 1))
            g_gate = self.block_builder.emit(relax.TupleGetItem(gate_tuple, 2))
            o_gate = self.block_builder.emit(relax.TupleGetItem(gate_tuple, 3))

Comment on lines +5944 to +6012
def test_lstm():
class BasicLSTM(nn.Module):
def __init__(self):
super().__init__()
self.lstm = nn.LSTM(
input_size=4,
hidden_size=8,
num_layers=1,
batch_first=True,
bidirectional=False,
)

def forward(self, x):
y, _ = self.lstm(x)
return y

torch.manual_seed(42)
x = torch.randn(2, 3, 4, dtype=torch.float32)
model = BasicLSTM()
with torch.no_grad():
pytorch_output = model(x)
exported_program = export(model, args=(x,))
mod = from_exported_program(exported_program)
target = tvm.target.Target("llvm")
ex = relax.build(mod, target)
vm = relax.VirtualMachine(ex, tvm.cpu())
x_tvm = tvm.runtime.tensor(x.numpy())
tvm_output = vm["main"](x_tvm)
if hasattr(tvm_output, "numpy"):
tvm_output_np = tvm_output.numpy()
else:
tvm_output_np = tvm_output[0].numpy()
assert (
pytorch_output.shape == tvm_output_np.shape
), f"Shape mismatch: PyTorch {pytorch_output.shape} vs TVM {tvm_output_np.shape}"
np.testing.assert_allclose(pytorch_output.numpy(), tvm_output_np, rtol=1e-4, atol=1e-5)

class SeqFirstLSTM(nn.Module):
def __init__(self):
super().__init__()
self.lstm = nn.LSTM(
input_size=3,
hidden_size=6,
num_layers=1,
batch_first=False,
bidirectional=False,
)

def forward(self, x):
y, _ = self.lstm(x)
return y

torch.manual_seed(43)
x2 = torch.randn(4, 2, 3, dtype=torch.float32)
model2 = SeqFirstLSTM()
with torch.no_grad():
pytorch_output2 = model2(x2)
exported_program2 = export(model2, args=(x2,))
mod2 = from_exported_program(exported_program2)
ex2 = relax.build(mod2, target)
vm2 = relax.VirtualMachine(ex2, tvm.cpu())
x2_tvm = tvm.runtime.tensor(x2.numpy())
tvm_output2 = vm2["main"](x2_tvm)
if hasattr(tvm_output2, "numpy"):
tvm_output2_np = tvm_output2.numpy()
else:
tvm_output2_np = tvm_output2[0].numpy()
assert pytorch_output2.shape == tvm_output2_np.shape
np.testing.assert_allclose(pytorch_output2.numpy(), tvm_output2_np, rtol=1e-4, atol=1e-5)
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

The test_lstm function contains a significant amount of duplicated code for testing the batch_first=True and batch_first=False cases. This can be refactored into a helper function to improve readability and maintainability. The helper function could take the model and input tensor as arguments and perform the verification logic.

tlopex and others added 3 commits September 26, 2025 00:52
@MasterJH5574 MasterJH5574 merged commit 6c37194 into apache:main Sep 29, 2025
14 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.

3 participants