opData.es6 18.4 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
    'output': 'out',
    'out': 'out',
    'scale': 'scale',
    'bias': 'bias',
    'mean': 'mean',
54 55
    'variance': 'variance',
    'w': 'weight'
W
wangqun 已提交
56 57 58 59 60
};
// unique behavior
const opBehavior = {
    conv2d: [
        'needBatch',
61
        'adaptPaddings',
62 63
        'isApplySeparableConv',
        'batchComputeConv2d'
W
wangqun 已提交
64
    ],
W
wangqun 已提交
65
	conv2d_transpose: [
66 67
        'needBatch',
        // 'adaptPaddings'
W
wangqun 已提交
68
	],
W
wangqun 已提交
69 70 71 72 73
    batchnorm: [
        'needBatch',
        'mergeTensor'
    ],
    elementwise_add: [
W
wangqun 已提交
74 75
		'processAxis',
        'needBatch'
W
wangqun 已提交
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
    ],
    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 已提交
103
    ],
W
wangqun 已提交
104 105 106 107
    bilinear_interp:[
        'needBatch'
    ],
	reshape2: [
W
wangqun 已提交
108 109 110
		'needBatch',
		'inferShape'
	],
W
wangqun 已提交
111
	transpose2: [
W
wangqun 已提交
112 113 114 115 116 117 118
		'needBatch',
		'setPerm'
	],
    concat: [
        'normalizeDim',
        'needBatch'
    ],
119 120 121 122 123 124
    concat_mul: [
        'needBatch',
        'processDim',
        'normalizeDim',
        'normalizeDim2',
    ],
W
wangqun 已提交
125 126 127
    split: [
        'normalizeDim',
        'needBatch'
W
wangqun 已提交
128 129
    ],
    softmax: [
W
wangqun 已提交
130 131 132 133 134
        'needBatch'
    ],
    scale: [
        'needBatch'
    ],
135 136 137 138
    fc: [
        'flattenShape',
        'needBatch'
    ]
W
wangqun 已提交
139 140
};
const mergeType = 'conv2d-elementwise_add';
W
wangqun 已提交
141

W
wangqun 已提交
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
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',
159 160
                'bias_value': '0.0',
                'fuse_relu': false
W
wangqun 已提交
161
            };
W
wangqun 已提交
162

W
wangqun 已提交
163
            // tensor数据
W
wangqun 已提交
164 165 166
            this.inputTensors = [];
            this.outputTensors = [];
            this.fShaderParams = [];
W
wangqun 已提交
167
            this.buildTensor();
W
wangqun 已提交
168
            this.buildShaderParams();
W
wangqun 已提交
169 170 171
        }
    }

172 173 174 175 176 177 178 179 180 181 182 183 184
    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 已提交
185
    inferShape(){
W
wangqun 已提交
186
		if (this.name == 'reshape2'){
187 188 189 190 191 192 193
            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 已提交
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
			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 已提交
219
    buildTensor() {
W
wangqun 已提交
220

W
wangqun 已提交
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
        // 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 已提交
243 244 245 246
                    data.forEach(item => {
                        item.tensorName = tensorName[key.toLowerCase()];
                        tensorData.push(item);
                    });
W
wangqun 已提交
247 248 249 250 251 252 253 254
                }
            }
        }
        // unique behavior
        const behavior = opBehavior[this.name] || [];
        behavior.forEach(behavior => {
            this[behavior](tensorData);
        });
W
wangqun 已提交
255

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

                if (tensorName === 'out') {
                    this.outputTensors.push(tensor);
                }
                else {
                    this.inputTensors.push(tensor);
                }
W
wangqun 已提交
285 286 287 288
            }
        });
    }

W
wangqun 已提交
289
    buildShaderParams() {
W
wangqun 已提交
290 291 292 293
        // 计算属性
        for (let key in this.attrs) {
            if (this.attrs.hasOwnProperty(key)) {
                const item = this.attrs[key];
W
wangqun 已提交
294 295 296
                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 已提交
297 298 299 300 301 302 303 304 305 306
                } else {
                    this.data[key] = item;
                    // 获取shader所需的数据
                    let shaderAttr = shaderAttrs[this.name];
                    if (shaderAttr && shaderAttr.hasOwnProperty(key)) {
                        this.data[shaderAttr[key]] = item;
                    }
                }
            }
        }
