| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277 |
- /* jshint esversion: 6 */
- var mxnet = mxnet || {};
- var json = json || require('./json');
- var zip = zip || require('./zip');
- var ndarray = ndarray || {};
- mxnet.ModelFactory = class {
- match(context) {
- const identifier = context.identifier;
- const extension = identifier.split('.').pop().toLowerCase();
- if (extension === 'model' || extension === 'mar') {
- if (context.entries('zip').length > 0) {
- return true;
- }
- }
- else if (extension == 'json') {
- const obj = context.open('json');
- if (obj && obj.nodes && obj.arg_nodes && obj.heads) {
- return true;
- }
- }
- else if (extension == 'params') {
- const stream = context.stream;
- const signature = [ 0x12, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 ];
- if (stream.length > signature.length && stream.peek(signature.length).every((value, index) => value == signature[index])) {
- return true;
- }
- }
- return false;
- }
- open(context) {
- return mxnet.Metadata.open(context).then((metadata) => {
- const basename = (identifier, extension, suffix) => {
- const dots = identifier.split('.');
- if (dots.length >= 2 && dots.pop().toLowerCase() === extension) {
- const dashes = dots.join('.').split('-');
- if (dashes.length >= 2) {
- const token = dashes.pop();
- if (suffix) {
- if (token != suffix) {
- return null;
- }
- }
- else {
- for (let i = 0; i < token.length; i++) {
- const c = token.charAt(i);
- if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')) {
- continue;
- }
- return null;
- }
- }
- return dashes.join('-');
- }
- }
- return null;
- };
- const open_model = (metadata, format, manifest, symbol, signature, params) => {
- const parameters = new Map();
- if (params) {
- try {
- const stream = new ndarray.Stream(params);
- for (const key of Object.keys(stream.arrays)) {
- const name = (key.startsWith('arg:') || key.startsWith('aux:')) ? key.substring(4) : key;
- parameters.set(name, stream.arrays[key]);
- }
- }
- catch (error) {
- // continue regardless of error
- }
- }
- return new mxnet.Model(metadata, format, manifest, symbol, signature, parameters);
- };
- const identifier = context.identifier;
- const extension = context.identifier.split('.').pop().toLowerCase();
- let symbol = null;
- let params = null;
- let format = null;
- let base = null;
- switch (extension) {
- case 'json':
- try {
- symbol = context.open('json');
- if (symbol && symbol.nodes && symbol.nodes.some((node) => node && node.op == 'tvm_op')) {
- format = 'TVM';
- }
- }
- catch (error) {
- const message = error && error.message ? error.message : error.toString();
- throw new mxnet.Error("Failed to load symbol entry (" + message.replace(/\.$/, '') + ').');
- }
- base = basename(identifier, 'json', 'symbol');
- if (base) {
- return context.request(base + '-0000.params', null).then((stream) => {
- const buffer = stream.peek();
- return open_model(metadata, format, null, symbol, null, buffer);
- }).catch(() => {
- return open_model(metadata, format, null, symbol, null, params);
- });
- }
- return open_model(metadata, format, null, symbol, null, null);
- case 'params':
- params = context.stream.peek();
- base = basename(context.identifier, 'params');
- if (base) {
- return context.request(base + '-symbol.json', 'utf-8').then((text) => {
- symbol = JSON.parse(text);
- if (symbol && symbol.nodes && symbol.nodes.some((node) => node && node.op == 'tvm_op')) {
- format = 'TVM';
- }
- return open_model(metadata, format, null, symbol, null, params);
- }).catch(() => {
- return open_model(metadata, format, null, null, null, params);
- });
- }
- return open_model(metadata, format, null, null, null, params);
- case 'mar':
- case 'model': {
- const entries = new Map();
- try {
- for (const entry of context.entries('zip')) {
- entries.set(entry.name, entry);
- }
- }
- catch (err) {
- throw new mxnet.Error('Failed to decompress Zip archive. ' + err.message);
- }
- let manifestEntry = entries.get(entries.has('MANIFEST.json') ? 'MANIFEST.json' : 'MAR-INF/MANIFEST.json');
- let rootFolder = '';
- if (!manifestEntry) {
- const folders = Array.from(entries.keys()).filter((name) => name.endsWith('/')).filter((name) => entries.get(name + 'MANIFEST.json'));
- if (folders.length != 1) {
- throw new mxnet.Error("Manifest not found.");
- }
- rootFolder = folders[0];
- manifestEntry = entries.get(rootFolder + 'MANIFEST.json');
- }
- const decoder = new TextDecoder('utf-8');
- let manifest = null;
- try {
- manifest = JSON.parse(decoder.decode(manifestEntry.data));
- }
- catch (err) {
- throw new mxnet.Error('Failed to read manifest. ' + err.message);
- }
- let modelFormat = null;
- let symbolEntry = null;
- let signatureEntry = null;
- let paramsEntry = null;
- if (manifest.Model) {
- modelFormat = manifest.Model['Model-Format'];
- if (modelFormat && modelFormat != 'MXNet-Symbolic') {
- throw new mxnet.Error('Model format \'' + modelFormat + '\' not supported.');
- }
- format = 'MXNet Model Server';
- if (manifest['Model-Archive-Version']) {
- format += ' v' + manifest['Model-Archive-Version'].toString();
- }
- if (!manifest.Model.Symbol) {
- throw new mxnet.Error('Manifest does not contain symbol entry.');
- }
- symbolEntry = entries.get(rootFolder + manifest.Model.Symbol);
- if (manifest.Model.Signature) {
- signatureEntry = entries.get(rootFolder + manifest.Model.Signature);
- }
- if (manifest.Model.Parameters) {
- paramsEntry = entries.get(rootFolder + manifest.Model.Parameters);
- }
- }
- else if (manifest.model) {
- format = 'MXNet Model Archive';
- if (manifest.specificationVersion) {
- format += ' v' + manifest.specificationVersion.toString();
- }
- if (manifest.model.modelName) {
- symbolEntry = entries.get(rootFolder + manifest.model.modelName + '-symbol.json');
- let key = null;
- for (key of Array.from(entries.keys())) {
- key = key.substring(rootFolder.length);
- if (key.endsWith('.params') && key.startsWith(manifest.model.modelName)) {
- paramsEntry = entries.get(key);
- break;
- }
- }
- if (!symbolEntry && !paramsEntry) {
- for (key of Object.keys(entries)) {
- key = key.substring(rootFolder.length);
- if (key.endsWith('.params')) {
- paramsEntry = entries.get(key);
- break;
- }
- }
- }
- }
- }
- else {
- throw new mxnet.Error('Manifest does not contain model.');
- }
- if (!symbolEntry && !paramsEntry) {
- throw new mxnet.Error("Model does not contain symbol entry.");
- }
- try {
- if (symbolEntry) {
- symbol = JSON.parse(decoder.decode(symbolEntry.data));
- }
- }
- catch (err) {
- throw new mxnet.Error('Failed to load symbol entry.' + err.message);
- }
- if (paramsEntry) {
- params = paramsEntry.data;
- }
- let signature = null;
- try {
- if (signatureEntry) {
- signature = JSON.parse(decoder.decode(signatureEntry.data));
- }
- }
- catch (err) {
- // continue regardless of error
- }
- return open_model(metadata, format, manifest, symbol, signature, params);
- }
- default:
- throw new mxnet.Error('Unsupported file extension.');
- }
- });
- }
- };
- mxnet.Model = class {
- constructor(metadata, format, manifest, symbol, signature, params) {
- if (!symbol && !params) {
- throw new mxnet.Error('JSON symbol data not available.');
- }
- if (symbol) {
- if (!Object.prototype.hasOwnProperty.call(symbol, 'nodes')) {
- throw new mxnet.Error('JSON file does not contain an MXNet \'nodes\' property.');
- }
- if (!Object.prototype.hasOwnProperty.call(symbol, 'arg_nodes')) {
- throw new mxnet.Error('JSON file does not contain an MXNet \'arg_nodes\' property.');
- }
- if (!Object.prototype.hasOwnProperty.call(symbol, 'heads')) {
- throw new mxnet.Error('JSON file does not contain an MXNet \'heads\' property.');
- }
- }
- if (manifest) {
- if (manifest.Model && manifest.Model['Model-Name']) {
- this._name = manifest.Model['Model-Name'];
- }
- if (manifest.Model && manifest.Model.Description && this._name != manifest.Model.Description) {
- this._description = manifest.Model.Description;
- }
- if (manifest.Engine && manifest.Engine.MXNet) {
- const engineVersion = mxnet.Model._convert_version(manifest.Engine.MXNet);
- this._runtime = 'MXNet v' + (engineVersion ? engineVersion : manifest.Engine.MXNet.toString());
- }
- if (manifest.License) {
- this._license = manifest.License;
- }
- if (manifest.model && manifest.model.modelName) {
- this._name = manifest.model.modelName;
- }
- if (manifest.model && manifest.model.modelVersion) {
- this._version = manifest.model.modelVersion;
- }
- if (manifest.model && manifest.model.modelName && this._name != manifest.model.description) {
- this._description = manifest.model.description;
- }
- if (manifest.runtime) {
- this._runtime = manifest.runtime;
- }
- if (manifest.engine && manifest.engine.engineName) {
- const engine = manifest.engine.engineVersion ? manifest.engine.engineName + ' ' + manifest.engine.engineVersion : manifest.engine.engineName;
- this._runtime = this._runtime ? (this._runtime + ' (' + engine + ')') : engine;
- }
- if (manifest.publisher && manifest.publisher.author) {
- this._author = manifest.publisher.author;
- if (manifest.publisher.email) {
- this._author = this._author + ' <' + manifest.publisher.email + '>';
- }
- }
- if (manifest.license) {
- this._license = manifest.license;
- }
- }
- this._format = format;
- if (!this._format && symbol && symbol.attrs && symbol.attrs.mxnet_version) {
- const version = mxnet.Model._convert_version(symbol.attrs.mxnet_version);
- if (version) {
- this._format = 'MXNet v' + version;
- }
- }
- if (!this._format) {
- this._format = 'MXNet';
- }
- this._graphs = [];
- this._graphs.push(new mxnet.Graph(metadata, manifest, symbol, signature, params));
- }
- get format() {
- return this._format;
- }
- get name() {
- return this._name;
- }
- get version() {
- return this._version;
- }
- get description() {
- return this._description;
- }
- get author() {
- return this._author;
- }
- get license() {
- return this._license;
- }
- get runtime() {
- return this._runtime;
- }
- get graphs() {
- return this._graphs;
- }
- static _convert_version(value) {
- if (Array.isArray(value)) {
- if (value.length == 2 && value[0] == 'int') {
- const major = Math.floor(value[1] / 10000) % 100;
- const minor = Math.floor(value[1] / 100) % 100;
- const patch = Math.floor(value[1]) % 100;
- return [ major.toString(), minor.toString(), patch.toString() ].join('.');
- }
- }
- return null;
- }
- };
- mxnet.Graph = class {
- constructor(metadata, manifest, symbol, signature, params) {
- this._metadata = metadata;
- this._nodes = [];
- this._inputs = [];
- this._outputs = [];
- const tensors = new Map();
- if (params) {
- for (const pair of params) {
- const key = pair[0];
- const value = pair[1];
- tensors.set(key, new mxnet.Tensor('Initializer', key, new mxnet.TensorType(value.dataType, new mxnet.TensorShape(value.shape.dimensions)), value.data));
- }
- }
- if (symbol) {
- const nodes = symbol.nodes;
- const inputs = {};
- if (signature && signature.inputs) {
- for (const input of signature.inputs) {
- inputs[input.data_name] = input;
- }
- }
- const outputs = {};
- if (signature && signature.outputs) {
- for (const output of signature.outputs) {
- outputs[output.data_name] = output;
- }
- }
- for (const node of nodes) {
- node.outputs = [];
- }
- for (const node of nodes) {
- node.inputs = node.inputs.map((input) => {
- return mxnet.Graph._updateOutput(nodes, input);
- });
- }
- const outputCountMap = {};
- for (const node of nodes) {
- for (const output of node.outputs) {
- outputCountMap[output] = (outputCountMap[output] || 0) + 1;
- }
- }
- const argumentMap = {};
- for (const index of symbol.arg_nodes) {
- argumentMap[index] = (index < nodes.length) ? nodes[index] : null;
- }
- for (let i = 0; i < symbol.heads.length; i++) {
- const head = symbol.heads[i];
- const outputId = mxnet.Graph._updateOutput(nodes, head);
- const outputName = nodes[outputId[0]] ? nodes[outputId[0]].name : ('output' + ((i == 0) ? '' : (i + 1).toString()));
- let outputType = null;
- const outputSignature = outputs[outputName];
- if (outputSignature && outputSignature.data_shape) {
- outputType = new mxnet.TensorType(-1, new mxnet.TensorShape(outputSignature.data_shape));
- }
- this._outputs.push(new mxnet.Parameter(outputName, [ new mxnet.Argument('[' + outputId.join(',') + ']', outputType, null) ]));
- }
- const initializerMap = {};
- for (const node of nodes.filter((node, index) => !argumentMap[index])) {
- this._nodes.push(new mxnet.Node(this._metadata, node, argumentMap, initializerMap, tensors));
- }
- for (const argumentKey of Object.keys(argumentMap)) {
- const argument = argumentMap[argumentKey];
- if (argument && (!argument.inputs || argument.inputs.length == 0) && (argument.outputs && argument.outputs.length == 1)) {
- const inputId = argument.outputs[0];
- const inputName = argument.name;
- let inputType = null;
- const inputSignature = inputs[inputName];
- if (inputSignature && inputSignature.data_shape) {
- inputType = new mxnet.TensorType(-1, new mxnet.TensorShape(inputSignature.data_shape));
- }
- this._inputs.push(new mxnet.Parameter(inputName, [ new mxnet.Argument('[' + inputId.join(',') + ']', inputType) ]));
- }
- }
- }
- else if (params) {
- const blocks = new Map();
- let separator = Array.from(params.keys()).every((key) => key.indexOf('_') != -1) ? '_' : '';
- if (separator.length == 0) {
- separator = Array.from(params.keys()).every((key) => key.indexOf('.') != -1) ? '.' : '';
- }
- if (separator.length > 0) {
- for (const param of params) {
- const key = param[0];
- const parts = key.split(separator);
- let argumentName = parts.pop();
- if (key.endsWith('moving_mean') || key.endsWith('moving_var')) {
- argumentName = [ parts.pop(), argumentName ].join(separator);
- }
- const nodeName = parts.join(separator);
- if (!blocks.has(nodeName)) {
- blocks.set(nodeName, { name: nodeName, op: 'Weights', params: [] });
- }
- blocks.get(nodeName).params.push({ name: argumentName, id: key });
- }
- }
- else {
- throw new mxnet.Error("Unsupported key format in params.");
- }
- for (const block of blocks.values()) {
- this._nodes.push(new mxnet.Node(metadata, block, {}, {}, tensors));
- }
- }
- }
- get name() {
- return '';
- }
- get inputs() {
- return this._inputs;
- }
- get outputs() {
- return this._outputs;
- }
- get nodes() {
- return this._nodes;
- }
- static _updateOutput(nodes, input) {
- const nodeIndex = input[0];
- const node = nodes[nodeIndex];
- const outputIndex = input[1];
- if (node) {
- while (outputIndex >= node.outputs.length) {
- node.outputs.push([ nodeIndex, node.outputs.length ]);
- }
- }
- return [ nodeIndex, outputIndex ];
- }
- };
- mxnet.Parameter = class {
- constructor(name, args) {
- this._name = name;
- this._arguments = args;
- }
- get name() {
- return this._name;
- }
- get visible() {
- return true;
- }
- get arguments() {
- return this._arguments;
- }
- };
- mxnet.Argument = class {
- constructor(name, type, initializer) {
- if (typeof name !== 'string') {
- throw new mxnet.Error("Invalid argument identifier '" + JSON.stringify(name) + "'.");
- }
- this._name = name;
- this._type = type || null;
- this._initializer = initializer || null;
- }
- get name() {
- if (this._initializer) {
- return this._initializer.name;
- }
- return this._name;
- }
- get type() {
- if (this._initializer) {
- return this._initializer.type;
- }
- return this._type;
- }
- get initializer() {
- return this._initializer;
- }
- };
- mxnet.Node = class {
- constructor(metadata, node, argumentMap, initializerMap, tensors) {
- this._metadata = metadata;
- this._type = node.op;
- this._name = node.name;
- this._attributes = [];
- this._inputs = [];
- this._outputs = [];
- const attrs = node.attrs || node.attr || node.param;
- if (attrs) {
- if (this._type == 'tvm_op' && attrs.func_name) {
- this._type = attrs.func_name;
- }
- for (const attributeName of Object.keys(attrs)) {
- if (this._type != 'tvm_op' && attributeName != 'func_name') {
- this._attributes.push(new mxnet.Attribute(this._metadata, this.type, attributeName, attrs[attributeName]));
- }
- }
- }
- let initializer = null;
- const schema = metadata.type(this.type);
- if (node.inputs) {
- let inputs = node.inputs;
- if (this._type == 'RNN') {
- inputs = inputs.map((input) => {
- const argumentNodeIndex = input[0];
- const argument = argumentMap[argumentNodeIndex];
- if (argument && argument.op == 'null' && argument.name &&
- argument.name.endsWith('_parameters') && argument.attr && argument.attr.__init__) {
- this._attributes.push(new mxnet.Attribute(this._metadata, this.type, argument.name, argument.attr.__init__));
- delete argumentMap[argumentNodeIndex];
- return null;
- }
- return input;
- });
- inputs = inputs.filter((item) => item != null);
- }
- const initializers = {};
- for (const input of inputs) {
- const id = '[' + input.join(',') + ']';
- initializer = initializerMap[id];
- if (!initializer) {
- const argumentNodeIndex = input[0];
- const argument = argumentMap[argumentNodeIndex];
- if (argument && argument.name &&
- (!argument.inputs || argument.inputs.length == 0) &&
- (argument.outputs && argument.outputs.length == 1)) {
- initializer = tensors.get(argument.name) || null;
- if (initializer) {
- delete argumentMap[argumentNodeIndex];
- }
- else {
- let prefix = this._name;
- if (prefix.endsWith('_fwd')) {
- prefix = prefix.slice(0, -3);
- }
- if (argument.name && (argument.name.startsWith(prefix + '_') || argument.name.startsWith(prefix + '.'))) {
- let dataType = -1;
- let shape = [];
- if (argument.attrs && argument.attrs.__dtype__ && argument.attrs.__shape__) {
- try {
- dataType = parseInt(argument.attrs.__dtype__);
- shape = JSON.parse('[' + argument.attrs.__shape__.replace('(', '').replace(')', '').split(' ').join('').split(',').map((dimension => dimension || '"?"' )).join(',') + ']');
- }
- catch (err) {
- // continue regardless of error
- }
- }
- let argumentType = null;
- if (dataType !== -1 || shape.length > 0) {
- argumentType = new mxnet.TensorType(dataType, new mxnet.TensorShape(shape));
- }
- else {
- argumentType = new mxnet.TensorType(-1, new mxnet.TensorShape(null));
- }
- initializer = new mxnet.Tensor('Initializer', argument.name, argumentType, null);
- delete argumentMap[argumentNodeIndex];
- }
- }
- }
- }
- if (initializer) {
- initializers[id] = initializer;
- initializerMap[id] = initializer;
- }
- }
- let inputIndex = 0;
- if (schema && schema.inputs) {
- for (const inputDef of schema.inputs) {
- if (inputIndex < inputs.length || inputDef.option != 'optional') {
- const inputCount = (inputDef.option == 'variadic') ? (inputs.length - inputIndex) : 1;
- const inputArguments = [];
- for (const input of inputs.slice(inputIndex, inputIndex + inputCount)) {
- const inputId = '[' + input.join(',') + ']';
- if (inputId != '' || inputDef.option != 'optional') {
- inputArguments.push(new mxnet.Argument(inputId, inputDef.type, initializers[inputId]));
- }
- }
- this._inputs.push(new mxnet.Parameter(inputDef.name, inputArguments));
- inputIndex += inputCount;
- }
- }
- }
- if (inputIndex < inputs.length) {
- this._inputs.push(...inputs.slice(inputIndex).map((input, index) => {
- const inputId = '[' + input.join(',') + ']';
- return new mxnet.Parameter((inputIndex + index).toString(), [
- new mxnet.Argument(inputId, null, initializers[inputId])
- ]);
- }));
- }
- }
- if (node.outputs) {
- const outputs = node.outputs;
- let outputIndex = 0;
- if (schema && schema.outputs) {
- for (const outputDef of schema.outputs) {
- if (outputIndex < outputs.length || outputDef.option != 'optional') {
- const outputArguments = [];
- const outputCount = (outputDef.option == 'variadic') ? (outputs.length - outputIndex) : 1;
- for (const output of outputs.slice(outputIndex, outputIndex + outputCount)) {
- outputArguments.push(new mxnet.Argument('[' + output.join(',') + ']', null, null));
- }
- this._outputs.push(new mxnet.Parameter(outputDef.name, outputArguments));
- outputIndex += outputCount;
- }
- }
- }
- if (outputIndex < outputs.length) {
- this._outputs.push(...outputs.slice(outputIndex).map((output, index) => {
- return new mxnet.Parameter((outputIndex + index).toString(), [
- new mxnet.Argument('[' + output.join(',') + ']', null, null)
- ]);
- }));
- }
- }
- if (node.params) {
- for (const param of node.params) {
- this._inputs.push(new mxnet.Parameter(param.name, [
- new mxnet.Argument(param.id, null, tensors.get(param.id) || null)
- ]));
- }
- }
- }
- get type() {
- return this._type;
- }
- get metadata() {
- return this._metadata.type(this._type);
- }
- get name() {
- return this._name;
- }
- get inputs() {
- return this._inputs;
- }
- get outputs() {
- return this._outputs;
- }
- get attributes() {
- return this._attributes;
- }
- };
- mxnet.Attribute = class {
- constructor(metadata, type, name, value) {
- this._name = name;
- this._value = value;
- let number;
- const schema = metadata.attribute(type, name);
- if (schema && schema.type) {
- switch (schema.type) {
- case 'boolean':
- switch (value) {
- case 'True':
- this._value = true;
- break;
- case 'False':
- this._value = false;
- break;
- }
- break;
- case 'int32':
- number = Number.parseInt(this._value, 10);
- this._value = Number.isNaN(this._value - number) ? value : number;
- break;
- case 'float32':
- case 'float64':
- number = Number.parseFloat(this._value);
- this._value = Number.isNaN(this._value - number) ? value : number;
- break;
- case 'int32[]':
- if (this._value.length > 2 && this._value.startsWith('(') && this._value.endsWith(')')) {
- let array = [];
- const items = this._value.substring(1, this._value.length - 1).split(',')
- .map((item) => item.trim())
- .map((item) => item.endsWith('L') ? item.substring(0, item.length - 1) : item);
- for (const item of items) {
- number = Number.parseInt(item, 10);
- if (Number.isNaN(item - number)) {
- array = null;
- }
- else if (array != null) {
- array.push(number);
- }
- }
- if (array != null) {
- this._value = array;
- }
- }
- break;
- }
- }
- if (schema) {
- if (Object.prototype.hasOwnProperty.call(schema, 'visible') && !schema.visible) {
- this._visible = false;
- }
- else if (Object.prototype.hasOwnProperty.call(schema, 'default')) {
- let defaultValue = schema.default;
- if (this._value == defaultValue) {
- this._visible = false;
- }
- else if (Array.isArray(this._value) && Array.isArray(defaultValue)) {
- defaultValue = defaultValue.slice(0, defaultValue.length);
- if (defaultValue.length > 1 && defaultValue[defaultValue.length - 1] == null) {
- defaultValue.pop();
- while (defaultValue.length < this._value.length) {
- defaultValue.push(defaultValue[defaultValue.length - 1]);
- }
- }
- if (this._value.every((item, index) => { return item == defaultValue[index]; })) {
- this._visible = false;
- }
- }
- }
- }
- }
- get name() {
- return this._name;
- }
- get type() {
- return this._type;
- }
- get value() {
- return this._value;
- }
- get visible() {
- return this._visible == false ? false : true;
- }
- };
- mxnet.Tensor = class {
- constructor(kind, name, type, data) {
- this._kind = kind;
- this._name = name;
- this._type = type;
- this._data = data;
- }
- get kind() {
- return 'Initializer';
- }
- get name() {
- return this._name;
- }
- get type() {
- return this._type;
- }
- get state() {
- return this._context().state;
- }
- get value() {
- const context = this._context();
- if (context.state) {
- return null;
- }
- context.limit = Number.MAX_SAFE_INTEGER;
- return this._decode(context, 0);
- }
- toString() {
- const context = this._context();
- if (context.state) {
- return '';
- }
- context.limit = 10000;
- const value = this._decode(context, 0);
- return JSON.stringify(value, null, 4);
- }
- _context() {
- const context = {};
- context.state = null;
- context.index = 0;
- context.count = 0;
- if (!this._data) {
- context.state = 'Tensor data is empty.';
- return context;
- }
- if (!this._type && this._type.dataType === '?') {
- context.state = 'Tensor has no data type.';
- return context;
- }
- if (this._type.shape.length < 1) {
- context.state = 'Tensor has unknown shape.';
- return context;
- }
- context.dataType = this._type.dataType;
- context.dimensions = this._type.shape.dimensions;
- context.data = new DataView(this._data.buffer, this._data.byteOffset, this._data.byteLength);
- return context;
- }
- _decode(context, dimension) {
- const results = [];
- const size = context.dimensions[dimension];
- if (dimension == context.dimensions.length - 1) {
- for (let i = 0; i < size; i++) {
- if (context.count > context.limit) {
- results.push('...');
- return results;
- }
- switch (context.dataType) {
- case 'float32':
- results.push(context.data.getFloat32(context.index, true));
- context.index += 4;
- context.count++;
- break;
- case 'float64':
- results.push(context.data.getFloat64(context.index, true));
- context.index += 8;
- context.count++;
- break;
- case 'float16':
- results.push(mxnet.Tensor._decodeNumberFromFloat16(context.data.getUint16(context.index, true)));
- context.index += 2;
- context.count++;
- break;
- case 'uint8':
- results.push(context.data.getUint8(context.index, true));
- context.index += 1;
- context.count++;
- break;
- case 'int32':
- results.push(context.data.getInt32(context.index, true));
- context.index += 4;
- context.count++;
- break;
- case 'int8':
- results.push(context.data.getInt8(context.index, true));
- context.index += 1;
- context.count++;
- break;
- case 'int64':
- results.push(context.data.getInt64(context.index, true));
- context.index += 8;
- context.count++;
- break;
- }
- }
- }
- else {
- for (let j = 0; j < size; j++) {
- if (context.count > context.limit) {
- results.push('...');
- return results;
- }
- results.push(this._decode(context, dimension + 1));
- }
- }
- return results;
- }
- static _decodeNumberFromFloat16(value) {
- const s = (value & 0x8000) >> 15;
- const e = (value & 0x7C00) >> 10;
- const f = value & 0x03FF;
- if(e == 0) {
- return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
- }
- else if (e == 0x1F) {
- return f ? NaN : ((s ? -1 : 1) * Infinity);
- }
- return (s ? -1 : 1) * Math.pow(2, e-15) * (1 + (f / Math.pow(2, 10)));
- }
- };
- mxnet.TensorType = class {
- constructor(dataType, shape) {
- switch (dataType) {
- case 0: this._dataType = 'float32'; break;
- case 1: this._dataType = 'float64'; break;
- case 2: this._dataType = 'float16'; break;
- case 3: this._dataType = 'uint8'; break;
- case 4: this._dataType = 'int32'; break;
- case 5: this._dataType = 'int8'; break;
- case 6: this._dataType = 'int64'; break;
- case -1: this._dataType = '?'; break;
- default: throw new mxnet.Error("Unknown type '" + dataType + "'.");
- }
- this._shape = shape;
- }
- get dataType() {
- return this._dataType;
- }
- get shape() {
- return this._shape;
- }
- toString() {
- return this._dataType + this._shape.toString();
- }
- };
- mxnet.TensorShape = class {
- constructor(dimensions) {
- this._dimensions = dimensions;
- }
- get dimensions() {
- return this._dimensions;
- }
- toString() {
- if (this._dimensions) {
- if (this._dimensions.length == 0) {
- return '';
- }
- return '[' + this._dimensions.map((dimension) => dimension.toString()).join(',') + ']';
- }
- return '';
- }
- };
- mxnet.Metadata = class {
- static open(context) {
- if (mxnet.Metadata._metadata) {
- return Promise.resolve(mxnet.Metadata._metadata);
- }
- return context.request('mxnet-metadata.json', 'utf-8', null).then((data) => {
- mxnet.Metadata._metadata = new mxnet.Metadata(data);
- return mxnet.Metadata._metadata;
- }).catch(() => {
- mxnet.Metadata._metadata = new mxnet.Metadata(null);
- return mxnet.Metadata._metadata;
- });
- }
- constructor(data) {
- this._map = new Map();
- this._attributeCache = {};
- if (data) {
- const metadata = JSON.parse(data);
- this._map = new Map(metadata.map((item) => [ item.name, item ]));
- }
- }
- type(name) {
- return this._map.get(name);
- }
- attribute(type, name) {
- let map = this._attributeCache[type];
- if (!map) {
- map = {};
- const schema = this.type(type);
- if (schema && schema.attributes) {
- for (const attribute of schema.attributes) {
- map[attribute.name] = attribute;
- }
- }
- this._attributeCache[type] = map;
- }
- return map[name] || null;
- }
- };
- mxnet.Error = class extends Error {
- constructor(message) {
- super(message);
- this.name = 'Error loading MXNet model.';
- }
- };
- ndarray.Stream = class {
- constructor(buffer) {
- this._arrays = {};
- const reader = new ndarray.Reader(buffer);
- if (!reader.checkSignature([ 0x12, 1, 0, 0, 0, 0, 0, 0 ])) {
- throw new ndarray.Error('Invalid signature.');
- }
- if (!reader.checkSignature([ 0, 0, 0, 0, 0, 0, 0, 0 ])) {
- throw new ndarray.Error('Invalid reserved block.');
- }
- const data = [];
- for (let dataSize = reader.uint64(); dataSize > 0; dataSize--) {
- data.push(new ndarray.Array(reader));
- }
- const decoder = new TextDecoder('ascii');
- const names = [];
- for (let namesSize = reader.uint64(); namesSize > 0; namesSize--) {
- const name = decoder.decode(reader.read(reader.uint64()));
- names.push(name);
- }
- if (names.length != data.length) {
- throw new ndarray.Error('Label count mismatch.');
- }
- for (let i = 0; i < names.length; i++) {
- this._arrays[names[i]] = data[i];
- }
- }
- get arrays() {
- return this._arrays;
- }
- };
- ndarray.Array = class {
- constructor(reader) {
- ndarray.Array._dataTypeSizeTable = [ 4, 8, 2, 1, 4, 1, 8 ];
- if (reader.checkSignature([ 0xc9, 0xfa, 0x93, 0xF9 ])) {
- this._loadV2(reader);
- }
- else if (reader.checkSignature([ 0xc8, 0xfa, 0x93, 0xF9 ])) {
- this._loadV1(reader);
- }
- else {
- this._loadV0(reader);
- }
- }
- _loadV2(reader) {
- const stype = reader.uint32();
- let num_aux_data = 0;
- switch (stype) {
- case 0: num_aux_data = 0; break; // kDefaultStorage
- case 1: num_aux_data = 1; break; // kRowSparseStorage
- case 2: num_aux_data = 2; break; // kCSRStorage
- }
- this.sshape = null;
- if (num_aux_data > 0) {
- this.sshape = new ndarray.Shape(reader, true);
- }
- this._shape = new ndarray.Shape(reader, true);
- if (this._shape.dimensions.length == 0) {
- return;
- }
- this._context = new ndarray.Context(reader);
- this._dataType = reader.uint32();
- if (num_aux_data > 0) {
- throw new ndarray.Error('Not implemented.');
- }
- const dataTypeSize = (this._dataType < ndarray.Array._dataTypeSizeTable.length) ? ndarray.Array._dataTypeSizeTable[this._dataType] : 0;
- const size = dataTypeSize * this._shape.size();
- this._data = reader.read(size);
- }
- _loadV1(reader) {
- this._shape = new ndarray.Shape(reader, true);
- if (this._shape.dimensions.length == 0) {
- return;
- }
- this._context = new ndarray.Context(reader);
- this._dataType = reader.uint32();
- const dataTypeSize = (this._dataType < ndarray.Array._dataTypeSizeTable.length) ? ndarray.Array._dataTypeSizeTable[this._dataType] : 0;
- const size = dataTypeSize * this._shape.size();
- this._data = reader.read(size);
- }
- _loadV0(reader) {
- this._shape = new ndarray.Shape(reader, false);
- this._context = new ndarray.Context(reader);
- this._dataType = reader.uint32();
- const dataTypeSize = (this._dataType < ndarray.Array._dataTypeSizeTable.length) ? ndarray.Array._dataTypeSizeTable[this._dataType] : 0;
- const size = dataTypeSize * this._shape.size();
- this._data = reader.read(size);
- }
- get dataType() {
- return this._dataType;
- }
- get shape() {
- return this._shape;
- }
- get data() {
- return this._data;
- }
- };
- ndarray.Shape = class {
- constructor(reader, uint64) {
- const ndim = reader.uint32();
- this._dimensions = [];
- for (let i = 0; i < ndim; i++) {
- this._dimensions.push(uint64 ? reader.uint64() : reader.uint32());
- }
- }
- get dimensions() {
- return this._dimensions;
- }
- size() {
- return this._dimensions.reduce((a, b) => a * b);
- }
- };
- ndarray.Context = class {
- constructor(reader) {
- this._deviceType = reader.uint32();
- this._deviceId = reader.uint32();
- }
- };
- ndarray.Reader = class {
- constructor(buffer) {
- this._buffer = buffer;
- this._position = 0;
- this._end = buffer.length;
- }
- checkSignature(signature) {
- if (this._position + signature.length <= this._end) {
- for (let i = 0; i < signature.length; i++) {
- if (this._buffer[this._position + i] != signature[i]) {
- return false;
- }
- }
- }
- this._position += signature.length;
- return true;
- }
- read(size) {
- if (this._position + size > this._end) {
- throw new ndarray.Error('Data not available.');
- }
- const data = this._buffer.subarray(this._position, this._position + size);
- this._position += size;
- return data;
- }
- uint16() {
- if (this._position + 2 > this._end) {
- throw new ndarray.Error('Data not available.');
- }
- const value = this._buffer[this._position] | (this._buffer[this._position + 1] << 8);
- this._position += 2;
- return value;
- }
- uint32() {
- return this.uint16() | (this.uint16() << 16);
- }
- uint64() {
- const value = this.uint32();
- if (this.uint32() != 0) {
- throw new ndarray.Error('Large int64 value.');
- }
- return value;
- }
- };
- ndarray.Error = class extends Error {
- constructor(message) {
- super(message);
- this.name = 'NDArray Error';
- }
- };
- if (typeof module !== 'undefined' && typeof module.exports === 'object') {
- module.exports.ModelFactory = mxnet.ModelFactory;
- }
|