paddle.js 57 KB

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