opData.es6 17.6 KB
Newer Older
W
wangqun 已提交
1 2 3
/* eslint-disable */
import Utils from './utils';
import Tensor from './tensor';
4

W
wangqun 已提交
5 6
/**
 * @file op的数据对象
W
wangqun 已提交
7
 * @author yangmingming
W
wangqun 已提交
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
 *
 */
const keys = [
    'paddings',
    'strides',
    'dilations',
    'ksize'
];
// 从tensor对象中获取的数据
const tensorAttrs = [
    'length_shape',
    'width_shape',
    'height_shape',
    'width_texture',
    'height_texture',
    'offset_x',
    'offset_y',
    'limit',
    'channel',
    'total_shape'
];
// shader中需要的常量
const shaderAttrs = {
    scale: {
        'bias': 'bias_value',
        'scale': 'multi_value'
    },
    pool2d: {
        'pooling_type': 'type_pool'
    },
    pool2d_winograd: {
        'pooling_type': 'type_pool'
    }
};
// model的名字和paddleJS的tensor名字mapping
const tensorName = {
    'input': 'origin',
    'x': 'origin',
    'filter': 'filter',
    'y': 'counter',
48
    'z': 'appender',
W
wangqun 已提交
49 50 51 52 53 54 55 56 57 58 59
    'output': 'out',
    'out': 'out',
    'scale': 'scale',
    'bias': 'bias',
    'mean': 'mean',
    'variance': 'variance'
};
// unique behavior
const opBehavior = {
    conv2d: [
        'needBatch',
60
        'adaptPaddings',
W
wangqun 已提交
61 62
        'isApplySeparableConv'
    ],
W
wangqun 已提交
63
	conv2d_transpose: [
64 65
        'needBatch',
        // 'adaptPaddings'
W
wangqun 已提交
66
	],
W
wangqun 已提交
67 68 69 70 71
    batchnorm: [
        'needBatch',
        'mergeTensor'
    ],
    elementwise_add: [
W
wangqun 已提交
72 73
		'processAxis',
        'needBatch'
W
wangqun 已提交
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
    ],
    conv2d_elementwise_add: [
        'mergeAttrs',
        'setActiveFunc',
        'needBatch'
    ],
    pool2d: [
        'isMax',
        'needBatch',
        'setPacked',
        'isGlobalPooling'
    ],
    relu: [
        'transToPrelu',
        'needBatch'
    ],
    relu6: [
        'transToRelu6',
        'needBatch'
    ],
    leaky_relu: [
        'transToLeakyrelu',
        'needBatch'
    ],
    mul: [
        'reshape',
        'needBatch'
W
wangqun 已提交
101
    ],
W
wangqun 已提交
102 103 104 105
    bilinear_interp:[
        'needBatch'
    ],
	reshape2: [
W
wangqun 已提交
106 107 108
		'needBatch',
		'inferShape'
	],
W
wangqun 已提交
109
	transpose2: [
W
wangqun 已提交
110 111 112 113 114 115 116
		'needBatch',
		'setPerm'
	],
    concat: [
        'normalizeDim',
        'needBatch'
    ],
117 118 119 120 121 122
    concat_mul: [
        'needBatch',
        'processDim',
        'normalizeDim',
        'normalizeDim2',
    ],
W
wangqun 已提交
123 124 125
    split: [
        'normalizeDim',
        'needBatch'
W
wangqun 已提交
126 127
    ],
    softmax: [
W
wangqun 已提交
128 129 130 131 132
        'needBatch'
    ],
    scale: [
        'needBatch'
    ],
W
wangqun 已提交
133 134
};
const mergeType = 'conv2d-elementwise_add';
W
wangqun 已提交
135

