shevchenko 3.0.7 → 3.0.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (135) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +4 -4
  3. package/dist/cjs/anthroponym-declension/anthroponym-inflector.js +3 -3
  4. package/dist/cjs/anthroponym-declension/bootstrap.js +3 -3
  5. package/dist/cjs/anthroponym-declension/family-name-classifier/artifacts/model.bundle.json.js +3 -3
  6. package/dist/cjs/anthroponym-declension/family-name-classifier/cache/incorrect-predictions.json.js +3 -3
  7. package/dist/cjs/anthroponym-declension/family-name-classifier/family-name-class-transformer.js +3 -3
  8. package/dist/cjs/anthroponym-declension/family-name-classifier/family-name-classifer.js +3 -3
  9. package/dist/cjs/anthroponym-declension/family-name-classifier/model-bundle-loader.js +3 -3
  10. package/dist/cjs/anthroponym-declension/family-name-classifier/model-config.js +3 -3
  11. package/dist/cjs/anthroponym-declension/family-name-classifier/word-transformer.js +3 -3
  12. package/dist/cjs/anthroponym-declension/family-name-inflector.js +4 -4
  13. package/dist/cjs/anthroponym-declension/family-name-inflector.js.map +1 -1
  14. package/dist/cjs/anthroponym-declension/given-name-inflector.js +4 -4
  15. package/dist/cjs/anthroponym-declension/given-name-inflector.js.map +1 -1
  16. package/dist/cjs/anthroponym-declension/name-inflector.js +3 -3
  17. package/dist/cjs/anthroponym-declension/patronymic-name-inflector.js +5 -5
  18. package/dist/cjs/anthroponym-declension/patronymic-name-inflector.js.map +1 -1
  19. package/dist/cjs/gender-detection/detect-gender.js +3 -3
  20. package/dist/cjs/gender-detection/given-names-genders.json.js +3 -3
  21. package/dist/cjs/index.js +5 -3
  22. package/dist/cjs/index.js.map +1 -1
  23. package/dist/cjs/input-validation.js +54 -49
  24. package/dist/cjs/input-validation.js.map +1 -1
  25. package/dist/cjs/language/alphabet.js +3 -3
  26. package/dist/cjs/language/grammatical-case.js +3 -3
  27. package/dist/cjs/language/grammatical-gender.js +3 -3
  28. package/dist/cjs/language/letter-case.js +3 -3
  29. package/dist/cjs/language/linguistics.js +3 -3
  30. package/dist/cjs/language/word-class.js +3 -3
  31. package/dist/cjs/shevchenko.js +97 -18
  32. package/dist/cjs/shevchenko.js.map +1 -1
  33. package/dist/cjs/word-declension/append-command-runner.js +3 -3
  34. package/dist/cjs/word-declension/bootstrap.js +4 -4
  35. package/dist/cjs/word-declension/command-runner-factory.js +3 -3
  36. package/dist/cjs/word-declension/declension-rule-inflector.js +3 -3
  37. package/dist/cjs/word-declension/declension-types.js +3 -3
  38. package/dist/cjs/word-declension/declension-types.js.map +1 -1
  39. package/dist/cjs/word-declension/replace-command-runner.js +3 -3
  40. package/dist/cjs/word-declension/{declension-rules.json.js → rules/artifacts/declension-rules.json.js} +123 -103
  41. package/dist/{es/word-declension → cjs/word-declension/rules/artifacts}/declension-rules.json.js.map +1 -1
  42. package/dist/cjs/word-declension/word-inflector.js +7 -7
  43. package/dist/cjs/word-declension/word-inflector.js.map +1 -1
  44. package/dist/es/anthroponym-declension/anthroponym-inflector.js +3 -3
  45. package/dist/es/anthroponym-declension/anthroponym.d.ts +2 -2
  46. package/dist/es/anthroponym-declension/anthroponym.d.ts.map +1 -1
  47. package/dist/es/anthroponym-declension/bootstrap.js +3 -3
  48. package/dist/es/anthroponym-declension/family-name-classifier/artifacts/model.bundle.json.js +3 -3
  49. package/dist/es/anthroponym-declension/family-name-classifier/cache/incorrect-predictions.json.js +3 -3
  50. package/dist/es/anthroponym-declension/family-name-classifier/data-utils.d.ts +3 -3
  51. package/dist/es/anthroponym-declension/family-name-classifier/data-utils.d.ts.map +1 -1
  52. package/dist/es/anthroponym-declension/family-name-classifier/family-name-class-transformer.js +3 -3
  53. package/dist/es/anthroponym-declension/family-name-classifier/family-name-class.d.ts +2 -2
  54. package/dist/es/anthroponym-declension/family-name-classifier/family-name-class.d.ts.map +1 -1
  55. package/dist/es/anthroponym-declension/family-name-classifier/family-name-classifer.js +3 -3
  56. package/dist/es/anthroponym-declension/family-name-classifier/model-bundle-loader.js +3 -3
  57. package/dist/es/anthroponym-declension/family-name-classifier/model-config.js +3 -3
  58. package/dist/es/anthroponym-declension/family-name-classifier/scripts/train-model.d.ts +2 -2
  59. package/dist/es/anthroponym-declension/family-name-classifier/scripts/train-model.d.ts.map +1 -1
  60. package/dist/es/anthroponym-declension/family-name-classifier/word-transformer.js +3 -3
  61. package/dist/es/anthroponym-declension/family-name-inflector.js +4 -4
  62. package/dist/es/anthroponym-declension/family-name-inflector.js.map +1 -1
  63. package/dist/es/anthroponym-declension/given-name-inflector.js +4 -4
  64. package/dist/es/anthroponym-declension/given-name-inflector.js.map +1 -1
  65. package/dist/es/anthroponym-declension/name-inflector.js +3 -3
  66. package/dist/es/anthroponym-declension/patronymic-name-inflector.d.ts.map +1 -1
  67. package/dist/es/anthroponym-declension/patronymic-name-inflector.js +5 -5
  68. package/dist/es/anthroponym-declension/patronymic-name-inflector.js.map +1 -1
  69. package/dist/es/contracts.d.ts +10 -4
  70. package/dist/es/contracts.d.ts.map +1 -1
  71. package/dist/es/gender-detection/detect-gender.js +3 -3
  72. package/dist/es/gender-detection/given-names-genders.json.js +3 -3
  73. package/dist/es/index.js +4 -3
  74. package/dist/es/index.js.map +1 -1
  75. package/dist/es/input-validation.d.ts +6 -4
  76. package/dist/es/input-validation.d.ts.map +1 -1
  77. package/dist/es/input-validation.js +54 -50
  78. package/dist/es/input-validation.js.map +1 -1
  79. package/dist/es/language/alphabet.js +3 -3
  80. package/dist/es/language/grammatical-case.js +3 -3
  81. package/dist/es/language/grammatical-gender.js +3 -3
  82. package/dist/es/language/letter-case.js +3 -3
  83. package/dist/es/language/linguistics.js +3 -3
  84. package/dist/es/language/word-class.js +3 -3
  85. package/dist/es/shevchenko.d.ts +87 -15
  86. package/dist/es/shevchenko.d.ts.map +1 -1
  87. package/dist/es/shevchenko.js +97 -18
  88. package/dist/es/shevchenko.js.map +1 -1
  89. package/dist/es/word-declension/append-command-runner.js +3 -3
  90. package/dist/es/word-declension/bootstrap.js +4 -4
  91. package/dist/es/word-declension/command-runner-factory.js +3 -3
  92. package/dist/es/word-declension/declension-rule-inflector.js +3 -3
  93. package/dist/es/word-declension/declension-rule-matchers.d.ts +5 -5
  94. package/dist/es/word-declension/declension-rule-matchers.d.ts.map +1 -1
  95. package/dist/es/word-declension/declension-types.d.ts +12 -11
  96. package/dist/es/word-declension/declension-types.d.ts.map +1 -1
  97. package/dist/es/word-declension/declension-types.js +3 -3
  98. package/dist/es/word-declension/declension-types.js.map +1 -1
  99. package/dist/es/word-declension/replace-command-runner.js +3 -3
  100. package/dist/es/word-declension/{declension-rules.json.js → rules/artifacts/declension-rules.json.js} +123 -103
  101. package/dist/{cjs/word-declension → es/word-declension/rules/artifacts}/declension-rules.json.js.map +1 -1
  102. package/dist/es/word-declension/rules/scripts/build-declension-rules.d.ts +2 -0
  103. package/dist/es/word-declension/rules/scripts/build-declension-rules.d.ts.map +1 -0
  104. package/dist/es/word-declension/word-inflector.d.ts +5 -7
  105. package/dist/es/word-declension/word-inflector.d.ts.map +1 -1
  106. package/dist/es/word-declension/word-inflector.js +7 -7
  107. package/dist/es/word-declension/word-inflector.js.map +1 -1
  108. package/dist/umd/shevchenko.min.js +188 -188
  109. package/dist/umd/shevchenko.min.js.map +1 -1
  110. package/package.json +5 -6
  111. package/src/anthroponym-declension/anthroponym.ts +2 -2
  112. package/src/anthroponym-declension/family-name-classifier/data-utils.ts +3 -3
  113. package/src/anthroponym-declension/family-name-classifier/family-name-class.ts +2 -2
  114. package/src/anthroponym-declension/family-name-classifier/model-bundle-saver.ts +4 -4
  115. package/src/anthroponym-declension/family-name-classifier/scripts/cache-incorrect-predictions.ts +6 -6
  116. package/src/anthroponym-declension/family-name-classifier/scripts/train-model.ts +7 -7
  117. package/src/anthroponym-declension/family-name-inflector.ts +1 -1
  118. package/src/anthroponym-declension/given-name-inflector.ts +1 -1
  119. package/src/anthroponym-declension/patronymic-name-inflector.ts +3 -2
  120. package/src/contracts.ts +12 -4
  121. package/src/input-validation.ts +65 -51
  122. package/src/shevchenko.ts +127 -23
  123. package/src/word-declension/README.md +1 -1
  124. package/src/word-declension/bootstrap.ts +1 -1
  125. package/src/word-declension/declension-rule-matchers.ts +10 -7
  126. package/src/word-declension/declension-types.ts +13 -11
  127. package/src/word-declension/rules/adjective-declension-rules.json +649 -0
  128. package/src/word-declension/{declension-rules.json → rules/artifacts/declension-rules.json} +121 -100
  129. package/src/word-declension/rules/exception-declension-rules.json +842 -0
  130. package/src/word-declension/rules/noun-declension-rules.json +6301 -0
  131. package/src/word-declension/rules/scripts/build-declension-rules.ts +40 -0
  132. package/src/word-declension/word-inflector.ts +13 -11
  133. package/dist/es/word-declension/scripts/load-declension-rules.d.ts +0 -2
  134. package/dist/es/word-declension/scripts/load-declension-rules.d.ts.map +0 -1
  135. package/src/word-declension/scripts/load-declension-rules.ts +0 -14
@@ -1,13 +1,13 @@
1
1
  /**
2
2
  * @file JavaScript library for declension of Ukrainian anthroponyms
3
3
  * @module shevchenko
4
- * @version 3.0.7
5
- * @author Oleksandr Tolochko <tooleks@gmail.com>
4
+ * @version 3.0.9
5
+ * @author Oleksandr Tolochko <shevchenko-js@tooleks.com>
6
6
  * @license MIT
7
- * @copyright 2017-2023 Oleksandr Tolochko <tooleks@gmail.com>
7
+ * @copyright 2017-2024 Oleksandr Tolochko <shevchenko-js@tooleks.com>
8
8
  * @see {@link git+https://github.com/tooleks/shevchenko-js.git}
9
9
  */
10
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("crypto")):"function"==typeof define&&define.amd?define(["exports","crypto"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).shevchenko={},e.require$$0)}(this,(function(e,t){"use strict";function n(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var i=n(t);function a(e,t,n,i){return new(n||(n=Promise))((function(a,s){function r(e){try{l(i.next(e))}catch(e){s(e)}}function o(e){try{l(i.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?a(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(r,o)}l((i=i.apply(e,t||[])).next())}))}var s,r;!function(e){e[e["а"]=1]="а",e[e["б"]=2]="б",e[e["в"]=3]="в",e[e["г"]=4]="г",e[e["ґ"]=5]="ґ",e[e["д"]=6]="д",e[e["е"]=7]="е",e[e["є"]=8]="є",e[e["ж"]=9]="ж",e[e["з"]=10]="з",e[e["и"]=11]="и",e[e["і"]=12]="і",e[e["ї"]=13]="ї",e[e["й"]=14]="й",e[e["к"]=15]="к",e[e["л"]=16]="л",e[e["м"]=17]="м",e[e["н"]=18]="н",e[e["о"]=19]="о",e[e["п"]=20]="п",e[e["р"]=21]="р",e[e["с"]=22]="с",e[e["т"]=23]="т",e[e["у"]=24]="у",e[e["ф"]=25]="ф",e[e["х"]=26]="х",e[e["ц"]=27]="ц",e[e["ч"]=28]="ч",e[e["ш"]=29]="ш",e[e["щ"]=30]="щ",e[e["ь"]=31]="ь",e[e["ю"]=32]="ю",e[e["я"]=33]="я"}(s||(s={})),Object.keys(s).length,function(e){e.NOUN="noun",e.ADJECTIVE="adjective"}(r||(r={}));const o=/[аоуеиіяюєї]/gi;function l(e){return 1===function(e){const t=e.match(o);return null==t?0:t.length}(e)}var c,u,h;function p(e,t=0){const n=e.charAt(t);return n===n.toUpperCase()}function d(e,t=0){const n=e.charAt(t);return n===n.toLowerCase()}e.GrammaticalCase=void 0,(c=e.GrammaticalCase||(e.GrammaticalCase={})).NOMINATIVE="nominative",c.GENITIVE="genitive",c.DATIVE="dative",c.ACCUSATIVE="accusative",c.ABLATIVE="ablative",c.LOCATIVE="locative",c.VOCATIVE="vocative",e.GrammaticalGender=void 0,(u=e.GrammaticalGender||(e.GrammaticalGender={})).MASCULINE="masculine",u.FEMININE="feminine";class m{constructor(e){this.command=e}exec(e){return e+this.command.value}}!function(e){e.REPLACE="replace",e.APPEND="append"}(h||(h={}));class f{constructor(e){this.command=e}exec(){return this.command.value}}class g{make(e){switch(e.action){case h.APPEND:return new m(e);case h.REPLACE:return new f(e);default:throw new TypeError(`Invalid command action: ${e.action}.`)}}}class v{constructor(e){this.rule=e,this.commandRunnerFactory=new g}inflect(e,t){const[n]=this.rule.grammaticalCases[t];if(n){const t=new RegExp(this.rule.pattern.modify,"gi"),i=e.replace(t,((e,...t)=>{let i="";const a=function(e){const t=new RegExp(`${e.toString()}|`).exec("");return null==t?0:t.length-1}(this.rule.pattern.modify);for(let e=0;e<a;e+=1){let a=t[e];const s=n[e];null!=s&&(a=this.commandRunnerFactory.make(s).exec(a)),i+=a}return i}));return function(e,t){let n="";for(let i=0;i<t.length;i+=1){const a=e[i]||e[e.length-1],s=t[i];d(a)?n+=s.toLowerCase():p(a)?n+=s.toUpperCase():n+=s}return n}(e,i)}return e}}const y=[{description:"жіноче ім'я любов",examples:["любов"],wordClass:"noun",gender:["feminine"],priority:6,application:["givenName"],pattern:{find:"^любов$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"append",value:"і"}}],dative:[{0:{action:"append",value:"і"}}],accusative:[],ablative:[{0:{action:"append",value:"'ю"}}],locative:[{0:{action:"append",value:"і"}}],vocative:[{0:{action:"append",value:"е"}}]}},{description:"чоловічі імена федір, сидір",examples:["федір","сидір"],wordClass:"noun",gender:["masculine"],priority:6,application:["givenName"],pattern:{find:"^(федір|сидір)$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],dative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"у"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],accusative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],ablative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ом"}}],locative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"у"}}],vocative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"е"}}]}},{description:"слово суддя",examples:["суддя"],wordClass:"noun",gender:["masculine","feminine"],priority:6,application:["familyName"],pattern:{find:"^суддя$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"і"}}],dative:[{0:{action:"replace",value:"і"}}],accusative:[{0:{action:"replace",value:"ю"}}],ablative:[{0:{action:"replace",value:"ею"}}],locative:[{0:{action:"replace",value:"і"}}],vocative:[{0:{action:"replace",value:"е"}}]}},{description:"слово рілля",examples:["рілля"],wordClass:"noun",gender:["masculine","feminine"],priority:6,application:["familyName"],pattern:{find:"^рілля$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"і"}}],dative:[{0:{action:"replace",value:"і"}}],accusative:[{0:{action:"replace",value:"ю"}}],ablative:[{0:{action:"replace",value:"ею"}}],locative:[{0:{action:"replace",value:"і"}}],vocative:[{0:{action:"replace",value:"е"}}]}},{description:"друга відміна / чоловічий рід / м'яка група / на -(голосний)вень",examples:["півень"],wordClass:"noun",gender:["masculine"],priority:6,application:[],pattern:{find:"(а|е|є|и|і|ї|о|у|ю|я)вень$",modify:"(.{1})(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:""},2:{action:"replace",value:"я"}}],dative:[{0:{action:"replace",value:""},2:{action:"replace",value:"ю"}},{0:{action:"replace",value:""},2:{action:"replace",value:"еві"}}],accusative:[{0:{action:"replace",value:""},2:{action:"replace",value:"я"}}],ablative:[{0:{action:"replace",value:""},2:{action:"replace",value:"ем"}}],locative:[{0:{action:"replace",value:""},2:{action:"replace",value:"еві"}},{0:{action:"replace",value:""},2:{action:"replace",value:"ю"}}],vocative:[{0:{action:"replace",value:""},2:{action:"replace",value:"ю"}}]}},{description:"друга відміна / чоловічий рід / м'яка група / на -(голосний)лець",examples:["стрілець","білець"],wordClass:"noun",gender:["masculine"],priority:6,application:[],pattern:{find:"(а|е|є|и|і|ї|о|у|ю|я)лець$",modify:"(.{1})(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"ь"},2:{action:"replace",value:"я"}}],dative:[{0:{action:"replace",value:"ь"},2:{action:"replace",value:"ю"}},{0:{action:"replace",value:"ь"},2:{action:"replace",value:"еві"}}],accusative:[{0:{action:"replace",value:"ь"},2:{action:"replace",value:"я"}}],ablative:[{0:{action:"replace",value:"ь"},2:{action:"replace",value:"ем"}}],locative:[{0:{action:"replace",value:"ь"},2:{action:"replace",value:"ю"}},{0:{action:"replace",value:"ь"},2:{action:"replace",value:"еві"}}],vocative:[{0:{action:"replace",value:"ь"},2:{action:"replace",value:"ю"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -(к|п|кр|пл|др|жив)іт",examples:["кіт","кріт"],wordClass:"noun",gender:["masculine"],priority:6,application:[],pattern:{find:"(к|п|кр|пл|др|жив)іт$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],dative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"у"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],accusative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],ablative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ом"}}],locative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"і"}}],vocative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -грім",examples:["грім"],wordClass:"noun",gender:["masculine"],priority:6,application:[],pattern:{find:"грім$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],dative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"у"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],accusative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],ablative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ом"}}],locative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"і"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],vocative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -(дзвін|хрін)",examples:["дзвін"],wordClass:"noun",gender:["masculine"],priority:6,application:[],pattern:{find:"(дзвін|хрін)$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],dative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"у"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],accusative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],ablative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ом"}}],locative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"і"}}],vocative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -батіг",examples:["батіг"],wordClass:"noun",gender:["masculine"],priority:6,application:[],pattern:{find:"батіг$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],dative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"у"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],accusative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],ablative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ом"}}],locative:[{0:{action:"replace",value:"о"},1:{action:"replace",value:"зі"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],vocative:[{0:{action:"replace",value:"о"},1:{action:"replace",value:"гу"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -сокіл",examples:["сокіл"],wordClass:"noun",gender:["masculine"],priority:6,application:[],pattern:{find:"сокіл$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],dative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"у"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],accusative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],ablative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ом"}}],locative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],vocative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / м'яка група / на -кріль",examples:["кріль"],wordClass:"noun",gender:["masculine"],priority:6,application:[],pattern:{find:"кріль$",modify:"(.{1})(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"о"},2:{action:"replace",value:"я"}}],dative:[{0:{action:"replace",value:"о"},2:{action:"replace",value:"ю"}},{0:{action:"replace",value:"о"},2:{action:"replace",value:"еві"}}],accusative:[{0:{action:"replace",value:"о"},2:{action:"replace",value:"я"}}],ablative:[{0:{action:"replace",value:"о"},2:{action:"replace",value:"ем"}}],locative:[{0:{action:"replace",value:"о"},2:{action:"replace",value:"ю"}},{0:{action:"replace",value:"о"},2:{action:"replace",value:"еві"}}],vocative:[{0:{action:"replace",value:"о"},2:{action:"replace",value:"ю"}}]}},{description:"чоловічі імена ігор, лазар",examples:["ігор","лазар"],wordClass:"noun",gender:["masculine"],priority:5,application:[],pattern:{find:"^(ігор|лазар)$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"append",value:"я"}}],dative:[{0:{action:"append",value:"ю"}},{0:{action:"append",value:"еві"}}],accusative:[{0:{action:"append",value:"я"}}],ablative:[{0:{action:"append",value:"ем"}}],locative:[{0:{action:"append",value:"ю"}},{0:{action:"append",value:"еві"}}],vocative:[{0:{action:"append",value:"ю"}}]}},{description:"слово сіль",examples:["сіль"],wordClass:"noun",gender:["masculine"],priority:5,application:["familyName"],pattern:{find:"^сіль$",modify:"(.{1})(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"о"},2:{action:"replace",value:"і"}}],dative:[{0:{action:"replace",value:"о"},2:{action:"replace",value:"і"}}],accusative:[],ablative:[{2:{action:"replace",value:"лю"}}],locative:[{0:{action:"replace",value:"о"},2:{action:"replace",value:"і"}}],vocative:[{0:{action:"replace",value:"о"},2:{action:"replace",value:"е"}}]}},{description:"друга відміна / чоловічий рід / м'яка група / на -(голосний)(твердий приголосний)е(ц|н)ь",examples:["половець"],wordClass:"noun",gender:["masculine"],priority:5,application:[],pattern:{find:"(а|е|є|и|і|ї|о|у|ю|я)(б|в|г|ґ|д|дз|дж|ж|з|к|л|м|н|п|р|с|т|ф|х|ц|ч|ш|щ)е(ц|н)ь$",modify:"(.{1})(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:""},2:{action:"replace",value:"я"}}],dative:[{0:{action:"replace",value:""},2:{action:"replace",value:"ю"}},{0:{action:"replace",value:""},2:{action:"replace",value:"еві"}}],accusative:[{0:{action:"replace",value:""},2:{action:"replace",value:"я"}}],ablative:[{0:{action:"replace",value:""},2:{action:"replace",value:"ем"}}],locative:[{0:{action:"replace",value:""},2:{action:"replace",value:"ю"}},{0:{action:"replace",value:""},2:{action:"replace",value:"еві"}}],vocative:[{0:{action:"replace",value:""},2:{action:"replace",value:"ю"}}]}},{description:"друга відміна / чоловічий рід / м'яка група / на -(твердий приголосний)(твердий приголосний)е(ц|н)ь",examples:["жнець"],wordClass:"noun",gender:["masculine"],priority:5,application:[],pattern:{find:"(б|в|г|ґ|д|дз|дж|ж|з|к|л|м|н|п|р|с|т|ф|х|ц|ч|ш|щ)(б|в|г|ґ|д|дз|дж|ж|з|к|л|м|н|п|р|с|т|ф|х|ц|ч|ш|щ)е(ц|н)ь$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"я"}}],dative:[{0:{action:"replace",value:"ю"}},{0:{action:"replace",value:"еві"}}],accusative:[{0:{action:"replace",value:"я"}}],ablative:[{0:{action:"replace",value:"ем"}}],locative:[{0:{action:"replace",value:"ю"}},{0:{action:"replace",value:"еві"}}],vocative:[{0:{action:"replace",value:"ю"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -(рід|плід)",examples:["рід","плід"],wordClass:"noun",gender:["masculine"],priority:5,application:[],pattern:{find:"(рід|плід)$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],dative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"у"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],accusative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],ablative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ом"}}],locative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"і"}}],vocative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / тверда група / чоловічі прізвища на -ніс, без чергування",examples:["ханіс","деніс","маніс"],wordClass:"noun",gender:["masculine"],priority:5,application:[],pattern:{find:"^(б|в|г|ґ|д|дз|дж|ж|з|й|к|л|м|н|п|р|с|т|ф|х|ц|ч|ш|щ)(а|е|є|и|і|ї|о|у|ю|я)ніс$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"append",value:"а"}}],dative:[{0:{action:"append",value:"у"}},{0:{action:"append",value:"ові"}}],accusative:[{0:{action:"append",value:"а"}}],ablative:[{0:{action:"append",value:"ом"}}],locative:[{0:{action:"append",value:"ові"}},{0:{action:"append",value:"і"}}],vocative:[{0:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -(з|яв)ір",examples:["дивозір","явір"],wordClass:"noun",gender:["masculine"],priority:5,application:[],pattern:{find:"(з|яв|г)ір$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],dative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"у"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],accusative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],ablative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ом"}}],locative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"і"}}],vocative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -орел",examples:["орел"],wordClass:"noun",gender:["masculine"],priority:5,application:[],pattern:{find:"орел$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"л"},1:{action:"replace",value:"а"}}],dative:[{0:{action:"replace",value:"л"},1:{action:"replace",value:"ові"}},{0:{action:"replace",value:"л"},1:{action:"replace",value:"у"}}],accusative:[{0:{action:"replace",value:"л"},1:{action:"replace",value:"а"}}],ablative:[{0:{action:"replace",value:"л"},1:{action:"replace",value:"ом"}}],locative:[{0:{action:"replace",value:"л"},1:{action:"replace",value:"ові"}}],vocative:[{0:{action:"replace",value:"л"},1:{action:"replace",value:"е"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -якір",examples:["якір"],wordClass:"noun",gender:["masculine"],priority:5,application:[],pattern:{find:"якір$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"о"},1:{action:"append",value:"я"}}],dative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ю"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"еві"}}],accusative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"я"}}],ablative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ем"}}],locative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"еві"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"і"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ю"}}],vocative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ю"}}]}},{description:"друга відміна / чоловічий рід / м'яка група / на -бідь",examples:["лебідь"],wordClass:"noun",gender:["masculine"],priority:5,application:[],pattern:{find:".бідь$",modify:"(.{1})(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"е"},2:{action:"replace",value:"я"}}],dative:[{0:{action:"replace",value:"е"},2:{action:"replace",value:"ю"}},{0:{action:"replace",value:"е"},2:{action:"replace",value:"еві"}}],accusative:[{0:{action:"replace",value:"е"},2:{action:"replace",value:"я"}}],ablative:[{0:{action:"replace",value:"е"},2:{action:"replace",value:"ем"}}],locative:[{0:{action:"replace",value:"е"},2:{action:"replace",value:"ю"}},{0:{action:"replace",value:"е"},2:{action:"replace",value:"еві"}}],vocative:[{0:{action:"replace",value:"е"},2:{action:"replace",value:"ю"}}]}},{description:"друга відміна / чоловічий рід / м'яка група / на -мінь",examples:["кремінь"],wordClass:"noun",gender:["masculine"],priority:5,application:[],pattern:{find:".мінь$",modify:"(.{1})(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"е"},2:{action:"replace",value:"я"}}],dative:[{0:{action:"replace",value:"е"},2:{action:"replace",value:"ю"}},{0:{action:"replace",value:"е"},2:{action:"replace",value:"еві"}}],accusative:[{0:{action:"replace",value:"е"},2:{action:"replace",value:"я"}}],ablative:[{0:{action:"replace",value:"е"},2:{action:"replace",value:"ем"}}],locative:[{0:{action:"replace",value:"е"},2:{action:"replace",value:"ю"}},{0:{action:"replace",value:"е"},2:{action:"replace",value:"еві"}}],vocative:[{0:{action:"replace",value:"е"},2:{action:"replace",value:"ю"}}]}},{description:"друга відміна / чоловічий рід / м'яка група / на -сіль",examples:["кисіль"],wordClass:"noun",gender:["masculine"],priority:5,application:[],pattern:{find:"сіль$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"я"}}],dative:[{0:{action:"replace",value:"ю"}},{0:{action:"replace",value:"еві"}}],accusative:[{0:{action:"replace",value:"я"}}],ablative:[{0:{action:"replace",value:"ем"}}],locative:[{0:{action:"replace",value:"ю"}},{0:{action:"replace",value:"еві"}}],vocative:[{0:{action:"replace",value:"ю"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -кінь",examples:["кінь"],wordClass:"noun",gender:["masculine"],priority:5,application:[],pattern:{find:"кінь$",modify:"(.{1})(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"о"},2:{action:"replace",value:"я"}}],dative:[{0:{action:"replace",value:"о"},2:{action:"replace",value:"ю"}},{0:{action:"replace",value:"о"},2:{action:"replace",value:"еві"}}],accusative:[{0:{action:"replace",value:"о"},2:{action:"replace",value:"я"}}],ablative:[{0:{action:"replace",value:"о"},2:{action:"replace",value:"ем"}}],locative:[{0:{action:"replace",value:"о"},2:{action:"replace",value:"і"}},{0:{action:"replace",value:"о"},2:{action:"replace",value:"еві"}}],vocative:[{0:{action:"replace",value:"о"},2:{action:"replace",value:"ю"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -куліш",examples:["куліш"],wordClass:"noun",gender:["masculine"],priority:5,application:[],pattern:{find:"куліш$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"append",value:"а"}}],dative:[{0:{action:"append",value:"у"}}],accusative:[{0:{action:"append",value:"а"}}],ablative:[{0:{action:"append",value:"ем"}}],locative:[{0:{action:"append",value:"еві"}}],vocative:[{0:{action:"append",value:"е"}}]}},{description:"жіночий рід / на -(твердий приголосний)ька",examples:["ільницька","сумська"],wordClass:"adjective",gender:["feminine"],priority:4,application:["familyName"],pattern:{find:"(б|в|г|ґ|д|дз|дж|ж|з|к|л|м|н|п|р|с|т|ф|х|ц|ч|ш|щ)ька$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"ої"}}],dative:[{0:{action:"replace",value:"ій"}}],accusative:[{0:{action:"replace",value:"у"}}],ablative:[{0:{action:"replace",value:"ою"}}],locative:[{0:{action:"replace",value:"ій"}}],vocative:[]}},{description:"жіночий рід / на -ова",examples:["іванова"],wordClass:"adjective",gender:["feminine"],priority:4,application:["familyName"],pattern:{find:"ова$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"ої"}}],dative:[{0:{action:"replace",value:"ій"}}],accusative:[{0:{action:"replace",value:"у"}}],ablative:[{0:{action:"replace",value:"ою"}}],locative:[{0:{action:"replace",value:"ій"}}],vocative:[]}},{description:"жіночий рід / на -іна",examples:["зеленкіна"],wordClass:"adjective",gender:["feminine"],priority:4,application:["familyName"],pattern:{find:"іна$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"ої"}}],dative:[{0:{action:"replace",value:"ій"}}],accusative:[{0:{action:"replace",value:"у"}}],ablative:[{0:{action:"replace",value:"ою"}}],locative:[{0:{action:"replace",value:"ій"}}],vocative:[]}},{description:"друга відміна / чоловічий рід / м'яка група / на -(голосний)єць",examples:["заєць"],wordClass:"noun",gender:["masculine"],priority:4,application:[],pattern:{find:"(а|е|є|и|і|ї|о|у|ю|я)єць$",modify:"(.{1})(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"й"},2:{action:"replace",value:"я"}}],dative:[{0:{action:"replace",value:"й"},2:{action:"replace",value:"ю"}},{0:{action:"replace",value:"й"},2:{action:"replace",value:"еві"}}],accusative:[{0:{action:"replace",value:"й"},2:{action:"replace",value:"я"}}],ablative:[{0:{action:"replace",value:"й"},2:{action:"replace",value:"ем"}}],locative:[{0:{action:"replace",value:"й"},2:{action:"replace",value:"ю"}},{0:{action:"replace",value:"й"},2:{action:"replace",value:"еві"}}],vocative:[{0:{action:"replace",value:"й"},2:{action:"replace",value:"ю"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -віз",examples:["узвіз"],wordClass:"noun",gender:["masculine"],priority:4,application:[],pattern:{find:"віз$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],dative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"у"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],accusative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],ablative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ом"}}],locative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"і"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],vocative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -ків",examples:["яків"],wordClass:"noun",gender:["masculine"],priority:4,application:[],pattern:{find:".ків$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],dative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"у"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],accusative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],ablative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ом"}}],locative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"і"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],vocative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -(к|р)іп",examples:["прокіп"],wordClass:"noun",gender:["masculine"],priority:4,application:[],pattern:{find:".(к|р)іп$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],dative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"у"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],accusative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],ablative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ом"}}],locative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"і"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],vocative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -піп",examples:["прокіп"],wordClass:"noun",gender:["masculine"],priority:4,application:[],pattern:{find:"піп$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],dative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"у"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],accusative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],ablative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ом"}}],locative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"і"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],vocative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -ніс",examples:["кривоніс"],wordClass:"noun",gender:["masculine"],priority:4,application:[],pattern:{find:"ніс$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],dative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"у"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],accusative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],ablative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ом"}}],locative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"і"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],vocative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -віл",examples:["рябовіл"],wordClass:"noun",gender:["masculine"],priority:4,application:[],pattern:{find:"віл$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],dative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"у"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],accusative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],ablative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ом"}}],locative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"і"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],vocative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -ріг",examples:["пиріг"],wordClass:"noun",gender:["masculine"],priority:4,application:[],pattern:{find:"ріг$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],dative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"у"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],accusative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],ablative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ом"}}],locative:[{0:{action:"replace",value:"о"},1:{action:"replace",value:"зі"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],vocative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"у"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -хід",examples:["прихід"],wordClass:"noun",gender:["masculine"],priority:4,application:[],pattern:{find:"хід$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],dative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"у"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],accusative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],ablative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ом"}}],locative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"і"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],vocative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"е"}}]}},{description:"друга відміна / жіночий рід / м'яка група / на -(голосний)ль",examples:["мішель","ніколь","cесіль"],wordClass:"noun",gender:["feminine"],priority:4,application:["givenName"],pattern:{find:"(а|е|є|и|і|ї|о|у|ю|я)ль$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{1:{action:"replace",value:"і"}}],dative:[{1:{action:"replace",value:"і"}}],accusative:[],ablative:[{0:{action:"replace",value:"лл"},1:{action:"replace",value:"ю"}}],locative:[{1:{action:"replace",value:"і"}}],vocative:[]}},{description:"друга відміна / жіночий рід / м'яка група / на (губний_приголосний)",examples:["зейнаб","руф"],wordClass:"noun",gender:["feminine"],priority:4,application:["givenName"],pattern:{find:"(б|п|в|м|ф)$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"append",value:"і"}}],dative:[{0:{action:"append",value:"і"}}],accusative:[{0:{action:"append",value:"і"}}],ablative:[{0:{action:"append",value:"і"}}],locative:[{0:{action:"append",value:"і"}}],vocative:[{0:{action:"append",value:"і"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -ишин",examples:["ковалишин"],wordClass:"noun",gender:["masculine"],priority:4,application:[],pattern:{find:"ишин$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"append",value:"а"}}],dative:[{0:{action:"append",value:"у"}}],accusative:[{0:{action:"append",value:"а"}}],ablative:[{0:{action:"append",value:"им"}}],locative:[{0:{action:"append",value:"у"}}],vocative:[{0:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -(аго|ово)",examples:["живаго"],wordClass:"noun",gender:["masculine"],priority:4,application:[],pattern:{find:"(аго|ово)$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[],dative:[],accusative:[],ablative:[],locative:[],vocative:[]}},{description:"друга відміна / чоловічий рід / тверда група / на -тер",examples:["вітер"],wordClass:"noun",gender:["masculine"],priority:4,application:[],pattern:{find:"тер$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:""},1:{action:"append",value:"а"}}],dative:[{0:{action:"replace",value:""},1:{action:"append",value:"у"}}],accusative:[{0:{action:"replace",value:""},1:{action:"append",value:"а"}}],ablative:[{0:{action:"replace",value:""},1:{action:"append",value:"ом"}}],locative:[{0:{action:"replace",value:""},1:{action:"append",value:"ові"}}],vocative:[{0:{action:"replace",value:""},1:{action:"append",value:"е"}}]}},{description:"перша відміна / чоловічий рід / тверда група / на -світ",examples:["світ"],wordClass:"noun",gender:["masculine"],priority:4,application:[],pattern:{find:"світ$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"append",value:"а"}}],dative:[{0:{action:"append",value:"у"}}],accusative:[{0:{action:"append",value:"а"}}],ablative:[{0:{action:"append",value:"ом"}}],locative:[{0:{action:"append",value:"ові"}}],vocative:[{0:{action:"append",value:"е"}}]}},{description:"чоловічі імена / на -(в|д)ір",examples:["дір","вір"],wordClass:"noun",gender:["masculine"],priority:4,application:[],pattern:{find:"(в|д)ір$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"append",value:"а"}}],dative:[{0:{action:"append",value:"у"}},{0:{action:"append",value:"ові"}}],accusative:[{0:{action:"append",value:"а"}}],ablative:[{0:{action:"append",value:"ом"}}],locative:[{0:{action:"append",value:"ові"}},{0:{action:"append",value:"у"}}],vocative:[{0:{action:"append",value:"е"}}]}},{description:"чоловічий рід / на -кій (помилкова транслітерація)",examples:["дідківській"],wordClass:"adjective",gender:["masculine"],priority:3,application:["familyName"],pattern:{find:"кій$",modify:"(.{2})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"ого"}}],dative:[{0:{action:"replace",value:"ому"}}],accusative:[{0:{action:"replace",value:"ого"}}],ablative:[{0:{action:"replace",value:"им"}}],locative:[{0:{action:"replace",value:"ому"}}],vocative:[]}},{description:"множина / на -их",examples:["седих"],wordClass:"adjective",gender:["masculine"],priority:3,application:[],pattern:{find:"их$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[],dative:[],accusative:[],ablative:[],locative:[],vocative:[]}},{description:"друга відміна / чоловічий рід / тверда група / на -га",examples:["нога"],wordClass:"noun",gender:["masculine"],priority:3,application:[],pattern:{find:"га$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{1:{action:"replace",value:"и"}}],dative:[{0:{action:"replace",value:"з"},1:{action:"replace",value:"і"}}],accusative:[{1:{action:"replace",value:"у"}}],ablative:[{1:{action:"replace",value:"ою"}}],locative:[{0:{action:"replace",value:"з"},1:{action:"replace",value:"і"}}],vocative:[{1:{action:"replace",value:"о"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -кіш",examples:["розкіш"],wordClass:"noun",gender:["masculine"],priority:3,application:[],pattern:{find:"кіш$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],dative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"еві"}}],accusative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],ablative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ем"}}],locative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"еві"}}],vocative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / м'яка група / на -ьо",examples:["іваньо","кузьо"],wordClass:"noun",gender:["masculine"],priority:3,application:[],pattern:{find:"ьо$",modify:"(.{2})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"я"}}],dative:[{0:{action:"replace",value:"ю"}}],accusative:[{0:{action:"replace",value:"я"}}],ablative:[{0:{action:"append",value:"м"}}],locative:[{0:{action:"replace",value:"ю"}}],vocative:[]}},{description:"друга відміна / чоловічий рід / тверда група / бусел",examples:["бусел"],wordClass:"noun",gender:["masculine"],priority:3,application:[],pattern:{find:"бусел$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:""},1:{action:"append",value:"а"}}],dative:[{0:{action:"replace",value:""},1:{action:"append",value:"ові"}},{0:{action:"replace",value:""},1:{action:"append",value:"у"}}],accusative:[{0:{action:"replace",value:""},1:{action:"append",value:"а"}}],ablative:[{0:{action:"replace",value:""},1:{action:"append",value:"ом"}}],locative:[{0:{action:"replace",value:""},1:{action:"append",value:"і"}}],vocative:[{0:{action:"replace",value:""},1:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -е[вмн]",examples:["артем","семен","лев"],wordClass:"noun",gender:["masculine"],priority:3,application:[],pattern:{find:"е[вмн]$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"append",value:"а"}}],dative:[{0:{action:"append",value:"у"}}],accusative:[{0:{action:"append",value:"а"}}],ablative:[{0:{action:"append",value:"ом"}}],locative:[{0:{action:"append",value:"ові"}}],vocative:[{0:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -пес",examples:["пес"],wordClass:"noun",gender:["masculine"],priority:3,application:[],pattern:{find:"пес$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:""},1:{action:"append",value:"а"}}],dative:[{0:{action:"replace",value:""},1:{action:"append",value:"у"}}],accusative:[{0:{action:"replace",value:""},1:{action:"append",value:"а"}}],ablative:[{0:{action:"replace",value:""},1:{action:"append",value:"ом"}}],locative:[{0:{action:"replace",value:""},1:{action:"append",value:"ові"}}],vocative:[{0:{action:"replace",value:""},1:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -ко",examples:["марко"],wordClass:"noun",gender:["masculine"],priority:3,application:[],pattern:{find:"ко$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"а"}}],dative:[{0:{action:"replace",value:"у"}},{0:{action:"replace",value:"ові"}}],accusative:[{0:{action:"replace",value:"а"}}],ablative:[{0:{action:"replace",value:"ом"}}],locative:[{0:{action:"replace",value:"ові"}},{0:{action:"replace",value:"у"}}],vocative:[{0:{action:"replace",value:"у"}}]}},{description:"друга відміна / чоловічий рід / м'яка група / на -ий",examples:["батий"],wordClass:"noun",gender:["masculine"],priority:3,application:[],pattern:{find:"ий$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"я"}}],dative:[{0:{action:"replace",value:"ю"}}],accusative:[{0:{action:"replace",value:"я"}}],ablative:[{0:{action:"replace",value:"єм"}}],locative:[{0:{action:"replace",value:"ю"}},{0:{action:"replace",value:"ї"}}],vocative:[{0:{action:"replace",value:"ю"}}]}},{description:"перша відміна / чоловічий рід / тверда група / на -йо",examples:["йойо"],wordClass:"noun",gender:["masculine"],priority:3,application:[],pattern:{find:"йо$",modify:"(.{2})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"я"}}],dative:[{0:{action:"append",value:"ві"}}],accusative:[{0:{action:"replace",value:"я"}}],ablative:[{0:{action:"append",value:"м"}}],locative:[{0:{action:"append",value:"ві"}}],vocative:[]}},{description:"перша відміна / чоловічий рід / тверда група / на -бо",examples:["голембо"],wordClass:"noun",gender:["masculine"],priority:3,application:[],pattern:{find:"бо$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"и"}}],dative:[{0:{action:"replace",value:"і"}}],accusative:[{0:{action:"replace",value:"у"}}],ablative:[{0:{action:"replace",value:"ою"}}],locative:[{0:{action:"replace",value:"і"}}],vocative:[]}},{description:"чоловічий рід / на -ой, -ий",examples:["толстой","сухомлинський"],wordClass:"adjective",gender:["masculine"],priority:2,application:["familyName"],pattern:{find:"(ой|ий)$",modify:"(.{2})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"ого"}}],dative:[{0:{action:"replace",value:"ому"}}],accusative:[{0:{action:"replace",value:"ого"}}],ablative:[{0:{action:"replace",value:"им"}}],locative:[{0:{action:"replace",value:"ому"}}],vocative:[]}},{description:"чоловічий рід / на -ій",examples:["заболотній"],wordClass:"adjective",gender:["masculine"],priority:2,application:["familyName"],pattern:{find:"ій$",modify:"(.{2})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"ього"}}],dative:[{0:{action:"replace",value:"ьому"}}],accusative:[{0:{action:"replace",value:"ього"}}],ablative:[{0:{action:"replace",value:"ім"}}],locative:[{0:{action:"replace",value:"ьому"}}],vocative:[]}},{description:"жіночий рід / на -(твердий приголосний)а",examples:["зелена"],wordClass:"adjective",gender:["feminine"],priority:2,application:["familyName"],pattern:{find:"(б|в|г|ґ|д|дз|дж|ж|з|к|л|м|н|п|р|с|т|ф|х|ц|ч|ш|щ)а$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"ої"}}],dative:[{0:{action:"replace",value:"ій"}}],accusative:[{0:{action:"replace",value:"у"}}],ablative:[{0:{action:"replace",value:"ою"}}],locative:[{0:{action:"replace",value:"ій"}}],vocative:[]}},{description:"жіночий рід / на -(твердий приголосний)я",examples:["задорожня"],wordClass:"adjective",gender:["feminine"],priority:2,application:["familyName"],pattern:{find:"(б|в|г|ґ|д|дз|дж|ж|з|к|л|м|н|п|р|с|т|ф|х|ц|ч|ш|щ)я$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"ьої"}}],dative:[{0:{action:"replace",value:"ій"}}],accusative:[{0:{action:"replace",value:"ю"}}],ablative:[{0:{action:"replace",value:"ьою"}}],locative:[{0:{action:"replace",value:"ій"}}],vocative:[]}},{description:"жіночий рід / на -ая",examples:["толстая"],wordClass:"adjective",gender:["feminine"],priority:2,application:["familyName"],pattern:{find:"ая$",modify:"(.{2})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"ої"}}],dative:[{0:{action:"replace",value:"ій"}}],accusative:[{0:{action:"replace",value:"ую"}}],ablative:[{0:{action:"replace",value:"ою"}}],locative:[{0:{action:"replace",value:"ій"}}],vocative:[]}},{description:"жіночий рід / на -яя",examples:["заболотняя"],wordClass:"adjective",gender:["feminine"],priority:2,application:["familyName"],pattern:{find:"яя$",modify:"(.{2})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"ьої"}}],dative:[{0:{action:"replace",value:"ій"}}],accusative:[{0:{action:"replace",value:"ю"}}],ablative:[{0:{action:"replace",value:"ьою"}}],locative:[{0:{action:"replace",value:"ій"}}],vocative:[]}},{description:"чоловічі по батькові та прізвища / на -ич",examples:["валерійович","риндич"],wordClass:"noun",gender:["masculine"],priority:2,application:["patronymicName","familyName"],pattern:{find:"ич$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"append",value:"а"}}],dative:[{0:{action:"append",value:"у"}}],accusative:[{0:{action:"append",value:"а"}}],ablative:[{0:{action:"append",value:"ем"}}],locative:[{0:{action:"append",value:"у"}}],vocative:[{0:{action:"append",value:"у"}}]}},{description:"чоловічі по батькові та прізвища / на -іч",examples:["ілліч"],wordClass:"noun",gender:["masculine"],priority:2,application:["patronymicName","familyName"],pattern:{find:"іч$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"append",value:"а"}}],dative:[{0:{action:"append",value:"у"}},{0:{action:"append",value:"еві"}}],accusative:[{0:{action:"append",value:"а"}}],ablative:[{0:{action:"append",value:"ем"}}],locative:[{0:{action:"append",value:"і"}},{0:{action:"append",value:"у"}},{0:{action:"append",value:"еві"}}],vocative:[{0:{action:"append",value:"у"}}]}},{description:"жіночі по батькові / на -на",examples:["юріївна"],wordClass:"noun",gender:["feminine"],priority:2,application:["patronymicName"],pattern:{find:"на$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"и"}}],dative:[{0:{action:"replace",value:"і"}}],accusative:[{0:{action:"replace",value:"у"}}],ablative:[{0:{action:"replace",value:"ою"}}],locative:[{0:{action:"replace",value:"і"}}],vocative:[{0:{action:"replace",value:"о"}}]}},{description:"жіночі імена / на -(твердий приголосний)я",examples:["неля"],wordClass:"noun",gender:["feminine"],priority:2,application:["givenName"],pattern:{find:"(б|в|г|ґ|д|дз|дж|ж|з|к|л|м|н|п|р|с|т|ф|х|ц|ч|ш|щ)я$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"і"}}],dative:[{0:{action:"replace",value:"і"}}],accusative:[{0:{action:"replace",value:"ю"}}],ablative:[{0:{action:"replace",value:"ею"}}],locative:[{0:{action:"replace",value:"і"}}],vocative:[{0:{action:"replace",value:"ю"}}]}},{description:"чоловічі імена / на -ня",examples:["женя"],wordClass:"noun",gender:["masculine"],priority:2,application:["givenName"],pattern:{find:"ня$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"і"}}],dative:[{0:{action:"replace",value:"і"}}],accusative:[{0:{action:"replace",value:"ю"}}],ablative:[{0:{action:"replace",value:"ею"}}],locative:[{0:{action:"replace",value:"і"}}],vocative:[{0:{action:"replace",value:"ю"}}]}},{description:"друга відміна / чоловічий рід / тверда група/ на -ов",examples:["павлов"],wordClass:"noun",gender:["masculine"],priority:2,application:["familyName"],pattern:{find:"ов$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"append",value:"а"}}],dative:[{0:{action:"append",value:"у"}}],accusative:[{0:{action:"append",value:"а"}}],ablative:[{0:{action:"append",value:"им"}}],locative:[{0:{action:"append",value:"у"}}],vocative:[{0:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -ів",examples:["ковалів"],wordClass:"noun",gender:["masculine"],priority:2,application:["familyName"],pattern:{find:"ів$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"append",value:"а"}}],dative:[{0:{action:"append",value:"у"}}],accusative:[{0:{action:"append",value:"а"}}],ablative:[{0:{action:"append",value:"им"}}],locative:[{0:{action:"append",value:"у"}}],vocative:[{0:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -яр",examples:["скляр"],wordClass:"noun",gender:["masculine"],priority:2,application:[],pattern:{find:"яр$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"append",value:"а"}}],dative:[{0:{action:"append",value:"у"}},{0:{action:"append",value:"еві"}}],accusative:[{0:{action:"append",value:"а"}}],ablative:[{0:{action:"append",value:"ем"}}],locative:[{0:{action:"append",value:"еві"}},{0:{action:"append",value:"у"}}],vocative:[{0:{action:"append",value:"е"}}]}},{description:"друга відміна / жіночий рід / тверда, м'яка група / на -(о|ь|твердий приголосний)",examples:["шевченко"],wordClass:"noun",gender:["feminine"],priority:2,application:[],pattern:{find:"(о|ь|(б|в|г|ґ|д|дз|дж|ж|з|к|л|м|н|п|р|с|т|ф|х|ц|ч|ш|щ))$",modify:"(.{2})$"},grammaticalCases:{nominative:[],genitive:[],dative:[],accusative:[],ablative:[],locative:[],vocative:[]}},{description:"друга відміна / чоловічий рід / тверда група / на -ок",examples:["бурячок"],wordClass:"noun",gender:["masculine"],priority:2,application:[],pattern:{find:"((?<=(а|е|є|и|і|ї|о|у|ю|я).*(а|е|є|и|і|ї|о|у|ю|я).*л)|(?<=(а|е|є|и|і|ї|о|у|ю|я).*[^л]))ок$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:""},1:{action:"append",value:"а"}}],dative:[{0:{action:"replace",value:""},1:{action:"append",value:"у"}},{0:{action:"replace",value:""},1:{action:"append",value:"ові"}}],accusative:[{0:{action:"replace",value:""},1:{action:"append",value:"а"}}],ablative:[{0:{action:"replace",value:""},1:{action:"append",value:"ом"}}],locative:[{0:{action:"replace",value:""},1:{action:"append",value:"ові"}}],vocative:[{0:{action:"replace",value:""},1:{action:"append",value:"у"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -е(тверда_прилосона)",examples:["марек"],wordClass:"noun",gender:["masculine"],priority:2,application:[],pattern:{find:"е(б|в|г|ґ|д|дз|дж|ж|з|к|л|м|н|п|р|с|т|ф|х|ц|ч|ш|щ)$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"append",value:"а"}}],dative:[{0:{action:"append",value:"у"}}],accusative:[{0:{action:"append",value:"а"}}],ablative:[{0:{action:"append",value:"ом"}}],locative:[{0:{action:"append",value:"ові"}}],vocative:[{0:{action:"append",value:"у"}}]}},{description:"друга відміна / чоловічий рід / м'яка група / на -(твердий приголосний)я",examples:["гмиря"],wordClass:"noun",gender:["masculine","feminine"],priority:2,application:[],pattern:{find:"(б|в|г|ґ|д|дз|дж|ж|з|к|л|м|н|п|р|с|т|ф|х|ц|ч|ш|щ)я$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"і"}}],dative:[{0:{action:"replace",value:"і"}}],accusative:[{0:{action:"replace",value:"ю"}}],ablative:[{0:{action:"replace",value:"ею"}}],locative:[{0:{action:"replace",value:"і"}}],vocative:[{0:{action:"replace",value:"е"}}]}},{description:"друга відміна / чоловічий, жіночий роди / м'яка група / на -(голосний|ь|й)я",examples:["юлія","майя"],wordClass:"noun",gender:["masculine","feminine"],priority:2,application:[],pattern:{find:"((а|е|є|и|і|ї|о|у|ю|я)|ь|й)я$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"ї"}}],dative:[{0:{action:"replace",value:"ї"}}],accusative:[{0:{action:"replace",value:"ю"}}],ablative:[{0:{action:"replace",value:"єю"}}],locative:[{0:{action:"replace",value:"ї"}}],vocative:[{0:{action:"replace",value:"є"}}]}},{description:"друга відміна / чоловічий рід / мішана група / на -(дж|ж|ч|ш)",examples:["януш","джордж"],wordClass:"noun",gender:["masculine"],priority:2,application:[],pattern:{find:"(дж|ж|ч|ш)$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"append",value:"а"}}],dative:[{0:{action:"append",value:"у"}},{0:{action:"append",value:"еві"}}],accusative:[{0:{action:"append",value:"а"}}],ablative:[{0:{action:"append",value:"ем"}}],locative:[{0:{action:"append",value:"еві"}},{0:{action:"append",value:"і"}},{0:{action:"append",value:"у"}}],vocative:[{0:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / тверда група / (свекор|цукор)",examples:["свекор","цукор"],wordClass:"noun",gender:["masculine"],priority:2,application:[],pattern:{find:"(свекор|цукор)$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:""},1:{action:"append",value:"а"}}],dative:[{0:{action:"replace",value:""},1:{action:"append",value:"ові"}},{0:{action:"replace",value:""},1:{action:"append",value:"у"}}],accusative:[{0:{action:"replace",value:""},1:{action:"append",value:"а"}}],ablative:[{0:{action:"replace",value:""},1:{action:"append",value:"ом"}}],locative:[{0:{action:"replace",value:""},1:{action:"append",value:"ові"}},{0:{action:"replace",value:""},1:{action:"append",value:"у"}}],vocative:[{0:{action:"replace",value:""},1:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / тверда група / снігир",examples:["снігир"],wordClass:"noun",gender:["masculine"],priority:2,application:[],pattern:{find:"снігир$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"append",value:"я"}}],dative:[{0:{action:"append",value:"еві"}},{0:{action:"append",value:"ю"}}],accusative:[{0:{action:"append",value:"я"}}],ablative:[{0:{action:"append",value:"ем"}}],locative:[{0:{action:"append",value:"еві"}},{0:{action:"append",value:"ю"}}],vocative:[{0:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -к",examples:["кузик","мисяк"],wordClass:"noun",gender:["masculine"],priority:2,application:[],pattern:{find:"к$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"append",value:"а"}}],dative:[{0:{action:"append",value:"у"}},{0:{action:"append",value:"ові"}}],accusative:[{0:{action:"append",value:"а"}}],ablative:[{0:{action:"append",value:"ом"}}],locative:[{0:{action:"append",value:"ові"}},{0:{action:"append",value:"у"}}],vocative:[{0:{action:"append",value:"у"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -х",examples:["кожух"],wordClass:"noun",gender:["masculine"],priority:2,application:[],pattern:{find:"х$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"append",value:"а"}}],dative:[{0:{action:"append",value:"у"}},{0:{action:"append",value:"ові"}}],accusative:[{0:{action:"append",value:"а"}}],ablative:[{0:{action:"append",value:"ом"}}],locative:[{0:{action:"append",value:"ові"}}],vocative:[{0:{action:"append",value:"у"}}]}},{description:"друга відміна / чоловічий рід / м'яка група / соловей",examples:["соловей"],wordClass:"noun",gender:["masculine"],priority:2,application:[],pattern:{find:"соловей$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:""},1:{action:"replace",value:"'я"}}],dative:[{0:{action:"replace",value:""},1:{action:"replace",value:"'єві"}},{0:{action:"replace",value:""},1:{action:"replace",value:"'ю"}}],accusative:[{0:{action:"replace",value:""},1:{action:"replace",value:"'я"}}],ablative:[{0:{action:"replace",value:""},1:{action:"replace",value:"'єм"}}],locative:[{0:{action:"replace",value:""},1:{action:"replace",value:"'ї"}},{0:{action:"replace",value:""},1:{action:"replace",value:"'ю"}},{0:{action:"replace",value:""},1:{action:"replace",value:"'єві"}}],vocative:[{0:{action:"replace",value:""},1:{action:"replace",value:"'ю"}}]}},{description:"перша відміна / чоловічий, жіночий роди / тверда група / на -ха",examples:["старуха"],wordClass:"noun",gender:["masculine","feminine"],priority:2,application:[],pattern:{find:"ха$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{1:{action:"replace",value:"и"}}],dative:[{0:{action:"replace",value:"с"},1:{action:"replace",value:"і"}}],accusative:[{1:{action:"replace",value:"у"}}],ablative:[{1:{action:"replace",value:"ою"}}],locative:[{0:{action:"replace",value:"с"},1:{action:"replace",value:"і"}}],vocative:[{1:{action:"replace",value:"о"}},{1:{action:"replace",value:"а"}}]}},{description:"перша відміна / чоловічий, жіночий роди / тверда група / на -ка",examples:["прилука"],wordClass:"noun",gender:["masculine","feminine"],priority:2,application:[],pattern:{find:"ка$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{1:{action:"replace",value:"и"}}],dative:[{0:{action:"replace",value:"ц"},1:{action:"replace",value:"і"}}],accusative:[{1:{action:"replace",value:"у"}}],ablative:[{1:{action:"replace",value:"ою"}}],locative:[{0:{action:"replace",value:"ц"},1:{action:"replace",value:"і"}}],vocative:[{1:{action:"replace",value:"о"}},{1:{action:"replace",value:"а"}}]}},{description:"друга відміна / чоловічий рід / м'яка група / журавель",examples:["журавель"],wordClass:"noun",gender:["masculine"],priority:2,application:[],pattern:{find:"журавель$",modify:"(.{3})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"ля"}}],dative:[{0:{action:"replace",value:"леві"}},{0:{action:"replace",value:"лю"}}],accusative:[{0:{action:"replace",value:"ля"}}],ablative:[{0:{action:"replace",value:"лем"}}],locative:[{0:{action:"replace",value:"лю"}},{0:{action:"replace",value:"і"}}],vocative:[{0:{action:"replace",value:"лю"}}]}},{description:"перша відміна / чоловічий рід / тверда група / на -(твердий приголосний)о",examples:["петро","павло"],wordClass:"noun",gender:["masculine"],priority:2,application:[],pattern:{find:"(б|в|г|ґ|д|дз|дж|ж|з|к|л|м|н|п|р|с|т|ф|х|ц|ч|ш|щ)о$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"а"}}],dative:[{0:{action:"replace",value:"у"}}],accusative:[{0:{action:"replace",value:"а"}}],ablative:[{0:{action:"replace",value:"ом"}}],locative:[{0:{action:"replace",value:"ові"}}],vocative:[{0:{action:"replace",value:"е"}}]}},{description:"перша відміна / жіночий рід / тверда група / на -(г|ґ)а",examples:["ольга"],wordClass:"noun",gender:["feminine"],priority:2,application:[],pattern:{find:"(г|ґ)а$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{1:{action:"replace",value:"и"}}],dative:[{0:{action:"replace",value:"з"},1:{action:"replace",value:"і"}}],accusative:[{1:{action:"replace",value:"у"}}],ablative:[{1:{action:"replace",value:"ою"}}],locative:[{0:{action:"replace",value:"з"},1:{action:"replace",value:"і"}}],vocative:[{1:{action:"replace",value:"о"}}]}},{description:"перша відміна / чоловічий рід / тверда група / на -ле",examples:["поле"],wordClass:"noun",gender:["masculine","feminine"],priority:2,application:[],pattern:{find:"ле$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"я"}}],dative:[{0:{action:"replace",value:"ю"}}],accusative:[{0:{action:"replace",value:"е"}}],ablative:[{0:{action:"replace",value:"ем"}}],locative:[{0:{action:"replace",value:"і"}}],vocative:[]}},{description:"перша відміна / чоловічий, жіночий роди / мішана група / на -а",examples:["мойша"],wordClass:"noun",gender:["masculine","feminine"],priority:2,application:[],pattern:{find:"(дж|ж|ч|ш|щ)а$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"і"}}],dative:[{0:{action:"replace",value:"і"}}],accusative:[{0:{action:"replace",value:"у"}}],ablative:[{0:{action:"replace",value:"ею"}}],locative:[{0:{action:"replace",value:"і"}}],vocative:[{0:{action:"replace",value:"о"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -(твердий приголосний)",examples:["олександр"],wordClass:"noun",gender:["masculine"],priority:1,application:[],pattern:{find:"(б|в|г|ґ|д|дз|дж|ж|з|к|л|м|н|п|р|с|т|ф|х|ц|ч|ш|щ)$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"append",value:"а"}}],dative:[{0:{action:"append",value:"у"}},{0:{action:"append",value:"ові"}}],accusative:[{0:{action:"append",value:"а"}}],ablative:[{0:{action:"append",value:"ом"}}],locative:[{0:{action:"append",value:"ові"}},{0:{action:"append",value:"у"}}],vocative:[{0:{action:"append",value:"е"}}]}},{description:"перша відміна / чоловічий, жіночий роди / тверда група / на -а",examples:["анна"],wordClass:"noun",gender:["masculine","feminine"],priority:1,application:[],pattern:{find:"а$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"и"}}],dative:[{0:{action:"replace",value:"і"}}],accusative:[{0:{action:"replace",value:"у"}}],ablative:[{0:{action:"replace",value:"ою"}}],locative:[{0:{action:"replace",value:"і"}}],vocative:[{0:{action:"replace",value:"о"}}]}},{description:"друга відміна / чоловічий рід / м'яка група / на -й",examples:["валерій"],wordClass:"noun",gender:["masculine"],priority:1,application:[],pattern:{find:"й$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"я"}}],dative:[{0:{action:"replace",value:"ю"}},{0:{action:"replace",value:"єві"}}],accusative:[{0:{action:"replace",value:"я"}}],ablative:[{0:{action:"replace",value:"єм"}}],locative:[{0:{action:"replace",value:"єві"}},{0:{action:"replace",value:"ю"}},{0:{action:"replace",value:"ї"}}],vocative:[{0:{action:"replace",value:"ю"}}]}},{description:"друга відміна / чоловічий рід / м'яка група / на -ь",examples:["петрунь"],wordClass:"noun",gender:["masculine"],priority:1,application:[],pattern:{find:"ь$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"я"}}],dative:[{0:{action:"replace",value:"ю"}}],accusative:[{0:{action:"replace",value:"я"}}],ablative:[{0:{action:"replace",value:"ем"}}],locative:[{0:{action:"replace",value:"еві"}}],vocative:[{0:{action:"replace",value:"ю"}}]}},{description:"жіночі імена / на -('|`)я",examples:["дар'я","мар'я"],wordClass:"noun",gender:["feminine"],priority:1,application:["givenName"],pattern:{find:"('|`)я$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"ї"}}],dative:[{0:{action:"replace",value:"ї"}}],accusative:[{0:{action:"replace",value:"ю"}}],ablative:[{0:{action:"replace",value:"єю"}}],locative:[{0:{action:"replace",value:"ї"}}],vocative:[{0:{action:"replace",value:"є"}}]}}],b=new class{constructor(e){this.declensionRules=[...e].sort(((e,t)=>t.priority-e.priority))}inflect(e,t){return a(this,void 0,void 0,(function*(){const[n]=yield this.findMatchingRules(e,t);return null==n?e:new v(n).inflect(e,t.grammaticalCase)}))}findMatchingRules(e,t){return a(this,void 0,void 0,(function*(){const n=this.declensionRules.filter((e=>e.gender.includes(t.gender))).filter((e=>!t.application||0===e.application.length||e.application.includes(t.application))).filter((t=>new RegExp(t.pattern.find,"gi").test(e))).filter((e=>!t.wordClass||e.wordClass===t.wordClass)).filter(((e,n,i)=>!t.customRuleFilter||t.customRuleFilter(e,n,i)));return n}))}}(y);class w{constructor(e,t){this.backend=e,this.dataMover=t,this.data=new WeakMap,this.dataIdsCount=0}get(e){return this.data.has(e)||this.dataMover.moveData(this.backend,e),this.data.get(e)}set(e,t){this.dataIdsCount++,this.data.set(e,t)}has(e){return this.data.has(e)}delete(e){return this.dataIdsCount--,this.data.delete(e)}numDataIds(){return this.dataIdsCount}}class k{refCount(e){return x("refCount")}incRef(e){return x("incRef")}timerAvailable(){return!0}time(e){return x("time")}read(e){return x("read")}readSync(e){return x("readSync")}readToGPU(e,t){return x("readToGPU")}numDataIds(){return x("numDataIds")}disposeData(e,t){return x("disposeData")}write(e,t,n){return x("write")}move(e,t,n,i,a){return x("move")}createTensorFromGPUData(e,t,n){return x("createTensorFromGPUData")}memory(){return x("memory")}floatPrecision(){return x("floatPrecision")}epsilon(){return 32===this.floatPrecision()?1e-7:1e-4}dispose(){return x("dispose")}}function x(e){throw new Error(`'${e}' not yet implemented or not found in the registry. This kernel may not be supported by the tfjs backend you have chosen`)}
10
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("crypto")):"function"==typeof define&&define.amd?define(["exports","crypto"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).shevchenko={},e.require$$0)}(this,(function(e,t){"use strict";function n(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var i=n(t);function a(e,t,n,i){return new(n||(n=Promise))((function(a,s){function r(e){try{l(i.next(e))}catch(e){s(e)}}function o(e){try{l(i.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?a(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(r,o)}l((i=i.apply(e,t||[])).next())}))}var s,r;!function(e){e[e["а"]=1]="а",e[e["б"]=2]="б",e[e["в"]=3]="в",e[e["г"]=4]="г",e[e["ґ"]=5]="ґ",e[e["д"]=6]="д",e[e["е"]=7]="е",e[e["є"]=8]="є",e[e["ж"]=9]="ж",e[e["з"]=10]="з",e[e["и"]=11]="и",e[e["і"]=12]="і",e[e["ї"]=13]="ї",e[e["й"]=14]="й",e[e["к"]=15]="к",e[e["л"]=16]="л",e[e["м"]=17]="м",e[e["н"]=18]="н",e[e["о"]=19]="о",e[e["п"]=20]="п",e[e["р"]=21]="р",e[e["с"]=22]="с",e[e["т"]=23]="т",e[e["у"]=24]="у",e[e["ф"]=25]="ф",e[e["х"]=26]="х",e[e["ц"]=27]="ц",e[e["ч"]=28]="ч",e[e["ш"]=29]="ш",e[e["щ"]=30]="щ",e[e["ь"]=31]="ь",e[e["ю"]=32]="ю",e[e["я"]=33]="я"}(s||(s={})),Object.keys(s).length,function(e){e.NOUN="noun",e.ADJECTIVE="adjective"}(r||(r={}));const o=/[аоуеиіяюєї]/gi;function l(e){return 1===function(e){const t=e.match(o);return null==t?0:t.length}(e)}var c,u,h;function p(e,t=0){const n=e.charAt(t);return n===n.toUpperCase()}function d(e,t=0){const n=e.charAt(t);return n===n.toLowerCase()}e.GrammaticalCase=void 0,(c=e.GrammaticalCase||(e.GrammaticalCase={})).NOMINATIVE="nominative",c.GENITIVE="genitive",c.DATIVE="dative",c.ACCUSATIVE="accusative",c.ABLATIVE="ablative",c.LOCATIVE="locative",c.VOCATIVE="vocative",e.GrammaticalGender=void 0,(u=e.GrammaticalGender||(e.GrammaticalGender={})).MASCULINE="masculine",u.FEMININE="feminine";class m{constructor(e){this.command=e}exec(e){return e+this.command.value}}!function(e){e.REPLACE="replace",e.APPEND="append"}(h||(h={}));class f{constructor(e){this.command=e}exec(){return this.command.value}}class g{make(e){switch(e.action){case h.APPEND:return new m(e);case h.REPLACE:return new f(e);default:throw new TypeError(`Invalid command action: ${e.action}.`)}}}class v{constructor(e){this.rule=e,this.commandRunnerFactory=new g}inflect(e,t){const[n]=this.rule.grammaticalCases[t];if(n){const t=new RegExp(this.rule.pattern.modify,"gi"),i=e.replace(t,((e,...t)=>{let i="";const a=function(e){const t=new RegExp(`${e.toString()}|`).exec("");return null==t?0:t.length-1}(this.rule.pattern.modify);for(let e=0;e<a;e+=1){let a=t[e];const s=n[e];null!=s&&(a=this.commandRunnerFactory.make(s).exec(a)),i+=a}return i}));return function(e,t){let n="";for(let i=0;i<t.length;i+=1){const a=e[i]||e[e.length-1],s=t[i];d(a)?n+=s.toLowerCase():p(a)?n+=s.toUpperCase():n+=s}return n}(e,i)}return e}}const y=[{description:"жіноче ім'я любов",examples:["любов"],wordClass:"noun",gender:["feminine"],priority:6,applicationType:["givenName"],pattern:{find:"^любов$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"append",value:"і"}}],dative:[{0:{action:"append",value:"і"}}],accusative:[],ablative:[{0:{action:"append",value:"'ю"}}],locative:[{0:{action:"append",value:"і"}}],vocative:[{0:{action:"append",value:"е"}}]}},{description:"чоловічі імена федір, сидір",examples:["федір","сидір"],wordClass:"noun",gender:["masculine"],priority:6,applicationType:["givenName"],pattern:{find:"^(федір|сидір)$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],dative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"у"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],accusative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],ablative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ом"}}],locative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"у"}}],vocative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"е"}}]}},{description:"слово суддя",examples:["суддя"],wordClass:"noun",gender:["masculine","feminine"],priority:6,applicationType:["familyName"],pattern:{find:"^суддя$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"і"}}],dative:[{0:{action:"replace",value:"і"}}],accusative:[{0:{action:"replace",value:"ю"}}],ablative:[{0:{action:"replace",value:"ею"}}],locative:[{0:{action:"replace",value:"і"}}],vocative:[{0:{action:"replace",value:"е"}}]}},{description:"слово рілля",examples:["рілля"],wordClass:"noun",gender:["masculine","feminine"],priority:6,applicationType:["familyName"],pattern:{find:"^рілля$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"і"}}],dative:[{0:{action:"replace",value:"і"}}],accusative:[{0:{action:"replace",value:"ю"}}],ablative:[{0:{action:"replace",value:"ею"}}],locative:[{0:{action:"replace",value:"і"}}],vocative:[{0:{action:"replace",value:"е"}}]}},{description:"друга відміна / чоловічий рід / м'яка група / на -(голосний)вень",examples:["півень"],wordClass:"noun",gender:["masculine"],priority:6,applicationType:[],pattern:{find:"(а|е|є|и|і|ї|о|у|ю|я)вень$",modify:"(.{1})(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:""},2:{action:"replace",value:"я"}}],dative:[{0:{action:"replace",value:""},2:{action:"replace",value:"ю"}},{0:{action:"replace",value:""},2:{action:"replace",value:"еві"}}],accusative:[{0:{action:"replace",value:""},2:{action:"replace",value:"я"}}],ablative:[{0:{action:"replace",value:""},2:{action:"replace",value:"ем"}}],locative:[{0:{action:"replace",value:""},2:{action:"replace",value:"еві"}},{0:{action:"replace",value:""},2:{action:"replace",value:"ю"}}],vocative:[{0:{action:"replace",value:""},2:{action:"replace",value:"ю"}}]}},{description:"друга відміна / чоловічий рід / м'яка група / на -(голосний)лець",examples:["стрілець","білець"],wordClass:"noun",gender:["masculine"],priority:6,applicationType:[],pattern:{find:"(а|е|є|и|і|ї|о|у|ю|я)лець$",modify:"(.{1})(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"ь"},2:{action:"replace",value:"я"}}],dative:[{0:{action:"replace",value:"ь"},2:{action:"replace",value:"ю"}},{0:{action:"replace",value:"ь"},2:{action:"replace",value:"еві"}}],accusative:[{0:{action:"replace",value:"ь"},2:{action:"replace",value:"я"}}],ablative:[{0:{action:"replace",value:"ь"},2:{action:"replace",value:"ем"}}],locative:[{0:{action:"replace",value:"ь"},2:{action:"replace",value:"ю"}},{0:{action:"replace",value:"ь"},2:{action:"replace",value:"еві"}}],vocative:[{0:{action:"replace",value:"ь"},2:{action:"replace",value:"ю"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -(к|п|кр|пл|др|жив)іт",examples:["кіт","кріт"],wordClass:"noun",gender:["masculine"],priority:6,applicationType:[],pattern:{find:"(к|п|кр|пл|др|жив)іт$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],dative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"у"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],accusative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],ablative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ом"}}],locative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"і"}}],vocative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -грім",examples:["грім"],wordClass:"noun",gender:["masculine"],priority:6,applicationType:[],pattern:{find:"грім$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],dative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"у"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],accusative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],ablative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ом"}}],locative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"і"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],vocative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -(дзвін|хрін)",examples:["дзвін"],wordClass:"noun",gender:["masculine"],priority:6,applicationType:[],pattern:{find:"(дзвін|хрін)$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],dative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"у"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],accusative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],ablative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ом"}}],locative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"і"}}],vocative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -батіг",examples:["батіг"],wordClass:"noun",gender:["masculine"],priority:6,applicationType:[],pattern:{find:"батіг$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],dative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"у"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],accusative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],ablative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ом"}}],locative:[{0:{action:"replace",value:"о"},1:{action:"replace",value:"зі"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],vocative:[{0:{action:"replace",value:"о"},1:{action:"replace",value:"гу"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -сокіл",examples:["сокіл"],wordClass:"noun",gender:["masculine"],priority:6,applicationType:[],pattern:{find:"сокіл$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],dative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"у"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],accusative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],ablative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ом"}}],locative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],vocative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / м'яка група / на -кріль",examples:["кріль"],wordClass:"noun",gender:["masculine"],priority:6,applicationType:[],pattern:{find:"кріль$",modify:"(.{1})(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"о"},2:{action:"replace",value:"я"}}],dative:[{0:{action:"replace",value:"о"},2:{action:"replace",value:"ю"}},{0:{action:"replace",value:"о"},2:{action:"replace",value:"еві"}}],accusative:[{0:{action:"replace",value:"о"},2:{action:"replace",value:"я"}}],ablative:[{0:{action:"replace",value:"о"},2:{action:"replace",value:"ем"}}],locative:[{0:{action:"replace",value:"о"},2:{action:"replace",value:"ю"}},{0:{action:"replace",value:"о"},2:{action:"replace",value:"еві"}}],vocative:[{0:{action:"replace",value:"о"},2:{action:"replace",value:"ю"}}]}},{description:"чоловічі імена ігор, лазар",examples:["ігор","лазар"],wordClass:"noun",gender:["masculine"],priority:5,applicationType:[],pattern:{find:"^(ігор|лазар)$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"append",value:"я"}}],dative:[{0:{action:"append",value:"ю"}},{0:{action:"append",value:"еві"}}],accusative:[{0:{action:"append",value:"я"}}],ablative:[{0:{action:"append",value:"ем"}}],locative:[{0:{action:"append",value:"ю"}},{0:{action:"append",value:"еві"}}],vocative:[{0:{action:"append",value:"ю"}}]}},{description:"слово сіль",examples:["сіль"],wordClass:"noun",gender:["masculine"],priority:5,applicationType:["familyName"],pattern:{find:"^сіль$",modify:"(.{1})(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"о"},2:{action:"replace",value:"і"}}],dative:[{0:{action:"replace",value:"о"},2:{action:"replace",value:"і"}}],accusative:[],ablative:[{2:{action:"replace",value:"лю"}}],locative:[{0:{action:"replace",value:"о"},2:{action:"replace",value:"і"}}],vocative:[{0:{action:"replace",value:"о"},2:{action:"replace",value:"е"}}]}},{description:"друга відміна / чоловічий рід / м'яка група / на -(голосний)(твердий приголосний)е(ц|н)ь",examples:["половець"],wordClass:"noun",gender:["masculine"],priority:5,applicationType:[],pattern:{find:"(а|е|є|и|і|ї|о|у|ю|я)(б|в|г|ґ|д|дз|дж|ж|з|к|л|м|н|п|р|с|т|ф|х|ц|ч|ш|щ)е(ц|н)ь$",modify:"(.{1})(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:""},2:{action:"replace",value:"я"}}],dative:[{0:{action:"replace",value:""},2:{action:"replace",value:"ю"}},{0:{action:"replace",value:""},2:{action:"replace",value:"еві"}}],accusative:[{0:{action:"replace",value:""},2:{action:"replace",value:"я"}}],ablative:[{0:{action:"replace",value:""},2:{action:"replace",value:"ем"}}],locative:[{0:{action:"replace",value:""},2:{action:"replace",value:"ю"}},{0:{action:"replace",value:""},2:{action:"replace",value:"еві"}}],vocative:[{0:{action:"replace",value:""},2:{action:"replace",value:"ю"}}]}},{description:"друга відміна / чоловічий рід / м'яка група / на -(твердий приголосний)(твердий приголосний)е(ц|н)ь",examples:["жнець"],wordClass:"noun",gender:["masculine"],priority:5,applicationType:[],pattern:{find:"(б|в|г|ґ|д|дз|дж|ж|з|к|л|м|н|п|р|с|т|ф|х|ц|ч|ш|щ)(б|в|г|ґ|д|дз|дж|ж|з|к|л|м|н|п|р|с|т|ф|х|ц|ч|ш|щ)е(ц|н)ь$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"я"}}],dative:[{0:{action:"replace",value:"ю"}},{0:{action:"replace",value:"еві"}}],accusative:[{0:{action:"replace",value:"я"}}],ablative:[{0:{action:"replace",value:"ем"}}],locative:[{0:{action:"replace",value:"ю"}},{0:{action:"replace",value:"еві"}}],vocative:[{0:{action:"replace",value:"ю"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -(рід|плід)",examples:["рід","плід"],wordClass:"noun",gender:["masculine"],priority:5,applicationType:[],pattern:{find:"(рід|плід)$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],dative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"у"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],accusative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],ablative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ом"}}],locative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"і"}}],vocative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / тверда група / чоловічі прізвища на -ніс, без чергування",examples:["ханіс","деніс","маніс"],wordClass:"noun",gender:["masculine"],priority:5,applicationType:[],pattern:{find:"^(б|в|г|ґ|д|дз|дж|ж|з|й|к|л|м|н|п|р|с|т|ф|х|ц|ч|ш|щ)(а|е|є|и|і|ї|о|у|ю|я)ніс$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"append",value:"а"}}],dative:[{0:{action:"append",value:"у"}},{0:{action:"append",value:"ові"}}],accusative:[{0:{action:"append",value:"а"}}],ablative:[{0:{action:"append",value:"ом"}}],locative:[{0:{action:"append",value:"ові"}},{0:{action:"append",value:"і"}}],vocative:[{0:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -(з|яв)ір",examples:["дивозір","явір"],wordClass:"noun",gender:["masculine"],priority:5,applicationType:[],pattern:{find:"(з|яв|г)ір$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],dative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"у"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],accusative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],ablative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ом"}}],locative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"і"}}],vocative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -орел",examples:["орел"],wordClass:"noun",gender:["masculine"],priority:5,applicationType:[],pattern:{find:"орел$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"л"},1:{action:"replace",value:"а"}}],dative:[{0:{action:"replace",value:"л"},1:{action:"replace",value:"ові"}},{0:{action:"replace",value:"л"},1:{action:"replace",value:"у"}}],accusative:[{0:{action:"replace",value:"л"},1:{action:"replace",value:"а"}}],ablative:[{0:{action:"replace",value:"л"},1:{action:"replace",value:"ом"}}],locative:[{0:{action:"replace",value:"л"},1:{action:"replace",value:"ові"}}],vocative:[{0:{action:"replace",value:"л"},1:{action:"replace",value:"е"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -якір",examples:["якір"],wordClass:"noun",gender:["masculine"],priority:5,applicationType:[],pattern:{find:"якір$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"о"},1:{action:"append",value:"я"}}],dative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ю"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"еві"}}],accusative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"я"}}],ablative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ем"}}],locative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"еві"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"і"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ю"}}],vocative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ю"}}]}},{description:"друга відміна / чоловічий рід / м'яка група / на -бідь",examples:["лебідь"],wordClass:"noun",gender:["masculine"],priority:5,applicationType:[],pattern:{find:".бідь$",modify:"(.{1})(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"е"},2:{action:"replace",value:"я"}}],dative:[{0:{action:"replace",value:"е"},2:{action:"replace",value:"ю"}},{0:{action:"replace",value:"е"},2:{action:"replace",value:"еві"}}],accusative:[{0:{action:"replace",value:"е"},2:{action:"replace",value:"я"}}],ablative:[{0:{action:"replace",value:"е"},2:{action:"replace",value:"ем"}}],locative:[{0:{action:"replace",value:"е"},2:{action:"replace",value:"ю"}},{0:{action:"replace",value:"е"},2:{action:"replace",value:"еві"}}],vocative:[{0:{action:"replace",value:"е"},2:{action:"replace",value:"ю"}}]}},{description:"друга відміна / чоловічий рід / м'яка група / на -мінь",examples:["кремінь"],wordClass:"noun",gender:["masculine"],priority:5,applicationType:[],pattern:{find:".мінь$",modify:"(.{1})(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"е"},2:{action:"replace",value:"я"}}],dative:[{0:{action:"replace",value:"е"},2:{action:"replace",value:"ю"}},{0:{action:"replace",value:"е"},2:{action:"replace",value:"еві"}}],accusative:[{0:{action:"replace",value:"е"},2:{action:"replace",value:"я"}}],ablative:[{0:{action:"replace",value:"е"},2:{action:"replace",value:"ем"}}],locative:[{0:{action:"replace",value:"е"},2:{action:"replace",value:"ю"}},{0:{action:"replace",value:"е"},2:{action:"replace",value:"еві"}}],vocative:[{0:{action:"replace",value:"е"},2:{action:"replace",value:"ю"}}]}},{description:"друга відміна / чоловічий рід / м'яка група / на -сіль",examples:["кисіль"],wordClass:"noun",gender:["masculine"],priority:5,applicationType:[],pattern:{find:"сіль$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"я"}}],dative:[{0:{action:"replace",value:"ю"}},{0:{action:"replace",value:"еві"}}],accusative:[{0:{action:"replace",value:"я"}}],ablative:[{0:{action:"replace",value:"ем"}}],locative:[{0:{action:"replace",value:"ю"}},{0:{action:"replace",value:"еві"}}],vocative:[{0:{action:"replace",value:"ю"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -кінь",examples:["кінь"],wordClass:"noun",gender:["masculine"],priority:5,applicationType:[],pattern:{find:"кінь$",modify:"(.{1})(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"о"},2:{action:"replace",value:"я"}}],dative:[{0:{action:"replace",value:"о"},2:{action:"replace",value:"ю"}},{0:{action:"replace",value:"о"},2:{action:"replace",value:"еві"}}],accusative:[{0:{action:"replace",value:"о"},2:{action:"replace",value:"я"}}],ablative:[{0:{action:"replace",value:"о"},2:{action:"replace",value:"ем"}}],locative:[{0:{action:"replace",value:"о"},2:{action:"replace",value:"і"}},{0:{action:"replace",value:"о"},2:{action:"replace",value:"еві"}}],vocative:[{0:{action:"replace",value:"о"},2:{action:"replace",value:"ю"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -куліш",examples:["куліш"],wordClass:"noun",gender:["masculine"],priority:5,applicationType:[],pattern:{find:"куліш$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"append",value:"а"}}],dative:[{0:{action:"append",value:"у"}}],accusative:[{0:{action:"append",value:"а"}}],ablative:[{0:{action:"append",value:"ем"}}],locative:[{0:{action:"append",value:"еві"}}],vocative:[{0:{action:"append",value:"е"}}]}},{description:"жіночий рід / на -(твердий приголосний)ька",examples:["ільницька","сумська"],wordClass:"adjective",gender:["feminine"],priority:4,applicationType:["familyName"],pattern:{find:"(б|в|г|ґ|д|дз|дж|ж|з|к|л|м|н|п|р|с|т|ф|х|ц|ч|ш|щ)ька$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"ої"}}],dative:[{0:{action:"replace",value:"ій"}}],accusative:[{0:{action:"replace",value:"у"}}],ablative:[{0:{action:"replace",value:"ою"}}],locative:[{0:{action:"replace",value:"ій"}}],vocative:[]}},{description:"жіночий рід / на -ова",examples:["іванова"],wordClass:"adjective",gender:["feminine"],priority:4,applicationType:["familyName"],pattern:{find:"ова$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"ої"}}],dative:[{0:{action:"replace",value:"ій"}}],accusative:[{0:{action:"replace",value:"у"}}],ablative:[{0:{action:"replace",value:"ою"}}],locative:[{0:{action:"replace",value:"ій"}}],vocative:[]}},{description:"жіночий рід / на -іна",examples:["зеленкіна"],wordClass:"adjective",gender:["feminine"],priority:4,applicationType:["familyName"],pattern:{find:"іна$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"ої"}}],dative:[{0:{action:"replace",value:"ій"}}],accusative:[{0:{action:"replace",value:"у"}}],ablative:[{0:{action:"replace",value:"ою"}}],locative:[{0:{action:"replace",value:"ій"}}],vocative:[]}},{description:"друга відміна / чоловічий рід / м'яка група / на -(голосний)єць",examples:["заєць"],wordClass:"noun",gender:["masculine"],priority:4,applicationType:[],pattern:{find:"(а|е|є|и|і|ї|о|у|ю|я)єць$",modify:"(.{1})(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"й"},2:{action:"replace",value:"я"}}],dative:[{0:{action:"replace",value:"й"},2:{action:"replace",value:"ю"}},{0:{action:"replace",value:"й"},2:{action:"replace",value:"еві"}}],accusative:[{0:{action:"replace",value:"й"},2:{action:"replace",value:"я"}}],ablative:[{0:{action:"replace",value:"й"},2:{action:"replace",value:"ем"}}],locative:[{0:{action:"replace",value:"й"},2:{action:"replace",value:"ю"}},{0:{action:"replace",value:"й"},2:{action:"replace",value:"еві"}}],vocative:[{0:{action:"replace",value:"й"},2:{action:"replace",value:"ю"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -віз",examples:["узвіз"],wordClass:"noun",gender:["masculine"],priority:4,applicationType:[],pattern:{find:"віз$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],dative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"у"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],accusative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],ablative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ом"}}],locative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"і"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],vocative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -ків",examples:["яків"],wordClass:"noun",gender:["masculine"],priority:4,applicationType:["givenName"],pattern:{find:".ків$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],dative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"у"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],accusative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],ablative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ом"}}],locative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"і"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],vocative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -(к|р)іп",examples:["прокіп"],wordClass:"noun",gender:["masculine"],priority:4,applicationType:[],pattern:{find:".(к|р)іп$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],dative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"у"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],accusative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],ablative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ом"}}],locative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"і"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],vocative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -піп",examples:["прокіп"],wordClass:"noun",gender:["masculine"],priority:4,applicationType:[],pattern:{find:"піп$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],dative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"у"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],accusative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],ablative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ом"}}],locative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"і"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],vocative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -ніс",examples:["кривоніс"],wordClass:"noun",gender:["masculine"],priority:4,applicationType:[],pattern:{find:"ніс$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],dative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"у"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],accusative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],ablative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ом"}}],locative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"і"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],vocative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -віл",examples:["рябовіл"],wordClass:"noun",gender:["masculine"],priority:4,applicationType:[],pattern:{find:"віл$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],dative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"у"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],accusative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],ablative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ом"}}],locative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"і"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],vocative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -ріг",examples:["пиріг"],wordClass:"noun",gender:["masculine"],priority:4,applicationType:[],pattern:{find:"ріг$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],dative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"у"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],accusative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],ablative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ом"}}],locative:[{0:{action:"replace",value:"о"},1:{action:"replace",value:"зі"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],vocative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"у"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -хід",examples:["прихід"],wordClass:"noun",gender:["masculine"],priority:4,applicationType:[],pattern:{find:"хід$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],dative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"у"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],accusative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],ablative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ом"}}],locative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"і"}},{0:{action:"replace",value:"о"},1:{action:"append",value:"ові"}}],vocative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"е"}}]}},{description:"друга відміна / жіночий рід / м'яка група / на -(голосний)ль",examples:["мішель","ніколь","cесіль"],wordClass:"noun",gender:["feminine"],priority:4,applicationType:["givenName"],pattern:{find:"(а|е|є|и|і|ї|о|у|ю|я)ль$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{1:{action:"replace",value:"і"}}],dative:[{1:{action:"replace",value:"і"}}],accusative:[],ablative:[{0:{action:"replace",value:"лл"},1:{action:"replace",value:"ю"}}],locative:[{1:{action:"replace",value:"і"}}],vocative:[]}},{description:"друга відміна / жіночий рід / м'яка група / на (губний_приголосний)",examples:["зейнаб","руф"],wordClass:"noun",gender:["feminine"],priority:4,applicationType:["givenName"],pattern:{find:"(б|п|в|м|ф)$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"append",value:"і"}}],dative:[{0:{action:"append",value:"і"}}],accusative:[{0:{action:"append",value:"і"}}],ablative:[{0:{action:"append",value:"і"}}],locative:[{0:{action:"append",value:"і"}}],vocative:[{0:{action:"append",value:"і"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -ишин",examples:["ковалишин"],wordClass:"noun",gender:["masculine"],priority:4,applicationType:[],pattern:{find:"ишин$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"append",value:"а"}}],dative:[{0:{action:"append",value:"у"}}],accusative:[{0:{action:"append",value:"а"}}],ablative:[{0:{action:"append",value:"им"}}],locative:[{0:{action:"append",value:"у"}}],vocative:[{0:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -(аго|ово)",examples:["живаго"],wordClass:"noun",gender:["masculine"],priority:4,applicationType:[],pattern:{find:"(аго|ово)$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[],dative:[],accusative:[],ablative:[],locative:[],vocative:[]}},{description:"друга відміна / чоловічий рід / тверда група / на -тер",examples:["вітер"],wordClass:"noun",gender:["masculine"],priority:4,applicationType:[],pattern:{find:"тер$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:""},1:{action:"append",value:"а"}}],dative:[{0:{action:"replace",value:""},1:{action:"append",value:"у"}}],accusative:[{0:{action:"replace",value:""},1:{action:"append",value:"а"}}],ablative:[{0:{action:"replace",value:""},1:{action:"append",value:"ом"}}],locative:[{0:{action:"replace",value:""},1:{action:"append",value:"ові"}}],vocative:[{0:{action:"replace",value:""},1:{action:"append",value:"е"}}]}},{description:"перша відміна / чоловічий рід / тверда група / на -світ",examples:["світ"],wordClass:"noun",gender:["masculine"],priority:4,applicationType:[],pattern:{find:"світ$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"append",value:"а"}}],dative:[{0:{action:"append",value:"у"}}],accusative:[{0:{action:"append",value:"а"}}],ablative:[{0:{action:"append",value:"ом"}}],locative:[{0:{action:"append",value:"ові"}}],vocative:[{0:{action:"append",value:"е"}}]}},{description:"чоловічі імена / на -(в|д)ір",examples:["дір","вір"],wordClass:"noun",gender:["masculine"],priority:4,applicationType:[],pattern:{find:"(в|д)ір$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"append",value:"а"}}],dative:[{0:{action:"append",value:"у"}},{0:{action:"append",value:"ові"}}],accusative:[{0:{action:"append",value:"а"}}],ablative:[{0:{action:"append",value:"ом"}}],locative:[{0:{action:"append",value:"ові"}},{0:{action:"append",value:"у"}}],vocative:[{0:{action:"append",value:"е"}}]}},{description:"чоловічий рід / на -кій (помилкова транслітерація)",examples:["дідківській"],wordClass:"adjective",gender:["masculine"],priority:3,applicationType:["familyName"],pattern:{find:"кій$",modify:"(.{2})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"ого"}}],dative:[{0:{action:"replace",value:"ому"}}],accusative:[{0:{action:"replace",value:"ого"}}],ablative:[{0:{action:"replace",value:"им"}}],locative:[{0:{action:"replace",value:"ому"}}],vocative:[]}},{description:"множина / на -их",examples:["седих"],wordClass:"adjective",gender:["masculine"],priority:3,applicationType:[],pattern:{find:"их$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[],dative:[],accusative:[],ablative:[],locative:[],vocative:[]}},{description:"друга відміна / чоловічий рід / тверда група / на -га",examples:["нога"],wordClass:"noun",gender:["masculine"],priority:3,applicationType:[],pattern:{find:"га$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{1:{action:"replace",value:"и"}}],dative:[{0:{action:"replace",value:"з"},1:{action:"replace",value:"і"}}],accusative:[{1:{action:"replace",value:"у"}}],ablative:[{1:{action:"replace",value:"ою"}}],locative:[{0:{action:"replace",value:"з"},1:{action:"replace",value:"і"}}],vocative:[{1:{action:"replace",value:"о"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -кіш",examples:["розкіш"],wordClass:"noun",gender:["masculine"],priority:3,applicationType:[],pattern:{find:"кіш$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],dative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"еві"}}],accusative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"а"}}],ablative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"ем"}}],locative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"еві"}}],vocative:[{0:{action:"replace",value:"о"},1:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / м'яка група / на -ьо",examples:["іваньо","кузьо"],wordClass:"noun",gender:["masculine"],priority:3,applicationType:[],pattern:{find:"ьо$",modify:"(.{2})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"я"}}],dative:[{0:{action:"replace",value:"ю"}}],accusative:[{0:{action:"replace",value:"я"}}],ablative:[{0:{action:"append",value:"м"}}],locative:[{0:{action:"replace",value:"ю"}}],vocative:[]}},{description:"друга відміна / чоловічий рід / тверда група / бусел",examples:["бусел"],wordClass:"noun",gender:["masculine"],priority:3,applicationType:[],pattern:{find:"бусел$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:""},1:{action:"append",value:"а"}}],dative:[{0:{action:"replace",value:""},1:{action:"append",value:"ові"}},{0:{action:"replace",value:""},1:{action:"append",value:"у"}}],accusative:[{0:{action:"replace",value:""},1:{action:"append",value:"а"}}],ablative:[{0:{action:"replace",value:""},1:{action:"append",value:"ом"}}],locative:[{0:{action:"replace",value:""},1:{action:"append",value:"і"}}],vocative:[{0:{action:"replace",value:""},1:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -е[вмн]",examples:["артем","семен","лев"],wordClass:"noun",gender:["masculine"],priority:3,applicationType:[],pattern:{find:"е[вмн]$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"append",value:"а"}}],dative:[{0:{action:"append",value:"у"}}],accusative:[{0:{action:"append",value:"а"}}],ablative:[{0:{action:"append",value:"ом"}}],locative:[{0:{action:"append",value:"ові"}}],vocative:[{0:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -пес",examples:["пес"],wordClass:"noun",gender:["masculine"],priority:3,applicationType:[],pattern:{find:"пес$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:""},1:{action:"append",value:"а"}}],dative:[{0:{action:"replace",value:""},1:{action:"append",value:"у"}}],accusative:[{0:{action:"replace",value:""},1:{action:"append",value:"а"}}],ablative:[{0:{action:"replace",value:""},1:{action:"append",value:"ом"}}],locative:[{0:{action:"replace",value:""},1:{action:"append",value:"ові"}}],vocative:[{0:{action:"replace",value:""},1:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -ко",examples:["марко"],wordClass:"noun",gender:["masculine"],priority:3,applicationType:[],pattern:{find:"ко$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"а"}}],dative:[{0:{action:"replace",value:"у"}},{0:{action:"replace",value:"ові"}}],accusative:[{0:{action:"replace",value:"а"}}],ablative:[{0:{action:"replace",value:"ом"}}],locative:[{0:{action:"replace",value:"ові"}},{0:{action:"replace",value:"у"}}],vocative:[{0:{action:"replace",value:"у"}}]}},{description:"друга відміна / чоловічий рід / м'яка група / на -ий",examples:["батий"],wordClass:"noun",gender:["masculine"],priority:3,applicationType:[],pattern:{find:"ий$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"я"}}],dative:[{0:{action:"replace",value:"ю"}}],accusative:[{0:{action:"replace",value:"я"}}],ablative:[{0:{action:"replace",value:"єм"}}],locative:[{0:{action:"replace",value:"ю"}},{0:{action:"replace",value:"ї"}}],vocative:[{0:{action:"replace",value:"ю"}}]}},{description:"перша відміна / чоловічий рід / тверда група / на -йо",examples:["йойо"],wordClass:"noun",gender:["masculine"],priority:3,applicationType:[],pattern:{find:"йо$",modify:"(.{2})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"я"}}],dative:[{0:{action:"append",value:"ві"}}],accusative:[{0:{action:"replace",value:"я"}}],ablative:[{0:{action:"append",value:"м"}}],locative:[{0:{action:"append",value:"ві"}}],vocative:[]}},{description:"перша відміна / чоловічий рід / тверда група / на -бо",examples:["голембо"],wordClass:"noun",gender:["masculine"],priority:3,applicationType:[],pattern:{find:"бо$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"и"}}],dative:[{0:{action:"replace",value:"і"}}],accusative:[{0:{action:"replace",value:"у"}}],ablative:[{0:{action:"replace",value:"ою"}}],locative:[{0:{action:"replace",value:"і"}}],vocative:[]}},{description:"чоловічий рід / на -ой, -ий",examples:["толстой","сухомлинський"],wordClass:"adjective",gender:["masculine"],priority:2,applicationType:["familyName"],pattern:{find:"(ой|ий)$",modify:"(.{2})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"ого"}}],dative:[{0:{action:"replace",value:"ому"}}],accusative:[{0:{action:"replace",value:"ого"}}],ablative:[{0:{action:"replace",value:"им"}}],locative:[{0:{action:"replace",value:"ому"}}],vocative:[]}},{description:"чоловічий рід / на -ій",examples:["заболотній"],wordClass:"adjective",gender:["masculine"],priority:2,applicationType:["familyName"],pattern:{find:"ій$",modify:"(.{2})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"ього"}}],dative:[{0:{action:"replace",value:"ьому"}}],accusative:[{0:{action:"replace",value:"ього"}}],ablative:[{0:{action:"replace",value:"ім"}}],locative:[{0:{action:"replace",value:"ьому"}}],vocative:[]}},{description:"жіночий рід / на -(твердий приголосний)а",examples:["зелена"],wordClass:"adjective",gender:["feminine"],priority:2,applicationType:["familyName"],pattern:{find:"(б|в|г|ґ|д|дз|дж|ж|з|к|л|м|н|п|р|с|т|ф|х|ц|ч|ш|щ)а$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"ої"}}],dative:[{0:{action:"replace",value:"ій"}}],accusative:[{0:{action:"replace",value:"у"}}],ablative:[{0:{action:"replace",value:"ою"}}],locative:[{0:{action:"replace",value:"ій"}}],vocative:[]}},{description:"жіночий рід / на -(твердий приголосний)я",examples:["задорожня"],wordClass:"adjective",gender:["feminine"],priority:2,applicationType:["familyName"],pattern:{find:"(б|в|г|ґ|д|дз|дж|ж|з|к|л|м|н|п|р|с|т|ф|х|ц|ч|ш|щ)я$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"ьої"}}],dative:[{0:{action:"replace",value:"ій"}}],accusative:[{0:{action:"replace",value:"ю"}}],ablative:[{0:{action:"replace",value:"ьою"}}],locative:[{0:{action:"replace",value:"ій"}}],vocative:[]}},{description:"жіночий рід / на -ая",examples:["толстая"],wordClass:"adjective",gender:["feminine"],priority:2,applicationType:["familyName"],pattern:{find:"ая$",modify:"(.{2})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"ої"}}],dative:[{0:{action:"replace",value:"ій"}}],accusative:[{0:{action:"replace",value:"ую"}}],ablative:[{0:{action:"replace",value:"ою"}}],locative:[{0:{action:"replace",value:"ій"}}],vocative:[]}},{description:"жіночий рід / на -яя",examples:["заболотняя"],wordClass:"adjective",gender:["feminine"],priority:2,applicationType:["familyName"],pattern:{find:"яя$",modify:"(.{2})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"ьої"}}],dative:[{0:{action:"replace",value:"ій"}}],accusative:[{0:{action:"replace",value:"ю"}}],ablative:[{0:{action:"replace",value:"ьою"}}],locative:[{0:{action:"replace",value:"ій"}}],vocative:[]}},{description:"чоловічі по батькові та прізвища / на -ич",examples:["валерійович","риндич"],wordClass:"noun",gender:["masculine"],priority:2,applicationType:["patronymicName","familyName"],pattern:{find:"ич$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"append",value:"а"}}],dative:[{0:{action:"append",value:"у"}}],accusative:[{0:{action:"append",value:"а"}}],ablative:[{0:{action:"append",value:"ем"}}],locative:[{0:{action:"append",value:"у"}}],vocative:[{0:{action:"append",value:"у"}}]}},{description:"чоловічі по батькові та прізвища / на -іч",examples:["ілліч"],wordClass:"noun",gender:["masculine"],priority:2,applicationType:["patronymicName","familyName"],pattern:{find:"іч$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"append",value:"а"}}],dative:[{0:{action:"append",value:"у"}},{0:{action:"append",value:"еві"}}],accusative:[{0:{action:"append",value:"а"}}],ablative:[{0:{action:"append",value:"ем"}}],locative:[{0:{action:"append",value:"і"}},{0:{action:"append",value:"у"}},{0:{action:"append",value:"еві"}}],vocative:[{0:{action:"append",value:"у"}}]}},{description:"жіночі по батькові / на -на",examples:["юріївна"],wordClass:"noun",gender:["feminine"],priority:2,applicationType:["patronymicName"],pattern:{find:"на$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"и"}}],dative:[{0:{action:"replace",value:"і"}}],accusative:[{0:{action:"replace",value:"у"}}],ablative:[{0:{action:"replace",value:"ою"}}],locative:[{0:{action:"replace",value:"і"}}],vocative:[{0:{action:"replace",value:"о"}}]}},{description:"жіночі імена / на -(твердий приголосний)я",examples:["неля"],wordClass:"noun",gender:["feminine"],priority:2,applicationType:["givenName"],pattern:{find:"(б|в|г|ґ|д|дз|дж|ж|з|к|л|м|н|п|р|с|т|ф|х|ц|ч|ш|щ)я$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"і"}}],dative:[{0:{action:"replace",value:"і"}}],accusative:[{0:{action:"replace",value:"ю"}}],ablative:[{0:{action:"replace",value:"ею"}}],locative:[{0:{action:"replace",value:"і"}}],vocative:[{0:{action:"replace",value:"ю"}}]}},{description:"чоловічі імена / на -ня",examples:["женя"],wordClass:"noun",gender:["masculine"],priority:2,applicationType:["givenName"],pattern:{find:"ня$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"і"}}],dative:[{0:{action:"replace",value:"і"}}],accusative:[{0:{action:"replace",value:"ю"}}],ablative:[{0:{action:"replace",value:"ею"}}],locative:[{0:{action:"replace",value:"і"}}],vocative:[{0:{action:"replace",value:"ю"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -ов, -ев (-єв), -ів (-їв), -ін (-їн)",examples:["павлов","нікітін"],wordClass:"noun",gender:["masculine"],priority:2,applicationType:["familyName"],pattern:{find:"([оеє]в|[ії]в|[ії]н)$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"append",value:"а"}}],dative:[{0:{action:"append",value:"у"}}],accusative:[{0:{action:"append",value:"а"}}],ablative:[{0:{action:"append",value:"им"}}],locative:[{0:{action:"append",value:"і"}},{0:{action:"append",value:"у"}}],vocative:[{0:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -ин",examples:["гаршин"],wordClass:"noun",gender:["masculine"],priority:2,applicationType:["familyName"],pattern:{find:"[^у][^с]ин$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"append",value:"а"}}],dative:[{0:{action:"append",value:"ові"}},{0:{action:"append",value:"у"}}],accusative:[{0:{action:"append",value:"а"}}],ablative:[{0:{action:"append",value:"им"}}],locative:[{0:{action:"append",value:"і"}},{0:{action:"append",value:"у"}}],vocative:[{0:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -яр",examples:["скляр"],wordClass:"noun",gender:["masculine"],priority:2,applicationType:[],pattern:{find:"яр$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"append",value:"а"}}],dative:[{0:{action:"append",value:"у"}},{0:{action:"append",value:"еві"}}],accusative:[{0:{action:"append",value:"а"}}],ablative:[{0:{action:"append",value:"ем"}}],locative:[{0:{action:"append",value:"еві"}},{0:{action:"append",value:"у"}}],vocative:[{0:{action:"append",value:"е"}}]}},{description:"друга відміна / жіночий рід / тверда, м'яка група / на -(о|ь|твердий приголосний)",examples:["шевченко"],wordClass:"noun",gender:["feminine"],priority:2,applicationType:[],pattern:{find:"(о|ь|(б|в|г|ґ|д|дз|дж|ж|з|к|л|м|н|п|р|с|т|ф|х|ц|ч|ш|щ))$",modify:"(.{2})$"},grammaticalCases:{nominative:[],genitive:[],dative:[],accusative:[],ablative:[],locative:[],vocative:[]}},{description:"друга відміна / чоловічий рід / тверда група / на -ок",examples:["бурячок"],wordClass:"noun",gender:["masculine"],priority:2,applicationType:[],pattern:{find:"((?<=(а|е|є|и|і|ї|о|у|ю|я).*(а|е|є|и|і|ї|о|у|ю|я).*л)|(?<=(а|е|є|и|і|ї|о|у|ю|я).*[^л]))ок$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:""},1:{action:"append",value:"а"}}],dative:[{0:{action:"replace",value:""},1:{action:"append",value:"у"}},{0:{action:"replace",value:""},1:{action:"append",value:"ові"}}],accusative:[{0:{action:"replace",value:""},1:{action:"append",value:"а"}}],ablative:[{0:{action:"replace",value:""},1:{action:"append",value:"ом"}}],locative:[{0:{action:"replace",value:""},1:{action:"append",value:"ові"}}],vocative:[{0:{action:"replace",value:""},1:{action:"append",value:"у"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -е(тверда_прилосона)",examples:["марек"],wordClass:"noun",gender:["masculine"],priority:2,applicationType:[],pattern:{find:"е(б|в|г|ґ|д|дз|дж|ж|з|к|л|м|н|п|р|с|т|ф|х|ц|ч|ш|щ)$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"append",value:"а"}}],dative:[{0:{action:"append",value:"у"}}],accusative:[{0:{action:"append",value:"а"}}],ablative:[{0:{action:"append",value:"ом"}}],locative:[{0:{action:"append",value:"ові"}}],vocative:[{0:{action:"append",value:"у"}}]}},{description:"друга відміна / чоловічий рід / м'яка група / на -(твердий приголосний)я",examples:["гмиря"],wordClass:"noun",gender:["masculine","feminine"],priority:2,applicationType:[],pattern:{find:"(б|в|г|ґ|д|дз|дж|ж|з|к|л|м|н|п|р|с|т|ф|х|ц|ч|ш|щ)я$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"і"}}],dative:[{0:{action:"replace",value:"і"}}],accusative:[{0:{action:"replace",value:"ю"}}],ablative:[{0:{action:"replace",value:"ею"}}],locative:[{0:{action:"replace",value:"і"}}],vocative:[{0:{action:"replace",value:"е"}}]}},{description:"друга відміна / чоловічий, жіночий роди / м'яка група / на -(голосний|ь|й)я",examples:["юлія","майя"],wordClass:"noun",gender:["masculine","feminine"],priority:2,applicationType:[],pattern:{find:"((а|е|є|и|і|ї|о|у|ю|я)|ь|й)я$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"ї"}}],dative:[{0:{action:"replace",value:"ї"}}],accusative:[{0:{action:"replace",value:"ю"}}],ablative:[{0:{action:"replace",value:"єю"}}],locative:[{0:{action:"replace",value:"ї"}}],vocative:[{0:{action:"replace",value:"є"}}]}},{description:"друга відміна / чоловічий рід / мішана група / на -(дж|ж|ч|ш)",examples:["януш","джордж"],wordClass:"noun",gender:["masculine"],priority:2,applicationType:[],pattern:{find:"(дж|ж|ч|ш)$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"append",value:"а"}}],dative:[{0:{action:"append",value:"у"}},{0:{action:"append",value:"еві"}}],accusative:[{0:{action:"append",value:"а"}}],ablative:[{0:{action:"append",value:"ем"}}],locative:[{0:{action:"append",value:"еві"}},{0:{action:"append",value:"і"}},{0:{action:"append",value:"у"}}],vocative:[{0:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / тверда група / (свекор|цукор)",examples:["свекор","цукор"],wordClass:"noun",gender:["masculine"],priority:2,applicationType:[],pattern:{find:"(свекор|цукор)$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:""},1:{action:"append",value:"а"}}],dative:[{0:{action:"replace",value:""},1:{action:"append",value:"ові"}},{0:{action:"replace",value:""},1:{action:"append",value:"у"}}],accusative:[{0:{action:"replace",value:""},1:{action:"append",value:"а"}}],ablative:[{0:{action:"replace",value:""},1:{action:"append",value:"ом"}}],locative:[{0:{action:"replace",value:""},1:{action:"append",value:"ові"}},{0:{action:"replace",value:""},1:{action:"append",value:"у"}}],vocative:[{0:{action:"replace",value:""},1:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / тверда група / снігир",examples:["снігир"],wordClass:"noun",gender:["masculine"],priority:2,applicationType:[],pattern:{find:"снігир$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"append",value:"я"}}],dative:[{0:{action:"append",value:"еві"}},{0:{action:"append",value:"ю"}}],accusative:[{0:{action:"append",value:"я"}}],ablative:[{0:{action:"append",value:"ем"}}],locative:[{0:{action:"append",value:"еві"}},{0:{action:"append",value:"ю"}}],vocative:[{0:{action:"append",value:"е"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -к",examples:["кузик","мисяк"],wordClass:"noun",gender:["masculine"],priority:2,applicationType:[],pattern:{find:"к$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"append",value:"а"}}],dative:[{0:{action:"append",value:"у"}},{0:{action:"append",value:"ові"}}],accusative:[{0:{action:"append",value:"а"}}],ablative:[{0:{action:"append",value:"ом"}}],locative:[{0:{action:"append",value:"ові"}},{0:{action:"append",value:"у"}}],vocative:[{0:{action:"append",value:"у"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -х",examples:["кожух"],wordClass:"noun",gender:["masculine"],priority:2,applicationType:[],pattern:{find:"х$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"append",value:"а"}}],dative:[{0:{action:"append",value:"у"}},{0:{action:"append",value:"ові"}}],accusative:[{0:{action:"append",value:"а"}}],ablative:[{0:{action:"append",value:"ом"}}],locative:[{0:{action:"append",value:"ові"}}],vocative:[{0:{action:"append",value:"у"}}]}},{description:"друга відміна / чоловічий рід / м'яка група / соловей",examples:["соловей"],wordClass:"noun",gender:["masculine"],priority:2,applicationType:[],pattern:{find:"соловей$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:""},1:{action:"replace",value:"'я"}}],dative:[{0:{action:"replace",value:""},1:{action:"replace",value:"'єві"}},{0:{action:"replace",value:""},1:{action:"replace",value:"'ю"}}],accusative:[{0:{action:"replace",value:""},1:{action:"replace",value:"'я"}}],ablative:[{0:{action:"replace",value:""},1:{action:"replace",value:"'єм"}}],locative:[{0:{action:"replace",value:""},1:{action:"replace",value:"'ї"}},{0:{action:"replace",value:""},1:{action:"replace",value:"'ю"}},{0:{action:"replace",value:""},1:{action:"replace",value:"'єві"}}],vocative:[{0:{action:"replace",value:""},1:{action:"replace",value:"'ю"}}]}},{description:"перша відміна / чоловічий, жіночий роди / тверда група / на -ха",examples:["старуха"],wordClass:"noun",gender:["masculine","feminine"],priority:2,applicationType:[],pattern:{find:"ха$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{1:{action:"replace",value:"и"}}],dative:[{0:{action:"replace",value:"с"},1:{action:"replace",value:"і"}}],accusative:[{1:{action:"replace",value:"у"}}],ablative:[{1:{action:"replace",value:"ою"}}],locative:[{0:{action:"replace",value:"с"},1:{action:"replace",value:"і"}}],vocative:[{1:{action:"replace",value:"о"}},{1:{action:"replace",value:"а"}}]}},{description:"перша відміна / чоловічий, жіночий роди / тверда група / на -ка",examples:["прилука"],wordClass:"noun",gender:["masculine","feminine"],priority:2,applicationType:[],pattern:{find:"ка$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{1:{action:"replace",value:"и"}}],dative:[{0:{action:"replace",value:"ц"},1:{action:"replace",value:"і"}}],accusative:[{1:{action:"replace",value:"у"}}],ablative:[{1:{action:"replace",value:"ою"}}],locative:[{0:{action:"replace",value:"ц"},1:{action:"replace",value:"і"}}],vocative:[{1:{action:"replace",value:"о"}},{1:{action:"replace",value:"а"}}]}},{description:"друга відміна / чоловічий рід / м'яка група / журавель",examples:["журавель"],wordClass:"noun",gender:["masculine"],priority:2,applicationType:[],pattern:{find:"журавель$",modify:"(.{3})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"ля"}}],dative:[{0:{action:"replace",value:"леві"}},{0:{action:"replace",value:"лю"}}],accusative:[{0:{action:"replace",value:"ля"}}],ablative:[{0:{action:"replace",value:"лем"}}],locative:[{0:{action:"replace",value:"лю"}},{0:{action:"replace",value:"і"}}],vocative:[{0:{action:"replace",value:"лю"}}]}},{description:"перша відміна / чоловічий рід / тверда група / на -(твердий приголосний)о",examples:["петро","павло"],wordClass:"noun",gender:["masculine"],priority:2,applicationType:[],pattern:{find:"(б|в|г|ґ|д|дз|дж|ж|з|к|л|м|н|п|р|с|т|ф|х|ц|ч|ш|щ)о$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"а"}}],dative:[{0:{action:"replace",value:"у"}}],accusative:[{0:{action:"replace",value:"а"}}],ablative:[{0:{action:"replace",value:"ом"}}],locative:[{0:{action:"replace",value:"ові"}}],vocative:[{0:{action:"replace",value:"е"}}]}},{description:"перша відміна / жіночий рід / тверда група / на -(г|ґ)а",examples:["ольга"],wordClass:"noun",gender:["feminine"],priority:2,applicationType:[],pattern:{find:"(г|ґ)а$",modify:"(.{1})(.{1})$"},grammaticalCases:{nominative:[],genitive:[{1:{action:"replace",value:"и"}}],dative:[{0:{action:"replace",value:"з"},1:{action:"replace",value:"і"}}],accusative:[{1:{action:"replace",value:"у"}}],ablative:[{1:{action:"replace",value:"ою"}}],locative:[{0:{action:"replace",value:"з"},1:{action:"replace",value:"і"}}],vocative:[{1:{action:"replace",value:"о"}}]}},{description:"перша відміна / чоловічий рід / тверда група / на -ле",examples:["поле"],wordClass:"noun",gender:["masculine","feminine"],priority:2,applicationType:[],pattern:{find:"ле$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"я"}}],dative:[{0:{action:"replace",value:"ю"}}],accusative:[{0:{action:"replace",value:"е"}}],ablative:[{0:{action:"replace",value:"ем"}}],locative:[{0:{action:"replace",value:"і"}}],vocative:[]}},{description:"перша відміна / чоловічий, жіночий роди / мішана група / на -а",examples:["мойша"],wordClass:"noun",gender:["masculine","feminine"],priority:2,applicationType:[],pattern:{find:"(дж|ж|ч|ш|щ)а$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"і"}}],dative:[{0:{action:"replace",value:"і"}}],accusative:[{0:{action:"replace",value:"у"}}],ablative:[{0:{action:"replace",value:"ею"}}],locative:[{0:{action:"replace",value:"і"}}],vocative:[{0:{action:"replace",value:"о"}}]}},{description:"друга відміна / чоловічий рід / тверда група / на -(твердий приголосний)",examples:["олександр"],wordClass:"noun",gender:["masculine"],priority:1,applicationType:[],pattern:{find:"(б|в|г|ґ|д|дз|дж|ж|з|к|л|м|н|п|р|с|т|ф|х|ц|ч|ш|щ)$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"append",value:"а"}}],dative:[{0:{action:"append",value:"у"}},{0:{action:"append",value:"ові"}}],accusative:[{0:{action:"append",value:"а"}}],ablative:[{0:{action:"append",value:"ом"}}],locative:[{0:{action:"append",value:"ові"}},{0:{action:"append",value:"у"}}],vocative:[{0:{action:"append",value:"е"}}]}},{description:"перша відміна / чоловічий, жіночий роди / тверда група / на -а",examples:["анна"],wordClass:"noun",gender:["masculine","feminine"],priority:1,applicationType:[],pattern:{find:"а$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"и"}}],dative:[{0:{action:"replace",value:"і"}}],accusative:[{0:{action:"replace",value:"у"}}],ablative:[{0:{action:"replace",value:"ою"}}],locative:[{0:{action:"replace",value:"і"}}],vocative:[{0:{action:"replace",value:"о"}}]}},{description:"друга відміна / чоловічий рід / м'яка група / на -й",examples:["валерій"],wordClass:"noun",gender:["masculine"],priority:1,applicationType:[],pattern:{find:"й$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"я"}}],dative:[{0:{action:"replace",value:"ю"}},{0:{action:"replace",value:"єві"}}],accusative:[{0:{action:"replace",value:"я"}}],ablative:[{0:{action:"replace",value:"єм"}}],locative:[{0:{action:"replace",value:"єві"}},{0:{action:"replace",value:"ю"}},{0:{action:"replace",value:"ї"}}],vocative:[{0:{action:"replace",value:"ю"}}]}},{description:"друга відміна / чоловічий рід / м'яка група / на -ь",examples:["петрунь"],wordClass:"noun",gender:["masculine"],priority:1,applicationType:[],pattern:{find:"ь$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"я"}}],dative:[{0:{action:"replace",value:"ю"}}],accusative:[{0:{action:"replace",value:"я"}}],ablative:[{0:{action:"replace",value:"ем"}}],locative:[{0:{action:"replace",value:"еві"}}],vocative:[{0:{action:"replace",value:"ю"}}]}},{description:"жіночі імена / на -('|`)я",examples:["дар'я","мар'я"],wordClass:"noun",gender:["feminine"],priority:1,applicationType:["givenName"],pattern:{find:"('|`)я$",modify:"(.{1})$"},grammaticalCases:{nominative:[],genitive:[{0:{action:"replace",value:"ї"}}],dative:[{0:{action:"replace",value:"ї"}}],accusative:[{0:{action:"replace",value:"ю"}}],ablative:[{0:{action:"replace",value:"єю"}}],locative:[{0:{action:"replace",value:"ї"}}],vocative:[{0:{action:"replace",value:"є"}}]}}],b=new class{constructor(e){this.declensionRules=[...e].sort(((e,t)=>t.priority-e.priority))}inflect(e,t){return a(this,void 0,void 0,(function*(){const[n]=yield this.findMatchingRules(e,t);return null==n?e:new v(n).inflect(e,t.grammaticalCase)}))}findMatchingRules(e,t){return a(this,void 0,void 0,(function*(){const n=this.declensionRules.filter((e=>e.gender.includes(t.gender))).filter((e=>!t.applicationType||0===e.applicationType.length||e.applicationType.includes(t.applicationType))).filter((t=>new RegExp(t.pattern.find,"gi").test(e))).filter((e=>!t.wordClass||e.wordClass===t.wordClass)).filter(((e,n,i)=>!t.customRuleFilter||t.customRuleFilter(e,n,i)));return n}))}}(y);class w{constructor(e,t){this.backend=e,this.dataMover=t,this.data=new WeakMap,this.dataIdsCount=0}get(e){return this.data.has(e)||this.dataMover.moveData(this.backend,e),this.data.get(e)}set(e,t){this.dataIdsCount++,this.data.set(e,t)}has(e){return this.data.has(e)}delete(e){return this.dataIdsCount--,this.data.delete(e)}numDataIds(){return this.dataIdsCount}}class k{refCount(e){return x("refCount")}incRef(e){return x("incRef")}timerAvailable(){return!0}time(e){return x("time")}read(e){return x("read")}readSync(e){return x("readSync")}readToGPU(e,t){return x("readToGPU")}numDataIds(){return x("numDataIds")}disposeData(e,t){return x("disposeData")}write(e,t,n){return x("write")}move(e,t,n,i,a){return x("move")}createTensorFromGPUData(e,t,n){return x("createTensorFromGPUData")}memory(){return x("memory")}floatPrecision(){return x("floatPrecision")}epsilon(){return 32===this.floatPrecision()?1e-7:1e-4}dispose(){return x("dispose")}}function x(e){throw new Error(`'${e}' not yet implemented or not found in the registry. This kernel may not be supported by the tfjs backend you have chosen`)}
11
11
  /**
12
12
  * @license
13
13
  * Copyright 2020 Google LLC. All Rights Reserved.
@@ -23,7 +23,7 @@
23
23
  * See the License for the specific language governing permissions and
24
24
  * limitations under the License.
25
25
  * =============================================================================
26
- */function S(e){let t=e.length,n=0;for(;t>0;)n=Math.random()*t|0,t--,N(e,t,n)}function N(e,t,n){const i=e[t];e[t]=e[n],e[n]=i}function I(e,t){if(!e)throw new Error("string"==typeof t?t:t())}function T(e,t,n=""){I(C(e,t),(()=>n+` Shapes ${e} and ${t} must match`))}function E(e){I(null!=e,(()=>"The input to the tensor constructor must be a non-null value."))}function A(e){if(0===e.length)return 1;let t=e[0];for(let n=1;n<e.length;n++)t*=e[n];return t}function C(e,t){if(e===t)return!0;if(null==e||null==t)return!1;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function $(e){return e%1==0}function j(e,t){return t<=e.length?e:e+" ".repeat(t-e.length)}function z(e,t){const n=t.length;return I((e=null==e?t.map(((e,t)=>t)):[].concat(e)).every((e=>e>=-n&&e<n)),(()=>`All values in axis param must be in range [-${n}, ${n}) but got axis ${e}`)),I(e.every((e=>$(e))),(()=>`All values in axis param must be integers but got axis ${e}`)),e.map((e=>e<0?n+e:e))}function D(e,t){let n=null;if(null==e||"float32"===e)n=new Float32Array(t);else if("int32"===e)n=new Int32Array(t);else{if("bool"!==e)throw new Error(`Unknown data type ${e}`);n=new Uint8Array(t)}return n}function F(e,t){let n=null;if(null==e||"float32"===e)n=new Float32Array(t);else if("int32"===e)n=new Int32Array(t);else if("bool"===e)n=new Uint8Array(t);else{if("string"!==e)throw new Error(`Unknown data type ${e}`);n=new Array(t)}return n}function _(e){if("float32"===e||"int32"===e)return 4;if("complex64"===e)return 8;if("bool"===e)return 1;throw new Error(`Unknown dtype ${e}`)}function R(e){return"string"==typeof e||e instanceof String}function L(e){return"number"==typeof e}function M(e){return Array.isArray(e)?M(e[0]):e instanceof Float32Array?"float32":e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray?"int32":L(e)?"float32":R(e)?"string":"boolean"==typeof e?"bool":"float32"}function O(e){return!!(e&&e.constructor&&e.call&&e.apply)}function P(e){const t=e.length;if(t<2)return[];const n=new Array(t-1);n[t-2]=e[t-1];for(let i=t-3;i>=0;--i)n[i]=n[i+1]*e[i+1];return n}function B(e,t,n,i=!1){const a=new Array;if(1===t.length){const s=t[0]*(i?2:1);for(let t=0;t<s;t++)a[t]=n[e+t]}else{const s=t[0],r=t.slice(1),o=r.reduce(((e,t)=>e*t))*(i?2:1);for(let t=0;t<s;t++)a[t]=B(e+t*o,r,n,i)}return a}function U(e,t,n=!1){if(0===e.length)return t[0];const i=e.reduce(((e,t)=>e*t))*(n?2:1);if(0===i)return[];if(i!==t.length)throw new Error(`[${e}] does not match the input size ${t.length}${n?" for a complex tensor":""}.`);return B(0,e,t,n)}function W(e,t){const n=G(e,t);for(let e=0;e<n.length;e++)n[e]=1;return n}function G(e,t){if(null==t||"float32"===t||"complex64"===t)return new Float32Array(e);if("int32"===t)return new Int32Array(e);if("bool"===t)return new Uint8Array(e);throw new Error(`Unknown data type ${t}`)}function V(e){e.forEach((t=>{I(Number.isInteger(t)&&t>=0,(()=>`Tensor must have a shape comprised of positive integers but got shape [${e}].`))}))}function K(e,t,n){if(0===t)return 0;if(1===t)return e[0];let i=e[e.length-1];for(let t=0;t<e.length-1;++t)i+=n[t]*e[t];return i}function q(e,t,n){if(0===t)return[];if(1===t)return[e];const i=new Array(t);for(let t=0;t<i.length-1;++t)i[t]=Math.floor(e/n[t]),e-=i[t]*n[t];return i[i.length-1]=e,i}function H(e){return e&&e.then&&"function"==typeof e.then}
26
+ */function S(e){let t=e.length,n=0;for(;t>0;)n=Math.random()*t|0,t--,N(e,t,n)}function N(e,t,n){const i=e[t];e[t]=e[n],e[n]=i}function T(e,t){if(!e)throw new Error("string"==typeof t?t:t())}function I(e,t,n=""){T(E(e,t),(()=>n+` Shapes ${e} and ${t} must match`))}function A(e){T(null!=e,(()=>"The input to the tensor constructor must be a non-null value."))}function C(e){if(0===e.length)return 1;let t=e[0];for(let n=1;n<e.length;n++)t*=e[n];return t}function E(e,t){if(e===t)return!0;if(null==e||null==t)return!1;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function $(e){return e%1==0}function j(e,t){return t<=e.length?e:e+" ".repeat(t-e.length)}function z(e,t){const n=t.length;return T((e=null==e?t.map(((e,t)=>t)):[].concat(e)).every((e=>e>=-n&&e<n)),(()=>`All values in axis param must be in range [-${n}, ${n}) but got axis ${e}`)),T(e.every((e=>$(e))),(()=>`All values in axis param must be integers but got axis ${e}`)),e.map((e=>e<0?n+e:e))}function D(e,t){let n=null;if(null==e||"float32"===e)n=new Float32Array(t);else if("int32"===e)n=new Int32Array(t);else{if("bool"!==e)throw new Error(`Unknown data type ${e}`);n=new Uint8Array(t)}return n}function F(e,t){let n=null;if(null==e||"float32"===e)n=new Float32Array(t);else if("int32"===e)n=new Int32Array(t);else if("bool"===e)n=new Uint8Array(t);else{if("string"!==e)throw new Error(`Unknown data type ${e}`);n=new Array(t)}return n}function _(e){if("float32"===e||"int32"===e)return 4;if("complex64"===e)return 8;if("bool"===e)return 1;throw new Error(`Unknown dtype ${e}`)}function R(e){return"string"==typeof e||e instanceof String}function L(e){return"number"==typeof e}function M(e){return Array.isArray(e)?M(e[0]):e instanceof Float32Array?"float32":e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray?"int32":L(e)?"float32":R(e)?"string":"boolean"==typeof e?"bool":"float32"}function O(e){return!!(e&&e.constructor&&e.call&&e.apply)}function P(e){const t=e.length;if(t<2)return[];const n=new Array(t-1);n[t-2]=e[t-1];for(let i=t-3;i>=0;--i)n[i]=n[i+1]*e[i+1];return n}function B(e,t,n,i=!1){const a=new Array;if(1===t.length){const s=t[0]*(i?2:1);for(let t=0;t<s;t++)a[t]=n[e+t]}else{const s=t[0],r=t.slice(1),o=r.reduce(((e,t)=>e*t))*(i?2:1);for(let t=0;t<s;t++)a[t]=B(e+t*o,r,n,i)}return a}function U(e,t,n=!1){if(0===e.length)return t[0];const i=e.reduce(((e,t)=>e*t))*(n?2:1);if(0===i)return[];if(i!==t.length)throw new Error(`[${e}] does not match the input size ${t.length}${n?" for a complex tensor":""}.`);return B(0,e,t,n)}function W(e,t){const n=V(e,t);for(let e=0;e<n.length;e++)n[e]=1;return n}function V(e,t){if(null==t||"float32"===t||"complex64"===t)return new Float32Array(e);if("int32"===t)return new Int32Array(e);if("bool"===t)return new Uint8Array(e);throw new Error(`Unknown data type ${t}`)}function G(e){e.forEach((t=>{T(Number.isInteger(t)&&t>=0,(()=>`Tensor must have a shape comprised of positive integers but got shape [${e}].`))}))}function K(e,t,n){if(0===t)return 0;if(1===t)return e[0];let i=e[e.length-1];for(let t=0;t<e.length-1;++t)i+=n[t]*e[t];return i}function q(e,t,n){if(0===t)return[];if(1===t)return[e];const i=new Array(t);for(let t=0;t<i.length-1;++t)i[t]=Math.floor(e/n[t]),e-=i[t]*n[t];return i[i.length-1]=e,i}function H(e){return e&&e.then&&"function"==typeof e.then}
27
27
  /**
28
28
  * @license
29
29
  * Copyright 2017 Google LLC. All Rights Reserved.
@@ -39,7 +39,7 @@
39
39
  * See the License for the specific language governing permissions and
40
40
  * limitations under the License.
41
41
  * =============================================================================
42
- */const J="tfjsflags";class Z{constructor(e){this.global=e,this.flags={},this.flagRegistry={},this.urlFlags={},this.getQueryParams=Y,this.populateURLFlags()}setPlatform(e,t){null!=this.platform&&(Q().getBool("IS_TEST")||Q().getBool("PROD")||console.warn(`Platform ${this.platformName} has already been set. Overwriting the platform with ${e}.`)),this.platformName=e,this.platform=t}registerFlag(e,t,n){if(this.flagRegistry[e]={evaluationFn:t,setHook:n},null!=this.urlFlags[e]){const t=this.urlFlags[e];Q().getBool("IS_TEST")||Q().getBool("PROD")||console.warn(`Setting feature override from URL ${e}: ${t}.`),this.set(e,t)}}async getAsync(e){return e in this.flags||(this.flags[e]=await this.evaluateFlag(e)),this.flags[e]}get(e){if(e in this.flags)return this.flags[e];const t=this.evaluateFlag(e);if(H(t))throw new Error(`Flag ${e} cannot be synchronously evaluated. Please use getAsync() instead.`);return this.flags[e]=t,this.flags[e]}getNumber(e){return this.get(e)}getBool(e){return this.get(e)}getFlags(){return this.flags}get features(){return this.flags}set(e,t){if(null==this.flagRegistry[e])throw new Error(`Cannot set flag ${e} as it has not been registered.`);this.flags[e]=t,null!=this.flagRegistry[e].setHook&&this.flagRegistry[e].setHook(t)}evaluateFlag(e){if(null==this.flagRegistry[e])throw new Error(`Cannot evaluate flag '${e}': no evaluation function found.`);return this.flagRegistry[e].evaluationFn()}setFlags(e){this.flags=Object.assign({},e)}reset(){this.flags={},this.urlFlags={},this.populateURLFlags()}populateURLFlags(){if(void 0===this.global||void 0===this.global.location||void 0===this.global.location.search)return;const e=this.getQueryParams(this.global.location.search);if(J in e){e[J].split(",").forEach((e=>{const[t,n]=e.split(":");this.urlFlags[t]=function(e,t){if("true"===(t=t.toLowerCase())||"false"===t)return"true"===t;if(""+ +t===t)return+t;throw new Error(`Could not parse value flag value ${t} for flag ${e}.`)}(t,n)}))}}}function Y(e){const t={};return e.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,((e,...n)=>(function(e,t,n){e[decodeURIComponent(t)]=decodeURIComponent(n||"")}(t,n[0],n[1]),n.join("=")))),t}function Q(){return ee}let X,ee=null;function te(){if(null==X){let e;if("undefined"!=typeof window)e=window;else if("undefined"!=typeof global)e=global;else if("undefined"!=typeof process)e=process;else{if("undefined"==typeof self)throw new Error("Could not find a global object");e=self}X=e}return X}function ne(e,t){const n=function(){const e=te();return null==e._tfGlobals&&(e._tfGlobals=new Map),e._tfGlobals}();if(n.has(e))return n.get(e);{const i=t();return n.set(e,i),n.get(e)}}const ie="Add",ae="ArgMax",se="AvgPool",re="AvgPool3D",oe="BatchMatMul",le="BatchToSpaceND",ce="Cast",ue="ClipByValue",he="ComplexAbs",pe="Concat",de="Conv2D",me="Conv2DBackpropInput",fe="Conv3D",ge="Cosh",ve="Cumsum",ye="DepthwiseConv2dNative",be="RealDiv",we="Elu",ke="ExpandDims",xe="Floor",Se="FloorDiv",Ne="FusedBatchNorm",Ie="GatherV2",Te="GreaterEqual",Ee="Identity",Ae="LeakyRelu",Ce="Log1p",$e="Maximum",je="MaxPool",ze="MaxPool3D",De="Mean",Fe="Minimum",_e="Multiply",Re="OnesLike",Le="OneHot",Me="Pack",Oe="PadV2",Pe="Prelu",Be="Relu",Ue="Reshape",We="ResizeNearestNeighbor",Ge="ResizeBilinear",Ve="Relu6",Ke="Reverse",qe="Round",He="Rsqrt",Je="Select",Ze="Selu",Ye="Slice",Qe="Sinh",Xe="Sigmoid",et="Softplus",tt="Sqrt",nt="Sum",it="SpaceToBatchND",at="SplitV",st="Softmax",rt="SquaredDifference",ot="Tanh",lt="Tile",ct="Transpose",ut="Unpack",ht="UnsortedSegmentSum",pt="ZerosLike",dt="Step",mt="_FusedMatMul",ft="FusedConv2D";
42
+ */const J="tfjsflags";class Z{constructor(e){this.global=e,this.flags={},this.flagRegistry={},this.urlFlags={},this.getQueryParams=Y,this.populateURLFlags()}setPlatform(e,t){null!=this.platform&&(Q().getBool("IS_TEST")||Q().getBool("PROD")||console.warn(`Platform ${this.platformName} has already been set. Overwriting the platform with ${e}.`)),this.platformName=e,this.platform=t}registerFlag(e,t,n){if(this.flagRegistry[e]={evaluationFn:t,setHook:n},null!=this.urlFlags[e]){const t=this.urlFlags[e];Q().getBool("IS_TEST")||Q().getBool("PROD")||console.warn(`Setting feature override from URL ${e}: ${t}.`),this.set(e,t)}}async getAsync(e){return e in this.flags||(this.flags[e]=await this.evaluateFlag(e)),this.flags[e]}get(e){if(e in this.flags)return this.flags[e];const t=this.evaluateFlag(e);if(H(t))throw new Error(`Flag ${e} cannot be synchronously evaluated. Please use getAsync() instead.`);return this.flags[e]=t,this.flags[e]}getNumber(e){return this.get(e)}getBool(e){return this.get(e)}getFlags(){return this.flags}get features(){return this.flags}set(e,t){if(null==this.flagRegistry[e])throw new Error(`Cannot set flag ${e} as it has not been registered.`);this.flags[e]=t,null!=this.flagRegistry[e].setHook&&this.flagRegistry[e].setHook(t)}evaluateFlag(e){if(null==this.flagRegistry[e])throw new Error(`Cannot evaluate flag '${e}': no evaluation function found.`);return this.flagRegistry[e].evaluationFn()}setFlags(e){this.flags=Object.assign({},e)}reset(){this.flags={},this.urlFlags={},this.populateURLFlags()}populateURLFlags(){if(void 0===this.global||void 0===this.global.location||void 0===this.global.location.search)return;const e=this.getQueryParams(this.global.location.search);if(J in e){e[J].split(",").forEach((e=>{const[t,n]=e.split(":");this.urlFlags[t]=function(e,t){if("true"===(t=t.toLowerCase())||"false"===t)return"true"===t;if(""+ +t===t)return+t;throw new Error(`Could not parse value flag value ${t} for flag ${e}.`)}(t,n)}))}}}function Y(e){const t={};return e.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,((e,...n)=>(function(e,t,n){e[decodeURIComponent(t)]=decodeURIComponent(n||"")}(t,n[0],n[1]),n.join("=")))),t}function Q(){return ee}let X,ee=null;function te(){if(null==X){let e;if("undefined"!=typeof window)e=window;else if("undefined"!=typeof global)e=global;else if("undefined"!=typeof process)e=process;else{if("undefined"==typeof self)throw new Error("Could not find a global object");e=self}X=e}return X}function ne(e,t){const n=function(){const e=te();return null==e._tfGlobals&&(e._tfGlobals=new Map),e._tfGlobals}();if(n.has(e))return n.get(e);{const i=t();return n.set(e,i),n.get(e)}}const ie="Add",ae="ArgMax",se="AvgPool",re="AvgPool3D",oe="BatchMatMul",le="BatchToSpaceND",ce="Cast",ue="ClipByValue",he="ComplexAbs",pe="Concat",de="Conv2D",me="Conv2DBackpropInput",fe="Conv3D",ge="Cosh",ve="Cumsum",ye="DepthwiseConv2dNative",be="RealDiv",we="Elu",ke="ExpandDims",xe="Floor",Se="FloorDiv",Ne="FusedBatchNorm",Te="GatherV2",Ie="GreaterEqual",Ae="Identity",Ce="LeakyRelu",Ee="Log1p",$e="Maximum",je="MaxPool",ze="MaxPool3D",De="Mean",Fe="Minimum",_e="Multiply",Re="OnesLike",Le="OneHot",Me="Pack",Oe="PadV2",Pe="Prelu",Be="Relu",Ue="Reshape",We="ResizeNearestNeighbor",Ve="ResizeBilinear",Ge="Relu6",Ke="Reverse",qe="Round",He="Rsqrt",Je="Select",Ze="Selu",Ye="Slice",Qe="Sinh",Xe="Sigmoid",et="Softplus",tt="Sqrt",nt="Sum",it="SpaceToBatchND",at="SplitV",st="Softmax",rt="SquaredDifference",ot="Tanh",lt="Tile",ct="Transpose",ut="Unpack",ht="UnsortedSegmentSum",pt="ZerosLike",dt="Step",mt="_FusedMatMul",ft="FusedConv2D";
43
43
  /**
44
44
  * @license
45
45
  * Copyright 2018 Google LLC. All Rights Reserved.
@@ -88,7 +88,7 @@ function gt(...e){Q().getBool("IS_TEST")||Q().getBool("PROD")||console.warn(...e
88
88
  * See the License for the specific language governing permissions and
89
89
  * limitations under the License.
90
90
  * =============================================================================
91
- */function It(e,t){if("string"===t)throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(e)&&(e=$t(e)),Q().getBool("DEBUG")&&function(e,t){for(let n=0;n<e.length;n++){const i=e[n];if(isNaN(i)||!isFinite(i))throw Error(`A tensor of type ${t} being uploaded contains ${i}.`)}}(e,t),function(e,t){return e instanceof Float32Array&&"float32"===t||e instanceof Int32Array&&"int32"===t||e instanceof Uint8Array&&"bool"===t}(e,t))return e;if(null==t||"float32"===t||"complex64"===t)return new Float32Array(e);if("int32"===t)return new Int32Array(e);if("bool"===t){const t=new Uint8Array(e.length);for(let n=0;n<t.length;++n)0!==Math.round(e[n])&&(t[n]=1);return t}throw new Error(`Unknown data type ${t}`)}function Tt(){return Q().platform.now()}function Et(e,t="utf-8"){return t=t||"utf-8",Q().platform.encode(e,t)}function At(e,t="utf-8"){return t=t||"utf-8",Q().platform.decode(e,t)}function Ct(e){return Q().platform.isTypedArray(e)}function $t(e,t=[],n=!1){if(null==t&&(t=[]),"boolean"==typeof e||"number"==typeof e||"string"==typeof e||H(e)||null==e||Ct(e)&&n)t.push(e);else if(Array.isArray(e)||Ct(e))for(let i=0;i<e.length;++i)$t(e[i],t,n);else{let i=-1;for(const t of Object.keys(e))/^([1-9]+[0-9]*|0)$/.test(t)&&(i=Math.max(i,Number(t)));for(let a=0;a<=i;a++)$t(e[a],t,n)}return t}
91
+ */function Tt(e,t){if("string"===t)throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(e)&&(e=$t(e)),Q().getBool("DEBUG")&&function(e,t){for(let n=0;n<e.length;n++){const i=e[n];if(isNaN(i)||!isFinite(i))throw Error(`A tensor of type ${t} being uploaded contains ${i}.`)}}(e,t),function(e,t){return e instanceof Float32Array&&"float32"===t||e instanceof Int32Array&&"int32"===t||e instanceof Uint8Array&&"bool"===t}(e,t))return e;if(null==t||"float32"===t||"complex64"===t)return new Float32Array(e);if("int32"===t)return new Int32Array(e);if("bool"===t){const t=new Uint8Array(e.length);for(let n=0;n<t.length;++n)0!==Math.round(e[n])&&(t[n]=1);return t}throw new Error(`Unknown data type ${t}`)}function It(){return Q().platform.now()}function At(e,t="utf-8"){return t=t||"utf-8",Q().platform.encode(e,t)}function Ct(e,t="utf-8"){return t=t||"utf-8",Q().platform.decode(e,t)}function Et(e){return Q().platform.isTypedArray(e)}function $t(e,t=[],n=!1){if(null==t&&(t=[]),"boolean"==typeof e||"number"==typeof e||"string"==typeof e||H(e)||null==e||Et(e)&&n)t.push(e);else if(Array.isArray(e)||Et(e))for(let i=0;i<e.length;++i)$t(e[i],t,n);else{let i=-1;for(const t of Object.keys(e))/^([1-9]+[0-9]*|0)$/.test(t)&&(i=Math.max(i,Number(t)));for(let a=0;a<=i;a++)$t(e[a],t,n)}return t}
92
92
  /**
93
93
  * @license
94
94
  * Copyright 2018 Google LLC. All Rights Reserved.
@@ -104,7 +104,7 @@ function gt(...e){Q().getBool("IS_TEST")||Q().getBool("PROD")||console.warn(...e
104
104
  * See the License for the specific language governing permissions and
105
105
  * limitations under the License.
106
106
  * =============================================================================
107
- */class jt{constructor(e,t){this.backendTimer=e,this.logger=t,null==t&&(this.logger=new Dt)}profileKernel(e,t,n){let i;const a=()=>{i=n()};let s;const r=Tt();if(this.backendTimer.timerAvailable())s=this.backendTimer.time(a);else{a();for(const e of i)e.dataSync();s=Promise.resolve({kernelMs:Tt()-r})}if(Q().getBool("CHECK_COMPUTATION_FOR_ERRORS"))for(let t=0;t<i.length;t++){const n=i[t];n.data().then((t=>{zt(t,n.dtype,e)}))}return{kernelName:e,outputs:i,inputs:t,timeMs:s.then((e=>e.kernelMs)),extraInfo:s.then((e=>null!=e.getExtraProfileInfo?e.getExtraProfileInfo():""))}}logKernelProfile(e){const{kernelName:t,outputs:n,timeMs:i,inputs:a,extraInfo:s}=e;n.forEach((e=>{Promise.all([e.data(),i,s]).then((n=>{this.logger.logKernelProfile(t,e,n[0],n[1],a,n[2])}))}))}}function zt(e,t,n){if("float32"!==t)return!1;for(let t=0;t<e.length;t++){const i=e[t];if(isNaN(i)||!isFinite(i))return console.warn(`Found ${i} in the result of '${n}'`),!0}return!1}class Dt{logKernelProfile(e,t,n,i,a,s){const r="number"==typeof i?j(`${i}ms`,9):i.error,o=j(e,25),l=t.rank,c=t.size,u=j(t.shape.toString(),14);let h="";for(const e in a){const n=a[e];if(null!=n){const i=n.shape||t.shape,a=i.length;h+=`${e}: ${a}D ${a>0?i:""} `}}console.log(`%c${o}\t%c${r}\t%c${l}D ${u}\t%c${c}\t%c${h}\t%c${s}`,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")}}
107
+ */class jt{constructor(e,t){this.backendTimer=e,this.logger=t,null==t&&(this.logger=new Dt)}profileKernel(e,t,n){let i;const a=()=>{i=n()};let s;const r=It();if(this.backendTimer.timerAvailable())s=this.backendTimer.time(a);else{a();for(const e of i)e.dataSync();s=Promise.resolve({kernelMs:It()-r})}if(Q().getBool("CHECK_COMPUTATION_FOR_ERRORS"))for(let t=0;t<i.length;t++){const n=i[t];n.data().then((t=>{zt(t,n.dtype,e)}))}return{kernelName:e,outputs:i,inputs:t,timeMs:s.then((e=>e.kernelMs)),extraInfo:s.then((e=>null!=e.getExtraProfileInfo?e.getExtraProfileInfo():""))}}logKernelProfile(e){const{kernelName:t,outputs:n,timeMs:i,inputs:a,extraInfo:s}=e;n.forEach((e=>{Promise.all([e.data(),i,s]).then((n=>{this.logger.logKernelProfile(t,e,n[0],n[1],a,n[2])}))}))}}function zt(e,t,n){if("float32"!==t)return!1;for(let t=0;t<e.length;t++){const i=e[t];if(isNaN(i)||!isFinite(i))return console.warn(`Found ${i} in the result of '${n}'`),!0}return!1}class Dt{logKernelProfile(e,t,n,i,a,s){const r="number"==typeof i?j(`${i}ms`,9):i.error,o=j(e,25),l=t.rank,c=t.size,u=j(t.shape.toString(),14);let h="";for(const e in a){const n=a[e];if(null!=n){const i=n.shape||t.shape,a=i.length;h+=`${e}: ${a}D ${a>0?i:""} `}}console.log(`%c${o}\t%c${r}\t%c${l}D ${u}\t%c${c}\t%c${h}\t%c${s}`,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")}}
108
108
  /**
109
109
  * @license
110
110
  * Copyright 2017 Google LLC. All Rights Reserved.
@@ -120,7 +120,7 @@ function gt(...e){Q().getBool("IS_TEST")||Q().getBool("PROD")||console.warn(...e
120
120
  * See the License for the specific language governing permissions and
121
121
  * limitations under the License.
122
122
  * =============================================================================
123
- */function Ft(e,t,n,i){const a=P(t),s=function(e,t,n,i){const a=A(t),s=i[i.length-1],r=new Array(s).fill(0),o=t.length,l="complex64"===n?Mt(e):e;if(o>1)for(let e=0;e<a/s;e++){const t=e*s;for(let e=0;e<s;e++)r[e]=Math.max(r[e],_t(l[t+e],0,n).length)}return r}(e,t,n,a),r=t.length,o=Lt(e,t,n,a,s),l=["Tensor"];return i&&(l.push(` dtype: ${n}`),l.push(` rank: ${r}`),l.push(` shape: [${t}]`),l.push(" values:")),l.push(o.map((e=>" "+e)).join("\n")),l.join("\n")}function _t(e,t,n){let i;return i=Array.isArray(e)?`${parseFloat(e[0].toFixed(7))} + ${parseFloat(e[1].toFixed(7))}j`:R(e)?`'${e}'`:"bool"===n?Rt(e):parseFloat(e.toFixed(7)).toString(),j(i,t)}function Rt(e){return 0===e?"false":"true"}function Lt(e,t,n,i,a,s=!0){const r="complex64"===n?2:1,o=t[0],l=t.length;if(0===l){if("complex64"===n){return[_t(Mt(e)[0],0,n)]}return"bool"===n?[Rt(e[0])]:[e[0].toString()]}if(1===l){if(o>20){const t=3*r;let i=Array.from(e.slice(0,t)),s=Array.from(e.slice((o-3)*r,o*r));return"complex64"===n&&(i=Mt(i),s=Mt(s)),["["+i.map(((e,t)=>_t(e,a[t],n))).join(", ")+", ..., "+s.map(((e,t)=>_t(e,a[o-3+t],n))).join(", ")+"]"]}return["["+("complex64"===n?Mt(e):Array.from(e)).map(((e,t)=>_t(e,a[t],n))).join(", ")+"]"]}const c=t.slice(1),u=i.slice(1),h=i[0]*r,p=[];if(o>20){for(let t=0;t<3;t++){const i=t*h,s=i+h;p.push(...Lt(e.slice(i,s),c,n,u,a,!1))}p.push("...");for(let t=o-3;t<o;t++){const i=t*h,s=i+h;p.push(...Lt(e.slice(i,s),c,n,u,a,t===o-1))}}else for(let t=0;t<o;t++){const i=t*h,s=i+h;p.push(...Lt(e.slice(i,s),c,n,u,a,t===o-1))}const d=2===l?",":"";p[0]="["+(o>0?p[0]+d:"");for(let e=1;e<p.length-1;e++)p[e]=" "+p[e]+d;let m=",\n";for(let e=2;e<l;e++)m+="\n";return p[p.length-1]=" "+p[p.length-1]+"]"+(s?"":m),p}function Mt(e){const t=[];for(let n=0;n<e.length;n+=2)t.push([e[n],e[n+1]]);return t}
123
+ */function Ft(e,t,n,i){const a=P(t),s=function(e,t,n,i){const a=C(t),s=i[i.length-1],r=new Array(s).fill(0),o=t.length,l="complex64"===n?Mt(e):e;if(o>1)for(let e=0;e<a/s;e++){const t=e*s;for(let e=0;e<s;e++)r[e]=Math.max(r[e],_t(l[t+e],0,n).length)}return r}(e,t,n,a),r=t.length,o=Lt(e,t,n,a,s),l=["Tensor"];return i&&(l.push(` dtype: ${n}`),l.push(` rank: ${r}`),l.push(` shape: [${t}]`),l.push(" values:")),l.push(o.map((e=>" "+e)).join("\n")),l.join("\n")}function _t(e,t,n){let i;return i=Array.isArray(e)?`${parseFloat(e[0].toFixed(7))} + ${parseFloat(e[1].toFixed(7))}j`:R(e)?`'${e}'`:"bool"===n?Rt(e):parseFloat(e.toFixed(7)).toString(),j(i,t)}function Rt(e){return 0===e?"false":"true"}function Lt(e,t,n,i,a,s=!0){const r="complex64"===n?2:1,o=t[0],l=t.length;if(0===l){if("complex64"===n){return[_t(Mt(e)[0],0,n)]}return"bool"===n?[Rt(e[0])]:[e[0].toString()]}if(1===l){if(o>20){const t=3*r;let i=Array.from(e.slice(0,t)),s=Array.from(e.slice((o-3)*r,o*r));return"complex64"===n&&(i=Mt(i),s=Mt(s)),["["+i.map(((e,t)=>_t(e,a[t],n))).join(", ")+", ..., "+s.map(((e,t)=>_t(e,a[o-3+t],n))).join(", ")+"]"]}return["["+("complex64"===n?Mt(e):Array.from(e)).map(((e,t)=>_t(e,a[t],n))).join(", ")+"]"]}const c=t.slice(1),u=i.slice(1),h=i[0]*r,p=[];if(o>20){for(let t=0;t<3;t++){const i=t*h,s=i+h;p.push(...Lt(e.slice(i,s),c,n,u,a,!1))}p.push("...");for(let t=o-3;t<o;t++){const i=t*h,s=i+h;p.push(...Lt(e.slice(i,s),c,n,u,a,t===o-1))}}else for(let t=0;t<o;t++){const i=t*h,s=i+h;p.push(...Lt(e.slice(i,s),c,n,u,a,t===o-1))}const d=2===l?",":"";p[0]="["+(o>0?p[0]+d:"");for(let e=1;e<p.length-1;e++)p[e]=" "+p[e]+d;let m=",\n";for(let e=2;e<l;e++)m+="\n";return p[p.length-1]=" "+p[p.length-1]+"]"+(s?"":m),p}function Mt(e){const t=[];for(let n=0;n<e.length;n+=2)t.push([e[n],e[n+1]]);return t}
124
124
  /**
125
125
  * @license
126
126
  * Copyright 2017 Google LLC. All Rights Reserved.
@@ -136,7 +136,7 @@ function gt(...e){Q().getBool("IS_TEST")||Q().getBool("PROD")||console.warn(...e
136
136
  * See the License for the specific language governing permissions and
137
137
  * limitations under the License.
138
138
  * =============================================================================
139
- */class Ot{constructor(e,t,n){if(this.dtype=t,this.shape=e.slice(),this.size=A(e),null!=n){const e=n.length;I(e===this.size,(()=>`Length of values '${e}' does not match the size inferred by the shape '${this.size}'.`))}if("complex64"===t)throw new Error("complex64 dtype TensorBuffers are not supported. Please create a TensorBuffer for the real and imaginary parts separately and call tf.complex(real, imag).");this.values=n||F(t,this.size),this.strides=P(e)}set(e,...t){0===t.length&&(t=[0]),I(t.length===this.rank,(()=>`The number of provided coordinates (${t.length}) must match the rank (${this.rank})`));const n=this.locToIndex(t);this.values[n]=e}get(...e){0===e.length&&(e=[0]);let t=0;for(const n of e){if(n<0||n>=this.shape[t]){const t=`Requested out of range element at ${e}. Buffer shape=${this.shape}`;throw new Error(t)}t++}let n=e[e.length-1];for(let t=0;t<e.length-1;++t)n+=this.strides[t]*e[t];return this.values[n]}locToIndex(e){if(0===this.rank)return 0;if(1===this.rank)return e[0];let t=e[e.length-1];for(let n=0;n<e.length-1;++n)t+=this.strides[n]*e[n];return t}indexToLoc(e){if(0===this.rank)return[];if(1===this.rank)return[e];const t=new Array(this.shape.length);for(let n=0;n<t.length-1;++n)t[n]=Math.floor(e/this.strides[n]),e-=t[n]*this.strides[n];return t[t.length-1]=e,t}get rank(){return this.shape.length}toTensor(){return Pt().makeTensor(this.values,this.shape,this.dtype)}}let Pt=null,Bt=null;class Ut{constructor(e,t,n,i){this.kept=!1,this.isDisposedInternal=!1,this.shape=e.slice(),this.dtype=t||"float32",this.size=A(e),this.strides=P(e),this.dataId=n,this.id=i,this.rankType=this.rank<5?this.rank.toString():"higher"}get rank(){return this.shape.length}async buffer(){const e=await this.data();return Bt.buffer(this.shape,this.dtype,e)}bufferSync(){return Bt.buffer(this.shape,this.dtype,this.dataSync())}async array(){const e=await this.data();return U(this.shape,e,"complex64"===this.dtype)}arraySync(){return U(this.shape,this.dataSync(),"complex64"===this.dtype)}async data(){this.throwIfDisposed();const e=Pt().read(this.dataId);if("string"===this.dtype){const t=await e;try{return t.map((e=>At(e)))}catch(e){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}}return e}dataToGPU(e){return this.throwIfDisposed(),Pt().readToGPU(this.dataId,e)}dataSync(){this.throwIfDisposed();const e=Pt().readSync(this.dataId);if("string"===this.dtype)try{return e.map((e=>At(e)))}catch(e){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}return e}async bytes(){this.throwIfDisposed();const e=await Pt().read(this.dataId);return"string"===this.dtype?e:new Uint8Array(e.buffer)}dispose(){this.isDisposed||(Pt().disposeTensor(this),this.isDisposedInternal=!0)}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return Bt.print(this,e)}clone(){return this.throwIfDisposed(),Bt.clone(this)}toString(e=!1){return Ft(this.dataSync(),this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),Bt.cast(this,e)}variable(e=!0,t,n){return this.throwIfDisposed(),Pt().makeVariable(this,e,t,n)}}Object.defineProperty(Ut,Symbol.hasInstance,{value:e=>!!e&&null!=e.data&&null!=e.dataSync&&null!=e.throwIfDisposed}),ne("Tensor",(()=>Ut));class Wt extends Ut{constructor(e,t,n,i){super(e.shape,e.dtype,e.dataId,i),this.trainable=t,this.name=n}assign(e){if(e.dtype!==this.dtype)throw new Error(`dtype of the new value (${e.dtype}) and previous value (${this.dtype}) must match`);if(!C(e.shape,this.shape))throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);Pt().disposeTensor(this),this.dataId=e.dataId,Pt().incRef(this,null)}dispose(){Pt().disposeVariable(this),this.isDisposedInternal=!0}}
139
+ */class Ot{constructor(e,t,n){if(this.dtype=t,this.shape=e.slice(),this.size=C(e),null!=n){const e=n.length;T(e===this.size,(()=>`Length of values '${e}' does not match the size inferred by the shape '${this.size}'.`))}if("complex64"===t)throw new Error("complex64 dtype TensorBuffers are not supported. Please create a TensorBuffer for the real and imaginary parts separately and call tf.complex(real, imag).");this.values=n||F(t,this.size),this.strides=P(e)}set(e,...t){0===t.length&&(t=[0]),T(t.length===this.rank,(()=>`The number of provided coordinates (${t.length}) must match the rank (${this.rank})`));const n=this.locToIndex(t);this.values[n]=e}get(...e){0===e.length&&(e=[0]);let t=0;for(const n of e){if(n<0||n>=this.shape[t]){const t=`Requested out of range element at ${e}. Buffer shape=${this.shape}`;throw new Error(t)}t++}let n=e[e.length-1];for(let t=0;t<e.length-1;++t)n+=this.strides[t]*e[t];return this.values[n]}locToIndex(e){if(0===this.rank)return 0;if(1===this.rank)return e[0];let t=e[e.length-1];for(let n=0;n<e.length-1;++n)t+=this.strides[n]*e[n];return t}indexToLoc(e){if(0===this.rank)return[];if(1===this.rank)return[e];const t=new Array(this.shape.length);for(let n=0;n<t.length-1;++n)t[n]=Math.floor(e/this.strides[n]),e-=t[n]*this.strides[n];return t[t.length-1]=e,t}get rank(){return this.shape.length}toTensor(){return Pt().makeTensor(this.values,this.shape,this.dtype)}}let Pt=null,Bt=null;class Ut{constructor(e,t,n,i){this.kept=!1,this.isDisposedInternal=!1,this.shape=e.slice(),this.dtype=t||"float32",this.size=C(e),this.strides=P(e),this.dataId=n,this.id=i,this.rankType=this.rank<5?this.rank.toString():"higher"}get rank(){return this.shape.length}async buffer(){const e=await this.data();return Bt.buffer(this.shape,this.dtype,e)}bufferSync(){return Bt.buffer(this.shape,this.dtype,this.dataSync())}async array(){const e=await this.data();return U(this.shape,e,"complex64"===this.dtype)}arraySync(){return U(this.shape,this.dataSync(),"complex64"===this.dtype)}async data(){this.throwIfDisposed();const e=Pt().read(this.dataId);if("string"===this.dtype){const t=await e;try{return t.map((e=>Ct(e)))}catch(e){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}}return e}dataToGPU(e){return this.throwIfDisposed(),Pt().readToGPU(this.dataId,e)}dataSync(){this.throwIfDisposed();const e=Pt().readSync(this.dataId);if("string"===this.dtype)try{return e.map((e=>Ct(e)))}catch(e){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}return e}async bytes(){this.throwIfDisposed();const e=await Pt().read(this.dataId);return"string"===this.dtype?e:new Uint8Array(e.buffer)}dispose(){this.isDisposed||(Pt().disposeTensor(this),this.isDisposedInternal=!0)}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return Bt.print(this,e)}clone(){return this.throwIfDisposed(),Bt.clone(this)}toString(e=!1){return Ft(this.dataSync(),this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),Bt.cast(this,e)}variable(e=!0,t,n){return this.throwIfDisposed(),Pt().makeVariable(this,e,t,n)}}Object.defineProperty(Ut,Symbol.hasInstance,{value:e=>!!e&&null!=e.data&&null!=e.dataSync&&null!=e.throwIfDisposed}),ne("Tensor",(()=>Ut));class Wt extends Ut{constructor(e,t,n,i){super(e.shape,e.dtype,e.dataId,i),this.trainable=t,this.name=n}assign(e){if(e.dtype!==this.dtype)throw new Error(`dtype of the new value (${e.dtype}) and previous value (${this.dtype}) must match`);if(!E(e.shape,this.shape))throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);Pt().disposeTensor(this),this.dataId=e.dataId,Pt().incRef(this,null)}dispose(){Pt().disposeVariable(this),this.isDisposedInternal=!0}}
140
140
  /**
141
141
  * @license
142
142
  * Copyright 2017 Google LLC. All Rights Reserved.
@@ -153,7 +153,7 @@ function gt(...e){Q().getBool("IS_TEST")||Q().getBool("PROD")||console.warn(...e
153
153
  * limitations under the License.
154
154
  * =============================================================================
155
155
  */
156
- var Gt,Vt,Kt,qt,Ht;Object.defineProperty(Wt,Symbol.hasInstance,{value:e=>e instanceof Ut&&null!=e.assign&&e.assign instanceof Function}),function(e){e.R0="R0",e.R1="R1",e.R2="R2",e.R3="R3",e.R4="R4",e.R5="R5",e.R6="R6"}(Gt||(Gt={})),function(e){e.float32="float32",e.int32="int32",e.bool="int32",e.complex64="complex64"}(Vt||(Vt={})),function(e){e.float32="float32",e.int32="int32",e.bool="bool",e.complex64="complex64"}(Kt||(Kt={})),function(e){e.float32="float32",e.int32="float32",e.bool="float32",e.complex64="complex64"}(qt||(qt={})),function(e){e.float32="complex64",e.int32="complex64",e.bool="complex64",e.complex64="complex64"}(Ht||(Ht={}));const Jt={float32:qt,int32:Vt,bool:Kt,complex64:Ht};function Zt(e,t){if("string"===e||"string"===t){if("string"===e&&"string"===t)return"string";throw new Error(`Can not upcast ${e} with ${t}`)}return Jt[e][t]}
156
+ var Vt,Gt,Kt,qt,Ht;Object.defineProperty(Wt,Symbol.hasInstance,{value:e=>e instanceof Ut&&null!=e.assign&&e.assign instanceof Function}),function(e){e.R0="R0",e.R1="R1",e.R2="R2",e.R3="R3",e.R4="R4",e.R5="R5",e.R6="R6"}(Vt||(Vt={})),function(e){e.float32="float32",e.int32="int32",e.bool="int32",e.complex64="complex64"}(Gt||(Gt={})),function(e){e.float32="float32",e.int32="int32",e.bool="bool",e.complex64="complex64"}(Kt||(Kt={})),function(e){e.float32="float32",e.int32="float32",e.bool="float32",e.complex64="complex64"}(qt||(qt={})),function(e){e.float32="complex64",e.int32="complex64",e.bool="complex64",e.complex64="complex64"}(Ht||(Ht={}));const Jt={float32:qt,int32:Gt,bool:Kt,complex64:Ht};function Zt(e,t){if("string"===e||"string"===t){if("string"===e&&"string"===t)return"string";throw new Error(`Can not upcast ${e} with ${t}`)}return Jt[e][t]}
157
157
  /**
158
158
  * @license
159
159
  * Copyright 2018 Google LLC. All Rights Reserved.
@@ -185,7 +185,7 @@ var Gt,Vt,Kt,qt,Ht;Object.defineProperty(Wt,Symbol.hasInstance,{value:e=>e insta
185
185
  * See the License for the specific language governing permissions and
186
186
  * limitations under the License.
187
187
  * =============================================================================
188
- */const a=e;for(const e in a){const i=a[e];n.has(i)||(n.add(i),Xt(i,t,n))}}function en(e){return null!=e.kernelName}class tn{constructor(){this.registeredVariables={},this.nextTapeNodeId=0,this.numBytes=0,this.numTensors=0,this.numStringTensors=0,this.numDataBuffers=0,this.gradientDepth=0,this.kernelDepth=0,this.scopeStack=[],this.numDataMovesStack=[],this.nextScopeId=0,this.tensorInfo=new WeakMap,this.profiling=!1,this.activeProfile={newBytes:0,newTensors:0,peakBytes:0,kernels:[],result:null,get kernelNames(){return Array.from(new Set(this.kernels.map((e=>e.name))))}}}dispose(){for(const e in this.registeredVariables)this.registeredVariables[e].dispose()}}class nn{constructor(e){this.ENV=e,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new tn}async ready(){if(null!=this.pendingBackendInit)return this.pendingBackendInit.then((()=>{}));if(null!=this.backendInstance)return;const e=this.getSortedBackends();for(let t=0;t<e.length;t++){const n=e[t];if(await this.initializeBackend(n).success)return void await this.setBackend(n)}throw new Error("Could not initialize any backends, all backend initializations failed.")}get backend(){if(null!=this.pendingBackendInit)throw new Error(`Backend '${this.backendName}' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods`);if(null==this.backendInstance){const{name:e,asyncInit:t}=this.initializeBackendsAndReturnBest();if(t)throw new Error(`The highest priority backend '${e}' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods`);this.setBackend(e)}return this.backendInstance}backendNames(){return Object.keys(this.registryFactory)}findBackend(e){if(!(e in this.registry)){if(!(e in this.registryFactory))return null;{const{asyncInit:t}=this.initializeBackend(e);if(t)return null}}return this.registry[e]}findBackendFactory(e){return e in this.registryFactory?this.registryFactory[e].factory:null}registerBackend(e,t,n=1){return e in this.registryFactory?(gt(`${e} backend was already registered. Reusing existing backend factory.`),!1):(this.registryFactory[e]={factory:t,priority:n},!0)}async setBackend(e){if(null==this.registryFactory[e])throw new Error(`Backend name '${e}' not found in registry`);if(this.backendName=e,null==this.registry[e]){this.backendInstance=null;const{success:t,asyncInit:n}=this.initializeBackend(e);if(!(n?await t:t))return!1}return this.backendInstance=this.registry[e],this.setupRegisteredKernels(),this.profiler=new jt(this.backendInstance),!0}setupRegisteredKernels(){kt(this.backendName).forEach((e=>{null!=e.setupFunc&&e.setupFunc(this.backendInstance)}))}disposeRegisteredKernels(e){kt(e).forEach((t=>{null!=t.disposeFunc&&t.disposeFunc(this.registry[e])}))}initializeBackend(e){const t=this.registryFactory[e];if(null==t)throw new Error(`Cannot initialize backend ${e}, no registration found.`);try{const n=t.factory();if(!n||n instanceof k||"function"!=typeof n.then)return this.registry[e]=n,{success:!0,asyncInit:!1};{const t=++this.pendingBackendInitId,i=n.then((n=>!(t<this.pendingBackendInitId)&&(this.registry[e]=n,this.pendingBackendInit=null,!0))).catch((n=>(t<this.pendingBackendInitId||(this.pendingBackendInit=null,gt(`Initialization of backend ${e} failed`),gt(n.stack||n.message)),!1)));return this.pendingBackendInit=i,{success:i,asyncInit:!0}}}catch(t){return gt(`Initialization of backend ${e} failed`),gt(t.stack||t.message),{success:!1,asyncInit:!1}}}removeBackend(e){if(!(e in this.registryFactory))throw new Error(`${e} backend not found in registry`);this.backendName===e&&null!=this.pendingBackendInit&&this.pendingBackendInitId++,e in this.registry&&(this.disposeRegisteredKernels(e),this.registry[e].dispose(),delete this.registry[e]),delete this.registryFactory[e],this.backendName===e&&(this.pendingBackendInit=null,this.backendName=null,this.backendInstance=null)}getSortedBackends(){if(0===Object.keys(this.registryFactory).length)throw new Error("No backend found in registry.");return Object.keys(this.registryFactory).sort(((e,t)=>this.registryFactory[t].priority-this.registryFactory[e].priority))}initializeBackendsAndReturnBest(){const e=this.getSortedBackends();for(let t=0;t<e.length;t++){const n=e[t],{success:i,asyncInit:a}=this.initializeBackend(n);if(a||i)return{name:n,asyncInit:a}}throw new Error("Could not initialize any backends, all backend initializations failed.")}moveData(e,t){const n=this.state.tensorInfo.get(t),i=n.backend,a=this.readSync(t),s=i.refCount(t);i.disposeData(t,!0),n.backend=e,e.move(t,a,n.shape,n.dtype,s),this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack[this.state.numDataMovesStack.length-1]++}tidy(e,t){let n,i=null;if(null==t){if("function"!=typeof e)throw new Error("Please provide a function to tidy()");t=e}else{if("string"!=typeof e&&!(e instanceof String))throw new Error("When calling with two arguments, the first argument to tidy() must be a string");if("function"!=typeof t)throw new Error("When calling with two arguments, the 2nd argument to tidy() must be a function");i=e}return this.scopedRun((()=>this.startScope(i)),(()=>this.endScope(n)),(()=>(n=t(),n instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),n)))}scopedRun(e,t,n){e();try{const e=n();return t(),e}catch(e){throw t(),e}}nextTensorId(){return nn.nextTensorId++}nextVariableId(){return nn.nextVariableId++}clone(e){const t=sn.runKernel(Ee,{x:e}),n={x:e};return this.addTapeNode(this.state.activeScope.name,n,[t],(e=>({x:()=>{const t={x:e},n={dtype:"float32"};return sn.runKernel(ce,t,n)}})),[],{}),t}runKernel(e,t,n){null==this.backendName&&this.backend;if(!(null!=bt(e,this.backendName)))throw new Error(`Kernel '${e}' not registered for backend '${this.backendName}'`);return this.runKernelFunc({kernelName:e,inputs:t,attrs:n})}shouldCheckForMemLeaks(){return this.ENV.getBool("IS_TEST")}checkKernelForMemLeak(e,t,n){const i=this.backend.numDataIds();let a=0;n.forEach((e=>{a+="complex64"===e.dtype?3:1}));const s=this.state.numDataMovesStack[this.state.numDataMovesStack.length-1],r=i-t-a-s;if(r>0)throw new Error(`Backend '${this.backendName}' has an internal memory leak (${r} data ids) after running '${e}'`)}runKernelFunc(e){let t,n=[];const i=this.isTapeOn(),a=this.state.numBytes,s=this.state.numTensors;let r,o;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0),null==this.backendName&&this.backend;const l=en(e)?e.kernelName:null!=this.state.activeScope?this.state.activeScope.name:"";if(en(e)){const{kernelName:t,inputs:a,attrs:s}=e;null==this.backendName&&this.backend;const l=bt(t,this.backendName);I(null!=l,(()=>`Cannot find registered kernel '${t}' for backend '${this.backendName}'`)),r=()=>{const e=this.backend.numDataIds();o=l.kernelFunc({inputs:a,attrs:s,backend:this.backend});const r=Array.isArray(o)?o:[o];this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(t,e,r);const c=r.map((e=>null!=e.rank?e:this.makeTensorFromTensorInfo(e)));if(i){const e=this.getTensorsForGradient(t,a,c);n=this.saveTensorsForBackwardMode(e)}return c}}else{const{forwardFunc:t}=e,a=e=>{i&&(n=e.map((e=>this.keep(this.clone(e)))))};r=()=>{const e=this.backend.numDataIds();o=this.tidy((()=>t(this.backend,a)));const n=Array.isArray(o)?o:[o];return this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(l,e,n),n}}const{inputs:c,attrs:u}=e,h=en(e)?null:e.backwardsFunc;let p;return this.scopedRun((()=>this.state.kernelDepth++),(()=>this.state.kernelDepth--),(()=>{this.ENV.getBool("DEBUG")||this.state.profiling?(p=this.profiler.profileKernel(l,c,(()=>r())),this.ENV.getBool("DEBUG")&&this.profiler.logKernelProfile(p),t=p.outputs):t=r()})),i&&this.addTapeNode(l,c,t,h,n,u),this.state.profiling&&this.state.activeProfile.kernels.push({name:l,bytesAdded:this.state.numBytes-a,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-s,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(c).map((e=>null!=c[e]?c[e].shape:null)),outputShapes:t.map((e=>e.shape)),kernelTimeMs:p.timeMs,extraInfo:p.extraInfo}),Array.isArray(o)?t:t[0]}saveTensorsForBackwardMode(e){const t=e.map((e=>this.keep(this.clone(e))));return t}getTensorsForGradient(e,t,n){const i=wt(e);if(null!=i){const e=i.inputsToSave||[],a=i.outputsToSave||[];let s;i.saveAllInputs?(I(Array.isArray(t),(()=>"saveAllInputs is true, expected inputs to be an array.")),s=Object.keys(t).map((e=>t[e]))):s=e.map((e=>t[e]));const r=n.filter(((e,t)=>a[t]));return s.concat(r)}return[]}makeTensor(e,t,n,i){if(null==e)throw new Error("Values passed to engine.makeTensor() are null");n=n||"float32",i=i||this.backend;let a=e;"string"===n&&R(e[0])&&(a=e.map((e=>Et(e))));const s=i.write(a,t,n),r=new Ut(t,n,s,this.nextTensorId());if(this.trackTensor(r,i),"string"===n){const e=this.state.tensorInfo.get(s),t=function(e){if(null==e)return 0;let t=0;return e.forEach((e=>t+=e.length)),t}(a);this.state.numBytes+=t-e.bytes,e.bytes=t}return r}makeTensorFromDataId(e,t,n,i){const a={dataId:e,shape:t,dtype:n=n||"float32"};return this.makeTensorFromTensorInfo(a,i)}makeTensorFromTensorInfo(e,t){const{dataId:n,shape:i,dtype:a}=e,s=new Ut(i,a,n,this.nextTensorId());return this.trackTensor(s,t),s}makeVariable(e,t=!0,n,i){n=n||this.nextVariableId().toString(),null!=i&&i!==e.dtype&&(e=e.cast(i));const a=new Wt(e,t,n,this.nextTensorId());if(null!=this.state.registeredVariables[a.name])throw new Error(`Variable with name ${a.name} was already registered`);return this.state.registeredVariables[a.name]=a,this.incRef(a,this.backend),a}trackTensor(e,t){this.state.numTensors++,"string"===e.dtype&&this.state.numStringTensors++;let n=0;"complex64"!==e.dtype&&"string"!==e.dtype&&(n=e.size*_(e.dtype)),this.state.numBytes+=n,this.state.tensorInfo.has(e.dataId)||(this.state.numDataBuffers++,this.state.tensorInfo.set(e.dataId,{backend:t||this.backend,dtype:e.dtype,shape:e.shape,bytes:n})),e instanceof Wt||this.track(e)}incRef(e,t){this.trackTensor(e,t),this.backend.incRef(e.dataId)}removeDataId(e,t){this.state.tensorInfo.has(e)&&this.state.tensorInfo.get(e).backend===t&&(this.state.tensorInfo.delete(e),this.state.numDataBuffers--)}disposeTensor(e){if(!this.state.tensorInfo.has(e.dataId))return;const t=this.state.tensorInfo.get(e.dataId);if(this.state.numTensors--,"string"===e.dtype&&(this.state.numStringTensors--,this.state.numBytes-=t.bytes),"complex64"!==e.dtype&&"string"!==e.dtype){const t=e.size*_(e.dtype);this.state.numBytes-=t}t.backend.disposeData(e.dataId)&&this.removeDataId(e.dataId,t.backend)}disposeVariables(){for(const e in this.state.registeredVariables){const t=this.state.registeredVariables[e];this.disposeVariable(t)}}disposeVariable(e){this.disposeTensor(e),null!=this.state.registeredVariables[e.name]&&delete this.state.registeredVariables[e.name]}memory(){const e=this.backend.memory();return e.numTensors=this.state.numTensors,e.numDataBuffers=this.state.numDataBuffers,e.numBytes=this.state.numBytes,this.state.numStringTensors>0&&(e.unreliable=!0,null==e.reasons&&(e.reasons=[]),e.reasons.push("Memory usage by string tensors is approximate (2 bytes per character)")),e}async profile(e){this.state.profiling=!0;const t=this.state.numBytes,n=this.state.numTensors;this.state.activeProfile.kernels=[],this.state.activeProfile.result=await e(),this.state.profiling=!1,this.state.activeProfile.peakBytes=Math.max(...this.state.activeProfile.kernels.map((e=>e.totalBytesSnapshot))),this.state.activeProfile.newBytes=this.state.numBytes-t,this.state.activeProfile.newTensors=this.state.numTensors-n;for(const e of this.state.activeProfile.kernels)e.kernelTimeMs=await e.kernelTimeMs,e.extraInfo=await e.extraInfo;return this.state.activeProfile}isTapeOn(){return this.state.gradientDepth>0&&0===this.state.kernelDepth}addTapeNode(e,t,n,i,a,s){const r={id:this.state.nextTapeNodeId++,kernelName:e,inputs:t,outputs:n,saved:a},o=wt(e);null!=o&&(i=o.gradFunc),null!=i&&(r.gradient=e=>(e=e.map(((e,t)=>{if(null==e){const e=n[t],i=G(e.size,e.dtype);return this.makeTensor(i,e.shape,e.dtype)}return e})),i(e.length>1?e:e[0],a,s))),this.state.activeTape.push(r)}keep(e){return e.kept=!0,e}startTape(){0===this.state.gradientDepth&&(this.state.activeTape=[]),this.state.gradientDepth++}endTape(){this.state.gradientDepth--}startScope(e){const t={track:[],name:"unnamed scope",id:this.state.nextScopeId++};e&&(t.name=e),this.state.scopeStack.push(t),this.state.activeScope=t}endScope(e){const t=Qt(e),n=new Set(t.map((e=>e.id)));for(let e=0;e<this.state.activeScope.track.length;e++){const t=this.state.activeScope.track[e];t.kept||n.has(t.id)||t.dispose()}const i=this.state.scopeStack.pop();this.state.activeScope=0===this.state.scopeStack.length?null:this.state.scopeStack[this.state.scopeStack.length-1],t.forEach((e=>{e.kept||e.scopeId!==i.id||this.track(e)}))}gradients(e,t,n,i=!1){if(I(t.length>0,(()=>"gradients() received an empty list of xs.")),null!=n&&"float32"!==n.dtype)throw new Error(`dy must have 'float32' dtype, but has '${n.dtype}'`);const a=this.scopedRun((()=>this.startTape()),(()=>this.endTape()),(()=>this.tidy("forward",e)));I(a instanceof Ut,(()=>"The result y returned by f() must be a tensor."));const s=function(e,t,n){const i={},a={};for(let e=0;e<t.length;e++)i[t[e].id]=!0;for(let n=0;n<e.length;n++){const s=e[n],r=s.inputs;for(const e in r){const n=r[e];let o=!1;for(let e=0;e<t.length;e++)if(i[n.id]){s.outputs.forEach((e=>i[e.id]=!0)),o=!0,a[s.id]=!0;break}if(o)break}}const s={};s[n.id]=!0;const r={};for(let t=e.length-1;t>=0;t--){const n=e[t],i=n.inputs;for(let e=0;e<n.outputs.length;e++)if(s[n.outputs[e].id]){for(const e in i)s[i[e].id]=!0,r[n.id]=!0;break}}const o=[];for(let t=0;t<e.length;t++){const n=e[t];if(a[n.id]&&r[n.id]){const e={};for(const t in n.inputs){const a=n.inputs[t];i[a.id]&&(e[t]=a)}const t=Object.assign({},n);t.inputs=e,t.outputs=n.outputs,o.push(t)}}return o}(this.state.activeTape,t,a);if(!i&&0===s.length&&t.length>0)throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that the f you passed encloses all operations that lead from x to y.");return this.tidy("backward",(()=>{const e={};e[a.id]=null==n?function(e){const t=W(A(e),"float32");return sn.makeTensor(t,e,"float32")}(a.shape):n,function(e,t,n,i){for(let a=t.length-1;a>=0;a--){const s=t[a],r=[];if(s.outputs.forEach((t=>{const n=e[t.id];null!=n?r.push(n):r.push(null)})),null==s.gradient)throw new Error(`Cannot compute gradient: gradient function not found for ${s.kernelName}.`);const o=s.gradient(r);for(const t in s.inputs){if(!(t in o))throw new Error(`Cannot backprop through input ${t}. Available gradients found: ${Object.keys(o)}.`);const a=n((()=>o[t]()));if("float32"!==a.dtype)throw new Error(`Error in gradient for op ${s.kernelName}. The gradient of input ${t} must have 'float32' dtype, but has '${a.dtype}'`);const r=s.inputs[t];if(!C(a.shape,r.shape))throw new Error(`Error in gradient for op ${s.kernelName}. The gradient of input '${t}' has shape '${a.shape}', which does not match the shape of the input '${r.shape}'`);if(null==e[r.id])e[r.id]=a;else{const t=e[r.id];e[r.id]=i(t,a),t.dispose()}}}}
188
+ */const a=e;for(const e in a){const i=a[e];n.has(i)||(n.add(i),Xt(i,t,n))}}function en(e){return null!=e.kernelName}class tn{constructor(){this.registeredVariables={},this.nextTapeNodeId=0,this.numBytes=0,this.numTensors=0,this.numStringTensors=0,this.numDataBuffers=0,this.gradientDepth=0,this.kernelDepth=0,this.scopeStack=[],this.numDataMovesStack=[],this.nextScopeId=0,this.tensorInfo=new WeakMap,this.profiling=!1,this.activeProfile={newBytes:0,newTensors:0,peakBytes:0,kernels:[],result:null,get kernelNames(){return Array.from(new Set(this.kernels.map((e=>e.name))))}}}dispose(){for(const e in this.registeredVariables)this.registeredVariables[e].dispose()}}class nn{constructor(e){this.ENV=e,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new tn}async ready(){if(null!=this.pendingBackendInit)return this.pendingBackendInit.then((()=>{}));if(null!=this.backendInstance)return;const e=this.getSortedBackends();for(let t=0;t<e.length;t++){const n=e[t];if(await this.initializeBackend(n).success)return void await this.setBackend(n)}throw new Error("Could not initialize any backends, all backend initializations failed.")}get backend(){if(null!=this.pendingBackendInit)throw new Error(`Backend '${this.backendName}' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods`);if(null==this.backendInstance){const{name:e,asyncInit:t}=this.initializeBackendsAndReturnBest();if(t)throw new Error(`The highest priority backend '${e}' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods`);this.setBackend(e)}return this.backendInstance}backendNames(){return Object.keys(this.registryFactory)}findBackend(e){if(!(e in this.registry)){if(!(e in this.registryFactory))return null;{const{asyncInit:t}=this.initializeBackend(e);if(t)return null}}return this.registry[e]}findBackendFactory(e){return e in this.registryFactory?this.registryFactory[e].factory:null}registerBackend(e,t,n=1){return e in this.registryFactory?(gt(`${e} backend was already registered. Reusing existing backend factory.`),!1):(this.registryFactory[e]={factory:t,priority:n},!0)}async setBackend(e){if(null==this.registryFactory[e])throw new Error(`Backend name '${e}' not found in registry`);if(this.backendName=e,null==this.registry[e]){this.backendInstance=null;const{success:t,asyncInit:n}=this.initializeBackend(e);if(!(n?await t:t))return!1}return this.backendInstance=this.registry[e],this.setupRegisteredKernels(),this.profiler=new jt(this.backendInstance),!0}setupRegisteredKernels(){kt(this.backendName).forEach((e=>{null!=e.setupFunc&&e.setupFunc(this.backendInstance)}))}disposeRegisteredKernels(e){kt(e).forEach((t=>{null!=t.disposeFunc&&t.disposeFunc(this.registry[e])}))}initializeBackend(e){const t=this.registryFactory[e];if(null==t)throw new Error(`Cannot initialize backend ${e}, no registration found.`);try{const n=t.factory();if(!n||n instanceof k||"function"!=typeof n.then)return this.registry[e]=n,{success:!0,asyncInit:!1};{const t=++this.pendingBackendInitId,i=n.then((n=>!(t<this.pendingBackendInitId)&&(this.registry[e]=n,this.pendingBackendInit=null,!0))).catch((n=>(t<this.pendingBackendInitId||(this.pendingBackendInit=null,gt(`Initialization of backend ${e} failed`),gt(n.stack||n.message)),!1)));return this.pendingBackendInit=i,{success:i,asyncInit:!0}}}catch(t){return gt(`Initialization of backend ${e} failed`),gt(t.stack||t.message),{success:!1,asyncInit:!1}}}removeBackend(e){if(!(e in this.registryFactory))throw new Error(`${e} backend not found in registry`);this.backendName===e&&null!=this.pendingBackendInit&&this.pendingBackendInitId++,e in this.registry&&(this.disposeRegisteredKernels(e),this.registry[e].dispose(),delete this.registry[e]),delete this.registryFactory[e],this.backendName===e&&(this.pendingBackendInit=null,this.backendName=null,this.backendInstance=null)}getSortedBackends(){if(0===Object.keys(this.registryFactory).length)throw new Error("No backend found in registry.");return Object.keys(this.registryFactory).sort(((e,t)=>this.registryFactory[t].priority-this.registryFactory[e].priority))}initializeBackendsAndReturnBest(){const e=this.getSortedBackends();for(let t=0;t<e.length;t++){const n=e[t],{success:i,asyncInit:a}=this.initializeBackend(n);if(a||i)return{name:n,asyncInit:a}}throw new Error("Could not initialize any backends, all backend initializations failed.")}moveData(e,t){const n=this.state.tensorInfo.get(t),i=n.backend,a=this.readSync(t),s=i.refCount(t);i.disposeData(t,!0),n.backend=e,e.move(t,a,n.shape,n.dtype,s),this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack[this.state.numDataMovesStack.length-1]++}tidy(e,t){let n,i=null;if(null==t){if("function"!=typeof e)throw new Error("Please provide a function to tidy()");t=e}else{if("string"!=typeof e&&!(e instanceof String))throw new Error("When calling with two arguments, the first argument to tidy() must be a string");if("function"!=typeof t)throw new Error("When calling with two arguments, the 2nd argument to tidy() must be a function");i=e}return this.scopedRun((()=>this.startScope(i)),(()=>this.endScope(n)),(()=>(n=t(),n instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),n)))}scopedRun(e,t,n){e();try{const e=n();return t(),e}catch(e){throw t(),e}}nextTensorId(){return nn.nextTensorId++}nextVariableId(){return nn.nextVariableId++}clone(e){const t=sn.runKernel(Ae,{x:e}),n={x:e};return this.addTapeNode(this.state.activeScope.name,n,[t],(e=>({x:()=>{const t={x:e},n={dtype:"float32"};return sn.runKernel(ce,t,n)}})),[],{}),t}runKernel(e,t,n){null==this.backendName&&this.backend;if(!(null!=bt(e,this.backendName)))throw new Error(`Kernel '${e}' not registered for backend '${this.backendName}'`);return this.runKernelFunc({kernelName:e,inputs:t,attrs:n})}shouldCheckForMemLeaks(){return this.ENV.getBool("IS_TEST")}checkKernelForMemLeak(e,t,n){const i=this.backend.numDataIds();let a=0;n.forEach((e=>{a+="complex64"===e.dtype?3:1}));const s=this.state.numDataMovesStack[this.state.numDataMovesStack.length-1],r=i-t-a-s;if(r>0)throw new Error(`Backend '${this.backendName}' has an internal memory leak (${r} data ids) after running '${e}'`)}runKernelFunc(e){let t,n=[];const i=this.isTapeOn(),a=this.state.numBytes,s=this.state.numTensors;let r,o;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0),null==this.backendName&&this.backend;const l=en(e)?e.kernelName:null!=this.state.activeScope?this.state.activeScope.name:"";if(en(e)){const{kernelName:t,inputs:a,attrs:s}=e;null==this.backendName&&this.backend;const l=bt(t,this.backendName);T(null!=l,(()=>`Cannot find registered kernel '${t}' for backend '${this.backendName}'`)),r=()=>{const e=this.backend.numDataIds();o=l.kernelFunc({inputs:a,attrs:s,backend:this.backend});const r=Array.isArray(o)?o:[o];this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(t,e,r);const c=r.map((e=>null!=e.rank?e:this.makeTensorFromTensorInfo(e)));if(i){const e=this.getTensorsForGradient(t,a,c);n=this.saveTensorsForBackwardMode(e)}return c}}else{const{forwardFunc:t}=e,a=e=>{i&&(n=e.map((e=>this.keep(this.clone(e)))))};r=()=>{const e=this.backend.numDataIds();o=this.tidy((()=>t(this.backend,a)));const n=Array.isArray(o)?o:[o];return this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(l,e,n),n}}const{inputs:c,attrs:u}=e,h=en(e)?null:e.backwardsFunc;let p;return this.scopedRun((()=>this.state.kernelDepth++),(()=>this.state.kernelDepth--),(()=>{this.ENV.getBool("DEBUG")||this.state.profiling?(p=this.profiler.profileKernel(l,c,(()=>r())),this.ENV.getBool("DEBUG")&&this.profiler.logKernelProfile(p),t=p.outputs):t=r()})),i&&this.addTapeNode(l,c,t,h,n,u),this.state.profiling&&this.state.activeProfile.kernels.push({name:l,bytesAdded:this.state.numBytes-a,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-s,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(c).map((e=>null!=c[e]?c[e].shape:null)),outputShapes:t.map((e=>e.shape)),kernelTimeMs:p.timeMs,extraInfo:p.extraInfo}),Array.isArray(o)?t:t[0]}saveTensorsForBackwardMode(e){const t=e.map((e=>this.keep(this.clone(e))));return t}getTensorsForGradient(e,t,n){const i=wt(e);if(null!=i){const e=i.inputsToSave||[],a=i.outputsToSave||[];let s;i.saveAllInputs?(T(Array.isArray(t),(()=>"saveAllInputs is true, expected inputs to be an array.")),s=Object.keys(t).map((e=>t[e]))):s=e.map((e=>t[e]));const r=n.filter(((e,t)=>a[t]));return s.concat(r)}return[]}makeTensor(e,t,n,i){if(null==e)throw new Error("Values passed to engine.makeTensor() are null");n=n||"float32",i=i||this.backend;let a=e;"string"===n&&R(e[0])&&(a=e.map((e=>At(e))));const s=i.write(a,t,n),r=new Ut(t,n,s,this.nextTensorId());if(this.trackTensor(r,i),"string"===n){const e=this.state.tensorInfo.get(s),t=function(e){if(null==e)return 0;let t=0;return e.forEach((e=>t+=e.length)),t}(a);this.state.numBytes+=t-e.bytes,e.bytes=t}return r}makeTensorFromDataId(e,t,n,i){const a={dataId:e,shape:t,dtype:n=n||"float32"};return this.makeTensorFromTensorInfo(a,i)}makeTensorFromTensorInfo(e,t){const{dataId:n,shape:i,dtype:a}=e,s=new Ut(i,a,n,this.nextTensorId());return this.trackTensor(s,t),s}makeVariable(e,t=!0,n,i){n=n||this.nextVariableId().toString(),null!=i&&i!==e.dtype&&(e=e.cast(i));const a=new Wt(e,t,n,this.nextTensorId());if(null!=this.state.registeredVariables[a.name])throw new Error(`Variable with name ${a.name} was already registered`);return this.state.registeredVariables[a.name]=a,this.incRef(a,this.backend),a}trackTensor(e,t){this.state.numTensors++,"string"===e.dtype&&this.state.numStringTensors++;let n=0;"complex64"!==e.dtype&&"string"!==e.dtype&&(n=e.size*_(e.dtype)),this.state.numBytes+=n,this.state.tensorInfo.has(e.dataId)||(this.state.numDataBuffers++,this.state.tensorInfo.set(e.dataId,{backend:t||this.backend,dtype:e.dtype,shape:e.shape,bytes:n})),e instanceof Wt||this.track(e)}incRef(e,t){this.trackTensor(e,t),this.backend.incRef(e.dataId)}removeDataId(e,t){this.state.tensorInfo.has(e)&&this.state.tensorInfo.get(e).backend===t&&(this.state.tensorInfo.delete(e),this.state.numDataBuffers--)}disposeTensor(e){if(!this.state.tensorInfo.has(e.dataId))return;const t=this.state.tensorInfo.get(e.dataId);if(this.state.numTensors--,"string"===e.dtype&&(this.state.numStringTensors--,this.state.numBytes-=t.bytes),"complex64"!==e.dtype&&"string"!==e.dtype){const t=e.size*_(e.dtype);this.state.numBytes-=t}t.backend.disposeData(e.dataId)&&this.removeDataId(e.dataId,t.backend)}disposeVariables(){for(const e in this.state.registeredVariables){const t=this.state.registeredVariables[e];this.disposeVariable(t)}}disposeVariable(e){this.disposeTensor(e),null!=this.state.registeredVariables[e.name]&&delete this.state.registeredVariables[e.name]}memory(){const e=this.backend.memory();return e.numTensors=this.state.numTensors,e.numDataBuffers=this.state.numDataBuffers,e.numBytes=this.state.numBytes,this.state.numStringTensors>0&&(e.unreliable=!0,null==e.reasons&&(e.reasons=[]),e.reasons.push("Memory usage by string tensors is approximate (2 bytes per character)")),e}async profile(e){this.state.profiling=!0;const t=this.state.numBytes,n=this.state.numTensors;this.state.activeProfile.kernels=[],this.state.activeProfile.result=await e(),this.state.profiling=!1,this.state.activeProfile.peakBytes=Math.max(...this.state.activeProfile.kernels.map((e=>e.totalBytesSnapshot))),this.state.activeProfile.newBytes=this.state.numBytes-t,this.state.activeProfile.newTensors=this.state.numTensors-n;for(const e of this.state.activeProfile.kernels)e.kernelTimeMs=await e.kernelTimeMs,e.extraInfo=await e.extraInfo;return this.state.activeProfile}isTapeOn(){return this.state.gradientDepth>0&&0===this.state.kernelDepth}addTapeNode(e,t,n,i,a,s){const r={id:this.state.nextTapeNodeId++,kernelName:e,inputs:t,outputs:n,saved:a},o=wt(e);null!=o&&(i=o.gradFunc),null!=i&&(r.gradient=e=>(e=e.map(((e,t)=>{if(null==e){const e=n[t],i=V(e.size,e.dtype);return this.makeTensor(i,e.shape,e.dtype)}return e})),i(e.length>1?e:e[0],a,s))),this.state.activeTape.push(r)}keep(e){return e.kept=!0,e}startTape(){0===this.state.gradientDepth&&(this.state.activeTape=[]),this.state.gradientDepth++}endTape(){this.state.gradientDepth--}startScope(e){const t={track:[],name:"unnamed scope",id:this.state.nextScopeId++};e&&(t.name=e),this.state.scopeStack.push(t),this.state.activeScope=t}endScope(e){const t=Qt(e),n=new Set(t.map((e=>e.id)));for(let e=0;e<this.state.activeScope.track.length;e++){const t=this.state.activeScope.track[e];t.kept||n.has(t.id)||t.dispose()}const i=this.state.scopeStack.pop();this.state.activeScope=0===this.state.scopeStack.length?null:this.state.scopeStack[this.state.scopeStack.length-1],t.forEach((e=>{e.kept||e.scopeId!==i.id||this.track(e)}))}gradients(e,t,n,i=!1){if(T(t.length>0,(()=>"gradients() received an empty list of xs.")),null!=n&&"float32"!==n.dtype)throw new Error(`dy must have 'float32' dtype, but has '${n.dtype}'`);const a=this.scopedRun((()=>this.startTape()),(()=>this.endTape()),(()=>this.tidy("forward",e)));T(a instanceof Ut,(()=>"The result y returned by f() must be a tensor."));const s=function(e,t,n){const i={},a={};for(let e=0;e<t.length;e++)i[t[e].id]=!0;for(let n=0;n<e.length;n++){const s=e[n],r=s.inputs;for(const e in r){const n=r[e];let o=!1;for(let e=0;e<t.length;e++)if(i[n.id]){s.outputs.forEach((e=>i[e.id]=!0)),o=!0,a[s.id]=!0;break}if(o)break}}const s={};s[n.id]=!0;const r={};for(let t=e.length-1;t>=0;t--){const n=e[t],i=n.inputs;for(let e=0;e<n.outputs.length;e++)if(s[n.outputs[e].id]){for(const e in i)s[i[e].id]=!0,r[n.id]=!0;break}}const o=[];for(let t=0;t<e.length;t++){const n=e[t];if(a[n.id]&&r[n.id]){const e={};for(const t in n.inputs){const a=n.inputs[t];i[a.id]&&(e[t]=a)}const t=Object.assign({},n);t.inputs=e,t.outputs=n.outputs,o.push(t)}}return o}(this.state.activeTape,t,a);if(!i&&0===s.length&&t.length>0)throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that the f you passed encloses all operations that lead from x to y.");return this.tidy("backward",(()=>{const e={};e[a.id]=null==n?function(e){const t=W(C(e),"float32");return sn.makeTensor(t,e,"float32")}(a.shape):n,function(e,t,n,i){for(let a=t.length-1;a>=0;a--){const s=t[a],r=[];if(s.outputs.forEach((t=>{const n=e[t.id];null!=n?r.push(n):r.push(null)})),null==s.gradient)throw new Error(`Cannot compute gradient: gradient function not found for ${s.kernelName}.`);const o=s.gradient(r);for(const t in s.inputs){if(!(t in o))throw new Error(`Cannot backprop through input ${t}. Available gradients found: ${Object.keys(o)}.`);const a=n((()=>o[t]()));if("float32"!==a.dtype)throw new Error(`Error in gradient for op ${s.kernelName}. The gradient of input ${t} must have 'float32' dtype, but has '${a.dtype}'`);const r=s.inputs[t];if(!E(a.shape,r.shape))throw new Error(`Error in gradient for op ${s.kernelName}. The gradient of input '${t}' has shape '${a.shape}', which does not match the shape of the input '${r.shape}'`);if(null==e[r.id])e[r.id]=a;else{const t=e[r.id];e[r.id]=i(t,a),t.dispose()}}}}
189
189
  /**
190
190
  * @license
191
191
  * Copyright 2018 Google LLC. All Rights Reserved.
@@ -201,7 +201,7 @@ var Gt,Vt,Kt,qt,Ht;Object.defineProperty(Wt,Symbol.hasInstance,{value:e=>e insta
201
201
  * See the License for the specific language governing permissions and
202
202
  * limitations under the License.
203
203
  * =============================================================================
204
- */(e,s,(e=>this.tidy(e)),rn);const i=t.map((t=>e[t.id]));return 0===this.state.gradientDepth&&(this.state.activeTape.forEach((e=>{for(const t of e.saved)t.dispose()})),this.state.activeTape=null),{value:a,grads:i}}))}customGrad(e){return I(O(e),(()=>"The f passed in customGrad(f) must be a function.")),(...t)=>{let n;I(t.every((e=>e instanceof Ut)),(()=>"The args passed in customGrad(f)(x1, x2,...) must all be tensors"));const i={};t.forEach(((e,t)=>{i[t]=e}));return this.runKernelFunc({forwardFunc:(i,a)=>(n=e(...t,a),I(n.value instanceof Ut,(()=>"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor")),I(O(n.gradFunc),(()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function.")),n.value),backwardsFunc:(e,i)=>{const a=n.gradFunc(e,i),s=Array.isArray(a)?a:[a];I(s.length===t.length,(()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns the same number of tensors as inputs passed to f(...).")),I(s.every((e=>e instanceof Ut)),(()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns a list of only tensors."));const r={};return s.forEach(((e,t)=>{r[t]=()=>e})),r},inputs:i})}}readSync(e){return this.state.tensorInfo.get(e).backend.readSync(e)}read(e){return this.state.tensorInfo.get(e).backend.read(e)}readToGPU(e,t){return this.state.tensorInfo.get(e).backend.readToGPU(e,t)}async time(e){const t=Tt(),n=await this.backend.time(e);return n.wallMs=Tt()-t,n}track(e){return null!=this.state.activeScope&&(e.scopeId=this.state.activeScope.id,this.state.activeScope.track.push(e)),e}get registeredVariables(){return this.state.registeredVariables}reset(){this.pendingBackendInitId++,this.state.dispose(),this.ENV.reset(),this.state=new tn;for(const e in this.registry)this.disposeRegisteredKernels(e),this.registry[e].dispose(),delete this.registry[e];this.backendName=null,this.backendInstance=null,this.pendingBackendInit=null}}function an(){const e=te();if(null==e._tfengine){const t=new Z(e);e._tfengine=new nn(t)}var t;
204
+ */(e,s,(e=>this.tidy(e)),rn);const i=t.map((t=>e[t.id]));return 0===this.state.gradientDepth&&(this.state.activeTape.forEach((e=>{for(const t of e.saved)t.dispose()})),this.state.activeTape=null),{value:a,grads:i}}))}customGrad(e){return T(O(e),(()=>"The f passed in customGrad(f) must be a function.")),(...t)=>{let n;T(t.every((e=>e instanceof Ut)),(()=>"The args passed in customGrad(f)(x1, x2,...) must all be tensors"));const i={};t.forEach(((e,t)=>{i[t]=e}));return this.runKernelFunc({forwardFunc:(i,a)=>(n=e(...t,a),T(n.value instanceof Ut,(()=>"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor")),T(O(n.gradFunc),(()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function.")),n.value),backwardsFunc:(e,i)=>{const a=n.gradFunc(e,i),s=Array.isArray(a)?a:[a];T(s.length===t.length,(()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns the same number of tensors as inputs passed to f(...).")),T(s.every((e=>e instanceof Ut)),(()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns a list of only tensors."));const r={};return s.forEach(((e,t)=>{r[t]=()=>e})),r},inputs:i})}}readSync(e){return this.state.tensorInfo.get(e).backend.readSync(e)}read(e){return this.state.tensorInfo.get(e).backend.read(e)}readToGPU(e,t){return this.state.tensorInfo.get(e).backend.readToGPU(e,t)}async time(e){const t=It(),n=await this.backend.time(e);return n.wallMs=It()-t,n}track(e){return null!=this.state.activeScope&&(e.scopeId=this.state.activeScope.id,this.state.activeScope.track.push(e)),e}get registeredVariables(){return this.state.registeredVariables}reset(){this.pendingBackendInitId++,this.state.dispose(),this.ENV.reset(),this.state=new tn;for(const e in this.registry)this.disposeRegisteredKernels(e),this.registry[e].dispose(),delete this.registry[e];this.backendName=null,this.backendInstance=null,this.pendingBackendInit=null}}function an(){const e=te();if(null==e._tfengine){const t=new Z(e);e._tfengine=new nn(t)}var t;
205
205
  /**
206
206
  * @license
207
207
  * Copyright 2020 Google LLC. All Rights Reserved.
@@ -267,7 +267,7 @@ const on=Q();
267
267
  * limitations under the License.
268
268
  * =============================================================================
269
269
  */
270
- function ln(e,t){let n=e;if(Ct(e))return"string"===t?[]:[e.length];if("object"==typeof e){if("texture"in e){const t=e.channels||"RGBA";return[e.height,e.width*t.length]}if("buffer"in e&&!(e.buffer instanceof ArrayBuffer))return[e.buffer.size/(null==t?4:_(t))]}if(!Array.isArray(e))return[];const i=[];for(;Array.isArray(n)||Ct(n)&&"string"!==t;)i.push(n.length),n=n[0];return Array.isArray(e)&&Q().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&cn(e,i,[]),i}function cn(e,t,n){if(n=n||[],!Array.isArray(e)&&!Ct(e))return void I(0===t.length,(()=>`Element arr[${n.join("][")}] is a primitive, but should be an array/TypedArray of ${t[0]} elements`));I(t.length>0,(()=>`Element arr[${n.join("][")}] should be a primitive, but is an array of ${e.length} elements`)),I(e.length===t[0],(()=>`Element arr[${n.join("][")}] should have ${t[0]} elements, but has ${e.length} elements`));const i=t.slice(1);for(let t=0;t<e.length;++t)cn(e[t],i,n.concat(t))}function un(e,t,n,i){if("string_or_numeric"!==e){if(null==e)throw new Error("Expected dtype cannot be null.");if("numeric"!==e&&e!==t||"numeric"===e&&"string"===t)throw new Error(`Argument '${n}' passed to '${i}' must be ${e} tensor, but got ${t} tensor`)}}function hn(e,t,n,i="numeric"){if(e instanceof Ut)return un(i,e.dtype,t,n),e;let a=M(e);if("string"!==a&&["bool","int32","float32"].indexOf(i)>=0&&(a=i),un(i,a,t,n),null==e||!Ct(e)&&!Array.isArray(e)&&"number"!=typeof e&&"boolean"!=typeof e&&"string"!=typeof e){const i=null==e?"null":e.constructor.name;throw new Error(`Argument '${t}' passed to '${n}' must be a Tensor or TensorLike, but got '${i}'`)}const s=ln(e,a);Ct(e)||Array.isArray(e)||(e=[e]);const r="string"!==a?It(e,a):$t(e,[],!0);return sn.makeTensor(r,s,a)}function pn(e,t,n,i="numeric"){if(!Array.isArray(e))throw new Error(`Argument ${t} passed to ${n} must be a \`Tensor[]\` or \`TensorLike[]\``);return e.map(((e,a)=>hn(e,`${t}[${a}]`,n,i)))}
270
+ function ln(e,t){let n=e;if(Et(e))return"string"===t?[]:[e.length];if("object"==typeof e){if("texture"in e){const t=e.channels||"RGBA";return[e.height,e.width*t.length]}if("buffer"in e&&!(e.buffer instanceof ArrayBuffer))return[e.buffer.size/(null==t?4:_(t))]}if(!Array.isArray(e))return[];const i=[];for(;Array.isArray(n)||Et(n)&&"string"!==t;)i.push(n.length),n=n[0];return Array.isArray(e)&&Q().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&cn(e,i,[]),i}function cn(e,t,n){if(n=n||[],!Array.isArray(e)&&!Et(e))return void T(0===t.length,(()=>`Element arr[${n.join("][")}] is a primitive, but should be an array/TypedArray of ${t[0]} elements`));T(t.length>0,(()=>`Element arr[${n.join("][")}] should be a primitive, but is an array of ${e.length} elements`)),T(e.length===t[0],(()=>`Element arr[${n.join("][")}] should have ${t[0]} elements, but has ${e.length} elements`));const i=t.slice(1);for(let t=0;t<e.length;++t)cn(e[t],i,n.concat(t))}function un(e,t,n,i){if("string_or_numeric"!==e){if(null==e)throw new Error("Expected dtype cannot be null.");if("numeric"!==e&&e!==t||"numeric"===e&&"string"===t)throw new Error(`Argument '${n}' passed to '${i}' must be ${e} tensor, but got ${t} tensor`)}}function hn(e,t,n,i="numeric"){if(e instanceof Ut)return un(i,e.dtype,t,n),e;let a=M(e);if("string"!==a&&["bool","int32","float32"].indexOf(i)>=0&&(a=i),un(i,a,t,n),null==e||!Et(e)&&!Array.isArray(e)&&"number"!=typeof e&&"boolean"!=typeof e&&"string"!=typeof e){const i=null==e?"null":e.constructor.name;throw new Error(`Argument '${t}' passed to '${n}' must be a Tensor or TensorLike, but got '${i}'`)}const s=ln(e,a);Et(e)||Array.isArray(e)||(e=[e]);const r="string"!==a?Tt(e,a):$t(e,[],!0);return sn.makeTensor(r,s,a)}function pn(e,t,n,i="numeric"){if(!Array.isArray(e))throw new Error(`Argument ${t} passed to ${n} must be a \`Tensor[]\` or \`TensorLike[]\``);return e.map(((e,a)=>hn(e,`${t}[${a}]`,n,i)))}
271
271
  /**
272
272
  * @license
273
273
  * Copyright 2018 Google LLC. All Rights Reserved.
@@ -299,7 +299,7 @@ function ln(e,t){let n=e;if(Ct(e))return"string"===t?[]:[e.length];if("object"==
299
299
  * See the License for the specific language governing permissions and
300
300
  * limitations under the License.
301
301
  * =============================================================================
302
- */const mn=dn({complex_:function(e,t){const n=hn(e,"real","complex"),i=hn(t,"imag","complex");T(n.shape,i.shape,`real and imag shapes, ${n.shape} and ${i.shape}, must match in call to tf.complex().`);const a={real:n,imag:i};return sn.runKernel("Complex",a)}});
302
+ */const mn=dn({complex_:function(e,t){const n=hn(e,"real","complex"),i=hn(t,"imag","complex");I(n.shape,i.shape,`real and imag shapes, ${n.shape} and ${i.shape}, must match in call to tf.complex().`);const a={real:n,imag:i};return sn.runKernel("Complex",a)}});
303
303
  /**
304
304
  * @license
305
305
  * Copyright 2018 Google LLC. All Rights Reserved.
@@ -315,7 +315,7 @@ function ln(e,t){let n=e;if(Ct(e))return"string"===t?[]:[e.length];if("object"==
315
315
  * See the License for the specific language governing permissions and
316
316
  * limitations under the License.
317
317
  * =============================================================================
318
- */function fn(e,t,n,i){if(null==i)i=M(e);else if("complex64"===i)throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if("object"==typeof e&&("texture"in e||"buffer"in e&&!(e.buffer instanceof ArrayBuffer))){if("float32"!==i&&"int32"!==i)throw new Error(`Creating tensor from GPU data only supports 'float32'|'int32' dtype, while the dtype is ${i}.`);return sn.backend.createTensorFromGPUData(e,t||n,i)}if(!Ct(e)&&!Array.isArray(e)&&"number"!=typeof e&&"boolean"!=typeof e&&"string"!=typeof e)throw new Error("values passed to tensor(values) must be a number/boolean/string or an array of numbers/booleans/strings, or a TypedArray");if(null!=t){V(t);const e=A(t),i=A(n);I(e===i,(()=>`Based on the provided shape, [${t}], the tensor should have ${e} values but has ${i}`));for(let e=0;e<n.length;++e){const i=n[e],a=e!==n.length-1||i!==A(t.slice(e));I(n[e]===t[e]||!a,(()=>`Error creating a new Tensor. Inferred shape (${n}) does not match the provided shape (${t}). `))}}return Ct(e)||Array.isArray(e)||(e=[e]),t=t||n,e="string"!==i?It(e,i):$t(e,[],!0),sn.makeTensor(e,t,i)}
318
+ */function fn(e,t,n,i){if(null==i)i=M(e);else if("complex64"===i)throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if("object"==typeof e&&("texture"in e||"buffer"in e&&!(e.buffer instanceof ArrayBuffer))){if("float32"!==i&&"int32"!==i)throw new Error(`Creating tensor from GPU data only supports 'float32'|'int32' dtype, while the dtype is ${i}.`);return sn.backend.createTensorFromGPUData(e,t||n,i)}if(!Et(e)&&!Array.isArray(e)&&"number"!=typeof e&&"boolean"!=typeof e&&"string"!=typeof e)throw new Error("values passed to tensor(values) must be a number/boolean/string or an array of numbers/booleans/strings, or a TypedArray");if(null!=t){G(t);const e=C(t),i=C(n);T(e===i,(()=>`Based on the provided shape, [${t}], the tensor should have ${e} values but has ${i}`));for(let e=0;e<n.length;++e){const i=n[e],a=e!==n.length-1||i!==C(t.slice(e));T(n[e]===t[e]||!a,(()=>`Error creating a new Tensor. Inferred shape (${n}) does not match the provided shape (${t}). `))}}return Et(e)||Array.isArray(e)||(e=[e]),t=t||n,e="string"!==i?Tt(e,i):$t(e,[],!0),sn.makeTensor(e,t,i)}
319
319
  /**
320
320
  * @license
321
321
  * Copyright 2018 Google LLC. All Rights Reserved.
@@ -363,7 +363,7 @@ function ln(e,t){let n=e;if(Ct(e))return"string"===t?[]:[e.length];if("object"==
363
363
  * See the License for the specific language governing permissions and
364
364
  * limitations under the License.
365
365
  * =============================================================================
366
- */async function yn(e,t){const n=[],i=[],a=Array.isArray(e)?e.map((e=>e.name)):Object.keys(e);for(let s=0;s<a.length;++s){const r=a[s],o=Array.isArray(e)?e[s].tensor:e[r];if("float32"!==o.dtype&&"int32"!==o.dtype&&"bool"!==o.dtype&&"string"!==o.dtype&&"complex64"!==o.dtype)throw new Error(`Unsupported dtype in weight '${r}': ${o.dtype}`);const l={name:r,shape:o.shape,dtype:o.dtype};if("string"===o.dtype){const e=new Promise((async e=>{const t=await o.bytes(),n=t.reduce(((e,t)=>e+t.length),0)+4*t.length,i=new Uint8Array(n);let a=0;for(let e=0;e<t.length;e++){const n=t[e],s=new Uint8Array(new Uint32Array([n.length]).buffer);i.set(s,a),a+=4,i.set(n,a),a+=n.length}e(i)}));i.push(e)}else i.push(o.data());null!=t&&(l.group=t),n.push(l)}return{data:bn(await Promise.all(i)),specs:n}}function bn(e){if(null===e)throw new Error(`Invalid input value: ${JSON.stringify(e)}`);let t=0;const n=[];e.forEach((e=>{if(t+=e.byteLength,n.push(e.byteLength===e.buffer.byteLength?e:new e.constructor(e)),!(e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint8Array))throw new Error(`Unsupported TypedArray subtype: ${e.constructor.name}`)}));const i=new Uint8Array(t);let a=0;return n.forEach((e=>{i.set(new Uint8Array(e.buffer),a),a+=e.byteLength})),i.buffer}const wn="undefined"!=typeof Buffer&&("undefined"==typeof Blob||"undefined"==typeof atob||"undefined"==typeof btoa);function kn(e){return wn?Buffer.byteLength(e):new Blob([e]).size}function xn(e){if(1===e.length)return e[0];let t=0;e.forEach((e=>{t+=e.byteLength}));const n=new Uint8Array(t);let i=0;return e.forEach((e=>{n.set(new Uint8Array(e),i),i+=e.byteLength})),n.buffer}async function Sn(e,t){let n,i;return null!=e.weightsManifest&&([n,i]=await t(e.weightsManifest)),function(e,t,n){const i={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy};if(null!=e.trainingConfig&&(i.trainingConfig=e.trainingConfig),null!=e.weightsManifest){if(!t)throw new Error("modelJSON has weightsManifest but weightSpecs is null");if(!n)throw new Error("modelJSON has weightsManifest but weightData is null");i.weightSpecs=t,i.weightData=n}return null!=e.signature&&(i.signature=e.signature),null!=e.userDefinedMetadata&&(i.userDefinedMetadata=e.userDefinedMetadata),null!=e.modelInitializer&&(i.modelInitializer=e.modelInitializer),null!=e.initializerSignature&&(i.initializerSignature=e.initializerSignature),i}(e,n,i)}function Nn(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("Expected JSON model topology, received ArrayBuffer.");return{dateSaved:new Date,modelTopologyType:"JSON",modelTopologyBytes:null==e.modelTopology?0:kn(JSON.stringify(e.modelTopology)),weightSpecsBytes:null==e.weightSpecs?0:kn(JSON.stringify(e.weightSpecs)),weightDataBytes:null==e.weightData?0:e.weightData.byteLength}}function In(){const e=function(){const e=e=>{let t=e<<13,n=0;for(;0==(8388608&t);)n-=8388608,t<<=1;return t&=-8388609,n+=947912704,t|n},t=new Uint32Array(2048);t[0]=0;for(let n=1;n<1024;n++)t[n]=e(n);for(let e=1024;e<2048;e++)t[e]=939524096+(e-1024<<13);return t}(),t=function(){const e=new Uint32Array(64);e[0]=0,e[31]=1199570944,e[32]=2147483648,e[63]=3347054592;for(let t=1;t<31;t++)e[t]=t<<23;for(let t=33;t<63;t++)e[t]=2147483648+(t-32<<23);return e}(),n=function(){const e=new Uint32Array(64);for(let t=0;t<64;t++)e[t]=1024;return e[0]=e[32]=0,e}();return i=>{const a=new ArrayBuffer(4*i.length),s=new Uint32Array(a);for(let a=0;a<i.length;a++){const r=i[a],o=e[n[r>>10]+(1023&r)]+t[r>>10];s[a]=o}return new Float32Array(a)}}
366
+ */async function yn(e,t){const n=[],i=[],a=Array.isArray(e)?e.map((e=>e.name)):Object.keys(e);for(let s=0;s<a.length;++s){const r=a[s],o=Array.isArray(e)?e[s].tensor:e[r];if("float32"!==o.dtype&&"int32"!==o.dtype&&"bool"!==o.dtype&&"string"!==o.dtype&&"complex64"!==o.dtype)throw new Error(`Unsupported dtype in weight '${r}': ${o.dtype}`);const l={name:r,shape:o.shape,dtype:o.dtype};if("string"===o.dtype){const e=new Promise((async e=>{const t=await o.bytes(),n=t.reduce(((e,t)=>e+t.length),0)+4*t.length,i=new Uint8Array(n);let a=0;for(let e=0;e<t.length;e++){const n=t[e],s=new Uint8Array(new Uint32Array([n.length]).buffer);i.set(s,a),a+=4,i.set(n,a),a+=n.length}e(i)}));i.push(e)}else i.push(o.data());null!=t&&(l.group=t),n.push(l)}return{data:bn(await Promise.all(i)),specs:n}}function bn(e){if(null===e)throw new Error(`Invalid input value: ${JSON.stringify(e)}`);let t=0;const n=[];e.forEach((e=>{if(t+=e.byteLength,n.push(e.byteLength===e.buffer.byteLength?e:new e.constructor(e)),!(e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint8Array))throw new Error(`Unsupported TypedArray subtype: ${e.constructor.name}`)}));const i=new Uint8Array(t);let a=0;return n.forEach((e=>{i.set(new Uint8Array(e.buffer),a),a+=e.byteLength})),i.buffer}const wn="undefined"!=typeof Buffer&&("undefined"==typeof Blob||"undefined"==typeof atob||"undefined"==typeof btoa);function kn(e){return wn?Buffer.byteLength(e):new Blob([e]).size}function xn(e){if(1===e.length)return e[0];let t=0;e.forEach((e=>{t+=e.byteLength}));const n=new Uint8Array(t);let i=0;return e.forEach((e=>{n.set(new Uint8Array(e),i),i+=e.byteLength})),n.buffer}async function Sn(e,t){let n,i;return null!=e.weightsManifest&&([n,i]=await t(e.weightsManifest)),function(e,t,n){const i={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy};if(null!=e.trainingConfig&&(i.trainingConfig=e.trainingConfig),null!=e.weightsManifest){if(!t)throw new Error("modelJSON has weightsManifest but weightSpecs is null");if(!n)throw new Error("modelJSON has weightsManifest but weightData is null");i.weightSpecs=t,i.weightData=n}return null!=e.signature&&(i.signature=e.signature),null!=e.userDefinedMetadata&&(i.userDefinedMetadata=e.userDefinedMetadata),null!=e.modelInitializer&&(i.modelInitializer=e.modelInitializer),null!=e.initializerSignature&&(i.initializerSignature=e.initializerSignature),i}(e,n,i)}function Nn(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("Expected JSON model topology, received ArrayBuffer.");return{dateSaved:new Date,modelTopologyType:"JSON",modelTopologyBytes:null==e.modelTopology?0:kn(JSON.stringify(e.modelTopology)),weightSpecsBytes:null==e.weightSpecs?0:kn(JSON.stringify(e.weightSpecs)),weightDataBytes:null==e.weightData?0:e.weightData.byteLength}}function Tn(){const e=function(){const e=e=>{let t=e<<13,n=0;for(;0==(8388608&t);)n-=8388608,t<<=1;return t&=-8388609,n+=947912704,t|n},t=new Uint32Array(2048);t[0]=0;for(let n=1;n<1024;n++)t[n]=e(n);for(let e=1024;e<2048;e++)t[e]=939524096+(e-1024<<13);return t}(),t=function(){const e=new Uint32Array(64);e[0]=0,e[31]=1199570944,e[32]=2147483648,e[63]=3347054592;for(let t=1;t<31;t++)e[t]=t<<23;for(let t=33;t<63;t++)e[t]=2147483648+(t-32<<23);return e}(),n=function(){const e=new Uint32Array(64);for(let t=0;t<64;t++)e[t]=1024;return e[0]=e[32]=0,e}();return i=>{const a=new ArrayBuffer(4*i.length),s=new Uint32Array(a);for(let a=0;a<i.length;a++){const r=i[a],o=e[n[r>>10]+(1023&r)]+t[r>>10];s[a]=o}return new Float32Array(a)}}
367
367
  /**
368
368
  * @license
369
369
  * Copyright 2018 Google LLC. All Rights Reserved.
@@ -379,7 +379,7 @@ function ln(e,t){let n=e;if(Ct(e))return"string"===t?[]:[e.length];if("object"==
379
379
  * See the License for the specific language governing permissions and
380
380
  * limitations under the License.
381
381
  * =============================================================================
382
- */class Tn{constructor(){this.saveRouters=[],this.loadRouters=[]}static getInstance(){return null==Tn.instance&&(Tn.instance=new Tn),Tn.instance}static registerSaveRouter(e){Tn.getInstance().saveRouters.push(e)}static registerLoadRouter(e){Tn.getInstance().loadRouters.push(e)}static getSaveHandlers(e){return Tn.getHandlers(e,"save")}static getLoadHandlers(e,t){return Tn.getHandlers(e,"load",t)}static getHandlers(e,t,n){const i=[];return("load"===t?Tn.getInstance().loadRouters:Tn.getInstance().saveRouters).forEach((t=>{const a=t(e,n);null!==a&&i.push(a)})),i}}const En="tensorflowjs",An="models_store",Cn="model_info_store";function $n(){if(!Q().getBool("IS_BROWSER"))throw new Error("Failed to obtain IndexedDB factory because the current environmentis not a web browser.");const e="undefined"==typeof window?self:window,t=e.indexedDB||e.mozIndexedDB||e.webkitIndexedDB||e.msIndexedDB||e.shimIndexedDB;if(null==t)throw new Error("The current browser does not appear to support IndexedDB.");return t}function jn(e){const t=e.result;t.createObjectStore(An,{keyPath:"modelPath"}),t.createObjectStore(Cn,{keyPath:"modelPath"})}class zn{constructor(e){if(this.indexedDB=$n(),null==e||!e)throw new Error("For IndexedDB, modelPath must not be null, undefined or empty.");this.modelPath=e}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");return this.databaseAction(this.modelPath,e)}async load(){return this.databaseAction(this.modelPath)}databaseAction(e,t){return new Promise(((e,n)=>{const i=this.indexedDB.open(En,1);i.onupgradeneeded=()=>jn(i),i.onsuccess=()=>{const a=i.result;if(null==t){const t=a.transaction(An,"readonly"),i=t.objectStore(An).get(this.modelPath);i.onsuccess=()=>{if(null==i.result)return a.close(),n(new Error(`Cannot find model with path '${this.modelPath}' in IndexedDB.`));e(i.result.modelArtifacts)},i.onerror=e=>(a.close(),n(i.error)),t.oncomplete=()=>a.close()}else{const i=Nn(t),s=a.transaction(Cn,"readwrite");let r=s.objectStore(Cn);const o=r.put({modelPath:this.modelPath,modelArtifactsInfo:i});let l;o.onsuccess=()=>{l=a.transaction(An,"readwrite");const o=l.objectStore(An).put({modelPath:this.modelPath,modelArtifacts:t,modelArtifactsInfo:i});o.onsuccess=()=>e({modelArtifactsInfo:i}),o.onerror=e=>{r=s.objectStore(Cn);const t=r.delete(this.modelPath);t.onsuccess=()=>(a.close(),n(o.error)),t.onerror=e=>(a.close(),n(o.error))}},o.onerror=e=>(a.close(),n(o.error)),s.oncomplete=()=>{null==l?a.close():l.oncomplete=()=>a.close()}}},i.onerror=e=>n(i.error)}))}}zn.URL_SCHEME="indexeddb://";const Dn=e=>{return Q().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(zn.URL_SCHEME)?(t=e.slice(zn.URL_SCHEME.length),new zn(t)):null;var t};Tn.registerSaveRouter(Dn),Tn.registerLoadRouter(Dn);class Fn{constructor(){this.indexedDB=$n()}async listModels(){return new Promise(((e,t)=>{const n=this.indexedDB.open(En,1);n.onupgradeneeded=()=>jn(n),n.onsuccess=()=>{const i=n.result,a=i.transaction(Cn,"readonly"),s=a.objectStore(Cn).getAll();s.onsuccess=()=>{const t={};for(const e of s.result)t[e.modelPath]=e.modelArtifactsInfo;e(t)},s.onerror=e=>(i.close(),t(s.error)),a.oncomplete=()=>i.close()},n.onerror=e=>t(n.error)}))}async removeModel(e){var t;return e=(t=e).startsWith(zn.URL_SCHEME)?t.slice(zn.URL_SCHEME.length):t,new Promise(((t,n)=>{const i=this.indexedDB.open(En,1);i.onupgradeneeded=()=>jn(i),i.onsuccess=()=>{const a=i.result,s=a.transaction(Cn,"readwrite"),r=s.objectStore(Cn),o=r.get(e);let l;o.onsuccess=()=>{if(null==o.result)return a.close(),n(new Error(`Cannot find model with path '${e}' in IndexedDB.`));{const i=r.delete(e),s=()=>{l=a.transaction(An,"readwrite");const i=l.objectStore(An).delete(e);i.onsuccess=()=>t(o.result.modelArtifactsInfo),i.onerror=e=>n(o.error)};i.onsuccess=s,i.onerror=e=>(s(),a.close(),n(o.error))}},o.onerror=e=>(a.close(),n(o.error)),s.oncomplete=()=>{null==l?a.close():l.oncomplete=()=>a.close()}},i.onerror=e=>n(i.error)}))}}
382
+ */class In{constructor(){this.saveRouters=[],this.loadRouters=[]}static getInstance(){return null==In.instance&&(In.instance=new In),In.instance}static registerSaveRouter(e){In.getInstance().saveRouters.push(e)}static registerLoadRouter(e){In.getInstance().loadRouters.push(e)}static getSaveHandlers(e){return In.getHandlers(e,"save")}static getLoadHandlers(e,t){return In.getHandlers(e,"load",t)}static getHandlers(e,t,n){const i=[];return("load"===t?In.getInstance().loadRouters:In.getInstance().saveRouters).forEach((t=>{const a=t(e,n);null!==a&&i.push(a)})),i}}const An="tensorflowjs",Cn="models_store",En="model_info_store";function $n(){if(!Q().getBool("IS_BROWSER"))throw new Error("Failed to obtain IndexedDB factory because the current environmentis not a web browser.");const e="undefined"==typeof window?self:window,t=e.indexedDB||e.mozIndexedDB||e.webkitIndexedDB||e.msIndexedDB||e.shimIndexedDB;if(null==t)throw new Error("The current browser does not appear to support IndexedDB.");return t}function jn(e){const t=e.result;t.createObjectStore(Cn,{keyPath:"modelPath"}),t.createObjectStore(En,{keyPath:"modelPath"})}class zn{constructor(e){if(this.indexedDB=$n(),null==e||!e)throw new Error("For IndexedDB, modelPath must not be null, undefined or empty.");this.modelPath=e}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");return this.databaseAction(this.modelPath,e)}async load(){return this.databaseAction(this.modelPath)}databaseAction(e,t){return new Promise(((e,n)=>{const i=this.indexedDB.open(An,1);i.onupgradeneeded=()=>jn(i),i.onsuccess=()=>{const a=i.result;if(null==t){const t=a.transaction(Cn,"readonly"),i=t.objectStore(Cn).get(this.modelPath);i.onsuccess=()=>{if(null==i.result)return a.close(),n(new Error(`Cannot find model with path '${this.modelPath}' in IndexedDB.`));e(i.result.modelArtifacts)},i.onerror=e=>(a.close(),n(i.error)),t.oncomplete=()=>a.close()}else{const i=Nn(t),s=a.transaction(En,"readwrite");let r=s.objectStore(En);const o=r.put({modelPath:this.modelPath,modelArtifactsInfo:i});let l;o.onsuccess=()=>{l=a.transaction(Cn,"readwrite");const o=l.objectStore(Cn).put({modelPath:this.modelPath,modelArtifacts:t,modelArtifactsInfo:i});o.onsuccess=()=>e({modelArtifactsInfo:i}),o.onerror=e=>{r=s.objectStore(En);const t=r.delete(this.modelPath);t.onsuccess=()=>(a.close(),n(o.error)),t.onerror=e=>(a.close(),n(o.error))}},o.onerror=e=>(a.close(),n(o.error)),s.oncomplete=()=>{null==l?a.close():l.oncomplete=()=>a.close()}}},i.onerror=e=>n(i.error)}))}}zn.URL_SCHEME="indexeddb://";const Dn=e=>{return Q().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(zn.URL_SCHEME)?(t=e.slice(zn.URL_SCHEME.length),new zn(t)):null;var t};In.registerSaveRouter(Dn),In.registerLoadRouter(Dn);class Fn{constructor(){this.indexedDB=$n()}async listModels(){return new Promise(((e,t)=>{const n=this.indexedDB.open(An,1);n.onupgradeneeded=()=>jn(n),n.onsuccess=()=>{const i=n.result,a=i.transaction(En,"readonly"),s=a.objectStore(En).getAll();s.onsuccess=()=>{const t={};for(const e of s.result)t[e.modelPath]=e.modelArtifactsInfo;e(t)},s.onerror=e=>(i.close(),t(s.error)),a.oncomplete=()=>i.close()},n.onerror=e=>t(n.error)}))}async removeModel(e){var t;return e=(t=e).startsWith(zn.URL_SCHEME)?t.slice(zn.URL_SCHEME.length):t,new Promise(((t,n)=>{const i=this.indexedDB.open(An,1);i.onupgradeneeded=()=>jn(i),i.onsuccess=()=>{const a=i.result,s=a.transaction(En,"readwrite"),r=s.objectStore(En),o=r.get(e);let l;o.onsuccess=()=>{if(null==o.result)return a.close(),n(new Error(`Cannot find model with path '${e}' in IndexedDB.`));{const i=r.delete(e),s=()=>{l=a.transaction(Cn,"readwrite");const i=l.objectStore(Cn).delete(e);i.onsuccess=()=>t(o.result.modelArtifactsInfo),i.onerror=e=>n(o.error)};i.onsuccess=s,i.onerror=e=>(s(),a.close(),n(o.error))}},o.onerror=e=>(a.close(),n(o.error)),s.oncomplete=()=>{null==l?a.close():l.oncomplete=()=>a.close()}},i.onerror=e=>n(i.error)}))}}
383
383
  /**
384
384
  * @license
385
385
  * Copyright 2018 Google LLC. All Rights Reserved.
@@ -395,7 +395,7 @@ function ln(e,t){let n=e;if(Ct(e))return"string"===t?[]:[e.length];if("object"==
395
395
  * See the License for the specific language governing permissions and
396
396
  * limitations under the License.
397
397
  * =============================================================================
398
- */const _n="/",Rn="tensorflowjs_models",Ln="info",Mn="model_topology",On="weight_specs",Pn="weight_data",Bn="model_metadata";function Un(e){return{info:[Rn,e,Ln].join(_n),topology:[Rn,e,Mn].join(_n),weightSpecs:[Rn,e,On].join(_n),weightData:[Rn,e,Pn].join(_n),modelMetadata:[Rn,e,Bn].join(_n)}}function Wn(e){for(const t of Object.values(e))window.localStorage.removeItem(t)}function Gn(e){const t=e.split(_n);if(t.length<3)throw new Error(`Invalid key format: ${e}`);return t.slice(1,t.length-1).join(_n)}class Vn{constructor(e){if(!Q().getBool("IS_BROWSER")||"undefined"==typeof window||void 0===window.localStorage)throw new Error("The current environment does not support local storage.");if(this.LS=window.localStorage,null==e||!e)throw new Error("For local storage, modelPath must not be null, undefined or empty.");this.modelPath=e,this.keys=Un(this.modelPath)}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");{const t=JSON.stringify(e.modelTopology),n=JSON.stringify(e.weightSpecs),i=Nn(e);try{this.LS.setItem(this.keys.info,JSON.stringify(i)),this.LS.setItem(this.keys.topology,t),this.LS.setItem(this.keys.weightSpecs,n),this.LS.setItem(this.keys.weightData,function(e){if(wn)return Buffer.from(e).toString("base64");const t=new Uint8Array(e);let n="";for(let e=0,i=t.length;e<i;e++)n+=String.fromCharCode(t[e]);return btoa(n)}(e.weightData));const a={format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,signature:null!=e.signature?e.signature:void 0,userDefinedMetadata:null!=e.userDefinedMetadata?e.userDefinedMetadata:void 0,modelInitializer:null!=e.modelInitializer?e.modelInitializer:void 0,initializerSignature:null!=e.initializerSignature?e.initializerSignature:void 0,trainingConfig:null!=e.trainingConfig?e.trainingConfig:void 0};return this.LS.setItem(this.keys.modelMetadata,JSON.stringify(a)),{modelArtifactsInfo:i}}catch(e){throw Wn(this.keys),new Error(`Failed to save model '${this.modelPath}' to local storage: size quota being exceeded is a possible cause of this failure: modelTopologyBytes=${i.modelTopologyBytes}, weightSpecsBytes=${i.weightSpecsBytes}, weightDataBytes=${i.weightDataBytes}.`)}}}async load(){const e=JSON.parse(this.LS.getItem(this.keys.info));if(null==e)throw new Error(`In local storage, there is no model with name '${this.modelPath}'`);if("JSON"!==e.modelTopologyType)throw new Error("BrowserLocalStorage does not support loading non-JSON model topology yet.");const t={},n=JSON.parse(this.LS.getItem(this.keys.topology));if(null==n)throw new Error(`In local storage, the topology of model '${this.modelPath}' is missing.`);t.modelTopology=n;const i=JSON.parse(this.LS.getItem(this.keys.weightSpecs));if(null==i)throw new Error(`In local storage, the weight specs of model '${this.modelPath}' are missing.`);t.weightSpecs=i;const a=this.LS.getItem(this.keys.modelMetadata);if(null!=a){const e=JSON.parse(a);t.format=e.format,t.generatedBy=e.generatedBy,t.convertedBy=e.convertedBy,null!=e.signature&&(t.signature=e.signature),null!=e.userDefinedMetadata&&(t.userDefinedMetadata=e.userDefinedMetadata),null!=e.modelInitializer&&(t.modelInitializer=e.modelInitializer),null!=e.initializerSignature&&(t.initializerSignature=e.initializerSignature),null!=e.trainingConfig&&(t.trainingConfig=e.trainingConfig)}const s=this.LS.getItem(this.keys.weightData);if(null==s)throw new Error(`In local storage, the binary weight values of model '${this.modelPath}' are missing.`);return t.weightData=function(e){if(wn){const t=Buffer.from(e,"base64");return t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}const t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;++e)n.set([t.charCodeAt(e)],e);return n.buffer}(s),t}}Vn.URL_SCHEME="localstorage://";const Kn=e=>{return Q().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(Vn.URL_SCHEME)?(t=e.slice(Vn.URL_SCHEME.length),new Vn(t)):null;var t};Tn.registerSaveRouter(Kn),Tn.registerLoadRouter(Kn);class qn{constructor(){I(Q().getBool("IS_BROWSER"),(()=>"Current environment is not a web browser")),I("undefined"==typeof window||void 0!==window.localStorage,(()=>"Current browser does not appear to support localStorage")),this.LS=window.localStorage}async listModels(){const e={},t=Rn+_n,n=_n+Ln;for(let i=0;i<this.LS.length;++i){const a=this.LS.key(i);if(a.startsWith(t)&&a.endsWith(n)){e[Gn(a)]=JSON.parse(this.LS.getItem(a))}}return e}async removeModel(e){var t;const n=Un(e=(t=e).startsWith(Vn.URL_SCHEME)?t.slice(Vn.URL_SCHEME.length):t);if(null==this.LS.getItem(n.info))throw new Error(`Cannot find model at path '${e}'`);const i=JSON.parse(this.LS.getItem(n.info));return Wn(n),i}}
398
+ */const _n="/",Rn="tensorflowjs_models",Ln="info",Mn="model_topology",On="weight_specs",Pn="weight_data",Bn="model_metadata";function Un(e){return{info:[Rn,e,Ln].join(_n),topology:[Rn,e,Mn].join(_n),weightSpecs:[Rn,e,On].join(_n),weightData:[Rn,e,Pn].join(_n),modelMetadata:[Rn,e,Bn].join(_n)}}function Wn(e){for(const t of Object.values(e))window.localStorage.removeItem(t)}function Vn(e){const t=e.split(_n);if(t.length<3)throw new Error(`Invalid key format: ${e}`);return t.slice(1,t.length-1).join(_n)}class Gn{constructor(e){if(!Q().getBool("IS_BROWSER")||"undefined"==typeof window||void 0===window.localStorage)throw new Error("The current environment does not support local storage.");if(this.LS=window.localStorage,null==e||!e)throw new Error("For local storage, modelPath must not be null, undefined or empty.");this.modelPath=e,this.keys=Un(this.modelPath)}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");{const t=JSON.stringify(e.modelTopology),n=JSON.stringify(e.weightSpecs),i=Nn(e);try{this.LS.setItem(this.keys.info,JSON.stringify(i)),this.LS.setItem(this.keys.topology,t),this.LS.setItem(this.keys.weightSpecs,n),this.LS.setItem(this.keys.weightData,function(e){if(wn)return Buffer.from(e).toString("base64");const t=new Uint8Array(e);let n="";for(let e=0,i=t.length;e<i;e++)n+=String.fromCharCode(t[e]);return btoa(n)}(e.weightData));const a={format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,signature:null!=e.signature?e.signature:void 0,userDefinedMetadata:null!=e.userDefinedMetadata?e.userDefinedMetadata:void 0,modelInitializer:null!=e.modelInitializer?e.modelInitializer:void 0,initializerSignature:null!=e.initializerSignature?e.initializerSignature:void 0,trainingConfig:null!=e.trainingConfig?e.trainingConfig:void 0};return this.LS.setItem(this.keys.modelMetadata,JSON.stringify(a)),{modelArtifactsInfo:i}}catch(e){throw Wn(this.keys),new Error(`Failed to save model '${this.modelPath}' to local storage: size quota being exceeded is a possible cause of this failure: modelTopologyBytes=${i.modelTopologyBytes}, weightSpecsBytes=${i.weightSpecsBytes}, weightDataBytes=${i.weightDataBytes}.`)}}}async load(){const e=JSON.parse(this.LS.getItem(this.keys.info));if(null==e)throw new Error(`In local storage, there is no model with name '${this.modelPath}'`);if("JSON"!==e.modelTopologyType)throw new Error("BrowserLocalStorage does not support loading non-JSON model topology yet.");const t={},n=JSON.parse(this.LS.getItem(this.keys.topology));if(null==n)throw new Error(`In local storage, the topology of model '${this.modelPath}' is missing.`);t.modelTopology=n;const i=JSON.parse(this.LS.getItem(this.keys.weightSpecs));if(null==i)throw new Error(`In local storage, the weight specs of model '${this.modelPath}' are missing.`);t.weightSpecs=i;const a=this.LS.getItem(this.keys.modelMetadata);if(null!=a){const e=JSON.parse(a);t.format=e.format,t.generatedBy=e.generatedBy,t.convertedBy=e.convertedBy,null!=e.signature&&(t.signature=e.signature),null!=e.userDefinedMetadata&&(t.userDefinedMetadata=e.userDefinedMetadata),null!=e.modelInitializer&&(t.modelInitializer=e.modelInitializer),null!=e.initializerSignature&&(t.initializerSignature=e.initializerSignature),null!=e.trainingConfig&&(t.trainingConfig=e.trainingConfig)}const s=this.LS.getItem(this.keys.weightData);if(null==s)throw new Error(`In local storage, the binary weight values of model '${this.modelPath}' are missing.`);return t.weightData=function(e){if(wn){const t=Buffer.from(e,"base64");return t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}const t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;++e)n.set([t.charCodeAt(e)],e);return n.buffer}(s),t}}Gn.URL_SCHEME="localstorage://";const Kn=e=>{return Q().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(Gn.URL_SCHEME)?(t=e.slice(Gn.URL_SCHEME.length),new Gn(t)):null;var t};In.registerSaveRouter(Kn),In.registerLoadRouter(Kn);class qn{constructor(){T(Q().getBool("IS_BROWSER"),(()=>"Current environment is not a web browser")),T("undefined"==typeof window||void 0!==window.localStorage,(()=>"Current browser does not appear to support localStorage")),this.LS=window.localStorage}async listModels(){const e={},t=Rn+_n,n=_n+Ln;for(let i=0;i<this.LS.length;++i){const a=this.LS.key(i);if(a.startsWith(t)&&a.endsWith(n)){e[Vn(a)]=JSON.parse(this.LS.getItem(a))}}return e}async removeModel(e){var t;const n=Un(e=(t=e).startsWith(Gn.URL_SCHEME)?t.slice(Gn.URL_SCHEME.length):t);if(null==this.LS.getItem(n.info))throw new Error(`Cannot find model at path '${e}'`);const i=JSON.parse(this.LS.getItem(n.info));return Wn(n),i}}
399
399
  /**
400
400
  * @license
401
401
  * Copyright 2019 Google LLC. All Rights Reserved.
@@ -411,7 +411,7 @@ function ln(e,t){let n=e;if(Ct(e))return"string"===t?[]:[e.length];if("object"==
411
411
  * See the License for the specific language governing permissions and
412
412
  * limitations under the License.
413
413
  * =============================================================================
414
- */function Hn(e,t,n,i){!function(e){I(null!=e&&Array.isArray(e)&&e.length>0,(()=>"promises must be a none empty array"))}(e),function(e,t){I(e>=0&&e<=1,(()=>`Progress fraction must be in range [0, 1], but got startFraction ${e}`)),I(t>=0&&t<=1,(()=>`Progress fraction must be in range [0, 1], but got endFraction ${t}`)),I(t>=e,(()=>`startFraction must be no more than endFraction, but got startFraction ${e} and endFraction ${t}`))}(n=null==n?0:n,i=null==i?1:i);let a=0;return Promise.all(e.map((s=>(s.then((s=>{const r=n+ ++a/e.length*(i-n);return t(r),s})),s))))}
414
+ */function Hn(e,t,n,i){!function(e){T(null!=e&&Array.isArray(e)&&e.length>0,(()=>"promises must be a none empty array"))}(e),function(e,t){T(e>=0&&e<=1,(()=>`Progress fraction must be in range [0, 1], but got startFraction ${e}`)),T(t>=0&&t<=1,(()=>`Progress fraction must be in range [0, 1], but got endFraction ${t}`)),T(t>=e,(()=>`startFraction must be no more than endFraction, but got startFraction ${e} and endFraction ${t}`))}(n=null==n?0:n,i=null==i?1:i);let a=0;return Promise.all(e.map((s=>(s.then((s=>{const r=n+ ++a/e.length*(i-n);return t(r),s})),s))))}
415
415
  /**
416
416
  * @license
417
417
  * Copyright 2018 Google LLC. All Rights Reserved.
@@ -427,7 +427,7 @@ function ln(e,t){let n=e;if(Ct(e))return"string"===t?[]:[e.length];if("object"==
427
427
  * See the License for the specific language governing permissions and
428
428
  * limitations under the License.
429
429
  * =============================================================================
430
- */class Jn{constructor(e,t){if(this.DEFAULT_METHOD="POST",null==t&&(t={}),this.weightPathPrefix=t.weightPathPrefix,this.onProgress=t.onProgress,this.weightUrlConverter=t.weightUrlConverter,null!=t.fetchFunc?(I("function"==typeof t.fetchFunc,(()=>"Must pass a function that matches the signature of `fetch` (see https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)")),this.fetch=t.fetchFunc):this.fetch=Q().platform.fetch,I(null!=e&&e.length>0,(()=>"URL path for http must not be null, undefined or empty.")),Array.isArray(e)&&I(2===e.length,(()=>`URL paths for http must have a length of 2, (actual length is ${e.length}).`)),this.path=e,null!=t.requestInit&&null!=t.requestInit.body)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=t.requestInit||{}}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");const t=Object.assign({method:this.DEFAULT_METHOD},this.requestInit);t.body=new FormData;const n=function(e,t){const n={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,weightsManifest:t};return null!=e.signature&&(n.signature=e.signature),null!=e.userDefinedMetadata&&(n.userDefinedMetadata=e.userDefinedMetadata),null!=e.modelInitializer&&(n.modelInitializer=e.modelInitializer),null!=e.initializerSignature&&(n.initializerSignature=e.initializerSignature),null!=e.trainingConfig&&(n.trainingConfig=e.trainingConfig),n}(e,[{paths:["./model.weights.bin"],weights:e.weightSpecs}]);t.body.append("model.json",new Blob([JSON.stringify(n)],{type:"application/json"}),"model.json"),null!=e.weightData&&t.body.append("model.weights.bin",new Blob([e.weightData],{type:"application/octet-stream"}),"model.weights.bin");const i=await this.fetch(this.path,t);if(i.ok)return{modelArtifactsInfo:Nn(e),responses:[i]};throw new Error(`BrowserHTTPRequest.save() failed due to HTTP response status ${i.status}.`)}async load(){const e=await this.fetch(this.path,this.requestInit);if(!e.ok)throw new Error(`Request to ${this.path} failed with status code ${e.status}. Please verify this URL points to the model JSON of the model to load.`);let t;try{t=await e.json()}catch(e){let t=`Failed to parse model JSON of response from ${this.path}.`;throw this.path.endsWith(".pb")?t+=" Your path contains a .pb file extension. Support for .pb models have been removed in TensorFlow.js 1.0 in favor of .json models. You can re-convert your Python TensorFlow model using the TensorFlow.js 1.0 conversion scripts or you can convert your.pb models with the 'pb2json'NPM script in the tensorflow/tfjs-converter repository.":t+=" Please make sure the server is serving valid JSON for this request.",new Error(t)}const n=t.modelTopology,i=t.weightsManifest;if(null==n&&null==i)throw new Error(`The JSON from HTTP path ${this.path} contains neither model topology or manifest for weights.`);return Sn(t,(e=>this.loadWeights(e)))}async loadWeights(e){const t=Array.isArray(this.path)?this.path[1]:this.path,[n,i]=function(e){const t=e.lastIndexOf("/"),n=e.lastIndexOf("?"),i=e.substring(0,t),a=n>t?e.substring(n):"";return[i+"/",a]}(t),a=this.weightPathPrefix||n,s=function(e){const t=[];for(const n of e)t.push(...n.weights);return t}(e),r=[],o=[];for(const t of e)for(const e of t.paths)null!=this.weightUrlConverter?o.push(this.weightUrlConverter(e)):r.push(a+e+i);this.weightUrlConverter&&r.push(...await Promise.all(o));const l=await async function(e,t){null==t&&(t={});const n=null==t.fetchFunc?Q().platform.fetch:t.fetchFunc,i=e.map((e=>n(e,t.requestInit,{isBinary:!0}))),a=(null==t.onProgress?await Promise.all(i):await Hn(i,t.onProgress,0,.5)).map((e=>e.arrayBuffer()));return null==t.onProgress?await Promise.all(a):await Hn(a,t.onProgress,.5,1)}
430
+ */class Jn{constructor(e,t){if(this.DEFAULT_METHOD="POST",null==t&&(t={}),this.weightPathPrefix=t.weightPathPrefix,this.onProgress=t.onProgress,this.weightUrlConverter=t.weightUrlConverter,null!=t.fetchFunc?(T("function"==typeof t.fetchFunc,(()=>"Must pass a function that matches the signature of `fetch` (see https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)")),this.fetch=t.fetchFunc):this.fetch=Q().platform.fetch,T(null!=e&&e.length>0,(()=>"URL path for http must not be null, undefined or empty.")),Array.isArray(e)&&T(2===e.length,(()=>`URL paths for http must have a length of 2, (actual length is ${e.length}).`)),this.path=e,null!=t.requestInit&&null!=t.requestInit.body)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=t.requestInit||{}}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");const t=Object.assign({method:this.DEFAULT_METHOD},this.requestInit);t.body=new FormData;const n=function(e,t){const n={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,weightsManifest:t};return null!=e.signature&&(n.signature=e.signature),null!=e.userDefinedMetadata&&(n.userDefinedMetadata=e.userDefinedMetadata),null!=e.modelInitializer&&(n.modelInitializer=e.modelInitializer),null!=e.initializerSignature&&(n.initializerSignature=e.initializerSignature),null!=e.trainingConfig&&(n.trainingConfig=e.trainingConfig),n}(e,[{paths:["./model.weights.bin"],weights:e.weightSpecs}]);t.body.append("model.json",new Blob([JSON.stringify(n)],{type:"application/json"}),"model.json"),null!=e.weightData&&t.body.append("model.weights.bin",new Blob([e.weightData],{type:"application/octet-stream"}),"model.weights.bin");const i=await this.fetch(this.path,t);if(i.ok)return{modelArtifactsInfo:Nn(e),responses:[i]};throw new Error(`BrowserHTTPRequest.save() failed due to HTTP response status ${i.status}.`)}async load(){const e=await this.fetch(this.path,this.requestInit);if(!e.ok)throw new Error(`Request to ${this.path} failed with status code ${e.status}. Please verify this URL points to the model JSON of the model to load.`);let t;try{t=await e.json()}catch(e){let t=`Failed to parse model JSON of response from ${this.path}.`;throw this.path.endsWith(".pb")?t+=" Your path contains a .pb file extension. Support for .pb models have been removed in TensorFlow.js 1.0 in favor of .json models. You can re-convert your Python TensorFlow model using the TensorFlow.js 1.0 conversion scripts or you can convert your.pb models with the 'pb2json'NPM script in the tensorflow/tfjs-converter repository.":t+=" Please make sure the server is serving valid JSON for this request.",new Error(t)}const n=t.modelTopology,i=t.weightsManifest;if(null==n&&null==i)throw new Error(`The JSON from HTTP path ${this.path} contains neither model topology or manifest for weights.`);return Sn(t,(e=>this.loadWeights(e)))}async loadWeights(e){const t=Array.isArray(this.path)?this.path[1]:this.path,[n,i]=function(e){const t=e.lastIndexOf("/"),n=e.lastIndexOf("?"),i=e.substring(0,t),a=n>t?e.substring(n):"";return[i+"/",a]}(t),a=this.weightPathPrefix||n,s=function(e){const t=[];for(const n of e)t.push(...n.weights);return t}(e),r=[],o=[];for(const t of e)for(const e of t.paths)null!=this.weightUrlConverter?o.push(this.weightUrlConverter(e)):r.push(a+e+i);this.weightUrlConverter&&r.push(...await Promise.all(o));const l=await async function(e,t){null==t&&(t={});const n=null==t.fetchFunc?Q().platform.fetch:t.fetchFunc,i=e.map((e=>n(e,t.requestInit,{isBinary:!0}))),a=(null==t.onProgress?await Promise.all(i):await Hn(i,t.onProgress,0,.5)).map((e=>e.arrayBuffer()));return null==t.onProgress?await Promise.all(a):await Hn(a,t.onProgress,.5,1)}
431
431
  /**
432
432
  * @license
433
433
  * Copyright 2018 Google LLC. All Rights Reserved.
@@ -443,7 +443,7 @@ function ln(e,t){let n=e;if(Ct(e))return"string"===t?[]:[e.length];if("object"==
443
443
  * See the License for the specific language governing permissions and
444
444
  * limitations under the License.
445
445
  * =============================================================================
446
- */(r,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress});return[s,xn(l)]}}function Zn(e){return null!=e.match(Jn.URL_SCHEME_REGEX)}Jn.URL_SCHEME_REGEX=/^https?:\/\//;const Yn=(e,t)=>{if("undefined"==typeof fetch&&(null==t||null==t.fetchFunc))return null;{let n=!0;if(n=Array.isArray(e)?e.every((e=>Zn(e))):Zn(e),n)return Qn(e,t)}return null};function Qn(e,t){return new Jn(e,t)}Tn.registerSaveRouter(Yn),Tn.registerLoadRouter(Yn);class Xn{constructor(){this.managers={}}static getInstance(){return null==Xn.instance&&(Xn.instance=new Xn),Xn.instance}static registerManager(e,t){I(null!=e,(()=>"scheme must not be undefined or null.")),e.endsWith("://")&&(e=e.slice(0,e.indexOf("://"))),I(e.length>0,(()=>"scheme must not be an empty string."));const n=Xn.getInstance();I(null==n.managers[e],(()=>`A model store manager is already registered for scheme '${e}'.`)),n.managers[e]=t}static getManager(e){const t=Xn.getInstance().managers[e];if(null==t)throw new Error(`Cannot find model manager for scheme '${e}'`);return t}static getSchemes(){return Object.keys(Xn.getInstance().managers)}}
446
+ */(r,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress});return[s,xn(l)]}}function Zn(e){return null!=e.match(Jn.URL_SCHEME_REGEX)}Jn.URL_SCHEME_REGEX=/^https?:\/\//;const Yn=(e,t)=>{if("undefined"==typeof fetch&&(null==t||null==t.fetchFunc))return null;{let n=!0;if(n=Array.isArray(e)?e.every((e=>Zn(e))):Zn(e),n)return Qn(e,t)}return null};function Qn(e,t){return new Jn(e,t)}In.registerSaveRouter(Yn),In.registerLoadRouter(Yn);class Xn{constructor(){this.managers={}}static getInstance(){return null==Xn.instance&&(Xn.instance=new Xn),Xn.instance}static registerManager(e,t){T(null!=e,(()=>"scheme must not be undefined or null.")),e.endsWith("://")&&(e=e.slice(0,e.indexOf("://"))),T(e.length>0,(()=>"scheme must not be an empty string."));const n=Xn.getInstance();T(null==n.managers[e],(()=>`A model store manager is already registered for scheme '${e}'.`)),n.managers[e]=t}static getManager(e){const t=Xn.getInstance().managers[e];if(null==t)throw new Error(`Cannot find model manager for scheme '${e}'`);return t}static getSchemes(){return Object.keys(Xn.getInstance().managers)}}
447
447
  /**
448
448
  * @license
449
449
  * Copyright 2020 Google Inc. All Rights Reserved.
@@ -572,7 +572,7 @@ function(e){const t={input:hn(e,"input","imag")};return sn.runKernel("Imag",t)}}
572
572
  * See the License for the specific language governing permissions and
573
573
  * limitations under the License.
574
574
  * =============================================================================
575
- */const hi=dn({transpose_:function(e,t,n){const i=hn(e,"x","transpose");if(null==t&&(t=i.shape.map(((e,t)=>t)).reverse()),I(i.rank===t.length,(()=>`Error in transpose: rank of input ${i.rank} must match length of perm ${t}.`)),t.forEach((e=>{I(e>=0&&e<i.rank,(()=>"All entries in 'perm' must be between 0 and "+(i.rank-1)+` but got ${t}`))})),i.rank<=1)return i.clone();const a={x:i},s={perm:t};return"complex64"===i.dtype?si((()=>{let e=ui(i),t=li(i);return e=sn.runKernel(ct,{x:e},s),t=sn.runKernel(ct,{x:t},s),n&&(t=ci(t)),mn(e,t)})):sn.runKernel(ct,a,s)}});
575
+ */const hi=dn({transpose_:function(e,t,n){const i=hn(e,"x","transpose");if(null==t&&(t=i.shape.map(((e,t)=>t)).reverse()),T(i.rank===t.length,(()=>`Error in transpose: rank of input ${i.rank} must match length of perm ${t}.`)),t.forEach((e=>{T(e>=0&&e<i.rank,(()=>"All entries in 'perm' must be between 0 and "+(i.rank-1)+` but got ${t}`))})),i.rank<=1)return i.clone();const a={x:i},s={perm:t};return"complex64"===i.dtype?si((()=>{let e=ui(i),t=li(i);return e=sn.runKernel(ct,{x:e},s),t=sn.runKernel(ct,{x:t},s),n&&(t=ci(t)),mn(e,t)})):sn.runKernel(ct,a,s)}});
576
576
  /**
577
577
  * @license
578
578
  * Copyright 2017 Google LLC. All Rights Reserved.
@@ -604,7 +604,7 @@ function(e){const t={input:hn(e,"input","imag")};return sn.runKernel("Imag",t)}}
604
604
  * See the License for the specific language governing permissions and
605
605
  * limitations under the License.
606
606
  * =============================================================================
607
- */function fi(e,t,n){let i;const a=e.shape.length;let s;return i="number"==typeof t?[t,...new Array(a-1).fill(0)]:t.length<a?t.concat(new Array(a-t.length).fill(0)):t.slice(),i.forEach((e=>{I(-1!==e,(()=>"slice() does not support negative begin indexing."))})),s=null==n?new Array(a).fill(-1):"number"==typeof n?[n,...new Array(a-1).fill(-1)]:n.length<a?n.concat(new Array(a-n.length).fill(-1)):n,s=s.map(((t,n)=>t>=0?t:(I(-1===t,(()=>`Negative size values should be exactly -1 but got ${t} for the slice() size at index ${n}.`)),e.shape[n]-i[n]))),[i,s]}
607
+ */function fi(e,t,n){let i;const a=e.shape.length;let s;return i="number"==typeof t?[t,...new Array(a-1).fill(0)]:t.length<a?t.concat(new Array(a-t.length).fill(0)):t.slice(),i.forEach((e=>{T(-1!==e,(()=>"slice() does not support negative begin indexing."))})),s=null==n?new Array(a).fill(-1):"number"==typeof n?[n,...new Array(a-1).fill(-1)]:n.length<a?n.concat(new Array(a-n.length).fill(-1)):n,s=s.map(((t,n)=>t>=0?t:(T(-1===t,(()=>`Negative size values should be exactly -1 but got ${t} for the slice() size at index ${n}.`)),e.shape[n]-i[n]))),[i,s]}
608
608
  /**
609
609
  * @license
610
610
  * Copyright 2018 Google LLC. All Rights Reserved.
@@ -620,7 +620,7 @@ function(e){const t={input:hn(e,"input","imag")};return sn.runKernel("Imag",t)}}
620
620
  * See the License for the specific language governing permissions and
621
621
  * limitations under the License.
622
622
  * =============================================================================
623
- */class gi{getClassName(){return this.constructor.className}static fromConfig(e,t){return new e(t)}}class vi{constructor(){this.classNameMap={}}static getMap(){return null==vi.instance&&(vi.instance=new vi),vi.instance}static register(e){vi.getMap().classNameMap[e.className]=[e,e.fromConfig]}}function yi(e){I(null!=e.className,(()=>"Class being registered does not have the static className property defined.")),I("string"==typeof e.className,(()=>"className is required to be a string, but got type "+typeof e.className)),I(e.className.length>0,(()=>"Class being registered has an empty-string as its className, which is disallowed.")),vi.register(e)}
623
+ */class gi{getClassName(){return this.constructor.className}static fromConfig(e,t){return new e(t)}}class vi{constructor(){this.classNameMap={}}static getMap(){return null==vi.instance&&(vi.instance=new vi),vi.instance}static register(e){vi.getMap().classNameMap[e.className]=[e,e.fromConfig]}}function yi(e){T(null!=e.className,(()=>"Class being registered does not have the static className property defined.")),T("string"==typeof e.className,(()=>"className is required to be a string, but got type "+typeof e.className)),T(e.className.length>0,(()=>"Class being registered has an empty-string as its className, which is disallowed.")),vi.register(e)}
624
624
  /**
625
625
  * @license
626
626
  * Copyright 2020 Google LLC. All Rights Reserved.
@@ -732,7 +732,7 @@ function(e){const t={input:hn(e,"input","imag")};return sn.runKernel("Imag",t)}}
732
732
  * See the License for the specific language governing permissions and
733
733
  * limitations under the License.
734
734
  * =============================================================================
735
- */const Ii=dn({any_:function(e,t=null,n=!1){const i={x:hn(e,"x","any","bool")},a={axis:t,keepDims:n};return sn.runKernel("Any",i,a)}});
735
+ */const Ti=dn({any_:function(e,t=null,n=!1){const i={x:hn(e,"x","any","bool")},a={axis:t,keepDims:n};return sn.runKernel("Any",i,a)}});
736
736
  /**
737
737
  * @license
738
738
  * Copyright 2020 Google Inc. All Rights Reserved.
@@ -748,7 +748,7 @@ function(e){const t={input:hn(e,"input","imag")};return sn.runKernel("Imag",t)}}
748
748
  * See the License for the specific language governing permissions and
749
749
  * limitations under the License.
750
750
  * =============================================================================
751
- */const Ti=dn({argMax_:function(e,t=0){const n={x:hn(e,"x","argMax")},i={axis:t};return sn.runKernel(ae,n,i)}});
751
+ */const Ii=dn({argMax_:function(e,t=0){const n={x:hn(e,"x","argMax")},i={axis:t};return sn.runKernel(ae,n,i)}});
752
752
  /**
753
753
  * @license
754
754
  * Copyright 2020 Google LLC. All Rights Reserved.
@@ -764,7 +764,7 @@ function(e){const t={input:hn(e,"input","imag")};return sn.runKernel("Imag",t)}}
764
764
  * See the License for the specific language governing permissions and
765
765
  * limitations under the License.
766
766
  * =============================================================================
767
- */function Ei(e,t,n,i,a,s,r=!1,o="channelsLast"){let[l,c,u,h]=[-1,-1,-1,-1];if("channelsLast"===o)[l,c,u,h]=e;else{if("channelsFirst"!==o)throw new Error(`Unknown dataFormat ${o}`);[l,h,c,u]=e}const[p,d,,m]=t,[f,g]=Ai(n),[v,y]=Ai(i),b=Ci(p,v),w=Ci(d,y),{padInfo:k,outHeight:x,outWidth:S}=function(e,t,n,i,a,s,r,o,l){let c,u,h;if("number"==typeof e){c={top:e,bottom:e,left:e,right:e,type:0===e?"VALID":"NUMBER"};const a=function(e,t,n,i,a){null==i&&(i=function(e,t,n,i=1){const a=Ci(t,i);return Math.floor((e[0]*(n-1)-n+a)/2)}(e,t,n));const s=e[0],r=e[1],o=$i((s-t+2*i)/n+1,a),l=$i((r-t+2*i)/n+1,a);return[o,l]}([t,n],s,i,e,o);u=a[0],h=a[1]}else if("same"===e){u=Math.ceil(t/i),h=Math.ceil(n/a);const e=Math.max(0,(u-1)*i+s-t),o=Math.max(0,(h-1)*a+r-n),l=Math.floor(e/2),p=e-l,d=Math.floor(o/2);c={top:l,bottom:p,left:d,right:o-d,type:"SAME"}}else if("valid"===e)c={top:0,bottom:0,left:0,right:0,type:"VALID"},u=Math.ceil((t-s+1)/i),h=Math.ceil((n-r+1)/a);else{if("object"!=typeof e)throw Error(`Unknown padding parameter: ${e}`);{const p="channelsLast"===l?e[1][0]:e[2][0],d="channelsLast"===l?e[1][1]:e[2][1],m="channelsLast"===l?e[2][0]:e[3][0],f="channelsLast"===l?e[2][1]:e[3][1];c={top:p,bottom:d,left:m,right:f,type:0===p&&0===d&&0===m&&0===f?"VALID":"EXPLICIT"},u=$i((t-s+p+d)/i+1,o),h=$i((n-r+m+f)/a+1,o)}}return{padInfo:c,outHeight:u,outWidth:h}}(a,c,u,f,g,b,w,s,o),N=r?m*h:m;let I;return"channelsFirst"===o?I=[l,N,x,S]:"channelsLast"===o&&(I=[l,x,S,N]),{batchSize:l,dataFormat:o,inHeight:c,inWidth:u,inChannels:h,outHeight:x,outWidth:S,outChannels:N,padInfo:k,strideHeight:f,strideWidth:g,filterHeight:p,filterWidth:d,effectiveFilterHeight:b,effectiveFilterWidth:w,dilationHeight:v,dilationWidth:y,inShape:e,outShape:I,filterShape:t}}function Ai(e){return"number"==typeof e?[e,e,e]:2===e.length?[e[0],e[1],1]:e}function Ci(e,t){return t<=1?e:e+(e-1)*(t-1)}function $i(e,t){if(!t)return Math.trunc(e);switch(t){case"round":return Math.round(e);case"ceil":return Math.ceil(e);case"floor":return Math.floor(e);default:throw new Error(`Unknown roundingMode ${t}`)}}function ji(e){const[t,n,i]=Ai(e);return 1===t&&1===n&&1===i}function zi(e,t){return ji(e)||ji(t)}function Di(e){return Ai(e).every((e=>e>0))}function Fi(e,t,n){if(null!=n){if("string"==typeof t)throw Error(`Error in ${e}: pad must be an integer when using dimRoundingMode ${n} but got pad ${t}.`);if("number"==typeof t)I($(t),(()=>`Error in ${e}: pad must be an integer when using dimRoundingMode ${n} but got pad ${t}.`));else{if("object"!=typeof t)throw Error(`Error in ${e}: Unknown padding parameter: ${t}`);t.forEach((t=>{t.forEach((t=>{I($(t),(()=>`Error in ${e}: pad must be an integer when using dimRoundingMode ${n} but got pad ${t}.`))}))}))}}}
767
+ */function Ai(e,t,n,i,a,s,r=!1,o="channelsLast"){let[l,c,u,h]=[-1,-1,-1,-1];if("channelsLast"===o)[l,c,u,h]=e;else{if("channelsFirst"!==o)throw new Error(`Unknown dataFormat ${o}`);[l,h,c,u]=e}const[p,d,,m]=t,[f,g]=Ci(n),[v,y]=Ci(i),b=Ei(p,v),w=Ei(d,y),{padInfo:k,outHeight:x,outWidth:S}=function(e,t,n,i,a,s,r,o,l){let c,u,h;if("number"==typeof e){c={top:e,bottom:e,left:e,right:e,type:0===e?"VALID":"NUMBER"};const a=function(e,t,n,i,a){null==i&&(i=function(e,t,n,i=1){const a=Ei(t,i);return Math.floor((e[0]*(n-1)-n+a)/2)}(e,t,n));const s=e[0],r=e[1],o=$i((s-t+2*i)/n+1,a),l=$i((r-t+2*i)/n+1,a);return[o,l]}([t,n],s,i,e,o);u=a[0],h=a[1]}else if("same"===e){u=Math.ceil(t/i),h=Math.ceil(n/a);const e=Math.max(0,(u-1)*i+s-t),o=Math.max(0,(h-1)*a+r-n),l=Math.floor(e/2),p=e-l,d=Math.floor(o/2);c={top:l,bottom:p,left:d,right:o-d,type:"SAME"}}else if("valid"===e)c={top:0,bottom:0,left:0,right:0,type:"VALID"},u=Math.ceil((t-s+1)/i),h=Math.ceil((n-r+1)/a);else{if("object"!=typeof e)throw Error(`Unknown padding parameter: ${e}`);{const p="channelsLast"===l?e[1][0]:e[2][0],d="channelsLast"===l?e[1][1]:e[2][1],m="channelsLast"===l?e[2][0]:e[3][0],f="channelsLast"===l?e[2][1]:e[3][1];c={top:p,bottom:d,left:m,right:f,type:0===p&&0===d&&0===m&&0===f?"VALID":"EXPLICIT"},u=$i((t-s+p+d)/i+1,o),h=$i((n-r+m+f)/a+1,o)}}return{padInfo:c,outHeight:u,outWidth:h}}(a,c,u,f,g,b,w,s,o),N=r?m*h:m;let T;return"channelsFirst"===o?T=[l,N,x,S]:"channelsLast"===o&&(T=[l,x,S,N]),{batchSize:l,dataFormat:o,inHeight:c,inWidth:u,inChannels:h,outHeight:x,outWidth:S,outChannels:N,padInfo:k,strideHeight:f,strideWidth:g,filterHeight:p,filterWidth:d,effectiveFilterHeight:b,effectiveFilterWidth:w,dilationHeight:v,dilationWidth:y,inShape:e,outShape:T,filterShape:t}}function Ci(e){return"number"==typeof e?[e,e,e]:2===e.length?[e[0],e[1],1]:e}function Ei(e,t){return t<=1?e:e+(e-1)*(t-1)}function $i(e,t){if(!t)return Math.trunc(e);switch(t){case"round":return Math.round(e);case"ceil":return Math.ceil(e);case"floor":return Math.floor(e);default:throw new Error(`Unknown roundingMode ${t}`)}}function ji(e){const[t,n,i]=Ci(e);return 1===t&&1===n&&1===i}function zi(e,t){return ji(e)||ji(t)}function Di(e){return Ci(e).every((e=>e>0))}function Fi(e,t,n){if(null!=n){if("string"==typeof t)throw Error(`Error in ${e}: pad must be an integer when using dimRoundingMode ${n} but got pad ${t}.`);if("number"==typeof t)T($(t),(()=>`Error in ${e}: pad must be an integer when using dimRoundingMode ${n} but got pad ${t}.`));else{if("object"!=typeof t)throw Error(`Error in ${e}: Unknown padding parameter: ${t}`);t.forEach((t=>{t.forEach((t=>{T($(t),(()=>`Error in ${e}: pad must be an integer when using dimRoundingMode ${n} but got pad ${t}.`))}))}))}}}
768
768
  /**
769
769
  * @license
770
770
  * Copyright 2020 Google LLC. All Rights Reserved.
@@ -796,7 +796,7 @@ function(e){const t={input:hn(e,"input","imag")};return sn.runKernel("Imag",t)}}
796
796
  * See the License for the specific language governing permissions and
797
797
  * limitations under the License.
798
798
  * =============================================================================
799
- */const Ri=dn({avgPool_:function(e,t,n,i,a){const s=hn(e,"x","avgPool","float32");I(zi(n,1),(()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${n} and dilations '1'`));let r=s,o=!1;3===s.rank&&(o=!0,r=_i(s,[1,s.shape[0],s.shape[1],s.shape[2]])),I(4===r.rank,(()=>`Error in avgPool: x must be rank 4 but got rank ${r.rank}.`)),Fi("avgPool",i,a);const l={x:r},c={filterSize:t,strides:n,pad:i,dimRoundingMode:a};let u=sn.runKernel(se,l,c);return u=ei(u,s.dtype),o?_i(u,[u.shape[1],u.shape[2],u.shape[3]]):u}});
799
+ */const Ri=dn({avgPool_:function(e,t,n,i,a){const s=hn(e,"x","avgPool","float32");T(zi(n,1),(()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${n} and dilations '1'`));let r=s,o=!1;3===s.rank&&(o=!0,r=_i(s,[1,s.shape[0],s.shape[1],s.shape[2]])),T(4===r.rank,(()=>`Error in avgPool: x must be rank 4 but got rank ${r.rank}.`)),Fi("avgPool",i,a);const l={x:r},c={filterSize:t,strides:n,pad:i,dimRoundingMode:a};let u=sn.runKernel(se,l,c);return u=ei(u,s.dtype),o?_i(u,[u.shape[1],u.shape[2],u.shape[3]]):u}});
800
800
  /**
801
801
  * @license
802
802
  * Copyright 2020 Google LLC. All Rights Reserved.
@@ -812,7 +812,7 @@ function(e){const t={input:hn(e,"input","imag")};return sn.runKernel("Imag",t)}}
812
812
  * See the License for the specific language governing permissions and
813
813
  * limitations under the License.
814
814
  * =============================================================================
815
- */const Li=dn({avgPool3d_:function(e,t,n,i,a,s="NDHWC"){const r=hn(e,"x","avgPool3d","float32");let o=r,l=!1;4===r.rank&&(l=!0,o=_i(r,[1,r.shape[0],r.shape[1],r.shape[2],r.shape[3]])),I(5===o.rank,(()=>`Error in avgPool3d: x must be rank 5 but got rank ${o.rank}.`)),I("NDHWC"===s,(()=>`Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of ${s}`)),I("number"==typeof n&&n>0||Array.isArray(n)&&n[0]>0&&n[1]>0&&n[2]>0,(()=>`Error in avgPool3d: Stride must be > 0, but got '${n}'`)),Fi("avgPool3d",i,a);const c={x:o},u={filterSize:t,strides:n,pad:i,dimRoundingMode:a,dataFormat:s};let h=sn.runKernel(re,c,u);return h=ei(h,o.dtype),l?_i(h,[h.shape[1],h.shape[2],h.shape[3],h.shape[4]]):h}});
815
+ */const Li=dn({avgPool3d_:function(e,t,n,i,a,s="NDHWC"){const r=hn(e,"x","avgPool3d","float32");let o=r,l=!1;4===r.rank&&(l=!0,o=_i(r,[1,r.shape[0],r.shape[1],r.shape[2],r.shape[3]])),T(5===o.rank,(()=>`Error in avgPool3d: x must be rank 5 but got rank ${o.rank}.`)),T("NDHWC"===s,(()=>`Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of ${s}`)),T("number"==typeof n&&n>0||Array.isArray(n)&&n[0]>0&&n[1]>0&&n[2]>0,(()=>`Error in avgPool3d: Stride must be > 0, but got '${n}'`)),Fi("avgPool3d",i,a);const c={x:o},u={filterSize:t,strides:n,pad:i,dimRoundingMode:a,dataFormat:s};let h=sn.runKernel(re,c,u);return h=ei(h,o.dtype),l?_i(h,[h.shape[1],h.shape[2],h.shape[3],h.shape[4]]):h}});
816
816
  /**
817
817
  * @license
818
818
  * Copyright 2020 Google LLC. All Rights Reserved.
@@ -828,7 +828,7 @@ function(e){const t={input:hn(e,"input","imag")};return sn.runKernel("Imag",t)}}
828
828
  * See the License for the specific language governing permissions and
829
829
  * limitations under the License.
830
830
  * =============================================================================
831
- */const Mi=dn({clone_:function(e){const t={x:hn(e,"x","clone","string_or_numeric")};return sn.runKernel(Ee,t)}});
831
+ */const Mi=dn({clone_:function(e){const t={x:hn(e,"x","clone","string_or_numeric")};return sn.runKernel(Ae,t)}});
832
832
  /**
833
833
  * @license
834
834
  * Copyright 2020 Google LLC. All Rights Reserved.
@@ -844,7 +844,7 @@ function(e){const t={input:hn(e,"input","imag")};return sn.runKernel("Imag",t)}}
844
844
  * See the License for the specific language governing permissions and
845
845
  * limitations under the License.
846
846
  * =============================================================================
847
- */const Oi=dn({concat_:function(e,t=0){I(e.length>=1,(()=>"Pass at least one tensor to concat"));const n=pn(e,"tensors","concat","string_or_numeric");if("complex64"===n[0].dtype&&n.forEach((e=>{if("complex64"!==e.dtype)throw new Error(`Cannot concatenate complex64 tensors with a tensor\n with dtype ${e.dtype}. `)})),1===n.length)return Mi(n[0]);const i=n,a={axis:t};return sn.runKernel(pe,i,a)}});
847
+ */const Oi=dn({concat_:function(e,t=0){T(e.length>=1,(()=>"Pass at least one tensor to concat"));const n=pn(e,"tensors","concat","string_or_numeric");if("complex64"===n[0].dtype&&n.forEach((e=>{if("complex64"!==e.dtype)throw new Error(`Cannot concatenate complex64 tensors with a tensor\n with dtype ${e.dtype}. `)})),1===n.length)return Mi(n[0]);const i=n,a={axis:t};return sn.runKernel(pe,i,a)}});
848
848
  /**
849
849
  * @license
850
850
  * Copyright 2018 Google LLC. All Rights Reserved.
@@ -908,7 +908,7 @@ function(e){const t={input:hn(e,"input","imag")};return sn.runKernel("Imag",t)}}
908
908
  * See the License for the specific language governing permissions and
909
909
  * limitations under the License.
910
910
  * =============================================================================
911
- */const Wi=dn({batchToSpaceND_:function(e,t,n){const i=hn(e,"x","batchToSpaceND"),a=t.reduce(((e,t)=>e*t));I(i.rank>=1+t.length,(()=>`input rank is ${i.rank} but should be > than blockShape.length ${t.length}`)),I(n.length===t.length,(()=>`crops.length is ${n.length} but should be equal to blockShape.length ${t.length}`)),I(i.shape[0]%a==0,(()=>`input tensor batch is ${i.shape[0]} but is not divisible by the product of the elements of blockShape ${t.join(" * ")} === ${a}`));const s={x:i},r={blockShape:t,crops:n};return sn.runKernel(le,s,r)}});const Gi=dn({batchNorm_:
911
+ */const Wi=dn({batchToSpaceND_:function(e,t,n){const i=hn(e,"x","batchToSpaceND"),a=t.reduce(((e,t)=>e*t));T(i.rank>=1+t.length,(()=>`input rank is ${i.rank} but should be > than blockShape.length ${t.length}`)),T(n.length===t.length,(()=>`crops.length is ${n.length} but should be equal to blockShape.length ${t.length}`)),T(i.shape[0]%a==0,(()=>`input tensor batch is ${i.shape[0]} but is not divisible by the product of the elements of blockShape ${t.join(" * ")} === ${a}`));const s={x:i},r={blockShape:t,crops:n};return sn.runKernel(le,s,r)}});const Vi=dn({batchNorm_:
912
912
  /**
913
913
  * @license
914
914
  * Copyright 2020 Google LLC. All Rights Reserved.
@@ -925,7 +925,7 @@ function(e){const t={input:hn(e,"input","imag")};return sn.runKernel("Imag",t)}}
925
925
  * limitations under the License.
926
926
  * =============================================================================
927
927
  */
928
- function(e,t,n,i,a,s){null==s&&(s=.001);const r=hn(e,"x","batchNorm"),o=hn(t,"mean","batchNorm"),l=hn(n,"variance","batchNorm");let c,u;null!=a&&(c=hn(a,"scale","batchNorm")),null!=i&&(u=hn(i,"offset","batchNorm")),I(o.rank===l.rank,(()=>"Batch normalization gradient requires mean and variance to have equal ranks.")),I(null==u||o.rank===u.rank,(()=>"Batch normalization gradient requires mean and offset to have equal ranks.")),I(null==c||o.rank===c.rank,(()=>"Batch normalization gradient requires mean and scale to have equal ranks."));const h={x:function(e){let t;return t=0===e.rank||1===e.rank?_i(e,[1,1,1,e.size]):2===e.rank?_i(e,[1,1,e.shape[0],e.shape[1]]):3===e.rank?_i(e,[1,e.shape[0],e.shape[1],e.shape[2]]):e,t}(r),scale:c,offset:u,mean:o,variance:l},p={varianceEpsilon:s},d=sn.runKernel(Ne,h,p);return _i(d,r.shape)}});const Vi=dn({batchNorm2d_:function(e,t,n,i,a,s){const r=hn(e,"x","batchNorm"),o=hn(t,"mean","batchNorm"),l=hn(n,"variance","batchNorm");let c,u;return null!=a&&(c=hn(a,"scale","batchNorm")),null!=i&&(u=hn(i,"offset","batchNorm")),I(2===r.rank,(()=>`Error in batchNorm2D: x must be rank 2 but got rank ${r.rank}.`)),I(2===o.rank||1===o.rank,(()=>`Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank ${o.rank}.`)),I(2===l.rank||1===l.rank,(()=>`Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank ${l.rank}.`)),null!=c&&I(2===c.rank||1===c.rank,(()=>`Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${c.rank}.`)),null!=u&&I(2===u.rank||1===u.rank,(()=>`Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank ${u.rank}.`)),Gi(r,o,l,u,c,s)}});const Ki=dn({batchNorm3d_:function(e,t,n,i,a,s){const r=hn(e,"x","batchNorm"),o=hn(t,"mean","batchNorm"),l=hn(n,"variance","batchNorm");let c,u;return null!=a&&(c=hn(a,"scale","batchNorm")),null!=i&&(u=hn(i,"offset","batchNorm")),I(3===r.rank,(()=>`Error in batchNorm3D: x must be rank 3 but got rank ${r.rank}.`)),I(3===o.rank||1===o.rank,(()=>`Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank ${o.rank}.`)),I(3===l.rank||1===l.rank,(()=>`Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank ${l.rank}.`)),null!=c&&I(3===c.rank||1===c.rank,(()=>`Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank ${c.rank}.`)),null!=u&&I(3===u.rank||1===u.rank,(()=>`Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank ${u.rank}.`)),Gi(r,o,l,u,c,s)}});const qi=dn({batchNorm4d_:function(e,t,n,i,a,s){const r=hn(e,"x","batchNorm"),o=hn(t,"mean","batchNorm"),l=hn(n,"variance","batchNorm");let c,u;return null!=a&&(c=hn(a,"scale","batchNorm")),null!=i&&(u=hn(i,"offset","batchNorm")),I(4===r.rank,(()=>`Error in batchNorm4D: x must be rank 4 but got rank ${r.rank}.`)),I(4===o.rank||1===o.rank,(()=>`Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank ${o.rank}.`)),I(4===l.rank||1===l.rank,(()=>`Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank ${l.rank}.`)),null!=c&&I(4===c.rank||1===c.rank,(()=>`Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank ${c.rank}.`)),null!=u&&I(4===u.rank||1===u.rank,(()=>`Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank ${u.rank}.`)),Gi(r,o,l,u,c,s)}});
928
+ function(e,t,n,i,a,s){null==s&&(s=.001);const r=hn(e,"x","batchNorm"),o=hn(t,"mean","batchNorm"),l=hn(n,"variance","batchNorm");let c,u;null!=a&&(c=hn(a,"scale","batchNorm")),null!=i&&(u=hn(i,"offset","batchNorm")),T(o.rank===l.rank,(()=>"Batch normalization gradient requires mean and variance to have equal ranks.")),T(null==u||o.rank===u.rank,(()=>"Batch normalization gradient requires mean and offset to have equal ranks.")),T(null==c||o.rank===c.rank,(()=>"Batch normalization gradient requires mean and scale to have equal ranks."));const h={x:function(e){let t;return t=0===e.rank||1===e.rank?_i(e,[1,1,1,e.size]):2===e.rank?_i(e,[1,1,e.shape[0],e.shape[1]]):3===e.rank?_i(e,[1,e.shape[0],e.shape[1],e.shape[2]]):e,t}(r),scale:c,offset:u,mean:o,variance:l},p={varianceEpsilon:s},d=sn.runKernel(Ne,h,p);return _i(d,r.shape)}});const Gi=dn({batchNorm2d_:function(e,t,n,i,a,s){const r=hn(e,"x","batchNorm"),o=hn(t,"mean","batchNorm"),l=hn(n,"variance","batchNorm");let c,u;return null!=a&&(c=hn(a,"scale","batchNorm")),null!=i&&(u=hn(i,"offset","batchNorm")),T(2===r.rank,(()=>`Error in batchNorm2D: x must be rank 2 but got rank ${r.rank}.`)),T(2===o.rank||1===o.rank,(()=>`Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank ${o.rank}.`)),T(2===l.rank||1===l.rank,(()=>`Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank ${l.rank}.`)),null!=c&&T(2===c.rank||1===c.rank,(()=>`Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${c.rank}.`)),null!=u&&T(2===u.rank||1===u.rank,(()=>`Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank ${u.rank}.`)),Vi(r,o,l,u,c,s)}});const Ki=dn({batchNorm3d_:function(e,t,n,i,a,s){const r=hn(e,"x","batchNorm"),o=hn(t,"mean","batchNorm"),l=hn(n,"variance","batchNorm");let c,u;return null!=a&&(c=hn(a,"scale","batchNorm")),null!=i&&(u=hn(i,"offset","batchNorm")),T(3===r.rank,(()=>`Error in batchNorm3D: x must be rank 3 but got rank ${r.rank}.`)),T(3===o.rank||1===o.rank,(()=>`Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank ${o.rank}.`)),T(3===l.rank||1===l.rank,(()=>`Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank ${l.rank}.`)),null!=c&&T(3===c.rank||1===c.rank,(()=>`Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank ${c.rank}.`)),null!=u&&T(3===u.rank||1===u.rank,(()=>`Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank ${u.rank}.`)),Vi(r,o,l,u,c,s)}});const qi=dn({batchNorm4d_:function(e,t,n,i,a,s){const r=hn(e,"x","batchNorm"),o=hn(t,"mean","batchNorm"),l=hn(n,"variance","batchNorm");let c,u;return null!=a&&(c=hn(a,"scale","batchNorm")),null!=i&&(u=hn(i,"offset","batchNorm")),T(4===r.rank,(()=>`Error in batchNorm4D: x must be rank 4 but got rank ${r.rank}.`)),T(4===o.rank||1===o.rank,(()=>`Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank ${o.rank}.`)),T(4===l.rank||1===l.rank,(()=>`Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank ${l.rank}.`)),null!=c&&T(4===c.rank||1===c.rank,(()=>`Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank ${c.rank}.`)),null!=u&&T(4===u.rank||1===u.rank,(()=>`Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank ${u.rank}.`)),Vi(r,o,l,u,c,s)}});
929
929
  /**
930
930
  * @license
931
931
  * Copyright 2020 Google LLC. All Rights Reserved.
@@ -941,7 +941,7 @@ function(e,t,n,i,a,s){null==s&&(s=.001);const r=hn(e,"x","batchNorm"),o=hn(t,"me
941
941
  * See the License for the specific language governing permissions and
942
942
  * limitations under the License.
943
943
  * =============================================================================
944
- */const Hi=dn({bincount_:function(e,t,n){const i=hn(e,"x","bincount"),a=hn(t,"weights","bincount");I("int32"===i.dtype,(()=>`Error in bincount: input dtype must be int32, but got ${i.dtype}`)),I(n>=0,(()=>`size must be non-negative, but got ${n}.`)),I(a.size===i.size||0===a.size,(()=>`Error in bincount: weights must have the same size as input or0-length, but got input shape: ${i.shape}, weights shape: ${a.shape}.`));const s={x:i,weights:a},r={size:n};return sn.runKernel("Bincount",s,r)}});
944
+ */const Hi=dn({bincount_:function(e,t,n){const i=hn(e,"x","bincount"),a=hn(t,"weights","bincount");T("int32"===i.dtype,(()=>`Error in bincount: input dtype must be int32, but got ${i.dtype}`)),T(n>=0,(()=>`size must be non-negative, but got ${n}.`)),T(a.size===i.size||0===a.size,(()=>`Error in bincount: weights must have the same size as input or0-length, but got input shape: ${i.shape}, weights shape: ${a.shape}.`));const s={x:i,weights:a},r={size:n};return sn.runKernel("Bincount",s,r)}});
945
945
  /**
946
946
  * @license
947
947
  * Copyright 2020 Google LLC. All Rights Reserved.
@@ -957,7 +957,7 @@ function(e,t,n,i,a,s){null==s&&(s=.001);const r=hn(e,"x","batchNorm"),o=hn(t,"me
957
957
  * See the License for the specific language governing permissions and
958
958
  * limitations under the License.
959
959
  * =============================================================================
960
- */const Ji=dn({broadcastTo_:function(e,t){let n=hn(e,"broadcastTo","x");const i=n.shape;if(V(t),t.length<n.rank)throw new Error(`broadcastTo(): shape.length=${t.length} < input.rank=${n.rank}.`);if(t.length>n.rank){const e=n.shape.slice();for(;e.length<t.length;)e.unshift(1);n=_i(n,e)}const a=n.shape,s=Array.from(t);for(let e=t.length-1;e>=0;e--)if(a[e]===t[e])s[e]=1;else if(1!==n.shape[e])throw new Error(`broadcastTo(): [${i}] cannot be broadcast to [${t}].`);if(0===s.map(((e,t)=>e>1?t:-1)).filter((e=>e>=0)).length)return Mi(n);const r={x:n},o={reps:s};return sn.runKernel(lt,r,o)}});
960
+ */const Ji=dn({broadcastTo_:function(e,t){let n=hn(e,"broadcastTo","x");const i=n.shape;if(G(t),t.length<n.rank)throw new Error(`broadcastTo(): shape.length=${t.length} < input.rank=${n.rank}.`);if(t.length>n.rank){const e=n.shape.slice();for(;e.length<t.length;)e.unshift(1);n=_i(n,e)}const a=n.shape,s=Array.from(t);for(let e=t.length-1;e>=0;e--)if(a[e]===t[e])s[e]=1;else if(1!==n.shape[e])throw new Error(`broadcastTo(): [${i}] cannot be broadcast to [${t}].`);if(0===s.map(((e,t)=>e>1?t:-1)).filter((e=>e>=0)).length)return Mi(n);const r={x:n},o={reps:s};return sn.runKernel(lt,r,o)}});
961
961
  /**
962
962
  * @license
963
963
  * Copyright 2020 Google Inc. All Rights Reserved.
@@ -973,7 +973,7 @@ function(e,t,n,i,a,s){null==s&&(s=.001);const r=hn(e,"x","batchNorm"),o=hn(t,"me
973
973
  * See the License for the specific language governing permissions and
974
974
  * limitations under the License.
975
975
  * =============================================================================
976
- */function Zi(e,t="float32",n){return t=t||"float32",V(e),new Ot(e,t,n)}
976
+ */function Zi(e,t="float32",n){return t=t||"float32",G(e),new Ot(e,t,n)}
977
977
  /**
978
978
  * @license
979
979
  * Copyright 2020 Google LLC. All Rights Reserved.
@@ -989,7 +989,7 @@ function(e,t,n,i,a,s){null==s&&(s=.001);const r=hn(e,"x","batchNorm"),o=hn(t,"me
989
989
  * See the License for the specific language governing permissions and
990
990
  * limitations under the License.
991
991
  * =============================================================================
992
- */function Yi(e,t,n){V(e);const i={shape:e,value:t,dtype:n};return sn.runKernel("Fill",{},i)}
992
+ */function Yi(e,t,n){G(e);const i={shape:e,value:t,dtype:n};return sn.runKernel("Fill",{},i)}
993
993
  /**
994
994
  * @license
995
995
  * Copyright 2018 Google LLC. All Rights Reserved.
@@ -1005,7 +1005,7 @@ function(e,t,n,i,a,s){null==s&&(s=.001);const r=hn(e,"x","batchNorm"),o=hn(t,"me
1005
1005
  * See the License for the specific language governing permissions and
1006
1006
  * limitations under the License.
1007
1007
  * =============================================================================
1008
- */const Qi=dn({clipByValue_:function(e,t,n){const i=hn(e,"x","clipByValue");if(I(t<=n,(()=>`Error in clip: min (${t}) must be less than or equal to max (${n}).`)),t===n)return Yi(i.shape,t,i.dtype);const a={x:i},s={clipValueMin:t,clipValueMax:n};return sn.runKernel(ue,a,s)}});const Xi=dn({concat1d_:function(e){return Oi(e,0)}});const ea=dn({concat2d_:function(e,t){return Oi(e,t)}});const ta=dn({concat3d_:function(e,t){return Oi(e,t)}});const na=dn({concat4d_:function(e,t){return Oi(e,t)}});
1008
+ */const Qi=dn({clipByValue_:function(e,t,n){const i=hn(e,"x","clipByValue");if(T(t<=n,(()=>`Error in clip: min (${t}) must be less than or equal to max (${n}).`)),t===n)return Yi(i.shape,t,i.dtype);const a={x:i},s={clipValueMin:t,clipValueMax:n};return sn.runKernel(ue,a,s)}});const Xi=dn({concat1d_:function(e){return Oi(e,0)}});const ea=dn({concat2d_:function(e,t){return Oi(e,t)}});const ta=dn({concat3d_:function(e,t){return Oi(e,t)}});const na=dn({concat4d_:function(e,t){return Oi(e,t)}});
1009
1009
  /**
1010
1010
  * @license
1011
1011
  * Copyright 2020 Google LLC. All Rights Reserved.
@@ -1021,7 +1021,7 @@ function(e,t,n,i,a,s){null==s&&(s=.001);const r=hn(e,"x","batchNorm"),o=hn(t,"me
1021
1021
  * See the License for the specific language governing permissions and
1022
1022
  * limitations under the License.
1023
1023
  * =============================================================================
1024
- */const ia=dn({conv2d_:function(e,t,n,i,a="NHWC",s=[1,1],r){const o=hn(e,"x","conv2d","float32"),l=hn(t,"filter","conv2d","float32");let c=o,u=!1;3===o.rank&&(u=!0,c=_i(o,[1,o.shape[0],o.shape[1],o.shape[2]])),I(4===c.rank,(()=>`Error in conv2d: input must be rank 4, but got rank ${c.rank}.`)),I(4===l.rank,(()=>`Error in conv2d: filter must be rank 4, but got rank ${l.rank}.`)),Fi("conv2d",i,r);const h="NHWC"===a?c.shape[3]:c.shape[1];I(h===l.shape[2],(()=>`Error in conv2d: depth of input (${h}) must match input depth for filter ${l.shape[2]}.`)),I(zi(n,s),(()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${s}'`)),I(Di(s),(()=>"Error in conv2D: Dilated rates should be larger than 0.")),I(Di(n),(()=>"Error in conv2D: Strides should be larger than 0."));const p={x:c,filter:l},d={strides:n,pad:i,dataFormat:a,dilations:s,dimRoundingMode:r},m=sn.runKernel(de,p,d);return u?_i(m,[m.shape[1],m.shape[2],m.shape[3]]):m}});const aa=dn({conv1d_:function(e,t,n,i,a="NWC",s=1,r){const o=hn(e,"x","conv1d"),l=hn(t,"filter","conv1d");let c=o,u=!1;2===o.rank&&(u=!0,c=_i(o,[1,o.shape[0],o.shape[1]])),I(3===c.rank,(()=>`Error in conv1d: input must be rank 3, but got rank ${c.rank}.`)),I(3===l.rank,(()=>`Error in conv1d: filter must be rank 3, but got rank ${l.rank}.`)),Fi("conv1d",i,r),I(c.shape[2]===l.shape[1],(()=>`Error in conv1d: depth of input (${c.shape[2]}) must match input depth for filter ${l.shape[1]}.`)),I(zi(n,s),(()=>`Error in conv1D: Either stride or dilation must be 1. Got stride ${n} and dilation '${s}'`)),I(Di(s),(()=>"Error in conv1D: Dilated rates should be larger than 0.")),I(Di(n),(()=>"Error in conv1D: Stride should be larger than 0.")),I("NWC"===a,(()=>`Error in conv1d: got dataFormat of ${a} but only NWC is currently supported.`));const h=_i(l,[1,l.shape[0],l.shape[1],l.shape[2]]),p=_i(c,[c.shape[0],1,c.shape[1],c.shape[2]]),d=ia(p,h,[1,n],i,"NHWC",[1,s],r);return _i(d,u?[d.shape[2],d.shape[3]]:[d.shape[0],d.shape[2],d.shape[3]])}});
1024
+ */const ia=dn({conv2d_:function(e,t,n,i,a="NHWC",s=[1,1],r){const o=hn(e,"x","conv2d","float32"),l=hn(t,"filter","conv2d","float32");let c=o,u=!1;3===o.rank&&(u=!0,c=_i(o,[1,o.shape[0],o.shape[1],o.shape[2]])),T(4===c.rank,(()=>`Error in conv2d: input must be rank 4, but got rank ${c.rank}.`)),T(4===l.rank,(()=>`Error in conv2d: filter must be rank 4, but got rank ${l.rank}.`)),Fi("conv2d",i,r);const h="NHWC"===a?c.shape[3]:c.shape[1];T(h===l.shape[2],(()=>`Error in conv2d: depth of input (${h}) must match input depth for filter ${l.shape[2]}.`)),T(zi(n,s),(()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${s}'`)),T(Di(s),(()=>"Error in conv2D: Dilated rates should be larger than 0.")),T(Di(n),(()=>"Error in conv2D: Strides should be larger than 0."));const p={x:c,filter:l},d={strides:n,pad:i,dataFormat:a,dilations:s,dimRoundingMode:r},m=sn.runKernel(de,p,d);return u?_i(m,[m.shape[1],m.shape[2],m.shape[3]]):m}});const aa=dn({conv1d_:function(e,t,n,i,a="NWC",s=1,r){const o=hn(e,"x","conv1d"),l=hn(t,"filter","conv1d");let c=o,u=!1;2===o.rank&&(u=!0,c=_i(o,[1,o.shape[0],o.shape[1]])),T(3===c.rank,(()=>`Error in conv1d: input must be rank 3, but got rank ${c.rank}.`)),T(3===l.rank,(()=>`Error in conv1d: filter must be rank 3, but got rank ${l.rank}.`)),Fi("conv1d",i,r),T(c.shape[2]===l.shape[1],(()=>`Error in conv1d: depth of input (${c.shape[2]}) must match input depth for filter ${l.shape[1]}.`)),T(zi(n,s),(()=>`Error in conv1D: Either stride or dilation must be 1. Got stride ${n} and dilation '${s}'`)),T(Di(s),(()=>"Error in conv1D: Dilated rates should be larger than 0.")),T(Di(n),(()=>"Error in conv1D: Stride should be larger than 0.")),T("NWC"===a,(()=>`Error in conv1d: got dataFormat of ${a} but only NWC is currently supported.`));const h=_i(l,[1,l.shape[0],l.shape[1],l.shape[2]]),p=_i(c,[c.shape[0],1,c.shape[1],c.shape[2]]),d=ia(p,h,[1,n],i,"NHWC",[1,s],r);return _i(d,u?[d.shape[2],d.shape[3]]:[d.shape[0],d.shape[2],d.shape[3]])}});
1025
1025
  /**
1026
1026
  * @license
1027
1027
  * Copyright 2020 Google LLC. All Rights Reserved.
@@ -1037,7 +1037,7 @@ function(e,t,n,i,a,s){null==s&&(s=.001);const r=hn(e,"x","batchNorm"),o=hn(t,"me
1037
1037
  * See the License for the specific language governing permissions and
1038
1038
  * limitations under the License.
1039
1039
  * =============================================================================
1040
- */const sa=dn({conv2DBackpropInput_:function(e,t,n,i,a,s="NHWC",r){I(e.length===t.rank,(()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`));let o=e,l=t,c=!1;3===t.rank&&(c=!0,l=_i(t,[1,t.shape[0],t.shape[1],t.shape[2]]),o=[1,e[0],e[1],e[2]]),I(4===o.length,(()=>`Error in conv2dDerInput: inShape must be length 4, but got length ${o.length}.`)),I(4===l.rank,(()=>`Error in conv2dDerInput: dy must be rank 4, but got rank ${l.rank}`)),I(4===n.rank,(()=>`Error in conv2dDerInput: filter must be rank 4, but got rank ${n.rank}`));const u="NHWC"===s?o[3]:o[1],h="NHWC"===s?l.shape[3]:l.shape[1];I(u===n.shape[2],(()=>`Error in conv2dDerInput: depth of input (${u}) must match input depth for filter ${n.shape[2]}.`)),I(h===n.shape[3],(()=>`Error in conv2dDerInput: depth of output (${h}) must match output depth for filter ${n.shape[3]}.`)),Fi("conv2dDerInput",a,r);const p={dy:l,filter:n},d={strides:i,pad:a,dataFormat:s,dimRoundingMode:r,inputShape:o},m=sn.runKernel(me,p,d);return c?_i(m,[m.shape[1],m.shape[2],m.shape[3]]):m}});const ra=dn({conv2dTranspose_:function(e,t,n,i,a,s){const r=hn(e,"x","conv2dTranspose"),o=hn(t,"filter","conv2dTranspose");return sa(n,r,o,i,a,"NHWC",s)}});
1040
+ */const sa=dn({conv2DBackpropInput_:function(e,t,n,i,a,s="NHWC",r){T(e.length===t.rank,(()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`));let o=e,l=t,c=!1;3===t.rank&&(c=!0,l=_i(t,[1,t.shape[0],t.shape[1],t.shape[2]]),o=[1,e[0],e[1],e[2]]),T(4===o.length,(()=>`Error in conv2dDerInput: inShape must be length 4, but got length ${o.length}.`)),T(4===l.rank,(()=>`Error in conv2dDerInput: dy must be rank 4, but got rank ${l.rank}`)),T(4===n.rank,(()=>`Error in conv2dDerInput: filter must be rank 4, but got rank ${n.rank}`));const u="NHWC"===s?o[3]:o[1],h="NHWC"===s?l.shape[3]:l.shape[1];T(u===n.shape[2],(()=>`Error in conv2dDerInput: depth of input (${u}) must match input depth for filter ${n.shape[2]}.`)),T(h===n.shape[3],(()=>`Error in conv2dDerInput: depth of output (${h}) must match output depth for filter ${n.shape[3]}.`)),Fi("conv2dDerInput",a,r);const p={dy:l,filter:n},d={strides:i,pad:a,dataFormat:s,dimRoundingMode:r,inputShape:o},m=sn.runKernel(me,p,d);return c?_i(m,[m.shape[1],m.shape[2],m.shape[3]]):m}});const ra=dn({conv2dTranspose_:function(e,t,n,i,a,s){const r=hn(e,"x","conv2dTranspose"),o=hn(t,"filter","conv2dTranspose");return sa(n,r,o,i,a,"NHWC",s)}});
1041
1041
  /**
1042
1042
  * @license
1043
1043
  * Copyright 2020 Google LLC. All Rights Reserved.
@@ -1053,7 +1053,7 @@ function(e,t,n,i,a,s){null==s&&(s=.001);const r=hn(e,"x","batchNorm"),o=hn(t,"me
1053
1053
  * See the License for the specific language governing permissions and
1054
1054
  * limitations under the License.
1055
1055
  * =============================================================================
1056
- */const oa=dn({conv3d_:function(e,t,n,i,a="NDHWC",s=[1,1,1]){const r=hn(e,"x","conv3d"),o=hn(t,"filter","conv3d");let l=r,c=!1;4===r.rank&&(c=!0,l=_i(r,[1,r.shape[0],r.shape[1],r.shape[2],r.shape[3]])),I(5===l.rank,(()=>`Error in conv3d: input must be rank 5, but got rank ${l.rank}.`)),I(5===o.rank,(()=>`Error in conv3d: filter must be rank 5, but got rank ${o.rank}.`)),I(l.shape[4]===o.shape[3],(()=>`Error in conv3d: depth of input (${l.shape[4]}) must match input depth for filter ${o.shape[3]}.`)),I(zi(n,s),(()=>`Error in conv3D: Either strides or dilations must be 1. Got strides ${n} and dilations '${s}'`)),I("NDHWC"===a,(()=>`Error in conv3d: got dataFormat of ${a} but only NDHWC is currently supported.`)),I(Di(s),(()=>"Error in conv3D: Dilated rates should be larger than 0.")),I(Di(n),(()=>"Error in conv3D: Strides should be larger than 0."));const u={x:l,filter:o},h={strides:n,pad:i,dataFormat:a,dilations:s},p=sn.runKernel(fe,u,h);return c?_i(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}});
1056
+ */const oa=dn({conv3d_:function(e,t,n,i,a="NDHWC",s=[1,1,1]){const r=hn(e,"x","conv3d"),o=hn(t,"filter","conv3d");let l=r,c=!1;4===r.rank&&(c=!0,l=_i(r,[1,r.shape[0],r.shape[1],r.shape[2],r.shape[3]])),T(5===l.rank,(()=>`Error in conv3d: input must be rank 5, but got rank ${l.rank}.`)),T(5===o.rank,(()=>`Error in conv3d: filter must be rank 5, but got rank ${o.rank}.`)),T(l.shape[4]===o.shape[3],(()=>`Error in conv3d: depth of input (${l.shape[4]}) must match input depth for filter ${o.shape[3]}.`)),T(zi(n,s),(()=>`Error in conv3D: Either strides or dilations must be 1. Got strides ${n} and dilations '${s}'`)),T("NDHWC"===a,(()=>`Error in conv3d: got dataFormat of ${a} but only NDHWC is currently supported.`)),T(Di(s),(()=>"Error in conv3D: Dilated rates should be larger than 0.")),T(Di(n),(()=>"Error in conv3D: Strides should be larger than 0."));const u={x:l,filter:o},h={strides:n,pad:i,dataFormat:a,dilations:s},p=sn.runKernel(fe,u,h);return c?_i(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}});
1057
1057
  /**
1058
1058
  * @license
1059
1059
  * Copyright 2020 Google LLC. All Rights Reserved.
@@ -1069,7 +1069,7 @@ function(e,t,n,i,a,s){null==s&&(s=.001);const r=hn(e,"x","batchNorm"),o=hn(t,"me
1069
1069
  * See the License for the specific language governing permissions and
1070
1070
  * limitations under the License.
1071
1071
  * =============================================================================
1072
- */const la=dn({conv3DBackpropInput_:function(e,t,n,i,a){I(e.length===t.rank,(()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`));let s=e,r=t,o=!1;4===t.rank&&(o=!0,r=_i(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]]),s=[1,e[0],e[1],e[2],e[3]]);const l=s[4],c=r.shape[4];I(5===s.length,(()=>`Error in conv3dDerInput: inShape must be length 5, but got length ${s.length}.`)),I(5===r.rank,(()=>`Error in conv3dDerInput: dy must be rank 5, but got rank ${r.rank}`)),I(5===n.rank,(()=>`Error in conv3dDerInput: filter must be rank 5, but got rank ${n.rank}`)),I(l===n.shape[3],(()=>`Error in conv3dDerInput: depth of input (${l}) must match input depth for filter ${n.shape[3]}.`)),I(c===n.shape[4],(()=>`Error in conv3dDerInput: depth of output (${c}) must match output depth for filter ${n.shape[4]}.`));const u={dy:r,filter:n},h={pad:a,strides:i,inputShape:s},p=sn.runKernel("Conv3DBackpropInputV2",u,h);return o?_i(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}});const ca=dn({conv3dTranspose_:function(e,t,n,i,a){const s=hn(e,"x","conv3dTranspose"),r=hn(t,"filter","conv3dTranspose");return la(n,s,r,i,a)}});
1072
+ */const la=dn({conv3DBackpropInput_:function(e,t,n,i,a){T(e.length===t.rank,(()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`));let s=e,r=t,o=!1;4===t.rank&&(o=!0,r=_i(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]]),s=[1,e[0],e[1],e[2],e[3]]);const l=s[4],c=r.shape[4];T(5===s.length,(()=>`Error in conv3dDerInput: inShape must be length 5, but got length ${s.length}.`)),T(5===r.rank,(()=>`Error in conv3dDerInput: dy must be rank 5, but got rank ${r.rank}`)),T(5===n.rank,(()=>`Error in conv3dDerInput: filter must be rank 5, but got rank ${n.rank}`)),T(l===n.shape[3],(()=>`Error in conv3dDerInput: depth of input (${l}) must match input depth for filter ${n.shape[3]}.`)),T(c===n.shape[4],(()=>`Error in conv3dDerInput: depth of output (${c}) must match output depth for filter ${n.shape[4]}.`));const u={dy:r,filter:n},h={pad:a,strides:i,inputShape:s},p=sn.runKernel("Conv3DBackpropInputV2",u,h);return o?_i(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}});const ca=dn({conv3dTranspose_:function(e,t,n,i,a){const s=hn(e,"x","conv3dTranspose"),r=hn(t,"filter","conv3dTranspose");return la(n,s,r,i,a)}});
1073
1073
  /**
1074
1074
  * @license
1075
1075
  * Copyright 2018 Google LLC. All Rights Reserved.
@@ -1149,7 +1149,7 @@ function(e,t,n,i,a,s){null==s&&(s=.001);const r=hn(e,"x","batchNorm"),o=hn(t,"me
1149
1149
  * See the License for the specific language governing permissions and
1150
1150
  * limitations under the License.
1151
1151
  * =============================================================================
1152
- */const ma=dn({denseBincount_:function(e,t,n,i=!1){const a=hn(e,"x","denseBincount"),s=hn(t,"weights","denseBincount");I("int32"===a.dtype,(()=>`Error in denseBincount: input dtype must be int32, but got ${a.dtype}`)),I(a.rank<=2,(()=>`Error in denseBincount: input must be at most rank 2, but got rank ${a.rank}.`)),I(n>=0,(()=>`size must be non-negative, but got ${n}.`)),I(s.size===a.size||0===s.size,(()=>`Error in denseBincount: weights must have the same shape as x or 0-length, but got x shape: ${a.shape}, weights shape: ${s.shape}.`));const r={x:a,weights:s},o={size:n,binaryOutput:i};return sn.runKernel("DenseBincount",r,o)}});
1152
+ */const ma=dn({denseBincount_:function(e,t,n,i=!1){const a=hn(e,"x","denseBincount"),s=hn(t,"weights","denseBincount");T("int32"===a.dtype,(()=>`Error in denseBincount: input dtype must be int32, but got ${a.dtype}`)),T(a.rank<=2,(()=>`Error in denseBincount: input must be at most rank 2, but got rank ${a.rank}.`)),T(n>=0,(()=>`size must be non-negative, but got ${n}.`)),T(s.size===a.size||0===s.size,(()=>`Error in denseBincount: weights must have the same shape as x or 0-length, but got x shape: ${a.shape}, weights shape: ${s.shape}.`));const r={x:a,weights:s},o={size:n,binaryOutput:i};return sn.runKernel("DenseBincount",r,o)}});
1153
1153
  /**
1154
1154
  * @license
1155
1155
  * Copyright 2020 Google LLC. All Rights Reserved.
@@ -1165,7 +1165,7 @@ function(e,t,n,i,a,s){null==s&&(s=.001);const r=hn(e,"x","batchNorm"),o=hn(t,"me
1165
1165
  * See the License for the specific language governing permissions and
1166
1166
  * limitations under the License.
1167
1167
  * =============================================================================
1168
- */const fa=dn({depthwiseConv2d_:function(e,t,n,i,a="NHWC",s=[1,1],r){const o=hn(e,"x","depthwiseConv2d","float32"),l=hn(t,"filter","depthwiseConv2d","float32");let c=o,u=!1;3===o.rank&&(u=!0,c=_i(o,[1,o.shape[0],o.shape[1],o.shape[2]])),I(4===c.rank,(()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${c.rank}.`)),I(4===l.rank,(()=>`Error in depthwiseConv2d: filter must be rank 4, but got rank ${l.rank}.`));const h="NHWC"===a?c.shape[3]:c.shape[1];I(h===l.shape[2],(()=>`Error in depthwiseConv2d: number of input channels (${h}) must match the inChannels dimension in filter ${l.shape[2]}.`)),Fi("depthwiseConv2d",i,r);const p={x:c,filter:l},d={strides:n,pad:i,dataFormat:a,dilations:s,dimRoundingMode:r},m=sn.runKernel(ye,p,d);return u?_i(m,[m.shape[1],m.shape[2],m.shape[3]]):m}});
1168
+ */const fa=dn({depthwiseConv2d_:function(e,t,n,i,a="NHWC",s=[1,1],r){const o=hn(e,"x","depthwiseConv2d","float32"),l=hn(t,"filter","depthwiseConv2d","float32");let c=o,u=!1;3===o.rank&&(u=!0,c=_i(o,[1,o.shape[0],o.shape[1],o.shape[2]])),T(4===c.rank,(()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${c.rank}.`)),T(4===l.rank,(()=>`Error in depthwiseConv2d: filter must be rank 4, but got rank ${l.rank}.`));const h="NHWC"===a?c.shape[3]:c.shape[1];T(h===l.shape[2],(()=>`Error in depthwiseConv2d: number of input channels (${h}) must match the inChannels dimension in filter ${l.shape[2]}.`)),Fi("depthwiseConv2d",i,r);const p={x:c,filter:l},d={strides:n,pad:i,dataFormat:a,dilations:s,dimRoundingMode:r},m=sn.runKernel(ye,p,d);return u?_i(m,[m.shape[1],m.shape[2],m.shape[3]]):m}});
1169
1169
  /**
1170
1170
  * @license
1171
1171
  * Copyright 2020 Google LLC. All Rights Reserved.
@@ -1245,7 +1245,7 @@ function(e,t,n,i,a,s){null==s&&(s=.001);const r=hn(e,"x","batchNorm"),o=hn(t,"me
1245
1245
  * See the License for the specific language governing permissions and
1246
1246
  * limitations under the License.
1247
1247
  * =============================================================================
1248
- */function wa(e,t){for(let n=0;n<e.length;++n)if(e[e.length-n-1]!==t-1-n)return!1;return!0}function ka(e,t){const n=[],i=e.length;for(let a=0;a<i;a++)-1===t.indexOf(a)&&n.push(e[a]);return[n,t.map((t=>e[t]))]}function xa(e,t){return function(e,t,n){const i=e.length+t.length,a=[];let s=0,r=0;for(let o=0;o<i;o++)-1===n.indexOf(o)?a.push(e[s++]):a.push(t[r++]);return a}(e,t.map((e=>1)),t)}function Sa(e,t){if(wa(e,t))return null;const n=[];for(let i=0;i<t;++i)-1===e.indexOf(i)&&n.push(i);return e.forEach((e=>n.push(e))),n}function Na(e){return e.map(((e,t)=>[t,e])).sort(((e,t)=>e[1]-t[1])).map((e=>e[0]))}const Ia=dn({max_:
1248
+ */function wa(e,t){for(let n=0;n<e.length;++n)if(e[e.length-n-1]!==t-1-n)return!1;return!0}function ka(e,t){const n=[],i=e.length;for(let a=0;a<i;a++)-1===t.indexOf(a)&&n.push(e[a]);return[n,t.map((t=>e[t]))]}function xa(e,t){return function(e,t,n){const i=e.length+t.length,a=[];let s=0,r=0;for(let o=0;o<i;o++)-1===n.indexOf(o)?a.push(e[s++]):a.push(t[r++]);return a}(e,t.map((e=>1)),t)}function Sa(e,t){if(wa(e,t))return null;const n=[];for(let i=0;i<t;++i)-1===e.indexOf(i)&&n.push(i);return e.forEach((e=>n.push(e))),n}function Na(e){return e.map(((e,t)=>[t,e])).sort(((e,t)=>e[1]-t[1])).map((e=>e[0]))}const Ta=dn({max_:
1249
1249
  /**
1250
1250
  * @license
1251
1251
  * Copyright 2020 Google LLC. All Rights Reserved.
@@ -1278,7 +1278,7 @@ function(e,t=null,n=!1){const i={x:hn(e,"x","max")},a={reductionIndices:t,keepDi
1278
1278
  * See the License for the specific language governing permissions and
1279
1279
  * limitations under the License.
1280
1280
  * =============================================================================
1281
- */const Ta=dn({min_:function(e,t=null,n=!1){const i={x:hn(e,"x","min")},a={axis:t,keepDims:n};return sn.runKernel("Min",i,a)}});
1281
+ */const Ia=dn({min_:function(e,t=null,n=!1){const i={x:hn(e,"x","min")},a={axis:t,keepDims:n};return sn.runKernel("Min",i,a)}});
1282
1282
  /**
1283
1283
  * @license
1284
1284
  * Copyright 2020 Google LLC. All Rights Reserved.
@@ -1294,7 +1294,7 @@ function(e,t=null,n=!1){const i={x:hn(e,"x","max")},a={reductionIndices:t,keepDi
1294
1294
  * See the License for the specific language governing permissions and
1295
1295
  * limitations under the License.
1296
1296
  * =============================================================================
1297
- */const Ea=dn({pow_:function(e,t){let n=hn(e,"base","pow"),i=hn(t,"exp","pow");[n,i]=Yt(n,i);const a={a:n,b:i};return sn.runKernel("Pow",a)}});
1297
+ */const Aa=dn({pow_:function(e,t){let n=hn(e,"base","pow"),i=hn(t,"exp","pow");[n,i]=Yt(n,i);const a={a:n,b:i};return sn.runKernel("Pow",a)}});
1298
1298
  /**
1299
1299
  * @license
1300
1300
  * Copyright 2018 Google LLC. All Rights Reserved.
@@ -1310,7 +1310,7 @@ function(e,t=null,n=!1){const i={x:hn(e,"x","max")},a={reductionIndices:t,keepDi
1310
1310
  * See the License for the specific language governing permissions and
1311
1311
  * limitations under the License.
1312
1312
  * =============================================================================
1313
- */function Aa(e,t){if((Ct(e)&&"string"!==t||Array.isArray(e))&&"complex64"!==t)throw new Error("Error creating a new Scalar: value must be a primitive (number|boolean|string)");if("string"===t&&Ct(e)&&!(e instanceof Uint8Array))throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");return fn(e,[],[],t)}
1313
+ */function Ca(e,t){if((Et(e)&&"string"!==t||Array.isArray(e))&&"complex64"!==t)throw new Error("Error creating a new Scalar: value must be a primitive (number|boolean|string)");if("string"===t&&Et(e)&&!(e instanceof Uint8Array))throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");return fn(e,[],[],t)}
1314
1314
  /**
1315
1315
  * @license
1316
1316
  * Copyright 2018 Google LLC. All Rights Reserved.
@@ -1326,7 +1326,7 @@ function(e,t=null,n=!1){const i={x:hn(e,"x","max")},a={reductionIndices:t,keepDi
1326
1326
  * See the License for the specific language governing permissions and
1327
1327
  * limitations under the License.
1328
1328
  * =============================================================================
1329
- */const Ca=dn({sqrt_:function(e){const t={x:hn(e,"x","sqrt","float32")};return sn.runKernel(tt,t)}});
1329
+ */const Ea=dn({sqrt_:function(e){const t={x:hn(e,"x","sqrt","float32")};return sn.runKernel(tt,t)}});
1330
1330
  /**
1331
1331
  * @license
1332
1332
  * Copyright 2019 Google LLC. All Rights Reserved.
@@ -1374,7 +1374,7 @@ function(e,t=null,n=!1){const i={x:hn(e,"x","max")},a={reductionIndices:t,keepDi
1374
1374
  * See the License for the specific language governing permissions and
1375
1375
  * limitations under the License.
1376
1376
  * =============================================================================
1377
- */function za(e,t,n=null){if(0===e.rank)return Si(e);if(1!==e.rank&&null===n)return za(_i(e,[-1]),t,n);if(1===e.rank||"number"==typeof n||Array.isArray(n)&&1===n.length){if(1===t)return ja(Si(e),n);if(t===1/0)return Ia(Si(e),n);if(t===-1/0)return Ta(Si(e),n);if("euclidean"===t||2===t)return Ca(ja(Ea(Si(e),Aa(2,"int32")),n));throw new Error(`Error in norm: invalid ord value: ${t}`)}if(Array.isArray(n)&&2===n.length){if(1===t)return Ia(ja(Si(e),n[0]),n[1]-1);if(t===1/0)return Ia(ja(Si(e),n[1]),n[0]);if(t===-1/0)return Ta(ja(Si(e),n[1]),n[0]);if("fro"===t||"euclidean"===t)return Ca(ja($a(e),n));throw new Error(`Error in norm: invalid ord value: ${t}`)}throw new Error(`Error in norm: invalid axis: ${n}`)}const Da=dn({norm_:function(e,t="euclidean",n=null,i=!1){const a=za(e=hn(e,"x","norm"),t,n);let s=a.shape;if(i){const t=z(n,e.shape);s=xa(a.shape,t)}return _i(a,s)}});
1377
+ */function za(e,t,n=null){if(0===e.rank)return Si(e);if(1!==e.rank&&null===n)return za(_i(e,[-1]),t,n);if(1===e.rank||"number"==typeof n||Array.isArray(n)&&1===n.length){if(1===t)return ja(Si(e),n);if(t===1/0)return Ta(Si(e),n);if(t===-1/0)return Ia(Si(e),n);if("euclidean"===t||2===t)return Ea(ja(Aa(Si(e),Ca(2,"int32")),n));throw new Error(`Error in norm: invalid ord value: ${t}`)}if(Array.isArray(n)&&2===n.length){if(1===t)return Ta(ja(Si(e),n[0]),n[1]-1);if(t===1/0)return Ta(ja(Si(e),n[1]),n[0]);if(t===-1/0)return Ia(ja(Si(e),n[1]),n[0]);if("fro"===t||"euclidean"===t)return Ea(ja($a(e),n));throw new Error(`Error in norm: invalid ord value: ${t}`)}throw new Error(`Error in norm: invalid axis: ${n}`)}const Da=dn({norm_:function(e,t="euclidean",n=null,i=!1){const a=za(e=hn(e,"x","norm"),t,n);let s=a.shape;if(i){const t=z(n,e.shape);s=xa(a.shape,t)}return _i(a,s)}});
1378
1378
  /**
1379
1379
  * @license
1380
1380
  * Copyright 2018 Google LLC. All Rights Reserved.
@@ -1406,7 +1406,7 @@ function(e,t=null,n=!1){const i={x:hn(e,"x","max")},a={reductionIndices:t,keepDi
1406
1406
  * See the License for the specific language governing permissions and
1407
1407
  * limitations under the License.
1408
1408
  * =============================================================================
1409
- */const _a=dn({expandDims_:function(e,t=0){const n=hn(e,"x","expandDims","string_or_numeric");I(t<=n.rank,(()=>"Axis must be <= rank of the tensor"));const i={input:n},a={dim:t};return sn.runKernel(ke,i,a)}});
1409
+ */const _a=dn({expandDims_:function(e,t=0){const n=hn(e,"x","expandDims","string_or_numeric");T(t<=n.rank,(()=>"Axis must be <= rank of the tensor"));const i={input:n},a={dim:t};return sn.runKernel(ke,i,a)}});
1410
1410
  /**
1411
1411
  * @license
1412
1412
  * Copyright 2020 Google LLC. All Rights Reserved.
@@ -1422,7 +1422,7 @@ function(e,t=null,n=!1){const i={x:hn(e,"x","max")},a={reductionIndices:t,keepDi
1422
1422
  * See the License for the specific language governing permissions and
1423
1423
  * limitations under the License.
1424
1424
  * =============================================================================
1425
- */const Ra=dn({tile_:function(e,t){const n=hn(e,"x","tile","string_or_numeric");I(n.rank===t.length,(()=>`Error in transpose: rank of input ${n.rank} must match length of reps ${t}.`));const i={x:n},a={reps:t};return sn.runKernel(lt,i,a)}});
1425
+ */const Ra=dn({tile_:function(e,t){const n=hn(e,"x","tile","string_or_numeric");T(n.rank===t.length,(()=>`Error in transpose: rank of input ${n.rank} must match length of reps ${t}.`));const i={x:n},a={reps:t};return sn.runKernel(lt,i,a)}});
1426
1426
  /**
1427
1427
  * @license
1428
1428
  * Copyright 2020 Google LLC. All Rights Reserved.
@@ -1470,7 +1470,7 @@ function(e,t=null,n=!1){const i={x:hn(e,"x","max")},a={reductionIndices:t,keepDi
1470
1470
  * See the License for the specific language governing permissions and
1471
1471
  * limitations under the License.
1472
1472
  * =============================================================================
1473
- */const Oa=dn({gather_:function(e,t,n=0,i=0){const a={x:hn(e,"x","gather"),indices:hn(t,"indices","gather","int32")},s={axis:n,batchDims:i};return sn.runKernel(Ie,a,s)}});
1473
+ */const Oa=dn({gather_:function(e,t,n=0,i=0){const a={x:hn(e,"x","gather"),indices:hn(t,"indices","gather","int32")},s={axis:n,batchDims:i};return sn.runKernel(Te,a,s)}});
1474
1474
  /**
1475
1475
  * @license
1476
1476
  * Copyright 2020 Google LLC. All Rights Reserved.
@@ -1502,7 +1502,7 @@ function(e,t=null,n=!1){const i={x:hn(e,"x","max")},a={reductionIndices:t,keepDi
1502
1502
  * See the License for the specific language governing permissions and
1503
1503
  * limitations under the License.
1504
1504
  * =============================================================================
1505
- */const Ba=dn({greaterEqual_:function(e,t){let n=hn(e,"a","greaterEqual","string_or_numeric"),i=hn(t,"b","greaterEqual","string_or_numeric");[n,i]=Yt(n,i),mi(n.shape,i.shape);const a={a:n,b:i};return sn.runKernel(Te,a)}});
1505
+ */const Ba=dn({greaterEqual_:function(e,t){let n=hn(e,"a","greaterEqual","string_or_numeric"),i=hn(t,"b","greaterEqual","string_or_numeric");[n,i]=Yt(n,i),mi(n.shape,i.shape);const a={a:n,b:i};return sn.runKernel(Ie,a)}});
1506
1506
  /**
1507
1507
  * @license
1508
1508
  * Copyright 2020 Google LLC. All Rights Reserved.
@@ -1518,7 +1518,7 @@ function(e,t=null,n=!1){const i={x:hn(e,"x","max")},a={reductionIndices:t,keepDi
1518
1518
  * See the License for the specific language governing permissions and
1519
1519
  * limitations under the License.
1520
1520
  * =============================================================================
1521
- */const Ua=dn({leakyRelu_:function(e,t=.2){const n={x:hn(e,"x","leakyRelu")},i={alpha:t};return sn.runKernel(Ae,n,i)}});
1521
+ */const Ua=dn({leakyRelu_:function(e,t=.2){const n={x:hn(e,"x","leakyRelu")},i={alpha:t};return sn.runKernel(Ce,n,i)}});
1522
1522
  /**
1523
1523
  * @license
1524
1524
  * Copyright 2020 Google LLC. All Rights Reserved.
@@ -1550,7 +1550,7 @@ function(e,t=null,n=!1){const i={x:hn(e,"x","max")},a={reductionIndices:t,keepDi
1550
1550
  * See the License for the specific language governing permissions and
1551
1551
  * limitations under the License.
1552
1552
  * =============================================================================
1553
- */const Ga=dn({lessEqual_:function(e,t){let n=hn(e,"a","lessEqual","string_or_numeric"),i=hn(t,"b","lessEqual","string_or_numeric");[n,i]=Yt(n,i),mi(n.shape,i.shape);const a={a:n,b:i};return sn.runKernel("LessEqual",a)}});
1553
+ */const Va=dn({lessEqual_:function(e,t){let n=hn(e,"a","lessEqual","string_or_numeric"),i=hn(t,"b","lessEqual","string_or_numeric");[n,i]=Yt(n,i),mi(n.shape,i.shape);const a={a:n,b:i};return sn.runKernel("LessEqual",a)}});
1554
1554
  /**
1555
1555
  * @license
1556
1556
  * Copyright 2018 Google LLC. All Rights Reserved.
@@ -1566,7 +1566,7 @@ function(e,t=null,n=!1){const i={x:hn(e,"x","max")},a={reductionIndices:t,keepDi
1566
1566
  * See the License for the specific language governing permissions and
1567
1567
  * limitations under the License.
1568
1568
  * =============================================================================
1569
- */const Va=dn({log_:function(e){const t={x:hn(e,"x","log","float32")};return sn.runKernel("Log",t)}});
1569
+ */const Ga=dn({log_:function(e){const t={x:hn(e,"x","log","float32")};return sn.runKernel("Log",t)}});
1570
1570
  /**
1571
1571
  * @license
1572
1572
  * Copyright 2018 Google LLC. All Rights Reserved.
@@ -1582,7 +1582,7 @@ function(e,t=null,n=!1){const i={x:hn(e,"x","max")},a={reductionIndices:t,keepDi
1582
1582
  * See the License for the specific language governing permissions and
1583
1583
  * limitations under the License.
1584
1584
  * =============================================================================
1585
- */const Ka=dn({log1p_:function(e){const t={x:hn(e,"x","log1p")};return sn.runKernel(Ce,t)}});
1585
+ */const Ka=dn({log1p_:function(e){const t={x:hn(e,"x","log1p")};return sn.runKernel(Ee,t)}});
1586
1586
  /**
1587
1587
  * @license
1588
1588
  * Copyright 2018 Google LLC. All Rights Reserved.
@@ -1646,7 +1646,7 @@ function(e,t=null,n=!1){const i={x:hn(e,"x","max")},a={reductionIndices:t,keepDi
1646
1646
  * See the License for the specific language governing permissions and
1647
1647
  * limitations under the License.
1648
1648
  * =============================================================================
1649
- */const Za=dn({logSoftmax_:function(e,t=-1){const n=hn(e,"logits","logSoftmax");if(-1===t&&(t=n.rank-1),t!==n.rank-1)throw Error(`Log Softmax along a non-last dimension is not yet supported. Logits was rank ${n.rank} and axis was ${t}`);const i=qa(((e,n)=>{const i=Ia(e,t,!0),a=Ja(e,i),s=Ja(ei(a,"float32"),Va(ja(Fa(a),t,!0)));n([s]);return{value:s,gradFunc:(e,n)=>{const[i]=n,a=Fa(i);return Ja(e,xi(ja(e,t,!0),a))}}}));return i(n)}});
1649
+ */const Za=dn({logSoftmax_:function(e,t=-1){const n=hn(e,"logits","logSoftmax");if(-1===t&&(t=n.rank-1),t!==n.rank-1)throw Error(`Log Softmax along a non-last dimension is not yet supported. Logits was rank ${n.rank} and axis was ${t}`);const i=qa(((e,n)=>{const i=Ta(e,t,!0),a=Ja(e,i),s=Ja(ei(a,"float32"),Ga(ja(Fa(a),t,!0)));n([s]);return{value:s,gradFunc:(e,n)=>{const[i]=n,a=Fa(i);return Ja(e,xi(ja(e,t,!0),a))}}}));return i(n)}});
1650
1650
  /**
1651
1651
  * @license
1652
1652
  * Copyright 2020 Google LLC. All Rights Reserved.
@@ -1711,7 +1711,7 @@ function(e,t){const n=hn(e,"a","logicalAnd","bool"),i=hn(t,"b","logicalAnd","boo
1711
1711
  * See the License for the specific language governing permissions and
1712
1712
  * limitations under the License.
1713
1713
  * =============================================================================
1714
- */const Xa=dn({maxPool_:function(e,t,n,i,a){const s=hn(e,"x","maxPool");let r=s,o=!1;3===s.rank&&(o=!0,r=_i(s,[1,s.shape[0],s.shape[1],s.shape[2]])),I(4===r.rank,(()=>`Error in maxPool: input must be rank 4 but got rank ${r.rank}.`)),I(zi(n,1),(()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${n} and dilations '1'`)),Fi("maxPool",i,a);const l={x:r},c={filterSize:t,strides:n,pad:i,dimRoundingMode:a},u=sn.runKernel(je,l,c);return o?_i(u,[u.shape[1],u.shape[2],u.shape[3]]):u}});
1714
+ */const Xa=dn({maxPool_:function(e,t,n,i,a){const s=hn(e,"x","maxPool");let r=s,o=!1;3===s.rank&&(o=!0,r=_i(s,[1,s.shape[0],s.shape[1],s.shape[2]])),T(4===r.rank,(()=>`Error in maxPool: input must be rank 4 but got rank ${r.rank}.`)),T(zi(n,1),(()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${n} and dilations '1'`)),Fi("maxPool",i,a);const l={x:r},c={filterSize:t,strides:n,pad:i,dimRoundingMode:a},u=sn.runKernel(je,l,c);return o?_i(u,[u.shape[1],u.shape[2],u.shape[3]]):u}});
1715
1715
  /**
1716
1716
  * @license
1717
1717
  * Copyright 2020 Google LLC. All Rights Reserved.
@@ -1727,7 +1727,7 @@ function(e,t){const n=hn(e,"a","logicalAnd","bool"),i=hn(t,"b","logicalAnd","boo
1727
1727
  * See the License for the specific language governing permissions and
1728
1728
  * limitations under the License.
1729
1729
  * =============================================================================
1730
- */const es=dn({maxPool3d_:function(e,t=[1,1,1],n,i,a,s="NDHWC"){const r=hn(e,"x","maxPool3d");let o=r,l=!1;4===r.rank&&(l=!0,o=_i(r,[1,r.shape[0],r.shape[1],r.shape[2],r.shape[3]])),I(5===o.rank,(()=>`Error in maxPool3d: x must be rank 5 but got rank ${o.rank}.`)),I("NDHWC"===s,(()=>`Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of ${s}`)),Fi("maxPool3d",i,a);const c={x:o},u={filterSize:t,strides:n,pad:i,dimRoundingMode:a,dataFormat:s},h=sn.runKernel(ze,c,u);return l?_i(h,[h.shape[1],h.shape[2],h.shape[3],h.shape[4]]):h}});
1730
+ */const es=dn({maxPool3d_:function(e,t=[1,1,1],n,i,a,s="NDHWC"){const r=hn(e,"x","maxPool3d");let o=r,l=!1;4===r.rank&&(l=!0,o=_i(r,[1,r.shape[0],r.shape[1],r.shape[2],r.shape[3]])),T(5===o.rank,(()=>`Error in maxPool3d: x must be rank 5 but got rank ${o.rank}.`)),T("NDHWC"===s,(()=>`Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of ${s}`)),Fi("maxPool3d",i,a);const c={x:o},u={filterSize:t,strides:n,pad:i,dimRoundingMode:a,dataFormat:s},h=sn.runKernel(ze,c,u);return l?_i(h,[h.shape[1],h.shape[2],h.shape[3],h.shape[4]]):h}});
1731
1731
  /**
1732
1732
  * @license
1733
1733
  * Copyright 2020 Google LLC. All Rights Reserved.
@@ -1775,7 +1775,7 @@ function(e,t){const n=hn(e,"a","logicalAnd","bool"),i=hn(t,"b","logicalAnd","boo
1775
1775
  * See the License for the specific language governing permissions and
1776
1776
  * limitations under the License.
1777
1777
  * =============================================================================
1778
- */function is(e,t="float32"){if(V(e),"complex64"===t){const t=is(e,"float32"),n=is(e,"float32");return mn(t,n)}const n=G(A(e),t);return sn.makeTensor(n,e,t)}
1778
+ */function is(e,t="float32"){if(G(e),"complex64"===t){const t=is(e,"float32"),n=is(e,"float32");return mn(t,n)}const n=V(C(e),t);return sn.makeTensor(n,e,t)}
1779
1779
  /**
1780
1780
  * @license
1781
1781
  * Copyright 2018 Google LLC. All Rights Reserved.
@@ -1791,7 +1791,7 @@ function(e,t){const n=hn(e,"a","logicalAnd","bool"),i=hn(t,"b","logicalAnd","boo
1791
1791
  * See the License for the specific language governing permissions and
1792
1792
  * limitations under the License.
1793
1793
  * =============================================================================
1794
- */function as(e,t="float32"){if(V(e),"complex64"===t){const t=as(e,"float32"),n=is(e,"float32");return mn(t,n)}const n=W(A(e),t);return sn.makeTensor(n,e,t)}
1794
+ */function as(e,t="float32"){if(G(e),"complex64"===t){const t=as(e,"float32"),n=is(e,"float32");return mn(t,n)}const n=W(C(e),t);return sn.makeTensor(n,e,t)}
1795
1795
  /**
1796
1796
  * @license
1797
1797
  * Copyright 2020 Google LLC. All Rights Reserved.
@@ -1887,7 +1887,7 @@ function(e,t){const n=hn(e,"a","logicalAnd","bool"),i=hn(t,"b","logicalAnd","boo
1887
1887
  * See the License for the specific language governing permissions and
1888
1888
  * limitations under the License.
1889
1889
  * =============================================================================
1890
- */const us=dn({spaceToBatchND_:function(e,t,n){const i=hn(e,"x","spaceToBatchND");I(i.rank>=1+t.length,(()=>`input rank ${i.rank} should be > than [blockShape] ${t.length}`)),I(n.length===t.length,(()=>`paddings.shape[0] ${n.length} must be equal to [blockShape] ${t.length}`)),I(i.shape.reduce(((e,i,a)=>a>0&&a<=t.length?e&&(i+n[a-1][0]+n[a-1][1])%t[a-1]==0:e),!0),(()=>`input spatial dimensions ${i.shape.slice(1)} with paddings ${n.toString()} must be divisible by blockShapes ${t.toString()}`));const a={x:i},s={blockShape:t,paddings:n};return sn.runKernel(it,a,s)}});
1890
+ */const us=dn({spaceToBatchND_:function(e,t,n){const i=hn(e,"x","spaceToBatchND");T(i.rank>=1+t.length,(()=>`input rank ${i.rank} should be > than [blockShape] ${t.length}`)),T(n.length===t.length,(()=>`paddings.shape[0] ${n.length} must be equal to [blockShape] ${t.length}`)),T(i.shape.reduce(((e,i,a)=>a>0&&a<=t.length?e&&(i+n[a-1][0]+n[a-1][1])%t[a-1]==0:e),!0),(()=>`input spatial dimensions ${i.shape.slice(1)} with paddings ${n.toString()} must be divisible by blockShapes ${t.toString()}`));const a={x:i},s={blockShape:t,paddings:n};return sn.runKernel(it,a,s)}});
1891
1891
  /**
1892
1892
  * @license
1893
1893
  * Copyright 2020 Google LLC. All Rights Reserved.
@@ -1951,7 +1951,7 @@ function(e,t){const n=hn(e,"a","logicalAnd","bool"),i=hn(t,"b","logicalAnd","boo
1951
1951
  * See the License for the specific language governing permissions and
1952
1952
  * limitations under the License.
1953
1953
  * =============================================================================
1954
- */const Ns=dn({randomNormal_:function(e,t=0,n=1,i,a){if(V(e),null!=i&&"bool"===i)throw new Error(`Unsupported data type ${i}`);const s=new xs(t,n,i,!1,a),r=Zi(e,i);for(let e=0;e<r.values.length;e++)r.values[e]=s.nextValue();return r.toTensor()}});
1954
+ */const Ns=dn({randomNormal_:function(e,t=0,n=1,i,a){if(G(e),null!=i&&"bool"===i)throw new Error(`Unsupported data type ${i}`);const s=new xs(t,n,i,!1,a),r=Zi(e,i);for(let e=0;e<r.values.length;e++)r.values[e]=s.nextValue();return r.toTensor()}});
1955
1955
  /**
1956
1956
  * @license
1957
1957
  * Copyright 2020 Google LLC. All Rights Reserved.
@@ -1967,7 +1967,7 @@ function(e,t){const n=hn(e,"a","logicalAnd","bool"),i=hn(t,"b","logicalAnd","boo
1967
1967
  * See the License for the specific language governing permissions and
1968
1968
  * limitations under the License.
1969
1969
  * =============================================================================
1970
- */const Is=dn({randomUniform_:function(e,t=0,n=1,i="float32",a){V(e);const s=Zi(e,i),r=new Ss(t,n,null,a);for(let e=0;e<s.values.length;e++)s.values[e]=r.nextValue();return s.toTensor()}});
1970
+ */const Ts=dn({randomUniform_:function(e,t=0,n=1,i="float32",a){G(e);const s=Zi(e,i),r=new Ss(t,n,null,a);for(let e=0;e<s.values.length;e++)s.values[e]=r.nextValue();return s.toTensor()}});
1971
1971
  /**
1972
1972
  * @license
1973
1973
  * Copyright 2018 Google LLC. All Rights Reserved.
@@ -1983,7 +1983,7 @@ function(e,t){const n=hn(e,"a","logicalAnd","bool"),i=hn(t,"b","logicalAnd","boo
1983
1983
  * See the License for the specific language governing permissions and
1984
1984
  * limitations under the License.
1985
1985
  * =============================================================================
1986
- */function Ts(e,t,n=1,i="float32"){if(0===n)throw new Error("Cannot have a step of zero");const a={start:e,stop:t,step:n,dtype:i};return sn.runKernel("Range",{},a)}
1986
+ */function Is(e,t,n=1,i="float32"){if(0===n)throw new Error("Cannot have a step of zero");const a={start:e,stop:t,step:n,dtype:i};return sn.runKernel("Range",{},a)}
1987
1987
  /**
1988
1988
  * @license
1989
1989
  * Copyright 2020 Google LLC. All Rights Reserved.
@@ -1999,7 +1999,7 @@ function(e,t){const n=hn(e,"a","logicalAnd","bool"),i=hn(t,"b","logicalAnd","boo
1999
1999
  * See the License for the specific language governing permissions and
2000
2000
  * limitations under the License.
2001
2001
  * =============================================================================
2002
- */const Es=dn({relu_:function(e){const t={x:hn(e,"x","relu")};return sn.runKernel(Be,t)}});
2002
+ */const As=dn({relu_:function(e){const t={x:hn(e,"x","relu")};return sn.runKernel(Be,t)}});
2003
2003
  /**
2004
2004
  * @license
2005
2005
  * Copyright 2020 Google LLC. All Rights Reserved.
@@ -2015,7 +2015,7 @@ function(e,t){const n=hn(e,"a","logicalAnd","bool"),i=hn(t,"b","logicalAnd","boo
2015
2015
  * See the License for the specific language governing permissions and
2016
2016
  * limitations under the License.
2017
2017
  * =============================================================================
2018
- */const As=dn({relu6_:function(e){const t={x:hn(e,"x","relu6")};return sn.runKernel(Ve,t)}});
2018
+ */const Cs=dn({relu6_:function(e){const t={x:hn(e,"x","relu6")};return sn.runKernel(Ge,t)}});
2019
2019
  /**
2020
2020
  * @license
2021
2021
  * Copyright 2018 Google LLC. All Rights Reserved.
@@ -2031,7 +2031,7 @@ function(e,t){const n=hn(e,"a","logicalAnd","bool"),i=hn(t,"b","logicalAnd","boo
2031
2031
  * See the License for the specific language governing permissions and
2032
2032
  * limitations under the License.
2033
2033
  * =============================================================================
2034
- */const Cs=dn({reverse_:function(e,t){const n={x:hn(e,"x","reverse")},i={dims:t};return sn.runKernel(Ke,n,i)}});
2034
+ */const Es=dn({reverse_:function(e,t){const n={x:hn(e,"x","reverse")},i={dims:t};return sn.runKernel(Ke,n,i)}});
2035
2035
  /**
2036
2036
  * @license
2037
2037
  * Copyright 2018 Google LLC. All Rights Reserved.
@@ -2079,7 +2079,7 @@ function(e,t){const n=hn(e,"a","logicalAnd","bool"),i=hn(t,"b","logicalAnd","boo
2079
2079
  * See the License for the specific language governing permissions and
2080
2080
  * limitations under the License.
2081
2081
  * =============================================================================
2082
- */const zs=dn({selu_:function(e){const t={x:hn(e,"x","selu")};return sn.runKernel(Ze,t)}});const Ds=dn({separableConv2d_:function(e,t,n,i,a,s=[1,1],r="NHWC"){const o=hn(e,"x","separableConv2d"),l=hn(t,"depthwiseFilter","separableConv2d"),c=hn(n,"pointwiseFilter","separableConv2d");let u=o,h=!1;if(3===o.rank&&(h=!0,u=_i(o,[1,o.shape[0],o.shape[1],o.shape[2]])),"NCHW"===r)throw new Error("separableConv2d currently does not support dataFormat NCHW; only NHWC is supported");I(4===u.rank,(()=>`Error in separableConv2d: input must be rank 4, but got rank ${u.rank}.`)),I(4===l.rank,(()=>`Error in separableConv2d: depthwise filter must be rank 4, but got rank ${l.rank}.`)),I(4===c.rank,(()=>`Error in separableConv2d: pointwise filter must be rank 4, but got rank ${l.rank}.`)),I(1===c.shape[0],(()=>`Error in separableConv2d: the first dimension of pointwise filter must be 1, but got ${c.shape[0]}.`)),I(1===c.shape[1],(()=>`Error in separableConv2d: the second dimension of pointwise filter must be 1, but got ${c.shape[1]}.`));const p=l.shape[2],d=l.shape[3];I(c.shape[2]===p*d,(()=>`Error in separableConv2d: the third dimension of pointwise filter must be ${p*d}, but got ${c.shape[2]}.`));const m=fa(u,l,i,a,r,s),f=ia(m,c,1,"valid",r);return h?_i(f,[f.shape[1],f.shape[2],f.shape[3]]):f}});
2082
+ */const zs=dn({selu_:function(e){const t={x:hn(e,"x","selu")};return sn.runKernel(Ze,t)}});const Ds=dn({separableConv2d_:function(e,t,n,i,a,s=[1,1],r="NHWC"){const o=hn(e,"x","separableConv2d"),l=hn(t,"depthwiseFilter","separableConv2d"),c=hn(n,"pointwiseFilter","separableConv2d");let u=o,h=!1;if(3===o.rank&&(h=!0,u=_i(o,[1,o.shape[0],o.shape[1],o.shape[2]])),"NCHW"===r)throw new Error("separableConv2d currently does not support dataFormat NCHW; only NHWC is supported");T(4===u.rank,(()=>`Error in separableConv2d: input must be rank 4, but got rank ${u.rank}.`)),T(4===l.rank,(()=>`Error in separableConv2d: depthwise filter must be rank 4, but got rank ${l.rank}.`)),T(4===c.rank,(()=>`Error in separableConv2d: pointwise filter must be rank 4, but got rank ${l.rank}.`)),T(1===c.shape[0],(()=>`Error in separableConv2d: the first dimension of pointwise filter must be 1, but got ${c.shape[0]}.`)),T(1===c.shape[1],(()=>`Error in separableConv2d: the second dimension of pointwise filter must be 1, but got ${c.shape[1]}.`));const p=l.shape[2],d=l.shape[3];T(c.shape[2]===p*d,(()=>`Error in separableConv2d: the third dimension of pointwise filter must be ${p*d}, but got ${c.shape[2]}.`));const m=fa(u,l,i,a,r,s),f=ia(m,c,1,"valid",r);return h?_i(f,[f.shape[1],f.shape[2],f.shape[3]]):f}});
2083
2083
  /**
2084
2084
  * @license
2085
2085
  * Copyright 2018 Google LLC. All Rights Reserved.
@@ -2127,7 +2127,7 @@ function(e,t){const n=hn(e,"a","logicalAnd","bool"),i=hn(t,"b","logicalAnd","boo
2127
2127
  * See the License for the specific language governing permissions and
2128
2128
  * limitations under the License.
2129
2129
  * =============================================================================
2130
- */const Rs=dn({slice1d_:function(e,t,n){const i=hn(e,"x","slice1d");return I(1===i.rank,(()=>`slice1d expects a rank-1 tensor, but got a rank-${i.rank} tensor`)),Bi(i,[t],[n])}});
2130
+ */const Rs=dn({slice1d_:function(e,t,n){const i=hn(e,"x","slice1d");return T(1===i.rank,(()=>`slice1d expects a rank-1 tensor, but got a rank-${i.rank} tensor`)),Bi(i,[t],[n])}});
2131
2131
  /**
2132
2132
  * @license
2133
2133
  * Copyright 2018 Google LLC. All Rights Reserved.
@@ -2143,7 +2143,7 @@ function(e,t){const n=hn(e,"a","logicalAnd","bool"),i=hn(t,"b","logicalAnd","boo
2143
2143
  * See the License for the specific language governing permissions and
2144
2144
  * limitations under the License.
2145
2145
  * =============================================================================
2146
- */const Ls=dn({slice2d_:function(e,t,n){const i=hn(e,"x","slice2d");return I(2===i.rank,(()=>`slice2d expects a rank-2 tensor, but got a rank-${i.rank} tensor`)),Bi(i,t,n)}});
2146
+ */const Ls=dn({slice2d_:function(e,t,n){const i=hn(e,"x","slice2d");return T(2===i.rank,(()=>`slice2d expects a rank-2 tensor, but got a rank-${i.rank} tensor`)),Bi(i,t,n)}});
2147
2147
  /**
2148
2148
  * @license
2149
2149
  * Copyright 2018 Google LLC. All Rights Reserved.
@@ -2159,7 +2159,7 @@ function(e,t){const n=hn(e,"a","logicalAnd","bool"),i=hn(t,"b","logicalAnd","boo
2159
2159
  * See the License for the specific language governing permissions and
2160
2160
  * limitations under the License.
2161
2161
  * =============================================================================
2162
- */const Ms=dn({slice3d_:function(e,t,n){const i=hn(e,"x","slice3d");return I(3===i.rank,(()=>`slice3d expects a rank-3 tensor, but got a rank-${i.rank} tensor`)),Bi(i,t,n)}});
2162
+ */const Ms=dn({slice3d_:function(e,t,n){const i=hn(e,"x","slice3d");return T(3===i.rank,(()=>`slice3d expects a rank-3 tensor, but got a rank-${i.rank} tensor`)),Bi(i,t,n)}});
2163
2163
  /**
2164
2164
  * @license
2165
2165
  * Copyright 2018 Google LLC. All Rights Reserved.
@@ -2175,7 +2175,7 @@ function(e,t){const n=hn(e,"a","logicalAnd","bool"),i=hn(t,"b","logicalAnd","boo
2175
2175
  * See the License for the specific language governing permissions and
2176
2176
  * limitations under the License.
2177
2177
  * =============================================================================
2178
- */const Os=dn({slice4d_:function(e,t,n){const i=hn(e,"x","slice4d");return I(4===i.rank,(()=>`slice4d expects a rank-4 tensor, but got a rank-${i.rank} tensor`)),Bi(i,t,n)}});
2178
+ */const Os=dn({slice4d_:function(e,t,n){const i=hn(e,"x","slice4d");return T(4===i.rank,(()=>`slice4d expects a rank-4 tensor, but got a rank-${i.rank} tensor`)),Bi(i,t,n)}});
2179
2179
  /**
2180
2180
  * @license
2181
2181
  * Copyright 2018 Google LLC. All Rights Reserved.
@@ -2273,7 +2273,7 @@ function(e,t){const n=hn(e,"x","squeeze","string_or_numeric");return _i(n,functi
2273
2273
  * See the License for the specific language governing permissions and
2274
2274
  * limitations under the License.
2275
2275
  * =============================================================================
2276
- */const Ws=dn({stack_:function(e,t=0){const n=pn(e,"tensors","stack","string_or_numeric");I(n.length>=1,(()=>"Pass at least one tensor to tf.stack")),n.length>0&&I(t<=n[0].rank,(()=>"Axis must be <= rank of the tensor"));const i=n,a={axis:t};return sn.runKernel(Me,i,a)}});
2276
+ */const Ws=dn({stack_:function(e,t=0){const n=pn(e,"tensors","stack","string_or_numeric");T(n.length>=1,(()=>"Pass at least one tensor to tf.stack")),n.length>0&&T(t<=n[0].rank,(()=>"Axis must be <= rank of the tensor"));const i=n,a={axis:t};return sn.runKernel(Me,i,a)}});
2277
2277
  /**
2278
2278
  * @license
2279
2279
  * Copyright 2018 Google LLC. All Rights Reserved.
@@ -2289,7 +2289,7 @@ function(e,t){const n=hn(e,"x","squeeze","string_or_numeric");return _i(n,functi
2289
2289
  * See the License for the specific language governing permissions and
2290
2290
  * limitations under the License.
2291
2291
  * =============================================================================
2292
- */const Gs=dn({step_:function(e,t=0){const n={x:hn(e,"x","step")},i={alpha:t};return sn.runKernel(dt,n,i)}});
2292
+ */const Vs=dn({step_:function(e,t=0){const n={x:hn(e,"x","step")},i={alpha:t};return sn.runKernel(dt,n,i)}});
2293
2293
  /**
2294
2294
  * @license
2295
2295
  * Copyright 2018 Google LLC. All Rights Reserved.
@@ -2305,7 +2305,7 @@ function(e,t){const n=hn(e,"x","squeeze","string_or_numeric");return _i(n,functi
2305
2305
  * See the License for the specific language governing permissions and
2306
2306
  * limitations under the License.
2307
2307
  * =============================================================================
2308
- */function Vs(e,t){E(e);const n=ln(e,t);if(1!==n.length)throw new Error("tensor1d() requires values to be a flat/TypedArray");return fn(e,null,n,t)}
2308
+ */function Gs(e,t){A(e);const n=ln(e,t);if(1!==n.length)throw new Error("tensor1d() requires values to be a flat/TypedArray");return fn(e,null,n,t)}
2309
2309
  /**
2310
2310
  * @license
2311
2311
  * Copyright 2018 Google LLC. All Rights Reserved.
@@ -2321,7 +2321,7 @@ function(e,t){const n=hn(e,"x","squeeze","string_or_numeric");return _i(n,functi
2321
2321
  * See the License for the specific language governing permissions and
2322
2322
  * limitations under the License.
2323
2323
  * =============================================================================
2324
- */function Ks(e,t,n){if(E(e),null!=t&&2!==t.length)throw new Error("tensor2d() requires shape to have two numbers");const i=ln(e,n);if(2!==i.length&&1!==i.length)throw new Error("tensor2d() requires values to be number[][] or flat/TypedArray");if(1===i.length&&null==t)throw new Error("tensor2d() requires shape to be provided when `values` are a flat/TypedArray");return fn(e,t,i,n)}
2324
+ */function Ks(e,t,n){if(A(e),null!=t&&2!==t.length)throw new Error("tensor2d() requires shape to have two numbers");const i=ln(e,n);if(2!==i.length&&1!==i.length)throw new Error("tensor2d() requires values to be number[][] or flat/TypedArray");if(1===i.length&&null==t)throw new Error("tensor2d() requires shape to be provided when `values` are a flat/TypedArray");return fn(e,t,i,n)}
2325
2325
  /**
2326
2326
  * @license
2327
2327
  * Copyright 2020 Google LLC. All Rights Reserved.
@@ -2337,7 +2337,7 @@ function(e,t){const n=hn(e,"x","squeeze","string_or_numeric");return _i(n,functi
2337
2337
  * See the License for the specific language governing permissions and
2338
2338
  * limitations under the License.
2339
2339
  * =============================================================================
2340
- */const qs=dn({truncatedNormal_:function(e,t=0,n=1,i,a){if(V(e),null!=i&&"bool"===i)throw new Error("Unsupported data type $ { dtype }");const s=new xs(t,n,i,!0,a),r=Zi(e,i);for(let e=0;e<r.values.length;e++)r.values[e]=s.nextValue();return r.toTensor()}});
2340
+ */const qs=dn({truncatedNormal_:function(e,t=0,n=1,i,a){if(G(e),null!=i&&"bool"===i)throw new Error("Unsupported data type $ { dtype }");const s=new xs(t,n,i,!0,a),r=Zi(e,i);for(let e=0;e<r.values.length;e++)r.values[e]=s.nextValue();return r.toTensor()}});
2341
2341
  /**
2342
2342
  * @license
2343
2343
  * Copyright 2020 Google LLC. All Rights Reserved.
@@ -2353,7 +2353,7 @@ function(e,t){const n=hn(e,"x","squeeze","string_or_numeric");return _i(n,functi
2353
2353
  * See the License for the specific language governing permissions and
2354
2354
  * limitations under the License.
2355
2355
  * =============================================================================
2356
- */const Hs=dn({unsortedSegmentSum_:function(e,t,n){const i=hn(e,"x","unsortedSegmentSum"),a=hn(t,"segmentIds","unsortedSegmentSum","int32");I($(n),(()=>"numSegments must be of dtype int"));const s={x:i,segmentIds:a},r={numSegments:n};return sn.runKernel(ht,s,r)}});
2356
+ */const Hs=dn({unsortedSegmentSum_:function(e,t,n){const i=hn(e,"x","unsortedSegmentSum"),a=hn(t,"segmentIds","unsortedSegmentSum","int32");T($(n),(()=>"numSegments must be of dtype int"));const s={x:i,segmentIds:a},r={numSegments:n};return sn.runKernel(ht,s,r)}});
2357
2357
  /**
2358
2358
  * @license
2359
2359
  * Copyright 2020 Google LLC. All Rights Reserved.
@@ -2369,7 +2369,7 @@ function(e,t){const n=hn(e,"x","squeeze","string_or_numeric");return _i(n,functi
2369
2369
  * See the License for the specific language governing permissions and
2370
2370
  * limitations under the License.
2371
2371
  * =============================================================================
2372
- */const Js=dn({unstack_:function(e,t=0){const n=hn(e,"x","unstack","string_or_numeric");I(t>=-n.shape.length&&t<n.shape.length,(()=>`Axis = ${t} is not in [-${n.shape.length}, ${n.shape.length})`));const i={value:n},a={axis:t};return sn.runKernel(ut,i,a)}});
2372
+ */const Js=dn({unstack_:function(e,t=0){const n=hn(e,"x","unstack","string_or_numeric");T(t>=-n.shape.length&&t<n.shape.length,(()=>`Axis = ${t} is not in [-${n.shape.length}, ${n.shape.length})`));const i={value:n},a={axis:t};return sn.runKernel(ut,i,a)}});
2373
2373
  /**
2374
2374
  * @license
2375
2375
  * Copyright 2018 Google LLC. All Rights Reserved.
@@ -2402,7 +2402,7 @@ function(e,t){const n=hn(e,"x","squeeze","string_or_numeric");return _i(n,functi
2402
2402
  * limitations under the License.
2403
2403
  * =============================================================================
2404
2404
  */
2405
- function(e,t,n,i){const a=hn(e,"x","dropout");if(I("float32"===a.dtype,(()=>`x has to be a floating point tensor since it's going to be scaled, but got a ${a.dtype} tensor instead.`)),I(t>=0&&t<1,(()=>`rate must be a float in the range [0, 1), but got ${t}.`)),0===t)return e instanceof Ut?a.clone():a;const s=
2405
+ function(e,t,n,i){const a=hn(e,"x","dropout");if(T("float32"===a.dtype,(()=>`x has to be a floating point tensor since it's going to be scaled, but got a ${a.dtype} tensor instead.`)),T(t>=0&&t<1,(()=>`rate must be a float in the range [0, 1), but got ${t}.`)),0===t)return e instanceof Ut?a.clone():a;const s=
2406
2406
  /**
2407
2407
  * @license
2408
2408
  * Copyright 2019 Google LLC. All Rights Reserved.
@@ -2419,7 +2419,7 @@ function(e,t,n,i){const a=hn(e,"x","dropout");if(I("float32"===a.dtype,(()=>`x h
2419
2419
  * limitations under the License.
2420
2420
  * =============================================================================
2421
2421
  */
2422
- function(e,t){if(null==t)return e.shape.slice();if(C(e.shape,t))return t;if(e.shape.length===t.length){const n=[];for(let i=0;i<e.shape.length;i++)null==t[i]&&null!=e.shape[i]?n.push(e.shape[i]):n.push(t[i]);return n}return t}(a,n),r=1-t,o=ki(Ma(bi(Is(s,0,1,"float32",i),r)),r);return xi(a,o)}});
2422
+ function(e,t){if(null==t)return e.shape.slice();if(E(e.shape,t))return t;if(e.shape.length===t.length){const n=[];for(let i=0;i<e.shape.length;i++)null==t[i]&&null!=e.shape[i]?n.push(e.shape[i]):n.push(t[i]);return n}return t}(a,n),r=1-t,o=ki(Ma(bi(Ts(s,0,1,"float32",i),r)),r);return xi(a,o)}});
2423
2423
  /**
2424
2424
  * @license
2425
2425
  * Copyright 2019 Google LLC. All Rights Reserved.
@@ -2452,7 +2452,7 @@ function(e,t){if(null==t)return e.shape.slice();if(C(e.shape,t))return t;if(e.sh
2452
2452
  * limitations under the License.
2453
2453
  * =============================================================================
2454
2454
  */
2455
- function(e,t,n,i,a,s="NHWC",r){let o=e;3===e.rank&&(o=_i(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let l=t;3===l.rank&&(l=_i(t,[1,t.shape[0],t.shape[1],t.shape[2]])),I(4===o.rank,(()=>`Error in conv2dDerFilter: input must be rank 4, but got shape ${o.shape}.`)),I(4===l.rank,(()=>`Error in conv2dDerFilter: dy must be rank 4, but got shape ${l.shape}.`)),I(4===n.length,(()=>`Error in conv2dDerFilter: filterShape must be length 4, but got ${n}.`));const c="NHWC"===s?o.shape[3]:o.shape[1],u="NHWC"===s?l.shape[3]:l.shape[1];I(c===n[2],(()=>`Error in conv2dDerFilter: depth of input ${c}) must match input depth in filter (${n[2]}.`)),I(u===n[3],(()=>`Error in conv2dDerFilter: depth of dy (${u}) must match output depth for filter (${n[3]}).`)),Fi("conv2dDerFilter",a,r);const h={x:o,dy:l},p={strides:i,pad:a,dataFormat:s,dimRoundingMode:r,filterShape:n};return sn.runKernel("Conv2DBackpropFilter",h,p)}});
2455
+ function(e,t,n,i,a,s="NHWC",r){let o=e;3===e.rank&&(o=_i(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let l=t;3===l.rank&&(l=_i(t,[1,t.shape[0],t.shape[1],t.shape[2]])),T(4===o.rank,(()=>`Error in conv2dDerFilter: input must be rank 4, but got shape ${o.shape}.`)),T(4===l.rank,(()=>`Error in conv2dDerFilter: dy must be rank 4, but got shape ${l.shape}.`)),T(4===n.length,(()=>`Error in conv2dDerFilter: filterShape must be length 4, but got ${n}.`));const c="NHWC"===s?o.shape[3]:o.shape[1],u="NHWC"===s?l.shape[3]:l.shape[1];T(c===n[2],(()=>`Error in conv2dDerFilter: depth of input ${c}) must match input depth in filter (${n[2]}.`)),T(u===n[3],(()=>`Error in conv2dDerFilter: depth of dy (${u}) must match output depth for filter (${n[3]}).`)),Fi("conv2dDerFilter",a,r);const h={x:o,dy:l},p={strides:i,pad:a,dataFormat:s,dimRoundingMode:r,filterShape:n};return sn.runKernel("Conv2DBackpropFilter",h,p)}});
2456
2456
  /**
2457
2457
  * @license
2458
2458
  * Copyright 2019 Google LLC. All Rights Reserved.
@@ -2468,7 +2468,7 @@ function(e,t,n,i,a,s="NHWC",r){let o=e;3===e.rank&&(o=_i(e,[1,e.shape[0],e.shape
2468
2468
  * See the License for the specific language governing permissions and
2469
2469
  * limitations under the License.
2470
2470
  * =============================================================================
2471
- */function Qs(e,t,n){if(null==n||"linear"===n)return e;if("relu"===n)return xi(e,Gs(t));throw new Error(`Cannot compute gradient for fused activation ${n}.`)}function Xs(e,t){let n=t;const i=di(e.shape,t.shape);return i.length>0&&(n=ja(n,i)),_i(n,e.shape)}function er(e,t,n,i){if("linear"===t)return e;if("relu"===t)return Es(e);if("elu"===t)return ba(e);if("relu6"===t)return As(e);if("prelu"===t)return hs(e,n);if("leakyrelu"===t)return Ua(e,i);if("sigmoid"===t)return Pi(e);throw new Error(`Unknown fused activation ${t}.`)}const tr=(e,t)=>!(e>0)||"linear"===t;
2471
+ */function Qs(e,t,n){if(null==n||"linear"===n)return e;if("relu"===n)return xi(e,Vs(t));throw new Error(`Cannot compute gradient for fused activation ${n}.`)}function Xs(e,t){let n=t;const i=di(e.shape,t.shape);return i.length>0&&(n=ja(n,i)),_i(n,e.shape)}function er(e,t,n,i){if("linear"===t)return e;if("relu"===t)return As(e);if("elu"===t)return ba(e);if("relu6"===t)return Cs(e);if("prelu"===t)return hs(e,n);if("leakyrelu"===t)return Ua(e,i);if("sigmoid"===t)return Pi(e);throw new Error(`Unknown fused activation ${t}.`)}const tr=(e,t)=>!(e>0)||"linear"===t;
2472
2472
  /**
2473
2473
  * @license
2474
2474
  * Copyright 2019 Google LLC. All Rights Reserved.
@@ -2484,7 +2484,7 @@ function(e,t,n,i,a,s="NHWC",r){let o=e;3===e.rank&&(o=_i(e,[1,e.shape[0],e.shape
2484
2484
  * See the License for the specific language governing permissions and
2485
2485
  * limitations under the License.
2486
2486
  * =============================================================================
2487
- */const nr=dn({fusedConv2d_:function({x:e,filter:t,strides:n,pad:i,dataFormat:a="NHWC",dilations:s=[1,1],dimRoundingMode:r,bias:o,activation:l="linear",preluActivationWeights:c,leakyreluAlpha:u}){if(l=l||"linear",!1===tr(sn.state.gradientDepth,l)){I("NHWC"===a,(()=>`Error in fused conv2d: got dataFormat of ${a} but only NHWC is currently supported for the case of gradient depth is 0 and the activation is not linear.`));let h=ia(e,t,n,i,a,s,r);return null!=o&&(h=bi(h,o)),er(h,l,c,u)}const h=hn(e,"x","conv2d","float32"),p=hn(t,"filter","conv2d","float32");let d=h,m=!1;3===h.rank&&(m=!0,d=_i(h,[1,h.shape[0],h.shape[1],h.shape[2]])),I(4===d.rank,(()=>`Error in fused conv2d: input must be rank 4, but got rank ${d.rank}.`)),I(4===p.rank,(()=>`Error in fused conv2d: filter must be rank 4, but got rank ${p.rank}.`)),Fi("fused conv2d",i,r);const f="NHWC"===a?d.shape[3]:d.shape[1];I(p.shape[2]===f,(()=>`Error in conv2d: depth of input (${f}) must match input depth for filter ${p.shape[2]}.`)),I(zi(n,s),(()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${s}'`));const g=Ei(d.shape,p.shape,n,s,i,r);let v,y;if(null!=o&&(v=hn(o,"bias","fused conv2d"),[v]=Yt(v,h),"NHWC"===a?mi(g.outShape,v.shape):(I(v.shape.length<=1,(()=>`Error in fused conv2d: only supports scalar or 1-D Tensor bias for NCHW format but got the bias of rank-${v.shape.length}.`)),I(0===v.shape.length||v.shape[0]===g.outChannels||1===v.shape[0],(()=>`Error in fused conv2d: bias shape (${v.shape}) is not compatible with the number of output channels (${g.outChannels})`)))),null!=c){const e=c.shape;if(I(e.length<=1||3===e.length,(()=>`Error in fused conv2d: only supports scalar, 1-D Tensor or 3-D Tensor PReLU activation weights but got a tensor of rank-${e.length}.`)),1===e.length)I(1===e[0]||e[0]===g.outChannels,(()=>`Error in fused conv2d: PReLU activation weights (${e}) is not compatible with the number of output channels (${g.outChannels}).`));else if(3===e.length)try{mi(e,g.outShape)}catch(t){const n=`Error in fused conv2d: PReLU activation weights (${e}) is not compatible with the output shape of the conv2d (${g.outShape}).`;throw Error(n)}y=hn(c,"prelu weights","fused conv2d")}const b=(e,t)=>{I("NHWC"===a,(()=>`Error in gradient of fused conv2D: got dataFormat of ${a} but only NHWC is currently supported.`));const[r,o,c,u]=t,h=Qs(e,c,l);I(ji(s),(()=>`Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${s}'`));const p=[sa(o.shape,h,r,n,i),Ys(o,h,r.shape,n,i)];if(null!=u){const e=Xs(u,h);p.push(e)}return p},w={x:d,filter:p,bias:v,preluActivationWeights:y},k={strides:n,pad:i,dataFormat:a,dilations:s,dimRoundingMode:r,activation:l,leakyreluAlpha:u};if(null==o){const e=qa(((e,t,n)=>{let i=sn.runKernel(ft,w,k);return n([t,e,i]),m&&(i=_i(i,[i.shape[1],i.shape[2],i.shape[3]])),{value:i,gradFunc:b}}));return e(d,p)}{const e=qa(((e,t,n,i)=>{let a=sn.runKernel(ft,w,k);return i([t,e,a,n]),m&&(a=_i(a,[a.shape[1],a.shape[2],a.shape[3]])),{value:a,gradFunc:b}}));return e(d,p,v)}}});
2487
+ */const nr=dn({fusedConv2d_:function({x:e,filter:t,strides:n,pad:i,dataFormat:a="NHWC",dilations:s=[1,1],dimRoundingMode:r,bias:o,activation:l="linear",preluActivationWeights:c,leakyreluAlpha:u}){if(l=l||"linear",!1===tr(sn.state.gradientDepth,l)){T("NHWC"===a,(()=>`Error in fused conv2d: got dataFormat of ${a} but only NHWC is currently supported for the case of gradient depth is 0 and the activation is not linear.`));let h=ia(e,t,n,i,a,s,r);return null!=o&&(h=bi(h,o)),er(h,l,c,u)}const h=hn(e,"x","conv2d","float32"),p=hn(t,"filter","conv2d","float32");let d=h,m=!1;3===h.rank&&(m=!0,d=_i(h,[1,h.shape[0],h.shape[1],h.shape[2]])),T(4===d.rank,(()=>`Error in fused conv2d: input must be rank 4, but got rank ${d.rank}.`)),T(4===p.rank,(()=>`Error in fused conv2d: filter must be rank 4, but got rank ${p.rank}.`)),Fi("fused conv2d",i,r);const f="NHWC"===a?d.shape[3]:d.shape[1];T(p.shape[2]===f,(()=>`Error in conv2d: depth of input (${f}) must match input depth for filter ${p.shape[2]}.`)),T(zi(n,s),(()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${s}'`));const g=Ai(d.shape,p.shape,n,s,i,r);let v,y;if(null!=o&&(v=hn(o,"bias","fused conv2d"),[v]=Yt(v,h),"NHWC"===a?mi(g.outShape,v.shape):(T(v.shape.length<=1,(()=>`Error in fused conv2d: only supports scalar or 1-D Tensor bias for NCHW format but got the bias of rank-${v.shape.length}.`)),T(0===v.shape.length||v.shape[0]===g.outChannels||1===v.shape[0],(()=>`Error in fused conv2d: bias shape (${v.shape}) is not compatible with the number of output channels (${g.outChannels})`)))),null!=c){const e=c.shape;if(T(e.length<=1||3===e.length,(()=>`Error in fused conv2d: only supports scalar, 1-D Tensor or 3-D Tensor PReLU activation weights but got a tensor of rank-${e.length}.`)),1===e.length)T(1===e[0]||e[0]===g.outChannels,(()=>`Error in fused conv2d: PReLU activation weights (${e}) is not compatible with the number of output channels (${g.outChannels}).`));else if(3===e.length)try{mi(e,g.outShape)}catch(t){const n=`Error in fused conv2d: PReLU activation weights (${e}) is not compatible with the output shape of the conv2d (${g.outShape}).`;throw Error(n)}y=hn(c,"prelu weights","fused conv2d")}const b=(e,t)=>{T("NHWC"===a,(()=>`Error in gradient of fused conv2D: got dataFormat of ${a} but only NHWC is currently supported.`));const[r,o,c,u]=t,h=Qs(e,c,l);T(ji(s),(()=>`Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${s}'`));const p=[sa(o.shape,h,r,n,i),Ys(o,h,r.shape,n,i)];if(null!=u){const e=Xs(u,h);p.push(e)}return p},w={x:d,filter:p,bias:v,preluActivationWeights:y},k={strides:n,pad:i,dataFormat:a,dilations:s,dimRoundingMode:r,activation:l,leakyreluAlpha:u};if(null==o){const e=qa(((e,t,n)=>{let i=sn.runKernel(ft,w,k);return n([t,e,i]),m&&(i=_i(i,[i.shape[1],i.shape[2],i.shape[3]])),{value:i,gradFunc:b}}));return e(d,p)}{const e=qa(((e,t,n,i)=>{let a=sn.runKernel(ft,w,k);return i([t,e,a,n]),m&&(a=_i(a,[a.shape[1],a.shape[2],a.shape[3]])),{value:a,gradFunc:b}}));return e(d,p,v)}}});
2488
2488
  /**
2489
2489
  * @license
2490
2490
  * Copyright 2020 Google LLC. All Rights Reserved.
@@ -2532,7 +2532,7 @@ function(e,t,n,i,a,s="NHWC",r){let o=e;3===e.rank&&(o=_i(e,[1,e.shape[0],e.shape
2532
2532
  * See the License for the specific language governing permissions and
2533
2533
  * limitations under the License.
2534
2534
  * =============================================================================
2535
- */const sr=dn({fusedMatMul_:function({a:e,b:t,transposeA:n=!1,transposeB:i=!1,bias:a,activation:s="linear",preluActivationWeights:r,leakyreluAlpha:o=.2}){if(!1===tr(sn.state.gradientDepth,s)){let l=ti(e,t,n,i);return null!=a&&(l=bi(l,a)),er(l,s,r,o)}let l=hn(e,"a","fused matMul"),c=hn(t,"b","fused matMul");[l,c]=Yt(l,c);const u=n?l.shape[l.rank-2]:l.shape[l.rank-1],h=i?c.shape[c.rank-1]:c.shape[c.rank-2],p=n?l.shape[l.rank-1]:l.shape[l.rank-2],d=i?c.shape[c.rank-2]:c.shape[c.rank-1],m=l.shape.slice(0,-2),f=c.shape.slice(0,-2),g=A(m),v=A(f);I(u===h,(()=>`Error in fused matMul: inner shapes (${u}) and (${h}) of Tensors with shapes ${l.shape} and ${c.shape} and transposeA=${n} and transposeB=${i} must match.`));const y=mi(l.shape.slice(0,-2),c.shape.slice(0,-2)).concat([p,d]),b=_i(l,n?[g,u,p]:[g,p,u]),w=_i(c,i?[v,d,h]:[v,h,d]);let k,x;null!=a&&(k=hn(a,"bias","fused matMul"),[k]=Yt(k,l),mi(y,k.shape)),null!=r&&(x=hn(r,"prelu weights","fused matMul"));const S=(e,t)=>{const[r,o,l,c]=t,u=Qs(_i(e,l.shape),l,s);let h,p;if(n||i?!n&&i?(h=ti(u,o,!1,!1),p=ti(u,r,!0,!1)):n&&!i?(h=ti(o,u,!1,!0),p=ti(r,u,!1,!1)):(h=ti(o,u,!0,!0),p=ti(u,r,!0,!0)):(h=ti(u,o,!1,!0),p=ti(r,u,!0,!1)),null!=a){return[h,p,Xs(c,u)]}return[h,p]},N={a:b,b:w,bias:k,preluActivationWeights:x},T={transposeA:n,transposeB:i,activation:s,leakyreluAlpha:o};if(null==a){const e=qa(((e,t,n)=>{const i=sn.runKernel(mt,N,T);return n([e,t,i]),{value:_i(i,y),gradFunc:S}}));return e(b,w)}{const e=qa(((e,t,n,i)=>{const a=sn.runKernel(mt,N,T);return i([e,t,a,n]),{value:_i(a,y),gradFunc:S}}));return e(b,w,k)}}});
2535
+ */const sr=dn({fusedMatMul_:function({a:e,b:t,transposeA:n=!1,transposeB:i=!1,bias:a,activation:s="linear",preluActivationWeights:r,leakyreluAlpha:o=.2}){if(!1===tr(sn.state.gradientDepth,s)){let l=ti(e,t,n,i);return null!=a&&(l=bi(l,a)),er(l,s,r,o)}let l=hn(e,"a","fused matMul"),c=hn(t,"b","fused matMul");[l,c]=Yt(l,c);const u=n?l.shape[l.rank-2]:l.shape[l.rank-1],h=i?c.shape[c.rank-1]:c.shape[c.rank-2],p=n?l.shape[l.rank-1]:l.shape[l.rank-2],d=i?c.shape[c.rank-2]:c.shape[c.rank-1],m=l.shape.slice(0,-2),f=c.shape.slice(0,-2),g=C(m),v=C(f);T(u===h,(()=>`Error in fused matMul: inner shapes (${u}) and (${h}) of Tensors with shapes ${l.shape} and ${c.shape} and transposeA=${n} and transposeB=${i} must match.`));const y=mi(l.shape.slice(0,-2),c.shape.slice(0,-2)).concat([p,d]),b=_i(l,n?[g,u,p]:[g,p,u]),w=_i(c,i?[v,d,h]:[v,h,d]);let k,x;null!=a&&(k=hn(a,"bias","fused matMul"),[k]=Yt(k,l),mi(y,k.shape)),null!=r&&(x=hn(r,"prelu weights","fused matMul"));const S=(e,t)=>{const[r,o,l,c]=t,u=Qs(_i(e,l.shape),l,s);let h,p;if(n||i?!n&&i?(h=ti(u,o,!1,!1),p=ti(u,r,!0,!1)):n&&!i?(h=ti(o,u,!1,!0),p=ti(r,u,!1,!1)):(h=ti(o,u,!0,!0),p=ti(u,r,!0,!0)):(h=ti(u,o,!1,!0),p=ti(r,u,!0,!1)),null!=a){return[h,p,Xs(c,u)]}return[h,p]},N={a:b,b:w,bias:k,preluActivationWeights:x},I={transposeA:n,transposeB:i,activation:s,leakyreluAlpha:o};if(null==a){const e=qa(((e,t,n)=>{const i=sn.runKernel(mt,N,I);return n([e,t,i]),{value:_i(i,y),gradFunc:S}}));return e(b,w)}{const e=qa(((e,t,n,i)=>{const a=sn.runKernel(mt,N,I);return i([e,t,a,n]),{value:_i(a,y),gradFunc:S}}));return e(b,w,k)}}});
2536
2536
  /**
2537
2537
  * @license
2538
2538
  * Copyright 2019 Google LLC. All Rights Reserved.
@@ -2565,7 +2565,7 @@ function(e,t,n,i,a,s="NHWC",r){let o=e;3===e.rank&&(o=_i(e,[1,e.shape[0],e.shape
2565
2565
  * limitations under the License.
2566
2566
  * =============================================================================
2567
2567
  */
2568
- function(e,t,n,i,a="bilinear",s=0){const r=hn(e,"image","cropAndResize"),o=hn(t,"boxes","cropAndResize","float32"),l=hn(n,"boxInd","cropAndResize","int32"),c=o.shape[0];I(4===r.rank,(()=>`Error in cropAndResize: image must be rank 4,but got rank ${r.rank}.`)),I(2===o.rank&&4===o.shape[1],(()=>`Error in cropAndResize: boxes must be have size [${c},4] but had shape ${o.shape}.`)),I(1===l.rank&&l.shape[0]===c,(()=>`Error in cropAndResize: boxInd must be have size [${c}] but had shape ${o.shape}.`)),I(2===i.length,(()=>`Error in cropAndResize: cropSize must be of length 2, but got length ${i.length}.`)),I(i[0]>=1&&i[1]>=1,(()=>`cropSize must be atleast [1,1], but was ${i}`)),I("bilinear"===a||"nearest"===a,(()=>`method must be bilinear or nearest, but was ${a}`));const u={image:r,boxes:o,boxInd:l},h={method:a,extrapolationValue:s,cropSize:i};return sn.runKernel("CropAndResize",u,h)}});
2568
+ function(e,t,n,i,a="bilinear",s=0){const r=hn(e,"image","cropAndResize"),o=hn(t,"boxes","cropAndResize","float32"),l=hn(n,"boxInd","cropAndResize","int32"),c=o.shape[0];T(4===r.rank,(()=>`Error in cropAndResize: image must be rank 4,but got rank ${r.rank}.`)),T(2===o.rank&&4===o.shape[1],(()=>`Error in cropAndResize: boxes must be have size [${c},4] but had shape ${o.shape}.`)),T(1===l.rank&&l.shape[0]===c,(()=>`Error in cropAndResize: boxInd must be have size [${c}] but had shape ${o.shape}.`)),T(2===i.length,(()=>`Error in cropAndResize: cropSize must be of length 2, but got length ${i.length}.`)),T(i[0]>=1&&i[1]>=1,(()=>`cropSize must be atleast [1,1], but was ${i}`)),T("bilinear"===a||"nearest"===a,(()=>`method must be bilinear or nearest, but was ${a}`));const u={image:r,boxes:o,boxInd:l},h={method:a,extrapolationValue:s,cropSize:i};return sn.runKernel("CropAndResize",u,h)}});
2569
2569
  /**
2570
2570
  * @license
2571
2571
  * Copyright 2020 Google LLC. All Rights Reserved.
@@ -2581,7 +2581,7 @@ function(e,t,n,i,a="bilinear",s=0){const r=hn(e,"image","cropAndResize"),o=hn(t,
2581
2581
  * See the License for the specific language governing permissions and
2582
2582
  * limitations under the License.
2583
2583
  * =============================================================================
2584
- */const or=dn({flipLeftRight_:function(e){const t=hn(e,"image","flipLeftRight","float32");I(4===t.rank,(()=>`Error in flipLeftRight: image must be rank 4,but got rank ${t.rank}.`));const n={image:t};return sn.runKernel("FlipLeftRight",n,{})}});
2584
+ */const or=dn({flipLeftRight_:function(e){const t=hn(e,"image","flipLeftRight","float32");T(4===t.rank,(()=>`Error in flipLeftRight: image must be rank 4,but got rank ${t.rank}.`));const n={image:t};return sn.runKernel("FlipLeftRight",n,{})}});
2585
2585
  /**
2586
2586
  * @license
2587
2587
  * Copyright 2021 Google LLC. All Rights Reserved.
@@ -2597,7 +2597,7 @@ function(e,t,n,i,a="bilinear",s=0){const r=hn(e,"image","cropAndResize"),o=hn(t,
2597
2597
  * See the License for the specific language governing permissions and
2598
2598
  * limitations under the License.
2599
2599
  * =============================================================================
2600
- */const lr=dn({grayscaleToRGB_:function(e){const t=hn(e,"image","grayscaleToRGB"),n=t.rank-1,i=t.shape[n];I(t.rank>=2,(()=>`Error in grayscaleToRGB: images must be at least rank 2, but got rank ${t.rank}.`)),I(1===i,(()=>`Error in grayscaleToRGB: last dimension of a grayscale image should be size 1, but got size ${i}.`));const a=new Array(t.rank);return a.fill(1,0,n),a[n]=3,Ra(t,a)}});
2600
+ */const lr=dn({grayscaleToRGB_:function(e){const t=hn(e,"image","grayscaleToRGB"),n=t.rank-1,i=t.shape[n];T(t.rank>=2,(()=>`Error in grayscaleToRGB: images must be at least rank 2, but got rank ${t.rank}.`)),T(1===i,(()=>`Error in grayscaleToRGB: last dimension of a grayscale image should be size 1, but got size ${i}.`));const a=new Array(t.rank);return a.fill(1,0,n),a[n]=3,Ra(t,a)}});
2601
2601
  /**
2602
2602
  * @license
2603
2603
  * Copyright 2020 Google LLC. All Rights Reserved.
@@ -2613,7 +2613,7 @@ function(e,t,n,i,a="bilinear",s=0){const r=hn(e,"image","cropAndResize"),o=hn(t,
2613
2613
  * See the License for the specific language governing permissions and
2614
2614
  * limitations under the License.
2615
2615
  * =============================================================================
2616
- */const cr=dn({rotateWithOffset_:function(e,t,n=0,i=.5){const a=hn(e,"image","rotateWithOffset","float32");I(4===a.rank,(()=>`Error in rotateWithOffset: image must be rank 4,but got rank ${a.rank}.`));const s={image:a},r={radians:t,fillValue:n,center:i};return sn.runKernel("RotateWithOffset",s,r)}});
2616
+ */const cr=dn({rotateWithOffset_:function(e,t,n=0,i=.5){const a=hn(e,"image","rotateWithOffset","float32");T(4===a.rank,(()=>`Error in rotateWithOffset: image must be rank 4,but got rank ${a.rank}.`));const s={image:a},r={radians:t,fillValue:n,center:i};return sn.runKernel("RotateWithOffset",s,r)}});
2617
2617
  /**
2618
2618
  * @license
2619
2619
  * Copyright 2020 Google LLC. All Rights Reserved.
@@ -2629,7 +2629,7 @@ function(e,t,n,i,a="bilinear",s=0){const r=hn(e,"image","cropAndResize"),o=hn(t,
2629
2629
  * See the License for the specific language governing permissions and
2630
2630
  * limitations under the License.
2631
2631
  * =============================================================================
2632
- */function ur(e,t,n,i,a,s){null==i&&(i=.5),null==a&&(a=Number.NEGATIVE_INFINITY),null==s&&(s=0);const r=e.shape[0];return n=Math.min(n,r),I(0<=i&&i<=1,(()=>`iouThreshold must be in [0, 1], but was '${i}'`)),I(2===e.rank,(()=>`boxes must be a 2D tensor, but was of rank '${e.rank}'`)),I(4===e.shape[1],(()=>`boxes must have 4 columns, but 2nd dimension was ${e.shape[1]}`)),I(1===t.rank,(()=>"scores must be a 1D tensor")),I(t.shape[0]===r,(()=>`scores has incompatible shape with boxes. Expected ${r}, but was ${t.shape[0]}`)),I(0<=s&&s<=1,(()=>`softNmsSigma must be in [0, 1], but was '${s}'`)),{maxOutputSize:n,iouThreshold:i,scoreThreshold:a,softNmsSigma:s}}
2632
+ */function ur(e,t,n,i,a,s){null==i&&(i=.5),null==a&&(a=Number.NEGATIVE_INFINITY),null==s&&(s=0);const r=e.shape[0];return n=Math.min(n,r),T(0<=i&&i<=1,(()=>`iouThreshold must be in [0, 1], but was '${i}'`)),T(2===e.rank,(()=>`boxes must be a 2D tensor, but was of rank '${e.rank}'`)),T(4===e.shape[1],(()=>`boxes must have 4 columns, but 2nd dimension was ${e.shape[1]}`)),T(1===t.rank,(()=>"scores must be a 1D tensor")),T(t.shape[0]===r,(()=>`scores has incompatible shape with boxes. Expected ${r}, but was ${t.shape[0]}`)),T(0<=s&&s<=1,(()=>`softNmsSigma must be in [0, 1], but was '${s}'`)),{maxOutputSize:n,iouThreshold:i,scoreThreshold:a,softNmsSigma:s}}
2633
2633
  /**
2634
2634
  * @license
2635
2635
  * Copyright 2020 Google LLC. All Rights Reserved.
@@ -2693,7 +2693,7 @@ function(e,t,n,i,a="bilinear",s=0){const r=hn(e,"image","cropAndResize"),o=hn(t,
2693
2693
  * See the License for the specific language governing permissions and
2694
2694
  * limitations under the License.
2695
2695
  * =============================================================================
2696
- */const yr=async function(e,t,n,i=.5,a=Number.NEGATIVE_INFINITY){const s=hn(e,"boxes","nonMaxSuppressionAsync"),r=hn(t,"scores","nonMaxSuppressionAsync"),o=ur(s,r,n,i,a);n=o.maxOutputSize,i=o.iouThreshold,a=o.scoreThreshold;const l=await Promise.all([s.data(),r.data()]),c=l[0],u=l[1],{selectedIndices:h}=function(e,t,n,i,a){return mr(e,t,n,i,a,0)}(c,u,n,i,a);return s!==e&&s.dispose(),r!==t&&r.dispose(),Vs(h,"int32")};
2696
+ */const yr=async function(e,t,n,i=.5,a=Number.NEGATIVE_INFINITY){const s=hn(e,"boxes","nonMaxSuppressionAsync"),r=hn(t,"scores","nonMaxSuppressionAsync"),o=ur(s,r,n,i,a);n=o.maxOutputSize,i=o.iouThreshold,a=o.scoreThreshold;const l=await Promise.all([s.data(),r.data()]),c=l[0],u=l[1],{selectedIndices:h}=function(e,t,n,i,a){return mr(e,t,n,i,a,0)}(c,u,n,i,a);return s!==e&&s.dispose(),r!==t&&r.dispose(),Gs(h,"int32")};
2697
2697
  /**
2698
2698
  * @license
2699
2699
  * Copyright 2020 Google LLC. All Rights Reserved.
@@ -2725,7 +2725,7 @@ function(e,t,n,i,a="bilinear",s=0){const r=hn(e,"image","cropAndResize"),o=hn(t,
2725
2725
  * See the License for the specific language governing permissions and
2726
2726
  * limitations under the License.
2727
2727
  * =============================================================================
2728
- */const wr=async function(e,t,n,i=.5,a=Number.NEGATIVE_INFINITY,s=0){const r=hn(e,"boxes","nonMaxSuppressionAsync"),o=hn(t,"scores","nonMaxSuppressionAsync"),l=ur(r,o,n,i,a,s);n=l.maxOutputSize,i=l.iouThreshold,a=l.scoreThreshold,s=l.softNmsSigma;const c=await Promise.all([r.data(),o.data()]),u=c[0],h=c[1],{selectedIndices:p,selectedScores:d}=function(e,t,n,i,a,s){return mr(e,t,n,i,a,s,!0)}(u,h,n,i,a,s);return r!==e&&r.dispose(),o!==t&&o.dispose(),{selectedIndices:Vs(p,"int32"),selectedScores:Vs(d)}};
2728
+ */const wr=async function(e,t,n,i=.5,a=Number.NEGATIVE_INFINITY,s=0){const r=hn(e,"boxes","nonMaxSuppressionAsync"),o=hn(t,"scores","nonMaxSuppressionAsync"),l=ur(r,o,n,i,a,s);n=l.maxOutputSize,i=l.iouThreshold,a=l.scoreThreshold,s=l.softNmsSigma;const c=await Promise.all([r.data(),o.data()]),u=c[0],h=c[1],{selectedIndices:p,selectedScores:d}=function(e,t,n,i,a,s){return mr(e,t,n,i,a,s,!0)}(u,h,n,i,a,s);return r!==e&&r.dispose(),o!==t&&o.dispose(),{selectedIndices:Gs(p,"int32"),selectedScores:Gs(d)}};
2729
2729
  /**
2730
2730
  * @license
2731
2731
  * Copyright 2020 Google LLC. All Rights Reserved.
@@ -2757,7 +2757,7 @@ function(e,t,n,i,a="bilinear",s=0){const r=hn(e,"image","cropAndResize"),o=hn(t,
2757
2757
  * See the License for the specific language governing permissions and
2758
2758
  * limitations under the License.
2759
2759
  * =============================================================================
2760
- */const xr=async function(e,t,n,i=.5,a=Number.NEGATIVE_INFINITY,s=!1){const r=hn(e,"boxes","nonMaxSuppressionAsync"),o=hn(t,"scores","nonMaxSuppressionAsync"),l=ur(r,o,n,i,a,null),c=l.maxOutputSize,u=l.iouThreshold,h=l.scoreThreshold,[p,d]=await Promise.all([r.data(),o.data()]),{selectedIndices:m,validOutputs:f}=function(e,t,n,i,a,s){return mr(e,t,n,i,a,0,!1,s,!0)}(p,d,c,u,h,s);return r!==e&&r.dispose(),o!==t&&o.dispose(),{selectedIndices:Vs(m,"int32"),validOutputs:Aa(f,"int32")}};
2760
+ */const xr=async function(e,t,n,i=.5,a=Number.NEGATIVE_INFINITY,s=!1){const r=hn(e,"boxes","nonMaxSuppressionAsync"),o=hn(t,"scores","nonMaxSuppressionAsync"),l=ur(r,o,n,i,a,null),c=l.maxOutputSize,u=l.iouThreshold,h=l.scoreThreshold,[p,d]=await Promise.all([r.data(),o.data()]),{selectedIndices:m,validOutputs:f}=function(e,t,n,i,a,s){return mr(e,t,n,i,a,0,!1,s,!0)}(p,d,c,u,h,s);return r!==e&&r.dispose(),o!==t&&o.dispose(),{selectedIndices:Gs(m,"int32"),validOutputs:Ca(f,"int32")}};
2761
2761
  /**
2762
2762
  * @license
2763
2763
  * Copyright 2020 Google LLC. All Rights Reserved.
@@ -2773,7 +2773,7 @@ function(e,t,n,i,a="bilinear",s=0){const r=hn(e,"image","cropAndResize"),o=hn(t,
2773
2773
  * See the License for the specific language governing permissions and
2774
2774
  * limitations under the License.
2775
2775
  * =============================================================================
2776
- */const Sr=dn({resizeBilinear_:function(e,t,n=!1,i=!1){const a=hn(e,"images","resizeBilinear");I(3===a.rank||4===a.rank,(()=>`Error in resizeBilinear: x must be rank 3 or 4, but got rank ${a.rank}.`)),I(2===t.length,(()=>`Error in resizeBilinear: new shape must 2D, but got shape ${t}.`)),I(!1===i||!1===n,(()=>"Error in resizeBilinear: If halfPixelCenters is true, alignCorners must be false."));let s=a,r=!1;3===a.rank&&(r=!0,s=_i(a,[1,a.shape[0],a.shape[1],a.shape[2]]));const o={images:s},l={alignCorners:n,halfPixelCenters:i,size:t},c=sn.runKernel(Ge,o,l);return r?_i(c,[c.shape[1],c.shape[2],c.shape[3]]):c}});
2776
+ */const Sr=dn({resizeBilinear_:function(e,t,n=!1,i=!1){const a=hn(e,"images","resizeBilinear");T(3===a.rank||4===a.rank,(()=>`Error in resizeBilinear: x must be rank 3 or 4, but got rank ${a.rank}.`)),T(2===t.length,(()=>`Error in resizeBilinear: new shape must 2D, but got shape ${t}.`)),T(!1===i||!1===n,(()=>"Error in resizeBilinear: If halfPixelCenters is true, alignCorners must be false."));let s=a,r=!1;3===a.rank&&(r=!0,s=_i(a,[1,a.shape[0],a.shape[1],a.shape[2]]));const o={images:s},l={alignCorners:n,halfPixelCenters:i,size:t},c=sn.runKernel(Ve,o,l);return r?_i(c,[c.shape[1],c.shape[2],c.shape[3]]):c}});
2777
2777
  /**
2778
2778
  * @license
2779
2779
  * Copyright 2020 Google LLC. All Rights Reserved.
@@ -2789,7 +2789,7 @@ function(e,t,n,i,a="bilinear",s=0){const r=hn(e,"image","cropAndResize"),o=hn(t,
2789
2789
  * See the License for the specific language governing permissions and
2790
2790
  * limitations under the License.
2791
2791
  * =============================================================================
2792
- */const Nr=dn({resizeNearestNeighbor_:function(e,t,n=!1,i=!1){const a=hn(e,"images","resizeNearestNeighbor");I(3===a.rank||4===a.rank,(()=>`Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank ${a.rank}.`)),I(2===t.length,(()=>`Error in resizeNearestNeighbor: new shape must 2D, but got shape ${t}.`)),I("float32"===a.dtype||"int32"===a.dtype,(()=>"`images` must have `int32` or `float32` as dtype")),I(!1===i||!1===n,(()=>"Error in resizeNearestNeighbor: If halfPixelCenters is true, alignCorners must be false."));let s=a,r=!1;3===a.rank&&(r=!0,s=_i(a,[1,a.shape[0],a.shape[1],a.shape[2]]));const o={images:s},l={alignCorners:n,halfPixelCenters:i,size:t},c=sn.runKernel(We,o,l);return r?_i(c,[c.shape[1],c.shape[2],c.shape[3]]):c}});
2792
+ */const Nr=dn({resizeNearestNeighbor_:function(e,t,n=!1,i=!1){const a=hn(e,"images","resizeNearestNeighbor");T(3===a.rank||4===a.rank,(()=>`Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank ${a.rank}.`)),T(2===t.length,(()=>`Error in resizeNearestNeighbor: new shape must 2D, but got shape ${t}.`)),T("float32"===a.dtype||"int32"===a.dtype,(()=>"`images` must have `int32` or `float32` as dtype")),T(!1===i||!1===n,(()=>"Error in resizeNearestNeighbor: If halfPixelCenters is true, alignCorners must be false."));let s=a,r=!1;3===a.rank&&(r=!0,s=_i(a,[1,a.shape[0],a.shape[1],a.shape[2]]));const o={images:s},l={alignCorners:n,halfPixelCenters:i,size:t},c=sn.runKernel(We,o,l);return r?_i(c,[c.shape[1],c.shape[2],c.shape[3]]):c}});
2793
2793
  /**
2794
2794
  * @license
2795
2795
  * Copyright 2021 Google LLC. All Rights Reserved.
@@ -2805,7 +2805,7 @@ function(e,t,n,i,a="bilinear",s=0){const r=hn(e,"image","cropAndResize"),o=hn(t,
2805
2805
  * See the License for the specific language governing permissions and
2806
2806
  * limitations under the License.
2807
2807
  * =============================================================================
2808
- */const Ir=dn({threshold_:function(e,t="binary",n=!1,i=.5){const a=hn(e,"image","threshold"),s=a.shape[0]*a.shape[1];let r,o,l,c,u=xi(Vs([i]),255);if(I(3===a.rank,(()=>`Error in threshold: image must be rank 3,but got rank ${a.rank}.`)),I(3===a.shape[2]||1===a.shape[2],(()=>`Error in threshold: image color channel must be equal to 3 or 1but got ${a.shape[2]}.`)),I("int32"===a.dtype||"float32"===a.dtype,(()=>`Error in dtype: image dtype must be int32 or float32,but got dtype ${a.dtype}.`)),I("otsu"===t||"binary"===t,(()=>`Method must be binary or otsu, but was ${t}`)),3===a.shape[2]){[r,o,l]=Bs(a,[1,1,1],-1);const e=xi(r,.2989),t=xi(o,.587),n=xi(l,.114);c=bi(bi(e,t),n)}else c=e;if("otsu"===t){u=function(e,t){let n,i,a,s,r,o,l=Vs([-1]),c=Vs([0]),u=Vs([0]);for(let h=0;h<e.size-1;h++){n=Bi(e,0,h+1),i=Bi(e,h+1),r=ki(ja(n),t),o=ki(ja(i),t);const p=ja(xi(n,Ts(0,n.size)));a=ki(p,ja(n));const d=Yi(i.shape,n.size),m=bi(Ts(0,i.size),d),f=xi(i,m);s=ki(ja(f),ja(i));const g=Ja(a,s),v=Ja(a,s),y=xi(r,o);u=xi(xi(y,g),v);const b=Pa(u,c);c=va(b,u,c),l=va(b,Vs([h]),l)}return l}(Hi(ei($s(c),"int32"),gn([]),256),s)}const h=n?Ga(c,u):Pa(c,u);return ei(xi(h,255),"int32")}});
2808
+ */const Tr=dn({threshold_:function(e,t="binary",n=!1,i=.5){const a=hn(e,"image","threshold"),s=a.shape[0]*a.shape[1];let r,o,l,c,u=xi(Gs([i]),255);if(T(3===a.rank,(()=>`Error in threshold: image must be rank 3,but got rank ${a.rank}.`)),T(3===a.shape[2]||1===a.shape[2],(()=>`Error in threshold: image color channel must be equal to 3 or 1but got ${a.shape[2]}.`)),T("int32"===a.dtype||"float32"===a.dtype,(()=>`Error in dtype: image dtype must be int32 or float32,but got dtype ${a.dtype}.`)),T("otsu"===t||"binary"===t,(()=>`Method must be binary or otsu, but was ${t}`)),3===a.shape[2]){[r,o,l]=Bs(a,[1,1,1],-1);const e=xi(r,.2989),t=xi(o,.587),n=xi(l,.114);c=bi(bi(e,t),n)}else c=e;if("otsu"===t){u=function(e,t){let n,i,a,s,r,o,l=Gs([-1]),c=Gs([0]),u=Gs([0]);for(let h=0;h<e.size-1;h++){n=Bi(e,0,h+1),i=Bi(e,h+1),r=ki(ja(n),t),o=ki(ja(i),t);const p=ja(xi(n,Is(0,n.size)));a=ki(p,ja(n));const d=Yi(i.shape,n.size),m=bi(Is(0,i.size),d),f=xi(i,m);s=ki(ja(f),ja(i));const g=Ja(a,s),v=Ja(a,s),y=xi(r,o);u=xi(xi(y,g),v);const b=Pa(u,c);c=va(b,u,c),l=va(b,Gs([h]),l)}return l}(Hi(ei($s(c),"int32"),gn([]),256),s)}const h=n?Va(c,u):Pa(c,u);return ei(xi(h,255),"int32")}});
2809
2809
  /**
2810
2810
  * @license
2811
2811
  * Copyright 2021 Google LLC. All Rights Reserved.
@@ -2821,7 +2821,7 @@ function(e,t,n,i,a="bilinear",s=0){const r=hn(e,"image","cropAndResize"),o=hn(t,
2821
2821
  * See the License for the specific language governing permissions and
2822
2822
  * limitations under the License.
2823
2823
  * =============================================================================
2824
- */const Tr=dn({transform_:function(e,t,n="nearest",i="constant",a=0,s){const r=hn(e,"image","transform","float32"),o=hn(t,"transforms","transform","float32");I(4===r.rank,(()=>`Error in transform: image must be rank 4,but got rank ${r.rank}.`)),I(2===o.rank&&(o.shape[0]===r.shape[0]||1===o.shape[0])&&8===o.shape[1],(()=>"Error in transform: Input transform should be batch x 8 or 1 x 8")),I(null==s||2===s.length,(()=>`Error in transform: outputShape must be [height, width] or null, but got ${s}.`));const l={image:r,transforms:o},c={interpolation:n,fillMode:i,fillValue:a,outputShape:s};return sn.runKernel("Transform",l,c)}});
2824
+ */const Ir=dn({transform_:function(e,t,n="nearest",i="constant",a=0,s){const r=hn(e,"image","transform","float32"),o=hn(t,"transforms","transform","float32");T(4===r.rank,(()=>`Error in transform: image must be rank 4,but got rank ${r.rank}.`)),T(2===o.rank&&(o.shape[0]===r.shape[0]||1===o.shape[0])&&8===o.shape[1],(()=>"Error in transform: Input transform should be batch x 8 or 1 x 8")),T(null==s||2===s.length,(()=>`Error in transform: outputShape must be [height, width] or null, but got ${s}.`));const l={image:r,transforms:o},c={interpolation:n,fillMode:i,fillValue:a,outputShape:s};return sn.runKernel("Transform",l,c)}});
2825
2825
  /**
2826
2826
  * @license
2827
2827
  * Copyright 2020 Google LLC. All Rights Reserved.
@@ -2837,7 +2837,7 @@ function(e,t,n,i,a="bilinear",s=0){const r=hn(e,"image","cropAndResize"),o=hn(t,
2837
2837
  * See the License for the specific language governing permissions and
2838
2838
  * limitations under the License.
2839
2839
  * =============================================================================
2840
- */const Er=dn({bandPart_:function(e,t,n){I(t%1==0,(()=>`bandPart(): numLower must be an integer, got ${t}.`)),I(n%1==0,(()=>`bandPart(): numUpper must be an integer, got ${n}.`));const i=hn(e,"a","bandPart");I(i.rank>=2,(()=>`bandPart(): Rank must be at least 2, got ${i.rank}.`));const a=i.shape,[s,r]=i.shape.slice(-2);if(!(t<=s))throw new Error(`bandPart(): numLower (${t}) must not be greater than the number of rows (${s}).`);if(!(n<=r))throw new Error(`bandPart(): numUpper (${n}) must not be greater than the number of columns (${r}).`);t<0&&(t=s),n<0&&(n=r);const o=_i(Ts(0,s,1,"int32"),[-1,1]),l=Ts(0,r,1,"int32"),c=Ja(o,l),u=Ya(Ga(c,Aa(+t,"int32")),Ba(c,Aa(-n,"int32"))),h=is([s,r],i.dtype);return _i(Ws(Js(_i(i,[-1,s,r])).map((e=>va(u,e,h)))),a)}});
2840
+ */const Ar=dn({bandPart_:function(e,t,n){T(t%1==0,(()=>`bandPart(): numLower must be an integer, got ${t}.`)),T(n%1==0,(()=>`bandPart(): numUpper must be an integer, got ${n}.`));const i=hn(e,"a","bandPart");T(i.rank>=2,(()=>`bandPart(): Rank must be at least 2, got ${i.rank}.`));const a=i.shape,[s,r]=i.shape.slice(-2);if(!(t<=s))throw new Error(`bandPart(): numLower (${t}) must not be greater than the number of rows (${s}).`);if(!(n<=r))throw new Error(`bandPart(): numUpper (${n}) must not be greater than the number of columns (${r}).`);t<0&&(t=s),n<0&&(n=r);const o=_i(Is(0,s,1,"int32"),[-1,1]),l=Is(0,r,1,"int32"),c=Ja(o,l),u=Ya(Va(c,Ca(+t,"int32")),Ba(c,Ca(-n,"int32"))),h=is([s,r],i.dtype);return _i(Ws(Js(_i(i,[-1,s,r])).map((e=>va(u,e,h)))),a)}});
2841
2841
  /**
2842
2842
  * @license
2843
2843
  * Copyright 2020 Google LLC. All Rights Reserved.
@@ -2853,7 +2853,7 @@ function(e,t,n,i,a="bilinear",s=0){const r=hn(e,"image","cropAndResize"),o=hn(t,
2853
2853
  * See the License for the specific language governing permissions and
2854
2854
  * limitations under the License.
2855
2855
  * =============================================================================
2856
- */const Ar=dn({gramSchmidt_:function(e){let t;if(Array.isArray(e)){t=!1,I(null!=e&&e.length>0,(()=>"Gram-Schmidt process: input must not be null, undefined, or empty"));const n=e[0].shape[0];for(let t=1;t<e.length;++t)I(e[t].shape[0]===n,(()=>`Gram-Schmidt: Non-unique lengths found in the input vectors: (${e[t].shape[0]} vs. ${n})`))}else t=!0,e=Bs(e,e.shape[0],0).map((e=>Us(e,[0])));I(e.length<=e[0].shape[0],(()=>`Gram-Schmidt: Number of vectors (${e.length}) exceeds number of dimensions (${e[0].shape[0]}).`));const n=[],i=e;for(let t=0;t<e.length;++t)n.push(sn.tidy((()=>{let e=i[t];if(t>0)for(let i=0;i<t;++i){const t=xi(ja(xi(n[i],e)),n[i]);e=Ja(e,t)}return ki(e,Da(e,"euclidean"))})));return t?Ws(n,0):n}});
2856
+ */const Cr=dn({gramSchmidt_:function(e){let t;if(Array.isArray(e)){t=!1,T(null!=e&&e.length>0,(()=>"Gram-Schmidt process: input must not be null, undefined, or empty"));const n=e[0].shape[0];for(let t=1;t<e.length;++t)T(e[t].shape[0]===n,(()=>`Gram-Schmidt: Non-unique lengths found in the input vectors: (${e[t].shape[0]} vs. ${n})`))}else t=!0,e=Bs(e,e.shape[0],0).map((e=>Us(e,[0])));T(e.length<=e[0].shape[0],(()=>`Gram-Schmidt: Number of vectors (${e.length}) exceeds number of dimensions (${e[0].shape[0]}).`));const n=[],i=e;for(let t=0;t<e.length;++t)n.push(sn.tidy((()=>{let e=i[t];if(t>0)for(let i=0;i<t;++i){const t=xi(ja(xi(n[i],e)),n[i]);e=Ja(e,t)}return ki(e,Da(e,"euclidean"))})));return t?Ws(n,0):n}});
2857
2857
  /**
2858
2858
  * @license
2859
2859
  * Copyright 2020 Google LLC. All Rights Reserved.
@@ -2869,7 +2869,7 @@ function(e,t,n,i,a="bilinear",s=0){const r=hn(e,"image","cropAndResize"),o=hn(t,
2869
2869
  * See the License for the specific language governing permissions and
2870
2870
  * limitations under the License.
2871
2871
  * =============================================================================
2872
- */function Cr(e,t=!1){return sn.tidy((()=>{I(2===e.shape.length,(()=>`qr2d() requires a 2D Tensor, but got a ${e.shape.length}D Tensor.`));const n=e.shape[0],i=e.shape[1];let a=La(n),s=Mi(e);const r=Ks([[1]],[1,1]);let o=Mi(r);const l=n>=i?i:n;for(let e=0;e<l;++e){const t=s,l=o,c=a;[o,s,a]=sn.tidy((()=>{const t=Bi(s,[e,e],[n-e,1]),l=Da(t),c=Bi(s,[e,e],[1,1]),u=va(Pa(c,0),Ks([[-1]]),Ks([[1]])),h=Ja(c,xi(u,l)),p=ki(t,h);o=1===p.shape[0]?Mi(r):Oi([r,Bi(p,[1,0],[p.shape[0]-1,p.shape[1]])],0);const d=ci(ki(ti(u,h),l)),m=Bi(s,[e,0],[n-e,i]),f=xi(d,o),g=hi(o);if(0===e)s=Ja(m,ti(f,ti(g,m)));else{const t=Ja(m,ti(f,ti(g,m)));s=Oi([Bi(s,[0,0],[e,i]),t],0)}const v=hi(f),y=Bi(a,[0,e],[n,a.shape[1]-e]);if(0===e)a=Ja(y,ti(ti(y,o),v));else{const t=Ja(y,ti(ti(y,o),v));a=Oi([Bi(a,[0,0],[n,e]),t],1)}return[o,s,a]})),ri([t,l,c])}return!t&&n>i&&(a=Bi(a,[0,0],[n,i]),s=Bi(s,[0,0],[i,i])),[a,s]}))}const $r=dn({qr_:function(e,t=!1){if(I(e.rank>=2,(()=>`qr() requires input tensor to have a rank >= 2, but got rank ${e.rank}`)),2===e.rank)return Cr(e,t);{const n=e.shape.slice(0,e.shape.length-2).reduce(((e,t)=>e*t)),i=Js(_i(e,[n,e.shape[e.shape.length-2],e.shape[e.shape.length-1]]),0),a=[],s=[];i.forEach((e=>{const[n,i]=Cr(e,t);a.push(n),s.push(i)}));return[_i(Ws(a,0),e.shape),_i(Ws(s,0),e.shape)]}}});
2872
+ */function Er(e,t=!1){return sn.tidy((()=>{T(2===e.shape.length,(()=>`qr2d() requires a 2D Tensor, but got a ${e.shape.length}D Tensor.`));const n=e.shape[0],i=e.shape[1];let a=La(n),s=Mi(e);const r=Ks([[1]],[1,1]);let o=Mi(r);const l=n>=i?i:n;for(let e=0;e<l;++e){const t=s,l=o,c=a;[o,s,a]=sn.tidy((()=>{const t=Bi(s,[e,e],[n-e,1]),l=Da(t),c=Bi(s,[e,e],[1,1]),u=va(Pa(c,0),Ks([[-1]]),Ks([[1]])),h=Ja(c,xi(u,l)),p=ki(t,h);o=1===p.shape[0]?Mi(r):Oi([r,Bi(p,[1,0],[p.shape[0]-1,p.shape[1]])],0);const d=ci(ki(ti(u,h),l)),m=Bi(s,[e,0],[n-e,i]),f=xi(d,o),g=hi(o);if(0===e)s=Ja(m,ti(f,ti(g,m)));else{const t=Ja(m,ti(f,ti(g,m)));s=Oi([Bi(s,[0,0],[e,i]),t],0)}const v=hi(f),y=Bi(a,[0,e],[n,a.shape[1]-e]);if(0===e)a=Ja(y,ti(ti(y,o),v));else{const t=Ja(y,ti(ti(y,o),v));a=Oi([Bi(a,[0,0],[n,e]),t],1)}return[o,s,a]})),ri([t,l,c])}return!t&&n>i&&(a=Bi(a,[0,0],[n,i]),s=Bi(s,[0,0],[i,i])),[a,s]}))}const $r=dn({qr_:function(e,t=!1){if(T(e.rank>=2,(()=>`qr() requires input tensor to have a rank >= 2, but got rank ${e.rank}`)),2===e.rank)return Er(e,t);{const n=e.shape.slice(0,e.shape.length-2).reduce(((e,t)=>e*t)),i=Js(_i(e,[n,e.shape[e.shape.length-2],e.shape[e.shape.length-1]]),0),a=[],s=[];i.forEach((e=>{const[n,i]=Er(e,t);a.push(n),s.push(i)}));return[_i(Ws(a,0),e.shape),_i(Ws(s,0),e.shape)]}}});
2873
2873
  /**
2874
2874
  * @license
2875
2875
  * Copyright 2020 Google LLC. All Rights Reserved.
@@ -2885,7 +2885,7 @@ function(e,t,n,i,a="bilinear",s=0){const r=hn(e,"image","cropAndResize"),o=hn(t,
2885
2885
  * See the License for the specific language governing permissions and
2886
2886
  * limitations under the License.
2887
2887
  * =============================================================================
2888
- */var jr;!function(e){e[e.NONE=0]="NONE",e[e.MEAN=1]="MEAN",e[e.SUM=2]="SUM",e[e.SUM_BY_NONZERO_WEIGHTS=3]="SUM_BY_NONZERO_WEIGHTS"}(jr||(jr={}));const zr={flipLeftRight:or,grayscaleToRGB:lr,resizeNearestNeighbor:Nr,resizeBilinear:Sr,rotateWithOffset:cr,cropAndResize:rr,nonMaxSuppression:hr,nonMaxSuppressionAsync:yr,nonMaxSuppressionWithScore:br,nonMaxSuppressionWithScoreAsync:wr,nonMaxSuppressionPadded:kr,nonMaxSuppressionPaddedAsync:xr,threshold:Ir,transform:Tr},Dr={bandPart:Er,gramSchmidt:Ar,qr:$r};
2888
+ */var jr;!function(e){e[e.NONE=0]="NONE",e[e.MEAN=1]="MEAN",e[e.SUM=2]="SUM",e[e.SUM_BY_NONZERO_WEIGHTS=3]="SUM_BY_NONZERO_WEIGHTS"}(jr||(jr={}));const zr={flipLeftRight:or,grayscaleToRGB:lr,resizeNearestNeighbor:Nr,resizeBilinear:Sr,rotateWithOffset:cr,cropAndResize:rr,nonMaxSuppression:hr,nonMaxSuppressionAsync:yr,nonMaxSuppressionWithScore:br,nonMaxSuppressionWithScoreAsync:wr,nonMaxSuppressionPadded:kr,nonMaxSuppressionPaddedAsync:xr,threshold:Tr,transform:Ir},Dr={bandPart:Ar,gramSchmidt:Cr,qr:$r};
2889
2889
  /**
2890
2890
  * @license
2891
2891
  * Copyright 2020 Google LLC. All Rights Reserved.
@@ -2918,7 +2918,7 @@ function(e,t,n,i,a="bilinear",s=0){const r=hn(e,"image","cropAndResize"),o=hn(t,
2918
2918
  * limitations under the License.
2919
2919
  * =============================================================================
2920
2920
  */
2921
- class Fr extends gi{minimize(e,t=!1,n){const{value:i,grads:a}=this.computeGradients(e,n);if(null!=n){const e=n.map((e=>({name:e.name,tensor:a[e.name]})));this.applyGradients(e)}else this.applyGradients(a);return ri(a),t?i:(i.dispose(),null)}get iterations(){return null==this.iterations_&&(this.iterations_=0),this.iterations_}incrementIterations(){this.iterations_=this.iterations+1}computeGradients(e,t){return function(e,t){I(O(e),(()=>"The f passed in variableGrads(f) must be a function")),I(null==t||Array.isArray(t)&&t.every((e=>e instanceof Wt)),(()=>"The varList passed in variableGrads(f, varList) must be an array of variables"));const n=null!=t;if(!n){t=[];for(const e in sn.registeredVariables)t.push(sn.registeredVariables[e])}const i=n?t.filter((e=>!e.trainable)):null,a=t.length;t=t.filter((e=>e.trainable)),I(t.length>0,(()=>`variableGrads() expects at least one of the input variables to be trainable, but none of the ${a} variables is trainable.`));const{value:s,grads:r}=sn.gradients(e,t,null,!0);I(r.some((e=>null!=e)),(()=>"Cannot find a connection between any variable and the result of the loss function y=f(x). Please make sure the operations that use variables are inside the function f passed to minimize().")),I(0===s.rank,(()=>`The f passed in variableGrads(f) must return a scalar, but it returned a rank-${s.rank} tensor`));const o={};return t.forEach(((e,t)=>{null!=r[t]&&(o[e.name]=r[t])})),null!=i&&i.forEach((e=>o[e.name]=null)),{value:s,grads:o}}(e,t)}dispose(){null!=this.iterations_&&ri(this.iterations_)}async saveIterations(){return null==this.iterations_&&(this.iterations_=0),{name:"iter",tensor:Aa(this.iterations_,"int32")}}async getWeights(){throw new Error("getWeights() is not implemented for this optimizer yet.")}async setWeights(e){throw new Error(`setWeights() is not implemented for this optimizer class ${this.getClassName()}`)}async extractIterations(e){return this.iterations_=(await e[0].tensor.data())[0],e.slice(1)}}Object.defineProperty(Fr,Symbol.hasInstance,{value:e=>null!=e.minimize&&null!=e.computeGradients&&null!=e.applyGradients});
2921
+ class Fr extends gi{minimize(e,t=!1,n){const{value:i,grads:a}=this.computeGradients(e,n);if(null!=n){const e=n.map((e=>({name:e.name,tensor:a[e.name]})));this.applyGradients(e)}else this.applyGradients(a);return ri(a),t?i:(i.dispose(),null)}get iterations(){return null==this.iterations_&&(this.iterations_=0),this.iterations_}incrementIterations(){this.iterations_=this.iterations+1}computeGradients(e,t){return function(e,t){T(O(e),(()=>"The f passed in variableGrads(f) must be a function")),T(null==t||Array.isArray(t)&&t.every((e=>e instanceof Wt)),(()=>"The varList passed in variableGrads(f, varList) must be an array of variables"));const n=null!=t;if(!n){t=[];for(const e in sn.registeredVariables)t.push(sn.registeredVariables[e])}const i=n?t.filter((e=>!e.trainable)):null,a=t.length;t=t.filter((e=>e.trainable)),T(t.length>0,(()=>`variableGrads() expects at least one of the input variables to be trainable, but none of the ${a} variables is trainable.`));const{value:s,grads:r}=sn.gradients(e,t,null,!0);T(r.some((e=>null!=e)),(()=>"Cannot find a connection between any variable and the result of the loss function y=f(x). Please make sure the operations that use variables are inside the function f passed to minimize().")),T(0===s.rank,(()=>`The f passed in variableGrads(f) must return a scalar, but it returned a rank-${s.rank} tensor`));const o={};return t.forEach(((e,t)=>{null!=r[t]&&(o[e.name]=r[t])})),null!=i&&i.forEach((e=>o[e.name]=null)),{value:s,grads:o}}(e,t)}dispose(){null!=this.iterations_&&ri(this.iterations_)}async saveIterations(){return null==this.iterations_&&(this.iterations_=0),{name:"iter",tensor:Ca(this.iterations_,"int32")}}async getWeights(){throw new Error("getWeights() is not implemented for this optimizer yet.")}async setWeights(e){throw new Error(`setWeights() is not implemented for this optimizer class ${this.getClassName()}`)}async extractIterations(e){return this.iterations_=(await e[0].tensor.data())[0],e.slice(1)}}Object.defineProperty(Fr,Symbol.hasInstance,{value:e=>null!=e.minimize&&null!=e.computeGradients&&null!=e.applyGradients});
2922
2922
  /**
2923
2923
  * @license
2924
2924
  * Copyright 2018 Google LLC. All Rights Reserved.
@@ -2935,7 +2935,7 @@ class Fr extends gi{minimize(e,t=!1,n){const{value:i,grads:a}=this.computeGradie
2935
2935
  * limitations under the License.
2936
2936
  * =============================================================================
2937
2937
  */
2938
- class _r extends Fr{constructor(e,t,n=null){super(),this.learningRate=e,this.rho=t,this.epsilon=n,this.accumulatedGrads=[],this.accumulatedUpdates=[],null==n&&(this.epsilon=sn.backend.epsilon())}static get className(){return"Adadelta"}applyGradients(e){(Array.isArray(e)?e.map((e=>e.name)):Object.keys(e)).forEach(((t,n)=>{const i=sn.registeredVariables[t];null==this.accumulatedGrads[n]&&(this.accumulatedGrads[n]={originalName:`${t}/accum_grad`,variable:si((()=>ya(i).variable(false)))}),null==this.accumulatedUpdates[n]&&(this.accumulatedUpdates[n]={originalName:`${t}/accum_var`,variable:si((()=>ya(i).variable(false)))});const a=Array.isArray(e)?e[n].tensor:e[t];if(null==a)return;const s=this.accumulatedGrads[n].variable,r=this.accumulatedUpdates[n].variable;si((()=>{const e=bi(xi(s,this.rho),xi($a(a),1-this.rho)),t=xi(ki(Ca(bi(r,this.epsilon)),Ca(bi(s,this.epsilon))),a),n=bi(xi(r,this.rho),xi($a(t),1-this.rho));s.assign(e),r.assign(n);const o=bi(xi(t,-this.learningRate),i);i.assign(o)}))})),this.incrementIterations()}dispose(){null!=this.accumulatedUpdates&&(ri(this.accumulatedGrads.map((e=>e.variable))),ri(this.accumulatedUpdates.map((e=>e.variable))))}async getWeights(){const e=[...this.accumulatedGrads,...this.accumulatedUpdates];return[await this.saveIterations()].concat(e.map((e=>({name:e.originalName,tensor:e.variable}))))}async setWeights(e){const t=(e=await this.extractIterations(e)).length/2;this.accumulatedGrads=e.slice(0,t).map((e=>({originalName:e.name,variable:e.tensor.variable(false)}))),this.accumulatedUpdates=e.slice(t,2*t).map((e=>({originalName:e.name,variable:e.tensor.variable(false)})))}getConfig(){return{learningRate:this.learningRate,rho:this.rho,epsilon:this.epsilon}}static fromConfig(e,t){return new e(t.learningRate,t.rho,t.epsilon)}}
2938
+ class _r extends Fr{constructor(e,t,n=null){super(),this.learningRate=e,this.rho=t,this.epsilon=n,this.accumulatedGrads=[],this.accumulatedUpdates=[],null==n&&(this.epsilon=sn.backend.epsilon())}static get className(){return"Adadelta"}applyGradients(e){(Array.isArray(e)?e.map((e=>e.name)):Object.keys(e)).forEach(((t,n)=>{const i=sn.registeredVariables[t];null==this.accumulatedGrads[n]&&(this.accumulatedGrads[n]={originalName:`${t}/accum_grad`,variable:si((()=>ya(i).variable(false)))}),null==this.accumulatedUpdates[n]&&(this.accumulatedUpdates[n]={originalName:`${t}/accum_var`,variable:si((()=>ya(i).variable(false)))});const a=Array.isArray(e)?e[n].tensor:e[t];if(null==a)return;const s=this.accumulatedGrads[n].variable,r=this.accumulatedUpdates[n].variable;si((()=>{const e=bi(xi(s,this.rho),xi($a(a),1-this.rho)),t=xi(ki(Ea(bi(r,this.epsilon)),Ea(bi(s,this.epsilon))),a),n=bi(xi(r,this.rho),xi($a(t),1-this.rho));s.assign(e),r.assign(n);const o=bi(xi(t,-this.learningRate),i);i.assign(o)}))})),this.incrementIterations()}dispose(){null!=this.accumulatedUpdates&&(ri(this.accumulatedGrads.map((e=>e.variable))),ri(this.accumulatedUpdates.map((e=>e.variable))))}async getWeights(){const e=[...this.accumulatedGrads,...this.accumulatedUpdates];return[await this.saveIterations()].concat(e.map((e=>({name:e.originalName,tensor:e.variable}))))}async setWeights(e){const t=(e=await this.extractIterations(e)).length/2;this.accumulatedGrads=e.slice(0,t).map((e=>({originalName:e.name,variable:e.tensor.variable(false)}))),this.accumulatedUpdates=e.slice(t,2*t).map((e=>({originalName:e.name,variable:e.tensor.variable(false)})))}getConfig(){return{learningRate:this.learningRate,rho:this.rho,epsilon:this.epsilon}}static fromConfig(e,t){return new e(t.learningRate,t.rho,t.epsilon)}}
2939
2939
  /**
2940
2940
  * @license
2941
2941
  * Copyright 2018 Google LLC. All Rights Reserved.
@@ -2951,7 +2951,7 @@ class _r extends Fr{constructor(e,t,n=null){super(),this.learningRate=e,this.rho
2951
2951
  * See the License for the specific language governing permissions and
2952
2952
  * limitations under the License.
2953
2953
  * =============================================================================
2954
- */class Rr extends Fr{constructor(e,t=.1){super(),this.learningRate=e,this.initialAccumulatorValue=t,this.accumulatedGrads=[]}static get className(){return"Adagrad"}applyGradients(e){(Array.isArray(e)?e.map((e=>e.name)):Object.keys(e)).forEach(((t,n)=>{const i=sn.registeredVariables[t];if(null==this.accumulatedGrads[n]){const e=!1;this.accumulatedGrads[n]={originalName:`${t}/accumulator`,variable:si((()=>Yi(i.shape,this.initialAccumulatorValue).variable(e)))}}const a=Array.isArray(e)?e[n].tensor:e[t];if(null==a)return;const s=this.accumulatedGrads[n].variable;si((()=>{const e=bi(s,$a(a));s.assign(e);const t=bi(xi(ki(a,Ca(bi(e,sn.backend.epsilon()))),-this.learningRate),i);i.assign(t)}))})),this.incrementIterations()}dispose(){null!=this.accumulatedGrads&&ri(this.accumulatedGrads.map((e=>e.variable)))}async getWeights(){return[await this.saveIterations()].concat(this.accumulatedGrads.map((e=>({name:e.originalName,tensor:e.variable}))))}async setWeights(e){e=await this.extractIterations(e);this.accumulatedGrads=e.map((e=>({originalName:e.name,variable:e.tensor.variable(false)})))}getConfig(){return{learningRate:this.learningRate,initialAccumulatorValue:this.initialAccumulatorValue}}static fromConfig(e,t){return new e(t.learningRate,t.initialAccumulatorValue)}}
2954
+ */class Rr extends Fr{constructor(e,t=.1){super(),this.learningRate=e,this.initialAccumulatorValue=t,this.accumulatedGrads=[]}static get className(){return"Adagrad"}applyGradients(e){(Array.isArray(e)?e.map((e=>e.name)):Object.keys(e)).forEach(((t,n)=>{const i=sn.registeredVariables[t];if(null==this.accumulatedGrads[n]){const e=!1;this.accumulatedGrads[n]={originalName:`${t}/accumulator`,variable:si((()=>Yi(i.shape,this.initialAccumulatorValue).variable(e)))}}const a=Array.isArray(e)?e[n].tensor:e[t];if(null==a)return;const s=this.accumulatedGrads[n].variable;si((()=>{const e=bi(s,$a(a));s.assign(e);const t=bi(xi(ki(a,Ea(bi(e,sn.backend.epsilon()))),-this.learningRate),i);i.assign(t)}))})),this.incrementIterations()}dispose(){null!=this.accumulatedGrads&&ri(this.accumulatedGrads.map((e=>e.variable)))}async getWeights(){return[await this.saveIterations()].concat(this.accumulatedGrads.map((e=>({name:e.originalName,tensor:e.variable}))))}async setWeights(e){e=await this.extractIterations(e);this.accumulatedGrads=e.map((e=>({originalName:e.name,variable:e.tensor.variable(false)})))}getConfig(){return{learningRate:this.learningRate,initialAccumulatorValue:this.initialAccumulatorValue}}static fromConfig(e,t){return new e(t.learningRate,t.initialAccumulatorValue)}}
2955
2955
  /**
2956
2956
  * @license
2957
2957
  * Copyright 2018 Google LLC. All Rights Reserved.
@@ -2967,7 +2967,7 @@ class _r extends Fr{constructor(e,t,n=null){super(),this.learningRate=e,this.rho
2967
2967
  * See the License for the specific language governing permissions and
2968
2968
  * limitations under the License.
2969
2969
  * =============================================================================
2970
- */class Lr extends Fr{constructor(e,t,n,i=null){super(),this.learningRate=e,this.beta1=t,this.beta2=n,this.epsilon=i,this.accumulatedFirstMoment=[],this.accumulatedSecondMoment=[],si((()=>{this.accBeta1=Aa(t).variable(),this.accBeta2=Aa(n).variable()})),null==i&&(this.epsilon=sn.backend.epsilon())}static get className(){return"Adam"}applyGradients(e){const t=Array.isArray(e)?e.map((e=>e.name)):Object.keys(e);si((()=>{const n=Ja(1,this.accBeta1),i=Ja(1,this.accBeta2);t.forEach(((t,a)=>{const s=sn.registeredVariables[t];null==this.accumulatedFirstMoment[a]&&(this.accumulatedFirstMoment[a]={originalName:`${t}/m`,variable:si((()=>ya(s).variable(false)))}),null==this.accumulatedSecondMoment[a]&&(this.accumulatedSecondMoment[a]={originalName:`${t}/v`,variable:si((()=>ya(s).variable(false)))});const r=Array.isArray(e)?e[a].tensor:e[t];if(null==r)return;const o=this.accumulatedFirstMoment[a].variable,l=this.accumulatedSecondMoment[a].variable,c=bi(xi(o,this.beta1),xi(r,1-this.beta1)),u=bi(xi(l,this.beta2),xi($a(r),1-this.beta2)),h=ki(c,n),p=ki(u,i);o.assign(c),l.assign(u);const d=bi(xi(ki(h,bi(Ca(p),this.epsilon)),-this.learningRate),s);s.assign(d)})),this.accBeta1.assign(xi(this.accBeta1,this.beta1)),this.accBeta2.assign(xi(this.accBeta2,this.beta2))})),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.accBeta2.dispose(),null!=this.accumulatedFirstMoment&&ri(this.accumulatedFirstMoment.map((e=>e.variable))),null!=this.accumulatedSecondMoment&&ri(this.accumulatedSecondMoment.map((e=>e.variable)))}async getWeights(){const e=[...this.accumulatedFirstMoment,...this.accumulatedSecondMoment];return[await this.saveIterations()].concat(e.map((e=>({name:e.originalName,tensor:e.variable}))))}async setWeights(e){e=await this.extractIterations(e),si((()=>{this.accBeta1.assign(Ea(this.beta1,this.iterations_+1)),this.accBeta2.assign(Ea(this.beta2,this.iterations_+1))}));const t=e.length/2;this.accumulatedFirstMoment=e.slice(0,t).map((e=>({originalName:e.name,variable:e.tensor.variable(false)}))),this.accumulatedSecondMoment=e.slice(t,2*t).map((e=>({originalName:e.name,variable:e.tensor.variable(false)})))}getConfig(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon}}static fromConfig(e,t){return new e(t.learningRate,t.beta1,t.beta2,t.epsilon)}}
2970
+ */class Lr extends Fr{constructor(e,t,n,i=null){super(),this.learningRate=e,this.beta1=t,this.beta2=n,this.epsilon=i,this.accumulatedFirstMoment=[],this.accumulatedSecondMoment=[],si((()=>{this.accBeta1=Ca(t).variable(),this.accBeta2=Ca(n).variable()})),null==i&&(this.epsilon=sn.backend.epsilon())}static get className(){return"Adam"}applyGradients(e){const t=Array.isArray(e)?e.map((e=>e.name)):Object.keys(e);si((()=>{const n=Ja(1,this.accBeta1),i=Ja(1,this.accBeta2);t.forEach(((t,a)=>{const s=sn.registeredVariables[t];null==this.accumulatedFirstMoment[a]&&(this.accumulatedFirstMoment[a]={originalName:`${t}/m`,variable:si((()=>ya(s).variable(false)))}),null==this.accumulatedSecondMoment[a]&&(this.accumulatedSecondMoment[a]={originalName:`${t}/v`,variable:si((()=>ya(s).variable(false)))});const r=Array.isArray(e)?e[a].tensor:e[t];if(null==r)return;const o=this.accumulatedFirstMoment[a].variable,l=this.accumulatedSecondMoment[a].variable,c=bi(xi(o,this.beta1),xi(r,1-this.beta1)),u=bi(xi(l,this.beta2),xi($a(r),1-this.beta2)),h=ki(c,n),p=ki(u,i);o.assign(c),l.assign(u);const d=bi(xi(ki(h,bi(Ea(p),this.epsilon)),-this.learningRate),s);s.assign(d)})),this.accBeta1.assign(xi(this.accBeta1,this.beta1)),this.accBeta2.assign(xi(this.accBeta2,this.beta2))})),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.accBeta2.dispose(),null!=this.accumulatedFirstMoment&&ri(this.accumulatedFirstMoment.map((e=>e.variable))),null!=this.accumulatedSecondMoment&&ri(this.accumulatedSecondMoment.map((e=>e.variable)))}async getWeights(){const e=[...this.accumulatedFirstMoment,...this.accumulatedSecondMoment];return[await this.saveIterations()].concat(e.map((e=>({name:e.originalName,tensor:e.variable}))))}async setWeights(e){e=await this.extractIterations(e),si((()=>{this.accBeta1.assign(Aa(this.beta1,this.iterations_+1)),this.accBeta2.assign(Aa(this.beta2,this.iterations_+1))}));const t=e.length/2;this.accumulatedFirstMoment=e.slice(0,t).map((e=>({originalName:e.name,variable:e.tensor.variable(false)}))),this.accumulatedSecondMoment=e.slice(t,2*t).map((e=>({originalName:e.name,variable:e.tensor.variable(false)})))}getConfig(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon}}static fromConfig(e,t){return new e(t.learningRate,t.beta1,t.beta2,t.epsilon)}}
2971
2971
  /**
2972
2972
  * @license
2973
2973
  * Copyright 2018 Google LLC. All Rights Reserved.
@@ -2983,7 +2983,7 @@ class _r extends Fr{constructor(e,t,n=null){super(),this.learningRate=e,this.rho
2983
2983
  * See the License for the specific language governing permissions and
2984
2984
  * limitations under the License.
2985
2985
  * =============================================================================
2986
- */class Mr extends Fr{constructor(e,t,n,i=null,a=0){super(),this.learningRate=e,this.beta1=t,this.beta2=n,this.epsilon=i,this.decay=a,this.accumulatedFirstMoment=[],this.accumulatedWeightedInfNorm=[],si((()=>{this.iteration=Aa(0).variable(),this.accBeta1=Aa(t).variable()})),null==i&&(this.epsilon=sn.backend.epsilon())}static get className(){return"Adamax"}applyGradients(e){const t=Array.isArray(e)?e.map((e=>e.name)):Object.keys(e);si((()=>{const n=Ja(1,this.accBeta1),i=ki(-this.learningRate,bi(xi(this.iteration,this.decay),1));t.forEach(((t,a)=>{const s=sn.registeredVariables[t];null==this.accumulatedFirstMoment[a]&&(this.accumulatedFirstMoment[a]={originalName:`${t}/m`,variable:ya(s).variable(false)}),null==this.accumulatedWeightedInfNorm[a]&&(this.accumulatedWeightedInfNorm[a]={originalName:`${t}/v`,variable:ya(s).variable(false)});const r=Array.isArray(e)?e[a].tensor:e[t];if(null==r)return;const o=this.accumulatedFirstMoment[a].variable,l=this.accumulatedWeightedInfNorm[a].variable,c=bi(xi(o,this.beta1),xi(r,1-this.beta1)),u=xi(l,this.beta2),h=Si(r),p=ts(u,h);o.assign(c),l.assign(p);const d=bi(xi(ki(i,n),ki(c,bi(p,this.epsilon))),s);s.assign(d)})),this.iteration.assign(bi(this.iteration,1)),this.accBeta1.assign(xi(this.accBeta1,this.beta1))})),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.iteration.dispose(),null!=this.accumulatedFirstMoment&&ri(this.accumulatedFirstMoment.map((e=>e.variable))),null!=this.accumulatedWeightedInfNorm&&ri(this.accumulatedWeightedInfNorm.map((e=>e.variable)))}async getWeights(){throw new Error("getWeights() is not implemented for Adamax yet.")}async setWeights(e){throw new Error("setWeights() is not implemented for Adamax yet.")}getConfig(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon,decay:this.decay}}static fromConfig(e,t){return new e(t.learningRate,t.beta1,t.beta2,t.epsilon,t.decay)}}
2986
+ */class Mr extends Fr{constructor(e,t,n,i=null,a=0){super(),this.learningRate=e,this.beta1=t,this.beta2=n,this.epsilon=i,this.decay=a,this.accumulatedFirstMoment=[],this.accumulatedWeightedInfNorm=[],si((()=>{this.iteration=Ca(0).variable(),this.accBeta1=Ca(t).variable()})),null==i&&(this.epsilon=sn.backend.epsilon())}static get className(){return"Adamax"}applyGradients(e){const t=Array.isArray(e)?e.map((e=>e.name)):Object.keys(e);si((()=>{const n=Ja(1,this.accBeta1),i=ki(-this.learningRate,bi(xi(this.iteration,this.decay),1));t.forEach(((t,a)=>{const s=sn.registeredVariables[t];null==this.accumulatedFirstMoment[a]&&(this.accumulatedFirstMoment[a]={originalName:`${t}/m`,variable:ya(s).variable(false)}),null==this.accumulatedWeightedInfNorm[a]&&(this.accumulatedWeightedInfNorm[a]={originalName:`${t}/v`,variable:ya(s).variable(false)});const r=Array.isArray(e)?e[a].tensor:e[t];if(null==r)return;const o=this.accumulatedFirstMoment[a].variable,l=this.accumulatedWeightedInfNorm[a].variable,c=bi(xi(o,this.beta1),xi(r,1-this.beta1)),u=xi(l,this.beta2),h=Si(r),p=ts(u,h);o.assign(c),l.assign(p);const d=bi(xi(ki(i,n),ki(c,bi(p,this.epsilon))),s);s.assign(d)})),this.iteration.assign(bi(this.iteration,1)),this.accBeta1.assign(xi(this.accBeta1,this.beta1))})),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.iteration.dispose(),null!=this.accumulatedFirstMoment&&ri(this.accumulatedFirstMoment.map((e=>e.variable))),null!=this.accumulatedWeightedInfNorm&&ri(this.accumulatedWeightedInfNorm.map((e=>e.variable)))}async getWeights(){throw new Error("getWeights() is not implemented for Adamax yet.")}async setWeights(e){throw new Error("setWeights() is not implemented for Adamax yet.")}getConfig(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon,decay:this.decay}}static fromConfig(e,t){return new e(t.learningRate,t.beta1,t.beta2,t.epsilon,t.decay)}}
2987
2987
  /**
2988
2988
  * @license
2989
2989
  * Copyright 2018 Google LLC. All Rights Reserved.
@@ -2999,7 +2999,7 @@ class _r extends Fr{constructor(e,t,n=null){super(),this.learningRate=e,this.rho
2999
2999
  * See the License for the specific language governing permissions and
3000
3000
  * limitations under the License.
3001
3001
  * =============================================================================
3002
- */class Or extends Fr{constructor(e){super(),this.learningRate=e,this.setLearningRate(e)}static get className(){return"SGD"}applyGradients(e){(Array.isArray(e)?e.map((e=>e.name)):Object.keys(e)).forEach(((t,n)=>{const i=Array.isArray(e)?e[n].tensor:e[t];if(null==i)return;const a=sn.registeredVariables[t];si((()=>{const e=bi(xi(this.c,i),a);a.assign(e)}))})),this.incrementIterations()}setLearningRate(e){this.learningRate=e,null!=this.c&&this.c.dispose(),this.c=oi(Aa(-e))}dispose(){this.c.dispose()}async getWeights(){return[await this.saveIterations()]}async setWeights(e){if(0!==(e=await this.extractIterations(e)).length)throw new Error("SGD optimizer does not have settable weights.")}getConfig(){return{learningRate:this.learningRate}}static fromConfig(e,t){return new e(t.learningRate)}}
3002
+ */class Or extends Fr{constructor(e){super(),this.learningRate=e,this.setLearningRate(e)}static get className(){return"SGD"}applyGradients(e){(Array.isArray(e)?e.map((e=>e.name)):Object.keys(e)).forEach(((t,n)=>{const i=Array.isArray(e)?e[n].tensor:e[t];if(null==i)return;const a=sn.registeredVariables[t];si((()=>{const e=bi(xi(this.c,i),a);a.assign(e)}))})),this.incrementIterations()}setLearningRate(e){this.learningRate=e,null!=this.c&&this.c.dispose(),this.c=oi(Ca(-e))}dispose(){this.c.dispose()}async getWeights(){return[await this.saveIterations()]}async setWeights(e){if(0!==(e=await this.extractIterations(e)).length)throw new Error("SGD optimizer does not have settable weights.")}getConfig(){return{learningRate:this.learningRate}}static fromConfig(e,t){return new e(t.learningRate)}}
3003
3003
  /**
3004
3004
  * @license
3005
3005
  * Copyright 2018 Google LLC. All Rights Reserved.
@@ -3015,7 +3015,7 @@ class _r extends Fr{constructor(e,t,n=null){super(),this.learningRate=e,this.rho
3015
3015
  * See the License for the specific language governing permissions and
3016
3016
  * limitations under the License.
3017
3017
  * =============================================================================
3018
- */class Pr extends Or{constructor(e,t,n=!1){super(e),this.learningRate=e,this.momentum=t,this.useNesterov=n,this.accumulations=[],this.m=Aa(this.momentum)}static get className(){return"Momentum"}applyGradients(e){(Array.isArray(e)?e.map((e=>e.name)):Object.keys(e)).forEach(((t,n)=>{const i=sn.registeredVariables[t];if(null==this.accumulations[n]){const e=!1;this.accumulations[n]={originalName:`${t}/momentum`,variable:si((()=>ya(i).variable(e)))}}const a=this.accumulations[n].variable,s=Array.isArray(e)?e[n].tensor:e[t];null!=s&&si((()=>{let e;const t=bi(xi(this.m,a),s);e=this.useNesterov?bi(xi(this.c,bi(s,xi(t,this.m))),i):bi(xi(this.c,t),i),a.assign(t),i.assign(e)}))})),this.incrementIterations()}dispose(){this.m.dispose(),null!=this.accumulations&&ri(this.accumulations.map((e=>e.variable)))}setMomentum(e){this.momentum=e}async getWeights(){return[await this.saveIterations()].concat(this.accumulations.map((e=>({name:e.originalName,tensor:e.variable}))))}async setWeights(e){e=await this.extractIterations(e);this.accumulations=e.map((e=>({originalName:e.name,variable:e.tensor.variable(false)})))}getConfig(){return{learningRate:this.learningRate,momentum:this.momentum,useNesterov:this.useNesterov}}static fromConfig(e,t){return new e(t.learningRate,t.momentum,t.useNesterov)}}
3018
+ */class Pr extends Or{constructor(e,t,n=!1){super(e),this.learningRate=e,this.momentum=t,this.useNesterov=n,this.accumulations=[],this.m=Ca(this.momentum)}static get className(){return"Momentum"}applyGradients(e){(Array.isArray(e)?e.map((e=>e.name)):Object.keys(e)).forEach(((t,n)=>{const i=sn.registeredVariables[t];if(null==this.accumulations[n]){const e=!1;this.accumulations[n]={originalName:`${t}/momentum`,variable:si((()=>ya(i).variable(e)))}}const a=this.accumulations[n].variable,s=Array.isArray(e)?e[n].tensor:e[t];null!=s&&si((()=>{let e;const t=bi(xi(this.m,a),s);e=this.useNesterov?bi(xi(this.c,bi(s,xi(t,this.m))),i):bi(xi(this.c,t),i),a.assign(t),i.assign(e)}))})),this.incrementIterations()}dispose(){this.m.dispose(),null!=this.accumulations&&ri(this.accumulations.map((e=>e.variable)))}setMomentum(e){this.momentum=e}async getWeights(){return[await this.saveIterations()].concat(this.accumulations.map((e=>({name:e.originalName,tensor:e.variable}))))}async setWeights(e){e=await this.extractIterations(e);this.accumulations=e.map((e=>({originalName:e.name,variable:e.tensor.variable(false)})))}getConfig(){return{learningRate:this.learningRate,momentum:this.momentum,useNesterov:this.useNesterov}}static fromConfig(e,t){return new e(t.learningRate,t.momentum,t.useNesterov)}}
3019
3019
  /**
3020
3020
  * @license
3021
3021
  * Copyright 2018 Google LLC. All Rights Reserved.
@@ -3031,7 +3031,7 @@ class _r extends Fr{constructor(e,t,n=null){super(),this.learningRate=e,this.rho
3031
3031
  * See the License for the specific language governing permissions and
3032
3032
  * limitations under the License.
3033
3033
  * =============================================================================
3034
- */class Br extends Fr{constructor(e,t=.9,n=0,i=null,a=!1){if(super(),this.learningRate=e,this.decay=t,this.momentum=n,this.epsilon=i,this.accumulatedMeanSquares=[],this.accumulatedMoments=[],this.accumulatedMeanGrads=[],this.centered=a,null==i&&(this.epsilon=sn.backend.epsilon()),null==e)throw new Error("learningRate for RMSPropOptimizer must be defined.")}static get className(){return"RMSProp"}applyGradients(e){(Array.isArray(e)?e.map((e=>e.name)):Object.keys(e)).forEach(((t,n)=>{const i=sn.registeredVariables[t],a=!1;null==this.accumulatedMeanSquares[n]&&(this.accumulatedMeanSquares[n]={originalName:`${t}/rms`,variable:si((()=>ya(i).variable(a)))}),null==this.accumulatedMoments[n]&&(this.accumulatedMoments[n]={originalName:`${t}/momentum`,variable:si((()=>ya(i).variable(a)))}),null==this.accumulatedMeanGrads[n]&&this.centered&&(this.accumulatedMeanGrads[n]={originalName:`${t}/mg`,variable:si((()=>ya(i).variable(a)))});const s=Array.isArray(e)?e[n].tensor:e[t];if(null==s)return;const r=this.accumulatedMeanSquares[n].variable,o=this.accumulatedMoments[n].variable;si((()=>{const e=bi(xi(r,this.decay),xi($a(s),1-this.decay));if(this.centered){const t=this.accumulatedMeanGrads[n].variable,a=bi(xi(t,this.decay),xi(s,1-this.decay)),l=ki(xi(s,this.learningRate),Ca(Ja(e,bi($a(a),this.epsilon)))),c=bi(xi(o,this.momentum),l);r.assign(e),t.assign(a),o.assign(c);const u=Ja(i,c);i.assign(u)}else{const e=bi(xi(r,this.decay),xi($a(s),1-this.decay)),t=bi(xi(o,this.momentum),ki(xi(s,this.learningRate),Ca(bi(e,this.epsilon))));r.assign(e),o.assign(t);const n=Ja(i,t);i.assign(n)}}))})),this.incrementIterations()}dispose(){null!=this.accumulatedMeanSquares&&ri(this.accumulatedMeanSquares.map((e=>e.variable))),null!=this.accumulatedMeanGrads&&this.centered&&ri(this.accumulatedMeanGrads.map((e=>e.variable))),null!=this.accumulatedMoments&&ri(this.accumulatedMoments.map((e=>e.variable)))}async getWeights(){const e=[...this.accumulatedMeanSquares,...this.accumulatedMoments];return this.centered&&e.push(...this.accumulatedMeanGrads),[await this.saveIterations()].concat(e.map((e=>({name:e.originalName,tensor:e.variable}))))}async setWeights(e){e=await this.extractIterations(e);const t=this.centered?e.length/3:e.length/2,n=!1;this.accumulatedMeanSquares=e.slice(0,t).map((e=>({originalName:e.name,variable:e.tensor.variable(n)}))),this.accumulatedMoments=e.slice(t,2*t).map((e=>({originalName:e.name,variable:e.tensor.variable(n)}))),this.centered&&(this.accumulatedMeanGrads=e.slice(2*t,3*t).map((e=>({originalName:e.name,variable:e.tensor.variable(n)}))))}getConfig(){return{learningRate:this.learningRate,decay:this.decay,momentum:this.momentum,epsilon:this.epsilon,centered:this.centered}}static fromConfig(e,t){return new e(t.learningRate,t.decay,t.momentum,t.epsilon,t.centered)}}
3034
+ */class Br extends Fr{constructor(e,t=.9,n=0,i=null,a=!1){if(super(),this.learningRate=e,this.decay=t,this.momentum=n,this.epsilon=i,this.accumulatedMeanSquares=[],this.accumulatedMoments=[],this.accumulatedMeanGrads=[],this.centered=a,null==i&&(this.epsilon=sn.backend.epsilon()),null==e)throw new Error("learningRate for RMSPropOptimizer must be defined.")}static get className(){return"RMSProp"}applyGradients(e){(Array.isArray(e)?e.map((e=>e.name)):Object.keys(e)).forEach(((t,n)=>{const i=sn.registeredVariables[t],a=!1;null==this.accumulatedMeanSquares[n]&&(this.accumulatedMeanSquares[n]={originalName:`${t}/rms`,variable:si((()=>ya(i).variable(a)))}),null==this.accumulatedMoments[n]&&(this.accumulatedMoments[n]={originalName:`${t}/momentum`,variable:si((()=>ya(i).variable(a)))}),null==this.accumulatedMeanGrads[n]&&this.centered&&(this.accumulatedMeanGrads[n]={originalName:`${t}/mg`,variable:si((()=>ya(i).variable(a)))});const s=Array.isArray(e)?e[n].tensor:e[t];if(null==s)return;const r=this.accumulatedMeanSquares[n].variable,o=this.accumulatedMoments[n].variable;si((()=>{const e=bi(xi(r,this.decay),xi($a(s),1-this.decay));if(this.centered){const t=this.accumulatedMeanGrads[n].variable,a=bi(xi(t,this.decay),xi(s,1-this.decay)),l=ki(xi(s,this.learningRate),Ea(Ja(e,bi($a(a),this.epsilon)))),c=bi(xi(o,this.momentum),l);r.assign(e),t.assign(a),o.assign(c);const u=Ja(i,c);i.assign(u)}else{const e=bi(xi(r,this.decay),xi($a(s),1-this.decay)),t=bi(xi(o,this.momentum),ki(xi(s,this.learningRate),Ea(bi(e,this.epsilon))));r.assign(e),o.assign(t);const n=Ja(i,t);i.assign(n)}}))})),this.incrementIterations()}dispose(){null!=this.accumulatedMeanSquares&&ri(this.accumulatedMeanSquares.map((e=>e.variable))),null!=this.accumulatedMeanGrads&&this.centered&&ri(this.accumulatedMeanGrads.map((e=>e.variable))),null!=this.accumulatedMoments&&ri(this.accumulatedMoments.map((e=>e.variable)))}async getWeights(){const e=[...this.accumulatedMeanSquares,...this.accumulatedMoments];return this.centered&&e.push(...this.accumulatedMeanGrads),[await this.saveIterations()].concat(e.map((e=>({name:e.originalName,tensor:e.variable}))))}async setWeights(e){e=await this.extractIterations(e);const t=this.centered?e.length/3:e.length/2,n=!1;this.accumulatedMeanSquares=e.slice(0,t).map((e=>({originalName:e.name,variable:e.tensor.variable(n)}))),this.accumulatedMoments=e.slice(t,2*t).map((e=>({originalName:e.name,variable:e.tensor.variable(n)}))),this.centered&&(this.accumulatedMeanGrads=e.slice(2*t,3*t).map((e=>({originalName:e.name,variable:e.tensor.variable(n)}))))}getConfig(){return{learningRate:this.learningRate,decay:this.decay,momentum:this.momentum,epsilon:this.epsilon,centered:this.centered}}static fromConfig(e,t){return new e(t.learningRate,t.decay,t.momentum,t.epsilon,t.centered)}}
3035
3035
  /**
3036
3036
  * @license
3037
3037
  * Copyright 2018 Google LLC. All Rights Reserved.
@@ -3080,7 +3080,7 @@ const Ur=class{static sgd(e){return new Or(e)}static momentum(e,t,n=!1){return n
3080
3080
  * See the License for the specific language governing permissions and
3081
3081
  * limitations under the License.
3082
3082
  * =============================================================================
3083
- */function Gr(){return new Promise((e=>Wr((()=>e()))))}
3083
+ */function Vr(){return new Promise((e=>Wr((()=>e()))))}
3084
3084
  /**
3085
3085
  * @license
3086
3086
  * Copyright 2018 Google LLC. All Rights Reserved.
@@ -3113,7 +3113,7 @@ const Ur=class{static sgd(e){return new Or(e)}static momentum(e,t,n=!1){return n
3113
3113
  * limitations under the License.
3114
3114
  * =============================================================================
3115
3115
  */
3116
- function Vr(e,t){if(e.length!==t.length)throw new Error(`Cannot merge real and imag arrays of different lengths. real:${e.length}, imag: ${t.length}.`);const n=new Float32Array(2*e.length);for(let i=0;i<n.length;i+=2)n[i]=e[i/2],n[i+1]=t[i/2];return n}
3116
+ function Gr(e,t){if(e.length!==t.length)throw new Error(`Cannot merge real and imag arrays of different lengths. real:${e.length}, imag: ${t.length}.`);const n=new Float32Array(2*e.length);for(let i=0;i<n.length;i+=2)n[i]=e[i/2],n[i+1]=t[i/2];return n}
3117
3117
  /**
3118
3118
  * @license
3119
3119
  * Copyright 2018 Google LLC. All Rights Reserved.
@@ -3146,7 +3146,7 @@ function Vr(e,t){if(e.length!==t.length)throw new Error(`Cannot merge real and i
3146
3146
  * limitations under the License.
3147
3147
  * =============================================================================
3148
3148
  */
3149
- function Kr(e){try{return e.map((e=>At(e)))}catch(e){throw new Error(`Failed to decode encoded string bytes into utf-8, error: ${e}`)}}
3149
+ function Kr(e){try{return e.map((e=>Ct(e)))}catch(e){throw new Error(`Failed to decode encoded string bytes into utf-8, error: ${e}`)}}
3150
3150
  /**
3151
3151
  * @license
3152
3152
  * Copyright 2019 Google LLC. All Rights Reserved.
@@ -3163,7 +3163,7 @@ function Kr(e){try{return e.map((e=>At(e)))}catch(e){throw new Error(`Failed to
3163
3163
  * limitations under the License.
3164
3164
  * =============================================================================
3165
3165
  */
3166
- class qr{constructor(){this.messageName="setTimeoutCustom",this.functionRefs=[],this.handledMessageCount=0,this.hasEventListener=!1}fetch(e,t){return fetch(e,t)}now(){return performance.now()}encode(e,t){if("utf-8"!==t&&"utf8"!==t)throw new Error(`Browser's encoder only supports utf-8, but got ${t}`);return null==this.textEncoder&&(this.textEncoder=new TextEncoder),this.textEncoder.encode(e)}decode(e,t){return new TextDecoder(t).decode(e)}setTimeoutCustom(e,t){"undefined"!=typeof window&&Q().getBool("USE_SETTIMEOUTCUSTOM")?(this.functionRefs.push(e),setTimeout((()=>{window.postMessage({name:this.messageName,index:this.functionRefs.length-1},"*")}),t),this.hasEventListener||(this.hasEventListener=!0,window.addEventListener("message",(e=>{if(e.source===window&&e.data.name===this.messageName){e.stopPropagation();(0,this.functionRefs[e.data.index])(),this.handledMessageCount++,this.handledMessageCount===this.functionRefs.length&&(this.functionRefs=[],this.handledMessageCount=0)}}),!0))):setTimeout(e,t)}isTypedArray(e){return e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray}}if(Q().get("IS_BROWSER")){Q().setPlatform("browser",new qr);try{Xn.registerManager(Vn.URL_SCHEME,new qn)}catch(e){}try{Xn.registerManager(zn.URL_SCHEME,new Fn)}catch(e){}}
3166
+ class qr{constructor(){this.messageName="setTimeoutCustom",this.functionRefs=[],this.handledMessageCount=0,this.hasEventListener=!1}fetch(e,t){return fetch(e,t)}now(){return performance.now()}encode(e,t){if("utf-8"!==t&&"utf8"!==t)throw new Error(`Browser's encoder only supports utf-8, but got ${t}`);return null==this.textEncoder&&(this.textEncoder=new TextEncoder),this.textEncoder.encode(e)}decode(e,t){return new TextDecoder(t).decode(e)}setTimeoutCustom(e,t){"undefined"!=typeof window&&Q().getBool("USE_SETTIMEOUTCUSTOM")?(this.functionRefs.push(e),setTimeout((()=>{window.postMessage({name:this.messageName,index:this.functionRefs.length-1},"*")}),t),this.hasEventListener||(this.hasEventListener=!0,window.addEventListener("message",(e=>{if(e.source===window&&e.data.name===this.messageName){e.stopPropagation();(0,this.functionRefs[e.data.index])(),this.handledMessageCount++,this.handledMessageCount===this.functionRefs.length&&(this.functionRefs=[],this.handledMessageCount=0)}}),!0))):setTimeout(e,t)}isTypedArray(e){return e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray}}if(Q().get("IS_BROWSER")){Q().setPlatform("browser",new qr);try{Xn.registerManager(Gn.URL_SCHEME,new qn)}catch(e){}try{Xn.registerManager(zn.URL_SCHEME,new Fn)}catch(e){}}
3167
3167
  /**
3168
3168
  * @license
3169
3169
  * Copyright 2019 Google LLC. All Rights Reserved.
@@ -3230,7 +3230,7 @@ var Yr,Qr;
3230
3230
  * limitations under the License.
3231
3231
  * =============================================================================
3232
3232
  */
3233
- function Xr(e,t){Array.isArray(e)||(e=[e]),e.forEach((e=>{null!=e&&I("complex64"!==e.dtype,(()=>`${t} does not support complex64 tensors in the CPU backend.`))}))}
3233
+ function Xr(e,t){Array.isArray(e)||(e=[e]),e.forEach((e=>{null!=e&&T("complex64"!==e.dtype,(()=>`${t} does not support complex64 tensors in the CPU backend.`))}))}
3234
3234
  /**
3235
3235
  * @license
3236
3236
  * Copyright 2021 Google LLC. All Rights Reserved.
@@ -3263,7 +3263,7 @@ function Xr(e,t){Array.isArray(e)||(e=[e]),e.forEach((e=>{null!=e&&I("complex64"
3263
3263
  * limitations under the License.
3264
3264
  * =============================================================================
3265
3265
  */
3266
- function(e,t){const n=[];for(let e=0;e<t.length;e++)t[e]&&n.push(e);const i=Zi(e,"int32"),a=Zi([n.length,e.length],"int32");for(let t=0;t<n.length;t++){const s=i.indexToLoc(n[t]),r=t*e.length;a.values.set(s,r)}return a.toTensor()};class to extends k{constructor(){super(),this.blockSize=48,this.firstUse=!0,this.data=new w(this,ii())}nextDataId(){return to.nextDataId++}write(e,t,n){this.firstUse&&(this.firstUse=!1,Q().get("IS_NODE")&&gt("\n============================\nHi, looks like you are running TensorFlow.js in Node.js. To speed things up dramatically, install our node backend, visit https://github.com/tensorflow/tfjs-node for more details. \n============================"));const i={id:this.nextDataId()};return this.data.set(i,{values:e,dtype:n,refCount:1}),i}makeTensorInfo(e,t,n){let i;if("string"===t&&null!=n&&n.length>0&&R(n[0])){const a=n.map((e=>Et(e)));i=this.write(a,e,t)}else i=this.write(n,e,t);return{dataId:i,shape:e,dtype:t}}refCount(e){if(this.data.has(e)){return this.data.get(e).refCount}return 0}incRef(e){this.data.get(e).refCount++}decRef(e){if(this.data.has(e)){this.data.get(e).refCount--}}move(e,t,n,i,a){this.data.set(e,{values:t,dtype:i,refCount:a})}numDataIds(){return this.data.numDataIds()}async read(e){return this.readSync(e)}readSync(e){const{dtype:t,complexTensorInfos:n}=this.data.get(e);if("complex64"===t){return Vr(this.readSync(n.real.dataId),this.readSync(n.imag.dataId))}return function(e,t){if(Array.isArray(e))return e;if("float32"===t)return e instanceof Float32Array?e:new Float32Array(e);if("int32"===t)return e instanceof Int32Array?e:new Int32Array(e);if("bool"===t||"string"===t)return Uint8Array.from(new Int32Array(e));throw new Error(`Unknown dtype ${t}`)}(this.data.get(e).values,t)}bufferSync(e){const t=this.readSync(e.dataId);if("string"===e.dtype)try{const n=t.map((e=>At(e)));return Zi(e.shape,e.dtype,n)}catch(e){throw new Error("Failed to decode encoded string bytes into utf-8")}return Zi(e.shape,e.dtype,t)}makeOutput(e,t,n){return ii().makeTensorFromTensorInfo(this.makeTensorInfo(t,n,e),this)}disposeData(e,t=!1){if(this.data.has(e)){if(this.data.get(e).refCount--,!t&&this.data.get(e).refCount>0)return!1;const{complexTensorInfos:n}=this.data.get(e);null!=n&&(this.disposeData(n.real.dataId,!0),this.disposeData(n.imag.dataId,!0)),this.data.delete(e)}return!0}disposeIntermediateTensorInfo(e){this.disposeData(e.dataId)}async time(e){const t=Tt();e();return{kernelMs:Tt()-t}}memory(){return{unreliable:!0,reasons:["The reported memory is an upper bound. Due to automatic garbage collection, the true allocated memory may be less."]}}where(e){Xr([e],"where");const t=this.readSync(e.dataId);return eo(e.shape,t)}dispose(){}floatPrecision(){return 32}epsilon(){return super.epsilon()}}
3266
+ function(e,t){const n=[];for(let e=0;e<t.length;e++)t[e]&&n.push(e);const i=Zi(e,"int32"),a=Zi([n.length,e.length],"int32");for(let t=0;t<n.length;t++){const s=i.indexToLoc(n[t]),r=t*e.length;a.values.set(s,r)}return a.toTensor()};class to extends k{constructor(){super(),this.blockSize=48,this.firstUse=!0,this.data=new w(this,ii())}nextDataId(){return to.nextDataId++}write(e,t,n){this.firstUse&&(this.firstUse=!1,Q().get("IS_NODE")&&gt("\n============================\nHi, looks like you are running TensorFlow.js in Node.js. To speed things up dramatically, install our node backend, visit https://github.com/tensorflow/tfjs-node for more details. \n============================"));const i={id:this.nextDataId()};return this.data.set(i,{values:e,dtype:n,refCount:1}),i}makeTensorInfo(e,t,n){let i;if("string"===t&&null!=n&&n.length>0&&R(n[0])){const a=n.map((e=>At(e)));i=this.write(a,e,t)}else i=this.write(n,e,t);return{dataId:i,shape:e,dtype:t}}refCount(e){if(this.data.has(e)){return this.data.get(e).refCount}return 0}incRef(e){this.data.get(e).refCount++}decRef(e){if(this.data.has(e)){this.data.get(e).refCount--}}move(e,t,n,i,a){this.data.set(e,{values:t,dtype:i,refCount:a})}numDataIds(){return this.data.numDataIds()}async read(e){return this.readSync(e)}readSync(e){const{dtype:t,complexTensorInfos:n}=this.data.get(e);if("complex64"===t){return Gr(this.readSync(n.real.dataId),this.readSync(n.imag.dataId))}return function(e,t){if(Array.isArray(e))return e;if("float32"===t)return e instanceof Float32Array?e:new Float32Array(e);if("int32"===t)return e instanceof Int32Array?e:new Int32Array(e);if("bool"===t||"string"===t)return Uint8Array.from(new Int32Array(e));throw new Error(`Unknown dtype ${t}`)}(this.data.get(e).values,t)}bufferSync(e){const t=this.readSync(e.dataId);if("string"===e.dtype)try{const n=t.map((e=>Ct(e)));return Zi(e.shape,e.dtype,n)}catch(e){throw new Error("Failed to decode encoded string bytes into utf-8")}return Zi(e.shape,e.dtype,t)}makeOutput(e,t,n){return ii().makeTensorFromTensorInfo(this.makeTensorInfo(t,n,e),this)}disposeData(e,t=!1){if(this.data.has(e)){if(this.data.get(e).refCount--,!t&&this.data.get(e).refCount>0)return!1;const{complexTensorInfos:n}=this.data.get(e);null!=n&&(this.disposeData(n.real.dataId,!0),this.disposeData(n.imag.dataId,!0)),this.data.delete(e)}return!0}disposeIntermediateTensorInfo(e){this.disposeData(e.dataId)}async time(e){const t=It();e();return{kernelMs:It()-t}}memory(){return{unreliable:!0,reasons:["The reported memory is an upper bound. Due to automatic garbage collection, the true allocated memory may be less."]}}where(e){Xr([e],"where");const t=this.readSync(e.dataId);return eo(e.shape,t)}dispose(){}floatPrecision(){return 32}epsilon(){return super.epsilon()}}
3267
3267
  /**
3268
3268
  * @license
3269
3269
  * Copyright 2020 Google LLC. All Rights Reserved.
@@ -3280,7 +3280,7 @@ function(e,t){const n=[];for(let e=0;e<t.length;e++)t[e]&&n.push(e);const i=Zi(e
3280
3280
  * limitations under the License.
3281
3281
  * =============================================================================
3282
3282
  */
3283
- function no(e){return(t,n,i,a,s)=>{const r=mi(t,n),o=r.length,l=P(r),c=D(s,A(r)),u=t.length,h=n.length,p=P(t),d=P(n),m=pi(t,r),f=pi(n,r);if(m.length+f.length===0)for(let t=0;t<c.length;++t)c[t]=e(i[t%i.length],a[t%a.length]);else for(let t=0;t<c.length;++t){const n=q(t,o,l),s=n.slice(-u);m.forEach((e=>s[e]=0));const r=K(s,u,p),g=n.slice(-h);f.forEach((e=>g[e]=0));const v=K(g,h,d);c[t]=e(i[r],a[v])}return[c,r]}}
3283
+ function no(e){return(t,n,i,a,s)=>{const r=mi(t,n),o=r.length,l=P(r),c=D(s,C(r)),u=t.length,h=n.length,p=P(t),d=P(n),m=pi(t,r),f=pi(n,r);if(m.length+f.length===0)for(let t=0;t<c.length;++t)c[t]=e(i[t%i.length],a[t%a.length]);else for(let t=0;t<c.length;++t){const n=q(t,o,l),s=n.slice(-u);m.forEach((e=>s[e]=0));const r=K(s,u,p),g=n.slice(-h);f.forEach((e=>g[e]=0));const v=K(g,h,d);c[t]=e(i[r],a[v])}return[c,r]}}
3284
3284
  /**
3285
3285
  * @license
3286
3286
  * Copyright 2020 Google LLC. All Rights Reserved.
@@ -3312,7 +3312,7 @@ function no(e){return(t,n,i,a,s)=>{const r=mi(t,n),o=r.length,l=P(r),c=D(s,A(r))
3312
3312
  * See the License for the specific language governing permissions and
3313
3313
  * limitations under the License.
3314
3314
  * =============================================================================
3315
- */function ao(e,t,n="float32"){if("complex64"===n){return io({inputs:{real:ao(e,t,"float32"),imag:ao(e,t,"float32")},backend:e})}const i=G(A(t),n);return e.makeTensorInfo(t,n,i)}
3315
+ */function ao(e,t,n="float32"){if("complex64"===n){return io({inputs:{real:ao(e,t,"float32"),imag:ao(e,t,"float32")},backend:e})}const i=V(C(t),n);return e.makeTensorInfo(t,n,i)}
3316
3316
  /**
3317
3317
  * @license
3318
3318
  * Copyright 2020 Google LLC. All Rights Reserved.
@@ -3328,7 +3328,7 @@ function no(e){return(t,n,i,a,s)=>{const r=mi(t,n),o=r.length,l=P(r),c=D(s,A(r))
3328
3328
  * See the License for the specific language governing permissions and
3329
3329
  * limitations under the License.
3330
3330
  * =============================================================================
3331
- */function so(e){const{inputs:t,backend:n}=e,{x:i}=t;return n.incRef(i.dataId),{dataId:i.dataId,shape:i.shape,dtype:i.dtype}}to.nextDataId=0;const ro={kernelName:Ee,backendName:"cpu",kernelFunc:so};
3331
+ */function so(e){const{inputs:t,backend:n}=e,{x:i}=t;return n.incRef(i.dataId),{dataId:i.dataId,shape:i.shape,dtype:i.dtype}}to.nextDataId=0;const ro={kernelName:Ae,backendName:"cpu",kernelFunc:so};
3332
3332
  /**
3333
3333
  * @license
3334
3334
  * Copyright 2020 Google LLC. All Rights Reserved.
@@ -3360,7 +3360,7 @@ function no(e){return(t,n,i,a,s)=>{const r=mi(t,n),o=r.length,l=P(r),c=D(s,A(r))
3360
3360
  * See the License for the specific language governing permissions and
3361
3361
  * limitations under the License.
3362
3362
  * =============================================================================
3363
- */({inputs:{input:a},backend:n}),t=oo({inputs:{x:e},backend:n,attrs:{dtype:s}});return n.disposeIntermediateTensorInfo(e),t}if(r=a.dtype,"complex64"===(o=s)||"float32"===o&&"complex64"!==r||"int32"===o&&"float32"!==r&&"complex64"!==r||"bool"===o&&"bool"===r){const e=so({inputs:{x:a},backend:n});return{dataId:e.dataId,shape:e.shape,dtype:s}}var r,o;const l=n.data.get(a.dataId).values,[c,u,h]=function(e,t,n,i){if("int32"===i)return[t,"int32",Int32Array.from(e)];if("bool"===i){const i=It([0],n),[a,s]=no(((e,t)=>e!==t?1:0))(t,[],e,i,"bool");return[s,"bool",a]}throw new Error(`Error in Cast: failed to cast ${n} to ${i}`)}(l,a.shape,a.dtype,s);return n.makeTensorInfo(c,u,h)}const lo={kernelName:ce,backendName:"cpu",kernelFunc:oo};
3363
+ */({inputs:{input:a},backend:n}),t=oo({inputs:{x:e},backend:n,attrs:{dtype:s}});return n.disposeIntermediateTensorInfo(e),t}if(r=a.dtype,"complex64"===(o=s)||"float32"===o&&"complex64"!==r||"int32"===o&&"float32"!==r&&"complex64"!==r||"bool"===o&&"bool"===r){const e=so({inputs:{x:a},backend:n});return{dataId:e.dataId,shape:e.shape,dtype:s}}var r,o;const l=n.data.get(a.dataId).values,[c,u,h]=function(e,t,n,i){if("int32"===i)return[t,"int32",Int32Array.from(e)];if("bool"===i){const i=Tt([0],n),[a,s]=no(((e,t)=>e!==t?1:0))(t,[],e,i,"bool");return[s,"bool",a]}throw new Error(`Error in Cast: failed to cast ${n} to ${i}`)}(l,a.shape,a.dtype,s);return n.makeTensorInfo(c,u,h)}const lo={kernelName:ce,backendName:"cpu",kernelFunc:oo};
3364
3364
  /**
3365
3365
  * @license
3366
3366
  * Copyright 2020 Google LLC. All Rights Reserved.
@@ -3393,7 +3393,7 @@ function no(e){return(t,n,i,a,s)=>{const r=mi(t,n),o=r.length,l=P(r),c=D(s,A(r))
3393
3393
  * limitations under the License.
3394
3394
  * =============================================================================
3395
3395
  */
3396
- const co=no(((e,t)=>e+t)),uo=function(e){return(t,n,i,a,s,r)=>{const o=mi(t,n),l=A(o),c=o.length,u=P(o),h=D("float32",l),p=D("float32",l),d=pi(t,o),m=pi(n,o),f=Vr(i,a),g=Vr(s,r),v=t.length,y=P(t),b=n.length,w=P(n);if(d.length+m.length===0)for(let t=0;t<h.length;t++){const n=t%f.length,i=t%g.length,a=e(f[2*n],f[2*n+1],g[2*i],g[2*i+1]);h[t]=a.real,p[t]=a.imag}else for(let t=0;t<h.length;t++){const n=q(t,c,u),i=n.slice(-v);d.forEach((e=>i[e]=0));const a=K(i,v,y),s=n.slice(-b);m.forEach((e=>s[e]=0));const r=K(s,b,w),o=e(f[2*a],f[2*a+1],g[2*r],g[2*r+1]);h[t]=o.real,p[t]=o.imag}return[h,p,o]}}(((e,t,n,i)=>({real:e+n,imag:t+i}))),ho=(po=ie,mo=co,null==(fo=uo)?({inputs:e,backend:t})=>{const{a:n,b:i}=e,a=t;Xr([n,i],po);const s=a.data.get(n.dataId).values,r=a.data.get(i.dataId).values,o="string"===n.dtype?Kr(s):s,l="string"===n.dtype?Kr(r):r,c=go||n.dtype,[u,h]=mo(n.shape,i.shape,o,l,c);return a.makeTensorInfo(h,c,u)}:({inputs:e,backend:t})=>{const{a:n,b:i}=e,a=t;if("complex64"===n.dtype||"complex64"===i.dtype){const e=oo({inputs:{x:n},backend:a,attrs:{dtype:"complex64"}}),t=a.data.get(e.dataId),s=t.complexTensorInfos.real,r=t.complexTensorInfos.imag,o=a.data.get(s.dataId).values,l=a.data.get(r.dataId).values,c=oo({inputs:{x:i},backend:a,attrs:{dtype:"complex64"}}),u=a.data.get(c.dataId),h=u.complexTensorInfos.real,p=u.complexTensorInfos.imag,d=a.data.get(h.dataId).values,m=a.data.get(p.dataId).values,[f,g,v]=fo(n.shape,i.shape,o,l,d,m),y=a.makeTensorInfo(v,"float32",f),b=a.makeTensorInfo(v,"float32",g),w=io({inputs:{real:y,imag:b},backend:a});return a.disposeIntermediateTensorInfo(e),a.disposeIntermediateTensorInfo(c),a.disposeIntermediateTensorInfo(y),a.disposeIntermediateTensorInfo(b),w}{const e=a.data.get(n.dataId).values,t=a.data.get(i.dataId).values,s=go||n.dtype,[r,o]=mo(n.shape,i.shape,e,t,s);return a.makeTensorInfo(o,s,r)}});var po,mo,fo,go;const vo={kernelName:ie,backendName:"cpu",kernelFunc:ho};
3396
+ const co=no(((e,t)=>e+t)),uo=function(e){return(t,n,i,a,s,r)=>{const o=mi(t,n),l=C(o),c=o.length,u=P(o),h=D("float32",l),p=D("float32",l),d=pi(t,o),m=pi(n,o),f=Gr(i,a),g=Gr(s,r),v=t.length,y=P(t),b=n.length,w=P(n);if(d.length+m.length===0)for(let t=0;t<h.length;t++){const n=t%f.length,i=t%g.length,a=e(f[2*n],f[2*n+1],g[2*i],g[2*i+1]);h[t]=a.real,p[t]=a.imag}else for(let t=0;t<h.length;t++){const n=q(t,c,u),i=n.slice(-v);d.forEach((e=>i[e]=0));const a=K(i,v,y),s=n.slice(-b);m.forEach((e=>s[e]=0));const r=K(s,b,w),o=e(f[2*a],f[2*a+1],g[2*r],g[2*r+1]);h[t]=o.real,p[t]=o.imag}return[h,p,o]}}(((e,t,n,i)=>({real:e+n,imag:t+i}))),ho=(po=ie,mo=co,null==(fo=uo)?({inputs:e,backend:t})=>{const{a:n,b:i}=e,a=t;Xr([n,i],po);const s=a.data.get(n.dataId).values,r=a.data.get(i.dataId).values,o="string"===n.dtype?Kr(s):s,l="string"===n.dtype?Kr(r):r,c=go||n.dtype,[u,h]=mo(n.shape,i.shape,o,l,c);return a.makeTensorInfo(h,c,u)}:({inputs:e,backend:t})=>{const{a:n,b:i}=e,a=t;if("complex64"===n.dtype||"complex64"===i.dtype){const e=oo({inputs:{x:n},backend:a,attrs:{dtype:"complex64"}}),t=a.data.get(e.dataId),s=t.complexTensorInfos.real,r=t.complexTensorInfos.imag,o=a.data.get(s.dataId).values,l=a.data.get(r.dataId).values,c=oo({inputs:{x:i},backend:a,attrs:{dtype:"complex64"}}),u=a.data.get(c.dataId),h=u.complexTensorInfos.real,p=u.complexTensorInfos.imag,d=a.data.get(h.dataId).values,m=a.data.get(p.dataId).values,[f,g,v]=fo(n.shape,i.shape,o,l,d,m),y=a.makeTensorInfo(v,"float32",f),b=a.makeTensorInfo(v,"float32",g),w=io({inputs:{real:y,imag:b},backend:a});return a.disposeIntermediateTensorInfo(e),a.disposeIntermediateTensorInfo(c),a.disposeIntermediateTensorInfo(y),a.disposeIntermediateTensorInfo(b),w}{const e=a.data.get(n.dataId).values,t=a.data.get(i.dataId).values,s=go||n.dtype,[r,o]=mo(n.shape,i.shape,e,t,s);return a.makeTensorInfo(o,s,r)}});var po,mo,fo,go;const vo={kernelName:ie,backendName:"cpu",kernelFunc:ho};
3397
3397
  /**
3398
3398
  * @license
3399
3399
  * Copyright 2020 Google LLC. All Rights Reserved.
@@ -3409,7 +3409,7 @@ const co=no(((e,t)=>e+t)),uo=function(e){return(t,n,i,a,s,r)=>{const o=mi(t,n),l
3409
3409
  * See the License for the specific language governing permissions and
3410
3410
  * limitations under the License.
3411
3411
  * =============================================================================
3412
- */function yo(e,t,n){return({inputs:i,attrs:a,backend:s})=>{const{x:r}=i;if(Xr(r,e),"string"===r.dtype||"string"===n)throw new Error("unaryKernelFunc does not support string input/output");const o=s,l=o.data.get(r.dataId).values,c=A(r.shape),u=n||r.dtype,h=F(u,c);for(let e=0;e<c;++e)h[e]=t(l[e],a);return o.makeTensorInfo(r.shape,u,h)}}
3412
+ */function yo(e,t,n){return({inputs:i,attrs:a,backend:s})=>{const{x:r}=i;if(Xr(r,e),"string"===r.dtype||"string"===n)throw new Error("unaryKernelFunc does not support string input/output");const o=s,l=o.data.get(r.dataId).values,c=C(r.shape),u=n||r.dtype,h=F(u,c);for(let e=0;e<c;++e)h[e]=t(l[e],a);return o.makeTensorInfo(r.shape,u,h)}}
3413
3413
  /**
3414
3414
  * @license
3415
3415
  * Copyright 2020 Google LLC. All Rights Reserved.
@@ -3459,7 +3459,7 @@ function bo(e){const{inputs:t,attrs:n,backend:i}=e,{x:a}=t,{perm:s}=n;Xr(a,"tran
3459
3459
  * limitations under the License.
3460
3460
  * =============================================================================
3461
3461
  */
3462
- function(e,t,n,i,a){const s=t.length,r=A(t),o=P(t),l=P(a),c=D(n,A(a));for(let t=0;t<r;++t){const n=q(t,s,o),a=new Array(n.length);for(let e=0;e<a.length;e++)a[e]=n[i[e]];c[K(a,s,l)]=e[t]}return c}(i.data.get(a.dataId).values,a.shape,a.dtype,s,o);return{dataId:i.write(l,o,a.dtype),shape:o,dtype:a.dtype}}const wo={kernelName:ct,backendName:"cpu",kernelFunc:bo},ko=yo(Xe,(e=>1/(1+Math.exp(-e)))),xo={kernelName:Xe,backendName:"cpu",kernelFunc:ko};
3462
+ function(e,t,n,i,a){const s=t.length,r=C(t),o=P(t),l=P(a),c=D(n,C(a));for(let t=0;t<r;++t){const n=q(t,s,o),a=new Array(n.length);for(let e=0;e<a.length;e++)a[e]=n[i[e]];c[K(a,s,l)]=e[t]}return c}(i.data.get(a.dataId).values,a.shape,a.dtype,s,o);return{dataId:i.write(l,o,a.dtype),shape:o,dtype:a.dtype}}const wo={kernelName:ct,backendName:"cpu",kernelFunc:bo},ko=yo(Xe,(e=>1/(1+Math.exp(-e)))),xo={kernelName:Xe,backendName:"cpu",kernelFunc:ko};
3463
3463
  /**
3464
3464
  * @license
3465
3465
  * Copyright 2020 Google LLC. All Rights Reserved.
@@ -3492,7 +3492,7 @@ function(e,t,n,i,a){const s=t.length,r=A(t),o=P(t),l=P(a),c=D(n,A(a));for(let t=
3492
3492
  * limitations under the License.
3493
3493
  * =============================================================================
3494
3494
  */
3495
- function So(e,t,n,i,a){const s=function(e,t,n){let i=n.length;for(let e=0;e<n.length;e++)if(n[e]>1){i=e;break}for(let a=i+1;a<n.length;a++)if(t[a]>0||n[a]!==e[a])return!1;return!0}(i,t,n),r=A(n),o=P(i);if(s){const n=function(e,t){let n=e.length>0?e[e.length-1]:1;for(let i=0;i<e.length-1;i++)n+=e[i]*t[i];return n}(t,o);return"string"===a?e.slice(n,n+r):e.subarray(n,n+r)}const l=Zi(i,a,"string"===a?Kr(e):e),c=Zi(n,a);for(let e=0;e<c.size;++e){const n=c.indexToLoc(e),i=n.map(((e,n)=>e+t[n]));c.set(l.get(...i),...n)}return"string"===a?c.values.map((e=>Et(e))):c.values}function No(e){const{inputs:t,backend:n,attrs:i}=e,{x:a}=t,{begin:s,size:r}=i;Xr(a,"slice");const[o,l]=fi(a,s,r);!function(e,t,n){const i=e.shape.length;I(i===t.length,(()=>`Error in slice${i}D: Length of begin ${t} must match the rank of the array (${i}).`)),I(i===n.length,(()=>`Error in slice${i}D: Length of size ${n} must match the rank of the array (${i}).`));for(let a=0;a<i;++a)I(t[a]+n[a]<=e.shape[a],(()=>`Error in slice${i}D: begin[${a}] + size[${a}] (${t[a]+n[a]}) would overflow input.shape[${a}] (${e.shape[a]})`))}(a,o,l);const c=So(n.data.get(a.dataId).values,o,l,a.shape,a.dtype);return n.makeTensorInfo(l,a.dtype,c)}const Io={kernelName:Ye,backendName:"cpu",kernelFunc:No};
3495
+ function So(e,t,n,i,a){const s=function(e,t,n){let i=n.length;for(let e=0;e<n.length;e++)if(n[e]>1){i=e;break}for(let a=i+1;a<n.length;a++)if(t[a]>0||n[a]!==e[a])return!1;return!0}(i,t,n),r=C(n),o=P(i);if(s){const n=function(e,t){let n=e.length>0?e[e.length-1]:1;for(let i=0;i<e.length-1;i++)n+=e[i]*t[i];return n}(t,o);return"string"===a?e.slice(n,n+r):e.subarray(n,n+r)}const l=Zi(i,a,"string"===a?Kr(e):e),c=Zi(n,a);for(let e=0;e<c.size;++e){const n=c.indexToLoc(e),i=n.map(((e,n)=>e+t[n]));c.set(l.get(...i),...n)}return"string"===a?c.values.map((e=>At(e))):c.values}function No(e){const{inputs:t,backend:n,attrs:i}=e,{x:a}=t,{begin:s,size:r}=i;Xr(a,"slice");const[o,l]=fi(a,s,r);!function(e,t,n){const i=e.shape.length;T(i===t.length,(()=>`Error in slice${i}D: Length of begin ${t} must match the rank of the array (${i}).`)),T(i===n.length,(()=>`Error in slice${i}D: Length of size ${n} must match the rank of the array (${i}).`));for(let a=0;a<i;++a)T(t[a]+n[a]<=e.shape[a],(()=>`Error in slice${i}D: begin[${a}] + size[${a}] (${t[a]+n[a]}) would overflow input.shape[${a}] (${e.shape[a]})`))}(a,o,l);const c=So(n.data.get(a.dataId).values,o,l,a.shape,a.dtype);return n.makeTensorInfo(l,a.dtype,c)}const To={kernelName:Ye,backendName:"cpu",kernelFunc:No};
3496
3496
  /**
3497
3497
  * @license
3498
3498
  * Copyright 2019 Google LLC. All Rights Reserved.
@@ -3525,7 +3525,7 @@ function So(e,t,n,i,a){const s=function(e,t,n){let i=n.length;for(let e=0;e<n.le
3525
3525
  * limitations under the License.
3526
3526
  * =============================================================================
3527
3527
  */
3528
- function To(e){const{inputs:t,backend:n,attrs:i}=e,{x:a}=t,{shape:s}=i,r=A(a.shape),o=function(e,t){let n=1,i=-1;for(let t=0;t<e.length;++t)if(e[t]>=0)n*=e[t];else if(-1===e[t]){if(-1!==i)throw Error(`Shapes can only have 1 implicit size. Found -1 at dim ${i} and dim ${t}`);i=t}else if(e[t]<0)throw Error(`Shapes can not be < 0. Found ${e[t]} at dim ${t}`);if(-1===i){if(t>0&&t!==n)throw Error(`Size(${t}) must match the product of shape ${e}`);return e}if(0===n)throw Error(`Cannot infer the missing size in [${e}] when there are 0 elements`);if(t%n!=0)throw Error(`The implicit shape can't be a fractional number. Got ${t} / ${n}`);const a=e.slice();return a[i]=t/n,a}(s,r),l=A(o);I(r===l,(()=>`The new shape (${o}) has ${l} elements and the old shape (${a.shape}) has ${r} elements. The new shape and old shape must have the same number of elements.`)),n.incRef(a.dataId);const c=n.data.get(a.dataId);if(null!=c.complexTensorInfos){const e=c.complexTensorInfos.real,t=c.complexTensorInfos.imag;e.shape=o,t.shape=o}return{dataId:a.dataId,shape:o,dtype:a.dtype}}
3528
+ function Io(e){const{inputs:t,backend:n,attrs:i}=e,{x:a}=t,{shape:s}=i,r=C(a.shape),o=function(e,t){let n=1,i=-1;for(let t=0;t<e.length;++t)if(e[t]>=0)n*=e[t];else if(-1===e[t]){if(-1!==i)throw Error(`Shapes can only have 1 implicit size. Found -1 at dim ${i} and dim ${t}`);i=t}else if(e[t]<0)throw Error(`Shapes can not be < 0. Found ${e[t]} at dim ${t}`);if(-1===i){if(t>0&&t!==n)throw Error(`Size(${t}) must match the product of shape ${e}`);return e}if(0===n)throw Error(`Cannot infer the missing size in [${e}] when there are 0 elements`);if(t%n!=0)throw Error(`The implicit shape can't be a fractional number. Got ${t} / ${n}`);const a=e.slice();return a[i]=t/n,a}(s,r),l=C(o);T(r===l,(()=>`The new shape (${o}) has ${l} elements and the old shape (${a.shape}) has ${r} elements. The new shape and old shape must have the same number of elements.`)),n.incRef(a.dataId);const c=n.data.get(a.dataId);if(null!=c.complexTensorInfos){const e=c.complexTensorInfos.real,t=c.complexTensorInfos.imag;e.shape=o,t.shape=o}return{dataId:a.dataId,shape:o,dtype:a.dtype}}
3529
3529
  /**
3530
3530
  * @license
3531
3531
  * Copyright 2020 Google LLC. All Rights Reserved.
@@ -3542,7 +3542,7 @@ function To(e){const{inputs:t,backend:n,attrs:i}=e,{x:a}=t,{shape:s}=i,r=A(a.sha
3542
3542
  * limitations under the License.
3543
3543
  * =============================================================================
3544
3544
  */
3545
- !function(e,t,n=1){sn.registerBackend(e,t,n)}("cpu",(()=>new to),1);const Eo={kernelName:Ue,backendName:"cpu",kernelFunc:To};
3545
+ !function(e,t,n=1){sn.registerBackend(e,t,n)}("cpu",(()=>new to),1);const Ao={kernelName:Ue,backendName:"cpu",kernelFunc:Io};
3546
3546
  /**
3547
3547
  * @license
3548
3548
  * Copyright 2020 Google LLC. All Rights Reserved.
@@ -3558,7 +3558,7 @@ function To(e){const{inputs:t,backend:n,attrs:i}=e,{x:a}=t,{shape:s}=i,r=A(a.sha
3558
3558
  * See the License for the specific language governing permissions and
3559
3559
  * limitations under the License.
3560
3560
  * =============================================================================
3561
- */const Ao={kernelName:Ie,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:i}=e,{x:a,indices:s}=t,{axis:r,batchDims:o}=i;Xr([a,s],"gatherV2");const l=z(r,a.shape)[0],c=n.data.get(s.dataId).values,u=a.shape[l];for(let e=0;e<c.length;++e){const t=c[e];I(t<=u-1&&t>=0,(()=>`GatherV2: the index value ${t} is not in [0, ${u-1}]`))}let h=o;null==o&&(h=0);const p=A(s.shape),d=function(e,t,n,i){const a=t.shape.length,s=e.shape.length;if(0!==i&&(i<-a||i>a))throw new Error(`Expect batchDims in the range of [-${a}, ${a}], but got ${i}`);if(i<0&&(i+=a),i>s)throw new Error(`batchDims (${i}) must be less than rank(x) (\n ${s}).`);if(n<i)throw new Error(`batchDims (${i}) must be less than or equal to axis (${n}).`);for(let n=0;n<i;++n)if(e.shape[n]!==t.shape[n])throw new Error(`x.shape[${n}]: ${e.shape[n]} should be equal to indices.shape[${n}]: ${t.shape[n]}.`);const r=e.shape[n],o=[];let l=1,c=1,u=1;for(let t=0;t<i;++t)o.push(e.shape[t]),l*=e.shape[t];for(let t=i;t<n;t++)o.push(e.shape[t]),c*=e.shape[t];for(let e=i;e<a;e++)o.push(t.shape[e]);for(let t=n+1;t<s;t++)o.push(e.shape[t]),u*=e.shape[t];return{batchSize:l,sliceSize:u,outerSize:c,dimSize:r,outputShape:o}}(a,s,l,h),m=To({inputs:{x:a},backend:n,attrs:{shape:[d.batchSize,d.outerSize,d.dimSize,d.sliceSize]}}),f=To({inputs:{x:s},backend:n,attrs:{shape:[d.batchSize,p/d.batchSize]}}),g=[d.batchSize,d.outerSize,p/d.batchSize,d.sliceSize],v=n.bufferSync(f),y=function(e,t,n){const i=Zi(n,e.dtype);for(let n=0;n<i.size;++n){const a=i.indexToLoc(n).slice(),s=a[0],r=a[2],o=t.locToIndex([s,r]);a[2]=t.values[o];const l=e.locToIndex(a);0<=l&&l<e.values.length&&(i.values[n]=e.values[l])}return i}(n.bufferSync(m),v,g);return n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(f),n.makeTensorInfo(d.outputShape,y.dtype,y.values)}};
3561
+ */const Co={kernelName:Te,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:i}=e,{x:a,indices:s}=t,{axis:r,batchDims:o}=i;Xr([a,s],"gatherV2");const l=z(r,a.shape)[0],c=n.data.get(s.dataId).values,u=a.shape[l];for(let e=0;e<c.length;++e){const t=c[e];T(t<=u-1&&t>=0,(()=>`GatherV2: the index value ${t} is not in [0, ${u-1}]`))}let h=o;null==o&&(h=0);const p=C(s.shape),d=function(e,t,n,i){const a=t.shape.length,s=e.shape.length;if(0!==i&&(i<-a||i>a))throw new Error(`Expect batchDims in the range of [-${a}, ${a}], but got ${i}`);if(i<0&&(i+=a),i>s)throw new Error(`batchDims (${i}) must be less than rank(x) (\n ${s}).`);if(n<i)throw new Error(`batchDims (${i}) must be less than or equal to axis (${n}).`);for(let n=0;n<i;++n)if(e.shape[n]!==t.shape[n])throw new Error(`x.shape[${n}]: ${e.shape[n]} should be equal to indices.shape[${n}]: ${t.shape[n]}.`);const r=e.shape[n],o=[];let l=1,c=1,u=1;for(let t=0;t<i;++t)o.push(e.shape[t]),l*=e.shape[t];for(let t=i;t<n;t++)o.push(e.shape[t]),c*=e.shape[t];for(let e=i;e<a;e++)o.push(t.shape[e]);for(let t=n+1;t<s;t++)o.push(e.shape[t]),u*=e.shape[t];return{batchSize:l,sliceSize:u,outerSize:c,dimSize:r,outputShape:o}}(a,s,l,h),m=Io({inputs:{x:a},backend:n,attrs:{shape:[d.batchSize,d.outerSize,d.dimSize,d.sliceSize]}}),f=Io({inputs:{x:s},backend:n,attrs:{shape:[d.batchSize,p/d.batchSize]}}),g=[d.batchSize,d.outerSize,p/d.batchSize,d.sliceSize],v=n.bufferSync(f),y=function(e,t,n){const i=Zi(n,e.dtype);for(let n=0;n<i.size;++n){const a=i.indexToLoc(n).slice(),s=a[0],r=a[2],o=t.locToIndex([s,r]);a[2]=t.values[o];const l=e.locToIndex(a);0<=l&&l<e.values.length&&(i.values[n]=e.values[l])}return i}(n.bufferSync(m),v,g);return n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(f),n.makeTensorInfo(d.outputShape,y.dtype,y.values)}};
3562
3562
  /**
3563
3563
  * @license
3564
3564
  * Copyright 2020 Google LLC. All Rights Reserved.
@@ -3574,7 +3574,7 @@ function To(e){const{inputs:t,backend:n,attrs:i}=e,{x:a}=t,{shape:s}=i,r=A(a.sha
3574
3574
  * See the License for the specific language governing permissions and
3575
3575
  * limitations under the License.
3576
3576
  * =============================================================================
3577
- */const Co={kernelName:nt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:i}=e,{x:a}=t,{axis:s,keepDims:r}=i;let o;Xr(a,"sum"),o="bool"===a.dtype?oo({inputs:{x:a},backend:n,attrs:{dtype:"int32"}}):so({inputs:{x:a},backend:n});const l=o.shape.length,c=z(s,o.shape),u=Sa(c,l);let h=c,p=o;null!=u&&(p=bo({inputs:{x:o},backend:n,attrs:{perm:u}}),h=function(e,t){const n=[];for(let i=t-e;i<t;++i)n.push(i);return n}(h.length,l)),function(e,t,n){I(wa(t,n),(()=>`${e} supports only inner-most axes for now. Got axes ${t} and rank-${n} input.`))}("sum",h,p.shape.length);const[d,m]=ka(p.shape,h);let f=ao(n,d,Zt(p.dtype,"int32"));const g=A(m),v=n.data.get(f.dataId).values,y=n.data.get(p.dataId).values;for(let e=0;e<v.length;++e){const t=e*g;let n=0;for(let e=0;e<g;++e)n+=y[t+e];v[e]=n}if(r){const e=f;f=To({inputs:{x:f},backend:n,attrs:{shape:xa(f.shape,c)}}),n.disposeIntermediateTensorInfo(e)}return n.disposeIntermediateTensorInfo(o),null!=u&&n.disposeIntermediateTensorInfo(p),f}};
3577
+ */const Eo={kernelName:nt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:i}=e,{x:a}=t,{axis:s,keepDims:r}=i;let o;Xr(a,"sum"),o="bool"===a.dtype?oo({inputs:{x:a},backend:n,attrs:{dtype:"int32"}}):so({inputs:{x:a},backend:n});const l=o.shape.length,c=z(s,o.shape),u=Sa(c,l);let h=c,p=o;null!=u&&(p=bo({inputs:{x:o},backend:n,attrs:{perm:u}}),h=function(e,t){const n=[];for(let i=t-e;i<t;++i)n.push(i);return n}(h.length,l)),function(e,t,n){T(wa(t,n),(()=>`${e} supports only inner-most axes for now. Got axes ${t} and rank-${n} input.`))}("sum",h,p.shape.length);const[d,m]=ka(p.shape,h);let f=ao(n,d,Zt(p.dtype,"int32"));const g=C(m),v=n.data.get(f.dataId).values,y=n.data.get(p.dataId).values;for(let e=0;e<v.length;++e){const t=e*g;let n=0;for(let e=0;e<g;++e)n+=y[t+e];v[e]=n}if(r){const e=f;f=Io({inputs:{x:f},backend:n,attrs:{shape:xa(f.shape,c)}}),n.disposeIntermediateTensorInfo(e)}return n.disposeIntermediateTensorInfo(o),null!=u&&n.disposeIntermediateTensorInfo(p),f}};
3578
3578
  /**
3579
3579
  * @license
3580
3580
  * Copyright 2020 Google LLC. All Rights Reserved.
@@ -3606,7 +3606,7 @@ function To(e){const{inputs:t,backend:n,attrs:i}=e,{x:a}=t,{shape:s}=i,r=A(a.sha
3606
3606
  * See the License for the specific language governing permissions and
3607
3607
  * limitations under the License.
3608
3608
  * =============================================================================
3609
- */const jo={kernelName:ut,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:i}=e,{value:a}=t;let{axis:s}=i;s<0&&(s+=a.shape.length);const r=a.shape.length,o=a.shape[s],l=new Array(r-1);let c=0;for(let e=0;e<r;e++)e!==s&&(l[c++]=a.shape[e]);const u=new Array(r).fill(0),h=a.shape.slice();h[s]=1;const p=new Array(o);for(let e=0;e<p.length;e++){u[s]=e;const t=No({inputs:{x:a},backend:n,attrs:{begin:u,size:h}});p[e]=To({inputs:{x:t},backend:n,attrs:{shape:l}}),n.disposeIntermediateTensorInfo(t)}return p}},zo=yo(we,(e=>e>=0?e:Math.exp(e)-1));
3609
+ */const jo={kernelName:ut,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:i}=e,{value:a}=t;let{axis:s}=i;s<0&&(s+=a.shape.length);const r=a.shape.length,o=a.shape[s],l=new Array(r-1);let c=0;for(let e=0;e<r;e++)e!==s&&(l[c++]=a.shape[e]);const u=new Array(r).fill(0),h=a.shape.slice();h[s]=1;const p=new Array(o);for(let e=0;e<p.length;e++){u[s]=e;const t=No({inputs:{x:a},backend:n,attrs:{begin:u,size:h}});p[e]=Io({inputs:{x:t},backend:n,attrs:{shape:l}}),n.disposeIntermediateTensorInfo(t)}return p}},zo=yo(we,(e=>e>=0?e:Math.exp(e)-1));
3610
3610
  /**
3611
3611
  * @license
3612
3612
  * Copyright 2020 Google LLC. All Rights Reserved.
@@ -3656,7 +3656,7 @@ const Do=no(((e,t)=>e<0?t*e:e));
3656
3656
  * limitations under the License.
3657
3657
  * =============================================================================
3658
3658
  */
3659
- const Fo=yo(Be,(e=>Math.max(0,e))),_o={kernelName:Be,backendName:"cpu",kernelFunc:Fo},Ro=yo(Ve,(e=>Math.min(Math.max(0,e),6)));
3659
+ const Fo=yo(Be,(e=>Math.max(0,e))),_o={kernelName:Be,backendName:"cpu",kernelFunc:Fo},Ro=yo(Ge,(e=>Math.min(Math.max(0,e),6)));
3660
3660
  /**
3661
3661
  * @license
3662
3662
  * Copyright 2020 Google LLC. All Rights Reserved.
@@ -3690,7 +3690,7 @@ function Lo(e,t,n,i,a){if("linear"===n)return so({inputs:{x:t},backend:e});if("r
3690
3690
  * limitations under the License.
3691
3691
  * =============================================================================
3692
3692
  */
3693
- return function(e){const{inputs:t,backend:n,attrs:i}=e,{x:a}=t,{alpha:s}=i;Xr([a],"leakyRelu");const r=A(a.shape),o=n.data.get(a.dataId).values,l=D("float32",r);for(let e=0;e<o.length;e++)l[e]=o[e]<0?s*o[e]:o[e];return n.makeTensorInfo(a.shape,"float32",l)}({inputs:{x:t},backend:e,attrs:{alpha:a}});if("sigmoid"===n)return ko({inputs:{x:t},backend:e});throw new Error(`Activation ${n} has not been implemented for the CPU backend.`)}
3693
+ return function(e){const{inputs:t,backend:n,attrs:i}=e,{x:a}=t,{alpha:s}=i;Xr([a],"leakyRelu");const r=C(a.shape),o=n.data.get(a.dataId).values,l=D("float32",r);for(let e=0;e<o.length;e++)l[e]=o[e]<0?s*o[e]:o[e];return n.makeTensorInfo(a.shape,"float32",l)}({inputs:{x:t},backend:e,attrs:{alpha:a}});if("sigmoid"===n)return ko({inputs:{x:t},backend:e});throw new Error(`Activation ${n} has not been implemented for the CPU backend.`)}
3694
3694
  /**
3695
3695
  * @license
3696
3696
  * Copyright 2020 Google LLC. All Rights Reserved.
@@ -3723,7 +3723,7 @@ return function(e){const{inputs:t,backend:n,attrs:i}=e,{x:a}=t,{alpha:s}=i;Xr([a
3723
3723
  * limitations under the License.
3724
3724
  * =============================================================================
3725
3725
  */
3726
- function(e){const{inputs:t,backend:n,attrs:i}=e,{a:a,b:s,bias:r,preluActivationWeights:o}=t,{transposeA:l,transposeB:c,activation:u,leakyreluAlpha:h}=i;let p,d,m;const f=[],g=function(e){const{inputs:t,backend:n,attrs:i}=e,{a:a,b:s}=t,{transposeA:r,transposeB:o}=i;Xr([a,s],"matMul");const l=a.shape.length,c=s.shape.length,u=r?a.shape[l-2]:a.shape[l-1],h=o?s.shape[c-1]:s.shape[c-2],p=r?a.shape[l-1]:a.shape[l-2],d=o?s.shape[c-2]:s.shape[c-1],m=a.shape.slice(0,-2),f=s.shape.slice(0,-2),g=A(m),v=A(f),y=mi(a.shape.slice(0,-2),s.shape.slice(0,-2)).concat([p,d]);I(u===h,(()=>`Error in matMul: inner shapes (${u}) and (${h}) of Tensors with shapes ${a.shape} and ${s.shape} and transposeA=${r} and transposeB=${o} must match.`));const b=o?[v,d,h]:[v,h,d],w=To({inputs:{x:a},backend:n,attrs:{shape:r?[g,u,p]:[g,p,u]}}),k=To({inputs:{x:s},backend:n,attrs:{shape:b}}),x=r?w.shape[1]:w.shape[2],S=r?w.shape[2]:w.shape[1],N=o?k.shape[1]:k.shape[2],T=Math.max(g,v),E=n.data.get(w.dataId).values,C=n.data.get(k.dataId).values,$=P(w.shape),j=P(k.shape),[z,D,F]=r?[$[0],1,$[1]]:[$[0],$[1],1],[_,R,L]=o?[1,j[1],j[0]]:[j[1],1,j[0]],M=S*N,O=Zi([T,S,N],w.dtype),B=O.values,U=n.blockSize;for(let e=0;e<T;e++){const t=e%g,n=e%v;for(let i=0;i<S;i+=U){const a=Math.min(i+U,S);for(let s=0;s<N;s+=U){const r=Math.min(s+U,N);for(let o=0;o<x;o+=U){const l=Math.min(o+U,x);for(let c=i;c<a;c++)for(let i=s;i<r;i++){let a=0;for(let e=o;e<l;e++)a+=E[t*z+c*D+e*F]*C[e*_+i*R+n*L];B[e*M+(c*N+i)]+=a}}}}}return n.disposeIntermediateTensorInfo(w),n.disposeIntermediateTensorInfo(k),n.makeTensorInfo(y,O.dtype,O.values)}({inputs:{a:a,b:s},attrs:{transposeA:l,transposeB:c},backend:n});p=g,r&&(d=ho({inputs:{a:p,b:r},backend:n}),f.push(p),p=d),u&&(m=Lo(n,p,u,o,h),f.push(p),p=m);for(const e of f)n.disposeIntermediateTensorInfo(e);return p}};
3726
+ function(e){const{inputs:t,backend:n,attrs:i}=e,{a:a,b:s,bias:r,preluActivationWeights:o}=t,{transposeA:l,transposeB:c,activation:u,leakyreluAlpha:h}=i;let p,d,m;const f=[],g=function(e){const{inputs:t,backend:n,attrs:i}=e,{a:a,b:s}=t,{transposeA:r,transposeB:o}=i;Xr([a,s],"matMul");const l=a.shape.length,c=s.shape.length,u=r?a.shape[l-2]:a.shape[l-1],h=o?s.shape[c-1]:s.shape[c-2],p=r?a.shape[l-1]:a.shape[l-2],d=o?s.shape[c-2]:s.shape[c-1],m=a.shape.slice(0,-2),f=s.shape.slice(0,-2),g=C(m),v=C(f),y=mi(a.shape.slice(0,-2),s.shape.slice(0,-2)).concat([p,d]);T(u===h,(()=>`Error in matMul: inner shapes (${u}) and (${h}) of Tensors with shapes ${a.shape} and ${s.shape} and transposeA=${r} and transposeB=${o} must match.`));const b=o?[v,d,h]:[v,h,d],w=Io({inputs:{x:a},backend:n,attrs:{shape:r?[g,u,p]:[g,p,u]}}),k=Io({inputs:{x:s},backend:n,attrs:{shape:b}}),x=r?w.shape[1]:w.shape[2],S=r?w.shape[2]:w.shape[1],N=o?k.shape[1]:k.shape[2],I=Math.max(g,v),A=n.data.get(w.dataId).values,E=n.data.get(k.dataId).values,$=P(w.shape),j=P(k.shape),[z,D,F]=r?[$[0],1,$[1]]:[$[0],$[1],1],[_,R,L]=o?[1,j[1],j[0]]:[j[1],1,j[0]],M=S*N,O=Zi([I,S,N],w.dtype),B=O.values,U=n.blockSize;for(let e=0;e<I;e++){const t=e%g,n=e%v;for(let i=0;i<S;i+=U){const a=Math.min(i+U,S);for(let s=0;s<N;s+=U){const r=Math.min(s+U,N);for(let o=0;o<x;o+=U){const l=Math.min(o+U,x);for(let c=i;c<a;c++)for(let i=s;i<r;i++){let a=0;for(let e=o;e<l;e++)a+=A[t*z+c*D+e*F]*E[e*_+i*R+n*L];B[e*M+(c*N+i)]+=a}}}}}return n.disposeIntermediateTensorInfo(w),n.disposeIntermediateTensorInfo(k),n.makeTensorInfo(y,O.dtype,O.values)}({inputs:{a:a,b:s},attrs:{transposeA:l,transposeB:c},backend:n});p=g,r&&(d=ho({inputs:{a:p,b:r},backend:n}),f.push(p),p=d),u&&(m=Lo(n,p,u,o,h),f.push(p),p=m);for(const e of f)n.disposeIntermediateTensorInfo(e);return p}};
3727
3727
  /**
3728
3728
  * @license
3729
3729
  * Copyright 2018 Google LLC
@@ -3741,7 +3741,7 @@ function(e){const{inputs:t,backend:n,attrs:i}=e,{a:a,b:s,bias:r,preluActivationW
3741
3741
  * license that can be found in the LICENSE file or at
3742
3742
  * https://opensource.org/licenses/MIT.
3743
3743
  * =============================================================================
3744
- */class Go{constructor(e){this.maxEntries=e||100,this.cache=new Map}get(e){let t;return this.cache.has(e)&&(t=this.cache.get(e),this.cache.delete(e),this.cache.set(e,t)),t}put(e,t){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this.maxEntries){const e=this.cache.keys().next().value;this.cache.delete(e)}this.cache.set(e,t)}getMaxEntries(){return this.maxEntries}setMaxEntries(e){if(e<0)throw new Error(`The maxEntries of LRU caches must be at least 0, but got ${e}.`);if(this.maxEntries>e)for(let t=0;t<this.maxEntries-e;t++){const e=this.cache.keys().next().value;this.cache.delete(e)}this.maxEntries=e}}
3744
+ */class Vo{constructor(e){this.maxEntries=e||100,this.cache=new Map}get(e){let t;return this.cache.has(e)&&(t=this.cache.get(e),this.cache.delete(e),this.cache.set(e,t)),t}put(e,t){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this.maxEntries){const e=this.cache.keys().next().value;this.cache.delete(e)}this.cache.set(e,t)}getMaxEntries(){return this.maxEntries}setMaxEntries(e){if(e<0)throw new Error(`The maxEntries of LRU caches must be at least 0, but got ${e}.`);if(this.maxEntries>e)for(let t=0;t<this.maxEntries-e;t++){const e=this.cache.keys().next().value;this.cache.delete(e)}this.maxEntries=e}}
3745
3745
  /**
3746
3746
  * @license
3747
3747
  * Copyright 2018 Google LLC
@@ -3750,7 +3750,7 @@ function(e){const{inputs:t,backend:n,attrs:i}=e,{a:a,b:s,bias:r,preluActivationW
3750
3750
  * license that can be found in the LICENSE file or at
3751
3751
  * https://opensource.org/licenses/MIT.
3752
3752
  * =============================================================================
3753
- */function Vo(e,t){if(Array.isArray(e)){let n=[];for(let i=0;i<t;i++)n=n.concat(e);return n}{const n=new Array(t);return n.fill(e),n}}function Ko(e,t){if(!e)throw new Wo(t)}function qo(e,t){let n=0;for(const i of e)i===t&&n++;return n}function Ho(e){return 1===e.length?e[0]:e}function Jo(e){return Array.isArray(e)?e:[e]}function Zo(e){const t=e.replace(/(.)([A-Z][a-z0-9]+)/g,"$1_$2").replace(/([a-z])([A-Z])/g,"$1_$2").toLowerCase();return"_"!==t[0]?t:"private"+t}function Yo(e){return e.length<=1||-1===e.indexOf("_")?e:e.replace(/[_]+(\w|$)/g,((e,t)=>t.toUpperCase()))}let Qo={};function Xo(e){if(null==e)return null;const t={};return t.className=e.getClassName(),t.config=e.getConfig(),t}function el(e){if(null!=e&&"object"==typeof e)if(Array.isArray(e))e.forEach((e=>el(e)));else{const t=Object.keys(e);for(const n of t){const t=e[n];null!=t&&"object"==typeof t&&(Array.isArray(t)||"ndarray"!==t.type||"number"!=typeof t.value?el(t):e[n]=t.value)}}}function tl(e,t={},n={},i="object",a=!1){if("string"==typeof e){const a=e;let s;if(a in n)s=n[a];else if(a in Qo)s=Qo[a];else if(s=t[a],null==s)throw new Bo(`Unknown ${i}: ${e}. This may be due to one of the following reasons:\n1. The ${i} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.\n2. The custom ${i} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);return s}{const s=e;if(null==s.className||null==s.config)throw new Bo(`${i}: Improper config format: ${JSON.stringify(s)}.\n'className' and 'config' must set.`);const r=s.className;let o,l;if(r in n?[o,l]=n[r]:r in Qo?[o,l]=Qo.className:r in t&&([o,l]=t[r]),null==o)throw new Bo(`Unknown ${i}: ${r}. This may be due to one of the following reasons:\n1. The ${i} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.\n2. The custom ${i} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);if(null!=l){const e={};for(const t of Object.keys(Qo))e[t]=Qo[t];for(const t of Object.keys(n))e[t]=n[t];s.config.customObjects=e;const t=Object.assign({},Qo);for(const e of Object.keys(n))Qo[e]=n[e];el(s.config);const i=l(o,s.config,n,a);return Qo=Object.assign({},t),i}{const e=Object.assign({},Qo);for(const e of Object.keys(n))Qo[e]=n[e];const t=new o(s.config);return Qo=Object.assign({},e),t}}}function nl(e,t){return-1*function(e,t){return e<t?-1:e>t?1:0}(e,t)}function il(e){if(null==e)return e;const t=[];for(const n of e)-1===t.indexOf(n)&&t.push(n);return t}function al(e){if(null==e)throw new Bo(`Invalid value in obj: ${JSON.stringify(e)}`);for(const t in e)if(e.hasOwnProperty(t))return!1;return!0}function sl(e,t,n){if(null!=n&&e.indexOf(n)<0)throw new Bo(`${n} is not a valid ${t}. Valid values are ${e} or null/undefined.`)}function rl(e,t,n=0,i=1/0){return Ko(n>=0),Ko(i>=n),Array.isArray(e)&&e.length>=n&&e.length<=i&&e.every((e=>typeof e===t))}function ol(e,t){Array.isArray(e)?(I(e.length>0,(()=>`${t} is unexpectedly an empty array.`)),e.forEach(((e,n)=>ol(e,`element ${n+1} of ${t}`)))):I(Number.isInteger(e)&&e>0,(()=>`Expected ${t} to be a positive integer, but got ${ll(e)}.`))}function ll(e){return null===e?"null":Array.isArray(e)?"["+e.map((e=>ll(e))).join(",")+"]":"string"==typeof e?`"${e}"`:`${e}`}function cl(e){return"relu"===e?"relu":"linear"===e?"linear":"elu"===e?"elu":null}
3753
+ */function Go(e,t){if(Array.isArray(e)){let n=[];for(let i=0;i<t;i++)n=n.concat(e);return n}{const n=new Array(t);return n.fill(e),n}}function Ko(e,t){if(!e)throw new Wo(t)}function qo(e,t){let n=0;for(const i of e)i===t&&n++;return n}function Ho(e){return 1===e.length?e[0]:e}function Jo(e){return Array.isArray(e)?e:[e]}function Zo(e){const t=e.replace(/(.)([A-Z][a-z0-9]+)/g,"$1_$2").replace(/([a-z])([A-Z])/g,"$1_$2").toLowerCase();return"_"!==t[0]?t:"private"+t}function Yo(e){return e.length<=1||-1===e.indexOf("_")?e:e.replace(/[_]+(\w|$)/g,((e,t)=>t.toUpperCase()))}let Qo={};function Xo(e){if(null==e)return null;const t={};return t.className=e.getClassName(),t.config=e.getConfig(),t}function el(e){if(null!=e&&"object"==typeof e)if(Array.isArray(e))e.forEach((e=>el(e)));else{const t=Object.keys(e);for(const n of t){const t=e[n];null!=t&&"object"==typeof t&&(Array.isArray(t)||"ndarray"!==t.type||"number"!=typeof t.value?el(t):e[n]=t.value)}}}function tl(e,t={},n={},i="object",a=!1){if("string"==typeof e){const a=e;let s;if(a in n)s=n[a];else if(a in Qo)s=Qo[a];else if(s=t[a],null==s)throw new Bo(`Unknown ${i}: ${e}. This may be due to one of the following reasons:\n1. The ${i} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.\n2. The custom ${i} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);return s}{const s=e;if(null==s.className||null==s.config)throw new Bo(`${i}: Improper config format: ${JSON.stringify(s)}.\n'className' and 'config' must set.`);const r=s.className;let o,l;if(r in n?[o,l]=n[r]:r in Qo?[o,l]=Qo.className:r in t&&([o,l]=t[r]),null==o)throw new Bo(`Unknown ${i}: ${r}. This may be due to one of the following reasons:\n1. The ${i} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.\n2. The custom ${i} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);if(null!=l){const e={};for(const t of Object.keys(Qo))e[t]=Qo[t];for(const t of Object.keys(n))e[t]=n[t];s.config.customObjects=e;const t=Object.assign({},Qo);for(const e of Object.keys(n))Qo[e]=n[e];el(s.config);const i=l(o,s.config,n,a);return Qo=Object.assign({},t),i}{const e=Object.assign({},Qo);for(const e of Object.keys(n))Qo[e]=n[e];const t=new o(s.config);return Qo=Object.assign({},e),t}}}function nl(e,t){return-1*function(e,t){return e<t?-1:e>t?1:0}(e,t)}function il(e){if(null==e)return e;const t=[];for(const n of e)-1===t.indexOf(n)&&t.push(n);return t}function al(e){if(null==e)throw new Bo(`Invalid value in obj: ${JSON.stringify(e)}`);for(const t in e)if(e.hasOwnProperty(t))return!1;return!0}function sl(e,t,n){if(null!=n&&e.indexOf(n)<0)throw new Bo(`${n} is not a valid ${t}. Valid values are ${e} or null/undefined.`)}function rl(e,t,n=0,i=1/0){return Ko(n>=0),Ko(i>=n),Array.isArray(e)&&e.length>=n&&e.length<=i&&e.every((e=>typeof e===t))}function ol(e,t){Array.isArray(e)?(T(e.length>0,(()=>`${t} is unexpectedly an empty array.`)),e.forEach(((e,n)=>ol(e,`element ${n+1} of ${t}`)))):T(Number.isInteger(e)&&e>0,(()=>`Expected ${t} to be a positive integer, but got ${ll(e)}.`))}function ll(e){return null===e?"null":Array.isArray(e)?"["+e.map((e=>ll(e))).join(",")+"]":"string"==typeof e?`"${e}"`:`${e}`}function cl(e){return"relu"===e?"relu":"linear"===e?"linear":"elu"===e?"elu":null}
3754
3754
  /**
3755
3755
  * @license
3756
3756
  * Copyright 2018 Google LLC
@@ -3768,7 +3768,7 @@ function(e){const{inputs:t,backend:n,attrs:i}=e,{a:a,b:s,bias:r,preluActivationW
3768
3768
  * license that can be found in the LICENSE file or at
3769
3769
  * https://opensource.org/licenses/MIT.
3770
3770
  * =============================================================================
3771
- */const ml=["channelsFirst","channelsLast"],fl=["nearest","bilinear"],gl=["valid","same","causal"],vl=["max","avg"],yl=["sum","mul","concat","ave"],bl=new Map;function wl(e){sl(ml,"DataFormat",e)}function kl(e){sl(gl,"PaddingMode",e)}function xl(e){sl(vl,"PoolMode",e)}const Sl=[];function Nl(e,t){Sl.push(e);try{const e=t();return Sl.pop(),e}catch(e){throw Sl.pop(),e}}function Il(e){if(!Al(e))throw new Error("Not a valid tensor name: '"+e+"'");return(0===Sl.length?"":Sl.join("/")+"/")+e}function Tl(e){if(!Al(e))throw new Error("Not a valid tensor name: '"+e+"'");bl.has(e)||bl.set(e,0);const t=bl.get(e);if(bl.set(e,bl.get(e)+1),t>0){const n=`${e}_${t}`;return bl.set(n,1),n}return e}const El=new RegExp(/^[A-Za-z0-9][-A-Za-z0-9\._\/]*$/);function Al(e){return!!e.match(El)}
3771
+ */const ml=["channelsFirst","channelsLast"],fl=["nearest","bilinear"],gl=["valid","same","causal"],vl=["max","avg"],yl=["sum","mul","concat","ave"],bl=new Map;function wl(e){sl(ml,"DataFormat",e)}function kl(e){sl(gl,"PaddingMode",e)}function xl(e){sl(vl,"PoolMode",e)}const Sl=[];function Nl(e,t){Sl.push(e);try{const e=t();return Sl.pop(),e}catch(e){throw Sl.pop(),e}}function Tl(e){if(!Cl(e))throw new Error("Not a valid tensor name: '"+e+"'");return(0===Sl.length?"":Sl.join("/")+"/")+e}function Il(e){if(!Cl(e))throw new Error("Not a valid tensor name: '"+e+"'");bl.has(e)||bl.set(e,0);const t=bl.get(e);if(bl.set(e,bl.get(e)+1),t>0){const n=`${e}_${t}`;return bl.set(n,1),n}return e}const Al=new RegExp(/^[A-Za-z0-9][-A-Za-z0-9\._\/]*$/);function Cl(e){return!!e.match(Al)}
3772
3772
  /**
3773
3773
  * @license
3774
3774
  * Copyright 2018 Google LLC
@@ -3777,7 +3777,7 @@ function(e){const{inputs:t,backend:n,attrs:i}=e,{a:a,b:s,bias:r,preluActivationW
3777
3777
  * license that can be found in the LICENSE file or at
3778
3778
  * https://opensource.org/licenses/MIT.
3779
3779
  * =============================================================================
3780
- */function Cl(e,t,n){null==t&&(t=0),null==n&&(n=e.length);let i=1;for(let a=t;a<n;++a)i*=e[a];return i}function $l(e){if(0===e.length)return Number.NaN;let t=Number.POSITIVE_INFINITY;for(let n=0;n<e.length;n++){const i=e[n];i<t&&(t=i)}return t}function jl(e){if(0===e.length)return Number.NaN;let t=Number.NEGATIVE_INFINITY;for(let n=0;n<e.length;n++){const i=e[n];i>t&&(t=i)}return t}function zl(e,t){if(t<e)throw new Bo(`end (${t}) < begin (${e}) is forbidden.`);const n=[];for(let i=e;i<t;++i)n.push(i);return n}
3780
+ */function El(e,t,n){null==t&&(t=0),null==n&&(n=e.length);let i=1;for(let a=t;a<n;++a)i*=e[a];return i}function $l(e){if(0===e.length)return Number.NaN;let t=Number.POSITIVE_INFINITY;for(let n=0;n<e.length;n++){const i=e[n];i<t&&(t=i)}return t}function jl(e){if(0===e.length)return Number.NaN;let t=Number.NEGATIVE_INFINITY;for(let n=0;n<e.length;n++){const i=e[n];i>t&&(t=i)}return t}function zl(e,t){if(t<e)throw new Bo(`end (${t}) < begin (${e}) is forbidden.`);const n=[];for(let i=e;i<t;++i)n.push(i);return n}
3781
3781
  /**
3782
3782
  * @license
3783
3783
  * Copyright 2018 Google LLC
@@ -3796,7 +3796,7 @@ function(e){const{inputs:t,backend:n,attrs:i}=e,{a:a,b:s,bias:r,preluActivationW
3796
3796
  * https://opensource.org/licenses/MIT.
3797
3797
  * =============================================================================
3798
3798
  */
3799
- function _l(e,t){return ei(e,t)}function Rl(e,t=-1){const n=e.shape.slice();return t<0&&(t=n.length+t+1),n.splice(t,0,1),_i(e,n)}function Ll(e,t,n){return si((()=>{switch(e.rank){case 1:return Rs(e,t,n);case 2:return Ls(e,[t,0],[n,e.shape[1]]);case 3:return Ms(e,[t,0,0],[n,e.shape[1],e.shape[2]]);case 4:return Os(e,[t,0,0,0],[n,e.shape[1],e.shape[2],e.shape[3]]);case 5:return Bi(e,[t,0,0,0,0],[n,e.shape[1],e.shape[2],e.shape[3],e.shape[4]]);case 6:return Bi(e,[t,0,0,0,0,0],[n,e.shape[1],e.shape[2],e.shape[3],e.shape[4],e.shape[5]]);default:throw new Bo(`sliceAlongFirstAxis() received an unsupported tensor rank: ${e.rank}`)}}))}function Ml(e,t,n){return si((()=>{switch(e.rank){case 1:return Rs(e,t,n);case 2:return Ls(e,[0,t],[e.shape[0],n]);case 3:return Ms(e,[0,0,t],[e.shape[0],e.shape[1],n]);case 4:return Os(e,[0,0,0,t],[e.shape[0],e.shape[1],e.shape[2],n]);default:throw new Bo(`sliceAlongLastAxis() received an unsupported tensor rank: ${e.rank}`)}}))}function Ol(e,t,n,i){return si((()=>{switch(e.rank){case 1:return Rs(e,t,n);case 2:switch(i){case 1:return Ll(e,t,n);case 2:return Ml(e,t,n);default:throw new Bo(`The axis is not within the rank of the tensor ${i}`)}case 3:switch(i){case 1:return Ll(e,t,n);case 2:return Ms(e,[0,t,0],[e.shape[0],n,e.shape[2]]);case 3:return Ml(e,t,n);default:throw new Bo(`The axis is not within the rank of the tensor ${i}`)}case 4:switch(i){case 1:return Ll(e,t,n);case 2:return Os(e,[0,t,0,0],[e.shape[0],n,e.shape[2],e.shape[3]]);case 3:return Os(e,[0,0,t,0],[e.shape[0],e.shape[1],n,e.shape[3]]);case 4:return Ml(e,t,n);default:throw new Bo(`The axis is not within the rank of the tensor ${i}`)}default:throw new Bo(`sliceAlongLastAxis() received an unsupported tensor rank: ${e.rank}`)}}))}function Pl(e,t=-1){let n;return t<0&&(n=e[0].rank,t=0!==n?n:0),t===e[0].rank&&(t=-1),Oi(e,t)}function Bl(e,t){switch(e.rank){case 1:return Xi([e,t]);case 2:return ea([e,t],0);case 3:return ta([e,t],0);case 4:return na([e,t],0);default:throw new Bo(`concatAlongFirstAxis() received an unsupported tensor rank: ${e.rank}`)}}function Ul(e,t){if(Array.isArray(t)||(t=[t]),e.rank!==t.length)throw new Bo(`The length of input n (${t.length}) does not match the number of dimensions in input x (${e.rank})`);return Ra(e,t)}function Wl(e,t=0,n=1,i,a){return Ns(e,t,n,i,a)}function Gl(e,t,n,i){if(e.rank<2||t.rank<2)throw new Uo(`dot requires both inputs to be rank >= 2 but got x shape = ${e.shape} and y shape = ${t.shape}`);if(t.rank>=3){if(e.shape.slice(-1)[0]!==t.shape.slice(-2)[0])throw new Uo(`If rank y >= 3, then the second last dim of y must equal the last dim of x but got x shape = ${e.shape} and y shape = ${t.shape}`)}if(2===e.rank&&2===t.rank){return sr({a:e,b:t,transposeA:!1,transposeB:!1,bias:i?ql(e.rank,i,"channelsLast"):null,activation:n})}{const a=e.shape.slice(),s=a.pop();e=_i(e,[-1,s]);const r=t.shape.slice(),o=r.pop(),l=r.pop(),c=[...r,o],u=Array.from({length:t.rank},((e,n)=>0===n?t.rank-2:n<=t.rank-2?n-1:n));t=_i(hi(t,u),[l,-1]);const h=[...a,...c];return _i(sr({a:e,b:t,transposeA:!1,transposeB:!1,bias:i?ql(e.rank,i,"channelsLast"):null,activation:n}),h)}}function Vl(e,t,n){return si((()=>(t=Array.isArray(t)?Vs(t,"int32"):ei(t,"int32"),Oa(e,t,n))))}function Kl(e){return xi(e,e)}function ql(e,t,n){const i=t.shape;if(1!==t.rank&&t.rank!==e)throw new Bo(`Unexpected bias dimensions: ${t.rank}; expected it to be 1 or ${e}`);if(5===e){if("channelsFirst"===n)return 1===i.length?_i(t,[1,i[0],1,1,1]):_i(t,[1,i[3],i[0],i[1],i[2]]);if("channelsLast"===n)return 1===i.length?_i(t,[1,1,1,1,i[0]]):_i(t,[1].concat(i))}else if(4===e){if("channelsFirst"===n)return 1===i.length?_i(t,[1,i[0],1,1]):_i(t,[1,i[2],i[0],i[1]]);if("channelsLast"===n)return 1===i.length?_i(t,[1,1,1,i[0]]):_i(t,[1].concat(i))}else if(3===e){if("channelsFirst"===n)return 1===i.length?_i(t,[1,i[0],1]):_i(t,[1,i[1],i[0]]);if("channelsLast"===n)return 1===i.length?_i(t,[1,1,i[0]]):_i(t,[1].concat(i))}else if(e<3)return t;throw new Bo(`Unsupported input rank by biasAdd: ${t.rank}`)}function Hl(e,t,n){return si((()=>(null==n&&(n="channelsLast"),wl(n),bi(e,ql(e.rank,t,n)))))}function Jl(e,t,n,i){return si((()=>Zs(e,t,n,i)))}function Zl(e,t,n=!1){return n?e():t()}
3799
+ function _l(e,t){return ei(e,t)}function Rl(e,t=-1){const n=e.shape.slice();return t<0&&(t=n.length+t+1),n.splice(t,0,1),_i(e,n)}function Ll(e,t,n){return si((()=>{switch(e.rank){case 1:return Rs(e,t,n);case 2:return Ls(e,[t,0],[n,e.shape[1]]);case 3:return Ms(e,[t,0,0],[n,e.shape[1],e.shape[2]]);case 4:return Os(e,[t,0,0,0],[n,e.shape[1],e.shape[2],e.shape[3]]);case 5:return Bi(e,[t,0,0,0,0],[n,e.shape[1],e.shape[2],e.shape[3],e.shape[4]]);case 6:return Bi(e,[t,0,0,0,0,0],[n,e.shape[1],e.shape[2],e.shape[3],e.shape[4],e.shape[5]]);default:throw new Bo(`sliceAlongFirstAxis() received an unsupported tensor rank: ${e.rank}`)}}))}function Ml(e,t,n){return si((()=>{switch(e.rank){case 1:return Rs(e,t,n);case 2:return Ls(e,[0,t],[e.shape[0],n]);case 3:return Ms(e,[0,0,t],[e.shape[0],e.shape[1],n]);case 4:return Os(e,[0,0,0,t],[e.shape[0],e.shape[1],e.shape[2],n]);default:throw new Bo(`sliceAlongLastAxis() received an unsupported tensor rank: ${e.rank}`)}}))}function Ol(e,t,n,i){return si((()=>{switch(e.rank){case 1:return Rs(e,t,n);case 2:switch(i){case 1:return Ll(e,t,n);case 2:return Ml(e,t,n);default:throw new Bo(`The axis is not within the rank of the tensor ${i}`)}case 3:switch(i){case 1:return Ll(e,t,n);case 2:return Ms(e,[0,t,0],[e.shape[0],n,e.shape[2]]);case 3:return Ml(e,t,n);default:throw new Bo(`The axis is not within the rank of the tensor ${i}`)}case 4:switch(i){case 1:return Ll(e,t,n);case 2:return Os(e,[0,t,0,0],[e.shape[0],n,e.shape[2],e.shape[3]]);case 3:return Os(e,[0,0,t,0],[e.shape[0],e.shape[1],n,e.shape[3]]);case 4:return Ml(e,t,n);default:throw new Bo(`The axis is not within the rank of the tensor ${i}`)}default:throw new Bo(`sliceAlongLastAxis() received an unsupported tensor rank: ${e.rank}`)}}))}function Pl(e,t=-1){let n;return t<0&&(n=e[0].rank,t=0!==n?n:0),t===e[0].rank&&(t=-1),Oi(e,t)}function Bl(e,t){switch(e.rank){case 1:return Xi([e,t]);case 2:return ea([e,t],0);case 3:return ta([e,t],0);case 4:return na([e,t],0);default:throw new Bo(`concatAlongFirstAxis() received an unsupported tensor rank: ${e.rank}`)}}function Ul(e,t){if(Array.isArray(t)||(t=[t]),e.rank!==t.length)throw new Bo(`The length of input n (${t.length}) does not match the number of dimensions in input x (${e.rank})`);return Ra(e,t)}function Wl(e,t=0,n=1,i,a){return Ns(e,t,n,i,a)}function Vl(e,t,n,i){if(e.rank<2||t.rank<2)throw new Uo(`dot requires both inputs to be rank >= 2 but got x shape = ${e.shape} and y shape = ${t.shape}`);if(t.rank>=3){if(e.shape.slice(-1)[0]!==t.shape.slice(-2)[0])throw new Uo(`If rank y >= 3, then the second last dim of y must equal the last dim of x but got x shape = ${e.shape} and y shape = ${t.shape}`)}if(2===e.rank&&2===t.rank){return sr({a:e,b:t,transposeA:!1,transposeB:!1,bias:i?ql(e.rank,i,"channelsLast"):null,activation:n})}{const a=e.shape.slice(),s=a.pop();e=_i(e,[-1,s]);const r=t.shape.slice(),o=r.pop(),l=r.pop(),c=[...r,o],u=Array.from({length:t.rank},((e,n)=>0===n?t.rank-2:n<=t.rank-2?n-1:n));t=_i(hi(t,u),[l,-1]);const h=[...a,...c];return _i(sr({a:e,b:t,transposeA:!1,transposeB:!1,bias:i?ql(e.rank,i,"channelsLast"):null,activation:n}),h)}}function Gl(e,t,n){return si((()=>(t=Array.isArray(t)?Gs(t,"int32"):ei(t,"int32"),Oa(e,t,n))))}function Kl(e){return xi(e,e)}function ql(e,t,n){const i=t.shape;if(1!==t.rank&&t.rank!==e)throw new Bo(`Unexpected bias dimensions: ${t.rank}; expected it to be 1 or ${e}`);if(5===e){if("channelsFirst"===n)return 1===i.length?_i(t,[1,i[0],1,1,1]):_i(t,[1,i[3],i[0],i[1],i[2]]);if("channelsLast"===n)return 1===i.length?_i(t,[1,1,1,1,i[0]]):_i(t,[1].concat(i))}else if(4===e){if("channelsFirst"===n)return 1===i.length?_i(t,[1,i[0],1,1]):_i(t,[1,i[2],i[0],i[1]]);if("channelsLast"===n)return 1===i.length?_i(t,[1,1,1,i[0]]):_i(t,[1].concat(i))}else if(3===e){if("channelsFirst"===n)return 1===i.length?_i(t,[1,i[0],1]):_i(t,[1,i[1],i[0]]);if("channelsLast"===n)return 1===i.length?_i(t,[1,1,i[0]]):_i(t,[1].concat(i))}else if(e<3)return t;throw new Bo(`Unsupported input rank by biasAdd: ${t.rank}`)}function Hl(e,t,n){return si((()=>(null==n&&(n="channelsLast"),wl(n),bi(e,ql(e.rank,t,n)))))}function Jl(e,t,n,i){return si((()=>Zs(e,t,n,i)))}function Zl(e,t,n=!1){return n?e():t()}
3800
3800
  /**
3801
3801
  * @license
3802
3802
  * Copyright 2018 Google LLC
@@ -3805,7 +3805,7 @@ function _l(e,t){return ei(e,t)}function Rl(e,t=-1){const n=e.shape.slice();retu
3805
3805
  * license that can be found in the LICENSE file or at
3806
3806
  * https://opensource.org/licenses/MIT.
3807
3807
  * =============================================================================
3808
- */const Yl=["fanIn","fanOut","fanAvg"],Ql=["normal","uniform","truncatedNormal"];class Xl extends gi{fromConfigUsesCustomObjects(){return!1}getConfig(){return{}}}class ec extends Xl{apply(e,t){return is(e,t)}}ec.className="Zeros",yi(ec);class tc extends Xl{apply(e,t){return as(e,t)}}tc.className="Ones",yi(tc);class nc extends Xl{constructor(e){if(super(),"object"!=typeof e)throw new Bo(`Expected argument of type ConstantConfig but got ${e}`);if(void 0===e.value)throw new Bo(`config must have value set but got ${e}`);this.value=e.value}apply(e,t){return si((()=>xi(Aa(this.value),as(e,t))))}getConfig(){return{value:this.value}}}nc.className="Constant",yi(nc);class ic extends Xl{constructor(e){super(),this.DEFAULT_MINVAL=-.05,this.DEFAULT_MAXVAL=.05,this.minval=e.minval||this.DEFAULT_MINVAL,this.maxval=e.maxval||this.DEFAULT_MAXVAL,this.seed=e.seed}apply(e,t){return Is(e,this.minval,this.maxval,t,this.seed)}getConfig(){return{minval:this.minval,maxval:this.maxval,seed:this.seed}}}ic.className="RandomUniform",yi(ic);class ac extends Xl{constructor(e){super(),this.DEFAULT_MEAN=0,this.DEFAULT_STDDEV=.05,this.mean=e.mean||this.DEFAULT_MEAN,this.stddev=e.stddev||this.DEFAULT_STDDEV,this.seed=e.seed}apply(e,t){if("float32"!==(t=t||"float32")&&"int32"!==t)throw new Uo(`randomNormal does not support dType ${t}.`);return Wl(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}}ac.className="RandomNormal",yi(ac);class sc extends Xl{constructor(e){super(),this.DEFAULT_MEAN=0,this.DEFAULT_STDDEV=.05,this.mean=e.mean||this.DEFAULT_MEAN,this.stddev=e.stddev||this.DEFAULT_STDDEV,this.seed=e.seed}apply(e,t){if("float32"!==(t=t||"float32")&&"int32"!==t)throw new Uo(`truncatedNormal does not support dType ${t}.`);return qs(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}}sc.className="TruncatedNormal",yi(sc);class rc extends Xl{constructor(e){super(),this.gain=null!=e.gain?e.gain:1}apply(e,t){return si((()=>{if(2!==e.length||e[0]!==e[1])throw new Bo("Identity matrix initializer can only be used for 2D square matrices.");return xi(this.gain,La(e[0]))}))}getConfig(){return{gain:this.gain}}}rc.className="Identity",yi(rc);class oc extends Xl{constructor(e){if(super(),e.scale<0)throw new Bo(`scale must be a positive float. Got: ${e.scale}`);
3808
+ */const Yl=["fanIn","fanOut","fanAvg"],Ql=["normal","uniform","truncatedNormal"];class Xl extends gi{fromConfigUsesCustomObjects(){return!1}getConfig(){return{}}}class ec extends Xl{apply(e,t){return is(e,t)}}ec.className="Zeros",yi(ec);class tc extends Xl{apply(e,t){return as(e,t)}}tc.className="Ones",yi(tc);class nc extends Xl{constructor(e){if(super(),"object"!=typeof e)throw new Bo(`Expected argument of type ConstantConfig but got ${e}`);if(void 0===e.value)throw new Bo(`config must have value set but got ${e}`);this.value=e.value}apply(e,t){return si((()=>xi(Ca(this.value),as(e,t))))}getConfig(){return{value:this.value}}}nc.className="Constant",yi(nc);class ic extends Xl{constructor(e){super(),this.DEFAULT_MINVAL=-.05,this.DEFAULT_MAXVAL=.05,this.minval=e.minval||this.DEFAULT_MINVAL,this.maxval=e.maxval||this.DEFAULT_MAXVAL,this.seed=e.seed}apply(e,t){return Ts(e,this.minval,this.maxval,t,this.seed)}getConfig(){return{minval:this.minval,maxval:this.maxval,seed:this.seed}}}ic.className="RandomUniform",yi(ic);class ac extends Xl{constructor(e){super(),this.DEFAULT_MEAN=0,this.DEFAULT_STDDEV=.05,this.mean=e.mean||this.DEFAULT_MEAN,this.stddev=e.stddev||this.DEFAULT_STDDEV,this.seed=e.seed}apply(e,t){if("float32"!==(t=t||"float32")&&"int32"!==t)throw new Uo(`randomNormal does not support dType ${t}.`);return Wl(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}}ac.className="RandomNormal",yi(ac);class sc extends Xl{constructor(e){super(),this.DEFAULT_MEAN=0,this.DEFAULT_STDDEV=.05,this.mean=e.mean||this.DEFAULT_MEAN,this.stddev=e.stddev||this.DEFAULT_STDDEV,this.seed=e.seed}apply(e,t){if("float32"!==(t=t||"float32")&&"int32"!==t)throw new Uo(`truncatedNormal does not support dType ${t}.`);return qs(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}}sc.className="TruncatedNormal",yi(sc);class rc extends Xl{constructor(e){super(),this.gain=null!=e.gain?e.gain:1}apply(e,t){return si((()=>{if(2!==e.length||e[0]!==e[1])throw new Bo("Identity matrix initializer can only be used for 2D square matrices.");return xi(this.gain,La(e[0]))}))}getConfig(){return{gain:this.gain}}}rc.className="Identity",yi(rc);class oc extends Xl{constructor(e){if(super(),e.scale<0)throw new Bo(`scale must be a positive float. Got: ${e.scale}`);
3809
3809
  /**
3810
3810
  * @license
3811
3811
  * Copyright 2018 Google LLC
@@ -3815,7 +3815,7 @@ function _l(e,t){return ei(e,t)}function Rl(e,t=-1){const n=e.shape.slice();retu
3815
3815
  * https://opensource.org/licenses/MIT.
3816
3816
  * =============================================================================
3817
3817
  */
3818
- var t;this.scale=null==e.scale?1:e.scale,this.mode=null==e.mode?"fanIn":e.mode,t=this.mode,sl(Yl,"FanMode",t),this.distribution=null==e.distribution?"normal":e.distribution,function(e){sl(Ql,"Distribution",e)}(this.distribution),this.seed=e.seed}apply(e,t){const n=function(e,t="channelsLast"){let n,i;if(wl(t),2===e.length)n=e[0],i=e[1];else if(-1!==[3,4,5].indexOf(e.length)){if("channelsFirst"===t){const t=Cl(e,2);n=e[1]*t,i=e[0]*t}else if("channelsLast"===t){const t=Cl(e,0,e.length-2);n=e[e.length-2]*t,i=e[e.length-1]*t}}else{const t=Cl(e);n=Math.sqrt(t),i=Math.sqrt(t)}return[n,i]}(e),i=n[0],a=n[1];let s=this.scale;if("fanIn"===this.mode?s/=Math.max(1,i):"fanOut"===this.mode?s/=Math.max(1,a):s/=Math.max(1,(i+a)/2),"normal"===this.distribution){const n=Math.sqrt(s);if("float32"!==(t=t||"float32")&&"int32"!==t)throw new Uo(`${this.getClassName()} does not support dType ${t}.`);return qs(e,0,n,t,this.seed)}{const n=Math.sqrt(3*s);return Is(e,-n,n,t,this.seed)}}getConfig(){return{scale:this.scale,mode:this.mode,distribution:this.distribution,seed:this.seed}}}oc.className="VarianceScaling",yi(oc);class lc extends oc{constructor(e){super({scale:1,mode:"fanAvg",distribution:"uniform",seed:null==e?null:e.seed})}getClassName(){return oc.className}}lc.className="GlorotUniform",yi(lc);class cc extends oc{constructor(e){super({scale:1,mode:"fanAvg",distribution:"normal",seed:null==e?null:e.seed})}getClassName(){return oc.className}}cc.className="GlorotNormal",yi(cc);class uc extends oc{constructor(e){super({scale:2,mode:"fanIn",distribution:"normal",seed:null==e?null:e.seed})}getClassName(){return oc.className}}uc.className="HeNormal",yi(uc);class hc extends oc{constructor(e){super({scale:2,mode:"fanIn",distribution:"uniform",seed:null==e?null:e.seed})}getClassName(){return oc.className}}hc.className="HeUniform",yi(hc);class pc extends oc{constructor(e){super({scale:1,mode:"fanIn",distribution:"normal",seed:null==e?null:e.seed})}getClassName(){return oc.className}}pc.className="LeCunNormal",yi(pc);class dc extends oc{constructor(e){super({scale:1,mode:"fanIn",distribution:"uniform",seed:null==e?null:e.seed})}getClassName(){return oc.className}}dc.className="LeCunUniform",yi(dc);class mc extends Xl{constructor(e){if(super(),this.DEFAULT_GAIN=1,this.gain=null==e.gain?this.DEFAULT_GAIN:e.gain,this.seed=e.seed,null!=this.seed)throw new Uo("Random seed is not implemented for Orthogonal Initializer yet.")}apply(e,t){return si((()=>{if(e.length<2)throw new Uo("Shape must be at least 2D.");e[0]*e[1]>2e3&&console.warn(`Orthogonal initializer is being called on a matrix with more than 2000 (${e[0]*e[1]}) elements: Slowness may result.`);const t=Wl(e[0]>e[1]?[e[1],e[0]]:e,0,1,"float32");let n=Dr.gramSchmidt(t);return e[0]>e[1]&&(n=hi(n)),xi(this.gain,n)}))}getConfig(){return{gain:this.gain,seed:this.seed}}}mc.className="Orthogonal",yi(mc);const fc={constant:"Constant",glorotNormal:"GlorotNormal",glorotUniform:"GlorotUniform",heNormal:"HeNormal",heUniform:"HeUniform",identity:"Identity",leCunNormal:"LeCunNormal",leCunUniform:"LeCunUniform",ones:"Ones",orthogonal:"Orthogonal",randomNormal:"RandomNormal",randomUniform:"RandomUniform",truncatedNormal:"TruncatedNormal",varianceScaling:"VarianceScaling",zeros:"Zeros"};function gc(e,t={}){return tl(e,vi.getMap().classNameMap,t,"initializer")}function vc(e){return Xo(e)}function yc(e){if("string"==typeof e){const t=e in fc?fc[e]:e;if("GlorotNormal"===t)return new cc;if("GlorotUniform"===t)return new lc;if("HeNormal"===t)return new uc;if("HeUniform"===t)return new hc;if("LeCunNormal"===t)return new pc;if("LeCunUniform"===t)return new dc;{const e={};return e.className=t,e.config={},gc(e)}}return e instanceof Xl?e:gc(e)}
3818
+ var t;this.scale=null==e.scale?1:e.scale,this.mode=null==e.mode?"fanIn":e.mode,t=this.mode,sl(Yl,"FanMode",t),this.distribution=null==e.distribution?"normal":e.distribution,function(e){sl(Ql,"Distribution",e)}(this.distribution),this.seed=e.seed}apply(e,t){const n=function(e,t="channelsLast"){let n,i;if(wl(t),2===e.length)n=e[0],i=e[1];else if(-1!==[3,4,5].indexOf(e.length)){if("channelsFirst"===t){const t=El(e,2);n=e[1]*t,i=e[0]*t}else if("channelsLast"===t){const t=El(e,0,e.length-2);n=e[e.length-2]*t,i=e[e.length-1]*t}}else{const t=El(e);n=Math.sqrt(t),i=Math.sqrt(t)}return[n,i]}(e),i=n[0],a=n[1];let s=this.scale;if("fanIn"===this.mode?s/=Math.max(1,i):"fanOut"===this.mode?s/=Math.max(1,a):s/=Math.max(1,(i+a)/2),"normal"===this.distribution){const n=Math.sqrt(s);if("float32"!==(t=t||"float32")&&"int32"!==t)throw new Uo(`${this.getClassName()} does not support dType ${t}.`);return qs(e,0,n,t,this.seed)}{const n=Math.sqrt(3*s);return Ts(e,-n,n,t,this.seed)}}getConfig(){return{scale:this.scale,mode:this.mode,distribution:this.distribution,seed:this.seed}}}oc.className="VarianceScaling",yi(oc);class lc extends oc{constructor(e){super({scale:1,mode:"fanAvg",distribution:"uniform",seed:null==e?null:e.seed})}getClassName(){return oc.className}}lc.className="GlorotUniform",yi(lc);class cc extends oc{constructor(e){super({scale:1,mode:"fanAvg",distribution:"normal",seed:null==e?null:e.seed})}getClassName(){return oc.className}}cc.className="GlorotNormal",yi(cc);class uc extends oc{constructor(e){super({scale:2,mode:"fanIn",distribution:"normal",seed:null==e?null:e.seed})}getClassName(){return oc.className}}uc.className="HeNormal",yi(uc);class hc extends oc{constructor(e){super({scale:2,mode:"fanIn",distribution:"uniform",seed:null==e?null:e.seed})}getClassName(){return oc.className}}hc.className="HeUniform",yi(hc);class pc extends oc{constructor(e){super({scale:1,mode:"fanIn",distribution:"normal",seed:null==e?null:e.seed})}getClassName(){return oc.className}}pc.className="LeCunNormal",yi(pc);class dc extends oc{constructor(e){super({scale:1,mode:"fanIn",distribution:"uniform",seed:null==e?null:e.seed})}getClassName(){return oc.className}}dc.className="LeCunUniform",yi(dc);class mc extends Xl{constructor(e){if(super(),this.DEFAULT_GAIN=1,this.gain=null==e.gain?this.DEFAULT_GAIN:e.gain,this.seed=e.seed,null!=this.seed)throw new Uo("Random seed is not implemented for Orthogonal Initializer yet.")}apply(e,t){return si((()=>{if(e.length<2)throw new Uo("Shape must be at least 2D.");e[0]*e[1]>2e3&&console.warn(`Orthogonal initializer is being called on a matrix with more than 2000 (${e[0]*e[1]}) elements: Slowness may result.`);const t=Wl(e[0]>e[1]?[e[1],e[0]]:e,0,1,"float32");let n=Dr.gramSchmidt(t);return e[0]>e[1]&&(n=hi(n)),xi(this.gain,n)}))}getConfig(){return{gain:this.gain,seed:this.seed}}}mc.className="Orthogonal",yi(mc);const fc={constant:"Constant",glorotNormal:"GlorotNormal",glorotUniform:"GlorotUniform",heNormal:"HeNormal",heUniform:"HeUniform",identity:"Identity",leCunNormal:"LeCunNormal",leCunUniform:"LeCunUniform",ones:"Ones",orthogonal:"Orthogonal",randomNormal:"RandomNormal",randomUniform:"RandomUniform",truncatedNormal:"TruncatedNormal",varianceScaling:"VarianceScaling",zeros:"Zeros"};function gc(e,t={}){return tl(e,vi.getMap().classNameMap,t,"initializer")}function vc(e){return Xo(e)}function yc(e){if("string"==typeof e){const t=e in fc?fc[e]:e;if("GlorotNormal"===t)return new cc;if("GlorotUniform"===t)return new lc;if("HeNormal"===t)return new uc;if("HeUniform"===t)return new hc;if("LeCunNormal"===t)return new pc;if("LeCunUniform"===t)return new dc;{const e={};return e.className=t,e.config={},gc(e)}}return e instanceof Xl?e:gc(e)}
3819
3819
  /**
3820
3820
  * @license
3821
3821
  * Copyright 2018 Google LLC
@@ -3842,7 +3842,7 @@ var t;this.scale=null==e.scale?1:e.scale,this.mode=null==e.mode?"fanIn":e.mode,t
3842
3842
  * license that can be found in the LICENSE file or at
3843
3843
  * https://opensource.org/licenses/MIT.
3844
3844
  * =============================================================================
3845
- */const Nc="Variable";class Ic{constructor(e,t="float32",n=Nc,i=!0,a=null){this.dtype=null==t?"float32":t,this.shape=e.shape,this.id=hl(),n=null==n?Nc:n,this.originalName=Il(n),this.name=Tl(this.originalName),this.trainable_=i,this.constraint=a,this.val=function(e,t=!0,n,i){return sn.makeVariable(e,t,n,i)}(e,this.trainable_,this.name,this.dtype)}read(){return this.assertNotDisposed(),this.val}write(e){return this.assertNotDisposed(),function(e,t){if(e.shape.toString()!==t.shape.toString())throw new Error("Shape mismatch: "+JSON.stringify(e.shape)+" vs. "+JSON.stringify(t.shape))}(this.val,e),this.val.id!==e.id&&(this.val.assign(e),null!=this.constraint&&this.val.assign(this.constraint.apply(this.val))),this}dispose(){this.assertNotDisposed(),this.val.dispose()}assertNotDisposed(){if(this.val.isDisposed)throw new Error(`LayersVariable ${this.name} is already disposed.`)}get trainable(){return this.trainable_}set trainable(e){this.trainable_=e,this.val.trainable=e}}function Tc(e){return e.map((e=>e.read()))}function Ec(e){e.forEach((e=>{e[0].write(e[1])}))}
3845
+ */const Nc="Variable";class Tc{constructor(e,t="float32",n=Nc,i=!0,a=null){this.dtype=null==t?"float32":t,this.shape=e.shape,this.id=hl(),n=null==n?Nc:n,this.originalName=Tl(n),this.name=Il(this.originalName),this.trainable_=i,this.constraint=a,this.val=function(e,t=!0,n,i){return sn.makeVariable(e,t,n,i)}(e,this.trainable_,this.name,this.dtype)}read(){return this.assertNotDisposed(),this.val}write(e){return this.assertNotDisposed(),function(e,t){if(e.shape.toString()!==t.shape.toString())throw new Error("Shape mismatch: "+JSON.stringify(e.shape)+" vs. "+JSON.stringify(t.shape))}(this.val,e),this.val.id!==e.id&&(this.val.assign(e),null!=this.constraint&&this.val.assign(this.constraint.apply(this.val))),this}dispose(){this.assertNotDisposed(),this.val.dispose()}assertNotDisposed(){if(this.val.isDisposed)throw new Error(`LayersVariable ${this.name} is already disposed.`)}get trainable(){return this.trainable_}set trainable(e){this.trainable_=e,this.val.trainable=e}}function Ic(e){return e.map((e=>e.read()))}function Ac(e){e.forEach((e=>{e[0].write(e[1])}))}
3846
3846
  /**
3847
3847
  * @license
3848
3848
  * Copyright 2018 Google LLC
@@ -3851,7 +3851,7 @@ var t;this.scale=null==e.scale?1:e.scale,this.mode=null==e.mode?"fanIn":e.mode,t
3851
3851
  * license that can be found in the LICENSE file or at
3852
3852
  * https://opensource.org/licenses/MIT.
3853
3853
  * =============================================================================
3854
- */class Ac{constructor(e){this.dtype=e.dtype,this.shape=e.shape,null!=e.shape?this.ndim=e.shape.length:this.ndim=e.ndim,this.maxNDim=e.maxNDim,this.minNDim=e.minNDim,this.axes=e.axes||{}}}class Cc{constructor(e,t,n,i,a,s,r){this.dtype=e,this.shape=t,this.sourceLayer=n,this.inputs=i,this.callArgs=a,this.outputTensorIndex=r,this.id=hl(),null!=s&&(this.originalName=Il(s),this.name=Tl(this.originalName)),this.rank=t.length}}let $c=0;class jc{constructor(e,t){this.callArgs=t,this.id=$c++,this.outboundLayer=e.outboundLayer,this.inboundLayers=e.inboundLayers,this.nodeIndices=e.nodeIndices,this.tensorIndices=e.tensorIndices,this.inputTensors=e.inputTensors,this.outputTensors=e.outputTensors,this.inputMasks=e.inputMasks,this.outputMasks=e.outputMasks,this.inputShapes=e.inputShapes,this.outputShapes=e.outputShapes;for(const t of e.inboundLayers)null!=t&&t.outboundNodes.push(this);e.outboundLayer.inboundNodes.push(this)}getConfig(){const e=[];for(const t of this.inboundLayers)null!=t?e.push(t.name):e.push(null);return{outboundLayer:this.outboundLayer?this.outboundLayer.name:null,inboundLayers:e,nodeIndices:this.nodeIndices,tensorIndices:this.tensorIndices}}}let zc=0;class Dc extends gi{constructor(e={}){super(),this._callHook=null,this._addedWeightNames=[],this._stateful=!1,this.id=zc++,this.activityRegularizer=null,this.inputSpec=null,this.supportsMasking=!1,this._trainableWeights=[],this._nonTrainableWeights=[],this._losses=[],this._updates=[],this._built=!1,this.inboundNodes=[],this.outboundNodes=[];let t=e.name;if(!t){const e=this.getClassName();t=Zo(e)+"_"+dl(e)}if(this.name=t,this.trainable_=null==e.trainable||e.trainable,null!=e.inputShape||null!=e.batchInputShape){let t;if(null!=e.batchInputShape)t=e.batchInputShape;else if(null!=e.inputShape){let n=null;null!=e.batchSize&&(n=e.batchSize),t=[n].concat(e.inputShape)}this.batchInputShape=t;let n=e.dtype;null==n&&(n=e.inputDType),null==n&&(n="float32"),this.dtype=n}null!=e.weights?this.initialWeights=e.weights:this.initialWeights=null,this._refCount=null,this.fastWeightInitDuringBuild=!1}static nodeKey(e,t){return e.name+"_ib-"+t.toString()}getNodeAtIndex(e,t){if(0===this.inboundNodes.length)throw new Po(`The layer has never been called and thus has no defined ${t}.`);if(this.inboundNodes.length<=e)throw new Bo(`Asked to get ${t} at node ${e}, but the layer has only ${this.inboundNodes.length} inbound nodes.`);return this.inboundNodes[e]}getInputAt(e){return Ho(this.getNodeAtIndex(e,"input").inputTensors)}getOutputAt(e){return Ho(this.getNodeAtIndex(e,"output").outputTensors)}get input(){if(this.inboundNodes.length>1)throw new Oo(`Layer ${this.name} has multiple inbound nodes, hence the notion of "layer input" is ill-defined. Use \`getInputAt(nodeIndex)\` instead.`);if(0===this.inboundNodes.length)throw new Oo(`Layer ${this.name} is not connected, no input to return.`);return Ho(this.getNodeAtIndex(0,"input").inputTensors)}get output(){if(0===this.inboundNodes.length)throw new Oo(`Layer ${this.name} has no inbound nodes.`);if(this.inboundNodes.length>1)throw new Oo(`Layer ${this.name} has multiple inbound nodes, hence the notion of "layer output" is ill-defined. Use \`getOutputAt(nodeIndex)\` instead.`);return Ho(this.getNodeAtIndex(0,"output").outputTensors)}get losses(){return this._losses}calculateLosses(){return this.losses.map((e=>e()))}get updates(){return this._updates}get built(){return this._built}set built(e){this._built=e}get trainable(){return this.trainable_}set trainable(e){this._trainableWeights.forEach((t=>t.trainable=e)),this.trainable_=e}get trainableWeights(){return this.trainable_?this._trainableWeights.filter((e=>e.trainable)):[]}set trainableWeights(e){this._trainableWeights=e}get nonTrainableWeights(){return this.trainable?this._trainableWeights.filter((e=>!e.trainable)).concat(this._nonTrainableWeights):this._trainableWeights.concat(this._nonTrainableWeights)}set nonTrainableWeights(e){this._nonTrainableWeights=e}get weights(){return this.trainableWeights.concat(this.nonTrainableWeights)}get stateful(){return this._stateful}resetStates(){if(!this.stateful)throw new Error("Cannot call the resetStates() method of a non-stateful Layer object.")}assertInputCompatibility(e){if(e=Jo(e),null==this.inputSpec||0===this.inputSpec.length)return;const t=Jo(this.inputSpec);if(e.length!==t.length)throw new Bo(`Layer ${this.name} expects ${t.length} inputs, but it received ${e.length} input tensors. Input received: ${e}`);for(let n=0;n<e.length;n++){const i=e[n],a=t[n];if(null==a)continue;const s=i.rank;if(null!=a.ndim&&s!==a.ndim)throw new Bo(`Input ${n} is incompatible with layer ${this.name}: expected ndim=${a.ndim}, found ndim=${s}`);if(null!=a.maxNDim&&s>a.maxNDim)throw new Bo(`Input ${n} is incompatible with layer ${this.name}: expected max_ndim=${a.maxNDim}, found ndim=${s}`);if(null!=a.minNDim&&s<a.minNDim)throw new Bo(`Input ${n} is incompatible with layer ${this.name}: expected min_ndim=${a.minNDim}, found ndim=${s}.`);if(null!=a.dtype&&i.dtype!==a.dtype)throw new Bo(`Input ${n} is incompatible with layer ${this.name} : expected dtype=${a.dtype}, found dtype=${i.dtype}.`);if(a.axes){const e=i.shape;for(const t in a.axes){const i=Number(t),s=a.axes[t],r=i>=0?e[i]:e[e.length+i];if(null!=s&&-1===[s,null].indexOf(r))throw new Bo(`Input ${n} is incompatible with layer ${this.name}: expected axis ${i} of input shape to have value ${s} but got shape ${e}.`)}}if(null!=a.shape)for(let e=0;e<a.shape.length;++e){const t=a.shape[e],s=i.shape[e];if(null!=t&&null!=s&&t!==s)throw new Bo(`Input ${n} is incompatible with layer ${this.name}: expected shape=${a.shape}, found shape=${i.shape}.`)}}}call(e,t){return e}invokeCallHook(e,t){null!=this._callHook&&this._callHook(e,t)}setCallHook(e){this._callHook=e}clearCallHook(){this._callHook=null}apply(e,t){t=t||{},this.assertNotDisposed();const n=Jo(e);let i=!0;for(const e of n)if(!(e instanceof Cc)){i=!1;break}let a=!0;for(const e of n)if(e instanceof Cc){a=!1;break}if(i===a)throw new Bo("Arguments to apply() must be all SymbolicTensors or all Tensors");return Nl(this.name,(()=>{if(!this.built){this.assertInputCompatibility(e);const t=[];for(const n of Jo(e))t.push(n.shape);this.build(Ho(t)),this.built=!0,this.initialWeights&&this.setWeights(this.initialWeights),null===this._refCount&&a&&(this._refCount=1)}if(this.assertInputCompatibility(e),a){let i=this.call(e,t);const a=Jo(i),s=[];for(let e of a)-1!==n.indexOf(e)&&(e=e.clone()),s.push(e);if(i=Ho(s),null!=this.activityRegularizer)throw new Uo("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return i}{const n=function(e){e=Jo(e);const t=[];for(const n of e)t.push(n.shape);return Ho(t)}(e),i=this.computeOutputShape(n);let a;const s="float32";if(this.warnOnIncompatibleInputShape(Array.isArray(e)?n[0]:n),a=null!=i&&i.length>0&&Array.isArray(i[0])?i.map(((n,i)=>new Cc(s,n,this,Jo(e),t,this.name,i))):new Cc(s,i,this,Jo(e),t,this.name),this.addInboundNode(e,a,null,null,n,i,t),this._refCount++,null!=this.activityRegularizer)throw new Uo("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return a}}))}warnOnIncompatibleInputShape(e){if(null!=this.batchInputShape)if(e.length!==this.batchInputShape.length)console.warn(`The rank of the input tensor provided (shape: ${JSON.stringify(e)}) does not match that of the batchInputShape (${JSON.stringify(this.batchInputShape)}) of the layer ${this.name}`);else{let t=!1;this.batchInputShape.forEach(((n,i)=>{null!=n&&null!=e[i]&&e[i]!==n&&(t=!0)})),t&&console.warn(`The shape of the input tensor (${JSON.stringify(e)}) does not match the expectation of layer ${this.name}: ${JSON.stringify(this.batchInputShape)}`)}}get outputShape(){if(null==this.inboundNodes||0===this.inboundNodes.length)throw new Oo(`The layer ${this.name} has never been called and thus has no defined output shape.`);const e=[];for(const t of this.inboundNodes){const n=JSON.stringify(t.outputShapes);-1===e.indexOf(n)&&e.push(n)}if(1===e.length){const e=this.inboundNodes[0].outputShapes;return Array.isArray(e)&&Array.isArray(e[0])&&1===e.length?e[0]:e}throw new Oo(`The layer ${this.name} has multiple inbound nodes with different output shapes. Hence the notion of "output shape" is ill-defined for the layer.`)}countParams(){if(!this.built)throw new Po(`You tried to call countParams() on ${this.name}, but the layer is not built yet. Build it first by calling build(batchInputShape).`);return Sc(this.weights)}build(e){this.built=!0}getWeights(e=!1){return Tc(e?this.trainableWeights:this.weights)}setWeights(e){si((()=>{const t=this.weights;if(t.length!==e.length)throw new Bo(`You called setWeights(weights) on layer "${this.name}" with a weight list of length ${e.length}, but the layer was expecting ${t.length} weights. Provided weights: ${e}...`);if(0===t.length)return;const n=[],i=Tc(t);for(let a=0;a<i.length;++a){const s=i[a],r=t[a],o=e[a];if(!C(s.shape,o.shape))throw new Bo(`Layer weight shape ${s.shape} not compatible with provided weight shape ${o.shape}`);n.push([r,o])}Ec(n)}))}addWeight(e,t,n,i,a,s,r,o){if(-1!==this._addedWeightNames.indexOf(e))throw new Bo(`Duplicate weight name ${e} for layer ${this.name}`);this._addedWeightNames.push(e),null==n&&(n="float32"),this.fastWeightInitDuringBuild&&(i=null!=o?o():yc("zeros"));const l=i.apply(t,n),c=new Ic(l,n,e,s,r);return l.dispose(),null!=a&&this.addLoss((()=>a.apply(c.read()))),null==s&&(s=!0),s?this._trainableWeights.push(c):this._nonTrainableWeights.push(c),c}setFastWeightInitDuringBuild(e){this.fastWeightInitDuringBuild=e}addLoss(e){null==e||Array.isArray(e)&&0===e.length||(e=Jo(e),void 0!==this._losses&&null!==this._losses&&this.losses.push(...e))}computeOutputShape(e){return e}computeMask(e,t){if(!this.supportsMasking){if(null!=t){if(!Array.isArray(t))throw new TypeError(`Layer ${this.name} does not support masking, but was passed an inputMask.`);t.forEach((e=>{if(null!=e)throw new TypeError(`Layer ${this.name} does not support masking, but was passed an inputMask.`)}))}return null}return t}addInboundNode(e,t,n,i,a,s,r=null){const o=Jo(e);t=Jo(t),n=Jo(n),i=Jo(i),a=wc(a),s=wc(s);const l=[],c=[],u=[];for(const e of o)l.push(e.sourceLayer),c.push(e.nodeIndex),u.push(e.tensorIndex);new jc({outboundLayer:this,inboundLayers:l,nodeIndices:c,tensorIndices:u,inputTensors:o,outputTensors:t,inputMasks:n,outputMasks:i,inputShapes:a,outputShapes:s},r);for(let e=0;e<t.length;e++)t[e].sourceLayer=this,t[e].nodeIndex=this.inboundNodes.length-1,t[e].tensorIndex=e}getConfig(){const e={name:this.name,trainable:this.trainable};return null!=this.batchInputShape&&(e.batchInputShape=this.batchInputShape),null!=this.dtype&&(e.dtype=this.dtype),e}disposeWeights(){return this.weights.forEach((e=>e.dispose())),this.weights.length}assertNotDisposed(){if(0===this._refCount)throw new Error(`Layer '${this.name}' is already disposed.`)}dispose(){if(!this.built)throw new Error(`Cannot dispose Layer ${this.name} because it has not been built yet.`);if(null===this._refCount)throw new Error(`Cannot dispose Layer ${this.name} because it has not been used yet.`);this.assertNotDisposed();let e=0;return 0==--this._refCount&&(e=this.disposeWeights()),{refCountAfterDispose:this._refCount,numDisposedVariables:e}}}function Fc(e,t,n){if((null==t||null!=n&&n>0)&&(t=e.sourceLayer,n=e.nodeIndex),0===t.inboundNodes.length)return[e];{const e=t.inboundNodes[n];if(0===e.inboundLayers.length)return e.inputTensors;{const t=[];for(let n=0;n<e.inboundLayers.length;n++){const i=Fc(e.inputTensors[n],e.inboundLayers[n],e.nodeIndices[n]);for(const e of i)-1===t.indexOf(e)&&t.push(e)}return t}}}
3854
+ */class Cc{constructor(e){this.dtype=e.dtype,this.shape=e.shape,null!=e.shape?this.ndim=e.shape.length:this.ndim=e.ndim,this.maxNDim=e.maxNDim,this.minNDim=e.minNDim,this.axes=e.axes||{}}}class Ec{constructor(e,t,n,i,a,s,r){this.dtype=e,this.shape=t,this.sourceLayer=n,this.inputs=i,this.callArgs=a,this.outputTensorIndex=r,this.id=hl(),null!=s&&(this.originalName=Tl(s),this.name=Il(this.originalName)),this.rank=t.length}}let $c=0;class jc{constructor(e,t){this.callArgs=t,this.id=$c++,this.outboundLayer=e.outboundLayer,this.inboundLayers=e.inboundLayers,this.nodeIndices=e.nodeIndices,this.tensorIndices=e.tensorIndices,this.inputTensors=e.inputTensors,this.outputTensors=e.outputTensors,this.inputMasks=e.inputMasks,this.outputMasks=e.outputMasks,this.inputShapes=e.inputShapes,this.outputShapes=e.outputShapes;for(const t of e.inboundLayers)null!=t&&t.outboundNodes.push(this);e.outboundLayer.inboundNodes.push(this)}getConfig(){const e=[];for(const t of this.inboundLayers)null!=t?e.push(t.name):e.push(null);return{outboundLayer:this.outboundLayer?this.outboundLayer.name:null,inboundLayers:e,nodeIndices:this.nodeIndices,tensorIndices:this.tensorIndices}}}let zc=0;class Dc extends gi{constructor(e={}){super(),this._callHook=null,this._addedWeightNames=[],this._stateful=!1,this.id=zc++,this.activityRegularizer=null,this.inputSpec=null,this.supportsMasking=!1,this._trainableWeights=[],this._nonTrainableWeights=[],this._losses=[],this._updates=[],this._built=!1,this.inboundNodes=[],this.outboundNodes=[];let t=e.name;if(!t){const e=this.getClassName();t=Zo(e)+"_"+dl(e)}if(this.name=t,this.trainable_=null==e.trainable||e.trainable,null!=e.inputShape||null!=e.batchInputShape){let t;if(null!=e.batchInputShape)t=e.batchInputShape;else if(null!=e.inputShape){let n=null;null!=e.batchSize&&(n=e.batchSize),t=[n].concat(e.inputShape)}this.batchInputShape=t;let n=e.dtype;null==n&&(n=e.inputDType),null==n&&(n="float32"),this.dtype=n}null!=e.weights?this.initialWeights=e.weights:this.initialWeights=null,this._refCount=null,this.fastWeightInitDuringBuild=!1}static nodeKey(e,t){return e.name+"_ib-"+t.toString()}getNodeAtIndex(e,t){if(0===this.inboundNodes.length)throw new Po(`The layer has never been called and thus has no defined ${t}.`);if(this.inboundNodes.length<=e)throw new Bo(`Asked to get ${t} at node ${e}, but the layer has only ${this.inboundNodes.length} inbound nodes.`);return this.inboundNodes[e]}getInputAt(e){return Ho(this.getNodeAtIndex(e,"input").inputTensors)}getOutputAt(e){return Ho(this.getNodeAtIndex(e,"output").outputTensors)}get input(){if(this.inboundNodes.length>1)throw new Oo(`Layer ${this.name} has multiple inbound nodes, hence the notion of "layer input" is ill-defined. Use \`getInputAt(nodeIndex)\` instead.`);if(0===this.inboundNodes.length)throw new Oo(`Layer ${this.name} is not connected, no input to return.`);return Ho(this.getNodeAtIndex(0,"input").inputTensors)}get output(){if(0===this.inboundNodes.length)throw new Oo(`Layer ${this.name} has no inbound nodes.`);if(this.inboundNodes.length>1)throw new Oo(`Layer ${this.name} has multiple inbound nodes, hence the notion of "layer output" is ill-defined. Use \`getOutputAt(nodeIndex)\` instead.`);return Ho(this.getNodeAtIndex(0,"output").outputTensors)}get losses(){return this._losses}calculateLosses(){return this.losses.map((e=>e()))}get updates(){return this._updates}get built(){return this._built}set built(e){this._built=e}get trainable(){return this.trainable_}set trainable(e){this._trainableWeights.forEach((t=>t.trainable=e)),this.trainable_=e}get trainableWeights(){return this.trainable_?this._trainableWeights.filter((e=>e.trainable)):[]}set trainableWeights(e){this._trainableWeights=e}get nonTrainableWeights(){return this.trainable?this._trainableWeights.filter((e=>!e.trainable)).concat(this._nonTrainableWeights):this._trainableWeights.concat(this._nonTrainableWeights)}set nonTrainableWeights(e){this._nonTrainableWeights=e}get weights(){return this.trainableWeights.concat(this.nonTrainableWeights)}get stateful(){return this._stateful}resetStates(){if(!this.stateful)throw new Error("Cannot call the resetStates() method of a non-stateful Layer object.")}assertInputCompatibility(e){if(e=Jo(e),null==this.inputSpec||0===this.inputSpec.length)return;const t=Jo(this.inputSpec);if(e.length!==t.length)throw new Bo(`Layer ${this.name} expects ${t.length} inputs, but it received ${e.length} input tensors. Input received: ${e}`);for(let n=0;n<e.length;n++){const i=e[n],a=t[n];if(null==a)continue;const s=i.rank;if(null!=a.ndim&&s!==a.ndim)throw new Bo(`Input ${n} is incompatible with layer ${this.name}: expected ndim=${a.ndim}, found ndim=${s}`);if(null!=a.maxNDim&&s>a.maxNDim)throw new Bo(`Input ${n} is incompatible with layer ${this.name}: expected max_ndim=${a.maxNDim}, found ndim=${s}`);if(null!=a.minNDim&&s<a.minNDim)throw new Bo(`Input ${n} is incompatible with layer ${this.name}: expected min_ndim=${a.minNDim}, found ndim=${s}.`);if(null!=a.dtype&&i.dtype!==a.dtype)throw new Bo(`Input ${n} is incompatible with layer ${this.name} : expected dtype=${a.dtype}, found dtype=${i.dtype}.`);if(a.axes){const e=i.shape;for(const t in a.axes){const i=Number(t),s=a.axes[t],r=i>=0?e[i]:e[e.length+i];if(null!=s&&-1===[s,null].indexOf(r))throw new Bo(`Input ${n} is incompatible with layer ${this.name}: expected axis ${i} of input shape to have value ${s} but got shape ${e}.`)}}if(null!=a.shape)for(let e=0;e<a.shape.length;++e){const t=a.shape[e],s=i.shape[e];if(null!=t&&null!=s&&t!==s)throw new Bo(`Input ${n} is incompatible with layer ${this.name}: expected shape=${a.shape}, found shape=${i.shape}.`)}}}call(e,t){return e}invokeCallHook(e,t){null!=this._callHook&&this._callHook(e,t)}setCallHook(e){this._callHook=e}clearCallHook(){this._callHook=null}apply(e,t){t=t||{},this.assertNotDisposed();const n=Jo(e);let i=!0;for(const e of n)if(!(e instanceof Ec)){i=!1;break}let a=!0;for(const e of n)if(e instanceof Ec){a=!1;break}if(i===a)throw new Bo("Arguments to apply() must be all SymbolicTensors or all Tensors");return Nl(this.name,(()=>{if(!this.built){this.assertInputCompatibility(e);const t=[];for(const n of Jo(e))t.push(n.shape);this.build(Ho(t)),this.built=!0,this.initialWeights&&this.setWeights(this.initialWeights),null===this._refCount&&a&&(this._refCount=1)}if(this.assertInputCompatibility(e),a){let i=this.call(e,t);const a=Jo(i),s=[];for(let e of a)-1!==n.indexOf(e)&&(e=e.clone()),s.push(e);if(i=Ho(s),null!=this.activityRegularizer)throw new Uo("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return i}{const n=function(e){e=Jo(e);const t=[];for(const n of e)t.push(n.shape);return Ho(t)}(e),i=this.computeOutputShape(n);let a;const s="float32";if(this.warnOnIncompatibleInputShape(Array.isArray(e)?n[0]:n),a=null!=i&&i.length>0&&Array.isArray(i[0])?i.map(((n,i)=>new Ec(s,n,this,Jo(e),t,this.name,i))):new Ec(s,i,this,Jo(e),t,this.name),this.addInboundNode(e,a,null,null,n,i,t),this._refCount++,null!=this.activityRegularizer)throw new Uo("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return a}}))}warnOnIncompatibleInputShape(e){if(null!=this.batchInputShape)if(e.length!==this.batchInputShape.length)console.warn(`The rank of the input tensor provided (shape: ${JSON.stringify(e)}) does not match that of the batchInputShape (${JSON.stringify(this.batchInputShape)}) of the layer ${this.name}`);else{let t=!1;this.batchInputShape.forEach(((n,i)=>{null!=n&&null!=e[i]&&e[i]!==n&&(t=!0)})),t&&console.warn(`The shape of the input tensor (${JSON.stringify(e)}) does not match the expectation of layer ${this.name}: ${JSON.stringify(this.batchInputShape)}`)}}get outputShape(){if(null==this.inboundNodes||0===this.inboundNodes.length)throw new Oo(`The layer ${this.name} has never been called and thus has no defined output shape.`);const e=[];for(const t of this.inboundNodes){const n=JSON.stringify(t.outputShapes);-1===e.indexOf(n)&&e.push(n)}if(1===e.length){const e=this.inboundNodes[0].outputShapes;return Array.isArray(e)&&Array.isArray(e[0])&&1===e.length?e[0]:e}throw new Oo(`The layer ${this.name} has multiple inbound nodes with different output shapes. Hence the notion of "output shape" is ill-defined for the layer.`)}countParams(){if(!this.built)throw new Po(`You tried to call countParams() on ${this.name}, but the layer is not built yet. Build it first by calling build(batchInputShape).`);return Sc(this.weights)}build(e){this.built=!0}getWeights(e=!1){return Ic(e?this.trainableWeights:this.weights)}setWeights(e){si((()=>{const t=this.weights;if(t.length!==e.length)throw new Bo(`You called setWeights(weights) on layer "${this.name}" with a weight list of length ${e.length}, but the layer was expecting ${t.length} weights. Provided weights: ${e}...`);if(0===t.length)return;const n=[],i=Ic(t);for(let a=0;a<i.length;++a){const s=i[a],r=t[a],o=e[a];if(!E(s.shape,o.shape))throw new Bo(`Layer weight shape ${s.shape} not compatible with provided weight shape ${o.shape}`);n.push([r,o])}Ac(n)}))}addWeight(e,t,n,i,a,s,r,o){if(-1!==this._addedWeightNames.indexOf(e))throw new Bo(`Duplicate weight name ${e} for layer ${this.name}`);this._addedWeightNames.push(e),null==n&&(n="float32"),this.fastWeightInitDuringBuild&&(i=null!=o?o():yc("zeros"));const l=i.apply(t,n),c=new Tc(l,n,e,s,r);return l.dispose(),null!=a&&this.addLoss((()=>a.apply(c.read()))),null==s&&(s=!0),s?this._trainableWeights.push(c):this._nonTrainableWeights.push(c),c}setFastWeightInitDuringBuild(e){this.fastWeightInitDuringBuild=e}addLoss(e){null==e||Array.isArray(e)&&0===e.length||(e=Jo(e),void 0!==this._losses&&null!==this._losses&&this.losses.push(...e))}computeOutputShape(e){return e}computeMask(e,t){if(!this.supportsMasking){if(null!=t){if(!Array.isArray(t))throw new TypeError(`Layer ${this.name} does not support masking, but was passed an inputMask.`);t.forEach((e=>{if(null!=e)throw new TypeError(`Layer ${this.name} does not support masking, but was passed an inputMask.`)}))}return null}return t}addInboundNode(e,t,n,i,a,s,r=null){const o=Jo(e);t=Jo(t),n=Jo(n),i=Jo(i),a=wc(a),s=wc(s);const l=[],c=[],u=[];for(const e of o)l.push(e.sourceLayer),c.push(e.nodeIndex),u.push(e.tensorIndex);new jc({outboundLayer:this,inboundLayers:l,nodeIndices:c,tensorIndices:u,inputTensors:o,outputTensors:t,inputMasks:n,outputMasks:i,inputShapes:a,outputShapes:s},r);for(let e=0;e<t.length;e++)t[e].sourceLayer=this,t[e].nodeIndex=this.inboundNodes.length-1,t[e].tensorIndex=e}getConfig(){const e={name:this.name,trainable:this.trainable};return null!=this.batchInputShape&&(e.batchInputShape=this.batchInputShape),null!=this.dtype&&(e.dtype=this.dtype),e}disposeWeights(){return this.weights.forEach((e=>e.dispose())),this.weights.length}assertNotDisposed(){if(0===this._refCount)throw new Error(`Layer '${this.name}' is already disposed.`)}dispose(){if(!this.built)throw new Error(`Cannot dispose Layer ${this.name} because it has not been built yet.`);if(null===this._refCount)throw new Error(`Cannot dispose Layer ${this.name} because it has not been used yet.`);this.assertNotDisposed();let e=0;return 0==--this._refCount&&(e=this.disposeWeights()),{refCountAfterDispose:this._refCount,numDisposedVariables:e}}}function Fc(e,t,n){if((null==t||null!=n&&n>0)&&(t=e.sourceLayer,n=e.nodeIndex),0===t.inboundNodes.length)return[e];{const e=t.inboundNodes[n];if(0===e.inboundLayers.length)return e.inputTensors;{const t=[];for(let n=0;n<e.inboundLayers.length;n++){const i=Fc(e.inputTensors[n],e.inboundLayers[n],e.nodeIndices[n]);for(const e of i)-1===t.indexOf(e)&&t.push(e)}return t}}}
3855
3855
  /**
3856
3856
  * @license
3857
3857
  * Copyright 2018 Google LLC
@@ -3860,7 +3860,7 @@ var t;this.scale=null==e.scale?1:e.scale,this.mode=null==e.mode?"fanIn":e.mode,t
3860
3860
  * license that can be found in the LICENSE file or at
3861
3861
  * https://opensource.org/licenses/MIT.
3862
3862
  * =============================================================================
3863
- */class _c extends Dc{constructor(e){if(super({dtype:e.dtype,name:null!=e.name?e.name:dl("input").toString()}),null==e.batchSize&&(e.batchSize=null),null==e.sparse&&(e.sparse=!1),this.trainable=!1,this.built=!0,this.sparse=e.sparse,null!=e.inputShape&&null!=e.batchInputShape)throw new Bo("Only provide the inputShape OR batchInputShape argument to inputLayer, not both at the same time.");let t=e.batchInputShape;if(null==t){if(null==e.inputShape)throw new Bo("An InputLayer should be passed either a `batchInputShape` or an `inputShape`.");t=[e.batchSize].concat(e.inputShape)}else if(null!=e.batchSize)throw new Bo("Cannot specify batchSize if batchInputShape is specified when creating an InputLayer.");const n=e.dtype||"float32";this.batchInputShape=t,this.dtype=n,this.inputSpec=[{shape:t}];const i=new Cc(this.dtype,this.batchInputShape,this,[],{},this.name);i.nodeIndex=0,i.tensorIndex=0,new jc({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:[i],outputTensors:[i],inputMasks:[null],outputMasks:[null],inputShapes:[t],outputShapes:[t]})}apply(e,t){throw new Bo(`Cannot pass any input to an InputLayer's apply() method. InputLayer name: ${this.name}`)}dispose(){return{refCountAfterDispose:this._refCount,numDisposedVariables:0}}getConfig(){return{batchInputShape:this.batchInputShape,dtype:this.dtype,sparse:this.sparse,name:this.name}}}_c.className="InputLayer",yi(_c);class Rc{constructor(e){if(this.id2Value={},this.id2Mask={},this.name2Id={},e instanceof Rc)for(const t in e.id2Value)this.id2Value[t]=e.id2Value[t],t in e.id2Mask&&(this.id2Mask[t]=e.id2Mask[t]);else{if(null==e)return;for(const t of e)this.add(t.key,t.value)}}add(e,t,n){if(null!=this.id2Value[e.id])throw new Bo(`Duplicate key: name=${e.name}, id=${e.id}`);return this.id2Value[e.id]=
3863
+ */class _c extends Dc{constructor(e){if(super({dtype:e.dtype,name:null!=e.name?e.name:dl("input").toString()}),null==e.batchSize&&(e.batchSize=null),null==e.sparse&&(e.sparse=!1),this.trainable=!1,this.built=!0,this.sparse=e.sparse,null!=e.inputShape&&null!=e.batchInputShape)throw new Bo("Only provide the inputShape OR batchInputShape argument to inputLayer, not both at the same time.");let t=e.batchInputShape;if(null==t){if(null==e.inputShape)throw new Bo("An InputLayer should be passed either a `batchInputShape` or an `inputShape`.");t=[e.batchSize].concat(e.inputShape)}else if(null!=e.batchSize)throw new Bo("Cannot specify batchSize if batchInputShape is specified when creating an InputLayer.");const n=e.dtype||"float32";this.batchInputShape=t,this.dtype=n,this.inputSpec=[{shape:t}];const i=new Ec(this.dtype,this.batchInputShape,this,[],{},this.name);i.nodeIndex=0,i.tensorIndex=0,new jc({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:[i],outputTensors:[i],inputMasks:[null],outputMasks:[null],inputShapes:[t],outputShapes:[t]})}apply(e,t){throw new Bo(`Cannot pass any input to an InputLayer's apply() method. InputLayer name: ${this.name}`)}dispose(){return{refCountAfterDispose:this._refCount,numDisposedVariables:0}}getConfig(){return{batchInputShape:this.batchInputShape,dtype:this.dtype,sparse:this.sparse,name:this.name}}}_c.className="InputLayer",yi(_c);class Rc{constructor(e){if(this.id2Value={},this.id2Mask={},this.name2Id={},e instanceof Rc)for(const t in e.id2Value)this.id2Value[t]=e.id2Value[t],t in e.id2Mask&&(this.id2Mask[t]=e.id2Mask[t]);else{if(null==e)return;for(const t of e)this.add(t.key,t.value)}}add(e,t,n){if(null!=this.id2Value[e.id])throw new Bo(`Duplicate key: name=${e.name}, id=${e.id}`);return this.id2Value[e.id]=
3864
3864
  /**
3865
3865
  * @license
3866
3866
  * Copyright 2018 Google LLC
@@ -3870,7 +3870,7 @@ var t;this.scale=null==e.scale?1:e.scale,this.mode=null==e.mode?"fanIn":e.mode,t
3870
3870
  * https://opensource.org/licenses/MIT.
3871
3871
  * =============================================================================
3872
3872
  */
3873
- function(e,t){if(null==e.dtype||e.dtype===t.dtype)return t;try{return ei(t,e.dtype)}catch(n){throw new Bo(`The dtype of the feed (${t.dtype}) can not be cast to the dtype of the key '${e.name}' (${e.dtype}).`)}}(e,t),this.name2Id[e.name]=e.id,null!=n&&(this.id2Mask[e.id]=n),this}addFeed(e){this.add(e.key,e.value)}hasKey(e){return null!=this.id2Value[e.id]}names(){return Object.keys(this.name2Id)}getValue(e){if(e instanceof Cc){if(null==this.id2Value[e.id])throw new Bo(`Nonexistent key: ${e.name}`);return this.id2Value[e.id]}{const t=this.name2Id[e];if(null==t)throw new Bo(`Feed dict has no SymbolicTensor name: ${e}`);return this.id2Value[t]}}getMask(e){if(e instanceof Cc){if(null==this.id2Value[e.id])throw new Bo(`Nonexistent key: ${e.name}`);return this.id2Mask[e.id]}{const t=this.name2Id[e];if(null==t)throw new Bo(`Feed dict has no SymbolicTensor name: ${e}`);return this.id2Mask[t]}}disposeMasks(){null!=this.id2Mask&&ri(this.id2Mask)}}const Lc=new Go,Mc=new Go;function Oc(e,t,n,i){const a=null!=n&&n.training,s=Array.isArray(e),r=s?e:[e],o=r.map((e=>e.name)),l=[],c=t.names();for(const e of o)-1!==c.indexOf(e)?l.push(t.getValue(e)):l.push(null);null!=i&&(i.maxNumTensors=-1/0,i.minNumTensors=1/0);const u=o.join(",")+"|"+t.names().sort().join(",");let h,p=Lc.get(u);if(null==p){const e=function(e,t){I(null!=e&&e.length>0,(()=>"Expected at least one fetch, got none"));let n=[],i={};if(1===e.length){const a=Bc(e[0],t);n=a.sorted,i=a.recipientMap}else{const a=new Set;for(const s of e){const{sorted:e,recipientMap:r}=Bc(s,t);for(const t of e)a.has(t.name)||(n.push(t),a.add(t.name));for(const e in r)null==i[e]&&(i[e]=new Set),r[e].forEach((t=>i[e].add(t)))}}return{sorted:n,recipientCounts:Pc(i)}}(r,t);p=e.sorted,h=e.recipientCounts,Lc.put(u,p),Mc.put(u,h)}h={},a||Object.assign(h,Mc.get(u));const d=new Rc(t);for(let e=0;e<p.length;++e){if(null!=i){const e=ai().numTensors;e>i.maxNumTensors&&(i.maxNumTensors=e),e<i.minNumTensors&&(i.minNumTensors=e)}const s=p[e],r=s.sourceLayer;if(r instanceof _c)continue;const c=[],u=[],m=[];let f=!1;for(const e of s.inputs){const n=d.getValue(e),i=d.getMask(e);c.push(n),u.push(i),null!=i&&(f=!0),a||(h[e.name]--,0!==h[e.name]||t.hasKey(e)||-1!==o.indexOf(e.name)||n.isDisposed||!0===e.sourceLayer.stateful||m.push(n))}f&&((n=n||{}).mask=u[0]);const g=Jo(r.apply(c,n));let v=null;r.supportsMasking&&(v=r.computeMask(c,u));const y=Uc(s),b=Array.isArray(y)?y:[y];for(let e=0;e<b.length;++e){d.hasKey(b[e])||d.add(b[e],g[e],Array.isArray(v)?v[0]:v);const t=o.indexOf(b[e].name);-1!==t&&(l[t]=g[e])}a||ri(m)}return d.disposeMasks(),s?l:l[0]}function Pc(e){const t={};for(const n in e)t[n]=e[n].size;return t}function Bc(e,t){const n=new Set,i=[],a={};for(const e of t.names())n.add(e);const s=[],r=[];for(s.push(e);s.length>0;){const e=s[s.length-1];if(n.has(e.name)){s.pop();continue}const t=r[r.length-1]===s.length-1;if(0===e.inputs.length||t)s.pop(),i.push(e),n.add(e.name),t&&r.pop();else{r.push(s.length-1);for(const t of e.inputs)null==a[t.name]&&(a[t.name]=new Set),a[t.name].add(e.name),n.has(t.name)||s.push(t)}}return{sorted:i,recipientMap:a}}function Uc(e){let t;if(1===e.sourceLayer.inboundNodes.length)t=e.sourceLayer.output;else{let n=null;for(let t=0;t<e.sourceLayer.inboundNodes.length;++t)for(const i of e.sourceLayer.inboundNodes[t].outputTensors)if(i.id===e.id){n=t;break}t=e.sourceLayer.getOutputAt(n)}return t}
3873
+ function(e,t){if(null==e.dtype||e.dtype===t.dtype)return t;try{return ei(t,e.dtype)}catch(n){throw new Bo(`The dtype of the feed (${t.dtype}) can not be cast to the dtype of the key '${e.name}' (${e.dtype}).`)}}(e,t),this.name2Id[e.name]=e.id,null!=n&&(this.id2Mask[e.id]=n),this}addFeed(e){this.add(e.key,e.value)}hasKey(e){return null!=this.id2Value[e.id]}names(){return Object.keys(this.name2Id)}getValue(e){if(e instanceof Ec){if(null==this.id2Value[e.id])throw new Bo(`Nonexistent key: ${e.name}`);return this.id2Value[e.id]}{const t=this.name2Id[e];if(null==t)throw new Bo(`Feed dict has no SymbolicTensor name: ${e}`);return this.id2Value[t]}}getMask(e){if(e instanceof Ec){if(null==this.id2Value[e.id])throw new Bo(`Nonexistent key: ${e.name}`);return this.id2Mask[e.id]}{const t=this.name2Id[e];if(null==t)throw new Bo(`Feed dict has no SymbolicTensor name: ${e}`);return this.id2Mask[t]}}disposeMasks(){null!=this.id2Mask&&ri(this.id2Mask)}}const Lc=new Vo,Mc=new Vo;function Oc(e,t,n,i){const a=null!=n&&n.training,s=Array.isArray(e),r=s?e:[e],o=r.map((e=>e.name)),l=[],c=t.names();for(const e of o)-1!==c.indexOf(e)?l.push(t.getValue(e)):l.push(null);null!=i&&(i.maxNumTensors=-1/0,i.minNumTensors=1/0);const u=o.join(",")+"|"+t.names().sort().join(",");let h,p=Lc.get(u);if(null==p){const e=function(e,t){T(null!=e&&e.length>0,(()=>"Expected at least one fetch, got none"));let n=[],i={};if(1===e.length){const a=Bc(e[0],t);n=a.sorted,i=a.recipientMap}else{const a=new Set;for(const s of e){const{sorted:e,recipientMap:r}=Bc(s,t);for(const t of e)a.has(t.name)||(n.push(t),a.add(t.name));for(const e in r)null==i[e]&&(i[e]=new Set),r[e].forEach((t=>i[e].add(t)))}}return{sorted:n,recipientCounts:Pc(i)}}(r,t);p=e.sorted,h=e.recipientCounts,Lc.put(u,p),Mc.put(u,h)}h={},a||Object.assign(h,Mc.get(u));const d=new Rc(t);for(let e=0;e<p.length;++e){if(null!=i){const e=ai().numTensors;e>i.maxNumTensors&&(i.maxNumTensors=e),e<i.minNumTensors&&(i.minNumTensors=e)}const s=p[e],r=s.sourceLayer;if(r instanceof _c)continue;const c=[],u=[],m=[];let f=!1;for(const e of s.inputs){const n=d.getValue(e),i=d.getMask(e);c.push(n),u.push(i),null!=i&&(f=!0),a||(h[e.name]--,0!==h[e.name]||t.hasKey(e)||-1!==o.indexOf(e.name)||n.isDisposed||!0===e.sourceLayer.stateful||m.push(n))}f&&((n=n||{}).mask=u[0]);const g=Jo(r.apply(c,n));let v=null;r.supportsMasking&&(v=r.computeMask(c,u));const y=Uc(s),b=Array.isArray(y)?y:[y];for(let e=0;e<b.length;++e){d.hasKey(b[e])||d.add(b[e],g[e],Array.isArray(v)?v[0]:v);const t=o.indexOf(b[e].name);-1!==t&&(l[t]=g[e])}a||ri(m)}return d.disposeMasks(),s?l:l[0]}function Pc(e){const t={};for(const n in e)t[n]=e[n].size;return t}function Bc(e,t){const n=new Set,i=[],a={};for(const e of t.names())n.add(e);const s=[],r=[];for(s.push(e);s.length>0;){const e=s[s.length-1];if(n.has(e.name)){s.pop();continue}const t=r[r.length-1]===s.length-1;if(0===e.inputs.length||t)s.pop(),i.push(e),n.add(e.name),t&&r.pop();else{r.push(s.length-1);for(const t of e.inputs)null==a[t.name]&&(a[t.name]=new Set),a[t.name].add(e.name),n.has(t.name)||s.push(t)}}return{sorted:i,recipientMap:a}}function Uc(e){let t;if(1===e.sourceLayer.inboundNodes.length)t=e.sourceLayer.output;else{let n=null;for(let t=0;t<e.sourceLayer.inboundNodes.length;++t)for(const i of e.sourceLayer.inboundNodes[t].outputTensors)if(i.id===e.id){n=t;break}t=e.sourceLayer.getOutputAt(n)}return t}
3874
3874
  /**
3875
3875
  * @license
3876
3876
  * Copyright 2022 Google LLC. All Rights Reserved.
@@ -3903,7 +3903,7 @@ function(e,t){if(null==e.dtype||e.dtype===t.dtype)return t;try{return ei(t,e.dty
3903
3903
  * limitations under the License.
3904
3904
  * =============================================================================
3905
3905
  */
3906
- const Wc={kernelName:"Abs",inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>xi(e,Gs(ei(n,"float32"),-1))}}},Gc={kernelName:"Acos",inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const t=$a(ei(n,"float32")),i=Ca(Ja(Aa(1),t));return ci(ki(e,i))}}}},Vc={kernelName:"Acosh",inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const t=Ca(Ja($a(ei(n,"float32")),1));return ki(e,t)}}}},Kc={kernelName:ie,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,i]=t,a=mi(n.shape,i.shape);return{a:()=>{let t=e;const i=di(n.shape,a);return i.length>0&&(t=ja(t,i)),_i(t,n.shape)},b:()=>{let t=e;const n=di(i.shape,a);return n.length>0&&(t=ja(t,n)),_i(t,i.shape)}}}},qc={kernelName:"AddN",saveAllInputs:!0,gradFunc:(e,t)=>{const n={};return t.forEach(((t,i)=>{n[i]=()=>e.clone()})),n}},Hc={kernelName:ae,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>ya(n)}}},Jc={kernelName:"ArgMin",inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>ya(n)}}},Zc={kernelName:"Asin",inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>ki(e,Ca(Ja(Aa(1),$a(ei(n,"float32")))))}}},Yc={kernelName:"Asinh",inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const t=Ca(bi(Aa(1),$a(ei(n,"float32"))));return ki(e,t)}}}},Qc={kernelName:"Atan2",inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,i]=t,a=mi(n.shape,i.shape);return{a:()=>{const t=bi($a(n),$a(i));let s=xi(e,ki(i,t));const r=di(n.shape,a);return r.length>0&&(s=ja(s,r)),_i(s,n.shape)},b:()=>{const t=bi($a(n),$a(i));let s=ci(xi(e,ki(n,t)));const r=di(i.shape,a);return r.length>0&&(s=ja(s,r)),_i(s,i.shape)}}}},Xc={kernelName:"Atan",inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>ki(e,bi($a(ei(n,"float32")),1))}}},eu={kernelName:"Atanh",inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>ki(e,Ja(Aa(1),$a(ei(n,"float32"))))}}};
3906
+ const Wc={kernelName:"Abs",inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>xi(e,Vs(ei(n,"float32"),-1))}}},Vc={kernelName:"Acos",inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const t=$a(ei(n,"float32")),i=Ea(Ja(Ca(1),t));return ci(ki(e,i))}}}},Gc={kernelName:"Acosh",inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const t=Ea(Ja($a(ei(n,"float32")),1));return ki(e,t)}}}},Kc={kernelName:ie,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,i]=t,a=mi(n.shape,i.shape);return{a:()=>{let t=e;const i=di(n.shape,a);return i.length>0&&(t=ja(t,i)),_i(t,n.shape)},b:()=>{let t=e;const n=di(i.shape,a);return n.length>0&&(t=ja(t,n)),_i(t,i.shape)}}}},qc={kernelName:"AddN",saveAllInputs:!0,gradFunc:(e,t)=>{const n={};return t.forEach(((t,i)=>{n[i]=()=>e.clone()})),n}},Hc={kernelName:ae,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>ya(n)}}},Jc={kernelName:"ArgMin",inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>ya(n)}}},Zc={kernelName:"Asin",inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>ki(e,Ea(Ja(Ca(1),$a(ei(n,"float32")))))}}},Yc={kernelName:"Asinh",inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const t=Ea(bi(Ca(1),$a(ei(n,"float32"))));return ki(e,t)}}}},Qc={kernelName:"Atan2",inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,i]=t,a=mi(n.shape,i.shape);return{a:()=>{const t=bi($a(n),$a(i));let s=xi(e,ki(i,t));const r=di(n.shape,a);return r.length>0&&(s=ja(s,r)),_i(s,n.shape)},b:()=>{const t=bi($a(n),$a(i));let s=ci(xi(e,ki(n,t)));const r=di(i.shape,a);return r.length>0&&(s=ja(s,r)),_i(s,i.shape)}}}},Xc={kernelName:"Atan",inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>ki(e,bi($a(ei(n,"float32")),1))}}},eu={kernelName:"Atanh",inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>ki(e,Ja(Ca(1),$a(ei(n,"float32"))))}}};
3907
3907
  /**
3908
3908
  * @license
3909
3909
  * Copyright 2020 Google LLC. All Rights Reserved.
@@ -3936,7 +3936,7 @@ const Wc={kernelName:"Abs",inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return
3936
3936
  * limitations under the License.
3937
3937
  * =============================================================================
3938
3938
  */
3939
- function(e,t,n,i,a,s){const r=hn(e,"dy","avgPool3dGrad"),o=hn(t,"input","avgPool3dGrad");let l=r,c=o,u=!1;4===o.rank&&(u=!0,l=_i(r,[1,r.shape[0],r.shape[1],r.shape[2],r.shape[3]]),c=_i(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),I(5===l.rank,(()=>`Error in avgPool3dGrad: dy must be rank 5 but got rank ${l.rank}.`)),I(5===c.rank,(()=>`Error in avgPool3dGrad: input must be rank 5 but got rank ${c.rank}.`)),Fi("avgPool3dGrad",a,s);const h={dy:l,input:c},p={filterSize:n,strides:i,pad:a,dimRoundingMode:s},d=sn.runKernel("AvgPool3DGrad",h,p);return u?_i(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}}),nu={kernelName:re,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[i]=t,{filterSize:a,strides:s,pad:r,dimRoundingMode:o}=n;return{x:()=>tu(e,i,a,s,r,o)}}};
3939
+ function(e,t,n,i,a,s){const r=hn(e,"dy","avgPool3dGrad"),o=hn(t,"input","avgPool3dGrad");let l=r,c=o,u=!1;4===o.rank&&(u=!0,l=_i(r,[1,r.shape[0],r.shape[1],r.shape[2],r.shape[3]]),c=_i(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),T(5===l.rank,(()=>`Error in avgPool3dGrad: dy must be rank 5 but got rank ${l.rank}.`)),T(5===c.rank,(()=>`Error in avgPool3dGrad: input must be rank 5 but got rank ${c.rank}.`)),Fi("avgPool3dGrad",a,s);const h={dy:l,input:c},p={filterSize:n,strides:i,pad:a,dimRoundingMode:s},d=sn.runKernel("AvgPool3DGrad",h,p);return u?_i(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}}),nu={kernelName:re,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[i]=t,{filterSize:a,strides:s,pad:r,dimRoundingMode:o}=n;return{x:()=>tu(e,i,a,s,r,o)}}};
3940
3940
  /**
3941
3941
  * @license
3942
3942
  * Copyright 2020 Google LLC. All Rights Reserved.
@@ -3969,7 +3969,7 @@ function(e,t,n,i,a,s){const r=hn(e,"dy","avgPool3dGrad"),o=hn(t,"input","avgPool
3969
3969
  * limitations under the License.
3970
3970
  * =============================================================================
3971
3971
  */
3972
- function(e,t,n,i,a){const s=hn(e,"dy","avgPoolGrad"),r=hn(t,"input","avgPoolGrad");I(r.rank===s.rank,(()=>`Rank of input (${r.rank}) does not match rank of dy (${s.rank})`));let o=r,l=s,c=!1;3===r.rank&&(c=!0,o=_i(r,[1,r.shape[0],r.shape[1],r.shape[2]]),l=_i(s,[1,s.shape[0],s.shape[1],s.shape[2]])),I(4===l.rank,(()=>`Error in avgPoolGrad: dy must be rank 4 but got rank ${l.rank}.`)),I(4===o.rank,(()=>`Error in avgPoolGrad: input must be rank 4 but got rank ${o.rank}.`));const u={dy:l,input:o},h={filterSize:n,strides:i,pad:a},p=sn.runKernel("AvgPoolGrad",u,h);return c?_i(p,[p.shape[1],p.shape[2],p.shape[3]]):p}}),au={kernelName:se,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[i]=t,{filterSize:a,strides:s,pad:r}=n;return{x:()=>iu(e,i,a,s,r)}}},su={kernelName:oe,inputsToSave:["a","b"],gradFunc:(e,t,n)=>{const[i,a]=t,{transposeA:s,transposeB:r}=n;return s||r?!s&&r?{a:()=>ti(e,a,!1,!1),b:()=>ti(e,i,!0,!1)}:s&&!r?{a:()=>ti(a,e,!1,!0),b:()=>ti(i,e,!1,!1)}:{a:()=>ti(a,e,!0,!0),b:()=>ti(e,i,!0,!0)}:{a:()=>ti(e,a,!1,!0),b:()=>ti(i,e,!0,!1)}}},ru={kernelName:le,gradFunc:(e,t,n)=>{const{blockShape:i,crops:a}=n;return{x:()=>us(e,i,a)}}},ou={kernelName:"BroadcastTo",gradFunc:(e,t,n)=>{const i=n,a=i.inputShape,s=i.shape,r=Array.from(s);for(let e=a.length-1;e>=0;e--)if(a[e]===s[e])r[e]=1;else if(1!==a[e])throw new Error(`broadcastTo(): [${a}] cannot be broadcast to [${s}].`);const o=[];for(let e=0;e<r.length;e++)r[e]>1&&o.push(e);return{x:()=>ja(e,o,!0)}}},lu={kernelName:ce,gradFunc:e=>({x:()=>e.clone()})},cu={kernelName:"Ceil",gradFunc:e=>({x:()=>ya(e)})},uu={kernelName:ue,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[i]=t,{clipValueMin:a,clipValueMax:s}=n;return{x:()=>va(Ya(Ba(i,a),Ga(i,s)),e,ya(e))}}},hu={kernelName:he,inputsToSave:["x"],gradFunc:Wc.gradFunc},pu={kernelName:pe,saveAllInputs:!0,gradFunc:(e,t,n)=>{const i=t.map((e=>e.shape)),{axis:a}=n,s=z(a,t[0].shape)[0],r=i.map((e=>e[s]));return Bs(e,r,s).map((e=>()=>e))}},du={kernelName:de,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{const[i,a]=t,{dilations:s,strides:r,pad:o,dataFormat:l}=n;return I(ji(s),(()=>`Error in gradient of conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${s}'`)),{x:()=>sa(i.shape,e,a,r,o,l),filter:()=>Ys(i,e,a.shape,r,o,l)}}},mu={kernelName:me,inputsToSave:["dy","filter"],gradFunc:(e,t,n)=>{const[i,a]=t,{strides:s,pad:r,dataFormat:o,dimRoundingMode:l}=n;return{dy:()=>ia(e,a,s,r,o,1,l),filter:()=>Ys(e,i,a.shape,s,r,o,l)}}};
3972
+ function(e,t,n,i,a){const s=hn(e,"dy","avgPoolGrad"),r=hn(t,"input","avgPoolGrad");T(r.rank===s.rank,(()=>`Rank of input (${r.rank}) does not match rank of dy (${s.rank})`));let o=r,l=s,c=!1;3===r.rank&&(c=!0,o=_i(r,[1,r.shape[0],r.shape[1],r.shape[2]]),l=_i(s,[1,s.shape[0],s.shape[1],s.shape[2]])),T(4===l.rank,(()=>`Error in avgPoolGrad: dy must be rank 4 but got rank ${l.rank}.`)),T(4===o.rank,(()=>`Error in avgPoolGrad: input must be rank 4 but got rank ${o.rank}.`));const u={dy:l,input:o},h={filterSize:n,strides:i,pad:a},p=sn.runKernel("AvgPoolGrad",u,h);return c?_i(p,[p.shape[1],p.shape[2],p.shape[3]]):p}}),au={kernelName:se,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[i]=t,{filterSize:a,strides:s,pad:r}=n;return{x:()=>iu(e,i,a,s,r)}}},su={kernelName:oe,inputsToSave:["a","b"],gradFunc:(e,t,n)=>{const[i,a]=t,{transposeA:s,transposeB:r}=n;return s||r?!s&&r?{a:()=>ti(e,a,!1,!1),b:()=>ti(e,i,!0,!1)}:s&&!r?{a:()=>ti(a,e,!1,!0),b:()=>ti(i,e,!1,!1)}:{a:()=>ti(a,e,!0,!0),b:()=>ti(e,i,!0,!0)}:{a:()=>ti(e,a,!1,!0),b:()=>ti(i,e,!0,!1)}}},ru={kernelName:le,gradFunc:(e,t,n)=>{const{blockShape:i,crops:a}=n;return{x:()=>us(e,i,a)}}},ou={kernelName:"BroadcastTo",gradFunc:(e,t,n)=>{const i=n,a=i.inputShape,s=i.shape,r=Array.from(s);for(let e=a.length-1;e>=0;e--)if(a[e]===s[e])r[e]=1;else if(1!==a[e])throw new Error(`broadcastTo(): [${a}] cannot be broadcast to [${s}].`);const o=[];for(let e=0;e<r.length;e++)r[e]>1&&o.push(e);return{x:()=>ja(e,o,!0)}}},lu={kernelName:ce,gradFunc:e=>({x:()=>e.clone()})},cu={kernelName:"Ceil",gradFunc:e=>({x:()=>ya(e)})},uu={kernelName:ue,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[i]=t,{clipValueMin:a,clipValueMax:s}=n;return{x:()=>va(Ya(Ba(i,a),Va(i,s)),e,ya(e))}}},hu={kernelName:he,inputsToSave:["x"],gradFunc:Wc.gradFunc},pu={kernelName:pe,saveAllInputs:!0,gradFunc:(e,t,n)=>{const i=t.map((e=>e.shape)),{axis:a}=n,s=z(a,t[0].shape)[0],r=i.map((e=>e[s]));return Bs(e,r,s).map((e=>()=>e))}},du={kernelName:de,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{const[i,a]=t,{dilations:s,strides:r,pad:o,dataFormat:l}=n;return T(ji(s),(()=>`Error in gradient of conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${s}'`)),{x:()=>sa(i.shape,e,a,r,o,l),filter:()=>Ys(i,e,a.shape,r,o,l)}}},mu={kernelName:me,inputsToSave:["dy","filter"],gradFunc:(e,t,n)=>{const[i,a]=t,{strides:s,pad:r,dataFormat:o,dimRoundingMode:l}=n;return{dy:()=>ia(e,a,s,r,o,1,l),filter:()=>Ys(e,i,a.shape,s,r,o,l)}}};
3973
3973
  /**
3974
3974
  * @license
3975
3975
  * Copyright 2020 Google LLC. All Rights Reserved.
@@ -4002,7 +4002,7 @@ function(e,t,n,i,a){const s=hn(e,"dy","avgPoolGrad"),r=hn(t,"input","avgPoolGrad
4002
4002
  * limitations under the License.
4003
4003
  * =============================================================================
4004
4004
  */
4005
- function(e,t,n,i,a){let s=e;4===e.rank&&(s=_i(e,[1,e.shape[0],e.shape[1],e.shape[2],e.shape[3]]));let r=t;4===r.rank&&(r=_i(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]])),I(5===s.rank,(()=>`Error in conv3dDerFilter: input must be rank 5, but got shape ${s.shape}.`)),I(5===r.rank,(()=>`Error in conv3dDerFilter: dy must be rank 5, but got shape ${r.shape}.`)),I(5===n.length,(()=>`Error in conv3dDerFilter: filterShape must be length 5, but got ${n}.`)),I(s.shape[4]===n[3],(()=>`Error in conv3dDerFilter: depth of input ${s.shape[4]}) must match input depth in filter (${n[3]}.`)),I(r.shape[4]===n[4],(()=>`Error in conv3dDerFilter: depth of dy (${r.shape[4]}) must match output depth for filter (${n[4]}).`));const o={x:s,dy:r},l={strides:i,pad:a,filterShape:n};return sn.runKernel("Conv3DBackpropFilterV2",o,l)}}),gu={kernelName:fe,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{const{dilations:i,strides:a,pad:s}=n;I(ji(i),(()=>`Error in gradient of conv3D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${i}'`));const[r,o]=t;return{x:()=>la(r.shape,e,o,a,s),filter:()=>fu(r,e,o.shape,a,s)}}},vu={kernelName:"Cos",inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>xi(ci(Fs(ei(n,"float32"))),e)}}},yu={kernelName:ge,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>xi(_s(ei(n,"float32")),e)}}},bu={kernelName:ve,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[i]=t,{axis:a,exclusive:s,reverse:r}=n;return{x:()=>{const t=Sa([a],i.rank);let n=da(e,a,s,!r);return null!=t&&(n=hi(n,t)),n}}}},wu={kernelName:ye,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{const{dilations:i,strides:a,pad:s,dimRoundingMode:r}=n,o=null==i?[1,1]:i;I(ji(o),(()=>`Error in gradient of depthwiseConv2dNative: dilation rates greater than 1 are not yet supported. Got dilations '${o}'`));const[l,c]=t;return I(4===l.rank,(()=>`Error in gradient of depthwiseConv2dNative: input must be rank 4, but got rank ${l.rank}.`)),I(4===c.rank,(()=>`Error in gradient of depthwiseConv2dNative: filter must be rank 4, but got rank ${c.rank}.`)),I(l.shape[3]===c.shape[2],(()=>`Error in gradient of depthwiseConv2d: number of input channels (${l.shape[3]}) must match the inChannels dimension in filter ${c.shape[2]}.`)),I(zi(a,o),(()=>`Error in gradient of depthwiseConv2d: Either strides or dilations must be 1. Got strides ${a} and dilations '${o}'.`)),Fi("depthwiseConv2d",s,r),{x:()=>ar(l.shape,e,c,a,s,o,r),filter:()=>ir(l,e,c.shape,a,s,o,r)}}},ku={kernelName:"Dilation2D",inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{const[i,a]=t,s={x:i,filter:a,dy:e},r={x:i,filter:a,dy:e};return{x:()=>sn.runKernel("Dilation2DBackpropInput",s,n),filter:()=>sn.runKernel("Dilation2DBackpropFilter",r,n)}}},xu={kernelName:we,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t,i={dy:e,y:n};return{x:()=>sn.runKernel("EluGrad",i)}}},Su={kernelName:"Erf",inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t,i=xi(Fa(ci($a(n))),2/Math.sqrt(Math.PI));return{x:()=>xi(e,i)}}},Nu={kernelName:"Exp",outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t;return{x:()=>xi(e,n)}}},Iu={kernelName:ke,inputsToSave:["input"],gradFunc:(e,t)=>{const[n]=t;return{input:()=>_i(e,n.shape)}}},Tu={kernelName:"Expm1",inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>xi(e,Fa(n))}}},Eu={kernelName:xe,gradFunc:e=>({x:()=>ya(e)})},Au={kernelName:Se,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,i]=t,a=mi(n.shape,i.shape);return{a:()=>{const t=ki(e,ei(i,"float32")),s=di(n.shape,a);return s.length>0?_i(ja(t,s),n.shape):t},b:()=>{let t=xi(e,ei(n,"float32"));const s=di(i.shape,a);s.length>0&&(t=_i(ja(t,s),i.shape));const r=$a(i);return ci(ki(t,ei(r,"float32")))}}}},Cu={kernelName:Ne,inputsToSave:["x","mean","variance","scale"],gradFunc:(e,t,n)=>{const{varianceEpsilon:i}=n,[a,s,r,o]=t,l=null==o?Aa(1):o,c=di(s.shape,a.shape),u=[];if(1===s.rank){for(let e=0;e<a.shape.length-1;++e)u.push(a.shape[e]);u.push(1)}const h=Ja(a,s),p=xi(e,l),d=js(bi(r,Aa(i))),m=xi(xi(xi(d,d),d),Aa(-.5));return{x:()=>1===s.rank?_i(xi(xi(e,Ra(_i(d,[1,1,1,s.shape[0]]),u)),l),a.shape):_i(xi(xi(e,d),l),a.shape),mean:()=>{let e=xi(xi(d,Aa(-1)),p);return 1===s.rank&&(e=ja(e,c)),_i(e,s.shape)},variance:()=>{let e=xi(xi(m,h),p);return 1===s.rank&&(e=ja(e,c)),_i(e,s.shape)},scale:()=>{const t=xi(h,d);let n=xi(e,t);return 1===s.rank&&(n=ja(n,c)),_i(n,s.shape)},offset:()=>{let t=e;return 1===s.rank&&(t=ja(t,c)),_i(t,s.shape)}}}},$u={kernelName:Ie,inputsToSave:["x","indices"],gradFunc:(e,t,n)=>{const[i,a]=t,{axis:s}=n,r=z(s,i.shape)[0];return{x:()=>{const t=i.shape,n=a.size,o=t.slice(0,r),l=o.length,c=t.slice(s,t.length).slice(1),u=c.length,h=ju(0,l),p=ju(l+1,l+1+u),d=zu([o,[n],c]),m=_i(e,d),f=_i(a,[n]),g=zu([[l],h,p]),v=hi(m,g);let y=Hs(v,f,i.shape[r]);const b=Na(g);return y=hi(y,b),y},indices:()=>a}}};
4005
+ function(e,t,n,i,a){let s=e;4===e.rank&&(s=_i(e,[1,e.shape[0],e.shape[1],e.shape[2],e.shape[3]]));let r=t;4===r.rank&&(r=_i(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]])),T(5===s.rank,(()=>`Error in conv3dDerFilter: input must be rank 5, but got shape ${s.shape}.`)),T(5===r.rank,(()=>`Error in conv3dDerFilter: dy must be rank 5, but got shape ${r.shape}.`)),T(5===n.length,(()=>`Error in conv3dDerFilter: filterShape must be length 5, but got ${n}.`)),T(s.shape[4]===n[3],(()=>`Error in conv3dDerFilter: depth of input ${s.shape[4]}) must match input depth in filter (${n[3]}.`)),T(r.shape[4]===n[4],(()=>`Error in conv3dDerFilter: depth of dy (${r.shape[4]}) must match output depth for filter (${n[4]}).`));const o={x:s,dy:r},l={strides:i,pad:a,filterShape:n};return sn.runKernel("Conv3DBackpropFilterV2",o,l)}}),gu={kernelName:fe,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{const{dilations:i,strides:a,pad:s}=n;T(ji(i),(()=>`Error in gradient of conv3D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${i}'`));const[r,o]=t;return{x:()=>la(r.shape,e,o,a,s),filter:()=>fu(r,e,o.shape,a,s)}}},vu={kernelName:"Cos",inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>xi(ci(Fs(ei(n,"float32"))),e)}}},yu={kernelName:ge,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>xi(_s(ei(n,"float32")),e)}}},bu={kernelName:ve,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[i]=t,{axis:a,exclusive:s,reverse:r}=n;return{x:()=>{const t=Sa([a],i.rank);let n=da(e,a,s,!r);return null!=t&&(n=hi(n,t)),n}}}},wu={kernelName:ye,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{const{dilations:i,strides:a,pad:s,dimRoundingMode:r}=n,o=null==i?[1,1]:i;T(ji(o),(()=>`Error in gradient of depthwiseConv2dNative: dilation rates greater than 1 are not yet supported. Got dilations '${o}'`));const[l,c]=t;return T(4===l.rank,(()=>`Error in gradient of depthwiseConv2dNative: input must be rank 4, but got rank ${l.rank}.`)),T(4===c.rank,(()=>`Error in gradient of depthwiseConv2dNative: filter must be rank 4, but got rank ${c.rank}.`)),T(l.shape[3]===c.shape[2],(()=>`Error in gradient of depthwiseConv2d: number of input channels (${l.shape[3]}) must match the inChannels dimension in filter ${c.shape[2]}.`)),T(zi(a,o),(()=>`Error in gradient of depthwiseConv2d: Either strides or dilations must be 1. Got strides ${a} and dilations '${o}'.`)),Fi("depthwiseConv2d",s,r),{x:()=>ar(l.shape,e,c,a,s,o,r),filter:()=>ir(l,e,c.shape,a,s,o,r)}}},ku={kernelName:"Dilation2D",inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{const[i,a]=t,s={x:i,filter:a,dy:e},r={x:i,filter:a,dy:e};return{x:()=>sn.runKernel("Dilation2DBackpropInput",s,n),filter:()=>sn.runKernel("Dilation2DBackpropFilter",r,n)}}},xu={kernelName:we,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t,i={dy:e,y:n};return{x:()=>sn.runKernel("EluGrad",i)}}},Su={kernelName:"Erf",inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t,i=xi(Fa(ci($a(n))),2/Math.sqrt(Math.PI));return{x:()=>xi(e,i)}}},Nu={kernelName:"Exp",outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t;return{x:()=>xi(e,n)}}},Tu={kernelName:ke,inputsToSave:["input"],gradFunc:(e,t)=>{const[n]=t;return{input:()=>_i(e,n.shape)}}},Iu={kernelName:"Expm1",inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>xi(e,Fa(n))}}},Au={kernelName:xe,gradFunc:e=>({x:()=>ya(e)})},Cu={kernelName:Se,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,i]=t,a=mi(n.shape,i.shape);return{a:()=>{const t=ki(e,ei(i,"float32")),s=di(n.shape,a);return s.length>0?_i(ja(t,s),n.shape):t},b:()=>{let t=xi(e,ei(n,"float32"));const s=di(i.shape,a);s.length>0&&(t=_i(ja(t,s),i.shape));const r=$a(i);return ci(ki(t,ei(r,"float32")))}}}},Eu={kernelName:Ne,inputsToSave:["x","mean","variance","scale"],gradFunc:(e,t,n)=>{const{varianceEpsilon:i}=n,[a,s,r,o]=t,l=null==o?Ca(1):o,c=di(s.shape,a.shape),u=[];if(1===s.rank){for(let e=0;e<a.shape.length-1;++e)u.push(a.shape[e]);u.push(1)}const h=Ja(a,s),p=xi(e,l),d=js(bi(r,Ca(i))),m=xi(xi(xi(d,d),d),Ca(-.5));return{x:()=>1===s.rank?_i(xi(xi(e,Ra(_i(d,[1,1,1,s.shape[0]]),u)),l),a.shape):_i(xi(xi(e,d),l),a.shape),mean:()=>{let e=xi(xi(d,Ca(-1)),p);return 1===s.rank&&(e=ja(e,c)),_i(e,s.shape)},variance:()=>{let e=xi(xi(m,h),p);return 1===s.rank&&(e=ja(e,c)),_i(e,s.shape)},scale:()=>{const t=xi(h,d);let n=xi(e,t);return 1===s.rank&&(n=ja(n,c)),_i(n,s.shape)},offset:()=>{let t=e;return 1===s.rank&&(t=ja(t,c)),_i(t,s.shape)}}}},$u={kernelName:Te,inputsToSave:["x","indices"],gradFunc:(e,t,n)=>{const[i,a]=t,{axis:s}=n,r=z(s,i.shape)[0];return{x:()=>{const t=i.shape,n=a.size,o=t.slice(0,r),l=o.length,c=t.slice(s,t.length).slice(1),u=c.length,h=ju(0,l),p=ju(l+1,l+1+u),d=zu([o,[n],c]),m=_i(e,d),f=_i(a,[n]),g=zu([[l],h,p]),v=hi(m,g);let y=Hs(v,f,i.shape[r]);const b=Na(g);return y=hi(y,b),y},indices:()=>a}}};
4006
4006
  /**
4007
4007
  * @license
4008
4008
  * Copyright 2020 Google LLC. All Rights Reserved.
@@ -4034,7 +4034,7 @@ function(e,t,n,i,a){let s=e;4===e.rank&&(s=_i(e,[1,e.shape[0],e.shape[1],e.shape
4034
4034
  * See the License for the specific language governing permissions and
4035
4035
  * limitations under the License.
4036
4036
  * =============================================================================
4037
- */const Du={kernelName:Te,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,i]=t;return{a:()=>ya(n),b:()=>ya(i)}}},Fu={kernelName:Ee,gradFunc:e=>({x:()=>ei(e,"float32")})},_u={kernelName:"IsFinite",gradFunc:e=>({x:()=>ya(e)})},Ru={kernelName:"IsInf",gradFunc:e=>({x:()=>ya(e)})},Lu={kernelName:"IsNan",gradFunc:e=>({x:()=>ya(e)})},Mu={kernelName:Ae,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[i]=t,{alpha:a}=n,s=Pa(i,0);return{x:()=>va(s,e,xi(e,a))}}},Ou={kernelName:Ce,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>ki(e,bi(n,1))}}},Pu={kernelName:"Log",inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>ki(e,ei(n,"float32"))}}},Bu={kernelName:"LogSoftmax",inputsToSave:[],outputsToSave:[!0],gradFunc:(e,t,n)=>{const[i]=t,{axis:a}=n;return{logits:()=>{const t=Fa(i);return Ja(e,xi(ja(e,a,!0),t))}}}};
4037
+ */const Du={kernelName:Ie,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,i]=t;return{a:()=>ya(n),b:()=>ya(i)}}},Fu={kernelName:Ae,gradFunc:e=>({x:()=>ei(e,"float32")})},_u={kernelName:"IsFinite",gradFunc:e=>({x:()=>ya(e)})},Ru={kernelName:"IsInf",gradFunc:e=>({x:()=>ya(e)})},Lu={kernelName:"IsNan",gradFunc:e=>({x:()=>ya(e)})},Mu={kernelName:Ce,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[i]=t,{alpha:a}=n,s=Pa(i,0);return{x:()=>va(s,e,xi(e,a))}}},Ou={kernelName:Ee,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>ki(e,bi(n,1))}}},Pu={kernelName:"Log",inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>ki(e,ei(n,"float32"))}}},Bu={kernelName:"LogSoftmax",inputsToSave:[],outputsToSave:[!0],gradFunc:(e,t,n)=>{const[i]=t,{axis:a}=n;return{logits:()=>{const t=Fa(i);return Ja(e,xi(ja(e,a,!0),t))}}}};
4038
4038
  /**
4039
4039
  * @license
4040
4040
  * Copyright 2020 Google LLC. All Rights Reserved.
@@ -4100,7 +4100,7 @@ function(e,t,n,i=5,a=1,s=1,r=.5){const o={x:e,y:t,dy:n},l={depthRadius:i,bias:a,
4100
4100
  * limitations under the License.
4101
4101
  * =============================================================================
4102
4102
  */
4103
- function Gu(e,t,n,i){return t.rank<n.rank&&(t=_i(t,xa(t.shape,i))),e.rank<n.rank&&(e=_i(e,xa(e.shape,i))),{x:()=>xi(e,ei(ga(n,t),e.dtype))}}
4103
+ function Vu(e,t,n,i){return t.rank<n.rank&&(t=_i(t,xa(t.shape,i))),e.rank<n.rank&&(e=_i(e,xa(e.shape,i))),{x:()=>xi(e,ei(ga(n,t),e.dtype))}}
4104
4104
  /**
4105
4105
  * @license
4106
4106
  * Copyright 2020 Google LLC. All Rights Reserved.
@@ -4116,7 +4116,7 @@ function Gu(e,t,n,i){return t.rank<n.rank&&(t=_i(t,xa(t.shape,i))),e.rank<n.rank
4116
4116
  * See the License for the specific language governing permissions and
4117
4117
  * limitations under the License.
4118
4118
  * =============================================================================
4119
- */const Vu={kernelName:"Max",inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const i=n,{reductionIndices:a}=i,s=t[0],r=Gu(e,t[1],s,z(a,s.shape));return{x:()=>r.x()}}},Ku={kernelName:$e,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,i]=t;return{a:()=>xi(e,ei(Ba(n,i),"float32")),b:()=>xi(e,ei(Wa(n,i),"float32"))}}};
4119
+ */const Gu={kernelName:"Max",inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const i=n,{reductionIndices:a}=i,s=t[0],r=Vu(e,t[1],s,z(a,s.shape));return{x:()=>r.x()}}},Ku={kernelName:$e,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,i]=t;return{a:()=>xi(e,ei(Ba(n,i),"float32")),b:()=>xi(e,ei(Wa(n,i),"float32"))}}};
4120
4120
  /**
4121
4121
  * @license
4122
4122
  * Copyright 2020 Google LLC. All Rights Reserved.
@@ -4149,7 +4149,7 @@ function Gu(e,t,n,i){return t.rank<n.rank&&(t=_i(t,xa(t.shape,i))),e.rank<n.rank
4149
4149
  * limitations under the License.
4150
4150
  * =============================================================================
4151
4151
  */
4152
- function(e,t,n,i,a,s,r){const o=hn(e,"dy","maxPool3dGrad"),l=hn(t,"input","maxPool3dGrad"),c=hn(n,"output","maxPool3dGrad");let u=o,h=l,p=c,d=!1;4===l.rank&&(d=!0,u=_i(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]]),h=_i(l,[1,l.shape[0],l.shape[1],l.shape[2],l.shape[3]]),p=_i(c,[1,c.shape[0],c.shape[1],c.shape[2],c.shape[3]])),I(5===u.rank,(()=>`Error in maxPool3dGrad: dy must be rank 5 but got rank ${u.rank}.`)),I(5===h.rank,(()=>`Error in maxPool3dGrad: input must be rank 5 but got rank ${h.rank}.`)),I(5===p.rank,(()=>`Error in maxPool3dGrad: output must be rank 5 but got rank ${p.rank}.`)),Fi("maxPool3dGrad",s,r);const m={dy:u,input:h,output:p},f={filterSize:i,strides:a,pad:s,dimRoundingMode:r},g=sn.runKernel("MaxPool3DGrad",m,f);return d?_i(g,[g.shape[1],g.shape[2],g.shape[3],g.shape[4]]):g}}),Hu={kernelName:ze,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const[i,a]=t,{filterSize:s,strides:r,pad:o,dimRoundingMode:l}=n;return{x:()=>qu(e,i,a,s,r,o,l)}}};
4152
+ function(e,t,n,i,a,s,r){const o=hn(e,"dy","maxPool3dGrad"),l=hn(t,"input","maxPool3dGrad"),c=hn(n,"output","maxPool3dGrad");let u=o,h=l,p=c,d=!1;4===l.rank&&(d=!0,u=_i(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]]),h=_i(l,[1,l.shape[0],l.shape[1],l.shape[2],l.shape[3]]),p=_i(c,[1,c.shape[0],c.shape[1],c.shape[2],c.shape[3]])),T(5===u.rank,(()=>`Error in maxPool3dGrad: dy must be rank 5 but got rank ${u.rank}.`)),T(5===h.rank,(()=>`Error in maxPool3dGrad: input must be rank 5 but got rank ${h.rank}.`)),T(5===p.rank,(()=>`Error in maxPool3dGrad: output must be rank 5 but got rank ${p.rank}.`)),Fi("maxPool3dGrad",s,r);const m={dy:u,input:h,output:p},f={filterSize:i,strides:a,pad:s,dimRoundingMode:r},g=sn.runKernel("MaxPool3DGrad",m,f);return d?_i(g,[g.shape[1],g.shape[2],g.shape[3],g.shape[4]]):g}}),Hu={kernelName:ze,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const[i,a]=t,{filterSize:s,strides:r,pad:o,dimRoundingMode:l}=n;return{x:()=>qu(e,i,a,s,r,o,l)}}};
4153
4153
  /**
4154
4154
  * @license
4155
4155
  * Copyright 2020 Google LLC. All Rights Reserved.
@@ -4182,7 +4182,7 @@ function(e,t,n,i,a,s,r){const o=hn(e,"dy","maxPool3dGrad"),l=hn(t,"input","maxPo
4182
4182
  * limitations under the License.
4183
4183
  * =============================================================================
4184
4184
  */
4185
- function(e,t,n,i,a,s,r){const o=hn(e,"dy","maxPoolGrad"),l=hn(t,"input","maxPoolGrad"),c=hn(n,"output","maxPoolGrad");I(l.rank===o.rank,(()=>`Rank of input (${l.rank}) does not match rank of dy (${o.rank})`)),I(4===o.rank,(()=>`Error in maxPoolGrad: dy must be rank 4 but got rank ${o.rank}.`)),I(4===l.rank,(()=>`Error in maxPoolGrad: input must be rank 4 but got rank ${l.rank}.`)),Fi("maxPoolGrad",s,r);const u={dy:o,input:l,output:c},h={filterSize:i,strides:a,pad:s,dimRoundingMode:r};return sn.runKernel("MaxPoolGrad",u,h)}}),Zu={kernelName:je,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const[i,a]=t,{filterSize:s,strides:r,pad:o}=n;return{x:()=>Ju(e,i,a,s,r,o)}}},Yu={kernelName:Oe,inputsToSave:["x"],gradFunc:(e,t,n)=>{const i=t[0],{paddings:a}=n,s=a.map((e=>e[0]));return{x:()=>Bi(e,s,i.shape)}}},Qu={kernelName:"Pow",inputsToSave:["a","b"],outputsToSave:[!0],gradFunc:(e,t)=>{const[n,i,a]=t,s=n,r=i,o=mi(s.shape,r.shape);return{a:()=>{const t=ei(r,"float32");let n=xi(e,xi(t,Ea(s,Ja(t,Aa(1)))));const i=di(s.shape,o);return i.length>0&&(n=ja(n,i)),_i(n,s.shape)},b:()=>{const t=Pa(s,0),n=va(t,Va(s),ya(s));let i=xi(e,xi(a,n));const l=di(r.shape,o);return l.length>0&&(i=ja(i,l)),_i(i,r.shape)}}}};
4185
+ function(e,t,n,i,a,s,r){const o=hn(e,"dy","maxPoolGrad"),l=hn(t,"input","maxPoolGrad"),c=hn(n,"output","maxPoolGrad");T(l.rank===o.rank,(()=>`Rank of input (${l.rank}) does not match rank of dy (${o.rank})`)),T(4===o.rank,(()=>`Error in maxPoolGrad: dy must be rank 4 but got rank ${o.rank}.`)),T(4===l.rank,(()=>`Error in maxPoolGrad: input must be rank 4 but got rank ${l.rank}.`)),Fi("maxPoolGrad",s,r);const u={dy:o,input:l,output:c},h={filterSize:i,strides:a,pad:s,dimRoundingMode:r};return sn.runKernel("MaxPoolGrad",u,h)}}),Zu={kernelName:je,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const[i,a]=t,{filterSize:s,strides:r,pad:o}=n;return{x:()=>Ju(e,i,a,s,r,o)}}},Yu={kernelName:Oe,inputsToSave:["x"],gradFunc:(e,t,n)=>{const i=t[0],{paddings:a}=n,s=a.map((e=>e[0]));return{x:()=>Bi(e,s,i.shape)}}},Qu={kernelName:"Pow",inputsToSave:["a","b"],outputsToSave:[!0],gradFunc:(e,t)=>{const[n,i,a]=t,s=n,r=i,o=mi(s.shape,r.shape);return{a:()=>{const t=ei(r,"float32");let n=xi(e,xi(t,Aa(s,Ja(t,Ca(1)))));const i=di(s.shape,o);return i.length>0&&(n=ja(n,i)),_i(n,s.shape)},b:()=>{const t=Pa(s,0),n=va(t,Ga(s),ya(s));let i=xi(e,xi(a,n));const l=di(r.shape,o);return l.length>0&&(i=ja(i,l)),_i(i,r.shape)}}}};
4186
4186
  /**
4187
4187
  * @license
4188
4188
  * Copyright 2020 Google LLC. All Rights Reserved.
@@ -4248,7 +4248,7 @@ function(e,t,n){const i=e.shape.slice();i[n]=1;const a=_i(t,i),s=pa(e,n,!0,!1),r
4248
4248
  * limitations under the License.
4249
4249
  * =============================================================================
4250
4250
  */
4251
- const nh=[Wc,Gc,Vc,Kc,qc,Hc,Jc,Zc,Yc,Qc,Xc,eu,nu,au,su,ru,ou,lu,cu,uu,hu,pu,mu,du,gu,vu,yu,bu,wu,ku,{kernelName:be,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,i]=t,a=mi(n.shape,i.shape);return{a:()=>{const t=ki(e,ei(i,"float32")),s=di(n.shape,a);return s.length>0?_i(ja(t,s),n.shape):t},b:()=>{let t=xi(e,ei(n,"float32"));const s=di(i.shape,a);s.length>0&&(t=_i(ja(t,s),i.shape));const r=$a(i);return ci(ki(t,ei(r,"float32")))}}}},xu,Su,Nu,Iu,Tu,Au,Eu,Cu,$u,Du,Fu,_u,Ru,Lu,Mu,Ou,Pu,Bu,Wu,Vu,Vu,Ku,Hu,Zu,{kernelName:De,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[i]=t,{axis:a}=n,s=z(a,i.shape),r=A(ka(i.shape,s)[1]);return{x:()=>{const t=i.shape.slice();s.forEach((e=>{t[e]=1}));const n=_i(e,t);return ki(xi(n,as(i.shape,"float32")),r)}}}},{kernelName:"Min",inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const i=n,{axis:a}=i,[s,r]=t,o=Gu(e,r,s,z(a,s.shape));return{x:()=>o.x()}}},{kernelName:Fe,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,i]=t;return{a:()=>xi(e,ei(Ga(n,i),"float32")),b:()=>xi(e,ei(Pa(n,i),"float32"))}}},{kernelName:"MirrorPad",inputsToSave:["x"],gradFunc:(e,t,n)=>{const i=t[0],{paddings:a}=n,s=a.map((e=>e[0]));return{x:()=>Bi(e,s,i.shape)}}},{kernelName:"Mod",inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,i]=t,a=mi(n.shape,i.shape);return{a:()=>{const t=di(n.shape,a);return t.length>0?_i(ja(e,t),n.shape):e},b:()=>{const t=xi(e,ci(Ma(ki(n,i)))),s=di(i.shape,a);return s.length>0?_i(ja(t,s),i.shape):t}}}},{kernelName:_e,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,i]=t,a=mi(n.shape,i.shape);return{a:()=>{const t=xi(e,ei(i,"float32")),s=di(n.shape,a);return s.length>0?_i(ja(t,s),n.shape):t},b:()=>{const t=xi(e,ei(n,"float32")),s=di(i.shape,a);return s.length>0?_i(ja(t,s),i.shape):t}}}},{kernelName:"Neg",gradFunc:e=>({x:()=>ci(e)})},{kernelName:Le,inputsToSave:["indices"],gradFunc:(e,t)=>{const n=t[0];return{indices:()=>is(n.shape,"float32")}}},{kernelName:Re,gradFunc:e=>({x:()=>ya(e)})},{kernelName:Me,saveAllInputs:!0,gradFunc:(e,t,n)=>{const{axis:i}=n;return Js(e,i).map((e=>()=>e))}},Yu,Yu,Qu,{kernelName:Pe,inputsToSave:["x","alpha"],gradFunc:(e,t)=>{const[n,i]=t,a=Pa(n,0);return{x:()=>va(a,e,xi(e,i)),alpha:()=>{let t=va(a,ya(e),xi(e,n));const s=di(i.shape,e.shape);return s.length>0&&(t=ja(t,s)),_i(t,i.shape)}}}},{kernelName:"Prod",inputsToSave:["x"],gradFunc:(e,t,n)=>{const[i]=t,{axis:a}=n;let s=[];return s=null==a?i.shape.map(((e,t)=>t)):"number"==typeof a?[a]:a,{x:()=>Xu(i,e,s)}}},{kernelName:"Reciprocal",inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>ki(e,ci($a(n)))}}},{kernelName:Ve,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t,i=xi(Ga(n,6),Gs(n));return{x:()=>xi(e,ei(i,"float32"))}}},{kernelName:Be,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>xi(e,ei(Gs(n),"float32"))}}},{kernelName:Ue,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>_i(e,n.shape)}}},{kernelName:Ge,inputsToSave:["images"],gradFunc:(e,t,n)=>{const[i]=t,a={dy:e,images:i};return{images:()=>sn.runKernel("ResizeBilinearGrad",a,n)}}},{kernelName:We,inputsToSave:["images"],gradFunc:(e,t,n)=>{const[i]=t,a={dy:e,images:i};return{images:()=>sn.runKernel("ResizeNearestNeighborGrad",a,n)}}},{kernelName:Ke,gradFunc:(e,t,n)=>{const{dims:i}=n,a=z(i,e.shape);return{x:()=>Cs(e,a)}}},{kernelName:qe,gradFunc:e=>({x:()=>ya(e)})},{kernelName:He,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>ci(ki(e,xi(Ea(n,1.5),2)))}}},{kernelName:Je,inputsToSave:["condition"],gradFunc:(e,t)=>{const[n]=t;return{condition:()=>ei(ya(n),"float32"),t:()=>xi(e,ei(n,e.dtype)),e:()=>xi(e,ei(Qa(n),e.dtype))}}},{kernelName:Ze,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const t=Pa(n,Aa(0)),i=Aa(1.7580993408473768),a=Aa(1.0507009873554805),s=xi(e,a),r=xi(xi(e,i),Fa(ei(n,"float32")));return va(t,s,r)}}}},{kernelName:Xe,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t;return{x:()=>xi(e,xi(n,Ja(Aa(1),n)))}}},{kernelName:"Sign",gradFunc:e=>({x:()=>ya(e)})},{kernelName:"Sin",inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>xi(ua(ei(n,"float32")),e)}}},{kernelName:Qe,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>xi(ha(ei(n,"float32")),e)}}},{kernelName:Ye,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[i]=t,{begin:a,size:s}=n,r=i.shape,[o,l]=fi(i,a,s),c=[];for(let t=0;t<e.rank;t++)c.push([o[t],r[t]-o[t]-l[t]]);return{x:()=>cs(e,c)}}},{kernelName:st,outputsToSave:[!0],gradFunc:(e,t,n)=>{const[i]=t,{dim:a}=n,s=xi(e,i);return{logits:()=>Ja(s,xi(ja(s,[a],true),i))}}},{kernelName:et,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>xi(e,Pi(n))}}},eh,eh,th,th,{kernelName:tt,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>ki(e,xi(Ca(ei(n,"float32")),2))}}},{kernelName:rt,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,i]=t,a=Aa(2);return{a:()=>xi(e,xi(a,Ja(n,i))),b:()=>xi(e,xi(a,Ja(i,n)))}}},{kernelName:"Square",inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>xi(e,xi(ei(n,"float32"),2))}}},{kernelName:dt,gradFunc:e=>({x:()=>ya(e)})},{kernelName:"Sub",inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,i]=t,a=mi(n.shape,i.shape);return{a:()=>{let t=e;const i=di(n.shape,a);return i.length>0&&(t=ja(t,i)),_i(t,n.shape)},b:()=>{let t=e;const n=di(i.shape,a);return n.length>0&&(t=ja(t,n)),_i(ci(t),i.shape)}}}},{kernelName:nt,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[i]=t,a=i.shape.slice(),{axis:s}=n;z(s,i.shape).forEach((e=>{a[e]=1}));const r=_i(e,a),o=xi(r,as(i.shape,"float32"));return{x:()=>o}}},{kernelName:"Tan",inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>ki(e,$a(ua(n)))}}},{kernelName:ot,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t;return{x:()=>xi(Ja(Aa(1),$a(n)),e)}}},{kernelName:lt,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[i]=t,{reps:a}=n;return{x:()=>{let t=ya(i);if(1===i.rank)for(let n=0;n<a[0];++n)t=bi(t,Bi(e,[n*i.shape[0]],[i.shape[0]]));else if(2===i.rank)for(let n=0;n<a[0];++n)for(let s=0;s<a[1];++s)t=bi(t,Bi(e,[n*i.shape[0],s*i.shape[1]],[i.shape[0],i.shape[1]]));else if(3===i.rank)for(let n=0;n<a[0];++n)for(let s=0;s<a[1];++s)for(let r=0;r<a[2];++r)t=bi(t,Bi(e,[n*i.shape[0],s*i.shape[1],r*i.shape[2]],[i.shape[0],i.shape[1],i.shape[2]]));else{if(4!==i.rank)throw new Error(`Gradient for tile operation is not implemented for rank-${i.rank} tensors yet.`);for(let n=0;n<a[0];++n)for(let s=0;s<a[1];++s)for(let r=0;r<a[2];++r)for(let o=0;o<a[3];++o)t=bi(t,Bi(e,[n*i.shape[0],s*i.shape[1],r*i.shape[2],o*i.shape[3]],[i.shape[0],i.shape[1],i.shape[2],i.shape[3]]))}return t}}}},{kernelName:ct,gradFunc:(e,t,n)=>{const i=n,{perm:a}=i,s=Na(a);return{x:()=>hi(e,s)}}},{kernelName:ut,gradFunc:(e,t,n)=>{const i=n,{axis:a}=i;return{value:()=>Ws(e,a)}}},{kernelName:ht,inputsToSave:["segmentIds"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>function(e,t){const n=ts(t,ya(t)),i=Oa(e,n);let a=Ba(t,Aa(0,"int32"));const s=i.rank-a.rank;for(let e=0;e<s;++e)a=_a(a,e+1);a=Ya(a,as(i.shape,"bool"));const r=ya(i);return va(a,i,r)}(e,n)}}},{kernelName:pt,gradFunc:e=>({x:()=>ya(e)})}];
4251
+ const nh=[Wc,Vc,Gc,Kc,qc,Hc,Jc,Zc,Yc,Qc,Xc,eu,nu,au,su,ru,ou,lu,cu,uu,hu,pu,mu,du,gu,vu,yu,bu,wu,ku,{kernelName:be,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,i]=t,a=mi(n.shape,i.shape);return{a:()=>{const t=ki(e,ei(i,"float32")),s=di(n.shape,a);return s.length>0?_i(ja(t,s),n.shape):t},b:()=>{let t=xi(e,ei(n,"float32"));const s=di(i.shape,a);s.length>0&&(t=_i(ja(t,s),i.shape));const r=$a(i);return ci(ki(t,ei(r,"float32")))}}}},xu,Su,Nu,Tu,Iu,Cu,Au,Eu,$u,Du,Fu,_u,Ru,Lu,Mu,Ou,Pu,Bu,Wu,Gu,Gu,Ku,Hu,Zu,{kernelName:De,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[i]=t,{axis:a}=n,s=z(a,i.shape),r=C(ka(i.shape,s)[1]);return{x:()=>{const t=i.shape.slice();s.forEach((e=>{t[e]=1}));const n=_i(e,t);return ki(xi(n,as(i.shape,"float32")),r)}}}},{kernelName:"Min",inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const i=n,{axis:a}=i,[s,r]=t,o=Vu(e,r,s,z(a,s.shape));return{x:()=>o.x()}}},{kernelName:Fe,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,i]=t;return{a:()=>xi(e,ei(Va(n,i),"float32")),b:()=>xi(e,ei(Pa(n,i),"float32"))}}},{kernelName:"MirrorPad",inputsToSave:["x"],gradFunc:(e,t,n)=>{const i=t[0],{paddings:a}=n,s=a.map((e=>e[0]));return{x:()=>Bi(e,s,i.shape)}}},{kernelName:"Mod",inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,i]=t,a=mi(n.shape,i.shape);return{a:()=>{const t=di(n.shape,a);return t.length>0?_i(ja(e,t),n.shape):e},b:()=>{const t=xi(e,ci(Ma(ki(n,i)))),s=di(i.shape,a);return s.length>0?_i(ja(t,s),i.shape):t}}}},{kernelName:_e,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,i]=t,a=mi(n.shape,i.shape);return{a:()=>{const t=xi(e,ei(i,"float32")),s=di(n.shape,a);return s.length>0?_i(ja(t,s),n.shape):t},b:()=>{const t=xi(e,ei(n,"float32")),s=di(i.shape,a);return s.length>0?_i(ja(t,s),i.shape):t}}}},{kernelName:"Neg",gradFunc:e=>({x:()=>ci(e)})},{kernelName:Le,inputsToSave:["indices"],gradFunc:(e,t)=>{const n=t[0];return{indices:()=>is(n.shape,"float32")}}},{kernelName:Re,gradFunc:e=>({x:()=>ya(e)})},{kernelName:Me,saveAllInputs:!0,gradFunc:(e,t,n)=>{const{axis:i}=n;return Js(e,i).map((e=>()=>e))}},Yu,Yu,Qu,{kernelName:Pe,inputsToSave:["x","alpha"],gradFunc:(e,t)=>{const[n,i]=t,a=Pa(n,0);return{x:()=>va(a,e,xi(e,i)),alpha:()=>{let t=va(a,ya(e),xi(e,n));const s=di(i.shape,e.shape);return s.length>0&&(t=ja(t,s)),_i(t,i.shape)}}}},{kernelName:"Prod",inputsToSave:["x"],gradFunc:(e,t,n)=>{const[i]=t,{axis:a}=n;let s=[];return s=null==a?i.shape.map(((e,t)=>t)):"number"==typeof a?[a]:a,{x:()=>Xu(i,e,s)}}},{kernelName:"Reciprocal",inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>ki(e,ci($a(n)))}}},{kernelName:Ge,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t,i=xi(Va(n,6),Vs(n));return{x:()=>xi(e,ei(i,"float32"))}}},{kernelName:Be,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>xi(e,ei(Vs(n),"float32"))}}},{kernelName:Ue,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>_i(e,n.shape)}}},{kernelName:Ve,inputsToSave:["images"],gradFunc:(e,t,n)=>{const[i]=t,a={dy:e,images:i};return{images:()=>sn.runKernel("ResizeBilinearGrad",a,n)}}},{kernelName:We,inputsToSave:["images"],gradFunc:(e,t,n)=>{const[i]=t,a={dy:e,images:i};return{images:()=>sn.runKernel("ResizeNearestNeighborGrad",a,n)}}},{kernelName:Ke,gradFunc:(e,t,n)=>{const{dims:i}=n,a=z(i,e.shape);return{x:()=>Es(e,a)}}},{kernelName:qe,gradFunc:e=>({x:()=>ya(e)})},{kernelName:He,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>ci(ki(e,xi(Aa(n,1.5),2)))}}},{kernelName:Je,inputsToSave:["condition"],gradFunc:(e,t)=>{const[n]=t;return{condition:()=>ei(ya(n),"float32"),t:()=>xi(e,ei(n,e.dtype)),e:()=>xi(e,ei(Qa(n),e.dtype))}}},{kernelName:Ze,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const t=Pa(n,Ca(0)),i=Ca(1.7580993408473768),a=Ca(1.0507009873554805),s=xi(e,a),r=xi(xi(e,i),Fa(ei(n,"float32")));return va(t,s,r)}}}},{kernelName:Xe,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t;return{x:()=>xi(e,xi(n,Ja(Ca(1),n)))}}},{kernelName:"Sign",gradFunc:e=>({x:()=>ya(e)})},{kernelName:"Sin",inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>xi(ua(ei(n,"float32")),e)}}},{kernelName:Qe,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>xi(ha(ei(n,"float32")),e)}}},{kernelName:Ye,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[i]=t,{begin:a,size:s}=n,r=i.shape,[o,l]=fi(i,a,s),c=[];for(let t=0;t<e.rank;t++)c.push([o[t],r[t]-o[t]-l[t]]);return{x:()=>cs(e,c)}}},{kernelName:st,outputsToSave:[!0],gradFunc:(e,t,n)=>{const[i]=t,{dim:a}=n,s=xi(e,i);return{logits:()=>Ja(s,xi(ja(s,[a],true),i))}}},{kernelName:et,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>xi(e,Pi(n))}}},eh,eh,th,th,{kernelName:tt,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>ki(e,xi(Ea(ei(n,"float32")),2))}}},{kernelName:rt,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,i]=t,a=Ca(2);return{a:()=>xi(e,xi(a,Ja(n,i))),b:()=>xi(e,xi(a,Ja(i,n)))}}},{kernelName:"Square",inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>xi(e,xi(ei(n,"float32"),2))}}},{kernelName:dt,gradFunc:e=>({x:()=>ya(e)})},{kernelName:"Sub",inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,i]=t,a=mi(n.shape,i.shape);return{a:()=>{let t=e;const i=di(n.shape,a);return i.length>0&&(t=ja(t,i)),_i(t,n.shape)},b:()=>{let t=e;const n=di(i.shape,a);return n.length>0&&(t=ja(t,n)),_i(ci(t),i.shape)}}}},{kernelName:nt,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[i]=t,a=i.shape.slice(),{axis:s}=n;z(s,i.shape).forEach((e=>{a[e]=1}));const r=_i(e,a),o=xi(r,as(i.shape,"float32"));return{x:()=>o}}},{kernelName:"Tan",inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>ki(e,$a(ua(n)))}}},{kernelName:ot,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t;return{x:()=>xi(Ja(Ca(1),$a(n)),e)}}},{kernelName:lt,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[i]=t,{reps:a}=n;return{x:()=>{let t=ya(i);if(1===i.rank)for(let n=0;n<a[0];++n)t=bi(t,Bi(e,[n*i.shape[0]],[i.shape[0]]));else if(2===i.rank)for(let n=0;n<a[0];++n)for(let s=0;s<a[1];++s)t=bi(t,Bi(e,[n*i.shape[0],s*i.shape[1]],[i.shape[0],i.shape[1]]));else if(3===i.rank)for(let n=0;n<a[0];++n)for(let s=0;s<a[1];++s)for(let r=0;r<a[2];++r)t=bi(t,Bi(e,[n*i.shape[0],s*i.shape[1],r*i.shape[2]],[i.shape[0],i.shape[1],i.shape[2]]));else{if(4!==i.rank)throw new Error(`Gradient for tile operation is not implemented for rank-${i.rank} tensors yet.`);for(let n=0;n<a[0];++n)for(let s=0;s<a[1];++s)for(let r=0;r<a[2];++r)for(let o=0;o<a[3];++o)t=bi(t,Bi(e,[n*i.shape[0],s*i.shape[1],r*i.shape[2],o*i.shape[3]],[i.shape[0],i.shape[1],i.shape[2],i.shape[3]]))}return t}}}},{kernelName:ct,gradFunc:(e,t,n)=>{const i=n,{perm:a}=i,s=Na(a);return{x:()=>hi(e,s)}}},{kernelName:ut,gradFunc:(e,t,n)=>{const i=n,{axis:a}=i;return{value:()=>Ws(e,a)}}},{kernelName:ht,inputsToSave:["segmentIds"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>function(e,t){const n=ts(t,ya(t)),i=Oa(e,n);let a=Ba(t,Ca(0,"int32"));const s=i.rank-a.rank;for(let e=0;e<s;++e)a=_a(a,e+1);a=Ya(a,as(i.shape,"bool"));const r=ya(i);return va(a,i,r)}(e,n)}}},{kernelName:pt,gradFunc:e=>({x:()=>ya(e)})}];
4252
4252
  /**
4253
4253
  * @license
4254
4254
  * Copyright 2020 Google LLC. All Rights Reserved.
@@ -4273,7 +4273,7 @@ const nh=[Wc,Gc,Vc,Kc,qc,Hc,Jc,Zc,Yc,Qc,Xc,eu,nu,au,su,ru,ou,lu,cu,uu,hu,pu,mu,d
4273
4273
  * license that can be found in the LICENSE file or at
4274
4274
  * https://opensource.org/licenses/MIT.
4275
4275
  * =============================================================================
4276
- */function ih(e,t){return si((()=>Ca(ja(xi(e,e),t,!0))))}class ah extends gi{getConfig(){return{}}}class sh extends ah{constructor(e){super(),this.defaultMaxValue=2,this.defaultAxis=0,this.maxValue=null!=e.maxValue?e.maxValue:this.defaultMaxValue,this.axis=null!=e.axis?e.axis:this.defaultAxis}apply(e){return si((()=>{const t=ih(e,this.axis),n=Qi(t,0,this.maxValue);return xi(e,ki(n,bi(Fl(),t)))}))}getConfig(){return{maxValue:this.maxValue,axis:this.axis}}}sh.className="MaxNorm",yi(sh);class rh extends ah{constructor(e){super(),this.defaultAxis=0,this.axis=null!=e.axis?e.axis:this.defaultAxis}apply(e){return si((()=>ki(e,bi(Fl(),ih(e,this.axis)))))}getConfig(){return{axis:this.axis}}}rh.className="UnitNorm",yi(rh);class oh extends ah{apply(e){return Es(e)}}oh.className="NonNeg",yi(oh);class lh extends ah{constructor(e){super(),this.defaultMinValue=0,this.defaultMaxValue=1,this.defaultRate=1,this.defaultAxis=0,this.minValue=null!=e.minValue?e.minValue:this.defaultMinValue,this.maxValue=null!=e.maxValue?e.maxValue:this.defaultMaxValue,this.rate=null!=e.rate?e.rate:this.defaultRate,this.axis=null!=e.axis?e.axis:this.defaultAxis}apply(e){return si((()=>{const t=ih(e,this.axis),n=bi(xi(this.rate,Qi(t,this.minValue,this.maxValue)),xi(1-this.rate,t));return xi(e,ki(n,bi(Fl(),t)))}))}getConfig(){return{minValue:this.minValue,maxValue:this.maxValue,rate:this.rate,axis:this.axis}}}lh.className="MinMaxNorm",yi(lh);const ch={maxNorm:"MaxNorm",minMaxNorm:"MinMaxNorm",nonNeg:"NonNeg",unitNorm:"UnitNorm"};function uh(e){return Xo(e)}function hh(e,t={}){return tl(e,vi.getMap().classNameMap,t,"constraint")}function ph(e){if(null==e)return null;if("string"==typeof e){return hh({className:e in ch?ch[e]:e,config:{}})}return e instanceof ah?e:hh(e)}
4276
+ */function ih(e,t){return si((()=>Ea(ja(xi(e,e),t,!0))))}class ah extends gi{getConfig(){return{}}}class sh extends ah{constructor(e){super(),this.defaultMaxValue=2,this.defaultAxis=0,this.maxValue=null!=e.maxValue?e.maxValue:this.defaultMaxValue,this.axis=null!=e.axis?e.axis:this.defaultAxis}apply(e){return si((()=>{const t=ih(e,this.axis),n=Qi(t,0,this.maxValue);return xi(e,ki(n,bi(Fl(),t)))}))}getConfig(){return{maxValue:this.maxValue,axis:this.axis}}}sh.className="MaxNorm",yi(sh);class rh extends ah{constructor(e){super(),this.defaultAxis=0,this.axis=null!=e.axis?e.axis:this.defaultAxis}apply(e){return si((()=>ki(e,bi(Fl(),ih(e,this.axis)))))}getConfig(){return{axis:this.axis}}}rh.className="UnitNorm",yi(rh);class oh extends ah{apply(e){return As(e)}}oh.className="NonNeg",yi(oh);class lh extends ah{constructor(e){super(),this.defaultMinValue=0,this.defaultMaxValue=1,this.defaultRate=1,this.defaultAxis=0,this.minValue=null!=e.minValue?e.minValue:this.defaultMinValue,this.maxValue=null!=e.maxValue?e.maxValue:this.defaultMaxValue,this.rate=null!=e.rate?e.rate:this.defaultRate,this.axis=null!=e.axis?e.axis:this.defaultAxis}apply(e){return si((()=>{const t=ih(e,this.axis),n=bi(xi(this.rate,Qi(t,this.minValue,this.maxValue)),xi(1-this.rate,t));return xi(e,ki(n,bi(Fl(),t)))}))}getConfig(){return{minValue:this.minValue,maxValue:this.maxValue,rate:this.rate,axis:this.axis}}}lh.className="MinMaxNorm",yi(lh);const ch={maxNorm:"MaxNorm",minMaxNorm:"MinMaxNorm",nonNeg:"NonNeg",unitNorm:"UnitNorm"};function uh(e){return Xo(e)}function hh(e,t={}){return tl(e,vi.getMap().classNameMap,t,"constraint")}function ph(e){if(null==e)return null;if("string"==typeof e){return hh({className:e in ch?ch[e]:e,config:{}})}return e instanceof ah?e:hh(e)}
4277
4277
  /**
4278
4278
  * @license
4279
4279
  * Copyright 2018 Google LLC
@@ -4291,7 +4291,7 @@ const nh=[Wc,Gc,Vc,Kc,qc,Hc,Jc,Zc,Yc,Qc,Xc,eu,nu,au,su,ru,ou,lu,cu,uu,hu,pu,mu,d
4291
4291
  * license that can be found in the LICENSE file or at
4292
4292
  * https://opensource.org/licenses/MIT.
4293
4293
  * =============================================================================
4294
- */var fh;!function(e){e[e.SILENT=0]="SILENT",e[e.VERBOSE=1]="VERBOSE"}(fh||(fh={}));class gh{constructor(){this.validationData=null}setParams(e){this.params=e}async onEpochBegin(e,t){}async onEpochEnd(e,t){}async onBatchBegin(e,t){}async onBatchEnd(e,t){}async onTrainBegin(e){}async onTrainEnd(e){}setModel(e){}}class vh{constructor(e,t=10){null==e&&(e=[]),this.callbacks=e,this.queueLength=t}append(e){this.callbacks.push(e)}setParams(e){for(const t of this.callbacks)t.setParams(e)}setModel(e){for(const t of this.callbacks)t.setModel(e)}async onEpochBegin(e,t){null==t&&(t={});for(const n of this.callbacks)await n.onEpochBegin(e,t)}async onEpochEnd(e,t){null==t&&(t={});for(const n of this.callbacks)await n.onEpochEnd(e,t)}async onBatchBegin(e,t){null==t&&(t={});for(const n of this.callbacks)await n.onBatchBegin(e,t)}async onBatchEnd(e,t){null==t&&(t={});for(const n of this.callbacks)await n.onBatchEnd(e,t)}async onTrainBegin(e){null==e&&(e={});for(const t of this.callbacks)await t.onTrainBegin(e)}async onTrainEnd(e){null==e&&(e={});for(const t of this.callbacks)await t.onTrainEnd(e)}}class yh extends gh{constructor(){super()}async onEpochBegin(e){this.seen=0,this.totals={}}async onBatchEnd(e,t){null==t&&(t={});const n=null==t.size?0:t.size;this.seen+=n;for(const e in t){const i=t[e];if("number"==typeof i)this.totals.hasOwnProperty(e)||(this.totals[e]=0),this.totals[e]=this.totals[e]+i*n;else{let t;e in this.totals?t=this.totals[e]:this.totals[e]=0;const a=si((()=>bi(this.totals[e],xi(i,n))));this.totals[e]=a,null!=t&&t.dispose()}}}async onEpochEnd(e,t){if(null!=t)for(const e of this.params.metrics)null!=this.totals[e]&&("number"==typeof this.totals[e]?t[e]=this.totals[e]/this.seen:si((()=>{const n=xi(ki(1,this.seen),this.totals[e]);t[e]=n,this.totals[e].dispose(),oi(t[e])})))}}class bh extends gh{async onTrainBegin(e){this.epoch=[],this.history={}}async onEpochEnd(e,t){null==t&&(t={}),this.epoch.push(e);for(const e in t)null==this.history[e]&&(this.history[e]=[]),this.history[e].push(t[e])}async syncData(){const e=[],t=[],n=[];for(const i in this.history){const a=this.history[i];for(let s=0;s<a.length;++s)if("number"!=typeof a[s]){const r=a[s];e.push(r.data()),t.push(i),n.push(s)}}const i=await Promise.all(e);for(let e=0;e<i.length;++e){this.history[t[e]][n[e]].dispose(),this.history[t[e]][n[e]]=i[e][0]}}}class wh extends gh{constructor(e,t){if(super(),this.currentEpoch=0,this.nowFunc=e.nowFunc,this.nextFrameFunc=e.nextFrameFunc||Gr,this.yieldEvery=t||"auto","auto"===this.yieldEvery&&(this.yieldEvery=125),"never"===this.yieldEvery&&null!=e.onYield)throw new Error("yieldEvery is `never` but you provided an `onYield` callback. Either change `yieldEvery` or remove the callback");L(this.yieldEvery)&&(this.maybeWait=function(e,t,n){let i,a=null!=n?n():Tt();return(...s)=>{const r=null!=n?n():Tt();return r-a<t||(a=r,i=e(...s)),i}}(this.maybeWait.bind(this),this.yieldEvery,this.nowFunc)),this.trainBegin=e.onTrainBegin,this.trainEnd=e.onTrainEnd,this.epochBegin=e.onEpochBegin,this.epochEnd=e.onEpochEnd,this.batchBegin=e.onBatchBegin,this.batchEnd=e.onBatchEnd,this.yield=e.onYield}async maybeWait(e,t,n){const i=[];null!=this.yield&&(await dh(n),i.push(this.yield(e,t,n))),i.push(this.nextFrameFunc()),await Promise.all(i)}async onEpochBegin(e,t){this.currentEpoch=e,null!=this.epochBegin&&(await dh(t),await this.epochBegin(e,t))}async onEpochEnd(e,t){const n=[];null!=this.epochEnd&&(await dh(t),n.push(this.epochEnd(e,t))),"epoch"===this.yieldEvery&&n.push(this.nextFrameFunc()),await Promise.all(n)}async onBatchBegin(e,t){null!=this.batchBegin&&(await dh(t),await this.batchBegin(e,t))}async onBatchEnd(e,t){const n=[];null!=this.batchEnd&&(await dh(t),n.push(this.batchEnd(e,t))),"batch"===this.yieldEvery?n.push(this.nextFrameFunc()):L(this.yieldEvery)&&n.push(this.maybeWait(this.currentEpoch,e,t)),await Promise.all(n)}async onTrainBegin(e){null!=this.trainBegin&&(await dh(e),await this.trainBegin(e))}async onTrainEnd(e){null!=this.trainEnd&&(await dh(e),await this.trainEnd(e))}}function kh(e,t){if(null==e&&(e={}),e instanceof gh)return[e];if(Array.isArray(e)&&e[0]instanceof gh)return e;return Jo(e).map((e=>new wh(e,t)))}class xh{constructor(){}static registerCallbackConstructor(e,t){I(e>=0&&Number.isInteger(e),(()=>`Verbosity level is expected to be an integer >= 0, but got ${e}`)),xh.checkForDuplicate(t),null==xh.constructors[e]&&(xh.constructors[e]=[]),xh.constructors[e].push(t)}static checkForDuplicate(e){for(const t in xh.constructors){xh.constructors[+t].forEach((t=>{if(t===e)throw new Bo("Duplicate callback constructor.")}))}}static clear(){xh.constructors={}}static createCallbacks(e){const t=[];for(const n in xh.constructors){const i=+n;e>=i&&t.push(...xh.constructors[i])}return t.map((e=>new e))}}function Sh(e,t,n,i,a,s,r,o,l){const c=new bh,u=[new yh,...xh.createCallbacks(t)];null!=e&&u.push(...e),u.push(c);const h=new vh(u);return h.setParams({epochs:n,initialEpoch:i,samples:a,steps:s,batchSize:r,verbose:t,doValidation:o,metrics:l}),{callbackList:h,history:c}}
4294
+ */var fh;!function(e){e[e.SILENT=0]="SILENT",e[e.VERBOSE=1]="VERBOSE"}(fh||(fh={}));class gh{constructor(){this.validationData=null}setParams(e){this.params=e}async onEpochBegin(e,t){}async onEpochEnd(e,t){}async onBatchBegin(e,t){}async onBatchEnd(e,t){}async onTrainBegin(e){}async onTrainEnd(e){}setModel(e){}}class vh{constructor(e,t=10){null==e&&(e=[]),this.callbacks=e,this.queueLength=t}append(e){this.callbacks.push(e)}setParams(e){for(const t of this.callbacks)t.setParams(e)}setModel(e){for(const t of this.callbacks)t.setModel(e)}async onEpochBegin(e,t){null==t&&(t={});for(const n of this.callbacks)await n.onEpochBegin(e,t)}async onEpochEnd(e,t){null==t&&(t={});for(const n of this.callbacks)await n.onEpochEnd(e,t)}async onBatchBegin(e,t){null==t&&(t={});for(const n of this.callbacks)await n.onBatchBegin(e,t)}async onBatchEnd(e,t){null==t&&(t={});for(const n of this.callbacks)await n.onBatchEnd(e,t)}async onTrainBegin(e){null==e&&(e={});for(const t of this.callbacks)await t.onTrainBegin(e)}async onTrainEnd(e){null==e&&(e={});for(const t of this.callbacks)await t.onTrainEnd(e)}}class yh extends gh{constructor(){super()}async onEpochBegin(e){this.seen=0,this.totals={}}async onBatchEnd(e,t){null==t&&(t={});const n=null==t.size?0:t.size;this.seen+=n;for(const e in t){const i=t[e];if("number"==typeof i)this.totals.hasOwnProperty(e)||(this.totals[e]=0),this.totals[e]=this.totals[e]+i*n;else{let t;e in this.totals?t=this.totals[e]:this.totals[e]=0;const a=si((()=>bi(this.totals[e],xi(i,n))));this.totals[e]=a,null!=t&&t.dispose()}}}async onEpochEnd(e,t){if(null!=t)for(const e of this.params.metrics)null!=this.totals[e]&&("number"==typeof this.totals[e]?t[e]=this.totals[e]/this.seen:si((()=>{const n=xi(ki(1,this.seen),this.totals[e]);t[e]=n,this.totals[e].dispose(),oi(t[e])})))}}class bh extends gh{async onTrainBegin(e){this.epoch=[],this.history={}}async onEpochEnd(e,t){null==t&&(t={}),this.epoch.push(e);for(const e in t)null==this.history[e]&&(this.history[e]=[]),this.history[e].push(t[e])}async syncData(){const e=[],t=[],n=[];for(const i in this.history){const a=this.history[i];for(let s=0;s<a.length;++s)if("number"!=typeof a[s]){const r=a[s];e.push(r.data()),t.push(i),n.push(s)}}const i=await Promise.all(e);for(let e=0;e<i.length;++e){this.history[t[e]][n[e]].dispose(),this.history[t[e]][n[e]]=i[e][0]}}}class wh extends gh{constructor(e,t){if(super(),this.currentEpoch=0,this.nowFunc=e.nowFunc,this.nextFrameFunc=e.nextFrameFunc||Vr,this.yieldEvery=t||"auto","auto"===this.yieldEvery&&(this.yieldEvery=125),"never"===this.yieldEvery&&null!=e.onYield)throw new Error("yieldEvery is `never` but you provided an `onYield` callback. Either change `yieldEvery` or remove the callback");L(this.yieldEvery)&&(this.maybeWait=function(e,t,n){let i,a=null!=n?n():It();return(...s)=>{const r=null!=n?n():It();return r-a<t||(a=r,i=e(...s)),i}}(this.maybeWait.bind(this),this.yieldEvery,this.nowFunc)),this.trainBegin=e.onTrainBegin,this.trainEnd=e.onTrainEnd,this.epochBegin=e.onEpochBegin,this.epochEnd=e.onEpochEnd,this.batchBegin=e.onBatchBegin,this.batchEnd=e.onBatchEnd,this.yield=e.onYield}async maybeWait(e,t,n){const i=[];null!=this.yield&&(await dh(n),i.push(this.yield(e,t,n))),i.push(this.nextFrameFunc()),await Promise.all(i)}async onEpochBegin(e,t){this.currentEpoch=e,null!=this.epochBegin&&(await dh(t),await this.epochBegin(e,t))}async onEpochEnd(e,t){const n=[];null!=this.epochEnd&&(await dh(t),n.push(this.epochEnd(e,t))),"epoch"===this.yieldEvery&&n.push(this.nextFrameFunc()),await Promise.all(n)}async onBatchBegin(e,t){null!=this.batchBegin&&(await dh(t),await this.batchBegin(e,t))}async onBatchEnd(e,t){const n=[];null!=this.batchEnd&&(await dh(t),n.push(this.batchEnd(e,t))),"batch"===this.yieldEvery?n.push(this.nextFrameFunc()):L(this.yieldEvery)&&n.push(this.maybeWait(this.currentEpoch,e,t)),await Promise.all(n)}async onTrainBegin(e){null!=this.trainBegin&&(await dh(e),await this.trainBegin(e))}async onTrainEnd(e){null!=this.trainEnd&&(await dh(e),await this.trainEnd(e))}}function kh(e,t){if(null==e&&(e={}),e instanceof gh)return[e];if(Array.isArray(e)&&e[0]instanceof gh)return e;return Jo(e).map((e=>new wh(e,t)))}class xh{constructor(){}static registerCallbackConstructor(e,t){T(e>=0&&Number.isInteger(e),(()=>`Verbosity level is expected to be an integer >= 0, but got ${e}`)),xh.checkForDuplicate(t),null==xh.constructors[e]&&(xh.constructors[e]=[]),xh.constructors[e].push(t)}static checkForDuplicate(e){for(const t in xh.constructors){xh.constructors[+t].forEach((t=>{if(t===e)throw new Bo("Duplicate callback constructor.")}))}}static clear(){xh.constructors={}}static createCallbacks(e){const t=[];for(const n in xh.constructors){const i=+n;e>=i&&t.push(...xh.constructors[i])}return t.map((e=>new e))}}function Sh(e,t,n,i,a,s,r,o,l){const c=new bh,u=[new yh,...xh.createCallbacks(t)];null!=e&&u.push(...e),u.push(c);const h=new vh(u);return h.setParams({epochs:n,initialEpoch:i,samples:a,steps:s,batchSize:r,verbose:t,doValidation:o,metrics:l}),{callbackList:h,history:c}}
4295
4295
  /**
4296
4296
  * @license
4297
4297
  * Copyright 2018 Google LLC
@@ -4309,7 +4309,7 @@ const nh=[Wc,Gc,Vc,Kc,qc,Hc,Jc,Zc,Yc,Qc,Xc,eu,nu,au,su,ru,ou,lu,cu,uu,hu,pu,mu,d
4309
4309
  * license that can be found in the LICENSE file or at
4310
4310
  * https://opensource.org/licenses/MIT.
4311
4311
  * =============================================================================
4312
- */function Ih(e,t){return si((()=>{"float32"!==e.dtype&&(e=ei(e,"float32"));const n=ja(Kl(e),t,!0),i=Yi(n.shape,Fl()),a=Ca(ts(n,i));return ki(e,a)}))}function Th(e,t){return si((()=>ns(Kl(Ja(t,e)),-1)))}function Eh(e,t){return si((()=>ns(Si(Ja(t,e)),-1)))}function Ah(e,t){return si((()=>{const n=Ja(e,t),i=Qi(Si(e),Fl(),Number.MAX_VALUE),a=Si(ki(n,i));return xi(100,ns(a,-1))}))}function Ch(e,t,n=!1){return si((()=>{if(n)t=Ps(t);else{const e=ja(t,t.shape.length-1,!0);t=ki(t,e)}return t=Qi(t,Fl(),1-Fl()),ci(ja(xi(ei(e,"float32"),Va(t)),t.shape.length-1))}))}function $h(e,t,n=!1){return si((()=>{const i=ei(Ma(function(e){const t=[Cl(e.shape)];return _i(e,t)}(e)),"int32"),a=(t=Qi(t,Fl(),1-Fl())).shape;return Ch(_i(ni(i,a[a.length-1]),a),t,n)}))}function jh(e,t){return si((()=>{let n;return n=Qi(t,Fl(),1-Fl()),n=Va(ki(n,Ja(1,n))),ns(function(e,t){if(!C(e.shape,t.shape))throw new Bo(`logits and labels must have the same shape, but got shapes ${JSON.stringify(e.shape)} and ${JSON.stringify(t.shape)}`);return si((()=>{const n=Es(t),i=ci(Si(t));return bi(Ja(n,xi(t,e)),Ka(Fa(i)))}))}(e,n),-1)}))}function zh(e,t){return si((()=>{const n=Ih(e,-1),i=Ih(t,-1),a=xi(n,i);return ci(ja(a,-1))}))}xh.constructors={};const Dh={meanSquaredError:Th,meanAbsoluteError:Eh,meanAbsolutePercentageError:Ah,meanSquaredLogarithmicError:function(e,t){return si((()=>{const n=Qi(t,Fl(),Number.MAX_VALUE),i=Va(bi(1,n)),a=Qi(e,Fl(),Number.MAX_VALUE),s=Va(bi(1,a));return ns(Kl(Ja(i,s)),-1)}))},squaredHinge:function(e,t){return si((()=>{const n=ts(0,Ja(1,xi(e,t)));return ns(Kl(n),-1)}))},hinge:function(e,t){return si((()=>{const n=ts(0,Ja(1,xi(e,t)));return ns(n,-1)}))},categoricalHinge:function(e,t){return si((()=>{const n=ja(xi(e,t),-1),i=Ia(xi(Ja(1,e),t),-1);return ts(0,bi(1,Ja(i,n)))}))},logcosh:function(e,t){return si((()=>{const n=Math.log(2),i=Ja(t,e),a=Ja(bi(i,Ha(xi(-2,i))),n);return ns(a,-1)}))},categoricalCrossentropy:Ch,sparseCategoricalCrossentropy:$h,binaryCrossentropy:jh,kullbackLeiblerDivergence:function(e,t){return si((()=>{const n=Qi(e,Fl(),1),i=Qi(t,Fl(),1);return ja(xi(e,Va(ki(n,i))),-1)}))},poisson:function(e,t){return si((()=>{const n=Va(bi(Fl(),t));return ns(Ja(t,xi(e,n)),-1)}))},cosineProximity:zh};function Fh(e){if("string"==typeof e){if(e in Dh)return Dh[e];let t=`Unknown loss ${e}`;throw e.toLowerCase().includes("softmaxcrossentropy")&&(t=`Unknown loss ${e}. Use "categoricalCrossentropy" as the string name for tf.losses.softmaxCrossEntropy`),new Bo(t)}return e}
4312
+ */function Th(e,t){return si((()=>{"float32"!==e.dtype&&(e=ei(e,"float32"));const n=ja(Kl(e),t,!0),i=Yi(n.shape,Fl()),a=Ea(ts(n,i));return ki(e,a)}))}function Ih(e,t){return si((()=>ns(Kl(Ja(t,e)),-1)))}function Ah(e,t){return si((()=>ns(Si(Ja(t,e)),-1)))}function Ch(e,t){return si((()=>{const n=Ja(e,t),i=Qi(Si(e),Fl(),Number.MAX_VALUE),a=Si(ki(n,i));return xi(100,ns(a,-1))}))}function Eh(e,t,n=!1){return si((()=>{if(n)t=Ps(t);else{const e=ja(t,t.shape.length-1,!0);t=ki(t,e)}return t=Qi(t,Fl(),1-Fl()),ci(ja(xi(ei(e,"float32"),Ga(t)),t.shape.length-1))}))}function $h(e,t,n=!1){return si((()=>{const i=ei(Ma(function(e){const t=[El(e.shape)];return _i(e,t)}(e)),"int32"),a=(t=Qi(t,Fl(),1-Fl())).shape;return Eh(_i(ni(i,a[a.length-1]),a),t,n)}))}function jh(e,t){return si((()=>{let n;return n=Qi(t,Fl(),1-Fl()),n=Ga(ki(n,Ja(1,n))),ns(function(e,t){if(!E(e.shape,t.shape))throw new Bo(`logits and labels must have the same shape, but got shapes ${JSON.stringify(e.shape)} and ${JSON.stringify(t.shape)}`);return si((()=>{const n=As(t),i=ci(Si(t));return bi(Ja(n,xi(t,e)),Ka(Fa(i)))}))}(e,n),-1)}))}function zh(e,t){return si((()=>{const n=Th(e,-1),i=Th(t,-1),a=xi(n,i);return ci(ja(a,-1))}))}xh.constructors={};const Dh={meanSquaredError:Ih,meanAbsoluteError:Ah,meanAbsolutePercentageError:Ch,meanSquaredLogarithmicError:function(e,t){return si((()=>{const n=Qi(t,Fl(),Number.MAX_VALUE),i=Ga(bi(1,n)),a=Qi(e,Fl(),Number.MAX_VALUE),s=Ga(bi(1,a));return ns(Kl(Ja(i,s)),-1)}))},squaredHinge:function(e,t){return si((()=>{const n=ts(0,Ja(1,xi(e,t)));return ns(Kl(n),-1)}))},hinge:function(e,t){return si((()=>{const n=ts(0,Ja(1,xi(e,t)));return ns(n,-1)}))},categoricalHinge:function(e,t){return si((()=>{const n=ja(xi(e,t),-1),i=Ta(xi(Ja(1,e),t),-1);return ts(0,bi(1,Ja(i,n)))}))},logcosh:function(e,t){return si((()=>{const n=Math.log(2),i=Ja(t,e),a=Ja(bi(i,Ha(xi(-2,i))),n);return ns(a,-1)}))},categoricalCrossentropy:Eh,sparseCategoricalCrossentropy:$h,binaryCrossentropy:jh,kullbackLeiblerDivergence:function(e,t){return si((()=>{const n=Qi(e,Fl(),1),i=Qi(t,Fl(),1);return ja(xi(e,Ga(ki(n,i))),-1)}))},poisson:function(e,t){return si((()=>{const n=Ga(bi(Fl(),t));return ns(Ja(t,xi(e,n)),-1)}))},cosineProximity:zh};function Fh(e){if("string"==typeof e){if(e in Dh)return Dh[e];let t=`Unknown loss ${e}`;throw e.toLowerCase().includes("softmaxcrossentropy")&&(t=`Unknown loss ${e}. Use "categoricalCrossentropy" as the string name for tf.losses.softmaxCrossEntropy`),new Bo(t)}return e}
4313
4313
  /**
4314
4314
  * @license
4315
4315
  * Copyright 2018 Google LLC
@@ -4318,7 +4318,7 @@ const nh=[Wc,Gc,Vc,Kc,qc,Hc,Jc,Zc,Yc,Qc,Xc,eu,nu,au,su,ru,ou,lu,cu,uu,hu,pu,mu,d
4318
4318
  * license that can be found in the LICENSE file or at
4319
4319
  * https://opensource.org/licenses/MIT.
4320
4320
  * =============================================================================
4321
- */function _h(e,t){return si((()=>{const n=xi(.5,ls(t)),i=_l(Pa(t,n),e.dtype);return ns(ga(e,i),-1)}))}function Rh(e,t){return si((()=>_l(ga(Ti(e,-1),Ti(t,-1)),"float32")))}function Lh(e,t){return jh(e,t)}function Mh(e,t){return e.rank===t.rank&&(e=Us(e,[e.rank-1])),(t=Ti(t,-1)).dtype!==e.dtype&&(t=ei(t,e.dtype)),ei(ga(e,t),"float32")}const Oh=Ch,Ph=$h,Bh={binaryAccuracy:_h,categoricalAccuracy:Rh,precision:function(e,t){return si((()=>{const n=function(e,t){return si((()=>ei(ja(Ya(ga(e,1),ga(t,1))),"float32")))}(e,t),i=function(e,t){return si((()=>ei(ja(Ya(ga(e,0),ga(t,1))),"float32")))}(e,t),a=bi(n,i);return ei(va(Pa(a,0),ki(n,a),0),"float32")}))},categoricalCrossentropy:Oh,sparseCategoricalCrossentropy:Ph,mse:Th,MSE:Th,mae:Eh,MAE:Eh,mape:Ah,MAPE:Ah,cosine:zh};function Uh(e){if("string"==typeof e&&e in Bh)return Bh[e];if("string"!=typeof e&&null!=e)return e;throw new Bo(`Unknown metric ${e}`)}function Wh(e){if(Ko(null!==e,`Unknown LossOrMetricFn ${e}`),"string"==typeof e)return e;{let t;for(const n of Object.keys(Dh))if(Dh[n]===e){t=n;break}if(void 0!==t)return t;for(const n of Object.keys(Bh))if(Bh[n]===e){t=n;break}return void 0!==t?t:e.name}}
4321
+ */function _h(e,t){return si((()=>{const n=xi(.5,ls(t)),i=_l(Pa(t,n),e.dtype);return ns(ga(e,i),-1)}))}function Rh(e,t){return si((()=>_l(ga(Ii(e,-1),Ii(t,-1)),"float32")))}function Lh(e,t){return jh(e,t)}function Mh(e,t){return e.rank===t.rank&&(e=Us(e,[e.rank-1])),(t=Ii(t,-1)).dtype!==e.dtype&&(t=ei(t,e.dtype)),ei(ga(e,t),"float32")}const Oh=Eh,Ph=$h,Bh={binaryAccuracy:_h,categoricalAccuracy:Rh,precision:function(e,t){return si((()=>{const n=function(e,t){return si((()=>ei(ja(Ya(ga(e,1),ga(t,1))),"float32")))}(e,t),i=function(e,t){return si((()=>ei(ja(Ya(ga(e,0),ga(t,1))),"float32")))}(e,t),a=bi(n,i);return ei(va(Pa(a,0),ki(n,a),0),"float32")}))},categoricalCrossentropy:Oh,sparseCategoricalCrossentropy:Ph,mse:Ih,MSE:Ih,mae:Ah,MAE:Ah,mape:Ch,MAPE:Ch,cosine:zh};function Uh(e){if("string"==typeof e&&e in Bh)return Bh[e];if("string"!=typeof e&&null!=e)return e;throw new Bo(`Unknown metric ${e}`)}function Wh(e){if(Ko(null!==e,`Unknown LossOrMetricFn ${e}`),"string"==typeof e)return e;{let t;for(const n of Object.keys(Dh))if(Dh[n]===e){t=n;break}if(void 0!==t)return t;for(const n of Object.keys(Bh))if(Bh[n]===e){t=n;break}return void 0!==t?t:e.name}}
4322
4322
  /**
4323
4323
  * @license
4324
4324
  * Copyright 2018 Google LLC
@@ -4337,7 +4337,7 @@ const nh=[Wc,Gc,Vc,Kc,qc,Hc,Jc,Zc,Yc,Qc,Xc,eu,nu,au,su,ru,ou,lu,cu,uu,hu,pu,mu,d
4337
4337
  * https://opensource.org/licenses/MIT.
4338
4338
  * =============================================================================
4339
4339
  */
4340
- const Gh=1048576;function Vh(e,t,n=!1){if(null==e||"object"!=typeof e||Object.getPrototypeOf(e)!==Object.prototype||!Kh(e))throw new Error("User-defined metadata is expected to be a JSON object, but is not.");if(n){const n=JSON.stringify(e);n.length>Gh&&console.warn(`User-defined metadata of model "${t}" is too large in size (length=${n.length} when serialized). It is not recommended to store such large objects in user-defined metadata. Please make sure its serialized length is <= 1048576.`)}}function Kh(e){if(null===e)return!0;if("object"==typeof e){if(Object.getPrototypeOf(e)===Object.prototype){const t=Object.keys(e);for(const n of t){if("string"!=typeof n)return!1;if(!Kh(e[n]))return!1}return!0}if(Array.isArray(e)){for(const t of e)if(!Kh(t))return!1;return!0}return!1}{const t=typeof e;return"string"===t||"number"===t||"boolean"===t}}
4340
+ const Vh=1048576;function Gh(e,t,n=!1){if(null==e||"object"!=typeof e||Object.getPrototypeOf(e)!==Object.prototype||!Kh(e))throw new Error("User-defined metadata is expected to be a JSON object, but is not.");if(n){const n=JSON.stringify(e);n.length>Vh&&console.warn(`User-defined metadata of model "${t}" is too large in size (length=${n.length} when serialized). It is not recommended to store such large objects in user-defined metadata. Please make sure its serialized length is <= 1048576.`)}}function Kh(e){if(null===e)return!0;if("object"==typeof e){if(Object.getPrototypeOf(e)===Object.prototype){const t=Object.keys(e);for(const n of t){if("string"!=typeof n)return!1;if(!Kh(e[n]))return!1}return!0}if(Array.isArray(e)){for(const t of e)if(!Kh(t))return!1;return!0}return!1}{const t=typeof e;return"string"===t||"number"===t||"boolean"===t}}
4341
4341
  /**
4342
4342
  * @license
4343
4343
  * Copyright 2018 Google LLC
@@ -4365,7 +4365,7 @@ const Gh=1048576;function Vh(e,t,n=!1){if(null==e||"object"!=typeof e||Object.ge
4365
4365
  * license that can be found in the LICENSE file or at
4366
4366
  * https://opensource.org/licenses/MIT.
4367
4367
  * =============================================================================
4368
- */class tp extends Dc{constructor(e){if(super({}),this.containerNodes=new Set,this.name=e.name,null==this.name){const e=this.getClassName().toLowerCase();this.name=dl(e)}if(this.supportsMasking=!1,this.trainable_=!0,Array.isArray(e.inputs)?this.inputs=e.inputs.slice():this.inputs=[e.inputs],Array.isArray(e.outputs)?this.outputs=e.outputs.slice():this.outputs=[e.outputs],il(this.inputs).length!==this.inputs.length)throw new Bo(`The list of inputs passed to the model is redundant. All inputs should only appear once. Found: ${this.inputs.map((e=>e.name))}`);il(this.outputs).length!==this.outputs.length&&console.warn(`The list of outputs passed to the model is redundant. All outputs should only appear once. Found: ${this.outputs.map((e=>e.name))}`),this.inputLayers=[],this.inputLayersNodeIndices=[],this.inputLayersTensorIndices=[],this.outputLayers=[],this.outputLayersNodeIndices=[],this.outputLayersTensorIndices=[],this.layers=[],this.internalContainerRefs=[];for(const e of this.outputs){const t=e.sourceLayer,n=e.nodeIndex,i=e.tensorIndex;this.outputLayers.push(t),this.outputLayersNodeIndices.push(n),this.outputLayersTensorIndices.push(i)}for(const e of this.inputs){const t=e.sourceLayer,n=e.nodeIndex,i=e.tensorIndex;Ko(0===n,"input layer has >1 nodes"),Ko(0===i,"input layer has >1 tensors"),this.inputLayers.push(t),this.inputLayersNodeIndices.push(n),this.inputLayersTensorIndices.push(i)}this.inputNames=[],this.outputNames=[],this.feedInputShapes=[],this.feedInputNames=[],this.feedOutputNames=[];for(let t=0;t<this.inputLayers.length;t++){const n=this.inputLayers[t];if(!(n instanceof _c))throw new TypeError(`Input layers to a LayersModel must be InputLayer objects. Received inputs: ${e.inputs}. Input ${t} (0-based) originates from layer type ${n.getClassName()}.`);this.inputNames.push(n.name),this.feedInputShapes.push(n.batchInputShape),this.feedInputNames.push(n.name)}for(const e of this.outputLayers)this.outputNames.push(e.name);this.internalInputShapes=this.inputs.map((e=>e.shape)),this.internalOutputShapes=this.outputs.map((e=>e.shape));const t={},n={},i={},a={},s={},r=[],o=(e,t,n,i,a,l)=>{null!=i&&null!=a&&null!=l||(i=e.sourceLayer,a=e.nodeIndex,l=e.tensorIndex);const c=i.inboundNodes[a];if(-1!==n.indexOf(c))throw new Po(`The tensor ${e.name} at layer "${i.name}" is part of a cycle.`);if(-1!==t.indexOf(c))return;this.containerNodes.add(tp.nodeKey(i,a)),i.id in s||(s[i.id]=Object.keys(s).length),-1===n.indexOf(c)&&n.push(c);const u=c.inboundLayers.length;for(let e=0;e<u;e++){const i=c.inputTensors[e],a=c.inboundLayers[e],s=c.nodeIndices[e],r=c.tensorIndices[e];o(i,t,n,a,s,r)}for(t.push(c);n.indexOf(c)>=0;)n.splice(n.indexOf(c),1);r.push(c)},l=[],c=[];for(const e of this.outputs)o(e,l,c);const u=r.slice().reverse();for(const e of u){n[e.id]=e,e.id in t||(t[e.id]=0);let s=t[e.id];const r=null==i[e.outboundLayer.id]?0:i[e.outboundLayer.id];s=Math.max(s,r),i[e.outboundLayer.id]=s,a[e.outboundLayer.id]=e.outboundLayer,t[e.id]=s;for(let i=0;i<e.inboundLayers.length;i++){const a=e.inboundLayers[i],r=e.nodeIndices[i],o=a.inboundNodes[r],l=null==t[o.id]?0:t[o.id];t[o.id]=Math.max(s+1,l),n[o.id]=o}}const h={};for(const e in t){const i=t[e];i in h||(h[i]=[]),h[i].push(n[e])}const p={};for(const e in i){const t=i[e];t in p||(p[t]=[]),p[t].push(a[e])}let d=Object.keys(p).map((e=>parseInt(e,10))).sort(nl);this.layers=[];for(const e of d){const t=p[e];t.sort(((e,t)=>{const n=s[e.id],i=s[t.id];return n<i?-1:n>i?1:0}));for(const e of t)e instanceof tp&&this.internalContainerRefs.push(e),this.layers.push(e)}this.layersByDepth=p,d=Object.keys(h).map((e=>parseInt(e,10))).sort(nl);const m=this.inputs.slice(),f=[];for(const e of d)for(const t of h[e]){const e=t.outboundLayer;if(null!=e){for(const n of t.inputTensors)if(-1===m.indexOf(n))throw new Po(`Graph disconnected: cannot obtain value for tensor ${n} at layer "${e.name}". The following previous layers were accessed without issue: ${f}`);for(const e of t.outputTensors)m.push(e);f.push(e.name)}}this.nodesByDepth=h;const g=this.layers.map((e=>e.name));for(const e of g){const t=g.filter((t=>t===e)).length;if(1!==t)throw new Po(`The name "${e}" is used ${t} times in the model. All layer names should be unique. Layer names: `+JSON.stringify(g))}this.outboundNodes=[],this.inboundNodes=[],new jc({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:this.inputs.map((e=>null)),outputMasks:this.outputs.map((e=>null)),inputShapes:this.inputs.map((e=>e.shape)),outputShapes:this.outputs.map((e=>e.shape))}),this.built=!0,this._refCount=1}assertNotDisposed(){if(0===this._refCount)throw new Error(`Container '${this.name}' is already disposed.`)}dispose(){this.assertNotDisposed();const e={refCountAfterDispose:null,numDisposedVariables:0};if(0==--this._refCount){for(const t of this.layers)e.numDisposedVariables+=t.dispose().numDisposedVariables;for(const t of this.internalContainerRefs)e.numDisposedVariables+=t.dispose().numDisposedVariables}return e.refCountAfterDispose=this._refCount,e}get trainable(){return this.trainable_}set trainable(e){this.layers.forEach((t=>{t._trainableWeights.forEach((t=>t.trainable=e))})),this.trainable_=e}get trainableWeights(){if(this._trainableWeights.length>0)throw new Bo("Container instance unexpectedly contains _trainableWeights.The trainable weights of a Container are a union of the trainable weights of its consituent Layers. Its own _trainableWeights must remain an empty Array.");if(!this.trainable)return[];let e=[];for(const t of this.layers)e=e.concat(t.trainableWeights);return e}get nonTrainableWeights(){const e=[];for(const t of this.layers)e.push(...t.nonTrainableWeights);if(!this.trainable){const t=[];for(const e of this.layers)t.push(...e.trainableWeights);return t.concat(e)}return e}get weights(){return this.trainableWeights.concat(this.nonTrainableWeights)}loadWeights(e,t=!0){const n={};let i=0;for(const e of this.layers)for(const t of e.weights){if(null!=n[t.originalName])throw new Bo(`Duplicate weight name: ${t.originalName}`);n[t.originalName]=t,i++}const a=[];for(const i in e){let s=i;if(null==n[i]){const e=i.split("/");s=e.slice(0,-2).concat([e[e.length-1]]).join("/")}if(null!=n[s])a.push([n[s],e[i]]);else if(t)throw new Bo(`Provided weight data has no target variable: ${i}`);delete n[s]}if(t){const e=[];for(const t in n)e.push(t);if(e.length>0)throw new Bo(`${e.length} of ${i} weights are not set: ${e}`)}Ec(a)}updatedConfig(){const e=this.getConfig(),t={};return t.className=this.getClassName(),t.config=e,t.kerasVersion=`tfjs-layers ${ep}`,t.backend="TensorFlow.js",t}toJSON(e,t=!0){const n=Xh(this.updatedConfig());return t?JSON.stringify(n):n}call(e,t){return si((()=>{e=Jo(e);const n=new Rc;for(let t=0;t<this.inputs.length;++t)n.add(this.inputs[t],e[t]);return Oc(this.outputs,n,t)}))}computeMask(e,t){return si((()=>{let n;return e=Jo(e),n=null==t?Vo(null,e.length):Jo(t),this.runInternalGraph(e,n)[1]}))}computeOutputShape(e){const t=wc(e);if(t.length!==this.inputLayers.length)throw new Bo(`Invalid inputShape argument ${e}: model has ${this.inputLayers.length} tensor inputs.`);const n={};for(let e=0;e<t.length;e++){const i=this.inputLayers[e],a=t[e];n[i.name+"_0_0"]=a}const i=Object.keys(this.nodesByDepth).map((e=>parseInt(e,10))).sort(nl);if(i.length>1)for(const e of i){const t=this.nodesByDepth[e];for(const e of t){const t=e.outboundLayer;if(-1!==this.inputLayers.map((e=>e.id)).indexOf(t.id))continue;const i=[];for(let t=0;t<e.inboundLayers.length;t++){const a=e.inboundLayers[t],s=e.nodeIndices[t],r=e.tensorIndices[t],o=n[`${a.name}_${s}_${r}`];i.push(o)}const a=wc(t.computeOutputShape(Ho(i))),s=t.inboundNodes.indexOf(e);for(let e=0;e<a.length;e++){n[`${t.name}_${s}_${e}`]=a[e]}}}const a=[],s=[];for(let e=0;e<this.outputLayers.length;e++){const t=this.outputLayers[e],n=this.outputLayersNodeIndices[e],i=this.outputLayersTensorIndices[e],a=`${t.name}_${n}_${i}`;s.push(a)}for(let e=0;e<s.length;e++){const t=s[e];Ko(t in n),a.push(n[t])}return Ho(a)}runInternalGraph(e,t){null==t&&(t=Vo(null,e.length));const n={};for(let i=0;i<this.inputs.length;++i){const a=this.inputs[i],s=e[i],r=t[i];n[a.id]=[s,r]}const i=Object.keys(this.nodesByDepth).map((e=>parseInt(e,10))).sort(nl);for(const e of i){const t=this.nodesByDepth[e];for(const e of t){const t=e.outboundLayer,i=e.inputTensors,a=e.outputTensors,s=new Array;for(const e of i)e.id in n&&s.push(n[e.id]);if(s.length===i.length){let i,r,o,l,c={};if(null!=e.callArgs&&(c=e.callArgs),1===s.length){const[e,n]=s[0];null==c.mask&&(c.mask=n),o=Jo(t.call(e,c)),l=Jo(t.computeMask(e,n)),i=[e],r=[n]}else i=s.map((e=>e[0])),r=s.map((e=>e[1])),null==c.mask&&(c.mask=r),o=Jo(t.call(i,c)),l=Jo(t.computeMask(i,r));if(t.activityRegularizer)throw new Uo("LayersModel invocation with concrete Tensor value(s) in the presence of activity regularizer(s) is not supported yet.");for(let e=0;e<a.length;++e){const t=a[e],i=o[e],s=l[e];n[t.id]=[i,s]}}}}const a=[],s=[],r=[];for(const e of this.outputs){Ko(e.id in n,`Could not compute output ${e.name} : ${e.id}`);const[t,i]=n[e.id];r.push(t.shape),a.push(t),s.push(i)}return[a,s,r]}buildNodeConversionMap(e){const t={};let n;for(const e of this.layers){n=e instanceof tp?1:0;for(let i=0;i<e.inboundNodes.length;i++){const a=tp.nodeKey(e,i);this.containerNodes.has(a)&&(t[a]=n,n+=1)}}return t}getLayer(e,t){if(null!=t){if(this.layers.length<=t)throw new Bo(`Was asked to retrieve layer at index ${t}, but model only has ${this.layers.length} layer(s).`);return this.layers[t]}if(null==e)throw new Bo("Provide either a layer name or layer index");for(const t of this.layers)if(t.name===e)return t;throw new Bo(`No such layer: ${e}`)}calculateLosses(){return si((()=>{const e=[];for(const t of this.layers)for(let n=0;n<t.inboundNodes.length;++n){const i=tp.nodeKey(t,n);this.containerNodes.has(i)&&e.push(...t.calculateLosses())}return e}))}getConfig(){const e={name:this.name},t=this.buildNodeConversionMap(this.layers),n=[];for(const e of this.layers){const i=e.getClassName(),a=e.getConfig(),s=[];for(let n=0;n<e.inboundNodes.length;n++){const i=e.inboundNodes[n],a=tp.nodeKey(e,n);let r={};if(this.containerNodes.has(a)){if(i.callArgs)try{JSON.stringify(i.callArgs),r=i.callArgs}catch(t){console.warn(`Layer ${e.name} was passed non-serializable keyword arguments: ${i.callArgs}. They will not be included in the serialized model (and thus will be missing at deserialization time).`),r={}}if(i.inboundLayers.length>0){const e=[];for(let n=0;n<i.inboundLayers.length;n++){const a=i.inboundLayers[n],s=i.nodeIndices[n],o=i.tensorIndices[n];let l=t[tp.nodeKey(a,s)];null==l&&(l=0),e.push([a.name,l,o,r])}s.push(e)}}}const r={};r.name=e.name,r.className=i,r.config=a,r.inboundNodes=s,n.push(r)}e.layers=n;const i=[];for(let e=0;e<this.inputLayers.length;e++){const n=this.inputLayers[e],a=this.inputLayersNodeIndices[e],s=tp.nodeKey(n,a);if(!this.containerNodes.has(s))continue;let r=t[s];null==r&&(r=0);const o=this.inputLayersTensorIndices[e];i.push([n.name,r,o])}e.inputLayers=i;const a=[];for(let e=0;e<this.outputLayers.length;e++){const n=this.outputLayers[e],i=this.outputLayersNodeIndices[e],s=tp.nodeKey(n,i);if(!this.containerNodes.has(s))continue;let r=t[s];null==r&&(r=0);const o=this.outputLayersTensorIndices[e];a.push([n.name,r,o])}return e.outputLayers=a,e}static fromConfig(e,t,n={},i=!1){const a={},s={};function r(e,t){e.name in s?s[e.name].push(t):s[e.name]=[t]}function o(e,t){const n=[];let i;for(const s of t){const o=s[0],l=s[1],c=s[2];if(i=null==s[3]?{}:s[3],!(o in a))return void r(e,t);const u=a[o];if(u.inboundNodes.length<=l)return void r(e,t);const h=u.inboundNodes[l];n.push(h.outputTensors[c])}n.length>0&&e.apply(Ho(n),i)}function l(e){const n=e.name,s=Nh(e,null!=t.customObjects?t.customObjects:{});s.setFastWeightInitDuringBuild(i),a[n]=s;e.inboundNodes.forEach((e=>{if(!(e instanceof Array))throw new Bo(`Corrupted configuration, expected array for nodeData: ${e}`);r(s,e)}))}const c=t.name,u=t.layers;for(const e of u)l(e);for(;!al(s);)for(const e of u){const t=a[e.name];if(t.name in s){const e=s[t.name];delete s[t.name];for(const n of e)o(t,n)}}const h=[],p=[],d=t.inputLayers;for(const e of d){const t=e[0],n=e[1],i=e[2];Ko(t in a);const s=a[t].inboundNodes[n].outputTensors;h.push(s[i])}const m=t.outputLayers;for(const e of m){const t=e[0],n=e[1],i=e[2];Ko(t in a);const s=a[t].inboundNodes[n].outputTensors;p.push(s[i])}return new e({inputs:h,outputs:p,name:c})}get stateful(){if(this._stateful)throw new Bo("Container instance unexpectedly has _stateful = true. The statefulness of a Container is determined by the Layers it contains. Its _stateful property must remain the default false.");for(const e of this.layers)if(e.stateful)return!0;return!1}resetStates(){si((()=>{this.layers.forEach((e=>{e.stateful&&e.resetStates()}))}))}}
4368
+ */class tp extends Dc{constructor(e){if(super({}),this.containerNodes=new Set,this.name=e.name,null==this.name){const e=this.getClassName().toLowerCase();this.name=dl(e)}if(this.supportsMasking=!1,this.trainable_=!0,Array.isArray(e.inputs)?this.inputs=e.inputs.slice():this.inputs=[e.inputs],Array.isArray(e.outputs)?this.outputs=e.outputs.slice():this.outputs=[e.outputs],il(this.inputs).length!==this.inputs.length)throw new Bo(`The list of inputs passed to the model is redundant. All inputs should only appear once. Found: ${this.inputs.map((e=>e.name))}`);il(this.outputs).length!==this.outputs.length&&console.warn(`The list of outputs passed to the model is redundant. All outputs should only appear once. Found: ${this.outputs.map((e=>e.name))}`),this.inputLayers=[],this.inputLayersNodeIndices=[],this.inputLayersTensorIndices=[],this.outputLayers=[],this.outputLayersNodeIndices=[],this.outputLayersTensorIndices=[],this.layers=[],this.internalContainerRefs=[];for(const e of this.outputs){const t=e.sourceLayer,n=e.nodeIndex,i=e.tensorIndex;this.outputLayers.push(t),this.outputLayersNodeIndices.push(n),this.outputLayersTensorIndices.push(i)}for(const e of this.inputs){const t=e.sourceLayer,n=e.nodeIndex,i=e.tensorIndex;Ko(0===n,"input layer has >1 nodes"),Ko(0===i,"input layer has >1 tensors"),this.inputLayers.push(t),this.inputLayersNodeIndices.push(n),this.inputLayersTensorIndices.push(i)}this.inputNames=[],this.outputNames=[],this.feedInputShapes=[],this.feedInputNames=[],this.feedOutputNames=[];for(let t=0;t<this.inputLayers.length;t++){const n=this.inputLayers[t];if(!(n instanceof _c))throw new TypeError(`Input layers to a LayersModel must be InputLayer objects. Received inputs: ${e.inputs}. Input ${t} (0-based) originates from layer type ${n.getClassName()}.`);this.inputNames.push(n.name),this.feedInputShapes.push(n.batchInputShape),this.feedInputNames.push(n.name)}for(const e of this.outputLayers)this.outputNames.push(e.name);this.internalInputShapes=this.inputs.map((e=>e.shape)),this.internalOutputShapes=this.outputs.map((e=>e.shape));const t={},n={},i={},a={},s={},r=[],o=(e,t,n,i,a,l)=>{null!=i&&null!=a&&null!=l||(i=e.sourceLayer,a=e.nodeIndex,l=e.tensorIndex);const c=i.inboundNodes[a];if(-1!==n.indexOf(c))throw new Po(`The tensor ${e.name} at layer "${i.name}" is part of a cycle.`);if(-1!==t.indexOf(c))return;this.containerNodes.add(tp.nodeKey(i,a)),i.id in s||(s[i.id]=Object.keys(s).length),-1===n.indexOf(c)&&n.push(c);const u=c.inboundLayers.length;for(let e=0;e<u;e++){const i=c.inputTensors[e],a=c.inboundLayers[e],s=c.nodeIndices[e],r=c.tensorIndices[e];o(i,t,n,a,s,r)}for(t.push(c);n.indexOf(c)>=0;)n.splice(n.indexOf(c),1);r.push(c)},l=[],c=[];for(const e of this.outputs)o(e,l,c);const u=r.slice().reverse();for(const e of u){n[e.id]=e,e.id in t||(t[e.id]=0);let s=t[e.id];const r=null==i[e.outboundLayer.id]?0:i[e.outboundLayer.id];s=Math.max(s,r),i[e.outboundLayer.id]=s,a[e.outboundLayer.id]=e.outboundLayer,t[e.id]=s;for(let i=0;i<e.inboundLayers.length;i++){const a=e.inboundLayers[i],r=e.nodeIndices[i],o=a.inboundNodes[r],l=null==t[o.id]?0:t[o.id];t[o.id]=Math.max(s+1,l),n[o.id]=o}}const h={};for(const e in t){const i=t[e];i in h||(h[i]=[]),h[i].push(n[e])}const p={};for(const e in i){const t=i[e];t in p||(p[t]=[]),p[t].push(a[e])}let d=Object.keys(p).map((e=>parseInt(e,10))).sort(nl);this.layers=[];for(const e of d){const t=p[e];t.sort(((e,t)=>{const n=s[e.id],i=s[t.id];return n<i?-1:n>i?1:0}));for(const e of t)e instanceof tp&&this.internalContainerRefs.push(e),this.layers.push(e)}this.layersByDepth=p,d=Object.keys(h).map((e=>parseInt(e,10))).sort(nl);const m=this.inputs.slice(),f=[];for(const e of d)for(const t of h[e]){const e=t.outboundLayer;if(null!=e){for(const n of t.inputTensors)if(-1===m.indexOf(n))throw new Po(`Graph disconnected: cannot obtain value for tensor ${n} at layer "${e.name}". The following previous layers were accessed without issue: ${f}`);for(const e of t.outputTensors)m.push(e);f.push(e.name)}}this.nodesByDepth=h;const g=this.layers.map((e=>e.name));for(const e of g){const t=g.filter((t=>t===e)).length;if(1!==t)throw new Po(`The name "${e}" is used ${t} times in the model. All layer names should be unique. Layer names: `+JSON.stringify(g))}this.outboundNodes=[],this.inboundNodes=[],new jc({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:this.inputs.map((e=>null)),outputMasks:this.outputs.map((e=>null)),inputShapes:this.inputs.map((e=>e.shape)),outputShapes:this.outputs.map((e=>e.shape))}),this.built=!0,this._refCount=1}assertNotDisposed(){if(0===this._refCount)throw new Error(`Container '${this.name}' is already disposed.`)}dispose(){this.assertNotDisposed();const e={refCountAfterDispose:null,numDisposedVariables:0};if(0==--this._refCount){for(const t of this.layers)e.numDisposedVariables+=t.dispose().numDisposedVariables;for(const t of this.internalContainerRefs)e.numDisposedVariables+=t.dispose().numDisposedVariables}return e.refCountAfterDispose=this._refCount,e}get trainable(){return this.trainable_}set trainable(e){this.layers.forEach((t=>{t._trainableWeights.forEach((t=>t.trainable=e))})),this.trainable_=e}get trainableWeights(){if(this._trainableWeights.length>0)throw new Bo("Container instance unexpectedly contains _trainableWeights.The trainable weights of a Container are a union of the trainable weights of its consituent Layers. Its own _trainableWeights must remain an empty Array.");if(!this.trainable)return[];let e=[];for(const t of this.layers)e=e.concat(t.trainableWeights);return e}get nonTrainableWeights(){const e=[];for(const t of this.layers)e.push(...t.nonTrainableWeights);if(!this.trainable){const t=[];for(const e of this.layers)t.push(...e.trainableWeights);return t.concat(e)}return e}get weights(){return this.trainableWeights.concat(this.nonTrainableWeights)}loadWeights(e,t=!0){const n={};let i=0;for(const e of this.layers)for(const t of e.weights){if(null!=n[t.originalName])throw new Bo(`Duplicate weight name: ${t.originalName}`);n[t.originalName]=t,i++}const a=[];for(const i in e){let s=i;if(null==n[i]){const e=i.split("/");s=e.slice(0,-2).concat([e[e.length-1]]).join("/")}if(null!=n[s])a.push([n[s],e[i]]);else if(t)throw new Bo(`Provided weight data has no target variable: ${i}`);delete n[s]}if(t){const e=[];for(const t in n)e.push(t);if(e.length>0)throw new Bo(`${e.length} of ${i} weights are not set: ${e}`)}Ac(a)}updatedConfig(){const e=this.getConfig(),t={};return t.className=this.getClassName(),t.config=e,t.kerasVersion=`tfjs-layers ${ep}`,t.backend="TensorFlow.js",t}toJSON(e,t=!0){const n=Xh(this.updatedConfig());return t?JSON.stringify(n):n}call(e,t){return si((()=>{e=Jo(e);const n=new Rc;for(let t=0;t<this.inputs.length;++t)n.add(this.inputs[t],e[t]);return Oc(this.outputs,n,t)}))}computeMask(e,t){return si((()=>{let n;return e=Jo(e),n=null==t?Go(null,e.length):Jo(t),this.runInternalGraph(e,n)[1]}))}computeOutputShape(e){const t=wc(e);if(t.length!==this.inputLayers.length)throw new Bo(`Invalid inputShape argument ${e}: model has ${this.inputLayers.length} tensor inputs.`);const n={};for(let e=0;e<t.length;e++){const i=this.inputLayers[e],a=t[e];n[i.name+"_0_0"]=a}const i=Object.keys(this.nodesByDepth).map((e=>parseInt(e,10))).sort(nl);if(i.length>1)for(const e of i){const t=this.nodesByDepth[e];for(const e of t){const t=e.outboundLayer;if(-1!==this.inputLayers.map((e=>e.id)).indexOf(t.id))continue;const i=[];for(let t=0;t<e.inboundLayers.length;t++){const a=e.inboundLayers[t],s=e.nodeIndices[t],r=e.tensorIndices[t],o=n[`${a.name}_${s}_${r}`];i.push(o)}const a=wc(t.computeOutputShape(Ho(i))),s=t.inboundNodes.indexOf(e);for(let e=0;e<a.length;e++){n[`${t.name}_${s}_${e}`]=a[e]}}}const a=[],s=[];for(let e=0;e<this.outputLayers.length;e++){const t=this.outputLayers[e],n=this.outputLayersNodeIndices[e],i=this.outputLayersTensorIndices[e],a=`${t.name}_${n}_${i}`;s.push(a)}for(let e=0;e<s.length;e++){const t=s[e];Ko(t in n),a.push(n[t])}return Ho(a)}runInternalGraph(e,t){null==t&&(t=Go(null,e.length));const n={};for(let i=0;i<this.inputs.length;++i){const a=this.inputs[i],s=e[i],r=t[i];n[a.id]=[s,r]}const i=Object.keys(this.nodesByDepth).map((e=>parseInt(e,10))).sort(nl);for(const e of i){const t=this.nodesByDepth[e];for(const e of t){const t=e.outboundLayer,i=e.inputTensors,a=e.outputTensors,s=new Array;for(const e of i)e.id in n&&s.push(n[e.id]);if(s.length===i.length){let i,r,o,l,c={};if(null!=e.callArgs&&(c=e.callArgs),1===s.length){const[e,n]=s[0];null==c.mask&&(c.mask=n),o=Jo(t.call(e,c)),l=Jo(t.computeMask(e,n)),i=[e],r=[n]}else i=s.map((e=>e[0])),r=s.map((e=>e[1])),null==c.mask&&(c.mask=r),o=Jo(t.call(i,c)),l=Jo(t.computeMask(i,r));if(t.activityRegularizer)throw new Uo("LayersModel invocation with concrete Tensor value(s) in the presence of activity regularizer(s) is not supported yet.");for(let e=0;e<a.length;++e){const t=a[e],i=o[e],s=l[e];n[t.id]=[i,s]}}}}const a=[],s=[],r=[];for(const e of this.outputs){Ko(e.id in n,`Could not compute output ${e.name} : ${e.id}`);const[t,i]=n[e.id];r.push(t.shape),a.push(t),s.push(i)}return[a,s,r]}buildNodeConversionMap(e){const t={};let n;for(const e of this.layers){n=e instanceof tp?1:0;for(let i=0;i<e.inboundNodes.length;i++){const a=tp.nodeKey(e,i);this.containerNodes.has(a)&&(t[a]=n,n+=1)}}return t}getLayer(e,t){if(null!=t){if(this.layers.length<=t)throw new Bo(`Was asked to retrieve layer at index ${t}, but model only has ${this.layers.length} layer(s).`);return this.layers[t]}if(null==e)throw new Bo("Provide either a layer name or layer index");for(const t of this.layers)if(t.name===e)return t;throw new Bo(`No such layer: ${e}`)}calculateLosses(){return si((()=>{const e=[];for(const t of this.layers)for(let n=0;n<t.inboundNodes.length;++n){const i=tp.nodeKey(t,n);this.containerNodes.has(i)&&e.push(...t.calculateLosses())}return e}))}getConfig(){const e={name:this.name},t=this.buildNodeConversionMap(this.layers),n=[];for(const e of this.layers){const i=e.getClassName(),a=e.getConfig(),s=[];for(let n=0;n<e.inboundNodes.length;n++){const i=e.inboundNodes[n],a=tp.nodeKey(e,n);let r={};if(this.containerNodes.has(a)){if(i.callArgs)try{JSON.stringify(i.callArgs),r=i.callArgs}catch(t){console.warn(`Layer ${e.name} was passed non-serializable keyword arguments: ${i.callArgs}. They will not be included in the serialized model (and thus will be missing at deserialization time).`),r={}}if(i.inboundLayers.length>0){const e=[];for(let n=0;n<i.inboundLayers.length;n++){const a=i.inboundLayers[n],s=i.nodeIndices[n],o=i.tensorIndices[n];let l=t[tp.nodeKey(a,s)];null==l&&(l=0),e.push([a.name,l,o,r])}s.push(e)}}}const r={};r.name=e.name,r.className=i,r.config=a,r.inboundNodes=s,n.push(r)}e.layers=n;const i=[];for(let e=0;e<this.inputLayers.length;e++){const n=this.inputLayers[e],a=this.inputLayersNodeIndices[e],s=tp.nodeKey(n,a);if(!this.containerNodes.has(s))continue;let r=t[s];null==r&&(r=0);const o=this.inputLayersTensorIndices[e];i.push([n.name,r,o])}e.inputLayers=i;const a=[];for(let e=0;e<this.outputLayers.length;e++){const n=this.outputLayers[e],i=this.outputLayersNodeIndices[e],s=tp.nodeKey(n,i);if(!this.containerNodes.has(s))continue;let r=t[s];null==r&&(r=0);const o=this.outputLayersTensorIndices[e];a.push([n.name,r,o])}return e.outputLayers=a,e}static fromConfig(e,t,n={},i=!1){const a={},s={};function r(e,t){e.name in s?s[e.name].push(t):s[e.name]=[t]}function o(e,t){const n=[];let i;for(const s of t){const o=s[0],l=s[1],c=s[2];if(i=null==s[3]?{}:s[3],!(o in a))return void r(e,t);const u=a[o];if(u.inboundNodes.length<=l)return void r(e,t);const h=u.inboundNodes[l];n.push(h.outputTensors[c])}n.length>0&&e.apply(Ho(n),i)}function l(e){const n=e.name,s=Nh(e,null!=t.customObjects?t.customObjects:{});s.setFastWeightInitDuringBuild(i),a[n]=s;e.inboundNodes.forEach((e=>{if(!(e instanceof Array))throw new Bo(`Corrupted configuration, expected array for nodeData: ${e}`);r(s,e)}))}const c=t.name,u=t.layers;for(const e of u)l(e);for(;!al(s);)for(const e of u){const t=a[e.name];if(t.name in s){const e=s[t.name];delete s[t.name];for(const n of e)o(t,n)}}const h=[],p=[],d=t.inputLayers;for(const e of d){const t=e[0],n=e[1],i=e[2];Ko(t in a);const s=a[t].inboundNodes[n].outputTensors;h.push(s[i])}const m=t.outputLayers;for(const e of m){const t=e[0],n=e[1],i=e[2];Ko(t in a);const s=a[t].inboundNodes[n].outputTensors;p.push(s[i])}return new e({inputs:h,outputs:p,name:c})}get stateful(){if(this._stateful)throw new Bo("Container instance unexpectedly has _stateful = true. The statefulness of a Container is determined by the Layers it contains. Its _stateful property must remain the default false.");for(const e of this.layers)if(e.stateful)return!0;return!1}resetStates(){si((()=>{this.layers.forEach((e=>{e.stateful&&e.resetStates()}))}))}}
4369
4369
  /**
4370
4370
  * @license
4371
4371
  * Copyright 2018 Google LLC
@@ -4374,7 +4374,7 @@ const Gh=1048576;function Vh(e,t,n=!1){if(null==e||"object"!=typeof e||Object.ge
4374
4374
  * license that can be found in the LICENSE file or at
4375
4375
  * https://opensource.org/licenses/MIT.
4376
4376
  * =============================================================================
4377
- */function np(e,t){return function(e,t,n){const i=t.length;if(null==e||Array.isArray(e)&&0===e.length)return t.map((e=>null));if(1===i)return Array.isArray(e)&&1===e.length?e:"object"==typeof e&&t[0]in e?[e[t[0]]]:[e];if(Array.isArray(e)){if(e.length!==i)throw new Error(`Provided ${n} is an array of ${e.length} element(s), but the model has ${i} outputs. Make sure a set of weights is provided for each model output.`);return e}if("object"==typeof e&&Object.keys(e).length>0&&"object"==typeof e[Object.keys(e)[0]]){const n=[];return t.forEach((t=>{t in e?n.push(e[t]):n.push(null)})),n}throw new Error(`The model has multiple (${i}) outputs, so ${n} must be either an array with ${i} elements or an object with ${t} keys. Provided ${n} not understood: ${JSON.stringify(e)}`)}(e,t,"classWeight")}async function ip(e,t,n,i){if(null!=t||null!=i)throw new Error("Support sampleWeight is not implemented yet");if(null!=n){const t=si((()=>{if(1===e.shape.length)return Mi(e);if(2===e.shape.length){if(e.shape[1]>1){return Ti(e,1)}if(1===e.shape[1])return _i(e,[e.shape[0]]);throw new Error(`Encountered unexpected last-dimension size (${e.shape[1]}) during handling of class weights. The size is expected to be >= 1.`)}throw new Error(`Unexpected rank of target (y) tensor (${e.rank}) during handling of class weights. The rank is expected to be 1 or 2.`)})),i=Array.from(await t.data());ri(t);const a=[];return i.forEach((e=>{if(null==n[e])throw new Error(`classWeight must contain all classes in the training data. The class ${e} exists in the data but not in classWeight`);a.push(n[e])})),Vs(a,"float32")}return null}function ap(e,t){return xi(e,t)}
4377
+ */function np(e,t){return function(e,t,n){const i=t.length;if(null==e||Array.isArray(e)&&0===e.length)return t.map((e=>null));if(1===i)return Array.isArray(e)&&1===e.length?e:"object"==typeof e&&t[0]in e?[e[t[0]]]:[e];if(Array.isArray(e)){if(e.length!==i)throw new Error(`Provided ${n} is an array of ${e.length} element(s), but the model has ${i} outputs. Make sure a set of weights is provided for each model output.`);return e}if("object"==typeof e&&Object.keys(e).length>0&&"object"==typeof e[Object.keys(e)[0]]){const n=[];return t.forEach((t=>{t in e?n.push(e[t]):n.push(null)})),n}throw new Error(`The model has multiple (${i}) outputs, so ${n} must be either an array with ${i} elements or an object with ${t} keys. Provided ${n} not understood: ${JSON.stringify(e)}`)}(e,t,"classWeight")}async function ip(e,t,n,i){if(null!=t||null!=i)throw new Error("Support sampleWeight is not implemented yet");if(null!=n){const t=si((()=>{if(1===e.shape.length)return Mi(e);if(2===e.shape.length){if(e.shape[1]>1){return Ii(e,1)}if(1===e.shape[1])return _i(e,[e.shape[0]]);throw new Error(`Encountered unexpected last-dimension size (${e.shape[1]}) during handling of class weights. The size is expected to be >= 1.`)}throw new Error(`Unexpected rank of target (y) tensor (${e.rank}) during handling of class weights. The rank is expected to be 1 or 2.`)})),i=Array.from(await t.data());ri(t);const a=[];return i.forEach((e=>{if(null==n[e])throw new Error(`classWeight must contain all classes in the training data. The class ${e} exists in the data but not in classWeight`);a.push(n[e])})),Gs(a,"float32")}return null}function ap(e,t){return xi(e,t)}
4378
4378
  /**
4379
4379
  * @license
4380
4380
  * Copyright 2018 Google LLC
@@ -4383,7 +4383,7 @@ const Gh=1048576;function Vh(e,t,n=!1){if(null==e||"object"!=typeof e||Object.ge
4383
4383
  * license that can be found in the LICENSE file or at
4384
4384
  * https://opensource.org/licenses/MIT.
4385
4385
  * =============================================================================
4386
- */function sp(e,t){let n,i;const a=t;n=a.xs,i=a.ys,I(null!=n&&null!=i,(()=>`A Dataset iterator for fitDataset() is expected to generate objects of the form \`{xs: xVal, ys: yVal}\`, where the two values may be \`tf.Tensor\`, an array of Tensors, or a map of string to Tensor. The provided Dataset instead generates ${t}`));const s=rp("input",e.inputNames,n),r=rp("output",e.outputNames,i),o=s[0].shape[0];I(s.length===e.inputs.length,(()=>`LayersModel has ${e.inputs.length} inputs, but the dataset provides ${s.length} inputs. (Expected input keys: ${JSON.stringify(e.inputNames)})`)),I(r.length===e.outputs.length,(()=>`LayersModel has ${e.outputs.length} outputs, but the dataset provides ${r.length} outputs. (Expected output keys: ${JSON.stringify(e.outputNames)})`));for(let t=0;t<s.length;t++)I(s[t].shape[0]===o,(()=>`Batch size mismatch: input ${e.inputNames[t]} has ${s[t].shape[0]}; expected ${o} based on input ${e.inputNames[0]}.`));for(let t=0;t<r.length;t++)I(r[t].shape[0]===o,(()=>`Batch size mismatch: output ${e.outputNames[t]} has ${r[t].shape[0]}; expected ${o} based on input ${e.inputNames[0]}.`));return{xs:s,ys:r}}function rp(e,t,n){if(n instanceof Ut)return[n];if(Array.isArray(n))return I(n.length===t.length,(()=>`Received an array of ${n.length} Tensors, but expected ${t.length} to match the ${e} keys ${t}.`)),n;{const i=[];for(const a of t){if(null==n[a])throw new Bo(`The feature data generated by the dataset lacks the required ${e} key '${a}'.`);i.push(n[a])}return i}}async function op(e,t,n){const i=null!=n.batchesPerEpoch;if(I(null!=e.optimizer,(()=>"You must compile a model before training/testing. Use LayersModel.compile(modelCompileConfig).")),I(null!=n,(()=>"For fitDataset(), the 2nd argument (config) is required, but it is not provided in this call.")),I(null!=n.epochs&&n.epochs>0&&Number.isInteger(n.epochs),(()=>`For fitDataset(), config.epochs is expected to be a positive integer, but got ${n.epochs}`)),I(!i||n.batchesPerEpoch>0&&Number.isInteger(n.batchesPerEpoch),(()=>`For fitDataset(), config.batchesPerEpoch is expected to be a positive integer if specified, but got ${n.batchesPerEpoch}`)),I(null==n.validationSplit,(()=>"`validationSplit` is not supported by `fitDataset()`. Use validationData instead.")),e.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");e.isTraining=!0;try{const a=null!=n.validationData;let s,r;if(a)if(lp(n.validationData))I(null==n.validationBatches||n.validationBatches>0&&Number.isInteger(n.validationBatches),(()=>`For fitDataset() with dataset-based validation, config.validationBatches is expected not to be provided, or to be a positive integer, but got ${n.validationBatches}`));else{const e=function(e){if(3===e.length)throw new Uo("Validation with sample weights is not implemented yet.");return{xs:e[0],ys:e[1]}}(n.validationData);s=e.xs,r=e.ys}const o=e.makeTrainFunction(),l=e.getDedupedMetricsNames();let c;c=a?l.slice().concat(l.map((e=>"val_"+e))):l.slice();const u=kh(n.callbacks,n.yieldEvery),h=null==n.verbose?1:n.verbose,{callbackList:p,history:d}=Sh(u,h,n.epochs,null,null,function(e,t){let n=null;null!=t.batchesPerEpoch?n=t.batchesPerEpoch:Number.isFinite(e.size)&&(n=e.size);return n}(t,n),null,a,c);p.setModel(e),e.history=d,await p.onTrainBegin(),e.stopTraining_=!1;let m=null==n.initialEpoch?0:n.initialEpoch,f=await t.iterator();for(;m<n.epochs;){const c={};await p.onEpochBegin(m);let u=0,h=0;for(i||(f=await t.iterator());!i||u<n.batchesPerEpoch;){const t=await f.next();if(i&&t.done){console.warn(`You provided \`batchesPerEpoch\` as ${n.batchesPerEpoch}, but your dataset iterator ran out of data after ${u} batches; interrupting training. Make sure that your dataset can generate at least \`batchesPerEpoch * epochs\` batches (in this case, `+n.batchesPerEpoch*n.epochs+" batches). You may need to use the repeat() function when building your dataset.");break}if(null!=t.value){const{xs:i,ys:a}=sp(e,t.value),s={};s.batch=h,s.size=i[0].shape[0],await p.onBatchBegin(h,s);const r=[];if(null!=n.classWeight){const t=np(n.classWeight,e.outputNames);for(let e=0;e<t.length;++e)r.push(await ip(a[e],null,t[e]))}const c=i.concat(a).concat(r),d=o(c);ri(c);for(let e=0;e<l.length;++e){const t=l[e],n=d[e];s[t]=n,oi(n)}await p.onBatchEnd(h,s),mh(s),h++,u++}if(i?u>=n.batchesPerEpoch:t.done){if(a){let t;t=lp(n.validationData)?Jo(await e.evaluateDataset(n.validationData,{batches:n.validationBatches})):Jo(e.evaluate(s,r,{batchSize:null==n.validationBatchSize?32:n.validationBatchSize,verbose:0}));for(let n=0;n<e.metricsNames.length;++n)c[`val_${e.metricsNames[n]}`]=t[n]}break}if(e.stopTraining_)break}if(await p.onEpochEnd(m,c),m++,e.stopTraining_)break}return await p.onTrainEnd(),await e.history.syncData(),e.history}finally{e.isTraining=!1}}function lp(e){return"function"==typeof e.iterator}
4386
+ */function sp(e,t){let n,i;const a=t;n=a.xs,i=a.ys,T(null!=n&&null!=i,(()=>`A Dataset iterator for fitDataset() is expected to generate objects of the form \`{xs: xVal, ys: yVal}\`, where the two values may be \`tf.Tensor\`, an array of Tensors, or a map of string to Tensor. The provided Dataset instead generates ${t}`));const s=rp("input",e.inputNames,n),r=rp("output",e.outputNames,i),o=s[0].shape[0];T(s.length===e.inputs.length,(()=>`LayersModel has ${e.inputs.length} inputs, but the dataset provides ${s.length} inputs. (Expected input keys: ${JSON.stringify(e.inputNames)})`)),T(r.length===e.outputs.length,(()=>`LayersModel has ${e.outputs.length} outputs, but the dataset provides ${r.length} outputs. (Expected output keys: ${JSON.stringify(e.outputNames)})`));for(let t=0;t<s.length;t++)T(s[t].shape[0]===o,(()=>`Batch size mismatch: input ${e.inputNames[t]} has ${s[t].shape[0]}; expected ${o} based on input ${e.inputNames[0]}.`));for(let t=0;t<r.length;t++)T(r[t].shape[0]===o,(()=>`Batch size mismatch: output ${e.outputNames[t]} has ${r[t].shape[0]}; expected ${o} based on input ${e.inputNames[0]}.`));return{xs:s,ys:r}}function rp(e,t,n){if(n instanceof Ut)return[n];if(Array.isArray(n))return T(n.length===t.length,(()=>`Received an array of ${n.length} Tensors, but expected ${t.length} to match the ${e} keys ${t}.`)),n;{const i=[];for(const a of t){if(null==n[a])throw new Bo(`The feature data generated by the dataset lacks the required ${e} key '${a}'.`);i.push(n[a])}return i}}async function op(e,t,n){const i=null!=n.batchesPerEpoch;if(T(null!=e.optimizer,(()=>"You must compile a model before training/testing. Use LayersModel.compile(modelCompileConfig).")),T(null!=n,(()=>"For fitDataset(), the 2nd argument (config) is required, but it is not provided in this call.")),T(null!=n.epochs&&n.epochs>0&&Number.isInteger(n.epochs),(()=>`For fitDataset(), config.epochs is expected to be a positive integer, but got ${n.epochs}`)),T(!i||n.batchesPerEpoch>0&&Number.isInteger(n.batchesPerEpoch),(()=>`For fitDataset(), config.batchesPerEpoch is expected to be a positive integer if specified, but got ${n.batchesPerEpoch}`)),T(null==n.validationSplit,(()=>"`validationSplit` is not supported by `fitDataset()`. Use validationData instead.")),e.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");e.isTraining=!0;try{const a=null!=n.validationData;let s,r;if(a)if(lp(n.validationData))T(null==n.validationBatches||n.validationBatches>0&&Number.isInteger(n.validationBatches),(()=>`For fitDataset() with dataset-based validation, config.validationBatches is expected not to be provided, or to be a positive integer, but got ${n.validationBatches}`));else{const e=function(e){if(3===e.length)throw new Uo("Validation with sample weights is not implemented yet.");return{xs:e[0],ys:e[1]}}(n.validationData);s=e.xs,r=e.ys}const o=e.makeTrainFunction(),l=e.getDedupedMetricsNames();let c;c=a?l.slice().concat(l.map((e=>"val_"+e))):l.slice();const u=kh(n.callbacks,n.yieldEvery),h=null==n.verbose?1:n.verbose,{callbackList:p,history:d}=Sh(u,h,n.epochs,null,null,function(e,t){let n=null;null!=t.batchesPerEpoch?n=t.batchesPerEpoch:Number.isFinite(e.size)&&(n=e.size);return n}(t,n),null,a,c);p.setModel(e),e.history=d,await p.onTrainBegin(),e.stopTraining_=!1;let m=null==n.initialEpoch?0:n.initialEpoch,f=await t.iterator();for(;m<n.epochs;){const c={};await p.onEpochBegin(m);let u=0,h=0;for(i||(f=await t.iterator());!i||u<n.batchesPerEpoch;){const t=await f.next();if(i&&t.done){console.warn(`You provided \`batchesPerEpoch\` as ${n.batchesPerEpoch}, but your dataset iterator ran out of data after ${u} batches; interrupting training. Make sure that your dataset can generate at least \`batchesPerEpoch * epochs\` batches (in this case, `+n.batchesPerEpoch*n.epochs+" batches). You may need to use the repeat() function when building your dataset.");break}if(null!=t.value){const{xs:i,ys:a}=sp(e,t.value),s={};s.batch=h,s.size=i[0].shape[0],await p.onBatchBegin(h,s);const r=[];if(null!=n.classWeight){const t=np(n.classWeight,e.outputNames);for(let e=0;e<t.length;++e)r.push(await ip(a[e],null,t[e]))}const c=i.concat(a).concat(r),d=o(c);ri(c);for(let e=0;e<l.length;++e){const t=l[e],n=d[e];s[t]=n,oi(n)}await p.onBatchEnd(h,s),mh(s),h++,u++}if(i?u>=n.batchesPerEpoch:t.done){if(a){let t;t=lp(n.validationData)?Jo(await e.evaluateDataset(n.validationData,{batches:n.validationBatches})):Jo(e.evaluate(s,r,{batchSize:null==n.validationBatchSize?32:n.validationBatchSize,verbose:0}));for(let n=0;n<e.metricsNames.length;++n)c[`val_${e.metricsNames[n]}`]=t[n]}break}if(e.stopTraining_)break}if(await p.onEpochEnd(m,c),m++,e.stopTraining_)break}return await p.onTrainEnd(),await e.history.syncData(),e.history}finally{e.isTraining=!1}}function lp(e){return"function"==typeof e.iterator}
4387
4387
  /**
4388
4388
  * @license
4389
4389
  * Copyright 2018 Google LLC
@@ -4393,7 +4393,7 @@ const Gh=1048576;function Vh(e,t,n=!1){if(null==e||"object"!=typeof e||Object.ge
4393
4393
  * https://opensource.org/licenses/MIT.
4394
4394
  * =============================================================================
4395
4395
  */
4396
- function cp(e){I(e>0&&Number.isInteger(e),(()=>`batchSize is required to be a positive integer, but got ${e}`))}function up(e,t,n){return null==e?[null]:Array.isArray(e)?e.map((e=>Ll(e,t,n-t))):Ll(e,t,n-t)}function hp(e,t){return si((()=>null==e?null:Array.isArray(e)?e.map((e=>hp(e,t))):Vl(e,"int32"===t.dtype?t:ei(t,"int32"))))}function pp(e,t){const n=[];let i=0,a=null;for(;i<e;)a=i+t,a>=e&&(a=e),n.push([i,a]),i=a;return n}function dp(e){const t=[];e instanceof Ut&&(e=[e]);for(let n=0;n<e.length;++n){const i=e[n];if(1===i.rank)t.push(Rl(i,1));else{if(0===i.rank)throw new Error("Expected tensor to be at least 1D, but received a 0D tensor (scalar).");t.push(i)}}return t}function mp(e,t){if(null==e)return;const n=[];if(t instanceof Ut)n.push(t.id);else if(Array.isArray(t))t.forEach((e=>n.push(e.id)));else if(null!=t)for(const e in t){const i=t[e];n.push(i.id)}const i=[];if(e instanceof Ut)-1===n.indexOf(e.id)&&i.push(e);else if(Array.isArray(e))e.forEach((e=>{-1===n.indexOf(e.id)&&i.push(e)}));else if(null!=e)for(const t in e){const a=e[t];-1===n.indexOf(a.id)&&i.push(a)}i.forEach((e=>{e.isDisposed||e.dispose()}))}
4396
+ function cp(e){T(e>0&&Number.isInteger(e),(()=>`batchSize is required to be a positive integer, but got ${e}`))}function up(e,t,n){return null==e?[null]:Array.isArray(e)?e.map((e=>Ll(e,t,n-t))):Ll(e,t,n-t)}function hp(e,t){return si((()=>null==e?null:Array.isArray(e)?e.map((e=>hp(e,t))):Gl(e,"int32"===t.dtype?t:ei(t,"int32"))))}function pp(e,t){const n=[];let i=0,a=null;for(;i<e;)a=i+t,a>=e&&(a=e),n.push([i,a]),i=a;return n}function dp(e){const t=[];e instanceof Ut&&(e=[e]);for(let n=0;n<e.length;++n){const i=e[n];if(1===i.rank)t.push(Rl(i,1));else{if(0===i.rank)throw new Error("Expected tensor to be at least 1D, but received a 0D tensor (scalar).");t.push(i)}}return t}function mp(e,t){if(null==e)return;const n=[];if(t instanceof Ut)n.push(t.id);else if(Array.isArray(t))t.forEach((e=>n.push(e.id)));else if(null!=t)for(const e in t){const i=t[e];n.push(i.id)}const i=[];if(e instanceof Ut)-1===n.indexOf(e.id)&&i.push(e);else if(Array.isArray(e))e.forEach((e=>{-1===n.indexOf(e.id)&&i.push(e)}));else if(null!=e)for(const t in e){const a=e[t];-1===n.indexOf(a.id)&&i.push(a)}i.forEach((e=>{e.isDisposed||e.dispose()}))}
4397
4397
  /**
4398
4398
  * @license
4399
4399
  * Copyright 2018 Google LLC
@@ -4402,7 +4402,7 @@ function cp(e){I(e>0&&Number.isInteger(e),(()=>`batchSize is required to be a po
4402
4402
  * license that can be found in the LICENSE file or at
4403
4403
  * https://opensource.org/licenses/MIT.
4404
4404
  * =============================================================================
4405
- */function fp(e){return Array.isArray(e)}function gp(e){return!function(e){return e instanceof Ut}(e)&&!fp(e)}function vp(e,t,n,i=!0,a=""){if(null==t||0===t.length){if(null!=e){let t=!1;if(fp(e)&&e.length>0)t=!0;else if(gp(e)){for(const n in e)if(e.hasOwnProperty(n)){t=!0;break}}else t=!0;if(t)throw new Bo(`Error when checking model ${a} expected no data, but got ${e}`)}return[]}if(null==e)return t.map((e=>null));let s;if(gp(e)){s=[];for(const n of t){if(null==e[n])throw new Bo(`No data provided for "${n}". Need data for each key in: ${t}`);s.push(e[n])}}else if(fp(e)){if(e.length!==t.length)throw new Bo(`Error when checking model ${a}: the Array of Tensors that you are passing to your model is not the size the model expected. Expected to see ${t.length} Tensor(s), but instead got the following list of Tensor(s): ${e}`);s=e}else{if(t.length>1)throw new Bo(`The model ${a} expects ${t.length} Tensor(s), but only received one Tensor. Found: Tensor with shape ${e.shape}`);s=[e]}if(s=dp(s),null!=n)for(let e=0;e<t.length;++e){if(null==n[e])continue;const r=s[e];if(r.shape.length!==n[e].length)throw new Bo(`Error when checking ${a}: expected ${t[e]} to have ${n[e].length} dimension(s). but got array with shape ${r.shape}`);for(let t=0;t<n[e].length;++t){if(0===t&&!i)continue;const s=r.shape[t],o=n[e][t];if(null!=o&&o>=0&&s!==o)throw new Bo(`${a} expected a batch of elements where each example has shape [${n[e].slice(1,n[e].length)}] (i.e.,tensor shape [*,${n[e].slice(1,n[e].length)}]) but the ${a} received an input with ${r.shape[0]} examples, each with shape [${r.shape.slice(1,r.shape.length)}] (tensor shape [${r.shape}])`)}}return s}function yp(e,t,n,i=!0,a=""){let s;if(Array.isArray(e)){if(e.length!==t.length)throw new Bo(`Error when checking model ${a}: the Array of Tensors that you are passing to your model is not the size the the model expected. Expected to see ${t.length} Tensor(s), but instead got ${e.length} Tensors(s).`);s=e}else{if(t.length>1)throw new Bo(`The model expects ${t.length} ${a} Tensors, but only received one Tensor. Found: array with shape ${JSON.stringify(e.shape)}.`);s=[e]}if(null!=n)for(let e=0;e<t.length;++e){if(null==n[e])continue;const r=s[e];if(r.shape.length!==n[e].length)throw new Bo(`Error when checking ${a}: expected ${t[e]} to have ${n[e].length} dimension(s), but got array with shape ${JSON.stringify(r.shape)}`);for(let s=0;s<n[e].length;++s){if(0===s&&!i)continue;const o=r.shape[s],l=n[e][s];if(null!=l&&l!==o)throw new Bo(`Error when checking ${a}: expected ${t[e]} to have shape ${JSON.stringify(n[e])} but got array with shape ${JSON.stringify(r.shape)}.`)}}}class bp extends tp{constructor(e){super(e),this.isTraining=!1}summary(e,t,n=console.log){if(!this.built)throw new Bo("This model has never been called, thus its weights have not been created yet. So no summary can be displayed. Build the model first (e.g., by calling it on some test data).");qh(this,e,t,n)}compile(e){if(null==e.loss&&(e.loss=[]),this.loss=e.loss,"string"==typeof e.optimizer)this.optimizer_=function(e){const t={Adagrad:()=>Ur.adagrad(.01),Adadelta:()=>Ur.adadelta(1,.95,Fl()),Adam:()=>Ur.adam(.001,.9,.999,Fl()),Adamax:()=>Ur.adamax(.002,.9,.999,Fl(),0),RMSProp:()=>Ur.rmsprop(.001,.9,0,Fl()),SGD:()=>Ur.sgd(.01)};if(t.adagrad=t.Adagrad,t.adadelta=t.Adadelta,t.adam=t.Adam,t.adamax=t.Adamax,t.rmsprop=t.RMSProp,t.sgd=t.SGD,e in t)return t[e]();throw new Bo(`Unknown Optimizer ${e}`)}(e.optimizer),this.isOptimizerOwned=!0;else{if(!(e.optimizer instanceof Fr))throw new Bo("User-defined optimizer must be an instance of tf.Optimizer.");this.optimizer_=e.optimizer,this.isOptimizerOwned=!1}let t=[];if(Array.isArray(e.loss)||"string"==typeof e.loss||"function"==typeof e.loss)if(Array.isArray(e.loss)){if(e.loss.length!==this.outputs.length)throw new Bo(`When passing an Array as loss, it should have one entry per model output. The model has ${this.outputs.length} output(s), but you passed loss=${e.loss}.`);const n=e.loss;t=n.map((e=>Fh(e)))}else{const n=Fh(e.loss);this.outputs.forEach((e=>{t.push(n)}))}else{e.loss=e.loss;for(const t in e.loss)if(-1===this.outputNames.indexOf(t))throw new Bo(`Unknown entry in loss dictionary: "${t}". Only expected the following keys: ${this.outputNames}`);for(const n of this.outputNames)null==e.loss[n]&&console.warn(`Output "${n}" is missing from loss dictionary. We assume this was done on purpose, and we will not be expecting data to be passed to ${n} during training`),t.push(Fh(e.loss[n]))}this.lossFunctions=t,this.feedOutputNames=[],this.feedOutputShapes=[],this.feedLossFns=[];for(let e=0;e<this.outputs.length;++e){const t=this.internalOutputShapes[e],n=this.outputNames[e];this.feedOutputNames.push(n),this.feedOutputShapes.push(t),this.feedLossFns.push(this.lossFunctions[e])}const n=[];this.metrics=e.metrics,this.metricsNames=["loss"],this.metricsTensors=[],Nl("loss",(()=>{for(let e=0;e<this.outputs.length;++e){if(-1!==n.indexOf(e))continue;const t=this.lossFunctions[e];this.outputs.length>1&&(this.metricsTensors.push([t,e]),this.metricsNames.push(this.outputNames[e]+"_loss"))}}));const i=function(e,t){if(null==e||Array.isArray(e)&&0===e.length)return t.map((e=>[]));let n;if("string"==typeof e||"function"==typeof e)n=[e];else{if(!Array.isArray(e)&&"object"!=typeof e)throw new TypeError(`Type of metrics argument not understood. Expected an string,function, Array, or Object, found: ${e}`);n=e}if(Array.isArray(n))return t.map((e=>n));{const e=[];for(const i of t){let t=n.hasOwnProperty(i)?n[i]:[];Array.isArray(t)||(t=[t]),e.push(t)}return e}}(e.metrics,this.outputNames),a=(e,t,n)=>{this.outputNames.length>1&&(t=this.outputNames[e]+"_"+t),this.metricsNames.push(t),this.metricsTensors.push([n,e])};Nl("metric",(()=>{for(let e=0;e<this.outputs.length;++e){if(-1!==n.indexOf(e))continue;(t=>{let n,i,s;for(const r of t){if("string"==typeof r&&-1!==["accuracy","acc","crossentropy","ce"].indexOf(r)){const t=this.internalOutputShapes[e];let a;1===t[t.length-1]||this.lossFunctions[e]===jh?-1!==["accuracy","acc"].indexOf(r)?i=_h:-1!==["crossentropy","ce"].indexOf(r)&&(i=Lh):this.lossFunctions[e]===$h?-1!==["accuracy","acc"].indexOf(r)?i=Mh:-1!==["crossentropy","ce"].indexOf(r)&&(i=Ph):-1!==["accuracy","acc"].indexOf(r)?i=Rh:-1!==["crossentropy","ce"].indexOf(r)&&(i=Oh),-1!==["accuracy","acc"].indexOf(r)?a="acc":-1!==["crossentropy","ce"].indexOf(r)&&(a="ce"),s=i,n=""+a}else{const e=Uh(r);s=e,n=""+Wh(r)}let t;Nl(n,(()=>{t=s})),a(e,n,t)}})(i[e])}})),this.collectedTrainableWeights=this.trainableWeights}checkTrainableWeightsConsistency(){null!=this.collectedTrainableWeights&&this.trainableWeights.length!==this.collectedTrainableWeights.length&&console.warn("Discrepancy between trainableweights and collected trainable weights. Did you set `model.trainable` without calling `model.compile()` afterwards?")}evaluate(e,t,n={}){const i=null==n.batchSize?32:n.batchSize;cp(i);const a=this.standardizeUserDataXY(e,t,!0,i);try{const s=a[0].concat(a[1]);this.makeTestFunction();const r=this.testFunction;return Ho(this.testLoop(r,s,i,n.verbose,n.steps))}finally{mp(a[0],e),mp(a[1],t)}}async evaluateDataset(e,t){return this.makeTestFunction(),async function(e,t,n){const i=null!=(n=n||{}).batches,a=e.testFunction;let s=[];if(n.verbose>0)throw new Uo("Verbose mode is not implemented yet.");I(!i||n.batches>0&&Number.isInteger(n.batches),(()=>`Test loop expects \`batches\` to be a positive integer, but received ${JSON.stringify(n.batches)}`));const r="function"==typeof t.next?t:await t.iterator();let o=0,l=0;for(;!i||l<n.batches;){const t=await r.next();if(s=si((()=>{if(t.value){const{xs:n,ys:i}=sp(e,t.value),r=n.concat(i),c=si((()=>a(r)));if(ri(r),0===l)for(let e=0;e<c.length;++e)s.push(Aa(0));const u=r[0].shape[0];for(let e=0;e<c.length;++e){const t=c[e],n=s[e];s[e]=si((()=>bi(s[e],xi(u,t)))),l>0&&ri(n)}ri(c),o+=u,++l}return s})),t.done){i&&console.warn(`Your dataset iterator ran out of data during evaluateDataset(). Interrupting evalution. Make sure that your dataset can generate at least \`batches\` batches (in this case, ${n.batches} batches). You may need to use the repeat() function when building your dataset.`);break}}for(let e=0;e<s.length;++e){const t=s[e];s[e]=ki(s[e],o),ri(t)}return Ho(s)}(this,e,t)}checkNumSamples(e,t,n,i="steps"){let a;if(null!=n){if(a=null,null!=t)throw new Bo(`If ${i} is set, batchSize must be null or undefined.Got batchSize = ${t}`)}else{if(null==e)throw new Bo(`Either the input data should have a defined shape, or ${i} shoud be specified.`);a=Array.isArray(e)?e[0].shape[0]:e.shape[0]}return a}execute(e,t){if(Array.isArray(t)&&0===t.length)throw new Bo("`outputs` is an empty Array, which is not allowed.");const n=Array.isArray(t),i=n?t:[t],a=this.retrieveSymbolicTensors(i),s=new Rc;if(e instanceof Ut&&(e=[e]),Array.isArray(e)){if(e.length!==this.inputs.length)throw new Bo(`The number of inputs provided (${e.length}) does not match the number of inputs of this model (${this.inputs.length}).`);for(let t=0;t<this.inputs.length;++t)s.add(this.inputs[t],e[t])}else for(const t of this.inputs){const n=e[t.name];if(null==n)throw new Bo(`No value is provided for the model's input ${t.name}`);s.add(t,n)}const r=Oc(a,s);return n?r:r[0]}retrieveSymbolicTensors(e){const t=Vo(null,e.length);let n=e.length;for(const i of this.layers){const a=Array.isArray(i.output)?i.output:[i.output],s=a.map((e=>e.name));for(let i=0;i<e.length;++i){const r=s.indexOf(e[i]);if(-1!==r&&(t[i]=a[r],n--),0===n)break}if(0===n)break}if(n>0){const n=[];throw t.forEach(((t,i)=>{null==t&&n.push(e[i])})),new Bo(`Cannot find SymbolicTensors for output name(s): ${JSON.stringify(n)}`)}return t}predictLoop(e,t=32,n=!1){return si((()=>{const i=this.checkNumSamples(e);if(n)throw new Uo("Verbose predictLoop() is not implemented yet.");const a=pp(i,t),s=this.outputs.map((e=>[]));for(let t=0;t<a.length;++t){si((()=>{const n=a[t][0],i=a[t][1],s=up(e,n,i),r=[];if(Array.isArray(s))for(let e=0;e<s.length;++e)r.push({key:this.inputs[e],value:s[e]});else r.push({key:this.inputs[0],value:s});const o=new Rc(r);return Oc(this.outputs,o)})).forEach(((e,t)=>s[t].push(e)))}return Ho(s.map((e=>Oi(e,0))))}))}predict(e,t={}){const n=dp(e);yp(n,this.inputNames,this.feedInputShapes,!1);try{const i=null==t.batchSize?32:t.batchSize;return cp(i),this.predictLoop(n,i)}finally{mp(n,e)}}predictOnBatch(e){yp(e,this.inputNames,this.feedInputShapes,!0);const t=(Array.isArray(e)?e[0]:e).shape[0];return this.predictLoop(e,t)}standardizeUserDataXY(e,t,n=!0,i){if(null==this.optimizer_)throw new Po("You must compile a model before training/testing. Use LayersModel.compile(modelCompileArgs).");const a=[];for(let e=0;e<this.feedOutputShapes.length;++e){const t=this.feedOutputShapes[e];this.feedLossFns[e]===$h?a.push(t.slice(0,t.length-1).concat([1])):a.push(t)}if(function(e,t,n){const i=il(e.map((e=>e.shape[0])));i.sort();const a=il(t.map((e=>e.shape[0])));if(a.sort(),i.length>1)throw new Bo(`All input Tensors (x) should have the same number of samples. Got array shapes: ${JSON.stringify(e.map((e=>e.shape)))}`);if(a.length>1)throw new Bo(`All target Tensors (y) should have the same number of samples. Got array shapes: ${JSON.stringify(t.map((e=>e.shape)))}`);if(i.length>0&&a.length>0&&!C(i,a))throw new Bo(`Input Tensors should have the same number of samples as target Tensors. Found ${i[0]} input sample(s) and ${a[0]} target sample(s).`)}(e=vp(e,this.feedInputNames,this.feedInputShapes,!1,"input"),t=vp(t,this.feedOutputNames,a,!1,"target")),function(e,t,n){const i=[Th,jh,Ch];for(let a=0;a<e.length;++a){const s=e[a],r=t[a],o=n[a];if(null!=r){if(r===Ch&&1===s.shape[s.shape.length-1])throw new Bo(`You are passing a target array of shape ${s.shape} while using a loss 'categorical_crossentropy'. 'categorical_crossentropy'expects targets to be binary matrices (1s and 0s) of shape [samples, classes].`);if(-1!==i.indexOf(r)){const e=s.shape.slice(1),t=o.slice(1);for(let n=0;n<e.length;++n){const i=e[n],a=t[n];if(null!=a&&i!==a)throw new Bo(`A target Tensor with shape ${s.shape} was passed for an output of shape ${o}, while using a loss function that expects targets to have the same shape as the output.`)}}}}}(t,this.feedLossFns,this.feedOutputShapes),this.stateful&&null!=i&&i>0&&e[0].shape[0]%i!=0)throw new Bo(`In a stateful network, you should only pass inputs with a number of samples that is divisible by the batch size ${i}. Found: ${e[0].shape[0]} sample(s).`);return[e,t]}async standardizeUserData(e,t,n,i,a=!0,s){const[r,o]=this.standardizeUserDataXY(e,t,a,s);if(null!=n)throw new Error("sample weight is not supported yet.");let l=null;if(null!=i){const e=np(i,this.outputNames);l=[];for(let t=0;t<e.length;++t)l.push(await ip(o[t],null,e[t]))}return[r,o,l]}testLoop(e,t,n,i=0,a){return si((()=>{const s=this.checkNumSamples(t,n,a,"steps"),r=[];if(i>0)throw new Uo("Verbose mode is not implemented yet.");if(null!=a)throw new Uo("steps mode in testLoop() is not implemented yet");{const i=pp(s,n),a=Vs(zl(0,s));for(let n=0;n<i.length;++n){const s=i[n][0],o=i[n][1],l=Ll(a,s,o-s),c=hp(t,l),u=e(c);if(0===n)for(let e=0;e<u.length;++e)r.push(Aa(0));for(let e=0;e<u.length;++e){const t=u[e];r[e]=bi(r[e],xi(o-s,t))}}for(let e=0;e<r.length;++e)r[e]=ki(r[e],s)}return r}))}getDedupedMetricsNames(){const e=this.metricsNames,t=[];for(let n=0;n<e.length;++n){const i=e[n];let a=i;if(qo(e,i)>1){a+=`_${qo(e.slice(0,n),i)}`}t.push(a)}return t}makeTrainFunction(){return e=>{const t=[],n=e.slice(0,this.inputs.length),i=e.slice(this.inputs.length,this.inputs.length+this.outputs.length),a=e.slice(this.inputs.length+this.outputs.length,this.inputs.length+2*this.outputs.length),s=[],r=this.collectedTrainableWeights.map((e=>e.read()));return[this.optimizer_.minimize((()=>{const e=[];for(let t=0;t<this.inputs.length;++t)e.push({key:this.inputs[t],value:n[t]});const r=new Rc(e),o=Oc(this.outputs,r,{training:!0});let l;for(let e=0;e<this.lossFunctions.length;++e){let n=(0,this.lossFunctions[e])(i[e],o[e]);null!=a[e]&&(n=ap(n,a[e]));const s=ns(n);t.push(s),l=0===e?n:bi(l,n)}for(let e=0;e<this.metricsTensors.length;++e){let n;if(this.outputs.length>1&&e<this.outputs.length)n=t[e];else{const t=this.metricsTensors[e][0],a=this.metricsTensors[e][1];n=ns(t(i[a],o[a]))}oi(n),s.push(n)}return l=ns(l),this.calculateLosses().forEach((e=>{l=bi(l,e)})),l}),!0,r)].concat(s)}}makeTestFunction(){this.testFunction=e=>si((()=>{const t=[];let n;const i=e.slice(0,this.inputs.length),a=e.slice(this.inputs.length,this.inputs.length+this.outputs.length),s=[];for(let e=0;e<this.inputs.length;++e)s.push({key:this.inputs[e],value:i[e]});const r=new Rc(s),o=Oc(this.outputs,r);for(let e=0;e<this.lossFunctions.length;++e){const i=this.lossFunctions[e],s=ns(i(a[e],o[e]));n=0===e?s:bi(n,s),t.push(n)}for(let e=0;e<this.metricsTensors.length;++e){const n=this.metricsTensors[e][0],i=this.metricsTensors[e][1],s=ns(n(a[i],o[i]));t.push(s)}return t}))}async fit(e,t,n={}){if(this.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");let i,a,s,r,o,l,c,u,h;this.isTraining=!0;try{const p=null==n.batchSize?32:n.batchSize;cp(p);const d=!1,m=await this.standardizeUserData(e,t,n.sampleWeight,n.classWeight,d,p);i=m[0],a=m[1],h=m[2];let f,g=!1;if(null!=n.validationData&&n.validationData.length>0){if(g=!0,2!==n.validationData.length)throw 3===n.validationData.length?new Uo("validationData including sample weights is not supported yet."):new Bo(`When passing validation data, it must contain 2 (valX, valY) or 3 (valX, valY, valSampleWeight) items; ${n.validationData} is invalid.`);o=n.validationData[0],l=n.validationData[1];const e=!0,t=await this.standardizeUserData(o,l,null,null,e,p);c=t[0],u=t[1],f=c.concat(u)}else if(null!=n.validationSplit&&n.validationSplit>0&&n.validationSplit<1){g=!0;const e=Math.floor(i[0].shape[0]*(1-n.validationSplit)),t=i[0].shape[0];c=up(i,e,t),s=i,i=up(i,0,e),u=up(a,e,t),r=a,a=up(a,0,e),f=c.concat(u)}else null!=n.validationSteps&&(g=!0);const v=i.concat(a).concat(h);this.checkTrainableWeightsConsistency();const y=this.makeTrainFunction(),b=this.getDedupedMetricsNames();let w,k;g?(this.makeTestFunction(),w=this.testFunction,k=b.slice().concat(b.map((e=>"val_"+e)))):(w=null,f=[],k=b.slice());const x=kh(n.callbacks,n.yieldEvery);return await this.fitLoop(y,v,b,p,n.epochs,n.verbose,x,w,f,n.shuffle,k,n.initialEpoch,null,null)}finally{this.isTraining=!1,mp(i,e),mp(a,t),mp(s,e),mp(r,t),mp(c,o),mp(u,l),null!=h&&ri(h)}}async fitLoop(e,t,n,i,a,s,r,o,l,c,u,h,p,d){null==i&&(i=32),null==a&&(a=1),null==c&&(c=!0),null==h&&(h=0);let m=!1;if(null!=o&&null!=l&&(m=!0),null!=d&&(m=!0,null==p))throw new Bo("Can only use `validationSteps` when doing step-wise training, i.e., `stepsPerEpoch` must be set.");const f=this.checkNumSamples(t,i,p,"steps_per_epoch");let g;null!=f&&(g=zl(0,f)),null==s&&(s=1);const{callbackList:v,history:y}=Sh(r,s,a,h,f,p,i,m,u);v.setModel(this),this.history=y,await v.onTrainBegin(),this.stopTraining_=!1;for(let s=h;s<a;++s){await v.onEpochBegin(s);const a={};if(null!=p)throw new Uo("stepsPerEpoch mode is not implemented yet.");{if("batch"===c)throw new Uo("batch shuffling is not implemneted yet");c&&S(g);const s=Vs(g),r=pp(f,i);for(let c=0;c<r.length;++c){const u={};if(await v.onBatchBegin(c,u),si((()=>{const h=r[c][0],p=r[c][1],d=Ll(s,h,p-h);u.batch=c,u.size=p-h;const f=hp(t,d),g=e(f);for(let e=0;e<n.length;++e){const t=n[e],i=g[e];u[t]=i,oi(i)}if(c===r.length-1&&m){const e=this.testLoop(o,l,i);for(let t=0;t<n.length;++t){const i=n[t],s=e[t];oi(s),a["val_"+i]=s}}})),await v.onBatchEnd(c,u),mh(u),this.stopTraining_)break}s.dispose()}if(await v.onEpochEnd(s,a),this.stopTraining_)break}return await v.onTrainEnd(),await this.history.syncData(),this.history}async fitDataset(e,t){return op(this,e,t)}async trainOnBatch(e,t){const n=await this.standardizeUserData(e,t),i=n[0],a=n[1],s=this.makeTrainFunction()(i.concat(a)),r=[];for(const e of s){const t=await e.data();r.push(t[0])}return ri(s),mp(n[0],e),mp(n[1],t),Ho(r)}getNamedWeights(e){const t=[],n=null!=e&&e.trainableOnly,i=n?this.trainableWeights:this.weights,a=this.getWeights(n);for(let e=0;e<i.length;++e)n&&!i[e].trainable||t.push({name:i[e].originalName,tensor:a[e]});return t}set stopTraining(e){this.stopTraining_=e}get stopTraining(){return this.stopTraining_}get optimizer(){return this.optimizer_}set optimizer(e){this.optimizer_!==e&&(this.optimizer_=e,this.isOptimizerOwned=!1)}dispose(){const e=super.dispose();if(0===e.refCountAfterDispose&&null!=this.optimizer&&this.isOptimizerOwned){const t=ai().numTensors;this.optimizer_.dispose(),e.numDisposedVariables+=t-ai().numTensors}return e}getLossIdentifiers(){let e;if("string"==typeof this.loss)e=Zo(this.loss);else if(Array.isArray(this.loss)){for(const e of this.loss)if("string"!=typeof e)throw new Error("Serialization of non-string loss is not supported.");e=this.loss.map((e=>Zo(e)))}else{const t=Object.keys(this.loss);e={};const n=this.loss;for(const i of t){if("string"!=typeof n[i])throw new Error("Serialization of non-string loss is not supported.");e[i]=Zo(n[i])}}return e}getMetricIdentifiers(){if("string"==typeof this.metrics||"function"==typeof this.metrics)return[Zo(Wh(this.metrics))];if(Array.isArray(this.metrics))return this.metrics.map((e=>Zo(Wh(e))));{const e={};for(const t in this.metrics)e[t]=Zo(Wh(this.metrics[t]));return e}}getTrainingConfig(){return{loss:this.getLossIdentifiers(),metrics:this.getMetricIdentifiers(),optimizer_config:{class_name:this.optimizer.getClassName(),config:this.optimizer.getConfig()}}}loadTrainingConfig(e){if(null!=e.weighted_metrics)throw new Error("Loading weight_metrics is not supported yet.");if(null!=e.loss_weights)throw new Error("Loading loss_weights is not supported yet.");if(null!=e.sample_weight_mode)throw new Error("Loading sample_weight_mode is not supported yet.");const t=Nh(Qh(e.optimizer_config));let n,i;if("string"==typeof e.loss)n=Yo(e.loss);else if(Array.isArray(e.loss))n=e.loss.map((e=>Yo(e)));else if(null!=e.loss){n={};for(const t in e.loss)n[t]=Yo(e.loss[t])}if(Array.isArray(e.metrics))i=e.metrics.map((e=>Yo(e)));else if(null!=e.metrics){i={};for(const t in e.metrics)i[t]=Yo(e.metrics[t])}this.compile({loss:n,metrics:i,optimizer:t})}async save(e,t){if("string"==typeof e){const t=(n=e,Tn.getSaveHandlers(n));if(0===t.length)throw new Bo(`Cannot find any save handlers for URL '${e}'`);if(t.length>1)throw new Bo(`Found more than one (${t.length}) save handlers for URL '${e}'`);e=t[0]}var n;if(null==e.save)throw new Bo("LayersModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");const i=await yn(this.getNamedWeights(t)),a={modelTopology:this.toJSON(null,!1),format:"layers-model",generatedBy:`TensorFlow.js tfjs-layers v${ep}`,convertedBy:null};if(null!=t&&t.includeOptimizer&&null!=this.optimizer){a.trainingConfig=this.getTrainingConfig();const e="optimizer",{data:t,specs:n}=await yn(await this.optimizer.getWeights(),e);i.specs.push(...n),i.data=xn([i.data,t])}if(null!=this.userDefinedMetadata){const e=!0;Vh(this.userDefinedMetadata,this.name,e),a.userDefinedMetadata=this.userDefinedMetadata}return a.weightData=i.data,a.weightSpecs=i.specs,e.save(a)}setUserDefinedMetadata(e){Vh(e,this.name),this.userDefinedMetadata=e}getUserDefinedMetadata(){return this.userDefinedMetadata}}bp.className="Model",yi(bp);class wp extends bp{}
4405
+ */function fp(e){return Array.isArray(e)}function gp(e){return!function(e){return e instanceof Ut}(e)&&!fp(e)}function vp(e,t,n,i=!0,a=""){if(null==t||0===t.length){if(null!=e){let t=!1;if(fp(e)&&e.length>0)t=!0;else if(gp(e)){for(const n in e)if(e.hasOwnProperty(n)){t=!0;break}}else t=!0;if(t)throw new Bo(`Error when checking model ${a} expected no data, but got ${e}`)}return[]}if(null==e)return t.map((e=>null));let s;if(gp(e)){s=[];for(const n of t){if(null==e[n])throw new Bo(`No data provided for "${n}". Need data for each key in: ${t}`);s.push(e[n])}}else if(fp(e)){if(e.length!==t.length)throw new Bo(`Error when checking model ${a}: the Array of Tensors that you are passing to your model is not the size the model expected. Expected to see ${t.length} Tensor(s), but instead got the following list of Tensor(s): ${e}`);s=e}else{if(t.length>1)throw new Bo(`The model ${a} expects ${t.length} Tensor(s), but only received one Tensor. Found: Tensor with shape ${e.shape}`);s=[e]}if(s=dp(s),null!=n)for(let e=0;e<t.length;++e){if(null==n[e])continue;const r=s[e];if(r.shape.length!==n[e].length)throw new Bo(`Error when checking ${a}: expected ${t[e]} to have ${n[e].length} dimension(s). but got array with shape ${r.shape}`);for(let t=0;t<n[e].length;++t){if(0===t&&!i)continue;const s=r.shape[t],o=n[e][t];if(null!=o&&o>=0&&s!==o)throw new Bo(`${a} expected a batch of elements where each example has shape [${n[e].slice(1,n[e].length)}] (i.e.,tensor shape [*,${n[e].slice(1,n[e].length)}]) but the ${a} received an input with ${r.shape[0]} examples, each with shape [${r.shape.slice(1,r.shape.length)}] (tensor shape [${r.shape}])`)}}return s}function yp(e,t,n,i=!0,a=""){let s;if(Array.isArray(e)){if(e.length!==t.length)throw new Bo(`Error when checking model ${a}: the Array of Tensors that you are passing to your model is not the size the the model expected. Expected to see ${t.length} Tensor(s), but instead got ${e.length} Tensors(s).`);s=e}else{if(t.length>1)throw new Bo(`The model expects ${t.length} ${a} Tensors, but only received one Tensor. Found: array with shape ${JSON.stringify(e.shape)}.`);s=[e]}if(null!=n)for(let e=0;e<t.length;++e){if(null==n[e])continue;const r=s[e];if(r.shape.length!==n[e].length)throw new Bo(`Error when checking ${a}: expected ${t[e]} to have ${n[e].length} dimension(s), but got array with shape ${JSON.stringify(r.shape)}`);for(let s=0;s<n[e].length;++s){if(0===s&&!i)continue;const o=r.shape[s],l=n[e][s];if(null!=l&&l!==o)throw new Bo(`Error when checking ${a}: expected ${t[e]} to have shape ${JSON.stringify(n[e])} but got array with shape ${JSON.stringify(r.shape)}.`)}}}class bp extends tp{constructor(e){super(e),this.isTraining=!1}summary(e,t,n=console.log){if(!this.built)throw new Bo("This model has never been called, thus its weights have not been created yet. So no summary can be displayed. Build the model first (e.g., by calling it on some test data).");qh(this,e,t,n)}compile(e){if(null==e.loss&&(e.loss=[]),this.loss=e.loss,"string"==typeof e.optimizer)this.optimizer_=function(e){const t={Adagrad:()=>Ur.adagrad(.01),Adadelta:()=>Ur.adadelta(1,.95,Fl()),Adam:()=>Ur.adam(.001,.9,.999,Fl()),Adamax:()=>Ur.adamax(.002,.9,.999,Fl(),0),RMSProp:()=>Ur.rmsprop(.001,.9,0,Fl()),SGD:()=>Ur.sgd(.01)};if(t.adagrad=t.Adagrad,t.adadelta=t.Adadelta,t.adam=t.Adam,t.adamax=t.Adamax,t.rmsprop=t.RMSProp,t.sgd=t.SGD,e in t)return t[e]();throw new Bo(`Unknown Optimizer ${e}`)}(e.optimizer),this.isOptimizerOwned=!0;else{if(!(e.optimizer instanceof Fr))throw new Bo("User-defined optimizer must be an instance of tf.Optimizer.");this.optimizer_=e.optimizer,this.isOptimizerOwned=!1}let t=[];if(Array.isArray(e.loss)||"string"==typeof e.loss||"function"==typeof e.loss)if(Array.isArray(e.loss)){if(e.loss.length!==this.outputs.length)throw new Bo(`When passing an Array as loss, it should have one entry per model output. The model has ${this.outputs.length} output(s), but you passed loss=${e.loss}.`);const n=e.loss;t=n.map((e=>Fh(e)))}else{const n=Fh(e.loss);this.outputs.forEach((e=>{t.push(n)}))}else{e.loss=e.loss;for(const t in e.loss)if(-1===this.outputNames.indexOf(t))throw new Bo(`Unknown entry in loss dictionary: "${t}". Only expected the following keys: ${this.outputNames}`);for(const n of this.outputNames)null==e.loss[n]&&console.warn(`Output "${n}" is missing from loss dictionary. We assume this was done on purpose, and we will not be expecting data to be passed to ${n} during training`),t.push(Fh(e.loss[n]))}this.lossFunctions=t,this.feedOutputNames=[],this.feedOutputShapes=[],this.feedLossFns=[];for(let e=0;e<this.outputs.length;++e){const t=this.internalOutputShapes[e],n=this.outputNames[e];this.feedOutputNames.push(n),this.feedOutputShapes.push(t),this.feedLossFns.push(this.lossFunctions[e])}const n=[];this.metrics=e.metrics,this.metricsNames=["loss"],this.metricsTensors=[],Nl("loss",(()=>{for(let e=0;e<this.outputs.length;++e){if(-1!==n.indexOf(e))continue;const t=this.lossFunctions[e];this.outputs.length>1&&(this.metricsTensors.push([t,e]),this.metricsNames.push(this.outputNames[e]+"_loss"))}}));const i=function(e,t){if(null==e||Array.isArray(e)&&0===e.length)return t.map((e=>[]));let n;if("string"==typeof e||"function"==typeof e)n=[e];else{if(!Array.isArray(e)&&"object"!=typeof e)throw new TypeError(`Type of metrics argument not understood. Expected an string,function, Array, or Object, found: ${e}`);n=e}if(Array.isArray(n))return t.map((e=>n));{const e=[];for(const i of t){let t=n.hasOwnProperty(i)?n[i]:[];Array.isArray(t)||(t=[t]),e.push(t)}return e}}(e.metrics,this.outputNames),a=(e,t,n)=>{this.outputNames.length>1&&(t=this.outputNames[e]+"_"+t),this.metricsNames.push(t),this.metricsTensors.push([n,e])};Nl("metric",(()=>{for(let e=0;e<this.outputs.length;++e){if(-1!==n.indexOf(e))continue;(t=>{let n,i,s;for(const r of t){if("string"==typeof r&&-1!==["accuracy","acc","crossentropy","ce"].indexOf(r)){const t=this.internalOutputShapes[e];let a;1===t[t.length-1]||this.lossFunctions[e]===jh?-1!==["accuracy","acc"].indexOf(r)?i=_h:-1!==["crossentropy","ce"].indexOf(r)&&(i=Lh):this.lossFunctions[e]===$h?-1!==["accuracy","acc"].indexOf(r)?i=Mh:-1!==["crossentropy","ce"].indexOf(r)&&(i=Ph):-1!==["accuracy","acc"].indexOf(r)?i=Rh:-1!==["crossentropy","ce"].indexOf(r)&&(i=Oh),-1!==["accuracy","acc"].indexOf(r)?a="acc":-1!==["crossentropy","ce"].indexOf(r)&&(a="ce"),s=i,n=""+a}else{const e=Uh(r);s=e,n=""+Wh(r)}let t;Nl(n,(()=>{t=s})),a(e,n,t)}})(i[e])}})),this.collectedTrainableWeights=this.trainableWeights}checkTrainableWeightsConsistency(){null!=this.collectedTrainableWeights&&this.trainableWeights.length!==this.collectedTrainableWeights.length&&console.warn("Discrepancy between trainableweights and collected trainable weights. Did you set `model.trainable` without calling `model.compile()` afterwards?")}evaluate(e,t,n={}){const i=null==n.batchSize?32:n.batchSize;cp(i);const a=this.standardizeUserDataXY(e,t,!0,i);try{const s=a[0].concat(a[1]);this.makeTestFunction();const r=this.testFunction;return Ho(this.testLoop(r,s,i,n.verbose,n.steps))}finally{mp(a[0],e),mp(a[1],t)}}async evaluateDataset(e,t){return this.makeTestFunction(),async function(e,t,n){const i=null!=(n=n||{}).batches,a=e.testFunction;let s=[];if(n.verbose>0)throw new Uo("Verbose mode is not implemented yet.");T(!i||n.batches>0&&Number.isInteger(n.batches),(()=>`Test loop expects \`batches\` to be a positive integer, but received ${JSON.stringify(n.batches)}`));const r="function"==typeof t.next?t:await t.iterator();let o=0,l=0;for(;!i||l<n.batches;){const t=await r.next();if(s=si((()=>{if(t.value){const{xs:n,ys:i}=sp(e,t.value),r=n.concat(i),c=si((()=>a(r)));if(ri(r),0===l)for(let e=0;e<c.length;++e)s.push(Ca(0));const u=r[0].shape[0];for(let e=0;e<c.length;++e){const t=c[e],n=s[e];s[e]=si((()=>bi(s[e],xi(u,t)))),l>0&&ri(n)}ri(c),o+=u,++l}return s})),t.done){i&&console.warn(`Your dataset iterator ran out of data during evaluateDataset(). Interrupting evalution. Make sure that your dataset can generate at least \`batches\` batches (in this case, ${n.batches} batches). You may need to use the repeat() function when building your dataset.`);break}}for(let e=0;e<s.length;++e){const t=s[e];s[e]=ki(s[e],o),ri(t)}return Ho(s)}(this,e,t)}checkNumSamples(e,t,n,i="steps"){let a;if(null!=n){if(a=null,null!=t)throw new Bo(`If ${i} is set, batchSize must be null or undefined.Got batchSize = ${t}`)}else{if(null==e)throw new Bo(`Either the input data should have a defined shape, or ${i} shoud be specified.`);a=Array.isArray(e)?e[0].shape[0]:e.shape[0]}return a}execute(e,t){if(Array.isArray(t)&&0===t.length)throw new Bo("`outputs` is an empty Array, which is not allowed.");const n=Array.isArray(t),i=n?t:[t],a=this.retrieveSymbolicTensors(i),s=new Rc;if(e instanceof Ut&&(e=[e]),Array.isArray(e)){if(e.length!==this.inputs.length)throw new Bo(`The number of inputs provided (${e.length}) does not match the number of inputs of this model (${this.inputs.length}).`);for(let t=0;t<this.inputs.length;++t)s.add(this.inputs[t],e[t])}else for(const t of this.inputs){const n=e[t.name];if(null==n)throw new Bo(`No value is provided for the model's input ${t.name}`);s.add(t,n)}const r=Oc(a,s);return n?r:r[0]}retrieveSymbolicTensors(e){const t=Go(null,e.length);let n=e.length;for(const i of this.layers){const a=Array.isArray(i.output)?i.output:[i.output],s=a.map((e=>e.name));for(let i=0;i<e.length;++i){const r=s.indexOf(e[i]);if(-1!==r&&(t[i]=a[r],n--),0===n)break}if(0===n)break}if(n>0){const n=[];throw t.forEach(((t,i)=>{null==t&&n.push(e[i])})),new Bo(`Cannot find SymbolicTensors for output name(s): ${JSON.stringify(n)}`)}return t}predictLoop(e,t=32,n=!1){return si((()=>{const i=this.checkNumSamples(e);if(n)throw new Uo("Verbose predictLoop() is not implemented yet.");const a=pp(i,t),s=this.outputs.map((e=>[]));for(let t=0;t<a.length;++t){si((()=>{const n=a[t][0],i=a[t][1],s=up(e,n,i),r=[];if(Array.isArray(s))for(let e=0;e<s.length;++e)r.push({key:this.inputs[e],value:s[e]});else r.push({key:this.inputs[0],value:s});const o=new Rc(r);return Oc(this.outputs,o)})).forEach(((e,t)=>s[t].push(e)))}return Ho(s.map((e=>Oi(e,0))))}))}predict(e,t={}){const n=dp(e);yp(n,this.inputNames,this.feedInputShapes,!1);try{const i=null==t.batchSize?32:t.batchSize;return cp(i),this.predictLoop(n,i)}finally{mp(n,e)}}predictOnBatch(e){yp(e,this.inputNames,this.feedInputShapes,!0);const t=(Array.isArray(e)?e[0]:e).shape[0];return this.predictLoop(e,t)}standardizeUserDataXY(e,t,n=!0,i){if(null==this.optimizer_)throw new Po("You must compile a model before training/testing. Use LayersModel.compile(modelCompileArgs).");const a=[];for(let e=0;e<this.feedOutputShapes.length;++e){const t=this.feedOutputShapes[e];this.feedLossFns[e]===$h?a.push(t.slice(0,t.length-1).concat([1])):a.push(t)}if(function(e,t,n){const i=il(e.map((e=>e.shape[0])));i.sort();const a=il(t.map((e=>e.shape[0])));if(a.sort(),i.length>1)throw new Bo(`All input Tensors (x) should have the same number of samples. Got array shapes: ${JSON.stringify(e.map((e=>e.shape)))}`);if(a.length>1)throw new Bo(`All target Tensors (y) should have the same number of samples. Got array shapes: ${JSON.stringify(t.map((e=>e.shape)))}`);if(i.length>0&&a.length>0&&!E(i,a))throw new Bo(`Input Tensors should have the same number of samples as target Tensors. Found ${i[0]} input sample(s) and ${a[0]} target sample(s).`)}(e=vp(e,this.feedInputNames,this.feedInputShapes,!1,"input"),t=vp(t,this.feedOutputNames,a,!1,"target")),function(e,t,n){const i=[Ih,jh,Eh];for(let a=0;a<e.length;++a){const s=e[a],r=t[a],o=n[a];if(null!=r){if(r===Eh&&1===s.shape[s.shape.length-1])throw new Bo(`You are passing a target array of shape ${s.shape} while using a loss 'categorical_crossentropy'. 'categorical_crossentropy'expects targets to be binary matrices (1s and 0s) of shape [samples, classes].`);if(-1!==i.indexOf(r)){const e=s.shape.slice(1),t=o.slice(1);for(let n=0;n<e.length;++n){const i=e[n],a=t[n];if(null!=a&&i!==a)throw new Bo(`A target Tensor with shape ${s.shape} was passed for an output of shape ${o}, while using a loss function that expects targets to have the same shape as the output.`)}}}}}(t,this.feedLossFns,this.feedOutputShapes),this.stateful&&null!=i&&i>0&&e[0].shape[0]%i!=0)throw new Bo(`In a stateful network, you should only pass inputs with a number of samples that is divisible by the batch size ${i}. Found: ${e[0].shape[0]} sample(s).`);return[e,t]}async standardizeUserData(e,t,n,i,a=!0,s){const[r,o]=this.standardizeUserDataXY(e,t,a,s);if(null!=n)throw new Error("sample weight is not supported yet.");let l=null;if(null!=i){const e=np(i,this.outputNames);l=[];for(let t=0;t<e.length;++t)l.push(await ip(o[t],null,e[t]))}return[r,o,l]}testLoop(e,t,n,i=0,a){return si((()=>{const s=this.checkNumSamples(t,n,a,"steps"),r=[];if(i>0)throw new Uo("Verbose mode is not implemented yet.");if(null!=a)throw new Uo("steps mode in testLoop() is not implemented yet");{const i=pp(s,n),a=Gs(zl(0,s));for(let n=0;n<i.length;++n){const s=i[n][0],o=i[n][1],l=Ll(a,s,o-s),c=hp(t,l),u=e(c);if(0===n)for(let e=0;e<u.length;++e)r.push(Ca(0));for(let e=0;e<u.length;++e){const t=u[e];r[e]=bi(r[e],xi(o-s,t))}}for(let e=0;e<r.length;++e)r[e]=ki(r[e],s)}return r}))}getDedupedMetricsNames(){const e=this.metricsNames,t=[];for(let n=0;n<e.length;++n){const i=e[n];let a=i;if(qo(e,i)>1){a+=`_${qo(e.slice(0,n),i)}`}t.push(a)}return t}makeTrainFunction(){return e=>{const t=[],n=e.slice(0,this.inputs.length),i=e.slice(this.inputs.length,this.inputs.length+this.outputs.length),a=e.slice(this.inputs.length+this.outputs.length,this.inputs.length+2*this.outputs.length),s=[],r=this.collectedTrainableWeights.map((e=>e.read()));return[this.optimizer_.minimize((()=>{const e=[];for(let t=0;t<this.inputs.length;++t)e.push({key:this.inputs[t],value:n[t]});const r=new Rc(e),o=Oc(this.outputs,r,{training:!0});let l;for(let e=0;e<this.lossFunctions.length;++e){let n=(0,this.lossFunctions[e])(i[e],o[e]);null!=a[e]&&(n=ap(n,a[e]));const s=ns(n);t.push(s),l=0===e?n:bi(l,n)}for(let e=0;e<this.metricsTensors.length;++e){let n;if(this.outputs.length>1&&e<this.outputs.length)n=t[e];else{const t=this.metricsTensors[e][0],a=this.metricsTensors[e][1];n=ns(t(i[a],o[a]))}oi(n),s.push(n)}return l=ns(l),this.calculateLosses().forEach((e=>{l=bi(l,e)})),l}),!0,r)].concat(s)}}makeTestFunction(){this.testFunction=e=>si((()=>{const t=[];let n;const i=e.slice(0,this.inputs.length),a=e.slice(this.inputs.length,this.inputs.length+this.outputs.length),s=[];for(let e=0;e<this.inputs.length;++e)s.push({key:this.inputs[e],value:i[e]});const r=new Rc(s),o=Oc(this.outputs,r);for(let e=0;e<this.lossFunctions.length;++e){const i=this.lossFunctions[e],s=ns(i(a[e],o[e]));n=0===e?s:bi(n,s),t.push(n)}for(let e=0;e<this.metricsTensors.length;++e){const n=this.metricsTensors[e][0],i=this.metricsTensors[e][1],s=ns(n(a[i],o[i]));t.push(s)}return t}))}async fit(e,t,n={}){if(this.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");let i,a,s,r,o,l,c,u,h;this.isTraining=!0;try{const p=null==n.batchSize?32:n.batchSize;cp(p);const d=!1,m=await this.standardizeUserData(e,t,n.sampleWeight,n.classWeight,d,p);i=m[0],a=m[1],h=m[2];let f,g=!1;if(null!=n.validationData&&n.validationData.length>0){if(g=!0,2!==n.validationData.length)throw 3===n.validationData.length?new Uo("validationData including sample weights is not supported yet."):new Bo(`When passing validation data, it must contain 2 (valX, valY) or 3 (valX, valY, valSampleWeight) items; ${n.validationData} is invalid.`);o=n.validationData[0],l=n.validationData[1];const e=!0,t=await this.standardizeUserData(o,l,null,null,e,p);c=t[0],u=t[1],f=c.concat(u)}else if(null!=n.validationSplit&&n.validationSplit>0&&n.validationSplit<1){g=!0;const e=Math.floor(i[0].shape[0]*(1-n.validationSplit)),t=i[0].shape[0];c=up(i,e,t),s=i,i=up(i,0,e),u=up(a,e,t),r=a,a=up(a,0,e),f=c.concat(u)}else null!=n.validationSteps&&(g=!0);const v=i.concat(a).concat(h);this.checkTrainableWeightsConsistency();const y=this.makeTrainFunction(),b=this.getDedupedMetricsNames();let w,k;g?(this.makeTestFunction(),w=this.testFunction,k=b.slice().concat(b.map((e=>"val_"+e)))):(w=null,f=[],k=b.slice());const x=kh(n.callbacks,n.yieldEvery);return await this.fitLoop(y,v,b,p,n.epochs,n.verbose,x,w,f,n.shuffle,k,n.initialEpoch,null,null)}finally{this.isTraining=!1,mp(i,e),mp(a,t),mp(s,e),mp(r,t),mp(c,o),mp(u,l),null!=h&&ri(h)}}async fitLoop(e,t,n,i,a,s,r,o,l,c,u,h,p,d){null==i&&(i=32),null==a&&(a=1),null==c&&(c=!0),null==h&&(h=0);let m=!1;if(null!=o&&null!=l&&(m=!0),null!=d&&(m=!0,null==p))throw new Bo("Can only use `validationSteps` when doing step-wise training, i.e., `stepsPerEpoch` must be set.");const f=this.checkNumSamples(t,i,p,"steps_per_epoch");let g;null!=f&&(g=zl(0,f)),null==s&&(s=1);const{callbackList:v,history:y}=Sh(r,s,a,h,f,p,i,m,u);v.setModel(this),this.history=y,await v.onTrainBegin(),this.stopTraining_=!1;for(let s=h;s<a;++s){await v.onEpochBegin(s);const a={};if(null!=p)throw new Uo("stepsPerEpoch mode is not implemented yet.");{if("batch"===c)throw new Uo("batch shuffling is not implemneted yet");c&&S(g);const s=Gs(g),r=pp(f,i);for(let c=0;c<r.length;++c){const u={};if(await v.onBatchBegin(c,u),si((()=>{const h=r[c][0],p=r[c][1],d=Ll(s,h,p-h);u.batch=c,u.size=p-h;const f=hp(t,d),g=e(f);for(let e=0;e<n.length;++e){const t=n[e],i=g[e];u[t]=i,oi(i)}if(c===r.length-1&&m){const e=this.testLoop(o,l,i);for(let t=0;t<n.length;++t){const i=n[t],s=e[t];oi(s),a["val_"+i]=s}}})),await v.onBatchEnd(c,u),mh(u),this.stopTraining_)break}s.dispose()}if(await v.onEpochEnd(s,a),this.stopTraining_)break}return await v.onTrainEnd(),await this.history.syncData(),this.history}async fitDataset(e,t){return op(this,e,t)}async trainOnBatch(e,t){const n=await this.standardizeUserData(e,t),i=n[0],a=n[1],s=this.makeTrainFunction()(i.concat(a)),r=[];for(const e of s){const t=await e.data();r.push(t[0])}return ri(s),mp(n[0],e),mp(n[1],t),Ho(r)}getNamedWeights(e){const t=[],n=null!=e&&e.trainableOnly,i=n?this.trainableWeights:this.weights,a=this.getWeights(n);for(let e=0;e<i.length;++e)n&&!i[e].trainable||t.push({name:i[e].originalName,tensor:a[e]});return t}set stopTraining(e){this.stopTraining_=e}get stopTraining(){return this.stopTraining_}get optimizer(){return this.optimizer_}set optimizer(e){this.optimizer_!==e&&(this.optimizer_=e,this.isOptimizerOwned=!1)}dispose(){const e=super.dispose();if(0===e.refCountAfterDispose&&null!=this.optimizer&&this.isOptimizerOwned){const t=ai().numTensors;this.optimizer_.dispose(),e.numDisposedVariables+=t-ai().numTensors}return e}getLossIdentifiers(){let e;if("string"==typeof this.loss)e=Zo(this.loss);else if(Array.isArray(this.loss)){for(const e of this.loss)if("string"!=typeof e)throw new Error("Serialization of non-string loss is not supported.");e=this.loss.map((e=>Zo(e)))}else{const t=Object.keys(this.loss);e={};const n=this.loss;for(const i of t){if("string"!=typeof n[i])throw new Error("Serialization of non-string loss is not supported.");e[i]=Zo(n[i])}}return e}getMetricIdentifiers(){if("string"==typeof this.metrics||"function"==typeof this.metrics)return[Zo(Wh(this.metrics))];if(Array.isArray(this.metrics))return this.metrics.map((e=>Zo(Wh(e))));{const e={};for(const t in this.metrics)e[t]=Zo(Wh(this.metrics[t]));return e}}getTrainingConfig(){return{loss:this.getLossIdentifiers(),metrics:this.getMetricIdentifiers(),optimizer_config:{class_name:this.optimizer.getClassName(),config:this.optimizer.getConfig()}}}loadTrainingConfig(e){if(null!=e.weighted_metrics)throw new Error("Loading weight_metrics is not supported yet.");if(null!=e.loss_weights)throw new Error("Loading loss_weights is not supported yet.");if(null!=e.sample_weight_mode)throw new Error("Loading sample_weight_mode is not supported yet.");const t=Nh(Qh(e.optimizer_config));let n,i;if("string"==typeof e.loss)n=Yo(e.loss);else if(Array.isArray(e.loss))n=e.loss.map((e=>Yo(e)));else if(null!=e.loss){n={};for(const t in e.loss)n[t]=Yo(e.loss[t])}if(Array.isArray(e.metrics))i=e.metrics.map((e=>Yo(e)));else if(null!=e.metrics){i={};for(const t in e.metrics)i[t]=Yo(e.metrics[t])}this.compile({loss:n,metrics:i,optimizer:t})}async save(e,t){if("string"==typeof e){const t=(n=e,In.getSaveHandlers(n));if(0===t.length)throw new Bo(`Cannot find any save handlers for URL '${e}'`);if(t.length>1)throw new Bo(`Found more than one (${t.length}) save handlers for URL '${e}'`);e=t[0]}var n;if(null==e.save)throw new Bo("LayersModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");const i=await yn(this.getNamedWeights(t)),a={modelTopology:this.toJSON(null,!1),format:"layers-model",generatedBy:`TensorFlow.js tfjs-layers v${ep}`,convertedBy:null};if(null!=t&&t.includeOptimizer&&null!=this.optimizer){a.trainingConfig=this.getTrainingConfig();const e="optimizer",{data:t,specs:n}=await yn(await this.optimizer.getWeights(),e);i.specs.push(...n),i.data=xn([i.data,t])}if(null!=this.userDefinedMetadata){const e=!0;Gh(this.userDefinedMetadata,this.name,e),a.userDefinedMetadata=this.userDefinedMetadata}return a.weightData=i.data,a.weightSpecs=i.specs,e.save(a)}setUserDefinedMetadata(e){Gh(e,this.name),this.userDefinedMetadata=e}getUserDefinedMetadata(){return this.userDefinedMetadata}}bp.className="Model",yi(bp);class wp extends bp{}
4406
4406
  /**
4407
4407
  * @license
4408
4408
  * Copyright 2018 Google LLC
@@ -4412,7 +4412,7 @@ function cp(e){I(e>0&&Number.isInteger(e),(()=>`batchSize is required to be a po
4412
4412
  * https://opensource.org/licenses/MIT.
4413
4413
  * =============================================================================
4414
4414
  */
4415
- async function kp(e,t){if(null==t&&(t={}),"string"==typeof e){const a=(n=e,i=t,Tn.getLoadHandlers(n,i));if(0===a.length)a.push(function(e,t){return Qn(e,t)}
4415
+ async function kp(e,t){if(null==t&&(t={}),"string"==typeof e){const a=(n=e,i=t,In.getLoadHandlers(n,i));if(0===a.length)a.push(function(e,t){return Qn(e,t)}
4416
4416
  /**
4417
4417
  * @license
4418
4418
  * Copyright 2018 Google LLC. All Rights Reserved.
@@ -4444,7 +4444,7 @@ async function kp(e,t){if(null==t&&(t={}),"string"==typeof e){const a=(n=e,i=t,T
4444
4444
  * See the License for the specific language governing permissions and
4445
4445
  * limitations under the License.
4446
4446
  * =============================================================================
4447
- */return async function(e,t,n){null==n&&(n={});if(null==e.load)throw new Bo("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");const i=await e.load();let a=i.modelTopology;null!=a.model_config&&(a=a.model_config);const s=null==n.strict||n.strict,r=null!=i.weightData&&null!=i.weightSpecs&&s,o=Nh(Qh(a),t,r),l=i.trainingConfig;null!=l&&o.loadTrainingConfig(l);null!=i.userDefinedMetadata&&o.setUserDefinedMetadata(i.userDefinedMetadata);if(null!=i.weightData){if(null==i.weightSpecs)throw new Bo("LayersModel artifacts contains weight data, but not weight specs. Therefore loading of weights cannot proceed.");const{modelWeights:e,optimizerWeights:t}=function(e,t){const n=function(e,t){const n={};let i,a=0;for(const s of t){const t=s.name,r=s.dtype,o=s.shape,l=A(o);let c;if("quantization"in s){const n=s.quantization;if("uint8"===n.dtype||"uint16"===n.dtype){if(!("min"in n)||!("scale"in n))throw new Error(`Weight ${s.name} with quantization ${n.dtype} doesn't have corresponding metadata min and scale.`)}else{if("float16"!==n.dtype)throw new Error(`Weight ${s.name} has unknown quantization dtype ${n.dtype}. Supported quantization dtypes are: 'uint8', 'uint16', and 'float16'.`);if("float32"!==r)throw new Error(`Weight ${s.name} is quantized with ${n.dtype} which only supports weights of type float32 not ${r}.`)}const o=vn[n.dtype],u=e.slice(a,a+l*o),h="uint8"===n.dtype?new Uint8Array(u):new Uint16Array(u);if("float32"===r)if("uint8"===n.dtype||"uint16"===n.dtype){c=new Float32Array(h.length);for(let e=0;e<h.length;e++){const t=h[e];c[e]=t*n.scale+n.min}}else{if("float16"!==n.dtype)throw new Error(`Unsupported quantization type ${n.dtype} for weight type float32.`);void 0===i&&(i=In()),c=i(h)}else{if("int32"!==r)throw new Error(`Unsupported dtype in weight '${t}': ${r}`);if("uint8"!==n.dtype&&"uint16"!==n.dtype)throw new Error(`Unsupported quantization type ${n.dtype} for weight type int32.`);c=new Int32Array(h.length);for(let e=0;e<h.length;e++){const t=h[e];c[e]=Math.round(t*n.scale+n.min)}}a+=l*o}else if("string"===r){const t=A(s.shape);c=[];for(let n=0;n<t;n++){const t=new Uint32Array(e.slice(a,a+4))[0];a+=4;const n=new Uint8Array(e.slice(a,a+t));c.push(n),a+=t}}else{const i=vn[r],s=e.slice(a,a+l*i);if("float32"===r)c=new Float32Array(s);else if("int32"===r)c=new Int32Array(s);else if("bool"===r)c=new Uint8Array(s);else{if("complex64"!==r)throw new Error(`Unsupported dtype in weight '${t}': ${r}`);{c=new Float32Array(s);const e=new Float32Array(c.length/2),i=new Float32Array(c.length/2);for(let t=0;t<e.length;t++)e[t]=c[2*t],i[t]=c[2*t+1];const a=gn(e,o,"float32"),r=gn(i,o,"float32");n[t]=mn(a,r),a.dispose(),r.dispose()}}a+=l*i}"complex64"!==r&&(n[t]=gn(c,o,r))}return n}(e,t),i={},a=[];return t.forEach((e=>{"optimizer"===e.group?a.push({name:e.name,tensor:n[e.name]}):i[e.name]=n[e.name]})),{modelWeights:i,optimizerWeights:a}}(i.weightData,i.weightSpecs);o.loadWeights(e,s),null!=o.optimizer&&t.length>0&&await o.optimizer.setWeights(t),ri(e),ri(t.map((e=>e.tensor)))}return o}(e,void 0,t)}wp.className="Functional",yi(wp);class xp extends bp{constructor(e){if(super({inputs:[],outputs:[]}),e=e||{},this.trainable=!0,this.built=!1,this.name=null!=e.name?e.name:dl("sequential_"),null!=e.layers)for(const t of e.layers)this.add(t)}checkShape(e){if(e.inboundNodes[0].outputTensors[0].shape.some((e=>e<0)))throw new Bo(`Negative dimension size caused by adding layer ${e.name} with input shape [${e.inboundNodes[0].inputTensors[0].shape}]`)}add(e){const t=e instanceof xp||e instanceof bp;let n;if(t){if(n=e,1!==n.outputs.length)throw new Bo("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");if(1!==n.inputs.length)throw new Bo("All layers in a Sequential model should have a single input tensor. For multi-input layers, use the functional API.")}if(0===this.outputs.length){if(0===e.inboundNodes.length){if(null==e.batchInputShape)throw new Bo("The first layer in a Sequential model must get an `inputShape` or `batchInputShape` argument.");const t=function(e){if(null==e.batchShape&&null==e.shape)throw new Error("Please provide to Input either a `shape` or a `batchShape` argument. Note that `shape` does not include the batch dimension.");if(null!=e.batchShape&&null!=e.shape)throw new Bo("Please provide either a `shape` or `batchShape` argument to Input, but not both.");let t=e.batchShape;null!=e.shape&&null==t&&(t=[null].concat(e.shape));let n=e.dtype;return null==n&&(n="float32"),new _c({batchInputShape:t,name:e.name,dtype:n,sparse:e.sparse}).inboundNodes[0].outputTensors[0]}({batchShape:e.batchInputShape,dtype:e.dtype,name:e.name+"_input"});e.apply(t)}if(t)this.outputs=n.outputs,this.inputs=n.inputs;else{if(1!==e.inboundNodes.length)throw new Bo(`A layer added to a Sequential model must not already be connected somewhere else. LayersModel received layer ${e.name} which has ${e.inboundNodes.length} pre-existing inbound connections.`);if(1!==e.inboundNodes[0].outputTensors.length)throw new Bo("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");this.checkShape(e),this.outputs=[e.inboundNodes[0].outputTensors[0]],this.inputs=Fc(this.outputs[0])}this.inboundNodes=[],new jc({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:Vo(null,this.inputs.length),outputMasks:[null],inputShapes:this.inputs.map((e=>e.shape)),outputShapes:this.outputs[0].shape})}else{const t=e.apply(this.outputs[0]);if(Array.isArray(t))throw new TypeError("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");this.checkShape(e),this.outputs=[t],this.inboundNodes[0].outputTensors=this.outputs,this.inboundNodes[0].outputShapes=[this.outputs[0].shape]}this.layers.push(e),this.built=!1}pop(){if(0===this.layers.length)throw new TypeError("There are no layers in the model.");if(this.layers.pop(),0===this.layers.length)this.outputs=[],this.inboundNodes=[],this.outboundNodes=[];else{const e=this.layers.length-1;this.layers[e].outboundNodes=[],this.outputs=[this.layers[e].output],this.inboundNodes[0].outputTensors=this.outputs,this.inboundNodes[0].outputShapes=[this.outputs[0].shape]}}call(e,t){return null==this.model&&this.build(),this.model.call(e,t)}build(e){if(xc(e),0===this.inputs.length||0===this.outputs.length)throw new TypeError("Sequential model cannot be built: model is empty. Add some layers first.");this.model=new bp({inputs:this.inputs,outputs:this.outputs[0],name:this.name+"_model"}),this.model.trainable=this.trainable,this.supportsMasking=this.model.supportsMasking,this.inputLayers=this.model.inputLayers,this.inputLayersNodeIndices=this.model.inputLayersNodeIndices,this.inputLayersTensorIndices=this.model.inputLayersTensorIndices,this.outputLayers=this.model.outputLayers,this.outputLayersNodeIndices=this.model.outputLayersNodeIndices,this.outputLayersTensorIndices=this.model.outputLayersTensorIndices,this.nodesByDepth=this.model.nodesByDepth,this.containerNodes=this.model.containerNodes,this.outputNames=this.model.outputNames,this.inputNames=this.model.inputNames,this.built=!0}countParams(){return this.built||this.build(),super.countParams()}summary(e,t,n=console.log){this.built||this.build(),super.summary(e,t,n)}setWeights(e){null==this.model&&this.build(),this.model.setWeights(e)}evaluate(e,t,n={}){if(!this.built)throw new Po("The model needs to be compiled before being used.");return this.model.evaluate(e,t,n)}async evaluateDataset(e,t){if(!this.built)throw new Po("The model needs to be compiled before being used.");return this.model.evaluateDataset(e,t)}predict(e,t={}){return null==this.model&&this.build(),this.model.predict(e,t)}predictOnBatch(e){return null==this.model&&this.build(),this.model.predictOnBatch(e)}compile(e){this.build(),this.model.compile(e),this.optimizer_=this.model.optimizer,this.isOptimizerOwned=this.model.isOptimizerOwned,this.loss=this.model.loss,this.metrics=this.model.metrics,this.metricsTensors=this.model.metricsTensors,this.metricsNames=this.model.metricsNames}get optimizer(){return null==this.model?void 0:this.model.optimizer}set optimizer(e){this.model.optimizer=e}async fit(e,t,n={}){if(!this.built)throw new Po("The model needs to be compiled before being used.");return this.model.fit(e,t,n)}async fitDataset(e,t){if(!this.built)throw new Po("The model needs to be compiled before being used.");return this.model.fitDataset(e,t)}async trainOnBatch(e,t){return this.model.trainOnBatch(e,t)}static fromConfig(e,t,n={},i=!1){let a,s={};if(t instanceof Array){if(null==t[0].className||"Merge"===t[0].className)throw new Bo("Legacy serialization format not supported yet.");a=t}else I(null!=t.layers,(()=>"When the config data for a Sequential model is not an Array, it must be an Object that contains the 'layers' field.")),a=t.layers,delete t.layers,s=t;const r=new e(s);if(!(r instanceof xp))throw new Uo(`Sequential.fromConfig called on non-Sequential input: ${r}`);for(const e of a){const t=Nh(e,void 0,i);i&&t.setFastWeightInitDuringBuild(!0),r.add(t)}return r}set stopTraining(e){if(null==this.model)throw new Bo("Cannot set the stopTraining property of a sequential model before it is compiled.");this.model.stopTraining=e}get stopTraining(){if(null==this.model)throw new Bo("Cannot get the stopTraining property of a sequential model before it is compiled.");return this.model.stopTraining}getConfig(){const e=[];for(const t of this.layers){const n={};n.className=t.getClassName(),n.config=t.getConfig(),e.push(n)}return{name:this.name,layers:e}}}xp.className="Sequential",yi(xp);
4447
+ */return async function(e,t,n){null==n&&(n={});if(null==e.load)throw new Bo("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");const i=await e.load();let a=i.modelTopology;null!=a.model_config&&(a=a.model_config);const s=null==n.strict||n.strict,r=null!=i.weightData&&null!=i.weightSpecs&&s,o=Nh(Qh(a),t,r),l=i.trainingConfig;null!=l&&o.loadTrainingConfig(l);null!=i.userDefinedMetadata&&o.setUserDefinedMetadata(i.userDefinedMetadata);if(null!=i.weightData){if(null==i.weightSpecs)throw new Bo("LayersModel artifacts contains weight data, but not weight specs. Therefore loading of weights cannot proceed.");const{modelWeights:e,optimizerWeights:t}=function(e,t){const n=function(e,t){const n={};let i,a=0;for(const s of t){const t=s.name,r=s.dtype,o=s.shape,l=C(o);let c;if("quantization"in s){const n=s.quantization;if("uint8"===n.dtype||"uint16"===n.dtype){if(!("min"in n)||!("scale"in n))throw new Error(`Weight ${s.name} with quantization ${n.dtype} doesn't have corresponding metadata min and scale.`)}else{if("float16"!==n.dtype)throw new Error(`Weight ${s.name} has unknown quantization dtype ${n.dtype}. Supported quantization dtypes are: 'uint8', 'uint16', and 'float16'.`);if("float32"!==r)throw new Error(`Weight ${s.name} is quantized with ${n.dtype} which only supports weights of type float32 not ${r}.`)}const o=vn[n.dtype],u=e.slice(a,a+l*o),h="uint8"===n.dtype?new Uint8Array(u):new Uint16Array(u);if("float32"===r)if("uint8"===n.dtype||"uint16"===n.dtype){c=new Float32Array(h.length);for(let e=0;e<h.length;e++){const t=h[e];c[e]=t*n.scale+n.min}}else{if("float16"!==n.dtype)throw new Error(`Unsupported quantization type ${n.dtype} for weight type float32.`);void 0===i&&(i=Tn()),c=i(h)}else{if("int32"!==r)throw new Error(`Unsupported dtype in weight '${t}': ${r}`);if("uint8"!==n.dtype&&"uint16"!==n.dtype)throw new Error(`Unsupported quantization type ${n.dtype} for weight type int32.`);c=new Int32Array(h.length);for(let e=0;e<h.length;e++){const t=h[e];c[e]=Math.round(t*n.scale+n.min)}}a+=l*o}else if("string"===r){const t=C(s.shape);c=[];for(let n=0;n<t;n++){const t=new Uint32Array(e.slice(a,a+4))[0];a+=4;const n=new Uint8Array(e.slice(a,a+t));c.push(n),a+=t}}else{const i=vn[r],s=e.slice(a,a+l*i);if("float32"===r)c=new Float32Array(s);else if("int32"===r)c=new Int32Array(s);else if("bool"===r)c=new Uint8Array(s);else{if("complex64"!==r)throw new Error(`Unsupported dtype in weight '${t}': ${r}`);{c=new Float32Array(s);const e=new Float32Array(c.length/2),i=new Float32Array(c.length/2);for(let t=0;t<e.length;t++)e[t]=c[2*t],i[t]=c[2*t+1];const a=gn(e,o,"float32"),r=gn(i,o,"float32");n[t]=mn(a,r),a.dispose(),r.dispose()}}a+=l*i}"complex64"!==r&&(n[t]=gn(c,o,r))}return n}(e,t),i={},a=[];return t.forEach((e=>{"optimizer"===e.group?a.push({name:e.name,tensor:n[e.name]}):i[e.name]=n[e.name]})),{modelWeights:i,optimizerWeights:a}}(i.weightData,i.weightSpecs);o.loadWeights(e,s),null!=o.optimizer&&t.length>0&&await o.optimizer.setWeights(t),ri(e),ri(t.map((e=>e.tensor)))}return o}(e,void 0,t)}wp.className="Functional",yi(wp);class xp extends bp{constructor(e){if(super({inputs:[],outputs:[]}),e=e||{},this.trainable=!0,this.built=!1,this.name=null!=e.name?e.name:dl("sequential_"),null!=e.layers)for(const t of e.layers)this.add(t)}checkShape(e){if(e.inboundNodes[0].outputTensors[0].shape.some((e=>e<0)))throw new Bo(`Negative dimension size caused by adding layer ${e.name} with input shape [${e.inboundNodes[0].inputTensors[0].shape}]`)}add(e){const t=e instanceof xp||e instanceof bp;let n;if(t){if(n=e,1!==n.outputs.length)throw new Bo("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");if(1!==n.inputs.length)throw new Bo("All layers in a Sequential model should have a single input tensor. For multi-input layers, use the functional API.")}if(0===this.outputs.length){if(0===e.inboundNodes.length){if(null==e.batchInputShape)throw new Bo("The first layer in a Sequential model must get an `inputShape` or `batchInputShape` argument.");const t=function(e){if(null==e.batchShape&&null==e.shape)throw new Error("Please provide to Input either a `shape` or a `batchShape` argument. Note that `shape` does not include the batch dimension.");if(null!=e.batchShape&&null!=e.shape)throw new Bo("Please provide either a `shape` or `batchShape` argument to Input, but not both.");let t=e.batchShape;null!=e.shape&&null==t&&(t=[null].concat(e.shape));let n=e.dtype;return null==n&&(n="float32"),new _c({batchInputShape:t,name:e.name,dtype:n,sparse:e.sparse}).inboundNodes[0].outputTensors[0]}({batchShape:e.batchInputShape,dtype:e.dtype,name:e.name+"_input"});e.apply(t)}if(t)this.outputs=n.outputs,this.inputs=n.inputs;else{if(1!==e.inboundNodes.length)throw new Bo(`A layer added to a Sequential model must not already be connected somewhere else. LayersModel received layer ${e.name} which has ${e.inboundNodes.length} pre-existing inbound connections.`);if(1!==e.inboundNodes[0].outputTensors.length)throw new Bo("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");this.checkShape(e),this.outputs=[e.inboundNodes[0].outputTensors[0]],this.inputs=Fc(this.outputs[0])}this.inboundNodes=[],new jc({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:Go(null,this.inputs.length),outputMasks:[null],inputShapes:this.inputs.map((e=>e.shape)),outputShapes:this.outputs[0].shape})}else{const t=e.apply(this.outputs[0]);if(Array.isArray(t))throw new TypeError("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");this.checkShape(e),this.outputs=[t],this.inboundNodes[0].outputTensors=this.outputs,this.inboundNodes[0].outputShapes=[this.outputs[0].shape]}this.layers.push(e),this.built=!1}pop(){if(0===this.layers.length)throw new TypeError("There are no layers in the model.");if(this.layers.pop(),0===this.layers.length)this.outputs=[],this.inboundNodes=[],this.outboundNodes=[];else{const e=this.layers.length-1;this.layers[e].outboundNodes=[],this.outputs=[this.layers[e].output],this.inboundNodes[0].outputTensors=this.outputs,this.inboundNodes[0].outputShapes=[this.outputs[0].shape]}}call(e,t){return null==this.model&&this.build(),this.model.call(e,t)}build(e){if(xc(e),0===this.inputs.length||0===this.outputs.length)throw new TypeError("Sequential model cannot be built: model is empty. Add some layers first.");this.model=new bp({inputs:this.inputs,outputs:this.outputs[0],name:this.name+"_model"}),this.model.trainable=this.trainable,this.supportsMasking=this.model.supportsMasking,this.inputLayers=this.model.inputLayers,this.inputLayersNodeIndices=this.model.inputLayersNodeIndices,this.inputLayersTensorIndices=this.model.inputLayersTensorIndices,this.outputLayers=this.model.outputLayers,this.outputLayersNodeIndices=this.model.outputLayersNodeIndices,this.outputLayersTensorIndices=this.model.outputLayersTensorIndices,this.nodesByDepth=this.model.nodesByDepth,this.containerNodes=this.model.containerNodes,this.outputNames=this.model.outputNames,this.inputNames=this.model.inputNames,this.built=!0}countParams(){return this.built||this.build(),super.countParams()}summary(e,t,n=console.log){this.built||this.build(),super.summary(e,t,n)}setWeights(e){null==this.model&&this.build(),this.model.setWeights(e)}evaluate(e,t,n={}){if(!this.built)throw new Po("The model needs to be compiled before being used.");return this.model.evaluate(e,t,n)}async evaluateDataset(e,t){if(!this.built)throw new Po("The model needs to be compiled before being used.");return this.model.evaluateDataset(e,t)}predict(e,t={}){return null==this.model&&this.build(),this.model.predict(e,t)}predictOnBatch(e){return null==this.model&&this.build(),this.model.predictOnBatch(e)}compile(e){this.build(),this.model.compile(e),this.optimizer_=this.model.optimizer,this.isOptimizerOwned=this.model.isOptimizerOwned,this.loss=this.model.loss,this.metrics=this.model.metrics,this.metricsTensors=this.model.metricsTensors,this.metricsNames=this.model.metricsNames}get optimizer(){return null==this.model?void 0:this.model.optimizer}set optimizer(e){this.model.optimizer=e}async fit(e,t,n={}){if(!this.built)throw new Po("The model needs to be compiled before being used.");return this.model.fit(e,t,n)}async fitDataset(e,t){if(!this.built)throw new Po("The model needs to be compiled before being used.");return this.model.fitDataset(e,t)}async trainOnBatch(e,t){return this.model.trainOnBatch(e,t)}static fromConfig(e,t,n={},i=!1){let a,s={};if(t instanceof Array){if(null==t[0].className||"Merge"===t[0].className)throw new Bo("Legacy serialization format not supported yet.");a=t}else T(null!=t.layers,(()=>"When the config data for a Sequential model is not an Array, it must be an Object that contains the 'layers' field.")),a=t.layers,delete t.layers,s=t;const r=new e(s);if(!(r instanceof xp))throw new Uo(`Sequential.fromConfig called on non-Sequential input: ${r}`);for(const e of a){const t=Nh(e,void 0,i);i&&t.setFastWeightInitDuringBuild(!0),r.add(t)}return r}set stopTraining(e){if(null==this.model)throw new Bo("Cannot set the stopTraining property of a sequential model before it is compiled.");this.model.stopTraining=e}get stopTraining(){if(null==this.model)throw new Bo("Cannot get the stopTraining property of a sequential model before it is compiled.");return this.model.stopTraining}getConfig(){const e=[];for(const t of this.layers){const n={};n.className=t.getClassName(),n.config=t.getConfig(),e.push(n)}return{name:this.name,layers:e}}}xp.className="Sequential",yi(xp);
4448
4448
  /**
4449
4449
  * @license
4450
4450
  * Copyright 2018 Google LLC
@@ -4454,7 +4454,7 @@ async function kp(e,t){if(null==t&&(t={}),"string"==typeof e){const a=(n=e,i=t,T
4454
4454
  * https://opensource.org/licenses/MIT.
4455
4455
  * =============================================================================
4456
4456
  */
4457
- class Sp extends gi{getConfig(){return{}}}class Np extends Sp{apply(e,t=1){return function(e,t=1){if(1!==t)throw new Uo(`Support for alpha values other than 1 (${t}) is not implemented yet.`);return ba(e)}(e,t)}}Np.className="elu",yi(Np);class Ip extends Sp{apply(e){return zs(e)}}Ip.className="selu",yi(Ip);class Tp extends Sp{apply(e){return Es(e)}}Tp.className="relu",yi(Tp);class Ep extends Sp{apply(e){return si((()=>ss(6,Es(e))))}}Ep.className="relu6",yi(Ep);class Ap extends Sp{apply(e){return e}}Ap.className="linear",yi(Ap);class Cp extends Sp{apply(e){return Pi(e)}}Cp.className="sigmoid",yi(Cp);class $p extends Sp{apply(e){return function(e){return si((()=>{const t=bi(.5,xi(.2,e));return Qi(t,0,1)}))}(e)}}$p.className="hardSigmoid",yi($p);class jp extends Sp{apply(e){return Ha(e)}}jp.className="softplus",yi(jp);class zp extends Sp{apply(e){return function(e){return si((()=>ki(e,bi(Si(e),1))))}(e)}}zp.className="softsign",yi(zp);class Dp extends Sp{apply(e){return Ui(e)}}Dp.className="tanh",yi(Dp);class Fp extends Sp{apply(e,t=-1){return Ps(e,t)}}Fp.className="softmax",yi(Fp);class _p extends Sp{apply(e,t=-1){return Za(e,t)}}_p.className="logSoftmax",yi(_p);class Rp extends Sp{apply(e,t=1){return si((()=>xi(Pi(xi(e,t)),e)))}}Rp.className="swish",yi(Rp);class Lp extends Sp{apply(e){return si((()=>xi(e,Ui(Ha(e)))))}}function Mp(e){return e.getClassName()}function Op(e,t={}){return tl(e,vi.getMap().classNameMap,t,"activation")}function Pp(e){if(null==e){const e={className:"linear",config:{}};return Op(e)}if("string"==typeof e){const t={};return t.className=e,t.config={},Op(t)}return e instanceof Sp?e:Op(e)}
4457
+ class Sp extends gi{getConfig(){return{}}}class Np extends Sp{apply(e,t=1){return function(e,t=1){if(1!==t)throw new Uo(`Support for alpha values other than 1 (${t}) is not implemented yet.`);return ba(e)}(e,t)}}Np.className="elu",yi(Np);class Tp extends Sp{apply(e){return zs(e)}}Tp.className="selu",yi(Tp);class Ip extends Sp{apply(e){return As(e)}}Ip.className="relu",yi(Ip);class Ap extends Sp{apply(e){return si((()=>ss(6,As(e))))}}Ap.className="relu6",yi(Ap);class Cp extends Sp{apply(e){return e}}Cp.className="linear",yi(Cp);class Ep extends Sp{apply(e){return Pi(e)}}Ep.className="sigmoid",yi(Ep);class $p extends Sp{apply(e){return function(e){return si((()=>{const t=bi(.5,xi(.2,e));return Qi(t,0,1)}))}(e)}}$p.className="hardSigmoid",yi($p);class jp extends Sp{apply(e){return Ha(e)}}jp.className="softplus",yi(jp);class zp extends Sp{apply(e){return function(e){return si((()=>ki(e,bi(Si(e),1))))}(e)}}zp.className="softsign",yi(zp);class Dp extends Sp{apply(e){return Ui(e)}}Dp.className="tanh",yi(Dp);class Fp extends Sp{apply(e,t=-1){return Ps(e,t)}}Fp.className="softmax",yi(Fp);class _p extends Sp{apply(e,t=-1){return Za(e,t)}}_p.className="logSoftmax",yi(_p);class Rp extends Sp{apply(e,t=1){return si((()=>xi(Pi(xi(e,t)),e)))}}Rp.className="swish",yi(Rp);class Lp extends Sp{apply(e){return si((()=>xi(e,Ui(Ha(e)))))}}function Mp(e){return e.getClassName()}function Op(e,t={}){return tl(e,vi.getMap().classNameMap,t,"activation")}function Pp(e){if(null==e){const e={className:"linear",config:{}};return Op(e)}if("string"==typeof e){const t={};return t.className=e,t.config={},Op(t)}return e instanceof Sp?e:Op(e)}
4458
4458
  /**
4459
4459
  * @license
4460
4460
  * Copyright 2018 Google LLC
@@ -4463,7 +4463,7 @@ class Sp extends gi{getConfig(){return{}}}class Np extends Sp{apply(e,t=1){retur
4463
4463
  * license that can be found in the LICENSE file or at
4464
4464
  * https://opensource.org/licenses/MIT.
4465
4465
  * =============================================================================
4466
- */Lp.className="mish",yi(Lp);class Bp extends gi{}class Up extends Bp{constructor(e){super(),function(e){if(null!=e&&"object"!=typeof e)throw new Error(`Argument to L1L2 regularizer's constructor is expected to be an object, but received: ${e}`)}(e),this.l1=null==e||null==e.l1?.01:e.l1,this.l2=null==e||null==e.l2?.01:e.l2,this.hasL1=0!==this.l1,this.hasL2=0!==this.l2}apply(e){return si((()=>{let t=is([1]);return this.hasL1&&(t=bi(t,ja(xi(this.l1,Si(e))))),this.hasL2&&(t=bi(t,ja(xi(this.l2,Kl(e))))),_i(t,[])}))}getConfig(){return{l1:this.l1,l2:this.l2}}static fromConfig(e,t){return new e({l1:t.l1,l2:t.l2})}}Up.className="L1L2",yi(Up);const Wp={l1l2:"L1L2"};function Gp(e){return Xo(e)}function Vp(e,t={}){return tl(e,vi.getMap().classNameMap,t,"regularizer")}function Kp(e){if(null==e)return null;if("string"==typeof e){return Vp({className:e in Wp?Wp[e]:e,config:{}})}return e instanceof Bp?e:Vp(e)}
4466
+ */Lp.className="mish",yi(Lp);class Bp extends gi{}class Up extends Bp{constructor(e){super(),function(e){if(null!=e&&"object"!=typeof e)throw new Error(`Argument to L1L2 regularizer's constructor is expected to be an object, but received: ${e}`)}(e),this.l1=null==e||null==e.l1?.01:e.l1,this.l2=null==e||null==e.l2?.01:e.l2,this.hasL1=0!==this.l1,this.hasL2=0!==this.l2}apply(e){return si((()=>{let t=is([1]);return this.hasL1&&(t=bi(t,ja(xi(this.l1,Si(e))))),this.hasL2&&(t=bi(t,ja(xi(this.l2,Kl(e))))),_i(t,[])}))}getConfig(){return{l1:this.l1,l2:this.l2}}static fromConfig(e,t){return new e({l1:t.l1,l2:t.l2})}}Up.className="L1L2",yi(Up);const Wp={l1l2:"L1L2"};function Vp(e){return Xo(e)}function Gp(e,t={}){return tl(e,vi.getMap().classNameMap,t,"regularizer")}function Kp(e){if(null==e)return null;if("string"==typeof e){return Gp({className:e in Wp?Wp[e]:e,config:{}})}return e instanceof Bp?e:Gp(e)}
4467
4467
  /**
4468
4468
  * @license
4469
4469
  * Copyright 2018 Google LLC
@@ -4472,7 +4472,7 @@ class Sp extends gi{getConfig(){return{}}}class Np extends Sp{apply(e,t=1){retur
4472
4472
  * license that can be found in the LICENSE file or at
4473
4473
  * https://opensource.org/licenses/MIT.
4474
4474
  * =============================================================================
4475
- */class qp extends Dc{constructor(e){super(null==e?{}:e),this.supportsMasking=!0,null!=e&&(this.maxValue=e.maxValue)}call(e,t){e=kc(e);let n=Es(e);return null!=this.maxValue&&(n=Qi(n,0,this.maxValue)),n}computeOutputShape(e){return e}getConfig(){const e={maxValue:this.maxValue},t=super.getConfig();return Object.assign(e,t),e}}qp.className="ReLU",yi(qp);class Hp extends Dc{constructor(e){super(null==e?{}:e),this.DEFAULT_ALPHA=.3,null==e&&(e={}),this.alpha=null==e.alpha?this.DEFAULT_ALPHA:e.alpha}call(e,t){const n=kc(e);return Ua(n,this.alpha)}computeOutputShape(e){return e}getConfig(){const e={alpha:this.alpha},t=super.getConfig();return Object.assign(e,t),e}}Hp.className="LeakyReLU",yi(Hp);class Jp extends Dc{constructor(e){if(super(null==e?{}:e),this.DEFAULT_ALPHA_INITIALIZER="zeros",null==e&&(e={}),this.supportsMasking=!0,this.alphaInitializer=yc(e.alphaInitializer||this.DEFAULT_ALPHA_INITIALIZER),this.alphaRegularizer=Kp(e.alphaRegularizer),this.alphaConstraint=ph(e.alphaConstraint),null==e.sharedAxes)this.sharedAxes=null;else if(Array.isArray(e.sharedAxes))this.sharedAxes=e.sharedAxes;else{if("number"!=typeof e.sharedAxes)throw new Bo(`Expected sharedAxes to be a number or an array of numbers, but got ${e.sharedAxes}`);this.sharedAxes=[e.sharedAxes]}}build(e){const t=(e=xc(e)).slice(1);if(null!=this.sharedAxes)for(const e of this.sharedAxes)t[e-1]=1;this.alpha=this.addWeight("alpha",t,"float32",this.alphaInitializer,this.alphaRegularizer,!0,this.alphaConstraint);const n={};if(null!=this.sharedAxes)for(let t=1;t<e.length;++t)n[t]=e[t];this.inputSpec=[new Ac({ndim:e.length,axes:n})],this.built=!0}call(e,t){return e=kc(e),hs(e,this.alpha.read())}getConfig(){const e={alphaInitializer:vc(this.alphaInitializer),alphaRegularizer:Gp(this.alphaRegularizer),alphaConstraint:uh(this.alphaConstraint),sharedAxes:this.sharedAxes},t=super.getConfig();return Object.assign(e,t),e}}Jp.className="PReLU",yi(Jp);class Zp extends Dc{constructor(e){if(super(null==e?{}:e),this.DEFAULT_ALPHA=1,null==e&&(e={}),null!=e.alpha&&e.alpha!==this.DEFAULT_ALPHA)throw new Uo(`Non-default alpha value (${e.alpha}) is not supported by the ELU layer yet.`);this.alpha=null==e.alpha?this.DEFAULT_ALPHA:e.alpha}call(e,t){const n=kc(e);return ba(n)}computeOutputShape(e){return e}getConfig(){const e={alpha:this.alpha},t=super.getConfig();return Object.assign(e,t),e}}Zp.className="ELU",yi(Zp);class Yp extends Dc{constructor(e){super(null==e?{}:e),this.DEFAULT_THETA=1,null==e&&(e={}),this.theta=null==e.theta?this.DEFAULT_THETA:e.theta}call(e,t){const n=kc(e);return xi(n,ei(Pa(n,this.theta),"float32"))}computeOutputShape(e){return e}getConfig(){const e={theta:this.theta},t=super.getConfig();return Object.assign(e,t),e}}Yp.className="ThresholdedReLU",yi(Yp);class Qp extends Dc{constructor(e){super(null==e?{}:e),this.DEFAULT_AXIS=1,null==e&&(e={}),this.softmax=(new Fp).apply,this.axis=null==e.axis?this.DEFAULT_AXIS:e.axis}call(e,t){const n=kc(e);return this.softmax(n,this.axis)}computeOutputShape(e){return e}getConfig(){const e={axis:this.axis},t=super.getConfig();return Object.assign(e,t),e}}
4475
+ */class qp extends Dc{constructor(e){super(null==e?{}:e),this.supportsMasking=!0,null!=e&&(this.maxValue=e.maxValue)}call(e,t){e=kc(e);let n=As(e);return null!=this.maxValue&&(n=Qi(n,0,this.maxValue)),n}computeOutputShape(e){return e}getConfig(){const e={maxValue:this.maxValue},t=super.getConfig();return Object.assign(e,t),e}}qp.className="ReLU",yi(qp);class Hp extends Dc{constructor(e){super(null==e?{}:e),this.DEFAULT_ALPHA=.3,null==e&&(e={}),this.alpha=null==e.alpha?this.DEFAULT_ALPHA:e.alpha}call(e,t){const n=kc(e);return Ua(n,this.alpha)}computeOutputShape(e){return e}getConfig(){const e={alpha:this.alpha},t=super.getConfig();return Object.assign(e,t),e}}Hp.className="LeakyReLU",yi(Hp);class Jp extends Dc{constructor(e){if(super(null==e?{}:e),this.DEFAULT_ALPHA_INITIALIZER="zeros",null==e&&(e={}),this.supportsMasking=!0,this.alphaInitializer=yc(e.alphaInitializer||this.DEFAULT_ALPHA_INITIALIZER),this.alphaRegularizer=Kp(e.alphaRegularizer),this.alphaConstraint=ph(e.alphaConstraint),null==e.sharedAxes)this.sharedAxes=null;else if(Array.isArray(e.sharedAxes))this.sharedAxes=e.sharedAxes;else{if("number"!=typeof e.sharedAxes)throw new Bo(`Expected sharedAxes to be a number or an array of numbers, but got ${e.sharedAxes}`);this.sharedAxes=[e.sharedAxes]}}build(e){const t=(e=xc(e)).slice(1);if(null!=this.sharedAxes)for(const e of this.sharedAxes)t[e-1]=1;this.alpha=this.addWeight("alpha",t,"float32",this.alphaInitializer,this.alphaRegularizer,!0,this.alphaConstraint);const n={};if(null!=this.sharedAxes)for(let t=1;t<e.length;++t)n[t]=e[t];this.inputSpec=[new Cc({ndim:e.length,axes:n})],this.built=!0}call(e,t){return e=kc(e),hs(e,this.alpha.read())}getConfig(){const e={alphaInitializer:vc(this.alphaInitializer),alphaRegularizer:Vp(this.alphaRegularizer),alphaConstraint:uh(this.alphaConstraint),sharedAxes:this.sharedAxes},t=super.getConfig();return Object.assign(e,t),e}}Jp.className="PReLU",yi(Jp);class Zp extends Dc{constructor(e){if(super(null==e?{}:e),this.DEFAULT_ALPHA=1,null==e&&(e={}),null!=e.alpha&&e.alpha!==this.DEFAULT_ALPHA)throw new Uo(`Non-default alpha value (${e.alpha}) is not supported by the ELU layer yet.`);this.alpha=null==e.alpha?this.DEFAULT_ALPHA:e.alpha}call(e,t){const n=kc(e);return ba(n)}computeOutputShape(e){return e}getConfig(){const e={alpha:this.alpha},t=super.getConfig();return Object.assign(e,t),e}}Zp.className="ELU",yi(Zp);class Yp extends Dc{constructor(e){super(null==e?{}:e),this.DEFAULT_THETA=1,null==e&&(e={}),this.theta=null==e.theta?this.DEFAULT_THETA:e.theta}call(e,t){const n=kc(e);return xi(n,ei(Pa(n,this.theta),"float32"))}computeOutputShape(e){return e}getConfig(){const e={theta:this.theta},t=super.getConfig();return Object.assign(e,t),e}}Yp.className="ThresholdedReLU",yi(Yp);class Qp extends Dc{constructor(e){super(null==e?{}:e),this.DEFAULT_AXIS=1,null==e&&(e={}),this.softmax=(new Fp).apply,this.axis=null==e.axis?this.DEFAULT_AXIS:e.axis}call(e,t){const n=kc(e);return this.softmax(n,this.axis)}computeOutputShape(e){return e}getConfig(){const e={axis:this.axis},t=super.getConfig();return Object.assign(e,t),e}}
4476
4476
  /**
4477
4477
  * @license
4478
4478
  * Copyright 2018 Google LLC
@@ -4482,7 +4482,7 @@ class Sp extends gi{getConfig(){return{}}}class Np extends Sp{apply(e,t=1){retur
4482
4482
  * https://opensource.org/licenses/MIT.
4483
4483
  * =============================================================================
4484
4484
  */
4485
- function Xp(e,t,n){if("number"==typeof e)return Vo(e,t);if(e.length!==t)throw new Bo(`The ${n} argument must be an integer or tuple of ${t} integers. Received: ${e.length} elements.`);for(let a=0;a<t;++a){const s=e[a];if((i=s)!==parseInt(i.toString(),10))throw new Bo(`The ${n} argument must be an integer or tuple of ${t} integers. Received: ${JSON.stringify(e)} including a non-integer number ${s}`)}return e;var i}function ed(e,t,n,i,a=1){if(null==e)return e;let s;return s="same"===n?e:e-(t+(t-1)*(a-1))+1,Math.floor((s+i-1)/i)}function td(e,t,n,i){if(null==e)return null;if("valid"===i)e=e*t+jl([n-t,0]);else{if("same"!==i)throw new Bo(`Unsupport padding mode: ${i}.`);e*=t}return e}
4485
+ function Xp(e,t,n){if("number"==typeof e)return Go(e,t);if(e.length!==t)throw new Bo(`The ${n} argument must be an integer or tuple of ${t} integers. Received: ${e.length} elements.`);for(let a=0;a<t;++a){const s=e[a];if((i=s)!==parseInt(i.toString(),10))throw new Bo(`The ${n} argument must be an integer or tuple of ${t} integers. Received: ${JSON.stringify(e)} including a non-integer number ${s}`)}return e;var i}function ed(e,t,n,i,a=1){if(null==e)return e;let s;return s="same"===n?e:e-(t+(t-1)*(a-1))+1,Math.floor((s+i-1)/i)}function td(e,t,n,i){if(null==e)return null;if("valid"===i)e=e*t+jl([n-t,0]);else{if("same"!==i)throw new Bo(`Unsupport padding mode: ${i}.`);e*=t}return e}
4486
4486
  /**
4487
4487
  * @license
4488
4488
  * Copyright 2018 Google LLC
@@ -4491,7 +4491,7 @@ function Xp(e,t,n){if("number"==typeof e)return Vo(e,t);if(e.length!==t)throw ne
4491
4491
  * license that can be found in the LICENSE file or at
4492
4492
  * https://opensource.org/licenses/MIT.
4493
4493
  * =============================================================================
4494
- */function nd(e,t){return si((()=>(wl(t),"channelsFirst"===t?hi(e,[0,2,3,1]):e)))}function id(e,t){return si((()=>(wl(t),"channelsFirst"===t?hi(e,[0,2,3,4,1]):e)))}function ad(e,t,n,i=[1,1],a="valid",s,r,o=null){return si((()=>{if(null==s&&(s="channelsLast"),wl(s),3!==e.rank&&4!==e.rank)throw new Bo(`conv2dWithBiasActivation expects input to be of rank 3 or 4, but received ${e.rank}.`);if(3!==t.rank&&4!==t.rank)throw new Bo(`conv2dWithBiasActivation expects kernel to be of rank 3 or 4, but received ${e.rank}.`);let l=nd(e,s);if("causal"===a)throw new Uo("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");return l=nr({x:l,filter:t,strides:i,pad:"same"===a?"same":"valid",dilations:r,dataFormat:"NHWC",bias:n,activation:o}),"channelsFirst"===s&&(l=hi(l,[0,3,1,2])),l}))}Qp.className="Softmax",yi(Qp);class sd extends Dc{constructor(e,t){if(super(t),this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",sd.verifyArgs(t),this.rank=e,ol(this.rank,"rank"),1!==this.rank&&2!==this.rank&&3!==this.rank)throw new Uo(`Convolution layer for rank other than 1, 2, or 3 (${this.rank}) is not implemented yet.`);if(this.kernelSize=Xp(t.kernelSize,e,"kernelSize"),this.strides=Xp(null==t.strides?1:t.strides,e,"strides"),this.padding=null==t.padding?"valid":t.padding,kl(this.padding),this.dataFormat=null==t.dataFormat?"channelsLast":t.dataFormat,wl(this.dataFormat),this.activation=Pp(t.activation),this.useBias=null==t.useBias||t.useBias,this.biasInitializer=yc(t.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.biasConstraint=ph(t.biasConstraint),this.biasRegularizer=Kp(t.biasRegularizer),this.activityRegularizer=Kp(t.activityRegularizer),this.dilationRate=Xp(null==t.dilationRate?1:t.dilationRate,e,"dilationRate"),1===this.rank&&Array.isArray(this.dilationRate)&&1!==this.dilationRate.length)throw new Bo(`dilationRate must be a number or an array of a single number for 1D convolution, but received ${JSON.stringify(this.dilationRate)}`);if(2===this.rank){if("number"==typeof this.dilationRate)this.dilationRate=[this.dilationRate,this.dilationRate];else if(2!==this.dilationRate.length)throw new Bo(`dilationRate must be a number or array of two numbers for 2D convolution, but received ${JSON.stringify(this.dilationRate)}`)}else if(3===this.rank)if("number"==typeof this.dilationRate)this.dilationRate=[this.dilationRate,this.dilationRate,this.dilationRate];else if(3!==this.dilationRate.length)throw new Bo(`dilationRate must be a number or array of three numbers for 3D convolution, but received ${JSON.stringify(this.dilationRate)}`)}static verifyArgs(e){if(Ko("kernelSize"in e,"required key 'kernelSize' not in config"),"number"!=typeof e.kernelSize&&!rl(e.kernelSize,"number",1,3))throw new Bo(`BaseConv expects config.kernelSize to be number or number[] with length 1, 2, or 3, but received ${JSON.stringify(e.kernelSize)}.`)}getConfig(){const e={kernelSize:this.kernelSize,strides:this.strides,padding:this.padding,dataFormat:this.dataFormat,dilationRate:this.dilationRate,activation:Mp(this.activation),useBias:this.useBias,biasInitializer:vc(this.biasInitializer),biasRegularizer:Gp(this.biasRegularizer),activityRegularizer:Gp(this.activityRegularizer),biasConstraint:uh(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}}class rd extends sd{constructor(e,t){super(e,t),this.kernel=null,rd.verifyArgs(t),this.filters=t.filters,ol(this.filters,"filters"),this.kernelInitializer=yc(t.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.kernelConstraint=ph(t.kernelConstraint),this.kernelRegularizer=Kp(t.kernelRegularizer)}build(e){e=xc(e);const t="channelsFirst"===this.dataFormat?1:e.length-1;if(null==e[t])throw new Bo(`The channel dimension of the input should be defined. Found ${e[t]}`);const n=e[t],i=this.kernelSize.concat([n,this.filters]);this.kernel=this.addWeight("kernel",i,null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[{ndim:this.rank+2,axes:{[t]:n}}],this.built=!0}call(e,t){return si((()=>{let t;e=kc(e);const n=null==this.bias?null:this.bias.read(),i=cl(this.activation.getClassName());if(null!=i&&2===this.rank)t=ad(e,this.kernel.read(),n,this.strides,this.padding,this.dataFormat,this.dilationRate,i);else{if(1===this.rank)t=function(e,t,n,i=1,a="valid",s,r=1){return si((()=>{if(null==s&&(s="channelsLast"),wl(s),3!==e.shape.length)throw new Bo(`The input of a conv1dWithBias operation should be 3, but is ${e.shape.length} instead.`);if(3!==t.shape.length)throw new Bo(`The kernel for a conv1dWithBias operation should be 3, but is ${t.shape.length} instead`);if(null!=n&&1!==n.shape.length)throw new Bo(`The bias for a conv1dWithBias operation should be 1, but is ${t.shape.length} instead`);if("channelsFirst"===s&&(e=hi(e,[0,2,1])),"causal"===a)throw new Uo("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");let o=aa(e,t,i,"same"===a?"same":"valid","NWC",r);return null!=n&&(o=Hl(o,n)),o}))}(e,this.kernel.read(),n,this.strides[0],this.padding,this.dataFormat,this.dilationRate[0]);else if(2===this.rank)t=ad(e,this.kernel.read(),n,this.strides,this.padding,this.dataFormat,this.dilationRate);else{if(3!==this.rank)throw new Uo("convolutions greater than 3D are not implemented yet.");t=function(e,t,n,i=[1,1,1],a="valid",s,r){return si((()=>{if(null==s&&(s="channelsLast"),wl(s),4!==e.rank&&5!==e.rank)throw new Bo(`conv3dWithBias expects input to be of rank 4 or 5, but received ${e.rank}.`);if(4!==t.rank&&5!==t.rank)throw new Bo(`conv3dWithBias expects kernel to be of rank 4 or 5, but received ${e.rank}.`);let o=id(e,s);if("causal"===a)throw new Uo("The support for CAUSAL padding mode in conv3dWithBias is not implemented yet.");return o=oa(o,t,i,"same"===a?"same":"valid","NDHWC",r),null!=n&&(o=Hl(o,n)),"channelsFirst"===s&&(o=hi(o,[0,4,1,2,3])),o}))}(e,this.kernel.read(),n,this.strides,this.padding,this.dataFormat,this.dilationRate)}null!=this.activation&&(t=this.activation.apply(t))}return t}))}computeOutputShape(e){e=xc(e);const t=[],n="channelsLast"===this.dataFormat?e.slice(1,e.length-1):e.slice(2);for(let e=0;e<n.length;++e){const i=ed(n[e],this.kernelSize[e],this.padding,this.strides[e],"number"==typeof this.dilationRate?this.dilationRate:this.dilationRate[e]);t.push(i)}let i=[e[0]];return"channelsLast"===this.dataFormat?(i=i.concat(t),i.push(this.filters)):(i.push(this.filters),i=i.concat(t)),i}getConfig(){const e={filters:this.filters,kernelInitializer:vc(this.kernelInitializer),kernelRegularizer:Gp(this.kernelRegularizer),kernelConstraint:uh(this.kernelConstraint)},t=super.getConfig();return Object.assign(e,t),e}static verifyArgs(e){if(!("filters"in e)||"number"!=typeof e.filters||e.filters<1)throw new Bo(`Convolution layer expected config.filters to be a 'number' > 0 but got ${JSON.stringify(e.filters)}`)}}class od extends rd{constructor(e){super(2,e),od.verifyArgs(e)}getConfig(){const e=super.getConfig();return delete e.rank,e}static verifyArgs(e){if("number"!=typeof e.kernelSize&&!rl(e.kernelSize,"number",1,2))throw new Bo(`Conv2D expects config.kernelSize to be number or number[] with length 1 or 2, but received ${JSON.stringify(e.kernelSize)}.`)}}od.className="Conv2D",yi(od);class ld extends rd{constructor(e){super(3,e),ld.verifyArgs(e)}getConfig(){const e=super.getConfig();return delete e.rank,e}static verifyArgs(e){if("number"!=typeof e.kernelSize&&(!Array.isArray(e.kernelSize)||1!==e.kernelSize.length&&3!==e.kernelSize.length))throw new Bo(`Conv3D expects config.kernelSize to be number or [number, number, number], but received ${JSON.stringify(e.kernelSize)}.`)}}ld.className="Conv3D",yi(ld);class cd extends od{constructor(e){if(super(e),this.inputSpec=[new Ac({ndim:4})],"same"!==this.padding&&"valid"!==this.padding)throw new Bo(`Conv2DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(e){if(4!==(e=xc(e)).length)throw new Bo("Input should have rank 4; Received input shape: "+JSON.stringify(e));const t="channelsFirst"===this.dataFormat?1:e.length-1;if(null==e[t])throw new Bo("The channel dimension of the inputs should be defined. Found `None`.");const n=e[t],i=this.kernelSize.concat([this.filters,n]);this.kernel=this.addWeight("kernel",i,"float32",this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[new Ac({ndim:4,axes:{[t]:n}})],this.built=!0}call(e,t){return si((()=>{let t=kc(e);if(4!==t.shape.length)throw new Bo(`Conv2DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-${t.shape.length}`);const n=t.shape,i=n[0];let a,s;"channelsFirst"===this.dataFormat?(a=2,s=3):(a=1,s=2);const r=n[a],o=n[s],l=this.kernelSize[0],c=this.kernelSize[1],u=this.strides[0],h=this.strides[1],p=[i,td(r,u,l,this.padding),td(o,h,c,this.padding),this.filters];"channelsLast"!==this.dataFormat&&(t=hi(t,[0,2,3,1]));let d=ra(t,this.kernel.read(),p,this.strides,this.padding);return"channelsLast"!==this.dataFormat&&(d=hi(d,[0,3,1,2])),null!=this.bias&&(d=Hl(d,this.bias.read(),this.dataFormat)),null!=this.activation&&(d=this.activation.apply(d)),d}))}computeOutputShape(e){const t=(e=xc(e)).slice();let n,i,a;"channelsFirst"===this.dataFormat?(n=1,i=2,a=3):(n=3,i=1,a=2);const s=this.kernelSize[0],r=this.kernelSize[1],o=this.strides[0],l=this.strides[1];return t[n]=this.filters,t[i]=td(t[i],o,s,this.padding),t[a]=td(t[a],l,r,this.padding),t}getConfig(){const e=super.getConfig();return delete e.dilationRate,e}}cd.className="Conv2DTranspose",yi(cd);class ud extends ld{constructor(e){if(super(e),this.inputSpec=[new Ac({ndim:5})],"same"!==this.padding&&"valid"!==this.padding)throw new Bo(`Conv3DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(e){if(5!==(e=xc(e)).length)throw new Bo("Input should have rank 5; Received input shape: "+JSON.stringify(e));const t="channelsFirst"===this.dataFormat?1:e.length-1;if(null==e[t])throw new Bo("The channel dimension of the inputs should be defined. Found `None`.");const n=e[t],i=this.kernelSize.concat([this.filters,n]);this.kernel=this.addWeight("kernel",i,"float32",this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[new Ac({ndim:5,axes:{[t]:n}})],this.built=!0}call(e,t){return si((()=>{let t=kc(e);if(5!==t.shape.length)throw new Bo(`Conv3DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-${t.shape.length}`);const n=t.shape,i=n[0];let a,s,r;"channelsFirst"===this.dataFormat?(r=2,a=3,s=4):(r=1,a=2,s=3);const o=n[r],l=n[a],c=n[s],u=this.kernelSize[0],h=this.kernelSize[1],p=this.kernelSize[2],d=this.strides[0],m=this.strides[1],f=this.strides[2],g=[i,td(o,d,u,this.padding),td(l,m,h,this.padding),td(c,f,p,this.padding),this.filters];"channelsLast"!==this.dataFormat&&(t=hi(t,[0,2,3,4,1]));let v=ca(t,this.kernel.read(),g,this.strides,this.padding);return"channelsLast"!==this.dataFormat&&(v=hi(v,[0,4,1,2,3])),null!==this.bias&&(v=Hl(v,this.bias.read(),this.dataFormat)),null!==this.activation&&(v=this.activation.apply(v)),v}))}computeOutputShape(e){const t=(e=xc(e)).slice();let n,i,a,s;"channelsFirst"===this.dataFormat?(n=1,i=2,a=3,s=4):(n=4,i=1,a=2,s=3);const r=this.kernelSize[0],o=this.kernelSize[1],l=this.kernelSize[2],c=this.strides[0],u=this.strides[1],h=this.strides[2];return t[n]=this.filters,t[i]=td(t[i],c,r,this.padding),t[a]=td(t[a],u,o,this.padding),t[s]=td(t[s],h,l,this.padding),t}getConfig(){const e=super.getConfig();return delete e.dilationRate,e}}ud.className="Conv3DTranspose",yi(ud);class hd extends rd{constructor(e,t){if(super(e,t),this.DEFAULT_DEPTHWISE_INITIALIZER="glorotUniform",this.DEFAULT_POINTWISE_INITIALIZER="glorotUniform",this.depthwiseKernel=null,this.pointwiseKernel=null,null==t.filters)throw new Bo("The `filters` configuration field is required by SeparableConv, but is unspecified.");if(null!=t.kernelInitializer||null!=t.kernelRegularizer||null!=t.kernelConstraint)throw new Bo("Fields kernelInitializer, kernelRegularizer and kernelConstraint are invalid for SeparableConv2D. Use depthwiseInitializer, depthwiseRegularizer, depthwiseConstraint, pointwiseInitializer, pointwiseRegularizer and pointwiseConstraint instead.");if(null!=t.padding&&"same"!==t.padding&&"valid"!==t.padding)throw new Bo(`SeparableConv${this.rank}D supports only padding modes: 'same' and 'valid', but received ${JSON.stringify(t.padding)}`);this.depthMultiplier=null==t.depthMultiplier?1:t.depthMultiplier,this.depthwiseInitializer=yc(t.depthwiseInitializer||this.DEFAULT_DEPTHWISE_INITIALIZER),this.depthwiseRegularizer=Kp(t.depthwiseRegularizer),this.depthwiseConstraint=ph(t.depthwiseConstraint),this.pointwiseInitializer=yc(t.depthwiseInitializer||this.DEFAULT_POINTWISE_INITIALIZER),this.pointwiseRegularizer=Kp(t.pointwiseRegularizer),this.pointwiseConstraint=ph(t.pointwiseConstraint)}build(e){if((e=xc(e)).length<this.rank+2)throw new Bo(`Inputs to SeparableConv${this.rank}D should have rank ${this.rank+2}, but received input shape: ${JSON.stringify(e)}`);const t="channelsFirst"===this.dataFormat?1:e.length-1;if(null==e[t]||e[t]<0)throw new Bo(`The channel dimension of the inputs should be defined, but found ${JSON.stringify(e[t])}`);const n=e[t],i=this.kernelSize.concat([n,this.depthMultiplier]),a=[];for(let e=0;e<this.rank;++e)a.push(1);a.push(n*this.depthMultiplier,this.filters);const s=!0;this.depthwiseKernel=this.addWeight("depthwise_kernel",i,"float32",this.depthwiseInitializer,this.depthwiseRegularizer,s,this.depthwiseConstraint),this.pointwiseKernel=this.addWeight("pointwise_kernel",a,"float32",this.pointwiseInitializer,this.pointwiseRegularizer,s,this.pointwiseConstraint),this.useBias?this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,s,this.biasConstraint):this.bias=null,this.inputSpec=[new Ac({ndim:this.rank+2,axes:{[t]:n}})],this.built=!0}call(e,t){return si((()=>{let t;if(e=kc(e),1===this.rank)throw new Uo("1D separable convolution is not implemented yet.");return 2===this.rank&&("channelsFirst"===this.dataFormat&&(e=hi(e,[0,2,3,1])),t=Ds(e,this.depthwiseKernel.read(),this.pointwiseKernel.read(),this.strides,this.padding,this.dilationRate,"NHWC")),this.useBias&&(t=Hl(t,this.bias.read(),this.dataFormat)),null!=this.activation&&(t=this.activation.apply(t)),"channelsFirst"===this.dataFormat&&(t=hi(t,[0,3,1,2])),t}))}getConfig(){const e=super.getConfig();return delete e.rank,delete e.kernelInitializer,delete e.kernelRegularizer,delete e.kernelConstraint,e.depthwiseInitializer=vc(this.depthwiseInitializer),e.pointwiseInitializer=vc(this.pointwiseInitializer),e.depthwiseRegularizer=Gp(this.depthwiseRegularizer),e.pointwiseRegularizer=Gp(this.pointwiseRegularizer),e.depthwiseConstraint=uh(this.depthwiseConstraint),e.pointwiseConstraint=uh(this.pointwiseConstraint),e}}hd.className="SeparableConv";class pd extends hd{constructor(e){super(2,e)}}pd.className="SeparableConv2D",yi(pd);class dd extends rd{constructor(e){super(1,e),dd.verifyArgs(e),this.inputSpec=[{ndim:3}]}getConfig(){const e=super.getConfig();return delete e.rank,delete e.dataFormat,e}static verifyArgs(e){if("number"!=typeof e.kernelSize&&!rl(e.kernelSize,"number",1,1))throw new Bo(`Conv1D expects config.kernelSize to be number or number[] with length 1, but received ${JSON.stringify(e.kernelSize)}.`)}}dd.className="Conv1D",yi(dd);class md extends Dc{constructor(e){super(e),"number"==typeof e.cropping?this.cropping=[[e.cropping,e.cropping],[e.cropping,e.cropping]]:"number"==typeof e.cropping[0]?this.cropping=[[e.cropping[0],e.cropping[0]],[e.cropping[1],e.cropping[1]]]:this.cropping=e.cropping,this.dataFormat=void 0===e.dataFormat?"channelsLast":e.dataFormat,this.inputSpec=[{ndim:4}]}computeOutputShape(e){return"channelsFirst"===this.dataFormat?[e[0],e[1],e[2]-this.cropping[0][0]-this.cropping[0][1],e[3]-this.cropping[1][0]-this.cropping[1][1]]:[e[0],e[1]-this.cropping[0][0]-this.cropping[0][1],e[2]-this.cropping[1][0]-this.cropping[1][1],e[3]]}call(e,t){return si((()=>{if(e=kc(e),"channelsLast"===this.dataFormat){const t=Ol(e,this.cropping[0][0],e.shape[1]-this.cropping[0][0]-this.cropping[0][1],2);return Ol(t,this.cropping[1][0],e.shape[2]-this.cropping[1][1]-this.cropping[1][0],3)}{const t=Ol(e,this.cropping[0][0],e.shape[2]-this.cropping[0][0]-this.cropping[0][1],3);return Ol(t,this.cropping[1][0],e.shape[3]-this.cropping[1][1]-this.cropping[1][0],4)}}))}getConfig(){const e={cropping:this.cropping,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}md.className="Cropping2D",yi(md);class fd extends Dc{constructor(e){var t;super(e),this.DEFAULT_SIZE=[2,2],this.inputSpec=[{ndim:4}],this.size=null==e.size?this.DEFAULT_SIZE:e.size,this.dataFormat=null==e.dataFormat?"channelsLast":e.dataFormat,wl(this.dataFormat),this.interpolation=null==e.interpolation?"nearest":e.interpolation,t=this.interpolation,sl(fl,"InterpolationFormat",t)}computeOutputShape(e){if("channelsFirst"===this.dataFormat){const t=null==e[2]?null:this.size[0]*e[2],n=null==e[3]?null:this.size[1]*e[3];return[e[0],e[1],t,n]}{const t=null==e[1]?null:this.size[0]*e[1],n=null==e[2]?null:this.size[1]*e[2];return[e[0],t,n,e[3]]}}call(e,t){return si((()=>{let t=kc(e);const n=t.shape;if("channelsFirst"===this.dataFormat){t=hi(t,[0,2,3,1]);const e=this.size[0]*n[2],i=this.size[1]*n[3],a="nearest"===this.interpolation?zr.resizeNearestNeighbor(t,[e,i]):zr.resizeBilinear(t,[e,i]);return hi(a,[0,3,1,2])}{const e=this.size[0]*n[1],i=this.size[1]*n[2];return"nearest"===this.interpolation?zr.resizeNearestNeighbor(t,[e,i]):zr.resizeBilinear(t,[e,i])}}))}getConfig(){const e={size:this.size,dataFormat:this.dataFormat,interpolation:this.interpolation},t=super.getConfig();return Object.assign(e,t),e}}fd.className="UpSampling2D",yi(fd);class gd extends sd{constructor(e){super(2,e),this.depthwiseKernel=null,this.depthMultiplier=null==e.depthMultiplier?1:e.depthMultiplier,this.depthwiseInitializer=yc(e.depthwiseInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.depthwiseConstraint=ph(e.depthwiseConstraint),this.depthwiseRegularizer=Kp(e.depthwiseRegularizer)}build(e){if((e=xc(e)).length<4)throw new Bo(`Inputs to DepthwiseConv2D should have rank 4. Received input shape: ${JSON.stringify(e)}.`);const t="channelsFirst"===this.dataFormat?1:3;if(null==e[t]||e[t]<0)throw new Bo(`The channel dimension of the inputs to DepthwiseConv2D should be defined, but is not (${e[t]}).`);const n=e[t],i=[this.kernelSize[0],this.kernelSize[1],n,this.depthMultiplier];this.depthwiseKernel=this.addWeight("depthwise_kernel",i,null,this.depthwiseInitializer,this.depthwiseRegularizer,!0,this.depthwiseConstraint),this.useBias?this.bias=this.addWeight("bias",[n*this.depthMultiplier],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(e,t){return si((()=>{let t=
4494
+ */function nd(e,t){return si((()=>(wl(t),"channelsFirst"===t?hi(e,[0,2,3,1]):e)))}function id(e,t){return si((()=>(wl(t),"channelsFirst"===t?hi(e,[0,2,3,4,1]):e)))}function ad(e,t,n,i=[1,1],a="valid",s,r,o=null){return si((()=>{if(null==s&&(s="channelsLast"),wl(s),3!==e.rank&&4!==e.rank)throw new Bo(`conv2dWithBiasActivation expects input to be of rank 3 or 4, but received ${e.rank}.`);if(3!==t.rank&&4!==t.rank)throw new Bo(`conv2dWithBiasActivation expects kernel to be of rank 3 or 4, but received ${e.rank}.`);let l=nd(e,s);if("causal"===a)throw new Uo("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");return l=nr({x:l,filter:t,strides:i,pad:"same"===a?"same":"valid",dilations:r,dataFormat:"NHWC",bias:n,activation:o}),"channelsFirst"===s&&(l=hi(l,[0,3,1,2])),l}))}Qp.className="Softmax",yi(Qp);class sd extends Dc{constructor(e,t){if(super(t),this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",sd.verifyArgs(t),this.rank=e,ol(this.rank,"rank"),1!==this.rank&&2!==this.rank&&3!==this.rank)throw new Uo(`Convolution layer for rank other than 1, 2, or 3 (${this.rank}) is not implemented yet.`);if(this.kernelSize=Xp(t.kernelSize,e,"kernelSize"),this.strides=Xp(null==t.strides?1:t.strides,e,"strides"),this.padding=null==t.padding?"valid":t.padding,kl(this.padding),this.dataFormat=null==t.dataFormat?"channelsLast":t.dataFormat,wl(this.dataFormat),this.activation=Pp(t.activation),this.useBias=null==t.useBias||t.useBias,this.biasInitializer=yc(t.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.biasConstraint=ph(t.biasConstraint),this.biasRegularizer=Kp(t.biasRegularizer),this.activityRegularizer=Kp(t.activityRegularizer),this.dilationRate=Xp(null==t.dilationRate?1:t.dilationRate,e,"dilationRate"),1===this.rank&&Array.isArray(this.dilationRate)&&1!==this.dilationRate.length)throw new Bo(`dilationRate must be a number or an array of a single number for 1D convolution, but received ${JSON.stringify(this.dilationRate)}`);if(2===this.rank){if("number"==typeof this.dilationRate)this.dilationRate=[this.dilationRate,this.dilationRate];else if(2!==this.dilationRate.length)throw new Bo(`dilationRate must be a number or array of two numbers for 2D convolution, but received ${JSON.stringify(this.dilationRate)}`)}else if(3===this.rank)if("number"==typeof this.dilationRate)this.dilationRate=[this.dilationRate,this.dilationRate,this.dilationRate];else if(3!==this.dilationRate.length)throw new Bo(`dilationRate must be a number or array of three numbers for 3D convolution, but received ${JSON.stringify(this.dilationRate)}`)}static verifyArgs(e){if(Ko("kernelSize"in e,"required key 'kernelSize' not in config"),"number"!=typeof e.kernelSize&&!rl(e.kernelSize,"number",1,3))throw new Bo(`BaseConv expects config.kernelSize to be number or number[] with length 1, 2, or 3, but received ${JSON.stringify(e.kernelSize)}.`)}getConfig(){const e={kernelSize:this.kernelSize,strides:this.strides,padding:this.padding,dataFormat:this.dataFormat,dilationRate:this.dilationRate,activation:Mp(this.activation),useBias:this.useBias,biasInitializer:vc(this.biasInitializer),biasRegularizer:Vp(this.biasRegularizer),activityRegularizer:Vp(this.activityRegularizer),biasConstraint:uh(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}}class rd extends sd{constructor(e,t){super(e,t),this.kernel=null,rd.verifyArgs(t),this.filters=t.filters,ol(this.filters,"filters"),this.kernelInitializer=yc(t.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.kernelConstraint=ph(t.kernelConstraint),this.kernelRegularizer=Kp(t.kernelRegularizer)}build(e){e=xc(e);const t="channelsFirst"===this.dataFormat?1:e.length-1;if(null==e[t])throw new Bo(`The channel dimension of the input should be defined. Found ${e[t]}`);const n=e[t],i=this.kernelSize.concat([n,this.filters]);this.kernel=this.addWeight("kernel",i,null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[{ndim:this.rank+2,axes:{[t]:n}}],this.built=!0}call(e,t){return si((()=>{let t;e=kc(e);const n=null==this.bias?null:this.bias.read(),i=cl(this.activation.getClassName());if(null!=i&&2===this.rank)t=ad(e,this.kernel.read(),n,this.strides,this.padding,this.dataFormat,this.dilationRate,i);else{if(1===this.rank)t=function(e,t,n,i=1,a="valid",s,r=1){return si((()=>{if(null==s&&(s="channelsLast"),wl(s),3!==e.shape.length)throw new Bo(`The input of a conv1dWithBias operation should be 3, but is ${e.shape.length} instead.`);if(3!==t.shape.length)throw new Bo(`The kernel for a conv1dWithBias operation should be 3, but is ${t.shape.length} instead`);if(null!=n&&1!==n.shape.length)throw new Bo(`The bias for a conv1dWithBias operation should be 1, but is ${t.shape.length} instead`);if("channelsFirst"===s&&(e=hi(e,[0,2,1])),"causal"===a)throw new Uo("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");let o=aa(e,t,i,"same"===a?"same":"valid","NWC",r);return null!=n&&(o=Hl(o,n)),o}))}(e,this.kernel.read(),n,this.strides[0],this.padding,this.dataFormat,this.dilationRate[0]);else if(2===this.rank)t=ad(e,this.kernel.read(),n,this.strides,this.padding,this.dataFormat,this.dilationRate);else{if(3!==this.rank)throw new Uo("convolutions greater than 3D are not implemented yet.");t=function(e,t,n,i=[1,1,1],a="valid",s,r){return si((()=>{if(null==s&&(s="channelsLast"),wl(s),4!==e.rank&&5!==e.rank)throw new Bo(`conv3dWithBias expects input to be of rank 4 or 5, but received ${e.rank}.`);if(4!==t.rank&&5!==t.rank)throw new Bo(`conv3dWithBias expects kernel to be of rank 4 or 5, but received ${e.rank}.`);let o=id(e,s);if("causal"===a)throw new Uo("The support for CAUSAL padding mode in conv3dWithBias is not implemented yet.");return o=oa(o,t,i,"same"===a?"same":"valid","NDHWC",r),null!=n&&(o=Hl(o,n)),"channelsFirst"===s&&(o=hi(o,[0,4,1,2,3])),o}))}(e,this.kernel.read(),n,this.strides,this.padding,this.dataFormat,this.dilationRate)}null!=this.activation&&(t=this.activation.apply(t))}return t}))}computeOutputShape(e){e=xc(e);const t=[],n="channelsLast"===this.dataFormat?e.slice(1,e.length-1):e.slice(2);for(let e=0;e<n.length;++e){const i=ed(n[e],this.kernelSize[e],this.padding,this.strides[e],"number"==typeof this.dilationRate?this.dilationRate:this.dilationRate[e]);t.push(i)}let i=[e[0]];return"channelsLast"===this.dataFormat?(i=i.concat(t),i.push(this.filters)):(i.push(this.filters),i=i.concat(t)),i}getConfig(){const e={filters:this.filters,kernelInitializer:vc(this.kernelInitializer),kernelRegularizer:Vp(this.kernelRegularizer),kernelConstraint:uh(this.kernelConstraint)},t=super.getConfig();return Object.assign(e,t),e}static verifyArgs(e){if(!("filters"in e)||"number"!=typeof e.filters||e.filters<1)throw new Bo(`Convolution layer expected config.filters to be a 'number' > 0 but got ${JSON.stringify(e.filters)}`)}}class od extends rd{constructor(e){super(2,e),od.verifyArgs(e)}getConfig(){const e=super.getConfig();return delete e.rank,e}static verifyArgs(e){if("number"!=typeof e.kernelSize&&!rl(e.kernelSize,"number",1,2))throw new Bo(`Conv2D expects config.kernelSize to be number or number[] with length 1 or 2, but received ${JSON.stringify(e.kernelSize)}.`)}}od.className="Conv2D",yi(od);class ld extends rd{constructor(e){super(3,e),ld.verifyArgs(e)}getConfig(){const e=super.getConfig();return delete e.rank,e}static verifyArgs(e){if("number"!=typeof e.kernelSize&&(!Array.isArray(e.kernelSize)||1!==e.kernelSize.length&&3!==e.kernelSize.length))throw new Bo(`Conv3D expects config.kernelSize to be number or [number, number, number], but received ${JSON.stringify(e.kernelSize)}.`)}}ld.className="Conv3D",yi(ld);class cd extends od{constructor(e){if(super(e),this.inputSpec=[new Cc({ndim:4})],"same"!==this.padding&&"valid"!==this.padding)throw new Bo(`Conv2DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(e){if(4!==(e=xc(e)).length)throw new Bo("Input should have rank 4; Received input shape: "+JSON.stringify(e));const t="channelsFirst"===this.dataFormat?1:e.length-1;if(null==e[t])throw new Bo("The channel dimension of the inputs should be defined. Found `None`.");const n=e[t],i=this.kernelSize.concat([this.filters,n]);this.kernel=this.addWeight("kernel",i,"float32",this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[new Cc({ndim:4,axes:{[t]:n}})],this.built=!0}call(e,t){return si((()=>{let t=kc(e);if(4!==t.shape.length)throw new Bo(`Conv2DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-${t.shape.length}`);const n=t.shape,i=n[0];let a,s;"channelsFirst"===this.dataFormat?(a=2,s=3):(a=1,s=2);const r=n[a],o=n[s],l=this.kernelSize[0],c=this.kernelSize[1],u=this.strides[0],h=this.strides[1],p=[i,td(r,u,l,this.padding),td(o,h,c,this.padding),this.filters];"channelsLast"!==this.dataFormat&&(t=hi(t,[0,2,3,1]));let d=ra(t,this.kernel.read(),p,this.strides,this.padding);return"channelsLast"!==this.dataFormat&&(d=hi(d,[0,3,1,2])),null!=this.bias&&(d=Hl(d,this.bias.read(),this.dataFormat)),null!=this.activation&&(d=this.activation.apply(d)),d}))}computeOutputShape(e){const t=(e=xc(e)).slice();let n,i,a;"channelsFirst"===this.dataFormat?(n=1,i=2,a=3):(n=3,i=1,a=2);const s=this.kernelSize[0],r=this.kernelSize[1],o=this.strides[0],l=this.strides[1];return t[n]=this.filters,t[i]=td(t[i],o,s,this.padding),t[a]=td(t[a],l,r,this.padding),t}getConfig(){const e=super.getConfig();return delete e.dilationRate,e}}cd.className="Conv2DTranspose",yi(cd);class ud extends ld{constructor(e){if(super(e),this.inputSpec=[new Cc({ndim:5})],"same"!==this.padding&&"valid"!==this.padding)throw new Bo(`Conv3DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(e){if(5!==(e=xc(e)).length)throw new Bo("Input should have rank 5; Received input shape: "+JSON.stringify(e));const t="channelsFirst"===this.dataFormat?1:e.length-1;if(null==e[t])throw new Bo("The channel dimension of the inputs should be defined. Found `None`.");const n=e[t],i=this.kernelSize.concat([this.filters,n]);this.kernel=this.addWeight("kernel",i,"float32",this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[new Cc({ndim:5,axes:{[t]:n}})],this.built=!0}call(e,t){return si((()=>{let t=kc(e);if(5!==t.shape.length)throw new Bo(`Conv3DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-${t.shape.length}`);const n=t.shape,i=n[0];let a,s,r;"channelsFirst"===this.dataFormat?(r=2,a=3,s=4):(r=1,a=2,s=3);const o=n[r],l=n[a],c=n[s],u=this.kernelSize[0],h=this.kernelSize[1],p=this.kernelSize[2],d=this.strides[0],m=this.strides[1],f=this.strides[2],g=[i,td(o,d,u,this.padding),td(l,m,h,this.padding),td(c,f,p,this.padding),this.filters];"channelsLast"!==this.dataFormat&&(t=hi(t,[0,2,3,4,1]));let v=ca(t,this.kernel.read(),g,this.strides,this.padding);return"channelsLast"!==this.dataFormat&&(v=hi(v,[0,4,1,2,3])),null!==this.bias&&(v=Hl(v,this.bias.read(),this.dataFormat)),null!==this.activation&&(v=this.activation.apply(v)),v}))}computeOutputShape(e){const t=(e=xc(e)).slice();let n,i,a,s;"channelsFirst"===this.dataFormat?(n=1,i=2,a=3,s=4):(n=4,i=1,a=2,s=3);const r=this.kernelSize[0],o=this.kernelSize[1],l=this.kernelSize[2],c=this.strides[0],u=this.strides[1],h=this.strides[2];return t[n]=this.filters,t[i]=td(t[i],c,r,this.padding),t[a]=td(t[a],u,o,this.padding),t[s]=td(t[s],h,l,this.padding),t}getConfig(){const e=super.getConfig();return delete e.dilationRate,e}}ud.className="Conv3DTranspose",yi(ud);class hd extends rd{constructor(e,t){if(super(e,t),this.DEFAULT_DEPTHWISE_INITIALIZER="glorotUniform",this.DEFAULT_POINTWISE_INITIALIZER="glorotUniform",this.depthwiseKernel=null,this.pointwiseKernel=null,null==t.filters)throw new Bo("The `filters` configuration field is required by SeparableConv, but is unspecified.");if(null!=t.kernelInitializer||null!=t.kernelRegularizer||null!=t.kernelConstraint)throw new Bo("Fields kernelInitializer, kernelRegularizer and kernelConstraint are invalid for SeparableConv2D. Use depthwiseInitializer, depthwiseRegularizer, depthwiseConstraint, pointwiseInitializer, pointwiseRegularizer and pointwiseConstraint instead.");if(null!=t.padding&&"same"!==t.padding&&"valid"!==t.padding)throw new Bo(`SeparableConv${this.rank}D supports only padding modes: 'same' and 'valid', but received ${JSON.stringify(t.padding)}`);this.depthMultiplier=null==t.depthMultiplier?1:t.depthMultiplier,this.depthwiseInitializer=yc(t.depthwiseInitializer||this.DEFAULT_DEPTHWISE_INITIALIZER),this.depthwiseRegularizer=Kp(t.depthwiseRegularizer),this.depthwiseConstraint=ph(t.depthwiseConstraint),this.pointwiseInitializer=yc(t.depthwiseInitializer||this.DEFAULT_POINTWISE_INITIALIZER),this.pointwiseRegularizer=Kp(t.pointwiseRegularizer),this.pointwiseConstraint=ph(t.pointwiseConstraint)}build(e){if((e=xc(e)).length<this.rank+2)throw new Bo(`Inputs to SeparableConv${this.rank}D should have rank ${this.rank+2}, but received input shape: ${JSON.stringify(e)}`);const t="channelsFirst"===this.dataFormat?1:e.length-1;if(null==e[t]||e[t]<0)throw new Bo(`The channel dimension of the inputs should be defined, but found ${JSON.stringify(e[t])}`);const n=e[t],i=this.kernelSize.concat([n,this.depthMultiplier]),a=[];for(let e=0;e<this.rank;++e)a.push(1);a.push(n*this.depthMultiplier,this.filters);const s=!0;this.depthwiseKernel=this.addWeight("depthwise_kernel",i,"float32",this.depthwiseInitializer,this.depthwiseRegularizer,s,this.depthwiseConstraint),this.pointwiseKernel=this.addWeight("pointwise_kernel",a,"float32",this.pointwiseInitializer,this.pointwiseRegularizer,s,this.pointwiseConstraint),this.useBias?this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,s,this.biasConstraint):this.bias=null,this.inputSpec=[new Cc({ndim:this.rank+2,axes:{[t]:n}})],this.built=!0}call(e,t){return si((()=>{let t;if(e=kc(e),1===this.rank)throw new Uo("1D separable convolution is not implemented yet.");return 2===this.rank&&("channelsFirst"===this.dataFormat&&(e=hi(e,[0,2,3,1])),t=Ds(e,this.depthwiseKernel.read(),this.pointwiseKernel.read(),this.strides,this.padding,this.dilationRate,"NHWC")),this.useBias&&(t=Hl(t,this.bias.read(),this.dataFormat)),null!=this.activation&&(t=this.activation.apply(t)),"channelsFirst"===this.dataFormat&&(t=hi(t,[0,3,1,2])),t}))}getConfig(){const e=super.getConfig();return delete e.rank,delete e.kernelInitializer,delete e.kernelRegularizer,delete e.kernelConstraint,e.depthwiseInitializer=vc(this.depthwiseInitializer),e.pointwiseInitializer=vc(this.pointwiseInitializer),e.depthwiseRegularizer=Vp(this.depthwiseRegularizer),e.pointwiseRegularizer=Vp(this.pointwiseRegularizer),e.depthwiseConstraint=uh(this.depthwiseConstraint),e.pointwiseConstraint=uh(this.pointwiseConstraint),e}}hd.className="SeparableConv";class pd extends hd{constructor(e){super(2,e)}}pd.className="SeparableConv2D",yi(pd);class dd extends rd{constructor(e){super(1,e),dd.verifyArgs(e),this.inputSpec=[{ndim:3}]}getConfig(){const e=super.getConfig();return delete e.rank,delete e.dataFormat,e}static verifyArgs(e){if("number"!=typeof e.kernelSize&&!rl(e.kernelSize,"number",1,1))throw new Bo(`Conv1D expects config.kernelSize to be number or number[] with length 1, but received ${JSON.stringify(e.kernelSize)}.`)}}dd.className="Conv1D",yi(dd);class md extends Dc{constructor(e){super(e),"number"==typeof e.cropping?this.cropping=[[e.cropping,e.cropping],[e.cropping,e.cropping]]:"number"==typeof e.cropping[0]?this.cropping=[[e.cropping[0],e.cropping[0]],[e.cropping[1],e.cropping[1]]]:this.cropping=e.cropping,this.dataFormat=void 0===e.dataFormat?"channelsLast":e.dataFormat,this.inputSpec=[{ndim:4}]}computeOutputShape(e){return"channelsFirst"===this.dataFormat?[e[0],e[1],e[2]-this.cropping[0][0]-this.cropping[0][1],e[3]-this.cropping[1][0]-this.cropping[1][1]]:[e[0],e[1]-this.cropping[0][0]-this.cropping[0][1],e[2]-this.cropping[1][0]-this.cropping[1][1],e[3]]}call(e,t){return si((()=>{if(e=kc(e),"channelsLast"===this.dataFormat){const t=Ol(e,this.cropping[0][0],e.shape[1]-this.cropping[0][0]-this.cropping[0][1],2);return Ol(t,this.cropping[1][0],e.shape[2]-this.cropping[1][1]-this.cropping[1][0],3)}{const t=Ol(e,this.cropping[0][0],e.shape[2]-this.cropping[0][0]-this.cropping[0][1],3);return Ol(t,this.cropping[1][0],e.shape[3]-this.cropping[1][1]-this.cropping[1][0],4)}}))}getConfig(){const e={cropping:this.cropping,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}md.className="Cropping2D",yi(md);class fd extends Dc{constructor(e){var t;super(e),this.DEFAULT_SIZE=[2,2],this.inputSpec=[{ndim:4}],this.size=null==e.size?this.DEFAULT_SIZE:e.size,this.dataFormat=null==e.dataFormat?"channelsLast":e.dataFormat,wl(this.dataFormat),this.interpolation=null==e.interpolation?"nearest":e.interpolation,t=this.interpolation,sl(fl,"InterpolationFormat",t)}computeOutputShape(e){if("channelsFirst"===this.dataFormat){const t=null==e[2]?null:this.size[0]*e[2],n=null==e[3]?null:this.size[1]*e[3];return[e[0],e[1],t,n]}{const t=null==e[1]?null:this.size[0]*e[1],n=null==e[2]?null:this.size[1]*e[2];return[e[0],t,n,e[3]]}}call(e,t){return si((()=>{let t=kc(e);const n=t.shape;if("channelsFirst"===this.dataFormat){t=hi(t,[0,2,3,1]);const e=this.size[0]*n[2],i=this.size[1]*n[3],a="nearest"===this.interpolation?zr.resizeNearestNeighbor(t,[e,i]):zr.resizeBilinear(t,[e,i]);return hi(a,[0,3,1,2])}{const e=this.size[0]*n[1],i=this.size[1]*n[2];return"nearest"===this.interpolation?zr.resizeNearestNeighbor(t,[e,i]):zr.resizeBilinear(t,[e,i])}}))}getConfig(){const e={size:this.size,dataFormat:this.dataFormat,interpolation:this.interpolation},t=super.getConfig();return Object.assign(e,t),e}}fd.className="UpSampling2D",yi(fd);class gd extends sd{constructor(e){super(2,e),this.depthwiseKernel=null,this.depthMultiplier=null==e.depthMultiplier?1:e.depthMultiplier,this.depthwiseInitializer=yc(e.depthwiseInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.depthwiseConstraint=ph(e.depthwiseConstraint),this.depthwiseRegularizer=Kp(e.depthwiseRegularizer)}build(e){if((e=xc(e)).length<4)throw new Bo(`Inputs to DepthwiseConv2D should have rank 4. Received input shape: ${JSON.stringify(e)}.`);const t="channelsFirst"===this.dataFormat?1:3;if(null==e[t]||e[t]<0)throw new Bo(`The channel dimension of the inputs to DepthwiseConv2D should be defined, but is not (${e[t]}).`);const n=e[t],i=[this.kernelSize[0],this.kernelSize[1],n,this.depthMultiplier];this.depthwiseKernel=this.addWeight("depthwise_kernel",i,null,this.depthwiseInitializer,this.depthwiseRegularizer,!0,this.depthwiseConstraint),this.useBias?this.bias=this.addWeight("bias",[n*this.depthMultiplier],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(e,t){return si((()=>{let t=
4495
4495
  /**
4496
4496
  * @license
4497
4497
  * Copyright 2018 Google LLC
@@ -4501,7 +4501,7 @@ function Xp(e,t,n){if("number"==typeof e)return Vo(e,t);if(e.length!==t)throw ne
4501
4501
  * https://opensource.org/licenses/MIT.
4502
4502
  * =============================================================================
4503
4503
  */
4504
- function(e,t,n=[1,1],i="valid",a,s){return si((()=>{null==a&&(a="channelsLast"),wl(a);let r=nd(e,a);if(4!==e.rank)throw new Bo(`Input for depthwiseConv2d is required to be 4-D, but is instead ${e.rank}-D`);if(4!==t.rank)throw new Bo(`depthwiseKernel is required to be 4-D, but is instead ${t.rank}-D`);return r=fa(r,t,n,"same"===i?"same":"valid","NHWC",s),"channelsFirst"===a&&(r=hi(r,[0,3,1,2])),r}))}(e=kc(e),this.depthwiseKernel.read(),this.strides,this.padding,this.dataFormat,null);return this.useBias&&(t=Hl(t,this.bias.read(),this.dataFormat)),null!=this.activation&&(t=this.activation.apply(t)),t}))}computeOutputShape(e){e=xc(e);const t="channelsFirst"===this.dataFormat?e[2]:e[1],n="channelsFirst"===this.dataFormat?e[3]:e[2],i="channelsFirst"===this.dataFormat?e[1]*this.depthMultiplier:e[3]*this.depthMultiplier,a=ed(t,this.kernelSize[0],this.padding,this.strides[0]),s=ed(n,this.kernelSize[1],this.padding,this.strides[1]);return"channelsFirst"===this.dataFormat?[e[0],i,a,s]:[e[0],a,s,i]}getConfig(){const e=super.getConfig();return e.depthMultiplier=this.depthMultiplier,e.depthwiseInitializer=vc(this.depthwiseInitializer),e.depthwiseRegularizer=Gp(this.depthwiseRegularizer),e.depthwiseConstraint=uh(this.depthwiseRegularizer),e}}
4504
+ function(e,t,n=[1,1],i="valid",a,s){return si((()=>{null==a&&(a="channelsLast"),wl(a);let r=nd(e,a);if(4!==e.rank)throw new Bo(`Input for depthwiseConv2d is required to be 4-D, but is instead ${e.rank}-D`);if(4!==t.rank)throw new Bo(`depthwiseKernel is required to be 4-D, but is instead ${t.rank}-D`);return r=fa(r,t,n,"same"===i?"same":"valid","NHWC",s),"channelsFirst"===a&&(r=hi(r,[0,3,1,2])),r}))}(e=kc(e),this.depthwiseKernel.read(),this.strides,this.padding,this.dataFormat,null);return this.useBias&&(t=Hl(t,this.bias.read(),this.dataFormat)),null!=this.activation&&(t=this.activation.apply(t)),t}))}computeOutputShape(e){e=xc(e);const t="channelsFirst"===this.dataFormat?e[2]:e[1],n="channelsFirst"===this.dataFormat?e[3]:e[2],i="channelsFirst"===this.dataFormat?e[1]*this.depthMultiplier:e[3]*this.depthMultiplier,a=ed(t,this.kernelSize[0],this.padding,this.strides[0]),s=ed(n,this.kernelSize[1],this.padding,this.strides[1]);return"channelsFirst"===this.dataFormat?[e[0],i,a,s]:[e[0],a,s,i]}getConfig(){const e=super.getConfig();return e.depthMultiplier=this.depthMultiplier,e.depthwiseInitializer=vc(this.depthwiseInitializer),e.depthwiseRegularizer=Vp(this.depthwiseRegularizer),e.depthwiseConstraint=uh(this.depthwiseRegularizer),e}}
4505
4505
  /**
4506
4506
  * @license
4507
4507
  * Copyright 2018 Google LLC
@@ -4511,7 +4511,7 @@ function(e,t,n=[1,1],i="valid",a,s){return si((()=>{null==a&&(a="channelsLast"),
4511
4511
  * https://opensource.org/licenses/MIT.
4512
4512
  * =============================================================================
4513
4513
  */
4514
- function vd(e,t,n,i){if(Array.isArray(e)){if(null!=t||null!=n)throw new Bo("When inputs is an array, neither initialState or constants should be provided");null!=i&&(n=e.slice(e.length-i,e.length),e=e.slice(0,e.length-i)),e.length>1&&(t=e.slice(1,e.length)),e=e[0]}function a(e){return null==e||Array.isArray(e)?e:[e]}return{inputs:e,initialState:t=a(t),constants:n=a(n)}}function yd(e,t,n,i=!1,a,s,r=!1,o=!1){return si((()=>{const l=t.shape.length;if(l<3)throw new Bo(`Input should be at least 3D, but is ${l}D.`);const c=[1,0].concat(zl(2,l));if(t=hi(t,c),null!=s)throw new Uo("The rnn() functoin of the deeplearn.js backend does not support constants yet.");r&&console.warn("Backend rnn(): the unroll = true option is not applicable to the imperative deeplearn.js backend."),null!=a&&((a=ei(ei(a,"bool"),"float32")).rank===l-1&&(a=_a(a,-1)),a=hi(a,c)),i&&(t=Cs(t,0),null!=a&&(a=Cs(a,0)));const u=[];let h,p=n;const d=t.shape[0],m=Js(t);let f,g;null!=a&&(f=Js(a));for(let t=0;t<d;++t){const n=m[t],i=si((()=>e(n,p)));if(null==a)h=i[0],p=i[1];else{const e=si((()=>{const e=f[t],n=Ja(ls(e),e);return{output:bi(xi(i[0],e),xi(p[0],n)),newStates:p.map(((t,a)=>bi(xi(i[1][a],e),xi(t,n))))}}));h=e.output,p=e.newStates}o&&u.push(h)}if(o){g=Ws(u,1)}return[h,g,p]}))}gd.className="DepthwiseConv2D",yi(gd);class bd extends Dc{constructor(e){let t;if(super(e),null==e.cell)throw new Bo("cell property is missing for the constructor of RNN.");if(t=Array.isArray(e.cell)?new Ed({cells:e.cell}):e.cell,null==t.stateSize)throw new Bo("The RNN cell should have an attribute `stateSize` (tuple of integers, one integer per RNN state).");this.cell=t,this.returnSequences=null!=e.returnSequences&&e.returnSequences,this.returnState=null!=e.returnState&&e.returnState,this.goBackwards=null!=e.goBackwards&&e.goBackwards,this._stateful=null!=e.stateful&&e.stateful,this.unroll=null!=e.unroll&&e.unroll,this.supportsMasking=!0,this.inputSpec=[new Ac({ndim:3})],this.stateSpec=null,this.states_=null,this.numConstants=null,this.keptStates=[]}getStates(){if(null==this.states_){return zl(0,Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1).map((e=>null))}return this.states_}setStates(e){this.states_=e}computeOutputShape(e){bc(e)&&(e=e[0]);let t=this.cell.stateSize;Array.isArray(t)||(t=[t]);const n=t[0];let i;if(i=this.returnSequences?[e[0],e[1],n]:[e[0],n],this.returnState){const n=[];for(const i of t)n.push([e[0],i]);return[i].concat(n)}return i}computeMask(e,t){return si((()=>{Array.isArray(t)&&(t=t[0]);const e=this.returnSequences?t:null;if(this.returnState){const t=this.states.map((e=>null));return[e].concat(t)}return e}))}get states(){if(null==this.states_){const e=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1,t=[];for(let n=0;n<e;++n)t.push(null);return t}return this.states_}set states(e){this.states_=e}build(e){if(null!=this.numConstants)throw new Uo("Constants support is not implemented in RNN yet.");bc(e)&&(e=e[0]);const t=this.stateful?e[0]:null,n=e.slice(2);this.inputSpec[0]=new Ac({shape:[t,null,...n]});const i=[e[0]].concat(e.slice(2));let a;if(this.cell.build(i),a=Array.isArray(this.cell.stateSize)?this.cell.stateSize:[this.cell.stateSize],null!=this.stateSpec){if(!C(this.stateSpec.map((e=>e.shape[e.shape.length-1])),a))throw new Bo(`An initialState was passed that is not compatible with cell.stateSize. Received stateSpec=${this.stateSpec}; However cell.stateSize is ${this.cell.stateSize}`)}else this.stateSpec=a.map((e=>new Ac({shape:[null,e]})));this.stateful&&this.resetStates()}resetStates(e,t=!1){si((()=>{if(!this.stateful)throw new Oo("Cannot call resetStates() on an RNN Layer that is not stateful.");const n=this.inputSpec[0].shape[0];if(null==n)throw new Bo("If an RNN is stateful, it needs to know its batch size. Specify the batch size of your input tensors: \n- If using a Sequential model, specify the batch size by passing a `batchInputShape` option to your first layer.\n- If using the functional API, specify the batch size by passing a `batchShape` option to your Input layer.");if(null==this.states_)Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map((e=>is([n,e]))):this.states_=[is([n,this.cell.stateSize])];else if(null==e)ri(this.states_),null!=this.keptStates&&(ri(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map((e=>is([n,e]))):this.states_[0]=is([n,this.cell.stateSize]);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new Bo(`Layer ${this.name} expects ${this.states_.length} state(s), but it received ${e.length} state value(s). Input received: ${e}`);!0===t?this.keptStates.push(this.states_.slice()):ri(this.states_);for(let t=0;t<this.states_.length;++t){const i=e[t],a=Array.isArray(this.cell.stateSize)?this.cell.stateSize[t]:this.cell.stateSize,s=[n,a];if(!C(i.shape,s))throw new Bo(`State ${t} is incompatible with layer ${this.name}: expected shape=${s}, received shape=${i.shape}`);this.states_[t]=i}}this.states_=this.states_.map((e=>oi(e.clone())))}))}apply(e,t){let n=null==t?null:t.initialState,i=null==t?null:t.constants;null==t&&(t={});const a=vd(e,n,i,this.numConstants);e=a.inputs,n=a.initialState,i=a.constants;let s=[],r=[];if(null!=n){t.initialState=n,s=s.concat(n),this.stateSpec=[];for(const e of n)this.stateSpec.push(new Ac({shape:e.shape}));r=r.concat(this.stateSpec)}null!=i&&(t.constants=i,s=s.concat(i),this.numConstants=i.length);if(s[0]instanceof Cc){const n=[e].concat(s),i=this.inputSpec.concat(r),a=this.inputSpec;this.inputSpec=i;const o=super.apply(n,t);return this.inputSpec=a,o}return super.apply(e,t)}call(e,t){return si((()=>{const n=null==t?null:t.mask,i=null==t?null:t.training;let a=null==t?null:t.initialState;e=kc(e),null==a&&(a=this.stateful?this.states_:this.getInitialState(e));const s=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1;if(a.length!==s)throw new Bo(`RNN Layer has ${s} state(s) but was passed ${a.length} initial state(s).`);this.unroll&&console.warn("Ignoring unroll = true for RNN layer, due to imperative backend.");const r={training:i},o=yd(((e,t)=>{const n=this.cell.call([e].concat(t),r);return[n[0],n.slice(1)]}),e,a,this.goBackwards,n,null,this.unroll,this.returnSequences),l=o[0],c=o[1],u=o[2];this.stateful&&this.resetStates(u,i);const h=this.returnSequences?c:l;return this.returnState?[h].concat(u):h}))}getInitialState(e){return si((()=>{let t=is(e.shape);return t=ja(t,[1,2]),t=Rl(t),Array.isArray(this.cell.stateSize)?this.cell.stateSize.map((e=>e>1?Ul(t,[1,e]):t)):this.cell.stateSize>1?[Ul(t,[1,this.cell.stateSize])]:[t]}))}get trainableWeights(){return this.trainable?this.cell.trainableWeights:[]}get nonTrainableWeights(){return this.trainable?this.cell.nonTrainableWeights:this.cell.weights}setFastWeightInitDuringBuild(e){super.setFastWeightInitDuringBuild(e),null!=this.cell&&this.cell.setFastWeightInitDuringBuild(e)}getConfig(){const e=super.getConfig(),t={returnSequences:this.returnSequences,returnState:this.returnState,goBackwards:this.goBackwards,stateful:this.stateful,unroll:this.unroll};null!=this.numConstants&&(t.numConstants=this.numConstants);const n=this.cell.getConfig();return this.getClassName()===bd.className&&(t.cell={className:this.cell.getClassName(),config:n}),Object.assign(Object.assign(Object.assign({},n),e),t)}static fromConfig(e,t,n={}){const i=Nh(t.cell,n);return new e(Object.assign(t,{cell:i}))}}bd.className="RNN",yi(bd);class wd extends Dc{}class kd extends wd{constructor(e){super(e),this.DEFAULT_ACTIVATION="tanh",this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_RECURRENT_INITIALIZER="orthogonal",this.DEFAULT_BIAS_INITIALIZER="zeros",this.units=e.units,ol(this.units,"units"),this.activation=Pp(null==e.activation?this.DEFAULT_ACTIVATION:e.activation),this.useBias=null==e.useBias||e.useBias,this.kernelInitializer=yc(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=yc(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=yc(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=Kp(e.kernelRegularizer),this.recurrentRegularizer=Kp(e.recurrentRegularizer),this.biasRegularizer=Kp(e.biasRegularizer),this.kernelConstraint=ph(e.kernelConstraint),this.recurrentConstraint=ph(e.recurrentConstraint),this.biasConstraint=ph(e.biasConstraint),this.dropout=$l([1,jl([0,null==e.dropout?0:e.dropout])]),this.recurrentDropout=$l([1,jl([0,null==e.recurrentDropout?0:e.recurrentDropout])]),this.dropoutFunc=e.dropoutFunc,this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){e=xc(e),this.kernel=this.addWeight("kernel",[e[e.length-1],this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,this.units],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias?this.bias=this.addWeight("bias",[this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(e,t){return si((()=>{if(2!==e.length)throw new Bo(`SimpleRNNCell expects 2 input Tensors, got ${e.length}.`);let n=e[1];e=e[0];const i=null!=t.training&&t.training;let a;0<this.dropout&&this.dropout<1&&null==this.dropoutMask&&(this.dropoutMask=Ad({ones:()=>ls(e),rate:this.dropout,training:i,dropoutFunc:this.dropoutFunc})),0<this.recurrentDropout&&this.recurrentDropout<1&&null==this.recurrentDropoutMask&&(this.recurrentDropoutMask=Ad({ones:()=>ls(n),rate:this.recurrentDropout,training:i,dropoutFunc:this.dropoutFunc}));const s=this.dropoutMask,r=this.recurrentDropoutMask;a=Gl(null!=s?xi(e,s):e,this.kernel.read()),null!=this.bias&&(a=Hl(a,this.bias.read())),null!=r&&(n=xi(n,r));let o=bi(a,Gl(n,this.recurrentKernel.read()));return null!=this.activation&&(o=this.activation.apply(o)),[o,o]}))}getConfig(){const e=super.getConfig(),t={units:this.units,activation:Mp(this.activation),useBias:this.useBias,kernelInitializer:vc(this.kernelInitializer),recurrentInitializer:vc(this.recurrentInitializer),biasInitializer:vc(this.biasInitializer),kernelRegularizer:Gp(this.kernelRegularizer),recurrentRegularizer:Gp(this.recurrentRegularizer),biasRegularizer:Gp(this.biasRegularizer),activityRegularizer:Gp(this.activityRegularizer),kernelConstraint:uh(this.kernelConstraint),recurrentConstraint:uh(this.recurrentConstraint),biasConstraint:uh(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout};return Object.assign(Object.assign({},e),t)}}kd.className="SimpleRNNCell",yi(kd);class xd extends bd{constructor(e){e.cell=new kd(e),super(e)}call(e,t){return si((()=>{null!=this.cell.dropoutMask&&(ri(this.cell.dropoutMask),this.cell.dropoutMask=null),null!=this.cell.recurrentDropoutMask&&(ri(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);const n=null==t?null:t.mask,i=null==t?null:t.training,a=null==t?null:t.initialState;return super.call(e,{mask:n,training:i,initialState:a})}))}static fromConfig(e,t){return new e(t)}}xd.className="SimpleRNN",yi(xd);class Sd extends wd{constructor(e){if(super(e),this.DEFAULT_ACTIVATION="tanh",this.DEFAULT_RECURRENT_ACTIVATION="hardSigmoid",this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_RECURRENT_INITIALIZER="orthogonal",this.DEFAULT_BIAS_INITIALIZER="zeros",e.resetAfter)throw new Bo("GRUCell does not support reset_after parameter set to true.");this.units=e.units,ol(this.units,"units"),this.activation=Pp(void 0===e.activation?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=Pp(void 0===e.recurrentActivation?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=null==e.useBias||e.useBias,this.kernelInitializer=yc(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=yc(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=yc(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=Kp(e.kernelRegularizer),this.recurrentRegularizer=Kp(e.recurrentRegularizer),this.biasRegularizer=Kp(e.biasRegularizer),this.kernelConstraint=ph(e.kernelConstraint),this.recurrentConstraint=ph(e.recurrentConstraint),this.biasConstraint=ph(e.biasConstraint),this.dropout=$l([1,jl([0,null==e.dropout?0:e.dropout])]),this.recurrentDropout=$l([1,jl([0,null==e.recurrentDropout?0:e.recurrentDropout])]),this.dropoutFunc=e.dropoutFunc,this.implementation=e.implementation,this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){const t=(e=xc(e))[e.length-1];this.kernel=this.addWeight("kernel",[t,3*this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,3*this.units],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias?this.bias=this.addWeight("bias",[3*this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(e,t){return si((()=>{if(2!==e.length)throw new Bo(`GRUCell expects 2 input Tensors (inputs, h, c), got ${e.length}.`);const n=null!=t.training&&t.training;let i=e[1];e=e[0],0<this.dropout&&this.dropout<1&&null==this.dropoutMask&&(this.dropoutMask=Ad({ones:()=>ls(e),rate:this.dropout,training:n,count:3,dropoutFunc:this.dropoutFunc})),0<this.recurrentDropout&&this.recurrentDropout<1&&null==this.recurrentDropoutMask&&(this.recurrentDropoutMask=Ad({ones:()=>ls(i),rate:this.recurrentDropout,training:n,count:3,dropoutFunc:this.dropoutFunc}));const a=this.dropoutMask,s=this.recurrentDropoutMask;let r,o,l;0<this.dropout&&this.dropout<1&&(e=xi(e,a[0]));let c=Gl(e,this.kernel.read());this.useBias&&(c=Hl(c,this.bias.read())),0<this.recurrentDropout&&this.recurrentDropout<1&&(i=xi(i,s[0]));const u=this.recurrentKernel.read(),[h,p]=Bs(u,[2*this.units,this.units],u.rank-1),d=Gl(i,h),[m,f,g]=Bs(c,3,c.rank-1),[v,y]=Bs(d,2,d.rank-1);r=this.recurrentActivation.apply(bi(m,v)),o=this.recurrentActivation.apply(bi(f,y));const b=Gl(xi(o,i),p);l=this.activation.apply(bi(g,b));const w=bi(xi(r,i),xi(bi(1,ci(r)),l));return[w,w]}))}getConfig(){const e=super.getConfig(),t={units:this.units,activation:Mp(this.activation),recurrentActivation:Mp(this.recurrentActivation),useBias:this.useBias,kernelInitializer:vc(this.kernelInitializer),recurrentInitializer:vc(this.recurrentInitializer),biasInitializer:vc(this.biasInitializer),kernelRegularizer:Gp(this.kernelRegularizer),recurrentRegularizer:Gp(this.recurrentRegularizer),biasRegularizer:Gp(this.biasRegularizer),activityRegularizer:Gp(this.activityRegularizer),kernelConstraint:uh(this.kernelConstraint),recurrentConstraint:uh(this.recurrentConstraint),biasConstraint:uh(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation,resetAfter:!1};return Object.assign(Object.assign({},e),t)}}Sd.className="GRUCell",yi(Sd);class Nd extends bd{constructor(e){0===e.implementation&&console.warn("`implementation=0` has been deprecated, and now defaults to `implementation=1`. Please update your layer call."),e.cell=new Sd(e),super(e)}call(e,t){return si((()=>{null!=this.cell.dropoutMask&&(ri(this.cell.dropoutMask),this.cell.dropoutMask=null),null!=this.cell.recurrentDropoutMask&&(ri(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);const n=null==t?null:t.mask,i=null==t?null:t.training,a=null==t?null:t.initialState;return super.call(e,{mask:n,training:i,initialState:a})}))}static fromConfig(e,t){return 0===t.implmentation&&(t.implementation=1),new e(t)}}Nd.className="GRU",yi(Nd);class Id extends wd{constructor(e){super(e),this.DEFAULT_ACTIVATION="tanh",this.DEFAULT_RECURRENT_ACTIVATION="hardSigmoid",this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_RECURRENT_INITIALIZER="orthogonal",this.DEFAULT_BIAS_INITIALIZER="zeros",this.units=e.units,ol(this.units,"units"),this.activation=Pp(void 0===e.activation?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=Pp(void 0===e.recurrentActivation?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=null==e.useBias||e.useBias,this.kernelInitializer=yc(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=yc(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=yc(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.unitForgetBias=e.unitForgetBias,this.kernelRegularizer=Kp(e.kernelRegularizer),this.recurrentRegularizer=Kp(e.recurrentRegularizer),this.biasRegularizer=Kp(e.biasRegularizer),this.kernelConstraint=ph(e.kernelConstraint),this.recurrentConstraint=ph(e.recurrentConstraint),this.biasConstraint=ph(e.biasConstraint),this.dropout=$l([1,jl([0,null==e.dropout?0:e.dropout])]),this.recurrentDropout=$l([1,jl([0,null==e.recurrentDropout?0:e.recurrentDropout])]),this.dropoutFunc=e.dropoutFunc,this.implementation=e.implementation,this.stateSize=[this.units,this.units],this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){var t;const n=(e=xc(e))[e.length-1];let i;if(this.kernel=this.addWeight("kernel",[n,4*this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,4*this.units],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias){if(this.unitForgetBias){const e=this.biasInitializer,n=this.units;i=new((t=class extends Xl{apply(t,i){const a=e.apply([n]),s=(new tc).apply([n]),r=e.apply([2*n]);return Bl(Bl(a,s),r)}}).className="CustomInit",t)}else i=this.biasInitializer;this.bias=this.addWeight("bias",[4*this.units],null,i,this.biasRegularizer,!0,this.biasConstraint)}else this.bias=null;this.built=!0}call(e,t){return si((()=>{const n=null!=t.training&&t.training;if(3!==e.length)throw new Bo(`LSTMCell expects 3 input Tensors (inputs, h, c), got ${e.length}.`);let i=e[1];const a=e[2];e=e[0],0<this.dropout&&this.dropout<1&&null==this.dropoutMask&&(this.dropoutMask=Ad({ones:()=>ls(e),rate:this.dropout,training:n,count:4,dropoutFunc:this.dropoutFunc})),0<this.recurrentDropout&&this.recurrentDropout<1&&null==this.recurrentDropoutMask&&(this.recurrentDropoutMask=Ad({ones:()=>ls(i),rate:this.recurrentDropout,training:n,count:4,dropoutFunc:this.dropoutFunc}));const s=this.dropoutMask,r=this.recurrentDropoutMask;let o,l,c,u;0<this.dropout&&this.dropout<1&&(e=xi(e,s[0]));let h=Gl(e,this.kernel.read());0<this.recurrentDropout&&this.recurrentDropout<1&&(i=xi(i,r[0])),h=bi(h,Gl(i,this.recurrentKernel.read())),this.useBias&&(h=Hl(h,this.bias.read()));const[p,d,m,f]=Bs(h,4,h.rank-1);o=this.recurrentActivation.apply(p),l=this.recurrentActivation.apply(d),c=bi(xi(l,a),xi(o,this.activation.apply(m))),u=this.recurrentActivation.apply(f);const g=xi(u,this.activation.apply(c));return[g,g,c]}))}getConfig(){const e=super.getConfig(),t={units:this.units,activation:Mp(this.activation),recurrentActivation:Mp(this.recurrentActivation),useBias:this.useBias,kernelInitializer:vc(this.kernelInitializer),recurrentInitializer:vc(this.recurrentInitializer),biasInitializer:vc(this.biasInitializer),unitForgetBias:this.unitForgetBias,kernelRegularizer:Gp(this.kernelRegularizer),recurrentRegularizer:Gp(this.recurrentRegularizer),biasRegularizer:Gp(this.biasRegularizer),activityRegularizer:Gp(this.activityRegularizer),kernelConstraint:uh(this.kernelConstraint),recurrentConstraint:uh(this.recurrentConstraint),biasConstraint:uh(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation};return Object.assign(Object.assign({},e),t)}}Id.className="LSTMCell",yi(Id);class Td extends bd{constructor(e){0===e.implementation&&console.warn("`implementation=0` has been deprecated, and now defaults to `implementation=1`. Please update your layer call."),e.cell=new Id(e),super(e)}call(e,t){return si((()=>{null!=this.cell.dropoutMask&&(ri(this.cell.dropoutMask),this.cell.dropoutMask=null),null!=this.cell.recurrentDropoutMask&&(ri(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);const n=null==t?null:t.mask,i=null==t?null:t.training,a=null==t?null:t.initialState;return super.call(e,{mask:n,training:i,initialState:a})}))}static fromConfig(e,t){return 0===t.implmentation&&(t.implementation=1),new e(t)}}Td.className="LSTM",yi(Td);class Ed extends wd{constructor(e){super(e),this.cells=e.cells}get stateSize(){const e=[];for(const t of this.cells.slice().reverse())Array.isArray(t.stateSize)?e.push(...t.stateSize):e.push(t.stateSize);return e}call(e,t){return si((()=>{let n=e.slice(1);const i=[];for(const e of this.cells.slice().reverse())Array.isArray(e.stateSize)?i.push(n.splice(0,e.stateSize.length)):i.push(n.splice(0,1));i.reverse();const a=[];let s;for(let r=0;r<this.cells.length;++r){const o=this.cells[r];n=i[r],s=0===r?[e[0]].concat(n):[s[0]].concat(n),s=o.call(s,t),a.push(s.slice(1))}n=[];for(const e of a.slice().reverse())n.push(...e);return[s[0]].concat(n)}))}build(e){let t;bc(e)&&(e=e[0]),this.cells.forEach(((n,i)=>{Nl(`RNNCell_${i}`,(()=>{n.build(e),t=Array.isArray(n.stateSize)?n.stateSize[0]:n.stateSize,e=[e[0],t]}))})),this.built=!0}getConfig(){const e=super.getConfig(),t={cells:this.cells.map((e=>({className:e.getClassName(),config:e.getConfig()})))};return Object.assign(Object.assign({},e),t)}static fromConfig(e,t,n={}){const i=[];for(const e of t.cells)i.push(Nh(e,n));return new e({cells:i})}get trainableWeights(){if(!this.trainable)return[];const e=[];for(const t of this.cells)e.push(...t.trainableWeights);return e}get nonTrainableWeights(){const e=[];for(const t of this.cells)e.push(...t.nonTrainableWeights);if(!this.trainable){const t=[];for(const e of this.cells)t.push(...e.trainableWeights);return t.concat(e)}return e}getWeights(){const e=[];for(const t of this.cells)e.push(...t.weights);return Tc(e)}setWeights(e){const t=[];for(const n of this.cells){const i=n.weights.length,a=e.splice(i);for(let e=0;e<n.weights.length;++e)t.push([n.weights[e],a[e]])}Ec(t)}}function Ad(e){const{ones:t,rate:n,training:i=!1,count:a=1,dropoutFunc:s}=e,r=()=>null!=s?s(t(),n):Jl(t(),n),o=()=>Zl(r,t,i);if(!a||a<=1)return oi(o().clone());return Array(a).fill(void 0).map(o).map((e=>oi(e.clone())))}
4514
+ function vd(e,t,n,i){if(Array.isArray(e)){if(null!=t||null!=n)throw new Bo("When inputs is an array, neither initialState or constants should be provided");null!=i&&(n=e.slice(e.length-i,e.length),e=e.slice(0,e.length-i)),e.length>1&&(t=e.slice(1,e.length)),e=e[0]}function a(e){return null==e||Array.isArray(e)?e:[e]}return{inputs:e,initialState:t=a(t),constants:n=a(n)}}function yd(e,t,n,i=!1,a,s,r=!1,o=!1){return si((()=>{const l=t.shape.length;if(l<3)throw new Bo(`Input should be at least 3D, but is ${l}D.`);const c=[1,0].concat(zl(2,l));if(t=hi(t,c),null!=s)throw new Uo("The rnn() functoin of the deeplearn.js backend does not support constants yet.");r&&console.warn("Backend rnn(): the unroll = true option is not applicable to the imperative deeplearn.js backend."),null!=a&&((a=ei(ei(a,"bool"),"float32")).rank===l-1&&(a=_a(a,-1)),a=hi(a,c)),i&&(t=Es(t,0),null!=a&&(a=Es(a,0)));const u=[];let h,p=n;const d=t.shape[0],m=Js(t);let f,g;null!=a&&(f=Js(a));for(let t=0;t<d;++t){const n=m[t],i=si((()=>e(n,p)));if(null==a)h=i[0],p=i[1];else{const e=si((()=>{const e=f[t],n=Ja(ls(e),e);return{output:bi(xi(i[0],e),xi(p[0],n)),newStates:p.map(((t,a)=>bi(xi(i[1][a],e),xi(t,n))))}}));h=e.output,p=e.newStates}o&&u.push(h)}if(o){g=Ws(u,1)}return[h,g,p]}))}gd.className="DepthwiseConv2D",yi(gd);class bd extends Dc{constructor(e){let t;if(super(e),null==e.cell)throw new Bo("cell property is missing for the constructor of RNN.");if(t=Array.isArray(e.cell)?new Ad({cells:e.cell}):e.cell,null==t.stateSize)throw new Bo("The RNN cell should have an attribute `stateSize` (tuple of integers, one integer per RNN state).");this.cell=t,this.returnSequences=null!=e.returnSequences&&e.returnSequences,this.returnState=null!=e.returnState&&e.returnState,this.goBackwards=null!=e.goBackwards&&e.goBackwards,this._stateful=null!=e.stateful&&e.stateful,this.unroll=null!=e.unroll&&e.unroll,this.supportsMasking=!0,this.inputSpec=[new Cc({ndim:3})],this.stateSpec=null,this.states_=null,this.numConstants=null,this.keptStates=[]}getStates(){if(null==this.states_){return zl(0,Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1).map((e=>null))}return this.states_}setStates(e){this.states_=e}computeOutputShape(e){bc(e)&&(e=e[0]);let t=this.cell.stateSize;Array.isArray(t)||(t=[t]);const n=t[0];let i;if(i=this.returnSequences?[e[0],e[1],n]:[e[0],n],this.returnState){const n=[];for(const i of t)n.push([e[0],i]);return[i].concat(n)}return i}computeMask(e,t){return si((()=>{Array.isArray(t)&&(t=t[0]);const e=this.returnSequences?t:null;if(this.returnState){const t=this.states.map((e=>null));return[e].concat(t)}return e}))}get states(){if(null==this.states_){const e=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1,t=[];for(let n=0;n<e;++n)t.push(null);return t}return this.states_}set states(e){this.states_=e}build(e){if(null!=this.numConstants)throw new Uo("Constants support is not implemented in RNN yet.");bc(e)&&(e=e[0]);const t=this.stateful?e[0]:null,n=e.slice(2);this.inputSpec[0]=new Cc({shape:[t,null,...n]});const i=[e[0]].concat(e.slice(2));let a;if(this.cell.build(i),a=Array.isArray(this.cell.stateSize)?this.cell.stateSize:[this.cell.stateSize],null!=this.stateSpec){if(!E(this.stateSpec.map((e=>e.shape[e.shape.length-1])),a))throw new Bo(`An initialState was passed that is not compatible with cell.stateSize. Received stateSpec=${this.stateSpec}; However cell.stateSize is ${this.cell.stateSize}`)}else this.stateSpec=a.map((e=>new Cc({shape:[null,e]})));this.stateful&&this.resetStates()}resetStates(e,t=!1){si((()=>{if(!this.stateful)throw new Oo("Cannot call resetStates() on an RNN Layer that is not stateful.");const n=this.inputSpec[0].shape[0];if(null==n)throw new Bo("If an RNN is stateful, it needs to know its batch size. Specify the batch size of your input tensors: \n- If using a Sequential model, specify the batch size by passing a `batchInputShape` option to your first layer.\n- If using the functional API, specify the batch size by passing a `batchShape` option to your Input layer.");if(null==this.states_)Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map((e=>is([n,e]))):this.states_=[is([n,this.cell.stateSize])];else if(null==e)ri(this.states_),null!=this.keptStates&&(ri(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map((e=>is([n,e]))):this.states_[0]=is([n,this.cell.stateSize]);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new Bo(`Layer ${this.name} expects ${this.states_.length} state(s), but it received ${e.length} state value(s). Input received: ${e}`);!0===t?this.keptStates.push(this.states_.slice()):ri(this.states_);for(let t=0;t<this.states_.length;++t){const i=e[t],a=Array.isArray(this.cell.stateSize)?this.cell.stateSize[t]:this.cell.stateSize,s=[n,a];if(!E(i.shape,s))throw new Bo(`State ${t} is incompatible with layer ${this.name}: expected shape=${s}, received shape=${i.shape}`);this.states_[t]=i}}this.states_=this.states_.map((e=>oi(e.clone())))}))}apply(e,t){let n=null==t?null:t.initialState,i=null==t?null:t.constants;null==t&&(t={});const a=vd(e,n,i,this.numConstants);e=a.inputs,n=a.initialState,i=a.constants;let s=[],r=[];if(null!=n){t.initialState=n,s=s.concat(n),this.stateSpec=[];for(const e of n)this.stateSpec.push(new Cc({shape:e.shape}));r=r.concat(this.stateSpec)}null!=i&&(t.constants=i,s=s.concat(i),this.numConstants=i.length);if(s[0]instanceof Ec){const n=[e].concat(s),i=this.inputSpec.concat(r),a=this.inputSpec;this.inputSpec=i;const o=super.apply(n,t);return this.inputSpec=a,o}return super.apply(e,t)}call(e,t){return si((()=>{const n=null==t?null:t.mask,i=null==t?null:t.training;let a=null==t?null:t.initialState;e=kc(e),null==a&&(a=this.stateful?this.states_:this.getInitialState(e));const s=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1;if(a.length!==s)throw new Bo(`RNN Layer has ${s} state(s) but was passed ${a.length} initial state(s).`);this.unroll&&console.warn("Ignoring unroll = true for RNN layer, due to imperative backend.");const r={training:i},o=yd(((e,t)=>{const n=this.cell.call([e].concat(t),r);return[n[0],n.slice(1)]}),e,a,this.goBackwards,n,null,this.unroll,this.returnSequences),l=o[0],c=o[1],u=o[2];this.stateful&&this.resetStates(u,i);const h=this.returnSequences?c:l;return this.returnState?[h].concat(u):h}))}getInitialState(e){return si((()=>{let t=is(e.shape);return t=ja(t,[1,2]),t=Rl(t),Array.isArray(this.cell.stateSize)?this.cell.stateSize.map((e=>e>1?Ul(t,[1,e]):t)):this.cell.stateSize>1?[Ul(t,[1,this.cell.stateSize])]:[t]}))}get trainableWeights(){return this.trainable?this.cell.trainableWeights:[]}get nonTrainableWeights(){return this.trainable?this.cell.nonTrainableWeights:this.cell.weights}setFastWeightInitDuringBuild(e){super.setFastWeightInitDuringBuild(e),null!=this.cell&&this.cell.setFastWeightInitDuringBuild(e)}getConfig(){const e=super.getConfig(),t={returnSequences:this.returnSequences,returnState:this.returnState,goBackwards:this.goBackwards,stateful:this.stateful,unroll:this.unroll};null!=this.numConstants&&(t.numConstants=this.numConstants);const n=this.cell.getConfig();return this.getClassName()===bd.className&&(t.cell={className:this.cell.getClassName(),config:n}),Object.assign(Object.assign(Object.assign({},n),e),t)}static fromConfig(e,t,n={}){const i=Nh(t.cell,n);return new e(Object.assign(t,{cell:i}))}}bd.className="RNN",yi(bd);class wd extends Dc{}class kd extends wd{constructor(e){super(e),this.DEFAULT_ACTIVATION="tanh",this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_RECURRENT_INITIALIZER="orthogonal",this.DEFAULT_BIAS_INITIALIZER="zeros",this.units=e.units,ol(this.units,"units"),this.activation=Pp(null==e.activation?this.DEFAULT_ACTIVATION:e.activation),this.useBias=null==e.useBias||e.useBias,this.kernelInitializer=yc(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=yc(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=yc(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=Kp(e.kernelRegularizer),this.recurrentRegularizer=Kp(e.recurrentRegularizer),this.biasRegularizer=Kp(e.biasRegularizer),this.kernelConstraint=ph(e.kernelConstraint),this.recurrentConstraint=ph(e.recurrentConstraint),this.biasConstraint=ph(e.biasConstraint),this.dropout=$l([1,jl([0,null==e.dropout?0:e.dropout])]),this.recurrentDropout=$l([1,jl([0,null==e.recurrentDropout?0:e.recurrentDropout])]),this.dropoutFunc=e.dropoutFunc,this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){e=xc(e),this.kernel=this.addWeight("kernel",[e[e.length-1],this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,this.units],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias?this.bias=this.addWeight("bias",[this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(e,t){return si((()=>{if(2!==e.length)throw new Bo(`SimpleRNNCell expects 2 input Tensors, got ${e.length}.`);let n=e[1];e=e[0];const i=null!=t.training&&t.training;let a;0<this.dropout&&this.dropout<1&&null==this.dropoutMask&&(this.dropoutMask=Cd({ones:()=>ls(e),rate:this.dropout,training:i,dropoutFunc:this.dropoutFunc})),0<this.recurrentDropout&&this.recurrentDropout<1&&null==this.recurrentDropoutMask&&(this.recurrentDropoutMask=Cd({ones:()=>ls(n),rate:this.recurrentDropout,training:i,dropoutFunc:this.dropoutFunc}));const s=this.dropoutMask,r=this.recurrentDropoutMask;a=Vl(null!=s?xi(e,s):e,this.kernel.read()),null!=this.bias&&(a=Hl(a,this.bias.read())),null!=r&&(n=xi(n,r));let o=bi(a,Vl(n,this.recurrentKernel.read()));return null!=this.activation&&(o=this.activation.apply(o)),[o,o]}))}getConfig(){const e=super.getConfig(),t={units:this.units,activation:Mp(this.activation),useBias:this.useBias,kernelInitializer:vc(this.kernelInitializer),recurrentInitializer:vc(this.recurrentInitializer),biasInitializer:vc(this.biasInitializer),kernelRegularizer:Vp(this.kernelRegularizer),recurrentRegularizer:Vp(this.recurrentRegularizer),biasRegularizer:Vp(this.biasRegularizer),activityRegularizer:Vp(this.activityRegularizer),kernelConstraint:uh(this.kernelConstraint),recurrentConstraint:uh(this.recurrentConstraint),biasConstraint:uh(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout};return Object.assign(Object.assign({},e),t)}}kd.className="SimpleRNNCell",yi(kd);class xd extends bd{constructor(e){e.cell=new kd(e),super(e)}call(e,t){return si((()=>{null!=this.cell.dropoutMask&&(ri(this.cell.dropoutMask),this.cell.dropoutMask=null),null!=this.cell.recurrentDropoutMask&&(ri(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);const n=null==t?null:t.mask,i=null==t?null:t.training,a=null==t?null:t.initialState;return super.call(e,{mask:n,training:i,initialState:a})}))}static fromConfig(e,t){return new e(t)}}xd.className="SimpleRNN",yi(xd);class Sd extends wd{constructor(e){if(super(e),this.DEFAULT_ACTIVATION="tanh",this.DEFAULT_RECURRENT_ACTIVATION="hardSigmoid",this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_RECURRENT_INITIALIZER="orthogonal",this.DEFAULT_BIAS_INITIALIZER="zeros",e.resetAfter)throw new Bo("GRUCell does not support reset_after parameter set to true.");this.units=e.units,ol(this.units,"units"),this.activation=Pp(void 0===e.activation?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=Pp(void 0===e.recurrentActivation?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=null==e.useBias||e.useBias,this.kernelInitializer=yc(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=yc(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=yc(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=Kp(e.kernelRegularizer),this.recurrentRegularizer=Kp(e.recurrentRegularizer),this.biasRegularizer=Kp(e.biasRegularizer),this.kernelConstraint=ph(e.kernelConstraint),this.recurrentConstraint=ph(e.recurrentConstraint),this.biasConstraint=ph(e.biasConstraint),this.dropout=$l([1,jl([0,null==e.dropout?0:e.dropout])]),this.recurrentDropout=$l([1,jl([0,null==e.recurrentDropout?0:e.recurrentDropout])]),this.dropoutFunc=e.dropoutFunc,this.implementation=e.implementation,this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){const t=(e=xc(e))[e.length-1];this.kernel=this.addWeight("kernel",[t,3*this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,3*this.units],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias?this.bias=this.addWeight("bias",[3*this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(e,t){return si((()=>{if(2!==e.length)throw new Bo(`GRUCell expects 2 input Tensors (inputs, h, c), got ${e.length}.`);const n=null!=t.training&&t.training;let i=e[1];e=e[0],0<this.dropout&&this.dropout<1&&null==this.dropoutMask&&(this.dropoutMask=Cd({ones:()=>ls(e),rate:this.dropout,training:n,count:3,dropoutFunc:this.dropoutFunc})),0<this.recurrentDropout&&this.recurrentDropout<1&&null==this.recurrentDropoutMask&&(this.recurrentDropoutMask=Cd({ones:()=>ls(i),rate:this.recurrentDropout,training:n,count:3,dropoutFunc:this.dropoutFunc}));const a=this.dropoutMask,s=this.recurrentDropoutMask;let r,o,l;0<this.dropout&&this.dropout<1&&(e=xi(e,a[0]));let c=Vl(e,this.kernel.read());this.useBias&&(c=Hl(c,this.bias.read())),0<this.recurrentDropout&&this.recurrentDropout<1&&(i=xi(i,s[0]));const u=this.recurrentKernel.read(),[h,p]=Bs(u,[2*this.units,this.units],u.rank-1),d=Vl(i,h),[m,f,g]=Bs(c,3,c.rank-1),[v,y]=Bs(d,2,d.rank-1);r=this.recurrentActivation.apply(bi(m,v)),o=this.recurrentActivation.apply(bi(f,y));const b=Vl(xi(o,i),p);l=this.activation.apply(bi(g,b));const w=bi(xi(r,i),xi(bi(1,ci(r)),l));return[w,w]}))}getConfig(){const e=super.getConfig(),t={units:this.units,activation:Mp(this.activation),recurrentActivation:Mp(this.recurrentActivation),useBias:this.useBias,kernelInitializer:vc(this.kernelInitializer),recurrentInitializer:vc(this.recurrentInitializer),biasInitializer:vc(this.biasInitializer),kernelRegularizer:Vp(this.kernelRegularizer),recurrentRegularizer:Vp(this.recurrentRegularizer),biasRegularizer:Vp(this.biasRegularizer),activityRegularizer:Vp(this.activityRegularizer),kernelConstraint:uh(this.kernelConstraint),recurrentConstraint:uh(this.recurrentConstraint),biasConstraint:uh(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation,resetAfter:!1};return Object.assign(Object.assign({},e),t)}}Sd.className="GRUCell",yi(Sd);class Nd extends bd{constructor(e){0===e.implementation&&console.warn("`implementation=0` has been deprecated, and now defaults to `implementation=1`. Please update your layer call."),e.cell=new Sd(e),super(e)}call(e,t){return si((()=>{null!=this.cell.dropoutMask&&(ri(this.cell.dropoutMask),this.cell.dropoutMask=null),null!=this.cell.recurrentDropoutMask&&(ri(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);const n=null==t?null:t.mask,i=null==t?null:t.training,a=null==t?null:t.initialState;return super.call(e,{mask:n,training:i,initialState:a})}))}static fromConfig(e,t){return 0===t.implmentation&&(t.implementation=1),new e(t)}}Nd.className="GRU",yi(Nd);class Td extends wd{constructor(e){super(e),this.DEFAULT_ACTIVATION="tanh",this.DEFAULT_RECURRENT_ACTIVATION="hardSigmoid",this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_RECURRENT_INITIALIZER="orthogonal",this.DEFAULT_BIAS_INITIALIZER="zeros",this.units=e.units,ol(this.units,"units"),this.activation=Pp(void 0===e.activation?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=Pp(void 0===e.recurrentActivation?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=null==e.useBias||e.useBias,this.kernelInitializer=yc(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=yc(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=yc(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.unitForgetBias=e.unitForgetBias,this.kernelRegularizer=Kp(e.kernelRegularizer),this.recurrentRegularizer=Kp(e.recurrentRegularizer),this.biasRegularizer=Kp(e.biasRegularizer),this.kernelConstraint=ph(e.kernelConstraint),this.recurrentConstraint=ph(e.recurrentConstraint),this.biasConstraint=ph(e.biasConstraint),this.dropout=$l([1,jl([0,null==e.dropout?0:e.dropout])]),this.recurrentDropout=$l([1,jl([0,null==e.recurrentDropout?0:e.recurrentDropout])]),this.dropoutFunc=e.dropoutFunc,this.implementation=e.implementation,this.stateSize=[this.units,this.units],this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){var t;const n=(e=xc(e))[e.length-1];let i;if(this.kernel=this.addWeight("kernel",[n,4*this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,4*this.units],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias){if(this.unitForgetBias){const e=this.biasInitializer,n=this.units;i=new((t=class extends Xl{apply(t,i){const a=e.apply([n]),s=(new tc).apply([n]),r=e.apply([2*n]);return Bl(Bl(a,s),r)}}).className="CustomInit",t)}else i=this.biasInitializer;this.bias=this.addWeight("bias",[4*this.units],null,i,this.biasRegularizer,!0,this.biasConstraint)}else this.bias=null;this.built=!0}call(e,t){return si((()=>{const n=null!=t.training&&t.training;if(3!==e.length)throw new Bo(`LSTMCell expects 3 input Tensors (inputs, h, c), got ${e.length}.`);let i=e[1];const a=e[2];e=e[0],0<this.dropout&&this.dropout<1&&null==this.dropoutMask&&(this.dropoutMask=Cd({ones:()=>ls(e),rate:this.dropout,training:n,count:4,dropoutFunc:this.dropoutFunc})),0<this.recurrentDropout&&this.recurrentDropout<1&&null==this.recurrentDropoutMask&&(this.recurrentDropoutMask=Cd({ones:()=>ls(i),rate:this.recurrentDropout,training:n,count:4,dropoutFunc:this.dropoutFunc}));const s=this.dropoutMask,r=this.recurrentDropoutMask;let o,l,c,u;0<this.dropout&&this.dropout<1&&(e=xi(e,s[0]));let h=Vl(e,this.kernel.read());0<this.recurrentDropout&&this.recurrentDropout<1&&(i=xi(i,r[0])),h=bi(h,Vl(i,this.recurrentKernel.read())),this.useBias&&(h=Hl(h,this.bias.read()));const[p,d,m,f]=Bs(h,4,h.rank-1);o=this.recurrentActivation.apply(p),l=this.recurrentActivation.apply(d),c=bi(xi(l,a),xi(o,this.activation.apply(m))),u=this.recurrentActivation.apply(f);const g=xi(u,this.activation.apply(c));return[g,g,c]}))}getConfig(){const e=super.getConfig(),t={units:this.units,activation:Mp(this.activation),recurrentActivation:Mp(this.recurrentActivation),useBias:this.useBias,kernelInitializer:vc(this.kernelInitializer),recurrentInitializer:vc(this.recurrentInitializer),biasInitializer:vc(this.biasInitializer),unitForgetBias:this.unitForgetBias,kernelRegularizer:Vp(this.kernelRegularizer),recurrentRegularizer:Vp(this.recurrentRegularizer),biasRegularizer:Vp(this.biasRegularizer),activityRegularizer:Vp(this.activityRegularizer),kernelConstraint:uh(this.kernelConstraint),recurrentConstraint:uh(this.recurrentConstraint),biasConstraint:uh(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation};return Object.assign(Object.assign({},e),t)}}Td.className="LSTMCell",yi(Td);class Id extends bd{constructor(e){0===e.implementation&&console.warn("`implementation=0` has been deprecated, and now defaults to `implementation=1`. Please update your layer call."),e.cell=new Td(e),super(e)}call(e,t){return si((()=>{null!=this.cell.dropoutMask&&(ri(this.cell.dropoutMask),this.cell.dropoutMask=null),null!=this.cell.recurrentDropoutMask&&(ri(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);const n=null==t?null:t.mask,i=null==t?null:t.training,a=null==t?null:t.initialState;return super.call(e,{mask:n,training:i,initialState:a})}))}static fromConfig(e,t){return 0===t.implmentation&&(t.implementation=1),new e(t)}}Id.className="LSTM",yi(Id);class Ad extends wd{constructor(e){super(e),this.cells=e.cells}get stateSize(){const e=[];for(const t of this.cells.slice().reverse())Array.isArray(t.stateSize)?e.push(...t.stateSize):e.push(t.stateSize);return e}call(e,t){return si((()=>{let n=e.slice(1);const i=[];for(const e of this.cells.slice().reverse())Array.isArray(e.stateSize)?i.push(n.splice(0,e.stateSize.length)):i.push(n.splice(0,1));i.reverse();const a=[];let s;for(let r=0;r<this.cells.length;++r){const o=this.cells[r];n=i[r],s=0===r?[e[0]].concat(n):[s[0]].concat(n),s=o.call(s,t),a.push(s.slice(1))}n=[];for(const e of a.slice().reverse())n.push(...e);return[s[0]].concat(n)}))}build(e){let t;bc(e)&&(e=e[0]),this.cells.forEach(((n,i)=>{Nl(`RNNCell_${i}`,(()=>{n.build(e),t=Array.isArray(n.stateSize)?n.stateSize[0]:n.stateSize,e=[e[0],t]}))})),this.built=!0}getConfig(){const e=super.getConfig(),t={cells:this.cells.map((e=>({className:e.getClassName(),config:e.getConfig()})))};return Object.assign(Object.assign({},e),t)}static fromConfig(e,t,n={}){const i=[];for(const e of t.cells)i.push(Nh(e,n));return new e({cells:i})}get trainableWeights(){if(!this.trainable)return[];const e=[];for(const t of this.cells)e.push(...t.trainableWeights);return e}get nonTrainableWeights(){const e=[];for(const t of this.cells)e.push(...t.nonTrainableWeights);if(!this.trainable){const t=[];for(const e of this.cells)t.push(...e.trainableWeights);return t.concat(e)}return e}getWeights(){const e=[];for(const t of this.cells)e.push(...t.weights);return Ic(e)}setWeights(e){const t=[];for(const n of this.cells){const i=n.weights.length,a=e.splice(i);for(let e=0;e<n.weights.length;++e)t.push([n.weights[e],a[e]])}Ac(t)}}function Cd(e){const{ones:t,rate:n,training:i=!1,count:a=1,dropoutFunc:s}=e,r=()=>null!=s?s(t(),n):Jl(t(),n),o=()=>Zl(r,t,i);if(!a||a<=1)return oi(o().clone());return Array(a).fill(void 0).map(o).map((e=>oi(e.clone())))}
4515
4515
  /**
4516
4516
  * @license
4517
4517
  * Copyright 2020 Google LLC
@@ -4520,7 +4520,7 @@ function vd(e,t,n,i){if(Array.isArray(e)){if(null!=t||null!=n)throw new Bo("When
4520
4520
  * license that can be found in the LICENSE file or at
4521
4521
  * https://opensource.org/licenses/MIT.
4522
4522
  * =============================================================================
4523
- */Ed.className="StackedRNNCells",yi(Ed);var Cd=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var a=0;for(i=Object.getOwnPropertySymbols(e);a<i.length;a++)t.indexOf(i[a])<0&&Object.prototype.propertyIsEnumerable.call(e,i[a])&&(n[i[a]]=e[i[a]])}return n};class $d extends bd{constructor(e){if(e.unroll)throw new Uo("Unrolling is not possible with convolutional RNNs.");if(Array.isArray(e.cell))throw new Uo("It is not possible at the moment to stack convolutional cells.");super(e),this.inputSpec=[new Ac({ndim:5})]}call(e,t){return si((()=>{if(null!=this.cell.dropoutMask&&(ri(this.cell.dropoutMask),this.cell.dropoutMask=null),null!=this.cell.recurrentDropoutMask&&(ri(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null),t&&t.constants)throw new Bo("ConvRNN2D cell does not support constants");const n=null==t?null:t.mask,i=null==t?null:t.training,a=null==t?null:t.initialState;return super.call(e,{mask:n,training:i,initialState:a})}))}computeOutputShape(e){let t=this.computeSingleOutputShape(e);return this.returnSequences||(t=[t[0],...t.slice(2)]),this.returnState&&(t=[t,...Array(2).fill([e[0],...t.slice(-3)])]),t}getInitialState(e){return si((()=>{const{stateSize:t}=this.cell,n=e.shape,i=this.computeSingleOutputShape(n),a=is([i[0],...i.slice(2)]);return Array.isArray(t)?Array(t.length).fill(a):[a]}))}resetStates(e,t=!1){si((()=>{if(!this.stateful)throw new Oo("Cannot call resetStates() on an RNN Layer that is not stateful.");const n=this.inputSpec[0].shape,i=this.computeSingleOutputShape(n),a=[i[0],...i.slice(2)];if(null==n[0])throw new Bo("If an RNN is stateful, it needs to know its batch size. Specify the batch size of your input tensors: \n- If using a Sequential model, specify the batch size by passing a `batchInputShape` option to your first layer.\n- If using the functional API, specify the batch size by passing a `batchShape` option to your Input layer.");if(null==this.getStates())Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map((()=>is(a))):this.states_=[is(a)];else if(null==e)ri(this.states_),null!=this.keptStates&&(ri(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map((()=>is(a))):this.states_[0]=is(a);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new Bo(`Layer ${this.name} expects ${this.states_.length} state(s), but it received ${e.length} state value(s). Input received: ${e}`);t?this.keptStates.push(this.states_.slice()):ri(this.states_);for(let t=0;t<this.states_.length;++t){const n=e[t],i=a;if(!C(n.shape,i))throw new Bo(`State ${t} is incompatible with layer ${this.name}: expected shape=${i}, received shape=${n.shape}`);this.states_[t]=n}}this.states_=this.states_.map((e=>oi(e.clone())))}))}computeSingleOutputShape(e){const{dataFormat:t,filters:n,kernelSize:i,padding:a,strides:s,dilationRate:r}=this.cell,o="channelsFirst"===t,l=e[o?3:2],c=e[o?4:3],u=ed(l,i[0],a,s[0],r[0]),h=ed(c,i[1],a,s[1],r[1]);return[...e.slice(0,2),...o?[n,u,h]:[u,h,n]]}}$d.className="ConvRNN2D";class jd extends Id{constructor(e){const{filters:t,kernelSize:n,strides:i,padding:a,dataFormat:s,dilationRate:r}=e;super(Object.assign(Object.assign({},e),{units:t})),this.filters=t,ol(this.filters,"filters"),this.kernelSize=Xp(n,2,"kernelSize"),this.kernelSize.forEach((e=>ol(e,"kernelSize"))),this.strides=Xp(i||1,2,"strides"),this.strides.forEach((e=>ol(e,"strides"))),this.padding=a||"valid",kl(this.padding),this.dataFormat=s||"channelsLast",wl(this.dataFormat),this.dilationRate=Xp(r||1,2,"dilationRate"),this.dilationRate.forEach((e=>ol(e,"dilationRate")))}build(e){var t;e=xc(e);const n="channelsFirst"===this.dataFormat?1:e.length-1;if(null==e[n])throw new Bo(`The channel dimension of the input should be defined. Found ${e[n]}`);const i=e[n],a=this.kernelSize.concat([i,4*this.filters]);this.kernel=this.addWeight("kernel",a,null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint);const s=this.kernelSize.concat([this.filters,4*this.filters]);if(this.recurrentKernel=this.addWeight("recurrent_kernel",s,null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias){let e;if(this.unitForgetBias){const n=this.biasInitializer,i=this.filters;e=new((t=class extends Xl{apply(e,t){return Pl([n.apply([i]),as([i]),n.apply([2*i])])}}).className="CustomInit",t)}else e=this.biasInitializer;this.bias=this.addWeight("bias",[4*this.filters],null,e,this.biasRegularizer,!0,this.biasConstraint)}this.built=!0}call(e,t){return si((()=>{if(3!==e.length)throw new Bo(`ConvLSTM2DCell expects 3 input Tensors (inputs, h, c), got ${e.length}.`);const n=t.training||!1,i=e[0],a=e[1],s=e[2];0<this.dropout&&this.dropout<1&&null==this.dropoutMask&&(this.dropoutMask=Ad({ones:()=>ls(i),rate:this.dropout,training:n,count:4,dropoutFunc:this.dropoutFunc}));const r=this.dropoutMask,o=(e,t,n)=>t&&t[n]?xi(t[n],e):e;let l=o(i,r,0),c=o(i,r,1),u=o(i,r,2),h=o(i,r,3);0<this.recurrentDropout&&this.recurrentDropout<1&&null==this.recurrentDropoutMask&&(this.recurrentDropoutMask=Ad({ones:()=>ls(a),rate:this.recurrentDropout,training:n,count:4,dropoutFunc:this.dropoutFunc}));const p=this.recurrentDropoutMask;let d=o(a,p,0),m=o(a,p,1),f=o(a,p,2),g=o(a,p,3);const[v,y,b,w]=Bs(this.kernel.read(),4,3),[k,x,S,N]=this.useBias?Bs(this.bias.read(),4):[null,null,null,null];l=this.inputConv(l,v,k,this.padding),c=this.inputConv(c,y,x,this.padding),u=this.inputConv(u,b,S,this.padding),h=this.inputConv(h,w,N,this.padding);const[I,T,E,A]=Bs(this.recurrentKernel.read(),4,3);d=this.recurrentConv(d,I),m=this.recurrentConv(m,T),f=this.recurrentConv(f,E),g=this.recurrentConv(g,A);const C=this.recurrentActivation.apply(bi(l,d)),$=this.recurrentActivation.apply(bi(c,m)),j=bi(xi($,s),xi(C,this.activation.apply(bi(u,f)))),z=xi(this.recurrentActivation.apply(bi(h,g)),this.activation.apply(j));return[z,z,j]}))}getConfig(){const e=super.getConfig(),t=Cd(e,["units"]),n={filters:this.filters,kernelSize:this.kernelSize,padding:this.padding,dataFormat:this.dataFormat,dilationRate:this.dilationRate,strides:this.strides};return Object.assign(Object.assign({},t),n)}inputConv(e,t,n,i){const a=ia(e,t,this.strides,i||"valid","channelsFirst"===this.dataFormat?"NCHW":"NHWC",this.dilationRate);return n?Hl(a,n,this.dataFormat):a}recurrentConv(e,t){return ia(e,t,1,"same","channelsFirst"===this.dataFormat?"NCHW":"NHWC")}}jd.className="ConvLSTM2DCell",yi(jd);class zd extends $d{constructor(e){const t=new jd(e);super(Object.assign(Object.assign({},e),{cell:t}))}static fromConfig(e,t){return new e(t)}}zd.className="ConvLSTM2D",yi(zd);
4523
+ */Ad.className="StackedRNNCells",yi(Ad);var Ed=function(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var a=0;for(i=Object.getOwnPropertySymbols(e);a<i.length;a++)t.indexOf(i[a])<0&&Object.prototype.propertyIsEnumerable.call(e,i[a])&&(n[i[a]]=e[i[a]])}return n};class $d extends bd{constructor(e){if(e.unroll)throw new Uo("Unrolling is not possible with convolutional RNNs.");if(Array.isArray(e.cell))throw new Uo("It is not possible at the moment to stack convolutional cells.");super(e),this.inputSpec=[new Cc({ndim:5})]}call(e,t){return si((()=>{if(null!=this.cell.dropoutMask&&(ri(this.cell.dropoutMask),this.cell.dropoutMask=null),null!=this.cell.recurrentDropoutMask&&(ri(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null),t&&t.constants)throw new Bo("ConvRNN2D cell does not support constants");const n=null==t?null:t.mask,i=null==t?null:t.training,a=null==t?null:t.initialState;return super.call(e,{mask:n,training:i,initialState:a})}))}computeOutputShape(e){let t=this.computeSingleOutputShape(e);return this.returnSequences||(t=[t[0],...t.slice(2)]),this.returnState&&(t=[t,...Array(2).fill([e[0],...t.slice(-3)])]),t}getInitialState(e){return si((()=>{const{stateSize:t}=this.cell,n=e.shape,i=this.computeSingleOutputShape(n),a=is([i[0],...i.slice(2)]);return Array.isArray(t)?Array(t.length).fill(a):[a]}))}resetStates(e,t=!1){si((()=>{if(!this.stateful)throw new Oo("Cannot call resetStates() on an RNN Layer that is not stateful.");const n=this.inputSpec[0].shape,i=this.computeSingleOutputShape(n),a=[i[0],...i.slice(2)];if(null==n[0])throw new Bo("If an RNN is stateful, it needs to know its batch size. Specify the batch size of your input tensors: \n- If using a Sequential model, specify the batch size by passing a `batchInputShape` option to your first layer.\n- If using the functional API, specify the batch size by passing a `batchShape` option to your Input layer.");if(null==this.getStates())Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map((()=>is(a))):this.states_=[is(a)];else if(null==e)ri(this.states_),null!=this.keptStates&&(ri(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map((()=>is(a))):this.states_[0]=is(a);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new Bo(`Layer ${this.name} expects ${this.states_.length} state(s), but it received ${e.length} state value(s). Input received: ${e}`);t?this.keptStates.push(this.states_.slice()):ri(this.states_);for(let t=0;t<this.states_.length;++t){const n=e[t],i=a;if(!E(n.shape,i))throw new Bo(`State ${t} is incompatible with layer ${this.name}: expected shape=${i}, received shape=${n.shape}`);this.states_[t]=n}}this.states_=this.states_.map((e=>oi(e.clone())))}))}computeSingleOutputShape(e){const{dataFormat:t,filters:n,kernelSize:i,padding:a,strides:s,dilationRate:r}=this.cell,o="channelsFirst"===t,l=e[o?3:2],c=e[o?4:3],u=ed(l,i[0],a,s[0],r[0]),h=ed(c,i[1],a,s[1],r[1]);return[...e.slice(0,2),...o?[n,u,h]:[u,h,n]]}}$d.className="ConvRNN2D";class jd extends Td{constructor(e){const{filters:t,kernelSize:n,strides:i,padding:a,dataFormat:s,dilationRate:r}=e;super(Object.assign(Object.assign({},e),{units:t})),this.filters=t,ol(this.filters,"filters"),this.kernelSize=Xp(n,2,"kernelSize"),this.kernelSize.forEach((e=>ol(e,"kernelSize"))),this.strides=Xp(i||1,2,"strides"),this.strides.forEach((e=>ol(e,"strides"))),this.padding=a||"valid",kl(this.padding),this.dataFormat=s||"channelsLast",wl(this.dataFormat),this.dilationRate=Xp(r||1,2,"dilationRate"),this.dilationRate.forEach((e=>ol(e,"dilationRate")))}build(e){var t;e=xc(e);const n="channelsFirst"===this.dataFormat?1:e.length-1;if(null==e[n])throw new Bo(`The channel dimension of the input should be defined. Found ${e[n]}`);const i=e[n],a=this.kernelSize.concat([i,4*this.filters]);this.kernel=this.addWeight("kernel",a,null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint);const s=this.kernelSize.concat([this.filters,4*this.filters]);if(this.recurrentKernel=this.addWeight("recurrent_kernel",s,null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias){let e;if(this.unitForgetBias){const n=this.biasInitializer,i=this.filters;e=new((t=class extends Xl{apply(e,t){return Pl([n.apply([i]),as([i]),n.apply([2*i])])}}).className="CustomInit",t)}else e=this.biasInitializer;this.bias=this.addWeight("bias",[4*this.filters],null,e,this.biasRegularizer,!0,this.biasConstraint)}this.built=!0}call(e,t){return si((()=>{if(3!==e.length)throw new Bo(`ConvLSTM2DCell expects 3 input Tensors (inputs, h, c), got ${e.length}.`);const n=t.training||!1,i=e[0],a=e[1],s=e[2];0<this.dropout&&this.dropout<1&&null==this.dropoutMask&&(this.dropoutMask=Cd({ones:()=>ls(i),rate:this.dropout,training:n,count:4,dropoutFunc:this.dropoutFunc}));const r=this.dropoutMask,o=(e,t,n)=>t&&t[n]?xi(t[n],e):e;let l=o(i,r,0),c=o(i,r,1),u=o(i,r,2),h=o(i,r,3);0<this.recurrentDropout&&this.recurrentDropout<1&&null==this.recurrentDropoutMask&&(this.recurrentDropoutMask=Cd({ones:()=>ls(a),rate:this.recurrentDropout,training:n,count:4,dropoutFunc:this.dropoutFunc}));const p=this.recurrentDropoutMask;let d=o(a,p,0),m=o(a,p,1),f=o(a,p,2),g=o(a,p,3);const[v,y,b,w]=Bs(this.kernel.read(),4,3),[k,x,S,N]=this.useBias?Bs(this.bias.read(),4):[null,null,null,null];l=this.inputConv(l,v,k,this.padding),c=this.inputConv(c,y,x,this.padding),u=this.inputConv(u,b,S,this.padding),h=this.inputConv(h,w,N,this.padding);const[T,I,A,C]=Bs(this.recurrentKernel.read(),4,3);d=this.recurrentConv(d,T),m=this.recurrentConv(m,I),f=this.recurrentConv(f,A),g=this.recurrentConv(g,C);const E=this.recurrentActivation.apply(bi(l,d)),$=this.recurrentActivation.apply(bi(c,m)),j=bi(xi($,s),xi(E,this.activation.apply(bi(u,f)))),z=xi(this.recurrentActivation.apply(bi(h,g)),this.activation.apply(j));return[z,z,j]}))}getConfig(){const e=super.getConfig(),t=Ed(e,["units"]),n={filters:this.filters,kernelSize:this.kernelSize,padding:this.padding,dataFormat:this.dataFormat,dilationRate:this.dilationRate,strides:this.strides};return Object.assign(Object.assign({},t),n)}inputConv(e,t,n,i){const a=ia(e,t,this.strides,i||"valid","channelsFirst"===this.dataFormat?"NCHW":"NHWC",this.dilationRate);return n?Hl(a,n,this.dataFormat):a}recurrentConv(e,t){return ia(e,t,1,"same","channelsFirst"===this.dataFormat?"NCHW":"NHWC")}}jd.className="ConvLSTM2DCell",yi(jd);class zd extends $d{constructor(e){const t=new jd(e);super(Object.assign(Object.assign({},e),{cell:t}))}static fromConfig(e,t){return new e(t)}}zd.className="ConvLSTM2D",yi(zd);
4524
4524
  /**
4525
4525
  * @license
4526
4526
  * Copyright 2018 Google LLC
@@ -4530,7 +4530,7 @@ function vd(e,t,n,i){if(Array.isArray(e)){if(null!=t||null!=n)throw new Bo("When
4530
4530
  * https://opensource.org/licenses/MIT.
4531
4531
  * =============================================================================
4532
4532
  */
4533
- class Dd extends Dc{constructor(e){super(e),this.rate=Math.max(Math.min(e.rate,1),0),this.noiseShape=e.noiseShape,this.seed=e.seed,this.supportsMasking=!0}getNoiseShape(e){if(null==this.noiseShape)return this.noiseShape;const t=e.shape,n=[];for(let e=0;e<this.noiseShape.length;++e)n.push(null==this.noiseShape[e]?t[e]:this.noiseShape[e]);return n}call(e,t){return si((()=>{this.invokeCallHook(e,t);const n=kc(e);if(0<this.rate&&this.rate<1){const e=null!=t.training&&t.training,i=this.getNoiseShape(n);return Zl((()=>Jl(n,this.rate,i,this.seed)),(()=>n),e)}return e}))}getConfig(){const e={rate:this.rate,noiseShape:this.noiseShape,seed:this.seed},t=super.getConfig();return Object.assign(e,t),e}dispose(){return super.dispose()}}Dd.className="Dropout",yi(Dd);class Fd extends Dd{constructor(e){super(e),this.inputSpec=[{ndim:3}]}getNoiseShape(e){const t=e.shape;return[t[0],1,t[2]]}}Fd.className="SpatialDropout1D",yi(Fd);class _d extends Dc{constructor(e){if(super(e),this.activation=null,this.useBias=!0,this.kernel=null,this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",null==e.batchInputShape&&null==e.inputShape&&null!=e.inputDim){let t=null;null!=e.batchSize&&(t=e.batchSize),this.batchInputShape=[t,e.inputDim]}this.units=e.units,ol(this.units,"units"),this.activation=Pp(e.activation),null!=e.useBias&&(this.useBias=e.useBias),this.kernelInitializer=yc(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.biasInitializer=yc(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelConstraint=ph(e.kernelConstraint),this.biasConstraint=ph(e.biasConstraint),this.kernelRegularizer=Kp(e.kernelRegularizer),this.biasRegularizer=Kp(e.biasRegularizer),this.activityRegularizer=Kp(e.activityRegularizer),this.supportsMasking=!0,this.inputSpec=[{minNDim:2}]}build(e){const t=(e=xc(e))[e.length-1];null==this.kernel&&(this.kernel=this.addWeight("kernel",[t,this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint))),this.inputSpec=[{minNDim:2,axes:{[-1]:t}}],this.built=!0}computeOutputShape(e){const t=(e=xc(e)).slice();return t[t.length-1]=this.units,t}call(e,t){return si((()=>{this.invokeCallHook(e,t);const n=kc(e),i=cl(this.activation.getClassName());let a;return null!=i?a=Gl(n,this.kernel.read(),i,this.bias?this.bias.read():null):(a=Gl(n,this.kernel.read()),null!=this.bias&&(a=Hl(a,this.bias.read())),null!=this.activation&&(a=this.activation.apply(a))),a}))}getConfig(){const e={units:this.units,activation:Mp(this.activation),useBias:this.useBias,kernelInitializer:vc(this.kernelInitializer),biasInitializer:vc(this.biasInitializer),kernelRegularizer:Gp(this.kernelRegularizer),biasRegularizer:Gp(this.biasRegularizer),activityRegularizer:Gp(this.activityRegularizer),kernelConstraint:uh(this.kernelConstraint),biasConstraint:uh(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}}_d.className="Dense",yi(_d);class Rd extends Dc{constructor(e){super(e=e||{}),this.inputSpec=[{minNDim:3}],this.dataFormat=e.dataFormat}computeOutputShape(e){e=xc(e);for(const t of e.slice(1))if(null==t)throw new Bo(`The shape of the input to "Flatten" is not fully defined (got ${e.slice(1)}). Make sure to pass a complete "input_shape" or "batch_input_shape" argument to the first layer in your model.`);return[e[0],Cl(e,1)]}call(e,t){return si((()=>{this.invokeCallHook(e,t);let n=kc(e);if("channelsFirst"===this.dataFormat&&n.rank>1){const e=[0];for(let t=2;t<n.rank;++t)e.push(t);e.push(1),n=hi(n,e)}return function(e){if(e.rank<=1)throw new Bo(`batchFlatten requires a minimum rank of 2. Got rank: ${e.rank}.`);const t=[e.shape[0],Cl(e.shape,1)];return _i(e,t)}(n)}))}getConfig(){const e={};null!=this.dataFormat&&(e.dataFormat=this.dataFormat);const t=super.getConfig();return Object.assign(e,t),e}}Rd.className="Flatten",yi(Rd);class Ld extends Dc{constructor(e){super(e),this.supportsMasking=!0,this.activation=Pp(e.activation)}call(e,t){return si((()=>{this.invokeCallHook(e,t);const n=kc(e);return this.activation.apply(n)}))}getConfig(){const e={activation:Mp(this.activation)},t=super.getConfig();return Object.assign(e,t),e}}Ld.className="Activation",yi(Ld);class Md extends Dc{constructor(e){super(e),this.n=e.n,this.inputSpec=[{ndim:2}]}computeOutputShape(e){return[e[0],this.n,e[1]]}call(e,t){return si((()=>{return e=kc(e),t=e,n=this.n,si((()=>{if(2!==t.shape.length)throw new Bo(`repeat() expects a rank-2 tensor, but received a rank-${t.shape.length} tensor.`);return Ul(Rl(t,1),[1,n,1])}));var t,n}))}getConfig(){const e={n:this.n},t=super.getConfig();return Object.assign(e,t),e}}Md.className="RepeatVector",yi(Md);class Od extends Dc{constructor(e){super(e),this.targetShape=e.targetShape;for(let e=0;e<this.targetShape.length;++e)this.isUnknown(this.targetShape[e])&&(this.targetShape[e]=null)}isUnknown(e){return e<0||null==e}fixUnknownDimension(e,t){const n="Total size of new array must be unchanged.",i=t.slice();let a=1,s=null;for(let e=0;e<i.length;++e){const t=i[e];if(this.isUnknown(t)){if(null!==s)throw new Bo("Can only specifiy one unknown dimension.");s=e}else a*=t}const r=Cl(e);if(null!==s){if(0===a||r%a!=0)throw new Bo(n);i[s]=r/a}else if(r!==a)throw new Bo(n);return i}computeOutputShape(e){let t=!1;for(let n=0;n<e.length;++n)if(this.isUnknown(e[n])){t=!0;break}return t?e.slice(0,1).concat(this.targetShape):e.slice(0,1).concat(this.fixUnknownDimension(e.slice(1),this.targetShape))}call(e,t){return si((()=>{this.invokeCallHook(e,t);const n=kc(e),i=n.shape,a=i.slice(0,1).concat(this.fixUnknownDimension(i.slice(1),this.targetShape));return _i(n,a)}))}getConfig(){const e={targetShape:this.targetShape},t=super.getConfig();return Object.assign(e,t),e}}Od.className="Reshape",yi(Od);class Pd extends Dc{constructor(e){if(super(e),null==e.dims)throw new Error("Required configuration field `dims` is missing during Permute constructor call.");if(!Array.isArray(e.dims))throw new Error(`Permute constructor requires \`dims\` to be an Array, but received ${e.dims} instead.`);const t=zl(1,e.dims.length+1);if(!C(e.dims.slice().sort(),t))throw new Error("Invalid permutation `dims`: "+JSON.stringify(e.dims)+" `dims` must contain consecutive integers starting from 1.");this.dims=e.dims,this.dimsIncludingBatch=[0].concat(this.dims),this.inputSpec=[new Ac({ndim:this.dims.length+1})]}computeOutputShape(e){const t=(e=xc(e)).slice();return this.dims.forEach(((n,i)=>{t[i+1]=e[n]})),t}call(e,t){return hi(kc(e),this.dimsIncludingBatch)}getConfig(){const e={dims:this.dims},t=super.getConfig();return Object.assign(e,t),e}}Pd.className="Permute",yi(Pd);class Bd extends Dc{constructor(e){super(null==e?{}:e),this.supportsMasking=!0,this.maskValue=null!=e?null==e.maskValue?0:e.maskValue:0}computeOutputShape(e){return e}getConfig(){const e=super.getConfig(),t={maskValue:this.maskValue};return Object.assign(t,e),t}computeMask(e,t){const n=kc(e);return Ii(os(n,this.maskValue),-1)}call(e,t){return si((()=>{this.invokeCallHook(e,t);const n=kc(e),i=Ii(os(n,this.maskValue),-1,!0);return xi(n,ei(i,n.dtype))}))}}Bd.className="Masking",yi(Bd);
4533
+ class Dd extends Dc{constructor(e){super(e),this.rate=Math.max(Math.min(e.rate,1),0),this.noiseShape=e.noiseShape,this.seed=e.seed,this.supportsMasking=!0}getNoiseShape(e){if(null==this.noiseShape)return this.noiseShape;const t=e.shape,n=[];for(let e=0;e<this.noiseShape.length;++e)n.push(null==this.noiseShape[e]?t[e]:this.noiseShape[e]);return n}call(e,t){return si((()=>{this.invokeCallHook(e,t);const n=kc(e);if(0<this.rate&&this.rate<1){const e=null!=t.training&&t.training,i=this.getNoiseShape(n);return Zl((()=>Jl(n,this.rate,i,this.seed)),(()=>n),e)}return e}))}getConfig(){const e={rate:this.rate,noiseShape:this.noiseShape,seed:this.seed},t=super.getConfig();return Object.assign(e,t),e}dispose(){return super.dispose()}}Dd.className="Dropout",yi(Dd);class Fd extends Dd{constructor(e){super(e),this.inputSpec=[{ndim:3}]}getNoiseShape(e){const t=e.shape;return[t[0],1,t[2]]}}Fd.className="SpatialDropout1D",yi(Fd);class _d extends Dc{constructor(e){if(super(e),this.activation=null,this.useBias=!0,this.kernel=null,this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",null==e.batchInputShape&&null==e.inputShape&&null!=e.inputDim){let t=null;null!=e.batchSize&&(t=e.batchSize),this.batchInputShape=[t,e.inputDim]}this.units=e.units,ol(this.units,"units"),this.activation=Pp(e.activation),null!=e.useBias&&(this.useBias=e.useBias),this.kernelInitializer=yc(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.biasInitializer=yc(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelConstraint=ph(e.kernelConstraint),this.biasConstraint=ph(e.biasConstraint),this.kernelRegularizer=Kp(e.kernelRegularizer),this.biasRegularizer=Kp(e.biasRegularizer),this.activityRegularizer=Kp(e.activityRegularizer),this.supportsMasking=!0,this.inputSpec=[{minNDim:2}]}build(e){const t=(e=xc(e))[e.length-1];null==this.kernel&&(this.kernel=this.addWeight("kernel",[t,this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint))),this.inputSpec=[{minNDim:2,axes:{[-1]:t}}],this.built=!0}computeOutputShape(e){const t=(e=xc(e)).slice();return t[t.length-1]=this.units,t}call(e,t){return si((()=>{this.invokeCallHook(e,t);const n=kc(e),i=cl(this.activation.getClassName());let a;return null!=i?a=Vl(n,this.kernel.read(),i,this.bias?this.bias.read():null):(a=Vl(n,this.kernel.read()),null!=this.bias&&(a=Hl(a,this.bias.read())),null!=this.activation&&(a=this.activation.apply(a))),a}))}getConfig(){const e={units:this.units,activation:Mp(this.activation),useBias:this.useBias,kernelInitializer:vc(this.kernelInitializer),biasInitializer:vc(this.biasInitializer),kernelRegularizer:Vp(this.kernelRegularizer),biasRegularizer:Vp(this.biasRegularizer),activityRegularizer:Vp(this.activityRegularizer),kernelConstraint:uh(this.kernelConstraint),biasConstraint:uh(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}}_d.className="Dense",yi(_d);class Rd extends Dc{constructor(e){super(e=e||{}),this.inputSpec=[{minNDim:3}],this.dataFormat=e.dataFormat}computeOutputShape(e){e=xc(e);for(const t of e.slice(1))if(null==t)throw new Bo(`The shape of the input to "Flatten" is not fully defined (got ${e.slice(1)}). Make sure to pass a complete "input_shape" or "batch_input_shape" argument to the first layer in your model.`);return[e[0],El(e,1)]}call(e,t){return si((()=>{this.invokeCallHook(e,t);let n=kc(e);if("channelsFirst"===this.dataFormat&&n.rank>1){const e=[0];for(let t=2;t<n.rank;++t)e.push(t);e.push(1),n=hi(n,e)}return function(e){if(e.rank<=1)throw new Bo(`batchFlatten requires a minimum rank of 2. Got rank: ${e.rank}.`);const t=[e.shape[0],El(e.shape,1)];return _i(e,t)}(n)}))}getConfig(){const e={};null!=this.dataFormat&&(e.dataFormat=this.dataFormat);const t=super.getConfig();return Object.assign(e,t),e}}Rd.className="Flatten",yi(Rd);class Ld extends Dc{constructor(e){super(e),this.supportsMasking=!0,this.activation=Pp(e.activation)}call(e,t){return si((()=>{this.invokeCallHook(e,t);const n=kc(e);return this.activation.apply(n)}))}getConfig(){const e={activation:Mp(this.activation)},t=super.getConfig();return Object.assign(e,t),e}}Ld.className="Activation",yi(Ld);class Md extends Dc{constructor(e){super(e),this.n=e.n,this.inputSpec=[{ndim:2}]}computeOutputShape(e){return[e[0],this.n,e[1]]}call(e,t){return si((()=>{return e=kc(e),t=e,n=this.n,si((()=>{if(2!==t.shape.length)throw new Bo(`repeat() expects a rank-2 tensor, but received a rank-${t.shape.length} tensor.`);return Ul(Rl(t,1),[1,n,1])}));var t,n}))}getConfig(){const e={n:this.n},t=super.getConfig();return Object.assign(e,t),e}}Md.className="RepeatVector",yi(Md);class Od extends Dc{constructor(e){super(e),this.targetShape=e.targetShape;for(let e=0;e<this.targetShape.length;++e)this.isUnknown(this.targetShape[e])&&(this.targetShape[e]=null)}isUnknown(e){return e<0||null==e}fixUnknownDimension(e,t){const n="Total size of new array must be unchanged.",i=t.slice();let a=1,s=null;for(let e=0;e<i.length;++e){const t=i[e];if(this.isUnknown(t)){if(null!==s)throw new Bo("Can only specifiy one unknown dimension.");s=e}else a*=t}const r=El(e);if(null!==s){if(0===a||r%a!=0)throw new Bo(n);i[s]=r/a}else if(r!==a)throw new Bo(n);return i}computeOutputShape(e){let t=!1;for(let n=0;n<e.length;++n)if(this.isUnknown(e[n])){t=!0;break}return t?e.slice(0,1).concat(this.targetShape):e.slice(0,1).concat(this.fixUnknownDimension(e.slice(1),this.targetShape))}call(e,t){return si((()=>{this.invokeCallHook(e,t);const n=kc(e),i=n.shape,a=i.slice(0,1).concat(this.fixUnknownDimension(i.slice(1),this.targetShape));return _i(n,a)}))}getConfig(){const e={targetShape:this.targetShape},t=super.getConfig();return Object.assign(e,t),e}}Od.className="Reshape",yi(Od);class Pd extends Dc{constructor(e){if(super(e),null==e.dims)throw new Error("Required configuration field `dims` is missing during Permute constructor call.");if(!Array.isArray(e.dims))throw new Error(`Permute constructor requires \`dims\` to be an Array, but received ${e.dims} instead.`);const t=zl(1,e.dims.length+1);if(!E(e.dims.slice().sort(),t))throw new Error("Invalid permutation `dims`: "+JSON.stringify(e.dims)+" `dims` must contain consecutive integers starting from 1.");this.dims=e.dims,this.dimsIncludingBatch=[0].concat(this.dims),this.inputSpec=[new Cc({ndim:this.dims.length+1})]}computeOutputShape(e){const t=(e=xc(e)).slice();return this.dims.forEach(((n,i)=>{t[i+1]=e[n]})),t}call(e,t){return hi(kc(e),this.dimsIncludingBatch)}getConfig(){const e={dims:this.dims},t=super.getConfig();return Object.assign(e,t),e}}Pd.className="Permute",yi(Pd);class Bd extends Dc{constructor(e){super(null==e?{}:e),this.supportsMasking=!0,this.maskValue=null!=e?null==e.maskValue?0:e.maskValue:0}computeOutputShape(e){return e}getConfig(){const e=super.getConfig(),t={maskValue:this.maskValue};return Object.assign(t,e),t}computeMask(e,t){const n=kc(e);return Ti(os(n,this.maskValue),-1)}call(e,t){return si((()=>{this.invokeCallHook(e,t);const n=kc(e),i=Ti(os(n,this.maskValue),-1,!0);return xi(n,ei(i,n.dtype))}))}}Bd.className="Masking",yi(Bd);
4534
4534
  /**
4535
4535
  * @license
4536
4536
  * Copyright 2018 Google LLC
@@ -4540,7 +4540,7 @@ class Dd extends Dc{constructor(e){super(e),this.rate=Math.max(Math.min(e.rate,1
4540
4540
  * https://opensource.org/licenses/MIT.
4541
4541
  * =============================================================================
4542
4542
  */
4543
- class Ud extends Dc{constructor(e){if(super(e),this.embeddings=null,this.DEFAULT_EMBEDDINGS_INITIALIZER="randomUniform",null==e.batchInputShape&&null==e.inputShape){let t=null;null!=e.batchSize&&(t=e.batchSize),null==e.inputLength?this.batchInputShape=[t,null]:this.batchInputShape=[t].concat(Jo(e.inputLength))}this.inputDim=e.inputDim,ol(this.inputDim,"inputDim"),this.outputDim=e.outputDim,ol(this.outputDim,"outputDim"),this.embeddingsInitializer=yc(e.embeddingsInitializer||this.DEFAULT_EMBEDDINGS_INITIALIZER),this.embeddingsRegularizer=Kp(e.embeddingsRegularizer),this.activityRegularizer=Kp(e.activityRegularizer),this.embeddingsConstraint=ph(e.embeddingsConstraint),this.maskZero=e.maskZero,this.supportsMasking=e.maskZero,this.inputLength=e.inputLength}build(e){this.embeddings=this.addWeight("embeddings",[this.inputDim,this.outputDim],this.dtype,this.embeddingsInitializer,this.embeddingsRegularizer,!0,this.embeddingsConstraint),this.built=!0}warnOnIncompatibleInputShape(e){}computeMask(e,t){return si((()=>this.maskZero?(e=kc(e),os(e,ya(e))):null))}computeOutputShape(e){if(e=xc(e),null==this.inputLength)return[...e,this.outputDim];const t=Jo(this.inputLength);if(t.length!==e.length-1)throw new Bo(`"inputLength" is ${this.inputLength}, but received input shape has shape ${e}`);{let n=0;for(let i=0;i<t.length;++i){const a=t[i],s=e[i+1];if(null!=a&&null!=s&&a!==s)throw new Bo(`"inputLength" is ${this.inputLength}, but received input shape has shape ${e}`);null==a&&(t[n]=s),n++}}return[e[0],...t,this.outputDim]}call(e,t){return si((()=>{this.invokeCallHook(e,t);let n=kc(e);"int32"!==n.dtype&&(n=_l(n,"int32"));const i=Vl(this.embeddings.read(),_i(n,[n.size]));return _i(i,xc(this.computeOutputShape(n.shape)))}))}getConfig(){const e={inputDim:this.inputDim,outputDim:this.outputDim,embeddingsInitializer:vc(this.embeddingsInitializer),embeddingsRegularizer:Gp(this.embeddingsRegularizer),activityRegularizer:Gp(this.activityRegularizer),embeddingsConstraint:uh(this.embeddingsConstraint),maskZero:this.maskZero,inputLength:this.inputLength},t=super.getConfig();return Object.assign(e,t),e}}Ud.className="Embedding",yi(Ud);
4543
+ class Ud extends Dc{constructor(e){if(super(e),this.embeddings=null,this.DEFAULT_EMBEDDINGS_INITIALIZER="randomUniform",null==e.batchInputShape&&null==e.inputShape){let t=null;null!=e.batchSize&&(t=e.batchSize),null==e.inputLength?this.batchInputShape=[t,null]:this.batchInputShape=[t].concat(Jo(e.inputLength))}this.inputDim=e.inputDim,ol(this.inputDim,"inputDim"),this.outputDim=e.outputDim,ol(this.outputDim,"outputDim"),this.embeddingsInitializer=yc(e.embeddingsInitializer||this.DEFAULT_EMBEDDINGS_INITIALIZER),this.embeddingsRegularizer=Kp(e.embeddingsRegularizer),this.activityRegularizer=Kp(e.activityRegularizer),this.embeddingsConstraint=ph(e.embeddingsConstraint),this.maskZero=e.maskZero,this.supportsMasking=e.maskZero,this.inputLength=e.inputLength}build(e){this.embeddings=this.addWeight("embeddings",[this.inputDim,this.outputDim],this.dtype,this.embeddingsInitializer,this.embeddingsRegularizer,!0,this.embeddingsConstraint),this.built=!0}warnOnIncompatibleInputShape(e){}computeMask(e,t){return si((()=>this.maskZero?(e=kc(e),os(e,ya(e))):null))}computeOutputShape(e){if(e=xc(e),null==this.inputLength)return[...e,this.outputDim];const t=Jo(this.inputLength);if(t.length!==e.length-1)throw new Bo(`"inputLength" is ${this.inputLength}, but received input shape has shape ${e}`);{let n=0;for(let i=0;i<t.length;++i){const a=t[i],s=e[i+1];if(null!=a&&null!=s&&a!==s)throw new Bo(`"inputLength" is ${this.inputLength}, but received input shape has shape ${e}`);null==a&&(t[n]=s),n++}}return[e[0],...t,this.outputDim]}call(e,t){return si((()=>{this.invokeCallHook(e,t);let n=kc(e);"int32"!==n.dtype&&(n=_l(n,"int32"));const i=Gl(this.embeddings.read(),_i(n,[n.size]));return _i(i,xc(this.computeOutputShape(n.shape)))}))}getConfig(){const e={inputDim:this.inputDim,outputDim:this.outputDim,embeddingsInitializer:vc(this.embeddingsInitializer),embeddingsRegularizer:Vp(this.embeddingsRegularizer),activityRegularizer:Vp(this.activityRegularizer),embeddingsConstraint:uh(this.embeddingsConstraint),maskZero:this.maskZero,inputLength:this.inputLength},t=super.getConfig();return Object.assign(e,t),e}}Ud.className="Embedding",yi(Ud);
4544
4544
  /**
4545
4545
  * @license
4546
4546
  * Copyright 2018 Google LLC
@@ -4550,7 +4550,7 @@ class Ud extends Dc{constructor(e){if(super(e),this.embeddings=null,this.DEFAULT
4550
4550
  * https://opensource.org/licenses/MIT.
4551
4551
  * =============================================================================
4552
4552
  */
4553
- class Wd extends Dc{constructor(e){super(e||{}),this.supportsMasking=!0}mergeFunction(e){throw new Uo}computeElementwiseOpOutputShape(e,t){if(null==e||null==t)return null;if(e.length<t.length)return this.computeElementwiseOpOutputShape(t,e);if(0===t.length)return e;const n=e.slice(0,e.length-t.length);for(let i=0;i<t.length;++i){const a=e[e.length-t.length+i],s=t[i];if(null==a||null==s||a<0||s<0)n.push(null);else if(1===a)n.push(s);else if(1===s)n.push(a);else{if(a!==s)throw new Bo("Operands could not be broadcast together with shapes "+JSON.stringify(e)+" "+JSON.stringify(t));n.push(a)}}return n}build(e){if(Array.isArray(e)&&!Array.isArray(e[0])&&(e=[xc(e)]),e.length<2)throw new Bo(`A merge layer should be called on an Array of at least 2 inputs. Got ${e.length} input(s).`);let t=[];for(const n of e)null!=n&&null!==n[0]&&t.push(n[0]);if(t=il(t),t.length>1)throw new Bo(`Can not merge tensors with different batch sizes. Got tensors with shapes: ${JSON.stringify(e)}.`);let n=null==e[0]?null:e[0].slice(1);for(let t=1;t<e.length;++t){const i=null==e[t]?null:e[t].slice(1);n=this.computeElementwiseOpOutputShape(n,i)}const i=e.map((e=>e.length));-1===e.indexOf(null)&&1===il(i).length?this.reshapeRequired=!1:this.reshapeRequired=!0}call(e,t){return si((()=>{if(this.reshapeRequired){const t=[],n=e.map((e=>e.rank));if(-1===n.indexOf(null)){const i=jl(n);for(let n of e){const e=n.rank;for(let t=0;t<i-e;++t)n=Rl(n,1);t.push(n)}return this.mergeFunction(t)}{let n=!1;for(const i of e){const e=i.rank;if(null==e){const e=i.shape,a=e[0],s=e.slice(1).concat([a]);let r=_i(i,[a].concat(Cl(e.slice(1))));r=hi(r,[1,0]),r=_i(r,s),t.push(r),n=!0}else if(e>1){const a=zl(1,e).concat([0]);t.push(hi(i,a)),n=!0}else t.push(i)}let i=this.mergeFunction(t);const a=i.rank;if(n)if(null==a){const e=i.shape,t=e[e.length-1],n=[t].concat(e.slice(0,e.length-1));i=_i(hi(_i(i,[-1,t]),[1,0]),n)}else if(a>1){const e=[a-1].concat(zl(0,a-1));i=hi(i,e)}return i}}return this.mergeFunction(e)}))}computeOutputShape(e){let t;t=null==e[0]?null:e[0].slice(1);for(let n=1;n<e.length;++n){const i=null==e[n]?null:e[n].slice(1);t=this.computeElementwiseOpOutputShape(t,i)}let n=[];for(const t of e)null!=t&&null!==t[0]&&n.push(t[0]);return n=il(n),t=1===n.length?n.concat(t):[null].concat(t),t}computeMask(e,t){return si((()=>{if(null==t)return null;if(!Array.isArray(t))throw new Bo("`mask` should be an Array");if(!Array.isArray(e))throw new Bo("`inputs` should be an Array");if(t.length!==e.length)throw new Bo(`The Array 'inputs' and 'mask' are expected to have the same length, but have different lengths (${e.length} vs ${t.length})`);if(t.every((e=>null==e)))return null;let n=(t=t.map((e=>null==e?e:_a(e,0))))[0];for(let e=1;e<t.length-1;++e)n=Ya(n,t[e]);return n}))}}class Gd extends Wd{constructor(e){super(e)}mergeFunction(e){return si((()=>{let t=e[0].clone();for(let n=1;n<e.length;++n)t=bi(t,e[n]);return t}))}}Gd.className="Add",yi(Gd);class Vd extends Wd{constructor(e){super(e)}mergeFunction(e){return si((()=>{let t=e[0].clone();for(let n=1;n<e.length;++n)t=xi(t,e[n]);return t}))}}Vd.className="Multiply",yi(Vd);class Kd extends Wd{constructor(e){super(e)}mergeFunction(e){return si((()=>{let t=e[0].clone();for(let n=1;n<e.length;++n)t=bi(t,e[n]);return xi(1/e.length,t)}))}}Kd.className="Average",yi(Kd);class qd extends Wd{constructor(e){super(e)}mergeFunction(e){return si((()=>{let t=e[0];for(let n=1;n<e.length;++n)t=ts(t,e[n]);return t}))}}qd.className="Maximum",yi(qd);class Hd extends Wd{constructor(e){super(e)}mergeFunction(e){return si((()=>{let t=e[0];for(let n=1;n<e.length;++n)t=ss(t,e[n]);return t}))}}Hd.className="Minimum",yi(Hd);class Jd extends Wd{constructor(e){super(e),this.DEFAULT_AXIS=-1,null==e&&(e={}),this.axis=null==e.axis?this.DEFAULT_AXIS:e.axis,this.supportsMasking=!0,this.reshapeRequired=!1}build(e){if(!Array.isArray(e)||!Array.isArray(e[0])||1===e.length)throw new Bo("A `Concatenate` layer should be called on a list of at least 2 inputs");let t=!0;for(const n of e)if(null!=n){t=!1;break}if(t)return;const n=[];for(let t=0;t<e.length;++t){const i=e[t].slice();i.splice(this.axis,1);let a=!1;for(const e of n)if(C(e,i)){a=!0;break}a||n.push(i)}if(n.length>1)throw new Bo("A `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got input shapes: "+JSON.stringify(e))}mergeFunction(e){return si((()=>Pl(e,this.axis)))}computeOutputShape(e){if(!Array.isArray(e)||!Array.isArray(e[0]))throw new Bo("A `Concatenate` layer should be called on a list of inputs.");const t=e,n=t[0].slice(),i=this.axis<0?n.length+this.axis:this.axis;for(const e of t.slice(1)){if(null==n[i]||null==e[i]){n[i]=null;break}n[i]+=e[i]}return n}computeMask(e,t){if(null==t)return null;if(!Array.isArray(t))throw new Bo("`mask` should be an array for Concatenate");if(!Array.isArray(e))throw new Bo("`inputs` should be an array for Concatenate");if(t.length!==e.length)throw new Bo(`Mismatch in the length of mask (${t.length}) and the legnth of inputs (${e.length})`);return si((()=>{let n=!0;if(t.forEach((e=>{null==e||(n=!1)})),n)return null;const i=[];for(let n=0;n<e.length;++n)null==t[n]?i.push(ei(ls(e[n]),"bool")):t[n].rank<e[n].rank?i.push(_a(t[n],-1)):i.push(t[n]);const a=Oi(i,this.axis);return Ni(a,-1,!1)}))}getConfig(){const e={axis:this.axis},t=super.getConfig();return Object.assign(e,t),e}}function Zd(e,t){for(;e<0;)e+=t;return e}Jd.className="Concatenate",yi(Jd);class Yd extends Wd{constructor(e){super(e),this.axes=e.axes,this.normalize=null!=e.normalize&&e.normalize,this.supportsMasking=!0,this.reshapeRequired=!1}build(e){I(Array.isArray(e)&&2===e.length&&Array.isArray(e[0])&&Array.isArray(e[1]),(()=>"A `Dot` layer should be called on a list of exactly 2 inputs."));const t=e[0],n=e[1];if(t.length>3||n.length>3)throw new Uo("Dot layer does not support tensors of 4D or higher rank yet.");const i=this.interpretAxes(t,n);if(t[i[0]]!==n[i[1]])throw new Bo(`Dimension incompatibility: ${t[i[0]]} !== ${n[i[1]]}`)}mergeFunction(e){if(2!==e.length)throw new Bo(`A \`Dot\` layer must be called on exactly 2 inputs, but received ${e.length} input(s).`);let t,n=e[0],i=e[1];return t=Array.isArray(this.axes)?this.axes.map(((t,n)=>Zd(t,e[n].shape.length))):[Zd(this.axes,n.shape.length),Zd(this.axes,i.shape.length)],this.normalize&&(n=Ih(n,t[0]),i=Ih(i,t[1])),function(e,t,n){if(e.shape.length>3||t.shape.length>3)throw new Uo("batchDot is not implemented for tensors of 4D or higher rank yet");if(I(e.shape.length>=2,(()=>`batchDot requires the rank of x to be >= 2, but got ${e.shape.length}`)),I(e.shape.length>=2,(()=>`batchDot requires the rank of y to be >= 2, but got ${t.shape.length}`)),"number"==typeof n&&(n=[n,n]),"complex64"===e.dtype||"complex64"===t.dtype)throw new Uo("batchDot is not implemented for complex64-type Tensors yet.");const i=e.shape.length,a=t.shape.length;null==n&&(n=[i-1,a-2]);const s=n;return si((()=>{let n,r;if(i>a){n=i-a;const e=[];for(let t=0;t<n;++t)e.push(1);t=_i(t,t.shape.concat(e))}else if(a>i){n=a-i;const t=[];for(let e=0;e<n;++e)t.push(1);e=_i(e,e.shape.concat(t))}else n=0;if(2===e.shape.length&&2===t.shape.length)r=s[0]===s[1]?ja(xi(e,t),s[0]):ja(xi(hi(e,[1,0]),t),s[1]);else{const n=s[0]!==e.shape.length-1,i=s[1]===t.shape.length-1;r=ti(e,t,n,i)}if(n>0){let e;e=i>a?i+a-3:i-1;const t=[];for(let i=e;i<e+n;++i)t.push(i);r=Us(r,t)}return 1===r.shape.length&&(r=_a(r,1)),r}))}(n,i,t)}interpretAxes(e,t){let n;return n=Array.isArray(this.axes)?this.axes:[Zd(this.axes,e.length),Zd(this.axes,t.length)],n}computeOutputShape(e){I(Array.isArray(e)&&2===e.length&&Array.isArray(e[0])&&Array.isArray(e[1]),(()=>"A `Dot` layer should be called on a list of exactly 2 inputs."));const t=e[0].slice(),n=e[1].slice();if(t.length>3||n.length>3)throw new Uo("Dot layer does not support tensors of 4D or higher rank yet.");const i=this.interpretAxes(t,n);t.splice(i[0],1),n.splice(i[1],1),n.splice(0,1);const a=t.concat(n);return 1===a.length&&a.push(1),a}computeMask(e,t){return null}getConfig(){const e={axes:this.axes,normalize:this.normalize},t=super.getConfig();return Object.assign(e,t),e}}Yd.className="Dot",yi(Yd);
4553
+ class Wd extends Dc{constructor(e){super(e||{}),this.supportsMasking=!0}mergeFunction(e){throw new Uo}computeElementwiseOpOutputShape(e,t){if(null==e||null==t)return null;if(e.length<t.length)return this.computeElementwiseOpOutputShape(t,e);if(0===t.length)return e;const n=e.slice(0,e.length-t.length);for(let i=0;i<t.length;++i){const a=e[e.length-t.length+i],s=t[i];if(null==a||null==s||a<0||s<0)n.push(null);else if(1===a)n.push(s);else if(1===s)n.push(a);else{if(a!==s)throw new Bo("Operands could not be broadcast together with shapes "+JSON.stringify(e)+" "+JSON.stringify(t));n.push(a)}}return n}build(e){if(Array.isArray(e)&&!Array.isArray(e[0])&&(e=[xc(e)]),e.length<2)throw new Bo(`A merge layer should be called on an Array of at least 2 inputs. Got ${e.length} input(s).`);let t=[];for(const n of e)null!=n&&null!==n[0]&&t.push(n[0]);if(t=il(t),t.length>1)throw new Bo(`Can not merge tensors with different batch sizes. Got tensors with shapes: ${JSON.stringify(e)}.`);let n=null==e[0]?null:e[0].slice(1);for(let t=1;t<e.length;++t){const i=null==e[t]?null:e[t].slice(1);n=this.computeElementwiseOpOutputShape(n,i)}const i=e.map((e=>e.length));-1===e.indexOf(null)&&1===il(i).length?this.reshapeRequired=!1:this.reshapeRequired=!0}call(e,t){return si((()=>{if(this.reshapeRequired){const t=[],n=e.map((e=>e.rank));if(-1===n.indexOf(null)){const i=jl(n);for(let n of e){const e=n.rank;for(let t=0;t<i-e;++t)n=Rl(n,1);t.push(n)}return this.mergeFunction(t)}{let n=!1;for(const i of e){const e=i.rank;if(null==e){const e=i.shape,a=e[0],s=e.slice(1).concat([a]);let r=_i(i,[a].concat(El(e.slice(1))));r=hi(r,[1,0]),r=_i(r,s),t.push(r),n=!0}else if(e>1){const a=zl(1,e).concat([0]);t.push(hi(i,a)),n=!0}else t.push(i)}let i=this.mergeFunction(t);const a=i.rank;if(n)if(null==a){const e=i.shape,t=e[e.length-1],n=[t].concat(e.slice(0,e.length-1));i=_i(hi(_i(i,[-1,t]),[1,0]),n)}else if(a>1){const e=[a-1].concat(zl(0,a-1));i=hi(i,e)}return i}}return this.mergeFunction(e)}))}computeOutputShape(e){let t;t=null==e[0]?null:e[0].slice(1);for(let n=1;n<e.length;++n){const i=null==e[n]?null:e[n].slice(1);t=this.computeElementwiseOpOutputShape(t,i)}let n=[];for(const t of e)null!=t&&null!==t[0]&&n.push(t[0]);return n=il(n),t=1===n.length?n.concat(t):[null].concat(t),t}computeMask(e,t){return si((()=>{if(null==t)return null;if(!Array.isArray(t))throw new Bo("`mask` should be an Array");if(!Array.isArray(e))throw new Bo("`inputs` should be an Array");if(t.length!==e.length)throw new Bo(`The Array 'inputs' and 'mask' are expected to have the same length, but have different lengths (${e.length} vs ${t.length})`);if(t.every((e=>null==e)))return null;let n=(t=t.map((e=>null==e?e:_a(e,0))))[0];for(let e=1;e<t.length-1;++e)n=Ya(n,t[e]);return n}))}}class Vd extends Wd{constructor(e){super(e)}mergeFunction(e){return si((()=>{let t=e[0].clone();for(let n=1;n<e.length;++n)t=bi(t,e[n]);return t}))}}Vd.className="Add",yi(Vd);class Gd extends Wd{constructor(e){super(e)}mergeFunction(e){return si((()=>{let t=e[0].clone();for(let n=1;n<e.length;++n)t=xi(t,e[n]);return t}))}}Gd.className="Multiply",yi(Gd);class Kd extends Wd{constructor(e){super(e)}mergeFunction(e){return si((()=>{let t=e[0].clone();for(let n=1;n<e.length;++n)t=bi(t,e[n]);return xi(1/e.length,t)}))}}Kd.className="Average",yi(Kd);class qd extends Wd{constructor(e){super(e)}mergeFunction(e){return si((()=>{let t=e[0];for(let n=1;n<e.length;++n)t=ts(t,e[n]);return t}))}}qd.className="Maximum",yi(qd);class Hd extends Wd{constructor(e){super(e)}mergeFunction(e){return si((()=>{let t=e[0];for(let n=1;n<e.length;++n)t=ss(t,e[n]);return t}))}}Hd.className="Minimum",yi(Hd);class Jd extends Wd{constructor(e){super(e),this.DEFAULT_AXIS=-1,null==e&&(e={}),this.axis=null==e.axis?this.DEFAULT_AXIS:e.axis,this.supportsMasking=!0,this.reshapeRequired=!1}build(e){if(!Array.isArray(e)||!Array.isArray(e[0])||1===e.length)throw new Bo("A `Concatenate` layer should be called on a list of at least 2 inputs");let t=!0;for(const n of e)if(null!=n){t=!1;break}if(t)return;const n=[];for(let t=0;t<e.length;++t){const i=e[t].slice();i.splice(this.axis,1);let a=!1;for(const e of n)if(E(e,i)){a=!0;break}a||n.push(i)}if(n.length>1)throw new Bo("A `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got input shapes: "+JSON.stringify(e))}mergeFunction(e){return si((()=>Pl(e,this.axis)))}computeOutputShape(e){if(!Array.isArray(e)||!Array.isArray(e[0]))throw new Bo("A `Concatenate` layer should be called on a list of inputs.");const t=e,n=t[0].slice(),i=this.axis<0?n.length+this.axis:this.axis;for(const e of t.slice(1)){if(null==n[i]||null==e[i]){n[i]=null;break}n[i]+=e[i]}return n}computeMask(e,t){if(null==t)return null;if(!Array.isArray(t))throw new Bo("`mask` should be an array for Concatenate");if(!Array.isArray(e))throw new Bo("`inputs` should be an array for Concatenate");if(t.length!==e.length)throw new Bo(`Mismatch in the length of mask (${t.length}) and the legnth of inputs (${e.length})`);return si((()=>{let n=!0;if(t.forEach((e=>{null==e||(n=!1)})),n)return null;const i=[];for(let n=0;n<e.length;++n)null==t[n]?i.push(ei(ls(e[n]),"bool")):t[n].rank<e[n].rank?i.push(_a(t[n],-1)):i.push(t[n]);const a=Oi(i,this.axis);return Ni(a,-1,!1)}))}getConfig(){const e={axis:this.axis},t=super.getConfig();return Object.assign(e,t),e}}function Zd(e,t){for(;e<0;)e+=t;return e}Jd.className="Concatenate",yi(Jd);class Yd extends Wd{constructor(e){super(e),this.axes=e.axes,this.normalize=null!=e.normalize&&e.normalize,this.supportsMasking=!0,this.reshapeRequired=!1}build(e){T(Array.isArray(e)&&2===e.length&&Array.isArray(e[0])&&Array.isArray(e[1]),(()=>"A `Dot` layer should be called on a list of exactly 2 inputs."));const t=e[0],n=e[1];if(t.length>3||n.length>3)throw new Uo("Dot layer does not support tensors of 4D or higher rank yet.");const i=this.interpretAxes(t,n);if(t[i[0]]!==n[i[1]])throw new Bo(`Dimension incompatibility: ${t[i[0]]} !== ${n[i[1]]}`)}mergeFunction(e){if(2!==e.length)throw new Bo(`A \`Dot\` layer must be called on exactly 2 inputs, but received ${e.length} input(s).`);let t,n=e[0],i=e[1];return t=Array.isArray(this.axes)?this.axes.map(((t,n)=>Zd(t,e[n].shape.length))):[Zd(this.axes,n.shape.length),Zd(this.axes,i.shape.length)],this.normalize&&(n=Th(n,t[0]),i=Th(i,t[1])),function(e,t,n){if(e.shape.length>3||t.shape.length>3)throw new Uo("batchDot is not implemented for tensors of 4D or higher rank yet");if(T(e.shape.length>=2,(()=>`batchDot requires the rank of x to be >= 2, but got ${e.shape.length}`)),T(e.shape.length>=2,(()=>`batchDot requires the rank of y to be >= 2, but got ${t.shape.length}`)),"number"==typeof n&&(n=[n,n]),"complex64"===e.dtype||"complex64"===t.dtype)throw new Uo("batchDot is not implemented for complex64-type Tensors yet.");const i=e.shape.length,a=t.shape.length;null==n&&(n=[i-1,a-2]);const s=n;return si((()=>{let n,r;if(i>a){n=i-a;const e=[];for(let t=0;t<n;++t)e.push(1);t=_i(t,t.shape.concat(e))}else if(a>i){n=a-i;const t=[];for(let e=0;e<n;++e)t.push(1);e=_i(e,e.shape.concat(t))}else n=0;if(2===e.shape.length&&2===t.shape.length)r=s[0]===s[1]?ja(xi(e,t),s[0]):ja(xi(hi(e,[1,0]),t),s[1]);else{const n=s[0]!==e.shape.length-1,i=s[1]===t.shape.length-1;r=ti(e,t,n,i)}if(n>0){let e;e=i>a?i+a-3:i-1;const t=[];for(let i=e;i<e+n;++i)t.push(i);r=Us(r,t)}return 1===r.shape.length&&(r=_a(r,1)),r}))}(n,i,t)}interpretAxes(e,t){let n;return n=Array.isArray(this.axes)?this.axes:[Zd(this.axes,e.length),Zd(this.axes,t.length)],n}computeOutputShape(e){T(Array.isArray(e)&&2===e.length&&Array.isArray(e[0])&&Array.isArray(e[1]),(()=>"A `Dot` layer should be called on a list of exactly 2 inputs."));const t=e[0].slice(),n=e[1].slice();if(t.length>3||n.length>3)throw new Uo("Dot layer does not support tensors of 4D or higher rank yet.");const i=this.interpretAxes(t,n);t.splice(i[0],1),n.splice(i[1],1),n.splice(0,1);const a=t.concat(n);return 1===a.length&&a.push(1),a}computeMask(e,t){return null}getConfig(){const e={axes:this.axes,normalize:this.normalize},t=super.getConfig();return Object.assign(e,t),e}}Yd.className="Dot",yi(Yd);
4554
4554
  /**
4555
4555
  * @license
4556
4556
  * Copyright 2018 Google LLC
@@ -4560,7 +4560,7 @@ class Wd extends Dc{constructor(e){super(e||{}),this.supportsMasking=!0}mergeFun
4560
4560
  * https://opensource.org/licenses/MIT.
4561
4561
  * =============================================================================
4562
4562
  */
4563
- class Qd extends Dc{constructor(e){super(e),this.supportsMasking=!0,this.stddev=e.stddev}computeOutputShape(e){return e}getConfig(){const e=super.getConfig(),t={stddev:this.stddev};return Object.assign(t,e),t}call(e,t){return si((()=>{this.invokeCallHook(e,t);const n=kc(e);return Zl((()=>bi(Wl(n.shape,0,this.stddev),n)),(()=>n),t.training||!1)}))}}Qd.className="GaussianNoise",yi(Qd);class Xd extends Dc{constructor(e){super(e),this.supportsMasking=!0,this.rate=e.rate}computeOutputShape(e){return e}getConfig(){const e=super.getConfig(),t={rate:this.rate};return Object.assign(t,e),t}call(e,t){return si((()=>{this.invokeCallHook(e,t);const n=kc(e);if(this.rate>0&&this.rate<1){return Zl((()=>{const e=Math.sqrt(this.rate/(1-this.rate));return xi(n,Wl(n.shape,1,e))}),(()=>n),t.training||!1)}return n}))}}Xd.className="GaussianDropout",yi(Xd);class em extends Dc{constructor(e){super(e),this.supportsMasking=!0,this.rate=e.rate,this.noiseShape=e.noiseShape}_getNoiseShape(e){return this.noiseShape||kc(e).shape}computeOutputShape(e){return e}getConfig(){const e=super.getConfig(),t={rate:this.rate};return Object.assign(t,e),t}call(e,t){return si((()=>{if(this.rate<1&&this.rate>0){const n=this._getNoiseShape(e);return Zl((()=>{const t=kc(e),i=-1.7580993408473766;let a=Ba(Is(n),this.rate);a=_l(a,"float32");const s=((1-this.rate)*(1+this.rate*i**2))**-.5,r=-s*i*this.rate,o=bi(xi(t,a),xi(bi(a,-1),i));return bi(xi(o,s),r)}),(()=>kc(e)),t.training||!1)}return e}))}}
4563
+ class Qd extends Dc{constructor(e){super(e),this.supportsMasking=!0,this.stddev=e.stddev}computeOutputShape(e){return e}getConfig(){const e=super.getConfig(),t={stddev:this.stddev};return Object.assign(t,e),t}call(e,t){return si((()=>{this.invokeCallHook(e,t);const n=kc(e);return Zl((()=>bi(Wl(n.shape,0,this.stddev),n)),(()=>n),t.training||!1)}))}}Qd.className="GaussianNoise",yi(Qd);class Xd extends Dc{constructor(e){super(e),this.supportsMasking=!0,this.rate=e.rate}computeOutputShape(e){return e}getConfig(){const e=super.getConfig(),t={rate:this.rate};return Object.assign(t,e),t}call(e,t){return si((()=>{this.invokeCallHook(e,t);const n=kc(e);if(this.rate>0&&this.rate<1){return Zl((()=>{const e=Math.sqrt(this.rate/(1-this.rate));return xi(n,Wl(n.shape,1,e))}),(()=>n),t.training||!1)}return n}))}}Xd.className="GaussianDropout",yi(Xd);class em extends Dc{constructor(e){super(e),this.supportsMasking=!0,this.rate=e.rate,this.noiseShape=e.noiseShape}_getNoiseShape(e){return this.noiseShape||kc(e).shape}computeOutputShape(e){return e}getConfig(){const e=super.getConfig(),t={rate:this.rate};return Object.assign(t,e),t}call(e,t){return si((()=>{if(this.rate<1&&this.rate>0){const n=this._getNoiseShape(e);return Zl((()=>{const t=kc(e),i=-1.7580993408473766;let a=Ba(Ts(n),this.rate);a=_l(a,"float32");const s=((1-this.rate)*(1+this.rate*i**2))**-.5,r=-s*i*this.rate,o=bi(xi(t,a),xi(bi(a,-1),i));return bi(xi(o,s),r)}),(()=>kc(e)),t.training||!1)}return e}))}}
4564
4564
  /**
4565
4565
  * @license
4566
4566
  * Copyright 2018 Google LLC
@@ -4570,7 +4570,7 @@ class Qd extends Dc{constructor(e){super(e),this.supportsMasking=!0,this.stddev=
4570
4570
  * https://opensource.org/licenses/MIT.
4571
4571
  * =============================================================================
4572
4572
  */
4573
- function tm(e,t,n,i,a,s=.001){let r;if(2===e.rank)r=Vi(e,t,n,i,a,s);else if(3===e.rank)r=Ki(e,t,n,i,a,s);else{if(4!==e.rank)throw new Uo(`batchNormalization is not implemented for array of rank ${e.rank} yet`);r=qi(e,t,n,i,a,s)}return r}function nm(e,t,n,i,a=.001){return C(i.slice().sort(),zl(0,e.rank-1))?function(e,t,n,i,a=.001){return si((()=>{const s=rs(e,i),r=s.mean,o=s.variance;return[tm(e,r,o,n,t,a),r,o]}))}(e,t,n,i,a):function(e,t,n,i,a=.001){return si((()=>{const s=rs(e,i),r=s.mean,o=s.variance,l=[];for(const t of zl(0,e.rank))-1!==i.indexOf(t)?l.push(1):l.push(e.shape[t]);const c=_i(r,l),u=_i(o,l),h=null==t?null:_i(t,l),p=null==n?null:_i(n,l);return[tm(e,c,u,p,h,a),r,o]}))}(e,t,n,i,a)}em.className="AlphaDropout",yi(em);class im extends Dc{constructor(e){null==e&&(e={}),super(e),this.supportsMasking=!0,this.axis=null==e.axis?-1:e.axis,this.momentum=null==e.momentum?.99:e.momentum,this.epsilon=null==e.epsilon?.001:e.epsilon,this.center=null==e.center||e.center,this.scale=null==e.scale||e.scale,this.betaInitializer=yc(e.betaInitializer||"zeros"),this.gammaInitializer=yc(e.gammaInitializer||"ones"),this.movingMeanInitializer=yc(e.movingMeanInitializer||"zeros"),this.movingVarianceInitializer=yc(e.movingVarianceInitializer||"ones"),this.betaConstraint=ph(e.betaConstraint),this.gammaConstraint=ph(e.gammaConstraint),this.betaRegularizer=Kp(e.betaRegularizer),this.gammaRegularizer=Kp(e.gammaRegularizer)}build(e){e=xc(e);const t=this.axis>=0?this.axis:this.axis+e.length,n=e[t];if(null==n)throw new Bo(`Axis ${t} of input tensor should have a defined dimension but the layer received an input with shape ${JSON.stringify(e)}.`);this.inputSpec=[new Ac({ndim:e.length,axes:{[t]:n}})];const i=[n];this.scale&&(this.gamma=this.addWeight("gamma",i,null,this.gammaInitializer,this.gammaRegularizer,!0,this.gammaConstraint)),this.center&&(this.beta=this.addWeight("beta",i,null,this.betaInitializer,this.betaRegularizer,!0,this.betaConstraint)),this.movingMean=this.addWeight("moving_mean",i,null,this.movingMeanInitializer,null,!1),this.movingVariance=this.addWeight("moving_variance",i,null,this.movingVarianceInitializer,null,!1),this.built=!0}call(e,t){return si((()=>{const n=null!=t.training&&t.training,i=kc(e),a=i.shape,s=a.length,r=zl(0,s),o=this.axis>=0?this.axis:this.axis+s;r.splice(o,1);const l=Vo(1,s);l[o]=a[o];const c=r.slice();c.sort();const u=!C(c,zl(0,s).slice(0,s-1));if(!n)return(()=>{if(u){const e=_i(this.movingMean.read(),l),t=_i(this.movingVariance.read(),l),n=this.center?_i(this.beta.read(),l):null,a=this.scale?_i(this.gamma.read(),l):null;return tm(i,e,t,n,a,this.epsilon)}return tm(i,this.movingMean.read(),this.movingVariance.read(),null==this.beta?null:this.beta.read(),null==this.gamma?null:this.gamma.read(),this.epsilon)})();const[h,p,d]=nm(i,this.gamma.read(),this.beta.read(),r,this.epsilon),m=(e,t,n)=>{si((()=>{const i=1-n,a=e.read(),s=xi(Ja(a,t),i);e.write(Ja(a,s))}))};return(()=>{m(this.movingMean,p,this.momentum),m(this.movingVariance,d,this.momentum)})(),h}))}getConfig(){const e={axis:this.axis,momentum:this.momentum,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:vc(this.betaInitializer),gammaInitializer:vc(this.gammaInitializer),movingMeanInitializer:vc(this.movingMeanInitializer),movingVarianceInitializer:vc(this.movingVarianceInitializer),betaRegularizer:Gp(this.betaRegularizer),gammaRegularizer:Gp(this.gammaRegularizer),betaConstraint:uh(this.betaConstraint),gammaConstraint:uh(this.gammaConstraint)},t=super.getConfig();return Object.assign(e,t),e}}im.className="BatchNormalization",yi(im);class am extends Dc{constructor(e){if(null==e&&(e={}),super(e),this.axis=null==e.axis?-1:e.axis,"number"==typeof this.axis){if(!Number.isInteger(this.axis))throw new Error(`Expected axis to be an integer, but received ${this.axis}`)}else{if(!Array.isArray(this.axis))throw new Error(`Expected axis to be an integer or an array of integers, but received ${JSON.stringify(this.axis)}`);for(const e of this.axis)if(!Number.isInteger(e))throw new Error(`Expected axis to be an array of integers, but received ${JSON.stringify(this.axis)}`)}this.epsilon=null==e.epsilon?.001:e.epsilon,this.center=null==e.center||e.center,this.scale=null==e.scale||e.scale,this.betaInitializer=yc(e.betaInitializer||"zeros"),this.gammaInitializer=yc(e.gammaInitializer||"ones"),this.betaRegularizer=Kp(e.betaRegularizer),this.gammaRegularizer=Kp(e.gammaRegularizer),this.supportsMasking=!0}build(e){const t=(e=xc(e)).length;"number"==typeof this.axis&&(this.axis=[this.axis]);for(let e=0;e<this.axis.length;++e)this.axis[e]<0&&(this.axis[e]+=t);for(const e of this.axis)if(e<0||e>=t)throw new Error(`Invalid axis: ${e}`);if(this.axis.length!==il(this.axis).length)throw new Error(`Found duplicate axes in: ${this.axis}`);const n=this.axis.map((t=>e[t]));this.scale?this.gamma=this.addWeight("gamma",n,"float32",this.gammaInitializer,this.gammaRegularizer,true):this.gamma=null,this.center?this.beta=this.addWeight("beta",n,"float32",this.betaInitializer,this.betaRegularizer,true):this.beta=null,this.built=!0}call(e,t){const n=kc(e),i=n.shape,a=i.length;return si((()=>{let{mean:e,variance:t}=rs(n,this.axis,!0);const s=Vo(1,a);for(const e of this.axis)s[e]=i[e];const r=e=>null!=e&&e.shape.length!==a?_i(e,s):e;let o=this.scale?r(this.gamma.read()):null,l=this.center?r(this.beta.read()):null;const c=[],u=[];for(let e=0;e<a;++e)-1!==this.axis.indexOf(e)?(c.push(i[e]),u.push(1)):(c.push(1),u.push(i[e]));return e=Ra(e,c),t=Ra(t,c),null!=o&&(o=Ra(o,u)),null!=l&&(l=Ra(l,u)),tm(n,e,t,l,o,this.epsilon)}))}getConfig(){const e={axis:this.axis,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:vc(this.betaInitializer),gammaInitializer:vc(this.gammaInitializer),betaRegularizer:Gp(this.betaRegularizer),gammaRegularizer:Gp(this.gammaRegularizer)},t=super.getConfig();return Object.assign(e,t),e}}am.className="LayerNormalization",yi(am);class sm extends Dc{constructor(e){if(null==e&&(e={}),super(e),this.dataFormat=null==e.dataFormat?"channelsLast":e.dataFormat,null==e.padding)this.padding=[[1,1],[1,1]];else if("number"==typeof e.padding)this.padding=[[e.padding,e.padding],[e.padding,e.padding]];else{if(e.padding=e.padding,2!==e.padding.length)throw new Bo(`ZeroPadding2D expects padding to be a length-2 array, but received a length-${e.padding.length} array.`);let t,n;if("number"==typeof e.padding[0])t=[e.padding[0],e.padding[0]],n=[e.padding[1],e.padding[1]];else{if(e.padding=e.padding,2!==e.padding[0].length)throw new Bo(`ZeroPadding2D expects height padding to be a length-2 array, but received a length-${e.padding[0].length} array.`);if(t=e.padding[0],2!==e.padding[1].length)throw new Bo(`ZeroPadding2D expects width padding to be a length-2 array, but received a length-${e.padding[1].length} array.`);n=e.padding[1]}this.padding=[t,n]}this.inputSpec=[new Ac({ndim:4})]}computeOutputShape(e){let t,n;return e=xc(e),"channelsFirst"===this.dataFormat?(t=null!=e[2]&&e[2]>=0?e[2]+this.padding[0][0]+this.padding[0][1]:null,n=null!=e[3]&&e[3]>=0?e[3]+this.padding[1][0]+this.padding[1][1]:null,[e[0],e[1],t,n]):(t=null!=e[1]&&e[1]>=0?e[1]+this.padding[0][0]+this.padding[0][1]:null,n=null!=e[2]&&e[2]>=0?e[2]+this.padding[1][0]+this.padding[1][1]:null,[e[0],t,n,e[3]])}call(e,t){return si((()=>{return t=kc(e),n=this.padding,i=this.dataFormat,si((()=>{if(4!==t.rank)throw new Bo(`temporalPadding expects input tensor to be 4-D, but received a ${t.rank}-D tensor.`);if(null==n&&(n=[[1,1],[1,1]]),2!==n.length||2!==n[0].length||2!==n[1].length)throw new Bo("spatial2dPadding expects `padding` to be an Array of two Arrays, each of which is an Array of two integers.");if(null==i&&(i="channelsLast"),"channelsLast"!==i&&"channelsFirst"!==i)throw new Bo(`Unknown data format: ${i}. Supported data formats are 'channelsLast' and 'channelsFirst.`);let e;return e="channelsFirst"===i?[[0,0],[0,0],n[0],n[1]]:[[0,0],n[0],n[1],[0,0]],cs(t,e)}));
4573
+ function tm(e,t,n,i,a,s=.001){let r;if(2===e.rank)r=Gi(e,t,n,i,a,s);else if(3===e.rank)r=Ki(e,t,n,i,a,s);else{if(4!==e.rank)throw new Uo(`batchNormalization is not implemented for array of rank ${e.rank} yet`);r=qi(e,t,n,i,a,s)}return r}function nm(e,t,n,i,a=.001){return E(i.slice().sort(),zl(0,e.rank-1))?function(e,t,n,i,a=.001){return si((()=>{const s=rs(e,i),r=s.mean,o=s.variance;return[tm(e,r,o,n,t,a),r,o]}))}(e,t,n,i,a):function(e,t,n,i,a=.001){return si((()=>{const s=rs(e,i),r=s.mean,o=s.variance,l=[];for(const t of zl(0,e.rank))-1!==i.indexOf(t)?l.push(1):l.push(e.shape[t]);const c=_i(r,l),u=_i(o,l),h=null==t?null:_i(t,l),p=null==n?null:_i(n,l);return[tm(e,c,u,p,h,a),r,o]}))}(e,t,n,i,a)}em.className="AlphaDropout",yi(em);class im extends Dc{constructor(e){null==e&&(e={}),super(e),this.supportsMasking=!0,this.axis=null==e.axis?-1:e.axis,this.momentum=null==e.momentum?.99:e.momentum,this.epsilon=null==e.epsilon?.001:e.epsilon,this.center=null==e.center||e.center,this.scale=null==e.scale||e.scale,this.betaInitializer=yc(e.betaInitializer||"zeros"),this.gammaInitializer=yc(e.gammaInitializer||"ones"),this.movingMeanInitializer=yc(e.movingMeanInitializer||"zeros"),this.movingVarianceInitializer=yc(e.movingVarianceInitializer||"ones"),this.betaConstraint=ph(e.betaConstraint),this.gammaConstraint=ph(e.gammaConstraint),this.betaRegularizer=Kp(e.betaRegularizer),this.gammaRegularizer=Kp(e.gammaRegularizer)}build(e){e=xc(e);const t=this.axis>=0?this.axis:this.axis+e.length,n=e[t];if(null==n)throw new Bo(`Axis ${t} of input tensor should have a defined dimension but the layer received an input with shape ${JSON.stringify(e)}.`);this.inputSpec=[new Cc({ndim:e.length,axes:{[t]:n}})];const i=[n];this.scale&&(this.gamma=this.addWeight("gamma",i,null,this.gammaInitializer,this.gammaRegularizer,!0,this.gammaConstraint)),this.center&&(this.beta=this.addWeight("beta",i,null,this.betaInitializer,this.betaRegularizer,!0,this.betaConstraint)),this.movingMean=this.addWeight("moving_mean",i,null,this.movingMeanInitializer,null,!1),this.movingVariance=this.addWeight("moving_variance",i,null,this.movingVarianceInitializer,null,!1),this.built=!0}call(e,t){return si((()=>{const n=null!=t.training&&t.training,i=kc(e),a=i.shape,s=a.length,r=zl(0,s),o=this.axis>=0?this.axis:this.axis+s;r.splice(o,1);const l=Go(1,s);l[o]=a[o];const c=r.slice();c.sort();const u=!E(c,zl(0,s).slice(0,s-1));if(!n)return(()=>{if(u){const e=_i(this.movingMean.read(),l),t=_i(this.movingVariance.read(),l),n=this.center?_i(this.beta.read(),l):null,a=this.scale?_i(this.gamma.read(),l):null;return tm(i,e,t,n,a,this.epsilon)}return tm(i,this.movingMean.read(),this.movingVariance.read(),null==this.beta?null:this.beta.read(),null==this.gamma?null:this.gamma.read(),this.epsilon)})();const[h,p,d]=nm(i,this.gamma.read(),this.beta.read(),r,this.epsilon),m=(e,t,n)=>{si((()=>{const i=1-n,a=e.read(),s=xi(Ja(a,t),i);e.write(Ja(a,s))}))};return(()=>{m(this.movingMean,p,this.momentum),m(this.movingVariance,d,this.momentum)})(),h}))}getConfig(){const e={axis:this.axis,momentum:this.momentum,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:vc(this.betaInitializer),gammaInitializer:vc(this.gammaInitializer),movingMeanInitializer:vc(this.movingMeanInitializer),movingVarianceInitializer:vc(this.movingVarianceInitializer),betaRegularizer:Vp(this.betaRegularizer),gammaRegularizer:Vp(this.gammaRegularizer),betaConstraint:uh(this.betaConstraint),gammaConstraint:uh(this.gammaConstraint)},t=super.getConfig();return Object.assign(e,t),e}}im.className="BatchNormalization",yi(im);class am extends Dc{constructor(e){if(null==e&&(e={}),super(e),this.axis=null==e.axis?-1:e.axis,"number"==typeof this.axis){if(!Number.isInteger(this.axis))throw new Error(`Expected axis to be an integer, but received ${this.axis}`)}else{if(!Array.isArray(this.axis))throw new Error(`Expected axis to be an integer or an array of integers, but received ${JSON.stringify(this.axis)}`);for(const e of this.axis)if(!Number.isInteger(e))throw new Error(`Expected axis to be an array of integers, but received ${JSON.stringify(this.axis)}`)}this.epsilon=null==e.epsilon?.001:e.epsilon,this.center=null==e.center||e.center,this.scale=null==e.scale||e.scale,this.betaInitializer=yc(e.betaInitializer||"zeros"),this.gammaInitializer=yc(e.gammaInitializer||"ones"),this.betaRegularizer=Kp(e.betaRegularizer),this.gammaRegularizer=Kp(e.gammaRegularizer),this.supportsMasking=!0}build(e){const t=(e=xc(e)).length;"number"==typeof this.axis&&(this.axis=[this.axis]);for(let e=0;e<this.axis.length;++e)this.axis[e]<0&&(this.axis[e]+=t);for(const e of this.axis)if(e<0||e>=t)throw new Error(`Invalid axis: ${e}`);if(this.axis.length!==il(this.axis).length)throw new Error(`Found duplicate axes in: ${this.axis}`);const n=this.axis.map((t=>e[t]));this.scale?this.gamma=this.addWeight("gamma",n,"float32",this.gammaInitializer,this.gammaRegularizer,true):this.gamma=null,this.center?this.beta=this.addWeight("beta",n,"float32",this.betaInitializer,this.betaRegularizer,true):this.beta=null,this.built=!0}call(e,t){const n=kc(e),i=n.shape,a=i.length;return si((()=>{let{mean:e,variance:t}=rs(n,this.axis,!0);const s=Go(1,a);for(const e of this.axis)s[e]=i[e];const r=e=>null!=e&&e.shape.length!==a?_i(e,s):e;let o=this.scale?r(this.gamma.read()):null,l=this.center?r(this.beta.read()):null;const c=[],u=[];for(let e=0;e<a;++e)-1!==this.axis.indexOf(e)?(c.push(i[e]),u.push(1)):(c.push(1),u.push(i[e]));return e=Ra(e,c),t=Ra(t,c),null!=o&&(o=Ra(o,u)),null!=l&&(l=Ra(l,u)),tm(n,e,t,l,o,this.epsilon)}))}getConfig(){const e={axis:this.axis,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:vc(this.betaInitializer),gammaInitializer:vc(this.gammaInitializer),betaRegularizer:Vp(this.betaRegularizer),gammaRegularizer:Vp(this.gammaRegularizer)},t=super.getConfig();return Object.assign(e,t),e}}am.className="LayerNormalization",yi(am);class sm extends Dc{constructor(e){if(null==e&&(e={}),super(e),this.dataFormat=null==e.dataFormat?"channelsLast":e.dataFormat,null==e.padding)this.padding=[[1,1],[1,1]];else if("number"==typeof e.padding)this.padding=[[e.padding,e.padding],[e.padding,e.padding]];else{if(e.padding=e.padding,2!==e.padding.length)throw new Bo(`ZeroPadding2D expects padding to be a length-2 array, but received a length-${e.padding.length} array.`);let t,n;if("number"==typeof e.padding[0])t=[e.padding[0],e.padding[0]],n=[e.padding[1],e.padding[1]];else{if(e.padding=e.padding,2!==e.padding[0].length)throw new Bo(`ZeroPadding2D expects height padding to be a length-2 array, but received a length-${e.padding[0].length} array.`);if(t=e.padding[0],2!==e.padding[1].length)throw new Bo(`ZeroPadding2D expects width padding to be a length-2 array, but received a length-${e.padding[1].length} array.`);n=e.padding[1]}this.padding=[t,n]}this.inputSpec=[new Cc({ndim:4})]}computeOutputShape(e){let t,n;return e=xc(e),"channelsFirst"===this.dataFormat?(t=null!=e[2]&&e[2]>=0?e[2]+this.padding[0][0]+this.padding[0][1]:null,n=null!=e[3]&&e[3]>=0?e[3]+this.padding[1][0]+this.padding[1][1]:null,[e[0],e[1],t,n]):(t=null!=e[1]&&e[1]>=0?e[1]+this.padding[0][0]+this.padding[0][1]:null,n=null!=e[2]&&e[2]>=0?e[2]+this.padding[1][0]+this.padding[1][1]:null,[e[0],t,n,e[3]])}call(e,t){return si((()=>{return t=kc(e),n=this.padding,i=this.dataFormat,si((()=>{if(4!==t.rank)throw new Bo(`temporalPadding expects input tensor to be 4-D, but received a ${t.rank}-D tensor.`);if(null==n&&(n=[[1,1],[1,1]]),2!==n.length||2!==n[0].length||2!==n[1].length)throw new Bo("spatial2dPadding expects `padding` to be an Array of two Arrays, each of which is an Array of two integers.");if(null==i&&(i="channelsLast"),"channelsLast"!==i&&"channelsFirst"!==i)throw new Bo(`Unknown data format: ${i}. Supported data formats are 'channelsLast' and 'channelsFirst.`);let e;return e="channelsFirst"===i?[[0,0],[0,0],n[0],n[1]]:[[0,0],n[0],n[1],[0,0]],cs(t,e)}));
4574
4574
  /**
4575
4575
  * @license
4576
4576
  * Copyright 2018 Google LLC
@@ -4590,7 +4590,7 @@ var t,n,i}))}getConfig(){const e={padding:this.padding,dataFormat:this.dataForma
4590
4590
  * https://opensource.org/licenses/MIT.
4591
4591
  * =============================================================================
4592
4592
  */
4593
- function rm(e,t,n,i,a,s){return si((()=>{let r;wl(a),xl(s),kl(i),null==n&&(n=[1,1]),null==i&&(i="valid"),null==a&&(a="channelsLast"),null==s&&(s="max"),e=nd(e,a);const o="same"===i?"same":"valid";return r="max"===s?Xa(e,t,n,o):Ri(e,t,n,o),"channelsFirst"===a&&(r=hi(r,[0,3,1,2])),r}))}function om(e,t,n,i,a,s){return si((()=>{let r;wl(a),xl(s),kl(i),null==n&&(n=[1,1,1]),null==i&&(i="valid"),null==a&&(a="channelsLast"),null==s&&(s="max"),e=id(e,a);const o="same"===i?"same":"valid";return r="max"===s?es(e,t,n,o):Li(e,t,n,o),"channelsFirst"===a&&(r=hi(r,[0,4,1,2,3])),r}))}sm.className="ZeroPadding2D",yi(sm);class lm extends Dc{constructor(e){if(null==e.poolSize&&(e.poolSize=2),super(e),"number"==typeof e.poolSize)this.poolSize=[e.poolSize];else{if(!Array.isArray(e.poolSize)||1!==e.poolSize.length||"number"!=typeof e.poolSize[0])throw new Bo(`poolSize for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.poolSize)}`);this.poolSize=e.poolSize}if(ol(this.poolSize,"poolSize"),null==e.strides)this.strides=this.poolSize;else if("number"==typeof e.strides)this.strides=[e.strides];else{if(!Array.isArray(e.strides)||1!==e.strides.length||"number"!=typeof e.strides[0])throw new Bo(`strides for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.strides)}`);this.strides=e.strides}ol(this.strides,"strides"),this.padding=null==e.padding?"valid":e.padding,kl(this.padding),this.inputSpec=[new Ac({ndim:3})]}computeOutputShape(e){const t=ed((e=xc(e))[1],this.poolSize[0],this.padding,this.strides[0]);return[e[0],t,e[2]]}call(e,t){return si((()=>{this.invokeCallHook(e,t),e=Rl(kc(e),2);const n=this.poolingFunction(kc(e),[this.poolSize[0],1],[this.strides[0],1],this.padding,"channelsLast");return Us(n,[2])}))}getConfig(){const e={poolSize:this.poolSize,padding:this.padding,strides:this.strides},t=super.getConfig();return Object.assign(e,t),e}}class cm extends lm{constructor(e){super(e)}poolingFunction(e,t,n,i,a){return wl(a),kl(i),rm(e,t,n,i,a,"max")}}cm.className="MaxPooling1D",yi(cm);class um extends lm{constructor(e){super(e)}poolingFunction(e,t,n,i,a){return wl(a),kl(i),rm(e,t,n,i,a,"avg")}}um.className="AveragePooling1D",yi(um);class hm extends Dc{constructor(e){if(null==e.poolSize&&(e.poolSize=[2,2]),super(e),this.poolSize=Array.isArray(e.poolSize)?e.poolSize:[e.poolSize,e.poolSize],null==e.strides)this.strides=this.poolSize;else if(Array.isArray(e.strides)){if(2!==e.strides.length)throw new Bo(`If the strides property of a 2D pooling layer is an Array, it is expected to have a length of 2, but received length ${e.strides.length}.`);this.strides=e.strides}else this.strides=[e.strides,e.strides];ol(this.poolSize,"poolSize"),ol(this.strides,"strides"),this.padding=null==e.padding?"valid":e.padding,this.dataFormat=null==e.dataFormat?"channelsLast":e.dataFormat,wl(this.dataFormat),kl(this.padding),this.inputSpec=[new Ac({ndim:4})]}computeOutputShape(e){e=xc(e);let t="channelsFirst"===this.dataFormat?e[2]:e[1],n="channelsFirst"===this.dataFormat?e[3]:e[2];return t=ed(t,this.poolSize[0],this.padding,this.strides[0]),n=ed(n,this.poolSize[1],this.padding,this.strides[1]),"channelsFirst"===this.dataFormat?[e[0],e[1],t,n]:[e[0],t,n,e[3]]}call(e,t){return si((()=>(this.invokeCallHook(e,t),this.poolingFunction(kc(e),this.poolSize,this.strides,this.padding,this.dataFormat))))}getConfig(){const e={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}class pm extends hm{constructor(e){super(e)}poolingFunction(e,t,n,i,a){return wl(a),kl(i),rm(e,t,n,i,a,"max")}}pm.className="MaxPooling2D",yi(pm);class dm extends hm{constructor(e){super(e)}poolingFunction(e,t,n,i,a){return wl(a),kl(i),rm(e,t,n,i,a,"avg")}}dm.className="AveragePooling2D",yi(dm);class mm extends Dc{constructor(e){if(null==e.poolSize&&(e.poolSize=[2,2,2]),super(e),this.poolSize=Array.isArray(e.poolSize)?e.poolSize:[e.poolSize,e.poolSize,e.poolSize],null==e.strides)this.strides=this.poolSize;else if(Array.isArray(e.strides)){if(3!==e.strides.length)throw new Bo(`If the strides property of a 3D pooling layer is an Array, it is expected to have a length of 3, but received length ${e.strides.length}.`);this.strides=e.strides}else this.strides=[e.strides,e.strides,e.strides];ol(this.poolSize,"poolSize"),ol(this.strides,"strides"),this.padding=null==e.padding?"valid":e.padding,this.dataFormat=null==e.dataFormat?"channelsLast":e.dataFormat,wl(this.dataFormat),kl(this.padding),this.inputSpec=[new Ac({ndim:5})]}computeOutputShape(e){e=xc(e);let t="channelsFirst"===this.dataFormat?e[2]:e[1],n="channelsFirst"===this.dataFormat?e[3]:e[2],i="channelsFirst"===this.dataFormat?e[4]:e[3];return t=ed(t,this.poolSize[0],this.padding,this.strides[0]),n=ed(n,this.poolSize[1],this.padding,this.strides[1]),i=ed(i,this.poolSize[2],this.padding,this.strides[2]),"channelsFirst"===this.dataFormat?[e[0],e[1],t,n,i]:[e[0],t,n,i,e[4]]}call(e,t){return si((()=>(this.invokeCallHook(e,t),this.poolingFunction(kc(e),this.poolSize,this.strides,this.padding,this.dataFormat))))}getConfig(){const e={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}class fm extends mm{constructor(e){super(e)}poolingFunction(e,t,n,i,a){return wl(a),kl(i),om(e,t,n,i,a,"max")}}fm.className="MaxPooling3D",yi(fm);class gm extends mm{constructor(e){super(e)}poolingFunction(e,t,n,i,a){return wl(a),kl(i),om(e,t,n,i,a,"avg")}}gm.className="AveragePooling3D",yi(gm);class vm extends Dc{constructor(e){super(e),this.inputSpec=[new Ac({ndim:3})]}computeOutputShape(e){return[e[0],e[2]]}call(e,t){throw new Uo}}class ym extends vm{constructor(e){super(e||{})}call(e,t){return si((()=>{const t=kc(e);return ns(t,1)}))}}ym.className="GlobalAveragePooling1D",yi(ym);class bm extends vm{constructor(e){super(e||{})}call(e,t){return si((()=>{const t=kc(e);return Ia(t,1)}))}}bm.className="GlobalMaxPooling1D",yi(bm);class wm extends Dc{constructor(e){super(e),this.dataFormat=null==e.dataFormat?"channelsLast":e.dataFormat,wl(this.dataFormat),this.inputSpec=[new Ac({ndim:4})]}computeOutputShape(e){return"channelsLast"===this.dataFormat?[e[0],e[3]]:[e[0],e[1]]}call(e,t){throw new Uo}getConfig(){const e={dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}class km extends wm{call(e,t){return si((()=>{const t=kc(e);return"channelsLast"===this.dataFormat?ns(t,[1,2]):ns(t,[2,3])}))}}km.className="GlobalAveragePooling2D",yi(km);class xm extends wm{call(e,t){return si((()=>{const t=kc(e);return"channelsLast"===this.dataFormat?Ia(t,[1,2]):Ia(t,[2,3])}))}}xm.className="GlobalMaxPooling2D",yi(xm);
4593
+ function rm(e,t,n,i,a,s){return si((()=>{let r;wl(a),xl(s),kl(i),null==n&&(n=[1,1]),null==i&&(i="valid"),null==a&&(a="channelsLast"),null==s&&(s="max"),e=nd(e,a);const o="same"===i?"same":"valid";return r="max"===s?Xa(e,t,n,o):Ri(e,t,n,o),"channelsFirst"===a&&(r=hi(r,[0,3,1,2])),r}))}function om(e,t,n,i,a,s){return si((()=>{let r;wl(a),xl(s),kl(i),null==n&&(n=[1,1,1]),null==i&&(i="valid"),null==a&&(a="channelsLast"),null==s&&(s="max"),e=id(e,a);const o="same"===i?"same":"valid";return r="max"===s?es(e,t,n,o):Li(e,t,n,o),"channelsFirst"===a&&(r=hi(r,[0,4,1,2,3])),r}))}sm.className="ZeroPadding2D",yi(sm);class lm extends Dc{constructor(e){if(null==e.poolSize&&(e.poolSize=2),super(e),"number"==typeof e.poolSize)this.poolSize=[e.poolSize];else{if(!Array.isArray(e.poolSize)||1!==e.poolSize.length||"number"!=typeof e.poolSize[0])throw new Bo(`poolSize for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.poolSize)}`);this.poolSize=e.poolSize}if(ol(this.poolSize,"poolSize"),null==e.strides)this.strides=this.poolSize;else if("number"==typeof e.strides)this.strides=[e.strides];else{if(!Array.isArray(e.strides)||1!==e.strides.length||"number"!=typeof e.strides[0])throw new Bo(`strides for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.strides)}`);this.strides=e.strides}ol(this.strides,"strides"),this.padding=null==e.padding?"valid":e.padding,kl(this.padding),this.inputSpec=[new Cc({ndim:3})]}computeOutputShape(e){const t=ed((e=xc(e))[1],this.poolSize[0],this.padding,this.strides[0]);return[e[0],t,e[2]]}call(e,t){return si((()=>{this.invokeCallHook(e,t),e=Rl(kc(e),2);const n=this.poolingFunction(kc(e),[this.poolSize[0],1],[this.strides[0],1],this.padding,"channelsLast");return Us(n,[2])}))}getConfig(){const e={poolSize:this.poolSize,padding:this.padding,strides:this.strides},t=super.getConfig();return Object.assign(e,t),e}}class cm extends lm{constructor(e){super(e)}poolingFunction(e,t,n,i,a){return wl(a),kl(i),rm(e,t,n,i,a,"max")}}cm.className="MaxPooling1D",yi(cm);class um extends lm{constructor(e){super(e)}poolingFunction(e,t,n,i,a){return wl(a),kl(i),rm(e,t,n,i,a,"avg")}}um.className="AveragePooling1D",yi(um);class hm extends Dc{constructor(e){if(null==e.poolSize&&(e.poolSize=[2,2]),super(e),this.poolSize=Array.isArray(e.poolSize)?e.poolSize:[e.poolSize,e.poolSize],null==e.strides)this.strides=this.poolSize;else if(Array.isArray(e.strides)){if(2!==e.strides.length)throw new Bo(`If the strides property of a 2D pooling layer is an Array, it is expected to have a length of 2, but received length ${e.strides.length}.`);this.strides=e.strides}else this.strides=[e.strides,e.strides];ol(this.poolSize,"poolSize"),ol(this.strides,"strides"),this.padding=null==e.padding?"valid":e.padding,this.dataFormat=null==e.dataFormat?"channelsLast":e.dataFormat,wl(this.dataFormat),kl(this.padding),this.inputSpec=[new Cc({ndim:4})]}computeOutputShape(e){e=xc(e);let t="channelsFirst"===this.dataFormat?e[2]:e[1],n="channelsFirst"===this.dataFormat?e[3]:e[2];return t=ed(t,this.poolSize[0],this.padding,this.strides[0]),n=ed(n,this.poolSize[1],this.padding,this.strides[1]),"channelsFirst"===this.dataFormat?[e[0],e[1],t,n]:[e[0],t,n,e[3]]}call(e,t){return si((()=>(this.invokeCallHook(e,t),this.poolingFunction(kc(e),this.poolSize,this.strides,this.padding,this.dataFormat))))}getConfig(){const e={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}class pm extends hm{constructor(e){super(e)}poolingFunction(e,t,n,i,a){return wl(a),kl(i),rm(e,t,n,i,a,"max")}}pm.className="MaxPooling2D",yi(pm);class dm extends hm{constructor(e){super(e)}poolingFunction(e,t,n,i,a){return wl(a),kl(i),rm(e,t,n,i,a,"avg")}}dm.className="AveragePooling2D",yi(dm);class mm extends Dc{constructor(e){if(null==e.poolSize&&(e.poolSize=[2,2,2]),super(e),this.poolSize=Array.isArray(e.poolSize)?e.poolSize:[e.poolSize,e.poolSize,e.poolSize],null==e.strides)this.strides=this.poolSize;else if(Array.isArray(e.strides)){if(3!==e.strides.length)throw new Bo(`If the strides property of a 3D pooling layer is an Array, it is expected to have a length of 3, but received length ${e.strides.length}.`);this.strides=e.strides}else this.strides=[e.strides,e.strides,e.strides];ol(this.poolSize,"poolSize"),ol(this.strides,"strides"),this.padding=null==e.padding?"valid":e.padding,this.dataFormat=null==e.dataFormat?"channelsLast":e.dataFormat,wl(this.dataFormat),kl(this.padding),this.inputSpec=[new Cc({ndim:5})]}computeOutputShape(e){e=xc(e);let t="channelsFirst"===this.dataFormat?e[2]:e[1],n="channelsFirst"===this.dataFormat?e[3]:e[2],i="channelsFirst"===this.dataFormat?e[4]:e[3];return t=ed(t,this.poolSize[0],this.padding,this.strides[0]),n=ed(n,this.poolSize[1],this.padding,this.strides[1]),i=ed(i,this.poolSize[2],this.padding,this.strides[2]),"channelsFirst"===this.dataFormat?[e[0],e[1],t,n,i]:[e[0],t,n,i,e[4]]}call(e,t){return si((()=>(this.invokeCallHook(e,t),this.poolingFunction(kc(e),this.poolSize,this.strides,this.padding,this.dataFormat))))}getConfig(){const e={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}class fm extends mm{constructor(e){super(e)}poolingFunction(e,t,n,i,a){return wl(a),kl(i),om(e,t,n,i,a,"max")}}fm.className="MaxPooling3D",yi(fm);class gm extends mm{constructor(e){super(e)}poolingFunction(e,t,n,i,a){return wl(a),kl(i),om(e,t,n,i,a,"avg")}}gm.className="AveragePooling3D",yi(gm);class vm extends Dc{constructor(e){super(e),this.inputSpec=[new Cc({ndim:3})]}computeOutputShape(e){return[e[0],e[2]]}call(e,t){throw new Uo}}class ym extends vm{constructor(e){super(e||{})}call(e,t){return si((()=>{const t=kc(e);return ns(t,1)}))}}ym.className="GlobalAveragePooling1D",yi(ym);class bm extends vm{constructor(e){super(e||{})}call(e,t){return si((()=>{const t=kc(e);return Ta(t,1)}))}}bm.className="GlobalMaxPooling1D",yi(bm);class wm extends Dc{constructor(e){super(e),this.dataFormat=null==e.dataFormat?"channelsLast":e.dataFormat,wl(this.dataFormat),this.inputSpec=[new Cc({ndim:4})]}computeOutputShape(e){return"channelsLast"===this.dataFormat?[e[0],e[3]]:[e[0],e[1]]}call(e,t){throw new Uo}getConfig(){const e={dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}class km extends wm{call(e,t){return si((()=>{const t=kc(e);return"channelsLast"===this.dataFormat?ns(t,[1,2]):ns(t,[2,3])}))}}km.className="GlobalAveragePooling2D",yi(km);class xm extends wm{call(e,t){return si((()=>{const t=kc(e);return"channelsLast"===this.dataFormat?Ta(t,[1,2]):Ta(t,[2,3])}))}}xm.className="GlobalMaxPooling2D",yi(xm);
4594
4594
  /**
4595
4595
  * @license
4596
4596
  * Copyright 2018 Google LLC
@@ -4600,7 +4600,7 @@ function rm(e,t,n,i,a,s){return si((()=>{let r;wl(a),xl(s),kl(i),null==n&&(n=[1,
4600
4600
  * https://opensource.org/licenses/MIT.
4601
4601
  * =============================================================================
4602
4602
  */
4603
- class Sm extends Dc{constructor(e){super(e),this.layer=e.layer}build(e){this.built=!0}get trainable(){return null!=this.layer&&this.layer.trainable}set trainable(e){null!=this.layer&&(this.layer.trainable=e)}get trainableWeights(){return this.layer.trainableWeights}get nonTrainableWeights(){return this.layer.nonTrainableWeights}get updates(){return this.layer._updates}get losses(){return this.layer.losses}getWeights(){return this.layer.getWeights()}setWeights(e){this.layer.setWeights(e)}getConfig(){const e={layer:{className:this.layer.getClassName(),config:this.layer.getConfig()}},t=super.getConfig();return Object.assign(e,t),e}setFastWeightInitDuringBuild(e){super.setFastWeightInitDuringBuild(e),null!=this.layer&&this.layer.setFastWeightInitDuringBuild(e)}static fromConfig(e,t,n={}){const i=Nh(t.layer,n);delete t.layer;const a={layer:i};return Object.assign(a,t),new e(a)}}class Nm extends Sm{constructor(e){super(e),this.supportsMasking=!0}build(e){if((e=xc(e)).length<3)throw new Bo(`TimeDistributed layer expects an input shape >= 3D, but received input shape ${JSON.stringify(e)}`);this.inputSpec=[{shape:e}];const t=[e[0]].concat(e.slice(2));this.layer.built||(this.layer.build(t),this.layer.built=!0),super.build(e)}computeOutputShape(e){const t=[(e=xc(e))[0]].concat(e.slice(2)),n=this.layer.computeOutputShape(t),i=e[1];return[n[0],i].concat(n.slice(1))}call(e,t){return si((()=>yd(((e,n)=>[kc(this.layer.call(e,t)),[]]),e=kc(e),[],!1,null,null,!1,!0)[1]))}}Nm.className="TimeDistributed",yi(Nm);class Im extends Sm{constructor(e){super(e);const t=e.layer.getConfig(),n={};n.className=e.layer.getClassName(),n.config=t,this.forwardLayer=Nh(n),t.goBackwards=!0!==t.goBackwards;const i={};var a;if(i.className=e.layer.getClassName(),i.config=t,this.backwardLayer=Nh(i),this.forwardLayer.name="forward_"+this.forwardLayer.name,this.backwardLayer.name="backward_"+this.backwardLayer.name,this.mergeMode=void 0===e.mergeMode?"concat":e.mergeMode,a=this.mergeMode,sl(yl,"BidirectionalMergeMode",a),e.weights)throw new Uo("weights support is not implemented for Bidirectional layer yet.");this._stateful=e.layer.stateful,this.returnSequences=e.layer.returnSequences,this.returnState=e.layer.returnState,this.supportsMasking=!0,this._trainable=!0,this.inputSpec=e.layer.inputSpec,this.numConstants=null}get trainable(){return this._trainable}set trainable(e){this._trainable=e,null!=this.forwardLayer&&(this.forwardLayer.trainable=e),null!=this.backwardLayer&&(this.backwardLayer.trainable=e)}getWeights(){return this.forwardLayer.getWeights().concat(this.backwardLayer.getWeights())}setWeights(e){const t=e.length,n=Math.floor(t/2);this.forwardLayer.setWeights(e.slice(0,n)),this.backwardLayer.setWeights(e.slice(n))}computeOutputShape(e){let t,n,i,a=this.forwardLayer.computeOutputShape(e);return Array.isArray(a)&&Array.isArray(a[0])||(a=[a]),this.returnState?(i=a.slice(1),t=a[0]):t=a[0],"concat"===this.mergeMode?(t[t.length-1]*=2,n=[t]):n=null==this.mergeMode?[t,t.slice()]:[t],this.returnState?null==this.mergeMode?n.concat(i).concat(i.slice()):[t].concat(i).concat(i.slice()):Ho(n)}apply(e,t){let n=null==t?null:t.initialState,i=null==t?null:t.constants;null==t&&(t={});const a=vd(e,n,i,this.numConstants);if(e=a.inputs,n=a.initialState,i=a.constants,Array.isArray(e)&&(n=e.slice(1),e=e[0]),(null==n||0===n.length)&&null==i)return super.apply(e,t);const s=[],r=[];if(null!=n){const e=n.length;if(e%2>0)throw new Bo("When passing `initialState` to a Bidrectional RNN, the state should be an Array containing the states of the underlying RNNs.");t.initialState=n,s.push(...n);const i=n.map((e=>new Ac({shape:e.shape})));this.forwardLayer.stateSpec=i.slice(0,e/2),this.backwardLayer.stateSpec=i.slice(e/2),r.push(...i)}if(null!=i)throw new Uo("Support for constants in Bidirectional layers is not implemented yet.");const o=s[0]instanceof Cc;for(const e of s)if(e instanceof Cc!==o)throw new Bo("The initial state of a Bidirectional layer cannot be specified as a mix of symbolic and non-symbolic tensors");if(o){const n=[e].concat(s),i=this.inputSpec.concat(r),a=this.inputSpec;this.inputSpec=i;const o=super.apply(n,t);return this.inputSpec=a,o}return super.apply(e,t)}call(e,t){return si((()=>{const n=t.initialState;let i,a,s,r;if(null==n)i=this.forwardLayer.call(e,t),a=this.backwardLayer.call(e,t);else{const s=n.slice(0,n.length/2),r=n.slice(n.length/2);i=this.forwardLayer.call(e,Object.assign(t,{initialState:s})),a=this.backwardLayer.call(e,Object.assign(t,{initialState:r}))}return this.returnState&&(Array.isArray(i)&&(s=i.slice(1).concat(a.slice(1))),i=i[0],a=a[0]),this.returnSequences&&(a=Cs(a,1)),"concat"===this.mergeMode?r=Pl([i,a]):"sum"===this.mergeMode?r=bi(i,a):"ave"===this.mergeMode?r=xi(.5,bi(i,a)):"mul"===this.mergeMode?r=xi(i,a):null==this.mergeMode&&(r=[i,a]),this.returnState?null==this.mergeMode?r.concat(s):[r].concat(s):r}))}resetStates(e){this.forwardLayer.resetStates(),this.backwardLayer.resetStates()}build(e){Nl(this.forwardLayer.name,(()=>{this.forwardLayer.build(e)})),Nl(this.backwardLayer.name,(()=>{this.backwardLayer.build(e)})),this.built=!0}computeMask(e,t){let n;if(Array.isArray(t)&&(t=t[0]),n=this.returnSequences?null==this.mergeMode?[t,t]:t:null==this.mergeMode?[null,null]:null,this.returnState){const e=this.forwardLayer.states.map((e=>null));return Array.isArray(n)?n.concat(e).concat(e):[n].concat(e).concat(e)}return n}get trainableWeights(){return this.forwardLayer.trainableWeights.concat(this.backwardLayer.trainableWeights)}get nonTrainableWeights(){return this.forwardLayer.nonTrainableWeights.concat(this.backwardLayer.nonTrainableWeights)}setFastWeightInitDuringBuild(e){super.setFastWeightInitDuringBuild(e),null!=this.forwardLayer&&this.forwardLayer.setFastWeightInitDuringBuild(e),null!=this.backwardLayer&&this.backwardLayer.setFastWeightInitDuringBuild(e)}getConfig(){const e={mergeMode:this.mergeMode},t=super.getConfig();return Object.assign(e,t),e}static fromConfig(e,t){const n=Nh(t.layer);if(delete t.layer,null!=t.numConstants)throw new Uo("Deserialization of a Bidirectional layer with numConstants present is not supported yet.");const i=t;return i.layer=n,new e(i)}}Im.className="Bidirectional",yi(Im);
4603
+ class Sm extends Dc{constructor(e){super(e),this.layer=e.layer}build(e){this.built=!0}get trainable(){return null!=this.layer&&this.layer.trainable}set trainable(e){null!=this.layer&&(this.layer.trainable=e)}get trainableWeights(){return this.layer.trainableWeights}get nonTrainableWeights(){return this.layer.nonTrainableWeights}get updates(){return this.layer._updates}get losses(){return this.layer.losses}getWeights(){return this.layer.getWeights()}setWeights(e){this.layer.setWeights(e)}getConfig(){const e={layer:{className:this.layer.getClassName(),config:this.layer.getConfig()}},t=super.getConfig();return Object.assign(e,t),e}setFastWeightInitDuringBuild(e){super.setFastWeightInitDuringBuild(e),null!=this.layer&&this.layer.setFastWeightInitDuringBuild(e)}static fromConfig(e,t,n={}){const i=Nh(t.layer,n);delete t.layer;const a={layer:i};return Object.assign(a,t),new e(a)}}class Nm extends Sm{constructor(e){super(e),this.supportsMasking=!0}build(e){if((e=xc(e)).length<3)throw new Bo(`TimeDistributed layer expects an input shape >= 3D, but received input shape ${JSON.stringify(e)}`);this.inputSpec=[{shape:e}];const t=[e[0]].concat(e.slice(2));this.layer.built||(this.layer.build(t),this.layer.built=!0),super.build(e)}computeOutputShape(e){const t=[(e=xc(e))[0]].concat(e.slice(2)),n=this.layer.computeOutputShape(t),i=e[1];return[n[0],i].concat(n.slice(1))}call(e,t){return si((()=>yd(((e,n)=>[kc(this.layer.call(e,t)),[]]),e=kc(e),[],!1,null,null,!1,!0)[1]))}}Nm.className="TimeDistributed",yi(Nm);class Tm extends Sm{constructor(e){super(e);const t=e.layer.getConfig(),n={};n.className=e.layer.getClassName(),n.config=t,this.forwardLayer=Nh(n),t.goBackwards=!0!==t.goBackwards;const i={};var a;if(i.className=e.layer.getClassName(),i.config=t,this.backwardLayer=Nh(i),this.forwardLayer.name="forward_"+this.forwardLayer.name,this.backwardLayer.name="backward_"+this.backwardLayer.name,this.mergeMode=void 0===e.mergeMode?"concat":e.mergeMode,a=this.mergeMode,sl(yl,"BidirectionalMergeMode",a),e.weights)throw new Uo("weights support is not implemented for Bidirectional layer yet.");this._stateful=e.layer.stateful,this.returnSequences=e.layer.returnSequences,this.returnState=e.layer.returnState,this.supportsMasking=!0,this._trainable=!0,this.inputSpec=e.layer.inputSpec,this.numConstants=null}get trainable(){return this._trainable}set trainable(e){this._trainable=e,null!=this.forwardLayer&&(this.forwardLayer.trainable=e),null!=this.backwardLayer&&(this.backwardLayer.trainable=e)}getWeights(){return this.forwardLayer.getWeights().concat(this.backwardLayer.getWeights())}setWeights(e){const t=e.length,n=Math.floor(t/2);this.forwardLayer.setWeights(e.slice(0,n)),this.backwardLayer.setWeights(e.slice(n))}computeOutputShape(e){let t,n,i,a=this.forwardLayer.computeOutputShape(e);return Array.isArray(a)&&Array.isArray(a[0])||(a=[a]),this.returnState?(i=a.slice(1),t=a[0]):t=a[0],"concat"===this.mergeMode?(t[t.length-1]*=2,n=[t]):n=null==this.mergeMode?[t,t.slice()]:[t],this.returnState?null==this.mergeMode?n.concat(i).concat(i.slice()):[t].concat(i).concat(i.slice()):Ho(n)}apply(e,t){let n=null==t?null:t.initialState,i=null==t?null:t.constants;null==t&&(t={});const a=vd(e,n,i,this.numConstants);if(e=a.inputs,n=a.initialState,i=a.constants,Array.isArray(e)&&(n=e.slice(1),e=e[0]),(null==n||0===n.length)&&null==i)return super.apply(e,t);const s=[],r=[];if(null!=n){const e=n.length;if(e%2>0)throw new Bo("When passing `initialState` to a Bidrectional RNN, the state should be an Array containing the states of the underlying RNNs.");t.initialState=n,s.push(...n);const i=n.map((e=>new Cc({shape:e.shape})));this.forwardLayer.stateSpec=i.slice(0,e/2),this.backwardLayer.stateSpec=i.slice(e/2),r.push(...i)}if(null!=i)throw new Uo("Support for constants in Bidirectional layers is not implemented yet.");const o=s[0]instanceof Ec;for(const e of s)if(e instanceof Ec!==o)throw new Bo("The initial state of a Bidirectional layer cannot be specified as a mix of symbolic and non-symbolic tensors");if(o){const n=[e].concat(s),i=this.inputSpec.concat(r),a=this.inputSpec;this.inputSpec=i;const o=super.apply(n,t);return this.inputSpec=a,o}return super.apply(e,t)}call(e,t){return si((()=>{const n=t.initialState;let i,a,s,r;if(null==n)i=this.forwardLayer.call(e,t),a=this.backwardLayer.call(e,t);else{const s=n.slice(0,n.length/2),r=n.slice(n.length/2);i=this.forwardLayer.call(e,Object.assign(t,{initialState:s})),a=this.backwardLayer.call(e,Object.assign(t,{initialState:r}))}return this.returnState&&(Array.isArray(i)&&(s=i.slice(1).concat(a.slice(1))),i=i[0],a=a[0]),this.returnSequences&&(a=Es(a,1)),"concat"===this.mergeMode?r=Pl([i,a]):"sum"===this.mergeMode?r=bi(i,a):"ave"===this.mergeMode?r=xi(.5,bi(i,a)):"mul"===this.mergeMode?r=xi(i,a):null==this.mergeMode&&(r=[i,a]),this.returnState?null==this.mergeMode?r.concat(s):[r].concat(s):r}))}resetStates(e){this.forwardLayer.resetStates(),this.backwardLayer.resetStates()}build(e){Nl(this.forwardLayer.name,(()=>{this.forwardLayer.build(e)})),Nl(this.backwardLayer.name,(()=>{this.backwardLayer.build(e)})),this.built=!0}computeMask(e,t){let n;if(Array.isArray(t)&&(t=t[0]),n=this.returnSequences?null==this.mergeMode?[t,t]:t:null==this.mergeMode?[null,null]:null,this.returnState){const e=this.forwardLayer.states.map((e=>null));return Array.isArray(n)?n.concat(e).concat(e):[n].concat(e).concat(e)}return n}get trainableWeights(){return this.forwardLayer.trainableWeights.concat(this.backwardLayer.trainableWeights)}get nonTrainableWeights(){return this.forwardLayer.nonTrainableWeights.concat(this.backwardLayer.nonTrainableWeights)}setFastWeightInitDuringBuild(e){super.setFastWeightInitDuringBuild(e),null!=this.forwardLayer&&this.forwardLayer.setFastWeightInitDuringBuild(e),null!=this.backwardLayer&&this.backwardLayer.setFastWeightInitDuringBuild(e)}getConfig(){const e={mergeMode:this.mergeMode},t=super.getConfig();return Object.assign(e,t),e}static fromConfig(e,t){const n=Nh(t.layer);if(delete t.layer,null!=t.numConstants)throw new Uo("Deserialization of a Bidirectional layer with numConstants present is not supported yet.");const i=t;return i.layer=n,new e(i)}}Tm.className="Bidirectional",yi(Tm);
4604
4604
  /**
4605
4605
  * @license
4606
4606
  * Copyright 2022 CodeSmith LLC
@@ -4610,7 +4610,7 @@ class Sm extends Dc{constructor(e){super(e),this.layer=e.layer}build(e){this.bui
4610
4610
  * https://opensource.org/licenses/MIT.
4611
4611
  * =============================================================================
4612
4612
  */
4613
- class Tm extends Dc{constructor(e){super(e),this.scale=e.scale,e.offset?this.offset=e.offset:this.offset=0}getConfig(){const e={scale:this.scale,offset:this.offset},t=super.getConfig();return Object.assign(e,t),e}call(e,t){return si((()=>("float32"!==(e=kc(e)).dtype&&(e=_l(e,"float32")),bi(xi(e,this.scale),this.offset))))}}Tm.className="Rescaling",yi(Tm);
4613
+ class Im extends Dc{constructor(e){super(e),this.scale=e.scale,e.offset?this.offset=e.offset:this.offset=0}getConfig(){const e={scale:this.scale,offset:this.offset},t=super.getConfig();return Object.assign(e,t),e}call(e,t){return si((()=>("float32"!==(e=kc(e)).dtype&&(e=_l(e,"float32")),bi(xi(e,this.scale),this.offset))))}}Im.className="Rescaling",yi(Im);
4614
4614
  /**
4615
4615
  * @license
4616
4616
  * Copyright 2022 CodeSmith LLC
@@ -4620,7 +4620,7 @@ class Tm extends Dc{constructor(e){super(e),this.scale=e.scale,e.offset?this.off
4620
4620
  * https://opensource.org/licenses/MIT.
4621
4621
  * =============================================================================
4622
4622
  */
4623
- const{resizeBilinear:Em,cropAndResize:Am}=zr;class Cm extends Dc{constructor(e){super(e),this.height=e.height,this.width=e.width}centerCrop(e,t,n,i,a,s,r,o){return si((()=>{let l,c=!1;const u=[t/s,n/r,(i+t)/s,(a+n)/r],h=[];3===e.rank?(c=!0,l=Ws([e])):l=e;for(let e=0;e<l.shape[0];e++)h.push(u);const p=gn(h,[h.length,4]),d=Ts(0,h.length,1,"int32"),m=Am(l,p,d,[i,a],"nearest");return _l(c?kc(Js(m)):m,o)}))}upsize(e,t,n,i){return si((()=>_l(Em(e,[t,n]),i)))}call(e,t){return si((()=>{const t=kc(e),n=t.dtype,i=t.shape,a=i[i.length-3],s=i[i.length-2];let r=0;a!==this.height&&(r=Math.floor((a-this.height)/2));let o=0;return s!==this.width&&(o=Math.floor((s-this.width)/2),0===o&&(o=1)),r>=0&&o>=0?this.centerCrop(t,r,o,this.height,this.width,a,s,n):this.upsize(e,this.height,this.width,n)}))}getConfig(){const e={height:this.height,width:this.width},t=super.getConfig();return Object.assign(e,t),e}computeOutputShape(e){const t=(e=xc(e)).length-3,n=e.length-2;return e[t]=this.height,e[n]=this.width,e}}Cm.className="CenterCrop",yi(Cm);
4623
+ const{resizeBilinear:Am,cropAndResize:Cm}=zr;class Em extends Dc{constructor(e){super(e),this.height=e.height,this.width=e.width}centerCrop(e,t,n,i,a,s,r,o){return si((()=>{let l,c=!1;const u=[t/s,n/r,(i+t)/s,(a+n)/r],h=[];3===e.rank?(c=!0,l=Ws([e])):l=e;for(let e=0;e<l.shape[0];e++)h.push(u);const p=gn(h,[h.length,4]),d=Is(0,h.length,1,"int32"),m=Cm(l,p,d,[i,a],"nearest");return _l(c?kc(Js(m)):m,o)}))}upsize(e,t,n,i){return si((()=>_l(Am(e,[t,n]),i)))}call(e,t){return si((()=>{const t=kc(e),n=t.dtype,i=t.shape,a=i[i.length-3],s=i[i.length-2];let r=0;a!==this.height&&(r=Math.floor((a-this.height)/2));let o=0;return s!==this.width&&(o=Math.floor((s-this.width)/2),0===o&&(o=1)),r>=0&&o>=0?this.centerCrop(t,r,o,this.height,this.width,a,s,n):this.upsize(e,this.height,this.width,n)}))}getConfig(){const e={height:this.height,width:this.width},t=super.getConfig();return Object.assign(e,t),e}computeOutputShape(e){const t=(e=xc(e)).length-3,n=e.length-2;return e[t]=this.height,e[n]=this.width,e}}Em.className="CenterCrop",yi(Em);
4624
4624
  /**
4625
4625
  * @license
4626
4626
  * Copyright 2022 CodeSmith LLC
@@ -4630,7 +4630,7 @@ const{resizeBilinear:Em,cropAndResize:Am}=zr;class Cm extends Dc{constructor(e){
4630
4630
  * https://opensource.org/licenses/MIT.
4631
4631
  * =============================================================================
4632
4632
  */
4633
- class $m extends Dc{constructor(e){super(e),this.numTokens=e.numTokens,e.outputMode?this.outputMode=e.outputMode:this.outputMode="multiHot"}getConfig(){const e={numTokens:this.numTokens,outputMode:this.outputMode},t=super.getConfig();return Object.assign(e,t),e}computeOutputShape(e){return null==(e=xc(e))?[this.numTokens]:"oneHot"===this.outputMode&&1!==e[e.length-1]?(e.push(this.numTokens),e):(e[e.length-1]=this.numTokens,e)}call(e,t){return si((()=>{let n;if("int32"!==(e=kc(e)).dtype&&(e=_l(e,"int32")),void 0!==t.countWeights){if("count"!==this.outputMode)throw new Bo(`countWeights is not used when outputMode !== count.\n Received countWeights=${t.countWeights}`);n=kc(t.countWeights)}const i=Ia(e),a=Ta(e),s=Pa(this.numTokens,i).bufferSync().get(0),r=Ba(a,0).bufferSync().get(0);if(!s||!r)throw new Bo(`Input values must be between 0 < values <= numTokens with numTokens=${this.numTokens}`);
4633
+ class $m extends Dc{constructor(e){super(e),this.numTokens=e.numTokens,e.outputMode?this.outputMode=e.outputMode:this.outputMode="multiHot"}getConfig(){const e={numTokens:this.numTokens,outputMode:this.outputMode},t=super.getConfig();return Object.assign(e,t),e}computeOutputShape(e){return null==(e=xc(e))?[this.numTokens]:"oneHot"===this.outputMode&&1!==e[e.length-1]?(e.push(this.numTokens),e):(e[e.length-1]=this.numTokens,e)}call(e,t){return si((()=>{let n;if("int32"!==(e=kc(e)).dtype&&(e=_l(e,"int32")),void 0!==t.countWeights){if("count"!==this.outputMode)throw new Bo(`countWeights is not used when outputMode !== count.\n Received countWeights=${t.countWeights}`);n=kc(t.countWeights)}const i=Ta(e),a=Ia(e),s=Pa(this.numTokens,i).bufferSync().get(0),r=Ba(a,0).bufferSync().get(0);if(!s||!r)throw new Bo(`Input values must be between 0 < values <= numTokens with numTokens=${this.numTokens}`);
4634
4634
  /**
4635
4635
  * @license
4636
4636
  * Copyright 2022 CodeSmith LLC
@@ -4667,7 +4667,7 @@ const jm=new Set(["bilinear","nearest"]);class zm extends Dc{constructor(e){if(s
4667
4667
  * limitations under the License.
4668
4668
  * =============================================================================
4669
4669
  */
4670
- xt(Io),xt(lo),xt(Eo),xt(Ao),xt(Co),xt($o),xt(wo),xt(jo),xt(Mo),xt(vo),xt(_o),xt(xo),xt(ro);var Dm={"штих":"noun","пяних":"noun","белих":"adjective","борзих":"adjective","малих":"adjective","старих":"adjective","дарнопих":"noun","сухих":"adjective","черемних":"noun","сирих":"adjective","плохих":"adjective","целих":"adjective","жих":"noun","войцих":"noun","скорих":"adjective","бурих":"adjective","чалих":"adjective","серих":"adjective","удалих":"adjective","карих":"adjective","гених":"noun","литвих":"noun","марцих":"noun","сізих":"adjective","яних":"noun","мжачих":"adjective","сірих":"adjective","янбих":"noun","бодрих":"adjective","стрий":"noun","чорторий":"noun","юрий":"adjective","цибрий":"noun","цібрий":"noun","карий":"adjective","куприй":"noun","кирий":"noun","негрий":"noun","губрий":"noun","шкабрий":"noun","замрий":"noun","передрий":"noun","одерий":"noun","жегрий":"noun","жарий":"adjective","зюбрий":"noun","семерий":"noun","лий":"noun","бий":"noun","рий":"noun","вий":"noun","ший":"noun","валий":"noun","крайній":"adjective","осінній":"adjective","кутній":"adjective","середній":"adjective","горішній":"adjective","безродній":"adjective","осадчій":"adjective","кий":"noun","новохатній":"adjective","очеретній":"adjective","рбий":"noun","закутній":"adjective","недавній":"adjective","порожній":"adjective","бокий":"noun","вчерашній":"adjective","огородній":"adjective","трощий":"noun","вчорашній":"adjective","житній":"adjective","нижній":"adjective","синій":"adjective","хорий":"noun","краснобокій":"adjective","хижній":"adjective","забродній":"adjective","калюжній":"adjective","виноградній":"adjective","коломий":"noun","летучій":"adjective","поздній":"adjective","серий":"noun","нагорній":"adjective","фартушній":"adjective","холошвій":"noun","батий":"noun","волошиній":"adjective","жирий":"noun","заможній":"adjective","короткій":"adjective","останній":"adjective","передній":"adjective","піддубній":"adjective","пізній":"adjective","погородній":"adjective","бояжній":"adjective","смий":"noun","задвірній":"adjective","остатній":"adjective","підсадній":"adjective","достатній":"adjective","зимній":"adjective","рябой":"adjective","рудой":"adjective","козодой":"noun","яровой":"adjective","кривой":"adjective","садовой":"adjective","полевой":"adjective","сисой":"noun","плохой":"adjective","сухой":"adjective","гаєвой":"adjective","глухой":"adjective","горевой":"adjective","кутовой":"adjective","копаной":"adjective","злой":"adjective","сєдой":"adjective","благой":"adjective","водостой":"noun","косой":"adjective","ліждвой":"noun","большой":"adjective","половой":"adjective","чорной":"adjective","косогой":"adjective","золотой":"adjective","лановой":"adjective","яловой":"adjective","дорогой":"adjective","німой":"adjective","первой":"adjective","русой":"adjective","худой":"adjective","цаподой":"noun","авасілой":"noun","валовой":"adjective","гнідой":"adjective","молокопой":"noun","золотобой":"noun","ярковой":"noun","аміхалакіой":"noun","седой":"adjective","крутой":"adjective","кучной":"adjective","слепой":"adjective","дурной":"adjective","молодой":"adjective","бухой":"adjective","самотній":"adjective","біла":"adjective","бура":"adjective","велика":"adjective","домовина":"noun","рослина":"noun","врецьона":"noun","глибока":"adjective","висока":"adjective","гладка":"adjective","грицина":"noun","гужва":"noun","ковінька":"noun","дика":"adjective","діброва":"noun","кицька":"noun","ківа":"noun","лепка":"adjective","островерха":"adjective","петрина":"noun","прудка":"adjective","семенина":"noun","турчина":"noun","чуприна":"noun","швидка":"adjective","щербина":"noun","яковина":"noun","синьоока":"adjective","крива":"adjective","сліпа":"adjective","глуха":"adjective","жовта":"adjective","добра":"adjective","хоробра":"adjective","сухоребра":"adjective","гарна":"adjective","мала":"adjective","весна":"noun","зла":"adjective","жива":"adjective","ніяка":"adjective","ціла":"adjective","молода":"adjective","далека":"adjective","золота":"adjective","жвава":"adjective","дорога":"adjective","коса":"adjective","литва":"noun","чужа":"adjective","тепла":"adjective","груба":"adjective","слава":"noun","брова":"noun","стара":"adjective","катерина":"noun","василина":"noun","нижня":"adjective","худа":"adjective","проста":"adjective","дівоча":"adjective","крута":"adjective","метка":"adjective","чорна":"adjective","сторона":"noun","невкрита":"adjective","руда":"adjective","темна":"adjective","проява":"noun","тиха":"adjective","божа":"adjective","весела":"adjective","бабина":"adjective","суха":"adjective","люта":"adjective","стіна":"noun","вража":"adjective","хороша":"adjective","легка":"adjective","козача":"adjective","польща":"noun","недужа":"adjective","розлога":"adjective","гаряча":"adjective","середня":"adjective","торішня":"adjective","сита":"adjective","гостра":"adjective","осіння":"adjective","невесела":"adjective","москва":"noun","широка":"adjective","половина":"noun","синя":"adjective","сира":"adjective","довга":"adjective","коротка":"adjective","лукава":"adjective","абияка":"adjective","королева":"noun","чайна":"adjective","сіра":"adjective","сутула":"adjective","сава":"noun","дебела":"adjective","мокра":"adjective","убога":"adjective","безрука":"adjective","димна":"adjective","мила":"adjective","боса":"adjective","гола":"adjective","красноока":"adjective","остання":"adjective","десна":"noun","житня":"adjective","тризна":"noun","цупка":"adjective","порожня":"adjective","ліва":"adjective","сьома":"adjective","вовна":"noun","сова":"noun","бела":"adjective","ряба":"adjective","гніда":"adjective","гожа":"adjective","кисла":"adjective","кутня":"adjective","огниста":"adjective","мудра":"adjective","дужа":"adjective","підстава":"noun","бодра":"adjective","бадьора":"adjective","кривохижа":"adjective","прихожа":"adjective","побожа":"adjective","пригожа":"adjective","петрунька":"noun","ковинька":"noun","кишинька":"noun","кропивянька":"noun","зеленька":"noun","лабунька":"noun","м'якенька":"adjective","бухонька":"noun","сиза":"adjective","маза":"adjective","блаза":"adjective","улина":"adjective","ейвена":"adjective","еремина":"adjective","ена":"adjective","клята":"adjective","периста":"adjective","працевита":"adjective","свіжа":"adjective","рижа":"adjective","копистира":"noun","скорина":"noun","більченя":"noun","кривошеня":"noun","нестереня":"noun","захарченя":"noun","войценя":"noun","протасеня":"noun","олещеня":"noun","денисеня":"noun","стрельченя":"noun","молодоженя":"noun","заграва":"noun","неменша":"adjective","неменьша":"adjective","меньша":"adjective","паший":"noun","пєша":"adjective","дзвінка":"adjective","пухка":"adjective","безпала":"adjective","вобла":"adjective","горжа":"adjective","горіла":"adjective","китаста":"adjective","лиса":"adjective","осадча":"adjective","пелехата":"adjective","підпала":"adjective","ставнича":"adjective","чала":"adjective","чубата":"adjective","целомудра":"adjective","кара":"adjective","коцупатра":"adjective","немудра":"adjective","шара":"adjective","шингира":"adjective","передера":"adjective","далекора":"adjective","жара":"adjective","яра":"adjective","золотопера":"adjective","остра":"adjective","хитра":"adjective","прозора":"adjective","карчинска":"adjective","гнила":"adjective","хижа":"adjective","крижа":"adjective","погоріла":"adjective","куца":"adjective","солодка":"adjective","безверха":"adjective","усата":"adjective","довгопола":"adjective","щербата":"adjective","пишна":"adjective","хоружа":"adjective","мирна":"adjective","долга":"adjective","бєла":"adjective","надточа":"adjective","гаркава":"adjective","мягка":"adjective","топча":"adjective","товста":"adjective","блага":"adjective","захожа":"adjective","боліла":"adjective","басиста":"adjective","басіста":"adjective","люба":"adjective","горбата":"adjective","драна":"adjective","куряча":"adjective","куса":"adjective","зайва":"adjective","кругла":"adjective","брижата":"adjective","скора":"adjective","плоха":"adjective","горяча":"adjective","тверда":"adjective","невідома":"adjective","картава":"adjective","горна":"adjective","черна":"adjective","гуржа":"adjective","гикава":"adjective","шита":"adjective","сєра":"adjective","сіда":"adjective","гнуча":"adjective","слизька":"adjective","бистра":"adjective","полева":"adjective","парубоча":"adjective","вібла":"adjective","мазна":"adjective","волохата":"adjective","шалена":"adjective","щира":"adjective","слаба":"adjective","суковата":"adjective","нища":"adjective","одинока":"adjective","сядриста":"adjective","яшна":"adjective","ракоча":"adjective","губата":"adjective","летуча":"adjective","патлата":"adjective","вяла":"adjective","гірна":"adjective","кіптіла":"adjective","кривовяза":"adjective","лиха":"adjective","подуфала":"adjective","буйна":"adjective","зайшла":"adjective","купрата":"adjective","мерзла":"adjective","варгата":"adjective","горда":"adjective","драпата":"adjective","загризла":"adjective","кичата":"adjective","оковита":"adjective","тлуста":"adjective","тонка":"adjective","коптіла":"adjective","погожа":"adjective","товстокора":"adjective","гладенька":"adjective","глубока":"adjective","періста":"adjective","виконавча":"adjective","кохана":"adjective","кризька":"adjective","німа":"adjective","росла":"adjective","некипіла":"adjective","плакуща":"adjective","похила":"adjective","строга":"adjective","богата":"adjective","заливча":"adjective","крамна":"adjective","поставнича":"adjective","безуса":"adjective","плоска":"adjective","сергата":"adjective","сухотепла":"adjective","толста":"adjective","шарпата":"adjective","безребра":"adjective","душна":"adjective","змерзла":"adjective","золотоверха":"adjective","наточа":"adjective","положа":"adjective","рокоча":"adjective","горлата":"adjective","скупа":"adjective","бібла":"adjective","ільніцка":"adjective","рогоча":"adjective","сміла":"adjective","щедра":"adjective","безклуба":"adjective","білоока":"adjective","шерстка":"adjective","безкишка":"adjective","летюча":"adjective","ловча":"adjective","піша":"adjective","раба":"adjective","суховерха":"adjective","тягла":"adjective","шаблиста":"adjective","шубала":"adjective","бедрата":"adjective","верлата":"adjective","галича":"adjective","запухла":"adjective","зубата":"adjective","кунта":"adjective","некрита":"adjective","пахуча":"adjective","теляча":"adjective","шпарка":"adjective","глива":"adjective","косата":"adjective","любима":"adjective","низька":"adjective","окрепка":"adjective","робоча":"adjective","слизькоуха":"adjective","хропата":"adjective","цівата":"adjective","шията":"adjective","безборода":"adjective","голоборода":"adjective","голомоза":"adjective","горєла":"adjective","єжела":"adjective","калиста":"adjective","корчиста":"adjective","курна":"adjective","надута":"adjective","пікуща":"adjective","погорела":"adjective","савіцка":"adjective","тупа":"adjective","дзяна":"adjective","жовкла":"adjective","колюча":"adjective","мазана":"adjective","сапата":"adjective","світа":"adjective","сухолитка":"adjective","цаберяба":"adjective","цвіла":"adjective","чупла":"adjective","асадча":"adjective","гарагата":"adjective","дзюбата":"adjective","долгопола":"adjective","жилава":"adjective","козина":"adjective","крепка":"adjective","ласа":"adjective","личката":"adjective","лобата":"adjective","льогка":"adjective","мишаста":"adjective","невмита":"adjective","перката":"adjective","рідка":"adjective","саплива":"adjective","тонкошкура":"adjective","цепла":"adjective","беззуба":"adjective","бушна":"adjective","бяла":"adjective","кріпка":"adjective","лакома":"adjective","майна":"adjective","нагла":"adjective","огніста":"adjective","осядла":"adjective","рабоча":"adjective","рапава":"adjective","розмаїта":"adjective","тупча":"adjective","ушата":"adjective","чорноока":"adjective","галянта":"adjective","голомовза":"adjective","одажа":"adjective","орлата":"adjective","пашиста":"adjective","пробита":"adjective","сепіта":"adjective","слабка":"adjective","цікава":"adjective","шамка":"adjective","шибиста":"adjective","баліцка":"adjective","бита":"adjective","боляча":"adjective","глабчаста":"adjective","гусліста":"adjective","деньдобра":"adjective","замліла":"adjective","лабата":"adjective","мяка":"adjective","несміла":"adjective","нєма":"adjective","обща":"adjective","одайна":"adjective","оката":"adjective","остиста":"adjective","пахуща":"adjective","пстра":"adjective","сладка":"adjective","храпата":"adjective","чесніша":"adjective","чула":"adjective","бідноша":"adjective","довгорука":"adjective","довгоша":"adjective","іваніцка":"adjective","корната":"adjective","кулява":"adjective","літуча":"adjective","марна":"adjective","медзата":"adjective","обмокла":"adjective","піджара":"adjective","побоча":"adjective","сагата":"adjective","удала":"adjective","усяка":"adjective","байдужа":"adjective","бескорса":"adjective","гірка":"adjective","главата":"adjective","горча":"adjective","горька":"adjective","добровольска":"adjective","довгопта":"adjective","досужа":"adjective","драпята":"adjective","камяна":"adjective","каправа":"adjective","киричата":"adjective","колота":"adjective","комарніцка":"adjective","люзна":"adjective","молодша":"adjective","неумита":"adjective","пересідла":"adjective","підла":"adjective","пухла":"adjective","семяниста":"adjective","сіроока":"adjective","стряпча":"adjective","твереза":"adjective","цибульска":"adjective","чарна":"adjective","ярка":"adjective","безгуба":"adjective","білоборода":"adjective","болєла":"adjective","бровата":"adjective","гікава":"adjective","голобока":"adjective","драбата":"adjective","жарка":"adjective","каплата":"adjective","кісла":"adjective","ковалевска":"adjective","ковальска":"adjective","козловска":"adjective","крилата":"adjective","куцка":"adjective","малоока":"adjective","мгка":"adjective","немята":"adjective","непроста":"adjective","нехороша":"adjective","пелихата":"adjective","підласа":"adjective","подпала":"adjective","руцка":"adjective","семениста":"adjective","услиста":"adjective","шорстка":"adjective","хила":"adjective","буката":"adjective","васалата":"adjective","вибла":"adjective","видойна":"adjective","виловата":"adjective","гарча":"adjective","горела":"adjective","дута":"adjective","зибла":"adjective","індича":"adjective","кальноока":"adjective","карнауха":"adjective","кривобедра":"adjective","кричфалуша":"adjective","кубата":"adjective","кужда":"adjective","ломана":"adjective","мацевита":"adjective","івашина":"noun","солоха":"adjective","перерва":"noun","проскура":"adjective","бова":"noun","сметана":"noun","дуброва":"noun","проскурня":"noun","родіна":"noun","єна":"noun","солонина":"noun","ліщина":"noun","лугина":"adjective","сосна":"noun","гавва":"noun","ужва":"noun","кулина":"adjective","халява":"noun","холява":"noun","підкова":"noun","крайня":"adjective","хохотва":"noun","цибулька":"noun","нікульча":"noun","кравчина":"noun","лупина":"adjective","лихошва":"noun","думбрава":"noun","плахотня":"adjective","покутня":"adjective","пона":"noun","семена":"noun","грона":"noun","єва":"noun","парасківа":"noun","шова":"noun","бурдужа":"adjective","козюберда":"adjective","говтва":"noun","приколота":"adjective","варнава":"noun","гурина":"adjective","рябокобила":"noun","кучина":"adjective","савва":"noun","кремена":"noun","малая":"adjective","горішня":"adjective","бурдюжа":"adjective","слаква":"noun","городня":"adjective","лиштва":"noun","цяцька":"noun","походня":"noun","недавня":"adjective","долішня":"adjective","марюхна":"noun","борона":"noun","колошва":"noun","семенча":"noun","затона":"noun","заплава":"noun","краснопера":"adjective","рибитва":"noun","сидора":"adjective","краплина":"noun","крутиголова":"noun","бакалина":"adjective","немна":"noun","очеретня":"adjective","пробийголова":"noun","мальона":"noun","сажина":"adjective","вчерашня":"adjective","бузина":"noun","забийворота":"noun","магльона":"noun","нейчева":"noun","потороча":"noun","ревіна":"noun","матьора":"adjective","святина":"noun","хіна":"noun","кожина":"adjective","наріжня":"noun","леона":"noun","передня":"adjective","савина":"adjective","сікачина":"noun","кльова":"noun","недолуга":"adjective","шкоропата":"noun","карасава":"noun","морева":"adjective","мустафіна":"noun","цьова":"noun","бубна":"noun","катона":"noun","міна":"noun","похвала":"noun","слоква":"noun","статіва":"noun","строна":"noun","вова":"noun","карева":"adjective","місюна":"noun","швая":"noun","бальва":"noun","вершина":"noun","врона":"noun","білокобила":"noun","гордина":"noun","кольва":"noun","льова":"noun","перекліта":"noun","основа":"noun","харена":"noun","борозна":"noun","будаква":"noun","каранікола":"noun","палесіка":"noun","рожина":"noun","штана":"noun","вицина":"noun","дубна":"noun","жовна":"noun","зіва":"noun","катарина":"noun","похмура":"adjective","фесина":"noun","шемена":"noun","галутва":"noun","зарева":"noun","ковальва":"noun","мирона":"noun","новосела":"noun","пачина":"adjective","совва":"noun","гіна":"noun","корона":"noun","новоженя":"noun","підберезня":"adjective","ряднина":"noun","сакська":"noun","канна":"noun","лукачина":"noun","плачінта":"noun","редьква":"noun","софина":"adjective","шатня":"adjective","блозва":"noun","вчорашня":"adjective","гриценя":"noun","куропатва":"noun","людва":"noun","стехна":"noun","парахоня":"noun","плєва":"noun","яворина":"noun","бендина":"noun","жовтонога":"adjective","конева":"adjective","мандалина":"noun","мацина":"noun","перезва":"noun","похвата":"noun","токмина":"noun","тюрина":"adjective","гицина":"noun","дзіна":"noun","куява":"noun","малонога":"adjective","стоколоса":"adjective","тимина":"adjective","біднина":"noun","вдовина":"adjective","лисохмара":"noun","микитина":"adjective","полівара":"noun","рибонька":"noun","ружина":"noun","тишина":"noun","цюрмаста":"noun","чалая":"adjective","васина":"noun","воїна":"noun","гулая":"noun","кова":"noun","она":"noun","палісіка":"noun","підошва":"noun","свидина":"noun","тирсина":"noun","хаврона":"noun","зона":"noun","кнзєва":"noun","розна":"adjective","ронжина":"noun","рудомина":"noun","сальва":"noun","скільсара":"noun","служала":"noun","фомина":"adjective","чупина":"adjective","шалупня":"noun","джупина":"noun","зоська":"noun","кузява":"noun","неледва":"noun","равва":"noun","разьва":"noun","шкорина":"noun","білозора":"adjective","бранціра":"noun","випна":"noun","галина":"adjective","мандаліна":"noun","мицька":"noun","мячина":"adjective","недосєка":"noun","пристая":"noun","м'яка":"adjective","вовчина":"noun","гринява":"noun","дівонька":"noun","ігіна":"noun","обійдихата":"noun","хижня":"adjective","челядина":"noun","янева":"adjective","голева":"adjective","дзюнька":"noun","дубрава":"noun","лигомина":"noun","мална":"noun","мархева":"noun","несправа":"noun","озява":"noun","панна":"noun","пупена":"noun","силява":"noun","сухокобила":"noun","цюрмоста":"noun","чевельча":"noun","чівільча":"noun","башева":"noun","бражна":"noun","варавва":"noun","волна":"noun","гольча":"noun","густа":"adjective","достатня":"adjective","зуграва":"noun","карапулька":"noun","кірна":"adjective","крапіва":"noun","луковина":"noun","мамона":"noun","мелещеня":"noun","мряна":"noun","параскева":"noun","похідня":"noun","пріхна":"noun","свтина":"noun","сьоська":"noun","терепіща":"noun","ціцяла":"noun","бодаква":"noun","гальвіта":"noun","деревенча":"noun","дона":"noun","дубена":"noun","задависвічка":"noun","йовва":"noun","капаціла":"noun","котельва":"noun","лісота":"noun","малюська":"noun","підсадня":"adjective","рєва":"noun","сувора":"adjective","хаджава":"noun","хомина":"adjective","псина":"noun","бобина":"noun","болотня":"adjective","бруква":"noun","кіона":"noun","ковбінька":"noun","кривонога":"adjective","лєва":"noun","мухина":"adjective","нефортуна":"noun","органіста":"noun","пасулька":"noun","пристава":"noun","бачина":"noun","безкорса":"adjective","бєлокобила":"noun","борзина":"noun","бружина":"noun","воротня":"adjective","гальона":"noun","голтва":"noun","горемульта":"noun","дацина":"noun","забанджала":"noun","злая":"adjective","кікена":"noun","коропатва":"noun","кузина":"adjective","лапунька":"noun","літава":"noun","мінчуна":"noun","на":"noun","ничая":"noun","новіцка":"adjective","пенькна":"noun","пухна":"noun","пуцята":"noun","рісна":"noun","розмаіта":"noun","румина":"adjective","свтна":"noun","сердита":"adjective","січінава":"noun","сментина":"noun","трізна":"noun","шкуропата":"noun","безхутра":"adjective","гальва":"noun","гнєда":"adjective","гребенча":"noun","гусонька":"noun","калабанька":"noun","козупляка":"noun","лапина":"adjective","мурина":"adjective","некульча":"noun","орона":"noun","парна":"adjective","пліва":"noun","приходька":"noun","сенина":"noun","солотва":"noun","тетева":"adjective","хавана":"noun","царева":"adjective","ахалая":"noun","варенька":"noun","варшава":"noun","вересоча":"noun","галунька":"noun","гліва":"noun","голина":"adjective","грузька":"adjective","гудина":"noun","євона":"noun","кірева":"adjective","кожем'яка":"noun","колоберда":"adjective","курінька":"noun","маржина":"noun","мигалина":"noun","мікава":"adjective","падва":"noun","паланичка":"adjective","палена":"adjective","подкова":"noun","ратушня":"adjective","селегейна":"noun","сминтина":"noun","сумина":"adjective","теміркая":"noun","ухата":"adjective","хавроня":"noun","холоста":"adjective","ціва":"noun","чернята":"noun","чикольва":"noun","шалина":"adjective","юдина":"adjective","адвена":"noun","балева":"adjective","брона":"noun","вербовата":"adjective","веремєва":"noun","волчаста":"adjective","гафина":"adjective","голутва":"noun","закрева":"noun","каджая":"noun","кальченя":"noun","капаниста":"adjective","кикина":"adjective","костерева":"noun","кривокобила":"noun","кулєва":"noun","лавна":"noun","маліцка":"adjective","молдова":"noun","моркова":"noun","пажина":"adjective","перевернихата":"noun","пилева":"adjective","піддубня":"adjective","постіва":"noun","пуста":"adjective","суботня":"adjective","фадеева":"adjective","ходаніцка":"adjective","хохітва":"noun","цибата":"adjective","черноока":"adjective","чкадуа":"noun","чокена":"noun","шепетина":"noun","шербина":"noun","яка":"adjective","ятва":"noun","безена":"noun","безшкура":"adjective","безязика":"adjective","белая":"adjective","берулава":"noun","бузна":"noun","бурсала":"noun","бучаста":"adjective","вчина":"noun","гапона":"noun","гернажа":"noun","гордуна":"noun","горсва":"noun","горясва":"noun","грицька":"noun","двіжона":"noun","задурня":"adjective","заслона":"noun","зачешигрива":"noun","йона":"noun","качна":"adjective","козовіта":"noun","криворота":"adjective","кур'ята":"noun","лозна":"adjective","люлява":"noun","лютая":"adjective","матухна":"noun","накутня":"adjective","плохая":"adjective","бухая":"adjective","самотня":"adjective","панібудьласка":"noun"};class Fm{encode(e){const t=new Uint8Array(1);switch(e.wordClass){case r.NOUN:t[0]=1;break;case r.ADJECTIVE:t[0]=0;break;default:throw new TypeError(`Invalid word class: "${e.wordClass}".`)}return t}decode(e){if(e.length<1||e.length>1)throw new RangeError("Invalid vector length.");const t=e[0];if(t<0||t>1)throw new RangeError("Invalid vector value.");return{wordClass:t>=.5?r.NOUN:r.ADJECTIVE}}}class _m{constructor(e,t=0){this.vectorSize=e,this.unknownCharcode=t}encode(e){var t;const n=new Uint8Array(this.vectorSize),i=e.slice(-this.vectorSize).toLowerCase().padStart(this.vectorSize,"-");for(let e=0;e<i.length;e+=1){const a=i[e];n[e]=null!==(t=s[a])&&void 0!==t?t:this.unknownCharcode}return n}}Q().set("IS_NODE",!1);var Rm={class_name:"Sequential",config:{name:"sequential_1",layers:[{class_name:"Embedding",config:{input_dim:34,output_dim:16,embeddings_initializer:{class_name:"RandomUniform",config:{minval:-.05,maxval:.05,seed:null}},embeddings_regularizer:null,activity_regularizer:null,embeddings_constraint:null,mask_zero:null,input_length:null,name:"embedding_Embedding1",trainable:!0,batch_input_shape:[null,null]}},{class_name:"SimpleRNN",config:{name:"simple_rnn_SimpleRNN1",trainable:!0,units:16,activation:"relu",use_bias:!0,kernel_initializer:{class_name:"VarianceScaling",config:{scale:1,mode:"fan_avg",distribution:"normal",seed:null}},recurrent_initializer:{class_name:"Orthogonal",config:{gain:1,seed:null}},bias_initializer:{class_name:"Zeros",config:{}},kernel_regularizer:null,recurrent_regularizer:null,bias_regularizer:null,activity_regularizer:null,kernel_constraint:null,recurrent_constraint:null,bias_constraint:null,dropout:0,recurrent_dropout:0,return_sequences:!1,return_state:!1,go_backwards:!1,stateful:!1,unroll:!1}},{class_name:"Dense",config:{units:1,activation:"sigmoid",use_bias:!0,kernel_initializer:{class_name:"VarianceScaling",config:{scale:1,mode:"fan_avg",distribution:"normal",seed:null}},bias_initializer:{class_name:"Zeros",config:{}},kernel_regularizer:null,bias_regularizer:null,activity_regularizer:null,kernel_constraint:null,bias_constraint:null,name:"dense_Dense1",trainable:!0}}]},keras_version:"tfjs-layers 4.2.0",backend:"tensor_flow.js"},Lm=[{name:"embedding_Embedding1/embeddings",shape:[34,16],dtype:"float32"},{name:"simple_rnn_SimpleRNN1/kernel",shape:[16,16],dtype:"float32"},{name:"simple_rnn_SimpleRNN1/recurrent_kernel",shape:[16,16],dtype:"float32"},{name:"simple_rnn_SimpleRNN1/bias",shape:[16],dtype:"float32"},{name:"dense_Dense1/kernel",shape:[16,1],dtype:"float32"},{name:"dense_Dense1/bias",shape:[1],dtype:"float32"}],Mm="D3HrvZUs7rxT6Vu+tVsfvPLyB70zbt695ECPvKyKWj7TnUO+JZ9pvs8MkL3/1DQ+kftzvPGZZL4aDpe8KiOnvSvRHz52vQK9mGiSPm50B72RCfM+7hW6PSOuTz7b9zG+M5MOPv/mYL7Q9Rk+aPgRvrfQuT6mQ2Q+eOawPp/PpLyM9yY+zB4APT27n75OVUk+V8y6vetFyD0zPlW+sqPfPER8Ub6J1pI+5QwEvcZktT12HLW+FSFGPU6s2ryQapW9/MNNvoK1t71R5sK8N6Y/vjqBzTtusl2+0Ks8PpZOQ74ua5U9TOIfvkpgHDxho/294hcTPkJaiL1iXTo9o28bPhnMBr69EoG8CAeCvtgxXT5kMKq+KnLfPbScM73jYjw+LTa8vSeQWj49+cU7/FH2PKtOwr5y8K29GMMdvrkIgb0wK4C8Zeq2vXlG+L15O4c+CaFGvpmCjD5guBg+0AAQPv0EjT3CdZ0+vLOBulXEAb7VVpi+WldAPpIP8T0ETFm+NcLIPZix17rKGEW+n8jxPfT8hr43TLC8esPRvX6k4D1lZ0C+WERdPo4Qab4SdWw+uWSevp7+zTjX5Xi8nw+ZvldSb7xUfke7HX01PVOV2zzFqV2+SqcNvvPUTz0nzZi9Zl+ePWj6Wr3PLjY+vbjrvSRr6b1es/w8oaLjPUC0G72spye9rsomPtW/t72QYEy9AtR6PuX44z1dLrk9k6HAPE1+Eb7w1mY+N8MSvuMLsj1qmsO6JrRAvsJowr7iA1E+udZGPDLR57xRSj8+GFSnvYNUujxIvpM8FHmHvkr8QD38Po29LslnvShYOD45FAE7vfaWPbnegruqB2W9MdUkPpskUb3YGTU+L3gwvQhAYD4ed66+qJQUvjydBr7bSam8fYz/PCTisD7GYoQ+HDxJvSaIR77s3u+8sVTkvaDBaL13FBs+Z8T4vT4aKj2d4DC7ft+GPvVXFLxGXGI9RJ9avl7RCD6ujIy+M+/zPQbAtr3B2+c9BpZcPYIBTj7QNsM95bqEPc221T3u7TO+M2PIPU/BQb78/nk+f4TmvV5Elj0VOAK+0Y+DPq0GkL364pI98CGUvjK4IL1CLoK+kohXvTS3I76BpcM9WE0Rva5vkz301Ui+CLe7vWkLnT1sjpM8EYyWPWblIryk+gI+gnQSvu9XKL7jtni9Rc/IvaonHj2sKBc+VzRovpdOpT64szY+OavnvfzjeLuBH62+OqC2OoeMBr0eJVi7ST7CPLK/3jxTOoC9BRUSPjNBaD6OIlm+7ApUPlbsWj5KIKi+J9F1Pfi88L1+JdA9a6F+PsiRub06rh2+HlXnPb5Wj774l+i6nifjvWMCtL2WnqW9pUNdvjQM4L0ZJDy9lZ+LPbJWhj2hUZO+iWF0vhq17zqKwOI9Qq6sPWo8gD3c0co9/5WaPLN6PL6HOLO8fXvUvEF2IL4QJ7S98UzCPZJTlb6VUCM+y7dqvkJXyTyxD+I9N6PXvUxuqr0jiuM9p1OgO/wUFL07zEy+n5rPvSLifbt4N5e+kbdRviF6Db0ZSjo+B+dXvqB+iT7nFI68Z9bUPU9FGT21fz4+fee2vaIHqLzRTtG8aGggPqQlpD1GORk9/FpnPjatAL60OPg8x+qAPdU74zxSk6+9lYwdPikogr6pxao99PmXvH+yEz4zu5U9IeURPXqY9LpuvYk8OGmYvFX7+TtuUaO9qg0GPph0Xr5vdYM+0deHvozgtryfgDC8DaCGPTVxHb6q0fI97pWqPOXMAj7Y9ae+fljRuoumt71vblO+UaetPcadt7yiUYi9R9x8PqXbmb4V9gK+v2jjvVsTU72VAJ29JC1vPcpy1D2uNZM9N5mlvru77rxAZSo9jZWkvv+0HD6CY6k9RvnyvLM8Wr4/Yjo+aEr4vcUQkj3Ef7+7DusLvhf0oLxUt1u+LdOWPndY+Ty5+Dq+QfqQvqgCbj7V0L68swkNviGjaz0SkyQ+h9uuvckW97rM35m+O7ERPQvQ4L2XN3a9XwqPPifY7TynN0i9enwJPWh2Tj27c02+k0bpPWtEGz4p+qs9DzsKPhlEoD7U1qM9v7SAvNgeIr7tPJM9om6CvhmNcz7pBIa9HEvlPRmEGj7SzgE9tdoAO8dkeT2N2Xm9ChofvhVPSj19rZG+A2PfPVrax72zacc9YWsTvjSKAj4inbu9GbJGvSEnt76qFeq8JsAnvZ0cO75Lk7e5G8+WPrc5Cb3RGVg+xwxfvgTMNr18pdU9U49jPaRh5rg8G2Q+iUtrObd+jT0FTYG+XgVgvKwXJr6TWuG9BWosPlr9pT6IF2G+boCIvU0FOb39ivu9aMA5viC1S714C3q+CES6Pt11j76mNqk+/btevCcEVL7z5cK+ALgyPJeTPb0+7O+7lftrPslPZz1EqIY9DWKYvdtgWL5/DwI9Q2NFvJhKcb0MMQo+NtltPWZcmT2FlVA9V5Nnvc9IJr0TXCA+nAIuPoF7xbon0SQ+Kwi8ve0ePb6O3++9k2/GvZoLlrxRDM48DwOkvEiWIz7jsgC+NYZzvTu7Jb7Jcgm8qAoyPg8zkT3o8UI+7Mt/vZsaYj7UZDm+Z4BTPBgkQr7CSTs+PKpvPbkSED3tAaW9LJ9APo74Fz62CFe8xMDCPi83F76ttk++K6FGvQkDDr42fbG+N9cbPvP1Br2CU1c+qukfvu3DJz6Vjfy8jlM9PZNaKL4Ceu29dDVCvoG7fD5qTLu75+YoPXt8GD7ey2U+KpynvemmCL1L1VC9LsfhvcoBND44he273UFiPrLzK72XXPS9ZjZGPtBwh7gwW2i+ccbxvXtoMj4Q/u49AzHBvoTjHD40AuW+OiwYP4x9JD6PGAY/KN7+Pc0xhb6OqxY9AptQvbc7Or39a9e6DJ/zPvd+iz6XX7g6kqsEP5LI1L7ICBk+1k5SP0lR0T43qYI+kbFLvcUh5L7+v90+5mnZveLTxj03yAS+phJLvW7x3b4m3J68GeeBvlrhgj05ac++0Yyfvcrz7L1/Y/i+ZjMKPhEy6j3ImRu+fRRuPkunGL5dMVG+Yd5Fv6ys1z6PXYI+JhzOvaGxDT4p38I+QcDHPtkxbb0XnjM/ogGYviZrLj291se+iNNqvpZuUb7nas8+lj4tvvyQ3D7w+FO9r4ybPs7MJD+WsIG9pGxHPqmQo75RdUG/gFs2vRXbrj7n87w9aGosPm8vDr/oUeO+2pWxPsk1RT7lvPS+YBmZvkDPU745ORi/BxbNPg83pD2KOSq9Nh0tPw6bSj+WVTk97hLcPnMDpT7GgXW8dL46vltPvb11QOu9CeYDPYDxwbx5UQ8+MnesPb+Ajj7Uv7m+qE+TvM+Qt77g88s+7940P8/1zj5p9+g+FugoPgNebT69zXg+IbhFvnHq6LsVozg+iIaBPau6Kr6tTOG+U1bhPS6zFD64rqY/FZebvhOPeL5DGXo+dwgLPjKu6z5+X78+iAsNPrs/Pb+RQoe+6MyqvWutu75ml7G+3Casvq63/b4exKi9+5lMv7V/yb4twI49cbIcv/+5/r5lWxE/78Q+PhjngT4SENI9xZKXPmmQEb9UJGK+eYE3vtOLiDxf4zo+9KX5Pl0APj9PhqA+i/wMv1iRsjzngaK+/ocBv8RUnr0hPdM+YAshv896DL1aukY+kiIJvsKhvD66FTi++84Fv5vWjL4lr6W+OLvyvba/krzwXgm9X8rUvv+XNb7jhSo/zfCAPLRlqD4Fn5S+DeQfP0847T7NIZ4+/gMAPxyfcT6VQOM+UOmWvWDtrD4TLFW9NGQSveJN9T7AuFm+MvUSv/TnFz8uw68+k05IPj26MTwDLsW+hsLFvifDqD7Z6d28z+AOv1DeZL8TnA++mrwBvT0BGL5ireW+PLbOOQjsJjzUmya/CcavOz8kwr70lmK+PHcmPsmi9r5VeAI+yly7PSGkIT6xV1Q/uHsKP4WFir4DBcc+SIJuPlP0Lb5Nufu+dKc3vk/X4L2Qvyo/jJSCPr3+Vr7NNA4/5AqcPoYisjuvO6g9JGKRPgxvQj/bUnG8yqAbP8wDO75rdkO+keIuPvrKxT4VCoQ9fx3XPih9K77kIOg99g2gPcrn4rxDzyy+TDdxPpzmHz//YWM+PIXFvTGs4z5SaaE9NAwkv4Qcub6gS3g+6Wa0vf3qJD8NDC2/q4z6PFVEob5p8yG+uSjhvjAMgD4GQ2Q/+EfRPlrsL79K2PO+FyOrPav1lT6vSzQ+nQOovRiVMD4Yfg4+weDxPv9V8b3ix407T0mFvEXdYT4DaKq+rE4YviLa2r4q/vI7hVWOvWgaV77A7QU/OU2iPp8QQT58RIA+Lbf+vo65Fz1RDRw+mv6WvdOImj4/IyY9a+vPO/pDuj6WiFe94SnbvW0cAb5HUcQ8croTvdeGIT6Q5p89/2EpPyPapj33gSS+q161vhFrSj00b5A9P6g4vssdob5sS5G+r72gvUDqCj+C5+a9lJHFPjtFxz10OYs+qXakvlUu5Trwp749nrcQPbAzwr5pCs8+UhoIvsHVdT7iw+i+UYxzPgTn5T50arg+R/4IP7kH2T2cguW+pQX+vFqQdr3z5yY+SdURProPID4CXhA9crIcP/7a4D6r/549Ly6lvXeFUb9n9xs/CC3oPrOgAj8iPwo/8nPXviKqAr8q6TQ+vrumPrdtHz8prJq+V1/oPUZWGr4Y4cU9nRopvtRCkz2jeTy+pJW0PgwDyz6XfIo+QmZevqCRSj1/pIa+KoufPllZvT5o244+nRIYP3TbM70N+8y+a7d2vcsSWj4Cdrw+AT8hPVoDwL0BxL2+G1pmPo/CZL66zSS+g2rFPvewar7nfGe+YEuevRgFIr7dyRS+KES0Pnu1p754F6s+/inJPXa3tL4Qd5A+OmbLPWvlnb75WsU9rRHMvsgqxD5MQ90+Y38LPnBkZj7fKIs9uJCHvdiuXr6D/Rw9hpVyPu9Vqr4Qzom85dP6vYymmr1yG5w+2gSMPlV5tT1D1ks+EKTZPm4gOb6ZC+w+k8EOPA8oXb6r9z2+h6Tgvm7Dvj7OzJQ+7tkIPvbDjz4TN6u9GneSPTIooD7GdRA/wYQ4vVr7b71F/QI+cRORPrRPWzxVX22+Yu2vPsHriL720za+oBlVPogMe72YNKM8r9aEO5uq1z7RegW+4aX1PqfYRD/wpfI9sVqvPCI99jpAtWC9eXJ2PBb++j6w+809iODsPfwV0b2kL7S9D+FLPQZECD4oYRA+V1Z+vjarEj5ZF/q8KJSAPkjENr7zNd28pKODPj8FPL8mgFY8kJVMvgBfQ75uooK++9TaPg/5Cr5Pzo6+1Yy3viONQL/Fvng+Bmn6vTpQkb0N7Oi94ZVHPYE2Hr7J/Rk+zQzKvL3Chj5d85o+Q/YRPrsjnj7YzJY+01w3PyVgGD6INkM+XtnevbmxiL7Z1NI+jpdgvggkdz0QnJq+35a8PZX0SL4+y78+grnOPYHzlD2VKRA/xRW4PqyCPL4Cowa/Ku+pvZabKz99894+sY/Vva/ezL1zsUw+er4IP8DL/D1qa2a+m6B3PK8Cq76mu2++gsjvvP0kBz8pWqe+SyotvKUdmz4pFXA7bkXCvbwSbj44g7c8mID4viXITL56E/G9zBVuPPD+u7wCmJc9v1nDuyyEX77G7Nq8GUwXvQJRVT3nTYY9/wK9Pct9sT1dCqU9aRsHvlmTFD2/B5M9PclmvNt2Jb8eqR2+bZhIvlmRVT4k0zU/OFSyvnCsHb/BfrK+ZZJGv10pNT8uXQk/AaVXvgbtG76M5kC+b6zpPfBICD8I1Lm8",Om={format:"layers-model",generatedBy:"TensorFlow.js tfjs-layers v4.2.0",convertedBy:null};const Pm="undefined"!=typeof Buffer&&("undefined"==typeof Blob||"undefined"==typeof atob||"undefined"==typeof btoa);class Bm{inflect(e,t,n){return a(this,void 0,void 0,(function*(){const i=[],a=e.split("-");for(let e=0;e<a.length;e+=1){const s=yield this.inflectNamePart(a[e],t,n,e===a.length-1);i.push(s)}return i.join("-")}))}}const Um=/[ая]$/i,Wm=/(ой|ий|ій|их)$/i;const Gm=new class extends Bm{constructor(e){super(),this.wordInflector=e}inflectNamePart(e,t,n){return this.wordInflector.inflect(e,{grammaticalCase:n,gender:t,application:"givenName"})}}(b),Vm=new class extends Bm{constructor(e){super(),this.wordInflector=e}inflectNamePart(e,t,n){return this.wordInflector.inflect(e,{grammaticalCase:n,gender:t,application:"patronymicName",customRuleFilter:e=>e.application.includes("patronymicName")})}}(b),Km=new class{constructor(e){this.modelLoader=e,this.modelPromise=null,this.wordTransformer=new _m(20),this.familyNameClassTransformer=new Fm}classify(e){return a(this,void 0,void 0,(function*(){let t=this.getCached(e);if(null!=t)return t;const n=yield this.loadModel(),i=this.wordTransformer.encode(e),a=yield n.predict(Ks([i])).data();return t=this.familyNameClassTransformer.decode(a),t}))}getCached(e){let t=null;const n=Dm[e.toLowerCase()];return n&&(t={wordClass:n}),t}loadModel(){return a(this,void 0,void 0,(function*(){return null==this.modelPromise&&(this.modelPromise=kp(this.modelLoader)),this.modelPromise}))}}(new class{load(){return a(this,void 0,void 0,(function*(){const e={};if(e.modelTopology=Rm,e.weightSpecs=Lm,e.weightData=function(e){if(Pm){const t=Buffer.from(e,"base64");return t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}const t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;++e)n.set([t.charCodeAt(e)],e);return n.buffer}(Mm),null!=Om){const t=Om;e.format=t.format,e.generatedBy=t.generatedBy,e.convertedBy=t.convertedBy,null!=t.signature&&(e.signature=t.signature),null!=t.userDefinedMetadata&&(e.userDefinedMetadata=t.userDefinedMetadata),null!=t.modelInitializer&&(e.modelInitializer=t.modelInitializer),null!=t.initializerSignature&&(e.initializerSignature=t.initializerSignature),null!=t.trainingConfig&&(e.trainingConfig=t.trainingConfig)}return e}))}}),qm=new class extends Bm{constructor(e,t){super(),this.wordInflector=e,this.familyNameClassifier=t}inflectNamePart(e,t,n,i){return a(this,void 0,void 0,(function*(){if(!i&&l(e))return e;let a=null;return this.isUncertainFamilyNameClass(e,t)&&(a=yield this.familyNameClassifier.classify(e)),this.wordInflector.inflect(e,{grammaticalCase:n,gender:t,wordClass:null==a?void 0:a.wordClass,application:"familyName"})}))}isUncertainFamilyNameClass(t,n){return n===e.GrammaticalGender.FEMININE&&Um.test(t)||n===e.GrammaticalGender.MASCULINE&&Wm.test(t)}}(b,Km),Hm=new class{constructor(e,t,n){this.givenNameInflector=e,this.patronymicNameInflector=t,this.familyNameInflector=n}inflect(e,t,n){return a(this,void 0,void 0,(function*(){const i={};return null!=e.givenName&&(i.givenName=yield this.givenNameInflector.inflect(e.givenName,t,n)),null!=e.patronymicName&&(i.patronymicName=yield this.patronymicNameInflector.inflect(e.patronymicName,t,n)),null!=e.familyName&&(i.familyName=yield this.familyNameInflector.inflect(e.familyName,t,n)),i}))}}
4670
+ xt(To),xt(lo),xt(Ao),xt(Co),xt(Eo),xt($o),xt(wo),xt(jo),xt(Mo),xt(vo),xt(_o),xt(xo),xt(ro);var Dm={"штих":"noun","пяних":"noun","белих":"adjective","борзих":"adjective","малих":"adjective","старих":"adjective","дарнопих":"noun","сухих":"adjective","черемних":"noun","сирих":"adjective","плохих":"adjective","целих":"adjective","жих":"noun","войцих":"noun","скорих":"adjective","бурих":"adjective","чалих":"adjective","серих":"adjective","удалих":"adjective","карих":"adjective","гених":"noun","литвих":"noun","марцих":"noun","сізих":"adjective","яних":"noun","мжачих":"adjective","сірих":"adjective","янбих":"noun","бодрих":"adjective","стрий":"noun","чорторий":"noun","юрий":"adjective","цибрий":"noun","цібрий":"noun","карий":"adjective","куприй":"noun","кирий":"noun","негрий":"noun","губрий":"noun","шкабрий":"noun","замрий":"noun","передрий":"noun","одерий":"noun","жегрий":"noun","жарий":"adjective","зюбрий":"noun","семерий":"noun","лий":"noun","бий":"noun","рий":"noun","вий":"noun","ший":"noun","валий":"noun","крайній":"adjective","осінній":"adjective","кутній":"adjective","середній":"adjective","горішній":"adjective","безродній":"adjective","осадчій":"adjective","кий":"noun","новохатній":"adjective","очеретній":"adjective","рбий":"noun","закутній":"adjective","недавній":"adjective","порожній":"adjective","бокий":"noun","вчерашній":"adjective","огородній":"adjective","трощий":"noun","вчорашній":"adjective","житній":"adjective","нижній":"adjective","синій":"adjective","хорий":"noun","краснобокій":"adjective","хижній":"adjective","забродній":"adjective","калюжній":"adjective","виноградній":"adjective","коломий":"noun","летучій":"adjective","поздній":"adjective","серий":"noun","нагорній":"adjective","фартушній":"adjective","холошвій":"noun","батий":"noun","волошиній":"adjective","жирий":"noun","заможній":"adjective","короткій":"adjective","останній":"adjective","передній":"adjective","піддубній":"adjective","пізній":"adjective","погородній":"adjective","бояжній":"adjective","смий":"noun","задвірній":"adjective","остатній":"adjective","підсадній":"adjective","достатній":"adjective","зимній":"adjective","рябой":"adjective","рудой":"adjective","козодой":"noun","яровой":"adjective","кривой":"adjective","садовой":"adjective","полевой":"adjective","сисой":"noun","плохой":"adjective","сухой":"adjective","гаєвой":"adjective","глухой":"adjective","горевой":"adjective","кутовой":"adjective","копаной":"adjective","злой":"adjective","сєдой":"adjective","благой":"adjective","водостой":"noun","косой":"adjective","ліждвой":"noun","большой":"adjective","половой":"adjective","чорной":"adjective","косогой":"adjective","золотой":"adjective","лановой":"adjective","яловой":"adjective","дорогой":"adjective","німой":"adjective","первой":"adjective","русой":"adjective","худой":"adjective","цаподой":"noun","авасілой":"noun","валовой":"adjective","гнідой":"adjective","молокопой":"noun","золотобой":"noun","ярковой":"noun","аміхалакіой":"noun","седой":"adjective","крутой":"adjective","кучной":"adjective","слепой":"adjective","дурной":"adjective","молодой":"adjective","бухой":"adjective","самотній":"adjective","біла":"adjective","бура":"adjective","велика":"adjective","домовина":"noun","рослина":"noun","врецьона":"noun","глибока":"adjective","висока":"adjective","гладка":"adjective","грицина":"noun","гужва":"noun","ковінька":"noun","дика":"adjective","діброва":"noun","кицька":"noun","ківа":"noun","лепка":"adjective","островерха":"adjective","петрина":"noun","прудка":"adjective","семенина":"noun","турчина":"noun","чуприна":"noun","швидка":"adjective","щербина":"noun","яковина":"noun","синьоока":"adjective","крива":"adjective","сліпа":"adjective","глуха":"adjective","жовта":"adjective","добра":"adjective","хоробра":"adjective","сухоребра":"adjective","гарна":"adjective","мала":"adjective","весна":"noun","зла":"adjective","жива":"adjective","ніяка":"adjective","ціла":"adjective","молода":"adjective","далека":"adjective","золота":"adjective","жвава":"adjective","дорога":"adjective","коса":"adjective","литва":"noun","чужа":"adjective","тепла":"adjective","груба":"adjective","слава":"noun","брова":"noun","стара":"adjective","катерина":"noun","василина":"noun","нижня":"adjective","худа":"adjective","проста":"adjective","дівоча":"adjective","крута":"adjective","метка":"adjective","чорна":"adjective","сторона":"noun","невкрита":"adjective","руда":"adjective","темна":"adjective","проява":"noun","тиха":"adjective","божа":"adjective","весела":"adjective","бабина":"adjective","суха":"adjective","люта":"adjective","стіна":"noun","вража":"adjective","хороша":"adjective","легка":"adjective","козача":"adjective","польща":"noun","недужа":"adjective","розлога":"adjective","гаряча":"adjective","середня":"adjective","торішня":"adjective","сита":"adjective","гостра":"adjective","осіння":"adjective","невесела":"adjective","москва":"noun","широка":"adjective","половина":"noun","синя":"adjective","сира":"adjective","довга":"adjective","коротка":"adjective","лукава":"adjective","абияка":"adjective","королева":"noun","чайна":"adjective","сіра":"adjective","сутула":"adjective","сава":"noun","дебела":"adjective","мокра":"adjective","убога":"adjective","безрука":"adjective","димна":"adjective","мила":"adjective","боса":"adjective","гола":"adjective","красноока":"adjective","остання":"adjective","десна":"noun","житня":"adjective","тризна":"noun","цупка":"adjective","порожня":"adjective","ліва":"adjective","сьома":"adjective","вовна":"noun","сова":"noun","бела":"adjective","ряба":"adjective","гніда":"adjective","гожа":"adjective","кисла":"adjective","кутня":"adjective","огниста":"adjective","мудра":"adjective","дужа":"adjective","підстава":"noun","бодра":"adjective","бадьора":"adjective","кривохижа":"adjective","прихожа":"adjective","побожа":"adjective","пригожа":"adjective","петрунька":"noun","ковинька":"noun","кишинька":"noun","кропивянька":"noun","зеленька":"noun","лабунька":"noun","м'якенька":"adjective","бухонька":"noun","сиза":"adjective","маза":"adjective","блаза":"adjective","улина":"adjective","ейвена":"adjective","еремина":"adjective","ена":"adjective","клята":"adjective","периста":"adjective","працевита":"adjective","свіжа":"adjective","рижа":"adjective","копистира":"noun","скорина":"noun","більченя":"noun","кривошеня":"noun","нестереня":"noun","захарченя":"noun","войценя":"noun","протасеня":"noun","олещеня":"noun","денисеня":"noun","стрельченя":"noun","молодоженя":"noun","заграва":"noun","неменша":"adjective","неменьша":"adjective","меньша":"adjective","паший":"noun","пєша":"adjective","дзвінка":"adjective","пухка":"adjective","безпала":"adjective","вобла":"adjective","горжа":"adjective","горіла":"adjective","китаста":"adjective","лиса":"adjective","осадча":"adjective","пелехата":"adjective","підпала":"adjective","ставнича":"adjective","чала":"adjective","чубата":"adjective","целомудра":"adjective","кара":"adjective","коцупатра":"adjective","немудра":"adjective","шара":"adjective","шингира":"adjective","передера":"adjective","далекора":"adjective","жара":"adjective","яра":"adjective","золотопера":"adjective","остра":"adjective","хитра":"adjective","прозора":"adjective","карчинска":"adjective","гнила":"adjective","хижа":"adjective","крижа":"adjective","погоріла":"adjective","куца":"adjective","солодка":"adjective","безверха":"adjective","усата":"adjective","довгопола":"adjective","щербата":"adjective","пишна":"adjective","хоружа":"adjective","мирна":"adjective","долга":"adjective","бєла":"adjective","надточа":"adjective","гаркава":"adjective","мягка":"adjective","топча":"adjective","товста":"adjective","блага":"adjective","захожа":"adjective","боліла":"adjective","басиста":"adjective","басіста":"adjective","люба":"adjective","горбата":"adjective","драна":"adjective","куряча":"adjective","куса":"adjective","зайва":"adjective","кругла":"adjective","брижата":"adjective","скора":"adjective","плоха":"adjective","горяча":"adjective","тверда":"adjective","невідома":"adjective","картава":"adjective","горна":"adjective","черна":"adjective","гуржа":"adjective","гикава":"adjective","шита":"adjective","сєра":"adjective","сіда":"adjective","гнуча":"adjective","слизька":"adjective","бистра":"adjective","полева":"adjective","парубоча":"adjective","вібла":"adjective","мазна":"adjective","волохата":"adjective","шалена":"adjective","щира":"adjective","слаба":"adjective","суковата":"adjective","нища":"adjective","одинока":"adjective","сядриста":"adjective","яшна":"adjective","ракоча":"adjective","губата":"adjective","летуча":"adjective","патлата":"adjective","вяла":"adjective","гірна":"adjective","кіптіла":"adjective","кривовяза":"adjective","лиха":"adjective","подуфала":"adjective","буйна":"adjective","зайшла":"adjective","купрата":"adjective","мерзла":"adjective","варгата":"adjective","горда":"adjective","драпата":"adjective","загризла":"adjective","кичата":"adjective","оковита":"adjective","тлуста":"adjective","тонка":"adjective","коптіла":"adjective","погожа":"adjective","товстокора":"adjective","гладенька":"adjective","глубока":"adjective","періста":"adjective","виконавча":"adjective","кохана":"adjective","кризька":"adjective","німа":"adjective","росла":"adjective","некипіла":"adjective","плакуща":"adjective","похила":"adjective","строга":"adjective","богата":"adjective","заливча":"adjective","крамна":"adjective","поставнича":"adjective","безуса":"adjective","плоска":"adjective","сергата":"adjective","сухотепла":"adjective","толста":"adjective","шарпата":"adjective","безребра":"adjective","душна":"adjective","змерзла":"adjective","золотоверха":"adjective","наточа":"adjective","положа":"adjective","рокоча":"adjective","горлата":"adjective","скупа":"adjective","бібла":"adjective","ільніцка":"adjective","рогоча":"adjective","сміла":"adjective","щедра":"adjective","безклуба":"adjective","білоока":"adjective","шерстка":"adjective","безкишка":"adjective","летюча":"adjective","ловча":"adjective","піша":"adjective","раба":"adjective","суховерха":"adjective","тягла":"adjective","шаблиста":"adjective","шубала":"adjective","бедрата":"adjective","верлата":"adjective","галича":"adjective","запухла":"adjective","зубата":"adjective","кунта":"adjective","некрита":"adjective","пахуча":"adjective","теляча":"adjective","шпарка":"adjective","глива":"adjective","косата":"adjective","любима":"adjective","низька":"adjective","окрепка":"adjective","робоча":"adjective","слизькоуха":"adjective","хропата":"adjective","цівата":"adjective","шията":"adjective","безборода":"adjective","голоборода":"adjective","голомоза":"adjective","горєла":"adjective","єжела":"adjective","калиста":"adjective","корчиста":"adjective","курна":"adjective","надута":"adjective","пікуща":"adjective","погорела":"adjective","савіцка":"adjective","тупа":"adjective","дзяна":"adjective","жовкла":"adjective","колюча":"adjective","мазана":"adjective","сапата":"adjective","світа":"adjective","сухолитка":"adjective","цаберяба":"adjective","цвіла":"adjective","чупла":"adjective","асадча":"adjective","гарагата":"adjective","дзюбата":"adjective","долгопола":"adjective","жилава":"adjective","козина":"adjective","крепка":"adjective","ласа":"adjective","личката":"adjective","лобата":"adjective","льогка":"adjective","мишаста":"adjective","невмита":"adjective","перката":"adjective","рідка":"adjective","саплива":"adjective","тонкошкура":"adjective","цепла":"adjective","беззуба":"adjective","бушна":"adjective","бяла":"adjective","кріпка":"adjective","лакома":"adjective","майна":"adjective","нагла":"adjective","огніста":"adjective","осядла":"adjective","рабоча":"adjective","рапава":"adjective","розмаїта":"adjective","тупча":"adjective","ушата":"adjective","чорноока":"adjective","галянта":"adjective","голомовза":"adjective","одажа":"adjective","орлата":"adjective","пашиста":"adjective","пробита":"adjective","сепіта":"adjective","слабка":"adjective","цікава":"adjective","шамка":"adjective","шибиста":"adjective","баліцка":"adjective","бита":"adjective","боляча":"adjective","глабчаста":"adjective","гусліста":"adjective","деньдобра":"adjective","замліла":"adjective","лабата":"adjective","мяка":"adjective","несміла":"adjective","нєма":"adjective","обща":"adjective","одайна":"adjective","оката":"adjective","остиста":"adjective","пахуща":"adjective","пстра":"adjective","сладка":"adjective","храпата":"adjective","чесніша":"adjective","чула":"adjective","бідноша":"adjective","довгорука":"adjective","довгоша":"adjective","іваніцка":"adjective","корната":"adjective","кулява":"adjective","літуча":"adjective","марна":"adjective","медзата":"adjective","обмокла":"adjective","піджара":"adjective","побоча":"adjective","сагата":"adjective","удала":"adjective","усяка":"adjective","байдужа":"adjective","бескорса":"adjective","гірка":"adjective","главата":"adjective","горча":"adjective","горька":"adjective","добровольска":"adjective","довгопта":"adjective","досужа":"adjective","драпята":"adjective","камяна":"adjective","каправа":"adjective","киричата":"adjective","колота":"adjective","комарніцка":"adjective","люзна":"adjective","молодша":"adjective","неумита":"adjective","пересідла":"adjective","підла":"adjective","пухла":"adjective","семяниста":"adjective","сіроока":"adjective","стряпча":"adjective","твереза":"adjective","цибульска":"adjective","чарна":"adjective","ярка":"adjective","безгуба":"adjective","білоборода":"adjective","болєла":"adjective","бровата":"adjective","гікава":"adjective","голобока":"adjective","драбата":"adjective","жарка":"adjective","каплата":"adjective","кісла":"adjective","ковалевска":"adjective","ковальска":"adjective","козловска":"adjective","крилата":"adjective","куцка":"adjective","малоока":"adjective","мгка":"adjective","немята":"adjective","непроста":"adjective","нехороша":"adjective","пелихата":"adjective","підласа":"adjective","подпала":"adjective","руцка":"adjective","семениста":"adjective","услиста":"adjective","шорстка":"adjective","хила":"adjective","буката":"adjective","васалата":"adjective","вибла":"adjective","видойна":"adjective","виловата":"adjective","гарча":"adjective","горела":"adjective","дута":"adjective","зибла":"adjective","індича":"adjective","кальноока":"adjective","карнауха":"adjective","кривобедра":"adjective","кричфалуша":"adjective","кубата":"adjective","кужда":"adjective","ломана":"adjective","мацевита":"adjective","івашина":"noun","солоха":"adjective","перерва":"noun","проскура":"adjective","бова":"noun","сметана":"noun","дуброва":"noun","проскурня":"noun","родіна":"noun","єна":"noun","солонина":"noun","ліщина":"noun","лугина":"adjective","сосна":"noun","гавва":"noun","ужва":"noun","кулина":"adjective","халява":"noun","холява":"noun","підкова":"noun","крайня":"adjective","хохотва":"noun","цибулька":"noun","нікульча":"noun","кравчина":"noun","лупина":"adjective","лихошва":"noun","думбрава":"noun","плахотня":"adjective","покутня":"adjective","пона":"noun","семена":"noun","грона":"noun","єва":"noun","парасківа":"noun","шова":"noun","бурдужа":"adjective","козюберда":"adjective","говтва":"noun","приколота":"adjective","варнава":"noun","гурина":"adjective","рябокобила":"noun","кучина":"adjective","савва":"noun","кремена":"noun","малая":"adjective","горішня":"adjective","бурдюжа":"adjective","слаква":"noun","городня":"adjective","лиштва":"noun","цяцька":"noun","походня":"noun","недавня":"adjective","долішня":"adjective","марюхна":"noun","борона":"noun","колошва":"noun","семенча":"noun","затона":"noun","заплава":"noun","краснопера":"adjective","рибитва":"noun","сидора":"adjective","краплина":"noun","крутиголова":"noun","бакалина":"adjective","немна":"noun","очеретня":"adjective","пробийголова":"noun","мальона":"noun","сажина":"adjective","вчерашня":"adjective","бузина":"noun","забийворота":"noun","магльона":"noun","нейчева":"noun","потороча":"noun","ревіна":"noun","матьора":"adjective","святина":"noun","хіна":"noun","кожина":"adjective","наріжня":"noun","леона":"noun","передня":"adjective","савина":"adjective","сікачина":"noun","кльова":"noun","недолуга":"adjective","шкоропата":"noun","карасава":"noun","морева":"adjective","мустафіна":"noun","цьова":"noun","бубна":"noun","катона":"noun","міна":"noun","похвала":"noun","слоква":"noun","статіва":"noun","строна":"noun","вова":"noun","карева":"adjective","місюна":"noun","швая":"noun","бальва":"noun","вершина":"noun","врона":"noun","білокобила":"noun","гордина":"noun","кольва":"noun","льова":"noun","перекліта":"noun","основа":"noun","харена":"noun","борозна":"noun","будаква":"noun","каранікола":"noun","палесіка":"noun","рожина":"noun","штана":"noun","вицина":"noun","дубна":"noun","жовна":"noun","зіва":"noun","катарина":"noun","похмура":"adjective","фесина":"noun","шемена":"noun","галутва":"noun","зарева":"noun","ковальва":"noun","мирона":"noun","новосела":"noun","пачина":"adjective","совва":"noun","гіна":"noun","корона":"noun","новоженя":"noun","підберезня":"adjective","ряднина":"noun","сакська":"noun","канна":"noun","лукачина":"noun","плачінта":"noun","редьква":"noun","софина":"adjective","шатня":"adjective","блозва":"noun","вчорашня":"adjective","гриценя":"noun","куропатва":"noun","людва":"noun","стехна":"noun","парахоня":"noun","плєва":"noun","яворина":"noun","бендина":"noun","жовтонога":"adjective","конева":"adjective","мандалина":"noun","мацина":"noun","перезва":"noun","похвата":"noun","токмина":"noun","тюрина":"adjective","гицина":"noun","дзіна":"noun","куява":"noun","малонога":"adjective","стоколоса":"adjective","тимина":"adjective","біднина":"noun","вдовина":"adjective","лисохмара":"noun","микитина":"adjective","полівара":"noun","рибонька":"noun","ружина":"noun","тишина":"noun","цюрмаста":"noun","чалая":"adjective","васина":"noun","воїна":"noun","гулая":"noun","кова":"noun","она":"noun","палісіка":"noun","підошва":"noun","свидина":"noun","тирсина":"noun","хаврона":"noun","зона":"noun","кнзєва":"noun","розна":"adjective","ронжина":"noun","рудомина":"noun","сальва":"noun","скільсара":"noun","служала":"noun","фомина":"adjective","чупина":"adjective","шалупня":"noun","джупина":"noun","зоська":"noun","кузява":"noun","неледва":"noun","равва":"noun","разьва":"noun","шкорина":"noun","білозора":"adjective","бранціра":"noun","випна":"noun","галина":"adjective","мандаліна":"noun","мицька":"noun","мячина":"adjective","недосєка":"noun","пристая":"noun","м'яка":"adjective","вовчина":"noun","гринява":"noun","дівонька":"noun","ігіна":"noun","обійдихата":"noun","хижня":"adjective","челядина":"noun","янева":"adjective","голева":"adjective","дзюнька":"noun","дубрава":"noun","лигомина":"noun","мална":"noun","мархева":"noun","несправа":"noun","озява":"noun","панна":"noun","пупена":"noun","силява":"noun","сухокобила":"noun","цюрмоста":"noun","чевельча":"noun","чівільча":"noun","башева":"noun","бражна":"noun","варавва":"noun","волна":"noun","гольча":"noun","густа":"adjective","достатня":"adjective","зуграва":"noun","карапулька":"noun","кірна":"adjective","крапіва":"noun","луковина":"noun","мамона":"noun","мелещеня":"noun","мряна":"noun","параскева":"noun","похідня":"noun","пріхна":"noun","свтина":"noun","сьоська":"noun","терепіща":"noun","ціцяла":"noun","бодаква":"noun","гальвіта":"noun","деревенча":"noun","дона":"noun","дубена":"noun","задависвічка":"noun","йовва":"noun","капаціла":"noun","котельва":"noun","лісота":"noun","малюська":"noun","підсадня":"adjective","рєва":"noun","сувора":"adjective","хаджава":"noun","хомина":"adjective","псина":"noun","бобина":"noun","болотня":"adjective","бруква":"noun","кіона":"noun","ковбінька":"noun","кривонога":"adjective","лєва":"noun","мухина":"adjective","нефортуна":"noun","органіста":"noun","пасулька":"noun","пристава":"noun","бачина":"noun","безкорса":"adjective","бєлокобила":"noun","борзина":"noun","бружина":"noun","воротня":"adjective","гальона":"noun","голтва":"noun","горемульта":"noun","дацина":"noun","забанджала":"noun","злая":"adjective","кікена":"noun","коропатва":"noun","кузина":"adjective","лапунька":"noun","літава":"noun","мінчуна":"noun","на":"noun","ничая":"noun","новіцка":"adjective","пенькна":"noun","пухна":"noun","пуцята":"noun","рісна":"noun","розмаіта":"noun","румина":"adjective","свтна":"noun","сердита":"adjective","січінава":"noun","сментина":"noun","трізна":"noun","шкуропата":"noun","безхутра":"adjective","гальва":"noun","гнєда":"adjective","гребенча":"noun","гусонька":"noun","калабанька":"noun","козупляка":"noun","лапина":"adjective","мурина":"adjective","некульча":"noun","орона":"noun","парна":"adjective","пліва":"noun","приходька":"noun","сенина":"noun","солотва":"noun","тетева":"adjective","хавана":"noun","царева":"adjective","ахалая":"noun","варенька":"noun","варшава":"noun","вересоча":"noun","галунька":"noun","гліва":"noun","голина":"adjective","грузька":"adjective","гудина":"noun","євона":"noun","кірева":"adjective","кожем'яка":"noun","колоберда":"adjective","курінька":"noun","маржина":"noun","мигалина":"noun","мікава":"adjective","падва":"noun","паланичка":"adjective","палена":"adjective","подкова":"noun","ратушня":"adjective","селегейна":"noun","сминтина":"noun","сумина":"adjective","теміркая":"noun","ухата":"adjective","хавроня":"noun","холоста":"adjective","ціва":"noun","чернята":"noun","чикольва":"noun","шалина":"adjective","юдина":"adjective","адвена":"noun","балева":"adjective","брона":"noun","вербовата":"adjective","веремєва":"noun","волчаста":"adjective","гафина":"adjective","голутва":"noun","закрева":"noun","каджая":"noun","кальченя":"noun","капаниста":"adjective","кикина":"adjective","костерева":"noun","кривокобила":"noun","кулєва":"noun","лавна":"noun","маліцка":"adjective","молдова":"noun","моркова":"noun","пажина":"adjective","перевернихата":"noun","пилева":"adjective","піддубня":"adjective","постіва":"noun","пуста":"adjective","суботня":"adjective","фадеева":"adjective","ходаніцка":"adjective","хохітва":"noun","цибата":"adjective","черноока":"adjective","чкадуа":"noun","чокена":"noun","шепетина":"noun","шербина":"noun","яка":"adjective","ятва":"noun","безена":"noun","безшкура":"adjective","безязика":"adjective","белая":"adjective","берулава":"noun","бузна":"noun","бурсала":"noun","бучаста":"adjective","вчина":"noun","гапона":"noun","гернажа":"noun","гордуна":"noun","горсва":"noun","горясва":"noun","грицька":"noun","двіжона":"noun","задурня":"adjective","заслона":"noun","зачешигрива":"noun","йона":"noun","качна":"adjective","козовіта":"noun","криворота":"adjective","кур'ята":"noun","лозна":"adjective","люлява":"noun","лютая":"adjective","матухна":"noun","накутня":"adjective","плохая":"adjective","бухая":"adjective","самотня":"adjective","панібудьласка":"noun"};class Fm{encode(e){const t=new Uint8Array(1);switch(e.wordClass){case r.NOUN:t[0]=1;break;case r.ADJECTIVE:t[0]=0;break;default:throw new TypeError(`Invalid word class: "${e.wordClass}".`)}return t}decode(e){if(e.length<1||e.length>1)throw new RangeError("Invalid vector length.");const t=e[0];if(t<0||t>1)throw new RangeError("Invalid vector value.");return{wordClass:t>=.5?r.NOUN:r.ADJECTIVE}}}class _m{constructor(e,t=0){this.vectorSize=e,this.unknownCharcode=t}encode(e){var t;const n=new Uint8Array(this.vectorSize),i=e.slice(-this.vectorSize).toLowerCase().padStart(this.vectorSize,"-");for(let e=0;e<i.length;e+=1){const a=i[e];n[e]=null!==(t=s[a])&&void 0!==t?t:this.unknownCharcode}return n}}Q().set("IS_NODE",!1);var Rm={class_name:"Sequential",config:{name:"sequential_1",layers:[{class_name:"Embedding",config:{input_dim:34,output_dim:16,embeddings_initializer:{class_name:"RandomUniform",config:{minval:-.05,maxval:.05,seed:null}},embeddings_regularizer:null,activity_regularizer:null,embeddings_constraint:null,mask_zero:null,input_length:null,name:"embedding_Embedding1",trainable:!0,batch_input_shape:[null,null]}},{class_name:"SimpleRNN",config:{name:"simple_rnn_SimpleRNN1",trainable:!0,units:16,activation:"relu",use_bias:!0,kernel_initializer:{class_name:"VarianceScaling",config:{scale:1,mode:"fan_avg",distribution:"normal",seed:null}},recurrent_initializer:{class_name:"Orthogonal",config:{gain:1,seed:null}},bias_initializer:{class_name:"Zeros",config:{}},kernel_regularizer:null,recurrent_regularizer:null,bias_regularizer:null,activity_regularizer:null,kernel_constraint:null,recurrent_constraint:null,bias_constraint:null,dropout:0,recurrent_dropout:0,return_sequences:!1,return_state:!1,go_backwards:!1,stateful:!1,unroll:!1}},{class_name:"Dense",config:{units:1,activation:"sigmoid",use_bias:!0,kernel_initializer:{class_name:"VarianceScaling",config:{scale:1,mode:"fan_avg",distribution:"normal",seed:null}},bias_initializer:{class_name:"Zeros",config:{}},kernel_regularizer:null,bias_regularizer:null,activity_regularizer:null,kernel_constraint:null,bias_constraint:null,name:"dense_Dense1",trainable:!0}}]},keras_version:"tfjs-layers 4.2.0",backend:"tensor_flow.js"},Lm=[{name:"embedding_Embedding1/embeddings",shape:[34,16],dtype:"float32"},{name:"simple_rnn_SimpleRNN1/kernel",shape:[16,16],dtype:"float32"},{name:"simple_rnn_SimpleRNN1/recurrent_kernel",shape:[16,16],dtype:"float32"},{name:"simple_rnn_SimpleRNN1/bias",shape:[16],dtype:"float32"},{name:"dense_Dense1/kernel",shape:[16,1],dtype:"float32"},{name:"dense_Dense1/bias",shape:[1],dtype:"float32"}],Mm="D3HrvZUs7rxT6Vu+tVsfvPLyB70zbt695ECPvKyKWj7TnUO+JZ9pvs8MkL3/1DQ+kftzvPGZZL4aDpe8KiOnvSvRHz52vQK9mGiSPm50B72RCfM+7hW6PSOuTz7b9zG+M5MOPv/mYL7Q9Rk+aPgRvrfQuT6mQ2Q+eOawPp/PpLyM9yY+zB4APT27n75OVUk+V8y6vetFyD0zPlW+sqPfPER8Ub6J1pI+5QwEvcZktT12HLW+FSFGPU6s2ryQapW9/MNNvoK1t71R5sK8N6Y/vjqBzTtusl2+0Ks8PpZOQ74ua5U9TOIfvkpgHDxho/294hcTPkJaiL1iXTo9o28bPhnMBr69EoG8CAeCvtgxXT5kMKq+KnLfPbScM73jYjw+LTa8vSeQWj49+cU7/FH2PKtOwr5y8K29GMMdvrkIgb0wK4C8Zeq2vXlG+L15O4c+CaFGvpmCjD5guBg+0AAQPv0EjT3CdZ0+vLOBulXEAb7VVpi+WldAPpIP8T0ETFm+NcLIPZix17rKGEW+n8jxPfT8hr43TLC8esPRvX6k4D1lZ0C+WERdPo4Qab4SdWw+uWSevp7+zTjX5Xi8nw+ZvldSb7xUfke7HX01PVOV2zzFqV2+SqcNvvPUTz0nzZi9Zl+ePWj6Wr3PLjY+vbjrvSRr6b1es/w8oaLjPUC0G72spye9rsomPtW/t72QYEy9AtR6PuX44z1dLrk9k6HAPE1+Eb7w1mY+N8MSvuMLsj1qmsO6JrRAvsJowr7iA1E+udZGPDLR57xRSj8+GFSnvYNUujxIvpM8FHmHvkr8QD38Po29LslnvShYOD45FAE7vfaWPbnegruqB2W9MdUkPpskUb3YGTU+L3gwvQhAYD4ed66+qJQUvjydBr7bSam8fYz/PCTisD7GYoQ+HDxJvSaIR77s3u+8sVTkvaDBaL13FBs+Z8T4vT4aKj2d4DC7ft+GPvVXFLxGXGI9RJ9avl7RCD6ujIy+M+/zPQbAtr3B2+c9BpZcPYIBTj7QNsM95bqEPc221T3u7TO+M2PIPU/BQb78/nk+f4TmvV5Elj0VOAK+0Y+DPq0GkL364pI98CGUvjK4IL1CLoK+kohXvTS3I76BpcM9WE0Rva5vkz301Ui+CLe7vWkLnT1sjpM8EYyWPWblIryk+gI+gnQSvu9XKL7jtni9Rc/IvaonHj2sKBc+VzRovpdOpT64szY+OavnvfzjeLuBH62+OqC2OoeMBr0eJVi7ST7CPLK/3jxTOoC9BRUSPjNBaD6OIlm+7ApUPlbsWj5KIKi+J9F1Pfi88L1+JdA9a6F+PsiRub06rh2+HlXnPb5Wj774l+i6nifjvWMCtL2WnqW9pUNdvjQM4L0ZJDy9lZ+LPbJWhj2hUZO+iWF0vhq17zqKwOI9Qq6sPWo8gD3c0co9/5WaPLN6PL6HOLO8fXvUvEF2IL4QJ7S98UzCPZJTlb6VUCM+y7dqvkJXyTyxD+I9N6PXvUxuqr0jiuM9p1OgO/wUFL07zEy+n5rPvSLifbt4N5e+kbdRviF6Db0ZSjo+B+dXvqB+iT7nFI68Z9bUPU9FGT21fz4+fee2vaIHqLzRTtG8aGggPqQlpD1GORk9/FpnPjatAL60OPg8x+qAPdU74zxSk6+9lYwdPikogr6pxao99PmXvH+yEz4zu5U9IeURPXqY9LpuvYk8OGmYvFX7+TtuUaO9qg0GPph0Xr5vdYM+0deHvozgtryfgDC8DaCGPTVxHb6q0fI97pWqPOXMAj7Y9ae+fljRuoumt71vblO+UaetPcadt7yiUYi9R9x8PqXbmb4V9gK+v2jjvVsTU72VAJ29JC1vPcpy1D2uNZM9N5mlvru77rxAZSo9jZWkvv+0HD6CY6k9RvnyvLM8Wr4/Yjo+aEr4vcUQkj3Ef7+7DusLvhf0oLxUt1u+LdOWPndY+Ty5+Dq+QfqQvqgCbj7V0L68swkNviGjaz0SkyQ+h9uuvckW97rM35m+O7ERPQvQ4L2XN3a9XwqPPifY7TynN0i9enwJPWh2Tj27c02+k0bpPWtEGz4p+qs9DzsKPhlEoD7U1qM9v7SAvNgeIr7tPJM9om6CvhmNcz7pBIa9HEvlPRmEGj7SzgE9tdoAO8dkeT2N2Xm9ChofvhVPSj19rZG+A2PfPVrax72zacc9YWsTvjSKAj4inbu9GbJGvSEnt76qFeq8JsAnvZ0cO75Lk7e5G8+WPrc5Cb3RGVg+xwxfvgTMNr18pdU9U49jPaRh5rg8G2Q+iUtrObd+jT0FTYG+XgVgvKwXJr6TWuG9BWosPlr9pT6IF2G+boCIvU0FOb39ivu9aMA5viC1S714C3q+CES6Pt11j76mNqk+/btevCcEVL7z5cK+ALgyPJeTPb0+7O+7lftrPslPZz1EqIY9DWKYvdtgWL5/DwI9Q2NFvJhKcb0MMQo+NtltPWZcmT2FlVA9V5Nnvc9IJr0TXCA+nAIuPoF7xbon0SQ+Kwi8ve0ePb6O3++9k2/GvZoLlrxRDM48DwOkvEiWIz7jsgC+NYZzvTu7Jb7Jcgm8qAoyPg8zkT3o8UI+7Mt/vZsaYj7UZDm+Z4BTPBgkQr7CSTs+PKpvPbkSED3tAaW9LJ9APo74Fz62CFe8xMDCPi83F76ttk++K6FGvQkDDr42fbG+N9cbPvP1Br2CU1c+qukfvu3DJz6Vjfy8jlM9PZNaKL4Ceu29dDVCvoG7fD5qTLu75+YoPXt8GD7ey2U+KpynvemmCL1L1VC9LsfhvcoBND44he273UFiPrLzK72XXPS9ZjZGPtBwh7gwW2i+ccbxvXtoMj4Q/u49AzHBvoTjHD40AuW+OiwYP4x9JD6PGAY/KN7+Pc0xhb6OqxY9AptQvbc7Or39a9e6DJ/zPvd+iz6XX7g6kqsEP5LI1L7ICBk+1k5SP0lR0T43qYI+kbFLvcUh5L7+v90+5mnZveLTxj03yAS+phJLvW7x3b4m3J68GeeBvlrhgj05ac++0Yyfvcrz7L1/Y/i+ZjMKPhEy6j3ImRu+fRRuPkunGL5dMVG+Yd5Fv6ys1z6PXYI+JhzOvaGxDT4p38I+QcDHPtkxbb0XnjM/ogGYviZrLj291se+iNNqvpZuUb7nas8+lj4tvvyQ3D7w+FO9r4ybPs7MJD+WsIG9pGxHPqmQo75RdUG/gFs2vRXbrj7n87w9aGosPm8vDr/oUeO+2pWxPsk1RT7lvPS+YBmZvkDPU745ORi/BxbNPg83pD2KOSq9Nh0tPw6bSj+WVTk97hLcPnMDpT7GgXW8dL46vltPvb11QOu9CeYDPYDxwbx5UQ8+MnesPb+Ajj7Uv7m+qE+TvM+Qt77g88s+7940P8/1zj5p9+g+FugoPgNebT69zXg+IbhFvnHq6LsVozg+iIaBPau6Kr6tTOG+U1bhPS6zFD64rqY/FZebvhOPeL5DGXo+dwgLPjKu6z5+X78+iAsNPrs/Pb+RQoe+6MyqvWutu75ml7G+3Casvq63/b4exKi9+5lMv7V/yb4twI49cbIcv/+5/r5lWxE/78Q+PhjngT4SENI9xZKXPmmQEb9UJGK+eYE3vtOLiDxf4zo+9KX5Pl0APj9PhqA+i/wMv1iRsjzngaK+/ocBv8RUnr0hPdM+YAshv896DL1aukY+kiIJvsKhvD66FTi++84Fv5vWjL4lr6W+OLvyvba/krzwXgm9X8rUvv+XNb7jhSo/zfCAPLRlqD4Fn5S+DeQfP0847T7NIZ4+/gMAPxyfcT6VQOM+UOmWvWDtrD4TLFW9NGQSveJN9T7AuFm+MvUSv/TnFz8uw68+k05IPj26MTwDLsW+hsLFvifDqD7Z6d28z+AOv1DeZL8TnA++mrwBvT0BGL5ireW+PLbOOQjsJjzUmya/CcavOz8kwr70lmK+PHcmPsmi9r5VeAI+yly7PSGkIT6xV1Q/uHsKP4WFir4DBcc+SIJuPlP0Lb5Nufu+dKc3vk/X4L2Qvyo/jJSCPr3+Vr7NNA4/5AqcPoYisjuvO6g9JGKRPgxvQj/bUnG8yqAbP8wDO75rdkO+keIuPvrKxT4VCoQ9fx3XPih9K77kIOg99g2gPcrn4rxDzyy+TDdxPpzmHz//YWM+PIXFvTGs4z5SaaE9NAwkv4Qcub6gS3g+6Wa0vf3qJD8NDC2/q4z6PFVEob5p8yG+uSjhvjAMgD4GQ2Q/+EfRPlrsL79K2PO+FyOrPav1lT6vSzQ+nQOovRiVMD4Yfg4+weDxPv9V8b3ix407T0mFvEXdYT4DaKq+rE4YviLa2r4q/vI7hVWOvWgaV77A7QU/OU2iPp8QQT58RIA+Lbf+vo65Fz1RDRw+mv6WvdOImj4/IyY9a+vPO/pDuj6WiFe94SnbvW0cAb5HUcQ8croTvdeGIT6Q5p89/2EpPyPapj33gSS+q161vhFrSj00b5A9P6g4vssdob5sS5G+r72gvUDqCj+C5+a9lJHFPjtFxz10OYs+qXakvlUu5Trwp749nrcQPbAzwr5pCs8+UhoIvsHVdT7iw+i+UYxzPgTn5T50arg+R/4IP7kH2T2cguW+pQX+vFqQdr3z5yY+SdURProPID4CXhA9crIcP/7a4D6r/549Ly6lvXeFUb9n9xs/CC3oPrOgAj8iPwo/8nPXviKqAr8q6TQ+vrumPrdtHz8prJq+V1/oPUZWGr4Y4cU9nRopvtRCkz2jeTy+pJW0PgwDyz6XfIo+QmZevqCRSj1/pIa+KoufPllZvT5o244+nRIYP3TbM70N+8y+a7d2vcsSWj4Cdrw+AT8hPVoDwL0BxL2+G1pmPo/CZL66zSS+g2rFPvewar7nfGe+YEuevRgFIr7dyRS+KES0Pnu1p754F6s+/inJPXa3tL4Qd5A+OmbLPWvlnb75WsU9rRHMvsgqxD5MQ90+Y38LPnBkZj7fKIs9uJCHvdiuXr6D/Rw9hpVyPu9Vqr4Qzom85dP6vYymmr1yG5w+2gSMPlV5tT1D1ks+EKTZPm4gOb6ZC+w+k8EOPA8oXb6r9z2+h6Tgvm7Dvj7OzJQ+7tkIPvbDjz4TN6u9GneSPTIooD7GdRA/wYQ4vVr7b71F/QI+cRORPrRPWzxVX22+Yu2vPsHriL720za+oBlVPogMe72YNKM8r9aEO5uq1z7RegW+4aX1PqfYRD/wpfI9sVqvPCI99jpAtWC9eXJ2PBb++j6w+809iODsPfwV0b2kL7S9D+FLPQZECD4oYRA+V1Z+vjarEj5ZF/q8KJSAPkjENr7zNd28pKODPj8FPL8mgFY8kJVMvgBfQ75uooK++9TaPg/5Cr5Pzo6+1Yy3viONQL/Fvng+Bmn6vTpQkb0N7Oi94ZVHPYE2Hr7J/Rk+zQzKvL3Chj5d85o+Q/YRPrsjnj7YzJY+01w3PyVgGD6INkM+XtnevbmxiL7Z1NI+jpdgvggkdz0QnJq+35a8PZX0SL4+y78+grnOPYHzlD2VKRA/xRW4PqyCPL4Cowa/Ku+pvZabKz99894+sY/Vva/ezL1zsUw+er4IP8DL/D1qa2a+m6B3PK8Cq76mu2++gsjvvP0kBz8pWqe+SyotvKUdmz4pFXA7bkXCvbwSbj44g7c8mID4viXITL56E/G9zBVuPPD+u7wCmJc9v1nDuyyEX77G7Nq8GUwXvQJRVT3nTYY9/wK9Pct9sT1dCqU9aRsHvlmTFD2/B5M9PclmvNt2Jb8eqR2+bZhIvlmRVT4k0zU/OFSyvnCsHb/BfrK+ZZJGv10pNT8uXQk/AaVXvgbtG76M5kC+b6zpPfBICD8I1Lm8",Om={format:"layers-model",generatedBy:"TensorFlow.js tfjs-layers v4.2.0",convertedBy:null};const Pm="undefined"!=typeof Buffer&&("undefined"==typeof Blob||"undefined"==typeof atob||"undefined"==typeof btoa);class Bm{inflect(e,t,n){return a(this,void 0,void 0,(function*(){const i=[],a=e.split("-");for(let e=0;e<a.length;e+=1){const s=yield this.inflectNamePart(a[e],t,n,e===a.length-1);i.push(s)}return i.join("-")}))}}const Um=/[ая]$/i,Wm=/(ой|ий|ій|их)$/i;const Vm=new class extends Bm{constructor(e){super(),this.wordInflector=e}inflectNamePart(e,t,n){return this.wordInflector.inflect(e,{grammaticalCase:n,gender:t,applicationType:"givenName"})}}(b),Gm=new class extends Bm{constructor(e){super(),this.wordInflector=e}inflectNamePart(e,t,n){return this.wordInflector.inflect(e,{grammaticalCase:n,gender:t,applicationType:"patronymicName",customRuleFilter:e=>e.applicationType.includes("patronymicName")})}}(b),Km=new class{constructor(e){this.modelLoader=e,this.modelPromise=null,this.wordTransformer=new _m(20),this.familyNameClassTransformer=new Fm}classify(e){return a(this,void 0,void 0,(function*(){let t=this.getCached(e);if(null!=t)return t;const n=yield this.loadModel(),i=this.wordTransformer.encode(e),a=yield n.predict(Ks([i])).data();return t=this.familyNameClassTransformer.decode(a),t}))}getCached(e){let t=null;const n=Dm[e.toLowerCase()];return n&&(t={wordClass:n}),t}loadModel(){return a(this,void 0,void 0,(function*(){return null==this.modelPromise&&(this.modelPromise=kp(this.modelLoader)),this.modelPromise}))}}(new class{load(){return a(this,void 0,void 0,(function*(){const e={};if(e.modelTopology=Rm,e.weightSpecs=Lm,e.weightData=function(e){if(Pm){const t=Buffer.from(e,"base64");return t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}const t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;++e)n.set([t.charCodeAt(e)],e);return n.buffer}(Mm),null!=Om){const t=Om;e.format=t.format,e.generatedBy=t.generatedBy,e.convertedBy=t.convertedBy,null!=t.signature&&(e.signature=t.signature),null!=t.userDefinedMetadata&&(e.userDefinedMetadata=t.userDefinedMetadata),null!=t.modelInitializer&&(e.modelInitializer=t.modelInitializer),null!=t.initializerSignature&&(e.initializerSignature=t.initializerSignature),null!=t.trainingConfig&&(e.trainingConfig=t.trainingConfig)}return e}))}}),qm=new class extends Bm{constructor(e,t){super(),this.wordInflector=e,this.familyNameClassifier=t}inflectNamePart(e,t,n,i){return a(this,void 0,void 0,(function*(){if(!i&&l(e))return e;let a=null;return this.isUncertainFamilyNameClass(e,t)&&(a=yield this.familyNameClassifier.classify(e)),this.wordInflector.inflect(e,{grammaticalCase:n,gender:t,wordClass:null==a?void 0:a.wordClass,applicationType:"familyName"})}))}isUncertainFamilyNameClass(t,n){return n===e.GrammaticalGender.FEMININE&&Um.test(t)||n===e.GrammaticalGender.MASCULINE&&Wm.test(t)}}(b,Km),Hm=new class{constructor(e,t,n){this.givenNameInflector=e,this.patronymicNameInflector=t,this.familyNameInflector=n}inflect(e,t,n){return a(this,void 0,void 0,(function*(){const i={};return null!=e.givenName&&(i.givenName=yield this.givenNameInflector.inflect(e.givenName,t,n)),null!=e.patronymicName&&(i.patronymicName=yield this.patronymicNameInflector.inflect(e.patronymicName,t,n)),null!=e.familyName&&(i.familyName=yield this.familyNameInflector.inflect(e.familyName,t,n)),i}))}}
4671
4671
  /**
4672
4672
  * @license
4673
4673
  * Copyright 2020 Google LLC. All Rights Reserved.
@@ -4683,5 +4683,5 @@ xt(Io),xt(lo),xt(Eo),xt(Ao),xt(Co),xt($o),xt(wo),xt(jo),xt(Mo),xt(vo),xt(_o),xt(
4683
4683
  * See the License for the specific language governing permissions and
4684
4684
  * limitations under the License.
4685
4685
  * =============================================================================
4686
- */(Gm,Vm,qm);var Jm={"августа":"feminine","аврелія":"feminine","аврора":"feminine","агапія":"feminine","агата":"feminine","агафія":"feminine","агафоника":"feminine","аглаїда":"feminine","аглая":"feminine","агнеса":"feminine","агнія":"feminine","агрипина":"feminine","ада":"feminine","аделаїда":"feminine","аделіна":"feminine","адріана":"feminine","аеліта":"feminine","аза":"feminine","азалія":"feminine","аїда":"feminine","акилина":"feminine","алевтина":"feminine","аліна":"feminine","аліса":"feminine","алла":"feminine","альбертина":"feminine","альбіна":"feminine","альвіна":"feminine","альфреда":"feminine","анастасія":"feminine","анатолія":"feminine","ангеліна":"feminine","анжела":"feminine","анжеліка":"feminine","анна":"feminine","антонида":"feminine","антоніна":"feminine","антонія":"feminine","анфіса":"feminine","аполлінарія":"feminine","аполлонія":"feminine","аріадна":"feminine","аркадія":"feminine","арсена":"feminine","арсенія":"feminine","артемізія":"feminine","артеміза":"feminine","артемісія":"feminine","артеміса":"feminine","артемія":"feminine","аскліпія":"feminine","ася":"feminine","аурика":"feminine","афанасія":"feminine","афіна":"feminine","атена":"feminine","афродіта":"feminine","бажана":"feminine","барбара":"feminine","беатриса":"feminine","белла":"feminine","берта":"feminine","богдана":"feminine","богуслава":"feminine","божена":"feminine","болеслава":"feminine","борислава":"feminine","броніслава":"feminine","валентина":"feminine","валерія":"feminine","ванда":"feminine","варвара":"feminine","василина":"feminine","васса":"feminine","векла":"feminine","венера":"feminine","вероніка":"feminine","вівдя":"feminine","вікторина":"feminine","вікторія":"feminine","вілена":"feminine","віленіна":"feminine","віліна":"feminine","віола":"feminine","віолетта":"feminine","віра":"feminine","віргінія":"feminine","віринея":"feminine","вірослава":"feminine","віта":"feminine","віталіна":"feminine","віталія":"feminine","влада":"feminine","владилена":"feminine","владислава":"feminine","владлена":"feminine","власта":"feminine","володимира":"feminine","воля":"masculine","всеслава":"feminine","в'ячеслава":"feminine","гаїна":"feminine","галина":"feminine","ганна":"feminine","гафія":"feminine","гелена":"feminine","георгіна":"feminine","гертруда":"feminine","глафіра":"feminine","глафира":"feminine","гликерія":"feminine","ликерія":"feminine","ликера":"feminine","горпина":"feminine","густава":"feminine","дана":"feminine","дарина":"feminine","одарина":"feminine","одарка":"feminine","дарія":"feminine","дзвенимира":"feminine","дзвенислава":"feminine","дзвінка":"feminine","діана":"feminine","діна":"feminine","домна":"feminine","домаха":"feminine","донна":"feminine","доротея":"feminine","дорофея":"feminine","евеліна":"feminine","едіта":"feminine","елеонора":"feminine","елла":"feminine","елвіна":"feminine","ельвіра":"feminine","емма":"feminine","еммануель":"feminine","еммануїла":"feminine","емілія":"feminine","еріка":"feminine","есмеральда":"feminine","естер":"feminine","есфір":"feminine","єва":"feminine","євгенія":"feminine","ївга":"feminine","югина":"feminine","євдокія":"feminine","докія":"feminine","явдоха":"feminine","євфросинія":"feminine","єфросинія":"feminine","єкатерина":"feminine","єлизавета":"feminine","лизавета":"feminine","лисавета":"feminine","гальшка":"feminine","єпистимія":"feminine","єпистима":"feminine","жадана":"feminine","жанна":"feminine","ждана":"feminine","жозефіна":"feminine","забава":"feminine","звенигора":"feminine","звенислава":"feminine","звонимира":"feminine","земфіра":"feminine","зірка":"feminine","зінаїда":"feminine","злата":"feminine","златомира":"feminine","златоуста":"feminine","золотодана":"feminine","зорегляда":"feminine","зореслава":"feminine","зорина":"feminine","зоряна":"feminine","зоря":"feminine","зоя":"feminine","іванна":"feminine","ігорина":"feminine","ілона":"feminine","інга":"feminine","інна":"feminine","інеса":"feminine","ірина":"feminine","ірма":"feminine","іларія":"feminine","ісидора":"feminine","ія":"feminine","йовілла":"feminine","йосипа":"feminine","осипа":"feminine","йосифата":"feminine","казимира":"feminine","казка":"feminine","калина":"feminine","капітоліна":"feminine","капитолина":"feminine","капитоліна":"feminine","карина":"feminine","кароліна":"feminine","кассандра":"feminine","катерина":"feminine","катря":"feminine","квітка":"feminine","квітослава":"feminine","кикилія":"feminine","цецилія":"feminine","килина":"feminine","кіра":"feminine","клавдія":"feminine","клара":"feminine","клеопатра":"feminine","колодара":"feminine","констанція":"feminine","корина":"feminine","кора":"feminine","корнелія":"feminine","красимира":"feminine","красновида":"feminine","краснолика":"feminine","красуня":"feminine","ксенія":"feminine","аксенія":"feminine","оксенія":"feminine","оксана":"feminine","купава":"feminine","лада":"feminine","ладислава":"feminine","ладомила":"feminine","ладомира":"feminine","лариса":"feminine","левина":"feminine","леля":"feminine","леся":"feminine","либідь":"feminine","лідія":"feminine","лілія":"feminine","лілея":"feminine","ліна":"feminine","лола":"feminine","лоліта":"feminine","лукія":"feminine","лукина":"feminine","лукреція":"feminine","любава":"feminine","любаня":"feminine","любислава":"feminine","любов":"feminine","любомила":"feminine","любомира":"feminine","люборада":"feminine","людмила":"feminine","людомила":"feminine","любослава":"feminine","льоля":"feminine","літвіна":"feminine","мавка":"feminine","магадара":"feminine","магдалина":"feminine","магдалена":"feminine","магда":"feminine","маїна":"feminine","майя":"feminine","маківка":"feminine","малуня":"feminine","малуша":"feminine","мальва":"feminine","мальвіна":"feminine","маргарита":"feminine","марта":"feminine","марфа":"feminine","марута":"feminine","марія":"feminine","мар'я":"feminine","марічка":"feminine","марина":"feminine","мартина":"feminine","мар'яна":"feminine","маріанна":"feminine","маріамна":"feminine","медорада":"feminine","меланія":"feminine","мелітина":"feminine","мечислава":"feminine","милана":"feminine","милована":"feminine","миловида":"feminine","милодара":"feminine","милослава":"feminine","мирана":"feminine","миробога":"feminine","миролюба":"feminine","мирослава":"feminine","михайлина":"feminine","млада":"feminine","мокрина":"feminine","макрина":"feminine","моніка":"feminine","мотря":"feminine","мстислава":"feminine","мудролюба":"feminine","надія":"feminine","надіслава":"feminine","найда":"feminine","найдена":"feminine","наслава":"feminine","настасія":"feminine","настя":"feminine","наталія":"feminine","наталя":"feminine","наталка":"feminine","неля":"feminine","немира":"feminine","нігослава":"feminine","незабудка":"feminine","ніка":"feminine","ніна":"feminine","нінель":"feminine","нонна":"feminine","огняна":"feminine","октавія":"feminine","олександра":"feminine","олена":"feminine","олеся":"feminine","олівія":"feminine","олімпіада":"feminine","олімпія":"feminine","ольга":"feminine","ореста":"feminine","оримира":"feminine","орина":"feminine","орислава":"feminine","орися":"feminine","оріяна":"feminine","оріянка":"feminine","орогоста":"feminine","острозора":"feminine","остромира":"feminine","осмомисла":"feminine","остромова":"feminine","пава":"feminine","павла":"feminine","павлина":"feminine","пелагія":"feminine","пелагея":"feminine","палагна":"feminine","палазга":"feminine","параскева":"feminine","параскевія":"feminine","парасковія":"feminine","перелюба":"feminine","перемила":"feminine","перемисла":"feminine","пистина":"feminine","півонія":"feminine","поліна":"feminine","позвізда":"feminine","полеза":"feminine","поляна":"feminine","потішана":"feminine","предслава":"feminine","пріська":"feminine","пульхерія":"feminine","пульхера":"feminine","рада":"feminine","радана":"feminine","радимира":"feminine","радмила":"feminine","радогоста":"feminine","радомира":"feminine","радослава":"feminine","раїна":"feminine","раїса":"feminine","ревека":"feminine","ребекка":"feminine","регіна":"feminine","рената":"feminine","римма":"feminine","рина":"feminine","ріана":"feminine","ріанна":"feminine","рідна":"feminine","рогволода":"feminine","рогніда":"feminine","родослава":"feminine","рожана":"feminine","роза":"feminine","розалія":"feminine","рузалія":"feminine","роксана":"feminine","роксолана":"feminine","ромашка":"feminine","романа":"feminine","ромена":"feminine","росава":"feminine","росина":"feminine","ростислава":"feminine","ростичара":"feminine","ростуня":"feminine","рудана":"feminine","роналіна":"feminine","рошель":"feminine","русана":"feminine","руслана":"feminine","русудана":"feminine","русява":"feminine","русявка":"feminine","рут":"feminine","руф":"feminine","руфіна":"feminine","руфина":"feminine","сабріна":"feminine","санта":"feminine","сара":"feminine","сарра":"feminine","світлана":"feminine","світовида":"feminine","світогора":"feminine","світодара":"feminine","світозара":"feminine","світолика":"feminine","світолюба":"feminine","світослава":"feminine","світояра":"feminine","свободана":"feminine","святогора":"feminine","святолюба":"feminine","святослава":"feminine","севастіана":"feminine","северина":"feminine","секлета":"feminine","секлетина":"feminine","серафима":"feminine","силата":"feminine","силолюба":"feminine","силослава":"feminine","синезора":"feminine","синьоока":"feminine","сільвія":"feminine","сімона":"feminine","слава":"masculine","славина":"feminine","славолюба":"feminine","славомила":"feminine","сміяна":"feminine","сніжана":"feminine","сніжинка":"feminine","собіслава":"feminine","соломія":"feminine","соломонія":"feminine","сологуба":"feminine","сонцевида":"feminine","сонцедара":"feminine","сонцелика":"feminine","сонцеслава":"feminine","соня":"feminine","софія":"feminine","станимира":"feminine","станіслава":"feminine","стелла":"feminine","стефанида":"feminine","стефанія":"feminine","сусанна":"feminine","сосанна":"feminine","судимира":"feminine","судислава":"feminine","сюзанна":"feminine","тава":"feminine","таїсія":"feminine","таїса":"feminine","тамара":"feminine","татолюба":"feminine","твердислава":"feminine","твердогоста":"feminine","творимира":"feminine","творислава":"feminine","текля":"feminine","тереза":"feminine","тетяна":"feminine","тіна":"feminine","толигніва":"feminine","тонкостана":"feminine","трояна":"feminine","улита":"feminine","уляна":"feminine","устина":"feminine","фаїна":"feminine","февронія":"feminine","февросія":"feminine","хівря":"feminine","фекла":"feminine","феліція":"feminine","фелікса":"feminine","филікитата":"feminine","филіцитата":"feminine","филіцата":"feminine","феодора":"feminine","федора":"feminine","тодора":"feminine","федосія":"feminine","феодосія":"feminine","теодозія":"feminine","фотина":"feminine","фотинія":"feminine","фота":"feminine","хотина":"feminine","фросина":"feminine","харита":"feminine","харитина":"feminine","харитя":"feminine","хриса":"feminine","христина":"feminine","христя":"feminine","цецілія":"feminine","цвітана":"feminine","чеслава":"feminine","чухрія":"feminine","юдит":"feminine","юдиф":"feminine","юдихва":"feminine","юзефа":"feminine","юлія":"feminine","юлина":"feminine","юліанія":"feminine","юліанна":"feminine","юліана":"feminine","юнія":"feminine","юстина":"feminine","юхимія":"feminine","юхима":"feminine","юхимина":"feminine","євфимiя":"feminine","єфимія":"feminine","хима":"feminine","ядвіга":"feminine","яна":"feminine","яніна":"feminine","ярина":"feminine","яромира":"feminine","ярослава":"feminine","августин":"masculine","авксентій":"masculine","аврелій":"masculine","автоном":"masculine","адам":"masculine","адріян":"masculine","адріан":"masculine","азар":"masculine","азарій":"masculine","алевтин":"masculine","альберт":"masculine","амвросій":"masculine","анастас":"masculine","анастасій":"masculine","анатолій":"masculine","андрон":"masculine","андрій":"masculine","ондрій":"masculine","антон":"masculine","антоній":"masculine","онтін":"masculine","анісій":"masculine","онісій":"masculine","аркадій":"masculine","арсен":"masculine","арсеній":"masculine","артем":"masculine","артур":"masculine","орхип":"masculine","атанас":"masculine","опанас":"masculine","афанасій":"masculine","аскольд":"masculine","оскольд":"masculine","атрей":"masculine","бажан":"masculine","батко":"masculine","біловид":"masculine","білогост":"masculine","біломир":"masculine","білослав":"masculine","білотур":"masculine","білян":"masculine","благовид":"masculine","благовіст":"masculine","благодар":"masculine","богдан":"masculine","богуслав":"masculine","божан":"masculine","божедар":"masculine","божейко":"masculine","божемир":"masculine","божен":"masculine","божко":"masculine","бойко":"masculine","болеслав":"masculine","боримир":"masculine","боримисл":"masculine","борис":"masculine","борислав":"masculine","боян":"masculine","бративой":"masculine","братимир":"masculine","братислав":"masculine","братко":"masculine","братомил":"masculine","братослав":"masculine","брячислав":"masculine","боронислав":"masculine","будивид":"masculine","будивой":"masculine","будимил":"masculine","будимир":"masculine","будислав":"masculine","буймир":"masculine","буйтур":"masculine","буревій":"masculine","буревіст":"masculine","валентин":"masculine","валерій":"masculine","варфоломій":"masculine","василь":"masculine","вадим":"masculine","ведан":"masculine","велемир":"masculine","велемудр":"masculine","велет":"masculine","величар":"masculine","величко":"masculine","вербан":"masculine","веремій":"masculine","вернидуб":"masculine","вернислав":"masculine","веселан":"masculine","витомир":"masculine","вишата":"masculine","вишезор":"masculine","вишеслав":"masculine","віктор":"masculine","вір":"masculine","віродан":"masculine","віродар":"masculine","вірослав":"masculine","віст":"masculine","вістан":"masculine","віталій":"masculine","вітан":"masculine","вітомир":"masculine","вітрян":"masculine","влад":"masculine","владислав":"masculine","власт":"masculine","вогнедар":"masculine","вогнян":"masculine","водограй":"masculine","водотрав":"masculine","воїслав":"masculine","волелюб":"masculine","володар":"masculine","володимир":"masculine","володислав":"masculine","воротислав":"masculine","вратислав":"masculine","вратан":"masculine","всевлад":"masculine","всеволод":"masculine","вселюб":"masculine","вселюд":"masculine","всеслав":"masculine","вукол":"masculine","вакула":"masculine","в'ячеслав":"masculine","гаврило":"masculine","гарнослав":"masculine","гатусил":"masculine","гатуслав":"masculine","геннадій":"masculine","георгій":"masculine","герасим":"masculine","гервасій":"masculine","гладко":"masculine","гліб":"masculine","гнат":"masculine","годомир":"masculine","голубко":"masculine","горун":"masculine","гордій":"masculine","гордислав":"masculine","гордогост":"masculine","гордодум":"masculine","гордомисл":"masculine","гордослав":"masculine","гордята":"masculine","горигляд":"masculine","горимир":"masculine","горимисл":"masculine","горисвіт":"masculine","горислав":"masculine","горицвіт":"masculine","гостомисл":"masculine","гострозір":"masculine","гостята":"masculine","градимир":"masculine","градислав":"masculine","гранислав":"masculine","грива":"masculine","григорій":"masculine","гремислав":"masculine","грозан":"masculine","громовик":"masculine","гуляйвітер":"masculine","густомисл":"masculine","давид":"masculine","далемил":"masculine","далемир":"masculine","далібор":"masculine","дан":"masculine","данило":"masculine","данко":"masculine","дантур":"masculine","дар":"masculine","дарій":"masculine","дарибог":"masculine","даромир":"masculine","денис":"masculine","демид":"masculine","дем'ян":"masculine","держикрай":"masculine","держислав":"masculine","дибач":"masculine","дивозір":"masculine","дій":"masculine","дмитро":"masculine","добрибій":"masculine","добривод":"masculine","добрик":"masculine","добрило":"masculine","добриня":"masculine","добрисвіт":"masculine","добровіст":"masculine","доброгост":"masculine","добродум":"masculine","добролик":"masculine","добролюб":"masculine","добромир":"masculine","добромисл":"masculine","доброслав":"masculine","доморад":"masculine","домослав":"masculine","дорогобуг":"masculine","дорогомир":"masculine","дорогомисл":"masculine","дорогосил":"masculine","дорогочин":"masculine","дорофій":"masculine","домінік":"masculine","драган":"masculine","драгомир":"masculine","євген":"masculine","євгеній":"masculine","євлампій":"masculine","єремій":"masculine","євстафій":"masculine","єгор":"masculine","жадан":"masculine","ждан":"masculine","живорід":"masculine","живосил":"masculine","живослав":"masculine","житомир":"masculine","життєлюб":"masculine","жито":"masculine","захар":"masculine","захарій":"masculine","збоїслав":"masculine","зборислав":"masculine","звенигор":"masculine","звенимир":"masculine","звенислав":"masculine","здоровега":"masculine","земислав":"masculine","зіновій":"masculine","зиновій":"masculine","злат":"masculine","златомир":"masculine","златоус":"masculine","златодан":"masculine","злотан":"masculine","злотодан":"masculine","зорегляд":"masculine","зоремир":"masculine","зорепад":"masculine","зореслав":"masculine","зорян":"masculine","іван":"masculine","івантослав":"masculine","ігор":"masculine","ізяслав":"masculine","іларіон":"masculine","ілля":"masculine","іоанн":"masculine","каленик":"masculine","квітан":"masculine","києслав":"masculine","кий":"masculine","кирило":"masculine","киян":"masculine","кіндрат":"masculine","княжослав":"masculine","конон":"masculine","корній":"masculine","корнило":"masculine","корнилій":"masculine","корнелій":"masculine","колодар":"masculine","колодій":"masculine","красун":"masculine","крилач":"masculine","куйбіда":"masculine","курило":"masculine","костянтин":"masculine","кузьма":"masculine","лаврін":"masculine","лаврентій":"masculine","лад":"masculine","ладо":"masculine","ладимир":"masculine","ладислав":"masculine","ладолюб":"masculine","ладомир":"masculine","лев":"masculine","левко":"masculine","леонід":"masculine","листвич":"masculine","ліпослав":"masculine","лоліт":"masculine","лук'ян":"masculine","любим":"masculine","любовир":"masculine","любодар":"masculine","любозар":"masculine","любомил":"masculine","любомир":"masculine","любомисл":"masculine","любомудр":"masculine","любослав":"masculine","людомил":"masculine","людислав":"masculine","лютобор":"masculine","лютомисл":"masculine","лука":"masculine","маврикій":"masculine","магадар":"masculine","магамир":"masculine","магаслав":"masculine","маркіян":"masculine","май":"masculine","макар":"masculine","максим":"masculine","малик":"masculine","маломир":"masculine","марко":"masculine","мартин":"masculine","мар'ян":"masculine","матвій":"masculine","медомир":"masculine","межамир":"masculine","мечислав":"masculine","мизамир":"masculine","микита":"masculine","микола":"masculine","милан":"masculine","милован":"masculine","милодар":"masculine","милодух":"masculine","милослав":"masculine","мир":"masculine","миробог":"masculine","мирогост":"masculine","миролюб":"masculine","мирон":"masculine","мирослав":"masculine","михайло":"masculine","мовчан":"masculine","молибог":"masculine","мстибог":"masculine","мстивой":"masculine","мстислав":"masculine","мудролюб":"masculine","мусій":"masculine","муховіст":"masculine","нагнибіда":"masculine","надій":"masculine","найден":"masculine","наслав":"masculine","недан":"masculine","немир":"masculine","нестор":"masculine","непобор":"masculine","нігослав":"masculine","назарій":"masculine","никифор":"masculine","ничипір":"masculine","никодим":"masculine","остромисл":"masculine","одинець":"masculine","олег":"masculine","олександр":"masculine","олексій":"masculine","олесь":"masculine","олелько":"masculine","омелян":"masculine","онуфрій":"masculine","орест":"masculine","осемрит":"masculine","оремів":"masculine","оримир":"masculine","осмомисл":"masculine","остап":"masculine","острозор":"masculine","остромир":"masculine","остромов":"masculine","охрім":"masculine","олекса":"masculine","павло":"masculine","пантелеймон":"masculine","панас":"masculine","первушко":"masculine","перелюб":"masculine","перемил":"masculine","перемисл":"masculine","пересвіт":"masculine","переяслав":"masculine","першик":"masculine","петро":"masculine","пилип":"masculine","пимен":"masculine","пимін":"masculine","пимон":"masculine","подолян":"masculine","позвізд":"masculine","полель":"masculine","полян":"masculine","порфир":"masculine","потап":"masculine","пребислав":"masculine","предислав":"masculine","пор":"masculine","палац":"masculine","п'єр":"masculine","рава":"masculine","рад":"masculine","радан":"masculine","радечко":"masculine","радивой":"masculine","радило":"masculine","радим":"masculine","радимир":"masculine","радослав":"masculine","радко":"masculine","радован":"masculine","радогост":"masculine","радомир":"masculine","радомисл":"masculine","ратибор":"masculine","ратимир":"masculine","ратислав":"masculine","рафаїл":"masculine","ревун":"masculine","рід":"masculine","рогволод":"masculine","родан":"masculine","родіон":"masculine","родослав":"masculine","рожден":"masculine","роксолан":"masculine","роман":"masculine","ростислав":"masculine","ростичар":"masculine","ростун":"masculine","рудан":"masculine","рус":"masculine","русан":"masculine","руслан":"masculine","русудан":"masculine","сармат":"masculine","сварг":"masculine","свирид":"masculine","світ":"masculine","світан":"masculine","світлан":"masculine","світлогор":"masculine","світогор":"masculine","світовид":"masculine","світодар":"masculine","світозар":"masculine","світокол":"masculine","світолик":"masculine","світолюб":"masculine","світомир":"masculine","світослав":"masculine","світояр":"masculine","свободан":"masculine","святовид":"masculine","святогор":"masculine","святолюб":"masculine","святополк":"masculine","святослав":"masculine","святояр":"masculine","северин":"masculine","семен":"masculine","семибор":"masculine","семирад":"masculine","серафим":"masculine","сергій":"masculine","сердитко":"masculine","сила":"masculine","силан":"masculine","силолюб":"masculine","силослав":"masculine","синьоок":"masculine","скол":"masculine","славобор":"masculine","славолюб":"masculine","славомир":"masculine","славута":"masculine","снага":"masculine","сніжан":"masculine","сновид":"masculine","снозір":"masculine","собібор":"masculine","собімир":"masculine","собіслав":"masculine","сокіл":"masculine","соловей":"masculine","сологуб":"masculine","солопій":"masculine","сонцевид":"masculine","сонцедар":"masculine","сонцелик":"masculine","спас":"masculine","станимир":"masculine","станислав":"masculine","стародум":"masculine","степан":"masculine","стефаній":"masculine","стожар":"masculine","стоймир":"masculine","стоян":"masculine","судивой":"masculine","судимир":"masculine","судислав":"masculine","сурма":"masculine","тарас":"masculine","татомир":"masculine","тарослав":"masculine","таросик":"masculine","твердигост":"masculine","твердислав":"masculine","творилад":"masculine","творимир":"masculine","творислав":"masculine","теодозій":"masculine","терентій":"masculine","тімох":"masculine","тимофій":"masculine","тиміш":"masculine","тимур":"masculine","тихомир":"masculine","тихон":"masculine","тодось":"masculine","толигнів":"masculine","толислав":"masculine","тригост":"masculine","троян":"masculine","триріг":"masculine","тур":"masculine","турбог":"masculine","турбрід":"masculine","улас":"masculine","уличан":"masculine","ус":"masculine","устим":"masculine","флор":"masculine","фрол":"masculine","федір":"masculine","фауст":"masculine","хвала":"masculine","хвалибог":"masculine","хвалимир":"masculine","ходота":"masculine","хорив":"masculine","хорошко":"masculine","хотибор":"masculine","хотимир":"masculine","хотян":"masculine","хранимир":"masculine","христофор":"masculine","худан":"masculine","царко":"masculine","цвітан":"masculine","царук":"masculine","чара":"masculine","чернин":"masculine","чеслав":"masculine","чесмил":"masculine","честислав":"masculine","щастибог":"masculine","щастислав":"masculine","щедрогост":"masculine","щек":"masculine","юліан":"masculine","юлій":"masculine","юрій":"masculine","юхим":"masculine","явір":"masculine","яволод":"masculine","яків":"masculine","ян":"masculine","яр":"masculine","ярема":"masculine","ярило":"masculine","яровид":"masculine","яровит":"masculine","яромил":"masculine","яромир":"masculine","яромисл":"masculine","ярополк":"masculine","яросвіт":"masculine","ярослав":"masculine","ярош":"masculine","яртур":"masculine","ярчик":"masculine","ясен":"masculine","ясновид":"masculine","ясногор":"masculine","яснозір":"masculine","яснолик":"masculine"};const Zm=/[иі]ч$/,Ym=/на$/,Qm=/[`"]/g;function Xm(t){ef(t),function(t){if(![e.GrammaticalGender.MASCULINE,e.GrammaticalGender.FEMININE].includes(t))throw new TypeError(`The "gender" parameter must be one of the following: "${e.GrammaticalGender.MASCULINE}", "${e.GrammaticalGender.FEMININE}".`)}(t.gender),tf(t)}function ef(e){if("object"!=typeof e||null==e)throw new TypeError("The input type must be an object.")}function tf(e){if(void 0===e.givenName&&void 0===e.patronymicName&&void 0===e.familyName)throw new TypeError('At least one of the following parameters must present: "givenName", "patronymicName", "familyName".');if(void 0!==e.givenName&&"string"!=typeof e.givenName)throw new TypeError('The "givenName" parameter must be a string.');if(void 0!==e.patronymicName&&"string"!=typeof e.patronymicName)throw new TypeError('The "patronymicName" parameter must be a string.');if(void 0!==e.familyName&&"string"!=typeof e.familyName)throw new TypeError('The "familyName" parameter must be a string.')}e.detectGender=function(t){return a(this,void 0,void 0,(function*(){return function(e){ef(e),tf(e)}(t),function(t){if(t.patronymicName){const n=t.patronymicName.toLocaleLowerCase();if(Zm.test(n))return e.GrammaticalGender.MASCULINE;if(Ym.test(n))return e.GrammaticalGender.FEMININE}if(t.givenName){const e=t.givenName.replace(Qm,"'").toLocaleLowerCase(),n=Jm[e];if(null!=n)return n}return null}(t)}))},e.inAblative=function(t){return a(this,void 0,void 0,(function*(){return Xm(t),Hm.inflect(t,t.gender,e.GrammaticalCase.ABLATIVE)}))},e.inAccusative=function(t){return a(this,void 0,void 0,(function*(){return Xm(t),Hm.inflect(t,t.gender,e.GrammaticalCase.ACCUSATIVE)}))},e.inDative=function(t){return a(this,void 0,void 0,(function*(){return Xm(t),Hm.inflect(t,t.gender,e.GrammaticalCase.DATIVE)}))},e.inGenitive=function(t){return a(this,void 0,void 0,(function*(){return Xm(t),Hm.inflect(t,t.gender,e.GrammaticalCase.GENITIVE)}))},e.inLocative=function(t){return a(this,void 0,void 0,(function*(){return Xm(t),Hm.inflect(t,t.gender,e.GrammaticalCase.LOCATIVE)}))},e.inNominative=function(t){return a(this,void 0,void 0,(function*(){return Xm(t),Hm.inflect(t,t.gender,e.GrammaticalCase.NOMINATIVE)}))},e.inVocative=function(t){return a(this,void 0,void 0,(function*(){return Xm(t),Hm.inflect(t,t.gender,e.GrammaticalCase.VOCATIVE)}))},Object.defineProperty(e,"__esModule",{value:!0})}));
4686
+ */(Vm,Gm,qm);var Jm={"августа":"feminine","аврелія":"feminine","аврора":"feminine","агапія":"feminine","агата":"feminine","агафія":"feminine","агафоника":"feminine","аглаїда":"feminine","аглая":"feminine","агнеса":"feminine","агнія":"feminine","агрипина":"feminine","ада":"feminine","аделаїда":"feminine","аделіна":"feminine","адріана":"feminine","аеліта":"feminine","аза":"feminine","азалія":"feminine","аїда":"feminine","акилина":"feminine","алевтина":"feminine","аліна":"feminine","аліса":"feminine","алла":"feminine","альбертина":"feminine","альбіна":"feminine","альвіна":"feminine","альфреда":"feminine","анастасія":"feminine","анатолія":"feminine","ангеліна":"feminine","анжела":"feminine","анжеліка":"feminine","анна":"feminine","антонида":"feminine","антоніна":"feminine","антонія":"feminine","анфіса":"feminine","аполлінарія":"feminine","аполлонія":"feminine","аріадна":"feminine","аркадія":"feminine","арсена":"feminine","арсенія":"feminine","артемізія":"feminine","артеміза":"feminine","артемісія":"feminine","артеміса":"feminine","артемія":"feminine","аскліпія":"feminine","ася":"feminine","аурика":"feminine","афанасія":"feminine","афіна":"feminine","атена":"feminine","афродіта":"feminine","бажана":"feminine","барбара":"feminine","беатриса":"feminine","белла":"feminine","берта":"feminine","богдана":"feminine","богуслава":"feminine","божена":"feminine","болеслава":"feminine","борислава":"feminine","броніслава":"feminine","валентина":"feminine","валерія":"feminine","ванда":"feminine","варвара":"feminine","василина":"feminine","васса":"feminine","векла":"feminine","венера":"feminine","вероніка":"feminine","вівдя":"feminine","вікторина":"feminine","вікторія":"feminine","вілена":"feminine","віленіна":"feminine","віліна":"feminine","віола":"feminine","віолетта":"feminine","віра":"feminine","віргінія":"feminine","віринея":"feminine","вірослава":"feminine","віта":"feminine","віталіна":"feminine","віталія":"feminine","влада":"feminine","владилена":"feminine","владислава":"feminine","владлена":"feminine","власта":"feminine","володимира":"feminine","воля":"masculine","всеслава":"feminine","в'ячеслава":"feminine","гаїна":"feminine","галина":"feminine","ганна":"feminine","гафія":"feminine","гелена":"feminine","георгіна":"feminine","гертруда":"feminine","глафіра":"feminine","глафира":"feminine","гликерія":"feminine","ликерія":"feminine","ликера":"feminine","горпина":"feminine","густава":"feminine","дана":"feminine","дарина":"feminine","одарина":"feminine","одарка":"feminine","дарія":"feminine","дзвенимира":"feminine","дзвенислава":"feminine","дзвінка":"feminine","діана":"feminine","діна":"feminine","домна":"feminine","домаха":"feminine","донна":"feminine","доротея":"feminine","дорофея":"feminine","евеліна":"feminine","едіта":"feminine","елеонора":"feminine","елла":"feminine","елвіна":"feminine","ельвіра":"feminine","емма":"feminine","еммануель":"feminine","еммануїла":"feminine","емілія":"feminine","еріка":"feminine","есмеральда":"feminine","естер":"feminine","есфір":"feminine","єва":"feminine","євгенія":"feminine","ївга":"feminine","югина":"feminine","євдокія":"feminine","докія":"feminine","явдоха":"feminine","євфросинія":"feminine","єфросинія":"feminine","єкатерина":"feminine","єлизавета":"feminine","лизавета":"feminine","лисавета":"feminine","гальшка":"feminine","єпистимія":"feminine","єпистима":"feminine","жадана":"feminine","жанна":"feminine","ждана":"feminine","жозефіна":"feminine","забава":"feminine","звенигора":"feminine","звенислава":"feminine","звонимира":"feminine","земфіра":"feminine","зірка":"feminine","зінаїда":"feminine","злата":"feminine","златомира":"feminine","златоуста":"feminine","золотодана":"feminine","зорегляда":"feminine","зореслава":"feminine","зорина":"feminine","зоряна":"feminine","зоря":"feminine","зоя":"feminine","іванна":"feminine","ігорина":"feminine","ілона":"feminine","інга":"feminine","інна":"feminine","інеса":"feminine","ірина":"feminine","ірма":"feminine","іларія":"feminine","ісидора":"feminine","ія":"feminine","йовілла":"feminine","йосипа":"feminine","осипа":"feminine","йосифата":"feminine","казимира":"feminine","казка":"feminine","калина":"feminine","капітоліна":"feminine","капитолина":"feminine","капитоліна":"feminine","карина":"feminine","кароліна":"feminine","кассандра":"feminine","катерина":"feminine","катря":"feminine","квітка":"feminine","квітослава":"feminine","кикилія":"feminine","цецилія":"feminine","килина":"feminine","кіра":"feminine","клавдія":"feminine","клара":"feminine","клеопатра":"feminine","колодара":"feminine","констанція":"feminine","корина":"feminine","кора":"feminine","корнелія":"feminine","красимира":"feminine","красновида":"feminine","краснолика":"feminine","красуня":"feminine","ксенія":"feminine","аксенія":"feminine","оксенія":"feminine","оксана":"feminine","купава":"feminine","лада":"feminine","ладислава":"feminine","ладомила":"feminine","ладомира":"feminine","лариса":"feminine","левина":"feminine","леля":"feminine","леся":"feminine","либідь":"feminine","лідія":"feminine","лілія":"feminine","лілея":"feminine","ліна":"feminine","лола":"feminine","лоліта":"feminine","лукія":"feminine","лукина":"feminine","лукреція":"feminine","любава":"feminine","любаня":"feminine","любислава":"feminine","любов":"feminine","любомила":"feminine","любомира":"feminine","люборада":"feminine","людмила":"feminine","людомила":"feminine","любослава":"feminine","льоля":"feminine","літвіна":"feminine","мавка":"feminine","магадара":"feminine","магдалина":"feminine","магдалена":"feminine","магда":"feminine","маїна":"feminine","майя":"feminine","маківка":"feminine","малуня":"feminine","малуша":"feminine","мальва":"feminine","мальвіна":"feminine","маргарита":"feminine","марта":"feminine","марфа":"feminine","марута":"feminine","марія":"feminine","мар'я":"feminine","марічка":"feminine","марина":"feminine","мартина":"feminine","мар'яна":"feminine","маріанна":"feminine","маріамна":"feminine","медорада":"feminine","меланія":"feminine","мелітина":"feminine","мечислава":"feminine","милана":"feminine","милована":"feminine","миловида":"feminine","милодара":"feminine","милослава":"feminine","мирана":"feminine","миробога":"feminine","миролюба":"feminine","мирослава":"feminine","михайлина":"feminine","млада":"feminine","мокрина":"feminine","макрина":"feminine","моніка":"feminine","мотря":"feminine","мстислава":"feminine","мудролюба":"feminine","надія":"feminine","надіслава":"feminine","найда":"feminine","найдена":"feminine","наслава":"feminine","настасія":"feminine","настя":"feminine","наталія":"feminine","наталя":"feminine","наталка":"feminine","неля":"feminine","немира":"feminine","нігослава":"feminine","незабудка":"feminine","ніка":"feminine","ніна":"feminine","нінель":"feminine","нонна":"feminine","огняна":"feminine","октавія":"feminine","олександра":"feminine","олена":"feminine","олеся":"feminine","олівія":"feminine","олімпіада":"feminine","олімпія":"feminine","ольга":"feminine","ореста":"feminine","оримира":"feminine","орина":"feminine","орислава":"feminine","орися":"feminine","оріяна":"feminine","оріянка":"feminine","орогоста":"feminine","острозора":"feminine","остромира":"feminine","осмомисла":"feminine","остромова":"feminine","пава":"feminine","павла":"feminine","павлина":"feminine","пелагія":"feminine","пелагея":"feminine","палагна":"feminine","палазга":"feminine","параскева":"feminine","параскевія":"feminine","парасковія":"feminine","перелюба":"feminine","перемила":"feminine","перемисла":"feminine","пистина":"feminine","півонія":"feminine","поліна":"feminine","позвізда":"feminine","полеза":"feminine","поляна":"feminine","потішана":"feminine","предслава":"feminine","пріська":"feminine","пульхерія":"feminine","пульхера":"feminine","рада":"feminine","радана":"feminine","радимира":"feminine","радмила":"feminine","радогоста":"feminine","радомира":"feminine","радослава":"feminine","раїна":"feminine","раїса":"feminine","ревека":"feminine","ребекка":"feminine","регіна":"feminine","рената":"feminine","римма":"feminine","рина":"feminine","ріана":"feminine","ріанна":"feminine","рідна":"feminine","рогволода":"feminine","рогніда":"feminine","родослава":"feminine","рожана":"feminine","роза":"feminine","розалія":"feminine","рузалія":"feminine","роксана":"feminine","роксолана":"feminine","ромашка":"feminine","романа":"feminine","ромена":"feminine","росава":"feminine","росина":"feminine","ростислава":"feminine","ростичара":"feminine","ростуня":"feminine","рудана":"feminine","роналіна":"feminine","рошель":"feminine","русана":"feminine","руслана":"feminine","русудана":"feminine","русява":"feminine","русявка":"feminine","рут":"feminine","руф":"feminine","руфіна":"feminine","руфина":"feminine","сабріна":"feminine","санта":"feminine","сара":"feminine","сарра":"feminine","світлана":"feminine","світовида":"feminine","світогора":"feminine","світодара":"feminine","світозара":"feminine","світолика":"feminine","світолюба":"feminine","світослава":"feminine","світояра":"feminine","свободана":"feminine","святогора":"feminine","святолюба":"feminine","святослава":"feminine","севастіана":"feminine","северина":"feminine","секлета":"feminine","секлетина":"feminine","серафима":"feminine","силата":"feminine","силолюба":"feminine","силослава":"feminine","синезора":"feminine","синьоока":"feminine","сільвія":"feminine","сімона":"feminine","слава":"masculine","славина":"feminine","славолюба":"feminine","славомила":"feminine","сміяна":"feminine","сніжана":"feminine","сніжинка":"feminine","собіслава":"feminine","соломія":"feminine","соломонія":"feminine","сологуба":"feminine","сонцевида":"feminine","сонцедара":"feminine","сонцелика":"feminine","сонцеслава":"feminine","соня":"feminine","софія":"feminine","станимира":"feminine","станіслава":"feminine","стелла":"feminine","стефанида":"feminine","стефанія":"feminine","сусанна":"feminine","сосанна":"feminine","судимира":"feminine","судислава":"feminine","сюзанна":"feminine","тава":"feminine","таїсія":"feminine","таїса":"feminine","тамара":"feminine","татолюба":"feminine","твердислава":"feminine","твердогоста":"feminine","творимира":"feminine","творислава":"feminine","текля":"feminine","тереза":"feminine","тетяна":"feminine","тіна":"feminine","толигніва":"feminine","тонкостана":"feminine","трояна":"feminine","улита":"feminine","уляна":"feminine","устина":"feminine","фаїна":"feminine","февронія":"feminine","февросія":"feminine","хівря":"feminine","фекла":"feminine","феліція":"feminine","фелікса":"feminine","филікитата":"feminine","филіцитата":"feminine","филіцата":"feminine","феодора":"feminine","федора":"feminine","тодора":"feminine","федосія":"feminine","феодосія":"feminine","теодозія":"feminine","фотина":"feminine","фотинія":"feminine","фота":"feminine","хотина":"feminine","фросина":"feminine","харита":"feminine","харитина":"feminine","харитя":"feminine","хриса":"feminine","христина":"feminine","христя":"feminine","цецілія":"feminine","цвітана":"feminine","чеслава":"feminine","чухрія":"feminine","юдит":"feminine","юдиф":"feminine","юдихва":"feminine","юзефа":"feminine","юлія":"feminine","юлина":"feminine","юліанія":"feminine","юліанна":"feminine","юліана":"feminine","юнія":"feminine","юстина":"feminine","юхимія":"feminine","юхима":"feminine","юхимина":"feminine","євфимiя":"feminine","єфимія":"feminine","хима":"feminine","ядвіга":"feminine","яна":"feminine","яніна":"feminine","ярина":"feminine","яромира":"feminine","ярослава":"feminine","августин":"masculine","авксентій":"masculine","аврелій":"masculine","автоном":"masculine","адам":"masculine","адріян":"masculine","адріан":"masculine","азар":"masculine","азарій":"masculine","алевтин":"masculine","альберт":"masculine","амвросій":"masculine","анастас":"masculine","анастасій":"masculine","анатолій":"masculine","андрон":"masculine","андрій":"masculine","ондрій":"masculine","антон":"masculine","антоній":"masculine","онтін":"masculine","анісій":"masculine","онісій":"masculine","аркадій":"masculine","арсен":"masculine","арсеній":"masculine","артем":"masculine","артур":"masculine","орхип":"masculine","атанас":"masculine","опанас":"masculine","афанасій":"masculine","аскольд":"masculine","оскольд":"masculine","атрей":"masculine","бажан":"masculine","батко":"masculine","біловид":"masculine","білогост":"masculine","біломир":"masculine","білослав":"masculine","білотур":"masculine","білян":"masculine","благовид":"masculine","благовіст":"masculine","благодар":"masculine","богдан":"masculine","богуслав":"masculine","божан":"masculine","божедар":"masculine","божейко":"masculine","божемир":"masculine","божен":"masculine","божко":"masculine","бойко":"masculine","болеслав":"masculine","боримир":"masculine","боримисл":"masculine","борис":"masculine","борислав":"masculine","боян":"masculine","бративой":"masculine","братимир":"masculine","братислав":"masculine","братко":"masculine","братомил":"masculine","братослав":"masculine","брячислав":"masculine","боронислав":"masculine","будивид":"masculine","будивой":"masculine","будимил":"masculine","будимир":"masculine","будислав":"masculine","буймир":"masculine","буйтур":"masculine","буревій":"masculine","буревіст":"masculine","валентин":"masculine","валерій":"masculine","варфоломій":"masculine","василь":"masculine","вадим":"masculine","ведан":"masculine","велемир":"masculine","велемудр":"masculine","велет":"masculine","величар":"masculine","величко":"masculine","вербан":"masculine","веремій":"masculine","вернидуб":"masculine","вернислав":"masculine","веселан":"masculine","витомир":"masculine","вишата":"masculine","вишезор":"masculine","вишеслав":"masculine","віктор":"masculine","вір":"masculine","віродан":"masculine","віродар":"masculine","вірослав":"masculine","віст":"masculine","вістан":"masculine","віталій":"masculine","вітан":"masculine","вітомир":"masculine","вітрян":"masculine","влад":"masculine","владислав":"masculine","власт":"masculine","вогнедар":"masculine","вогнян":"masculine","водограй":"masculine","водотрав":"masculine","воїслав":"masculine","волелюб":"masculine","володар":"masculine","володимир":"masculine","володислав":"masculine","воротислав":"masculine","вратислав":"masculine","вратан":"masculine","всевлад":"masculine","всеволод":"masculine","вселюб":"masculine","вселюд":"masculine","всеслав":"masculine","вукол":"masculine","вакула":"masculine","в'ячеслав":"masculine","гаврило":"masculine","гарнослав":"masculine","гатусил":"masculine","гатуслав":"masculine","геннадій":"masculine","георгій":"masculine","герасим":"masculine","гервасій":"masculine","гладко":"masculine","гліб":"masculine","гнат":"masculine","годомир":"masculine","голубко":"masculine","горун":"masculine","гордій":"masculine","гордислав":"masculine","гордогост":"masculine","гордодум":"masculine","гордомисл":"masculine","гордослав":"masculine","гордята":"masculine","горигляд":"masculine","горимир":"masculine","горимисл":"masculine","горисвіт":"masculine","горислав":"masculine","горицвіт":"masculine","гостомисл":"masculine","гострозір":"masculine","гостята":"masculine","градимир":"masculine","градислав":"masculine","гранислав":"masculine","грива":"masculine","григорій":"masculine","гремислав":"masculine","грозан":"masculine","громовик":"masculine","гуляйвітер":"masculine","густомисл":"masculine","давид":"masculine","далемил":"masculine","далемир":"masculine","далібор":"masculine","дан":"masculine","данило":"masculine","данко":"masculine","дантур":"masculine","дар":"masculine","дарій":"masculine","дарибог":"masculine","даромир":"masculine","денис":"masculine","демид":"masculine","дем'ян":"masculine","держикрай":"masculine","держислав":"masculine","дибач":"masculine","дивозір":"masculine","дій":"masculine","дмитро":"masculine","добрибій":"masculine","добривод":"masculine","добрик":"masculine","добрило":"masculine","добриня":"masculine","добрисвіт":"masculine","добровіст":"masculine","доброгост":"masculine","добродум":"masculine","добролик":"masculine","добролюб":"masculine","добромир":"masculine","добромисл":"masculine","доброслав":"masculine","доморад":"masculine","домослав":"masculine","дорогобуг":"masculine","дорогомир":"masculine","дорогомисл":"masculine","дорогосил":"masculine","дорогочин":"masculine","дорофій":"masculine","домінік":"masculine","драган":"masculine","драгомир":"masculine","євген":"masculine","євгеній":"masculine","євлампій":"masculine","єремій":"masculine","євстафій":"masculine","єгор":"masculine","жадан":"masculine","ждан":"masculine","живорід":"masculine","живосил":"masculine","живослав":"masculine","житомир":"masculine","життєлюб":"masculine","жито":"masculine","захар":"masculine","захарій":"masculine","збоїслав":"masculine","зборислав":"masculine","звенигор":"masculine","звенимир":"masculine","звенислав":"masculine","здоровега":"masculine","земислав":"masculine","зіновій":"masculine","зиновій":"masculine","злат":"masculine","златомир":"masculine","златоус":"masculine","златодан":"masculine","злотан":"masculine","злотодан":"masculine","зорегляд":"masculine","зоремир":"masculine","зорепад":"masculine","зореслав":"masculine","зорян":"masculine","іван":"masculine","івантослав":"masculine","ігор":"masculine","ізяслав":"masculine","іларіон":"masculine","ілля":"masculine","іоанн":"masculine","каленик":"masculine","квітан":"masculine","києслав":"masculine","кий":"masculine","кирило":"masculine","киян":"masculine","кіндрат":"masculine","княжослав":"masculine","конон":"masculine","корній":"masculine","корнило":"masculine","корнилій":"masculine","корнелій":"masculine","колодар":"masculine","колодій":"masculine","красун":"masculine","крилач":"masculine","куйбіда":"masculine","курило":"masculine","костянтин":"masculine","кузьма":"masculine","лаврін":"masculine","лаврентій":"masculine","лад":"masculine","ладо":"masculine","ладимир":"masculine","ладислав":"masculine","ладолюб":"masculine","ладомир":"masculine","лев":"masculine","левко":"masculine","леонід":"masculine","листвич":"masculine","ліпослав":"masculine","лоліт":"masculine","лук'ян":"masculine","любим":"masculine","любовир":"masculine","любодар":"masculine","любозар":"masculine","любомил":"masculine","любомир":"masculine","любомисл":"masculine","любомудр":"masculine","любослав":"masculine","людомил":"masculine","людислав":"masculine","лютобор":"masculine","лютомисл":"masculine","лука":"masculine","маврикій":"masculine","магадар":"masculine","магамир":"masculine","магаслав":"masculine","маркіян":"masculine","май":"masculine","макар":"masculine","максим":"masculine","малик":"masculine","маломир":"masculine","марко":"masculine","мартин":"masculine","мар'ян":"masculine","матвій":"masculine","медомир":"masculine","межамир":"masculine","мечислав":"masculine","мизамир":"masculine","микита":"masculine","микола":"masculine","милан":"masculine","милован":"masculine","милодар":"masculine","милодух":"masculine","милослав":"masculine","мир":"masculine","миробог":"masculine","мирогост":"masculine","миролюб":"masculine","мирон":"masculine","мирослав":"masculine","михайло":"masculine","мовчан":"masculine","молибог":"masculine","мстибог":"masculine","мстивой":"masculine","мстислав":"masculine","мудролюб":"masculine","мусій":"masculine","муховіст":"masculine","нагнибіда":"masculine","надій":"masculine","найден":"masculine","наслав":"masculine","недан":"masculine","немир":"masculine","нестор":"masculine","непобор":"masculine","нігослав":"masculine","назарій":"masculine","никифор":"masculine","ничипір":"masculine","никодим":"masculine","остромисл":"masculine","одинець":"masculine","олег":"masculine","олександр":"masculine","олексій":"masculine","олесь":"masculine","олелько":"masculine","омелян":"masculine","онуфрій":"masculine","орест":"masculine","осемрит":"masculine","оремів":"masculine","оримир":"masculine","осмомисл":"masculine","остап":"masculine","острозор":"masculine","остромир":"masculine","остромов":"masculine","охрім":"masculine","олекса":"masculine","павло":"masculine","пантелеймон":"masculine","панас":"masculine","первушко":"masculine","перелюб":"masculine","перемил":"masculine","перемисл":"masculine","пересвіт":"masculine","переяслав":"masculine","першик":"masculine","петро":"masculine","пилип":"masculine","пимен":"masculine","пимін":"masculine","пимон":"masculine","подолян":"masculine","позвізд":"masculine","полель":"masculine","полян":"masculine","порфир":"masculine","потап":"masculine","пребислав":"masculine","предислав":"masculine","пор":"masculine","палац":"masculine","п'єр":"masculine","рава":"masculine","рад":"masculine","радан":"masculine","радечко":"masculine","радивой":"masculine","радило":"masculine","радим":"masculine","радимир":"masculine","радослав":"masculine","радко":"masculine","радован":"masculine","радогост":"masculine","радомир":"masculine","радомисл":"masculine","ратибор":"masculine","ратимир":"masculine","ратислав":"masculine","рафаїл":"masculine","ревун":"masculine","рід":"masculine","рогволод":"masculine","родан":"masculine","родіон":"masculine","родослав":"masculine","рожден":"masculine","роксолан":"masculine","роман":"masculine","ростислав":"masculine","ростичар":"masculine","ростун":"masculine","рудан":"masculine","рус":"masculine","русан":"masculine","руслан":"masculine","русудан":"masculine","сармат":"masculine","сварг":"masculine","свирид":"masculine","світ":"masculine","світан":"masculine","світлан":"masculine","світлогор":"masculine","світогор":"masculine","світовид":"masculine","світодар":"masculine","світозар":"masculine","світокол":"masculine","світолик":"masculine","світолюб":"masculine","світомир":"masculine","світослав":"masculine","світояр":"masculine","свободан":"masculine","святовид":"masculine","святогор":"masculine","святолюб":"masculine","святополк":"masculine","святослав":"masculine","святояр":"masculine","северин":"masculine","семен":"masculine","семибор":"masculine","семирад":"masculine","серафим":"masculine","сергій":"masculine","сердитко":"masculine","сила":"masculine","силан":"masculine","силолюб":"masculine","силослав":"masculine","синьоок":"masculine","скол":"masculine","славобор":"masculine","славолюб":"masculine","славомир":"masculine","славута":"masculine","снага":"masculine","сніжан":"masculine","сновид":"masculine","снозір":"masculine","собібор":"masculine","собімир":"masculine","собіслав":"masculine","сокіл":"masculine","соловей":"masculine","сологуб":"masculine","солопій":"masculine","сонцевид":"masculine","сонцедар":"masculine","сонцелик":"masculine","спас":"masculine","станимир":"masculine","станислав":"masculine","стародум":"masculine","степан":"masculine","стефаній":"masculine","стожар":"masculine","стоймир":"masculine","стоян":"masculine","судивой":"masculine","судимир":"masculine","судислав":"masculine","сурма":"masculine","тарас":"masculine","татомир":"masculine","тарослав":"masculine","таросик":"masculine","твердигост":"masculine","твердислав":"masculine","творилад":"masculine","творимир":"masculine","творислав":"masculine","теодозій":"masculine","терентій":"masculine","тімох":"masculine","тимофій":"masculine","тиміш":"masculine","тимур":"masculine","тихомир":"masculine","тихон":"masculine","тодось":"masculine","толигнів":"masculine","толислав":"masculine","тригост":"masculine","троян":"masculine","триріг":"masculine","тур":"masculine","турбог":"masculine","турбрід":"masculine","улас":"masculine","уличан":"masculine","ус":"masculine","устим":"masculine","флор":"masculine","фрол":"masculine","федір":"masculine","фауст":"masculine","хвала":"masculine","хвалибог":"masculine","хвалимир":"masculine","ходота":"masculine","хорив":"masculine","хорошко":"masculine","хотибор":"masculine","хотимир":"masculine","хотян":"masculine","хранимир":"masculine","христофор":"masculine","худан":"masculine","царко":"masculine","цвітан":"masculine","царук":"masculine","чара":"masculine","чернин":"masculine","чеслав":"masculine","чесмил":"masculine","честислав":"masculine","щастибог":"masculine","щастислав":"masculine","щедрогост":"masculine","щек":"masculine","юліан":"masculine","юлій":"masculine","юрій":"masculine","юхим":"masculine","явір":"masculine","яволод":"masculine","яків":"masculine","ян":"masculine","яр":"masculine","ярема":"masculine","ярило":"masculine","яровид":"masculine","яровит":"masculine","яромил":"masculine","яромир":"masculine","яромисл":"masculine","ярополк":"masculine","яросвіт":"masculine","ярослав":"masculine","ярош":"masculine","яртур":"masculine","ярчик":"masculine","ясен":"masculine","ясновид":"masculine","ясногор":"masculine","яснозір":"masculine","яснолик":"masculine"};const Zm=/[иі]ч$/,Ym=/на$/,Qm=/[`"]/g;class Xm extends TypeError{}function ef(t){if(!nf(t))throw new Xm("The input type must be an object.");if(!function(e,t){return t.includes(e)}(t.gender,Object.values(e.GrammaticalGender)))throw new Xm(`The "gender" parameter must be one of the following: "${e.GrammaticalGender.MASCULINE}", "${e.GrammaticalGender.FEMININE}".`);if(!tf(t.givenName)&&!tf(t.patronymicName)&&!tf(t.familyName))throw new Xm('At least one of the following parameters must present: "givenName", "patronymicName", "familyName".');if(tf(t.givenName)&&!af(t.givenName))throw new Xm('The "givenName" parameter must be a string.');if(tf(t.patronymicName)&&!af(t.patronymicName))throw new Xm('The "patronymicName" parameter must be a string.');if(tf(t.familyName)&&!af(t.familyName))throw new Xm('The "familyName" parameter must be a string.')}function tf(e){return void 0!==e}function nf(e){return null!=e&&"object"==typeof e}function af(e){return"string"==typeof e}e.InputValidationError=Xm,e.detectGender=function(t){return a(this,void 0,void 0,(function*(){return function(e){if(!nf(e))throw new Xm("The input type must be an object.");if(!tf(e.givenName)&&!tf(e.patronymicName)&&!tf(e.familyName))throw new Xm('At least one of the following parameters must present: "givenName", "patronymicName", "familyName".');if(tf(e.givenName)&&!af(e.givenName))throw new Xm('The "givenName" parameter must be a string.');if(tf(e.patronymicName)&&!af(e.patronymicName))throw new Xm('The "patronymicName" parameter must be a string.');if(tf(e.familyName)&&!af(e.familyName))throw new Xm('The "familyName" parameter must be a string.')}(t),function(t){if(t.patronymicName){const n=t.patronymicName.toLocaleLowerCase();if(Zm.test(n))return e.GrammaticalGender.MASCULINE;if(Ym.test(n))return e.GrammaticalGender.FEMININE}if(t.givenName){const e=t.givenName.replace(Qm,"'").toLocaleLowerCase(),n=Jm[e];if(null!=n)return n}return null}(t)}))},e.inAblative=function(t){return a(this,void 0,void 0,(function*(){ef(t);return yield Hm.inflect(t,t.gender,e.GrammaticalCase.ABLATIVE)}))},e.inAccusative=function(t){return a(this,void 0,void 0,(function*(){ef(t);return yield Hm.inflect(t,t.gender,e.GrammaticalCase.ACCUSATIVE)}))},e.inDative=function(t){return a(this,void 0,void 0,(function*(){ef(t);return yield Hm.inflect(t,t.gender,e.GrammaticalCase.DATIVE)}))},e.inGenitive=function(t){return a(this,void 0,void 0,(function*(){ef(t);return yield Hm.inflect(t,t.gender,e.GrammaticalCase.GENITIVE)}))},e.inLocative=function(t){return a(this,void 0,void 0,(function*(){ef(t);return yield Hm.inflect(t,t.gender,e.GrammaticalCase.LOCATIVE)}))},e.inNominative=function(t){return a(this,void 0,void 0,(function*(){ef(t);return yield Hm.inflect(t,t.gender,e.GrammaticalCase.NOMINATIVE)}))},e.inVocative=function(t){return a(this,void 0,void 0,(function*(){ef(t);return yield Hm.inflect(t,t.gender,e.GrammaticalCase.VOCATIVE)}))},Object.defineProperty(e,"__esModule",{value:!0})}));
4687
4687
  //# sourceMappingURL=shevchenko.min.js.map