graph.es6 11.7 KB
Newer Older
W
wangqun 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/* eslint-disable */
import GraphExecutor from '../executor/executor';
import IO from '../feed/imageFeed';
import Runtime from '../runtime/runtime';
import OpData from '../utils/opData';
import Factory from '../factory/fshader/factory';
import Utils from '../utils/utils';

/**
 * @file Graph,绘制生成model网络
 * @author wangqun@baidu.com
 */
// 生成factory实例
const factory = new Factory({});
// 获取op的输入配置
const opConfs = factory.getOpConfs();
W
wangqun 已提交
17
let opindex = 0;
W
wangqun 已提交
18 19 20 21 22 23 24 25 26 27 28 29 30

export default class Graph {
    constructor(options) {
        this.version  = '0.0.1';
        this.handler = 'io.IOHandler';
        this.weightMap = '';
        this.options = options || {};
        // feed数据
        this.feed = null;
        this.index = 0;
        this.feedOp = null;
        this.feedItem = null;
        this.test = false;
W
wangqun 已提交
31
        this.formatLayout = 'NCHW';
W
wangqun 已提交
32 33 34 35
        this.isExecuted = false;
        // 网络层数
        this.iLayer = 0;

W
wangqun 已提交
36 37 38 39 40 41 42 43
        if (this.options && this.options.options ) {
            if (this.options.options.test === true) {
                this.test = true;
            }
            if (this.options.options.formatLayout) {
                this.formatLayout = this.options.options.formatLayout;
            }

W
wangqun 已提交
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
        }

        if (!this.inst) {
            // op runner
            this.inst = Runtime.init();
            factory.setWebglVersion(this.inst.getWebglVersion());

        }
    }

