masahi commented on a change in pull request #6449:
URL: https://github.com/apache/incubator-tvm/pull/6449#discussion_r489103955



##########
File path: tests/python/frontend/pytorch/test_object_detection.py
##########
@@ -0,0 +1,136 @@
+# 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.
+# pylint: disable=import-self, invalid-name, unused-argument
+"""Test torch vision fasterrcnn and maskrcnn models"""
+import numpy as np
+import torch
+import torchvision
+import cv2
+
+import tvm
+
+from tvm import relay
+from tvm.runtime.vm import VirtualMachine
+from tvm.contrib.download import download
+
+
+in_size = 512
+
+
+def process_image(img):
+    img = cv2.imread(img).astype("float32")
+    img = cv2.resize(img, (in_size, in_size))
+    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
+    img = torch.from_numpy(img / 255.0).permute(2, 0, 1).float()
+    img = torch.unsqueeze(img, axis=0)
+
+    return img
+
+
+def do_trace(model, inp, in_size=in_size):
+    model_trace = torch.jit.trace(model, inp)
+    model_trace.eval()
+    return model_trace
+
+
+def dict_to_tuple(out_dict):
+    if "masks" in out_dict.keys():
+        return out_dict["boxes"], out_dict["scores"], out_dict["labels"], 
out_dict["masks"]
+    return out_dict["boxes"], out_dict["scores"], out_dict["labels"]
+
+
+class TraceWrapper(torch.nn.Module):
+    def __init__(self, model):
+        super().__init__()
+        self.model = model
+
+    def forward(self, inp):
+        out = self.model(inp)
+        return dict_to_tuple(out[0])
+
+
+def generate_jit_model(index):
+    model_funcs = [
+        torchvision.models.detection.fasterrcnn_resnet50_fpn,
+        torchvision.models.detection.maskrcnn_resnet50_fpn,
+    ]
+
+    model_func = model_funcs[index]
+    model = TraceWrapper(model_func(pretrained=True))
+
+    model.eval()
+    inp = torch.Tensor(np.random.uniform(0.0, 250.0, size=(1, 3, in_size, 
in_size)))
+
+    with torch.no_grad():
+        out = model(inp)
+
+        script_module = do_trace(model, inp)
+        script_out = script_module(inp)
+
+        assert len(out[0]) > 0 and len(script_out[0]) > 0
+        return script_module
+
+
+def test_detection_models(model_index, score_threshold=0.9):
+    img = "test_street_small.jpg"
+    img_url = (
+        "https://raw.githubusercontent.com/dmlc/web-data/";
+        "master/gluoncv/detection/street_small.jpg"
+    )
+    download(img_url, img)
+
+    input_shape = (1, 3, in_size, in_size)
+    target = "llvm"
+    input_name = "input0"
+    shape_list = [(input_name, input_shape)]
+
+    scripted_model = generate_jit_model(model_index)
+    mod, params = relay.frontend.from_pytorch(scripted_model, shape_list)
+
+    with tvm.transform.PassContext(opt_level=3, 
disabled_pass=["FoldScaleAxis"]):
+        vm_exec = relay.vm.compile(mod, target=target, params=params)
+
+    ctx = tvm.cpu()
+    vm = VirtualMachine(vm_exec, ctx)
+    data = process_image(img)
+    pt_res = scripted_model(data)
+    data = data.detach().numpy()
+    vm.set_input("main", **{input_name: data})
+    tvm_res = vm.run()
+
+    # Note: due to accumulated numerical error, we can't directly compare 
results
+    # with pytorch output. Some boxes might have a quite tiny difference in 
score
+    # and the order can become different. We just measure how many valid boxes
+    # there are for input image.
+    pt_scores = pt_res[1].detach().numpy().tolist()
+    tvm_scores = tvm_res[1].asnumpy().tolist()
+    num_pt_valid_scores = num_tvm_valid_scores = 0
+

Review comment:
       I'm comparing the two output (box coordinates etc) by eye balling the 
raw numerical values, and it looks good!
   
   I hope we can have a better way to test the outputs, for example extracting 
valid box indices based on score, sort indices by score, and sort boxes by 
sorted indices, like I did below. 
   
   ```
   In [59]: boxes_pt[ind_pt]                                                    
                                                                                
                                    
   Out[59]: 
   array([[2.04335907e+02, 1.14787331e+02, 2.59456146e+02, 2.23669510e+02],
          [1.44117985e+01, 1.24377182e+02, 6.13694534e+01, 2.14236847e+02],
          [1.74448120e+02, 1.58607117e+02, 2.78158417e+02, 2.36064560e+02],
          [1.17156494e+02, 1.18118942e+02, 1.53017059e+02, 1.92442230e+02],
          [1.00772736e+02, 1.22123978e+02, 1.23872040e+02, 1.93398422e+02],
          [1.49618347e+02, 1.32603149e+02, 2.18598679e+02, 1.74433960e+02],
          [2.13966250e-01, 1.39350525e+02, 1.12648888e+01, 1.53912018e+02],
          [1.33723541e+02, 1.24649574e+02, 1.64407623e+02, 1.61921951e+02],
          [8.67264709e+01, 1.28565033e+02, 9.51557159e+01, 1.56289093e+02]],
         dtype=float32)
   
   In [60]: boxes_tvm[ind_tvm]                                                  
                                                                                
                                 
   Out[60]: 
   array([[204.3359    , 114.78732   , 259.45615   , 223.66951   ],
          [ 14.411795  , 124.37717   ,  61.369446  , 214.23685   ],
          [174.44815   , 158.60712   , 278.1584    , 236.06454   ],
          [117.156494  , 118.118935  , 153.01706   , 192.44223   ],
          [100.772736  , 122.12396   , 123.87204   , 193.39842   ],
          [149.61836   , 132.60315   , 218.5987    , 174.43396   ],
          [  0.39432764, 139.76776   ,  11.332638  , 153.84328   ],
          [133.72354   , 124.64958   , 164.40762   , 161.92194   ],
          [ 86.72647   , 128.56502   ,  95.155716  , 156.28911   ]],
         dtype=float32)
   ```




----------------------------------------------------------------
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.

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


Reply via email to