Source file reader.ml
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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
open Base
module Format = Stdlib.Format
module Fun = Stdlib.Fun
module Oproto = Onnx_protoc
module Oprotom = Oproto.Onnx.ModelProto
exception ParseError of string
type t = {
n_inputs : int;
n_outputs : int;
nir : (Nir.Ngraph.t, string) Result.t;
}
module Convert : sig
val nir_of_onnx_protoc : Oproto.Onnx.ModelProto.t -> Nir.Ngraph.t
val get_input_output_dim : Oproto.Onnx.ModelProto.t -> int * int
end = struct
let get_shape_of_dims (s : Oproto.Onnx.TensorShapeProto.t) =
Nir.Shape.of_list
@@ List.map s ~f:(function
| { value = `Dim_value v; _ } -> Int64.to_int_exn v
| { value = `Dim_param s; _ } ->
failwith (Fmt.str "Parameteric shape %s" s)
| { value = `not_set; _ } -> failwith "Part of a shape not set")
let get_shape_of_value (s : Oproto.Onnx.ValueInfoProto.t) =
match s with
| { type' = Some { value = `Tensor_type { shape = Some v; _ }; _ }; _ } ->
get_shape_of_dims v
| _ -> failwith "Value as not shape"
let get_nested_dims (s : Oproto.Onnx.ValueInfoProto.t list) =
match List.nth s 0 with
| Some { type' = Some { value = `Tensor_type { shape = Some v; _ }; _ }; _ }
->
v
| _ -> []
let flattened_dim (s : Oproto.Onnx.TensorShapeProto.Dimension.t list) =
Nir.Shape.size (get_shape_of_dims s)
let get_input_output_dim (model : Oprotom.t) =
let input_shape, output_shape =
match model.graph with
| Some g -> (get_nested_dims g.input, get_nested_dims g.output)
| _ -> ([], [])
in
let input_flat_dim = flattened_dim input_shape in
let output_flat_dim = flattened_dim output_shape in
(input_flat_dim, output_flat_dim)
let convert_tensor (ts : Oproto.Onnx.TensorProto.t) : Nir.Gentensor.t =
let dims = Nir.Shape.of_list @@ List.map ~f:Int64.to_int_exn ts.dims in
let size = Nir.Shape.size dims in
let read_raw ~get kind =
match ts.raw_data with
| None ->
failwith "TensorProto have no data field for the given data type"
| Some data ->
let t = Bigarray.(Array1.create kind c_layout size) in
for i = 0 to size - 1 do
let v = get data i in
Bigarray.Array1.set t i v
done;
Nir.Tensor.of_array1 dims t
in
let read_gen ~get ~conv elt_size kind custom_data =
match custom_data with
| [] ->
read_raw kind ~get:(fun raw coord_in_data ->
let offset = elt_size * coord_in_data in
get raw offset)
| l when List.length l <> size ->
failwith "not enough data according to dimension"
| l ->
let t = Bigarray.(Array1.create kind c_layout size) in
List.iteri l ~f:(fun i f -> Bigarray.Array1.set t i (conv f));
Nir.Tensor.of_array1 dims t
in
match ts.data_type with
| None -> failwith "TensorProto should have a type"
| Some ty -> (
match ty with
| UNDEFINED -> failwith "Invalid UNDEFINED data type"
| FLOAT ->
Float
(read_gen 4 Float64 ts.float_data
~get:EndianBytes.LittleEndian.get_float ~conv:Fun.id)
| UINT8 ->
UInt8
(read_gen 1 Int8_unsigned ts.int32_data
~get:EndianBytes.LittleEndian.get_uint8 ~conv:Int32.to_int_exn)
| INT8 ->
Int8
(read_gen 1 Int8_signed ts.int32_data
~get:EndianBytes.LittleEndian.get_int8 ~conv:Int32.to_int_exn)
| INT32 ->
Int32
(read_gen 4 Int32 ts.int32_data
~get:EndianBytes.LittleEndian.get_int32 ~conv:Fun.id)
| INT64 ->
Int64
(read_gen 8 Int64 ts.int64_data
~get:EndianBytes.LittleEndian.get_int64 ~conv:Fun.id)
| DOUBLE ->
Float
(read_gen 4 Float64 ts.float_data
~get:EndianBytes.LittleEndian.get_float ~conv:Fun.id)
| UINT16 | INT16 | STRING | BOOL | FLOAT16 | UINT32 | UINT64 | COMPLEX64
| COMPLEX128 | BFLOAT16 ->
failwith "Unsupported data type")
type value =
| Node of Oproto.Onnx.NodeProto.t
| Tensor of Oproto.Onnx.TensorProto.t
let produce_cfg (g : Oproto.Onnx.GraphProto.t) =
let open Oproto.Onnx in
let converted = Hashtbl.create (module String) in
let of_output_value = Hashtbl.create (module String) in
List.iter g.node ~f:(fun n ->
match n.output with
| [] -> failwith "Node without output"
| [ o ] ->
Hashtbl.add_exn of_output_value ~key:o ~data:(Node n)
| _ -> failwith "Node with multiple outputs are not handled");
List.iter g.initializer' ~f:(fun t ->
match t.name with
| None -> failwith "Initializer must have a name"
| Some o ->
Hashtbl.add_exn of_output_value ~key:o ~data:(Tensor t));
assert (List.is_empty g.sparse_initializer);
let output, output_shape =
match g.output with
| [] -> failwith "graph without output"
| [ output ] -> (Option.value_exn output.name, get_shape_of_value output)
| _ -> failwith "graph with more than one output"
in
let input_name, input_shape =
let input =
List.filter_map g.input ~f:(fun i ->
let name = Option.value_exn i.name in
if Hashtbl.mem of_output_value name
then None
else Some (name, get_shape_of_value i))
in
match input with
| [] -> failwith "graph without input, can be accepted"
| [ input ] -> input
| _ -> failwith "graph with more than one input node (unsupported)"
in
Hashtbl.add_exn converted ~key:input_name
~data:(Nir.Node.create (Input { shape = input_shape }));
let rec convert output =
Hashtbl.findi_or_add ~default:convert_aux converted output
and convert_aux output =
let value = Hashtbl.find_exn of_output_value output in
match value with
| Node n ->
let one_arg = function
| [ input ] -> input
| _ -> failwith "should have one argument"
in
let two_arg = function
| [ input1; input2 ] -> (input1, input2)
| _ -> failwith "should have two arguments"
in
let attrs =
Hashtbl.of_alist_exn
(module String)
(List.map ~f:(fun a -> (Option.value_exn a.name, a)) n.attribute)
in
let get_attr ?default name m =
match Hashtbl.find attrs name with
| Some v -> m v
| None -> (
match default with
| Some v -> v
| None -> Fmt.failwith "Required attribute %s missing" name)
in
let get_float ?default name : float =
get_attr ?default name (function
| { type' = Some AttributeProto.AttributeType.FLOAT; f = Some f; _ }
->
f
| _ -> failwith "Attribute wrongly typed")
in
let get_int ?default name : int =
get_attr ?default name (function
| { type' = Some AttributeProto.AttributeType.INT; i = Some i; _ }
->
Int64.to_int_exn i
| _ -> failwith "Attribute wrongly typed")
in
let get_ints ?default name : int list =
get_attr ?default name (function
| { type' = Some AttributeProto.AttributeType.INTS; ints = l; _ } ->
List.map ~f:Int64.to_int_exn l
| _ -> failwith "Attribute wrongly typed")
in
let get_tensor ?default name : Nir.Gentensor.t =
get_attr ?default name (function
| {
type' = Some AttributeProto.AttributeType.TENSOR;
t = Some t;
_;
} ->
convert_tensor t
| _ -> failwith "Attribute wrongly typed")
in
let get_bool ?default name = get_int ?default name = 1 in
let n' =
match n.op_type with
| None -> failwith "Node without op_type (No-op?)"
| Some s -> (
match s with
| "Add" ->
let input1, input2 = two_arg n.input in
Nir.Node.Add { input1 = convert input1; input2 = convert input2 }
| "Sub" ->
let input1, input2 = two_arg n.input in
Nir.Node.Sub { input1 = convert input1; input2 = convert input2 }
| "Mul" ->
let input1, input2 = two_arg n.input in
Nir.Node.Mul { input1 = convert input1; input2 = convert input2 }
| "Div" ->
let input1, input2 = two_arg n.input in
Nir.Node.Div { input1 = convert input1; input2 = convert input2 }
| "Pow" ->
let input1, input2 = two_arg n.input in
Nir.Node.Pow { input1 = convert input1; input2 = convert input2 }
| "Relu" ->
let input1 = one_arg n.input in
Nir.Node.ReLu { input = convert input1 }
| "MatMul" ->
let input1, input2 = two_arg n.input in
Nir.Node.Matmul
{ input1 = convert input1; input2 = convert input2 }
| "QLinearMatMul" ->
let ( inputA,
inputA_scale,
inputA_zero_point,
inputB,
inputB_scale,
inputB_zero_point,
y_scale,
y_zero_point ) =
match n.input with
| [
inputA;
inputA_scale;
inputA_zero_point;
inputB;
inputB_scale;
inputB_zero_point;
y_scale;
y_zero_point;
] ->
( inputA,
inputA_scale,
inputA_zero_point,
inputB,
inputB_scale,
inputB_zero_point,
y_scale,
y_zero_point )
| _ -> failwith "QLinearMatMul must have 8 inputs"
in
Nir.Node.QLinearMatMul
{
inputA = convert inputA;
inputA_scale = convert inputA_scale;
inputA_zero_point = convert inputA_zero_point;
inputB = convert inputB;
inputB_scale = convert inputB_scale;
inputB_zero_point = convert inputB_zero_point;
y_scale = convert y_scale;
y_zero_point = convert y_zero_point;
}
| "Gemm" ->
let inputA, inputB, inputC =
match n.input with
| [ inputA; inputB ] -> (inputA, inputB, None)
| [ inputA; inputB; inputC ] -> (inputA, inputB, Some inputC)
| _ -> failwith "Gemm must have 2 or 3 inputs"
in
Nir.Node.Gemm
{
inputA = convert inputA;
inputB = convert inputB;
inputC = Option.map ~f:convert inputC;
alpha = get_float ~default:1.0 "alpha";
beta = get_float ~default:1.0 "beta";
transA = get_int ~default:0 "transA";
transB = get_int ~default:0 "transB";
}
| "QGemm" ->
let ( inputA,
inputA_scale,
inputA_zero_point,
inputB,
inputB_scale,
inputB_zero_point,
inputC,
y_scale,
y_zero_point ) =
match n.input with
| [
inputA;
inputA_scale;
inputA_zero_point;
inputB;
inputB_scale;
inputB_zero_point;
] ->
( inputA,
inputA_scale,
inputA_zero_point,
inputB,
inputB_scale,
inputB_zero_point,
None,
None,
None )
| [
inputA;
inputA_scale;
inputA_zero_point;
inputB;
inputB_scale;
inputB_zero_point;
inputC;
] ->
( inputA,
inputA_scale,
inputA_zero_point,
inputB,
inputB_scale,
inputB_zero_point,
Some inputC,
None,
None )
| [
inputA;
inputA_scale;
inputA_zero_point;
inputB;
inputB_scale;
inputB_zero_point;
inputC;
y_scale;
] ->
( inputA,
inputA_scale,
inputA_zero_point,
inputB,
inputB_scale,
inputB_zero_point,
Some inputC,
Some y_scale,
None )
| [
inputA;
inputA_scale;
inputA_zero_point;
inputB;
inputB_scale;
inputB_zero_point;
inputC;
y_scale;
y_zero_point;
] ->
( inputA,
inputA_scale,
inputA_zero_point,
inputB,
inputB_scale,
inputB_zero_point,
Some inputC,
Some y_scale,
Some y_zero_point )
| _ -> failwith "QGemm must have between 6 and 9 inputs"
in
let inputA = convert inputA in
let inputA_scale = convert inputA_scale in
let inputA_zero_point = convert inputA_zero_point in
let inputB = convert inputB in
let inputB_scale = convert inputB_scale in
let inputB_zero_point = convert inputB_zero_point in
let inputC = Option.map ~f:convert inputC in
let y_scale = Option.map ~f:convert y_scale in
let y_zero_point = Option.map ~f:convert y_zero_point in
let alpha = get_float ~default:1.0 "alpha" in
let transA = get_int ~default:0 "transA" in
let transB = get_int ~default:0 "transB" in
Nir.Node.QGemm
{
inputA;
inputA_scale;
inputA_zero_point;
inputB;
inputB_scale;
inputB_zero_point;
inputC;
y_scale;
y_zero_point;
alpha;
transA;
transB;
}
| "LogSoftmax" -> Nir.Node.LogSoftmax
| "Transpose" ->
Nir.Node.Transpose
{ input = convert (one_arg n.input); perm = get_ints "perm" }
| "Squeeze" ->
let data, axes =
match n.input with
| [ data ] -> (convert data, None)
| [ data; axes ] -> (convert data, Some (convert axes))
| _ -> failwith "Squeeze must have 1 or 2 inputs"
in
Nir.Node.Squeeze { data; axes }
| "MaxPool" -> MaxPool
| "Constant" -> Constant { data = get_tensor "value" }
| "Conv" -> Conv
| "Flatten" ->
Flatten
{ input = convert @@ one_arg n.input; axis = get_int "axis" }
| "Reshape" ->
let input, shape = two_arg n.input in
Reshape { input = convert input; shape = convert shape }
| "Abs" -> Nir.Node.Abs { input = convert @@ one_arg n.input }
| "Log" -> Nir.Node.Log { input = convert @@ one_arg n.input }
| "RandomNormal" ->
Nir.Node.RandomNormal
{
dtype = get_int "dtype";
mean = get_float "mean";
scale = get_float "scale";
seed = get_float "seed";
shape = Array.of_list (get_ints "shape");
}
| "ArgMax" ->
ArgMax
{
input = convert @@ one_arg n.input;
axis = get_int "axis";
keepdims = get_bool ~default:1 "keepdims";
}
| "Concat" ->
Concat
{
inputs = n.input |> List.map ~f:(fun i -> convert i);
axis = get_int "axis";
}
| "Sign" -> Sign { input = convert @@ one_arg n.input }
| "QuantizeLinear" ->
let x, y_scale, y_zero_point =
match n.input with
| [ x; y_scale ] -> (x, y_scale, None)
| [ x; y_scale; y_zero_point ] -> (x, y_scale, Some y_zero_point)
| _ -> failwith "QuantizeLinear must have 2 or 3 inputs"
in
Nir.Node.QuantizeLinear
{
x = convert x;
y_scale = convert y_scale;
y_zero_point = Option.map ~f:convert y_zero_point;
axis = get_int ~default:1 "axis";
}
| "DequantizeLinear" ->
let x, x_scale, x_zero_point =
match n.input with
| [ x; x_scale ] -> (x, x_scale, None)
| [ x; x_scale; x_zero_point ] -> (x, x_scale, Some x_zero_point)
| _ -> failwith "DequantizeLinear must have 2 or 3 inputs"
in
Nir.Node.DequantizeLinear
{
x = convert x;
x_scale = convert x_scale;
x_zero_point = Option.map ~f:convert x_zero_point;
axis = get_int ~default:1 "axis";
}
| s -> failwith (Printf.sprintf "Unknown operators %s" s))
in
Nir.Node.create n'
| Tensor t -> Nir.Node.create (Constant { data = convert_tensor t })
in
let output' = convert output in
assert (Nir.Shape.equal output'.shape output_shape);
Nir.Ngraph.create output'
let nir_of_onnx_protoc (model : Oprotom.t) =
(match model.ir_version with
| None -> failwith "IR version not specified"
| Some (3L | 4L | 5L | 6L | 7L | 8L | 9L | 10L) -> ()
| Some i -> failwith (Printf.sprintf "Unsupported IR version %Li" i));
assert (not (List.is_empty model.opset_import));
if false
then
List.iter model.opset_import ~f:(fun opset ->
Format.printf "opset:%s (%Li)@."
(Option.value ~default:"" opset.domain)
(Option.value_exn opset.version));
match model.graph with
| Some g -> produce_cfg g
| None -> raise (ParseError "No graph in ONNX input file found")
end
let parse_in_channel in_channel =
let open Result in
try
let buf = Stdio.In_channel.input_all in_channel in
let reader = Ocaml_protoc_plugin.Reader.create buf in
match Oprotom.from_proto reader with
| Ok r ->
let n_inputs, n_outputs = Convert.get_input_output_dim r in
let nir =
try Ok (Convert.nir_of_onnx_protoc r) with
| ParseError s | Sys_error s -> Error s
| Failure msg -> Error (Format.sprintf "Unexpected error: %s" msg)
in
Ok { n_inputs; n_outputs; nir }
| _ -> Error "Cannot read protobuf"
with
| Sys_error s -> Error s
| Failure msg -> Error (Format.sprintf "Unexpected error: %s" msg)
let from_file filename =
let in_channel = Stdlib.open_in filename in
Fun.protect
~finally:(fun () -> Stdlib.close_in in_channel)
(fun () -> parse_in_channel in_channel)