    buildOpData(op) {
        const executor = this.constructExecutor(op);
        const opData = new OpData(op.type, executor.inputs, executor.outputs, executor.attrs);
        const name = opData.name;

W
wangqun 已提交
59 60 61 62 63 64
        opData.program = [];
        opData.program = opData.outputTensors.map((outTensor, index) => {
            const fsCode = factory.buildShader(name, opData.fShaderParams[index], index);
            return this.inst.createProgram(fsCode, outTensor);
        });

W
wangqun 已提交
65 66
        opData.renderData = opConfs[name].map(elem => {
            let item = Object.assign({}, elem);
W
wangqun 已提交
67
            const tensorData = opData.inputTensors.find(tensor => tensor.name === item.tensor);
W
wangqun 已提交
68
            if (item.type === 'texture') {
W
wangqun 已提交
69
                item.tensorId = tensorData.opts.type;
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
                item.data = tensorData.data;
                if (this.feedOp.id === op.id && item.tensor === 'origin') {
                    item.shape = tensorData.shape;
                    this.feedItem = item;
                }
                item['width_texture'] = tensorData['width_texture'];
                item['height_texture'] = tensorData['height_texture'];
                item['channel'] = tensorData['channel'];
            } else if (item.type === 'uniform') {
                item.data = tensorData[item.variable];
            }
            return item;
        });
        // console.timeEnd('opData.renderData');
        opData.iLayer = this.iLayer++;
        op.opData = opData;
        // delete op.inputs;
        // delete op.outputs;
        // delete op.attrs;
    }
    execute_(executor) {
        if (executor.type === 'fetch') {
            return;
        }
W
wangqun 已提交
94 95 96
        opindex++;
        // console.log(opindex);
        //if (executor.opData) console.log(executor.opData.iLayer);
W
wangqun 已提交
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
        executor.execute(this.inst, this.isExecuted);
        if (executor.next) {
            const id = executor.next;
            const next = this.getTensor(id);
            this.execute_(next[0]);
        }
    }
    /**
     * Executes inference for the model for given input tensors.
     * @param inputs
     * @param outputs
     * @returns {*}
     */
    execute(inputs) {
        this.feed = inputs;
        const executor = this.getNetsStart(this.weightMap);
        if (!this.inst) {
            this.inst = Runtime.init({
                'width_raw_canvas': 512,
                'height_raw_canvas': 512
            });
        }
        if (this.isExecuted) {
            this.updateFeed();
        }
        this.execute_(executor[0]);
        this.isExecuted = true;
        return this.inst;
    }
    updateFeed() {
        this.feedItem.data = this.feed.input[0].data;
        // Utils.img2texture(this.feedItem);
    }
    /**
     * predict enter
     * @param inputs
     * @param config
     */
    predict(inputs, config) {
        return this.execute_(inputs, true, this.outputNodes);
    }
    getTensorAttr(name) {
        return this.data.vars.filter((item, i) => {
            if (name === item.name)
            return item;
        });
    }
    constructExecutor(executor) {
        let that = this;
        const inputName = executor.inputsName[0];
        const input = executor.inputs;
        const output = executor.outputs;
        Object.keys(output).forEach(function(key){
W
wangqun 已提交
150 151 152
            output[key].forEach((item, index) => {
                output[key][index] = that.getTensorAttr(item)[0];
            });
W
wangqun 已提交
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
        });
        Object.keys(input).forEach(function(key){
            if (that.test && ((key === 'Input') || (key === 'X'))) {
                input[key] = that.getTensorAttr(input[key][0]);
                that.feedOp = executor;
            }
            else if ((key === 'Input') && (inputName === 'pixel')) {
                // const pixel = that.getTensorAttr(inputName);
                // const io = new IO();
                // input[key] = io.fromPixels(that.feed, pixel);
                input[key] = that.feed.input;

                that.feedOp = executor;
            }
            else if ((key === 'Input') && (inputName === 'image' || inputName === 'x')) {
                // that.feed.input[0].data = that.testData;
                input[key] = that.feed.input;

                that.feedOp = executor;
            }
            else {
                input[key] = that.getTensorAttr(input[key][0]);
            }
        });
        // console.log(input);
        return {
            inputs: input,
            outputs: output,
            attrs: executor.attrs,
            type: executor.type,
            next: executor.next
        };
    }
    /**
     * Construct Ops Relationship
     * @param ops
     * @returns {*}
     */
    constructOpsMap(ops) {
        return ops.map((item, idx) => {
            const outputsName = item.outputsName[0];
            const next = this.getNextExecutor(ops, outputsName);
            if (next.length > 0) {
                item.next = next[0].id;
            }
            return item;
        });
    }
W
wangqun 已提交
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

    execute_try(temp, ops, idtoindex, executed, inline, prev){
        console.log('execute_try!first look at this op');
        console.log(ops[temp]);
        let canrun = this.checkifcanrun(temp, ops, idtoindex, executed);
        if (canrun === false) {
            // console.log('canrun === false!');
            var a = inline.pop();
            this.execute_try(idtoindex[a.id], ops, idtoindex, executed, inline, prev);
            return;
        }
        if (prev >=0) {
            ops[prev].next = ops[temp].id;
        }
        ops[temp].outputsName.forEach(function(item, index) {
            executed[item] = true;
        })
        let next = this.getNextByOp(ops, ops[temp]);
        // console.log('this is its next:');
        // console.dir(next);
        while (next.length === 1) {
            let flag = true;
            for (let i = 0; i < next[0].inputsName.length; i++){
                if (executed[next[0].inputsName[i]] === false) flag = false;
            }
            if (flag === false) {
                // console.log('can not execute next now! jump to another op:');

                if (inline.length === 0) return;
                prev = temp;
                let a = inline.pop();
                // console.dir(a);
                ops[temp].next = a.id;
                temp = idtoindex[a.id];
                this.execute_try(temp, ops, idtoindex, executed, inline, prev);
                return;
            }
            else {
                // console.log('now execute next op! it is');
                ops[temp].next = next[0].id;
                temp = idtoindex[next[0].id];
                // console.dir(ops[temp]);
                next = this.getNextByOp(ops, ops[temp]);
                // console.log('its next is: ');
                ops[temp].outputsName.forEach(function(item, index) {
                    executed[item] = true;
                })
                // console.dir(next);
            }
        }
        if (next.length > 1){
            // console.log('next.length > 1!!!');
            for (let i = next.length - 1; i >=0 ; i--){
                 inline.push(next[i]);
            }

            var a = inline.pop();
            this.execute_try(idtoindex[a.id], ops, idtoindex, executed, inline, temp);
        }
        return;
    }


