forked from otcshare/chromium-src
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ml_graph_builder.cc
2539 lines (2323 loc) · 98.8 KB
/
ml_graph_builder.cc
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
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/renderer/modules/ml/webnn/ml_graph_builder.h"
#include <algorithm>
#include <numeric>
#include <utility>
#include "base/numerics/checked_math.h"
#include "third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_ml_clamp_options.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_ml_conv_2d_options.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_ml_gemm_options.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_ml_operand_descriptor.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_ml_pool_2d_options.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_ml_resample_2d_options.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_ml_arg_min_max_options.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_ml_concat_options_internal.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_ml_gather_options.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_ml_transpose_options.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_ml_squeeze_options.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_ml_slice_options_internal.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_ml_instance_normalization_options.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_ml_reduce_options.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_ml_fill_sequence_options.h"
#include "third_party/blink/renderer/core/dom/dom_exception.h"
#include "third_party/blink/renderer/core/inspector/console_message.h"
#include "third_party/blink/renderer/modules/ml/ml.h"
#include "third_party/blink/renderer/modules/ml/ml_context.h"
#include "third_party/blink/renderer/modules/ml/webnn/buildflags.h"
#include "third_party/blink/renderer/modules/ml/webnn/ml_graph.h"
#include "third_party/blink/renderer/modules/ml/webnn/ml_operand.h"
#include "third_party/blink/renderer/modules/ml/webnn/mojo_graph.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/heap/collection_support/heap_deque.h"
#if BUILDFLAG(BUILD_WEBNN_WITH_XNNPACK)
#include "third_party/blink/renderer/modules/ml/webnn/ml_graph_xnnpack.h"
#endif
// HACK:::
#pragma optimize("", off)
namespace blink {
namespace {
MLGraphBuilder::BackendForTesting* g_backend_for_testing = nullptr;
bool IsFloatingPointType(V8MLOperandType::Enum operand_type) {
switch (operand_type) {
case V8MLOperandType::Enum::kFloat32:
case V8MLOperandType::Enum::kFloat16:
return true;
case V8MLOperandType::Enum::kInt32:
case V8MLOperandType::Enum::kUint32:
case V8MLOperandType::Enum::kInt8:
case V8MLOperandType::Enum::kUint8:
return false;
}
}
bool IsBooleanType(V8MLOperandType::Enum operand_type) {
// Boolean types are unsigned 8-bit values.
switch (operand_type) {
case V8MLOperandType::Enum::kFloat32:
case V8MLOperandType::Enum::kFloat16:
case V8MLOperandType::Enum::kInt32:
case V8MLOperandType::Enum::kUint32:
case V8MLOperandType::Enum::kInt8:
return false;
case V8MLOperandType::Enum::kUint8:
return true;
}
}
bool IsIndexType(V8MLOperandType::Enum operand_type) {
// Index types are integers, signed or unsigned.
switch (operand_type) {
case V8MLOperandType::Enum::kFloat32:
case V8MLOperandType::Enum::kFloat16:
case V8MLOperandType::Enum::kInt8:
case V8MLOperandType::Enum::kUint8:
return false;
case V8MLOperandType::Enum::kInt32:
case V8MLOperandType::Enum::kUint32:
return true;
}
}
bool ValidateClampOptions(const MLClampOptions* options,
ExceptionState& exception_state) {
// The generated code of MLClampOptions uses blink::ToRestrictedFloat to
// convert the min/max value to a single precision float. It will throw on
// non-finite values.
if (options->hasMinValue() && options->hasMaxValue()) {
if (options->minValue() > options->maxValue()) {
exception_state.ThrowDOMException(
DOMExceptionCode::kDataError,
String::Format("The min value (%f) should be less than or equal to "
"the max value (%f).",
options->minValue(), options->maxValue()));
return false;
}
}
return true;
}
bool ValidateAxis(uint32_t axis,
uint32_t dimension_count,
const char* operator_name,
ExceptionState& exception_state) {
if (axis >= dimension_count)
{
exception_state.ThrowDOMException(
DOMExceptionCode::kDataError,
String::Format(
"The %s axis (%u) must be within the dimension count (%u).",
operator_name,
axis, dimension_count));
return false;
}
return true;
}
bool ValidateAxes(base::span<const uint32_t> axes,
uint32_t dimension_count,
const char* operator_name,
ExceptionState& exception_state) {
Vector<uint32_t> seen_axes(dimension_count);
for (auto axis : axes)
{
if (axis >= dimension_count)
{
exception_state.ThrowDOMException(
DOMExceptionCode::kDataError,
String::Format(
"The %s axis (%u) must be less than the dimension count (%u).",
operator_name,
axis, dimension_count));
return false;
}
if (seen_axes[axis])
{
exception_state.ThrowDOMException(
DOMExceptionCode::kDataError,
String::Format(
"Each %s axis (%u) must only occur once.",
operator_name, axis));
return false;
}
seen_axes[axis] = true;
}
return true;
}
// Generates a 32-bit mask, validating all axes fit within 32 dimensions.
bool ValidateAxesMask(base::span<const uint32_t> axes,
const char* operator_name,
ExceptionState& exception_state,
/*out*/ uint32_t& axes_mask) {
uint32_t current_mask = 0x00000000;
axes_mask = current_mask;
const uint32_t maximum_rank = 32; // Only have 32 bits available.
for (auto axis : axes)
{
if (axis >= maximum_rank)
{
exception_state.ThrowDOMException(
DOMExceptionCode::kDataError,
String::Format(
"%s axis (%u) is beyond the maximum (%u).",
operator_name,
axis, maximum_rank));
return false;
}
current_mask |= 1 << axis;
}
axes_mask = current_mask;
return true;
}
// Computes the number of elements given the dimensions.
// Note this expects dimensions that are already known and validated
// and thus cannot overflow, rather than untrusted parameters like
// reshape's new shape before validation.
uint32_t ComputeElementCount(base::span<const uint32_t> dimensions)
{
return std::accumulate(dimensions.begin(), dimensions.end(), 1u, std::multiplies<uint32_t>{});
}
// Increases the rank to a minimum count by padding with leading ones.
Vector<uint32_t> ExpandDimensions(
const base::span<const uint32_t> original_dimensions,
wtf_size_t minimum_rank) {
wtf_size_t old_rank = static_cast<wtf_size_t>(original_dimensions.size());
wtf_size_t new_rank = std::max(minimum_rank, static_cast<wtf_size_t>(old_rank));
wtf_size_t leading_filler_count = new_rank - old_rank;
Vector<uint32_t> expanded_dimensions(new_rank, 1u);
std::copy(original_dimensions.begin(), original_dimensions.end(),
expanded_dimensions.begin() + leading_filler_count);
return expanded_dimensions;
}
// Broadcast the input shapes and return the output shape.
// If bidirectional is true, its behavior follows the numpy-broadcasting-rule:
// https://numpy.org/doc/stable/user/basics.broadcasting.html#general-broadcasting-rules.
// Otherwise, it unidirectionally broadcasts the lhs to the rhs.
// The ignorable tail count is useful for cases like MatMul, where you want
// to ignore the trailing tail of dimensions and only broadcast the leading
// ones, because the trailing part (returned as 0's) will be filled in later.
absl::optional<Vector<uint32_t>> BroadcastShapes(
base::span<const uint32_t> dims_lhs,
base::span<const uint32_t> dims_rhs,
bool bidirectional = true,
wtf_size_t ignorable_tail_count = 0
) {
// If bidirectional is true, the rank of the output shape is the maximum
// rank of the input shapes. Otherwise it is as the same as the rhs' rank.
auto rank_lhs = static_cast<wtf_size_t>(dims_lhs.size());
auto rank_rhs = static_cast<wtf_size_t>(dims_rhs.size());
auto rank_output = bidirectional ? std::max(rank_lhs, rank_rhs) : rank_rhs;
Vector<uint32_t> dims_output(rank_output);
// Note the loop effectively works backwards from the end of the dimensions
// array (the counter is forward, but accesses are relative the end).
for (wtf_size_t i = ignorable_tail_count; i < rank_output; ++i) {
auto dim_lhs = i < rank_lhs ? dims_lhs[rank_lhs - i - 1] : 1;
DCHECK_GT(dim_lhs, uint32_t(0));
auto dim_rhs = i < rank_rhs ? dims_rhs[rank_rhs - i - 1] : 1;
DCHECK_GT(dim_rhs, uint32_t(0));
// If bidirectional is true, two dimensions are compatible when they are
// equal, or one of them is 1. Otherwise, two dimensions are compatible
// when they are equal, or the lhs dimension is 1.
if (bidirectional) {
if (dim_lhs != dim_rhs && dim_lhs != 1 && dim_rhs != 1) {
return absl::nullopt;
}
} else if (dim_lhs != dim_rhs && dim_lhs != 1) {
return absl::nullopt;
}
// If bidirectional is true, for each dimension of the output tensor, its
// size is the maximum size along that dimension of the input shapes.
// Otherwise, its size is the same as the rhs.
dims_output[rank_output - i - 1] =
bidirectional ? std::max(dim_lhs, dim_rhs) : dim_rhs;
}
return dims_output;
}
MLOperand* BuildUnaryOperator(MLGraphBuilder* builder,
MLOperator::OperatorKind kind,
const MLOperand* input,
ExceptionState& exception_state) {
String error_message;
auto* ml_operator = MakeGarbageCollected<MLOperator>(builder, kind);
Vector<uint32_t> output_dimensions = input->Dimensions();
auto* output = MLOperand::ValidateAndCreateOutput(
builder, input->Type(), std::move(output_dimensions), ml_operator, /*out*/ error_message);
if (!output) {
exception_state.ThrowDOMException(DOMExceptionCode::kDataError,
error_message);
return nullptr;
}
ml_operator->Connect({input}, {output});
return output;
}
MLOperand* BuildUnaryOperator(
MLGraphBuilder* builder,
MLOperator::OperatorKind kind,
const MLOperand* input,
Vector<uint32_t> output_dimensions,
V8MLOperandType::Enum output_data_type,
const bindings::DictionaryBase* options,
ExceptionState& exception_state) {
String error_message;
auto* ml_operator = MakeGarbageCollected<MLOperator>(builder, kind, options);
auto* output = MLOperand::ValidateAndCreateOutput(
builder, output_data_type, std::move(output_dimensions), ml_operator,
/*out*/ error_message);
if (!output) {
exception_state.ThrowDOMException(DOMExceptionCode::kDataError,
error_message);
return nullptr;
}
ml_operator->Connect({input}, {output});
return output;
}
MLOperand* BuildElementwiseBinary(MLGraphBuilder* builder,
MLOperator::OperatorKind kind,
const MLOperand* a,
const MLOperand* b,
V8MLOperandType::Enum output_data_type,
ExceptionState& exception_state) {
if (a->Type() != b->Type()) {
exception_state.ThrowDOMException(DOMExceptionCode::kDataError,
"The input types don't match.");
return nullptr;
}
absl::optional<Vector<uint32_t>> dims_output =
BroadcastShapes(a->Dimensions(), b->Dimensions());
if (!dims_output) {
exception_state.ThrowDOMException(
DOMExceptionCode::kDataError,
"The input shapes are not broadcastable.");
return nullptr;
}
auto* binary = MakeGarbageCollected<MLOperator>(builder, kind);
String error_message;
auto* output = MLOperand::ValidateAndCreateOutput(
builder, output_data_type, std::move(dims_output.value()), binary, error_message);
if (!output) {
exception_state.ThrowDOMException(DOMExceptionCode::kDataError,
error_message);
return nullptr;
}
binary->Connect({a, b}, {output});
return output;
}
MLOperand* BuildArgMinMax(MLGraphBuilder* graph_builder,
MLOperator::OperatorKind operator_kind,
const char* operator_name,
const MLOperand* input,
const MLArgMinMaxOptions* options,
ExceptionState& exception_state) {
// Validate axis.
uint32_t axis = options->axis();
auto& input_dimensions = input->Dimensions();
if (!ValidateAxis(axis,
input_dimensions.size(),
operator_name,
exception_state)) {
return nullptr;
}
// Determine output size, eliminating the active axis or keeping it with size 1.
Vector<uint32_t> output_dimensions = input_dimensions;
if (options->keepDimensions())
{
output_dimensions[axis] = 1;
}
else
{
output_dimensions.EraseAt(axis);
}
return BuildUnaryOperator(graph_builder, operator_kind, input,
output_dimensions, V8MLOperandType::Enum::kUint32, options,
exception_state);
}
MLOperand* BuildReductionOperator(MLGraphBuilder* graph_builder,
MLOperator::OperatorKind operator_kind,
const char* operator_name,
const MLOperand* input,
const MLReduceOptions* options,
ExceptionState& exception_state) {
const auto& input_dimensions = input->Dimensions();
const wtf_size_t input_rank = input_dimensions.size();
Vector<uint32_t> axes;
uint32_t axes_mask = 0xFFFFFFFF; // Remove all axes by default, if none passed.
// Verify the axes are within the input rank and not duplicated.
if (options->hasAxes())
{
axes = options->axes();
if (!ValidateAxes(axes, input_rank, operator_name, exception_state)) {
return nullptr;
}
if (!ValidateAxesMask(options->axes(),
operator_name,
exception_state,
/*out*/ axes_mask)) {
return nullptr;
}
}
else // Reduce all dimensions if permutations are missing.
{
axes.resize(input_rank);
std::iota(axes.begin(), axes.end(), 0u);
// axes_mask already 0xFFFFFFFF.
}
// Set dimension to 1 that are reduced.
// or erase them entirely if MLReduceOptions::keepDimensions = false.
Vector<uint32_t> output_dimensions = input_dimensions;
wtf_size_t output_rank = input_rank;
bool keep_dimensions = options->keepDimensions();
for (wtf_size_t i = 0; i < output_rank; /*increment in loop*/)
{
wtf_size_t advance_count = 1;
if (axes_mask & (1 << i)) {
if (keep_dimensions) {
output_dimensions[i] = 1u; // Reduce dimension.
}
else {
output_dimensions.EraseAt(i); // Remove reduced dimension.
advance_count = 0; // Stay at the current index.
--output_rank;
}
}
i += advance_count;
}
// Pass the normalized options onward, simplifying the lower level's job.
MLReduceOptions* normalized_options = MLReduceOptions::Create();
normalized_options->setAxes(axes);
return BuildUnaryOperator(graph_builder, operator_kind, input,
output_dimensions, input->Type(), normalized_options,
exception_state);
}
struct PaddingSizes {
uint32_t begin;
uint32_t end;
};
// Calculate the padding given auto pad, input size, filter size, stride and
// dilation. Return the calculated padding sizes if no error.
absl::optional<PaddingSizes> CalculatePaddingForAutoPad(
V8MLAutoPad::Enum auto_pad,
const uint32_t input_size,
const uint32_t filter_size,
const uint32_t stride,
const uint32_t dilation) {
auto checked_output_size =
(base::MakeCheckedNum<uint32_t>(input_size) + stride - 1) / stride;
auto checked_dilated_filter_size =
(base::MakeCheckedNum<uint32_t>(filter_size) - 1) * dilation + 1;
auto checked_needed_input_size =
(checked_output_size - 1) * stride + checked_dilated_filter_size;
if (!checked_needed_input_size.IsValid()) {
return absl::nullopt;
}
auto checked_total_padding =
checked_needed_input_size.ValueOrDie() > input_size
? checked_needed_input_size - input_size
: base::MakeCheckedNum<uint32_t>(0);
base::CheckedNumeric<uint32_t> checked_padding_begin, checked_padding_end;
switch (auto_pad) {
case V8MLAutoPad::Enum::kSameUpper:
checked_padding_begin = checked_total_padding / 2;
checked_padding_end = (checked_total_padding + 1) / 2;
break;
case V8MLAutoPad::Enum::kSameLower:
checked_padding_begin = (checked_total_padding + 1) / 2;
checked_padding_end = checked_total_padding / 2;
break;
default:
NOTREACHED();
}
uint32_t padding_begin, padding_end;
if (!checked_padding_begin.AssignIfValid(&padding_begin) ||
!checked_padding_end.AssignIfValid(&padding_end)) {
return absl::nullopt;
}
return PaddingSizes({.begin = padding_begin, .end = padding_end});
}
// Calculate the output size for conv2d based on WebNN spec:
// https://www.w3.org/TR/webnn/#api-mlgraphbuilder-conv2d
// Return the calculated output size if no error.
absl::optional<double> CalculateConv2dOutputSize(
const uint32_t input_size,
const uint32_t filter_size,
const uint32_t beginning_padding,
const uint32_t ending_padding,
const uint32_t stride,
const uint32_t dilation,
String& error_message) {
// Calculate the dilated filter sizes.
auto checked_effective_filter_size =
(base::MakeCheckedNum<uint32_t>(filter_size) - 1) * dilation + 1;
if (!checked_effective_filter_size.IsValid()) {
error_message = "The effective filter size is too large.";
return absl::nullopt;
}
// Calculate the output size in double precision floating point number that
// ensures all dimension values of type uint32_t can be exactly represented.
// https://en.wikipedia.org/wiki/Double-precision_floating-point_format#Precision_limitations_on_integer_values
// The max value of checked_output_size should be 3 * UINT_MAX + 1,
// which is smaller than the max safe integer value for double type.
auto checked_output_size =
(base::MakeCheckedNum<double>(input_size) -
checked_effective_filter_size + beginning_padding + ending_padding) /
stride +
1;
if (checked_output_size.ValueOrDie() < 0) {
error_message = "The input size is too small to fill the window.";
return absl::nullopt;
}
// Check if the value is valid for rounding to uint32_t type.
if (!checked_output_size.IsValid<uint32_t>()) {
error_message = "The output size is too large.";
return absl::nullopt;
}
return checked_output_size.ValueOrDie();
}
struct FloatSize2D {
double height;
double width;
};
// Validate and calculate the output spatial dimensions of conv2d given
// input sizes, filter sizes, padding, strides and dilations.
// Return the calculated output sizes in double precision floating point
// number if no errors.
absl::optional<FloatSize2D> ValidateAndCalculateConv2dOutputSizes(
const uint32_t input_height,
const uint32_t input_width,
const uint32_t filter_height,
const uint32_t filter_width,
const Vector<uint32_t>& padding,
const Vector<uint32_t>& strides,
const Vector<uint32_t>& dilations,
const V8MLAutoPad auto_pad,
ExceptionState& exception_state) {
// Validate padding and get its values.
if (padding.size() != 4) {
exception_state.ThrowDOMException(DOMExceptionCode::kDataError,
"The length of padding should be 4.");
return absl::nullopt;
}
uint32_t padding_beginning_height = padding[0];
uint32_t padding_ending_height = padding[1];
uint32_t padding_beginning_width = padding[2];
uint32_t padding_ending_width = padding[3];
// Validate strides and get its values.
if (strides.size() != 2) {
exception_state.ThrowDOMException(DOMExceptionCode::kDataError,
"The length of strides should be 2.");
return absl::nullopt;
}
if (std::any_of(strides.begin(), strides.end(),
[](uint32_t x) { return x == 0; })) {
exception_state.ThrowDOMException(DOMExceptionCode::kDataError,
"All strides should be greater than 0.");
return absl::nullopt;
}
const uint32_t stride_height = strides[0];
const uint32_t stride_width = strides[1];
// Validate dilations and get its values.
if (dilations.size() != 2) {
exception_state.ThrowDOMException(DOMExceptionCode::kDataError,
"The length of dilations should be 2.");
return absl::nullopt;
}
if (std::any_of(dilations.begin(), dilations.end(),
[](uint32_t x) { return x == 0; })) {
exception_state.ThrowDOMException(
DOMExceptionCode::kDataError,
"All dilations should be greater than 0.");
return absl::nullopt;
}
const uint32_t dilation_height = dilations[0];
const uint32_t dilation_width = dilations[1];
// When the autoPad is other than "explicit", the values in the
// options.padding array are ignored and the explicit padding values need to
// be calculated.
if (auto_pad != V8MLAutoPad::Enum::kExplicit) {
auto padding_sizes_height = MLGraphBuilder::CalculatePaddingForAutoPad(
auto_pad.AsEnum(), input_height, filter_height, stride_height,
dilation_height);
if (!padding_sizes_height) {
exception_state.ThrowDOMException(
DOMExceptionCode::kDataError,
"Overflow occurred when calculating "
"the padding along the height dimension.");
return absl::nullopt;
}
padding_beginning_height = padding_sizes_height.value().begin;
padding_ending_height = padding_sizes_height.value().end;
auto padding_sizes_width = MLGraphBuilder::CalculatePaddingForAutoPad(
auto_pad.AsEnum(), input_width, filter_width, stride_width,
dilation_width);
if (!padding_sizes_width) {
exception_state.ThrowDOMException(
DOMExceptionCode::kDataError,
"Overflow occurred when calculating "
"the padding along the width dimension.");
return absl::nullopt;
}
padding_beginning_width = padding_sizes_width.value().begin;
padding_ending_width = padding_sizes_width.value().end;
}
String error_message;
auto float_output_height = CalculateConv2dOutputSize(
input_height, filter_height, padding_beginning_height,
padding_ending_height, stride_height, dilation_height, error_message);
if (!float_output_height) {
exception_state.ThrowDOMException(
DOMExceptionCode::kDataError,
"Failed to calculate the output height: " + error_message);
return absl::nullopt;
}
auto float_output_width = CalculateConv2dOutputSize(
input_width, filter_width, padding_beginning_width, padding_ending_width,
stride_width, dilation_width, error_message);
if (!float_output_width) {
exception_state.ThrowDOMException(
DOMExceptionCode::kDataError,
"Failed to calculate the output width: " + error_message);
return absl::nullopt;
}
return FloatSize2D({.height = float_output_height.value(),
.width = float_output_width.value()});
}
MLOperand* BuildPool2d(MLGraphBuilder* builder,
MLOperator::OperatorKind kind,
const MLOperand* input,
const MLPool2dOptions* options,
ExceptionState& exception_state) {
// Validate input operand and set its sizes.
const auto input_shape = input->Dimensions();
if (input_shape.size() != 4) {
exception_state.ThrowDOMException(DOMExceptionCode::kDataError,
"The input should be a 4-D tensor.");
return nullptr;
}
// The layout option specifies the layout format of the input tensor.
uint32_t input_batches, input_channels, input_height, input_width;
switch (options->layout().AsEnum()) {
case V8MLInputOperandLayout::Enum::kNchw:
// "nchw": [batches, channels, height, width]
input_batches = input_shape[0];
input_channels = input_shape[1];
input_height = input_shape[2];
input_width = input_shape[3];
break;
case V8MLInputOperandLayout::Enum::kNhwc:
// "nhwc": [batches, height, width, channels]
input_batches = input_shape[0];
input_height = input_shape[1];
input_width = input_shape[2];
input_channels = input_shape[3];
break;
}
// Validate windowDimensions and get its values. If not present, the window
// dimensions are assumed to be the height and width dimensions of the input
// shape. The current WebNN spec defines the windowDimensions as signed
// integer:
// https://www.w3.org/TR/webnn/#dom-mlpool2doptions-windowdimensions
// However, there is a proposal of using unsigned integer:
// https://github.com/webmachinelearning/webnn/pull/294
// Before the change merged, the signed integers are checked_cast to
// unsigned integers for output shape calculation.
uint32_t window_height = input_height;
uint32_t window_width = input_width;
if (options->hasWindowDimensions()) {
if (options->windowDimensions().size() != 2) {
exception_state.ThrowDOMException(
DOMExceptionCode::kDataError,
"The length of window dimensions should be 2.");
return nullptr;
}
if (std::any_of(options->windowDimensions().begin(),
options->windowDimensions().end(),
[](uint32_t x) { return x == 0; })) {
exception_state.ThrowDOMException(
DOMExceptionCode::kDataError,
"All window dimensions should be greater than 0.");
return nullptr;
}
window_height = options->windowDimensions()[0];
window_width = options->windowDimensions()[1];
}
// Reuse ValidateAndCalculateConv2dOutputSizes to calculate pool2d output
// sizes.
const auto output_sizes = ValidateAndCalculateConv2dOutputSizes(
input_height, input_width, window_height, window_width,
// If padding is not present, the values are assumed to be [0,0,0,0].
options->getPaddingOr({0, 0, 0, 0}),
// If strides is not present, the values are assumed to be [1,1].
options->getStridesOr({1, 1}),
// If dilations is not present, the values are assumed to be [1, 1].
options->getDilationsOr({1, 1}), options->autoPad(), exception_state);
if (!output_sizes) {
return nullptr;
}
const uint32_t floor_output_height =
base::ClampFloor<uint32_t>(output_sizes.value().height);
const uint32_t ceil_output_height =
base::ClampCeil<uint32_t>(output_sizes.value().height);
const uint32_t floor_output_width =
base::ClampFloor<uint32_t>(output_sizes.value().width);
const uint32_t ceil_output_width =
base::ClampCeil<uint32_t>(output_sizes.value().width);
uint32_t output_height, output_width;
if (options->hasOutputSizes()) {
// TODO([email protected]): report a DevTools warning message if
// rounding type is provided but ignored.
if (options->outputSizes().size() != 2) {
exception_state.ThrowDOMException(
DOMExceptionCode::kDataError,
"The length of output sizes should be 2.");
return nullptr;
}
if (std::any_of(options->outputSizes().begin(),
options->outputSizes().end(),
[](uint32_t x) { return x == 0; })) {
exception_state.ThrowDOMException(
DOMExceptionCode::kDataError,
"All output sizes should be greater than 0.");
return nullptr;
}
uint32_t user_output_height = options->outputSizes()[0];
uint32_t user_output_width = options->outputSizes()[1];
// Check whether the user supplied output sizes is either floor or ceil
// rounding of the calculated output sizes. The backend implementation
// should check whether the indicated rounding type is supported.
if ((user_output_height == floor_output_height &&
user_output_width == floor_output_width) ||
(user_output_height == ceil_output_height &&
user_output_width == ceil_output_width)) {
output_height = user_output_height;
output_width = user_output_width;
} else {
exception_state.ThrowDOMException(
DOMExceptionCode::kDataError,
(floor_output_height == ceil_output_height &&
floor_output_width == ceil_output_width)
? String::Format("The output sizes should be [%u, %u].",
floor_output_height, floor_output_width)
: String::Format(
"The output sizes should be either [%u, %u] or [%u, %u].",
floor_output_height, floor_output_width, ceil_output_height,
ceil_output_width));
return nullptr;
}
} else {
switch (options->roundingType().AsEnum()) {
case V8MLRoundingType::Enum::kFloor:
output_height = floor_output_height;
output_width = floor_output_width;
break;
case V8MLRoundingType::Enum::kCeil:
output_height = ceil_output_height;
output_width = ceil_output_width;
break;
}
}
// The layout option specifies the layout format of the output tensor.
Vector<uint32_t> output_shape;
switch (options->layout().AsEnum()) {
case V8MLInputOperandLayout::Enum::kNchw:
// "nchw": [batches, channels, height, width]
output_shape = {input_batches, input_channels, output_height,
output_width};
break;
case V8MLInputOperandLayout::Enum::kNhwc:
// "nhwc": [batches, height, width, channels]
output_shape = {input_batches, output_height, output_width,
input_channels};
break;
}
// Create pool2d operator and its output operand. Connect the pool2d
// operator to its input and output operands.
auto* pool2d = MakeGarbageCollected<MLOperator>(builder, kind, options);
String error_message;
auto* output = MLOperand::ValidateAndCreateOutput(
builder, input->Type(), std::move(output_shape), pool2d, error_message);
if (!output) {
exception_state.ThrowDOMException(DOMExceptionCode::kDataError,
error_message);
return nullptr;
}
pool2d->Connect({input}, {output});
return output;
}
} // namespace
// static
MLGraphBuilder* MLGraphBuilder::Create(MLContext* context) {
return MakeGarbageCollected<MLGraphBuilder>(context);
}
MLGraphBuilder::MLGraphBuilder(MLContext* context) : ml_context_(context) {}
MLGraphBuilder::~MLGraphBuilder() = default;
void MLGraphBuilder::Trace(Visitor* visitor) const {
visitor->Trace(ml_context_);
ScriptWrappable::Trace(visitor);
}
MLContext* MLGraphBuilder::GetContext() const {
return ml_context_;
}
// static
absl::optional<MLGraphBuilder::PaddingSizes>
MLGraphBuilder::CalculatePaddingForAutoPad(V8MLAutoPad::Enum auto_pad,
const uint32_t input_size,
const uint32_t filter_size,
const uint32_t stride,
const uint32_t dilation) {
auto checked_output_size =
(base::MakeCheckedNum<uint32_t>(input_size) + stride - 1) / stride;
auto checked_dilated_filter_size =
(base::MakeCheckedNum<uint32_t>(filter_size) - 1) * dilation + 1;
auto checked_needed_input_size =
(checked_output_size - 1) * stride + checked_dilated_filter_size;
if (!checked_needed_input_size.IsValid()) {
return absl::nullopt;
}
auto checked_total_padding =
checked_needed_input_size.ValueOrDie() > input_size
? checked_needed_input_size - input_size
: base::MakeCheckedNum<uint32_t>(0);
base::CheckedNumeric<uint32_t> checked_padding_begin, checked_padding_end;
switch (auto_pad) {
case V8MLAutoPad::Enum::kSameUpper:
checked_padding_begin = checked_total_padding / 2;
checked_padding_end = (checked_total_padding + 1) / 2;
break;
case V8MLAutoPad::Enum::kSameLower:
checked_padding_begin = (checked_total_padding + 1) / 2;
checked_padding_end = checked_total_padding / 2;
break;
default:
NOTREACHED();
}
uint32_t padding_begin, padding_end;
if (!checked_padding_begin.AssignIfValid(&padding_begin) ||
!checked_padding_end.AssignIfValid(&padding_end)) {
return absl::nullopt;
}
return PaddingSizes({.begin = padding_begin, .end = padding_end});
}
MLOperand* MLGraphBuilder::input(String name,
const MLOperandDescriptor* desc,
ExceptionState& exception_state) {
String error_message;
// If no dimensions, it represents a scalar. Set dimensions to {1}.
Vector<uint32_t> dimensions = desc->getDimensionsOr({1});
auto* input_operand = MLOperand::ValidateAndCreateInput(
this, desc->type().AsEnum(), std::move(dimensions), std::move(name),
error_message);
if (!input_operand) {
exception_state.ThrowDOMException(DOMExceptionCode::kDataError,
error_message);
return nullptr;
}
return input_operand;
}
MLOperand* MLGraphBuilder::constant(const MLOperandDescriptor* desc,
NotShared<DOMArrayBufferView> buffer_view,
ExceptionState& exception_state) {
String error_message;
// If no dimensions, it represents a scalar. Set dimensions to {1}.
Vector<uint32_t> dimensions = desc->getDimensionsOr({1});
auto* constant_operand = MLOperand::ValidateAndCreateConstant(
this, desc->type().AsEnum(), std::move(dimensions), buffer_view.Get(),
error_message);
if (!constant_operand) {
exception_state.ThrowDOMException(DOMExceptionCode::kDataError,
error_message);
return nullptr;
}
return constant_operand;
}
MLOperand* MLGraphBuilder::clamp(const MLOperand* input,
const MLClampOptions* options,
ExceptionState& exception_state) {
if (!ValidateClampOptions(options, exception_state)) {
return nullptr;
}
auto* clamp = MakeGarbageCollected<MLOperator>(
this, MLOperator::OperatorKind::kClamp, options);
// According to WebNN spec
// https://www.w3.org/TR/webnn/#api-mlgraphbuilder-clamp, the output tensor of
// clamp has the same type and dimensions as its input.
String error_message;
auto* output = MLOperand::ValidateAndCreateOutput(
this, input->Type(), input->Dimensions(), clamp, error_message);
if (!output) {
exception_state.ThrowDOMException(DOMExceptionCode::kDataError,
error_message);
return nullptr;
}
clamp->Connect({input}, {output});
return output;
}
MLOperator* MLGraphBuilder::clamp(const MLClampOptions* options,
ExceptionState& exception_state) {
if (!ValidateClampOptions(options, exception_state)) {
return nullptr;
}
// Create the clamp operator that would be used as an activation function.
return MakeGarbageCollected<MLOperator>(
this, MLOperator::OperatorKind::kClamp, options);
}
MLOperand* MLGraphBuilder::conv2d(const MLOperand* input,
const MLOperand* filter,
const MLConv2dOptions* options,
ExceptionState& exception_state) {
// Validate input operand and set its sizes.
const auto input_shape = input->Dimensions();
if (input_shape.size() != 4) {
exception_state.ThrowDOMException(DOMExceptionCode::kDataError,
"The input should be a 4-D tensor.");
return nullptr;
}
// The input layout option specifies the layout format of the input tensor.
uint32_t input_batches, input_channels, input_height, input_width;
switch (options->inputLayout().AsEnum()) {
case V8MLInputOperandLayout::Enum::kNchw:
// "nchw": [batches, input_channels, height, width]
input_batches = input_shape[0];
input_channels = input_shape[1];
input_height = input_shape[2];
input_width = input_shape[3];
break;
case V8MLInputOperandLayout::Enum::kNhwc:
// "nhwc": [batches, height, width, input_channels]
input_batches = input_shape[0];
input_height = input_shape[1];
input_width = input_shape[2];
input_channels = input_shape[3];
break;
}
// Validate filter operand and set its sizes.
if (filter->Type() != input->Type()) {
exception_state.ThrowDOMException(
DOMExceptionCode::kDataError,
"The filter type doesn't match the input type.");
return nullptr;
}
const auto filter_shape = filter->Dimensions();
if (filter_shape.size() != 4) {
exception_state.ThrowDOMException(DOMExceptionCode::kDataError,
"The filter should be a 4-D tensor.");
return nullptr;
}
// The filter layout specifies the filter layout format.
uint32_t filter_height, filter_width, output_channels, filter_input_channels;
switch (options->filterLayout().AsEnum()) {
case V8MLConv2dFilterOperandLayout::Enum::kHwio:
// "hwio": [height, width, input_channels/groups, output_channels]
filter_height = filter_shape[0];
filter_width = filter_shape[1];
filter_input_channels = filter_shape[2];
output_channels = filter_shape[3];
break;
case V8MLConv2dFilterOperandLayout::Enum::kOhwi:
// "ohwi": [output_channels, height, width, input_channels/groups]
output_channels = filter_shape[0];
filter_height = filter_shape[1];
filter_width = filter_shape[2];
filter_input_channels = filter_shape[3];
break;
case V8MLConv2dFilterOperandLayout::Enum::kIhwo:
// "ihwo": [input_channels/groups, height, width, output_channels]
filter_input_channels = filter_shape[0];
filter_height = filter_shape[1];
filter_width = filter_shape[2];