W
wangqun 已提交
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
export default class OpData {
    constructor(name, input = {}, output = {}, attrs = {}) {
        this.realName = name;
        this.name = name;
        this.attrs = attrs;
        // 检查是否是融合op
        this.checkIsMerge();
        // 是否忽略当前当前op, 使用dropout
        // dropout是指在深度学习网络的训练过程中,对于神经网络单元,按照一定的概率将其暂时从网络中丢弃。
        this.isPass = this.checkIsPass();
        if (this.isPass) {
            this.input = input;
            this.output = output;
            // op数据, 当前不扩展
            this.data = {
                'active_function': 'scale',
                'multi_value': '1.0',
153 154
                'bias_value': '0.0',
                'fuse_relu': false
W
wangqun 已提交
155
            };
W
wangqun 已提交
156

W
wangqun 已提交
157
            // tensor数据
W
wangqun 已提交
158 159 160
            this.inputTensors = [];
            this.outputTensors = [];
            this.fShaderParams = [];
W
wangqun 已提交
161
            this.buildTensor();
W
wangqun 已提交
162
            this.buildShaderParams();
W
wangqun 已提交
163 164 165
        }
    }

166 167 168 169 170 171 172 173 174 175 176 177 178
    adaptPaddings() {
        for (let key in this.attrs) {
            if (this.attrs.hasOwnProperty(key) && key === 'paddings') {
                const item = this.attrs[key];
                const [x, y] = item;
                if (x === 0 && y === 1) {
                    // 兼容paddings为[0, 1]的情况
                    this.attrs[key][1] = 0;
                }
                return;
            }
        }
    }
W
wangqun 已提交
179
    inferShape(){
W
wangqun 已提交
180
		if (this.name == 'reshape2'){
181 182 183 184 185 186 187
            let inputShape = this.input.X[0].shape;
            // 把shape变更为new_shape
            if (this.attrs.shape) {
                this.attrs.new_shape = this.attrs.shape;
                delete this.attrs.shape;
            }

W
wangqun 已提交
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
			let targetShape = this.attrs.new_shape;
			for (let i = 0; i < targetShape.length; i++){
				if (targetShape[i] == 0) {
					targetShape[i] = inputShape[i];
            	}
        	}
			let total_length = 1;
			for (let j = 0;j < inputShape.length; j++){
				total_length *= inputShape[j];
			}
			let minusPos = -1;
			for (let i = 0; i < targetShape.length; i++){
				if (targetShape[i] == -1) {
					minusPos = i;
					continue;
            	}
            	total_length /= targetShape[i];
        	}
        	if (minusPos != -1) {
				targetShape[minusPos] = total_length;
			}
			this.output.Out[0].shape = targetShape;
		}
	}

W
wangqun 已提交
213
    buildTensor() {
W
wangqun 已提交
214

W
wangqun 已提交
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
        // todo: 是否需要形状对齐
        // todo: 是否需要广播tensor
        const tensorData = [];
        for (let key in this.input) {
            if (this.input.hasOwnProperty(key)) {
                const data = this.input[key] || [{}];
                // 默认取第一个数据
                if (tensorName[key.toLowerCase()]) {
                    data[0].tensorName = tensorName[key.toLowerCase()];
                    tensorData.push(data[0]);
                }
            }
        }
        // debugger
        // todo: 临时删除output里的Y
        delete this.output.Y;
        // 输出tensor
        for (let key in this.output) {
            if (this.output.hasOwnProperty(key)) {
                // 默认取第一个数据
                const data = this.output[key] || [{}];
                if (tensorName[key.toLowerCase()]) {
W
wangqun 已提交
237 238 239 240
                    data.forEach(item => {
                        item.tensorName = tensorName[key.toLowerCase()];
                        tensorData.push(item);
                    });
W
wangqun 已提交
241 242 243 244 245 246 247 248
                }
            }
        }
        // unique behavior
        const behavior = opBehavior[this.name] || [];
        behavior.forEach(behavior => {
            this[behavior](tensorData);
        });
W
wangqun 已提交
249

W
wangqun 已提交
250 251 252
        // 生成tensor对象
        tensorData.forEach(data => {
            if (data) {
W
wangqun 已提交
253 254
                let tensor = null;
                const tensorName = data.tensorName;
W
wangqun 已提交
255
                if (data.notTensor) {
W
wangqun 已提交
256 257
                    tensor = {
                        name: tensorName,
W
wangqun 已提交
258 259 260 261
                        data: new Float32Array(data.data),
                        total_shape: data.data.length
                    };
                } else {
W
wangqun 已提交
262
                    tensor = new Tensor({
W
wangqun 已提交
263
                        type: data.name,
W
wangqun 已提交
264
                        name: tensorName,
W
wangqun 已提交
265 266 267 268 269 270 271
                        shape: data.shape,
                        data: data.data,
                        needBatch: data.needBatch || false,
                        notCompressed: data.notCompressed || false,
                        isPacked: data.isPacked || false
                    });
                }
W
wangqun 已提交
272 273 274 275 276 277 278

                if (tensorName === 'out') {
                    this.outputTensors.push(tensor);
                }
                else {
                    this.inputTensors.push(tensor);
                }
W
wangqun 已提交
279 280 281 282
            }
        });
    }

W
wangqun 已提交
283
    buildShaderParams() {
W
wangqun 已提交
284 285 286 287
        // 计算属性
        for (let key in this.attrs) {
            if (this.attrs.hasOwnProperty(key)) {
                const item = this.attrs[key];
W
wangqun 已提交
288 289 290
                if (Object.prototype.toString.call(item) === '[object Array]' && keys.indexOf(key) > -1) {
                    this.data[key + '_x'] = item[0];
                    this.data[key + '_y'] = item[1];
W
wangqun 已提交
291 292 293 294 295 296 297 298 299 300
                } else {
                    this.data[key] = item;
                    // 获取shader所需的数据
                    let shaderAttr = shaderAttrs[this.name];
                    if (shaderAttr && shaderAttr.hasOwnProperty(key)) {
                        this.data[shaderAttr[key]] = item;
                    }
                }
            }
        }
W
wangqun 已提交
301 302
        // 遍历 获取input tensor的数据
        this.inputTensors.forEach(inputTensor => {
W
wangqun 已提交
303
            tensorAttrs.forEach(attr => {
W
wangqun 已提交
304
                this.data[attr+ '_' + inputTensor.name] = inputTensor[attr];
W
wangqun 已提交
305
            });
W
wangqun 已提交
306 307 308 309 310 311
        });

        // 根据out tensor 个数 生成对应的 fShader 个数
        this.outputTensors.forEach(outTensor => {
            const params = JSON.parse(JSON.stringify(this.data));
            // 获取output tensor的数据
W
wangqun 已提交
312

W
wangqun 已提交
313 314 315 316 317 318
            tensorAttrs.forEach(attr => {
                params[attr+ '_' + outTensor.name] = outTensor[attr];
            });
            this.fShaderParams.push(params);
        });

W
wangqun 已提交
319 320 321 322 323 324
    }

