-
Notifications
You must be signed in to change notification settings - Fork 5
/
model.go
280 lines (224 loc) · 6.67 KB
/
model.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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
package gonnx
import (
"archive/zip"
"io"
"os"
"github.com/advancedclimatesystems/gonnx/onnx"
"github.com/advancedclimatesystems/gonnx/ops"
"google.golang.org/protobuf/proto"
"gorgonia.org/tensor"
)
// Tensors is a map with tensors.
type Tensors map[string]tensor.Tensor
// Model defines a model that can be used for inference.
type Model struct {
mp *onnx.ModelProto
parameters Tensors
Opset Opset
}
// NewModelFromFile creates a new model from a path to a file.
func NewModelFromFile(path string) (*Model, error) {
bytesModel, err := os.ReadFile(path)
if err != nil {
return nil, err
}
return NewModelFromBytes(bytesModel)
}
// NewModelFromZipFile creates a new model from a file in a zip archive.
func NewModelFromZipFile(file *zip.File) (*Model, error) {
fc, err := file.Open()
if err != nil {
return nil, err
}
bytesModel, err := io.ReadAll(fc)
if err != nil {
return nil, err
}
return NewModelFromBytes(bytesModel)
}
// NewModelFromBytes creates a new model from a list of bytes.
func NewModelFromBytes(bytesModel []byte) (*Model, error) {
mp, err := ModelProtoFromBytes(bytesModel)
if err != nil {
return nil, err
}
return NewModel(mp)
}
// NewModel creates a new model ready for inference given a path to an onnx file.
func NewModel(mp *onnx.ModelProto) (*Model, error) {
params, err := mp.Graph.Params()
if err != nil {
return nil, err
}
opsetImports := mp.GetOpsetImport()
var opsetID int64
for i := 0; i < len(opsetImports); i++ {
version := opsetImports[i].GetVersion()
if version > opsetID {
opsetID = version
}
}
opset, err := ResolveOpset(opsetID)
if err != nil {
return nil, err
}
return &Model{
mp: mp,
parameters: params,
Opset: opset,
}, nil
}
// ModelProtoFromBytes creates an onnx.ModelProto based on a list of bytes.
func ModelProtoFromBytes(bytesModel []byte) (*onnx.ModelProto, error) {
mp := &onnx.ModelProto{}
if err := proto.Unmarshal(bytesModel, mp); err != nil {
return nil, err
}
return mp, nil
}
// InputNames returns this models input names as defined by the model proto.
func (m *Model) InputNames() []string {
return m.mp.Graph.InputNames()
}
// InputShapes returns the shapes for all input tensors.
func (m *Model) InputShapes() onnx.Shapes {
return m.mp.Graph.InputShapes()
}
// InputDimSize returns the size of the input dimension given an input tensor.
func (m *Model) InputDimSize(input string, i int) (int, error) {
if !m.hasInput(input) {
return 0, ErrModel("input %v does not exist", input)
}
inputShape := m.mp.Graph.InputShapes()[input]
if i >= len(inputShape) {
return 0, ErrModel("input %v only has %d dimensions, but index %d was required", input, len(inputShape), i)
}
return int(inputShape[i].Size), nil
}
// OutputNames returns this models output names as defined by the model proto.
func (m *Model) OutputNames() []string {
return m.mp.Graph.OutputNames()
}
// OutputShapes returns the shapes for all output tensors.
func (m *Model) OutputShapes() onnx.Shapes {
return m.mp.Graph.OutputShapes()
}
// OutputShape returns the shape of a specific output tensors.
func (m *Model) OutputShape(output string) onnx.Shape {
return m.mp.Graph.OutputShapes()[output]
}
// ParamNames returns this models parameter names as defined by the model proto.
func (m *Model) ParamNames() []string {
return m.mp.Graph.ParamNames()
}
func (m *Model) hasInput(input string) bool {
for _, inputName := range m.InputNames() {
if inputName == input {
return true
}
}
return false
}
// Run builds and executes the computional graph of the network given the inputs.
func (m *Model) Run(inputs Tensors) (Tensors, error) {
if err := m.validateShapes(inputs); err != nil {
return nil, err
}
tensors := make(Tensors)
for inputName, inputTensor := range inputs {
tensors[inputName] = inputTensor
}
for parameterName, parameterTensor := range m.parameters {
tensors[parameterName] = parameterTensor
}
for _, n := range m.mp.Graph.GetNode() {
op, ok := m.Opset[n.GetOpType()]
if !ok {
return nil, ops.ErrUnknownOperatorType(n.GetOpType())
}
if err := m.applyOp(op(), n, tensors); err != nil {
return nil, err
}
}
outputTensors := make(Tensors)
for _, outputName := range m.OutputNames() {
outputTensors[outputName] = tensors[outputName]
}
return outputTensors, nil
}
// applyOp applies the operation to the graph.
func (m *Model) applyOp(op ops.Operator, n *onnx.NodeProto, tensors Tensors) error {
if err := op.Init(n); err != nil {
return err
}
inputTensors, err := getInputTensorsForNode(n.GetInput(), tensors)
if err != nil {
return err
}
inputTensors, err = op.ValidateInputs(inputTensors)
if err != nil {
return err
}
outputTensors, err := op.Apply(inputTensors)
if err != nil {
return err
}
return setOutputTensorsOfNode(n.GetOutput(), outputTensors, tensors)
}
// validateShapes validates if the tensors passed in have the same shape as the shapes defined
// by the onnx.Shapes.
func (m *Model) validateShapes(inputTensors Tensors) error {
for name, shapeExpected := range m.InputShapes() {
// If the input is a parameter, the user does not have to provide a tensor for it.
if _, ok := m.parameters[name]; ok {
continue
}
tensor, ok := inputTensors[name]
if !ok {
return ErrModel("tensor: %v not found", name)
}
shapeReceived := tensor.Shape()
if len(shapeReceived) != len(shapeExpected) {
return ErrInvalidShape(shapeExpected, shapeReceived)
}
for i, dim := range shapeExpected {
// because the dimension is dynamic, it can have any size
// and we do not have to check for it
if dim.IsDynamic {
continue
}
if dim.Size != int64(shapeReceived[i]) {
return ErrInvalidShape(shapeExpected, shapeReceived)
}
}
}
return nil
}
func getInputTensorsForNode(names []string, tensors Tensors) ([]tensor.Tensor, error) {
var inputTensors []tensor.Tensor
for _, tensorName := range names {
// An empty name can happen in between optional inputs, like:
// [<required_input>, <optional_input>, nil, <optional_input>]
// In such a case, ONNX includes the name of the input in the node, and we need
// to set a value (nil) for it, although it will not be used.
if tensorName == "" {
inputTensors = append(inputTensors, nil)
} else if tensor, ok := tensors[tensorName]; ok {
inputTensors = append(inputTensors, tensor)
} else {
return nil, ErrModel("no tensor yet for name %v", tensorName)
}
}
return inputTensors, nil
}
func setOutputTensorsOfNode(
names []string, outputTensors []tensor.Tensor, tensors Tensors,
) error {
if len(names) != len(outputTensors) {
return ErrModel("could not set output tensor")
}
for i, tensor := range outputTensors {
tensors[names[i]] = tensor
}
return nil
}