paddle.js 57 KB

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