forked from webmachinelearning/webnn-samples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathresnet50v2_nhwc.js
195 lines (180 loc) · 7.19 KB
/
resnet50v2_nhwc.js
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
'use strict';
import {buildConstantByNpy, computePadding2DForAutoPad} from '../common/utils.js';
const autoPad = 'same-upper';
const strides = [2, 2];
const layout = 'nhwc';
// ResNet 50 V2 model with 'nhwc' layout
export class ResNet50V2Nhwc {
constructor() {
this.context_ = null;
this.builder_ = null;
this.graph_ = null;
this.weightsUrl_ = '../test-data/models/resnet50v2_nhwc/weights/';
if (location.hostname.toLowerCase().indexOf('github.io') > -1) {
this.weightsUrl_ = 'https://d3i5xkfad89fac.cloudfront.net/test-data/models/resnet50v2_nhwc/weights/';
}
this.inputOptions = {
mean: [127.5, 127.5, 127.5],
std: [127.5, 127.5, 127.5],
inputLayout: layout,
labelUrl: './labels/labels1001.txt',
inputDimensions: [1, 224, 224, 3],
};
this.outputDimensions = [1, 1001];
}
async buildConv_(input, nameIndices, options = {}, relu = true) {
let prefix = this.weightsUrl_ + 'resnet_v2_50_';
// Items in 'nameIndices' represent the indices of block, unit, conv
// respectively, except two kinds of specific conv names:
// 1. contains 'shortcut', e.g.
// resnet_v2_50_block1_unit_1_bottleneck_v2_shortcut_weights.npy
// 2. contains 'logits', e.g. resnet_v2_50_logits_weights.npy
if (nameIndices[0] !== '' && nameIndices[1] !== '') {
prefix += `block${nameIndices[0]}_unit_${nameIndices[1]}_bottleneck_v2_`;
}
if (nameIndices[2] === 'shortcut') {
prefix += 'shortcut';
} else if (nameIndices[2] === 'logits') {
prefix += nameIndices[2];
} else {
prefix += 'conv' + nameIndices[2];
}
const weightsName = prefix + '_weights.npy';
const weights = await buildConstantByNpy(this.builder_, weightsName);
const biasName = prefix + '_Conv2D_bias.npy';
const bias = await buildConstantByNpy(this.builder_, biasName);
options.inputLayout = layout;
options.filterLayout = 'ohwi';
options.bias = bias;
if (relu) {
options.activation = this.builder_.relu();
}
// WebNN spec drops autoPad support, compute the explicit padding instead.
if (options.autoPad == 'same-upper') {
options.padding =
computePadding2DForAutoPad(
/* nwhc */[input.shape()[1], input.shape()[2]],
/* ohwi */[weights.shape()[1], weights.shape()[2]],
options.strides, options.dilations, options.autoPad);
}
return this.builder_.conv2d(input, weights, options);
}
async buildFusedBatchNorm_(input, nameIndices) {
let prefix = this.weightsUrl_ + 'resnet_v2_50_';
if (nameIndices[0] === 'postnorm') {
prefix += 'postnorm';
} else {
prefix +=
`block${nameIndices[0]}_unit_${nameIndices[1]}_bottleneck_v2_preact`;
}
const mulParamName = prefix + '_FusedBatchNorm_mul_0_param.npy';
const mulParam = await buildConstantByNpy(this.builder_, mulParamName);
const addParamName = prefix + '_FusedBatchNorm_add_param.npy';
const addParam = await buildConstantByNpy(this.builder_, addParamName);
return this.builder_.relu(
this.builder_.add(this.builder_.mul(input, mulParam), addParam));
}
async buildBottleneckV2_(
input, nameIndices, downsample = false, shortcut = true) {
let residual = input;
const fusedBn = await this.buildFusedBatchNorm_(input, nameIndices);
const conv1 = await this.buildConv_(
fusedBn, nameIndices.concat(['1']), {autoPad});
let conv2;
if (downsample) {
residual = await this.buildConv_(
fusedBn, nameIndices.concat(['shortcut']), {autoPad}, false);
}
if (!downsample && shortcut) {
residual = this.builder_.maxPool2d(
input, {windowDimensions: [2, 2], strides, layout, autoPad});
conv2 = await this.buildConv_(
conv1, nameIndices.concat(['2']), {strides, padding: [1, 1, 1, 1]});
} else {
conv2 = await this.buildConv_(
conv1, nameIndices.concat(['2']), {autoPad});
}
const conv3 = await this.buildConv_(
conv2, nameIndices.concat(['3']), {autoPad}, false);
return this.builder_.add(conv3, residual);
}
async load(contextOptions) {
this.context_ = await navigator.ml.createContext(contextOptions);
this.builder_ = new MLGraphBuilder(this.context_);
const input = this.builder_.input('input', {
type: 'float32',
dataType: 'float32',
dimensions: this.inputOptions.inputDimensions,
});
const conv1 = await this.buildConv_(
input, ['', '', '1'], {strides, padding: [3, 3, 3, 3]}, false);
const windowDimensions = [3, 3];
const pool = this.builder_.maxPool2d(
conv1, {windowDimensions, strides, layout,
padding: computePadding2DForAutoPad(
/* nhwc */ [conv1.shape()[1], conv1.shape()[2]],
windowDimensions, strides, /* dilations */ undefined,
'same-upper')});
// Block 1
const bottleneck1 = await this.buildBottleneckV2_(pool, ['1', '1'], true);
const bottleneck2 = await this.buildBottleneckV2_(
bottleneck1, ['1', '2'], false, false);
const bottleneck3 = await this.buildBottleneckV2_(
bottleneck2, ['1', '3']);
// Block 2
const bottleneck4 = await this.buildBottleneckV2_(
bottleneck3, ['2', '1'], true);
const bottleneck5 = await this.buildBottleneckV2_(
bottleneck4, ['2', '2'], false, false);
const bottleneck6 = await this.buildBottleneckV2_(
bottleneck5, ['2', '3'], false, false);
const bottleneck7 = await this.buildBottleneckV2_(
bottleneck6, ['2', '4']);
// Block 3
const bottleneck8 = await this.buildBottleneckV2_(
bottleneck7, ['3', '1'], true);
const loop = async (node, num) => {
if (num > 5) {
return node;
} else {
const newNode = await this.buildBottleneckV2_(
node, ['3', num.toString()], false, false);
num++;
return loop(newNode, num);
}
};
const bottleneck9 = await loop(bottleneck8, 2);
const bottleneck10 = await this.buildBottleneckV2_(
bottleneck9, ['3', '6']);
// Block 4
const bottleneck11 = await this.buildBottleneckV2_(
bottleneck10, ['4', '1'], true);
const bottleneck12 = await this.buildBottleneckV2_(
bottleneck11, ['4', '2'], false, false);
const bottleneck13 = await this.buildBottleneckV2_(
bottleneck12, ['4', '3'], false, false);
const fusedBn =
await this.buildFusedBatchNorm_(bottleneck13, ['postnorm']);
const mean = this.builder_.averagePool2d(fusedBn, {layout});
const conv2 = await this.buildConv_(
mean, ['', '', 'logits'], {autoPad}, false);
const reshape = this.builder_.reshape(conv2, [1, 1001]);
return this.builder_.softmax(reshape);
}
async build(outputOperand) {
this.graph_ = await this.builder_.build({'output': outputOperand});
}
// Release the constant tensors of a model
dispose() {
// dispose() is only available in webnn-polyfill
if (this.graph_ !== null && 'dispose' in this.graph_) {
this.graph_.dispose();
}
}
async compute(inputBuffer, outputBuffer) {
const inputs = {'input': inputBuffer};
const outputs = {'output': outputBuffer};
const results = await this.context_.compute(this.graph_, inputs, outputs);
return results;
}
}