    needBatch(tensorData = []) {
        tensorData.forEach(data => (data.needBatch = true));
    }

W
wangqun 已提交
325
	setPerm(tensorData = []){
W
wangqun 已提交
326
		let arrayPerm = this.attrs['axis'];
W
wangqun 已提交
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
		let l = arrayPerm.length;
		if (l == 3) {
			if (arrayPerm == [2,0,1]) {
				arrayPerm = [1,2,0];
		}
			else if (arrayPerm == [1,2,0]){
				arrayPerm = [2,0,1];
		}
		}
		else if (l == 4){
			let temp = [0,0,0,0];
			for (let i = 0; i < 4; i++){
				temp[[arrayPerm[i]]] = i;
			}
			arrayPerm = temp;
		}
		this.data['perm_0'] = 0;
		this.data['perm_1'] = 0;
		this.data['perm_2'] = 0;
		this.data['perm_3'] = 0;
		if (l >= 1) {
			this.data['perm_0'] = arrayPerm[0];
		}
		if (l >= 2) {
			this.data['perm_1'] = arrayPerm[1];
		}
		if (l >= 3) {
			this.data['perm_2'] = arrayPerm[2];
		}
		if (l >= 4) {
			this.data['perm_3'] = arrayPerm[3];
		}
		this.data['perm_size'] = l;
	}

W
wangqun 已提交
362 363 364 365 366 367 368 369 370 371 372 373 374 375
    isGlobalPooling(tensorData = []) {
        let counter = tensorData.filter(tensor => (tensor.tensorName === 'origin'))[0] || {};
        let length = counter.shape && counter.shape.length || 0;
        if (length > 2 && this.attrs['global_pooling']) {
            this.attrs.ksize = [counter.shape[length - 2], counter.shape[length - 1]];
        }
    }

