opData.es6 15.2 KB
Newer Older
W
wangqun 已提交
1 2 3 4 5
/* eslint-disable */
import Utils from './utils';
import Tensor from './tensor';
/**
 * @file op的数据对象
W
wangqun 已提交
6
 * @author yangmingming
W
wangqun 已提交
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
 *
 */
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',
    'output': 'out',
    'out': 'out',
    'scale': 'scale',
    'bias': 'bias',
    'mean': 'mean',
    'variance': 'variance'
};
// unique behavior
const opBehavior = {
    conv2d: [
        'needBatch',
        'isApplySeparableConv'
    ],
W
wangqun 已提交
60 61 62
	conv2d_transpose: [
		'needBatch'
	],
W
wangqun 已提交
63 64 65 66 67
    batchnorm: [
        'needBatch',
        'mergeTensor'
    ],
    elementwise_add: [
W
wangqun 已提交
68 69
        'needBatch',
		'processAxis'
W
wangqun 已提交
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
    ],
    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 已提交
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
    ],
	reshape: [
		'needBatch',
		'inferShape'
	],
	transpose: [
		'needBatch',
		'setPerm'
	],
    concat: [
        'normalizeDim',
        'needBatch'
    ],
    split: [
        'normalizeDim',
        'needBatch'
W
wangqun 已提交
113 114
    ],
    softmax: [
W
wangqun 已提交
115 116 117 118 119
        'needBatch'
    ],
    scale: [
        'needBatch'
    ],
W
wangqun 已提交
120 121
};
const mergeType = 'conv2d-elementwise_add';
W
wangqun 已提交
122

W
wangqun 已提交
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
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',
                'bias_value': '0.0'
            };
W
wangqun 已提交
142

W
wangqun 已提交
143
            // tensor数据
W
wangqun 已提交
144 145 146
            this.inputTensors = [];
            this.outputTensors = [];
            this.fShaderParams = [];
W
wangqun 已提交
147
            this.buildTensor();
W
wangqun 已提交
148
            this.buildShaderParams();
W
wangqun 已提交
149 150 151
        }
    }

W
wangqun 已提交
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
    inferShape(){
		if (this.name == 'reshape'){
			let inputShape = this.input.X[0].shape;
			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 已提交
180
    buildTensor() {
W
wangqun 已提交
181

W
wangqun 已提交
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
        // 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 已提交
204 205 206 207
                    data.forEach(item => {
                        item.tensorName = tensorName[key.toLowerCase()];
                        tensorData.push(item);
                    });
W
wangqun 已提交
208 209 210 211 212 213 214 215
                }
            }
        }
        // unique behavior
        const behavior = opBehavior[this.name] || [];
        behavior.forEach(behavior => {
            this[behavior](tensorData);
        });
W
wangqun 已提交
216

W
wangqun 已提交
217 218 219
        // 生成tensor对象
        tensorData.forEach(data => {
            if (data) {
W
wangqun 已提交
220 221
                let tensor = null;
                const tensorName = data.tensorName;
W
wangqun 已提交
222
                if (data.notTensor) {
W
wangqun 已提交
223 224
                    tensor = {
                        name: tensorName,
W
wangqun 已提交
225 226 227 228
                        data: new Float32Array(data.data),
                        total_shape: data.data.length
                    };
                } else {
W
wangqun 已提交
229
                    tensor = new Tensor({
W
wangqun 已提交
230
                        type: data.name,
W
wangqun 已提交
231
                        name: tensorName,
W
wangqun 已提交
232 233 234 235 236 237 238
                        shape: data.shape,
                        data: data.data,
                        needBatch: data.needBatch || false,
                        notCompressed: data.notCompressed || false,
                        isPacked: data.isPacked || false
                    });
                }
W
wangqun 已提交
239 240 241 242 243 244 245

                if (tensorName === 'out') {
                    this.outputTensors.push(tensor);
                }
                else {
                    this.inputTensors.push(tensor);
                }
W
wangqun 已提交
246 247 248 249
            }
        });
    }

W
wangqun 已提交
250
    buildShaderParams() {
W
wangqun 已提交
251 252 253 254
        // 计算属性
        for (let key in this.attrs) {
            if (this.attrs.hasOwnProperty(key)) {
                const item = this.attrs[key];
W
wangqun 已提交
255 256 257
                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 已提交
258 259 260 261 262 263 264 265 266 267
                } else {
                    this.data[key] = item;
                    // 获取shader所需的数据
                    let shaderAttr = shaderAttrs[this.name];
                    if (shaderAttr && shaderAttr.hasOwnProperty(key)) {
                        this.data[shaderAttr[key]] = item;
                    }
                }
            }
        }
W
wangqun 已提交
268 269
        // 遍历 获取input tensor的数据
        this.inputTensors.forEach(inputTensor => {
W
wangqun 已提交
270
            tensorAttrs.forEach(attr => {
W
wangqun 已提交
271
                this.data[attr+ '_' + inputTensor.name] = inputTensor[attr];
W
wangqun 已提交
272
            });
W
wangqun 已提交
273 274 275 276 277 278 279 280 281 282 283 284
        });

        // 根据out tensor 个数 生成对应的 fShader 个数
        this.outputTensors.forEach(outTensor => {
            const params = JSON.parse(JSON.stringify(this.data));
            // 获取output tensor的数据
            tensorAttrs.forEach(attr => {
                params[attr+ '_' + outTensor.name] = outTensor[attr];
            });
            this.fShaderParams.push(params);
        });

W
wangqun 已提交
285 286 287 288 289 290
    }

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

W
wangqun 已提交
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
	setPerm(tensorData = []){
		let arrayPerm = this.attrs['perm'];
		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 已提交
328 329 330 331 332 333 334 335 336 337 338 339 340 341
    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 已提交
342

W
wangqun 已提交
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
    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;
        const filter = tensorData.filter(item => {
            const [b, c, h, w] = item.shape;
            return (b === groups) && (c === 1) && (item.tensorName === 'filter');
        });
        if (filter && filter.length) {
            // 可以执行separable conv
            this.name += '_depthwise';
        }
    }

    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 已提交
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
    normalizeDim() {
        const origin_shape = this.input.X[0].shape;
        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 的长度
        this.attrs.inputs_dim = [origin_shape[axis]];
        this.attrs.dim = 4 - origin_shape.length + axis;
    }

    processAxis() {
		let shape_x = this.input.X[0].shape;
		let shape_y = this.input.Y[0].shape;
		let y_length = shape_y.length;
		for (let i = shape_y.length - 1; i >=0 ;i--){
			if (shape_y[i] == 1) {
				y_length -= 1;
			}
		}
		let axis_temp = this.attrs['axis'];
		if (axis_temp == -1) {
			this.attrs['axis'] = shape_x.length - y_length;
		}
		this.attrs['shape_length_origin'] = shape_x.length;
		this.attrs['shape_length_counter'] = y_length;
	}

W
wangqun 已提交
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
    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 已提交
488 489 490 491 492 493
     //   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 已提交
494

W
wangqun 已提交
495
        // tensorData[result[constants[0] + 'Index']].data = data;
W
wangqun 已提交
496 497 498 499
        for (let i = 0; i < constants.length; i++){
            tensorData[result[constants[i] + 'Index']].data = result[constants[i]].data;
        }
        // 充分利用shader空间
W
wangqun 已提交
500 501 502 503 504
        //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 已提交
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
    }

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