masahi commented on a change in pull request #8447:
URL: https://github.com/apache/tvm/pull/8447#discussion_r671624142



##########
File path: tests/python/frontend/pytorch/test_lstms.py
##########
@@ -0,0 +1,378 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+import tvm
+import tvm.testing
+import numpy as np
+import torch
+import onnx
+import sys
+import shutil
+import pytest
+
+from tvm import relay
+from tvm.contrib import graph_executor
+
+from pathlib import Path
+from torch import nn
+
+## Model parameters
+model_feature_size = 5
+model_hidden_size = 10
+model_num_layers = 2
+seqs_length = 15
+projection_size = 7
+batch_size = 3
+
+
+def check_torch_version_for_proj_in_lstm():
+    """
+    proj_size parameter is supported in torch.nn.LSTM layer started from 1.8.0 
torch version
+    """
+    me = False
+
+    version = torch.__version__
+    major, minor, micro = version.split(".")
+
+    if int(major) > 1:
+        me = True
+    elif int(major) == 1:
+        if int(minor) >= 8:
+            me = True
+
+    return me
+
+
+class LSTM_Model(nn.Module):
+    def __init__(
+        self,
+        device,
+        batch_first=False,
+        layer_num=1,
+        bidirectional=False,
+        proj_size=0,
+        use_bias=True,
+        rnd_weights_init=False,
+    ):
+        super().__init__()
+
+        self.device = device
+        self.batch_first = batch_first
+        self.use_bias = use_bias
+
+        # Network defition
+        if check_torch_version_for_proj_in_lstm():
+            self.lstm = nn.LSTM(
+                input_size=model_feature_size,
+                hidden_size=model_hidden_size,
+                num_layers=layer_num,
+                bidirectional=bidirectional,
+                proj_size=proj_size,
+                batch_first=batch_first,
+                bias=use_bias,
+            ).to(device)
+        else:
+            if proj_size > 0:
+                print(
+                    "WARNING: projection is not supported for torch version 
less than 1.8.0! ",
+                    "LSTM was constructed without projection!",
+                )
+                # sys.exit()
+            self.lstm = nn.LSTM(
+                input_size=model_feature_size,
+                hidden_size=model_hidden_size,
+                num_layers=layer_num,
+                bidirectional=bidirectional,
+                batch_first=batch_first,
+                bias=use_bias,
+            ).to(device)
+
+        if rnd_weights_init:
+            self.gen_rnd_weights()
+
+    def forward(self, input, hidden_init=None):
+        """
+        Computes the output tensor after input inference along LSTM layer.
+
+        :param input: batch of data as a tensor of shape (seqs_length, 
batch_size, model_feature_size) or (batch_size, seqs_length, 
model_feature_size) if self.batch_first = True
+        :param hidden_init: initial hidden state of the LSTM as a tensor of 
shape (num_layers, batch_size, hidden_size). Will default to a tensor of zeros 
if None.
+        :return: the output tensor of shape (batch_size, model_hidden_size)
+        """
+        # Pass the input through the LSTM layers and retrieve all outputs, the 
final hidden state
+        # and the final cell state.
+        out, (hidden, cell) = self.lstm(input, hidden_init)
+
+        return out
+
+    def gen_rnd_weights(self):
+        """
+        Generate random weigths for the model with biases
+        Without projection:
+            For first weights group:
+                Wi (4*model_hidden_size, model_feature_size)
+                Wh (4*model_hidden_size, model_hidden_size)
+                Bi (4*model_hidden_size)
+                Bh (4*model_hidden_size)
+            For first bidirectional weights group:
+                Wi (4*model_hidden_size, model_feature_size)
+                Wh (4*model_hidden_size, model_hidden_size)
+                Bi (4*model_hidden_size)
+                Bh (4*model_hidden_size)
+            For other weights group:
+                Wi (4*model_hidden_size, model_hidden_size)
+                Wh (4*model_hidden_size, model_hidden_size)
+                Bi (4*model_hidden_size)
+                Bh (4*model_hidden_size)
+        With projection:
+            For first weights group:
+                Wi (4*model_hidden_size, model_feature_size)
+                Wh (4*model_hidden_size, proj_size)
+                Bi (4*model_hidden_size)
+                Bh (4*model_hidden_size)
+                P  (proj_size, model_hidden_size)
+            For first bidirectional weights group:
+                Wi (4*model_hidden_size, model_feature_size)
+                Wh (4*model_hidden_size, proj_size)
+                Bi (4*model_hidden_size)
+                Bh (4*model_hidden_size)
+                P  (proj_size, model_hidden_size)
+            For other weights group:
+                Wi (4*model_hidden_size, proj_size * num_directions)
+                Wh (4*model_hidden_size, proj_size)
+                Bi (4*model_hidden_size)
+                Bh (4*model_hidden_size)
+                P  (proj_size, model_hidden_size)
+        For generation of random weigths for the model without biases Bi and 
Bh are skipped
+        """
+        for weight_group in self.lstm.all_weights:
+            for weight in weight_group:
+                weight.data = torch.rand(weight.shape)
+
+    def get_dummy_input(self):
+        shape = [seqs_length, batch_size, model_feature_size]
+        if self.batch_first:
+            shape = [batch_size, seqs_length, model_feature_size]
+        res = torch.rand(shape)
+
+        return res, shape
+
+
+def compare(input, gold_data, rtol=1e-5, atol=1e-5):
+    tvm.testing.assert_allclose(input, gold_data, rtol=rtol, atol=atol)
+    # remain = np.abs(gold_data - input)
+    # err = np.max(remain)
+    # if err < 1e-6:
+    #     print("SUCCESS: RESULTS ARE THE SAME WITH MAX ERROR {} AND EPSILON 
{}".format(err, 1e-6))
+    # else:
+    #     print("WARNING: RESULTS ARE NOT THE SAME WITH ERROR {}".format(err))
+
+
+def check_lstm_with_type(lstm_type):
+    # Create outdir directory to keep temporal files
+    out_dir = Path.cwd().joinpath("output")
+    out_dir.mkdir(exist_ok=True, parents=True)
+    has_proj = "p" in lstm_type

Review comment:
       No need to create temp directory if you remove onnx test.




-- 
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: commits-unsubscr...@tvm.apache.org

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


Reply via email to