    mergeAttrs() {
        this.attrs = this.attrs.reduce((attrs, item) => {
            return Object.assign(attrs, item);
        }, {});
    }

W
wangqun 已提交
376

W
wangqun 已提交
377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392
    isApplyWinoGrad(tensorData = []) {
        const filter = tensorData.filter(item => {
            const [b, c, h, w] = item.shape;
            return (h === 3) && (w === 3) && (item.tensorName === 'filter');
        });
        // 使用winograd算法
        if (filter && filter.length) {
            this.setPacked(tensorData);
            this.applyWinograd(tensorData);
            this.setOutputPacked(tensorData);
            this.name += '_winograd';
        }
    }

    isApplySeparableConv(tensorData = []) {
        const groups = this.attrs.groups;
393 394
        let hasBias = false;
        let outC;
W
wangqun 已提交
395
        const filter = tensorData.filter(item => {
396 397 398 399 400 401 402 403 404
            const {shape, tensorName} = item;
            if (tensorName === 'bias') {
                hasBias = true;
            }
            const [b, c, h, w] = shape;
            if (!hasBias && !outC && tensorName === 'out') {
                outC = c;
            }

W
wangqun 已提交
405 406 407 408 409 410
            return (b === groups) && (c === 1) && (item.tensorName === 'filter');
        });
        if (filter && filter.length) {
            // 可以执行separable conv
            this.name += '_depthwise';
        }
411 412 413 414 415 416 417 418 419

        !hasBias && tensorData.push({
            name: "conv1_scale_offset",
            needBatch: true,
            persistable: true,
            shape: [outC],
            data: Array.from(new Float32Array(outC), i => 0),
            tensorName: "bias"
        });
W
wangqun 已提交
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
    }

    setPacked(tensorData = []) {
        const isPacked = this.attrs.ispacked;
        tensorData.forEach(item => {
            if (item.tensorName === 'origin' && isPacked) {
                item.isPacked = true;
                if (this.name.indexOf('pool') > -1) {
                    this.name += '_winograd';
                }
            }
        });
    }

    applyWinograd(tensorData = []) {
        tensorData.forEach(item => {
            if (item.tensorName === 'filter') {
                const [b, c, h, w] = item.shape;
                item.shape = [b, c, 4, 4];
                item.data = Utils.applyFilterWinograd(item.data, item.shape);
            }
        });
    }

    setOutputPacked(tensorData = []) {
        tensorData.forEach(item => {
            if (item.tensorName === 'out') {
                item.isPacked = true;
            }
        });
    }

    isMax(tensorData = []) {
        const type = this.attrs['pooling_type'] === 'max' ? 1 : 0;
        this.attrs['pooling_type'] = type;
        if (type === 1) {
            this.name += '_max';
        }
    }

    transToPrelu(tensorData = []) {
        this.data['multi_value'] = '0.0';
        this.data['active_function'] = 'prelu';
    }

    transToRelu6(tensorData = []) {
        this.data['multi_value'] = this.attrs['threshold'];
        this.data['active_function'] = 'relu6';
    }

    transToLeakyrelu(tensorData = []) {
        this.data['multi_value'] = this.attrs.alpha;
        this.data['active_function'] = 'leakyRelu';
        this.name = 'relu';
    }

    setActiveFunc() {
        // 用于融合op
        const suffix = this.realName.replace(mergeType + '-', '');
        if (suffix === 'leaky_relu') {
            this.data['multi_value'] = this.attrs.alpha;
            this.data['active_function'] = 'leakyRelu';
        }
    }

W
wangqun 已提交
485
    normalizeDim() {
W
wangqun 已提交
486 487 488 489 490 491 492 493 494
        let origin_shape_temp = this.input.X[0].shape;
        if (origin_shape_temp.length < 4) {
            let batch = [];
            for (let i = 0; i < (4 - origin_shape_temp.length); i++) {
                batch.push(1);
            }
            origin_shape_temp = batch.concat(origin_shape_temp);
        }
        const origin_shape = origin_shape_temp;
W
wangqun 已提交
495 496 497 498 499 500 501 502
        const axis = this.attrs.axis > -1 ? this.attrs.axis : origin_shape.length + this.attrs.axis;
        const dim_value = [];
        for (let index = 0; index < origin_shape[axis]; index++) {
            dim_value[index] = index;
        }
        this.attrs.target_length = dim_value.length;
        this.attrs.target_value = dim_value;
        // 保存 输入 tensor 对应dim 的长度
503
        this.attrs.inputs_dim = origin_shape[axis];
W
wangqun 已提交
504 505
        this.attrs.dim = 4 - origin_shape.length + axis;
    }
506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528
    normalizeDim2() {
        let origin_shape_temp = this.input.Y[0].shape;
        if (origin_shape_temp.length < 4) {
            let batch = [];
            for (let i = 0; i < (4 - origin_shape_temp.length); i++) {
                batch.push(1);
            }
            origin_shape_temp = batch.concat(origin_shape_temp);
        }
        const origin_shape = origin_shape_temp;
        const axis = this.attrs.axis > -1 ? this.attrs.axis : origin_shape.length + this.attrs.axis;

        // 保存 输入 tensor 对应dim 的长度
        this.attrs.append_num = origin_shape[axis];
    }