W
wangqun 已提交
307 308
        // 遍历 获取input tensor的数据
        this.inputTensors.forEach(inputTensor => {
W
wangqun 已提交
309
            tensorAttrs.forEach(attr => {
W
wangqun 已提交
310
                this.data[attr+ '_' + inputTensor.name] = inputTensor[attr];
W
wangqun 已提交
311
            });
W
wangqun 已提交
312 313 314 315 316 317
        });

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

W
wangqun 已提交
319 320 321 322 323 324
            tensorAttrs.forEach(attr => {
                params[attr+ '_' + outTensor.name] = outTensor[attr];
            });
            this.fShaderParams.push(params);
        });

W
wangqun 已提交
325 326 327 328 329 330
    }

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

W
wangqun 已提交
331
	setPerm(tensorData = []){
W
wangqun 已提交
332
		let arrayPerm = this.attrs['axis'];
W
wangqun 已提交
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
		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 已提交
368 369 370 371 372 373 374 375 376 377 378 379 380 381
    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 已提交
382

W
wangqun 已提交
383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398
    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;
399 400
        let hasBias = false;
        let outC;
W
wangqun 已提交
401
        const filter = tensorData.filter(item => {
402 403 404 405 406 407 408 409 410
            const {shape, tensorName} = item;
            if (tensorName === 'bias') {
                hasBias = true;
            }
            const [b, c, h, w] = shape;
            if (!hasBias && !outC && tensorName === 'out') {
                outC = c;
            }

W
wangqun 已提交
411 412 413 414 415 416
            return (b === groups) && (c === 1) && (item.tensorName === 'filter');
        });
        if (filter && filter.length) {
            // 可以执行separable conv
            this.name += '_depthwise';
        }
417 418 419 420 421 422 423 424 425

        !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 已提交
426 427
    }

428 429 430 431 432 433 434
    batchComputeConv2d() {
        let origin_shape_temp = this.input.Filter[0].shape;
        let inChannels = origin_shape_temp[1];
        this.attrs.filter_nearest_vec4 = Math.floor(inChannels / 4) * 4;
        this.attrs.filter_remainder_vec4 = inChannels % 4;
    }

W
wangqun 已提交
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
    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 已提交
498
    normalizeDim() {
W
wangqun 已提交
499 500 501 502 503 504 505 506 507
        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 已提交
508 509 510 511 512 513 514 515
        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 的长度
516
        this.attrs.inputs_dim = origin_shape[axis];
W
wangqun 已提交
517 518
        this.attrs.dim = 4 - origin_shape.length + axis;
    }
519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541
    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 已提交
542 543 544

    processAxis() {
		let shape_x = this.input.X[0].shape;
W
wangqun 已提交
545 546 547 548 549 550 551 552
        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 已提交
553 554
	}

555 556 557 558 559 560 561 562 563
    flattenShape(tensorData = []) {
        const target = tensorData.find(item => item.shape.length > 2);
        if (target) {
            const padShape = Utils.padToFourDimShape(target.shape);
            target.shape = [padShape[0] * padShape[2], padShape[1] * padShape[3]];
        }

    }

W
wangqun 已提交
564
    reshape(tensorData = []) {
565 566 567 568
        const input = tensorData.find(item => item.tensorName === 'origin');
        const counter = tensorData.find(item => item.tensorName === 'counter');
        const out = tensorData.find(item => item.tensorName === 'out' || item.tensorName === 'output');

W
wangqun 已提交
569
        if (counter.shape.length > input.shape.length) {
570 571
            input = counter;
            counter = input;
W
wangqun 已提交
572 573
        }
        if (input.shape.length > 2 && counter.shape.length === 2) {
574
            let shape = Utils.getReshapeInPaddle(input.shape, counter.shape, out.shape);
W
wangqun 已提交
575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590
            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 已提交
591 592 593 594 595 596
     //   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 已提交
597

W
wangqun 已提交
598
        // tensorData[result[constants[0] + 'Index']].data = data;
W
wangqun 已提交
599 600 601 602
        for (let i = 0; i < constants.length; i++){
            tensorData[result[constants[i] + 'Index']].data = result[constants[i]].data;
        }
        // 充分利用shader空间
W
wangqun 已提交
603 604 605 606 607
        //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 已提交
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
    }

    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 = {};
    }
}