    arrangeMap(ops) {
        // console.log('arrangeMap!');
        // console.dir(ops);
        var idtoindex = {};
        var executed = {};
        var inline = [];
        let temp = 0;
        // console.log('graph ops:');
        // console.dir(ops);
        let ops1 = ops;
        ops1.forEach(function(item, index) {
            idtoindex[item.id] = index;
            // console.dir(item);
            item.outputsName.forEach(function(i, idx){
                executed[i] = false;
            })
        });

        //ops[0].inputsName[0] = {name : "feed"};
       // ops[0].outputsName[0] = {name : "image"};
        this.execute_try(temp, ops, idtoindex, executed, inline, -1);
        return ops;
    }

    checkifcanrun(temp, ops, executed){
        if (!ops[temp].inputsName) return true;
        for (let i = 0; i < ops[temp].inputsName.length; i++){
                if (executed[ops[temp].inputsName[i]] === false)  return false;
        }
        return true;
    }






W
wangqun 已提交
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
    /**
     * Get Ops Nets Start Node
     * @param ops
     * @returns {*}
     */
    getNetsStart(ops) {
        return ops.filter((item) => {
            if (item.type === 'feed') {
                return true;
            }
        });
    }
    /**
     * Get Ops Nets Last Node
     * @param ops
     * @returns {*}
     */
    getNetsEnd(ops) {
        return ops.filter((item) => {
            if (item.type === 'fetch') {
                return true;
            }
        });
    }
    /**
     * get tensor by id
     * @param id
     * @returns {*}
     */
    getTensor(id) {
        return this.weightMap.filter((item, i) => {
            if (id === item.id)
                return item;
        });
    }
W
wangqun 已提交
336 337 338 339 340 341 342 343 344
    formatWeight(vars) {
        if (this.formatLayout === 'NHWC') {
            vars.map((item) => {
                if (item.data && item.shape) {
                    item.data =  Utils.nhwc2nchw(item.data, item.shape);
                }
            });
        }
    };
W
wangqun 已提交
345 346 347 348 349 350
    /**
     * Create Ops Executor Object Map
     * @param ops
     * @returns {*}
     */
    createOpsMap(ops) {
W
wangqun 已提交
351 352
        // console.log('ops!!');
        // console.dir(ops);
W
wangqun 已提交
353 354 355 356 357 358 359 360 361 362 363 364 365 366
        return ops.map((item, idx) => {
            item.idx = idx;
            const graphExecutor = new GraphExecutor(item);
            return graphExecutor;
        });
    }
    /**
     * Get The Next Executor need Exec
     * @param ops
     * @param id
     * @returns {*}
     */
    getNextExecutor(ops, id) {
        return ops.filter((item, key) => {
W
wangqun 已提交
367 368 369 370
            for (let i = 0; i < item.inputsName.length; i++) {
                if (id === item.inputsName[i]) {
                    return true;
                }
W
wangqun 已提交
371 372 373 374
            }
        });
    }

W
wangqun 已提交
375 376 377 378 379 380 381 382 383 384 385
    getNextByOp(ops, op) {
        return ops.filter((item, key) => {
            for (let i = 0; i < item.inputsName.length; i++) {
                for(let j = 0; j < op.outputsName.length; j++) {
                    if (item.inputsName[i] === op.outputsName[j]) {
                        return true;
                    }
                }
            }
        });
    }
W
wangqun 已提交
386 387 388 389 390 391 392 393
    /**
     * dispose
     */
    dispose() {
        this.executor.dispose();
    }
}
/* eslint-enable */