    processDim() {
        const axis = this.attrs.axis;
        if (axis !== -1) {
            let shape = this.input.X[0].shape;
            this.attrs.axis += 4 - shape.length;
        }
    }
W
wangqun 已提交
529 530 531

    processAxis() {
		let shape_x = this.input.X[0].shape;
W
wangqun 已提交
532 533 534 535 536 537 538 539
        let shape_y = this.input.Y[0].shape;
        let axis_temp = this.attrs['axis'];
        if (axis_temp == -1) {
            this.attrs['axis'] = shape_x.length - shape_y.length;
        }
        else {
            this.attrs['axis'] = 4 - shape_y.length - axis_temp;
        }
W
wangqun 已提交
540 541
	}

W
wangqun 已提交
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
    reshape(tensorData = []) {
        let input = tensorData[0];
        let counter = tensorData[1];
        if (counter.shape.length > input.shape.length) {
            input = tensorData[1];
            counter = tensorData[0];
        }
        if (input.shape.length > 2 && counter.shape.length === 2) {
            let shape = Utils.getReshapeInPaddle(input.shape, counter.shape, tensorData[2].shape);
            input.shape = shape;
        }

    }

    mergeTensor(tensorData = []) {
        // 融合scale、bias、variance、mean

        let constants = ['scale', 'bias', 'variance', 'mean'];
        let result = {};
        let data = [];
        tensorData.forEach((tensor, index) => {
            result[tensor.tensorName] = tensor;
            result[tensor.tensorName + 'Index'] = index;
        });

W
wangqun 已提交
567 568 569 570 571 572
     //   for (let i = 0; i < result[constants[0]].shape[0]; i++) {
      //      data.push(result[constants[0]].data[i]);
      //      data.push(result[constants[1]].data[i]);
     //       data.push(result[constants[2]].data[i]);
      //      data.push(result[constants[3]].data[i]);
      //  }
W
wangqun 已提交
573

W
wangqun 已提交
574
        // tensorData[result[constants[0] + 'Index']].data = data;
W
wangqun 已提交
575 576 577 578
        for (let i = 0; i < constants.length; i++){
            tensorData[result[constants[i] + 'Index']].data = result[constants[i]].data;
        }
        // 充分利用shader空间
W
wangqun 已提交
579 580 581 582 583
        //tensorData[result[constants[0] + 'Index']].notCompressed = true;
       // tensorData[result[constants[0] + 'Index']].shape[0] *= 4;
        //tensorData.splice(result[constants[1] + 'Index'], 1, 0);
        //tensorData.splice(result[constants[2] + 'Index'], 1, 0);
        //tensorData.splice(result[constants[3] + 'Index'], 1, 0);
W
wangqun 已提交
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
    }

    checkIsMerge() {
        if (this.name.indexOf(mergeType) > -1
            && Object.prototype.toString.apply(this.attrs) === '[object Array]') {
            // 第一个融合op
            this.name  = 'conv2d_elementwise_add';
            return true;
        }
        return false;
    }

    checkIsPass() {
        if (this.name === 'dropout') {
            if (this.attrs['dropout_implementation'] === 'downgrade_in_infer') {
                this.name = 'scale';
                this.attrs['scale'] = this.attrs['dropout_prob'];
                this.attrs['bias'] = 0.0;
                return true;
            }
            return false;
        }
        if (this.name === 'depthwise_conv2d') {
            this.name = 'conv2d';
        }
        return true;
    }

    dispose() {
        this.input = null;
        this.output = null;
        this.attrs = null;
        for (let key in this.tensor) {
            this.tensor[key].dispose();
        }
        this.tensor = {};
    }
}