paddle.js 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415
  1. import * as base from './base.js';
  2. import * as flatbuffers from './flatbuffers.js';
  3. import * as protobuf from './protobuf.js';
  4. import * as python from './python.js';
  5. const paddle = {};
  6. paddle.ModelFactory = class {
  7. async match(context) {
  8. const identifier = context.identifier;
  9. const extension = identifier.lastIndexOf('.') > 0 ? identifier.split('.').pop().toLowerCase() : '';
  10. if (identifier === '__model__' || extension === '__model__' || extension === 'paddle' || extension === 'pdmodel') {
  11. const tags = await context.tags('pb');
  12. if (tags.get(1) === 2) {
  13. return context.set('paddle.pb');
  14. }
  15. }
  16. if (extension === 'pbtxt' || extension === 'txt') {
  17. const tags = await context.tags('pbtxt');
  18. if (tags.has('blocks')) {
  19. return context.set('paddle.pbtxt');
  20. }
  21. }
  22. const stream = context.stream;
  23. if (stream && stream.length > 16 && stream.peek(16).every((value) => value === 0x00)) {
  24. return context.set('paddle.params');
  25. }
  26. const pickle = await paddle.Pickle.open(context);
  27. if (pickle) {
  28. return context.set(pickle.name, pickle);
  29. }
  30. const entries = await paddle.Entries.open(context);
  31. if (entries) {
  32. return context.set(entries.name, entries);
  33. }
  34. const naive = await paddle.NaiveBuffer.open(context);
  35. if (naive) {
  36. return context.set(naive.name, naive);
  37. }
  38. const obj = await context.peek('json');
  39. if (obj && obj.base_code && obj.program) {
  40. return context.set('paddle.ir', obj);
  41. }
  42. return null;
  43. }
  44. filter(context, match) {
  45. if (context.type === 'paddle.pb' && (match.type === 'paddle.params' || match.type === 'paddle.pickle')) {
  46. return false;
  47. }
  48. if (context.type === 'paddle.naive.model' && match.type === 'paddle.naive.param') {
  49. return false;
  50. }
  51. return true;
  52. }
  53. async open(context) {
  54. const metadata = await context.metadata('paddle-metadata.json');
  55. switch (context.type) {
  56. case 'paddle.naive':
  57. case 'paddle.naive.model':
  58. case 'paddle.naive.param': {
  59. paddle.schema = await context.require('./paddle-schema');
  60. paddle.schema = paddle.schema.paddle.lite.fbs.proto;
  61. const target = context.value;
  62. target.read();
  63. return new paddle.Model(metadata, target.format, target.model, target.weights);
  64. }
  65. case 'paddle.ir': {
  66. const ir = new paddle.IR(context.value);
  67. const format = `PaddlePaddle IR v${ir.version}`;
  68. return new paddle.Model(metadata, format, ir.desc, ir.tensors);
  69. }
  70. default: {
  71. paddle.proto = await context.require('./paddle-proto');
  72. paddle.proto = paddle.proto.paddle.framework.proto;
  73. const identifier = context.identifier;
  74. const parts = identifier.split('.');
  75. const extension = parts.pop().toLowerCase();
  76. const base = parts.join('.');
  77. const openProgram = async (context, type) => {
  78. const program = {};
  79. switch (type) {
  80. case 'paddle.pbtxt': {
  81. try {
  82. const reader = await context.read('protobuf.text');
  83. reader.enum = function(type) {
  84. const token = this.token();
  85. this.next();
  86. this.semicolon();
  87. if (type[token] !== undefined) {
  88. return type[token];
  89. }
  90. if (token === 'LOD_TENSOR') {
  91. return type.DENSE_TENSOR;
  92. }
  93. throw new paddle.Error(`Unknown enum value '${token}' ${this.location()}`);
  94. };
  95. reader.field = function(tag, message) {
  96. if (message instanceof paddle.proto.VarType && tag === 'lod_tensor') {
  97. message.dense_tensor = paddle.proto.VarType.DenseTensorDesc.decodeText(reader);
  98. } else {
  99. throw new Error(`Unknown field '${tag}' ${this.location()}`);
  100. }
  101. };
  102. program.desc = paddle.proto.ProgramDesc.decodeText(reader);
  103. } catch (error) {
  104. const message = error && error.message ? error.message : error.toString();
  105. throw new paddle.Error(`File text format is not paddle.ProgramDesc (${message.replace(/\.$/, '')}).`);
  106. }
  107. break;
  108. }
  109. case 'paddle.pb': {
  110. try {
  111. const reader = await context.read('protobuf.binary');
  112. program.desc = paddle.proto.ProgramDesc.decode(reader);
  113. } catch (error) {
  114. const message = error && error.message ? error.message : error.toString();
  115. throw new paddle.Error(`File format is not paddle.ProgramDesc (${message.replace(/\.$/, '')}).`);
  116. }
  117. break;
  118. }
  119. default: {
  120. throw new paddle.Error(`Unsupported Paddle format '${type}'.`);
  121. }
  122. }
  123. const formatVersion = (version) => {
  124. if (version && version.version !== undefined) {
  125. const number = version.version.toNumber();
  126. if (number > 0) {
  127. const list = [Math.floor(number / 1000000) % 1000, Math.floor(number / 1000) % 1000, number % 1000];
  128. if (list.slice(-1).pop() === 0) {
  129. list.pop();
  130. if (list.slice(-1).pop() === 0) {
  131. list.pop();
  132. }
  133. }
  134. return ` v${list.map((item) => item.toString()).join('.')}`;
  135. }
  136. }
  137. return '';
  138. };
  139. program.format = `PaddlePaddle${formatVersion(program.desc.version)}`;
  140. const variables = new Set();
  141. for (const block of program.desc.blocks) {
  142. const blockVars = new Set();
  143. for (const variable of block.vars) {
  144. if (variable.persistable && variable.type &&
  145. variable.type.type !== paddle.DataType.FETCH_LIST &&
  146. variable.type.type !== paddle.DataType.FEED_MINIBATCH) {
  147. blockVars.add(variable.name);
  148. }
  149. }
  150. for (const op of block.ops) {
  151. for (const input of op.inputs) {
  152. for (const argument of input.arguments) {
  153. if (blockVars.has(argument)) {
  154. variables.add(argument);
  155. }
  156. }
  157. }
  158. }
  159. }
  160. program.vars = Array.from(variables).sort();
  161. return program;
  162. };
  163. const loadParams = (stream) => {
  164. const params = [];
  165. while (stream.position < stream.length) {
  166. const tensor = paddle.Utility.openTensorDesc(stream);
  167. params.push(tensor);
  168. }
  169. return params;
  170. };
  171. const mapParams = (params, program) => {
  172. const weights = new Map();
  173. const vars = program.vars.slice();
  174. for (const param of params) {
  175. weights.set(vars.shift(), param);
  176. }
  177. return weights;
  178. };
  179. switch (context.type) {
  180. case 'paddle.pickle': {
  181. const target = context.value;
  182. return new paddle.Model(metadata, target.format, null, target.weights);
  183. }
  184. case 'paddle.entries': {
  185. const target = context.value;
  186. target.read();
  187. return new paddle.Model(metadata, target.format, null, target.weights);
  188. }
  189. case 'paddle.params': {
  190. const file = identifier === 'params' ? 'model' : `${base}.pdmodel`;
  191. const params = loadParams(context.stream);
  192. try {
  193. const content = await context.fetch(file);
  194. const program = await openProgram(content, 'paddle.pb');
  195. const weights = mapParams(params, program);
  196. return new paddle.Model(metadata, program.format, program.desc, weights);
  197. } catch {
  198. const weights = new Map(params.map((param, index) => [index.toString(), param]));
  199. return new paddle.Model(metadata, 'PaddlePaddle Inference Weights', null, weights);
  200. }
  201. }
  202. case 'paddle.pb':
  203. case 'paddle.pbtxt': {
  204. const loadEntries = async (context, program) => {
  205. const promises = program.vars.map((name) => context.fetch(name).then((context) => context.stream).catch(() => null));
  206. const streams = await Promise.all(promises);
  207. const params = streams.map((stream) => stream ? paddle.Utility.openTensorDesc(stream) : null);
  208. const weights = mapParams(params, program);
  209. return new paddle.Model(metadata, program.format, program.desc, weights);
  210. };
  211. const openNumPyArrayPickle = (stream) => {
  212. const execution = new python.Execution();
  213. const pickle = execution.__import__('pickle');
  214. const unpickler = new pickle.Unpickler(stream);
  215. const obj = unpickler.load();
  216. const container = new paddle.Pickle(obj);
  217. return container.weights || new Map();
  218. };
  219. const program = await openProgram(context, context.type);
  220. if (extension === 'pdmodel') {
  221. try {
  222. const name = `${base}.pdiparams`;
  223. const content = await context.fetch(name);
  224. const params = loadParams(content.stream);
  225. const weights = mapParams(params, program);
  226. return new paddle.Model(metadata, program.format, program.desc, weights);
  227. } catch {
  228. try {
  229. const name = `${base}.pdparams`;
  230. const content = await context.fetch(name);
  231. const weights = openNumPyArrayPickle(content.stream);
  232. try {
  233. const name = `${base}.pdopt`;
  234. const content = await context.fetch(name);
  235. for (const [name, value] of openNumPyArrayPickle(content.stream)) {
  236. if (!weights.has(name)) {
  237. weights.set(name, value);
  238. }
  239. }
  240. return new paddle.Model(metadata, program.format, program.desc, weights);
  241. } catch {
  242. return new paddle.Model(metadata, program.format, program.desc, weights);
  243. }
  244. } catch {
  245. try {
  246. const name = `${base}.pdopt`;
  247. const content = await context.fetch(name);
  248. const weights = openNumPyArrayPickle(content.stream);
  249. return new paddle.Model(metadata, program.format, program.desc, weights);
  250. } catch {
  251. return loadEntries(context, program);
  252. }
  253. }
  254. }
  255. }
  256. if (identifier === 'model') {
  257. try {
  258. const content = await context.fetch('params');
  259. const params = loadParams(content.stream);
  260. const weights = mapParams(params, program);
  261. return new paddle.Model(metadata, program.format, program.desc, weights);
  262. } catch {
  263. return loadEntries(context, program);
  264. }
  265. }
  266. return loadEntries(context, program);
  267. }
  268. default: {
  269. throw new paddle.Error(`Unsupported PaddlePaddle format '${context.type}'.`);
  270. }
  271. }
  272. }
  273. }
  274. }
  275. };
  276. paddle.Model = class {
  277. constructor(metadata, format, desc, tensors) {
  278. desc = desc && Array.isArray(desc.blocks) ? desc : { blocks: [null] };
  279. this.format = format;
  280. this.modules = desc.blocks.map((block) => new paddle.Graph(metadata, block, tensors));
  281. }
  282. };
  283. paddle.Graph = class {
  284. constructor(metadata, block, tensors) {
  285. this.nodes = [];
  286. this.inputs = [];
  287. this.outputs = [];
  288. if (block) {
  289. this.name = block.idx.toString();
  290. const values = new Map();
  291. if (block.kind === 'block') {
  292. for (const [name, input] of block.argInputs) {
  293. const [parameter, tensorType] = input;
  294. const value = new paddle.Value(name, tensorType, null, null);
  295. values.set(name, value);
  296. this.inputs.push(new paddle.Argument(parameter, [value]));
  297. }
  298. }
  299. for (const variable of block.vars) {
  300. const type = variable.type && variable.type.type && variable.type.dense_tensor && variable.type.dense_tensor.tensor ? paddle.Utility.createTensorType(variable.type.dense_tensor.tensor.data_type, variable.type.dense_tensor.tensor.dims) : null;
  301. const tensor = variable.persistable && variable.type && variable.type.type !== paddle.DataType.FETCH_LIST && variable.type.type !== paddle.DataType.FEED_MINIBATCH ? (tensors.get(variable.name) || new paddle.Tensor(type)) : null;
  302. values.set(variable.name, new paddle.Value(variable.name, type, tensor));
  303. }
  304. const scope = {};
  305. for (let i = 0; i < block.ops.length; i++) {
  306. for (const input of block.ops[i].inputs) {
  307. input.arguments = input.arguments.map((argument) => scope[argument] ? scope[argument] : argument);
  308. }
  309. for (const output of block.ops[i].outputs) {
  310. output.arguments = output.arguments.map((argument) => {
  311. if (scope[argument]) {
  312. const next = `${argument}\n${i}`; // custom argument id
  313. scope[argument] = next;
  314. return next;
  315. }
  316. scope[argument] = argument;
  317. return argument;
  318. });
  319. }
  320. }
  321. for (const op of block.ops) {
  322. for (const input of op.inputs) {
  323. for (const name of input.arguments) {
  324. if (!values.has(name)) {
  325. values.set(name, new paddle.Value(name, null, null));
  326. }
  327. }
  328. }
  329. for (const output of op.outputs) {
  330. for (const name of output.arguments) {
  331. if (output.values && output.values.has(name)) {
  332. values.set(name, output.values.get(name));
  333. }
  334. if (!values.has(name)) {
  335. values.set(name, new paddle.Value(name, null, null));
  336. }
  337. }
  338. }
  339. }
  340. let lastNode = null;
  341. let lastOutput = null;
  342. for (const op of block.ops) {
  343. if (op.type === 'feed') {
  344. let name = '';
  345. const attr = op.attrs.find((attr) => attr.name === 'col');
  346. if (attr) {
  347. if (op.kind === 'op') {
  348. name = attr.irValue.toString();
  349. } else {
  350. name = attr.i.toString();
  351. }
  352. }
  353. const argument = new paddle.Argument(name, op.outputs[0].arguments.map((id) => values.get(id)));
  354. this.inputs.push(argument);
  355. } else if (op.type === 'fetch') {
  356. let name = '';
  357. const attr = op.attrs.find((attr) => attr.name === 'col');
  358. if (attr) {
  359. if (op.kind === 'op') {
  360. name = attr.irValue.toString();
  361. } else {
  362. name = attr.i.toString();
  363. }
  364. }
  365. const argument = new paddle.Argument(name, op.inputs[0].arguments.map((id) => values.get(id)));
  366. this.outputs.push(argument);
  367. } else {
  368. const node = new paddle.Node(metadata, op, values);
  369. if (op.inputs.length === 1 && op.inputs[0].arguments.length === 1 &&
  370. op.outputs.length >= 1 && op.outputs[0].arguments.length === 1 &&
  371. op.inputs[0].arguments[0].split('\n').shift() === op.outputs[0].arguments[0].split('\n').shift() &&
  372. lastNode &&
  373. lastOutput === op.inputs[0].arguments[0].split('\n').shift()) {
  374. lastNode.chain.push(node);
  375. } else {
  376. this.nodes.push(node);
  377. lastNode = null;
  378. lastOutput = null;
  379. if (op.outputs.length === 1 && op.outputs[0].arguments.length === 1) {
  380. lastNode = node;
  381. lastOutput = op.outputs[0].arguments[0].split('\n').shift();
  382. }
  383. }
  384. }
  385. }
  386. } else {
  387. const values = new Map();
  388. const ops = new Map();
  389. for (const [name, tensor] of tensors) {
  390. values.set(name, new paddle.Value(name, tensor.type, tensor));
  391. const separator = name.indexOf('.') === -1 ? '_' : '.';
  392. const regex = /(.*)_((w_attr|scale|weights|offset|b|w|b_attr)_(moment|beta|velocity|mean_square|mean_grad).*)/;
  393. let parts = [];
  394. if (separator === '.') {
  395. parts = name.split(separator);
  396. } else if (regex.test(name)) {
  397. parts = regex.exec(name).slice(1, 3);
  398. } else {
  399. parts = ['', name];
  400. }
  401. const parameter_name = parts.pop();
  402. const op_name = parts.join(separator);
  403. if (!ops.has(op_name)) {
  404. ops.set(op_name, { name: op_name, type: 'Weights', inputs: [] });
  405. }
  406. const op = ops.get(op_name);
  407. op.inputs.push({ parameter: parameter_name, arguments: [name] });
  408. }
  409. for (const op of Array.from(ops.values())) {
  410. this.nodes.push(new paddle.Node(metadata, op, values));
  411. }
  412. }
  413. }
  414. };
  415. paddle.Argument = class {
  416. constructor(name, value, type, visible) {
  417. this.name = name;
  418. this.value = value;
  419. if (type) {
  420. this.type = type;
  421. }
  422. if (visible === false) {
  423. this.visible = visible;
  424. }
  425. }
  426. };
  427. paddle.Value = class {
  428. constructor(name, type, initializer = null) {
  429. if (typeof name !== 'string') {
  430. throw new paddle.Error(`Invalid value identifier '${JSON.stringify(name)}'.`);
  431. }
  432. this.name = name;
  433. this.type = !type && initializer ? initializer.type : type;
  434. this.initializer = initializer;
  435. }
  436. };
  437. paddle.Node = class {
  438. constructor(metadata, op, values) {
  439. const type = op.type;
  440. this.type = metadata.type(type) || { name: type };
  441. this.name = op.name || '';
  442. this.description = op.description || '';
  443. this.identifier = op.identifier || '';
  444. this.attributes = [];
  445. this.inputs = [];
  446. this.outputs = [];
  447. this.chain = [];
  448. if (op.attrs) {
  449. this.attributes = op.attrs.map((attr) => {
  450. const name = attr.name;
  451. const meta = metadata.attribute(this.type.name, name);
  452. let value = '?';
  453. let visible = true;
  454. let type = null;
  455. switch (attr.type) {
  456. case paddle.AttributeType.STRING:
  457. type = 'string';
  458. value = attr.s;
  459. break;
  460. case paddle.AttributeType.STRINGS:
  461. type = 'string[]';
  462. value = Array.from(attr.strings);
  463. break;
  464. case paddle.AttributeType.BOOLEAN:
  465. type = 'boolean';
  466. value = attr.b;
  467. break;
  468. case paddle.AttributeType.BOOLEANS:
  469. type = 'boolean[]';
  470. value = attr.bools ? Array.from(attr.bools) : attr.bools;
  471. break;
  472. case paddle.AttributeType.FLOAT:
  473. type = 'float32';
  474. value = attr.f;
  475. break;
  476. case paddle.AttributeType.FLOATS:
  477. type = 'float32[]';
  478. value = attr.floats ? Array.from(attr.floats) : attr.floats;
  479. break;
  480. case paddle.AttributeType.FLOAT64:
  481. type = 'float64';
  482. value = attr.float64;
  483. break;
  484. case paddle.AttributeType.FLOAT64S:
  485. type = 'float64[]';
  486. value = attr.float64s ? Array.from(attr.float64s) : attr.float64s;
  487. break;
  488. case paddle.AttributeType.INT:
  489. type = 'int32';
  490. value = attr.i;
  491. break;
  492. case paddle.AttributeType.INTS:
  493. type = 'int32[]';
  494. value = attr.ints ? Array.from(attr.ints) : attr.ints;
  495. break;
  496. case paddle.AttributeType.LONG:
  497. type = 'int64';
  498. break;
  499. case paddle.AttributeType.LONGS:
  500. type = 'int64[]';
  501. break;
  502. case 1000: // ir
  503. type = attr.irType;
  504. value = attr.irValue;
  505. break;
  506. case 1001: // graph
  507. type = 'graph';
  508. value = new paddle.Graph(metadata, attr.block, attr.vars);
  509. break;
  510. default:
  511. break;
  512. }
  513. switch (name) {
  514. case 'use_mkldnn':
  515. case 'use_cudnn':
  516. case 'op_callstack':
  517. case 'op_role':
  518. case 'op_role_var':
  519. case 'op_namescope':
  520. case 'is_test':
  521. visible = false;
  522. break;
  523. default:
  524. break;
  525. }
  526. if (meta) {
  527. if (meta.default !== undefined) {
  528. const defaultValue = meta.default;
  529. if (defaultValue === value) {
  530. visible = false;
  531. } else if (Array.isArray(value) && Array.isArray(defaultValue) && value.length === defaultValue.length) {
  532. if (value.every((item, index) => item === defaultValue[index])) {
  533. visible = false;
  534. }
  535. }
  536. }
  537. }
  538. return new paddle.Argument(name, value, type, visible);
  539. });
  540. }
  541. if (op.inputs) {
  542. for (const input of op.inputs) {
  543. if (input.arguments.length > 0) {
  544. this.inputs.push(new paddle.Argument(input.parameter, input.arguments.map((name) => values.get(name))));
  545. }
  546. }
  547. }
  548. if (op.outputs) {
  549. for (const output of op.outputs) {
  550. if (output.arguments.length > 0) {
  551. this.outputs.push(new paddle.Argument(output.parameter, output.arguments.map((name) => values.get(name))));
  552. }
  553. }
  554. }
  555. const updates = [
  556. [this.inputs, 'X'],
  557. [this.inputs, 'Input'],
  558. [this.outputs, 'Y'],
  559. [this.outputs, 'Out']
  560. ];
  561. for (const [list, name] of updates) {
  562. let item = null;
  563. for (let i = 0; i < list.length; i++) {
  564. if (list[i].name === name) {
  565. item = list[i];
  566. list.splice(i, 1);
  567. break;
  568. }
  569. }
  570. if (item) {
  571. list.splice(0, 0, item);
  572. }
  573. }
  574. }
  575. };
  576. paddle.Tensor = class {
  577. constructor(type, data, category = '') {
  578. this.type = type;
  579. this.values = data;
  580. this.category = category;
  581. }
  582. };
  583. paddle.TensorType = class {
  584. constructor(dataType, shape, layout, denotation) {
  585. this.dataType = dataType;
  586. this.shape = shape;
  587. this.layout = layout;
  588. this.denotation = denotation;
  589. }
  590. toString() {
  591. return this.dataType + this.shape.toString();
  592. }
  593. };
  594. paddle.TensorShape = class {
  595. constructor(dimensions) {
  596. dimensions = dimensions.map((dim) => typeof dim === 'bigint' ? dim.toNumber() : dim);
  597. this.dimensions = dimensions.map((dimension) => {
  598. return dimension === -1 ? '?' : dimension;
  599. });
  600. }
  601. toString() {
  602. return (this.dimensions && this.dimensions.length) ? (`[${this.dimensions.join(',')}]`) : '';
  603. }
  604. };
  605. paddle.Entries = class {
  606. static async open(context) {
  607. let entries = await context.peek('zip');
  608. if (entries instanceof Map === false) {
  609. entries = await context.peek('tar');
  610. }
  611. if (entries instanceof Map) {
  612. entries = Array.from(entries);
  613. entries = new Map(entries.filter(([name]) => !name.endsWith('/') && !name.split('/').pop().startsWith('.')).slice());
  614. if (entries.size > 2 && Array.from(entries).every(([name, value]) => name.split('_').length > 0 && value.peek(16).every((value) => value === 0x00))) {
  615. return new paddle.Entries(entries);
  616. }
  617. }
  618. return null;
  619. }
  620. constructor(data) {
  621. this.name = 'paddle.entries';
  622. this.format = 'PaddlePaddle Weights';
  623. this.data = data;
  624. }
  625. read() {
  626. if (this.data) {
  627. let rootFolder = null;
  628. for (const [name] of this.data) {
  629. if (!name.startsWith('.') || name.startsWith('./')) {
  630. const parts = name.split('/');
  631. let folder = '';
  632. if (parts.length > 2 && parts[0] === '.') {
  633. folder = `./${parts[1]}/`;
  634. } else if (parts.length > 1) {
  635. folder = `${parts[0]}/`;
  636. }
  637. if (rootFolder !== null && rootFolder !== '' && folder !== rootFolder) {
  638. rootFolder = '';
  639. } else {
  640. rootFolder = folder;
  641. }
  642. }
  643. }
  644. this.weights = new Map();
  645. for (const [name, stream] of this.data) {
  646. if (name.startsWith(rootFolder)) {
  647. const key = name.substring(rootFolder.length);
  648. const tensor = paddle.Utility.openTensorDesc(stream);
  649. this.weights.set(key, tensor);
  650. }
  651. }
  652. delete this.data;
  653. }
  654. }
  655. };
  656. paddle.Pickle = class {
  657. static async open(context) {
  658. const obj = await context.peek('pkl');
  659. const container = new paddle.Pickle(obj);
  660. if (container.weights !== null) {
  661. return container;
  662. }
  663. return null;
  664. }
  665. constructor(obj) {
  666. this.name = 'paddle.pickle';
  667. this.format = 'PaddlePaddle Pickle';
  668. this._weights = null;
  669. if (obj && !Array.isArray(obj) && (obj instanceof Map || Object(obj) === obj)) {
  670. const entries = (obj) => {
  671. if (obj instanceof Map) {
  672. return Array.from(obj);
  673. } else if (Object(obj) === obj) {
  674. return Object.entries(obj);
  675. }
  676. return [];
  677. };
  678. const filter = (obj) => {
  679. const list = [];
  680. if (obj && !Array.isArray(obj)) {
  681. for (const [name, value] of entries(obj)) {
  682. if (name !== 'StructuredToParameterName@@') {
  683. const obj = value && Array.isArray(value) && value.length === 2 && value[0] === name ? value[1] : value;
  684. if (obj && !Array.isArray(obj) && obj.__class__ && obj.__class__.__module__ === 'numpy' && obj.__class__.__name__ === 'ndarray') {
  685. list.push([name, obj]);
  686. }
  687. }
  688. }
  689. }
  690. return list;
  691. };
  692. const weights = filter(obj);
  693. if (weights.length > 0) {
  694. this._weights = weights;
  695. } else {
  696. const list = entries(obj);
  697. if (list.filter(([name]) => name !== 'StructuredToParameterName@@').length === 1) {
  698. const weights = filter(list[0][1]);
  699. if (weights.length > 0) {
  700. this._weights = weights;
  701. }
  702. }
  703. if (this._weights === null && list.filter(([name]) => name === 'StructuredToParameterName@@').length > 0) {
  704. this._weights = [];
  705. }
  706. }
  707. }
  708. }
  709. get weights() {
  710. if (this._weights && Array.isArray(this._weights)) {
  711. const weights = new Map();
  712. for (const [name, value] of this._weights) {
  713. const type = new paddle.TensorType(value.dtype.__name__, new paddle.TensorShape(value.shape));
  714. const data = value.data;
  715. const tensor = new paddle.Tensor(type, data, 'NumPy Array');
  716. weights.set(name, tensor);
  717. }
  718. this._weights = weights;
  719. }
  720. return this._weights;
  721. }
  722. };
  723. paddle.NaiveBuffer = class {
  724. static async open(context) {
  725. const stream = context.stream;
  726. if (stream && stream.length > 4) {
  727. const buffer = stream.peek(4);
  728. if (buffer[0] > 2 || buffer[1] !== 0x00 || buffer[2] !== 0x76 || buffer[3] !== 0x32) {
  729. if (context.identifier === '__model__.nb') {
  730. return new paddle.NaiveBuffer('paddle.naive.model', stream, -1);
  731. }
  732. if (context.identifier === 'param.nb') {
  733. return new paddle.NaiveBuffer('paddle.naive.param', stream, -1);
  734. }
  735. }
  736. if (buffer[1] === 0x00 && buffer[0] <= 2) {
  737. return new paddle.NaiveBuffer('paddle.naive', stream, buffer[0]);
  738. }
  739. }
  740. return null;
  741. }
  742. constructor(name, stream, meta_version) {
  743. this.name = name;
  744. this.stream = stream;
  745. this.meta_version = meta_version;
  746. }
  747. read() {
  748. const reader = base.BinaryReader.open(this.stream);
  749. if (this.meta_version >= 2) {
  750. reader.skip(2);
  751. }
  752. const decoder = new TextDecoder('utf-8');
  753. const opt_version = reader.read(16);
  754. const version = decoder.decode(opt_version.slice(0, opt_version.indexOf(0x00)));
  755. this.format = `Paddle Lite${version && version.match(/^v\d+\.\d+\.\d+$/) ? ` ${version}` : ''}`;
  756. const topo_size = reader.uint64().toNumber();
  757. const openProgramDesc = (buffer) => {
  758. const reader = flatbuffers.BinaryReader.open(buffer);
  759. return paddle.schema.ProgramDesc.create(reader);
  760. };
  761. const openParamDesc = (buffer) => {
  762. const reader = flatbuffers.BinaryReader.open(buffer);
  763. return paddle.schema.ParamDesc.create(reader);
  764. };
  765. switch (this.meta_version) {
  766. case -1: {
  767. throw new paddle.Error('Paddle Lite naive buffer format is deprecated.');
  768. }
  769. case 0:
  770. case 1: {
  771. throw new paddle.Error(`Paddle Lite meta format '${this.meta_version}' is deprecated.`);
  772. }
  773. case 2: {
  774. const topo_data = new Uint8Array(topo_size);
  775. topo_data.set(reader.read(topo_size), 0);
  776. this.model = openProgramDesc(topo_data);
  777. reader.uint16(); // version
  778. reader.uint16(); // meta_size
  779. const header_size = reader.uint16();
  780. const params_size = reader.uint16();
  781. reader.uint32(); // max_tensor_size
  782. reader.skip(header_size - 6);
  783. this.weights = new Map();
  784. for (let i = 0; i < params_size; i++) {
  785. const total_size = reader.uint32();
  786. const offset = reader.uint32();
  787. const param_bytes = total_size - offset;
  788. const param_data = reader.read(param_bytes);
  789. const desc = openParamDesc(param_data);
  790. const data = desc.variable.data;
  791. const data_type = desc.variable.data_type;
  792. const dim = desc.variable.dim;
  793. const type = paddle.Utility.createTensorType(data_type, dim);
  794. const tensor = new paddle.Tensor(type, data);
  795. this.weights.set(desc.name, tensor);
  796. }
  797. break;
  798. }
  799. default: {
  800. throw new paddle.Error(`Unsupported Paddle Lite naive buffer meta format '${this.meta_version}'.`);
  801. }
  802. }
  803. delete this.stream;
  804. }
  805. };
  806. paddle.Utility = class {
  807. static createTensorType(data_type, shape) {
  808. if (!paddle.Utility._dataTypes) {
  809. const length = Math.max.apply(null, Object.entries(paddle.DataType).map(([, value]) => value));
  810. paddle.Utility._dataTypes = new Array(length);
  811. const types = new Map([
  812. ['bool', 'boolean'],
  813. ['bf16', 'bfloat16'], ['fp16', 'float16'], ['fp32', 'float32'], ['fp64', 'float64'],
  814. ['fp8_e4m3fn', 'float8e4m3fn'], ['fp8_e5m2', 'float8e5m2']
  815. ]);
  816. for (const [name, index] of Object.entries(paddle.DataType)) {
  817. const key = name.toLowerCase();
  818. paddle.Utility._dataTypes[index] = types.has(key) ? types.get(key) : key;
  819. }
  820. }
  821. const dataType = data_type < paddle.Utility._dataTypes.length ? paddle.Utility._dataTypes[data_type] : '?';
  822. return new paddle.TensorType(dataType, new paddle.TensorShape(shape));
  823. }
  824. static openTensorDesc(stream) {
  825. const signature = stream.read(16);
  826. if (!signature.every((value) => value === 0x00)) {
  827. throw new paddle.Error('Invalid paddle.TensorDesc signature.');
  828. }
  829. const length = base.BinaryReader.open(stream.read(4)).uint32();
  830. const buffer = stream.read(length);
  831. const reader = protobuf.BinaryReader.open(buffer);
  832. const tensorDesc = paddle.proto.VarType.TensorDesc.decode(reader);
  833. const dims = tensorDesc.dims.map((dim) => dim.toNumber());
  834. const size = dims.reduce((a, b) => a * b, 1);
  835. let itemsize = 0;
  836. switch (tensorDesc.data_type) {
  837. case paddle.DataType.BOOL: itemsize = 1; break;
  838. case paddle.DataType.FP16: itemsize = 2; break;
  839. case paddle.DataType.FP32: itemsize = 4; break;
  840. case paddle.DataType.FP64: itemsize = 8; break;
  841. case paddle.DataType.INT8: itemsize = 1; break;
  842. case paddle.DataType.INT16: itemsize = 2; break;
  843. case paddle.DataType.INT32: itemsize = 4; break;
  844. case paddle.DataType.INT64: itemsize = 8; break;
  845. case paddle.DataType.UINT8: itemsize = 1; break;
  846. default: throw new paddle.Error(`Invalid inference params data type '${tensorDesc.data_type}'.`);
  847. }
  848. const type = paddle.Utility.createTensorType(tensorDesc.data_type, tensorDesc.dims);
  849. const data = stream.read(itemsize * size);
  850. return new paddle.Tensor(type, data);
  851. }
  852. };
  853. paddle.DataType = {
  854. BOOL: 0,
  855. INT16: 1,
  856. INT32: 2,
  857. INT64: 3,
  858. FP16: 4,
  859. FP32: 5,
  860. FP64: 6,
  861. DENSE_TENSOR: 7,
  862. SELECTED_ROWS: 8,
  863. FEED_MINIBATCH: 9,
  864. FETCH_LIST: 10,
  865. STEP_SCOPES: 11,
  866. LOD_RANK_TABLE: 12,
  867. DENSE_TENSOR_ARRAY: 13,
  868. PLACE_LIST: 14,
  869. READER: 15,
  870. RAW: 17,
  871. TUPLE: 18,
  872. SIZE_T: 19,
  873. UINT8: 20,
  874. INT8: 21,
  875. BF16: 22,
  876. COMPLEX64: 23,
  877. COMPLEX128: 24,
  878. STRING: 25,
  879. STRINGS: 26,
  880. FP8_E4M3FN: 32,
  881. FP8_E5M2: 33,
  882. };
  883. paddle.AttributeType = {
  884. INT: 0,
  885. FLOAT: 1,
  886. STRING: 2,
  887. INTS: 3,
  888. FLOATS: 4,
  889. STRINGS: 5,
  890. BOOLEAN: 6,
  891. BOOLEANS: 7,
  892. BLOCK: 8,
  893. LONG: 9,
  894. BLOCKS: 10,
  895. LONGS: 11,
  896. FLOAT64S: 12,
  897. VAR: 13,
  898. VARS: 14,
  899. FLOAT64: 15
  900. };
  901. paddle.IR = class {
  902. constructor(obj) {
  903. this._names = new Map();
  904. this._crossRegionInputs = new Map();
  905. this.base_code = obj.base_code;
  906. this.version = obj.base_code.version;
  907. const program = obj.program;
  908. const regions = [];
  909. for (const region of program.regions) {
  910. regions.push(this.region(region));
  911. }
  912. const [programRegion] = regions;
  913. this.desc = programRegion;
  914. this.tensors = new Map();
  915. }
  916. region(value) {
  917. const obj = {};
  918. obj.kind = 'region';
  919. obj.name = value['#'];
  920. obj.idx = value['#'];
  921. obj.vars = new Map();
  922. obj.blocks = [];
  923. for (const block of value.blocks) {
  924. obj.blocks.push(this.block(block));
  925. }
  926. const [block] = obj.blocks;
  927. obj.block = block;
  928. return obj;
  929. }
  930. block(value) {
  931. const obj = {};
  932. obj.kind = 'block';
  933. obj.name = value['#'];
  934. obj.idx = value['#'];
  935. obj.vars = new Map();
  936. obj.argInputs = new Map();
  937. if (value.args) {
  938. for (const input of value.args) {
  939. const [, type] = input.TT && input.TT['#'] ? input.TT['#'].split('.') : null;
  940. if (type === 't_dtensor') {
  941. const [parameter, name,] = this.getParaName(input);
  942. const tensorType = this.createTensorType(input);
  943. obj.argInputs.set(name, [parameter, tensorType]);
  944. }
  945. }
  946. }
  947. let inputNames = new Set();
  948. let outputNames = new Set();
  949. obj.ops = [];
  950. for (const op of value.ops) {
  951. const irOp = this.op(op);
  952. obj.ops.push(irOp);
  953. inputNames = new Set([...inputNames, ...irOp.inputNames]);
  954. outputNames = new Set([...outputNames, ...irOp.outputNames]);
  955. }
  956. const missInputs = new Set([...inputNames].filter((item) => !outputNames.has(item)));
  957. if (missInputs) {
  958. for (const name of missInputs) {
  959. const output = this.getCrossInput(name);
  960. if (output) {
  961. obj.argInputs.set(name, [output.parameter, output.tensorType]);
  962. }
  963. }
  964. }
  965. return obj;
  966. }
  967. op(op) {
  968. const obj = {};
  969. obj.kind = 'op';
  970. const opInfo = this.getOpInfo(op);
  971. obj.name = opInfo.fullName;
  972. obj.type = opInfo.type;
  973. obj.identifier = opInfo.rawType;
  974. obj.attrs = [];
  975. for (const [idx, value] of Object.entries(op.A)) {
  976. obj.attrs.push(this.attr(idx, value, opInfo));
  977. }
  978. if (op.regions !== undefined) {
  979. for (const region of op.regions) {
  980. const regionAttr = this.region(region);
  981. obj.attrs.push(this.attr(null, regionAttr, null));
  982. }
  983. }
  984. const inputNames = new Set();
  985. const outputNames = new Set();
  986. const createInput = (input, opInfo) => {
  987. const [parameterName, inputName] = this.getParaName(input, opInfo.namePrefix);
  988. return { arguments: [inputName], parameter: parameterName };
  989. };
  990. const inputs = [];
  991. if (op.I) {
  992. const inputArray = Array.isArray(op.I) ? op.I : [op.I];
  993. for (const input of inputArray) {
  994. inputs.push(createInput(input, opInfo));
  995. const [, name] = this.getParaName(input, opInfo.namePrefix);
  996. inputNames.add(name);
  997. }
  998. }
  999. const createOutput = (output, opInfo, idx, outputAttr) => {
  1000. const [parameterName, outputName] = this.getParaName(output, opInfo.namePrefix);
  1001. const valuesMap = new Map();
  1002. let tType = null;
  1003. const [, typeType] = output.TT['#'].split('.');
  1004. if (typeType === 't_dtensor') {
  1005. const denotation = this.getOutputAttr(opInfo, idx, outputAttr);
  1006. const tensorType = this.createTensorType(output, denotation);
  1007. valuesMap.set(outputName, new paddle.Value(outputName, tensorType, null));
  1008. tType = tensorType;
  1009. } else {
  1010. valuesMap.set(outputName, new paddle.Value(outputName, null, null, null));
  1011. }
  1012. return {
  1013. arguments: [outputName],
  1014. parameter: parameterName,
  1015. tensorType: tType,
  1016. values: valuesMap
  1017. };
  1018. };
  1019. const outputs = [];
  1020. if (op.O) {
  1021. const outputArray = Array.isArray(op.O) ? op.O : [op.O];
  1022. for (const [idx, output] of Object.entries(outputArray)) {
  1023. const irOutput = createOutput(output, opInfo, idx, op.OA);
  1024. outputs.push(irOutput);
  1025. const [, name, isNegative] = this.getParaName(output, opInfo.namePrefix);
  1026. outputNames.add(name);
  1027. if (!isNegative && !this.hasCrossInput(name)) {
  1028. this.addCrossInput(name, irOutput);
  1029. }
  1030. }
  1031. }
  1032. if (op.regions) {
  1033. const collectRegions = (irReader, regions) => {
  1034. let inputs = new Map();
  1035. let outputs = new Map();
  1036. for (const region of regions) {
  1037. for (const block of region.blocks) {
  1038. for (const op of block.ops) {
  1039. const opInfo = this.getOpInfo(op);
  1040. if (op.I) {
  1041. const opInputs = Array.isArray(op.I) ? op.I : [op.I];
  1042. for (const input of opInputs) {
  1043. const [, name, isNegative] = irReader.getParaName(input, opInfo.namePrefix);
  1044. if (!isNegative && !inputs.has(name)) {
  1045. inputs.set(name, [input, opInfo]);
  1046. }
  1047. }
  1048. }
  1049. if (op.O) {
  1050. const opOutputs = Array.isArray(op.O) ? op.O : [op.O];
  1051. for (const [idx, output] of Object.entries(opOutputs)) {
  1052. const [, name, isNegative] = irReader.getParaName(output, opInfo.namePrefix);
  1053. if (!isNegative && !outputs.has(name)) {
  1054. outputs.set(name, [output, opInfo, idx, op.OA]);
  1055. }
  1056. }
  1057. }
  1058. if (op.regions) {
  1059. const [subInputs, subOutputs] = collectRegions(irReader, op.regions);
  1060. inputs = new Map([...inputs, ...subInputs]);
  1061. outputs = new Map([...outputs, ...subOutputs]);
  1062. }
  1063. }
  1064. }
  1065. }
  1066. return [inputs, outputs];
  1067. };
  1068. const [subInputs, subOutputs] = collectRegions(this, op.regions);
  1069. for (const [name, inputArgs] of subInputs) {
  1070. if (!inputNames.has(name) && !subOutputs.has(name)) {
  1071. const [input, opInfo] = inputArgs;
  1072. inputs.push(createInput(input, opInfo));
  1073. inputNames.add(name);
  1074. }
  1075. }
  1076. for (const [name, outputArgs] of subOutputs) {
  1077. if (!outputNames.has(name) && !subInputs.has(name)) {
  1078. const [output, opInfo, idx, oa] = outputArgs;
  1079. outputs.push(createOutput(output, opInfo, idx, oa));
  1080. outputNames.add(name);
  1081. }
  1082. }
  1083. }
  1084. obj.inputs = inputs;
  1085. obj.outputs = outputs;
  1086. obj.inputNames = inputNames;
  1087. obj.outputNames = outputNames;
  1088. return obj;
  1089. }
  1090. attr(idx, value, opInfo) {
  1091. const obj = {};
  1092. obj.kind = 'attr';
  1093. if (value.kind === 'region') {
  1094. obj.name = value.name;
  1095. obj.type = 1001; // graph
  1096. obj.block = value.block;
  1097. obj.vars = value.vars;
  1098. } else {
  1099. const [attrName, attrType, attrValue] = this.getAttr(opInfo, idx, value);
  1100. obj.name = attrName;
  1101. obj.type = 1000; // ir
  1102. obj.irType = attrType;
  1103. obj.irValue = attrValue;
  1104. }
  1105. return obj;
  1106. }
  1107. getParaName(tensor, namePrefix) {
  1108. let idx = '';
  1109. if ('%' in tensor) {
  1110. idx = tensor['%'];
  1111. } else if ('#' in tensor) {
  1112. idx = tensor['#'];
  1113. }
  1114. if (tensor.TT && !this._names.has(idx)) {
  1115. const prefix = namePrefix || idx;
  1116. this._names.set(idx, `${prefix}`);
  1117. }
  1118. return [`${idx}`, this._names.has(idx) ? this._names.get(idx) : `${idx}`, Number.isInteger(idx) ? idx < 0 : false];
  1119. }
  1120. hasCrossInput(name) {
  1121. return this._crossRegionInputs.has(name);
  1122. }
  1123. getCrossInput(name) {
  1124. return this._crossRegionInputs.has(name) ? this._crossRegionInputs.get(name) : null;
  1125. }
  1126. addCrossInput(name, input) {
  1127. this._crossRegionInputs.set(name, input);
  1128. }
  1129. getOpInfo(op) {
  1130. const obj = {};
  1131. obj.rawType = op['#'];
  1132. obj._type = op['#'];
  1133. obj._name = op['#'];
  1134. switch (op['#']) {
  1135. case 'p': {
  1136. obj.kind = 'p';
  1137. [obj._name] = op.A.slice(3);
  1138. obj._type = this.getCompressOp(obj._type);
  1139. op.OA = [...op.OA, ...op.A];
  1140. obj.type = obj._type;
  1141. obj.name = obj._type;
  1142. obj.fullName = obj._type;
  1143. obj.namePrefix = obj._name;
  1144. break;
  1145. }
  1146. case '1.data': {
  1147. obj.kind = 'data';
  1148. [obj._opKey, obj._opType] = obj._name.split('.');
  1149. let prefix = '';
  1150. for (const attr of op.A) {
  1151. if (attr.N === 'name') {
  1152. prefix = attr.AT.D;
  1153. break;
  1154. }
  1155. }
  1156. obj._attr = op.A;
  1157. obj.type = obj._opType;
  1158. obj.name = obj._opType;
  1159. obj.fullName = `${this.getCompressOp(obj._opKey)}.${obj._opType}`;
  1160. obj.namePrefix = prefix;
  1161. break;
  1162. }
  1163. default: {
  1164. obj.kind = '';
  1165. [obj._opKey, obj._opType] = obj._name.split('.');
  1166. obj.type = obj._opType;
  1167. obj.name = obj._opType;
  1168. obj.fullName = `${this.getCompressOp(obj._opKey)}.${obj._opType}`;
  1169. obj.namePrefix = null;
  1170. break;
  1171. }
  1172. }
  1173. return obj;
  1174. }
  1175. createTensorType(data, denotation) {
  1176. const [type, dims, layout, ,] = data.TT.D;
  1177. const [, dataType] = type['#'].split('.');
  1178. const dtype = this.getType(dataType);
  1179. const shape = new paddle.TensorShape(dims);
  1180. return new paddle.TensorType(dtype, shape, layout, denotation);
  1181. }
  1182. getType(type) {
  1183. type = type.includes('_') ? type.split('_')[1] : type;
  1184. switch (type) {
  1185. case 'bool': return 'boolean';
  1186. case 'bf16': return 'bfloat16';
  1187. case 'fp16': return 'float16';
  1188. case 'fp32': return 'float32';
  1189. case 'fp64': return 'float64';
  1190. case 'fp8_e4m3fn': return 'float8e4m3fn';
  1191. case 'fp8_e5m2': return 'float8e5m2';
  1192. case 'f8e4m3fn': return 'float8e4m3fn';
  1193. case 'f8e5m2': return 'float8e5m2';
  1194. case 'f16': return 'float16';
  1195. case 'f32': return 'float32';
  1196. case 'f64': return 'float64';
  1197. case 'i8': return 'int8';
  1198. case 'ui8': return 'uint8';
  1199. case 'i16': return 'int16';
  1200. case 'i32': return 'int32';
  1201. case 'i64': return 'int64';
  1202. case 'c64': return 'complex<float32>';
  1203. case 'c128': return 'complex<float64>';
  1204. case 'str': return 'string';
  1205. default: return type;
  1206. }
  1207. }
  1208. getCompressOp(opType) {
  1209. switch (opType) {
  1210. case '0': return 'builtin';
  1211. case '1': return 'pd_op';
  1212. case '2': return 'cf';
  1213. case '3': return 'custom_op';
  1214. case '4': return 'pd_dist';
  1215. case 'p': return 'parameter';
  1216. default: return opType;
  1217. }
  1218. }
  1219. getAttrDenotation(name, value) {
  1220. if (value) {
  1221. if (typeof value === 'boolean') {
  1222. return `${name}`;
  1223. }
  1224. if (name !== 'name' && name !== 'dtype') {
  1225. return `${name}:${value}`;
  1226. }
  1227. }
  1228. return '';
  1229. }
  1230. getAttr(opInfo, idx, value) {
  1231. if (opInfo.kind === 'p') {
  1232. let attrName = '';
  1233. let attrType = '';
  1234. let attrValue = '';
  1235. switch (idx) {
  1236. case '0':
  1237. attrName = 'is_distributed';
  1238. attrType = this.getType('a_bool');
  1239. break;
  1240. case '1':
  1241. attrName = 'is_parameter';
  1242. attrType = this.getType('a_bool');
  1243. break;
  1244. case '2':
  1245. attrName = 'need_clip';
  1246. attrType = this.getType('a_bool');
  1247. break;
  1248. case '3':
  1249. attrName = 'name';
  1250. attrType = this.getType('a_str');
  1251. break;
  1252. default:
  1253. break;
  1254. }
  1255. attrValue = attrType === this.getType('a_bool') ? value === 1 : value;
  1256. return [attrName, attrType, attrValue];
  1257. }
  1258. const attrName = value.N;
  1259. let attrType = this.getType(value.AT['#'].split('.')[1]);
  1260. let attrValue = value.AT.D;
  1261. if (attrType === this.getType('a_array') && attrValue.length > 0) {
  1262. const subType = this.getType(attrValue[0]['#'].split('.')[1]);
  1263. attrType = `${subType}[]`;
  1264. const valueData = [];
  1265. for (const attr of attrValue) {
  1266. valueData.push(attr.D);
  1267. }
  1268. attrValue = valueData;
  1269. }
  1270. if (attrName === 'place') {
  1271. const [place, val,] = attrValue;
  1272. let device = place;
  1273. switch (device) {
  1274. case 0: device = 'UNDEFINED'; break;
  1275. case 1: device = 'CPU'; break;
  1276. case 2: device = 'GPU'; break;
  1277. case 3: device = 'GPUPINNED'; break;
  1278. case 4: device = 'XPU'; break;
  1279. case 7: device = 'IPU'; break;
  1280. case 9: device = 'CUSTOM'; break;
  1281. default: break;
  1282. }
  1283. attrValue = `${device}:${val}`;
  1284. }
  1285. if (attrName === 'shape') {
  1286. attrValue = new paddle.TensorShape(attrValue);
  1287. }
  1288. return [attrName, attrType, attrValue];
  1289. }
  1290. getOutputAttr(opInfo, idx, outputAttr) {
  1291. switch (opInfo.kind) {
  1292. case 'p': {
  1293. const denotation = [];
  1294. if (outputAttr[0] === 1) {
  1295. denotation.push('persistable');
  1296. }
  1297. if (outputAttr[1] === 1) {
  1298. denotation.push('stop_gradient');
  1299. }
  1300. if (outputAttr[2] === 1) {
  1301. denotation.push('trainable');
  1302. }
  1303. if (outputAttr[3] === 1) {
  1304. denotation.push('is_distributed');
  1305. }
  1306. if (outputAttr[4] === 1) {
  1307. denotation.push('is_parameter');
  1308. }
  1309. if (outputAttr[5] === 1) {
  1310. denotation.push('need_clip');
  1311. }
  1312. return denotation.join(';');
  1313. }
  1314. case 'data': {
  1315. const denotation = [];
  1316. for (const attr of outputAttr) {
  1317. const attrName = attr.N;
  1318. const attrValue = attr.AT.D[idx].D;
  1319. const attrDenotation = this.getAttrDenotation(attrName, attrValue);
  1320. if (attrDenotation) {
  1321. denotation.push(attrDenotation);
  1322. }
  1323. }
  1324. for (const value of opInfo._attr) {
  1325. const [attrName, , attrValue] = this.getAttr(opInfo, null, value);
  1326. const attrDenotation = this.getAttrDenotation(attrName, attrValue);
  1327. if (attrDenotation) {
  1328. denotation.push(attrDenotation);
  1329. }
  1330. }
  1331. return denotation.join(';');
  1332. }
  1333. default: {
  1334. const denotation = [];
  1335. for (const attr of outputAttr) {
  1336. const attrName = attr.N;
  1337. const attrValue = attr.AT.D[idx].D;
  1338. const attrDenotation = this.getAttrDenotation(attrName, attrValue);
  1339. if (attrDenotation) {
  1340. denotation.push(attrDenotation);
  1341. }
  1342. }
  1343. return denotation.join(';');
  1344. }
  1345. }
  1346. }
  1347. };
  1348. paddle.Error = class extends Error {
  1349. constructor(message) {
  1350. super(message);
  1351. this.name = 'Error loading PaddlePaddle model.';
  1352. }
  1353. };
  1354. export const ModelFactory = paddle.ModelFactory;