-
-
Notifications
You must be signed in to change notification settings - Fork 71
/
decoder.go
259 lines (244 loc) · 6.01 KB
/
decoder.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
package onnx
import (
"reflect"
"github.com/gogo/protobuf/proto"
"github.com/owulveryck/onnx-go/internal/onnx/ir"
"github.com/pkg/errors"
"gonum.org/v1/gonum/graph"
"gorgonia.org/tensor"
)
// Model is a wrapper around a computation graph.
// Input and Output are containing the ID of the corresponding nodes.
type Model struct {
backend Backend
dbByName map[string]graph.Node
Input []int64
Output []int64
}
// NewModel with dst as backend.
// dst should be a non-nil pointer.
func NewModel(dst Backend) *Model {
return &Model{
dbByName: make(map[string]graph.Node, 0),
backend: dst,
}
}
// UnmarshalBinary decodes the binary data in onnx format into the model
func (m *Model) UnmarshalBinary(data []byte) error {
pbModel := &ir.ModelProto{}
err := proto.Unmarshal(data, pbModel)
if err != nil {
return err
}
return m.decodeProto(pbModel)
}
// GetNodeByName is a utility method that returns a node of the computation graph
func (m *Model) GetNodeByName(name string) (graph.Node, bool) {
n, ok := m.dbByName[name]
return n, ok
}
func (m *Model) processValue(io *ir.ValueInfoProto) (graph.Node, error) {
if io == nil {
return nil, errors.New("cannot process nil value")
}
var opts []tensor.ConsOpt
dst := m.backend
n := dst.NewNode()
if _, ok := n.(Namer); ok {
n.(Namer).SetName(io.Name)
}
dst.AddNode(n)
m.dbByName[io.Name] = n
if io.Type == nil {
return n, nil
}
if _, ok := n.(DataCarrier); !ok {
return n, nil
}
ttype := io.Type.GetTensorType()
if ttype.GetShape() != nil {
var shape []int
for i := range ttype.Shape.Dim {
_, ok := ttype.Shape.Dim[i].GetValue().(*ir.TensorShapeProto_Dimension_DimValue)
if ok {
shape = append(shape, int(ttype.Shape.Dim[i].GetDimValue()))
}
}
opts = append(opts, tensor.WithShape(shape...))
}
dtype, err := ir.TensorProto_DataType(ttype.GetElemType()).Dtype()
if err != nil {
return n, err
}
opts = append(opts, tensor.Of(dtype))
t := tensor.New(opts...)
err = n.(DataCarrier).SetTensor(t)
if err != nil {
return n, err
}
return n, nil
}
// decodeProto decode a protobuf definition inside the model
func (m *Model) decodeProto(model *ir.ModelProto) error {
rv := reflect.ValueOf(m.backend)
if rv.Kind() != reflect.Ptr || rv.IsNil() {
return &InvalidUnmarshalError{reflect.TypeOf(m.backend)}
}
if model == nil {
return errModelIsNil
}
if model.Graph == nil {
return errGraphIsNil
}
if len(model.Graph.Node) == 0 {
return errEmptyGraph
}
if len(model.Graph.Output) == 0 {
return errGraphNoIO
}
if len(model.Graph.Input)+len(model.Graph.Output) == 0 {
return errGraphNoIO
}
err := m.applyModelProtoGraph(model)
if err != nil {
return err
}
return nil
}
// applyModelProtoGraph apply model proto graph tensors to model
func (m *Model) applyModelProtoGraph(model *ir.ModelProto) error {
m.Input = make([]int64, len(model.Graph.Input))
m.Output = make([]int64, len(model.Graph.Output))
m.dbByName = make(map[string]graph.Node, len(model.Graph.Output)+len(model.Graph.Input))
// Well...
for i, io := range model.Graph.Input {
n, err := m.processValue(io)
if err != nil {
return err
}
m.Input[i] = n.ID()
}
for _, io := range model.Graph.ValueInfo {
_, err := m.processValue(io)
if err != nil {
return err
}
}
for i, io := range model.Graph.Output {
n, err := m.processValue(io)
if err != nil {
return err
}
m.Output[i] = n.ID()
}
err := m.applyModelProtoGraphTensors(model)
if err != nil {
return err
}
err = m.applyModelProtoGraphNodeOperations(model)
if err != nil {
return err
}
return nil
}
// applyModelProtoGraphTensors apply model proto graph tensors to model
func (m *Model) applyModelProtoGraphTensors(model *ir.ModelProto) error {
for _, tensorProto := range model.Graph.GetInitializer() {
name := tensorProto.GetName()
if name == "" {
return errors.New("initializer should have a name")
}
n, ok := m.dbByName[name]
if !ok {
n = insertNode(m, n, name)
}
// Remove it from the input
// find the ID
for i := 0; i < len(m.Input); i++ {
if m.Input[i] == n.ID() {
m.Input = append(m.Input[:i], m.Input[i+1:]...)
}
}
if _, ok := n.(DataCarrier); !ok {
continue
}
t, err := tensorProto.Tensor()
if err != nil {
return err
}
err = n.(DataCarrier).SetTensor(t)
if err != nil {
return err
}
}
return nil
}
// applyModelProtoGraphNodeOperations apply model proto graph node operations to model
func (m *Model) applyModelProtoGraphNodeOperations(model *ir.ModelProto) error {
dst := m.backend
for _, node := range model.Graph.Node {
outputNodes := make([]graph.Node, len(node.Output))
for i, output := range node.Output {
var ok bool
var no graph.Node
if no, ok = m.dbByName[output]; !ok {
no = dst.NewNode()
if _, ok := no.(Namer); ok {
no.(Namer).SetName(output)
}
dst.AddNode(no)
m.dbByName[output] = no
}
// If node is input-less, fake an input by creating an empty value
if len(node.Input) == 0 {
inputName := node.Name + "/input"
_, err := m.processValue(&ir.ValueInfoProto{
Name: inputName,
})
if err != nil {
return err
}
node.Input = append(node.Input, inputName)
}
// input should be ordered for non-commutatives operations
for i, input := range node.Input {
var ni graph.Node
var ok bool
if ni, ok = m.dbByName[input]; !ok {
ni = dst.NewNode()
if _, ok := ni.(Namer); ok {
ni.(Namer).SetName(input)
}
dst.AddNode(ni)
m.dbByName[input] = ni
}
e := dst.NewWeightedEdge(no, ni, float64(i))
dst.SetWeightedEdge(e)
}
outputNodes[i] = no
}
// The graph can apply operations
attrs, err := toOperationAttributes(node.GetAttribute())
if err != nil {
return err
}
err = dst.ApplyOperation(Operation{
node.OpType,
attrs,
}, outputNodes...)
if err != nil {
return err
}
}
return nil
}
func insertNode(m *Model, n graph.Node, name string) graph.Node {
dst := m.backend
n = dst.NewNode()
if n, ok := n.(Namer); ok {
n.SetName(name)
}
dst.AddNode(n)
m.dbByName[name] = n
return n
}