graph.es6 9.9 KB
Newer Older
W
wangqun 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/* eslint-disable */
import GraphExecutor from '../executor/executor';
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 已提交
16
let opindex = 0;
W
wangqun 已提交
17 18 19 20 21 22 23 24 25 26 27 28 29

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 已提交
30
        this.formatLayout = 'NCHW';
W
wangqun 已提交
31 32 33 34
        this.isExecuted = false;
        // 网络层数
        this.iLayer = 0;

W
wangqun 已提交
35 36 37 38 39 40 41 42
        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 已提交
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
        }

        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 已提交
58 59 60 61 62 63
        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 已提交
64 65
        opData.renderData = opConfs[name].map(elem => {
            let item = Object.assign({}, elem);
W
wangqun 已提交
66
            const tensorData = opData.inputTensors.find(tensor => tensor.name === item.tensor);
W
wangqun 已提交
67
            if (item.type === 'texture') {
W
wangqun 已提交
68
                item.tensorId = tensorData.opts.type;
W
wangqun 已提交
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
                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 已提交
93
        opindex++;
W
wangqun 已提交
94
        executor.execute(this.inst, this.isExecuted);
95 96 97 98 99 100 101
        if (false && executor.opData && opindex >= 184){
            console.log('return!');
            console.dir(executor);
            console.dir(executor.type);
            console.dir(this);
            return;
        }
W
wangqun 已提交
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
        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 已提交
154 155 156
            output[key].forEach((item, index) => {
                output[key][index] = that.getTensorAttr(item)[0];
            });
W
wangqun 已提交
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 201 202 203 204
        });
        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 已提交
205 206 207 208 209



    arrangeMap(ops) {
        var executed = {};
210 211
        var inIndex = [];
        var idtoindex = {};
W
wangqun 已提交
212 213 214 215
        let temp = 0;
        let ops1 = ops;
        ops1.forEach(function(item, index) {
            item.outputsName.forEach(function(i, idx){
216
                executed[i] = true;
W
wangqun 已提交
217 218 219
            })
        });

220 221 222 223 224 225 226 227 228 229 230
         ops1.forEach(function(item, index) {
            inIndex[index] = 0;
            idtoindex[item.id] = index;
            if (item.inputsName.length > 1) {
                item.inputsName.forEach(function(i,idx){
                    if (executed[i] == true) inIndex[index]++;
                })
            }
            else inIndex[index] = item.inputsName.length;
        });
        this.topoSort(ops, inIndex, idtoindex);
W
wangqun 已提交
231 232 233
        return ops;
    }

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
    topoSort(ops, inIndex, idtoindex){
        var inline = [];
        inline.push(ops[0]);
        let ops_temp = ops.slice(0);
        let prev = null;
        let a = ops[0];
        while(inline.length > 0){
            if (prev != null) ops[idtoindex[prev.id]].next = a.id;
            prev = a;
            a = inline.pop();
            for (let i = 0; i < a.outputsName.length; i++){
                for (let k = 0; k < ops_temp.length; k++){
                    for (let j = 0; j < ops_temp[k].inputsName.length; j++){
                        if (ops_temp[k].inputsName[j] == a.outputsName[i]) {
                            inIndex[idtoindex[ops_temp[k].id]]--;
                            if (inIndex[idtoindex[ops_temp[k].id]] == 0){
                                inline.push(ops[idtoindex[ops_temp[k].id]]);
                                ops_temp.splice(k,1);
                                k--;
                                break;
                            }
                        }
                    }
                }
            }
W
wangqun 已提交
259 260 261 262
        }
    }


W
wangqun 已提交
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
    /**
     * 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 已提交
298 299 300 301 302 303 304 305 306
    formatWeight(vars) {
        if (this.formatLayout === 'NHWC') {
            vars.map((item) => {
                if (item.data && item.shape) {
                    item.data =  Utils.nhwc2nchw(item.data, item.shape);
                }
            });
        }
    };
W
wangqun 已提交
307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326
    /**
     * Create Ops Executor Object Map
     * @param ops
     * @returns {*}
     */
    createOpsMap(ops) {
        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 已提交
327 328 329 330
            for (let i = 0; i < item.inputsName.length; i++) {
                if (id === item.inputsName[i]) {
                    return true;
                }
W
wangqun 已提交
331 332 333 334 335 336 337 338 339 340 341 342
            }
        });
    }

    /**
     * dispose
     */
    dispose() {
        this.executor.dispose();
    }
}
/* eslint-enable */