gemini-code-assist[bot] commented on code in PR #18492:
URL: https://github.com/apache/tvm/pull/18492#discussion_r2553994590
##########
python/tvm/relax/frontend/torch/exported_program_translator.py:
##########
@@ -34,6 +34,40 @@ class ExportedProgramImporter(BaseFXGraphImporter):
from torch import fx
+ @staticmethod
+ def _convert_pytorch_tensor_to_tvm(tensor_value: torch.Tensor) ->
tvm.runtime.Tensor:
+ """Convert a PyTorch tensor to TVM tensor, handling sparse tensors.
+
+ Parameters
+ ----------
+ tensor_value : torch.Tensor
+ The PyTorch tensor to convert.
+
+ Returns
+ -------
+ tvm.runtime.Tensor
+ The converted TVM tensor.
+ """
+ # Check if tensor is sparse (non-strided layout)
+ # PyTorch sparse tensors have layout != torch.strided
+ is_sparse = tensor_value.layout != torch.strided
+
+ # Detach the tensor first
+ tensor_detached = tensor_value.detach()
+
+ # If sparse, convert to dense first
+ if is_sparse:
+ tensor_detached = tensor_detached.to_dense()
Review Comment:

The logic for handling sparse tensors is correct. However, it can be
refactored for better clarity and conciseness. The current implementation uses
a boolean flag and reassigns the `tensor_detached` variable, which can be
slightly harder to follow. A more direct approach would be to use a new
variable for the tensor to be converted, which avoids reassignment and makes
the code easier to read. This also makes some of the comments redundant.
```suggestion
# PyTorch sparse tensors (layout != torch.strided) must be converted
to dense.
if tensor_value.layout != torch.strided:
tensor_to_convert = tensor_value.to_dense()
else:
tensor_to_convert = tensor_value
tensor_detached = tensor_to_convert.detach()
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]