singa-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From GitBox <...@apache.org>
Subject [GitHub] [incubator-singa] nudles commented on a change in pull request #416: singa-onnx
Date Thu, 07 Mar 2019 15:14:12 GMT
nudles commented on a change in pull request #416: singa-onnx
URL: https://github.com/apache/incubator-singa/pull/416#discussion_r263426576
 
 

 ##########
 File path: python/singa/sonnx.py
 ##########
 @@ -0,0 +1,289 @@
+#
+# 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.
+#
+
+
+
+from __future__ import division
+from singa import tensor
+from singa import autograd
+from onnx import helper,checker
+from onnx import AttributeProto, TensorProto, GraphProto
+from onnx import numpy_helper
+from  onnx.backend.base import BackendRep as backendRep
+from  onnx.backend.base import Backend as backend
+from collections import Counter, deque
+
+from . import singa_wrap as singa
+from autograd import *
+from autograd import _Conv2d,_Pooling2d,_BatchNorm2d
+#if not import, there will be an error
+from singa.tensor import to_numpy
+
+
+class BackendRep(backendRep):
+    def __init__(self,model,device):
+        self.model, self.modeldic = Backend.onnx_model_init(model,device)
+        self.handledic={}
+    def run(self,inputs):
+        self.y,self.modeldic=Backend.run(self.model, self.modeldic,inputs,self.handledic)
+        return self.y
+
+
+
+class Backend(backend):
+
+    @staticmethod
+    def convhandle(name,handledic,x,model):
+        if(name in handledic):return handledic
+        i = Backend.find_name(model,name)
+
+        shape = Backend.find_shape(model,i.input[1])
+        cin,cout,k=shape[1], shape[0], (shape[2],shape[2])
+        padding=(int(i.attribute[1].ints[0]),int(i.attribute[1].ints[0]))
+        stride=(int(i.attribute[2].ints[0]),int(i.attribute[2].ints[0]))
+
+        handledic[name] = singa.CudnnConvHandle(x.data, k, stride,padding, cin, cout, True)
+        handledic[name].device_id = x.device.id()
+        return handledic
+
+
+    @staticmethod
+    def MaxPool2dhandle(name,handledic,x,model):
+        if(name in handledic):return handledic
+        i = Backend.find_name(model,name)
+        k = (int(i.attribute[0].ints[0]),int(i.attribute[0].ints[0]))
+        padding=(int(i.attribute[1].ints[0]),int(i.attribute[1].ints[0]))
+        stride=(int(i.attribute[2].ints[0]),int(i.attribute[2].ints[0]))
+
+        handledic[name] = singa.CudnnPoolingHandle(x.data, k, stride, padding, True)
+        handledic[name].device_id = x.device.id()
+        return handledic
+
+    @staticmethod
+    def AveragePoolhandle(name,handledic,x,model):
+        if(name in handledic):return handledic
+        i = Backend.find_name(model,name)
+        k = (int(i.attribute[0].ints[0]),int(i.attribute[0].ints[0]))
+        padding=(int(i.attribute[1].ints[0]),int(i.attribute[1].ints[0]))
+        stride=(int(i.attribute[2].ints[0]),int(i.attribute[2].ints[0]))
+
+        handledic[name] = singa.CudnnPoolingHandle(x.data, k, stride, padding, False)
+        handledic[name].device_id = x.device.id()
+        return handledic
+
+    @staticmethod
+    def BatchNormalizationhandle(name,handledic,x,model):
+        if(name in handledic):return handledic
+        handledic[name] = singa.CudnnBatchNormHandle(0.9, x.data)
+        handledic[name].device_id = x.device.id()
+        return handledic
+
+
+
+
+
+
+    @staticmethod
+    def onnx_model_init(model,device):
+        '''
+        input model
+
+        return: model and model dictionary
+        '''
+
+        modeldic = {}
+        for i in model.graph.node:
+            if (i.op_type == 'Constant'):
+                modeldic[str(i.output[0])] = tensor.Tensor(device=device,data=numpy_helper.to_array(i.attribute[0].t),requires_grad=True,
stores_grad=True)
+
+        return model,modeldic
+
+
+    @staticmethod
+    def find_name(model,name):
+        for i in model.graph.node:
+            if (i.name == name):
+                return i
+
+
+    @staticmethod
+    def find_shape(model,input):
+        '''
+        # find weight shape for layers
+        '''
+        for i in model.graph.node:
+            if (i.op_type == 'Constant' and i.output[0] == input):
+                return numpy_helper.to_array(i.attribute[0].t).shape
+
+
+    @staticmethod
+    def run_model(model,inputs,device):
+        model, modeldic  = Backend.onnx_model_init(model,device)
+        return Backend.run(model, modeldic,inputs)[0]
+
+    @staticmethod
+    def run(model, modeldic,inputs,handledic={}):
+        '''
+            input: input for singa model
+            load other nodes of onnx
+            '''
+        supportLayer = ['Conv','MaxPool','AveragePool','BatchNormalization']
+        oper=modeldic
+        autograd.training = True
+        for counter,i in enumerate(model.graph.input):
+            oper[i.name] = inputs[counter]
+        for i in model.graph.node:
+            if (i.op_type == 'Relu'):
+                oper[str(i.output[0])] = autograd.relu(oper[str(i.input[0])])
+            elif (i.op_type == 'Softmax'):
+                oper[str(i.output[0])] = autograd.softmax(oper[str(i.input[0])])
+            elif (i.op_type == 'Add'):
+                oper[str(i.output[0])] = autograd.add(oper[str(i.input[0])], oper[str(i.input[1])])
+            elif (i.op_type == 'MatMul'):
+                oper[str(i.output[0])] = autograd.matmul(oper[str(i.input[0])], oper[str(i.input[1])])
+            elif (i.op_type == 'Flatten'):
+                oper[str(i.output[0])] = autograd.flatten(oper[str(i.input[0])])
+            elif(i.op_type == 'Concat'):
+                oper[str(i.output[0])] = autograd.cat((oper[str(i.input[0])], oper[str(i.input[1])]),int(i.attribute[0].i))
+            elif(i.op_type == 'Tanh'):
+                oper[str(i.output[0])] = autograd.tanh(oper[str(i.input[0])])
+            elif (i.op_type == 'Sigmoid'):
+                oper[str(i.output[0])] = autograd.sigmoid(oper[str(i.input[0])])
+            elif (i.op_type == 'Mul'):
+                oper[str(i.output[0])] = autograd.mul(oper[str(i.input[0])],oper[str(i.input[1])])
+            elif (i.op_type == 'Conv'):
+                handledic = Backend.convhandle(i.name,handledic,oper[str(i.input[0])],model)
 
 Review comment:
   if the handle is used immediately, do you need to put it into a dict?
   creating the handle in every iteration is expensive!

----------------------------------------------------------------
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:
users@infra.apache.org


With regards,
Apache Git Services

Mime
View raw message