shevchenko 3.1.0-alpha.5 → 3.1.0-alpha.6
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.
- package/dist/cjs/anthroponym-declension/anthroponym-inflector.js +1 -1
- package/dist/cjs/anthroponym-declension/bootstrap.js +1 -1
- package/dist/cjs/anthroponym-declension/family-name-classifier/artifacts/model.bundle.json.js +1 -1
- package/dist/cjs/anthroponym-declension/family-name-classifier/cache/incorrect-predictions.json.js +1 -1
- package/dist/cjs/anthroponym-declension/family-name-classifier/family-name-class-transformer.js +1 -1
- package/dist/cjs/anthroponym-declension/family-name-classifier/family-name-classifer.js +1 -1
- package/dist/cjs/anthroponym-declension/family-name-classifier/model-bundle-loader.js +1 -1
- package/dist/cjs/anthroponym-declension/family-name-classifier/model-config.js +1 -1
- package/dist/cjs/anthroponym-declension/family-name-classifier/word-transformer.js +1 -1
- package/dist/cjs/anthroponym-declension/family-name-inflector.js +1 -1
- package/dist/cjs/anthroponym-declension/given-name-inflector.js +1 -1
- package/dist/cjs/anthroponym-declension/name-inflector.js +1 -1
- package/dist/cjs/anthroponym-declension/patronymic-name-inflector.js +1 -1
- package/dist/cjs/extension.js +9 -1
- package/dist/cjs/gender-detection/detect-gender.js +1 -1
- package/dist/cjs/gender-detection/given-names-genders.json.js +1 -1
- package/dist/cjs/index.js +1 -1
- package/dist/cjs/input-validation.js +27 -41
- package/dist/cjs/language/alphabet.js +1 -1
- package/dist/cjs/language/grammatical-case.js +1 -1
- package/dist/cjs/language/grammatical-gender.js +1 -1
- package/dist/cjs/language/letter-case.js +1 -1
- package/dist/cjs/language/linguistics.js +1 -1
- package/dist/cjs/language/word-class.js +1 -1
- package/dist/cjs/shevchenko.js +1 -1
- package/dist/cjs/word-declension/append-command-runner.js +1 -1
- package/dist/cjs/word-declension/bootstrap.js +1 -1
- package/dist/cjs/word-declension/command-runner-factory.js +1 -1
- package/dist/cjs/word-declension/declension-rule-inflector.js +1 -1
- package/dist/cjs/word-declension/declension-types.js +1 -1
- package/dist/cjs/word-declension/replace-command-runner.js +1 -1
- package/dist/cjs/word-declension/rules/artifacts/declension-rules.json.js +1 -1
- package/dist/cjs/word-declension/word-inflector.js +1 -1
- package/dist/es/anthroponym-declension/anthroponym-inflector.js +1 -1
- package/dist/es/anthroponym-declension/bootstrap.js +1 -1
- package/dist/es/anthroponym-declension/family-name-classifier/artifacts/model.bundle.json.js +1 -1
- package/dist/es/anthroponym-declension/family-name-classifier/cache/incorrect-predictions.json.js +1 -1
- package/dist/es/anthroponym-declension/family-name-classifier/family-name-class-transformer.js +1 -1
- package/dist/es/anthroponym-declension/family-name-classifier/family-name-classifer.js +1 -1
- package/dist/es/anthroponym-declension/family-name-classifier/model-bundle-loader.js +1 -1
- package/dist/es/anthroponym-declension/family-name-classifier/model-config.js +1 -1
- package/dist/es/anthroponym-declension/family-name-classifier/word-transformer.js +1 -1
- package/dist/es/anthroponym-declension/family-name-inflector.js +1 -1
- package/dist/es/anthroponym-declension/given-name-inflector.js +1 -1
- package/dist/es/anthroponym-declension/name-inflector.js +1 -1
- package/dist/es/anthroponym-declension/patronymic-name-inflector.js +1 -1
- package/dist/es/extension.d.ts +2 -2
- package/dist/es/extension.js +9 -2
- package/dist/es/gender-detection/detect-gender.js +1 -1
- package/dist/es/gender-detection/given-names-genders.json.js +1 -1
- package/dist/es/index.js +1 -1
- package/dist/es/input-validation.d.ts +2 -2
- package/dist/es/input-validation.js +27 -41
- package/dist/es/language/alphabet.js +1 -1
- package/dist/es/language/grammatical-case.js +1 -1
- package/dist/es/language/grammatical-gender.js +1 -1
- package/dist/es/language/letter-case.js +1 -1
- package/dist/es/language/linguistics.js +1 -1
- package/dist/es/language/word-class.js +1 -1
- package/dist/es/shevchenko.js +1 -1
- package/dist/es/word-declension/append-command-runner.js +1 -1
- package/dist/es/word-declension/bootstrap.js +1 -1
- package/dist/es/word-declension/command-runner-factory.js +1 -1
- package/dist/es/word-declension/declension-rule-inflector.js +1 -1
- package/dist/es/word-declension/declension-types.js +1 -1
- package/dist/es/word-declension/replace-command-runner.js +1 -1
- package/dist/es/word-declension/rules/artifacts/declension-rules.json.js +1 -1
- package/dist/es/word-declension/word-inflector.js +1 -1
- package/dist/umd/shevchenko.min.js +89 -89
- package/package.json +3 -2
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* @file JavaScript library for declension of Ukrainian anthroponyms
|
|
3
3
|
* @module shevchenko
|
|
4
|
-
* @version 3.1.0-alpha.
|
|
4
|
+
* @version 3.1.0-alpha.6
|
|
5
5
|
* @author Oleksandr Tolochko <shevchenko-js@tooleks.com>
|
|
6
6
|
* @license MIT
|
|
7
7
|
* @copyright 2017-2024 Oleksandr Tolochko <shevchenko-js@tooleks.com>
|
|
@@ -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 T(e,t){if(!e)throw new Error("string"==typeof t?t:t())}function I(e,t,n=""){T(
|
|
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(A(e,t),(()=>n+` Shapes ${e} and ${t} must match`))}function $(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 A(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(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(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){return F(e,t)}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=>{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)}getString(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){const n=t.toLowerCase();return"true"===n||"false"===n?"true"===n:""+ +n===n?+n:t}(0,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"
|
|
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)}getString(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){const n=t.toLowerCase();return"true"===n||"false"===n?"true"===n:""+ +n===n?+n:t}(0,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",$e="Identity",Ce="LeakyRelu",Ae="Log1p",Ee="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";
|
|
43
43
|
/**
|
|
44
44
|
* @license
|
|
45
45
|
* 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
|
-
*/function It(e,t){if("string"===t)throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(e)&&(e=jt(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
|
|
107
|
+
*/function It(e,t){if("string"===t)throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(e)&&(e=jt(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 $t(){return Q().platform.now()}function Ct(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 Et(e){return null!=Q().platform.isTypedArray?Q().platform.isTypedArray(e):Tt(e)}function jt(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)jt(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++)jt(e[a],t,n)}return t}
|
|
108
108
|
/**
|
|
109
109
|
* @license
|
|
110
110
|
* Copyright 2018 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
|
-
*/class zt{constructor(e,t){this.backendTimer=e,this.logger=t,null==t&&(this.logger=new Ft)}profileKernel(e,t,n){let i;const a=()=>{i=n()};let s;const r
|
|
123
|
+
*/class zt{constructor(e,t){this.backendTimer=e,this.logger=t,null==t&&(this.logger=new Ft)}profileKernel(e,t,n){let i;const a=()=>{i=n()};let s;const r=$t();if(this.backendTimer.timerAvailable())s=this.backendTimer.time(a);else{a();for(const e of i)e.dataSync();s=Promise.resolve({kernelMs:$t()-r})}if(Q().getBool("CHECK_COMPUTATION_FOR_ERRORS"))for(let t=0;t<i.length;t++){const n=i[t];n.data().then((t=>{Dt(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 Dt(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 Ft{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")}}
|
|
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
|
-
*/function _t(e,t,n,i){const a=P(t),s=function(e,t,n,i){const a=
|
|
139
|
+
*/function _t(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?Ot(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],Rt(l[t+e],0,n).length)}return r}(e,t,n,a),r=t.length,o=Mt(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 Rt(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?Lt(e):parseFloat(e.toFixed(7)).toString(),j(i,t)}function Lt(e){return 0===e?"false":"true"}function Mt(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[Rt(Ot(e)[0],0,n)]}return"bool"===n?[Lt(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=Ot(i),s=Ot(s)),["["+i.map(((e,t)=>Rt(e,a[t],n))).join(", ")+", ..., "+s.map(((e,t)=>Rt(e,a[o-3+t],n))).join(", ")+"]"]}return["["+("complex64"===n?Ot(e):Array.from(e)).map(((e,t)=>Rt(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(...Mt(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(...Mt(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(...Mt(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 Ot(e){const t=[];for(let n=0;n<e.length;n+=2)t.push([e[n],e[n+1]]);return t}
|
|
140
140
|
/**
|
|
141
141
|
* @license
|
|
142
142
|
* Copyright 2017 Google LLC. All Rights Reserved.
|
|
@@ -152,7 +152,7 @@ function gt(...e){Q().getBool("IS_TEST")||Q().getBool("PROD")||console.warn(...e
|
|
|
152
152
|
* See the License for the specific language governing permissions and
|
|
153
153
|
* limitations under the License.
|
|
154
154
|
* =============================================================================
|
|
155
|
-
*/class Pt{constructor(e,t,n){if(this.dtype=t,this.shape=e.slice(),this.size=
|
|
155
|
+
*/class Pt{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 Bt().makeTensor(this.values,this.shape,this.dtype)}}let Bt=null,Ut=null;class Wt{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 Ut.buffer(this.shape,this.dtype,e)}bufferSync(){return Ut.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=Bt().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(),Bt().readToGPU(this.dataId,e)}dataSync(){this.throwIfDisposed();const e=Bt().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 Bt().read(this.dataId);return"string"===this.dtype?e:new Uint8Array(e.buffer)}dispose(){this.isDisposed||(this.kerasMask&&this.kerasMask.dispose(),Bt().disposeTensor(this),this.isDisposedInternal=!0)}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return Ut.print(this,e)}clone(){return this.throwIfDisposed(),Ut.clone(this)}toString(e=!1){return _t(this.dataSync(),this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),Ut.cast(this,e)}variable(e=!0,t,n){return this.throwIfDisposed(),Bt().makeVariable(this,e,t,n)}}function Gt(){return ne("Tensor",(()=>Wt))}Object.defineProperty(Wt,Symbol.hasInstance,{value:e=>!!e&&null!=e.data&&null!=e.dataSync&&null!=e.throwIfDisposed}),Gt();class Vt extends Wt{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(!A(e.shape,this.shape))throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);Bt().disposeTensor(this),this.dataId=e.dataId,Bt().incRef(this,null)}dispose(){Bt().disposeVariable(this),this.isDisposedInternal=!0}}
|
|
156
156
|
/**
|
|
157
157
|
* @license
|
|
158
158
|
* Copyright 2017 Google LLC. All Rights Reserved.
|
|
@@ -201,7 +201,7 @@ var Kt,qt,Ht,Jt,Zt;Object.defineProperty(Vt,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
|
-
*/const a=e;for(const e in a){const i=a[e];n.has(i)||(n.add(i),an(i,t,n))}}function sn(e){return null!=e.kernelName}class rn{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 on{constructor(e){this.ENV=e,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new rn}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 zt(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 on.nextTensorId++}nextVariableId(){return on.nextVariableId++}clone(e){const t=cn.runKernel(Ce,{x:e}),n={x:e};return this.addTapeNode(this.state.activeScope.name,n,[t],(e=>({x:()=>{const t={x:e},n={dtype:"float32"};return cn.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=sn(e)?e.kernelName:null!=this.state.activeScope?this.state.activeScope.name:"";if(sn(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=sn(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 Wt(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 Wt(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 Vt(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 Vt||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=nn(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 Wt,(()=>"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 cn.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(!$(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()}}}}
|
|
204
|
+
*/const a=e;for(const e in a){const i=a[e];n.has(i)||(n.add(i),an(i,t,n))}}function sn(e){return null!=e.kernelName}class rn{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 on{constructor(e){this.ENV=e,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new rn}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 zt(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 on.nextTensorId++}nextVariableId(){return on.nextVariableId++}clone(e){const t=cn.runKernel($e,{x:e}),n={x:e};return this.addTapeNode(this.state.activeScope.name,n,[t],(e=>({x:()=>{const t={x:e},n={dtype:"float32"};return cn.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=sn(e)?e.kernelName:null!=this.state.activeScope?this.state.activeScope.name:"";if(sn(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=sn(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=>Ct(e))));const s=i.write(a,t,n),r=new Wt(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 Wt(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 Vt(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 Vt||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=nn(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 Wt,(()=>"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 cn.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(!A(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()}}}}
|
|
205
205
|
/**
|
|
206
206
|
* @license
|
|
207
207
|
* Copyright 2018 Google LLC. All Rights Reserved.
|
|
@@ -217,7 +217,7 @@ var Kt,qt,Ht,Jt,Zt;Object.defineProperty(Vt,Symbol.hasInstance,{value:e=>e insta
|
|
|
217
217
|
* See the License for the specific language governing permissions and
|
|
218
218
|
* limitations under the License.
|
|
219
219
|
* =============================================================================
|
|
220
|
-
*/(e,s,(e=>this.tidy(e)),un);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 Wt)),(()=>"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 Wt,(()=>"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 Wt)),(()=>"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
|
|
220
|
+
*/(e,s,(e=>this.tidy(e)),un);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 Wt)),(()=>"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 Wt,(()=>"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 Wt)),(()=>"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=$t(),n=await this.backend.time(e);return n.wallMs=$t()-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 rn;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 ln(){const e=te();if(null==e._tfengine){const t=new Z(e);e._tfengine=new on(t)}var t;
|
|
221
221
|
/**
|
|
222
222
|
* @license
|
|
223
223
|
* Copyright 2020 Google LLC. All Rights Reserved.
|
|
@@ -331,7 +331,7 @@ function pn(e,t){let n=e;if(Et(e))return"string"===t?[]:[e.length];if(Xt(e)){con
|
|
|
331
331
|
* See the License for the specific language governing permissions and
|
|
332
332
|
* limitations under the License.
|
|
333
333
|
* =============================================================================
|
|
334
|
-
*/function bn(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(en(e)||Xt(e)){if("float32"!==i&&"int32"!==i)throw new Error(`Creating tensor from GPU data only supports 'float32'|'int32' dtype, while the dtype is ${i}.`);return cn.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){V(t);const e=
|
|
334
|
+
*/function bn(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(en(e)||Xt(e)){if("float32"!==i&&"int32"!==i)throw new Error(`Creating tensor from GPU data only supports 'float32'|'int32' dtype, while the dtype is ${i}.`);return cn.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){V(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?It(e,i):jt(e,[],!0),cn.makeTensor(e,t,i)}
|
|
335
335
|
/**
|
|
336
336
|
* @license
|
|
337
337
|
* Copyright 2018 Google LLC. All Rights Reserved.
|
|
@@ -379,7 +379,7 @@ function pn(e,t){let n=e;if(Et(e))return"string"===t?[]:[e.length];if(Xt(e)){con
|
|
|
379
379
|
* See the License for the specific language governing permissions and
|
|
380
380
|
* limitations under the License.
|
|
381
381
|
* =============================================================================
|
|
382
|
-
*/(this.shards,t);return-1===n?-1:(this.previousShardIndex=n,this.previousShardIndex)}}function Sn(){return cn}function Nn(){return cn.memory()}function Tn(e,t){return cn.tidy(e,t)}function In(e){nn(e).forEach((e=>e.dispose()))}function
|
|
382
|
+
*/(this.shards,t);return-1===n?-1:(this.previousShardIndex=n,this.previousShardIndex)}}function Sn(){return cn}function Nn(){return cn.memory()}function Tn(e,t){return cn.tidy(e,t)}function In(e){nn(e).forEach((e=>e.dispose()))}function $n(e){return cn.keep(e)}async function Cn(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:jn(await Promise.all(i)),specs:n}}function An(e,t){const n=C(e.shape);let i;if("quantization"in e){const t=e.quantization;i=kn[t.dtype]}else{if("string"===e.dtype){let e=0;for(let i=0;i<n;i++)e+=4+new Uint32Array(t(e,e+4))[0];return e}i=kn[e.dtype]}return n*i}function En(e,t){const n=e.name,i=e.dtype,a=e.shape,s=C(a);let r,o=0;if("quantization"in e){const a=e.quantization;if("uint8"===a.dtype||"uint16"===a.dtype){if(!("min"in a)||!("scale"in a))throw new Error(`Weight ${e.name} with quantization ${a.dtype} doesn't have corresponding metadata min and scale.`)}else{if("float16"!==a.dtype)throw new Error(`Weight ${e.name} has unknown quantization dtype ${a.dtype}. Supported quantization dtypes are: 'uint8', 'uint16', and 'float16'.`);if("float32"!==i)throw new Error(`Weight ${e.name} is quantized with ${a.dtype} which only supports weights of type float32 not ${i}.`)}const l=kn[a.dtype],c="uint8"===a.dtype?new Uint8Array(t):new Uint16Array(t);if("float32"===i)if("uint8"===a.dtype||"uint16"===a.dtype){r=new Float32Array(c.length);for(let e=0;e<c.length;e++){const t=c[e];r[e]=t*a.scale+a.min}}else{if("float16"!==a.dtype)throw new Error(`Unsupported quantization type ${a.dtype} for weight type float32.`);{const e=function(){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)}}
|
|
383
383
|
/**
|
|
384
384
|
* @license
|
|
385
385
|
* Copyright 2018 Google LLC. All Rights Reserved.
|
|
@@ -395,7 +395,7 @@ function pn(e,t){let n=e;if(Et(e))return"string"===t?[]:[e.length];if(Xt(e)){con
|
|
|
395
395
|
* See the License for the specific language governing permissions and
|
|
396
396
|
* limitations under the License.
|
|
397
397
|
* =============================================================================
|
|
398
|
-
*/();r=e(c)}}else{if("int32"!==i)throw new Error(`Unsupported dtype in weight '${n}': ${i}`);if("uint8"!==a.dtype&&"uint16"!==a.dtype)throw new Error(`Unsupported quantization type ${a.dtype} for weight type int32.`);r=new Int32Array(c.length);for(let e=0;e<c.length;e++){const t=c[e];r[e]=Math.round(t*a.scale+a.min)}}o+=s*l}else if("string"===i){const n=
|
|
398
|
+
*/();r=e(c)}}else{if("int32"!==i)throw new Error(`Unsupported dtype in weight '${n}': ${i}`);if("uint8"!==a.dtype&&"uint16"!==a.dtype)throw new Error(`Unsupported quantization type ${a.dtype} for weight type int32.`);r=new Int32Array(c.length);for(let e=0;e<c.length;e++){const t=c[e];r[e]=Math.round(t*a.scale+a.min)}}o+=s*l}else if("string"===i){const n=C(e.shape);r=[];for(let e=0;e<n;e++){const e=new Uint32Array(t.slice(o,o+4))[0];o+=4;const n=new Uint8Array(t.slice(o,o+e));r.push(n),o+=e}}else{const e=kn[i];if("float32"===i)r=new Float32Array(t);else if("int32"===i)r=new Int32Array(t);else{if("bool"!==i){if("complex64"===i){r=new Float32Array(t);const e=new Float32Array(r.length/2),n=new Float32Array(r.length/2);for(let t=0;t<e.length;t++)e[t]=r[2*t],n[t]=r[2*t+1];const i=wn(e,a,"float32"),s=wn(n,a,"float32"),o=yn(i,s);return i.dispose(),s.dispose(),o}throw new Error(`Unsupported dtype in weight '${n}': ${i}`)}r=new Uint8Array(t)}o+=s*e}return wn(r,a,i)}function jn(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 zn="undefined"!=typeof Buffer&&("undefined"==typeof Blob||"undefined"==typeof atob||"undefined"==typeof btoa);function Dn(e){return zn?Buffer.byteLength(e,"utf8"):new Blob([e]).size}async function Fn(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 _n(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:Dn(JSON.stringify(e.modelTopology)),weightSpecsBytes:null==e.weightSpecs?0:Dn(JSON.stringify(e.weightSpecs)),weightDataBytes:null==e.weightData?0:new xn(e.weightData).byteLength}}function Rn(e){const t=[];for(const n of e)t.push(...n.weights);return t}class Ln{constructor(){this.saveRouters=[],this.loadRouters=[]}static getInstance(){return null==Ln.instance&&(Ln.instance=new Ln),Ln.instance}static registerSaveRouter(e){Ln.getInstance().saveRouters.push(e)}static registerLoadRouter(e){Ln.getInstance().loadRouters.push(e)}static getSaveHandlers(e){return Ln.getHandlers(e,"save")}static getLoadHandlers(e,t){return Ln.getHandlers(e,"load",t)}static getHandlers(e,t,n){const i=[];return("load"===t?Ln.getInstance().loadRouters:Ln.getInstance().saveRouters).forEach((t=>{const a=t(e,n);null!==a&&i.push(a)})),i}}const Mn="tensorflowjs",On="models_store",Pn="model_info_store";function Bn(){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 Un(e){const t=e.result;t.createObjectStore(On,{keyPath:"modelPath"}),t.createObjectStore(Pn,{keyPath:"modelPath"})}class Wn{constructor(e){if(this.indexedDB=Bn(),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(Mn,1);i.onupgradeneeded=()=>Un(i),i.onsuccess=()=>{const a=i.result;if(null==t){const t=a.transaction(On,"readonly"),i=t.objectStore(On).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{t.weightData=xn.join(t.weightData);const i=_n(t),s=a.transaction(Pn,"readwrite");let r,o,l=s.objectStore(Pn);try{r=l.put({modelPath:this.modelPath,modelArtifactsInfo:i})}catch(e){return n(e)}r.onsuccess=()=>{o=a.transaction(On,"readwrite");const r=o.objectStore(On);let c;try{c=r.put({modelPath:this.modelPath,modelArtifacts:t,modelArtifactsInfo:i})}catch(e){return n(e)}c.onsuccess=()=>e({modelArtifactsInfo:i}),c.onerror=e=>{l=s.objectStore(Pn);const t=l.delete(this.modelPath);t.onsuccess=()=>(a.close(),n(c.error)),t.onerror=e=>(a.close(),n(c.error))}},r.onerror=e=>(a.close(),n(r.error)),s.oncomplete=()=>{null==o?a.close():o.oncomplete=()=>a.close()}}},i.onerror=e=>n(i.error)}))}}Wn.URL_SCHEME="indexeddb://";const Gn=e=>{return Q().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(Wn.URL_SCHEME)?(t=e.slice(Wn.URL_SCHEME.length),new Wn(t)):null;var t};Ln.registerSaveRouter(Gn),Ln.registerLoadRouter(Gn);class Vn{constructor(){this.indexedDB=Bn()}async listModels(){return new Promise(((e,t)=>{const n=this.indexedDB.open(Mn,1);n.onupgradeneeded=()=>Un(n),n.onsuccess=()=>{const i=n.result,a=i.transaction(Pn,"readonly"),s=a.objectStore(Pn).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(Wn.URL_SCHEME)?t.slice(Wn.URL_SCHEME.length):t,new Promise(((t,n)=>{const i=this.indexedDB.open(Mn,1);i.onupgradeneeded=()=>Un(i),i.onsuccess=()=>{const a=i.result,s=a.transaction(Pn,"readwrite"),r=s.objectStore(Pn),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(On,"readwrite");const i=l.objectStore(On).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)}))}}
|
|
399
399
|
/**
|
|
400
400
|
* @license
|
|
401
401
|
* Copyright 2018 Google LLC. All Rights Reserved.
|
|
@@ -635,7 +635,7 @@ function pn(e,t){let n=e;if(Et(e))return"string"===t?[]:[e.length];if(Xt(e)){con
|
|
|
635
635
|
* See the License for the specific language governing permissions and
|
|
636
636
|
* limitations under the License.
|
|
637
637
|
* =============================================================================
|
|
638
|
-
*/const
|
|
638
|
+
*/const $i=vn({add_:function(e,t){let n=fn(e,"a","add"),i=fn(t,"b","add");[n,i]=tn(n,i);const a={a:n,b:i};return cn.runKernel(ie,a)}});
|
|
639
639
|
/**
|
|
640
640
|
* @license
|
|
641
641
|
* Copyright 2020 Google LLC. All Rights Reserved.
|
|
@@ -651,7 +651,7 @@ function pn(e,t){let n=e;if(Et(e))return"string"===t?[]:[e.length];if(Xt(e)){con
|
|
|
651
651
|
* See the License for the specific language governing permissions and
|
|
652
652
|
* limitations under the License.
|
|
653
653
|
* =============================================================================
|
|
654
|
-
*/const
|
|
654
|
+
*/const Ci=vn({floorDiv_:function(e,t){let n=fn(e,"a","floorDiv"),i=fn(t,"b","floorDiv");[n,i]=tn(n,i);const a={a:n,b:i};return cn.runKernel(Se,a)}});
|
|
655
655
|
/**
|
|
656
656
|
* @license
|
|
657
657
|
* Copyright 2020 Google LLC. All Rights Reserved.
|
|
@@ -667,7 +667,7 @@ function pn(e,t){let n=e;if(Et(e))return"string"===t?[]:[e.length];if(Xt(e)){con
|
|
|
667
667
|
* See the License for the specific language governing permissions and
|
|
668
668
|
* limitations under the License.
|
|
669
669
|
* =============================================================================
|
|
670
|
-
*/const
|
|
670
|
+
*/const Ai=vn({div_:function(e,t){let n=fn(e,"a","div"),i=fn(t,"b","div");if([n,i]=tn(n,i),"int32"===n.dtype&&"int32"===i.dtype)return Ci(n,i);const a={a:n,b:i};return cn.runKernel(be,a,{})}});
|
|
671
671
|
/**
|
|
672
672
|
* @license
|
|
673
673
|
* Copyright 2020 Google LLC. All Rights Reserved.
|
|
@@ -827,7 +827,7 @@ function pn(e,t){let n=e;if(Et(e))return"string"===t?[]:[e.length];if(Xt(e)){con
|
|
|
827
827
|
* See the License for the specific language governing permissions and
|
|
828
828
|
* limitations under the License.
|
|
829
829
|
* =============================================================================
|
|
830
|
-
*/const Ki=vn({clone_:function(e){const t={x:fn(e,"x","clone","string_or_numeric")};return cn.runKernel(
|
|
830
|
+
*/const Ki=vn({clone_:function(e){const t={x:fn(e,"x","clone","string_or_numeric")};return cn.runKernel($e,t)}});
|
|
831
831
|
/**
|
|
832
832
|
* @license
|
|
833
833
|
* Copyright 2020 Google LLC. All Rights Reserved.
|
|
@@ -1228,7 +1228,7 @@ function(e,t,n,i,a,s){null==s&&(s=.001);const r=fn(e,"x","batchNorm"),o=fn(t,"me
|
|
|
1228
1228
|
* See the License for the specific language governing permissions and
|
|
1229
1229
|
* limitations under the License.
|
|
1230
1230
|
* =============================================================================
|
|
1231
|
-
*/const
|
|
1231
|
+
*/const $a=vn({einsum_:function(e,...t){const n=t.map(((e,t)=>fn(e,`tensors${t}`,"einsum"))),i={equation:e};return cn.runKernel("Einsum",n,i)}});
|
|
1232
1232
|
/**
|
|
1233
1233
|
* @license
|
|
1234
1234
|
* Copyright 2020 Google LLC. All Rights Reserved.
|
|
@@ -1244,7 +1244,7 @@ function(e,t,n,i,a,s){null==s&&(s=.001);const r=fn(e,"x","batchNorm"),o=fn(t,"me
|
|
|
1244
1244
|
* See the License for the specific language governing permissions and
|
|
1245
1245
|
* limitations under the License.
|
|
1246
1246
|
* =============================================================================
|
|
1247
|
-
*/const
|
|
1247
|
+
*/const Ca=vn({elu_:function(e){const t={x:fn(e,"x","elu","float32")};return cn.runKernel(we,t)}});
|
|
1248
1248
|
/**
|
|
1249
1249
|
* @license
|
|
1250
1250
|
* Copyright 2018 Google LLC. All Rights Reserved.
|
|
@@ -1260,7 +1260,7 @@ function(e,t,n,i,a,s){null==s&&(s=.001);const r=fn(e,"x","batchNorm"),o=fn(t,"me
|
|
|
1260
1260
|
* See the License for the specific language governing permissions and
|
|
1261
1261
|
* limitations under the License.
|
|
1262
1262
|
* =============================================================================
|
|
1263
|
-
*/const
|
|
1263
|
+
*/const Aa=vn({erf_:function(e){let t=fn(e,"x","erf");T("int32"===t.dtype||"float32"===t.dtype,(()=>"Input dtype must be `int32` or `float32`.")),"int32"===t.dtype&&(t=hi(t,"float32"));const n={x:t};return cn.runKernel("Erf",n)}});
|
|
1264
1264
|
/**
|
|
1265
1265
|
* @license
|
|
1266
1266
|
* Copyright 2017 Google LLC. All Rights Reserved.
|
|
@@ -1549,7 +1549,7 @@ function(e,t=null,n=!1){const i={x:fn(e,"x","max")},a={reductionIndices:t,keepDi
|
|
|
1549
1549
|
* See the License for the specific language governing permissions and
|
|
1550
1550
|
* limitations under the License.
|
|
1551
1551
|
* =============================================================================
|
|
1552
|
-
*/const Qa=vn({leakyRelu_:function(e,t=.2){const n={x:fn(e,"x","leakyRelu")},i={alpha:t};return cn.runKernel(
|
|
1552
|
+
*/const Qa=vn({leakyRelu_:function(e,t=.2){const n={x:fn(e,"x","leakyRelu")},i={alpha:t};return cn.runKernel(Ce,n,i)}});
|
|
1553
1553
|
/**
|
|
1554
1554
|
* @license
|
|
1555
1555
|
* Copyright 2020 Google LLC. All Rights Reserved.
|
|
@@ -1613,7 +1613,7 @@ function(e,t=null,n=!1){const i={x:fn(e,"x","max")},a={reductionIndices:t,keepDi
|
|
|
1613
1613
|
* See the License for the specific language governing permissions and
|
|
1614
1614
|
* limitations under the License.
|
|
1615
1615
|
* =============================================================================
|
|
1616
|
-
*/const ns=vn({log1p_:function(e){const t={x:fn(e,"x","log1p")};return cn.runKernel(
|
|
1616
|
+
*/const ns=vn({log1p_:function(e){const t={x:fn(e,"x","log1p")};return cn.runKernel(Ae,t)}});
|
|
1617
1617
|
/**
|
|
1618
1618
|
* @license
|
|
1619
1619
|
* Copyright 2018 Google LLC. All Rights Reserved.
|
|
@@ -1693,7 +1693,7 @@ function(e,t=null,n=!1){const i={x:fn(e,"x","max")},a={reductionIndices:t,keepDi
|
|
|
1693
1693
|
* See the License for the specific language governing permissions and
|
|
1694
1694
|
* limitations under the License.
|
|
1695
1695
|
* =============================================================================
|
|
1696
|
-
*/const os=vn({logSumExp_:function(e,t=null,n=!1){const i=fn(e,"x","logSumExp"),a=z(t,i.shape),s=_a(i,a,!0),r=ss(i,s),o=Ga(r),l=Ba(o,a),c=ts(l),u
|
|
1696
|
+
*/const os=vn({logSumExp_:function(e,t=null,n=!1){const i=fn(e,"x","logSumExp"),a=z(t,i.shape),s=_a(i,a,!0),r=ss(i,s),o=Ga(r),l=Ba(o,a),c=ts(l),u=$i(Wi(s,c.shape),c);if(n){const e=za(u.shape,a);return Wi(u,e)}return u}});
|
|
1697
1697
|
/**
|
|
1698
1698
|
* @license
|
|
1699
1699
|
* Copyright 2020 Google LLC. All Rights Reserved.
|
|
@@ -1805,7 +1805,7 @@ function(e,t=null,n=!1){const i={x:fn(e,"x","max")},a={reductionIndices:t,keepDi
|
|
|
1805
1805
|
* See the License for the specific language governing permissions and
|
|
1806
1806
|
* limitations under the License.
|
|
1807
1807
|
* =============================================================================
|
|
1808
|
-
*/function ms(e,t="float32"){if(V(e),"complex64"===t){const t=ms(e,"float32"),n=ms(e,"float32");return yn(t,n)}const n=G(
|
|
1808
|
+
*/function ms(e,t="float32"){if(V(e),"complex64"===t){const t=ms(e,"float32"),n=ms(e,"float32");return yn(t,n)}const n=G(C(e),t);return cn.makeTensor(n,e,t)}
|
|
1809
1809
|
/**
|
|
1810
1810
|
* @license
|
|
1811
1811
|
* Copyright 2018 Google LLC. All Rights Reserved.
|
|
@@ -1821,7 +1821,7 @@ function(e,t=null,n=!1){const i={x:fn(e,"x","max")},a={reductionIndices:t,keepDi
|
|
|
1821
1821
|
* See the License for the specific language governing permissions and
|
|
1822
1822
|
* limitations under the License.
|
|
1823
1823
|
* =============================================================================
|
|
1824
|
-
*/function fs(e,t="float32"){if(V(e),"complex64"===t){const t=fs(e,"float32"),n=ms(e,"float32");return yn(t,n)}const n=W(
|
|
1824
|
+
*/function fs(e,t="float32"){if(V(e),"complex64"===t){const t=fs(e,"float32"),n=ms(e,"float32");return yn(t,n)}const n=W(C(e),t);return cn.makeTensor(n,e,t)}
|
|
1825
1825
|
/**
|
|
1826
1826
|
* @license
|
|
1827
1827
|
* Copyright 2020 Google LLC. All Rights Reserved.
|
|
@@ -1949,7 +1949,7 @@ function(e,t=null,n=!1){const i={x:fn(e,"x","max")},a={reductionIndices:t,keepDi
|
|
|
1949
1949
|
* See the License for the specific language governing permissions and
|
|
1950
1950
|
* limitations under the License.
|
|
1951
1951
|
* =============================================================================
|
|
1952
|
-
*/var Ss="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function Ns(e,t,n){return e(n={path:t,exports:{},require:function(e,t){return function(){throw new Error("Dynamic requires are not currently supported by @rollup/plugin-commonjs")}(null==t&&n.path)}},n.exports),n.exports}var Ts=Ns((function(e){!function(e,t,n){function i(e){var t=this,n=function(){var e=4022871197,t=function(t){t=String(t);for(var n=0;n<t.length;n++){var i=.02519603282416938*(e+=t.charCodeAt(n));i-=e=i>>>0,e=(i*=e)>>>0,e+=4294967296*(i-=e)}return 2.3283064365386963e-10*(e>>>0)};return t}();t.next=function(){var e=2091639*t.s0+2.3283064365386963e-10*t.c;return t.s0=t.s1,t.s1=t.s2,t.s2=e-(t.c=0|e)},t.c=1,t.s0=n(" "),t.s1=n(" "),t.s2=n(" "),t.s0-=n(e),t.s0<0&&(t.s0+=1),t.s1-=n(e),t.s1<0&&(t.s1+=1),t.s2-=n(e),t.s2<0&&(t.s2+=1),n=null}function a(e,t){return t.c=e.c,t.s0=e.s0,t.s1=e.s1,t.s2=e.s2,t}function s(e,t){var n=new i(e),s=t&&t.state,r=n.next;return r.int32=function(){return 4294967296*n.next()|0},r.double=function(){return r()+11102230246251565e-32*(2097152*r()|0)},r.quick=r,s&&("object"==typeof s&&a(s,n),r.state=function(){return a(n,{})}),r}t&&t.exports?t.exports=s:n&&n.amd?n((function(){return s})):this.alea=s}(0,e,!1)})),Is=Ns((function(e){!function(e,t,n){function i(e){var t=this,n="";t.x=0,t.y=0,t.z=0,t.w=0,t.next=function(){var e=t.x^t.x<<11;return t.x=t.y,t.y=t.z,t.z=t.w,t.w^=t.w>>>19^e^e>>>8},e===(0|e)?t.x=e:n+=e;for(var i=0;i<n.length+64;i++)t.x^=0|n.charCodeAt(i),t.next()}function a(e,t){return t.x=e.x,t.y=e.y,t.z=e.z,t.w=e.w,t}function s(e,t){var n=new i(e),s=t&&t.state,r=function(){return(n.next()>>>0)/4294967296};return r.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},r.int32=n.next,r.quick=r,s&&("object"==typeof s&&a(s,n),r.state=function(){return a(n,{})}),r}t&&t.exports?t.exports=s:n&&n.amd?n((function(){return s})):this.xor128=s}(0,e,!1)}))
|
|
1952
|
+
*/var Ss="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function Ns(e,t,n){return e(n={path:t,exports:{},require:function(e,t){return function(){throw new Error("Dynamic requires are not currently supported by @rollup/plugin-commonjs")}(null==t&&n.path)}},n.exports),n.exports}var Ts=Ns((function(e){!function(e,t,n){function i(e){var t=this,n=function(){var e=4022871197,t=function(t){t=String(t);for(var n=0;n<t.length;n++){var i=.02519603282416938*(e+=t.charCodeAt(n));i-=e=i>>>0,e=(i*=e)>>>0,e+=4294967296*(i-=e)}return 2.3283064365386963e-10*(e>>>0)};return t}();t.next=function(){var e=2091639*t.s0+2.3283064365386963e-10*t.c;return t.s0=t.s1,t.s1=t.s2,t.s2=e-(t.c=0|e)},t.c=1,t.s0=n(" "),t.s1=n(" "),t.s2=n(" "),t.s0-=n(e),t.s0<0&&(t.s0+=1),t.s1-=n(e),t.s1<0&&(t.s1+=1),t.s2-=n(e),t.s2<0&&(t.s2+=1),n=null}function a(e,t){return t.c=e.c,t.s0=e.s0,t.s1=e.s1,t.s2=e.s2,t}function s(e,t){var n=new i(e),s=t&&t.state,r=n.next;return r.int32=function(){return 4294967296*n.next()|0},r.double=function(){return r()+11102230246251565e-32*(2097152*r()|0)},r.quick=r,s&&("object"==typeof s&&a(s,n),r.state=function(){return a(n,{})}),r}t&&t.exports?t.exports=s:n&&n.amd?n((function(){return s})):this.alea=s}(0,e,!1)})),Is=Ns((function(e){!function(e,t,n){function i(e){var t=this,n="";t.x=0,t.y=0,t.z=0,t.w=0,t.next=function(){var e=t.x^t.x<<11;return t.x=t.y,t.y=t.z,t.z=t.w,t.w^=t.w>>>19^e^e>>>8},e===(0|e)?t.x=e:n+=e;for(var i=0;i<n.length+64;i++)t.x^=0|n.charCodeAt(i),t.next()}function a(e,t){return t.x=e.x,t.y=e.y,t.z=e.z,t.w=e.w,t}function s(e,t){var n=new i(e),s=t&&t.state,r=function(){return(n.next()>>>0)/4294967296};return r.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},r.int32=n.next,r.quick=r,s&&("object"==typeof s&&a(s,n),r.state=function(){return a(n,{})}),r}t&&t.exports?t.exports=s:n&&n.amd?n((function(){return s})):this.xor128=s}(0,e,!1)})),$s=Ns((function(e){!function(e,t,n){function i(e){var t=this,n="";t.next=function(){var e=t.x^t.x>>>2;return t.x=t.y,t.y=t.z,t.z=t.w,t.w=t.v,(t.d=t.d+362437|0)+(t.v=t.v^t.v<<4^e^e<<1)|0},t.x=0,t.y=0,t.z=0,t.w=0,t.v=0,e===(0|e)?t.x=e:n+=e;for(var i=0;i<n.length+64;i++)t.x^=0|n.charCodeAt(i),i==n.length&&(t.d=t.x<<10^t.x>>>4),t.next()}function a(e,t){return t.x=e.x,t.y=e.y,t.z=e.z,t.w=e.w,t.v=e.v,t.d=e.d,t}function s(e,t){var n=new i(e),s=t&&t.state,r=function(){return(n.next()>>>0)/4294967296};return r.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},r.int32=n.next,r.quick=r,s&&("object"==typeof s&&a(s,n),r.state=function(){return a(n,{})}),r}t&&t.exports?t.exports=s:n&&n.amd?n((function(){return s})):this.xorwow=s}(0,e,!1)})),Cs=Ns((function(e){!function(e,t,n){function i(e){var t=this;t.next=function(){var e,n,i=t.x,a=t.i;return e=i[a],n=(e^=e>>>7)^e<<24,n^=(e=i[a+1&7])^e>>>10,n^=(e=i[a+3&7])^e>>>3,n^=(e=i[a+4&7])^e<<7,e=i[a+7&7],n^=(e^=e<<13)^e<<9,i[a]=n,t.i=a+1&7,n},function(e,t){var n,i=[];if(t===(0|t))i[0]=t;else for(t=""+t,n=0;n<t.length;++n)i[7&n]=i[7&n]<<15^t.charCodeAt(n)+i[n+1&7]<<13;for(;i.length<8;)i.push(0);for(n=0;n<8&&0===i[n];++n);for(8==n?i[7]=-1:i[n],e.x=i,e.i=0,n=256;n>0;--n)e.next()}(t,e)}function a(e,t){return t.x=e.x.slice(),t.i=e.i,t}function s(e,t){null==e&&(e=+new Date);var n=new i(e),s=t&&t.state,r=function(){return(n.next()>>>0)/4294967296};return r.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},r.int32=n.next,r.quick=r,s&&(s.x&&a(s,n),r.state=function(){return a(n,{})}),r}t&&t.exports?t.exports=s:n&&n.amd?n((function(){return s})):this.xorshift7=s}(0,e,!1)})),As=Ns((function(e){!function(e,t,n){function i(e){var t=this;t.next=function(){var e,n,i=t.w,a=t.X,s=t.i;return t.w=i=i+1640531527|0,n=a[s+34&127],e=a[s=s+1&127],n^=n<<13,e^=e<<17,n^=n>>>15,e^=e>>>12,n=a[s]=n^e,t.i=s,n+(i^i>>>16)|0},function(e,t){var n,i,a,s,r,o=[],l=128;for(t===(0|t)?(i=t,t=null):(t+="\0",i=0,l=Math.max(l,t.length)),a=0,s=-32;s<l;++s)t&&(i^=t.charCodeAt((s+32)%t.length)),0===s&&(r=i),i^=i<<10,i^=i>>>15,i^=i<<4,i^=i>>>13,s>=0&&(r=r+1640531527|0,a=0==(n=o[127&s]^=i+r)?a+1:0);for(a>=128&&(o[127&(t&&t.length||0)]=-1),a=127,s=512;s>0;--s)i=o[a+34&127],n=o[a=a+1&127],i^=i<<13,n^=n<<17,i^=i>>>15,n^=n>>>12,o[a]=i^n;e.w=r,e.X=o,e.i=a}(t,e)}function a(e,t){return t.i=e.i,t.w=e.w,t.X=e.X.slice(),t}function s(e,t){null==e&&(e=+new Date);var n=new i(e),s=t&&t.state,r=function(){return(n.next()>>>0)/4294967296};return r.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},r.int32=n.next,r.quick=r,s&&(s.X&&a(s,n),r.state=function(){return a(n,{})}),r}t&&t.exports?t.exports=s:n&&n.amd?n((function(){return s})):this.xor4096=s}(0,e,!1)})),Es=Ns((function(e){!function(e,t,n){function i(e){var t=this,n="";t.next=function(){var e=t.b,n=t.c,i=t.d,a=t.a;return e=e<<25^e>>>7^n,n=n-i|0,i=i<<24^i>>>8^a,a=a-e|0,t.b=e=e<<20^e>>>12^n,t.c=n=n-i|0,t.d=i<<16^n>>>16^a,t.a=a-e|0},t.a=0,t.b=0,t.c=-1640531527,t.d=1367130551,e===Math.floor(e)?(t.a=e/4294967296|0,t.b=0|e):n+=e;for(var i=0;i<n.length+20;i++)t.b^=0|n.charCodeAt(i),t.next()}function a(e,t){return t.a=e.a,t.b=e.b,t.c=e.c,t.d=e.d,t}function s(e,t){var n=new i(e),s=t&&t.state,r=function(){return(n.next()>>>0)/4294967296};return r.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},r.int32=n.next,r.quick=r,s&&("object"==typeof s&&a(s,n),r.state=function(){return a(n,{})}),r}t&&t.exports?t.exports=s:n&&n.amd?n((function(){return s})):this.tychei=s}(0,e,!1)})),js=Ns((function(e){!function(t,n,a){var s,r=256,o="random",l=a.pow(r,6),c=a.pow(2,52),u=2*c,h=255;function p(e,i,h){var p=[],y=g(f((i=1==i?{entropy:!0}:i||{}).entropy?[e,v(n)]:null==e?function(){try{var e;return s&&(e=s.randomBytes)?e=e(r):(e=new Uint8Array(r),(t.crypto||t.msCrypto).getRandomValues(e)),v(e)}catch(e){var i=t.navigator,a=i&&i.plugins;return[+new Date,t,a,t.screen,v(n)]}}():e,3),p),b=new d(p),w=function(){for(var e=b.g(6),t=l,n=0;e<c;)e=(e+n)*r,t*=r,n=b.g(1);for(;e>=u;)e/=2,t/=2,n>>>=1;return(e+n)/t};return w.int32=function(){return 0|b.g(4)},w.quick=function(){return b.g(4)/4294967296},w.double=w,g(v(b.S),n),(i.pass||h||function(e,t,n,i){return i&&(i.S&&m(i,b),e.state=function(){return m(b,{})}),n?(a[o]=e,t):e})(w,y,"global"in i?i.global:this==a,i.state)}function d(e){var t,n=e.length,i=this,a=0,s=i.i=i.j=0,o=i.S=[];for(n||(e=[n++]);a<r;)o[a]=a++;for(a=0;a<r;a++)o[a]=o[s=h&s+e[a%n]+(t=o[a])],o[s]=t;(i.g=function(e){for(var t,n=0,a=i.i,s=i.j,o=i.S;e--;)t=o[a=h&a+1],n=n*r+o[h&(o[a]=o[s=h&s+t])+(o[s]=t)];return i.i=a,i.j=s,n})(r)}function m(e,t){return t.i=e.i,t.j=e.j,t.S=e.S.slice(),t}function f(e,t){var n,i=[],a=typeof e;if(t&&"object"==a)for(n in e)try{i.push(f(e[n],t-1))}catch(e){}return i.length?i:"string"==a?e:e+"\0"}function g(e,t){for(var n,i=e+"",a=0;a<i.length;)t[h&a]=h&(n^=19*t[h&a])+i.charCodeAt(a++);return v(t)}function v(e){return String.fromCharCode.apply(0,e)}if(g(a.random(),n),e.exports){e.exports=p;try{s=i.default}catch(e){}}else a["seed"+o]=p}("undefined"!=typeof self?self:Ss,[],Math)}));js.alea=Ts,js.xor128=Is,js.xorwow=$s,js.xorshift7=Cs,js.xor4096=As,js.tychei=Es;var zs=js;
|
|
1953
1953
|
/**
|
|
1954
1954
|
* @license
|
|
1955
1955
|
* Copyright 2018 Google LLC. All Rights Reserved.
|
|
@@ -2335,7 +2335,7 @@ function(e,t){const n=fn(e,"x","squeeze","string_or_numeric");return Wi(n,functi
|
|
|
2335
2335
|
* See the License for the specific language governing permissions and
|
|
2336
2336
|
* limitations under the License.
|
|
2337
2337
|
* =============================================================================
|
|
2338
|
-
*/function nr(e,t){
|
|
2338
|
+
*/function nr(e,t){$(e);const n=pn(e,t);if(1!==n.length)throw new Error("tensor1d() requires values to be a flat/TypedArray");return bn(e,null,n,t)}
|
|
2339
2339
|
/**
|
|
2340
2340
|
* @license
|
|
2341
2341
|
* Copyright 2018 Google LLC. All Rights Reserved.
|
|
@@ -2351,7 +2351,7 @@ function(e,t){const n=fn(e,"x","squeeze","string_or_numeric");return Wi(n,functi
|
|
|
2351
2351
|
* See the License for the specific language governing permissions and
|
|
2352
2352
|
* limitations under the License.
|
|
2353
2353
|
* =============================================================================
|
|
2354
|
-
*/function ir(e,t,n){if(
|
|
2354
|
+
*/function ir(e,t,n){if($(e),null!=t&&2!==t.length)throw new Error("tensor2d() requires shape to have two numbers");const i=pn(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 bn(e,t,i,n)}
|
|
2355
2355
|
/**
|
|
2356
2356
|
* @license
|
|
2357
2357
|
* Copyright 2020 Google LLC. All Rights Reserved.
|
|
@@ -2449,7 +2449,7 @@ function(e,t,n,i){const a=fn(e,"x","dropout");if(T("float32"===a.dtype,(()=>`x h
|
|
|
2449
2449
|
* limitations under the License.
|
|
2450
2450
|
* =============================================================================
|
|
2451
2451
|
*/
|
|
2452
|
-
function(e,t){if(null==t)return e.shape.slice();if(
|
|
2452
|
+
function(e,t){if(null==t)return e.shape.slice();if(A(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=Ai(Ha($i(Rs(s,0,1,"float32",i),r)),r);return Ei(a,o)}});
|
|
2453
2453
|
/**
|
|
2454
2454
|
* @license
|
|
2455
2455
|
* Copyright 2019 Google LLC. All Rights Reserved.
|
|
@@ -2498,7 +2498,7 @@ function(e,t,n,i,a,s="NHWC",r){let o=e;3===e.rank&&(o=Wi(e,[1,e.shape[0],e.shape
|
|
|
2498
2498
|
* See the License for the specific language governing permissions and
|
|
2499
2499
|
* limitations under the License.
|
|
2500
2500
|
* =============================================================================
|
|
2501
|
-
*/function cr(e,t,n){if(null==n||"linear"===n)return e;if("relu"===n)return Ei(e,tr(t));throw new Error(`Cannot compute gradient for fused activation ${n}.`)}function ur(e,t){let n=t;const i=bi(e.shape,t.shape);return i.length>0&&(n=Ba(n,i)),Wi(n,e.shape)}function hr(e,t,n,i){if("linear"===t)return e;if("relu"===t)return Ms(e);if("elu"===t)return
|
|
2501
|
+
*/function cr(e,t,n){if(null==n||"linear"===n)return e;if("relu"===n)return Ei(e,tr(t));throw new Error(`Cannot compute gradient for fused activation ${n}.`)}function ur(e,t){let n=t;const i=bi(e.shape,t.shape);return i.length>0&&(n=Ba(n,i)),Wi(n,e.shape)}function hr(e,t,n,i){if("linear"===t)return e;if("relu"===t)return Ms(e);if("elu"===t)return Ca(e);if("relu6"===t)return Os(e);if("prelu"===t)return xs(e,n);if("leakyrelu"===t)return Qa(e,i);if("sigmoid"===t)return Hi(e);throw new Error(`Unknown fused activation ${t}.`)}const pr=(e,t)=>!(e>0)||"linear"===t;
|
|
2502
2502
|
/**
|
|
2503
2503
|
* @license
|
|
2504
2504
|
* Copyright 2019 Google LLC. All Rights Reserved.
|
|
@@ -2514,7 +2514,7 @@ function(e,t,n,i,a,s="NHWC",r){let o=e;3===e.rank&&(o=Wi(e,[1,e.shape[0],e.shape
|
|
|
2514
2514
|
* See the License for the specific language governing permissions and
|
|
2515
2515
|
* limitations under the License.
|
|
2516
2516
|
* =============================================================================
|
|
2517
|
-
*/const dr=vn({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===pr(cn.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=ha(e,t,n,i,a,s,r);return null!=o&&(h
|
|
2517
|
+
*/const dr=vn({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===pr(cn.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=ha(e,t,n,i,a,s,r);return null!=o&&(h=$i(h,o)),hr(h,l,c,u)}const h=fn(e,"x","conv2d","float32"),p=fn(t,"filter","conv2d","float32");let d=h,m=!1;3===h.rank&&(m=!0,d=Wi(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}.`)),Ui("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(Pi(n,s),(()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${s}'`));const g=_i(d.shape,p.shape,n,s,i,r);let v,y;if(null!=o&&(v=fn(o,"bias","fused conv2d"),[v]=tn(v,h),"NHWC"===a?wi(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{wi(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=fn(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=cr(e,c,l);T(Oi(s),(()=>`Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${s}'`));const p=[da(o.shape,h,r,n,i),lr(o,h,r.shape,n,i)];if(null!=u){const e=ur(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=is(((e,t,n)=>{let i=cn.runKernel(ft,w,k);return n([t,e,i]),m&&(i=Wi(i,[i.shape[1],i.shape[2],i.shape[3]])),{value:i,gradFunc:b}}));return e(d,p)}{const e=is(((e,t,n,i)=>{let a=cn.runKernel(ft,w,k);return i([t,e,a,n]),m&&(a=Wi(a,[a.shape[1],a.shape[2],a.shape[3]])),{value:a,gradFunc:b}}));return e(d,p,v)}}});
|
|
2518
2518
|
/**
|
|
2519
2519
|
* @license
|
|
2520
2520
|
* Copyright 2020 Google LLC. All Rights Reserved.
|
|
@@ -2562,7 +2562,7 @@ function(e,t,n,i,a,s="NHWC",r){let o=e;3===e.rank&&(o=Wi(e,[1,e.shape[0],e.shape
|
|
|
2562
2562
|
* See the License for the specific language governing permissions and
|
|
2563
2563
|
* limitations under the License.
|
|
2564
2564
|
* =============================================================================
|
|
2565
|
-
*/const gr=vn({fusedMatMul_:function({a:e,b:t,transposeA:n=!1,transposeB:i=!1,bias:a,activation:s="linear",preluActivationWeights:r,leakyreluAlpha:o=.2}){if(!1===pr(cn.state.gradientDepth,s)){let l=pi(e,t,n,i);return null!=a&&(l
|
|
2565
|
+
*/const gr=vn({fusedMatMul_:function({a:e,b:t,transposeA:n=!1,transposeB:i=!1,bias:a,activation:s="linear",preluActivationWeights:r,leakyreluAlpha:o=.2}){if(!1===pr(cn.state.gradientDepth,s)){let l=pi(e,t,n,i);return null!=a&&(l=$i(l,a)),hr(l,s,r,o)}let l=fn(e,"a","fused matMul"),c=fn(t,"b","fused matMul");[l,c]=tn(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=wi(l.shape.slice(0,-2),c.shape.slice(0,-2)).concat([p,d]),b=Wi(l,n?[g,u,p]:[g,p,u]),w=Wi(c,i?[v,d,h]:[v,h,d]);let k,x;null!=a&&(k=fn(a,"bias","fused matMul"),[k]=tn(k,l),wi(y,k.shape)),null!=r&&(x=fn(r,"prelu weights","fused matMul"));const S=(e,t)=>{const[r,o,l,c]=t,u=cr(Wi(e,l.shape),l,s);let h,p;if(n||i?!n&&i?(h=pi(u,o,!1,!1),p=pi(u,r,!0,!1)):n&&!i?(h=pi(o,u,!1,!0),p=pi(r,u,!1,!1)):(h=pi(o,u,!0,!0),p=pi(u,r,!0,!0)):(h=pi(u,o,!1,!0),p=pi(r,u,!0,!1)),null!=a){return[h,p,ur(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=is(((e,t,n)=>{const i=cn.runKernel(mt,N,I);return n([e,t,i]),{value:Wi(i,y),gradFunc:S}}));return e(b,w)}{const e=is(((e,t,n,i)=>{const a=cn.runKernel(mt,N,I);return i([e,t,a,n]),{value:Wi(a,y),gradFunc:S}}));return e(b,w,k)}}});
|
|
2566
2566
|
/**
|
|
2567
2567
|
* @license
|
|
2568
2568
|
* Copyright 2019 Google LLC. All Rights Reserved.
|
|
@@ -2643,7 +2643,7 @@ function(e,t,n,i,a="bilinear",s=0){const r=fn(e,"image","cropAndResize"),o=fn(t,
|
|
|
2643
2643
|
* See the License for the specific language governing permissions and
|
|
2644
2644
|
* limitations under the License.
|
|
2645
2645
|
* =============================================================================
|
|
2646
|
-
*/const wr=vn({rgbToGrayscale_:function(e){const t=fn(e,"image","RGBToGrayscale"),n=t.rank-1,i=t.shape[n];T(t.rank>=2,(()=>`Error in RGBToGrayscale: images must be at least rank 2, but got rank ${t.rank}.`)),T(3===i,(()=>`Error in RGBToGrayscale: last dimension of an RGB image should be size 3, but got size ${i}.`));const a=t.dtype,s=hi(t,"float32"),r=nr([.2989,.587,.114]);let o;switch(t.rank){case 2:o
|
|
2646
|
+
*/const wr=vn({rgbToGrayscale_:function(e){const t=fn(e,"image","RGBToGrayscale"),n=t.rank-1,i=t.shape[n];T(t.rank>=2,(()=>`Error in RGBToGrayscale: images must be at least rank 2, but got rank ${t.rank}.`)),T(3===i,(()=>`Error in RGBToGrayscale: last dimension of an RGB image should be size 3, but got size ${i}.`));const a=t.dtype,s=hi(t,"float32"),r=nr([.2989,.587,.114]);let o;switch(t.rank){case 2:o=$a("ij,j->i",s,r);break;case 3:o=$a("ijk,k->ij",s,r);break;case 4:o=$a("ijkl,l->ijk",s,r);break;case 5:o=$a("ijklm,m->ijkl",s,r);break;case 6:o=$a("ijklmn,n->ijklm",s,r);break;default:throw new Error("Not a valid tensor rank.")}return o=Va(o,-1),hi(o,a)}});
|
|
2647
2647
|
/**
|
|
2648
2648
|
* @license
|
|
2649
2649
|
* Copyright 2020 Google LLC. All Rights Reserved.
|
|
@@ -2723,7 +2723,7 @@ function(e,t,n,i,a="bilinear",s=0){const r=fn(e,"image","cropAndResize"),o=fn(t,
|
|
|
2723
2723
|
* See the License for the specific language governing permissions and
|
|
2724
2724
|
* limitations under the License.
|
|
2725
2725
|
* =============================================================================
|
|
2726
|
-
*/(e,t,n||Tr)}(e,t,n),a=i<0?-(i+1):i;e.splice(a,0,t)}function Tr(e,t){return e>t?1:e<t?-1:0}function Ir(e,t,n,i,a,s,r=!1,o=!1,l=!1){const c=[];for(let e=0;e<t.length;e++)t[e]>a&&c.push({score:t[e],boxIndex:e,suppressBeginIndex:0});c.sort(
|
|
2726
|
+
*/(e,t,n||Tr)}(e,t,n),a=i<0?-(i+1):i;e.splice(a,0,t)}function Tr(e,t){return e>t?1:e<t?-1:0}function Ir(e,t,n,i,a,s,r=!1,o=!1,l=!1){const c=[];for(let e=0;e<t.length;e++)t[e]>a&&c.push({score:t[e],boxIndex:e,suppressBeginIndex:0});c.sort(Ar);const u=s>0?-.5/s:0,h=[],p=[];for(;h.length<n&&c.length>0;){const t=c.pop(),{score:n,boxIndex:s,suppressBeginIndex:r}=t;if(n<a)break;let o=!1;for(let n=h.length-1;n>=r;--n){const r=$r(e,s,h[n]);if(r>=i){o=!0;break}if(t.score=t.score*Cr(i,u,r),t.score<=a)break}t.suppressBeginIndex=h.length,o||(t.score===n?(h.push(s),p.push(t.score)):t.score>a&&Nr(c,t,Ar))}const d=h.length,m=n-d;o&&m>0&&(h.push(...new Array(m).fill(0)),p.push(...new Array(m).fill(0)));const f={selectedIndices:h};return r&&(f.selectedScores=p),l&&(f.validOutputs=d),f}function $r(e,t,n){const i=e.subarray(4*t,4*t+4),a=e.subarray(4*n,4*n+4),s=Math.min(i[0],i[2]),r=Math.min(i[1],i[3]),o=Math.max(i[0],i[2]),l=Math.max(i[1],i[3]),c=Math.min(a[0],a[2]),u=Math.min(a[1],a[3]),h=Math.max(a[0],a[2]),p=Math.max(a[1],a[3]),d=(o-s)*(l-r),m=(h-c)*(p-u);if(d<=0||m<=0)return 0;const f=Math.max(s,c),g=Math.max(r,u),v=Math.min(o,h),y=Math.min(l,p),b=Math.max(v-f,0)*Math.max(y-g,0);return b/(d+m-b)}function Cr(e,t,n){const i=Math.exp(t*n*n);return n<=e?i:0}function Ar(e,t){return e.score-t.score||e.score===t.score&&t.boxIndex-e.boxIndex}
|
|
2727
2727
|
/**
|
|
2728
2728
|
* @license
|
|
2729
2729
|
* Copyright 2020 Google LLC. All Rights Reserved.
|
|
@@ -2851,7 +2851,7 @@ function(e,t,n,i,a="bilinear",s=0){const r=fn(e,"image","cropAndResize"),o=fn(t,
|
|
|
2851
2851
|
* See the License for the specific language governing permissions and
|
|
2852
2852
|
* limitations under the License.
|
|
2853
2853
|
* =============================================================================
|
|
2854
|
-
*/const Lr=vn({threshold_:function(e,t="binary",n=!1,i=.5){const a=fn(e,"image","threshold"),s=a.shape[0]*a.shape[1];let r,o,l,c,u=Ei(nr([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]=Qs(a,[1,1,1],-1);const e=Ei(r,.2989),t=Ei(o,.587),n=Ei(l,.114);c
|
|
2854
|
+
*/const Lr=vn({threshold_:function(e,t="binary",n=!1,i=.5){const a=fn(e,"image","threshold"),s=a.shape[0]*a.shape[1];let r,o,l,c,u=Ei(nr([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]=Qs(a,[1,1,1],-1);const e=Ei(r,.2989),t=Ei(o,.587),n=Ei(l,.114);c=$i($i(e,t),n)}else c=e;if("otsu"===t){u=function(e,t){let n,i,a,s,r,o,l=nr([-1]),c=nr([0]),u=nr([0]);for(let h=0;h<e.size-1;h++){n=Ji(e,0,h+1),i=Ji(e,h+1),r=Ai(Ba(n),t),o=Ai(Ba(i),t);const p=Ba(Ei(n,Ls(0,n.size)));a=Ai(p,Ba(n));const d=sa(i.shape,n.size),m=$i(Ls(0,i.size),d),f=Ei(i,m);s=Ai(Ba(f),Ba(i));const g=ss(a,s),v=ss(a,s),y=Ei(r,o);u=Ei(Ei(y,g),v);const b=Za(u,c);c=Ta(b,u,c),l=Ta(b,nr([h]),l)}return l}(na(hi(Bs(c),"int32"),wn([]),256),s)}const h=n?es(c,u):Za(c,u);return hi(Ei(h,255),"int32")}});
|
|
2855
2855
|
/**
|
|
2856
2856
|
* @license
|
|
2857
2857
|
* Copyright 2021 Google LLC. All Rights Reserved.
|
|
@@ -2899,7 +2899,7 @@ function(e,t,n,i,a="bilinear",s=0){const r=fn(e,"image","cropAndResize"),o=fn(t,
|
|
|
2899
2899
|
* See the License for the specific language governing permissions and
|
|
2900
2900
|
* limitations under the License.
|
|
2901
2901
|
* =============================================================================
|
|
2902
|
-
*/const Pr=vn({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=Qs(e,e.shape[0],0).map((e=>Xs(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(cn.tidy((()=>{let e=i[t];if(t>0)for(let i=0;i<t;++i){const t=Ei(Ba(Ei(n[i],e)),n[i]);e=ss(e,t)}return
|
|
2902
|
+
*/const Pr=vn({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=Qs(e,e.shape[0],0).map((e=>Xs(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(cn.tidy((()=>{let e=i[t];if(t>0)for(let i=0;i<t;++i){const t=Ei(Ba(Ei(n[i],e)),n[i]);e=ss(e,t)}return Ai(e,Wa(e,"euclidean"))})));return t?er(n,0):n}});
|
|
2903
2903
|
/**
|
|
2904
2904
|
* @license
|
|
2905
2905
|
* Copyright 2020 Google LLC. All Rights Reserved.
|
|
@@ -2915,7 +2915,7 @@ function(e,t,n,i,a="bilinear",s=0){const r=fn(e,"image","cropAndResize"),o=fn(t,
|
|
|
2915
2915
|
* See the License for the specific language governing permissions and
|
|
2916
2916
|
* limitations under the License.
|
|
2917
2917
|
* =============================================================================
|
|
2918
|
-
*/function Br(e,t=!1){return cn.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=qa(n),s=Ki(e);const r=ir([[1]],[1,1]);let o=Ki(r);const l=n>=i?i:n;for(let e=0;e<l;++e){const t=s,l=o,c=a;[o,s,a]=cn.tidy((()=>{const t=Ji(s,[e,e],[n-e,1]),l=Wa(t),c=Ji(s,[e,e],[1,1]),u=Ta(Za(c,0),ir([[-1]]),ir([[1]])),h=ss(c,Ei(u,l)),p
|
|
2918
|
+
*/function Br(e,t=!1){return cn.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=qa(n),s=Ki(e);const r=ir([[1]],[1,1]);let o=Ki(r);const l=n>=i?i:n;for(let e=0;e<l;++e){const t=s,l=o,c=a;[o,s,a]=cn.tidy((()=>{const t=Ji(s,[e,e],[n-e,1]),l=Wa(t),c=Ji(s,[e,e],[1,1]),u=Ta(Za(c,0),ir([[-1]]),ir([[1]])),h=ss(c,Ei(u,l)),p=Ai(t,h);o=1===p.shape[0]?Ki(r):qi([r,Ji(p,[1,0],[p.shape[0]-1,p.shape[1]])],0);const d=fi(Ai(pi(u,h),l)),m=Ji(s,[e,0],[n-e,i]),f=Ei(d,o),g=vi(o);if(0===e)s=ss(m,pi(f,pi(g,m)));else{const t=ss(m,pi(f,pi(g,m)));s=qi([Ji(s,[0,0],[e,i]),t],0)}const v=vi(f),y=Ji(a,[0,e],[n,a.shape[1]-e]);if(0===e)a=ss(y,pi(pi(y,o),v));else{const t=ss(y,pi(pi(y,o),v));a=qi([Ji(a,[0,0],[n,e]),t],1)}return[o,s,a]})),In([t,l,c])}return!t&&n>i&&(a=Ji(a,[0,0],[n,i]),s=Ji(s,[0,0],[i,i])),[a,s]}))}const Ur=vn({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 Br(e,t);{const n=e.shape.slice(0,e.shape.length-2).reduce(((e,t)=>e*t)),i=rr(Wi(e,[n,e.shape[e.shape.length-2],e.shape[e.shape.length-1]]),0),a=[],s=[];i.forEach((e=>{const[n,i]=Br(e,t);a.push(n),s.push(i)}));return[Wi(er(a,0),e.shape),Wi(er(s,0),e.shape)]}}});
|
|
2919
2919
|
/**
|
|
2920
2920
|
* @license
|
|
2921
2921
|
* Copyright 2020 Google LLC. All Rights Reserved.
|
|
@@ -2981,7 +2981,7 @@ class Kr extends Ni{minimize(e,t=!1,n){const{value:i,grads:a}=this.computeGradie
|
|
|
2981
2981
|
* limitations under the License.
|
|
2982
2982
|
* =============================================================================
|
|
2983
2983
|
*/
|
|
2984
|
-
class qr extends Kr{static get className(){return"Adadelta"}constructor(e,t,n=null){super(),this.learningRate=e,this.rho=t,this.epsilon=n,this.accumulatedGrads=[],this.accumulatedUpdates=[],null==n&&(this.epsilon=cn.backend.epsilon())}applyGradients(e){(Array.isArray(e)?e.map((e=>e.name)):Object.keys(e)).forEach(((t,n)=>{const i=cn.registeredVariables[t];null==this.accumulatedGrads[n]&&(this.accumulatedGrads[n]={originalName:`${t}/accum_grad`,variable:Tn((()=>Ia(i).variable(false)))}),null==this.accumulatedUpdates[n]&&(this.accumulatedUpdates[n]={originalName:`${t}/accum_var`,variable:Tn((()=>Ia(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;Tn((()=>{const e
|
|
2984
|
+
class qr extends Kr{static get className(){return"Adadelta"}constructor(e,t,n=null){super(),this.learningRate=e,this.rho=t,this.epsilon=n,this.accumulatedGrads=[],this.accumulatedUpdates=[],null==n&&(this.epsilon=cn.backend.epsilon())}applyGradients(e){(Array.isArray(e)?e.map((e=>e.name)):Object.keys(e)).forEach(((t,n)=>{const i=cn.registeredVariables[t];null==this.accumulatedGrads[n]&&(this.accumulatedGrads[n]={originalName:`${t}/accum_grad`,variable:Tn((()=>Ia(i).variable(false)))}),null==this.accumulatedUpdates[n]&&(this.accumulatedUpdates[n]={originalName:`${t}/accum_var`,variable:Tn((()=>Ia(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;Tn((()=>{const e=$i(Ei(s,this.rho),Ei(Pa(a),1-this.rho)),t=Ei(Ai(Oa($i(r,this.epsilon)),Oa($i(s,this.epsilon))),a),n=$i(Ei(r,this.rho),Ei(Pa(t),1-this.rho));s.assign(e),r.assign(n);const o=$i(Ei(t,-this.learningRate),i);i.assign(o)}))})),this.incrementIterations()}dispose(){null!=this.accumulatedUpdates&&(In(this.accumulatedGrads.map((e=>e.variable))),In(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)}}
|
|
2985
2985
|
/**
|
|
2986
2986
|
* @license
|
|
2987
2987
|
* Copyright 2018 Google LLC. All Rights Reserved.
|
|
@@ -2997,7 +2997,7 @@ class qr extends Kr{static get className(){return"Adadelta"}constructor(e,t,n=nu
|
|
|
2997
2997
|
* See the License for the specific language governing permissions and
|
|
2998
2998
|
* limitations under the License.
|
|
2999
2999
|
* =============================================================================
|
|
3000
|
-
*/class Hr extends Kr{static get className(){return"Adagrad"}constructor(e,t=.1){super(),this.learningRate=e,this.initialAccumulatorValue=t,this.accumulatedGrads=[]}applyGradients(e){(Array.isArray(e)?e.map((e=>e.name)):Object.keys(e)).forEach(((t,n)=>{const i=cn.registeredVariables[t];if(null==this.accumulatedGrads[n]){const e=!1;this.accumulatedGrads[n]={originalName:`${t}/accumulator`,variable:Tn((()=>sa(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;Tn((()=>{const e
|
|
3000
|
+
*/class Hr extends Kr{static get className(){return"Adagrad"}constructor(e,t=.1){super(),this.learningRate=e,this.initialAccumulatorValue=t,this.accumulatedGrads=[]}applyGradients(e){(Array.isArray(e)?e.map((e=>e.name)):Object.keys(e)).forEach(((t,n)=>{const i=cn.registeredVariables[t];if(null==this.accumulatedGrads[n]){const e=!1;this.accumulatedGrads[n]={originalName:`${t}/accumulator`,variable:Tn((()=>sa(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;Tn((()=>{const e=$i(s,Pa(a));s.assign(e);const t=$i(Ei(Ai(a,Oa($i(e,cn.backend.epsilon()))),-this.learningRate),i);i.assign(t)}))})),this.incrementIterations()}dispose(){null!=this.accumulatedGrads&&In(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)}}
|
|
3001
3001
|
/**
|
|
3002
3002
|
* @license
|
|
3003
3003
|
* Copyright 2018 Google LLC. All Rights Reserved.
|
|
@@ -3013,7 +3013,7 @@ class qr extends Kr{static get className(){return"Adadelta"}constructor(e,t,n=nu
|
|
|
3013
3013
|
* See the License for the specific language governing permissions and
|
|
3014
3014
|
* limitations under the License.
|
|
3015
3015
|
* =============================================================================
|
|
3016
|
-
*/class Jr extends Kr{static get className(){return"Adam"}constructor(e,t,n,i=null){super(),this.learningRate=e,this.beta1=t,this.beta2=n,this.epsilon=i,this.accumulatedFirstMoment=[],this.accumulatedSecondMoment=[],Tn((()=>{this.accBeta1=Ma(t).variable(),this.accBeta2=Ma(n).variable()})),null==i&&(this.epsilon=cn.backend.epsilon())}applyGradients(e){const t=Array.isArray(e)?e.map((e=>e.name)):Object.keys(e);Tn((()=>{const n=ss(1,this.accBeta1),i=ss(1,this.accBeta2);t.forEach(((t,a)=>{const s=cn.registeredVariables[t];null==this.accumulatedFirstMoment[a]&&(this.accumulatedFirstMoment[a]={originalName:`${t}/m`,variable:Tn((()=>Ia(s).variable(false)))}),null==this.accumulatedSecondMoment[a]&&(this.accumulatedSecondMoment[a]={originalName:`${t}/v`,variable:Tn((()=>Ia(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
|
|
3016
|
+
*/class Jr extends Kr{static get className(){return"Adam"}constructor(e,t,n,i=null){super(),this.learningRate=e,this.beta1=t,this.beta2=n,this.epsilon=i,this.accumulatedFirstMoment=[],this.accumulatedSecondMoment=[],Tn((()=>{this.accBeta1=Ma(t).variable(),this.accBeta2=Ma(n).variable()})),null==i&&(this.epsilon=cn.backend.epsilon())}applyGradients(e){const t=Array.isArray(e)?e.map((e=>e.name)):Object.keys(e);Tn((()=>{const n=ss(1,this.accBeta1),i=ss(1,this.accBeta2);t.forEach(((t,a)=>{const s=cn.registeredVariables[t];null==this.accumulatedFirstMoment[a]&&(this.accumulatedFirstMoment[a]={originalName:`${t}/m`,variable:Tn((()=>Ia(s).variable(false)))}),null==this.accumulatedSecondMoment[a]&&(this.accumulatedSecondMoment[a]={originalName:`${t}/v`,variable:Tn((()=>Ia(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=$i(Ei(o,this.beta1),Ei(r,1-this.beta1)),u=$i(Ei(l,this.beta2),Ei(Pa(r),1-this.beta2)),h=Ai(c,n),p=Ai(u,i);o.assign(c),l.assign(u);const d=$i(Ei(Ai(h,$i(Oa(p),this.epsilon)),-this.learningRate),s);s.assign(d)})),this.accBeta1.assign(Ei(this.accBeta1,this.beta1)),this.accBeta2.assign(Ei(this.accBeta2,this.beta2))})),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.accBeta2.dispose(),null!=this.accumulatedFirstMoment&&In(this.accumulatedFirstMoment.map((e=>e.variable))),null!=this.accumulatedSecondMoment&&In(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),Tn((()=>{this.accBeta1.assign(La(this.beta1,this.iterations_+1)),this.accBeta2.assign(La(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)}}
|
|
3017
3017
|
/**
|
|
3018
3018
|
* @license
|
|
3019
3019
|
* Copyright 2018 Google LLC. All Rights Reserved.
|
|
@@ -3029,7 +3029,7 @@ class qr extends Kr{static get className(){return"Adadelta"}constructor(e,t,n=nu
|
|
|
3029
3029
|
* See the License for the specific language governing permissions and
|
|
3030
3030
|
* limitations under the License.
|
|
3031
3031
|
* =============================================================================
|
|
3032
|
-
*/class Zr extends Kr{static get className(){return"Adamax"}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=[],Tn((()=>{this.iteration=Ma(0).variable(),this.accBeta1=Ma(t).variable()})),null==i&&(this.epsilon=cn.backend.epsilon())}applyGradients(e){const t=Array.isArray(e)?e.map((e=>e.name)):Object.keys(e);Tn((()=>{const n=ss(1,this.accBeta1),i
|
|
3032
|
+
*/class Zr extends Kr{static get className(){return"Adamax"}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=[],Tn((()=>{this.iteration=Ma(0).variable(),this.accBeta1=Ma(t).variable()})),null==i&&(this.epsilon=cn.backend.epsilon())}applyGradients(e){const t=Array.isArray(e)?e.map((e=>e.name)):Object.keys(e);Tn((()=>{const n=ss(1,this.accBeta1),i=Ai(-this.learningRate,$i(Ei(this.iteration,this.decay),1));t.forEach(((t,a)=>{const s=cn.registeredVariables[t];null==this.accumulatedFirstMoment[a]&&(this.accumulatedFirstMoment[a]={originalName:`${t}/m`,variable:Ia(s).variable(false)}),null==this.accumulatedWeightedInfNorm[a]&&(this.accumulatedWeightedInfNorm[a]={originalName:`${t}/v`,variable:Ia(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=$i(Ei(o,this.beta1),Ei(r,1-this.beta1)),u=Ei(l,this.beta2),h=ji(r),p=ps(u,h);o.assign(c),l.assign(p);const d=$i(Ei(Ai(i,n),Ai(c,$i(p,this.epsilon))),s);s.assign(d)})),this.iteration.assign($i(this.iteration,1)),this.accBeta1.assign(Ei(this.accBeta1,this.beta1))})),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.iteration.dispose(),null!=this.accumulatedFirstMoment&&In(this.accumulatedFirstMoment.map((e=>e.variable))),null!=this.accumulatedWeightedInfNorm&&In(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)}}
|
|
3033
3033
|
/**
|
|
3034
3034
|
* @license
|
|
3035
3035
|
* Copyright 2018 Google LLC. All Rights Reserved.
|
|
@@ -3045,7 +3045,7 @@ class qr extends Kr{static get className(){return"Adadelta"}constructor(e,t,n=nu
|
|
|
3045
3045
|
* See the License for the specific language governing permissions and
|
|
3046
3046
|
* limitations under the License.
|
|
3047
3047
|
* =============================================================================
|
|
3048
|
-
*/class Yr extends Kr{static get className(){return"SGD"}constructor(e){super(),this.learningRate=e,this.setLearningRate(e)}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=cn.registeredVariables[t];Tn((()=>{const e
|
|
3048
|
+
*/class Yr extends Kr{static get className(){return"SGD"}constructor(e){super(),this.learningRate=e,this.setLearningRate(e)}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=cn.registeredVariables[t];Tn((()=>{const e=$i(Ei(this.c,i),a);a.assign(e)}))})),this.incrementIterations()}setLearningRate(e){this.learningRate=e,null!=this.c&&this.c.dispose(),this.c=$n(Ma(-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)}}
|
|
3049
3049
|
/**
|
|
3050
3050
|
* @license
|
|
3051
3051
|
* Copyright 2018 Google LLC. All Rights Reserved.
|
|
@@ -3061,7 +3061,7 @@ class qr extends Kr{static get className(){return"Adadelta"}constructor(e,t,n=nu
|
|
|
3061
3061
|
* See the License for the specific language governing permissions and
|
|
3062
3062
|
* limitations under the License.
|
|
3063
3063
|
* =============================================================================
|
|
3064
|
-
*/class Qr extends Yr{static get className(){return"Momentum"}constructor(e,t,n=!1){super(e),this.learningRate=e,this.momentum=t,this.useNesterov=n,this.accumulations=[],this.m=Ma(this.momentum)}applyGradients(e){(Array.isArray(e)?e.map((e=>e.name)):Object.keys(e)).forEach(((t,n)=>{const i=cn.registeredVariables[t];if(null==this.accumulations[n]){const e=!1;this.accumulations[n]={originalName:`${t}/momentum`,variable:Tn((()=>Ia(i).variable(e)))}}const a=this.accumulations[n].variable,s=Array.isArray(e)?e[n].tensor:e[t];null!=s&&Tn((()=>{let e;const t
|
|
3064
|
+
*/class Qr extends Yr{static get className(){return"Momentum"}constructor(e,t,n=!1){super(e),this.learningRate=e,this.momentum=t,this.useNesterov=n,this.accumulations=[],this.m=Ma(this.momentum)}applyGradients(e){(Array.isArray(e)?e.map((e=>e.name)):Object.keys(e)).forEach(((t,n)=>{const i=cn.registeredVariables[t];if(null==this.accumulations[n]){const e=!1;this.accumulations[n]={originalName:`${t}/momentum`,variable:Tn((()=>Ia(i).variable(e)))}}const a=this.accumulations[n].variable,s=Array.isArray(e)?e[n].tensor:e[t];null!=s&&Tn((()=>{let e;const t=$i(Ei(this.m,a),s);e=this.useNesterov?$i(Ei(this.c,$i(s,Ei(t,this.m))),i):$i(Ei(this.c,t),i),a.assign(t),i.assign(e)}))})),this.incrementIterations()}dispose(){this.m.dispose(),null!=this.accumulations&&In(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)}}
|
|
3065
3065
|
/**
|
|
3066
3066
|
* @license
|
|
3067
3067
|
* Copyright 2018 Google LLC. All Rights Reserved.
|
|
@@ -3077,7 +3077,7 @@ class qr extends Kr{static get className(){return"Adadelta"}constructor(e,t,n=nu
|
|
|
3077
3077
|
* See the License for the specific language governing permissions and
|
|
3078
3078
|
* limitations under the License.
|
|
3079
3079
|
* =============================================================================
|
|
3080
|
-
*/class Xr extends Kr{static get className(){return"RMSProp"}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=cn.backend.epsilon()),null==e)throw new Error("learningRate for RMSPropOptimizer must be defined.")}applyGradients(e){(Array.isArray(e)?e.map((e=>e.name)):Object.keys(e)).forEach(((t,n)=>{const i=cn.registeredVariables[t],a=!1;null==this.accumulatedMeanSquares[n]&&(this.accumulatedMeanSquares[n]={originalName:`${t}/rms`,variable:Tn((()=>Ia(i).variable(a)))}),null==this.accumulatedMoments[n]&&(this.accumulatedMoments[n]={originalName:`${t}/momentum`,variable:Tn((()=>Ia(i).variable(a)))}),null==this.accumulatedMeanGrads[n]&&this.centered&&(this.accumulatedMeanGrads[n]={originalName:`${t}/mg`,variable:Tn((()=>Ia(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;Tn((()=>{const e
|
|
3080
|
+
*/class Xr extends Kr{static get className(){return"RMSProp"}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=cn.backend.epsilon()),null==e)throw new Error("learningRate for RMSPropOptimizer must be defined.")}applyGradients(e){(Array.isArray(e)?e.map((e=>e.name)):Object.keys(e)).forEach(((t,n)=>{const i=cn.registeredVariables[t],a=!1;null==this.accumulatedMeanSquares[n]&&(this.accumulatedMeanSquares[n]={originalName:`${t}/rms`,variable:Tn((()=>Ia(i).variable(a)))}),null==this.accumulatedMoments[n]&&(this.accumulatedMoments[n]={originalName:`${t}/momentum`,variable:Tn((()=>Ia(i).variable(a)))}),null==this.accumulatedMeanGrads[n]&&this.centered&&(this.accumulatedMeanGrads[n]={originalName:`${t}/mg`,variable:Tn((()=>Ia(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;Tn((()=>{const e=$i(Ei(r,this.decay),Ei(Pa(s),1-this.decay));if(this.centered){const t=this.accumulatedMeanGrads[n].variable,a=$i(Ei(t,this.decay),Ei(s,1-this.decay)),l=Ai(Ei(s,this.learningRate),Oa(ss(e,$i(Pa(a),this.epsilon)))),c=$i(Ei(o,this.momentum),l);r.assign(e),t.assign(a),o.assign(c);const u=ss(i,c);i.assign(u)}else{const e=$i(Ei(r,this.decay),Ei(Pa(s),1-this.decay)),t=$i(Ei(o,this.momentum),Ai(Ei(s,this.learningRate),Oa($i(e,this.epsilon))));r.assign(e),o.assign(t);const n=ss(i,t);i.assign(n)}}))})),this.incrementIterations()}dispose(){null!=this.accumulatedMeanSquares&&In(this.accumulatedMeanSquares.map((e=>e.variable))),null!=this.accumulatedMeanGrads&&this.centered&&In(this.accumulatedMeanGrads.map((e=>e.variable))),null!=this.accumulatedMoments&&In(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)}}
|
|
3081
3081
|
/**
|
|
3082
3082
|
* @license
|
|
3083
3083
|
* Copyright 2018 Google LLC. All Rights Reserved.
|
|
@@ -3192,7 +3192,7 @@ function io(e,t){if(e.length!==t.length)throw new Error(`Cannot merge real and i
|
|
|
3192
3192
|
* limitations under the License.
|
|
3193
3193
|
* =============================================================================
|
|
3194
3194
|
*/
|
|
3195
|
-
function ao(e){try{return e.map((e
|
|
3195
|
+
function ao(e){try{return e.map((e=>At(e)))}catch(e){throw new Error(`Failed to decode encoded string bytes into utf-8, error: ${e}`)}}
|
|
3196
3196
|
/**
|
|
3197
3197
|
* @license
|
|
3198
3198
|
* Copyright 2019 Google LLC. All Rights Reserved.
|
|
@@ -3309,7 +3309,7 @@ function ho(e,t){Array.isArray(e)||(e=[e]),e.forEach((e=>{null!=e&&T("complex64"
|
|
|
3309
3309
|
* limitations under the License.
|
|
3310
3310
|
* =============================================================================
|
|
3311
3311
|
*/
|
|
3312
|
-
function(e,t){const n=[];for(let e=0;e<t.length;e++)t[e]&&n.push(e);const i=aa(e,"int32"),a=aa([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 mo extends k{nextDataId(){return mo.nextDataId++}constructor(){super(),this.blockSize=48,this.firstUse=!0,this.data=new w(this,Sn())}write(e,t,n){this.firstUse&&(this.firstUse=!1,Q().get("IS_NODE")&>("\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=>
|
|
3312
|
+
function(e,t){const n=[];for(let e=0;e<t.length;e++)t[e]&&n.push(e);const i=aa(e,"int32"),a=aa([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 mo extends k{nextDataId(){return mo.nextDataId++}constructor(){super(),this.blockSize=48,this.firstUse=!0,this.data=new w(this,Sn())}write(e,t,n){this.firstUse&&(this.firstUse=!1,Q().get("IS_NODE")&>("\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=>Ct(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 io(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 aa(e.shape,e.dtype,n)}catch(e){throw new Error("Failed to decode encoded string bytes into utf-8")}return aa(e.shape,e.dtype,t)}makeOutput(e,t,n){return Sn().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=$t();e();return{kernelMs:$t()-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){ho([e],"where");const t=this.readSync(e.dataId);return po(e.shape,t)}dispose(){}floatPrecision(){return 32}epsilon(){return super.epsilon()}}
|
|
3313
3313
|
/**
|
|
3314
3314
|
* @license
|
|
3315
3315
|
* Copyright 2020 Google LLC. All Rights Reserved.
|
|
@@ -3326,7 +3326,7 @@ function(e,t){const n=[];for(let e=0;e<t.length;e++)t[e]&&n.push(e);const i=aa(e
|
|
|
3326
3326
|
* limitations under the License.
|
|
3327
3327
|
* =============================================================================
|
|
3328
3328
|
*/
|
|
3329
|
-
function fo(e){return(t,n,i,a,s)=>{const r=wi(t,n),o=r.length,l=P(r),c=D(s,
|
|
3329
|
+
function fo(e){return(t,n,i,a,s)=>{const r=wi(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=yi(t,r),f=yi(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]}}
|
|
3330
3330
|
/**
|
|
3331
3331
|
* @license
|
|
3332
3332
|
* Copyright 2020 Google LLC. All Rights Reserved.
|
|
@@ -3358,7 +3358,7 @@ function fo(e){return(t,n,i,a,s)=>{const r=wi(t,n),o=r.length,l=P(r),c=D(s,A(r))
|
|
|
3358
3358
|
* See the License for the specific language governing permissions and
|
|
3359
3359
|
* limitations under the License.
|
|
3360
3360
|
* =============================================================================
|
|
3361
|
-
*/function vo(e,t,n="float32"){if("complex64"===n){return go({inputs:{real:vo(e,t,"float32"),imag:vo(e,t,"float32")},backend:e})}const i=G(
|
|
3361
|
+
*/function vo(e,t,n="float32"){if("complex64"===n){return go({inputs:{real:vo(e,t,"float32"),imag:vo(e,t,"float32")},backend:e})}const i=G(C(t),n);return e.makeTensorInfo(t,n,i)}
|
|
3362
3362
|
/**
|
|
3363
3363
|
* @license
|
|
3364
3364
|
* Copyright 2020 Google LLC. All Rights Reserved.
|
|
@@ -3374,7 +3374,7 @@ function fo(e){return(t,n,i,a,s)=>{const r=wi(t,n),o=r.length,l=P(r),c=D(s,A(r))
|
|
|
3374
3374
|
* See the License for the specific language governing permissions and
|
|
3375
3375
|
* limitations under the License.
|
|
3376
3376
|
* =============================================================================
|
|
3377
|
-
*/function yo(e){const{inputs:t,backend:n}=e,{x:i}=t;return n.incRef(i.dataId),{dataId:i.dataId,shape:i.shape,dtype:i.dtype}}mo.nextDataId=0;const bo={kernelName
|
|
3377
|
+
*/function yo(e){const{inputs:t,backend:n}=e,{x:i}=t;return n.incRef(i.dataId),{dataId:i.dataId,shape:i.shape,dtype:i.dtype}}mo.nextDataId=0;const bo={kernelName:$e,backendName:"cpu",kernelFunc:yo};
|
|
3378
3378
|
/**
|
|
3379
3379
|
* @license
|
|
3380
3380
|
* Copyright 2020 Google LLC. All Rights Reserved.
|
|
@@ -3439,7 +3439,7 @@ function fo(e){return(t,n,i,a,s)=>{const r=wi(t,n),o=r.length,l=P(r),c=D(s,A(r))
|
|
|
3439
3439
|
* limitations under the License.
|
|
3440
3440
|
* =============================================================================
|
|
3441
3441
|
*/
|
|
3442
|
-
const xo=fo(((e,t)=>e+t)),So=function(e){return(t,n,i,a,s,r)=>{const o=wi(t,n),l=
|
|
3442
|
+
const xo=fo(((e,t)=>e+t)),So=function(e){return(t,n,i,a,s,r)=>{const o=wi(t,n),l=C(o),c=o.length,u=P(o),h=D("float32",l),p=D("float32",l),d=yi(t,o),m=yi(n,o),f=io(i,a),g=io(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}))),No=(To=ie,Io=xo,null==($o=So)?({inputs:e,backend:t})=>{const{a:n,b:i}=e,a=t;ho([n,i],To);const s=a.data.get(n.dataId).values,r=a.data.get(i.dataId).values,o="string"===n.dtype?ao(s):s,l="string"===n.dtype?ao(r):r,c=Co||n.dtype,[u,h]=Io(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=wo({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=wo({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]=$o(n.shape,i.shape,o,l,d,m),y=a.makeTensorInfo(v,"float32",f),b=a.makeTensorInfo(v,"float32",g),w=go({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=Co||n.dtype,[r,o]=Io(n.shape,i.shape,e,t,s);return a.makeTensorInfo(o,s,r)}});var To,Io,$o,Co;const Ao={kernelName:ie,backendName:"cpu",kernelFunc:No};
|
|
3443
3443
|
/**
|
|
3444
3444
|
* @license
|
|
3445
3445
|
* Copyright 2020 Google LLC. All Rights Reserved.
|
|
@@ -3522,7 +3522,7 @@ function jo(e){const{inputs:t,attrs:n,backend:i}=e,{x:a}=t,{perm:s}=n;ho(a,"tran
|
|
|
3522
3522
|
* limitations under the License.
|
|
3523
3523
|
* =============================================================================
|
|
3524
3524
|
*/
|
|
3525
|
-
function(e,t,n,i,a){const s=t.length,r=
|
|
3525
|
+
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 zo={kernelName:ct,backendName:"cpu",kernelFunc:jo},Do=Eo(Xe,(e=>1/(1+Math.exp(-e)))),Fo={kernelName:Xe,backendName:"cpu",kernelFunc:Do};
|
|
3526
3526
|
/**
|
|
3527
3527
|
* @license
|
|
3528
3528
|
* Copyright 2020 Google LLC. All Rights Reserved.
|
|
@@ -3555,7 +3555,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=
|
|
|
3555
3555
|
* limitations under the License.
|
|
3556
3556
|
* =============================================================================
|
|
3557
3557
|
*/
|
|
3558
|
-
function _o(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=
|
|
3558
|
+
function _o(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=aa(i,a,"string"===a?ao(e):e),c=aa(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=>Ct(e))):c.values}function Ro(e){const{inputs:t,backend:n,attrs:i}=e,{x:a}=t,{begin:s,size:r}=i;ho(a,"slice");const[o,l]=ki(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=_o(n.data.get(a.dataId).values,o,l,a.shape,a.dtype);return n.makeTensorInfo(l,a.dtype,c)}const Lo={kernelName:Ye,backendName:"cpu",kernelFunc:Ro};
|
|
3559
3559
|
/**
|
|
3560
3560
|
* @license
|
|
3561
3561
|
* Copyright 2019 Google LLC. All Rights Reserved.
|
|
@@ -3588,7 +3588,7 @@ function _o(e,t,n,i,a){const s=function(e,t,n){let i=n.length;for(let e=0;e<n.le
|
|
|
3588
3588
|
* limitations under the License.
|
|
3589
3589
|
* =============================================================================
|
|
3590
3590
|
*/
|
|
3591
|
-
function Mo(e){const{inputs:t,backend:n,attrs:i}=e,{x:a}=t,{shape:s}=i,r=
|
|
3591
|
+
function Mo(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}}
|
|
3592
3592
|
/**
|
|
3593
3593
|
* @license
|
|
3594
3594
|
* Copyright 2020 Google LLC. All Rights Reserved.
|
|
@@ -3621,7 +3621,7 @@ function Mo(e){const{inputs:t,backend:n,attrs:i}=e,{x:a}=t,{shape:s}=i,r=A(a.sha
|
|
|
3621
3621
|
* See the License for the specific language governing permissions and
|
|
3622
3622
|
* limitations under the License.
|
|
3623
3623
|
* =============================================================================
|
|
3624
|
-
*/const Po={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;ho([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=
|
|
3624
|
+
*/const Po={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;ho([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=Mo({inputs:{x:a},backend:n,attrs:{shape:[d.batchSize,d.outerSize,d.dimSize,d.sliceSize]}}),f=Mo({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=aa(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)}};
|
|
3625
3625
|
/**
|
|
3626
3626
|
* @license
|
|
3627
3627
|
* Copyright 2020 Google LLC. All Rights Reserved.
|
|
@@ -3637,7 +3637,7 @@ function Mo(e){const{inputs:t,backend:n,attrs:i}=e,{x:a}=t,{shape:s}=i,r=A(a.sha
|
|
|
3637
3637
|
* See the License for the specific language governing permissions and
|
|
3638
3638
|
* limitations under the License.
|
|
3639
3639
|
* =============================================================================
|
|
3640
|
-
*/const Bo={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;ho(a,"sum"),o="bool"===a.dtype?wo({inputs:{x:a},backend:n,attrs:{dtype:"int32"}}):yo({inputs:{x:a},backend:n});const l=o.shape.length,c=z(s,o.shape),u=Da(c,l);let h=c,p=o;null!=u&&(p=jo({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(Ea(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]=ja(p.shape,h);let f=vo(n,d,Qt(p.dtype,"int32"));const g=
|
|
3640
|
+
*/const Bo={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;ho(a,"sum"),o="bool"===a.dtype?wo({inputs:{x:a},backend:n,attrs:{dtype:"int32"}}):yo({inputs:{x:a},backend:n});const l=o.shape.length,c=z(s,o.shape),u=Da(c,l);let h=c,p=o;null!=u&&(p=jo({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(Ea(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]=ja(p.shape,h);let f=vo(n,d,Qt(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=Mo({inputs:{x:f},backend:n,attrs:{shape:za(f.shape,c)}}),n.disposeIntermediateTensorInfo(e)}return n.disposeIntermediateTensorInfo(o),null!=u&&n.disposeIntermediateTensorInfo(p),f}};
|
|
3641
3641
|
/**
|
|
3642
3642
|
* @license
|
|
3643
3643
|
* Copyright 2020 Google LLC. All Rights Reserved.
|
|
@@ -3753,7 +3753,7 @@ function Jo(e,t,n,i,a){if("linear"===n)return yo({inputs:{x:t},backend:e});if("r
|
|
|
3753
3753
|
* limitations under the License.
|
|
3754
3754
|
* =============================================================================
|
|
3755
3755
|
*/
|
|
3756
|
-
return function(e){const{inputs:t,backend:n,attrs:i}=e,{x:a}=t,{alpha:s}=i;ho([a],"leakyRelu");const r=
|
|
3756
|
+
return function(e){const{inputs:t,backend:n,attrs:i}=e,{x:a}=t,{alpha:s}=i;ho([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 Do({inputs:{x:t},backend:e});throw new Error(`Activation ${n} has not been implemented for the CPU backend.`)}
|
|
3757
3757
|
/**
|
|
3758
3758
|
* @license
|
|
3759
3759
|
* Copyright 2020 Google LLC. All Rights Reserved.
|
|
@@ -3786,7 +3786,7 @@ return function(e){const{inputs:t,backend:n,attrs:i}=e,{x:a}=t,{alpha:s}=i;ho([a
|
|
|
3786
3786
|
* limitations under the License.
|
|
3787
3787
|
* =============================================================================
|
|
3788
3788
|
*/
|
|
3789
|
-
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;ho([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=
|
|
3789
|
+
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;ho([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=wi(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=Mo({inputs:{x:a},backend:n,attrs:{shape:r?[g,u,p]:[g,p,u]}}),k=Mo({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),$=n.data.get(w.dataId).values,A=n.data.get(k.dataId).values,E=P(w.shape),j=P(k.shape),[z,D,F]=r?[E[0],1,E[1]]:[E[0],E[1],1],[_,R,L]=o?[1,j[1],j[0]]:[j[1],1,j[0]],M=S*N,O=aa([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+=$[t*z+c*D+e*F]*A[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=No({inputs:{a:p,b:r},backend:n}),f.push(p),p=d),u&&(m=Jo(n,p,u,o,h),f.push(p),p=m);for(const e of f)n.disposeIntermediateTensorInfo(e);return p}};
|
|
3790
3790
|
/**
|
|
3791
3791
|
* @license
|
|
3792
3792
|
* Copyright 2018 Google LLC
|
|
@@ -3831,7 +3831,7 @@ function(e){const{inputs:t,backend:n,attrs:i}=e,{a:a,b:s,bias:r,preluActivationW
|
|
|
3831
3831
|
* license that can be found in the LICENSE file or at
|
|
3832
3832
|
* https://opensource.org/licenses/MIT.
|
|
3833
3833
|
* =============================================================================
|
|
3834
|
-
*/const Il=["channelsFirst","channelsLast"]
|
|
3834
|
+
*/const Il=["channelsFirst","channelsLast"],$l=["nearest","bilinear"],Cl=["valid","same","causal"],Al=["max","avg"],El=["sum","mul","concat","ave"],jl=new Map;function zl(e){vl(Il,"DataFormat",e)}function Dl(e){vl(Cl,"PaddingMode",e)}function Fl(e){vl(Al,"PoolMode",e)}const _l=[];function Rl(e,t){_l.push(e);try{const e=t();return _l.pop(),e}catch(e){throw _l.pop(),e}}function Ll(e){if(!Pl(e))throw new Error("Not a valid tensor name: '"+e+"'");return(0===_l.length?"":_l.join("/")+"/")+e}function Ml(e){if(!Pl(e))throw new Error("Not a valid tensor name: '"+e+"'");jl.has(e)||jl.set(e,0);const t=jl.get(e);if(jl.set(e,jl.get(e)+1),t>0){const n=`${e}_${t}`;return jl.set(n,1),n}return e}const Ol=new RegExp(/^[A-Za-z0-9][-A-Za-z0-9\._\/]*$/);function Pl(e){return!!e.match(Ol)}
|
|
3835
3835
|
/**
|
|
3836
3836
|
* @license
|
|
3837
3837
|
* Copyright 2018 Google LLC
|
|
@@ -3859,7 +3859,7 @@ function(e){const{inputs:t,backend:n,attrs:i}=e,{a:a,b:s,bias:r,preluActivationW
|
|
|
3859
3859
|
* https://opensource.org/licenses/MIT.
|
|
3860
3860
|
* =============================================================================
|
|
3861
3861
|
*/
|
|
3862
|
-
function ql(e,t){return hi(e,t)}function Hl(e,t=-1){const n=e.shape.slice();return t<0&&(t=n.length+t+1),n.splice(t,0,1),Wi(e,n)}function Jl(e,t,n){return Tn((()=>{switch(e.rank){case 1:return qs(e,t,n);case 2:return Hs(e,[t,0],[n,e.shape[1]]);case 3:return Js(e,[t,0,0],[n,e.shape[1],e.shape[2]]);case 4:return Zs(e,[t,0,0,0],[n,e.shape[1],e.shape[2],e.shape[3]]);case 5:return Ji(e,[t,0,0,0,0],[n,e.shape[1],e.shape[2],e.shape[3],e.shape[4]]);case 6:return Ji(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 Xo(`sliceAlongFirstAxis() received an unsupported tensor rank: ${e.rank}`)}}))}function Zl(e,t,n){return Tn((()=>{switch(e.rank){case 1:return qs(e,t,n);case 2:return Hs(e,[0,t],[e.shape[0],n]);case 3:return Js(e,[0,0,t],[e.shape[0],e.shape[1],n]);case 4:return Zs(e,[0,0,0,t],[e.shape[0],e.shape[1],e.shape[2],n]);default:throw new Xo(`sliceAlongLastAxis() received an unsupported tensor rank: ${e.rank}`)}}))}function Yl(e,t,n,i){return Tn((()=>{switch(e.rank){case 1:return qs(e,t,n);case 2:switch(i){case 1:return Jl(e,t,n);case 2:return Zl(e,t,n);default:throw new Xo(`The axis is not within the rank of the tensor ${i}`)}case 3:switch(i){case 1:return Jl(e,t,n);case 2:return Js(e,[0,t,0],[e.shape[0],n,e.shape[2]]);case 3:return Zl(e,t,n);default:throw new Xo(`The axis is not within the rank of the tensor ${i}`)}case 4:switch(i){case 1:return Jl(e,t,n);case 2:return Zs(e,[0,t,0,0],[e.shape[0],n,e.shape[2],e.shape[3]]);case 3:return Zs(e,[0,0,t,0],[e.shape[0],e.shape[1],n,e.shape[3]]);case 4:return Zl(e,t,n);default:throw new Xo(`The axis is not within the rank of the tensor ${i}`)}default:throw new Xo(`sliceAlongLastAxis() received an unsupported tensor rank: ${e.rank}`)}}))}function Ql(e,t=-1){let n;return t<0&&(n=e[0].rank,t=0!==n?n:0),t===e[0].rank&&(t=-1),qi(e,t)}function Xl(e,t){switch(e.rank){case 1:return oa([e,t]);case 2:return la([e,t],0);case 3:return ca([e,t],0);case 4:return ua([e,t],0);default:throw new Xo(`concatAlongFirstAxis() received an unsupported tensor rank: ${e.rank}`)}}function ec(e,t){if(Array.isArray(t)||(t=[t]),e.rank!==t.length)throw new Xo(`The length of input n (${t.length}) does not match the number of dimensions in input x (${e.rank})`);return Ka(e,t)}function tc(e,t=0,n=1,i,a){return _s(e,t,n,i,a)}function nc(e,t,n,i){if(e.rank<2||t.rank<2)throw new el(`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 el(`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 gr({a:e,b:t,transposeA:!1,transposeB:!1,bias:i?sc(e.rank,i,"channelsLast"):null,activation:n})}{const a=e.shape.slice(),s=a.pop();e=Wi(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=Wi(vi(t,u),[l,-1]);const h=[...a,...c];return Wi(gr({a:e,b:t,transposeA:!1,transposeB:!1,bias:i?sc(e.rank,i,"channelsLast"):null,activation:n}),h)}}function ic(e,t,n){return Tn((()=>(t=Array.isArray(t)?nr(t,"int32"):hi(t,"int32"),Ja(e,t,n))))}function ac(e){return Ei(e,e)}function sc(e,t,n){const i=t.shape;if(1!==t.rank&&t.rank!==e)throw new Xo(`Unexpected bias dimensions: ${t.rank}; expected it to be 1 or ${e}`);if(5===e){if("channelsFirst"===n)return 1===i.length?Wi(t,[1,i[0],1,1,1]):Wi(t,[1,i[3],i[0],i[1],i[2]]);if("channelsLast"===n)return 1===i.length?Wi(t,[1,1,1,1,i[0]]):Wi(t,[1].concat(i))}else if(4===e){if("channelsFirst"===n)return 1===i.length?Wi(t,[1,i[0],1,1]):Wi(t,[1,i[2],i[0],i[1]]);if("channelsLast"===n)return 1===i.length?Wi(t,[1,1,1,i[0]]):Wi(t,[1].concat(i))}else if(3===e){if("channelsFirst"===n)return 1===i.length?Wi(t,[1,i[0],1]):Wi(t,[1,i[1],i[0]]);if("channelsLast"===n)return 1===i.length?Wi(t,[1,1,i[0]]):Wi(t,[1].concat(i))}else if(e<3)return t;throw new Xo(`Unsupported input rank by biasAdd: ${t.rank}`)}function rc(e,t,n){return Tn((()=>(null==n&&(n="channelsLast"),zl(n)
|
|
3862
|
+
function ql(e,t){return hi(e,t)}function Hl(e,t=-1){const n=e.shape.slice();return t<0&&(t=n.length+t+1),n.splice(t,0,1),Wi(e,n)}function Jl(e,t,n){return Tn((()=>{switch(e.rank){case 1:return qs(e,t,n);case 2:return Hs(e,[t,0],[n,e.shape[1]]);case 3:return Js(e,[t,0,0],[n,e.shape[1],e.shape[2]]);case 4:return Zs(e,[t,0,0,0],[n,e.shape[1],e.shape[2],e.shape[3]]);case 5:return Ji(e,[t,0,0,0,0],[n,e.shape[1],e.shape[2],e.shape[3],e.shape[4]]);case 6:return Ji(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 Xo(`sliceAlongFirstAxis() received an unsupported tensor rank: ${e.rank}`)}}))}function Zl(e,t,n){return Tn((()=>{switch(e.rank){case 1:return qs(e,t,n);case 2:return Hs(e,[0,t],[e.shape[0],n]);case 3:return Js(e,[0,0,t],[e.shape[0],e.shape[1],n]);case 4:return Zs(e,[0,0,0,t],[e.shape[0],e.shape[1],e.shape[2],n]);default:throw new Xo(`sliceAlongLastAxis() received an unsupported tensor rank: ${e.rank}`)}}))}function Yl(e,t,n,i){return Tn((()=>{switch(e.rank){case 1:return qs(e,t,n);case 2:switch(i){case 1:return Jl(e,t,n);case 2:return Zl(e,t,n);default:throw new Xo(`The axis is not within the rank of the tensor ${i}`)}case 3:switch(i){case 1:return Jl(e,t,n);case 2:return Js(e,[0,t,0],[e.shape[0],n,e.shape[2]]);case 3:return Zl(e,t,n);default:throw new Xo(`The axis is not within the rank of the tensor ${i}`)}case 4:switch(i){case 1:return Jl(e,t,n);case 2:return Zs(e,[0,t,0,0],[e.shape[0],n,e.shape[2],e.shape[3]]);case 3:return Zs(e,[0,0,t,0],[e.shape[0],e.shape[1],n,e.shape[3]]);case 4:return Zl(e,t,n);default:throw new Xo(`The axis is not within the rank of the tensor ${i}`)}default:throw new Xo(`sliceAlongLastAxis() received an unsupported tensor rank: ${e.rank}`)}}))}function Ql(e,t=-1){let n;return t<0&&(n=e[0].rank,t=0!==n?n:0),t===e[0].rank&&(t=-1),qi(e,t)}function Xl(e,t){switch(e.rank){case 1:return oa([e,t]);case 2:return la([e,t],0);case 3:return ca([e,t],0);case 4:return ua([e,t],0);default:throw new Xo(`concatAlongFirstAxis() received an unsupported tensor rank: ${e.rank}`)}}function ec(e,t){if(Array.isArray(t)||(t=[t]),e.rank!==t.length)throw new Xo(`The length of input n (${t.length}) does not match the number of dimensions in input x (${e.rank})`);return Ka(e,t)}function tc(e,t=0,n=1,i,a){return _s(e,t,n,i,a)}function nc(e,t,n,i){if(e.rank<2||t.rank<2)throw new el(`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 el(`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 gr({a:e,b:t,transposeA:!1,transposeB:!1,bias:i?sc(e.rank,i,"channelsLast"):null,activation:n})}{const a=e.shape.slice(),s=a.pop();e=Wi(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=Wi(vi(t,u),[l,-1]);const h=[...a,...c];return Wi(gr({a:e,b:t,transposeA:!1,transposeB:!1,bias:i?sc(e.rank,i,"channelsLast"):null,activation:n}),h)}}function ic(e,t,n){return Tn((()=>(t=Array.isArray(t)?nr(t,"int32"):hi(t,"int32"),Ja(e,t,n))))}function ac(e){return Ei(e,e)}function sc(e,t,n){const i=t.shape;if(1!==t.rank&&t.rank!==e)throw new Xo(`Unexpected bias dimensions: ${t.rank}; expected it to be 1 or ${e}`);if(5===e){if("channelsFirst"===n)return 1===i.length?Wi(t,[1,i[0],1,1,1]):Wi(t,[1,i[3],i[0],i[1],i[2]]);if("channelsLast"===n)return 1===i.length?Wi(t,[1,1,1,1,i[0]]):Wi(t,[1].concat(i))}else if(4===e){if("channelsFirst"===n)return 1===i.length?Wi(t,[1,i[0],1,1]):Wi(t,[1,i[2],i[0],i[1]]);if("channelsLast"===n)return 1===i.length?Wi(t,[1,1,1,i[0]]):Wi(t,[1].concat(i))}else if(3===e){if("channelsFirst"===n)return 1===i.length?Wi(t,[1,i[0],1]):Wi(t,[1,i[1],i[0]]);if("channelsLast"===n)return 1===i.length?Wi(t,[1,1,i[0]]):Wi(t,[1].concat(i))}else if(e<3)return t;throw new Xo(`Unsupported input rank by biasAdd: ${t.rank}`)}function rc(e,t,n){return Tn((()=>(null==n&&(n="channelsLast"),zl(n),$i(e,sc(e.rank,t,n)))))}function oc(e,t,n,i){return Tn((()=>or(e,t,n,i)))}function lc(e,t,n=!1){return n?e():t()}
|
|
3863
3863
|
/**
|
|
3864
3864
|
* @license
|
|
3865
3865
|
* Copyright 2018 Google LLC
|
|
@@ -3878,7 +3878,7 @@ function ql(e,t){return hi(e,t)}function Hl(e,t=-1){const n=e.shape.slice();retu
|
|
|
3878
3878
|
* https://opensource.org/licenses/MIT.
|
|
3879
3879
|
* =============================================================================
|
|
3880
3880
|
*/
|
|
3881
|
-
var t;this.scale=null==e.scale?1:e.scale,this.mode=null==e.mode?"fanIn":e.mode,t=this.mode,vl(cc,"FanMode",t),this.distribution=null==e.distribution?"normal":e.distribution,function(e){vl(uc,"Distribution",e)}(this.distribution),this.seed=e.seed}apply(e,t){const n=function(e,t="channelsLast"){let n,i;if(zl(t),2===e.length)n=e[0],i=e[1];else if(-1!==[3,4,5].indexOf(e.length)){if("channelsFirst"===t){const t=Bl(e,2);n=e[1]*t,i=e[0]*t}else if("channelsLast"===t){const t=Bl(e,0,e.length-2);n=e[e.length-2]*t,i=e[e.length-1]*t}}else{const t=Bl(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 el(`${this.getClassName()} does not support dType ${t}.`);return ar(e,0,n,t,this.seed)}{const n=Math.sqrt(3*s);return Rs(e,-n,n,t,this.seed)}}getConfig(){return{scale:this.scale,mode:this.mode,distribution:this.distribution,seed:this.seed}}}bc.className="VarianceScaling",Ii(bc);class wc extends bc{constructor(e){super({scale:1,mode:"fanAvg",distribution:"uniform",seed:null==e?null:e.seed})}getClassName(){return bc.className}}wc.className="GlorotUniform",Ii(wc);class kc extends bc{constructor(e){super({scale:1,mode:"fanAvg",distribution:"normal",seed:null==e?null:e.seed})}getClassName(){return bc.className}}kc.className="GlorotNormal",Ii(kc);class xc extends bc{constructor(e){super({scale:2,mode:"fanIn",distribution:"normal",seed:null==e?null:e.seed})}getClassName(){return bc.className}}xc.className="HeNormal",Ii(xc);class Sc extends bc{constructor(e){super({scale:2,mode:"fanIn",distribution:"uniform",seed:null==e?null:e.seed})}getClassName(){return bc.className}}Sc.className="HeUniform",Ii(Sc);class Nc extends bc{constructor(e){super({scale:1,mode:"fanIn",distribution:"normal",seed:null==e?null:e.seed})}getClassName(){return bc.className}}Nc.className="LeCunNormal",Ii(Nc);class Tc extends bc{constructor(e){super({scale:1,mode:"fanIn",distribution:"uniform",seed:null==e?null:e.seed})}getClassName(){return bc.className}}Tc.className="LeCunUniform",Ii(Tc);class Ic extends hc{constructor(e){super(),this.DEFAULT_GAIN=1,this.ELEMENTS_WARN_SLOW=2e3,this.gain=null==e.gain?this.DEFAULT_GAIN:e.gain,this.seed=e.seed}apply(e,t){return Tn((()=>{if(e.length<2)throw new el("Shape must be at least 2D.");if("int32"!==t&&"float32"!==t&&void 0!==t)throw new TypeError(`Unsupported data type ${t}.`);const n=
|
|
3881
|
+
var t;this.scale=null==e.scale?1:e.scale,this.mode=null==e.mode?"fanIn":e.mode,t=this.mode,vl(cc,"FanMode",t),this.distribution=null==e.distribution?"normal":e.distribution,function(e){vl(uc,"Distribution",e)}(this.distribution),this.seed=e.seed}apply(e,t){const n=function(e,t="channelsLast"){let n,i;if(zl(t),2===e.length)n=e[0],i=e[1];else if(-1!==[3,4,5].indexOf(e.length)){if("channelsFirst"===t){const t=Bl(e,2);n=e[1]*t,i=e[0]*t}else if("channelsLast"===t){const t=Bl(e,0,e.length-2);n=e[e.length-2]*t,i=e[e.length-1]*t}}else{const t=Bl(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 el(`${this.getClassName()} does not support dType ${t}.`);return ar(e,0,n,t,this.seed)}{const n=Math.sqrt(3*s);return Rs(e,-n,n,t,this.seed)}}getConfig(){return{scale:this.scale,mode:this.mode,distribution:this.distribution,seed:this.seed}}}bc.className="VarianceScaling",Ii(bc);class wc extends bc{constructor(e){super({scale:1,mode:"fanAvg",distribution:"uniform",seed:null==e?null:e.seed})}getClassName(){return bc.className}}wc.className="GlorotUniform",Ii(wc);class kc extends bc{constructor(e){super({scale:1,mode:"fanAvg",distribution:"normal",seed:null==e?null:e.seed})}getClassName(){return bc.className}}kc.className="GlorotNormal",Ii(kc);class xc extends bc{constructor(e){super({scale:2,mode:"fanIn",distribution:"normal",seed:null==e?null:e.seed})}getClassName(){return bc.className}}xc.className="HeNormal",Ii(xc);class Sc extends bc{constructor(e){super({scale:2,mode:"fanIn",distribution:"uniform",seed:null==e?null:e.seed})}getClassName(){return bc.className}}Sc.className="HeUniform",Ii(Sc);class Nc extends bc{constructor(e){super({scale:1,mode:"fanIn",distribution:"normal",seed:null==e?null:e.seed})}getClassName(){return bc.className}}Nc.className="LeCunNormal",Ii(Nc);class Tc extends bc{constructor(e){super({scale:1,mode:"fanIn",distribution:"uniform",seed:null==e?null:e.seed})}getClassName(){return bc.className}}Tc.className="LeCunUniform",Ii(Tc);class Ic extends hc{constructor(e){super(),this.DEFAULT_GAIN=1,this.ELEMENTS_WARN_SLOW=2e3,this.gain=null==e.gain?this.DEFAULT_GAIN:e.gain,this.seed=e.seed}apply(e,t){return Tn((()=>{if(e.length<2)throw new el("Shape must be at least 2D.");if("int32"!==t&&"float32"!==t&&void 0!==t)throw new TypeError(`Unsupported data type ${t}.`);const n=C(e.slice(0,-1)),i=e[e.length-1],a=n*i;a>this.ELEMENTS_WARN_SLOW&&console.warn(`Orthogonal initializer is being called on a matrix with more than ${this.ELEMENTS_WARN_SLOW} (${a}) elements: Slowness may result.`);const s=tc([Math.max(i,n),Math.min(i,n)],0,1,t,this.seed),r=Vr.qr(s,!1);let o=r[0];const l=r[1].flatten().stridedSlice([0],[Math.min(i,n)*Math.min(i,n)],[Math.min(i,n)+1]);return o=Ei(o,l.sign()),n<i&&(o=o.transpose()),Ei(Ma(this.gain),o.reshape(e))}))}getConfig(){return{gain:this.gain,seed:this.seed}}}Ic.className="Orthogonal",Ii(Ic);const $c={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 Cc(e,t={}){return dl(e,Ti.getMap().classNameMap,t,"initializer")}function Ac(e){return hl(e)}function Ec(e){if("string"==typeof e){const t=e in $c?$c[e]:e;if("GlorotNormal"===t)return new kc;if("GlorotUniform"===t)return new wc;if("HeNormal"===t)return new xc;if("HeUniform"===t)return new Sc;if("LeCunNormal"===t)return new Nc;if("LeCunUniform"===t)return new Tc;{const e={};return e.className=t,e.config={},Cc(e)}}return e instanceof hc?e:Cc(e)}
|
|
3882
3882
|
/**
|
|
3883
3883
|
* @license
|
|
3884
3884
|
* Copyright 2018 Google LLC
|
|
@@ -3923,7 +3923,7 @@ var t;this.scale=null==e.scale?1:e.scale,this.mode=null==e.mode?"fanIn":e.mode,t
|
|
|
3923
3923
|
* license that can be found in the LICENSE file or at
|
|
3924
3924
|
* https://opensource.org/licenses/MIT.
|
|
3925
3925
|
* =============================================================================
|
|
3926
|
-
*/(e);if(i===a)throw new Xo("Arguments to apply() must be all SymbolicTensors or all Tensors");return Rl(this.name,(()=>{if(!this.built){this.assertInputCompatibility(e);const t=[];for(const n of ol(e))t.push(n.shape);this.build(rl(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);this.supportsMasking&&this.setMaskMetadata(e,i);const a=ol(i),s=[];for(let e of a)-1!==n.indexOf(e)&&(e=e.clone()),s.push(e);if(i=rl(s),null!=this.activityRegularizer)throw new el("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return i}{const n=function(e){e=ol(e);const t=[];for(const n of e)t.push(n.shape);return rl(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 Bc(s,n,this,ol(e),t,this.name,i))):new Bc(s,i,this,ol(e),t,this.name),this.addInboundNode(e,a,null,null,n,i,t),this._refCount++,null!=this.activityRegularizer)throw new el("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 Yo(`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 Yo(`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 Qo(`You tried to call countParams() on ${this.name}, but the layer is not built yet. Build it first by calling build(batchInputShape).`);return _c(this.weights)}build(e){this.built=!0}getWeights(e=!1){return Mc(e?this.trainableWeights:this.weights)}setWeights(e){Tn((()=>{const t=this.weights;if(t.length!==e.length)throw new Xo(`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=Mc(t);for(let a=0;a<i.length;++a){const s=i[a],r=t[a],o=e[a];if(
|
|
3926
|
+
*/(e);if(i===a)throw new Xo("Arguments to apply() must be all SymbolicTensors or all Tensors");return Rl(this.name,(()=>{if(!this.built){this.assertInputCompatibility(e);const t=[];for(const n of ol(e))t.push(n.shape);this.build(rl(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);this.supportsMasking&&this.setMaskMetadata(e,i);const a=ol(i),s=[];for(let e of a)-1!==n.indexOf(e)&&(e=e.clone()),s.push(e);if(i=rl(s),null!=this.activityRegularizer)throw new el("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return i}{const n=function(e){e=ol(e);const t=[];for(const n of e)t.push(n.shape);return rl(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 Bc(s,n,this,ol(e),t,this.name,i))):new Bc(s,i,this,ol(e),t,this.name),this.addInboundNode(e,a,null,null,n,i,t),this._refCount++,null!=this.activityRegularizer)throw new el("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 Yo(`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 Yo(`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 Qo(`You tried to call countParams() on ${this.name}, but the layer is not built yet. Build it first by calling build(batchInputShape).`);return _c(this.weights)}build(e){this.built=!0}getWeights(e=!1){return Mc(e?this.trainableWeights:this.weights)}setWeights(e){Tn((()=>{const t=this.weights;if(t.length!==e.length)throw new Xo(`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=Mc(t);for(let a=0;a<i.length;++a){const s=i[a],r=t[a],o=e[a];if(!A(s.shape,o.shape))throw new Xo(`Layer weight shape ${s.shape} not compatible with provided weight shape ${o.shape}`);n.push([r,o])}Oc(n)}))}addWeight(e,t,n,i,a,s,r,o){if(-1!==this._addedWeightNames.indexOf(e))throw new Xo(`Duplicate weight name ${e} for layer ${this.name}`);this._addedWeightNames.push(e),null==n&&(n="float32"),this.fastWeightInitDuringBuild&&(i=null!=o?o():Ec("zeros"));const l=i.apply(t,n),c=new Lc(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=ol(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}setMaskMetadata(e,t,n){if(!this.supportsMasking)return;const i=this.computeMask(e,n),a=ol(t),s=ol(i);if(a.length!==s.length)throw new Error(`${this.name} outputs ${a.length} tensors but ${a.length} masks for those tensors`);for(let e=0;e<a.length;e++)a[e].kerasMask=s[e]}addInboundNode(e,t,n,i,a,s,r=null){const o=ol(e);t=ol(t),n=ol(n),i=ol(i),a=zc(a),s=zc(s);const l=[],c=[],u=[];for(const e of o)l.push(e.sourceLayer),c.push(e.nodeIndex),u.push(e.tensorIndex);new Wc({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 Kc(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=Kc(e.inputTensors[n],e.inboundLayers[n],e.nodeIndices[n]);for(const e of i)-1===t.indexOf(e)&&t.push(e)}return t}}}class qc extends Vc{constructor(e){if(super({dtype:e.dtype,name:null!=e.name?e.name:Tl("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 Xo("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 Xo("An InputLayer should be passed either a `batchInputShape` or an `inputShape`.");t=[e.batchSize].concat(e.inputShape)}else if(null!=e.batchSize)throw new Xo("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 Bc(this.dtype,this.batchInputShape,this,[],{},this.name);i.nodeIndex=0,i.tensorIndex=0,new Wc({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:[i],outputTensors:[i],inputMasks:[null],outputMasks:[null],inputShapes:[t],outputShapes:[t]})}apply(e,t){throw new Xo(`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}}}qc.className="InputLayer",Ii(qc);class Hc{constructor(e){if(this.id2Value={},this.id2Mask={},this.name2Id={},e instanceof Hc)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 Xo(`Duplicate key: name=${e.name}, id=${e.id}`);return this.id2Value[e.id]=
|
|
3927
3927
|
/**
|
|
3928
3928
|
* @license
|
|
3929
3929
|
* Copyright 2018 Google LLC
|
|
@@ -3966,7 +3966,7 @@ function(e,t){if(null==e.dtype||e.dtype===t.dtype)return t;try{return hi(t,e.dty
|
|
|
3966
3966
|
* limitations under the License.
|
|
3967
3967
|
* =============================================================================
|
|
3968
3968
|
*/
|
|
3969
|
-
const tu={kernelName:"Abs",inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Ei(e,tr(hi(n,"float32"),-1))}}},nu={kernelName:"Acos",inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const t=Pa(hi(n,"float32")),i=Oa(ss(Ma(1),t));return fi(
|
|
3969
|
+
const tu={kernelName:"Abs",inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Ei(e,tr(hi(n,"float32"),-1))}}},nu={kernelName:"Acos",inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const t=Pa(hi(n,"float32")),i=Oa(ss(Ma(1),t));return fi(Ai(e,i))}}}},iu={kernelName:"Acosh",inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const t=Oa(ss(Pa(hi(n,"float32")),1));return Ai(e,t)}}}},au={kernelName:ie,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,i]=t,a=wi(n.shape,i.shape);return{a:()=>{let t=e;const i=bi(n.shape,a);return i.length>0&&(t=Ba(t,i)),Wi(t,n.shape)},b:()=>{let t=e;const n=bi(i.shape,a);return n.length>0&&(t=Ba(t,n)),Wi(t,i.shape)}}}},su={kernelName:"AddN",saveAllInputs:!0,gradFunc:(e,t)=>{const n={};return t.forEach(((t,i)=>{n[i]=()=>e.clone()})),n}},ru={kernelName:ae,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Ia(n)}}},ou={kernelName:"ArgMin",inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Ia(n)}}},lu={kernelName:"Asin",inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Ai(e,Oa(ss(Ma(1),Pa(hi(n,"float32")))))}}},cu={kernelName:"Asinh",inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const t=Oa($i(Ma(1),Pa(hi(n,"float32"))));return Ai(e,t)}}}},uu={kernelName:"Atan2",inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,i]=t,a=wi(n.shape,i.shape);return{a:()=>{const t=$i(Pa(n),Pa(i));let s=Ei(e,Ai(i,t));const r=bi(n.shape,a);return r.length>0&&(s=Ba(s,r)),Wi(s,n.shape)},b:()=>{const t=$i(Pa(n),Pa(i));let s=fi(Ei(e,Ai(n,t)));const r=bi(i.shape,a);return r.length>0&&(s=Ba(s,r)),Wi(s,i.shape)}}}},hu={kernelName:"Atan",inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Ai(e,$i(Pa(hi(n,"float32")),1))}}},pu={kernelName:"Atanh",inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Ai(e,ss(Ma(1),Pa(hi(n,"float32"))))}}};
|
|
3970
3970
|
/**
|
|
3971
3971
|
* @license
|
|
3972
3972
|
* Copyright 2020 Google LLC. All Rights Reserved.
|
|
@@ -4048,7 +4048,7 @@ function(e,t,n,i,a){const s=fn(e,"dy","avgPoolGrad"),r=fn(t,"input","avgPoolGrad
|
|
|
4048
4048
|
* See the License for the specific language governing permissions and
|
|
4049
4049
|
* limitations under the License.
|
|
4050
4050
|
* =============================================================================
|
|
4051
|
-
*/const
|
|
4051
|
+
*/const $u=vn({conv3DBackpropFilter_:
|
|
4052
4052
|
/**
|
|
4053
4053
|
* @license
|
|
4054
4054
|
* Copyright 2020 Google LLC. All Rights Reserved.
|
|
@@ -4065,7 +4065,7 @@ function(e,t,n,i,a){const s=fn(e,"dy","avgPoolGrad"),r=fn(t,"input","avgPoolGrad
|
|
|
4065
4065
|
* limitations under the License.
|
|
4066
4066
|
* =============================================================================
|
|
4067
4067
|
*/
|
|
4068
|
-
function(e,t,n,i,a){let s=e;4===e.rank&&(s=Wi(e,[1,e.shape[0],e.shape[1],e.shape[2],e.shape[3]]));let r=t;4===r.rank&&(r=Wi(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 cn.runKernel("Conv3DBackpropFilterV2",o,l)}}),
|
|
4068
|
+
function(e,t,n,i,a){let s=e;4===e.rank&&(s=Wi(e,[1,e.shape[0],e.shape[1],e.shape[2],e.shape[3]]));let r=t;4===r.rank&&(r=Wi(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 cn.runKernel("Conv3DBackpropFilterV2",o,l)}}),Cu={kernelName:fe,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{const{dilations:i,strides:a,pad:s}=n;T(Oi(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:()=>ga(r.shape,e,o,a,s),filter:()=>$u(r,e,o.shape,a,s)}}},Au={kernelName:"Cos",inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Ei(fi(Vs(hi(n,"float32"))),e)}}},Eu={kernelName:ge,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Ei(Ks(hi(n,"float32")),e)}}},ju={kernelName:ve,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[i]=t,{axis:a,exclusive:s,reverse:r}=n;return{x:()=>{const t=Da([a],i.rank);let n=ka(e,a,s,!r);return null!=t&&(n=vi(n,t)),n}}}},zu={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(Oi(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(Pi(a,o),(()=>`Error in gradient of depthwiseConv2d: Either strides or dilations must be 1. Got strides ${a} and dilations '${o}'.`)),Ui("depthwiseConv2d",s,r),{x:()=>fr(l.shape,e,c,a,s,o,r),filter:()=>mr(l,e,c.shape,a,s,o,r)}}},Du={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:()=>cn.runKernel("Dilation2DBackpropInput",s,n),filter:()=>cn.runKernel("Dilation2DBackpropFilter",r,n)}}},Fu={kernelName:we,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t,i={dy:e,y:n};return{x:()=>cn.runKernel("EluGrad",i)}}},_u={kernelName:"Erf",inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t,i=Ei(Ga(fi(Pa(n))),2/Math.sqrt(Math.PI));return{x:()=>Ei(e,i)}}},Ru={kernelName:"Exp",outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Ei(e,n)}}},Lu={kernelName:ke,inputsToSave:["input"],gradFunc:(e,t)=>{const[n]=t;return{input:()=>Wi(e,n.shape)}}},Mu={kernelName:"Expm1",inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Ei(e,Ga(n))}}},Ou={kernelName:xe,gradFunc:e=>({x:()=>Ia(e)})},Pu={kernelName:Se,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,i]=t,a=wi(n.shape,i.shape);return{a:()=>{const t=Ai(e,hi(i,"float32")),s=bi(n.shape,a);return s.length>0?Wi(Ba(t,s),n.shape):t},b:()=>{let t=Ei(e,hi(n,"float32"));const s=bi(i.shape,a);s.length>0&&(t=Wi(Ba(t,s),i.shape));const r=Pa(i);return fi(Ai(t,hi(r,"float32")))}}}},Bu={kernelName:Ne,inputsToSave:["x","mean","variance","scale"],gradFunc:(e,t,n)=>{const{varianceEpsilon:i}=n,[a,s,r,o]=t,l=null==o?Ma(1):o,c=bi(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=ss(a,s),p=Ei(e,l),d=Us($i(r,Ma(i))),m=Ei(Ei(Ei(d,d),d),Ma(-.5));return{x:()=>1===s.rank?Wi(Ei(Ei(e,Ka(Wi(d,[1,1,1,s.shape[0]]),u)),l),a.shape):Wi(Ei(Ei(e,d),l),a.shape),mean:()=>{let e=Ei(Ei(d,Ma(-1)),p);return 1===s.rank&&(e=Ba(e,c)),Wi(e,s.shape)},variance:()=>{let e=Ei(Ei(m,h),p);return 1===s.rank&&(e=Ba(e,c)),Wi(e,s.shape)},scale:()=>{const t=Ei(h,d);let n=Ei(e,t);return 1===s.rank&&(n=Ba(n,c)),Wi(n,s.shape)},offset:()=>{let t=e;return 1===s.rank&&(t=Ba(t,c)),Wi(t,s.shape)}}}},Uu={kernelName:Te,inputsToSave:["x","indices"],gradFunc:(e,t,n)=>{const[i,a]=t,{axis:s,batchDims:r}=n,o=z(s,i.shape)[0],l=(e,t,n)=>()=>{const i=e.shape,a=t.size,r=i.slice(0,o),l=r.length,c=i.slice(s,i.length).slice(1),u=c.length,h=Wu(0,l),p=Wu(l+1,l+1+u),d=Gu([r,[a],c]),m=Wi(n,d),f=Wi(t,[a]),g=Gu([[l],h,p]),v=vi(m,g);let y=sr(v,f,e.shape[o]);const b=Fa(g);return y=vi(y,b),y};if(1===r){const t=i.shape[0],n=i.split(t,0);return{x:()=>{const t=er(n.map(((t,n)=>l(t,a.slice(n,1),e.slice(n,1))())));return t.reshape(i.shape)},indices:()=>a}}return{x:l(i,a,e),indices:()=>a}}};
|
|
4069
4069
|
/**
|
|
4070
4070
|
* @license
|
|
4071
4071
|
* Copyright 2020 Google LLC. All Rights Reserved.
|
|
@@ -4097,7 +4097,7 @@ function(e,t,n,i,a){let s=e;4===e.rank&&(s=Wi(e,[1,e.shape[0],e.shape[1],e.shape
|
|
|
4097
4097
|
* See the License for the specific language governing permissions and
|
|
4098
4098
|
* limitations under the License.
|
|
4099
4099
|
* =============================================================================
|
|
4100
|
-
*/const Vu={kernelName:Ie,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,i]=t;return{a:()=>Ia(n),b:()=>Ia(i)}}},Ku={kernelName
|
|
4100
|
+
*/const Vu={kernelName:Ie,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,i]=t;return{a:()=>Ia(n),b:()=>Ia(i)}}},Ku={kernelName:$e,gradFunc:e=>({x:()=>hi(e,"float32")})},qu={kernelName:"IsFinite",gradFunc:e=>({x:()=>Ia(e)})},Hu={kernelName:"IsInf",gradFunc:e=>({x:()=>Ia(e)})},Ju={kernelName:"IsNan",gradFunc:e=>({x:()=>Ia(e)})},Zu={kernelName:Ce,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[i]=t,{alpha:a}=n,s=Za(i,0);return{x:()=>Ta(s,e,Ei(e,a))}}},Yu={kernelName:Ae,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Ai(e,$i(n,1))}}},Qu={kernelName:"Log",inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Ai(e,hi(n,"float32"))}}},Xu={kernelName:"LogSoftmax",inputsToSave:[],outputsToSave:[!0],gradFunc:(e,t,n)=>{const[i]=t,{axis:a}=n;return{logits:()=>{const t=Ga(i);return ss(e,Ei(Ba(e,a,!0),t))}}}};
|
|
4101
4101
|
/**
|
|
4102
4102
|
* @license
|
|
4103
4103
|
* Copyright 2020 Google LLC. All Rights Reserved.
|
|
@@ -4311,7 +4311,7 @@ function(e,t,n){const i=e.shape.slice();i[n]=1;const a=Wi(t,i),s=wa(e,n,!0,!1),r
|
|
|
4311
4311
|
* limitations under the License.
|
|
4312
4312
|
* =============================================================================
|
|
4313
4313
|
*/
|
|
4314
|
-
const mh=[tu,nu,iu,au,su,ru,ou,lu,cu,uu,hu,pu,mu,gu,vu,yu,bu,wu,ku,xu,Su,Nu,Iu,Tu,Au
|
|
4314
|
+
const mh=[tu,nu,iu,au,su,ru,ou,lu,cu,uu,hu,pu,mu,gu,vu,yu,bu,wu,ku,xu,Su,Nu,Iu,Tu,Cu,Au,Eu,ju,zu,Du,{kernelName:be,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,i]=t,a=wi(n.shape,i.shape);return{a:()=>{const t=Ai(e,hi(i,"float32")),s=bi(n.shape,a);return s.length>0?Wi(Ba(t,s),n.shape):t},b:()=>{let t=Ei(e,hi(n,"float32"));const s=bi(i.shape,a);s.length>0&&(t=Wi(Ba(t,s),i.shape));const r=Pa(i);return fi(Ai(t,hi(r,"float32")))}}}},Fu,_u,Ru,Lu,Mu,Pu,Ou,Bu,Uu,Vu,Ku,qu,Hu,Ju,Zu,Yu,Qu,Xu,th,ih,ih,ah,rh,lh,{kernelName:De,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[i]=t,{axis:a}=n,s=z(a,i.shape),r=C(ja(i.shape,s)[1]);return{x:()=>{const t=i.shape.slice();s.forEach((e=>{t[e]=1}));const n=Wi(e,t);return Ai(Ei(n,fs(i.shape,"float32")),r)}}}},{kernelName:"Min",inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const i=n,{axis:a}=i,[s,r]=t,o=nh(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:()=>Ei(e,hi(es(n,i),"float32")),b:()=>Ei(e,hi(Za(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:()=>Ji(e,s,i.shape)}}},{kernelName:"Mod",inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,i]=t,a=wi(n.shape,i.shape);return{a:()=>{const t=bi(n.shape,a);return t.length>0?Wi(Ba(e,t),n.shape):e},b:()=>{const t=Ei(e,fi(Ha(Ai(n,i)))),s=bi(i.shape,a);return s.length>0?Wi(Ba(t,s),i.shape):t}}}},{kernelName:_e,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,i]=t,a=wi(n.shape,i.shape);return{a:()=>{const t=Ei(e,hi(i,"float32")),s=bi(n.shape,a);return s.length>0?Wi(Ba(t,s),n.shape):t},b:()=>{const t=Ei(e,hi(n,"float32")),s=bi(i.shape,a);return s.length>0?Wi(Ba(t,s),i.shape):t}}}},{kernelName:"Neg",gradFunc:e=>({x:()=>fi(e)})},{kernelName:Le,inputsToSave:["indices"],gradFunc:(e,t)=>{const n=t[0];return{indices:()=>ms(n.shape,"float32")}}},{kernelName:Re,gradFunc:e=>({x:()=>Ia(e)})},{kernelName:Me,saveAllInputs:!0,gradFunc:(e,t,n)=>{const{axis:i}=n;return rr(e,i).map((e=>()=>e))}},ch,ch,uh,{kernelName:Pe,inputsToSave:["x","alpha"],gradFunc:(e,t)=>{const[n,i]=t,a=Za(n,0);return{x:()=>Ta(a,e,Ei(e,i)),alpha:()=>{let t=Ta(a,Ia(e),Ei(e,n));const s=bi(i.shape,e.shape);return s.length>0&&(t=Ba(t,s)),Wi(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:()=>hh(i,e,s)}}},{kernelName:"Reciprocal",inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Ai(e,fi(Pa(n)))}}},{kernelName:Ve,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t,i=Ei(es(n,6),tr(n));return{x:()=>Ei(e,hi(i,"float32"))}}},{kernelName:Be,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Ei(e,hi(tr(n),"float32"))}}},{kernelName:Ue,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Wi(e,n.shape)}}},{kernelName:Ge,inputsToSave:["images"],gradFunc:(e,t,n)=>{const[i]=t,a={dy:e,images:i};return{images:()=>cn.runKernel("ResizeBilinearGrad",a,n)}}},{kernelName:We,inputsToSave:["images"],gradFunc:(e,t,n)=>{const[i]=t,a={dy:e,images:i};return{images:()=>cn.runKernel("ResizeNearestNeighborGrad",a,n)}}},{kernelName:Ke,gradFunc:(e,t,n)=>{const{dims:i}=n,a=z(i,e.shape);return{x:()=>Ps(e,a)}}},{kernelName:qe,gradFunc:e=>({x:()=>Ia(e)})},{kernelName:He,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>fi(Ai(e,Ei(La(n,1.5),2)))}}},{kernelName:Je,inputsToSave:["condition"],gradFunc:(e,t)=>{const[n]=t;return{condition:()=>hi(Ia(n),"float32"),t:()=>Ei(e,hi(n,e.dtype)),e:()=>Ei(e,hi(cs(n),e.dtype))}}},{kernelName:Ze,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const t=Za(n,Ma(0)),i=Ma(1.7580993408473768),a=Ma(1.0507009873554805),s=Ei(e,a),r=Ei(Ei(e,i),Ga(hi(n,"float32")));return Ta(t,s,r)}}}},{kernelName:Xe,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Ei(e,Ei(n,ss(Ma(1),n)))}}},{kernelName:"Sign",gradFunc:e=>({x:()=>Ia(e)})},{kernelName:"Sin",inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Ei(ya(hi(n,"float32")),e)}}},{kernelName:Qe,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Ei(ba(hi(n,"float32")),e)}}},{kernelName:Ye,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[i]=t,{begin:a,size:s}=n,r=i.shape,[o,l]=ki(i,a,s),c=[];for(let t=0;t<e.rank;t++)c.push([o[t],r[t]-o[t]-l[t]]);return{x:()=>ws(e,c)}}},{kernelName:st,outputsToSave:[!0],gradFunc:(e,t,n)=>{const[i]=t,{dim:a}=n,s=Ei(e,i);return{logits:()=>ss(s,Ei(Ba(s,[a],true),i))}}},{kernelName:et,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Ei(e,Hi(n))}}},ph,ph,dh,dh,{kernelName:tt,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Ai(e,Ei(Oa(hi(n,"float32")),2))}}},{kernelName:rt,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,i]=t,a=Ma(2);return{a:()=>Ei(e,Ei(a,ss(n,i))),b:()=>Ei(e,Ei(a,ss(i,n)))}}},{kernelName:"Square",inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Ei(e,Ei(hi(n,"float32"),2))}}},{kernelName:dt,gradFunc:e=>({x:()=>Ia(e)})},{kernelName:"Sub",inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,i]=t,a=wi(n.shape,i.shape);return{a:()=>{let t=e;const i=bi(n.shape,a);return i.length>0&&(t=Ba(t,i)),Wi(t,n.shape)},b:()=>{let t=e;const n=bi(i.shape,a);return n.length>0&&(t=Ba(t,n)),Wi(fi(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=Wi(e,a),o=Ei(r,fs(i.shape,"float32"));return{x:()=>o}}},{kernelName:"Tan",inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Ai(e,Pa(ya(n)))}}},{kernelName:ot,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Ei(ss(Ma(1),Pa(n)),e)}}},{kernelName:lt,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[i]=t,{reps:a}=n;return{x:()=>{let t=Ia(i);if(1===i.rank)for(let n=0;n<a[0];++n)t=$i(t,Ji(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=$i(t,Ji(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=$i(t,Ji(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=$i(t,Ji(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=Fa(a);return{x:()=>vi(e,s)}}},{kernelName:ut,gradFunc:(e,t,n)=>{const i=n,{axis:a}=i;return{value:()=>er(e,a)}}},{kernelName:ht,inputsToSave:["segmentIds"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>function(e,t){const n=ps(t,Ia(t)),i=Ja(e,n);let a=Ya(t,Ma(0,"int32"));const s=i.rank-a.rank;for(let e=0;e<s;++e)a=Va(a,e+1);a=ls(a,fs(i.shape,"bool"));const r=Ia(i);return Ta(a,i,r)}(e,n)}}},{kernelName:pt,gradFunc:e=>({x:()=>Ia(e)})}];
|
|
4315
4315
|
/**
|
|
4316
4316
|
* @license
|
|
4317
4317
|
* Copyright 2020 Google LLC. All Rights Reserved.
|
|
@@ -4336,7 +4336,7 @@ const mh=[tu,nu,iu,au,su,ru,ou,lu,cu,uu,hu,pu,mu,gu,vu,yu,bu,wu,ku,xu,Su,Nu,Iu,T
|
|
|
4336
4336
|
* license that can be found in the LICENSE file or at
|
|
4337
4337
|
* https://opensource.org/licenses/MIT.
|
|
4338
4338
|
* =============================================================================
|
|
4339
|
-
*/function fh(e,t){return Tn((()=>Oa(Ba(Ei(e,e),t,!0))))}class gh extends Ni{getConfig(){return{}}}class vh extends gh{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 Tn((()=>{const t=fh(e,this.axis),n=ra(t,0,this.maxValue);return Ei(e,$i(
|
|
4339
|
+
*/function fh(e,t){return Tn((()=>Oa(Ba(Ei(e,e),t,!0))))}class gh extends Ni{getConfig(){return{}}}class vh extends gh{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 Tn((()=>{const t=fh(e,this.axis),n=ra(t,0,this.maxValue);return Ei(e,Ai(n,$i(Kl(),t)))}))}getConfig(){return{maxValue:this.maxValue,axis:this.axis}}}vh.className="MaxNorm",Ii(vh);class yh extends gh{constructor(e){super(),this.defaultAxis=0,this.axis=null!=e.axis?e.axis:this.defaultAxis}apply(e){return Tn((()=>Ai(e,$i(Kl(),fh(e,this.axis)))))}getConfig(){return{axis:this.axis}}}yh.className="UnitNorm",Ii(yh);class bh extends gh{apply(e){return Ms(e)}}bh.className="NonNeg",Ii(bh);class wh extends gh{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 Tn((()=>{const t=fh(e,this.axis),n=$i(Ei(this.rate,ra(t,this.minValue,this.maxValue)),Ei(1-this.rate,t));return Ei(e,Ai(n,$i(Kl(),t)))}))}getConfig(){return{minValue:this.minValue,maxValue:this.maxValue,rate:this.rate,axis:this.axis}}}wh.className="MinMaxNorm",Ii(wh);const kh={maxNorm:"MaxNorm",minMaxNorm:"MinMaxNorm",nonNeg:"NonNeg",unitNorm:"UnitNorm"};function xh(e){return hl(e)}function Sh(e,t={}){return dl(e,Ti.getMap().classNameMap,t,"constraint")}function Nh(e){if(null==e)return null;if("string"==typeof e){return Sh({className:e in kh?kh[e]:e,config:{}})}return e instanceof gh?e:Sh(e)}
|
|
4340
4340
|
/**
|
|
4341
4341
|
* @license
|
|
4342
4342
|
* Copyright 2018 Google LLC
|
|
@@ -4354,7 +4354,7 @@ const mh=[tu,nu,iu,au,su,ru,ou,lu,cu,uu,hu,pu,mu,gu,vu,yu,bu,wu,ku,xu,Su,Nu,Iu,T
|
|
|
4354
4354
|
* license that can be found in the LICENSE file or at
|
|
4355
4355
|
* https://opensource.org/licenses/MIT.
|
|
4356
4356
|
* =============================================================================
|
|
4357
|
-
*/var
|
|
4357
|
+
*/var $h;!function(e){e[e.SILENT=0]="SILENT",e[e.VERBOSE=1]="VERBOSE"}($h||($h={}));class Ch{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 Ah{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 Eh extends Ch{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=Tn((()=>$i(this.totals[e],Ei(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:Tn((()=>{const n=Ei(Ai(1,this.seen),this.totals[e]);t[e]=n,this.totals[e].dispose(),$n(t[e])})))}}class jh extends Ch{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 zh extends Ch{constructor(e,t){if(super(),this.currentEpoch=0,this.nowFunc=e.nowFunc,this.nextFrameFunc=e.nextFrameFunc||no,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():$t();return(...s)=>{const r=null!=n?n():$t();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 Th(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 Th(t),await this.epochBegin(e,t))}async onEpochEnd(e,t){const n=[];null!=this.epochEnd&&(await Th(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 Th(t),await this.batchBegin(e,t))}async onBatchEnd(e,t){const n=[];null!=this.batchEnd&&(await Th(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 Th(e),await this.trainBegin(e))}async onTrainEnd(e){null!=this.trainEnd&&(await Th(e),await this.trainEnd(e))}}function Dh(e,t){if(null==e&&(e={}),e instanceof Ch)return[e];if(Array.isArray(e)&&e[0]instanceof Ch)return e;return ol(e).map((e=>new zh(e,t)))}class Fh{constructor(){}static registerCallbackConstructor(e,t){T(e>=0&&Number.isInteger(e),(()=>`Verbosity level is expected to be an integer >= 0, but got ${e}`)),Fh.checkForDuplicate(t),null==Fh.constructors[e]&&(Fh.constructors[e]=[]),Fh.constructors[e].push(t)}static checkForDuplicate(e){for(const t in Fh.constructors){Fh.constructors[+t].forEach((t=>{if(t===e)throw new Xo("Duplicate callback constructor.")}))}}static clear(){Fh.constructors={}}static createCallbacks(e){const t=[];for(const n in Fh.constructors){const i=+n;e>=i&&t.push(...Fh.constructors[i])}return t.map((e=>new e))}}function _h(e,t,n,i,a,s,r,o,l){const c=new jh,u=[new Eh,...Fh.createCallbacks(t)];null!=e&&u.push(...e),u.push(c);const h=new Ah(u);return h.setParams({epochs:n,initialEpoch:i,samples:a,steps:s,batchSize:r,verbose:t,doValidation:o,metrics:l}),{callbackList:h,history:c}}
|
|
4358
4358
|
/**
|
|
4359
4359
|
* @license
|
|
4360
4360
|
* Copyright 2018 Google LLC
|
|
@@ -4372,7 +4372,7 @@ const mh=[tu,nu,iu,au,su,ru,ou,lu,cu,uu,hu,pu,mu,gu,vu,yu,bu,wu,ku,xu,Su,Nu,Iu,T
|
|
|
4372
4372
|
* license that can be found in the LICENSE file or at
|
|
4373
4373
|
* https://opensource.org/licenses/MIT.
|
|
4374
4374
|
* =============================================================================
|
|
4375
|
-
*/function Lh(e,t){return Tn((()=>{"float32"!==e.dtype&&(e=hi(e,"float32"));const n=Ba(ac(e),t,!0),i=sa(n.shape,Kl()),a=Oa(ps(n,i));return
|
|
4375
|
+
*/function Lh(e,t){return Tn((()=>{"float32"!==e.dtype&&(e=hi(e,"float32"));const n=Ba(ac(e),t,!0),i=sa(n.shape,Kl()),a=Oa(ps(n,i));return Ai(e,a)}))}function Mh(e,t){return Tn((()=>ds(ac(ss(t,e)),-1)))}function Oh(e,t){return Tn((()=>ds(ji(ss(t,e)),-1)))}function Ph(e,t){return Tn((()=>{const n=ss(e,t),i=ra(ji(e),Kl(),Number.MAX_VALUE),a=ji(Ai(n,i));return Ei(100,ds(a,-1))}))}function Bh(e,t,n=!1){return Tn((()=>{if(n)t=Ys(t);else{const e=Ba(t,t.shape.length-1,!0);t=Ai(t,e)}return t=ra(t,Kl(),1-Kl()),fi(Ba(Ei(hi(e,"float32"),ts(t)),t.shape.length-1))}))}function Uh(e,t,n=!1){return Tn((()=>{const i=hi(Ha(function(e){const t=[Bl(e.shape)];return Wi(e,t)}(e)),"int32"),a=(t=ra(t,Kl(),1-Kl())).shape;return Bh(Wi(di(i,a[a.length-1]),a),t,n)}))}function Wh(e,t){return Tn((()=>{let n;return n=ra(t,Kl(),1-Kl()),n=ts(Ai(n,ss(1,n))),ds(function(e,t){if(!A(e.shape,t.shape))throw new Xo(`logits and labels must have the same shape, but got shapes ${JSON.stringify(e.shape)} and ${JSON.stringify(t.shape)}`);return Tn((()=>{const n=Ms(t),i=fi(ji(t));return $i(ss(n,Ei(t,e)),ns(Ga(i)))}))}(e,n),-1)}))}function Gh(e,t){return Tn((()=>{const n=Lh(e,-1),i=Lh(t,-1),a=Ei(n,i);return fi(Ba(a,-1))}))}Fh.constructors={};const Vh={meanSquaredError:Mh,meanAbsoluteError:Oh,meanAbsolutePercentageError:Ph,meanSquaredLogarithmicError:function(e,t){return Tn((()=>{const n=ra(t,Kl(),Number.MAX_VALUE),i=ts($i(1,n)),a=ra(e,Kl(),Number.MAX_VALUE),s=ts($i(1,a));return ds(ac(ss(i,s)),-1)}))},squaredHinge:function(e,t){return Tn((()=>{const n=ps(0,ss(1,Ei(e,t)));return ds(ac(n),-1)}))},hinge:function(e,t){return Tn((()=>{const n=ps(0,ss(1,Ei(e,t)));return ds(n,-1)}))},categoricalHinge:function(e,t){return Tn((()=>{const n=Ba(Ei(e,t),-1),i=_a(Ei(ss(1,e),t),-1);return ps(0,$i(1,ss(i,n)))}))},logcosh:function(e,t){return Tn((()=>{const n=Math.log(2),i=ss(t,e),a=ss($i(i,as(Ei(-2,i))),n);return ds(a,-1)}))},categoricalCrossentropy:Bh,sparseCategoricalCrossentropy:Uh,binaryCrossentropy:Wh,kullbackLeiblerDivergence:function(e,t){return Tn((()=>{const n=ra(e,Kl(),1),i=ra(t,Kl(),1);return Ba(Ei(e,ts(Ai(n,i))),-1)}))},poisson:function(e,t){return Tn((()=>{const n=ts($i(Kl(),t));return ds(ss(t,Ei(e,n)),-1)}))},cosineProximity:Gh};function Kh(e){if("string"==typeof e){if(e in Vh)return Vh[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 Xo(t)}return e}
|
|
4376
4376
|
/**
|
|
4377
4377
|
* @license
|
|
4378
4378
|
* Copyright 2018 Google LLC
|
|
@@ -4381,7 +4381,7 @@ const mh=[tu,nu,iu,au,su,ru,ou,lu,cu,uu,hu,pu,mu,gu,vu,yu,bu,wu,ku,xu,Su,Nu,Iu,T
|
|
|
4381
4381
|
* license that can be found in the LICENSE file or at
|
|
4382
4382
|
* https://opensource.org/licenses/MIT.
|
|
4383
4383
|
* =============================================================================
|
|
4384
|
-
*/function qh(e,t){return Tn((()=>{const n=Ei(.5,bs(t)),i=ql(Za(t,n),e.dtype);return ds(Na(e,i),-1)}))}function Hh(e,t){return Tn((()=>ql(Na(Fi(e,-1),Fi(t,-1)),"float32")))}function Jh(e,t){return Wh(e,t)}function Zh(e,t){return e.rank===t.rank&&(e=Xs(e,[e.rank-1])),(t=Fi(t,-1)).dtype!==e.dtype&&(t=hi(t,e.dtype)),hi(Na(e,t),"float32")}const Yh=Bh,Qh=Uh,Xh={binaryAccuracy:qh,categoricalAccuracy:Hh,precision:function(e,t){return Tn((()=>{const n=function(e,t){return Tn((()=>hi(Ba(ls(Na(e,1),Na(t,1))),"float32")))}(e,t),i=function(e,t){return Tn((()=>hi(Ba(ls(Na(e,0),Na(t,1))),"float32")))}(e,t),a
|
|
4384
|
+
*/function qh(e,t){return Tn((()=>{const n=Ei(.5,bs(t)),i=ql(Za(t,n),e.dtype);return ds(Na(e,i),-1)}))}function Hh(e,t){return Tn((()=>ql(Na(Fi(e,-1),Fi(t,-1)),"float32")))}function Jh(e,t){return Wh(e,t)}function Zh(e,t){return e.rank===t.rank&&(e=Xs(e,[e.rank-1])),(t=Fi(t,-1)).dtype!==e.dtype&&(t=hi(t,e.dtype)),hi(Na(e,t),"float32")}const Yh=Bh,Qh=Uh,Xh={binaryAccuracy:qh,categoricalAccuracy:Hh,precision:function(e,t){return Tn((()=>{const n=function(e,t){return Tn((()=>hi(Ba(ls(Na(e,1),Na(t,1))),"float32")))}(e,t),i=function(e,t){return Tn((()=>hi(Ba(ls(Na(e,0),Na(t,1))),"float32")))}(e,t),a=$i(n,i);return hi(Ta(Za(a,0),Ai(n,a),0),"float32")}))},categoricalCrossentropy:Yh,sparseCategoricalCrossentropy:Qh,mse:Mh,MSE:Mh,mae:Oh,MAE:Oh,mape:Ph,MAPE:Ph,cosine:Gh};function ep(e){if("string"==typeof e&&e in Xh)return Xh[e];if("string"!=typeof e&&null!=e)return e;throw new Xo(`Unknown metric ${e}`)}function tp(e){if(al(null!==e,`Unknown LossOrMetricFn ${e}`),"string"==typeof e)return e;{let t;for(const n of Object.keys(Vh))if(Vh[n]===e){t=n;break}if(void 0!==t)return t;for(const n of Object.keys(Xh))if(Xh[n]===e){t=n;break}return void 0!==t?t:e.name}}
|
|
4385
4385
|
/**
|
|
4386
4386
|
* @license
|
|
4387
4387
|
* Copyright 2018 Google LLC
|
|
@@ -4446,7 +4446,7 @@ const np=1048576;function ip(e,t,n=!1){if(null==e||"object"!=typeof e||Object.ge
|
|
|
4446
4446
|
* license that can be found in the LICENSE file or at
|
|
4447
4447
|
* https://opensource.org/licenses/MIT.
|
|
4448
4448
|
* =============================================================================
|
|
4449
|
-
*/function vp(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=yp("input",e.inputNames,n),r=yp("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 yp(e,t,n){if(n instanceof Wt)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 Xo(`The feature data generated by the dataset lacks the required ${e} key '${a}'.`);i.push(n[a])}return i}}async function bp(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(wp(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 el("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=Dh(n.callbacks,n.yieldEvery),h=null==n.verbose?1:n.verbose,{callbackList:p,history:d}=_h(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}=vp(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=mp(n.classWeight,e.outputNames);for(let e=0;e<t.length;++e)r.push(await fp(a[e],null,t[e]))}const c=i.concat(a).concat(r),d=o(c);In(c);for(let e=0;e<l.length;++e){const t=l[e],n=d[e];s[t]=n
|
|
4449
|
+
*/function vp(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=yp("input",e.inputNames,n),r=yp("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 yp(e,t,n){if(n instanceof Wt)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 Xo(`The feature data generated by the dataset lacks the required ${e} key '${a}'.`);i.push(n[a])}return i}}async function bp(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(wp(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 el("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=Dh(n.callbacks,n.yieldEvery),h=null==n.verbose?1:n.verbose,{callbackList:p,history:d}=_h(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}=vp(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=mp(n.classWeight,e.outputNames);for(let e=0;e<t.length;++e)r.push(await fp(a[e],null,t[e]))}const c=i.concat(a).concat(r),d=o(c);In(c);for(let e=0;e<l.length;++e){const t=l[e],n=d[e];s[t]=n,$n(n)}await p.onBatchEnd(h,s),Ih(s),h++,u++}if(i?u>=n.batchesPerEpoch:t.done){if(a){let t;t=wp(n.validationData)?ol(await e.evaluateDataset(n.validationData,{batches:n.validationBatches})):ol(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 wp(e){return"function"==typeof e.iterator}
|
|
4450
4450
|
/**
|
|
4451
4451
|
* @license
|
|
4452
4452
|
* Copyright 2018 Google LLC
|
|
@@ -4465,7 +4465,7 @@ function kp(e){T(e>0&&Number.isInteger(e),(()=>`batchSize is required to be a po
|
|
|
4465
4465
|
* license that can be found in the LICENSE file or at
|
|
4466
4466
|
* https://opensource.org/licenses/MIT.
|
|
4467
4467
|
* =============================================================================
|
|
4468
|
-
*/function Cp(e){return Array.isArray(e)}function Ap(e){return!function(e){return e instanceof Wt}(e)&&!Cp(e)}function $p(e,t,n,i=!0,a=""){if(null==t||0===t.length){if(null!=e){let t=!1;if(Cp(e)&&e.length>0)t=!0;else if(Ap(e)){for(const n in e)if(e.hasOwnProperty(n)){t=!0;break}}else t=!0;if(t)throw new Xo(`Error when checking model ${a} expected no data, but got ${e}`)}return[]}if(null==e)return t.map((e=>null));let s;if(Ap(e)){s=[];for(const n of t){if(null==e[n])throw new Xo(`No data provided for "${n}". Need data for each key in: ${t}`);s.push(e[n])}}else if(Cp(e)){if(e.length!==t.length)throw new Xo(`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 Xo(`The model ${a} expects ${t.length} Tensor(s), but only received one Tensor. Found: Tensor with shape ${e.shape}`);s=[e]}if(s=Tp(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 Xo(`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 Xo(`${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 Ep(e,t,n,i=!0,a=""){let s;if(Array.isArray(e)){if(e.length!==t.length)throw new Xo(`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 Xo(`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 Xo(`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 Xo(`Error when checking ${a}: expected ${t[e]} to have shape ${JSON.stringify(n[e])} but got array with shape ${JSON.stringify(r.shape)}.`)}}}class jp extends dp{constructor(e){super(e),this.isTraining=!1}summary(e,t,n=console.log){if(!this.built)throw new Xo("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).");sp(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:()=>eo.adagrad(.01),Adadelta:()=>eo.adadelta(1,.95,Kl()),Adam:()=>eo.adam(.001,.9,.999,Kl()),Adamax:()=>eo.adamax(.002,.9,.999,Kl(),0),RMSProp:()=>eo.rmsprop(.001,.9,0,Kl()),SGD:()=>eo.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 Xo(`Unknown Optimizer ${e}`)}(e.optimizer),this.isOptimizerOwned=!0;else{if(!(e.optimizer instanceof Kr))throw new Xo("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 Xo(`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=>Kh(e)))}else{const n=Kh(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 Xo(`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(Kh(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=[],Rl("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])};Rl("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]===Wh?-1!==["accuracy","acc"].indexOf(r)?i=qh:-1!==["crossentropy","ce"].indexOf(r)&&(i=Jh):this.lossFunctions[e]===Uh?-1!==["accuracy","acc"].indexOf(r)?i=Zh:-1!==["crossentropy","ce"].indexOf(r)&&(i=Qh):-1!==["accuracy","acc"].indexOf(r)?i=Hh:-1!==["crossentropy","ce"].indexOf(r)&&(i=Yh),-1!==["accuracy","acc"].indexOf(r)?a="acc":-1!==["crossentropy","ce"].indexOf(r)&&(a="ce"),s=i,n=""+a}else{const e=ep(r);s=e,n=""+tp(r)}let t;Rl(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;kp(i);const a=this.standardizeUserDataXY(e,t,!0,i);try{const s=a[0].concat(a[1]);this.makeTestFunction();const r=this.testFunction;return rl(this.testLoop(r,s,i,n.verbose,n.steps))}finally{Ip(a[0],e),Ip(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 el("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=Tn((()=>{if(t.value){const{xs:n,ys:i}=vp(e,t.value),r=n.concat(i),c=Tn((()=>a(r)));if(In(r),0===l)for(let e=0;e<c.length;++e)s.push(Ma(0));const u=r[0].shape[0];for(let e=0;e<c.length;++e){const t=c[e],n=s[e];s[e]=Tn((()=>Ci(s[e],Ei(u,t)))),l>0&&In(n)}In(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]=$i(s[e],o),In(t)}return rl(s)}(this,e,t)}checkNumSamples(e,t,n,i="steps"){let a;if(null!=n){if(a=null,null!=t)throw new Xo(`If ${i} is set, batchSize must be null or undefined.Got batchSize = ${t}`)}else{if(null==e)throw new Xo(`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 Xo("`outputs` is an empty Array, which is not allowed.");const n=Array.isArray(t),i=n?t:[t],a=this.retrieveSymbolicTensors(i),s=new Hc;if(e instanceof Wt&&(e=[e]),Array.isArray(e)){if(e.length!==this.inputs.length)throw new Xo(`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 Xo(`No value is provided for the model's input ${t.name}`);s.add(t,n)}const r=Yc(a,s);return n?r:r[0]}retrieveSymbolicTensors(e){const t=il(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 Xo(`Cannot find SymbolicTensors for output name(s): ${JSON.stringify(n)}`)}return t}predictLoop(e,t=32,n=!1){return Tn((()=>{const i=this.checkNumSamples(e);if(n)throw new el("Verbose predictLoop() is not implemented yet.");const a=Np(i,t),s=this.outputs.map((e=>[]));for(let t=0;t<a.length;++t){Tn((()=>{const n=a[t][0],i=a[t][1],s=xp(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 Hc(r);return Yc(this.outputs,o)})).forEach(((e,t)=>s[t].push(e)))}return rl(s.map((e=>qi(e,0))))}))}predict(e,t={}){const n=Tp(e);Ep(n,this.inputNames,this.feedInputShapes,!1);try{const i=null==t.batchSize?32:t.batchSize;return kp(i),this.predictLoop(n,i)}finally{Ip(n,e)}}predictOnBatch(e){Ep(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 Qo("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]===Uh?a.push(t.slice(0,t.length-1).concat([1])):a.push(t)}if(function(e,t,n){const i=fl(e.map((e=>e.shape[0])));i.sort();const a=fl(t.map((e=>e.shape[0])));if(a.sort(),i.length>1)throw new Xo(`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 Xo(`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&&!$(i,a))throw new Xo(`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=$p(e,this.feedInputNames,this.feedInputShapes,!1,"input"),t=$p(t,this.feedOutputNames,a,!1,"target")),function(e,t,n){const i=[Mh,Wh,Bh];for(let a=0;a<e.length;++a){const s=e[a],r=t[a],o=n[a];if(null!=r){if(r===Bh&&1===s.shape[s.shape.length-1])throw new Xo(`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 Xo(`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 Xo(`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=mp(i,this.outputNames);l=[];for(let t=0;t<e.length;++t)l.push(await fp(o[t],null,e[t]))}return[r,o,l]}testLoop(e,t,n,i=0,a){return Tn((()=>{const s=this.checkNumSamples(t,n,a,"steps"),r=[];if(i>0)throw new el("Verbose mode is not implemented yet.");if(null!=a)throw new el("steps mode in testLoop() is not implemented yet");{const i=Np(s,n),a=nr(Gl(0,s));for(let n=0;n<i.length;++n){const s=i[n][0],o=i[n][1],l=Jl(a,s,o-s),c=Sp(t,l),u=e(c);if(0===n)for(let e=0;e<u.length;++e)r.push(Ma(0));for(let e=0;e<u.length;++e){const t=u[e];r[e]=Ci(r[e],Ei(o-s,t))}}for(let e=0;e<r.length;++e)r[e]=$i(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(sl(e,i)>1){a+=`_${sl(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 Hc(e),o=Yc(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=gp(n,a[e]));const s=ds(n);t.push(s),l=0===e?n:Ci(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=ds(t(i[a],o[a]))}Cn(n),s.push(n)}return l=ds(l),this.calculateLosses().forEach((e=>{l=Ci(l,e)})),l}),!0,r)].concat(s)}}makeTestFunction(){this.testFunction=e=>Tn((()=>{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 Hc(s),o=Yc(this.outputs,r);for(let e=0;e<this.lossFunctions.length;++e){const i=this.lossFunctions[e],s=ds(i(a[e],o[e]));n=0===e?s:Ci(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=ds(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;kp(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 el("validationData including sample weights is not supported yet."):new Xo(`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=xp(i,e,t),s=i,i=xp(i,0,e),u=xp(a,e,t),r=a,a=xp(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=Dh(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,Ip(i,e),Ip(a,t),Ip(s,e),Ip(r,t),Ip(c,o),Ip(u,l),null!=h&&In(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 Xo("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=Gl(0,f)),null==s&&(s=1);const{callbackList:v,history:y}=_h(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 el("stepsPerEpoch mode is not implemented yet.");{if("batch"===c)throw new el("batch shuffling is not implemneted yet");c&&S(g);const s=nr(g),r=Np(f,i);for(let c=0;c<r.length;++c){const u={};if(await v.onBatchBegin(c,u),Tn((()=>{const h=r[c][0],p=r[c][1],d=Jl(s,h,p-h);u.batch=c,u.size=p-h;const f=Sp(t,d),g=e(f);for(let e=0;e<n.length;++e){const t=n[e],i=g[e];u[t]=i,Cn(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];Cn(s),a["val_"+i]=s}}})),await v.onBatchEnd(c,u),Ih(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 bp(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 In(s),Ip(n[0],e),Ip(n[1],t),rl(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=Nn().numTensors;this.optimizer_.dispose(),e.numDisposedVariables+=t-Nn().numTensors}return e}getLossIdentifiers(){let e;if("string"==typeof this.loss)e=ll(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=>ll(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]=ll(n[i])}}return e}getMetricIdentifiers(){if("string"==typeof this.metrics||"function"==typeof this.metrics)return[ll(tp(this.metrics))];if(Array.isArray(this.metrics))return this.metrics.map((e=>ll(tp(e))));{const e={};for(const t in this.metrics)e[t]=ll(tp(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=Rh(up(e.optimizer_config));let n,i;if("string"==typeof e.loss)n=cl(e.loss);else if(Array.isArray(e.loss))n=e.loss.map((e=>cl(e)));else if(null!=e.loss){n={};for(const t in e.loss)n[t]=cl(e.loss[t])}if(Array.isArray(e.metrics))i=e.metrics.map((e=>cl(e)));else if(null!=e.metrics){i={};for(const t in e.metrics)i[t]=cl(e.metrics[t])}this.compile({loss:n,metrics:i,optimizer:t})}async save(e,t){if("string"==typeof e){const t=(n=e,Ln.getSaveHandlers(n));if(0===t.length)throw new Xo(`Cannot find any save handlers for URL '${e}'`);if(t.length>1)throw new Xo(`Found more than one (${t.length}) save handlers for URL '${e}'`);e=t[0]}var n;if(null==e.save)throw new Xo("LayersModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");const i=await An(this.getNamedWeights(t)),a={modelTopology:this.toJSON(null,!1),format:"layers-model",generatedBy:`TensorFlow.js tfjs-layers v${pp}`,convertedBy:null};if(null!=t&&t.includeOptimizer&&null!=this.optimizer){a.trainingConfig=this.getTrainingConfig();const e="optimizer",{data:t,specs:n}=await An(await this.optimizer.getWeights(),e);i.specs.push(...n),i.data=(s=[i.data,t],xn.join(s))}var s;if(null!=this.userDefinedMetadata){const e=!0;ip(this.userDefinedMetadata,this.name,e),a.userDefinedMetadata=this.userDefinedMetadata}return a.weightData=i.data,a.weightSpecs=i.specs,e.save(a)}setUserDefinedMetadata(e){ip(e,this.name),this.userDefinedMetadata=e}getUserDefinedMetadata(){return this.userDefinedMetadata}}jp.className="Model",Ii(jp);class zp extends jp{}
|
|
4468
|
+
*/function $p(e){return Array.isArray(e)}function Cp(e){return!function(e){return e instanceof Wt}(e)&&!$p(e)}function Ap(e,t,n,i=!0,a=""){if(null==t||0===t.length){if(null!=e){let t=!1;if($p(e)&&e.length>0)t=!0;else if(Cp(e)){for(const n in e)if(e.hasOwnProperty(n)){t=!0;break}}else t=!0;if(t)throw new Xo(`Error when checking model ${a} expected no data, but got ${e}`)}return[]}if(null==e)return t.map((e=>null));let s;if(Cp(e)){s=[];for(const n of t){if(null==e[n])throw new Xo(`No data provided for "${n}". Need data for each key in: ${t}`);s.push(e[n])}}else if($p(e)){if(e.length!==t.length)throw new Xo(`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 Xo(`The model ${a} expects ${t.length} Tensor(s), but only received one Tensor. Found: Tensor with shape ${e.shape}`);s=[e]}if(s=Tp(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 Xo(`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 Xo(`${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 Ep(e,t,n,i=!0,a=""){let s;if(Array.isArray(e)){if(e.length!==t.length)throw new Xo(`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 Xo(`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 Xo(`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 Xo(`Error when checking ${a}: expected ${t[e]} to have shape ${JSON.stringify(n[e])} but got array with shape ${JSON.stringify(r.shape)}.`)}}}class jp extends dp{constructor(e){super(e),this.isTraining=!1}summary(e,t,n=console.log){if(!this.built)throw new Xo("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).");sp(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:()=>eo.adagrad(.01),Adadelta:()=>eo.adadelta(1,.95,Kl()),Adam:()=>eo.adam(.001,.9,.999,Kl()),Adamax:()=>eo.adamax(.002,.9,.999,Kl(),0),RMSProp:()=>eo.rmsprop(.001,.9,0,Kl()),SGD:()=>eo.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 Xo(`Unknown Optimizer ${e}`)}(e.optimizer),this.isOptimizerOwned=!0;else{if(!(e.optimizer instanceof Kr))throw new Xo("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 Xo(`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=>Kh(e)))}else{const n=Kh(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 Xo(`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(Kh(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=[],Rl("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])};Rl("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]===Wh?-1!==["accuracy","acc"].indexOf(r)?i=qh:-1!==["crossentropy","ce"].indexOf(r)&&(i=Jh):this.lossFunctions[e]===Uh?-1!==["accuracy","acc"].indexOf(r)?i=Zh:-1!==["crossentropy","ce"].indexOf(r)&&(i=Qh):-1!==["accuracy","acc"].indexOf(r)?i=Hh:-1!==["crossentropy","ce"].indexOf(r)&&(i=Yh),-1!==["accuracy","acc"].indexOf(r)?a="acc":-1!==["crossentropy","ce"].indexOf(r)&&(a="ce"),s=i,n=""+a}else{const e=ep(r);s=e,n=""+tp(r)}let t;Rl(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;kp(i);const a=this.standardizeUserDataXY(e,t,!0,i);try{const s=a[0].concat(a[1]);this.makeTestFunction();const r=this.testFunction;return rl(this.testLoop(r,s,i,n.verbose,n.steps))}finally{Ip(a[0],e),Ip(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 el("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=Tn((()=>{if(t.value){const{xs:n,ys:i}=vp(e,t.value),r=n.concat(i),c=Tn((()=>a(r)));if(In(r),0===l)for(let e=0;e<c.length;++e)s.push(Ma(0));const u=r[0].shape[0];for(let e=0;e<c.length;++e){const t=c[e],n=s[e];s[e]=Tn((()=>$i(s[e],Ei(u,t)))),l>0&&In(n)}In(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]=Ai(s[e],o),In(t)}return rl(s)}(this,e,t)}checkNumSamples(e,t,n,i="steps"){let a;if(null!=n){if(a=null,null!=t)throw new Xo(`If ${i} is set, batchSize must be null or undefined.Got batchSize = ${t}`)}else{if(null==e)throw new Xo(`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 Xo("`outputs` is an empty Array, which is not allowed.");const n=Array.isArray(t),i=n?t:[t],a=this.retrieveSymbolicTensors(i),s=new Hc;if(e instanceof Wt&&(e=[e]),Array.isArray(e)){if(e.length!==this.inputs.length)throw new Xo(`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 Xo(`No value is provided for the model's input ${t.name}`);s.add(t,n)}const r=Yc(a,s);return n?r:r[0]}retrieveSymbolicTensors(e){const t=il(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 Xo(`Cannot find SymbolicTensors for output name(s): ${JSON.stringify(n)}`)}return t}predictLoop(e,t=32,n=!1){return Tn((()=>{const i=this.checkNumSamples(e);if(n)throw new el("Verbose predictLoop() is not implemented yet.");const a=Np(i,t),s=this.outputs.map((e=>[]));for(let t=0;t<a.length;++t){Tn((()=>{const n=a[t][0],i=a[t][1],s=xp(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 Hc(r);return Yc(this.outputs,o)})).forEach(((e,t)=>s[t].push(e)))}return rl(s.map((e=>qi(e,0))))}))}predict(e,t={}){const n=Tp(e);Ep(n,this.inputNames,this.feedInputShapes,!1);try{const i=null==t.batchSize?32:t.batchSize;return kp(i),this.predictLoop(n,i)}finally{Ip(n,e)}}predictOnBatch(e){Ep(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 Qo("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]===Uh?a.push(t.slice(0,t.length-1).concat([1])):a.push(t)}if(function(e,t,n){const i=fl(e.map((e=>e.shape[0])));i.sort();const a=fl(t.map((e=>e.shape[0])));if(a.sort(),i.length>1)throw new Xo(`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 Xo(`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&&!A(i,a))throw new Xo(`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=Ap(e,this.feedInputNames,this.feedInputShapes,!1,"input"),t=Ap(t,this.feedOutputNames,a,!1,"target")),function(e,t,n){const i=[Mh,Wh,Bh];for(let a=0;a<e.length;++a){const s=e[a],r=t[a],o=n[a];if(null!=r){if(r===Bh&&1===s.shape[s.shape.length-1])throw new Xo(`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 Xo(`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 Xo(`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=mp(i,this.outputNames);l=[];for(let t=0;t<e.length;++t)l.push(await fp(o[t],null,e[t]))}return[r,o,l]}testLoop(e,t,n,i=0,a){return Tn((()=>{const s=this.checkNumSamples(t,n,a,"steps"),r=[];if(i>0)throw new el("Verbose mode is not implemented yet.");if(null!=a)throw new el("steps mode in testLoop() is not implemented yet");{const i=Np(s,n),a=nr(Gl(0,s));for(let n=0;n<i.length;++n){const s=i[n][0],o=i[n][1],l=Jl(a,s,o-s),c=Sp(t,l),u=e(c);if(0===n)for(let e=0;e<u.length;++e)r.push(Ma(0));for(let e=0;e<u.length;++e){const t=u[e];r[e]=$i(r[e],Ei(o-s,t))}}for(let e=0;e<r.length;++e)r[e]=Ai(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(sl(e,i)>1){a+=`_${sl(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 Hc(e),o=Yc(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=gp(n,a[e]));const s=ds(n);t.push(s),l=0===e?n:$i(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=ds(t(i[a],o[a]))}$n(n),s.push(n)}return l=ds(l),this.calculateLosses().forEach((e=>{l=$i(l,e)})),l}),!0,r)].concat(s)}}makeTestFunction(){this.testFunction=e=>Tn((()=>{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 Hc(s),o=Yc(this.outputs,r);for(let e=0;e<this.lossFunctions.length;++e){const i=this.lossFunctions[e],s=ds(i(a[e],o[e]));n=0===e?s:$i(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=ds(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;kp(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 el("validationData including sample weights is not supported yet."):new Xo(`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=xp(i,e,t),s=i,i=xp(i,0,e),u=xp(a,e,t),r=a,a=xp(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=Dh(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,Ip(i,e),Ip(a,t),Ip(s,e),Ip(r,t),Ip(c,o),Ip(u,l),null!=h&&In(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 Xo("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=Gl(0,f)),null==s&&(s=1);const{callbackList:v,history:y}=_h(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 el("stepsPerEpoch mode is not implemented yet.");{if("batch"===c)throw new el("batch shuffling is not implemneted yet");c&&S(g);const s=nr(g),r=Np(f,i);for(let c=0;c<r.length;++c){const u={};if(await v.onBatchBegin(c,u),Tn((()=>{const h=r[c][0],p=r[c][1],d=Jl(s,h,p-h);u.batch=c,u.size=p-h;const f=Sp(t,d),g=e(f);for(let e=0;e<n.length;++e){const t=n[e],i=g[e];u[t]=i,$n(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];$n(s),a["val_"+i]=s}}})),await v.onBatchEnd(c,u),Ih(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 bp(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 In(s),Ip(n[0],e),Ip(n[1],t),rl(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=Nn().numTensors;this.optimizer_.dispose(),e.numDisposedVariables+=t-Nn().numTensors}return e}getLossIdentifiers(){let e;if("string"==typeof this.loss)e=ll(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=>ll(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]=ll(n[i])}}return e}getMetricIdentifiers(){if("string"==typeof this.metrics||"function"==typeof this.metrics)return[ll(tp(this.metrics))];if(Array.isArray(this.metrics))return this.metrics.map((e=>ll(tp(e))));{const e={};for(const t in this.metrics)e[t]=ll(tp(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=Rh(up(e.optimizer_config));let n,i;if("string"==typeof e.loss)n=cl(e.loss);else if(Array.isArray(e.loss))n=e.loss.map((e=>cl(e)));else if(null!=e.loss){n={};for(const t in e.loss)n[t]=cl(e.loss[t])}if(Array.isArray(e.metrics))i=e.metrics.map((e=>cl(e)));else if(null!=e.metrics){i={};for(const t in e.metrics)i[t]=cl(e.metrics[t])}this.compile({loss:n,metrics:i,optimizer:t})}async save(e,t){if("string"==typeof e){const t=(n=e,Ln.getSaveHandlers(n));if(0===t.length)throw new Xo(`Cannot find any save handlers for URL '${e}'`);if(t.length>1)throw new Xo(`Found more than one (${t.length}) save handlers for URL '${e}'`);e=t[0]}var n;if(null==e.save)throw new Xo("LayersModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");const i=await Cn(this.getNamedWeights(t)),a={modelTopology:this.toJSON(null,!1),format:"layers-model",generatedBy:`TensorFlow.js tfjs-layers v${pp}`,convertedBy:null};if(null!=t&&t.includeOptimizer&&null!=this.optimizer){a.trainingConfig=this.getTrainingConfig();const e="optimizer",{data:t,specs:n}=await Cn(await this.optimizer.getWeights(),e);i.specs.push(...n),i.data=(s=[i.data,t],xn.join(s))}var s;if(null!=this.userDefinedMetadata){const e=!0;ip(this.userDefinedMetadata,this.name,e),a.userDefinedMetadata=this.userDefinedMetadata}return a.weightData=i.data,a.weightSpecs=i.specs,e.save(a)}setUserDefinedMetadata(e){ip(e,this.name),this.userDefinedMetadata=e}getUserDefinedMetadata(){return this.userDefinedMetadata}}jp.className="Model",Ii(jp);class zp extends jp{}
|
|
4469
4469
|
/**
|
|
4470
4470
|
* @license
|
|
4471
4471
|
* Copyright 2018 Google LLC
|
|
@@ -4507,7 +4507,7 @@ async function Dp(e,t){if(null==t&&(t={}),"string"==typeof e){const a=(n=e,i=t,L
|
|
|
4507
4507
|
* See the License for the specific language governing permissions and
|
|
4508
4508
|
* limitations under the License.
|
|
4509
4509
|
* =============================================================================
|
|
4510
|
-
*/return async function(e,t,n){null==n&&(n={});if(null==e.load)throw new Xo("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=Rh(up(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 Xo("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=new xn(e),i={};let a=0;for(const e of t){const t
|
|
4510
|
+
*/return async function(e,t,n){null==n&&(n={});if(null==e.load)throw new Xo("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=Rh(up(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 Xo("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=new xn(e),i={};let a=0;for(const e of t){const t=An(e,((e,t)=>n.slice(a+e,a+t)));i[e.name]=En(e,n.slice(a,a+t)),a+=t}return i}(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),In(e),In(t.map((e=>e.tensor)))}return o}(e,void 0,t)}zp.className="Functional",Ii(zp);class Fp extends jp{constructor(e){if(super({inputs:[],outputs:[]}),e=e||{},this.trainable=!0,this.built=!1,this.name=null!=e.name?e.name:Tl("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 Xo(`Negative dimension size caused by adding layer ${e.name} with input shape [${e.inboundNodes[0].inputTensors[0].shape}]`)}add(e){const t=e instanceof Fp||e instanceof jp;let n;if(t){if(n=e,1!==n.outputs.length)throw new Xo("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 Xo("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 Xo("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 Xo("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 qc({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 Xo(`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 Xo("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=Kc(this.outputs[0])}this.inboundNodes=[],new Wc({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:il(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(Fc(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 jp({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 Qo("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 Qo("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 Qo("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 Qo("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 Xo("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 Fp))throw new el(`Sequential.fromConfig called on non-Sequential input: ${r}`);for(const e of a){const t=Rh(e,void 0,i);i&&t.setFastWeightInitDuringBuild(!0),r.add(t)}return r}set stopTraining(e){if(null==this.model)throw new Xo("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 Xo("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}}}Fp.className="Sequential",Ii(Fp);
|
|
4511
4511
|
/**
|
|
4512
4512
|
* @license
|
|
4513
4513
|
* Copyright 2018 Google LLC
|
|
@@ -4517,7 +4517,7 @@ async function Dp(e,t){if(null==t&&(t={}),"string"==typeof e){const a=(n=e,i=t,L
|
|
|
4517
4517
|
* https://opensource.org/licenses/MIT.
|
|
4518
4518
|
* =============================================================================
|
|
4519
4519
|
*/
|
|
4520
|
-
class _p extends Ni{getConfig(){return{}}}class Rp extends _p{apply(e,t=1){return function(e,t=1){if(1!==t)throw new el(`Support for alpha values other than 1 (${t}) is not implemented yet.`);return
|
|
4520
|
+
class _p extends Ni{getConfig(){return{}}}class Rp extends _p{apply(e,t=1){return function(e,t=1){if(1!==t)throw new el(`Support for alpha values other than 1 (${t}) is not implemented yet.`);return Ca(e)}(e,t)}}Rp.className="elu",Ii(Rp);class Lp extends _p{apply(e){return Ws(e)}}Lp.className="selu",Ii(Lp);class Mp extends _p{apply(e){return Ms(e)}}Mp.className="relu",Ii(Mp);class Op extends _p{apply(e){return Tn((()=>gs(6,Ms(e))))}}Op.className="relu6",Ii(Op);class Pp extends _p{apply(e){return e}}Pp.className="linear",Ii(Pp);class Bp extends _p{apply(e){return Hi(e)}}Bp.className="sigmoid",Ii(Bp);class Up extends _p{apply(e){return function(e){return Tn((()=>{const t=$i(.5,Ei(.2,e));return ra(t,0,1)}))}(e)}}Up.className="hardSigmoid",Ii(Up);class Wp extends _p{apply(e){return as(e)}}Wp.className="softplus",Ii(Wp);class Gp extends _p{apply(e){return function(e){return Tn((()=>Ai(e,$i(ji(e),1))))}(e)}}Gp.className="softsign",Ii(Gp);class Vp extends _p{apply(e){return Zi(e)}}Vp.className="tanh",Ii(Vp);class Kp extends _p{apply(e,t=-1){return Ys(e,t)}}Kp.className="softmax",Ii(Kp);class qp extends _p{apply(e,t=-1){return rs(e,t)}}qp.className="logSoftmax",Ii(qp);class Hp extends _p{apply(e){return Tn((()=>Tn((()=>{const t=Math.sqrt(2),n=Ei(.5,$i(1,Aa(Ai(e,t))));return Ei(e,n)}))))}}Hp.className="gelu",Ii(Hp);class Jp extends _p{apply(e){return Tn((()=>Ei(.5,Ei(e,$i(1,Zi(Ei(Oa(Ai(2,Math.PI)),$i(e,Ei(.044715,La(e,3))))))))))}}Jp.className="gelu_new",Ii(Jp);class Zp extends _p{apply(e){return Tn((()=>Ei(e,Zi(as(e)))))}}Zp.className="mish",Ii(Zp);class Yp extends _p{apply(e,t=1){return Tn((()=>Ei(Hi(Ei(e,t)),e)))}}function Qp(e){return e.getClassName()}function Xp(e,t={}){return dl(e,Ti.getMap().classNameMap,t,"activation")}function ed(e){if(null==e){const e={className:"linear",config:{}};return Xp(e)}if("string"==typeof e){const t={};return t.className=e,t.config={},Xp(t)}return e instanceof _p?e:Xp(e)}
|
|
4521
4521
|
/**
|
|
4522
4522
|
* @license
|
|
4523
4523
|
* Copyright 2018 Google LLC
|
|
@@ -4526,7 +4526,7 @@ class _p extends Ni{getConfig(){return{}}}class Rp extends _p{apply(e,t=1){retur
|
|
|
4526
4526
|
* license that can be found in the LICENSE file or at
|
|
4527
4527
|
* https://opensource.org/licenses/MIT.
|
|
4528
4528
|
* =============================================================================
|
|
4529
|
-
*/Yp.className="swish",Ii(Yp);class td extends Ni{}class nd extends td{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 Tn((()=>{let t=ms([1]);return this.hasL1&&(t
|
|
4529
|
+
*/Yp.className="swish",Ii(Yp);class td extends Ni{}class nd extends td{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 Tn((()=>{let t=ms([1]);return this.hasL1&&(t=$i(t,Ba(Ei(this.l1,ji(e))))),this.hasL2&&(t=$i(t,Ba(Ei(this.l2,ac(e))))),Wi(t,[])}))}getConfig(){return{l1:this.l1,l2:this.l2}}static fromConfig(e,t){return new e({l1:t.l1,l2:t.l2})}}nd.className="L1L2",Ii(nd);const id={l1l2:"L1L2"};function ad(e){return hl(e)}function sd(e,t={}){return dl(e,Ti.getMap().classNameMap,t,"regularizer")}function rd(e){if(null==e)return null;if("string"==typeof e){return sd({className:e in id?id[e]:e,config:{}})}return e instanceof td?e:sd(e)}
|
|
4530
4530
|
/**
|
|
4531
4531
|
* @license
|
|
4532
4532
|
* Copyright 2018 Google LLC
|
|
@@ -4535,7 +4535,7 @@ class _p extends Ni{getConfig(){return{}}}class Rp extends _p{apply(e,t=1){retur
|
|
|
4535
4535
|
* license that can be found in the LICENSE file or at
|
|
4536
4536
|
* https://opensource.org/licenses/MIT.
|
|
4537
4537
|
* =============================================================================
|
|
4538
|
-
*/class od extends Vc{constructor(e){super(null==e?{}:e),this.supportsMasking=!0,null!=e&&(this.maxValue=e.maxValue)}call(e,t){e=Dc(e);let n=Ms(e);return null!=this.maxValue&&(n=ra(n,0,this.maxValue)),n}computeOutputShape(e){return e}getConfig(){const e={maxValue:this.maxValue},t=super.getConfig();return Object.assign(e,t),e}}od.className="ReLU",Ii(od);class ld extends Vc{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=Dc(e);return Qa(n,this.alpha)}computeOutputShape(e){return e}getConfig(){const e={alpha:this.alpha},t=super.getConfig();return Object.assign(e,t),e}}ld.className="LeakyReLU",Ii(ld);class cd extends Vc{constructor(e){if(super(null==e?{}:e),this.DEFAULT_ALPHA_INITIALIZER="zeros",null==e&&(e={}),this.supportsMasking=!0,this.alphaInitializer=Ec(e.alphaInitializer||this.DEFAULT_ALPHA_INITIALIZER),this.alphaRegularizer=rd(e.alphaRegularizer),this.alphaConstraint=Nh(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 Xo(`Expected sharedAxes to be a number or an array of numbers, but got ${e.sharedAxes}`);this.sharedAxes=[e.sharedAxes]}}build(e){const t=(e=Fc(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 Pc({ndim:e.length,axes:n})],this.built=!0}call(e,t){return e=Dc(e),xs(e,this.alpha.read())}getConfig(){const e={alphaInitializer
|
|
4538
|
+
*/class od extends Vc{constructor(e){super(null==e?{}:e),this.supportsMasking=!0,null!=e&&(this.maxValue=e.maxValue)}call(e,t){e=Dc(e);let n=Ms(e);return null!=this.maxValue&&(n=ra(n,0,this.maxValue)),n}computeOutputShape(e){return e}getConfig(){const e={maxValue:this.maxValue},t=super.getConfig();return Object.assign(e,t),e}}od.className="ReLU",Ii(od);class ld extends Vc{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=Dc(e);return Qa(n,this.alpha)}computeOutputShape(e){return e}getConfig(){const e={alpha:this.alpha},t=super.getConfig();return Object.assign(e,t),e}}ld.className="LeakyReLU",Ii(ld);class cd extends Vc{constructor(e){if(super(null==e?{}:e),this.DEFAULT_ALPHA_INITIALIZER="zeros",null==e&&(e={}),this.supportsMasking=!0,this.alphaInitializer=Ec(e.alphaInitializer||this.DEFAULT_ALPHA_INITIALIZER),this.alphaRegularizer=rd(e.alphaRegularizer),this.alphaConstraint=Nh(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 Xo(`Expected sharedAxes to be a number or an array of numbers, but got ${e.sharedAxes}`);this.sharedAxes=[e.sharedAxes]}}build(e){const t=(e=Fc(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 Pc({ndim:e.length,axes:n})],this.built=!0}call(e,t){return e=Dc(e),xs(e,this.alpha.read())}getConfig(){const e={alphaInitializer:Ac(this.alphaInitializer),alphaRegularizer:ad(this.alphaRegularizer),alphaConstraint:xh(this.alphaConstraint),sharedAxes:this.sharedAxes},t=super.getConfig();return Object.assign(e,t),e}}cd.className="PReLU",Ii(cd);class ud extends Vc{constructor(e){if(super(null==e?{}:e),this.DEFAULT_ALPHA=1,null==e&&(e={}),null!=e.alpha&&e.alpha!==this.DEFAULT_ALPHA)throw new el(`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=Dc(e);return Ca(n)}computeOutputShape(e){return e}getConfig(){const e={alpha:this.alpha},t=super.getConfig();return Object.assign(e,t),e}}ud.className="ELU",Ii(ud);class hd extends Vc{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=Dc(e);return Ei(n,hi(Za(n,this.theta),"float32"))}computeOutputShape(e){return e}getConfig(){const e={theta:this.theta},t=super.getConfig();return Object.assign(e,t),e}}hd.className="ThresholdedReLU",Ii(hd);class pd extends Vc{constructor(e){super(null==e?{}:e),this.DEFAULT_AXIS=1,null==e&&(e={}),this.softmax=(new Kp).apply,this.axis=null==e.axis?this.DEFAULT_AXIS:e.axis}call(e,t){return Tn((()=>{let n=Dc(e);const i=t.mask;if(null!=i){const e=Ei(ss(fs(n.shape),hi(i,n.dtype)),Ma(-1e9));n=$i(n,e)}return this.axis instanceof Array?this.axis.length>1?Ga(ss(n,os(n,this.axis,!0))):this.softmax(n,this.axis[0]):this.softmax(n,this.axis)}))}computeOutputShape(e){return e}getConfig(){const e={axis:this.axis},t=super.getConfig();return Object.assign(e,t),e}}
|
|
4539
4539
|
/**
|
|
4540
4540
|
* @license
|
|
4541
4541
|
* Copyright 2018 Google LLC
|
|
@@ -4554,7 +4554,7 @@ function dd(e,t,n){if("number"==typeof e)return il(e,t);if(e.length!==t)throw ne
|
|
|
4554
4554
|
* license that can be found in the LICENSE file or at
|
|
4555
4555
|
* https://opensource.org/licenses/MIT.
|
|
4556
4556
|
* =============================================================================
|
|
4557
|
-
*/function gd(e,t){return Tn((()=>(zl(t),"channelsFirst"===t?vi(e,[0,2,3,1]):e)))}function vd(e,t){return Tn((()=>(zl(t),"channelsFirst"===t?vi(e,[0,2,3,4,1]):e)))}function yd(e,t,n,i=[1,1],a="valid",s,r,o=null){return Tn((()=>{if(null==s&&(s="channelsLast"),zl(s),3!==e.rank&&4!==e.rank)throw new Xo(`conv2dWithBiasActivation expects input to be of rank 3 or 4, but received ${e.rank}.`);if(3!==t.rank&&4!==t.rank)throw new Xo(`conv2dWithBiasActivation expects kernel to be of rank 3 or 4, but received ${e.rank}.`);let l=gd(e,s);if("causal"===a)throw new el("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");return l=dr({x:l,filter:t,strides:i,pad:"same"===a?"same":"valid",dilations:r,dataFormat:"NHWC",bias:n,activation:o}),"channelsFirst"===s&&(l=vi(l,[0,3,1,2])),l}))}pd.className="Softmax",Ii(pd);class bd extends Vc{constructor(e,t){if(super(t),this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",bd.verifyArgs(t),this.rank=e,bl(this.rank,"rank"),1!==this.rank&&2!==this.rank&&3!==this.rank)throw new el(`Convolution layer for rank other than 1, 2, or 3 (${this.rank}) is not implemented yet.`);if(this.kernelSize=dd(t.kernelSize,e,"kernelSize"),this.strides=dd(null==t.strides?1:t.strides,e,"strides"),this.padding=null==t.padding?"valid":t.padding,Dl(this.padding),this.dataFormat=null==t.dataFormat?"channelsLast":t.dataFormat,zl(this.dataFormat),this.activation=ed(t.activation),this.useBias=null==t.useBias||t.useBias,this.biasInitializer=Ec(t.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.biasConstraint=Nh(t.biasConstraint),this.biasRegularizer=rd(t.biasRegularizer),this.activityRegularizer=rd(t.activityRegularizer),this.dilationRate=dd(null==t.dilationRate?1:t.dilationRate,e,"dilationRate"),1===this.rank&&Array.isArray(this.dilationRate)&&1!==this.dilationRate.length)throw new Xo(`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 Xo(`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 Xo(`dilationRate must be a number or array of three numbers for 3D convolution, but received ${JSON.stringify(this.dilationRate)}`)}static verifyArgs(e){if(al("kernelSize"in e,"required key 'kernelSize' not in config"),"number"!=typeof e.kernelSize&&!yl(e.kernelSize,"number",1,3))throw new Xo(`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:Qp(this.activation),useBias:this.useBias,biasInitializer:$c(this.biasInitializer),biasRegularizer:ad(this.biasRegularizer),activityRegularizer:ad(this.activityRegularizer),biasConstraint:xh(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}}class wd extends bd{constructor(e,t){super(e,t),this.kernel=null,wd.verifyArgs(t),this.filters=t.filters,bl(this.filters,"filters"),this.kernelInitializer=Ec(t.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.kernelConstraint=Nh(t.kernelConstraint),this.kernelRegularizer=rd(t.kernelRegularizer)}build(e){e=Fc(e);const t="channelsFirst"===this.dataFormat?1:e.length-1;if(null==e[t])throw new Xo(`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 Tn((()=>{let t;e=Dc(e);const n=null==this.bias?null:this.bias.read(),i=kl(this.activation.getClassName());if(null!=i&&2===this.rank)t=yd(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 Tn((()=>{if(null==s&&(s="channelsLast"),zl(s),3!==e.shape.length)throw new Xo(`The input of a conv1dWithBias operation should be 3, but is ${e.shape.length} instead.`);if(3!==t.shape.length)throw new Xo(`The kernel for a conv1dWithBias operation should be 3, but is ${t.shape.length} instead`);if(null!=n&&1!==n.shape.length)throw new Xo(`The bias for a conv1dWithBias operation should be 1, but is ${n.shape.length} instead`);if("channelsFirst"===s&&(e=vi(e,[0,2,1])),"causal"===a)throw new el("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");let o=pa(e,t,i,"same"===a?"same":"valid","NWC",r);return null!=n&&(o=rc(o,n)),o}))}(e,this.kernel.read(),n,this.strides[0],this.padding,this.dataFormat,this.dilationRate[0]);else if(2===this.rank)t=yd(e,this.kernel.read(),n,this.strides,this.padding,this.dataFormat,this.dilationRate);else{if(3!==this.rank)throw new el("convolutions greater than 3D are not implemented yet.");t=function(e,t,n,i=[1,1,1],a="valid",s,r){return Tn((()=>{if(null==s&&(s="channelsLast"),zl(s),4!==e.rank&&5!==e.rank)throw new Xo(`conv3dWithBias expects input to be of rank 4 or 5, but received ${e.rank}.`);if(4!==t.rank&&5!==t.rank)throw new Xo(`conv3dWithBias expects kernel to be of rank 4 or 5, but received ${e.rank}.`);let o=vd(e,s);if("causal"===a)throw new el("The support for CAUSAL padding mode in conv3dWithBias is not implemented yet.");return o=fa(o,t,i,"same"===a?"same":"valid","NDHWC",r),null!=n&&(o=rc(o,n)),"channelsFirst"===s&&(o=vi(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=Fc(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=md(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:$c(this.kernelInitializer),kernelRegularizer:ad(this.kernelRegularizer),kernelConstraint:xh(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 Xo(`Convolution layer expected config.filters to be a 'number' > 0 but got ${JSON.stringify(e.filters)}`)}}class kd extends wd{constructor(e){super(2,e),kd.verifyArgs(e)}getConfig(){const e=super.getConfig();return delete e.rank,e}static verifyArgs(e){if("number"!=typeof e.kernelSize&&!yl(e.kernelSize,"number",1,2))throw new Xo(`Conv2D expects config.kernelSize to be number or number[] with length 1 or 2, but received ${JSON.stringify(e.kernelSize)}.`)}}kd.className="Conv2D",Ii(kd);class xd extends wd{constructor(e){super(3,e),xd.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 Xo(`Conv3D expects config.kernelSize to be number or [number, number, number], but received ${JSON.stringify(e.kernelSize)}.`)}}xd.className="Conv3D",Ii(xd);class Sd extends kd{constructor(e){if(super(e),this.inputSpec=[new Pc({ndim:4})],"same"!==this.padding&&"valid"!==this.padding)throw new Xo(`Conv2DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(e){if(4!==(e=Fc(e)).length)throw new Xo("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 Xo("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 Pc({ndim:4,axes:{[t]:n}})],this.built=!0}call(e,t){return Tn((()=>{let t=Dc(e);if(4!==t.shape.length)throw new Xo(`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,fd(r,u,l,this.padding),fd(o,h,c,this.padding),this.filters];"channelsLast"!==this.dataFormat&&(t=vi(t,[0,2,3,1]));let d=ma(t,this.kernel.read(),p,this.strides,this.padding);return"channelsLast"!==this.dataFormat&&(d=vi(d,[0,3,1,2])),null!=this.bias&&(d=rc(d,this.bias.read(),this.dataFormat)),null!=this.activation&&(d=this.activation.apply(d)),d}))}computeOutputShape(e){const t=(e=Fc(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]=fd(t[i],o,s,this.padding),t[a]=fd(t[a],l,r,this.padding),t}getConfig(){const e=super.getConfig();return delete e.dilationRate,e}}Sd.className="Conv2DTranspose",Ii(Sd);class Nd extends xd{constructor(e){if(super(e),this.inputSpec=[new Pc({ndim:5})],"same"!==this.padding&&"valid"!==this.padding)throw new Xo(`Conv3DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(e){if(5!==(e=Fc(e)).length)throw new Xo("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 Xo("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 Pc({ndim:5,axes:{[t]:n}})],this.built=!0}call(e,t){return Tn((()=>{let t=Dc(e);if(5!==t.shape.length)throw new Xo(`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,fd(o,d,u,this.padding),fd(l,m,h,this.padding),fd(c,f,p,this.padding),this.filters];"channelsLast"!==this.dataFormat&&(t=vi(t,[0,2,3,4,1]));let v=va(t,this.kernel.read(),g,this.strides,this.padding);return"channelsLast"!==this.dataFormat&&(v=vi(v,[0,4,1,2,3])),null!==this.bias&&(v=rc(v,this.bias.read(),this.dataFormat)),null!==this.activation&&(v=this.activation.apply(v)),v}))}computeOutputShape(e){const t=(e=Fc(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]=fd(t[i],c,r,this.padding),t[a]=fd(t[a],u,o,this.padding),t[s]=fd(t[s],h,l,this.padding),t}getConfig(){const e=super.getConfig();return delete e.dilationRate,e}}Nd.className="Conv3DTranspose",Ii(Nd);class Td extends wd{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 Xo("The `filters` configuration field is required by SeparableConv, but is unspecified.");if(null!=t.kernelInitializer||null!=t.kernelRegularizer||null!=t.kernelConstraint)throw new Xo("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 Xo(`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=Ec(t.depthwiseInitializer||this.DEFAULT_DEPTHWISE_INITIALIZER),this.depthwiseRegularizer=rd(t.depthwiseRegularizer),this.depthwiseConstraint=Nh(t.depthwiseConstraint),this.pointwiseInitializer=Ec(t.depthwiseInitializer||this.DEFAULT_POINTWISE_INITIALIZER),this.pointwiseRegularizer=rd(t.pointwiseRegularizer),this.pointwiseConstraint=Nh(t.pointwiseConstraint)}build(e){if((e=Fc(e)).length<this.rank+2)throw new Xo(`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 Xo(`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 Pc({ndim:this.rank+2,axes:{[t]:n}})],this.built=!0}call(e,t){return Tn((()=>{let t;if(e=Dc(e),1===this.rank)throw new el("1D separable convolution is not implemented yet.");return 2===this.rank&&("channelsFirst"===this.dataFormat&&(e=vi(e,[0,2,3,1])),t=Gs(e,this.depthwiseKernel.read(),this.pointwiseKernel.read(),this.strides,this.padding,this.dilationRate,"NHWC")),this.useBias&&(t=rc(t,this.bias.read(),this.dataFormat)),null!=this.activation&&(t=this.activation.apply(t)),"channelsFirst"===this.dataFormat&&(t=vi(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=$c(this.depthwiseInitializer),e.pointwiseInitializer=$c(this.pointwiseInitializer),e.depthwiseRegularizer=ad(this.depthwiseRegularizer),e.pointwiseRegularizer=ad(this.pointwiseRegularizer),e.depthwiseConstraint=xh(this.depthwiseConstraint),e.pointwiseConstraint=xh(this.pointwiseConstraint),e}}Td.className="SeparableConv";class Id extends Td{constructor(e){super(2,e)}}Id.className="SeparableConv2D",Ii(Id);class Cd extends wd{constructor(e){super(1,e),Cd.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&&!yl(e.kernelSize,"number",1,1))throw new Xo(`Conv1D expects config.kernelSize to be number or number[] with length 1, but received ${JSON.stringify(e.kernelSize)}.`)}}Cd.className="Conv1D",Ii(Cd);class Ad extends Vc{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 Tn((()=>{if(e=Dc(e),"channelsLast"===this.dataFormat){const t=Yl(e,this.cropping[0][0],e.shape[1]-this.cropping[0][0]-this.cropping[0][1],2);return Yl(t,this.cropping[1][0],e.shape[2]-this.cropping[1][1]-this.cropping[1][0],3)}{const t=Yl(e,this.cropping[0][0],e.shape[2]-this.cropping[0][0]-this.cropping[0][1],3);return Yl(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}}Ad.className="Cropping2D",Ii(Ad);class $d extends Vc{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,zl(this.dataFormat),this.interpolation=null==e.interpolation?"nearest":e.interpolation,t=this.interpolation,vl(Cl,"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 Tn((()=>{let t=Dc(e);const n=t.shape;if("channelsFirst"===this.dataFormat){t=vi(t,[0,2,3,1]);const e=this.size[0]*n[2],i=this.size[1]*n[3],a="nearest"===this.interpolation?Gr.resizeNearestNeighbor(t,[e,i]):Gr.resizeBilinear(t,[e,i]);return vi(a,[0,3,1,2])}{const e=this.size[0]*n[1],i=this.size[1]*n[2];return"nearest"===this.interpolation?Gr.resizeNearestNeighbor(t,[e,i]):Gr.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}}$d.className="UpSampling2D",Ii($d);class Ed extends bd{constructor(e){super(2,e),this.depthwiseKernel=null,this.depthMultiplier=null==e.depthMultiplier?1:e.depthMultiplier,this.depthwiseInitializer=Ec(e.depthwiseInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.depthwiseConstraint=Nh(e.depthwiseConstraint),this.depthwiseRegularizer=rd(e.depthwiseRegularizer)}build(e){if((e=Fc(e)).length<4)throw new Xo(`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 Xo(`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 Tn((()=>{let t=
|
|
4557
|
+
*/function gd(e,t){return Tn((()=>(zl(t),"channelsFirst"===t?vi(e,[0,2,3,1]):e)))}function vd(e,t){return Tn((()=>(zl(t),"channelsFirst"===t?vi(e,[0,2,3,4,1]):e)))}function yd(e,t,n,i=[1,1],a="valid",s,r,o=null){return Tn((()=>{if(null==s&&(s="channelsLast"),zl(s),3!==e.rank&&4!==e.rank)throw new Xo(`conv2dWithBiasActivation expects input to be of rank 3 or 4, but received ${e.rank}.`);if(3!==t.rank&&4!==t.rank)throw new Xo(`conv2dWithBiasActivation expects kernel to be of rank 3 or 4, but received ${e.rank}.`);let l=gd(e,s);if("causal"===a)throw new el("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");return l=dr({x:l,filter:t,strides:i,pad:"same"===a?"same":"valid",dilations:r,dataFormat:"NHWC",bias:n,activation:o}),"channelsFirst"===s&&(l=vi(l,[0,3,1,2])),l}))}pd.className="Softmax",Ii(pd);class bd extends Vc{constructor(e,t){if(super(t),this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",bd.verifyArgs(t),this.rank=e,bl(this.rank,"rank"),1!==this.rank&&2!==this.rank&&3!==this.rank)throw new el(`Convolution layer for rank other than 1, 2, or 3 (${this.rank}) is not implemented yet.`);if(this.kernelSize=dd(t.kernelSize,e,"kernelSize"),this.strides=dd(null==t.strides?1:t.strides,e,"strides"),this.padding=null==t.padding?"valid":t.padding,Dl(this.padding),this.dataFormat=null==t.dataFormat?"channelsLast":t.dataFormat,zl(this.dataFormat),this.activation=ed(t.activation),this.useBias=null==t.useBias||t.useBias,this.biasInitializer=Ec(t.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.biasConstraint=Nh(t.biasConstraint),this.biasRegularizer=rd(t.biasRegularizer),this.activityRegularizer=rd(t.activityRegularizer),this.dilationRate=dd(null==t.dilationRate?1:t.dilationRate,e,"dilationRate"),1===this.rank&&Array.isArray(this.dilationRate)&&1!==this.dilationRate.length)throw new Xo(`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 Xo(`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 Xo(`dilationRate must be a number or array of three numbers for 3D convolution, but received ${JSON.stringify(this.dilationRate)}`)}static verifyArgs(e){if(al("kernelSize"in e,"required key 'kernelSize' not in config"),"number"!=typeof e.kernelSize&&!yl(e.kernelSize,"number",1,3))throw new Xo(`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:Qp(this.activation),useBias:this.useBias,biasInitializer:Ac(this.biasInitializer),biasRegularizer:ad(this.biasRegularizer),activityRegularizer:ad(this.activityRegularizer),biasConstraint:xh(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}}class wd extends bd{constructor(e,t){super(e,t),this.kernel=null,wd.verifyArgs(t),this.filters=t.filters,bl(this.filters,"filters"),this.kernelInitializer=Ec(t.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.kernelConstraint=Nh(t.kernelConstraint),this.kernelRegularizer=rd(t.kernelRegularizer)}build(e){e=Fc(e);const t="channelsFirst"===this.dataFormat?1:e.length-1;if(null==e[t])throw new Xo(`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 Tn((()=>{let t;e=Dc(e);const n=null==this.bias?null:this.bias.read(),i=kl(this.activation.getClassName());if(null!=i&&2===this.rank)t=yd(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 Tn((()=>{if(null==s&&(s="channelsLast"),zl(s),3!==e.shape.length)throw new Xo(`The input of a conv1dWithBias operation should be 3, but is ${e.shape.length} instead.`);if(3!==t.shape.length)throw new Xo(`The kernel for a conv1dWithBias operation should be 3, but is ${t.shape.length} instead`);if(null!=n&&1!==n.shape.length)throw new Xo(`The bias for a conv1dWithBias operation should be 1, but is ${n.shape.length} instead`);if("channelsFirst"===s&&(e=vi(e,[0,2,1])),"causal"===a)throw new el("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");let o=pa(e,t,i,"same"===a?"same":"valid","NWC",r);return null!=n&&(o=rc(o,n)),o}))}(e,this.kernel.read(),n,this.strides[0],this.padding,this.dataFormat,this.dilationRate[0]);else if(2===this.rank)t=yd(e,this.kernel.read(),n,this.strides,this.padding,this.dataFormat,this.dilationRate);else{if(3!==this.rank)throw new el("convolutions greater than 3D are not implemented yet.");t=function(e,t,n,i=[1,1,1],a="valid",s,r){return Tn((()=>{if(null==s&&(s="channelsLast"),zl(s),4!==e.rank&&5!==e.rank)throw new Xo(`conv3dWithBias expects input to be of rank 4 or 5, but received ${e.rank}.`);if(4!==t.rank&&5!==t.rank)throw new Xo(`conv3dWithBias expects kernel to be of rank 4 or 5, but received ${e.rank}.`);let o=vd(e,s);if("causal"===a)throw new el("The support for CAUSAL padding mode in conv3dWithBias is not implemented yet.");return o=fa(o,t,i,"same"===a?"same":"valid","NDHWC",r),null!=n&&(o=rc(o,n)),"channelsFirst"===s&&(o=vi(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=Fc(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=md(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:Ac(this.kernelInitializer),kernelRegularizer:ad(this.kernelRegularizer),kernelConstraint:xh(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 Xo(`Convolution layer expected config.filters to be a 'number' > 0 but got ${JSON.stringify(e.filters)}`)}}class kd extends wd{constructor(e){super(2,e),kd.verifyArgs(e)}getConfig(){const e=super.getConfig();return delete e.rank,e}static verifyArgs(e){if("number"!=typeof e.kernelSize&&!yl(e.kernelSize,"number",1,2))throw new Xo(`Conv2D expects config.kernelSize to be number or number[] with length 1 or 2, but received ${JSON.stringify(e.kernelSize)}.`)}}kd.className="Conv2D",Ii(kd);class xd extends wd{constructor(e){super(3,e),xd.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 Xo(`Conv3D expects config.kernelSize to be number or [number, number, number], but received ${JSON.stringify(e.kernelSize)}.`)}}xd.className="Conv3D",Ii(xd);class Sd extends kd{constructor(e){if(super(e),this.inputSpec=[new Pc({ndim:4})],"same"!==this.padding&&"valid"!==this.padding)throw new Xo(`Conv2DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(e){if(4!==(e=Fc(e)).length)throw new Xo("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 Xo("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 Pc({ndim:4,axes:{[t]:n}})],this.built=!0}call(e,t){return Tn((()=>{let t=Dc(e);if(4!==t.shape.length)throw new Xo(`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,fd(r,u,l,this.padding),fd(o,h,c,this.padding),this.filters];"channelsLast"!==this.dataFormat&&(t=vi(t,[0,2,3,1]));let d=ma(t,this.kernel.read(),p,this.strides,this.padding);return"channelsLast"!==this.dataFormat&&(d=vi(d,[0,3,1,2])),null!=this.bias&&(d=rc(d,this.bias.read(),this.dataFormat)),null!=this.activation&&(d=this.activation.apply(d)),d}))}computeOutputShape(e){const t=(e=Fc(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]=fd(t[i],o,s,this.padding),t[a]=fd(t[a],l,r,this.padding),t}getConfig(){const e=super.getConfig();return delete e.dilationRate,e}}Sd.className="Conv2DTranspose",Ii(Sd);class Nd extends xd{constructor(e){if(super(e),this.inputSpec=[new Pc({ndim:5})],"same"!==this.padding&&"valid"!==this.padding)throw new Xo(`Conv3DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(e){if(5!==(e=Fc(e)).length)throw new Xo("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 Xo("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 Pc({ndim:5,axes:{[t]:n}})],this.built=!0}call(e,t){return Tn((()=>{let t=Dc(e);if(5!==t.shape.length)throw new Xo(`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,fd(o,d,u,this.padding),fd(l,m,h,this.padding),fd(c,f,p,this.padding),this.filters];"channelsLast"!==this.dataFormat&&(t=vi(t,[0,2,3,4,1]));let v=va(t,this.kernel.read(),g,this.strides,this.padding);return"channelsLast"!==this.dataFormat&&(v=vi(v,[0,4,1,2,3])),null!==this.bias&&(v=rc(v,this.bias.read(),this.dataFormat)),null!==this.activation&&(v=this.activation.apply(v)),v}))}computeOutputShape(e){const t=(e=Fc(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]=fd(t[i],c,r,this.padding),t[a]=fd(t[a],u,o,this.padding),t[s]=fd(t[s],h,l,this.padding),t}getConfig(){const e=super.getConfig();return delete e.dilationRate,e}}Nd.className="Conv3DTranspose",Ii(Nd);class Td extends wd{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 Xo("The `filters` configuration field is required by SeparableConv, but is unspecified.");if(null!=t.kernelInitializer||null!=t.kernelRegularizer||null!=t.kernelConstraint)throw new Xo("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 Xo(`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=Ec(t.depthwiseInitializer||this.DEFAULT_DEPTHWISE_INITIALIZER),this.depthwiseRegularizer=rd(t.depthwiseRegularizer),this.depthwiseConstraint=Nh(t.depthwiseConstraint),this.pointwiseInitializer=Ec(t.depthwiseInitializer||this.DEFAULT_POINTWISE_INITIALIZER),this.pointwiseRegularizer=rd(t.pointwiseRegularizer),this.pointwiseConstraint=Nh(t.pointwiseConstraint)}build(e){if((e=Fc(e)).length<this.rank+2)throw new Xo(`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 Xo(`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 Pc({ndim:this.rank+2,axes:{[t]:n}})],this.built=!0}call(e,t){return Tn((()=>{let t;if(e=Dc(e),1===this.rank)throw new el("1D separable convolution is not implemented yet.");return 2===this.rank&&("channelsFirst"===this.dataFormat&&(e=vi(e,[0,2,3,1])),t=Gs(e,this.depthwiseKernel.read(),this.pointwiseKernel.read(),this.strides,this.padding,this.dilationRate,"NHWC")),this.useBias&&(t=rc(t,this.bias.read(),this.dataFormat)),null!=this.activation&&(t=this.activation.apply(t)),"channelsFirst"===this.dataFormat&&(t=vi(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=Ac(this.depthwiseInitializer),e.pointwiseInitializer=Ac(this.pointwiseInitializer),e.depthwiseRegularizer=ad(this.depthwiseRegularizer),e.pointwiseRegularizer=ad(this.pointwiseRegularizer),e.depthwiseConstraint=xh(this.depthwiseConstraint),e.pointwiseConstraint=xh(this.pointwiseConstraint),e}}Td.className="SeparableConv";class Id extends Td{constructor(e){super(2,e)}}Id.className="SeparableConv2D",Ii(Id);class $d extends wd{constructor(e){super(1,e),$d.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&&!yl(e.kernelSize,"number",1,1))throw new Xo(`Conv1D expects config.kernelSize to be number or number[] with length 1, but received ${JSON.stringify(e.kernelSize)}.`)}}$d.className="Conv1D",Ii($d);class Cd extends Vc{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 Tn((()=>{if(e=Dc(e),"channelsLast"===this.dataFormat){const t=Yl(e,this.cropping[0][0],e.shape[1]-this.cropping[0][0]-this.cropping[0][1],2);return Yl(t,this.cropping[1][0],e.shape[2]-this.cropping[1][1]-this.cropping[1][0],3)}{const t=Yl(e,this.cropping[0][0],e.shape[2]-this.cropping[0][0]-this.cropping[0][1],3);return Yl(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}}Cd.className="Cropping2D",Ii(Cd);class Ad extends Vc{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,zl(this.dataFormat),this.interpolation=null==e.interpolation?"nearest":e.interpolation,t=this.interpolation,vl($l,"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 Tn((()=>{let t=Dc(e);const n=t.shape;if("channelsFirst"===this.dataFormat){t=vi(t,[0,2,3,1]);const e=this.size[0]*n[2],i=this.size[1]*n[3],a="nearest"===this.interpolation?Gr.resizeNearestNeighbor(t,[e,i]):Gr.resizeBilinear(t,[e,i]);return vi(a,[0,3,1,2])}{const e=this.size[0]*n[1],i=this.size[1]*n[2];return"nearest"===this.interpolation?Gr.resizeNearestNeighbor(t,[e,i]):Gr.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}}Ad.className="UpSampling2D",Ii(Ad);class Ed extends bd{constructor(e){super(2,e),this.depthwiseKernel=null,this.depthMultiplier=null==e.depthMultiplier?1:e.depthMultiplier,this.depthwiseInitializer=Ec(e.depthwiseInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.depthwiseConstraint=Nh(e.depthwiseConstraint),this.depthwiseRegularizer=rd(e.depthwiseRegularizer)}build(e){if((e=Fc(e)).length<4)throw new Xo(`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 Xo(`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 Tn((()=>{let t=
|
|
4558
4558
|
/**
|
|
4559
4559
|
* @license
|
|
4560
4560
|
* Copyright 2018 Google LLC
|
|
@@ -4564,7 +4564,7 @@ function dd(e,t,n){if("number"==typeof e)return il(e,t);if(e.length!==t)throw ne
|
|
|
4564
4564
|
* https://opensource.org/licenses/MIT.
|
|
4565
4565
|
* =============================================================================
|
|
4566
4566
|
*/
|
|
4567
|
-
function(e,t,n=[1,1],i="valid",a,s){return Tn((()=>{null==a&&(a="channelsLast"),zl(a);let r=gd(e,a);if(4!==e.rank)throw new Xo(`Input for depthwiseConv2d is required to be 4-D, but is instead ${e.rank}-D`);if(4!==t.rank)throw new Xo(`depthwiseKernel is required to be 4-D, but is instead ${t.rank}-D`);return r=Sa(r,t,n,"same"===i?"same":"valid","NHWC",s),"channelsFirst"===a&&(r=vi(r,[0,3,1,2])),r}))}(e=Dc(e),this.depthwiseKernel.read(),this.strides,this.padding,this.dataFormat,null);return this.useBias&&(t=rc(t,this.bias.read(),this.dataFormat)),null!=this.activation&&(t=this.activation.apply(t)),t}))}computeOutputShape(e){e=Fc(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=md(t,this.kernelSize[0],this.padding,this.strides[0]),s=md(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
|
|
4567
|
+
function(e,t,n=[1,1],i="valid",a,s){return Tn((()=>{null==a&&(a="channelsLast"),zl(a);let r=gd(e,a);if(4!==e.rank)throw new Xo(`Input for depthwiseConv2d is required to be 4-D, but is instead ${e.rank}-D`);if(4!==t.rank)throw new Xo(`depthwiseKernel is required to be 4-D, but is instead ${t.rank}-D`);return r=Sa(r,t,n,"same"===i?"same":"valid","NHWC",s),"channelsFirst"===a&&(r=vi(r,[0,3,1,2])),r}))}(e=Dc(e),this.depthwiseKernel.read(),this.strides,this.padding,this.dataFormat,null);return this.useBias&&(t=rc(t,this.bias.read(),this.dataFormat)),null!=this.activation&&(t=this.activation.apply(t)),t}))}computeOutputShape(e){e=Fc(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=md(t,this.kernelSize[0],this.padding,this.strides[0]),s=md(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=Ac(this.depthwiseInitializer),e.depthwiseRegularizer=ad(this.depthwiseRegularizer),e.depthwiseConstraint=xh(this.depthwiseRegularizer),e}}
|
|
4568
4568
|
/**
|
|
4569
4569
|
* @license
|
|
4570
4570
|
* Copyright 2018 Google LLC
|
|
@@ -4574,7 +4574,7 @@ function(e,t,n=[1,1],i="valid",a,s){return Tn((()=>{null==a&&(a="channelsLast"),
|
|
|
4574
4574
|
* https://opensource.org/licenses/MIT.
|
|
4575
4575
|
* =============================================================================
|
|
4576
4576
|
*/
|
|
4577
|
-
function jd(e,t,n,i){if(Array.isArray(e)){if(null!=t||null!=n)throw new Xo("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 zd(e,t,n,i=!1,a,s,r=!1,o=!1){return Tn((()=>{const l=t.shape.length;if(l<3)throw new Xo(`Input should be at least 3D, but is ${l}D.`);const c=[1,0].concat(Gl(2,l));if(t=vi(t,c),null!=s)throw new el("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=hi(hi(a,"bool"),"float32")).rank===l-1&&(a=Va(a,-1)),a=vi(a,c)),i&&(t=Ps(t,0),null!=a&&(a=Ps(a,0)));const u=[];let h,p=n;const d=t.shape[0],m=rr(t);let f,g;null!=a&&(f=rr(a));for(let t=0;t<d;++t){const n=m[t],i=Tn((()=>e(n,p)));if(null==a)h=i[0],p=i[1];else{const e=Tn((()=>{const e=f[t],n=ss(bs(e),e);return{output:Ci(Ei(i[0],e),Ei(p[0],n)),newStates:p.map(((t,a)=>Ci(Ei(i[1][a],e),Ei(t,n))))}}));h=e.output,p=e.newStates}o&&u.push(h)}if(o){g=er(u,1)}return[h,g,p]}))}Ed.className="DepthwiseConv2D",Ii(Ed);class Dd extends Vc{constructor(e){let t;if(super(e),null==e.cell)throw new Xo("cell property is missing for the constructor of RNN.");if(t=Array.isArray(e.cell)?new Bd({cells:e.cell}):e.cell,null==t.stateSize)throw new Xo("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 Pc({ndim:3})],this.stateSpec=null,this.states_=null,this.numConstants=null,this.keptStates=[]}getStates(){if(null==this.states_){return Gl(0,Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1).map((e=>null))}return this.states_}setStates(e){this.states_=e}computeOutputShape(e){jc(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 Tn((()=>{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 el("Constants support is not implemented in RNN yet.");jc(e)&&(e=e[0]);const t=this.stateful?e[0]:null,n=e.slice(2);this.inputSpec[0]=new Pc({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(!$(this.stateSpec.map((e=>e.shape[e.shape.length-1])),a))throw new Xo(`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 Pc({shape:[null,e]})));this.stateful&&this.resetStates()}resetStates(e,t=!1){Tn((()=>{if(!this.stateful)throw new Yo("Cannot call resetStates() on an RNN Layer that is not stateful.");const n=this.inputSpec[0].shape[0];if(null==n)throw new Xo("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=>ms([n,e]))):this.states_=[ms([n,this.cell.stateSize])];else if(null==e)In(this.states_),null!=this.keptStates&&(In(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map((e=>ms([n,e]))):this.states_[0]=ms([n,this.cell.stateSize]);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new Xo(`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()):In(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(!$(i.shape,s))throw new Xo(`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=>Cn(e.clone())))}))}apply(e,t){let n=null==t?null:t.initialState,i=null==t?null:t.constants;null==t&&(t={});const a=jd(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 Pc({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 Bc){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 Tn((()=>{const n=null==t?null:t.mask,i=null==t?null:t.training;let a=null==t?null:t.initialState;e=Dc(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 Xo(`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=zd(((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 Tn((()=>{let t=ms(e.shape);return t=Ba(t,[1,2]),t=Hl(t),Array.isArray(this.cell.stateSize)?this.cell.stateSize.map((e=>e>1?ec(t,[1,e]):t)):this.cell.stateSize>1?[ec(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()===Dd.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=Rh(t.cell,n);return new e(Object.assign(t,{cell:i}))}}Dd.className="RNN",Ii(Dd);class Fd extends Vc{}class _d extends Fd{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,bl(this.units,"units"),this.activation=ed(null==e.activation?this.DEFAULT_ACTIVATION:e.activation),this.useBias=null==e.useBias||e.useBias,this.kernelInitializer=Ec(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=Ec(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=Ec(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=rd(e.kernelRegularizer),this.recurrentRegularizer=rd(e.recurrentRegularizer),this.biasRegularizer=rd(e.biasRegularizer),this.kernelConstraint=Nh(e.kernelConstraint),this.recurrentConstraint=Nh(e.recurrentConstraint),this.biasConstraint=Nh(e.biasConstraint),this.dropout=Ul([1,Wl([0,null==e.dropout?0:e.dropout])]),this.recurrentDropout=Ul([1,Wl([0,null==e.recurrentDropout?0:e.recurrentDropout])]),this.dropoutFunc=e.dropoutFunc,this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){e=Fc(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 Tn((()=>{if(2!==e.length)throw new Xo(`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=Ud({ones:()=>bs(e),rate:this.dropout,training:i,dropoutFunc:this.dropoutFunc})),0<this.recurrentDropout&&this.recurrentDropout<1&&null==this.recurrentDropoutMask&&(this.recurrentDropoutMask=Ud({ones:()=>bs(n),rate:this.recurrentDropout,training:i,dropoutFunc:this.dropoutFunc}));const s=this.dropoutMask,r=this.recurrentDropoutMask;a=nc(null!=s?Ei(e,s):e,this.kernel.read()),null!=this.bias&&(a=rc(a,this.bias.read())),null!=r&&(n=Ei(n,r));let o=Ci(a,nc(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:Qp(this.activation),useBias:this.useBias,kernelInitializer:$c(this.kernelInitializer),recurrentInitializer:$c(this.recurrentInitializer),biasInitializer:$c(this.biasInitializer),kernelRegularizer:ad(this.kernelRegularizer),recurrentRegularizer:ad(this.recurrentRegularizer),biasRegularizer:ad(this.biasRegularizer),activityRegularizer:ad(this.activityRegularizer),kernelConstraint:xh(this.kernelConstraint),recurrentConstraint:xh(this.recurrentConstraint),biasConstraint:xh(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout};return Object.assign(Object.assign({},e),t)}}_d.className="SimpleRNNCell",Ii(_d);class Rd extends Dd{constructor(e){e.cell=new _d(e),super(e)}call(e,t){return Tn((()=>{null!=this.cell.dropoutMask&&(In(this.cell.dropoutMask),this.cell.dropoutMask=null),null!=this.cell.recurrentDropoutMask&&(In(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)}}Rd.className="SimpleRNN",Ii(Rd);class Ld extends Fd{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 Xo("GRUCell does not support reset_after parameter set to true.");this.units=e.units,bl(this.units,"units"),this.activation=ed(void 0===e.activation?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=ed(void 0===e.recurrentActivation?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=null==e.useBias||e.useBias,this.kernelInitializer=Ec(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=Ec(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=Ec(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=rd(e.kernelRegularizer),this.recurrentRegularizer=rd(e.recurrentRegularizer),this.biasRegularizer=rd(e.biasRegularizer),this.kernelConstraint=Nh(e.kernelConstraint),this.recurrentConstraint=Nh(e.recurrentConstraint),this.biasConstraint=Nh(e.biasConstraint),this.dropout=Ul([1,Wl([0,null==e.dropout?0:e.dropout])]),this.recurrentDropout=Ul([1,Wl([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=Fc(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 Tn((()=>{if(2!==e.length)throw new Xo(`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=Ud({ones:()=>bs(e),rate:this.dropout,training:n,count:3,dropoutFunc:this.dropoutFunc})),0<this.recurrentDropout&&this.recurrentDropout<1&&null==this.recurrentDropoutMask&&(this.recurrentDropoutMask=Ud({ones:()=>bs(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=Ei(e,a[0]));let c=nc(e,this.kernel.read());this.useBias&&(c=rc(c,this.bias.read())),0<this.recurrentDropout&&this.recurrentDropout<1&&(i=Ei(i,s[0]));const u=this.recurrentKernel.read(),[h,p]=Qs(u,[2*this.units,this.units],u.rank-1),d=nc(i,h),[m,f,g]=Qs(c,3,c.rank-1),[v,y]=Qs(d,2,d.rank-1);r=this.recurrentActivation.apply(Ci(m,v)),o=this.recurrentActivation.apply(Ci(f,y));const b=nc(Ei(o,i),p);l=this.activation.apply(Ci(g,b));const w=Ci(Ei(r,i),Ei(Ci(1,fi(r)),l));return[w,w]}))}getConfig(){const e=super.getConfig(),t={units:this.units,activation:Qp(this.activation),recurrentActivation:Qp(this.recurrentActivation),useBias:this.useBias,kernelInitializer:$c(this.kernelInitializer),recurrentInitializer:$c(this.recurrentInitializer),biasInitializer:$c(this.biasInitializer),kernelRegularizer:ad(this.kernelRegularizer),recurrentRegularizer:ad(this.recurrentRegularizer),biasRegularizer:ad(this.biasRegularizer),activityRegularizer:ad(this.activityRegularizer),kernelConstraint:xh(this.kernelConstraint),recurrentConstraint:xh(this.recurrentConstraint),biasConstraint:xh(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation,resetAfter:!1};return Object.assign(Object.assign({},e),t)}}Ld.className="GRUCell",Ii(Ld);class Md extends Dd{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 Ld(e),super(e)}call(e,t){return Tn((()=>{null!=this.cell.dropoutMask&&(In(this.cell.dropoutMask),this.cell.dropoutMask=null),null!=this.cell.recurrentDropoutMask&&(In(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)}}Md.className="GRU",Ii(Md);class Od extends Fd{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,bl(this.units,"units"),this.activation=ed(void 0===e.activation?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=ed(void 0===e.recurrentActivation?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=null==e.useBias||e.useBias,this.kernelInitializer=Ec(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=Ec(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=Ec(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.unitForgetBias=e.unitForgetBias,this.kernelRegularizer=rd(e.kernelRegularizer),this.recurrentRegularizer=rd(e.recurrentRegularizer),this.biasRegularizer=rd(e.biasRegularizer),this.kernelConstraint=Nh(e.kernelConstraint),this.recurrentConstraint=Nh(e.recurrentConstraint),this.biasConstraint=Nh(e.biasConstraint),this.dropout=Ul([1,Wl([0,null==e.dropout?0:e.dropout])]),this.recurrentDropout=Ul([1,Wl([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=Fc(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 hc{apply(t,i){const a=e.apply([n]),s=(new dc).apply([n]),r=e.apply([2*n]);return Xl(Xl(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 Tn((()=>{const n=null!=t.training&&t.training;if(3!==e.length)throw new Xo(`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=Ud({ones:()=>bs(e),rate:this.dropout,training:n,count:4,dropoutFunc:this.dropoutFunc})),0<this.recurrentDropout&&this.recurrentDropout<1&&null==this.recurrentDropoutMask&&(this.recurrentDropoutMask=Ud({ones:()=>bs(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=Ei(e,s[0]));let h=nc(e,this.kernel.read());0<this.recurrentDropout&&this.recurrentDropout<1&&(i=Ei(i,r[0])),h=Ci(h,nc(i,this.recurrentKernel.read())),this.useBias&&(h=rc(h,this.bias.read()));const[p,d,m,f]=Qs(h,4,h.rank-1);o=this.recurrentActivation.apply(p),l=this.recurrentActivation.apply(d),c=Ci(Ei(l,a),Ei(o,this.activation.apply(m))),u=this.recurrentActivation.apply(f);const g=Ei(u,this.activation.apply(c));return[g,g,c]}))}getConfig(){const e=super.getConfig(),t={units:this.units,activation:Qp(this.activation),recurrentActivation:Qp(this.recurrentActivation),useBias:this.useBias,kernelInitializer:$c(this.kernelInitializer),recurrentInitializer:$c(this.recurrentInitializer),biasInitializer:$c(this.biasInitializer),unitForgetBias:this.unitForgetBias,kernelRegularizer:ad(this.kernelRegularizer),recurrentRegularizer:ad(this.recurrentRegularizer),biasRegularizer:ad(this.biasRegularizer),activityRegularizer:ad(this.activityRegularizer),kernelConstraint:xh(this.kernelConstraint),recurrentConstraint:xh(this.recurrentConstraint),biasConstraint:xh(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation};return Object.assign(Object.assign({},e),t)}}Od.className="LSTMCell",Ii(Od);class Pd extends Dd{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 Od(e),super(e)}call(e,t){return Tn((()=>{null!=this.cell.dropoutMask&&(In(this.cell.dropoutMask),this.cell.dropoutMask=null),null!=this.cell.recurrentDropoutMask&&(In(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)}}Pd.className="LSTM",Ii(Pd);class Bd extends Fd{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 Tn((()=>{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;jc(e)&&(e=e[0]),this.cells.forEach(((n,i)=>{Rl(`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(Rh(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 Mc(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]])}Oc(t)}}function Ud(e){const{ones:t,rate:n,training:i=!1,count:a=1,dropoutFunc:s}=e,r=()=>null!=s?s(t(),n):oc(t(),n),o=()=>lc(r,t,i);if(!a||a<=1)return Cn(o().clone());return Array(a).fill(void 0).map(o).map((e=>Cn(e.clone())))}
|
|
4577
|
+
function jd(e,t,n,i){if(Array.isArray(e)){if(null!=t||null!=n)throw new Xo("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 zd(e,t,n,i=!1,a,s,r=!1,o=!1){return Tn((()=>{const l=t.shape.length;if(l<3)throw new Xo(`Input should be at least 3D, but is ${l}D.`);const c=[1,0].concat(Gl(2,l));if(t=vi(t,c),null!=s)throw new el("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=hi(hi(a,"bool"),"float32")).rank===l-1&&(a=Va(a,-1)),a=vi(a,c)),i&&(t=Ps(t,0),null!=a&&(a=Ps(a,0)));const u=[];let h,p=n;const d=t.shape[0],m=rr(t);let f,g;null!=a&&(f=rr(a));for(let t=0;t<d;++t){const n=m[t],i=Tn((()=>e(n,p)));if(null==a)h=i[0],p=i[1];else{const e=Tn((()=>{const e=f[t],n=ss(bs(e),e);return{output:$i(Ei(i[0],e),Ei(p[0],n)),newStates:p.map(((t,a)=>$i(Ei(i[1][a],e),Ei(t,n))))}}));h=e.output,p=e.newStates}o&&u.push(h)}if(o){g=er(u,1)}return[h,g,p]}))}Ed.className="DepthwiseConv2D",Ii(Ed);class Dd extends Vc{constructor(e){let t;if(super(e),null==e.cell)throw new Xo("cell property is missing for the constructor of RNN.");if(t=Array.isArray(e.cell)?new Bd({cells:e.cell}):e.cell,null==t.stateSize)throw new Xo("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 Pc({ndim:3})],this.stateSpec=null,this.states_=null,this.numConstants=null,this.keptStates=[]}getStates(){if(null==this.states_){return Gl(0,Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1).map((e=>null))}return this.states_}setStates(e){this.states_=e}computeOutputShape(e){jc(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 Tn((()=>{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 el("Constants support is not implemented in RNN yet.");jc(e)&&(e=e[0]);const t=this.stateful?e[0]:null,n=e.slice(2);this.inputSpec[0]=new Pc({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(!A(this.stateSpec.map((e=>e.shape[e.shape.length-1])),a))throw new Xo(`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 Pc({shape:[null,e]})));this.stateful&&this.resetStates()}resetStates(e,t=!1){Tn((()=>{if(!this.stateful)throw new Yo("Cannot call resetStates() on an RNN Layer that is not stateful.");const n=this.inputSpec[0].shape[0];if(null==n)throw new Xo("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=>ms([n,e]))):this.states_=[ms([n,this.cell.stateSize])];else if(null==e)In(this.states_),null!=this.keptStates&&(In(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map((e=>ms([n,e]))):this.states_[0]=ms([n,this.cell.stateSize]);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new Xo(`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()):In(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(!A(i.shape,s))throw new Xo(`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=>$n(e.clone())))}))}apply(e,t){let n=null==t?null:t.initialState,i=null==t?null:t.constants;null==t&&(t={});const a=jd(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 Pc({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 Bc){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 Tn((()=>{const n=null==t?null:t.mask,i=null==t?null:t.training;let a=null==t?null:t.initialState;e=Dc(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 Xo(`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=zd(((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 Tn((()=>{let t=ms(e.shape);return t=Ba(t,[1,2]),t=Hl(t),Array.isArray(this.cell.stateSize)?this.cell.stateSize.map((e=>e>1?ec(t,[1,e]):t)):this.cell.stateSize>1?[ec(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()===Dd.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=Rh(t.cell,n);return new e(Object.assign(t,{cell:i}))}}Dd.className="RNN",Ii(Dd);class Fd extends Vc{}class _d extends Fd{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,bl(this.units,"units"),this.activation=ed(null==e.activation?this.DEFAULT_ACTIVATION:e.activation),this.useBias=null==e.useBias||e.useBias,this.kernelInitializer=Ec(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=Ec(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=Ec(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=rd(e.kernelRegularizer),this.recurrentRegularizer=rd(e.recurrentRegularizer),this.biasRegularizer=rd(e.biasRegularizer),this.kernelConstraint=Nh(e.kernelConstraint),this.recurrentConstraint=Nh(e.recurrentConstraint),this.biasConstraint=Nh(e.biasConstraint),this.dropout=Ul([1,Wl([0,null==e.dropout?0:e.dropout])]),this.recurrentDropout=Ul([1,Wl([0,null==e.recurrentDropout?0:e.recurrentDropout])]),this.dropoutFunc=e.dropoutFunc,this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){e=Fc(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 Tn((()=>{if(2!==e.length)throw new Xo(`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=Ud({ones:()=>bs(e),rate:this.dropout,training:i,dropoutFunc:this.dropoutFunc})),0<this.recurrentDropout&&this.recurrentDropout<1&&null==this.recurrentDropoutMask&&(this.recurrentDropoutMask=Ud({ones:()=>bs(n),rate:this.recurrentDropout,training:i,dropoutFunc:this.dropoutFunc}));const s=this.dropoutMask,r=this.recurrentDropoutMask;a=nc(null!=s?Ei(e,s):e,this.kernel.read()),null!=this.bias&&(a=rc(a,this.bias.read())),null!=r&&(n=Ei(n,r));let o=$i(a,nc(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:Qp(this.activation),useBias:this.useBias,kernelInitializer:Ac(this.kernelInitializer),recurrentInitializer:Ac(this.recurrentInitializer),biasInitializer:Ac(this.biasInitializer),kernelRegularizer:ad(this.kernelRegularizer),recurrentRegularizer:ad(this.recurrentRegularizer),biasRegularizer:ad(this.biasRegularizer),activityRegularizer:ad(this.activityRegularizer),kernelConstraint:xh(this.kernelConstraint),recurrentConstraint:xh(this.recurrentConstraint),biasConstraint:xh(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout};return Object.assign(Object.assign({},e),t)}}_d.className="SimpleRNNCell",Ii(_d);class Rd extends Dd{constructor(e){e.cell=new _d(e),super(e)}call(e,t){return Tn((()=>{null!=this.cell.dropoutMask&&(In(this.cell.dropoutMask),this.cell.dropoutMask=null),null!=this.cell.recurrentDropoutMask&&(In(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)}}Rd.className="SimpleRNN",Ii(Rd);class Ld extends Fd{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 Xo("GRUCell does not support reset_after parameter set to true.");this.units=e.units,bl(this.units,"units"),this.activation=ed(void 0===e.activation?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=ed(void 0===e.recurrentActivation?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=null==e.useBias||e.useBias,this.kernelInitializer=Ec(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=Ec(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=Ec(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=rd(e.kernelRegularizer),this.recurrentRegularizer=rd(e.recurrentRegularizer),this.biasRegularizer=rd(e.biasRegularizer),this.kernelConstraint=Nh(e.kernelConstraint),this.recurrentConstraint=Nh(e.recurrentConstraint),this.biasConstraint=Nh(e.biasConstraint),this.dropout=Ul([1,Wl([0,null==e.dropout?0:e.dropout])]),this.recurrentDropout=Ul([1,Wl([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=Fc(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 Tn((()=>{if(2!==e.length)throw new Xo(`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=Ud({ones:()=>bs(e),rate:this.dropout,training:n,count:3,dropoutFunc:this.dropoutFunc})),0<this.recurrentDropout&&this.recurrentDropout<1&&null==this.recurrentDropoutMask&&(this.recurrentDropoutMask=Ud({ones:()=>bs(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=Ei(e,a[0]));let c=nc(e,this.kernel.read());this.useBias&&(c=rc(c,this.bias.read())),0<this.recurrentDropout&&this.recurrentDropout<1&&(i=Ei(i,s[0]));const u=this.recurrentKernel.read(),[h,p]=Qs(u,[2*this.units,this.units],u.rank-1),d=nc(i,h),[m,f,g]=Qs(c,3,c.rank-1),[v,y]=Qs(d,2,d.rank-1);r=this.recurrentActivation.apply($i(m,v)),o=this.recurrentActivation.apply($i(f,y));const b=nc(Ei(o,i),p);l=this.activation.apply($i(g,b));const w=$i(Ei(r,i),Ei($i(1,fi(r)),l));return[w,w]}))}getConfig(){const e=super.getConfig(),t={units:this.units,activation:Qp(this.activation),recurrentActivation:Qp(this.recurrentActivation),useBias:this.useBias,kernelInitializer:Ac(this.kernelInitializer),recurrentInitializer:Ac(this.recurrentInitializer),biasInitializer:Ac(this.biasInitializer),kernelRegularizer:ad(this.kernelRegularizer),recurrentRegularizer:ad(this.recurrentRegularizer),biasRegularizer:ad(this.biasRegularizer),activityRegularizer:ad(this.activityRegularizer),kernelConstraint:xh(this.kernelConstraint),recurrentConstraint:xh(this.recurrentConstraint),biasConstraint:xh(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation,resetAfter:!1};return Object.assign(Object.assign({},e),t)}}Ld.className="GRUCell",Ii(Ld);class Md extends Dd{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 Ld(e),super(e)}call(e,t){return Tn((()=>{null!=this.cell.dropoutMask&&(In(this.cell.dropoutMask),this.cell.dropoutMask=null),null!=this.cell.recurrentDropoutMask&&(In(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)}}Md.className="GRU",Ii(Md);class Od extends Fd{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,bl(this.units,"units"),this.activation=ed(void 0===e.activation?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=ed(void 0===e.recurrentActivation?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=null==e.useBias||e.useBias,this.kernelInitializer=Ec(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=Ec(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=Ec(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.unitForgetBias=e.unitForgetBias,this.kernelRegularizer=rd(e.kernelRegularizer),this.recurrentRegularizer=rd(e.recurrentRegularizer),this.biasRegularizer=rd(e.biasRegularizer),this.kernelConstraint=Nh(e.kernelConstraint),this.recurrentConstraint=Nh(e.recurrentConstraint),this.biasConstraint=Nh(e.biasConstraint),this.dropout=Ul([1,Wl([0,null==e.dropout?0:e.dropout])]),this.recurrentDropout=Ul([1,Wl([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=Fc(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 hc{apply(t,i){const a=e.apply([n]),s=(new dc).apply([n]),r=e.apply([2*n]);return Xl(Xl(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 Tn((()=>{const n=null!=t.training&&t.training;if(3!==e.length)throw new Xo(`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=Ud({ones:()=>bs(e),rate:this.dropout,training:n,count:4,dropoutFunc:this.dropoutFunc})),0<this.recurrentDropout&&this.recurrentDropout<1&&null==this.recurrentDropoutMask&&(this.recurrentDropoutMask=Ud({ones:()=>bs(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=Ei(e,s[0]));let h=nc(e,this.kernel.read());0<this.recurrentDropout&&this.recurrentDropout<1&&(i=Ei(i,r[0])),h=$i(h,nc(i,this.recurrentKernel.read())),this.useBias&&(h=rc(h,this.bias.read()));const[p,d,m,f]=Qs(h,4,h.rank-1);o=this.recurrentActivation.apply(p),l=this.recurrentActivation.apply(d),c=$i(Ei(l,a),Ei(o,this.activation.apply(m))),u=this.recurrentActivation.apply(f);const g=Ei(u,this.activation.apply(c));return[g,g,c]}))}getConfig(){const e=super.getConfig(),t={units:this.units,activation:Qp(this.activation),recurrentActivation:Qp(this.recurrentActivation),useBias:this.useBias,kernelInitializer:Ac(this.kernelInitializer),recurrentInitializer:Ac(this.recurrentInitializer),biasInitializer:Ac(this.biasInitializer),unitForgetBias:this.unitForgetBias,kernelRegularizer:ad(this.kernelRegularizer),recurrentRegularizer:ad(this.recurrentRegularizer),biasRegularizer:ad(this.biasRegularizer),activityRegularizer:ad(this.activityRegularizer),kernelConstraint:xh(this.kernelConstraint),recurrentConstraint:xh(this.recurrentConstraint),biasConstraint:xh(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation};return Object.assign(Object.assign({},e),t)}}Od.className="LSTMCell",Ii(Od);class Pd extends Dd{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 Od(e),super(e)}call(e,t){return Tn((()=>{null!=this.cell.dropoutMask&&(In(this.cell.dropoutMask),this.cell.dropoutMask=null),null!=this.cell.recurrentDropoutMask&&(In(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)}}Pd.className="LSTM",Ii(Pd);class Bd extends Fd{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 Tn((()=>{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;jc(e)&&(e=e[0]),this.cells.forEach(((n,i)=>{Rl(`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(Rh(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 Mc(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]])}Oc(t)}}function Ud(e){const{ones:t,rate:n,training:i=!1,count:a=1,dropoutFunc:s}=e,r=()=>null!=s?s(t(),n):oc(t(),n),o=()=>lc(r,t,i);if(!a||a<=1)return $n(o().clone());return Array(a).fill(void 0).map(o).map((e=>$n(e.clone())))}
|
|
4578
4578
|
/**
|
|
4579
4579
|
* @license
|
|
4580
4580
|
* Copyright 2020 Google LLC
|
|
@@ -4583,7 +4583,7 @@ function jd(e,t,n,i){if(Array.isArray(e)){if(null!=t||null!=n)throw new Xo("When
|
|
|
4583
4583
|
* license that can be found in the LICENSE file or at
|
|
4584
4584
|
* https://opensource.org/licenses/MIT.
|
|
4585
4585
|
* =============================================================================
|
|
4586
|
-
*/Bd.className="StackedRNNCells",Ii(Bd);var Wd=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 Gd extends Dd{constructor(e){if(e.unroll)throw new el("Unrolling is not possible with convolutional RNNs.");if(Array.isArray(e.cell))throw new el("It is not possible at the moment to stack convolutional cells.");super(e),this.inputSpec=[new Pc({ndim:5})]}call(e,t){return Tn((()=>{if(null!=this.cell.dropoutMask&&(In(this.cell.dropoutMask),this.cell.dropoutMask=null),null!=this.cell.recurrentDropoutMask&&(In(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null),t&&t.constants)throw new Xo("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 Tn((()=>{const{stateSize:t}=this.cell,n=e.shape,i=this.computeSingleOutputShape(n),a=ms([i[0],...i.slice(2)]);return Array.isArray(t)?Array(t.length).fill(a):[a]}))}resetStates(e,t=!1){Tn((()=>{if(!this.stateful)throw new Yo("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 Xo("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((()=>ms(a))):this.states_=[ms(a)];else if(null==e)In(this.states_),null!=this.keptStates&&(In(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map((()=>ms(a))):this.states_[0]=ms(a);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new Xo(`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()):In(this.states_);for(let t=0;t<this.states_.length;++t){const n=e[t],i=a;if(
|
|
4586
|
+
*/Bd.className="StackedRNNCells",Ii(Bd);var Wd=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 Gd extends Dd{constructor(e){if(e.unroll)throw new el("Unrolling is not possible with convolutional RNNs.");if(Array.isArray(e.cell))throw new el("It is not possible at the moment to stack convolutional cells.");super(e),this.inputSpec=[new Pc({ndim:5})]}call(e,t){return Tn((()=>{if(null!=this.cell.dropoutMask&&(In(this.cell.dropoutMask),this.cell.dropoutMask=null),null!=this.cell.recurrentDropoutMask&&(In(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null),t&&t.constants)throw new Xo("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 Tn((()=>{const{stateSize:t}=this.cell,n=e.shape,i=this.computeSingleOutputShape(n),a=ms([i[0],...i.slice(2)]);return Array.isArray(t)?Array(t.length).fill(a):[a]}))}resetStates(e,t=!1){Tn((()=>{if(!this.stateful)throw new Yo("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 Xo("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((()=>ms(a))):this.states_=[ms(a)];else if(null==e)In(this.states_),null!=this.keptStates&&(In(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map((()=>ms(a))):this.states_[0]=ms(a);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new Xo(`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()):In(this.states_);for(let t=0;t<this.states_.length;++t){const n=e[t],i=a;if(!A(n.shape,i))throw new Xo(`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=>$n(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=md(l,i[0],a,s[0],r[0]),h=md(c,i[1],a,s[1],r[1]);return[...e.slice(0,2),...o?[n,u,h]:[u,h,n]]}}Gd.className="ConvRNN2D";class Vd extends Od{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,bl(this.filters,"filters"),this.kernelSize=dd(n,2,"kernelSize"),this.kernelSize.forEach((e=>bl(e,"kernelSize"))),this.strides=dd(i||1,2,"strides"),this.strides.forEach((e=>bl(e,"strides"))),this.padding=a||"valid",Dl(this.padding),this.dataFormat=s||"channelsLast",zl(this.dataFormat),this.dilationRate=dd(r||1,2,"dilationRate"),this.dilationRate.forEach((e=>bl(e,"dilationRate")))}build(e){var t;e=Fc(e);const n="channelsFirst"===this.dataFormat?1:e.length-1;if(null==e[n])throw new Xo(`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 hc{apply(e,t){return Ql([n.apply([i]),fs([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 Tn((()=>{if(3!==e.length)throw new Xo(`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=Ud({ones:()=>bs(i),rate:this.dropout,training:n,count:4,dropoutFunc:this.dropoutFunc}));const r=this.dropoutMask,o=(e,t,n)=>t&&t[n]?Ei(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=Ud({ones:()=>bs(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]=Qs(this.kernel.read(),4,3),[k,x,S,N]=this.useBias?Qs(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,$,C]=Qs(this.recurrentKernel.read(),4,3);d=this.recurrentConv(d,T),m=this.recurrentConv(m,I),f=this.recurrentConv(f,$),g=this.recurrentConv(g,C);const A=this.recurrentActivation.apply($i(l,d)),E=this.recurrentActivation.apply($i(c,m)),j=$i(Ei(E,s),Ei(A,this.activation.apply($i(u,f)))),z=Ei(this.recurrentActivation.apply($i(h,g)),this.activation.apply(j));return[z,z,j]}))}getConfig(){const e=super.getConfig(),t=Wd(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=ha(e,t,this.strides,i||"valid","channelsFirst"===this.dataFormat?"NCHW":"NHWC",this.dilationRate);return n?rc(a,n,this.dataFormat):a}recurrentConv(e,t){return ha(e,t,1,"same","channelsFirst"===this.dataFormat?"NCHW":"NHWC")}}Vd.className="ConvLSTM2DCell",Ii(Vd);class Kd extends Gd{constructor(e){const t=new Vd(e);super(Object.assign(Object.assign({},e),{cell:t}))}static fromConfig(e,t){return new e(t)}}Kd.className="ConvLSTM2D",Ii(Kd);
|
|
4587
4587
|
/**
|
|
4588
4588
|
* @license
|
|
4589
4589
|
* Copyright 2018 Google LLC
|
|
@@ -4593,7 +4593,7 @@ function jd(e,t,n,i){if(Array.isArray(e)){if(null!=t||null!=n)throw new Xo("When
|
|
|
4593
4593
|
* https://opensource.org/licenses/MIT.
|
|
4594
4594
|
* =============================================================================
|
|
4595
4595
|
*/
|
|
4596
|
-
class qd extends Vc{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 Tn((()=>{this.invokeCallHook(e,t);const n=Dc(e);if(0<this.rate&&this.rate<1){const e=null!=t.training&&t.training,i=this.getNoiseShape(n);return lc((()=>oc(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()}}qd.className="Dropout",Ii(qd);class Hd extends qd{constructor(e){super(e),this.inputSpec=[{ndim:3}]}getNoiseShape(e){const t=e.shape;return[t[0],1,t[2]]}}Hd.className="SpatialDropout1D",Ii(Hd);class Jd extends Vc{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,bl(this.units,"units"),this.activation=ed(e.activation),null!=e.useBias&&(this.useBias=e.useBias),this.kernelInitializer=Ec(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.biasInitializer=Ec(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelConstraint=Nh(e.kernelConstraint),this.biasConstraint=Nh(e.biasConstraint),this.kernelRegularizer=rd(e.kernelRegularizer),this.biasRegularizer=rd(e.biasRegularizer),this.activityRegularizer=rd(e.activityRegularizer),this.supportsMasking=!0,this.inputSpec=[{minNDim:2}]}build(e){const t=(e=Fc(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=Fc(e)).slice();return t[t.length-1]=this.units,t}call(e,t){return Tn((()=>{this.invokeCallHook(e,t);const n=Dc(e),i=kl(this.activation.getClassName());let a;return null!=i?a=nc(n,this.kernel.read(),i,this.bias?this.bias.read():null):(a=nc(n,this.kernel.read()),null!=this.bias&&(a=rc(a,this.bias.read())),null!=this.activation&&(a=this.activation.apply(a))),a}))}getConfig(){const e={units:this.units,activation:Qp(this.activation),useBias:this.useBias,kernelInitializer
|
|
4596
|
+
class qd extends Vc{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 Tn((()=>{this.invokeCallHook(e,t);const n=Dc(e);if(0<this.rate&&this.rate<1){const e=null!=t.training&&t.training,i=this.getNoiseShape(n);return lc((()=>oc(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()}}qd.className="Dropout",Ii(qd);class Hd extends qd{constructor(e){super(e),this.inputSpec=[{ndim:3}]}getNoiseShape(e){const t=e.shape;return[t[0],1,t[2]]}}Hd.className="SpatialDropout1D",Ii(Hd);class Jd extends Vc{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,bl(this.units,"units"),this.activation=ed(e.activation),null!=e.useBias&&(this.useBias=e.useBias),this.kernelInitializer=Ec(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.biasInitializer=Ec(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelConstraint=Nh(e.kernelConstraint),this.biasConstraint=Nh(e.biasConstraint),this.kernelRegularizer=rd(e.kernelRegularizer),this.biasRegularizer=rd(e.biasRegularizer),this.activityRegularizer=rd(e.activityRegularizer),this.supportsMasking=!0,this.inputSpec=[{minNDim:2}]}build(e){const t=(e=Fc(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=Fc(e)).slice();return t[t.length-1]=this.units,t}call(e,t){return Tn((()=>{this.invokeCallHook(e,t);const n=Dc(e),i=kl(this.activation.getClassName());let a;return null!=i?a=nc(n,this.kernel.read(),i,this.bias?this.bias.read():null):(a=nc(n,this.kernel.read()),null!=this.bias&&(a=rc(a,this.bias.read())),null!=this.activation&&(a=this.activation.apply(a))),a}))}getConfig(){const e={units:this.units,activation:Qp(this.activation),useBias:this.useBias,kernelInitializer:Ac(this.kernelInitializer),biasInitializer:Ac(this.biasInitializer),kernelRegularizer:ad(this.kernelRegularizer),biasRegularizer:ad(this.biasRegularizer),activityRegularizer:ad(this.activityRegularizer),kernelConstraint:xh(this.kernelConstraint),biasConstraint:xh(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}}Jd.className="Dense",Ii(Jd);class Zd extends Vc{constructor(e){super(e=e||{}),this.inputSpec=[{minNDim:3}],this.dataFormat=e.dataFormat}computeOutputShape(e){e=Fc(e);for(const t of e.slice(1))if(null==t)throw new Xo(`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],Bl(e,1)]}call(e,t){return Tn((()=>{this.invokeCallHook(e,t);let n=Dc(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=vi(n,e)}return function(e){if(e.rank<=1)throw new Xo(`batchFlatten requires a minimum rank of 2. Got rank: ${e.rank}.`);const t=[e.shape[0],Bl(e.shape,1)];return Wi(e,t)}(n)}))}getConfig(){const e={};null!=this.dataFormat&&(e.dataFormat=this.dataFormat);const t=super.getConfig();return Object.assign(e,t),e}}Zd.className="Flatten",Ii(Zd);class Yd extends Vc{constructor(e){super(e),this.supportsMasking=!0,this.activation=ed(e.activation)}call(e,t){return Tn((()=>{this.invokeCallHook(e,t);const n=Dc(e);return this.activation.apply(n)}))}getConfig(){const e={activation:Qp(this.activation)},t=super.getConfig();return Object.assign(e,t),e}}Yd.className="Activation",Ii(Yd);class Qd extends Vc{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 Tn((()=>{return e=Dc(e),t=e,n=this.n,Tn((()=>{if(2!==t.shape.length)throw new Xo(`repeat() expects a rank-2 tensor, but received a rank-${t.shape.length} tensor.`);return ec(Hl(t,1),[1,n,1])}));var t,n}))}getConfig(){const e={n:this.n},t=super.getConfig();return Object.assign(e,t),e}}Qd.className="RepeatVector",Ii(Qd);class Xd extends Vc{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 Xo("Can only specifiy one unknown dimension.");s=e}else a*=t}const r=Bl(e);if(null!==s){if(0===a||r%a!=0)throw new Xo(n);i[s]=r/a}else if(r!==a)throw new Xo(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 Tn((()=>{this.invokeCallHook(e,t);const n=Dc(e),i=n.shape,a=i.slice(0,1).concat(this.fixUnknownDimension(i.slice(1),this.targetShape));return Wi(n,a)}))}getConfig(){const e={targetShape:this.targetShape},t=super.getConfig();return Object.assign(e,t),e}}Xd.className="Reshape",Ii(Xd);class em extends Vc{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=Gl(1,e.dims.length+1);if(!A(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 Pc({ndim:this.dims.length+1})]}computeOutputShape(e){const t=(e=Fc(e)).slice();return this.dims.forEach(((n,i)=>{t[i+1]=e[n]})),t}call(e,t){return vi(Dc(e),this.dimsIncludingBatch)}getConfig(){const e={dims:this.dims},t=super.getConfig();return Object.assign(e,t),e}}em.className="Permute",Ii(em);class tm extends Vc{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=Dc(e);return Di(ys(n,this.maskValue),-1)}call(e,t){return Tn((()=>{this.invokeCallHook(e,t);const n=Dc(e),i=Di(ys(n,this.maskValue),-1,!0);return Ei(n,hi(i,n.dtype))}))}}tm.className="Masking",Ii(tm);
|
|
4597
4597
|
/**
|
|
4598
4598
|
* @license
|
|
4599
4599
|
* Copyright 2018 Google LLC
|
|
@@ -4603,7 +4603,7 @@ class qd extends Vc{constructor(e){super(e),this.rate=Math.max(Math.min(e.rate,1
|
|
|
4603
4603
|
* https://opensource.org/licenses/MIT.
|
|
4604
4604
|
* =============================================================================
|
|
4605
4605
|
*/
|
|
4606
|
-
class nm extends Vc{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(ol(e.inputLength))}this.inputDim=e.inputDim,bl(this.inputDim,"inputDim"),this.outputDim=e.outputDim,bl(this.outputDim,"outputDim"),this.embeddingsInitializer=Ec(e.embeddingsInitializer||this.DEFAULT_EMBEDDINGS_INITIALIZER),this.embeddingsRegularizer=rd(e.embeddingsRegularizer),this.activityRegularizer=rd(e.activityRegularizer),this.embeddingsConstraint=Nh(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 Tn((()=>this.maskZero?(e=Dc(e),ys(e,Ia(e))):null))}computeOutputShape(e){if(e=Fc(e),null==this.inputLength)return[...e,this.outputDim];const t=ol(this.inputLength);if(t.length!==e.length-1)throw new Xo(`"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 Xo(`"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 Tn((()=>{this.invokeCallHook(e,t);let n=Dc(e);"int32"!==n.dtype&&(n=ql(n,"int32"));const i=ic(this.embeddings.read(),Wi(n,[n.size]));return Wi(i,Fc(this.computeOutputShape(n.shape)))}))}getConfig(){const e={inputDim:this.inputDim,outputDim:this.outputDim,embeddingsInitializer
|
|
4606
|
+
class nm extends Vc{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(ol(e.inputLength))}this.inputDim=e.inputDim,bl(this.inputDim,"inputDim"),this.outputDim=e.outputDim,bl(this.outputDim,"outputDim"),this.embeddingsInitializer=Ec(e.embeddingsInitializer||this.DEFAULT_EMBEDDINGS_INITIALIZER),this.embeddingsRegularizer=rd(e.embeddingsRegularizer),this.activityRegularizer=rd(e.activityRegularizer),this.embeddingsConstraint=Nh(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 Tn((()=>this.maskZero?(e=Dc(e),ys(e,Ia(e))):null))}computeOutputShape(e){if(e=Fc(e),null==this.inputLength)return[...e,this.outputDim];const t=ol(this.inputLength);if(t.length!==e.length-1)throw new Xo(`"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 Xo(`"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 Tn((()=>{this.invokeCallHook(e,t);let n=Dc(e);"int32"!==n.dtype&&(n=ql(n,"int32"));const i=ic(this.embeddings.read(),Wi(n,[n.size]));return Wi(i,Fc(this.computeOutputShape(n.shape)))}))}getConfig(){const e={inputDim:this.inputDim,outputDim:this.outputDim,embeddingsInitializer:Ac(this.embeddingsInitializer),embeddingsRegularizer:ad(this.embeddingsRegularizer),activityRegularizer:ad(this.activityRegularizer),embeddingsConstraint:xh(this.embeddingsConstraint),maskZero:this.maskZero,inputLength:this.inputLength},t=super.getConfig();return Object.assign(e,t),e}}nm.className="Embedding",Ii(nm);
|
|
4607
4607
|
/**
|
|
4608
4608
|
* @license
|
|
4609
4609
|
* Copyright 2018 Google LLC
|
|
@@ -4613,7 +4613,7 @@ class nm extends Vc{constructor(e){if(super(e),this.embeddings=null,this.DEFAULT
|
|
|
4613
4613
|
* https://opensource.org/licenses/MIT.
|
|
4614
4614
|
* =============================================================================
|
|
4615
4615
|
*/
|
|
4616
|
-
class im extends Vc{constructor(e){super(e||{}),this.supportsMasking=!0}mergeFunction(e){throw new el}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 Xo("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=[Fc(e)]),e.length<2)throw new Xo(`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=fl(t),t.length>1)throw new Xo(`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===fl(i).length?this.reshapeRequired=!1:this.reshapeRequired=!0}call(e,t){return Tn((()=>{if(this.reshapeRequired){const t=[],n=e.map((e=>e.rank));if(-1===n.indexOf(null)){const i=Wl(n);for(let n of e){const e=n.rank;for(let t=0;t<i-e;++t)n=Hl(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=Wi(i,[a].concat(Bl(e.slice(1))));r=vi(r,[1,0]),r=Wi(r,s),t.push(r),n=!0}else if(e>1){const a=Gl(1,e).concat([0]);t.push(vi(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=Wi(vi(Wi(i,[-1,t]),[1,0]),n)}else if(a>1){const e=[a-1].concat(Gl(0,a-1));i=vi(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=fl(n),t=1===n.length?n.concat(t):[null].concat(t),t}computeMask(e,t){return Tn((()=>{if(null==t)return null;if(!Array.isArray(t))throw new Xo("`mask` should be an Array");if(!Array.isArray(e))throw new Xo("`inputs` should be an Array");if(t.length!==e.length)throw new Xo(`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:Va(e,0))))[0];for(let e=1;e<t.length-1;++e)n=ls(n,t[e]);return n}))}}class am extends im{constructor(e){super(e)}mergeFunction(e){return Tn((()=>{let t=e[0].clone();for(let n=1;n<e.length;++n)t
|
|
4616
|
+
class im extends Vc{constructor(e){super(e||{}),this.supportsMasking=!0}mergeFunction(e){throw new el}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 Xo("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=[Fc(e)]),e.length<2)throw new Xo(`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=fl(t),t.length>1)throw new Xo(`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===fl(i).length?this.reshapeRequired=!1:this.reshapeRequired=!0}call(e,t){return Tn((()=>{if(this.reshapeRequired){const t=[],n=e.map((e=>e.rank));if(-1===n.indexOf(null)){const i=Wl(n);for(let n of e){const e=n.rank;for(let t=0;t<i-e;++t)n=Hl(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=Wi(i,[a].concat(Bl(e.slice(1))));r=vi(r,[1,0]),r=Wi(r,s),t.push(r),n=!0}else if(e>1){const a=Gl(1,e).concat([0]);t.push(vi(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=Wi(vi(Wi(i,[-1,t]),[1,0]),n)}else if(a>1){const e=[a-1].concat(Gl(0,a-1));i=vi(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=fl(n),t=1===n.length?n.concat(t):[null].concat(t),t}computeMask(e,t){return Tn((()=>{if(null==t)return null;if(!Array.isArray(t))throw new Xo("`mask` should be an Array");if(!Array.isArray(e))throw new Xo("`inputs` should be an Array");if(t.length!==e.length)throw new Xo(`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:Va(e,0))))[0];for(let e=1;e<t.length-1;++e)n=ls(n,t[e]);return n}))}}class am extends im{constructor(e){super(e)}mergeFunction(e){return Tn((()=>{let t=e[0].clone();for(let n=1;n<e.length;++n)t=$i(t,e[n]);return t}))}}am.className="Add",Ii(am);class sm extends im{constructor(e){super(e)}mergeFunction(e){return Tn((()=>{let t=e[0].clone();for(let n=1;n<e.length;++n)t=Ei(t,e[n]);return t}))}}sm.className="Multiply",Ii(sm);class rm extends im{constructor(e){super(e)}mergeFunction(e){return Tn((()=>{let t=e[0].clone();for(let n=1;n<e.length;++n)t=$i(t,e[n]);return Ei(1/e.length,t)}))}}rm.className="Average",Ii(rm);class om extends im{constructor(e){super(e)}mergeFunction(e){return Tn((()=>{let t=e[0];for(let n=1;n<e.length;++n)t=ps(t,e[n]);return t}))}}om.className="Maximum",Ii(om);class lm extends im{constructor(e){super(e)}mergeFunction(e){return Tn((()=>{let t=e[0];for(let n=1;n<e.length;++n)t=gs(t,e[n]);return t}))}}lm.className="Minimum",Ii(lm);class cm extends im{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 Xo("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(A(e,i)){a=!0;break}a||n.push(i)}if(n.length>1)throw new Xo("A `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got input shapes: "+JSON.stringify(e))}mergeFunction(e){return Tn((()=>Ql(e,this.axis)))}computeOutputShape(e){if(!Array.isArray(e)||!Array.isArray(e[0]))throw new Xo("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 Xo("`mask` should be an array for Concatenate");if(!Array.isArray(e))throw new Xo("`inputs` should be an array for Concatenate");if(t.length!==e.length)throw new Xo(`Mismatch in the length of mask (${t.length}) and the legnth of inputs (${e.length})`);return Tn((()=>{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(hi(bs(e[n]),"bool")):t[n].rank<e[n].rank?i.push(Va(t[n],-1)):i.push(t[n]);const a=qi(i,this.axis);return zi(a,-1,!1)}))}getConfig(){const e={axis:this.axis},t=super.getConfig();return Object.assign(e,t),e}}function um(e,t){for(;e<0;)e+=t;return e}cm.className="Concatenate",Ii(cm);class hm extends im{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 el("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 Xo(`Dimension incompatibility: ${t[i[0]]} !== ${n[i[1]]}`)}mergeFunction(e){if(2!==e.length)throw new Xo(`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)=>um(t,e[n].shape.length))):[um(this.axes,n.shape.length),um(this.axes,i.shape.length)],this.normalize&&(n=Lh(n,t[0]),i=Lh(i,t[1])),function(e,t,n){if(e.shape.length>3||t.shape.length>3)throw new el("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 el("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 Tn((()=>{let n,r;if(i>a){n=i-a;const e=[];for(let t=0;t<n;++t)e.push(1);t=Wi(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=Wi(e,e.shape.concat(t))}else n=0;if(2===e.shape.length&&2===t.shape.length)r=s[0]===s[1]?Ba(Ei(e,t),s[0]):Ba(Ei(vi(e,[1,0]),t),s[1]);else{const n=s[0]!==e.shape.length-1,i=s[1]===t.shape.length-1;r=pi(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=Xs(r,t)}return 1===r.shape.length&&(r=Va(r,1)),r}))}(n,i,t)}interpretAxes(e,t){let n;return n=Array.isArray(this.axes)?this.axes:[um(this.axes,e.length),um(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 el("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}}hm.className="Dot",Ii(hm);
|
|
4617
4617
|
/**
|
|
4618
4618
|
* @license
|
|
4619
4619
|
* Copyright 2018 Google LLC
|
|
@@ -4623,7 +4623,7 @@ class im extends Vc{constructor(e){super(e||{}),this.supportsMasking=!0}mergeFun
|
|
|
4623
4623
|
* https://opensource.org/licenses/MIT.
|
|
4624
4624
|
* =============================================================================
|
|
4625
4625
|
*/
|
|
4626
|
-
class pm extends Vc{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 Tn((()=>{this.invokeCallHook(e,t);const n=Dc(e);return lc((()
|
|
4626
|
+
class pm extends Vc{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 Tn((()=>{this.invokeCallHook(e,t);const n=Dc(e);return lc((()=>$i(tc(n.shape,0,this.stddev),n)),(()=>n),t.training||!1)}))}}pm.className="GaussianNoise",Ii(pm);class dm extends Vc{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 Tn((()=>{this.invokeCallHook(e,t);const n=Dc(e);if(this.rate>0&&this.rate<1){return lc((()=>{const e=Math.sqrt(this.rate/(1-this.rate));return Ei(n,tc(n.shape,1,e))}),(()=>n),t.training||!1)}return n}))}}dm.className="GaussianDropout",Ii(dm);class mm extends Vc{constructor(e){super(e),this.supportsMasking=!0,this.rate=e.rate,this.noiseShape=e.noiseShape}_getNoiseShape(e){return this.noiseShape||Dc(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 Tn((()=>{if(this.rate<1&&this.rate>0){const n=this._getNoiseShape(e);return lc((()=>{const t=Dc(e),i=-1.7580993408473766;let a=Ya(Rs(n),this.rate);a=ql(a,"float32");const s=((1-this.rate)*(1+this.rate*i**2))**-.5,r=-s*i*this.rate,o=$i(Ei(t,a),Ei($i(a,-1),i));return $i(Ei(o,s),r)}),(()=>Dc(e)),t.training||!1)}return e}))}}
|
|
4627
4627
|
/**
|
|
4628
4628
|
* @license
|
|
4629
4629
|
* Copyright 2018 Google LLC
|
|
@@ -4633,7 +4633,7 @@ class pm extends Vc{constructor(e){super(e),this.supportsMasking=!0,this.stddev=
|
|
|
4633
4633
|
* https://opensource.org/licenses/MIT.
|
|
4634
4634
|
* =============================================================================
|
|
4635
4635
|
*/
|
|
4636
|
-
function fm(e,t,n,i,a,s=.001){let r;if(2===e.rank)r=Xi(e,t,n,i,a,s);else if(3===e.rank)r=ea(e,t,n,i,a,s);else{if(4!==e.rank)throw new el(`batchNormalization is not implemented for array of rank ${e.rank} yet`);r=ta(e,t,n,i,a,s)}return r}function gm(e,t,n,i,a=.001){return
|
|
4636
|
+
function fm(e,t,n,i,a,s=.001){let r;if(2===e.rank)r=Xi(e,t,n,i,a,s);else if(3===e.rank)r=ea(e,t,n,i,a,s);else{if(4!==e.rank)throw new el(`batchNormalization is not implemented for array of rank ${e.rank} yet`);r=ta(e,t,n,i,a,s)}return r}function gm(e,t,n,i,a=.001){return A(i.slice().sort(),Gl(0,e.rank-1))?function(e,t,n,i,a=.001){return Tn((()=>{const s=vs(e,i),r=s.mean,o=s.variance;return[fm(e,r,o,n,t,a),r,o]}))}(e,t,n,i,a):function(e,t,n,i,a=.001){return Tn((()=>{const s=vs(e,i),r=s.mean,o=s.variance,l=[];for(const t of Gl(0,e.rank))-1!==i.indexOf(t)?l.push(1):l.push(e.shape[t]);const c=Wi(r,l),u=Wi(o,l),h=null==t?null:Wi(t,l),p=null==n?null:Wi(n,l);return[fm(e,c,u,p,h,a),r,o]}))}(e,t,n,i,a)}mm.className="AlphaDropout",Ii(mm);class vm extends Vc{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=Ec(e.betaInitializer||"zeros"),this.gammaInitializer=Ec(e.gammaInitializer||"ones"),this.movingMeanInitializer=Ec(e.movingMeanInitializer||"zeros"),this.movingVarianceInitializer=Ec(e.movingVarianceInitializer||"ones"),this.betaConstraint=Nh(e.betaConstraint),this.gammaConstraint=Nh(e.gammaConstraint),this.betaRegularizer=rd(e.betaRegularizer),this.gammaRegularizer=rd(e.gammaRegularizer)}build(e){e=Fc(e);const t=this.axis>=0?this.axis:this.axis+e.length,n=e[t];if(null==n)throw new Xo(`Axis ${t} of input tensor should have a defined dimension but the layer received an input with shape ${JSON.stringify(e)}.`);this.inputSpec=[new Pc({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 Tn((()=>{const n=null!=t.training&&t.training,i=Dc(e),a=i.shape,s=a.length,r=Gl(0,s),o=this.axis>=0?this.axis:this.axis+s;r.splice(o,1);const l=il(1,s);l[o]=a[o];const c=r.slice();c.sort();const u=!A(c,Gl(0,s).slice(0,s-1));if(!n)return(()=>{if(u){const e=Wi(this.movingMean.read(),l),t=Wi(this.movingVariance.read(),l),n=this.center?Wi(this.beta.read(),l):null,a=this.scale?Wi(this.gamma.read(),l):null;return fm(i,e,t,n,a,this.epsilon)}return fm(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]=gm(i,this.gamma.read(),this.beta.read(),r,this.epsilon),m=(e,t,n)=>{Tn((()=>{const i=1-n,a=e.read(),s=Ei(ss(a,t),i);e.write(ss(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:Ac(this.betaInitializer),gammaInitializer:Ac(this.gammaInitializer),movingMeanInitializer:Ac(this.movingMeanInitializer),movingVarianceInitializer:Ac(this.movingVarianceInitializer),betaRegularizer:ad(this.betaRegularizer),gammaRegularizer:ad(this.gammaRegularizer),betaConstraint:xh(this.betaConstraint),gammaConstraint:xh(this.gammaConstraint)},t=super.getConfig();return Object.assign(e,t),e}}vm.className="BatchNormalization",Ii(vm);class ym extends Vc{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=Ec(e.betaInitializer||"zeros"),this.gammaInitializer=Ec(e.gammaInitializer||"ones"),this.betaRegularizer=rd(e.betaRegularizer),this.gammaRegularizer=rd(e.gammaRegularizer),this.supportsMasking=!0}build(e){const t=(e=Fc(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!==fl(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=Dc(e),i=n.shape,a=i.length;return Tn((()=>{let{mean:e,variance:t}=vs(n,this.axis,!0);const s=il(1,a);for(const e of this.axis)s[e]=i[e];const r=e=>null!=e&&e.shape.length!==a?Wi(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=Ka(e,c),t=Ka(t,c),null!=o&&(o=Ka(o,u)),null!=l&&(l=Ka(l,u)),fm(n,e,t,l,o,this.epsilon)}))}getConfig(){const e={axis:this.axis,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:Ac(this.betaInitializer),gammaInitializer:Ac(this.gammaInitializer),betaRegularizer:ad(this.betaRegularizer),gammaRegularizer:ad(this.gammaRegularizer)},t=super.getConfig();return Object.assign(e,t),e}}ym.className="LayerNormalization",Ii(ym);class bm extends Vc{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 Xo(`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 Xo(`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 Xo(`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 Pc({ndim:4})]}computeOutputShape(e){let t,n;return e=Fc(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 Tn((()=>{return t=Dc(e),n=this.padding,i=this.dataFormat,Tn((()=>{if(4!==t.rank)throw new Xo(`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 Xo("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 Xo(`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]],ws(t,e)}));
|
|
4637
4637
|
/**
|
|
4638
4638
|
* @license
|
|
4639
4639
|
* Copyright 2018 Google LLC
|
|
@@ -4653,7 +4653,7 @@ var t,n,i}))}getConfig(){const e={padding:this.padding,dataFormat:this.dataForma
|
|
|
4653
4653
|
* https://opensource.org/licenses/MIT.
|
|
4654
4654
|
* =============================================================================
|
|
4655
4655
|
*/
|
|
4656
|
-
function wm(e,t,n,i,a,s){return Tn((()=>{let r;zl(a),Fl(s),Dl(i),null==n&&(n=[1,1]),null==i&&(i="valid"),null==a&&(a="channelsLast"),null==s&&(s="max"),e=gd(e,a);const o="same"===i?"same":"valid";return r="max"===s?us(e,t,n,o):Gi(e,t,n,o),"channelsFirst"===a&&(r=vi(r,[0,3,1,2])),r}))}function km(e,t,n,i,a,s){return Tn((()=>{let r;zl(a),Fl(s),Dl(i),null==n&&(n=[1,1,1]),null==i&&(i="valid"),null==a&&(a="channelsLast"),null==s&&(s="max"),e=vd(e,a);const o="same"===i?"same":"valid";return r="max"===s?hs(e,t,n,o):Vi(e,t,n,o),"channelsFirst"===a&&(r=vi(r,[0,4,1,2,3])),r}))}bm.className="ZeroPadding2D",Ii(bm);class xm extends Vc{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 Xo(`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(bl(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 Xo(`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}bl(this.strides,"strides"),this.padding=null==e.padding?"valid":e.padding,Dl(this.padding),this.inputSpec=[new Pc({ndim:3})]}computeOutputShape(e){const t=md((e=Fc(e))[1],this.poolSize[0],this.padding,this.strides[0]);return[e[0],t,e[2]]}call(e,t){return Tn((()=>{this.invokeCallHook(e,t),e=Hl(Dc(e),2);const n=this.poolingFunction(Dc(e),[this.poolSize[0],1],[this.strides[0],1],this.padding,"channelsLast");return Xs(n,[2])}))}getConfig(){const e={poolSize:this.poolSize,padding:this.padding,strides:this.strides},t=super.getConfig();return Object.assign(e,t),e}}class Sm extends xm{constructor(e){super(e)}poolingFunction(e,t,n,i,a){return zl(a),Dl(i),wm(e,t,n,i,a,"max")}}Sm.className="MaxPooling1D",Ii(Sm);class Nm extends xm{constructor(e){super(e)}poolingFunction(e,t,n,i,a){return zl(a),Dl(i),wm(e,t,n,i,a,"avg")}}Nm.className="AveragePooling1D",Ii(Nm);class Tm extends Vc{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 Xo(`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];bl(this.poolSize,"poolSize"),bl(this.strides,"strides"),this.padding=null==e.padding?"valid":e.padding,this.dataFormat=null==e.dataFormat?"channelsLast":e.dataFormat,zl(this.dataFormat),Dl(this.padding),this.inputSpec=[new Pc({ndim:4})]}computeOutputShape(e){e=Fc(e);let t="channelsFirst"===this.dataFormat?e[2]:e[1],n="channelsFirst"===this.dataFormat?e[3]:e[2];return t=md(t,this.poolSize[0],this.padding,this.strides[0]),n=md(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 Tn((()=>(this.invokeCallHook(e,t),this.poolingFunction(Dc(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 Im extends Tm{constructor(e){super(e)}poolingFunction(e,t,n,i,a){return zl(a),Dl(i),wm(e,t,n,i,a,"max")}}Im.className="MaxPooling2D",Ii(Im);class
|
|
4656
|
+
function wm(e,t,n,i,a,s){return Tn((()=>{let r;zl(a),Fl(s),Dl(i),null==n&&(n=[1,1]),null==i&&(i="valid"),null==a&&(a="channelsLast"),null==s&&(s="max"),e=gd(e,a);const o="same"===i?"same":"valid";return r="max"===s?us(e,t,n,o):Gi(e,t,n,o),"channelsFirst"===a&&(r=vi(r,[0,3,1,2])),r}))}function km(e,t,n,i,a,s){return Tn((()=>{let r;zl(a),Fl(s),Dl(i),null==n&&(n=[1,1,1]),null==i&&(i="valid"),null==a&&(a="channelsLast"),null==s&&(s="max"),e=vd(e,a);const o="same"===i?"same":"valid";return r="max"===s?hs(e,t,n,o):Vi(e,t,n,o),"channelsFirst"===a&&(r=vi(r,[0,4,1,2,3])),r}))}bm.className="ZeroPadding2D",Ii(bm);class xm extends Vc{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 Xo(`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(bl(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 Xo(`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}bl(this.strides,"strides"),this.padding=null==e.padding?"valid":e.padding,Dl(this.padding),this.inputSpec=[new Pc({ndim:3})]}computeOutputShape(e){const t=md((e=Fc(e))[1],this.poolSize[0],this.padding,this.strides[0]);return[e[0],t,e[2]]}call(e,t){return Tn((()=>{this.invokeCallHook(e,t),e=Hl(Dc(e),2);const n=this.poolingFunction(Dc(e),[this.poolSize[0],1],[this.strides[0],1],this.padding,"channelsLast");return Xs(n,[2])}))}getConfig(){const e={poolSize:this.poolSize,padding:this.padding,strides:this.strides},t=super.getConfig();return Object.assign(e,t),e}}class Sm extends xm{constructor(e){super(e)}poolingFunction(e,t,n,i,a){return zl(a),Dl(i),wm(e,t,n,i,a,"max")}}Sm.className="MaxPooling1D",Ii(Sm);class Nm extends xm{constructor(e){super(e)}poolingFunction(e,t,n,i,a){return zl(a),Dl(i),wm(e,t,n,i,a,"avg")}}Nm.className="AveragePooling1D",Ii(Nm);class Tm extends Vc{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 Xo(`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];bl(this.poolSize,"poolSize"),bl(this.strides,"strides"),this.padding=null==e.padding?"valid":e.padding,this.dataFormat=null==e.dataFormat?"channelsLast":e.dataFormat,zl(this.dataFormat),Dl(this.padding),this.inputSpec=[new Pc({ndim:4})]}computeOutputShape(e){e=Fc(e);let t="channelsFirst"===this.dataFormat?e[2]:e[1],n="channelsFirst"===this.dataFormat?e[3]:e[2];return t=md(t,this.poolSize[0],this.padding,this.strides[0]),n=md(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 Tn((()=>(this.invokeCallHook(e,t),this.poolingFunction(Dc(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 Im extends Tm{constructor(e){super(e)}poolingFunction(e,t,n,i,a){return zl(a),Dl(i),wm(e,t,n,i,a,"max")}}Im.className="MaxPooling2D",Ii(Im);class $m extends Tm{constructor(e){super(e)}poolingFunction(e,t,n,i,a){return zl(a),Dl(i),wm(e,t,n,i,a,"avg")}}$m.className="AveragePooling2D",Ii($m);class Cm extends Vc{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 Xo(`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];bl(this.poolSize,"poolSize"),bl(this.strides,"strides"),this.padding=null==e.padding?"valid":e.padding,this.dataFormat=null==e.dataFormat?"channelsLast":e.dataFormat,zl(this.dataFormat),Dl(this.padding),this.inputSpec=[new Pc({ndim:5})]}computeOutputShape(e){e=Fc(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=md(t,this.poolSize[0],this.padding,this.strides[0]),n=md(n,this.poolSize[1],this.padding,this.strides[1]),i=md(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 Tn((()=>(this.invokeCallHook(e,t),this.poolingFunction(Dc(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 Am extends Cm{constructor(e){super(e)}poolingFunction(e,t,n,i,a){return zl(a),Dl(i),km(e,t,n,i,a,"max")}}Am.className="MaxPooling3D",Ii(Am);class Em extends Cm{constructor(e){super(e)}poolingFunction(e,t,n,i,a){return zl(a),Dl(i),km(e,t,n,i,a,"avg")}}Em.className="AveragePooling3D",Ii(Em);class jm extends Vc{constructor(e){super(e),this.inputSpec=[new Pc({ndim:3})]}computeOutputShape(e){return[e[0],e[2]]}call(e,t){throw new el}}class zm extends jm{constructor(e){super(e||{})}call(e,t){return Tn((()=>{const t=Dc(e);return ds(t,1)}))}}zm.className="GlobalAveragePooling1D",Ii(zm);class Dm extends jm{constructor(e){super(e||{})}call(e,t){return Tn((()=>{const t=Dc(e);return _a(t,1)}))}}Dm.className="GlobalMaxPooling1D",Ii(Dm);class Fm extends Vc{constructor(e){super(e),this.dataFormat=null==e.dataFormat?"channelsLast":e.dataFormat,zl(this.dataFormat),this.inputSpec=[new Pc({ndim:4})]}computeOutputShape(e){return"channelsLast"===this.dataFormat?[e[0],e[3]]:[e[0],e[1]]}call(e,t){throw new el}getConfig(){const e={dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}class _m extends Fm{call(e,t){return Tn((()=>{const t=Dc(e);return"channelsLast"===this.dataFormat?ds(t,[1,2]):ds(t,[2,3])}))}}_m.className="GlobalAveragePooling2D",Ii(_m);class Rm extends Fm{call(e,t){return Tn((()=>{const t=Dc(e);return"channelsLast"===this.dataFormat?_a(t,[1,2]):_a(t,[2,3])}))}}Rm.className="GlobalMaxPooling2D",Ii(Rm);
|
|
4657
4657
|
/**
|
|
4658
4658
|
* @license
|
|
4659
4659
|
* Copyright 2018 Google LLC
|
|
@@ -4663,7 +4663,7 @@ function wm(e,t,n,i,a,s){return Tn((()=>{let r;zl(a),Fl(s),Dl(i),null==n&&(n=[1,
|
|
|
4663
4663
|
* https://opensource.org/licenses/MIT.
|
|
4664
4664
|
* =============================================================================
|
|
4665
4665
|
*/
|
|
4666
|
-
class Lm extends Vc{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=Rh(t.layer,n);delete t.layer;const a={layer:i};return Object.assign(a,t),new e(a)}}class Mm extends Lm{constructor(e){super(e),this.supportsMasking=!0}build(e){if((e=Fc(e)).length<3)throw new Xo(`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=Fc(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 Tn((()=>zd(((e,n)=>[Dc(this.layer.call(e,t)),[]]),e=Dc(e),[],!1,null,null,!1,!0)[1]))}}Mm.className="TimeDistributed",Ii(Mm);class Om extends Lm{constructor(e){super(e);const t=e.layer.getConfig(),n={};n.className=e.layer.getClassName(),n.config=t,this.forwardLayer=Rh(n),t.goBackwards=!0!==t.goBackwards;const i={};var a;if(i.className=e.layer.getClassName(),i.config=t,this.backwardLayer=Rh(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,vl(El,"BidirectionalMergeMode",a),e.weights)throw new el("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()):rl(n)}apply(e,t){let n=null==t?null:t.initialState,i=null==t?null:t.constants;null==t&&(t={});const a=jd(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 Xo("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 Pc({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 el("Support for constants in Bidirectional layers is not implemented yet.");const o=s[0]instanceof Bc;for(const e of s)if(e instanceof Bc!==o)throw new Xo("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 Tn((()=>{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=Ps(a,1)),"concat"===this.mergeMode?r=Ql([i,a]):"sum"===this.mergeMode?r
|
|
4666
|
+
class Lm extends Vc{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=Rh(t.layer,n);delete t.layer;const a={layer:i};return Object.assign(a,t),new e(a)}}class Mm extends Lm{constructor(e){super(e),this.supportsMasking=!0}build(e){if((e=Fc(e)).length<3)throw new Xo(`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=Fc(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 Tn((()=>zd(((e,n)=>[Dc(this.layer.call(e,t)),[]]),e=Dc(e),[],!1,null,null,!1,!0)[1]))}}Mm.className="TimeDistributed",Ii(Mm);class Om extends Lm{constructor(e){super(e);const t=e.layer.getConfig(),n={};n.className=e.layer.getClassName(),n.config=t,this.forwardLayer=Rh(n),t.goBackwards=!0!==t.goBackwards;const i={};var a;if(i.className=e.layer.getClassName(),i.config=t,this.backwardLayer=Rh(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,vl(El,"BidirectionalMergeMode",a),e.weights)throw new el("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()):rl(n)}apply(e,t){let n=null==t?null:t.initialState,i=null==t?null:t.constants;null==t&&(t={});const a=jd(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 Xo("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 Pc({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 el("Support for constants in Bidirectional layers is not implemented yet.");const o=s[0]instanceof Bc;for(const e of s)if(e instanceof Bc!==o)throw new Xo("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 Tn((()=>{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=Ps(a,1)),"concat"===this.mergeMode?r=Ql([i,a]):"sum"===this.mergeMode?r=$i(i,a):"ave"===this.mergeMode?r=Ei(.5,$i(i,a)):"mul"===this.mergeMode?r=Ei(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){Rl(this.forwardLayer.name,(()=>{this.forwardLayer.build(e)})),Rl(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=Rh(t.layer);if(delete t.layer,null!=t.numConstants)throw new el("Deserialization of a Bidirectional layer with numConstants present is not supported yet.");const i=t;return i.layer=n,new e(i)}}Om.className="Bidirectional",Ii(Om);
|
|
4667
4667
|
/**
|
|
4668
4668
|
* @license
|
|
4669
4669
|
* Copyright 2022 CodeSmith LLC
|
|
@@ -4673,7 +4673,7 @@ class Lm extends Vc{constructor(e){super(e),this.layer=e.layer}build(e){this.bui
|
|
|
4673
4673
|
* https://opensource.org/licenses/MIT.
|
|
4674
4674
|
* =============================================================================
|
|
4675
4675
|
*/
|
|
4676
|
-
class Pm extends Vc{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 Tn((()=>("float32"!==(e=Dc(e)).dtype&&(e=ql(e,"float32"))
|
|
4676
|
+
class Pm extends Vc{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 Tn((()=>("float32"!==(e=Dc(e)).dtype&&(e=ql(e,"float32")),$i(Ei(e,this.scale),this.offset))))}}Pm.className="Rescaling",Ii(Pm);
|
|
4677
4677
|
/**
|
|
4678
4678
|
* @license
|
|
4679
4679
|
* Copyright 2022 CodeSmith LLC
|
|
@@ -4760,7 +4760,7 @@ const Jm=new Set(["bilinear","nearest"]);class Zm extends Hm{constructor(e){supe
|
|
|
4760
4760
|
* limitations under the License.
|
|
4761
4761
|
* =============================================================================
|
|
4762
4762
|
*/
|
|
4763
|
-
xt(Lo),xt(ko),xt(Oo),xt(Po),xt(Bo),xt(Uo),xt(zo),xt(Wo),xt(Zo),xt($o),xt(qo),xt(Fo),xt(bo);var Ym={"штих":"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 Qm{encode(t){const n=new Uint8Array(1);switch(t.wordClass){case e.WordClass.NOUN:n[0]=1;break;case e.WordClass.ADJECTIVE:n[0]=0;break;default:throw new TypeError(`Invalid word class: "${t.wordClass}".`)}return n}decode(t){if(t.length<1||t.length>1)throw new RangeError("Invalid vector length.");const n=t[0];if(n<0||n>1)throw new RangeError("Invalid vector value.");return{wordClass:n>=.5?e.WordClass.NOUN:e.WordClass.ADJECTIVE}}}class Xm{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 ef={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"},tf=[{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"}],nf="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",af={format:"layers-model",generatedBy:"TensorFlow.js tfjs-layers v4.2.0",convertedBy:null};const sf="undefined"!=typeof Buffer&&("undefined"==typeof Blob||"undefined"==typeof atob||"undefined"==typeof btoa);class rf{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 of=/[ая]$/i,lf=/(ой|ий|ій|их)$/i;const cf=new class extends rf{constructor(e){super(),this.wordInflector=e}inflectNamePart(e,t,n){return this.wordInflector.inflect(e,{grammaticalCase:n,gender:t,applicationType:"givenName"})}}(b),uf=new class extends rf{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),hf=new class{constructor(e){this.modelLoader=e,this.modelPromise=null,this.wordTransformer=new Xm(20),this.familyNameClassTransformer=new Qm}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(ir([i])).data();return t=this.familyNameClassTransformer.decode(a),t}))}getCached(e){let t=null;const n=Ym[e.toLowerCase()];return n&&(t={wordClass:n}),t}loadModel(){return a(this,void 0,void 0,(function*(){return null==this.modelPromise&&(this.modelPromise=Dp(this.modelLoader)),this.modelPromise}))}}(new class{load(){return a(this,void 0,void 0,(function*(){const e={};if(e.modelTopology=ef,e.weightSpecs=tf,e.weightData=function(e){if(sf){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}(nf),null!=af){const t=af;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}))}}),pf=new class extends rf{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&&of.test(t)||n===e.GrammaticalGender.MASCULINE&&lf.test(t)}}(b,hf),df=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}))}}
|
|
4763
|
+
xt(Lo),xt(ko),xt(Oo),xt(Po),xt(Bo),xt(Uo),xt(zo),xt(Wo),xt(Zo),xt(Ao),xt(qo),xt(Fo),xt(bo);var Ym={"штих":"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 Qm{encode(t){const n=new Uint8Array(1);switch(t.wordClass){case e.WordClass.NOUN:n[0]=1;break;case e.WordClass.ADJECTIVE:n[0]=0;break;default:throw new TypeError(`Invalid word class: "${t.wordClass}".`)}return n}decode(t){if(t.length<1||t.length>1)throw new RangeError("Invalid vector length.");const n=t[0];if(n<0||n>1)throw new RangeError("Invalid vector value.");return{wordClass:n>=.5?e.WordClass.NOUN:e.WordClass.ADJECTIVE}}}class Xm{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 ef={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"},tf=[{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"}],nf="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",af={format:"layers-model",generatedBy:"TensorFlow.js tfjs-layers v4.2.0",convertedBy:null};const sf="undefined"!=typeof Buffer&&("undefined"==typeof Blob||"undefined"==typeof atob||"undefined"==typeof btoa);class rf{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 of=/[ая]$/i,lf=/(ой|ий|ій|их)$/i;const cf=new class extends rf{constructor(e){super(),this.wordInflector=e}inflectNamePart(e,t,n){return this.wordInflector.inflect(e,{grammaticalCase:n,gender:t,applicationType:"givenName"})}}(b),uf=new class extends rf{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),hf=new class{constructor(e){this.modelLoader=e,this.modelPromise=null,this.wordTransformer=new Xm(20),this.familyNameClassTransformer=new Qm}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(ir([i])).data();return t=this.familyNameClassTransformer.decode(a),t}))}getCached(e){let t=null;const n=Ym[e.toLowerCase()];return n&&(t={wordClass:n}),t}loadModel(){return a(this,void 0,void 0,(function*(){return null==this.modelPromise&&(this.modelPromise=Dp(this.modelLoader)),this.modelPromise}))}}(new class{load(){return a(this,void 0,void 0,(function*(){const e={};if(e.modelTopology=ef,e.weightSpecs=tf,e.weightData=function(e){if(sf){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}(nf),null!=af){const t=af;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}))}}),pf=new class extends rf{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&&of.test(t)||n===e.GrammaticalGender.MASCULINE&&lf.test(t)}}(b,hf),df=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}))}}
|
|
4764
4764
|
/**
|
|
4765
4765
|
* @license
|
|
4766
4766
|
* Copyright 2020 Google LLC. All Rights Reserved.
|
|
@@ -4776,4 +4776,4 @@ xt(Lo),xt(ko),xt(Oo),xt(Po),xt(Bo),xt(Uo),xt(zo),xt(Wo),xt(Zo),xt($o),xt(qo),xt(
|
|
|
4776
4776
|
* See the License for the specific language governing permissions and
|
|
4777
4777
|
* limitations under the License.
|
|
4778
4778
|
* =============================================================================
|
|
4779
|
-
*/(cf,uf,pf),mf=[];var ff={"августа":"feminine","аврелія":"feminine","аврора":"feminine","агапія":"feminine","агата":"feminine","агафія":"feminine","агафоника":"feminine","аглаїда":"feminine","аглая":"feminine","агнеса":"feminine","агнія":"feminine","агрипина":"feminine","ада":"feminine","аделаїда":"feminine","аделіна":"feminine","адріана":"feminine","аеліта":"feminine","аза":"feminine","азалія":"feminine","аїда":"feminine","акилина":"feminine","алевтина":"feminine","аліна":"feminine","аліса":"feminine","алла":"feminine","альбертина":"feminine","альбіна":"feminine","альвіна":"feminine","альфреда":"feminine","анастасія":"feminine","анатолія":"feminine","ангеліна":"feminine","анжела":"feminine","анжеліка":"feminine","анна":"feminine","антонида":"feminine","антоніна":"feminine","антонія":"feminine","анфіса":"feminine","аполлінарія":"feminine","аполлонія":"feminine","аріадна":"feminine","аркадія":"feminine","арсена":"feminine","арсенія":"feminine","артемізія":"feminine","артеміза":"feminine","артемісія":"feminine","артеміса":"feminine","артемія":"feminine","аскліпія":"feminine","ася":"feminine","аурика":"feminine","афанасія":"feminine","афіна":"feminine","атена":"feminine","афродіта":"feminine","бажана":"feminine","барбара":"feminine","беатриса":"feminine","белла":"feminine","берта":"feminine","богдана":"feminine","богуслава":"feminine","божена":"feminine","болеслава":"feminine","борислава":"feminine","броніслава":"feminine","валентина":"feminine","валерія":"feminine","ванда":"feminine","варвара":"feminine","василина":"feminine","васса":"feminine","векла":"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 gf=/[иі]ч$/,vf=/на$/,yf=/[`"]/g;class bf extends TypeError{}function wf(e){return void 0!==e}function kf(e){return null!=e&&"object"==typeof e}function xf(e){return"string"==typeof e}function Sf(t,n){return a(this,void 0,void 0,(function*(){!function(t){if(!kf(t))throw new bf("The input type must be an object.");if(!function(e,t){return t.includes(e)}(t.gender,Object.values(e.GrammaticalGender)))throw new bf(`The "gender" parameter must be one of the following: "${e.GrammaticalGender.MASCULINE}", "${e.GrammaticalGender.FEMININE}".`);if(!wf(t.givenName)&&!wf(t.patronymicName)&&!wf(t.familyName))throw new bf('At least one of the following parameters must present: "givenName", "patronymicName", "familyName".');if(wf(t.givenName)&&!xf(t.givenName))throw new bf('The "givenName" parameter must be a string.');if(wf(t.patronymicName)&&!xf(t.patronymicName))throw new bf('The "patronymicName" parameter must be a string.');if(wf(t.familyName)&&!xf(t.familyName))throw new bf('The "familyName" parameter must be a string.')}(n);const i=yield df.inflect(n,n.gender,t),s=yield function(e,t){var n;return a(this,void 0,void 0,(function*(){const i={};for(const a of mf){const s=yield null===(n=a.afterInflect)||void 0===n?void 0:n.call(a,e,t);null!=s&&Object.assign(i,s)}return i}))}(t,n);return Object.assign(Object.assign({},i),s)}))}e.InputValidationError=bf,e.WordInflector=y,e.detectGender=function(t){return a(this,void 0,void 0,(function*(){return function(e){if(!kf(e))throw new bf("The input type must be an object.");if(!wf(e.givenName)&&!wf(e.patronymicName)&&!wf(e.familyName))throw new bf('At least one of the following parameters must present: "givenName", "patronymicName", "familyName".');if(wf(e.givenName)&&!xf(e.givenName))throw new bf('The "givenName" parameter must be a string.');if(wf(e.patronymicName)&&!xf(e.patronymicName))throw new bf('The "patronymicName" parameter must be a string.');if(wf(e.familyName)&&!xf(e.familyName))throw new bf('The "familyName" parameter must be a string.')}(t),function(t){if(t.patronymicName){const n=t.patronymicName.toLocaleLowerCase();if(gf.test(n))return e.GrammaticalGender.MASCULINE;if(vf.test(n))return e.GrammaticalGender.FEMININE}if(t.givenName){const e=t.givenName.replace(yf,"'").toLocaleLowerCase(),n=ff[e];if(null!=n)return n}return null}(t)}))},e.inAblative=function(t){return a(this,void 0,void 0,(function*(){return Sf(e.GrammaticalCase.ABLATIVE,t)}))},e.inAccusative=function(t){return a(this,void 0,void 0,(function*(){return Sf(e.GrammaticalCase.ACCUSATIVE,t)}))},e.inDative=function(t){return a(this,void 0,void 0,(function*(){return Sf(e.GrammaticalCase.DATIVE,t)}))},e.inGenitive=function(t){return a(this,void 0,void 0,(function*(){return Sf(e.GrammaticalCase.GENITIVE,t)}))},e.inLocative=function(t){return a(this,void 0,void 0,(function*(){return Sf(e.GrammaticalCase.LOCATIVE,t)}))},e.inNominative=function(t){return a(this,void 0,void 0,(function*(){return Sf(e.GrammaticalCase.NOMINATIVE,t)}))},e.inVocative=function(t){return a(this,void 0,void 0,(function*(){return Sf(e.GrammaticalCase.VOCATIVE,t)}))},e.registerExtension=function(e){const t=e({wordInflector:b});mf.push(t)},Object.defineProperty(e,"__esModule",{value:!0})}));
|
|
4779
|
+
*/(cf,uf,pf),mf=[];function ff(){const e=[];for(const t of mf)e.push(...t.fieldNames);return e}var gf={"августа":"feminine","аврелія":"feminine","аврора":"feminine","агапія":"feminine","агата":"feminine","агафія":"feminine","агафоника":"feminine","аглаїда":"feminine","аглая":"feminine","агнеса":"feminine","агнія":"feminine","агрипина":"feminine","ада":"feminine","аделаїда":"feminine","аделіна":"feminine","адріана":"feminine","аеліта":"feminine","аза":"feminine","азалія":"feminine","аїда":"feminine","акилина":"feminine","алевтина":"feminine","аліна":"feminine","аліса":"feminine","алла":"feminine","альбертина":"feminine","альбіна":"feminine","альвіна":"feminine","альфреда":"feminine","анастасія":"feminine","анатолія":"feminine","ангеліна":"feminine","анжела":"feminine","анжеліка":"feminine","анна":"feminine","антонида":"feminine","антоніна":"feminine","антонія":"feminine","анфіса":"feminine","аполлінарія":"feminine","аполлонія":"feminine","аріадна":"feminine","аркадія":"feminine","арсена":"feminine","арсенія":"feminine","артемізія":"feminine","артеміза":"feminine","артемісія":"feminine","артеміса":"feminine","артемія":"feminine","аскліпія":"feminine","ася":"feminine","аурика":"feminine","афанасія":"feminine","афіна":"feminine","атена":"feminine","афродіта":"feminine","бажана":"feminine","барбара":"feminine","беатриса":"feminine","белла":"feminine","берта":"feminine","богдана":"feminine","богуслава":"feminine","божена":"feminine","болеслава":"feminine","борислава":"feminine","броніслава":"feminine","валентина":"feminine","валерія":"feminine","ванда":"feminine","варвара":"feminine","василина":"feminine","васса":"feminine","векла":"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 vf=/[иі]ч$/,yf=/на$/,bf=/[`"]/g;class wf extends TypeError{}const kf=["givenName","patronymicName","familyName"];function xf(e){return"object"==typeof e&&null!=e}function Sf(t,n){return a(this,void 0,void 0,(function*(){!function(t){if(!xf(t))throw new wf("The input type must be an object.");if(!Object.values(e.GrammaticalGender).includes(t.gender))throw new wf(`The "gender" parameter must be one of the following: "${Object.values(e.GrammaticalGender).join('", "')}".`);const n=[...kf,...ff()];if(!n.some((e=>e in t&&void 0!==t[e])))throw new wf(`At least one of the following parameters must present: "${n.join('", "')}".`);for(const e of n)if(e in t&&"string"!=typeof t[e])throw new wf(`The "${e}" parameter must be a string.`)}(n);const i=yield df.inflect(n,n.gender,t),s=yield function(e,t){var n;return a(this,void 0,void 0,(function*(){const i={};for(const a of mf){const s=yield null===(n=a.afterInflect)||void 0===n?void 0:n.call(a,e,t);null!=s&&Object.assign(i,s)}return i}))}(t,n);return Object.assign(Object.assign({},i),s)}))}e.InputValidationError=wf,e.WordInflector=y,e.detectGender=function(t){return a(this,void 0,void 0,(function*(){return function(e){if(!xf(e))throw new wf("The input type must be an object.");if(!kf.some((t=>t in e&&void 0!==e[t])))throw new wf(`At least one of the following parameters must present: "${kf.join('", "')}".`);for(const t of kf)if(t in e&&"string"!=typeof e[t])throw new wf(`The "${t}" parameter must be a string.`)}(t),function(t){if(t.patronymicName){const n=t.patronymicName.toLocaleLowerCase();if(vf.test(n))return e.GrammaticalGender.MASCULINE;if(yf.test(n))return e.GrammaticalGender.FEMININE}if(t.givenName){const e=t.givenName.replace(bf,"'").toLocaleLowerCase(),n=gf[e];if(null!=n)return n}return null}(t)}))},e.inAblative=function(t){return a(this,void 0,void 0,(function*(){return Sf(e.GrammaticalCase.ABLATIVE,t)}))},e.inAccusative=function(t){return a(this,void 0,void 0,(function*(){return Sf(e.GrammaticalCase.ACCUSATIVE,t)}))},e.inDative=function(t){return a(this,void 0,void 0,(function*(){return Sf(e.GrammaticalCase.DATIVE,t)}))},e.inGenitive=function(t){return a(this,void 0,void 0,(function*(){return Sf(e.GrammaticalCase.GENITIVE,t)}))},e.inLocative=function(t){return a(this,void 0,void 0,(function*(){return Sf(e.GrammaticalCase.LOCATIVE,t)}))},e.inNominative=function(t){return a(this,void 0,void 0,(function*(){return Sf(e.GrammaticalCase.NOMINATIVE,t)}))},e.inVocative=function(t){return a(this,void 0,void 0,(function*(){return Sf(e.GrammaticalCase.VOCATIVE,t)}))},e.registerExtension=function(e){const t=e({wordInflector:b});mf.push(t)},Object.defineProperty(e,"__esModule",{value:!0})}));
|